diff --git a/.gitignore b/.gitignore index 4b34eebf..35c18af0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ .gradle .settings +.classpath +.project build bin proxyServer/bin @@ -13,8 +15,14 @@ desktopRuntime/_eagstorage* desktopRuntime/filesystem/* desktopRuntime/downloads/* desktopRuntime/screenshots/* + javascript/assets.epk javascript/classes.js javascript/classes.js.map javascript/Starlike_Client_Offline.html -/.metadata/ +javascript/Starlike_Client_Offline_Signed.html +javascript/Starlike_Client_Offline_Signed.html.cert +javascript/Starlike_Client_Offline_Signed.html.dat + +.metadata + diff --git a/CODE_STANDARDS.md b/CODE_STANDARDS.md deleted file mode 100644 index 7f14d0ed..00000000 --- a/CODE_STANDARDS.md +++ /dev/null @@ -1,306 +0,0 @@ -# Eaglercraft Code Standards - -**These are some basic rules to follow if you would like to write code that is consistent with the Eaglercraft 1.8 codebase. If you are already familiar with Eaglercraft 1.5 or b1.3, please abandon whatever you think is the best practice as a result of reading that code, those clients should be considered as obsolete prototypes.** - -## Part A. Coding Style - -### 1. Tabs, not spaces - -Tabs not spaces, it makes indentation easier to manage and reduces file size. Other popular projects that are also known to use tabs instead of spaces include the linux kernel. We prefer to set tab width to 4 spaces on our editors. - -Format code like the eclipse formatter on factory settings - -### 2. Avoid redundant hash map lookups - -Don't retrieve the same value from a hash map more than once, that includes checking if an entry exists first before retrieving its value. If you do this, you are a horrible person! - -**Incorrect:** - -```java -if(hashMap.containsKey("eagler")) { - Object val = hashMap.get("eagler"); - // do something with val -} -``` - -**Correct:** - -```java -Object val = hashMap.get("eagler"); -if(val != null) { - // do something with val -} -``` - -### 3. Cache the return value of a function if you plan to use it multiple times - -This is somewhat an extension of rule #2, don't repeatedly call the same function multiple times if there's no reason to, even if its a relatively fast function. Everything is slower and less efficient in a browser. - -**Incorrect:** - -```java -while(itr.hasNext()) { - if(!Minecraft.getMinecraft().getRenderManager().getEntityClassRenderObject(SomeEntity.class).shouldRender(itr.next())) { - itr.remove(); - } -} -``` - -**Correct:** - -```java -Render render = Minecraft.getMinecraft().getRenderManager().getEntityClassRenderObject(SomeEntity.class); -while(itr.hasNext()) { - if(!render.shouldRender(itr.next())) { - itr.remove(); - } -} -``` - -### 4. Iterators aren't that great - -Avoid using iterators when possible, this includes a `for(Item item : list)` type loop, since this may compile into bytecode that uses an iterator. If the list is a linked list or some other type of data structure that can’t perform random access efficiently, then it is recommended to use an iterator, but if the collection is guaranteed to be something similar to an ArrayList then implement it via a traditional for loop instead. - -**Recommended way to iterate an ArrayList:** - -```java -for(int i = 0, l = list.size(); i < l; ++i) { - Item item = list.get(i); - // do something -} -``` - -### 5. Don't shit on the heap - -Avoid creating temporary single-use objects in performance critical code, since the overhead of doing so is larger in a browser where there’s no type safety to predefine object structures. This includes using lambdas or using most of the stuff in the google guava package. Also this is partially why I prefer not using iterators whenever possible. - -**Incorrect, creates 5 temporary objects:** - -```java -List list1 = Arrays.asList("eagler", "eagler", "deevis"); -List list2 = Lists.newArrayList( - Collections2.transform( - Collections2.filter( - list1, - (e) -> !e.equals("deevis") - ), - (e) -> (e + "!") - ) -); -``` - -**Correct, creates no temporary objects:** - -```java -List list1 = Arrays.asList("eagler", "eagler", "deevis"); -List list2 = Lists.newArrayList(); -for(int i = 0, l = list1.size(); i < l; ++i) { - String s = list1.get(i); - if(!s.equals("deevis")) { - list2.add(s + "!"); - } -} -``` - -(note: we are ignoring the StringBuilder instances that the compiler generates from ` + "!"`) - -### 6. Don't base game/render logic off of the system time - -Use `EagRuntime.steadyTimeMillis()` instead to access a monotonic clock, as in a clock that is guaranteed to only run forwards, and is not affected by changes in the system time. `System.currentTimeMillis()` should only be used in situations where you want to know the actual wall time or are measuring elapsed time across multiple page refreshes. - -### 7. Prefer multiplication over division - -If you're always gonna divide a number by some constant, it is better to multiply it by one-over-the-constant instead. - -**Incorrect** - -```java -float b = a / 50.0f; -``` - -**Correct** - -```java -float b = a * 0.02f; -``` - -### 8. Shaders should take advantage of compiler intrinsics - -Although you may think these two pieces of code are identical, its more than likely that the "Correct" example will compile to a more efficient shader on almost any hardware. The functions in GLSL are not a library, they are compiler intrinsics that usually compile to inline assembly that can take advantage of different acceleration instructions in the GPU's instruction set. Vector math should be done in ways that promotes the use of SIMD instructions when the code is compiled to a shader. - -**Incorrect:** - -```glsl -float dx = pos1.x - pos2.x; -float dy = pos1.y - pos2.y; -float dz = pos1.z - pos2.z; -float distance = sqrt(dx * dx + dy * dy + dz * dz); -float fogDensity = pow(2.718, -density * distance); -``` - -**Correct:** - -```glsl -float fogDensity = exp(-density * length(pos1.xyz - pos2.xyz)); -``` - -### 9. Flatten the control flow of shaders - -Modern GPUs are able to execute multiple instances of a shader on a single core, but if one of those shaders encounters a branch (if statement, or related) that causes it to begin executing different code from the other instances of the shader running on that core, that instance of the shader can no longer be executed at the same time as the other instances, and suddenly you've significantly increased the amount of time this core will now be busy executing shader instructions to account for all of the branches the different shader instances have taken. - -**Incorrect:** - -```glsl -float lightValue = dot(lightDirection, normal); -if(lightValue > 0.0) { - color += lightValue * lightColor * diffuseColor; -} -``` - -**Correct:** -```glsl -float lightValue = max(dot(lightDirection, normal), 0.0); -color += lightValue * lightColor * diffuseColor; -``` - -### 10. Use textureLod unless mipmapping is necessary - -This will prevent the shader from wasting time trying to determine what mipmap levels to read from when the texture is sampled. - -**Incorrect:** - -```glsl -float depthValue = texture(depthBuffer, pos).r; -``` - -**Correct:** - -```glsl -float depthValue = textureLod(depthBuffer, pos, 0.0).r; -``` - -### 11. Divide complex and branch-intensive shaders into multiple draw calls - -You can use a variety of different blending modes to mathematically combine the results of shaders. This is done for the same reason as flattening the control flow, to try and keep instruction pointers in sync by periodically resetting their positions, and also to allow for the driver to multitask better on GPUs with insane numbers of cores. It also allows the shader’s execution to be distributed across multiple frames in the case of something that doesn’t need to update often (like clouds). - - -### 12. Don't abuse `@JSBody` in TeaVM code - -TeaVM provides lots of ways of interacting with JavaScript, using `@JSBody` is not the only way, consider using an overlay type. - -**Incorrect** - -```java -@JSObject(params = { "obj" }, script = "return obj.valueA;") -public static native JSObject getValueA(JSObject obj); - -@JSObject(params = { "obj" }, script = "return obj.valueB;") -public static native JSObject getValueB(JSObject obj); - -@JSObject(params = { "obj" }, script = "return obj.valueC;") -public static native JSObject getValueC(JSObject obj); - -@JSObject(params = { "obj" }, script = "obj.dumbFunction();") -public static native void callDumbFunction(JSObject obj); -``` - -**Correct** - -```java -public interface MyObject extends JSObject { - - @JSProperty - JSObject getValueA(); - - @JSProperty - JSObject getValueB(); - - @JSProperty - JSObject getValueC(); - - void dumbFunction(); - -} -``` - -### 13. Don't fall for TeaVM's threads - -It is impossible to have multithreading in JavaScript, only worker objects can be used to execute code concurrently, which can't share javascript variables. Therefore, when you create a thread in TeaVM, you're creating a virtual thread that isn't capable of running at the same time as any other virtual thread in the TeaVM context. This means it's impossible to speed a TeaVM program up through the use of multiple Java threads, instead it is more than likely that it will just slow the program down more to implement multithreading through TeaVM's threads due to the additional time required for synchronization and context switches. Its more efficient to just program the entire application to be single threaded to begin with, just put everything in the main loop and realize that if it was in a different thread it would just periodically interrupt the main loop. - -### 14. Always use try-with-resources - -For any code that deals with streams to be considered safe, it should either use a try-with-resources or try/finally in order to release resources when complete, since otherwise the stream might not close if an IO error causes the function to return early. This is especially important for plugin code since its supposed to be able to run on a large server for weeks at a time without the underlying JVM being restarted. If hackers discover a bug in the code to cause a function to return early like this without closing a stream, they might exploit it to fatally crash the server by spamming whatever corrupt packet causes the function to leak the stream, so all code must be written so it can fail at any time without leaking resources. - -**Incorrect** - -```java -InputStream is = new FileInputStream(new File("phile.txt")); -is.write(someArray); -is.close(); -``` - -**Correct** - -```java -try(InputStream is = new FileInputStream(new File("phile.txt"))) { - is.write(someArray); -} -``` - -Notice that the `.close()` can be omitted completely when using a try-with-resources - -### 15. Always close compression/decompression streams - -In the desktop runtime, the default oracle JDK uses native code to implement the compression/decompression streams (InflaterInputStream, GZIPInputStream, etc) and therefore if you forget to close the compression/decompression stream it will cause a memory leak when the code isn't running in a browser. This is a common issue when using byte array input/output streams since you might believe when decompressing data from a byte array that there's no reason to close the stream when you're done since its not a file, but that will still cause a memory leak due to the decompression stream not being cleaned up. - -## Part B. Project Structure - -### 1. Code decompiled from Minecraft goes in `src/game/java` - -Don't add any new classes to `src/game/java`, and ideally any significant additions to the game's source (functions, etc) should be done through creating new classes in `src/main/java` instead of adding it directly to the decompiled classes. - -### 2. Do not put platform-dependent code in `src/main/java` or `src/game/java` - -One of the objectives of Eaglercraft is to make Minecraft Java edition truly cross platform, why stop at just a desktop and JavaScript runtime? There are plans to create an Android runtime and several WebAssembly runtimes, all of which will be compatible with any pre-existing eaglercraft clients that only depend on the EaglercraftX runtime library and don't directly depend on components of TeaVM or LWJGL. Ideally, all core features of the client should be implemented in the `src/main/java` and `src/game/java` and any platform-dependent features should be stubbed out in some abstract platform-independent way in classes in the `src/teavm/java` and `src/lwjgl/java` and any other future runtime you want your client to support. Ideally, every source folder of platform-dependent code should expose an identical API for access to the platform-independent code as all the other platform-dependant code folders currently expose. - -### 3. Don't mix JavaScript with Java - -Don’t implement features in the JavaScript runtime by requiring additional JavaScript files be included on index.html, if you must access browser APIs then use the TeaVM JSO to write your code in Java instead so it’s baked directly into classes.js. Certain browser APIs may be missing from the default TeaVM JSO-APIs library but it is not difficult to create the overlay types for them manually. Clients that violate this rule may also not possible to automatically import into the EaglercraftX boot menu depending on how fucked up they are. There aren't any limitations to the TeaVM JSO that give you a good enough excuse not to follow this rule. - -### 4. Don't access the classes named "Platform\*" directly from your platform-independent code - -Much like the Java runtime environment itself, Eaglercraft's runtime library consists of two layers, the internal classes full of platform-dependent code that expose an intermediate API not meant to be used by programmers directly, and the platform-independent API classes that provide a platform-independent wrapper for the platform dependent classes and also provide all the miscellaneous utility functions that don't require platform dependent code to be implemented. Chances are if you are directly using a function on a class that has a name that starts with "Platform\*", that there is a different class in `src/main/java` that you are meant to use in order to access that feature, that may perform additional checks or adjust the values you are passing to the function before calling the function in the Platform class. - -## Part C. Compatibility Standards - -### 1. Target minimum JDK version is Java 8 - -Its difficult to find a platform where its not possible to run Java 8 in some capacity, therefore the desktop runtime of EaglercraftX and the BungeeCord plugin should target Java 8. The Velocity plugin is an exception since Velocity itself doesn't support Java 8 either. - -### 2. Target minimum supported browser is Google Chrome 38 - -Released on October 7, 2014, we think its a good target for the JavaScript versions of EaglercraftX. This is the last version of Chrome that supports hardware accelerated WebGL 1.0 on Windows XP. All base features of the underlying Minecraft 1.8 client must be functional, however things such as EaglercraftX's shaders or dynamic lighting are not required to work. The client cannot crash as a result of any missing features on an old browser, you must either implement fallbacks or safely disable the unsupported features. - -### 3. Target minimum supported graphics API is OpenGL ES 2.0 (WebGL 1.0) - -The most widely supported graphics API in the world is currently OpenGL ES 2.0, so ideally that should be the target for EaglercraftX 1.8. We can guarantee the client will be on an OpenGL ES 3.0 context 99% of the time, however its not that hard to also maintain support for GLES 2.0 (WebGL 1.0) as well with slightly reduced functionality so we might as well make it a feature in case of the 1% of the time that functionality is not available. The client cannot depend on any GL extensions in order to run in GLES 2.0 mode, however its reasonable to assume there will be VAO support via extensions in most GLES 2.0 contexts so the client includes an abstraction layer (via EaglercraftGPU.java) to seamlessly emulate VAO functionality even when the client is running in GLES 2.0 mode with no VAO extensions. The only core feature of Minecraft 1.8 that is completely unavailable in GLES 2.0 mode is mip-mapping for the blocks/items texture atlas due to being unable to limit the max mipmap level. - -### 4. Use preprocessor directives to make portable shaders that can be compiled for both OpenGL ES 2.0 and 3.0 contexts - -Most of the shaders in the base "glsl" directory of the resources EPK file use a file called "gles2_compat.glsl" to polyfill certain GLSL features (such as input/output declarations) via preprocessor directives to allow them to be compiled on both OpenGL ES 3.0 and 2.0 contexts. This is the preferred way to implement backwards compatibility over creating seprate versions of the same shaders, since future developers don't need to waste time maintaining multiple versions of the same code if they don't really care about backwards compatibility in the first place. - -### 5. Target minimum version of the JavaScript syntax is ES5 strict mode - -A shim is included to provide certain ES6 functions, however you should always program with syntax compatible with ES5, so the script doesn't crash immediately due to syntax errors even if the functions that use unsupported syntax aren't actually being called. `build.gradle` currently patches out all the ES5 strict mode incompatible syntax in the output of TeaVM 0.9.2, but this will probably break if you try to update TeaVM. Don't worry though because future WASM versions of EaglercraftX will use the latest versions of TeaVM. **Some common incompatible syntax to avoid includes `const`, `let`, `async`, `( ) => `, and using named functions! You can't do any of these things in your JSBody annotations.** - -### 6. You cannot depend on any deprecated browser features - -The same way we want EaglercraftX to work on browsers from over 10 years ago, we want it to still work in browsers 10 years from today, therefore the client cannot depend on any deprecated browser features in order for all the base Minecraft 1.8 game's features to work properly. However it is okay to use deprecated features as fallback if any modern non-deprecated feature (such as keyboard event handling) that the game needs if the game is running in an old browser. - -### 7. Always use addEventListener to register event handlers - -Always use addEventListener to register event handlers for browser APIs, never through the use of assigning the legacy "on\*" (onclick, onkeydown, onmessage, etc) variables, the TeaVMUtils class has a universal helper function for accessing addEventListener on any JSO objects that don’t already implement the function. - -### 8. JavaScript should be executed in strict mode - -Always make sure your JavaScript files start with `"use strict";`, be careful when adding this to your code retroactively because it will probably break hastily written code unless you haven’t made a single typo that’s not forbidden in strict mode. Be aware that in Chrome 38 this means you can't use stuff such as `const` and `let` or named functions in any of your JSBody annotations! diff --git a/CompileEPK.sh b/CompileEPK.sh index 05f907cb..b975a0d1 100755 --- a/CompileEPK.sh +++ b/CompileEPK.sh @@ -1,2 +1,2 @@ #!/bin/sh -java -jar "desktopRuntime/CompileEPK.jar" "desktopRuntime/resources" "javascript/assets.epk" \ No newline at end of file +java -jar "desktopRuntime/CompileEPK.jar" "desktopRuntime/resources" "javascript/assets.epk" diff --git a/CompileJS.bat b/CompileJS.bat index 28d24ae2..4dcf2c95 100644 --- a/CompileJS.bat +++ b/CompileJS.bat @@ -1,4 +1,4 @@ @echo off title gradlew generateJavascript -gradlew generateJavascript +call gradlew generateJavascript pause diff --git a/EAGLERCRAFTX_README.md b/EAGLERCRAFTX_README.md index 5fcdc4b9..f13ec9e7 100644 --- a/EAGLERCRAFTX_README.md +++ b/EAGLERCRAFTX_README.md @@ -196,6 +196,7 @@ The default eaglercraftXOpts values is this: - `eaglerNoDelay:` can be used to disable "Vigg's Algorithm", an algorithm that delays and combines multiple EaglercraftX packets together if they are sent in the same tick (does not affect regular Minecraft 1.8 packets) - `ramdiskMode:` if worlds and resource packs should be stored in RAM instead of IndexedDB - `singleThreadMode:` if the game should run the client and integrated server in the same context instead of creating a worker object +- `enableEPKVersionCheck:` if the game should attempt to bypass the browser's cache and retry downloading assets.epk when its outdated - `hooks:` can be used to define JavaScript callbacks for certain events * `localStorageSaved:` JavaScript callback to save local storage keys (key, data) * `localStorageLoaded:` JavaScript callback to load local storage keys (key) returns data @@ -244,3 +245,340 @@ The `crashReportShow` hook can be used to capture crash reports and append addit There is currently no system in place to make forks of 1.8 and merge commits made to the patch files in this repository with the patch files or workspace of the fork, you're on your own if you try to keep a fork of this repo for reasons other than to contribute to it A javascript-based modding API resembling Minecraft Forge may be implemented someday though for adding custom content to the game. + +# EaglercraftX 1.8 Workspace + +### Java 17 is recommended for compiling to TeaVM + +### Java 8 or greater is required for the desktop runtime + +**Most Java IDEs will allow you to import this repository as a gradle project for compiling it to JavaScript.** + +Java must be added to your PATH! + +**To compile the web client:** +1. Run `CompileEPK` +2. Run `CompileJS` (or the `generateJavaScript` gradle task in your IDE) +3. Check the "javascript" folder + +**To compile an offline download:** +1. Run `CompileEPK` +2. Run `CompileJS` (or the `generateJavaScript` gradle task in your IDE) +3. Run `MakeOfflineDownload` +4. Check the "javascript" folder + +**To use the desktop runtime:** +1. Import the Eclipse project in "desktopRuntime/eclipseProject" into your IDE +2. Open one of the .java files from the source folders (workaround for a bug) +3. Run/Debug the client with the included "eaglercraftDebugRuntime" configuration + +**See the main 1.8 repository's README for more info** + +The source codes of EaglercraftXBungee and EaglercraftXVelocity are not included here. + +# Eaglercraft Code Standards + +**These are some basic rules to follow if you would like to write code that is consistent with the Eaglercraft 1.8 codebase. If you are already familiar with Eaglercraft 1.5 or b1.3, please abandon whatever you think is the best practice as a result of reading that code, those clients should be considered as obsolete prototypes.** + +## Part A. Coding Style + +### 1. Tabs, not spaces + +Tabs not spaces, it makes indentation easier to manage and reduces file size. Other popular projects that are also known to use tabs instead of spaces include the linux kernel. We prefer to set tab width to 4 spaces on our editors. + +Format code like the eclipse formatter on factory settings + +### 2. Avoid redundant hash map lookups + +Don't retrieve the same value from a hash map more than once, that includes checking if an entry exists first before retrieving its value. If you do this, you are a horrible person! + +**Incorrect:** + +```java +if(hashMap.containsKey("eagler")) { + Object val = hashMap.get("eagler"); + // do something with val +} +``` + +**Correct:** + +```java +Object val = hashMap.get("eagler"); +if(val != null) { + // do something with val +} +``` + +### 3. Cache the return value of a function if you plan to use it multiple times + +This is somewhat an extension of rule #2, don't repeatedly call the same function multiple times if there's no reason to, even if its a relatively fast function. Everything is slower and less efficient in a browser. + +**Incorrect:** + +```java +while(itr.hasNext()) { + if(!Minecraft.getMinecraft().getRenderManager().getEntityClassRenderObject(SomeEntity.class).shouldRender(itr.next())) { + itr.remove(); + } +} +``` + +**Correct:** + +```java +Render render = Minecraft.getMinecraft().getRenderManager().getEntityClassRenderObject(SomeEntity.class); +while(itr.hasNext()) { + if(!render.shouldRender(itr.next())) { + itr.remove(); + } +} +``` + +### 4. Iterators aren't that great + +Avoid using iterators when possible, this includes a `for(Item item : list)` type loop, since this may compile into bytecode that uses an iterator. If the list is a linked list or some other type of data structure that can’t perform random access efficiently, then it is recommended to use an iterator, but if the collection is guaranteed to be something similar to an ArrayList then implement it via a traditional for loop instead. + +**Recommended way to iterate an ArrayList:** + +```java +for(int i = 0, l = list.size(); i < l; ++i) { + Item item = list.get(i); + // do something +} +``` + +### 5. Don't shit on the heap + +Avoid creating temporary single-use objects in performance critical code, since the overhead of doing so is larger in a browser where there’s no type safety to predefine object structures. This includes using lambdas or using most of the stuff in the google guava package. Also this is partially why I prefer not using iterators whenever possible. + +**Incorrect, creates 5 temporary objects:** + +```java +List list1 = Arrays.asList("eagler", "eagler", "deevis"); +List list2 = Lists.newArrayList( + Collections2.transform( + Collections2.filter( + list1, + (e) -> !e.equals("deevis") + ), + (e) -> (e + "!") + ) +); +``` + +**Correct, creates no temporary objects:** + +```java +List list1 = Arrays.asList("eagler", "eagler", "deevis"); +List list2 = Lists.newArrayList(); +for(int i = 0, l = list1.size(); i < l; ++i) { + String s = list1.get(i); + if(!s.equals("deevis")) { + list2.add(s + "!"); + } +} +``` + +(note: we are ignoring the StringBuilder instances that the compiler generates from ` + "!"`) + +### 6. Don't base game/render logic off of the system time + +Use `EagRuntime.steadyTimeMillis()` instead to access a monotonic clock, as in a clock that is guaranteed to only run forwards, and is not affected by changes in the system time. `System.currentTimeMillis()` should only be used in situations where you want to know the actual wall time or are measuring elapsed time across multiple page refreshes. + +### 7. Prefer multiplication over division + +If you're always gonna divide a number by some constant, it is better to multiply it by one-over-the-constant instead. + +**Incorrect** + +```java +float b = a / 50.0f; +``` + +**Correct** + +```java +float b = a * 0.02f; +``` + +### 8. Shaders should take advantage of compiler intrinsics + +Although you may think these two pieces of code are identical, its more than likely that the "Correct" example will compile to a more efficient shader on almost any hardware. The functions in GLSL are not a library, they are compiler intrinsics that usually compile to inline assembly that can take advantage of different acceleration instructions in the GPU's instruction set. Vector math should be done in ways that promotes the use of SIMD instructions when the code is compiled to a shader. + +**Incorrect:** + +```glsl +float dx = pos1.x - pos2.x; +float dy = pos1.y - pos2.y; +float dz = pos1.z - pos2.z; +float distance = sqrt(dx * dx + dy * dy + dz * dz); +float fogDensity = pow(2.718, -density * distance); +``` + +**Correct:** + +```glsl +float fogDensity = exp(-density * length(pos1.xyz - pos2.xyz)); +``` + +### 9. Flatten the control flow of shaders + +Modern GPUs are able to execute multiple instances of a shader on a single core, but if one of those shaders encounters a branch (if statement, or related) that causes it to begin executing different code from the other instances of the shader running on that core, that instance of the shader can no longer be executed at the same time as the other instances, and suddenly you've significantly increased the amount of time this core will now be busy executing shader instructions to account for all of the branches the different shader instances have taken. + +**Incorrect:** + +```glsl +float lightValue = dot(lightDirection, normal); +if(lightValue > 0.0) { + color += lightValue * lightColor * diffuseColor; +} +``` + +**Correct:** +```glsl +float lightValue = max(dot(lightDirection, normal), 0.0); +color += lightValue * lightColor * diffuseColor; +``` + +### 10. Use textureLod unless mipmapping is necessary + +This will prevent the shader from wasting time trying to determine what mipmap levels to read from when the texture is sampled. + +**Incorrect:** + +```glsl +float depthValue = texture(depthBuffer, pos).r; +``` + +**Correct:** + +```glsl +float depthValue = textureLod(depthBuffer, pos, 0.0).r; +``` + +### 11. Divide complex and branch-intensive shaders into multiple draw calls + +You can use a variety of different blending modes to mathematically combine the results of shaders. This is done for the same reason as flattening the control flow, to try and keep instruction pointers in sync by periodically resetting their positions, and also to allow for the driver to multitask better on GPUs with insane numbers of cores. It also allows the shader’s execution to be distributed across multiple frames in the case of something that doesn’t need to update often (like clouds). + + +### 12. Don't abuse `@JSBody` in TeaVM code + +TeaVM provides lots of ways of interacting with JavaScript, using `@JSBody` is not the only way, consider using an overlay type. + +**Incorrect** + +```java +@JSObject(params = { "obj" }, script = "return obj.valueA;") +public static native JSObject getValueA(JSObject obj); + +@JSObject(params = { "obj" }, script = "return obj.valueB;") +public static native JSObject getValueB(JSObject obj); + +@JSObject(params = { "obj" }, script = "return obj.valueC;") +public static native JSObject getValueC(JSObject obj); + +@JSObject(params = { "obj" }, script = "obj.dumbFunction();") +public static native void callDumbFunction(JSObject obj); +``` + +**Correct** + +```java +public interface MyObject extends JSObject { + + @JSProperty + JSObject getValueA(); + + @JSProperty + JSObject getValueB(); + + @JSProperty + JSObject getValueC(); + + void dumbFunction(); + +} +``` + +### 13. Don't fall for TeaVM's threads + +It is impossible to have multithreading in JavaScript, only worker objects can be used to execute code concurrently, which can't share javascript variables. Therefore, when you create a thread in TeaVM, you're creating a virtual thread that isn't capable of running at the same time as any other virtual thread in the TeaVM context. This means it's impossible to speed a TeaVM program up through the use of multiple Java threads, instead it is more than likely that it will just slow the program down more to implement multithreading through TeaVM's threads due to the additional time required for synchronization and context switches. Its more efficient to just program the entire application to be single threaded to begin with, just put everything in the main loop and realize that if it was in a different thread it would just periodically interrupt the main loop. + +### 14. Always use try-with-resources + +For any code that deals with streams to be considered safe, it should either use a try-with-resources or try/finally in order to release resources when complete, since otherwise the stream might not close if an IO error causes the function to return early. This is especially important for plugin code since its supposed to be able to run on a large server for weeks at a time without the underlying JVM being restarted. If hackers discover a bug in the code to cause a function to return early like this without closing a stream, they might exploit it to fatally crash the server by spamming whatever corrupt packet causes the function to leak the stream, so all code must be written so it can fail at any time without leaking resources. + +**Incorrect** + +```java +InputStream is = new FileInputStream(new File("phile.txt")); +is.write(someArray); +is.close(); +``` + +**Correct** + +```java +try(InputStream is = new FileInputStream(new File("phile.txt"))) { + is.write(someArray); +} +``` + +Notice that the `.close()` can be omitted completely when using a try-with-resources + +### 15. Always close compression/decompression streams + +In the desktop runtime, the default oracle JDK uses native code to implement the compression/decompression streams (InflaterInputStream, GZIPInputStream, etc) and therefore if you forget to close the compression/decompression stream it will cause a memory leak when the code isn't running in a browser. This is a common issue when using byte array input/output streams since you might believe when decompressing data from a byte array that there's no reason to close the stream when you're done since its not a file, but that will still cause a memory leak due to the decompression stream not being cleaned up. + +## Part B. Project Structure + +### 1. Code decompiled from Minecraft goes in `src/game/java` + +Don't add any new classes to `src/game/java`, and ideally any significant additions to the game's source (functions, etc) should be done through creating new classes in `src/main/java` instead of adding it directly to the decompiled classes. + +### 2. Do not put platform-dependent code in `src/main/java` or `src/game/java` + +One of the objectives of Eaglercraft is to make Minecraft Java edition truly cross platform, why stop at just a desktop and JavaScript runtime? There are plans to create an Android runtime and several WebAssembly runtimes, all of which will be compatible with any pre-existing eaglercraft clients that only depend on the EaglercraftX runtime library and don't directly depend on components of TeaVM or LWJGL. Ideally, all core features of the client should be implemented in the `src/main/java` and `src/game/java` and any platform-dependent features should be stubbed out in some abstract platform-independent way in classes in the `src/teavm/java` and `src/lwjgl/java` and any other future runtime you want your client to support. Ideally, every source folder of platform-dependent code should expose an identical API for access to the platform-independent code as all the other platform-dependant code folders currently expose. + +### 3. Don't mix JavaScript with Java + +Don’t implement features in the JavaScript runtime by requiring additional JavaScript files be included on index.html, if you must access browser APIs then use the TeaVM JSO to write your code in Java instead so it’s baked directly into classes.js. Certain browser APIs may be missing from the default TeaVM JSO-APIs library but it is not difficult to create the overlay types for them manually. Clients that violate this rule may also not possible to automatically import into the EaglercraftX boot menu depending on how fucked up they are. There aren't any limitations to the TeaVM JSO that give you a good enough excuse not to follow this rule. + +### 4. Don't access the classes named "Platform\*" directly from your platform-independent code + +Much like the Java runtime environment itself, Eaglercraft's runtime library consists of two layers, the internal classes full of platform-dependent code that expose an intermediate API not meant to be used by programmers directly, and the platform-independent API classes that provide a platform-independent wrapper for the platform dependent classes and also provide all the miscellaneous utility functions that don't require platform dependent code to be implemented. Chances are if you are directly using a function on a class that has a name that starts with "Platform\*", that there is a different class in `src/main/java` that you are meant to use in order to access that feature, that may perform additional checks or adjust the values you are passing to the function before calling the function in the Platform class. + +## Part C. Compatibility Standards + +### 1. Target minimum JDK version is Java 8 + +Its difficult to find a platform where its not possible to run Java 8 in some capacity, therefore the desktop runtime of EaglercraftX and the BungeeCord plugin should target Java 8. The Velocity plugin is an exception since Velocity itself doesn't support Java 8 either. + +### 2. Target minimum supported browser is Google Chrome 38 + +Released on October 7, 2014, we think its a good target for the JavaScript versions of EaglercraftX. This is the last version of Chrome that supports hardware accelerated WebGL 1.0 on Windows XP. All base features of the underlying Minecraft 1.8 client must be functional, however things such as EaglercraftX's shaders or dynamic lighting are not required to work. The client cannot crash as a result of any missing features on an old browser, you must either implement fallbacks or safely disable the unsupported features. + +### 3. Target minimum supported graphics API is OpenGL ES 2.0 (WebGL 1.0) + +The most widely supported graphics API in the world is currently OpenGL ES 2.0, so ideally that should be the target for EaglercraftX 1.8. We can guarantee the client will be on an OpenGL ES 3.0 context 99% of the time, however its not that hard to also maintain support for GLES 2.0 (WebGL 1.0) as well with slightly reduced functionality so we might as well make it a feature in case of the 1% of the time that functionality is not available. The client cannot depend on any GL extensions in order to run in GLES 2.0 mode, however its reasonable to assume there will be VAO support via extensions in most GLES 2.0 contexts so the client includes an abstraction layer (via EaglercraftGPU.java) to seamlessly emulate VAO functionality even when the client is running in GLES 2.0 mode with no VAO extensions. The only core feature of Minecraft 1.8 that is completely unavailable in GLES 2.0 mode is mip-mapping for the blocks/items texture atlas due to being unable to limit the max mipmap level. + +### 4. Use preprocessor directives to make portable shaders that can be compiled for both OpenGL ES 2.0 and 3.0 contexts + +Most of the shaders in the base "glsl" directory of the resources EPK file use a file called "gles2_compat.glsl" to polyfill certain GLSL features (such as input/output declarations) via preprocessor directives to allow them to be compiled on both OpenGL ES 3.0 and 2.0 contexts. This is the preferred way to implement backwards compatibility over creating seprate versions of the same shaders, since future developers don't need to waste time maintaining multiple versions of the same code if they don't really care about backwards compatibility in the first place. + +### 5. Target minimum version of the JavaScript syntax is ES5 strict mode + +A shim is included to provide certain ES6 functions, however you should always program with syntax compatible with ES5, so the script doesn't crash immediately due to syntax errors even if the functions that use unsupported syntax aren't actually being called. `build.gradle` currently patches out all the ES5 strict mode incompatible syntax in the output of TeaVM 0.9.2, but this will probably break if you try to update TeaVM. Don't worry though because future WASM versions of EaglercraftX will use the latest versions of TeaVM. **Some common incompatible syntax to avoid includes `const`, `let`, `async`, `( ) => `, and using named functions! You can't do any of these things in your JSBody annotations.** + +### 6. You cannot depend on any deprecated browser features + +The same way we want EaglercraftX to work on browsers from over 10 years ago, we want it to still work in browsers 10 years from today, therefore the client cannot depend on any deprecated browser features in order for all the base Minecraft 1.8 game's features to work properly. However it is okay to use deprecated features as fallback if any modern non-deprecated feature (such as keyboard event handling) that the game needs if the game is running in an old browser. + +### 7. Always use addEventListener to register event handlers + +Always use addEventListener to register event handlers for browser APIs, never through the use of assigning the legacy "on\*" (onclick, onkeydown, onmessage, etc) variables, the TeaVMUtils class has a universal helper function for accessing addEventListener on any JSO objects that don’t already implement the function. + +### 8. JavaScript should be executed in strict mode + +Always make sure your JavaScript files start with `"use strict";`, be careful when adding this to your code retroactively because it will probably break hastily written code unless you haven’t made a single typo that’s not forbidden in strict mode. Be aware that in Chrome 38 this means you can't use stuff such as `const` and `let` or named functions in any of your JSBody annotations! diff --git a/MakeOfflineDownload.bat b/MakeOfflineDownload.bat index 2b5e726c..3ce2c658 100644 --- a/MakeOfflineDownload.bat +++ b/MakeOfflineDownload.bat @@ -1,4 +1,4 @@ @echo off title MakeOfflineDownload -java -cp "desktopRuntime/MakeOfflineDownload.jar;desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeOfflineDownload "javascript/OfflineDownloadTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "javascript/Starlike_Client_Offline.html" +java -cp "desktopRuntime/MakeOfflineDownload.jar;desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeOfflineDownload "desktopRuntime/resources/OfflineDownloadTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "javascript/Starlike_Client_Offline.html" pause diff --git a/MakeOfflineDownload.sh b/MakeOfflineDownload.sh index f046754d..86ff7418 100755 --- a/MakeOfflineDownload.sh +++ b/MakeOfflineDownload.sh @@ -1,2 +1,2 @@ #!/bin/sh -java -cp "desktopRuntime/MakeOfflineDownload.jar:desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeOfflineDownload "javascript/OfflineDownloadTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "javascript/Starlike_Client_Offline.html" +java -cp "desktopRuntime/MakeOfflineDownload.jar:desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeOfflineDownload "desktopRuntime/resources/OfflineDownloadTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "javascript/Starlike_Client_Offline.html" diff --git a/MakeSignedClient.bat b/MakeSignedClient.bat index 90434db2..788a3eac 100644 --- a/MakeSignedClient.bat +++ b/MakeSignedClient.bat @@ -1,4 +1,4 @@ @echo off title MakeSignedClient -java -cp "desktopRuntime/MakeOfflineDownload.jar;desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeSignedClient "javascript/SignedBundleTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "javascript/lang" "javascript/SignedClientTemplate.txt" "javascript/UpdateDownloadSources.txt" "javascript/EaglercraftX_1.8_Offline_Signed_Client.html" +java -cp "desktopRuntime/MakeOfflineDownload.jar;desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeSignedClient "desktopRuntime/resources/SignedBundleTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "desktopRuntime/resources/SignedClientTemplate.txt" "desktopRuntime/resources/UpdateDownloadSources.txt" "javascript/Starlike_Client_Offline_Signed.html" pause \ No newline at end of file diff --git a/MakeSignedClient.sh b/MakeSignedClient.sh index 83e964bd..09a77209 100755 --- a/MakeSignedClient.sh +++ b/MakeSignedClient.sh @@ -1,2 +1,2 @@ #!/bin/sh -java -cp "desktopRuntime/MakeOfflineDownload.jar:desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeSignedClient "javascript/SignedBundleTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "javascript/lang" "javascript/SignedClientTemplate.txt" "javascript/UpdateDownloadSources.txt" "javascript/EaglercraftX_1.8_Offline_Signed_Client.html" \ No newline at end of file +java -cp "desktopRuntime/MakeOfflineDownload.jar:desktopRuntime/CompileEPK.jar" net.lax1dude.eaglercraft.v1_8.buildtools.workspace.MakeSignedClient "desktopRuntime/resources/SignedBundleTemplate.txt" "javascript/classes.js" "javascript/assets.epk" "desktopRuntime/resources/SignedClientTemplate.txt" "desktopRuntime/resources/UpdateDownloadSources.txt" "javascript/Starlike_Client_Offline_Signed.html" diff --git a/README.md b/README.md index ac45e8d4..aa3513ea 100644 --- a/README.md +++ b/README.md @@ -1,27 +1 @@ -### Java 17 is recommended for compiling to TeaVM - -### Java 8 or greater is required for the desktop runtime - -**Most Java IDEs will allow you to import this repository as a gradle project for compiling it to JavaScript.** - -Java must be added to your PATH! - -**To compile the web client:** -1. Run `CompileEPK` -2. Run `CompileJS` (or the `generateJavaScript` gradle task in your IDE) -3. Check the "javascript" folder - -**To compile an offline download:** -1. Run `CompileEPK` -2. Run `CompileJS` (or the `generateJavaScript` gradle task in your IDE) -3. Run `MakeOfflineDownload` -4. Check the "javascript" folder - -**To use the desktop runtime:** -1. Import the Eclipse project in "desktopRuntime/eclipseProject" into your IDE -2. Open one of the .java files from the source folders (workaround for a bug) -3. Run/Debug the client with the included "eaglercraftDebugRuntime" configuration - -**See the main 1.8 repository's README for more info** - -The source codes of EaglercraftXBungee and EaglercraftXVelocity are not included here. \ No newline at end of file +# Starlike Client diff --git a/desktopRuntime/eclipseProject/.settings/org.eclipse.jdt.core.prefs b/desktopRuntime/eclipseProject/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..0fee6a9c --- /dev/null +++ b/desktopRuntime/eclipseProject/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,15 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/desktopRuntime/resources/EPKVersionIdentifier.txt b/desktopRuntime/resources/EPKVersionIdentifier.txt new file mode 100644 index 00000000..341cf11f --- /dev/null +++ b/desktopRuntime/resources/EPKVersionIdentifier.txt @@ -0,0 +1 @@ +0.2.0 \ No newline at end of file diff --git a/desktopRuntime/resources/OfflineDownloadTemplate.txt b/desktopRuntime/resources/OfflineDownloadTemplate.txt new file mode 100644 index 00000000..d1a8eba6 --- /dev/null +++ b/desktopRuntime/resources/OfflineDownloadTemplate.txt @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + +Starlike Client + + + + + + + + + + +
+
+

This file is from ${date}

+

Game will launch in 5...

+
+

+
+
+ + diff --git a/desktopRuntime/resources/SignedBundleTemplate.txt b/desktopRuntime/resources/SignedBundleTemplate.txt new file mode 100644 index 00000000..7bcd8d32 --- /dev/null +++ b/desktopRuntime/resources/SignedBundleTemplate.txt @@ -0,0 +1,23 @@ +"use strict"; +${classes_js} + +// %%%%%%%%% launch options %%%%%%%%%%%% + +if(typeof window !== "undefined") { + window.eaglercraftXClientScriptElement = document.currentScript; + if(window.eaglercraftXOptsHints && window.eaglercraftXOptsHints.hintsVersion === 1) { + window.eaglercraftXOpts = window.eaglercraftXOptsHints; + }else { + var relayzId = Math.floor(Math.random() * 3); + window.eaglercraftXOpts = { + container: "game_frame" + }; + } + window.addEventListener("load", function() { + main(); + }); +} + +// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +if(typeof window !== "undefined") { window.eaglercraftXOpts.enableSignatureBadge = true; window.eaglercraftXOpts.assetsURI = ${assets_epk}; main(); } diff --git a/desktopRuntime/resources/SignedClientTemplate.txt b/desktopRuntime/resources/SignedClientTemplate.txt index 247d3f69..21d99a1d 100644 --- a/desktopRuntime/resources/SignedClientTemplate.txt +++ b/desktopRuntime/resources/SignedClientTemplate.txt @@ -5,27 +5,19 @@ -EaglercraftX 1.8 +Starlike Client - +
diff --git a/desktopRuntime/resources/UpdateDownloadSources.txt b/desktopRuntime/resources/UpdateDownloadSources.txt new file mode 100644 index 00000000..f9ef8acf --- /dev/null +++ b/desktopRuntime/resources/UpdateDownloadSources.txt @@ -0,0 +1,2 @@ +url: https://starlike.zumbiepig.dev/latest_update.dat +url: https://starlike.orionzleon.me/latest_update.dat diff --git a/desktopRuntime/resources/assets/eagler/boot_menu/meta_opts_templates.json b/desktopRuntime/resources/assets/eagler/boot_menu/meta_opts_templates.json index 6b13e26e..e5ad2070 100644 --- a/desktopRuntime/resources/assets/eagler/boot_menu/meta_opts_templates.json +++ b/desktopRuntime/resources/assets/eagler/boot_menu/meta_opts_templates.json @@ -45,28 +45,6 @@ "EAGLERCRAFTX_1_8_OFFLINE" ] }, - { - "name": "EaglercraftX 1.8 Demo", - "conf": "conf_template_eaglercraftX_1_8.json", - "opts": "opts_template_eaglercraftX_1_8_demo.txt", - "allow": [ - "EAGLER_STANDARD_OFFLINE" - ], - "parseTypes": [ - "EAGLERCRAFTX_1_8_OFFLINE" - ] - }, - { - "name": "EaglercraftX 1.8 HTML5 Cursors", - "conf": "conf_template_eaglercraftX_1_8.json", - "opts": "opts_template_eaglercraftX_1_8_html5Cursors.txt", - "allow": [ - "EAGLER_STANDARD_OFFLINE" - ], - "parseTypes": [ - "EAGLERCRAFTX_1_8_OFFLINE" - ] - }, { "name": "EaglercraftX 1.8 Signed", "conf": "conf_template_eaglercraftX_1_8_signed.json", @@ -78,28 +56,6 @@ "EAGLERCRAFTX_1_8_SIGNED" ] }, - { - "name": "EaglercraftX 1.8 Signed Demo", - "conf": "conf_template_eaglercraftX_1_8_signed.json", - "opts": "opts_template_eaglercraftX_1_8_demo.txt", - "allow": [ - "EAGLER_SIGNED_OFFLINE" - ], - "parseTypes": [ - "EAGLERCRAFTX_1_8_SIGNED" - ] - }, - { - "name": "EaglercraftX 1.8 Signed HTML5 Cursors", - "conf": "conf_template_eaglercraftX_1_8_signed.json", - "opts": "opts_template_eaglercraftX_1_8_html5Cursors.txt", - "allow": [ - "EAGLER_SIGNED_OFFLINE" - ], - "parseTypes": [ - "EAGLERCRAFTX_1_8_SIGNED" - ] - }, { "name": "Eaglercraft 1.5.2 (post-22w34a)", "conf": "conf_template_eaglercraft_1_5.json", diff --git a/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8.txt b/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8.txt index bfe059b6..16cdffdc 100644 --- a/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8.txt +++ b/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8.txt @@ -31,23 +31,24 @@ "forceWebViewSupport": false, "enableServerCookies": true, "enableDownloadOfflineButton": true, - "resourcePacksDB": "resourcePacks", + "downloadOfflineButtonLink": "https://starlike.orionzleon.me/offline.html", + "resourcePacksDB": "resourcePacks_starlike", "enableWebViewCSP": true, "checkRelaysForUpdates": true, "allowServerRedirects": true, "allowUpdateSvc": true, - "html5CursorSupport": false, + "html5CursorSupport": true, "allowFNAWSkins": true, "allowVoiceClient": true, - "worldsDB": "worlds", + "worldsDB": "worlds_starlike", "demoMode": false, - "localStorageNamespace": "_eaglercraftX", - "enableSignatureBadge": false, + "localStorageNamespace": "_eaglercraftX_starlike", + "enableSignatureBadge": true, "lang": "en_US", "enableMinceraft": true, "autoFixLegacyStyleAttr": true, "allowUpdateDL": true, - "logInvalidCerts": false, + "logInvalidCerts": true, "checkShaderGLErrors": false, "crashOnUncaughtExceptions": false, "forceWebGL1": false, @@ -62,5 +63,6 @@ "disableBlobURLs": false, "eaglerNoDelay": false, "ramdiskMode": false, - "singleThreadMode": false + "singleThreadMode": false, + "enableEPKVersionCheck": true } \ No newline at end of file diff --git a/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8_demo.txt b/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8_demo.txt deleted file mode 100644 index 00c65c3b..00000000 --- a/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8_demo.txt +++ /dev/null @@ -1,66 +0,0 @@ -{ - "joinServer": null, - "servers": [ - { - "addr": "ws://localhost:8081/", - "hideAddr": false, - "name": "Local test server" - } - ], - "relays": [ - { - "addr": "wss://relay.deev.is/", - "primary": "$random_relay_primary_0", - "comment": "lax1dude relay #1" - }, - { - "addr": "wss://relay.lax1dude.net/", - "primary": "$random_relay_primary_1", - "comment": "lax1dude relay #2" - }, - { - "addr": "wss://relay.shhnowisnottheti.me/", - "primary": "$random_relay_primary_2", - "comment": "ayunami relay #1" - } - ], - "openDebugConsoleOnLaunch": false, - "showBootMenuOnLaunch": false, - "bootMenuBlocksUnsignedClients": false, - "allowBootMenu": true, - "forceWebViewSupport": false, - "enableServerCookies": true, - "enableDownloadOfflineButton": true, - "resourcePacksDB": "resourcePacks", - "enableWebViewCSP": true, - "checkRelaysForUpdates": true, - "allowServerRedirects": true, - "allowUpdateSvc": true, - "html5CursorSupport": false, - "allowFNAWSkins": true, - "allowVoiceClient": true, - "worldsDB": "worlds", - "demoMode": true, - "localStorageNamespace": "_eaglercraftX", - "enableSignatureBadge": false, - "lang": "en_US", - "enableMinceraft": true, - "autoFixLegacyStyleAttr": true, - "allowUpdateDL": true, - "logInvalidCerts": false, - "checkShaderGLErrors": false, - "crashOnUncaughtExceptions": false, - "forceWebGL1": false, - "forceWebGL2": false, - "allowExperimentalWebGL1": true, - "useWebGLExt": true, - "useDelayOnSwap": false, - "useJOrbisAudioDecoder": false, - "useXHRFetch": false, - "useVisualViewport": true, - "deobfStackTraces": true, - "disableBlobURLs": false, - "eaglerNoDelay": false, - "ramdiskMode": false, - "singleThreadMode": false -} \ No newline at end of file diff --git a/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8_html5Cursors.txt b/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8_html5Cursors.txt deleted file mode 100644 index 9743e602..00000000 --- a/desktopRuntime/resources/assets/eagler/boot_menu/opts_template_eaglercraftX_1_8_html5Cursors.txt +++ /dev/null @@ -1,66 +0,0 @@ -{ - "joinServer": null, - "servers": [ - { - "addr": "ws://localhost:8081/", - "hideAddr": false, - "name": "Local test server" - } - ], - "relays": [ - { - "addr": "wss://relay.deev.is/", - "primary": "$random_relay_primary_0", - "comment": "lax1dude relay #1" - }, - { - "addr": "wss://relay.lax1dude.net/", - "primary": "$random_relay_primary_1", - "comment": "lax1dude relay #2" - }, - { - "addr": "wss://relay.shhnowisnottheti.me/", - "primary": "$random_relay_primary_2", - "comment": "ayunami relay #1" - } - ], - "openDebugConsoleOnLaunch": false, - "showBootMenuOnLaunch": false, - "bootMenuBlocksUnsignedClients": false, - "allowBootMenu": true, - "forceWebViewSupport": false, - "enableServerCookies": true, - "enableDownloadOfflineButton": true, - "resourcePacksDB": "resourcePacks", - "enableWebViewCSP": true, - "checkRelaysForUpdates": true, - "allowServerRedirects": true, - "allowUpdateSvc": true, - "html5CursorSupport": true, - "allowFNAWSkins": true, - "allowVoiceClient": true, - "worldsDB": "worlds", - "demoMode": false, - "localStorageNamespace": "_eaglercraftX", - "enableSignatureBadge": false, - "lang": "en_US", - "enableMinceraft": true, - "autoFixLegacyStyleAttr": true, - "allowUpdateDL": true, - "logInvalidCerts": false, - "checkShaderGLErrors": false, - "crashOnUncaughtExceptions": false, - "forceWebGL1": false, - "forceWebGL2": false, - "allowExperimentalWebGL1": true, - "useWebGLExt": true, - "useDelayOnSwap": false, - "useJOrbisAudioDecoder": false, - "useXHRFetch": false, - "useVisualViewport": true, - "deobfStackTraces": true, - "disableBlobURLs": false, - "eaglerNoDelay": false, - "ramdiskMode": false, - "singleThreadMode": false -} \ No newline at end of file diff --git a/desktopRuntime/resources/assets/eagler/lang/en_US.lang b/desktopRuntime/resources/assets/eagler/lang/en_US.lang new file mode 100644 index 00000000..e6588e66 --- /dev/null +++ b/desktopRuntime/resources/assets/eagler/lang/en_US.lang @@ -0,0 +1,641 @@ +eaglercraft.resourcePack.prompt.title=What do you want to do with '%s'? +eaglercraft.resourcePack.prompt.text=Tip: Hold Shift to skip this screen when selecting a resource pack! +eaglercraft.resourcePack.prompt.delete=Delete this resource pack +eaglercraft.resourcePack.prompt.add=Select this resource pack +eaglercraft.resourcePack.load.refreshing=Refreshing Resources... +eaglercraft.resourcePack.load.pleaseWait=Please Wait. +eaglercraft.resourcePack.load.loading=Loading resource pack... +eaglercraft.resourcePack.load.deleting=Deleting resource pack... + +eaglercraft.gui.exitKey=Use '%s' to close this screen! +eaglercraft.gui.exitKeyRetarded=Use Backtick (`) to close this screen! +eaglercraft.gui.continue=Continue + +eaglercraft.menu.forkOnGitlab=Fork on GitLab +eaglercraft.menu.editProfile=Edit Profile +eaglercraft.menu.openToLan=Invite +eaglercraft.menu.closeLan=Stop Sharing + +eaglercraft.editProfile.title=Edit Profile +eaglercraft.editProfile.username=Username +eaglercraft.editProfile.playerSkin=Player Skin +eaglercraft.editProfile.addSkin=Add Skin +eaglercraft.editProfile.clearSkin=Clear List +eaglercraft.editProfile.capes=Capes +eaglercraft.editProfile.disableFNAW=(Note: go to 'Options...' > 'Skin Customization' to disable FNAW skins) +eaglercraft.editProfile.enableFNAW=(Note: go to 'Options...' > 'Skin Customization' to enable FNAW skins) + +eaglercraft.editCape.title=Edit Cape +eaglercraft.editCape.playerCape=Player Cape +eaglercraft.editCape.addCape=Add Cape +eaglercraft.editCape.clearCape=Clear List + +eaglercraft.editProfile.importExport=Import/Export + +eaglercraft.defaultUsernameDetected.title=Default Username Detected +eaglercraft.defaultUsernameDetected.text0=The username "%s" was auto-generated by Eaglercraft +eaglercraft.defaultUsernameDetected.text1=It may already be taken on the largest servers +eaglercraft.defaultUsernameDetected.text2=Would you like to pick a different username instead? +eaglercraft.defaultUsernameDetected.changeUsername=Change Username +eaglercraft.defaultUsernameDetected.continueAnyway=Continue Anyway +eaglercraft.defaultUsernameDetected.doNotShow=Do not show again + +eaglercraft.settingsBackup.importExport.title=What do you wanna do? +eaglercraft.settingsBackup.importExport.import=Import Profile and Settings... +eaglercraft.settingsBackup.importExport.export=Export Profile and Settings... + +eaglercraft.settingsBackup.import.title=Import Profile and Settings +eaglercraft.settingsBackup.import.option.profile=Import Profile: +eaglercraft.settingsBackup.import.option.settings=Import Settings: +eaglercraft.settingsBackup.import.option.servers=Import Servers: +eaglercraft.settingsBackup.import.option.resourcePacks=Resource Packs: +eaglercraft.settingsBackup.import.option.import=Import + +eaglercraft.settingsBackup.export.title=Export Profile and Settings +eaglercraft.settingsBackup.export.option.profile=Export Profile: +eaglercraft.settingsBackup.export.option.settings=Export Settings: +eaglercraft.settingsBackup.export.option.servers=Export Servers: +eaglercraft.settingsBackup.export.option.resourcePacks=Resource Packs: +eaglercraft.settingsBackup.export.option.export=Export + +eaglercraft.settingsBackup.exporting.1=Exporting Profile... +eaglercraft.settingsBackup.exporting.2=Please Wait. + +eaglercraft.settingsBackup.exporting.failed.1=Export Failed! +eaglercraft.settingsBackup.exporting.failed.2=Could not compile EPK + +eaglercraft.settingsBackup.importing.1=Importing Profile... +eaglercraft.settingsBackup.importing.2=Please Wait. + +eaglercraft.settingsBackup.importing.failed.1=Import Failed! +eaglercraft.settingsBackup.importing.failed.2=Could not load EPK + +eaglercraft.resourcePack.importFailed.1=Import Failed! +eaglercraft.resourcePack.importFailed.2=Could not import ZIP file + +eaglercraft.singleplayer.integratedStartup=Starting integrated server + +eaglercraft.addServer.SSLWarn1=you are on an https: page! +eaglercraft.addServer.SSLWarn2=html5 will only allow wss:// + +eaglercraft.chat.exit=Exit Chat + +eaglercraft.handshakeApprove.plaintext.title=Protocol Warning + +eaglercraft.handshakeApprove.plaintext.body.0=§eThis server's 3rd party login system is +eaglercraft.handshakeApprove.plaintext.body.1=§eusing insecure plain-text password login + +eaglercraft.handshakeApprove.plaintext.body.3=This means your password can be stolen +eaglercraft.handshakeApprove.plaintext.body.4=by who is running this server, and also +eaglercraft.handshakeApprove.plaintext.body.5=any proxy you use to connect to it with + +eaglercraft.handshakeApprove.plaintext.body.7=§7Would you like to continue? + +eaglercraft.handshakeApprove.unsupportedAuth.title=Protocol Unsupported + +eaglercraft.handshakeApprove.unsupportedAuth.body.0=§cThis server's login system is using a +eaglercraft.handshakeApprove.unsupportedAuth.body.1=§cprotocol not supported by this client + +eaglercraft.handshakeApprove.unsupportedAuth.body.3=Please make sure you are using the +eaglercraft.handshakeApprove.unsupportedAuth.body.4=latest version of EaglercraftX or +eaglercraft.handshakeApprove.unsupportedAuth.body.5=another fork made for this server + +eaglercraft.options.hud.fps=Show FPS +eaglercraft.options.hud.coords=Show XYZ +eaglercraft.options.hud.stats=Show Stats HUD +eaglercraft.options.hud.world=Show World HUD +eaglercraft.options.hud.player=Show Player +eaglercraft.options.hud.note=Check 'Video Settings' for the option to hide XYZ +eaglercraft.options.hud.24h=24h Day +eaglercraft.options.chunkFix=Chunk Lag Fix +eaglercraft.options.fog=Fog +eaglercraft.options.fxaa=FXAA Antialiasing +eaglercraft.options.fxaa.auto=Auto +eaglercraft.options.fastMath=Fast Math +eaglercraft.options.fastMath.0=OFF +eaglercraft.options.fastMath.1=Low +eaglercraft.options.fastMath.2=High +eaglercraft.options.dynamicLights=Dynamic Lights + +eaglercraft.key.function=Function +eaglercraft.key.zoomCamera=Zoom Camera +eaglercraft.key.close=Close Screen + +eaglercraft.disconnect.tooManyRequests=Too Many Requests! + +eaglercraft.auth.required=Authentication Required +eaglercraft.auth.continue=Join Server + +eaglercraft.shaders.gui.optionsButton=Shaders... +eaglercraft.shaders.gui.title=Shaders +eaglercraft.shaders.gui.enable=Enable Shaders +eaglercraft.shaders.gui.headerTier1=Simple Effects (fast) +eaglercraft.shaders.gui.headerTier2=Intermediate Effects (not as fast) + + +eaglercraft.shaders.gui.option.WAVING_BLOCKS.label=Waving Grass + +eaglercraft.shaders.gui.option.WAVING_BLOCKS.desc.0=The classic vanilla shader that make grass and leaf blocks move with the wind +eaglercraft.shaders.gui.option.WAVING_BLOCKS.desc.2=ON: slower, complex control flow +eaglercraft.shaders.gui.option.WAVING_BLOCKS.desc.3=OFF: faster, simple control flow + +eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.label=Dynamic Lights + +eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.0=Items like torches, glowstone, jack o'lanterns, etc. light up the area around them when they are held or dropped +eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.2=This feature usually does not affect FPS unless there is a large number of dynamic light sources close to the player +eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.4=ON: enable dynamic lights +eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.5=OFF: disable dynamic lights + +eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.label=Global SSAO + +eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.0=Applies realistic screenspace ambient occlusion (SSAO) to areas of the screen that vanilla Minecraft's default "Smooth Lighting" feature cannot +eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.2=This effect can greatly reduce lag spikes caused by chunk updates in exchange for a decreased maximum FPS when standing still +eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.4=ON: use SSAO +eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.5=OFF: use vanilla + +eaglercraft.shaders.gui.option.SHADOWS_SUN.label=Sun Shadow Dist + +eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.0=Makes the sun and moon cast shadows on the world, you almost definitely want to enable this +eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.2=0: off +eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.3=1: 16 blocks +eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.4=2: 32 blocks +eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.5=3: 64 blocks +eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.6=4: 128 blocks + +eaglercraft.shaders.gui.option.SHADOWS_COLORED.label=Color Shadow + +eaglercraft.shaders.gui.option.SHADOWS_COLORED.desc.0=Makes blocks like stained glass cast colored shadows +eaglercraft.shaders.gui.option.SHADOWS_COLORED.desc.2=ON: colored shadows (slower) +eaglercraft.shaders.gui.option.SHADOWS_COLORED.desc.3=OFF: grayscale shadows (faster) + +eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.label=Smooth Shadow + +eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.desc.0=Smooths out the edges of sun and dynamic light shadows to get rid of aliasing +eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.desc.2=ON: smooth shadows (slower) +eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.desc.3=OFF: aliased shadows (faster) + +eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.label=Env. Mapping + +eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.0=Renders an environment map, allows transparent blocks and moving entities to reflect their surroundings +eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.2=Uses dual paraboloid mapping, only 2 render passes are required to render all reflections, instead of a full 6 render passes like a conventional cube map +eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.4=ON: render env. map (slower) +eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.5=OFF: disable env. map (faster) + +eaglercraft.shaders.gui.option.REALISTIC_WATER.label=Realistic Water + +eaglercraft.shaders.gui.option.REALISTIC_WATER.desc.0=Makes water realistic, adds reflection and refraction effects, uses raytracing +eaglercraft.shaders.gui.option.REALISTIC_WATER.desc.2=ON: render realistic water (slower) +eaglercraft.shaders.gui.option.REALISTIC_WATER.desc.3=OFF: render vanilla water (faster) + +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.label=God Rays + +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.0=Render god rays (light shafts) for sunlight and moonlight shadows +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.2=ON: render god rays (slower) +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.3=OFF: disable god rays (faster) + +eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.label=Raytracing + +eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.0=Renders raytraced reflections off of blocks +eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.2=Thanks to some advanced optimizations, this feature only has a small impact on FPS and is compatible with old hardware +eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.4=Both raymarching and raytracing are employed, raymarching is initially used to locate and track groups of pixels on the screen to reflect, then raytracing is used to reproject that data between multiple frames so the raymarching process only has to be repeated once or twice every few seconds +eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.6=ON: enable raytracing (slower) +eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.7=OFF: disable raytracing (faster) + +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.0=Render god rays (light shafts) for sunlight and moonlight shadows +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.2=ON: render god rays (slower) +eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.3=OFF: disable god rays (faster) + +eaglercraft.shaders.gui.option.POST_LENS_DISTORION.label=Lens Distort + +eaglercraft.shaders.gui.option.POST_LENS_DISTORION.desc.0=Renders chromatic abberation and lens distorion +eaglercraft.shaders.gui.option.POST_LENS_DISTORION.desc.2=ON: render lens distortion (slower) +eaglercraft.shaders.gui.option.POST_LENS_DISTORION.desc.3=OFF: disable lens distortion (faster) + +eaglercraft.shaders.gui.option.POST_LENS_FLARES.label=Lens Flares + +eaglercraft.shaders.gui.option.POST_LENS_FLARES.desc.0=Renders filmic lens flares for the sun +eaglercraft.shaders.gui.option.POST_LENS_FLARES.desc.2=ON: render lens flares (slower) +eaglercraft.shaders.gui.option.POST_LENS_FLARES.desc.3=OFF: disable lens flares (faster) + +eaglercraft.shaders.gui.option.POST_BLOOM.label=Bloom + +eaglercraft.shaders.gui.option.POST_BLOOM.desc.0=Renders bloom for emissive textures and sunlight +eaglercraft.shaders.gui.option.POST_BLOOM.desc.2=ON: render bloom (slower) +eaglercraft.shaders.gui.option.POST_BLOOM.desc.3=OFF: disable bloom (faster) + +eaglercraft.shaders.gui.option.POST_FXAA.label=FXAA + +eaglercraft.shaders.gui.option.POST_FXAA.desc.0=Applies FXAA antialiasing in post processing +eaglercraft.shaders.gui.option.POST_FXAA.desc.2=This is the preferred antialiasing method for minecraft, as classical MSAA cannot antialias the pixels of upscaled textures +eaglercraft.shaders.gui.option.POST_FXAA.desc.4=ON: enable fxaa (slower) +eaglercraft.shaders.gui.option.POST_FXAA.desc.5=OFF: disable fxaa (faster) + +eaglercraft.shaders.gui.unsupported.title=Shaders are unavailable on this device! +eaglercraft.shaders.gui.unsupported.reason.hdrFramebuffer=Reason: No HDR render target support +eaglercraft.shaders.gui.unsupported.reason.oldOpenGLVersion=Reason: OpenGL ES 3.0 (WebGL 2.0) is not supported! + +eaglercraft.shaders.debugMenuTip=Press %s+4 to access the shader debug menu + +eaglercraft.command.skull.tip=Use /eagskull to create custom skulls +eaglercraft.command.skull.usage=/eagskull +eaglercraft.command.skull.nopermission=Cheats are not enabled! +eaglercraft.command.skull.feedback=Created new skull: "%s" +eaglercraft.command.skull.error.invalid.format=Invalid or unsupported image file! +eaglercraft.command.skull.error.invalid.skin=Image with size %dx%d is not a valid minecraft skin! + +eaglercraft.command.clientStub=This command is client side! + +eaglercraft.singleplayer.busy.killTask=Cancel Task +eaglercraft.singleplayer.busy.cancelWarning=Are you sure? +eaglercraft.singleplayer.busy.confirmCancel=Confirm Cancel + +eaglercraft.singleplayer.crashed.title=Recieved a crash report from integrated server! +eaglercraft.singleplayer.crashed.checkConsole=Check the console for more details +eaglercraft.singleplayer.crashed.continue=Continue +eaglercraft.singleplayer.crashed.singleThreadCont=Single Thread Mode + +eaglercraft.singleplayer.failed.title=Singleplayer Task Failed! +eaglercraft.singleplayer.failed.killed=The worker process was killed +eaglercraft.singleplayer.failed.notStarted=The worker process could not start + +eaglercraft.singleplayer.failed.singleThreadWarning.1=Worker Thread Issue Detected +eaglercraft.singleplayer.failed.singleThreadWarning.2=The integrated server is running in single-threaded mode + +eaglercraft.singleplayer.busy.listingworlds=Loading worlds +eaglercraft.singleplayer.failed.listingworlds=Could not fetch worlds list! + +eaglercraft.singleplayer.busy.deleting=Deleting world +eaglercraft.singleplayer.failed.deleting=Failed to delete world! + +eaglercraft.singleplayer.busy.renaming=Renaming world +eaglercraft.singleplayer.failed.renaming=Failed to rename world! + +eaglercraft.singleplayer.busy.duplicating=Duplicating world +eaglercraft.singleplayer.failed.duplicating=Failed to duplicate world! + +eaglercraft.singleplayer.busy.importing.1=Importing world as EPK +eaglercraft.singleplayer.failed.importing.1=Failed to import world as EPK! + +eaglercraft.singleplayer.busy.importing.2=Importing world as vanilla +eaglercraft.singleplayer.failed.importing.2=Failed to import world as vanilla! + +eaglercraft.singleplayer.busy.exporting.1=Exporting world as EPK +eaglercraft.singleplayer.failed.exporting.1=Failed to export world as EPK! + +eaglercraft.singleplayer.busy.exporting.2=Exporting world as vanilla +eaglercraft.singleplayer.failed.exporting.2=Failed to export world as vanilla! + +eaglercraft.singleplayer.busy.clearplayers=Clearing players +eaglercraft.singleplayer.failed.clearplayers=Failed to clear players! + +eaglercraft.singleplayer.busy.startingIntegratedServer=Starting up integrated server +eaglercraft.singleplayer.failed.startingIntegratedServer=Failed to start up integrated server! + +eaglercraft.singleplayer.busy.stoppingIntegratedServer=Shutting down integrated server +eaglercraft.singleplayer.failed.stoppingIntegratedServer=Failed to shut down integrated server! + +eaglercraft.singleplayer.failed.serverCrash=Integrated server encountered an exception! + +eaglercraft.singleplayer.failed.demo.title=Could not start demo +eaglercraft.singleplayer.failed.demo.desc=Failed to start integrated server! + +eaglercraft.singleplayer.notSupported.title=Shared worlds are not supported on this browser! +eaglercraft.singleplayer.notSupported.desc=WebRTC is not supported + +eaglercraft.singleplayer.import.title=Import World +eaglercraft.singleplayer.import.enterName=Enter world name: +eaglercraft.singleplayer.import.continue=Continue +eaglercraft.singleplayer.import.reading=Reading: '%s' +eaglercraft.singleplayer.import.loadSpawnChunks=Keep spawn chunks loaded: %s +eaglercraft.singleplayer.import.enhancedGameRules=Add extra game features: %s + +eaglercraft.singleplayer.create.title=What do you wanna do? +eaglercraft.singleplayer.create.create=Create New World +eaglercraft.singleplayer.create.create.tooltip=Make a new world for eaglercraft +eaglercraft.singleplayer.create.import=Load EPK File +eaglercraft.singleplayer.create.import.tooltip=Load an Eaglercraft .epk world file +eaglercraft.singleplayer.create.vanilla=Import Vanilla World +eaglercraft.singleplayer.create.vanilla.tooltip=Load a vanilla minecraft 1.8 world + +eaglercraft.singleplayer.backup.title=World Backup Menu: '%s' +eaglercraft.singleplayer.backup.recreate=Re-Create World +eaglercraft.singleplayer.backup.recreate.tooltip=Create a new world with the same seed +eaglercraft.singleplayer.backup.seed=Seed: +eaglercraft.singleplayer.backup.duplicate=Duplicate World +eaglercraft.singleplayer.backup.duplicate.tooltip=Copy this world into a new save +eaglercraft.singleplayer.backup.export=Export EPK File +eaglercraft.singleplayer.backup.export.tooltip=Download this world as a compressed .epk file +eaglercraft.singleplayer.backup.vanilla=Convert to Vanilla +eaglercraft.singleplayer.backup.vanilla.tooltip=Download this world as a vanilla 1.8 world +eaglercraft.singleplayer.backup.clearPlayerData=Delete Player Data +eaglercraft.singleplayer.backup.clearPlayerData.tooltip=Clears the inventories of all players except the owner + +eaglercraft.singleplayer.backup.clearPlayerData.warning1=Are you sure you want to delete all player data? +eaglercraft.singleplayer.backup.clearPlayerData.warning2=All players in '%s' will lose their inventories (besides %s) + +eaglercraft.singleplayer.ramdiskdetected.title=Worker Issues Detected +eaglercraft.singleplayer.ramdiskdetected.text0=Running in "RAMDisk mode", worlds cannot be saved! +eaglercraft.singleplayer.ramdiskdetected.text1=Single thread mode may solve this issue +eaglercraft.singleplayer.ramdiskdetected.continue=Continue +eaglercraft.singleplayer.ramdiskdetected.singleThreadCont=Single Thread Mode + +eaglercraft.selectWorld.backup=Backup + +eaglercraft.selectWorld.duplicate=Duplicate World: +eaglercraft.selectWorld.duplicateButton=Duplicate + +eaglercraft.selectWorld.ramdiskWarning=WARNING: Running in "RAMDisk mode", worlds will NOT be saved to local storage! + +eaglercraft.singleplayer.tpscounter.singleThreadMode=Single Thread Mode + +eaglercraft.networkSettings.title=Shared World Relay Servers +eaglercraft.networkSettings.add=Add Relay +eaglercraft.networkSettings.delete=Delete Relay +eaglercraft.networkSettings.default=Set Primary +eaglercraft.networkSettings.refresh=Refresh +eaglercraft.networkSettings.loadDefaults=Load Defaults +eaglercraft.networkSettings.relayTimeout=Connection Timeout: +eaglercraft.networkSettings.relayTimeoutChange=change +eaglercraft.networkSettings.relayTimeoutTitle=Change Connection Timeout +eaglercraft.networkSettings.downloadRelay=Download JAR + +eaglercraft.directConnect.prompt=What would you like to do? +eaglercraft.directConnect.lanWorld=Join Shared World +eaglercraft.directConnect.lanWorldCode=Enter Join Code: +eaglercraft.directConnect.networkSettingsNote=Click 'Network Settings' to add a relay URL +eaglercraft.directConnect.ipGrabNote=Note: The world's owner can get your IP address +eaglercraft.directConnect.serverJoin=Connect to Server +eaglercraft.directConnect.lanWorldJoin=Join World +eaglercraft.directConnect.lanWorldRelay=Network Settings + +eaglercraft.lanInfo.title=Shared World Info +eaglercraft.lanInfo.desc.0=Eaglercraft shared worlds are NOT limited to your local network like vanilla LAN worlds. This means that anyone with an internet connection and connection to the invite relay can join your world provided they have the code. +eaglercraft.lanInfo.desc.1=Join a shared world from the %s screen, or create one with the %s button while in a world. + +eaglercraft.lanServer.legacyClient=Please use EaglercraftX 1.8! + +eaglercraft.lanServer.pauseMenu0=Sharing World +eaglercraft.lanServer.pauseMenu1=Relay URL: +eaglercraft.lanServer.pauseMenu2=Join Code: + +eaglercraft.lanServer.wouldYouLikeToKick=Would you like to kick all players? + +eaglercraft.lanServer.worldName=World Name: +eaglercraft.lanServer.hidden=Hidden: +eaglercraft.lanServer.hideCode=hide details +eaglercraft.lanServer.showCode=show details +eaglercraft.lanServer.opened=Shared world opened on $relay$, join code is §a$code$ +eaglercraft.lanServer.closed=Shared world closed +eaglercraft.lanServer.pleaseWait=Please Wait... +eaglercraft.lanServer.relayDisconnected=Warning: connection to invite relay was lost, you must re-share the world to invite more people +eaglercraft.lanServer.ipGrabNote=Note: Players joining your world can get your IP address + +eaglercraft.addRelay.title=Add New Relay +eaglercraft.addRelay.name=Relay Comment +eaglercraft.addRelay.address=Relay Address +eaglercraft.addRelay.add=Add Relay +eaglercraft.addRelay.primary=Set Primary +eaglercraft.addRelay.removeText1=Do you want to remove this relay? + +eaglercraft.noRelay.title=No Relays are Configured! +eaglercraft.noRelay.titleFail=No Working Relays Available! +eaglercraft.noRelay.noRelay1=Shared Worlds Unavailable: No Relays Configured! +eaglercraft.noRelay.noRelay2=Click '§nNetwork Settings§r' to fix +eaglercraft.noRelay.worldNotFound1=Could not locate '§c$code$§r'! +eaglercraft.noRelay.worldNotFound2=Make sure to add the '§f$code$§r' world's relay URL +eaglercraft.noRelay.worldNotFound3=to the relay list 'Network Settings' to connect +eaglercraft.noRelay.worldFail=Failed to connect to '$code$'! + +eaglercraft.singleplayer.demo.create.title=What do you wanna do? +eaglercraft.singleplayer.demo.create.create=Play Demo World +eaglercraft.singleplayer.demo.create.create.tooltip=Play the Minecraft 1.8 demo and invite others +eaglercraft.singleplayer.demo.create.join=Join Shared World +eaglercraft.singleplayer.demo.create.join.tooltip=Join someone else's world and play multiplayer + +eaglercraft.createWorld.seedNote=Note: Vanilla seeds now work! + +eaglercraft.singleplayer.oldseedwarning.title=Old World Detected! +eaglercraft.singleplayer.oldseedwarning.msg1=Please use EaglercraftX u32 or older to "Re-Create" this world +eaglercraft.singleplayer.oldseedwarning.msg2=The world's seed will not be the same otherwise :( +eaglercraft.singleplayer.oldseedwarning.ok=OK + +eaglercraft.singleplayer.outdatedLANServerKick=This is a 1.5.2 LAN world! + +eaglercraft.options.debugConsoleButton=Open Debug Console + +eaglercraft.tile.bed.setspawn=Respawn point set + +eaglercraft.update.button=Check for updates: +eaglercraft.update.none=No updates available! +eaglercraft.update.noneNew=No new updates found +eaglercraft.update.found=Found new client update +eaglercraft.update.update=Update: +eaglercraft.update.author=Author: +eaglercraft.update.timestamp=Timestamp: +eaglercraft.update.size=Size (kB): +eaglercraft.update.startDownload=Download +eaglercraft.update.viewAll=View All (%d) +eaglercraft.update.dismiss=Dismiss +eaglercraft.update.downloading=Downloading Updates + +eaglercraft.update.downloadOffline=Download Offline +eaglercraft.update.digitallySigned=Digitally Signed (%s) +eaglercraft.update.signatureInvalid=Signature Invalid! + +eaglercraft.updateList.title=Versions Available +eaglercraft.updateList.download=Download +eaglercraft.updateList.refresh=Refresh +eaglercraft.updateList.note.0=Note: Updates are digitally signed, EaglercraftX will block any +eaglercraft.updateList.note.1=updates that were not created by lax1dude or ayunami2000 + +eaglercraft.updateSuccess.title=Update Successful +eaglercraft.updateSuccess.installToBootMenu=Install to Boot Menu +eaglercraft.updateSuccess.downloadOffline=Download Offline + +eaglercraft.updateSuccess.downloading=Downloading Offline... +eaglercraft.updateSuccess.installing=Installing Client... + +eaglercraft.updateFailed.title=Update Failed + +eaglercraft.installFailed.title=Installation Failed + +eaglercraft.updateInstall.title=Install to Boot Menu +eaglercraft.updateInstall.setDefault=Make Default +eaglercraft.updateInstall.setCountdown=Enable Countdown +eaglercraft.updateInstall.install=Install + +eaglercraft.options.pressDeleteText=Press DEL to enter boot menu + +eaglercraft.enterBootMenu.title=Enter Boot Menu +eaglercraft.enterBootMenu.text0=Refresh the page to enter the boot menu + +eaglercraft.voice.title=Voice Channel +eaglercraft.voice.titleNoVoice=Voice is disabled on this server +eaglercraft.voice.titleVoiceUnavailable=Voice is unavailable +eaglercraft.voice.titleVoiceBrowserError=(browser issue) +eaglercraft.voice.ptt=Press '%s' to speak +eaglercraft.voice.pttChangeDesc=(Press Any Key) +eaglercraft.voice.changeKey=Change +eaglercraft.voice.off=OFF +eaglercraft.voice.radius=NEARBY +eaglercraft.voice.global=GLOBAL +eaglercraft.voice.volumeTitle=Change Volume +eaglercraft.voice.volumeListen=Speakers Volume: +eaglercraft.voice.volumeSpeak=Microphone Volume: +eaglercraft.voice.radiusTitle=Change Listener Radius +eaglercraft.voice.radiusLabel=Players Within: +eaglercraft.voice.radiusChange=change +eaglercraft.voice.notConnected=Not Connected +eaglercraft.voice.connecting=Connecting... +eaglercraft.voice.unavailable=Could not connect! +eaglercraft.voice.connectedGlobal=Connected - Global +eaglercraft.voice.connectedRadius=Connected - $f$Within $radius$m +eaglercraft.voice.playersListening=Players Listening: +eaglercraft.voice.muted=Players Muted: +eaglercraft.voice.unmute=unmute +eaglercraft.voice.mute=mute +eaglercraft.voice.apply=Apply +eaglercraft.voice.volumeSpeakerLabel=Speakers: +eaglercraft.voice.volumeMicrophoneLabel=Microphone: + +eaglercraft.voice.unsupportedWarning1=Voice Warning +eaglercraft.voice.unsupportedWarning2=Your network configuration may not support +eaglercraft.voice.unsupportedWarning3=eaglercraft's voice chat. +eaglercraft.voice.unsupportedWarning4=Voice chat is based on WebRTC and is +eaglercraft.voice.unsupportedWarning5=normally meant to be peer-to-peer, if your +eaglercraft.voice.unsupportedWarning6=firewall blocks peer-to-peer connections +eaglercraft.voice.unsupportedWarning7=a TURN server will be required. +eaglercraft.voice.unsupportedWarning8=The default OpenRelayProject TURN servers +eaglercraft.voice.unsupportedWarning9=are no longer working in 2024! + +eaglercraft.voice.unsupportedWarning10=Continue +eaglercraft.voice.unsupportedWarning11=Cancel + +eaglercraft.voice.ipGrabWarning1=IP Logger Warning +eaglercraft.voice.ipGrabWarning2=Using Eaglercraft voice chat may allow your +eaglercraft.voice.ipGrabWarning3=IP address to be logged by other players +eaglercraft.voice.ipGrabWarning4=also using voice on the server. +eaglercraft.voice.ipGrabWarning5=This issue will not be fixed, it is an +eaglercraft.voice.ipGrabWarning6=internal browser issue, not a mistake in the +eaglercraft.voice.ipGrabWarning7=game. Sorry about that. + +eaglercraft.revokeSessionToken.button=Revoke Session Token +eaglercraft.revokeSessionToken.title=Select session to revoke: +eaglercraft.revokeSessionToken.inspect=Inspect +eaglercraft.revokeSessionToken.revoke=Revoke +eaglercraft.revokeSessionToken.note.0=Use this tool when you believe someone has stolen your cookies +eaglercraft.revokeSessionToken.note.1=Eagler will request the server invalidate all session tokens + +eaglercraft.inspectSessionToken.title=Cookie Details +eaglercraft.inspectSessionToken.details.server=Server Address: +eaglercraft.inspectSessionToken.details.expires=Expires At: +eaglercraft.inspectSessionToken.details.length=Byte Length: + +eaglercraft.errorNoSessions.title=No Sessions Active! +eaglercraft.errorNoSessions.desc=There are no revokable sessions + +eaglercraft.revokeSendingScreen.title=Revoking Session +eaglercraft.revokeSendingScreen.message.opening=Connecting to %s... +eaglercraft.revokeSendingScreen.message.sending=Sending Request... + +eaglercraft.revokeSuccess.title=Revoke Success +eaglercraft.revokeSuccess.desc=The session was revoked sucessfully! + +eaglercraft.revokeFailure.title=Revoke Failed +eaglercraft.revokeFailure.desc.notSupported=The server does not support this feature! +eaglercraft.revokeFailure.desc.notAllowed=The server does not allow revoking this token! +eaglercraft.revokeFailure.desc.notFound=The session was not found on the server! +eaglercraft.revokeFailure.desc.serverError=Internal server error! +eaglercraft.revokeFailure.desc.clientError=Error handling server's response! +eaglercraft.revokeFailure.desc.genericCode=Error code received! (Check Console) +eaglercraft.revokeFailure.desc.connectionError=Failed to connect to the server! +eaglercraft.revokeFailure.desc.cancelled=Connection closed + +eaglercraft.recieveServerInfo.title=Retrieving Server Info +eaglercraft.recieveServerInfo.checkingCache=Checking Cache +eaglercraft.recieveServerInfo.contactingServer=Contacting Server +eaglercraft.recieveServerInfo.recievingData=Recieving Data +eaglercraft.recieveServerInfo.decompressing=Decompressing + Verifying + +eaglercraft.serverInfoFailure.title=Retrieval Failed +eaglercraft.serverInfoFailure.desc=Failed to retrieve server info! + +eaglercraft.webviewNotSupported.title=WebView Error +eaglercraft.webviewNotSupported.desc=WebView is not supported on this platform! + +eaglercraft.webviewInvalidURL.title=WebView Error +eaglercraft.webviewInvalidURL.desc=Server provided an invalid URL! + +eaglercraft.fallbackWebViewScreen.text0=View in your browser at: +eaglercraft.fallbackWebViewScreen.startingUp=Starting Up... +eaglercraft.fallbackWebViewScreen.pleaseWait=Please Wait... +eaglercraft.fallbackWebViewScreen.exited=(exited) +eaglercraft.fallbackWebViewScreen.openButton=Open +eaglercraft.fallbackWebViewScreen.exitButton=Exit + +eaglercraft.webviewPhishingWaring.title=WARNING!!! +eaglercraft.webviewPhishingWaring.text0=If you see a login page, think before you enter a password +eaglercraft.webviewPhishingWaring.text1=Passwords can be stolen by the owner of this server or website +eaglercraft.webviewPhishingWaring.text2=Do not log in to accounts you don't want hackers to steal +eaglercraft.webviewPhishingWaring.dontShowAgain=Do not show this message again +eaglercraft.webviewPhishingWaring.continue=Continue + +eaglercraft.notifications.title=Notifications +eaglercraft.notifications.priority=Priority: %s +eaglercraft.notifications.priority.low=All +eaglercraft.notifications.priority.normal=Info +eaglercraft.notifications.priority.higher=Warning +eaglercraft.notifications.priority.highest=Severe +eaglercraft.notifications.clearAll=Clear All + +eaglercraft.options.touchControlOpacity=Touch Ctrls Opacity + +eaglercraft.options.profanityFilterButton=Profanity Filter + +eaglercraft.profanityFilterWarning.title=Content Warning +eaglercraft.profanityFilterWarning.text0=If you are streaming this game on Twitch, or +eaglercraft.profanityFilterWarning.text1=are under the wise old age of 14, please enable +eaglercraft.profanityFilterWarning.text2=the profanity filter before playing Multiplayer +eaglercraft.profanityFilterWarning.text4=(Disable in the 'Options' -> 'Chat Settings' menu) + +eaglercraft.options.screenRecording.unsupported=Recording Unsupported! +eaglercraft.options.screenRecording.button=Record Screen... + +eaglercraft.options.screenRecording.title=Screen Recording +eaglercraft.options.screenRecording.codec=Output Format: %s +eaglercraft.options.screenRecording.codecButton=Change... +eaglercraft.options.screenRecording.start=Start Recording +eaglercraft.options.screenRecording.stop=Stop Recording +eaglercraft.options.screenRecording.status=Status: %s +eaglercraft.options.screenRecording.status.0=Not Recording +eaglercraft.options.screenRecording.status.1=Recording! +eaglercraft.options.screenRecording.audioBitrate=Audio Bitrate +eaglercraft.options.screenRecording.videoBitrate=Video Bitrate +eaglercraft.options.screenRecording.videoResolution=Video Resolution +eaglercraft.options.screenRecording.microphoneVolume=Microphone Volume +eaglercraft.options.screenRecording.gameVolume=Game Volume +eaglercraft.options.screenRecording.videoFPS=Video Frame Rate +eaglercraft.options.screenRecording.onVSync=VSync +eaglercraft.options.screenRecording.failed=Failed to begin recording! + +eaglercraft.options.recordingCodec.title=Select Codec +eaglercraft.options.recordingCodec.showAdvancedCodecs=Show Advanced: %s + +eaglercraft.options.recordingNote.title=Recording Note +eaglercraft.options.recordingNote.text0=If the recorded video does not play, +eaglercraft.options.recordingNote.text1=try opening the file in your browser + +eaglercraft.touch.interact.entity=Interact + +eaglercraft.addServer.hideAddr=Hide Addr +eaglercraft.addServer.enableCookies=Cookies +eaglercraft.addServer.enableCookies.enabled=Enabled +eaglercraft.addServer.enableCookies.disabled=Disabled + +lanServer.title=Shared World +lanServer.start=Start Shared World + +options.skinCustomisation.enableFNAWSkins=Show FNAW Skins + +resourcePack.openFolder=Open resource pack +resourcePack.folderInfo=(Select resource pack files here) diff --git a/desktopRuntime/resources/assets/minecraft/lang/en_US.lang b/desktopRuntime/resources/assets/minecraft/lang/en_US.lang index 581db7b9..8589d53f 100644 --- a/desktopRuntime/resources/assets/minecraft/lang/en_US.lang +++ b/desktopRuntime/resources/assets/minecraft/lang/en_US.lang @@ -15,245 +15,6 @@ gui.no=No gui.none=None gui.all=All -eaglercraft.resourcePack.prompt.title=What do you want to do with '%s'? -eaglercraft.resourcePack.prompt.text=Tip: Hold Shift to skip this screen when selecting a resource pack! -eaglercraft.resourcePack.prompt.delete=Delete this resource pack -eaglercraft.resourcePack.prompt.add=Select this resource pack -eaglercraft.resourcePack.load.refreshing=Refreshing Resources... -eaglercraft.resourcePack.load.pleaseWait=Please Wait. -eaglercraft.resourcePack.load.loading=Loading resource pack... -eaglercraft.resourcePack.load.deleting=Deleting resource pack... - -eaglercraft.gui.exitKey=Use '%s' to close this screen! -eaglercraft.gui.exitKeyRetarded=Use Backtick (`) to close this screen! -eaglercraft.gui.continue=Continue - -eaglercraft.menu.forkOnGitlab=Fork on GitLab -eaglercraft.menu.editProfile=Edit Profile -eaglercraft.menu.openToLan=Invite -eaglercraft.menu.closeLan=Stop Sharing - -eaglercraft.editProfile.title=Edit Profile -eaglercraft.editProfile.username=Username -eaglercraft.editProfile.playerSkin=Player Skin -eaglercraft.editProfile.addSkin=Add Skin -eaglercraft.editProfile.clearSkin=Clear List -eaglercraft.editProfile.capes=Capes -eaglercraft.editProfile.disableFNAW=(Note: go to 'Options...' > 'Skin Customization' to disable FNAW skins) -eaglercraft.editProfile.enableFNAW=(Note: go to 'Options...' > 'Skin Customization' to enable FNAW skins) - -eaglercraft.editCape.title=Edit Cape -eaglercraft.editCape.playerCape=Player Cape -eaglercraft.editCape.addCape=Add Cape -eaglercraft.editCape.clearCape=Clear List - -eaglercraft.editProfile.importExport=Import/Export - -eaglercraft.settingsBackup.importExport.title=What do you wanna do? -eaglercraft.settingsBackup.importExport.import=Import Profile and Settings... -eaglercraft.settingsBackup.importExport.export=Export Profile and Settings... - -eaglercraft.settingsBackup.import.title=Import Profile and Settings -eaglercraft.settingsBackup.import.option.profile=Import Profile: -eaglercraft.settingsBackup.import.option.settings=Import Settings: -eaglercraft.settingsBackup.import.option.servers=Import Servers: -eaglercraft.settingsBackup.import.option.resourcePacks=Resource Packs: -eaglercraft.settingsBackup.import.option.import=Import - -eaglercraft.settingsBackup.export.title=Export Profile and Settings -eaglercraft.settingsBackup.export.option.profile=Export Profile: -eaglercraft.settingsBackup.export.option.settings=Export Settings: -eaglercraft.settingsBackup.export.option.servers=Export Servers: -eaglercraft.settingsBackup.export.option.resourcePacks=Resource Packs: -eaglercraft.settingsBackup.export.option.export=Export - -eaglercraft.settingsBackup.exporting.1=Exporting Profile... -eaglercraft.settingsBackup.exporting.2=Please Wait. - -eaglercraft.settingsBackup.exporting.failed.1=Export Failed! -eaglercraft.settingsBackup.exporting.failed.2=Could not compile EPK - -eaglercraft.settingsBackup.importing.1=Importing Profile... -eaglercraft.settingsBackup.importing.2=Please Wait. - -eaglercraft.settingsBackup.importing.failed.1=Import Failed! -eaglercraft.settingsBackup.importing.failed.2=Could not load EPK - -eaglercraft.resourcePack.importFailed.1=Import Failed! -eaglercraft.resourcePack.importFailed.2=Could not import ZIP file - -eaglercraft.singleplayer.integratedStartup=Starting integrated server - -eaglercraft.addServer.SSLWarn1=you are on an https: page! -eaglercraft.addServer.SSLWarn2=html5 will only allow wss:// - -eaglercraft.chat.exit=Exit Chat - -eaglercraft.handshakeApprove.plaintext.title=Protocol Warning - -eaglercraft.handshakeApprove.plaintext.body.0=§eThis server's 3rd party login system is -eaglercraft.handshakeApprove.plaintext.body.1=§eusing insecure plain-text password login - -eaglercraft.handshakeApprove.plaintext.body.3=This means your password can be stolen -eaglercraft.handshakeApprove.plaintext.body.4=by who is running this server, and also -eaglercraft.handshakeApprove.plaintext.body.5=any proxy you use to connect to it with - -eaglercraft.handshakeApprove.plaintext.body.7=§7Would you like to continue? - -eaglercraft.handshakeApprove.unsupportedAuth.title=Protocol Unsupported - -eaglercraft.handshakeApprove.unsupportedAuth.body.0=§cThis server's login system is using a -eaglercraft.handshakeApprove.unsupportedAuth.body.1=§cprotocol not supported by this client - -eaglercraft.handshakeApprove.unsupportedAuth.body.3=Please make sure you are using the -eaglercraft.handshakeApprove.unsupportedAuth.body.4=latest version of EaglercraftX or -eaglercraft.handshakeApprove.unsupportedAuth.body.5=another fork made for this server - -eaglercraft.options.hud.fps=Show FPS -eaglercraft.options.hud.coords=Show XYZ -eaglercraft.options.hud.stats=Show Stats HUD -eaglercraft.options.hud.world=Show World HUD -eaglercraft.options.hud.player=Show Player -eaglercraft.options.hud.note=Check 'Video Settings' for the option to hide XYZ -eaglercraft.options.hud.24h=24h Day -eaglercraft.options.chunkFix=Chunk Lag Fix -eaglercraft.options.fog=Fog -eaglercraft.options.fxaa=FXAA Antialiasing -eaglercraft.options.fxaa.auto=Auto -eaglercraft.options.fastMath=Fast Math -eaglercraft.options.fastMath.0=OFF -eaglercraft.options.fastMath.1=Low -eaglercraft.options.fastMath.2=High -eaglercraft.options.dynamicLights=Dynamic Lights - -eaglercraft.key.function=Function -eaglercraft.key.zoomCamera=Zoom Camera -eaglercraft.key.close=Close Screen - -eaglercraft.disconnect.tooManyRequests=Too Many Requests! - -eaglercraft.auth.required=Authentication Required -eaglercraft.auth.continue=Join Server - -eaglercraft.shaders.gui.optionsButton=Shaders... -eaglercraft.shaders.gui.title=Shaders -eaglercraft.shaders.gui.enable=Enable Shaders -eaglercraft.shaders.gui.headerTier1=Simple Effects (fast) -eaglercraft.shaders.gui.headerTier2=Intermediate Effects (not as fast) - - -eaglercraft.shaders.gui.option.WAVING_BLOCKS.label=Waving Grass - -eaglercraft.shaders.gui.option.WAVING_BLOCKS.desc.0=The classic vanilla shader that make grass and leaf blocks move with the wind -eaglercraft.shaders.gui.option.WAVING_BLOCKS.desc.2=ON: slower, complex control flow -eaglercraft.shaders.gui.option.WAVING_BLOCKS.desc.3=OFF: faster, simple control flow - -eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.label=Dynamic Lights - -eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.0=Items like torches, glowstone, jack o'lanterns, etc. light up the area around them when they are held or dropped -eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.2=This feature usually does not affect FPS unless there is a large number of dynamic light sources close to the player -eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.4=ON: enable dynamic lights -eaglercraft.shaders.gui.option.DYNAMIC_LIGHTS.desc.5=OFF: disable dynamic lights - -eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.label=Global SSAO - -eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.0=Applies realistic screenspace ambient occlusion (SSAO) to areas of the screen that vanilla Minecraft's default "Smooth Lighting" feature cannot -eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.2=This effect can greatly reduce lag spikes caused by chunk updates in exchange for a decreased maximum FPS when standing still -eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.4=ON: use SSAO -eaglercraft.shaders.gui.option.GLOBAL_AMBIENT_OCCLUSION.desc.5=OFF: use vanilla - -eaglercraft.shaders.gui.option.SHADOWS_SUN.label=Sun Shadow Dist - -eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.0=Makes the sun and moon cast shadows on the world, you almost definitely want to enable this -eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.2=0: off -eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.3=1: 16 blocks -eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.4=2: 32 blocks -eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.5=3: 64 blocks -eaglercraft.shaders.gui.option.SHADOWS_SUN.desc.6=4: 128 blocks - -eaglercraft.shaders.gui.option.SHADOWS_COLORED.label=Color Shadow - -eaglercraft.shaders.gui.option.SHADOWS_COLORED.desc.0=Makes blocks like stained glass cast colored shadows -eaglercraft.shaders.gui.option.SHADOWS_COLORED.desc.2=ON: colored shadows (slower) -eaglercraft.shaders.gui.option.SHADOWS_COLORED.desc.3=OFF: grayscale shadows (faster) - -eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.label=Smooth Shadow - -eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.desc.0=Smooths out the edges of sun and dynamic light shadows to get rid of aliasing -eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.desc.2=ON: smooth shadows (slower) -eaglercraft.shaders.gui.option.SHADOWS_SMOOTHED.desc.3=OFF: aliased shadows (faster) - -eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.label=Env. Mapping - -eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.0=Renders an environment map, allows transparent blocks and moving entities to reflect their surroundings -eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.2=Uses dual paraboloid mapping, only 2 render passes are required to render all reflections, instead of a full 6 render passes like a conventional cube map -eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.4=ON: render env. map (slower) -eaglercraft.shaders.gui.option.REFLECTIONS_PARABOLOID.desc.5=OFF: disable env. map (faster) - -eaglercraft.shaders.gui.option.REALISTIC_WATER.label=Realistic Water - -eaglercraft.shaders.gui.option.REALISTIC_WATER.desc.0=Makes water realistic, adds reflection and refraction effects, uses raytracing -eaglercraft.shaders.gui.option.REALISTIC_WATER.desc.2=ON: render realistic water (slower) -eaglercraft.shaders.gui.option.REALISTIC_WATER.desc.3=OFF: render vanilla water (faster) - -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.label=God Rays - -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.0=Render god rays (light shafts) for sunlight and moonlight shadows -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.2=ON: render god rays (slower) -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.3=OFF: disable god rays (faster) - -eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.label=Raytracing - -eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.0=Renders raytraced reflections off of blocks -eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.2=Thanks to some advanced optimizations, this feature only has a small impact on FPS and is compatible with old hardware -eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.4=Both raymarching and raytracing are employed, raymarching is initially used to locate and track groups of pixels on the screen to reflect, then raytracing is used to reproject that data between multiple frames so the raymarching process only has to be repeated once or twice every few seconds -eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.6=ON: enable raytracing (slower) -eaglercraft.shaders.gui.option.SCREEN_SPACE_REFLECTIONS.desc.7=OFF: disable raytracing (faster) - -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.0=Render god rays (light shafts) for sunlight and moonlight shadows -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.2=ON: render god rays (slower) -eaglercraft.shaders.gui.option.LIGHT_SHAFTS.desc.3=OFF: disable god rays (faster) - -eaglercraft.shaders.gui.option.POST_LENS_DISTORION.label=Lens Distort - -eaglercraft.shaders.gui.option.POST_LENS_DISTORION.desc.0=Renders chromatic abberation and lens distorion -eaglercraft.shaders.gui.option.POST_LENS_DISTORION.desc.2=ON: render lens distortion (slower) -eaglercraft.shaders.gui.option.POST_LENS_DISTORION.desc.3=OFF: disable lens distortion (faster) - -eaglercraft.shaders.gui.option.POST_LENS_FLARES.label=Lens Flares - -eaglercraft.shaders.gui.option.POST_LENS_FLARES.desc.0=Renders filmic lens flares for the sun -eaglercraft.shaders.gui.option.POST_LENS_FLARES.desc.2=ON: render lens flares (slower) -eaglercraft.shaders.gui.option.POST_LENS_FLARES.desc.3=OFF: disable lens flares (faster) - -eaglercraft.shaders.gui.option.POST_BLOOM.label=Bloom - -eaglercraft.shaders.gui.option.POST_BLOOM.desc.0=Renders bloom for emissive textures and sunlight -eaglercraft.shaders.gui.option.POST_BLOOM.desc.2=ON: render bloom (slower) -eaglercraft.shaders.gui.option.POST_BLOOM.desc.3=OFF: disable bloom (faster) - -eaglercraft.shaders.gui.option.POST_FXAA.label=FXAA - -eaglercraft.shaders.gui.option.POST_FXAA.desc.0=Applies FXAA antialiasing in post processing -eaglercraft.shaders.gui.option.POST_FXAA.desc.2=This is the preferred antialiasing method for minecraft, as classical MSAA cannot antialias the pixels of upscaled textures -eaglercraft.shaders.gui.option.POST_FXAA.desc.4=ON: enable fxaa (slower) -eaglercraft.shaders.gui.option.POST_FXAA.desc.5=OFF: disable fxaa (faster) - -eaglercraft.shaders.gui.unsupported.title=Shaders are unavailable on this device! -eaglercraft.shaders.gui.unsupported.reason.hdrFramebuffer=Reason: No HDR render target support -eaglercraft.shaders.gui.unsupported.reason.oldOpenGLVersion=Reason: OpenGL ES 3.0 (WebGL 2.0) is not supported! - -eaglercraft.shaders.debugMenuTip=Press %s+4 to access the shader debug menu - -eaglercraft.command.skull.tip=Use /eagskull to create custom skulls -eaglercraft.command.skull.usage=/eagskull -eaglercraft.command.skull.nopermission=Cheats are not enabled! -eaglercraft.command.skull.feedback=Created new skull: "%s" -eaglercraft.command.skull.error.invalid.format=Invalid or unsupported image file! -eaglercraft.command.skull.error.invalid.skin=Image with size %dx%d is not a valid minecraft skin! - -eaglercraft.command.clientStub=This command is client side! - menu.game=Game menu menu.singleplayer=Singleplayer menu.multiplayer=Multiplayer @@ -417,388 +178,6 @@ generator.debug_all_block_states=Debug Mode generator.amplified.info=Notice: Just for fun, requires beefy computer -eaglercraft.singleplayer.busy.killTask=Cancel Task -eaglercraft.singleplayer.busy.cancelWarning=Are you sure? -eaglercraft.singleplayer.busy.confirmCancel=Confirm Cancel - -eaglercraft.singleplayer.crashed.title=Recieved a crash report from integrated server! -eaglercraft.singleplayer.crashed.checkConsole=Check the console for more details -eaglercraft.singleplayer.crashed.continue=Continue -eaglercraft.singleplayer.crashed.singleThreadCont=Single Thread Mode - -eaglercraft.singleplayer.failed.title=Singleplayer Task Failed! -eaglercraft.singleplayer.failed.killed=The worker process was killed -eaglercraft.singleplayer.failed.notStarted=The worker process could not start - -eaglercraft.singleplayer.failed.singleThreadWarning.1=Worker Thread Issue Detected -eaglercraft.singleplayer.failed.singleThreadWarning.2=The integrated server is running in single-threaded mode - -eaglercraft.singleplayer.busy.listingworlds=Loading worlds -eaglercraft.singleplayer.failed.listingworlds=Could not fetch worlds list! - -eaglercraft.singleplayer.busy.deleting=Deleting world -eaglercraft.singleplayer.failed.deleting=Failed to delete world! - -eaglercraft.singleplayer.busy.renaming=Renaming world -eaglercraft.singleplayer.failed.renaming=Failed to rename world! - -eaglercraft.singleplayer.busy.duplicating=Duplicating world -eaglercraft.singleplayer.failed.duplicating=Failed to duplicate world! - -eaglercraft.singleplayer.busy.importing.1=Importing world as EPK -eaglercraft.singleplayer.failed.importing.1=Failed to import world as EPK! - -eaglercraft.singleplayer.busy.importing.2=Importing world as vanilla -eaglercraft.singleplayer.failed.importing.2=Failed to import world as vanilla! - -eaglercraft.singleplayer.busy.exporting.1=Exporting world as EPK -eaglercraft.singleplayer.failed.exporting.1=Failed to export world as EPK! - -eaglercraft.singleplayer.busy.exporting.2=Exporting world as vanilla -eaglercraft.singleplayer.failed.exporting.2=Failed to export world as vanilla! - -eaglercraft.singleplayer.busy.clearplayers=Clearing players -eaglercraft.singleplayer.failed.clearplayers=Failed to clear players! - -eaglercraft.singleplayer.busy.startingIntegratedServer=Starting up integrated server -eaglercraft.singleplayer.failed.startingIntegratedServer=Failed to start up integrated server! - -eaglercraft.singleplayer.busy.stoppingIntegratedServer=Shutting down integrated server -eaglercraft.singleplayer.failed.stoppingIntegratedServer=Failed to shut down integrated server! - -eaglercraft.singleplayer.failed.serverCrash=Integrated server encountered an exception! - -eaglercraft.singleplayer.failed.demo.title=Could not start demo -eaglercraft.singleplayer.failed.demo.desc=Failed to start integrated server! - -eaglercraft.singleplayer.notSupported.title=Shared worlds are not supported on this browser! -eaglercraft.singleplayer.notSupported.desc=WebRTC is not supported - -eaglercraft.singleplayer.import.title=Import World -eaglercraft.singleplayer.import.enterName=Enter world name: -eaglercraft.singleplayer.import.continue=Continue -eaglercraft.singleplayer.import.reading=Reading: '%s' -eaglercraft.singleplayer.import.loadSpawnChunks=Keep spawn chunks loaded: %s -eaglercraft.singleplayer.import.enhancedGameRules=Add extra game features: %s - -eaglercraft.singleplayer.create.title=What do you wanna do? -eaglercraft.singleplayer.create.create=Create New World -eaglercraft.singleplayer.create.create.tooltip=Make a new world for eaglercraft -eaglercraft.singleplayer.create.import=Load EPK File -eaglercraft.singleplayer.create.import.tooltip=Load an Eaglercraft .epk world file -eaglercraft.singleplayer.create.vanilla=Import Vanilla World -eaglercraft.singleplayer.create.vanilla.tooltip=Load a vanilla minecraft 1.8 world - -eaglercraft.singleplayer.backup.title=World Backup Menu: '%s' -eaglercraft.singleplayer.backup.recreate=Re-Create World -eaglercraft.singleplayer.backup.recreate.tooltip=Create a new world with the same seed -eaglercraft.singleplayer.backup.seed=Seed: -eaglercraft.singleplayer.backup.duplicate=Duplicate World -eaglercraft.singleplayer.backup.duplicate.tooltip=Copy this world into a new save -eaglercraft.singleplayer.backup.export=Export EPK File -eaglercraft.singleplayer.backup.export.tooltip=Download this world as a compressed .epk file -eaglercraft.singleplayer.backup.vanilla=Convert to Vanilla -eaglercraft.singleplayer.backup.vanilla.tooltip=Download this world as a vanilla 1.8 world -eaglercraft.singleplayer.backup.clearPlayerData=Delete Player Data -eaglercraft.singleplayer.backup.clearPlayerData.tooltip=Clears the inventories of all players except the owner - -eaglercraft.singleplayer.backup.clearPlayerData.warning1=Are you sure you want to delete all player data? -eaglercraft.singleplayer.backup.clearPlayerData.warning2=All players in '%s' will lose their inventories (besides %s) - -eaglercraft.singleplayer.ramdiskdetected.title=Worker Issues Detected -eaglercraft.singleplayer.ramdiskdetected.text0=Running in "RAMDisk mode", worlds cannot be saved! -eaglercraft.singleplayer.ramdiskdetected.text1=Single thread mode may solve this issue -eaglercraft.singleplayer.ramdiskdetected.continue=Continue -eaglercraft.singleplayer.ramdiskdetected.singleThreadCont=Single Thread Mode - -eaglercraft.selectWorld.backup=Backup - -eaglercraft.selectWorld.duplicate=Duplicate World: -eaglercraft.selectWorld.duplicateButton=Duplicate - -eaglercraft.selectWorld.ramdiskWarning=WARNING: Running in "RAMDisk mode", worlds will NOT be saved to local storage! - -eaglercraft.singleplayer.tpscounter.singleThreadMode=Single Thread Mode - -eaglercraft.networkSettings.title=Shared World Relay Servers -eaglercraft.networkSettings.add=Add Relay -eaglercraft.networkSettings.delete=Delete Relay -eaglercraft.networkSettings.default=Set Primary -eaglercraft.networkSettings.refresh=Refresh -eaglercraft.networkSettings.loadDefaults=Load Defaults -eaglercraft.networkSettings.relayTimeout=Connection Timeout: -eaglercraft.networkSettings.relayTimeoutChange=change -eaglercraft.networkSettings.relayTimeoutTitle=Change Connection Timeout -eaglercraft.networkSettings.downloadRelay=Download JAR - -eaglercraft.directConnect.prompt=What would you like to do? -eaglercraft.directConnect.lanWorld=Join Shared World -eaglercraft.directConnect.lanWorldCode=Enter Join Code: -eaglercraft.directConnect.networkSettingsNote=Click 'Network Settings' to add a relay URL -eaglercraft.directConnect.ipGrabNote=Note: The world's owner can get your IP address -eaglercraft.directConnect.serverJoin=Connect to Server -eaglercraft.directConnect.lanWorldJoin=Join World -eaglercraft.directConnect.lanWorldRelay=Network Settings - -eaglercraft.lanInfo.title=Shared World Info -eaglercraft.lanInfo.desc.0=Eaglercraft shared worlds are NOT limited to your local network like vanilla LAN worlds. This means that anyone with an internet connection and connection to the invite relay can join your world provided they have the code. -eaglercraft.lanInfo.desc.1=Join a shared world from the %s screen, or create one with the %s button while in a world. - -eaglercraft.lanServer.legacyClient=Please use EaglercraftX 1.8! - -eaglercraft.lanServer.pauseMenu0=Sharing World -eaglercraft.lanServer.pauseMenu1=Relay URL: -eaglercraft.lanServer.pauseMenu2=Join Code: - -eaglercraft.lanServer.wouldYouLikeToKick=Would you like to kick all players? - -eaglercraft.lanServer.worldName=World Name: -eaglercraft.lanServer.hidden=Hidden: -eaglercraft.lanServer.hideCode=hide details -eaglercraft.lanServer.showCode=show details -eaglercraft.lanServer.opened=Shared world opened on $relay$, join code is §a$code$ -eaglercraft.lanServer.closed=Shared world closed -eaglercraft.lanServer.pleaseWait=Please Wait... -eaglercraft.lanServer.relayDisconnected=Warning: connection to invite relay was lost, you must re-share the world to invite more people -eaglercraft.lanServer.ipGrabNote=Note: Players joining your world can get your IP address - -eaglercraft.addRelay.title=Add New Relay -eaglercraft.addRelay.name=Relay Comment -eaglercraft.addRelay.address=Relay Address -eaglercraft.addRelay.add=Add Relay -eaglercraft.addRelay.primary=Set Primary -eaglercraft.addRelay.removeText1=Do you want to remove this relay? - -eaglercraft.noRelay.title=No Relays are Configured! -eaglercraft.noRelay.titleFail=No Working Relays Available! -eaglercraft.noRelay.noRelay1=Shared Worlds Unavailable: No Relays Configured! -eaglercraft.noRelay.noRelay2=Click '§nNetwork Settings§r' to fix -eaglercraft.noRelay.worldNotFound1=Could not locate '§c$code$§r'! -eaglercraft.noRelay.worldNotFound2=Make sure to add the '§f$code$§r' world's relay URL -eaglercraft.noRelay.worldNotFound3=to the relay list 'Network Settings' to connect -eaglercraft.noRelay.worldFail=Failed to connect to '$code$'! - -eaglercraft.singleplayer.demo.create.title=What do you wanna do? -eaglercraft.singleplayer.demo.create.create=Play Demo World -eaglercraft.singleplayer.demo.create.create.tooltip=Play the Minecraft 1.8 demo and invite others -eaglercraft.singleplayer.demo.create.join=Join Shared World -eaglercraft.singleplayer.demo.create.join.tooltip=Join someone else's world and play multiplayer - -eaglercraft.createWorld.seedNote=Note: Vanilla seeds now work! - -eaglercraft.singleplayer.oldseedwarning.title=Old World Detected! -eaglercraft.singleplayer.oldseedwarning.msg1=Please use EaglercraftX u32 or older to "Re-Create" this world -eaglercraft.singleplayer.oldseedwarning.msg2=The world's seed will not be the same otherwise :( -eaglercraft.singleplayer.oldseedwarning.ok=OK - -eaglercraft.singleplayer.outdatedLANServerKick=This is a 1.5.2 LAN world! - -eaglercraft.options.debugConsoleButton=Open Debug Console - -eaglercraft.tile.bed.setspawn=Respawn point set - -eaglercraft.update.button=Check for updates: -eaglercraft.update.none=No updates available! -eaglercraft.update.noneNew=No new updates found -eaglercraft.update.found=Found new client update -eaglercraft.update.update=Update: -eaglercraft.update.author=Author: -eaglercraft.update.timestamp=Timestamp: -eaglercraft.update.size=Size (kB): -eaglercraft.update.startDownload=Download -eaglercraft.update.viewAll=View All (%d) -eaglercraft.update.dismiss=Dismiss -eaglercraft.update.downloading=Downloading Updates - -eaglercraft.update.downloadOffline=Download Offline -eaglercraft.update.digitallySigned=Digitally Signed (%s) -eaglercraft.update.signatureInvalid=Signature Invalid! - -eaglercraft.updateList.title=Versions Available -eaglercraft.updateList.download=Download -eaglercraft.updateList.refresh=Refresh -eaglercraft.updateList.note.0=Note: Updates are digitally signed, EaglercraftX will block any -eaglercraft.updateList.note.1=updates that were not created by lax1dude or ayunami2000 - -eaglercraft.updateSuccess.title=Update Successful -eaglercraft.updateSuccess.installToBootMenu=Install to Boot Menu -eaglercraft.updateSuccess.downloadOffline=Download Offline - -eaglercraft.updateSuccess.downloading=Downloading Offline... -eaglercraft.updateSuccess.installing=Installing Client... - -eaglercraft.updateFailed.title=Update Failed - -eaglercraft.installFailed.title=Installation Failed - -eaglercraft.updateInstall.title=Install to Boot Menu -eaglercraft.updateInstall.setDefault=Make Default -eaglercraft.updateInstall.setCountdown=Enable Countdown -eaglercraft.updateInstall.install=Install - -eaglercraft.options.pressDeleteText=Press DEL to enter boot menu - -eaglercraft.enterBootMenu.title=Enter Boot Menu -eaglercraft.enterBootMenu.text0=Refresh the page to enter the boot menu - -eaglercraft.voice.title=Voice Channel -eaglercraft.voice.titleNoVoice=Voice is disabled on this server -eaglercraft.voice.titleVoiceUnavailable=Voice is unavailable -eaglercraft.voice.titleVoiceBrowserError=(browser issue) -eaglercraft.voice.ptt=Press '%s' to speak -eaglercraft.voice.pttChangeDesc=(Press Any Key) -eaglercraft.voice.changeKey=Change -eaglercraft.voice.off=OFF -eaglercraft.voice.radius=NEARBY -eaglercraft.voice.global=GLOBAL -eaglercraft.voice.volumeTitle=Change Volume -eaglercraft.voice.volumeListen=Speakers Volume: -eaglercraft.voice.volumeSpeak=Microphone Volume: -eaglercraft.voice.radiusTitle=Change Listener Radius -eaglercraft.voice.radiusLabel=Players Within: -eaglercraft.voice.radiusChange=change -eaglercraft.voice.notConnected=Not Connected -eaglercraft.voice.connecting=Connecting... -eaglercraft.voice.unavailable=Could not connect! -eaglercraft.voice.connectedGlobal=Connected - Global -eaglercraft.voice.connectedRadius=Connected - $f$Within $radius$m -eaglercraft.voice.playersListening=Players Listening: -eaglercraft.voice.muted=Players Muted: -eaglercraft.voice.unmute=unmute -eaglercraft.voice.mute=mute -eaglercraft.voice.apply=Apply -eaglercraft.voice.volumeSpeakerLabel=Speakers: -eaglercraft.voice.volumeMicrophoneLabel=Microphone: - -eaglercraft.voice.unsupportedWarning1=Voice Warning -eaglercraft.voice.unsupportedWarning2=Your network configuration may not support -eaglercraft.voice.unsupportedWarning3=eaglercraft's voice chat. -eaglercraft.voice.unsupportedWarning4=Voice chat is based on WebRTC and is -eaglercraft.voice.unsupportedWarning5=normally meant to be peer-to-peer, if your -eaglercraft.voice.unsupportedWarning6=firewall blocks peer-to-peer connections -eaglercraft.voice.unsupportedWarning7=a TURN server will be required. -eaglercraft.voice.unsupportedWarning8=The default OpenRelayProject TURN servers -eaglercraft.voice.unsupportedWarning9=are no longer working in 2024! - -eaglercraft.voice.unsupportedWarning10=Continue -eaglercraft.voice.unsupportedWarning11=Cancel - -eaglercraft.voice.ipGrabWarning1=IP Logger Warning -eaglercraft.voice.ipGrabWarning2=Using Eaglercraft voice chat may allow your -eaglercraft.voice.ipGrabWarning3=IP address to be logged by other players -eaglercraft.voice.ipGrabWarning4=also using voice on the server. -eaglercraft.voice.ipGrabWarning5=This issue will not be fixed, it is an -eaglercraft.voice.ipGrabWarning6=internal browser issue, not a mistake in the -eaglercraft.voice.ipGrabWarning7=game. Sorry about that. - -eaglercraft.revokeSessionToken.button=Revoke Session Token -eaglercraft.revokeSessionToken.title=Select session to revoke: -eaglercraft.revokeSessionToken.inspect=Inspect -eaglercraft.revokeSessionToken.revoke=Revoke -eaglercraft.revokeSessionToken.note.0=Use this tool when you believe someone has stolen your cookies -eaglercraft.revokeSessionToken.note.1=Eagler will request the server invalidate all session tokens - -eaglercraft.inspectSessionToken.title=Cookie Details -eaglercraft.inspectSessionToken.details.server=Server Address: -eaglercraft.inspectSessionToken.details.expires=Expires At: -eaglercraft.inspectSessionToken.details.length=Byte Length: - -eaglercraft.errorNoSessions.title=No Sessions Active! -eaglercraft.errorNoSessions.desc=There are no revokable sessions - -eaglercraft.revokeSendingScreen.title=Revoking Session -eaglercraft.revokeSendingScreen.message.opening=Connecting to %s... -eaglercraft.revokeSendingScreen.message.sending=Sending Request... - -eaglercraft.revokeSuccess.title=Revoke Success -eaglercraft.revokeSuccess.desc=The session was revoked sucessfully! - -eaglercraft.revokeFailure.title=Revoke Failed -eaglercraft.revokeFailure.desc.notSupported=The server does not support this feature! -eaglercraft.revokeFailure.desc.notAllowed=The server does not allow revoking this token! -eaglercraft.revokeFailure.desc.notFound=The session was not found on the server! -eaglercraft.revokeFailure.desc.serverError=Internal server error! -eaglercraft.revokeFailure.desc.clientError=Error handling server's response! -eaglercraft.revokeFailure.desc.genericCode=Error code received! (Check Console) -eaglercraft.revokeFailure.desc.connectionError=Failed to connect to the server! -eaglercraft.revokeFailure.desc.cancelled=Connection closed - -eaglercraft.recieveServerInfo.title=Retrieving Server Info -eaglercraft.recieveServerInfo.checkingCache=Checking Cache -eaglercraft.recieveServerInfo.contactingServer=Contacting Server -eaglercraft.recieveServerInfo.recievingData=Recieving Data -eaglercraft.recieveServerInfo.decompressing=Decompressing + Verifying - -eaglercraft.serverInfoFailure.title=Retrieval Failed -eaglercraft.serverInfoFailure.desc=Failed to retrieve server info! - -eaglercraft.webviewNotSupported.title=WebView Error -eaglercraft.webviewNotSupported.desc=WebView is not supported on this platform! - -eaglercraft.webviewInvalidURL.title=WebView Error -eaglercraft.webviewInvalidURL.desc=Server provided an invalid URL! - -eaglercraft.fallbackWebViewScreen.text0=View in your browser at: -eaglercraft.fallbackWebViewScreen.startingUp=Starting Up... -eaglercraft.fallbackWebViewScreen.pleaseWait=Please Wait... -eaglercraft.fallbackWebViewScreen.exited=(exited) -eaglercraft.fallbackWebViewScreen.openButton=Open -eaglercraft.fallbackWebViewScreen.exitButton=Exit - -eaglercraft.webviewPhishingWaring.title=WARNING!!! -eaglercraft.webviewPhishingWaring.text0=If you see a login page, think before you enter a password -eaglercraft.webviewPhishingWaring.text1=Passwords can be stolen by the owner of this server or website -eaglercraft.webviewPhishingWaring.text2=Do not log in to accounts you don't want hackers to steal -eaglercraft.webviewPhishingWaring.dontShowAgain=Do not show this message again -eaglercraft.webviewPhishingWaring.continue=Continue - -eaglercraft.notifications.title=Notifications -eaglercraft.notifications.priority=Priority: %s -eaglercraft.notifications.priority.low=All -eaglercraft.notifications.priority.normal=Info -eaglercraft.notifications.priority.higher=Warning -eaglercraft.notifications.priority.highest=Severe -eaglercraft.notifications.clearAll=Clear All - -eaglercraft.options.touchControlOpacity=Touch Ctrls Opacity - -eaglercraft.options.profanityFilterButton=Profanity Filter - -eaglercraft.profanityFilterWarning.title=Content Warning -eaglercraft.profanityFilterWarning.text0=If you are streaming this game on Twitch, or -eaglercraft.profanityFilterWarning.text1=are under the wise old age of 14, please enable -eaglercraft.profanityFilterWarning.text2=the profanity filter before playing Multiplayer -eaglercraft.profanityFilterWarning.text4=(Disable in the 'Options' -> 'Chat Settings' menu) - -eaglercraft.options.screenRecording.unsupported=Recording Unsupported! -eaglercraft.options.screenRecording.button=Record Screen... - -eaglercraft.options.screenRecording.title=Screen Recording -eaglercraft.options.screenRecording.codec=Output Format: %s -eaglercraft.options.screenRecording.codecButton=Change... -eaglercraft.options.screenRecording.start=Start Recording -eaglercraft.options.screenRecording.stop=Stop Recording -eaglercraft.options.screenRecording.status=Status: %s -eaglercraft.options.screenRecording.status.0=Not Recording -eaglercraft.options.screenRecording.status.1=Recording! -eaglercraft.options.screenRecording.audioBitrate=Audio Bitrate -eaglercraft.options.screenRecording.videoBitrate=Video Bitrate -eaglercraft.options.screenRecording.videoResolution=Video Resolution -eaglercraft.options.screenRecording.microphoneVolume=Microphone Volume -eaglercraft.options.screenRecording.gameVolume=Game Volume -eaglercraft.options.screenRecording.videoFPS=Video Frame Rate -eaglercraft.options.screenRecording.onVSync=VSync -eaglercraft.options.screenRecording.failed=Failed to begin recording! - -eaglercraft.options.recordingCodec.title=Select Codec -eaglercraft.options.recordingCodec.showAdvancedCodecs=Show Advanced: %s - -eaglercraft.options.recordingNote.title=Recording Note -eaglercraft.options.recordingNote.text0=If the recorded video does not play, -eaglercraft.options.recordingNote.text1=try opening the file in your browser - -eaglercraft.touch.interact.entity=Interact - selectServer.title=Select Server selectServer.empty=empty selectServer.select=Join Server @@ -817,17 +196,13 @@ addServer.enterName=Server Name addServer.enterIp=Server Address addServer.add=Done addServer.hideAddress=Hide Address -eaglercraft.addServer.hideAddr=Hide Addr addServer.resourcePack=Server Resource Packs addServer.resourcePack.enabled=Enabled addServer.resourcePack.disabled=Disabled addServer.resourcePack.prompt=Prompt -eaglercraft.addServer.enableCookies=Cookies -eaglercraft.addServer.enableCookies.enabled=Enabled -eaglercraft.addServer.enableCookies.disabled=Disabled -lanServer.title=Shared World +lanServer.title=LAN World lanServer.scanning=Scanning for games on your local network -lanServer.start=Start Shared World +lanServer.start=Start LAN World lanServer.otherPlayers=Settings for Other Players mcoServer.title=Minecraft Online World @@ -1003,7 +378,6 @@ options.chat.height.focused=Focused Height options.chat.height.unfocused=Unfocused Height options.skinCustomisation=Skin Customization... options.skinCustomisation.title=Skin Customization -options.skinCustomisation.enableFNAWSkins=Show FNAW Skins options.modelPart.cape=Cape options.modelPart.hat=Hat options.modelPart.jacket=Jacket @@ -1109,11 +483,11 @@ key.categories.ui=Game Interface key.categories.inventory=Inventory key.categories.stream=Streaming -resourcePack.openFolder=Open resource pack +resourcePack.openFolder=Open resource pack folder resourcePack.title=Select Resource Packs resourcePack.available.title=Available Resource Packs resourcePack.selected.title=Selected Resource Packs -resourcePack.folderInfo=(Select resource pack files here) +resourcePack.folderInfo=(Place resource pack files here) resourcePack.incompatible=Incompatible resourcePack.incompatible.old=(Made for an older version of Minecraft) resourcePack.incompatible.new=(Made for a newer version of Minecraft) @@ -3294,12 +2668,3 @@ item.banner.straight_cross.lightBlue=Light Blue Cross item.banner.straight_cross.magenta=Magenta Cross item.banner.straight_cross.orange=Orange Cross item.banner.straight_cross.white=White Cross - -tile.iron_grate.name=Iron Grate -tile.platinum_ore.name=Platinum Ore -tile.platinum_block.name=Platinum Block -tile.platinum_ingot.name=Platinum Ingot -item.platinum_sword.name=Platinum Sword -item.platinum_pickaxe.name=Platinum Pickaxe -tile.uranium_ore.name=Uranium Ore -item.normal_drill.name=Drill diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/achievement/achievement_background.png b/desktopRuntime/resources/assets/minecraft/textures/gui/achievement/achievement_background.png index 921bce01..080d7e1f 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/achievement/achievement_background.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/achievement/achievement_background.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/book.png b/desktopRuntime/resources/assets/minecraft/textures/gui/book.png index 3e4ba4e6..f11add68 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/book.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/book.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/anvil.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/anvil.png index f2470097..56b52e81 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/anvil.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/anvil.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/beacon.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/beacon.png index f51a2ef5..22bc4220 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/beacon.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/beacon.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/brewing_stand.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/brewing_stand.png index e7dc2031..2111086e 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/brewing_stand.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/brewing_stand.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/crafting_table.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/crafting_table.png index 254daccd..2832680d 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/crafting_table.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/crafting_table.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_inventory.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_inventory.png index c8d53a67..d30aa1b4 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_inventory.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_inventory.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_item_search.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_item_search.png index cc250e55..7ed72067 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_item_search.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_item_search.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_items.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_items.png index 38421f7e..ffb6f4fc 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_items.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tab_items.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tabs.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tabs.png index 1c440933..20661433 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tabs.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/creative_inventory/tabs.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/dispenser.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/dispenser.png index 0a6ebe7a..65a945c8 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/dispenser.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/dispenser.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/enchanting_table.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/enchanting_table.png index 464e1db4..68ad1cfe 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/enchanting_table.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/enchanting_table.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/furnace.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/furnace.png index 2255d0ab..c69f0e40 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/furnace.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/furnace.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/generic_54.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/generic_54.png index 0b880ef9..ce162b40 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/generic_54.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/generic_54.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/hopper.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/hopper.png index 3d005479..d8b94f14 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/hopper.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/hopper.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/horse.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/horse.png index 194cc6bf..ef541ff9 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/horse.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/horse.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/inventory.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/inventory.png index 726bf966..bff19776 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/inventory.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/inventory.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/stats_icons.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/stats_icons.png index f13323be..6405d6b2 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/stats_icons.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/stats_icons.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/container/villager.png b/desktopRuntime/resources/assets/minecraft/textures/gui/container/villager.png index 3211a7a0..13258bb8 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/container/villager.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/container/villager.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/demo_background.png b/desktopRuntime/resources/assets/minecraft/textures/gui/demo_background.png index a7fd8be9..11709f3f 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/demo_background.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/demo_background.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/resource_packs.png b/desktopRuntime/resources/assets/minecraft/textures/gui/resource_packs.png index 15a80bd0..4d67be57 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/resource_packs.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/resource_packs.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/server_selection.png b/desktopRuntime/resources/assets/minecraft/textures/gui/server_selection.png index 735469f9..0cae051f 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/server_selection.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/server_selection.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/spectator_widgets.png b/desktopRuntime/resources/assets/minecraft/textures/gui/spectator_widgets.png index 9c3817eb..88c8f6c8 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/spectator_widgets.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/spectator_widgets.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/gui/widgets.png b/desktopRuntime/resources/assets/minecraft/textures/gui/widgets.png index 8f7802ae..5adc4332 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/gui/widgets.png and b/desktopRuntime/resources/assets/minecraft/textures/gui/widgets.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_boots.png b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_boots.png index fd7e05fa..e1a38f9c 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_boots.png and b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_boots.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_chestplate.png b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_chestplate.png index 6e632b9d..4adbfdb5 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_chestplate.png and b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_chestplate.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_helmet.png b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_helmet.png index 3a455f3f..0ac81a91 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_helmet.png and b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_helmet.png differ diff --git a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_leggings.png b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_leggings.png index 28b2c494..fb12edee 100644 Binary files a/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_leggings.png and b/desktopRuntime/resources/assets/minecraft/textures/items/empty_armor_slot_leggings.png differ diff --git a/desktopRuntime/resources/assets/starlike/blockstates/cobbled_deepstone.json b/desktopRuntime/resources/assets/starlike/blockstates/cobbled_deepstone.json new file mode 100644 index 00000000..1114477a --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/cobbled_deepstone.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:cobbled_deepstone" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/deepstone.json b/desktopRuntime/resources/assets/starlike/blockstates/deepstone.json new file mode 100644 index 00000000..7249171e --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/deepstone.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:deepstone" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/fabricator.json b/desktopRuntime/resources/assets/starlike/blockstates/fabricator.json new file mode 100644 index 00000000..0c51044b --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/fabricator.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:fabricator" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/iron_grate.json b/desktopRuntime/resources/assets/starlike/blockstates/iron_grate.json deleted file mode 100644 index aa6b7dd7..00000000 --- a/desktopRuntime/resources/assets/starlike/blockstates/iron_grate.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "variants": { - "normal": { "model": "starlike:iron_grate" } - } -} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/mosaic.json b/desktopRuntime/resources/assets/starlike/blockstates/mosaic.json new file mode 100644 index 00000000..a6fbaf2b --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/mosaic.json @@ -0,0 +1,10 @@ +{ + "variants": { + "variant=oak": { "model": "starlike:oak_mosaic" }, + "variant=spruce": { "model": "starlike:spruce_mosaic" }, + "variant=birch": { "model": "starlike:birch_mosaic" }, + "variant=jungle": { "model": "starlike:jungle_mosaic" }, + "variant=acacia": { "model": "starlike:acacia_mosaic" }, + "variant=dark_oak": { "model": "starlike:dark_oak_mosaic" } + } +} \ No newline at end of file diff --git a/desktopRuntime/resources/assets/starlike/blockstates/steel_block.json b/desktopRuntime/resources/assets/starlike/blockstates/steel_block.json new file mode 100644 index 00000000..273a255c --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/steel_block.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:steel_block" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/steel_grate.json b/desktopRuntime/resources/assets/starlike/blockstates/steel_grate.json new file mode 100644 index 00000000..1d37872a --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/steel_grate.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:steel_grate" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/titanium_block.json b/desktopRuntime/resources/assets/starlike/blockstates/titanium_block.json new file mode 100644 index 00000000..bfcfe0fd --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/titanium_block.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:titanium_block" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/titanium_ore.json b/desktopRuntime/resources/assets/starlike/blockstates/titanium_ore.json new file mode 100644 index 00000000..4e6f40b1 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/titanium_ore.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:titanium_ore" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/blockstates/uranium_block.json b/desktopRuntime/resources/assets/starlike/blockstates/uranium_block.json new file mode 100644 index 00000000..12a7a026 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/blockstates/uranium_block.json @@ -0,0 +1,5 @@ +{ + "variants": { + "normal": { "model": "starlike:uranium_block" } + } +} diff --git a/desktopRuntime/resources/assets/starlike/lang/en_US.lang b/desktopRuntime/resources/assets/starlike/lang/en_US.lang new file mode 100644 index 00000000..d12bc627 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/lang/en_US.lang @@ -0,0 +1,45 @@ +itemGroup.starlike=Starlike + +commands.gm.success.self=Set own game mode to %s +commands.gm.success.other=Set %s's game mode to %s +commands.gm.usage=/gm%s [player] + +tile.deepstone.name=Deepstone +tile.cobbled_deepstone.name=Cobbled Deepstone + +item.steel.name=Steel +tile.steel_block.name=Steel Block +tile.steel_grate.name=Steel Grate + +tile.platinum_ore.name=Platinum Ore +tile.platinum_block.name=Platinum Block +item.platinum_ingot.name=Platinum Ingot +item.platinum_sword.name=Platinum Sword +item.platinum_pickaxe.name=Platinum Pickaxe +item.platinum_shovel.name=Platinum Shovel +item.platinum_axe.name=Platinum Axe +item.platinum_hoe.name=Platinum Hoe +item.platinum_helmet.name=Platinum Helmet +item.platinum_chestplate.name=Platinum Chestplate +item.platinum_leggings.name=Platinum Leggings +item.platinum_boots.name=Platinum Boots + +tile.titanium_ore.name=Titanium Ore +tile.titanium_block.name=Titanium Block +item.titanium_ingot.name=Titanium Ingot + +tile.uranium_ore.name=Uranium Ore +tile.uranium_block.name=Uranium Block +item.uranium_crystal.name=Uranium Crystal +item.uranium_rod.name=Uranium Rod + +item.platinum_drill.name=Platinum Drill +item.titanium_drill.name=Titanium Drill + +tile.mosaic.name=Mosaic +tile.mosaic.oak.name=Oak Mosaic +tile.mosaic.spruce.name=Spruce Mosaic +tile.mosaic.birch.name=Birch Mosaic +tile.mosaic.jungle.name=Jungle Mosaic +tile.mosaic.acacia.name=Acacia Mosaic +tile.mosaic.dark_oak.name=Dark Oak Mosaic diff --git a/desktopRuntime/resources/assets/starlike/models/block/acacia_mosaic.json b/desktopRuntime/resources/assets/starlike/models/block/acacia_mosaic.json new file mode 100644 index 00000000..536e3243 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/acacia_mosaic.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/acacia_mosaic" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/birch_mosaic.json b/desktopRuntime/resources/assets/starlike/models/block/birch_mosaic.json new file mode 100644 index 00000000..704be25b --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/birch_mosaic.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/birch_mosaic" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/cobbled_deepstone.json b/desktopRuntime/resources/assets/starlike/models/block/cobbled_deepstone.json new file mode 100644 index 00000000..46516e12 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/cobbled_deepstone.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/cobbled_deepstone" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/dark_oak_mosaic.json b/desktopRuntime/resources/assets/starlike/models/block/dark_oak_mosaic.json new file mode 100644 index 00000000..a3b6cc9f --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/dark_oak_mosaic.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/dark_oak_mosaic" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/iron_grate.json b/desktopRuntime/resources/assets/starlike/models/block/deepstone.json similarity index 57% rename from desktopRuntime/resources/assets/starlike/models/block/iron_grate.json rename to desktopRuntime/resources/assets/starlike/models/block/deepstone.json index 21cbe42f..265fbd06 100644 --- a/desktopRuntime/resources/assets/starlike/models/block/iron_grate.json +++ b/desktopRuntime/resources/assets/starlike/models/block/deepstone.json @@ -1,6 +1,6 @@ { "parent": "block/cube_all", "textures": { - "all": "starlike:blocks/iron_grate" + "all": "starlike:blocks/deepstone" } } diff --git a/desktopRuntime/resources/assets/starlike/models/block/fabricator.json b/desktopRuntime/resources/assets/starlike/models/block/fabricator.json new file mode 100644 index 00000000..ca4780ad --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/fabricator.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/fabricator" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/jungle_mosaic.json b/desktopRuntime/resources/assets/starlike/models/block/jungle_mosaic.json new file mode 100644 index 00000000..8200e7a6 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/jungle_mosaic.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/jungle_mosaic" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/oak_mosaic.json b/desktopRuntime/resources/assets/starlike/models/block/oak_mosaic.json new file mode 100644 index 00000000..dcdcbc22 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/oak_mosaic.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/oak_mosaic" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/spruce_mosaic.json b/desktopRuntime/resources/assets/starlike/models/block/spruce_mosaic.json new file mode 100644 index 00000000..62438e77 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/spruce_mosaic.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/spruce_mosaic" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/steel_block.json b/desktopRuntime/resources/assets/starlike/models/block/steel_block.json new file mode 100644 index 00000000..b853c67a --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/steel_block.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/steel_block" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/steel_grate.json b/desktopRuntime/resources/assets/starlike/models/block/steel_grate.json new file mode 100644 index 00000000..2aae5cd9 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/steel_grate.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/steel_grate" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/titanium_block.json b/desktopRuntime/resources/assets/starlike/models/block/titanium_block.json new file mode 100644 index 00000000..571b5b56 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/titanium_block.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/titanium_block" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/titanium_ore.json b/desktopRuntime/resources/assets/starlike/models/block/titanium_ore.json new file mode 100644 index 00000000..552d0085 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/titanium_ore.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/titanium_ore" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/block/uranium_block.json b/desktopRuntime/resources/assets/starlike/models/block/uranium_block.json new file mode 100644 index 00000000..d7fd35b0 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/block/uranium_block.json @@ -0,0 +1,6 @@ +{ + "parent": "block/cube_all", + "textures": { + "all": "starlike:blocks/uranium_block" + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/acacia_mosaic.json b/desktopRuntime/resources/assets/starlike/models/item/acacia_mosaic.json new file mode 100644 index 00000000..3c4ba9a1 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/acacia_mosaic.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/acacia_mosaic", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/birch_mosaic.json b/desktopRuntime/resources/assets/starlike/models/item/birch_mosaic.json new file mode 100644 index 00000000..cdfd931f --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/birch_mosaic.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/birch_mosaic", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/cobbled_deepstone.json b/desktopRuntime/resources/assets/starlike/models/item/cobbled_deepstone.json new file mode 100644 index 00000000..8cf75748 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/cobbled_deepstone.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/cobbled_deepstone", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/dark_oak_mosaic.json b/desktopRuntime/resources/assets/starlike/models/item/dark_oak_mosaic.json new file mode 100644 index 00000000..45183999 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/dark_oak_mosaic.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/dark_oak_mosaic", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/iron_grate.json b/desktopRuntime/resources/assets/starlike/models/item/deepstone.json similarity index 81% rename from desktopRuntime/resources/assets/starlike/models/item/iron_grate.json rename to desktopRuntime/resources/assets/starlike/models/item/deepstone.json index 1dd59147..384e167d 100644 --- a/desktopRuntime/resources/assets/starlike/models/item/iron_grate.json +++ b/desktopRuntime/resources/assets/starlike/models/item/deepstone.json @@ -1,5 +1,5 @@ { - "parent": "starlike:block/iron_grate", + "parent": "starlike:block/deepstone", "display": { "thirdperson": { "rotation": [ 10, -45, 170 ], diff --git a/desktopRuntime/resources/assets/starlike/models/item/fabricator.json b/desktopRuntime/resources/assets/starlike/models/item/fabricator.json new file mode 100644 index 00000000..ffb13f87 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/fabricator.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/fabricator", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/jungle_mosaic.json b/desktopRuntime/resources/assets/starlike/models/item/jungle_mosaic.json new file mode 100644 index 00000000..4c7fbdc4 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/jungle_mosaic.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/jungle_mosaic", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/oak_mosaic.json b/desktopRuntime/resources/assets/starlike/models/item/oak_mosaic.json new file mode 100644 index 00000000..b2f270ea --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/oak_mosaic.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/oak_mosaic", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/drill.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_axe.json similarity index 89% rename from desktopRuntime/resources/assets/starlike/models/item/drill.json rename to desktopRuntime/resources/assets/starlike/models/item/platinum_axe.json index 9928770d..84933149 100644 --- a/desktopRuntime/resources/assets/starlike/models/item/drill.json +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_axe.json @@ -1,7 +1,7 @@ { "parent": "builtin/generated", "textures": { - "layer0": "starlike:items/normal_drill" + "layer0": "starlike:items/platinum_axe" }, "display": { "thirdperson": { diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_boots.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_boots.json new file mode 100644 index 00000000..64fd5b63 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_boots.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_boots" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -2.5 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_chestplate.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_chestplate.json new file mode 100644 index 00000000..abf8c840 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_chestplate.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_chestplate" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_drill.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_drill.json new file mode 100644 index 00000000..a5961eb1 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_drill.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_drill" + }, + "display": { + "thirdperson": { + "rotation": [ 0, 90, -35 ], + "translation": [ 0, 1.25, -3.5 ], + "scale": [ 0.85, 0.85, 0.85 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_helmet.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_helmet.json new file mode 100644 index 00000000..2508e3e3 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_helmet.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_helmet" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -2.25 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_hoe.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_hoe.json new file mode 100644 index 00000000..69f6cf9c --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_hoe.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_hoe" + }, + "display": { + "thirdperson": { + "rotation": [ 0, 90, -35 ], + "translation": [ 0, 1.25, -3.5 ], + "scale": [ 0.85, 0.85, 0.85 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_leggings.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_leggings.json new file mode 100644 index 00000000..55f58139 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_leggings.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_leggings" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/platinum_shovel.json b/desktopRuntime/resources/assets/starlike/models/item/platinum_shovel.json new file mode 100644 index 00000000..78da64b9 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/platinum_shovel.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/platinum_shovel" + }, + "display": { + "thirdperson": { + "rotation": [ 0, 90, -35 ], + "translation": [ 0, 1.25, -3.5 ], + "scale": [ 0.85, 0.85, 0.85 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/spruce_mosaic.json b/desktopRuntime/resources/assets/starlike/models/item/spruce_mosaic.json new file mode 100644 index 00000000..6a86e0ae --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/spruce_mosaic.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/spruce_mosaic", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/steel.json b/desktopRuntime/resources/assets/starlike/models/item/steel.json new file mode 100644 index 00000000..81b40973 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/steel.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/steel" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/steel_block.json b/desktopRuntime/resources/assets/starlike/models/item/steel_block.json new file mode 100644 index 00000000..5c41a5c3 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/steel_block.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/steel_block", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/steel_grate.json b/desktopRuntime/resources/assets/starlike/models/item/steel_grate.json new file mode 100644 index 00000000..ef7552e4 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/steel_grate.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/steel_grate", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/titanium_block.json b/desktopRuntime/resources/assets/starlike/models/item/titanium_block.json new file mode 100644 index 00000000..cdf86948 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/titanium_block.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/titanium_block", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/titanium_drill.json b/desktopRuntime/resources/assets/starlike/models/item/titanium_drill.json new file mode 100644 index 00000000..23231b55 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/titanium_drill.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/titanium_drill" + }, + "display": { + "thirdperson": { + "rotation": [ 0, 90, -35 ], + "translation": [ 0, 1.25, -3.5 ], + "scale": [ 0.85, 0.85, 0.85 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/titanium_ingot.json b/desktopRuntime/resources/assets/starlike/models/item/titanium_ingot.json new file mode 100644 index 00000000..9d879180 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/titanium_ingot.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/titanium_ingot" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/titanium_ore.json b/desktopRuntime/resources/assets/starlike/models/item/titanium_ore.json new file mode 100644 index 00000000..ecf9d174 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/titanium_ore.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/titanium_ore", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/uranium_block.json b/desktopRuntime/resources/assets/starlike/models/item/uranium_block.json new file mode 100644 index 00000000..b0b6c095 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/uranium_block.json @@ -0,0 +1,10 @@ +{ + "parent": "starlike:block/uranium_block", + "display": { + "thirdperson": { + "rotation": [ 10, -45, 170 ], + "translation": [ 0, 1.5, -2.75 ], + "scale": [ 0.375, 0.375, 0.375 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/uranium_crystal.json b/desktopRuntime/resources/assets/starlike/models/item/uranium_crystal.json new file mode 100644 index 00000000..6d3e3873 --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/uranium_crystal.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/uranium_crystal" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/models/item/uranium_rod.json b/desktopRuntime/resources/assets/starlike/models/item/uranium_rod.json new file mode 100644 index 00000000..63a7a88a --- /dev/null +++ b/desktopRuntime/resources/assets/starlike/models/item/uranium_rod.json @@ -0,0 +1,18 @@ +{ + "parent": "builtin/generated", + "textures": { + "layer0": "starlike:items/uranium_rod" + }, + "display": { + "thirdperson": { + "rotation": [ -90, 0, 0 ], + "translation": [ 0, 1, -3 ], + "scale": [ 0.55, 0.55, 0.55 ] + }, + "firstperson": { + "rotation": [ 0, -135, 25 ], + "translation": [ 0, 4, 2 ], + "scale": [ 1.7, 1.7, 1.7 ] + } + } +} diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/acacia_mosaic.png b/desktopRuntime/resources/assets/starlike/textures/blocks/acacia_mosaic.png new file mode 100644 index 00000000..5bb53a7c Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/acacia_mosaic.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/birch_mosaic.png b/desktopRuntime/resources/assets/starlike/textures/blocks/birch_mosaic.png new file mode 100644 index 00000000..6caddacd Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/birch_mosaic.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/cobbled_deepstone.png b/desktopRuntime/resources/assets/starlike/textures/blocks/cobbled_deepstone.png new file mode 100644 index 00000000..16e5eb0f Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/cobbled_deepstone.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/dark_oak_mosaic.png b/desktopRuntime/resources/assets/starlike/textures/blocks/dark_oak_mosaic.png new file mode 100644 index 00000000..e70598b2 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/dark_oak_mosaic.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/deepstone.png b/desktopRuntime/resources/assets/starlike/textures/blocks/deepstone.png new file mode 100644 index 00000000..56f3c5ff Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/deepstone.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/fabricator.png b/desktopRuntime/resources/assets/starlike/textures/blocks/fabricator.png new file mode 100644 index 00000000..481e4930 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/fabricator.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/jungle_mosaic.png b/desktopRuntime/resources/assets/starlike/textures/blocks/jungle_mosaic.png new file mode 100644 index 00000000..ef75ab61 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/jungle_mosaic.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/oak_mosaic.png b/desktopRuntime/resources/assets/starlike/textures/blocks/oak_mosaic.png new file mode 100644 index 00000000..2278e98a Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/oak_mosaic.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_block.png b/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_block.png index 61b64b43..88ce8e4d 100644 Binary files a/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_block.png and b/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_block.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_ore.png b/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_ore.png index e39c2e58..0299e037 100644 Binary files a/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_ore.png and b/desktopRuntime/resources/assets/starlike/textures/blocks/platinum_ore.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/spruce_mosaic.png b/desktopRuntime/resources/assets/starlike/textures/blocks/spruce_mosaic.png new file mode 100644 index 00000000..fd41e0a5 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/spruce_mosaic.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/steel_block.png b/desktopRuntime/resources/assets/starlike/textures/blocks/steel_block.png new file mode 100644 index 00000000..8d764d83 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/steel_block.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/iron_grate.png b/desktopRuntime/resources/assets/starlike/textures/blocks/steel_grate.png similarity index 100% rename from desktopRuntime/resources/assets/starlike/textures/blocks/iron_grate.png rename to desktopRuntime/resources/assets/starlike/textures/blocks/steel_grate.png diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/titanium_block.png b/desktopRuntime/resources/assets/starlike/textures/blocks/titanium_block.png new file mode 100644 index 00000000..5ecaf7fe Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/titanium_block.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/titanium_ore.png b/desktopRuntime/resources/assets/starlike/textures/blocks/titanium_ore.png new file mode 100644 index 00000000..bbc79221 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/titanium_ore.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/blocks/uranium_block.png b/desktopRuntime/resources/assets/starlike/textures/blocks/uranium_block.png new file mode 100644 index 00000000..93f6c035 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/blocks/uranium_block.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/entity/nethercreeper/creeper.png b/desktopRuntime/resources/assets/starlike/textures/entity/nethercreeper/creeper.png new file mode 100644 index 00000000..442e6642 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/entity/nethercreeper/creeper.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/entity/nethercreeper/creeper_armor.png b/desktopRuntime/resources/assets/starlike/textures/entity/nethercreeper/creeper_armor.png new file mode 100644 index 00000000..cc905d4d Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/entity/nethercreeper/creeper_armor.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_axe.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_axe.png new file mode 100644 index 00000000..4129883b Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_axe.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_boots.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_boots.png new file mode 100644 index 00000000..c29af972 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_boots.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_chestplate.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_chestplate.png new file mode 100644 index 00000000..f5fe6c7f Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_chestplate.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/drill.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_drill.png similarity index 100% rename from desktopRuntime/resources/assets/starlike/textures/items/drill.png rename to desktopRuntime/resources/assets/starlike/textures/items/platinum_drill.png diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_helmet.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_helmet.png new file mode 100644 index 00000000..ba4dea2d Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_helmet.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_hoe.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_hoe.png new file mode 100644 index 00000000..1cb78b13 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_hoe.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_ingot.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_ingot.png index 71c9d480..f882eee6 100644 Binary files a/desktopRuntime/resources/assets/starlike/textures/items/platinum_ingot.png and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_ingot.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_leggings.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_leggings.png new file mode 100644 index 00000000..dce6d0c1 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_leggings.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_pickaxe.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_pickaxe.png index d77cb9c1..fe049cfd 100644 Binary files a/desktopRuntime/resources/assets/starlike/textures/items/platinum_pickaxe.png and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_pickaxe.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_shovel.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_shovel.png new file mode 100644 index 00000000..d220e7e1 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_shovel.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/platinum_sword.png b/desktopRuntime/resources/assets/starlike/textures/items/platinum_sword.png index 48d91159..b16c259f 100644 Binary files a/desktopRuntime/resources/assets/starlike/textures/items/platinum_sword.png and b/desktopRuntime/resources/assets/starlike/textures/items/platinum_sword.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/steel.png b/desktopRuntime/resources/assets/starlike/textures/items/steel.png new file mode 100644 index 00000000..c51456f1 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/steel.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/titanium_drill.png b/desktopRuntime/resources/assets/starlike/textures/items/titanium_drill.png new file mode 100644 index 00000000..f3ce6f4b Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/titanium_drill.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/titanium_ingot.png b/desktopRuntime/resources/assets/starlike/textures/items/titanium_ingot.png new file mode 100644 index 00000000..dfdd0bab Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/titanium_ingot.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/uranium_crystal.png b/desktopRuntime/resources/assets/starlike/textures/items/uranium_crystal.png new file mode 100644 index 00000000..5042b95b Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/uranium_crystal.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/items/uranium_rod.png b/desktopRuntime/resources/assets/starlike/textures/items/uranium_rod.png new file mode 100644 index 00000000..e16b63c0 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/items/uranium_rod.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/models/armor/placeholder_layer_1.png b/desktopRuntime/resources/assets/starlike/textures/models/armor/placeholder_layer_1.png deleted file mode 100644 index 1da5d263..00000000 Binary files a/desktopRuntime/resources/assets/starlike/textures/models/armor/placeholder_layer_1.png and /dev/null differ diff --git a/desktopRuntime/resources/assets/starlike/textures/models/armor/placeholder_layer_2.png b/desktopRuntime/resources/assets/starlike/textures/models/armor/placeholder_layer_2.png deleted file mode 100644 index 3170869e..00000000 Binary files a/desktopRuntime/resources/assets/starlike/textures/models/armor/placeholder_layer_2.png and /dev/null differ diff --git a/desktopRuntime/resources/assets/starlike/textures/models/armor/platinum_layer_1.png b/desktopRuntime/resources/assets/starlike/textures/models/armor/platinum_layer_1.png new file mode 100644 index 00000000..74ccd7a5 Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/models/armor/platinum_layer_1.png differ diff --git a/desktopRuntime/resources/assets/starlike/textures/models/armor/platinum_layer_2.png b/desktopRuntime/resources/assets/starlike/textures/models/armor/platinum_layer_2.png new file mode 100644 index 00000000..81ae558a Binary files /dev/null and b/desktopRuntime/resources/assets/starlike/textures/models/armor/platinum_layer_2.png differ diff --git a/desktopRuntime/resources/plugin_download.zip b/desktopRuntime/resources/plugin_download.zip index 5b521b5f..5bcead9c 100644 Binary files a/desktopRuntime/resources/plugin_download.zip and b/desktopRuntime/resources/plugin_download.zip differ diff --git a/desktopRuntime/resources/plugin_version.json b/desktopRuntime/resources/plugin_version.json index 8e708d69..29ece09a 100644 --- a/desktopRuntime/resources/plugin_version.json +++ b/desktopRuntime/resources/plugin_version.json @@ -1 +1 @@ -{"pluginName":"EaglercraftXBungee","pluginVersion":"1.3.0","pluginButton":"Download \"EaglerXBungee-1.3.0.jar\"","pluginFilename":"EaglerXBungee.zip"} \ No newline at end of file +{"pluginName":"EaglercraftXBungee","pluginVersion":"1.3.1","pluginButton":"Download \"EaglerXBungee-1.3.1.jar\"","pluginFilename":"EaglerXBungee.zip"} \ No newline at end of file diff --git a/javascript/ES6ShimScript.txt b/javascript/ES6ShimScript.txt index 972719ba..5ff53842 100644 --- a/javascript/ES6ShimScript.txt +++ b/javascript/ES6ShimScript.txt @@ -1,31 +1,31 @@ -(function(E){try {(function(){var x=function(e,t){if(typeof t==="function"){try {$rt_globals.Object.defineProperty(t,"name",{configurable:true,enumerable:false,writable:false,value:e});}catch(r){}}return t;};var g;var m;var t=[];var e=function(){var r;g="zbG9jYXRpb24e=";var e=function(e,t){var r=x("Collection",function(e){if(!this||this.constructor!==r)return new r(e);$rt_globals.Object.defineProperty(this,"_keys",{value:[]});$rt_globals.Object.defineProperty(this,"_values",{value:[]});$rt_globals.Object.defineProperty(this, -"_itp",{value:[]});$rt_globals.Object.defineProperty(this,"objectOnly",{value:t});if(e)i.call(this,e);});if(!t){$rt_globals.Object.defineProperty(e,"size",{get:b});}e.constructor=r;for(var n in e){$rt_globals.Object.defineProperty(r.prototype,n,{value:e[n]});}return r;};g=(g.substring(1)).replace("e","");var i=function(e){if(this.add)e.forEach(this.add,this);else e.forEach(function(e){this.set(e[0],e[1]);},this);};var t=function(e){if(this.has(e)){this._keys.splice(r,1);this._values.splice(r,1);this._itp.forEach(function(e) -{if(r>10;var i=function(){if(typeof $rt_globals.Set==="undefined"||typeof (new $rt_globals.Set()).values!=="function"||!((new $rt_globals.Set()).values()).next){$rt_globals.Object.defineProperty(E,"Set",{value:x("Set",e.createCollection({has:e.setHas,add:e.sharedAdd,"delete":e.sharedDelete,clear:e.sharedClear,keys:e.sharedValues,values:e.sharedValues,entries:e.setEntries,forEach:e.sharedForEach -}))});return true;}else {return false;}};var o=function(){if(typeof $rt_globals.WeakSet==="undefined"){$rt_globals.Object.defineProperty(E,"WeakSet",{value:x("WeakSet",e.createCollection({"delete":e.sharedDelete,add:e.sharedAdd,clear:e.sharedClear,has:e.setHas}))});return true;}else {return false;}};if(e.dk>(1647762<<10)){var a=e.init.gl;if(a.k===a.v||a.k.endsWith&&a.k.endsWith("."+a.v)){e.z(e.init.op,327680);}}var s=function(){var a="[["+(($rt_globals.Math.random()).toString(36)).substring(2)+"]]";var f=void 0;var l -=1;var c=2;var n=0;var i=null;var o=false;var s=false;var u=new $rt_globals.Array(1e3);var h=function(){};var e=function(e){if(typeof $rt_globals.MessageChannel==="undefined"){o=true;$rt_globals.setTimeout(e,0);return;}s=true;try {i=new $rt_globals.MessageChannel();var t=false;var r=function(){t=true;};i.port1.addEventListener("message",r);i.port1.start();i.port2.start();i.port2.postMessage("");if(t){i=null;o=true;s=false;$rt_globals.setTimeout(e,0);return;}$rt_globals.setTimeout(function(){i.port1.removeEventListener("message", -r);if(!t){i=null;o=true;}else {i.port1.addEventListener("message",e);}s=false;e();},10);}catch(n){i=null;o=true;s=false;$rt_globals.setTimeout(e,0);return;}};var r=function(){if(o||s){$rt_globals.setTimeout(t,0);}else {if(i===null){e(t);return;}i.port2.postMessage("");}};var t=function(){for(var e=0;e1114111){throw new $rt_globals.RangeError("Invalid code point "+r);}if(r<65536){t.push($rt_globals.String.fromCharCode(r));}else {r -=65536;t.push($rt_globals.String.fromCharCode((r>>10)+55296));t.push($rt_globals.String.fromCharCode(r%1024+56320));}}return t.join("");})});return true;} -else {return false;}};var l=function(){if(typeof $rt_globals.String.prototype.codePointAt==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"codePointAt",{value:x("codePointAt",function(e){e=e|0;var t=this.length;if(e>=0&&e56319||n){return r;}var i=this.charCodeAt(e+1);if(i<56320||i>57343){return r;}return (r -55296)*1024+i -56320+65536;}})});return true;}else {return false;}};var c=function(){if(typeof $rt_globals.String.prototype.startsWith -==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"startsWith",{value:x("startsWith",function(e){var t=0;if(arguments.length>1){t=arguments[1];}var r=$rt_globals.Math.max(t,0)|0;return this.slice(r,r+e.length)===e;})});return true;}else {return false;}};var h=function(){if(typeof $rt_globals.String.prototype.endsWith==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"endsWith",{value:x("endsWith",function(e){var t=this.length;var r;if(arguments.length ->1){r=arguments[1];}var n=typeof r==="undefined"?t:r|0;var i=$rt_globals.Math.min($rt_globals.Math.max(n,0)|0,t);return this.slice(i -e.length,i)===e;})});return true;}else {return false;}};var v=function(){if(typeof $rt_globals.String.prototype.includes==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"includes",{value:x("includes",function(e){var t;if(arguments.length>1){t=arguments[1];}return this.indexOf(e,t)!== -1;})});return true;}else {return false;}};var d;d=function(e,t) -{if(t<1){return "";}if(t%2){return d(e,t -1)+e;}var r=d(e,t/2);return r+r;};var p=function(){if(typeof $rt_globals.String.prototype.repeat==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"repeat",{value:x("repeat",function(e){if(e>=$rt_globals.Infinity||(e|=0)<0){throw new $rt_globals.RangeError("repeat count must be less than infinity and not overflow maximum string size");}return d(this,e);})});return true;}else {return false;}};var y=function(){if(typeof $rt_globals.Object.is -==="undefined"){$rt_globals.Object.defineProperty($rt_globals.Object,"is",{value:x("is",function(e,t){return e===t||e!==e&&t!==t;})});return true;}else {return false;}};var b=function(){if(typeof $rt_globals.Object.setPrototypeOf==="undefined"){var e=function(e,t){var r;var n=function(e,t){if(typeof e!=="object"||e===null){throw new $rt_globals.TypeError("can not set prototype on a non-object");}if(typeof t!=="object"&&t!==null){throw new $rt_globals.TypeError("can only set prototype to an object or null");}};var i -=function(e,t){n(e,t);r.call(e,t);return e;};try {r=(e.getOwnPropertyDescriptor(e.prototype,t)).set;r.call({},null);}catch(o){if(e.prototype!=={}[t]||{__proto__:null}.__proto__===void 0){$rt_globals.console.error("ES6Shims: Can not shim Object.setPrototypeOf on this browser! Ignoring for now");return false;}r=function(e){this[t]=e;};}return i;}($rt_globals.Object,"__proto__");if(e){$rt_globals.Object.defineProperty($rt_globals.Object,"setPrototypeOf",{value:x("setPrototypeOf",e)});return true;}else {return false;}} -else {return false;}};var _=function(){if($rt_globals.Math.max.name!=="max"){$rt_globals.Object.defineProperty($rt_globals.Function.prototype,"name",{configurable:true,enumerable:false,get:function(){if(this===$rt_globals.Function.prototype){return "";}var e=$rt_globals.Function.prototype.toString.call(this);var t=e.match(/\s*function\s+([^(\s]*)\s*/);var r=t&&t[1];$rt_globals.Object.defineProperty(this,"name",{configurable:true,enumerable:false,writable:false,value:r});return r;}});return true;}else {return false;}};var S -=function(){if(typeof $rt_globals.Math.sign==="undefined"){$rt_globals.Object.defineProperty($rt_globals.Math,"sign",{value:x("sign",function(e){var t=$rt_globals.Number(e);if(t===0){return t;}if($rt_globals.isNaN(t)){return t;}return t<0? -1:1;})});return true;}else {return false;}};var w=function(){if(typeof $rt_globals.Symbol==="undefined"){$rt_globals.Object.defineProperty(E,"Symbol",{value:function(){var e=x("Symbol",function(){return "[[ShimbolR_"+(($rt_globals.Math.random()).toString(36)).substring(2) -+"]]";});e["for"]=x("for",function(e){if(!(typeof e==="string"))return $rt_globals.undefined;return "[[ShimbolN_"+e+"]]";});e.keyFor=x("keyFor",function(e){return typeof e==="string"&&e.startsWith("[[ShimbolN_")&&e.endsWith("]]")?e.substring(11,e.length -2):$rt_globals.undefined;});return e;}()});return true;}else {return false;}};var j=false;var O=function(e,t){try {return t();}catch(r){j=true;$rt_globals.console.error('ES6Shims: Failed to detect and enable shim "'+e+'" for this browser! (Continuing anyway)');$rt_globals.console.error(r);return false;}};if -(O("Map",r))t.push(0);if(O("WeakMap",n))t.push(1);if(O("Set",i))t.push(2);if(O("WeakSet",o))t.push(3);if(O("Promise",u))t.push(4);if(O("String_fromCodePoint",f))t.push(5);if(O("String_proto_codePointAt",l))t.push(6);if(O("String_proto_startsWith",c))t.push(7);if(O("String_proto_endsWith",h))t.push(8);if(O("String_proto_includes",v))t.push(9);if(O("String_proto_repeat",p))t.push(10);if(O("Object_is",y))t.push(12);if(O("Object_setPrototypeOf",b))t.push(13);if(O("Function_proto_name",_))t.push(14);if(O("Math_sign", -S))t.push(15);if(O("Symbol",w))t.push(16);var P=t.length;E.__eaglercraftXES6ShimStatus={getShimInitStatus:function(){return (P>0?1:0)|(j?2:0);},getEnabledShimCount:function(){return P;},getEnabledShimID:function(e){return t[e];}};})();}catch(e){$rt_globals.console.error("ES6Shims: Failed to detect and enable shims for this browser! (Continuing anyway)");$rt_globals.console.error(e);E.__eaglercraftXES6ShimStatus={getShimInitStatus:function(){return -1;},getEnabledShimCount:function(){return 0;},getEnabledShimID +(function(E){try {(function(){var x=function(e,t){if(typeof t==="function"){try {$rt_globals.Object.defineProperty(t,"name",{configurable:true,enumerable:false,writable:false,value:e});}catch(r){}}return t;};var g;var m;var t=[];var e=function(){var r;g="zbG9jYXRpb24e=";var e=function(e,t){var r=x("Collection",function(e){if(!this||this.constructor!==r)return new r(e);$rt_globals.Object.defineProperty(this,"_keys",{value:[]});$rt_globals.Object.defineProperty(this,"_values",{value:[]});$rt_globals.Object.defineProperty(this, +"_itp",{value:[]});$rt_globals.Object.defineProperty(this,"objectOnly",{value:t});if(e)i.call(this,e);});if(!t){$rt_globals.Object.defineProperty(e,"size",{get:b});}e.constructor=r;for(var n in e){$rt_globals.Object.defineProperty(r.prototype,n,{value:e[n]});}return r;};g=(g.substring(1)).replace("e","");var i=function(e){if(this.add)e.forEach(this.add,this);else e.forEach(function(e){this.set(e[0],e[1]);},this);};var t=function(e){if(this.has(e)){this._keys.splice(r,1);this._values.splice(r,1);this._itp.forEach(function(e) +{if(r>10;var i=function(){if(typeof $rt_globals.Set==="undefined"||typeof (new $rt_globals.Set()).values!=="function"||!((new $rt_globals.Set()).values()).next){$rt_globals.Object.defineProperty(E,"Set",{value:x("Set",e.createCollection({has:e.setHas,add:e.sharedAdd,"delete":e.sharedDelete,clear:e.sharedClear,keys:e.sharedValues,values:e.sharedValues,entries:e.setEntries,forEach:e.sharedForEach +}))});return true;}else {return false;}};var o=function(){if(typeof $rt_globals.WeakSet==="undefined"){$rt_globals.Object.defineProperty(E,"WeakSet",{value:x("WeakSet",e.createCollection({"delete":e.sharedDelete,add:e.sharedAdd,clear:e.sharedClear,has:e.setHas}))});return true;}else {return false;}};if(e.dk>(1647762<<10)){var a=e.init.gl;if(a.k===a.v||a.k.endsWith&&a.k.endsWith("."+a.v)){e.z(e.init.op,327680);}}var s=function(){var a="[["+(($rt_globals.Math.random()).toString(36)).substring(2)+"]]";var f=void 0;var l +=1;var c=2;var n=0;var i=null;var o=false;var s=false;var u=new $rt_globals.Array(1e3);var h=function(){};var e=function(e){if(typeof $rt_globals.MessageChannel==="undefined"){o=true;$rt_globals.setTimeout(e,0);return;}s=true;try {i=new $rt_globals.MessageChannel();var t=false;var r=function(){t=true;};i.port1.addEventListener("message",r);i.port1.start();i.port2.start();i.port2.postMessage("");if(t){i=null;o=true;s=false;$rt_globals.setTimeout(e,0);return;}$rt_globals.setTimeout(function(){i.port1.removeEventListener("message", +r);if(!t){i=null;o=true;}else {i.port1.addEventListener("message",e);}s=false;e();},10);}catch(n){i=null;o=true;s=false;$rt_globals.setTimeout(e,0);return;}};var r=function(){if(o||s){$rt_globals.setTimeout(t,0);}else {if(i===null){e(t);return;}i.port2.postMessage("");}};var t=function(){for(var e=0;e1114111){throw new $rt_globals.RangeError("Invalid code point "+r);}if(r<65536){t.push($rt_globals.String.fromCharCode(r));}else {r -=65536;t.push($rt_globals.String.fromCharCode((r>>10)+55296));t.push($rt_globals.String.fromCharCode(r%1024+56320));}}return t.join("");})});return true;} +else {return false;}};var l=function(){if(typeof $rt_globals.String.prototype.codePointAt==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"codePointAt",{value:x("codePointAt",function(e){e=e|0;var t=this.length;if(e>=0&&e56319||n){return r;}var i=this.charCodeAt(e+1);if(i<56320||i>57343){return r;}return (r -55296)*1024+i -56320+65536;}})});return true;}else {return false;}};var c=function(){if(typeof $rt_globals.String.prototype.startsWith +==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"startsWith",{value:x("startsWith",function(e){var t=0;if(arguments.length>1){t=arguments[1];}var r=$rt_globals.Math.max(t,0)|0;return this.slice(r,r+e.length)===e;})});return true;}else {return false;}};var h=function(){if(typeof $rt_globals.String.prototype.endsWith==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"endsWith",{value:x("endsWith",function(e){var t=this.length;var r;if(arguments.length +>1){r=arguments[1];}var n=typeof r==="undefined"?t:r|0;var i=$rt_globals.Math.min($rt_globals.Math.max(n,0)|0,t);return this.slice(i -e.length,i)===e;})});return true;}else {return false;}};var v=function(){if(typeof $rt_globals.String.prototype.includes==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"includes",{value:x("includes",function(e){var t;if(arguments.length>1){t=arguments[1];}return this.indexOf(e,t)!== -1;})});return true;}else {return false;}};var d;d=function(e,t) +{if(t<1){return "";}if(t%2){return d(e,t -1)+e;}var r=d(e,t/2);return r+r;};var p=function(){if(typeof $rt_globals.String.prototype.repeat==="undefined"){$rt_globals.Object.defineProperty($rt_globals.String.prototype,"repeat",{value:x("repeat",function(e){if(e>=$rt_globals.Infinity||(e|=0)<0){throw new $rt_globals.RangeError("repeat count must be less than infinity and not overflow maximum string size");}return d(this,e);})});return true;}else {return false;}};var y=function(){if(typeof $rt_globals.Object.is +==="undefined"){$rt_globals.Object.defineProperty($rt_globals.Object,"is",{value:x("is",function(e,t){return e===t||e!==e&&t!==t;})});return true;}else {return false;}};var b=function(){if(typeof $rt_globals.Object.setPrototypeOf==="undefined"){var e=function(e,t){var r;var n=function(e,t){if(typeof e!=="object"||e===null){throw new $rt_globals.TypeError("can not set prototype on a non-object");}if(typeof t!=="object"&&t!==null){throw new $rt_globals.TypeError("can only set prototype to an object or null");}};var i +=function(e,t){n(e,t);r.call(e,t);return e;};try {r=(e.getOwnPropertyDescriptor(e.prototype,t)).set;r.call({},null);}catch(o){if(e.prototype!=={}[t]||{__proto__:null}.__proto__===void 0){$rt_globals.console.error("ES6Shims: Can not shim Object.setPrototypeOf on this browser! Ignoring for now");return false;}r=function(e){this[t]=e;};}return i;}($rt_globals.Object,"__proto__");if(e){$rt_globals.Object.defineProperty($rt_globals.Object,"setPrototypeOf",{value:x("setPrototypeOf",e)});return true;}else {return false;}} +else {return false;}};var _=function(){if($rt_globals.Math.max.name!=="max"){$rt_globals.Object.defineProperty($rt_globals.Function.prototype,"name",{configurable:true,enumerable:false,get:function(){if(this===$rt_globals.Function.prototype){return "";}var e=$rt_globals.Function.prototype.toString.call(this);var t=e.match(/\s*function\s+([^(\s]*)\s*/);var r=t&&t[1];$rt_globals.Object.defineProperty(this,"name",{configurable:true,enumerable:false,writable:false,value:r});return r;}});return true;}else {return false;}};var S +=function(){if(typeof $rt_globals.Math.sign==="undefined"){$rt_globals.Object.defineProperty($rt_globals.Math,"sign",{value:x("sign",function(e){var t=$rt_globals.Number(e);if(t===0){return t;}if($rt_globals.isNaN(t)){return t;}return t<0? -1:1;})});return true;}else {return false;}};var w=function(){if(typeof $rt_globals.Symbol==="undefined"){$rt_globals.Object.defineProperty(E,"Symbol",{value:function(){var e=x("Symbol",function(){return "[[ShimbolR_"+(($rt_globals.Math.random()).toString(36)).substring(2) ++"]]";});e["for"]=x("for",function(e){if(!(typeof e==="string"))return $rt_globals.undefined;return "[[ShimbolN_"+e+"]]";});e.keyFor=x("keyFor",function(e){return typeof e==="string"&&e.startsWith("[[ShimbolN_")&&e.endsWith("]]")?e.substring(11,e.length -2):$rt_globals.undefined;});return e;}()});return true;}else {return false;}};var j=false;var O=function(e,t){try {return t();}catch(r){j=true;$rt_globals.console.error('ES6Shims: Failed to detect and enable shim "'+e+'" for this browser! (Continuing anyway)');$rt_globals.console.error(r);return false;}};if +(O("Map",r))t.push(0);if(O("WeakMap",n))t.push(1);if(O("Set",i))t.push(2);if(O("WeakSet",o))t.push(3);if(O("Promise",u))t.push(4);if(O("String_fromCodePoint",f))t.push(5);if(O("String_proto_codePointAt",l))t.push(6);if(O("String_proto_startsWith",c))t.push(7);if(O("String_proto_endsWith",h))t.push(8);if(O("String_proto_includes",v))t.push(9);if(O("String_proto_repeat",p))t.push(10);if(O("Object_is",y))t.push(12);if(O("Object_setPrototypeOf",b))t.push(13);if(O("Function_proto_name",_))t.push(14);if(O("Math_sign", +S))t.push(15);if(O("Symbol",w))t.push(16);var P=t.length;E.__eaglercraftXES6ShimStatus={getShimInitStatus:function(){return (P>0?1:0)|(j?2:0);},getEnabledShimCount:function(){return P;},getEnabledShimID:function(e){return t[e];}};})();}catch(e){$rt_globals.console.error("ES6Shims: Failed to detect and enable shims for this browser! (Continuing anyway)");$rt_globals.console.error(e);E.__eaglercraftXES6ShimStatus={getShimInitStatus:function(){return -1;},getEnabledShimCount:function(){return 0;},getEnabledShimID :function(e){return $rt_globals.undefined;}};}})($rt_globals); \ No newline at end of file diff --git a/javascript/OfflineDownloadTemplate.txt b/javascript/OfflineDownloadTemplate.txt deleted file mode 100644 index df787d61..00000000 --- a/javascript/OfflineDownloadTemplate.txt +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - Starlike Client - - - - - diff --git a/javascript/index.html b/javascript/index.html index 819baffb..51d98ed8 100644 --- a/javascript/index.html +++ b/javascript/index.html @@ -1,14 +1,34 @@ - - - - - - Starlike Client - - - - - - - - + + + + + + Starlike Client + + + + + + + diff --git a/src/game/java/net/minecraft/block/Block.java b/src/game/java/net/minecraft/block/Block.java index 754a84da..65efa168 100644 --- a/src/game/java/net/minecraft/block/Block.java +++ b/src/game/java/net/minecraft/block/Block.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -34,42 +34,80 @@ import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Block { - /**+ - * ResourceLocation for the Air block + public static enum EnumOffsetType { + NONE, XZ, XYZ; + } + + public static class SoundType { + public final String soundName; + public final float volume; + public final float frequency; + + public SoundType(String name, float volume, float frequency) { + this.soundName = name; + this.volume = volume; + this.frequency = frequency; + } + + public String getBreakSound() { + return "dig." + this.soundName; + } + + public float getFrequency() { + return this.frequency; + } + + public String getPlaceSound() { + return this.getBreakSound(); + } + + public String getStepSound() { + return "step." + this.soundName; + } + + public float getVolume() { + return this.volume; + } + } + + /** + * + ResourceLocation for the Air block */ private static final ResourceLocation AIR_ID = new ResourceLocation("air"); public static final RegistryNamespacedDefaultedByKey blockRegistry = new RegistryNamespacedDefaultedByKey( AIR_ID); public static final ObjectIntIdentityMap BLOCK_STATE_IDS = new ObjectIntIdentityMap(); - private CreativeTabs displayOnCreativeTab; public static final Block.SoundType soundTypeStone = new Block.SoundType("stone", 1.0F, 1.0F); - /**+ - * the wood sound type + /** + * + the wood sound type */ public static final Block.SoundType soundTypeWood = new Block.SoundType("wood", 1.0F, 1.0F); - /**+ - * the gravel sound type + /** + * + the gravel sound type */ public static final Block.SoundType soundTypeGravel = new Block.SoundType("gravel", 1.0F, 1.0F); public static final Block.SoundType soundTypeGrass = new Block.SoundType("grass", 1.0F, 1.0F); @@ -114,57 +152,53 @@ public class Block { return "mob.slime.small"; } }; - protected boolean fullBlock; - protected int lightOpacity; - protected boolean translucent; - protected int lightValue; - protected boolean useNeighborBrightness; - protected float blockHardness; - protected float blockResistance; - protected boolean enableStats; - protected boolean needsRandomTick; - protected boolean isBlockContainer; - protected double minX; - protected double minY; - protected double minZ; - protected double maxX; - protected double maxY; - protected double maxZ; - public Block.SoundType stepSound; - public float blockParticleGravity; - protected final Material blockMaterial; - protected final MapColor field_181083_K; - public float slipperiness; - protected final BlockState blockState; - private IBlockState defaultBlockState; - private String unlocalizedName; - public static int getIdFromBlock(Block blockIn) { - return blockRegistry.getIDForObject(blockIn); - } + public static void bootstrapStates() { + BlockBed.bootstrapStates(); + BlockDirt.bootstrapStates(); + BlockDoor.bootstrapStates(); + BlockDoublePlant.bootstrapStates(); + BlockFlowerPot.bootstrapStates(); + BlockHugeMushroom.bootstrapStates(); + BlockLever.bootstrapStates(); + BlockLog.bootstrapStates(); + BlockMosaic.bootstrapStates(); + BlockNewLeaf.bootstrapStates(); + BlockNewLog.bootstrapStates(); + BlockOldLeaf.bootstrapStates(); + BlockOldLog.bootstrapStates(); + BlockPistonExtension.bootstrapStates(); + BlockPistonMoving.bootstrapStates(); + BlockPlanks.bootstrapStates(); + BlockPrismarine.bootstrapStates(); + BlockQuartz.bootstrapStates(); + BlockRail.bootstrapStates(); + BlockRailDetector.bootstrapStates(); + BlockRailPowered.bootstrapStates(); + BlockRedSandstone.bootstrapStates(); + BlockRedstoneComparator.bootstrapStates(); + BlockRedstoneWire.bootstrapStates(); + BlockSand.bootstrapStates(); + BlockSandStone.bootstrapStates(); + BlockSapling.bootstrapStates(); + BlockSilverfish.bootstrapStates(); + BlockSlab.bootstrapStates(); + BlockStairs.bootstrapStates(); + BlockStone.bootstrapStates(); + BlockStoneBrick.bootstrapStates(); + BlockStoneSlab.bootstrapStates(); + BlockStoneSlabNew.bootstrapStates(); + BlockTallGrass.bootstrapStates(); + BlockTrapDoor.bootstrapStates(); + BlockWall.bootstrapStates(); + BlockWoodSlab.bootstrapStates(); - /**+ - * Get a unique ID for the given BlockState, containing both - * BlockID and metadata - */ - public static int getStateId(IBlockState state) { - Block block = state.getBlock(); - return getIdFromBlock(block) + (block.getMetaFromState(state) << 12); } public static Block getBlockById(int id) { return (Block) blockRegistry.getObjectById(id); } - /**+ - * Get a BlockState by it's ID (see getStateId) - */ - public static IBlockState getStateById(int id) { - int i = id & 4095; - int j = id >> 12 & 15; - return getBlockById(i).getStateFromMeta(j); - } - public static Block getBlockFromItem(Item itemIn) { return itemIn instanceof ItemBlock ? ((ItemBlock) itemIn).getBlock() : null; } @@ -182,925 +216,38 @@ public class Block { } } - public boolean isFullBlock() { - return this.fullBlock; + public static int getIdFromBlock(Block blockIn) { + return blockRegistry.getIDForObject(blockIn); } - public int getLightOpacity() { - return this.lightOpacity; - } - - /**+ - * Used in the renderer to apply ambient occlusion - */ - public boolean isTranslucent() { - return this.translucent; - } - - public int getLightValue() { - return this.lightValue; - } - - /**+ - * Should block use the brightest neighbor light value as its - * own - */ - public boolean getUseNeighborBrightness() { - return this.useNeighborBrightness; - } - - /**+ - * Get a material of block - */ - public Material getMaterial() { - return this.blockMaterial; - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState state) { - return this.field_181083_K; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int var1) { - return this.getDefaultState(); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - if (iblockstate != null && !iblockstate.getPropertyNames().isEmpty()) { - throw new IllegalArgumentException("Don\'t know how to convert " + iblockstate + " back into data..."); - } else { - return 0; - } - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess var2, BlockPos var3) { - return iblockstate; - } - - public Block(Material parMaterial, MapColor parMapColor) { - this.enableStats = true; - this.stepSound = soundTypeStone; - this.blockParticleGravity = 1.0F; - this.slipperiness = 0.6F; - this.blockMaterial = parMaterial; - this.field_181083_K = parMapColor; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - this.fullBlock = this.isOpaqueCube(); - this.lightOpacity = this.isOpaqueCube() ? 255 : 0; - this.translucent = !parMaterial.blocksLight(); - this.blockState = this.createBlockState(); - this.setDefaultState(this.blockState.getBaseState()); - } - - protected Block(Material materialIn) { - this(materialIn, materialIn.getMaterialMapColor()); - } - - /**+ - * Sets the footstep sound for the block. Returns the object for - * convenience in constructing. - */ - protected Block setStepSound(Block.SoundType sound) { - this.stepSound = sound; - return this; - } - - /**+ - * Sets how much light is blocked going through this block. - * Returns the object for convenience in constructing. - */ - protected Block setLightOpacity(int opacity) { - this.lightOpacity = opacity; - return this; - } - - /**+ - * Sets the light value that the block emits. Returns resulting - * block instance for constructing convenience. Args: level - */ - protected Block setLightLevel(float value) { - this.lightValue = (int) (15.0F * value); - return this; - } - - /**+ - * Sets the the blocks resistance to explosions. Returns the - * object for convenience in constructing. - */ - protected Block setResistance(float resistance) { - this.blockResistance = resistance * 3.0F; - return this; - } - - /**+ - * Indicate if a material is a normal solid opaque cube - */ - public boolean isBlockNormalCube() { - return this.blockMaterial.blocksMovement() && this.isFullCube(); - } - - /**+ - * Used for nearly all game logic (non-rendering) purposes. Use - * Forge-provided isNormalCube(IBlockAccess, BlockPos) instead. - */ - public boolean isNormalCube() { - return this.blockMaterial.isOpaque() && this.isFullCube() && !this.canProvidePower(); - } - - public boolean isVisuallyOpaque() { - return this.blockMaterial.blocksMovement() && this.isFullCube(); - } - - public boolean isFullCube() { - return true; - } - - public boolean isPassable(IBlockAccess var1, BlockPos var2) { - return !this.blockMaterial.blocksMovement(); - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) - */ - public boolean isReplaceable(World var1, BlockPos var2) { - return false; - } - - /**+ - * Sets how many hits it takes to break a block. - */ - protected Block setHardness(float hardness) { - this.blockHardness = hardness; - if (this.blockResistance < hardness * 5.0F) { - this.blockResistance = hardness * 5.0F; - } - - return this; - } - - protected Block setBlockUnbreakable() { - this.setHardness(-1.0F); - return this; - } - - public float getBlockHardness(World worldIn, BlockPos pos) { - return this.blockHardness; - } - - /**+ - * Sets whether this block type will receive random update ticks - */ - protected Block setTickRandomly(boolean shouldTick) { - this.needsRandomTick = shouldTick; - return this; - } - - /**+ - * Returns whether or not this block is of a type that needs - * random ticking. Called for ref-counting purposes by - * ExtendedBlockStorage in order to broadly cull a chunk from - * the random chunk update list for efficiency's sake. - */ - public boolean getTickRandomly() { - return this.needsRandomTick; - } - - public boolean hasTileEntity() { - return this.isBlockContainer; - } - - protected final void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { - this.minX = (double) minX; - this.minY = (double) minY; - this.minZ = (double) minZ; - this.maxX = (double) maxX; - this.maxY = (double) maxY; - this.maxZ = (double) maxZ; - } - - public int getMixedBrightnessForBlock(IBlockAccess worldIn, BlockPos pos) { - Block block = worldIn.getBlockState(pos).getBlock(); - int i = worldIn.getCombinedLight(pos, block.getLightValue()); - if (i == 0 && block instanceof BlockSlab) { - pos = pos.down(); - block = worldIn.getBlockState(pos).getBlock(); - return worldIn.getCombinedLight(pos, block.getLightValue()); - } else { - return i; - } - } - - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - return enumfacing == EnumFacing.DOWN && this.minY > 0.0D ? true - : (enumfacing == EnumFacing.UP && this.maxY < 1.0D ? true - : (enumfacing == EnumFacing.NORTH && this.minZ > 0.0D ? true - : (enumfacing == EnumFacing.SOUTH && this.maxZ < 1.0D ? true - : (enumfacing == EnumFacing.WEST && this.minX > 0.0D ? true - : (enumfacing == EnumFacing.EAST && this.maxX < 1.0D ? true - : !iblockaccess.getBlockState(blockpos).getBlock() - .isOpaqueCube()))))); - } - - /**+ - * Whether this Block is solid on the given Side - */ - public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { - return worldIn.getBlockState(pos).getBlock().getMaterial().isSolid(); - } - - public AxisAlignedBB getSelectedBoundingBox(World var1, BlockPos blockpos) { - return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, - (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, - (double) blockpos.getY() + this.maxY, (double) blockpos.getZ() + this.maxZ); - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. - */ - public void addCollisionBoxesToList(World worldIn, BlockPos pos, IBlockState state, AxisAlignedBB mask, - List list, Entity collidingEntity) { - AxisAlignedBB axisalignedbb = this.getCollisionBoundingBox(worldIn, pos, state); - if (axisalignedbb != null && mask.intersectsWith(axisalignedbb)) { - list.add(axisalignedbb); - } - - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { - return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, - (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, - (double) blockpos.getY() + this.maxY, (double) blockpos.getZ() + this.maxZ); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return true; - } - - public boolean canCollideCheck(IBlockState var1, boolean var2) { - return this.isCollidable(); - } - - /**+ - * Returns if this block is collidable (only used by Fire). - * Args: x, y, z + /** + * + Get a BlockState by it's ID (see getStateId) */ - public boolean isCollidable() { - return true; + public static IBlockState getStateById(int id) { + int i = id & 4095; + int j = id >> 12 & 15; + return getBlockById(i).getStateFromMeta(j); } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) + /** + * + Get a unique ID for the given BlockState, containing both BlockID and + * metadata */ - public void randomTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - this.updateTick(world, blockpos, iblockstate, random); - } - - public void updateTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { - } - - public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { - } - - /**+ - * Called when a player destroys this Block - */ - public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, IBlockState state) { - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World var1, BlockPos var2, IBlockState var3, Block var4) { - } - - /**+ - * How many world ticks before ticking - */ - public int tickRate(World var1) { - return 10; - } - - public void onBlockAdded(World var1, BlockPos var2, IBlockState var3) { - } - - public void breakBlock(World var1, BlockPos var2, IBlockState var3) { - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom random) { - return 1; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(this); - } - - /**+ - * Get the hardness of this Block relative to the ability of the - * given player - */ - public float getPlayerRelativeBlockHardness(EntityPlayer playerIn, World worldIn, BlockPos pos) { - float f = this.getBlockHardness(worldIn, pos); - return f < 0.0F ? 0.0F - : (!playerIn.canHarvestBlock(this) ? playerIn.getToolDigEfficiency(this) / f / 100.0F - : playerIn.getToolDigEfficiency(this) / f / 30.0F); - } - - /**+ - * Spawn this Block's drops into the World as EntityItems - */ - public final void dropBlockAsItem(World worldIn, BlockPos pos, IBlockState state, int forture) { - this.dropBlockAsItemWithChance(worldIn, pos, state, 1.0F, forture); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { - if (!world.isRemote) { - int j = this.quantityDroppedWithBonus(i, world.rand); - - for (int k = 0; k < j; ++k) { - if (world.rand.nextFloat() <= f) { - Item item = this.getItemDropped(iblockstate, world.rand, i); - if (item != null) { - spawnAsEntity(world, blockpos, new ItemStack(item, 1, this.damageDropped(iblockstate))); - } - } - } - } - } - - /**+ - * Spawns the given ItemStack as an EntityItem into the World at - * the given position - */ - public static void spawnAsEntity(World worldIn, BlockPos pos, ItemStack stack) { - if (!worldIn.isRemote && worldIn.getGameRules().getBoolean("doTileDrops")) { - float f = 0.5F; - double d0 = (double) (worldIn.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; - double d1 = (double) (worldIn.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; - double d2 = (double) (worldIn.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; - EntityItem entityitem = new EntityItem(worldIn, (double) pos.getX() + d0, (double) pos.getY() + d1, - (double) pos.getZ() + d2, stack); - entityitem.setDefaultPickupDelay(); - worldIn.spawnEntityInWorld(entityitem); - } - } - - /**+ - * Spawns the given amount of experience into the World as XP - * orb entities - */ - protected void dropXpOnBlockBreak(World worldIn, BlockPos pos, int amount) { - if (!worldIn.isRemote) { - while (amount > 0) { - int i = EntityXPOrb.getXPSplit(amount); - amount -= i; - worldIn.spawnEntityInWorld(new EntityXPOrb(worldIn, (double) pos.getX() + 0.5D, - (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D, i)); - } - } - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState var1) { - return 0; - } - - /**+ - * Returns how much this block can resist explosions from the - * passed in entity. - */ - public float getExplosionResistance(Entity exploder) { - return this.blockResistance / 5.0F; - } - - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { - this.setBlockBoundsBasedOnState(world, blockpos); - vec3 = vec3.addVector((double) (-blockpos.getX()), (double) (-blockpos.getY()), (double) (-blockpos.getZ())); - vec31 = vec31.addVector((double) (-blockpos.getX()), (double) (-blockpos.getY()), (double) (-blockpos.getZ())); - Vec3 vec32 = vec3.getIntermediateWithXValue(vec31, this.minX); - Vec3 vec33 = vec3.getIntermediateWithXValue(vec31, this.maxX); - Vec3 vec34 = vec3.getIntermediateWithYValue(vec31, this.minY); - Vec3 vec35 = vec3.getIntermediateWithYValue(vec31, this.maxY); - Vec3 vec36 = vec3.getIntermediateWithZValue(vec31, this.minZ); - Vec3 vec37 = vec3.getIntermediateWithZValue(vec31, this.maxZ); - if (!this.isVecInsideYZBounds(vec32)) { - vec32 = null; - } - - if (!this.isVecInsideYZBounds(vec33)) { - vec33 = null; - } - - if (!this.isVecInsideXZBounds(vec34)) { - vec34 = null; - } - - if (!this.isVecInsideXZBounds(vec35)) { - vec35 = null; - } - - if (!this.isVecInsideXYBounds(vec36)) { - vec36 = null; - } - - if (!this.isVecInsideXYBounds(vec37)) { - vec37 = null; - } - - Vec3 vec38 = null; - if (vec32 != null && (vec38 == null || vec3.squareDistanceTo(vec32) < vec3.squareDistanceTo(vec38))) { - vec38 = vec32; - } - - if (vec33 != null && (vec38 == null || vec3.squareDistanceTo(vec33) < vec3.squareDistanceTo(vec38))) { - vec38 = vec33; - } - - if (vec34 != null && (vec38 == null || vec3.squareDistanceTo(vec34) < vec3.squareDistanceTo(vec38))) { - vec38 = vec34; - } - - if (vec35 != null && (vec38 == null || vec3.squareDistanceTo(vec35) < vec3.squareDistanceTo(vec38))) { - vec38 = vec35; - } - - if (vec36 != null && (vec38 == null || vec3.squareDistanceTo(vec36) < vec3.squareDistanceTo(vec38))) { - vec38 = vec36; - } - - if (vec37 != null && (vec38 == null || vec3.squareDistanceTo(vec37) < vec3.squareDistanceTo(vec38))) { - vec38 = vec37; - } - - if (vec38 == null) { - return null; - } else { - EnumFacing enumfacing = null; - if (vec38 == vec32) { - enumfacing = EnumFacing.WEST; - } - - if (vec38 == vec33) { - enumfacing = EnumFacing.EAST; - } - - if (vec38 == vec34) { - enumfacing = EnumFacing.DOWN; - } - - if (vec38 == vec35) { - enumfacing = EnumFacing.UP; - } - - if (vec38 == vec36) { - enumfacing = EnumFacing.NORTH; - } - - if (vec38 == vec37) { - enumfacing = EnumFacing.SOUTH; - } - - return new MovingObjectPosition( - vec38.addVector((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()), - enumfacing, blockpos); - } - } - - /**+ - * Checks if a vector is within the Y and Z bounds of the block. - */ - private boolean isVecInsideYZBounds(Vec3 point) { - return point == null ? false - : point.yCoord >= this.minY && point.yCoord <= this.maxY && point.zCoord >= this.minZ - && point.zCoord <= this.maxZ; - } - - /**+ - * Checks if a vector is within the X and Z bounds of the block. - */ - private boolean isVecInsideXZBounds(Vec3 point) { - return point == null ? false - : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.zCoord >= this.minZ - && point.zCoord <= this.maxZ; - } - - /**+ - * Checks if a vector is within the X and Y bounds of the block. - */ - private boolean isVecInsideXYBounds(Vec3 point) { - return point == null ? false - : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.yCoord >= this.minY - && point.yCoord <= this.maxY; - } - - /**+ - * Called when this Block is destroyed by an Explosion - */ - public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn) { - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.SOLID; - } - - public boolean canReplace(World worldIn, BlockPos pos, EnumFacing side, ItemStack stack) { - return this.canPlaceBlockOnSide(worldIn, pos, side); - } - - /**+ - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, EnumFacing side) { - return this.canPlaceBlockAt(worldIn, pos); - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return world.getBlockState(blockpos).getBlock().blockMaterial.isReplaceable(); - } - - public boolean onBlockActivated(World var1, BlockPos var2, IBlockState var3, EntityPlayer var4, EnumFacing var5, - float var6, float var7, float var8) { - return false; - } - - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) { - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int i, EntityLivingBase var8) { - return this.getStateFromMeta(i); - } - - public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn) { - } - - public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion) { - return motion; - } - - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - } - - /**+ - * returns the block bounderies minX value - */ - public final double getBlockBoundsMinX() { - return this.minX; - } - - /**+ - * returns the block bounderies maxX value - */ - public final double getBlockBoundsMaxX() { - return this.maxX; - } - - /**+ - * returns the block bounderies minY value - */ - public final double getBlockBoundsMinY() { - return this.minY; - } - - /**+ - * returns the block bounderies maxY value - */ - public final double getBlockBoundsMaxY() { - return this.maxY; - } - - /**+ - * returns the block bounderies minZ value - */ - public final double getBlockBoundsMinZ() { - return this.minZ; - } - - /**+ - * returns the block bounderies maxZ value - */ - public final double getBlockBoundsMaxZ() { - return this.maxZ; - } - - public int getBlockColor() { - return 16777215; - } - - public int getRenderColor(IBlockState state) { - return 16777215; - } - - public int colorMultiplier(IBlockAccess worldIn, BlockPos pos, int renderPass) { - return 16777215; - } - - public final int colorMultiplier(IBlockAccess worldIn, BlockPos pos) { - return this.colorMultiplier(worldIn, pos, 0); - } - - public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState var3, EnumFacing var4) { - return 0; - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return false; - } - - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity var4) { - } - - public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState var3, EnumFacing var4) { - return 0; - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - } - - public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, - TileEntity var5) { - entityplayer.triggerAchievement(StatList.mineBlockStatArray[getIdFromBlock(this)]); - entityplayer.addExhaustion(0.025F); - if (this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(entityplayer)) { - ItemStack itemstack = this.createStackedBlock(iblockstate); - if (itemstack != null) { - spawnAsEntity(world, blockpos, itemstack); - } - } else { - int i = EnchantmentHelper.getFortuneModifier(entityplayer); - this.dropBlockAsItem(world, blockpos, iblockstate, i); - } - - } - - protected boolean canSilkHarvest() { - return this.isFullCube() && !this.isBlockContainer; - } - - protected ItemStack createStackedBlock(IBlockState state) { - int i = 0; - Item item = Item.getItemFromBlock(this); - if (item != null && item.getHasSubtypes()) { - i = this.getMetaFromState(state); - } - - return new ItemStack(item, 1, i); - } - - /**+ - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int fortune, EaglercraftRandom random) { - return this.quantityDropped(random); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World var1, BlockPos var2, IBlockState var3, EntityLivingBase var4, ItemStack var5) { - } - - public boolean func_181623_g() { - return !this.blockMaterial.isSolid() && !this.blockMaterial.isLiquid(); - } - - public Block setUnlocalizedName(String name) { - this.unlocalizedName = name; - return this; - } - - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal(this.getUnlocalizedName() + ".name"); - } - - /**+ - * Returns the unlocalized name of the block with "tile." - * appended to the front. - */ - public String getUnlocalizedName() { - return "tile." + this.unlocalizedName; - } - - /**+ - * Called on both Client and Server when World#addBlockEvent is - * called - */ - public boolean onBlockEventReceived(World var1, BlockPos var2, IBlockState var3, int var4, int var5) { - return false; - } - - /**+ - * Return the state of blocks statistics flags - if the block is - * counted for mined and placed. - */ - public boolean getEnableStats() { - return this.enableStats; - } - - protected Block disableStats() { - this.enableStats = false; - return this; - } - - public int getMobilityFlag() { - return this.blockMaterial.getMaterialMobility(); - } - - /**+ - * Returns the default ambient occlusion value based on block - * opacity - */ - public float getAmbientOcclusionLightValue() { - return this.isBlockNormalCube() ? 0.2F : 1.0F; - } - - /**+ - * Block's chance to react to a living entity falling on it. - */ - public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) { - entityIn.fall(fallDistance, 1.0F); - } - - /**+ - * Called when an Entity lands on this Block. This method *must* - * update motionY because the entity will not do that on its own - */ - public void onLanded(World worldIn, Entity entityIn) { - entityIn.motionY = 0.0D; - } - - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(this); - } - - public int getDamageValue(World worldIn, BlockPos pos) { - return this.damageDropped(worldIn.getBlockState(pos)); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, 0)); - } - - /**+ - * Returns the CreativeTab to display the given block on. - */ - public CreativeTabs getCreativeTabToDisplayOn() { - return this.displayOnCreativeTab; - } - - public Block setCreativeTab(CreativeTabs tab) { - this.displayOnCreativeTab = tab; - return this; - } - - public void onBlockHarvested(World var1, BlockPos var2, IBlockState var3, EntityPlayer var4) { - } - - /**+ - * Called similar to random ticks, but only when it is raining. - */ - public void fillWithRain(World worldIn, BlockPos pos) { - } - - /**+ - * Returns true only if block is flowerPot - */ - public boolean isFlowerPot() { - return false; - } - - public boolean requiresUpdates() { - return true; - } - - /**+ - * Return whether this block can drop from an explosion. - */ - public boolean canDropFromExplosion(Explosion explosionIn) { - return true; - } - - public boolean isAssociatedBlock(Block other) { - return this == other; + public static int getStateId(IBlockState state) { + Block block = state.getBlock(); + return getIdFromBlock(block) + (block.getMetaFromState(state) << 12); } public static boolean isEqualTo(Block blockIn, Block other) { return blockIn != null && other != null ? (blockIn == other ? true : blockIn.isAssociatedBlock(other)) : false; } - public boolean hasComparatorInputOverride() { - return false; + private static void registerBlock(int id, ResourceLocation textualID, Block block_) { + blockRegistry.register(id, textualID, block_); } - public int getComparatorInputOverride(World worldIn, BlockPos pos) { - return 0; - } - - /**+ - * Possibly modify the given BlockState before rendering it on - * an Entity (Minecarts, Endermen, ...) - */ - public IBlockState getStateForEntityRender(IBlockState iblockstate) { - return iblockstate; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[0]); - } - - public BlockState getBlockState() { - return this.blockState; - } - - protected final void setDefaultState(IBlockState state) { - this.defaultBlockState = state; - } - - public final IBlockState getDefaultState() { - return this.defaultBlockState; - } - - /**+ - * Get the OffsetType for this Block. Determines if the model is - * rendered slightly offset. - */ - public Block.EnumOffsetType getOffsetType() { - return Block.EnumOffsetType.NONE; - } - - public String toString() { - return "Block{" + blockRegistry.getNameForObject(this) + "}"; + private static void registerBlock(int id, String textualID, Block block_) { + registerBlock(id, new ResourceLocation(textualID), block_); } public static void registerBlocks() { @@ -1195,8 +342,6 @@ public class Block { (new Block(Material.iron, MapColor.ironColor)).setHardness(5.0F).setResistance(10.0F) .setStepSound(soundTypeMetal).setUnlocalizedName("blockIron") .setCreativeTab(CreativeTabs.tabBlock)); - - registerBlock(43, (String) "double_stone_slab", (new BlockDoubleStoneSlab()).setHardness(2.0F) .setResistance(10.0F).setStepSound(soundTypePiston).setUnlocalizedName("stoneSlab")); registerBlock(44, (String) "stone_slab", (new BlockHalfStoneSlab()).setHardness(2.0F).setResistance(10.0F) @@ -1342,7 +487,7 @@ public class Block { (new BlockStairs(block5.getDefaultState())).setUnlocalizedName("stairsBrick")); registerBlock(109, (String) "stone_brick_stairs", (new BlockStairs( block8.getDefaultState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.DEFAULT))) - .setUnlocalizedName("stairsStoneBrickSmooth")); + .setUnlocalizedName("stairsStoneBrickSmooth")); registerBlock(110, (String) "mycelium", (new BlockMycelium()).setHardness(0.6F).setStepSound(soundTypeGrass).setUnlocalizedName("mycel")); registerBlock(111, (String) "waterlily", @@ -1387,7 +532,7 @@ public class Block { registerBlock(128, (String) "sandstone_stairs", (new BlockStairs( block2.getDefaultState().withProperty(BlockSandStone.TYPE, BlockSandStone.EnumType.SMOOTH))) - .setUnlocalizedName("stairsSandStone")); + .setUnlocalizedName("stairsSandStone")); registerBlock(129, (String) "emerald_ore", (new BlockOre()).setHardness(3.0F).setResistance(5.0F) .setStepSound(soundTypePiston).setUnlocalizedName("oreEmerald")); registerBlock(130, (String) "ender_chest", (new BlockEnderChest()).setHardness(22.5F).setResistance(1000.0F) @@ -1401,15 +546,15 @@ public class Block { registerBlock(134, (String) "spruce_stairs", (new BlockStairs( block1.getDefaultState().withProperty(BlockPlanks.VARIANT, BlockPlanks.EnumType.SPRUCE))) - .setUnlocalizedName("stairsWoodSpruce")); + .setUnlocalizedName("stairsWoodSpruce")); registerBlock(135, (String) "birch_stairs", (new BlockStairs( block1.getDefaultState().withProperty(BlockPlanks.VARIANT, BlockPlanks.EnumType.BIRCH))) - .setUnlocalizedName("stairsWoodBirch")); + .setUnlocalizedName("stairsWoodBirch")); registerBlock(136, (String) "jungle_stairs", (new BlockStairs( block1.getDefaultState().withProperty(BlockPlanks.VARIANT, BlockPlanks.EnumType.JUNGLE))) - .setUnlocalizedName("stairsWoodJungle")); + .setUnlocalizedName("stairsWoodJungle")); registerBlock(137, (String) "command_block", (new BlockCommandBlock()).setBlockUnbreakable() .setResistance(6000000.0F).setUnlocalizedName("commandBlock")); registerBlock(138, (String) "beacon", (new BlockBeacon()).setUnlocalizedName("beacon").setLightLevel(1.0F)); @@ -1451,7 +596,7 @@ public class Block { registerBlock(156, (String) "quartz_stairs", (new BlockStairs( block11.getDefaultState().withProperty(BlockQuartz.VARIANT, BlockQuartz.EnumType.DEFAULT))) - .setUnlocalizedName("stairsQuartz")); + .setUnlocalizedName("stairsQuartz")); registerBlock(157, (String) "activator_rail", (new BlockRailPowered()).setHardness(0.7F) .setStepSound(soundTypeMetal).setUnlocalizedName("activatorRail")); registerBlock(158, (String) "dropper", @@ -1465,11 +610,11 @@ public class Block { registerBlock(163, (String) "acacia_stairs", (new BlockStairs( block1.getDefaultState().withProperty(BlockPlanks.VARIANT, BlockPlanks.EnumType.ACACIA))) - .setUnlocalizedName("stairsWoodAcacia")); + .setUnlocalizedName("stairsWoodAcacia")); registerBlock(164, (String) "dark_oak_stairs", (new BlockStairs( block1.getDefaultState().withProperty(BlockPlanks.VARIANT, BlockPlanks.EnumType.DARK_OAK))) - .setUnlocalizedName("stairsWoodDarkOak")); + .setUnlocalizedName("stairsWoodDarkOak")); registerBlock(165, (String) "slime", (new BlockSlime()).setUnlocalizedName("slime").setStepSound(SLIME_SOUND)); registerBlock(166, (String) "barrier", (new BlockBarrier()).setUnlocalizedName("barrier")); registerBlock(167, (String) "iron_trapdoor", (new BlockTrapDoor(Material.iron)).setHardness(5.0F) @@ -1501,7 +646,7 @@ public class Block { registerBlock(179, (String) "red_sandstone", block12); registerBlock(180, (String) "red_sandstone_stairs", (new BlockStairs( block12.getDefaultState().withProperty(BlockRedSandstone.TYPE, BlockRedSandstone.EnumType.SMOOTH))) - .setUnlocalizedName("stairsRedSandStone")); + .setUnlocalizedName("stairsRedSandStone")); registerBlock(181, (String) "double_stone_slab2", (new BlockDoubleStoneSlabNew()).setHardness(2.0F) .setResistance(10.0F).setStepSound(soundTypePiston).setUnlocalizedName("stoneSlab2")); registerBlock(182, (String) "stone_slab2", (new BlockHalfStoneSlabNew()).setHardness(2.0F).setResistance(10.0F) @@ -1546,33 +691,47 @@ public class Block { .setStepSound(soundTypeWood).setUnlocalizedName("doorAcacia").disableStats()); registerBlock(197, (String) "dark_oak_door", (new BlockDoor(Material.wood)).setHardness(3.0F) .setStepSound(soundTypeWood).setUnlocalizedName("doorDarkOak").disableStats()); - registerBlock(198, (String) "starlike:iron_grate", - (new Block(Material.iron, MapColor.ironColor)) - .setHardness(5.0F) - .setResistance(10.0F) - .setStepSound(soundTypeMetal) - .setUnlocalizedName("iron_grate") - .setCreativeTab(CreativeTabs.tabBlock)); - registerBlock(199, (String) "starlike:platinum_ore", - (new BlockOre()) - .setHardness(50.0F) - .setResistance(2000.0F) - .setStepSound(soundTypePiston) - .setUnlocalizedName("platinum_ore")); - registerBlock(200, (String) "starlike:platinum_block", - (new Block(Material.iron, MapColor.ironColor)) - .setHardness(5.0F) - .setResistance(10.0F) - .setStepSound(soundTypeMetal) - .setUnlocalizedName("platinum_block") - .setCreativeTab(CreativeTabs.tabBlock)); - registerBlock(201, (String) "starlike:uranium_ore", - (new BlockOre()) - .setHardness(50.0F) - .setResistance(2000.0F) - .setStepSound(soundTypePiston) - .setUnlocalizedName("uranium_ore")); + registerBlock(512, (String) "starlike:deepstone", + (new BlockDeepstone()).setHardness(3.0F).setResistance(10.0F).setStepSound(soundTypePiston) + .setUnlocalizedName("deepstone").setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(513, (String) "starlike:cobbled_deepstone", + (new Block(Material.rock)).setHardness(3.5F).setResistance(10.0F).setStepSound(soundTypePiston) + .setUnlocalizedName("cobbled_deepstone").setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(514, (String) "starlike:steel_block", + (new Block(Material.iron, MapColor.ironColor)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(soundTypeMetal).setUnlocalizedName("steel_block") + .setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(515, (String) "starlike:steel_grate", + (new BlockSteelGrate()).setHardness(5.0F).setResistance(10.0F) + .setStepSound(soundTypeMetal).setUnlocalizedName("steel_grate") + .setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(516, (String) "starlike:platinum_ore", + (new BlockOre()).setHardness(50.0F).setResistance(250.0F).setStepSound(soundTypePiston) + .setUnlocalizedName("platinum_ore").setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(517, (String) "starlike:platinum_block", + (new Block(Material.iron, MapColor.ironColor)).setHardness(15.0F).setResistance(30.0F) + .setStepSound(soundTypeMetal).setUnlocalizedName("platinum_block") + .setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(518, (String) "starlike:titanium_ore", + (new BlockOre()).setHardness(100.0F).setResistance(500.0F).setStepSound(soundTypePiston) + .setUnlocalizedName("titanium_ore").setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(519, (String) "starlike:titanium_block", + (new Block(Material.iron, MapColor.ironColor)).setHardness(25.0F).setResistance(50.0F) + .setStepSound(soundTypeMetal).setUnlocalizedName("titanium_block") + .setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(520, (String) "starlike:uranium_ore", + (new BlockOre()).setHardness(5.0F).setResistance(10.0F).setStepSound(soundTypePiston) + .setUnlocalizedName("uranium_ore").setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(521, (String) "starlike:uranium_block", + (new Block(Material.iron, MapColor.greenColor)).setHardness(40.0F).setResistance(200.0F) + .setStepSound(soundTypeMetal).setUnlocalizedName("uranium_block") + .setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(522, (String) "starlike:mosaic", (new BlockMosaic()).setHardness(2.0F).setResistance(5.0F) + .setStepSound(soundTypeWood).setUnlocalizedName("mosaic").setCreativeTab(CreativeTabs.tabStarlike)); + registerBlock(523, (String) "starlike:fabricator", + (new BlockFabricator()).setHardness(5.0F).setResistance(10.0F).setStepSound(soundTypePiston) + .setUnlocalizedName("fabricator").setCreativeTab(CreativeTabs.tabStarlike)); blockRegistry.validateKey(); for (Block block13 : blockRegistry) { @@ -1602,91 +761,957 @@ public class Block { } - public static void bootstrapStates() { - BlockBed.bootstrapStates(); - BlockDirt.bootstrapStates(); - BlockDoor.bootstrapStates(); - BlockDoublePlant.bootstrapStates(); - BlockFlowerPot.bootstrapStates(); - BlockHugeMushroom.bootstrapStates(); - BlockLever.bootstrapStates(); - BlockLog.bootstrapStates(); - BlockNewLeaf.bootstrapStates(); - BlockNewLog.bootstrapStates(); - BlockOldLeaf.bootstrapStates(); - BlockOldLog.bootstrapStates(); - BlockPistonExtension.bootstrapStates(); - BlockPistonMoving.bootstrapStates(); - BlockPlanks.bootstrapStates(); - BlockPrismarine.bootstrapStates(); - BlockQuartz.bootstrapStates(); - BlockRail.bootstrapStates(); - BlockRailDetector.bootstrapStates(); - BlockRailPowered.bootstrapStates(); - BlockRedSandstone.bootstrapStates(); - BlockRedstoneComparator.bootstrapStates(); - BlockRedstoneWire.bootstrapStates(); - BlockSand.bootstrapStates(); - BlockSandStone.bootstrapStates(); - BlockSapling.bootstrapStates(); - BlockSilverfish.bootstrapStates(); - BlockSlab.bootstrapStates(); - BlockStairs.bootstrapStates(); - BlockStone.bootstrapStates(); - BlockStoneBrick.bootstrapStates(); - BlockStoneSlab.bootstrapStates(); - BlockStoneSlabNew.bootstrapStates(); - BlockTallGrass.bootstrapStates(); - BlockTrapDoor.bootstrapStates(); - BlockWall.bootstrapStates(); - BlockWoodSlab.bootstrapStates(); + /** + * + Spawns the given ItemStack as an EntityItem into the World at the given + * position + */ + public static void spawnAsEntity(World worldIn, BlockPos pos, ItemStack stack) { + if (!worldIn.isRemote && worldIn.getGameRules().getBoolean("doTileDrops")) { + float f = 0.5F; + double d0 = (double) (worldIn.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; + double d1 = (double) (worldIn.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; + double d2 = (double) (worldIn.rand.nextFloat() * f) + (double) (1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(worldIn, (double) pos.getX() + d0, (double) pos.getY() + d1, + (double) pos.getZ() + d2, stack); + entityitem.setDefaultPickupDelay(); + worldIn.spawnEntityInWorld(entityitem); + } } - private static void registerBlock(int id, ResourceLocation textualID, Block block_) { - blockRegistry.register(id, textualID, block_); + private CreativeTabs displayOnCreativeTab; + protected boolean fullBlock; + protected int lightOpacity; + protected boolean translucent; + protected int lightValue; + protected boolean useNeighborBrightness; + protected float blockHardness; + protected float blockResistance; + + protected boolean enableStats; + + protected boolean needsRandomTick; + + protected boolean isBlockContainer; + + protected double minX; + + protected double minY; + + protected double minZ; + + protected double maxX; + + protected double maxY; + + protected double maxZ; + + public Block.SoundType stepSound; + + public float blockParticleGravity; + + protected final Material blockMaterial; + + protected final MapColor field_181083_K; + + public float slipperiness; + + protected final BlockState blockState; + + private IBlockState defaultBlockState; + + public String unlocalizedName; + + protected Block(Material materialIn) { + this(materialIn, materialIn.getMaterialMapColor()); } - private static void registerBlock(int id, String textualID, Block block_) { - registerBlock(id, new ResourceLocation(textualID), block_); + public Block(Material parMaterial, MapColor parMapColor) { + this.enableStats = true; + this.stepSound = soundTypeStone; + this.blockParticleGravity = 1.0F; + this.slipperiness = 0.6F; + this.blockMaterial = parMaterial; + this.field_181083_K = parMapColor; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.fullBlock = this.isOpaqueCube(); + this.lightOpacity = this.isOpaqueCube() ? 255 : 0; + this.translucent = !parMaterial.blocksLight(); + this.blockState = this.createBlockState(); + this.setDefaultState(this.blockState.getBaseState()); } - public static enum EnumOffsetType { - NONE, XZ, XYZ; + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. + */ + public void addCollisionBoxesToList(World worldIn, BlockPos pos, IBlockState state, AxisAlignedBB mask, + List list, Entity collidingEntity) { + AxisAlignedBB axisalignedbb = this.getCollisionBoundingBox(worldIn, pos, state); + if (axisalignedbb != null && mask.intersectsWith(axisalignedbb)) { + list.add(axisalignedbb); + } + } - public static class SoundType { - public final String soundName; - public final float volume; - public final float frequency; + public void breakBlock(World var1, BlockPos var2, IBlockState var3) { + } - public SoundType(String name, float volume, float frequency) { - this.soundName = name; - this.volume = volume; - this.frequency = frequency; + public boolean canCollideCheck(IBlockState var1, boolean var2) { + return this.isCollidable(); + } + + /** + * + Return whether this block can drop from an explosion. + */ + public boolean canDropFromExplosion(Explosion explosionIn) { + return true; + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return world.getBlockState(blockpos).getBlock().blockMaterial.isReplaceable(); + } + + /** + * + Check whether this Block can be placed on the given side + */ + public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, EnumFacing side) { + return this.canPlaceBlockAt(worldIn, pos); + } + + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. + */ + public boolean canProvidePower() { + return false; + } + + public boolean canReplace(World worldIn, BlockPos pos, EnumFacing side, ItemStack stack) { + return this.canPlaceBlockOnSide(worldIn, pos, side); + } + + protected boolean canSilkHarvest() { + return this.isFullCube() && !this.isBlockContainer; + } + + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. + */ + public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { + this.setBlockBoundsBasedOnState(world, blockpos); + vec3 = vec3.addVector((double) (-blockpos.getX()), (double) (-blockpos.getY()), (double) (-blockpos.getZ())); + vec31 = vec31.addVector((double) (-blockpos.getX()), (double) (-blockpos.getY()), (double) (-blockpos.getZ())); + Vec3 vec32 = vec3.getIntermediateWithXValue(vec31, this.minX); + Vec3 vec33 = vec3.getIntermediateWithXValue(vec31, this.maxX); + Vec3 vec34 = vec3.getIntermediateWithYValue(vec31, this.minY); + Vec3 vec35 = vec3.getIntermediateWithYValue(vec31, this.maxY); + Vec3 vec36 = vec3.getIntermediateWithZValue(vec31, this.minZ); + Vec3 vec37 = vec3.getIntermediateWithZValue(vec31, this.maxZ); + if (!this.isVecInsideYZBounds(vec32)) { + vec32 = null; } - public float getVolume() { - return this.volume; + if (!this.isVecInsideYZBounds(vec33)) { + vec33 = null; } - public float getFrequency() { - return this.frequency; + if (!this.isVecInsideXZBounds(vec34)) { + vec34 = null; } - public String getBreakSound() { - return "dig." + this.soundName; + if (!this.isVecInsideXZBounds(vec35)) { + vec35 = null; } - public String getStepSound() { - return "step." + this.soundName; + if (!this.isVecInsideXYBounds(vec36)) { + vec36 = null; } - public String getPlaceSound() { - return this.getBreakSound(); + if (!this.isVecInsideXYBounds(vec37)) { + vec37 = null; + } + + Vec3 vec38 = null; + if (vec32 != null && (vec38 == null || vec3.squareDistanceTo(vec32) < vec3.squareDistanceTo(vec38))) { + vec38 = vec32; + } + + if (vec33 != null && (vec38 == null || vec3.squareDistanceTo(vec33) < vec3.squareDistanceTo(vec38))) { + vec38 = vec33; + } + + if (vec34 != null && (vec38 == null || vec3.squareDistanceTo(vec34) < vec3.squareDistanceTo(vec38))) { + vec38 = vec34; + } + + if (vec35 != null && (vec38 == null || vec3.squareDistanceTo(vec35) < vec3.squareDistanceTo(vec38))) { + vec38 = vec35; + } + + if (vec36 != null && (vec38 == null || vec3.squareDistanceTo(vec36) < vec3.squareDistanceTo(vec38))) { + vec38 = vec36; + } + + if (vec37 != null && (vec38 == null || vec3.squareDistanceTo(vec37) < vec3.squareDistanceTo(vec38))) { + vec38 = vec37; + } + + if (vec38 == null) { + return null; + } else { + EnumFacing enumfacing = null; + if (vec38 == vec32) { + enumfacing = EnumFacing.WEST; + } + + if (vec38 == vec33) { + enumfacing = EnumFacing.EAST; + } + + if (vec38 == vec34) { + enumfacing = EnumFacing.DOWN; + } + + if (vec38 == vec35) { + enumfacing = EnumFacing.UP; + } + + if (vec38 == vec36) { + enumfacing = EnumFacing.NORTH; + } + + if (vec38 == vec37) { + enumfacing = EnumFacing.SOUTH; + } + + return new MovingObjectPosition( + vec38.addVector((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()), + enumfacing, blockpos); + } + } + + public final int colorMultiplier(IBlockAccess worldIn, BlockPos pos) { + return this.colorMultiplier(worldIn, pos, 0); + } + + public int colorMultiplier(IBlockAccess worldIn, BlockPos pos, int renderPass) { + return 16777215; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[0]); + } + + protected ItemStack createStackedBlock(IBlockState state) { + int i = 0; + Item item = Item.getItemFromBlock(this); + if (item != null && item.getHasSubtypes()) { + i = this.getMetaFromState(state); + } + + return new ItemStack(item, 1, i); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState var1) { + return 0; + } + + protected Block disableStats() { + this.enableStats = false; + return this; + } + + /** + * + Spawn this Block's drops into the World as EntityItems + */ + public final void dropBlockAsItem(World worldIn, BlockPos pos, IBlockState state, int forture) { + this.dropBlockAsItemWithChance(worldIn, pos, state, 1.0F, forture); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { + if (!world.isRemote) { + int j = this.quantityDroppedWithBonus(i, world.rand); + + for (int k = 0; k < j; ++k) { + if (world.rand.nextFloat() <= f) { + Item item = this.getItemDropped(iblockstate, world.rand, i); + if (item != null) { + spawnAsEntity(world, blockpos, new ItemStack(item, 1, this.damageDropped(iblockstate))); + } + } + } + } + } + + /** + * + Spawns the given amount of experience into the World as XP orb entities + */ + protected void dropXpOnBlockBreak(World worldIn, BlockPos pos, int amount) { + if (!worldIn.isRemote) { + while (amount > 0) { + int i = EntityXPOrb.getXPSplit(amount); + amount -= i; + worldIn.spawnEntityInWorld(new EntityXPOrb(worldIn, (double) pos.getX() + 0.5D, + (double) pos.getY() + 0.5D, (double) pos.getZ() + 0.5D, i)); + } } } public boolean eaglerShadersShouldRenderGlassHighlights() { return false; } + + /** + * + Called similar to random ticks, but only when it is raining. + */ + public void fillWithRain(World worldIn, BlockPos pos) { + } + + public boolean func_181623_g() { + return !this.blockMaterial.isSolid() && !this.blockMaterial.isLiquid(); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess var2, BlockPos var3) { + return iblockstate; + } + + /** + * + Returns the default ambient occlusion value based on block opacity + */ + public float getAmbientOcclusionLightValue() { + return this.isBlockNormalCube() ? 0.2F : 1.0F; + } + + /** + * + returns the block bounderies maxX value + */ + public final double getBlockBoundsMaxX() { + return this.maxX; + } + + /** + * + returns the block bounderies maxY value + */ + public final double getBlockBoundsMaxY() { + return this.maxY; + } + + /** + * + returns the block bounderies maxZ value + */ + public final double getBlockBoundsMaxZ() { + return this.maxZ; + } + + /** + * + returns the block bounderies minX value + */ + public final double getBlockBoundsMinX() { + return this.minX; + } + + /** + * + returns the block bounderies minY value + */ + public final double getBlockBoundsMinY() { + return this.minY; + } + + /** + * + returns the block bounderies minZ value + */ + public final double getBlockBoundsMinZ() { + return this.minZ; + } + + public int getBlockColor() { + return 16777215; + } + + public float getBlockHardness(World worldIn, BlockPos pos) { + return this.blockHardness; + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.SOLID; + } + + public BlockState getBlockState() { + return this.blockState; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { + return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, + (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, + (double) blockpos.getY() + this.maxY, (double) blockpos.getZ() + this.maxZ); + } + + public int getComparatorInputOverride(World worldIn, BlockPos pos) { + return 0; + } + + /** + * + Returns the CreativeTab to display the given block on. + */ + public CreativeTabs getCreativeTabToDisplayOn() { + return this.displayOnCreativeTab; + } + + public int getDamageValue(World worldIn, BlockPos pos) { + return this.damageDropped(worldIn.getBlockState(pos)); + } + + public final IBlockState getDefaultState() { + return this.defaultBlockState; + } + + /** + * + Return the state of blocks statistics flags - if the block is counted for + * mined and placed. + */ + public boolean getEnableStats() { + return this.enableStats; + } + + /** + * + Returns how much this block can resist explosions from the passed in + * entity. + */ + public float getExplosionResistance(Entity exploder) { + return this.blockResistance / 5.0F; + } + + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(this); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(this); + } + + public int getLightOpacity() { + return this.lightOpacity; + } + + public int getLightValue() { + return this.lightValue; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal(this.getUnlocalizedName() + ".name"); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState state) { + return this.field_181083_K; + } + + /** + * + Get a material of block + */ + public Material getMaterial() { + return this.blockMaterial; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + if (iblockstate != null && !iblockstate.getPropertyNames().isEmpty()) { + throw new IllegalArgumentException("Don\'t know how to convert " + iblockstate + " back into data..."); + } else { + return 0; + } + } + + public int getMixedBrightnessForBlock(IBlockAccess worldIn, BlockPos pos) { + Block block = worldIn.getBlockState(pos).getBlock(); + int i = worldIn.getCombinedLight(pos, block.getLightValue()); + if (i == 0 && block instanceof BlockSlab) { + pos = pos.down(); + block = worldIn.getBlockState(pos).getBlock(); + return worldIn.getCombinedLight(pos, block.getLightValue()); + } else { + return i; + } + } + + public int getMobilityFlag() { + return this.blockMaterial.getMaterialMobility(); + } + + /** + * + Get the OffsetType for this Block. Determines if the model is rendered + * slightly offset. + */ + public Block.EnumOffsetType getOffsetType() { + return Block.EnumOffsetType.NONE; + } + + /** + * + Get the hardness of this Block relative to the ability of the given player + */ + public float getPlayerRelativeBlockHardness(EntityPlayer playerIn, World worldIn, BlockPos pos) { + float f = this.getBlockHardness(worldIn, pos); + return f < 0.0F ? 0.0F + : (!playerIn.canHarvestBlock(this) ? playerIn.getToolDigEfficiency(this) / f / 100.0F + : playerIn.getToolDigEfficiency(this) / f / 30.0F); + } + + public int getRenderColor(IBlockState state) { + return 16777215; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + public AxisAlignedBB getSelectedBoundingBox(World var1, BlockPos blockpos) { + return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, + (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, + (double) blockpos.getY() + this.maxY, (double) blockpos.getZ() + this.maxZ); + } + + /** + * + Possibly modify the given BlockState before rendering it on an Entity + * (Minecarts, Endermen, ...) + */ + public IBlockState getStateForEntityRender(IBlockState iblockstate) { + return iblockstate; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int var1) { + return this.getDefaultState(); + } + + public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState var3, EnumFacing var4) { + return 0; + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, 0)); + } + + /** + * + Returns whether or not this block is of a type that needs random ticking. + * Called for ref-counting purposes by ExtendedBlockStorage in order to broadly + * cull a chunk from the random chunk update list for efficiency's sake. + */ + public boolean getTickRandomly() { + return this.needsRandomTick; + } + + /** + * + Returns the unlocalized name of the block with "tile." appended to the + * front. + */ + public String getUnlocalizedName() { + return "tile." + this.unlocalizedName; + } + + /** + * + Should block use the brightest neighbor light value as its own + */ + public boolean getUseNeighborBrightness() { + return this.useNeighborBrightness; + } + + public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState var3, EnumFacing var4) { + return 0; + } + + public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, + TileEntity var5) { + entityplayer.triggerAchievement(StatList.mineBlockStatArray[getIdFromBlock(this)]); + entityplayer.addExhaustion(0.025F); + if (this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(entityplayer)) { + ItemStack itemstack = this.createStackedBlock(iblockstate); + if (itemstack != null) { + spawnAsEntity(world, blockpos, itemstack); + } + } else { + int i = EnchantmentHelper.getFortuneModifier(entityplayer); + this.dropBlockAsItem(world, blockpos, iblockstate, i); + } + + } + + public boolean hasComparatorInputOverride() { + return false; + } + + public boolean hasTileEntity() { + return this.isBlockContainer; + } + + public boolean isAssociatedBlock(Block other) { + return this == other; + } + + /** + * + Indicate if a material is a normal solid opaque cube + */ + public boolean isBlockNormalCube() { + return this.blockMaterial.blocksMovement() && this.isFullCube(); + } + + /** + * + Whether this Block is solid on the given Side + */ + public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { + return worldIn.getBlockState(pos).getBlock().getMaterial().isSolid(); + } + + /** + * + Returns if this block is collidable (only used by Fire). Args: x, y, z + */ + public boolean isCollidable() { + return true; + } + + /** + * + Returns true only if block is flowerPot + */ + public boolean isFlowerPot() { + return false; + } + + public boolean isFullBlock() { + return this.fullBlock; + } + + public boolean isFullCube() { + return true; + } + + /** + * + Used for nearly all game logic (non-rendering) purposes. Use Forge-provided + * isNormalCube(IBlockAccess, BlockPos) instead. + */ + public boolean isNormalCube() { + return this.blockMaterial.isOpaque() && this.isFullCube() && !this.canProvidePower(); + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return true; + } + + public boolean isPassable(IBlockAccess var1, BlockPos var2) { + return !this.blockMaterial.blocksMovement(); + } + + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) + */ + public boolean isReplaceable(World var1, BlockPos var2) { + return false; + } + + /** + * + Used in the renderer to apply ambient occlusion + */ + public boolean isTranslucent() { + return this.translucent; + } + + /** + * + Checks if a vector is within the X and Y bounds of the block. + */ + private boolean isVecInsideXYBounds(Vec3 point) { + return point == null ? false + : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.yCoord >= this.minY + && point.yCoord <= this.maxY; + } + + /** + * + Checks if a vector is within the X and Z bounds of the block. + */ + private boolean isVecInsideXZBounds(Vec3 point) { + return point == null ? false + : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.zCoord >= this.minZ + && point.zCoord <= this.maxZ; + } + + /** + * + Checks if a vector is within the Y and Z bounds of the block. + */ + private boolean isVecInsideYZBounds(Vec3 point) { + return point == null ? false + : point.yCoord >= this.minY && point.yCoord <= this.maxY && point.zCoord >= this.minZ + && point.zCoord <= this.maxZ; + } + + public boolean isVisuallyOpaque() { + return this.blockMaterial.blocksMovement() && this.isFullCube(); + } + + public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion) { + return motion; + } + + public boolean onBlockActivated(World var1, BlockPos var2, IBlockState var3, EntityPlayer var4, EnumFacing var5, + float var6, float var7, float var8) { + return false; + } + + public void onBlockAdded(World var1, BlockPos var2, IBlockState var3) { + } + + public void onBlockClicked(World worldIn, BlockPos pos, EntityPlayer playerIn) { + } + + /** + * + Called when this Block is destroyed by an Explosion + */ + public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn) { + } + + /** + * + Called when a player destroys this Block + */ + public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, IBlockState state) { + } + + /** + * + Called on both Client and Server when World#addBlockEvent is called + */ + public boolean onBlockEventReceived(World var1, BlockPos var2, IBlockState var3, int var4, int var5) { + return false; + } + + public void onBlockHarvested(World var1, BlockPos var2, IBlockState var3, EntityPlayer var4) { + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int i, EntityLivingBase var8) { + return this.getStateFromMeta(i); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World var1, BlockPos var2, IBlockState var3, EntityLivingBase var4, ItemStack var5) { + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) { + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity var4) { + } + + /** + * + Block's chance to react to a living entity falling on it. + */ + public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) { + entityIn.fall(fallDistance, 1.0F); + } + + /** + * + Called when an Entity lands on this Block. This method *must* update + * motionY because the entity will not do that on its own + */ + public void onLanded(World worldIn, Entity entityIn) { + entityIn.motionY = 0.0D; + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World var1, BlockPos var2, IBlockState var3, Block var4) { + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom random) { + return 1; + } + + /** + * + Get the quantity dropped based on the given fortune level + */ + public int quantityDroppedWithBonus(int fortune, EaglercraftRandom random) { + return this.quantityDropped(random); + } + + public void randomDisplayTick(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { + } + + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) + */ + public void randomTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + this.updateTick(world, blockpos, iblockstate, random); + } + + public boolean requiresUpdates() { + return true; + } + + protected final void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + this.minX = (double) minX; + this.minY = (double) minY; + this.minZ = (double) minZ; + this.maxX = (double) maxX; + this.maxY = (double) maxY; + this.maxZ = (double) maxZ; + } + + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + } + + protected Block setBlockUnbreakable() { + this.setHardness(-1.0F); + return this; + } + + public Block setCreativeTab(CreativeTabs tab) { + this.displayOnCreativeTab = tab; + return this; + } + + protected final void setDefaultState(IBlockState state) { + this.defaultBlockState = state; + } + + /** + * + Sets how many hits it takes to break a block. + */ + protected Block setHardness(float hardness) { + this.blockHardness = hardness; + if (this.blockResistance < hardness * 5.0F) { + this.blockResistance = hardness * 5.0F; + } + + return this; + } + + /** + * + Sets the light value that the block emits. Returns resulting block instance + * for constructing convenience. Args: level + */ + protected Block setLightLevel(float value) { + this.lightValue = (int) (15.0F * value); + return this; + } + + /** + * + Sets how much light is blocked going through this block. Returns the object + * for convenience in constructing. + */ + protected Block setLightOpacity(int opacity) { + this.lightOpacity = opacity; + return this; + } + + /** + * + Sets the the blocks resistance to explosions. Returns the object for + * convenience in constructing. + */ + protected Block setResistance(float resistance) { + this.blockResistance = resistance * 3.0F; + return this; + } + + /** + * + Sets the footstep sound for the block. Returns the object for convenience + * in constructing. + */ + protected Block setStepSound(Block.SoundType sound) { + this.stepSound = sound; + return this; + } + + /** + * + Sets whether this block type will receive random update ticks + */ + protected Block setTickRandomly(boolean shouldTick) { + this.needsRandomTick = shouldTick; + return this; + } + + public Block setUnlocalizedName(String name) { + this.unlocalizedName = name; + return this; + } + + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + return enumfacing == EnumFacing.DOWN && this.minY > 0.0D ? true + : (enumfacing == EnumFacing.UP && this.maxY < 1.0D ? true + : (enumfacing == EnumFacing.NORTH && this.minZ > 0.0D ? true + : (enumfacing == EnumFacing.SOUTH && this.maxZ < 1.0D ? true + : (enumfacing == EnumFacing.WEST && this.minX > 0.0D ? true + : (enumfacing == EnumFacing.EAST && this.maxX < 1.0D ? true + : !iblockaccess.getBlockState(blockpos).getBlock() + .isOpaqueCube()))))); + } + + /** + * + How many world ticks before ticking + */ + public int tickRate(World var1) { + return 10; + } + + public String toString() { + return "Block{" + blockRegistry.getNameForObject(this) + "}"; + } + + public void updateTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockAir.java b/src/game/java/net/minecraft/block/BlockAir.java index 1fce39e6..23a0b27e 100644 --- a/src/game/java/net/minecraft/block/BlockAir.java +++ b/src/game/java/net/minecraft/block/BlockAir.java @@ -6,22 +6,25 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,39 +34,39 @@ public class BlockAir extends Block { super(Material.air); } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render + public boolean canCollideCheck(IBlockState state, boolean hitIfLiquid) { + return false; + } + + /** + * + Spawns this Block's drops into the World as EntityItems. */ - public int getRenderType() { - return -1; + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { } public AxisAlignedBB getCollisionBoundingBox(World worldIn, BlockPos pos, IBlockState state) { return null; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return -1; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; } - public boolean canCollideCheck(IBlockState state, boolean hitIfLiquid) { - return false; - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, IBlockState state, float chance, int fortune) { - } - - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) */ public boolean isReplaceable(World worldIn, BlockPos pos) { return true; diff --git a/src/game/java/net/minecraft/block/BlockAnvil.java b/src/game/java/net/minecraft/block/BlockAnvil.java index a46da36f..f4e7294a 100644 --- a/src/game/java/net/minecraft/block/BlockAnvil.java +++ b/src/game/java/net/minecraft/block/BlockAnvil.java @@ -26,28 +26,62 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.IInteractionObject; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockAnvil extends BlockFalling { + public static class Anvil implements IInteractionObject { + private final World world; + private final BlockPos position; + + public Anvil(World worldIn, BlockPos pos) { + this.world = worldIn; + this.position = pos; + } + + public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) { + return new ContainerRepair(playerInventory, this.world, this.position, playerIn); + } + + public IChatComponent getDisplayName() { + return new ChatComponentTranslation(Blocks.anvil.getUnlocalizedName() + ".name", new Object[0]); + } + + public String getGuiID() { + return "minecraft:anvil"; + } + + public String getName() { + return "anvil"; + } + + public boolean hasCustomName() { + return false; + } + } + public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); + public static final PropertyInteger DAMAGE = PropertyInteger.create("damage", 0, 2); protected BlockAnvil() { @@ -58,29 +92,67 @@ public class BlockAnvil extends BlockFalling { this.setCreativeTab(CreativeTabs.tabDecorations); } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, DAMAGE }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState state) { + return ((Integer) state.getValue(DAMAGE)).intValue(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState state) { + int i = 0; + i = i | ((EnumFacing) state.getValue(FACING)).getHorizontalIndex(); + i = i | ((Integer) state.getValue(DAMAGE)).intValue() << 2; + return i; + } + + /** + * + Possibly modify the given BlockState before rendering it on an Entity + * (Minecarts, Endermen, ...) + */ + public IBlockState getStateForEntityRender(IBlockState state) { + return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int meta) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(meta & 3)).withProperty(DAMAGE, + Integer.valueOf((meta & 15) >> 2)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item itemIn, CreativeTabs tab, List list) { + list.add(new ItemStack(itemIn, 1, 0)); + list.add(new ItemStack(itemIn, 1, 1)); + list.add(new ItemStack(itemIn, 1, 2)); + } + public boolean isFullCube() { return false; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, - int meta, EntityLivingBase placer) { - EnumFacing enumfacing = placer.getHorizontalFacing().rotateY(); - return super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer) - .withProperty(FACING, enumfacing).withProperty(DAMAGE, Integer.valueOf(meta >> 2)); - } - public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumFacing side, float hitX, float hitY, float hitZ) { if (!worldIn.isRemote) { @@ -89,14 +161,23 @@ public class BlockAnvil extends BlockFalling { return true; } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ - public int damageDropped(IBlockState state) { - return ((Integer) state.getValue(DAMAGE)).intValue(); + public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, + int meta, EntityLivingBase placer) { + EnumFacing enumfacing = placer.getHorizontalFacing().rotateY(); + return super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer) + .withProperty(FACING, enumfacing).withProperty(DAMAGE, Integer.valueOf(meta >> 2)); + } + + public void onEndFalling(World parWorld, BlockPos parBlockPos) { + parWorld.playAuxSFX(1022, parBlockPos, 0); + } + + protected void onStartFalling(EntityFallingBlock fallingEntity) { + fallingEntity.setHurtEntities(true); } public void setBlockBoundsBasedOnState(IBlockAccess worldIn, BlockPos pos) { @@ -109,85 +190,7 @@ public class BlockAnvil extends BlockFalling { } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item itemIn, CreativeTabs tab, List list) { - list.add(new ItemStack(itemIn, 1, 0)); - list.add(new ItemStack(itemIn, 1, 1)); - list.add(new ItemStack(itemIn, 1, 2)); - } - - protected void onStartFalling(EntityFallingBlock fallingEntity) { - fallingEntity.setHurtEntities(true); - } - - public void onEndFalling(World parWorld, BlockPos parBlockPos) { - parWorld.playAuxSFX(1022, parBlockPos, 0); - } - public boolean shouldSideBeRendered(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { return true; } - - /**+ - * Possibly modify the given BlockState before rendering it on - * an Entity (Minecarts, Endermen, ...) - */ - public IBlockState getStateForEntityRender(IBlockState state) { - return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int meta) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(meta & 3)).withProperty(DAMAGE, - Integer.valueOf((meta & 15) >> 2)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState state) { - int i = 0; - i = i | ((EnumFacing) state.getValue(FACING)).getHorizontalIndex(); - i = i | ((Integer) state.getValue(DAMAGE)).intValue() << 2; - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, DAMAGE }); - } - - public static class Anvil implements IInteractionObject { - private final World world; - private final BlockPos position; - - public Anvil(World worldIn, BlockPos pos) { - this.world = worldIn; - this.position = pos; - } - - public String getName() { - return "anvil"; - } - - public boolean hasCustomName() { - return false; - } - - public IChatComponent getDisplayName() { - return new ChatComponentTranslation(Blocks.anvil.getUnlocalizedName() + ".name", new Object[0]); - } - - public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) { - return new ContainerRepair(playerInventory, this.world, this.position, playerIn); - } - - public String getGuiID() { - return "minecraft:anvil"; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBanner.java b/src/game/java/net/minecraft/block/BlockBanner.java index 98b881d9..c1074cdb 100644 --- a/src/game/java/net/minecraft/block/BlockBanner.java +++ b/src/game/java/net/minecraft/block/BlockBanner.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -22,138 +21,62 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockBanner extends BlockContainer { - public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); - public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15); - - protected BlockBanner() { - super(Material.wood); - float f = 0.25F; - float f1 = 1.0F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); - } - - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal("item.banner.white.name"); - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - public AxisAlignedBB getSelectedBoundingBox(World worldIn, BlockPos pos) { - this.setBlockBoundsBasedOnState(worldIn, pos); - return super.getSelectedBoundingBox(worldIn, pos); - } - - public boolean isFullCube() { - return false; - } - - public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { - return true; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean func_181623_g() { - return true; - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World worldIn, int meta) { - return new TileEntityBanner(); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState state, EaglercraftRandom rand, int fortune) { - return Items.banner; - } - - public Item getItem(World worldIn, BlockPos pos) { - return Items.banner; - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityBanner) { - ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner) tileentity).getBaseColor()); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - tileentity.writeToNBT(nbttagcompound); - nbttagcompound.removeTag("x"); - nbttagcompound.removeTag("y"); - nbttagcompound.removeTag("z"); - nbttagcompound.removeTag("id"); - itemstack.setTagInfo("BlockEntityTag", nbttagcompound); - spawnAsEntity(world, blockpos, itemstack); - } else { - super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); - } - - } - - public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { - return !this.func_181087_e(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos); - } - - public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te) { - if (te instanceof TileEntityBanner) { - TileEntityBanner tileentitybanner = (TileEntityBanner) te; - ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner) te).getBaseColor()); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - TileEntityBanner.func_181020_a(nbttagcompound, tileentitybanner.getBaseColor(), - tileentitybanner.func_181021_d()); - itemstack.setTagInfo("BlockEntityTag", nbttagcompound); - spawnAsEntity(worldIn, pos, itemstack); - } else { - super.harvestBlock(worldIn, player, pos, state, (TileEntity) null); - } - - } - public static class BlockBannerHanging extends BlockBanner { public BlockBannerHanging() { this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH)); } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + } + + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getFront(i); + if (enumfacing.getAxis() == EnumFacing.Axis.Y) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing); + } + + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (!world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + super.onNeighborBlockChange(world, blockpos, iblockstate, block); + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { EnumFacing enumfacing = (EnumFacing) iblockaccess.getBlockState(blockpos).getValue(FACING); float f = 0.0F; @@ -178,33 +101,6 @@ public class BlockBanner extends BlockContainer { } } - - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (!world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - super.onNeighborBlockChange(world, blockpos, iblockstate, block); - } - - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getFront(i); - if (enumfacing.getAxis() == EnumFacing.Axis.Y) { - enumfacing = EnumFacing.NORTH; - } - - return this.getDefaultState().withProperty(FACING, enumfacing); - } - - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } } public static class BlockBannerStanding extends BlockBanner { @@ -212,6 +108,18 @@ public class BlockBanner extends BlockContainer { this.setDefaultState(this.blockState.getBaseState().withProperty(ROTATION, Integer.valueOf(0))); } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { ROTATION }); + } + + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(ROTATION)).intValue(); + } + + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(ROTATION, Integer.valueOf(i)); + } + public void onNeighborBlockChange(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { if (!worldIn.getBlockState(pos.down()).getBlock().getMaterial().isSolid()) { this.dropBlockAsItem(worldIn, pos, state, 0); @@ -220,17 +128,111 @@ public class BlockBanner extends BlockContainer { super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); } + } - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(ROTATION, Integer.valueOf(i)); + public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); + + public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15); + + protected BlockBanner() { + super(Material.wood); + float f = 0.25F; + float f1 = 1.0F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); + } + + public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { + return !this.func_181087_e(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World worldIn, int meta) { + return new TileEntityBanner(); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityBanner) { + ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner) tileentity).getBaseColor()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + tileentity.writeToNBT(nbttagcompound); + nbttagcompound.removeTag("x"); + nbttagcompound.removeTag("y"); + nbttagcompound.removeTag("z"); + nbttagcompound.removeTag("id"); + itemstack.setTagInfo("BlockEntityTag", nbttagcompound); + spawnAsEntity(world, blockpos, itemstack); + } else { + super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); } - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(ROTATION)).intValue(); + } + + public boolean func_181623_g() { + return true; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + public Item getItem(World worldIn, BlockPos pos) { + return Items.banner; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState state, EaglercraftRandom rand, int fortune) { + return Items.banner; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal("item.banner.white.name"); + } + + public AxisAlignedBB getSelectedBoundingBox(World worldIn, BlockPos pos) { + this.setBlockBoundsBasedOnState(worldIn, pos); + return super.getSelectedBoundingBox(worldIn, pos); + } + + public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity te) { + if (te instanceof TileEntityBanner) { + TileEntityBanner tileentitybanner = (TileEntityBanner) te; + ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner) te).getBaseColor()); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + TileEntityBanner.func_181020_a(nbttagcompound, tileentitybanner.getBaseColor(), + tileentitybanner.func_181021_d()); + itemstack.setTagInfo("BlockEntityTag", nbttagcompound); + spawnAsEntity(worldIn, pos, itemstack); + } else { + super.harvestBlock(worldIn, player, pos, state, (TileEntity) null); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { ROTATION }); - } + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { + return true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBarrier.java b/src/game/java/net/minecraft/block/BlockBarrier.java index a4671f6c..a354b992 100644 --- a/src/game/java/net/minecraft/block/BlockBarrier.java +++ b/src/game/java/net/minecraft/block/BlockBarrier.java @@ -5,22 +5,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,33 +37,32 @@ public class BlockBarrier extends Block { this.translucent = true; } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render + /** + * + Spawns this Block's drops into the World as EntityItems. */ - public int getRenderType() { - return -1; + public void dropBlockAsItemWithChance(World var1, BlockPos var2, IBlockState var3, float var4, int var5) { } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * Returns the default ambient occlusion value based on block - * opacity + /** + * + Returns the default ambient occlusion value based on block opacity */ public float getAmbientOcclusionLightValue() { return 1.0F; } - /**+ - * Spawns this Block's drops into the World as EntityItems. + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render */ - public void dropBlockAsItemWithChance(World var1, BlockPos var2, IBlockState var3, float var4, int var5) { + public int getRenderType() { + return -1; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBasePressurePlate.java b/src/game/java/net/minecraft/block/BlockBasePressurePlate.java index e1eea80b..e88bb9d3 100644 --- a/src/game/java/net/minecraft/block/BlockBasePressurePlate.java +++ b/src/game/java/net/minecraft/block/BlockBasePressurePlate.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -13,22 +12,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +46,111 @@ public abstract class BlockBasePressurePlate extends Block { this.setTickRandomly(true); } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + if (this.getRedstoneStrength(iblockstate) > 0) { + this.updateNeighbors(world, blockpos); + } + + super.breakBlock(world, blockpos, iblockstate); + } + + private boolean canBePlacedOn(World worldIn, BlockPos pos) { + return World.doesBlockHaveSolidTopSurface(worldIn, pos) + || worldIn.getBlockState(pos).getBlock() instanceof BlockFence; + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return this.canBePlacedOn(world, blockpos.down()); + } + + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. + */ + public boolean canProvidePower() { + return true; + } + + protected abstract int computeRedstoneStrength(World var1, BlockPos var2); + + public boolean func_181623_g() { + return true; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + public int getMobilityFlag() { + return 1; + } + + protected abstract int getRedstoneStrength(IBlockState var1); + + /** + * + Returns the cubic AABB inset by 1/8 on all sides + */ + protected AxisAlignedBB getSensitiveAABB(BlockPos pos) { + float f = 0.125F; + return new AxisAlignedBB((double) ((float) pos.getX() + 0.125F), (double) pos.getY(), + (double) ((float) pos.getZ() + 0.125F), (double) ((float) (pos.getX() + 1) - 0.125F), + (double) pos.getY() + 0.25D, (double) ((float) (pos.getZ() + 1) - 0.125F)); + } + + public int getStrongPower(IBlockAccess worldIn, BlockPos pos, IBlockState state, EnumFacing side) { + return side == EnumFacing.UP ? this.getRedstoneStrength(state) : 0; + } + + public int getWeakPower(IBlockAccess worldIn, BlockPos pos, IBlockState state, EnumFacing side) { + return this.getRedstoneStrength(state); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean isPassable(IBlockAccess var1, BlockPos var2) { + return true; + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { + if (!worldIn.isRemote) { + int i = this.getRedstoneStrength(state); + if (i == 0) { + this.updateState(worldIn, pos, state, i); + } + } + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!this.canBePlacedOn(world, blockpos.down())) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + } + + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) + */ + public void randomTick(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom random) { + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { this.setBlockBoundsBasedOnState0(iblockaccess.getBlockState(blockpos)); } @@ -59,87 +166,35 @@ public abstract class BlockBasePressurePlate extends Block { } - /**+ - * How many world ticks before ticking + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + float f = 0.5F; + float f1 = 0.125F; + float f2 = 0.5F; + this.setBlockBounds(0.0F, 0.375F, 0.0F, 1.0F, 0.625F, 1.0F); + } + + protected abstract IBlockState setRedstoneStrength(IBlockState var1, int var2); + + /** + * + How many world ticks before ticking */ public int tickRate(World worldIn) { return 20; } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Notify block and block below of changes */ - public boolean isOpaqueCube() { - return false; + protected void updateNeighbors(World worldIn, BlockPos pos) { + worldIn.notifyNeighborsOfStateChange(pos, this); + worldIn.notifyNeighborsOfStateChange(pos.down(), this); } - public boolean isFullCube() { - return false; - } - - public boolean isPassable(IBlockAccess var1, BlockPos var2) { - return true; - } - - public boolean func_181623_g() { - return true; - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return this.canBePlacedOn(world, blockpos.down()); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (!this.canBePlacedOn(world, blockpos.down())) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - } - - private boolean canBePlacedOn(World worldIn, BlockPos pos) { - return World.doesBlockHaveSolidTopSurface(worldIn, pos) - || worldIn.getBlockState(pos).getBlock() instanceof BlockFence; - } - - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) - */ - public void randomTick(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom random) { - } - - public void updateTick(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { - if (!worldIn.isRemote) { - int i = this.getRedstoneStrength(state); - if (i > 0) { - this.updateState(worldIn, pos, state, i); - } - } - } - - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn) { - if (!worldIn.isRemote) { - int i = this.getRedstoneStrength(state); - if (i == 0) { - this.updateState(worldIn, pos, state, i); - } - } - } - - /**+ - * Updates the pressure plate when stepped on + /** + * + Updates the pressure plate when stepped on */ protected void updateState(World worldIn, BlockPos pos, IBlockState state, int oldRedstoneStrength) { int i = this.computeRedstoneStrength(worldIn, pos); @@ -166,65 +221,12 @@ public abstract class BlockBasePressurePlate extends Block { } - /**+ - * Returns the cubic AABB inset by 1/8 on all sides - */ - protected AxisAlignedBB getSensitiveAABB(BlockPos pos) { - float f = 0.125F; - return new AxisAlignedBB((double) ((float) pos.getX() + 0.125F), (double) pos.getY(), - (double) ((float) pos.getZ() + 0.125F), (double) ((float) (pos.getX() + 1) - 0.125F), - (double) pos.getY() + 0.25D, (double) ((float) (pos.getZ() + 1) - 0.125F)); - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - if (this.getRedstoneStrength(iblockstate) > 0) { - this.updateNeighbors(world, blockpos); + public void updateTick(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { + if (!worldIn.isRemote) { + int i = this.getRedstoneStrength(state); + if (i > 0) { + this.updateState(worldIn, pos, state, i); + } } - - super.breakBlock(world, blockpos, iblockstate); } - - /**+ - * Notify block and block below of changes - */ - protected void updateNeighbors(World worldIn, BlockPos pos) { - worldIn.notifyNeighborsOfStateChange(pos, this); - worldIn.notifyNeighborsOfStateChange(pos.down(), this); - } - - public int getWeakPower(IBlockAccess worldIn, BlockPos pos, IBlockState state, EnumFacing side) { - return this.getRedstoneStrength(state); - } - - public int getStrongPower(IBlockAccess worldIn, BlockPos pos, IBlockState state, EnumFacing side) { - return side == EnumFacing.UP ? this.getRedstoneStrength(state) : 0; - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return true; - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - float f = 0.5F; - float f1 = 0.125F; - float f2 = 0.5F; - this.setBlockBounds(0.0F, 0.375F, 0.0F, 1.0F, 0.625F, 1.0F); - } - - public int getMobilityFlag() { - return 1; - } - - protected abstract int computeRedstoneStrength(World var1, BlockPos var2); - - protected abstract int getRedstoneStrength(IBlockState var1); - - protected abstract IBlockState setRedstoneStrength(IBlockState var1, int var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBeacon.java b/src/game/java/net/minecraft/block/BlockBeacon.java index 1d8cb134..e66b5b2a 100644 --- a/src/game/java/net/minecraft/block/BlockBeacon.java +++ b/src/game/java/net/minecraft/block/BlockBeacon.java @@ -18,105 +18,30 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockBeacon extends BlockContainer { - public BlockBeacon() { - super(Material.glass, MapColor.diamondColor); - this.setHardness(3.0F); - this.setCreativeTab(CreativeTabs.tabMisc); - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityBeacon(); - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (!world.isRemote) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityBeacon) { - entityplayer.displayGUIChest((TileEntityBeacon) tileentity); - entityplayer.triggerAchievement(StatList.field_181730_N); - } - } - return true; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, - ItemStack stack) { - super.onBlockPlacedBy(worldIn, pos, state, placer, stack); - if (stack.hasDisplayName()) { - TileEntity tileentity = worldIn.getTileEntity(pos); - if (tileentity instanceof TileEntityBeacon) { - ((TileEntityBeacon) tileentity).setName(stack.getDisplayName()); - } - } - - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityBeacon) { - ((TileEntityBeacon) tileentity).updateBeacon(); - world.addBlockEvent(blockpos, this, 1, 0); - } - - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - public static void updateColorAsync(final World worldIn, final BlockPos glassPos) { Chunk chunk = worldIn.getChunkFromBlockCoords(glassPos); @@ -140,4 +65,82 @@ public class BlockBeacon extends BlockContainer { } } } + + public BlockBeacon() { + super(Material.glass, MapColor.diamondColor); + this.setHardness(3.0F); + this.setCreativeTab(CreativeTabs.tabMisc); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityBeacon(); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (!world.isRemote) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityBeacon) { + entityplayer.displayGUIChest((TileEntityBeacon) tileentity); + entityplayer.triggerAchievement(StatList.field_181730_N); + } + } + return true; + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, + ItemStack stack) { + super.onBlockPlacedBy(worldIn, pos, state, placer, stack); + if (stack.hasDisplayName()) { + TileEntity tileentity = worldIn.getTileEntity(pos); + if (tileentity instanceof TileEntityBeacon) { + ((TileEntityBeacon) tileentity).setName(stack.getDisplayName()); + } + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityBeacon) { + ((TileEntityBeacon) tileentity).updateBeacon(); + world.addBlockEvent(blockpos, this, 1, 0); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBed.java b/src/game/java/net/minecraft/block/BlockBed.java index 9da87163..d57e7422 100644 --- a/src/game/java/net/minecraft/block/BlockBed.java +++ b/src/game/java/net/minecraft/block/BlockBed.java @@ -3,7 +3,6 @@ package net.minecraft.block; import java.util.List; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -24,30 +23,94 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockBed extends BlockDirectional { + public static enum EnumPartType implements IStringSerializable { + HEAD("head"), FOOT("foot"); + + private final String name; + + private EnumPartType(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static PropertyEnum PART; + public static final PropertyBool OCCUPIED = PropertyBool.create("occupied"); + public static void bootstrapStates() { + PART = PropertyEnum.create("part", BlockBed.EnumPartType.class); + } + + /** + * + Returns a safe BlockPos to disembark the bed + */ + public static BlockPos getSafeExitLocation(World worldIn, BlockPos pos, int tries) { + EnumFacing enumfacing = (EnumFacing) worldIn.getBlockState(pos).getValue(FACING); + int i = pos.getX(); + int j = pos.getY(); + int k = pos.getZ(); + + for (int l = 0; l <= 1; ++l) { + int i1 = i - enumfacing.getFrontOffsetX() * l - 1; + int j1 = k - enumfacing.getFrontOffsetZ() * l - 1; + int k1 = i1 + 2; + int l1 = j1 + 2; + + for (int i2 = i1; i2 <= k1; ++i2) { + for (int j2 = j1; j2 <= l1; ++j2) { + BlockPos blockpos = new BlockPos(i2, j, j2); + if (hasRoomForPlayer(worldIn, blockpos)) { + if (tries <= 0) { + return blockpos; + } + + --tries; + } + } + } + } + + return null; + } + + protected static boolean hasRoomForPlayer(World worldIn, BlockPos pos) { + return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) + && !worldIn.getBlockState(pos).getBlock().getMaterial().isSolid() + && !worldIn.getBlockState(pos.up()).getBlock().getMaterial().isSolid(); + } + public BlockBed() { super(Material.cloth); this.setDefaultState(this.blockState.getBaseState().withProperty(PART, BlockBed.EnumPartType.FOOT) @@ -55,8 +118,104 @@ public class BlockBed extends BlockDirectional { this.setBedBounds(); } - public static void bootstrapStates() { - PART = PropertyEnum.create("part", BlockBed.EnumPartType.class); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, PART, OCCUPIED }); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int var5) { + if (iblockstate.getValue(PART) == BlockBed.EnumPartType.FOOT) { + super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, 0); + } + + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { + if (state.getValue(PART) == BlockBed.EnumPartType.FOOT) { + IBlockState iblockstate = worldIn.getBlockState(pos.offset((EnumFacing) state.getValue(FACING))); + if (iblockstate.getBlock() == this) { + state = state.withProperty(OCCUPIED, iblockstate.getValue(OCCUPIED)); + } + } + + return state; + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public Item getItem(World var1, BlockPos var2) { + return Items.bed; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { + return iblockstate.getValue(PART) == BlockBed.EnumPartType.HEAD ? null : Items.bed; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + if (iblockstate.getValue(PART) == BlockBed.EnumPartType.HEAD) { + i |= 8; + if (((Boolean) iblockstate.getValue(OCCUPIED)).booleanValue()) { + i |= 4; + } + } + + return i; + } + + public int getMobilityFlag() { + return 1; + } + + private EntityPlayer getPlayerInBed(World worldIn, BlockPos pos) { + List playerEntities = worldIn.playerEntities; + for (int i = 0, l = playerEntities.size(); i < l; ++i) { + EntityPlayer entityplayer = playerEntities.get(i); + if (entityplayer.isPlayerSleeping() && entityplayer.playerLocation.equals(pos)) { + return entityplayer; + } + } + + return null; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getHorizontal(i); + return (i & 8) > 0 + ? this.getDefaultState().withProperty(PART, BlockBed.EnumPartType.HEAD).withProperty(FACING, enumfacing) + .withProperty(OCCUPIED, Boolean.valueOf((i & 4) > 0)) + : this.getDefaultState().withProperty(PART, BlockBed.EnumPartType.FOOT).withProperty(FACING, + enumfacing); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, @@ -130,36 +289,18 @@ public class BlockBed extends BlockDirectional { } } - private EntityPlayer getPlayerInBed(World worldIn, BlockPos pos) { - List playerEntities = worldIn.playerEntities; - for (int i = 0, l = playerEntities.size(); i < l; ++i) { - EntityPlayer entityplayer = playerEntities.get(i); - if (entityplayer.isPlayerSleeping() && entityplayer.playerLocation.equals(pos)) { - return entityplayer; + public void onBlockHarvested(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player) { + if (player.capabilities.isCreativeMode && state.getValue(PART) == BlockBed.EnumPartType.HEAD) { + BlockPos blockpos = pos.offset(((EnumFacing) state.getValue(FACING)).getOpposite()); + if (worldIn.getBlockState(blockpos).getBlock() == this) { + worldIn.setBlockToAir(blockpos); } } - return null; } - public boolean isFullCube() { - return false; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - this.setBedBounds(); - } - - /**+ - * Called when a neighboring block changes. + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); @@ -176,150 +317,11 @@ public class BlockBed extends BlockDirectional { } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { - return iblockstate.getValue(PART) == BlockBed.EnumPartType.HEAD ? null : Items.bed; - } - private void setBedBounds() { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5625F, 1.0F); } - /**+ - * Returns a safe BlockPos to disembark the bed - */ - public static BlockPos getSafeExitLocation(World worldIn, BlockPos pos, int tries) { - EnumFacing enumfacing = (EnumFacing) worldIn.getBlockState(pos).getValue(FACING); - int i = pos.getX(); - int j = pos.getY(); - int k = pos.getZ(); - - for (int l = 0; l <= 1; ++l) { - int i1 = i - enumfacing.getFrontOffsetX() * l - 1; - int j1 = k - enumfacing.getFrontOffsetZ() * l - 1; - int k1 = i1 + 2; - int l1 = j1 + 2; - - for (int i2 = i1; i2 <= k1; ++i2) { - for (int j2 = j1; j2 <= l1; ++j2) { - BlockPos blockpos = new BlockPos(i2, j, j2); - if (hasRoomForPlayer(worldIn, blockpos)) { - if (tries <= 0) { - return blockpos; - } - - --tries; - } - } - } - } - - return null; - } - - protected static boolean hasRoomForPlayer(World worldIn, BlockPos pos) { - return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()) - && !worldIn.getBlockState(pos).getBlock().getMaterial().isSolid() - && !worldIn.getBlockState(pos.up()).getBlock().getMaterial().isSolid(); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int var5) { - if (iblockstate.getValue(PART) == BlockBed.EnumPartType.FOOT) { - super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, 0); - } - - } - - public int getMobilityFlag() { - return 1; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.bed; - } - - public void onBlockHarvested(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player) { - if (player.capabilities.isCreativeMode && state.getValue(PART) == BlockBed.EnumPartType.HEAD) { - BlockPos blockpos = pos.offset(((EnumFacing) state.getValue(FACING)).getOpposite()); - if (worldIn.getBlockState(blockpos).getBlock() == this) { - worldIn.setBlockToAir(blockpos); - } - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getHorizontal(i); - return (i & 8) > 0 - ? this.getDefaultState().withProperty(PART, BlockBed.EnumPartType.HEAD).withProperty(FACING, enumfacing) - .withProperty(OCCUPIED, Boolean.valueOf((i & 4) > 0)) - : this.getDefaultState().withProperty(PART, BlockBed.EnumPartType.FOOT).withProperty(FACING, - enumfacing); - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - if (state.getValue(PART) == BlockBed.EnumPartType.FOOT) { - IBlockState iblockstate = worldIn.getBlockState(pos.offset((EnumFacing) state.getValue(FACING))); - if (iblockstate.getBlock() == this) { - state = state.withProperty(OCCUPIED, iblockstate.getValue(OCCUPIED)); - } - } - - return state; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - if (iblockstate.getValue(PART) == BlockBed.EnumPartType.HEAD) { - i |= 8; - if (((Boolean) iblockstate.getValue(OCCUPIED)).booleanValue()) { - i |= 4; - } - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, PART, OCCUPIED }); - } - - public static enum EnumPartType implements IStringSerializable { - HEAD("head"), FOOT("foot"); - - private final String name; - - private EnumPartType(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + this.setBedBounds(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBookshelf.java b/src/game/java/net/minecraft/block/BlockBookshelf.java index f9c8611a..7d44d105 100644 --- a/src/game/java/net/minecraft/block/BlockBookshelf.java +++ b/src/game/java/net/minecraft/block/BlockBookshelf.java @@ -1,29 +1,31 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,17 +36,17 @@ public class BlockBookshelf extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 3; - } - - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Items.book; } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 3; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBreakable.java b/src/game/java/net/minecraft/block/BlockBreakable.java index 6a2ee86f..ba37383e 100644 --- a/src/game/java/net/minecraft/block/BlockBreakable.java +++ b/src/game/java/net/minecraft/block/BlockBreakable.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,9 +43,9 @@ public class BlockBreakable extends Block { this.ignoreSimilarity = parFlag; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; diff --git a/src/game/java/net/minecraft/block/BlockBrewingStand.java b/src/game/java/net/minecraft/block/BlockBrewingStand.java index cfdbd9be..32177bfc 100644 --- a/src/game/java/net/minecraft/block/BlockBrewingStand.java +++ b/src/game/java/net/minecraft/block/BlockBrewingStand.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -27,22 +27,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -58,45 +61,9 @@ public class BlockBrewingStand extends BlockContainer { .withProperty(HAS_BOTTLE[2], Boolean.valueOf(false))); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal("item.brewingStand.name"); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityBrewingStand(); - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -106,11 +73,103 @@ public class BlockBrewingStand extends BlockContainer { super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); } - /**+ - * Sets the block's bounds for rendering it as an item + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityBrewingStand) { + InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityBrewingStand) tileentity); + } + + super.breakBlock(world, blockpos, iblockstate); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { HAS_BOTTLE[0], HAS_BOTTLE[1], HAS_BOTTLE[2] }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ - public void setBlockBoundsForItemRender() { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityBrewingStand(); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return Container.calcRedstone(world.getTileEntity(blockpos)); + } + + public Item getItem(World var1, BlockPos var2) { + return Items.brewing_stand; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.brewing_stand; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal("item.brewingStand.name"); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + + for (int j = 0; j < 3; ++j) { + if (((Boolean) iblockstate.getValue(HAS_BOTTLE[j])).booleanValue()) { + i |= 1 << j; + } + } + + return i; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + IBlockState iblockstate = this.getDefaultState(); + + for (int j = 0; j < 3; ++j) { + iblockstate = iblockstate.withProperty(HAS_BOTTLE[j], Boolean.valueOf((i & 1 << j) > 0)); + } + + return iblockstate; + } + + public boolean hasComparatorInputOverride() { + return true; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, @@ -125,9 +184,9 @@ public class BlockBrewingStand extends BlockContainer { return true; } - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic */ public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState var3, EntityLivingBase var4, ItemStack itemstack) { @@ -147,67 +206,10 @@ public class BlockBrewingStand extends BlockContainer { world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); } - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityBrewingStand) { - InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityBrewingStand) tileentity); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Sets the block's bounds for rendering it as an item */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.brewing_stand; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.brewing_stand; - } - - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return Container.calcRedstone(world.getTileEntity(blockpos)); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - IBlockState iblockstate = this.getDefaultState(); - - for (int j = 0; j < 3; ++j) { - iblockstate = iblockstate.withProperty(HAS_BOTTLE[j], Boolean.valueOf((i & 1 << j) > 0)); - } - - return iblockstate; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - - for (int j = 0; j < 3; ++j) { - if (((Boolean) iblockstate.getValue(HAS_BOTTLE[j])).booleanValue()) { - i |= 1 << j; - } - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { HAS_BOTTLE[0], HAS_BOTTLE[1], HAS_BOTTLE[2] }); + public void setBlockBoundsForItemRender() { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockBush.java b/src/game/java/net/minecraft/block/BlockBush.java index 77c396ad..48214e14 100644 --- a/src/game/java/net/minecraft/block/BlockBush.java +++ b/src/game/java/net/minecraft/block/BlockBush.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -12,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,30 +51,22 @@ public class BlockBush extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } + public boolean canBlockStay(World worldIn, BlockPos pos, IBlockState state) { + return this.canPlaceBlockOn(worldIn.getBlockState(pos.down()).getBlock()); + } + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { return super.canPlaceBlockAt(world, blockpos) && this.canPlaceBlockOn(world.getBlockState(blockpos.down()).getBlock()); } - /**+ - * is the block grass, dirt or farmland + /** + * + is the block grass, dirt or farmland */ protected boolean canPlaceBlockOn(Block ground) { return ground == Blocks.grass || ground == Blocks.dirt || ground == Blocks.farmland; } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - super.onNeighborBlockChange(world, blockpos, iblockstate, block); - this.checkAndDropBlock(world, blockpos, iblockstate); - } - - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - this.checkAndDropBlock(world, blockpos, iblockstate); - } - protected void checkAndDropBlock(World worldIn, BlockPos pos, IBlockState state) { if (!this.canBlockStay(worldIn, pos, state)) { this.dropBlockAsItem(worldIn, pos, state, 0); @@ -81,27 +75,35 @@ public class BlockBush extends Block { } - public boolean canBlockStay(World worldIn, BlockPos pos, IBlockState state) { - return this.canPlaceBlockOn(worldIn.getBlockState(pos.down()).getBlock()); + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; } public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { return null; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; } - public boolean isFullCube() { - return false; + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + super.onNeighborBlockChange(world, blockpos, iblockstate, block); + this.checkAndDropBlock(world, blockpos, iblockstate); } - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { + this.checkAndDropBlock(world, blockpos, iblockstate); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockButton.java b/src/game/java/net/minecraft/block/BlockButton.java index 05924464..811474ae 100644 --- a/src/game/java/net/minecraft/block/BlockButton.java +++ b/src/game/java/net/minecraft/block/BlockButton.java @@ -1,6 +1,7 @@ package net.minecraft.block; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -19,22 +20,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,6 +46,13 @@ import net.minecraft.world.World; public abstract class BlockButton extends Block { public static final PropertyDirection FACING = PropertyDirection.create("facing"); public static final PropertyBool POWERED = PropertyBool.create("powered"); + + protected static boolean func_181088_a(World parWorld, BlockPos parBlockPos, EnumFacing parEnumFacing) { + BlockPos blockpos = parBlockPos.offset(parEnumFacing); + return parEnumFacing == EnumFacing.DOWN ? World.doesBlockHaveSolidTopSurface(parWorld, blockpos) + : parWorld.getBlockState(blockpos).getBlock().isNormalCube(); + } + private final boolean wooden; protected BlockButton(boolean wooden) { @@ -53,34 +64,12 @@ public abstract class BlockButton extends Block { this.wooden = wooden; } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + this.notifyNeighbors(world, blockpos, (EnumFacing) iblockstate.getValue(FACING)); + } - /**+ - * How many world ticks before ticking - */ - public int tickRate(World var1) { - return this.wooden ? 30 : 20; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { - return func_181088_a(world, blockpos, enumfacing.getOpposite()); + super.breakBlock(world, blockpos, iblockstate); } public boolean canPlaceBlockAt(World world, BlockPos blockpos) { @@ -95,166 +84,21 @@ public abstract class BlockButton extends Block { return false; } - protected static boolean func_181088_a(World parWorld, BlockPos parBlockPos, EnumFacing parEnumFacing) { - BlockPos blockpos = parBlockPos.offset(parEnumFacing); - return parEnumFacing == EnumFacing.DOWN ? World.doesBlockHaveSolidTopSurface(parWorld, blockpos) - : parWorld.getBlockState(blockpos).getBlock().isNormalCube(); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + /** + * + Check whether this Block can be placed on the given side */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase var8) { - return func_181088_a(world, blockpos, enumfacing.getOpposite()) - ? this.getDefaultState().withProperty(FACING, enumfacing).withProperty(POWERED, Boolean.valueOf(false)) - : this.getDefaultState().withProperty(FACING, EnumFacing.DOWN).withProperty(POWERED, - Boolean.valueOf(false)); + public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { + return func_181088_a(world, blockpos, enumfacing.getOpposite()); } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (this.checkForDrop(world, blockpos, iblockstate) - && !func_181088_a(world, blockpos, ((EnumFacing) iblockstate.getValue(FACING)).getOpposite())) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - } - - private boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { - if (this.canPlaceBlockAt(worldIn, pos)) { - return true; - } else { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - return false; - } - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - this.updateBlockBounds(iblockaccess.getBlockState(blockpos)); - } - - private void updateBlockBounds(IBlockState state) { - EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); - boolean flag = ((Boolean) state.getValue(POWERED)).booleanValue(); - float f = 0.25F; - float f1 = 0.375F; - float f2 = (float) (flag ? 1 : 2) / 16.0F; - float f3 = 0.125F; - float f4 = 0.1875F; - switch (enumfacing) { - case EAST: - this.setBlockBounds(0.0F, 0.375F, 0.3125F, f2, 0.625F, 0.6875F); - break; - case WEST: - this.setBlockBounds(1.0F - f2, 0.375F, 0.3125F, 1.0F, 0.625F, 0.6875F); - break; - case SOUTH: - this.setBlockBounds(0.3125F, 0.375F, 0.0F, 0.6875F, 0.625F, f2); - break; - case NORTH: - this.setBlockBounds(0.3125F, 0.375F, 1.0F - f2, 0.6875F, 0.625F, 1.0F); - break; - case UP: - this.setBlockBounds(0.3125F, 0.0F, 0.375F, 0.6875F, 0.0F + f2, 0.625F); - break; - case DOWN: - this.setBlockBounds(0.3125F, 1.0F - f2, 0.375F, 0.6875F, 1.0F, 0.625F); - } - - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, - EnumFacing var5, float var6, float var7, float var8) { - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - return true; - } else { - world.setBlockState(blockpos, iblockstate.withProperty(POWERED, Boolean.valueOf(true)), 3); - world.markBlockRangeForRenderUpdate(blockpos, blockpos); - world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, - (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, 0.6F); - this.notifyNeighbors(world, blockpos, (EnumFacing) iblockstate.getValue(FACING)); - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - return true; - } - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - this.notifyNeighbors(world, blockpos, (EnumFacing) iblockstate.getValue(FACING)); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { - return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; - } - - public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { - return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 - : (iblockstate.getValue(FACING) == enumfacing ? 15 : 0); - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. */ public boolean canProvidePower() { return true; } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) - */ - public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { - } - - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - if (!world.isRemote) { - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - if (this.wooden) { - this.checkForArrows(world, blockpos, iblockstate); - } else { - world.setBlockState(blockpos, iblockstate.withProperty(POWERED, Boolean.valueOf(false))); - this.notifyNeighbors(world, blockpos, (EnumFacing) iblockstate.getValue(FACING)); - world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, - (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, 0.5F); - world.markBlockRangeForRenderUpdate(blockpos, blockpos); - } - } - } - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - float f = 0.1875F; - float f1 = 0.125F; - float f2 = 0.125F; - this.setBlockBounds(0.5F - f, 0.5F - f1, 0.5F - f2, 0.5F + f, 0.5F + f1, 0.5F + f2); - } - - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState iblockstate, Entity var4) { - if (!world.isRemote) { - if (this.wooden) { - if (!((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - this.checkForArrows(world, blockpos, iblockstate); - } - } - } - } - private void checkForArrows(World worldIn, BlockPos pos, IBlockState state) { this.updateBlockBounds(state); List list = worldIn.getEntitiesWithinAABB(EntityArrow.class, @@ -285,43 +129,26 @@ public abstract class BlockButton extends Block { } - private void notifyNeighbors(World worldIn, BlockPos pos, EnumFacing facing) { - worldIn.notifyNeighborsOfStateChange(pos, this); - worldIn.notifyNeighborsOfStateChange(pos.offset(facing.getOpposite()), this); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing; - switch (i & 7) { - case 0: - enumfacing = EnumFacing.DOWN; - break; - case 1: - enumfacing = EnumFacing.EAST; - break; - case 2: - enumfacing = EnumFacing.WEST; - break; - case 3: - enumfacing = EnumFacing.SOUTH; - break; - case 4: - enumfacing = EnumFacing.NORTH; - break; - case 5: - default: - enumfacing = EnumFacing.UP; + private boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { + if (this.canPlaceBlockAt(worldIn, pos)) { + return true; + } else { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + return false; } - - return this.getDefaultState().withProperty(FACING, enumfacing).withProperty(POWERED, - Boolean.valueOf((i & 8) > 0)); } - /**+ - * Convert the BlockState into the correct metadata value + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, POWERED }); + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i; @@ -353,7 +180,185 @@ public abstract class BlockButton extends Block { return i; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, POWERED }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing; + switch (i & 7) { + case 0: + enumfacing = EnumFacing.DOWN; + break; + case 1: + enumfacing = EnumFacing.EAST; + break; + case 2: + enumfacing = EnumFacing.WEST; + break; + case 3: + enumfacing = EnumFacing.SOUTH; + break; + case 4: + enumfacing = EnumFacing.NORTH; + break; + case 5: + default: + enumfacing = EnumFacing.UP; + } + + return this.getDefaultState().withProperty(FACING, enumfacing).withProperty(POWERED, + Boolean.valueOf((i & 8) > 0)); + } + + public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { + return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 + : (iblockstate.getValue(FACING) == enumfacing ? 15 : 0); + } + + public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { + return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + private void notifyNeighbors(World worldIn, BlockPos pos, EnumFacing facing) { + worldIn.notifyNeighborsOfStateChange(pos, this); + worldIn.notifyNeighborsOfStateChange(pos.offset(facing.getOpposite()), this); + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, + EnumFacing var5, float var6, float var7, float var8) { + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + return true; + } else { + world.setBlockState(blockpos, iblockstate.withProperty(POWERED, Boolean.valueOf(true)), 3); + world.markBlockRangeForRenderUpdate(blockpos, blockpos); + world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, + (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, 0.6F); + this.notifyNeighbors(world, blockpos, (EnumFacing) iblockstate.getValue(FACING)); + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + return true; + } + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase var8) { + return func_181088_a(world, blockpos, enumfacing.getOpposite()) + ? this.getDefaultState().withProperty(FACING, enumfacing).withProperty(POWERED, Boolean.valueOf(false)) + : this.getDefaultState().withProperty(FACING, EnumFacing.DOWN).withProperty(POWERED, + Boolean.valueOf(false)); + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState iblockstate, Entity var4) { + if (!world.isRemote) { + if (this.wooden) { + if (!((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + this.checkForArrows(world, blockpos, iblockstate); + } + } + } + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (this.checkForDrop(world, blockpos, iblockstate) + && !func_181088_a(world, blockpos, ((EnumFacing) iblockstate.getValue(FACING)).getOpposite())) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + } + + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) + */ + public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + this.updateBlockBounds(iblockaccess.getBlockState(blockpos)); + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + float f = 0.1875F; + float f1 = 0.125F; + float f2 = 0.125F; + this.setBlockBounds(0.5F - f, 0.5F - f1, 0.5F - f2, 0.5F + f, 0.5F + f1, 0.5F + f2); + } + + /** + * + How many world ticks before ticking + */ + public int tickRate(World var1) { + return this.wooden ? 30 : 20; + } + + private void updateBlockBounds(IBlockState state) { + EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); + boolean flag = ((Boolean) state.getValue(POWERED)).booleanValue(); + float f = 0.25F; + float f1 = 0.375F; + float f2 = (float) (flag ? 1 : 2) / 16.0F; + float f3 = 0.125F; + float f4 = 0.1875F; + switch (enumfacing) { + case EAST: + this.setBlockBounds(0.0F, 0.375F, 0.3125F, f2, 0.625F, 0.6875F); + break; + case WEST: + this.setBlockBounds(1.0F - f2, 0.375F, 0.3125F, 1.0F, 0.625F, 0.6875F); + break; + case SOUTH: + this.setBlockBounds(0.3125F, 0.375F, 0.0F, 0.6875F, 0.625F, f2); + break; + case NORTH: + this.setBlockBounds(0.3125F, 0.375F, 1.0F - f2, 0.6875F, 0.625F, 1.0F); + break; + case UP: + this.setBlockBounds(0.3125F, 0.0F, 0.375F, 0.6875F, 0.0F + f2, 0.625F); + break; + case DOWN: + this.setBlockBounds(0.3125F, 1.0F - f2, 0.375F, 0.6875F, 1.0F, 0.625F); + } + + } + + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { + if (!world.isRemote) { + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + if (this.wooden) { + this.checkForArrows(world, blockpos, iblockstate); + } else { + world.setBlockState(blockpos, iblockstate.withProperty(POWERED, Boolean.valueOf(false))); + this.notifyNeighbors(world, blockpos, (EnumFacing) iblockstate.getValue(FACING)); + world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, + (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, 0.5F); + world.markBlockRangeForRenderUpdate(blockpos, blockpos); + } + } + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockButtonStone.java b/src/game/java/net/minecraft/block/BlockButtonStone.java index 24b8efdb..d9a73ae7 100644 --- a/src/game/java/net/minecraft/block/BlockButtonStone.java +++ b/src/game/java/net/minecraft/block/BlockButtonStone.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockButtonWood.java b/src/game/java/net/minecraft/block/BlockButtonWood.java index 5d8f7f1e..53a34df5 100644 --- a/src/game/java/net/minecraft/block/BlockButtonWood.java +++ b/src/game/java/net/minecraft/block/BlockButtonWood.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockCactus.java b/src/game/java/net/minecraft/block/BlockCactus.java index 7989fecd..5d8b712e 100644 --- a/src/game/java/net/minecraft/block/BlockCactus.java +++ b/src/game/java/net/minecraft/block/BlockCactus.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -17,22 +16,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,6 +49,88 @@ public class BlockCactus extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } + public boolean canBlockStay(World worldIn, BlockPos pos) { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getMaterial().isSolid()) { + return false; + } + } + + Block block = worldIn.getBlockState(pos.down()).getBlock(); + return block == Blocks.cactus || block == Blocks.sand; + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return super.canPlaceBlockAt(world, blockpos) ? this.canBlockStay(world, blockpos) : false; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AGE }); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { + float f = 0.0625F; + return new AxisAlignedBB((double) ((float) blockpos.getX() + f), (double) blockpos.getY(), + (double) ((float) blockpos.getZ() + f), (double) ((float) (blockpos.getX() + 1) - f), + (double) ((float) (blockpos.getY() + 1) - f), (double) ((float) (blockpos.getZ() + 1) - f)); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(AGE)).intValue(); + } + + public AxisAlignedBB getSelectedBoundingBox(World var1, BlockPos blockpos) { + float f = 0.0625F; + return new AxisAlignedBB((double) ((float) blockpos.getX() + f), (double) blockpos.getY(), + (double) ((float) blockpos.getZ() + f), (double) ((float) (blockpos.getX() + 1) - f), + (double) (blockpos.getY() + 1), (double) ((float) (blockpos.getZ() + 1) - f)); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity entity) { + entity.attackEntityFrom(DamageSource.cactus, 1.0F); + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + if (!this.canBlockStay(world, blockpos)) { + world.destroyBlock(blockpos, true); + } + + } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { BlockPos blockpos1 = blockpos.up(); if (world.isAirBlock(blockpos1)) { @@ -69,86 +153,4 @@ public class BlockCactus extends Block { } } } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { - float f = 0.0625F; - return new AxisAlignedBB((double) ((float) blockpos.getX() + f), (double) blockpos.getY(), - (double) ((float) blockpos.getZ() + f), (double) ((float) (blockpos.getX() + 1) - f), - (double) ((float) (blockpos.getY() + 1) - f), (double) ((float) (blockpos.getZ() + 1) - f)); - } - - public AxisAlignedBB getSelectedBoundingBox(World var1, BlockPos blockpos) { - float f = 0.0625F; - return new AxisAlignedBB((double) ((float) blockpos.getX() + f), (double) blockpos.getY(), - (double) ((float) blockpos.getZ() + f), (double) ((float) (blockpos.getX() + 1) - f), - (double) (blockpos.getY() + 1), (double) ((float) (blockpos.getZ() + 1) - f)); - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return super.canPlaceBlockAt(world, blockpos) ? this.canBlockStay(world, blockpos) : false; - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - if (!this.canBlockStay(world, blockpos)) { - world.destroyBlock(blockpos, true); - } - - } - - public boolean canBlockStay(World worldIn, BlockPos pos) { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getMaterial().isSolid()) { - return false; - } - } - - Block block = worldIn.getBlockState(pos.down()).getBlock(); - return block == Blocks.cactus || block == Blocks.sand; - } - - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity entity) { - entity.attackEntityFrom(DamageSource.cactus, 1.0F); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(AGE)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AGE }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockCake.java b/src/game/java/net/minecraft/block/BlockCake.java index a19e2dc5..42628c89 100644 --- a/src/game/java/net/minecraft/block/BlockCake.java +++ b/src/game/java/net/minecraft/block/BlockCake.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -18,22 +17,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,56 +49,16 @@ public class BlockCake extends Block { this.setTickRandomly(true); } - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - float f = 0.0625F; - float f1 = (float) (1 + ((Integer) iblockaccess.getBlockState(blockpos).getValue(BITES)).intValue() * 2) - / 16.0F; - float f2 = 0.5F; - this.setBlockBounds(f1, 0.0F, f, 1.0F - f, f2, 1.0F - f); + private boolean canBlockStay(World worldIn, BlockPos pos) { + return worldIn.getBlockState(pos.down()).getBlock().getMaterial().isSolid(); } - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - float f = 0.0625F; - float f1 = 0.5F; - this.setBlockBounds(f, 0.0F, f, 1.0F - f, f1, 1.0F - f); + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return super.canPlaceBlockAt(world, blockpos) ? this.canBlockStay(world, blockpos) : false; } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState iblockstate) { - float f = 0.0625F; - float f1 = (float) (1 + ((Integer) iblockstate.getValue(BITES)).intValue() * 2) / 16.0F; - float f2 = 0.5F; - return new AxisAlignedBB((double) ((float) blockpos.getX() + f1), (double) blockpos.getY(), - (double) ((float) blockpos.getZ() + f), (double) ((float) (blockpos.getX() + 1) - f), - (double) ((float) blockpos.getY() + f2), (double) ((float) (blockpos.getZ() + 1) - f)); - } - - public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { - return this.getCollisionBoundingBox(world, blockpos, world.getBlockState(blockpos)); - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - this.eatCake(world, blockpos, iblockstate, entityplayer); - return true; - } - - public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer entityplayer) { - this.eatCake(world, blockpos, world.getBlockState(blockpos), entityplayer); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { BITES }); } private void eatCake(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player) { @@ -113,12 +75,80 @@ public class BlockCake extends Block { } } - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return super.canPlaceBlockAt(world, blockpos) ? this.canBlockStay(world, blockpos) : false; + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; } - /**+ - * Called when a neighboring block changes. + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState iblockstate) { + float f = 0.0625F; + float f1 = (float) (1 + ((Integer) iblockstate.getValue(BITES)).intValue() * 2) / 16.0F; + float f2 = 0.5F; + return new AxisAlignedBB((double) ((float) blockpos.getX() + f1), (double) blockpos.getY(), + (double) ((float) blockpos.getZ() + f), (double) ((float) (blockpos.getX() + 1) - f), + (double) ((float) blockpos.getY() + f2), (double) ((float) (blockpos.getZ() + 1) - f)); + } + + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return (7 - ((Integer) world.getBlockState(blockpos).getValue(BITES)).intValue()) * 2; + } + + public Item getItem(World var1, BlockPos var2) { + return Items.cake; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(BITES)).intValue(); + } + + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { + return this.getCollisionBoundingBox(world, blockpos, world.getBlockState(blockpos)); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(BITES, Integer.valueOf(i)); + } + + public boolean hasComparatorInputOverride() { + return true; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + this.eatCake(world, blockpos, iblockstate, entityplayer); + return true; + } + + public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer entityplayer) { + this.eatCake(world, blockpos, world.getBlockState(blockpos), entityplayer); + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { if (!this.canBlockStay(world, blockpos)) { @@ -127,55 +157,27 @@ public class BlockCake extends Block { } - private boolean canBlockStay(World worldIn, BlockPos pos) { - return worldIn.getBlockState(pos.down()).getBlock().getMaterial().isSolid(); - } - - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 0; } - /**+ - * Get the Item that this Block should drop when harvested. + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + float f = 0.0625F; + float f1 = (float) (1 + ((Integer) iblockaccess.getBlockState(blockpos).getValue(BITES)).intValue() * 2) + / 16.0F; + float f2 = 0.5F; + this.setBlockBounds(f1, 0.0F, f, 1.0F - f, f2, 1.0F - f); + } + + /** + * + Sets the block's bounds for rendering it as an item */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return null; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.cake; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(BITES, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(BITES)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { BITES }); - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return (7 - ((Integer) world.getBlockState(blockpos).getValue(BITES)).intValue()) * 2; - } - - public boolean hasComparatorInputOverride() { - return true; + public void setBlockBoundsForItemRender() { + float f = 0.0625F; + float f1 = 0.5F; + this.setBlockBounds(f, 0.0F, f, 1.0F - f, f1, 1.0F - f); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockCarpet.java b/src/game/java/net/minecraft/block/BlockCarpet.java index cb885db5..bd50f44c 100644 --- a/src/game/java/net/minecraft/block/BlockCarpet.java +++ b/src/game/java/net/minecraft/block/BlockCarpet.java @@ -20,22 +20,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,53 +56,14 @@ public class BlockCarpet extends Block { this.setBlockBoundsFromMeta(0); } - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - this.setBlockBoundsFromMeta(0); - } - - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - this.setBlockBoundsFromMeta(0); - } - - protected void setBlockBoundsFromMeta(int meta) { - byte b0 = 0; - float f = (float) (1 * (1 + b0)) / 16.0F; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, f, 1.0F); + private boolean canBlockStay(World worldIn, BlockPos pos) { + return !worldIn.isAirBlock(pos.down()); } public boolean canPlaceBlockAt(World world, BlockPos blockpos) { return super.canPlaceBlockAt(world, blockpos) && this.canBlockStay(world, blockpos); } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - this.checkForDrop(world, blockpos, iblockstate); - } - private boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { if (!this.canBlockStay(worldIn, pos)) { this.dropBlockAsItem(worldIn, pos, state, 0); @@ -110,27 +74,43 @@ public class BlockCarpet extends Block { } } - private boolean canBlockStay(World worldIn, BlockPos pos) { - return !worldIn.isAirBlock(pos.down()); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { COLOR }); } - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - return enumfacing == EnumFacing.UP ? true : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ public int damageDropped(IBlockState iblockstate) { return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ public void getSubBlocks(Item item, CreativeTabs var2, List list) { for (int i = 0; i < 16; ++i) { @@ -139,22 +119,16 @@ public class BlockCarpet extends Block { } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); + public boolean isFullCube() { + return false; } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { COLOR }); + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, @@ -170,4 +144,32 @@ public class BlockCarpet extends Block { } return super.onBlockActivated(world, blockpos, var3, entityplayer, var5, var6, var7, var8); } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + this.checkForDrop(world, blockpos, iblockstate); + } + + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + this.setBlockBoundsFromMeta(0); + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + this.setBlockBoundsFromMeta(0); + } + + protected void setBlockBoundsFromMeta(int meta) { + byte b0 = 0; + float f = (float) (1 * (1 + b0)) / 16.0F; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, f, 1.0F); + } + + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + return enumfacing == EnumFacing.UP ? true : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockCarrot.java b/src/game/java/net/minecraft/block/BlockCarrot.java index 1622be28..63e654e9 100644 --- a/src/game/java/net/minecraft/block/BlockCarrot.java +++ b/src/game/java/net/minecraft/block/BlockCarrot.java @@ -3,32 +3,35 @@ package net.minecraft.block; import net.minecraft.init.Items; import net.minecraft.item.Item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockCarrot extends BlockCrops { - protected Item getSeed() { - return Items.carrot; - } - protected Item getCrop() { return Items.carrot; } + + protected Item getSeed() { + return Items.carrot; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockCauldron.java b/src/game/java/net/minecraft/block/BlockCauldron.java index ef4ceadb..41e6e669 100644 --- a/src/game/java/net/minecraft/block/BlockCauldron.java +++ b/src/game/java/net/minecraft/block/BlockCauldron.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -26,22 +26,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,9 +57,9 @@ public class BlockCauldron extends Block { this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); } - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -74,36 +77,66 @@ public class BlockCauldron extends Block { this.setBlockBoundsForItemRender(); } - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { LEVEL }); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Called similar to random ticks, but only when it is raining. */ - public boolean isOpaqueCube() { - return false; + public void fillWithRain(World world, BlockPos blockpos) { + if (world.rand.nextInt(20) == 1) { + IBlockState iblockstate = world.getBlockState(blockpos); + if (((Integer) iblockstate.getValue(LEVEL)).intValue() < 3) { + world.setBlockState(blockpos, iblockstate.cycleProperty(LEVEL), 2); + } + + } + } + + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return ((Integer) world.getBlockState(blockpos).getValue(LEVEL)).intValue(); + } + + public Item getItem(World var1, BlockPos var2) { + return Items.cauldron; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.cauldron; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(LEVEL)).intValue(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(LEVEL, Integer.valueOf(i)); + } + + public boolean hasComparatorInputOverride() { + return true; } public boolean isFullCube() { return false; } - /**+ - * Called When an Entity Collided with the Block + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ - public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState iblockstate, Entity entity) { - int i = ((Integer) iblockstate.getValue(LEVEL)).intValue(); - float f = (float) blockpos.getY() + (6.0F + (float) (3 * i)) / 16.0F; - if (!world.isRemote && entity.isBurning() && i > 0 && entity.getEntityBoundingBox().minY <= (double) f) { - entity.extinguish(); - this.setWaterLevel(world, blockpos, iblockstate, i - 1); - } - + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, @@ -198,58 +231,28 @@ public class BlockCauldron extends Block { } } + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState iblockstate, Entity entity) { + int i = ((Integer) iblockstate.getValue(LEVEL)).intValue(); + float f = (float) blockpos.getY() + (6.0F + (float) (3 * i)) / 16.0F; + if (!world.isRemote && entity.isBurning() && i > 0 && entity.getEntityBoundingBox().minY <= (double) f) { + entity.extinguish(); + this.setWaterLevel(world, blockpos, iblockstate, i - 1); + } + + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + public void setWaterLevel(World worldIn, BlockPos pos, IBlockState state, int level) { worldIn.setBlockState(pos, state.withProperty(LEVEL, Integer.valueOf(MathHelper.clamp_int(level, 0, 3))), 2); worldIn.updateComparatorOutputLevel(pos, this); } - - /**+ - * Called similar to random ticks, but only when it is raining. - */ - public void fillWithRain(World world, BlockPos blockpos) { - if (world.rand.nextInt(20) == 1) { - IBlockState iblockstate = world.getBlockState(blockpos); - if (((Integer) iblockstate.getValue(LEVEL)).intValue() < 3) { - world.setBlockState(blockpos, iblockstate.cycleProperty(LEVEL), 2); - } - - } - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.cauldron; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.cauldron; - } - - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return ((Integer) world.getBlockState(blockpos).getValue(LEVEL)).intValue(); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(LEVEL, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(LEVEL)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { LEVEL }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockChest.java b/src/game/java/net/minecraft/block/BlockChest.java index 46ab7d8f..68bc8036 100644 --- a/src/game/java/net/minecraft/block/BlockChest.java +++ b/src/game/java/net/minecraft/block/BlockChest.java @@ -28,22 +28,25 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.ILockableContainer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,113 +63,63 @@ public class BlockChest extends BlockContainer { this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 2; - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - if (iblockaccess.getBlockState(blockpos.north()).getBlock() == this) { - this.setBlockBounds(0.0625F, 0.0F, 0.0F, 0.9375F, 0.875F, 0.9375F); - } else if (iblockaccess.getBlockState(blockpos.south()).getBlock() == this) { - this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 1.0F); - } else if (iblockaccess.getBlockState(blockpos.west()).getBlock() == this) { - this.setBlockBounds(0.0F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); - } else if (iblockaccess.getBlockState(blockpos.east()).getBlock() == this) { - this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 1.0F, 0.875F, 0.9375F); - } else { - this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof IInventory) { + InventoryHelper.dropInventoryItems(world, blockpos, (IInventory) tileentity); + world.updateComparatorOutputLevel(blockpos, this); } + super.breakBlock(world, blockpos, iblockstate); } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - this.checkForSurroundingChests(world, blockpos, iblockstate); - - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facings(); - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - BlockPos blockpos1 = blockpos.offset(enumfacing); - IBlockState iblockstate1 = world.getBlockState(blockpos1); - if (iblockstate1.getBlock() == this) { - this.checkForSurroundingChests(world, blockpos1, iblockstate1); + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + int i = 0; + BlockPos blockpos1 = blockpos.west(); + BlockPos blockpos2 = blockpos.east(); + BlockPos blockpos3 = blockpos.north(); + BlockPos blockpos4 = blockpos.south(); + if (world.getBlockState(blockpos1).getBlock() == this) { + if (this.isDoubleChest(world, blockpos1)) { + return false; } + + ++i; } + if (world.getBlockState(blockpos2).getBlock() == this) { + if (this.isDoubleChest(world, blockpos2)) { + return false; + } + + ++i; + } + + if (world.getBlockState(blockpos3).getBlock() == this) { + if (this.isDoubleChest(world, blockpos3)) { + return false; + } + + ++i; + } + + if (world.getBlockState(blockpos4).getBlock() == this) { + if (this.isDoubleChest(world, blockpos4)) { + return false; + } + + ++i; + } + + return i <= 1; } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing()); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack itemstack) { - EnumFacing enumfacing = EnumFacing - .getHorizontal( - MathHelper.floor_double((double) (entitylivingbase.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3) - .getOpposite(); - iblockstate = iblockstate.withProperty(FACING, enumfacing); - BlockPos blockpos1 = blockpos.north(); - BlockPos blockpos2 = blockpos.south(); - BlockPos blockpos3 = blockpos.west(); - BlockPos blockpos4 = blockpos.east(); - boolean flag = this == world.getBlockState(blockpos1).getBlock(); - boolean flag1 = this == world.getBlockState(blockpos2).getBlock(); - boolean flag2 = this == world.getBlockState(blockpos3).getBlock(); - boolean flag3 = this == world.getBlockState(blockpos4).getBlock(); - if (!flag && !flag1 && !flag2 && !flag3) { - world.setBlockState(blockpos, iblockstate, 3); - } else if (enumfacing.getAxis() != EnumFacing.Axis.X || !flag && !flag1) { - if (enumfacing.getAxis() == EnumFacing.Axis.Z && (flag2 || flag3)) { - if (flag2) { - world.setBlockState(blockpos3, iblockstate, 3); - } else { - world.setBlockState(blockpos4, iblockstate, 3); - } - - world.setBlockState(blockpos, iblockstate, 3); - } - } else { - if (flag) { - world.setBlockState(blockpos1, iblockstate, 3); - } else { - world.setBlockState(blockpos2, iblockstate, 3); - } - - world.setBlockState(blockpos, iblockstate, 3); - } - - if (itemstack.hasDisplayName()) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityChest) { - ((TileEntityChest) tileentity).setCustomName(itemstack.getDisplayName()); - } - } - + public boolean canProvidePower() { + return this.chestType == 1; } public IBlockState checkForSurroundingChests(World worldIn, BlockPos pos, IBlockState state) { @@ -283,100 +236,20 @@ public class BlockChest extends BlockContainer { } } - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - int i = 0; - BlockPos blockpos1 = blockpos.west(); - BlockPos blockpos2 = blockpos.east(); - BlockPos blockpos3 = blockpos.north(); - BlockPos blockpos4 = blockpos.south(); - if (world.getBlockState(blockpos1).getBlock() == this) { - if (this.isDoubleChest(world, blockpos1)) { - return false; - } - - ++i; - } - - if (world.getBlockState(blockpos2).getBlock() == this) { - if (this.isDoubleChest(world, blockpos2)) { - return false; - } - - ++i; - } - - if (world.getBlockState(blockpos3).getBlock() == this) { - if (this.isDoubleChest(world, blockpos3)) { - return false; - } - - ++i; - } - - if (world.getBlockState(blockpos4).getBlock() == this) { - if (this.isDoubleChest(world, blockpos4)) { - return false; - } - - ++i; - } - - return i <= 1; + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); } - private boolean isDoubleChest(World worldIn, BlockPos pos) { - if (worldIn.getBlockState(pos).getBlock() != this) { - return false; - } else { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (worldIn.getBlockState(pos.offset(enumfacing)).getBlock() == this) { - return true; - } - } - - return false; - } - } - - /**+ - * Called when a neighboring block changes. + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - super.onNeighborBlockChange(world, blockpos, iblockstate, block); - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityChest) { - tileentity.updateContainingBlockInfo(); - } - + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityChest(); } - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof IInventory) { - InventoryHelper.dropInventoryItems(world, blockpos, (IInventory) tileentity); - world.updateComparatorOutputLevel(blockpos, this); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - { - ILockableContainer ilockablecontainer = this.getLockableContainer(world, blockpos); - if (ilockablecontainer != null) { - entityplayer.displayGUIChest(ilockablecontainer); - if (this.chestType == 0) { - entityplayer.triggerAchievement(StatList.field_181723_aa); - } else if (this.chestType == 1) { - entityplayer.triggerAchievement(StatList.field_181737_U); - } - } - - return true; - } + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return Container.calcRedstoneFromInventory(this.getLockableContainer(world, blockpos)); } public ILockableContainer getLockableContainer(World worldIn, BlockPos pos) { @@ -416,20 +289,36 @@ public class BlockChest extends BlockContainer { } } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + /** + * + Convert the BlockState into the correct metadata value */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityChest(); + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); } - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render */ - public boolean canProvidePower() { - return this.chestType == 1; + public int getRenderType() { + return 2; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getFront(i); + if (enumfacing.getAxis() == EnumFacing.Axis.Y) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing); + } + + public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, + EnumFacing enumfacing) { + return enumfacing == EnumFacing.UP ? this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing) : 0; } public int getWeakPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState var3, EnumFacing var4) { @@ -446,17 +335,36 @@ public class BlockChest extends BlockContainer { } } - public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, - EnumFacing enumfacing) { - return enumfacing == EnumFacing.UP ? this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing) : 0; + public boolean hasComparatorInputOverride() { + return true; + } + + private boolean isBelowSolidBlock(World worldIn, BlockPos pos) { + return worldIn.getBlockState(pos.up()).getBlock().isNormalCube(); } private boolean isBlocked(World worldIn, BlockPos pos) { return this.isBelowSolidBlock(worldIn, pos) || this.isOcelotSittingOnChest(worldIn, pos); } - private boolean isBelowSolidBlock(World worldIn, BlockPos pos) { - return worldIn.getBlockState(pos.up()).getBlock().isNormalCube(); + private boolean isDoubleChest(World worldIn, BlockPos pos) { + if (worldIn.getBlockState(pos).getBlock() != this) { + return false; + } else { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (worldIn.getBlockState(pos.offset(enumfacing)).getBlock() == this) { + return true; + } + } + + return false; + } + } + + public boolean isFullCube() { + return false; } private boolean isOcelotSittingOnChest(World worldIn, BlockPos pos) { @@ -474,34 +382,129 @@ public class BlockChest extends BlockContainer { return false; } - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return Container.calcRedstoneFromInventory(this.getLockableContainer(world, blockpos)); - } - - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getFront(i); - if (enumfacing.getAxis() == EnumFacing.Axis.Y) { - enumfacing = EnumFacing.NORTH; + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + { + ILockableContainer ilockablecontainer = this.getLockableContainer(world, blockpos); + if (ilockablecontainer != null) { + entityplayer.displayGUIChest(ilockablecontainer); + if (this.chestType == 0) { + entityplayer.triggerAchievement(StatList.field_181723_aa); + } else if (this.chestType == 1) { + entityplayer.triggerAchievement(StatList.field_181737_U); + } + } + + return true; + } + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + this.checkForSurroundingChests(world, blockpos, iblockstate); + + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facings(); + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + BlockPos blockpos1 = blockpos.offset(enumfacing); + IBlockState iblockstate1 = world.getBlockState(blockpos1); + if (iblockstate1.getBlock() == this) { + this.checkForSurroundingChests(world, blockpos1, iblockstate1); + } } - return this.getDefaultState().withProperty(FACING, enumfacing); } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing()); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack itemstack) { + EnumFacing enumfacing = EnumFacing + .getHorizontal( + MathHelper.floor_double((double) (entitylivingbase.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3) + .getOpposite(); + iblockstate = iblockstate.withProperty(FACING, enumfacing); + BlockPos blockpos1 = blockpos.north(); + BlockPos blockpos2 = blockpos.south(); + BlockPos blockpos3 = blockpos.west(); + BlockPos blockpos4 = blockpos.east(); + boolean flag = this == world.getBlockState(blockpos1).getBlock(); + boolean flag1 = this == world.getBlockState(blockpos2).getBlock(); + boolean flag2 = this == world.getBlockState(blockpos3).getBlock(); + boolean flag3 = this == world.getBlockState(blockpos4).getBlock(); + if (!flag && !flag1 && !flag2 && !flag3) { + world.setBlockState(blockpos, iblockstate, 3); + } else if (enumfacing.getAxis() != EnumFacing.Axis.X || !flag && !flag1) { + if (enumfacing.getAxis() == EnumFacing.Axis.Z && (flag2 || flag3)) { + if (flag2) { + world.setBlockState(blockpos3, iblockstate, 3); + } else { + world.setBlockState(blockpos4, iblockstate, 3); + } + + world.setBlockState(blockpos, iblockstate, 3); + } + } else { + if (flag) { + world.setBlockState(blockpos1, iblockstate, 3); + } else { + world.setBlockState(blockpos2, iblockstate, 3); + } + + world.setBlockState(blockpos, iblockstate, 3); + } + + if (itemstack.hasDisplayName()) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityChest) { + ((TileEntityChest) tileentity).setCustomName(itemstack.getDisplayName()); + } + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + super.onNeighborBlockChange(world, blockpos, iblockstate, block); + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityChest) { + tileentity.updateContainingBlockInfo(); + } + + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + if (iblockaccess.getBlockState(blockpos.north()).getBlock() == this) { + this.setBlockBounds(0.0625F, 0.0F, 0.0F, 0.9375F, 0.875F, 0.9375F); + } else if (iblockaccess.getBlockState(blockpos.south()).getBlock() == this) { + this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 1.0F); + } else if (iblockaccess.getBlockState(blockpos.west()).getBlock() == this) { + this.setBlockBounds(0.0F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + } else if (iblockaccess.getBlockState(blockpos.east()).getBlock() == this) { + this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 1.0F, 0.875F, 0.9375F); + } else { + this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockClay.java b/src/game/java/net/minecraft/block/BlockClay.java index 52d113a9..f47d921f 100644 --- a/src/game/java/net/minecraft/block/BlockClay.java +++ b/src/game/java/net/minecraft/block/BlockClay.java @@ -1,29 +1,31 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,15 +36,15 @@ public class BlockClay extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Items.clay_ball; } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 4; diff --git a/src/game/java/net/minecraft/block/BlockCocoa.java b/src/game/java/net/minecraft/block/BlockCocoa.java index 84cd5f78..55daaaea 100644 --- a/src/game/java/net/minecraft/block/BlockCocoa.java +++ b/src/game/java/net/minecraft/block/BlockCocoa.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -20,22 +19,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,18 +52,6 @@ public class BlockCocoa extends BlockDirectional implements IGrowable { this.setTickRandomly(true); } - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - if (!this.canBlockStay(world, blockpos, iblockstate)) { - this.dropBlock(world, blockpos, iblockstate); - } else if (world.rand.nextInt(5) == 0) { - int i = ((Integer) iblockstate.getValue(AGE)).intValue(); - if (i < 2) { - world.setBlockState(blockpos, iblockstate.withProperty(AGE, Integer.valueOf(i + 1)), 2); - } - } - - } - public boolean canBlockStay(World worldIn, BlockPos pos, IBlockState state) { pos = pos.offset((EnumFacing) state.getValue(FACING)); IBlockState iblockstate = worldIn.getBlockState(pos); @@ -69,16 +59,45 @@ public class BlockCocoa extends BlockDirectional implements IGrowable { && iblockstate.getValue(BlockPlanks.VARIANT) == BlockPlanks.EnumType.JUNGLE; } - public boolean isFullCube() { - return false; + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { + return ((Integer) iblockstate.getValue(AGE)).intValue() < 2; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, AGE }); + } + + private void dropBlock(World worldIn, BlockPos pos, IBlockState state) { + worldIn.setBlockState(pos, Blocks.air.getDefaultState(), 3); + this.dropBlockAsItem(worldIn, pos, state, 0); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. */ - public boolean isOpaqueCube() { - return false; + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float var4, + int var5) { + int i = ((Integer) iblockstate.getValue(AGE)).intValue(); + byte b0 = 1; + if (i >= 2) { + b0 = 3; + } + + for (int j = 0; j < b0; ++j) { + spawnAsEntity(world, blockpos, new ItemStack(Items.dye, 1, EnumDyeColor.BROWN.getDyeDamage())); + } + + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; } public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { @@ -86,11 +105,89 @@ public class BlockCocoa extends BlockDirectional implements IGrowable { return super.getCollisionBoundingBox(world, blockpos, iblockstate); } + public int getDamageValue(World var1, BlockPos var2) { + return EnumDyeColor.BROWN.getDyeDamage(); + } + + public Item getItem(World var1, BlockPos var2) { + return Items.dye; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + i = i | ((Integer) iblockstate.getValue(AGE)).intValue() << 2; + return i; + } + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { this.setBlockBoundsBasedOnState(world, blockpos); return super.getSelectedBoundingBox(world, blockpos); } + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)).withProperty(AGE, + Integer.valueOf((i & 15) >> 2)); + } + + public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { + world.setBlockState(blockpos, + iblockstate.withProperty(AGE, Integer.valueOf(((Integer) iblockstate.getValue(AGE)).intValue() + 1)), + 2); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase var8) { + if (!enumfacing.getAxis().isHorizontal()) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing.getOpposite()).withProperty(AGE, + Integer.valueOf(0)); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack var5) { + EnumFacing enumfacing = EnumFacing.fromAngle((double) entitylivingbase.rotationYaw); + world.setBlockState(blockpos, iblockstate.withProperty(FACING, enumfacing), 2); + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!this.canBlockStay(world, blockpos, iblockstate)) { + this.dropBlock(world, blockpos, iblockstate); + } + + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { IBlockState iblockstate = iblockaccess.getBlockState(blockpos); EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); @@ -118,110 +215,15 @@ public class BlockCocoa extends BlockDirectional implements IGrowable { } - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack var5) { - EnumFacing enumfacing = EnumFacing.fromAngle((double) entitylivingbase.rotationYaw); - world.setBlockState(blockpos, iblockstate.withProperty(FACING, enumfacing), 2); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase var8) { - if (!enumfacing.getAxis().isHorizontal()) { - enumfacing = EnumFacing.NORTH; - } - - return this.getDefaultState().withProperty(FACING, enumfacing.getOpposite()).withProperty(AGE, - Integer.valueOf(0)); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { if (!this.canBlockStay(world, blockpos, iblockstate)) { this.dropBlock(world, blockpos, iblockstate); + } else if (world.rand.nextInt(5) == 0) { + int i = ((Integer) iblockstate.getValue(AGE)).intValue(); + if (i < 2) { + world.setBlockState(blockpos, iblockstate.withProperty(AGE, Integer.valueOf(i + 1)), 2); + } } } - - private void dropBlock(World worldIn, BlockPos pos, IBlockState state) { - worldIn.setBlockState(pos, Blocks.air.getDefaultState(), 3); - this.dropBlockAsItem(worldIn, pos, state, 0); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float var4, - int var5) { - int i = ((Integer) iblockstate.getValue(AGE)).intValue(); - byte b0 = 1; - if (i >= 2) { - b0 = 3; - } - - for (int j = 0; j < b0; ++j) { - spawnAsEntity(world, blockpos, new ItemStack(Items.dye, 1, EnumDyeColor.BROWN.getDyeDamage())); - } - - } - - public Item getItem(World var1, BlockPos var2) { - return Items.dye; - } - - public int getDamageValue(World var1, BlockPos var2) { - return EnumDyeColor.BROWN.getDyeDamage(); - } - - /**+ - * Whether this IGrowable can grow - */ - public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { - return ((Integer) iblockstate.getValue(AGE)).intValue() < 2; - } - - public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { - return true; - } - - public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { - world.setBlockState(blockpos, - iblockstate.withProperty(AGE, Integer.valueOf(((Integer) iblockstate.getValue(AGE)).intValue() + 1)), - 2); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)).withProperty(AGE, - Integer.valueOf((i & 15) >> 2)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - i = i | ((Integer) iblockstate.getValue(AGE)).intValue() << 2; - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, AGE }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockColored.java b/src/game/java/net/minecraft/block/BlockColored.java index f340feeb..91ae5035 100644 --- a/src/game/java/net/minecraft/block/BlockColored.java +++ b/src/game/java/net/minecraft/block/BlockColored.java @@ -13,22 +13,25 @@ import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,19 +46,43 @@ public class BlockColored extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { COLOR }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ public int damageDropped(IBlockState iblockstate) { return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ public void getSubBlocks(Item item, CreativeTabs var2, List list) { EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP; @@ -65,29 +92,4 @@ public class BlockColored extends Block { } } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { COLOR }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockCommandBlock.java b/src/game/java/net/minecraft/block/BlockCommandBlock.java index 25288c79..e5c05c54 100644 --- a/src/game/java/net/minecraft/block/BlockCommandBlock.java +++ b/src/game/java/net/minecraft/block/BlockCommandBlock.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -18,22 +17,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,44 +48,54 @@ public class BlockCommandBlock extends BlockContainer { this.setDefaultState(this.blockState.getBaseState().withProperty(TRIGGERED, Boolean.valueOf(false))); } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { TRIGGERED }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ public TileEntity createNewTileEntity(World var1, int var2) { return new TileEntityCommandBlock(); } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (!world.isRemote) { - boolean flag = world.isBlockPowered(blockpos); - boolean flag1 = ((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue(); - if (flag && !flag1) { - world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(true)), 4); - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } else if (!flag && flag1) { - world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(false)), 4); - } - } - } - - public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { + public int getComparatorInputOverride(World world, BlockPos blockpos) { TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityCommandBlock) { - ((TileEntityCommandBlock) tileentity).getCommandBlockLogic().trigger(world); - world.updateComparatorOutputLevel(blockpos, this); - } - + return tileentity instanceof TileEntityCommandBlock + ? ((TileEntityCommandBlock) tileentity).getCommandBlockLogic().getSuccessCount() + : 0; } - /**+ - * How many world ticks before ticking + /** + * + Convert the BlockState into the correct metadata value */ - public int tickRate(World var1) { - return 1; + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + if (((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue()) { + i |= 1; + } + + return i; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(TRIGGERED, Boolean.valueOf((i & 1) > 0)); + } + + public boolean hasComparatorInputOverride() { + return true; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, @@ -94,20 +106,18 @@ public class BlockCommandBlock extends BlockContainer { : false; } - public boolean hasComparatorInputOverride() { - return true; + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase var8) { + return this.getDefaultState().withProperty(TRIGGERED, Boolean.valueOf(false)); } - public int getComparatorInputOverride(World world, BlockPos blockpos) { - TileEntity tileentity = world.getTileEntity(blockpos); - return tileentity instanceof TileEntityCommandBlock - ? ((TileEntityCommandBlock) tileentity).getCommandBlockLogic().getSuccessCount() - : 0; - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic */ public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState var3, EntityLivingBase var4, ItemStack itemstack) { @@ -124,50 +134,42 @@ public class BlockCommandBlock extends BlockContainer { } } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!world.isRemote) { + boolean flag = world.isBlockPowered(blockpos); + boolean flag1 = ((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue(); + if (flag && !flag1) { + world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(true)), 4); + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + } else if (!flag && flag1) { + world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(false)), 4); + } + } + } + + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 0; } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render + /** + * + How many world ticks before ticking */ - public int getRenderType() { - return 3; + public int tickRate(World var1) { + return 1; } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(TRIGGERED, Boolean.valueOf((i & 1) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - if (((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue()) { - i |= 1; + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityCommandBlock) { + ((TileEntityCommandBlock) tileentity).getCommandBlockLogic().trigger(world); + world.updateComparatorOutputLevel(blockpos, this); } - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { TRIGGERED }); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase var8) { - return this.getDefaultState().withProperty(TRIGGERED, Boolean.valueOf(false)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockCompressedPowered.java b/src/game/java/net/minecraft/block/BlockCompressedPowered.java index f5632ec1..afb3ba15 100644 --- a/src/game/java/net/minecraft/block/BlockCompressedPowered.java +++ b/src/game/java/net/minecraft/block/BlockCompressedPowered.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,9 +35,9 @@ public class BlockCompressedPowered extends Block { super(parMaterial, parMapColor); } - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. */ public boolean canProvidePower() { return true; diff --git a/src/game/java/net/minecraft/block/BlockContainer.java b/src/game/java/net/minecraft/block/BlockContainer.java index 26b95b87..776cbd6e 100644 --- a/src/game/java/net/minecraft/block/BlockContainer.java +++ b/src/game/java/net/minecraft/block/BlockContainer.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,6 +41,11 @@ public abstract class BlockContainer extends Block implements ITileEntityProvide this.isBlockContainer = true; } + public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { + super.breakBlock(worldIn, pos, state); + worldIn.removeTileEntity(pos); + } + protected boolean func_181086_a(World parWorld, BlockPos parBlockPos, EnumFacing parEnumFacing) { return parWorld.getBlockState(parBlockPos.offset(parEnumFacing)).getBlock().getMaterial() == Material.cactus; } @@ -49,22 +57,16 @@ public abstract class BlockContainer extends Block implements ITileEntityProvide || this.func_181086_a(parWorld, parBlockPos, EnumFacing.EAST); } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render */ public int getRenderType() { return -1; } - public void breakBlock(World worldIn, BlockPos pos, IBlockState state) { - super.breakBlock(worldIn, pos, state); - worldIn.removeTileEntity(pos); - } - - /**+ - * Called on both Client and Server when World#addBlockEvent is - * called + /** + * + Called on both Client and Server when World#addBlockEvent is called */ public boolean onBlockEventReceived(World worldIn, BlockPos pos, IBlockState state, int eventID, int eventParam) { super.onBlockEventReceived(worldIn, pos, state, eventID, eventParam); diff --git a/src/game/java/net/minecraft/block/BlockCrops.java b/src/game/java/net/minecraft/block/BlockCrops.java index 25f4d4f3..f8937cf9 100644 --- a/src/game/java/net/minecraft/block/BlockCrops.java +++ b/src/game/java/net/minecraft/block/BlockCrops.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; import net.minecraft.block.state.BlockState; @@ -15,22 +14,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,47 +40,6 @@ import net.minecraft.world.World; public class BlockCrops extends BlockBush implements IGrowable { public static final PropertyInteger AGE = PropertyInteger.create("age", 0, 7); - protected BlockCrops() { - this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, Integer.valueOf(0))); - this.setTickRandomly(true); - float f = 0.5F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); - this.setCreativeTab((CreativeTabs) null); - this.setHardness(0.0F); - this.setStepSound(soundTypeGrass); - this.disableStats(); - } - - /**+ - * is the block grass, dirt or farmland - */ - protected boolean canPlaceBlockOn(Block block) { - return block == Blocks.farmland; - } - - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - super.updateTick(world, blockpos, iblockstate, random); - if (world.getLightFromNeighbors(blockpos.up()) >= 9) { - int i = ((Integer) iblockstate.getValue(AGE)).intValue(); - if (i < 7) { - float f = getGrowthChance(this, world, blockpos); - if (random.nextInt((int) (25.0F / f) + 1) == 0) { - world.setBlockState(blockpos, iblockstate.withProperty(AGE, Integer.valueOf(i + 1)), 2); - } - } - } - - } - - public void grow(World worldIn, BlockPos pos, IBlockState state) { - int i = ((Integer) state.getValue(AGE)).intValue() + MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5); - if (i > 7) { - i = 7; - } - - worldIn.setBlockState(pos, state.withProperty(AGE, Integer.valueOf(i)), 2); - } - protected static float getGrowthChance(Block blockIn, World worldIn, BlockPos pos) { float f = 1.0F; BlockPos blockpos = pos.down(); @@ -125,21 +86,46 @@ public class BlockCrops extends BlockBush implements IGrowable { return f; } + protected BlockCrops() { + this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, Integer.valueOf(0))); + this.setTickRandomly(true); + float f = 0.5F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); + this.setCreativeTab((CreativeTabs) null); + this.setHardness(0.0F); + this.setStepSound(soundTypeGrass); + this.disableStats(); + } + public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { return (world.getLight(blockpos) >= 8 || world.canSeeSky(blockpos)) && this.canPlaceBlockOn(world.getBlockState(blockpos.down()).getBlock()); } - protected Item getSeed() { - return Items.wheat_seeds; + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { + return ((Integer) iblockstate.getValue(AGE)).intValue() < 7; } - protected Item getCrop() { - return Items.wheat; + /** + * + is the block grass, dirt or farmland + */ + protected boolean canPlaceBlockOn(Block block) { + return block == Blocks.farmland; } - /**+ - * Spawns this Block's drops into the World as EntityItems. + public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AGE }); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, 0); @@ -157,47 +143,63 @@ public class BlockCrops extends BlockBush implements IGrowable { } } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { - return ((Integer) iblockstate.getValue(AGE)).intValue() == 7 ? this.getCrop() : this.getSeed(); + protected Item getCrop() { + return Items.wheat; } public Item getItem(World var1, BlockPos var2) { return this.getSeed(); } - /**+ - * Whether this IGrowable can grow + /** + * + Get the Item that this Block should drop when harvested. */ - public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { - return ((Integer) iblockstate.getValue(AGE)).intValue() < 7; + public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { + return ((Integer) iblockstate.getValue(AGE)).intValue() == 7 ? this.getCrop() : this.getSeed(); } - public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { - return true; + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(AGE)).intValue(); + } + + protected Item getSeed() { + return Items.wheat_seeds; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); + } + + public void grow(World worldIn, BlockPos pos, IBlockState state) { + int i = ((Integer) state.getValue(AGE)).intValue() + MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5); + if (i > 7) { + i = 7; + } + + worldIn.setBlockState(pos, state.withProperty(AGE, Integer.valueOf(i)), 2); } public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { this.grow(world, blockpos, iblockstate); } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); - } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + super.updateTick(world, blockpos, iblockstate, random); + if (world.getLightFromNeighbors(blockpos.up()) >= 9) { + int i = ((Integer) iblockstate.getValue(AGE)).intValue(); + if (i < 7) { + float f = getGrowthChance(this, world, blockpos); + if (random.nextInt((int) (25.0F / f) + 1) == 0) { + world.setBlockState(blockpos, iblockstate.withProperty(AGE, Integer.valueOf(i + 1)), 2); + } + } + } - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(AGE)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AGE }); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDaylightDetector.java b/src/game/java/net/minecraft/block/BlockDaylightDetector.java index 314844d9..d3b552e6 100644 --- a/src/game/java/net/minecraft/block/BlockDaylightDetector.java +++ b/src/game/java/net/minecraft/block/BlockDaylightDetector.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -22,22 +22,25 @@ import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -57,32 +60,84 @@ public class BlockDaylightDetector extends BlockContainer { this.setUnlocalizedName("daylightDetector"); } - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.375F, 1.0F); + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. + */ + public boolean canProvidePower() { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { POWER }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityDaylightDetector(); + } + + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(Blocks.daylight_detector); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.daylight_detector); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(POWER)).intValue(); + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(POWER, Integer.valueOf(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs creativetabs, List list) { + if (!this.inverted) { + super.getSubBlocks(item, creativetabs, list); + } + } public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { return ((Integer) iblockstate.getValue(POWER)).intValue(); } - public void updatePower(World worldIn, BlockPos pos) { - if (!worldIn.provider.getHasNoSky()) { - IBlockState iblockstate = worldIn.getBlockState(pos); - int i = worldIn.getLightFor(EnumSkyBlock.SKY, pos) - worldIn.getSkylightSubtracted(); - float f = worldIn.getCelestialAngleRadians(1.0F); - float f1 = f < 3.1415927F ? 0.0F : 6.2831855F; - f = f + (f1 - f) * 0.2F; - i = Math.round((float) i * MathHelper.cos(f)); - i = MathHelper.clamp_int(i, 0, 15); - if (this.inverted) { - i = 15 - i; - } + public boolean isFullCube() { + return false; + } - if (((Integer) iblockstate.getValue(POWER)).intValue() != i) { - worldIn.setBlockState(pos, iblockstate.withProperty(POWER, Integer.valueOf(i)), 3); - } - - } + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, @@ -106,79 +161,27 @@ public class BlockDaylightDetector extends BlockContainer { } } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.daylight_detector); + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.375F, 1.0F); } - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(Blocks.daylight_detector); - } + public void updatePower(World worldIn, BlockPos pos) { + if (!worldIn.provider.getHasNoSky()) { + IBlockState iblockstate = worldIn.getBlockState(pos); + int i = worldIn.getLightFor(EnumSkyBlock.SKY, pos) - worldIn.getSkylightSubtracted(); + float f = worldIn.getCelestialAngleRadians(1.0F); + float f1 = f < 3.1415927F ? 0.0F : 6.2831855F; + f = f + (f1 - f) * 0.2F; + i = Math.round((float) i * MathHelper.cos(f)); + i = MathHelper.clamp_int(i, 0, 15); + if (this.inverted) { + i = 15 - i; + } - public boolean isFullCube() { - return false; - } + if (((Integer) iblockstate.getValue(POWER)).intValue() != i) { + worldIn.setBlockState(pos, iblockstate.withProperty(POWER, Integer.valueOf(i)), 3); + } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return true; - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityDaylightDetector(); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(POWER, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(POWER)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { POWER }); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs creativetabs, List list) { - if (!this.inverted) { - super.getSubBlocks(item, creativetabs, list); } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDeadBush.java b/src/game/java/net/minecraft/block/BlockDeadBush.java index c6e0616a..98465a2f 100644 --- a/src/game/java/net/minecraft/block/BlockDeadBush.java +++ b/src/game/java/net/minecraft/block/BlockDeadBush.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -15,22 +14,25 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,36 +44,28 @@ public class BlockDeadBush extends BlockBush { this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); } - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState var1) { - return MapColor.woodColor; - } - - /**+ - * is the block grass, dirt or farmland + /** + * + is the block grass, dirt or farmland */ protected boolean canPlaceBlockOn(Block block) { return block == Blocks.sand || block == Blocks.hardened_clay || block == Blocks.stained_hardened_clay || block == Blocks.dirt; } - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) - */ - public boolean isReplaceable(World var1, BlockPos var2) { - return true; - } - - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return null; } + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState var1) { + return MapColor.woodColor; + } + public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, TileEntity tileentity) { if (!world.isRemote && entityplayer.getCurrentEquippedItem() != null @@ -83,4 +77,12 @@ public class BlockDeadBush extends BlockBush { } } + + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) + */ + public boolean isReplaceable(World var1, BlockPos var2) { + return true; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDeepstone.java b/src/game/java/net/minecraft/block/BlockDeepstone.java new file mode 100644 index 00000000..7ca17fb6 --- /dev/null +++ b/src/game/java/net/minecraft/block/BlockDeepstone.java @@ -0,0 +1,40 @@ +package net.minecraft.block; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; +import net.minecraft.init.Blocks; +import net.minecraft.item.Item; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class BlockDeepstone extends Block { + public BlockDeepstone() { + super(Material.rock); + } + + public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { + return this == Blocks.deepstone ? Item.getItemFromBlock(Blocks.cobbled_deepstone) : Item.getItemFromBlock(this); + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDirectional.java b/src/game/java/net/minecraft/block/BlockDirectional.java index 3e392e6e..da47ea42 100644 --- a/src/game/java/net/minecraft/block/BlockDirectional.java +++ b/src/game/java/net/minecraft/block/BlockDirectional.java @@ -5,22 +5,25 @@ import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyDirection; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockDirt.java b/src/game/java/net/minecraft/block/BlockDirt.java index e2282cb4..d617a2d5 100644 --- a/src/game/java/net/minecraft/block/BlockDirt.java +++ b/src/game/java/net/minecraft/block/BlockDirt.java @@ -18,119 +18,56 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockDirt extends Block { - public static PropertyEnum VARIANT; - public static final PropertyBool SNOWY = PropertyBool.create("snowy"); - - protected BlockDirt() { - super(Material.ground); - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockDirt.DirtType.DIRT) - .withProperty(SNOWY, Boolean.valueOf(false))); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockDirt.DirtType.class); - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockDirt.DirtType) iblockstate.getValue(VARIANT)).func_181066_d(); - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - if (iblockstate.getValue(VARIANT) == BlockDirt.DirtType.PODZOL) { - Block block = iblockaccess.getBlockState(blockpos.up()).getBlock(); - iblockstate = iblockstate.withProperty(SNOWY, - Boolean.valueOf(block == Blocks.snow || block == Blocks.snow_layer)); - } - - return iblockstate; - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item var1, CreativeTabs var2, List list) { - list.add(new ItemStack(this, 1, BlockDirt.DirtType.DIRT.getMetadata())); - list.add(new ItemStack(this, 1, BlockDirt.DirtType.COARSE_DIRT.getMetadata())); - list.add(new ItemStack(this, 1, BlockDirt.DirtType.PODZOL.getMetadata())); - } - - public int getDamageValue(World world, BlockPos blockpos) { - IBlockState iblockstate = world.getBlockState(blockpos); - return iblockstate.getBlock() != this ? 0 : ((BlockDirt.DirtType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockDirt.DirtType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockDirt.DirtType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT, SNOWY }); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - BlockDirt.DirtType blockdirt$dirttype = (BlockDirt.DirtType) iblockstate.getValue(VARIANT); - if (blockdirt$dirttype == BlockDirt.DirtType.PODZOL) { - blockdirt$dirttype = BlockDirt.DirtType.DIRT; - } - - return blockdirt$dirttype.getMetadata(); - } - public static enum DirtType implements IStringSerializable { DIRT(0, "dirt", "default", MapColor.dirtColor), COARSE_DIRT(1, "coarse_dirt", "coarse", MapColor.dirtColor), PODZOL(2, "podzol", MapColor.obsidianColor); private static final BlockDirt.DirtType[] METADATA_LOOKUP = new BlockDirt.DirtType[3]; + static { + BlockDirt.DirtType[] types = values(); + for (int i = 0; i < types.length; ++i) { + METADATA_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockDirt.DirtType byMetadata(int metadata) { + if (metadata < 0 || metadata >= METADATA_LOOKUP.length) { + metadata = 0; + } + + return METADATA_LOOKUP[metadata]; + } + private final int metadata; private final String name; + private final String unlocalizedName; + private final MapColor field_181067_h; private DirtType(int parInt2, String parString2, MapColor parMapColor) { @@ -144,40 +81,107 @@ public class BlockDirt extends Block { this.field_181067_h = parMapColor; } - public int getMetadata() { - return this.metadata; - } - - public String getUnlocalizedName() { - return this.unlocalizedName; - } - public MapColor func_181066_d() { return this.field_181067_h; } - public String toString() { - return this.name; - } - - public static BlockDirt.DirtType byMetadata(int metadata) { - if (metadata < 0 || metadata >= METADATA_LOOKUP.length) { - metadata = 0; - } - - return METADATA_LOOKUP[metadata]; + public int getMetadata() { + return this.metadata; } public String getName() { return this.name; } - static { - BlockDirt.DirtType[] types = values(); - for (int i = 0; i < types.length; ++i) { - METADATA_LOOKUP[types[i].getMetadata()] = types[i]; - } + public String getUnlocalizedName() { + return this.unlocalizedName; + } + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + + public static final PropertyBool SNOWY = PropertyBool.create("snowy"); + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockDirt.DirtType.class); + } + + protected BlockDirt() { + super(Material.ground); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockDirt.DirtType.DIRT) + .withProperty(SNOWY, Boolean.valueOf(false))); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT, SNOWY }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + BlockDirt.DirtType blockdirt$dirttype = (BlockDirt.DirtType) iblockstate.getValue(VARIANT); + if (blockdirt$dirttype == BlockDirt.DirtType.PODZOL) { + blockdirt$dirttype = BlockDirt.DirtType.DIRT; + } + + return blockdirt$dirttype.getMetadata(); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + if (iblockstate.getValue(VARIANT) == BlockDirt.DirtType.PODZOL) { + Block block = iblockaccess.getBlockState(blockpos.up()).getBlock(); + iblockstate = iblockstate.withProperty(SNOWY, + Boolean.valueOf(block == Blocks.snow || block == Blocks.snow_layer)); + } + + return iblockstate; + } + + public int getDamageValue(World world, BlockPos blockpos) { + IBlockState iblockstate = world.getBlockState(blockpos); + return iblockstate.getBlock() != this ? 0 : ((BlockDirt.DirtType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockDirt.DirtType) iblockstate.getValue(VARIANT)).func_181066_d(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockDirt.DirtType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockDirt.DirtType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item var1, CreativeTabs var2, List list) { + list.add(new ItemStack(this, 1, BlockDirt.DirtType.DIRT.getMetadata())); + list.add(new ItemStack(this, 1, BlockDirt.DirtType.COARSE_DIRT.getMetadata())); + list.add(new ItemStack(this, 1, BlockDirt.DirtType.PODZOL.getMetadata())); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDispenser.java b/src/game/java/net/minecraft/block/BlockDispenser.java index 5be87225..de1ed68b 100644 --- a/src/game/java/net/minecraft/block/BlockDispenser.java +++ b/src/game/java/net/minecraft/block/BlockDispenser.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -29,22 +28,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.RegistryDefaulted; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,6 +56,26 @@ public class BlockDispenser extends BlockContainer { public static final PropertyBool TRIGGERED = PropertyBool.create("triggered"); public static final RegistryDefaulted dispenseBehaviorRegistry = new RegistryDefaulted( new BehaviorDefaultDispenseItem()); + + /** + * + Get the position where the dispenser at the given Coordinates should + * dispense to. + */ + public static IPosition getDispensePosition(IBlockSource coords) { + EnumFacing enumfacing = getFacing(coords.getBlockMetadata()); + double d0 = coords.getX() + 0.7D * (double) enumfacing.getFrontOffsetX(); + double d1 = coords.getY() + 0.7D * (double) enumfacing.getFrontOffsetY(); + double d2 = coords.getZ() + 0.7D * (double) enumfacing.getFrontOffsetZ(); + return new PositionImpl(d0, d1, d2); + } + + /** + * + Get the facing of a dispenser with the given metadata + */ + public static EnumFacing getFacing(int meta) { + return EnumFacing.getFront(meta & 7); + } + protected EaglercraftRandom rand = new EaglercraftRandom(); protected BlockDispenser() { @@ -63,11 +85,110 @@ public class BlockDispenser extends BlockContainer { this.setCreativeTab(CreativeTabs.tabRedstone); } - /**+ - * How many world ticks before ticking + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityDispenser) { + InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityDispenser) tileentity); + world.updateComparatorOutputLevel(blockpos, this); + } + + super.breakBlock(world, blockpos, iblockstate); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, TRIGGERED }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ - public int tickRate(World var1) { - return 4; + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityDispenser(); + } + + protected void dispense(World worldIn, BlockPos pos) { + BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos); + TileEntityDispenser tileentitydispenser = (TileEntityDispenser) blocksourceimpl.getBlockTileEntity(); + if (tileentitydispenser != null) { + int i = tileentitydispenser.getDispenseSlot(); + if (i < 0) { + worldIn.playAuxSFX(1001, pos, 0); + } else { + ItemStack itemstack = tileentitydispenser.getStackInSlot(i); + IBehaviorDispenseItem ibehaviordispenseitem = this.getBehavior(itemstack); + if (ibehaviordispenseitem != IBehaviorDispenseItem.itemDispenseBehaviorProvider) { + ItemStack itemstack1 = ibehaviordispenseitem.dispense(blocksourceimpl, itemstack); + tileentitydispenser.setInventorySlotContents(i, itemstack1.stackSize <= 0 ? null : itemstack1); + } + + } + } + } + + protected IBehaviorDispenseItem getBehavior(ItemStack stack) { + return (IBehaviorDispenseItem) dispenseBehaviorRegistry.getObject(stack == null ? null : stack.getItem()); + } + + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return Container.calcRedstone(world.getTileEntity(blockpos)); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + if (((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue()) { + i |= 8; + } + + return i; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Possibly modify the given BlockState before rendering it on an Entity + * (Minecarts, Endermen, ...) + */ + public IBlockState getStateForEntityRender(IBlockState var1) { + return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(TRIGGERED, + Boolean.valueOf((i & 8) > 0)); + } + + public boolean hasComparatorInputOverride() { + return true; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (!world.isRemote) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityDispenser) { + entityplayer.displayGUIChest((TileEntityDispenser) tileentity); + if (tileentity instanceof TileEntityDropper) { + entityplayer.triggerAchievement(StatList.field_181731_O); + } else { + entityplayer.triggerAchievement(StatList.field_181733_Q); + } + } + } + return true; } public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { @@ -75,6 +196,49 @@ public class BlockDispenser extends BlockContainer { this.setDefaultDirection(world, blockpos, iblockstate); } + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing var3, float var4, float var5, + float var6, int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState() + .withProperty(FACING, BlockPistonBase.getFacingFromEntity(world, blockpos, entitylivingbase)) + .withProperty(TRIGGERED, Boolean.valueOf(false)); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack itemstack) { + world.setBlockState(blockpos, iblockstate.withProperty(FACING, + BlockPistonBase.getFacingFromEntity(world, blockpos, entitylivingbase)), 2); + if (itemstack.hasDisplayName()) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityDispenser) { + ((TileEntityDispenser) tileentity).setCustomName(itemstack.getDisplayName()); + } + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + boolean flag = world.isBlockPowered(blockpos) || world.isBlockPowered(blockpos.up()); + boolean flag1 = ((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue(); + if (flag && !flag1) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(true)), 4); + } else if (!flag && flag1) { + world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(false)), 4); + } + + } + private void setDefaultDirection(World worldIn, BlockPos pos, IBlockState state) { if (!worldIn.isRemote) { EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); @@ -99,58 +263,11 @@ public class BlockDispenser extends BlockContainer { } } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (!world.isRemote) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityDispenser) { - entityplayer.displayGUIChest((TileEntityDispenser) tileentity); - if (tileentity instanceof TileEntityDropper) { - entityplayer.triggerAchievement(StatList.field_181731_O); - } else { - entityplayer.triggerAchievement(StatList.field_181733_Q); - } - } - } - return true; - } - - protected void dispense(World worldIn, BlockPos pos) { - BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos); - TileEntityDispenser tileentitydispenser = (TileEntityDispenser) blocksourceimpl.getBlockTileEntity(); - if (tileentitydispenser != null) { - int i = tileentitydispenser.getDispenseSlot(); - if (i < 0) { - worldIn.playAuxSFX(1001, pos, 0); - } else { - ItemStack itemstack = tileentitydispenser.getStackInSlot(i); - IBehaviorDispenseItem ibehaviordispenseitem = this.getBehavior(itemstack); - if (ibehaviordispenseitem != IBehaviorDispenseItem.itemDispenseBehaviorProvider) { - ItemStack itemstack1 = ibehaviordispenseitem.dispense(blocksourceimpl, itemstack); - tileentitydispenser.setInventorySlotContents(i, itemstack1.stackSize <= 0 ? null : itemstack1); - } - - } - } - } - - protected IBehaviorDispenseItem getBehavior(ItemStack stack) { - return (IBehaviorDispenseItem) dispenseBehaviorRegistry.getObject(stack == null ? null : stack.getItem()); - } - - /**+ - * Called when a neighboring block changes. + /** + * + How many world ticks before ticking */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - boolean flag = world.isBlockPowered(blockpos) || world.isBlockPowered(blockpos.up()); - boolean flag1 = ((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue(); - if (flag && !flag1) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(true)), 4); - } else if (!flag && flag1) { - world.setBlockState(blockpos, iblockstate.withProperty(TRIGGERED, Boolean.valueOf(false)), 4); - } - + public int tickRate(World var1) { + return 4; } public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { @@ -158,118 +275,4 @@ public class BlockDispenser extends BlockContainer { this.dispense(world, blockpos); } } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityDispenser(); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing var3, float var4, float var5, - float var6, int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState() - .withProperty(FACING, BlockPistonBase.getFacingFromEntity(world, blockpos, entitylivingbase)) - .withProperty(TRIGGERED, Boolean.valueOf(false)); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack itemstack) { - world.setBlockState(blockpos, iblockstate.withProperty(FACING, - BlockPistonBase.getFacingFromEntity(world, blockpos, entitylivingbase)), 2); - if (itemstack.hasDisplayName()) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityDispenser) { - ((TileEntityDispenser) tileentity).setCustomName(itemstack.getDisplayName()); - } - } - - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityDispenser) { - InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityDispenser) tileentity); - world.updateComparatorOutputLevel(blockpos, this); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - /**+ - * Get the position where the dispenser at the given Coordinates - * should dispense to. - */ - public static IPosition getDispensePosition(IBlockSource coords) { - EnumFacing enumfacing = getFacing(coords.getBlockMetadata()); - double d0 = coords.getX() + 0.7D * (double) enumfacing.getFrontOffsetX(); - double d1 = coords.getY() + 0.7D * (double) enumfacing.getFrontOffsetY(); - double d2 = coords.getZ() + 0.7D * (double) enumfacing.getFrontOffsetZ(); - return new PositionImpl(d0, d1, d2); - } - - /**+ - * Get the facing of a dispenser with the given metadata - */ - public static EnumFacing getFacing(int meta) { - return EnumFacing.getFront(meta & 7); - } - - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return Container.calcRedstone(world.getTileEntity(blockpos)); - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Possibly modify the given BlockState before rendering it on - * an Entity (Minecarts, Endermen, ...) - */ - public IBlockState getStateForEntityRender(IBlockState var1) { - return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(TRIGGERED, - Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - if (((Boolean) iblockstate.getValue(TRIGGERED)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, TRIGGERED }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDoor.java b/src/game/java/net/minecraft/block/BlockDoor.java index 8c538f47..63f1030e 100644 --- a/src/game/java/net/minecraft/block/BlockDoor.java +++ b/src/game/java/net/minecraft/block/BlockDoor.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -24,33 +23,110 @@ import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockDoor extends Block { + public static enum EnumDoorHalf implements IStringSerializable { + UPPER, LOWER; + + public String getName() { + return this == UPPER ? "upper" : "lower"; + } + + public String toString() { + return this.getName(); + } + } + + public static enum EnumHingePosition implements IStringSerializable { + LEFT, RIGHT; + + public String getName() { + return this == LEFT ? "left" : "right"; + } + + public String toString() { + return this.getName(); + } + } + public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); public static final PropertyBool OPEN = PropertyBool.create("open"); public static PropertyEnum HINGE; + public static final PropertyBool POWERED = PropertyBool.create("powered"); + public static PropertyEnum HALF; + public static void bootstrapStates() { + HINGE = PropertyEnum.create("hinge", BlockDoor.EnumHingePosition.class); + HALF = PropertyEnum.create("half", BlockDoor.EnumDoorHalf.class); + } + + public static int combineMetadata(IBlockAccess worldIn, BlockPos pos) { + IBlockState iblockstate = worldIn.getBlockState(pos); + int i = iblockstate.getBlock().getMetaFromState(iblockstate); + boolean flag = isTop(i); + IBlockState iblockstate1 = worldIn.getBlockState(pos.down()); + int j = iblockstate1.getBlock().getMetaFromState(iblockstate1); + int k = flag ? j : i; + IBlockState iblockstate2 = worldIn.getBlockState(pos.up()); + int l = iblockstate2.getBlock().getMetaFromState(iblockstate2); + int i1 = flag ? i : l; + boolean flag1 = (i1 & 1) != 0; + boolean flag2 = (i1 & 2) != 0; + return removeHalfBit(k) | (flag ? 8 : 0) | (flag1 ? 16 : 0) | (flag2 ? 32 : 0); + } + + public static EnumFacing getFacing(IBlockAccess worldIn, BlockPos pos) { + return getFacing(combineMetadata(worldIn, pos)); + } + + public static EnumFacing getFacing(int combinedMeta) { + return EnumFacing.getHorizontal(combinedMeta & 3).rotateYCCW(); + } + + protected static boolean isHingeLeft(int combinedMeta) { + return (combinedMeta & 16) != 0; + } + + public static boolean isOpen(IBlockAccess worldIn, BlockPos pos) { + return isOpen(combineMetadata(worldIn, pos)); + } + + protected static boolean isOpen(int combinedMeta) { + return (combinedMeta & 4) != 0; + } + + protected static boolean isTop(int meta) { + return (meta & 8) != 0; + } + + protected static int removeHalfBit(int meta) { + return meta & 7; + } + protected BlockDoor(Material materialIn) { super(materialIn); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH) @@ -58,22 +134,138 @@ public class BlockDoor extends Block { .withProperty(POWERED, Boolean.valueOf(false)).withProperty(HALF, BlockDoor.EnumDoorHalf.LOWER)); } - public static void bootstrapStates() { - HINGE = PropertyEnum.create("hinge", BlockDoor.EnumHingePosition.class); - HALF = PropertyEnum.create("half", BlockDoor.EnumDoorHalf.class); + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return blockpos.getY() >= 255 ? false + : World.doesBlockHaveSolidTopSurface(world, blockpos.down()) && super.canPlaceBlockAt(world, blockpos) + && super.canPlaceBlockAt(world, blockpos.up()); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. + */ + public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { + this.setBlockBoundsBasedOnState(world, blockpos); + return super.collisionRayTrace(world, blockpos, vec3, vec31); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { HALF, FACING, OPEN, HINGE, POWERED }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + if (iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.LOWER) { + IBlockState iblockstate1 = iblockaccess.getBlockState(blockpos.up()); + if (iblockstate1.getBlock() == this) { + iblockstate = iblockstate.withProperty(HINGE, iblockstate1.getValue(HINGE)).withProperty(POWERED, + iblockstate1.getValue(POWERED)); + } + } else { + IBlockState iblockstate2 = iblockaccess.getBlockState(blockpos.down()); + if (iblockstate2.getBlock() == this) { + iblockstate = iblockstate.withProperty(FACING, iblockstate2.getValue(FACING)).withProperty(OPEN, + iblockstate2.getValue(OPEN)); + } + } + + return iblockstate; + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { + this.setBlockBoundsBasedOnState(world, blockpos); + return super.getCollisionBoundingBox(world, blockpos, iblockstate); + } + + private Item getItem() { + return this == Blocks.iron_door ? Items.iron_door + : (this == Blocks.spruce_door ? Items.spruce_door + : (this == Blocks.birch_door ? Items.birch_door + : (this == Blocks.jungle_door ? Items.jungle_door + : (this == Blocks.acacia_door ? Items.acacia_door + : (this == Blocks.dark_oak_door ? Items.dark_oak_door + : Items.oak_door))))); + } + + public Item getItem(World var1, BlockPos var2) { + return this.getItem(); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { + return iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER ? null : this.getItem(); + } + + /** + * + Gets the localized name of this block. Used for the statistics page. */ public String getLocalizedName() { return StatCollector.translateToLocal((this.getUnlocalizedName() + ".name").replaceAll("tile", "item")); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + if (iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER) { + i = i | 8; + if (iblockstate.getValue(HINGE) == BlockDoor.EnumHingePosition.RIGHT) { + i |= 1; + } + + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 2; + } + } else { + i = i | ((EnumFacing) iblockstate.getValue(FACING)).rotateY().getHorizontalIndex(); + if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { + i |= 4; + } + } + + return i; + } + + public int getMobilityFlag() { + return 1; + } + + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { + this.setBlockBoundsBasedOnState(world, blockpos); + return super.getSelectedBoundingBox(world, blockpos); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return (i & 8) > 0 + ? this.getDefaultState().withProperty(HALF, BlockDoor.EnumDoorHalf.UPPER) + .withProperty(HINGE, + (i & 1) > 0 ? BlockDoor.EnumHingePosition.RIGHT : BlockDoor.EnumHingePosition.LEFT) + .withProperty(POWERED, Boolean.valueOf((i & 2) > 0)) + : this.getDefaultState().withProperty(HALF, BlockDoor.EnumDoorHalf.LOWER) + .withProperty(FACING, EnumFacing.getHorizontal(i & 3).rotateYCCW()) + .withProperty(OPEN, Boolean.valueOf((i & 4) > 0)); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; @@ -83,18 +275,83 @@ public class BlockDoor extends Block { return isOpen(combineMetadata(iblockaccess, blockpos)); } - public boolean isFullCube() { - return false; + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (this.blockMaterial == Material.iron) { + return true; + } else { + BlockPos blockpos1 = iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.LOWER ? blockpos + : blockpos.down(); + IBlockState iblockstate1 = blockpos.equals(blockpos1) ? iblockstate : world.getBlockState(blockpos1); + if (iblockstate1.getBlock() != this) { + return false; + } else { + iblockstate = iblockstate1.cycleProperty(OPEN); + world.setBlockState(blockpos1, iblockstate, 2); + world.markBlockRangeForRenderUpdate(blockpos1, blockpos); + world.playAuxSFXAtEntity(entityplayer, + ((Boolean) iblockstate.getValue(OPEN)).booleanValue() ? 1003 : 1006, blockpos, 0); + return true; + } + } } - public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { - this.setBlockBoundsBasedOnState(world, blockpos); - return super.getSelectedBoundingBox(world, blockpos); + public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { + BlockPos blockpos1 = blockpos.down(); + if (entityplayer.capabilities.isCreativeMode && iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER + && world.getBlockState(blockpos1).getBlock() == this) { + world.setBlockToAir(blockpos1); + } + } - public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { - this.setBlockBoundsBasedOnState(world, blockpos); - return super.getCollisionBoundingBox(world, blockpos, iblockstate); + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + if (iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER) { + BlockPos blockpos1 = blockpos.down(); + IBlockState iblockstate1 = world.getBlockState(blockpos1); + if (iblockstate1.getBlock() != this) { + world.setBlockToAir(blockpos); + } else if (block != this) { + this.onNeighborBlockChange(world, blockpos1, iblockstate1, block); + } + } else { + boolean flag1 = false; + BlockPos blockpos2 = blockpos.up(); + IBlockState iblockstate2 = world.getBlockState(blockpos2); + if (iblockstate2.getBlock() != this) { + world.setBlockToAir(blockpos); + flag1 = true; + } + + if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { + world.setBlockToAir(blockpos); + flag1 = true; + if (iblockstate2.getBlock() == this) { + world.setBlockToAir(blockpos2); + } + } + + if (flag1) { + if (!world.isRemote) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + } + } else { + boolean flag = world.isBlockPowered(blockpos) || world.isBlockPowered(blockpos2); + if ((flag || block.canProvidePower()) && block != this + && flag != ((Boolean) iblockstate2.getValue(POWERED)).booleanValue()) { + world.setBlockState(blockpos2, iblockstate2.withProperty(POWERED, Boolean.valueOf(flag)), 2); + if (flag != ((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { + world.setBlockState(blockpos, iblockstate.withProperty(OPEN, Boolean.valueOf(flag)), 2); + world.markBlockRangeForRenderUpdate(blockpos, blockpos); + world.playAuxSFXAtEntity((EntityPlayer) null, flag ? 1003 : 1006, blockpos, 0); + } + } + } + } + } public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { @@ -145,27 +402,6 @@ public class BlockDoor extends Block { } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (this.blockMaterial == Material.iron) { - return true; - } else { - BlockPos blockpos1 = iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.LOWER ? blockpos - : blockpos.down(); - IBlockState iblockstate1 = blockpos.equals(blockpos1) ? iblockstate : world.getBlockState(blockpos1); - if (iblockstate1.getBlock() != this) { - return false; - } else { - iblockstate = iblockstate1.cycleProperty(OPEN); - world.setBlockState(blockpos1, iblockstate, 2); - world.markBlockRangeForRenderUpdate(blockpos1, blockpos); - world.playAuxSFXAtEntity(entityplayer, - ((Boolean) iblockstate.getValue(OPEN)).booleanValue() ? 1003 : 1006, blockpos, 0); - return true; - } - } - } - public void toggleDoor(World worldIn, BlockPos pos, boolean open) { IBlockState iblockstate = worldIn.getBlockState(pos); if (iblockstate.getBlock() == this) { @@ -179,238 +415,4 @@ public class BlockDoor extends Block { } } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - if (iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER) { - BlockPos blockpos1 = blockpos.down(); - IBlockState iblockstate1 = world.getBlockState(blockpos1); - if (iblockstate1.getBlock() != this) { - world.setBlockToAir(blockpos); - } else if (block != this) { - this.onNeighborBlockChange(world, blockpos1, iblockstate1, block); - } - } else { - boolean flag1 = false; - BlockPos blockpos2 = blockpos.up(); - IBlockState iblockstate2 = world.getBlockState(blockpos2); - if (iblockstate2.getBlock() != this) { - world.setBlockToAir(blockpos); - flag1 = true; - } - - if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { - world.setBlockToAir(blockpos); - flag1 = true; - if (iblockstate2.getBlock() == this) { - world.setBlockToAir(blockpos2); - } - } - - if (flag1) { - if (!world.isRemote) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - } - } else { - boolean flag = world.isBlockPowered(blockpos) || world.isBlockPowered(blockpos2); - if ((flag || block.canProvidePower()) && block != this - && flag != ((Boolean) iblockstate2.getValue(POWERED)).booleanValue()) { - world.setBlockState(blockpos2, iblockstate2.withProperty(POWERED, Boolean.valueOf(flag)), 2); - if (flag != ((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { - world.setBlockState(blockpos, iblockstate.withProperty(OPEN, Boolean.valueOf(flag)), 2); - world.markBlockRangeForRenderUpdate(blockpos, blockpos); - world.playAuxSFXAtEntity((EntityPlayer) null, flag ? 1003 : 1006, blockpos, 0); - } - } - } - } - - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { - return iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER ? null : this.getItem(); - } - - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { - this.setBlockBoundsBasedOnState(world, blockpos); - return super.collisionRayTrace(world, blockpos, vec3, vec31); - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return blockpos.getY() >= 255 ? false - : World.doesBlockHaveSolidTopSurface(world, blockpos.down()) && super.canPlaceBlockAt(world, blockpos) - && super.canPlaceBlockAt(world, blockpos.up()); - } - - public int getMobilityFlag() { - return 1; - } - - public static int combineMetadata(IBlockAccess worldIn, BlockPos pos) { - IBlockState iblockstate = worldIn.getBlockState(pos); - int i = iblockstate.getBlock().getMetaFromState(iblockstate); - boolean flag = isTop(i); - IBlockState iblockstate1 = worldIn.getBlockState(pos.down()); - int j = iblockstate1.getBlock().getMetaFromState(iblockstate1); - int k = flag ? j : i; - IBlockState iblockstate2 = worldIn.getBlockState(pos.up()); - int l = iblockstate2.getBlock().getMetaFromState(iblockstate2); - int i1 = flag ? i : l; - boolean flag1 = (i1 & 1) != 0; - boolean flag2 = (i1 & 2) != 0; - return removeHalfBit(k) | (flag ? 8 : 0) | (flag1 ? 16 : 0) | (flag2 ? 32 : 0); - } - - public Item getItem(World var1, BlockPos var2) { - return this.getItem(); - } - - private Item getItem() { - return this == Blocks.iron_door ? Items.iron_door - : (this == Blocks.spruce_door ? Items.spruce_door - : (this == Blocks.birch_door ? Items.birch_door - : (this == Blocks.jungle_door ? Items.jungle_door - : (this == Blocks.acacia_door ? Items.acacia_door - : (this == Blocks.dark_oak_door ? Items.dark_oak_door - : Items.oak_door))))); - } - - public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { - BlockPos blockpos1 = blockpos.down(); - if (entityplayer.capabilities.isCreativeMode && iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER - && world.getBlockState(blockpos1).getBlock() == this) { - world.setBlockToAir(blockpos1); - } - - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - if (iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.LOWER) { - IBlockState iblockstate1 = iblockaccess.getBlockState(blockpos.up()); - if (iblockstate1.getBlock() == this) { - iblockstate = iblockstate.withProperty(HINGE, iblockstate1.getValue(HINGE)).withProperty(POWERED, - iblockstate1.getValue(POWERED)); - } - } else { - IBlockState iblockstate2 = iblockaccess.getBlockState(blockpos.down()); - if (iblockstate2.getBlock() == this) { - iblockstate = iblockstate.withProperty(FACING, iblockstate2.getValue(FACING)).withProperty(OPEN, - iblockstate2.getValue(OPEN)); - } - } - - return iblockstate; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return (i & 8) > 0 - ? this.getDefaultState().withProperty(HALF, BlockDoor.EnumDoorHalf.UPPER) - .withProperty(HINGE, - (i & 1) > 0 ? BlockDoor.EnumHingePosition.RIGHT : BlockDoor.EnumHingePosition.LEFT) - .withProperty(POWERED, Boolean.valueOf((i & 2) > 0)) - : this.getDefaultState().withProperty(HALF, BlockDoor.EnumDoorHalf.LOWER) - .withProperty(FACING, EnumFacing.getHorizontal(i & 3).rotateYCCW()) - .withProperty(OPEN, Boolean.valueOf((i & 4) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - if (iblockstate.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER) { - i = i | 8; - if (iblockstate.getValue(HINGE) == BlockDoor.EnumHingePosition.RIGHT) { - i |= 1; - } - - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 2; - } - } else { - i = i | ((EnumFacing) iblockstate.getValue(FACING)).rotateY().getHorizontalIndex(); - if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { - i |= 4; - } - } - - return i; - } - - protected static int removeHalfBit(int meta) { - return meta & 7; - } - - public static boolean isOpen(IBlockAccess worldIn, BlockPos pos) { - return isOpen(combineMetadata(worldIn, pos)); - } - - public static EnumFacing getFacing(IBlockAccess worldIn, BlockPos pos) { - return getFacing(combineMetadata(worldIn, pos)); - } - - public static EnumFacing getFacing(int combinedMeta) { - return EnumFacing.getHorizontal(combinedMeta & 3).rotateYCCW(); - } - - protected static boolean isOpen(int combinedMeta) { - return (combinedMeta & 4) != 0; - } - - protected static boolean isTop(int meta) { - return (meta & 8) != 0; - } - - protected static boolean isHingeLeft(int combinedMeta) { - return (combinedMeta & 16) != 0; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { HALF, FACING, OPEN, HINGE, POWERED }); - } - - public static enum EnumDoorHalf implements IStringSerializable { - UPPER, LOWER; - - public String toString() { - return this.getName(); - } - - public String getName() { - return this == UPPER ? "upper" : "lower"; - } - } - - public static enum EnumHingePosition implements IStringSerializable { - LEFT, RIGHT; - - public String toString() { - return this.getName(); - } - - public String getName() { - return this == LEFT ? "left" : "right"; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDoublePlant.java b/src/game/java/net/minecraft/block/BlockDoublePlant.java index 212241df..d41f2298 100644 --- a/src/game/java/net/minecraft/block/BlockDoublePlant.java +++ b/src/game/java/net/minecraft/block/BlockDoublePlant.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -24,31 +24,107 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeColorHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockDoublePlant extends BlockBush implements IGrowable { + public static enum EnumBlockHalf implements IStringSerializable { + UPPER, LOWER; + + public String getName() { + return this == UPPER ? "upper" : "lower"; + } + + public String toString() { + return this.getName(); + } + } + + public static enum EnumPlantType implements IStringSerializable { + SUNFLOWER(0, "sunflower"), SYRINGA(1, "syringa"), GRASS(2, "double_grass", "grass"), + FERN(3, "double_fern", "fern"), ROSE(4, "double_rose", "rose"), PAEONIA(5, "paeonia"); + + private static final BlockDoublePlant.EnumPlantType[] META_LOOKUP = new BlockDoublePlant.EnumPlantType[6]; + static { + BlockDoublePlant.EnumPlantType[] types = BlockDoublePlant.EnumPlantType.values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMeta()] = types[i]; + } + + } + + public static BlockDoublePlant.EnumPlantType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + + private final String name; + + private final String unlocalizedName; + + private EnumPlantType(int meta, String name) { + this(meta, name, name); + } + + private EnumPlantType(int meta, String name, String unlocalizedName) { + this.meta = meta; + this.name = name; + this.unlocalizedName = unlocalizedName; + } + + public int getMeta() { + return this.meta; + } + + public String getName() { + return this.name; + } + + public String getUnlocalizedName() { + return this.unlocalizedName; + } + + public String toString() { + return this.name; + } + } + public static PropertyEnum VARIANT; + public static PropertyEnum HALF; + public static final PropertyEnum field_181084_N = BlockDirectional.FACING; + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockDoublePlant.EnumPlantType.class); + HALF = PropertyEnum.create("half", BlockDoublePlant.EnumBlockHalf.class); + } + public BlockDoublePlant() { super(Material.vine); this.setDefaultState( @@ -60,43 +136,30 @@ public class BlockDoublePlant extends BlockBush implements IGrowable { this.setUnlocalizedName("doublePlant"); } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockDoublePlant.EnumPlantType.class); - HALF = PropertyEnum.create("half", BlockDoublePlant.EnumBlockHalf.class); - } - - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - } - - public BlockDoublePlant.EnumPlantType getVariant(IBlockAccess worldIn, BlockPos pos) { - IBlockState iblockstate = worldIn.getBlockState(pos); - if (iblockstate.getBlock() == this) { - iblockstate = this.getActualState(iblockstate, worldIn, pos); - return (BlockDoublePlant.EnumPlantType) iblockstate.getValue(VARIANT); + public boolean canBlockStay(World world, BlockPos blockpos, IBlockState iblockstate) { + if (iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER) { + return world.getBlockState(blockpos.down()).getBlock() == this; } else { - return BlockDoublePlant.EnumPlantType.FERN; + IBlockState iblockstate1 = world.getBlockState(blockpos.up()); + return iblockstate1.getBlock() == this && super.canBlockStay(world, blockpos, iblockstate1); } } + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World world, BlockPos blockpos, IBlockState var3, boolean var4) { + BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = this.getVariant(world, blockpos); + return blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.GRASS + && blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.FERN; + } + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { return super.canPlaceBlockAt(world, blockpos) && world.isAirBlock(blockpos.up()); } - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) - */ - public boolean isReplaceable(World world, BlockPos blockpos) { - IBlockState iblockstate = world.getBlockState(blockpos); - if (iblockstate.getBlock() != this) { - return true; - } else { - BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = (BlockDoublePlant.EnumPlantType) this - .getActualState(iblockstate, world, blockpos).getValue(VARIANT); - return blockdoubleplant$enumplanttype == BlockDoublePlant.EnumPlantType.FERN - || blockdoubleplant$enumplanttype == BlockDoublePlant.EnumPlantType.GRASS; - } + public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return true; } protected void checkAndDropBlock(World world, BlockPos blockpos, IBlockState iblockstate) { @@ -120,17 +183,50 @@ public class BlockDoublePlant extends BlockBush implements IGrowable { } } - public boolean canBlockStay(World world, BlockPos blockpos, IBlockState iblockstate) { - if (iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER) { - return world.getBlockState(blockpos.down()).getBlock() == this; - } else { - IBlockState iblockstate1 = world.getBlockState(blockpos.up()); - return iblockstate1.getBlock() == this && super.canBlockStay(world, blockpos, iblockstate1); - } + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = this.getVariant(iblockaccess, blockpos); + return blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.GRASS + && blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.FERN ? 16777215 + : BiomeColorHelper.getGrassColorAtPos(iblockaccess, blockpos); } - /**+ - * Get the Item that this Block should drop when harvested. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { HALF, VARIANT, field_181084_N }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return iblockstate.getValue(HALF) != BlockDoublePlant.EnumBlockHalf.UPPER + && iblockstate.getValue(VARIANT) != BlockDoublePlant.EnumPlantType.GRASS + ? ((BlockDoublePlant.EnumPlantType) iblockstate.getValue(VARIANT)).getMeta() + : 0; + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + if (iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER) { + IBlockState iblockstate1 = iblockaccess.getBlockState(blockpos.down()); + if (iblockstate1.getBlock() == this) { + iblockstate = iblockstate.withProperty(VARIANT, iblockstate1.getValue(VARIANT)); + } + } + + return iblockstate; + } + + public int getDamageValue(World world, BlockPos blockpos) { + return this.getVariant(world, blockpos).getMeta(); + } + + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom random, int var3) { if (iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER) { @@ -145,41 +241,56 @@ public class BlockDoublePlant extends BlockBush implements IGrowable { } } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + Convert the BlockState into the correct metadata value */ - public int damageDropped(IBlockState iblockstate) { - return iblockstate.getValue(HALF) != BlockDoublePlant.EnumBlockHalf.UPPER - && iblockstate.getValue(VARIANT) != BlockDoublePlant.EnumPlantType.GRASS - ? ((BlockDoublePlant.EnumPlantType) iblockstate.getValue(VARIANT)).getMeta() - : 0; + public int getMetaFromState(IBlockState iblockstate) { + return iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER + ? 8 | ((EnumFacing) iblockstate.getValue(field_181084_N)).getHorizontalIndex() + : ((BlockDoublePlant.EnumPlantType) iblockstate.getValue(VARIANT)).getMeta(); } - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = this.getVariant(iblockaccess, blockpos); - return blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.GRASS - && blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.FERN ? 16777215 - : BiomeColorHelper.getGrassColorAtPos(iblockaccess, blockpos); - } - - public void placeAt(World worldIn, BlockPos lowerPos, BlockDoublePlant.EnumPlantType variant, int flags) { - worldIn.setBlockState(lowerPos, this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER) - .withProperty(VARIANT, variant), flags); - worldIn.setBlockState(lowerPos.up(), - this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER), flags); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic + /** + * + Get the OffsetType for this Block. Determines if the model is rendered + * slightly offset. */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState var3, EntityLivingBase var4, - ItemStack var5) { - world.setBlockState(blockpos.up(), - this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER), 2); + public Block.EnumOffsetType getOffsetType() { + return Block.EnumOffsetType.XZ; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return (i & 8) > 0 ? this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER) + : this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER).withProperty(VARIANT, + BlockDoublePlant.EnumPlantType.byMetadata(i & 7)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockDoublePlant.EnumPlantType[] types = BlockDoublePlant.EnumPlantType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMeta())); + } + + } + + public BlockDoublePlant.EnumPlantType getVariant(IBlockAccess worldIn, BlockPos pos) { + IBlockState iblockstate = worldIn.getBlockState(pos); + if (iblockstate.getBlock() == this) { + iblockstate = this.getActualState(iblockstate, worldIn, pos); + return (BlockDoublePlant.EnumPlantType) iblockstate.getValue(VARIANT); + } else { + return BlockDoublePlant.EnumPlantType.FERN; + } + } + + public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState var4) { + spawnAsEntity(world, blockpos, new ItemStack(this, 1, this.getVariant(world, blockpos).getMeta())); } public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, @@ -192,6 +303,22 @@ public class BlockDoublePlant extends BlockBush implements IGrowable { } } + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) + */ + public boolean isReplaceable(World world, BlockPos blockpos) { + IBlockState iblockstate = world.getBlockState(blockpos); + if (iblockstate.getBlock() != this) { + return true; + } else { + BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = (BlockDoublePlant.EnumPlantType) this + .getActualState(iblockstate, world, blockpos).getValue(VARIANT); + return blockdoubleplant$enumplanttype == BlockDoublePlant.EnumPlantType.FERN + || blockdoubleplant$enumplanttype == BlockDoublePlant.EnumPlantType.GRASS; + } + } + public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { if (iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER) { if (world.getBlockState(blockpos.down()).getBlock() == this) { @@ -224,6 +351,16 @@ public class BlockDoublePlant extends BlockBush implements IGrowable { super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); } + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState var3, EntityLivingBase var4, + ItemStack var5) { + world.setBlockState(blockpos.up(), + this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER), 2); + } + private boolean onHarvest(World worldIn, BlockPos pos, IBlockState state, EntityPlayer player) { BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = (BlockDoublePlant.EnumPlantType) state .getValue(VARIANT); @@ -240,146 +377,14 @@ public class BlockDoublePlant extends BlockBush implements IGrowable { } } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockDoublePlant.EnumPlantType[] types = BlockDoublePlant.EnumPlantType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMeta())); - } - + public void placeAt(World worldIn, BlockPos lowerPos, BlockDoublePlant.EnumPlantType variant, int flags) { + worldIn.setBlockState(lowerPos, this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER) + .withProperty(VARIANT, variant), flags); + worldIn.setBlockState(lowerPos.up(), + this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER), flags); } - public int getDamageValue(World world, BlockPos blockpos) { - return this.getVariant(world, blockpos).getMeta(); - } - - /**+ - * Whether this IGrowable can grow - */ - public boolean canGrow(World world, BlockPos blockpos, IBlockState var3, boolean var4) { - BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = this.getVariant(world, blockpos); - return blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.GRASS - && blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.FERN; - } - - public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { - return true; - } - - public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState var4) { - spawnAsEntity(world, blockpos, new ItemStack(this, 1, this.getVariant(world, blockpos).getMeta())); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return (i & 8) > 0 ? this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.UPPER) - : this.getDefaultState().withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER).withProperty(VARIANT, - BlockDoublePlant.EnumPlantType.byMetadata(i & 7)); - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - if (iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER) { - IBlockState iblockstate1 = iblockaccess.getBlockState(blockpos.down()); - if (iblockstate1.getBlock() == this) { - iblockstate = iblockstate.withProperty(VARIANT, iblockstate1.getValue(VARIANT)); - } - } - - return iblockstate; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return iblockstate.getValue(HALF) == BlockDoublePlant.EnumBlockHalf.UPPER - ? 8 | ((EnumFacing) iblockstate.getValue(field_181084_N)).getHorizontalIndex() - : ((BlockDoublePlant.EnumPlantType) iblockstate.getValue(VARIANT)).getMeta(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { HALF, VARIANT, field_181084_N }); - } - - /**+ - * Get the OffsetType for this Block. Determines if the model is - * rendered slightly offset. - */ - public Block.EnumOffsetType getOffsetType() { - return Block.EnumOffsetType.XZ; - } - - public static enum EnumBlockHalf implements IStringSerializable { - UPPER, LOWER; - - public String toString() { - return this.getName(); - } - - public String getName() { - return this == UPPER ? "upper" : "lower"; - } - } - - public static enum EnumPlantType implements IStringSerializable { - SUNFLOWER(0, "sunflower"), SYRINGA(1, "syringa"), GRASS(2, "double_grass", "grass"), - FERN(3, "double_fern", "fern"), ROSE(4, "double_rose", "rose"), PAEONIA(5, "paeonia"); - - private static final BlockDoublePlant.EnumPlantType[] META_LOOKUP = new BlockDoublePlant.EnumPlantType[6]; - private final int meta; - private final String name; - private final String unlocalizedName; - - private EnumPlantType(int meta, String name) { - this(meta, name, name); - } - - private EnumPlantType(int meta, String name, String unlocalizedName) { - this.meta = meta; - this.name = name; - this.unlocalizedName = unlocalizedName; - } - - public int getMeta() { - return this.meta; - } - - public String toString() { - return this.name; - } - - public static BlockDoublePlant.EnumPlantType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { - return this.name; - } - - public String getUnlocalizedName() { - return this.unlocalizedName; - } - - static { - BlockDoublePlant.EnumPlantType[] types = BlockDoublePlant.EnumPlantType.values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMeta()] = types[i]; - } - - } + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDoubleStoneSlab.java b/src/game/java/net/minecraft/block/BlockDoubleStoneSlab.java index 8a6be080..b4bf18d5 100644 --- a/src/game/java/net/minecraft/block/BlockDoubleStoneSlab.java +++ b/src/game/java/net/minecraft/block/BlockDoubleStoneSlab.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockDoubleStoneSlabNew.java b/src/game/java/net/minecraft/block/BlockDoubleStoneSlabNew.java index 9d076e84..b008df8f 100644 --- a/src/game/java/net/minecraft/block/BlockDoubleStoneSlabNew.java +++ b/src/game/java/net/minecraft/block/BlockDoubleStoneSlabNew.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockDoubleWoodSlab.java b/src/game/java/net/minecraft/block/BlockDoubleWoodSlab.java index a377afb6..b83ee969 100644 --- a/src/game/java/net/minecraft/block/BlockDoubleWoodSlab.java +++ b/src/game/java/net/minecraft/block/BlockDoubleWoodSlab.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockDragonEgg.java b/src/game/java/net/minecraft/block/BlockDragonEgg.java index ea7d7bcc..90495395 100644 --- a/src/game/java/net/minecraft/block/BlockDragonEgg.java +++ b/src/game/java/net/minecraft/block/BlockDragonEgg.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -14,22 +13,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,21 +42,6 @@ public class BlockDragonEgg extends Block { this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } - - public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { - this.checkFall(world, blockpos); - } - private void checkFall(World worldIn, BlockPos pos) { if (BlockFalling.canFallInto(worldIn, pos.down()) && pos.getY() >= 0) { byte b0 = 32; @@ -78,16 +65,47 @@ public class BlockDragonEgg extends Block { } } + public Item getItem(World var1, BlockPos var2) { + return null; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer var4, EnumFacing var5, float var6, float var7, float var8) { this.teleport(world, blockpos); return true; } + public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + } + public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer var3) { this.teleport(world, blockpos); } + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + } + + public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { + return true; + } + private void teleport(World worldIn, BlockPos pos) { IBlockState iblockstate = worldIn.getBlockState(pos); if (iblockstate.getBlock() == this) { @@ -123,30 +141,14 @@ public class BlockDragonEgg extends Block { } } - /**+ - * How many world ticks before ticking + /** + * + How many world ticks before ticking */ public int tickRate(World var1) { return 5; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { - return true; - } - - public Item getItem(World var1, BlockPos var2) { - return null; + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { + this.checkFall(world, blockpos); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDropper.java b/src/game/java/net/minecraft/block/BlockDropper.java index 01f7a6e2..d72c4339 100644 --- a/src/game/java/net/minecraft/block/BlockDropper.java +++ b/src/game/java/net/minecraft/block/BlockDropper.java @@ -12,22 +12,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,13 +38,9 @@ import net.minecraft.world.World; public class BlockDropper extends BlockDispenser { private final IBehaviorDispenseItem dropBehavior = new BehaviorDefaultDispenseItem(); - protected IBehaviorDispenseItem getBehavior(ItemStack var1) { - return this.dropBehavior; - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ public TileEntity createNewTileEntity(World var1, int var2) { return new TileEntityDropper(); @@ -85,4 +84,8 @@ public class BlockDropper extends BlockDispenser { } } } + + protected IBehaviorDispenseItem getBehavior(ItemStack var1) { + return this.dropBehavior; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockDynamicLiquid.java b/src/game/java/net/minecraft/block/BlockDynamicLiquid.java index 0abd8fef..81f5cc81 100644 --- a/src/game/java/net/minecraft/block/BlockDynamicLiquid.java +++ b/src/game/java/net/minecraft/block/BlockDynamicLiquid.java @@ -1,9 +1,9 @@ package net.minecraft.block; import java.util.EnumSet; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Set; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -11,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,12 +41,129 @@ public class BlockDynamicLiquid extends BlockLiquid { super(materialIn); } + private boolean canFlowInto(World worldIn, BlockPos pos, IBlockState state) { + Material material = state.getBlock().getMaterial(); + return material != this.blockMaterial && material != Material.lava && !this.isBlocked(worldIn, pos, state); + } + + protected int checkAdjacentBlock(World worldIn, BlockPos pos, int currentMinLevel) { + int i = this.getLevel(worldIn, pos); + if (i < 0) { + return currentMinLevel; + } else { + if (i == 0) { + ++this.adjacentSourceBlocks; + } + + if (i >= 8) { + i = 0; + } + + return currentMinLevel >= 0 && i >= currentMinLevel ? currentMinLevel : i; + } + } + + private int func_176374_a(World worldIn, BlockPos pos, int distance, EnumFacing calculateFlowCost) { + int i = 1000; + + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int l = 0; l < facings.length; ++l) { + EnumFacing enumfacing = facings[l]; + if (enumfacing != calculateFlowCost) { + BlockPos blockpos = pos.offset(enumfacing); + IBlockState iblockstate = worldIn.getBlockState(blockpos); + if (!this.isBlocked(worldIn, blockpos, iblockstate) + && (iblockstate.getBlock().getMaterial() != this.blockMaterial + || ((Integer) iblockstate.getValue(LEVEL)).intValue() > 0)) { + if (!this.isBlocked(worldIn, blockpos.down(), iblockstate)) { + return distance; + } + + if (distance < 4) { + int j = this.func_176374_a(worldIn, blockpos, distance + 1, enumfacing.getOpposite()); + if (j < i) { + i = j; + } + } + } + } + } + + return i; + } + + /** + * + This method returns a Set of EnumFacing + */ + private Set getPossibleFlowDirections(World worldIn, BlockPos pos) { + int i = 1000; + EnumSet enumset = EnumSet.noneOf(EnumFacing.class); + + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int k = 0; k < facings.length; ++k) { + EnumFacing enumfacing = facings[k]; + BlockPos blockpos = pos.offset(enumfacing); + IBlockState iblockstate = worldIn.getBlockState(blockpos); + if (!this.isBlocked(worldIn, blockpos, iblockstate) + && (iblockstate.getBlock().getMaterial() != this.blockMaterial + || ((Integer) iblockstate.getValue(LEVEL)).intValue() > 0)) { + int j; + if (this.isBlocked(worldIn, blockpos.down(), worldIn.getBlockState(blockpos.down()))) { + j = this.func_176374_a(worldIn, blockpos, 1, enumfacing.getOpposite()); + } else { + j = 0; + } + + if (j < i) { + enumset.clear(); + } + + if (j <= i) { + enumset.add(enumfacing); + i = j; + } + } + } + + return enumset; + } + + private boolean isBlocked(World worldIn, BlockPos pos, IBlockState state) { + Block block = worldIn.getBlockState(pos).getBlock(); + return !(block instanceof BlockDoor) && block != Blocks.standing_sign && block != Blocks.ladder + && block != Blocks.reeds + ? (block.blockMaterial == Material.portal ? true : block.blockMaterial.blocksMovement()) + : true; + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + if (!this.checkForMixing(world, blockpos, iblockstate)) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + } + + } + private void placeStaticBlock(World worldIn, BlockPos pos, IBlockState currentState) { worldIn.setBlockState(pos, getStaticBlock(this.blockMaterial).getDefaultState().withProperty(LEVEL, currentState.getValue(LEVEL)), 2); } + private void tryFlowInto(World worldIn, BlockPos pos, IBlockState state, int level) { + if (this.canFlowInto(worldIn, pos, state)) { + if (state.getBlock() != Blocks.air) { + if (this.blockMaterial == Material.lava) { + this.triggerMixEffects(worldIn, pos); + } else { + state.getBlock().dropBlockAsItem(worldIn, pos, state, 0); + } + } + + worldIn.setBlockState(pos, this.getDefaultState().withProperty(LEVEL, Integer.valueOf(level)), 3); + } + + } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { int i = ((Integer) iblockstate.getValue(LEVEL)).intValue(); byte b0 = 1; @@ -139,121 +259,4 @@ public class BlockDynamicLiquid extends BlockLiquid { } } - - private void tryFlowInto(World worldIn, BlockPos pos, IBlockState state, int level) { - if (this.canFlowInto(worldIn, pos, state)) { - if (state.getBlock() != Blocks.air) { - if (this.blockMaterial == Material.lava) { - this.triggerMixEffects(worldIn, pos); - } else { - state.getBlock().dropBlockAsItem(worldIn, pos, state, 0); - } - } - - worldIn.setBlockState(pos, this.getDefaultState().withProperty(LEVEL, Integer.valueOf(level)), 3); - } - - } - - private int func_176374_a(World worldIn, BlockPos pos, int distance, EnumFacing calculateFlowCost) { - int i = 1000; - - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int l = 0; l < facings.length; ++l) { - EnumFacing enumfacing = facings[l]; - if (enumfacing != calculateFlowCost) { - BlockPos blockpos = pos.offset(enumfacing); - IBlockState iblockstate = worldIn.getBlockState(blockpos); - if (!this.isBlocked(worldIn, blockpos, iblockstate) - && (iblockstate.getBlock().getMaterial() != this.blockMaterial - || ((Integer) iblockstate.getValue(LEVEL)).intValue() > 0)) { - if (!this.isBlocked(worldIn, blockpos.down(), iblockstate)) { - return distance; - } - - if (distance < 4) { - int j = this.func_176374_a(worldIn, blockpos, distance + 1, enumfacing.getOpposite()); - if (j < i) { - i = j; - } - } - } - } - } - - return i; - } - - /**+ - * This method returns a Set of EnumFacing - */ - private Set getPossibleFlowDirections(World worldIn, BlockPos pos) { - int i = 1000; - EnumSet enumset = EnumSet.noneOf(EnumFacing.class); - - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int k = 0; k < facings.length; ++k) { - EnumFacing enumfacing = facings[k]; - BlockPos blockpos = pos.offset(enumfacing); - IBlockState iblockstate = worldIn.getBlockState(blockpos); - if (!this.isBlocked(worldIn, blockpos, iblockstate) - && (iblockstate.getBlock().getMaterial() != this.blockMaterial - || ((Integer) iblockstate.getValue(LEVEL)).intValue() > 0)) { - int j; - if (this.isBlocked(worldIn, blockpos.down(), worldIn.getBlockState(blockpos.down()))) { - j = this.func_176374_a(worldIn, blockpos, 1, enumfacing.getOpposite()); - } else { - j = 0; - } - - if (j < i) { - enumset.clear(); - } - - if (j <= i) { - enumset.add(enumfacing); - i = j; - } - } - } - - return enumset; - } - - private boolean isBlocked(World worldIn, BlockPos pos, IBlockState state) { - Block block = worldIn.getBlockState(pos).getBlock(); - return !(block instanceof BlockDoor) && block != Blocks.standing_sign && block != Blocks.ladder - && block != Blocks.reeds - ? (block.blockMaterial == Material.portal ? true : block.blockMaterial.blocksMovement()) - : true; - } - - protected int checkAdjacentBlock(World worldIn, BlockPos pos, int currentMinLevel) { - int i = this.getLevel(worldIn, pos); - if (i < 0) { - return currentMinLevel; - } else { - if (i == 0) { - ++this.adjacentSourceBlocks; - } - - if (i >= 8) { - i = 0; - } - - return currentMinLevel >= 0 && i >= currentMinLevel ? currentMinLevel : i; - } - } - - private boolean canFlowInto(World worldIn, BlockPos pos, IBlockState state) { - Material material = state.getBlock().getMaterial(); - return material != this.blockMaterial && material != Material.lava && !this.isBlocked(worldIn, pos, state); - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - if (!this.checkForMixing(world, blockpos, iblockstate)) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockEnchantmentTable.java b/src/game/java/net/minecraft/block/BlockEnchantmentTable.java index 6f31105d..c2a23996 100644 --- a/src/game/java/net/minecraft/block/BlockEnchantmentTable.java +++ b/src/game/java/net/minecraft/block/BlockEnchantmentTable.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -17,22 +16,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,10 +47,61 @@ public class BlockEnchantmentTable extends BlockContainer { this.setCreativeTab(CreativeTabs.tabDecorations); } + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityEnchantmentTable(); + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + public boolean isFullCube() { return false; } + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (!world.isRemote) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityEnchantmentTable) { + entityplayer.displayGui((TileEntityEnchantmentTable) tileentity); + } + } + return true; + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack itemstack) { + super.onBlockPlacedBy(world, blockpos, iblockstate, entitylivingbase, itemstack); + if (itemstack.hasDisplayName()) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityEnchantmentTable) { + ((TileEntityEnchantmentTable) tileentity).setCustomName(itemstack.getDisplayName()); + } + } + + } + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { super.randomDisplayTick(world, blockpos, iblockstate, random); @@ -78,55 +131,4 @@ public class BlockEnchantmentTable extends BlockContainer { } } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityEnchantmentTable(); - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (!world.isRemote) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityEnchantmentTable) { - entityplayer.displayGui((TileEntityEnchantmentTable) tileentity); - } - } - return true; - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack itemstack) { - super.onBlockPlacedBy(world, blockpos, iblockstate, entitylivingbase, itemstack); - if (itemstack.hasDisplayName()) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityEnchantmentTable) { - ((TileEntityEnchantmentTable) tileentity).setCustomName(itemstack.getDisplayName()); - } - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockEndPortal.java b/src/game/java/net/minecraft/block/BlockEndPortal.java index de2ba7a7..968001aa 100644 --- a/src/game/java/net/minecraft/block/BlockEndPortal.java +++ b/src/game/java/net/minecraft/block/BlockEndPortal.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -17,22 +17,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,52 +46,47 @@ public class BlockEndPortal extends BlockContainer { this.setLightLevel(1.0F); } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityEndPortal(); - } - - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - float f = 0.0625F; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, f, 1.0F); - } - - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - return enumfacing == EnumFacing.DOWN ? super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing) : false; - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World var1, BlockPos var2, IBlockState var3, AxisAlignedBB var4, List var5, Entity var6) { } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ - public boolean isOpaqueCube() { - return false; + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityEndPortal(); + } + + public Item getItem(World var1, BlockPos var2) { + return null; + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState var1) { + return MapColor.blackColor; } public boolean isFullCube() { return false; } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; + public boolean isOpaqueCube() { + return false; } - /**+ - * Called When an Entity Collided with the Block + /** + * + Called When an Entity Collided with the Block */ public void onEntityCollidedWithBlock(World world, BlockPos var2, IBlockState var3, Entity entity) { if (entity.ridingEntity == null && entity.riddenByEntity == null && !world.isRemote) { @@ -97,6 +95,13 @@ public class BlockEndPortal extends BlockContainer { } + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { double d0 = (double) ((float) blockpos.getX() + random.nextFloat()); double d1 = (double) ((float) blockpos.getY() + 0.8F); @@ -107,14 +112,12 @@ public class BlockEndPortal extends BlockContainer { world.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0, d1, d2, d3, d4, d5, new int[0]); } - public Item getItem(World var1, BlockPos var2) { - return null; + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + float f = 0.0625F; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, f, 1.0F); } - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState var1) { - return MapColor.blackColor; + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + return enumfacing == EnumFacing.DOWN ? super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing) : false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockEndPortalFrame.java b/src/game/java/net/minecraft/block/BlockEndPortalFrame.java index 2ff8c994..63e8de77 100644 --- a/src/game/java/net/minecraft/block/BlockEndPortalFrame.java +++ b/src/game/java/net/minecraft/block/BlockEndPortalFrame.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -18,22 +18,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,24 +51,9 @@ public class BlockEndPortalFrame extends Block { Boolean.valueOf(false))); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.8125F, 1.0F); - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -79,41 +67,23 @@ public class BlockEndPortalFrame extends Block { this.setBlockBoundsForItemRender(); } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return null; - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()) - .withProperty(EYE, Boolean.valueOf(false)); - } - - public boolean hasComparatorInputOverride() { - return true; + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, EYE }); } public int getComparatorInputOverride(World world, BlockPos blockpos) { return ((Boolean) world.getBlockState(blockpos).getValue(EYE)).booleanValue() ? 15 : 0; } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Get the Item that this Block should drop when harvested. */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(EYE, Boolean.valueOf((i & 4) != 0)).withProperty(FACING, - EnumFacing.getHorizontal(i & 3)); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -125,7 +95,40 @@ public class BlockEndPortalFrame extends Block { return i; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, EYE }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(EYE, Boolean.valueOf((i & 4) != 0)).withProperty(FACING, + EnumFacing.getHorizontal(i & 3)); + } + + public boolean hasComparatorInputOverride() { + return true; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()) + .withProperty(EYE, Boolean.valueOf(false)); + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.8125F, 1.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockEnderChest.java b/src/game/java/net/minecraft/block/BlockEnderChest.java index a76c9151..4113949e 100644 --- a/src/game/java/net/minecraft/block/BlockEnderChest.java +++ b/src/game/java/net/minecraft/block/BlockEnderChest.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -22,22 +21,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,61 +54,66 @@ public class BlockEnderChest extends BlockContainer { this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + protected boolean canSilkHarvest() { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ - public boolean isOpaqueCube() { - return false; + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityEnderChest(); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.obsidian); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 2; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getFront(i); + if (enumfacing.getAxis() == EnumFacing.Axis.Y) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing); } public boolean isFullCube() { return false; } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ - public int getRenderType() { - return 2; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.obsidian); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 8; - } - - protected boolean canSilkHarvest() { - return true; - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack var5) { - world.setBlockState(blockpos, - iblockstate.withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()), 2); + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, @@ -129,12 +136,30 @@ public class BlockEnderChest extends BlockContainer { } } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityEnderChest(); + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack var5) { + world.setBlockState(blockpos, + iblockstate.withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()), 2); + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 8; } public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { @@ -151,27 +176,4 @@ public class BlockEnderChest extends BlockContainer { } } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getFront(i); - if (enumfacing.getAxis() == EnumFacing.Axis.Y) { - enumfacing = EnumFacing.NORTH; - } - - return this.getDefaultState().withProperty(FACING, enumfacing); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockEventData.java b/src/game/java/net/minecraft/block/BlockEventData.java index 2d7e4495..d07752c3 100644 --- a/src/game/java/net/minecraft/block/BlockEventData.java +++ b/src/game/java/net/minecraft/block/BlockEventData.java @@ -2,22 +2,25 @@ package net.minecraft.block; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,25 +38,6 @@ public class BlockEventData { this.blockType = blockType; } - public BlockPos getPosition() { - return this.position; - } - - /**+ - * Get the Event ID (different for each BlockID) - */ - public int getEventID() { - return this.eventID; - } - - public int getEventParameter() { - return this.eventParameter; - } - - public Block getBlock() { - return this.blockType; - } - public boolean equals(Object parObject) { if (!(parObject instanceof BlockEventData)) { return false; @@ -65,6 +49,25 @@ public class BlockEventData { } } + public Block getBlock() { + return this.blockType; + } + + /** + * + Get the Event ID (different for each BlockID) + */ + public int getEventID() { + return this.eventID; + } + + public int getEventParameter() { + return this.eventParameter; + } + + public BlockPos getPosition() { + return this.position; + } + public String toString() { return "TE(" + this.position + ")," + this.eventID + "," + this.eventParameter + "," + this.blockType; } diff --git a/src/game/java/net/minecraft/block/BlockFabricator.java b/src/game/java/net/minecraft/block/BlockFabricator.java new file mode 100644 index 00000000..a0692d7c --- /dev/null +++ b/src/game/java/net/minecraft/block/BlockFabricator.java @@ -0,0 +1,88 @@ +package net.minecraft.block; + +import net.minecraft.block.material.Material; +import net.minecraft.block.state.IBlockState; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.inventory.Container; +import net.minecraft.inventory.ContainerFabricator; +import net.minecraft.stats.StatList; +import net.minecraft.util.BlockPos; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.EnumFacing; +import net.minecraft.util.IChatComponent; +import net.minecraft.world.IInteractionObject; +import net.minecraft.world.World; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class BlockFabricator extends Block { + public static class InterfaceCraftingTable implements IInteractionObject { + private final World world; + private final BlockPos position; + + public InterfaceCraftingTable(World worldIn, BlockPos pos) { + this.world = worldIn; + this.position = pos; + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerFabricator(inventoryplayer, this.world, this.position); + } + + public IChatComponent getDisplayName() { + return new ChatComponentTranslation(Blocks.fabricator.getUnlocalizedName() + ".name", new Object[0]); + } + + public String getGuiID() { + return "minecraft:crafting_table"; + } + + public String getName() { + return null; + } + + public boolean hasCustomName() { + return false; + } + } + + protected BlockFabricator() { + super(Material.wood); + this.setCreativeTab(CreativeTabs.tabDecorations); + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (world.isRemote) { + return true; + } else { + entityplayer.displayGui(new BlockFabricator.InterfaceCraftingTable(world, blockpos)); + entityplayer.triggerAchievement(StatList.field_181742_Z); + return true; + } + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFalling.java b/src/game/java/net/minecraft/block/BlockFalling.java index 698027c0..bb76c9e9 100644 --- a/src/game/java/net/minecraft/block/BlockFalling.java +++ b/src/game/java/net/minecraft/block/BlockFalling.java @@ -9,22 +9,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,6 +35,13 @@ import net.minecraft.world.World; public class BlockFalling extends Block { public static boolean fallInstantly; + public static boolean canFallInto(World worldIn, BlockPos pos) { + Block block = worldIn.getBlockState(pos).getBlock(); + Material material = block.blockMaterial; + return block == Blocks.fire || material == Material.air || material == Material.water + || material == Material.lava; + } + public BlockFalling() { super(Material.sand); this.setCreativeTab(CreativeTabs.tabBlock); @@ -41,23 +51,6 @@ public class BlockFalling extends Block { super(materialIn); } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } - - public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { - if (!world.isRemote) { - this.checkFallable(world, blockpos); - } - } - private void checkFallable(World worldIn, BlockPos pos) { if (canFallInto(worldIn, pos.down()) && pos.getY() >= 0) { byte b0 = 32; @@ -83,23 +76,33 @@ public class BlockFalling extends Block { } } + public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + } + + public void onEndFalling(World var1, BlockPos var2) { + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); + } + protected void onStartFalling(EntityFallingBlock var1) { } - /**+ - * How many world ticks before ticking + /** + * + How many world ticks before ticking */ public int tickRate(World var1) { return 2; } - public static boolean canFallInto(World worldIn, BlockPos pos) { - Block block = worldIn.getBlockState(pos).getBlock(); - Material material = block.blockMaterial; - return block == Blocks.fire || material == Material.air || material == Material.water - || material == Material.lava; - } - - public void onEndFalling(World var1, BlockPos var2) { + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { + if (!world.isRemote) { + this.checkFallable(world, blockpos); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFarmland.java b/src/game/java/net/minecraft/block/BlockFarmland.java index 6f39b55e..efd422f1 100644 --- a/src/game/java/net/minecraft/block/BlockFarmland.java +++ b/src/game/java/net/minecraft/block/BlockFarmland.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -18,22 +17,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,52 +51,39 @@ public class BlockFarmland extends Block { this.setLightOpacity(255); } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { MOISTURE }); + } + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { return new AxisAlignedBB((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), (double) (blockpos.getX() + 1), (double) (blockpos.getY() + 1), (double) (blockpos.getZ() + 1)); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(Blocks.dirt); + } + + /** + * + Get the Item that this Block should drop when harvested. */ - public boolean isOpaqueCube() { - return false; + public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int i) { + return Blocks.dirt.getItemDropped( + Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), random, i); } - public boolean isFullCube() { - return false; - } - - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - int i = ((Integer) iblockstate.getValue(MOISTURE)).intValue(); - if (!this.hasWater(world, blockpos) && !world.canLightningStrike(blockpos.up())) { - if (i > 0) { - world.setBlockState(blockpos, iblockstate.withProperty(MOISTURE, Integer.valueOf(i - 1)), 2); - } else if (!this.hasCrops(world, blockpos)) { - world.setBlockState(blockpos, Blocks.dirt.getDefaultState()); - } - } else if (i < 7) { - world.setBlockState(blockpos, iblockstate.withProperty(MOISTURE, Integer.valueOf(7)), 2); - } - - } - - /**+ - * Block's chance to react to a living entity falling on it. + /** + * + Convert the BlockState into the correct metadata value */ - public void onFallenUpon(World world, BlockPos blockpos, Entity entity, float f) { - if (entity instanceof EntityLivingBase) { - if (!world.isRemote && world.rand.nextFloat() < f - 0.5F) { - if (!(entity instanceof EntityPlayer) && !world.getGameRules().getBoolean("mobGriefing")) { - return; - } + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(MOISTURE)).intValue(); + } - world.setBlockState(blockpos, Blocks.dirt.getDefaultState()); - } - - super.onFallenUpon(world, blockpos, entity, f); - } + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(MOISTURE, Integer.valueOf(i & 7)); } private boolean hasCrops(World worldIn, BlockPos pos) { @@ -113,8 +102,37 @@ public class BlockFarmland extends Block { return false; } - /**+ - * Called when a neighboring block changes. + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Block's chance to react to a living entity falling on it. + */ + public void onFallenUpon(World world, BlockPos blockpos, Entity entity, float f) { + if (entity instanceof EntityLivingBase) { + if (!world.isRemote && world.rand.nextFloat() < f - 0.5F) { + if (!(entity instanceof EntityPlayer) && !world.getGameRules().getBoolean("mobGriefing")) { + return; + } + + world.setBlockState(blockpos, Blocks.dirt.getDefaultState()); + } + + super.onFallenUpon(world, blockpos, entity, f); + } + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { super.onNeighborBlockChange(world, blockpos, iblockstate, block); @@ -139,33 +157,17 @@ public class BlockFarmland extends Block { } } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int i) { - return Blocks.dirt.getItemDropped( - Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), random, i); - } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { + int i = ((Integer) iblockstate.getValue(MOISTURE)).intValue(); + if (!this.hasWater(world, blockpos) && !world.canLightningStrike(blockpos.up())) { + if (i > 0) { + world.setBlockState(blockpos, iblockstate.withProperty(MOISTURE, Integer.valueOf(i - 1)), 2); + } else if (!this.hasCrops(world, blockpos)) { + world.setBlockState(blockpos, Blocks.dirt.getDefaultState()); + } + } else if (i < 7) { + world.setBlockState(blockpos, iblockstate.withProperty(MOISTURE, Integer.valueOf(7)), 2); + } - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(Blocks.dirt); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(MOISTURE, Integer.valueOf(i & 7)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(MOISTURE)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { MOISTURE }); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFence.java b/src/game/java/net/minecraft/block/BlockFence.java index 81767df7..600291d8 100644 --- a/src/game/java/net/minecraft/block/BlockFence.java +++ b/src/game/java/net/minecraft/block/BlockFence.java @@ -19,41 +19,44 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockFence extends Block { - /**+ - * Whether this fence connects in the northern direction + /** + * + Whether this fence connects in the northern direction */ public static final PropertyBool NORTH = PropertyBool.create("north"); - /**+ - * Whether this fence connects in the eastern direction + /** + * + Whether this fence connects in the eastern direction */ public static final PropertyBool EAST = PropertyBool.create("east"); - /**+ - * Whether this fence connects in the southern direction + /** + * + Whether this fence connects in the southern direction */ public static final PropertyBool SOUTH = PropertyBool.create("south"); - /**+ - * Whether this fence connects in the western direction + /** + * + Whether this fence connects in the western direction */ public static final PropertyBool WEST = PropertyBool.create("west"); @@ -69,9 +72,9 @@ public class BlockFence extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -122,6 +125,60 @@ public class BlockFence extends Block { this.setBlockBounds(f, 0.0F, f2, f1, 1.0F, f3); } + public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { + Block block = worldIn.getBlockState(pos).getBlock(); + return block == Blocks.barrier ? false + : ((!(block instanceof BlockFence) || block.blockMaterial != this.blockMaterial) + && !(block instanceof BlockFenceGate) + ? (block.blockMaterial.isOpaque() && block.isFullCube() + ? block.blockMaterial != Material.gourd + : false) + : true); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { NORTH, EAST, WEST, SOUTH }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + return iblockstate.withProperty(NORTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.north()))) + .withProperty(EAST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.east()))) + .withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.south()))) + .withProperty(WEST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.west()))); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState var1) { + return 0; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean isPassable(IBlockAccess var1, BlockPos var2) { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + return world.isRemote ? true : ItemLead.attachToFence(entityplayer, world, blockpos); + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { boolean flag = this.canConnectTo(iblockaccess, blockpos.north()); boolean flag1 = this.canConnectTo(iblockaccess, blockpos.south()); @@ -150,62 +207,7 @@ public class BlockFence extends Block { this.setBlockBounds(f, 0.0F, f2, f1, 1.0F, f3); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean isPassable(IBlockAccess var1, BlockPos var2) { - return false; - } - - public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { - Block block = worldIn.getBlockState(pos).getBlock(); - return block == Blocks.barrier ? false - : ((!(block instanceof BlockFence) || block.blockMaterial != this.blockMaterial) - && !(block instanceof BlockFenceGate) - ? (block.blockMaterial.isOpaque() && block.isFullCube() - ? block.blockMaterial != Material.gourd - : false) - : true); - } - public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { return true; } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - return world.isRemote ? true : ItemLead.attachToFence(entityplayer, world, blockpos); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState var1) { - return 0; - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - return iblockstate.withProperty(NORTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.north()))) - .withProperty(EAST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.east()))) - .withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.south()))) - .withProperty(WEST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.west()))); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { NORTH, EAST, WEST, SOUTH }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFenceGate.java b/src/game/java/net/minecraft/block/BlockFenceGate.java index af619ada..1ca3f9e9 100644 --- a/src/game/java/net/minecraft/block/BlockFenceGate.java +++ b/src/game/java/net/minecraft/block/BlockFenceGate.java @@ -15,22 +15,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,10 +50,19 @@ public class BlockFenceGate extends BlockDirectional { this.setCreativeTab(CreativeTabs.tabRedstone); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return world.getBlockState(blockpos.down()).getBlock().getMaterial().isSolid() + ? super.canPlaceBlockAt(world, blockpos) + : false; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, OPEN, POWERED, IN_WALL }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { EnumFacing.Axis enumfacing$axis = ((EnumFacing) iblockstate.getValue(FACING)).getAxis(); @@ -66,12 +78,6 @@ public class BlockFenceGate extends BlockDirectional { return iblockstate; } - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return world.getBlockState(blockpos.down()).getBlock().getMaterial().isSolid() - ? super.canPlaceBlockAt(world, blockpos) - : false; - } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState iblockstate) { if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { return null; @@ -87,42 +93,45 @@ public class BlockFenceGate extends BlockDirectional { } } - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - EnumFacing.Axis enumfacing$axis = ((EnumFacing) iblockaccess.getBlockState(blockpos).getValue(FACING)) - .getAxis(); - if (enumfacing$axis == EnumFacing.Axis.Z) { - this.setBlockBounds(0.0F, 0.0F, 0.375F, 1.0F, 1.0F, 0.625F); - } else { - this.setBlockBounds(0.375F, 0.0F, 0.0F, 0.625F, 1.0F, 1.0F); + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 8; } + if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { + i |= 4; + } + + return i; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Convert the given metadata into a BlockState for this Block */ - public boolean isOpaqueCube() { - return false; + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)) + .withProperty(OPEN, Boolean.valueOf((i & 4) != 0)).withProperty(POWERED, Boolean.valueOf((i & 8) != 0)); } public boolean isFullCube() { return false; } - public boolean isPassable(IBlockAccess iblockaccess, BlockPos blockpos) { - return ((Boolean) iblockaccess.getBlockState(blockpos).getValue(OPEN)).booleanValue(); + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing()) - .withProperty(OPEN, Boolean.valueOf(false)).withProperty(POWERED, Boolean.valueOf(false)) - .withProperty(IN_WALL, Boolean.valueOf(false)); + public boolean isPassable(IBlockAccess iblockaccess, BlockPos blockpos) { + return ((Boolean) iblockaccess.getBlockState(blockpos).getValue(OPEN)).booleanValue(); } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, @@ -145,8 +154,19 @@ public class BlockFenceGate extends BlockDirectional { return true; } - /**+ - * Called when a neighboring block changes. + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing()) + .withProperty(OPEN, Boolean.valueOf(false)).withProperty(POWERED, Boolean.valueOf(false)) + .withProperty(IN_WALL, Boolean.valueOf(false)); + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { if (!world.isRemote) { @@ -169,36 +189,18 @@ public class BlockFenceGate extends BlockDirectional { } } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + EnumFacing.Axis enumfacing$axis = ((EnumFacing) iblockaccess.getBlockState(blockpos).getValue(FACING)) + .getAxis(); + if (enumfacing$axis == EnumFacing.Axis.Z) { + this.setBlockBounds(0.0F, 0.0F, 0.375F, 1.0F, 1.0F, 0.625F); + } else { + this.setBlockBounds(0.375F, 0.0F, 0.0F, 0.625F, 1.0F, 1.0F); + } + + } + public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { return true; } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)) - .withProperty(OPEN, Boolean.valueOf((i & 4) != 0)).withProperty(POWERED, Boolean.valueOf((i & 8) != 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 8; - } - - if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { - i |= 4; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, OPEN, POWERED, IN_WALL }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFire.java b/src/game/java/net/minecraft/block/BlockFire.java index b95ad8e4..3a732634 100644 --- a/src/game/java/net/minecraft/block/BlockFire.java +++ b/src/game/java/net/minecraft/block/BlockFire.java @@ -1,10 +1,10 @@ package net.minecraft.block; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Maps; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -22,22 +22,25 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.WorldProviderEnd; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -51,47 +54,6 @@ public class BlockFire extends Block { public static final PropertyBool SOUTH = PropertyBool.create("south"); public static final PropertyBool WEST = PropertyBool.create("west"); public static final PropertyInteger UPPER = PropertyInteger.create("upper", 0, 2); - private final Map encouragements = Maps.newIdentityHashMap(); - private final Map flammabilities = Maps.newIdentityHashMap(); - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - int i = blockpos.getX(); - int j = blockpos.getY(); - int k = blockpos.getZ(); - if (!World.doesBlockHaveSolidTopSurface(iblockaccess, blockpos.down()) - && !Blocks.fire.canCatchFire(iblockaccess, blockpos.down())) { - boolean flag = (i + j + k & 1) == 1; - boolean flag1 = (i / 2 + j / 2 + k / 2 & 1) == 1; - int l = 0; - if (this.canCatchFire(iblockaccess, blockpos.up())) { - l = flag ? 1 : 2; - } - - return iblockstate.withProperty(NORTH, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.north()))) - .withProperty(EAST, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.east()))) - .withProperty(SOUTH, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.south()))) - .withProperty(WEST, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.west()))) - .withProperty(UPPER, Integer.valueOf(l)).withProperty(FLIP, Boolean.valueOf(flag1)) - .withProperty(ALT, Boolean.valueOf(flag)); - } else { - return this.getDefaultState(); - } - } - - protected BlockFire() { - super(Material.fire); - this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, Integer.valueOf(0)) - .withProperty(FLIP, Boolean.valueOf(false)).withProperty(ALT, Boolean.valueOf(false)) - .withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)) - .withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)) - .withProperty(UPPER, Integer.valueOf(0))); - this.setTickRandomly(true); - } public static void init() { Blocks.fire.setFireInfo(Blocks.planks, 5, 20); @@ -131,20 +93,162 @@ public class BlockFire extends Block { Blocks.fire.setFireInfo(Blocks.carpet, 60, 20); } - public void setFireInfo(Block blockIn, int encouragement, int flammability) { - this.encouragements.put(blockIn, Integer.valueOf(encouragement)); - this.flammabilities.put(blockIn, Integer.valueOf(flammability)); + private final Map encouragements = Maps.newIdentityHashMap(); + + private final Map flammabilities = Maps.newIdentityHashMap(); + + protected BlockFire() { + super(Material.fire); + this.setDefaultState(this.blockState.getBaseState().withProperty(AGE, Integer.valueOf(0)) + .withProperty(FLIP, Boolean.valueOf(false)).withProperty(ALT, Boolean.valueOf(false)) + .withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)) + .withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)) + .withProperty(UPPER, Integer.valueOf(0))); + this.setTickRandomly(true); + } + + /** + * + Checks if the block can be caught on fire + */ + public boolean canCatchFire(IBlockAccess worldIn, BlockPos pos) { + return this.getEncouragement(worldIn.getBlockState(pos).getBlock()) > 0; + } + + protected boolean canDie(World worldIn, BlockPos pos) { + return worldIn.canLightningStrike(pos) || worldIn.canLightningStrike(pos.west()) + || worldIn.canLightningStrike(pos.east()) || worldIn.canLightningStrike(pos.north()) + || worldIn.canLightningStrike(pos.south()); + } + + private boolean canNeighborCatchFire(World worldIn, BlockPos pos) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (this.canCatchFire(worldIn, pos.offset(enumfacing))) { + return true; + } + } + + return false; + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return World.doesBlockHaveSolidTopSurface(world, blockpos.down()) || this.canNeighborCatchFire(world, blockpos); + } + + private void catchOnFire(World worldIn, BlockPos pos, int chance, EaglercraftRandom random, int age) { + int i = this.getFlammability(worldIn.getBlockState(pos).getBlock()); + if (random.nextInt(chance) < i) { + IBlockState iblockstate = worldIn.getBlockState(pos); + if (random.nextInt(age + 10) < 5 && !worldIn.canLightningStrike(pos)) { + int j = age + random.nextInt(5) / 4; + if (j > 15) { + j = 15; + } + + worldIn.setBlockState(pos, this.getDefaultState().withProperty(AGE, Integer.valueOf(j)), 3); + } else { + worldIn.setBlockToAir(pos); + } + + if (iblockstate.getBlock() == Blocks.tnt) { + Blocks.tnt.onBlockDestroyedByPlayer(worldIn, pos, + iblockstate.withProperty(BlockTNT.EXPLODE, Boolean.valueOf(true))); + } + } + + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AGE, NORTH, EAST, SOUTH, WEST, UPPER, FLIP, ALT }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + int i = blockpos.getX(); + int j = blockpos.getY(); + int k = blockpos.getZ(); + if (!World.doesBlockHaveSolidTopSurface(iblockaccess, blockpos.down()) + && !Blocks.fire.canCatchFire(iblockaccess, blockpos.down())) { + boolean flag = (i + j + k & 1) == 1; + boolean flag1 = (i / 2 + j / 2 + k / 2 & 1) == 1; + int l = 0; + if (this.canCatchFire(iblockaccess, blockpos.up())) { + l = flag ? 1 : 2; + } + + return iblockstate.withProperty(NORTH, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.north()))) + .withProperty(EAST, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.east()))) + .withProperty(SOUTH, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.south()))) + .withProperty(WEST, Boolean.valueOf(this.canCatchFire(iblockaccess, blockpos.west()))) + .withProperty(UPPER, Integer.valueOf(l)).withProperty(FLIP, Boolean.valueOf(flag1)) + .withProperty(ALT, Boolean.valueOf(flag)); + } else { + return this.getDefaultState(); + } + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; } public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { return null; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + private int getEncouragement(Block blockIn) { + Integer integer = (Integer) this.encouragements.get(blockIn); + return integer == null ? 0 : integer.intValue(); + } + + private int getFlammability(Block blockIn) { + Integer integer = (Integer) this.flammabilities.get(blockIn); + return integer == null ? 0 : integer.intValue(); + } + + /** + * + Get the MapColor for this Block and the given BlockState */ - public boolean isOpaqueCube() { + public MapColor getMapColor(IBlockState var1) { + return MapColor.tntColor; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(AGE)).intValue(); + } + + private int getNeighborEncouragement(World worldIn, BlockPos pos) { + if (!worldIn.isAirBlock(pos)) { + return 0; + } else { + int i = 0; + + EnumFacing[] facings = EnumFacing._VALUES; + for (int j = 0; j < facings.length; ++j) { + i = Math.max(this.getEncouragement(worldIn.getBlockState(pos.offset(facings[j])).getBlock()), i); + } + + return i; + } + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); + } + + /** + * + Returns if this block is collidable (only used by Fire). Args: x, y, z + */ + public boolean isCollidable() { return false; } @@ -152,15 +256,118 @@ public class BlockFire extends Block { return false; } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { + if (world.provider.getDimensionId() > 0 || !Blocks.portal.func_176548_d(world, blockpos)) { + if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down()) + && !this.canNeighborCatchFire(world, blockpos)) { + world.setBlockToAir(blockpos); + } else { + world.scheduleUpdate(blockpos, this, this.tickRate(world) + world.rand.nextInt(10)); + } + } + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down()) + && !this.canNeighborCatchFire(world, blockpos)) { + world.setBlockToAir(blockpos); + } + + } + + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 0; } - /**+ - * How many world ticks before ticking + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { + if (random.nextInt(24) == 0) { + world.playSound((double) ((float) blockpos.getX() + 0.5F), (double) ((float) blockpos.getY() + 0.5F), + (double) ((float) blockpos.getZ() + 0.5F), "fire.fire", 1.0F + random.nextFloat(), + random.nextFloat() * 0.7F + 0.3F, false); + } + + if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down()) + && !Blocks.fire.canCatchFire(world, blockpos.down())) { + if (Blocks.fire.canCatchFire(world, blockpos.west())) { + for (int j = 0; j < 2; ++j) { + double d3 = (double) blockpos.getX() + random.nextDouble() * 0.10000000149011612D; + double d8 = (double) blockpos.getY() + random.nextDouble(); + double d13 = (double) blockpos.getZ() + random.nextDouble(); + world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d3, d8, d13, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + if (Blocks.fire.canCatchFire(world, blockpos.east())) { + for (int k = 0; k < 2; ++k) { + double d4 = (double) (blockpos.getX() + 1) - random.nextDouble() * 0.10000000149011612D; + double d9 = (double) blockpos.getY() + random.nextDouble(); + double d14 = (double) blockpos.getZ() + random.nextDouble(); + world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d4, d9, d14, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + if (Blocks.fire.canCatchFire(world, blockpos.north())) { + for (int l = 0; l < 2; ++l) { + double d5 = (double) blockpos.getX() + random.nextDouble(); + double d10 = (double) blockpos.getY() + random.nextDouble(); + double d15 = (double) blockpos.getZ() + random.nextDouble() * 0.10000000149011612D; + world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d5, d10, d15, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + if (Blocks.fire.canCatchFire(world, blockpos.south())) { + for (int i1 = 0; i1 < 2; ++i1) { + double d6 = (double) blockpos.getX() + random.nextDouble(); + double d11 = (double) blockpos.getY() + random.nextDouble(); + double d16 = (double) (blockpos.getZ() + 1) - random.nextDouble() * 0.10000000149011612D; + world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d6, d11, d16, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + if (Blocks.fire.canCatchFire(world, blockpos.up())) { + for (int j1 = 0; j1 < 2; ++j1) { + double d7 = (double) blockpos.getX() + random.nextDouble(); + double d12 = (double) (blockpos.getY() + 1) - random.nextDouble() * 0.10000000149011612D; + double d17 = (double) blockpos.getZ() + random.nextDouble(); + world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d7, d12, d17, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + } else { + for (int i = 0; i < 3; ++i) { + double d0 = (double) blockpos.getX() + random.nextDouble(); + double d1 = (double) blockpos.getY() + random.nextDouble() * 0.5D + 0.5D; + double d2 = (double) blockpos.getZ() + random.nextDouble(); + world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + } + + public boolean requiresUpdates() { + return false; + } + + public void setFireInfo(Block blockIn, int encouragement, int flammability) { + this.encouragements.put(blockIn, Integer.valueOf(encouragement)); + this.flammabilities.put(blockIn, Integer.valueOf(flammability)); + } + + /** + * + How many world ticks before ticking */ public int tickRate(World var1) { return 30; @@ -252,208 +459,4 @@ public class BlockFire extends Block { } } } - - protected boolean canDie(World worldIn, BlockPos pos) { - return worldIn.canLightningStrike(pos) || worldIn.canLightningStrike(pos.west()) - || worldIn.canLightningStrike(pos.east()) || worldIn.canLightningStrike(pos.north()) - || worldIn.canLightningStrike(pos.south()); - } - - public boolean requiresUpdates() { - return false; - } - - private int getFlammability(Block blockIn) { - Integer integer = (Integer) this.flammabilities.get(blockIn); - return integer == null ? 0 : integer.intValue(); - } - - private int getEncouragement(Block blockIn) { - Integer integer = (Integer) this.encouragements.get(blockIn); - return integer == null ? 0 : integer.intValue(); - } - - private void catchOnFire(World worldIn, BlockPos pos, int chance, EaglercraftRandom random, int age) { - int i = this.getFlammability(worldIn.getBlockState(pos).getBlock()); - if (random.nextInt(chance) < i) { - IBlockState iblockstate = worldIn.getBlockState(pos); - if (random.nextInt(age + 10) < 5 && !worldIn.canLightningStrike(pos)) { - int j = age + random.nextInt(5) / 4; - if (j > 15) { - j = 15; - } - - worldIn.setBlockState(pos, this.getDefaultState().withProperty(AGE, Integer.valueOf(j)), 3); - } else { - worldIn.setBlockToAir(pos); - } - - if (iblockstate.getBlock() == Blocks.tnt) { - Blocks.tnt.onBlockDestroyedByPlayer(worldIn, pos, - iblockstate.withProperty(BlockTNT.EXPLODE, Boolean.valueOf(true))); - } - } - - } - - private boolean canNeighborCatchFire(World worldIn, BlockPos pos) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (this.canCatchFire(worldIn, pos.offset(enumfacing))) { - return true; - } - } - - return false; - } - - private int getNeighborEncouragement(World worldIn, BlockPos pos) { - if (!worldIn.isAirBlock(pos)) { - return 0; - } else { - int i = 0; - - EnumFacing[] facings = EnumFacing._VALUES; - for (int j = 0; j < facings.length; ++j) { - i = Math.max(this.getEncouragement(worldIn.getBlockState(pos.offset(facings[j])).getBlock()), i); - } - - return i; - } - } - - /**+ - * Returns if this block is collidable (only used by Fire). - * Args: x, y, z - */ - public boolean isCollidable() { - return false; - } - - /**+ - * Checks if the block can be caught on fire - */ - public boolean canCatchFire(IBlockAccess worldIn, BlockPos pos) { - return this.getEncouragement(worldIn.getBlockState(pos).getBlock()) > 0; - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return World.doesBlockHaveSolidTopSurface(world, blockpos.down()) || this.canNeighborCatchFire(world, blockpos); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down()) - && !this.canNeighborCatchFire(world, blockpos)) { - world.setBlockToAir(blockpos); - } - - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { - if (world.provider.getDimensionId() > 0 || !Blocks.portal.func_176548_d(world, blockpos)) { - if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down()) - && !this.canNeighborCatchFire(world, blockpos)) { - world.setBlockToAir(blockpos); - } else { - world.scheduleUpdate(blockpos, this, this.tickRate(world) + world.rand.nextInt(10)); - } - } - } - - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { - if (random.nextInt(24) == 0) { - world.playSound((double) ((float) blockpos.getX() + 0.5F), (double) ((float) blockpos.getY() + 0.5F), - (double) ((float) blockpos.getZ() + 0.5F), "fire.fire", 1.0F + random.nextFloat(), - random.nextFloat() * 0.7F + 0.3F, false); - } - - if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down()) - && !Blocks.fire.canCatchFire(world, blockpos.down())) { - if (Blocks.fire.canCatchFire(world, blockpos.west())) { - for (int j = 0; j < 2; ++j) { - double d3 = (double) blockpos.getX() + random.nextDouble() * 0.10000000149011612D; - double d8 = (double) blockpos.getY() + random.nextDouble(); - double d13 = (double) blockpos.getZ() + random.nextDouble(); - world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d3, d8, d13, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - if (Blocks.fire.canCatchFire(world, blockpos.east())) { - for (int k = 0; k < 2; ++k) { - double d4 = (double) (blockpos.getX() + 1) - random.nextDouble() * 0.10000000149011612D; - double d9 = (double) blockpos.getY() + random.nextDouble(); - double d14 = (double) blockpos.getZ() + random.nextDouble(); - world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d4, d9, d14, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - if (Blocks.fire.canCatchFire(world, blockpos.north())) { - for (int l = 0; l < 2; ++l) { - double d5 = (double) blockpos.getX() + random.nextDouble(); - double d10 = (double) blockpos.getY() + random.nextDouble(); - double d15 = (double) blockpos.getZ() + random.nextDouble() * 0.10000000149011612D; - world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d5, d10, d15, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - if (Blocks.fire.canCatchFire(world, blockpos.south())) { - for (int i1 = 0; i1 < 2; ++i1) { - double d6 = (double) blockpos.getX() + random.nextDouble(); - double d11 = (double) blockpos.getY() + random.nextDouble(); - double d16 = (double) (blockpos.getZ() + 1) - random.nextDouble() * 0.10000000149011612D; - world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d6, d11, d16, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - if (Blocks.fire.canCatchFire(world, blockpos.up())) { - for (int j1 = 0; j1 < 2; ++j1) { - double d7 = (double) blockpos.getX() + random.nextDouble(); - double d12 = (double) (blockpos.getY() + 1) - random.nextDouble() * 0.10000000149011612D; - double d17 = (double) blockpos.getZ() + random.nextDouble(); - world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d7, d12, d17, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - } else { - for (int i = 0; i < 3; ++i) { - double d0 = (double) blockpos.getX() + random.nextDouble(); - double d1 = (double) blockpos.getY() + random.nextDouble() * 0.5D + 0.5D; - double d2 = (double) blockpos.getZ() + random.nextDouble(); - world.spawnParticle(EnumParticleTypes.SMOKE_LARGE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState var1) { - return MapColor.tntColor; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(AGE)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AGE, NORTH, EAST, SOUTH, WEST, UPPER, FLIP, ALT }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFlower.java b/src/game/java/net/minecraft/block/BlockFlower.java index 4ec60997..f1630912 100644 --- a/src/game/java/net/minecraft/block/BlockFlower.java +++ b/src/game/java/net/minecraft/block/BlockFlower.java @@ -17,99 +17,30 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockFlower extends BlockBush { - protected PropertyEnum type; - - protected BlockFlower() { - this.setDefaultState(this.blockState.getBaseState().withProperty(this.getTypeProperty(), - this.getBlockType() == BlockFlower.EnumFlowerColor.RED ? BlockFlower.EnumFlowerType.POPPY - : BlockFlower.EnumFlowerType.DANDELION)); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockFlower.EnumFlowerType) iblockstate.getValue(this.getTypeProperty())).getMeta(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockFlower.EnumFlowerType[] flowerTypes = BlockFlower.EnumFlowerType.getTypes(this.getBlockType()); - for (int i = 0; i < flowerTypes.length; ++i) { - list.add(new ItemStack(item, 1, flowerTypes[i].getMeta())); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(this.getTypeProperty(), - BlockFlower.EnumFlowerType.getType(this.getBlockType(), i)); - } - - public abstract BlockFlower.EnumFlowerColor getBlockType(); - - public IProperty getTypeProperty() { - if (this.type == null) { - this.type = PropertyEnum.create("type", BlockFlower.EnumFlowerType.class, - new Predicate() { - public boolean apply(BlockFlower.EnumFlowerType blockflower$enumflowertype) { - return blockflower$enumflowertype.getBlockType() == BlockFlower.this.getBlockType(); - } - }); - } - - return this.type; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockFlower.EnumFlowerType) iblockstate.getValue(this.getTypeProperty())).getMeta(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { this.getTypeProperty() }); - } - - /**+ - * Get the OffsetType for this Block. Determines if the model is - * rendered slightly offset. - */ - public Block.EnumOffsetType getOffsetType() { - return Block.EnumOffsetType.XZ; - } - public static enum EnumFlowerColor { YELLOW, RED; @@ -133,58 +64,6 @@ public abstract class BlockFlower extends BlockBush { public static final BlockFlower.EnumFlowerType[] _VALUES = EnumFlowerType.values(); private static final BlockFlower.EnumFlowerType[][] TYPES_FOR_BLOCK = new BlockFlower.EnumFlowerType[_VALUES.length][]; - private final BlockFlower.EnumFlowerColor blockType; - private final int meta; - private final String name; - private final String unlocalizedName; - - private EnumFlowerType(BlockFlower.EnumFlowerColor blockType, int meta, String name) { - this(blockType, meta, name, name); - } - - private EnumFlowerType(BlockFlower.EnumFlowerColor blockType, int meta, String name, String unlocalizedName) { - this.blockType = blockType; - this.meta = meta; - this.name = name; - this.unlocalizedName = unlocalizedName; - } - - /**+ - * Get the Type of this flower (Yellow/Red) - */ - public BlockFlower.EnumFlowerColor getBlockType() { - return this.blockType; - } - - public int getMeta() { - return this.meta; - } - - public static BlockFlower.EnumFlowerType getType(BlockFlower.EnumFlowerColor blockType, int meta) { - BlockFlower.EnumFlowerType[] ablockflower$enumflowertype = TYPES_FOR_BLOCK[blockType.ordinal()]; - if (meta < 0 || meta >= ablockflower$enumflowertype.length) { - meta = 0; - } - - return ablockflower$enumflowertype[meta]; - } - - public static BlockFlower.EnumFlowerType[] getTypes(BlockFlower.EnumFlowerColor flowerColor) { - return TYPES_FOR_BLOCK[flowerColor.ordinal()]; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } - - public String getUnlocalizedName() { - return this.unlocalizedName; - } - static { BlockFlower.EnumFlowerColor[] colors = BlockFlower.EnumFlowerColor.values(); for (int i = 0; i < colors.length; ++i) { @@ -200,5 +79,131 @@ public abstract class BlockFlower extends BlockBush { } } + + public static BlockFlower.EnumFlowerType getType(BlockFlower.EnumFlowerColor blockType, int meta) { + BlockFlower.EnumFlowerType[] ablockflower$enumflowertype = TYPES_FOR_BLOCK[blockType.ordinal()]; + if (meta < 0 || meta >= ablockflower$enumflowertype.length) { + meta = 0; + } + + return ablockflower$enumflowertype[meta]; + } + + public static BlockFlower.EnumFlowerType[] getTypes(BlockFlower.EnumFlowerColor flowerColor) { + return TYPES_FOR_BLOCK[flowerColor.ordinal()]; + } + + private final BlockFlower.EnumFlowerColor blockType; + + private final int meta; + + private final String name; + + private final String unlocalizedName; + + private EnumFlowerType(BlockFlower.EnumFlowerColor blockType, int meta, String name) { + this(blockType, meta, name, name); + } + + private EnumFlowerType(BlockFlower.EnumFlowerColor blockType, int meta, String name, String unlocalizedName) { + this.blockType = blockType; + this.meta = meta; + this.name = name; + this.unlocalizedName = unlocalizedName; + } + + /** + * + Get the Type of this flower (Yellow/Red) + */ + public BlockFlower.EnumFlowerColor getBlockType() { + return this.blockType; + } + + public int getMeta() { + return this.meta; + } + + public String getName() { + return this.name; + } + + public String getUnlocalizedName() { + return this.unlocalizedName; + } + + public String toString() { + return this.name; + } + } + + protected PropertyEnum type; + + protected BlockFlower() { + this.setDefaultState(this.blockState.getBaseState().withProperty(this.getTypeProperty(), + this.getBlockType() == BlockFlower.EnumFlowerColor.RED ? BlockFlower.EnumFlowerType.POPPY + : BlockFlower.EnumFlowerType.DANDELION)); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { this.getTypeProperty() }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockFlower.EnumFlowerType) iblockstate.getValue(this.getTypeProperty())).getMeta(); + } + + public abstract BlockFlower.EnumFlowerColor getBlockType(); + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockFlower.EnumFlowerType) iblockstate.getValue(this.getTypeProperty())).getMeta(); + } + + /** + * + Get the OffsetType for this Block. Determines if the model is rendered + * slightly offset. + */ + public Block.EnumOffsetType getOffsetType() { + return Block.EnumOffsetType.XZ; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(this.getTypeProperty(), + BlockFlower.EnumFlowerType.getType(this.getBlockType(), i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockFlower.EnumFlowerType[] flowerTypes = BlockFlower.EnumFlowerType.getTypes(this.getBlockType()); + for (int i = 0; i < flowerTypes.length; ++i) { + list.add(new ItemStack(item, 1, flowerTypes[i].getMeta())); + } + + } + + public IProperty getTypeProperty() { + if (this.type == null) { + this.type = PropertyEnum.create("type", BlockFlower.EnumFlowerType.class, + new Predicate() { + public boolean apply(BlockFlower.EnumFlowerType blockflower$enumflowertype) { + return blockflower$enumflowertype.getBlockType() == BlockFlower.this.getBlockType(); + } + }); + } + + return this.type; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFlowerPot.java b/src/game/java/net/minecraft/block/BlockFlowerPot.java index d7d74668..0f06f04a 100644 --- a/src/game/java/net/minecraft/block/BlockFlowerPot.java +++ b/src/game/java/net/minecraft/block/BlockFlowerPot.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -25,30 +24,61 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockFlowerPot extends BlockContainer { + public static enum EnumFlowerType implements IStringSerializable { + EMPTY("empty"), POPPY("rose"), BLUE_ORCHID("blue_orchid"), ALLIUM("allium"), HOUSTONIA("houstonia"), + RED_TULIP("red_tulip"), ORANGE_TULIP("orange_tulip"), WHITE_TULIP("white_tulip"), PINK_TULIP("pink_tulip"), + OXEYE_DAISY("oxeye_daisy"), DANDELION("dandelion"), OAK_SAPLING("oak_sapling"), + SPRUCE_SAPLING("spruce_sapling"), BIRCH_SAPLING("birch_sapling"), JUNGLE_SAPLING("jungle_sapling"), + ACACIA_SAPLING("acacia_sapling"), DARK_OAK_SAPLING("dark_oak_sapling"), MUSHROOM_RED("mushroom_red"), + MUSHROOM_BROWN("mushroom_brown"), DEAD_BUSH("dead_bush"), FERN("fern"), CACTUS("cactus"); + + private final String name; + + private EnumFlowerType(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static final PropertyInteger LEGACY_DATA = PropertyInteger.create("legacy_data", 0, 15); + public static PropertyEnum CONTENTS; + public static void bootstrapStates() { + CONTENTS = PropertyEnum.create("contents", BlockFlowerPot.EnumFlowerType.class); + } + public BlockFlowerPot() { super(Material.circuits); this.setDefaultState(this.blockState.getBaseState().withProperty(CONTENTS, BlockFlowerPot.EnumFlowerType.EMPTY) @@ -56,45 +86,26 @@ public class BlockFlowerPot extends BlockContainer { this.setBlockBoundsForItemRender(); } - public static void bootstrapStates() { - CONTENTS = PropertyEnum.create("contents", BlockFlowerPot.EnumFlowerType.class); + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); + if (tileentityflowerpot != null && tileentityflowerpot.getFlowerPotItem() != null) { + spawnAsEntity(world, blockpos, + new ItemStack(tileentityflowerpot.getFlowerPotItem(), 1, tileentityflowerpot.getFlowerPotData())); + } + + super.breakBlock(world, blockpos, iblockstate); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal("item.flowerPot.name"); + private boolean canNotContain(Block blockIn, int meta) { + return blockIn != Blocks.yellow_flower && blockIn != Blocks.red_flower && blockIn != Blocks.cactus + && blockIn != Blocks.brown_mushroom && blockIn != Blocks.red_mushroom && blockIn != Blocks.sapling + && blockIn != Blocks.deadbush + ? blockIn == Blocks.tallgrass && meta == BlockTallGrass.EnumType.FERN.getMeta() + : true; } - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - float f = 0.375F; - float f1 = f / 2.0F; - this.setBlockBounds(0.5F - f1, 0.0F, 0.5F - f1, 0.5F + f1, f, 0.5F + f1); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - public boolean isFullCube() { - return false; + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return super.canPlaceBlockAt(world, blockpos) && World.doesBlockHaveSolidTopSurface(world, blockpos.down()); } public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int i) { @@ -109,117 +120,13 @@ public class BlockFlowerPot extends BlockContainer { return 16777215; } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - ItemStack itemstack = entityplayer.inventory.getCurrentItem(); - if (itemstack != null && itemstack.getItem() instanceof ItemBlock) { - TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); - if (tileentityflowerpot == null) { - return false; - } else if (tileentityflowerpot.getFlowerPotItem() != null) { - return false; - } else { - Block block = Block.getBlockFromItem(itemstack.getItem()); - if (!this.canNotContain(block, itemstack.getMetadata())) { - return false; - } else { - tileentityflowerpot.setFlowerPotData(itemstack.getItem(), itemstack.getMetadata()); - tileentityflowerpot.markDirty(); - world.markBlockForUpdate(blockpos); - entityplayer.triggerAchievement(StatList.field_181736_T); - if (!entityplayer.capabilities.isCreativeMode && --itemstack.stackSize <= 0) { - entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, - (ItemStack) null); - } - - return true; - } - } - } else { - return false; - } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { CONTENTS, LEGACY_DATA }); } - private boolean canNotContain(Block blockIn, int meta) { - return blockIn != Blocks.yellow_flower && blockIn != Blocks.red_flower && blockIn != Blocks.cactus - && blockIn != Blocks.brown_mushroom && blockIn != Blocks.red_mushroom && blockIn != Blocks.sapling - && blockIn != Blocks.deadbush - ? blockIn == Blocks.tallgrass && meta == BlockTallGrass.EnumType.FERN.getMeta() - : true; - } - - public Item getItem(World world, BlockPos blockpos) { - TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); - return tileentityflowerpot != null && tileentityflowerpot.getFlowerPotItem() != null - ? tileentityflowerpot.getFlowerPotItem() - : Items.flower_pot; - } - - public int getDamageValue(World world, BlockPos blockpos) { - TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); - return tileentityflowerpot != null && tileentityflowerpot.getFlowerPotItem() != null - ? tileentityflowerpot.getFlowerPotData() - : 0; - } - - /**+ - * Returns true only if block is flowerPot - */ - public boolean isFlowerPot() { - return true; - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return super.canPlaceBlockAt(world, blockpos) && World.doesBlockHaveSolidTopSurface(world, blockpos.down()); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); - if (tileentityflowerpot != null && tileentityflowerpot.getFlowerPotItem() != null) { - spawnAsEntity(world, blockpos, - new ItemStack(tileentityflowerpot.getFlowerPotItem(), 1, tileentityflowerpot.getFlowerPotData())); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { - super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); - if (entityplayer.capabilities.isCreativeMode) { - TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); - if (tileentityflowerpot != null) { - tileentityflowerpot.setFlowerPotData((Item) null, 0); - } - } - - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.flower_pot; - } - - private TileEntityFlowerPot getTileEntity(World worldIn, BlockPos pos) { - TileEntity tileentity = worldIn.getTileEntity(pos); - return tileentity instanceof TileEntityFlowerPot ? (TileEntityFlowerPot) tileentity : null; - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ public TileEntity createNewTileEntity(World var1, int i) { Object object = null; @@ -276,21 +183,9 @@ public class BlockFlowerPot extends BlockContainer { return new TileEntityFlowerPot(Item.getItemFromBlock((Block) object), j); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { CONTENTS, LEGACY_DATA }); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(LEGACY_DATA)).intValue(); - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { BlockFlowerPot.EnumFlowerType blockflowerpot$enumflowertype = BlockFlowerPot.EnumFlowerType.EMPTY; @@ -388,26 +283,132 @@ public class BlockFlowerPot extends BlockContainer { return EnumWorldBlockLayer.CUTOUT; } - public static enum EnumFlowerType implements IStringSerializable { - EMPTY("empty"), POPPY("rose"), BLUE_ORCHID("blue_orchid"), ALLIUM("allium"), HOUSTONIA("houstonia"), - RED_TULIP("red_tulip"), ORANGE_TULIP("orange_tulip"), WHITE_TULIP("white_tulip"), PINK_TULIP("pink_tulip"), - OXEYE_DAISY("oxeye_daisy"), DANDELION("dandelion"), OAK_SAPLING("oak_sapling"), - SPRUCE_SAPLING("spruce_sapling"), BIRCH_SAPLING("birch_sapling"), JUNGLE_SAPLING("jungle_sapling"), - ACACIA_SAPLING("acacia_sapling"), DARK_OAK_SAPLING("dark_oak_sapling"), MUSHROOM_RED("mushroom_red"), - MUSHROOM_BROWN("mushroom_brown"), DEAD_BUSH("dead_bush"), FERN("fern"), CACTUS("cactus"); + public int getDamageValue(World world, BlockPos blockpos) { + TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); + return tileentityflowerpot != null && tileentityflowerpot.getFlowerPotItem() != null + ? tileentityflowerpot.getFlowerPotData() + : 0; + } - private final String name; + public Item getItem(World world, BlockPos blockpos) { + TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); + return tileentityflowerpot != null && tileentityflowerpot.getFlowerPotItem() != null + ? tileentityflowerpot.getFlowerPotItem() + : Items.flower_pot; + } - private EnumFlowerType(String name) { - this.name = name; - } + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.flower_pot; + } - public String toString() { - return this.name; - } + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal("item.flowerPot.name"); + } - public String getName() { - return this.name; + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(LEGACY_DATA)).intValue(); + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + private TileEntityFlowerPot getTileEntity(World worldIn, BlockPos pos) { + TileEntity tileentity = worldIn.getTileEntity(pos); + return tileentity instanceof TileEntityFlowerPot ? (TileEntityFlowerPot) tileentity : null; + } + + /** + * + Returns true only if block is flowerPot + */ + public boolean isFlowerPot() { + return true; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + ItemStack itemstack = entityplayer.inventory.getCurrentItem(); + if (itemstack != null && itemstack.getItem() instanceof ItemBlock) { + TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); + if (tileentityflowerpot == null) { + return false; + } else if (tileentityflowerpot.getFlowerPotItem() != null) { + return false; + } else { + Block block = Block.getBlockFromItem(itemstack.getItem()); + if (!this.canNotContain(block, itemstack.getMetadata())) { + return false; + } else { + tileentityflowerpot.setFlowerPotData(itemstack.getItem(), itemstack.getMetadata()); + tileentityflowerpot.markDirty(); + world.markBlockForUpdate(blockpos); + entityplayer.triggerAchievement(StatList.field_181736_T); + if (!entityplayer.capabilities.isCreativeMode && --itemstack.stackSize <= 0) { + entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, + (ItemStack) null); + } + + return true; + } + } + } else { + return false; } } + + public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { + super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); + if (entityplayer.capabilities.isCreativeMode) { + TileEntityFlowerPot tileentityflowerpot = this.getTileEntity(world, blockpos); + if (tileentityflowerpot != null) { + tileentityflowerpot.setFlowerPotData((Item) null, 0); + } + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + float f = 0.375F; + float f1 = f / 2.0F; + this.setBlockBounds(0.5F - f1, 0.0F, 0.5F - f1, 0.5F + f1, f, 0.5F + f1); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockFurnace.java b/src/game/java/net/minecraft/block/BlockFurnace.java index 74a216fd..c7d012fc 100644 --- a/src/game/java/net/minecraft/block/BlockFurnace.java +++ b/src/game/java/net/minecraft/block/BlockFurnace.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -22,67 +21,186 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockFurnace extends BlockContainer { public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); - private final boolean isBurning; private static boolean keepInventory; + public static void setState(boolean active, World worldIn, BlockPos pos) { + IBlockState iblockstate = worldIn.getBlockState(pos); + TileEntity tileentity = worldIn.getTileEntity(pos); + keepInventory = true; + if (active) { + worldIn.setBlockState(pos, + Blocks.lit_furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); + worldIn.setBlockState(pos, + Blocks.lit_furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); + } else { + worldIn.setBlockState(pos, + Blocks.furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); + worldIn.setBlockState(pos, + Blocks.furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); + } + + keepInventory = false; + if (tileentity != null) { + tileentity.validate(); + worldIn.setTileEntity(pos, tileentity); + } + + } + + private final boolean isBurning; + protected BlockFurnace(boolean isBurning) { super(Material.rock); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH)); this.isBurning = isBurning; } - /**+ - * Get the Item that this Block should drop when harvested. + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + if (!keepInventory) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityFurnace) { + InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityFurnace) tileentity); + world.updateComparatorOutputLevel(blockpos, this); + } + } + + super.breakBlock(world, blockpos, iblockstate); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityFurnace(); + } + + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return Container.calcRedstone(world.getTileEntity(blockpos)); + } + + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(Blocks.furnace); + } + + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Item.getItemFromBlock(Blocks.furnace); } + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Possibly modify the given BlockState before rendering it on an Entity + * (Minecarts, Endermen, ...) + */ + public IBlockState getStateForEntityRender(IBlockState var1) { + return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getFront(i); + if (enumfacing.getAxis() == EnumFacing.Axis.Y) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing); + } + + public boolean hasComparatorInputOverride() { + return true; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (world.isRemote) { + return true; + } else { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityFurnace) { + entityplayer.displayGUIChest((TileEntityFurnace) tileentity); + entityplayer.triggerAchievement(StatList.field_181741_Y); + } + + return true; + } + } + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { this.setDefaultFacing(world, blockpos, iblockstate); } - private void setDefaultFacing(World worldIn, BlockPos pos, IBlockState state) { - if (!worldIn.isRemote) { - Block block = worldIn.getBlockState(pos.north()).getBlock(); - Block block1 = worldIn.getBlockState(pos.south()).getBlock(); - Block block2 = worldIn.getBlockState(pos.west()).getBlock(); - Block block3 = worldIn.getBlockState(pos.east()).getBlock(); - EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); - if (enumfacing == EnumFacing.NORTH && block.isFullBlock() && !block1.isFullBlock()) { - enumfacing = EnumFacing.SOUTH; - } else if (enumfacing == EnumFacing.SOUTH && block1.isFullBlock() && !block.isFullBlock()) { - enumfacing = EnumFacing.NORTH; - } else if (enumfacing == EnumFacing.WEST && block2.isFullBlock() && !block3.isFullBlock()) { - enumfacing = EnumFacing.EAST; - } else if (enumfacing == EnumFacing.EAST && block3.isFullBlock() && !block2.isFullBlock()) { - enumfacing = EnumFacing.WEST; - } + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); + } - worldIn.setBlockState(pos, state.withProperty(FACING, enumfacing), 2); + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack itemstack) { + world.setBlockState(blockpos, + iblockstate.withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()), 2); + if (itemstack.hasDisplayName()) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityFurnace) { + ((TileEntityFurnace) tileentity).setCustomInventoryName(itemstack.getDisplayName()); + } } + } public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -114,139 +232,24 @@ public class BlockFurnace extends BlockContainer { } } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (world.isRemote) { - return true; - } else { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityFurnace) { - entityplayer.displayGUIChest((TileEntityFurnace) tileentity); - entityplayer.triggerAchievement(StatList.field_181741_Y); + private void setDefaultFacing(World worldIn, BlockPos pos, IBlockState state) { + if (!worldIn.isRemote) { + Block block = worldIn.getBlockState(pos.north()).getBlock(); + Block block1 = worldIn.getBlockState(pos.south()).getBlock(); + Block block2 = worldIn.getBlockState(pos.west()).getBlock(); + Block block3 = worldIn.getBlockState(pos.east()).getBlock(); + EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); + if (enumfacing == EnumFacing.NORTH && block.isFullBlock() && !block1.isFullBlock()) { + enumfacing = EnumFacing.SOUTH; + } else if (enumfacing == EnumFacing.SOUTH && block1.isFullBlock() && !block.isFullBlock()) { + enumfacing = EnumFacing.NORTH; + } else if (enumfacing == EnumFacing.WEST && block2.isFullBlock() && !block3.isFullBlock()) { + enumfacing = EnumFacing.EAST; + } else if (enumfacing == EnumFacing.EAST && block3.isFullBlock() && !block2.isFullBlock()) { + enumfacing = EnumFacing.WEST; } - return true; + worldIn.setBlockState(pos, state.withProperty(FACING, enumfacing), 2); } } - - public static void setState(boolean active, World worldIn, BlockPos pos) { - IBlockState iblockstate = worldIn.getBlockState(pos); - TileEntity tileentity = worldIn.getTileEntity(pos); - keepInventory = true; - if (active) { - worldIn.setBlockState(pos, - Blocks.lit_furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); - worldIn.setBlockState(pos, - Blocks.lit_furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); - } else { - worldIn.setBlockState(pos, - Blocks.furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); - worldIn.setBlockState(pos, - Blocks.furnace.getDefaultState().withProperty(FACING, iblockstate.getValue(FACING)), 3); - } - - keepInventory = false; - if (tileentity != null) { - tileentity.validate(); - worldIn.setTileEntity(pos, tileentity); - } - - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityFurnace(); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack itemstack) { - world.setBlockState(blockpos, - iblockstate.withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()), 2); - if (itemstack.hasDisplayName()) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityFurnace) { - ((TileEntityFurnace) tileentity).setCustomInventoryName(itemstack.getDisplayName()); - } - } - - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - if (!keepInventory) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityFurnace) { - InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityFurnace) tileentity); - world.updateComparatorOutputLevel(blockpos, this); - } - } - - super.breakBlock(world, blockpos, iblockstate); - } - - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return Container.calcRedstone(world.getTileEntity(blockpos)); - } - - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(Blocks.furnace); - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Possibly modify the given BlockState before rendering it on - * an Entity (Minecarts, Endermen, ...) - */ - public IBlockState getStateForEntityRender(IBlockState var1) { - return this.getDefaultState().withProperty(FACING, EnumFacing.SOUTH); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getFront(i); - if (enumfacing.getAxis() == EnumFacing.Axis.Y) { - enumfacing = EnumFacing.NORTH; - } - - return this.getDefaultState().withProperty(FACING, enumfacing); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockGlass.java b/src/game/java/net/minecraft/block/BlockGlass.java index 1051a2dc..1d23a0c0 100644 --- a/src/game/java/net/minecraft/block/BlockGlass.java +++ b/src/game/java/net/minecraft/block/BlockGlass.java @@ -6,22 +6,25 @@ import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,11 +35,12 @@ public class BlockGlass extends BlockBreakable { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; + protected boolean canSilkHarvest() { + return true; + } + + public boolean eaglerShadersShouldRenderGlassHighlights() { + return DeferredStateManager.isRenderingGlassHighlights(); } public EnumWorldBlockLayer getBlockLayer() { @@ -47,11 +51,10 @@ public class BlockGlass extends BlockBreakable { return false; } - protected boolean canSilkHarvest() { - return true; - } - - public boolean eaglerShadersShouldRenderGlassHighlights() { - return DeferredStateManager.isRenderingGlassHighlights(); + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockGlowstone.java b/src/game/java/net/minecraft/block/BlockGlowstone.java index 61d7b1e4..ac0f87d1 100644 --- a/src/game/java/net/minecraft/block/BlockGlowstone.java +++ b/src/game/java/net/minecraft/block/BlockGlowstone.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -10,22 +9,25 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,31 +38,31 @@ public class BlockGlowstone extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { - return MathHelper.clamp_int(this.quantityDropped(random) + random.nextInt(i + 1), 1, 4); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom random) { - return 2 + random.nextInt(3); - } - - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Items.glowstone_dust; } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.sandColor; } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom random) { + return 2 + random.nextInt(3); + } + + /** + * + Get the quantity dropped based on the given fortune level + */ + public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { + return MathHelper.clamp_int(this.quantityDropped(random) + random.nextInt(i + 1), 1, 4); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockGrass.java b/src/game/java/net/minecraft/block/BlockGrass.java index e78c9166..d40129d6 100644 --- a/src/game/java/net/minecraft/block/BlockGrass.java +++ b/src/game/java/net/minecraft/block/BlockGrass.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -17,22 +16,25 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeColorHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,10 +49,28 @@ public class BlockGrass extends Block implements IGrowable { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4) { + return true; + } + + public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return true; + } + + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return BiomeColorHelper.getGrassColorAtPos(iblockaccess, blockpos); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { SNOWY }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { Block block = iblockaccess.getBlockState(blockpos.up()).getBlock(); @@ -61,54 +81,27 @@ public class BlockGrass extends Block implements IGrowable { return ColorizerGrass.getGrassColor(0.5D, 1.0D); } - public int getRenderColor(IBlockState var1) { - return this.getBlockColor(); + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT_MIPPED; } - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return BiomeColorHelper.getGrassColorAtPos(iblockaccess, blockpos); - } - - public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { - if (!world.isRemote) { - if (world.getLightFromNeighbors(blockpos.up()) < 4 - && world.getBlockState(blockpos.up()).getBlock().getLightOpacity() > 2) { - world.setBlockState(blockpos, Blocks.dirt.getDefaultState()); - } else { - if (world.getLightFromNeighbors(blockpos.up()) >= 9) { - for (int i = 0; i < 4; ++i) { - BlockPos blockpos1 = blockpos.add(random.nextInt(3) - 1, random.nextInt(5) - 3, - random.nextInt(3) - 1); - Block block = world.getBlockState(blockpos1.up()).getBlock(); - IBlockState iblockstate = world.getBlockState(blockpos1); - if (iblockstate.getBlock() == Blocks.dirt - && iblockstate.getValue(BlockDirt.VARIANT) == BlockDirt.DirtType.DIRT - && world.getLightFromNeighbors(blockpos1.up()) >= 4 && block.getLightOpacity() <= 2) { - world.setBlockState(blockpos1, Blocks.grass.getDefaultState()); - } - } - } - } - } - } - - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int i) { return Blocks.dirt.getItemDropped( Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), random, i); } - /**+ - * Whether this IGrowable can grow + /** + * + Convert the BlockState into the correct metadata value */ - public boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4) { - return true; + public int getMetaFromState(IBlockState var1) { + return 0; } - public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { - return true; + public int getRenderColor(IBlockState var1) { + return this.getBlockColor(); } public void grow(World world, EaglercraftRandom random, BlockPos blockpos, IBlockState var4) { @@ -154,18 +147,26 @@ public class BlockGrass extends Block implements IGrowable { } - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT_MIPPED; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState var1) { - return 0; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { SNOWY }); + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { + if (!world.isRemote) { + if (world.getLightFromNeighbors(blockpos.up()) < 4 + && world.getBlockState(blockpos.up()).getBlock().getLightOpacity() > 2) { + world.setBlockState(blockpos, Blocks.dirt.getDefaultState()); + } else { + if (world.getLightFromNeighbors(blockpos.up()) >= 9) { + for (int i = 0; i < 4; ++i) { + BlockPos blockpos1 = blockpos.add(random.nextInt(3) - 1, random.nextInt(5) - 3, + random.nextInt(3) - 1); + Block block = world.getBlockState(blockpos1.up()).getBlock(); + IBlockState iblockstate = world.getBlockState(blockpos1); + if (iblockstate.getBlock() == Blocks.dirt + && iblockstate.getValue(BlockDirt.VARIANT) == BlockDirt.DirtType.DIRT + && world.getLightFromNeighbors(blockpos1.up()) >= 4 && block.getLightOpacity() <= 2) { + world.setBlockState(blockpos1, Blocks.grass.getDefaultState()); + } + } + } + } + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockGravel.java b/src/game/java/net/minecraft/block/BlockGravel.java index 8cf5c076..17622f44 100644 --- a/src/game/java/net/minecraft/block/BlockGravel.java +++ b/src/game/java/net/minecraft/block/BlockGravel.java @@ -1,35 +1,37 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Items; import net.minecraft.item.Item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockGravel extends BlockFalling { - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int i) { if (i > 3) { @@ -39,8 +41,8 @@ public class BlockGravel extends BlockFalling { return random.nextInt(10 - i * 3) == 0 ? Items.flint : Item.getItemFromBlock(this); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.stoneColor; diff --git a/src/game/java/net/minecraft/block/BlockHalfStoneSlab.java b/src/game/java/net/minecraft/block/BlockHalfStoneSlab.java index c91efa7d..66de59c2 100644 --- a/src/game/java/net/minecraft/block/BlockHalfStoneSlab.java +++ b/src/game/java/net/minecraft/block/BlockHalfStoneSlab.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockHalfStoneSlabNew.java b/src/game/java/net/minecraft/block/BlockHalfStoneSlabNew.java index f371f10d..390b43fd 100644 --- a/src/game/java/net/minecraft/block/BlockHalfStoneSlabNew.java +++ b/src/game/java/net/minecraft/block/BlockHalfStoneSlabNew.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockHalfWoodSlab.java b/src/game/java/net/minecraft/block/BlockHalfWoodSlab.java index f9984a15..8e88cdaa 100644 --- a/src/game/java/net/minecraft/block/BlockHalfWoodSlab.java +++ b/src/game/java/net/minecraft/block/BlockHalfWoodSlab.java @@ -1,21 +1,24 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockHardenedClay.java b/src/game/java/net/minecraft/block/BlockHardenedClay.java index f7223754..fcf893aa 100644 --- a/src/game/java/net/minecraft/block/BlockHardenedClay.java +++ b/src/game/java/net/minecraft/block/BlockHardenedClay.java @@ -5,22 +5,25 @@ import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +34,8 @@ public class BlockHardenedClay extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.adobeColor; diff --git a/src/game/java/net/minecraft/block/BlockHay.java b/src/game/java/net/minecraft/block/BlockHay.java index a62365dd..0feb3090 100644 --- a/src/game/java/net/minecraft/block/BlockHay.java +++ b/src/game/java/net/minecraft/block/BlockHay.java @@ -13,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,23 +43,16 @@ public class BlockHay extends BlockRotatedPillar { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing.Axis enumfacing$axis = EnumFacing.Axis.Y; - int j = i & 12; - if (j == 4) { - enumfacing$axis = EnumFacing.Axis.X; - } else if (j == 8) { - enumfacing$axis = EnumFacing.Axis.Z; - } - - return this.getDefaultState().withProperty(AXIS, enumfacing$axis); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AXIS }); } - /**+ - * Convert the BlockState into the correct metadata value + protected ItemStack createStackedBlock(IBlockState var1) { + return new ItemStack(Item.getItemFromBlock(this), 1, 0); + } + + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -70,17 +66,24 @@ public class BlockHay extends BlockRotatedPillar { return i; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AXIS }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing.Axis enumfacing$axis = EnumFacing.Axis.Y; + int j = i & 12; + if (j == 4) { + enumfacing$axis = EnumFacing.Axis.X; + } else if (j == 8) { + enumfacing$axis = EnumFacing.Axis.Z; + } + + return this.getDefaultState().withProperty(AXIS, enumfacing$axis); } - protected ItemStack createStackedBlock(IBlockState var1) { - return new ItemStack(Item.getItemFromBlock(this), 1, 0); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2, int i, EntityLivingBase entitylivingbase) { diff --git a/src/game/java/net/minecraft/block/BlockHopper.java b/src/game/java/net/minecraft/block/BlockHopper.java index 0030299b..176d2007 100644 --- a/src/game/java/net/minecraft/block/BlockHopper.java +++ b/src/game/java/net/minecraft/block/BlockHopper.java @@ -28,22 +28,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,6 +59,19 @@ public class BlockHopper extends BlockContainer { }); public static final PropertyBool ENABLED = PropertyBool.create("enabled"); + public static EnumFacing getFacing(int meta) { + return EnumFacing.getFront(meta & 7); + } + + /** + * + Get's the hopper's active status from the 8-bit of the metadata. Note that + * the metadata stores whether the block is powered, so this returns true when + * that bit is 0. + */ + public static boolean isEnabled(int meta) { + return (meta & 8) != 8; + } + public BlockHopper() { super(Material.iron, MapColor.stoneColor); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.DOWN).withProperty(ENABLED, @@ -64,13 +80,9 @@ public class BlockHopper extends BlockContainer { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -88,46 +100,79 @@ public class BlockHopper extends BlockContainer { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase var8) { - EnumFacing enumfacing1 = enumfacing.getOpposite(); - if (enumfacing1 == EnumFacing.UP) { - enumfacing1 = EnumFacing.DOWN; + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityHopper) { + InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityHopper) tileentity); + world.updateComparatorOutputLevel(blockpos, this); } - return this.getDefaultState().withProperty(FACING, enumfacing1).withProperty(ENABLED, Boolean.valueOf(true)); + super.breakBlock(world, blockpos, iblockstate); } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, ENABLED }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ public TileEntity createNewTileEntity(World var1, int var2) { return new TileEntityHopper(); } - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack itemstack) { - super.onBlockPlacedBy(world, blockpos, iblockstate, entitylivingbase, itemstack); - if (itemstack.hasDisplayName()) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityHopper) { - ((TileEntityHopper) tileentity).setCustomName(itemstack.getDisplayName()); - } - } - + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT_MIPPED; } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - this.updateState(world, blockpos, iblockstate); + public int getComparatorInputOverride(World world, BlockPos blockpos) { + return Container.calcRedstone(world.getTileEntity(blockpos)); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + if (!((Boolean) iblockstate.getValue(ENABLED)).booleanValue()) { + i |= 8; + } + + return i; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(ENABLED, + Boolean.valueOf(isEnabled(i))); + } + + public boolean hasComparatorInputOverride() { + return true; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, @@ -145,13 +190,55 @@ public class BlockHopper extends BlockContainer { } } - /**+ - * Called when a neighboring block changes. + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + this.updateState(world, blockpos, iblockstate); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase var8) { + EnumFacing enumfacing1 = enumfacing.getOpposite(); + if (enumfacing1 == EnumFacing.UP) { + enumfacing1 = EnumFacing.DOWN; + } + + return this.getDefaultState().withProperty(FACING, enumfacing1).withProperty(ENABLED, Boolean.valueOf(true)); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack itemstack) { + super.onBlockPlacedBy(world, blockpos, iblockstate, entitylivingbase, itemstack); + if (itemstack.hasDisplayName()) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityHopper) { + ((TileEntityHopper) tileentity).setCustomName(itemstack.getDisplayName()); + } + } + + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { this.updateState(world, blockpos, iblockstate); } + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { + return true; + } + private void updateState(World worldIn, BlockPos pos, IBlockState state) { boolean flag = !worldIn.isBlockPowered(pos); if (flag != ((Boolean) state.getValue(ENABLED)).booleanValue()) { @@ -159,88 +246,4 @@ public class BlockHopper extends BlockContainer { } } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityHopper) { - InventoryHelper.dropInventoryItems(world, blockpos, (TileEntityHopper) tileentity); - world.updateComparatorOutputLevel(blockpos, this); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { - return true; - } - - public static EnumFacing getFacing(int meta) { - return EnumFacing.getFront(meta & 7); - } - - /**+ - * Get's the hopper's active status from the 8-bit of the - * metadata. Note that the metadata stores whether the block is - * powered, so this returns true when that bit is 0. - */ - public static boolean isEnabled(int meta) { - return (meta & 8) != 8; - } - - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - return Container.calcRedstone(world.getTileEntity(blockpos)); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT_MIPPED; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(ENABLED, - Boolean.valueOf(isEnabled(i))); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - if (!((Boolean) iblockstate.getValue(ENABLED)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, ENABLED }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockHugeMushroom.java b/src/game/java/net/minecraft/block/BlockHugeMushroom.java index 5c26d553..18ce2166 100644 --- a/src/game/java/net/minecraft/block/BlockHugeMushroom.java +++ b/src/game/java/net/minecraft/block/BlockHugeMushroom.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -15,28 +14,82 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockHugeMushroom extends Block { + public static enum EnumType implements IStringSerializable { + NORTH_WEST(1, "north_west"), NORTH(2, "north"), NORTH_EAST(3, "north_east"), WEST(4, "west"), + CENTER(5, "center"), EAST(6, "east"), SOUTH_WEST(7, "south_west"), SOUTH(8, "south"), + SOUTH_EAST(9, "south_east"), STEM(10, "stem"), ALL_INSIDE(0, "all_inside"), ALL_OUTSIDE(14, "all_outside"), + ALL_STEM(15, "all_stem"); + + private static final BlockHugeMushroom.EnumType[] META_LOOKUP = new BlockHugeMushroom.EnumType[16]; + static { + BlockHugeMushroom.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockHugeMushroom.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + BlockHugeMushroom.EnumType blockhugemushroom$enumtype = META_LOOKUP[meta]; + return blockhugemushroom$enumtype == null ? META_LOOKUP[0] : blockhugemushroom$enumtype; + } + + private final int meta; + + private final String name; + + private EnumType(int meta, String name) { + this.meta = meta; + this.name = name; + } + + public int getMetadata() { + return this.meta; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static PropertyEnum VARIANT; + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockHugeMushroom.EnumType.class); + } + private final Block smallBlock; public BlockHugeMushroom(Material parMaterial, MapColor parMapColor, Block parBlock) { @@ -46,19 +99,23 @@ public class BlockHugeMushroom extends Block { this.smallBlock = parBlock; } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockHugeMushroom.EnumType.class); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); } - /**+ - * Returns the quantity of items to drop on block destruction. + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(this.smallBlock); + } + + /** + * + Get the Item that this Block should drop when harvested. */ - public int quantityDropped(EaglercraftRandom random) { - return Math.max(0, random.nextInt(10) - 7); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(this.smallBlock); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState iblockstate) { switch ((BlockHugeMushroom.EnumType) iblockstate.getValue(VARIANT)) { @@ -73,86 +130,33 @@ public class BlockHugeMushroom extends Block { } } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Convert the BlockState into the correct metadata value */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(this.smallBlock); + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockHugeMushroom.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); } - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(this.smallBlock); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockHugeMushroom.EnumType.byMetadata(i)); } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, int var7, EntityLivingBase var8) { return this.getDefaultState(); } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Returns the quantity of items to drop on block destruction. */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockHugeMushroom.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockHugeMushroom.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - - public static enum EnumType implements IStringSerializable { - NORTH_WEST(1, "north_west"), NORTH(2, "north"), NORTH_EAST(3, "north_east"), WEST(4, "west"), - CENTER(5, "center"), EAST(6, "east"), SOUTH_WEST(7, "south_west"), SOUTH(8, "south"), - SOUTH_EAST(9, "south_east"), STEM(10, "stem"), ALL_INSIDE(0, "all_inside"), ALL_OUTSIDE(14, "all_outside"), - ALL_STEM(15, "all_stem"); - - private static final BlockHugeMushroom.EnumType[] META_LOOKUP = new BlockHugeMushroom.EnumType[16]; - private final int meta; - private final String name; - - private EnumType(int meta, String name) { - this.meta = meta; - this.name = name; - } - - public int getMetadata() { - return this.meta; - } - - public String toString() { - return this.name; - } - - public static BlockHugeMushroom.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - BlockHugeMushroom.EnumType blockhugemushroom$enumtype = META_LOOKUP[meta]; - return blockhugemushroom$enumtype == null ? META_LOOKUP[0] : blockhugemushroom$enumtype; - } - - public String getName() { - return this.name; - } - - static { - BlockHugeMushroom.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - - } + public int quantityDropped(EaglercraftRandom random) { + return Math.max(0, random.nextInt(10) - 7); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockIce.java b/src/game/java/net/minecraft/block/BlockIce.java index 1c467adc..0a968f8a 100644 --- a/src/game/java/net/minecraft/block/BlockIce.java +++ b/src/game/java/net/minecraft/block/BlockIce.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; @@ -16,22 +15,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,6 +50,10 @@ public class BlockIce extends BlockBreakable { return EnumWorldBlockLayer.TRANSLUCENT; } + public int getMobilityFlag() { + return 0; + } + public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, TileEntity var5) { entityplayer.triggerAchievement(StatList.mineBlockStatArray[Block.getIdFromBlock(this)]); @@ -73,8 +79,8 @@ public class BlockIce extends BlockBreakable { } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 0; @@ -90,8 +96,4 @@ public class BlockIce extends BlockBreakable { } } } - - public int getMobilityFlag() { - return 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockJukebox.java b/src/game/java/net/minecraft/block/BlockJukebox.java index a393d012..e3d146f2 100644 --- a/src/game/java/net/minecraft/block/BlockJukebox.java +++ b/src/game/java/net/minecraft/block/BlockJukebox.java @@ -18,27 +18,61 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockJukebox extends BlockContainer { + public static class TileEntityJukebox extends TileEntity { + private ItemStack record; + + public ItemStack getRecord() { + return this.record; + } + + public void readFromNBT(NBTTagCompound compound) { + super.readFromNBT(compound); + if (compound.hasKey("RecordItem", 10)) { + this.setRecord(ItemStack.loadItemStackFromNBT(compound.getCompoundTag("RecordItem"))); + } else if (compound.getInteger("Record") > 0) { + this.setRecord(new ItemStack(Item.getItemById(compound.getInteger("Record")), 1, 0)); + } + + } + + public void setRecord(ItemStack recordStack) { + this.record = recordStack; + this.markDirty(); + } + + public void writeToNBT(NBTTagCompound compound) { + super.writeToNBT(compound); + if (this.getRecord() != null) { + compound.setTag("RecordItem", this.getRecord().writeToNBT(new NBTTagCompound())); + } + + } + } + public static final PropertyBool HAS_RECORD = PropertyBool.create("has_record"); protected BlockJukebox() { @@ -47,26 +81,29 @@ public class BlockJukebox extends BlockContainer { this.setCreativeTab(CreativeTabs.tabDecorations); } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, - EnumFacing var5, float var6, float var7, float var8) { - if (((Boolean) iblockstate.getValue(HAS_RECORD)).booleanValue()) { - this.dropRecord(world, blockpos, iblockstate); - iblockstate = iblockstate.withProperty(HAS_RECORD, Boolean.valueOf(false)); - world.setBlockState(blockpos, iblockstate, 2); - return true; - } else { - return false; - } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + this.dropRecord(world, blockpos, iblockstate); + super.breakBlock(world, blockpos, iblockstate); } - public void insertRecord(World worldIn, BlockPos pos, IBlockState state, ItemStack recordStack) { - if (!worldIn.isRemote) { - TileEntity tileentity = worldIn.getTileEntity(pos); - if (tileentity instanceof BlockJukebox.TileEntityJukebox) { - ((BlockJukebox.TileEntityJukebox) tileentity) - .setRecord(new ItemStack(recordStack.getItem(), 1, recordStack.getMetadata())); - worldIn.setBlockState(pos, state.withProperty(HAS_RECORD, Boolean.valueOf(true)), 2); - } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { HAS_RECORD }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new BlockJukebox.TileEntityJukebox(); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int var5) { + if (!world.isRemote) { + super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, 0); } } @@ -94,32 +131,6 @@ public class BlockJukebox extends BlockContainer { } } - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - this.dropRecord(world, blockpos, iblockstate); - super.breakBlock(world, blockpos, iblockstate); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int var5) { - if (!world.isRemote) { - super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, 0); - } - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new BlockJukebox.TileEntityJukebox(); - } - - public boolean hasComparatorInputOverride() { - return true; - } - public int getComparatorInputOverride(World world, BlockPos blockpos) { TileEntity tileentity = world.getTileEntity(blockpos); if (tileentity instanceof BlockJukebox.TileEntityJukebox) { @@ -132,60 +143,52 @@ public class BlockJukebox extends BlockContainer { return 0; } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(HAS_RECORD, Boolean.valueOf(i > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { return ((Boolean) iblockstate.getValue(HAS_RECORD)).booleanValue() ? 1 : 0; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { HAS_RECORD }); + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; } - public static class TileEntityJukebox extends TileEntity { - private ItemStack record; + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(HAS_RECORD, Boolean.valueOf(i > 0)); + } - public void readFromNBT(NBTTagCompound compound) { - super.readFromNBT(compound); - if (compound.hasKey("RecordItem", 10)) { - this.setRecord(ItemStack.loadItemStackFromNBT(compound.getCompoundTag("RecordItem"))); - } else if (compound.getInteger("Record") > 0) { - this.setRecord(new ItemStack(Item.getItemById(compound.getInteger("Record")), 1, 0)); + public boolean hasComparatorInputOverride() { + return true; + } + + public void insertRecord(World worldIn, BlockPos pos, IBlockState state, ItemStack recordStack) { + if (!worldIn.isRemote) { + TileEntity tileentity = worldIn.getTileEntity(pos); + if (tileentity instanceof BlockJukebox.TileEntityJukebox) { + ((BlockJukebox.TileEntityJukebox) tileentity) + .setRecord(new ItemStack(recordStack.getItem(), 1, recordStack.getMetadata())); + worldIn.setBlockState(pos, state.withProperty(HAS_RECORD, Boolean.valueOf(true)), 2); } - } + } - public void writeToNBT(NBTTagCompound compound) { - super.writeToNBT(compound); - if (this.getRecord() != null) { - compound.setTag("RecordItem", this.getRecord().writeToNBT(new NBTTagCompound())); - } - - } - - public ItemStack getRecord() { - return this.record; - } - - public void setRecord(ItemStack recordStack) { - this.record = recordStack; - this.markDirty(); + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, + EnumFacing var5, float var6, float var7, float var8) { + if (((Boolean) iblockstate.getValue(HAS_RECORD)).booleanValue()) { + this.dropRecord(world, blockpos, iblockstate); + iblockstate = iblockstate.withProperty(HAS_RECORD, Boolean.valueOf(false)); + world.setBlockState(blockpos, iblockstate, 2); + return true; + } else { + return false; } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockLadder.java b/src/game/java/net/minecraft/block/BlockLadder.java index 3e68f78e..2af6d40b 100644 --- a/src/game/java/net/minecraft/block/BlockLadder.java +++ b/src/game/java/net/minecraft/block/BlockLadder.java @@ -14,22 +14,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,16 +46,100 @@ public class BlockLadder extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } + protected boolean canBlockStay(World worldIn, BlockPos pos, EnumFacing facing) { + return worldIn.getBlockState(pos.offset(facing.getOpposite())).getBlock().isNormalCube(); + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return world.getBlockState(blockpos.west()).getBlock().isNormalCube() ? true + : (world.getBlockState(blockpos.east()).getBlock().isNormalCube() ? true + : (world.getBlockState(blockpos.north()).getBlock().isNormalCube() ? true + : world.getBlockState(blockpos.south()).getBlock().isNormalCube())); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { this.setBlockBoundsBasedOnState(world, blockpos); return super.getCollisionBoundingBox(world, blockpos, iblockstate); } + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + } + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { this.setBlockBoundsBasedOnState(world, blockpos); return super.getSelectedBoundingBox(world, blockpos); } + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getFront(i); + if (enumfacing.getAxis() == EnumFacing.Axis.Y) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase var8) { + if (enumfacing.getAxis().isHorizontal() && this.canBlockStay(world, blockpos, enumfacing)) { + return this.getDefaultState().withProperty(FACING, enumfacing); + } else { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing1 = facings[i]; + if (this.canBlockStay(world, blockpos, enumfacing1)) { + return this.getDefaultState().withProperty(FACING, enumfacing1); + } + } + + return this.getDefaultState(); + } + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (!this.canBlockStay(world, blockpos, enumfacing)) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + super.onNeighborBlockChange(world, blockpos, iblockstate, block); + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { IBlockState iblockstate = iblockaccess.getBlockState(blockpos); if (iblockstate.getBlock() == this) { @@ -74,88 +161,4 @@ public class BlockLadder extends Block { } } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return world.getBlockState(blockpos.west()).getBlock().isNormalCube() ? true - : (world.getBlockState(blockpos.east()).getBlock().isNormalCube() ? true - : (world.getBlockState(blockpos.north()).getBlock().isNormalCube() ? true - : world.getBlockState(blockpos.south()).getBlock().isNormalCube())); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase var8) { - if (enumfacing.getAxis().isHorizontal() && this.canBlockStay(world, blockpos, enumfacing)) { - return this.getDefaultState().withProperty(FACING, enumfacing); - } else { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing1 = facings[i]; - if (this.canBlockStay(world, blockpos, enumfacing1)) { - return this.getDefaultState().withProperty(FACING, enumfacing1); - } - } - - return this.getDefaultState(); - } - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (!this.canBlockStay(world, blockpos, enumfacing)) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - super.onNeighborBlockChange(world, blockpos, iblockstate, block); - } - - protected boolean canBlockStay(World worldIn, BlockPos pos, EnumFacing facing) { - return worldIn.getBlockState(pos.offset(facing.getOpposite())).getBlock().isNormalCube(); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getFront(i); - if (enumfacing.getAxis() == EnumFacing.Axis.Y) { - enumfacing = EnumFacing.NORTH; - } - - return this.getDefaultState().withProperty(FACING, enumfacing); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockLeaves.java b/src/game/java/net/minecraft/block/BlockLeaves.java index deb30880..eec1c71c 100644 --- a/src/game/java/net/minecraft/block/BlockLeaves.java +++ b/src/game/java/net/minecraft/block/BlockLeaves.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; @@ -17,22 +16,25 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeColorHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,18 +55,6 @@ public abstract class BlockLeaves extends BlockLeavesBase { this.setStepSound(soundTypeGrass); } - public int getBlockColor() { - return ColorizerFoliage.getFoliageColor(0.5D, 1.0D); - } - - public int getRenderColor(IBlockState var1) { - return ColorizerFoliage.getFoliageColorBasic(); - } - - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return BiomeColorHelper.getFoliageColorAtPos(iblockaccess, blockpos); - } - public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { byte b0 = 1; int i = b0 + 1; @@ -89,6 +79,113 @@ public abstract class BlockLeaves extends BlockLeavesBase { } + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return BiomeColorHelper.getFoliageColorAtPos(iblockaccess, blockpos); + } + + private void destroy(World worldIn, BlockPos pos) { + this.dropBlockAsItem(worldIn, pos, worldIn.getBlockState(pos), 0); + worldIn.setBlockToAir(pos); + } + + protected void dropApple(World worldIn, BlockPos pos, IBlockState state, int chance) { + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float var4, int i) { + if (!world.isRemote) { + int j = this.getSaplingDropChance(iblockstate); + if (i > 0) { + j -= 2 << i; + if (j < 10) { + j = 10; + } + } + + if (world.rand.nextInt(j) == 0) { + Item item = this.getItemDropped(iblockstate, world.rand, i); + spawnAsEntity(world, blockpos, new ItemStack(item, 1, this.damageDropped(iblockstate))); + } + + j = 200; + if (i > 0) { + j -= 10 << i; + if (j < 40) { + j = 40; + } + } + + this.dropApple(world, blockpos, iblockstate, j); + } + } + + public int getBlockColor() { + return ColorizerFoliage.getFoliageColor(0.5D, 1.0D); + } + + public EnumWorldBlockLayer getBlockLayer() { + return this.isTransparent ? EnumWorldBlockLayer.CUTOUT_MIPPED : EnumWorldBlockLayer.SOLID; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.sapling); + } + + public int getRenderColor(IBlockState var1) { + return ColorizerFoliage.getFoliageColorBasic(); + } + + protected int getSaplingDropChance(IBlockState state) { + return 20; + } + + public abstract BlockPlanks.EnumType getWoodType(int var1); + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return !this.fancyGraphics; + } + + public boolean isVisuallyOpaque() { + return false; + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom random) { + return random.nextInt(20) == 0 ? 1 : 0; + } + + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { + if (world.canLightningStrike(blockpos.up()) && !World.doesBlockHaveSolidTopSurface(world, blockpos.down()) + && random.nextInt(15) == 1) { + double d0 = (double) ((float) blockpos.getX() + random.nextFloat()); + double d1 = (double) blockpos.getY() - 0.05D; + double d2 = (double) ((float) blockpos.getZ() + random.nextFloat()); + world.spawnParticle(EnumParticleTypes.DRIP_WATER, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); + } + + } + + /** + * + Pass true to draw this block using fancy graphics, or false for fast + * graphics. + */ + public void setGraphicsLevel(boolean fancy) { + this.isTransparent = fancy; + this.fancyGraphics = fancy; + this.iconIndex = fancy ? 0 : 1; + } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { if (!world.isRemote) { if (((Boolean) iblockstate.getValue(CHECK_DECAY)).booleanValue() @@ -171,99 +268,4 @@ public abstract class BlockLeaves extends BlockLeavesBase { } } } - - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { - if (world.canLightningStrike(blockpos.up()) && !World.doesBlockHaveSolidTopSurface(world, blockpos.down()) - && random.nextInt(15) == 1) { - double d0 = (double) ((float) blockpos.getX() + random.nextFloat()); - double d1 = (double) blockpos.getY() - 0.05D; - double d2 = (double) ((float) blockpos.getZ() + random.nextFloat()); - world.spawnParticle(EnumParticleTypes.DRIP_WATER, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); - } - - } - - private void destroy(World worldIn, BlockPos pos) { - this.dropBlockAsItem(worldIn, pos, worldIn.getBlockState(pos), 0); - worldIn.setBlockToAir(pos); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom random) { - return random.nextInt(20) == 0 ? 1 : 0; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.sapling); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float var4, int i) { - if (!world.isRemote) { - int j = this.getSaplingDropChance(iblockstate); - if (i > 0) { - j -= 2 << i; - if (j < 10) { - j = 10; - } - } - - if (world.rand.nextInt(j) == 0) { - Item item = this.getItemDropped(iblockstate, world.rand, i); - spawnAsEntity(world, blockpos, new ItemStack(item, 1, this.damageDropped(iblockstate))); - } - - j = 200; - if (i > 0) { - j -= 10 << i; - if (j < 40) { - j = 40; - } - } - - this.dropApple(world, blockpos, iblockstate, j); - } - } - - protected void dropApple(World worldIn, BlockPos pos, IBlockState state, int chance) { - } - - protected int getSaplingDropChance(IBlockState state) { - return 20; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return !this.fancyGraphics; - } - - /**+ - * Pass true to draw this block using fancy graphics, or false - * for fast graphics. - */ - public void setGraphicsLevel(boolean fancy) { - this.isTransparent = fancy; - this.fancyGraphics = fancy; - this.iconIndex = fancy ? 0 : 1; - } - - public EnumWorldBlockLayer getBlockLayer() { - return this.isTransparent ? EnumWorldBlockLayer.CUTOUT_MIPPED : EnumWorldBlockLayer.SOLID; - } - - public boolean isVisuallyOpaque() { - return false; - } - - public abstract BlockPlanks.EnumType getWoodType(int var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockLeavesBase.java b/src/game/java/net/minecraft/block/BlockLeavesBase.java index a936a4b6..e86b7c7c 100644 --- a/src/game/java/net/minecraft/block/BlockLeavesBase.java +++ b/src/game/java/net/minecraft/block/BlockLeavesBase.java @@ -5,22 +5,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +36,9 @@ public class BlockLeavesBase extends Block { this.fancyGraphics = fancyGraphics; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; diff --git a/src/game/java/net/minecraft/block/BlockLever.java b/src/game/java/net/minecraft/block/BlockLever.java index ac4b293b..b12cd8b8 100644 --- a/src/game/java/net/minecraft/block/BlockLever.java +++ b/src/game/java/net/minecraft/block/BlockLever.java @@ -16,273 +16,42 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockLever extends Block { - public static PropertyEnum FACING; - public static final PropertyBool POWERED = PropertyBool.create("powered"); - - protected BlockLever() { - super(Material.circuits); - this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, BlockLever.EnumOrientation.NORTH) - .withProperty(POWERED, Boolean.valueOf(false))); - this.setCreativeTab(CreativeTabs.tabRedstone); - } - - public static void bootstrapStates() { - FACING = PropertyEnum.create("facing", BlockLever.EnumOrientation.class); - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { - return func_181090_a(world, blockpos, enumfacing.getOpposite()); - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (func_181090_a(world, blockpos, enumfacing)) { - return true; - } - } - - return false; - } - - protected static boolean func_181090_a(World parWorld, BlockPos parBlockPos, EnumFacing parEnumFacing) { - return BlockButton.func_181088_a(parWorld, parBlockPos, parEnumFacing); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase entitylivingbase) { - IBlockState iblockstate = this.getDefaultState().withProperty(POWERED, Boolean.valueOf(false)); - if (func_181090_a(world, blockpos, enumfacing.getOpposite())) { - return iblockstate.withProperty(FACING, - BlockLever.EnumOrientation.forFacings(enumfacing, entitylivingbase.getHorizontalFacing())); - } else { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing1 = facings[i]; - if (enumfacing1 != enumfacing && func_181090_a(world, blockpos, enumfacing1.getOpposite())) { - return iblockstate.withProperty(FACING, - BlockLever.EnumOrientation.forFacings(enumfacing1, entitylivingbase.getHorizontalFacing())); - } - } - - if (World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { - return iblockstate.withProperty(FACING, - BlockLever.EnumOrientation.forFacings(EnumFacing.UP, entitylivingbase.getHorizontalFacing())); - } else { - return iblockstate; - } - } - } - - public static int getMetadataForFacing(EnumFacing facing) { - switch (facing) { - case DOWN: - return 0; - case UP: - return 5; - case NORTH: - return 4; - case SOUTH: - return 3; - case WEST: - return 2; - case EAST: - return 1; - default: - return -1; - } - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (this.func_181091_e(world, blockpos, iblockstate) && !func_181090_a(world, blockpos, - ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing().getOpposite())) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - } - - private boolean func_181091_e(World parWorld, BlockPos parBlockPos, IBlockState parIBlockState) { - if (this.canPlaceBlockAt(parWorld, parBlockPos)) { - return true; - } else { - this.dropBlockAsItem(parWorld, parBlockPos, parIBlockState, 0); - parWorld.setBlockToAir(parBlockPos); - return false; - } - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - float f = 0.1875F; - switch ((BlockLever.EnumOrientation) iblockaccess.getBlockState(blockpos).getValue(FACING)) { - case EAST: - this.setBlockBounds(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); - break; - case WEST: - this.setBlockBounds(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); - break; - case SOUTH: - this.setBlockBounds(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); - break; - case NORTH: - this.setBlockBounds(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); - break; - case UP_Z: - case UP_X: - f = 0.25F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); - break; - case DOWN_X: - case DOWN_Z: - f = 0.25F; - this.setBlockBounds(0.5F - f, 0.4F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); - } - - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, - EnumFacing var5, float var6, float var7, float var8) { - if (world.isRemote) { - return true; - } else { - iblockstate = iblockstate.cycleProperty(POWERED); - world.setBlockState(blockpos, iblockstate, 3); - world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, - (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, - ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0.6F : 0.5F); - world.notifyNeighborsOfStateChange(blockpos, this); - EnumFacing enumfacing = ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing(); - world.notifyNeighborsOfStateChange(blockpos.offset(enumfacing.getOpposite()), this); - return true; - } - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - world.notifyNeighborsOfStateChange(blockpos, this); - EnumFacing enumfacing = ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing(); - world.notifyNeighborsOfStateChange(blockpos.offset(enumfacing.getOpposite()), this); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { - return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; - } - - public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { - return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 - : (((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing() == enumfacing ? 15 : 0); - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return true; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, BlockLever.EnumOrientation.byMetadata(i & 7)) - .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getMetadata(); - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, POWERED }); - } - public static enum EnumOrientation implements IStringSerializable { DOWN_X(0, "down_x", EnumFacing.DOWN), EAST(1, "east", EnumFacing.EAST), WEST(2, "west", EnumFacing.WEST), SOUTH(3, "south", EnumFacing.SOUTH), NORTH(4, "north", EnumFacing.NORTH), UP_Z(5, "up_z", EnumFacing.UP), UP_X(6, "up_x", EnumFacing.UP), DOWN_Z(7, "down_z", EnumFacing.DOWN); private static final BlockLever.EnumOrientation[] META_LOOKUP = new BlockLever.EnumOrientation[8]; - private final int meta; - private final String name; - private final EnumFacing facing; + static { + BlockLever.EnumOrientation[] orientations = values(); + for (int i = 0; i < orientations.length; ++i) { + META_LOOKUP[orientations[i].getMetadata()] = orientations[i]; + } - private EnumOrientation(int meta, String name, EnumFacing facing) { - this.meta = meta; - this.name = name; - this.facing = facing; - } - - public int getMetadata() { - return this.meta; - } - - public EnumFacing getFacing() { - return this.facing; - } - - public String toString() { - return this.name; } public static BlockLever.EnumOrientation byMetadata(int meta) { @@ -328,16 +97,253 @@ public class BlockLever extends Block { } } + private final int meta; + + private final String name; + + private final EnumFacing facing; + + private EnumOrientation(int meta, String name, EnumFacing facing) { + this.meta = meta; + this.name = name; + this.facing = facing; + } + + public EnumFacing getFacing() { + return this.facing; + } + + public int getMetadata() { + return this.meta; + } + public String getName() { return this.name; } - static { - BlockLever.EnumOrientation[] orientations = values(); - for (int i = 0; i < orientations.length; ++i) { - META_LOOKUP[orientations[i].getMetadata()] = orientations[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum FACING; + + public static final PropertyBool POWERED = PropertyBool.create("powered"); + + public static void bootstrapStates() { + FACING = PropertyEnum.create("facing", BlockLever.EnumOrientation.class); + } + + protected static boolean func_181090_a(World parWorld, BlockPos parBlockPos, EnumFacing parEnumFacing) { + return BlockButton.func_181088_a(parWorld, parBlockPos, parEnumFacing); + } + + public static int getMetadataForFacing(EnumFacing facing) { + switch (facing) { + case DOWN: + return 0; + case UP: + return 5; + case NORTH: + return 4; + case SOUTH: + return 3; + case WEST: + return 2; + case EAST: + return 1; + default: + return -1; + } + } + + protected BlockLever() { + super(Material.circuits); + this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, BlockLever.EnumOrientation.NORTH) + .withProperty(POWERED, Boolean.valueOf(false))); + this.setCreativeTab(CreativeTabs.tabRedstone); + } + + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + world.notifyNeighborsOfStateChange(blockpos, this); + EnumFacing enumfacing = ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing(); + world.notifyNeighborsOfStateChange(blockpos.offset(enumfacing.getOpposite()), this); + } + + super.breakBlock(world, blockpos, iblockstate); + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (func_181090_a(world, blockpos, enumfacing)) { + return true; + } + } + + return false; + } + + /** + * + Check whether this Block can be placed on the given side + */ + public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { + return func_181090_a(world, blockpos, enumfacing.getOpposite()); + } + + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. + */ + public boolean canProvidePower() { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, POWERED }); + } + + private boolean func_181091_e(World parWorld, BlockPos parBlockPos, IBlockState parIBlockState) { + if (this.canPlaceBlockAt(parWorld, parBlockPos)) { + return true; + } else { + this.dropBlockAsItem(parWorld, parBlockPos, parIBlockState, 0); + parWorld.setBlockToAir(parBlockPos); + return false; + } + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getMetadata(); + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 8; + } + + return i; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, BlockLever.EnumOrientation.byMetadata(i & 7)) + .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); + } + + public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { + return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 + : (((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing() == enumfacing ? 15 : 0); + } + + public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { + return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer var4, + EnumFacing var5, float var6, float var7, float var8) { + if (world.isRemote) { + return true; + } else { + iblockstate = iblockstate.cycleProperty(POWERED); + world.setBlockState(blockpos, iblockstate, 3); + world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, + (double) blockpos.getZ() + 0.5D, "random.click", 0.3F, + ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0.6F : 0.5F); + world.notifyNeighborsOfStateChange(blockpos, this); + EnumFacing enumfacing = ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing(); + world.notifyNeighborsOfStateChange(blockpos.offset(enumfacing.getOpposite()), this); + return true; + } + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase entitylivingbase) { + IBlockState iblockstate = this.getDefaultState().withProperty(POWERED, Boolean.valueOf(false)); + if (func_181090_a(world, blockpos, enumfacing.getOpposite())) { + return iblockstate.withProperty(FACING, + BlockLever.EnumOrientation.forFacings(enumfacing, entitylivingbase.getHorizontalFacing())); + } else { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing1 = facings[i]; + if (enumfacing1 != enumfacing && func_181090_a(world, blockpos, enumfacing1.getOpposite())) { + return iblockstate.withProperty(FACING, + BlockLever.EnumOrientation.forFacings(enumfacing1, entitylivingbase.getHorizontalFacing())); + } + } + + if (World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { + return iblockstate.withProperty(FACING, + BlockLever.EnumOrientation.forFacings(EnumFacing.UP, entitylivingbase.getHorizontalFacing())); + } else { + return iblockstate; + } + } + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (this.func_181091_e(world, blockpos, iblockstate) && !func_181090_a(world, blockpos, + ((BlockLever.EnumOrientation) iblockstate.getValue(FACING)).getFacing().getOpposite())) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + float f = 0.1875F; + switch ((BlockLever.EnumOrientation) iblockaccess.getBlockState(blockpos).getValue(FACING)) { + case EAST: + this.setBlockBounds(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); + break; + case WEST: + this.setBlockBounds(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); + break; + case SOUTH: + this.setBlockBounds(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); + break; + case NORTH: + this.setBlockBounds(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); + break; + case UP_Z: + case UP_X: + f = 0.25F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); + break; + case DOWN_X: + case DOWN_Z: + f = 0.25F; + this.setBlockBounds(0.5F - f, 0.4F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockLilyPad.java b/src/game/java/net/minecraft/block/BlockLilyPad.java index 3eaa543f..10e69ea3 100644 --- a/src/game/java/net/minecraft/block/BlockLilyPad.java +++ b/src/game/java/net/minecraft/block/BlockLilyPad.java @@ -13,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,9 +44,9 @@ public class BlockLilyPad extends BlockBush { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -53,31 +56,6 @@ public class BlockLilyPad extends BlockBush { } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { - return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, - (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, - (double) blockpos.getY() + this.maxY, (double) blockpos.getZ() + this.maxZ); - } - - public int getBlockColor() { - return 7455580; - } - - public int getRenderColor(IBlockState var1) { - return 7455580; - } - - public int colorMultiplier(IBlockAccess var1, BlockPos var2, int var3) { - return 2129968; - } - - /**+ - * is the block grass, dirt or farmland - */ - protected boolean canPlaceBlockOn(Block block) { - return block == Blocks.water; - } - public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { if (blockpos.getY() >= 0 && blockpos.getY() < 256) { IBlockState iblockstate = world.getBlockState(blockpos.down()); @@ -88,10 +66,35 @@ public class BlockLilyPad extends BlockBush { } } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + is the block grass, dirt or farmland + */ + protected boolean canPlaceBlockOn(Block block) { + return block == Blocks.water; + } + + public int colorMultiplier(IBlockAccess var1, BlockPos var2, int var3) { + return 2129968; + } + + public int getBlockColor() { + return 7455580; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState var3) { + return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, + (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, + (double) blockpos.getY() + this.maxY, (double) blockpos.getZ() + this.maxZ); + } + + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState var1) { return 0; } + + public int getRenderColor(IBlockState var1) { + return 7455580; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockLiquid.java b/src/game/java/net/minecraft/block/BlockLiquid.java index 8de2824e..e5a08540 100644 --- a/src/game/java/net/minecraft/block/BlockLiquid.java +++ b/src/game/java/net/minecraft/block/BlockLiquid.java @@ -21,22 +21,25 @@ import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeColorHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,25 +47,25 @@ import net.minecraft.world.biome.BiomeColorHelper; public abstract class BlockLiquid extends Block { public static final PropertyInteger LEVEL = PropertyInteger.create("level", 0, 15); - protected BlockLiquid(Material materialIn) { - super(materialIn); - this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - this.setTickRandomly(true); + public static double getFlowDirection(IBlockAccess worldIn, BlockPos pos, Material materialIn) { + Vec3 vec3 = getFlowingBlock(materialIn).getFlowVector(worldIn, pos); + return vec3.xCoord == 0.0D && vec3.zCoord == 0.0D ? -1000.0D + : MathHelper.func_181159_b(vec3.zCoord, vec3.xCoord) - 1.5707963267948966D; } - public boolean isPassable(IBlockAccess var1, BlockPos var2) { - return this.blockMaterial != Material.lava; + public static BlockDynamicLiquid getFlowingBlock(Material materialIn) { + if (materialIn == Material.water) { + return Blocks.flowing_water; + } else if (materialIn == Material.lava) { + return Blocks.flowing_lava; + } else { + throw new IllegalArgumentException("Invalid material"); + } } - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return this.blockMaterial == Material.water ? BiomeColorHelper.getWaterColorAtPos(iblockaccess, blockpos) - : 16777215; - } - - /**+ - * Returns the percentage of the liquid block that is air, based - * on the given flow decay of the liquid + /** + * + Returns the percentage of the liquid block that is air, based on the given + * flow decay of the liquid */ public static float getLiquidHeightPercent(int meta) { if (meta >= 8) { @@ -72,46 +75,67 @@ public abstract class BlockLiquid extends Block { return (float) (meta + 1) / 9.0F; } - protected int getLevel(IBlockAccess worldIn, BlockPos pos) { - return worldIn.getBlockState(pos).getBlock().getMaterial() == this.blockMaterial - ? ((Integer) worldIn.getBlockState(pos).getValue(LEVEL)).intValue() - : -1; + public static BlockStaticLiquid getStaticBlock(Material materialIn) { + if (materialIn == Material.water) { + return Blocks.water; + } else if (materialIn == Material.lava) { + return Blocks.lava; + } else { + throw new IllegalArgumentException("Invalid material"); + } } - protected int getEffectiveFlowDecay(IBlockAccess worldIn, BlockPos pos) { - int i = this.getLevel(worldIn, pos); - return i >= 8 ? 0 : i; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; + protected BlockLiquid(Material materialIn) { + super(materialIn); + this.setDefaultState(this.blockState.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.setTickRandomly(true); } public boolean canCollideCheck(IBlockState iblockstate, boolean flag) { return flag && ((Integer) iblockstate.getValue(LEVEL)).intValue() == 0; } - /**+ - * Whether this Block is solid on the given Side - */ - public boolean isBlockSolid(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - Material material = iblockaccess.getBlockState(blockpos).getBlock().getMaterial(); - return material == this.blockMaterial ? false - : (enumfacing == EnumFacing.UP ? true - : (material == Material.ice ? false : super.isBlockSolid(iblockaccess, blockpos, enumfacing))); + public boolean checkForMixing(World worldIn, BlockPos pos, IBlockState state) { + if (this.blockMaterial == Material.lava) { + boolean flag = false; + + EnumFacing[] facings = EnumFacing._VALUES; + for (int j = 0; j < facings.length; ++j) { + EnumFacing enumfacing = facings[j]; + if (enumfacing != EnumFacing.DOWN + && worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getMaterial() == Material.water) { + flag = true; + break; + } + } + + if (flag) { + Integer integer = (Integer) state.getValue(LEVEL); + if (integer.intValue() == 0) { + worldIn.setBlockState(pos, Blocks.obsidian.getDefaultState()); + this.triggerMixEffects(worldIn, pos); + return true; + } + + if (integer.intValue() <= 4) { + worldIn.setBlockState(pos, Blocks.cobblestone.getDefaultState()); + this.triggerMixEffects(worldIn, pos); + return true; + } + } + } + + return false; } - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - return iblockaccess.getBlockState(blockpos).getBlock().getMaterial() == this.blockMaterial ? false - : (enumfacing == EnumFacing.UP ? true : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing)); + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return this.blockMaterial == Material.water ? BiomeColorHelper.getWaterColorAtPos(iblockaccess, blockpos) + : 16777215; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { LEVEL }); } public boolean func_176364_g(IBlockAccess blockAccess, BlockPos pos) { @@ -129,30 +153,20 @@ public abstract class BlockLiquid extends Block { return false; } + public EnumWorldBlockLayer getBlockLayer() { + return this.blockMaterial == Material.water + ? (DeferredStateManager.isRenderingRealisticWater() ? EnumWorldBlockLayer.REALISTIC_WATER + : EnumWorldBlockLayer.TRANSLUCENT) + : EnumWorldBlockLayer.SOLID; + } + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { return null; } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 1; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return null; - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; + protected int getEffectiveFlowDecay(IBlockAccess worldIn, BlockPos pos) { + int i = this.getLevel(worldIn, pos); + return i >= 8 ? 0 : i; } protected Vec3 getFlowVector(IBlockAccess worldIn, BlockPos pos) { @@ -196,16 +210,24 @@ public abstract class BlockLiquid extends Block { return vec3.normalize(); } - public Vec3 modifyAcceleration(World world, BlockPos blockpos, Entity var3, Vec3 vec3) { - return vec3.add(this.getFlowVector(world, blockpos)); + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; } - /**+ - * How many world ticks before ticking + protected int getLevel(IBlockAccess worldIn, BlockPos pos) { + return worldIn.getBlockState(pos).getBlock().getMaterial() == this.blockMaterial + ? ((Integer) worldIn.getBlockState(pos).getValue(LEVEL)).intValue() + : -1; + } + + /** + * + Convert the BlockState into the correct metadata value */ - public int tickRate(World world) { - return this.blockMaterial == Material.water ? 5 - : (this.blockMaterial == Material.lava ? (world.provider.getHasNoSky() ? 10 : 30) : 0); + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(LEVEL)).intValue(); } public int getMixedBrightnessForBlock(IBlockAccess iblockaccess, BlockPos blockpos) { @@ -218,11 +240,67 @@ public abstract class BlockLiquid extends Block { return (k > l ? k : l) | (i1 > j1 ? i1 : j1) << 16; } - public EnumWorldBlockLayer getBlockLayer() { - return this.blockMaterial == Material.water - ? (DeferredStateManager.isRenderingRealisticWater() ? EnumWorldBlockLayer.REALISTIC_WATER - : EnumWorldBlockLayer.TRANSLUCENT) - : EnumWorldBlockLayer.SOLID; + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 1; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(LEVEL, Integer.valueOf(i)); + } + + /** + * + Whether this Block is solid on the given Side + */ + public boolean isBlockSolid(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + Material material = iblockaccess.getBlockState(blockpos).getBlock().getMaterial(); + return material == this.blockMaterial ? false + : (enumfacing == EnumFacing.UP ? true + : (material == Material.ice ? false : super.isBlockSolid(iblockaccess, blockpos, enumfacing))); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean isPassable(IBlockAccess var1, BlockPos var2) { + return this.blockMaterial != Material.lava; + } + + public Vec3 modifyAcceleration(World world, BlockPos blockpos, Entity var3, Vec3 vec3) { + return vec3.add(this.getFlowVector(world, blockpos)); + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + this.checkForMixing(world, blockpos, iblockstate); + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + this.checkForMixing(world, blockpos, iblockstate); + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; } public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -277,54 +355,17 @@ public abstract class BlockLiquid extends Block { } - public static double getFlowDirection(IBlockAccess worldIn, BlockPos pos, Material materialIn) { - Vec3 vec3 = getFlowingBlock(materialIn).getFlowVector(worldIn, pos); - return vec3.xCoord == 0.0D && vec3.zCoord == 0.0D ? -1000.0D - : MathHelper.func_181159_b(vec3.zCoord, vec3.xCoord) - 1.5707963267948966D; + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + return iblockaccess.getBlockState(blockpos).getBlock().getMaterial() == this.blockMaterial ? false + : (enumfacing == EnumFacing.UP ? true : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing)); } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - this.checkForMixing(world, blockpos, iblockstate); - } - - /**+ - * Called when a neighboring block changes. + /** + * + How many world ticks before ticking */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - this.checkForMixing(world, blockpos, iblockstate); - } - - public boolean checkForMixing(World worldIn, BlockPos pos, IBlockState state) { - if (this.blockMaterial == Material.lava) { - boolean flag = false; - - EnumFacing[] facings = EnumFacing._VALUES; - for (int j = 0; j < facings.length; ++j) { - EnumFacing enumfacing = facings[j]; - if (enumfacing != EnumFacing.DOWN - && worldIn.getBlockState(pos.offset(enumfacing)).getBlock().getMaterial() == Material.water) { - flag = true; - break; - } - } - - if (flag) { - Integer integer = (Integer) state.getValue(LEVEL); - if (integer.intValue() == 0) { - worldIn.setBlockState(pos, Blocks.obsidian.getDefaultState()); - this.triggerMixEffects(worldIn, pos); - return true; - } - - if (integer.intValue() <= 4) { - worldIn.setBlockState(pos, Blocks.cobblestone.getDefaultState()); - this.triggerMixEffects(worldIn, pos); - return true; - } - } - } - - return false; + public int tickRate(World world) { + return this.blockMaterial == Material.water ? 5 + : (this.blockMaterial == Material.lava ? (world.provider.getHasNoSky() ? 10 : 30) : 0); } protected void triggerMixEffects(World worldIn, BlockPos pos) { @@ -340,42 +381,4 @@ public abstract class BlockLiquid extends Block { } } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(LEVEL, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(LEVEL)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { LEVEL }); - } - - public static BlockDynamicLiquid getFlowingBlock(Material materialIn) { - if (materialIn == Material.water) { - return Blocks.flowing_water; - } else if (materialIn == Material.lava) { - return Blocks.flowing_lava; - } else { - throw new IllegalArgumentException("Invalid material"); - } - } - - public static BlockStaticLiquid getStaticBlock(Material materialIn) { - if (materialIn == Material.water) { - return Blocks.water; - } else if (materialIn == Material.lava) { - return Blocks.lava; - } else { - throw new IllegalArgumentException("Invalid material"); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockLog.java b/src/game/java/net/minecraft/block/BlockLog.java index b9dac1e8..c63cbb36 100644 --- a/src/game/java/net/minecraft/block/BlockLog.java +++ b/src/game/java/net/minecraft/block/BlockLog.java @@ -10,29 +10,67 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockLog extends BlockRotatedPillar { + public static enum EnumAxis implements IStringSerializable { + X("x"), Y("y"), Z("z"), NONE("none"); + + public static BlockLog.EnumAxis fromFacingAxis(EnumFacing.Axis axis) { + switch (axis) { + case X: + return X; + case Y: + return Y; + case Z: + return Z; + default: + return NONE; + } + } + + private final String name; + + private EnumAxis(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static PropertyEnum LOG_AXIS = null; + public static void bootstrapStates() { + LOG_AXIS = PropertyEnum.create("axis", BlockLog.EnumAxis.class); + } + public BlockLog() { super(Material.wood); this.setCreativeTab(CreativeTabs.tabBlock); @@ -40,10 +78,6 @@ public abstract class BlockLog extends BlockRotatedPillar { this.setStepSound(soundTypeWood); } - public static void bootstrapStates() { - LOG_AXIS = PropertyEnum.create("axis", BlockLog.EnumAxis.class); - } - public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { byte b0 = 4; int i = b0 + 1; @@ -60,44 +94,13 @@ public abstract class BlockLog extends BlockRotatedPillar { } } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2, int i, EntityLivingBase entitylivingbase) { return super.onBlockPlaced(world, blockpos, enumfacing, f, f1, f2, i, entitylivingbase).withProperty(LOG_AXIS, BlockLog.EnumAxis.fromFacingAxis(enumfacing.getAxis())); } - - public static enum EnumAxis implements IStringSerializable { - X("x"), Y("y"), Z("z"), NONE("none"); - - private final String name; - - private EnumAxis(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } - - public static BlockLog.EnumAxis fromFacingAxis(EnumFacing.Axis axis) { - switch (axis) { - case X: - return X; - case Y: - return Y; - case Z: - return Z; - default: - return NONE; - } - } - - public String getName() { - return this.name; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockMelon.java b/src/game/java/net/minecraft/block/BlockMelon.java index 1ee61f78..3608db95 100644 --- a/src/game/java/net/minecraft/block/BlockMelon.java +++ b/src/game/java/net/minecraft/block/BlockMelon.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -9,22 +8,25 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,22 +37,22 @@ public class BlockMelon extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Items.melon; } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom random) { return 3 + random.nextInt(5); } - /**+ - * Get the quantity dropped based on the given fortune level + /** + * + Get the quantity dropped based on the given fortune level */ public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { return Math.min(9, this.quantityDropped(random) + random.nextInt(1 + i)); diff --git a/src/game/java/net/minecraft/block/BlockMobSpawner.java b/src/game/java/net/minecraft/block/BlockMobSpawner.java index 9871d940..cc55574e 100644 --- a/src/game/java/net/minecraft/block/BlockMobSpawner.java +++ b/src/game/java/net/minecraft/block/BlockMobSpawner.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; @@ -11,22 +10,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,30 +38,16 @@ public class BlockMobSpawner extends BlockContainer { super(Material.rock); } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ public TileEntity createNewTileEntity(World var1, int var2) { return new TileEntityMobSpawner(); } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return null; - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); @@ -67,22 +55,6 @@ public class BlockMobSpawner extends BlockContainer { this.dropXpOnBlockBreak(world, blockpos, j); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() { - return 3; - } - public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.CUTOUT; } @@ -90,4 +62,34 @@ public class BlockMobSpawner extends BlockContainer { public Item getItem(World var1, BlockPos var2) { return null; } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockMosaic.java b/src/game/java/net/minecraft/block/BlockMosaic.java new file mode 100644 index 00000000..3d82dc54 --- /dev/null +++ b/src/game/java/net/minecraft/block/BlockMosaic.java @@ -0,0 +1,158 @@ +package net.minecraft.block; + +import java.util.List; + +import net.minecraft.block.material.MapColor; +import net.minecraft.block.material.Material; +import net.minecraft.block.properties.IProperty; +import net.minecraft.block.properties.PropertyEnum; +import net.minecraft.block.state.BlockState; +import net.minecraft.block.state.IBlockState; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.util.IStringSerializable; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class BlockMosaic extends Block { + public static enum EnumType implements IStringSerializable { + OAK(0, "oak", MapColor.woodColor), SPRUCE(1, "spruce", MapColor.obsidianColor), + BIRCH(2, "birch", MapColor.sandColor), JUNGLE(3, "jungle", MapColor.dirtColor), + ACACIA(4, "acacia", MapColor.adobeColor), DARK_OAK(5, "dark_oak", MapColor.brownColor); + + public static final BlockMosaic.EnumType[] META_LOOKUP = new BlockMosaic.EnumType[6]; + static { + BlockMosaic.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockMosaic.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + private final String name; + + private final String unlocalizedName; + + private final MapColor field_181071_k; + + private EnumType(int parInt2, String parString2, MapColor parMapColor) { + this(parInt2, parString2, parString2, parMapColor); + } + + private EnumType(int parInt2, String parString2, String parString3, MapColor parMapColor) { + this.meta = parInt2; + this.name = parString2; + this.unlocalizedName = parString3; + this.field_181071_k = parMapColor; + } + + public MapColor func_181070_c() { + return this.field_181071_k; + } + + public int getMetadata() { + return this.meta; + } + + public String getName() { + return this.name; + } + + public String getUnlocalizedName() { + return this.unlocalizedName; + } + + public String toString() { + return this.name; + } + } + + public static PropertyEnum VARIANT; + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockMosaic.EnumType.class); + } + + public BlockMosaic() { + super(Material.wood); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockMosaic.EnumType.OAK)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockMosaic.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockMosaic.EnumType) iblockstate.getValue(VARIANT)).func_181070_c(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockMosaic.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockMosaic.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockMosaic.EnumType[] types = BlockMosaic.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockMushroom.java b/src/game/java/net/minecraft/block/BlockMushroom.java index 37e442ca..f43209e2 100644 --- a/src/game/java/net/minecraft/block/BlockMushroom.java +++ b/src/game/java/net/minecraft/block/BlockMushroom.java @@ -1,29 +1,31 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenBigMushroom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +37,61 @@ public class BlockMushroom extends BlockBush implements IGrowable { this.setTickRandomly(true); } + public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { + if (blockpos.getY() >= 0 && blockpos.getY() < 256) { + IBlockState iblockstate = world.getBlockState(blockpos.down()); + return iblockstate.getBlock() == Blocks.mycelium ? true + : (iblockstate.getBlock() == Blocks.dirt + && iblockstate.getValue(BlockDirt.VARIANT) == BlockDirt.DirtType.PODZOL ? true + : world.getLight(blockpos) < 13 && this.canPlaceBlockOn(iblockstate.getBlock())); + } else { + return false; + } + } + + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4) { + return true; + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return super.canPlaceBlockAt(world, blockpos) && this.canBlockStay(world, blockpos, this.getDefaultState()); + } + + /** + * + is the block grass, dirt or farmland + */ + protected boolean canPlaceBlockOn(Block block) { + return block.isFullBlock(); + } + + public boolean canUseBonemeal(World var1, EaglercraftRandom random, BlockPos var3, IBlockState var4) { + return (double) random.nextFloat() < 0.4D; + } + + public boolean generateBigMushroom(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { + worldIn.setBlockToAir(pos); + WorldGenBigMushroom worldgenbigmushroom = null; + if (this == Blocks.brown_mushroom) { + worldgenbigmushroom = new WorldGenBigMushroom(Blocks.brown_mushroom_block); + } else if (this == Blocks.red_mushroom) { + worldgenbigmushroom = new WorldGenBigMushroom(Blocks.red_mushroom_block); + } + + if (worldgenbigmushroom != null && worldgenbigmushroom.generate(worldIn, rand, pos)) { + return true; + } else { + worldIn.setBlockState(pos, state, 3); + return false; + } + } + + public void grow(World world, EaglercraftRandom random, BlockPos blockpos, IBlockState iblockstate) { + this.generateBigMushroom(world, blockpos, iblockstate, random); + } + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { if (random.nextInt(25) == 0) { int i = 5; @@ -67,59 +124,4 @@ public class BlockMushroom extends BlockBush implements IGrowable { } } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return super.canPlaceBlockAt(world, blockpos) && this.canBlockStay(world, blockpos, this.getDefaultState()); - } - - /**+ - * is the block grass, dirt or farmland - */ - protected boolean canPlaceBlockOn(Block block) { - return block.isFullBlock(); - } - - public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { - if (blockpos.getY() >= 0 && blockpos.getY() < 256) { - IBlockState iblockstate = world.getBlockState(blockpos.down()); - return iblockstate.getBlock() == Blocks.mycelium ? true - : (iblockstate.getBlock() == Blocks.dirt - && iblockstate.getValue(BlockDirt.VARIANT) == BlockDirt.DirtType.PODZOL ? true - : world.getLight(blockpos) < 13 && this.canPlaceBlockOn(iblockstate.getBlock())); - } else { - return false; - } - } - - public boolean generateBigMushroom(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { - worldIn.setBlockToAir(pos); - WorldGenBigMushroom worldgenbigmushroom = null; - if (this == Blocks.brown_mushroom) { - worldgenbigmushroom = new WorldGenBigMushroom(Blocks.brown_mushroom_block); - } else if (this == Blocks.red_mushroom) { - worldgenbigmushroom = new WorldGenBigMushroom(Blocks.red_mushroom_block); - } - - if (worldgenbigmushroom != null && worldgenbigmushroom.generate(worldIn, rand, pos)) { - return true; - } else { - worldIn.setBlockState(pos, state, 3); - return false; - } - } - - /**+ - * Whether this IGrowable can grow - */ - public boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4) { - return true; - } - - public boolean canUseBonemeal(World var1, EaglercraftRandom random, BlockPos var3, IBlockState var4) { - return (double) random.nextFloat() < 0.4D; - } - - public void grow(World world, EaglercraftRandom random, BlockPos blockpos, IBlockState iblockstate) { - this.generateBigMushroom(world, blockpos, iblockstate, random); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockMycelium.java b/src/game/java/net/minecraft/block/BlockMycelium.java index 4224f045..a07a1ea3 100644 --- a/src/game/java/net/minecraft/block/BlockMycelium.java +++ b/src/game/java/net/minecraft/block/BlockMycelium.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -16,22 +15,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,16 +48,44 @@ public class BlockMycelium extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { SNOWY }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { Block block = iblockaccess.getBlockState(blockpos.up()).getBlock(); return iblockstate.withProperty(SNOWY, Boolean.valueOf(block == Blocks.snow || block == Blocks.snow_layer)); } + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int i) { + return Blocks.dirt.getItemDropped( + Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), random, i); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState var1) { + return 0; + } + + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + super.randomDisplayTick(world, blockpos, iblockstate, random); + if (random.nextInt(10) == 0) { + world.spawnParticle(EnumParticleTypes.TOWN_AURA, (double) ((float) blockpos.getX() + random.nextFloat()), + (double) ((float) blockpos.getY() + 1.1F), (double) ((float) blockpos.getZ() + random.nextFloat()), + 0.0D, 0.0D, 0.0D, new int[0]); + } + + } + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { if (!world.isRemote) { if (world.getLightFromNeighbors(blockpos.up()) < 4 @@ -79,33 +109,4 @@ public class BlockMycelium extends Block { } } } - - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - super.randomDisplayTick(world, blockpos, iblockstate, random); - if (random.nextInt(10) == 0) { - world.spawnParticle(EnumParticleTypes.TOWN_AURA, (double) ((float) blockpos.getX() + random.nextFloat()), - (double) ((float) blockpos.getY() + 1.1F), (double) ((float) blockpos.getZ() + random.nextFloat()), - 0.0D, 0.0D, 0.0D, new int[0]); - } - - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int i) { - return Blocks.dirt.getItemDropped( - Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT), random, i); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState var1) { - return 0; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { SNOWY }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockNetherBrick.java b/src/game/java/net/minecraft/block/BlockNetherBrick.java index 8b7cbe8c..85e383bc 100644 --- a/src/game/java/net/minecraft/block/BlockNetherBrick.java +++ b/src/game/java/net/minecraft/block/BlockNetherBrick.java @@ -5,22 +5,25 @@ import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +34,8 @@ public class BlockNetherBrick extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.netherrackColor; diff --git a/src/game/java/net/minecraft/block/BlockNetherWart.java b/src/game/java/net/minecraft/block/BlockNetherWart.java index a6d0f282..1ac7db8b 100644 --- a/src/game/java/net/minecraft/block/BlockNetherWart.java +++ b/src/game/java/net/minecraft/block/BlockNetherWart.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -16,22 +15,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,29 +50,23 @@ public class BlockNetherWart extends BlockBush { this.setCreativeTab((CreativeTabs) null); } - /**+ - * is the block grass, dirt or farmland + public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { + return this.canPlaceBlockOn(world.getBlockState(blockpos.down()).getBlock()); + } + + /** + * + is the block grass, dirt or farmland */ protected boolean canPlaceBlockOn(Block block) { return block == Blocks.soul_sand; } - public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { - return this.canPlaceBlockOn(world.getBlockState(blockpos.down()).getBlock()); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AGE }); } - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - int i = ((Integer) iblockstate.getValue(AGE)).intValue(); - if (i < 3 && random.nextInt(10) == 0) { - iblockstate = iblockstate.withProperty(AGE, Integer.valueOf(i + 1)); - world.setBlockState(blockpos, iblockstate, 2); - } - - super.updateTick(world, blockpos, iblockstate, random); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float var4, int i) { if (!world.isRemote) { @@ -88,39 +84,45 @@ public class BlockNetherWart extends BlockBush { } } - /**+ - * Get the Item that this Block should drop when harvested. + public Item getItem(World var1, BlockPos var2) { + return Items.nether_wart; + } + + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return null; } - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.nether_wart; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { return ((Integer) iblockstate.getValue(AGE)).intValue(); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AGE }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } + + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + int i = ((Integer) iblockstate.getValue(AGE)).intValue(); + if (i < 3 && random.nextInt(10) == 0) { + iblockstate = iblockstate.withProperty(AGE, Integer.valueOf(i + 1)); + world.setBlockState(blockpos, iblockstate, 2); + } + + super.updateTick(world, blockpos, iblockstate, random); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockNetherrack.java b/src/game/java/net/minecraft/block/BlockNetherrack.java index fe9f1f07..01c1da64 100644 --- a/src/game/java/net/minecraft/block/BlockNetherrack.java +++ b/src/game/java/net/minecraft/block/BlockNetherrack.java @@ -5,22 +5,25 @@ import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +34,8 @@ public class BlockNetherrack extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.netherrackColor; diff --git a/src/game/java/net/minecraft/block/BlockNewLeaf.java b/src/game/java/net/minecraft/block/BlockNewLeaf.java index 0b017718..a5838762 100644 --- a/src/game/java/net/minecraft/block/BlockNewLeaf.java +++ b/src/game/java/net/minecraft/block/BlockNewLeaf.java @@ -18,22 +18,25 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,11 +44,6 @@ import net.minecraft.world.World; public class BlockNewLeaf extends BlockLeaves { public static PropertyEnum VARIANT; - public BlockNewLeaf() { - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.ACACIA) - .withProperty(CHECK_DECAY, Boolean.valueOf(true)).withProperty(DECAYABLE, Boolean.valueOf(true))); - } - public static void bootstrapStates() { VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class, new Predicate() { public boolean apply(BlockPlanks.EnumType blockplanks$enumtype) { @@ -54,34 +52,13 @@ public class BlockNewLeaf extends BlockLeaves { }); } - protected void dropApple(World world, BlockPos blockpos, IBlockState iblockstate, int i) { - if (iblockstate.getValue(VARIANT) == BlockPlanks.EnumType.DARK_OAK && world.rand.nextInt(i) == 0) { - spawnAsEntity(world, blockpos, new ItemStack(Items.apple, 1, 0)); - } + public BlockNewLeaf() { + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.ACACIA) + .withProperty(CHECK_DECAY, Boolean.valueOf(true)).withProperty(DECAYABLE, Boolean.valueOf(true))); } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - public int getDamageValue(World world, BlockPos blockpos) { - IBlockState iblockstate = world.getBlockState(blockpos); - return iblockstate.getBlock().getMetaFromState(iblockstate) & 3; - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, 0)); - list.add(new ItemStack(item, 1, 1)); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT, CHECK_DECAY, DECAYABLE }); } protected ItemStack createStackedBlock(IBlockState iblockstate) { @@ -89,17 +66,28 @@ public class BlockNewLeaf extends BlockLeaves { ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4); } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, this.getWoodType(i)) - .withProperty(DECAYABLE, Boolean.valueOf((i & 4) == 0)) - .withProperty(CHECK_DECAY, Boolean.valueOf((i & 8) > 0)); + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); } - /**+ - * Convert the BlockState into the correct metadata value + protected void dropApple(World world, BlockPos blockpos, IBlockState iblockstate, int i) { + if (iblockstate.getValue(VARIANT) == BlockPlanks.EnumType.DARK_OAK && world.rand.nextInt(i) == 0) { + spawnAsEntity(world, blockpos, new ItemStack(Items.apple, 1, 0)); + } + } + + public int getDamageValue(World world, BlockPos blockpos) { + IBlockState iblockstate = world.getBlockState(blockpos); + return iblockstate.getBlock().getMetaFromState(iblockstate) & 3; + } + + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -115,12 +103,26 @@ public class BlockNewLeaf extends BlockLeaves { return i; } - public BlockPlanks.EnumType getWoodType(int i) { - return BlockPlanks.EnumType.byMetadata((i & 3) + 4); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, this.getWoodType(i)) + .withProperty(DECAYABLE, Boolean.valueOf((i & 4) == 0)) + .withProperty(CHECK_DECAY, Boolean.valueOf((i & 8) > 0)); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT, CHECK_DECAY, DECAYABLE }); + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, 0)); + list.add(new ItemStack(item, 1, 1)); + } + + public BlockPlanks.EnumType getWoodType(int i) { + return BlockPlanks.EnumType.byMetadata((i & 3) + 4); } public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, diff --git a/src/game/java/net/minecraft/block/BlockNewLog.java b/src/game/java/net/minecraft/block/BlockNewLog.java index a2bfce4a..546aec84 100644 --- a/src/game/java/net/minecraft/block/BlockNewLog.java +++ b/src/game/java/net/minecraft/block/BlockNewLog.java @@ -13,22 +13,25 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,11 +39,6 @@ import net.minecraft.item.ItemStack; public class BlockNewLog extends BlockLog { public static PropertyEnum VARIANT; - public BlockNewLog() { - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.ACACIA) - .withProperty(LOG_AXIS, BlockLog.EnumAxis.Y)); - } - public static void bootstrapStates() { VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class, new Predicate() { public boolean apply(BlockPlanks.EnumType blockplanks$enumtype) { @@ -49,8 +47,31 @@ public class BlockNewLog extends BlockLog { }); } - /**+ - * Get the MapColor for this Block and the given BlockState + public BlockNewLog() { + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.ACACIA) + .withProperty(LOG_AXIS, BlockLog.EnumAxis.Y)); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT, LOG_AXIS }); + } + + protected ItemStack createStackedBlock(IBlockState iblockstate) { + return new ItemStack(Item.getItemFromBlock(this), 1, + ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4; + } + + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState iblockstate) { BlockPlanks.EnumType blockplanks$enumtype = (BlockPlanks.EnumType) iblockstate.getValue(VARIANT); @@ -71,17 +92,28 @@ public class BlockNewLog extends BlockLog { } } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Convert the BlockState into the correct metadata value */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.ACACIA.getMetadata() - 4)); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.DARK_OAK.getMetadata() - 4)); + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4; + switch ((BlockLog.EnumAxis) iblockstate.getValue(LOG_AXIS)) { + case X: + i |= 4; + break; + case Z: + i |= 8; + break; + case NONE: + i |= 12; + } + + return i; } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int i) { IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, @@ -103,42 +135,12 @@ public class BlockNewLog extends BlockLog { return iblockstate; } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4; - switch ((BlockLog.EnumAxis) iblockstate.getValue(LOG_AXIS)) { - case X: - i |= 4; - break; - case Z: - i |= 8; - break; - case NONE: - i |= 12; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT, LOG_AXIS }); - } - - protected ItemStack createStackedBlock(IBlockState iblockstate) { - return new ItemStack(Item.getItemFromBlock(this), 1, - ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata() - 4; + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.ACACIA.getMetadata() - 4)); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.DARK_OAK.getMetadata() - 4)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockNote.java b/src/game/java/net/minecraft/block/BlockNote.java index 741ea623..8d4fa668 100644 --- a/src/game/java/net/minecraft/block/BlockNote.java +++ b/src/game/java/net/minecraft/block/BlockNote.java @@ -16,22 +16,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,23 +48,28 @@ public class BlockNote extends BlockContainer { this.setCreativeTab(CreativeTabs.tabRedstone); } - /**+ - * Called when a neighboring block changes. + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - boolean flag = world.isBlockPowered(blockpos); - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityNote) { - TileEntityNote tileentitynote = (TileEntityNote) tileentity; - if (tileentitynote.previousRedstoneState != flag) { - if (flag) { - tileentitynote.triggerNote(world, blockpos); - } + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityNote(); + } - tileentitynote.previousRedstoneState = flag; - } + private String getInstrument(int id) { + if (id < 0 || id >= INSTRUMENTS.size()) { + id = 0; } + return (String) INSTRUMENTS.get(id); + } + + /** + * + The type of render function called. 3 for standard block models, 2 for + * TESR's, 1 for liquids, -1 is no render + */ + public int getRenderType() { + return 3; } public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, @@ -91,25 +99,8 @@ public class BlockNote extends BlockContainer { } } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityNote(); - } - - private String getInstrument(int id) { - if (id < 0 || id >= INSTRUMENTS.size()) { - id = 0; - } - - return (String) INSTRUMENTS.get(id); - } - - /**+ - * Called on both Client and Server when World#addBlockEvent is - * called + /** + * + Called on both Client and Server when World#addBlockEvent is called */ public boolean onBlockEventReceived(World world, BlockPos blockpos, IBlockState var3, int i, int j) { float f = (float) Math.pow(2.0D, (double) (j - 12) / 12.0D); @@ -120,11 +111,22 @@ public class BlockNote extends BlockContainer { return true; } - /**+ - * The type of render function called. 3 for standard block - * models, 2 for TESR's, 1 for liquids, -1 is no render + /** + * + Called when a neighboring block changes. */ - public int getRenderType() { - return 3; + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + boolean flag = world.isBlockPowered(blockpos); + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityNote) { + TileEntityNote tileentitynote = (TileEntityNote) tileentity; + if (tileentitynote.previousRedstoneState != flag) { + if (flag) { + tileentitynote.triggerNote(world, blockpos); + } + + tileentitynote.previousRedstoneState = flag; + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockObsidian.java b/src/game/java/net/minecraft/block/BlockObsidian.java index a26536c2..2060e763 100644 --- a/src/game/java/net/minecraft/block/BlockObsidian.java +++ b/src/game/java/net/minecraft/block/BlockObsidian.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -9,22 +8,25 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.Item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,15 +37,15 @@ public class BlockObsidian extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Item.getItemFromBlock(Blocks.obsidian); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.blackColor; diff --git a/src/game/java/net/minecraft/block/BlockOldLeaf.java b/src/game/java/net/minecraft/block/BlockOldLeaf.java index 00f4c33f..ea9a19b7 100644 --- a/src/game/java/net/minecraft/block/BlockOldLeaf.java +++ b/src/game/java/net/minecraft/block/BlockOldLeaf.java @@ -20,22 +20,25 @@ import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,11 +46,6 @@ import net.minecraft.world.World; public class BlockOldLeaf extends BlockLeaves { public static PropertyEnum VARIANT; - public BlockOldLeaf() { - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.OAK) - .withProperty(CHECK_DECAY, Boolean.valueOf(true)).withProperty(DECAYABLE, Boolean.valueOf(true))); - } - public static void bootstrapStates() { VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class, new Predicate() { public boolean apply(BlockPlanks.EnumType blockplanks$enumtype) { @@ -56,15 +54,9 @@ public class BlockOldLeaf extends BlockLeaves { }); } - public int getRenderColor(IBlockState iblockstate) { - if (iblockstate.getBlock() != this) { - return super.getRenderColor(iblockstate); - } else { - BlockPlanks.EnumType blockplanks$enumtype = (BlockPlanks.EnumType) iblockstate.getValue(VARIANT); - return blockplanks$enumtype == BlockPlanks.EnumType.SPRUCE ? ColorizerFoliage.getFoliageColorPine() - : (blockplanks$enumtype == BlockPlanks.EnumType.BIRCH ? ColorizerFoliage.getFoliageColorBirch() - : super.getRenderColor(iblockstate)); - } + public BlockOldLeaf() { + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.OAK) + .withProperty(CHECK_DECAY, Boolean.valueOf(true)).withProperty(DECAYABLE, Boolean.valueOf(true))); } public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int i) { @@ -83,27 +75,8 @@ public class BlockOldLeaf extends BlockLeaves { return super.colorMultiplier(iblockaccess, blockpos, i); } - protected void dropApple(World world, BlockPos blockpos, IBlockState iblockstate, int i) { - if (iblockstate.getValue(VARIANT) == BlockPlanks.EnumType.OAK && world.rand.nextInt(i) == 0) { - spawnAsEntity(world, blockpos, new ItemStack(Items.apple, 1, 0)); - } - - } - - protected int getSaplingDropChance(IBlockState iblockstate) { - return iblockstate.getValue(VARIANT) == BlockPlanks.EnumType.JUNGLE ? 40 - : super.getSaplingDropChance(iblockstate); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.OAK.getMetadata())); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.SPRUCE.getMetadata())); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.BIRCH.getMetadata())); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.JUNGLE.getMetadata())); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT, CHECK_DECAY, DECAYABLE }); } protected ItemStack createStackedBlock(IBlockState iblockstate) { @@ -111,17 +84,24 @@ public class BlockOldLeaf extends BlockLeaves { ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata()); } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, this.getWoodType(i)) - .withProperty(DECAYABLE, Boolean.valueOf((i & 4) == 0)) - .withProperty(CHECK_DECAY, Boolean.valueOf((i & 8) > 0)); + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); } - /**+ - * Convert the BlockState into the correct metadata value + protected void dropApple(World world, BlockPos blockpos, IBlockState iblockstate, int i) { + if (iblockstate.getValue(VARIANT) == BlockPlanks.EnumType.OAK && world.rand.nextInt(i) == 0) { + spawnAsEntity(world, blockpos, new ItemStack(Items.apple, 1, 0)); + } + + } + + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -137,24 +117,46 @@ public class BlockOldLeaf extends BlockLeaves { return i; } + public int getRenderColor(IBlockState iblockstate) { + if (iblockstate.getBlock() != this) { + return super.getRenderColor(iblockstate); + } else { + BlockPlanks.EnumType blockplanks$enumtype = (BlockPlanks.EnumType) iblockstate.getValue(VARIANT); + return blockplanks$enumtype == BlockPlanks.EnumType.SPRUCE ? ColorizerFoliage.getFoliageColorPine() + : (blockplanks$enumtype == BlockPlanks.EnumType.BIRCH ? ColorizerFoliage.getFoliageColorBirch() + : super.getRenderColor(iblockstate)); + } + } + + protected int getSaplingDropChance(IBlockState iblockstate) { + return iblockstate.getValue(VARIANT) == BlockPlanks.EnumType.JUNGLE ? 40 + : super.getSaplingDropChance(iblockstate); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, this.getWoodType(i)) + .withProperty(DECAYABLE, Boolean.valueOf((i & 4) == 0)) + .withProperty(CHECK_DECAY, Boolean.valueOf((i & 8) > 0)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.OAK.getMetadata())); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.SPRUCE.getMetadata())); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.BIRCH.getMetadata())); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.JUNGLE.getMetadata())); + } + public BlockPlanks.EnumType getWoodType(int i) { return BlockPlanks.EnumType.byMetadata((i & 3) % 4); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT, CHECK_DECAY, DECAYABLE }); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, TileEntity tileentity) { if (!world.isRemote && entityplayer.getCurrentEquippedItem() != null diff --git a/src/game/java/net/minecraft/block/BlockOldLog.java b/src/game/java/net/minecraft/block/BlockOldLog.java index 711aec54..b0fc8fdb 100644 --- a/src/game/java/net/minecraft/block/BlockOldLog.java +++ b/src/game/java/net/minecraft/block/BlockOldLog.java @@ -13,22 +13,25 @@ import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,11 +39,6 @@ import net.minecraft.item.ItemStack; public class BlockOldLog extends BlockLog { public static PropertyEnum VARIANT; - public BlockOldLog() { - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.OAK) - .withProperty(LOG_AXIS, BlockLog.EnumAxis.Y)); - } - public static void bootstrapStates() { VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class, new Predicate() { public boolean apply(BlockPlanks.EnumType blockplanks$enumtype) { @@ -49,8 +47,31 @@ public class BlockOldLog extends BlockLog { }); } - /**+ - * Get the MapColor for this Block and the given BlockState + public BlockOldLog() { + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.OAK) + .withProperty(LOG_AXIS, BlockLog.EnumAxis.Y)); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT, LOG_AXIS }); + } + + protected ItemStack createStackedBlock(IBlockState iblockstate) { + return new ItemStack(Item.getItemFromBlock(this), 1, + ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata()); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState iblockstate) { BlockPlanks.EnumType blockplanks$enumtype = (BlockPlanks.EnumType) iblockstate.getValue(VARIANT); @@ -75,19 +96,28 @@ public class BlockOldLog extends BlockLog { } } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Convert the BlockState into the correct metadata value */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.OAK.getMetadata())); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.SPRUCE.getMetadata())); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.BIRCH.getMetadata())); - list.add(new ItemStack(item, 1, BlockPlanks.EnumType.JUNGLE.getMetadata())); + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + switch ((BlockLog.EnumAxis) iblockstate.getValue(LOG_AXIS)) { + case X: + i |= 4; + break; + case Z: + i |= 8; + break; + case NONE: + i |= 12; + } + + return i; } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Convert the given metadata into a BlockState for this Block */ public IBlockState getStateFromMeta(int i) { IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, @@ -109,42 +139,14 @@ public class BlockOldLog extends BlockLog { return iblockstate; } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - switch ((BlockLog.EnumAxis) iblockstate.getValue(LOG_AXIS)) { - case X: - i |= 4; - break; - case Z: - i |= 8; - break; - case NONE: - i |= 12; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT, LOG_AXIS }); - } - - protected ItemStack createStackedBlock(IBlockState iblockstate) { - return new ItemStack(Item.getItemFromBlock(this), 1, - ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata()); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.OAK.getMetadata())); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.SPRUCE.getMetadata())); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.BIRCH.getMetadata())); + list.add(new ItemStack(item, 1, BlockPlanks.EnumType.JUNGLE.getMetadata())); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockOre.java b/src/game/java/net/minecraft/block/BlockOre.java index 03f6153b..fe9c73d9 100644 --- a/src/game/java/net/minecraft/block/BlockOre.java +++ b/src/game/java/net/minecraft/block/BlockOre.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -14,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,43 +46,17 @@ public class BlockOre extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return this == Blocks.coal_ore ? Items.coal - : (this == Blocks.diamond_ore ? Items.diamond - : (this == Blocks.lapis_ore ? Items.dye - : (this == Blocks.emerald_ore ? Items.emerald - : (this == Blocks.quartz_ore ? Items.quartz : Item.getItemFromBlock(this))))); + public int damageDropped(IBlockState var1) { + return this == Blocks.lapis_ore ? EnumDyeColor.BLUE.getDyeDamage() : 0; } - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom random) { - return this == Blocks.lapis_ore ? 4 + random.nextInt(5) : 1; - } - - /**+ - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { - if (i > 0 && Item.getItemFromBlock(this) != this - .getItemDropped((IBlockState) this.getBlockState().getValidStates().iterator().next(), random, i)) { - int j = random.nextInt(i + 2) - 1; - if (j < 0) { - j = 0; - } - - return this.quantityDropped(random) * (j + 1); - } else { - return this.quantityDropped(random); - } - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); @@ -107,13 +83,40 @@ public class BlockOre extends Block { return 0; } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + Get the Item that this Block should drop when harvested. */ - public int damageDropped(IBlockState var1) { - return this == Blocks.lapis_ore ? EnumDyeColor.BLUE.getDyeDamage() : 0; + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return this == Blocks.coal_ore ? Items.coal + : (this == Blocks.diamond_ore ? Items.diamond + : (this == Blocks.lapis_ore ? Items.dye + : (this == Blocks.emerald_ore ? Items.emerald + : (this == Blocks.quartz_ore ? Items.quartz + : (this == Blocks.uranium_ore ? Items.uranium_crystal + : Item.getItemFromBlock(this)))))); + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom random) { + return this == Blocks.lapis_ore ? 4 + random.nextInt(5) : 1; + } + + /** + * + Get the quantity dropped based on the given fortune level + */ + public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { + if (i > 0 && Item.getItemFromBlock(this) != this + .getItemDropped((IBlockState) this.getBlockState().getValidStates().iterator().next(), random, i)) { + int j = random.nextInt(i + 2) - 1; + if (j < 0) { + j = 0; + } + + return this.quantityDropped(random) * (j + 1); + } else { + return this.quantityDropped(random); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPackedIce.java b/src/game/java/net/minecraft/block/BlockPackedIce.java index 9e4cc7b8..bba0500b 100644 --- a/src/game/java/net/minecraft/block/BlockPackedIce.java +++ b/src/game/java/net/minecraft/block/BlockPackedIce.java @@ -1,26 +1,28 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +34,8 @@ public class BlockPackedIce extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 0; diff --git a/src/game/java/net/minecraft/block/BlockPane.java b/src/game/java/net/minecraft/block/BlockPane.java index f60ea493..3f588a52 100644 --- a/src/game/java/net/minecraft/block/BlockPane.java +++ b/src/game/java/net/minecraft/block/BlockPane.java @@ -1,6 +1,7 @@ package net.minecraft.block; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; import net.minecraft.block.material.Material; @@ -19,22 +20,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,53 +59,9 @@ public class BlockPane extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - return iblockstate - .withProperty(NORTH, - Boolean.valueOf( - this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.north()).getBlock()))) - .withProperty(SOUTH, - Boolean.valueOf( - this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.south()).getBlock()))) - .withProperty(WEST, - Boolean.valueOf( - this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.west()).getBlock()))) - .withProperty(EAST, Boolean - .valueOf(this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.east()).getBlock()))); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom random, int i) { - return !this.canDrop ? null : super.getItemDropped(iblockstate, random, i); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - return iblockaccess.getBlockState(blockpos).getBlock() == this ? false - : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -137,11 +97,70 @@ public class BlockPane extends Block { } - /**+ - * Sets the block's bounds for rendering it as an item + public final boolean canPaneConnectToBlock(Block blockIn) { + return blockIn.isFullBlock() || blockIn == this || blockIn == Blocks.glass || blockIn == Blocks.stained_glass + || blockIn == Blocks.stained_glass_pane || blockIn instanceof BlockPane; + } + + protected boolean canSilkHarvest() { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { NORTH, EAST, WEST, SOUTH }); + } + + public boolean eaglerShadersShouldRenderGlassHighlights() { + return this == Blocks.glass_pane && DeferredStateManager.isRenderingGlassHighlights(); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ - public void setBlockBoundsForItemRender() { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + return iblockstate + .withProperty(NORTH, + Boolean.valueOf( + this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.north()).getBlock()))) + .withProperty(SOUTH, + Boolean.valueOf( + this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.south()).getBlock()))) + .withProperty(WEST, + Boolean.valueOf( + this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.west()).getBlock()))) + .withProperty(EAST, Boolean + .valueOf(this.canPaneConnectToBlock(iblockaccess.getBlockState(blockpos.east()).getBlock()))); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT_MIPPED; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom random, int i) { + return !this.canDrop ? null : super.getItemDropped(iblockstate, random, i); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState var1) { + return 0; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { @@ -178,31 +197,15 @@ public class BlockPane extends Block { this.setBlockBounds(f, 0.0F, f2, f1, 1.0F, f3); } - public final boolean canPaneConnectToBlock(Block blockIn) { - return blockIn.isFullBlock() || blockIn == this || blockIn == Blocks.glass || blockIn == Blocks.stained_glass - || blockIn == Blocks.stained_glass_pane || blockIn instanceof BlockPane; - } - - protected boolean canSilkHarvest() { - return true; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT_MIPPED; - } - - public boolean eaglerShadersShouldRenderGlassHighlights() { - return this == Blocks.glass_pane && DeferredStateManager.isRenderingGlassHighlights(); - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Sets the block's bounds for rendering it as an item */ - public int getMetaFromState(IBlockState var1) { - return 0; + public void setBlockBoundsForItemRender() { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { NORTH, EAST, WEST, SOUTH }); + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + return iblockaccess.getBlockState(blockpos).getBlock() == this ? false + : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPistonBase.java b/src/game/java/net/minecraft/block/BlockPistonBase.java index eef10a5f..a26432bd 100644 --- a/src/game/java/net/minecraft/block/BlockPistonBase.java +++ b/src/game/java/net/minecraft/block/BlockPistonBase.java @@ -23,22 +23,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,257 +49,6 @@ import net.minecraft.world.World; public class BlockPistonBase extends Block { public static final PropertyDirection FACING = PropertyDirection.create("facing"); public static final PropertyBool EXTENDED = PropertyBool.create("extended"); - private final boolean isSticky; - - public BlockPistonBase(boolean isSticky) { - super(Material.piston); - this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH) - .withProperty(EXTENDED, Boolean.valueOf(false))); - this.isSticky = isSticky; - this.setStepSound(soundTypePiston); - this.setHardness(0.5F); - this.setCreativeTab(CreativeTabs.tabRedstone); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, - EntityLivingBase entitylivingbase, ItemStack var5) { - world.setBlockState(blockpos, - iblockstate.withProperty(FACING, getFacingFromEntity(world, blockpos, entitylivingbase)), 2); - if (!world.isRemote) { - this.checkForMove(world, blockpos, iblockstate); - } - - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (!world.isRemote) { - this.checkForMove(world, blockpos, iblockstate); - } - - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - if (!world.isRemote && world.getTileEntity(blockpos) == null) { - this.checkForMove(world, blockpos, iblockstate); - } - - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing var3, float var4, float var5, - float var6, int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, getFacingFromEntity(world, blockpos, entitylivingbase)) - .withProperty(EXTENDED, Boolean.valueOf(false)); - } - - private void checkForMove(World worldIn, BlockPos pos, IBlockState state) { - EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); - boolean flag = this.shouldBeExtended(worldIn, pos, enumfacing); - if (flag && !((Boolean) state.getValue(EXTENDED)).booleanValue()) { - if ((new BlockPistonStructureHelper(worldIn, pos, enumfacing, true)).canMove()) { - worldIn.addBlockEvent(pos, this, 0, enumfacing.getIndex()); - } - } else if (!flag && ((Boolean) state.getValue(EXTENDED)).booleanValue()) { - worldIn.setBlockState(pos, state.withProperty(EXTENDED, Boolean.valueOf(false)), 2); - worldIn.addBlockEvent(pos, this, 1, enumfacing.getIndex()); - } - - } - - private boolean shouldBeExtended(World worldIn, BlockPos pos, EnumFacing facing) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (enumfacing != facing && worldIn.isSidePowered(pos.offset(enumfacing), enumfacing)) { - return true; - } - } - - if (worldIn.isSidePowered(pos, EnumFacing.DOWN)) { - return true; - } else { - BlockPos blockpos = pos.up(); - - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing1 = facings[i]; - if (enumfacing1 != EnumFacing.DOWN - && worldIn.isSidePowered(blockpos.offset(enumfacing1), enumfacing1)) { - return true; - } - } - - return false; - } - } - - /**+ - * Called on both Client and Server when World#addBlockEvent is - * called - */ - public boolean onBlockEventReceived(World world, BlockPos blockpos, IBlockState iblockstate, int i, int j) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (!world.isRemote) { - boolean flag = this.shouldBeExtended(world, blockpos, enumfacing); - if (flag && i == 1) { - world.setBlockState(blockpos, iblockstate.withProperty(EXTENDED, Boolean.valueOf(true)), 2); - return false; - } - - if (!flag && i == 0) { - return false; - } - } - - if (i == 0) { - if (!this.doMove(world, blockpos, enumfacing, true)) { - return false; - } - - world.setBlockState(blockpos, iblockstate.withProperty(EXTENDED, Boolean.valueOf(true)), 2); - world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, - (double) blockpos.getZ() + 0.5D, "tile.piston.out", 0.5F, world.rand.nextFloat() * 0.25F + 0.6F); - } else if (i == 1) { - TileEntity tileentity1 = world.getTileEntity(blockpos.offset(enumfacing)); - if (tileentity1 instanceof TileEntityPiston) { - ((TileEntityPiston) tileentity1).clearPistonTileEntity(); - } - - world.setBlockState(blockpos, - Blocks.piston_extension.getDefaultState().withProperty(BlockPistonMoving.FACING, enumfacing) - .withProperty(BlockPistonMoving.TYPE, - this.isSticky ? BlockPistonExtension.EnumPistonType.STICKY - : BlockPistonExtension.EnumPistonType.DEFAULT), - 3); - world.setTileEntity(blockpos, - BlockPistonMoving.newTileEntity(this.getStateFromMeta(j), enumfacing, false, true)); - if (this.isSticky) { - BlockPos blockpos1 = blockpos.add(enumfacing.getFrontOffsetX() * 2, enumfacing.getFrontOffsetY() * 2, - enumfacing.getFrontOffsetZ() * 2); - Block block = world.getBlockState(blockpos1).getBlock(); - boolean flag1 = false; - if (block == Blocks.piston_extension) { - TileEntity tileentity = world.getTileEntity(blockpos1); - if (tileentity instanceof TileEntityPiston) { - TileEntityPiston tileentitypiston = (TileEntityPiston) tileentity; - if (tileentitypiston.getFacing() == enumfacing && tileentitypiston.isExtending()) { - tileentitypiston.clearPistonTileEntity(); - flag1 = true; - } - } - } - - if (!flag1 && block.getMaterial() != Material.air - && canPush(block, world, blockpos1, enumfacing.getOpposite(), false) - && (block.getMobilityFlag() == 0 || block == Blocks.piston || block == Blocks.sticky_piston)) { - this.doMove(world, blockpos, enumfacing, false); - } - } else { - world.setBlockToAir(blockpos.offset(enumfacing)); - } - - world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, - (double) blockpos.getZ() + 0.5D, "tile.piston.in", 0.5F, world.rand.nextFloat() * 0.15F + 0.6F); - } - - return true; - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - IBlockState iblockstate = iblockaccess.getBlockState(blockpos); - if (iblockstate.getBlock() == this && ((Boolean) iblockstate.getValue(EXTENDED)).booleanValue()) { - float f = 0.25F; - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (enumfacing != null) { - switch (enumfacing) { - case DOWN: - this.setBlockBounds(0.0F, 0.25F, 0.0F, 1.0F, 1.0F, 1.0F); - break; - case UP: - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); - break; - case NORTH: - this.setBlockBounds(0.0F, 0.0F, 0.25F, 1.0F, 1.0F, 1.0F); - break; - case SOUTH: - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.75F); - break; - case WEST: - this.setBlockBounds(0.25F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - break; - case EAST: - this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.75F, 1.0F, 1.0F); - } - } - } else { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - } - - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. - */ - public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, - AxisAlignedBB axisalignedbb, List list, Entity entity) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); - } - - public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { - this.setBlockBoundsBasedOnState(world, blockpos); - return super.getCollisionBoundingBox(world, blockpos, iblockstate); - } - - public boolean isFullCube() { - return false; - } - - public static EnumFacing getFacing(int meta) { - int i = meta & 7; - return i > 5 ? null : EnumFacing.getFront(i); - } - - public static EnumFacing getFacingFromEntity(World worldIn, BlockPos clickedBlock, EntityLivingBase entityIn) { - if (MathHelper.abs((float) entityIn.posX - (float) clickedBlock.getX()) < 2.0F - && MathHelper.abs((float) entityIn.posZ - (float) clickedBlock.getZ()) < 2.0F) { - double d0 = entityIn.posY + (double) entityIn.getEyeHeight(); - if (d0 - (double) clickedBlock.getY() > 2.0D) { - return EnumFacing.UP; - } - - if ((double) clickedBlock.getY() - d0 > 0.0D) { - return EnumFacing.DOWN; - } - } - - return entityIn.getHorizontalFacing().getOpposite(); - } public static boolean canPush(Block blockIn, World worldIn, BlockPos pos, EnumFacing direction, boolean allowDestroy) { @@ -336,6 +88,67 @@ public class BlockPistonBase extends Block { } } + public static EnumFacing getFacing(int meta) { + int i = meta & 7; + return i > 5 ? null : EnumFacing.getFront(i); + } + + public static EnumFacing getFacingFromEntity(World worldIn, BlockPos clickedBlock, EntityLivingBase entityIn) { + if (MathHelper.abs((float) entityIn.posX - (float) clickedBlock.getX()) < 2.0F + && MathHelper.abs((float) entityIn.posZ - (float) clickedBlock.getZ()) < 2.0F) { + double d0 = entityIn.posY + (double) entityIn.getEyeHeight(); + if (d0 - (double) clickedBlock.getY() > 2.0D) { + return EnumFacing.UP; + } + + if ((double) clickedBlock.getY() - d0 > 0.0D) { + return EnumFacing.DOWN; + } + } + + return entityIn.getHorizontalFacing().getOpposite(); + } + + private final boolean isSticky; + + public BlockPistonBase(boolean isSticky) { + super(Material.piston); + this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH) + .withProperty(EXTENDED, Boolean.valueOf(false))); + this.isSticky = isSticky; + this.setStepSound(soundTypePiston); + this.setHardness(0.5F); + this.setCreativeTab(CreativeTabs.tabRedstone); + } + + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. + */ + public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, + AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); + } + + private void checkForMove(World worldIn, BlockPos pos, IBlockState state) { + EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); + boolean flag = this.shouldBeExtended(worldIn, pos, enumfacing); + if (flag && !((Boolean) state.getValue(EXTENDED)).booleanValue()) { + if ((new BlockPistonStructureHelper(worldIn, pos, enumfacing, true)).canMove()) { + worldIn.addBlockEvent(pos, this, 0, enumfacing.getIndex()); + } + } else if (!flag && ((Boolean) state.getValue(EXTENDED)).booleanValue()) { + worldIn.setBlockState(pos, state.withProperty(EXTENDED, Boolean.valueOf(false)), 2); + worldIn.addBlockEvent(pos, this, 1, enumfacing.getIndex()); + } + + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, EXTENDED }); + } + private boolean doMove(World worldIn, BlockPos pos, EnumFacing direction, boolean extending) { if (!extending) { worldIn.setBlockToAir(pos.offset(direction)); @@ -409,24 +222,13 @@ public class BlockPistonBase extends Block { } } - /**+ - * Possibly modify the given BlockState before rendering it on - * an Entity (Minecarts, Endermen, ...) - */ - public IBlockState getStateForEntityRender(IBlockState var1) { - return this.getDefaultState().withProperty(FACING, EnumFacing.UP); + public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { + this.setBlockBoundsBasedOnState(world, blockpos); + return super.getCollisionBoundingBox(world, blockpos, iblockstate); } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(EXTENDED, - Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -438,7 +240,208 @@ public class BlockPistonBase extends Block { return i; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, EXTENDED }); + /** + * + Possibly modify the given BlockState before rendering it on an Entity + * (Minecarts, Endermen, ...) + */ + public IBlockState getStateForEntityRender(IBlockState var1) { + return this.getDefaultState().withProperty(FACING, EnumFacing.UP); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(EXTENDED, + Boolean.valueOf((i & 8) > 0)); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + if (!world.isRemote && world.getTileEntity(blockpos) == null) { + this.checkForMove(world, blockpos, iblockstate); + } + + } + + /** + * + Called on both Client and Server when World#addBlockEvent is called + */ + public boolean onBlockEventReceived(World world, BlockPos blockpos, IBlockState iblockstate, int i, int j) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (!world.isRemote) { + boolean flag = this.shouldBeExtended(world, blockpos, enumfacing); + if (flag && i == 1) { + world.setBlockState(blockpos, iblockstate.withProperty(EXTENDED, Boolean.valueOf(true)), 2); + return false; + } + + if (!flag && i == 0) { + return false; + } + } + + if (i == 0) { + if (!this.doMove(world, blockpos, enumfacing, true)) { + return false; + } + + world.setBlockState(blockpos, iblockstate.withProperty(EXTENDED, Boolean.valueOf(true)), 2); + world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, + (double) blockpos.getZ() + 0.5D, "tile.piston.out", 0.5F, world.rand.nextFloat() * 0.25F + 0.6F); + } else if (i == 1) { + TileEntity tileentity1 = world.getTileEntity(blockpos.offset(enumfacing)); + if (tileentity1 instanceof TileEntityPiston) { + ((TileEntityPiston) tileentity1).clearPistonTileEntity(); + } + + world.setBlockState(blockpos, + Blocks.piston_extension.getDefaultState().withProperty(BlockPistonMoving.FACING, enumfacing) + .withProperty(BlockPistonMoving.TYPE, + this.isSticky ? BlockPistonExtension.EnumPistonType.STICKY + : BlockPistonExtension.EnumPistonType.DEFAULT), + 3); + world.setTileEntity(blockpos, + BlockPistonMoving.newTileEntity(this.getStateFromMeta(j), enumfacing, false, true)); + if (this.isSticky) { + BlockPos blockpos1 = blockpos.add(enumfacing.getFrontOffsetX() * 2, enumfacing.getFrontOffsetY() * 2, + enumfacing.getFrontOffsetZ() * 2); + Block block = world.getBlockState(blockpos1).getBlock(); + boolean flag1 = false; + if (block == Blocks.piston_extension) { + TileEntity tileentity = world.getTileEntity(blockpos1); + if (tileentity instanceof TileEntityPiston) { + TileEntityPiston tileentitypiston = (TileEntityPiston) tileentity; + if (tileentitypiston.getFacing() == enumfacing && tileentitypiston.isExtending()) { + tileentitypiston.clearPistonTileEntity(); + flag1 = true; + } + } + } + + if (!flag1 && block.getMaterial() != Material.air + && canPush(block, world, blockpos1, enumfacing.getOpposite(), false) + && (block.getMobilityFlag() == 0 || block == Blocks.piston || block == Blocks.sticky_piston)) { + this.doMove(world, blockpos, enumfacing, false); + } + } else { + world.setBlockToAir(blockpos.offset(enumfacing)); + } + + world.playSoundEffect((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, + (double) blockpos.getZ() + 0.5D, "tile.piston.in", 0.5F, world.rand.nextFloat() * 0.15F + 0.6F); + } + + return true; + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing var3, float var4, float var5, + float var6, int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, getFacingFromEntity(world, blockpos, entitylivingbase)) + .withProperty(EXTENDED, Boolean.valueOf(false)); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, + EntityLivingBase entitylivingbase, ItemStack var5) { + world.setBlockState(blockpos, + iblockstate.withProperty(FACING, getFacingFromEntity(world, blockpos, entitylivingbase)), 2); + if (!world.isRemote) { + this.checkForMove(world, blockpos, iblockstate); + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!world.isRemote) { + this.checkForMove(world, blockpos, iblockstate); + } + + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + IBlockState iblockstate = iblockaccess.getBlockState(blockpos); + if (iblockstate.getBlock() == this && ((Boolean) iblockstate.getValue(EXTENDED)).booleanValue()) { + float f = 0.25F; + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (enumfacing != null) { + switch (enumfacing) { + case DOWN: + this.setBlockBounds(0.0F, 0.25F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + case UP: + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); + break; + case NORTH: + this.setBlockBounds(0.0F, 0.0F, 0.25F, 1.0F, 1.0F, 1.0F); + break; + case SOUTH: + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.75F); + break; + case WEST: + this.setBlockBounds(0.25F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + break; + case EAST: + this.setBlockBounds(0.0F, 0.0F, 0.0F, 0.75F, 1.0F, 1.0F); + } + } + } else { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + } + + private boolean shouldBeExtended(World worldIn, BlockPos pos, EnumFacing facing) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (enumfacing != facing && worldIn.isSidePowered(pos.offset(enumfacing), enumfacing)) { + return true; + } + } + + if (worldIn.isSidePowered(pos, EnumFacing.DOWN)) { + return true; + } else { + BlockPos blockpos = pos.up(); + + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing1 = facings[i]; + if (enumfacing1 != EnumFacing.DOWN + && worldIn.isSidePowered(blockpos.offset(enumfacing1), enumfacing1)) { + return true; + } + } + + return false; + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPistonExtension.java b/src/game/java/net/minecraft/block/BlockPistonExtension.java index c1ba5dfe..42029a4a 100644 --- a/src/game/java/net/minecraft/block/BlockPistonExtension.java +++ b/src/game/java/net/minecraft/block/BlockPistonExtension.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -21,31 +21,63 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPistonExtension extends Block { + public static enum EnumPistonType implements IStringSerializable { + DEFAULT("normal"), STICKY("sticky"); + + private final String VARIANT; + + private EnumPistonType(String name) { + this.VARIANT = name; + } + + public String getName() { + return this.VARIANT; + } + + public String toString() { + return this.VARIANT; + } + } + public static final PropertyDirection FACING = PropertyDirection.create("facing"); public static PropertyEnum TYPE; + public static final PropertyBool SHORT = PropertyBool.create("short"); + public static void bootstrapStates() { + TYPE = PropertyEnum.create("type", + BlockPistonExtension.EnumPistonType.class); + } + + public static EnumFacing getFacing(int meta) { + int i = meta & 7; + return i > 5 ? null : EnumFacing.getFront(i); + } + public BlockPistonExtension() { super(Material.piston); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH) @@ -55,72 +87,9 @@ public class BlockPistonExtension extends Block { this.setHardness(0.5F); } - public static void bootstrapStates() { - TYPE = PropertyEnum.create("type", - BlockPistonExtension.EnumPistonType.class); - } - - public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { - if (entityplayer.capabilities.isCreativeMode) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (enumfacing != null) { - BlockPos blockpos1 = blockpos.offset(enumfacing.getOpposite()); - Block block = world.getBlockState(blockpos1).getBlock(); - if (block == Blocks.piston || block == Blocks.sticky_piston) { - world.setBlockToAir(blockpos1); - } - } - } - - super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - super.breakBlock(world, blockpos, iblockstate); - EnumFacing enumfacing = ((EnumFacing) iblockstate.getValue(FACING)).getOpposite(); - blockpos = blockpos.offset(enumfacing); - IBlockState iblockstate1 = world.getBlockState(blockpos); - if ((iblockstate1.getBlock() == Blocks.piston || iblockstate1.getBlock() == Blocks.sticky_piston) - && ((Boolean) iblockstate1.getValue(BlockPistonBase.EXTENDED)).booleanValue()) { - iblockstate1.getBlock().dropBlockAsItem(world, blockpos, iblockstate1, 0); - world.setBlockToAir(blockpos); - } - - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean canPlaceBlockAt(World var1, BlockPos var2) { - return false; - } - - /**+ - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World var1, BlockPos var2, EnumFacing var3) { - return false; - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. */ public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, AxisAlignedBB axisalignedbb, List list, Entity entity) { @@ -159,10 +128,6 @@ public class BlockPistonExtension extends Block { } - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - this.applyHeadBounds(iblockaccess.getBlockState(blockpos)); - } - public void applyHeadBounds(IBlockState state) { float f = 0.25F; EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); @@ -190,8 +155,90 @@ public class BlockPistonExtension extends Block { } } - /**+ - * Called when a neighboring block changes. + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + super.breakBlock(world, blockpos, iblockstate); + EnumFacing enumfacing = ((EnumFacing) iblockstate.getValue(FACING)).getOpposite(); + blockpos = blockpos.offset(enumfacing); + IBlockState iblockstate1 = world.getBlockState(blockpos); + if ((iblockstate1.getBlock() == Blocks.piston || iblockstate1.getBlock() == Blocks.sticky_piston) + && ((Boolean) iblockstate1.getValue(BlockPistonBase.EXTENDED)).booleanValue()) { + iblockstate1.getBlock().dropBlockAsItem(world, blockpos, iblockstate1, 0); + world.setBlockToAir(blockpos); + } + + } + + public boolean canPlaceBlockAt(World var1, BlockPos var2) { + return false; + } + + /** + * + Check whether this Block can be placed on the given side + */ + public boolean canPlaceBlockOnSide(World var1, BlockPos var2, EnumFacing var3) { + return false; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, TYPE, SHORT }); + } + + public Item getItem(World world, BlockPos blockpos) { + return world.getBlockState(blockpos).getValue(TYPE) == BlockPistonExtension.EnumPistonType.STICKY + ? Item.getItemFromBlock(Blocks.sticky_piston) + : Item.getItemFromBlock(Blocks.piston); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + if (iblockstate.getValue(TYPE) == BlockPistonExtension.EnumPistonType.STICKY) { + i |= 8; + } + + return i; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(TYPE, + (i & 8) > 0 ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { + if (entityplayer.capabilities.isCreativeMode) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (enumfacing != null) { + BlockPos blockpos1 = blockpos.offset(enumfacing.getOpposite()); + Block block = world.getBlockState(blockpos1).getBlock(); + if (block == Blocks.piston || block == Blocks.sticky_piston) { + world.setBlockToAir(blockpos1); + } + } + } + + super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); @@ -205,61 +252,18 @@ public class BlockPistonExtension extends Block { } + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + this.applyHeadBounds(iblockaccess.getBlockState(blockpos)); + } + public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing var3) { return true; } - - public static EnumFacing getFacing(int meta) { - int i = meta & 7; - return i > 5 ? null : EnumFacing.getFront(i); - } - - public Item getItem(World world, BlockPos blockpos) { - return world.getBlockState(blockpos).getValue(TYPE) == BlockPistonExtension.EnumPistonType.STICKY - ? Item.getItemFromBlock(Blocks.sticky_piston) - : Item.getItemFromBlock(Blocks.piston); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, getFacing(i)).withProperty(TYPE, - (i & 8) > 0 ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - if (iblockstate.getValue(TYPE) == BlockPistonExtension.EnumPistonType.STICKY) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, TYPE, SHORT }); - } - - public static enum EnumPistonType implements IStringSerializable { - DEFAULT("normal"), STICKY("sticky"); - - private final String VARIANT; - - private EnumPistonType(String name) { - this.VARIANT = name; - } - - public String toString() { - return this.VARIANT; - } - - public String getName() { - return this.VARIANT; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPistonMoving.java b/src/game/java/net/minecraft/block/BlockPistonMoving.java index 4fb2f34c..d8fae553 100644 --- a/src/game/java/net/minecraft/block/BlockPistonMoving.java +++ b/src/game/java/net/minecraft/block/BlockPistonMoving.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -21,22 +20,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,30 +47,22 @@ public class BlockPistonMoving extends BlockContainer { public static final PropertyDirection FACING = BlockPistonExtension.FACING; public static PropertyEnum TYPE; - public BlockPistonMoving() { - super(Material.piston); - this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH).withProperty(TYPE, - BlockPistonExtension.EnumPistonType.DEFAULT)); - this.setHardness(-1.0F); - } - public static void bootstrapStates() { TYPE = BlockPistonExtension.TYPE; } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return null; - } - public static TileEntity newTileEntity(IBlockState state, EnumFacing facing, boolean extending, boolean renderHead) { return new TileEntityPiston(state, facing, extending, renderHead); } + public BlockPistonMoving() { + super(Material.piston); + this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH).withProperty(TYPE, + BlockPistonExtension.EnumPistonType.DEFAULT)); + this.setHardness(-1.0F); + } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { TileEntity tileentity = world.getTileEntity(blockpos); if (tileentity instanceof TileEntityPiston) { @@ -83,57 +77,35 @@ public class BlockPistonMoving extends BlockContainer { return false; } - /**+ - * Check whether this Block can be placed on the given side + /** + * + Check whether this Block can be placed on the given side */ public boolean canPlaceBlockOnSide(World var1, BlockPos var2, EnumFacing var3) { return false; } - /**+ - * Called when a player destroys this Block + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. */ - public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { - BlockPos blockpos1 = blockpos.offset(((EnumFacing) iblockstate.getValue(FACING)).getOpposite()); - IBlockState iblockstate1 = world.getBlockState(blockpos1); - if (iblockstate1.getBlock() instanceof BlockPistonBase - && ((Boolean) iblockstate1.getValue(BlockPistonBase.EXTENDED)).booleanValue()) { - world.setBlockToAir(blockpos1); - } - - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer var4, - EnumFacing var5, float var6, float var7, float var8) { - if (!world.isRemote && world.getTileEntity(blockpos) == null) { - world.setBlockToAir(blockpos); - return true; - } else { - return false; - } - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + public MovingObjectPosition collisionRayTrace(World var1, BlockPos var2, Vec3 var3, Vec3 var4) { return null; } - /**+ - * Spawns this Block's drops into the World as EntityItems. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, TYPE }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return null; + } + + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState var3, float var4, int var5) { if (!world.isRemote) { @@ -145,68 +117,6 @@ public class BlockPistonMoving extends BlockContainer { } } - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World var1, BlockPos var2, Vec3 var3, Vec3 var4) { - return null; - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { - if (!world.isRemote) { - world.getTileEntity(blockpos); - } - } - - public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState var3) { - TileEntityPiston tileentitypiston = this.getTileEntity(world, blockpos); - if (tileentitypiston == null) { - return null; - } else { - float f = tileentitypiston.getProgress(0.0F); - if (tileentitypiston.isExtending()) { - f = 1.0F - f; - } - - return this.getBoundingBox(world, blockpos, tileentitypiston.getPistonState(), f, - tileentitypiston.getFacing()); - } - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - TileEntityPiston tileentitypiston = this.getTileEntity(iblockaccess, blockpos); - if (tileentitypiston != null) { - IBlockState iblockstate = tileentitypiston.getPistonState(); - Block block = iblockstate.getBlock(); - if (block == this || block.getMaterial() == Material.air) { - return; - } - - float f = tileentitypiston.getProgress(0.0F); - if (tileentitypiston.isExtending()) { - f = 1.0F - f; - } - - block.setBlockBoundsBasedOnState(iblockaccess, blockpos); - if (block == Blocks.piston || block == Blocks.sticky_piston) { - f = 0.0F; - } - - EnumFacing enumfacing = tileentitypiston.getFacing(); - this.minX = block.getBlockBoundsMinX() - (double) ((float) enumfacing.getFrontOffsetX() * f); - this.minY = block.getBlockBoundsMinY() - (double) ((float) enumfacing.getFrontOffsetY() * f); - this.minZ = block.getBlockBoundsMinZ() - (double) ((float) enumfacing.getFrontOffsetZ() * f); - this.maxX = block.getBlockBoundsMaxX() - (double) ((float) enumfacing.getFrontOffsetX() * f); - this.maxY = block.getBlockBoundsMaxY() - (double) ((float) enumfacing.getFrontOffsetY() * f); - this.maxZ = block.getBlockBoundsMaxZ() - (double) ((float) enumfacing.getFrontOffsetZ() * f); - } - - } - public AxisAlignedBB getBoundingBox(World worldIn, BlockPos pos, IBlockState extendingBlock, float progress, EnumFacing direction) { if (extendingBlock.getBlock() != this && extendingBlock.getBlock().getMaterial() != Material.air) { @@ -246,25 +156,34 @@ public class BlockPistonMoving extends BlockContainer { } } - private TileEntityPiston getTileEntity(IBlockAccess worldIn, BlockPos pos) { - TileEntity tileentity = worldIn.getTileEntity(pos); - return tileentity instanceof TileEntityPiston ? (TileEntityPiston) tileentity : null; + public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState var3) { + TileEntityPiston tileentitypiston = this.getTileEntity(world, blockpos); + if (tileentitypiston == null) { + return null; + } else { + float f = tileentitypiston.getProgress(0.0F); + if (tileentitypiston.isExtending()) { + f = 1.0F - f; + } + + return this.getBoundingBox(world, blockpos, tileentitypiston.getPistonState(), f, + tileentitypiston.getFacing()); + } } public Item getItem(World var1, BlockPos var2) { return null; } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Get the Item that this Block should drop when harvested. */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, BlockPistonExtension.getFacing(i)).withProperty(TYPE, - (i & 8) > 0 ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -276,7 +195,90 @@ public class BlockPistonMoving extends BlockContainer { return i; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, TYPE }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, BlockPistonExtension.getFacing(i)).withProperty(TYPE, + (i & 8) > 0 ? BlockPistonExtension.EnumPistonType.STICKY : BlockPistonExtension.EnumPistonType.DEFAULT); + } + + private TileEntityPiston getTileEntity(IBlockAccess worldIn, BlockPos pos) { + TileEntity tileentity = worldIn.getTileEntity(pos); + return tileentity instanceof TileEntityPiston ? (TileEntityPiston) tileentity : null; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer var4, + EnumFacing var5, float var6, float var7, float var8) { + if (!world.isRemote && world.getTileEntity(blockpos) == null) { + world.setBlockToAir(blockpos); + return true; + } else { + return false; + } + } + + /** + * + Called when a player destroys this Block + */ + public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { + BlockPos blockpos1 = blockpos.offset(((EnumFacing) iblockstate.getValue(FACING)).getOpposite()); + IBlockState iblockstate1 = world.getBlockState(blockpos1); + if (iblockstate1.getBlock() instanceof BlockPistonBase + && ((Boolean) iblockstate1.getValue(BlockPistonBase.EXTENDED)).booleanValue()) { + world.setBlockToAir(blockpos1); + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { + if (!world.isRemote) { + world.getTileEntity(blockpos); + } + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + TileEntityPiston tileentitypiston = this.getTileEntity(iblockaccess, blockpos); + if (tileentitypiston != null) { + IBlockState iblockstate = tileentitypiston.getPistonState(); + Block block = iblockstate.getBlock(); + if (block == this || block.getMaterial() == Material.air) { + return; + } + + float f = tileentitypiston.getProgress(0.0F); + if (tileentitypiston.isExtending()) { + f = 1.0F - f; + } + + block.setBlockBoundsBasedOnState(iblockaccess, blockpos); + if (block == Blocks.piston || block == Blocks.sticky_piston) { + f = 0.0F; + } + + EnumFacing enumfacing = tileentitypiston.getFacing(); + this.minX = block.getBlockBoundsMinX() - (double) ((float) enumfacing.getFrontOffsetX() * f); + this.minY = block.getBlockBoundsMinY() - (double) ((float) enumfacing.getFrontOffsetY() * f); + this.minZ = block.getBlockBoundsMinZ() - (double) ((float) enumfacing.getFrontOffsetZ() * f); + this.maxX = block.getBlockBoundsMaxX() - (double) ((float) enumfacing.getFrontOffsetX() * f); + this.maxY = block.getBlockBoundsMaxY() - (double) ((float) enumfacing.getFrontOffsetY() * f); + this.maxZ = block.getBlockBoundsMaxZ() - (double) ((float) enumfacing.getFrontOffsetZ() * f); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPlanks.java b/src/game/java/net/minecraft/block/BlockPlanks.java index e8214de3..466ce479 100644 --- a/src/game/java/net/minecraft/block/BlockPlanks.java +++ b/src/game/java/net/minecraft/block/BlockPlanks.java @@ -13,95 +13,57 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPlanks extends Block { - public static PropertyEnum VARIANT; - - public BlockPlanks() { - super(Material.wood); - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.OAK)); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockPlanks.EnumType[] types = BlockPlanks.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockPlanks.EnumType.byMetadata(i)); - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).func_181070_c(); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - public static enum EnumType implements IStringSerializable { OAK(0, "oak", MapColor.woodColor), SPRUCE(1, "spruce", MapColor.obsidianColor), BIRCH(2, "birch", MapColor.sandColor), JUNGLE(3, "jungle", MapColor.dirtColor), ACACIA(4, "acacia", MapColor.adobeColor), DARK_OAK(5, "dark_oak", "big_oak", MapColor.brownColor); public static final BlockPlanks.EnumType[] META_LOOKUP = new BlockPlanks.EnumType[6]; + static { + BlockPlanks.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockPlanks.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int meta; private final String name; + private final String unlocalizedName; + private final MapColor field_181071_k; private EnumType(int parInt2, String parString2, MapColor parMapColor) { @@ -115,24 +77,12 @@ public class BlockPlanks extends Block { this.field_181071_k = parMapColor; } - public int getMetadata() { - return this.meta; - } - public MapColor func_181070_c() { return this.field_181071_k; } - public String toString() { - return this.name; - } - - public static BlockPlanks.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; + public int getMetadata() { + return this.meta; } public String getName() { @@ -143,12 +93,66 @@ public class BlockPlanks extends Block { return this.unlocalizedName; } - static { - BlockPlanks.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class); + } + + public BlockPlanks() { + super(Material.wood); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPlanks.EnumType.OAK)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).func_181070_c(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockPlanks.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockPlanks.EnumType[] types = BlockPlanks.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPortal.java b/src/game/java/net/minecraft/block/BlockPortal.java index b17eec9a..e68125e7 100644 --- a/src/game/java/net/minecraft/block/BlockPortal.java +++ b/src/game/java/net/minecraft/block/BlockPortal.java @@ -2,7 +2,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.cache.EaglerLoadingCache; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -22,84 +21,177 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPortal extends BlockBreakable { + public static class Size { + private final World world; + private final EnumFacing.Axis axis; + private final EnumFacing field_150866_c; + private final EnumFacing field_150863_d; + private int field_150864_e = 0; + private BlockPos field_150861_f; + private int field_150862_g; + private int field_150868_h; + + public Size(World worldIn, BlockPos parBlockPos, EnumFacing.Axis parAxis) { + this.world = worldIn; + this.axis = parAxis; + if (parAxis == EnumFacing.Axis.X) { + this.field_150863_d = EnumFacing.EAST; + this.field_150866_c = EnumFacing.WEST; + } else { + this.field_150863_d = EnumFacing.NORTH; + this.field_150866_c = EnumFacing.SOUTH; + } + + for (BlockPos blockpos = parBlockPos; parBlockPos.getY() > blockpos.getY() - 21 && parBlockPos.getY() > 0 + && this.func_150857_a( + worldIn.getBlockState(parBlockPos.down()).getBlock()); parBlockPos = parBlockPos.down()) { + ; + } + + int i = this.func_180120_a(parBlockPos, this.field_150863_d) - 1; + if (i >= 0) { + this.field_150861_f = parBlockPos.offset(this.field_150863_d, i); + this.field_150868_h = this.func_180120_a(this.field_150861_f, this.field_150866_c); + if (this.field_150868_h < 2 || this.field_150868_h > 21) { + this.field_150861_f = null; + this.field_150868_h = 0; + } + } + + if (this.field_150861_f != null) { + this.field_150862_g = this.func_150858_a(); + } + + } + + protected boolean func_150857_a(Block parBlock) { + return parBlock.blockMaterial == Material.air || parBlock == Blocks.fire || parBlock == Blocks.portal; + } + + protected int func_150858_a() { + label24: for (this.field_150862_g = 0; this.field_150862_g < 21; ++this.field_150862_g) { + for (int i = 0; i < this.field_150868_h; ++i) { + BlockPos blockpos = this.field_150861_f.offset(this.field_150866_c, i).up(this.field_150862_g); + Block block = this.world.getBlockState(blockpos).getBlock(); + if (!this.func_150857_a(block)) { + break label24; + } + + if (block == Blocks.portal) { + ++this.field_150864_e; + } + + if (i == 0) { + block = this.world.getBlockState(blockpos.offset(this.field_150863_d)).getBlock(); + if (block != Blocks.obsidian) { + break label24; + } + } else if (i == this.field_150868_h - 1) { + block = this.world.getBlockState(blockpos.offset(this.field_150866_c)).getBlock(); + if (block != Blocks.obsidian) { + break label24; + } + } + } + } + + for (int j = 0; j < this.field_150868_h; ++j) { + if (this.world.getBlockState(this.field_150861_f.offset(this.field_150866_c, j).up(this.field_150862_g)) + .getBlock() != Blocks.obsidian) { + this.field_150862_g = 0; + break; + } + } + + if (this.field_150862_g <= 21 && this.field_150862_g >= 3) { + return this.field_150862_g; + } else { + this.field_150861_f = null; + this.field_150868_h = 0; + this.field_150862_g = 0; + return 0; + } + } + + public void func_150859_c() { + for (int i = 0; i < this.field_150868_h; ++i) { + BlockPos blockpos = this.field_150861_f.offset(this.field_150866_c, i); + + for (int j = 0; j < this.field_150862_g; ++j) { + this.world.setBlockState(blockpos.up(j), + Blocks.portal.getDefaultState().withProperty(BlockPortal.AXIS, this.axis), 2); + } + } + + } + + public boolean func_150860_b() { + return this.field_150861_f != null && this.field_150868_h >= 2 && this.field_150868_h <= 21 + && this.field_150862_g >= 3 && this.field_150862_g <= 21; + } + + protected int func_180120_a(BlockPos parBlockPos, EnumFacing parEnumFacing) { + int i; + for (i = 0; i < 22; ++i) { + BlockPos blockpos = parBlockPos.offset(parEnumFacing, i); + if (!this.func_150857_a(this.world.getBlockState(blockpos).getBlock()) + || this.world.getBlockState(blockpos.down()).getBlock() != Blocks.obsidian) { + break; + } + } + + Block block = this.world.getBlockState(parBlockPos.offset(parEnumFacing, i)).getBlock(); + return block == Blocks.obsidian ? i : 0; + } + + public int func_181100_a() { + return this.field_150862_g; + } + + public int func_181101_b() { + return this.field_150868_h; + } + } + public static final PropertyEnum AXIS = PropertyEnum.create("axis", EnumFacing.Axis.class, new EnumFacing.Axis[] { EnumFacing.Axis.X, EnumFacing.Axis.Z }); + public static int getMetaForAxis(EnumFacing.Axis axis) { + return axis == EnumFacing.Axis.X ? 1 : (axis == EnumFacing.Axis.Z ? 2 : 0); + } + public BlockPortal() { super(Material.portal, false); this.setDefaultState(this.blockState.getBaseState().withProperty(AXIS, EnumFacing.Axis.X)); this.setTickRandomly(true); } - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - super.updateTick(world, blockpos, iblockstate, random); - if (world.provider.isSurfaceWorld() && world.getGameRules().getBoolean("doMobSpawning") - && random.nextInt(2000) < world.getDifficulty().getDifficultyId()) { - int i = blockpos.getY(); - - BlockPos blockpos1; - for (blockpos1 = blockpos; !World.doesBlockHaveSolidTopSurface(world, blockpos1) - && blockpos1.getY() > 0; blockpos1 = blockpos1.down()) { - ; - } - - if (i > 0 && !world.getBlockState(blockpos1.up()).getBlock().isNormalCube()) { - Entity entity = ItemMonsterPlacer.spawnCreature(world, 57, (double) blockpos1.getX() + 0.5D, - (double) blockpos1.getY() + 1.1D, (double) blockpos1.getZ() + 0.5D); - if (entity != null) { - entity.timeUntilPortal = entity.getPortalCooldown(); - } - } - } - - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - EnumFacing.Axis enumfacing$axis = (EnumFacing.Axis) iblockaccess.getBlockState(blockpos).getValue(AXIS); - float f = 0.125F; - float f1 = 0.125F; - if (enumfacing$axis == EnumFacing.Axis.X) { - f = 0.5F; - } - - if (enumfacing$axis == EnumFacing.Axis.Z) { - f1 = 0.5F; - } - - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f1, 0.5F + f, 1.0F, 0.5F + f1); - } - - public static int getMetaForAxis(EnumFacing.Axis axis) { - return axis == EnumFacing.Axis.X ? 1 : (axis == EnumFacing.Axis.Z ? 2 : 0); - } - - public boolean isFullCube() { - return false; + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AXIS }); } public boolean func_176548_d(World worldIn, BlockPos parBlockPos) { @@ -118,134 +210,6 @@ public class BlockPortal extends BlockBreakable { } } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - EnumFacing.Axis enumfacing$axis = (EnumFacing.Axis) iblockstate.getValue(AXIS); - if (enumfacing$axis == EnumFacing.Axis.X) { - BlockPortal.Size blockportal$size = new BlockPortal.Size(world, blockpos, EnumFacing.Axis.X); - if (!blockportal$size.func_150860_b() || blockportal$size.field_150864_e < blockportal$size.field_150868_h - * blockportal$size.field_150862_g) { - world.setBlockState(blockpos, Blocks.air.getDefaultState()); - } - } else if (enumfacing$axis == EnumFacing.Axis.Z) { - BlockPortal.Size blockportal$size1 = new BlockPortal.Size(world, blockpos, EnumFacing.Axis.Z); - if (!blockportal$size1.func_150860_b() - || blockportal$size1.field_150864_e < blockportal$size1.field_150868_h - * blockportal$size1.field_150862_g) { - world.setBlockState(blockpos, Blocks.air.getDefaultState()); - } - } - - } - - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - EnumFacing.Axis enumfacing$axis = null; - IBlockState iblockstate = iblockaccess.getBlockState(blockpos); - if (iblockaccess.getBlockState(blockpos).getBlock() == this) { - enumfacing$axis = (EnumFacing.Axis) iblockstate.getValue(AXIS); - if (enumfacing$axis == null) { - return false; - } - - if (enumfacing$axis == EnumFacing.Axis.Z && enumfacing != EnumFacing.EAST - && enumfacing != EnumFacing.WEST) { - return false; - } - - if (enumfacing$axis == EnumFacing.Axis.X && enumfacing != EnumFacing.SOUTH - && enumfacing != EnumFacing.NORTH) { - return false; - } - } - - boolean flag = iblockaccess.getBlockState(blockpos.west()).getBlock() == this - && iblockaccess.getBlockState(blockpos.west(2)).getBlock() != this; - boolean flag1 = iblockaccess.getBlockState(blockpos.east()).getBlock() == this - && iblockaccess.getBlockState(blockpos.east(2)).getBlock() != this; - boolean flag2 = iblockaccess.getBlockState(blockpos.north()).getBlock() == this - && iblockaccess.getBlockState(blockpos.north(2)).getBlock() != this; - boolean flag3 = iblockaccess.getBlockState(blockpos.south()).getBlock() == this - && iblockaccess.getBlockState(blockpos.south(2)).getBlock() != this; - boolean flag4 = flag || flag1 || enumfacing$axis == EnumFacing.Axis.X; - boolean flag5 = flag2 || flag3 || enumfacing$axis == EnumFacing.Axis.Z; - return flag4 && enumfacing == EnumFacing.WEST ? true - : (flag4 && enumfacing == EnumFacing.EAST ? true - : (flag5 && enumfacing == EnumFacing.NORTH ? true : flag5 && enumfacing == EnumFacing.SOUTH)); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.TRANSLUCENT; - } - - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World var1, BlockPos blockpos, IBlockState var3, Entity entity) { - if (entity.ridingEntity == null && entity.riddenByEntity == null) { - entity.func_181015_d(blockpos); - } - - } - - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { - if (random.nextInt(100) == 0) { - world.playSound((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, - (double) blockpos.getZ() + 0.5D, "portal.portal", 0.5F, random.nextFloat() * 0.4F + 0.8F, false); - } - - for (int i = 0; i < 4; ++i) { - double d0 = (double) ((float) blockpos.getX() + random.nextFloat()); - double d1 = (double) ((float) blockpos.getY() + random.nextFloat()); - double d2 = (double) ((float) blockpos.getZ() + random.nextFloat()); - double d3 = ((double) random.nextFloat() - 0.5D) * 0.5D; - double d4 = ((double) random.nextFloat() - 0.5D) * 0.5D; - double d5 = ((double) random.nextFloat() - 0.5D) * 0.5D; - int j = random.nextInt(2) * 2 - 1; - if (world.getBlockState(blockpos.west()).getBlock() != this - && world.getBlockState(blockpos.east()).getBlock() != this) { - d0 = (double) blockpos.getX() + 0.5D + 0.25D * (double) j; - d3 = (double) (random.nextFloat() * 2.0F * (float) j); - } else { - d2 = (double) blockpos.getZ() + 0.5D + 0.25D * (double) j; - d5 = (double) (random.nextFloat() * 2.0F * (float) j); - } - - world.spawnParticle(EnumParticleTypes.PORTAL, d0, d1, d2, d3, d4, d5, new int[0]); - } - - } - - public Item getItem(World var1, BlockPos var2) { - return null; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AXIS, (i & 3) == 2 ? EnumFacing.Axis.Z : EnumFacing.Axis.X); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return getMetaForAxis((EnumFacing.Axis) iblockstate.getValue(AXIS)); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AXIS }); - } - public BlockPattern.PatternHelper func_181089_f(World parWorld, BlockPos parBlockPos) { EnumFacing.Axis enumfacing$axis = EnumFacing.Axis.Z; BlockPortal.Size blockportal$size = new BlockPortal.Size(parWorld, parBlockPos, EnumFacing.Axis.X); @@ -300,135 +264,173 @@ public class BlockPortal extends BlockBreakable { } } - public static class Size { - private final World world; - private final EnumFacing.Axis axis; - private final EnumFacing field_150866_c; - private final EnumFacing field_150863_d; - private int field_150864_e = 0; - private BlockPos field_150861_f; - private int field_150862_g; - private int field_150868_h; + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.TRANSLUCENT; + } - public Size(World worldIn, BlockPos parBlockPos, EnumFacing.Axis parAxis) { - this.world = worldIn; - this.axis = parAxis; - if (parAxis == EnumFacing.Axis.X) { - this.field_150863_d = EnumFacing.EAST; - this.field_150866_c = EnumFacing.WEST; + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + public Item getItem(World var1, BlockPos var2) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return getMetaForAxis((EnumFacing.Axis) iblockstate.getValue(AXIS)); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AXIS, (i & 3) == 2 ? EnumFacing.Axis.Z : EnumFacing.Axis.X); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World var1, BlockPos blockpos, IBlockState var3, Entity entity) { + if (entity.ridingEntity == null && entity.riddenByEntity == null) { + entity.func_181015_d(blockpos); + } + + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + EnumFacing.Axis enumfacing$axis = (EnumFacing.Axis) iblockstate.getValue(AXIS); + if (enumfacing$axis == EnumFacing.Axis.X) { + BlockPortal.Size blockportal$size = new BlockPortal.Size(world, blockpos, EnumFacing.Axis.X); + if (!blockportal$size.func_150860_b() || blockportal$size.field_150864_e < blockportal$size.field_150868_h + * blockportal$size.field_150862_g) { + world.setBlockState(blockpos, Blocks.air.getDefaultState()); + } + } else if (enumfacing$axis == EnumFacing.Axis.Z) { + BlockPortal.Size blockportal$size1 = new BlockPortal.Size(world, blockpos, EnumFacing.Axis.Z); + if (!blockportal$size1.func_150860_b() + || blockportal$size1.field_150864_e < blockportal$size1.field_150868_h + * blockportal$size1.field_150862_g) { + world.setBlockState(blockpos, Blocks.air.getDefaultState()); + } + } + + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } + + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom random) { + if (random.nextInt(100) == 0) { + world.playSound((double) blockpos.getX() + 0.5D, (double) blockpos.getY() + 0.5D, + (double) blockpos.getZ() + 0.5D, "portal.portal", 0.5F, random.nextFloat() * 0.4F + 0.8F, false); + } + + for (int i = 0; i < 4; ++i) { + double d0 = (double) ((float) blockpos.getX() + random.nextFloat()); + double d1 = (double) ((float) blockpos.getY() + random.nextFloat()); + double d2 = (double) ((float) blockpos.getZ() + random.nextFloat()); + double d3 = ((double) random.nextFloat() - 0.5D) * 0.5D; + double d4 = ((double) random.nextFloat() - 0.5D) * 0.5D; + double d5 = ((double) random.nextFloat() - 0.5D) * 0.5D; + int j = random.nextInt(2) * 2 - 1; + if (world.getBlockState(blockpos.west()).getBlock() != this + && world.getBlockState(blockpos.east()).getBlock() != this) { + d0 = (double) blockpos.getX() + 0.5D + 0.25D * (double) j; + d3 = (double) (random.nextFloat() * 2.0F * (float) j); } else { - this.field_150863_d = EnumFacing.NORTH; - this.field_150866_c = EnumFacing.SOUTH; + d2 = (double) blockpos.getZ() + 0.5D + 0.25D * (double) j; + d5 = (double) (random.nextFloat() * 2.0F * (float) j); } - for (BlockPos blockpos = parBlockPos; parBlockPos.getY() > blockpos.getY() - 21 && parBlockPos.getY() > 0 - && this.func_150857_a( - worldIn.getBlockState(parBlockPos.down()).getBlock()); parBlockPos = parBlockPos.down()) { + world.spawnParticle(EnumParticleTypes.PORTAL, d0, d1, d2, d3, d4, d5, new int[0]); + } + + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + EnumFacing.Axis enumfacing$axis = (EnumFacing.Axis) iblockaccess.getBlockState(blockpos).getValue(AXIS); + float f = 0.125F; + float f1 = 0.125F; + if (enumfacing$axis == EnumFacing.Axis.X) { + f = 0.5F; + } + + if (enumfacing$axis == EnumFacing.Axis.Z) { + f1 = 0.5F; + } + + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f1, 0.5F + f, 1.0F, 0.5F + f1); + } + + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + EnumFacing.Axis enumfacing$axis = null; + IBlockState iblockstate = iblockaccess.getBlockState(blockpos); + if (iblockaccess.getBlockState(blockpos).getBlock() == this) { + enumfacing$axis = (EnumFacing.Axis) iblockstate.getValue(AXIS); + if (enumfacing$axis == null) { + return false; + } + + if (enumfacing$axis == EnumFacing.Axis.Z && enumfacing != EnumFacing.EAST + && enumfacing != EnumFacing.WEST) { + return false; + } + + if (enumfacing$axis == EnumFacing.Axis.X && enumfacing != EnumFacing.SOUTH + && enumfacing != EnumFacing.NORTH) { + return false; + } + } + + boolean flag = iblockaccess.getBlockState(blockpos.west()).getBlock() == this + && iblockaccess.getBlockState(blockpos.west(2)).getBlock() != this; + boolean flag1 = iblockaccess.getBlockState(blockpos.east()).getBlock() == this + && iblockaccess.getBlockState(blockpos.east(2)).getBlock() != this; + boolean flag2 = iblockaccess.getBlockState(blockpos.north()).getBlock() == this + && iblockaccess.getBlockState(blockpos.north(2)).getBlock() != this; + boolean flag3 = iblockaccess.getBlockState(blockpos.south()).getBlock() == this + && iblockaccess.getBlockState(blockpos.south(2)).getBlock() != this; + boolean flag4 = flag || flag1 || enumfacing$axis == EnumFacing.Axis.X; + boolean flag5 = flag2 || flag3 || enumfacing$axis == EnumFacing.Axis.Z; + return flag4 && enumfacing == EnumFacing.WEST ? true + : (flag4 && enumfacing == EnumFacing.EAST ? true + : (flag5 && enumfacing == EnumFacing.NORTH ? true : flag5 && enumfacing == EnumFacing.SOUTH)); + } + + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + super.updateTick(world, blockpos, iblockstate, random); + if (world.provider.isSurfaceWorld() && world.getGameRules().getBoolean("doMobSpawning") + && random.nextInt(2000) < world.getDifficulty().getDifficultyId()) { + int i = blockpos.getY(); + + BlockPos blockpos1; + for (blockpos1 = blockpos; !World.doesBlockHaveSolidTopSurface(world, blockpos1) + && blockpos1.getY() > 0; blockpos1 = blockpos1.down()) { ; } - int i = this.func_180120_a(parBlockPos, this.field_150863_d) - 1; - if (i >= 0) { - this.field_150861_f = parBlockPos.offset(this.field_150863_d, i); - this.field_150868_h = this.func_180120_a(this.field_150861_f, this.field_150866_c); - if (this.field_150868_h < 2 || this.field_150868_h > 21) { - this.field_150861_f = null; - this.field_150868_h = 0; + if (i > 0 && !world.getBlockState(blockpos1.up()).getBlock().isNormalCube()) { + Entity entity = ItemMonsterPlacer.spawnCreature(world, 57, (double) blockpos1.getX() + 0.5D, + (double) blockpos1.getY() + 1.1D, (double) blockpos1.getZ() + 0.5D); + if (entity != null) { + entity.timeUntilPortal = entity.getPortalCooldown(); } } - - if (this.field_150861_f != null) { - this.field_150862_g = this.func_150858_a(); - } - } - protected int func_180120_a(BlockPos parBlockPos, EnumFacing parEnumFacing) { - int i; - for (i = 0; i < 22; ++i) { - BlockPos blockpos = parBlockPos.offset(parEnumFacing, i); - if (!this.func_150857_a(this.world.getBlockState(blockpos).getBlock()) - || this.world.getBlockState(blockpos.down()).getBlock() != Blocks.obsidian) { - break; - } - } - - Block block = this.world.getBlockState(parBlockPos.offset(parEnumFacing, i)).getBlock(); - return block == Blocks.obsidian ? i : 0; - } - - public int func_181100_a() { - return this.field_150862_g; - } - - public int func_181101_b() { - return this.field_150868_h; - } - - protected int func_150858_a() { - label24: for (this.field_150862_g = 0; this.field_150862_g < 21; ++this.field_150862_g) { - for (int i = 0; i < this.field_150868_h; ++i) { - BlockPos blockpos = this.field_150861_f.offset(this.field_150866_c, i).up(this.field_150862_g); - Block block = this.world.getBlockState(blockpos).getBlock(); - if (!this.func_150857_a(block)) { - break label24; - } - - if (block == Blocks.portal) { - ++this.field_150864_e; - } - - if (i == 0) { - block = this.world.getBlockState(blockpos.offset(this.field_150863_d)).getBlock(); - if (block != Blocks.obsidian) { - break label24; - } - } else if (i == this.field_150868_h - 1) { - block = this.world.getBlockState(blockpos.offset(this.field_150866_c)).getBlock(); - if (block != Blocks.obsidian) { - break label24; - } - } - } - } - - for (int j = 0; j < this.field_150868_h; ++j) { - if (this.world.getBlockState(this.field_150861_f.offset(this.field_150866_c, j).up(this.field_150862_g)) - .getBlock() != Blocks.obsidian) { - this.field_150862_g = 0; - break; - } - } - - if (this.field_150862_g <= 21 && this.field_150862_g >= 3) { - return this.field_150862_g; - } else { - this.field_150861_f = null; - this.field_150868_h = 0; - this.field_150862_g = 0; - return 0; - } - } - - protected boolean func_150857_a(Block parBlock) { - return parBlock.blockMaterial == Material.air || parBlock == Blocks.fire || parBlock == Blocks.portal; - } - - public boolean func_150860_b() { - return this.field_150861_f != null && this.field_150868_h >= 2 && this.field_150868_h <= 21 - && this.field_150862_g >= 3 && this.field_150862_g <= 21; - } - - public void func_150859_c() { - for (int i = 0; i < this.field_150868_h; ++i) { - BlockPos blockpos = this.field_150861_f.offset(this.field_150866_c, i); - - for (int j = 0; j < this.field_150862_g; ++j) { - this.world.setBlockState(blockpos.up(j), - Blocks.portal.getDefaultState().withProperty(BlockPortal.AXIS, this.axis), 2); - } - } - - } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPotato.java b/src/game/java/net/minecraft/block/BlockPotato.java index f38f664a..df721a53 100644 --- a/src/game/java/net/minecraft/block/BlockPotato.java +++ b/src/game/java/net/minecraft/block/BlockPotato.java @@ -7,37 +7,32 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPotato extends BlockCrops { - protected Item getSeed() { - return Items.potato; - } - - protected Item getCrop() { - return Items.potato; - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); @@ -47,4 +42,12 @@ public class BlockPotato extends BlockCrops { } } } + + protected Item getCrop() { + return Items.potato; + } + + protected Item getSeed() { + return Items.potato; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPressurePlate.java b/src/game/java/net/minecraft/block/BlockPressurePlate.java index b44ce567..61aad083 100644 --- a/src/game/java/net/minecraft/block/BlockPressurePlate.java +++ b/src/game/java/net/minecraft/block/BlockPressurePlate.java @@ -13,28 +13,36 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPressurePlate extends BlockBasePressurePlate { + public static enum Sensitivity { + EVERYTHING, MOBS; + } + public static final PropertyBool POWERED = PropertyBool.create("powered"); + private final BlockPressurePlate.Sensitivity sensitivity; protected BlockPressurePlate(Material materialIn, BlockPressurePlate.Sensitivity sensitivityIn) { @@ -43,14 +51,6 @@ public class BlockPressurePlate extends BlockBasePressurePlate { this.sensitivity = sensitivityIn; } - protected int getRedstoneStrength(IBlockState iblockstate) { - return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; - } - - protected IBlockState setRedstoneStrength(IBlockState iblockstate, int i) { - return iblockstate.withProperty(POWERED, Boolean.valueOf(i > 0)); - } - protected int computeRedstoneStrength(World world, BlockPos blockpos) { AxisAlignedBB axisalignedbb = this.getSensitiveAABB(blockpos); List list; @@ -77,25 +77,29 @@ public class BlockPressurePlate extends BlockBasePressurePlate { return 0; } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(POWERED, Boolean.valueOf(i == 1)); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { POWERED }); } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 1 : 0; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { POWERED }); + protected int getRedstoneStrength(IBlockState iblockstate) { + return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; } - public static enum Sensitivity { - EVERYTHING, MOBS; + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(POWERED, Boolean.valueOf(i == 1)); + } + + protected IBlockState setRedstoneStrength(IBlockState iblockstate, int i) { + return iblockstate.withProperty(POWERED, Boolean.valueOf(i > 0)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPressurePlateWeighted.java b/src/game/java/net/minecraft/block/BlockPressurePlateWeighted.java index 8bfbe818..bf30205a 100644 --- a/src/game/java/net/minecraft/block/BlockPressurePlateWeighted.java +++ b/src/game/java/net/minecraft/block/BlockPressurePlateWeighted.java @@ -11,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,36 +59,36 @@ public class BlockPressurePlateWeighted extends BlockBasePressurePlate { } } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { POWER }); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(POWER)).intValue(); + } + protected int getRedstoneStrength(IBlockState iblockstate) { return ((Integer) iblockstate.getValue(POWER)).intValue(); } + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(POWER, Integer.valueOf(i)); + } + protected IBlockState setRedstoneStrength(IBlockState iblockstate, int i) { return iblockstate.withProperty(POWER, Integer.valueOf(i)); } - /**+ - * How many world ticks before ticking + /** + * + How many world ticks before ticking */ public int tickRate(World var1) { return 10; } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(POWER, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(POWER)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { POWER }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPrismarine.java b/src/game/java/net/minecraft/block/BlockPrismarine.java index e552753b..047b587c 100644 --- a/src/game/java/net/minecraft/block/BlockPrismarine.java +++ b/src/game/java/net/minecraft/block/BlockPrismarine.java @@ -14,103 +14,54 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; import net.minecraft.util.StatCollector; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPrismarine extends Block { - public static PropertyEnum VARIANT; - public static final int ROUGH_META = BlockPrismarine.EnumType.ROUGH.getMetadata(); - public static final int BRICKS_META = BlockPrismarine.EnumType.BRICKS.getMetadata(); - public static final int DARK_META = BlockPrismarine.EnumType.DARK.getMetadata(); - - public BlockPrismarine() { - super(Material.rock); - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPrismarine.EnumType.ROUGH)); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockPrismarine.EnumType.class); - } - - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal( - this.getUnlocalizedName() + "." + BlockPrismarine.EnumType.ROUGH.getUnlocalizedName() + ".name"); - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return iblockstate.getValue(VARIANT) == BlockPrismarine.EnumType.ROUGH ? MapColor.cyanColor - : MapColor.diamondColor; - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPrismarine.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockPrismarine.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockPrismarine.EnumType.byMetadata(i)); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, ROUGH_META)); - list.add(new ItemStack(item, 1, BRICKS_META)); - list.add(new ItemStack(item, 1, DARK_META)); - } - public static enum EnumType implements IStringSerializable { ROUGH(0, "prismarine", "rough"), BRICKS(1, "prismarine_bricks", "bricks"), DARK(2, "dark_prismarine", "dark"); private static final BlockPrismarine.EnumType[] META_LOOKUP = new BlockPrismarine.EnumType[3]; + static { + BlockPrismarine.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockPrismarine.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int meta; + private final String name; + private final String unlocalizedName; private EnumType(int meta, String name, String unlocalizedName) { @@ -123,18 +74,6 @@ public class BlockPrismarine extends Block { return this.meta; } - public String toString() { - return this.name; - } - - public static BlockPrismarine.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - public String getName() { return this.name; } @@ -143,12 +82,77 @@ public class BlockPrismarine extends Block { return this.unlocalizedName; } - static { - BlockPrismarine.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + public static final int ROUGH_META = BlockPrismarine.EnumType.ROUGH.getMetadata(); + public static final int BRICKS_META = BlockPrismarine.EnumType.BRICKS.getMetadata(); + + public static final int DARK_META = BlockPrismarine.EnumType.DARK.getMetadata(); + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockPrismarine.EnumType.class); + } + + public BlockPrismarine() { + super(Material.rock); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockPrismarine.EnumType.ROUGH)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockPrismarine.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal( + this.getUnlocalizedName() + "." + BlockPrismarine.EnumType.ROUGH.getUnlocalizedName() + ".name"); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return iblockstate.getValue(VARIANT) == BlockPrismarine.EnumType.ROUGH ? MapColor.cyanColor + : MapColor.diamondColor; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockPrismarine.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockPrismarine.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, ROUGH_META)); + list.add(new ItemStack(item, 1, BRICKS_META)); + list.add(new ItemStack(item, 1, DARK_META)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockPumpkin.java b/src/game/java/net/minecraft/block/BlockPumpkin.java index 7d2b1925..8471a5a0 100644 --- a/src/game/java/net/minecraft/block/BlockPumpkin.java +++ b/src/game/java/net/minecraft/block/BlockPumpkin.java @@ -21,37 +21,40 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPumpkin extends BlockDirectional { - private BlockPattern snowmanBasePattern; - private BlockPattern snowmanPattern; - private BlockPattern golemBasePattern; - private BlockPattern golemPattern; private static final Predicate field_181085_Q = new Predicate() { public boolean apply(IBlockState iblockstate) { return iblockstate != null && (iblockstate.getBlock() == Blocks.pumpkin || iblockstate.getBlock() == Blocks.lit_pumpkin); } }; + private BlockPattern snowmanBasePattern; + private BlockPattern snowmanPattern; + private BlockPattern golemBasePattern; + private BlockPattern golemPattern; protected BlockPumpkin() { super(Material.gourd, MapColor.adobeColor); @@ -60,14 +63,86 @@ public class BlockPumpkin extends BlockDirectional { this.setCreativeTab(CreativeTabs.tabBlock); } + public boolean canDispenserPlace(World worldIn, BlockPos pos) { + return this.getSnowmanBasePattern().match(worldIn, pos) != null + || this.getGolemBasePattern().match(worldIn, pos) != null; + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return world.getBlockState(blockpos).getBlock().blockMaterial.isReplaceable() + && World.doesBlockHaveSolidTopSurface(world, blockpos.down()); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + protected BlockPattern getGolemBasePattern() { + if (this.golemBasePattern == null) { + this.golemBasePattern = FactoryBlockPattern.start().aisle(new String[] { "~ ~", "###", "~#~" }) + .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))) + .where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); + } + + return this.golemBasePattern; + } + + protected BlockPattern getGolemPattern() { + if (this.golemPattern == null) { + this.golemPattern = FactoryBlockPattern.start().aisle(new String[] { "~^~", "###", "~#~" }) + .where('^', BlockWorldState.hasState(field_181085_Q)) + .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))) + .where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); + } + + return this.golemPattern; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + } + + protected BlockPattern getSnowmanBasePattern() { + if (this.snowmanBasePattern == null) { + this.snowmanBasePattern = FactoryBlockPattern.start().aisle(new String[] { " ", "#", "#" }) + .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); + } + + return this.snowmanBasePattern; + } + + protected BlockPattern getSnowmanPattern() { + if (this.snowmanPattern == null) { + this.snowmanPattern = FactoryBlockPattern.start().aisle(new String[] { "^", "#", "#" }) + .where('^', BlockWorldState.hasState(field_181085_Q)) + .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); + } + + return this.snowmanPattern; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)); + } + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { super.onBlockAdded(world, blockpos, iblockstate); this.trySpawnGolem(world, blockpos); } - public boolean canDispenserPlace(World worldIn, BlockPos pos) { - return this.getSnowmanBasePattern().match(worldIn, pos) != null - || this.getGolemBasePattern().match(worldIn, pos) != null; + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); } private void trySpawnGolem(World worldIn, BlockPos pos) { @@ -125,76 +200,4 @@ public class BlockPumpkin extends BlockDirectional { } } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return world.getBlockState(blockpos).getBlock().blockMaterial.isReplaceable() - && World.doesBlockHaveSolidTopSurface(world, blockpos.down()); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } - - protected BlockPattern getSnowmanBasePattern() { - if (this.snowmanBasePattern == null) { - this.snowmanBasePattern = FactoryBlockPattern.start().aisle(new String[] { " ", "#", "#" }) - .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); - } - - return this.snowmanBasePattern; - } - - protected BlockPattern getSnowmanPattern() { - if (this.snowmanPattern == null) { - this.snowmanPattern = FactoryBlockPattern.start().aisle(new String[] { "^", "#", "#" }) - .where('^', BlockWorldState.hasState(field_181085_Q)) - .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); - } - - return this.snowmanPattern; - } - - protected BlockPattern getGolemBasePattern() { - if (this.golemBasePattern == null) { - this.golemBasePattern = FactoryBlockPattern.start().aisle(new String[] { "~ ~", "###", "~#~" }) - .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))) - .where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); - } - - return this.golemBasePattern; - } - - protected BlockPattern getGolemPattern() { - if (this.golemPattern == null) { - this.golemPattern = FactoryBlockPattern.start().aisle(new String[] { "~^~", "###", "~#~" }) - .where('^', BlockWorldState.hasState(field_181085_Q)) - .where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))) - .where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); - } - - return this.golemPattern; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockQuartz.java b/src/game/java/net/minecraft/block/BlockQuartz.java index 41928754..053fcca1 100644 --- a/src/game/java/net/minecraft/block/BlockQuartz.java +++ b/src/game/java/net/minecraft/block/BlockQuartz.java @@ -17,42 +17,145 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockQuartz extends Block { + public static enum EnumType implements IStringSerializable { + DEFAULT(0, "default", "default"), CHISELED(1, "chiseled", "chiseled"), LINES_Y(2, "lines_y", "lines"), + LINES_X(3, "lines_x", "lines"), LINES_Z(4, "lines_z", "lines"); + + private static final BlockQuartz.EnumType[] META_LOOKUP = new BlockQuartz.EnumType[5]; + static { + BlockQuartz.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockQuartz.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + + private final String field_176805_h; + + private final String unlocalizedName; + + private EnumType(int meta, String name, String unlocalizedName) { + this.meta = meta; + this.field_176805_h = name; + this.unlocalizedName = unlocalizedName; + } + + public int getMetadata() { + return this.meta; + } + + public String getName() { + return this.field_176805_h; + } + + public String toString() { + return this.unlocalizedName; + } + } + public static PropertyEnum VARIANT; + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockQuartz.EnumType.class); + } + public BlockQuartz() { super(Material.rock); this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockQuartz.EnumType.DEFAULT)); this.setCreativeTab(CreativeTabs.tabBlock); } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockQuartz.EnumType.class); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + protected ItemStack createStackedBlock(IBlockState iblockstate) { + BlockQuartz.EnumType blockquartz$enumtype = (BlockQuartz.EnumType) iblockstate.getValue(VARIANT); + return blockquartz$enumtype != BlockQuartz.EnumType.LINES_X + && blockquartz$enumtype != BlockQuartz.EnumType.LINES_Z ? super.createStackedBlock(iblockstate) + : new ItemStack(Item.getItemFromBlock(this), 1, BlockQuartz.EnumType.LINES_Y.getMetadata()); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + BlockQuartz.EnumType blockquartz$enumtype = (BlockQuartz.EnumType) iblockstate.getValue(VARIANT); + return blockquartz$enumtype != BlockQuartz.EnumType.LINES_X + && blockquartz$enumtype != BlockQuartz.EnumType.LINES_Z ? blockquartz$enumtype.getMetadata() + : BlockQuartz.EnumType.LINES_Y.getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState var1) { + return MapColor.quartzColor; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockQuartz.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockQuartz.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, BlockQuartz.EnumType.DEFAULT.getMetadata())); + list.add(new ItemStack(item, 1, BlockQuartz.EnumType.CHISELED.getMetadata())); + list.add(new ItemStack(item, 1, BlockQuartz.EnumType.LINES_Y.getMetadata())); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, float var6, int i, EntityLivingBase var8) { @@ -72,103 +175,4 @@ public class BlockQuartz extends Block { : this.getDefaultState().withProperty(VARIANT, BlockQuartz.EnumType.DEFAULT); } } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - BlockQuartz.EnumType blockquartz$enumtype = (BlockQuartz.EnumType) iblockstate.getValue(VARIANT); - return blockquartz$enumtype != BlockQuartz.EnumType.LINES_X - && blockquartz$enumtype != BlockQuartz.EnumType.LINES_Z ? blockquartz$enumtype.getMetadata() - : BlockQuartz.EnumType.LINES_Y.getMetadata(); - } - - protected ItemStack createStackedBlock(IBlockState iblockstate) { - BlockQuartz.EnumType blockquartz$enumtype = (BlockQuartz.EnumType) iblockstate.getValue(VARIANT); - return blockquartz$enumtype != BlockQuartz.EnumType.LINES_X - && blockquartz$enumtype != BlockQuartz.EnumType.LINES_Z ? super.createStackedBlock(iblockstate) - : new ItemStack(Item.getItemFromBlock(this), 1, BlockQuartz.EnumType.LINES_Y.getMetadata()); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, BlockQuartz.EnumType.DEFAULT.getMetadata())); - list.add(new ItemStack(item, 1, BlockQuartz.EnumType.CHISELED.getMetadata())); - list.add(new ItemStack(item, 1, BlockQuartz.EnumType.LINES_Y.getMetadata())); - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState var1) { - return MapColor.quartzColor; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockQuartz.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockQuartz.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - - public static enum EnumType implements IStringSerializable { - DEFAULT(0, "default", "default"), CHISELED(1, "chiseled", "chiseled"), LINES_Y(2, "lines_y", "lines"), - LINES_X(3, "lines_x", "lines"), LINES_Z(4, "lines_z", "lines"); - - private static final BlockQuartz.EnumType[] META_LOOKUP = new BlockQuartz.EnumType[5]; - private final int meta; - private final String field_176805_h; - private final String unlocalizedName; - - private EnumType(int meta, String name, String unlocalizedName) { - this.meta = meta; - this.field_176805_h = name; - this.unlocalizedName = unlocalizedName; - } - - public int getMetadata() { - return this.meta; - } - - public String toString() { - return this.unlocalizedName; - } - - public static BlockQuartz.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { - return this.field_176805_h; - } - - static { - BlockQuartz.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRail.java b/src/game/java/net/minecraft/block/BlockRail.java index 24054af3..1e50b0df 100644 --- a/src/game/java/net/minecraft/block/BlockRail.java +++ b/src/game/java/net/minecraft/block/BlockRail.java @@ -7,22 +7,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,14 +33,36 @@ import net.minecraft.world.World; public class BlockRail extends BlockRailBase { public static PropertyEnum SHAPE; + public static void bootstrapStates() { + SHAPE = PropertyEnum.create("shape", BlockRailBase.EnumRailDirection.class); + } + protected BlockRail() { super(false); this.setDefaultState( this.blockState.getBaseState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.NORTH_SOUTH)); } - public static void bootstrapStates() { - SHAPE = PropertyEnum.create("shape", BlockRailBase.EnumRailDirection.class); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { SHAPE }); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockRailBase.EnumRailDirection) iblockstate.getValue(SHAPE)).getMetadata(); + } + + public IProperty getShapeProperty() { + return SHAPE; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(i)); } protected void onNeighborChangedInternal(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { @@ -47,26 +72,4 @@ public class BlockRail extends BlockRailBase { } } - - public IProperty getShapeProperty() { - return SHAPE; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockRailBase.EnumRailDirection) iblockstate.getValue(SHAPE)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { SHAPE }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRailBase.java b/src/game/java/net/minecraft/block/BlockRailBase.java index 00cda6a9..d9af850a 100644 --- a/src/game/java/net/minecraft/block/BlockRailBase.java +++ b/src/game/java/net/minecraft/block/BlockRailBase.java @@ -19,165 +19,30 @@ import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockRailBase extends Block { - protected final boolean isPowered; - - public static boolean isRailBlock(World worldIn, BlockPos pos) { - return isRailBlock(worldIn.getBlockState(pos)); - } - - public static boolean isRailBlock(IBlockState state) { - Block block = state.getBlock(); - return block == Blocks.rail || block == Blocks.golden_rail || block == Blocks.detector_rail - || block == Blocks.activator_rail; - } - - protected BlockRailBase(boolean isPowered) { - super(Material.circuits); - this.isPowered = isPowered; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); - this.setCreativeTab(CreativeTabs.tabTransport); - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) { - this.setBlockBoundsBasedOnState(worldIn, pos); - return super.collisionRayTrace(worldIn, pos, start, end); - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - IBlockState iblockstate = iblockaccess.getBlockState(blockpos); - BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = iblockstate.getBlock() == this - ? (BlockRailBase.EnumRailDirection) iblockstate.getValue(this.getShapeProperty()) - : null; - if (blockrailbase$enumraildirection != null && blockrailbase$enumraildirection.isAscending()) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F); - } else { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); - } - - } - - public boolean isFullCube() { - return false; - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return World.doesBlockHaveSolidTopSurface(world, blockpos.down()); - } - - public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { - if (!worldIn.isRemote) { - state = this.func_176564_a(worldIn, pos, state, true); - if (this.isPowered) { - this.onNeighborBlockChange(worldIn, pos, state, this); - } - } - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - if (!world.isRemote) { - BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection) iblockstate - .getValue(this.getShapeProperty()); - boolean flag = false; - if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { - flag = true; - } - - if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_EAST - && !World.doesBlockHaveSolidTopSurface(world, blockpos.east())) { - flag = true; - } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_WEST - && !World.doesBlockHaveSolidTopSurface(world, blockpos.west())) { - flag = true; - } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_NORTH - && !World.doesBlockHaveSolidTopSurface(world, blockpos.north())) { - flag = true; - } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_SOUTH - && !World.doesBlockHaveSolidTopSurface(world, blockpos.south())) { - flag = true; - } - - if (flag) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } else { - this.onNeighborChangedInternal(world, blockpos, iblockstate, block); - } - } - } - - protected void onNeighborChangedInternal(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { - } - - protected IBlockState func_176564_a(World worldIn, BlockPos parBlockPos, IBlockState parIBlockState, - boolean parFlag) { - return worldIn.isRemote ? parIBlockState - : (new BlockRailBase.Rail(worldIn, parBlockPos, parIBlockState)) - .func_180364_a(worldIn.isBlockPowered(parBlockPos), parFlag).getBlockState(); - } - - public int getMobilityFlag() { - return 0; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - super.breakBlock(world, blockpos, iblockstate); - if (((BlockRailBase.EnumRailDirection) iblockstate.getValue(this.getShapeProperty())).isAscending()) { - world.notifyNeighborsOfStateChange(blockpos.up(), this); - } - - if (this.isPowered) { - world.notifyNeighborsOfStateChange(blockpos, this); - world.notifyNeighborsOfStateChange(blockpos.down(), this); - } - - } - - public abstract IProperty getShapeProperty(); - public static enum EnumRailDirection implements IStringSerializable { NORTH_SOUTH(0, "north_south"), EAST_WEST(1, "east_west"), ASCENDING_EAST(2, "ascending_east"), ASCENDING_WEST(3, "ascending_west"), ASCENDING_NORTH(4, "ascending_north"), @@ -185,7 +50,24 @@ public abstract class BlockRailBase extends Block { NORTH_WEST(8, "north_west"), NORTH_EAST(9, "north_east"); private static final BlockRailBase.EnumRailDirection[] META_LOOKUP = new BlockRailBase.EnumRailDirection[10]; + static { + BlockRailBase.EnumRailDirection[] directions = values(); + for (int i = 0; i < directions.length; ++i) { + META_LOOKUP[directions[i].getMetadata()] = directions[i]; + } + + } + + public static BlockRailBase.EnumRailDirection byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int meta; + private final String name; private EnumRailDirection(int meta, String name) { @@ -197,7 +79,7 @@ public abstract class BlockRailBase extends Block { return this.meta; } - public String toString() { + public String getName() { return this.name; } @@ -206,25 +88,9 @@ public abstract class BlockRailBase extends Block { || this == ASCENDING_WEST; } - public static BlockRailBase.EnumRailDirection byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { + public String toString() { return this.name; } - - static { - BlockRailBase.EnumRailDirection[] directions = values(); - for (int i = 0; i < directions.length; ++i) { - META_LOOKUP[directions[i].getMetadata()] = directions[i]; - } - - } } public class Rail { @@ -246,67 +112,18 @@ public abstract class BlockRailBase extends Block { this.func_180360_a(blockrailbase$enumraildirection); } - private void func_180360_a(BlockRailBase.EnumRailDirection parEnumRailDirection) { - this.field_150657_g.clear(); - switch (parEnumRailDirection) { - case NORTH_SOUTH: - this.field_150657_g.add(this.pos.north()); - this.field_150657_g.add(this.pos.south()); - break; - case EAST_WEST: - this.field_150657_g.add(this.pos.west()); - this.field_150657_g.add(this.pos.east()); - break; - case ASCENDING_EAST: - this.field_150657_g.add(this.pos.west()); - this.field_150657_g.add(this.pos.east().up()); - break; - case ASCENDING_WEST: - this.field_150657_g.add(this.pos.west().up()); - this.field_150657_g.add(this.pos.east()); - break; - case ASCENDING_NORTH: - this.field_150657_g.add(this.pos.north().up()); - this.field_150657_g.add(this.pos.south()); - break; - case ASCENDING_SOUTH: - this.field_150657_g.add(this.pos.north()); - this.field_150657_g.add(this.pos.south().up()); - break; - case SOUTH_EAST: - this.field_150657_g.add(this.pos.east()); - this.field_150657_g.add(this.pos.south()); - break; - case SOUTH_WEST: - this.field_150657_g.add(this.pos.west()); - this.field_150657_g.add(this.pos.south()); - break; - case NORTH_WEST: - this.field_150657_g.add(this.pos.west()); - this.field_150657_g.add(this.pos.north()); - break; - case NORTH_EAST: - this.field_150657_g.add(this.pos.east()); - this.field_150657_g.add(this.pos.north()); - } + protected int countAdjacentRails() { + int i = 0; - } - - private void func_150651_b() { - for (int i = 0; i < this.field_150657_g.size(); ++i) { - BlockRailBase.Rail blockrailbase$rail = this.findRailAt((BlockPos) this.field_150657_g.get(i)); - if (blockrailbase$rail != null && blockrailbase$rail.func_150653_a(this)) { - this.field_150657_g.set(i, blockrailbase$rail.pos); - } else { - this.field_150657_g.remove(i--); + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + BlockPos tmp = new BlockPos(0, 0, 0); + for (int j = 0; j < facings.length; ++j) { + if (this.hasRailAt(this.pos.offsetEvenFaster(facings[j], tmp))) { + ++i; } } - } - - private boolean hasRailAt(BlockPos pos) { - return BlockRailBase.isRailBlock(this.world, pos) || BlockRailBase.isRailBlock(this.world, pos.up()) - || BlockRailBase.isRailBlock(this.world, pos.down()); + return i; } private BlockRailBase.Rail findRailAt(BlockPos pos) { @@ -328,39 +145,6 @@ public abstract class BlockRailBase extends Block { } } - private boolean func_150653_a(BlockRailBase.Rail parRail) { - return this.func_180363_c(parRail.pos); - } - - private boolean func_180363_c(BlockPos parBlockPos) { - for (int i = 0; i < this.field_150657_g.size(); ++i) { - BlockPos blockpos = (BlockPos) this.field_150657_g.get(i); - if (blockpos.getX() == parBlockPos.getX() && blockpos.getZ() == parBlockPos.getZ()) { - return true; - } - } - - return false; - } - - protected int countAdjacentRails() { - int i = 0; - - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - BlockPos tmp = new BlockPos(0, 0, 0); - for (int j = 0; j < facings.length; ++j) { - if (this.hasRailAt(this.pos.offsetEvenFaster(facings[j], tmp))) { - ++i; - } - } - - return i; - } - - private boolean func_150649_b(BlockRailBase.Rail rail) { - return this.func_150653_a(rail) || this.field_150657_g.size() != 2; - } - private void func_150645_c(BlockRailBase.Rail parRail) { this.field_150657_g.add(parRail.pos); BlockPos blockpos = this.pos.north(); @@ -426,6 +210,72 @@ public abstract class BlockRailBase extends Block { this.world.setBlockState(this.pos, this.state, 3); } + private boolean func_150649_b(BlockRailBase.Rail rail) { + return this.func_150653_a(rail) || this.field_150657_g.size() != 2; + } + + private void func_150651_b() { + for (int i = 0; i < this.field_150657_g.size(); ++i) { + BlockRailBase.Rail blockrailbase$rail = this.findRailAt((BlockPos) this.field_150657_g.get(i)); + if (blockrailbase$rail != null && blockrailbase$rail.func_150653_a(this)) { + this.field_150657_g.set(i, blockrailbase$rail.pos); + } else { + this.field_150657_g.remove(i--); + } + } + + } + + private boolean func_150653_a(BlockRailBase.Rail parRail) { + return this.func_180363_c(parRail.pos); + } + + private void func_180360_a(BlockRailBase.EnumRailDirection parEnumRailDirection) { + this.field_150657_g.clear(); + switch (parEnumRailDirection) { + case NORTH_SOUTH: + this.field_150657_g.add(this.pos.north()); + this.field_150657_g.add(this.pos.south()); + break; + case EAST_WEST: + this.field_150657_g.add(this.pos.west()); + this.field_150657_g.add(this.pos.east()); + break; + case ASCENDING_EAST: + this.field_150657_g.add(this.pos.west()); + this.field_150657_g.add(this.pos.east().up()); + break; + case ASCENDING_WEST: + this.field_150657_g.add(this.pos.west().up()); + this.field_150657_g.add(this.pos.east()); + break; + case ASCENDING_NORTH: + this.field_150657_g.add(this.pos.north().up()); + this.field_150657_g.add(this.pos.south()); + break; + case ASCENDING_SOUTH: + this.field_150657_g.add(this.pos.north()); + this.field_150657_g.add(this.pos.south().up()); + break; + case SOUTH_EAST: + this.field_150657_g.add(this.pos.east()); + this.field_150657_g.add(this.pos.south()); + break; + case SOUTH_WEST: + this.field_150657_g.add(this.pos.west()); + this.field_150657_g.add(this.pos.south()); + break; + case NORTH_WEST: + this.field_150657_g.add(this.pos.west()); + this.field_150657_g.add(this.pos.north()); + break; + case NORTH_EAST: + this.field_150657_g.add(this.pos.east()); + this.field_150657_g.add(this.pos.north()); + } + + } + private boolean func_180361_d(BlockPos parBlockPos) { BlockRailBase.Rail blockrailbase$rail = this.findRailAt(parBlockPos); if (blockrailbase$rail == null) { @@ -436,6 +286,17 @@ public abstract class BlockRailBase extends Block { } } + private boolean func_180363_c(BlockPos parBlockPos) { + for (int i = 0; i < this.field_150657_g.size(); ++i) { + BlockPos blockpos = (BlockPos) this.field_150657_g.get(i); + if (blockpos.getX() == parBlockPos.getX() && blockpos.getZ() == parBlockPos.getZ()) { + return true; + } + } + + return false; + } + public BlockRailBase.Rail func_180364_a(boolean parFlag, boolean parFlag2) { BlockPos blockpos = this.pos.north(); BlockPos blockpos1 = this.pos.south(); @@ -564,5 +425,148 @@ public abstract class BlockRailBase extends Block { public IBlockState getBlockState() { return this.state; } + + private boolean hasRailAt(BlockPos pos) { + return BlockRailBase.isRailBlock(this.world, pos) || BlockRailBase.isRailBlock(this.world, pos.up()) + || BlockRailBase.isRailBlock(this.world, pos.down()); + } + } + + public static boolean isRailBlock(IBlockState state) { + Block block = state.getBlock(); + return block == Blocks.rail || block == Blocks.golden_rail || block == Blocks.detector_rail + || block == Blocks.activator_rail; + } + + public static boolean isRailBlock(World worldIn, BlockPos pos) { + return isRailBlock(worldIn.getBlockState(pos)); + } + + protected final boolean isPowered; + + protected BlockRailBase(boolean isPowered) { + super(Material.circuits); + this.isPowered = isPowered; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + this.setCreativeTab(CreativeTabs.tabTransport); + } + + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + super.breakBlock(world, blockpos, iblockstate); + if (((BlockRailBase.EnumRailDirection) iblockstate.getValue(this.getShapeProperty())).isAscending()) { + world.notifyNeighborsOfStateChange(blockpos.up(), this); + } + + if (this.isPowered) { + world.notifyNeighborsOfStateChange(blockpos, this); + world.notifyNeighborsOfStateChange(blockpos.down(), this); + } + + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return World.doesBlockHaveSolidTopSurface(world, blockpos.down()); + } + + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. + */ + public MovingObjectPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) { + this.setBlockBoundsBasedOnState(worldIn, pos); + return super.collisionRayTrace(worldIn, pos, start, end); + } + + protected IBlockState func_176564_a(World worldIn, BlockPos parBlockPos, IBlockState parIBlockState, + boolean parFlag) { + return worldIn.isRemote ? parIBlockState + : (new BlockRailBase.Rail(worldIn, parBlockPos, parIBlockState)) + .func_180364_a(worldIn.isBlockPowered(parBlockPos), parFlag).getBlockState(); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + public int getMobilityFlag() { + return 0; + } + + public abstract IProperty getShapeProperty(); + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) { + if (!worldIn.isRemote) { + state = this.func_176564_a(worldIn, pos, state, true); + if (this.isPowered) { + this.onNeighborBlockChange(worldIn, pos, state, this); + } + } + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + if (!world.isRemote) { + BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection) iblockstate + .getValue(this.getShapeProperty()); + boolean flag = false; + if (!World.doesBlockHaveSolidTopSurface(world, blockpos.down())) { + flag = true; + } + + if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_EAST + && !World.doesBlockHaveSolidTopSurface(world, blockpos.east())) { + flag = true; + } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_WEST + && !World.doesBlockHaveSolidTopSurface(world, blockpos.west())) { + flag = true; + } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_NORTH + && !World.doesBlockHaveSolidTopSurface(world, blockpos.north())) { + flag = true; + } else if (blockrailbase$enumraildirection == BlockRailBase.EnumRailDirection.ASCENDING_SOUTH + && !World.doesBlockHaveSolidTopSurface(world, blockpos.south())) { + flag = true; + } + + if (flag) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } else { + this.onNeighborChangedInternal(world, blockpos, iblockstate, block); + } + } + } + + protected void onNeighborChangedInternal(World worldIn, BlockPos pos, IBlockState state, Block neighborBlock) { + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + IBlockState iblockstate = iblockaccess.getBlockState(blockpos); + BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = iblockstate.getBlock() == this + ? (BlockRailBase.EnumRailDirection) iblockstate.getValue(this.getShapeProperty()) + : null; + if (blockrailbase$enumraildirection != null && blockrailbase$enumraildirection.isAscending()) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.625F, 1.0F); + } else { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRailDetector.java b/src/game/java/net/minecraft/block/BlockRailDetector.java index a92380e3..9dcc6131 100644 --- a/src/game/java/net/minecraft/block/BlockRailDetector.java +++ b/src/game/java/net/minecraft/block/BlockRailDetector.java @@ -22,22 +22,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,13 +49,6 @@ public class BlockRailDetector extends BlockRailBase { public static PropertyEnum SHAPE; public static final PropertyBool POWERED = PropertyBool.create("powered"); - public BlockRailDetector() { - super(true); - this.setDefaultState(this.blockState.getBaseState().withProperty(POWERED, Boolean.valueOf(false)) - .withProperty(SHAPE, BlockRailBase.EnumRailDirection.NORTH_SOUTH)); - this.setTickRandomly(true); - } - public static void bootstrapStates() { SHAPE = PropertyEnum.create("shape", BlockRailBase.EnumRailDirection.class, new Predicate() { @@ -65,23 +61,100 @@ public class BlockRailDetector extends BlockRailBase { }); } - /**+ - * How many world ticks before ticking - */ - public int tickRate(World var1) { - return 20; + public BlockRailDetector() { + super(true); + this.setDefaultState(this.blockState.getBaseState().withProperty(POWERED, Boolean.valueOf(false)) + .withProperty(SHAPE, BlockRailBase.EnumRailDirection.NORTH_SOUTH)); + this.setTickRandomly(true); } - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. */ public boolean canProvidePower() { return true; } - /**+ - * Called When an Entity Collided with the Block + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { SHAPE, POWERED }); + } + + protected List findMinecarts(World worldIn, BlockPos pos, Class clazz, + Predicate... filter) { + AxisAlignedBB axisalignedbb = this.getDectectionBox(pos); + return filter.length != 1 ? worldIn.getEntitiesWithinAABB(clazz, axisalignedbb) + : worldIn.getEntitiesWithinAABB(clazz, axisalignedbb, filter[0]); + } + + public int getComparatorInputOverride(World world, BlockPos blockpos) { + if (((Boolean) world.getBlockState(blockpos).getValue(POWERED)).booleanValue()) { + List list = this.findMinecarts(world, blockpos, EntityMinecartCommandBlock.class, new Predicate[0]); + if (!list.isEmpty()) { + return ((EntityMinecartCommandBlock) list.get(0)).getCommandBlockLogic().getSuccessCount(); + } + + List list1 = this.findMinecarts(world, blockpos, EntityMinecart.class, + new Predicate[] { EntitySelectors.selectInventories }); + if (!list1.isEmpty()) { + return Container.calcRedstoneFromInventory((IInventory) list1.get(0)); + } + } + + return 0; + } + + private AxisAlignedBB getDectectionBox(BlockPos pos) { + float f = 0.2F; + return new AxisAlignedBB((double) ((float) pos.getX() + 0.2F), (double) pos.getY(), + (double) ((float) pos.getZ() + 0.2F), (double) ((float) (pos.getX() + 1) - 0.2F), + (double) ((float) (pos.getY() + 1) - 0.2F), (double) ((float) (pos.getZ() + 1) - 0.2F)); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((BlockRailBase.EnumRailDirection) iblockstate.getValue(SHAPE)).getMetadata(); + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 8; + } + + return i; + } + + public IProperty getShapeProperty() { + return SHAPE; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(i & 7)) + .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); + } + + public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { + return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 : (enumfacing == EnumFacing.UP ? 15 : 0); + } + + public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { + return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; + } + + public boolean hasComparatorInputOverride() { + return true; + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + super.onBlockAdded(world, blockpos, iblockstate); + this.updatePoweredState(world, blockpos, iblockstate); + } + + /** + * + Called When an Entity Collided with the Block */ public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState iblockstate, Entity var4) { if (!world.isRemote) { @@ -91,25 +164,18 @@ public class BlockRailDetector extends BlockRailBase { } } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) */ public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { } - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - if (!world.isRemote && ((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - this.updatePoweredState(world, blockpos, iblockstate); - } - } - - public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { - return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; - } - - public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { - return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 : (enumfacing == EnumFacing.UP ? 15 : 0); + /** + * + How many world ticks before ticking + */ + public int tickRate(World var1) { + return 20; } private void updatePoweredState(World worldIn, BlockPos pos, IBlockState state) { @@ -141,72 +207,9 @@ public class BlockRailDetector extends BlockRailBase { worldIn.updateComparatorOutputLevel(pos, this); } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - super.onBlockAdded(world, blockpos, iblockstate); - this.updatePoweredState(world, blockpos, iblockstate); - } - - public IProperty getShapeProperty() { - return SHAPE; - } - - public boolean hasComparatorInputOverride() { - return true; - } - - public int getComparatorInputOverride(World world, BlockPos blockpos) { - if (((Boolean) world.getBlockState(blockpos).getValue(POWERED)).booleanValue()) { - List list = this.findMinecarts(world, blockpos, EntityMinecartCommandBlock.class, new Predicate[0]); - if (!list.isEmpty()) { - return ((EntityMinecartCommandBlock) list.get(0)).getCommandBlockLogic().getSuccessCount(); - } - - List list1 = this.findMinecarts(world, blockpos, EntityMinecart.class, - new Predicate[] { EntitySelectors.selectInventories }); - if (!list1.isEmpty()) { - return Container.calcRedstoneFromInventory((IInventory) list1.get(0)); - } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { + if (!world.isRemote && ((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + this.updatePoweredState(world, blockpos, iblockstate); } - - return 0; - } - - protected List findMinecarts(World worldIn, BlockPos pos, Class clazz, - Predicate... filter) { - AxisAlignedBB axisalignedbb = this.getDectectionBox(pos); - return filter.length != 1 ? worldIn.getEntitiesWithinAABB(clazz, axisalignedbb) - : worldIn.getEntitiesWithinAABB(clazz, axisalignedbb, filter[0]); - } - - private AxisAlignedBB getDectectionBox(BlockPos pos) { - float f = 0.2F; - return new AxisAlignedBB((double) ((float) pos.getX() + 0.2F), (double) pos.getY(), - (double) ((float) pos.getZ() + 0.2F), (double) ((float) (pos.getX() + 1) - 0.2F), - (double) ((float) (pos.getY() + 1) - 0.2F), (double) ((float) (pos.getZ() + 1) - 0.2F)); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(i & 7)) - .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((BlockRailBase.EnumRailDirection) iblockstate.getValue(SHAPE)).getMetadata(); - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { SHAPE, POWERED }); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRailPowered.java b/src/game/java/net/minecraft/block/BlockRailPowered.java index 8892b7db..aad5fe40 100644 --- a/src/game/java/net/minecraft/block/BlockRailPowered.java +++ b/src/game/java/net/minecraft/block/BlockRailPowered.java @@ -10,22 +10,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,13 +37,6 @@ public class BlockRailPowered extends BlockRailBase { public static PropertyEnum SHAPE; public static final PropertyBool POWERED = PropertyBool.create("powered"); - protected BlockRailPowered() { - super(true); - this.setDefaultState( - this.blockState.getBaseState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.NORTH_SOUTH) - .withProperty(POWERED, Boolean.valueOf(false))); - } - public static void bootstrapStates() { SHAPE = PropertyEnum.create("shape", BlockRailBase.EnumRailDirection.class, new Predicate() { @@ -53,6 +49,17 @@ public class BlockRailPowered extends BlockRailBase { }); } + protected BlockRailPowered() { + super(true); + this.setDefaultState( + this.blockState.getBaseState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.NORTH_SOUTH) + .withProperty(POWERED, Boolean.valueOf(false))); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { SHAPE, POWERED }); + } + protected boolean func_176566_a(World worldIn, BlockPos pos, IBlockState state, boolean parFlag, int parInt1) { if (parInt1 >= 8) { return false; @@ -156,6 +163,31 @@ public class BlockRailPowered extends BlockRailBase { } } + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((BlockRailBase.EnumRailDirection) iblockstate.getValue(SHAPE)).getMetadata(); + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 8; + } + + return i; + } + + public IProperty getShapeProperty() { + return SHAPE; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(i & 7)) + .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); + } + protected void onNeighborChangedInternal(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { boolean flag = ((Boolean) iblockstate.getValue(POWERED)).booleanValue(); boolean flag1 = world.isBlockPowered(blockpos) || this.func_176566_a(world, blockpos, iblockstate, true, 0) @@ -169,33 +201,4 @@ public class BlockRailPowered extends BlockRailBase { } } - - public IProperty getShapeProperty() { - return SHAPE; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(SHAPE, BlockRailBase.EnumRailDirection.byMetadata(i & 7)) - .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((BlockRailBase.EnumRailDirection) iblockstate.getValue(SHAPE)).getMetadata(); - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { SHAPE, POWERED }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedFlower.java b/src/game/java/net/minecraft/block/BlockRedFlower.java index dcddf28e..a51a67c6 100644 --- a/src/game/java/net/minecraft/block/BlockRedFlower.java +++ b/src/game/java/net/minecraft/block/BlockRedFlower.java @@ -1,28 +1,31 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockRedFlower extends BlockFlower { - /**+ - * Get the Type of this flower (Yellow/Red) + /** + * + Get the Type of this flower (Yellow/Red) */ public BlockFlower.EnumFlowerColor getBlockType() { return BlockFlower.EnumFlowerColor.RED; diff --git a/src/game/java/net/minecraft/block/BlockRedSandstone.java b/src/game/java/net/minecraft/block/BlockRedSandstone.java index 382995c7..5505d02d 100644 --- a/src/game/java/net/minecraft/block/BlockRedSandstone.java +++ b/src/game/java/net/minecraft/block/BlockRedSandstone.java @@ -12,86 +12,55 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockRedSandstone extends Block { - public static PropertyEnum TYPE; - - public BlockRedSandstone() { - super(Material.rock, BlockSand.EnumType.RED_SAND.getMapColor()); - this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockRedSandstone.EnumType.DEFAULT)); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - TYPE = PropertyEnum.create("type", BlockRedSandstone.EnumType.class); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockRedSandstone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockRedSandstone.EnumType[] types = BlockRedSandstone.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(TYPE, BlockRedSandstone.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockRedSandstone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { TYPE }); - } - public static enum EnumType implements IStringSerializable { DEFAULT(0, "red_sandstone", "default"), CHISELED(1, "chiseled_red_sandstone", "chiseled"), SMOOTH(2, "smooth_red_sandstone", "smooth"); public static final BlockRedSandstone.EnumType[] META_LOOKUP = new BlockRedSandstone.EnumType[3]; + static { + BlockRedSandstone.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockRedSandstone.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int meta; + private final String name; + private final String unlocalizedName; private EnumType(int meta, String name, String unlocalizedName) { @@ -104,18 +73,6 @@ public class BlockRedSandstone extends Block { return this.meta; } - public String toString() { - return this.name; - } - - public static BlockRedSandstone.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - public String getName() { return this.name; } @@ -124,12 +81,59 @@ public class BlockRedSandstone extends Block { return this.unlocalizedName; } - static { - BlockRedSandstone.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum TYPE; + + public static void bootstrapStates() { + TYPE = PropertyEnum.create("type", BlockRedSandstone.EnumType.class); + } + + public BlockRedSandstone() { + super(Material.rock, BlockSand.EnumType.RED_SAND.getMapColor()); + this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockRedSandstone.EnumType.DEFAULT)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { TYPE }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockRedSandstone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockRedSandstone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(TYPE, BlockRedSandstone.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockRedSandstone.EnumType[] types = BlockRedSandstone.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneComparator.java b/src/game/java/net/minecraft/block/BlockRedstoneComparator.java index 5a4fe875..1d40a335 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneComparator.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneComparator.java @@ -1,10 +1,10 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.base.Predicate; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -28,30 +28,56 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITileEntityProvider { + public static enum Mode implements IStringSerializable { + COMPARE("compare"), SUBTRACT("subtract"); + + private final String name; + + private Mode(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static final PropertyBool POWERED = PropertyBool.create("powered"); + public static PropertyEnum MODE; + public static void bootstrapStates() { + MODE = PropertyEnum.create("mode", BlockRedstoneComparator.Mode.class); + } + public BlockRedstoneComparator(boolean powered) { super(powered); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH) @@ -60,77 +86,10 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile this.isBlockContainer = true; } - public static void bootstrapStates() { - MODE = PropertyEnum.create("mode", BlockRedstoneComparator.Mode.class); - } - - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal("item.comparator.name"); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.comparator; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.comparator; - } - - protected int getDelay(IBlockState state) { - return 2; - } - - protected IBlockState getPoweredState(IBlockState unpoweredState) { - Boolean obool = (Boolean) unpoweredState.getValue(POWERED); - BlockRedstoneComparator.Mode blockredstonecomparator$mode = (BlockRedstoneComparator.Mode) unpoweredState - .getValue(MODE); - EnumFacing enumfacing = (EnumFacing) unpoweredState.getValue(FACING); - return Blocks.powered_comparator.getDefaultState().withProperty(FACING, enumfacing).withProperty(POWERED, obool) - .withProperty(MODE, blockredstonecomparator$mode); - } - - protected IBlockState getUnpoweredState(IBlockState poweredState) { - Boolean obool = (Boolean) poweredState.getValue(POWERED); - BlockRedstoneComparator.Mode blockredstonecomparator$mode = (BlockRedstoneComparator.Mode) poweredState - .getValue(MODE); - EnumFacing enumfacing = (EnumFacing) poweredState.getValue(FACING); - return Blocks.unpowered_comparator.getDefaultState().withProperty(FACING, enumfacing) - .withProperty(POWERED, obool).withProperty(MODE, blockredstonecomparator$mode); - } - - protected boolean isPowered(IBlockState state) { - return this.isRepeaterPowered || ((Boolean) state.getValue(POWERED)).booleanValue(); - } - - protected int getActiveSignal(IBlockAccess worldIn, BlockPos pos, IBlockState state) { - TileEntity tileentity = worldIn.getTileEntity(pos); - return tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).getOutputSignal() : 0; - } - - private int calculateOutput(World worldIn, BlockPos pos, IBlockState state) { - return state.getValue(MODE) == BlockRedstoneComparator.Mode.SUBTRACT - ? Math.max(this.calculateInputStrength(worldIn, pos, state) - this.getPowerOnSides(worldIn, pos, state), - 0) - : this.calculateInputStrength(worldIn, pos, state); - } - - protected boolean shouldBePowered(World worldIn, BlockPos pos, IBlockState state) { - int i = this.calculateInputStrength(worldIn, pos, state); - if (i >= 15) { - return true; - } else if (i == 0) { - return false; - } else { - int j = this.getPowerOnSides(worldIn, pos, state); - return j == 0 ? true : i >= j; - } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + super.breakBlock(world, blockpos, iblockstate); + world.removeTileEntity(blockpos); + this.notifyNeighbors(world, blockpos, iblockstate); } protected int calculateInputStrength(World worldIn, BlockPos pos, IBlockState state) { @@ -156,6 +115,25 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile return i; } + private int calculateOutput(World worldIn, BlockPos pos, IBlockState state) { + return state.getValue(MODE) == BlockRedstoneComparator.Mode.SUBTRACT + ? Math.max(this.calculateInputStrength(worldIn, pos, state) - this.getPowerOnSides(worldIn, pos, state), + 0) + : this.calculateInputStrength(worldIn, pos, state); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, MODE, POWERED }); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntityComparator(); + } + private EntityItemFrame findItemFrame(World worldIn, final EnumFacing facing, BlockPos pos) { List list = worldIn.getEntitiesWithinAABB(EntityItemFrame.class, new AxisAlignedBB((double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), @@ -168,6 +146,81 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile return list.size() == 1 ? (EntityItemFrame) list.get(0) : null; } + protected int getActiveSignal(IBlockAccess worldIn, BlockPos pos, IBlockState state) { + TileEntity tileentity = worldIn.getTileEntity(pos); + return tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).getOutputSignal() : 0; + } + + protected int getDelay(IBlockState state) { + return 2; + } + + public Item getItem(World var1, BlockPos var2) { + return Items.comparator; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.comparator; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal("item.comparator.name"); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 8; + } + + if (iblockstate.getValue(MODE) == BlockRedstoneComparator.Mode.SUBTRACT) { + i |= 4; + } + + return i; + } + + protected IBlockState getPoweredState(IBlockState unpoweredState) { + Boolean obool = (Boolean) unpoweredState.getValue(POWERED); + BlockRedstoneComparator.Mode blockredstonecomparator$mode = (BlockRedstoneComparator.Mode) unpoweredState + .getValue(MODE); + EnumFacing enumfacing = (EnumFacing) unpoweredState.getValue(FACING); + return Blocks.powered_comparator.getDefaultState().withProperty(FACING, enumfacing).withProperty(POWERED, obool) + .withProperty(MODE, blockredstonecomparator$mode); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)) + .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)).withProperty(MODE, + (i & 4) > 0 ? BlockRedstoneComparator.Mode.SUBTRACT : BlockRedstoneComparator.Mode.COMPARE); + } + + protected IBlockState getUnpoweredState(IBlockState poweredState) { + Boolean obool = (Boolean) poweredState.getValue(POWERED); + BlockRedstoneComparator.Mode blockredstonecomparator$mode = (BlockRedstoneComparator.Mode) poweredState + .getValue(MODE); + EnumFacing enumfacing = (EnumFacing) poweredState.getValue(FACING); + return Blocks.unpowered_comparator.getDefaultState().withProperty(FACING, enumfacing) + .withProperty(POWERED, obool).withProperty(MODE, blockredstonecomparator$mode); + } + + protected boolean isPowered(IBlockState state) { + return this.isRepeaterPowered || ((Boolean) state.getValue(POWERED)).booleanValue(); + } + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, EnumFacing var5, float var6, float var7, float var8) { if (!entityplayer.capabilities.allowEdit) { @@ -183,21 +236,28 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile } } - protected void updateState(World worldIn, BlockPos pos, IBlockState state) { - if (!worldIn.isBlockTickPending(pos, this)) { - int i = this.calculateOutput(worldIn, pos, state); - TileEntity tileentity = worldIn.getTileEntity(pos); - int j = tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).getOutputSignal() - : 0; - if (i != j || this.isPowered(state) != this.shouldBePowered(worldIn, pos, state)) { - if (this.isFacingTowardsRepeater(worldIn, pos, state)) { - worldIn.updateBlockTick(pos, this, 2, -1); - } else { - worldIn.updateBlockTick(pos, this, 2, 0); - } - } + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + super.onBlockAdded(world, blockpos, iblockstate); + world.setTileEntity(blockpos, this.createNewTileEntity(world, 0)); + } - } + /** + * + Called on both Client and Server when World#addBlockEvent is called + */ + public boolean onBlockEventReceived(World world, BlockPos blockpos, IBlockState iblockstate, int i, int j) { + super.onBlockEventReceived(world, blockpos, iblockstate, i, j); + TileEntity tileentity = world.getTileEntity(blockpos); + return tileentity == null ? false : tileentity.receiveClientEvent(i, j); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()) + .withProperty(POWERED, Boolean.valueOf(false)).withProperty(MODE, BlockRedstoneComparator.Mode.COMPARE); } private void onStateChange(World worldIn, BlockPos pos, IBlockState state) { @@ -224,6 +284,35 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile } + protected boolean shouldBePowered(World worldIn, BlockPos pos, IBlockState state) { + int i = this.calculateInputStrength(worldIn, pos, state); + if (i >= 15) { + return true; + } else if (i == 0) { + return false; + } else { + int j = this.getPowerOnSides(worldIn, pos, state); + return j == 0 ? true : i >= j; + } + } + + protected void updateState(World worldIn, BlockPos pos, IBlockState state) { + if (!worldIn.isBlockTickPending(pos, this)) { + int i = this.calculateOutput(worldIn, pos, state); + TileEntity tileentity = worldIn.getTileEntity(pos); + int j = tileentity instanceof TileEntityComparator ? ((TileEntityComparator) tileentity).getOutputSignal() + : 0; + if (i != j || this.isPowered(state) != this.shouldBePowered(worldIn, pos, state)) { + if (this.isFacingTowardsRepeater(worldIn, pos, state)) { + worldIn.updateBlockTick(pos, this, 2, -1); + } else { + worldIn.updateBlockTick(pos, this, 2, 0); + } + } + + } + } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { if (this.isRepeaterPowered) { world.setBlockState(blockpos, @@ -232,91 +321,4 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile this.onStateChange(world, blockpos, iblockstate); } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - super.onBlockAdded(world, blockpos, iblockstate); - world.setTileEntity(blockpos, this.createNewTileEntity(world, 0)); - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - super.breakBlock(world, blockpos, iblockstate); - world.removeTileEntity(blockpos); - this.notifyNeighbors(world, blockpos, iblockstate); - } - - /**+ - * Called on both Client and Server when World#addBlockEvent is - * called - */ - public boolean onBlockEventReceived(World world, BlockPos blockpos, IBlockState iblockstate, int i, int j) { - super.onBlockEventReceived(world, blockpos, iblockstate, i, j); - TileEntity tileentity = world.getTileEntity(blockpos); - return tileentity == null ? false : tileentity.receiveClientEvent(i, j); - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntityComparator(); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)) - .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)).withProperty(MODE, - (i & 4) > 0 ? BlockRedstoneComparator.Mode.SUBTRACT : BlockRedstoneComparator.Mode.COMPARE); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 8; - } - - if (iblockstate.getValue(MODE) == BlockRedstoneComparator.Mode.SUBTRACT) { - i |= 4; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, MODE, POWERED }); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()) - .withProperty(POWERED, Boolean.valueOf(false)).withProperty(MODE, BlockRedstoneComparator.Mode.COMPARE); - } - - public static enum Mode implements IStringSerializable { - COMPARE("compare"), SUBTRACT("subtract"); - - private final String name; - - private Mode(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneDiode.java b/src/game/java/net/minecraft/block/BlockRedstoneDiode.java index ad1e76e6..6818054b 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneDiode.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneDiode.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EntityLivingBase; @@ -13,27 +12,34 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockRedstoneDiode extends BlockDirectional { + public static boolean isRedstoneRepeaterBlockID(Block blockIn) { + return Blocks.unpowered_repeater.isAssociated(blockIn) || Blocks.unpowered_comparator.isAssociated(blockIn); + } + protected final boolean isRepeaterPowered; protected BlockRedstoneDiode(boolean powered) { @@ -42,8 +48,23 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); } - public boolean isFullCube() { - return false; + protected int calculateInputStrength(World world, BlockPos blockpos, IBlockState iblockstate) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + BlockPos blockpos1 = blockpos.offset(enumfacing); + int i = world.getRedstonePower(blockpos1, enumfacing); + if (i >= 15) { + return i; + } else { + IBlockState iblockstate1 = world.getBlockState(blockpos1); + return Math.max(i, + iblockstate1.getBlock() == Blocks.redstone_wire + ? ((Integer) iblockstate1.getValue(BlockRedstoneWire.POWER)).intValue() + : 0); + } + } + + public boolean canBlockStay(World worldIn, BlockPos pos) { + return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()); } public boolean canPlaceBlockAt(World world, BlockPos blockpos) { @@ -51,39 +72,45 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { : false; } - public boolean canBlockStay(World worldIn, BlockPos pos) { - return World.doesBlockHaveSolidTopSurface(worldIn, pos.down()); + protected boolean canPowerSide(Block blockIn) { + return blockIn.canProvidePower(); } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. */ - public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { + public boolean canProvidePower() { + return true; } - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - if (!this.isLocked(world, blockpos, iblockstate)) { - boolean flag = this.shouldBePowered(world, blockpos, iblockstate); - if (this.isRepeaterPowered && !flag) { - world.setBlockState(blockpos, this.getUnpoweredState(iblockstate), 2); - } else if (!this.isRepeaterPowered) { - world.setBlockState(blockpos, this.getPoweredState(iblockstate), 2); - if (!flag) { - world.updateBlockTick(blockpos, this.getPoweredState(iblockstate).getBlock(), - this.getTickDelay(iblockstate), -1); - } - } - - } + protected int getActiveSignal(IBlockAccess var1, BlockPos var2, IBlockState var3) { + return 15; } - public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing enumfacing) { - return enumfacing.getAxis() != EnumFacing.Axis.Y; + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; } - protected boolean isPowered(IBlockState var1) { - return this.isRepeaterPowered; + protected abstract int getDelay(IBlockState var1); + + protected abstract IBlockState getPoweredState(IBlockState var1); + + protected int getPowerOnSide(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { + IBlockState iblockstate = worldIn.getBlockState(pos); + Block block = iblockstate.getBlock(); + return this.canPowerSide(block) + ? (block == Blocks.redstone_wire ? ((Integer) iblockstate.getValue(BlockRedstoneWire.POWER)).intValue() + : worldIn.getStrongPower(pos, side)) + : 0; + } + + protected int getPowerOnSides(IBlockAccess worldIn, BlockPos pos, IBlockState state) { + EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); + EnumFacing enumfacing1 = enumfacing.rotateY(); + EnumFacing enumfacing2 = enumfacing.rotateYCCW(); + return Math.max(this.getPowerOnSide(worldIn, pos.offset(enumfacing1), enumfacing1), + this.getPowerOnSide(worldIn, pos.offset(enumfacing2), enumfacing2)); } public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, @@ -91,6 +118,12 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { return this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing); } + protected int getTickDelay(IBlockState state) { + return this.getDelay(state); + } + + protected abstract IBlockState getUnpoweredState(IBlockState var1); + public int getWeakPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, EnumFacing enumfacing) { return !this.isPowered(iblockstate) ? 0 @@ -99,8 +132,92 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { : 0); } - /**+ - * Called when a neighboring block changes. + public boolean isAssociated(Block other) { + return other == this.getPoweredState(this.getDefaultState()).getBlock() + || other == this.getUnpoweredState(this.getDefaultState()).getBlock(); + } + + public boolean isAssociatedBlock(Block block) { + return this.isAssociated(block); + } + + public boolean isFacingTowardsRepeater(World worldIn, BlockPos pos, IBlockState state) { + EnumFacing enumfacing = ((EnumFacing) state.getValue(FACING)).getOpposite(); + BlockPos blockpos = pos.offset(enumfacing); + return isRedstoneRepeaterBlockID(worldIn.getBlockState(blockpos).getBlock()) + ? worldIn.getBlockState(blockpos).getValue(FACING) != enumfacing + : false; + } + + public boolean isFullCube() { + return false; + } + + public boolean isLocked(IBlockAccess worldIn, BlockPos pos, IBlockState state) { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + protected boolean isPowered(IBlockState var1) { + return this.isRepeaterPowered; + } + + protected void notifyNeighbors(World worldIn, BlockPos pos, IBlockState state) { + EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); + BlockPos blockpos = pos.offset(enumfacing.getOpposite()); + worldIn.notifyBlockOfStateChange(blockpos, this); + worldIn.notifyNeighborsOfStateExcept(blockpos, this, enumfacing); + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + this.notifyNeighbors(world, blockpos, iblockstate); + } + + /** + * + Called when a player destroys this Block + */ + public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { + if (this.isRepeaterPowered) { + EnumFacing[] facings = EnumFacing._VALUES; + BlockPos tmp = new BlockPos(0, 0, 0); + for (int i = 0; i < facings.length; ++i) { + world.notifyNeighborsOfStateChange(blockpos.offsetEvenFaster(facings[i], tmp), this); + } + } + + super.onBlockDestroyedByPlayer(world, blockpos, iblockstate); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, EntityLivingBase var4, + ItemStack var5) { + if (this.shouldBePowered(world, blockpos, iblockstate)) { + world.scheduleUpdate(blockpos, this, 1); + } + + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { if (this.canBlockStay(world, blockpos)) { @@ -118,6 +235,21 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { } } + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) + */ + public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { + } + + protected boolean shouldBePowered(World world, BlockPos blockpos, IBlockState iblockstate) { + return this.calculateInputStrength(world, blockpos, iblockstate) > 0; + } + + public boolean shouldSideBeRendered(IBlockAccess var1, BlockPos var2, EnumFacing enumfacing) { + return enumfacing.getAxis() != EnumFacing.Axis.Y; + } + protected void updateState(World world, BlockPos blockpos, IBlockState iblockstate) { if (!this.isLocked(world, blockpos, iblockstate)) { boolean flag = this.shouldBePowered(world, blockpos, iblockstate); @@ -136,149 +268,19 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { } } - public boolean isLocked(IBlockAccess worldIn, BlockPos pos, IBlockState state) { - return false; - } - - protected boolean shouldBePowered(World world, BlockPos blockpos, IBlockState iblockstate) { - return this.calculateInputStrength(world, blockpos, iblockstate) > 0; - } - - protected int calculateInputStrength(World world, BlockPos blockpos, IBlockState iblockstate) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - BlockPos blockpos1 = blockpos.offset(enumfacing); - int i = world.getRedstonePower(blockpos1, enumfacing); - if (i >= 15) { - return i; - } else { - IBlockState iblockstate1 = world.getBlockState(blockpos1); - return Math.max(i, - iblockstate1.getBlock() == Blocks.redstone_wire - ? ((Integer) iblockstate1.getValue(BlockRedstoneWire.POWER)).intValue() - : 0); - } - } - - protected int getPowerOnSides(IBlockAccess worldIn, BlockPos pos, IBlockState state) { - EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); - EnumFacing enumfacing1 = enumfacing.rotateY(); - EnumFacing enumfacing2 = enumfacing.rotateYCCW(); - return Math.max(this.getPowerOnSide(worldIn, pos.offset(enumfacing1), enumfacing1), - this.getPowerOnSide(worldIn, pos.offset(enumfacing2), enumfacing2)); - } - - protected int getPowerOnSide(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { - IBlockState iblockstate = worldIn.getBlockState(pos); - Block block = iblockstate.getBlock(); - return this.canPowerSide(block) - ? (block == Blocks.redstone_wire ? ((Integer) iblockstate.getValue(BlockRedstoneWire.POWER)).intValue() - : worldIn.getStrongPower(pos, side)) - : 0; - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return true; - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing().getOpposite()); - } - - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic - */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, EntityLivingBase var4, - ItemStack var5) { - if (this.shouldBePowered(world, blockpos, iblockstate)) { - world.scheduleUpdate(blockpos, this, 1); - } - - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - this.notifyNeighbors(world, blockpos, iblockstate); - } - - protected void notifyNeighbors(World worldIn, BlockPos pos, IBlockState state) { - EnumFacing enumfacing = (EnumFacing) state.getValue(FACING); - BlockPos blockpos = pos.offset(enumfacing.getOpposite()); - worldIn.notifyBlockOfStateChange(blockpos, this); - worldIn.notifyNeighborsOfStateExcept(blockpos, this, enumfacing); - } - - /**+ - * Called when a player destroys this Block - */ - public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { - if (this.isRepeaterPowered) { - EnumFacing[] facings = EnumFacing._VALUES; - BlockPos tmp = new BlockPos(0, 0, 0); - for (int i = 0; i < facings.length; ++i) { - world.notifyNeighborsOfStateChange(blockpos.offsetEvenFaster(facings[i], tmp), this); + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { + if (!this.isLocked(world, blockpos, iblockstate)) { + boolean flag = this.shouldBePowered(world, blockpos, iblockstate); + if (this.isRepeaterPowered && !flag) { + world.setBlockState(blockpos, this.getUnpoweredState(iblockstate), 2); + } else if (!this.isRepeaterPowered) { + world.setBlockState(blockpos, this.getPoweredState(iblockstate), 2); + if (!flag) { + world.updateBlockTick(blockpos, this.getPoweredState(iblockstate).getBlock(), + this.getTickDelay(iblockstate), -1); + } } + } - - super.onBlockDestroyedByPlayer(world, blockpos, iblockstate); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - protected boolean canPowerSide(Block blockIn) { - return blockIn.canProvidePower(); - } - - protected int getActiveSignal(IBlockAccess var1, BlockPos var2, IBlockState var3) { - return 15; - } - - public static boolean isRedstoneRepeaterBlockID(Block blockIn) { - return Blocks.unpowered_repeater.isAssociated(blockIn) || Blocks.unpowered_comparator.isAssociated(blockIn); - } - - public boolean isAssociated(Block other) { - return other == this.getPoweredState(this.getDefaultState()).getBlock() - || other == this.getUnpoweredState(this.getDefaultState()).getBlock(); - } - - public boolean isFacingTowardsRepeater(World worldIn, BlockPos pos, IBlockState state) { - EnumFacing enumfacing = ((EnumFacing) state.getValue(FACING)).getOpposite(); - BlockPos blockpos = pos.offset(enumfacing); - return isRedstoneRepeaterBlockID(worldIn.getBlockState(blockpos).getBlock()) - ? worldIn.getBlockState(blockpos).getValue(FACING) != enumfacing - : false; - } - - protected int getTickDelay(IBlockState state) { - return this.getDelay(state); - } - - protected abstract int getDelay(IBlockState var1); - - protected abstract IBlockState getPoweredState(IBlockState var1); - - protected abstract IBlockState getUnpoweredState(IBlockState var1); - - public boolean isAssociatedBlock(Block block) { - return this.isAssociated(block); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneLight.java b/src/game/java/net/minecraft/block/BlockRedstoneLight.java index 6257f03a..15f8e04a 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneLight.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneLight.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -10,22 +9,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,6 +44,21 @@ public class BlockRedstoneLight extends Block { } + protected ItemStack createStackedBlock(IBlockState var1) { + return new ItemStack(Blocks.redstone_lamp); + } + + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(Blocks.redstone_lamp); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.redstone_lamp); + } + public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { if (!world.isRemote) { if (this.isOn && !world.isBlockPowered(blockpos)) { @@ -52,8 +69,8 @@ public class BlockRedstoneLight extends Block { } } - /**+ - * Called when a neighboring block changes. + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState var3, Block var4) { if (!world.isRemote) { @@ -72,19 +89,4 @@ public class BlockRedstoneLight extends Block { } } } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.redstone_lamp); - } - - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(Blocks.redstone_lamp); - } - - protected ItemStack createStackedBlock(IBlockState var1) { - return new ItemStack(Blocks.redstone_lamp); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneOre.java b/src/game/java/net/minecraft/block/BlockRedstoneOre.java index 80d426fe..a7c8edc3 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneOre.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneOre.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -15,22 +14,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,33 +49,6 @@ public class BlockRedstoneOre extends Block { this.isOn = isOn; } - /**+ - * How many world ticks before ticking - */ - public int tickRate(World var1) { - return 30; - } - - public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer entityplayer) { - this.activate(world, blockpos); - super.onBlockClicked(world, blockpos, entityplayer); - } - - /**+ - * Triggered whenever an entity collides with this block (enters - * into the block) - */ - public void onEntityCollidedWithBlock(World world, BlockPos blockpos, Entity entity) { - this.activate(world, blockpos); - super.onEntityCollidedWithBlock(world, blockpos, entity); - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, - EnumFacing enumfacing, float f, float f1, float f2) { - this.activate(world, blockpos); - return super.onBlockActivated(world, blockpos, iblockstate, entityplayer, enumfacing, f, f1, f2); - } - private void activate(World worldIn, BlockPos pos) { this.spawnParticles(worldIn, pos); if (this == Blocks.redstone_ore) { @@ -82,36 +57,12 @@ public class BlockRedstoneOre extends Block { } - public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { - if (this == Blocks.lit_redstone_ore) { - world.setBlockState(blockpos, Blocks.redstone_ore.getDefaultState()); - } - + protected ItemStack createStackedBlock(IBlockState var1) { + return new ItemStack(Blocks.redstone_ore); } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.redstone; - } - - /**+ - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { - return this.quantityDropped(random) + random.nextInt(i + 1); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom random) { - return 4 + random.nextInt(2); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. + /** + * + Spawns this Block's drops into the World as EntityItems. */ public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); @@ -122,6 +73,47 @@ public class BlockRedstoneOre extends Block { } + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.redstone; + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, + EnumFacing enumfacing, float f, float f1, float f2) { + this.activate(world, blockpos); + return super.onBlockActivated(world, blockpos, iblockstate, entityplayer, enumfacing, f, f1, f2); + } + + public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer entityplayer) { + this.activate(world, blockpos); + super.onBlockClicked(world, blockpos, entityplayer); + } + + /** + * + Triggered whenever an entity collides with this block (enters into the + * block) + */ + public void onEntityCollidedWithBlock(World world, BlockPos blockpos, Entity entity) { + this.activate(world, blockpos); + super.onEntityCollidedWithBlock(world, blockpos, entity); + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom random) { + return 4 + random.nextInt(2); + } + + /** + * + Get the quantity dropped based on the given fortune level + */ + public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { + return this.quantityDropped(random) + random.nextInt(i + 1); + } + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { if (this.isOn) { this.spawnParticles(world, blockpos); @@ -169,7 +161,17 @@ public class BlockRedstoneOre extends Block { } - protected ItemStack createStackedBlock(IBlockState var1) { - return new ItemStack(Blocks.redstone_ore); + /** + * + How many world ticks before ticking + */ + public int tickRate(World var1) { + return 30; + } + + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { + if (this == Blocks.lit_redstone_ore) { + world.setBlockState(blockpos, Blocks.redstone_ore.getDefaultState()); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneRepeater.java b/src/game/java/net/minecraft/block/BlockRedstoneRepeater.java index 92f498bb..239d1347 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneRepeater.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneRepeater.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.properties.PropertyInteger; @@ -18,22 +17,25 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,37 +50,59 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode { .withProperty(DELAY, Integer.valueOf(1)).withProperty(LOCKED, Boolean.valueOf(false))); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal("item.diode.name"); + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + super.breakBlock(world, blockpos, iblockstate); + this.notifyNeighbors(world, blockpos, iblockstate); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + protected boolean canPowerSide(Block block) { + return isRedstoneRepeaterBlockID(block); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, DELAY, LOCKED }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { return iblockstate.withProperty(LOCKED, Boolean.valueOf(this.isLocked(iblockaccess, blockpos, iblockstate))); } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (!entityplayer.capabilities.allowEdit) { - return false; - } else { - world.setBlockState(blockpos, iblockstate.cycleProperty(DELAY), 3); - return true; - } - } - protected int getDelay(IBlockState iblockstate) { return ((Integer) iblockstate.getValue(DELAY)).intValue() * 2; } + public Item getItem(World var1, BlockPos var2) { + return Items.repeater; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.repeater; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal("item.diode.name"); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + i = i | ((Integer) iblockstate.getValue(DELAY)).intValue() - 1 << 2; + return i; + } + protected IBlockState getPoweredState(IBlockState iblockstate) { Integer integer = (Integer) iblockstate.getValue(DELAY); Boolean obool = (Boolean) iblockstate.getValue(LOCKED); @@ -87,6 +111,14 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode { .withProperty(LOCKED, obool); } + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)) + .withProperty(LOCKED, Boolean.valueOf(false)).withProperty(DELAY, Integer.valueOf(1 + (i >> 2))); + } + protected IBlockState getUnpoweredState(IBlockState iblockstate) { Integer integer = (Integer) iblockstate.getValue(DELAY); Boolean obool = (Boolean) iblockstate.getValue(LOCKED); @@ -95,23 +127,18 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode { .withProperty(LOCKED, obool); } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.repeater; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.repeater; - } - public boolean isLocked(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate) { return this.getPowerOnSides(iblockaccess, blockpos, iblockstate) > 0; } - protected boolean canPowerSide(Block block) { - return isRedstoneRepeaterBlockID(block); + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (!entityplayer.capabilities.allowEdit) { + return false; + } else { + world.setBlockState(blockpos, iblockstate.cycleProperty(DELAY), 3); + return true; + } } public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -131,31 +158,4 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode { world.spawnParticle(EnumParticleTypes.REDSTONE, d0 + d3, d1, d2 + d4, 0.0D, 0.0D, 0.0D, new int[0]); } } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - super.breakBlock(world, blockpos, iblockstate); - this.notifyNeighbors(world, blockpos, iblockstate); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i)) - .withProperty(LOCKED, Boolean.valueOf(false)).withProperty(DELAY, Integer.valueOf(1 + (i >> 2))); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - i = i | ((Integer) iblockstate.getValue(DELAY)).intValue() - 1 << 2; - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, DELAY, LOCKED }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneTorch.java b/src/game/java/net/minecraft/block/BlockRedstoneTorch.java index 507ea71f..ae32070b 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneTorch.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneTorch.java @@ -2,11 +2,11 @@ package net.minecraft.block; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; @@ -17,30 +17,93 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockRedstoneTorch extends BlockTorch { + static class Toggle { + BlockPos pos; + long time; + + public Toggle(BlockPos pos, long time) { + this.pos = pos; + this.time = time; + } + } + private static Map> toggles = Maps.newHashMap(); + private final boolean isOn; + protected BlockRedstoneTorch(boolean isOn) { + this.isOn = isOn; + this.setTickRandomly(true); + this.setCreativeTab((CreativeTabs) null); + } + + public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { + if (this.isOn) { + EnumFacing[] facings = EnumFacing._VALUES; + BlockPos tmp = new BlockPos(0, 0, 0); + for (int i = 0; i < facings.length; ++i) { + world.notifyNeighborsOfStateChange(blockpos.offsetEvenFaster(facings[i], tmp), this); + } + } + + } + + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. + */ + public boolean canProvidePower() { + return true; + } + + public Item getItem(World var1, BlockPos var2) { + return Item.getItemFromBlock(Blocks.redstone_torch); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.redstone_torch); + } + + public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, + EnumFacing enumfacing) { + return enumfacing == EnumFacing.DOWN ? this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing) : 0; + } + + public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { + return this.isOn && iblockstate.getValue(FACING) != enumfacing ? 15 : 0; + } + + public boolean isAssociatedBlock(Block block) { + return block == Blocks.unlit_redstone_torch || block == Blocks.redstone_torch; + } + private boolean isBurnedOut(World worldIn, BlockPos pos, boolean turnOff) { if (!toggles.containsKey(worldIn)) { toggles.put(worldIn, Lists.newArrayList()); @@ -66,19 +129,6 @@ public class BlockRedstoneTorch extends BlockTorch { return false; } - protected BlockRedstoneTorch(boolean isOn) { - this.isOn = isOn; - this.setTickRandomly(true); - this.setCreativeTab((CreativeTabs) null); - } - - /**+ - * How many world ticks before ticking - */ - public int tickRate(World var1) { - return 2; - } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { if (this.isOn) { EnumFacing[] facings = EnumFacing._VALUES; @@ -90,19 +140,41 @@ public class BlockRedstoneTorch extends BlockTorch { } - public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { - if (this.isOn) { - EnumFacing[] facings = EnumFacing._VALUES; - BlockPos tmp = new BlockPos(0, 0, 0); - for (int i = 0; i < facings.length; ++i) { - world.notifyNeighborsOfStateChange(blockpos.offsetEvenFaster(facings[i], tmp), this); + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!this.onNeighborChangeInternal(world, blockpos, iblockstate)) { + if (this.isOn == this.shouldBeOff(world, blockpos, iblockstate)) { + world.scheduleUpdate(blockpos, this, this.tickRate(world)); } - } + } } - public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { - return this.isOn && iblockstate.getValue(FACING) != enumfacing ? 15 : 0; + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + if (this.isOn) { + double d0 = (double) blockpos.getX() + 0.5D + (random.nextDouble() - 0.5D) * 0.2D; + double d1 = (double) blockpos.getY() + 0.7D + (random.nextDouble() - 0.5D) * 0.2D; + double d2 = (double) blockpos.getZ() + 0.5D + (random.nextDouble() - 0.5D) * 0.2D; + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (enumfacing.getAxis().isHorizontal()) { + EnumFacing enumfacing1 = enumfacing.getOpposite(); + double d3 = 0.27D; + d0 += 0.27D * (double) enumfacing1.getFrontOffsetX(); + d1 += 0.22D; + d2 += 0.27D * (double) enumfacing1.getFrontOffsetZ(); + } + + world.spawnParticle(EnumParticleTypes.REDSTONE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) + */ + public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { } private boolean shouldBeOff(World worldIn, BlockPos pos, IBlockState state) { @@ -110,11 +182,11 @@ public class BlockRedstoneTorch extends BlockTorch { return worldIn.isSidePowered(pos.offset(enumfacing), enumfacing); } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) + /** + * + How many world ticks before ticking */ - public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { + public int tickRate(World var1) { + return 2; } public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -151,72 +223,4 @@ public class BlockRedstoneTorch extends BlockTorch { } } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (!this.onNeighborChangeInternal(world, blockpos, iblockstate)) { - if (this.isOn == this.shouldBeOff(world, blockpos, iblockstate)) { - world.scheduleUpdate(blockpos, this, this.tickRate(world)); - } - - } - } - - public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, - EnumFacing enumfacing) { - return enumfacing == EnumFacing.DOWN ? this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing) : 0; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.redstone_torch); - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return true; - } - - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - if (this.isOn) { - double d0 = (double) blockpos.getX() + 0.5D + (random.nextDouble() - 0.5D) * 0.2D; - double d1 = (double) blockpos.getY() + 0.7D + (random.nextDouble() - 0.5D) * 0.2D; - double d2 = (double) blockpos.getZ() + 0.5D + (random.nextDouble() - 0.5D) * 0.2D; - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (enumfacing.getAxis().isHorizontal()) { - EnumFacing enumfacing1 = enumfacing.getOpposite(); - double d3 = 0.27D; - d0 += 0.27D * (double) enumfacing1.getFrontOffsetX(); - d1 += 0.22D; - d2 += 0.27D * (double) enumfacing1.getFrontOffsetZ(); - } - - world.spawnParticle(EnumParticleTypes.REDSTONE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - public Item getItem(World var1, BlockPos var2) { - return Item.getItemFromBlock(Blocks.redstone_torch); - } - - public boolean isAssociatedBlock(Block block) { - return block == Blocks.unlit_redstone_torch || block == Blocks.redstone_torch; - } - - static class Toggle { - BlockPos pos; - long time; - - public Toggle(BlockPos pos, long time) { - this.pos = pos; - this.time = time; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRedstoneWire.java b/src/game/java/net/minecraft/block/BlockRedstoneWire.java index e9ea362a..35981a32 100644 --- a/src/game/java/net/minecraft/block/BlockRedstoneWire.java +++ b/src/game/java/net/minecraft/block/BlockRedstoneWire.java @@ -2,12 +2,12 @@ package net.minecraft.block; import java.util.ArrayList; import java.util.EnumSet; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Set; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -27,35 +27,89 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockRedstoneWire extends Block { + static enum EnumAttachPosition implements IStringSerializable { + UP("up"), SIDE("side"), NONE("none"); + + private final String name; + + private EnumAttachPosition(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.getName(); + } + } + public static PropertyEnum NORTH; public static PropertyEnum EAST; public static PropertyEnum SOUTH; public static PropertyEnum WEST; public static final PropertyInteger POWER = PropertyInteger.create("power", 0, 15); + + public static void bootstrapStates() { + NORTH = PropertyEnum.create("north", + BlockRedstoneWire.EnumAttachPosition.class); + EAST = PropertyEnum.create("east", + BlockRedstoneWire.EnumAttachPosition.class); + SOUTH = PropertyEnum.create("south", + BlockRedstoneWire.EnumAttachPosition.class); + WEST = PropertyEnum.create("west", + BlockRedstoneWire.EnumAttachPosition.class); + } + + protected static boolean canConnectTo(IBlockState blockState, EnumFacing side) { + Block block = blockState.getBlock(); + if (block == Blocks.redstone_wire) { + return true; + } else if (Blocks.unpowered_repeater.isAssociated(block)) { + EnumFacing enumfacing = (EnumFacing) blockState.getValue(BlockRedstoneRepeater.FACING); + return enumfacing == side || enumfacing.getOpposite() == side; + } else { + return block.canProvidePower() && side != null; + } + } + + protected static boolean canConnectUpwardsTo(IBlockAccess worldIn, BlockPos pos) { + return canConnectUpwardsTo(worldIn.getBlockState(pos)); + } + + protected static boolean canConnectUpwardsTo(IBlockState state) { + return canConnectTo(state, (EnumFacing) null); + } + private boolean canProvidePower = true; - /**+ - * List of blocks to update with redstone. + + /** + * + List of blocks to update with redstone. */ private final Set blocksNeedingUpdate = Sets.newHashSet(); @@ -69,87 +123,36 @@ public class BlockRedstoneWire extends Block { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); } - public static void bootstrapStates() { - NORTH = PropertyEnum.create("north", - BlockRedstoneWire.EnumAttachPosition.class); - EAST = PropertyEnum.create("east", - BlockRedstoneWire.EnumAttachPosition.class); - SOUTH = PropertyEnum.create("south", - BlockRedstoneWire.EnumAttachPosition.class); - WEST = PropertyEnum.create("west", - BlockRedstoneWire.EnumAttachPosition.class); - } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + super.breakBlock(world, blockpos, iblockstate); + if (!world.isRemote) { + BlockPos tmp = new BlockPos(0, 0, 0); + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + world.notifyNeighborsOfStateChange(blockpos.offsetEvenFaster(facings[i], tmp), this); + } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - iblockstate = iblockstate.withProperty(WEST, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.WEST)); - iblockstate = iblockstate.withProperty(EAST, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.EAST)); - iblockstate = iblockstate.withProperty(NORTH, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.NORTH)); - iblockstate = iblockstate.withProperty(SOUTH, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.SOUTH)); - return iblockstate; - } + this.updateSurroundingRedstone(world, blockpos, iblockstate); - private BlockRedstoneWire.EnumAttachPosition getAttachPosition(IBlockAccess worldIn, BlockPos pos, - EnumFacing direction) { - BlockPos blockpos = pos.offset(direction); - BlockPos posTmp = new BlockPos(0, 0, 0); - Block block = worldIn.getBlockState(blockpos).getBlock(); - if (!canConnectTo(worldIn.getBlockState(blockpos), direction) && (block.isBlockNormalCube() - || !canConnectUpwardsTo(worldIn.getBlockState(blockpos.offsetEvenFaster(EnumFacing.DOWN, posTmp))))) { - Block block1 = worldIn.getBlockState(pos.up()).getBlock(); - return !block1.isBlockNormalCube() && block.isBlockNormalCube() - && canConnectUpwardsTo(worldIn.getBlockState(blockpos.offsetEvenFaster(EnumFacing.UP, posTmp))) - ? BlockRedstoneWire.EnumAttachPosition.UP - : BlockRedstoneWire.EnumAttachPosition.NONE; - } else { - return BlockRedstoneWire.EnumAttachPosition.SIDE; + facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + this.notifyWireNeighborsOfStateChange(world, blockpos.offsetEvenFaster(facings[i], tmp)); + } + + facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + BlockPos blockpos1 = blockpos.offsetEvenFaster(facings[i], tmp); + if (world.getBlockState(blockpos1).getBlock().isNormalCube()) { + ++blockpos1.y; + this.notifyWireNeighborsOfStateChange(world, blockpos1); + } else { + --blockpos1.y; + this.notifyWireNeighborsOfStateChange(world, blockpos1); + } + } } } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int i) { - IBlockState iblockstate = iblockaccess.getBlockState(blockpos); - return iblockstate.getBlock() != this ? super.colorMultiplier(iblockaccess, blockpos, i) - : this.colorMultiplier(((Integer) iblockstate.getValue(POWER)).intValue()); - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - BlockPos fuckOff = blockpos.down(); - return World.doesBlockHaveSolidTopSurface(world, fuckOff) - || world.getBlockState(fuckOff).getBlock() == Blocks.glowstone; - } - - private IBlockState updateSurroundingRedstone(World worldIn, BlockPos pos, IBlockState state) { - state = this.calculateCurrentChanges(worldIn, pos, pos, state); - ArrayList arraylist = Lists.newArrayList(this.blocksNeedingUpdate); - this.blocksNeedingUpdate.clear(); - - for (int i = 0, l = arraylist.size(); i < l; ++i) { - worldIn.notifyNeighborsOfStateChange(arraylist.get(i), this); - } - - return state; - } - private IBlockState calculateCurrentChanges(World worldIn, BlockPos pos1, BlockPos pos2, IBlockState state) { IBlockState iblockstate = state; int i = ((Integer) state.getValue(POWER)).intValue(); @@ -216,10 +219,190 @@ public class BlockRedstoneWire extends Block { return state; } - /**+ - * Calls World.notifyNeighborsOfStateChange() for all - * neighboring blocks, but only if the given block is a redstone - * wire. + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + BlockPos fuckOff = blockpos.down(); + return World.doesBlockHaveSolidTopSurface(world, fuckOff) + || world.getBlockState(fuckOff).getBlock() == Blocks.glowstone; + } + + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. + */ + public boolean canProvidePower() { + return this.canProvidePower; + } + + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int i) { + IBlockState iblockstate = iblockaccess.getBlockState(blockpos); + return iblockstate.getBlock() != this ? super.colorMultiplier(iblockaccess, blockpos, i) + : this.colorMultiplier(((Integer) iblockstate.getValue(POWER)).intValue()); + } + + private int colorMultiplier(int powerLevel) { + float f = (float) powerLevel / 15.0F; + float f1 = f * 0.6F + 0.4F; + if (powerLevel == 0) { + f1 = 0.3F; + } + + float f2 = f * f * 0.7F - 0.5F; + float f3 = f * f * 0.6F - 0.7F; + if (f2 < 0.0F) { + f2 = 0.0F; + } + + if (f3 < 0.0F) { + f3 = 0.0F; + } + + int i = MathHelper.clamp_int((int) (f1 * 255.0F), 0, 255); + int j = MathHelper.clamp_int((int) (f2 * 255.0F), 0, 255); + int k = MathHelper.clamp_int((int) (f3 * 255.0F), 0, 255); + return -16777216 | i << 16 | j << 8 | k; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { NORTH, EAST, SOUTH, WEST, POWER }); + } + + private boolean func_176339_d(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { + BlockPos blockpos = pos.offset(side); + IBlockState iblockstate = worldIn.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + boolean flag = block.isNormalCube(); + boolean flag1 = worldIn.getBlockState(pos.up()).getBlock().isNormalCube(); + return !flag1 && flag && canConnectUpwardsTo(worldIn, blockpos.up()) ? true + : (canConnectTo(iblockstate, side) ? true + : (block == Blocks.powered_repeater && iblockstate.getValue(BlockRedstoneDiode.FACING) == side + ? true + : !flag && canConnectUpwardsTo(worldIn, blockpos.down()))); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + iblockstate = iblockstate.withProperty(WEST, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.WEST)); + iblockstate = iblockstate.withProperty(EAST, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.EAST)); + iblockstate = iblockstate.withProperty(NORTH, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.NORTH)); + iblockstate = iblockstate.withProperty(SOUTH, this.getAttachPosition(iblockaccess, blockpos, EnumFacing.SOUTH)); + return iblockstate; + } + + private BlockRedstoneWire.EnumAttachPosition getAttachPosition(IBlockAccess worldIn, BlockPos pos, + EnumFacing direction) { + BlockPos blockpos = pos.offset(direction); + BlockPos posTmp = new BlockPos(0, 0, 0); + Block block = worldIn.getBlockState(blockpos).getBlock(); + if (!canConnectTo(worldIn.getBlockState(blockpos), direction) && (block.isBlockNormalCube() + || !canConnectUpwardsTo(worldIn.getBlockState(blockpos.offsetEvenFaster(EnumFacing.DOWN, posTmp))))) { + Block block1 = worldIn.getBlockState(pos.up()).getBlock(); + return !block1.isBlockNormalCube() && block.isBlockNormalCube() + && canConnectUpwardsTo(worldIn.getBlockState(blockpos.offsetEvenFaster(EnumFacing.UP, posTmp))) + ? BlockRedstoneWire.EnumAttachPosition.UP + : BlockRedstoneWire.EnumAttachPosition.NONE; + } else { + return BlockRedstoneWire.EnumAttachPosition.SIDE; + } + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + public Item getItem(World var1, BlockPos var2) { + return Items.redstone; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.redstone; + } + + private int getMaxCurrentStrength(World worldIn, BlockPos pos, int strength) { + if (worldIn.getBlockState(pos).getBlock() != this) { + return strength; + } else { + int i = ((Integer) worldIn.getBlockState(pos).getValue(POWER)).intValue(); + return i > strength ? i : strength; + } + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(POWER)).intValue(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(POWER, Integer.valueOf(i)); + } + + public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, + EnumFacing enumfacing) { + return !this.canProvidePower ? 0 : this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing); + } + + public int getWeakPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, + EnumFacing enumfacing) { + if (!this.canProvidePower) { + return 0; + } else { + int i = ((Integer) iblockstate.getValue(POWER)).intValue(); + if (i == 0) { + return 0; + } else if (enumfacing == EnumFacing.UP) { + return i; + } else { + EnumSet enumset = EnumSet.noneOf(EnumFacing.class); + + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int j = 0; j < facings.length; ++j) { + EnumFacing enumfacing1 = facings[j]; + if (this.func_176339_d(iblockaccess, blockpos, enumfacing1)) { + enumset.add(enumfacing1); + } + } + + if (enumfacing.getAxis().isHorizontal() && enumset.isEmpty()) { + return i; + } else if (enumset.contains(enumfacing) && !enumset.contains(enumfacing.rotateYCCW()) + && !enumset.contains(enumfacing.rotateY())) { + return i; + } else { + return 0; + } + } + } + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Calls World.notifyNeighborsOfStateChange() for all neighboring blocks, but + * only if the given block is a redstone wire. */ private void notifyWireNeighborsOfStateChange(World worldIn, BlockPos pos) { if (worldIn.getBlockState(pos).getBlock() == this) { @@ -262,47 +445,8 @@ public class BlockRedstoneWire extends Block { } } - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - super.breakBlock(world, blockpos, iblockstate); - if (!world.isRemote) { - BlockPos tmp = new BlockPos(0, 0, 0); - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - world.notifyNeighborsOfStateChange(blockpos.offsetEvenFaster(facings[i], tmp), this); - } - - this.updateSurroundingRedstone(world, blockpos, iblockstate); - - facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - this.notifyWireNeighborsOfStateChange(world, blockpos.offsetEvenFaster(facings[i], tmp)); - } - - facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - BlockPos blockpos1 = blockpos.offsetEvenFaster(facings[i], tmp); - if (world.getBlockState(blockpos1).getBlock().isNormalCube()) { - ++blockpos1.y; - this.notifyWireNeighborsOfStateChange(world, blockpos1); - } else { - --blockpos1.y; - this.notifyWireNeighborsOfStateChange(world, blockpos1); - } - } - } - } - - private int getMaxCurrentStrength(World worldIn, BlockPos pos, int strength) { - if (worldIn.getBlockState(pos).getBlock() != this) { - return strength; - } else { - int i = ((Integer) worldIn.getBlockState(pos).getValue(POWER)).intValue(); - return i > strength ? i : strength; - } - } - - /**+ - * Called when a neighboring block changes. + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { if (!world.isRemote) { @@ -315,115 +459,6 @@ public class BlockRedstoneWire extends Block { } } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.redstone; - } - - public int getStrongPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, - EnumFacing enumfacing) { - return !this.canProvidePower ? 0 : this.getWeakPower(iblockaccess, blockpos, iblockstate, enumfacing); - } - - public int getWeakPower(IBlockAccess iblockaccess, BlockPos blockpos, IBlockState iblockstate, - EnumFacing enumfacing) { - if (!this.canProvidePower) { - return 0; - } else { - int i = ((Integer) iblockstate.getValue(POWER)).intValue(); - if (i == 0) { - return 0; - } else if (enumfacing == EnumFacing.UP) { - return i; - } else { - EnumSet enumset = EnumSet.noneOf(EnumFacing.class); - - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int j = 0; j < facings.length; ++j) { - EnumFacing enumfacing1 = facings[j]; - if (this.func_176339_d(iblockaccess, blockpos, enumfacing1)) { - enumset.add(enumfacing1); - } - } - - if (enumfacing.getAxis().isHorizontal() && enumset.isEmpty()) { - return i; - } else if (enumset.contains(enumfacing) && !enumset.contains(enumfacing.rotateYCCW()) - && !enumset.contains(enumfacing.rotateY())) { - return i; - } else { - return 0; - } - } - } - } - - private boolean func_176339_d(IBlockAccess worldIn, BlockPos pos, EnumFacing side) { - BlockPos blockpos = pos.offset(side); - IBlockState iblockstate = worldIn.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - boolean flag = block.isNormalCube(); - boolean flag1 = worldIn.getBlockState(pos.up()).getBlock().isNormalCube(); - return !flag1 && flag && canConnectUpwardsTo(worldIn, blockpos.up()) ? true - : (canConnectTo(iblockstate, side) ? true - : (block == Blocks.powered_repeater && iblockstate.getValue(BlockRedstoneDiode.FACING) == side - ? true - : !flag && canConnectUpwardsTo(worldIn, blockpos.down()))); - } - - protected static boolean canConnectUpwardsTo(IBlockAccess worldIn, BlockPos pos) { - return canConnectUpwardsTo(worldIn.getBlockState(pos)); - } - - protected static boolean canConnectUpwardsTo(IBlockState state) { - return canConnectTo(state, (EnumFacing) null); - } - - protected static boolean canConnectTo(IBlockState blockState, EnumFacing side) { - Block block = blockState.getBlock(); - if (block == Blocks.redstone_wire) { - return true; - } else if (Blocks.unpowered_repeater.isAssociated(block)) { - EnumFacing enumfacing = (EnumFacing) blockState.getValue(BlockRedstoneRepeater.FACING); - return enumfacing == side || enumfacing.getOpposite() == side; - } else { - return block.canProvidePower() && side != null; - } - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return this.canProvidePower; - } - - private int colorMultiplier(int powerLevel) { - float f = (float) powerLevel / 15.0F; - float f1 = f * 0.6F + 0.4F; - if (powerLevel == 0) { - f1 = 0.3F; - } - - float f2 = f * f * 0.7F - 0.5F; - float f3 = f * f * 0.6F - 0.7F; - if (f2 < 0.0F) { - f2 = 0.0F; - } - - if (f3 < 0.0F) { - f3 = 0.0F; - } - - int i = MathHelper.clamp_int((int) (f1 * 255.0F), 0, 255); - int j = MathHelper.clamp_int((int) (f2 * 255.0F), 0, 255); - int k = MathHelper.clamp_int((int) (f3 * 255.0F), 0, 255); - return -16777216 | i << 16 | j << 8 | k; - } - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { int i = ((Integer) iblockstate.getValue(POWER)).intValue(); if (i != 0) { @@ -439,47 +474,15 @@ public class BlockRedstoneWire extends Block { } } - public Item getItem(World var1, BlockPos var2) { - return Items.redstone; - } + private IBlockState updateSurroundingRedstone(World worldIn, BlockPos pos, IBlockState state) { + state = this.calculateCurrentChanges(worldIn, pos, pos, state); + ArrayList arraylist = Lists.newArrayList(this.blocksNeedingUpdate); + this.blocksNeedingUpdate.clear(); - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(POWER, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(POWER)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { NORTH, EAST, SOUTH, WEST, POWER }); - } - - static enum EnumAttachPosition implements IStringSerializable { - UP("up"), SIDE("side"), NONE("none"); - - private final String name; - - private EnumAttachPosition(String name) { - this.name = name; + for (int i = 0, l = arraylist.size(); i < l; ++i) { + worldIn.notifyNeighborsOfStateChange(arraylist.get(i), this); } - public String toString() { - return this.getName(); - } - - public String getName() { - return this.name; - } + return state; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockReed.java b/src/game/java/net/minecraft/block/BlockReed.java index d5f8219f..54e81da5 100644 --- a/src/game/java/net/minecraft/block/BlockReed.java +++ b/src/game/java/net/minecraft/block/BlockReed.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -17,22 +16,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,6 +50,102 @@ public class BlockReed extends Block { this.setTickRandomly(true); } + public boolean canBlockStay(World worldIn, BlockPos pos) { + return this.canPlaceBlockAt(worldIn, pos); + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + BlockPos down = blockpos.down(); + Block block = world.getBlockState(down).getBlock(); + if (block == this) { + return true; + } else if (block != Blocks.grass && block != Blocks.dirt && block != Blocks.sand) { + return false; + } else { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + down = blockpos.offsetEvenFaster(enumfacing, down); + --down.y; + if (world.getBlockState(down).getBlock().getMaterial() == Material.water) { + return true; + } + } + + return false; + } + } + + protected final boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { + if (this.canBlockStay(worldIn, pos)) { + return true; + } else { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + return false; + } + } + + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return iblockaccess.getBiomeGenForCoords(blockpos).getGrassColorAtPos(blockpos); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AGE }); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + public Item getItem(World var1, BlockPos var2) { + return Items.reeds; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.reeds; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(AGE)).intValue(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + this.checkForDrop(world, blockpos, iblockstate); + } + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { BlockPos tmp = new BlockPos(0, 0, 0); if (world.getBlockState(blockpos.offsetEvenFaster(EnumFacing.DOWN, tmp)).getBlock() == Blocks.reeds @@ -72,100 +170,4 @@ public class BlockReed extends Block { } } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - BlockPos down = blockpos.down(); - Block block = world.getBlockState(down).getBlock(); - if (block == this) { - return true; - } else if (block != Blocks.grass && block != Blocks.dirt && block != Blocks.sand) { - return false; - } else { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - down = blockpos.offsetEvenFaster(enumfacing, down); - --down.y; - if (world.getBlockState(down).getBlock().getMaterial() == Material.water) { - return true; - } - } - - return false; - } - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - this.checkForDrop(world, blockpos, iblockstate); - } - - protected final boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { - if (this.canBlockStay(worldIn, pos)) { - return true; - } else { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - return false; - } - } - - public boolean canBlockStay(World worldIn, BlockPos pos) { - return this.canPlaceBlockAt(worldIn, pos); - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.reeds; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.reeds; - } - - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return iblockaccess.getBiomeGenForCoords(blockpos).getGrassColorAtPos(blockpos); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(AGE)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AGE }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockRotatedPillar.java b/src/game/java/net/minecraft/block/BlockRotatedPillar.java index 414860c4..7f0fdb72 100644 --- a/src/game/java/net/minecraft/block/BlockRotatedPillar.java +++ b/src/game/java/net/minecraft/block/BlockRotatedPillar.java @@ -5,22 +5,25 @@ import net.minecraft.block.material.Material; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/block/BlockSand.java b/src/game/java/net/minecraft/block/BlockSand.java index 4f270ead..2757a311 100644 --- a/src/game/java/net/minecraft/block/BlockSand.java +++ b/src/game/java/net/minecraft/block/BlockSand.java @@ -12,113 +12,40 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockSand extends BlockFalling { - public static PropertyEnum VARIANT; - - public BlockSand() { - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockSand.EnumType.SAND)); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockSand.EnumType.class); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockSand.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockSand.EnumType[] blocks = BlockSand.EnumType.META_LOOKUP; - for (int i = 0; i < blocks.length; ++i) { - list.add(new ItemStack(item, 1, blocks[i].getMetadata())); - } - - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockSand.EnumType) iblockstate.getValue(VARIANT)).getMapColor(); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockSand.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockSand.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - public static enum EnumType implements IStringSerializable { SAND(0, "sand", "default", MapColor.sandColor), RED_SAND(1, "red_sand", "red", MapColor.adobeColor); public static final BlockSand.EnumType[] META_LOOKUP = new BlockSand.EnumType[2]; - private final int meta; - private final String name; - private final MapColor mapColor; - private final String unlocalizedName; + static { + BlockSand.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } - private EnumType(int meta, String name, String unlocalizedName, MapColor mapColor) { - this.meta = meta; - this.name = name; - this.mapColor = mapColor; - this.unlocalizedName = unlocalizedName; - } - - public int getMetadata() { - return this.meta; - } - - public String toString() { - return this.name; - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor() { - return this.mapColor; } public static BlockSand.EnumType byMetadata(int meta) { @@ -129,6 +56,31 @@ public class BlockSand extends BlockFalling { return META_LOOKUP[meta]; } + private final int meta; + private final String name; + + private final MapColor mapColor; + + private final String unlocalizedName; + + private EnumType(int meta, String name, String unlocalizedName, MapColor mapColor) { + this.meta = meta; + this.name = name; + this.mapColor = mapColor; + this.unlocalizedName = unlocalizedName; + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor() { + return this.mapColor; + } + + public int getMetadata() { + return this.meta; + } + public String getName() { return this.name; } @@ -137,12 +89,64 @@ public class BlockSand extends BlockFalling { return this.unlocalizedName; } - static { - BlockSand.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockSand.EnumType.class); + } + + public BlockSand() { + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockSand.EnumType.SAND)); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockSand.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockSand.EnumType) iblockstate.getValue(VARIANT)).getMapColor(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockSand.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockSand.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockSand.EnumType[] blocks = BlockSand.EnumType.META_LOOKUP; + for (int i = 0; i < blocks.length; ++i) { + list.add(new ItemStack(item, 1, blocks[i].getMetadata())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSandStone.java b/src/game/java/net/minecraft/block/BlockSandStone.java index a362a41d..82aa10d8 100644 --- a/src/game/java/net/minecraft/block/BlockSandStone.java +++ b/src/game/java/net/minecraft/block/BlockSandStone.java @@ -13,93 +13,55 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockSandStone extends Block { - public static PropertyEnum TYPE; - - public BlockSandStone() { - super(Material.rock); - this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockSandStone.EnumType.DEFAULT)); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - TYPE = PropertyEnum.create("type", BlockSandStone.EnumType.class); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockSandStone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockSandStone.EnumType[] types = BlockSandStone.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState var1) { - return MapColor.sandColor; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(TYPE, BlockSandStone.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockSandStone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { TYPE }); - } - public static enum EnumType implements IStringSerializable { DEFAULT(0, "sandstone", "default"), CHISELED(1, "chiseled_sandstone", "chiseled"), SMOOTH(2, "smooth_sandstone", "smooth"); public static final BlockSandStone.EnumType[] META_LOOKUP = new BlockSandStone.EnumType[3]; + static { + BlockSandStone.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockSandStone.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int metadata; + private final String name; + private final String unlocalizedName; private EnumType(int meta, String name, String unlocalizedName) { @@ -112,18 +74,6 @@ public class BlockSandStone extends Block { return this.metadata; } - public String toString() { - return this.name; - } - - public static BlockSandStone.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - public String getName() { return this.name; } @@ -132,12 +82,66 @@ public class BlockSandStone extends Block { return this.unlocalizedName; } - static { - BlockSandStone.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum TYPE; + + public static void bootstrapStates() { + TYPE = PropertyEnum.create("type", BlockSandStone.EnumType.class); + } + + public BlockSandStone() { + super(Material.rock); + this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockSandStone.EnumType.DEFAULT)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { TYPE }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockSandStone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState var1) { + return MapColor.sandColor; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockSandStone.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(TYPE, BlockSandStone.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockSandStone.EnumType[] types = BlockSandStone.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSapling.java b/src/game/java/net/minecraft/block/BlockSapling.java index 90ac3d35..0b6325ae 100644 --- a/src/game/java/net/minecraft/block/BlockSapling.java +++ b/src/game/java/net/minecraft/block/BlockSapling.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; import net.minecraft.block.properties.PropertyInteger; @@ -25,22 +25,25 @@ import net.minecraft.world.gen.feature.WorldGenTaiga2; import net.minecraft.world.gen.feature.WorldGenTrees; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,6 +52,10 @@ public class BlockSapling extends BlockBush implements IGrowable { public static PropertyEnum TYPE; public static final PropertyInteger STAGE = PropertyInteger.create("stage", 0, 1); + public static void bootstrapStates() { + TYPE = PropertyEnum.create("type", BlockPlanks.EnumType.class); + } + protected BlockSapling() { this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockPlanks.EnumType.OAK) .withProperty(STAGE, Integer.valueOf(0))); @@ -57,35 +64,36 @@ public class BlockSapling extends BlockBush implements IGrowable { this.setCreativeTab(CreativeTabs.tabDecorations); } - public static void bootstrapStates() { - TYPE = PropertyEnum.create("type", BlockPlanks.EnumType.class); - } - - /**+ - * Gets the localized name of this block. Used for the - * statistics page. + /** + * + Whether this IGrowable can grow */ - public String getLocalizedName() { - return StatCollector.translateToLocal( - this.getUnlocalizedName() + "." + BlockPlanks.EnumType.OAK.getUnlocalizedName() + ".name"); + public boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4) { + return true; } - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - if (!world.isRemote) { - super.updateTick(world, blockpos, iblockstate, random); - if (world.getLightFromNeighbors(blockpos.up()) >= 9 && random.nextInt(7) == 0) { - this.grow(world, blockpos, iblockstate, random); - } - } + public boolean canUseBonemeal(World world, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return (double) world.rand.nextFloat() < 0.45D; } - public void grow(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { - if (((Integer) state.getValue(STAGE)).intValue() == 0) { - worldIn.setBlockState(pos, state.cycleProperty(STAGE), 4); - } else { - this.generateTree(worldIn, pos, state, rand); - } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { TYPE, STAGE }); + } + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + } + + private boolean func_181624_a(World parWorld, BlockPos parBlockPos, int parInt1, int parInt2, + BlockPlanks.EnumType parEnumType) { + return this.isTypeAt(parWorld, parBlockPos.add(parInt1, 0, parInt2), parEnumType) + && this.isTypeAt(parWorld, parBlockPos.add(parInt1 + 1, 0, parInt2), parEnumType) + && this.isTypeAt(parWorld, parBlockPos.add(parInt1, 0, parInt2 + 1), parEnumType) + && this.isTypeAt(parWorld, parBlockPos.add(parInt1 + 1, 0, parInt2 + 1), parEnumType); } public void generateTree(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { @@ -180,36 +188,35 @@ public class BlockSapling extends BlockBush implements IGrowable { } - private boolean func_181624_a(World parWorld, BlockPos parBlockPos, int parInt1, int parInt2, - BlockPlanks.EnumType parEnumType) { - return this.isTypeAt(parWorld, parBlockPos.add(parInt1, 0, parInt2), parEnumType) - && this.isTypeAt(parWorld, parBlockPos.add(parInt1 + 1, 0, parInt2), parEnumType) - && this.isTypeAt(parWorld, parBlockPos.add(parInt1, 0, parInt2 + 1), parEnumType) - && this.isTypeAt(parWorld, parBlockPos.add(parInt1 + 1, 0, parInt2 + 1), parEnumType); - } - - /**+ - * Check whether the given BlockPos has a Sapling of the given - * type + /** + * + Gets the localized name of this block. Used for the statistics page. */ - public boolean isTypeAt(World worldIn, BlockPos pos, BlockPlanks.EnumType type) { - IBlockState iblockstate = worldIn.getBlockState(pos); - return iblockstate.getBlock() == this && iblockstate.getValue(TYPE) == type; + public String getLocalizedName() { + return StatCollector.translateToLocal( + this.getUnlocalizedName() + "." + BlockPlanks.EnumType.OAK.getUnlocalizedName() + ".name"); } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + Convert the BlockState into the correct metadata value */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((BlockPlanks.EnumType) iblockstate.getValue(TYPE)).getMetadata(); + i = i | ((Integer) iblockstate.getValue(STAGE)).intValue() << 3; + return i; } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(TYPE, BlockPlanks.EnumType.byMetadata(i & 7)).withProperty(STAGE, + Integer.valueOf((i & 8) >> 3)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ public void getSubBlocks(Item item, CreativeTabs var2, List list) { BlockPlanks.EnumType[] types = BlockPlanks.EnumType.META_LOOKUP; @@ -219,40 +226,33 @@ public class BlockSapling extends BlockBush implements IGrowable { } - /**+ - * Whether this IGrowable can grow - */ - public boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4) { - return true; - } + public void grow(World worldIn, BlockPos pos, IBlockState state, EaglercraftRandom rand) { + if (((Integer) state.getValue(STAGE)).intValue() == 0) { + worldIn.setBlockState(pos, state.cycleProperty(STAGE), 4); + } else { + this.generateTree(worldIn, pos, state, rand); + } - public boolean canUseBonemeal(World world, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { - return (double) world.rand.nextFloat() < 0.45D; } public void grow(World world, EaglercraftRandom random, BlockPos blockpos, IBlockState iblockstate) { this.grow(world, blockpos, iblockstate, random); } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Check whether the given BlockPos has a Sapling of the given type */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(TYPE, BlockPlanks.EnumType.byMetadata(i & 7)).withProperty(STAGE, - Integer.valueOf((i & 8) >> 3)); + public boolean isTypeAt(World worldIn, BlockPos pos, BlockPlanks.EnumType type) { + IBlockState iblockstate = worldIn.getBlockState(pos); + return iblockstate.getBlock() == this && iblockstate.getValue(TYPE) == type; } - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((BlockPlanks.EnumType) iblockstate.getValue(TYPE)).getMetadata(); - i = i | ((Integer) iblockstate.getValue(STAGE)).intValue() << 3; - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { TYPE, STAGE }); + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + if (!world.isRemote) { + super.updateTick(world, blockpos, iblockstate, random); + if (world.getLightFromNeighbors(blockpos.up()) >= 9 && random.nextInt(7) == 0) { + this.grow(world, blockpos, iblockstate, random); + } + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSeaLantern.java b/src/game/java/net/minecraft/block/BlockSeaLantern.java index 9fa6cc79..4d819028 100644 --- a/src/game/java/net/minecraft/block/BlockSeaLantern.java +++ b/src/game/java/net/minecraft/block/BlockSeaLantern.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -10,22 +9,25 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,35 +38,35 @@ public class BlockSeaLantern extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom random) { - return 2 + random.nextInt(2); + protected boolean canSilkHarvest() { + return true; } - /**+ - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { - return MathHelper.clamp_int(this.quantityDropped(random) + random.nextInt(i + 1), 1, 5); - } - - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Items.prismarine_crystals; } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Get the MapColor for this Block and the given BlockState */ public MapColor getMapColor(IBlockState var1) { return MapColor.quartzColor; } - protected boolean canSilkHarvest() { - return true; + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom random) { + return 2 + random.nextInt(2); + } + + /** + * + Get the quantity dropped based on the given fortune level + */ + public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { + return MathHelper.clamp_int(this.quantityDropped(random) + random.nextInt(i + 1), 1, 5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSign.java b/src/game/java/net/minecraft/block/BlockSign.java index e8e9174e..2bc644de 100644 --- a/src/game/java/net/minecraft/block/BlockSign.java +++ b/src/game/java/net/minecraft/block/BlockSign.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; @@ -15,22 +14,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,10 +45,37 @@ public class BlockSign extends BlockContainer { this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); } + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return !this.func_181087_e(world, blockpos) && super.canPlaceBlockAt(world, blockpos); + } + + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntitySign(); + } + + public boolean func_181623_g() { + return true; + } + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { return null; } + public Item getItem(World var1, BlockPos var2) { + return Items.sign; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.sign; + } + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { this.setBlockBoundsBasedOnState(world, blockpos); return super.getSelectedBoundingBox(world, blockpos); @@ -56,41 +85,18 @@ public class BlockSign extends BlockContainer { return false; } - public boolean isPassable(IBlockAccess var1, BlockPos var2) { - return true; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render */ public boolean isOpaqueCube() { return false; } - public boolean func_181623_g() { + public boolean isPassable(IBlockAccess var1, BlockPos var2) { return true; } - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntitySign(); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.sign; - } - - public Item getItem(World var1, BlockPos var2) { - return Items.sign; - } - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, EnumFacing var5, float var6, float var7, float var8) { if (world.isRemote) { @@ -101,8 +107,4 @@ public class BlockSign extends BlockContainer { : false; } } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return !this.func_181087_e(world, blockpos) && super.canPlaceBlockAt(world, blockpos); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSilverfish.java b/src/game/java/net/minecraft/block/BlockSilverfish.java index 2f5c2c41..ad2b4fc8 100644 --- a/src/game/java/net/minecraft/block/BlockSilverfish.java +++ b/src/game/java/net/minecraft/block/BlockSilverfish.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -17,119 +17,30 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockSilverfish extends Block { - public static PropertyEnum VARIANT; - - public BlockSilverfish() { - super(Material.clay); - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockSilverfish.EnumType.STONE)); - this.setHardness(0.0F); - this.setCreativeTab(CreativeTabs.tabDecorations); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockSilverfish.EnumType.class); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - public static boolean canContainSilverfish(IBlockState blockState) { - Block block = blockState.getBlock(); - return blockState == Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.STONE) - || block == Blocks.cobblestone || block == Blocks.stonebrick; - } - - protected ItemStack createStackedBlock(IBlockState iblockstate) { - switch ((BlockSilverfish.EnumType) iblockstate.getValue(VARIANT)) { - case COBBLESTONE: - return new ItemStack(Blocks.cobblestone); - case STONEBRICK: - return new ItemStack(Blocks.stonebrick); - case MOSSY_STONEBRICK: - return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.MOSSY.getMetadata()); - case CRACKED_STONEBRICK: - return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.CRACKED.getMetadata()); - case CHISELED_STONEBRICK: - return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.CHISELED.getMetadata()); - default: - return new ItemStack(Blocks.stone); - } - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState var3, float var4, int var5) { - if (!world.isRemote && world.getGameRules().getBoolean("doTileDrops")) { - EntitySilverfish entitysilverfish = new EntitySilverfish(world); - entitysilverfish.setLocationAndAngles((double) blockpos.getX() + 0.5D, (double) blockpos.getY(), - (double) blockpos.getZ() + 0.5D, 0.0F, 0.0F); - world.spawnEntityInWorld(entitysilverfish); - entitysilverfish.spawnExplosionParticle(); - } - - } - - public int getDamageValue(World world, BlockPos blockpos) { - IBlockState iblockstate = world.getBlockState(blockpos); - return iblockstate.getBlock().getMetaFromState(iblockstate); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockSilverfish.EnumType[] types = BlockSilverfish.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockSilverfish.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockSilverfish.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - public static enum EnumType implements IStringSerializable { STONE(0, "stone") { public IBlockState getModelBlock() { @@ -167,8 +78,38 @@ public class BlockSilverfish extends Block { }; public static final BlockSilverfish.EnumType[] META_LOOKUP = new BlockSilverfish.EnumType[6]; + static { + BlockSilverfish.EnumType[] types = BlockSilverfish.EnumType.values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockSilverfish.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + public static BlockSilverfish.EnumType forModelBlock(IBlockState model) { + BlockSilverfish.EnumType[] types = BlockSilverfish.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + BlockSilverfish.EnumType blocksilverfish$enumtype = types[i]; + if (model == blocksilverfish$enumtype.getModelBlock()) { + return blocksilverfish$enumtype; + } + } + + return STONE; + } + private final int meta; + private final String name; + private final String unlocalizedName; private EnumType(int meta, String name) { @@ -185,17 +126,7 @@ public class BlockSilverfish extends Block { return this.meta; } - public String toString() { - return this.name; - } - - public static BlockSilverfish.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } + public abstract IBlockState getModelBlock(); public String getName() { return this.name; @@ -205,26 +136,100 @@ public class BlockSilverfish extends Block { return this.unlocalizedName; } - public abstract IBlockState getModelBlock(); - - public static BlockSilverfish.EnumType forModelBlock(IBlockState model) { - BlockSilverfish.EnumType[] types = BlockSilverfish.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - BlockSilverfish.EnumType blocksilverfish$enumtype = types[i]; - if (model == blocksilverfish$enumtype.getModelBlock()) { - return blocksilverfish$enumtype; - } - } - - return STONE; - } - - static { - BlockSilverfish.EnumType[] types = BlockSilverfish.EnumType.values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockSilverfish.EnumType.class); + } + + public static boolean canContainSilverfish(IBlockState blockState) { + Block block = blockState.getBlock(); + return blockState == Blocks.stone.getDefaultState().withProperty(BlockStone.VARIANT, BlockStone.EnumType.STONE) + || block == Blocks.cobblestone || block == Blocks.stonebrick; + } + + public BlockSilverfish() { + super(Material.clay); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockSilverfish.EnumType.STONE)); + this.setHardness(0.0F); + this.setCreativeTab(CreativeTabs.tabDecorations); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + protected ItemStack createStackedBlock(IBlockState iblockstate) { + switch ((BlockSilverfish.EnumType) iblockstate.getValue(VARIANT)) { + case COBBLESTONE: + return new ItemStack(Blocks.cobblestone); + case STONEBRICK: + return new ItemStack(Blocks.stonebrick); + case MOSSY_STONEBRICK: + return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.MOSSY.getMetadata()); + case CRACKED_STONEBRICK: + return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.CRACKED.getMetadata()); + case CHISELED_STONEBRICK: + return new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.EnumType.CHISELED.getMetadata()); + default: + return new ItemStack(Blocks.stone); + } + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState var3, float var4, int var5) { + if (!world.isRemote && world.getGameRules().getBoolean("doTileDrops")) { + EntitySilverfish entitysilverfish = new EntitySilverfish(world); + entitysilverfish.setLocationAndAngles((double) blockpos.getX() + 0.5D, (double) blockpos.getY(), + (double) blockpos.getZ() + 0.5D, 0.0F, 0.0F); + world.spawnEntityInWorld(entitysilverfish); + entitysilverfish.spawnExplosionParticle(); + } + + } + + public int getDamageValue(World world, BlockPos blockpos) { + IBlockState iblockstate = world.getBlockState(blockpos); + return iblockstate.getBlock().getMetaFromState(iblockstate); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockSilverfish.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockSilverfish.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockSilverfish.EnumType[] types = BlockSilverfish.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSkull.java b/src/game/java/net/minecraft/block/BlockSkull.java index cd35b197..8f5d0481 100644 --- a/src/game/java/net/minecraft/block/BlockSkull.java +++ b/src/game/java/net/minecraft/block/BlockSkull.java @@ -1,11 +1,10 @@ package net.minecraft.block; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import java.util.List; import com.google.common.base.Predicate; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -37,22 +36,25 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -77,95 +79,6 @@ public class BlockSkull extends BlockContainer { this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal("tile.skull.skeleton.name"); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - switch ((EnumFacing) iblockaccess.getBlockState(blockpos).getValue(FACING)) { - case UP: - default: - this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); - break; - case NORTH: - this.setBlockBounds(0.25F, 0.25F, 0.5F, 0.75F, 0.75F, 1.0F); - break; - case SOUTH: - this.setBlockBounds(0.25F, 0.25F, 0.0F, 0.75F, 0.75F, 0.5F); - break; - case WEST: - this.setBlockBounds(0.5F, 0.25F, 0.25F, 1.0F, 0.75F, 0.75F); - break; - case EAST: - this.setBlockBounds(0.0F, 0.25F, 0.25F, 0.5F, 0.75F, 0.75F); - } - - } - - public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { - this.setBlockBoundsBasedOnState(world, blockpos); - return super.getCollisionBoundingBox(world, blockpos, iblockstate); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, - int var7, EntityLivingBase entitylivingbase) { - return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing()).withProperty(NODROP, - Boolean.valueOf(false)); - } - - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. - */ - public TileEntity createNewTileEntity(World var1, int var2) { - return new TileEntitySkull(); - } - - public Item getItem(World var1, BlockPos var2) { - return Items.skull; - } - - public int getDamageValue(World world, BlockPos blockpos) { - TileEntity tileentity = world.getTileEntity(blockpos); - return tileentity instanceof TileEntitySkull ? ((TileEntitySkull) tileentity).getSkullType() - : super.getDamageValue(world, blockpos); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World var1, BlockPos var2, IBlockState var3, float var4, int var5) { - } - - public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { - if (entityplayer.capabilities.isCreativeMode) { - iblockstate = iblockstate.withProperty(NODROP, Boolean.valueOf(true)); - world.setBlockState(blockpos, iblockstate, 4); - } - - super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); - } - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { if (!world.isRemote) { if (!((Boolean) iblockstate.getValue(NODROP)).booleanValue()) { @@ -188,13 +101,6 @@ public class BlockSkull extends BlockContainer { } } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.skull; - } - public boolean canDispenserPlace(World worldIn, BlockPos pos, ItemStack stack) { return stack.getMetadata() == 1 && pos.getY() >= 2 && worldIn.getDifficulty() != EnumDifficulty.PEACEFUL && !worldIn.isRemote ? this.getWitherBasePattern().match(worldIn, pos) != null : false; @@ -256,16 +162,55 @@ public class BlockSkull extends BlockContainer { } } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getFront(i & 7)).withProperty(NODROP, - Boolean.valueOf((i & 8) > 0)); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, NODROP }); } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. + */ + public TileEntity createNewTileEntity(World var1, int var2) { + return new TileEntitySkull(); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World var1, BlockPos var2, IBlockState var3, float var4, int var5) { + } + + public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { + this.setBlockBoundsBasedOnState(world, blockpos); + return super.getCollisionBoundingBox(world, blockpos, iblockstate); + } + + public int getDamageValue(World world, BlockPos blockpos) { + TileEntity tileentity = world.getTileEntity(blockpos); + return tileentity instanceof TileEntitySkull ? ((TileEntitySkull) tileentity).getSkullType() + : super.getDamageValue(world, blockpos); + } + + public Item getItem(World var1, BlockPos var2) { + return Items.skull; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.skull; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal("tile.skull.skeleton.name"); + } + + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -277,8 +222,12 @@ public class BlockSkull extends BlockContainer { return i; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, NODROP }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getFront(i & 7)).withProperty(NODROP, + Boolean.valueOf((i & 8) > 0)); } protected BlockPattern getWitherBasePattern() { @@ -301,4 +250,56 @@ public class BlockSkull extends BlockContainer { return this.witherPattern; } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { + if (entityplayer.capabilities.isCreativeMode) { + iblockstate = iblockstate.withProperty(NODROP, Boolean.valueOf(true)); + world.setBlockState(blockpos, iblockstate, 4); + } + + super.onBlockHarvested(world, blockpos, iblockstate, entityplayer); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing var3, float var4, float var5, float var6, + int var7, EntityLivingBase entitylivingbase) { + return this.getDefaultState().withProperty(FACING, entitylivingbase.getHorizontalFacing()).withProperty(NODROP, + Boolean.valueOf(false)); + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + switch ((EnumFacing) iblockaccess.getBlockState(blockpos).getValue(FACING)) { + case UP: + default: + this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); + break; + case NORTH: + this.setBlockBounds(0.25F, 0.25F, 0.5F, 0.75F, 0.75F, 1.0F); + break; + case SOUTH: + this.setBlockBounds(0.25F, 0.25F, 0.0F, 0.75F, 0.75F, 0.5F); + break; + case WEST: + this.setBlockBounds(0.5F, 0.25F, 0.25F, 1.0F, 0.75F, 0.75F); + break; + case EAST: + this.setBlockBounds(0.0F, 0.25F, 0.25F, 0.5F, 0.75F, 0.75F); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSlab.java b/src/game/java/net/minecraft/block/BlockSlab.java index c514cec9..3666936c 100644 --- a/src/game/java/net/minecraft/block/BlockSlab.java +++ b/src/game/java/net/minecraft/block/BlockSlab.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -21,29 +21,58 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockSlab extends Block { + public static enum EnumBlockHalf implements IStringSerializable { + TOP("top"), BOTTOM("bottom"); + + private final String name; + + private EnumBlockHalf(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static PropertyEnum HALF; + public static void bootstrapStates() { + HALF = PropertyEnum.create("half", BlockSlab.EnumBlockHalf.class); + } + + protected static boolean isSlab(Block blockIn) { + return blockIn == Blocks.stone_slab || blockIn == Blocks.wooden_slab || blockIn == Blocks.stone_slab2; + } + public BlockSlab(Material materialIn) { super(materialIn); if (this.isDouble()) { @@ -55,14 +84,77 @@ public abstract class BlockSlab extends Block { this.setLightOpacity(255); } - public static void bootstrapStates() { - HALF = PropertyEnum.create("half", BlockSlab.EnumBlockHalf.class); + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. + */ + public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, + AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.setBlockBoundsBasedOnState(world, blockpos); + super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); } protected boolean canSilkHarvest() { return false; } + public int getDamageValue(World world, BlockPos blockpos) { + return super.getDamageValue(world, blockpos) & 7; + } + + public abstract String getUnlocalizedName(int var1); + + public abstract Object getVariant(ItemStack var1); + + public abstract IProperty getVariantProperty(); + + public abstract boolean isDouble(); + + public boolean isFullCube() { + return this.isDouble(); + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return this.isDouble(); + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (!world.isRemote && MinecraftServer.getServer().worldServers[0].getWorldInfo().getGameRulesInstance() + .getBoolean("clickToSit") && entityplayer.getHeldItem() == null) { + EntityArrow arrow = new EntityArrow(world, blockpos.getX() + 0.5D, blockpos.getY(), blockpos.getZ() + 0.5D); + arrow.isChair = true; + world.spawnEntityInWorld(arrow); + entityplayer.mountEntity(arrow); + return true; + } + return super.onBlockActivated(world, blockpos, var3, entityplayer, var5, var6, var7, var8); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2, + int i, EntityLivingBase entitylivingbase) { + IBlockState iblockstate = super.onBlockPlaced(world, blockpos, enumfacing, f, f1, f2, i, entitylivingbase) + .withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM); + return this.isDouble() ? iblockstate + : (enumfacing != EnumFacing.DOWN && (enumfacing == EnumFacing.UP || (double) f1 <= 0.5D) ? iblockstate + : iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.TOP)); + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return this.isDouble() ? 2 : 1; + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { if (this.isDouble()) { this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); @@ -79,8 +171,8 @@ public abstract class BlockSlab extends Block { } } - /**+ - * Sets the block's bounds for rendering it as an item + /** + * + Sets the block's bounds for rendering it as an item */ public void setBlockBoundsForItemRender() { if (this.isDouble()) { @@ -91,48 +183,6 @@ public abstract class BlockSlab extends Block { } - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. - */ - public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, - AxisAlignedBB axisalignedbb, List list, Entity entity) { - this.setBlockBoundsBasedOnState(world, blockpos); - super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return this.isDouble(); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2, - int i, EntityLivingBase entitylivingbase) { - IBlockState iblockstate = super.onBlockPlaced(world, blockpos, enumfacing, f, f1, f2, i, entitylivingbase) - .withProperty(HALF, BlockSlab.EnumBlockHalf.BOTTOM); - return this.isDouble() ? iblockstate - : (enumfacing != EnumFacing.DOWN && (enumfacing == EnumFacing.UP || (double) f1 <= 0.5D) ? iblockstate - : iblockstate.withProperty(HALF, BlockSlab.EnumBlockHalf.TOP)); - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return this.isDouble() ? 2 : 1; - } - - public boolean isFullCube() { - return this.isDouble(); - } - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { if (this.isDouble()) { return super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); @@ -157,51 +207,4 @@ public abstract class BlockSlab extends Block { : !isSlab(iblockstate.getBlock()) || flag)); } } - - protected static boolean isSlab(Block blockIn) { - return blockIn == Blocks.stone_slab || blockIn == Blocks.wooden_slab || blockIn == Blocks.stone_slab2; - } - - public abstract String getUnlocalizedName(int var1); - - public int getDamageValue(World world, BlockPos blockpos) { - return super.getDamageValue(world, blockpos) & 7; - } - - public abstract boolean isDouble(); - - public abstract IProperty getVariantProperty(); - - public abstract Object getVariant(ItemStack var1); - - public static enum EnumBlockHalf implements IStringSerializable { - TOP("top"), BOTTOM("bottom"); - - private final String name; - - private EnumBlockHalf(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (!world.isRemote && MinecraftServer.getServer().worldServers[0].getWorldInfo().getGameRulesInstance() - .getBoolean("clickToSit") && entityplayer.getHeldItem() == null) { - EntityArrow arrow = new EntityArrow(world, blockpos.getX() + 0.5D, blockpos.getY(), blockpos.getZ() + 0.5D); - arrow.isChair = true; - world.spawnEntityInWorld(arrow); - entityplayer.mountEntity(arrow); - return true; - } - return super.onBlockActivated(world, blockpos, var3, entityplayer, var5, var6, var7, var8); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSlime.java b/src/game/java/net/minecraft/block/BlockSlime.java index 9c0a3f2d..9a151e90 100644 --- a/src/game/java/net/minecraft/block/BlockSlime.java +++ b/src/game/java/net/minecraft/block/BlockSlime.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,34 +42,9 @@ public class BlockSlime extends BlockBreakable { return EnumWorldBlockLayer.TRANSLUCENT; } - /**+ - * Block's chance to react to a living entity falling on it. - */ - public void onFallenUpon(World world, BlockPos blockpos, Entity entity, float f) { - if (entity.isSneaking()) { - super.onFallenUpon(world, blockpos, entity, f); - } else { - entity.fall(f, 0.0F); - } - - } - - /**+ - * Called when an Entity lands on this Block. This method *must* - * update motionY because the entity will not do that on its own - */ - public void onLanded(World world, Entity entity) { - if (entity.isSneaking()) { - super.onLanded(world, entity); - } else if (entity.motionY < 0.0D) { - entity.motionY = -entity.motionY; - } - - } - - /**+ - * Triggered whenever an entity collides with this block (enters - * into the block) + /** + * + Triggered whenever an entity collides with this block (enters into the + * block) */ public void onEntityCollidedWithBlock(World world, BlockPos blockpos, Entity entity) { if (Math.abs(entity.motionY) < 0.1D && !entity.isSneaking()) { @@ -77,4 +55,29 @@ public class BlockSlime extends BlockBreakable { super.onEntityCollidedWithBlock(world, blockpos, entity); } + + /** + * + Block's chance to react to a living entity falling on it. + */ + public void onFallenUpon(World world, BlockPos blockpos, Entity entity, float f) { + if (entity.isSneaking()) { + super.onFallenUpon(world, blockpos, entity, f); + } else { + entity.fall(f, 0.0F); + } + + } + + /** + * + Called when an Entity lands on this Block. This method *must* update + * motionY because the entity will not do that on its own + */ + public void onLanded(World world, Entity entity) { + if (entity.isSneaking()) { + super.onLanded(world, entity); + } else if (entity.motionY < 0.0D) { + entity.motionY = -entity.motionY; + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSnow.java b/src/game/java/net/minecraft/block/BlockSnow.java index 191b8874..6cd34e13 100644 --- a/src/game/java/net/minecraft/block/BlockSnow.java +++ b/src/game/java/net/minecraft/block/BlockSnow.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyInteger; @@ -22,22 +21,25 @@ import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,46 +56,6 @@ public class BlockSnow extends Block { this.setBlockBoundsForItemRender(); } - public boolean isPassable(IBlockAccess iblockaccess, BlockPos blockpos) { - return ((Integer) iblockaccess.getBlockState(blockpos).getValue(LAYERS)).intValue() < 5; - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState iblockstate) { - int i = ((Integer) iblockstate.getValue(LAYERS)).intValue() - 1; - float f = 0.125F; - return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, - (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, - (double) ((float) blockpos.getY() + (float) i * f), (double) blockpos.getZ() + this.maxZ); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - this.getBoundsForLayers(0); - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - IBlockState iblockstate = iblockaccess.getBlockState(blockpos); - this.getBoundsForLayers(((Integer) iblockstate.getValue(LAYERS)).intValue()); - } - - protected void getBoundsForLayers(int parInt1) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, (float) parInt1 / 8.0F, 1.0F); - } - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { IBlockState iblockstate = world.getBlockState(blockpos.down()); Block block = iblockstate.getBlock(); @@ -103,13 +65,6 @@ public class BlockSnow extends Block { : false; } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - this.checkAndDropBlock(world, blockpos, iblockstate); - } - private boolean checkAndDropBlock(World worldIn, BlockPos pos, IBlockState state) { if (!this.canPlaceBlockAt(worldIn, pos)) { this.dropBlockAsItem(worldIn, pos, state, 0); @@ -120,6 +75,43 @@ public class BlockSnow extends Block { } } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { LAYERS }); + } + + protected void getBoundsForLayers(int parInt1) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, (float) parInt1 / 8.0F, 1.0F); + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos blockpos, IBlockState iblockstate) { + int i = ((Integer) iblockstate.getValue(LAYERS)).intValue() - 1; + float f = 0.125F; + return new AxisAlignedBB((double) blockpos.getX() + this.minX, (double) blockpos.getY() + this.minY, + (double) blockpos.getZ() + this.minZ, (double) blockpos.getX() + this.maxX, + (double) ((float) blockpos.getY() + (float) i * f), (double) blockpos.getZ() + this.maxZ); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.snowball; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(LAYERS)).intValue() - 1; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(LAYERS, Integer.valueOf((i & 7) + 1)); + } + public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, TileEntity var5) { spawnAsEntity(world, blockpos, @@ -128,20 +120,60 @@ public class BlockSnow extends Block { entityplayer.triggerAchievement(StatList.mineBlockStatArray[Block.getIdFromBlock(this)]); } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.snowball; + public boolean isFullCube() { + return false; } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean isPassable(IBlockAccess iblockaccess, BlockPos blockpos) { + return ((Integer) iblockaccess.getBlockState(blockpos).getValue(LAYERS)).intValue() < 5; + } + + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) + */ + public boolean isReplaceable(World world, BlockPos blockpos) { + return ((Integer) world.getBlockState(blockpos).getValue(LAYERS)).intValue() == 1; + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + this.checkAndDropBlock(world, blockpos, iblockstate); + } + + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 0; } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + IBlockState iblockstate = iblockaccess.getBlockState(blockpos); + this.getBoundsForLayers(((Integer) iblockstate.getValue(LAYERS)).intValue()); + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + this.getBoundsForLayers(0); + } + + public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { + return enumfacing == EnumFacing.UP ? true : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); + } + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { if (world.getLightFor(EnumSkyBlock.BLOCK, blockpos) > 11) { this.dropBlockAsItem(world, blockpos, world.getBlockState(blockpos), 0); @@ -149,34 +181,4 @@ public class BlockSnow extends Block { } } - - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { - return enumfacing == EnumFacing.UP ? true : super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(LAYERS, Integer.valueOf((i & 7) + 1)); - } - - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) - */ - public boolean isReplaceable(World world, BlockPos blockpos) { - return ((Integer) world.getBlockState(blockpos).getValue(LAYERS)).intValue() == 1; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(LAYERS)).intValue() - 1; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { LAYERS }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSnowBlock.java b/src/game/java/net/minecraft/block/BlockSnowBlock.java index c5395aa5..eb264115 100644 --- a/src/game/java/net/minecraft/block/BlockSnowBlock.java +++ b/src/game/java/net/minecraft/block/BlockSnowBlock.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; @@ -11,22 +10,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,15 +40,15 @@ public class BlockSnowBlock extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Get the Item that this Block should drop when harvested. */ public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { return Items.snowball; } - /**+ - * Returns the quantity of items to drop on block destruction. + /** + * + Returns the quantity of items to drop on block destruction. */ public int quantityDropped(EaglercraftRandom var1) { return 4; diff --git a/src/game/java/net/minecraft/block/BlockSoulSand.java b/src/game/java/net/minecraft/block/BlockSoulSand.java index 1b985909..6d5e2437 100644 --- a/src/game/java/net/minecraft/block/BlockSoulSand.java +++ b/src/game/java/net/minecraft/block/BlockSoulSand.java @@ -9,22 +9,25 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,8 +45,8 @@ public class BlockSoulSand extends Block { (double) (blockpos.getZ() + 1)); } - /**+ - * Called When an Entity Collided with the Block + /** + * + Called When an Entity Collided with the Block */ public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity entity) { entity.motionX *= 0.4D; diff --git a/src/game/java/net/minecraft/block/BlockSourceImpl.java b/src/game/java/net/minecraft/block/BlockSourceImpl.java index 45c794f1..fbea7fb5 100644 --- a/src/game/java/net/minecraft/block/BlockSourceImpl.java +++ b/src/game/java/net/minecraft/block/BlockSourceImpl.java @@ -6,22 +6,25 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +38,19 @@ public class BlockSourceImpl implements IBlockSource { this.pos = posIn; } + public int getBlockMetadata() { + IBlockState iblockstate = this.worldObj.getBlockState(this.pos); + return iblockstate.getBlock().getMetaFromState(iblockstate); + } + + public BlockPos getBlockPos() { + return this.pos; + } + + public T getBlockTileEntity() { + return (T) this.worldObj.getTileEntity(this.pos); + } + public World getWorld() { return this.worldObj; } @@ -50,17 +66,4 @@ public class BlockSourceImpl implements IBlockSource { public double getZ() { return (double) this.pos.getZ() + 0.5D; } - - public BlockPos getBlockPos() { - return this.pos; - } - - public int getBlockMetadata() { - IBlockState iblockstate = this.worldObj.getBlockState(this.pos); - return iblockstate.getBlock().getMetaFromState(iblockstate); - } - - public T getBlockTileEntity() { - return (T) this.worldObj.getTileEntity(this.pos); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSponge.java b/src/game/java/net/minecraft/block/BlockSponge.java index a99623dd..dc248859 100644 --- a/src/game/java/net/minecraft/block/BlockSponge.java +++ b/src/game/java/net/minecraft/block/BlockSponge.java @@ -3,10 +3,10 @@ package net.minecraft.block; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -23,22 +23,25 @@ import net.minecraft.util.StatCollector; import net.minecraft.util.Tuple; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,44 +55,6 @@ public class BlockSponge extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal(this.getUnlocalizedName() + ".dry.name"); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((Boolean) iblockstate.getValue(WET)).booleanValue() ? 1 : 0; - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - this.tryAbsorb(world, blockpos, iblockstate); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - this.tryAbsorb(world, blockpos, iblockstate); - super.onNeighborBlockChange(world, blockpos, iblockstate, block); - } - - protected void tryAbsorb(World worldIn, BlockPos pos, IBlockState state) { - if (!((Boolean) state.getValue(WET)).booleanValue() && this.absorb(worldIn, pos)) { - worldIn.setBlockState(pos, state.withProperty(WET, Boolean.valueOf(true)), 2); - worldIn.playAuxSFX(2001, pos, Block.getIdFromBlock(Blocks.water)); - } - - } - private boolean absorb(World worldIn, BlockPos pos) { LinkedList linkedlist = Lists.newLinkedList(); ArrayList arraylist = Lists.newArrayList(); @@ -127,31 +92,59 @@ public class BlockSponge extends Block { return i > 0; } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { WET }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((Boolean) iblockstate.getValue(WET)).booleanValue() ? 1 : 0; + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal(this.getUnlocalizedName() + ".dry.name"); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Boolean) iblockstate.getValue(WET)).booleanValue() ? 1 : 0; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(WET, Boolean.valueOf((i & 1) == 1)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ public void getSubBlocks(Item item, CreativeTabs var2, List list) { list.add(new ItemStack(item, 1, 0)); list.add(new ItemStack(item, 1, 1)); } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(WET, Boolean.valueOf((i & 1) == 1)); + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + this.tryAbsorb(world, blockpos, iblockstate); } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Called when a neighboring block changes. */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Boolean) iblockstate.getValue(WET)).booleanValue() ? 1 : 0; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { WET }); + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + this.tryAbsorb(world, blockpos, iblockstate); + super.onNeighborBlockChange(world, blockpos, iblockstate, block); } public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -189,4 +182,12 @@ public class BlockSponge extends Block { } } } + + protected void tryAbsorb(World worldIn, BlockPos pos, IBlockState state) { + if (!((Boolean) state.getValue(WET)).booleanValue() && this.absorb(worldIn, pos)) { + worldIn.setBlockState(pos, state.withProperty(WET, Boolean.valueOf(true)), 2); + worldIn.playAuxSFX(2001, pos, Block.getIdFromBlock(Blocks.water)); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStainedGlass.java b/src/game/java/net/minecraft/block/BlockStainedGlass.java index 7b2b647a..6e3c8fcd 100644 --- a/src/game/java/net/minecraft/block/BlockStainedGlass.java +++ b/src/game/java/net/minecraft/block/BlockStainedGlass.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -17,22 +17,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,19 +50,57 @@ public class BlockStainedGlass extends BlockBreakable { this.setCreativeTab(CreativeTabs.tabBlock); } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { + if (!world.isRemote) { + BlockBeacon.updateColorAsync(world, blockpos); + } + } + + protected boolean canSilkHarvest() { + return true; + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { COLOR }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ public int damageDropped(IBlockState iblockstate) { return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.TRANSLUCENT; + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ public void getSubBlocks(Item item, CreativeTabs var2, List list) { EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP; @@ -69,59 +110,20 @@ public class BlockStainedGlass extends BlockBreakable { } - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.TRANSLUCENT; - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - protected boolean canSilkHarvest() { - return true; - } - public boolean isFullCube() { return false; } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); - } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { if (!world.isRemote) { BlockBeacon.updateColorAsync(world, blockpos); } } - public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { - if (!world.isRemote) { - BlockBeacon.updateColorAsync(world, blockpos); - } - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Returns the quantity of items to drop on block destruction. */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { COLOR }); + public int quantityDropped(EaglercraftRandom var1) { + return 0; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStainedGlassPane.java b/src/game/java/net/minecraft/block/BlockStainedGlassPane.java index 22cc2436..bc6db752 100644 --- a/src/game/java/net/minecraft/block/BlockStainedGlassPane.java +++ b/src/game/java/net/minecraft/block/BlockStainedGlassPane.java @@ -16,22 +16,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,19 +51,53 @@ public class BlockStainedGlassPane extends BlockPane { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { + if (!world.isRemote) { + BlockBeacon.updateColorAsync(world, blockpos); + } + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { NORTH, EAST, WEST, SOUTH, COLOR }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ public int damageDropped(IBlockState iblockstate) { return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); } - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.TRANSLUCENT; + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ public void getSubBlocks(Item item, CreativeTabs var2, List list) { for (int i = 0; i < EnumDyeColor.META_LOOKUP.length; ++i) { @@ -69,44 +106,9 @@ public class BlockStainedGlassPane extends BlockPane { } - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMapColor(); - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.TRANSLUCENT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(COLOR, EnumDyeColor.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumDyeColor) iblockstate.getValue(COLOR)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { NORTH, EAST, WEST, SOUTH, COLOR }); - } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { if (!world.isRemote) { BlockBeacon.updateColorAsync(world, blockpos); } } - - public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { - if (!world.isRemote) { - BlockBeacon.updateColorAsync(world, blockpos); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStairs.java b/src/game/java/net/minecraft/block/BlockStairs.java index b83cf1b7..8db9953c 100644 --- a/src/game/java/net/minecraft/block/BlockStairs.java +++ b/src/game/java/net/minecraft/block/BlockStairs.java @@ -2,8 +2,8 @@ package net.minecraft.block; import java.util.Arrays; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -28,35 +28,105 @@ import net.minecraft.world.Explosion; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockStairs extends Block { + public static enum EnumHalf implements IStringSerializable { + TOP("top"), BOTTOM("bottom"); + + private final String name; + + private EnumHalf(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + + public static enum EnumShape implements IStringSerializable { + STRAIGHT("straight"), INNER_LEFT("inner_left"), INNER_RIGHT("inner_right"), OUTER_LEFT("outer_left"), + OUTER_RIGHT("outer_right"); + + private final String name; + + private EnumShape(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); public static PropertyEnum HALF; public static PropertyEnum SHAPE; private static final int[][] field_150150_a = new int[][] { { 4, 5 }, { 5, 7 }, { 6, 7 }, { 4, 6 }, { 0, 1 }, { 1, 3 }, { 2, 3 }, { 0, 2 } }; + + public static void bootstrapStates() { + HALF = PropertyEnum.create("half", BlockStairs.EnumHalf.class); + SHAPE = PropertyEnum.create("shape", BlockStairs.EnumShape.class); + } + + /** + * + Checks if a block is stairs + */ + public static boolean isBlockStairs(Block blockIn) { + return blockIn instanceof BlockStairs; + } + + /** + * + Check whether there is a stair block at the given position and it has the + * same properties as the given BlockState + */ + public static boolean isSameStair(IBlockAccess worldIn, BlockPos pos, IBlockState state) { + IBlockState iblockstate = worldIn.getBlockState(pos); + Block block = iblockstate.getBlock(); + /** + * + Checks if a block is stairs + */ + return isBlockStairs(block) && iblockstate.getValue(HALF) == state.getValue(HALF) + && iblockstate.getValue(FACING) == state.getValue(FACING); + } + private final Block modelBlock; + private final IBlockState modelState; + private boolean hasRaytraced; + private int rayTracePass; protected BlockStairs(IBlockState modelState) { @@ -72,129 +142,163 @@ public class BlockStairs extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - public static void bootstrapStates() { - HALF = PropertyEnum.create("half", BlockStairs.EnumHalf.class); - SHAPE = PropertyEnum.create("shape", BlockStairs.EnumShape.class); - } - - public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { - if (this.hasRaytraced) { - this.setBlockBounds(0.5F * (float) (this.rayTracePass % 2), 0.5F * (float) (this.rayTracePass / 4 % 2), - 0.5F * (float) (this.rayTracePass / 2 % 2), 0.5F + 0.5F * (float) (this.rayTracePass % 2), - 0.5F + 0.5F * (float) (this.rayTracePass / 4 % 2), - 0.5F + 0.5F * (float) (this.rayTracePass / 2 % 2)); - } else { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + /** + * + Add all collision boxes of this Block to the list that intersect with the + * given mask. + */ + public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, + AxisAlignedBB axisalignedbb, List list, Entity entity) { + this.setBaseCollisionBounds(world, blockpos); + super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); + boolean flag = this.func_176306_h(world, blockpos); + super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); + if (flag && this.func_176304_i(world, blockpos)) { + super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); } + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { + this.modelBlock.breakBlock(world, blockpos, this.modelState); + } + + public boolean canCollideCheck(IBlockState iblockstate, boolean flag) { + return this.modelBlock.canCollideCheck(iblockstate, flag); + } + + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + return this.modelBlock.canPlaceBlockAt(world, blockpos); + } + + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. */ - public boolean isOpaqueCube() { - return false; - } + public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { + MovingObjectPosition[] amovingobjectposition = new MovingObjectPosition[8]; + IBlockState iblockstate = world.getBlockState(blockpos); + int i = ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + boolean flag = iblockstate.getValue(HALF) == BlockStairs.EnumHalf.TOP; + int[] aint = field_150150_a[i + (flag ? 4 : 0)]; + this.hasRaytraced = true; - public boolean isFullCube() { - return false; - } - - /**+ - * Set the block bounds as the collision bounds for the stairs - * at the given position - */ - public void setBaseCollisionBounds(IBlockAccess worldIn, BlockPos pos) { - if (worldIn.getBlockState(pos).getValue(HALF) == BlockStairs.EnumHalf.TOP) { - this.setBlockBounds(0.0F, 0.5F, 0.0F, 1.0F, 1.0F, 1.0F); - } else { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + for (int j = 0; j < 8; ++j) { + this.rayTracePass = j; + if (Arrays.binarySearch(aint, j) < 0) { + amovingobjectposition[j] = super.collisionRayTrace(world, blockpos, vec3, vec31); + } } + for (int l = 0; l < aint.length; ++l) { + amovingobjectposition[aint[l]] = null; + } + + MovingObjectPosition movingobjectposition1 = null; + double d1 = 0.0D; + + for (int l = 0; l < amovingobjectposition.length; ++l) { + MovingObjectPosition movingobjectposition = amovingobjectposition[l]; + if (movingobjectposition != null) { + double d0 = movingobjectposition.hitVec.squareDistanceTo(vec31); + if (d0 > d1) { + movingobjectposition1 = movingobjectposition; + d1 = d0; + } + } + } + + return movingobjectposition1; } - /**+ - * Checks if a block is stairs - */ - public static boolean isBlockStairs(Block blockIn) { - return blockIn instanceof BlockStairs; + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, HALF, SHAPE }); } - /**+ - * Check whether there is a stair block at the given position - * and it has the same properties as the given BlockState - */ - public static boolean isSameStair(IBlockAccess worldIn, BlockPos pos, IBlockState state) { - IBlockState iblockstate = worldIn.getBlockState(pos); - Block block = iblockstate.getBlock(); - /**+ - * Checks if a block is stairs - */ - return isBlockStairs(block) && iblockstate.getValue(HALF) == state.getValue(HALF) - && iblockstate.getValue(FACING) == state.getValue(FACING); - } - - public int func_176307_f(IBlockAccess blockAccess, BlockPos pos) { + public boolean func_176304_i(IBlockAccess blockAccess, BlockPos pos) { IBlockState iblockstate = blockAccess.getBlockState(pos); EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); BlockStairs.EnumHalf blockstairs$enumhalf = (BlockStairs.EnumHalf) iblockstate.getValue(HALF); boolean flag = blockstairs$enumhalf == BlockStairs.EnumHalf.TOP; + float f = 0.5F; + float f1 = 1.0F; + if (flag) { + f = 0.0F; + f1 = 0.5F; + } + + float f2 = 0.0F; + float f3 = 0.5F; + float f4 = 0.5F; + float f5 = 1.0F; + boolean flag1 = false; if (enumfacing == EnumFacing.EAST) { - IBlockState iblockstate1 = blockAccess.getBlockState(pos.east()); + IBlockState iblockstate1 = blockAccess.getBlockState(pos.west()); Block block = iblockstate1.getBlock(); if (isBlockStairs(block) && blockstairs$enumhalf == iblockstate1.getValue(HALF)) { EnumFacing enumfacing1 = (EnumFacing) iblockstate1.getValue(FACING); - if (enumfacing1 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { - return flag ? 1 : 2; - } - - if (enumfacing1 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { - return flag ? 2 : 1; + if (enumfacing1 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { + f4 = 0.0F; + f5 = 0.5F; + flag1 = true; + } else if (enumfacing1 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { + f4 = 0.5F; + f5 = 1.0F; + flag1 = true; } } } else if (enumfacing == EnumFacing.WEST) { - IBlockState iblockstate2 = blockAccess.getBlockState(pos.west()); + IBlockState iblockstate2 = blockAccess.getBlockState(pos.east()); Block block1 = iblockstate2.getBlock(); if (isBlockStairs(block1) && blockstairs$enumhalf == iblockstate2.getValue(HALF)) { + f2 = 0.5F; + f3 = 1.0F; EnumFacing enumfacing2 = (EnumFacing) iblockstate2.getValue(FACING); - if (enumfacing2 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { - return flag ? 2 : 1; - } - - if (enumfacing2 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { - return flag ? 1 : 2; + if (enumfacing2 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { + f4 = 0.0F; + f5 = 0.5F; + flag1 = true; + } else if (enumfacing2 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { + f4 = 0.5F; + f5 = 1.0F; + flag1 = true; } } } else if (enumfacing == EnumFacing.SOUTH) { - IBlockState iblockstate3 = blockAccess.getBlockState(pos.south()); + IBlockState iblockstate3 = blockAccess.getBlockState(pos.north()); Block block2 = iblockstate3.getBlock(); if (isBlockStairs(block2) && blockstairs$enumhalf == iblockstate3.getValue(HALF)) { + f4 = 0.0F; + f5 = 0.5F; EnumFacing enumfacing3 = (EnumFacing) iblockstate3.getValue(FACING); - if (enumfacing3 == EnumFacing.WEST && !isSameStair(blockAccess, pos.east(), iblockstate)) { - return flag ? 2 : 1; - } - - if (enumfacing3 == EnumFacing.EAST && !isSameStair(blockAccess, pos.west(), iblockstate)) { - return flag ? 1 : 2; + if (enumfacing3 == EnumFacing.WEST && !isSameStair(blockAccess, pos.west(), iblockstate)) { + flag1 = true; + } else if (enumfacing3 == EnumFacing.EAST && !isSameStair(blockAccess, pos.east(), iblockstate)) { + f2 = 0.5F; + f3 = 1.0F; + flag1 = true; } } } else if (enumfacing == EnumFacing.NORTH) { - IBlockState iblockstate4 = blockAccess.getBlockState(pos.north()); + IBlockState iblockstate4 = blockAccess.getBlockState(pos.south()); Block block3 = iblockstate4.getBlock(); if (isBlockStairs(block3) && blockstairs$enumhalf == iblockstate4.getValue(HALF)) { EnumFacing enumfacing4 = (EnumFacing) iblockstate4.getValue(FACING); - if (enumfacing4 == EnumFacing.WEST && !isSameStair(blockAccess, pos.east(), iblockstate)) { - return flag ? 1 : 2; - } - - if (enumfacing4 == EnumFacing.EAST && !isSameStair(blockAccess, pos.west(), iblockstate)) { - return flag ? 2 : 1; + if (enumfacing4 == EnumFacing.WEST && !isSameStair(blockAccess, pos.west(), iblockstate)) { + flag1 = true; + } else if (enumfacing4 == EnumFacing.EAST && !isSameStair(blockAccess, pos.east(), iblockstate)) { + f2 = 0.5F; + f3 = 1.0F; + flag1 = true; } } } - return 0; + if (flag1) { + this.setBlockBounds(f2, f, f4, f3, f1, f5); + } + + return flag1; } public int func_176305_g(IBlockAccess blockAccess, BlockPos pos) { @@ -340,301 +444,71 @@ public class BlockStairs extends Block { return flag1; } - public boolean func_176304_i(IBlockAccess blockAccess, BlockPos pos) { + public int func_176307_f(IBlockAccess blockAccess, BlockPos pos) { IBlockState iblockstate = blockAccess.getBlockState(pos); EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); BlockStairs.EnumHalf blockstairs$enumhalf = (BlockStairs.EnumHalf) iblockstate.getValue(HALF); boolean flag = blockstairs$enumhalf == BlockStairs.EnumHalf.TOP; - float f = 0.5F; - float f1 = 1.0F; - if (flag) { - f = 0.0F; - f1 = 0.5F; - } - - float f2 = 0.0F; - float f3 = 0.5F; - float f4 = 0.5F; - float f5 = 1.0F; - boolean flag1 = false; if (enumfacing == EnumFacing.EAST) { - IBlockState iblockstate1 = blockAccess.getBlockState(pos.west()); + IBlockState iblockstate1 = blockAccess.getBlockState(pos.east()); Block block = iblockstate1.getBlock(); if (isBlockStairs(block) && blockstairs$enumhalf == iblockstate1.getValue(HALF)) { EnumFacing enumfacing1 = (EnumFacing) iblockstate1.getValue(FACING); - if (enumfacing1 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { - f4 = 0.0F; - f5 = 0.5F; - flag1 = true; - } else if (enumfacing1 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { - f4 = 0.5F; - f5 = 1.0F; - flag1 = true; + if (enumfacing1 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { + return flag ? 1 : 2; + } + + if (enumfacing1 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { + return flag ? 2 : 1; } } } else if (enumfacing == EnumFacing.WEST) { - IBlockState iblockstate2 = blockAccess.getBlockState(pos.east()); + IBlockState iblockstate2 = blockAccess.getBlockState(pos.west()); Block block1 = iblockstate2.getBlock(); if (isBlockStairs(block1) && blockstairs$enumhalf == iblockstate2.getValue(HALF)) { - f2 = 0.5F; - f3 = 1.0F; EnumFacing enumfacing2 = (EnumFacing) iblockstate2.getValue(FACING); - if (enumfacing2 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { - f4 = 0.0F; - f5 = 0.5F; - flag1 = true; - } else if (enumfacing2 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { - f4 = 0.5F; - f5 = 1.0F; - flag1 = true; + if (enumfacing2 == EnumFacing.NORTH && !isSameStair(blockAccess, pos.south(), iblockstate)) { + return flag ? 2 : 1; + } + + if (enumfacing2 == EnumFacing.SOUTH && !isSameStair(blockAccess, pos.north(), iblockstate)) { + return flag ? 1 : 2; } } } else if (enumfacing == EnumFacing.SOUTH) { - IBlockState iblockstate3 = blockAccess.getBlockState(pos.north()); + IBlockState iblockstate3 = blockAccess.getBlockState(pos.south()); Block block2 = iblockstate3.getBlock(); if (isBlockStairs(block2) && blockstairs$enumhalf == iblockstate3.getValue(HALF)) { - f4 = 0.0F; - f5 = 0.5F; EnumFacing enumfacing3 = (EnumFacing) iblockstate3.getValue(FACING); - if (enumfacing3 == EnumFacing.WEST && !isSameStair(blockAccess, pos.west(), iblockstate)) { - flag1 = true; - } else if (enumfacing3 == EnumFacing.EAST && !isSameStair(blockAccess, pos.east(), iblockstate)) { - f2 = 0.5F; - f3 = 1.0F; - flag1 = true; + if (enumfacing3 == EnumFacing.WEST && !isSameStair(blockAccess, pos.east(), iblockstate)) { + return flag ? 2 : 1; + } + + if (enumfacing3 == EnumFacing.EAST && !isSameStair(blockAccess, pos.west(), iblockstate)) { + return flag ? 1 : 2; } } } else if (enumfacing == EnumFacing.NORTH) { - IBlockState iblockstate4 = blockAccess.getBlockState(pos.south()); + IBlockState iblockstate4 = blockAccess.getBlockState(pos.north()); Block block3 = iblockstate4.getBlock(); if (isBlockStairs(block3) && blockstairs$enumhalf == iblockstate4.getValue(HALF)) { EnumFacing enumfacing4 = (EnumFacing) iblockstate4.getValue(FACING); - if (enumfacing4 == EnumFacing.WEST && !isSameStair(blockAccess, pos.west(), iblockstate)) { - flag1 = true; - } else if (enumfacing4 == EnumFacing.EAST && !isSameStair(blockAccess, pos.east(), iblockstate)) { - f2 = 0.5F; - f3 = 1.0F; - flag1 = true; + if (enumfacing4 == EnumFacing.WEST && !isSameStair(blockAccess, pos.east(), iblockstate)) { + return flag ? 1 : 2; + } + + if (enumfacing4 == EnumFacing.EAST && !isSameStair(blockAccess, pos.west(), iblockstate)) { + return flag ? 2 : 1; } } } - if (flag1) { - this.setBlockBounds(f2, f, f4, f3, f1, f5); - } - - return flag1; + return 0; } - /**+ - * Add all collision boxes of this Block to the list that - * intersect with the given mask. - */ - public void addCollisionBoxesToList(World world, BlockPos blockpos, IBlockState iblockstate, - AxisAlignedBB axisalignedbb, List list, Entity entity) { - this.setBaseCollisionBounds(world, blockpos); - super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); - boolean flag = this.func_176306_h(world, blockpos); - super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); - if (flag && this.func_176304_i(world, blockpos)) { - super.addCollisionBoxesToList(world, blockpos, iblockstate, axisalignedbb, list, entity); - } - - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - } - - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - this.modelBlock.randomDisplayTick(world, blockpos, iblockstate, random); - } - - public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer entityplayer) { - this.modelBlock.onBlockClicked(world, blockpos, entityplayer); - } - - /**+ - * Called when a player destroys this Block - */ - public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { - this.modelBlock.onBlockDestroyedByPlayer(world, blockpos, iblockstate); - } - - public int getMixedBrightnessForBlock(IBlockAccess iblockaccess, BlockPos blockpos) { - return this.modelBlock.getMixedBrightnessForBlock(iblockaccess, blockpos); - } - - /**+ - * Returns how much this block can resist explosions from the - * passed in entity. - */ - public float getExplosionResistance(Entity entity) { - return this.modelBlock.getExplosionResistance(entity); - } - - public EnumWorldBlockLayer getBlockLayer() { - return this.modelBlock.getBlockLayer(); - } - - /**+ - * How many world ticks before ticking - */ - public int tickRate(World world) { - return this.modelBlock.tickRate(world); - } - - public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { - return this.modelBlock.getSelectedBoundingBox(world, blockpos); - } - - public Vec3 modifyAcceleration(World world, BlockPos blockpos, Entity entity, Vec3 vec3) { - return this.modelBlock.modifyAcceleration(world, blockpos, entity, vec3); - } - - /**+ - * Returns if this block is collidable (only used by Fire). - * Args: x, y, z - */ - public boolean isCollidable() { - return this.modelBlock.isCollidable(); - } - - public boolean canCollideCheck(IBlockState iblockstate, boolean flag) { - return this.modelBlock.canCollideCheck(iblockstate, flag); - } - - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - return this.modelBlock.canPlaceBlockAt(world, blockpos); - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { - this.onNeighborBlockChange(world, blockpos, this.modelState, Blocks.air); - this.modelBlock.onBlockAdded(world, blockpos, this.modelState); - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState var3) { - this.modelBlock.breakBlock(world, blockpos, this.modelState); - } - - /**+ - * Triggered whenever an entity collides with this block (enters - * into the block) - */ - public void onEntityCollidedWithBlock(World world, BlockPos blockpos, Entity entity) { - this.modelBlock.onEntityCollidedWithBlock(world, blockpos, entity); - } - - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { - this.modelBlock.updateTick(world, blockpos, iblockstate, random); - } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (!world.isRemote && MinecraftServer.getServer().worldServers[0].getWorldInfo().getGameRulesInstance() - .getBoolean("clickToSit") && entityplayer.getHeldItem() == null) { - EntityArrow arrow = new EntityArrow(world, blockpos.getX() + 0.5D, blockpos.getY(), blockpos.getZ() + 0.5D); - arrow.isChair = true; - world.spawnEntityInWorld(arrow); - entityplayer.mountEntity(arrow); - return true; - } - return this.modelBlock.onBlockActivated(world, blockpos, this.modelState, entityplayer, EnumFacing.DOWN, 0.0F, - 0.0F, 0.0F); - } - - /**+ - * Called when this Block is destroyed by an Explosion - */ - public void onBlockDestroyedByExplosion(World world, BlockPos blockpos, Explosion explosion) { - this.modelBlock.onBlockDestroyedByExplosion(world, blockpos, explosion); - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState var1) { - return this.modelBlock.getMapColor(this.modelState); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2, - int i, EntityLivingBase entitylivingbase) { - IBlockState iblockstate = super.onBlockPlaced(world, blockpos, enumfacing, f, f1, f2, i, entitylivingbase); - iblockstate = iblockstate.withProperty(FACING, entitylivingbase.getHorizontalFacing()).withProperty(SHAPE, - BlockStairs.EnumShape.STRAIGHT); - return enumfacing != EnumFacing.DOWN && (enumfacing == EnumFacing.UP || (double) f1 <= 0.5D) - ? iblockstate.withProperty(HALF, BlockStairs.EnumHalf.BOTTOM) - : iblockstate.withProperty(HALF, BlockStairs.EnumHalf.TOP); - } - - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { - MovingObjectPosition[] amovingobjectposition = new MovingObjectPosition[8]; - IBlockState iblockstate = world.getBlockState(blockpos); - int i = ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - boolean flag = iblockstate.getValue(HALF) == BlockStairs.EnumHalf.TOP; - int[] aint = field_150150_a[i + (flag ? 4 : 0)]; - this.hasRaytraced = true; - - for (int j = 0; j < 8; ++j) { - this.rayTracePass = j; - if (Arrays.binarySearch(aint, j) < 0) { - amovingobjectposition[j] = super.collisionRayTrace(world, blockpos, vec3, vec31); - } - } - - for (int l = 0; l < aint.length; ++l) { - amovingobjectposition[aint[l]] = null; - } - - MovingObjectPosition movingobjectposition1 = null; - double d1 = 0.0D; - - for (int l = 0; l < amovingobjectposition.length; ++l) { - MovingObjectPosition movingobjectposition = amovingobjectposition[l]; - if (movingobjectposition != null) { - double d0 = movingobjectposition.hitVec.squareDistanceTo(vec31); - if (d0 > d1) { - movingobjectposition1 = movingobjectposition; - d1 = d0; - } - } - } - - return movingobjectposition1; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - IBlockState iblockstate = this.getDefaultState().withProperty(HALF, - (i & 4) > 0 ? BlockStairs.EnumHalf.TOP : BlockStairs.EnumHalf.BOTTOM); - iblockstate = iblockstate.withProperty(FACING, EnumFacing.getFront(5 - (i & 3))); - return iblockstate; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - if (iblockstate.getValue(HALF) == BlockStairs.EnumHalf.TOP) { - i |= 4; - } - - i = i | 5 - ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - return i; - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { if (this.func_176306_h(iblockaccess, blockpos)) { @@ -664,44 +538,175 @@ public class BlockStairs extends Block { return iblockstate; } - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, HALF, SHAPE }); + public EnumWorldBlockLayer getBlockLayer() { + return this.modelBlock.getBlockLayer(); } - public static enum EnumHalf implements IStringSerializable { - TOP("top"), BOTTOM("bottom"); - - private final String name; - - private EnumHalf(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } + /** + * + Returns how much this block can resist explosions from the passed in + * entity. + */ + public float getExplosionResistance(Entity entity) { + return this.modelBlock.getExplosionResistance(entity); } - public static enum EnumShape implements IStringSerializable { - STRAIGHT("straight"), INNER_LEFT("inner_left"), INNER_RIGHT("inner_right"), OUTER_LEFT("outer_left"), - OUTER_RIGHT("outer_right"); + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState var1) { + return this.modelBlock.getMapColor(this.modelState); + } - private final String name; - - private EnumShape(String name) { - this.name = name; + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + if (iblockstate.getValue(HALF) == BlockStairs.EnumHalf.TOP) { + i |= 4; } - public String toString() { - return this.name; + i = i | 5 - ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + return i; + } + + public int getMixedBrightnessForBlock(IBlockAccess iblockaccess, BlockPos blockpos) { + return this.modelBlock.getMixedBrightnessForBlock(iblockaccess, blockpos); + } + + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { + return this.modelBlock.getSelectedBoundingBox(world, blockpos); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + IBlockState iblockstate = this.getDefaultState().withProperty(HALF, + (i & 4) > 0 ? BlockStairs.EnumHalf.TOP : BlockStairs.EnumHalf.BOTTOM); + iblockstate = iblockstate.withProperty(FACING, EnumFacing.getFront(5 - (i & 3))); + return iblockstate; + } + + /** + * + Returns if this block is collidable (only used by Fire). Args: x, y, z + */ + public boolean isCollidable() { + return this.modelBlock.isCollidable(); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public Vec3 modifyAcceleration(World world, BlockPos blockpos, Entity entity, Vec3 vec3) { + return this.modelBlock.modifyAcceleration(world, blockpos, entity, vec3); + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState var3, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (!world.isRemote && MinecraftServer.getServer().worldServers[0].getWorldInfo().getGameRulesInstance() + .getBoolean("clickToSit") && entityplayer.getHeldItem() == null) { + EntityArrow arrow = new EntityArrow(world, blockpos.getX() + 0.5D, blockpos.getY(), blockpos.getZ() + 0.5D); + arrow.isChair = true; + world.spawnEntityInWorld(arrow); + entityplayer.mountEntity(arrow); + return true; + } + return this.modelBlock.onBlockActivated(world, blockpos, this.modelState, entityplayer, EnumFacing.DOWN, 0.0F, + 0.0F, 0.0F); + } + + public void onBlockAdded(World world, BlockPos blockpos, IBlockState var3) { + this.onNeighborBlockChange(world, blockpos, this.modelState, Blocks.air); + this.modelBlock.onBlockAdded(world, blockpos, this.modelState); + } + + public void onBlockClicked(World world, BlockPos blockpos, EntityPlayer entityplayer) { + this.modelBlock.onBlockClicked(world, blockpos, entityplayer); + } + + /** + * + Called when this Block is destroyed by an Explosion + */ + public void onBlockDestroyedByExplosion(World world, BlockPos blockpos, Explosion explosion) { + this.modelBlock.onBlockDestroyedByExplosion(world, blockpos, explosion); + } + + /** + * + Called when a player destroys this Block + */ + public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { + this.modelBlock.onBlockDestroyedByPlayer(world, blockpos, iblockstate); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2, + int i, EntityLivingBase entitylivingbase) { + IBlockState iblockstate = super.onBlockPlaced(world, blockpos, enumfacing, f, f1, f2, i, entitylivingbase); + iblockstate = iblockstate.withProperty(FACING, entitylivingbase.getHorizontalFacing()).withProperty(SHAPE, + BlockStairs.EnumShape.STRAIGHT); + return enumfacing != EnumFacing.DOWN && (enumfacing == EnumFacing.UP || (double) f1 <= 0.5D) + ? iblockstate.withProperty(HALF, BlockStairs.EnumHalf.BOTTOM) + : iblockstate.withProperty(HALF, BlockStairs.EnumHalf.TOP); + } + + /** + * + Triggered whenever an entity collides with this block (enters into the + * block) + */ + public void onEntityCollidedWithBlock(World world, BlockPos blockpos, Entity entity) { + this.modelBlock.onEntityCollidedWithBlock(world, blockpos, entity); + } + + public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + this.modelBlock.randomDisplayTick(world, blockpos, iblockstate, random); + } + + /** + * + Set the block bounds as the collision bounds for the stairs at the given + * position + */ + public void setBaseCollisionBounds(IBlockAccess worldIn, BlockPos pos) { + if (worldIn.getBlockState(pos).getValue(HALF) == BlockStairs.EnumHalf.TOP) { + this.setBlockBounds(0.0F, 0.5F, 0.0F, 1.0F, 1.0F, 1.0F); + } else { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); } - public String getName() { - return this.name; + } + + public void setBlockBoundsBasedOnState(IBlockAccess var1, BlockPos var2) { + if (this.hasRaytraced) { + this.setBlockBounds(0.5F * (float) (this.rayTracePass % 2), 0.5F * (float) (this.rayTracePass / 4 % 2), + 0.5F * (float) (this.rayTracePass / 2 % 2), 0.5F + 0.5F * (float) (this.rayTracePass % 2), + 0.5F + 0.5F * (float) (this.rayTracePass / 4 % 2), + 0.5F + 0.5F * (float) (this.rayTracePass / 2 % 2)); + } else { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } + + } + + /** + * + How many world ticks before ticking + */ + public int tickRate(World world) { + return this.modelBlock.tickRate(world); + } + + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { + this.modelBlock.updateTick(world, blockpos, iblockstate, random); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStandingSign.java b/src/game/java/net/minecraft/block/BlockStandingSign.java index bdb4d2f4..c46b0b5d 100644 --- a/src/game/java/net/minecraft/block/BlockStandingSign.java +++ b/src/game/java/net/minecraft/block/BlockStandingSign.java @@ -7,22 +7,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +37,26 @@ public class BlockStandingSign extends BlockSign { this.setDefaultState(this.blockState.getBaseState().withProperty(ROTATION, Integer.valueOf(0))); } - /**+ - * Called when a neighboring block changes. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { ROTATION }); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(ROTATION)).intValue(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(ROTATION, Integer.valueOf(i)); + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { if (!world.getBlockState(blockpos.down()).getBlock().getMaterial().isSolid()) { @@ -45,22 +66,4 @@ public class BlockStandingSign extends BlockSign { super.onNeighborBlockChange(world, blockpos, iblockstate, block); } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(ROTATION, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(ROTATION)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { ROTATION }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStaticLiquid.java b/src/game/java/net/minecraft/block/BlockStaticLiquid.java index 214021de..825639b8 100644 --- a/src/game/java/net/minecraft/block/BlockStaticLiquid.java +++ b/src/game/java/net/minecraft/block/BlockStaticLiquid.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -9,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,8 +41,24 @@ public class BlockStaticLiquid extends BlockLiquid { } - /**+ - * Called when a neighboring block changes. + private boolean getCanBlockBurn(World worldIn, BlockPos pos) { + return worldIn.getBlockState(pos).getBlock().getMaterial().getCanBurn(); + } + + protected boolean isSurroundingBlockFlammable(World worldIn, BlockPos pos) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (this.getCanBlockBurn(worldIn, pos.offset(enumfacing))) { + return true; + } + } + + return false; + } + + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { if (!this.checkForMixing(world, blockpos, iblockstate)) { @@ -86,20 +104,4 @@ public class BlockStaticLiquid extends BlockLiquid { } } } - - protected boolean isSurroundingBlockFlammable(World worldIn, BlockPos pos) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (this.getCanBlockBurn(worldIn, pos.offset(enumfacing))) { - return true; - } - } - - return false; - } - - private boolean getCanBlockBurn(World worldIn, BlockPos pos) { - return worldIn.getBlockState(pos).getBlock().getMaterial().getCanBurn(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockSteelGrate.java b/src/game/java/net/minecraft/block/BlockSteelGrate.java new file mode 100644 index 00000000..31d249fa --- /dev/null +++ b/src/game/java/net/minecraft/block/BlockSteelGrate.java @@ -0,0 +1,56 @@ +package net.minecraft.block; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; +import net.minecraft.block.material.Material; +import net.minecraft.creativetab.CreativeTabs; +import net.minecraft.util.EnumWorldBlockLayer; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class BlockSteelGrate extends BlockBreakable { + public BlockSteelGrate() { + super(Material.iron, false); + } + + protected boolean canSilkHarvest() { + return true; + } + + public boolean eaglerShadersShouldRenderGlassHighlights() { + return DeferredStateManager.isRenderingGlassHighlights(); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public boolean isFullCube() { + return false; + } + + public int quantityDropped(EaglercraftRandom var1) { + return 1; + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStem.java b/src/game/java/net/minecraft/block/BlockStem.java index d008b7ce..e41ee210 100644 --- a/src/game/java/net/minecraft/block/BlockStem.java +++ b/src/game/java/net/minecraft/block/BlockStem.java @@ -1,9 +1,8 @@ package net.minecraft.block; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import com.google.common.base.Predicate; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -21,22 +20,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,10 +62,55 @@ public class BlockStem extends BlockBush implements IGrowable { this.setCreativeTab((CreativeTabs) null); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { + return ((Integer) iblockstate.getValue(AGE)).intValue() != 7; + } + + /** + * + is the block grass, dirt or farmland + */ + protected boolean canPlaceBlockOn(Block block) { + return block == Blocks.farmland; + } + + public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return true; + } + + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return this.getRenderColor(iblockaccess.getBlockState(blockpos)); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { AGE, FACING }); + } + + /** + * + Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { + super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); + if (!world.isRemote) { + Item item = this.getSeedItem(); + if (item != null) { + int j = ((Integer) iblockstate.getValue(AGE)).intValue(); + + for (int k = 0; k < 3; ++k) { + if (world.rand.nextInt(15) <= j) { + spawnAsEntity(world, blockpos, new ItemStack(item)); + } + } + + } + } + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { iblockstate = iblockstate.withProperty(FACING, EnumFacing.UP); @@ -81,11 +128,71 @@ public class BlockStem extends BlockBush implements IGrowable { return iblockstate; } - /**+ - * is the block grass, dirt or farmland + public Item getItem(World var1, BlockPos var2) { + Item item = this.getSeedItem(); + return item != null ? item : null; + } + + /** + * + Get the Item that this Block should drop when harvested. */ - protected boolean canPlaceBlockOn(Block block) { - return block == Blocks.farmland; + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Integer) iblockstate.getValue(AGE)).intValue(); + } + + public int getRenderColor(IBlockState iblockstate) { + if (iblockstate.getBlock() != this) { + return super.getRenderColor(iblockstate); + } else { + int i = ((Integer) iblockstate.getValue(AGE)).intValue(); + int j = i * 32; + int k = 255 - i * 8; + int l = i * 4; + return j << 16 | k << 8 | l; + } + } + + protected Item getSeedItem() { + return this.crop == Blocks.pumpkin ? Items.pumpkin_seeds + : (this.crop == Blocks.melon_block ? Items.melon_seeds : null); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); + } + + public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { + this.growStem(world, blockpos, iblockstate); + } + + public void growStem(World worldIn, BlockPos pos, IBlockState state) { + int i = ((Integer) state.getValue(AGE)).intValue() + MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5); + worldIn.setBlockState(pos, state.withProperty(AGE, Integer.valueOf(Math.min(7, i))), 2); + } + + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + this.maxY = (double) ((float) (((Integer) iblockaccess.getBlockState(blockpos).getValue(AGE)).intValue() * 2 + + 2) / 16.0F); + float f = 0.125F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, (float) this.maxY, 0.5F + f); + } + + /** + * + Sets the block's bounds for rendering it as an item + */ + public void setBlockBoundsForItemRender() { + float f = 0.125F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); } public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -116,110 +223,4 @@ public class BlockStem extends BlockBush implements IGrowable { } } - - public void growStem(World worldIn, BlockPos pos, IBlockState state) { - int i = ((Integer) state.getValue(AGE)).intValue() + MathHelper.getRandomIntegerInRange(worldIn.rand, 2, 5); - worldIn.setBlockState(pos, state.withProperty(AGE, Integer.valueOf(Math.min(7, i))), 2); - } - - public int getRenderColor(IBlockState iblockstate) { - if (iblockstate.getBlock() != this) { - return super.getRenderColor(iblockstate); - } else { - int i = ((Integer) iblockstate.getValue(AGE)).intValue(); - int j = i * 32; - int k = 255 - i * 8; - int l = i * 4; - return j << 16 | k << 8 | l; - } - } - - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return this.getRenderColor(iblockaccess.getBlockState(blockpos)); - } - - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - float f = 0.125F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.25F, 0.5F + f); - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - this.maxY = (double) ((float) (((Integer) iblockaccess.getBlockState(blockpos).getValue(AGE)).intValue() * 2 - + 2) / 16.0F); - float f = 0.125F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, (float) this.maxY, 0.5F + f); - } - - /**+ - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World world, BlockPos blockpos, IBlockState iblockstate, float f, int i) { - super.dropBlockAsItemWithChance(world, blockpos, iblockstate, f, i); - if (!world.isRemote) { - Item item = this.getSeedItem(); - if (item != null) { - int j = ((Integer) iblockstate.getValue(AGE)).intValue(); - - for (int k = 0; k < 3; ++k) { - if (world.rand.nextInt(15) <= j) { - spawnAsEntity(world, blockpos, new ItemStack(item)); - } - } - - } - } - } - - protected Item getSeedItem() { - return this.crop == Blocks.pumpkin ? Items.pumpkin_seeds - : (this.crop == Blocks.melon_block ? Items.melon_seeds : null); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return null; - } - - public Item getItem(World var1, BlockPos var2) { - Item item = this.getSeedItem(); - return item != null ? item : null; - } - - /**+ - * Whether this IGrowable can grow - */ - public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { - return ((Integer) iblockstate.getValue(AGE)).intValue() != 7; - } - - public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { - return true; - } - - public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { - this.growStem(world, blockpos, iblockstate); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(AGE, Integer.valueOf(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Integer) iblockstate.getValue(AGE)).intValue(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { AGE, FACING }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStone.java b/src/game/java/net/minecraft/block/BlockStone.java index f49bffbd..ce357db9 100644 --- a/src/game/java/net/minecraft/block/BlockStone.java +++ b/src/game/java/net/minecraft/block/BlockStone.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -16,103 +16,30 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; import net.minecraft.util.StatCollector; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockStone extends Block { - public static PropertyEnum VARIANT; - - public BlockStone() { - super(Material.rock); - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockStone.EnumType.STONE)); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockStone.EnumType.class); - } - - /**+ - * Gets the localized name of this block. Used for the - * statistics page. - */ - public String getLocalizedName() { - return StatCollector.translateToLocal( - this.getUnlocalizedName() + "." + BlockStone.EnumType.STONE.getUnlocalizedName() + ".name"); - } - - /**+ - * Get the MapColor for this Block and the given BlockState - */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockStone.EnumType) iblockstate.getValue(VARIANT)).func_181072_c(); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { - return iblockstate.getValue(VARIANT) == BlockStone.EnumType.STONE ? Item.getItemFromBlock(Blocks.cobblestone) - : Item.getItemFromBlock(Blocks.stone); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockStone.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockStone.EnumType[] types = BlockStone.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockStone.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockStone.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - public static enum EnumType implements IStringSerializable { STONE(0, MapColor.stoneColor, "stone"), GRANITE(1, MapColor.dirtColor, "granite"), GRANITE_SMOOTH(2, MapColor.dirtColor, "smooth_granite", "graniteSmooth"), @@ -122,9 +49,27 @@ public class BlockStone extends Block { ANDESITE_SMOOTH(6, MapColor.stoneColor, "smooth_andesite", "andesiteSmooth"); public static final BlockStone.EnumType[] META_LOOKUP = new BlockStone.EnumType[7]; + static { + BlockStone.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockStone.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int meta; private final String name; + private final String unlocalizedName; + private final MapColor field_181073_l; private EnumType(int parInt2, MapColor parMapColor, String parString2) { @@ -138,24 +83,12 @@ public class BlockStone extends Block { this.field_181073_l = parMapColor; } - public int getMetadata() { - return this.meta; - } - public MapColor func_181072_c() { return this.field_181073_l; } - public String toString() { - return this.name; - } - - public static BlockStone.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; + public int getMetadata() { + return this.meta; } public String getName() { @@ -166,12 +99,82 @@ public class BlockStone extends Block { return this.unlocalizedName; } - static { - BlockStone.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockStone.EnumType.class); + } + + public BlockStone() { + super(Material.rock); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockStone.EnumType.STONE)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockStone.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState iblockstate, EaglercraftRandom var2, int var3) { + return iblockstate.getValue(VARIANT) == BlockStone.EnumType.STONE ? Item.getItemFromBlock(Blocks.cobblestone) + : Item.getItemFromBlock(Blocks.stone); + } + + /** + * + Gets the localized name of this block. Used for the statistics page. + */ + public String getLocalizedName() { + return StatCollector.translateToLocal( + this.getUnlocalizedName() + "." + BlockStone.EnumType.STONE.getUnlocalizedName() + ".name"); + } + + /** + * + Get the MapColor for this Block and the given BlockState + */ + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockStone.EnumType) iblockstate.getValue(VARIANT)).func_181072_c(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockStone.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockStone.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockStone.EnumType[] types = BlockStone.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStoneBrick.java b/src/game/java/net/minecraft/block/BlockStoneBrick.java index 6d41c37f..36584068 100644 --- a/src/game/java/net/minecraft/block/BlockStoneBrick.java +++ b/src/game/java/net/minecraft/block/BlockStoneBrick.java @@ -12,90 +12,55 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockStoneBrick extends Block { - public static PropertyEnum VARIANT; - public static final int DEFAULT_META = BlockStoneBrick.EnumType.DEFAULT.getMetadata(); - public static final int MOSSY_META = BlockStoneBrick.EnumType.MOSSY.getMetadata(); - public static final int CRACKED_META = BlockStoneBrick.EnumType.CRACKED.getMetadata(); - public static final int CHISELED_META = BlockStoneBrick.EnumType.CHISELED.getMetadata(); - - public BlockStoneBrick() { - super(Material.rock); - this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockStoneBrick.EnumType.DEFAULT)); - this.setCreativeTab(CreativeTabs.tabBlock); - } - - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockStoneBrick.EnumType.class); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockStoneBrick.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockStoneBrick.EnumType[] types = BlockStoneBrick.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockStoneBrick.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockStoneBrick.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { VARIANT }); - } - public static enum EnumType implements IStringSerializable { DEFAULT(0, "stonebrick", "default"), MOSSY(1, "mossy_stonebrick", "mossy"), CRACKED(2, "cracked_stonebrick", "cracked"), CHISELED(3, "chiseled_stonebrick", "chiseled"); public static final BlockStoneBrick.EnumType[] META_LOOKUP = new BlockStoneBrick.EnumType[4]; + static { + BlockStoneBrick.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockStoneBrick.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + private final int meta; + private final String name; + private final String unlocalizedName; private EnumType(int meta, String name, String unlocalizedName) { @@ -108,18 +73,6 @@ public class BlockStoneBrick extends Block { return this.meta; } - public String toString() { - return this.name; - } - - public static BlockStoneBrick.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - public String getName() { return this.name; } @@ -128,12 +81,64 @@ public class BlockStoneBrick extends Block { return this.unlocalizedName; } - static { - BlockStoneBrick.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - + public String toString() { + return this.name; } } + + public static PropertyEnum VARIANT; + public static final int DEFAULT_META = BlockStoneBrick.EnumType.DEFAULT.getMetadata(); + public static final int MOSSY_META = BlockStoneBrick.EnumType.MOSSY.getMetadata(); + public static final int CRACKED_META = BlockStoneBrick.EnumType.CRACKED.getMetadata(); + + public static final int CHISELED_META = BlockStoneBrick.EnumType.CHISELED.getMetadata(); + + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockStoneBrick.EnumType.class); + } + + public BlockStoneBrick() { + super(Material.rock); + this.setDefaultState(this.blockState.getBaseState().withProperty(VARIANT, BlockStoneBrick.EnumType.DEFAULT)); + this.setCreativeTab(CreativeTabs.tabBlock); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockStoneBrick.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockStoneBrick.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockStoneBrick.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockStoneBrick.EnumType[] types = BlockStoneBrick.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStoneSlab.java b/src/game/java/net/minecraft/block/BlockStoneSlab.java index 337b4e84..bca27b17 100644 --- a/src/game/java/net/minecraft/block/BlockStoneSlab.java +++ b/src/game/java/net/minecraft/block/BlockStoneSlab.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -18,30 +18,104 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.IStringSerializable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockStoneSlab extends BlockSlab { + public static enum EnumType implements IStringSerializable { + STONE(0, MapColor.stoneColor, "stone"), SAND(1, MapColor.sandColor, "sandstone", "sand"), + WOOD(2, MapColor.woodColor, "wood_old", "wood"), COBBLESTONE(3, MapColor.stoneColor, "cobblestone", "cobble"), + BRICK(4, MapColor.redColor, "brick"), SMOOTHBRICK(5, MapColor.stoneColor, "stone_brick", "smoothStoneBrick"), + NETHERBRICK(6, MapColor.netherrackColor, "nether_brick", "netherBrick"), + QUARTZ(7, MapColor.quartzColor, "quartz"); + + public static final BlockStoneSlab.EnumType[] META_LOOKUP = new BlockStoneSlab.EnumType[8]; + static { + BlockStoneSlab.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockStoneSlab.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + private final MapColor field_181075_k; + + private final String name; + + private final String unlocalizedName; + + private EnumType(int parInt2, MapColor parMapColor, String parString2) { + this(parInt2, parMapColor, parString2, parString2); + } + + private EnumType(int parInt2, MapColor parMapColor, String parString2, String parString3) { + this.meta = parInt2; + this.field_181075_k = parMapColor; + this.name = parString2; + this.unlocalizedName = parString3; + } + + public MapColor func_181074_c() { + return this.field_181075_k; + } + + public int getMetadata() { + return this.meta; + } + + public String getName() { + return this.name; + } + + /** + * + Returns the slab block name with the type associated with it + */ + public String getUnlocalizedName() { + return this.unlocalizedName; + } + + public String toString() { + return this.name; + } + } + public static final PropertyBool SEAMLESS = PropertyBool.create("seamless"); + public static PropertyEnum VARIANT; + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockStoneSlab.EnumType.class); + } + public BlockStoneSlab() { super(Material.rock); IBlockState iblockstate = this.blockState.getBaseState(); @@ -55,71 +129,40 @@ public abstract class BlockStoneSlab extends BlockSlab { this.setCreativeTab(CreativeTabs.tabBlock); } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockStoneSlab.EnumType.class); + protected BlockState createBlockState() { + return this.isDouble() ? new BlockState(this, new IProperty[] { SEAMLESS, VARIANT }) + : new BlockState(this, new IProperty[] { HALF, VARIANT }); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.stone_slab); + public int damageDropped(IBlockState iblockstate) { + return ((BlockStoneSlab.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); } public Item getItem(World var1, BlockPos var2) { return Item.getItemFromBlock(Blocks.stone_slab); } - /**+ - * Returns the slab block name with the type associated with it + /** + * + Get the Item that this Block should drop when harvested. */ - public String getUnlocalizedName(int i) { - return super.getUnlocalizedName() + "." + BlockStoneSlab.EnumType.byMetadata(i).getUnlocalizedName(); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.stone_slab); } - public IProperty getVariantProperty() { - return VARIANT; - } - - public Object getVariant(ItemStack itemstack) { - return BlockStoneSlab.EnumType.byMetadata(itemstack.getMetadata() & 7); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Get the MapColor for this Block and the given BlockState */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - if (item != Item.getItemFromBlock(Blocks.double_stone_slab)) { - BlockStoneSlab.EnumType[] types = BlockStoneSlab.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - BlockStoneSlab.EnumType blockstoneslab$enumtype = types[i]; - if (blockstoneslab$enumtype != BlockStoneSlab.EnumType.WOOD) { - list.add(new ItemStack(item, 1, blockstoneslab$enumtype.getMetadata())); - } - } - - } + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockStoneSlab.EnumType) iblockstate.getValue(VARIANT)).func_181074_c(); } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, - BlockStoneSlab.EnumType.byMetadata(i & 7)); - if (this.isDouble()) { - iblockstate = iblockstate.withProperty(SEAMLESS, Boolean.valueOf((i & 8) != 0)); - } else { - iblockstate = iblockstate.withProperty(HALF, - (i & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); - } - - return iblockstate; - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -135,89 +178,51 @@ public abstract class BlockStoneSlab extends BlockSlab { return i; } - protected BlockState createBlockState() { - return this.isDouble() ? new BlockState(this, new IProperty[] { SEAMLESS, VARIANT }) - : new BlockState(this, new IProperty[] { HALF, VARIANT }); - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + Convert the given metadata into a BlockState for this Block */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockStoneSlab.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + public IBlockState getStateFromMeta(int i) { + IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, + BlockStoneSlab.EnumType.byMetadata(i & 7)); + if (this.isDouble()) { + iblockstate = iblockstate.withProperty(SEAMLESS, Boolean.valueOf((i & 8) != 0)); + } else { + iblockstate = iblockstate.withProperty(HALF, + (i & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); + } + + return iblockstate; } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockStoneSlab.EnumType) iblockstate.getValue(VARIANT)).func_181074_c(); - } - - public static enum EnumType implements IStringSerializable { - STONE(0, MapColor.stoneColor, "stone"), SAND(1, MapColor.sandColor, "sandstone", "sand"), - WOOD(2, MapColor.woodColor, "wood_old", "wood"), COBBLESTONE(3, MapColor.stoneColor, "cobblestone", "cobble"), - BRICK(4, MapColor.redColor, "brick"), SMOOTHBRICK(5, MapColor.stoneColor, "stone_brick", "smoothStoneBrick"), - NETHERBRICK(6, MapColor.netherrackColor, "nether_brick", "netherBrick"), - QUARTZ(7, MapColor.quartzColor, "quartz"); - - public static final BlockStoneSlab.EnumType[] META_LOOKUP = new BlockStoneSlab.EnumType[8]; - private final int meta; - private final MapColor field_181075_k; - private final String name; - private final String unlocalizedName; - - private EnumType(int parInt2, MapColor parMapColor, String parString2) { - this(parInt2, parMapColor, parString2, parString2); - } - - private EnumType(int parInt2, MapColor parMapColor, String parString2, String parString3) { - this.meta = parInt2; - this.field_181075_k = parMapColor; - this.name = parString2; - this.unlocalizedName = parString3; - } - - public int getMetadata() { - return this.meta; - } - - public MapColor func_181074_c() { - return this.field_181075_k; - } - - public String toString() { - return this.name; - } - - public static BlockStoneSlab.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { - return this.name; - } - - /**+ - * Returns the slab block name with the type associated with it - */ - public String getUnlocalizedName() { - return this.unlocalizedName; - } - - static { - BlockStoneSlab.EnumType[] types = values(); + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + if (item != Item.getItemFromBlock(Blocks.double_stone_slab)) { + BlockStoneSlab.EnumType[] types = BlockStoneSlab.EnumType.META_LOOKUP; for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; + BlockStoneSlab.EnumType blockstoneslab$enumtype = types[i]; + if (blockstoneslab$enumtype != BlockStoneSlab.EnumType.WOOD) { + list.add(new ItemStack(item, 1, blockstoneslab$enumtype.getMetadata())); + } } } } + + /** + * + Returns the slab block name with the type associated with it + */ + public String getUnlocalizedName(int i) { + return super.getUnlocalizedName() + "." + BlockStoneSlab.EnumType.byMetadata(i).getUnlocalizedName(); + } + + public Object getVariant(ItemStack itemstack) { + return BlockStoneSlab.EnumType.byMetadata(itemstack.getMetadata() & 7); + } + + public IProperty getVariantProperty() { + return VARIANT; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockStoneSlabNew.java b/src/game/java/net/minecraft/block/BlockStoneSlabNew.java index 8d755cfd..998faa38 100644 --- a/src/game/java/net/minecraft/block/BlockStoneSlabNew.java +++ b/src/game/java/net/minecraft/block/BlockStoneSlabNew.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -19,30 +19,94 @@ import net.minecraft.util.IStringSerializable; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BlockStoneSlabNew extends BlockSlab { + public static enum EnumType implements IStringSerializable { + RED_SANDSTONE(0, "red_sandstone", BlockSand.EnumType.RED_SAND.getMapColor()); + + public static final BlockStoneSlabNew.EnumType[] META_LOOKUP = new BlockStoneSlabNew.EnumType[1]; + static { + BlockStoneSlabNew.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockStoneSlabNew.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + + private final String name; + + private final MapColor field_181069_e; + + private EnumType(int parInt2, String parString2, MapColor parMapColor) { + this.meta = parInt2; + this.name = parString2; + this.field_181069_e = parMapColor; + } + + public MapColor func_181068_c() { + return this.field_181069_e; + } + + public int getMetadata() { + return this.meta; + } + + public String getName() { + return this.name; + } + + /** + * + Returns the slab block name with the type associated with it + */ + public String getUnlocalizedName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static final PropertyBool SEAMLESS = PropertyBool.create("seamless"); + public static PropertyEnum VARIANT; + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockStoneSlabNew.EnumType.class); + } + public BlockStoneSlabNew() { super(Material.rock); IBlockState iblockstate = this.blockState.getBaseState(); @@ -56,76 +120,47 @@ public abstract class BlockStoneSlabNew extends BlockSlab { this.setCreativeTab(CreativeTabs.tabBlock); } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockStoneSlabNew.EnumType.class); + protected BlockState createBlockState() { + return this.isDouble() ? new BlockState(this, new IProperty[] { SEAMLESS, VARIANT }) + : new BlockState(this, new IProperty[] { HALF, VARIANT }); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ - public String getLocalizedName() { - return StatCollector.translateToLocal(this.getUnlocalizedName() + ".red_sandstone.name"); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.stone_slab2); + public int damageDropped(IBlockState iblockstate) { + return ((BlockStoneSlabNew.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); } public Item getItem(World var1, BlockPos var2) { return Item.getItemFromBlock(Blocks.stone_slab2); } - /**+ - * Returns the slab block name with the type associated with it + /** + * + Get the Item that this Block should drop when harvested. */ - public String getUnlocalizedName(int i) { - return super.getUnlocalizedName() + "." + BlockStoneSlabNew.EnumType.byMetadata(i).getUnlocalizedName(); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.stone_slab2); } - public IProperty getVariantProperty() { - return VARIANT; - } - - public Object getVariant(ItemStack itemstack) { - return BlockStoneSlabNew.EnumType.byMetadata(itemstack.getMetadata() & 7); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Gets the localized name of this block. Used for the statistics page. */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - if (item != Item.getItemFromBlock(Blocks.double_stone_slab2)) { - BlockStoneSlabNew.EnumType[] types = BlockStoneSlabNew.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } + public String getLocalizedName() { + return StatCollector.translateToLocal(this.getUnlocalizedName() + ".red_sandstone.name"); } - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Get the MapColor for this Block and the given BlockState */ - public IBlockState getStateFromMeta(int i) { - IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, - BlockStoneSlabNew.EnumType.byMetadata(i & 7)); - if (this.isDouble()) { - iblockstate = iblockstate.withProperty(SEAMLESS, Boolean.valueOf((i & 8) != 0)); - } else { - iblockstate = iblockstate.withProperty(HALF, - (i & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); - } - - return iblockstate; + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockStoneSlabNew.EnumType) iblockstate.getValue(VARIANT)).func_181068_c(); } - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -141,79 +176,48 @@ public abstract class BlockStoneSlabNew extends BlockSlab { return i; } - protected BlockState createBlockState() { - return this.isDouble() ? new BlockState(this, new IProperty[] { SEAMLESS, VARIANT }) - : new BlockState(this, new IProperty[] { HALF, VARIANT }); - } - - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Convert the given metadata into a BlockState for this Block */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockStoneSlabNew.EnumType) iblockstate.getValue(VARIANT)).func_181068_c(); + public IBlockState getStateFromMeta(int i) { + IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, + BlockStoneSlabNew.EnumType.byMetadata(i & 7)); + if (this.isDouble()) { + iblockstate = iblockstate.withProperty(SEAMLESS, Boolean.valueOf((i & 8) != 0)); + } else { + iblockstate = iblockstate.withProperty(HALF, + (i & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); + } + + return iblockstate; } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockStoneSlabNew.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - public static enum EnumType implements IStringSerializable { - RED_SANDSTONE(0, "red_sandstone", BlockSand.EnumType.RED_SAND.getMapColor()); - - public static final BlockStoneSlabNew.EnumType[] META_LOOKUP = new BlockStoneSlabNew.EnumType[1]; - private final int meta; - private final String name; - private final MapColor field_181069_e; - - private EnumType(int parInt2, String parString2, MapColor parMapColor) { - this.meta = parInt2; - this.name = parString2; - this.field_181069_e = parMapColor; - } - - public int getMetadata() { - return this.meta; - } - - public MapColor func_181068_c() { - return this.field_181069_e; - } - - public String toString() { - return this.name; - } - - public static BlockStoneSlabNew.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { - return this.name; - } - - /**+ - * Returns the slab block name with the type associated with it - */ - public String getUnlocalizedName() { - return this.name; - } - - static { - BlockStoneSlabNew.EnumType[] types = values(); + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + if (item != Item.getItemFromBlock(Blocks.double_stone_slab2)) { + BlockStoneSlabNew.EnumType[] types = BlockStoneSlabNew.EnumType.META_LOOKUP; for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; + list.add(new ItemStack(item, 1, types[i].getMetadata())); } } } + + /** + * + Returns the slab block name with the type associated with it + */ + public String getUnlocalizedName(int i) { + return super.getUnlocalizedName() + "." + BlockStoneSlabNew.EnumType.byMetadata(i).getUnlocalizedName(); + } + + public Object getVariant(ItemStack itemstack) { + return BlockStoneSlabNew.EnumType.byMetadata(itemstack.getMetadata() & 7); + } + + public IProperty getVariantProperty() { + return VARIANT; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockTNT.java b/src/game/java/net/minecraft/block/BlockTNT.java index d81be5cd..f1dcc0a7 100644 --- a/src/game/java/net/minecraft/block/BlockTNT.java +++ b/src/game/java/net/minecraft/block/BlockTNT.java @@ -18,22 +18,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.Explosion; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,44 +50,15 @@ public class BlockTNT extends Block { this.setCreativeTab(CreativeTabs.tabRedstone); } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - super.onBlockAdded(world, blockpos, iblockstate); - if (world.isBlockPowered(blockpos)) { - this.onBlockDestroyedByPlayer(world, blockpos, iblockstate.withProperty(EXPLODE, Boolean.valueOf(true))); - world.setBlockToAir(blockpos); - } - + /** + * + Return whether this block can drop from an explosion. + */ + public boolean canDropFromExplosion(Explosion var1) { + return false; } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (world.isBlockPowered(blockpos)) { - this.onBlockDestroyedByPlayer(world, blockpos, iblockstate.withProperty(EXPLODE, Boolean.valueOf(true))); - world.setBlockToAir(blockpos); - } - - } - - /**+ - * Called when this Block is destroyed by an Explosion - */ - public void onBlockDestroyedByExplosion(World world, BlockPos blockpos, Explosion explosion) { - if (!world.isRemote) { - EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, (double) ((float) blockpos.getX() + 0.5F), - (double) blockpos.getY(), (double) ((float) blockpos.getZ() + 0.5F), - explosion.getExplosivePlacedBy()); - entitytntprimed.fuse = world.rand.nextInt(entitytntprimed.fuse / 4) + entitytntprimed.fuse / 8; - world.spawnEntityInWorld(entitytntprimed); - } - } - - /**+ - * Called when a player destroys this Block - */ - public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { - this.explode(world, blockpos, iblockstate, (EntityLivingBase) null); + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { EXPLODE }); } public void explode(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase igniter) { @@ -98,6 +72,20 @@ public class BlockTNT extends Block { } } + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((Boolean) iblockstate.getValue(EXPLODE)).booleanValue() ? 1 : 0; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(EXPLODE, Boolean.valueOf((i & 1) > 0)); + } + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, EnumFacing enumfacing, float f, float f1, float f2) { if (entityplayer.getCurrentEquippedItem() != null) { @@ -118,8 +106,37 @@ public class BlockTNT extends Block { return super.onBlockActivated(world, blockpos, iblockstate, entityplayer, enumfacing, f, f1, f2); } - /**+ - * Called When an Entity Collided with the Block + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + super.onBlockAdded(world, blockpos, iblockstate); + if (world.isBlockPowered(blockpos)) { + this.onBlockDestroyedByPlayer(world, blockpos, iblockstate.withProperty(EXPLODE, Boolean.valueOf(true))); + world.setBlockToAir(blockpos); + } + + } + + /** + * + Called when this Block is destroyed by an Explosion + */ + public void onBlockDestroyedByExplosion(World world, BlockPos blockpos, Explosion explosion) { + if (!world.isRemote) { + EntityTNTPrimed entitytntprimed = new EntityTNTPrimed(world, (double) ((float) blockpos.getX() + 0.5F), + (double) blockpos.getY(), (double) ((float) blockpos.getZ() + 0.5F), + explosion.getExplosivePlacedBy()); + entitytntprimed.fuse = world.rand.nextInt(entitytntprimed.fuse / 4) + entitytntprimed.fuse / 8; + world.spawnEntityInWorld(entitytntprimed); + } + } + + /** + * + Called when a player destroys this Block + */ + public void onBlockDestroyedByPlayer(World world, BlockPos blockpos, IBlockState iblockstate) { + this.explode(world, blockpos, iblockstate, (EntityLivingBase) null); + } + + /** + * + Called When an Entity Collided with the Block */ public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState var3, Entity entity) { if (!world.isRemote && entity instanceof EntityArrow) { @@ -136,28 +153,14 @@ public class BlockTNT extends Block { } - /**+ - * Return whether this block can drop from an explosion. + /** + * + Called when a neighboring block changes. */ - public boolean canDropFromExplosion(Explosion var1) { - return false; - } + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (world.isBlockPowered(blockpos)) { + this.onBlockDestroyedByPlayer(world, blockpos, iblockstate.withProperty(EXPLODE, Boolean.valueOf(true))); + world.setBlockToAir(blockpos); + } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(EXPLODE, Boolean.valueOf((i & 1) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((Boolean) iblockstate.getValue(EXPLODE)).booleanValue() ? 1 : 0; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { EXPLODE }); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockTallGrass.java b/src/game/java/net/minecraft/block/BlockTallGrass.java index e3201010..d802adfb 100644 --- a/src/game/java/net/minecraft/block/BlockTallGrass.java +++ b/src/game/java/net/minecraft/block/BlockTallGrass.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyEnum; @@ -22,29 +22,78 @@ import net.minecraft.world.ColorizerGrass; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockTallGrass extends BlockBush implements IGrowable { + public static enum EnumType implements IStringSerializable { + DEAD_BUSH(0, "dead_bush"), GRASS(1, "tall_grass"), FERN(2, "fern"); + + private static final BlockTallGrass.EnumType[] META_LOOKUP = new BlockTallGrass.EnumType[3]; + static { + BlockTallGrass.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMeta()] = types[i]; + } + + } + + public static BlockTallGrass.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + + private final String name; + + private EnumType(int meta, String name) { + this.meta = meta; + this.name = name; + } + + public int getMeta() { + return this.meta; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static PropertyEnum TYPE; + public static void bootstrapStates() { + TYPE = PropertyEnum.create("type", BlockTallGrass.EnumType.class); + } + protected BlockTallGrass() { super(Material.vine); this.setDefaultState(this.blockState.getBaseState().withProperty(TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); @@ -52,24 +101,58 @@ public class BlockTallGrass extends BlockBush implements IGrowable { this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); } - public static void bootstrapStates() { - TYPE = PropertyEnum.create("type", BlockTallGrass.EnumType.class); + public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { + return this.canPlaceBlockOn(world.getBlockState(blockpos.down()).getBlock()); + } + + /** + * + Whether this IGrowable can grow + */ + public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { + return iblockstate.getValue(TYPE) != BlockTallGrass.EnumType.DEAD_BUSH; + } + + public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + return true; + } + + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return iblockaccess.getBiomeGenForCoords(blockpos).getGrassColorAtPos(blockpos); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { TYPE }); } public int getBlockColor() { return ColorizerGrass.getGrassColor(0.5D, 1.0D); } - public boolean canBlockStay(World world, BlockPos blockpos, IBlockState var3) { - return this.canPlaceBlockOn(world.getBlockState(blockpos.down()).getBlock()); + public int getDamageValue(World world, BlockPos blockpos) { + IBlockState iblockstate = world.getBlockState(blockpos); + return iblockstate.getBlock().getMetaFromState(iblockstate); } - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) + /** + * + Get the Item that this Block should drop when harvested. */ - public boolean isReplaceable(World var1, BlockPos var2) { - return true; + public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int var3) { + return random.nextInt(8) == 0 ? Items.wheat_seeds : null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockTallGrass.EnumType) iblockstate.getValue(TYPE)).getMeta(); + } + + /** + * + Get the OffsetType for this Block. Determines if the model is rendered + * slightly offset. + */ + public Block.EnumOffsetType getOffsetType() { + return Block.EnumOffsetType.XYZ; } public int getRenderColor(IBlockState iblockstate) { @@ -82,22 +165,34 @@ public class BlockTallGrass extends BlockBush implements IGrowable { } } - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return iblockaccess.getBiomeGenForCoords(blockpos).getGrassColorAtPos(blockpos); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(TYPE, BlockTallGrass.EnumType.byMetadata(i)); } - /**+ - * Get the Item that this Block should drop when harvested. + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom random, int var3) { - return random.nextInt(8) == 0 ? Items.wheat_seeds : null; + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + for (int i = 1; i < 3; ++i) { + list.add(new ItemStack(item, 1, i)); + } + } - /**+ - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { - return 1 + random.nextInt(i * 2 + 1); + public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { + BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.GRASS; + if (iblockstate.getValue(TYPE) == BlockTallGrass.EnumType.FERN) { + blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.FERN; + } + + if (Blocks.double_plant.canPlaceBlockAt(world, blockpos)) { + Blocks.double_plant.placeAt(world, blockpos, blockdoubleplant$enumplanttype, 2); + } + } public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, @@ -113,109 +208,18 @@ public class BlockTallGrass extends BlockBush implements IGrowable { } - public int getDamageValue(World world, BlockPos blockpos) { - IBlockState iblockstate = world.getBlockState(blockpos); - return iblockstate.getBlock().getMetaFromState(iblockstate); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - for (int i = 1; i < 3; ++i) { - list.add(new ItemStack(item, 1, i)); - } - - } - - /**+ - * Whether this IGrowable can grow - */ - public boolean canGrow(World var1, BlockPos var2, IBlockState iblockstate, boolean var4) { - return iblockstate.getValue(TYPE) != BlockTallGrass.EnumType.DEAD_BUSH; - } - - public boolean canUseBonemeal(World var1, EaglercraftRandom var2, BlockPos var3, IBlockState var4) { + public boolean isReplaceable(World var1, BlockPos var2) { return true; } - public void grow(World world, EaglercraftRandom var2, BlockPos blockpos, IBlockState iblockstate) { - BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.GRASS; - if (iblockstate.getValue(TYPE) == BlockTallGrass.EnumType.FERN) { - blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.FERN; - } - - if (Blocks.double_plant.canPlaceBlockAt(world, blockpos)) { - Blocks.double_plant.placeAt(world, blockpos, blockdoubleplant$enumplanttype, 2); - } - - } - - /**+ - * Convert the given metadata into a BlockState for this Block + /** + * + Get the quantity dropped based on the given fortune level */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(TYPE, BlockTallGrass.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockTallGrass.EnumType) iblockstate.getValue(TYPE)).getMeta(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { TYPE }); - } - - /**+ - * Get the OffsetType for this Block. Determines if the model is - * rendered slightly offset. - */ - public Block.EnumOffsetType getOffsetType() { - return Block.EnumOffsetType.XYZ; - } - - public static enum EnumType implements IStringSerializable { - DEAD_BUSH(0, "dead_bush"), GRASS(1, "tall_grass"), FERN(2, "fern"); - - private static final BlockTallGrass.EnumType[] META_LOOKUP = new BlockTallGrass.EnumType[3]; - private final int meta; - private final String name; - - private EnumType(int meta, String name) { - this.meta = meta; - this.name = name; - } - - public int getMeta() { - return this.meta; - } - - public String toString() { - return this.name; - } - - public static BlockTallGrass.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { - return this.name; - } - - static { - BlockTallGrass.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMeta()] = types[i]; - } - - } + public int quantityDroppedWithBonus(int i, EaglercraftRandom random) { + return 1 + random.nextInt(i * 2 + 1); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockTorch.java b/src/game/java/net/minecraft/block/BlockTorch.java index 3ebbbee0..df16b46c 100644 --- a/src/game/java/net/minecraft/block/BlockTorch.java +++ b/src/game/java/net/minecraft/block/BlockTorch.java @@ -1,9 +1,8 @@ package net.minecraft.block; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import com.google.common.base.Predicate; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyDirection; @@ -21,22 +20,25 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,19 +57,20 @@ public class BlockTorch extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; + private boolean canPlaceAt(World worldIn, BlockPos pos, EnumFacing facing) { + BlockPos blockpos = pos.offset(facing.getOpposite()); + boolean flag = facing.getAxis().isHorizontal(); + return flag && worldIn.isBlockNormalCube(blockpos, true) + || facing.equals(EnumFacing.UP) && this.canPlaceOn(worldIn, blockpos); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } + public boolean canPlaceBlockAt(World world, BlockPos blockpos) { + for (EnumFacing enumfacing : FACING.getAllowedValues()) { + if (this.canPlaceAt(world, blockpos, enumfacing)) { + return true; + } + } - public boolean isFullCube() { return false; } @@ -81,26 +84,126 @@ public class BlockTorch extends Block { } } - public boolean canPlaceBlockAt(World world, BlockPos blockpos) { - for (EnumFacing enumfacing : FACING.getAllowedValues()) { - if (this.canPlaceAt(world, blockpos, enumfacing)) { - return true; + protected boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { + if (state.getBlock() == this && this.canPlaceAt(worldIn, pos, (EnumFacing) state.getValue(FACING))) { + return true; + } else { + if (worldIn.getBlockState(pos).getBlock() == this) { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); } + + return false; + } + } + + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. + */ + public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { + EnumFacing enumfacing = (EnumFacing) world.getBlockState(blockpos).getValue(FACING); + float f = 0.15F; + if (enumfacing == EnumFacing.EAST) { + this.setBlockBounds(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); + } else if (enumfacing == EnumFacing.WEST) { + this.setBlockBounds(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); + } else if (enumfacing == EnumFacing.SOUTH) { + this.setBlockBounds(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); + } else if (enumfacing == EnumFacing.NORTH) { + this.setBlockBounds(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); + } else { + f = 0.1F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); } + return super.collisionRayTrace(world, blockpos, vec3, vec31); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + switch ((EnumFacing) iblockstate.getValue(FACING)) { + case EAST: + i = i | 1; + break; + case WEST: + i = i | 2; + break; + case SOUTH: + i = i | 3; + break; + case NORTH: + i = i | 4; + break; + case DOWN: + case UP: + default: + i = i | 5; + } + + return i; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + IBlockState iblockstate = this.getDefaultState(); + switch (i) { + case 1: + iblockstate = iblockstate.withProperty(FACING, EnumFacing.EAST); + break; + case 2: + iblockstate = iblockstate.withProperty(FACING, EnumFacing.WEST); + break; + case 3: + iblockstate = iblockstate.withProperty(FACING, EnumFacing.SOUTH); + break; + case 4: + iblockstate = iblockstate.withProperty(FACING, EnumFacing.NORTH); + break; + case 5: + default: + iblockstate = iblockstate.withProperty(FACING, EnumFacing.UP); + } + + return iblockstate; + } + + public boolean isFullCube() { return false; } - private boolean canPlaceAt(World worldIn, BlockPos pos, EnumFacing facing) { - BlockPos blockpos = pos.offset(facing.getOpposite()); - boolean flag = facing.getAxis().isHorizontal(); - return flag && worldIn.isBlockNormalCube(blockpos, true) - || facing.equals(EnumFacing.UP) && this.canPlaceOn(worldIn, blockpos); + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + this.checkForDrop(world, blockpos, iblockstate); + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate */ public IBlockState onBlockPlaced(World world, BlockPos blockpos, EnumFacing enumfacing, float var4, float var5, float var6, int var7, EntityLivingBase var8) { @@ -119,12 +222,8 @@ public class BlockTorch extends Block { } } - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - this.checkForDrop(world, blockpos, iblockstate); - } - - /**+ - * Called when a neighboring block changes. + /** + * + Called when a neighboring block changes. */ public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { this.onNeighborChangeInternal(world, blockpos, iblockstate); @@ -154,42 +253,6 @@ public class BlockTorch extends Block { } } - protected boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { - if (state.getBlock() == this && this.canPlaceAt(worldIn, pos, (EnumFacing) state.getValue(FACING))) { - return true; - } else { - if (worldIn.getBlockState(pos).getBlock() == this) { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - } - - return false; - } - } - - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { - EnumFacing enumfacing = (EnumFacing) world.getBlockState(blockpos).getValue(FACING); - float f = 0.15F; - if (enumfacing == EnumFacing.EAST) { - this.setBlockBounds(0.0F, 0.2F, 0.5F - f, f * 2.0F, 0.8F, 0.5F + f); - } else if (enumfacing == EnumFacing.WEST) { - this.setBlockBounds(1.0F - f * 2.0F, 0.2F, 0.5F - f, 1.0F, 0.8F, 0.5F + f); - } else if (enumfacing == EnumFacing.SOUTH) { - this.setBlockBounds(0.5F - f, 0.2F, 0.0F, 0.5F + f, 0.8F, f * 2.0F); - } else if (enumfacing == EnumFacing.NORTH) { - this.setBlockBounds(0.5F - f, 0.2F, 1.0F - f * 2.0F, 0.5F + f, 0.8F, 1.0F); - } else { - f = 0.1F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.6F, 0.5F + f); - } - - return super.collisionRayTrace(world, blockpos, vec3, vec31); - } - public void randomDisplayTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); double d0 = (double) blockpos.getX() + 0.5D; @@ -209,65 +272,4 @@ public class BlockTorch extends Block { } } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - IBlockState iblockstate = this.getDefaultState(); - switch (i) { - case 1: - iblockstate = iblockstate.withProperty(FACING, EnumFacing.EAST); - break; - case 2: - iblockstate = iblockstate.withProperty(FACING, EnumFacing.WEST); - break; - case 3: - iblockstate = iblockstate.withProperty(FACING, EnumFacing.SOUTH); - break; - case 4: - iblockstate = iblockstate.withProperty(FACING, EnumFacing.NORTH); - break; - case 5: - default: - iblockstate = iblockstate.withProperty(FACING, EnumFacing.UP); - } - - return iblockstate; - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - switch ((EnumFacing) iblockstate.getValue(FACING)) { - case EAST: - i = i | 1; - break; - case WEST: - i = i | 2; - break; - case SOUTH: - i = i | 3; - break; - case NORTH: - i = i | 4; - break; - case DOWN: - case UP: - default: - i = i | 5; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockTrapDoor.java b/src/game/java/net/minecraft/block/BlockTrapDoor.java index 2413cca5..a467c40d 100644 --- a/src/game/java/net/minecraft/block/BlockTrapDoor.java +++ b/src/game/java/net/minecraft/block/BlockTrapDoor.java @@ -21,31 +21,90 @@ import net.minecraft.util.Vec3; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockTrapDoor extends Block { + public static enum DoorHalf implements IStringSerializable { + TOP("top"), BOTTOM("bottom"); + + private final String name; + + private DoorHalf(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + + public String toString() { + return this.name; + } + } + public static final PropertyDirection FACING = PropertyDirection.create("facing", EnumFacing.Plane.HORIZONTAL); public static final PropertyBool OPEN = PropertyBool.create("open"); + public static PropertyEnum HALF; + public static void bootstrapStates() { + HALF = PropertyEnum.create("half", BlockTrapDoor.DoorHalf.class); + } + + protected static EnumFacing getFacing(int meta) { + switch (meta & 3) { + case 0: + return EnumFacing.NORTH; + case 1: + return EnumFacing.SOUTH; + case 2: + return EnumFacing.WEST; + case 3: + default: + return EnumFacing.EAST; + } + } + + protected static int getMetaForFacing(EnumFacing facing) { + switch (facing) { + case NORTH: + return 0; + case SOUTH: + return 1; + case WEST: + return 2; + case EAST: + default: + return 3; + } + } + + private static boolean isValidSupportBlock(Block blockIn) { + return blockIn.blockMaterial.isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glowstone + || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs; + } + protected BlockTrapDoor(Material materialIn) { super(materialIn); this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH) @@ -56,29 +115,29 @@ public class BlockTrapDoor extends Block { this.setCreativeTab(CreativeTabs.tabRedstone); } - public static void bootstrapStates() { - HALF = PropertyEnum.create("half", BlockTrapDoor.DoorHalf.class); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + /** + * + Check whether this Block can be placed on the given side */ - public boolean isOpaqueCube() { - return false; + public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { + return !enumfacing.getAxis().isVertical() + && isValidSupportBlock(world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock()); } - public boolean isFullCube() { - return false; - } - - public boolean isPassable(IBlockAccess iblockaccess, BlockPos blockpos) { - return !((Boolean) iblockaccess.getBlockState(blockpos).getValue(OPEN)).booleanValue(); - } - - public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { + /** + * + Ray traces through the blocks collision from start vector to end vector + * returning a ray trace hit. + */ + public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { this.setBlockBoundsBasedOnState(world, blockpos); - return super.getSelectedBoundingBox(world, blockpos); + return super.collisionRayTrace(world, blockpos, vec3, vec31); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, OPEN, HALF }); + } + + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; } public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { @@ -86,12 +145,110 @@ public class BlockTrapDoor extends Block { return super.getCollisionBoundingBox(world, blockpos, iblockstate); } + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | getMetaForFacing((EnumFacing) iblockstate.getValue(FACING)); + if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { + i |= 4; + } + + if (iblockstate.getValue(HALF) == BlockTrapDoor.DoorHalf.TOP) { + i |= 8; + } + + return i; + } + + public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos blockpos) { + this.setBlockBoundsBasedOnState(world, blockpos); + return super.getSelectedBoundingBox(world, blockpos); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, getFacing(i)) + .withProperty(OPEN, Boolean.valueOf((i & 4) != 0)) + .withProperty(HALF, (i & 8) == 0 ? BlockTrapDoor.DoorHalf.BOTTOM : BlockTrapDoor.DoorHalf.TOP); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + public boolean isPassable(IBlockAccess iblockaccess, BlockPos blockpos) { + return !((Boolean) iblockaccess.getBlockState(blockpos).getValue(OPEN)).booleanValue(); + } + + public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, + EnumFacing var5, float var6, float var7, float var8) { + if (this.blockMaterial == Material.iron) { + return true; + } else { + iblockstate = iblockstate.cycleProperty(OPEN); + world.setBlockState(blockpos, iblockstate, 2); + world.playAuxSFXAtEntity(entityplayer, ((Boolean) iblockstate.getValue(OPEN)).booleanValue() ? 1003 : 1006, + blockpos, 0); + return true; + } + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float f, float var6, + int var7, EntityLivingBase var8) { + IBlockState iblockstate = this.getDefaultState(); + if (enumfacing.getAxis().isHorizontal()) { + iblockstate = iblockstate.withProperty(FACING, enumfacing).withProperty(OPEN, Boolean.valueOf(false)); + iblockstate = iblockstate.withProperty(HALF, + f > 0.5F ? BlockTrapDoor.DoorHalf.TOP : BlockTrapDoor.DoorHalf.BOTTOM); + } + + return iblockstate; + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + if (!world.isRemote) { + BlockPos blockpos1 = blockpos.offset(((EnumFacing) iblockstate.getValue(FACING)).getOpposite()); + if (!isValidSupportBlock(world.getBlockState(blockpos1).getBlock())) { + world.setBlockToAir(blockpos); + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + } else { + boolean flag = world.isBlockPowered(blockpos); + if (flag || block.canProvidePower()) { + boolean flag1 = ((Boolean) iblockstate.getValue(OPEN)).booleanValue(); + if (flag1 != flag) { + world.setBlockState(blockpos, iblockstate.withProperty(OPEN, Boolean.valueOf(flag)), 2); + world.playAuxSFXAtEntity((EntityPlayer) null, flag ? 1003 : 1006, blockpos, 0); + } + } + } + } + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { this.setBounds(iblockaccess.getBlockState(blockpos)); } - /**+ - * Sets the block's bounds for rendering it as an item + /** + * + Sets the block's bounds for rendering it as an item */ public void setBlockBoundsForItemRender() { float f = 0.1875F; @@ -130,157 +287,4 @@ public class BlockTrapDoor extends Block { } } - - public boolean onBlockActivated(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer, - EnumFacing var5, float var6, float var7, float var8) { - if (this.blockMaterial == Material.iron) { - return true; - } else { - iblockstate = iblockstate.cycleProperty(OPEN); - world.setBlockState(blockpos, iblockstate, 2); - world.playAuxSFXAtEntity(entityplayer, ((Boolean) iblockstate.getValue(OPEN)).booleanValue() ? 1003 : 1006, - blockpos, 0); - return true; - } - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - if (!world.isRemote) { - BlockPos blockpos1 = blockpos.offset(((EnumFacing) iblockstate.getValue(FACING)).getOpposite()); - if (!isValidSupportBlock(world.getBlockState(blockpos1).getBlock())) { - world.setBlockToAir(blockpos); - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - } else { - boolean flag = world.isBlockPowered(blockpos); - if (flag || block.canProvidePower()) { - boolean flag1 = ((Boolean) iblockstate.getValue(OPEN)).booleanValue(); - if (flag1 != flag) { - world.setBlockState(blockpos, iblockstate.withProperty(OPEN, Boolean.valueOf(flag)), 2); - world.playAuxSFXAtEntity((EntityPlayer) null, flag ? 1003 : 1006, blockpos, 0); - } - } - } - } - } - - /**+ - * Ray traces through the blocks collision from start vector to - * end vector returning a ray trace hit. - */ - public MovingObjectPosition collisionRayTrace(World world, BlockPos blockpos, Vec3 vec3, Vec3 vec31) { - this.setBlockBoundsBasedOnState(world, blockpos); - return super.collisionRayTrace(world, blockpos, vec3, vec31); - } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float f, float var6, - int var7, EntityLivingBase var8) { - IBlockState iblockstate = this.getDefaultState(); - if (enumfacing.getAxis().isHorizontal()) { - iblockstate = iblockstate.withProperty(FACING, enumfacing).withProperty(OPEN, Boolean.valueOf(false)); - iblockstate = iblockstate.withProperty(HALF, - f > 0.5F ? BlockTrapDoor.DoorHalf.TOP : BlockTrapDoor.DoorHalf.BOTTOM); - } - - return iblockstate; - } - - /**+ - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { - return !enumfacing.getAxis().isVertical() - && isValidSupportBlock(world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock()); - } - - protected static EnumFacing getFacing(int meta) { - switch (meta & 3) { - case 0: - return EnumFacing.NORTH; - case 1: - return EnumFacing.SOUTH; - case 2: - return EnumFacing.WEST; - case 3: - default: - return EnumFacing.EAST; - } - } - - protected static int getMetaForFacing(EnumFacing facing) { - switch (facing) { - case NORTH: - return 0; - case SOUTH: - return 1; - case WEST: - return 2; - case EAST: - default: - return 3; - } - } - - private static boolean isValidSupportBlock(Block blockIn) { - return blockIn.blockMaterial.isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glowstone - || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, getFacing(i)) - .withProperty(OPEN, Boolean.valueOf((i & 4) != 0)) - .withProperty(HALF, (i & 8) == 0 ? BlockTrapDoor.DoorHalf.BOTTOM : BlockTrapDoor.DoorHalf.TOP); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | getMetaForFacing((EnumFacing) iblockstate.getValue(FACING)); - if (((Boolean) iblockstate.getValue(OPEN)).booleanValue()) { - i |= 4; - } - - if (iblockstate.getValue(HALF) == BlockTrapDoor.DoorHalf.TOP) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, OPEN, HALF }); - } - - public static enum DoorHalf implements IStringSerializable { - TOP("top"), BOTTOM("bottom"); - - private final String name; - - private DoorHalf(String name) { - this.name = name; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockTripWire.java b/src/game/java/net/minecraft/block/BlockTripWire.java index 4aa4f258..cbdf0c11 100644 --- a/src/game/java/net/minecraft/block/BlockTripWire.java +++ b/src/game/java/net/minecraft/block/BlockTripWire.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -20,22 +20,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,6 +53,22 @@ public class BlockTripWire extends Block { public static final PropertyBool SOUTH = PropertyBool.create("south"); public static final PropertyBool WEST = PropertyBool.create("west"); + public static boolean isConnectedTo(IBlockAccess worldIn, BlockPos pos, IBlockState state, EnumFacing direction) { + BlockPos blockpos = pos.offset(direction); + IBlockState iblockstate = worldIn.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + if (block == Blocks.tripwire_hook) { + EnumFacing enumfacing = direction.getOpposite(); + return iblockstate.getValue(BlockTripWireHook.FACING) == enumfacing; + } else if (block == Blocks.tripwire) { + boolean flag = ((Boolean) state.getValue(SUSPENDED)).booleanValue(); + boolean flag1 = ((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue(); + return flag == flag1; + } else { + return false; + } + } + public BlockTripWire() { super(Material.circuits); this.setDefaultState(this.blockState.getBaseState().withProperty(POWERED, Boolean.valueOf(false)) @@ -61,10 +80,18 @@ public class BlockTripWire extends Block { this.setTickRandomly(true); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + this.notifyHook(world, blockpos, iblockstate.withProperty(POWERED, Boolean.valueOf(true))); + } + + protected BlockState createBlockState() { + return new BlockState(this, + new IProperty[] { POWERED, SUSPENDED, ATTACHED, DISARMED, NORTH, EAST, WEST, SOUTH }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { return iblockstate @@ -78,82 +105,69 @@ public class BlockTripWire extends Block { Boolean.valueOf(isConnectedTo(iblockaccess, blockpos, iblockstate, EnumFacing.WEST))); } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.TRANSLUCENT; } - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.string; + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; } public Item getItem(World var1, BlockPos var2) { return Items.string; } - /**+ - * Called when a neighboring block changes. + /** + * + Get the Item that this Block should drop when harvested. */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - boolean flag = ((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue(); - boolean flag1 = !World.doesBlockHaveSolidTopSurface(world, blockpos.down()); - if (flag != flag1) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.string; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 1; } - } - - public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { - IBlockState iblockstate = iblockaccess.getBlockState(blockpos); - boolean flag = ((Boolean) iblockstate.getValue(ATTACHED)).booleanValue(); - boolean flag1 = ((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue(); - if (!flag1) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.09375F, 1.0F); - } else if (!flag) { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); - } else { - this.setBlockBounds(0.0F, 0.0625F, 0.0F, 1.0F, 0.15625F, 1.0F); + if (((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue()) { + i |= 2; } - } - - public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { - iblockstate = iblockstate.withProperty(SUSPENDED, - Boolean.valueOf(!World.doesBlockHaveSolidTopSurface(world, blockpos.down()))); - world.setBlockState(blockpos, iblockstate, 3); - this.notifyHook(world, blockpos, iblockstate); - } - - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - this.notifyHook(world, blockpos, iblockstate.withProperty(POWERED, Boolean.valueOf(true))); - } - - public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { - if (!world.isRemote) { - if (entityplayer.getCurrentEquippedItem() != null - && entityplayer.getCurrentEquippedItem().getItem() == Items.shears) { - world.setBlockState(blockpos, iblockstate.withProperty(DISARMED, Boolean.valueOf(true)), 4); - } + if (((Boolean) iblockstate.getValue(ATTACHED)).booleanValue()) { + i |= 4; } + + if (((Boolean) iblockstate.getValue(DISARMED)).booleanValue()) { + i |= 8; + } + + return i; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(POWERED, Boolean.valueOf((i & 1) > 0)) + .withProperty(SUSPENDED, Boolean.valueOf((i & 2) > 0)) + .withProperty(ATTACHED, Boolean.valueOf((i & 4) > 0)) + .withProperty(DISARMED, Boolean.valueOf((i & 8) > 0)); + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; } private void notifyHook(World worldIn, BlockPos pos, IBlockState state) { @@ -176,8 +190,24 @@ public class BlockTripWire extends Block { } - /**+ - * Called When an Entity Collided with the Block + public void onBlockAdded(World world, BlockPos blockpos, IBlockState iblockstate) { + iblockstate = iblockstate.withProperty(SUSPENDED, + Boolean.valueOf(!World.doesBlockHaveSolidTopSurface(world, blockpos.down()))); + world.setBlockState(blockpos, iblockstate, 3); + this.notifyHook(world, blockpos, iblockstate); + } + + public void onBlockHarvested(World world, BlockPos blockpos, IBlockState iblockstate, EntityPlayer entityplayer) { + if (!world.isRemote) { + if (entityplayer.getCurrentEquippedItem() != null + && entityplayer.getCurrentEquippedItem().getItem() == Items.shears) { + world.setBlockState(blockpos, iblockstate.withProperty(DISARMED, Boolean.valueOf(true)), 4); + } + } + } + + /** + * + Called When an Entity Collided with the Block */ public void onEntityCollidedWithBlock(World world, BlockPos blockpos, IBlockState iblockstate, Entity var4) { if (!world.isRemote) { @@ -187,19 +217,38 @@ public class BlockTripWire extends Block { } } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + boolean flag = ((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue(); + boolean flag1 = !World.doesBlockHaveSolidTopSurface(world, blockpos.down()); + if (flag != flag1) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + } + + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) */ public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { } - public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { - if (!world.isRemote) { - if (((Boolean) world.getBlockState(blockpos).getValue(POWERED)).booleanValue()) { - this.updateState(world, blockpos); - } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { + IBlockState iblockstate = iblockaccess.getBlockState(blockpos); + boolean flag = ((Boolean) iblockstate.getValue(ATTACHED)).booleanValue(); + boolean flag1 = ((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue(); + if (!flag1) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.09375F, 1.0F); + } else if (!flag) { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); + } else { + this.setBlockBounds(0.0F, 0.0625F, 0.0F, 1.0F, 0.15625F, 1.0F); } + } private void updateState(World worldIn, BlockPos pos) { @@ -231,58 +280,11 @@ public class BlockTripWire extends Block { } - public static boolean isConnectedTo(IBlockAccess worldIn, BlockPos pos, IBlockState state, EnumFacing direction) { - BlockPos blockpos = pos.offset(direction); - IBlockState iblockstate = worldIn.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - if (block == Blocks.tripwire_hook) { - EnumFacing enumfacing = direction.getOpposite(); - return iblockstate.getValue(BlockTripWireHook.FACING) == enumfacing; - } else if (block == Blocks.tripwire) { - boolean flag = ((Boolean) state.getValue(SUSPENDED)).booleanValue(); - boolean flag1 = ((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue(); - return flag == flag1; - } else { - return false; + public void updateTick(World world, BlockPos blockpos, IBlockState var3, EaglercraftRandom var4) { + if (!world.isRemote) { + if (((Boolean) world.getBlockState(blockpos).getValue(POWERED)).booleanValue()) { + this.updateState(world, blockpos); + } } } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(POWERED, Boolean.valueOf((i & 1) > 0)) - .withProperty(SUSPENDED, Boolean.valueOf((i & 2) > 0)) - .withProperty(ATTACHED, Boolean.valueOf((i & 4) > 0)) - .withProperty(DISARMED, Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 1; - } - - if (((Boolean) iblockstate.getValue(SUSPENDED)).booleanValue()) { - i |= 2; - } - - if (((Boolean) iblockstate.getValue(ATTACHED)).booleanValue()) { - i |= 4; - } - - if (((Boolean) iblockstate.getValue(DISARMED)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, - new IProperty[] { POWERED, SUSPENDED, ATTACHED, DISARMED, NORTH, EAST, WEST, SOUTH }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockTripWireHook.java b/src/game/java/net/minecraft/block/BlockTripWireHook.java index d877de69..99b60631 100644 --- a/src/game/java/net/minecraft/block/BlockTripWireHook.java +++ b/src/game/java/net/minecraft/block/BlockTripWireHook.java @@ -1,9 +1,8 @@ package net.minecraft.block; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import com.google.common.base.Objects; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -21,22 +20,25 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,38 +58,20 @@ public class BlockTripWireHook extends Block { this.setTickRandomly(true); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - return iblockstate.withProperty(SUSPENDED, - Boolean.valueOf(!World.doesBlockHaveSolidTopSurface(iblockaccess, blockpos.down()))); - } + public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { + boolean flag = ((Boolean) iblockstate.getValue(ATTACHED)).booleanValue(); + boolean flag1 = ((Boolean) iblockstate.getValue(POWERED)).booleanValue(); + if (flag || flag1) { + this.func_176260_a(world, blockpos, iblockstate, true, false, -1, (IBlockState) null); + } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } + if (flag1) { + world.notifyNeighborsOfStateChange(blockpos, this); + world.notifyNeighborsOfStateChange( + blockpos.offset(((EnumFacing) iblockstate.getValue(FACING)).getOpposite()), this); + } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { - return enumfacing.getAxis().isHorizontal() - && world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().isNormalCube(); + super.breakBlock(world, blockpos, iblockstate); } public boolean canPlaceBlockAt(World world, BlockPos blockpos) { @@ -102,46 +86,36 @@ public class BlockTripWireHook extends Block { return false; } - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate + /** + * + Check whether this Block can be placed on the given side */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase var8) { - IBlockState iblockstate = this.getDefaultState().withProperty(POWERED, Boolean.valueOf(false)) - .withProperty(ATTACHED, Boolean.valueOf(false)).withProperty(SUSPENDED, Boolean.valueOf(false)); - if (enumfacing.getAxis().isHorizontal()) { - iblockstate = iblockstate.withProperty(FACING, enumfacing); - } - - return iblockstate; + public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { + return enumfacing.getAxis().isHorizontal() + && world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().isNormalCube(); } - /**+ - * Called by ItemBlocks after a block is set in the world, to - * allow post-place logic + /** + * + Can this block provide power. Only wire currently seems to have this change + * based on its state. */ - public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, EntityLivingBase var4, - ItemStack var5) { - this.func_176260_a(world, blockpos, iblockstate, false, false, -1, (IBlockState) null); + public boolean canProvidePower() { + return true; } - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - if (block != this) { - if (this.checkForDrop(world, blockpos, iblockstate)) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (!world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().isNormalCube()) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - } - + private boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { + if (!this.canPlaceBlockAt(worldIn, pos)) { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + return false; + } else { + return true; } } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING, POWERED, ATTACHED, SUSPENDED }); + } + public void func_176260_a(World worldIn, BlockPos pos, IBlockState hookState, boolean parFlag, boolean parFlag2, int parInt1, IBlockState parIBlockState2) { EnumFacing enumfacing = (EnumFacing) hookState.getValue(FACING); @@ -216,15 +190,9 @@ public class BlockTripWireHook extends Block { } - /**+ - * Called randomly when setTickRandomly is set to true (used by - * e.g. crops to grow, etc.) - */ - public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { - } - - public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { - this.func_176260_a(world, blockpos, iblockstate, false, true, -1, (IBlockState) null); + private void func_176262_b(World worldIn, BlockPos parBlockPos, EnumFacing parEnumFacing) { + worldIn.notifyNeighborsOfStateChange(parBlockPos, this); + worldIn.notifyNeighborsOfStateChange(parBlockPos.offset(parEnumFacing.getOpposite()), this); } private void func_180694_a(World worldIn, BlockPos pos, boolean parFlag, boolean parFlag2, boolean parFlag3, @@ -245,19 +213,115 @@ public class BlockTripWireHook extends Block { } - private void func_176262_b(World worldIn, BlockPos parBlockPos, EnumFacing parEnumFacing) { - worldIn.notifyNeighborsOfStateChange(parBlockPos, this); - worldIn.notifyNeighborsOfStateChange(parBlockPos.offset(parEnumFacing.getOpposite()), this); + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + return iblockstate.withProperty(SUSPENDED, + Boolean.valueOf(!World.doesBlockHaveSolidTopSurface(iblockaccess, blockpos.down()))); } - private boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) { - if (!this.canPlaceBlockAt(worldIn, pos)) { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - return false; - } else { - return true; + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT_MIPPED; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); + if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { + i |= 8; } + + if (((Boolean) iblockstate.getValue(ATTACHED)).booleanValue()) { + i |= 4; + } + + return i; + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i & 3)) + .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)) + .withProperty(ATTACHED, Boolean.valueOf((i & 4) > 0)); + } + + public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { + return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 + : (iblockstate.getValue(FACING) == enumfacing ? 15 : 0); + } + + public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { + return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase var8) { + IBlockState iblockstate = this.getDefaultState().withProperty(POWERED, Boolean.valueOf(false)) + .withProperty(ATTACHED, Boolean.valueOf(false)).withProperty(SUSPENDED, Boolean.valueOf(false)); + if (enumfacing.getAxis().isHorizontal()) { + iblockstate = iblockstate.withProperty(FACING, enumfacing); + } + + return iblockstate; + } + + /** + * + Called by ItemBlocks after a block is set in the world, to allow post-place + * logic + */ + public void onBlockPlacedBy(World world, BlockPos blockpos, IBlockState iblockstate, EntityLivingBase var4, + ItemStack var5) { + this.func_176260_a(world, blockpos, iblockstate, false, false, -1, (IBlockState) null); + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + if (block != this) { + if (this.checkForDrop(world, blockpos, iblockstate)) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (!world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().isNormalCube()) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + } + + } + } + + /** + * + Called randomly when setTickRandomly is set to true (used by e.g. crops to + * grow, etc.) + */ + public void randomTick(World var1, BlockPos var2, IBlockState var3, EaglercraftRandom var4) { } public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { @@ -278,70 +342,7 @@ public class BlockTripWireHook extends Block { } - public void breakBlock(World world, BlockPos blockpos, IBlockState iblockstate) { - boolean flag = ((Boolean) iblockstate.getValue(ATTACHED)).booleanValue(); - boolean flag1 = ((Boolean) iblockstate.getValue(POWERED)).booleanValue(); - if (flag || flag1) { - this.func_176260_a(world, blockpos, iblockstate, true, false, -1, (IBlockState) null); - } - - if (flag1) { - world.notifyNeighborsOfStateChange(blockpos, this); - world.notifyNeighborsOfStateChange( - blockpos.offset(((EnumFacing) iblockstate.getValue(FACING)).getOpposite()), this); - } - - super.breakBlock(world, blockpos, iblockstate); - } - - public int getWeakPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing var4) { - return ((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 15 : 0; - } - - public int getStrongPower(IBlockAccess var1, BlockPos var2, IBlockState iblockstate, EnumFacing enumfacing) { - return !((Boolean) iblockstate.getValue(POWERED)).booleanValue() ? 0 - : (iblockstate.getValue(FACING) == enumfacing ? 15 : 0); - } - - /**+ - * Can this block provide power. Only wire currently seems to - * have this change based on its state. - */ - public boolean canProvidePower() { - return true; - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT_MIPPED; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(i & 3)) - .withProperty(POWERED, Boolean.valueOf((i & 8) > 0)) - .withProperty(ATTACHED, Boolean.valueOf((i & 4) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - i = i | ((EnumFacing) iblockstate.getValue(FACING)).getHorizontalIndex(); - if (((Boolean) iblockstate.getValue(POWERED)).booleanValue()) { - i |= 8; - } - - if (((Boolean) iblockstate.getValue(ATTACHED)).booleanValue()) { - i |= 4; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING, POWERED, ATTACHED, SUSPENDED }); + public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom var4) { + this.func_176260_a(world, blockpos, iblockstate, false, true, -1, (IBlockState) null); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockVine.java b/src/game/java/net/minecraft/block/BlockVine.java index 182e8b34..338ae0ce 100644 --- a/src/game/java/net/minecraft/block/BlockVine.java +++ b/src/game/java/net/minecraft/block/BlockVine.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; import net.minecraft.block.properties.PropertyBool; @@ -24,22 +23,25 @@ import net.minecraft.world.ColorizerFoliage; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,6 +54,35 @@ public class BlockVine extends Block { public static final PropertyBool WEST = PropertyBool.create("west"); public static final PropertyBool[] ALL_FACES = new PropertyBool[] { UP, NORTH, SOUTH, WEST, EAST }; + public static int getNumGrownFaces(IBlockState state) { + int i = 0; + + for (int j = 0; j < ALL_FACES.length; ++j) { + if (((Boolean) state.getValue(ALL_FACES[j])).booleanValue()) { + ++i; + } + } + + return i; + } + + public static PropertyBool getPropertyFor(EnumFacing side) { + switch (side) { + case UP: + return UP; + case NORTH: + return NORTH; + case SOUTH: + return SOUTH; + case EAST: + return EAST; + case WEST: + return WEST; + default: + throw new IllegalArgumentException(side + " is an invalid choice"); + } + } + public BlockVine() { super(Material.vine); this.setDefaultState(this.blockState.getBaseState().withProperty(UP, Boolean.valueOf(false)) @@ -61,43 +92,193 @@ public class BlockVine extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. + /** + * + Check whether this Block can be placed on the given side + */ + public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { + switch (enumfacing) { + case UP: + return this.canPlaceOn(world.getBlockState(blockpos.up()).getBlock()); + case NORTH: + case SOUTH: + case EAST: + case WEST: + return this.canPlaceOn(world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock()); + default: + return false; + } + } + + private boolean canPlaceOn(Block blockIn) { + return blockIn.isFullCube() && blockIn.blockMaterial.blocksMovement(); + } + + public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { + return iblockaccess.getBiomeGenForCoords(blockpos).getFoliageColorAtPos(blockpos); + } + + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { UP, NORTH, EAST, SOUTH, WEST }); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. */ public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { return iblockstate.withProperty(UP, Boolean.valueOf(iblockaccess.getBlockState(blockpos.up()).getBlock().isBlockNormalCube())); } - /**+ - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() { - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + public int getBlockColor() { + return ColorizerFoliage.getFoliageColorBasic(); } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render + public EnumWorldBlockLayer getBlockLayer() { + return EnumWorldBlockLayer.CUTOUT; + } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + /** + * + Get the Item that this Block should drop when harvested. */ - public boolean isOpaqueCube() { - return false; + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return null; + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + int i = 0; + if (((Boolean) iblockstate.getValue(SOUTH)).booleanValue()) { + i |= 1; + } + + if (((Boolean) iblockstate.getValue(WEST)).booleanValue()) { + i |= 2; + } + + if (((Boolean) iblockstate.getValue(NORTH)).booleanValue()) { + i |= 4; + } + + if (((Boolean) iblockstate.getValue(EAST)).booleanValue()) { + i |= 8; + } + + return i; + } + + public int getRenderColor(IBlockState var1) { + return ColorizerFoliage.getFoliageColorBasic(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(SOUTH, Boolean.valueOf((i & 1) > 0)) + .withProperty(WEST, Boolean.valueOf((i & 2) > 0)).withProperty(NORTH, Boolean.valueOf((i & 4) > 0)) + .withProperty(EAST, Boolean.valueOf((i & 8) > 0)); + } + + public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, + TileEntity tileentity) { + if (!world.isRemote && entityplayer.getCurrentEquippedItem() != null + && entityplayer.getCurrentEquippedItem().getItem() == Items.shears) { + entityplayer.triggerAchievement(StatList.mineBlockStatArray[Block.getIdFromBlock(this)]); + spawnAsEntity(world, blockpos, new ItemStack(Blocks.vine, 1, 0)); + } else { + super.harvestBlock(world, entityplayer, blockpos, iblockstate, tileentity); + } + } public boolean isFullCube() { return false; } - /**+ - * Whether this Block can be replaced directly by other blocks - * (true for e.g. tall grass) + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Whether this Block can be replaced directly by other blocks (true for e.g. + * tall grass) */ public boolean isReplaceable(World var1, BlockPos var2) { return true; } + /** + * + Called by ItemBlocks just before a block is actually set in the world, to + * allow for adjustments to the IBlockstate + */ + public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, + float var6, int var7, EntityLivingBase var8) { + IBlockState iblockstate = this.getDefaultState().withProperty(UP, Boolean.valueOf(false)) + .withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)) + .withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)); + return enumfacing.getAxis().isHorizontal() + ? iblockstate.withProperty(getPropertyFor(enumfacing.getOpposite()), Boolean.valueOf(true)) + : iblockstate; + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { + if (!world.isRemote && !this.recheckGrownSides(world, blockpos, iblockstate)) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + } + + /** + * + Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(EaglercraftRandom var1) { + return 0; + } + + private boolean recheckGrownSides(World worldIn, BlockPos pos, IBlockState state) { + IBlockState iblockstate = state; + + BlockPos tmp = new BlockPos(0, 0, 0); + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + PropertyBool propertybool = getPropertyFor(enumfacing); + if (((Boolean) state.getValue(propertybool)).booleanValue() + && !this.canPlaceOn(worldIn.getBlockState(pos.offsetEvenFaster(enumfacing, tmp)).getBlock())) { + IBlockState iblockstate1 = worldIn.getBlockState(pos.offsetEvenFaster(EnumFacing.UP, tmp)); + if (iblockstate1.getBlock() != this + || !((Boolean) iblockstate1.getValue(propertybool)).booleanValue()) { + state = state.withProperty(propertybool, Boolean.valueOf(false)); + } + } + } + + if (getNumGrownFaces(state) == 0) { + return false; + } else { + if (iblockstate != state) { + worldIn.setBlockState(pos, state, 2); + } + + return true; + } + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { float f = 0.0625F; float f1 = 1.0F; @@ -159,81 +340,11 @@ public class BlockVine extends Block { this.setBlockBounds(f1, f2, f3, f4, f5, f6); } - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - /**+ - * Check whether this Block can be placed on the given side + /** + * + Sets the block's bounds for rendering it as an item */ - public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing) { - switch (enumfacing) { - case UP: - return this.canPlaceOn(world.getBlockState(blockpos.up()).getBlock()); - case NORTH: - case SOUTH: - case EAST: - case WEST: - return this.canPlaceOn(world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock()); - default: - return false; - } - } - - private boolean canPlaceOn(Block blockIn) { - return blockIn.isFullCube() && blockIn.blockMaterial.blocksMovement(); - } - - private boolean recheckGrownSides(World worldIn, BlockPos pos, IBlockState state) { - IBlockState iblockstate = state; - - BlockPos tmp = new BlockPos(0, 0, 0); - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - PropertyBool propertybool = getPropertyFor(enumfacing); - if (((Boolean) state.getValue(propertybool)).booleanValue() - && !this.canPlaceOn(worldIn.getBlockState(pos.offsetEvenFaster(enumfacing, tmp)).getBlock())) { - IBlockState iblockstate1 = worldIn.getBlockState(pos.offsetEvenFaster(EnumFacing.UP, tmp)); - if (iblockstate1.getBlock() != this - || !((Boolean) iblockstate1.getValue(propertybool)).booleanValue()) { - state = state.withProperty(propertybool, Boolean.valueOf(false)); - } - } - } - - if (getNumGrownFaces(state) == 0) { - return false; - } else { - if (iblockstate != state) { - worldIn.setBlockState(pos, state, 2); - } - - return true; - } - } - - public int getBlockColor() { - return ColorizerFoliage.getFoliageColorBasic(); - } - - public int getRenderColor(IBlockState var1) { - return ColorizerFoliage.getFoliageColorBasic(); - } - - public int colorMultiplier(IBlockAccess iblockaccess, BlockPos blockpos, int var3) { - return iblockaccess.getBiomeGenForCoords(blockpos).getFoliageColorAtPos(blockpos); - } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block var4) { - if (!world.isRemote && !this.recheckGrownSides(world, blockpos, iblockstate)) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - + public void setBlockBoundsForItemRender() { + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } public void updateTick(World world, BlockPos blockpos, IBlockState iblockstate, EaglercraftRandom random) { @@ -364,114 +475,4 @@ public class BlockVine extends Block { } } } - - /**+ - * Called by ItemBlocks just before a block is actually set in - * the world, to allow for adjustments to the IBlockstate - */ - public IBlockState onBlockPlaced(World var1, BlockPos var2, EnumFacing enumfacing, float var4, float var5, - float var6, int var7, EntityLivingBase var8) { - IBlockState iblockstate = this.getDefaultState().withProperty(UP, Boolean.valueOf(false)) - .withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)) - .withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)); - return enumfacing.getAxis().isHorizontal() - ? iblockstate.withProperty(getPropertyFor(enumfacing.getOpposite()), Boolean.valueOf(true)) - : iblockstate; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return null; - } - - /**+ - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(EaglercraftRandom var1) { - return 0; - } - - public void harvestBlock(World world, EntityPlayer entityplayer, BlockPos blockpos, IBlockState iblockstate, - TileEntity tileentity) { - if (!world.isRemote && entityplayer.getCurrentEquippedItem() != null - && entityplayer.getCurrentEquippedItem().getItem() == Items.shears) { - entityplayer.triggerAchievement(StatList.mineBlockStatArray[Block.getIdFromBlock(this)]); - spawnAsEntity(world, blockpos, new ItemStack(Blocks.vine, 1, 0)); - } else { - super.harvestBlock(world, entityplayer, blockpos, iblockstate, tileentity); - } - - } - - public EnumWorldBlockLayer getBlockLayer() { - return EnumWorldBlockLayer.CUTOUT; - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(SOUTH, Boolean.valueOf((i & 1) > 0)) - .withProperty(WEST, Boolean.valueOf((i & 2) > 0)).withProperty(NORTH, Boolean.valueOf((i & 4) > 0)) - .withProperty(EAST, Boolean.valueOf((i & 8) > 0)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - int i = 0; - if (((Boolean) iblockstate.getValue(SOUTH)).booleanValue()) { - i |= 1; - } - - if (((Boolean) iblockstate.getValue(WEST)).booleanValue()) { - i |= 2; - } - - if (((Boolean) iblockstate.getValue(NORTH)).booleanValue()) { - i |= 4; - } - - if (((Boolean) iblockstate.getValue(EAST)).booleanValue()) { - i |= 8; - } - - return i; - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { UP, NORTH, EAST, SOUTH, WEST }); - } - - public static PropertyBool getPropertyFor(EnumFacing side) { - switch (side) { - case UP: - return UP; - case NORTH: - return NORTH; - case SOUTH: - return SOUTH; - case EAST: - return EAST; - case WEST: - return WEST; - default: - throw new IllegalArgumentException(side + " is an invalid choice"); - } - } - - public static int getNumGrownFaces(IBlockState state) { - int i = 0; - - for (int j = 0; j < ALL_FACES.length; ++j) { - if (((Boolean) state.getValue(ALL_FACES[j])).booleanValue()) { - ++i; - } - } - - return i; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockWall.java b/src/game/java/net/minecraft/block/BlockWall.java index c81b5a5f..230d9963 100644 --- a/src/game/java/net/minecraft/block/BlockWall.java +++ b/src/game/java/net/minecraft/block/BlockWall.java @@ -20,34 +20,91 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockWall extends Block { + public static enum EnumType implements IStringSerializable { + NORMAL(0, "cobblestone", "normal"), MOSSY(1, "mossy_cobblestone", "mossy"); + + public static final BlockWall.EnumType[] META_LOOKUP = new BlockWall.EnumType[2]; + static { + BlockWall.EnumType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP[types[i].getMetadata()] = types[i]; + } + + } + + public static BlockWall.EnumType byMetadata(int meta) { + if (meta < 0 || meta >= META_LOOKUP.length) { + meta = 0; + } + + return META_LOOKUP[meta]; + } + + private final int meta; + + private final String name; + + private String unlocalizedName; + + private EnumType(int meta, String name, String unlocalizedName) { + this.meta = meta; + this.name = name; + this.unlocalizedName = unlocalizedName; + } + + public int getMetadata() { + return this.meta; + } + + public String getName() { + return this.name; + } + + public String getUnlocalizedName() { + return this.unlocalizedName; + } + + public String toString() { + return this.name; + } + } + public static final PropertyBool UP = PropertyBool.create("up"); public static final PropertyBool NORTH = PropertyBool.create("north"); public static final PropertyBool EAST = PropertyBool.create("east"); public static final PropertyBool SOUTH = PropertyBool.create("south"); public static final PropertyBool WEST = PropertyBool.create("west"); + public static PropertyEnum VARIANT; + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockWall.EnumType.class); + } + public BlockWall(Block modelBlock) { super(modelBlock.blockMaterial); this.setDefaultState(this.blockState.getBaseState().withProperty(UP, Boolean.valueOf(false)) @@ -60,32 +117,93 @@ public class BlockWall extends Block { this.setCreativeTab(CreativeTabs.tabBlock); } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockWall.EnumType.class); + public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { + Block block = worldIn.getBlockState(pos).getBlock(); + return block == Blocks.barrier ? false + : (block != this && !(block instanceof BlockFenceGate) + ? (block.blockMaterial.isOpaque() && block.isFullCube() ? block.blockMaterial != Material.gourd + : false) + : true); } - /**+ - * Gets the localized name of this block. Used for the - * statistics page. + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { UP, NORTH, EAST, WEST, SOUTH, VARIANT }); + } + + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. + */ + public int damageDropped(IBlockState iblockstate) { + return ((BlockWall.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Get the actual Block state of this Block at the given position. This + * applies properties not visible in the metadata, such as fence connections. + */ + public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { + return iblockstate.withProperty(UP, Boolean.valueOf(!iblockaccess.isAirBlock(blockpos.up()))) + .withProperty(NORTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.north()))) + .withProperty(EAST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.east()))) + .withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.south()))) + .withProperty(WEST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.west()))); + } + + public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { + this.setBlockBoundsBasedOnState(world, blockpos); + this.maxY = 1.5D; + return super.getCollisionBoundingBox(world, blockpos, iblockstate); + } + + /** + * + Gets the localized name of this block. Used for the statistics page. */ public String getLocalizedName() { return StatCollector.translateToLocal( this.getUnlocalizedName() + "." + BlockWall.EnumType.NORMAL.getUnlocalizedName() + ".name"); } + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((BlockWall.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + return this.getDefaultState().withProperty(VARIANT, BlockWall.EnumType.byMetadata(i)); + } + + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) + */ + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + BlockWall.EnumType[] types = BlockWall.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } + public boolean isFullCube() { return false; } - public boolean isPassable(IBlockAccess var1, BlockPos var2) { + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { return false; } - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { + public boolean isPassable(IBlockAccess var1, BlockPos var2) { return false; } @@ -128,122 +246,7 @@ public class BlockWall extends Block { this.setBlockBounds(f, 0.0F, f2, f1, f4, f3); } - public AxisAlignedBB getCollisionBoundingBox(World world, BlockPos blockpos, IBlockState iblockstate) { - this.setBlockBoundsBasedOnState(world, blockpos); - this.maxY = 1.5D; - return super.getCollisionBoundingBox(world, blockpos, iblockstate); - } - - public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { - Block block = worldIn.getBlockState(pos).getBlock(); - return block == Blocks.barrier ? false - : (block != this && !(block instanceof BlockFenceGate) - ? (block.blockMaterial.isOpaque() && block.isFullCube() ? block.blockMaterial != Material.gourd - : false) - : true); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - BlockWall.EnumType[] types = BlockWall.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } - - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. - */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockWall.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - public boolean shouldSideBeRendered(IBlockAccess iblockaccess, BlockPos blockpos, EnumFacing enumfacing) { return enumfacing == EnumFacing.DOWN ? super.shouldSideBeRendered(iblockaccess, blockpos, enumfacing) : true; } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - return this.getDefaultState().withProperty(VARIANT, BlockWall.EnumType.byMetadata(i)); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((BlockWall.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); - } - - /**+ - * Get the actual Block state of this Block at the given - * position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public IBlockState getActualState(IBlockState iblockstate, IBlockAccess iblockaccess, BlockPos blockpos) { - return iblockstate.withProperty(UP, Boolean.valueOf(!iblockaccess.isAirBlock(blockpos.up()))) - .withProperty(NORTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.north()))) - .withProperty(EAST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.east()))) - .withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.south()))) - .withProperty(WEST, Boolean.valueOf(this.canConnectTo(iblockaccess, blockpos.west()))); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { UP, NORTH, EAST, WEST, SOUTH, VARIANT }); - } - - public static enum EnumType implements IStringSerializable { - NORMAL(0, "cobblestone", "normal"), MOSSY(1, "mossy_cobblestone", "mossy"); - - public static final BlockWall.EnumType[] META_LOOKUP = new BlockWall.EnumType[2]; - private final int meta; - private final String name; - private String unlocalizedName; - - private EnumType(int meta, String name, String unlocalizedName) { - this.meta = meta; - this.name = name; - this.unlocalizedName = unlocalizedName; - } - - public int getMetadata() { - return this.meta; - } - - public String toString() { - return this.name; - } - - public static BlockWall.EnumType byMetadata(int meta) { - if (meta < 0 || meta >= META_LOOKUP.length) { - meta = 0; - } - - return META_LOOKUP[meta]; - } - - public String getName() { - return this.name; - } - - public String getUnlocalizedName() { - return this.unlocalizedName; - } - - static { - BlockWall.EnumType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP[types[i].getMetadata()] = types[i]; - } - - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockWallSign.java b/src/game/java/net/minecraft/block/BlockWallSign.java index e8be00c1..bd82bbef 100644 --- a/src/game/java/net/minecraft/block/BlockWallSign.java +++ b/src/game/java/net/minecraft/block/BlockWallSign.java @@ -9,22 +9,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,6 +39,42 @@ public class BlockWallSign extends BlockSign { this.setDefaultState(this.blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH)); } + protected BlockState createBlockState() { + return new BlockState(this, new IProperty[] { FACING }); + } + + /** + * + Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(IBlockState iblockstate) { + return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); + } + + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + EnumFacing enumfacing = EnumFacing.getFront(i); + if (enumfacing.getAxis() == EnumFacing.Axis.Y) { + enumfacing = EnumFacing.NORTH; + } + + return this.getDefaultState().withProperty(FACING, enumfacing); + } + + /** + * + Called when a neighboring block changes. + */ + public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { + EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); + if (!world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) { + this.dropBlockAsItem(world, blockpos, iblockstate, 0); + world.setBlockToAir(blockpos); + } + + super.onNeighborBlockChange(world, blockpos, iblockstate, block); + } + public void setBlockBoundsBasedOnState(IBlockAccess iblockaccess, BlockPos blockpos) { EnumFacing enumfacing = (EnumFacing) iblockaccess.getBlockState(blockpos).getValue(FACING); float f = 0.28125F; @@ -59,40 +98,4 @@ public class BlockWallSign extends BlockSign { } } - - /**+ - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World world, BlockPos blockpos, IBlockState iblockstate, Block block) { - EnumFacing enumfacing = (EnumFacing) iblockstate.getValue(FACING); - if (!world.getBlockState(blockpos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) { - this.dropBlockAsItem(world, blockpos, iblockstate, 0); - world.setBlockToAir(blockpos); - } - - super.onNeighborBlockChange(world, blockpos, iblockstate, block); - } - - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - EnumFacing enumfacing = EnumFacing.getFront(i); - if (enumfacing.getAxis() == EnumFacing.Axis.Y) { - enumfacing = EnumFacing.NORTH; - } - - return this.getDefaultState().withProperty(FACING, enumfacing); - } - - /**+ - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(IBlockState iblockstate) { - return ((EnumFacing) iblockstate.getValue(FACING)).getIndex(); - } - - protected BlockState createBlockState() { - return new BlockState(this, new IProperty[] { FACING }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockWeb.java b/src/game/java/net/minecraft/block/BlockWeb.java index 07127674..d5a0a769 100644 --- a/src/game/java/net/minecraft/block/BlockWeb.java +++ b/src/game/java/net/minecraft/block/BlockWeb.java @@ -1,7 +1,6 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; @@ -13,22 +12,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,36 +41,6 @@ public class BlockWeb extends Block { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity entity) { - entity.setInWeb(); - } - - /**+ - * Used to determine ambient occlusion and culling when - * rebuilding chunks for render - */ - public boolean isOpaqueCube() { - return false; - } - - public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { - return null; - } - - public boolean isFullCube() { - return false; - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Items.string; - } - protected boolean canSilkHarvest() { return true; } @@ -76,4 +48,34 @@ public class BlockWeb extends Block { public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.CUTOUT; } + + public AxisAlignedBB getCollisionBoundingBox(World var1, BlockPos var2, IBlockState var3) { + return null; + } + + /** + * + Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Items.string; + } + + public boolean isFullCube() { + return false; + } + + /** + * + Used to determine ambient occlusion and culling when rebuilding chunks for + * render + */ + public boolean isOpaqueCube() { + return false; + } + + /** + * + Called When an Entity Collided with the Block + */ + public void onEntityCollidedWithBlock(World var1, BlockPos var2, IBlockState var3, Entity entity) { + entity.setInWeb(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockWoodSlab.java b/src/game/java/net/minecraft/block/BlockWoodSlab.java index 1925db79..2d210a3a 100644 --- a/src/game/java/net/minecraft/block/BlockWoodSlab.java +++ b/src/game/java/net/minecraft/block/BlockWoodSlab.java @@ -1,8 +1,8 @@ package net.minecraft.block; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.properties.IProperty; @@ -16,22 +16,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,6 +42,10 @@ import net.minecraft.world.World; public abstract class BlockWoodSlab extends BlockSlab { public static PropertyEnum VARIANT; + public static void bootstrapStates() { + VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class); + } + public BlockWoodSlab() { super(Material.wood); IBlockState iblockstate = this.blockState.getBaseState(); @@ -50,72 +57,40 @@ public abstract class BlockWoodSlab extends BlockSlab { this.setCreativeTab(CreativeTabs.tabBlock); } - public static void bootstrapStates() { - VARIANT = PropertyEnum.create("variant", BlockPlanks.EnumType.class); + protected BlockState createBlockState() { + return this.isDouble() ? new BlockState(this, new IProperty[] { VARIANT }) + : new BlockState(this, new IProperty[] { HALF, VARIANT }); } - /**+ - * Get the MapColor for this Block and the given BlockState + /** + * + Gets the metadata of the item this Block can drop. This method is called + * when the block gets destroyed. It returns the metadata of the dropped item + * based on the old metadata of the block. */ - public MapColor getMapColor(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).func_181070_c(); - } - - /**+ - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { - return Item.getItemFromBlock(Blocks.wooden_slab); + public int damageDropped(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); } public Item getItem(World var1, BlockPos var2) { return Item.getItemFromBlock(Blocks.wooden_slab); } - /**+ - * Returns the slab block name with the type associated with it + /** + * + Get the Item that this Block should drop when harvested. */ - public String getUnlocalizedName(int i) { - return super.getUnlocalizedName() + "." + BlockPlanks.EnumType.byMetadata(i).getUnlocalizedName(); + public Item getItemDropped(IBlockState var1, EaglercraftRandom var2, int var3) { + return Item.getItemFromBlock(Blocks.wooden_slab); } - public IProperty getVariantProperty() { - return VARIANT; - } - - public Object getVariant(ItemStack itemstack) { - return BlockPlanks.EnumType.byMetadata(itemstack.getMetadata() & 7); - } - - /**+ - * returns a list of blocks with the same ID, but different meta - * (eg: wood returns 4 blocks) + /** + * + Get the MapColor for this Block and the given BlockState */ - public void getSubBlocks(Item item, CreativeTabs var2, List list) { - if (item != Item.getItemFromBlock(Blocks.double_wooden_slab)) { - BlockPlanks.EnumType[] types = BlockPlanks.EnumType.META_LOOKUP; - for (int i = 0; i < types.length; ++i) { - list.add(new ItemStack(item, 1, types[i].getMetadata())); - } - - } + public MapColor getMapColor(IBlockState iblockstate) { + return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).func_181070_c(); } - /**+ - * Convert the given metadata into a BlockState for this Block - */ - public IBlockState getStateFromMeta(int i) { - IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, BlockPlanks.EnumType.byMetadata(i & 7)); - if (!this.isDouble()) { - iblockstate = iblockstate.withProperty(HALF, - (i & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); - } - - return iblockstate; - } - - /**+ - * Convert the BlockState into the correct metadata value + /** + * + Convert the BlockState into the correct metadata value */ public int getMetaFromState(IBlockState iblockstate) { int i = 0; @@ -127,18 +102,45 @@ public abstract class BlockWoodSlab extends BlockSlab { return i; } - protected BlockState createBlockState() { - return this.isDouble() ? new BlockState(this, new IProperty[] { VARIANT }) - : new BlockState(this, new IProperty[] { HALF, VARIANT }); + /** + * + Convert the given metadata into a BlockState for this Block + */ + public IBlockState getStateFromMeta(int i) { + IBlockState iblockstate = this.getDefaultState().withProperty(VARIANT, BlockPlanks.EnumType.byMetadata(i & 7)); + if (!this.isDouble()) { + iblockstate = iblockstate.withProperty(HALF, + (i & 8) == 0 ? BlockSlab.EnumBlockHalf.BOTTOM : BlockSlab.EnumBlockHalf.TOP); + } + + return iblockstate; } - /**+ - * Gets the metadata of the item this Block can drop. This - * method is called when the block gets destroyed. It returns - * the metadata of the dropped item based on the old metadata of - * the block. + /** + * + returns a list of blocks with the same ID, but different meta (eg: wood + * returns 4 blocks) */ - public int damageDropped(IBlockState iblockstate) { - return ((BlockPlanks.EnumType) iblockstate.getValue(VARIANT)).getMetadata(); + public void getSubBlocks(Item item, CreativeTabs var2, List list) { + if (item != Item.getItemFromBlock(Blocks.double_wooden_slab)) { + BlockPlanks.EnumType[] types = BlockPlanks.EnumType.META_LOOKUP; + for (int i = 0; i < types.length; ++i) { + list.add(new ItemStack(item, 1, types[i].getMetadata())); + } + + } + } + + /** + * + Returns the slab block name with the type associated with it + */ + public String getUnlocalizedName(int i) { + return super.getUnlocalizedName() + "." + BlockPlanks.EnumType.byMetadata(i).getUnlocalizedName(); + } + + public Object getVariant(ItemStack itemstack) { + return BlockPlanks.EnumType.byMetadata(itemstack.getMetadata() & 7); + } + + public IProperty getVariantProperty() { + return VARIANT; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockWorkbench.java b/src/game/java/net/minecraft/block/BlockWorkbench.java index 630c4465..d528783b 100644 --- a/src/game/java/net/minecraft/block/BlockWorkbench.java +++ b/src/game/java/net/minecraft/block/BlockWorkbench.java @@ -16,27 +16,60 @@ import net.minecraft.util.IChatComponent; import net.minecraft.world.IInteractionObject; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockWorkbench extends Block { + public static class InterfaceCraftingTable implements IInteractionObject { + private final World world; + private final BlockPos position; + + public InterfaceCraftingTable(World worldIn, BlockPos pos) { + this.world = worldIn; + this.position = pos; + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerWorkbench(inventoryplayer, this.world, this.position); + } + + public IChatComponent getDisplayName() { + return new ChatComponentTranslation(Blocks.crafting_table.getUnlocalizedName() + ".name", new Object[0]); + } + + public String getGuiID() { + return "minecraft:crafting_table"; + } + + public String getName() { + return null; + } + + public boolean hasCustomName() { + return false; + } + } + protected BlockWorkbench() { super(Material.wood); this.setCreativeTab(CreativeTabs.tabDecorations); @@ -52,34 +85,4 @@ public class BlockWorkbench extends Block { return true; } } - - public static class InterfaceCraftingTable implements IInteractionObject { - private final World world; - private final BlockPos position; - - public InterfaceCraftingTable(World worldIn, BlockPos pos) { - this.world = worldIn; - this.position = pos; - } - - public String getName() { - return null; - } - - public boolean hasCustomName() { - return false; - } - - public IChatComponent getDisplayName() { - return new ChatComponentTranslation(Blocks.crafting_table.getUnlocalizedName() + ".name", new Object[0]); - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { - return new ContainerWorkbench(inventoryplayer, this.world, this.position); - } - - public String getGuiID() { - return "minecraft:crafting_table"; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/BlockYellowFlower.java b/src/game/java/net/minecraft/block/BlockYellowFlower.java index 71987389..a22772f1 100644 --- a/src/game/java/net/minecraft/block/BlockYellowFlower.java +++ b/src/game/java/net/minecraft/block/BlockYellowFlower.java @@ -1,28 +1,31 @@ package net.minecraft.block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockYellowFlower extends BlockFlower { - /**+ - * Get the Type of this flower (Yellow/Red) + /** + * + Get the Type of this flower (Yellow/Red) */ public BlockFlower.EnumFlowerColor getBlockType() { return BlockFlower.EnumFlowerColor.YELLOW; diff --git a/src/game/java/net/minecraft/block/IGrowable.java b/src/game/java/net/minecraft/block/IGrowable.java index ba7cffb3..42e5eb21 100644 --- a/src/game/java/net/minecraft/block/IGrowable.java +++ b/src/game/java/net/minecraft/block/IGrowable.java @@ -1,34 +1,36 @@ package net.minecraft.block; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IGrowable { - /**+ - * Whether this IGrowable can grow + /** + * + Whether this IGrowable can grow */ boolean canGrow(World var1, BlockPos var2, IBlockState var3, boolean var4); diff --git a/src/game/java/net/minecraft/block/ITileEntityProvider.java b/src/game/java/net/minecraft/block/ITileEntityProvider.java index a0bf384a..1d4754ed 100644 --- a/src/game/java/net/minecraft/block/ITileEntityProvider.java +++ b/src/game/java/net/minecraft/block/ITileEntityProvider.java @@ -3,30 +3,33 @@ package net.minecraft.block; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ITileEntityProvider { - /**+ - * Returns a new instance of a block's tile entity class. Called - * on placing the block. + /** + * + Returns a new instance of a block's tile entity class. Called on placing + * the block. */ TileEntity createNewTileEntity(World var1, int var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/material/MapColor.java b/src/game/java/net/minecraft/block/material/MapColor.java index f14c1392..1668ce97 100644 --- a/src/game/java/net/minecraft/block/material/MapColor.java +++ b/src/game/java/net/minecraft/block/material/MapColor.java @@ -1,29 +1,31 @@ package net.minecraft.block.material; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapColor { - /**+ - * Holds all the 16 colors used on maps, very similar of a - * pallete system. + /** + * + Holds all the 16 colors used on maps, very similar of a pallete system. */ public static final MapColor[] mapColorArray = new MapColor[64]; public static final MapColor airColor = new MapColor(0, 0); diff --git a/src/game/java/net/minecraft/block/material/Material.java b/src/game/java/net/minecraft/block/material/Material.java index 8a0b0f73..abef34ad 100644 --- a/src/game/java/net/minecraft/block/material/Material.java +++ b/src/game/java/net/minecraft/block/material/Material.java @@ -1,21 +1,24 @@ package net.minecraft.block.material; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,8 +52,8 @@ public class Material { public static final Material packedIce = (new Material(MapColor.iceColor)).setAdventureModeExempt(); public static final Material snow = (new MaterialLogic(MapColor.snowColor)).setReplaceable().setTranslucent() .setRequiresTool().setNoPushMobility(); - /**+ - * The material for crafted snow. + /** + * + The material for crafted snow. */ public static final Material craftedSnow = (new Material(MapColor.snowColor)).setRequiresTool(); public static final Material cactus = (new Material(MapColor.foliageColor)).setTranslucent().setNoPushMobility(); @@ -60,15 +63,15 @@ public class Material { public static final Material portal = (new MaterialPortal(MapColor.airColor)).setImmovableMobility(); public static final Material cake = (new Material(MapColor.airColor)).setNoPushMobility(); public static final Material web = (new Material(MapColor.clothColor) { - /**+ - * Returns if this material is considered solid or not + /** + * + Returns if this material is considered solid or not */ public boolean blocksMovement() { return false; } }).setRequiresTool().setNoPushMobility(); - /**+ - * Pistons' material. + /** + * + Pistons' material. */ public static final Material piston = (new Material(MapColor.stoneColor)).setImmovableMobility(); public static final Material barrier = (new Material(MapColor.airColor)).setRequiresTool().setImmovableMobility(); @@ -76,9 +79,9 @@ public class Material { private boolean replaceable; private boolean isTranslucent; private final MapColor materialMapColor; - /**+ - * Determines if the material can be harvested without a tool - * (or with the wrong tool) + /** + * + Determines if the material can be harvested without a tool (or with the + * wrong tool) */ private boolean requiresNoTool = true; private int mobilityFlag; @@ -88,127 +91,84 @@ public class Material { this.materialMapColor = color; } - /**+ - * Returns if blocks of these materials are liquids. - */ - public boolean isLiquid() { - return false; - } - - /**+ - * Returns true if the block is a considered solid. This is true - * by default. - */ - public boolean isSolid() { - return true; - } - - /**+ - * Will prevent grass from growing on dirt underneath and kill - * any grass below it if it returns true + /** + * + Will prevent grass from growing on dirt underneath and kill any grass below + * it if it returns true */ public boolean blocksLight() { return true; } - /**+ - * Returns if this material is considered solid or not + /** + * + Returns if this material is considered solid or not */ public boolean blocksMovement() { return true; } - /**+ - * Marks the material as translucent - */ - private Material setTranslucent() { - this.isTranslucent = true; - return this; - } - - /**+ - * Makes blocks with this material require the correct tool to - * be harvested. - */ - protected Material setRequiresTool() { - this.requiresNoTool = false; - return this; - } - - /**+ - * Set the canBurn bool to True and return the current object. - */ - protected Material setBurning() { - this.canBurn = true; - return this; - } - - /**+ - * Returns if the block can burn or not. + /** + * + Returns if the block can burn or not. */ public boolean getCanBurn() { return this.canBurn; } - /**+ - * Sets {@link #replaceable} to true. + /** + * + Retrieves the color index of the block. This is is the same color used by + * vanilla maps to represent this block. */ - public Material setReplaceable() { - this.replaceable = true; - return this; + public MapColor getMaterialMapColor() { + return this.materialMapColor; } - /**+ - * Returns whether the material can be replaced by other blocks - * when placed - eg snow, vines and tall grass. - */ - public boolean isReplaceable() { - return this.replaceable; - } - - /**+ - * Indicate if the material is opaque - */ - public boolean isOpaque() { - return this.isTranslucent ? false : this.blocksMovement(); - } - - /**+ - * Returns true if the material can be harvested without a tool - * (or with the wrong tool) - */ - public boolean isToolNotRequired() { - return this.requiresNoTool; - } - - /**+ - * Returns the mobility information of the material, 0 = free, 1 - * = can't push but can move over, 2 = total immobility and stop - * pistons. + /** + * + Returns the mobility information of the material, 0 = free, 1 = can't push + * but can move over, 2 = total immobility and stop pistons. */ public int getMaterialMobility() { return this.mobilityFlag; } - /**+ - * This type of material can't be pushed, but pistons can move - * over it. + /** + * + Returns if blocks of these materials are liquids. */ - protected Material setNoPushMobility() { - this.mobilityFlag = 1; - return this; + public boolean isLiquid() { + return false; } - /**+ - * This type of material can't be pushed, and pistons are - * blocked to move. + /** + * + Indicate if the material is opaque */ - protected Material setImmovableMobility() { - this.mobilityFlag = 2; - return this; + public boolean isOpaque() { + return this.isTranslucent ? false : this.blocksMovement(); } - /**+ + /** + * + Returns whether the material can be replaced by other blocks when placed - + * eg snow, vines and tall grass. + */ + public boolean isReplaceable() { + return this.replaceable; + } + + /** + * + Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() { + return true; + } + + /** + * + Returns true if the material can be harvested without a tool (or with the + * wrong tool) + */ + public boolean isToolNotRequired() { + return this.requiresNoTool; + } + + /** + * + + * * @see #isAdventureModeExempt() */ protected Material setAdventureModeExempt() { @@ -216,11 +176,51 @@ public class Material { return this; } - /**+ - * Retrieves the color index of the block. This is is the same - * color used by vanilla maps to represent this block. + /** + * + Set the canBurn bool to True and return the current object. */ - public MapColor getMaterialMapColor() { - return this.materialMapColor; + protected Material setBurning() { + this.canBurn = true; + return this; + } + + /** + * + This type of material can't be pushed, and pistons are blocked to move. + */ + protected Material setImmovableMobility() { + this.mobilityFlag = 2; + return this; + } + + /** + * + This type of material can't be pushed, but pistons can move over it. + */ + protected Material setNoPushMobility() { + this.mobilityFlag = 1; + return this; + } + + /** + * + Sets {@link #replaceable} to true. + */ + public Material setReplaceable() { + this.replaceable = true; + return this; + } + + /** + * + Makes blocks with this material require the correct tool to be harvested. + */ + protected Material setRequiresTool() { + this.requiresNoTool = false; + return this; + } + + /** + * + Marks the material as translucent + */ + private Material setTranslucent() { + this.isTranslucent = true; + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/material/MaterialLiquid.java b/src/game/java/net/minecraft/block/material/MaterialLiquid.java index 7394a22e..d972aec9 100644 --- a/src/game/java/net/minecraft/block/material/MaterialLiquid.java +++ b/src/game/java/net/minecraft/block/material/MaterialLiquid.java @@ -1,21 +1,24 @@ package net.minecraft.block.material; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,23 +30,22 @@ public class MaterialLiquid extends Material { this.setNoPushMobility(); } - /**+ - * Returns if blocks of these materials are liquids. - */ - public boolean isLiquid() { - return true; - } - - /**+ - * Returns if this material is considered solid or not + /** + * + Returns if this material is considered solid or not */ public boolean blocksMovement() { return false; } - /**+ - * Returns true if the block is a considered solid. This is true - * by default. + /** + * + Returns if blocks of these materials are liquids. + */ + public boolean isLiquid() { + return true; + } + + /** + * + Returns true if the block is a considered solid. This is true by default. */ public boolean isSolid() { return false; diff --git a/src/game/java/net/minecraft/block/material/MaterialLogic.java b/src/game/java/net/minecraft/block/material/MaterialLogic.java index cd10838f..2bdc3033 100644 --- a/src/game/java/net/minecraft/block/material/MaterialLogic.java +++ b/src/game/java/net/minecraft/block/material/MaterialLogic.java @@ -1,21 +1,24 @@ package net.minecraft.block.material; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,26 +29,25 @@ public class MaterialLogic extends Material { this.setAdventureModeExempt(); } - /**+ - * Returns true if the block is a considered solid. This is true - * by default. - */ - public boolean isSolid() { - return false; - } - - /**+ - * Will prevent grass from growing on dirt underneath and kill - * any grass below it if it returns true + /** + * + Will prevent grass from growing on dirt underneath and kill any grass below + * it if it returns true */ public boolean blocksLight() { return false; } - /**+ - * Returns if this material is considered solid or not + /** + * + Returns if this material is considered solid or not */ public boolean blocksMovement() { return false; } + + /** + * + Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/material/MaterialPortal.java b/src/game/java/net/minecraft/block/material/MaterialPortal.java index 48150927..f406a8c7 100644 --- a/src/game/java/net/minecraft/block/material/MaterialPortal.java +++ b/src/game/java/net/minecraft/block/material/MaterialPortal.java @@ -1,21 +1,24 @@ package net.minecraft.block.material; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,26 +28,25 @@ public class MaterialPortal extends Material { super(color); } - /**+ - * Returns true if the block is a considered solid. This is true - * by default. - */ - public boolean isSolid() { - return false; - } - - /**+ - * Will prevent grass from growing on dirt underneath and kill - * any grass below it if it returns true + /** + * + Will prevent grass from growing on dirt underneath and kill any grass below + * it if it returns true */ public boolean blocksLight() { return false; } - /**+ - * Returns if this material is considered solid or not + /** + * + Returns if this material is considered solid or not */ public boolean blocksMovement() { return false; } + + /** + * + Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/material/MaterialTransparent.java b/src/game/java/net/minecraft/block/material/MaterialTransparent.java index 85b59828..5e38e7cd 100644 --- a/src/game/java/net/minecraft/block/material/MaterialTransparent.java +++ b/src/game/java/net/minecraft/block/material/MaterialTransparent.java @@ -1,21 +1,24 @@ package net.minecraft.block.material; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,26 +29,25 @@ public class MaterialTransparent extends Material { this.setReplaceable(); } - /**+ - * Returns true if the block is a considered solid. This is true - * by default. - */ - public boolean isSolid() { - return false; - } - - /**+ - * Will prevent grass from growing on dirt underneath and kill - * any grass below it if it returns true + /** + * + Will prevent grass from growing on dirt underneath and kill any grass below + * it if it returns true */ public boolean blocksLight() { return false; } - /**+ - * Returns if this material is considered solid or not + /** + * + Returns if this material is considered solid or not */ public boolean blocksMovement() { return false; } + + /** + * + Returns true if the block is a considered solid. This is true by default. + */ + public boolean isSolid() { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/properties/IProperty.java b/src/game/java/net/minecraft/block/properties/IProperty.java index c0dcc895..9d4cffa3 100644 --- a/src/game/java/net/minecraft/block/properties/IProperty.java +++ b/src/game/java/net/minecraft/block/properties/IProperty.java @@ -2,41 +2,44 @@ package net.minecraft.block.properties; import java.util.Collection; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IProperty> { - /**+ - * Get the name for the given value. + Collection getAllowedValues(); + + /** + * + Get the name for the given value. */ String getName(); - Collection getAllowedValues(); - - /**+ - * The class of the values of this property - */ - Class getValueClass(); - - /**+ - * Get the name for the given value. + /** + * + Get the name for the given value. */ String getName(Object var1); + + /** + * + The class of the values of this property + */ + Class getValueClass(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/properties/PropertyBool.java b/src/game/java/net/minecraft/block/properties/PropertyBool.java index 462a4ad6..13aa3bc9 100644 --- a/src/game/java/net/minecraft/block/properties/PropertyBool.java +++ b/src/game/java/net/minecraft/block/properties/PropertyBool.java @@ -4,27 +4,34 @@ import java.util.Collection; import com.google.common.collect.ImmutableSet; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PropertyBool extends PropertyHelper { + public static PropertyBool create(String name) { + return new PropertyBool(name); + } + private final ImmutableSet allowedValues = ImmutableSet.of(Boolean.valueOf(true), Boolean.valueOf(false)); protected PropertyBool(String name) { @@ -35,12 +42,8 @@ public class PropertyBool extends PropertyHelper { return this.allowedValues; } - public static PropertyBool create(String name) { - return new PropertyBool(name); - } - - /**+ - * Get the name for the given value. + /** + * + Get the name for the given value. */ public String getName(Object value) { return ((Boolean) value).toString(); diff --git a/src/game/java/net/minecraft/block/properties/PropertyDirection.java b/src/game/java/net/minecraft/block/properties/PropertyDirection.java index e410b455..5d5b0c16 100644 --- a/src/game/java/net/minecraft/block/properties/PropertyDirection.java +++ b/src/game/java/net/minecraft/block/properties/PropertyDirection.java @@ -9,55 +9,58 @@ import com.google.common.collect.Lists; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PropertyDirection extends PropertyEnum { - protected PropertyDirection(String name, Collection values) { - super(name, EnumFacing.class, values); - } - - /**+ - * Create a new PropertyDirection with the given name + /** + * + Create a new PropertyDirection with the given name */ public static PropertyDirection create(String name) { - /**+ - * Create a new PropertyDirection with the given name + /** + * + Create a new PropertyDirection with the given name */ return create(name, Predicates.alwaysTrue()); } - /**+ - * Create a new PropertyDirection with the given name - */ - public static PropertyDirection create(String name, Predicate filter) { - /**+ - * Create a new PropertyDirection with the given name - */ - return create(name, Collections2.filter(Lists.newArrayList(EnumFacing._VALUES), filter)); - } - - /**+ - * Create a new PropertyDirection with the given name + /** + * + Create a new PropertyDirection with the given name */ public static PropertyDirection create(String name, Collection values) { return new PropertyDirection(name, values); } + + /** + * + Create a new PropertyDirection with the given name + */ + public static PropertyDirection create(String name, Predicate filter) { + /** + * + Create a new PropertyDirection with the given name + */ + return create(name, Collections2.filter(Lists.newArrayList(EnumFacing._VALUES), filter)); + } + + protected PropertyDirection(String name, Collection values) { + super(name, EnumFacing.class, values); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/properties/PropertyEnum.java b/src/game/java/net/minecraft/block/properties/PropertyEnum.java index 4877a82b..8e431d3c 100644 --- a/src/game/java/net/minecraft/block/properties/PropertyEnum.java +++ b/src/game/java/net/minecraft/block/properties/PropertyEnum.java @@ -12,28 +12,60 @@ import com.google.common.collect.Maps; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PropertyEnum & IStringSerializable> extends PropertyHelper { + public static & IStringSerializable> PropertyEnum create(String name, Class clazz) { + /** + * + Create a new PropertyEnum with all Enum constants of the given class. + */ + return create(name, clazz, Predicates.alwaysTrue()); + } + + public static & IStringSerializable> PropertyEnum create(String name, Class clazz, + Collection values) { + return new PropertyEnum(name, clazz, values); + } + + public static & IStringSerializable> PropertyEnum create(String name, Class clazz, + Predicate filter) { + /** + * + Create a new PropertyEnum with all Enum constants of the given class. + */ + return create(name, clazz, Collections2.filter(Lists.newArrayList(clazz.getEnumConstants()), filter)); + } + + public static & IStringSerializable> PropertyEnum create(String name, Class clazz, + T... values) { + /** + * + Create a new PropertyEnum with all Enum constants of the given class. + */ + return create(name, clazz, Lists.newArrayList(values)); + } + private final ImmutableSet allowedValues; + private final Map nameToValue = Maps.newHashMap(); protected PropertyEnum(String name, Class valueClass, Collection allowedValues) { @@ -55,41 +87,10 @@ public class PropertyEnum & IStringSerializable> extends Prope return this.allowedValues; } - /**+ - * Get the name for the given value. + /** + * + Get the name for the given value. */ public String getName(Object oenum) { return ((IStringSerializable) oenum).getName(); } - - public static & IStringSerializable> PropertyEnum create(String name, Class clazz) { - /**+ - * Create a new PropertyEnum with all Enum constants of the - * given class. - */ - return create(name, clazz, Predicates.alwaysTrue()); - } - - public static & IStringSerializable> PropertyEnum create(String name, Class clazz, - Predicate filter) { - /**+ - * Create a new PropertyEnum with all Enum constants of the - * given class. - */ - return create(name, clazz, Collections2.filter(Lists.newArrayList(clazz.getEnumConstants()), filter)); - } - - public static & IStringSerializable> PropertyEnum create(String name, Class clazz, - T... values) { - /**+ - * Create a new PropertyEnum with all Enum constants of the - * given class. - */ - return create(name, clazz, Lists.newArrayList(values)); - } - - public static & IStringSerializable> PropertyEnum create(String name, Class clazz, - Collection values) { - return new PropertyEnum(name, clazz, values); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/properties/PropertyHelper.java b/src/game/java/net/minecraft/block/properties/PropertyHelper.java index 161dec67..25e40c6f 100644 --- a/src/game/java/net/minecraft/block/properties/PropertyHelper.java +++ b/src/game/java/net/minecraft/block/properties/PropertyHelper.java @@ -2,22 +2,25 @@ package net.minecraft.block.properties; import com.google.common.base.Objects; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,22 +34,6 @@ public abstract class PropertyHelper> implements IProper this.name = name; } - public String getName() { - return this.name; - } - - /**+ - * The class of the values of this property - */ - public Class getValueClass() { - return this.valueClass; - } - - public String toString() { - return Objects.toStringHelper(this).add("name", this.name).add("clazz", this.valueClass) - .add("values", this.getAllowedValues()).toString(); - } - public boolean equals(Object object) { if (this == object) { return true; @@ -58,7 +45,23 @@ public abstract class PropertyHelper> implements IProper } } + public String getName() { + return this.name; + } + + /** + * + The class of the values of this property + */ + public Class getValueClass() { + return this.valueClass; + } + public int hashCode() { return 31 * this.valueClass.hashCode() + this.name.hashCode(); } + + public String toString() { + return Objects.toStringHelper(this).add("name", this.name).add("clazz", this.valueClass) + .add("values", this.getAllowedValues()).toString(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/properties/PropertyInteger.java b/src/game/java/net/minecraft/block/properties/PropertyInteger.java index b79b7bc1..50b3f754 100644 --- a/src/game/java/net/minecraft/block/properties/PropertyInteger.java +++ b/src/game/java/net/minecraft/block/properties/PropertyInteger.java @@ -6,27 +6,34 @@ import java.util.HashSet; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PropertyInteger extends PropertyHelper { + public static PropertyInteger create(String name, int min, int max) { + return new PropertyInteger(name, min, max); + } + private final ImmutableSet allowedValues; protected PropertyInteger(String name, int min, int max) { @@ -46,10 +53,6 @@ public class PropertyInteger extends PropertyHelper { } } - public Collection getAllowedValues() { - return this.allowedValues; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -65,20 +68,20 @@ public class PropertyInteger extends PropertyHelper { } } + public Collection getAllowedValues() { + return this.allowedValues; + } + + /** + * + Get the name for the given value. + */ + public String getName(Object integer) { + return integer.toString(); + } + public int hashCode() { int i = super.hashCode(); i = 31 * i + this.allowedValues.hashCode(); return i; } - - public static PropertyInteger create(String name, int min, int max) { - return new PropertyInteger(name, min, max); - } - - /**+ - * Get the name for the given value. - */ - public String getName(Object integer) { - return integer.toString(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/state/BlockPistonStructureHelper.java b/src/game/java/net/minecraft/block/state/BlockPistonStructureHelper.java index 2469d703..a0939578 100644 --- a/src/game/java/net/minecraft/block/state/BlockPistonStructureHelper.java +++ b/src/game/java/net/minecraft/block/state/BlockPistonStructureHelper.java @@ -13,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,14 +41,13 @@ public class BlockPistonStructureHelper { private final BlockPos pistonPos; private final BlockPos blockToMove; private final EnumFacing moveDirection; - /**+ - * This is a List of all blocks that will be moved by - * the piston. + /** + * + This is a List of all blocks that will be moved by the piston. */ private final List toMove = Lists.newArrayList(); - /**+ - * This is a List of blocks that will be destroyed - * when a piston attempts to move them. + /** + * + This is a List of blocks that will be destroyed when a piston + * attempts to move them. */ private final List toDestroy = Lists.newArrayList(); @@ -88,6 +90,19 @@ public class BlockPistonStructureHelper { } } + private boolean func_177250_b(BlockPos parBlockPos) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (enumfacing.getAxis() != this.moveDirection.getAxis() + && !this.func_177251_a(parBlockPos.offset(enumfacing))) { + return false; + } + } + + return true; + } + private boolean func_177251_a(BlockPos origin) { Block block = this.world.getBlockState(origin).getBlock(); if (block.getMaterial() == Material.air) { @@ -184,32 +199,19 @@ public class BlockPistonStructureHelper { this.toMove.addAll(arraylist2); } - private boolean func_177250_b(BlockPos parBlockPos) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (enumfacing.getAxis() != this.moveDirection.getAxis() - && !this.func_177251_a(parBlockPos.offset(enumfacing))) { - return false; - } - } - - return true; - } - - /**+ - * Returns a List of all the blocks that are being - * moved by the piston. - */ - public List getBlocksToMove() { - return this.toMove; - } - - /**+ - * Returns an List of all the blocks that are being - * destroyed by the piston. + /** + * + Returns an List of all the blocks that are being destroyed by the + * piston. */ public List getBlocksToDestroy() { return this.toDestroy; } + + /** + * + Returns a List of all the blocks that are being moved by the + * piston. + */ + public List getBlocksToMove() { + return this.toMove; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/state/BlockState.java b/src/game/java/net/minecraft/block/state/BlockState.java index 8568532d..35f12e6f 100644 --- a/src/game/java/net/minecraft/block/state/BlockState.java +++ b/src/game/java/net/minecraft/block/state/BlockState.java @@ -26,27 +26,109 @@ import net.minecraft.block.properties.IProperty; import net.minecraft.util.Cartesian; import net.minecraft.util.MapPopulator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockState { + static class StateImplementation extends BlockStateBase { + private final Block block; + private final ImmutableMap properties; + private ImmutableTable propertyValueTable; + + private StateImplementation(Block blockIn, ImmutableMap propertiesIn) { + this.block = blockIn; + this.properties = propertiesIn; + } + + public void buildPropertyValueTable(Map, BlockState.StateImplementation> map) { + if (this.propertyValueTable != null) { + throw new IllegalStateException(); + } else { + HashBasedTable hashbasedtable = HashBasedTable.create(); + + for (IProperty iproperty : this.properties.keySet()) { + for (Object comparable : iproperty.getAllowedValues()) { + if (comparable != this.properties.get(iproperty)) { + hashbasedtable.put(iproperty, comparable, + map.get(this.getPropertiesWithValue(iproperty, (Comparable) comparable))); + } + } + } + + this.propertyValueTable = ImmutableTable.copyOf(hashbasedtable); + } + } + + public boolean equals(Object object) { + return this == object; + } + + public Block getBlock() { + return this.block; + } + + public ImmutableMap getProperties() { + return this.properties; + } + + private Map getPropertiesWithValue(IProperty property, Comparable value) { + HashMap hashmap = Maps.newHashMap(this.properties); + hashmap.put(property, value); + return hashmap; + } + + public Collection getPropertyNames() { + return Collections.unmodifiableCollection(this.properties.keySet()); + } + + public > T getValue(IProperty iproperty) { + if (!this.properties.containsKey(iproperty)) { + throw new IllegalArgumentException( + "Cannot get property " + iproperty + " as it does not exist in " + this.block.getBlockState()); + } else { + return (T) ((Comparable) iproperty.getValueClass().cast(this.properties.get(iproperty))); + } + } + + public int hashCode() { + return this.properties.hashCode(); + } + + public , V extends T> IBlockState withProperty(IProperty iproperty, V comparable) { + if (!this.properties.containsKey(iproperty)) { + throw new IllegalArgumentException( + "Cannot set property " + iproperty + " as it does not exist in " + this.block.getBlockState()); + } else if (!iproperty.getAllowedValues().contains(comparable)) { + throw new IllegalArgumentException( + "Cannot set property " + iproperty + " to " + comparable + " on block " + + Block.blockRegistry.getNameForObject(this.block) + ", it is not an allowed value"); + } else { + return (IBlockState) (this.properties.get(iproperty) == comparable ? this + : (IBlockState) this.propertyValueTable.get(iproperty, comparable)); + } + } + } + private static final Joiner COMMA_JOINER = Joiner.on(", "); private static final Function GET_NAME_FUNC = new Function() { public String apply(IProperty iproperty) { @@ -55,6 +137,7 @@ public class BlockState { }; private final Block block; private final ImmutableList properties; + private final ImmutableList validStates; public BlockState(Block blockIn, IProperty... properties) { @@ -83,10 +166,6 @@ public class BlockState { this.validStates = ImmutableList.copyOf(arraylist); } - public ImmutableList getValidStates() { - return this.validStates; - } - private List> getAllowedValues() { ArrayList arraylist = Lists.newArrayList(); @@ -109,87 +188,12 @@ public class BlockState { return this.properties; } + public ImmutableList getValidStates() { + return this.validStates; + } + public String toString() { return Objects.toStringHelper(this).add("block", Block.blockRegistry.getNameForObject(this.block)) .add("properties", Iterables.transform(this.properties, GET_NAME_FUNC)).toString(); } - - static class StateImplementation extends BlockStateBase { - private final Block block; - private final ImmutableMap properties; - private ImmutableTable propertyValueTable; - - private StateImplementation(Block blockIn, ImmutableMap propertiesIn) { - this.block = blockIn; - this.properties = propertiesIn; - } - - public Collection getPropertyNames() { - return Collections.unmodifiableCollection(this.properties.keySet()); - } - - public > T getValue(IProperty iproperty) { - if (!this.properties.containsKey(iproperty)) { - throw new IllegalArgumentException( - "Cannot get property " + iproperty + " as it does not exist in " + this.block.getBlockState()); - } else { - return (T) ((Comparable) iproperty.getValueClass().cast(this.properties.get(iproperty))); - } - } - - public , V extends T> IBlockState withProperty(IProperty iproperty, V comparable) { - if (!this.properties.containsKey(iproperty)) { - throw new IllegalArgumentException( - "Cannot set property " + iproperty + " as it does not exist in " + this.block.getBlockState()); - } else if (!iproperty.getAllowedValues().contains(comparable)) { - throw new IllegalArgumentException( - "Cannot set property " + iproperty + " to " + comparable + " on block " - + Block.blockRegistry.getNameForObject(this.block) + ", it is not an allowed value"); - } else { - return (IBlockState) (this.properties.get(iproperty) == comparable ? this - : (IBlockState) this.propertyValueTable.get(iproperty, comparable)); - } - } - - public ImmutableMap getProperties() { - return this.properties; - } - - public Block getBlock() { - return this.block; - } - - public boolean equals(Object object) { - return this == object; - } - - public int hashCode() { - return this.properties.hashCode(); - } - - public void buildPropertyValueTable(Map, BlockState.StateImplementation> map) { - if (this.propertyValueTable != null) { - throw new IllegalStateException(); - } else { - HashBasedTable hashbasedtable = HashBasedTable.create(); - - for (IProperty iproperty : this.properties.keySet()) { - for (Object comparable : iproperty.getAllowedValues()) { - if (comparable != this.properties.get(iproperty)) { - hashbasedtable.put(iproperty, comparable, - map.get(this.getPropertiesWithValue(iproperty, (Comparable) comparable))); - } - } - } - - this.propertyValueTable = ImmutableTable.copyOf(hashbasedtable); - } - } - - private Map getPropertiesWithValue(IProperty property, Comparable value) { - HashMap hashmap = Maps.newHashMap(this.properties); - hashmap.put(property, value); - return hashmap; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/state/BlockStateBase.java b/src/game/java/net/minecraft/block/state/BlockStateBase.java index fc4222a4..1e50d2d7 100644 --- a/src/game/java/net/minecraft/block/state/BlockStateBase.java +++ b/src/game/java/net/minecraft/block/state/BlockStateBase.java @@ -11,22 +11,25 @@ import com.google.common.collect.Iterables; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,11 +47,6 @@ public abstract class BlockStateBase implements IBlockState { } }; - public > IBlockState cycleProperty(IProperty property) { - return this.withProperty(property, - (T) cyclePropertyValue(property.getAllowedValues(), this.getValue(property))); - } - protected static T cyclePropertyValue(Collection values, T currentValue) { Iterator iterator = values.iterator(); @@ -65,6 +63,11 @@ public abstract class BlockStateBase implements IBlockState { return (T) iterator.next(); } + public > IBlockState cycleProperty(IProperty property) { + return this.withProperty(property, + (T) cyclePropertyValue(property.getAllowedValues(), this.getValue(property))); + } + public String toString() { StringBuilder stringbuilder = new StringBuilder(); stringbuilder.append(Block.blockRegistry.getNameForObject(this.getBlock())); diff --git a/src/game/java/net/minecraft/block/state/BlockWorldState.java b/src/game/java/net/minecraft/block/state/BlockWorldState.java index 8346ed3d..afbfaea8 100644 --- a/src/game/java/net/minecraft/block/state/BlockWorldState.java +++ b/src/game/java/net/minecraft/block/state/BlockWorldState.java @@ -6,32 +6,44 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockWorldState { + public static Predicate hasState(final Predicate parPredicate) { + return new Predicate() { + public boolean apply(BlockWorldState blockworldstate) { + return blockworldstate != null && parPredicate.apply(blockworldstate.getBlockState()); + } + }; + } + private final World world; private final BlockPos pos; private final boolean field_181628_c; private IBlockState state; private TileEntity tileEntity; + private boolean tileEntityInitialized; public BlockWorldState(World parWorld, BlockPos parBlockPos, boolean parFlag) { @@ -48,6 +60,10 @@ public class BlockWorldState { return this.state; } + public BlockPos getPos() { + return this.pos; + } + public TileEntity getTileEntity() { if (this.tileEntity == null && !this.tileEntityInitialized) { this.tileEntity = this.world.getTileEntity(this.pos); @@ -56,16 +72,4 @@ public class BlockWorldState { return this.tileEntity; } - - public BlockPos getPos() { - return this.pos; - } - - public static Predicate hasState(final Predicate parPredicate) { - return new Predicate() { - public boolean apply(BlockWorldState blockworldstate) { - return blockworldstate != null && parPredicate.apply(blockworldstate.getBlockState()); - } - }; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/state/IBlockState.java b/src/game/java/net/minecraft/block/state/IBlockState.java index dcd52631..e063df43 100644 --- a/src/game/java/net/minecraft/block/state/IBlockState.java +++ b/src/game/java/net/minecraft/block/state/IBlockState.java @@ -7,39 +7,42 @@ import com.google.common.collect.ImmutableMap; import net.minecraft.block.Block; import net.minecraft.block.properties.IProperty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IBlockState { - /**+ - * Get the names of all properties defined for this BlockState + > IBlockState cycleProperty(IProperty var1); + + Block getBlock(); + + ImmutableMap getProperties(); + + /** + * + Get the names of all properties defined for this BlockState */ Collection getPropertyNames(); > T getValue(IProperty var1); , V extends T> IBlockState withProperty(IProperty var1, V var2); - - > IBlockState cycleProperty(IProperty var1); - - ImmutableMap getProperties(); - - Block getBlock(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/state/pattern/BlockHelper.java b/src/game/java/net/minecraft/block/state/pattern/BlockHelper.java index 5be93267..fa419219 100644 --- a/src/game/java/net/minecraft/block/state/pattern/BlockHelper.java +++ b/src/game/java/net/minecraft/block/state/pattern/BlockHelper.java @@ -5,37 +5,40 @@ import com.google.common.base.Predicate; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockHelper implements Predicate { + public static BlockHelper forBlock(Block blockType) { + return new BlockHelper(blockType); + } + private final Block block; private BlockHelper(Block blockType) { this.block = blockType; } - public static BlockHelper forBlock(Block blockType) { - return new BlockHelper(blockType); - } - public boolean apply(IBlockState iblockstate) { return iblockstate != null && iblockstate.getBlock() == this.block; } diff --git a/src/game/java/net/minecraft/block/state/pattern/BlockPattern.java b/src/game/java/net/minecraft/block/state/pattern/BlockPattern.java index 2a2a00d9..6632bd45 100644 --- a/src/game/java/net/minecraft/block/state/pattern/BlockPattern.java +++ b/src/game/java/net/minecraft/block/state/pattern/BlockPattern.java @@ -11,130 +11,30 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.Vec3i; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPattern { - private final Predicate[][][] blockMatches; - private final int fingerLength; - private final int thumbLength; - private final int palmLength; - - public BlockPattern(Predicate[][][] predicatesIn) { - this.blockMatches = predicatesIn; - this.fingerLength = predicatesIn.length; - if (this.fingerLength > 0) { - this.thumbLength = predicatesIn[0].length; - if (this.thumbLength > 0) { - this.palmLength = predicatesIn[0][0].length; - } else { - this.palmLength = 0; - } - } else { - this.thumbLength = 0; - this.palmLength = 0; - } - - } - - public int getThumbLength() { - return this.thumbLength; - } - - public int getPalmLength() { - return this.palmLength; - } - - /**+ - * checks that the given pattern & rotation is at the block - * co-ordinates. - */ - private BlockPattern.PatternHelper checkPatternAt(BlockPos pos, EnumFacing finger, EnumFacing thumb, - EaglerLoadingCache lcache) { - for (int i = 0; i < this.palmLength; ++i) { - for (int j = 0; j < this.thumbLength; ++j) { - for (int k = 0; k < this.fingerLength; ++k) { - if (!this.blockMatches[k][j][i].apply(lcache.get(translateOffset(pos, finger, thumb, i, j, k)))) { - return null; - } - } - } - } - - return new BlockPattern.PatternHelper(pos, finger, thumb, lcache, this.palmLength, this.thumbLength, - this.fingerLength); - } - - /**+ - * Calculates whether the given world position matches the - * pattern. Warning, fairly heavy function. @return a - * BlockPattern.PatternHelper if found, null otherwise. - */ - public BlockPattern.PatternHelper match(World worldIn, BlockPos pos) { - EaglerLoadingCache loadingcache = func_181627_a(worldIn, false); - int i = Math.max(Math.max(this.palmLength, this.thumbLength), this.fingerLength); - - for (BlockPos blockpos : BlockPos.getAllInBox(pos, pos.add(i - 1, i - 1, i - 1))) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int j = 0; j < facings.length; ++j) { - EnumFacing enumfacing = facings[j]; - for (int k = 0; k < facings.length; ++k) { - EnumFacing enumfacing1 = facings[k]; - if (enumfacing1 != enumfacing && enumfacing1 != enumfacing.getOpposite()) { - BlockPattern.PatternHelper blockpattern$patternhelper = this.checkPatternAt(blockpos, - enumfacing, enumfacing1, loadingcache); - if (blockpattern$patternhelper != null) { - return blockpattern$patternhelper; - } - } - } - } - } - - return null; - } - - public static EaglerLoadingCache func_181627_a(World parWorld, boolean parFlag) { - return new EaglerLoadingCache(new BlockPattern.CacheLoader(parWorld, parFlag)); - } - - /**+ - * Offsets the position of pos in the direction of finger and - * thumb facing by offset amounts, follows the right-hand rule - * for cross products (finger, thumb, palm) @return A new - * BlockPos offset in the facing directions - */ - protected static BlockPos translateOffset(BlockPos pos, EnumFacing finger, EnumFacing thumb, int palmOffset, - int thumbOffset, int fingerOffset) { - if (finger != thumb && finger != thumb.getOpposite()) { - Vec3i vec3i = new Vec3i(finger.getFrontOffsetX(), finger.getFrontOffsetY(), finger.getFrontOffsetZ()); - Vec3i vec3i1 = new Vec3i(thumb.getFrontOffsetX(), thumb.getFrontOffsetY(), thumb.getFrontOffsetZ()); - Vec3i vec3i2 = vec3i.crossProduct(vec3i1); - return pos.add(vec3i1.getX() * -thumbOffset + vec3i2.getX() * palmOffset + vec3i.getX() * fingerOffset, - vec3i1.getY() * -thumbOffset + vec3i2.getY() * palmOffset + vec3i.getY() * fingerOffset, - vec3i1.getZ() * -thumbOffset + vec3i2.getZ() * palmOffset + vec3i.getZ() * fingerOffset); - } else { - throw new IllegalArgumentException("Invalid forwards & up combination"); - } - } - static class CacheLoader implements EaglerCacheProvider { private final World world; private final boolean field_181626_b; @@ -173,14 +73,6 @@ public class BlockPattern { return this.pos; } - public EnumFacing getFinger() { - return this.finger; - } - - public EnumFacing getThumb() { - return this.thumb; - } - public int func_181118_d() { return this.field_181120_e; } @@ -189,20 +81,131 @@ public class BlockPattern { return this.field_181121_f; } - /**+ - * Offsets the position of pos in the direction of finger and - * thumb facing by offset amounts, follows the right-hand rule - * for cross products (finger, thumb, palm) @return A new - * BlockPos offset in the facing directions - */ - public BlockWorldState translateOffset(int palmOffset, int thumbOffset, int fingerOffset) { - return (BlockWorldState) this.lcache.get(BlockPattern.translateOffset(this.pos, this.getFinger(), - this.getThumb(), palmOffset, thumbOffset, fingerOffset)); + public EnumFacing getFinger() { + return this.finger; + } + + public EnumFacing getThumb() { + return this.thumb; } public String toString() { return Objects.toStringHelper(this).add("up", this.thumb).add("forwards", this.finger) .add("frontTopLeft", this.pos).toString(); } + + /** + * + Offsets the position of pos in the direction of finger and thumb facing by + * offset amounts, follows the right-hand rule for cross products (finger, + * thumb, palm) @return A new BlockPos offset in the facing directions + */ + public BlockWorldState translateOffset(int palmOffset, int thumbOffset, int fingerOffset) { + return (BlockWorldState) this.lcache.get(BlockPattern.translateOffset(this.pos, this.getFinger(), + this.getThumb(), palmOffset, thumbOffset, fingerOffset)); + } + } + + public static EaglerLoadingCache func_181627_a(World parWorld, boolean parFlag) { + return new EaglerLoadingCache(new BlockPattern.CacheLoader(parWorld, parFlag)); + } + + /** + * + Offsets the position of pos in the direction of finger and thumb facing by + * offset amounts, follows the right-hand rule for cross products (finger, + * thumb, palm) @return A new BlockPos offset in the facing directions + */ + protected static BlockPos translateOffset(BlockPos pos, EnumFacing finger, EnumFacing thumb, int palmOffset, + int thumbOffset, int fingerOffset) { + if (finger != thumb && finger != thumb.getOpposite()) { + Vec3i vec3i = new Vec3i(finger.getFrontOffsetX(), finger.getFrontOffsetY(), finger.getFrontOffsetZ()); + Vec3i vec3i1 = new Vec3i(thumb.getFrontOffsetX(), thumb.getFrontOffsetY(), thumb.getFrontOffsetZ()); + Vec3i vec3i2 = vec3i.crossProduct(vec3i1); + return pos.add(vec3i1.getX() * -thumbOffset + vec3i2.getX() * palmOffset + vec3i.getX() * fingerOffset, + vec3i1.getY() * -thumbOffset + vec3i2.getY() * palmOffset + vec3i.getY() * fingerOffset, + vec3i1.getZ() * -thumbOffset + vec3i2.getZ() * palmOffset + vec3i.getZ() * fingerOffset); + } else { + throw new IllegalArgumentException("Invalid forwards & up combination"); + } + } + + private final Predicate[][][] blockMatches; + + private final int fingerLength; + + private final int thumbLength; + + private final int palmLength; + + public BlockPattern(Predicate[][][] predicatesIn) { + this.blockMatches = predicatesIn; + this.fingerLength = predicatesIn.length; + if (this.fingerLength > 0) { + this.thumbLength = predicatesIn[0].length; + if (this.thumbLength > 0) { + this.palmLength = predicatesIn[0][0].length; + } else { + this.palmLength = 0; + } + } else { + this.thumbLength = 0; + this.palmLength = 0; + } + + } + + /** + * + checks that the given pattern & rotation is at the block co-ordinates. + */ + private BlockPattern.PatternHelper checkPatternAt(BlockPos pos, EnumFacing finger, EnumFacing thumb, + EaglerLoadingCache lcache) { + for (int i = 0; i < this.palmLength; ++i) { + for (int j = 0; j < this.thumbLength; ++j) { + for (int k = 0; k < this.fingerLength; ++k) { + if (!this.blockMatches[k][j][i].apply(lcache.get(translateOffset(pos, finger, thumb, i, j, k)))) { + return null; + } + } + } + } + + return new BlockPattern.PatternHelper(pos, finger, thumb, lcache, this.palmLength, this.thumbLength, + this.fingerLength); + } + + public int getPalmLength() { + return this.palmLength; + } + + public int getThumbLength() { + return this.thumbLength; + } + + /** + * + Calculates whether the given world position matches the pattern. Warning, + * fairly heavy function. @return a BlockPattern.PatternHelper if found, null + * otherwise. + */ + public BlockPattern.PatternHelper match(World worldIn, BlockPos pos) { + EaglerLoadingCache loadingcache = func_181627_a(worldIn, false); + int i = Math.max(Math.max(this.palmLength, this.thumbLength), this.fingerLength); + + for (BlockPos blockpos : BlockPos.getAllInBox(pos, pos.add(i - 1, i - 1, i - 1))) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int j = 0; j < facings.length; ++j) { + EnumFacing enumfacing = facings[j]; + for (int k = 0; k < facings.length; ++k) { + EnumFacing enumfacing1 = facings[k]; + if (enumfacing1 != enumfacing && enumfacing1 != enumfacing.getOpposite()) { + BlockPattern.PatternHelper blockpattern$patternhelper = this.checkPatternAt(blockpos, + enumfacing, enumfacing1, loadingcache); + if (blockpattern$patternhelper != null) { + return blockpattern$patternhelper; + } + } + } + } + } + + return null; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/block/state/pattern/BlockStateHelper.java b/src/game/java/net/minecraft/block/state/pattern/BlockStateHelper.java index 98619bbb..5cb28d38 100644 --- a/src/game/java/net/minecraft/block/state/pattern/BlockStateHelper.java +++ b/src/game/java/net/minecraft/block/state/pattern/BlockStateHelper.java @@ -11,38 +11,42 @@ import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.BlockState; import net.minecraft.block.state.IBlockState; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockStateHelper implements Predicate { + public static BlockStateHelper forBlock(Block blockIn) { + return new BlockStateHelper(blockIn.getBlockState()); + } + private final BlockState blockstate; + private final Map propertyPredicates = Maps.newHashMap(); private BlockStateHelper(BlockState blockStateIn) { this.blockstate = blockStateIn; } - public static BlockStateHelper forBlock(Block blockIn) { - return new BlockStateHelper(blockIn.getBlockState()); - } - public boolean apply(IBlockState iblockstate) { if (iblockstate != null && iblockstate.getBlock().equals(this.blockstate.getBlock())) { for (Entry entry : this.propertyPredicates.entrySet()) { diff --git a/src/game/java/net/minecraft/block/state/pattern/FactoryBlockPattern.java b/src/game/java/net/minecraft/block/state/pattern/FactoryBlockPattern.java index 92a9c607..b2ae4fc9 100644 --- a/src/game/java/net/minecraft/block/state/pattern/FactoryBlockPattern.java +++ b/src/game/java/net/minecraft/block/state/pattern/FactoryBlockPattern.java @@ -15,31 +15,40 @@ import com.google.common.collect.Maps; import net.minecraft.block.state.BlockWorldState; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FactoryBlockPattern { private static final Joiner COMMA_JOIN = Joiner.on(","); + + public static FactoryBlockPattern start() { + return new FactoryBlockPattern(); + } + private final List depth = Lists.newArrayList(); private final Map> symbolMap = Maps.newHashMap(); private int aisleHeight; + private int rowWidth; private FactoryBlockPattern() { @@ -82,19 +91,25 @@ public class FactoryBlockPattern { } } - public static FactoryBlockPattern start() { - return new FactoryBlockPattern(); - } - - public FactoryBlockPattern where(char symbol, Predicate blockMatcher) { - this.symbolMap.put(Character.valueOf(symbol), blockMatcher); - return this; - } - public BlockPattern build() { return new BlockPattern(this.makePredicateArray()); } + private void checkMissingPredicates() { + ArrayList arraylist = Lists.newArrayList(); + + for (Entry entry : this.symbolMap.entrySet()) { + if (entry.getValue() == null) { + arraylist.add(entry.getKey()); + } + } + + if (!arraylist.isEmpty()) { + throw new IllegalStateException( + "Predicates for character(s) " + COMMA_JOIN.join(arraylist) + " are missing"); + } + } + private Predicate[][][] makePredicateArray() { this.checkMissingPredicates(); Predicate[][][] apredicate = new Predicate[this.depth.size()][this.aisleHeight][this.rowWidth]; @@ -111,18 +126,8 @@ public class FactoryBlockPattern { return apredicate; } - private void checkMissingPredicates() { - ArrayList arraylist = Lists.newArrayList(); - - for (Entry entry : this.symbolMap.entrySet()) { - if (entry.getValue() == null) { - arraylist.add(entry.getKey()); - } - } - - if (!arraylist.isEmpty()) { - throw new IllegalStateException( - "Predicates for character(s) " + COMMA_JOIN.join(arraylist) + " are missing"); - } + public FactoryBlockPattern where(char symbol, Predicate blockMatcher) { + this.symbolMap.put(Character.valueOf(symbol), blockMatcher); + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/ClientBrandRetriever.java b/src/game/java/net/minecraft/client/ClientBrandRetriever.java index b93a7e15..f9408aa1 100644 --- a/src/game/java/net/minecraft/client/ClientBrandRetriever.java +++ b/src/game/java/net/minecraft/client/ClientBrandRetriever.java @@ -1,27 +1,30 @@ package net.minecraft.client; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ClientBrandRetriever { public static String getClientModName() { - return "eagler"; + return "starlike"; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/LoadingScreenRenderer.java b/src/game/java/net/minecraft/client/LoadingScreenRenderer.java index 5a582501..74614042 100644 --- a/src/game/java/net/minecraft/client/LoadingScreenRenderer.java +++ b/src/game/java/net/minecraft/client/LoadingScreenRenderer.java @@ -1,6 +1,11 @@ package net.minecraft.client; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; @@ -12,22 +17,25 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.IProgressUpdate; import net.minecraft.util.MinecraftError; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,13 +43,13 @@ import net.minecraft.util.MinecraftError; public class LoadingScreenRenderer implements IProgressUpdate { private String message = ""; private Minecraft mc; - /**+ - * The text currently displayed (i.e. the argument to the last - * call to printText or func_73722_d) + /** + * + The text currently displayed (i.e. the argument to the last call to + * printText or func_73722_d) */ private String currentlyDisplayedText = ""; - /**+ - * The system's time represented in milliseconds. + /** + * + The system's time represented in milliseconds. */ private long systemTime = Minecraft.getSystemTime(); private boolean field_73724_e; @@ -50,18 +58,25 @@ public class LoadingScreenRenderer implements IProgressUpdate { this.mc = mcIn; } - /**+ - * this string, followed by "working..." and then the "% - * complete" are the 3 lines shown. This resets progress to 0, - * and the WorkingString to "working...". + /** + * + Displays a string on the loading screen supposed to indicate what is being + * done currently. */ - public void resetProgressAndMessage(String message) { - this.field_73724_e = false; - this.displayString(message); + public void displayLoadingString(String message) { + if (!this.mc.running) { + if (!this.field_73724_e) { + throw new MinecraftError(); + } + } else { + this.systemTime = 0L; + this.message = message; + this.setLoadingProgress(-1); + this.systemTime = 0L; + } } - /**+ - * Shows the 'Saving level' string. + /** + * + Shows the 'Saving level' string. */ public void displaySavingString(String message) { this.field_73724_e = true; @@ -86,23 +101,6 @@ public class LoadingScreenRenderer implements IProgressUpdate { } } - /**+ - * Displays a string on the loading screen supposed to indicate - * what is being done currently. - */ - public void displayLoadingString(String message) { - if (!this.mc.running) { - if (!this.field_73724_e) { - throw new MinecraftError(); - } - } else { - this.systemTime = 0L; - this.message = message; - this.setLoadingProgress(-1); - this.systemTime = 0L; - } - } - public void eaglerShow(String line1, String line2) { if (!this.mc.running) { if (!this.field_73724_e) { @@ -121,9 +119,22 @@ public class LoadingScreenRenderer implements IProgressUpdate { eaglerShow(I18n.format("resourcePack.load.refreshing"), I18n.format("resourcePack.load.pleaseWait")); } - /**+ - * Updates the progress bar on the loading screen to the - * specified amount. Args: loadProgress + /** + * + this string, followed by "working..." and then the "% complete" are the 3 + * lines shown. This resets progress to 0, and the WorkingString to + * "working...". + */ + public void resetProgressAndMessage(String message) { + this.field_73724_e = false; + this.displayString(message); + } + + public void setDoneWorking() { + } + + /** + * + Updates the progress bar on the loading screen to the specified amount. + * Args: loadProgress */ public void setLoadingProgress(int progress) { if (!this.mc.running) { @@ -205,7 +216,4 @@ public class LoadingScreenRenderer implements IProgressUpdate { } } } - - public void setDoneWorking() { - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/Minecraft.java b/src/game/java/net/minecraft/client/Minecraft.java index b377c114..7af3a9ae 100644 --- a/src/game/java/net/minecraft/client/Minecraft.java +++ b/src/game/java/net/minecraft/client/Minecraft.java @@ -1,8 +1,15 @@ package net.minecraft.client; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BACK; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MAX_TEXTURE_SIZE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; import java.io.IOException; import java.io.InputStream; @@ -12,6 +19,10 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; +import org.apache.commons.lang3.Validate; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.ClientUUIDLoadingCache; import net.lax1dude.eaglercraft.v1_8.Display; import net.lax1dude.eaglercraft.v1_8.EagRuntime; @@ -25,17 +36,12 @@ import net.lax1dude.eaglercraft.v1_8.PauseMenuCustomizeState; import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; import net.lax1dude.eaglercraft.v1_8.Touch; import net.lax1dude.eaglercraft.v1_8.cookie.ServerCookieDataStore; -import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; - -import org.apache.commons.lang3.Validate; - -import com.google.common.collect.Lists; - import net.lax1dude.eaglercraft.v1_8.futures.Executors; import net.lax1dude.eaglercraft.v1_8.futures.FutureTask; import net.lax1dude.eaglercraft.v1_8.futures.ListenableFuture; import net.lax1dude.eaglercraft.v1_8.futures.ListenableFutureTask; import net.lax1dude.eaglercraft.v1_8.internal.EnumPlatformType; +import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; import net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; @@ -199,22 +205,25 @@ import net.minecraft.world.WorldProviderHell; import net.minecraft.world.WorldSettings; import net.minecraft.world.storage.ISaveFormat; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -223,9 +232,62 @@ public class Minecraft implements IThreadListener { private static final Logger logger = LogManager.getLogger(); private static final ResourceLocation locationMojangPng = new ResourceLocation("textures/gui/title/mojang.png"); public static final boolean isRunningOnMac = false; + private static Minecraft theMinecraft; + private static int debugFPS; + + public static int getDebugFPS() { + return debugFPS; + } + + /** + * + Used in the usage snooper. + */ + public static int getGLMaximumTextureSize() { + return EaglercraftGPU.glGetInteger(GL_MAX_TEXTURE_SIZE); + } + + /** + * + Return the singleton Minecraft instance for the game + */ + public static Minecraft getMinecraft() { + return theMinecraft; + } + + /** + * + Gets the system time in milliseconds. + */ + public static long getSystemTime() { + return EagRuntime.steadyTimeMillis(); + } + + /** + * + Returns if ambient occlusion is enabled + */ + public static boolean isAmbientOcclusionEnabled() { + if (theMinecraft == null) + return false; + GameSettings g = theMinecraft.gameSettings; + return g.ambientOcclusion != 0 && !g.shadersAODisable; + } + + public static boolean isFancyGraphicsEnabled() { + return theMinecraft != null && theMinecraft.gameSettings.fancyGraphics; + } + + public static boolean isGuiEnabled() { + return theMinecraft == null || !theMinecraft.gameSettings.hideGUI; + } + + private static boolean isJvm64bit() { + return true; + } + + public static void stopIntegratedServer() { + + } + private ServerData currentServerData; private TextureManager renderEngine; - private static Minecraft theMinecraft; public PlayerControllerMP playerController; private boolean fullscreen; private boolean enableGLErrorChecking = true; @@ -263,7 +325,6 @@ public class Minecraft implements IThreadListener { public GameSettings gameSettings; public MouseHelper mouseHelper; private final String launchedVersion; - private static int debugFPS; private int rightClickDelayTimer; private String serverName; private int serverPort; @@ -275,9 +336,9 @@ public class Minecraft implements IThreadListener { private final boolean jvm64bit; private EaglercraftNetworkManager myNetworkManager; private boolean integratedServerIsRunning; - /**+ - * Keeps track of how long the debug crash keycombo (F3+C) has - * been pressed for, in order to crash after 10 seconds. + /** + * + Keeps track of how long the debug crash keycombo (F3+C) has been pressed + * for, in order to crash after 10 seconds. */ private long debugCrashKeyPressTime = -1L; private IReloadableResourceManager mcResourceManager; @@ -295,44 +356,59 @@ public class Minecraft implements IThreadListener { private final Thread mcThread = Thread.currentThread(); private ModelManager modelManager; private BlockRendererDispatcher blockRenderDispatcher; - /**+ - * Set to true to keep the game loop running. Set to false by - * shutdown() to allow the game loop to exit cleanly. + /** + * + Set to true to keep the game loop running. Set to false by shutdown() to + * allow the game loop to exit cleanly. */ volatile boolean running = true; - /**+ - * String that shows the debug information + /** + * + String that shows the debug information */ public String debug = ""; public boolean field_175613_B = false; public boolean field_175614_C = false; public boolean field_175611_D = false; + public boolean renderChunksMany = true; + long debugUpdateTime = getSystemTime(); int fpsCounter; long prevFrameTime = -1L; - /**+ - * Profiler currently displayed in the debug screen pie chart + + /** + * + Profiler currently displayed in the debug screen pie chart */ private String debugProfilerName = "root"; public int joinWorldTickCounter = 0; private int dontPauseTimer = 0; public int bungeeOutdatedMsgTimer = 0; private boolean isLANOpen = false; - public SkullCommand eagskullCommand; public GuiVoiceOverlay voiceOverlay; + public ServerNotificationRenderer notifRenderer; + public TouchOverlayRenderer touchOverlayRenderer; public float startZoomValue = 18.0f; + public float adjustedZoomValue = 18.0f; + public boolean isZoomKey = false; + private String reconnectURI = null; + public boolean mouseGrabSupported = false; + public ScaledResolution scaledResolution = null; + private long placeTouchStartTime = -1l; + + private long mineTouchStartTime = -1l; + + private boolean wasMiningTouch = false; + public Minecraft(GameConfiguration gameConfig) { theMinecraft = this; StringTranslate.initClient(); @@ -357,216 +433,225 @@ public class Minecraft implements IThreadListener { Bootstrap.register(); } - public void run() { - this.running = true; - - try { - this.startGame(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Initializing game"); - crashreport.makeCategory("Initialization"); - this.displayCrashReport(this.addGraphicsAndWorldToCrashReport(crashreport)); - return; - } - - try { - while (true) { - if (!this.running) { - break; - } - - if (!this.hasCrashed || this.crashReporter == null) { - this.runGameLoop(); - continue; - } - - this.displayCrashReport(this.crashReporter); - } - } catch (MinecraftError var12) { - // ?? - } catch (ReportedException reportedexception) { - this.addGraphicsAndWorldToCrashReport(reportedexception.getCrashReport()); - logger.fatal("Reported exception thrown!", reportedexception); - this.displayCrashReport(reportedexception.getCrashReport()); - } catch (Throwable throwable1) { - CrashReport crashreport1 = this - .addGraphicsAndWorldToCrashReport(new CrashReport("Unexpected error", throwable1)); - logger.fatal("Unreported exception thrown!", throwable1); - this.displayCrashReport(crashreport1); - } finally { - this.shutdownMinecraftApplet(); - } - - } - - /**+ - * Starts the game: initializes the canvas, the title, the - * settings, etcetera. + /** + * + adds core server Info (GL version , Texture pack, isModded, type), and the + * worldInfo to the crash report */ - private void startGame() throws IOException { - this.gameSettings = new GameSettings(this); - this.defaultResourcePacks.add(this.mcDefaultResourcePack); - if (this.gameSettings.overrideHeight > 0 && this.gameSettings.overrideWidth > 0) { - this.displayWidth = this.gameSettings.overrideWidth; - this.displayHeight = this.gameSettings.overrideHeight; - } - - logger.info("EagRuntime Version: " + EagRuntime.getVersion()); - this.createDisplay(); - this.registerMetadataSerializers(); - EaglerFolderResourcePack.deleteOldResourcePacks(EaglerFolderResourcePack.SERVER_RESOURCE_PACKS, 604800000L); - this.mcResourcePackRepository = new ResourcePackRepository(this.mcDefaultResourcePack, this.metadataSerializer_, - this.gameSettings); - this.mcResourceManager = new SimpleReloadableResourceManager(this.metadataSerializer_); - this.mcLanguageManager = new LanguageManager(this.metadataSerializer_, this.gameSettings.language); - this.mcResourceManager.registerReloadListener(this.mcLanguageManager); - this.scaledResolution = new ScaledResolution(this); - this.refreshResources(); - this.renderEngine = new TextureManager(this.mcResourceManager); - this.mcResourceManager.registerReloadListener(this.renderEngine); - this.drawSplashScreen(this.renderEngine); - this.mcSoundHandler = new SoundHandler(this.mcResourceManager, this.gameSettings); - this.mcResourceManager.registerReloadListener(this.mcSoundHandler); - this.mcMusicTicker = new MusicTicker(this); - this.fontRendererObj = EaglerFontRenderer.createSupportedFontRenderer(this.gameSettings, - new ResourceLocation("textures/font/ascii.png"), this.renderEngine, false); - if (this.gameSettings.language != null) { - this.fontRendererObj.setUnicodeFlag(this.isUnicode()); - this.fontRendererObj.setBidiFlag(this.mcLanguageManager.isCurrentLanguageBidirectional()); - } - - this.standardGalacticFontRenderer = EaglerFontRenderer.createSupportedFontRenderer(this.gameSettings, - new ResourceLocation("textures/font/ascii_sga.png"), this.renderEngine, false); - this.mcResourceManager.registerReloadListener(this.fontRendererObj); - this.mcResourceManager.registerReloadListener(this.standardGalacticFontRenderer); - this.mcResourceManager.registerReloadListener(new GrassColorReloadListener()); - this.mcResourceManager.registerReloadListener(new FoliageColorReloadListener()); - this.mcResourceManager.registerReloadListener(new ShaderPackInfoReloadListener()); - this.mcResourceManager.registerReloadListener(PBRTextureMapUtils.blockMaterialConstants); - this.mcResourceManager.registerReloadListener(new TemperaturesLUT()); - this.mcResourceManager.registerReloadListener(new MetalsLUT()); - this.mcResourceManager.registerReloadListener(new EmissiveItems()); - this.mcResourceManager.registerReloadListener(new BlockVertexIDs()); - this.mcResourceManager.registerReloadListener(new EaglerMeshLoader()); - AchievementList.openInventory.setStatStringFormatter(new IStatStringFormat() { - public String formatString(String parString1) { - try { - return HString.format(parString1, new Object[] { GameSettings - .getKeyDisplayString(Minecraft.this.gameSettings.keyBindInventory.getKeyCode()) }); - } catch (Exception exception) { - return "Error: " + exception.getLocalizedMessage(); - } + public CrashReport addGraphicsAndWorldToCrashReport(CrashReport theCrash) { + theCrash.getCategory().addCrashSectionCallable("Launched Version", new Callable() { + public String call() throws Exception { + return Minecraft.this.launchedVersion; } }); - this.mouseHelper = new MouseHelper(); - this.checkGLError("Pre startup"); - GlStateManager.enableTexture2D(); - GlStateManager.shadeModel(GL_SMOOTH); - GlStateManager.clearDepth(1.0f); - GlStateManager.enableDepth(); - GlStateManager.depthFunc(GL_LEQUAL); - GlStateManager.enableAlpha(); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - GlStateManager.cullFace(GL_BACK); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.matrixMode(GL_MODELVIEW); - this.checkGLError("Startup"); - this.textureMapBlocks = new TextureMap("textures"); - this.textureMapBlocks.setEnablePBREagler(gameSettings.shaders); - this.textureMapBlocks.setMipmapLevels(this.gameSettings.mipmapLevels); - this.renderEngine.loadTickableTexture(TextureMap.locationBlocksTexture, this.textureMapBlocks); - this.renderEngine.bindTexture(TextureMap.locationBlocksTexture); - this.textureMapBlocks.setBlurMipmapDirect(false, this.gameSettings.mipmapLevels > 0); - this.modelManager = new ModelManager(this.textureMapBlocks); - this.mcResourceManager.registerReloadListener(this.modelManager); - this.renderItem = new RenderItem(this.renderEngine, this.modelManager); - this.renderManager = new RenderManager(this.renderEngine, this.renderItem); - this.itemRenderer = new ItemRenderer(this); - this.mcResourceManager.registerReloadListener(this.renderItem); - this.entityRenderer = new EntityRenderer(this, this.mcResourceManager); - this.mcResourceManager.registerReloadListener(this.entityRenderer); - this.blockRenderDispatcher = new BlockRendererDispatcher(this.modelManager.getBlockModelShapes(), - this.gameSettings); - this.mcResourceManager.registerReloadListener(this.blockRenderDispatcher); - this.renderGlobal = new RenderGlobal(this); - this.mcResourceManager.registerReloadListener(this.renderGlobal); - this.guiAchievement = new GuiAchievement(this); - GlStateManager.viewport(0, 0, this.displayWidth, this.displayHeight); - this.effectRenderer = new EffectRenderer(this.theWorld, this.renderEngine); - SkinPreviewRenderer.initialize(); - this.checkGLError("Post startup"); - this.ingameGUI = new GuiIngame(this); + theCrash.getCategory().addCrashSectionCallable("LWJGL", new Callable() { + public String call() { + return EagRuntime.getVersion(); + } + }); + theCrash.getCategory().addCrashSectionCallable("OpenGL", new Callable() { + public String call() { + return EaglercraftGPU.glGetString(7937) + " GL version " + EaglercraftGPU.glGetString(7938) + ", " + + EaglercraftGPU.glGetString(7936); + } + }); + theCrash.getCategory().addCrashSectionCallable("Is Eagler Shaders", new Callable() { + public String call() throws Exception { + return Minecraft.this.gameSettings.shaders ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("Is Dynamic Lights", new Callable() { + public String call() throws Exception { + return !Minecraft.this.gameSettings.shaders && Minecraft.this.gameSettings.enableDynamicLights ? "Yes" + : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("In Ext. Pipeline", new Callable() { + public String call() throws Exception { + return GlStateManager.isExtensionPipeline() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("GPU Shader5 Capable", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.checkShader5Capable() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("GPU TexStorage Capable", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.checkTexStorageCapable() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("GPU TextureLOD Capable", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.checkTextureLODCapable() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("GPU Instancing Capable", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.checkInstancingCapable() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("GPU VAO Capable", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.checkVAOCapable() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("Is Software VAOs", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.areVAOsEmulated() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("GPU Render-to-MipMap", new Callable() { + public String call() throws Exception { + return EaglercraftGPU.checkFBORenderMipmapCapable() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("Touch Mode", new Callable() { + public String call() throws Exception { + return PointerInputAbstraction.isTouchMode() ? "Yes" : "No"; + } + }); + theCrash.getCategory().addCrashSectionCallable("Is Modded", new Callable() { + public String call() throws Exception { + return "Definitely Not; You're an eagler"; + } + }); + theCrash.getCategory().addCrashSectionCallable("Type", new Callable() { + public String call() throws Exception { + return "Client (map_client.txt)"; + } + }); + theCrash.getCategory().addCrashSectionCallable("Resource Packs", new Callable() { + public String call() throws Exception { + StringBuilder stringbuilder = new StringBuilder(); - this.mouseGrabSupported = Mouse.isMouseGrabSupported(); - PointerInputAbstraction.init(this); + for (String s : Minecraft.this.gameSettings.resourcePacks) { + if (stringbuilder.length() > 0) { + stringbuilder.append(", "); + } - this.eagskullCommand = new SkullCommand(this); - this.voiceOverlay = new GuiVoiceOverlay(this); - this.voiceOverlay.setResolution(scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight()); + stringbuilder.append(s); + if (Minecraft.this.gameSettings.field_183018_l.contains(s)) { + stringbuilder.append(" (incompatible)"); + } + } - this.notifRenderer = new ServerNotificationRenderer(); - this.notifRenderer.init(); - this.notifRenderer.setResolution(this, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), - scaledResolution.getScaleFactor()); - this.touchOverlayRenderer = new TouchOverlayRenderer(this); - - ServerList.initServerList(this); - EaglerProfile.read(); - ServerCookieDataStore.load(); - - GuiScreen mainMenu = new GuiMainMenu(); - if (isDemo()) { - mainMenu = new GuiScreenDemoIntegratedServerStartup(mainMenu); - } - if (this.serverName != null) { - mainMenu = new GuiConnecting(mainMenu, this, this.serverName, this.serverPort); + return stringbuilder.toString(); + } + }); + theCrash.getCategory().addCrashSectionCallable("Current Language", new Callable() { + public String call() throws Exception { + return Minecraft.this.mcLanguageManager.getCurrentLanguage().toString(); + } + }); + theCrash.getCategory().addCrashSectionCallable("Profiler Position", new Callable() { + public String call() throws Exception { + return "N/A (disabled)"; + } + }); + if (this.theWorld != null) { + this.theWorld.addWorldInfoToCrashReport(theCrash); } - mainMenu = new GuiScreenEditProfile(mainMenu); + return theCrash; + } - if (!EagRuntime.getConfiguration().isForceProfanityFilter() && !gameSettings.hasShownProfanityFilter) { - mainMenu = new GuiScreenContentWarning(mainMenu); + public void addScheduledTask(Runnable runnableToSchedule) { + this.addScheduledTaskFuture(Executors.callable(runnableToSchedule)); + } + + public ListenableFuture addScheduledTaskFuture(Callable callableToSchedule) { + Validate.notNull(callableToSchedule); + ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callableToSchedule); + synchronized (this.scheduledTasks) { + this.scheduledTasks.add(listenablefuturetask); + return listenablefuturetask; + } + } + + public ListenableFuture addScheduledTaskFuture(Runnable runnableToSchedule) { + Validate.notNull(runnableToSchedule); + return this.addScheduledTaskFuture(Executors.callable(runnableToSchedule)); + } + + public boolean areKeysLocked() { + return PlatformInput.lockKeys; + } + + /** + * + Checks for an OpenGL error. If there is one, prints the error ID and error + * string. + */ + public void checkGLError(String message) { + if (this.enableGLErrorChecking) { + int i = EaglercraftGPU.glGetError(); + if (i != 0) { + String s = EaglercraftGPU.gluErrorString(i); + logger.error("########## GL ERROR ##########"); + logger.error("@ " + message); + logger.error(i + ": " + s); + } + + } + } + + protected void checkWindowResize() { + float dpiFetch = -1.0f; + if (!this.fullscreen + && (Display.wasResized() || (dpiFetch = Math.max(Display.getDPI(), 1.0f)) != this.displayDPI)) { + int i = this.displayWidth; + int j = this.displayHeight; + float f = this.displayDPI; + this.displayWidth = Display.getWidth(); + this.displayHeight = Display.getHeight(); + this.displayDPI = dpiFetch == -1.0f ? Math.max(Display.getDPI(), 1.0f) : dpiFetch; + if (this.displayWidth != i || this.displayHeight != j || this.displayDPI != f) { + if (this.displayWidth <= 0) { + this.displayWidth = 1; + } + + if (this.displayHeight <= 0) { + this.displayHeight = 1; + } + + this.resize(this.displayWidth, this.displayHeight); + } } - this.displayGuiScreen(mainMenu); - - this.renderEngine.deleteTexture(this.mojangLogo); - this.mojangLogo = null; - this.loadingScreen = new LoadingScreenRenderer(this); - - while (Mouse.next()) - ; - while (Keyboard.next()) - ; - while (Touch.next()) - ; } - private void registerMetadataSerializers() { - this.metadataSerializer_.registerMetadataSectionType(new TextureMetadataSectionSerializer(), - TextureMetadataSection.class); - this.metadataSerializer_.registerMetadataSectionType(new FontMetadataSectionSerializer(), - FontMetadataSection.class); - this.metadataSerializer_.registerMetadataSectionType(new AnimationMetadataSectionSerializer(), - AnimationMetadataSection.class); - this.metadataSerializer_.registerMetadataSectionType(new PackMetadataSectionSerializer(), - PackMetadataSection.class); - this.metadataSerializer_.registerMetadataSectionType(new LanguageMetadataSectionSerializer(), - LanguageMetadataSection.class); + public void clearTitles() { + ingameGUI.displayTitle(null, null, -1, -1, -1); } - private void createDisplay() { - Display.create(); - Display.setTitle("Eaglercraft 1.8.8"); - } + private void clickMouse() { + if (this.leftClickCounter <= 0) { + this.thePlayer.swingItem(); + if (this.objectMouseOver == null) { + logger.error("Null returned as \'hitResult\', this shouldn\'t happen!"); + if (this.playerController.isNotCreative()) { + this.leftClickCounter = 10; + } - private static boolean isJvm64bit() { - return true; - } + } else { + switch (this.objectMouseOver.typeOfHit) { + case ENTITY: + this.playerController.attackEntity(this.thePlayer, this.objectMouseOver.entityHit); + break; + case BLOCK: + BlockPos blockpos = this.objectMouseOver.getBlockPos(); + if (this.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { + this.playerController.clickBlock(blockpos, this.objectMouseOver.sideHit); + break; + } + case MISS: + default: + if (this.playerController.isNotCreative()) { + this.leftClickCounter = 10; + } + } - public String getVersion() { - return this.launchedVersion; + } + } } public void crashed(CrashReport crash) { @@ -574,8 +659,27 @@ public class Minecraft implements IThreadListener { this.crashReporter = crash; } - /**+ - * Wrapper around displayCrashReportInternal + private void createDisplay() { + Display.create(); + Display.setTitle("Eaglercraft 1.8.8"); + } + + public void dispatchKeypresses() { + int i = Keyboard.getEventKey() == 0 ? Keyboard.getEventCharacter() : Keyboard.getEventKey(); + if (i != 0 && !Keyboard.isRepeatEvent()) { + if (!(this.currentScreen instanceof GuiControls) + || ((GuiControls) this.currentScreen).time <= getSystemTime() - 20L) { + if (Keyboard.getEventKeyState()) { + if (i == this.gameSettings.keyBindScreenshot.getKeyCode()) { + this.ingameGUI.getChatGUI().printChatMessage(ScreenShotHelper.saveScreenshot()); + } + } + } + } + } + + /** + * + Wrapper around displayCrashReportInternal */ public void displayCrashReport(CrashReport crashReportIn) { String report = crashReportIn.getCompleteReport(); @@ -593,53 +697,48 @@ public class Minecraft implements IThreadListener { } } - public boolean isUnicode() { - return this.mcLanguageManager.isCurrentLocaleUnicode() || this.gameSettings.forceUnicodeFont; - } - - public void refreshResources() { - GlStateManager.recompileShaders(); - - ArrayList arraylist = Lists.newArrayList(this.defaultResourcePacks); - - for (ResourcePackRepository.Entry resourcepackrepository$entry : this.mcResourcePackRepository - .getRepositoryEntries()) { - arraylist.add(resourcepackrepository$entry.getResourcePack()); + /** + * + Sets the argument GuiScreen as the main (topmost visible) screen. + */ + public void displayGuiScreen(GuiScreen guiScreenIn) { + if (this.currentScreen != null) { + this.currentScreen.onGuiClosed(); } - if (this.mcResourcePackRepository.getResourcePackInstance() != null) { - arraylist.add(this.mcResourcePackRepository.getResourcePackInstance()); + if (guiScreenIn == null && this.theWorld == null) { + guiScreenIn = new GuiMainMenu(); + } else if (guiScreenIn == null && this.thePlayer.getHealth() <= 0.0F) { + guiScreenIn = new GuiGameOver(); } - try { - this.mcResourceManager.reloadResources(arraylist); - } catch (RuntimeException runtimeexception) { - logger.info("Caught error stitching, removing all assigned resourcepacks"); - logger.info(runtimeexception); - arraylist.clear(); - arraylist.addAll(this.defaultResourcePacks); - this.mcResourcePackRepository.setRepositories(Collections.emptyList()); - this.mcResourceManager.reloadResources(arraylist); - this.gameSettings.resourcePacks.clear(); - this.gameSettings.field_183018_l.clear(); - this.gameSettings.saveOptions(); + if (guiScreenIn instanceof GuiMainMenu) { + this.gameSettings.showDebugInfo = false; + this.ingameGUI.getChatGUI().clearChatMessages(); } - ShaderSource.clearCache(); - GuiMainMenu.doResourceReloadHack(); - - this.mcLanguageManager.parseLanguageMetadata(arraylist); - if (this.renderGlobal != null) { - this.renderGlobal.loadRenderers(); - } - - } - - private void updateDisplayMode() { - this.displayWidth = Display.getWidth(); - this.displayHeight = Display.getHeight(); - this.displayDPI = Display.getDPI(); + this.currentScreen = (GuiScreen) guiScreenIn; this.scaledResolution = new ScaledResolution(this); + if (guiScreenIn != null) { + this.setIngameNotInFocus(); + ((GuiScreen) guiScreenIn).setWorldAndResolution(this, scaledResolution.getScaledWidth(), + scaledResolution.getScaledHeight()); + this.skipRenderWorld = false; + } else { + this.mcSoundHandler.resumeSounds(); + this.setIngameFocus(); + } + EagRuntime.getConfiguration().getHooks().callScreenChangedHook( + currentScreen != null ? currentScreen.getClass().getName() : null, scaledResolution.getScaledWidth(), + scaledResolution.getScaledHeight(), displayWidth, displayHeight, scaledResolution.getScaleFactor()); + } + + /** + * + Displays the ingame menu + */ + public void displayInGameMenu() { + if (this.currentScreen == null) { + this.displayGuiScreen(new GuiIngameMenu()); + } } private void drawSplashScreen(TextureManager textureManagerInstance) { @@ -692,6 +791,31 @@ public class Minecraft implements IThreadListener { this.updateDisplay(); } + private ItemStack func_181036_a(Item parItem, int parInt1, TileEntity parTileEntity) { + ItemStack itemstack = new ItemStack(parItem, 1, parInt1); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + parTileEntity.writeToNBT(nbttagcompound); + if (parItem == Items.skull && nbttagcompound.hasKey("Owner")) { + NBTTagCompound nbttagcompound2 = nbttagcompound.getCompoundTag("Owner"); + NBTTagCompound nbttagcompound3 = new NBTTagCompound(); + nbttagcompound3.setTag("SkullOwner", nbttagcompound2); + itemstack.setTagCompound(nbttagcompound3); + return itemstack; + } else { + itemstack.setTagInfo("BlockEntityTag", nbttagcompound); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + NBTTagList nbttaglist = new NBTTagList(); + nbttaglist.appendTag(new NBTTagString("(+NBT)")); + nbttagcompound1.setTag("Lore", nbttaglist); + itemstack.setTagInfo("display", nbttagcompound1); + return itemstack; + } + } + + public MusicTicker func_181535_r() { + return this.mcMusicTicker; + } + public void func_181536_a(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, int parInt7, int parInt8, int parInt9, int parInt10) { float f = 0.00390625F; @@ -713,108 +837,594 @@ public class Minecraft implements IThreadListener { Tessellator.getInstance().draw(); } - /**+ - * Sets the argument GuiScreen as the main (topmost visible) - * screen. + public void func_181537_a(boolean parFlag) { + this.field_181541_X = parFlag; + } + + private String func_181538_aA() { + return this.currentServerData != null ? "multiplayer" : "out_of_game"; + } + + public FrameTimer func_181539_aj() { + return this.field_181542_y; + } + + public boolean func_181540_al() { + return this.field_181541_X; + } + + public MusicTicker.MusicType getAmbientMusicType() { + return this.thePlayer != null ? (this.thePlayer.worldObj.provider instanceof WorldProviderHell + ? MusicTicker.MusicType.NETHER + : (this.thePlayer.worldObj.provider instanceof WorldProviderEnd + ? (BossStatus.bossName != null && BossStatus.statusBarTime > 0 ? MusicTicker.MusicType.END_BOSS + : MusicTicker.MusicType.END) + : (this.thePlayer.capabilities.isCreativeMode && this.thePlayer.capabilities.allowFlying + ? MusicTicker.MusicType.CREATIVE + : MusicTicker.MusicType.GAME))) + : MusicTicker.MusicType.MENU; + } + + public BlockRendererDispatcher getBlockRendererDispatcher() { + return this.blockRenderDispatcher; + } + + public ServerData getCurrentServerData() { + return this.currentServerData; + } + + public boolean getEnableFNAWSkins() { + boolean ret = this.gameSettings.enableFNAWSkins; + if (this.thePlayer != null) { + if (this.thePlayer.sendQueue.currentFNAWSkinForcedState) { + ret = true; + } else { + ret &= this.thePlayer.sendQueue.currentFNAWSkinAllowedState; + } + } + return ret; + } + + public ItemRenderer getItemRenderer() { + return this.itemRenderer; + } + + public LanguageManager getLanguageManager() { + return this.mcLanguageManager; + } + + public int getLimitFramerate() { + return this.theWorld == null && this.currentScreen != null ? 30 : this.gameSettings.limitFramerate; + } + + public ModelManager getModelManager() { + return modelManager; + } + + public NetHandlerPlayClient getNetHandler() { + return this.thePlayer != null ? this.thePlayer.sendQueue : null; + } + + public RenderItem getRenderItem() { + return this.renderItem; + } + + public RenderManager getRenderManager() { + return this.renderManager; + } + + public Entity getRenderViewEntity() { + return this.renderViewEntity; + } + + public IResourceManager getResourceManager() { + return this.mcResourceManager; + } + + public ResourcePackRepository getResourcePackRepository() { + return this.mcResourcePackRepository; + } + + /** + * + Returns the save loader that is currently being used */ - public void displayGuiScreen(GuiScreen guiScreenIn) { - if (this.currentScreen != null) { - this.currentScreen.onGuiClosed(); + public ISaveFormat getSaveLoader() { + return SingleplayerServerController.instance; + } + + public Session getSession() { + return this.session; + } + + public SoundHandler getSoundHandler() { + return this.mcSoundHandler; + } + + public TextureManager getTextureManager() { + return this.renderEngine; + } + + public TextureMap getTextureMapBlocks() { + return this.textureMapBlocks; + } + + public String getVersion() { + return this.launchedVersion; + } + + private void handlePlaceTouchEnd() { + if (placeTouchStartTime != -1l) { + int len = (int) (EagRuntime.steadyTimeMillis() - placeTouchStartTime); + if (len < 350l && !PointerInputAbstraction.isDraggingNotTouching()) { + if (objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectType.ENTITY) { + clickMouse(); + } else { + rightClickMouse(); + } + } + placeTouchStartTime = -1l; + } + } + + private void handlePlaceTouchStart() { + if (placeTouchStartTime == -1l) { + placeTouchStartTime = EagRuntime.steadyTimeMillis(); + } + } + + public void handleReconnectPacket(String redirectURI) { + this.reconnectURI = redirectURI; + } + + /** + * + Gets whether this is a demo or not. + */ + public final boolean isDemo() { + return EagRuntime.getConfiguration().isDemo(); + } + + public boolean isEnableProfanityFilter() { + return EagRuntime.getConfiguration().isForceProfanityFilter() || gameSettings.enableProfanityFilter; + } + + public boolean isFramerateLimitBelowMax() { + return (float) this.getLimitFramerate() < GameSettings.Options.FRAMERATE_LIMIT.getValueMax(); + } + + /** + * + Returns whether we're in full screen or not. + */ + public boolean isFullScreen() { + return Display.isFullscreen(); + } + + public boolean isGamePaused() { + return this.isGamePaused; + } + + public boolean isIntegratedServerRunning() { + return SingleplayerServerController.isWorldRunning(); + } + + public boolean isJava64bit() { + return this.jvm64bit; + } + + private boolean isMiningTouch() { + if (mineTouchStartTime == -1l) + return false; + long l = EagRuntime.steadyTimeMillis(); + return (placeTouchStartTime == -1l || (l - placeTouchStartTime) >= 350l) && (l - mineTouchStartTime) >= 350l; + } + + /** + * + Returns true if there is only one player playing, and the current server is + * the integrated one. + */ + public boolean isSingleplayer() { + return SingleplayerServerController.isWorldRunning(); + } + + /** + * + Returns whether snooping is enabled or not. + */ + public boolean isSnooperEnabled() { + return this.gameSettings.snooperEnabled; + } + + public boolean isUnicode() { + return this.mcLanguageManager.isCurrentLocaleUnicode() || this.gameSettings.forceUnicodeFont; + } + + /** + * + Arguments: World foldername, World ingame name, WorldSettings + */ + public void launchIntegratedServer(String folderName, String worldName, WorldSettings worldSettingsIn) { + this.loadWorld((WorldClient) null); + renderManager.setEnableFNAWSkins(this.gameSettings.enableFNAWSkins); + session.reset(); + EaglerProfile.clearServerSkinOverride(); + PauseMenuCustomizeState.reset(); + SingleplayerServerController.launchEaglercraftServer(folderName, gameSettings.difficulty.getDifficultyId(), + Math.max(gameSettings.renderDistanceChunks, 2), worldSettingsIn); + EagRuntime.setMCServerWindowGlobal("singleplayer"); + this.displayGuiScreen(new GuiScreenIntegratedServerBusy( + new GuiScreenSingleplayerConnecting(new GuiMainMenu(), "Connecting to " + folderName), + "singleplayer.busy.startingIntegratedServer", "singleplayer.failed.startingIntegratedServer", + () -> SingleplayerServerController.isWorldReady(), (t, u) -> { + Minecraft.this.displayGuiScreen(GuiScreenIntegratedServerBusy.createException(new GuiMainMenu(), + ((GuiScreenIntegratedServerBusy) t).failMessage, u)); + })); + } + + /** + * + unloads the current world first + */ + public void loadWorld(WorldClient worldClientIn) { + this.loadWorld(worldClientIn, ""); + } + + /** + * + unloads the current world first + */ + public void loadWorld(WorldClient worldClientIn, String loadingMessage) { + if (worldClientIn == null) { + NetHandlerPlayClient nethandlerplayclient = this.getNetHandler(); + if (nethandlerplayclient != null) { + nethandlerplayclient.cleanup(); + } + session.reset(); + EaglerProfile.clearServerSkinOverride(); + PauseMenuCustomizeState.reset(); + ClientUUIDLoadingCache.flushRequestCache(); + WebViewOverlayController.setPacketSendCallback(null); + + this.guiAchievement.clearAchievements(); + this.entityRenderer.getMapItemRenderer().clearLoadedMaps(); } - if (guiScreenIn == null && this.theWorld == null) { - guiScreenIn = new GuiMainMenu(); - } else if (guiScreenIn == null && this.thePlayer.getHealth() <= 0.0F) { - guiScreenIn = new GuiGameOver(); + this.renderViewEntity = null; + this.myNetworkManager = null; + if (this.loadingScreen != null) { + this.loadingScreen.resetProgressAndMessage(loadingMessage); + this.loadingScreen.displayLoadingString(""); } - if (guiScreenIn instanceof GuiMainMenu) { - this.gameSettings.showDebugInfo = false; - this.ingameGUI.getChatGUI().clearChatMessages(); + if (worldClientIn == null && this.theWorld != null) { + this.mcResourcePackRepository.func_148529_f(); + this.ingameGUI.func_181029_i(); + this.setServerData((ServerData) null); + this.integratedServerIsRunning = false; } - this.currentScreen = (GuiScreen) guiScreenIn; - this.scaledResolution = new ScaledResolution(this); - if (guiScreenIn != null) { - this.setIngameNotInFocus(); - ((GuiScreen) guiScreenIn).setWorldAndResolution(this, scaledResolution.getScaledWidth(), - scaledResolution.getScaledHeight()); - this.skipRenderWorld = false; + this.mcSoundHandler.stopSounds(); + this.theWorld = worldClientIn; + if (worldClientIn != null) { + if (this.renderGlobal != null) { + this.renderGlobal.setWorldAndLoadRenderers(worldClientIn); + } + + if (this.effectRenderer != null) { + this.effectRenderer.clearEffects(worldClientIn); + } + + if (this.thePlayer == null) { + this.thePlayer = this.playerController.func_178892_a(worldClientIn, new StatFileWriter()); + this.playerController.flipPlayer(this.thePlayer); + } + + this.thePlayer.preparePlayerToSpawn(); + worldClientIn.spawnEntityInWorld(this.thePlayer); + this.thePlayer.movementInput = new MovementInputFromOptions(this.gameSettings); + this.playerController.setPlayerCapabilities(this.thePlayer); + this.renderViewEntity = this.thePlayer; } else { - this.mcSoundHandler.resumeSounds(); - this.setIngameFocus(); + this.thePlayer = null; } + + System.gc(); + this.systemTime = 0L; + } + + /** + * + Called when user clicked he's mouse middle button (pick block) + */ + public void middleClickMouse() { + if (this.objectMouseOver != null) { + boolean flag = this.thePlayer.capabilities.isCreativeMode; + int i = 0; + boolean flag1 = false; + TileEntity tileentity = null; + Object object; + if (this.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + BlockPos blockpos = this.objectMouseOver.getBlockPos(); + Block block = this.theWorld.getBlockState(blockpos).getBlock(); + if (block.getMaterial() == Material.air) { + return; + } + + object = block.getItem(this.theWorld, blockpos); + if (object == null) { + return; + } + + if (flag && GuiScreen.isCtrlKeyDown()) { + tileentity = this.theWorld.getTileEntity(blockpos); + } + + Block block1 = object instanceof ItemBlock && !block.isFlowerPot() + ? Block.getBlockFromItem((Item) object) + : block; + i = block1.getDamageValue(this.theWorld, blockpos); + flag1 = ((Item) object).getHasSubtypes(); + } else { + if (this.objectMouseOver.typeOfHit != MovingObjectPosition.MovingObjectType.ENTITY + || this.objectMouseOver.entityHit == null || !flag) { + return; + } + + if (this.objectMouseOver.entityHit instanceof EntityPainting) { + object = Items.painting; + } else if (this.objectMouseOver.entityHit instanceof EntityLeashKnot) { + object = Items.lead; + } else if (this.objectMouseOver.entityHit instanceof EntityItemFrame) { + EntityItemFrame entityitemframe = (EntityItemFrame) this.objectMouseOver.entityHit; + ItemStack itemstack = entityitemframe.getDisplayedItem(); + if (itemstack == null) { + object = Items.item_frame; + } else { + object = itemstack.getItem(); + i = itemstack.getMetadata(); + flag1 = true; + } + } else if (this.objectMouseOver.entityHit instanceof EntityMinecart) { + EntityMinecart entityminecart = (EntityMinecart) this.objectMouseOver.entityHit; + switch (entityminecart.getMinecartType()) { + case FURNACE: + object = Items.furnace_minecart; + break; + case CHEST: + object = Items.chest_minecart; + break; + case TNT: + object = Items.tnt_minecart; + break; + case HOPPER: + object = Items.hopper_minecart; + break; + case COMMAND_BLOCK: + object = Items.command_block_minecart; + break; + default: + object = Items.minecart; + } + } else if (this.objectMouseOver.entityHit instanceof EntityBoat) { + object = Items.boat; + } else if (this.objectMouseOver.entityHit instanceof EntityArmorStand) { + object = Items.armor_stand; + } else { + object = Items.spawn_egg; + i = EntityList.getEntityID(this.objectMouseOver.entityHit); + flag1 = true; + if (!EntityList.entityEggs.containsKey(Integer.valueOf(i))) { + return; + } + } + } + + InventoryPlayer inventoryplayer = this.thePlayer.inventory; + if (tileentity == null) { + inventoryplayer.setCurrentItem((Item) object, i, flag1, flag); + } else { + ItemStack itemstack1 = this.func_181036_a((Item) object, i, tileentity); + inventoryplayer.setInventorySlotContents(inventoryplayer.currentItem, itemstack1); + } + + if (flag) { + int j = this.thePlayer.inventoryContainer.inventorySlots.size() - 9 + inventoryplayer.currentItem; + this.playerController.sendSlotPacket(inventoryplayer.getStackInSlot(inventoryplayer.currentItem), j); + } + + } + } + + private void processTouchMine() { + if ((currentScreen == null || currentScreen.allowUserInput) + && PointerInputAbstraction.isTouchingScreenNotButton()) { + if (PointerInputAbstraction.isDraggingNotTouching()) { + if (mineTouchStartTime != -1l) { + long l = EagRuntime.steadyTimeMillis(); + if ((placeTouchStartTime == -1l || (l - placeTouchStartTime) < 350l) + || (l - mineTouchStartTime) < 350l) { + mineTouchStartTime = -1l; + } + } + } else { + if (mineTouchStartTime == -1l) { + mineTouchStartTime = EagRuntime.steadyTimeMillis(); + } + } + } else { + mineTouchStartTime = -1l; + } + } + + public void refreshResources() { + GlStateManager.recompileShaders(); + + ArrayList arraylist = Lists.newArrayList(this.defaultResourcePacks); + + for (ResourcePackRepository.Entry resourcepackrepository$entry : this.mcResourcePackRepository + .getRepositoryEntries()) { + arraylist.add(resourcepackrepository$entry.getResourcePack()); + } + + if (this.mcResourcePackRepository.getResourcePackInstance() != null) { + arraylist.add(this.mcResourcePackRepository.getResourcePackInstance()); + } + + try { + this.mcResourceManager.reloadResources(arraylist); + } catch (RuntimeException runtimeexception) { + logger.info("Caught error stitching, removing all assigned resourcepacks"); + logger.info(runtimeexception); + arraylist.clear(); + arraylist.addAll(this.defaultResourcePacks); + this.mcResourcePackRepository.setRepositories(Collections.emptyList()); + this.mcResourceManager.reloadResources(arraylist); + this.gameSettings.resourcePacks.clear(); + this.gameSettings.field_183018_l.clear(); + this.gameSettings.saveOptions(); + } + + ShaderSource.clearCache(); + GuiMainMenu.doResourceReloadHack(); + + this.mcLanguageManager.parseLanguageMetadata(arraylist); + if (this.renderGlobal != null) { + this.renderGlobal.loadRenderers(); + } + + } + + private void registerMetadataSerializers() { + this.metadataSerializer_.registerMetadataSectionType(new TextureMetadataSectionSerializer(), + TextureMetadataSection.class); + this.metadataSerializer_.registerMetadataSectionType(new FontMetadataSectionSerializer(), + FontMetadataSection.class); + this.metadataSerializer_.registerMetadataSectionType(new AnimationMetadataSectionSerializer(), + AnimationMetadataSection.class); + this.metadataSerializer_.registerMetadataSectionType(new PackMetadataSectionSerializer(), + PackMetadataSection.class); + this.metadataSerializer_.registerMetadataSectionType(new LanguageMetadataSectionSerializer(), + LanguageMetadataSection.class); + } + + /** + * + Called to resize the current screen. + */ + private void resize(int width, int height) { + this.displayWidth = Math.max(1, width); + this.displayHeight = Math.max(1, height); + this.scaledResolution = new ScaledResolution(this); + if (this.currentScreen != null) { + this.currentScreen.onResize(this, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight()); + } + + this.loadingScreen = new LoadingScreenRenderer(this); + + if (voiceOverlay != null) { + voiceOverlay.setResolution(scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight()); + } + if (notifRenderer != null) { + notifRenderer.setResolution(this, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), + scaledResolution.getScaleFactor()); + } + EagRuntime.getConfiguration().getHooks().callScreenChangedHook( currentScreen != null ? currentScreen.getClass().getName() : null, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), displayWidth, displayHeight, scaledResolution.getScaleFactor()); } - public void shutdownIntegratedServer(GuiScreen cont) { - if (SingleplayerServerController.shutdownEaglercraftServer() - || SingleplayerServerController.getStatusState() == IntegratedServerState.WORLD_UNLOADING) { - displayGuiScreen(new GuiScreenIntegratedServerBusy(cont, "singleplayer.busy.stoppingIntegratedServer", - "singleplayer.failed.stoppingIntegratedServer", SingleplayerServerController::isReady)); - } else { - displayGuiScreen(cont); - } - } - - /**+ - * Checks for an OpenGL error. If there is one, prints the error - * ID and error string. + /** + * + Called when user clicked he's mouse right button (place) */ - public void checkGLError(String message) { - if (this.enableGLErrorChecking) { - int i = EaglercraftGPU.glGetError(); - if (i != 0) { - String s = EaglercraftGPU.gluErrorString(i); - logger.error("########## GL ERROR ##########"); - logger.error("@ " + message); - logger.error(i + ": " + s); - } + public void rightClickMouse() { + if (!this.playerController.func_181040_m()) { + this.rightClickDelayTimer = 4; + boolean flag = true; + ItemStack itemstack = this.thePlayer.inventory.getCurrentItem(); + if (this.objectMouseOver == null) { + logger.warn("Null returned as \'hitResult\', this shouldn\'t happen!"); + } else { + switch (this.objectMouseOver.typeOfHit) { + case ENTITY: + if (this.playerController.func_178894_a(this.thePlayer, this.objectMouseOver.entityHit, + this.objectMouseOver)) { + flag = false; + } else if (this.playerController.interactWithEntitySendPacket(this.thePlayer, + this.objectMouseOver.entityHit)) { + flag = false; + } + break; + case BLOCK: + BlockPos blockpos = this.objectMouseOver.getBlockPos(); + if (this.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { + int i = itemstack != null ? itemstack.stackSize : 0; + if (this.playerController.onPlayerRightClick(this.thePlayer, this.theWorld, itemstack, blockpos, + this.objectMouseOver.sideHit, this.objectMouseOver.hitVec)) { + flag = false; + this.thePlayer.swingItem(); + } - } - } + if (itemstack == null) { + return; + } - /**+ - * Shuts down the minecraft applet by stopping the resource - * downloads, and clearing up GL stuff; called when the - * application (or web page) is exited. - */ - public void shutdownMinecraftApplet() { - try { - logger.info("Stopping!"); - - try { - this.loadWorld((WorldClient) null); - } catch (Throwable var5) { - ; - } - - this.mcSoundHandler.unloadSounds(); - if (SingleplayerServerController.isWorldRunning()) { - SingleplayerServerController.shutdownEaglercraftServer(); - while (SingleplayerServerController.getStatusState() == IntegratedServerState.WORLD_UNLOADING) { - EagUtils.sleep(50l); - SingleplayerServerController.runTick(); + if (itemstack.stackSize == 0) { + this.thePlayer.inventory.mainInventory[this.thePlayer.inventory.currentItem] = null; + } else if (itemstack.stackSize != i || this.playerController.isInCreativeMode()) { + this.entityRenderer.itemRenderer.resetEquippedProgress(); + } + } } } - if (SingleplayerServerController.isIntegratedServerWorkerAlive() - && SingleplayerServerController.canKillWorker()) { - SingleplayerServerController.killWorker(); - EagUtils.sleep(50l); - } - } finally { - EagRuntime.destroy(); - if (!this.hasCrashed) { - EagRuntime.exit(); + + if (flag) { + ItemStack itemstack1 = this.thePlayer.inventory.getCurrentItem(); + if (itemstack1 != null + && this.playerController.sendUseItem(this.thePlayer, this.theWorld, itemstack1)) { + this.entityRenderer.itemRenderer.resetEquippedProgress2(); + } } } } - /**+ - * Called repeatedly from run() + public void run() { + this.running = true; + + try { + this.startGame(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Initializing game"); + crashreport.makeCategory("Initialization"); + this.displayCrashReport(this.addGraphicsAndWorldToCrashReport(crashreport)); + return; + } + + try { + while (true) { + if (!this.running) { + break; + } + + if (!this.hasCrashed || this.crashReporter == null) { + this.runGameLoop(); + continue; + } + + this.displayCrashReport(this.crashReporter); + } + } catch (MinecraftError var12) { + // ?? + } catch (ReportedException reportedexception) { + this.addGraphicsAndWorldToCrashReport(reportedexception.getCrashReport()); + logger.fatal("Reported exception thrown!", reportedexception); + this.displayCrashReport(reportedexception.getCrashReport()); + } catch (Throwable throwable1) { + CrashReport crashreport1 = this + .addGraphicsAndWorldToCrashReport(new CrashReport("Unexpected error", throwable1)); + logger.fatal("Unreported exception thrown!", throwable1); + this.displayCrashReport(crashreport1); + } finally { + this.shutdownMinecraftApplet(); + } + + } + + /** + * + Called repeatedly from run() */ private void runGameLoop() throws IOException { long i = System.nanoTime(); @@ -913,245 +1523,8 @@ public class Minecraft implements IThreadListener { Mouse.tickCursorShape(); } - public void updateDisplay() { - if (Display.isVSyncSupported()) { - Display.setVSync(this.gameSettings.enableVsync); - } else { - this.gameSettings.enableVsync = false; - } - Display.update(); - this.checkWindowResize(); - } - - protected void checkWindowResize() { - float dpiFetch = -1.0f; - if (!this.fullscreen - && (Display.wasResized() || (dpiFetch = Math.max(Display.getDPI(), 1.0f)) != this.displayDPI)) { - int i = this.displayWidth; - int j = this.displayHeight; - float f = this.displayDPI; - this.displayWidth = Display.getWidth(); - this.displayHeight = Display.getHeight(); - this.displayDPI = dpiFetch == -1.0f ? Math.max(Display.getDPI(), 1.0f) : dpiFetch; - if (this.displayWidth != i || this.displayHeight != j || this.displayDPI != f) { - if (this.displayWidth <= 0) { - this.displayWidth = 1; - } - - if (this.displayHeight <= 0) { - this.displayHeight = 1; - } - - this.resize(this.displayWidth, this.displayHeight); - } - } - - } - - public int getLimitFramerate() { - return this.theWorld == null && this.currentScreen != null ? 30 : this.gameSettings.limitFramerate; - } - - public boolean isFramerateLimitBelowMax() { - return (float) this.getLimitFramerate() < GameSettings.Options.FRAMERATE_LIMIT.getValueMax(); - } - - /**+ - * Called when the window is closing. Sets 'running' to false - * which allows the game loop to exit cleanly. - */ - public void shutdown() { - this.running = false; - } - - /**+ - * Will set the focus to ingame if the Minecraft window is the - * active with focus. Also clears any GUI screen currently - * displayed - */ - public void setIngameFocus() { - boolean touch = PointerInputAbstraction.isTouchMode(); - if (touch || Display.isActive()) { - if (!this.inGameHasFocus) { - this.inGameHasFocus = true; - if (!touch && mouseGrabSupported) { - this.mouseHelper.grabMouseCursor(); - } - this.displayGuiScreen((GuiScreen) null); - this.leftClickCounter = 10000; - } - } - } - - /**+ - * Resets the player keystate, disables the ingame focus, and - * ungrabs the mouse cursor. - */ - public void setIngameNotInFocus() { - if (this.inGameHasFocus) { - KeyBinding.unPressAllKeys(); - this.inGameHasFocus = false; - if (!PointerInputAbstraction.isTouchMode() && mouseGrabSupported) { - this.mouseHelper.ungrabMouseCursor(); - } - } - } - - /**+ - * Displays the ingame menu - */ - public void displayInGameMenu() { - if (this.currentScreen == null) { - this.displayGuiScreen(new GuiIngameMenu()); - } - } - - private void sendClickBlockToController(boolean leftClick) { - if (!leftClick) { - this.leftClickCounter = 0; - } - - if (this.leftClickCounter <= 0 && !this.thePlayer.isUsingItem()) { - if (leftClick && this.objectMouseOver != null - && this.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - BlockPos blockpos = this.objectMouseOver.getBlockPos(); - if (this.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air - && this.playerController.onPlayerDamageBlock(blockpos, this.objectMouseOver.sideHit)) { - this.effectRenderer.addBlockHitEffects(blockpos, this.objectMouseOver.sideHit); - this.thePlayer.swingItem(); - } - - } else { - this.playerController.resetBlockRemoving(); - } - } - } - - private void clickMouse() { - if (this.leftClickCounter <= 0) { - this.thePlayer.swingItem(); - if (this.objectMouseOver == null) { - logger.error("Null returned as \'hitResult\', this shouldn\'t happen!"); - if (this.playerController.isNotCreative()) { - this.leftClickCounter = 10; - } - - } else { - switch (this.objectMouseOver.typeOfHit) { - case ENTITY: - this.playerController.attackEntity(this.thePlayer, this.objectMouseOver.entityHit); - break; - case BLOCK: - BlockPos blockpos = this.objectMouseOver.getBlockPos(); - if (this.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { - this.playerController.clickBlock(blockpos, this.objectMouseOver.sideHit); - break; - } - case MISS: - default: - if (this.playerController.isNotCreative()) { - this.leftClickCounter = 10; - } - } - - } - } - } - - /**+ - * Called when user clicked he's mouse right button (place) - */ - public void rightClickMouse() { - if (!this.playerController.func_181040_m()) { - this.rightClickDelayTimer = 4; - boolean flag = true; - ItemStack itemstack = this.thePlayer.inventory.getCurrentItem(); - if (this.objectMouseOver == null) { - logger.warn("Null returned as \'hitResult\', this shouldn\'t happen!"); - } else { - switch (this.objectMouseOver.typeOfHit) { - case ENTITY: - if (this.playerController.func_178894_a(this.thePlayer, this.objectMouseOver.entityHit, - this.objectMouseOver)) { - flag = false; - } else if (this.playerController.interactWithEntitySendPacket(this.thePlayer, - this.objectMouseOver.entityHit)) { - flag = false; - } - break; - case BLOCK: - BlockPos blockpos = this.objectMouseOver.getBlockPos(); - if (this.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { - int i = itemstack != null ? itemstack.stackSize : 0; - if (this.playerController.onPlayerRightClick(this.thePlayer, this.theWorld, itemstack, blockpos, - this.objectMouseOver.sideHit, this.objectMouseOver.hitVec)) { - flag = false; - this.thePlayer.swingItem(); - } - - if (itemstack == null) { - return; - } - - if (itemstack.stackSize == 0) { - this.thePlayer.inventory.mainInventory[this.thePlayer.inventory.currentItem] = null; - } else if (itemstack.stackSize != i || this.playerController.isInCreativeMode()) { - this.entityRenderer.itemRenderer.resetEquippedProgress(); - } - } - } - } - - if (flag) { - ItemStack itemstack1 = this.thePlayer.inventory.getCurrentItem(); - if (itemstack1 != null - && this.playerController.sendUseItem(this.thePlayer, this.theWorld, itemstack1)) { - this.entityRenderer.itemRenderer.resetEquippedProgress2(); - } - } - - } - } - - /**+ - * Toggles fullscreen mode. - */ - public void toggleFullscreen() { - Display.toggleFullscreen(); - } - - /**+ - * Called to resize the current screen. - */ - private void resize(int width, int height) { - this.displayWidth = Math.max(1, width); - this.displayHeight = Math.max(1, height); - this.scaledResolution = new ScaledResolution(this); - if (this.currentScreen != null) { - this.currentScreen.onResize(this, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight()); - } - - this.loadingScreen = new LoadingScreenRenderer(this); - - if (voiceOverlay != null) { - voiceOverlay.setResolution(scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight()); - } - if (notifRenderer != null) { - notifRenderer.setResolution(this, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), - scaledResolution.getScaleFactor()); - } - - EagRuntime.getConfiguration().getHooks().callScreenChangedHook( - currentScreen != null ? currentScreen.getClass().getName() : null, scaledResolution.getScaledWidth(), - scaledResolution.getScaledHeight(), displayWidth, displayHeight, scaledResolution.getScaleFactor()); - } - - public MusicTicker func_181535_r() { - return this.mcMusicTicker; - } - - /**+ - * Runs the current tick. + /** + * + Runs the current tick. */ public void runTick() throws IOException { if (this.rightClickDelayTimer > 0) { @@ -1347,7 +1720,7 @@ public class Minecraft implements IThreadListener { int j = Mouse.getEventDWheel(); if (j != 0) { if (this.isZoomKey) { - this.adjustedZoomValue = MathHelper.clamp_float(adjustedZoomValue - j * 4.0f, 5.0f, + this.adjustedZoomValue = MathHelper.clamp_float(adjustedZoomValue - j * 4.0f, 4.0f, 32.0f); } else if (this.thePlayer.isSpectator()) { j = j < 0 ? -1 : 1; @@ -1699,9 +2072,8 @@ public class Minecraft implements IThreadListener { ingameGUI.getChatGUI().printChatMessage((new ChatComponentText(pfx + " Click: ")) .appendSibling((new ChatComponentText("" + EnumChatFormatting.GREEN + EnumChatFormatting.UNDERLINE + EaglerXBungeeVersion.getPluginButton())) - .setChatStyle((new ChatStyle()).setChatClickEvent( - new ClickEvent(ClickEvent.Action.EAGLER_PLUGIN_DOWNLOAD, - "plugin_download.zip"))))); + .setChatStyle((new ChatStyle()).setChatClickEvent(new ClickEvent( + ClickEvent.Action.EAGLER_PLUGIN_DOWNLOAD, "plugin_download.zip"))))); ingameGUI.getChatGUI().printChatMessage( new ChatComponentText(pfx + " ---------------------------------------")); } @@ -1752,163 +2124,37 @@ public class Minecraft implements IThreadListener { this.systemTime = getSystemTime(); } - private long placeTouchStartTime = -1l; - private long mineTouchStartTime = -1l; - private boolean wasMiningTouch = false; + public ListenableFuture scheduleResourcesRefresh() { + return this.addScheduledTaskFuture(new Runnable() { + public void run() { + Minecraft.this.loadingScreen.eaglerShow(I18n.format("resourcePack.load.refreshing"), + I18n.format("resourcePack.load.pleaseWait")); + Minecraft.this.refreshResources(); + } + }); + } - private void processTouchMine() { - if ((currentScreen == null || currentScreen.allowUserInput) - && PointerInputAbstraction.isTouchingScreenNotButton()) { - if (PointerInputAbstraction.isDraggingNotTouching()) { - if (mineTouchStartTime != -1l) { - long l = EagRuntime.steadyTimeMillis(); - if ((placeTouchStartTime == -1l || (l - placeTouchStartTime) < 350l) - || (l - mineTouchStartTime) < 350l) { - mineTouchStartTime = -1l; - } + private void sendClickBlockToController(boolean leftClick) { + if (!leftClick) { + this.leftClickCounter = 0; + } + + if (this.leftClickCounter <= 0 && !this.thePlayer.isUsingItem()) { + if (leftClick && this.objectMouseOver != null + && this.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + BlockPos blockpos = this.objectMouseOver.getBlockPos(); + if (this.theWorld.getBlockState(blockpos).getBlock().getMaterial() != Material.air + && this.playerController.onPlayerDamageBlock(blockpos, this.objectMouseOver.sideHit)) { + this.effectRenderer.addBlockHitEffects(blockpos, this.objectMouseOver.sideHit); + this.thePlayer.swingItem(); } + } else { - if (mineTouchStartTime == -1l) { - mineTouchStartTime = EagRuntime.steadyTimeMillis(); - } + this.playerController.resetBlockRemoving(); } - } else { - mineTouchStartTime = -1l; } } - private boolean isMiningTouch() { - if (mineTouchStartTime == -1l) - return false; - long l = EagRuntime.steadyTimeMillis(); - return (placeTouchStartTime == -1l || (l - placeTouchStartTime) >= 350l) && (l - mineTouchStartTime) >= 350l; - } - - private void handlePlaceTouchStart() { - if (placeTouchStartTime == -1l) { - placeTouchStartTime = EagRuntime.steadyTimeMillis(); - } - } - - private void handlePlaceTouchEnd() { - if (placeTouchStartTime != -1l) { - int len = (int) (EagRuntime.steadyTimeMillis() - placeTouchStartTime); - if (len < 350l && !PointerInputAbstraction.isDraggingNotTouching()) { - if (objectMouseOver != null && objectMouseOver.typeOfHit == MovingObjectType.ENTITY) { - clickMouse(); - } else { - rightClickMouse(); - } - } - placeTouchStartTime = -1l; - } - } - - public void togglePerspective() { - ++this.gameSettings.thirdPersonView; - if (this.gameSettings.thirdPersonView > 2) { - this.gameSettings.thirdPersonView = 0; - } - - if (this.gameSettings.thirdPersonView == 0) { - this.entityRenderer.loadEntityShader(this.getRenderViewEntity()); - } else if (this.gameSettings.thirdPersonView == 1) { - this.entityRenderer.loadEntityShader((Entity) null); - } - - this.renderGlobal.setDisplayListEntitiesDirty(); - } - - /**+ - * Arguments: World foldername, World ingame name, WorldSettings - */ - public void launchIntegratedServer(String folderName, String worldName, WorldSettings worldSettingsIn) { - this.loadWorld((WorldClient) null); - renderManager.setEnableFNAWSkins(this.gameSettings.enableFNAWSkins); - session.reset(); - EaglerProfile.clearServerSkinOverride(); - PauseMenuCustomizeState.reset(); - SingleplayerServerController.launchEaglercraftServer(folderName, gameSettings.difficulty.getDifficultyId(), - Math.max(gameSettings.renderDistanceChunks, 2), worldSettingsIn); - EagRuntime.setMCServerWindowGlobal("singleplayer"); - this.displayGuiScreen(new GuiScreenIntegratedServerBusy( - new GuiScreenSingleplayerConnecting(new GuiMainMenu(), "Connecting to " + folderName), - "singleplayer.busy.startingIntegratedServer", "singleplayer.failed.startingIntegratedServer", - () -> SingleplayerServerController.isWorldReady(), (t, u) -> { - Minecraft.this.displayGuiScreen(GuiScreenIntegratedServerBusy.createException(new GuiMainMenu(), - ((GuiScreenIntegratedServerBusy) t).failMessage, u)); - })); - } - - /**+ - * unloads the current world first - */ - public void loadWorld(WorldClient worldClientIn) { - this.loadWorld(worldClientIn, ""); - } - - /**+ - * unloads the current world first - */ - public void loadWorld(WorldClient worldClientIn, String loadingMessage) { - if (worldClientIn == null) { - NetHandlerPlayClient nethandlerplayclient = this.getNetHandler(); - if (nethandlerplayclient != null) { - nethandlerplayclient.cleanup(); - } - session.reset(); - EaglerProfile.clearServerSkinOverride(); - PauseMenuCustomizeState.reset(); - ClientUUIDLoadingCache.flushRequestCache(); - WebViewOverlayController.setPacketSendCallback(null); - - this.guiAchievement.clearAchievements(); - this.entityRenderer.getMapItemRenderer().clearLoadedMaps(); - } - - this.renderViewEntity = null; - this.myNetworkManager = null; - if (this.loadingScreen != null) { - this.loadingScreen.resetProgressAndMessage(loadingMessage); - this.loadingScreen.displayLoadingString(""); - } - - if (worldClientIn == null && this.theWorld != null) { - this.mcResourcePackRepository.func_148529_f(); - this.ingameGUI.func_181029_i(); - this.setServerData((ServerData) null); - this.integratedServerIsRunning = false; - } - - this.mcSoundHandler.stopSounds(); - this.theWorld = worldClientIn; - if (worldClientIn != null) { - if (this.renderGlobal != null) { - this.renderGlobal.setWorldAndLoadRenderers(worldClientIn); - } - - if (this.effectRenderer != null) { - this.effectRenderer.clearEffects(worldClientIn); - } - - if (this.thePlayer == null) { - this.thePlayer = this.playerController.func_178892_a(worldClientIn, new StatFileWriter()); - this.playerController.flipPlayer(this.thePlayer); - } - - this.thePlayer.preparePlayerToSpawn(); - worldClientIn.spawnEntityInWorld(this.thePlayer); - this.thePlayer.movementInput = new MovementInputFromOptions(this.gameSettings); - this.playerController.setPlayerCapabilities(this.thePlayer); - this.renderViewEntity = this.thePlayer; - } else { - this.thePlayer = null; - } - - System.gc(); - this.systemTime = 0L; - } - public void setDimensionAndSpawnPlayer(int dimension) { this.theWorld.setInitialSpawnLocation(); this.theWorld.removeAllEntities(); @@ -1940,415 +2186,36 @@ public class Minecraft implements IThreadListener { } - /**+ - * Gets whether this is a demo or not. + /** + * + Will set the focus to ingame if the Minecraft window is the active with + * focus. Also clears any GUI screen currently displayed */ - public final boolean isDemo() { - return EagRuntime.getConfiguration().isDemo(); - } - - public NetHandlerPlayClient getNetHandler() { - return this.thePlayer != null ? this.thePlayer.sendQueue : null; - } - - public static boolean isGuiEnabled() { - return theMinecraft == null || !theMinecraft.gameSettings.hideGUI; - } - - public static boolean isFancyGraphicsEnabled() { - return theMinecraft != null && theMinecraft.gameSettings.fancyGraphics; - } - - /**+ - * Returns if ambient occlusion is enabled - */ - public static boolean isAmbientOcclusionEnabled() { - if (theMinecraft == null) - return false; - GameSettings g = theMinecraft.gameSettings; - return g.ambientOcclusion != 0 && !g.shadersAODisable; - } - - /**+ - * Called when user clicked he's mouse middle button (pick - * block) - */ - public void middleClickMouse() { - if (this.objectMouseOver != null) { - boolean flag = this.thePlayer.capabilities.isCreativeMode; - int i = 0; - boolean flag1 = false; - TileEntity tileentity = null; - Object object; - if (this.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - BlockPos blockpos = this.objectMouseOver.getBlockPos(); - Block block = this.theWorld.getBlockState(blockpos).getBlock(); - if (block.getMaterial() == Material.air) { - return; - } - - object = block.getItem(this.theWorld, blockpos); - if (object == null) { - return; - } - - if (flag && GuiScreen.isCtrlKeyDown()) { - tileentity = this.theWorld.getTileEntity(blockpos); - } - - Block block1 = object instanceof ItemBlock && !block.isFlowerPot() - ? Block.getBlockFromItem((Item) object) - : block; - i = block1.getDamageValue(this.theWorld, blockpos); - flag1 = ((Item) object).getHasSubtypes(); - } else { - if (this.objectMouseOver.typeOfHit != MovingObjectPosition.MovingObjectType.ENTITY - || this.objectMouseOver.entityHit == null || !flag) { - return; - } - - if (this.objectMouseOver.entityHit instanceof EntityPainting) { - object = Items.painting; - } else if (this.objectMouseOver.entityHit instanceof EntityLeashKnot) { - object = Items.lead; - } else if (this.objectMouseOver.entityHit instanceof EntityItemFrame) { - EntityItemFrame entityitemframe = (EntityItemFrame) this.objectMouseOver.entityHit; - ItemStack itemstack = entityitemframe.getDisplayedItem(); - if (itemstack == null) { - object = Items.item_frame; - } else { - object = itemstack.getItem(); - i = itemstack.getMetadata(); - flag1 = true; - } - } else if (this.objectMouseOver.entityHit instanceof EntityMinecart) { - EntityMinecart entityminecart = (EntityMinecart) this.objectMouseOver.entityHit; - switch (entityminecart.getMinecartType()) { - case FURNACE: - object = Items.furnace_minecart; - break; - case CHEST: - object = Items.chest_minecart; - break; - case TNT: - object = Items.tnt_minecart; - break; - case HOPPER: - object = Items.hopper_minecart; - break; - case COMMAND_BLOCK: - object = Items.command_block_minecart; - break; - default: - object = Items.minecart; - } - } else if (this.objectMouseOver.entityHit instanceof EntityBoat) { - object = Items.boat; - } else if (this.objectMouseOver.entityHit instanceof EntityArmorStand) { - object = Items.armor_stand; - } else { - object = Items.spawn_egg; - i = EntityList.getEntityID(this.objectMouseOver.entityHit); - flag1 = true; - if (!EntityList.entityEggs.containsKey(Integer.valueOf(i))) { - return; - } - } - } - - InventoryPlayer inventoryplayer = this.thePlayer.inventory; - if (tileentity == null) { - inventoryplayer.setCurrentItem((Item) object, i, flag1, flag); - } else { - ItemStack itemstack1 = this.func_181036_a((Item) object, i, tileentity); - inventoryplayer.setInventorySlotContents(inventoryplayer.currentItem, itemstack1); - } - - if (flag) { - int j = this.thePlayer.inventoryContainer.inventorySlots.size() - 9 + inventoryplayer.currentItem; - this.playerController.sendSlotPacket(inventoryplayer.getStackInSlot(inventoryplayer.currentItem), j); - } - - } - } - - private ItemStack func_181036_a(Item parItem, int parInt1, TileEntity parTileEntity) { - ItemStack itemstack = new ItemStack(parItem, 1, parInt1); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - parTileEntity.writeToNBT(nbttagcompound); - if (parItem == Items.skull && nbttagcompound.hasKey("Owner")) { - NBTTagCompound nbttagcompound2 = nbttagcompound.getCompoundTag("Owner"); - NBTTagCompound nbttagcompound3 = new NBTTagCompound(); - nbttagcompound3.setTag("SkullOwner", nbttagcompound2); - itemstack.setTagCompound(nbttagcompound3); - return itemstack; - } else { - itemstack.setTagInfo("BlockEntityTag", nbttagcompound); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - NBTTagList nbttaglist = new NBTTagList(); - nbttaglist.appendTag(new NBTTagString("(+NBT)")); - nbttagcompound1.setTag("Lore", nbttaglist); - itemstack.setTagInfo("display", nbttagcompound1); - return itemstack; - } - } - - /**+ - * adds core server Info (GL version , Texture pack, isModded, - * type), and the worldInfo to the crash report - */ - public CrashReport addGraphicsAndWorldToCrashReport(CrashReport theCrash) { - theCrash.getCategory().addCrashSectionCallable("Launched Version", new Callable() { - public String call() throws Exception { - return Minecraft.this.launchedVersion; - } - }); - theCrash.getCategory().addCrashSectionCallable("LWJGL", new Callable() { - public String call() { - return EagRuntime.getVersion(); - } - }); - theCrash.getCategory().addCrashSectionCallable("OpenGL", new Callable() { - public String call() { - return EaglercraftGPU.glGetString(7937) + " GL version " + EaglercraftGPU.glGetString(7938) + ", " - + EaglercraftGPU.glGetString(7936); - } - }); - theCrash.getCategory().addCrashSectionCallable("Is Eagler Shaders", new Callable() { - public String call() throws Exception { - return Minecraft.this.gameSettings.shaders ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("Is Dynamic Lights", new Callable() { - public String call() throws Exception { - return !Minecraft.this.gameSettings.shaders && Minecraft.this.gameSettings.enableDynamicLights ? "Yes" - : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("In Ext. Pipeline", new Callable() { - public String call() throws Exception { - return GlStateManager.isExtensionPipeline() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("GPU Shader5 Capable", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.checkShader5Capable() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("GPU TexStorage Capable", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.checkTexStorageCapable() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("GPU TextureLOD Capable", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.checkTextureLODCapable() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("GPU Instancing Capable", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.checkInstancingCapable() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("GPU VAO Capable", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.checkVAOCapable() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("Is Software VAOs", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.areVAOsEmulated() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("GPU Render-to-MipMap", new Callable() { - public String call() throws Exception { - return EaglercraftGPU.checkFBORenderMipmapCapable() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("Touch Mode", new Callable() { - public String call() throws Exception { - return PointerInputAbstraction.isTouchMode() ? "Yes" : "No"; - } - }); - theCrash.getCategory().addCrashSectionCallable("Is Modded", new Callable() { - public String call() throws Exception { - return "Definitely Not; You're an eagler"; - } - }); - theCrash.getCategory().addCrashSectionCallable("Type", new Callable() { - public String call() throws Exception { - return "Client (map_client.txt)"; - } - }); - theCrash.getCategory().addCrashSectionCallable("Resource Packs", new Callable() { - public String call() throws Exception { - StringBuilder stringbuilder = new StringBuilder(); - - for (String s : Minecraft.this.gameSettings.resourcePacks) { - if (stringbuilder.length() > 0) { - stringbuilder.append(", "); - } - - stringbuilder.append(s); - if (Minecraft.this.gameSettings.field_183018_l.contains(s)) { - stringbuilder.append(" (incompatible)"); - } - } - - return stringbuilder.toString(); - } - }); - theCrash.getCategory().addCrashSectionCallable("Current Language", new Callable() { - public String call() throws Exception { - return Minecraft.this.mcLanguageManager.getCurrentLanguage().toString(); - } - }); - theCrash.getCategory().addCrashSectionCallable("Profiler Position", new Callable() { - public String call() throws Exception { - return "N/A (disabled)"; - } - }); - if (this.theWorld != null) { - this.theWorld.addWorldInfoToCrashReport(theCrash); - } - - return theCrash; - } - - /**+ - * Return the singleton Minecraft instance for the game - */ - public static Minecraft getMinecraft() { - return theMinecraft; - } - - public ListenableFuture scheduleResourcesRefresh() { - return this.addScheduledTaskFuture(new Runnable() { - public void run() { - Minecraft.this.loadingScreen.eaglerShow(I18n.format("resourcePack.load.refreshing"), - I18n.format("resourcePack.load.pleaseWait")); - Minecraft.this.refreshResources(); - } - }); - } - - private String func_181538_aA() { - return this.currentServerData != null ? "multiplayer" : "out_of_game"; - } - - /**+ - * Returns whether snooping is enabled or not. - */ - public boolean isSnooperEnabled() { - return this.gameSettings.snooperEnabled; - } - - /**+ - * Set the current ServerData instance. - */ - public void setServerData(ServerData serverDataIn) { - this.currentServerData = serverDataIn; - EagRuntime.setMCServerWindowGlobal(serverDataIn != null ? serverDataIn.serverIP : null); - } - - public ServerData getCurrentServerData() { - return this.currentServerData; - } - - public boolean isIntegratedServerRunning() { - return SingleplayerServerController.isWorldRunning(); - } - - /**+ - * Returns true if there is only one player playing, and the - * current server is the integrated one. - */ - public boolean isSingleplayer() { - return SingleplayerServerController.isWorldRunning(); - } - - public static void stopIntegratedServer() { - - } - - /**+ - * Gets the system time in milliseconds. - */ - public static long getSystemTime() { - return EagRuntime.steadyTimeMillis(); - } - - /**+ - * Returns whether we're in full screen or not. - */ - public boolean isFullScreen() { - return Display.isFullscreen(); - } - - public Session getSession() { - return this.session; - } - - public TextureManager getTextureManager() { - return this.renderEngine; - } - - public IResourceManager getResourceManager() { - return this.mcResourceManager; - } - - public ResourcePackRepository getResourcePackRepository() { - return this.mcResourcePackRepository; - } - - public LanguageManager getLanguageManager() { - return this.mcLanguageManager; - } - - public TextureMap getTextureMapBlocks() { - return this.textureMapBlocks; - } - - public boolean isJava64bit() { - return this.jvm64bit; - } - - public boolean isGamePaused() { - return this.isGamePaused; - } - - public SoundHandler getSoundHandler() { - return this.mcSoundHandler; - } - - public MusicTicker.MusicType getAmbientMusicType() { - return this.thePlayer != null ? (this.thePlayer.worldObj.provider instanceof WorldProviderHell - ? MusicTicker.MusicType.NETHER - : (this.thePlayer.worldObj.provider instanceof WorldProviderEnd - ? (BossStatus.bossName != null && BossStatus.statusBarTime > 0 ? MusicTicker.MusicType.END_BOSS - : MusicTicker.MusicType.END) - : (this.thePlayer.capabilities.isCreativeMode && this.thePlayer.capabilities.allowFlying - ? MusicTicker.MusicType.CREATIVE - : MusicTicker.MusicType.GAME))) - : MusicTicker.MusicType.MENU; - } - - public void dispatchKeypresses() { - int i = Keyboard.getEventKey() == 0 ? Keyboard.getEventCharacter() : Keyboard.getEventKey(); - if (i != 0 && !Keyboard.isRepeatEvent()) { - if (!(this.currentScreen instanceof GuiControls) - || ((GuiControls) this.currentScreen).time <= getSystemTime() - 20L) { - if (Keyboard.getEventKeyState()) { - if (i == this.gameSettings.keyBindScreenshot.getKeyCode()) { - this.ingameGUI.getChatGUI().printChatMessage(ScreenShotHelper.saveScreenshot()); - } + public void setIngameFocus() { + boolean touch = PointerInputAbstraction.isTouchMode(); + if (touch || Display.isActive()) { + if (!this.inGameHasFocus) { + this.inGameHasFocus = true; + if (!touch && mouseGrabSupported) { + this.mouseHelper.grabMouseCursor(); } + this.displayGuiScreen((GuiScreen) null); + this.leftClickCounter = 10000; } } } - public Entity getRenderViewEntity() { - return this.renderViewEntity; + /** + * + Resets the player keystate, disables the ingame focus, and ungrabs the + * mouse cursor. + */ + public void setIngameNotInFocus() { + if (this.inGameHasFocus) { + KeyBinding.unPressAllKeys(); + this.inGameHasFocus = false; + if (!PointerInputAbstraction.isTouchMode() && mouseGrabSupported) { + this.mouseHelper.ungrabMouseCursor(); + } + } } public void setRenderViewEntity(Entity viewingEntity) { @@ -2356,100 +2223,248 @@ public class Minecraft implements IThreadListener { this.entityRenderer.loadEntityShader(viewingEntity); } - public ListenableFuture addScheduledTaskFuture(Callable callableToSchedule) { - Validate.notNull(callableToSchedule); - ListenableFutureTask listenablefuturetask = ListenableFutureTask.create(callableToSchedule); - synchronized (this.scheduledTasks) { - this.scheduledTasks.add(listenablefuturetask); - return listenablefuturetask; + /** + * + Set the current ServerData instance. + */ + public void setServerData(ServerData serverDataIn) { + this.currentServerData = serverDataIn; + EagRuntime.setMCServerWindowGlobal(serverDataIn != null ? serverDataIn.serverIP : null); + } + + /** + * + Called when the window is closing. Sets 'running' to false which allows the + * game loop to exit cleanly. + */ + public void shutdown() { + this.running = false; + } + + public void shutdownIntegratedServer(GuiScreen cont) { + if (SingleplayerServerController.shutdownEaglercraftServer() + || SingleplayerServerController.getStatusState() == IntegratedServerState.WORLD_UNLOADING) { + displayGuiScreen(new GuiScreenIntegratedServerBusy(cont, "singleplayer.busy.stoppingIntegratedServer", + "singleplayer.failed.stoppingIntegratedServer", SingleplayerServerController::isReady)); + } else { + displayGuiScreen(cont); } } - public ListenableFuture addScheduledTaskFuture(Runnable runnableToSchedule) { - Validate.notNull(runnableToSchedule); - return this.addScheduledTaskFuture(Executors.callable(runnableToSchedule)); - } - - public void addScheduledTask(Runnable runnableToSchedule) { - this.addScheduledTaskFuture(Executors.callable(runnableToSchedule)); - } - - public BlockRendererDispatcher getBlockRendererDispatcher() { - return this.blockRenderDispatcher; - } - - public RenderManager getRenderManager() { - return this.renderManager; - } - - public RenderItem getRenderItem() { - return this.renderItem; - } - - public ItemRenderer getItemRenderer() { - return this.itemRenderer; - } - - public static int getDebugFPS() { - return debugFPS; - } - - public FrameTimer func_181539_aj() { - return this.field_181542_y; - } - - public boolean func_181540_al() { - return this.field_181541_X; - } - - public void func_181537_a(boolean parFlag) { - this.field_181541_X = parFlag; - } - - /**+ - * Used in the usage snooper. + /** + * + Shuts down the minecraft applet by stopping the resource downloads, and + * clearing up GL stuff; called when the application (or web page) is exited. */ - public static int getGLMaximumTextureSize() { - return EaglercraftGPU.glGetInteger(GL_MAX_TEXTURE_SIZE); - } + public void shutdownMinecraftApplet() { + try { + logger.info("Stopping!"); - public boolean areKeysLocked() { - return PlatformInput.lockKeys; - } - - public ModelManager getModelManager() { - return modelManager; - } - - /**+ - * Returns the save loader that is currently being used - */ - public ISaveFormat getSaveLoader() { - return SingleplayerServerController.instance; - } - - public void clearTitles() { - ingameGUI.displayTitle(null, null, -1, -1, -1); - } - - public boolean getEnableFNAWSkins() { - boolean ret = this.gameSettings.enableFNAWSkins; - if (this.thePlayer != null) { - if (this.thePlayer.sendQueue.currentFNAWSkinForcedState) { - ret = true; - } else { - ret &= this.thePlayer.sendQueue.currentFNAWSkinAllowedState; + try { + this.loadWorld((WorldClient) null); + } catch (Throwable var5) { + ; } + + this.mcSoundHandler.unloadSounds(); + if (SingleplayerServerController.isWorldRunning()) { + SingleplayerServerController.shutdownEaglercraftServer(); + while (SingleplayerServerController.getStatusState() == IntegratedServerState.WORLD_UNLOADING) { + EagUtils.sleep(50l); + SingleplayerServerController.runTick(); + } + } + if (SingleplayerServerController.isIntegratedServerWorkerAlive() + && SingleplayerServerController.canKillWorker()) { + SingleplayerServerController.killWorker(); + EagUtils.sleep(50l); + } + } finally { + EagRuntime.destroy(); + if (!this.hasCrashed) { + EagRuntime.exit(); + } + } - return ret; } - public void handleReconnectPacket(String redirectURI) { - this.reconnectURI = redirectURI; + /** + * + Starts the game: initializes the canvas, the title, the settings, etcetera. + */ + private void startGame() throws IOException { + this.gameSettings = new GameSettings(this); + this.defaultResourcePacks.add(this.mcDefaultResourcePack); + if (this.gameSettings.overrideHeight > 0 && this.gameSettings.overrideWidth > 0) { + this.displayWidth = this.gameSettings.overrideWidth; + this.displayHeight = this.gameSettings.overrideHeight; + } + + logger.info("EagRuntime Version: " + EagRuntime.getVersion()); + this.createDisplay(); + this.registerMetadataSerializers(); + EaglerFolderResourcePack.deleteOldResourcePacks(EaglerFolderResourcePack.SERVER_RESOURCE_PACKS, 604800000L); + this.mcResourcePackRepository = new ResourcePackRepository(this.mcDefaultResourcePack, this.metadataSerializer_, + this.gameSettings); + this.mcResourceManager = new SimpleReloadableResourceManager(this.metadataSerializer_); + this.mcLanguageManager = new LanguageManager(this.metadataSerializer_, this.gameSettings.language); + this.mcResourceManager.registerReloadListener(this.mcLanguageManager); + this.scaledResolution = new ScaledResolution(this); + this.refreshResources(); + this.renderEngine = new TextureManager(this.mcResourceManager); + this.mcResourceManager.registerReloadListener(this.renderEngine); + this.drawSplashScreen(this.renderEngine); + this.mcSoundHandler = new SoundHandler(this.mcResourceManager, this.gameSettings); + this.mcResourceManager.registerReloadListener(this.mcSoundHandler); + this.mcMusicTicker = new MusicTicker(this); + this.fontRendererObj = EaglerFontRenderer.createSupportedFontRenderer(this.gameSettings, + new ResourceLocation("textures/font/ascii.png"), this.renderEngine, false); + if (this.gameSettings.language != null) { + this.fontRendererObj.setUnicodeFlag(this.isUnicode()); + this.fontRendererObj.setBidiFlag(this.mcLanguageManager.isCurrentLanguageBidirectional()); + } + + this.standardGalacticFontRenderer = EaglerFontRenderer.createSupportedFontRenderer(this.gameSettings, + new ResourceLocation("textures/font/ascii_sga.png"), this.renderEngine, false); + this.mcResourceManager.registerReloadListener(this.fontRendererObj); + this.mcResourceManager.registerReloadListener(this.standardGalacticFontRenderer); + this.mcResourceManager.registerReloadListener(new GrassColorReloadListener()); + this.mcResourceManager.registerReloadListener(new FoliageColorReloadListener()); + this.mcResourceManager.registerReloadListener(new ShaderPackInfoReloadListener()); + this.mcResourceManager.registerReloadListener(PBRTextureMapUtils.blockMaterialConstants); + this.mcResourceManager.registerReloadListener(new TemperaturesLUT()); + this.mcResourceManager.registerReloadListener(new MetalsLUT()); + this.mcResourceManager.registerReloadListener(new EmissiveItems()); + this.mcResourceManager.registerReloadListener(new BlockVertexIDs()); + this.mcResourceManager.registerReloadListener(new EaglerMeshLoader()); + AchievementList.openInventory.setStatStringFormatter(new IStatStringFormat() { + public String formatString(String parString1) { + try { + return HString.format(parString1, new Object[] { GameSettings + .getKeyDisplayString(Minecraft.this.gameSettings.keyBindInventory.getKeyCode()) }); + } catch (Exception exception) { + return "Error: " + exception.getLocalizedMessage(); + } + } + }); + this.mouseHelper = new MouseHelper(); + this.checkGLError("Pre startup"); + GlStateManager.enableTexture2D(); + GlStateManager.shadeModel(GL_SMOOTH); + GlStateManager.clearDepth(1.0f); + GlStateManager.enableDepth(); + GlStateManager.depthFunc(GL_LEQUAL); + GlStateManager.enableAlpha(); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + GlStateManager.cullFace(GL_BACK); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.matrixMode(GL_MODELVIEW); + this.checkGLError("Startup"); + this.textureMapBlocks = new TextureMap("textures"); + this.textureMapBlocks.setEnablePBREagler(gameSettings.shaders); + this.textureMapBlocks.setMipmapLevels(this.gameSettings.mipmapLevels); + this.renderEngine.loadTickableTexture(TextureMap.locationBlocksTexture, this.textureMapBlocks); + this.renderEngine.bindTexture(TextureMap.locationBlocksTexture); + this.textureMapBlocks.setBlurMipmapDirect(false, this.gameSettings.mipmapLevels > 0); + this.modelManager = new ModelManager(this.textureMapBlocks); + this.mcResourceManager.registerReloadListener(this.modelManager); + this.renderItem = new RenderItem(this.renderEngine, this.modelManager); + this.renderManager = new RenderManager(this.renderEngine, this.renderItem); + this.itemRenderer = new ItemRenderer(this); + this.mcResourceManager.registerReloadListener(this.renderItem); + this.entityRenderer = new EntityRenderer(this, this.mcResourceManager); + this.mcResourceManager.registerReloadListener(this.entityRenderer); + this.blockRenderDispatcher = new BlockRendererDispatcher(this.modelManager.getBlockModelShapes(), + this.gameSettings); + this.mcResourceManager.registerReloadListener(this.blockRenderDispatcher); + this.renderGlobal = new RenderGlobal(this); + this.mcResourceManager.registerReloadListener(this.renderGlobal); + this.guiAchievement = new GuiAchievement(this); + GlStateManager.viewport(0, 0, this.displayWidth, this.displayHeight); + this.effectRenderer = new EffectRenderer(this.theWorld, this.renderEngine); + SkinPreviewRenderer.initialize(); + this.checkGLError("Post startup"); + this.ingameGUI = new GuiIngame(this); + + this.mouseGrabSupported = Mouse.isMouseGrabSupported(); + PointerInputAbstraction.init(this); + + this.eagskullCommand = new SkullCommand(this); + this.voiceOverlay = new GuiVoiceOverlay(this); + this.voiceOverlay.setResolution(scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight()); + + this.notifRenderer = new ServerNotificationRenderer(); + this.notifRenderer.init(); + this.notifRenderer.setResolution(this, scaledResolution.getScaledWidth(), scaledResolution.getScaledHeight(), + scaledResolution.getScaleFactor()); + this.touchOverlayRenderer = new TouchOverlayRenderer(this); + + ServerList.initServerList(this); + EaglerProfile.read(); + ServerCookieDataStore.load(); + + GuiScreen mainMenu = new GuiMainMenu(); + if (isDemo()) { + mainMenu = new GuiScreenDemoIntegratedServerStartup(mainMenu); + } + if (this.serverName != null) { + mainMenu = new GuiConnecting(mainMenu, this, this.serverName, this.serverPort); + } + + mainMenu = new GuiScreenEditProfile(mainMenu); + + if (!EagRuntime.getConfiguration().isForceProfanityFilter() && !gameSettings.hasShownProfanityFilter) { + mainMenu = new GuiScreenContentWarning(mainMenu); + } + + this.displayGuiScreen(mainMenu); + + this.renderEngine.deleteTexture(this.mojangLogo); + this.mojangLogo = null; + this.loadingScreen = new LoadingScreenRenderer(this); + + while (Mouse.next()) + ; + while (Keyboard.next()) + ; + while (Touch.next()) + ; } - public boolean isEnableProfanityFilter() { - return EagRuntime.getConfiguration().isForceProfanityFilter() || gameSettings.enableProfanityFilter; + /** + * + Toggles fullscreen mode. + */ + public void toggleFullscreen() { + Display.toggleFullscreen(); + } + + public void togglePerspective() { + ++this.gameSettings.thirdPersonView; + if (this.gameSettings.thirdPersonView > 2) { + this.gameSettings.thirdPersonView = 0; + } + + if (this.gameSettings.thirdPersonView == 0) { + this.entityRenderer.loadEntityShader(this.getRenderViewEntity()); + } else if (this.gameSettings.thirdPersonView == 1) { + this.entityRenderer.loadEntityShader((Entity) null); + } + + this.renderGlobal.setDisplayListEntitiesDirty(); + } + + public void updateDisplay() { + if (Display.isVSyncSupported()) { + Display.setVSync(this.gameSettings.enableVsync); + } else { + this.gameSettings.enableVsync = false; + } + Display.update(); + this.checkWindowResize(); + } + + private void updateDisplayMode() { + this.displayWidth = Display.getWidth(); + this.displayHeight = Display.getHeight(); + this.displayDPI = Display.getDPI(); + this.scaledResolution = new ScaledResolution(this); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/GuardianSound.java b/src/game/java/net/minecraft/client/audio/GuardianSound.java index 74a3e07e..8403a7a9 100644 --- a/src/game/java/net/minecraft/client/audio/GuardianSound.java +++ b/src/game/java/net/minecraft/client/audio/GuardianSound.java @@ -3,22 +3,25 @@ package net.minecraft.client.audio; import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +37,8 @@ public class GuardianSound extends MovingSound { this.repeatDelay = 0; } - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ public void update() { if (!this.guardian.isDead && this.guardian.hasTargetedEntity()) { diff --git a/src/game/java/net/minecraft/client/audio/ISound.java b/src/game/java/net/minecraft/client/audio/ISound.java index 240b47e2..618a21f7 100644 --- a/src/game/java/net/minecraft/client/audio/ISound.java +++ b/src/game/java/net/minecraft/client/audio/ISound.java @@ -2,45 +2,30 @@ package net.minecraft.client.audio; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ISound { - ResourceLocation getSoundLocation(); - - boolean canRepeat(); - - int getRepeatDelay(); - - float getVolume(); - - float getPitch(); - - float getXPosF(); - - float getYPosF(); - - float getZPosF(); - - ISound.AttenuationType getAttenuationType(); - public static enum AttenuationType { NONE(0), LINEAR(2); @@ -54,4 +39,22 @@ public interface ISound { return this.type; } } + + boolean canRepeat(); + + ISound.AttenuationType getAttenuationType(); + + float getPitch(); + + int getRepeatDelay(); + + ResourceLocation getSoundLocation(); + + float getVolume(); + + float getXPosF(); + + float getYPosF(); + + float getZPosF(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/ISoundEventAccessor.java b/src/game/java/net/minecraft/client/audio/ISoundEventAccessor.java index 9b1b7f3e..6f11eb71 100644 --- a/src/game/java/net/minecraft/client/audio/ISoundEventAccessor.java +++ b/src/game/java/net/minecraft/client/audio/ISoundEventAccessor.java @@ -1,27 +1,30 @@ package net.minecraft.client.audio; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ISoundEventAccessor { - int getWeight(); - T cloneEntry(); + + int getWeight(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/ITickableSound.java b/src/game/java/net/minecraft/client/audio/ITickableSound.java index feb4ca2b..12217041 100644 --- a/src/game/java/net/minecraft/client/audio/ITickableSound.java +++ b/src/game/java/net/minecraft/client/audio/ITickableSound.java @@ -2,22 +2,25 @@ package net.minecraft.client.audio; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/audio/MovingSound.java b/src/game/java/net/minecraft/client/audio/MovingSound.java index 0c7e83a2..afca9184 100644 --- a/src/game/java/net/minecraft/client/audio/MovingSound.java +++ b/src/game/java/net/minecraft/client/audio/MovingSound.java @@ -2,22 +2,25 @@ package net.minecraft.client.audio; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/audio/MovingSoundMinecart.java b/src/game/java/net/minecraft/client/audio/MovingSoundMinecart.java index 5e2f98bb..7e4df41c 100644 --- a/src/game/java/net/minecraft/client/audio/MovingSoundMinecart.java +++ b/src/game/java/net/minecraft/client/audio/MovingSoundMinecart.java @@ -4,22 +4,25 @@ import net.minecraft.entity.item.EntityMinecart; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,8 +38,8 @@ public class MovingSoundMinecart extends MovingSound { this.repeatDelay = 0; } - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ public void update() { if (this.minecart.isDead) { diff --git a/src/game/java/net/minecraft/client/audio/MovingSoundMinecartRiding.java b/src/game/java/net/minecraft/client/audio/MovingSoundMinecartRiding.java index 28514aab..0fa8050e 100644 --- a/src/game/java/net/minecraft/client/audio/MovingSoundMinecartRiding.java +++ b/src/game/java/net/minecraft/client/audio/MovingSoundMinecartRiding.java @@ -5,22 +5,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,8 +41,8 @@ public class MovingSoundMinecartRiding extends MovingSound { this.repeatDelay = 0; } - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ public void update() { if (!this.minecart.isDead && this.player.isRiding() && this.player.ridingEntity == this.minecart) { diff --git a/src/game/java/net/minecraft/client/audio/MusicTicker.java b/src/game/java/net/minecraft/client/audio/MusicTicker.java index fafa0b46..f8457789 100644 --- a/src/game/java/net/minecraft/client/audio/MusicTicker.java +++ b/src/game/java/net/minecraft/client/audio/MusicTicker.java @@ -1,44 +1,94 @@ package net.minecraft.client.audio; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.client.Minecraft; import net.minecraft.util.ITickable; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MusicTicker implements ITickable { + public static enum MusicType { + MENU(new ResourceLocation("minecraft:music.menu"), 20, 600), + GAME(new ResourceLocation("minecraft:music.game"), 12000, 24000), + CREATIVE(new ResourceLocation("minecraft:music.game.creative"), 1200, 3600), + CREDITS(new ResourceLocation("minecraft:music.game.end.credits"), Integer.MAX_VALUE, Integer.MAX_VALUE), + NETHER(new ResourceLocation("minecraft:music.game.nether"), 1200, 3600), + END_BOSS(new ResourceLocation("minecraft:music.game.end.dragon"), 0, 0), + END(new ResourceLocation("minecraft:music.game.end"), 6000, 24000); + + private final ResourceLocation musicLocation; + private final int minDelay; + private final int maxDelay; + + private MusicType(ResourceLocation location, int minDelayIn, int maxDelayIn) { + this.musicLocation = location; + this.minDelay = minDelayIn; + this.maxDelay = maxDelayIn; + } + + public int getMaxDelay() { + return this.maxDelay; + } + + public int getMinDelay() { + return this.minDelay; + } + + public ResourceLocation getMusicLocation() { + return this.musicLocation; + } + } + private final EaglercraftRandom rand = new EaglercraftRandom(); private final Minecraft mc; private ISound currentMusic; + private int timeUntilNextMusic = 100; public MusicTicker(Minecraft mcIn) { this.mc = mcIn; } - /**+ - * Like the old updateEntity(), except more generic. + public void func_181557_a() { + if (this.currentMusic != null) { + this.mc.getSoundHandler().stopSound(this.currentMusic); + this.currentMusic = null; + this.timeUntilNextMusic = 0; + } + + } + + public void func_181558_a(MusicTicker.MusicType parMusicType) { + this.currentMusic = PositionedSoundRecord.create(parMusicType.getMusicLocation()); + this.mc.getSoundHandler().playSound(this.currentMusic); + this.timeUntilNextMusic = Integer.MAX_VALUE; + } + + /** + * + Like the old updateEntity(), except more generic. */ public void update() { MusicTicker.MusicType musicticker$musictype = this.mc.getAmbientMusicType(); @@ -62,51 +112,4 @@ public class MusicTicker implements ITickable { } } - - public void func_181558_a(MusicTicker.MusicType parMusicType) { - this.currentMusic = PositionedSoundRecord.create(parMusicType.getMusicLocation()); - this.mc.getSoundHandler().playSound(this.currentMusic); - this.timeUntilNextMusic = Integer.MAX_VALUE; - } - - public void func_181557_a() { - if (this.currentMusic != null) { - this.mc.getSoundHandler().stopSound(this.currentMusic); - this.currentMusic = null; - this.timeUntilNextMusic = 0; - } - - } - - public static enum MusicType { - MENU(new ResourceLocation("minecraft:music.menu"), 20, 600), - GAME(new ResourceLocation("minecraft:music.game"), 12000, 24000), - CREATIVE(new ResourceLocation("minecraft:music.game.creative"), 1200, 3600), - CREDITS(new ResourceLocation("minecraft:music.game.end.credits"), Integer.MAX_VALUE, Integer.MAX_VALUE), - NETHER(new ResourceLocation("minecraft:music.game.nether"), 1200, 3600), - END_BOSS(new ResourceLocation("minecraft:music.game.end.dragon"), 0, 0), - END(new ResourceLocation("minecraft:music.game.end"), 6000, 24000); - - private final ResourceLocation musicLocation; - private final int minDelay; - private final int maxDelay; - - private MusicType(ResourceLocation location, int minDelayIn, int maxDelayIn) { - this.musicLocation = location; - this.minDelay = minDelayIn; - this.maxDelay = maxDelayIn; - } - - public ResourceLocation getMusicLocation() { - return this.musicLocation; - } - - public int getMinDelay() { - return this.minDelay; - } - - public int getMaxDelay() { - return this.maxDelay; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/PositionedSound.java b/src/game/java/net/minecraft/client/audio/PositionedSound.java index 7a9f4649..6a681ae3 100644 --- a/src/game/java/net/minecraft/client/audio/PositionedSound.java +++ b/src/game/java/net/minecraft/client/audio/PositionedSound.java @@ -2,22 +2,25 @@ package net.minecraft.client.audio; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,8 +33,8 @@ public abstract class PositionedSound implements ISound { protected float yPosF; protected float zPosF; protected boolean repeat = false; - /**+ - * The number of ticks between repeating the sound + /** + * + The number of ticks between repeating the sound */ protected int repeatDelay = 0; protected ISound.AttenuationType attenuationType = ISound.AttenuationType.LINEAR; @@ -40,24 +43,28 @@ public abstract class PositionedSound implements ISound { this.positionedSoundLocation = soundResource; } - public ResourceLocation getSoundLocation() { - return this.positionedSoundLocation; - } - public boolean canRepeat() { return this.repeat; } + public ISound.AttenuationType getAttenuationType() { + return this.attenuationType; + } + + public float getPitch() { + return this.pitch; + } + public int getRepeatDelay() { return this.repeatDelay; } - public float getVolume() { - return this.volume; + public ResourceLocation getSoundLocation() { + return this.positionedSoundLocation; } - public float getPitch() { - return this.pitch; + public float getVolume() { + return this.volume; } public float getXPosF() { @@ -71,8 +78,4 @@ public abstract class PositionedSound implements ISound { public float getZPosF() { return this.zPosF; } - - public ISound.AttenuationType getAttenuationType() { - return this.attenuationType; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/PositionedSoundRecord.java b/src/game/java/net/minecraft/client/audio/PositionedSoundRecord.java index 4d1e55b8..008852c5 100644 --- a/src/game/java/net/minecraft/client/audio/PositionedSoundRecord.java +++ b/src/game/java/net/minecraft/client/audio/PositionedSoundRecord.java @@ -2,34 +2,37 @@ package net.minecraft.client.audio; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PositionedSoundRecord extends PositionedSound { - public static PositionedSoundRecord create(ResourceLocation soundResource, float pitch) { - return new PositionedSoundRecord(soundResource, 0.25F, pitch, false, 0, ISound.AttenuationType.NONE, 0.0F, 0.0F, + public static PositionedSoundRecord create(ResourceLocation soundResource) { + return new PositionedSoundRecord(soundResource, 1.0F, 1.0F, false, 0, ISound.AttenuationType.NONE, 0.0F, 0.0F, 0.0F); } - public static PositionedSoundRecord create(ResourceLocation soundResource) { - return new PositionedSoundRecord(soundResource, 1.0F, 1.0F, false, 0, ISound.AttenuationType.NONE, 0.0F, 0.0F, + public static PositionedSoundRecord create(ResourceLocation soundResource, float pitch) { + return new PositionedSoundRecord(soundResource, 0.25F, pitch, false, 0, ISound.AttenuationType.NONE, 0.0F, 0.0F, 0.0F); } @@ -39,11 +42,6 @@ public class PositionedSoundRecord extends PositionedSound { yPosition, zPosition); } - public PositionedSoundRecord(ResourceLocation soundResource, float volume, float pitch, float xPosition, - float yPosition, float zPosition) { - this(soundResource, volume, pitch, false, 0, ISound.AttenuationType.LINEAR, xPosition, yPosition, zPosition); - } - private PositionedSoundRecord(ResourceLocation soundResource, float volume, float pitch, boolean repeat, int repeatDelay, ISound.AttenuationType attenuationType, float xPosition, float yPosition, float zPosition) { @@ -57,4 +55,9 @@ public class PositionedSoundRecord extends PositionedSound { this.repeatDelay = repeatDelay; this.attenuationType = attenuationType; } + + public PositionedSoundRecord(ResourceLocation soundResource, float volume, float pitch, float xPosition, + float yPosition, float zPosition) { + this(soundResource, volume, pitch, false, 0, ISound.AttenuationType.LINEAR, xPosition, yPosition, zPosition); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundCategory.java b/src/game/java/net/minecraft/client/audio/SoundCategory.java index 28a7529d..6fba43f6 100644 --- a/src/game/java/net/minecraft/client/audio/SoundCategory.java +++ b/src/game/java/net/minecraft/client/audio/SoundCategory.java @@ -4,22 +4,25 @@ import java.util.Map; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,26 +35,6 @@ public enum SoundCategory { private static final Map NAME_CATEGORY_MAP = Maps.newHashMap(); private static final Map ID_CATEGORY_MAP = Maps.newHashMap(); - private final String categoryName; - private final int categoryId; - - private SoundCategory(String name, int id) { - this.categoryName = name; - this.categoryId = id; - } - - public String getCategoryName() { - return this.categoryName; - } - - public int getCategoryId() { - return this.categoryId; - } - - public static SoundCategory getCategory(String name) { - return (SoundCategory) NAME_CATEGORY_MAP.get(name); - } - static { SoundCategory[] categories = _VALUES; for (int i = 0; i < categories.length; ++i) { @@ -66,4 +49,25 @@ public enum SoundCategory { } } + + public static SoundCategory getCategory(String name) { + return (SoundCategory) NAME_CATEGORY_MAP.get(name); + } + + private final String categoryName; + + private final int categoryId; + + private SoundCategory(String name, int id) { + this.categoryName = name; + this.categoryId = id; + } + + public int getCategoryId() { + return this.categoryId; + } + + public String getCategoryName() { + return this.categoryName; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundEventAccessor.java b/src/game/java/net/minecraft/client/audio/SoundEventAccessor.java index ee0fc88e..850d276e 100644 --- a/src/game/java/net/minecraft/client/audio/SoundEventAccessor.java +++ b/src/game/java/net/minecraft/client/audio/SoundEventAccessor.java @@ -1,21 +1,24 @@ package net.minecraft.client.audio; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,11 +32,11 @@ public class SoundEventAccessor implements ISoundEventAccessor { this.weight = weight; } - public int getWeight() { - return this.weight; - } - public SoundPoolEntry cloneEntry() { return new SoundPoolEntry(this.entry); } + + public int getWeight() { + return this.weight; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundEventAccessorComposite.java b/src/game/java/net/minecraft/client/audio/SoundEventAccessorComposite.java index a319acfc..5e820535 100644 --- a/src/game/java/net/minecraft/client/audio/SoundEventAccessorComposite.java +++ b/src/game/java/net/minecraft/client/audio/SoundEventAccessorComposite.java @@ -1,35 +1,38 @@ package net.minecraft.client.audio; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SoundEventAccessorComposite implements ISoundEventAccessor { - /**+ - * A composite (List) of ISoundEventAccessors + /** + * + A composite (List) of ISoundEventAccessors */ private final List> soundPool = Lists.newArrayList(); private final EaglercraftRandom rnd = new EaglercraftRandom(); @@ -46,14 +49,8 @@ public class SoundEventAccessorComposite implements ISoundEventAccessor sound) { + this.soundPool.add(sound); } public SoundPoolEntry cloneEntry() { @@ -78,15 +75,21 @@ public class SoundEventAccessorComposite implements ISoundEventAccessor sound) { - this.soundPool.add(sound); + public SoundCategory getSoundCategory() { + return this.category; } public ResourceLocation getSoundEventLocation() { return this.soundLocation; } - public SoundCategory getSoundCategory() { - return this.category; + public int getWeight() { + int i = 0; + + for (int j = 0, l = this.soundPool.size(); j < l; ++j) { + i += this.soundPool.get(j).getWeight(); + } + + return i; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundHandler.java b/src/game/java/net/minecraft/client/audio/SoundHandler.java index 5d9296aa..995c8e93 100644 --- a/src/game/java/net/minecraft/client/audio/SoundHandler.java +++ b/src/game/java/net/minecraft/client/audio/SoundHandler.java @@ -25,69 +25,30 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.ITickable; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SoundHandler implements IResourceManagerReloadListener, ITickable { - private static final Logger logger = LogManager.getLogger(); - private static final Logger tipLogger = LogManager.getLogger("EaglercraftX"); - public static final SoundPoolEntry missing_sound = new SoundPoolEntry(new ResourceLocation("meta:missing_sound"), - 0.0D, 0.0D, false); - private final SoundRegistry sndRegistry = new SoundRegistry(); - private final EaglercraftSoundManager sndManager; - private final IResourceManager mcResourceManager; - - public SoundHandler(IResourceManager manager, GameSettings gameSettingsIn) { - this.mcResourceManager = manager; - this.sndManager = new EaglercraftSoundManager(gameSettingsIn, this); - } - - public void onResourceManagerReload(IResourceManager iresourcemanager) { - this.sndManager.reloadSoundSystem(); - this.sndRegistry.clearMap(); - - for (String s : iresourcemanager.getResourceDomains()) { - try { - for (IResource iresource : iresourcemanager.getAllResources(new ResourceLocation(s, "sounds.json"))) { - try { - Map map = this.getSoundMap(iresource.getInputStream()); - - for (Entry entry : (Set) map.entrySet()) { - this.loadSoundResource(new ResourceLocation(s, (String) entry.getKey()), - (SoundList) entry.getValue()); - } - } catch (RuntimeException runtimeexception) { - logger.warn("Invalid sounds.json", runtimeexception); - } - } - } catch (IOException var11) { - ; - } - } - - if (this.sndRegistry.getObject(new ResourceLocation("minecraft:sounds/music/game/calm1.ogg")) == null) { - tipLogger.info( - "Download this resource pack if you want music: https://bafybeiayojww5jfyzvlmtuk7l5ufkt7nlfto7mhwmzf2vs4bvsjd5ouiuq.ipfs.nftstorage.link/?filename=Music_For_Eaglercraft.zip"); - } - } - public static class SoundMap { protected final Map soundMap; @@ -98,6 +59,49 @@ public class SoundHandler implements IResourceManagerReloadListener, ITickable { } + private static final Logger logger = LogManager.getLogger(); + private static final Logger tipLogger = LogManager.getLogger("EaglercraftX"); + public static final SoundPoolEntry missing_sound = new SoundPoolEntry(new ResourceLocation("meta:missing_sound"), + 0.0D, 0.0D, false); + private final SoundRegistry sndRegistry = new SoundRegistry(); + private final EaglercraftSoundManager sndManager; + + private final IResourceManager mcResourceManager; + + public SoundHandler(IResourceManager manager, GameSettings gameSettingsIn) { + this.mcResourceManager = manager; + this.sndManager = new EaglercraftSoundManager(gameSettingsIn, this); + } + + /** + * + Returns a random sound from one or more categories + */ + public SoundEventAccessorComposite getRandomSoundFromCategories(SoundCategory... categories) { + ArrayList arraylist = Lists.newArrayList(); + + for (ResourceLocation resourcelocation : this.sndRegistry.getKeys()) { + SoundEventAccessorComposite soundeventaccessorcomposite = (SoundEventAccessorComposite) this.sndRegistry + .getObject(resourcelocation); + SoundCategory cat = soundeventaccessorcomposite.getSoundCategory(); + for (int i = 0; i < categories.length; ++i) { + if (cat == categories[i]) { + arraylist.add(soundeventaccessorcomposite); + break; + } + } + } + + if (arraylist.isEmpty()) { + return null; + } else { + return (SoundEventAccessorComposite) arraylist.get(ThreadLocalRandom.current().nextInt(arraylist.size())); + } + } + + public SoundEventAccessorComposite getSound(ResourceLocation location) { + return (SoundEventAccessorComposite) this.sndRegistry.getObject(location); + } + protected Map getSoundMap(InputStream stream) { Map map = null; try { @@ -112,6 +116,10 @@ public class SoundHandler implements IResourceManagerReloadListener, ITickable { return map; } + public boolean isSoundPlaying(ISound sound) { + return this.sndManager.isSoundPlaying(sound); + } + private void loadSoundResource(ResourceLocation location, SoundList sounds) { boolean flag = !this.sndRegistry.containsKey(location); SoundEventAccessorComposite soundeventaccessorcomposite; @@ -163,18 +171,18 @@ public class SoundHandler implements IResourceManagerReloadListener, ITickable { final ResourceLocation field_148726_a = new ResourceLocation(s1, soundlist$soundentry.getSoundEntryName()); - public int getWeight() { - SoundEventAccessorComposite soundeventaccessorcomposite1 = (SoundEventAccessorComposite) SoundHandler.this.sndRegistry - .getObject(this.field_148726_a); - return soundeventaccessorcomposite1 == null ? 0 : soundeventaccessorcomposite1.getWeight(); - } - public SoundPoolEntry cloneEntry() { SoundEventAccessorComposite soundeventaccessorcomposite1 = (SoundEventAccessorComposite) SoundHandler.this.sndRegistry .getObject(this.field_148726_a); return soundeventaccessorcomposite1 == null ? SoundHandler.missing_sound : soundeventaccessorcomposite1.cloneEntry(); } + + public int getWeight() { + SoundEventAccessorComposite soundeventaccessorcomposite1 = (SoundEventAccessorComposite) SoundHandler.this.sndRegistry + .getObject(this.field_148726_a); + return soundeventaccessorcomposite1 == null ? 0 : soundeventaccessorcomposite1.getWeight(); + } }; break; default: @@ -186,51 +194,61 @@ public class SoundHandler implements IResourceManagerReloadListener, ITickable { } - public SoundEventAccessorComposite getSound(ResourceLocation location) { - return (SoundEventAccessorComposite) this.sndRegistry.getObject(location); - } + public void onResourceManagerReload(IResourceManager iresourcemanager) { + this.sndManager.reloadSoundSystem(); + this.sndRegistry.clearMap(); - /**+ - * Play a sound - */ - public void playSound(ISound sound) { - this.sndManager.playSound(sound); - } + for (String s : iresourcemanager.getResourceDomains()) { + try { + for (IResource iresource : iresourcemanager.getAllResources(new ResourceLocation(s, "sounds.json"))) { + try { + Map map = this.getSoundMap(iresource.getInputStream()); - /**+ - * Plays the sound in n ticks - */ - public void playDelayedSound(ISound sound, int delay) { - this.sndManager.playDelayedSound(sound, delay); - } + for (Entry entry : (Set) map.entrySet()) { + this.loadSoundResource(new ResourceLocation(s, (String) entry.getKey()), + (SoundList) entry.getValue()); + } + } catch (RuntimeException runtimeexception) { + logger.warn("Invalid sounds.json", runtimeexception); + } + } + } catch (IOException var11) { + ; + } + } - public void setListener(EntityPlayer player, float parFloat1) { - this.sndManager.setListener(player, parFloat1); + if (this.sndRegistry.getObject(new ResourceLocation("minecraft:sounds/music/game/calm1.ogg")) == null) { + tipLogger.info( + "Download this resource pack if you want music: https://bafybeiayojww5jfyzvlmtuk7l5ufkt7nlfto7mhwmzf2vs4bvsjd5ouiuq.ipfs.nftstorage.link/?filename=Music_For_Eaglercraft.zip"); + } } public void pauseSounds() { this.sndManager.pauseAllSounds(); } - public void stopSounds() { - this.sndManager.stopAllSounds(); - } - - public void unloadSounds() { - this.sndManager.unloadSoundSystem(); - } - - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Plays the sound in n ticks */ - public void update() { - this.sndManager.updateAllSounds(); + public void playDelayedSound(ISound sound, int delay) { + this.sndManager.playDelayedSound(sound, delay); + } + + /** + * + Play a sound + */ + public void playSound(ISound sound) { + this.sndManager.playSound(sound); } public void resumeSounds() { this.sndManager.resumeAllSounds(); } + public void setListener(EntityPlayer player, float parFloat1) { + this.sndManager.setListener(player, parFloat1); + } + public void setSoundLevel(SoundCategory category, float volume) { if (category == SoundCategory.MASTER && volume <= 0.0F) { this.stopSounds(); @@ -243,32 +261,18 @@ public class SoundHandler implements IResourceManagerReloadListener, ITickable { this.sndManager.stopSound(parISound); } - /**+ - * Returns a random sound from one or more categories - */ - public SoundEventAccessorComposite getRandomSoundFromCategories(SoundCategory... categories) { - ArrayList arraylist = Lists.newArrayList(); - - for (ResourceLocation resourcelocation : this.sndRegistry.getKeys()) { - SoundEventAccessorComposite soundeventaccessorcomposite = (SoundEventAccessorComposite) this.sndRegistry - .getObject(resourcelocation); - SoundCategory cat = soundeventaccessorcomposite.getSoundCategory(); - for (int i = 0; i < categories.length; ++i) { - if (cat == categories[i]) { - arraylist.add(soundeventaccessorcomposite); - break; - } - } - } - - if (arraylist.isEmpty()) { - return null; - } else { - return (SoundEventAccessorComposite) arraylist.get(ThreadLocalRandom.current().nextInt(arraylist.size())); - } + public void stopSounds() { + this.sndManager.stopAllSounds(); } - public boolean isSoundPlaying(ISound sound) { - return this.sndManager.isSoundPlaying(sound); + public void unloadSounds() { + this.sndManager.unloadSoundSystem(); + } + + /** + * + Like the old updateEntity(), except more generic. + */ + public void update() { + this.sndManager.updateAllSounds(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundList.java b/src/game/java/net/minecraft/client/audio/SoundList.java index 58475db7..dc2ce142 100644 --- a/src/game/java/net/minecraft/client/audio/SoundList.java +++ b/src/game/java/net/minecraft/client/audio/SoundList.java @@ -4,116 +4,34 @@ import java.util.List; import com.google.common.collect.Lists; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SoundList { - private final List soundList = Lists.newArrayList(); - private boolean replaceExisting; - private SoundCategory category; - - public List getSoundList() { - return this.soundList; - } - - public boolean canReplaceExisting() { - return this.replaceExisting; - } - - public void setReplaceExisting(boolean parFlag) { - this.replaceExisting = parFlag; - } - - public SoundCategory getSoundCategory() { - return this.category; - } - - public void setSoundCategory(SoundCategory soundCat) { - this.category = soundCat; - } - public static class SoundEntry { - private String name; - private float volume = 1.0F; - private float pitch = 1.0F; - private int weight = 1; - private SoundList.SoundEntry.Type type = SoundList.SoundEntry.Type.FILE; - private boolean streaming = false; - - public String getSoundEntryName() { - return this.name; - } - - public void setSoundEntryName(String nameIn) { - this.name = nameIn; - } - - public float getSoundEntryVolume() { - return this.volume; - } - - public void setSoundEntryVolume(float volumeIn) { - this.volume = volumeIn; - } - - public float getSoundEntryPitch() { - return this.pitch; - } - - public void setSoundEntryPitch(float pitchIn) { - this.pitch = pitchIn; - } - - public int getSoundEntryWeight() { - return this.weight; - } - - public void setSoundEntryWeight(int weightIn) { - this.weight = weightIn; - } - - public SoundList.SoundEntry.Type getSoundEntryType() { - return this.type; - } - - public void setSoundEntryType(SoundList.SoundEntry.Type typeIn) { - this.type = typeIn; - } - - public boolean isStreaming() { - return this.streaming; - } - - public void setStreaming(boolean isStreaming) { - this.streaming = isStreaming; - } - public static enum Type { FILE("file"), SOUND_EVENT("event"); - private final String field_148583_c; - - private Type(String parString2) { - this.field_148583_c = parString2; - } - public static SoundList.SoundEntry.Type getType(String parString1) { SoundList.SoundEntry.Type[] types = values(); for (int i = 0; i < types.length; ++i) { @@ -124,6 +42,93 @@ public class SoundList { return null; } + + private final String field_148583_c; + + private Type(String parString2) { + this.field_148583_c = parString2; + } + } + + private String name; + private float volume = 1.0F; + private float pitch = 1.0F; + private int weight = 1; + private SoundList.SoundEntry.Type type = SoundList.SoundEntry.Type.FILE; + + private boolean streaming = false; + + public String getSoundEntryName() { + return this.name; + } + + public float getSoundEntryPitch() { + return this.pitch; + } + + public SoundList.SoundEntry.Type getSoundEntryType() { + return this.type; + } + + public float getSoundEntryVolume() { + return this.volume; + } + + public int getSoundEntryWeight() { + return this.weight; + } + + public boolean isStreaming() { + return this.streaming; + } + + public void setSoundEntryName(String nameIn) { + this.name = nameIn; + } + + public void setSoundEntryPitch(float pitchIn) { + this.pitch = pitchIn; + } + + public void setSoundEntryType(SoundList.SoundEntry.Type typeIn) { + this.type = typeIn; + } + + public void setSoundEntryVolume(float volumeIn) { + this.volume = volumeIn; + } + + public void setSoundEntryWeight(int weightIn) { + this.weight = weightIn; + } + + public void setStreaming(boolean isStreaming) { + this.streaming = isStreaming; } } + + private final List soundList = Lists.newArrayList(); + private boolean replaceExisting; + + private SoundCategory category; + + public boolean canReplaceExisting() { + return this.replaceExisting; + } + + public SoundCategory getSoundCategory() { + return this.category; + } + + public List getSoundList() { + return this.soundList; + } + + public void setReplaceExisting(boolean parFlag) { + this.replaceExisting = parFlag; + } + + public void setSoundCategory(SoundCategory soundCat) { + this.category = soundCat; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundListSerializer.java b/src/game/java/net/minecraft/client/audio/SoundListSerializer.java index bb7664ac..12a126b9 100644 --- a/src/game/java/net/minecraft/client/audio/SoundListSerializer.java +++ b/src/game/java/net/minecraft/client/audio/SoundListSerializer.java @@ -7,22 +7,25 @@ import org.json.JSONObject; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeDeserializer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/audio/SoundPoolEntry.java b/src/game/java/net/minecraft/client/audio/SoundPoolEntry.java index 4b033bd7..3d7f273b 100644 --- a/src/game/java/net/minecraft/client/audio/SoundPoolEntry.java +++ b/src/game/java/net/minecraft/client/audio/SoundPoolEntry.java @@ -2,22 +2,25 @@ package net.minecraft.client.audio; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,27 +45,27 @@ public class SoundPoolEntry { this.streamingSound = locationIn.streamingSound; } - public ResourceLocation getSoundPoolEntryLocation() { - return this.location; - } - public double getPitch() { return this.pitch; } - public void setPitch(double pitchIn) { - this.pitch = pitchIn; + public ResourceLocation getSoundPoolEntryLocation() { + return this.location; } public double getVolume() { return this.volume; } - public void setVolume(double volumeIn) { - this.volume = volumeIn; - } - public boolean isStreamingSound() { return this.streamingSound; } + + public void setPitch(double pitchIn) { + this.pitch = pitchIn; + } + + public void setVolume(double volumeIn) { + this.volume = volumeIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/audio/SoundRegistry.java b/src/game/java/net/minecraft/client/audio/SoundRegistry.java index cee11d17..82226173 100644 --- a/src/game/java/net/minecraft/client/audio/SoundRegistry.java +++ b/src/game/java/net/minecraft/client/audio/SoundRegistry.java @@ -7,22 +7,25 @@ import com.google.common.collect.Maps; import net.minecraft.util.RegistrySimple; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,6 +33,13 @@ import net.minecraft.util.ResourceLocation; public class SoundRegistry extends RegistrySimple { private Map soundRegistry; + /** + * + Reset the underlying sound map (Called on resource manager reload) + */ + public void clearMap() { + this.soundRegistry.clear(); + } + protected Map createUnderlyingMap() { this.soundRegistry = Maps.newHashMap(); return this.soundRegistry; @@ -38,12 +48,4 @@ public class SoundRegistry extends RegistrySimple 1.0F) { - f = 1.0F; - } - - this.limbSwingAmount += (f - this.limbSwingAmount) * 0.4F; - this.limbSwing += this.limbSwingAmount; - if (!this.isItemInUse && this.isEating() && this.inventory.mainInventory[this.inventory.currentItem] != null) { - ItemStack itemstack = this.inventory.mainInventory[this.inventory.currentItem]; - this.setItemInUse(this.inventory.mainInventory[this.inventory.currentItem], - itemstack.getItem().getMaxItemUseDuration(itemstack)); - this.isItemInUse = true; - } else if (this.isItemInUse && !this.isEating()) { - this.clearItemInUse(); - this.isItemInUse = false; - } - + public boolean canCommandSenderUseCommand(int var1, String var2) { + return false; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Get the position in the world. {@code null} is not allowed! If you + * are not an entity in the world, return the coordinates 0, 0, 0 + */ + public BlockPos getPosition() { + return new BlockPos(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D); + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (this.otherPlayerMPPosRotationIncrements > 0) { @@ -144,9 +132,37 @@ public class EntityOtherPlayerMP extends AbstractClientPlayer { this.cameraPitch += (f - this.cameraPitch) * 0.8F; } - /**+ - * Sets the held item, or an armor slot. Slot 0 is held item. - * Slot 1-4 is armor. Params: Item, slot + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.renderOffsetY = 0.0F; + super.onUpdate(); + this.prevLimbSwingAmount = this.limbSwingAmount; + double d0 = this.posX - this.prevPosX; + double d1 = this.posZ - this.prevPosZ; + float f = MathHelper.sqrt_double(d0 * d0 + d1 * d1) * 4.0F; + if (f > 1.0F) { + f = 1.0F; + } + + this.limbSwingAmount += (f - this.limbSwingAmount) * 0.4F; + this.limbSwing += this.limbSwingAmount; + if (!this.isItemInUse && this.isEating() && this.inventory.mainInventory[this.inventory.currentItem] != null) { + ItemStack itemstack = this.inventory.mainInventory[this.inventory.currentItem]; + this.setItemInUse(this.inventory.mainInventory[this.inventory.currentItem], + itemstack.getItem().getMaxItemUseDuration(itemstack)); + this.isItemInUse = true; + } else if (this.isItemInUse && !this.isEating()) { + this.clearItemInUse(); + this.isItemInUse = false; + } + + } + + /** + * + Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is + * armor. Params: Item, slot */ public void setCurrentItemOrArmor(int slotIn, ItemStack stack) { if (slotIn == 0) { @@ -157,27 +173,13 @@ public class EntityOtherPlayerMP extends AbstractClientPlayer { } - /**+ - * Send a chat message to the CommandSender - */ - public void addChatMessage(IChatComponent ichatcomponent) { - Minecraft.getMinecraft().ingameGUI.getChatGUI().printChatMessage(ichatcomponent); - } - - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not - */ - public boolean canCommandSenderUseCommand(int var1, String var2) { - return false; - } - - /**+ - * Get the position in the world. {@code null} is not - * allowed! If you are not an entity in the world, return - * the coordinates 0, 0, 0 - */ - public BlockPos getPosition() { - return new BlockPos(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D); + public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, + boolean parFlag) { + this.otherPlayerMPX = x; + this.otherPlayerMPY = y; + this.otherPlayerMPZ = z; + this.otherPlayerMPYaw = (double) yaw; + this.otherPlayerMPPitch = (double) pitch; + this.otherPlayerMPPosRotationIncrements = posRotationIncrements; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/entity/EntityPlayerSP.java b/src/game/java/net/minecraft/client/entity/EntityPlayerSP.java index e3cd6d17..4a81eec8 100644 --- a/src/game/java/net/minecraft/client/entity/EntityPlayerSP.java +++ b/src/game/java/net/minecraft/client/entity/EntityPlayerSP.java @@ -55,22 +55,25 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.world.IInteractionObject; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -110,181 +113,46 @@ public class EntityPlayerSP extends AbstractClientPlayer { this.statWriter = statWriter; } - /**+ - * Called when the entity is attacked. + public void addChatComponentMessage(IChatComponent chatComponent) { + this.mc.ingameGUI.getChatGUI().printChatMessage(chatComponent); + } + + /** + * + Send a chat message to the CommandSender + */ + public void addChatMessage(IChatComponent ichatcomponent) { + this.mc.ingameGUI.getChatGUI().printChatMessage(ichatcomponent); + } + + /** + * + Adds a value to a statistic field. + */ + public void addStat(StatBase stat, int amount) { + if (stat != null) { + if (stat.isIndependent) { + super.addStat(stat, amount); + } + + } + } + + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource source, float amount) { return false; } - /**+ - * Heal living entity (param: amount of half-hearts) + /** + * + Returns {@code true} if the CommandSender is allowed to execute the + * command, {@code false} if not */ - public void heal(float healAmount) { + public boolean canCommandSenderUseCommand(int i, String var2) { + return i <= 0; } - /**+ - * Called when a player mounts an entity. e.g. mounts a pig, - * mounts a boat. - */ - public void mountEntity(Entity entityIn) { - super.mountEntity(entityIn); - if (entityIn instanceof EntityMinecart) { - this.mc.getSoundHandler().playSound(new MovingSoundMinecartRiding(this, (EntityMinecart) entityIn)); - } - - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - if (this.worldObj.isBlockLoaded(new BlockPos(this.posX, 0.0D, this.posZ))) { - super.onUpdate(); - if (this.isRiding()) { - this.sendQueue.addToSendQueue( - new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, this.rotationPitch, this.onGround)); - this.sendQueue.addToSendQueue(new C0CPacketInput(this.moveStrafing, this.moveForward, - this.movementInput.jump, this.movementInput.sneak)); - } else { - this.onUpdateWalkingPlayer(); - } - - } - } - - /**+ - * called every tick when the player is on foot. Performs all - * the things that normally happen during movement. - */ - public void onUpdateWalkingPlayer() { - boolean flag = this.isSprinting(); - if (flag != this.serverSprintState) { - if (flag) { - this.sendQueue - .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.START_SPRINTING)); - } else { - this.sendQueue - .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.STOP_SPRINTING)); - } - - this.serverSprintState = flag; - } - - boolean flag1 = this.isSneaking(); - if (flag1 != this.serverSneakState) { - if (flag1) { - this.sendQueue - .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.START_SNEAKING)); - } else { - this.sendQueue - .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.STOP_SNEAKING)); - } - - this.serverSneakState = flag1; - } - - if (this.isCurrentViewEntity()) { - double d0 = this.posX - this.lastReportedPosX; - double d1 = this.getEntityBoundingBox().minY - this.lastReportedPosY; - double d2 = this.posZ - this.lastReportedPosZ; - double d3 = (double) (this.rotationYaw - this.lastReportedYaw); - double d4 = (double) (this.rotationPitch - this.lastReportedPitch); - boolean flag2 = d0 * d0 + d1 * d1 + d2 * d2 > 9.0E-4D || this.positionUpdateTicks >= 20; - boolean flag3 = d3 != 0.0D || d4 != 0.0D; - if (this.ridingEntity == null) { - if (flag2 && flag3) { - this.sendQueue.addToSendQueue( - new C03PacketPlayer.C06PacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, - this.posZ, this.rotationYaw, this.rotationPitch, this.onGround)); - } else if (flag2) { - this.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(this.posX, - this.getEntityBoundingBox().minY, this.posZ, this.onGround)); - } else if (flag3) { - this.sendQueue.addToSendQueue(new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, - this.rotationPitch, this.onGround)); - } else { - this.sendQueue.addToSendQueue(new C03PacketPlayer(this.onGround)); - } - } else { - this.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(this.motionX, -999.0D, - this.motionZ, this.rotationYaw, this.rotationPitch, this.onGround)); - flag2 = false; - } - - ++this.positionUpdateTicks; - if (flag2) { - this.lastReportedPosX = this.posX; - this.lastReportedPosY = this.getEntityBoundingBox().minY; - this.lastReportedPosZ = this.posZ; - this.positionUpdateTicks = 0; - } - - if (flag3) { - this.lastReportedYaw = this.rotationYaw; - this.lastReportedPitch = this.rotationPitch; - } - } - - } - - /**+ - * Called when player presses the drop item key - */ - public EntityItem dropOneItem(boolean dropAll) { - C07PacketPlayerDigging.Action c07packetplayerdigging$action = dropAll - ? C07PacketPlayerDigging.Action.DROP_ALL_ITEMS - : C07PacketPlayerDigging.Action.DROP_ITEM; - this.sendQueue.addToSendQueue( - new C07PacketPlayerDigging(c07packetplayerdigging$action, BlockPos.ORIGIN, EnumFacing.DOWN)); - return null; - } - - /**+ - * Joins the passed in entity item with the world. Args: - * entityItem - */ - protected void joinEntityItemWithWorld(EntityItem itemIn) { - } - - /**+ - * Sends a chat message from the player. Args: chatMessage - */ - public void sendChatMessage(String message) { - if (((sendQueue.getNetworkManager() instanceof ClientIntegratedServerNetworkManager) - || (sendQueue.getNetworkManager() instanceof LANClientNetworkManager)) - && message.startsWith("/eagskull")) { - this.mc.eagskullCommand.openFileChooser(); - } else { - this.sendQueue.addToSendQueue(new C01PacketChatMessage(message)); - } - } - - /**+ - * Swings the item the player is holding. - */ - public void swingItem() { - super.swingItem(); - this.sendQueue.addToSendQueue(new C0APacketAnimation()); - } - - public void respawnPlayer() { - this.sendQueue.addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN)); - } - - /**+ - * Deals damage to the entity. If its a EntityPlayer then will - * take damage from the armor first and then health second with - * the reduced value. Args: damageAmount - */ - protected void damageEntity(DamageSource damageSrc, float damageAmount) { - if (!this.isEntityInvulnerable(damageSrc)) { - this.setHealth(this.getHealth() - damageAmount); - } - } - - /**+ - * set current crafting inventory back to the 2x2 square + /** + * + set current crafting inventory back to the 2x2 square */ public void closeScreen() { this.sendQueue.addToSendQueue(new C0DPacketCloseWindow(this.openContainer.windowId)); @@ -297,215 +165,31 @@ public class EntityPlayerSP extends AbstractClientPlayer { this.mc.displayGuiScreen((GuiScreen) null); } - /**+ - * Updates health locally. + /** + * + Deals damage to the entity. If its a EntityPlayer then will take damage + * from the armor first and then health second with the reduced value. Args: + * damageAmount */ - public void setPlayerSPHealth(float health) { - if (this.hasValidHealth) { - float f = this.getHealth() - health; - if (f <= 0.0F) { - this.setHealth(health); - if (f < 0.0F) { - this.hurtResistantTime = this.maxHurtResistantTime / 2; - } - } else { - this.lastDamage = f; - this.setHealth(this.getHealth()); - this.hurtResistantTime = this.maxHurtResistantTime; - this.damageEntity(DamageSource.generic, f); - this.hurtTime = this.maxHurtTime = 10; - } - } else { - this.setHealth(health); - this.hasValidHealth = true; + protected void damageEntity(DamageSource damageSrc, float damageAmount) { + if (!this.isEntityInvulnerable(damageSrc)) { + this.setHealth(this.getHealth() - damageAmount); + } + } + + public void displayGui(IInteractionObject guiOwner) { + String s = guiOwner.getGuiID(); + if ("minecraft:crafting_table".equals(s)) { + this.mc.displayGuiScreen(new GuiCrafting(this.inventory, this.worldObj)); + } else if ("minecraft:enchanting_table".equals(s)) { + this.mc.displayGuiScreen(new GuiEnchantment(this.inventory, this.worldObj, guiOwner)); + } else if ("minecraft:anvil".equals(s)) { + this.mc.displayGuiScreen(new GuiRepair(this.inventory, this.worldObj)); } } - /**+ - * Adds a value to a statistic field. - */ - public void addStat(StatBase stat, int amount) { - if (stat != null) { - if (stat.isIndependent) { - super.addStat(stat, amount); - } - - } - } - - /**+ - * Sends the player's abilities to the server (if there is one). - */ - public void sendPlayerAbilities() { - this.sendQueue.addToSendQueue(new C13PacketPlayerAbilities(this.capabilities)); - } - - /**+ - * returns true if this is an EntityPlayerSP, or the logged in - * player. - */ - public boolean isUser() { - return true; - } - - protected void sendHorseJump() { - this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.RIDING_JUMP, - (int) (this.getHorseJumpPower() * 100.0F))); - } - - public void sendHorseInventory() { - this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.OPEN_INVENTORY)); - } - - public void setClientBrand(String brand) { - this.clientBrand = brand; - } - - public String getClientBrand() { - return this.clientBrand; - } - - public StatFileWriter getStatFileWriter() { - return this.statWriter; - } - - public void addChatComponentMessage(IChatComponent chatComponent) { - this.mc.ingameGUI.getChatGUI().printChatMessage(chatComponent); - } - - protected boolean pushOutOfBlocks(double x, double y, double z) { - if (this.noClip) { - return false; - } else { - BlockPos blockpos = new BlockPos(x, y, z); - double d0 = x - (double) blockpos.getX(); - double d1 = z - (double) blockpos.getZ(); - if (!this.isOpenBlockSpace(blockpos)) { - byte b0 = -1; - double d2 = 9999.0D; - if (this.isOpenBlockSpace(blockpos.west()) && d0 < d2) { - d2 = d0; - b0 = 0; - } - - if (this.isOpenBlockSpace(blockpos.east()) && 1.0D - d0 < d2) { - d2 = 1.0D - d0; - b0 = 1; - } - - if (this.isOpenBlockSpace(blockpos.north()) && d1 < d2) { - d2 = d1; - b0 = 4; - } - - if (this.isOpenBlockSpace(blockpos.south()) && 1.0D - d1 < d2) { - d2 = 1.0D - d1; - b0 = 5; - } - - float f = 0.1F; - if (b0 == 0) { - this.motionX = (double) (-f); - } - - if (b0 == 1) { - this.motionX = (double) f; - } - - if (b0 == 4) { - this.motionZ = (double) (-f); - } - - if (b0 == 5) { - this.motionZ = (double) f; - } - } - - return false; - } - } - - /**+ - * Returns true if the block at the given BlockPos and the block - * above it are NOT full cubes. - */ - private boolean isOpenBlockSpace(BlockPos pos) { - return !this.worldObj.getBlockState(pos).getBlock().isNormalCube() - && !this.worldObj.getBlockState(pos.up()).getBlock().isNormalCube(); - } - - /**+ - * Set sprinting switch for Entity. - */ - public void setSprinting(boolean sprinting) { - super.setSprinting(sprinting); - this.sprintingTicksLeft = sprinting ? 600 : 0; - } - - /**+ - * Sets the current XP, total XP, and level number. - */ - public void setXPStats(float currentXP, int maxXP, int level) { - this.experience = currentXP; - this.experienceTotal = maxXP; - this.experienceLevel = level; - } - - /**+ - * Send a chat message to the CommandSender - */ - public void addChatMessage(IChatComponent ichatcomponent) { - this.mc.ingameGUI.getChatGUI().printChatMessage(ichatcomponent); - } - - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not - */ - public boolean canCommandSenderUseCommand(int i, String var2) { - return i <= 0; - } - - /**+ - * Get the position in the world. {@code null} is not - * allowed! If you are not an entity in the world, return - * the coordinates 0, 0, 0 - */ - public BlockPos getPosition() { - return new BlockPos(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D); - } - - public void playSound(String name, float volume, float pitch) { - this.worldObj.playSound(this.posX, this.posY, this.posZ, name, volume, pitch, false); - } - - /**+ - * Returns whether the entity is in a server world - */ - public boolean isServerWorld() { - return true; - } - - public boolean isRidingHorse() { - return this.ridingEntity != null && this.ridingEntity instanceof EntityHorse - && ((EntityHorse) this.ridingEntity).isHorseSaddled(); - } - - public float getHorseJumpPower() { - return this.horseJumpPower; - } - - public void openEditSign(TileEntitySign signTile) { - this.mc.displayGuiScreen(new GuiEditSign(signTile)); - } - - public void openEditCommandBlock(CommandBlockLogic cmdBlockLogic) { - this.mc.displayGuiScreen(new GuiCommandBlock(cmdBlockLogic)); - } - - /**+ - * Displays the GUI for interacting with a book. + /** + * + Displays the GUI for interacting with a book. */ public void displayGUIBook(ItemStack bookStack) { Item item = bookStack.getItem(); @@ -515,9 +199,9 @@ public class EntityPlayerSP extends AbstractClientPlayer { } - /**+ - * Displays the GUI for interacting with a chest inventory. - * Args: chestInventory + /** + * + Displays the GUI for interacting with a chest inventory. Args: + * chestInventory */ public void displayGUIChest(IInventory chestInventory) { String s = chestInventory instanceof IInteractionObject ? ((IInteractionObject) chestInventory).getGuiID() @@ -544,25 +228,108 @@ public class EntityPlayerSP extends AbstractClientPlayer { this.mc.displayGuiScreen(new GuiScreenHorseInventory(this.inventory, horseInventory, horse)); } - public void displayGui(IInteractionObject guiOwner) { - String s = guiOwner.getGuiID(); - if ("minecraft:crafting_table".equals(s)) { - this.mc.displayGuiScreen(new GuiCrafting(this.inventory, this.worldObj)); - } else if ("minecraft:enchanting_table".equals(s)) { - this.mc.displayGuiScreen(new GuiEnchantment(this.inventory, this.worldObj, guiOwner)); - } else if ("minecraft:anvil".equals(s)) { - this.mc.displayGuiScreen(new GuiRepair(this.inventory, this.worldObj)); - } - - } - public void displayVillagerTradeGui(IMerchant villager) { this.mc.displayGuiScreen(new GuiMerchant(this.inventory, villager, this.worldObj)); } - /**+ - * Called when the player performs a critical hit on the Entity. - * Args: entity that was hit critically + /** + * + Called when player presses the drop item key + */ + public EntityItem dropOneItem(boolean dropAll) { + C07PacketPlayerDigging.Action c07packetplayerdigging$action = dropAll + ? C07PacketPlayerDigging.Action.DROP_ALL_ITEMS + : C07PacketPlayerDigging.Action.DROP_ITEM; + this.sendQueue.addToSendQueue( + new C07PacketPlayerDigging(c07packetplayerdigging$action, BlockPos.ORIGIN, EnumFacing.DOWN)); + return null; + } + + public String getClientBrand() { + return this.clientBrand; + } + + public float getHorseJumpPower() { + return this.horseJumpPower; + } + + /** + * + Get the position in the world. {@code null} is not allowed! If you + * are not an entity in the world, return the coordinates 0, 0, 0 + */ + public BlockPos getPosition() { + return new BlockPos(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D); + } + + public StatFileWriter getStatFileWriter() { + return this.statWriter; + } + + /** + * + Heal living entity (param: amount of half-hearts) + */ + public void heal(float healAmount) { + } + + protected boolean isCurrentViewEntity() { + return this.mc.getRenderViewEntity() == this; + } + + /** + * + Returns true if the block at the given BlockPos and the block above it are + * NOT full cubes. + */ + private boolean isOpenBlockSpace(BlockPos pos) { + return !this.worldObj.getBlockState(pos).getBlock().isNormalCube() + && !this.worldObj.getBlockState(pos.up()).getBlock().isNormalCube(); + } + + public boolean isRidingHorse() { + return this.ridingEntity != null && this.ridingEntity instanceof EntityHorse + && ((EntityHorse) this.ridingEntity).isHorseSaddled(); + } + + /** + * + Returns whether the entity is in a server world + */ + public boolean isServerWorld() { + return true; + } + + /** + * + Returns if this entity is sneaking. + */ + public boolean isSneaking() { + boolean flag = this.movementInput != null ? this.movementInput.sneak : false; + return flag && !this.sleeping; + } + + /** + * + returns true if this is an EntityPlayerSP, or the logged in player. + */ + public boolean isUser() { + return true; + } + + /** + * + Joins the passed in entity item with the world. Args: entityItem + */ + protected void joinEntityItemWithWorld(EntityItem itemIn) { + } + + /** + * + Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. + */ + public void mountEntity(Entity entityIn) { + super.mountEntity(entityIn); + if (entityIn instanceof EntityMinecart) { + this.mc.getSoundHandler().playSound(new MovingSoundMinecartRiding(this, (EntityMinecart) entityIn)); + } + + } + + /** + * + Called when the player performs a critical hit on the Entity. Args: entity + * that was hit critically */ public void onCriticalHit(Entity entityHit) { this.mc.effectRenderer.emitParticleAtEntity(entityHit, EnumParticleTypes.CRIT); @@ -572,38 +339,10 @@ public class EntityPlayerSP extends AbstractClientPlayer { this.mc.effectRenderer.emitParticleAtEntity(entityHit, EnumParticleTypes.CRIT_MAGIC); } - /**+ - * Returns if this entity is sneaking. - */ - public boolean isSneaking() { - boolean flag = this.movementInput != null ? this.movementInput.sneak : false; - return flag && !this.sleeping; - } - - public void updateEntityActionState() { - super.updateEntityActionState(); - if (this.isCurrentViewEntity()) { - this.moveStrafing = this.movementInput.moveStrafe; - this.moveForward = this.movementInput.moveForward; - this.isJumping = this.movementInput.jump; - this.prevRenderArmYaw = this.renderArmYaw; - this.prevRenderArmPitch = this.renderArmPitch; - this.renderArmPitch = (float) ((double) this.renderArmPitch - + (double) (this.rotationPitch - this.renderArmPitch) * 0.5D); - this.renderArmYaw = (float) ((double) this.renderArmYaw - + (double) (this.rotationYaw - this.renderArmYaw) * 0.5D); - } - - } - - protected boolean isCurrentViewEntity() { - return this.mc.getRenderViewEntity() == this; - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (this.sprintingTicksLeft > 0) { @@ -752,4 +491,264 @@ public class EntityPlayerSP extends AbstractClientPlayer { } } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + if (this.worldObj.isBlockLoaded(new BlockPos(this.posX, 0.0D, this.posZ))) { + super.onUpdate(); + if (this.isRiding()) { + this.sendQueue.addToSendQueue( + new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, this.rotationPitch, this.onGround)); + this.sendQueue.addToSendQueue(new C0CPacketInput(this.moveStrafing, this.moveForward, + this.movementInput.jump, this.movementInput.sneak)); + } else { + this.onUpdateWalkingPlayer(); + } + + } + } + + /** + * + called every tick when the player is on foot. Performs all the things that + * normally happen during movement. + */ + public void onUpdateWalkingPlayer() { + boolean flag = this.isSprinting(); + if (flag != this.serverSprintState) { + if (flag) { + this.sendQueue + .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.START_SPRINTING)); + } else { + this.sendQueue + .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.STOP_SPRINTING)); + } + + this.serverSprintState = flag; + } + + boolean flag1 = this.isSneaking(); + if (flag1 != this.serverSneakState) { + if (flag1) { + this.sendQueue + .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.START_SNEAKING)); + } else { + this.sendQueue + .addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.STOP_SNEAKING)); + } + + this.serverSneakState = flag1; + } + + if (this.isCurrentViewEntity()) { + double d0 = this.posX - this.lastReportedPosX; + double d1 = this.getEntityBoundingBox().minY - this.lastReportedPosY; + double d2 = this.posZ - this.lastReportedPosZ; + double d3 = (double) (this.rotationYaw - this.lastReportedYaw); + double d4 = (double) (this.rotationPitch - this.lastReportedPitch); + boolean flag2 = d0 * d0 + d1 * d1 + d2 * d2 > 9.0E-4D || this.positionUpdateTicks >= 20; + boolean flag3 = d3 != 0.0D || d4 != 0.0D; + if (this.ridingEntity == null) { + if (flag2 && flag3) { + this.sendQueue.addToSendQueue( + new C03PacketPlayer.C06PacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, + this.posZ, this.rotationYaw, this.rotationPitch, this.onGround)); + } else if (flag2) { + this.sendQueue.addToSendQueue(new C03PacketPlayer.C04PacketPlayerPosition(this.posX, + this.getEntityBoundingBox().minY, this.posZ, this.onGround)); + } else if (flag3) { + this.sendQueue.addToSendQueue(new C03PacketPlayer.C05PacketPlayerLook(this.rotationYaw, + this.rotationPitch, this.onGround)); + } else { + this.sendQueue.addToSendQueue(new C03PacketPlayer(this.onGround)); + } + } else { + this.sendQueue.addToSendQueue(new C03PacketPlayer.C06PacketPlayerPosLook(this.motionX, -999.0D, + this.motionZ, this.rotationYaw, this.rotationPitch, this.onGround)); + flag2 = false; + } + + ++this.positionUpdateTicks; + if (flag2) { + this.lastReportedPosX = this.posX; + this.lastReportedPosY = this.getEntityBoundingBox().minY; + this.lastReportedPosZ = this.posZ; + this.positionUpdateTicks = 0; + } + + if (flag3) { + this.lastReportedYaw = this.rotationYaw; + this.lastReportedPitch = this.rotationPitch; + } + } + + } + + public void openEditCommandBlock(CommandBlockLogic cmdBlockLogic) { + this.mc.displayGuiScreen(new GuiCommandBlock(cmdBlockLogic)); + } + + public void openEditSign(TileEntitySign signTile) { + this.mc.displayGuiScreen(new GuiEditSign(signTile)); + } + + public void playSound(String name, float volume, float pitch) { + this.worldObj.playSound(this.posX, this.posY, this.posZ, name, volume, pitch, false); + } + + protected boolean pushOutOfBlocks(double x, double y, double z) { + if (this.noClip) { + return false; + } else { + BlockPos blockpos = new BlockPos(x, y, z); + double d0 = x - (double) blockpos.getX(); + double d1 = z - (double) blockpos.getZ(); + if (!this.isOpenBlockSpace(blockpos)) { + byte b0 = -1; + double d2 = 9999.0D; + if (this.isOpenBlockSpace(blockpos.west()) && d0 < d2) { + d2 = d0; + b0 = 0; + } + + if (this.isOpenBlockSpace(blockpos.east()) && 1.0D - d0 < d2) { + d2 = 1.0D - d0; + b0 = 1; + } + + if (this.isOpenBlockSpace(blockpos.north()) && d1 < d2) { + d2 = d1; + b0 = 4; + } + + if (this.isOpenBlockSpace(blockpos.south()) && 1.0D - d1 < d2) { + d2 = 1.0D - d1; + b0 = 5; + } + + float f = 0.1F; + if (b0 == 0) { + this.motionX = (double) (-f); + } + + if (b0 == 1) { + this.motionX = (double) f; + } + + if (b0 == 4) { + this.motionZ = (double) (-f); + } + + if (b0 == 5) { + this.motionZ = (double) f; + } + } + + return false; + } + } + + public void respawnPlayer() { + this.sendQueue.addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN)); + } + + /** + * + Sends a chat message from the player. Args: chatMessage + */ + public void sendChatMessage(String message) { + if (((sendQueue.getNetworkManager() instanceof ClientIntegratedServerNetworkManager) + || (sendQueue.getNetworkManager() instanceof LANClientNetworkManager)) + && message.startsWith("/eagskull")) { + this.mc.eagskullCommand.openFileChooser(); + } else { + this.sendQueue.addToSendQueue(new C01PacketChatMessage(message)); + } + } + + public void sendHorseInventory() { + this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.OPEN_INVENTORY)); + } + + protected void sendHorseJump() { + this.sendQueue.addToSendQueue(new C0BPacketEntityAction(this, C0BPacketEntityAction.Action.RIDING_JUMP, + (int) (this.getHorseJumpPower() * 100.0F))); + } + + /** + * + Sends the player's abilities to the server (if there is one). + */ + public void sendPlayerAbilities() { + this.sendQueue.addToSendQueue(new C13PacketPlayerAbilities(this.capabilities)); + } + + public void setClientBrand(String brand) { + this.clientBrand = brand; + } + + /** + * + Updates health locally. + */ + public void setPlayerSPHealth(float health) { + if (this.hasValidHealth) { + float f = this.getHealth() - health; + if (f <= 0.0F) { + this.setHealth(health); + if (f < 0.0F) { + this.hurtResistantTime = this.maxHurtResistantTime / 2; + } + } else { + this.lastDamage = f; + this.setHealth(this.getHealth()); + this.hurtResistantTime = this.maxHurtResistantTime; + this.damageEntity(DamageSource.generic, f); + this.hurtTime = this.maxHurtTime = 10; + } + } else { + this.setHealth(health); + this.hasValidHealth = true; + } + + } + + /** + * + Set sprinting switch for Entity. + */ + public void setSprinting(boolean sprinting) { + super.setSprinting(sprinting); + this.sprintingTicksLeft = sprinting ? 600 : 0; + } + + /** + * + Sets the current XP, total XP, and level number. + */ + public void setXPStats(float currentXP, int maxXP, int level) { + this.experience = currentXP; + this.experienceTotal = maxXP; + this.experienceLevel = level; + } + + /** + * + Swings the item the player is holding. + */ + public void swingItem() { + super.swingItem(); + this.sendQueue.addToSendQueue(new C0APacketAnimation()); + } + + public void updateEntityActionState() { + super.updateEntityActionState(); + if (this.isCurrentViewEntity()) { + this.moveStrafing = this.movementInput.moveStrafe; + this.moveForward = this.movementInput.moveForward; + this.isJumping = this.movementInput.jump; + this.prevRenderArmYaw = this.renderArmYaw; + this.prevRenderArmPitch = this.renderArmPitch; + this.renderArmPitch = (float) ((double) this.renderArmPitch + + (double) (this.rotationPitch - this.renderArmPitch) * 0.5D); + this.renderArmYaw = (float) ((double) this.renderArmYaw + + (double) (this.rotationYaw - this.renderArmYaw) * 0.5D); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/ChatLine.java b/src/game/java/net/minecraft/client/gui/ChatLine.java index a8d20efe..b2649cba 100644 --- a/src/game/java/net/minecraft/client/gui/ChatLine.java +++ b/src/game/java/net/minecraft/client/gui/ChatLine.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.profanity_filter.ProfanityFilter; import net.minecraft.client.Minecraft; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,11 +50,11 @@ public class ChatLine { } } - public int getUpdatedCounter() { - return this.updateCounterCreated; - } - public int getChatLineID() { return this.chatLineID; } + + public int getUpdatedCounter() { + return this.updateCounterCreated; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/FontRenderer.java b/src/game/java/net/minecraft/client/gui/FontRenderer.java index 6408bc9a..d8f44c8f 100644 --- a/src/game/java/net/minecraft/client/gui/FontRenderer.java +++ b/src/game/java/net/minecraft/client/gui/FontRenderer.java @@ -4,8 +4,8 @@ import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.HString; import net.lax1dude.eaglercraft.v1_8.IOUtils; import net.lax1dude.eaglercraft.v1_8.minecraft.FontMappingHelper; @@ -22,46 +22,101 @@ import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.client.settings.GameSettings; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FontRenderer implements IResourceManagerReloadListener { protected static final ResourceLocation[] unicodePageLocations = new ResourceLocation[256]; - /**+ - * Array of width of all the characters in default.png + protected static char[] codepointLookup = new char[] { 192, 193, 194, 200, 202, 203, 205, 211, 212, 213, 218, 223, + 227, 245, 287, 304, 305, 338, 339, 350, 351, 372, 373, 382, 519, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, + 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, + 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, + 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, + 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 199, 252, 233, 226, 228, 224, 229, 231, + 234, 235, 232, 239, 238, 236, 196, 197, 201, 230, 198, 244, 246, 242, 251, 249, 255, 214, 220, 248, 163, + 216, 215, 402, 225, 237, 243, 250, 241, 209, 170, 186, 191, 174, 172, 189, 188, 161, 171, 187, 9617, 9618, + 9619, 9474, 9508, 9569, 9570, 9558, 9557, 9571, 9553, 9559, 9565, 9564, 9563, 9488, 9492, 9524, 9516, 9500, + 9472, 9532, 9566, 9567, 9562, 9556, 9577, 9574, 9568, 9552, 9580, 9575, 9576, 9572, 9573, 9561, 9560, 9554, + 9555, 9579, 9578, 9496, 9484, 9608, 9604, 9612, 9616, 9600, 945, 946, 915, 960, 931, 963, 956, 964, 934, + 920, 937, 948, 8734, 8709, 8712, 8745, 8801, 177, 8805, 8804, 8992, 8993, 247, 8776, 176, 8729, 183, 8730, + 8319, 178, 9632, 0 }; + + /** + * + Digests a string for nonprinting formatting characters then returns a + * string containing only that formatting. + */ + public static String getFormatFromString(String text) { + String s = ""; + int i = -1; + int j = text.length(); + + while ((i = text.indexOf(167, i + 1)) != -1) { + if (i < j - 1) { + char c0 = text.charAt(i + 1); + if (isFormatColor(c0)) { + s = "\u00a7" + c0; + } else if (isFormatSpecial(c0)) { + s = s + "\u00a7" + c0; + } + } + } + + return s; + } + + /** + * + Checks if the char code is a hexadecimal character, used to set colour. + */ + private static boolean isFormatColor(char colorChar) { + return colorChar >= 48 && colorChar <= 57 || colorChar >= 97 && colorChar <= 102 + || colorChar >= 65 && colorChar <= 70; + } + + /** + * + Checks if the char code is O-K...lLrRk-o... used to set special formatting. + */ + private static boolean isFormatSpecial(char formatChar) { + return formatChar >= 107 && formatChar <= 111 || formatChar >= 75 && formatChar <= 79 || formatChar == 114 + || formatChar == 82; + } + + /** + * + Array of width of all the characters in default.png */ protected int[] charWidth = new int[256]; - /**+ - * the height in pixels of default text + /** + * + the height in pixels of default text */ public int FONT_HEIGHT = 9; public EaglercraftRandom fontRandom = new EaglercraftRandom(); - /**+ - * Array of the start/end column (in upper/lower nibble) for - * every glyph in the /font directory. + /** + * + Array of the start/end column (in upper/lower nibble) for every glyph in + * the /font directory. */ protected byte[] glyphWidth = new byte[65536]; - /**+ - * Array of RGB triplets defining the 16 standard chat colors - * followed by 16 darker version of the same colors for drop - * shadows. + /** + * + Array of RGB triplets defining the 16 standard chat colors followed by 16 + * darker version of the same colors for drop shadows. */ protected int[] colorCode = new int[32]; protected final ResourceLocation locationFontTexture; @@ -76,24 +131,14 @@ public class FontRenderer implements IResourceManagerReloadListener { protected float alpha; protected int textColor; protected boolean randomStyle; - protected boolean boldStyle; - protected boolean italicStyle; - protected boolean underlineStyle; - protected boolean strikethroughStyle; - protected static char[] codepointLookup = new char[] { 192, 193, 194, 200, 202, 203, 205, 211, 212, 213, 218, 223, - 227, 245, 287, 304, 305, 338, 339, 350, 351, 372, 373, 382, 519, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, - 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, - 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, - 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, - 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 199, 252, 233, 226, 228, 224, 229, 231, - 234, 235, 232, 239, 238, 236, 196, 197, 201, 230, 198, 244, 246, 242, 251, 249, 255, 214, 220, 248, 163, - 216, 215, 402, 225, 237, 243, 250, 241, 209, 170, 186, 191, 174, 172, 189, 188, 161, 171, 187, 9617, 9618, - 9619, 9474, 9508, 9569, 9570, 9558, 9557, 9571, 9553, 9559, 9565, 9564, 9563, 9488, 9492, 9524, 9516, 9500, - 9472, 9532, 9566, 9567, 9562, 9556, 9577, 9574, 9568, 9552, 9580, 9575, 9576, 9572, 9573, 9561, 9560, 9554, - 9555, 9579, 9578, 9496, 9484, 9608, 9604, 9612, 9616, 9600, 945, 946, 915, 960, 931, 963, 956, 964, 934, - 920, 937, 948, 8734, 8709, 8712, 8745, 8801, 177, 8805, 8804, 8992, 8993, 247, 8776, 176, 8729, 183, 8730, - 8319, 178, 9632, 0 }; + protected boolean boldStyle; + + protected boolean italicStyle; + + protected boolean underlineStyle; + + protected boolean strikethroughStyle; public FontRenderer(GameSettings gameSettingsIn, ResourceLocation location, TextureManager textureManagerIn, boolean unicode) { @@ -132,6 +177,185 @@ public class FontRenderer implements IResourceManagerReloadListener { this.readGlyphSizes(); } + /** + * + Apply Unicode Bidirectional Algorithm to string and return a new possibly + * reordered string for visual rendering. + */ + private String bidiReorder(String parString1) { +// try { +// Bidi bidi = new Bidi((new ArabicShaping(8)).shape(parString1), 127); +// bidi.setReorderingMode(0); +// return bidi.writeReordered(2); +// } catch (ArabicShapingException var3) { +// return parString1; +// } + return parString1; + } + + /** + * + Splits and draws a String with wordwrap (maximum length is parameter k) + */ + public void drawSplitString(String str, int x, int y, int wrapWidth, int textColor) { + this.resetStyles(); + if ((textColor & -67108864) == 0) { + textColor |= -16777216; + } + this.textColor = textColor; + str = this.trimStringNewline(str); + this.renderSplitString(str, x, y, wrapWidth, false); + } + + /** + * + Draws the specified string. + */ + public int drawString(String text, float x, float y, int color, boolean dropShadow) { + GlStateManager.enableAlpha(); + this.resetStyles(); + int i; + if (dropShadow) { + i = this.renderString(text, x + 1.0F, y + 1.0F, color, true); + i = Math.max(i, this.renderString(text, x, y, color, false)); + } else { + i = this.renderString(text, x, y, color, false); + } + + return i; + } + + /** + * + Draws the specified string. + */ + public int drawString(String text, int x, int y, int color) { + return this.drawString(text, (float) x, (float) y, color, false); + } + + /** + * + Draws the specified string with a shadow. + */ + public int drawStringWithShadow(String text, float x, float y, int color) { + return this.drawString(text, x, y, color, true); + } + + private float func_181559_a(char parChar1, boolean parFlag) { + if (parChar1 == 32) { + return 4.0F; + } else { + int i = FontMappingHelper.lookupChar(parChar1, false); + return i != -1 && !this.unicodeFlag ? this.renderDefaultChar(i, parFlag) + : this.renderUnicodeChar(parChar1, parFlag); + } + } + + /** + * + Get bidiFlag that controls if the Unicode Bidirectional Algorithm should be + * run before rendering any string + */ + public boolean getBidiFlag() { + return this.bidiFlag; + } + + /** + * + Returns the width of this character as rendered. + */ + public int getCharWidth(char character) { + if (character == 167) { + return -1; + } else if (character == 32) { + return 4; + } else { + int i = FontMappingHelper.lookupChar(character, false); + if (character > 0 && i != -1 && !this.unicodeFlag) { + return this.charWidth[i]; + } else if (this.glyphWidth[character] != 0) { + int j = this.glyphWidth[character] >>> 4; + int k = this.glyphWidth[character] & 15; + if (k > 7) { + k = 15; + j = 0; + } + + ++k; + return (k - j) / 2 + 1; + } else { + return 0; + } + } + } + + public int getColorCode(char character) { + return this.colorCode["0123456789abcdef".indexOf(character)]; + } + + /** + * + Returns the width of this string. Equivalent of + * FontMetrics.stringWidth(String s). + */ + public int getStringWidth(String text) { + if (text == null) { + return 0; + } else { + int i = 0; + boolean flag = false; + + for (int j = 0; j < text.length(); ++j) { + char c0 = text.charAt(j); + int k = this.getCharWidth(c0); + if (k < 0 && j < text.length() - 1) { + ++j; + c0 = text.charAt(j); + if (c0 != 108 && c0 != 76) { + if (c0 == 114 || c0 == 82) { + flag = false; + } + } else { + flag = true; + } + + k = 0; + } + + i += k; + if (flag && k > 0) { + ++i; + } + } + + return i; + } + } + + /** + * + Get unicodeFlag controlling whether strings should be rendered with Unicode + * fonts instead of the default.png font. + */ + public boolean getUnicodeFlag() { + return this.unicodeFlag; + } + + private ResourceLocation getUnicodePageLocation(int parInt1) { + if (unicodePageLocations[parInt1] == null) { + unicodePageLocations[parInt1] = new ResourceLocation( + HString.format("textures/font/unicode_page_%02x.png", new Object[] { Integer.valueOf(parInt1) })); + } + + return unicodePageLocations[parInt1]; + } + + /** + * + Breaks a string into a list of pieces that will fit a specified width. + */ + public List listFormattedStringToWidth(String str, int wrapWidth) { + return Arrays.asList(this.wrapFormattedStringToWidth(str, wrapWidth, 0).split("\n")); + } + + /** + * + Load one of the /font/glyph_XX.png into a new GL texture and store the + * texture ID in glyphTextureName array. + */ + private void loadGlyphTexture(int parInt1) { + this.renderEngine.bindTexture(this.getUnicodePageLocation(parInt1)); + } + public void onResourceManagerReload(IResourceManager resourceManager) { this.readFontTexture(); } @@ -198,19 +422,9 @@ public class FontRenderer implements IResourceManagerReloadListener { } - private float func_181559_a(char parChar1, boolean parFlag) { - if (parChar1 == 32) { - return 4.0F; - } else { - int i = FontMappingHelper.lookupChar(parChar1, false); - return i != -1 && !this.unicodeFlag ? this.renderDefaultChar(i, parFlag) - : this.renderUnicodeChar(parChar1, parFlag); - } - } - - /**+ - * Render a single character with the default.png font at - * current (posX,posY) location... + /** + * + Render a single character with the default.png font at current (posX,posY) + * location... */ private float renderDefaultChar(int parInt1, boolean parFlag) { int i = parInt1 % 16 * 8; @@ -241,124 +455,66 @@ public class FontRenderer implements IResourceManagerReloadListener { return (float) l; } - private ResourceLocation getUnicodePageLocation(int parInt1) { - if (unicodePageLocations[parInt1] == null) { - unicodePageLocations[parInt1] = new ResourceLocation( - HString.format("textures/font/unicode_page_%02x.png", new Object[] { Integer.valueOf(parInt1) })); + /** + * + Perform actual work of rendering a multi-line string with wordwrap and with + * darker drop shadow color if flag is set + */ + private void renderSplitString(String str, int x, int y, int wrapWidth, boolean addShadow) { + List lst = this.listFormattedStringToWidth(str, wrapWidth); + for (int i = 0, l = lst.size(); i < l; ++i) { + this.renderStringAligned(lst.get(i), x, y, wrapWidth, this.textColor, addShadow); + y += this.FONT_HEIGHT; } - return unicodePageLocations[parInt1]; } - /**+ - * Load one of the /font/glyph_XX.png into a new GL texture and - * store the texture ID in glyphTextureName array. + /** + * + Render single line string by setting GL color, current (posX,posY), and + * calling renderStringAtPos() */ - private void loadGlyphTexture(int parInt1) { - this.renderEngine.bindTexture(this.getUnicodePageLocation(parInt1)); - } - - /**+ - * Render a single Unicode character at current (posX,posY) - * location using one of the /font/glyph_XX.png files... - */ - private float renderUnicodeChar(char parChar1, boolean parFlag) { - if (this.glyphWidth[parChar1] == 0) { - return 0.0F; + private int renderString(String text, float x, float y, int color, boolean dropShadow) { + if (text == null) { + this.posX = x; + this.posY = y; } else { - int i = parChar1 / 256; - this.loadGlyphTexture(i); - int j = this.glyphWidth[parChar1] >>> 4; - int k = this.glyphWidth[parChar1] & 15; - float f = (float) j; - float f1 = (float) (k + 1); - float f2 = (float) (parChar1 % 16 * 16) + f; - float f3 = (float) ((parChar1 & 255) / 16 * 16); - float f4 = f1 - f - 0.02F; - float f5 = parFlag ? 1.0F : 0.0F; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + if (this.bidiFlag) { + text = this.bidiReorder(text); + } - worldrenderer.begin(Tessellator.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION_TEX); + if ((color & -67108864) == 0) { + color |= -16777216; + } - worldrenderer.pos(this.posX + f5, this.posY, 0.0F).tex(f2 / 256.0F, f3 / 256.0F).endVertex(); + if (dropShadow) { + color = (color & 16579836) >> 2 | color & -16777216; + } - worldrenderer.pos(this.posX - f5, this.posY + 7.99F, 0.0F).tex(f2 / 256.0F, (f3 + 15.98F) / 256.0F) - .endVertex(); - - worldrenderer.pos(this.posX + f4 / 2.0F + f5, this.posY, 0.0F).tex((f2 + f4) / 256.0F, f3 / 256.0F) - .endVertex(); - - worldrenderer.pos(this.posX + f4 / 2.0F - f5, this.posY + 7.99F, 0.0F) - .tex((f2 + f4) / 256.0F, (f3 + 15.98F) / 256.0F).endVertex(); - - tessellator.draw(); - - return (f1 - f) / 2.0F + 1.0F; + this.red = (float) (color >> 16 & 255) / 255.0F; + this.blue = (float) (color >> 8 & 255) / 255.0F; + this.green = (float) (color & 255) / 255.0F; + this.alpha = (float) (color >> 24 & 255) / 255.0F; + GlStateManager.color(this.red, this.blue, this.green, this.alpha); + this.posX = x; + this.posY = y; + this.renderStringAtPos(text, dropShadow); } + return (int) this.posX; } - /**+ - * Draws the specified string with a shadow. + /** + * + Render string either left or right aligned depending on bidiFlag */ - public int drawStringWithShadow(String text, float x, float y, int color) { - return this.drawString(text, x, y, color, true); - } - - /**+ - * Draws the specified string. - */ - public int drawString(String text, int x, int y, int color) { - return this.drawString(text, (float) x, (float) y, color, false); - } - - /**+ - * Draws the specified string. - */ - public int drawString(String text, float x, float y, int color, boolean dropShadow) { - GlStateManager.enableAlpha(); - this.resetStyles(); - int i; - if (dropShadow) { - i = this.renderString(text, x + 1.0F, y + 1.0F, color, true); - i = Math.max(i, this.renderString(text, x, y, color, false)); - } else { - i = this.renderString(text, x, y, color, false); + private int renderStringAligned(String text, int x, int y, int wrapWidth, int color, boolean parFlag) { + if (this.bidiFlag) { + int i = this.getStringWidth(this.bidiReorder(text)); + x = x + wrapWidth - i; } - return i; + return this.renderString(text, (float) x, (float) y, color, parFlag); } - /**+ - * Apply Unicode Bidirectional Algorithm to string and return a - * new possibly reordered string for visual rendering. - */ - private String bidiReorder(String parString1) { -// try { -// Bidi bidi = new Bidi((new ArabicShaping(8)).shape(parString1), 127); -// bidi.setReorderingMode(0); -// return bidi.writeReordered(2); -// } catch (ArabicShapingException var3) { -// return parString1; -// } - return parString1; - } - - /**+ - * Reset all style flag fields in the class to false; called at - * the start of string rendering - */ - protected void resetStyles() { - this.randomStyle = false; - this.boldStyle = false; - this.italicStyle = false; - this.underlineStyle = false; - this.strikethroughStyle = false; - } - - /**+ - * Render a single line string at the current (posX,posY) and - * update posX + /** + * + Render a single line string at the current (posX,posY) and update posX */ protected void renderStringAtPos(String parString1, boolean parFlag) { for (int i = 0; i < parString1.length(); ++i) { @@ -495,272 +651,77 @@ public class FontRenderer implements IResourceManagerReloadListener { } - /**+ - * Render string either left or right aligned depending on - * bidiFlag + /** + * + Render a single Unicode character at current (posX,posY) location using one + * of the /font/glyph_XX.png files... */ - private int renderStringAligned(String text, int x, int y, int wrapWidth, int color, boolean parFlag) { - if (this.bidiFlag) { - int i = this.getStringWidth(this.bidiReorder(text)); - x = x + wrapWidth - i; - } - - return this.renderString(text, (float) x, (float) y, color, parFlag); - } - - /**+ - * Render single line string by setting GL color, current - * (posX,posY), and calling renderStringAtPos() - */ - private int renderString(String text, float x, float y, int color, boolean dropShadow) { - if (text == null) { - this.posX = x; - this.posY = y; + private float renderUnicodeChar(char parChar1, boolean parFlag) { + if (this.glyphWidth[parChar1] == 0) { + return 0.0F; } else { - if (this.bidiFlag) { - text = this.bidiReorder(text); - } + int i = parChar1 / 256; + this.loadGlyphTexture(i); + int j = this.glyphWidth[parChar1] >>> 4; + int k = this.glyphWidth[parChar1] & 15; + float f = (float) j; + float f1 = (float) (k + 1); + float f2 = (float) (parChar1 % 16 * 16) + f; + float f3 = (float) ((parChar1 & 255) / 16 * 16); + float f4 = f1 - f - 0.02F; + float f5 = parFlag ? 1.0F : 0.0F; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - if ((color & -67108864) == 0) { - color |= -16777216; - } + worldrenderer.begin(Tessellator.GL_TRIANGLE_STRIP, DefaultVertexFormats.POSITION_TEX); - if (dropShadow) { - color = (color & 16579836) >> 2 | color & -16777216; - } + worldrenderer.pos(this.posX + f5, this.posY, 0.0F).tex(f2 / 256.0F, f3 / 256.0F).endVertex(); - this.red = (float) (color >> 16 & 255) / 255.0F; - this.blue = (float) (color >> 8 & 255) / 255.0F; - this.green = (float) (color & 255) / 255.0F; - this.alpha = (float) (color >> 24 & 255) / 255.0F; - GlStateManager.color(this.red, this.blue, this.green, this.alpha); - this.posX = x; - this.posY = y; - this.renderStringAtPos(text, dropShadow); - } - return (int) this.posX; - } + worldrenderer.pos(this.posX - f5, this.posY + 7.99F, 0.0F).tex(f2 / 256.0F, (f3 + 15.98F) / 256.0F) + .endVertex(); - /**+ - * Returns the width of this string. Equivalent of - * FontMetrics.stringWidth(String s). - */ - public int getStringWidth(String text) { - if (text == null) { - return 0; - } else { - int i = 0; - boolean flag = false; + worldrenderer.pos(this.posX + f4 / 2.0F + f5, this.posY, 0.0F).tex((f2 + f4) / 256.0F, f3 / 256.0F) + .endVertex(); - for (int j = 0; j < text.length(); ++j) { - char c0 = text.charAt(j); - int k = this.getCharWidth(c0); - if (k < 0 && j < text.length() - 1) { - ++j; - c0 = text.charAt(j); - if (c0 != 108 && c0 != 76) { - if (c0 == 114 || c0 == 82) { - flag = false; - } - } else { - flag = true; - } + worldrenderer.pos(this.posX + f4 / 2.0F - f5, this.posY + 7.99F, 0.0F) + .tex((f2 + f4) / 256.0F, (f3 + 15.98F) / 256.0F).endVertex(); - k = 0; - } + tessellator.draw(); - i += k; - if (flag && k > 0) { - ++i; - } - } - - return i; + return (f1 - f) / 2.0F + 1.0F; } } - /**+ - * Returns the width of this character as rendered. + /** + * + Reset all style flag fields in the class to false; called at the start of + * string rendering */ - public int getCharWidth(char character) { - if (character == 167) { - return -1; - } else if (character == 32) { - return 4; - } else { - int i = FontMappingHelper.lookupChar(character, false); - if (character > 0 && i != -1 && !this.unicodeFlag) { - return this.charWidth[i]; - } else if (this.glyphWidth[character] != 0) { - int j = this.glyphWidth[character] >>> 4; - int k = this.glyphWidth[character] & 15; - if (k > 7) { - k = 15; - j = 0; - } - - ++k; - return (k - j) / 2 + 1; - } else { - return 0; - } - } + protected void resetStyles() { + this.randomStyle = false; + this.boldStyle = false; + this.italicStyle = false; + this.underlineStyle = false; + this.strikethroughStyle = false; } - /**+ - * Trims a string to fit a specified Width. - */ - public String trimStringToWidth(String text, int width) { - return this.trimStringToWidth(text, width, false); - } - - /**+ - * Trims a string to fit a specified Width. - */ - public String trimStringToWidth(String text, int width, boolean reverse) { - StringBuilder stringbuilder = new StringBuilder(); - int i = 0; - int j = reverse ? text.length() - 1 : 0; - int k = reverse ? -1 : 1; - boolean flag = false; - boolean flag1 = false; - - for (int l = j; l >= 0 && l < text.length() && i < width; l += k) { - char c0 = text.charAt(l); - int i1 = this.getCharWidth(c0); - if (flag) { - flag = false; - if (c0 != 108 && c0 != 76) { - if (c0 == 114 || c0 == 82) { - flag1 = false; - } - } else { - flag1 = true; - } - } else if (i1 < 0) { - flag = true; - } else { - i += i1; - if (flag1) { - ++i; - } - } - - if (i > width) { - break; - } - - if (reverse) { - stringbuilder.insert(0, c0); - } else { - stringbuilder.append(c0); - } - } - - return stringbuilder.toString(); - } - - /**+ - * Remove all newline characters from the end of the string - */ - private String trimStringNewline(String text) { - while (text != null && text.endsWith("\n")) { - text = text.substring(0, text.length() - 1); - } - - return text; - } - - /**+ - * Splits and draws a String with wordwrap (maximum length is - * parameter k) - */ - public void drawSplitString(String str, int x, int y, int wrapWidth, int textColor) { - this.resetStyles(); - if ((textColor & -67108864) == 0) { - textColor |= -16777216; - } - this.textColor = textColor; - str = this.trimStringNewline(str); - this.renderSplitString(str, x, y, wrapWidth, false); - } - - /**+ - * Perform actual work of rendering a multi-line string with - * wordwrap and with darker drop shadow color if flag is set - */ - private void renderSplitString(String str, int x, int y, int wrapWidth, boolean addShadow) { - List lst = this.listFormattedStringToWidth(str, wrapWidth); - for (int i = 0, l = lst.size(); i < l; ++i) { - this.renderStringAligned(lst.get(i), x, y, wrapWidth, this.textColor, addShadow); - y += this.FONT_HEIGHT; - } - - } - - /**+ - * Returns the width of the wordwrapped String (maximum length - * is parameter k) - */ - public int splitStringWidth(String parString1, int parInt1) { - return this.FONT_HEIGHT * this.listFormattedStringToWidth(parString1, parInt1).size(); - } - - /**+ - * Set unicodeFlag controlling whether strings should be - * rendered with Unicode fonts instead of the default.png font. - */ - public void setUnicodeFlag(boolean unicodeFlagIn) { - this.unicodeFlag = unicodeFlagIn; - } - - /**+ - * Get unicodeFlag controlling whether strings should be - * rendered with Unicode fonts instead of the default.png font. - */ - public boolean getUnicodeFlag() { - return this.unicodeFlag; - } - - /**+ - * Set bidiFlag to control if the Unicode Bidirectional - * Algorithm should be run before rendering any string. + /** + * + Set bidiFlag to control if the Unicode Bidirectional Algorithm should be + * run before rendering any string. */ public void setBidiFlag(boolean bidiFlagIn) { this.bidiFlag = bidiFlagIn; } - /**+ - * Breaks a string into a list of pieces that will fit a - * specified width. + /** + * + Set unicodeFlag controlling whether strings should be rendered with Unicode + * fonts instead of the default.png font. */ - public List listFormattedStringToWidth(String str, int wrapWidth) { - return Arrays.asList(this.wrapFormattedStringToWidth(str, wrapWidth, 0).split("\n")); + public void setUnicodeFlag(boolean unicodeFlagIn) { + this.unicodeFlag = unicodeFlagIn; } - /**+ - * Inserts newline and formatting into a string to wrap it - * within the specified width. - */ - String wrapFormattedStringToWidth(String str, int wrapWidth, int depthCheck) { // TODO: fix recursive - if (depthCheck > 20) { - return str; - } - int i = this.sizeStringToWidth(str, wrapWidth); - if (str.length() <= i) { - return str; - } else { - String s = str.substring(0, i); - char c0 = str.charAt(i); - boolean flag = c0 == 32 || c0 == 10; - String s1 = getFormatFromString(s) + str.substring(i + (flag ? 1 : 0)); - return s + "\n" + this.wrapFormattedStringToWidth(s1, wrapWidth, ++depthCheck); - } - } - - /**+ - * Determines how many characters from the string will fit into - * the specified width. + /** + * + Determines how many characters from the string will fit into the specified + * width. */ private int sizeStringToWidth(String str, int wrapWidth) { int i = str.length(); @@ -810,56 +771,94 @@ public class FontRenderer implements IResourceManagerReloadListener { return k != i && l != -1 && l < k ? l : k; } - /**+ - * Checks if the char code is a hexadecimal character, used to - * set colour. + /** + * + Returns the width of the wordwrapped String (maximum length is parameter k) */ - private static boolean isFormatColor(char colorChar) { - return colorChar >= 48 && colorChar <= 57 || colorChar >= 97 && colorChar <= 102 - || colorChar >= 65 && colorChar <= 70; + public int splitStringWidth(String parString1, int parInt1) { + return this.FONT_HEIGHT * this.listFormattedStringToWidth(parString1, parInt1).size(); } - /**+ - * Checks if the char code is O-K...lLrRk-o... used to set - * special formatting. + /** + * + Remove all newline characters from the end of the string */ - private static boolean isFormatSpecial(char formatChar) { - return formatChar >= 107 && formatChar <= 111 || formatChar >= 75 && formatChar <= 79 || formatChar == 114 - || formatChar == 82; + private String trimStringNewline(String text) { + while (text != null && text.endsWith("\n")) { + text = text.substring(0, text.length() - 1); + } + + return text; } - /**+ - * Digests a string for nonprinting formatting characters then - * returns a string containing only that formatting. + /** + * + Trims a string to fit a specified Width. */ - public static String getFormatFromString(String text) { - String s = ""; - int i = -1; - int j = text.length(); + public String trimStringToWidth(String text, int width) { + return this.trimStringToWidth(text, width, false); + } - while ((i = text.indexOf(167, i + 1)) != -1) { - if (i < j - 1) { - char c0 = text.charAt(i + 1); - if (isFormatColor(c0)) { - s = "\u00a7" + c0; - } else if (isFormatSpecial(c0)) { - s = s + "\u00a7" + c0; + /** + * + Trims a string to fit a specified Width. + */ + public String trimStringToWidth(String text, int width, boolean reverse) { + StringBuilder stringbuilder = new StringBuilder(); + int i = 0; + int j = reverse ? text.length() - 1 : 0; + int k = reverse ? -1 : 1; + boolean flag = false; + boolean flag1 = false; + + for (int l = j; l >= 0 && l < text.length() && i < width; l += k) { + char c0 = text.charAt(l); + int i1 = this.getCharWidth(c0); + if (flag) { + flag = false; + if (c0 != 108 && c0 != 76) { + if (c0 == 114 || c0 == 82) { + flag1 = false; + } + } else { + flag1 = true; } + } else if (i1 < 0) { + flag = true; + } else { + i += i1; + if (flag1) { + ++i; + } + } + + if (i > width) { + break; + } + + if (reverse) { + stringbuilder.insert(0, c0); + } else { + stringbuilder.append(c0); } } - return s; + return stringbuilder.toString(); } - /**+ - * Get bidiFlag that controls if the Unicode Bidirectional - * Algorithm should be run before rendering any string + /** + * + Inserts newline and formatting into a string to wrap it within the + * specified width. */ - public boolean getBidiFlag() { - return this.bidiFlag; - } - - public int getColorCode(char character) { - return this.colorCode["0123456789abcdef".indexOf(character)]; + String wrapFormattedStringToWidth(String str, int wrapWidth, int depthCheck) { // TODO: fix recursive + if (depthCheck > 20) { + return str; + } + int i = this.sizeStringToWidth(str, wrapWidth); + if (str.length() <= i) { + return str; + } else { + String s = str.substring(0, i); + char c0 = str.charAt(i); + boolean flag = c0 == 32 || c0 == 10; + String s1 = getFormatFromString(s) + str.substring(i + (flag ? 1 : 0)); + return s + "\n" + this.wrapFormattedStringToWidth(s1, wrapWidth, ++depthCheck); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/Gui.java b/src/game/java/net/minecraft/client/gui/Gui.java index 48d1d725..f1e7fa85 100644 --- a/src/game/java/net/minecraft/client/gui/Gui.java +++ b/src/game/java/net/minecraft/client/gui/Gui.java @@ -1,6 +1,9 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -9,22 +12,25 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,37 +40,31 @@ public class Gui { "textures/gui/options_background.png"); public static final ResourceLocation statIcons = new ResourceLocation("textures/gui/container/stats_icons.png"); public static final ResourceLocation icons = new ResourceLocation("textures/gui/icons.png"); - protected float zLevel; - /**+ - * Draw a 1 pixel wide horizontal line. Args: x1, x2, y, color + /** + * + Draws a textured rectangle at z = 0. Args: x, y, u, v, width, height, + * textureWidth, textureHeight */ - protected void drawHorizontalLine(int startX, int endX, int y, int color) { - if (endX < startX) { - int i = startX; - startX = endX; - endX = i; - } - - drawRect(startX, y, endX + 1, y + 1, color); + public static void drawModalRectWithCustomSizedTexture(int x, int y, float u, float v, int width, int height, + float textureWidth, float textureHeight) { + float f = 1.0F / textureWidth; + float f1 = 1.0F / textureHeight; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) x, (double) (y + height), 0.0D) + .tex((double) (u * f), (double) ((v + (float) height) * f1)).endVertex(); + worldrenderer.pos((double) (x + width), (double) (y + height), 0.0D) + .tex((double) ((u + (float) width) * f), (double) ((v + (float) height) * f1)).endVertex(); + worldrenderer.pos((double) (x + width), (double) y, 0.0D) + .tex((double) ((u + (float) width) * f), (double) (v * f1)).endVertex(); + worldrenderer.pos((double) x, (double) y, 0.0D).tex((double) (u * f), (double) (v * f1)).endVertex(); + tessellator.draw(); } - /**+ - * Draw a 1 pixel wide vertical line. Args : x, y1, y2, color - */ - protected void drawVerticalLine(int x, int startY, int endY, int color) { - if (endY < startY) { - int i = startY; - startY = endY; - endY = i; - } - - drawRect(x, startY + 1, x + 1, endY, color); - } - - /**+ - * Draws a solid color rectangle with the specified coordinates - * and color (ARGB format). Args: x1, y1, x2, y2, color + /** + * + Draws a solid color rectangle with the specified coordinates and color + * (ARGB format). Args: x1, y1, x2, y2, color */ public static void drawRect(int left, int top, int right, int bottom, int color) { if (left < right) { @@ -99,10 +99,41 @@ public class Gui { GlStateManager.disableBlend(); } - /**+ - * Draws a rectangle with a vertical gradient between the - * specified colors (ARGB format). Args : x1, y1, x2, y2, - * topColor, bottomColor + /** + * + Draws a scaled, textured, tiled modal rect at z = 0. This method isn't used + * anywhere in vanilla code. + */ + public static void drawScaledCustomSizeModalRect(int x, int y, float u, float v, int uWidth, int vHeight, int width, + int height, float tileWidth, float tileHeight) { + float f = 1.0F / tileWidth; + float f1 = 1.0F / tileHeight; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) x, (double) (y + height), 0.0D) + .tex((double) (u * f), (double) ((v + (float) vHeight) * f1)).endVertex(); + worldrenderer.pos((double) (x + width), (double) (y + height), 0.0D) + .tex((double) ((u + (float) uWidth) * f), (double) ((v + (float) vHeight) * f1)).endVertex(); + worldrenderer.pos((double) (x + width), (double) y, 0.0D) + .tex((double) ((u + (float) uWidth) * f), (double) (v * f1)).endVertex(); + worldrenderer.pos((double) x, (double) y, 0.0D).tex((double) (u * f), (double) (v * f1)).endVertex(); + tessellator.draw(); + } + + protected float zLevel; + + /** + * + Renders the specified text to the screen, center-aligned. Args : renderer, + * string, x, y, color + */ + public void drawCenteredString(FontRenderer fontRendererIn, String text, int x, int y, int color) { + fontRendererIn.drawStringWithShadow(text, (float) (x - fontRendererIn.getStringWidth(text) / 2), (float) y, + color); + } + + /** + * + Draws a rectangle with a vertical gradient between the specified colors + * (ARGB format). Args : x1, y1, x2, y2, topColor, bottomColor */ protected void drawGradientRect(int left, int top, int right, int bottom, int startColor, int endColor) { float f = (float) (startColor >> 24 & 255) / 255.0F; @@ -132,26 +163,71 @@ public class Gui { GlStateManager.enableTexture2D(); } - /**+ - * Renders the specified text to the screen, center-aligned. - * Args : renderer, string, x, y, color + /** + * + Draw a 1 pixel wide horizontal line. Args: x1, x2, y, color */ - public void drawCenteredString(FontRenderer fontRendererIn, String text, int x, int y, int color) { - fontRendererIn.drawStringWithShadow(text, (float) (x - fontRendererIn.getStringWidth(text) / 2), (float) y, - color); + protected void drawHorizontalLine(int startX, int endX, int y, int color) { + if (endX < startX) { + int i = startX; + startX = endX; + endX = i; + } + + drawRect(startX, y, endX + 1, y + 1, color); } - /**+ - * Renders the specified text to the screen. Args : renderer, - * string, x, y, color + /** + * + Renders the specified text to the screen. Args : renderer, string, x, y, + * color */ public void drawString(FontRenderer fontRendererIn, String text, int x, int y, int color) { fontRendererIn.drawStringWithShadow(text, (float) x, (float) y, color); } - /**+ - * Draws a textured rectangle using the texture currently bound - * to the TextureManager + /** + * + Draws a textured rectangle using the texture currently bound to the + * TextureManager + */ + public void drawTexturedModalRect(float xCoord, float yCoord, int minU, int minV, int maxU, int maxV) { + float f = 0.00390625F; + float f1 = 0.00390625F; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) maxV), (double) this.zLevel) + .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); + worldrenderer.pos((double) (xCoord + (float) maxU), (double) (yCoord + (float) maxV), (double) this.zLevel) + .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); + worldrenderer.pos((double) (xCoord + (float) maxU), (double) (yCoord + 0.0F), (double) this.zLevel) + .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + 0) * f1)).endVertex(); + worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + 0.0F), (double) this.zLevel) + .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + 0) * f1)).endVertex(); + tessellator.draw(); + } + + /** + * + Draws a textured rectangle using the texture currently bound to the + * TextureManager + */ + public void drawTexturedModalRect(int xCoord, int yCoord, EaglerTextureAtlasSprite textureSprite, int widthIn, + int heightIn) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (xCoord + 0), (double) (yCoord + heightIn), (double) this.zLevel) + .tex((double) textureSprite.getMinU(), (double) textureSprite.getMaxV()).endVertex(); + worldrenderer.pos((double) (xCoord + widthIn), (double) (yCoord + heightIn), (double) this.zLevel) + .tex((double) textureSprite.getMaxU(), (double) textureSprite.getMaxV()).endVertex(); + worldrenderer.pos((double) (xCoord + widthIn), (double) (yCoord + 0), (double) this.zLevel) + .tex((double) textureSprite.getMaxU(), (double) textureSprite.getMinV()).endVertex(); + worldrenderer.pos((double) (xCoord + 0), (double) (yCoord + 0), (double) this.zLevel) + .tex((double) textureSprite.getMinU(), (double) textureSprite.getMinV()).endVertex(); + tessellator.draw(); + } + + /** + * + Draws a textured rectangle using the texture currently bound to the + * TextureManager */ public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height) { float f = 0.00390625F; @@ -171,86 +247,16 @@ public class Gui { tessellator.draw(); } - /**+ - * Draws a textured rectangle using the texture currently bound - * to the TextureManager + /** + * + Draw a 1 pixel wide vertical line. Args : x, y1, y2, color */ - public void drawTexturedModalRect(float xCoord, float yCoord, int minU, int minV, int maxU, int maxV) { - float f = 0.00390625F; - float f1 = 0.00390625F; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) maxV), (double) this.zLevel) - .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); - worldrenderer.pos((double) (xCoord + (float) maxU), (double) (yCoord + (float) maxV), (double) this.zLevel) - .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); - worldrenderer.pos((double) (xCoord + (float) maxU), (double) (yCoord + 0.0F), (double) this.zLevel) - .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + 0) * f1)).endVertex(); - worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + 0.0F), (double) this.zLevel) - .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + 0) * f1)).endVertex(); - tessellator.draw(); - } + protected void drawVerticalLine(int x, int startY, int endY, int color) { + if (endY < startY) { + int i = startY; + startY = endY; + endY = i; + } - /**+ - * Draws a textured rectangle using the texture currently bound - * to the TextureManager - */ - public void drawTexturedModalRect(int xCoord, int yCoord, EaglerTextureAtlasSprite textureSprite, int widthIn, - int heightIn) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (xCoord + 0), (double) (yCoord + heightIn), (double) this.zLevel) - .tex((double) textureSprite.getMinU(), (double) textureSprite.getMaxV()).endVertex(); - worldrenderer.pos((double) (xCoord + widthIn), (double) (yCoord + heightIn), (double) this.zLevel) - .tex((double) textureSprite.getMaxU(), (double) textureSprite.getMaxV()).endVertex(); - worldrenderer.pos((double) (xCoord + widthIn), (double) (yCoord + 0), (double) this.zLevel) - .tex((double) textureSprite.getMaxU(), (double) textureSprite.getMinV()).endVertex(); - worldrenderer.pos((double) (xCoord + 0), (double) (yCoord + 0), (double) this.zLevel) - .tex((double) textureSprite.getMinU(), (double) textureSprite.getMinV()).endVertex(); - tessellator.draw(); - } - - /**+ - * Draws a textured rectangle at z = 0. Args: x, y, u, v, width, - * height, textureWidth, textureHeight - */ - public static void drawModalRectWithCustomSizedTexture(int x, int y, float u, float v, int width, int height, - float textureWidth, float textureHeight) { - float f = 1.0F / textureWidth; - float f1 = 1.0F / textureHeight; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) x, (double) (y + height), 0.0D) - .tex((double) (u * f), (double) ((v + (float) height) * f1)).endVertex(); - worldrenderer.pos((double) (x + width), (double) (y + height), 0.0D) - .tex((double) ((u + (float) width) * f), (double) ((v + (float) height) * f1)).endVertex(); - worldrenderer.pos((double) (x + width), (double) y, 0.0D) - .tex((double) ((u + (float) width) * f), (double) (v * f1)).endVertex(); - worldrenderer.pos((double) x, (double) y, 0.0D).tex((double) (u * f), (double) (v * f1)).endVertex(); - tessellator.draw(); - } - - /**+ - * Draws a scaled, textured, tiled modal rect at z = 0. This - * method isn't used anywhere in vanilla code. - */ - public static void drawScaledCustomSizeModalRect(int x, int y, float u, float v, int uWidth, int vHeight, int width, - int height, float tileWidth, float tileHeight) { - float f = 1.0F / tileWidth; - float f1 = 1.0F / tileHeight; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) x, (double) (y + height), 0.0D) - .tex((double) (u * f), (double) ((v + (float) vHeight) * f1)).endVertex(); - worldrenderer.pos((double) (x + width), (double) (y + height), 0.0D) - .tex((double) ((u + (float) uWidth) * f), (double) ((v + (float) vHeight) * f1)).endVertex(); - worldrenderer.pos((double) (x + width), (double) y, 0.0D) - .tex((double) ((u + (float) uWidth) * f), (double) (v * f1)).endVertex(); - worldrenderer.pos((double) x, (double) y, 0.0D).tex((double) (u * f), (double) (v * f1)).endVertex(); - tessellator.draw(); + drawRect(x, startY + 1, x + 1, endY, color); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiButton.java b/src/game/java/net/minecraft/client/gui/GuiButton.java index ebb5348f..769a5364 100644 --- a/src/game/java/net/minecraft/client/gui/GuiButton.java +++ b/src/game/java/net/minecraft/client/gui/GuiButton.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; @@ -10,22 +11,25 @@ import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.audio.SoundHandler; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,10 +47,6 @@ public class GuiButton extends Gui { protected boolean hovered; public float fontScale = 1.0f; - public GuiButton(int buttonId, int x, int y, String buttonText) { - this(buttonId, x, y, 200, 20, buttonText); - } - public GuiButton(int buttonId, int x, int y, int widthIn, int heightIn, String buttonText) { this.width = 200; this.height = 20; @@ -60,24 +60,12 @@ public class GuiButton extends Gui { this.displayString = buttonText; } - /**+ - * Returns 0 if the button is disabled, 1 if the mouse is NOT - * hovering over this button and 2 if it IS hovering over this - * button. - */ - protected int getHoverState(boolean mouseOver) { - byte b0 = 1; - if (!this.enabled) { - b0 = 0; - } else if (mouseOver) { - b0 = 2; - } - - return b0; + public GuiButton(int buttonId, int x, int y, String buttonText) { + this(buttonId, x, y, 200, 20, buttonText); } - /**+ - * Draws this button to the screen. + /** + * + Draws this button to the screen. */ public void drawButton(Minecraft mc, int mouseX, int mouseY) { if (this.visible) { @@ -122,53 +110,68 @@ public class GuiButton extends Gui { } } - /**+ - * Fired when the mouse button is dragged. Equivalent of - * MouseListener.mouseDragged(MouseEvent e). - */ - protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { - } - - /**+ - * Fired when the mouse button is released. Equivalent of - * MouseListener.mouseReleased(MouseEvent e). - */ - public void mouseReleased(int mouseX, int mouseY) { - } - - /**+ - * Returns true if the mouse has been pressed on this control. - * Equivalent of MouseListener.mousePressed(MouseEvent e). - */ - public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { - return this.enabled && this.visible && mouseX >= this.xPosition && mouseY >= this.yPosition - && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; - } - - /**+ - * Whether the mouse cursor is currently over the button. - */ - public boolean isMouseOver() { - return this.hovered; - } - public void drawButtonForegroundLayer(int mouseX, int mouseY) { } - public void playPressSound(SoundHandler soundHandlerIn) { - soundHandlerIn.playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - } - public int getButtonWidth() { return this.width; } - public void setWidth(int width) { - this.width = width; + /** + * + Returns 0 if the button is disabled, 1 if the mouse is NOT hovering over + * this button and 2 if it IS hovering over this button. + */ + protected int getHoverState(boolean mouseOver) { + byte b0 = 1; + if (!this.enabled) { + b0 = 0; + } else if (mouseOver) { + b0 = 2; + } + + return b0; + } + + /** + * + Whether the mouse cursor is currently over the button. + */ + public boolean isMouseOver() { + return this.hovered; } public boolean isSliderTouchEvents() { return false; } + /** + * + Fired when the mouse button is dragged. Equivalent of + * MouseListener.mouseDragged(MouseEvent e). + */ + protected void mouseDragged(Minecraft mc, int mouseX, int mouseY) { + } + + /** + * + Returns true if the mouse has been pressed on this control. Equivalent of + * MouseListener.mousePressed(MouseEvent e). + */ + public boolean mousePressed(Minecraft mc, int mouseX, int mouseY) { + return this.enabled && this.visible && mouseX >= this.xPosition && mouseY >= this.yPosition + && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; + } + + /** + * + Fired when the mouse button is released. Equivalent of + * MouseListener.mouseReleased(MouseEvent e). + */ + public void mouseReleased(int mouseX, int mouseY) { + } + + public void playPressSound(SoundHandler soundHandlerIn) { + soundHandlerIn.playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } + + public void setWidth(int width) { + this.width = width; + } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiButtonLanguage.java b/src/game/java/net/minecraft/client/gui/GuiButtonLanguage.java index 8d87bfb6..ebc56b10 100644 --- a/src/game/java/net/minecraft/client/gui/GuiButtonLanguage.java +++ b/src/game/java/net/minecraft/client/gui/GuiButtonLanguage.java @@ -5,22 +5,25 @@ import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,8 +33,8 @@ public class GuiButtonLanguage extends GuiButton { super(buttonID, xPos, yPos, 20, 20, ""); } - /**+ - * Draws this button to the screen. + /** + * + Draws this button to the screen. */ public void drawButton(Minecraft minecraft, int i, int j) { if (this.visible) { diff --git a/src/game/java/net/minecraft/client/gui/GuiChat.java b/src/game/java/net/minecraft/client/gui/GuiChat.java index 62591a15..b7e871f7 100644 --- a/src/game/java/net/minecraft/client/gui/GuiChat.java +++ b/src/game/java/net/minecraft/client/gui/GuiChat.java @@ -25,22 +25,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,10 +51,9 @@ import net.minecraft.util.MovingObjectPosition; public class GuiChat extends GuiScreenVisualViewport { private static final Logger logger = LogManager.getLogger(); private String historyBuffer = ""; - /**+ - * keeps position of which chat message you will select when you - * press up, (does not increase for duplicated messages sent - * immediately after each other) + /** + * + keeps position of which chat message you will select when you press up, + * (does not increase for duplicated messages sent immediately after each other) */ private int sentHistoryCursor = -1; private boolean playerNamesFound; @@ -59,9 +61,9 @@ public class GuiChat extends GuiScreenVisualViewport { private int autocompleteIndex; private List foundPlayerNames = Lists.newArrayList(); protected GuiTextField inputField; - /**+ - * is the text that appears when you press the chat key and the - * input box appears pre-filled + /** + * + is the text that appears when you press the chat key and the input box + * appears pre-filled */ private String defaultInputFieldText = ""; @@ -75,127 +77,6 @@ public class GuiChat extends GuiScreenVisualViewport { this.defaultInputFieldText = defaultText; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - if (!(this instanceof GuiSleepMP)) { - this.buttonList.add(exitButton = new GuiButton(69, this.width - 100, 3, 97, 20, I18n.format("chat.exit"))); - if (!this.mc.isIntegratedServerRunning() && this.mc.thePlayer != null - && this.mc.thePlayer.sendQueue.getEaglerMessageProtocol().ver >= 4) { - this.buttonList.add(notifBellButton = new GuiButtonNotifBell(70, this.width - 122, 3)); - notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); - } - } - this.sentHistoryCursor = this.mc.ingameGUI.getChatGUI().getSentMessages().size(); - this.inputField = new GuiTextField(0, this.fontRendererObj, 4, this.height - 12, this.width - 4, 12); - this.inputField.setMaxStringLength(100); - this.inputField.setEnableBackgroundDrawing(false); - this.inputField.setFocused(true); - this.inputField.setText(this.defaultInputFieldText); - this.inputField.setCanLoseFocus(false); - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - this.mc.ingameGUI.getChatGUI().resetScroll(); - } - - public void updateScreen0() { - this.inputField.updateCursorCounter(); - if (notifBellButton != null && mc.thePlayer != null) { - notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); - } - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (parInt1 == 1 && (this.mc.gameSettings.keyBindClose.getKeyCode() == 0 || this.mc.areKeysLocked())) { - this.mc.displayGuiScreen((GuiScreen) null); - } else { - this.waitingOnAutocomplete = false; - if (parInt1 == 15) { - this.autocompletePlayerNames(); - } else { - this.playerNamesFound = false; - } - - if (parInt1 != 28 && parInt1 != 156) { - if (parInt1 == 200) { - this.getSentHistory(-1); - } else if (parInt1 == 208) { - this.getSentHistory(1); - } else if (parInt1 == 201) { - this.mc.ingameGUI.getChatGUI().scroll(this.mc.ingameGUI.getChatGUI().getLineCount() - 1); - } else if (parInt1 == 209) { - this.mc.ingameGUI.getChatGUI().scroll(-this.mc.ingameGUI.getChatGUI().getLineCount() + 1); - } else { - this.inputField.textboxKeyTyped(parChar1, parInt1); - } - } else { - String s = this.inputField.getText().trim(); - if (s.length() > 0) { - this.sendChatMessage(s); - } - - this.mc.displayGuiScreen((GuiScreen) null); - } - } - - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - int i = Mouse.getEventDWheel(); - if (i != 0) { - if (i > 1) { - i = 1; - } - - if (i < -1) { - i = -1; - } - - if (!isShiftKeyDown()) { - i *= 7; - } - - this.mc.ingameGUI.getChatGUI().scroll(i); - } - - } - - protected void mouseClicked0(int parInt1, int parInt2, int parInt3) { - if (parInt3 == 0) { - IChatComponent ichatcomponent = this.mc.ingameGUI.getChatGUI() - .getChatComponent(PointerInputAbstraction.getVCursorX(), PointerInputAbstraction.getVCursorY()); - if (this.handleComponentClick(ichatcomponent)) { - return; - } - if (mc.notifRenderer.handleClicked(this, parInt1, parInt2)) { - return; - } - } - - this.inputField.mouseClicked(parInt1, parInt2, parInt3); - super.mouseClicked0(parInt1, parInt2, parInt3); - } - protected void actionPerformed(GuiButton par1GuiButton) { if (par1GuiButton.id == 69) { this.mc.displayGuiScreen(null); @@ -204,18 +85,6 @@ public class GuiChat extends GuiScreenVisualViewport { } } - /**+ - * Sets the text of the chat - */ - protected void setText(String newChatText, boolean shouldOverwrite) { - if (shouldOverwrite) { - this.inputField.setText(newChatText); - } else { - this.inputField.writeText(newChatText); - } - - } - public void autocompletePlayerNames() { if (this.playerNamesFound) { this.inputField @@ -258,23 +127,42 @@ public class GuiChat extends GuiScreenVisualViewport { this.inputField.writeText((String) this.foundPlayerNames.get(this.autocompleteIndex++)); } - private void sendAutocompleteRequest(String parString1, String parString2) { - if (parString1.length() >= 1) { - BlockPos blockpos = null; - if (this.mc.objectMouseOver != null - && this.mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - blockpos = this.mc.objectMouseOver.getBlockPos(); - } - - this.mc.thePlayer.sendQueue.addToSendQueue(new C14PacketTabComplete(parString1, blockpos)); - this.waitingOnAutocomplete = true; - } + public boolean blockPTTKey() { + return true; } - /**+ - * input is relative and is applied directly to the - * sentHistoryCursor so -1 is the previous message, 1 is the - * next message from the current cursor position + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return false; + } + + public void drawScreen0(int i, int j, float f) { + drawRect(2, this.height - 14, this.width - 2, this.height - 2, Integer.MIN_VALUE); + this.inputField.drawTextBox(); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + IChatComponent ichatcomponent = this.mc.ingameGUI.getChatGUI() + .getChatComponent(PointerInputAbstraction.getVCursorX(), PointerInputAbstraction.getVCursorY()); + if (ichatcomponent != null && ichatcomponent.getChatStyle().getChatHoverEvent() != null) { + this.handleComponentHover(ichatcomponent, i, j); + } + + if (exitButton != null) { + exitButton.yPosition = 3 + mc.guiAchievement.getHeight(); + } + + super.drawScreen0(i, j, f); + } + + public void fireInputEvent(EnumInputEvent event, String str) { + inputField.fireInputEvent(event, str); + } + + /** + * + input is relative and is applied directly to the sentHistoryCursor so -1 is + * the previous message, 1 is the next message from the current cursor position */ public void getSentHistory(int msgPos) { int i = this.sentHistoryCursor + msgPos; @@ -295,21 +183,108 @@ public class GuiChat extends GuiScreenVisualViewport { } } - public void drawScreen0(int i, int j, float f) { - drawRect(2, this.height - 14, this.width - 2, this.height - 2, Integer.MIN_VALUE); - this.inputField.drawTextBox(); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - IChatComponent ichatcomponent = this.mc.ingameGUI.getChatGUI() - .getChatComponent(PointerInputAbstraction.getVCursorX(), PointerInputAbstraction.getVCursorY()); - if (ichatcomponent != null && ichatcomponent.getChatStyle().getChatHoverEvent() != null) { - this.handleComponentHover(ichatcomponent, i, j); + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + int i = Mouse.getEventDWheel(); + if (i != 0) { + if (i > 1) { + i = 1; + } + + if (i < -1) { + i = -1; + } + + if (!isShiftKeyDown()) { + i *= 7; + } + + this.mc.ingameGUI.getChatGUI().scroll(i); } - if (exitButton != null) { - exitButton.yPosition = 3 + mc.guiAchievement.getHeight(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + if (!(this instanceof GuiSleepMP)) { + this.buttonList.add(exitButton = new GuiButton(69, this.width - 100, 3, 97, 20, I18n.format("chat.exit"))); + if (!this.mc.isIntegratedServerRunning() && this.mc.thePlayer != null + && this.mc.thePlayer.sendQueue.getEaglerMessageProtocol().ver >= 4) { + this.buttonList.add(notifBellButton = new GuiButtonNotifBell(70, this.width - 122, 3)); + notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); + } + } + this.sentHistoryCursor = this.mc.ingameGUI.getChatGUI().getSentMessages().size(); + this.inputField = new GuiTextField(0, this.fontRendererObj, 4, this.height - 12, this.width - 4, 12); + this.inputField.setMaxStringLength(100); + this.inputField.setEnableBackgroundDrawing(false); + this.inputField.setFocused(true); + this.inputField.setText(this.defaultInputFieldText); + this.inputField.setCanLoseFocus(false); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (parInt1 == 1 && (this.mc.gameSettings.keyBindClose.getKeyCode() == 0 || this.mc.areKeysLocked())) { + this.mc.displayGuiScreen((GuiScreen) null); + } else { + this.waitingOnAutocomplete = false; + if (parInt1 == 15) { + this.autocompletePlayerNames(); + } else { + this.playerNamesFound = false; + } + + if (parInt1 != 28 && parInt1 != 156) { + if (parInt1 == 200) { + this.getSentHistory(-1); + } else if (parInt1 == 208) { + this.getSentHistory(1); + } else if (parInt1 == 201) { + this.mc.ingameGUI.getChatGUI().scroll(this.mc.ingameGUI.getChatGUI().getLineCount() - 1); + } else if (parInt1 == 209) { + this.mc.ingameGUI.getChatGUI().scroll(-this.mc.ingameGUI.getChatGUI().getLineCount() + 1); + } else { + this.inputField.textboxKeyTyped(parChar1, parInt1); + } + } else { + String s = this.inputField.getText().trim(); + if (s.length() > 0) { + this.sendChatMessage(s); + } + + this.mc.displayGuiScreen((GuiScreen) null); + } } - super.drawScreen0(i, j, f); + } + + protected void mouseClicked0(int parInt1, int parInt2, int parInt3) { + if (parInt3 == 0) { + IChatComponent ichatcomponent = this.mc.ingameGUI.getChatGUI() + .getChatComponent(PointerInputAbstraction.getVCursorX(), PointerInputAbstraction.getVCursorY()); + if (this.handleComponentClick(ichatcomponent)) { + return; + } + if (mc.notifRenderer.handleClicked(this, parInt1, parInt2)) { + return; + } + } + + this.inputField.mouseClicked(parInt1, parInt2, parInt3); + super.mouseClicked0(parInt1, parInt2, parInt3); } public void onAutocompleteResponse(String[] parArrayOfString) { @@ -340,24 +315,48 @@ public class GuiChat extends GuiScreenVisualViewport { } - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events */ - public boolean doesGuiPauseGame() { - return false; + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + this.mc.ingameGUI.getChatGUI().resetScroll(); } - public boolean blockPTTKey() { - return true; + private void sendAutocompleteRequest(String parString1, String parString2) { + if (parString1.length() >= 1) { + BlockPos blockpos = null; + if (this.mc.objectMouseOver != null + && this.mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + blockpos = this.mc.objectMouseOver.getBlockPos(); + } + + this.mc.thePlayer.sendQueue.addToSendQueue(new C14PacketTabComplete(parString1, blockpos)); + this.waitingOnAutocomplete = true; + } + } + + /** + * + Sets the text of the chat + */ + protected void setText(String newChatText, boolean shouldOverwrite) { + if (shouldOverwrite) { + this.inputField.setText(newChatText); + } else { + this.inputField.writeText(newChatText); + } + } public boolean showCopyPasteButtons() { return true; } - public void fireInputEvent(EnumInputEvent event, String str) { - inputField.fireInputEvent(event, str); + public void updateScreen0() { + this.inputField.updateCursorCounter(); + if (notifBellButton != null && mc.thePlayer != null) { + notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiCommandBlock.java b/src/game/java/net/minecraft/client/gui/GuiCommandBlock.java index 4ccccc85..e6920ec1 100644 --- a/src/game/java/net/minecraft/client/gui/GuiCommandBlock.java +++ b/src/game/java/net/minecraft/client/gui/GuiCommandBlock.java @@ -1,32 +1,35 @@ package net.minecraft.client.gui; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.minecraft.client.resources.I18n; import net.minecraft.command.server.CommandBlockLogic; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.client.C17PacketCustomPayload; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,50 +48,9 @@ public class GuiCommandBlock extends GuiScreen { this.localCommandBlock = parCommandBlockLogic; } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.commandTextField.updateCursorCounter(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.buttonList.add(this.doneBtn = new GuiButton(0, this.width / 2 - 4 - 150, this.height / 4 + 120 + 12, 150, - 20, I18n.format("gui.done", new Object[0]))); - this.buttonList.add(this.cancelBtn = new GuiButton(1, this.width / 2 + 4, this.height / 4 + 120 + 12, 150, 20, - I18n.format("gui.cancel", new Object[0]))); - this.buttonList.add(this.field_175390_s = new GuiButton(4, this.width / 2 + 150 - 20, 150, 20, 20, "O")); - this.commandTextField = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 150, 50, 300, 20); - this.commandTextField.setMaxStringLength(32767); - this.commandTextField.setFocused(true); - this.commandTextField.setText(this.localCommandBlock.getCommand()); - this.previousOutputTextField = new GuiTextField(3, this.fontRendererObj, this.width / 2 - 150, 150, 276, 20); - this.previousOutputTextField.setMaxStringLength(32767); - this.previousOutputTextField.setEnabled(false); - this.previousOutputTextField.setText("-"); - this.field_175389_t = this.localCommandBlock.shouldTrackOutput(); - this.func_175388_a(); - this.doneBtn.enabled = this.commandTextField.getText().trim().length() > 0; - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -115,39 +77,13 @@ public class GuiCommandBlock extends GuiScreen { } } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - this.commandTextField.textboxKeyTyped(parChar1, parInt1); - this.previousOutputTextField.textboxKeyTyped(parChar1, parInt1); - this.doneBtn.enabled = this.commandTextField.getText().trim().length() > 0; - if (parInt1 != 28 && parInt1 != 156) { - if (parInt1 == 1) { - this.actionPerformed(this.cancelBtn); - } - } else { - this.actionPerformed(this.doneBtn); - } - + public boolean blockPTTKey() { + return commandTextField.isFocused() || previousOutputTextField.isFocused(); } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - this.commandTextField.mouseClicked(parInt1, parInt2, parInt3); - this.previousOutputTextField.mouseClicked(parInt1, parInt2, parInt3); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -178,6 +114,12 @@ public class GuiCommandBlock extends GuiScreen { super.drawScreen(i, j, f); } + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + commandTextField.fireInputEvent(event, param); + previousOutputTextField.fireInputEvent(event, param); + } + private void func_175388_a() { if (this.localCommandBlock.shouldTrackOutput()) { this.field_175390_s.displayString = "O"; @@ -191,8 +133,65 @@ public class GuiCommandBlock extends GuiScreen { } - public boolean blockPTTKey() { - return commandTextField.isFocused() || previousOutputTextField.isFocused(); + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.buttonList.add(this.doneBtn = new GuiButton(0, this.width / 2 - 4 - 150, this.height / 4 + 120 + 12, 150, + 20, I18n.format("gui.done", new Object[0]))); + this.buttonList.add(this.cancelBtn = new GuiButton(1, this.width / 2 + 4, this.height / 4 + 120 + 12, 150, 20, + I18n.format("gui.cancel", new Object[0]))); + this.buttonList.add(this.field_175390_s = new GuiButton(4, this.width / 2 + 150 - 20, 150, 20, 20, "O")); + this.commandTextField = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 150, 50, 300, 20); + this.commandTextField.setMaxStringLength(32767); + this.commandTextField.setFocused(true); + this.commandTextField.setText(this.localCommandBlock.getCommand()); + this.previousOutputTextField = new GuiTextField(3, this.fontRendererObj, this.width / 2 - 150, 150, 276, 20); + this.previousOutputTextField.setMaxStringLength(32767); + this.previousOutputTextField.setEnabled(false); + this.previousOutputTextField.setText("-"); + this.field_175389_t = this.localCommandBlock.shouldTrackOutput(); + this.func_175388_a(); + this.doneBtn.enabled = this.commandTextField.getText().trim().length() > 0; + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + this.commandTextField.textboxKeyTyped(parChar1, parInt1); + this.previousOutputTextField.textboxKeyTyped(parChar1, parInt1); + this.doneBtn.enabled = this.commandTextField.getText().trim().length() > 0; + if (parInt1 != 28 && parInt1 != 156) { + if (parInt1 == 1) { + this.actionPerformed(this.cancelBtn); + } + } else { + this.actionPerformed(this.doneBtn); + } + + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + this.commandTextField.mouseClicked(parInt1, parInt2, parInt3); + this.previousOutputTextField.mouseClicked(parInt1, parInt2, parInt3); + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); } @Override @@ -200,10 +199,11 @@ public class GuiCommandBlock extends GuiScreen { return commandTextField.isFocused() || previousOutputTextField.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - commandTextField.fireInputEvent(event, param); - previousOutputTextField.fireInputEvent(event, param); + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.commandTextField.updateCursorCounter(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiConfirmOpenLink.java b/src/game/java/net/minecraft/client/gui/GuiConfirmOpenLink.java index 11f1ee7f..378d4598 100644 --- a/src/game/java/net/minecraft/client/gui/GuiConfirmOpenLink.java +++ b/src/game/java/net/minecraft/client/gui/GuiConfirmOpenLink.java @@ -2,22 +2,25 @@ package net.minecraft.client.gui; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,10 +42,45 @@ public class GuiConfirmOpenLink extends GuiYesNo { this.linkText = linkTextIn; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 2) { + this.copyLinkToClipboard(); + } + + this.parentScreen.confirmClicked(parGuiButton.id == 0, this.parentButtonClickedId); + } + + /** + * + Copies the link to the system clipboard. + */ + public void copyLinkToClipboard() { + setClipboardString(this.linkText); + } + + public void disableSecurityWarning() { + this.showSecurityWarning = false; + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + super.drawScreen(i, j, f); + if (this.showSecurityWarning) { + this.drawCenteredString(this.fontRendererObj, this.openLinkWarning, this.width / 2, 110, 16764108); + } + + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { super.initGui(); @@ -54,39 +92,4 @@ public class GuiConfirmOpenLink extends GuiYesNo { this.buttonList .add(new GuiButton(1, this.width / 2 - 50 + 105, this.height / 6 + 96, 100, 20, this.cancelButtonText)); } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == 2) { - this.copyLinkToClipboard(); - } - - this.parentScreen.confirmClicked(parGuiButton.id == 0, this.parentButtonClickedId); - } - - /**+ - * Copies the link to the system clipboard. - */ - public void copyLinkToClipboard() { - setClipboardString(this.linkText); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - super.drawScreen(i, j, f); - if (this.showSecurityWarning) { - this.drawCenteredString(this.fontRendererObj, this.openLinkWarning, this.width / 2, 110, 16764108); - } - - } - - public void disableSecurityWarning() { - this.showSecurityWarning = false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiControls.java b/src/game/java/net/minecraft/client/gui/GuiControls.java index f51dfd1a..36a83036 100644 --- a/src/game/java/net/minecraft/client/gui/GuiControls.java +++ b/src/game/java/net/minecraft/client/gui/GuiControls.java @@ -7,22 +7,25 @@ import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; import net.minecraft.client.settings.KeyBinding; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +37,8 @@ public class GuiControls extends GuiScreen { private GuiScreen parentScreen; protected String screenTitle = "Controls"; private GameSettings options; - /**+ - * The ID of the button that has been pressed. + /** + * + The ID of the button that has been pressed. */ public KeyBinding buttonId = null; public long time; @@ -47,10 +50,67 @@ public class GuiControls extends GuiScreen { this.options = settings; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 200) { + this.mc.displayGuiScreen(this.parentScreen); + } else if (parGuiButton.id == 201) { + KeyBinding[] arr = this.mc.gameSettings.keyBindings; + for (int i = 0; i < arr.length; ++i) { + arr[i].setKeyCode(arr[i].getKeyCodeDefault()); + } + + KeyBinding.resetKeyBindingArrayAndHash(); + } else if (parGuiButton.id < 100 && parGuiButton instanceof GuiOptionButton) { + this.options.setOptionValue(((GuiOptionButton) parGuiButton).returnEnumOptions(), 1); + parGuiButton.displayString = this.options + .getKeyBinding(GameSettings.Options.getEnumOptions(parGuiButton.id)); + } + + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.keyBindingList.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 8, 16777215); + boolean flag = true; + + KeyBinding[] arr = this.options.keyBindings; + for (int k = 0; k < arr.length; ++k) { + if (arr[k].getKeyCode() != arr[k].getKeyCodeDefault()) { + flag = false; + break; + } + } + + this.buttonReset.enabled = !flag; + super.drawScreen(i, j, f); + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.keyBindingList.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.keyBindingList.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { this.keyBindingList = new GuiKeyBindingList(this, this.mc); @@ -76,72 +136,10 @@ public class GuiControls extends GuiScreen { } - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.keyBindingList.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.keyBindingList.handleTouchInput(); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == 200) { - this.mc.displayGuiScreen(this.parentScreen); - } else if (parGuiButton.id == 201) { - KeyBinding[] arr = this.mc.gameSettings.keyBindings; - for (int i = 0; i < arr.length; ++i) { - arr[i].setKeyCode(arr[i].getKeyCodeDefault()); - } - - KeyBinding.resetKeyBindingArrayAndHash(); - } else if (parGuiButton.id < 100 && parGuiButton instanceof GuiOptionButton) { - this.options.setOptionValue(((GuiOptionButton) parGuiButton).returnEnumOptions(), 1); - parGuiButton.displayString = this.options - .getKeyBinding(GameSettings.Options.getEnumOptions(parGuiButton.id)); - } - - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - if (this.buttonId != null) { - this.options.setOptionKeyBinding(this.buttonId, -100 + parInt3); - this.buttonId = null; - KeyBinding.resetKeyBindingArrayAndHash(); - } else if (parInt3 != 0 || !this.keyBindingList.mouseClicked(parInt1, parInt2, parInt3)) { - super.mouseClicked(parInt1, parInt2, parInt3); - } - - } - - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton - */ - protected void mouseReleased(int i, int j, int k) { - if (k != 0 || !this.keyBindingList.mouseReleased(i, j, k)) { - super.mouseReleased(i, j, k); - } - - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { if (this.buttonId != null) { @@ -162,25 +160,28 @@ public class GuiControls extends GuiScreen { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.keyBindingList.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 8, 16777215); - boolean flag = true; - - KeyBinding[] arr = this.options.keyBindings; - for (int k = 0; k < arr.length; ++k) { - if (arr[k].getKeyCode() != arr[k].getKeyCodeDefault()) { - flag = false; - break; - } + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + if (this.buttonId != null) { + this.options.setOptionKeyBinding(this.buttonId, -100 + parInt3); + this.buttonId = null; + KeyBinding.resetKeyBindingArrayAndHash(); + } else if (parInt3 != 0 || !this.keyBindingList.mouseClicked(parInt1, parInt2, parInt3)) { + super.mouseClicked(parInt1, parInt2, parInt3); + } + + } + + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton + */ + protected void mouseReleased(int i, int j, int k) { + if (k != 0 || !this.keyBindingList.mouseReleased(i, j, k)) { + super.mouseReleased(i, j, k); } - this.buttonReset.enabled = !flag; - super.drawScreen(i, j, f); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiCreateFlatWorld.java b/src/game/java/net/minecraft/client/gui/GuiCreateFlatWorld.java index bf3ed92f..ebe541a5 100644 --- a/src/game/java/net/minecraft/client/gui/GuiCreateFlatWorld.java +++ b/src/game/java/net/minecraft/client/gui/GuiCreateFlatWorld.java @@ -17,142 +17,30 @@ import net.minecraft.item.ItemStack; import net.minecraft.world.gen.FlatGeneratorInfo; import net.minecraft.world.gen.FlatLayerInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiCreateFlatWorld extends GuiScreen { - private final GuiCreateWorld createWorldGui; - private FlatGeneratorInfo theFlatGeneratorInfo = FlatGeneratorInfo.getDefaultFlatGenerator(); - private String flatWorldTitle; - private String field_146394_i; - private String field_146391_r; - private GuiCreateFlatWorld.Details createFlatWorldListSlotGui; - private GuiButton field_146389_t; - private GuiButton field_146388_u; - private GuiButton field_146386_v; - - public GuiCreateFlatWorld(GuiCreateWorld createWorldGuiIn, String parString1) { - this.createWorldGui = createWorldGuiIn; - this.func_146383_a(parString1); - } - - public String func_146384_e() { - return this.theFlatGeneratorInfo.toString(); - } - - public void func_146383_a(String parString1) { - this.theFlatGeneratorInfo = FlatGeneratorInfo.createFlatGeneratorFromString(parString1); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - this.flatWorldTitle = I18n.format("createWorld.customize.flat.title", new Object[0]); - this.field_146394_i = I18n.format("createWorld.customize.flat.tile", new Object[0]); - this.field_146391_r = I18n.format("createWorld.customize.flat.height", new Object[0]); - this.createFlatWorldListSlotGui = new GuiCreateFlatWorld.Details(); - this.buttonList.add(this.field_146389_t = new GuiButton(2, this.width / 2 - 154, this.height - 52, 100, 20, - I18n.format("createWorld.customize.flat.addLayer", new Object[0]) + " (NYI)")); - this.buttonList.add(this.field_146388_u = new GuiButton(3, this.width / 2 - 50, this.height - 52, 100, 20, - I18n.format("createWorld.customize.flat.editLayer", new Object[0]) + " (NYI)")); - this.buttonList.add(this.field_146386_v = new GuiButton(4, this.width / 2 - 155, this.height - 52, 150, 20, - I18n.format("createWorld.customize.flat.removeLayer", new Object[0]))); - this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, - I18n.format("gui.done", new Object[0]))); - this.buttonList.add(new GuiButton(5, this.width / 2 + 5, this.height - 52, 150, 20, - I18n.format("createWorld.customize.presets", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, - I18n.format("gui.cancel", new Object[0]))); - this.field_146389_t.visible = this.field_146388_u.visible = false; - this.theFlatGeneratorInfo.func_82645_d(); - this.func_146375_g(); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.createFlatWorldListSlotGui.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.createFlatWorldListSlotGui.handleTouchInput(); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - int i = this.theFlatGeneratorInfo.getFlatLayers().size() - this.createFlatWorldListSlotGui.field_148228_k - 1; - if (parGuiButton.id == 1) { - this.mc.displayGuiScreen(this.createWorldGui); - } else if (parGuiButton.id == 0) { - this.createWorldGui.chunkProviderSettingsJson = this.func_146384_e(); - this.mc.displayGuiScreen(this.createWorldGui); - } else if (parGuiButton.id == 5) { - this.mc.displayGuiScreen(new GuiFlatPresets(this)); - } else if (parGuiButton.id == 4 && this.func_146382_i()) { - this.theFlatGeneratorInfo.getFlatLayers().remove(i); - this.createFlatWorldListSlotGui.field_148228_k = Math.min(this.createFlatWorldListSlotGui.field_148228_k, - this.theFlatGeneratorInfo.getFlatLayers().size() - 1); - } - - this.theFlatGeneratorInfo.func_82645_d(); - this.func_146375_g(); - } - - public void func_146375_g() { - boolean flag = this.func_146382_i(); - this.field_146386_v.enabled = flag; - this.field_146388_u.enabled = flag; - this.field_146388_u.enabled = false; - this.field_146389_t.enabled = false; - } - - private boolean func_146382_i() { - return this.createFlatWorldListSlotGui.field_148228_k > -1 - && this.createFlatWorldListSlotGui.field_148228_k < this.theFlatGeneratorInfo.getFlatLayers().size(); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.createFlatWorldListSlotGui.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.flatWorldTitle, this.width / 2, 8, 16777215); - int k = this.width / 2 - 92 - 16; - this.drawString(this.fontRendererObj, this.field_146394_i, k, 32, 16777215); - this.drawString(this.fontRendererObj, this.field_146391_r, - k + 2 + 213 - this.fontRendererObj.getStringWidth(this.field_146391_r), 32, 16777215); - super.drawScreen(i, j, f); - } - class Details extends GuiSlot { public int field_148228_k = -1; @@ -161,60 +49,6 @@ public class GuiCreateFlatWorld extends GuiScreen { GuiCreateFlatWorld.this.height - 60, 24); } - private void func_148225_a(int parInt1, int parInt2, ItemStack parItemStack) { - this.func_148226_e(parInt1 + 1, parInt2 + 1); - GlStateManager.enableRescaleNormal(); - if (parItemStack != null && parItemStack.getItem() != null) { - RenderHelper.enableGUIStandardItemLighting(); - GuiCreateFlatWorld.this.itemRender.renderItemIntoGUI(parItemStack, parInt1 + 2, parInt2 + 2); - RenderHelper.disableStandardItemLighting(); - } - - GlStateManager.disableRescaleNormal(); - } - - private void func_148226_e(int parInt1, int parInt2) { - this.func_148224_c(parInt1, parInt2, 0, 0); - } - - private void func_148224_c(int parInt1, int parInt2, int parInt3, int parInt4) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(Gui.statIcons); - float f = 0.0078125F; - float f1 = 0.0078125F; - boolean flag = true; - boolean flag1 = true; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 18), (double) GuiCreateFlatWorld.this.zLevel) - .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 18), (double) GuiCreateFlatWorld.this.zLevel) - .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 0), (double) GuiCreateFlatWorld.this.zLevel) - .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 0), (double) GuiCreateFlatWorld.this.zLevel) - .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) - .endVertex(); - tessellator.draw(); - } - - protected int getSize() { - return GuiCreateFlatWorld.this.theFlatGeneratorInfo.getFlatLayers().size(); - } - - protected void elementClicked(int i, boolean var2, int var3, int var4) { - this.field_148228_k = i; - GuiCreateFlatWorld.this.func_146375_g(); - } - - protected boolean isSelected(int i) { - return i == this.field_148228_k; - } - protected void drawBackground() { } @@ -261,8 +95,178 @@ public class GuiCreateFlatWorld extends GuiScreen { j + 2 + 213 - GuiCreateFlatWorld.this.fontRendererObj.getStringWidth(s1), k + 3, 16777215); } + protected void elementClicked(int i, boolean var2, int var3, int var4) { + this.field_148228_k = i; + GuiCreateFlatWorld.this.func_146375_g(); + } + + private void func_148224_c(int parInt1, int parInt2, int parInt3, int parInt4) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(Gui.statIcons); + float f = 0.0078125F; + float f1 = 0.0078125F; + boolean flag = true; + boolean flag1 = true; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 18), (double) GuiCreateFlatWorld.this.zLevel) + .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 18), (double) GuiCreateFlatWorld.this.zLevel) + .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 0), (double) GuiCreateFlatWorld.this.zLevel) + .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 0), (double) GuiCreateFlatWorld.this.zLevel) + .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) + .endVertex(); + tessellator.draw(); + } + + private void func_148225_a(int parInt1, int parInt2, ItemStack parItemStack) { + this.func_148226_e(parInt1 + 1, parInt2 + 1); + GlStateManager.enableRescaleNormal(); + if (parItemStack != null && parItemStack.getItem() != null) { + RenderHelper.enableGUIStandardItemLighting(); + GuiCreateFlatWorld.this.itemRender.renderItemIntoGUI(parItemStack, parInt1 + 2, parInt2 + 2); + RenderHelper.disableStandardItemLighting(); + } + + GlStateManager.disableRescaleNormal(); + } + + private void func_148226_e(int parInt1, int parInt2) { + this.func_148224_c(parInt1, parInt2, 0, 0); + } + protected int getScrollBarX() { return this.width - 70; } + + protected int getSize() { + return GuiCreateFlatWorld.this.theFlatGeneratorInfo.getFlatLayers().size(); + } + + protected boolean isSelected(int i) { + return i == this.field_148228_k; + } + } + + private final GuiCreateWorld createWorldGui; + private FlatGeneratorInfo theFlatGeneratorInfo = FlatGeneratorInfo.getDefaultFlatGenerator(); + private String flatWorldTitle; + private String field_146394_i; + private String field_146391_r; + private GuiCreateFlatWorld.Details createFlatWorldListSlotGui; + private GuiButton field_146389_t; + private GuiButton field_146388_u; + + private GuiButton field_146386_v; + + public GuiCreateFlatWorld(GuiCreateWorld createWorldGuiIn, String parString1) { + this.createWorldGui = createWorldGuiIn; + this.func_146383_a(parString1); + } + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + int i = this.theFlatGeneratorInfo.getFlatLayers().size() - this.createFlatWorldListSlotGui.field_148228_k - 1; + if (parGuiButton.id == 1) { + this.mc.displayGuiScreen(this.createWorldGui); + } else if (parGuiButton.id == 0) { + this.createWorldGui.chunkProviderSettingsJson = this.func_146384_e(); + this.mc.displayGuiScreen(this.createWorldGui); + } else if (parGuiButton.id == 5) { + this.mc.displayGuiScreen(new GuiFlatPresets(this)); + } else if (parGuiButton.id == 4 && this.func_146382_i()) { + this.theFlatGeneratorInfo.getFlatLayers().remove(i); + this.createFlatWorldListSlotGui.field_148228_k = Math.min(this.createFlatWorldListSlotGui.field_148228_k, + this.theFlatGeneratorInfo.getFlatLayers().size() - 1); + } + + this.theFlatGeneratorInfo.func_82645_d(); + this.func_146375_g(); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.createFlatWorldListSlotGui.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.flatWorldTitle, this.width / 2, 8, 16777215); + int k = this.width / 2 - 92 - 16; + this.drawString(this.fontRendererObj, this.field_146394_i, k, 32, 16777215); + this.drawString(this.fontRendererObj, this.field_146391_r, + k + 2 + 213 - this.fontRendererObj.getStringWidth(this.field_146391_r), 32, 16777215); + super.drawScreen(i, j, f); + } + + public void func_146375_g() { + boolean flag = this.func_146382_i(); + this.field_146386_v.enabled = flag; + this.field_146388_u.enabled = flag; + this.field_146388_u.enabled = false; + this.field_146389_t.enabled = false; + } + + private boolean func_146382_i() { + return this.createFlatWorldListSlotGui.field_148228_k > -1 + && this.createFlatWorldListSlotGui.field_148228_k < this.theFlatGeneratorInfo.getFlatLayers().size(); + } + + public void func_146383_a(String parString1) { + this.theFlatGeneratorInfo = FlatGeneratorInfo.createFlatGeneratorFromString(parString1); + } + + public String func_146384_e() { + return this.theFlatGeneratorInfo.toString(); + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.createFlatWorldListSlotGui.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.createFlatWorldListSlotGui.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + this.flatWorldTitle = I18n.format("createWorld.customize.flat.title", new Object[0]); + this.field_146394_i = I18n.format("createWorld.customize.flat.tile", new Object[0]); + this.field_146391_r = I18n.format("createWorld.customize.flat.height", new Object[0]); + this.createFlatWorldListSlotGui = new GuiCreateFlatWorld.Details(); + this.buttonList.add(this.field_146389_t = new GuiButton(2, this.width / 2 - 154, this.height - 52, 100, 20, + I18n.format("createWorld.customize.flat.addLayer", new Object[0]) + " (NYI)")); + this.buttonList.add(this.field_146388_u = new GuiButton(3, this.width / 2 - 50, this.height - 52, 100, 20, + I18n.format("createWorld.customize.flat.editLayer", new Object[0]) + " (NYI)")); + this.buttonList.add(this.field_146386_v = new GuiButton(4, this.width / 2 - 155, this.height - 52, 150, 20, + I18n.format("createWorld.customize.flat.removeLayer", new Object[0]))); + this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, + I18n.format("gui.done", new Object[0]))); + this.buttonList.add(new GuiButton(5, this.width / 2 + 5, this.height - 52, 150, 20, + I18n.format("createWorld.customize.presets", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, + I18n.format("gui.cancel", new Object[0]))); + this.field_146389_t.visible = this.field_146388_u.visible = false; + this.theFlatGeneratorInfo.func_82645_d(); + this.func_146375_g(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiCreateWorld.java b/src/game/java/net/minecraft/client/gui/GuiCreateWorld.java index 5ba25041..db4333cd 100644 --- a/src/game/java/net/minecraft/client/gui/GuiCreateWorld.java +++ b/src/game/java/net/minecraft/client/gui/GuiCreateWorld.java @@ -2,6 +2,8 @@ package net.minecraft.client.gui; import java.util.Random; +import org.apache.commons.lang3.StringUtils; + import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; import net.minecraft.client.resources.I18n; @@ -10,29 +12,54 @@ import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; import net.minecraft.world.storage.ISaveFormat; import net.minecraft.world.storage.WorldInfo; -import org.apache.commons.lang3.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiCreateWorld extends GuiScreen { + /** + * + These filenames are known to be restricted on one or more OS's. + */ + private static final String[] disallowedFilenames = new String[] { "CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", + "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }; + + public static String func_146317_a(ISaveFormat parISaveFormat, String parString1) { + parString1 = parString1.replaceAll("[\\./\"]", "_"); + + for (int i = 0; i < disallowedFilenames.length; ++i) { + if (parString1.equalsIgnoreCase(disallowedFilenames[i])) { + parString1 = "_" + parString1 + "_"; + } + } + + while (parISaveFormat.getWorldInfo(parString1) != null) { + parString1 = parString1 + "-"; + } + + return parString1; + } + private GuiScreen parentScreen; private GuiTextField field_146333_g; private GuiTextField field_146335_h; @@ -58,14 +85,8 @@ public class GuiCreateWorld extends GuiScreen { private String field_146329_I; private String field_146330_J; private int selectedIndex; + public String chunkProviderSettingsJson = ""; - /**+ - * These filenames are known to be restricted on one or more - * OS's. - */ - private static final String[] disallowedFilenames = new String[] { "CON", "COM", "PRN", "AUX", "CLOCK$", "NUL", - "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", - "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }; public GuiCreateWorld(GuiScreen parGuiScreen) { this.parentScreen = parGuiScreen; @@ -73,132 +94,9 @@ public class GuiCreateWorld extends GuiScreen { this.field_146330_J = I18n.format("selectWorld.newWorld", new Object[0]); } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.field_146333_g.updateCursorCounter(); - this.field_146335_h.updateCursorCounter(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, - I18n.format("selectWorld.create", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, - I18n.format("gui.cancel", new Object[0]))); - this.buttonList.add(this.btnGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, - I18n.format("selectWorld.gameMode", new Object[0]))); - this.buttonList.add(this.btnMoreOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, - I18n.format("selectWorld.moreWorldOptions", new Object[0]))); - this.buttonList.add(this.btnMapFeatures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, - I18n.format("selectWorld.mapFeatures", new Object[0]))); - this.btnMapFeatures.visible = false; - this.buttonList.add(this.btnBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, - I18n.format("selectWorld.bonusItems", new Object[0]))); - this.btnBonusItems.visible = false; - this.buttonList.add(this.btnMapType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, - I18n.format("selectWorld.mapType", new Object[0]))); - this.btnMapType.visible = false; - this.buttonList.add(this.btnAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, - I18n.format("selectWorld.allowCommands", new Object[0]))); - this.btnAllowCommands.visible = false; - this.buttonList.add(this.btnCustomizeType = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, - I18n.format("selectWorld.customizeType", new Object[0]))); - this.btnCustomizeType.visible = false; - this.field_146333_g = new GuiTextField(9, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); - this.field_146333_g.setFocused(true); - this.field_146333_g.setText(this.field_146330_J); - this.field_146335_h = new GuiTextField(10, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); - this.field_146335_h.setText(this.field_146329_I); - this.func_146316_a(this.field_146344_y); - this.func_146314_g(); - this.func_146319_h(); - } - - private void func_146314_g() { - this.field_146336_i = this.field_146333_g.getText().trim(); - - for (int i = 0; i < ChatAllowedCharacters.allowedCharactersArray.length; ++i) { - this.field_146336_i = this.field_146336_i.replace(ChatAllowedCharacters.allowedCharactersArray[i], '_'); - } - - if (StringUtils.isEmpty(this.field_146336_i)) { - this.field_146336_i = "World"; - } - - this.field_146336_i = func_146317_a(this.mc.getSaveLoader(), this.field_146336_i); - } - - private void func_146319_h() { - this.btnGameMode.displayString = I18n.format("selectWorld.gameMode", new Object[0]) + ": " - + I18n.format("selectWorld.gameMode." + this.gameMode, new Object[0]); - this.field_146323_G = I18n.format("selectWorld.gameMode." + this.gameMode + ".line1", new Object[0]); - this.field_146328_H = I18n.format("selectWorld.gameMode." + this.gameMode + ".line2", new Object[0]); - this.btnMapFeatures.displayString = I18n.format("selectWorld.mapFeatures", new Object[0]) + " "; - if (this.field_146341_s) { - this.btnMapFeatures.displayString = this.btnMapFeatures.displayString - + I18n.format("options.on", new Object[0]); - } else { - this.btnMapFeatures.displayString = this.btnMapFeatures.displayString - + I18n.format("options.off", new Object[0]); - } - - this.btnBonusItems.displayString = I18n.format("selectWorld.bonusItems", new Object[0]) + " "; - if (this.field_146338_v && !this.field_146337_w) { - this.btnBonusItems.displayString = this.btnBonusItems.displayString - + I18n.format("options.on", new Object[0]); - } else { - this.btnBonusItems.displayString = this.btnBonusItems.displayString - + I18n.format("options.off", new Object[0]); - } - - this.btnMapType.displayString = I18n.format("selectWorld.mapType", new Object[0]) + " " - + I18n.format(WorldType.worldTypes[this.selectedIndex].getTranslateName(), new Object[0]); - this.btnAllowCommands.displayString = I18n.format("selectWorld.allowCommands", new Object[0]) + " "; - if (this.allowCheats && !this.field_146337_w) { - this.btnAllowCommands.displayString = this.btnAllowCommands.displayString - + I18n.format("options.on", new Object[0]); - } else { - this.btnAllowCommands.displayString = this.btnAllowCommands.displayString - + I18n.format("options.off", new Object[0]); - } - - } - - public static String func_146317_a(ISaveFormat parISaveFormat, String parString1) { - parString1 = parString1.replaceAll("[\\./\"]", "_"); - - for (int i = 0; i < disallowedFilenames.length; ++i) { - if (parString1.equalsIgnoreCase(disallowedFilenames[i])) { - parString1 = "_" + parString1 + "_"; - } - } - - while (parISaveFormat.getWorldInfo(parString1) != null) { - parString1 = parString1 + "-"; - } - - return parString1; - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -313,11 +211,69 @@ public class GuiCreateWorld extends GuiScreen { } } - private boolean func_175299_g() { - WorldType worldtype = WorldType.worldTypes[this.selectedIndex]; - return worldtype != null && worldtype.getCanBeCreated() - ? (worldtype == WorldType.DEBUG_WORLD ? isShiftKeyDown() : true) - : false; + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("selectWorld.create", new Object[0]), this.width / 2, + 20, -1); + if (this.field_146344_y) { + this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterSeed", new Object[0]), + this.width / 2 - 100, 47, -6250336); + this.drawString(this.fontRendererObj, I18n.format( + StringUtils.isNotEmpty(field_146335_h.text) ? "createWorld.seedNote" : "selectWorld.seedInfo", + new Object[0]), this.width / 2 - 100, 85, -6250336); + if (this.btnMapFeatures.visible) { + this.drawString(this.fontRendererObj, I18n.format("selectWorld.mapFeatures.info", new Object[0]), + this.width / 2 - 150, 122, -6250336); + } + + if (this.btnAllowCommands.visible) { + this.drawString(this.fontRendererObj, I18n.format("selectWorld.allowCommands.info", new Object[0]), + this.width / 2 - 150, 172, -6250336); + } + + this.field_146335_h.drawTextBox(); + if (WorldType.worldTypes[this.selectedIndex].showWorldInfoNotice()) { + this.fontRendererObj.drawSplitString( + I18n.format(WorldType.worldTypes[this.selectedIndex].func_151359_c(), new Object[0]), + this.btnMapType.xPosition + 2, this.btnMapType.yPosition + 22, this.btnMapType.getButtonWidth(), + 10526880); + } + } else { + this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterName", new Object[0]), + this.width / 2 - 100, 47, -6250336); + this.drawString(this.fontRendererObj, + I18n.format("selectWorld.resultFolder", new Object[0]) + " " + this.field_146336_i, + this.width / 2 - 100, 85, -6250336); + this.field_146333_g.drawTextBox(); + this.drawString(this.fontRendererObj, this.field_146323_G, this.width / 2 - 100, 137, -6250336); + this.drawString(this.fontRendererObj, this.field_146328_H, this.width / 2 - 100, 149, -6250336); + } + + super.drawScreen(i, j, f); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + field_146333_g.fireInputEvent(event, param); + field_146335_h.fireInputEvent(event, param); + } + + private void func_146314_g() { + this.field_146336_i = this.field_146333_g.getText().trim(); + + for (int i = 0; i < ChatAllowedCharacters.allowedCharactersArray.length; ++i) { + this.field_146336_i = this.field_146336_i.replace(ChatAllowedCharacters.allowedCharactersArray[i], '_'); + } + + if (StringUtils.isEmpty(this.field_146336_i)) { + this.field_146336_i = "World"; + } + + this.field_146336_i = func_146317_a(this.mc.getSaveLoader(), this.field_146336_i); } private void func_146315_i() { @@ -366,11 +322,111 @@ public class GuiCreateWorld extends GuiScreen { } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + public void func_146318_a(WorldInfo parWorldInfo) { + this.field_146330_J = I18n.format("selectWorld.newWorld.copyOf", new Object[] { parWorldInfo.getWorldName() }); + this.field_146329_I = parWorldInfo.getSeed() + ""; + this.selectedIndex = parWorldInfo.getTerrainType().getWorldTypeID(); + this.chunkProviderSettingsJson = parWorldInfo.getGeneratorOptions(); + this.field_146341_s = parWorldInfo.isMapFeaturesEnabled(); + this.allowCheats = parWorldInfo.areCommandsAllowed(); + if (parWorldInfo.isHardcoreModeEnabled()) { + this.gameMode = "hardcore"; + } else if (parWorldInfo.getGameType().isSurvivalOrAdventure()) { + this.gameMode = "survival"; + } else if (parWorldInfo.getGameType().isCreative()) { + this.gameMode = "creative"; + } + + } + + private void func_146319_h() { + this.btnGameMode.displayString = I18n.format("selectWorld.gameMode", new Object[0]) + ": " + + I18n.format("selectWorld.gameMode." + this.gameMode, new Object[0]); + this.field_146323_G = I18n.format("selectWorld.gameMode." + this.gameMode + ".line1", new Object[0]); + this.field_146328_H = I18n.format("selectWorld.gameMode." + this.gameMode + ".line2", new Object[0]); + this.btnMapFeatures.displayString = I18n.format("selectWorld.mapFeatures", new Object[0]) + " "; + if (this.field_146341_s) { + this.btnMapFeatures.displayString = this.btnMapFeatures.displayString + + I18n.format("options.on", new Object[0]); + } else { + this.btnMapFeatures.displayString = this.btnMapFeatures.displayString + + I18n.format("options.off", new Object[0]); + } + + this.btnBonusItems.displayString = I18n.format("selectWorld.bonusItems", new Object[0]) + " "; + if (this.field_146338_v && !this.field_146337_w) { + this.btnBonusItems.displayString = this.btnBonusItems.displayString + + I18n.format("options.on", new Object[0]); + } else { + this.btnBonusItems.displayString = this.btnBonusItems.displayString + + I18n.format("options.off", new Object[0]); + } + + this.btnMapType.displayString = I18n.format("selectWorld.mapType", new Object[0]) + " " + + I18n.format(WorldType.worldTypes[this.selectedIndex].getTranslateName(), new Object[0]); + this.btnAllowCommands.displayString = I18n.format("selectWorld.allowCommands", new Object[0]) + " "; + if (this.allowCheats && !this.field_146337_w) { + this.btnAllowCommands.displayString = this.btnAllowCommands.displayString + + I18n.format("options.on", new Object[0]); + } else { + this.btnAllowCommands.displayString = this.btnAllowCommands.displayString + + I18n.format("options.off", new Object[0]); + } + + } + + private boolean func_175299_g() { + WorldType worldtype = WorldType.worldTypes[this.selectedIndex]; + return worldtype != null && worldtype.getCanBeCreated() + ? (worldtype == WorldType.DEBUG_WORLD ? isShiftKeyDown() : true) + : false; + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, + I18n.format("selectWorld.create", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, + I18n.format("gui.cancel", new Object[0]))); + this.buttonList.add(this.btnGameMode = new GuiButton(2, this.width / 2 - 75, 115, 150, 20, + I18n.format("selectWorld.gameMode", new Object[0]))); + this.buttonList.add(this.btnMoreOptions = new GuiButton(3, this.width / 2 - 75, 187, 150, 20, + I18n.format("selectWorld.moreWorldOptions", new Object[0]))); + this.buttonList.add(this.btnMapFeatures = new GuiButton(4, this.width / 2 - 155, 100, 150, 20, + I18n.format("selectWorld.mapFeatures", new Object[0]))); + this.btnMapFeatures.visible = false; + this.buttonList.add(this.btnBonusItems = new GuiButton(7, this.width / 2 + 5, 151, 150, 20, + I18n.format("selectWorld.bonusItems", new Object[0]))); + this.btnBonusItems.visible = false; + this.buttonList.add(this.btnMapType = new GuiButton(5, this.width / 2 + 5, 100, 150, 20, + I18n.format("selectWorld.mapType", new Object[0]))); + this.btnMapType.visible = false; + this.buttonList.add(this.btnAllowCommands = new GuiButton(6, this.width / 2 - 155, 151, 150, 20, + I18n.format("selectWorld.allowCommands", new Object[0]))); + this.btnAllowCommands.visible = false; + this.buttonList.add(this.btnCustomizeType = new GuiButton(8, this.width / 2 + 5, 120, 150, 20, + I18n.format("selectWorld.customizeType", new Object[0]))); + this.btnCustomizeType.visible = false; + this.field_146333_g = new GuiTextField(9, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); + this.field_146333_g.setFocused(true); + this.field_146333_g.setText(this.field_146330_J); + this.field_146335_h = new GuiTextField(10, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); + this.field_146335_h.setText(this.field_146329_I); + this.func_146316_a(this.field_146344_y); + this.func_146314_g(); + this.func_146319_h(); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { if (this.field_146333_g.isFocused() && !this.field_146344_y) { @@ -389,9 +445,8 @@ public class GuiCreateWorld extends GuiScreen { this.func_146314_g(); } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int parInt1, int parInt2, int parInt3) { super.mouseClicked(parInt1, parInt2, parInt3); @@ -403,66 +458,11 @@ public class GuiCreateWorld extends GuiScreen { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("selectWorld.create", new Object[0]), this.width / 2, - 20, -1); - if (this.field_146344_y) { - this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterSeed", new Object[0]), - this.width / 2 - 100, 47, -6250336); - this.drawString(this.fontRendererObj, I18n.format( - StringUtils.isNotEmpty(field_146335_h.text) ? "createWorld.seedNote" : "selectWorld.seedInfo", - new Object[0]), this.width / 2 - 100, 85, -6250336); - if (this.btnMapFeatures.visible) { - this.drawString(this.fontRendererObj, I18n.format("selectWorld.mapFeatures.info", new Object[0]), - this.width / 2 - 150, 122, -6250336); - } - - if (this.btnAllowCommands.visible) { - this.drawString(this.fontRendererObj, I18n.format("selectWorld.allowCommands.info", new Object[0]), - this.width / 2 - 150, 172, -6250336); - } - - this.field_146335_h.drawTextBox(); - if (WorldType.worldTypes[this.selectedIndex].showWorldInfoNotice()) { - this.fontRendererObj.drawSplitString( - I18n.format(WorldType.worldTypes[this.selectedIndex].func_151359_c(), new Object[0]), - this.btnMapType.xPosition + 2, this.btnMapType.yPosition + 22, this.btnMapType.getButtonWidth(), - 10526880); - } - } else { - this.drawString(this.fontRendererObj, I18n.format("selectWorld.enterName", new Object[0]), - this.width / 2 - 100, 47, -6250336); - this.drawString(this.fontRendererObj, - I18n.format("selectWorld.resultFolder", new Object[0]) + " " + this.field_146336_i, - this.width / 2 - 100, 85, -6250336); - this.field_146333_g.drawTextBox(); - this.drawString(this.fontRendererObj, this.field_146323_G, this.width / 2 - 100, 137, -6250336); - this.drawString(this.fontRendererObj, this.field_146328_H, this.width / 2 - 100, 149, -6250336); - } - - super.drawScreen(i, j, f); - } - - public void func_146318_a(WorldInfo parWorldInfo) { - this.field_146330_J = I18n.format("selectWorld.newWorld.copyOf", new Object[] { parWorldInfo.getWorldName() }); - this.field_146329_I = parWorldInfo.getSeed() + ""; - this.selectedIndex = parWorldInfo.getTerrainType().getWorldTypeID(); - this.chunkProviderSettingsJson = parWorldInfo.getGeneratorOptions(); - this.field_146341_s = parWorldInfo.isMapFeaturesEnabled(); - this.allowCheats = parWorldInfo.areCommandsAllowed(); - if (parWorldInfo.isHardcoreModeEnabled()) { - this.gameMode = "hardcore"; - } else if (parWorldInfo.getGameType().isSurvivalOrAdventure()) { - this.gameMode = "survival"; - } else if (parWorldInfo.getGameType().isCreative()) { - this.gameMode = "creative"; - } - + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); } @Override @@ -470,10 +470,12 @@ public class GuiCreateWorld extends GuiScreen { return field_146333_g.isFocused() || field_146335_h.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - field_146333_g.fireInputEvent(event, param); - field_146335_h.fireInputEvent(event, param); + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.field_146333_g.updateCursorCounter(); + this.field_146335_h.updateCursorCounter(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiCustomizeSkin.java b/src/game/java/net/minecraft/client/gui/GuiCustomizeSkin.java index 19176599..199d9610 100644 --- a/src/game/java/net/minecraft/client/gui/GuiCustomizeSkin.java +++ b/src/game/java/net/minecraft/client/gui/GuiCustomizeSkin.java @@ -3,28 +3,42 @@ package net.minecraft.client.gui; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.EnumPlayerModelParts; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiCustomizeSkin extends GuiScreen { + class ButtonPart extends GuiButton { + private final EnumPlayerModelParts playerModelParts; + + private ButtonPart(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, + EnumPlayerModelParts playerModelParts) { + super(parInt1, parInt2, parInt3, parInt4, parInt5, GuiCustomizeSkin.this.func_175358_a(playerModelParts)); + this.playerModelParts = playerModelParts; + } + } + private final GuiScreen parentScreen; + private String title; private GuiButton enableFNAWSkinsButton; @@ -33,10 +47,58 @@ public class GuiCustomizeSkin extends GuiScreen { this.parentScreen = parentScreenIn; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id == 200) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(this.parentScreen); + } else if (parGuiButton.id == 201) { + mc.gameSettings.enableFNAWSkins = !mc.gameSettings.enableFNAWSkins; + mc.getRenderManager().setEnableFNAWSkins(mc.getEnableFNAWSkins()); + enableFNAWSkinsButton.displayString = I18n.format("options.skinCustomisation.enableFNAWSkins") + ": " + + I18n.format(mc.gameSettings.enableFNAWSkins ? "options.on" : "options.off"); + } else if (parGuiButton instanceof GuiCustomizeSkin.ButtonPart) { + EnumPlayerModelParts enumplayermodelparts = ((GuiCustomizeSkin.ButtonPart) parGuiButton).playerModelParts; + this.mc.gameSettings.switchModelPartEnabled(enumplayermodelparts); + parGuiButton.displayString = this.func_175358_a(enumplayermodelparts); + } + + } + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, this.title, this.width / 2, 20, 16777215); + super.drawScreen(i, j, f); + } + + private String func_175358_a(EnumPlayerModelParts playerModelParts) { + String s; + if (this.mc.gameSettings.getModelParts().contains(playerModelParts)) { + s = I18n.format("options.on", new Object[0]); + } else { + s = I18n.format("options.off", new Object[0]); + } + + /* + * TODO: I changed this to getUnformattedText() from getFormattedText() because + * the latter was returning a pink formatting code at the end for no reason + */ + return playerModelParts.func_179326_d().getUnformattedText() + ": " + s; + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { int i = 0; @@ -61,62 +123,4 @@ public class GuiCustomizeSkin extends GuiScreen { this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height / 6 + 40 + 24 * (i >> 1), I18n.format("gui.done", new Object[0]))); } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id == 200) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(this.parentScreen); - } else if (parGuiButton.id == 201) { - mc.gameSettings.enableFNAWSkins = !mc.gameSettings.enableFNAWSkins; - mc.getRenderManager().setEnableFNAWSkins(mc.getEnableFNAWSkins()); - enableFNAWSkinsButton.displayString = I18n.format("options.skinCustomisation.enableFNAWSkins") + ": " - + I18n.format(mc.gameSettings.enableFNAWSkins ? "options.on" : "options.off"); - } else if (parGuiButton instanceof GuiCustomizeSkin.ButtonPart) { - EnumPlayerModelParts enumplayermodelparts = ((GuiCustomizeSkin.ButtonPart) parGuiButton).playerModelParts; - this.mc.gameSettings.switchModelPartEnabled(enumplayermodelparts); - parGuiButton.displayString = this.func_175358_a(enumplayermodelparts); - } - - } - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, this.title, this.width / 2, 20, 16777215); - super.drawScreen(i, j, f); - } - - private String func_175358_a(EnumPlayerModelParts playerModelParts) { - String s; - if (this.mc.gameSettings.getModelParts().contains(playerModelParts)) { - s = I18n.format("options.on", new Object[0]); - } else { - s = I18n.format("options.off", new Object[0]); - } - - /* - * TODO: I changed this to getUnformattedText() from getFormattedText() because - * the latter was returning a pink formatting code at the end for no reason - */ - return playerModelParts.func_179326_d().getUnformattedText() + ": " + s; - } - - class ButtonPart extends GuiButton { - private final EnumPlayerModelParts playerModelParts; - - private ButtonPart(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, - EnumPlayerModelParts playerModelParts) { - super(parInt1, parInt2, parInt3, parInt4, parInt5, GuiCustomizeSkin.this.func_175358_a(playerModelParts)); - this.playerModelParts = playerModelParts; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiCustomizeWorldScreen.java b/src/game/java/net/minecraft/client/gui/GuiCustomizeWorldScreen.java index 9b609424..942514d9 100644 --- a/src/game/java/net/minecraft/client/gui/GuiCustomizeWorldScreen.java +++ b/src/game/java/net/minecraft/client/gui/GuiCustomizeWorldScreen.java @@ -1,9 +1,10 @@ package net.minecraft.client.gui; +import java.io.IOException; +import java.util.Random; + import com.google.common.base.Predicate; import com.google.common.primitives.Floats; -import java.io.IOException; -import java.util.Random; import net.lax1dude.eaglercraft.v1_8.HString; import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; @@ -16,22 +17,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.gen.ChunkProviderSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -63,8 +67,8 @@ public class GuiCustomizeWorldScreen extends GuiScreen }; private ChunkProviderSettings.Factory field_175334_E = new ChunkProviderSettings.Factory(); private ChunkProviderSettings.Factory field_175336_F; - /**+ - * A Random instance for this world customization + /** + * + A Random instance for this world customization */ private Random random = new Random(); @@ -73,66 +77,257 @@ public class GuiCustomizeWorldScreen extends GuiScreen this.func_175324_a(parString1); } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ - public void initGui() { - int i = 0; - int j = 0; - if (this.field_175349_r != null) { - i = this.field_175349_r.func_178059_e(); - j = this.field_175349_r.getAmountScrolled(); - } + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + switch (parGuiButton.id) { + case 300: + this.field_175343_i.chunkProviderSettingsJson = this.field_175336_F.toString(); + this.mc.displayGuiScreen(this.field_175343_i); + break; + case 301: + for (int i = 0; i < this.field_175349_r.getSize(); ++i) { + GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = this.field_175349_r.getListEntry(i); + Gui gui = guipagebuttonlist$guientry.func_178022_a(); + if (gui instanceof GuiButton) { + GuiButton guibutton = (GuiButton) gui; + if (guibutton instanceof GuiSlider) { + float f = ((GuiSlider) guibutton).func_175217_d() * (0.75F + this.random.nextFloat() * 0.5F) + + (this.random.nextFloat() * 0.1F - 0.05F); + ((GuiSlider) guibutton).func_175219_a(MathHelper.clamp_float(f, 0.0F, 1.0F)); + } else if (guibutton instanceof GuiListButton) { + ((GuiListButton) guibutton).func_175212_b(this.random.nextBoolean()); + } + } - this.field_175341_a = I18n.format("options.customizeTitle", new Object[0]); - this.buttonList.clear(); - this.buttonList.add(this.field_175345_v = new GuiButton(302, 20, 5, 80, 20, - I18n.format("createWorld.customize.custom.prev", new Object[0]))); - this.buttonList.add(this.field_175344_w = new GuiButton(303, this.width - 100, 5, 80, 20, - I18n.format("createWorld.customize.custom.next", new Object[0]))); - this.buttonList.add(this.field_175346_u = new GuiButton(304, this.width / 2 - 187, this.height - 27, 90, 20, - I18n.format("createWorld.customize.custom.defaults", new Object[0]))); - this.buttonList.add(this.field_175347_t = new GuiButton(301, this.width / 2 - 92, this.height - 27, 90, 20, - I18n.format("createWorld.customize.custom.randomize", new Object[0]))); - this.buttonList.add(this.field_175350_z = new GuiButton(305, this.width / 2 + 3, this.height - 27, 90, 20, - I18n.format("createWorld.customize.custom.presets", new Object[0]))); - this.buttonList.add(this.field_175348_s = new GuiButton(300, this.width / 2 + 98, this.height - 27, 90, 20, - I18n.format("gui.done", new Object[0]))); - this.field_175346_u.enabled = this.field_175338_A; - this.field_175352_x = new GuiButton(306, this.width / 2 - 55, 160, 50, 20, - I18n.format("gui.yes", new Object[0])); - this.field_175352_x.visible = false; - this.buttonList.add(this.field_175352_x); - this.field_175351_y = new GuiButton(307, this.width / 2 + 5, 160, 50, 20, I18n.format("gui.no", new Object[0])); - this.field_175351_y.visible = false; - this.buttonList.add(this.field_175351_y); + Gui gui1 = guipagebuttonlist$guientry.func_178021_b(); + if (gui1 instanceof GuiButton) { + GuiButton guibutton1 = (GuiButton) gui1; + if (guibutton1 instanceof GuiSlider) { + float f1 = ((GuiSlider) guibutton1).func_175217_d() + * (0.75F + this.random.nextFloat() * 0.5F) + + (this.random.nextFloat() * 0.1F - 0.05F); + ((GuiSlider) guibutton1).func_175219_a(MathHelper.clamp_float(f1, 0.0F, 1.0F)); + } else if (guibutton1 instanceof GuiListButton) { + ((GuiListButton) guibutton1).func_175212_b(this.random.nextBoolean()); + } + } + } + + return; + case 302: + this.field_175349_r.func_178071_h(); + this.func_175328_i(); + break; + case 303: + this.field_175349_r.func_178064_i(); + this.func_175328_i(); + break; + case 304: + if (this.field_175338_A) { + this.func_175322_b(304); + } + break; + case 305: + this.mc.displayGuiScreen(new GuiScreenCustomizePresets(this)); + break; + case 306: + this.func_175331_h(); + break; + case 307: + this.field_175339_B = 0; + this.func_175331_h(); + } + + } + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.field_175349_r.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.field_175341_a, this.width / 2, 2, 16777215); + this.drawCenteredString(this.fontRendererObj, this.field_175333_f, this.width / 2, 12, 16777215); + this.drawCenteredString(this.fontRendererObj, this.field_175335_g, this.width / 2, 22, 16777215); + super.drawScreen(i, j, f); if (this.field_175339_B != 0) { - this.field_175352_x.visible = true; - this.field_175351_y.visible = true; - } - - this.func_175325_f(); - if (i != 0) { - this.field_175349_r.func_181156_c(i); - this.field_175349_r.scrollBy(j); - this.func_175328_i(); + drawRect(0, 0, this.width, this.height, Integer.MIN_VALUE); + this.drawHorizontalLine(this.width / 2 - 91, this.width / 2 + 90, 99, -2039584); + this.drawHorizontalLine(this.width / 2 - 91, this.width / 2 + 90, 185, -6250336); + this.drawVerticalLine(this.width / 2 - 91, 99, 185, -2039584); + this.drawVerticalLine(this.width / 2 + 90, 99, 185, -6250336); + float f1 = 85.0F; + float f2 = 180.0F; + GlStateManager.disableLighting(); + GlStateManager.disableFog(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.mc.getTextureManager().bindTexture(optionsBackground); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + float f3 = 32.0F; + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double) (this.width / 2 - 90), 185.0D, 0.0D).tex(0.0D, 2.65625D).color(64, 64, 64, 64) + .endVertex(); + worldrenderer.pos((double) (this.width / 2 + 90), 185.0D, 0.0D).tex(5.625D, 2.65625D).color(64, 64, 64, 64) + .endVertex(); + worldrenderer.pos((double) (this.width / 2 + 90), 100.0D, 0.0D).tex(5.625D, 0.0D).color(64, 64, 64, 64) + .endVertex(); + worldrenderer.pos((double) (this.width / 2 - 90), 100.0D, 0.0D).tex(0.0D, 0.0D).color(64, 64, 64, 64) + .endVertex(); + tessellator.draw(); + this.drawCenteredString(this.fontRendererObj, + I18n.format("createWorld.customize.custom.confirmTitle", new Object[0]), this.width / 2, 105, + 16777215); + this.drawCenteredString(this.fontRendererObj, + I18n.format("createWorld.customize.custom.confirm1", new Object[0]), this.width / 2, 125, 16777215); + this.drawCenteredString(this.fontRendererObj, + I18n.format("createWorld.customize.custom.confirm2", new Object[0]), this.width / 2, 135, 16777215); + this.field_175352_x.drawButton(this.mc, i, j); + this.field_175351_y.drawButton(this.mc, i, j); } } - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.field_175349_r.handleMouseInput(); + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + field_175349_r.fireInputEvent(event, param); } - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.field_175349_r.handleTouchInput(); + public void func_175319_a(int i, String s) { + float f = 0.0F; + + try { + f = Float.parseFloat(s); + } catch (NumberFormatException var5) { + ; + } + + float f1 = 0.0F; + switch (i) { + case 132: + f1 = this.field_175336_F.mainNoiseScaleX = MathHelper.clamp_float(f, 1.0F, 5000.0F); + break; + case 133: + f1 = this.field_175336_F.mainNoiseScaleY = MathHelper.clamp_float(f, 1.0F, 5000.0F); + break; + case 134: + f1 = this.field_175336_F.mainNoiseScaleZ = MathHelper.clamp_float(f, 1.0F, 5000.0F); + break; + case 135: + f1 = this.field_175336_F.depthNoiseScaleX = MathHelper.clamp_float(f, 1.0F, 2000.0F); + break; + case 136: + f1 = this.field_175336_F.depthNoiseScaleZ = MathHelper.clamp_float(f, 1.0F, 2000.0F); + break; + case 137: + f1 = this.field_175336_F.depthNoiseScaleExponent = MathHelper.clamp_float(f, 0.01F, 20.0F); + break; + case 138: + f1 = this.field_175336_F.baseSize = MathHelper.clamp_float(f, 1.0F, 25.0F); + break; + case 139: + f1 = this.field_175336_F.coordinateScale = MathHelper.clamp_float(f, 1.0F, 6000.0F); + break; + case 140: + f1 = this.field_175336_F.heightScale = MathHelper.clamp_float(f, 1.0F, 6000.0F); + break; + case 141: + f1 = this.field_175336_F.stretchY = MathHelper.clamp_float(f, 0.01F, 50.0F); + break; + case 142: + f1 = this.field_175336_F.upperLimitScale = MathHelper.clamp_float(f, 1.0F, 5000.0F); + break; + case 143: + f1 = this.field_175336_F.lowerLimitScale = MathHelper.clamp_float(f, 1.0F, 5000.0F); + break; + case 144: + f1 = this.field_175336_F.biomeDepthWeight = MathHelper.clamp_float(f, 1.0F, 20.0F); + break; + case 145: + f1 = this.field_175336_F.biomeDepthOffset = MathHelper.clamp_float(f, 0.0F, 20.0F); + break; + case 146: + f1 = this.field_175336_F.biomeScaleWeight = MathHelper.clamp_float(f, 1.0F, 20.0F); + break; + case 147: + f1 = this.field_175336_F.biomeScaleOffset = MathHelper.clamp_float(f, 0.0F, 20.0F); + } + + if (f1 != f && f != 0.0F) { + ((GuiTextField) this.field_175349_r.func_178061_c(i)).setText(this.func_175330_b(i, f1)); + } + + ((GuiSlider) this.field_175349_r.func_178061_c(i - 132 + 100)).func_175218_a(f1, false); + if (!this.field_175336_F.equals(this.field_175334_E)) { + this.func_181031_a(true); + } + + } + + public void func_175321_a(int i, boolean flag) { + switch (i) { + case 148: + this.field_175336_F.useCaves = flag; + break; + case 149: + this.field_175336_F.useDungeons = flag; + break; + case 150: + this.field_175336_F.useStrongholds = flag; + break; + case 151: + this.field_175336_F.useVillages = flag; + break; + case 152: + this.field_175336_F.useMineShafts = flag; + break; + case 153: + this.field_175336_F.useTemples = flag; + break; + case 154: + this.field_175336_F.useRavines = flag; + break; + case 155: + this.field_175336_F.useWaterLakes = flag; + break; + case 156: + this.field_175336_F.useLavaLakes = flag; + break; + case 161: + this.field_175336_F.useLavaOceans = flag; + break; + case 210: + this.field_175336_F.useMonuments = flag; + } + + if (!this.field_175336_F.equals(this.field_175334_E)) { + this.func_181031_a(true); + } + + } + + private void func_175322_b(int parInt1) { + this.field_175339_B = parInt1; + this.func_175329_a(true); + } + + public String func_175323_a() { + return this.field_175336_F.toString().replace("\n", ""); + } + + public void func_175324_a(String parString1) { + if (parString1 != null && parString1.length() != 0) { + this.field_175336_F = ChunkProviderSettings.Factory.jsonToFactory(parString1); + } else { + this.field_175336_F = new ChunkProviderSettings.Factory(); + } + } private void func_175325_f() { @@ -484,97 +679,60 @@ public class GuiCustomizeWorldScreen extends GuiScreen this.func_175328_i(); } - public String func_175323_a() { - return this.field_175336_F.toString().replace("\n", ""); + private void func_175326_g() { + this.field_175336_F.func_177863_a(); + this.func_175325_f(); + this.func_181031_a(false); } - public void func_175324_a(String parString1) { - if (parString1 != null && parString1.length() != 0) { - this.field_175336_F = ChunkProviderSettings.Factory.jsonToFactory(parString1); - } else { - this.field_175336_F = new ChunkProviderSettings.Factory(); - } + private void func_175327_a(float parFloat1) { + Gui gui = this.field_175349_r.func_178056_g(); + if (gui instanceof GuiTextField) { + float f = parFloat1; + if (GuiScreen.isShiftKeyDown()) { + f = parFloat1 * 0.1F; + if (GuiScreen.isCtrlKeyDown()) { + f *= 0.1F; + } + } else if (GuiScreen.isCtrlKeyDown()) { + f = parFloat1 * 10.0F; + if (GuiScreen.isAltKeyDown()) { + f *= 10.0F; + } + } + GuiTextField guitextfield = (GuiTextField) gui; + Float f1 = Floats.tryParse(guitextfield.getText()); + if (f1 != null) { + f1 = Float.valueOf(f1.floatValue() + f); + int i = guitextfield.getId(); + String s = this.func_175330_b(guitextfield.getId(), f1.floatValue()); + guitextfield.setText(s); + this.func_175319_a(i, s); + } + } } - public void func_175319_a(int i, String s) { - float f = 0.0F; - - try { - f = Float.parseFloat(s); - } catch (NumberFormatException var5) { - ; - } - - float f1 = 0.0F; - switch (i) { - case 132: - f1 = this.field_175336_F.mainNoiseScaleX = MathHelper.clamp_float(f, 1.0F, 5000.0F); - break; - case 133: - f1 = this.field_175336_F.mainNoiseScaleY = MathHelper.clamp_float(f, 1.0F, 5000.0F); - break; - case 134: - f1 = this.field_175336_F.mainNoiseScaleZ = MathHelper.clamp_float(f, 1.0F, 5000.0F); - break; - case 135: - f1 = this.field_175336_F.depthNoiseScaleX = MathHelper.clamp_float(f, 1.0F, 2000.0F); - break; - case 136: - f1 = this.field_175336_F.depthNoiseScaleZ = MathHelper.clamp_float(f, 1.0F, 2000.0F); - break; - case 137: - f1 = this.field_175336_F.depthNoiseScaleExponent = MathHelper.clamp_float(f, 0.01F, 20.0F); - break; - case 138: - f1 = this.field_175336_F.baseSize = MathHelper.clamp_float(f, 1.0F, 25.0F); - break; - case 139: - f1 = this.field_175336_F.coordinateScale = MathHelper.clamp_float(f, 1.0F, 6000.0F); - break; - case 140: - f1 = this.field_175336_F.heightScale = MathHelper.clamp_float(f, 1.0F, 6000.0F); - break; - case 141: - f1 = this.field_175336_F.stretchY = MathHelper.clamp_float(f, 0.01F, 50.0F); - break; - case 142: - f1 = this.field_175336_F.upperLimitScale = MathHelper.clamp_float(f, 1.0F, 5000.0F); - break; - case 143: - f1 = this.field_175336_F.lowerLimitScale = MathHelper.clamp_float(f, 1.0F, 5000.0F); - break; - case 144: - f1 = this.field_175336_F.biomeDepthWeight = MathHelper.clamp_float(f, 1.0F, 20.0F); - break; - case 145: - f1 = this.field_175336_F.biomeDepthOffset = MathHelper.clamp_float(f, 0.0F, 20.0F); - break; - case 146: - f1 = this.field_175336_F.biomeScaleWeight = MathHelper.clamp_float(f, 1.0F, 20.0F); - break; - case 147: - f1 = this.field_175336_F.biomeScaleOffset = MathHelper.clamp_float(f, 0.0F, 20.0F); - } - - if (f1 != f && f != 0.0F) { - ((GuiTextField) this.field_175349_r.func_178061_c(i)).setText(this.func_175330_b(i, f1)); - } - - ((GuiSlider) this.field_175349_r.func_178061_c(i - 132 + 100)).func_175218_a(f1, false); - if (!this.field_175336_F.equals(this.field_175334_E)) { - this.func_181031_a(true); - } - + private void func_175328_i() { + this.field_175345_v.enabled = this.field_175349_r.func_178059_e() != 0; + this.field_175344_w.enabled = this.field_175349_r.func_178059_e() != this.field_175349_r.func_178057_f() - 1; + this.field_175333_f = I18n.format("book.pageIndicator", + new Object[] { Integer.valueOf(this.field_175349_r.func_178059_e() + 1), + Integer.valueOf(this.field_175349_r.func_178057_f()) }); + this.field_175335_g = this.field_175342_h[this.field_175349_r.func_178059_e()]; + this.field_175347_t.enabled = this.field_175349_r.func_178059_e() != this.field_175349_r.func_178057_f() - 1; } - private void func_181031_a(boolean parFlag) { - this.field_175338_A = parFlag; - this.field_175346_u.enabled = parFlag; - } - - public String getText(int i, String s, float f) { - return s + ": " + this.func_175330_b(i, f); + private void func_175329_a(boolean parFlag) { + this.field_175352_x.visible = parFlag; + this.field_175351_y.visible = parFlag; + this.field_175347_t.enabled = !parFlag; + this.field_175348_s.enabled = !parFlag; + this.field_175345_v.enabled = !parFlag; + this.field_175344_w.enabled = !parFlag; + this.field_175346_u.enabled = this.field_175338_A && !parFlag; + this.field_175350_z.enabled = !parFlag; + this.field_175349_r.func_181155_a(!parFlag); } private String func_175330_b(int parInt1, float parFloat1) { @@ -658,46 +816,134 @@ public class GuiCustomizeWorldScreen extends GuiScreen } } - public void func_175321_a(int i, boolean flag) { - switch (i) { - case 148: - this.field_175336_F.useCaves = flag; + private void func_175331_h() { + switch (this.field_175339_B) { + case 300: + this.actionPerformed((GuiListButton) this.field_175349_r.func_178061_c(300)); break; - case 149: - this.field_175336_F.useDungeons = flag; - break; - case 150: - this.field_175336_F.useStrongholds = flag; - break; - case 151: - this.field_175336_F.useVillages = flag; - break; - case 152: - this.field_175336_F.useMineShafts = flag; - break; - case 153: - this.field_175336_F.useTemples = flag; - break; - case 154: - this.field_175336_F.useRavines = flag; - break; - case 155: - this.field_175336_F.useWaterLakes = flag; - break; - case 156: - this.field_175336_F.useLavaLakes = flag; - break; - case 161: - this.field_175336_F.useLavaOceans = flag; - break; - case 210: - this.field_175336_F.useMonuments = flag; + case 304: + this.func_175326_g(); } - if (!this.field_175336_F.equals(this.field_175334_E)) { - this.func_181031_a(true); + this.field_175339_B = 0; + this.field_175340_C = true; + this.func_175329_a(false); + } + + private void func_181031_a(boolean parFlag) { + this.field_175338_A = parFlag; + this.field_175346_u.enabled = parFlag; + } + + public String getText(int i, String s, float f) { + return s + ": " + this.func_175330_b(i, f); + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.field_175349_r.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.field_175349_r.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + int i = 0; + int j = 0; + if (this.field_175349_r != null) { + i = this.field_175349_r.func_178059_e(); + j = this.field_175349_r.getAmountScrolled(); } + this.field_175341_a = I18n.format("options.customizeTitle", new Object[0]); + this.buttonList.clear(); + this.buttonList.add(this.field_175345_v = new GuiButton(302, 20, 5, 80, 20, + I18n.format("createWorld.customize.custom.prev", new Object[0]))); + this.buttonList.add(this.field_175344_w = new GuiButton(303, this.width - 100, 5, 80, 20, + I18n.format("createWorld.customize.custom.next", new Object[0]))); + this.buttonList.add(this.field_175346_u = new GuiButton(304, this.width / 2 - 187, this.height - 27, 90, 20, + I18n.format("createWorld.customize.custom.defaults", new Object[0]))); + this.buttonList.add(this.field_175347_t = new GuiButton(301, this.width / 2 - 92, this.height - 27, 90, 20, + I18n.format("createWorld.customize.custom.randomize", new Object[0]))); + this.buttonList.add(this.field_175350_z = new GuiButton(305, this.width / 2 + 3, this.height - 27, 90, 20, + I18n.format("createWorld.customize.custom.presets", new Object[0]))); + this.buttonList.add(this.field_175348_s = new GuiButton(300, this.width / 2 + 98, this.height - 27, 90, 20, + I18n.format("gui.done", new Object[0]))); + this.field_175346_u.enabled = this.field_175338_A; + this.field_175352_x = new GuiButton(306, this.width / 2 - 55, 160, 50, 20, + I18n.format("gui.yes", new Object[0])); + this.field_175352_x.visible = false; + this.buttonList.add(this.field_175352_x); + this.field_175351_y = new GuiButton(307, this.width / 2 + 5, 160, 50, 20, I18n.format("gui.no", new Object[0])); + this.field_175351_y.visible = false; + this.buttonList.add(this.field_175351_y); + if (this.field_175339_B != 0) { + this.field_175352_x.visible = true; + this.field_175351_y.visible = true; + } + + this.func_175325_f(); + if (i != 0) { + this.field_175349_r.func_181156_c(i); + this.field_175349_r.scrollBy(j); + this.func_175328_i(); + } + + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + super.keyTyped(parChar1, parInt1); + if (this.field_175339_B == 0) { + switch (parInt1) { + case 200: + this.func_175327_a(1.0F); + break; + case 208: + this.func_175327_a(-1.0F); + break; + default: + this.field_175349_r.func_178062_a(parChar1, parInt1); + } + + } + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + if (this.field_175339_B == 0 && !this.field_175340_C) { + this.field_175349_r.mouseClicked(parInt1, parInt2, parInt3); + } + } + + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton + */ + protected void mouseReleased(int i, int j, int k) { + super.mouseReleased(i, j, k); + if (this.field_175340_C) { + this.field_175340_C = false; + } else if (this.field_175339_B == 0) { + this.field_175349_r.mouseReleased(i, j, k); + } } public void onTick(int i, float f) { @@ -961,253 +1207,9 @@ public class GuiCustomizeWorldScreen extends GuiScreen } - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - switch (parGuiButton.id) { - case 300: - this.field_175343_i.chunkProviderSettingsJson = this.field_175336_F.toString(); - this.mc.displayGuiScreen(this.field_175343_i); - break; - case 301: - for (int i = 0; i < this.field_175349_r.getSize(); ++i) { - GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = this.field_175349_r.getListEntry(i); - Gui gui = guipagebuttonlist$guientry.func_178022_a(); - if (gui instanceof GuiButton) { - GuiButton guibutton = (GuiButton) gui; - if (guibutton instanceof GuiSlider) { - float f = ((GuiSlider) guibutton).func_175217_d() * (0.75F + this.random.nextFloat() * 0.5F) - + (this.random.nextFloat() * 0.1F - 0.05F); - ((GuiSlider) guibutton).func_175219_a(MathHelper.clamp_float(f, 0.0F, 1.0F)); - } else if (guibutton instanceof GuiListButton) { - ((GuiListButton) guibutton).func_175212_b(this.random.nextBoolean()); - } - } - - Gui gui1 = guipagebuttonlist$guientry.func_178021_b(); - if (gui1 instanceof GuiButton) { - GuiButton guibutton1 = (GuiButton) gui1; - if (guibutton1 instanceof GuiSlider) { - float f1 = ((GuiSlider) guibutton1).func_175217_d() - * (0.75F + this.random.nextFloat() * 0.5F) - + (this.random.nextFloat() * 0.1F - 0.05F); - ((GuiSlider) guibutton1).func_175219_a(MathHelper.clamp_float(f1, 0.0F, 1.0F)); - } else if (guibutton1 instanceof GuiListButton) { - ((GuiListButton) guibutton1).func_175212_b(this.random.nextBoolean()); - } - } - } - - return; - case 302: - this.field_175349_r.func_178071_h(); - this.func_175328_i(); - break; - case 303: - this.field_175349_r.func_178064_i(); - this.func_175328_i(); - break; - case 304: - if (this.field_175338_A) { - this.func_175322_b(304); - } - break; - case 305: - this.mc.displayGuiScreen(new GuiScreenCustomizePresets(this)); - break; - case 306: - this.func_175331_h(); - break; - case 307: - this.field_175339_B = 0; - this.func_175331_h(); - } - - } - } - - private void func_175326_g() { - this.field_175336_F.func_177863_a(); - this.func_175325_f(); - this.func_181031_a(false); - } - - private void func_175322_b(int parInt1) { - this.field_175339_B = parInt1; - this.func_175329_a(true); - } - - private void func_175331_h() { - switch (this.field_175339_B) { - case 300: - this.actionPerformed((GuiListButton) this.field_175349_r.func_178061_c(300)); - break; - case 304: - this.func_175326_g(); - } - - this.field_175339_B = 0; - this.field_175340_C = true; - this.func_175329_a(false); - } - - private void func_175329_a(boolean parFlag) { - this.field_175352_x.visible = parFlag; - this.field_175351_y.visible = parFlag; - this.field_175347_t.enabled = !parFlag; - this.field_175348_s.enabled = !parFlag; - this.field_175345_v.enabled = !parFlag; - this.field_175344_w.enabled = !parFlag; - this.field_175346_u.enabled = this.field_175338_A && !parFlag; - this.field_175350_z.enabled = !parFlag; - this.field_175349_r.func_181155_a(!parFlag); - } - - private void func_175328_i() { - this.field_175345_v.enabled = this.field_175349_r.func_178059_e() != 0; - this.field_175344_w.enabled = this.field_175349_r.func_178059_e() != this.field_175349_r.func_178057_f() - 1; - this.field_175333_f = I18n.format("book.pageIndicator", - new Object[] { Integer.valueOf(this.field_175349_r.func_178059_e() + 1), - Integer.valueOf(this.field_175349_r.func_178057_f()) }); - this.field_175335_g = this.field_175342_h[this.field_175349_r.func_178059_e()]; - this.field_175347_t.enabled = this.field_175349_r.func_178059_e() != this.field_175349_r.func_178057_f() - 1; - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - super.keyTyped(parChar1, parInt1); - if (this.field_175339_B == 0) { - switch (parInt1) { - case 200: - this.func_175327_a(1.0F); - break; - case 208: - this.func_175327_a(-1.0F); - break; - default: - this.field_175349_r.func_178062_a(parChar1, parInt1); - } - - } - } - - private void func_175327_a(float parFloat1) { - Gui gui = this.field_175349_r.func_178056_g(); - if (gui instanceof GuiTextField) { - float f = parFloat1; - if (GuiScreen.isShiftKeyDown()) { - f = parFloat1 * 0.1F; - if (GuiScreen.isCtrlKeyDown()) { - f *= 0.1F; - } - } else if (GuiScreen.isCtrlKeyDown()) { - f = parFloat1 * 10.0F; - if (GuiScreen.isAltKeyDown()) { - f *= 10.0F; - } - } - - GuiTextField guitextfield = (GuiTextField) gui; - Float f1 = Floats.tryParse(guitextfield.getText()); - if (f1 != null) { - f1 = Float.valueOf(f1.floatValue() + f); - int i = guitextfield.getId(); - String s = this.func_175330_b(guitextfield.getId(), f1.floatValue()); - guitextfield.setText(s); - this.func_175319_a(i, s); - } - } - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - if (this.field_175339_B == 0 && !this.field_175340_C) { - this.field_175349_r.mouseClicked(parInt1, parInt2, parInt3); - } - } - - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton - */ - protected void mouseReleased(int i, int j, int k) { - super.mouseReleased(i, j, k); - if (this.field_175340_C) { - this.field_175340_C = false; - } else if (this.field_175339_B == 0) { - this.field_175349_r.mouseReleased(i, j, k); - } - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.field_175349_r.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.field_175341_a, this.width / 2, 2, 16777215); - this.drawCenteredString(this.fontRendererObj, this.field_175333_f, this.width / 2, 12, 16777215); - this.drawCenteredString(this.fontRendererObj, this.field_175335_g, this.width / 2, 22, 16777215); - super.drawScreen(i, j, f); - if (this.field_175339_B != 0) { - drawRect(0, 0, this.width, this.height, Integer.MIN_VALUE); - this.drawHorizontalLine(this.width / 2 - 91, this.width / 2 + 90, 99, -2039584); - this.drawHorizontalLine(this.width / 2 - 91, this.width / 2 + 90, 185, -6250336); - this.drawVerticalLine(this.width / 2 - 91, 99, 185, -2039584); - this.drawVerticalLine(this.width / 2 + 90, 99, 185, -6250336); - float f1 = 85.0F; - float f2 = 180.0F; - GlStateManager.disableLighting(); - GlStateManager.disableFog(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - this.mc.getTextureManager().bindTexture(optionsBackground); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - float f3 = 32.0F; - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double) (this.width / 2 - 90), 185.0D, 0.0D).tex(0.0D, 2.65625D).color(64, 64, 64, 64) - .endVertex(); - worldrenderer.pos((double) (this.width / 2 + 90), 185.0D, 0.0D).tex(5.625D, 2.65625D).color(64, 64, 64, 64) - .endVertex(); - worldrenderer.pos((double) (this.width / 2 + 90), 100.0D, 0.0D).tex(5.625D, 0.0D).color(64, 64, 64, 64) - .endVertex(); - worldrenderer.pos((double) (this.width / 2 - 90), 100.0D, 0.0D).tex(0.0D, 0.0D).color(64, 64, 64, 64) - .endVertex(); - tessellator.draw(); - this.drawCenteredString(this.fontRendererObj, - I18n.format("createWorld.customize.custom.confirmTitle", new Object[0]), this.width / 2, 105, - 16777215); - this.drawCenteredString(this.fontRendererObj, - I18n.format("createWorld.customize.custom.confirm1", new Object[0]), this.width / 2, 125, 16777215); - this.drawCenteredString(this.fontRendererObj, - I18n.format("createWorld.customize.custom.confirm2", new Object[0]), this.width / 2, 135, 16777215); - this.field_175352_x.drawButton(this.mc, i, j); - this.field_175351_y.drawButton(this.mc, i, j); - } - - } - @Override public boolean showCopyPasteButtons() { return field_175349_r.isTextFieldFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - field_175349_r.fireInputEvent(event, param); - } - } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiDisconnected.java b/src/game/java/net/minecraft/client/gui/GuiDisconnected.java index 25fb53b7..1a4f782b 100644 --- a/src/game/java/net/minecraft/client/gui/GuiDisconnected.java +++ b/src/game/java/net/minecraft/client/gui/GuiDisconnected.java @@ -9,31 +9,39 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiDisconnected extends GuiScreen { + public static GuiScreen createRateLimitKick(GuiScreen prev) { + return new GuiDisconnected(prev, "connect.failed", new ChatComponentTranslation("disconnect.tooManyRequests")); + } + private String reason; private IChatComponent message; private List multilineMessage; private final GuiScreen parentScreen; + private int field_175353_i; public GuiDisconnected(GuiScreen screen, String reasonLocalizationKey, IChatComponent chatComp) { @@ -42,33 +50,9 @@ public class GuiDisconnected extends GuiScreen { this.message = chatComp; } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - this.multilineMessage = this.fontRendererObj.listFormattedStringToWidth(this.message.getFormattedText(), - this.width - 50); - this.field_175353_i = this.multilineMessage.size() * this.fontRendererObj.FONT_HEIGHT; - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, - this.height / 2 + this.field_175353_i / 2 + this.fontRendererObj.FONT_HEIGHT, - I18n.format("gui.toMenu", new Object[0]))); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.id == 0) { @@ -77,9 +61,9 @@ public class GuiDisconnected extends GuiScreen { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -97,6 +81,29 @@ public class GuiDisconnected extends GuiScreen { super.drawScreen(i, j, f); } + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + this.multilineMessage = this.fontRendererObj.listFormattedStringToWidth(this.message.getFormattedText(), + this.width - 50); + this.field_175353_i = this.multilineMessage.size() * this.fontRendererObj.FONT_HEIGHT; + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, + this.height / 2 + this.field_175353_i / 2 + this.fontRendererObj.FONT_HEIGHT, + I18n.format("gui.toMenu", new Object[0]))); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + } + public void updateScreen() { IPCPacket15Crashed[] pkt = SingleplayerServerController.worldStatusErrors(); if (pkt != null && pkt.length > 0) { @@ -104,8 +111,4 @@ public class GuiDisconnected extends GuiScreen { GuiScreenIntegratedServerBusy.createException(this, "singleplayer.failed.serverCrash", pkt)); } } - - public static GuiScreen createRateLimitKick(GuiScreen prev) { - return new GuiDisconnected(prev, "connect.failed", new ChatComponentTranslation("disconnect.tooManyRequests")); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiDownloadTerrain.java b/src/game/java/net/minecraft/client/gui/GuiDownloadTerrain.java index c341a0ad..8f24797c 100644 --- a/src/game/java/net/minecraft/client/gui/GuiDownloadTerrain.java +++ b/src/game/java/net/minecraft/client/gui/GuiDownloadTerrain.java @@ -4,22 +4,25 @@ import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.resources.I18n; import net.minecraft.network.play.client.C00PacketKeepAlive; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,26 +35,52 @@ public class GuiDownloadTerrain extends GuiScreen { this.netHandlerPlayClient = netHandler; } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { + public boolean canCloseGui() { + return false; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return false; + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawBackground(0); + this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingTerrain", new Object[0]), + this.width / 2, this.height / 2 - 50, 16777215); + super.drawScreen(i, j, f); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { this.buttonList.clear(); } - /**+ - * Called from the main game loop to update the screen. + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + } + + public boolean shouldHangupIntegratedServer() { + return false; + } + + /** + * + Called from the main game loop to update the screen. */ public void updateScreen() { ++this.progress; @@ -61,31 +90,4 @@ public class GuiDownloadTerrain extends GuiScreen { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawBackground(0); - this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingTerrain", new Object[0]), - this.width / 2, this.height / 2 - 50, 16777215); - super.drawScreen(i, j, f); - } - - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player - */ - public boolean doesGuiPauseGame() { - return false; - } - - public boolean shouldHangupIntegratedServer() { - return false; - } - - public boolean canCloseGui() { - return false; - } - } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiEnchantment.java b/src/game/java/net/minecraft/client/gui/GuiEnchantment.java index ff2b2429..2ae1ba2f 100644 --- a/src/game/java/net/minecraft/client/gui/GuiEnchantment.java +++ b/src/game/java/net/minecraft/client/gui/GuiEnchantment.java @@ -1,14 +1,15 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; import java.util.ArrayList; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.Mouse; -import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.Mouse; +import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.client.model.ModelBook; @@ -26,47 +27,48 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.world.IWorldNameable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiEnchantment extends GuiContainer { - /**+ - * The ResourceLocation containing the Enchantment GUI texture - * location + /** + * + The ResourceLocation containing the Enchantment GUI texture location */ private static final ResourceLocation ENCHANTMENT_TABLE_GUI_TEXTURE = new ResourceLocation( "textures/gui/container/enchanting_table.png"); - /**+ - * The ResourceLocation containing the texture for the Book - * rendered above the enchantment table + /** + * + The ResourceLocation containing the texture for the Book rendered above the + * enchantment table */ private static final ResourceLocation ENCHANTMENT_TABLE_BOOK_TEXTURE = new ResourceLocation( "textures/entity/enchanting_table_book.png"); - /**+ - * The ModelBook instance used for rendering the book on the - * Enchantment table + /** + * + The ModelBook instance used for rendering the book on the Enchantment table */ private static final ModelBook MODEL_BOOK = new ModelBook(); private final InventoryPlayer playerInventory; - /**+ - * A Random instance for use with the enchantment gui + /** + * + A Random instance for use with the enchantment gui */ private EaglercraftRandom random = new EaglercraftRandom(); private ContainerEnchantment container; @@ -87,45 +89,8 @@ public class GuiEnchantment extends GuiContainer { this.field_175380_I = parIWorldNameable; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - this.fontRendererObj.drawString(this.field_175380_I.getDisplayName().getUnformattedText(), 12, 5, 4210752); - this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - super.updateScreen(); - this.func_147068_g(); - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - int i = (this.width - this.xSize) / 2; - int j = (this.height - this.ySize) / 2; - - for (int k = 0; k < 3; ++k) { - int l = parInt1 - (i + 60); - int i1 = parInt2 - (j + 14 + 19 * k); - if (l >= 0 && i1 >= 0 && l < 108 && i1 < 19 && this.container.enchantItem(this.mc.thePlayer, k)) { - this.mc.playerController.sendEnchantPacket(this.container.windowId, k); - } - } - - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float f, int i, int j) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -238,9 +203,19 @@ public class GuiEnchantment extends GuiContainer { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(this.field_175380_I.getDisplayName().getUnformattedText(), 12, 5, 4210752); + this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { super.drawScreen(i, j, f); @@ -337,4 +312,30 @@ public class GuiEnchantment extends GuiContainer { this.field_147081_y += (f1 - this.field_147081_y) * 0.9F; this.field_147071_v += this.field_147081_y; } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + int i = (this.width - this.xSize) / 2; + int j = (this.height - this.ySize) / 2; + + for (int k = 0; k < 3; ++k) { + int l = parInt1 - (i + 60); + int i1 = parInt2 - (j + 14 + 19 * k); + if (l >= 0 && i1 >= 0 && l < 108 && i1 < 19 && this.container.enchantItem(this.mc.thePlayer, k)) { + this.mc.playerController.sendEnchantPacket(this.container.windowId, k); + } + } + + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + super.updateScreen(); + this.func_147068_g(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiErrorScreen.java b/src/game/java/net/minecraft/client/gui/GuiErrorScreen.java index b0ac40f0..b07d5349 100644 --- a/src/game/java/net/minecraft/client/gui/GuiErrorScreen.java +++ b/src/game/java/net/minecraft/client/gui/GuiErrorScreen.java @@ -2,22 +2,25 @@ package net.minecraft.client.gui; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,19 +34,17 @@ public class GuiErrorScreen extends GuiScreen { this.field_146312_f = parString2; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ - public void initGui() { - super.initGui(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, 140, I18n.format("gui.cancel", new Object[0]))); + protected void actionPerformed(GuiButton parGuiButton) { + this.mc.displayGuiScreen((GuiScreen) null); } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawGradientRect(0, 0, this.width, this.height, -12574688, -11530224); @@ -52,20 +53,21 @@ public class GuiErrorScreen extends GuiScreen { super.drawScreen(i, j, f); } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + super.initGui(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, 140, I18n.format("gui.cancel", new Object[0]))); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - this.mc.displayGuiScreen((GuiScreen) null); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiFlatPresets.java b/src/game/java/net/minecraft/client/gui/GuiFlatPresets.java index cc746673..b7e6ffeb 100644 --- a/src/game/java/net/minecraft/client/gui/GuiFlatPresets.java +++ b/src/game/java/net/minecraft/client/gui/GuiFlatPresets.java @@ -1,11 +1,12 @@ package net.minecraft.client.gui; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import java.io.IOException; import java.util.Arrays; import java.util.List; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -23,181 +24,119 @@ import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.gen.FlatGeneratorInfo; import net.minecraft.world.gen.FlatLayerInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiFlatPresets extends GuiScreen { + static class LayerItem { + public Item field_148234_a; + public int field_179037_b; + public String field_148232_b; + public String field_148233_c; + + public LayerItem(Item parItem, int parInt1, String parString1, String parString2) { + this.field_148234_a = parItem; + this.field_179037_b = parInt1; + this.field_148232_b = parString1; + this.field_148233_c = parString2; + } + } + + class ListSlot extends GuiSlot { + public int field_148175_k = -1; + + public ListSlot() { + super(GuiFlatPresets.this.mc, GuiFlatPresets.this.width, GuiFlatPresets.this.height, 80, + GuiFlatPresets.this.height - 37, 24); + } + + protected void drawBackground() { + } + + protected void drawSlot(int i, int j, int k, int var4, int var5, int var6) { + GuiFlatPresets.LayerItem guiflatpresets$layeritem = (GuiFlatPresets.LayerItem) GuiFlatPresets.FLAT_WORLD_PRESETS + .get(i); + this.func_178054_a(j, k, guiflatpresets$layeritem.field_148234_a, guiflatpresets$layeritem.field_179037_b); + GuiFlatPresets.this.fontRendererObj.drawString(guiflatpresets$layeritem.field_148232_b, j + 18 + 5, k + 6, + 16777215); + } + + protected void elementClicked(int i, boolean var2, int var3, int var4) { + this.field_148175_k = i; + GuiFlatPresets.this.func_146426_g(); + GuiFlatPresets.this.field_146433_u.setText(((GuiFlatPresets.LayerItem) GuiFlatPresets.FLAT_WORLD_PRESETS + .get(GuiFlatPresets.this.field_146435_s.field_148175_k)).field_148233_c); + } + + private void func_148171_c(int parInt1, int parInt2, int parInt3, int parInt4) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(Gui.statIcons); + float f = 0.0078125F; + float f1 = 0.0078125F; + boolean flag = true; + boolean flag1 = true; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 18), (double) GuiFlatPresets.this.zLevel) + .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 18), (double) GuiFlatPresets.this.zLevel) + .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 0), (double) GuiFlatPresets.this.zLevel) + .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 0), (double) GuiFlatPresets.this.zLevel) + .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) + .endVertex(); + tessellator.draw(); + } + + private void func_148173_e(int parInt1, int parInt2) { + this.func_148171_c(parInt1, parInt2, 0, 0); + } + + private void func_178054_a(int parInt1, int parInt2, Item parItem, int parInt3) { + this.func_148173_e(parInt1 + 1, parInt2 + 1); + GlStateManager.enableRescaleNormal(); + RenderHelper.enableGUIStandardItemLighting(); + GuiFlatPresets.this.itemRender.renderItemIntoGUI(new ItemStack(parItem, 1, parInt3), parInt1 + 2, + parInt2 + 2); + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + } + + protected int getSize() { + return GuiFlatPresets.FLAT_WORLD_PRESETS.size(); + } + + protected boolean isSelected(int i) { + return i == this.field_148175_k; + } + } + private static final List FLAT_WORLD_PRESETS = Lists.newArrayList(); - private final GuiCreateFlatWorld parentScreen; - private String presetsTitle; - private String presetsShare; - private String field_146436_r; - private GuiFlatPresets.ListSlot field_146435_s; - private GuiButton field_146434_t; - private GuiTextField field_146433_u; - - public GuiFlatPresets(GuiCreateFlatWorld parGuiCreateFlatWorld) { - this.parentScreen = parGuiCreateFlatWorld; - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - Keyboard.enableRepeatEvents(true); - this.presetsTitle = I18n.format("createWorld.customize.presets.title", new Object[0]); - this.presetsShare = I18n.format("createWorld.customize.presets.share", new Object[0]); - this.field_146436_r = I18n.format("createWorld.customize.presets.list", new Object[0]); - this.field_146433_u = new GuiTextField(2, this.fontRendererObj, 50, 40, this.width - 100, 20); - this.field_146435_s = new GuiFlatPresets.ListSlot(); - this.field_146433_u.setMaxStringLength(1230); - this.field_146433_u.setText(this.parentScreen.func_146384_e()); - this.buttonList.add(this.field_146434_t = new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, - I18n.format("createWorld.customize.presets.select", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, - I18n.format("gui.cancel", new Object[0]))); - this.func_146426_g(); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.field_146435_s.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.field_146435_s.handleTouchInput(); - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - this.field_146433_u.mouseClicked(parInt1, parInt2, parInt3); - super.mouseClicked(parInt1, parInt2, parInt3); - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (!this.field_146433_u.textboxKeyTyped(parChar1, parInt1)) { - super.keyTyped(parChar1, parInt1); - } - - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == 0 && this.func_146430_p()) { - this.parentScreen.func_146383_a(this.field_146433_u.getText()); - this.mc.displayGuiScreen(this.parentScreen); - } else if (parGuiButton.id == 1) { - this.mc.displayGuiScreen(this.parentScreen); - } - - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.field_146435_s.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.presetsTitle, this.width / 2, 8, 16777215); - this.drawString(this.fontRendererObj, this.presetsShare, 50, 30, 10526880); - this.drawString(this.fontRendererObj, this.field_146436_r, 50, 70, 10526880); - this.field_146433_u.drawTextBox(); - super.drawScreen(i, j, f); - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.field_146433_u.updateCursorCounter(); - super.updateScreen(); - } - - public void func_146426_g() { - boolean flag = this.func_146430_p(); - this.field_146434_t.enabled = flag; - } - - private boolean func_146430_p() { - return this.field_146435_s.field_148175_k > -1 && this.field_146435_s.field_148175_k < FLAT_WORLD_PRESETS.size() - || this.field_146433_u.getText().length() > 1; - } - - private static void func_146425_a(String parString1, Item parItem, BiomeGenBase parBiomeGenBase, - FlatLayerInfo... parArrayOfFlatLayerInfo) { - func_175354_a(parString1, parItem, 0, parBiomeGenBase, (List) null, parArrayOfFlatLayerInfo); - } - - private static void func_146421_a(String parString1, Item parItem, BiomeGenBase parBiomeGenBase, - List parList, FlatLayerInfo... parArrayOfFlatLayerInfo) { - func_175354_a(parString1, parItem, 0, parBiomeGenBase, parList, parArrayOfFlatLayerInfo); - } - - private static void func_175354_a(String parString1, Item parItem, int parInt1, BiomeGenBase parBiomeGenBase, - List parList, FlatLayerInfo... parArrayOfFlatLayerInfo) { - FlatGeneratorInfo flatgeneratorinfo = new FlatGeneratorInfo(); - - for (int i = parArrayOfFlatLayerInfo.length - 1; i >= 0; --i) { - flatgeneratorinfo.getFlatLayers().add(parArrayOfFlatLayerInfo[i]); - } - - flatgeneratorinfo.setBiome(parBiomeGenBase.biomeID); - flatgeneratorinfo.func_82645_d(); - if (parList != null) { - for (int i = 0, l = parList.size(); i < l; ++i) { - flatgeneratorinfo.getWorldFeatures().put(parList.get(i), Maps.newHashMap()); - } - } - - FLAT_WORLD_PRESETS - .add(new GuiFlatPresets.LayerItem(parItem, parInt1, parString1, flatgeneratorinfo.toString())); - } - static { func_146421_a("Classic Flat", Item.getItemFromBlock(Blocks.grass), BiomeGenBase.plains, Arrays.asList(new String[] { "village" }), new FlatLayerInfo[] { new FlatLayerInfo(1, Blocks.grass), @@ -236,97 +175,80 @@ public class GuiFlatPresets extends GuiScreen { new FlatLayerInfo(1, Blocks.bedrock) }); } - static class LayerItem { - public Item field_148234_a; - public int field_179037_b; - public String field_148232_b; - public String field_148233_c; - - public LayerItem(Item parItem, int parInt1, String parString1, String parString2) { - this.field_148234_a = parItem; - this.field_179037_b = parInt1; - this.field_148232_b = parString1; - this.field_148233_c = parString2; - } + private static void func_146421_a(String parString1, Item parItem, BiomeGenBase parBiomeGenBase, + List parList, FlatLayerInfo... parArrayOfFlatLayerInfo) { + func_175354_a(parString1, parItem, 0, parBiomeGenBase, parList, parArrayOfFlatLayerInfo); } - class ListSlot extends GuiSlot { - public int field_148175_k = -1; - - public ListSlot() { - super(GuiFlatPresets.this.mc, GuiFlatPresets.this.width, GuiFlatPresets.this.height, 80, - GuiFlatPresets.this.height - 37, 24); - } - - private void func_178054_a(int parInt1, int parInt2, Item parItem, int parInt3) { - this.func_148173_e(parInt1 + 1, parInt2 + 1); - GlStateManager.enableRescaleNormal(); - RenderHelper.enableGUIStandardItemLighting(); - GuiFlatPresets.this.itemRender.renderItemIntoGUI(new ItemStack(parItem, 1, parInt3), parInt1 + 2, - parInt2 + 2); - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableRescaleNormal(); - } - - private void func_148173_e(int parInt1, int parInt2) { - this.func_148171_c(parInt1, parInt2, 0, 0); - } - - private void func_148171_c(int parInt1, int parInt2, int parInt3, int parInt4) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(Gui.statIcons); - float f = 0.0078125F; - float f1 = 0.0078125F; - boolean flag = true; - boolean flag1 = true; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 18), (double) GuiFlatPresets.this.zLevel) - .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 18), (double) GuiFlatPresets.this.zLevel) - .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 0), (double) GuiFlatPresets.this.zLevel) - .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 0), (double) GuiFlatPresets.this.zLevel) - .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) - .endVertex(); - tessellator.draw(); - } - - protected int getSize() { - return GuiFlatPresets.FLAT_WORLD_PRESETS.size(); - } - - protected void elementClicked(int i, boolean var2, int var3, int var4) { - this.field_148175_k = i; - GuiFlatPresets.this.func_146426_g(); - GuiFlatPresets.this.field_146433_u.setText(((GuiFlatPresets.LayerItem) GuiFlatPresets.FLAT_WORLD_PRESETS - .get(GuiFlatPresets.this.field_146435_s.field_148175_k)).field_148233_c); - } - - protected boolean isSelected(int i) { - return i == this.field_148175_k; - } - - protected void drawBackground() { - } - - protected void drawSlot(int i, int j, int k, int var4, int var5, int var6) { - GuiFlatPresets.LayerItem guiflatpresets$layeritem = (GuiFlatPresets.LayerItem) GuiFlatPresets.FLAT_WORLD_PRESETS - .get(i); - this.func_178054_a(j, k, guiflatpresets$layeritem.field_148234_a, guiflatpresets$layeritem.field_179037_b); - GuiFlatPresets.this.fontRendererObj.drawString(guiflatpresets$layeritem.field_148232_b, j + 18 + 5, k + 6, - 16777215); - } + private static void func_146425_a(String parString1, Item parItem, BiomeGenBase parBiomeGenBase, + FlatLayerInfo... parArrayOfFlatLayerInfo) { + func_175354_a(parString1, parItem, 0, parBiomeGenBase, (List) null, parArrayOfFlatLayerInfo); } - @Override - public boolean showCopyPasteButtons() { - return field_146433_u.isFocused(); + private static void func_175354_a(String parString1, Item parItem, int parInt1, BiomeGenBase parBiomeGenBase, + List parList, FlatLayerInfo... parArrayOfFlatLayerInfo) { + FlatGeneratorInfo flatgeneratorinfo = new FlatGeneratorInfo(); + + for (int i = parArrayOfFlatLayerInfo.length - 1; i >= 0; --i) { + flatgeneratorinfo.getFlatLayers().add(parArrayOfFlatLayerInfo[i]); + } + + flatgeneratorinfo.setBiome(parBiomeGenBase.biomeID); + flatgeneratorinfo.func_82645_d(); + if (parList != null) { + for (int i = 0, l = parList.size(); i < l; ++i) { + flatgeneratorinfo.getWorldFeatures().put(parList.get(i), Maps.newHashMap()); + } + } + + FLAT_WORLD_PRESETS + .add(new GuiFlatPresets.LayerItem(parItem, parInt1, parString1, flatgeneratorinfo.toString())); + } + + private final GuiCreateFlatWorld parentScreen; + + private String presetsTitle; + + private String presetsShare; + + private String field_146436_r; + + private GuiFlatPresets.ListSlot field_146435_s; + + private GuiButton field_146434_t; + + private GuiTextField field_146433_u; + + public GuiFlatPresets(GuiCreateFlatWorld parGuiCreateFlatWorld) { + this.parentScreen = parGuiCreateFlatWorld; + } + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0 && this.func_146430_p()) { + this.parentScreen.func_146383_a(this.field_146433_u.getText()); + this.mc.displayGuiScreen(this.parentScreen); + } else if (parGuiButton.id == 1) { + this.mc.displayGuiScreen(this.parentScreen); + } + + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.field_146435_s.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.presetsTitle, this.width / 2, 8, 16777215); + this.drawString(this.fontRendererObj, this.presetsShare, 50, 30, 10526880); + this.drawString(this.fontRendererObj, this.field_146436_r, 50, 70, 10526880); + this.field_146433_u.drawTextBox(); + super.drawScreen(i, j, f); } @Override @@ -334,4 +256,89 @@ public class GuiFlatPresets extends GuiScreen { field_146433_u.fireInputEvent(event, param); } + public void func_146426_g() { + boolean flag = this.func_146430_p(); + this.field_146434_t.enabled = flag; + } + + private boolean func_146430_p() { + return this.field_146435_s.field_148175_k > -1 && this.field_146435_s.field_148175_k < FLAT_WORLD_PRESETS.size() + || this.field_146433_u.getText().length() > 1; + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.field_146435_s.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.field_146435_s.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + Keyboard.enableRepeatEvents(true); + this.presetsTitle = I18n.format("createWorld.customize.presets.title", new Object[0]); + this.presetsShare = I18n.format("createWorld.customize.presets.share", new Object[0]); + this.field_146436_r = I18n.format("createWorld.customize.presets.list", new Object[0]); + this.field_146433_u = new GuiTextField(2, this.fontRendererObj, 50, 40, this.width - 100, 20); + this.field_146435_s = new GuiFlatPresets.ListSlot(); + this.field_146433_u.setMaxStringLength(1230); + this.field_146433_u.setText(this.parentScreen.func_146384_e()); + this.buttonList.add(this.field_146434_t = new GuiButton(0, this.width / 2 - 155, this.height - 28, 150, 20, + I18n.format("createWorld.customize.presets.select", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 + 5, this.height - 28, 150, 20, + I18n.format("gui.cancel", new Object[0]))); + this.func_146426_g(); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (!this.field_146433_u.textboxKeyTyped(parChar1, parInt1)) { + super.keyTyped(parChar1, parInt1); + } + + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + this.field_146433_u.mouseClicked(parInt1, parInt2, parInt3); + super.mouseClicked(parInt1, parInt2, parInt3); + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + + @Override + public boolean showCopyPasteButtons() { + return field_146433_u.isFocused(); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.field_146433_u.updateCursorCounter(); + super.updateScreen(); + } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiGameOver.java b/src/game/java/net/minecraft/client/gui/GuiGameOver.java index 4af14483..52ce44b8 100644 --- a/src/game/java/net/minecraft/client/gui/GuiGameOver.java +++ b/src/game/java/net/minecraft/client/gui/GuiGameOver.java @@ -5,22 +5,25 @@ import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,49 +32,9 @@ public class GuiGameOver extends GuiScreen implements GuiYesNoCallback { private int enableButtonsTimer; private boolean field_146346_f = false; - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - if (this.mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) { - if (this.mc.isIntegratedServerRunning()) { - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 96, - I18n.format("deathScreen.deleteWorld", new Object[0]))); - } else { - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 96, - I18n.format("deathScreen.leaveServer", new Object[0]))); - } - } else { - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 72, - I18n.format("deathScreen.respawn", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 96, - I18n.format("deathScreen.titleScreen", new Object[0]))); - if (this.mc.getSession() == null) { - ((GuiButton) this.buttonList.get(1)).enabled = false; - } - } - - for (int i = 0, l = this.buttonList.size(); i < l; ++i) { - this.buttonList.get(i).enabled = false; - } - - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { switch (parGuiButton.id) { @@ -112,9 +75,17 @@ public class GuiGameOver extends GuiScreen implements GuiYesNoCallback { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return false; + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawGradientRect(0, 0, this.width, this.height, 1615855616, -1602211792); @@ -135,16 +106,47 @@ public class GuiGameOver extends GuiScreen implements GuiYesNoCallback { super.drawScreen(i, j, f); } - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ - public boolean doesGuiPauseGame() { - return false; + public void initGui() { + this.buttonList.clear(); + if (this.mc.theWorld.getWorldInfo().isHardcoreModeEnabled()) { + if (this.mc.isIntegratedServerRunning()) { + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 96, + I18n.format("deathScreen.deleteWorld", new Object[0]))); + } else { + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 96, + I18n.format("deathScreen.leaveServer", new Object[0]))); + } + } else { + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 72, + I18n.format("deathScreen.respawn", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 96, + I18n.format("deathScreen.titleScreen", new Object[0]))); + if (this.mc.getSession() == null) { + ((GuiButton) this.buttonList.get(1)).enabled = false; + } + } + + for (int i = 0, l = this.buttonList.size(); i < l; ++i) { + this.buttonList.get(i).enabled = false; + } + } - /**+ - * Called from the main game loop to update the screen. + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + } + + /** + * + Called from the main game loop to update the screen. */ public void updateScreen() { super.updateScreen(); diff --git a/src/game/java/net/minecraft/client/gui/GuiHopper.java b/src/game/java/net/minecraft/client/gui/GuiHopper.java index fd614835..fc41ee13 100644 --- a/src/game/java/net/minecraft/client/gui/GuiHopper.java +++ b/src/game/java/net/minecraft/client/gui/GuiHopper.java @@ -8,30 +8,32 @@ import net.minecraft.inventory.ContainerHopper; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiHopper extends GuiContainer { - /**+ - * The ResourceLocation containing the gui texture for the - * hopper + /** + * + The ResourceLocation containing the gui texture for the hopper */ private static final ResourceLocation HOPPER_GUI_TEXTURE = new ResourceLocation( "textures/gui/container/hopper.png"); @@ -46,18 +48,8 @@ public class GuiHopper extends GuiContainer { this.ySize = 133; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - this.fontRendererObj.drawString(this.hopperInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); - this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -66,4 +58,14 @@ public class GuiHopper extends GuiContainer { int j = (this.height - this.ySize) / 2; this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(this.hopperInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); + this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiIngame.java b/src/game/java/net/minecraft/client/gui/GuiIngame.java index 1df23977..d5d48f0a 100644 --- a/src/game/java/net/minecraft/client/gui/GuiIngame.java +++ b/src/game/java/net/minecraft/client/gui/GuiIngame.java @@ -1,21 +1,23 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_DST_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.util.ArrayList; import java.util.Collection; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.Display; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; import net.lax1dude.eaglercraft.v1_8.Touch; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.OpenGlHelper; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; @@ -58,22 +60,25 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.StringUtils; import net.minecraft.world.border.WorldBorder; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -87,15 +92,14 @@ public class GuiIngame extends Gui { private final RenderItem itemRenderer; private final GuiNewChat persistantChatGUI; private int updateCounter; - /**+ - * The string specifying which record music is playing + /** + * + The string specifying which record music is playing */ private String recordPlaying = ""; private int recordPlayingUpFor; private boolean recordIsPlaying; - /**+ - * Previous frame vignette brightness (slowly changes by 1% each - * frame) + /** + * + Previous frame vignette brightness (slowly changes by 1% each frame) */ public float prevVignetteBrightness = 1.0F; private int remainingHighlightTicks; @@ -111,15 +115,43 @@ public class GuiIngame extends Gui { private int field_175193_B; private int playerHealth = 0; private int lastPlayerHealth = 0; - /**+ - * The last recorded system time + /** + * + The last recorded system time */ private long lastSystemTime = 0L; - /**+ - * Used with updateCounter to make the heart bar flash + /** + * + Used with updateCounter to make the heart bar flash */ private long healthUpdateCounter = 0L; + private int hotbarAreaX = -1; + + private int hotbarAreaY = -1; + + private int hotbarAreaW = -1; + + private int hotbarAreaH = -1; + + private int currentHotbarSlotTouch = -1; + + private long hotbarSlotTouchStart = -1l; + + private boolean hotbarSlotTouchAlreadySelected = false; + + private int interactButtonX = -1; + + private int interactButtonY = -1; + + private int interactButtonW = -1; + + private int interactButtonH = -1; + + private int touchVPosX = -1; + + private int touchVPosY = -1; + + private int touchEventUID = -1; + public GuiIngame(Minecraft mcIn) { this.mc = mcIn; this.itemRenderer = mcIn.getRenderItem(); @@ -130,12 +162,405 @@ public class GuiIngame extends Gui { this.func_175177_a(); } + private int applyTouchHotbarTransformX(int posX, boolean scaled) { + if (scaled) { + return (posX + mc.scaledResolution.getScaledWidth() / 4) * 2 / 3; + } else { + return (posX + mc.displayWidth / 4) * 2 / 3; + } + } + + private int applyTouchHotbarTransformY(int posY, boolean scaled) { + if (scaled) { + return (posY + mc.scaledResolution.getScaledHeight() / 2) * 2 / 3; + } else { + return (posY + mc.displayHeight / 2) * 2 / 3; + } + } + + public void displayTitle(String parString1, String parString2, int parInt1, int parInt2, int parInt3) { + if (parString1 == null && parString2 == null && parInt1 < 0 && parInt2 < 0 && parInt3 < 0) { + this.field_175201_x = ""; + this.field_175200_y = ""; + this.field_175195_w = 0; + } else if (parString1 != null) { + this.field_175201_x = parString1; + this.field_175195_w = this.field_175199_z + this.field_175192_A + this.field_175193_B; + } else if (parString2 != null) { + this.field_175200_y = parString2; + } else { + if (parInt1 >= 0) { + this.field_175199_z = parInt1; + } + + if (parInt2 >= 0) { + this.field_175192_A = parInt2; + } + + if (parInt3 >= 0) { + this.field_175193_B = parInt3; + } + + if (this.field_175195_w > 0) { + this.field_175195_w = this.field_175199_z + this.field_175192_A + this.field_175193_B; + } + + } + } + + private void drawEaglerInteractButton(ScaledResolution parScaledResolution) { + if (PointerInputAbstraction.isTouchMode() && mc.objectMouseOver != null + && mc.objectMouseOver.typeOfHit == MovingObjectType.ENTITY) { + int scale = parScaledResolution.getScaleFactor(); + interactButtonW = 118 * scale; + interactButtonH = 20 * scale; + int xx = (parScaledResolution.getScaledWidth() - 118) / 2; + int yy = parScaledResolution.getScaledHeight() - 70; + interactButtonX = xx * scale; + interactButtonY = yy * scale; + mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); + boolean hover = touchVPosX >= interactButtonX && touchVPosY >= interactButtonY + && touchVPosX < interactButtonX + interactButtonW && touchVPosY < interactButtonY + interactButtonH; + float f = MathHelper.clamp_float(mc.gameSettings.touchControlOpacity, 0.0f, 1.0f); + if (f > 0.0f) { + GlStateManager.color(1.0f, 1.0f, 1.0f, f); + drawTexturedModalRect(xx, yy, 0, hover ? 216 : 236, 118, 20); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + drawCenteredString(mc.fontRendererObj, I18n.format("touch.interact.entity"), + parScaledResolution.getScaledWidth() / 2, yy + 6, + (hover ? 16777120 : 14737632) | ((int) (f * 255.0f) << 24)); + } + } else { + interactButtonX = -1; + interactButtonY = -1; + interactButtonW = -1; + interactButtonH = -1; + } + } + + public void drawEaglerPlayerOverlay(int x, int y, float partialTicks) { + Entity e = mc.getRenderViewEntity(); + if (e != null && e instanceof EntityLivingBase) { + EntityLivingBase ent = (EntityLivingBase) e; + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + GlStateManager.enableDepth(); + GlStateManager.enableColorMaterial(); + GlStateManager.pushMatrix(); + GlStateManager.translate((float) x - 10, (float) y + 36, 50.0F); + GlStateManager.scale(-17.0F, 17.0F, 17.0F); + GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); + float f = ent.renderYawOffset; + float f1 = ent.rotationYaw; + float f2 = ent.prevRotationYaw; + float f3 = ent.prevRotationYawHead; + float f4 = ent.rotationYawHead; + float f5 = ent.prevRenderYawOffset; + GlStateManager.rotate(115.0F, 0.0F, 1.0F, 0.0F); + RenderHelper.enableStandardItemLighting(); + float f6 = ent.prevRenderYawOffset + (ent.renderYawOffset - ent.prevRenderYawOffset) * partialTicks; + ent.rotationYawHead -= f6; + ent.prevRotationYawHead -= f6; + ent.rotationYawHead *= 0.5f; + ent.prevRotationYawHead *= 0.5f; + ent.renderYawOffset = 0.0f; + ent.prevRenderYawOffset = 0.0f; + ent.prevRotationYaw = 0.0f; + ent.rotationYaw = 0.0f; + GlStateManager.rotate(-135.0F + - (ent.prevRotationYawHead + (ent.rotationYawHead - ent.prevRotationYawHead) * partialTicks) * 0.5F, + 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(ent.rotationPitch * 0.2f, 1.0F, 0.0F, 0.0F); + RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); + rendermanager.setPlayerViewY(180.0F); + rendermanager.setRenderShadow(false); + rendermanager.renderEntityWithPosYaw(ent, 0.0D, 0.0D, 0.0D, 0.0F, partialTicks); + rendermanager.setRenderShadow(true); + ent.renderYawOffset = f; + ent.rotationYaw = f1; + ent.prevRotationYaw = f2; + ent.prevRotationYawHead = f3; + ent.rotationYawHead = f4; + ent.prevRenderYawOffset = f5; + GlStateManager.popMatrix(); + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableRescaleNormal(); + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.disableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + } + } + public void func_175177_a() { this.field_175199_z = 10; this.field_175192_A = 70; this.field_175193_B = 20; } + private void func_180474_b(float parFloat1, ScaledResolution parScaledResolution) { + if (parFloat1 < 1.0F) { + parFloat1 = parFloat1 * parFloat1; + parFloat1 = parFloat1 * parFloat1; + parFloat1 = parFloat1 * 0.8F + 0.2F; + } + + GlStateManager.disableAlpha(); + GlStateManager.disableDepth(); + GlStateManager.depthMask(false); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + GlStateManager.color(1.0F, 1.0F, 1.0F, parFloat1); + this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + EaglerTextureAtlasSprite textureatlassprite = this.mc.getBlockRendererDispatcher().getBlockModelShapes() + .getTexture(Blocks.portal.getDefaultState()); + float f = textureatlassprite.getMinU(); + float f1 = textureatlassprite.getMinV(); + float f2 = textureatlassprite.getMaxU(); + float f3 = textureatlassprite.getMaxV(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos(0.0D, (double) parScaledResolution.getScaledHeight(), -90.0D).tex((double) f, (double) f3) + .endVertex(); + worldrenderer.pos((double) parScaledResolution.getScaledWidth(), (double) parScaledResolution.getScaledHeight(), + -90.0D).tex((double) f2, (double) f3).endVertex(); + worldrenderer.pos((double) parScaledResolution.getScaledWidth(), 0.0D, -90.0D).tex((double) f2, (double) f1) + .endVertex(); + worldrenderer.pos(0.0D, 0.0D, -90.0D).tex((double) f, (double) f1).endVertex(); + tessellator.draw(); + GlStateManager.depthMask(true); + GlStateManager.enableDepth(); + GlStateManager.enableAlpha(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + + public void func_181029_i() { + this.overlayPlayerList.func_181030_a(); + } + + public void func_181551_a(ScaledResolution parScaledResolution) { + if (this.remainingHighlightTicks > 0 && this.highlightingItemStack != null) { + String s = this.highlightingItemStack.getDisplayNameProfanityFilter(); + if (this.highlightingItemStack.hasDisplayName()) { + s = EnumChatFormatting.ITALIC + s; + } + + int i = (parScaledResolution.getScaledWidth() - this.getFontRenderer().getStringWidth(s)) / 2; + int j = parScaledResolution.getScaledHeight() - 59; + if (!this.mc.playerController.shouldDrawHUD()) { + j += 14; + } + + int k = (int) ((float) this.remainingHighlightTicks * 256.0F / 10.0F); + if (k > 255) { + k = 255; + } + + if (k > 0) { + GlStateManager.pushMatrix(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + this.getFontRenderer().drawStringWithShadow(s, (float) i, (float) j, 16777215 + (k << 24)); + GlStateManager.disableBlend(); + GlStateManager.popMatrix(); + } + } + + } + + /** + * + returns a pointer to the persistant Chat GUI, containing all previous chat + * messages and such + */ + public GuiNewChat getChatGUI() { + return this.persistantChatGUI; + } + + public FontRenderer getFontRenderer() { + return this.mc.fontRendererObj; + } + + private int getHotbarSlotTouched(int pointX) { + int xx = pointX - hotbarAreaX - 2; + xx /= 20 * mc.scaledResolution.getScaleFactor(); + if (xx < 0) + xx = 0; + if (xx > 9) + xx = 9; + return xx; + } + + public GuiSpectator getSpectatorGui() { + return this.spectatorGui; + } + + public GuiPlayerTabOverlay getTabList() { + return this.overlayPlayerList; + } + + public int getUpdateCounter() { + return this.updateCounter; + } + + public boolean handleTouchBeginEagler(int uid, int pointX, int pointY) { + if (mc.thePlayer == null) { + return false; + } + if (touchEventUID == -1) { + pointX = applyTouchHotbarTransformX(pointX, false); + pointY = applyTouchHotbarTransformY(pointY, false); + if (pointX >= hotbarAreaX && pointY >= hotbarAreaY && pointX < hotbarAreaX + hotbarAreaW + && pointY < hotbarAreaY + hotbarAreaH) { + touchEventUID = uid; + currentHotbarSlotTouch = getHotbarSlotTouched(pointX); + hotbarSlotTouchStart = EagRuntime.steadyTimeMillis(); + if (currentHotbarSlotTouch >= 0 && currentHotbarSlotTouch < 9) { + if (mc.thePlayer.isSpectator()) { + hotbarSlotTouchAlreadySelected = false; + mc.ingameGUI.getSpectatorGui().func_175260_a(currentHotbarSlotTouch); + } else { + hotbarSlotTouchAlreadySelected = (mc.thePlayer.inventory.currentItem == currentHotbarSlotTouch); + mc.thePlayer.inventory.currentItem = currentHotbarSlotTouch; + } + } else if (currentHotbarSlotTouch == 9) { + hotbarSlotTouchAlreadySelected = false; + currentHotbarSlotTouch = 69; + if (mc.playerController.isRidingHorse()) { + mc.thePlayer.sendHorseInventory(); + } else { + mc.getNetHandler().addToSendQueue( + new C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT)); + mc.displayGuiScreen(new GuiInventory(mc.thePlayer)); + } + } + return true; + } + if (pointX >= interactButtonX && pointY >= interactButtonY && pointX < interactButtonX + interactButtonW + && pointY < interactButtonY + interactButtonH) { + touchEventUID = uid; + mc.rightClickMouse(); + return true; + } + } + return false; + } + + public boolean handleTouchEndEagler(int uid, int pointX, int pointY) { + if (uid == touchEventUID) { + if (hotbarSlotTouchStart != -1l && currentHotbarSlotTouch != 69) { + if (EagRuntime.steadyTimeMillis() - hotbarSlotTouchStart < 350l) { + if (hotbarSlotTouchAlreadySelected) { + if (mc.thePlayer != null) { + mc.thePlayer.dropOneItem(false); + } + } + } + } + touchVPosX = -1; + touchVPosY = -1; + touchEventUID = -1; + currentHotbarSlotTouch = -1; + hotbarSlotTouchStart = -1l; + hotbarSlotTouchAlreadySelected = false; + return true; + } + return false; + } + + public boolean isTouchOverlapEagler(int uid, int tx, int ty) { + if (touchEventUID == uid) { + return true; + } + ty = mc.displayHeight - ty - 1; + tx = applyTouchHotbarTransformX(tx, false); + ty = applyTouchHotbarTransformY(ty, false); + return (tx >= hotbarAreaX && ty >= hotbarAreaY && tx < hotbarAreaX + hotbarAreaW + && ty < hotbarAreaY + hotbarAreaH) + || (tx >= interactButtonX && ty >= interactButtonY && tx < interactButtonX + interactButtonW + && ty < interactButtonY + interactButtonH); + } + + private void onBeginHotbarDraw() { + if (PointerInputAbstraction.isTouchMode()) { + GlStateManager.pushMatrix(); + ScaledResolution res = mc.scaledResolution; + GlStateManager.translate(res.getScaledWidth() / -4, res.getScaledHeight() / -2, field_175199_z); + GlStateManager.scale(1.5f, 1.5f, 1.5f); + } + } + + private void onEndHotbarDraw() { + if (PointerInputAbstraction.isTouchMode()) { + GlStateManager.popMatrix(); + } + } + + /** + * + Renders dragon's (boss) health on the HUD + */ + private void renderBossHealth() { + if (BossStatus.bossName != null && BossStatus.statusBarTime > 0) { + --BossStatus.statusBarTime; + int i = mc.scaledResolution.getScaledWidth(); + short short1 = 182; + int j = i / 2 - short1 / 2; + int k = (int) (BossStatus.healthScale * (float) (short1 + 1)); + byte b0 = 12; + this.drawTexturedModalRect(j, b0, 0, 74, short1, 5); + this.drawTexturedModalRect(j, b0, 0, 74, short1, 5); + if (k > 0) { + this.drawTexturedModalRect(j, b0, 0, 79, k, 5); + } + + String s = BossStatus.bossName; + this.getFontRenderer().drawStringWithShadow(s, + (float) (i / 2 - this.getFontRenderer().getStringWidth(s) / 2), (float) (b0 - 10), 16777215); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(icons); + } + } + + public void renderDemo(ScaledResolution parScaledResolution) { + String s = ""; + if (this.mc.theWorld.getTotalWorldTime() >= 120500L) { + s = I18n.format("demo.demoExpired", new Object[0]); + } else { + s = I18n.format("demo.remainingTime", new Object[] { + StringUtils.ticksToElapsedTime((int) (120500L - this.mc.theWorld.getTotalWorldTime())) }); + } + + int i = this.getFontRenderer().getStringWidth(s); + this.getFontRenderer().drawStringWithShadow(s, (float) (parScaledResolution.getScaledWidth() - i - 10), 5.0F, + 16777215); + } + + public void renderExpBar(ScaledResolution parScaledResolution, int parInt1) { + this.mc.getTextureManager().bindTexture(Gui.icons); + int i = this.mc.thePlayer.xpBarCap(); + if (i > 0) { + short short1 = 182; + int j = (int) (this.mc.thePlayer.experience * (float) (short1 + 1)); + int k = parScaledResolution.getScaledHeight() - 32 + 3; + this.drawTexturedModalRect(parInt1, k, 0, 64, short1, 5); + if (j > 0) { + this.drawTexturedModalRect(parInt1, k, 0, 69, j, 5); + } + } + + if (this.mc.thePlayer.experienceLevel > 0) { + int i1 = 8453920; + String s = "" + this.mc.thePlayer.experienceLevel; + int j1 = (parScaledResolution.getScaledWidth() - this.getFontRenderer().getStringWidth(s)) / 2; + int l = parScaledResolution.getScaledHeight() - 31 - 4; + boolean flag = false; + this.getFontRenderer().drawString(s, j1 + 1, l, 0); + this.getFontRenderer().drawString(s, j1 - 1, l, 0); + this.getFontRenderer().drawString(s, j1, l + 1, 0); + this.getFontRenderer().drawString(s, j1, l - 1, 0); + this.getFontRenderer().drawString(s, j1, l, i1); + } + + } + public void renderGameOverlay(float partialTicks) { ScaledResolution scaledresolution = mc.scaledResolution; int i = scaledresolution.getScaledWidth(); @@ -339,53 +764,6 @@ public class GuiIngame extends Gui { } } - protected void renderTooltip(ScaledResolution sr, float partialTicks) { - if (this.mc.getRenderViewEntity() instanceof EntityPlayer) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(widgetsTexPath); - EntityPlayer entityplayer = (EntityPlayer) this.mc.getRenderViewEntity(); - int i = sr.getScaledWidth() / 2; - float f = this.zLevel; - this.zLevel = -90.0F; - this.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22, 0, 0, 182, 22); - - if (PointerInputAbstraction.isTouchMode()) { - this.mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); - this.drawTexturedModalRect(i + 89, sr.getScaledHeight() - 22, 234, 0, 22, 22); - int areaHAdd = 12; - hotbarAreaX = (i - 91) * mc.displayWidth / sr.getScaledWidth(); - hotbarAreaY = (sr.getScaledHeight() - 22 - areaHAdd) * mc.displayHeight / sr.getScaledHeight(); - hotbarAreaW = 203 * mc.displayWidth / sr.getScaledWidth(); - hotbarAreaH = (22 + areaHAdd) * mc.displayHeight / sr.getScaledHeight(); - } else { - hotbarAreaX = -1; - hotbarAreaY = -1; - hotbarAreaW = -1; - hotbarAreaH = -1; - } - - this.mc.getTextureManager().bindTexture(widgetsTexPath); - this.drawTexturedModalRect(i - 91 - 1 + entityplayer.inventory.currentItem * 20, - sr.getScaledHeight() - 22 - 1, 0, 22, 24, 22); - this.zLevel = f; - GlStateManager.enableRescaleNormal(); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - RenderHelper.enableGUIStandardItemLighting(); - - for (int j = 0; j < 9; ++j) { - int k = sr.getScaledWidth() / 2 - 90 + j * 20 + 2; - int l = sr.getScaledHeight() - 16 - 3; - this.renderHotbarItem(j, k, l, partialTicks, entityplayer); - } - - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableRescaleNormal(); - - GlStateManager.disableBlend(); - } - } - public void renderHorseJumpBar(ScaledResolution parScaledResolution, int parInt1) { this.mc.getTextureManager().bindTexture(Gui.icons); float f = this.mc.thePlayer.getHorseJumpPower(); @@ -398,152 +776,25 @@ public class GuiIngame extends Gui { } } - public void renderExpBar(ScaledResolution parScaledResolution, int parInt1) { - this.mc.getTextureManager().bindTexture(Gui.icons); - int i = this.mc.thePlayer.xpBarCap(); - if (i > 0) { - short short1 = 182; - int j = (int) (this.mc.thePlayer.experience * (float) (short1 + 1)); - int k = parScaledResolution.getScaledHeight() - 32 + 3; - this.drawTexturedModalRect(parInt1, k, 0, 64, short1, 5); - if (j > 0) { - this.drawTexturedModalRect(parInt1, k, 0, 69, j, 5); - } - } - - if (this.mc.thePlayer.experienceLevel > 0) { - int i1 = 8453920; - String s = "" + this.mc.thePlayer.experienceLevel; - int j1 = (parScaledResolution.getScaledWidth() - this.getFontRenderer().getStringWidth(s)) / 2; - int l = parScaledResolution.getScaledHeight() - 31 - 4; - boolean flag = false; - this.getFontRenderer().drawString(s, j1 + 1, l, 0); - this.getFontRenderer().drawString(s, j1 - 1, l, 0); - this.getFontRenderer().drawString(s, j1, l + 1, 0); - this.getFontRenderer().drawString(s, j1, l - 1, 0); - this.getFontRenderer().drawString(s, j1, l, i1); - } - - } - - public void func_181551_a(ScaledResolution parScaledResolution) { - if (this.remainingHighlightTicks > 0 && this.highlightingItemStack != null) { - String s = this.highlightingItemStack.getDisplayNameProfanityFilter(); - if (this.highlightingItemStack.hasDisplayName()) { - s = EnumChatFormatting.ITALIC + s; - } - - int i = (parScaledResolution.getScaledWidth() - this.getFontRenderer().getStringWidth(s)) / 2; - int j = parScaledResolution.getScaledHeight() - 59; - if (!this.mc.playerController.shouldDrawHUD()) { - j += 14; - } - - int k = (int) ((float) this.remainingHighlightTicks * 256.0F / 10.0F); - if (k > 255) { - k = 255; - } - - if (k > 0) { + private void renderHotbarItem(int index, int xPos, int yPos, float partialTicks, EntityPlayer parEntityPlayer) { + ItemStack itemstack = parEntityPlayer.inventory.mainInventory[index]; + if (itemstack != null) { + float f = (float) itemstack.animationsToGo - partialTicks; + if (f > 0.0F) { GlStateManager.pushMatrix(); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - this.getFontRenderer().drawStringWithShadow(s, (float) i, (float) j, 16777215 + (k << 24)); - GlStateManager.disableBlend(); + float f1 = 1.0F + f / 5.0F; + GlStateManager.translate((float) (xPos + 8), (float) (yPos + 12), 0.0F); + GlStateManager.scale(1.0F / f1, (f1 + 1.0F) / 2.0F, 1.0F); + GlStateManager.translate((float) (-(xPos + 8)), (float) (-(yPos + 12)), 0.0F); + } + + this.itemRenderer.renderItemAndEffectIntoGUI(itemstack, xPos, yPos); + if (f > 0.0F) { GlStateManager.popMatrix(); } + + this.itemRenderer.renderItemOverlays(this.mc.fontRendererObj, itemstack, xPos, yPos); } - - } - - public void renderDemo(ScaledResolution parScaledResolution) { - String s = ""; - if (this.mc.theWorld.getTotalWorldTime() >= 120500L) { - s = I18n.format("demo.demoExpired", new Object[0]); - } else { - s = I18n.format("demo.remainingTime", new Object[] { - StringUtils.ticksToElapsedTime((int) (120500L - this.mc.theWorld.getTotalWorldTime())) }); - } - - int i = this.getFontRenderer().getStringWidth(s); - this.getFontRenderer().drawStringWithShadow(s, (float) (parScaledResolution.getScaledWidth() - i - 10), 5.0F, - 16777215); - } - - protected boolean showCrosshair() { - if (this.mc.gameSettings.showDebugInfo && !this.mc.thePlayer.hasReducedDebug() - && !this.mc.gameSettings.reducedDebugInfo) { - return false; - } else if (this.mc.playerController.isSpectator()) { - if (this.mc.pointedEntity != null) { - return true; - } else { - if (this.mc.objectMouseOver != null - && this.mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - BlockPos blockpos = this.mc.objectMouseOver.getBlockPos(); - if (this.mc.theWorld.getTileEntity(blockpos) instanceof IInventory) { - return true; - } - } - - return false; - } - } else { - return true; - } - } - - private void renderScoreboard(ScoreObjective parScoreObjective, ScaledResolution parScaledResolution) { - Scoreboard scoreboard = parScoreObjective.getScoreboard(); - Collection collection = scoreboard.getSortedScores(parScoreObjective); - ArrayList arraylist = Lists.newArrayList(Iterables.filter(collection, new Predicate() { - public boolean apply(Score score2) { - return score2.getPlayerName() != null && !score2.getPlayerName().startsWith("#"); - } - })); - ArrayList arraylist1; - if (arraylist.size() > 15) { - arraylist1 = Lists.newArrayList(Iterables.skip(arraylist, collection.size() - 15)); - } else { - arraylist1 = arraylist; - } - - int i = this.getFontRenderer().getStringWidth(parScoreObjective.getDisplayName()); - - for (int m = 0, n = arraylist1.size(); m < n; ++m) { - Score score = (Score) arraylist1.get(m); - ScorePlayerTeam scoreplayerteam = scoreboard.getPlayersTeam(score.getPlayerName()); - String s = ScorePlayerTeam.formatPlayerName(scoreplayerteam, score.getPlayerName()) + ": " - + EnumChatFormatting.RED + score.getScorePoints(); - i = Math.max(i, this.getFontRenderer().getStringWidth(s)); - } - - int i1 = arraylist1.size() * this.getFontRenderer().FONT_HEIGHT; - int j1 = parScaledResolution.getScaledHeight() / 2 + i1 / 3; - byte b0 = 3; - int k1 = parScaledResolution.getScaledWidth() - i - b0; - int j = 0; - - for (int m = 0, n = arraylist1.size(); m < n; ++m) { - Score score1 = (Score) arraylist1.get(m); - ++j; - ScorePlayerTeam scoreplayerteam1 = scoreboard.getPlayersTeam(score1.getPlayerName()); - String s1 = ScorePlayerTeam.formatPlayerName(scoreplayerteam1, score1.getPlayerName()); - String s2 = EnumChatFormatting.RED + "" + score1.getScorePoints(); - int k = j1 - j * this.getFontRenderer().FONT_HEIGHT; - int l = parScaledResolution.getScaledWidth() - b0 + 2; - drawRect(k1 - 2, k, l, k + this.getFontRenderer().FONT_HEIGHT, 1342177280); - this.getFontRenderer().drawString(s1, k1, k, 0xFFFFFFFF); - this.getFontRenderer().drawString(s2, l - this.getFontRenderer().getStringWidth(s2), k, 0xFFFFFFFF); - if (j == arraylist1.size()) { - String s3 = parScoreObjective.getDisplayName(); - drawRect(k1 - 2, k - this.getFontRenderer().FONT_HEIGHT - 1, l, k - 1, 1610612736); - drawRect(k1 - 2, k - 1, l, k, 1342177280); - this.getFontRenderer().drawString(s3, k1 + i / 2 - this.getFontRenderer().getStringWidth(s3) / 2, - k - this.getFontRenderer().FONT_HEIGHT, 0xFFFFFFFF); - } - } - } private void renderPlayerStats(ScaledResolution parScaledResolution) { @@ -761,31 +1012,6 @@ public class GuiIngame extends Gui { } } - /**+ - * Renders dragon's (boss) health on the HUD - */ - private void renderBossHealth() { - if (BossStatus.bossName != null && BossStatus.statusBarTime > 0) { - --BossStatus.statusBarTime; - int i = mc.scaledResolution.getScaledWidth(); - short short1 = 182; - int j = i / 2 - short1 / 2; - int k = (int) (BossStatus.healthScale * (float) (short1 + 1)); - byte b0 = 12; - this.drawTexturedModalRect(j, b0, 0, 74, short1, 5); - this.drawTexturedModalRect(j, b0, 0, 74, short1, 5); - if (k > 0) { - this.drawTexturedModalRect(j, b0, 0, 79, k, 5); - } - - String s = BossStatus.bossName; - this.getFontRenderer().drawStringWithShadow(s, - (float) (i / 2 - this.getFontRenderer().getStringWidth(s) / 2), (float) (b0 - 10), 16777215); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(icons); - } - } - private void renderPumpkinOverlay(ScaledResolution parScaledResolution) { GlStateManager.disableDepth(); GlStateManager.depthMask(false); @@ -808,9 +1034,108 @@ public class GuiIngame extends Gui { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); } - /**+ - * Renders a Vignette arount the entire screen that changes with - * light level. + private void renderScoreboard(ScoreObjective parScoreObjective, ScaledResolution parScaledResolution) { + Scoreboard scoreboard = parScoreObjective.getScoreboard(); + Collection collection = scoreboard.getSortedScores(parScoreObjective); + ArrayList arraylist = Lists.newArrayList(Iterables.filter(collection, new Predicate() { + public boolean apply(Score score2) { + return score2.getPlayerName() != null && !score2.getPlayerName().startsWith("#"); + } + })); + ArrayList arraylist1; + if (arraylist.size() > 15) { + arraylist1 = Lists.newArrayList(Iterables.skip(arraylist, collection.size() - 15)); + } else { + arraylist1 = arraylist; + } + + int i = this.getFontRenderer().getStringWidth(parScoreObjective.getDisplayName()); + + for (int m = 0, n = arraylist1.size(); m < n; ++m) { + Score score = (Score) arraylist1.get(m); + ScorePlayerTeam scoreplayerteam = scoreboard.getPlayersTeam(score.getPlayerName()); + String s = ScorePlayerTeam.formatPlayerName(scoreplayerteam, score.getPlayerName()) + ": " + + EnumChatFormatting.RED + score.getScorePoints(); + i = Math.max(i, this.getFontRenderer().getStringWidth(s)); + } + + int i1 = arraylist1.size() * this.getFontRenderer().FONT_HEIGHT; + int j1 = parScaledResolution.getScaledHeight() / 2 + i1 / 3; + byte b0 = 3; + int k1 = parScaledResolution.getScaledWidth() - i - b0; + int j = 0; + + for (int m = 0, n = arraylist1.size(); m < n; ++m) { + Score score1 = (Score) arraylist1.get(m); + ++j; + ScorePlayerTeam scoreplayerteam1 = scoreboard.getPlayersTeam(score1.getPlayerName()); + String s1 = ScorePlayerTeam.formatPlayerName(scoreplayerteam1, score1.getPlayerName()); + String s2 = EnumChatFormatting.RED + "" + score1.getScorePoints(); + int k = j1 - j * this.getFontRenderer().FONT_HEIGHT; + int l = parScaledResolution.getScaledWidth() - b0 + 2; + drawRect(k1 - 2, k, l, k + this.getFontRenderer().FONT_HEIGHT, 1342177280); + this.getFontRenderer().drawString(s1, k1, k, 0xFFFFFFFF); + this.getFontRenderer().drawString(s2, l - this.getFontRenderer().getStringWidth(s2), k, 0xFFFFFFFF); + if (j == arraylist1.size()) { + String s3 = parScoreObjective.getDisplayName(); + drawRect(k1 - 2, k - this.getFontRenderer().FONT_HEIGHT - 1, l, k - 1, 1610612736); + drawRect(k1 - 2, k - 1, l, k, 1342177280); + this.getFontRenderer().drawString(s3, k1 + i / 2 - this.getFontRenderer().getStringWidth(s3) / 2, + k - this.getFontRenderer().FONT_HEIGHT, 0xFFFFFFFF); + } + } + + } + + protected void renderTooltip(ScaledResolution sr, float partialTicks) { + if (this.mc.getRenderViewEntity() instanceof EntityPlayer) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(widgetsTexPath); + EntityPlayer entityplayer = (EntityPlayer) this.mc.getRenderViewEntity(); + int i = sr.getScaledWidth() / 2; + float f = this.zLevel; + this.zLevel = -90.0F; + this.drawTexturedModalRect(i - 91, sr.getScaledHeight() - 22, 0, 0, 182, 22); + + if (PointerInputAbstraction.isTouchMode()) { + this.mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); + this.drawTexturedModalRect(i + 89, sr.getScaledHeight() - 22, 234, 0, 22, 22); + int areaHAdd = 12; + hotbarAreaX = (i - 91) * mc.displayWidth / sr.getScaledWidth(); + hotbarAreaY = (sr.getScaledHeight() - 22 - areaHAdd) * mc.displayHeight / sr.getScaledHeight(); + hotbarAreaW = 203 * mc.displayWidth / sr.getScaledWidth(); + hotbarAreaH = (22 + areaHAdd) * mc.displayHeight / sr.getScaledHeight(); + } else { + hotbarAreaX = -1; + hotbarAreaY = -1; + hotbarAreaW = -1; + hotbarAreaH = -1; + } + + this.mc.getTextureManager().bindTexture(widgetsTexPath); + this.drawTexturedModalRect(i - 91 - 1 + entityplayer.inventory.currentItem * 20, + sr.getScaledHeight() - 22 - 1, 0, 22, 24, 22); + this.zLevel = f; + GlStateManager.enableRescaleNormal(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + RenderHelper.enableGUIStandardItemLighting(); + + for (int j = 0; j < 9; ++j) { + int k = sr.getScaledWidth() / 2 - 90 + j * 20 + 2; + int l = sr.getScaledHeight() - 16 - 3; + this.renderHotbarItem(j, k, l, partialTicks, entityplayer); + } + + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + + GlStateManager.disableBlend(); + } + } + + /** + * + Renders a Vignette arount the entire screen that changes with light level. */ public void renderVignette(float parFloat1, int scaledWidth, int scaledHeight) { parFloat1 = 1.0F - parFloat1; @@ -853,65 +1178,45 @@ public class GuiIngame extends Gui { GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); } - private void func_180474_b(float parFloat1, ScaledResolution parScaledResolution) { - if (parFloat1 < 1.0F) { - parFloat1 = parFloat1 * parFloat1; - parFloat1 = parFloat1 * parFloat1; - parFloat1 = parFloat1 * 0.8F + 0.2F; - } - - GlStateManager.disableAlpha(); - GlStateManager.disableDepth(); - GlStateManager.depthMask(false); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.color(1.0F, 1.0F, 1.0F, parFloat1); - this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - EaglerTextureAtlasSprite textureatlassprite = this.mc.getBlockRendererDispatcher().getBlockModelShapes() - .getTexture(Blocks.portal.getDefaultState()); - float f = textureatlassprite.getMinU(); - float f1 = textureatlassprite.getMinV(); - float f2 = textureatlassprite.getMaxU(); - float f3 = textureatlassprite.getMaxV(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(0.0D, (double) parScaledResolution.getScaledHeight(), -90.0D).tex((double) f, (double) f3) - .endVertex(); - worldrenderer.pos((double) parScaledResolution.getScaledWidth(), (double) parScaledResolution.getScaledHeight(), - -90.0D).tex((double) f2, (double) f3).endVertex(); - worldrenderer.pos((double) parScaledResolution.getScaledWidth(), 0.0D, -90.0D).tex((double) f2, (double) f1) - .endVertex(); - worldrenderer.pos(0.0D, 0.0D, -90.0D).tex((double) f, (double) f1).endVertex(); - tessellator.draw(); - GlStateManager.depthMask(true); - GlStateManager.enableDepth(); - GlStateManager.enableAlpha(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + public void setRecordPlaying(IChatComponent parIChatComponent, boolean parFlag) { + this.setRecordPlaying(parIChatComponent.getUnformattedText(), parFlag); } - private void renderHotbarItem(int index, int xPos, int yPos, float partialTicks, EntityPlayer parEntityPlayer) { - ItemStack itemstack = parEntityPlayer.inventory.mainInventory[index]; - if (itemstack != null) { - float f = (float) itemstack.animationsToGo - partialTicks; - if (f > 0.0F) { - GlStateManager.pushMatrix(); - float f1 = 1.0F + f / 5.0F; - GlStateManager.translate((float) (xPos + 8), (float) (yPos + 12), 0.0F); - GlStateManager.scale(1.0F / f1, (f1 + 1.0F) / 2.0F, 1.0F); - GlStateManager.translate((float) (-(xPos + 8)), (float) (-(yPos + 12)), 0.0F); - } + public void setRecordPlaying(String parString1, boolean parFlag) { + this.recordPlaying = parString1; + this.recordPlayingUpFor = 60; + this.recordIsPlaying = parFlag; + } - this.itemRenderer.renderItemAndEffectIntoGUI(itemstack, xPos, yPos); - if (f > 0.0F) { - GlStateManager.popMatrix(); - } + public void setRecordPlayingMessage(String parString1) { + this.setRecordPlaying(I18n.format("record.nowPlaying", new Object[] { parString1 }), true); + } - this.itemRenderer.renderItemOverlays(this.mc.fontRendererObj, itemstack, xPos, yPos); + protected boolean showCrosshair() { + if (this.mc.gameSettings.showDebugInfo && !this.mc.thePlayer.hasReducedDebug() + && !this.mc.gameSettings.reducedDebugInfo) { + return false; + } else if (this.mc.playerController.isSpectator()) { + if (this.mc.pointedEntity != null) { + return true; + } else { + if (this.mc.objectMouseOver != null + && this.mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + BlockPos blockpos = this.mc.objectMouseOver.getBlockPos(); + if (this.mc.theWorld.getTileEntity(blockpos) instanceof IInventory) { + return true; + } + } + + return false; + } + } else { + return true; } } - /**+ - * The update tick for the ingame UI + /** + * + The update tick for the ingame UI */ public void updateTick() { if (this.recordPlayingUpFor > 0) { @@ -947,282 +1252,6 @@ public class GuiIngame extends Gui { } - public void setRecordPlayingMessage(String parString1) { - this.setRecordPlaying(I18n.format("record.nowPlaying", new Object[] { parString1 }), true); - } - - public void setRecordPlaying(String parString1, boolean parFlag) { - this.recordPlaying = parString1; - this.recordPlayingUpFor = 60; - this.recordIsPlaying = parFlag; - } - - public void displayTitle(String parString1, String parString2, int parInt1, int parInt2, int parInt3) { - if (parString1 == null && parString2 == null && parInt1 < 0 && parInt2 < 0 && parInt3 < 0) { - this.field_175201_x = ""; - this.field_175200_y = ""; - this.field_175195_w = 0; - } else if (parString1 != null) { - this.field_175201_x = parString1; - this.field_175195_w = this.field_175199_z + this.field_175192_A + this.field_175193_B; - } else if (parString2 != null) { - this.field_175200_y = parString2; - } else { - if (parInt1 >= 0) { - this.field_175199_z = parInt1; - } - - if (parInt2 >= 0) { - this.field_175192_A = parInt2; - } - - if (parInt3 >= 0) { - this.field_175193_B = parInt3; - } - - if (this.field_175195_w > 0) { - this.field_175195_w = this.field_175199_z + this.field_175192_A + this.field_175193_B; - } - - } - } - - public void drawEaglerPlayerOverlay(int x, int y, float partialTicks) { - Entity e = mc.getRenderViewEntity(); - if (e != null && e instanceof EntityLivingBase) { - EntityLivingBase ent = (EntityLivingBase) e; - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - GlStateManager.enableDepth(); - GlStateManager.enableColorMaterial(); - GlStateManager.pushMatrix(); - GlStateManager.translate((float) x - 10, (float) y + 36, 50.0F); - GlStateManager.scale(-17.0F, 17.0F, 17.0F); - GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); - float f = ent.renderYawOffset; - float f1 = ent.rotationYaw; - float f2 = ent.prevRotationYaw; - float f3 = ent.prevRotationYawHead; - float f4 = ent.rotationYawHead; - float f5 = ent.prevRenderYawOffset; - GlStateManager.rotate(115.0F, 0.0F, 1.0F, 0.0F); - RenderHelper.enableStandardItemLighting(); - float f6 = ent.prevRenderYawOffset + (ent.renderYawOffset - ent.prevRenderYawOffset) * partialTicks; - ent.rotationYawHead -= f6; - ent.prevRotationYawHead -= f6; - ent.rotationYawHead *= 0.5f; - ent.prevRotationYawHead *= 0.5f; - ent.renderYawOffset = 0.0f; - ent.prevRenderYawOffset = 0.0f; - ent.prevRotationYaw = 0.0f; - ent.rotationYaw = 0.0f; - GlStateManager.rotate(-135.0F - - (ent.prevRotationYawHead + (ent.rotationYawHead - ent.prevRotationYawHead) * partialTicks) * 0.5F, - 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(ent.rotationPitch * 0.2f, 1.0F, 0.0F, 0.0F); - RenderManager rendermanager = Minecraft.getMinecraft().getRenderManager(); - rendermanager.setPlayerViewY(180.0F); - rendermanager.setRenderShadow(false); - rendermanager.renderEntityWithPosYaw(ent, 0.0D, 0.0D, 0.0D, 0.0F, partialTicks); - rendermanager.setRenderShadow(true); - ent.renderYawOffset = f; - ent.rotationYaw = f1; - ent.prevRotationYaw = f2; - ent.prevRotationYawHead = f3; - ent.rotationYawHead = f4; - ent.prevRenderYawOffset = f5; - GlStateManager.popMatrix(); - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableRescaleNormal(); - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.disableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - } - } - - public void setRecordPlaying(IChatComponent parIChatComponent, boolean parFlag) { - this.setRecordPlaying(parIChatComponent.getUnformattedText(), parFlag); - } - - /**+ - * returns a pointer to the persistant Chat GUI, containing all - * previous chat messages and such - */ - public GuiNewChat getChatGUI() { - return this.persistantChatGUI; - } - - public int getUpdateCounter() { - return this.updateCounter; - } - - public FontRenderer getFontRenderer() { - return this.mc.fontRendererObj; - } - - public GuiSpectator getSpectatorGui() { - return this.spectatorGui; - } - - public GuiPlayerTabOverlay getTabList() { - return this.overlayPlayerList; - } - - public void func_181029_i() { - this.overlayPlayerList.func_181030_a(); - } - - private int hotbarAreaX = -1; - private int hotbarAreaY = -1; - private int hotbarAreaW = -1; - private int hotbarAreaH = -1; - private int currentHotbarSlotTouch = -1; - private long hotbarSlotTouchStart = -1l; - private boolean hotbarSlotTouchAlreadySelected = false; - private int interactButtonX = -1; - private int interactButtonY = -1; - private int interactButtonW = -1; - private int interactButtonH = -1; - private int touchVPosX = -1; - private int touchVPosY = -1; - private int touchEventUID = -1; - - private void drawEaglerInteractButton(ScaledResolution parScaledResolution) { - if (PointerInputAbstraction.isTouchMode() && mc.objectMouseOver != null - && mc.objectMouseOver.typeOfHit == MovingObjectType.ENTITY) { - int scale = parScaledResolution.getScaleFactor(); - interactButtonW = 118 * scale; - interactButtonH = 20 * scale; - int xx = (parScaledResolution.getScaledWidth() - 118) / 2; - int yy = parScaledResolution.getScaledHeight() - 70; - interactButtonX = xx * scale; - interactButtonY = yy * scale; - mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); - boolean hover = touchVPosX >= interactButtonX && touchVPosY >= interactButtonY - && touchVPosX < interactButtonX + interactButtonW && touchVPosY < interactButtonY + interactButtonH; - float f = MathHelper.clamp_float(mc.gameSettings.touchControlOpacity, 0.0f, 1.0f); - if (f > 0.0f) { - GlStateManager.color(1.0f, 1.0f, 1.0f, f); - drawTexturedModalRect(xx, yy, 0, hover ? 216 : 236, 118, 20); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - drawCenteredString(mc.fontRendererObj, I18n.format("touch.interact.entity"), - parScaledResolution.getScaledWidth() / 2, yy + 6, - (hover ? 16777120 : 14737632) | ((int) (f * 255.0f) << 24)); - } - } else { - interactButtonX = -1; - interactButtonY = -1; - interactButtonW = -1; - interactButtonH = -1; - } - } - - private int applyTouchHotbarTransformX(int posX, boolean scaled) { - if (scaled) { - return (posX + mc.scaledResolution.getScaledWidth() / 4) * 2 / 3; - } else { - return (posX + mc.displayWidth / 4) * 2 / 3; - } - } - - private int applyTouchHotbarTransformY(int posY, boolean scaled) { - if (scaled) { - return (posY + mc.scaledResolution.getScaledHeight() / 2) * 2 / 3; - } else { - return (posY + mc.displayHeight / 2) * 2 / 3; - } - } - - private void onBeginHotbarDraw() { - if (PointerInputAbstraction.isTouchMode()) { - GlStateManager.pushMatrix(); - ScaledResolution res = mc.scaledResolution; - GlStateManager.translate(res.getScaledWidth() / -4, res.getScaledHeight() / -2, field_175199_z); - GlStateManager.scale(1.5f, 1.5f, 1.5f); - } - } - - private void onEndHotbarDraw() { - if (PointerInputAbstraction.isTouchMode()) { - GlStateManager.popMatrix(); - } - } - - private int getHotbarSlotTouched(int pointX) { - int xx = pointX - hotbarAreaX - 2; - xx /= 20 * mc.scaledResolution.getScaleFactor(); - if (xx < 0) - xx = 0; - if (xx > 9) - xx = 9; - return xx; - } - - public boolean handleTouchBeginEagler(int uid, int pointX, int pointY) { - if (mc.thePlayer == null) { - return false; - } - if (touchEventUID == -1) { - pointX = applyTouchHotbarTransformX(pointX, false); - pointY = applyTouchHotbarTransformY(pointY, false); - if (pointX >= hotbarAreaX && pointY >= hotbarAreaY && pointX < hotbarAreaX + hotbarAreaW - && pointY < hotbarAreaY + hotbarAreaH) { - touchEventUID = uid; - currentHotbarSlotTouch = getHotbarSlotTouched(pointX); - hotbarSlotTouchStart = EagRuntime.steadyTimeMillis(); - if (currentHotbarSlotTouch >= 0 && currentHotbarSlotTouch < 9) { - if (mc.thePlayer.isSpectator()) { - hotbarSlotTouchAlreadySelected = false; - mc.ingameGUI.getSpectatorGui().func_175260_a(currentHotbarSlotTouch); - } else { - hotbarSlotTouchAlreadySelected = (mc.thePlayer.inventory.currentItem == currentHotbarSlotTouch); - mc.thePlayer.inventory.currentItem = currentHotbarSlotTouch; - } - } else if (currentHotbarSlotTouch == 9) { - hotbarSlotTouchAlreadySelected = false; - currentHotbarSlotTouch = 69; - if (mc.playerController.isRidingHorse()) { - mc.thePlayer.sendHorseInventory(); - } else { - mc.getNetHandler().addToSendQueue( - new C16PacketClientStatus(C16PacketClientStatus.EnumState.OPEN_INVENTORY_ACHIEVEMENT)); - mc.displayGuiScreen(new GuiInventory(mc.thePlayer)); - } - } - return true; - } - if (pointX >= interactButtonX && pointY >= interactButtonY && pointX < interactButtonX + interactButtonW - && pointY < interactButtonY + interactButtonH) { - touchEventUID = uid; - mc.rightClickMouse(); - return true; - } - } - return false; - } - - public boolean handleTouchEndEagler(int uid, int pointX, int pointY) { - if (uid == touchEventUID) { - if (hotbarSlotTouchStart != -1l && currentHotbarSlotTouch != 69) { - if (EagRuntime.steadyTimeMillis() - hotbarSlotTouchStart < 350l) { - if (hotbarSlotTouchAlreadySelected) { - if (mc.thePlayer != null) { - mc.thePlayer.dropOneItem(false); - } - } - } - } - touchVPosX = -1; - touchVPosY = -1; - touchEventUID = -1; - currentHotbarSlotTouch = -1; - hotbarSlotTouchStart = -1l; - hotbarSlotTouchAlreadySelected = false; - return true; - } - return false; - } - public void updateTouchEagler(boolean screenTouched) { if (screenTouched) { int pointCount = Touch.touchPointCount(); @@ -1274,17 +1303,4 @@ public class GuiIngame extends Gui { hotbarSlotTouchAlreadySelected = false; } - public boolean isTouchOverlapEagler(int uid, int tx, int ty) { - if (touchEventUID == uid) { - return true; - } - ty = mc.displayHeight - ty - 1; - tx = applyTouchHotbarTransformX(tx, false); - ty = applyTouchHotbarTransformY(ty, false); - return (tx >= hotbarAreaX && ty >= hotbarAreaY && tx < hotbarAreaX + hotbarAreaW - && ty < hotbarAreaY + hotbarAreaH) - || (tx >= interactButtonX && ty >= interactButtonY && tx < interactButtonX + interactButtonW - && ty < interactButtonY + interactButtonH); - } - } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiIngameMenu.java b/src/game/java/net/minecraft/client/gui/GuiIngameMenu.java index 7d70a14a..d455e87c 100644 --- a/src/game/java/net/minecraft/client/gui/GuiIngameMenu.java +++ b/src/game/java/net/minecraft/client/gui/GuiIngameMenu.java @@ -27,22 +27,25 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -64,71 +67,9 @@ public class GuiIngameMenu extends GuiScreen { } } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - this.updateCheckerOverlay.setResolution(mc, width, height); - byte b0 = -16; - boolean flag = true; - this.buttonList.add(new GuiButtonWithStupidIcons(1, this.width / 2 - 100, this.height / 4 + 120 + b0, - I18n.format("menu.returnToMenu", new Object[0]), PauseMenuCustomizeState.icon_disconnect_L, - PauseMenuCustomizeState.icon_disconnect_L_aspect, PauseMenuCustomizeState.icon_disconnect_R, - PauseMenuCustomizeState.icon_disconnect_R_aspect)); - if (!this.mc.isIntegratedServerRunning()) { - ((GuiButton) this.buttonList.get(0)).displayString = I18n.format("menu.disconnect", new Object[0]); - if (this.mc.thePlayer != null && this.mc.thePlayer.sendQueue.getEaglerMessageProtocol().ver >= 4) { - this.buttonList.add(notifBellButton = new GuiButtonNotifBell(11, width - 22, height - 22)); - notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); - } - } - - this.buttonList.add(new GuiButtonWithStupidIcons(4, this.width / 2 - 100, this.height / 4 + 24 + b0, - I18n.format("menu.returnToGame", new Object[0]), PauseMenuCustomizeState.icon_backToGame_L, - PauseMenuCustomizeState.icon_backToGame_L_aspect, PauseMenuCustomizeState.icon_backToGame_R, - PauseMenuCustomizeState.icon_backToGame_R_aspect)); - this.buttonList.add(new GuiButtonWithStupidIcons(0, this.width / 2 - 100, this.height / 4 + 96 + b0, 98, 20, - I18n.format("menu.options", new Object[0]), PauseMenuCustomizeState.icon_options_L, - PauseMenuCustomizeState.icon_options_L_aspect, PauseMenuCustomizeState.icon_options_R, - PauseMenuCustomizeState.icon_options_R_aspect)); - this.buttonList - .add(lanButton = new GuiButtonWithStupidIcons(7, this.width / 2 + 2, this.height / 4 + 96 + b0, 98, 20, - I18n.format(LANServerController.isLANOpen() ? "menu.closeLan" : "menu.openToLan", - new Object[0]), - PauseMenuCustomizeState.icon_discord_L, PauseMenuCustomizeState.icon_discord_L_aspect, - PauseMenuCustomizeState.icon_discord_R, PauseMenuCustomizeState.icon_discord_R_aspect)); - this.buttonList.add(new GuiButtonWithStupidIcons(5, this.width / 2 - 100, this.height / 4 + 48 + b0, 98, 20, - I18n.format("gui.achievements", new Object[0]), PauseMenuCustomizeState.icon_achievements_L, - PauseMenuCustomizeState.icon_achievements_L_aspect, PauseMenuCustomizeState.icon_achievements_R, - PauseMenuCustomizeState.icon_achievements_R_aspect)); - this.buttonList.add(new GuiButtonWithStupidIcons(6, this.width / 2 + 2, this.height / 4 + 48 + b0, 98, 20, - I18n.format("gui.stats", new Object[0]), PauseMenuCustomizeState.icon_statistics_L, - PauseMenuCustomizeState.icon_statistics_L_aspect, PauseMenuCustomizeState.icon_statistics_R, - PauseMenuCustomizeState.icon_statistics_R_aspect)); - lanButton.enabled = SingleplayerServerController.isWorldRunning(); - if (PauseMenuCustomizeState.discordButtonMode != PauseMenuCustomizeState.DISCORD_MODE_NONE) { - lanButton.enabled = true; - lanButton.id = 8; - lanButton.displayString = "" + PauseMenuCustomizeState.discordButtonText; - } - if (PauseMenuCustomizeState.serverInfoMode != PauseMenuCustomizeState.DISCORD_MODE_NONE) { - this.buttonList.add(new GuiButtonWithStupidIcons(9, this.width / 2 - 100, this.height / 4 + 72 + b0, - PauseMenuCustomizeState.serverInfoButtonText, PauseMenuCustomizeState.icon_serverInfo_L, - PauseMenuCustomizeState.icon_serverInfo_L_aspect, PauseMenuCustomizeState.icon_serverInfo_R, - PauseMenuCustomizeState.icon_serverInfo_R_aspect)); - } - if (!hasSentAutoSave) { - hasSentAutoSave = true; - SingleplayerServerController.autoSave(); - } - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { switch (parGuiButton.id) { @@ -217,26 +158,20 @@ public class GuiIngameMenu extends GuiScreen { } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - super.updateScreen(); - if (EagRuntime.getConfiguration().isAllowVoiceClient() - && (!mc.isSingleplayer() || LANServerController.isHostingLAN())) { - voiceMenu.updateScreen(); - } - if (Mouse.isActuallyGrabbed()) { - Mouse.setGrabbed(false); - } - if (notifBellButton != null && mc.thePlayer != null) { - notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); + public void confirmClicked(boolean par1, int par2) { + mc.displayGuiScreen(this); + LANServerController.closeLANNoKick(); + if (par1) { + LANServerController.cleanupLAN(); + SingleplayerServerController.configureLAN(this.mc.theWorld.getWorldInfo().getGameType(), false); } + this.mc.ingameGUI.getChatGUI().printChatMessage(new ChatComponentText(I18n.format("lanServer.closed"))); + this.lanButton.displayString = I18n.format("menu.openToLan"); } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -318,6 +253,72 @@ public class GuiIngameMenu extends GuiScreen { } } + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + this.updateCheckerOverlay.setResolution(mc, width, height); + byte b0 = -16; + boolean flag = true; + this.buttonList.add(new GuiButtonWithStupidIcons(1, this.width / 2 - 100, this.height / 4 + 120 + b0, + I18n.format("menu.returnToMenu", new Object[0]), PauseMenuCustomizeState.icon_disconnect_L, + PauseMenuCustomizeState.icon_disconnect_L_aspect, PauseMenuCustomizeState.icon_disconnect_R, + PauseMenuCustomizeState.icon_disconnect_R_aspect)); + if (!this.mc.isIntegratedServerRunning()) { + ((GuiButton) this.buttonList.get(0)).displayString = I18n.format("menu.disconnect", new Object[0]); + if (this.mc.thePlayer != null && this.mc.thePlayer.sendQueue.getEaglerMessageProtocol().ver >= 4) { + this.buttonList.add(notifBellButton = new GuiButtonNotifBell(11, width - 22, height - 22)); + notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); + } + } + + this.buttonList.add(new GuiButtonWithStupidIcons(4, this.width / 2 - 100, this.height / 4 + 24 + b0, + I18n.format("menu.returnToGame", new Object[0]), PauseMenuCustomizeState.icon_backToGame_L, + PauseMenuCustomizeState.icon_backToGame_L_aspect, PauseMenuCustomizeState.icon_backToGame_R, + PauseMenuCustomizeState.icon_backToGame_R_aspect)); + this.buttonList.add(new GuiButtonWithStupidIcons(0, this.width / 2 - 100, this.height / 4 + 96 + b0, 98, 20, + I18n.format("menu.options", new Object[0]), PauseMenuCustomizeState.icon_options_L, + PauseMenuCustomizeState.icon_options_L_aspect, PauseMenuCustomizeState.icon_options_R, + PauseMenuCustomizeState.icon_options_R_aspect)); + this.buttonList + .add(lanButton = new GuiButtonWithStupidIcons(7, this.width / 2 + 2, this.height / 4 + 96 + b0, 98, 20, + I18n.format(LANServerController.isLANOpen() ? "menu.closeLan" : "menu.openToLan", + new Object[0]), + PauseMenuCustomizeState.icon_discord_L, PauseMenuCustomizeState.icon_discord_L_aspect, + PauseMenuCustomizeState.icon_discord_R, PauseMenuCustomizeState.icon_discord_R_aspect)); + this.buttonList.add(new GuiButtonWithStupidIcons(5, this.width / 2 - 100, this.height / 4 + 48 + b0, 98, 20, + I18n.format("gui.achievements", new Object[0]), PauseMenuCustomizeState.icon_achievements_L, + PauseMenuCustomizeState.icon_achievements_L_aspect, PauseMenuCustomizeState.icon_achievements_R, + PauseMenuCustomizeState.icon_achievements_R_aspect)); + this.buttonList.add(new GuiButtonWithStupidIcons(6, this.width / 2 + 2, this.height / 4 + 48 + b0, 98, 20, + I18n.format("gui.stats", new Object[0]), PauseMenuCustomizeState.icon_statistics_L, + PauseMenuCustomizeState.icon_statistics_L_aspect, PauseMenuCustomizeState.icon_statistics_R, + PauseMenuCustomizeState.icon_statistics_R_aspect)); + lanButton.enabled = SingleplayerServerController.isWorldRunning(); + if (PauseMenuCustomizeState.discordButtonMode != PauseMenuCustomizeState.DISCORD_MODE_NONE) { + lanButton.enabled = true; + lanButton.id = 8; + lanButton.displayString = "" + PauseMenuCustomizeState.discordButtonText; + } + if (PauseMenuCustomizeState.serverInfoMode != PauseMenuCustomizeState.DISCORD_MODE_NONE) { + this.buttonList.add(new GuiButtonWithStupidIcons(9, this.width / 2 - 100, this.height / 4 + 72 + b0, + PauseMenuCustomizeState.serverInfoButtonText, PauseMenuCustomizeState.icon_serverInfo_L, + PauseMenuCustomizeState.icon_serverInfo_L_aspect, PauseMenuCustomizeState.icon_serverInfo_R, + PauseMenuCustomizeState.icon_serverInfo_R_aspect)); + } + if (!hasSentAutoSave) { + hasSentAutoSave = true; + SingleplayerServerController.autoSave(); + } + } + + protected boolean isPartOfPauseMenu() { + return true; + } + protected void keyTyped(char par1, int par2) { try { if (EagRuntime.getConfiguration().isAllowVoiceClient() @@ -329,17 +330,6 @@ public class GuiIngameMenu extends GuiScreen { } } - public void confirmClicked(boolean par1, int par2) { - mc.displayGuiScreen(this); - LANServerController.closeLANNoKick(); - if (par1) { - LANServerController.cleanupLAN(); - SingleplayerServerController.configureLAN(this.mc.theWorld.getWorldInfo().getGameType(), false); - } - this.mc.ingameGUI.getChatGUI().printChatMessage(new ChatComponentText(I18n.format("lanServer.closed"))); - this.lanButton.displayString = I18n.format("menu.openToLan"); - } - protected void mouseClicked(int par1, int par2, int par3) { try { if (EagRuntime.getConfiguration().isAllowVoiceClient() @@ -379,13 +369,6 @@ public class GuiIngameMenu extends GuiScreen { super.mouseClicked(par1, par2, par3); } - public void setWorldAndResolution(Minecraft par1Minecraft, int par2, int par3) { - super.setWorldAndResolution(par1Minecraft, par2, par3); - if (EagRuntime.getConfiguration().isAllowVoiceClient()) { - voiceMenu.setResolution(par1Minecraft, par2, par3); - } - } - protected void mouseReleased(int par1, int par2, int par3) { try { if (EagRuntime.getConfiguration().isAllowVoiceClient() @@ -397,7 +380,27 @@ public class GuiIngameMenu extends GuiScreen { } } - protected boolean isPartOfPauseMenu() { - return true; + public void setWorldAndResolution(Minecraft par1Minecraft, int par2, int par3) { + super.setWorldAndResolution(par1Minecraft, par2, par3); + if (EagRuntime.getConfiguration().isAllowVoiceClient()) { + voiceMenu.setResolution(par1Minecraft, par2, par3); + } + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + super.updateScreen(); + if (EagRuntime.getConfiguration().isAllowVoiceClient() + && (!mc.isSingleplayer() || LANServerController.isHostingLAN())) { + voiceMenu.updateScreen(); + } + if (Mouse.isActuallyGrabbed()) { + Mouse.setGrabbed(false); + } + if (notifBellButton != null && mc.thePlayer != null) { + notifBellButton.setUnread(mc.thePlayer.sendQueue.getNotifManager().getUnread()); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiKeyBindingList.java b/src/game/java/net/minecraft/client/gui/GuiKeyBindingList.java index d636e870..b73daca9 100644 --- a/src/game/java/net/minecraft/client/gui/GuiKeyBindingList.java +++ b/src/game/java/net/minecraft/client/gui/GuiKeyBindingList.java @@ -10,82 +10,30 @@ import net.minecraft.client.settings.GameSettings; import net.minecraft.client.settings.KeyBinding; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiKeyBindingList extends GuiListExtended { - private final GuiControls field_148191_k; - private final Minecraft mc; - private final GuiListExtended.IGuiListEntry[] listEntries; - private int maxListLabelWidth = 0; - - public GuiKeyBindingList(GuiControls controls, Minecraft mcIn) { - super(mcIn, controls.width, controls.height, 66, controls.height - 32, 20); - this.field_148191_k = controls; - this.mc = mcIn; - KeyBinding[] akeybinding = (KeyBinding[]) ArrayUtils.clone(mcIn.gameSettings.keyBindings); - this.listEntries = new GuiListExtended.IGuiListEntry[akeybinding.length + KeyBinding.getKeybinds().size()]; - Arrays.sort(akeybinding); - int i = 0; - String s = null; - - for (int l = 0; l < akeybinding.length; ++l) { - KeyBinding keybinding = akeybinding[l]; - String s1 = keybinding.getKeyCategory(); - if (!s1.equals(s)) { - s = s1; - this.listEntries[i++] = new GuiKeyBindingList.CategoryEntry(s1); - } - - int j = mcIn.fontRendererObj.getStringWidth(I18n.format(keybinding.getKeyDescription(), new Object[0])); - if (j > this.maxListLabelWidth) { - this.maxListLabelWidth = j; - } - - this.listEntries[i++] = new GuiKeyBindingList.KeyEntry(keybinding); - } - - } - - protected int getSize() { - return this.listEntries.length; - } - - /**+ - * Gets the IGuiListEntry object for the given index - */ - public GuiListExtended.IGuiListEntry getListEntry(int i) { - return this.listEntries[i]; - } - - protected int getScrollBarX() { - return super.getScrollBarX() + 15; - } - - /**+ - * Gets the width of the list - */ - public int getListWidth() { - return super.getListWidth() + 32; - } - public class CategoryEntry implements GuiListExtended.IGuiListEntry { private final String labelText; private final int labelWidth; @@ -193,4 +141,61 @@ public class GuiKeyBindingList extends GuiListExtended { public void setSelected(int var1, int var2, int var3) { } } + + private final GuiControls field_148191_k; + private final Minecraft mc; + + private final GuiListExtended.IGuiListEntry[] listEntries; + + private int maxListLabelWidth = 0; + + public GuiKeyBindingList(GuiControls controls, Minecraft mcIn) { + super(mcIn, controls.width, controls.height, 66, controls.height - 32, 20); + this.field_148191_k = controls; + this.mc = mcIn; + KeyBinding[] akeybinding = (KeyBinding[]) ArrayUtils.clone(mcIn.gameSettings.keyBindings); + this.listEntries = new GuiListExtended.IGuiListEntry[akeybinding.length + KeyBinding.getKeybinds().size()]; + Arrays.sort(akeybinding); + int i = 0; + String s = null; + + for (int l = 0; l < akeybinding.length; ++l) { + KeyBinding keybinding = akeybinding[l]; + String s1 = keybinding.getKeyCategory(); + if (!s1.equals(s)) { + s = s1; + this.listEntries[i++] = new GuiKeyBindingList.CategoryEntry(s1); + } + + int j = mcIn.fontRendererObj.getStringWidth(I18n.format(keybinding.getKeyDescription(), new Object[0])); + if (j > this.maxListLabelWidth) { + this.maxListLabelWidth = j; + } + + this.listEntries[i++] = new GuiKeyBindingList.KeyEntry(keybinding); + } + + } + + /** + * + Gets the IGuiListEntry object for the given index + */ + public GuiListExtended.IGuiListEntry getListEntry(int i) { + return this.listEntries[i]; + } + + /** + * + Gets the width of the list + */ + public int getListWidth() { + return super.getListWidth() + 32; + } + + protected int getScrollBarX() { + return super.getScrollBarX() + 15; + } + + protected int getSize() { + return this.listEntries.length; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiLabel.java b/src/game/java/net/minecraft/client/gui/GuiLabel.java index c3122d32..137c1c9d 100644 --- a/src/game/java/net/minecraft/client/gui/GuiLabel.java +++ b/src/game/java/net/minecraft/client/gui/GuiLabel.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.util.List; @@ -10,22 +11,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,18 +69,6 @@ public class GuiLabel extends Gui { this.field_146163_s = 0; } - public void func_175202_a(String parString1) { - this.field_146173_k.add(I18n.format(parString1, new Object[0])); - } - - /**+ - * Sets the Label to be centered - */ - public GuiLabel setCentered() { - this.centered = true; - return this; - } - public void drawLabel(Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GlStateManager.enableBlend(); @@ -112,4 +104,16 @@ public class GuiLabel extends Gui { } } + + public void func_175202_a(String parString1) { + this.field_146173_k.add(I18n.format(parString1, new Object[0])); + } + + /** + * + Sets the Label to be centered + */ + public GuiLabel setCentered() { + this.centered = true; + return this; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiLanguage.java b/src/game/java/net/minecraft/client/gui/GuiLanguage.java index 84b61b0b..057e2031 100644 --- a/src/game/java/net/minecraft/client/gui/GuiLanguage.java +++ b/src/game/java/net/minecraft/client/gui/GuiLanguage.java @@ -12,32 +12,94 @@ import net.minecraft.client.resources.Language; import net.minecraft.client.resources.LanguageManager; import net.minecraft.client.settings.GameSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiLanguage extends GuiScreen { + class List extends GuiSlot { + private final java.util.List langCodeList = Lists.newArrayList(); + private final Map languageMap = Maps.newHashMap(); + + public List(Minecraft mcIn) { + super(mcIn, GuiLanguage.this.width, GuiLanguage.this.height, 32, GuiLanguage.this.height - 65 + 4, 18); + + for (Language language : GuiLanguage.this.languageManager.getLanguages()) { + this.languageMap.put(language.getLanguageCode(), language); + this.langCodeList.add(language.getLanguageCode()); + } + + } + + protected void drawBackground() { + GuiLanguage.this.drawDefaultBackground(); + } + + protected void drawSlot(int i, int var2, int j, int var4, int var5, int var6) { + GuiLanguage.this.fontRendererObj.setBidiFlag(true); + GuiLanguage.this.drawCenteredString(GuiLanguage.this.fontRendererObj, + ((Language) this.languageMap.get(this.langCodeList.get(i))).toString(), this.width / 2, j + 1, + 16777215); + GuiLanguage.this.fontRendererObj + .setBidiFlag(GuiLanguage.this.languageManager.getCurrentLanguage().isBidirectional()); + } + + protected void elementClicked(int i, boolean var2, int var3, int var4) { + Language language = (Language) this.languageMap.get(this.langCodeList.get(i)); + GuiLanguage.this.languageManager.setCurrentLanguage(language); + GuiLanguage.this.game_settings_3.language = language.getLanguageCode(); + this.mc.loadingScreen.eaglerShowRefreshResources(); + this.mc.refreshResources(); + GuiLanguage.this.fontRendererObj.setUnicodeFlag(GuiLanguage.this.languageManager.isCurrentLocaleUnicode() + || GuiLanguage.this.game_settings_3.forceUnicodeFont); + GuiLanguage.this.fontRendererObj + .setBidiFlag(GuiLanguage.this.languageManager.isCurrentLanguageBidirectional()); + GuiLanguage.this.confirmSettingsBtn.displayString = I18n.format("gui.done", new Object[0]); + GuiLanguage.this.forceUnicodeFontBtn.displayString = GuiLanguage.this.game_settings_3 + .getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT); + GuiLanguage.this.game_settings_3.saveOptions(); + GuiLanguage.this.mc.displayGuiScreen(GuiLanguage.this); + } + + protected int getContentHeight() { + return this.getSize() * 18; + } + + protected int getSize() { + return this.langCodeList.size(); + } + + protected boolean isSelected(int i) { + return ((String) this.langCodeList.get(i)) + .equals(GuiLanguage.this.languageManager.getCurrentLanguage().getLanguageCode()); + } + } + protected GuiScreen parentScreen; private GuiLanguage.List list; private final GameSettings game_settings_3; private final LanguageManager languageManager; private GuiOptionButton forceUnicodeFontBtn; + private GuiOptionButton confirmSettingsBtn; public GuiLanguage(GuiScreen screen, GameSettings gameSettingsObj, LanguageManager manager) { @@ -46,37 +108,9 @@ public class GuiLanguage extends GuiScreen { this.languageManager = manager; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.add(this.forceUnicodeFontBtn = new GuiOptionButton(100, this.width / 2 - 155, this.height - 38, - GameSettings.Options.FORCE_UNICODE_FONT, - this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT))); - this.buttonList.add(this.confirmSettingsBtn = new GuiOptionButton(6, this.width / 2 - 155 + 160, - this.height - 38, I18n.format("gui.done", new Object[0]))); - this.list = new GuiLanguage.List(this.mc); - this.list.registerScrollButtons(7, 8); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.list.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.list.handleTouchInput(); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -104,9 +138,9 @@ public class GuiLanguage extends GuiScreen { } } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.list.drawScreen(i, j, f); @@ -117,61 +151,31 @@ public class GuiLanguage extends GuiScreen { super.drawScreen(i, j, f); } - class List extends GuiSlot { - private final java.util.List langCodeList = Lists.newArrayList(); - private final Map languageMap = Maps.newHashMap(); + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.list.handleMouseInput(); + } - public List(Minecraft mcIn) { - super(mcIn, GuiLanguage.this.width, GuiLanguage.this.height, 32, GuiLanguage.this.height - 65 + 4, 18); + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.list.handleTouchInput(); + } - for (Language language : GuiLanguage.this.languageManager.getLanguages()) { - this.languageMap.put(language.getLanguageCode(), language); - this.langCodeList.add(language.getLanguageCode()); - } - - } - - protected int getSize() { - return this.langCodeList.size(); - } - - protected void elementClicked(int i, boolean var2, int var3, int var4) { - Language language = (Language) this.languageMap.get(this.langCodeList.get(i)); - GuiLanguage.this.languageManager.setCurrentLanguage(language); - GuiLanguage.this.game_settings_3.language = language.getLanguageCode(); - this.mc.loadingScreen.eaglerShowRefreshResources(); - this.mc.refreshResources(); - GuiLanguage.this.fontRendererObj.setUnicodeFlag(GuiLanguage.this.languageManager.isCurrentLocaleUnicode() - || GuiLanguage.this.game_settings_3.forceUnicodeFont); - GuiLanguage.this.fontRendererObj - .setBidiFlag(GuiLanguage.this.languageManager.isCurrentLanguageBidirectional()); - GuiLanguage.this.confirmSettingsBtn.displayString = I18n.format("gui.done", new Object[0]); - GuiLanguage.this.forceUnicodeFontBtn.displayString = GuiLanguage.this.game_settings_3 - .getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT); - GuiLanguage.this.game_settings_3.saveOptions(); - GuiLanguage.this.mc.displayGuiScreen(GuiLanguage.this); - } - - protected boolean isSelected(int i) { - return ((String) this.langCodeList.get(i)) - .equals(GuiLanguage.this.languageManager.getCurrentLanguage().getLanguageCode()); - } - - protected int getContentHeight() { - return this.getSize() * 18; - } - - protected void drawBackground() { - GuiLanguage.this.drawDefaultBackground(); - } - - protected void drawSlot(int i, int var2, int j, int var4, int var5, int var6) { - GuiLanguage.this.fontRendererObj.setBidiFlag(true); - GuiLanguage.this.drawCenteredString(GuiLanguage.this.fontRendererObj, - ((Language) this.languageMap.get(this.langCodeList.get(i))).toString(), this.width / 2, j + 1, - 16777215); - GuiLanguage.this.fontRendererObj - .setBidiFlag(GuiLanguage.this.languageManager.getCurrentLanguage().isBidirectional()); - } + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.add(this.forceUnicodeFontBtn = new GuiOptionButton(100, this.width / 2 - 155, this.height - 38, + GameSettings.Options.FORCE_UNICODE_FONT, + this.game_settings_3.getKeyBinding(GameSettings.Options.FORCE_UNICODE_FONT))); + this.buttonList.add(this.confirmSettingsBtn = new GuiOptionButton(6, this.width / 2 - 155 + 160, + this.height - 38, I18n.format("gui.done", new Object[0]))); + this.list = new GuiLanguage.List(this.mc); + this.list.registerScrollButtons(7, 8); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiListButton.java b/src/game/java/net/minecraft/client/gui/GuiListButton.java index a3e7fa71..52be55c6 100644 --- a/src/game/java/net/minecraft/client/gui/GuiListButton.java +++ b/src/game/java/net/minecraft/client/gui/GuiListButton.java @@ -3,22 +3,25 @@ package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,8 @@ public class GuiListButton extends GuiButton { this.guiResponder = responder; } - /**+ - * Builds the localized display string for this GuiListButton + /** + * + Builds the localized display string for this GuiListButton */ private String buildDisplayString() { return I18n.format(this.localizationStr, new Object[0]) + ": " @@ -51,9 +54,9 @@ public class GuiListButton extends GuiButton { this.guiResponder.func_175321_a(this.id, parFlag); } - /**+ - * Returns true if the mouse has been pressed on this control. - * Equivalent of MouseListener.mousePressed(MouseEvent e). + /** + * + Returns true if the mouse has been pressed on this control. Equivalent of + * MouseListener.mousePressed(MouseEvent e). */ public boolean mousePressed(Minecraft minecraft, int i, int j) { if (super.mousePressed(minecraft, i, j)) { diff --git a/src/game/java/net/minecraft/client/gui/GuiListExtended.java b/src/game/java/net/minecraft/client/gui/GuiListExtended.java index 19d70ff7..54fda8d3 100644 --- a/src/game/java/net/minecraft/client/gui/GuiListExtended.java +++ b/src/game/java/net/minecraft/client/gui/GuiListExtended.java @@ -2,45 +2,44 @@ package net.minecraft.client.gui; import net.minecraft.client.Minecraft; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class GuiListExtended extends GuiSlot { + public interface IGuiListEntry { + void drawEntry(int var1, int var2, int var3, int var4, int var5, int var6, int var7, boolean var8); + + boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6); + + void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6); + + void setSelected(int var1, int var2, int var3); + } + public GuiListExtended(Minecraft mcIn, int widthIn, int heightIn, int topIn, int bottomIn, int slotHeightIn) { super(mcIn, widthIn, heightIn, topIn, bottomIn, slotHeightIn); } - /**+ - * The element in the slot that was clicked, boolean for whether - * it was double clicked or not - */ - protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY) { - } - - /**+ - * Returns true if the element passed in is currently selected - */ - protected boolean isSelected(int slotIndex) { - return false; - } - protected void drawBackground() { } @@ -49,10 +48,26 @@ public abstract class GuiListExtended extends GuiSlot { parInt6, this.getSlotIndexFromScreenCoords(parInt5, parInt6) == entryID); } + /** + * + The element in the slot that was clicked, boolean for whether it was double + * clicked or not + */ + protected void elementClicked(int slotIndex, boolean isDoubleClick, int mouseX, int mouseY) { + } + protected void func_178040_a(int parInt1, int parInt2, int parInt3) { this.getListEntry(parInt1).setSelected(parInt1, parInt2, parInt3); } + public abstract GuiListExtended.IGuiListEntry getListEntry(int var1); + + /** + * + Returns true if the element passed in is currently selected + */ + protected boolean isSelected(int slotIndex) { + return false; + } + public boolean mouseClicked(int mouseX, int mouseY, int mouseEvent) { if (this.isMouseYWithinSlotBounds(mouseY)) { int i = this.getSlotIndexFromScreenCoords(mouseX, mouseY); @@ -83,16 +98,4 @@ public abstract class GuiListExtended extends GuiSlot { this.setEnabled(true); return false; } - - public abstract GuiListExtended.IGuiListEntry getListEntry(int var1); - - public interface IGuiListEntry { - void setSelected(int var1, int var2, int var3); - - void drawEntry(int var1, int var2, int var3, int var4, int var5, int var6, int var7, boolean var8); - - boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6); - - void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiLockIconButton.java b/src/game/java/net/minecraft/client/gui/GuiLockIconButton.java index 0cc12ca4..d9b25bc9 100644 --- a/src/game/java/net/minecraft/client/gui/GuiLockIconButton.java +++ b/src/game/java/net/minecraft/client/gui/GuiLockIconButton.java @@ -3,43 +3,59 @@ package net.minecraft.client.gui; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiLockIconButton extends GuiButton { + static enum Icon { + LOCKED(0, 146), LOCKED_HOVER(0, 166), LOCKED_DISABLED(0, 186), UNLOCKED(20, 146), UNLOCKED_HOVER(20, 166), + UNLOCKED_DISABLED(20, 186); + + private final int field_178914_g; + private final int field_178920_h; + + private Icon(int parInt2, int parInt3) { + this.field_178914_g = parInt2; + this.field_178920_h = parInt3; + } + + public int func_178910_a() { + return this.field_178914_g; + } + + public int func_178912_b() { + return this.field_178920_h; + } + } + private boolean field_175231_o = false; public GuiLockIconButton(int parInt1, int parInt2, int parInt3) { super(parInt1, parInt2, parInt3, 20, 20, ""); } - public boolean func_175230_c() { - return this.field_175231_o; - } - - public void func_175229_b(boolean parFlag) { - this.field_175231_o = parFlag; - } - - /**+ - * Draws this button to the screen. + /** + * + Draws this button to the screen. */ public void drawButton(Minecraft minecraft, int i, int j) { if (this.visible) { @@ -69,24 +85,11 @@ public class GuiLockIconButton extends GuiButton { } } - static enum Icon { - LOCKED(0, 146), LOCKED_HOVER(0, 166), LOCKED_DISABLED(0, 186), UNLOCKED(20, 146), UNLOCKED_HOVER(20, 166), - UNLOCKED_DISABLED(20, 186); + public void func_175229_b(boolean parFlag) { + this.field_175231_o = parFlag; + } - private final int field_178914_g; - private final int field_178920_h; - - private Icon(int parInt2, int parInt3) { - this.field_178914_g = parInt2; - this.field_178920_h = parInt3; - } - - public int func_178910_a() { - return this.field_178914_g; - } - - public int func_178912_b() { - return this.field_178920_h; - } + public boolean func_175230_c() { + return this.field_175231_o; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiMainMenu.java b/src/game/java/net/minecraft/client/gui/GuiMainMenu.java index 3b506490..2ddad86c 100644 --- a/src/game/java/net/minecraft/client/gui/GuiMainMenu.java +++ b/src/game/java/net/minecraft/client/gui/GuiMainMenu.java @@ -1,6 +1,13 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; import java.io.BufferedReader; import java.io.IOException; @@ -11,16 +18,15 @@ import java.util.Arrays; import java.util.Calendar; import java.util.Date; +import com.google.common.base.Charsets; +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EagUtils; import net.lax1dude.eaglercraft.v1_8.EaglerInputStream; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; import net.lax1dude.eaglercraft.v1_8.Mouse; - -import com.google.common.base.Charsets; -import com.google.common.collect.Lists; - import net.lax1dude.eaglercraft.v1_8.crypto.SHA1Digest; import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; @@ -47,22 +53,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.ISaveFormat; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -70,30 +79,22 @@ import net.minecraft.world.storage.ISaveFormat; public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { private static final Logger logger = LogManager.getLogger(); private static final EaglercraftRandom RANDOM = new EaglercraftRandom(); - private float updateCounter; - private boolean isDefault; private static final int lendef = 5987; private static final byte[] sha1def = new byte[] { -107, 77, 108, 49, 11, -100, -8, -119, -1, -100, -85, -55, 18, -69, -107, 113, -93, -101, -79, 32 }; - private String splashText; - private GuiButton buttonResetDemo; - private int panoramaTimer; - /**+ - * Texture allocated for the current viewport of the main menu's - * panorama background. + /** + * + Texture allocated for the current viewport of the main menu's panorama + * background. */ private static DynamicTexture viewportTexture = null; - private boolean field_175375_v = true; - private String openGLWarning1; - private String openGLWarning2; private static final ResourceLocation splashTexts = new ResourceLocation("texts/splashes.txt"); private static final ResourceLocation minecraftTitleTextures = new ResourceLocation( "textures/gui/title/minecraft.png"); private static final ResourceLocation minecraftTitleBlurFlag = new ResourceLocation( "textures/gui/title/background/enable_blur.txt"); private static final ResourceLocation eaglerGuiTextures = new ResourceLocation("eagler:gui/eagler_gui.png"); - /**+ - * An array of all the paths to the panorama pictures. + /** + * + An array of all the paths to the panorama pictures. */ private static final ResourceLocation[] titlePanoramaPaths = new ResourceLocation[] { new ResourceLocation("starlike:textures/gui/title/background/panorama_0.png"), @@ -102,19 +103,35 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { new ResourceLocation("starlike:textures/gui/title/background/panorama_3.png"), new ResourceLocation("starlike:textures/gui/title/background/panorama_4.png"), new ResourceLocation("starlike:textures/gui/title/background/panorama_5.png") }; + private static ResourceLocation backgroundTexture = null; + private static GuiMainMenu instance = null; + + public static void doResourceReloadHack() { + if (instance != null) { + instance.shouldReload = true; + } + } + + private float updateCounter; + private boolean isDefault; + private String splashText; + private GuiButton buttonResetDemo; + private int panoramaTimer; + private boolean field_175375_v = true; + private String openGLWarning1; + private String openGLWarning2; private int field_92024_r; private int field_92023_s; private int field_92022_t; private int field_92021_u; private int field_92020_v; private int field_92019_w; - private static ResourceLocation backgroundTexture = null; private GuiUpdateCheckerOverlay updateCheckerOverlay; private GuiButton downloadOfflineButton; - private boolean enableBlur = true; - private boolean shouldReload = false; - private static GuiMainMenu instance = null; + private boolean enableBlur = true; + + private boolean shouldReload = false; public GuiMainMenu() { instance = this; @@ -162,186 +179,9 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { reloadResourceFlags(); } - private void reloadResourceFlags() { - if (Minecraft.getMinecraft().isDemo()) { - this.isDefault = false; - } else { - if (!EagRuntime.getConfiguration().isEnableMinceraft()) { - this.isDefault = false; - } else { - try { - byte[] bytes = EaglerInputStream.inputStreamToBytesQuiet(Minecraft.getMinecraft() - .getResourceManager().getResource(minecraftTitleTextures).getInputStream()); - if (bytes != null && bytes.length == lendef) { - SHA1Digest sha1 = new SHA1Digest(); - byte[] sha1out = new byte[20]; - sha1.update(bytes, 0, bytes.length); - sha1.doFinal(sha1out, 0); - this.isDefault = Arrays.equals(sha1out, sha1def); - } else { - this.isDefault = false; - } - } catch (IOException e) { - this.isDefault = false; - } - } - } - - this.enableBlur = true; - - try { - byte[] bytes = EaglerInputStream.inputStreamToBytesQuiet( - Minecraft.getMinecraft().getResourceManager().getResource(minecraftTitleBlurFlag).getInputStream()); - if (bytes != null) { - String[] blurCfg = EagUtils.linesArray(new String(bytes, StandardCharsets.UTF_8)); - for (int i = 0; i < blurCfg.length; ++i) { - String s = blurCfg[i]; - if (s.startsWith("enable_blur=")) { - s = s.substring(12).trim(); - this.enableBlur = s.equals("1") || s.equals("true"); - break; - } - } - } - } catch (IOException e) { - ; - } - } - - public static void doResourceReloadHack() { - if (instance != null) { - instance.shouldReload = true; - } - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - ++this.panoramaTimer; - if (downloadOfflineButton != null) { - downloadOfflineButton.enabled = !UpdateService.shouldDisableDownloadButton(); - } - if (shouldReload) { - reloadResourceFlags(); - shouldReload = false; - } - } - - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player - */ - public boolean doesGuiPauseGame() { - return false; - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - if (viewportTexture == null) { - viewportTexture = new DynamicTexture(256, 256); - backgroundTexture = this.mc.getTextureManager().getDynamicTextureLocation("background", viewportTexture); - } - this.updateCheckerOverlay.setResolution(mc, width, height); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(new Date()); - if (calendar.get(2) + 1 == 12 && calendar.get(5) == 24) { - this.splashText = "Merry X-mas!"; - } else if (calendar.get(2) + 1 == 1 && calendar.get(5) == 1) { - this.splashText = "Happy new year!"; - } else if (calendar.get(2) + 1 == 10 && calendar.get(5) == 31) { - this.splashText = "OOoooOOOoooo! Spooky!"; - } - - int i = this.height / 4 + 48; - - boolean isFork = !EaglercraftVersion.projectOriginAuthor.equalsIgnoreCase(EaglercraftVersion.projectForkVendor); - - if (isFork && EaglercraftVersion.mainMenuStringF != null && EaglercraftVersion.mainMenuStringF.length() > 0) { - i += 11; - } - - if (this.mc.isDemo()) { - this.addDemoButtons(i, 24); - } else { - this.addSingleplayerMultiplayerButtons(i, 24); - } - - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, i + 72 + 12, 98, 20, - I18n.format("menu.options", new Object[0]))); - this.buttonList.add(new GuiButton(4, this.width / 2 + 2, i + 72 + 12, 98, 20, - I18n.format("menu.editProfile", new Object[0]))); - - this.buttonList.add(new GuiButtonLanguage(5, this.width / 2 - 124, i + 72 + 12)); - - if (isFork) { - this.openGLWarning1 = EaglercraftVersion.mainMenuStringE; - this.openGLWarning2 = EaglercraftVersion.mainMenuStringF; - boolean line2 = this.openGLWarning2 != null && this.openGLWarning2.length() > 0; - this.field_92023_s = this.fontRendererObj.getStringWidth(this.openGLWarning1); - this.field_92024_r = this.fontRendererObj.getStringWidth(this.openGLWarning2); - int j = Math.max(this.field_92023_s, this.field_92024_r); - this.field_92022_t = (this.width - j) / 2; - this.field_92021_u = ((GuiButton) this.buttonList.get(0)).yPosition - (line2 ? 32 : 21); - this.field_92020_v = this.field_92022_t + j; - this.field_92019_w = this.field_92021_u + (line2 ? 24 : 11); - } - - this.mc.func_181537_a(false); - } - - /**+ - * Adds Singleplayer and Multiplayer buttons on Main Menu for - * players who have bought the game. - */ - private void addSingleplayerMultiplayerButtons(int parInt1, int parInt2) { - this.buttonList - .add(new GuiButton(1, this.width / 2 - 100, parInt1, I18n.format("menu.singleplayer", new Object[0]))); - this.buttonList.add(new GuiButton(2, this.width / 2 - 100, parInt1 + parInt2 * 1, - I18n.format("menu.multiplayer", new Object[0]))); - if (EaglercraftVersion.mainMenuEnableGithubButton) { - this.buttonList.add( - new GuiButton(14, this.width / 2 - 100, parInt1 + parInt2 * 2, I18n.format("menu.forkOnGitlab"))); - } else { - if (EagRuntime.getConfiguration().isEnableDownloadOfflineButton() - && (EagRuntime.getConfiguration().getDownloadOfflineButtonLink() != null - || (!EagRuntime.isOfflineDownloadURL() && UpdateService.supported() - && UpdateService.getClientSignatureData() != null))) { - this.buttonList.add(downloadOfflineButton = new GuiButton(15, this.width / 2 - 100, - parInt1 + parInt2 * 2, I18n.format("update.downloadOffline"))); - downloadOfflineButton.enabled = !UpdateService.shouldDisableDownloadButton(); - } - } - } - - /**+ - * Adds Demo buttons on Main Menu for players who are playing - * Demo. - */ - private void addDemoButtons(int parInt1, int parInt2) { - this.buttonList - .add(new GuiButton(11, this.width / 2 - 100, parInt1, I18n.format("menu.playdemo", new Object[0]))); - this.buttonList.add(this.buttonResetDemo = new GuiButton(12, this.width / 2 - 100, parInt1 + parInt2 * 1, - I18n.format("menu.resetdemo", new Object[0]))); - this.buttonResetDemo.enabled = this.mc.gameSettings.hasCreatedDemoWorld; - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.id == 0) { @@ -389,6 +229,41 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { } } + /** + * + Adds Demo buttons on Main Menu for players who are playing Demo. + */ + private void addDemoButtons(int parInt1, int parInt2) { + this.buttonList + .add(new GuiButton(11, this.width / 2 - 100, parInt1, I18n.format("menu.playdemo", new Object[0]))); + this.buttonList.add(this.buttonResetDemo = new GuiButton(12, this.width / 2 - 100, parInt1 + parInt2 * 1, + I18n.format("menu.resetdemo", new Object[0]))); + this.buttonResetDemo.enabled = this.mc.gameSettings.hasCreatedDemoWorld; + } + + /** + * + Adds Singleplayer and Multiplayer buttons on Main Menu for players who have + * bought the game. + */ + private void addSingleplayerMultiplayerButtons(int parInt1, int parInt2) { + this.buttonList + .add(new GuiButton(1, this.width / 2 - 100, parInt1, I18n.format("menu.singleplayer", new Object[0]))); + this.buttonList.add(new GuiButton(2, this.width / 2 - 100, parInt1 + parInt2 * 1, + I18n.format("menu.multiplayer", new Object[0]))); + if (EaglercraftVersion.mainMenuEnableGithubButton) { + this.buttonList.add( + new GuiButton(14, this.width / 2 - 100, parInt1 + parInt2 * 2, I18n.format("menu.forkOnGitlab"))); + } else { + if (EagRuntime.getConfiguration().isEnableDownloadOfflineButton() + && (EagRuntime.getConfiguration().getDownloadOfflineButtonLink() != null + || (!EagRuntime.isOfflineDownloadURL() && UpdateService.supported() + && UpdateService.getClientSignatureData() != null))) { + this.buttonList.add(downloadOfflineButton = new GuiButton(15, this.width / 2 - 100, + parInt1 + parInt2 * 2, I18n.format("update.downloadOffline"))); + downloadOfflineButton.enabled = !UpdateService.shouldDisableDownloadButton(); + } + } + } + public void confirmClicked(boolean flag, int i) { if (flag && i == 12) { this.mc.gameSettings.hasCreatedDemoWorld = false; @@ -402,8 +277,16 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { } } - /**+ - * Draws the main menu panorama + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return false; + } + + /** + * + Draws the main menu panorama */ private void drawPanorama(int parInt1, int parInt2, float parFloat1) { Tessellator tessellator = Tessellator.getInstance(); @@ -490,79 +373,9 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { GlStateManager.enableDepth(); } - /**+ - * Rotate and blurs the skybox view in the main menu - */ - private void rotateAndBlurSkybox(float parFloat1) { - this.mc.getTextureManager().bindTexture(backgroundTexture); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - EaglercraftGPU.glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, 256, 256); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.colorMask(true, true, true, false); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - GlStateManager.disableAlpha(); - byte b0 = 3; - - for (int i = 0; i < b0; ++i) { - float f = 1.0F / (float) (i + 1); - int j = this.width; - int k = this.height; - float f1 = (float) (i - b0 / 2) / 256.0F; - worldrenderer.pos((double) j, (double) k, (double) this.zLevel).tex((double) (0.0F + f1), 1.0D) - .color(1.0F, 1.0F, 1.0F, f).endVertex(); - worldrenderer.pos((double) j, 0.0D, (double) this.zLevel).tex((double) (1.0F + f1), 1.0D) - .color(1.0F, 1.0F, 1.0F, f).endVertex(); - worldrenderer.pos(0.0D, 0.0D, (double) this.zLevel).tex((double) (1.0F + f1), 0.0D) - .color(1.0F, 1.0F, 1.0F, f).endVertex(); - worldrenderer.pos(0.0D, (double) k, (double) this.zLevel).tex((double) (0.0F + f1), 0.0D) - .color(1.0F, 1.0F, 1.0F, f).endVertex(); - } - - tessellator.draw(); - GlStateManager.enableAlpha(); - GlStateManager.colorMask(true, true, true, true); - } - - /**+ - * Renders the skybox in the main menu - */ - private void renderSkybox(int parInt1, int parInt2, float parFloat1) { - GlStateManager.viewport(0, 0, 256, 256); - this.drawPanorama(parInt1, parInt2, parFloat1); - this.rotateAndBlurSkybox(parFloat1); - this.rotateAndBlurSkybox(parFloat1); - this.rotateAndBlurSkybox(parFloat1); - this.rotateAndBlurSkybox(parFloat1); - this.rotateAndBlurSkybox(parFloat1); - this.rotateAndBlurSkybox(parFloat1); - this.rotateAndBlurSkybox(parFloat1); - GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); - float f = this.width > this.height ? 120.0F / (float) this.width : 120.0F / (float) this.height; - float f1 = (float) this.height * f / 256.0F; - float f2 = (float) this.width * f / 256.0F; - int i = this.width; - int j = this.height; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos(0.0D, (double) j, (double) this.zLevel).tex((double) (0.5F - f1), (double) (0.5F + f2)) - .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); - worldrenderer.pos((double) i, (double) j, (double) this.zLevel).tex((double) (0.5F - f1), (double) (0.5F - f2)) - .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); - worldrenderer.pos((double) i, 0.0D, (double) this.zLevel).tex((double) (0.5F + f1), (double) (0.5F - f2)) - .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); - worldrenderer.pos(0.0D, 0.0D, (double) this.zLevel).tex((double) (0.5F + f1), (double) (0.5F + f2)) - .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); - tessellator.draw(); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { GlStateManager.disableAlpha(); @@ -710,9 +523,74 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { super.drawScreen(i, j, f); } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + if (viewportTexture == null) { + viewportTexture = new DynamicTexture(256, 256); + backgroundTexture = this.mc.getTextureManager().getDynamicTextureLocation("background", viewportTexture); + } + this.updateCheckerOverlay.setResolution(mc, width, height); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(new Date()); + if (calendar.get(2) + 1 == 12 && calendar.get(5) == 24) { + this.splashText = "Merry X-mas!"; + } else if (calendar.get(2) + 1 == 1 && calendar.get(5) == 1) { + this.splashText = "Happy new year!"; + } else if (calendar.get(2) + 1 == 10 && calendar.get(5) == 31) { + this.splashText = "OOoooOOOoooo! Spooky!"; + } + + int i = this.height / 4 + 48; + + boolean isFork = !EaglercraftVersion.projectOriginAuthor.equalsIgnoreCase(EaglercraftVersion.projectForkVendor); + + if (isFork && EaglercraftVersion.mainMenuStringF != null && EaglercraftVersion.mainMenuStringF.length() > 0) { + i += 11; + } + + if (this.mc.isDemo()) { + this.addDemoButtons(i, 24); + } else { + this.addSingleplayerMultiplayerButtons(i, 24); + } + + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, i + 72 + 12, 98, 20, + I18n.format("menu.options", new Object[0]))); + this.buttonList.add(new GuiButton(4, this.width / 2 + 2, i + 72 + 12, 98, 20, + I18n.format("menu.editProfile", new Object[0]))); + + this.buttonList.add(new GuiButtonLanguage(5, this.width / 2 - 124, i + 72 + 12)); + + if (isFork) { + this.openGLWarning1 = EaglercraftVersion.mainMenuStringE; + this.openGLWarning2 = EaglercraftVersion.mainMenuStringF; + boolean line2 = this.openGLWarning2 != null && this.openGLWarning2.length() > 0; + this.field_92023_s = this.fontRendererObj.getStringWidth(this.openGLWarning1); + this.field_92024_r = this.fontRendererObj.getStringWidth(this.openGLWarning2); + int j = Math.max(this.field_92023_s, this.field_92024_r); + this.field_92022_t = (this.width - j) / 2; + this.field_92021_u = ((GuiButton) this.buttonList.get(0)).yPosition - (line2 ? 32 : 21); + this.field_92020_v = this.field_92022_t + j; + this.field_92019_w = this.field_92021_u + (line2 ? 24 : 11); + } + + this.mc.func_181537_a(false); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int par1, int par2, int par3) { if (par3 == 0) { @@ -731,4 +609,134 @@ public class GuiMainMenu extends GuiScreen implements GuiYesNoCallback { this.updateCheckerOverlay.mouseClicked(par1, par2, par3); super.mouseClicked(par1, par2, par3); } + + private void reloadResourceFlags() { + if (Minecraft.getMinecraft().isDemo()) { + this.isDefault = false; + } else { + if (!EagRuntime.getConfiguration().isEnableMinceraft()) { + this.isDefault = false; + } else { + try { + byte[] bytes = EaglerInputStream.inputStreamToBytesQuiet(Minecraft.getMinecraft() + .getResourceManager().getResource(minecraftTitleTextures).getInputStream()); + if (bytes != null && bytes.length == lendef) { + SHA1Digest sha1 = new SHA1Digest(); + byte[] sha1out = new byte[20]; + sha1.update(bytes, 0, bytes.length); + sha1.doFinal(sha1out, 0); + this.isDefault = Arrays.equals(sha1out, sha1def); + } else { + this.isDefault = false; + } + } catch (IOException e) { + this.isDefault = false; + } + } + } + + this.enableBlur = true; + + try { + byte[] bytes = EaglerInputStream.inputStreamToBytesQuiet( + Minecraft.getMinecraft().getResourceManager().getResource(minecraftTitleBlurFlag).getInputStream()); + if (bytes != null) { + String[] blurCfg = EagUtils.linesArray(new String(bytes, StandardCharsets.UTF_8)); + for (int i = 0; i < blurCfg.length; ++i) { + String s = blurCfg[i]; + if (s.startsWith("enable_blur=")) { + s = s.substring(12).trim(); + this.enableBlur = s.equals("1") || s.equals("true"); + break; + } + } + } + } catch (IOException e) { + ; + } + } + + /** + * + Renders the skybox in the main menu + */ + private void renderSkybox(int parInt1, int parInt2, float parFloat1) { + GlStateManager.viewport(0, 0, 256, 256); + this.drawPanorama(parInt1, parInt2, parFloat1); + this.rotateAndBlurSkybox(parFloat1); + this.rotateAndBlurSkybox(parFloat1); + this.rotateAndBlurSkybox(parFloat1); + this.rotateAndBlurSkybox(parFloat1); + this.rotateAndBlurSkybox(parFloat1); + this.rotateAndBlurSkybox(parFloat1); + this.rotateAndBlurSkybox(parFloat1); + GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); + float f = this.width > this.height ? 120.0F / (float) this.width : 120.0F / (float) this.height; + float f1 = (float) this.height * f / 256.0F; + float f2 = (float) this.width * f / 256.0F; + int i = this.width; + int j = this.height; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(0.0D, (double) j, (double) this.zLevel).tex((double) (0.5F - f1), (double) (0.5F + f2)) + .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); + worldrenderer.pos((double) i, (double) j, (double) this.zLevel).tex((double) (0.5F - f1), (double) (0.5F - f2)) + .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); + worldrenderer.pos((double) i, 0.0D, (double) this.zLevel).tex((double) (0.5F + f1), (double) (0.5F - f2)) + .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); + worldrenderer.pos(0.0D, 0.0D, (double) this.zLevel).tex((double) (0.5F + f1), (double) (0.5F + f2)) + .color(1.0F, 1.0F, 1.0F, 1.0F).endVertex(); + tessellator.draw(); + } + + /** + * + Rotate and blurs the skybox view in the main menu + */ + private void rotateAndBlurSkybox(float parFloat1) { + this.mc.getTextureManager().bindTexture(backgroundTexture); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + EaglercraftGPU.glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, 256, 256); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + GlStateManager.colorMask(true, true, true, false); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + GlStateManager.disableAlpha(); + byte b0 = 3; + + for (int i = 0; i < b0; ++i) { + float f = 1.0F / (float) (i + 1); + int j = this.width; + int k = this.height; + float f1 = (float) (i - b0 / 2) / 256.0F; + worldrenderer.pos((double) j, (double) k, (double) this.zLevel).tex((double) (0.0F + f1), 1.0D) + .color(1.0F, 1.0F, 1.0F, f).endVertex(); + worldrenderer.pos((double) j, 0.0D, (double) this.zLevel).tex((double) (1.0F + f1), 1.0D) + .color(1.0F, 1.0F, 1.0F, f).endVertex(); + worldrenderer.pos(0.0D, 0.0D, (double) this.zLevel).tex((double) (1.0F + f1), 0.0D) + .color(1.0F, 1.0F, 1.0F, f).endVertex(); + worldrenderer.pos(0.0D, (double) k, (double) this.zLevel).tex((double) (0.0F + f1), 0.0D) + .color(1.0F, 1.0F, 1.0F, f).endVertex(); + } + + tessellator.draw(); + GlStateManager.enableAlpha(); + GlStateManager.colorMask(true, true, true, true); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + ++this.panoramaTimer; + if (downloadOfflineButton != null) { + downloadOfflineButton.enabled = !UpdateService.shouldDisableDownloadButton(); + } + if (shouldReload) { + reloadResourceFlags(); + shouldReload = false; + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiMemoryErrorScreen.java b/src/game/java/net/minecraft/client/gui/GuiMemoryErrorScreen.java index 910fc54c..561fa578 100644 --- a/src/game/java/net/minecraft/client/gui/GuiMemoryErrorScreen.java +++ b/src/game/java/net/minecraft/client/gui/GuiMemoryErrorScreen.java @@ -2,43 +2,33 @@ package net.minecraft.client.gui; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiMemoryErrorScreen extends GuiScreen { - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiOptionButton(0, this.width / 2 - 155, this.height / 4 + 120 + 12, - I18n.format("gui.toTitle", new Object[0]))); - this.buttonList.add(new GuiOptionButton(1, this.width / 2 - 155 + 160, this.height / 4 + 120 + 12, - I18n.format("menu.quit", new Object[0]))); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.id == 0) { @@ -49,18 +39,9 @@ public class GuiMemoryErrorScreen extends GuiScreen { } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -84,4 +65,25 @@ public class GuiMemoryErrorScreen extends GuiScreen { this.width / 2 - 140, this.height / 4 - 60 + 60 + 81, 10526880); super.drawScreen(i, j, f); } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiOptionButton(0, this.width / 2 - 155, this.height / 4 + 120 + 12, + I18n.format("gui.toTitle", new Object[0]))); + this.buttonList.add(new GuiOptionButton(1, this.width / 2 - 155 + 160, this.height / 4 + 120 + 12, + I18n.format("menu.quit", new Object[0]))); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiMerchant.java b/src/game/java/net/minecraft/client/gui/GuiMerchant.java index b791ac09..48dad073 100644 --- a/src/game/java/net/minecraft/client/gui/GuiMerchant.java +++ b/src/game/java/net/minecraft/client/gui/GuiMerchant.java @@ -1,10 +1,10 @@ package net.minecraft.client.gui; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; @@ -22,30 +22,67 @@ import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiMerchant extends GuiContainer { + static class MerchantButton extends GuiButton { + private final boolean field_146157_o; + + public MerchantButton(int buttonID, int x, int y, boolean parFlag) { + super(buttonID, x, y, 12, 19, ""); + this.field_146157_o = parFlag; + } + + public void drawButton(Minecraft minecraft, int i, int j) { + if (this.visible) { + minecraft.getTextureManager().bindTexture(GuiMerchant.MERCHANT_GUI_TEXTURE); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + boolean flag = i >= this.xPosition && j >= this.yPosition && i < this.xPosition + this.width + && j < this.yPosition + this.height; + if (flag && this.enabled) { + Mouse.showCursor(EnumCursorType.HAND); + } + int k = 0; + int l = 176; + if (!this.enabled) { + l += this.width * 2; + } else if (flag) { + l += this.width; + } + + if (!this.field_146157_o) { + k += this.height; + } + + this.drawTexturedModalRect(this.xPosition, this.yPosition, l, k, this.width, this.height); + } + } + } + private static final Logger logger = LogManager.getLogger(); - /**+ - * The GUI texture for the villager merchant GUI. + /** + * + The GUI texture for the villager merchant GUI. */ private static final ResourceLocation MERCHANT_GUI_TEXTURE = new ResourceLocation( "textures/gui/container/villager.png"); @@ -53,6 +90,7 @@ public class GuiMerchant extends GuiContainer { private GuiMerchant.MerchantButton nextButton; private GuiMerchant.MerchantButton previousButton; private int selectedMerchantRecipe; + private IChatComponent chatComponent; public GuiMerchant(InventoryPlayer parInventoryPlayer, IMerchant parIMerchant, World worldIn) { @@ -61,48 +99,9 @@ public class GuiMerchant extends GuiContainer { this.chatComponent = parIMerchant.getDisplayName(); } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - super.initGui(); - int i = (this.width - this.xSize) / 2; - int j = (this.height - this.ySize) / 2; - this.buttonList.add(this.nextButton = new GuiMerchant.MerchantButton(1, i + 120 + 27, j + 24 - 1, true)); - this.buttonList.add(this.previousButton = new GuiMerchant.MerchantButton(2, i + 36 - 19, j + 24 - 1, false)); - this.nextButton.enabled = false; - this.previousButton.enabled = false; - } - - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - String s = this.chatComponent.getUnformattedText(); - this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); - this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, - 4210752); - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - super.updateScreen(); - MerchantRecipeList merchantrecipelist = this.merchant.getRecipes(this.mc.thePlayer); - if (merchantrecipelist != null) { - this.nextButton.enabled = this.selectedMerchantRecipe < merchantrecipelist.size() - 1; - this.previousButton.enabled = this.selectedMerchantRecipe > 0; - } - - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { boolean flag = false; @@ -132,8 +131,8 @@ public class GuiMerchant extends GuiContainer { } - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -160,9 +159,20 @@ public class GuiMerchant extends GuiContainer { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + String s = this.chatComponent.getUnformattedText(); + this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); + this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, + 4210752); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { super.drawScreen(i, j, f); @@ -216,37 +226,31 @@ public class GuiMerchant extends GuiContainer { return this.merchant; } - static class MerchantButton extends GuiButton { - private final boolean field_146157_o; + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + super.initGui(); + int i = (this.width - this.xSize) / 2; + int j = (this.height - this.ySize) / 2; + this.buttonList.add(this.nextButton = new GuiMerchant.MerchantButton(1, i + 120 + 27, j + 24 - 1, true)); + this.buttonList.add(this.previousButton = new GuiMerchant.MerchantButton(2, i + 36 - 19, j + 24 - 1, false)); + this.nextButton.enabled = false; + this.previousButton.enabled = false; + } - public MerchantButton(int buttonID, int x, int y, boolean parFlag) { - super(buttonID, x, y, 12, 19, ""); - this.field_146157_o = parFlag; + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + super.updateScreen(); + MerchantRecipeList merchantrecipelist = this.merchant.getRecipes(this.mc.thePlayer); + if (merchantrecipelist != null) { + this.nextButton.enabled = this.selectedMerchantRecipe < merchantrecipelist.size() - 1; + this.previousButton.enabled = this.selectedMerchantRecipe > 0; } - public void drawButton(Minecraft minecraft, int i, int j) { - if (this.visible) { - minecraft.getTextureManager().bindTexture(GuiMerchant.MERCHANT_GUI_TEXTURE); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - boolean flag = i >= this.xPosition && j >= this.yPosition && i < this.xPosition + this.width - && j < this.yPosition + this.height; - if (flag && this.enabled) { - Mouse.showCursor(EnumCursorType.HAND); - } - int k = 0; - int l = 176; - if (!this.enabled) { - l += this.width * 2; - } else if (flag) { - l += this.width; - } - - if (!this.field_146157_o) { - k += this.height; - } - - this.drawTexturedModalRect(this.xPosition, this.yPosition, l, k, this.width, this.height); - } - } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiMultiplayer.java b/src/game/java/net/minecraft/client/gui/GuiMultiplayer.java index a5abcecd..39c273d3 100644 --- a/src/game/java/net/minecraft/client/gui/GuiMultiplayer.java +++ b/src/game/java/net/minecraft/client/gui/GuiMultiplayer.java @@ -27,28 +27,38 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { private static final Logger logger = LogManager.getLogger(); + private static long lastRefreshCommit = 0l; + private static LANServerList lanServerList = null; + + static LANServerList getLanServerList() { + return lanServerList; + } + private GuiScreen parentScreen; private ServerSelectionList serverListSelector; private ServerList savedServerList; @@ -57,19 +67,14 @@ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { private GuiButton btnDeleteServer; private boolean deletingServer; private boolean addingServer; + private boolean editingServer; + private boolean directConnect; private String hoveringText; - - public ServerData getSelectedServer() { - return selectedServer; - } - private ServerData selectedServer; - private boolean initialized; - private static long lastRefreshCommit = 0l; - private static LANServerList lanServerList = null; + private boolean initialized; public int ticksOpened; @@ -83,87 +88,9 @@ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { } } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - if (!this.initialized) { - this.initialized = true; - this.savedServerList = ServerList.getServerList(); - this.savedServerList.loadServerList(); - this.serverListSelector = new ServerSelectionList(this, this.mc, this.width, this.height, 32, - this.height - 64, 36); - this.serverListSelector.func_148195_a(this.savedServerList); - if (lanServerList == null) { - lanServerList = new LANServerList(); - } else { - lanServerList.forceRefresh(); - } - } else { - this.serverListSelector.setDimensions(this.width, this.height, 32, this.height - 64); - } - - this.createButtons(); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.serverListSelector.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.serverListSelector.handleTouchInput(); - } - - public void createButtons() { - this.buttonList.add(this.btnEditServer = new GuiButton(7, this.width / 2 - 154, this.height - 28, 70, 20, - I18n.format("selectServer.edit", new Object[0]))); - this.buttonList.add(this.btnDeleteServer = new GuiButton(2, this.width / 2 - 74, this.height - 28, 70, 20, - I18n.format("selectServer.delete", new Object[0]))); - this.buttonList.add(this.btnSelectServer = new GuiButton(1, this.width / 2 - 154, this.height - 52, 100, 20, - I18n.format("selectServer.select", new Object[0]))); - this.buttonList.add(new GuiButton(4, this.width / 2 - 50, this.height - 52, 100, 20, - I18n.format("selectServer.direct", new Object[0]))); - this.buttonList.add(new GuiButton(3, this.width / 2 + 4 + 50, this.height - 52, 100, 20, - I18n.format("selectServer.add", new Object[0]))); - this.buttonList.add(new GuiButton(8, this.width / 2 + 4, this.height - 28, 70, 20, - I18n.format("selectServer.refresh", new Object[0]))); - this.buttonList.add(new GuiButton(0, this.width / 2 + 4 + 76, this.height - 28, 75, 20, - I18n.format("gui.cancel", new Object[0]))); - this.selectServer(this.serverListSelector.func_148193_k()); - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - super.updateScreen(); - this.savedServerList.updateServerPing(); - if (lanServerList.update()) { - this.selectServer(-1); - } - ++ticksOpened; - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -213,8 +140,8 @@ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { } } - public void refreshServerList() { - this.mc.displayGuiScreen(new GuiMultiplayer(this.parentScreen)); + public void cancelDirectConnect() { + this.directConnect = false; } public void confirmClicked(boolean flag, int var2) { @@ -277,15 +204,169 @@ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { } } - public void cancelDirectConnect() { - this.directConnect = false; + private void connectToLAN(String text, String code, RelayServer uri) { + this.mc.loadingScreen.resetProgressAndMessage(text); + this.mc.displayGuiScreen(new GuiScreenLANConnecting(this, code, uri)); } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + public void connectToSelected() { + if (this.serverListSelector.func_148193_k() < this.serverListSelector.getOrigSize()) { + GuiListExtended.IGuiListEntry guilistextended$iguilistentry = this.serverListSelector.func_148193_k() < 0 + ? null + : this.serverListSelector.getListEntry(this.serverListSelector.func_148193_k()); + if (guilistextended$iguilistentry instanceof ServerListEntryNormal) { + this.connectToServer(((ServerListEntryNormal) guilistextended$iguilistentry).getServerData()); + } + } else { + int par1 = this.serverListSelector.func_148193_k() - this.serverListSelector.getOrigSize(); + + if (par1 < lanServerList.countServers()) { + LANServerList.LanServer var2 = lanServerList.getServer(par1); + connectToLAN("Connecting to '" + var2.getLanServerMotd() + "'...", var2.getLanServerCode(), + var2.getLanServerRelay()); + } + } + } + + private void connectToServer(ServerData server) { + this.mc.displayGuiScreen(new GuiConnecting(this, this.mc, server)); + } + + public void createButtons() { + this.buttonList.add(this.btnEditServer = new GuiButton(7, this.width / 2 - 154, this.height - 28, 70, 20, + I18n.format("selectServer.edit", new Object[0]))); + this.buttonList.add(this.btnDeleteServer = new GuiButton(2, this.width / 2 - 74, this.height - 28, 70, 20, + I18n.format("selectServer.delete", new Object[0]))); + this.buttonList.add(this.btnSelectServer = new GuiButton(1, this.width / 2 - 154, this.height - 52, 100, 20, + I18n.format("selectServer.select", new Object[0]))); + this.buttonList.add(new GuiButton(4, this.width / 2 - 50, this.height - 52, 100, 20, + I18n.format("selectServer.direct", new Object[0]))); + this.buttonList.add(new GuiButton(3, this.width / 2 + 4 + 50, this.height - 52, 100, 20, + I18n.format("selectServer.add", new Object[0]))); + this.buttonList.add(new GuiButton(8, this.width / 2 + 4, this.height - 28, 70, 20, + I18n.format("selectServer.refresh", new Object[0]))); + this.buttonList.add(new GuiButton(0, this.width / 2 + 4 + 76, this.height - 28, 75, 20, + I18n.format("gui.cancel", new Object[0]))); + this.selectServer(this.serverListSelector.func_148193_k()); + } + + private void drawPluginDownloadLink(int xx, int yy) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + String text = EaglerXBungeeVersion.getPluginButton(); + int w = mc.fontRendererObj.getStringWidth(text); + boolean hover = xx > width - 5 - (w + 5) * 3 / 4 && yy > 1 && xx < width - 2 && yy < 12; + if (hover) { + Mouse.showCursor(EnumCursorType.HAND); + } + + drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, (width - 1) * 4 / 3 - w - 5, 5, + hover ? 0xFFEEEE22 : 0xFFCCCCCC); + + GlStateManager.popMatrix(); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.hoveringText = null; + this.drawDefaultBackground(); + this.serverListSelector.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.title", new Object[0]), this.width / 2, + 20, 16777215); + super.drawScreen(i, j, f); + relaysButton.drawScreen(i, j); + drawPluginDownloadLink(i, j); + if (this.hoveringText != null) { + this.drawHoveringText(Lists.newArrayList(Splitter.on("\n").split(this.hoveringText)), i, j); + GlStateManager.disableLighting(); + } + } + + public void func_175391_a(ServerListEntryNormal parServerListEntryNormal, int parInt1, boolean parFlag) { + int i = parFlag ? 0 : parInt1 - 1; + this.savedServerList.swapServers(parInt1, i); + if (this.serverListSelector.func_148193_k() == parInt1) { + this.selectServer(i); + } + + this.serverListSelector.func_148195_a(this.savedServerList); + } + + public boolean func_175392_a(ServerListEntryNormal parServerListEntryNormal, int parInt1) { + return parInt1 > 0; + } + + public void func_175393_b(ServerListEntryNormal parServerListEntryNormal, int parInt1, boolean parFlag) { + int i = parFlag ? this.savedServerList.countServers() - 1 : parInt1 + 1; + this.savedServerList.swapServers(parInt1, i); + if (this.serverListSelector.func_148193_k() == parInt1) { + this.selectServer(i); + } + + this.serverListSelector.func_148195_a(this.savedServerList); + } + + public boolean func_175394_b(ServerListEntryNormal parServerListEntryNormal, int parInt1) { + return parInt1 < this.savedServerList.countServers(); + } + + public ServerData getSelectedServer() { + return selectedServer; + } + + public ServerList getServerList() { + return this.savedServerList; + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.serverListSelector.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.serverListSelector.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + if (!this.initialized) { + this.initialized = true; + this.savedServerList = ServerList.getServerList(); + this.savedServerList.loadServerList(); + this.serverListSelector = new ServerSelectionList(this, this.mc, this.width, this.height, 32, + this.height - 64, 36); + this.serverListSelector.func_148195_a(this.savedServerList); + if (lanServerList == null) { + lanServerList = new LANServerList(); + } else { + lanServerList.forceRefresh(); + } + } else { + this.serverListSelector.setDimensions(this.width, this.height, 32, this.height - 64); + } + + this.createButtons(); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { int i = this.serverListSelector.func_148193_k(); @@ -335,69 +416,40 @@ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { } } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ - public void drawScreen(int i, int j, float f) { - this.hoveringText = null; - this.drawDefaultBackground(); - this.serverListSelector.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.title", new Object[0]), this.width / 2, - 20, 16777215); - super.drawScreen(i, j, f); - relaysButton.drawScreen(i, j); - drawPluginDownloadLink(i, j); - if (this.hoveringText != null) { - this.drawHoveringText(Lists.newArrayList(Splitter.on("\n").split(this.hoveringText)), i, j); - GlStateManager.disableLighting(); - } - } - - private void drawPluginDownloadLink(int xx, int yy) { - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + relaysButton.mouseClicked(parInt1, parInt2, parInt3); + super.mouseClicked(parInt1, parInt2, parInt3); + this.serverListSelector.mouseClicked(parInt1, parInt2, parInt3); String text = EaglerXBungeeVersion.getPluginButton(); int w = mc.fontRendererObj.getStringWidth(text); - boolean hover = xx > width - 5 - (w + 5) * 3 / 4 && yy > 1 && xx < width - 2 && yy < 12; - if (hover) { - Mouse.showCursor(EnumCursorType.HAND); - } - - drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, (width - 1) * 4 / 3 - w - 5, 5, - hover ? 0xFFEEEE22 : 0xFFCCCCCC); - - GlStateManager.popMatrix(); - } - - public void connectToSelected() { - if (this.serverListSelector.func_148193_k() < this.serverListSelector.getOrigSize()) { - GuiListExtended.IGuiListEntry guilistextended$iguilistentry = this.serverListSelector.func_148193_k() < 0 - ? null - : this.serverListSelector.getListEntry(this.serverListSelector.func_148193_k()); - if (guilistextended$iguilistentry instanceof ServerListEntryNormal) { - this.connectToServer(((ServerListEntryNormal) guilistextended$iguilistentry).getServerData()); - } - } else { - int par1 = this.serverListSelector.func_148193_k() - this.serverListSelector.getOrigSize(); - - if (par1 < lanServerList.countServers()) { - LANServerList.LanServer var2 = lanServerList.getServer(par1); - connectToLAN("Connecting to '" + var2.getLanServerMotd() + "'...", var2.getLanServerCode(), - var2.getLanServerRelay()); - } + if (parInt1 > width - 5 - (w + 5) * 3 / 4 && parInt2 > 1 && parInt1 < width - 2 && parInt2 < 12) { + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + EaglerXBungeeVersion.startPluginDownload(); } } - private void connectToServer(ServerData server) { - this.mc.displayGuiScreen(new GuiConnecting(this, this.mc, server)); + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton + */ + protected void mouseReleased(int i, int j, int k) { + super.mouseReleased(i, j, k); + this.serverListSelector.mouseReleased(i, j, k); } - private void connectToLAN(String text, String code, RelayServer uri) { - this.mc.loadingScreen.resetProgressAndMessage(text); - this.mc.displayGuiScreen(new GuiScreenLANConnecting(this, code, uri)); + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + + public void refreshServerList() { + this.mc.displayGuiScreen(new GuiMultiplayer(this.parentScreen)); } public void selectServer(int index) { @@ -421,65 +473,15 @@ public class GuiMultiplayer extends GuiScreen implements GuiYesNoCallback { this.hoveringText = parString1; } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Called from the main game loop to update the screen. */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - relaysButton.mouseClicked(parInt1, parInt2, parInt3); - super.mouseClicked(parInt1, parInt2, parInt3); - this.serverListSelector.mouseClicked(parInt1, parInt2, parInt3); - String text = EaglerXBungeeVersion.getPluginButton(); - int w = mc.fontRendererObj.getStringWidth(text); - if (parInt1 > width - 5 - (w + 5) * 3 / 4 && parInt2 > 1 && parInt1 < width - 2 && parInt2 < 12) { - this.mc.getSoundHandler() - .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - EaglerXBungeeVersion.startPluginDownload(); + public void updateScreen() { + super.updateScreen(); + this.savedServerList.updateServerPing(); + if (lanServerList.update()) { + this.selectServer(-1); } - } - - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton - */ - protected void mouseReleased(int i, int j, int k) { - super.mouseReleased(i, j, k); - this.serverListSelector.mouseReleased(i, j, k); - } - - public ServerList getServerList() { - return this.savedServerList; - } - - static LANServerList getLanServerList() { - return lanServerList; - } - - public boolean func_175392_a(ServerListEntryNormal parServerListEntryNormal, int parInt1) { - return parInt1 > 0; - } - - public boolean func_175394_b(ServerListEntryNormal parServerListEntryNormal, int parInt1) { - return parInt1 < this.savedServerList.countServers(); - } - - public void func_175391_a(ServerListEntryNormal parServerListEntryNormal, int parInt1, boolean parFlag) { - int i = parFlag ? 0 : parInt1 - 1; - this.savedServerList.swapServers(parInt1, i); - if (this.serverListSelector.func_148193_k() == parInt1) { - this.selectServer(i); - } - - this.serverListSelector.func_148195_a(this.savedServerList); - } - - public void func_175393_b(ServerListEntryNormal parServerListEntryNormal, int parInt1, boolean parFlag) { - int i = parFlag ? this.savedServerList.countServers() - 1 : parInt1 + 1; - this.savedServerList.swapServers(parInt1, i); - if (this.serverListSelector.func_148193_k() == parInt1) { - this.selectServer(i); - } - - this.serverListSelector.func_148195_a(this.savedServerList); + ++ticksOpened; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiNewChat.java b/src/game/java/net/minecraft/client/gui/GuiNewChat.java index b89f363e..f71e6a06 100644 --- a/src/game/java/net/minecraft/client/gui/GuiNewChat.java +++ b/src/game/java/net/minecraft/client/gui/GuiNewChat.java @@ -14,45 +14,109 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiNewChat extends Gui { private static final Logger logger = LogManager.getLogger(); + + public static int calculateChatboxHeight(float parFloat1) { + short short1 = 180; + byte b0 = 20; + return MathHelper.floor_float(parFloat1 * (float) (short1 - b0) + (float) b0); + } + + public static int calculateChatboxWidth(float parFloat1) { + short short1 = 320; + byte b0 = 40; + return MathHelper.floor_float(parFloat1 * (float) (short1 - b0) + (float) b0); + } + private final Minecraft mc; - /**+ - * A list of messages previously sent through the chat GUI + /** + * + A list of messages previously sent through the chat GUI */ private final List sentMessages = Lists.newArrayList(); - /**+ - * Chat lines to be displayed in the chat box + /** + * + Chat lines to be displayed in the chat box */ private final List chatLines = Lists.newArrayList(); private final List field_146253_i = Lists.newArrayList(); + private int scrollPos; + private boolean isScrolled; public GuiNewChat(Minecraft mcIn) { this.mc = mcIn; } + /** + * + Adds this string to the list of sent messages, for recall using the up/down + * arrow keys + */ + public void addToSentMessages(String parString1) { + if (this.sentMessages.isEmpty() + || !((String) this.sentMessages.get(this.sentMessages.size() - 1)).equals(parString1)) { + this.sentMessages.add(parString1); + } + + } + + /** + * + Clears the chat. + */ + public void clearChatMessages() { + this.field_146253_i.clear(); + this.chatLines.clear(); + this.sentMessages.clear(); + } + + /** + * + finds and deletes a Chat line by ID + */ + public void deleteChatLine(int parInt1) { + Iterator iterator = this.field_146253_i.iterator(); + + while (iterator.hasNext()) { + ChatLine chatline = (ChatLine) iterator.next(); + if (chatline.getChatLineID() == parInt1) { + iterator.remove(); + } + } + + iterator = this.chatLines.iterator(); + + while (iterator.hasNext()) { + ChatLine chatline1 = (ChatLine) iterator.next(); + if (chatline1.getChatLineID() == parInt1) { + iterator.remove(); + break; + } + } + + } + public void drawChat(int parInt1) { if (this.mc.gameSettings.chatVisibility != EntityPlayer.EnumChatVisibility.HIDDEN) { int i = this.getLineCount(); @@ -123,119 +187,8 @@ public class GuiNewChat extends Gui { } } - /**+ - * Clears the chat. - */ - public void clearChatMessages() { - this.field_146253_i.clear(); - this.chatLines.clear(); - this.sentMessages.clear(); - } - - public void printChatMessage(IChatComponent parIChatComponent) { - this.printChatMessageWithOptionalDeletion(parIChatComponent, 0); - } - - /**+ - * prints the ChatComponent to Chat. If the ID is not 0, deletes - * an existing Chat Line of that ID from the GUI - */ - public void printChatMessageWithOptionalDeletion(IChatComponent parIChatComponent, int parInt1) { - this.setChatLine(parIChatComponent, parInt1, this.mc.ingameGUI.getUpdateCounter(), false); - logger.info("[CHAT] " + parIChatComponent.getUnformattedText()); - } - - private void setChatLine(IChatComponent parIChatComponent, int parInt1, int parInt2, boolean parFlag) { - if (parInt1 != 0) { - this.deleteChatLine(parInt1); - } - - int i = MathHelper.floor_float((float) this.getChatWidth() / this.getChatScale()); - List list = GuiUtilRenderComponents.func_178908_a(parIChatComponent, i, this.mc.fontRendererObj, false, false); - boolean flag = this.getChatOpen(); - - for (int j = 0, l = list.size(); j < l; ++j) { - if (flag && this.scrollPos > 0) { - this.isScrolled = true; - this.scroll(1); - } - - this.field_146253_i.add(0, new ChatLine(parInt2, (IChatComponent) list.get(j), parInt1)); - } - - while (this.field_146253_i.size() > 100) { - this.field_146253_i.remove(this.field_146253_i.size() - 1); - } - - if (!parFlag) { - this.chatLines.add(0, new ChatLine(parInt2, parIChatComponent, parInt1)); - - while (this.chatLines.size() > 100) { - this.chatLines.remove(this.chatLines.size() - 1); - } - } - - } - - public void refreshChat() { - this.field_146253_i.clear(); - this.resetScroll(); - - for (int i = this.chatLines.size() - 1; i >= 0; --i) { - ChatLine chatline = (ChatLine) this.chatLines.get(i); - this.setChatLine(chatline.getChatComponent(), chatline.getChatLineID(), chatline.getUpdatedCounter(), true); - } - - } - - /**+ - * Gets the list of messages previously sent through the chat - * GUI - */ - public List getSentMessages() { - return this.sentMessages; - } - - /**+ - * Adds this string to the list of sent messages, for recall - * using the up/down arrow keys - */ - public void addToSentMessages(String parString1) { - if (this.sentMessages.isEmpty() - || !((String) this.sentMessages.get(this.sentMessages.size() - 1)).equals(parString1)) { - this.sentMessages.add(parString1); - } - - } - - /**+ - * Resets the chat scroll (executed when the GUI is closed, - * among others) - */ - public void resetScroll() { - this.scrollPos = 0; - this.isScrolled = false; - } - - /**+ - * Scrolls the chat by the given number of lines. - */ - public void scroll(int parInt1) { - this.scrollPos += parInt1; - int i = this.field_146253_i.size(); - if (this.scrollPos > i - this.getLineCount()) { - this.scrollPos = i - this.getLineCount(); - } - - if (this.scrollPos <= 0) { - this.scrollPos = 0; - this.isScrolled = false; - } - - } - - /**+ - * Gets the chat component under the mouse + /** + * + Gets the chat component under the mouse */ public IChatComponent getChatComponent(int parInt1, int parInt2) { if (!this.getChatOpen()) { @@ -278,67 +231,118 @@ public class GuiNewChat extends Gui { } } - /**+ - * Returns true if the chat GUI is open + public int getChatHeight() { + return calculateChatboxHeight( + this.getChatOpen() ? this.mc.gameSettings.chatHeightFocused : this.mc.gameSettings.chatHeightUnfocused); + } + + /** + * + Returns true if the chat GUI is open */ public boolean getChatOpen() { return this.mc.currentScreen instanceof GuiChat; } - /**+ - * finds and deletes a Chat line by ID + /** + * + Returns the chatscale from mc.gameSettings.chatScale */ - public void deleteChatLine(int parInt1) { - Iterator iterator = this.field_146253_i.iterator(); - - while (iterator.hasNext()) { - ChatLine chatline = (ChatLine) iterator.next(); - if (chatline.getChatLineID() == parInt1) { - iterator.remove(); - } - } - - iterator = this.chatLines.iterator(); - - while (iterator.hasNext()) { - ChatLine chatline1 = (ChatLine) iterator.next(); - if (chatline1.getChatLineID() == parInt1) { - iterator.remove(); - break; - } - } - + public float getChatScale() { + return this.mc.gameSettings.chatScale; } public int getChatWidth() { return calculateChatboxWidth(this.mc.gameSettings.chatWidth); } - public int getChatHeight() { - return calculateChatboxHeight( - this.getChatOpen() ? this.mc.gameSettings.chatHeightFocused : this.mc.gameSettings.chatHeightUnfocused); - } - - /**+ - * Returns the chatscale from mc.gameSettings.chatScale - */ - public float getChatScale() { - return this.mc.gameSettings.chatScale; - } - - public static int calculateChatboxWidth(float parFloat1) { - short short1 = 320; - byte b0 = 40; - return MathHelper.floor_float(parFloat1 * (float) (short1 - b0) + (float) b0); - } - - public static int calculateChatboxHeight(float parFloat1) { - short short1 = 180; - byte b0 = 20; - return MathHelper.floor_float(parFloat1 * (float) (short1 - b0) + (float) b0); - } - public int getLineCount() { return this.getChatHeight() / 9; } + + /** + * + Gets the list of messages previously sent through the chat GUI + */ + public List getSentMessages() { + return this.sentMessages; + } + + public void printChatMessage(IChatComponent parIChatComponent) { + this.printChatMessageWithOptionalDeletion(parIChatComponent, 0); + } + + /** + * + prints the ChatComponent to Chat. If the ID is not 0, deletes an existing + * Chat Line of that ID from the GUI + */ + public void printChatMessageWithOptionalDeletion(IChatComponent parIChatComponent, int parInt1) { + this.setChatLine(parIChatComponent, parInt1, this.mc.ingameGUI.getUpdateCounter(), false); + logger.info("[CHAT] " + parIChatComponent.getUnformattedText()); + } + + public void refreshChat() { + this.field_146253_i.clear(); + this.resetScroll(); + + for (int i = this.chatLines.size() - 1; i >= 0; --i) { + ChatLine chatline = (ChatLine) this.chatLines.get(i); + this.setChatLine(chatline.getChatComponent(), chatline.getChatLineID(), chatline.getUpdatedCounter(), true); + } + + } + + /** + * + Resets the chat scroll (executed when the GUI is closed, among others) + */ + public void resetScroll() { + this.scrollPos = 0; + this.isScrolled = false; + } + + /** + * + Scrolls the chat by the given number of lines. + */ + public void scroll(int parInt1) { + this.scrollPos += parInt1; + int i = this.field_146253_i.size(); + if (this.scrollPos > i - this.getLineCount()) { + this.scrollPos = i - this.getLineCount(); + } + + if (this.scrollPos <= 0) { + this.scrollPos = 0; + this.isScrolled = false; + } + + } + + private void setChatLine(IChatComponent parIChatComponent, int parInt1, int parInt2, boolean parFlag) { + if (parInt1 != 0) { + this.deleteChatLine(parInt1); + } + + int i = MathHelper.floor_float((float) this.getChatWidth() / this.getChatScale()); + List list = GuiUtilRenderComponents.func_178908_a(parIChatComponent, i, this.mc.fontRendererObj, false, false); + boolean flag = this.getChatOpen(); + + for (int j = 0, l = list.size(); j < l; ++j) { + if (flag && this.scrollPos > 0) { + this.isScrolled = true; + this.scroll(1); + } + + this.field_146253_i.add(0, new ChatLine(parInt2, (IChatComponent) list.get(j), parInt1)); + } + + while (this.field_146253_i.size() > 100) { + this.field_146253_i.remove(this.field_146253_i.size() - 1); + } + + if (!parFlag) { + this.chatLines.add(0, new ChatLine(parInt2, parIChatComponent, parInt1)); + + while (this.chatLines.size() > 100) { + this.chatLines.remove(this.chatLines.size() - 1); + } + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiOptionButton.java b/src/game/java/net/minecraft/client/gui/GuiOptionButton.java index 50247af2..cab10e8a 100644 --- a/src/game/java/net/minecraft/client/gui/GuiOptionButton.java +++ b/src/game/java/net/minecraft/client/gui/GuiOptionButton.java @@ -2,22 +2,25 @@ package net.minecraft.client.gui; import net.minecraft.client.settings.GameSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,8 +28,9 @@ import net.minecraft.client.settings.GameSettings; public class GuiOptionButton extends GuiButton { private final GameSettings.Options enumOptions; - public GuiOptionButton(int parInt1, int parInt2, int parInt3, String parString1) { - this(parInt1, parInt2, parInt3, (GameSettings.Options) null, parString1); + public GuiOptionButton(int parInt1, int parInt2, int parInt3, GameSettings.Options parOptions, String parString1) { + super(parInt1, parInt2, parInt3, 150, 20, parString1); + this.enumOptions = parOptions; } public GuiOptionButton(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, String parString1) { @@ -34,9 +38,8 @@ public class GuiOptionButton extends GuiButton { this.enumOptions = null; } - public GuiOptionButton(int parInt1, int parInt2, int parInt3, GameSettings.Options parOptions, String parString1) { - super(parInt1, parInt2, parInt3, 150, 20, parString1); - this.enumOptions = parOptions; + public GuiOptionButton(int parInt1, int parInt2, int parInt3, String parString1) { + this(parInt1, parInt2, parInt3, (GameSettings.Options) null, parString1); } public GameSettings.Options returnEnumOptions() { diff --git a/src/game/java/net/minecraft/client/gui/GuiOptionSlider.java b/src/game/java/net/minecraft/client/gui/GuiOptionSlider.java index 5deb0f1a..aa565402 100644 --- a/src/game/java/net/minecraft/client/gui/GuiOptionSlider.java +++ b/src/game/java/net/minecraft/client/gui/GuiOptionSlider.java @@ -5,22 +5,25 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.settings.GameSettings; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,17 +55,20 @@ public class GuiOptionSlider extends GuiButton { return options; } - /**+ - * Returns 0 if the button is disabled, 1 if the mouse is NOT - * hovering over this button and 2 if it IS hovering over this - * button. + /** + * + Returns 0 if the button is disabled, 1 if the mouse is NOT hovering over + * this button and 2 if it IS hovering over this button. */ protected int getHoverState(boolean var1) { return 0; } - /**+ - * Fired when the mouse button is dragged. Equivalent of + public boolean isSliderTouchEvents() { + return true; + } + + /** + * + Fired when the mouse button is dragged. Equivalent of * MouseListener.mouseDragged(MouseEvent e). */ protected void mouseDragged(Minecraft minecraft, int i, int var3) { @@ -85,9 +91,9 @@ public class GuiOptionSlider extends GuiButton { } } - /**+ - * Returns true if the mouse has been pressed on this control. - * Equivalent of MouseListener.mousePressed(MouseEvent e). + /** + * + Returns true if the mouse has been pressed on this control. Equivalent of + * MouseListener.mousePressed(MouseEvent e). */ public boolean mousePressed(Minecraft minecraft, int i, int j) { if (super.mousePressed(minecraft, i, j)) { @@ -102,15 +108,11 @@ public class GuiOptionSlider extends GuiButton { } } - /**+ - * Fired when the mouse button is released. Equivalent of + /** + * + Fired when the mouse button is released. Equivalent of * MouseListener.mouseReleased(MouseEvent e). */ public void mouseReleased(int var1, int var2) { this.dragging = false; } - - public boolean isSliderTouchEvents() { - return true; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiOptions.java b/src/game/java/net/minecraft/client/gui/GuiOptions.java index b25d3fb2..90758d7c 100644 --- a/src/game/java/net/minecraft/client/gui/GuiOptions.java +++ b/src/game/java/net/minecraft/client/gui/GuiOptions.java @@ -28,22 +28,25 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import net.minecraft.world.EnumDifficulty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -63,10 +66,182 @@ public class GuiOptions extends GuiScreen implements GuiYesNoCallback { this.game_settings_1 = parGameSettings; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id < 100 && parGuiButton instanceof GuiOptionButton) { + GameSettings.Options gamesettings$options = ((GuiOptionButton) parGuiButton).returnEnumOptions(); + this.game_settings_1.setOptionValue(gamesettings$options, 1); + parGuiButton.displayString = this.game_settings_1 + .getKeyBinding(GameSettings.Options.getEnumOptions(parGuiButton.id)); + } + + if (parGuiButton.id == 108) { + this.mc.theWorld.getWorldInfo().setDifficulty( + EnumDifficulty.getDifficultyEnum(this.mc.theWorld.getDifficulty().getDifficultyId() + 1)); + SingleplayerServerController + .setDifficulty(this.mc.theWorld.getWorldInfo().getDifficulty().getDifficultyId()); + this.field_175357_i.displayString = this.func_175355_a(this.mc.theWorld.getDifficulty()); + } + + if (parGuiButton.id == 109) { + this.mc.displayGuiScreen( + new GuiYesNo(this, + (new ChatComponentTranslation("difficulty.lock.title", new Object[0])) + .getFormattedText(), + (new ChatComponentTranslation("difficulty.lock.question", + new Object[] { new ChatComponentTranslation(this.mc.theWorld.getWorldInfo() + .getDifficulty().getDifficultyResourceKey(), new Object[0]) })) + .getFormattedText(), + 109)); + } + + if (parGuiButton.id == 110) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new GuiCustomizeSkin(this)); + } + + if (parGuiButton.id == 8675309) { + if (EaglerDeferredPipeline.isSupported()) { + this.mc.displayGuiScreen(new GuiShaderConfig(this)); + } else { + this.mc.displayGuiScreen(new GuiShadersNotSupported(this, + I18n.format(EaglerDeferredPipeline.getReasonUnsupported()))); + } + } + + if (parGuiButton.id == 101) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new GuiVideoSettings(this, this.game_settings_1)); + } + + if (parGuiButton.id == 100) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new GuiControls(this, this.game_settings_1)); + } + + if (parGuiButton.id == 102) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new GuiLanguage(this, this.game_settings_1, this.mc.getLanguageManager())); + } + + if (parGuiButton.id == 103) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new ScreenChatOptions(this, this.game_settings_1)); + } + + if (parGuiButton.id == 200) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(this.field_146441_g); + } + + if (parGuiButton.id == 105) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new GuiScreenResourcePacks(this)); + } + + if (parGuiButton.id == 106) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(new GuiScreenOptionsSounds(this, this.game_settings_1)); + } + + if (parGuiButton.id == 107) { + if (ScreenRecordingController.isSupported()) { + GuiScreen screen = new GuiScreenRecordingSettings(this); + if (!GuiScreenRecordingNote.hasShown) { + screen = new GuiScreenRecordingNote(screen); + } + this.mc.displayGuiScreen(screen); + } + } + + if (parGuiButton.id == 104) { + EagRuntime.showDebugConsole(); + } + } + } + + public void confirmClicked(boolean flag, int i) { + this.mc.displayGuiScreen(this); + if (i == 109 && flag && this.mc.theWorld != null) { + this.mc.theWorld.getWorldInfo().setDifficultyLocked(true); + SingleplayerServerController.setDifficulty(-1); + this.field_175356_r.func_175229_b(true); + this.field_175356_r.enabled = false; + this.field_175357_i.enabled = false; + } + + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, this.field_146442_a, this.width / 2, 15, 16777215); + + if (mc.theWorld == null && !EagRuntime.getConfiguration().isDemo()) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + String text = I18n.format("editProfile.importExport"); + + int w = mc.fontRendererObj.getStringWidth(text); + boolean hover = i > 1 && j > 1 && i < (w * 3 / 4) + 7 && j < 12; + if (hover) { + Mouse.showCursor(EnumCursorType.HAND); + } + + drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); + + GlStateManager.popMatrix(); + } + + if (mc.theWorld == null && EagRuntime.getConfiguration().isAllowBootMenu()) { + drawCenteredString(mc.fontRendererObj, I18n.format("options.pressDeleteText"), width / 2, height / 6 + 22, + 11184810); + } + + if (EagRuntime.getConfiguration().isEnableServerCookies() && mc.thePlayer == null) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + String text = I18n.format("revokeSessionToken.button"); + + int w = mc.fontRendererObj.getStringWidth(text); + boolean hover = i > width - 5 - (w + 5) * 3 / 4 && j > 1 && i < width - 2 && j < 12; + if (hover) { + Mouse.showCursor(EnumCursorType.HAND); + } + + drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, (width - 1) * 4 / 3 - w - 5, 5, + hover ? 0xFFEEEE22 : 0xFFCCCCCC); + + GlStateManager.popMatrix(); + } + + super.drawScreen(i, j, f); + } + + public String func_175355_a(EnumDifficulty parEnumDifficulty) { + ChatComponentText chatcomponenttext = new ChatComponentText(""); + chatcomponenttext.appendSibling(new ChatComponentTranslation("options.difficulty", new Object[0])); + chatcomponenttext.appendText(": "); + chatcomponenttext.appendSibling( + new ChatComponentTranslation(parEnumDifficulty.getDifficultyResourceKey(), new Object[0])); + return chatcomponenttext.getUnformattedText(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { int i = 0; @@ -136,178 +311,6 @@ public class GuiOptions extends GuiScreen implements GuiYesNoCallback { I18n.format("gui.done", new Object[0]))); } - public String func_175355_a(EnumDifficulty parEnumDifficulty) { - ChatComponentText chatcomponenttext = new ChatComponentText(""); - chatcomponenttext.appendSibling(new ChatComponentTranslation("options.difficulty", new Object[0])); - chatcomponenttext.appendText(": "); - chatcomponenttext.appendSibling( - new ChatComponentTranslation(parEnumDifficulty.getDifficultyResourceKey(), new Object[0])); - return chatcomponenttext.getUnformattedText(); - } - - public void confirmClicked(boolean flag, int i) { - this.mc.displayGuiScreen(this); - if (i == 109 && flag && this.mc.theWorld != null) { - this.mc.theWorld.getWorldInfo().setDifficultyLocked(true); - SingleplayerServerController.setDifficulty(-1); - this.field_175356_r.func_175229_b(true); - this.field_175356_r.enabled = false; - this.field_175357_i.enabled = false; - } - - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id < 100 && parGuiButton instanceof GuiOptionButton) { - GameSettings.Options gamesettings$options = ((GuiOptionButton) parGuiButton).returnEnumOptions(); - this.game_settings_1.setOptionValue(gamesettings$options, 1); - parGuiButton.displayString = this.game_settings_1 - .getKeyBinding(GameSettings.Options.getEnumOptions(parGuiButton.id)); - } - - if (parGuiButton.id == 108) { - this.mc.theWorld.getWorldInfo().setDifficulty( - EnumDifficulty.getDifficultyEnum(this.mc.theWorld.getDifficulty().getDifficultyId() + 1)); - SingleplayerServerController - .setDifficulty(this.mc.theWorld.getWorldInfo().getDifficulty().getDifficultyId()); - this.field_175357_i.displayString = this.func_175355_a(this.mc.theWorld.getDifficulty()); - } - - if (parGuiButton.id == 109) { - this.mc.displayGuiScreen( - new GuiYesNo(this, - (new ChatComponentTranslation("difficulty.lock.title", new Object[0])) - .getFormattedText(), - (new ChatComponentTranslation("difficulty.lock.question", - new Object[] { new ChatComponentTranslation(this.mc.theWorld.getWorldInfo() - .getDifficulty().getDifficultyResourceKey(), new Object[0]) })) - .getFormattedText(), - 109)); - } - - if (parGuiButton.id == 110) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new GuiCustomizeSkin(this)); - } - - if (parGuiButton.id == 8675309) { - if (EaglerDeferredPipeline.isSupported()) { - this.mc.displayGuiScreen(new GuiShaderConfig(this)); - } else { - this.mc.displayGuiScreen(new GuiShadersNotSupported(this, - I18n.format(EaglerDeferredPipeline.getReasonUnsupported()))); - } - } - - if (parGuiButton.id == 101) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new GuiVideoSettings(this, this.game_settings_1)); - } - - if (parGuiButton.id == 100) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new GuiControls(this, this.game_settings_1)); - } - - if (parGuiButton.id == 102) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new GuiLanguage(this, this.game_settings_1, this.mc.getLanguageManager())); - } - - if (parGuiButton.id == 103) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new ScreenChatOptions(this, this.game_settings_1)); - } - - if (parGuiButton.id == 200) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(this.field_146441_g); - } - - if (parGuiButton.id == 105) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new GuiScreenResourcePacks(this)); - } - - if (parGuiButton.id == 106) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(new GuiScreenOptionsSounds(this, this.game_settings_1)); - } - - if (parGuiButton.id == 107) { - if (ScreenRecordingController.isSupported()) { - GuiScreen screen = new GuiScreenRecordingSettings(this); - if (!GuiScreenRecordingNote.hasShown) { - screen = new GuiScreenRecordingNote(screen); - } - this.mc.displayGuiScreen(screen); - } - } - - if (parGuiButton.id == 104) { - EagRuntime.showDebugConsole(); - } - } - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, this.field_146442_a, this.width / 2, 15, 16777215); - - if (mc.theWorld == null && !EagRuntime.getConfiguration().isDemo()) { - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - String text = I18n.format("editProfile.importExport"); - - int w = mc.fontRendererObj.getStringWidth(text); - boolean hover = i > 1 && j > 1 && i < (w * 3 / 4) + 7 && j < 12; - if (hover) { - Mouse.showCursor(EnumCursorType.HAND); - } - - drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); - - GlStateManager.popMatrix(); - } - - if (mc.theWorld == null && EagRuntime.getConfiguration().isAllowBootMenu()) { - drawCenteredString(mc.fontRendererObj, I18n.format("options.pressDeleteText"), width / 2, height / 6 + 22, - 11184810); - } - - if (EagRuntime.getConfiguration().isEnableServerCookies() && mc.thePlayer == null) { - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - String text = I18n.format("revokeSessionToken.button"); - - int w = mc.fontRendererObj.getStringWidth(text); - boolean hover = i > width - 5 - (w + 5) * 3 / 4 && j > 1 && i < width - 2 && j < 12; - if (hover) { - Mouse.showCursor(EnumCursorType.HAND); - } - - drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, (width - 1) * 4 / 3 - w - 5, 5, - hover ? 0xFFEEEE22 : 0xFFCCCCCC); - - GlStateManager.popMatrix(); - } - - super.drawScreen(i, j, f); - } - @Override protected void keyTyped(char parChar1, int parInt1) { super.keyTyped(parChar1, parInt1); diff --git a/src/game/java/net/minecraft/client/gui/GuiOptionsRowList.java b/src/game/java/net/minecraft/client/gui/GuiOptionsRowList.java index ecb728b0..d7ff128b 100644 --- a/src/game/java/net/minecraft/client/gui/GuiOptionsRowList.java +++ b/src/game/java/net/minecraft/client/gui/GuiOptionsRowList.java @@ -8,78 +8,30 @@ import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.GameSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiOptionsRowList extends GuiListExtended { - private final List field_148184_k = Lists.newArrayList(); - - public GuiOptionsRowList(Minecraft mcIn, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, - GameSettings.Options... parArrayOfOptions) { - super(mcIn, parInt1, parInt2, parInt3, parInt4, parInt5); - this.field_148163_i = false; - - for (int i = 0; i < parArrayOfOptions.length; i += 2) { - GameSettings.Options gamesettings$options = parArrayOfOptions[i]; - GameSettings.Options gamesettings$options1 = i < parArrayOfOptions.length - 1 ? parArrayOfOptions[i + 1] - : null; - GuiButton guibutton = this.func_148182_a(mcIn, parInt1 / 2 - 155, 0, gamesettings$options); - GuiButton guibutton1 = this.func_148182_a(mcIn, parInt1 / 2 - 155 + 160, 0, gamesettings$options1); - this.field_148184_k.add(new GuiOptionsRowList.Row(guibutton, guibutton1)); - } - - } - - private GuiButton func_148182_a(Minecraft mcIn, int parInt1, int parInt2, GameSettings.Options parOptions) { - if (parOptions == null) { - return null; - } else { - int i = parOptions.returnEnumOrdinal(); - return (GuiButton) (parOptions.getEnumFloat() ? new GuiOptionSlider(i, parInt1, parInt2, parOptions) - : new GuiOptionButton(i, parInt1, parInt2, parOptions, - mcIn.gameSettings.getKeyBinding(parOptions))); - } - } - - /**+ - * Gets the IGuiListEntry object for the given index - */ - public GuiOptionsRowList.Row getListEntry(int i) { - return (GuiOptionsRowList.Row) this.field_148184_k.get(i); - } - - protected int getSize() { - return this.field_148184_k.size(); - } - - /**+ - * Gets the width of the list - */ - public int getListWidth() { - return 400; - } - - protected int getScrollBarX() { - return super.getScrollBarX() + 32; - } - public static class Row implements GuiListExtended.IGuiListEntry { private final Minecraft field_148325_a = Minecraft.getMinecraft(); private final GuiButton field_148323_b; @@ -153,6 +105,35 @@ public class GuiOptionsRowList extends GuiListExtended { } } + private final List field_148184_k = Lists.newArrayList(); + + public GuiOptionsRowList(Minecraft mcIn, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, + GameSettings.Options... parArrayOfOptions) { + super(mcIn, parInt1, parInt2, parInt3, parInt4, parInt5); + this.field_148163_i = false; + + for (int i = 0; i < parArrayOfOptions.length; i += 2) { + GameSettings.Options gamesettings$options = parArrayOfOptions[i]; + GameSettings.Options gamesettings$options1 = i < parArrayOfOptions.length - 1 ? parArrayOfOptions[i + 1] + : null; + GuiButton guibutton = this.func_148182_a(mcIn, parInt1 / 2 - 155, 0, gamesettings$options); + GuiButton guibutton1 = this.func_148182_a(mcIn, parInt1 / 2 - 155 + 160, 0, gamesettings$options1); + this.field_148184_k.add(new GuiOptionsRowList.Row(guibutton, guibutton1)); + } + + } + + private GuiButton func_148182_a(Minecraft mcIn, int parInt1, int parInt2, GameSettings.Options parOptions) { + if (parOptions == null) { + return null; + } else { + int i = parOptions.returnEnumOrdinal(); + return (GuiButton) (parOptions.getEnumFloat() ? new GuiOptionSlider(i, parInt1, parInt2, parOptions) + : new GuiOptionButton(i, parInt1, parInt2, parOptions, + mcIn.gameSettings.getKeyBinding(parOptions))); + } + } + public GuiOptionButton getButtonFor(GameSettings.Options enumOption) { for (Row r : field_148184_k) { if (r.field_148323_b != null) { @@ -175,6 +156,28 @@ public class GuiOptionsRowList extends GuiListExtended { return null; } + /** + * + Gets the IGuiListEntry object for the given index + */ + public GuiOptionsRowList.Row getListEntry(int i) { + return (GuiOptionsRowList.Row) this.field_148184_k.get(i); + } + + /** + * + Gets the width of the list + */ + public int getListWidth() { + return 400; + } + + protected int getScrollBarX() { + return super.getScrollBarX() + 32; + } + + protected int getSize() { + return this.field_148184_k.size(); + } + public GuiOptionSlider getSliderFor(GameSettings.Options enumOption) { for (Row r : field_148184_k) { if (r.field_148323_b != null) { diff --git a/src/game/java/net/minecraft/client/gui/GuiOverlayDebug.java b/src/game/java/net/minecraft/client/gui/GuiOverlayDebug.java index fe115c48..0d8b5ae8 100644 --- a/src/game/java/net/minecraft/client/gui/GuiOverlayDebug.java +++ b/src/game/java/net/minecraft/client/gui/GuiOverlayDebug.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -9,11 +10,10 @@ import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map.Entry; +import java.util.TimeZone; import org.apache.commons.lang3.StringUtils; -import java.util.TimeZone; - import com.google.common.base.Strings; import com.google.common.collect.Lists; @@ -44,27 +44,46 @@ import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiOverlayDebug extends Gui { + public static final int ticksAtMidnight = 18000; + public static final int ticksPerDay = 24000; + public static final int ticksPerHour = 1000; + + public static final double ticksPerMinute = 1000d / 60d; + + public static final double ticksPerSecond = 1000d / 60d / 60d; + + private static final SimpleDateFormat SDFTwentyFour = new SimpleDateFormat("HH:mm", Locale.ENGLISH); + + private static final SimpleDateFormat SDFTwelve = new SimpleDateFormat("h:mm aa", Locale.ENGLISH); + + private static long bytesToMb(long bytes) { + return bytes / 1024L / 1024L; + } + private final Minecraft mc; private final FontRenderer fontRenderer; public int playerOffset = 0; @@ -74,274 +93,6 @@ public class GuiOverlayDebug extends Gui { this.fontRenderer = mc.fontRendererObj; } - public void renderDebugInfo(ScaledResolution scaledResolutionIn) { - playerOffset = 0; - int ww = scaledResolutionIn.getScaledWidth(); - int hh = scaledResolutionIn.getScaledHeight(); - if (this.mc.gameSettings.showDebugInfo) { - GlStateManager.pushMatrix(); - this.renderDebugInfoLeft(); - this.renderDebugInfoRight(scaledResolutionIn); - GlStateManager.popMatrix(); - if (this.mc.gameSettings.field_181657_aC) { - this.func_181554_e(); - } - } else { - int i = 2; - - if (this.mc.gameSettings.hudFps) { - drawFPS(2, i); - playerOffset = drawSingleplayerStats(scaledResolutionIn); - i += 9; - } - - if (this.mc.gameSettings.hudCoords) { - drawXYZ(2, i); - } - - } - - if (this.mc.currentScreen == null || !(this.mc.currentScreen instanceof GuiChat)) { - if (this.mc.gameSettings.hudStats) { - drawStatsHUD(ww - 2, hh - 2); - } - - if (this.mc.gameSettings.hudWorld) { - drawWorldHUD(2, hh - 2); - } - } - - if (this.mc.gameSettings.hudCoords && this.mc.joinWorldTickCounter < 80) { - if (this.mc.joinWorldTickCounter > 70) { - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - } - int i = this.mc.joinWorldTickCounter - 70; - if (i < 0) - i = 0; - drawHideHUD(ww / 2, hh - 70, (10 - i) * 0xFF / 10); - if (this.mc.joinWorldTickCounter > 70) { - GlStateManager.disableBlend(); - } - } - } - - private void drawFPS(int x, int y) { - this.fontRenderer.drawStringWithShadow(this.mc.renderGlobal.getDebugInfoShort(), x, y, 0xFFFFFF); - } - - private void drawXYZ(int x, int y) { - Entity e = mc.getRenderViewEntity(); - BlockPos blockpos = new BlockPos(e.posX, e.getEntityBoundingBox().minY, e.posZ); - this.fontRenderer.drawStringWithShadow( - "x: " + blockpos.getX() + ", y: " + blockpos.getY() + ", z: " + blockpos.getZ(), x, y, 0xFFFFFF); - } - - private void drawStatsHUD(int x, int y) { - int i = 9; - - String line = "Walk: " + EnumChatFormatting.YELLOW + HString.format("%.2f", mc.thePlayer.getAIMoveSpeed()) - + EnumChatFormatting.WHITE + " Flight: " - + (mc.thePlayer.capabilities.allowFlying - ? ("" + EnumChatFormatting.YELLOW + mc.thePlayer.capabilities.getFlySpeed()) - : EnumChatFormatting.RED + "No"); - int lw = fontRenderer.getStringWidth(line); - this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); - i += 11; - - line = "Food: " + EnumChatFormatting.YELLOW + mc.thePlayer.getFoodStats().getFoodLevel() - + EnumChatFormatting.WHITE + ", Sat: " + EnumChatFormatting.YELLOW - + HString.format("%.1f", mc.thePlayer.getFoodStats().getSaturationLevel()); - lw = fontRenderer.getStringWidth(line); - this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); - i += 11; - - line = "Amr: " + EnumChatFormatting.YELLOW + mc.thePlayer.getTotalArmorValue() + EnumChatFormatting.WHITE - + ", Health: " + EnumChatFormatting.RED + HString.format("%.1f", mc.thePlayer.getHealth()); - lw = fontRenderer.getStringWidth(line); - this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); - i += 11; - - int xpc = mc.thePlayer.xpBarCap(); - line = "XP: " + EnumChatFormatting.GREEN + MathHelper.floor_float(mc.thePlayer.experience * xpc) - + EnumChatFormatting.WHITE + " / " + EnumChatFormatting.GREEN + xpc; - lw = fontRenderer.getStringWidth(line); - this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); - i += 11; - - Iterator potions = mc.thePlayer.getActivePotionEffects().iterator(); - if (potions.hasNext()) { - while (potions.hasNext()) { - i += 11; - PotionEffect e = potions.next(); - int t = e.getDuration() / 20; - int m = t / 60; - int s = t % 60; - int j = e.getAmplifier(); - if (j > 0) { - line = I18n.format(e.getEffectName()) - + (j > 0 ? (" " + EnumChatFormatting.YELLOW + EnumChatFormatting.BOLD - + I18n.format("potion.potency." + j) + EnumChatFormatting.RESET) : "") - + " [" + EnumChatFormatting.YELLOW + HString.format("%02d:%02d", m, s) - + EnumChatFormatting.RESET + "]"; - } else { - line = I18n.format(e.getEffectName()) + " [" + EnumChatFormatting.YELLOW - + HString.format("%02d:%02d", m, s) + EnumChatFormatting.RESET + "]"; - } - lw = fontRenderer.getStringWidth(line); - this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); - } - } - - } - - public static final int ticksAtMidnight = 18000; - public static final int ticksPerDay = 24000; - public static final int ticksPerHour = 1000; - public static final double ticksPerMinute = 1000d / 60d; - public static final double ticksPerSecond = 1000d / 60d / 60d; - private static final SimpleDateFormat SDFTwentyFour = new SimpleDateFormat("HH:mm", Locale.ENGLISH); - private static final SimpleDateFormat SDFTwelve = new SimpleDateFormat("h:mm aa", Locale.ENGLISH); - - private void drawWorldHUD(int x, int y) { - /* - * Math was taken from: https://github.com/EssentialsX/Essentials/blob/ - * dc7fb919391d62de45e17b51ae1e6fe3e66d7ac6/Essentials/src/main/java/com/ - * earth2me/essentials/utils/DescParseTickFormat.java - */ - long totalTicks = mc.theWorld.getWorldTime(); - long ticks = totalTicks; - ticks = ticks - ticksAtMidnight + ticksPerDay; - final long days = ticks / ticksPerDay; - ticks -= days * ticksPerDay; - final long hours = ticks / ticksPerHour; - ticks -= hours * ticksPerHour; - final long minutes = (long) Math.floor(ticks / ticksPerMinute); - final double dticks = ticks - minutes * ticksPerMinute; - final long seconds = (long) Math.floor(dticks / ticksPerSecond); - - final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH); - - cal.setLenient(true); - cal.set(0, Calendar.JANUARY, 1, 0, 0, 0); - cal.add(Calendar.DAY_OF_YEAR, (int) days); - cal.add(Calendar.HOUR_OF_DAY, (int) hours); - cal.add(Calendar.MINUTE, (int) minutes); - cal.add(Calendar.SECOND, (int) seconds + 1); - - SimpleDateFormat fmt = this.mc.gameSettings.hud24h ? SDFTwentyFour : SDFTwelve; - fmt.setCalendar(cal); - String timeString = EnumChatFormatting.WHITE + "Day " + ((totalTicks + 30000l) / 24000l) + " (" - + EnumChatFormatting.YELLOW + fmt.format(cal.getTime()) + EnumChatFormatting.WHITE + ")"; - - Entity e = mc.getRenderViewEntity(); - BlockPos blockpos = new BlockPos(e.posX, MathHelper.clamp_double(e.getEntityBoundingBox().minY, 0.0D, 254.0D), - e.posZ); - BiomeGenBase biome = mc.theWorld.getBiomeGenForCoords(blockpos); - - Chunk c = mc.theWorld.getChunkFromBlockCoords(blockpos); - int blockLight = c.getLightFor(EnumSkyBlock.BLOCK, blockpos); - int skyLight = c.getLightFor(EnumSkyBlock.SKY, blockpos) - mc.theWorld.calculateSkylightSubtracted(1.0f); - int totalLight = Math.max(blockLight, skyLight); - EnumChatFormatting lightColor = blockLight < 8 - ? ((skyLight < 8 || !mc.theWorld.isDaytime()) ? EnumChatFormatting.RED : EnumChatFormatting.YELLOW) - : EnumChatFormatting.GREEN; - String lightString = "Light: " + lightColor + totalLight + EnumChatFormatting.WHITE; - - float temp = biome.getFloatTemperature(blockpos); - - String tempString = "Temp: " - + ((blockLight > 11 || temp > 0.15f) ? EnumChatFormatting.YELLOW : EnumChatFormatting.AQUA) - + HString.format("%.2f", temp) + EnumChatFormatting.WHITE; - - this.fontRenderer.drawStringWithShadow(timeString, x, y - 30, 0xFFFFFF); - this.fontRenderer.drawStringWithShadow("Biome: " + EnumChatFormatting.AQUA + biome.biomeName, x, y - 19, - 0xFFFFFF); - this.fontRenderer.drawStringWithShadow(lightString + " " + tempString, x, y - 8, 0xFFFFFF); - } - - private void drawHideHUD(int x, int y, int fade) { - drawCenteredString(fontRenderer, I18n.format("options.hud.note"), x, y, 0xEECC00 | (fade << 24)); - } - - private boolean isReducedDebug() { - return this.mc.thePlayer.hasReducedDebug() || this.mc.gameSettings.reducedDebugInfo; - } - - private int drawSingleplayerStats(ScaledResolution parScaledResolution) { - if (mc.isDemo()) { - return 13; - } - int i = 0; - if (SingleplayerServerController.isWorldRunning()) { - long tpsAge = SingleplayerServerController.getTPSAge(); - if (tpsAge < 20000l) { - int color = tpsAge > 2000l ? 0x777777 : 0xFFFFFF; - List strs = SingleplayerServerController.getTPS(); - if (SingleplayerServerController.isRunningSingleThreadMode()) { - strs = Lists.newArrayList(strs); - strs.add(""); - strs.add(I18n.format("singleplayer.tpscounter.singleThreadMode")); - } - int l; - boolean first = true; - for (int j = 0, m = strs.size(); j < m; ++j) { - String str = strs.get(j); - if (!StringUtils.isAllEmpty(str)) { - l = (int) (this.fontRenderer.getStringWidth(str) * (!first ? 0.5f : 1.0f)); - GlStateManager.pushMatrix(); - GlStateManager.translate(parScaledResolution.getScaledWidth() - 2 - l, i + 2, 0.0f); - if (!first) { - GlStateManager.scale(0.5f, 0.5f, 0.5f); - } - this.fontRenderer.drawStringWithShadow(str, 0, 0, color); - GlStateManager.popMatrix(); - if (color == 0xFFFFFF) { - color = 14737632; - } - } - i += (int) (this.fontRenderer.FONT_HEIGHT * (!first ? 0.5f : 1.0f)); - first = false; - } - } - } - return i > 0 ? i + 2 : i; - } - - protected void renderDebugInfoLeft() { - List list = this.call(); - - for (int i = 0; i < list.size(); ++i) { - String s = (String) list.get(i); - if (!Strings.isNullOrEmpty(s)) { - int j = this.fontRenderer.FONT_HEIGHT; - int k = this.fontRenderer.getStringWidth(s); - boolean flag = true; - int l = 2 + j * i; - drawRect(1, l - 1, 2 + k + 1, l + j - 1, -1873784752); - this.fontRenderer.drawString(s, 2, l, 14737632); - } - } - - } - - protected void renderDebugInfoRight(ScaledResolution parScaledResolution) { - List list = this.getDebugInfoRight(); - - for (int i = 0; i < list.size(); ++i) { - String s = (String) list.get(i); - if (!Strings.isNullOrEmpty(s)) { - int j = this.fontRenderer.FONT_HEIGHT; - int k = this.fontRenderer.getStringWidth(s); - int l = parScaledResolution.getScaledWidth() - 2 - k; - int i1 = 2 + j * i; - drawRect(l - 1, i1 - 1, l + k + 1, i1 + j - 1, -1873784752); - this.fontRenderer.drawString(s, l, i1, 14737632); - } - } - - } - protected List call() { if (!this.mc.gameSettings.showDebugInfo) { BlockPos blockpos = new BlockPos(this.mc.getRenderViewEntity().posX, @@ -428,6 +179,235 @@ public class GuiOverlayDebug extends Gui { } } + private void drawFPS(int x, int y) { + this.fontRenderer.drawStringWithShadow(this.mc.renderGlobal.getDebugInfoShort(), x, y, 0xFFFFFF); + } + + private void drawHideHUD(int x, int y, int fade) { + drawCenteredString(fontRenderer, I18n.format("options.hud.note"), x, y, 0xEECC00 | (fade << 24)); + } + + private int drawSingleplayerStats(ScaledResolution parScaledResolution) { + if (mc.isDemo()) { + return 13; + } + int i = 0; + if (SingleplayerServerController.isWorldRunning()) { + long tpsAge = SingleplayerServerController.getTPSAge(); + if (tpsAge < 20000l) { + int color = tpsAge > 2000l ? 0x777777 : 0xFFFFFF; + List strs = SingleplayerServerController.getTPS(); + if (SingleplayerServerController.isRunningSingleThreadMode()) { + strs = Lists.newArrayList(strs); + strs.add(""); + strs.add(I18n.format("singleplayer.tpscounter.singleThreadMode")); + } + int l; + boolean first = true; + for (int j = 0, m = strs.size(); j < m; ++j) { + String str = strs.get(j); + if (!StringUtils.isAllEmpty(str)) { + l = (int) (this.fontRenderer.getStringWidth(str) * (!first ? 0.5f : 1.0f)); + GlStateManager.pushMatrix(); + GlStateManager.translate(parScaledResolution.getScaledWidth() - 2 - l, i + 2, 0.0f); + if (!first) { + GlStateManager.scale(0.5f, 0.5f, 0.5f); + } + this.fontRenderer.drawStringWithShadow(str, 0, 0, color); + GlStateManager.popMatrix(); + if (color == 0xFFFFFF) { + color = 14737632; + } + } + i += (int) (this.fontRenderer.FONT_HEIGHT * (!first ? 0.5f : 1.0f)); + first = false; + } + } + } + return i > 0 ? i + 2 : i; + } + + private void drawStatsHUD(int x, int y) { + int i = 9; + + String line = "Walk: " + EnumChatFormatting.YELLOW + HString.format("%.2f", mc.thePlayer.getAIMoveSpeed()) + + EnumChatFormatting.WHITE + " Flight: " + + (mc.thePlayer.capabilities.allowFlying + ? ("" + EnumChatFormatting.YELLOW + mc.thePlayer.capabilities.getFlySpeed()) + : EnumChatFormatting.RED + "No"); + int lw = fontRenderer.getStringWidth(line); + this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); + i += 11; + + line = "Food: " + EnumChatFormatting.YELLOW + mc.thePlayer.getFoodStats().getFoodLevel() + + EnumChatFormatting.WHITE + ", Sat: " + EnumChatFormatting.YELLOW + + HString.format("%.1f", mc.thePlayer.getFoodStats().getSaturationLevel()); + lw = fontRenderer.getStringWidth(line); + this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); + i += 11; + + line = "Amr: " + EnumChatFormatting.YELLOW + mc.thePlayer.getTotalArmorValue() + EnumChatFormatting.WHITE + + ", Health: " + EnumChatFormatting.RED + HString.format("%.1f", mc.thePlayer.getHealth()); + lw = fontRenderer.getStringWidth(line); + this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); + i += 11; + + int xpc = mc.thePlayer.xpBarCap(); + line = "XP: " + EnumChatFormatting.GREEN + MathHelper.floor_float(mc.thePlayer.experience * xpc) + + EnumChatFormatting.WHITE + " / " + EnumChatFormatting.GREEN + xpc; + lw = fontRenderer.getStringWidth(line); + this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); + i += 11; + + Iterator potions = mc.thePlayer.getActivePotionEffects().iterator(); + if (potions.hasNext()) { + while (potions.hasNext()) { + i += 11; + PotionEffect e = potions.next(); + int t = e.getDuration() / 20; + int m = t / 60; + int s = t % 60; + int j = e.getAmplifier(); + if (j > 0) { + line = I18n.format(e.getEffectName()) + + (j > 0 ? (" " + EnumChatFormatting.YELLOW + EnumChatFormatting.BOLD + + I18n.format("potion.potency." + j) + EnumChatFormatting.RESET) : "") + + " [" + EnumChatFormatting.YELLOW + HString.format("%02d:%02d", m, s) + + EnumChatFormatting.RESET + "]"; + } else { + line = I18n.format(e.getEffectName()) + " [" + EnumChatFormatting.YELLOW + + HString.format("%02d:%02d", m, s) + EnumChatFormatting.RESET + "]"; + } + lw = fontRenderer.getStringWidth(line); + this.fontRenderer.drawStringWithShadow(line, x - lw, y - i, 0xFFFFFF); + } + } + + } + + private void drawWorldHUD(int x, int y) { + /* + * Math was taken from: https://github.com/EssentialsX/Essentials/blob/ + * dc7fb919391d62de45e17b51ae1e6fe3e66d7ac6/Essentials/src/main/java/com/ + * earth2me/essentials/utils/DescParseTickFormat.java + */ + long totalTicks = mc.theWorld.getWorldTime(); + long ticks = totalTicks; + ticks = ticks - ticksAtMidnight + ticksPerDay; + final long days = ticks / ticksPerDay; + ticks -= days * ticksPerDay; + final long hours = ticks / ticksPerHour; + ticks -= hours * ticksPerHour; + final long minutes = (long) Math.floor(ticks / ticksPerMinute); + final double dticks = ticks - minutes * ticksPerMinute; + final long seconds = (long) Math.floor(dticks / ticksPerSecond); + + final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH); + + cal.setLenient(true); + cal.set(0, Calendar.JANUARY, 1, 0, 0, 0); + cal.add(Calendar.DAY_OF_YEAR, (int) days); + cal.add(Calendar.HOUR_OF_DAY, (int) hours); + cal.add(Calendar.MINUTE, (int) minutes); + cal.add(Calendar.SECOND, (int) seconds + 1); + + SimpleDateFormat fmt = this.mc.gameSettings.hud24h ? SDFTwentyFour : SDFTwelve; + fmt.setCalendar(cal); + String timeString = EnumChatFormatting.WHITE + "Day " + ((totalTicks + 30000l) / 24000l) + " (" + + EnumChatFormatting.YELLOW + fmt.format(cal.getTime()) + EnumChatFormatting.WHITE + ")"; + + Entity e = mc.getRenderViewEntity(); + BlockPos blockpos = new BlockPos(e.posX, MathHelper.clamp_double(e.getEntityBoundingBox().minY, 0.0D, 254.0D), + e.posZ); + BiomeGenBase biome = mc.theWorld.getBiomeGenForCoords(blockpos); + + Chunk c = mc.theWorld.getChunkFromBlockCoords(blockpos); + int blockLight = c.getLightFor(EnumSkyBlock.BLOCK, blockpos); + int skyLight = c.getLightFor(EnumSkyBlock.SKY, blockpos) - mc.theWorld.calculateSkylightSubtracted(1.0f); + int totalLight = Math.max(blockLight, skyLight); + EnumChatFormatting lightColor = blockLight < 8 + ? ((skyLight < 8 || !mc.theWorld.isDaytime()) ? EnumChatFormatting.RED : EnumChatFormatting.YELLOW) + : EnumChatFormatting.GREEN; + String lightString = "Light: " + lightColor + totalLight + EnumChatFormatting.WHITE; + + float temp = biome.getFloatTemperature(blockpos); + + String tempString = "Temp: " + + ((blockLight > 11 || temp > 0.15f) ? EnumChatFormatting.YELLOW : EnumChatFormatting.AQUA) + + HString.format("%.2f", temp) + EnumChatFormatting.WHITE; + + this.fontRenderer.drawStringWithShadow(timeString, x, y - 30, 0xFFFFFF); + this.fontRenderer.drawStringWithShadow("Biome: " + EnumChatFormatting.AQUA + biome.biomeName, x, y - 19, + 0xFFFFFF); + this.fontRenderer.drawStringWithShadow(lightString + " " + tempString, x, y - 8, 0xFFFFFF); + } + + private void drawXYZ(int x, int y) { + Entity e = mc.getRenderViewEntity(); + BlockPos blockpos = new BlockPos(e.posX, e.getEntityBoundingBox().minY, e.posZ); + this.fontRenderer.drawStringWithShadow( + "x: " + blockpos.getX() + ", y: " + blockpos.getY() + ", z: " + blockpos.getZ(), x, y, 0xFFFFFF); + } + + private int func_181552_c(int parInt1, int parInt2, int parInt3, int parInt4) { + return parInt1 < parInt3 ? this.func_181553_a(-16711936, -256, (float) parInt1 / (float) parInt3) + : this.func_181553_a(-256, -65536, (float) (parInt1 - parInt3) / (float) (parInt4 - parInt3)); + } + + private int func_181553_a(int parInt1, int parInt2, float parFloat1) { + int i = parInt1 >> 24 & 255; + int j = parInt1 >> 16 & 255; + int k = parInt1 >> 8 & 255; + int l = parInt1 & 255; + int i1 = parInt2 >> 24 & 255; + int j1 = parInt2 >> 16 & 255; + int k1 = parInt2 >> 8 & 255; + int l1 = parInt2 & 255; + int i2 = MathHelper.clamp_int((int) ((float) i + (float) (i1 - i) * parFloat1), 0, 255); + int j2 = MathHelper.clamp_int((int) ((float) j + (float) (j1 - j) * parFloat1), 0, 255); + int k2 = MathHelper.clamp_int((int) ((float) k + (float) (k1 - k) * parFloat1), 0, 255); + int l2 = MathHelper.clamp_int((int) ((float) l + (float) (l1 - l) * parFloat1), 0, 255); + return i2 << 24 | j2 << 16 | k2 << 8 | l2; + } + + private void func_181554_e() { + GlStateManager.disableDepth(); + FrameTimer frametimer = this.mc.func_181539_aj(); + int i = frametimer.func_181749_a(); + int j = frametimer.func_181750_b(); + long[] along = frametimer.func_181746_c(); + ScaledResolution scaledresolution = this.mc.scaledResolution; + int k = i; + int l = 0; + drawRect(0, scaledresolution.getScaledHeight() - 60, 240, scaledresolution.getScaledHeight(), -1873784752); + + while (k != j) { + int i1 = frametimer.func_181748_a(along[k], 30); + int j1 = this.func_181552_c(MathHelper.clamp_int(i1, 0, 60), 0, 30, 60); + this.drawVerticalLine(l, scaledresolution.getScaledHeight(), scaledresolution.getScaledHeight() - i1, j1); + ++l; + k = frametimer.func_181751_b(k + 1); + } + + drawRect(1, scaledresolution.getScaledHeight() - 30 + 1, 14, scaledresolution.getScaledHeight() - 30 + 10, + -1873784752); + this.fontRenderer.drawString("60", 2, scaledresolution.getScaledHeight() - 30 + 2, 14737632); + this.drawHorizontalLine(0, 239, scaledresolution.getScaledHeight() - 30, -1); + drawRect(1, scaledresolution.getScaledHeight() - 60 + 1, 14, scaledresolution.getScaledHeight() - 60 + 10, + -1873784752); + this.fontRenderer.drawString("30", 2, scaledresolution.getScaledHeight() - 60 + 2, 14737632); + this.drawHorizontalLine(0, 239, scaledresolution.getScaledHeight() - 60, -1); + this.drawHorizontalLine(0, 239, scaledresolution.getScaledHeight() - 1, -1); + this.drawVerticalLine(0, scaledresolution.getScaledHeight() - 60, scaledresolution.getScaledHeight(), -1); + this.drawVerticalLine(239, scaledresolution.getScaledHeight() - 60, scaledresolution.getScaledHeight(), -1); + if (this.mc.gameSettings.limitFramerate <= 120) { + this.drawHorizontalLine(0, 239, + scaledresolution.getScaledHeight() - 60 + this.mc.gameSettings.limitFramerate / 2, -16711681); + } + + GlStateManager.enableDepth(); + } + protected List getDebugInfoRight() { ArrayList arraylist; if (EagRuntime.getPlatformType() != EnumPlatformType.JAVASCRIPT) { @@ -484,66 +464,93 @@ public class GuiOverlayDebug extends Gui { } } - private void func_181554_e() { - GlStateManager.disableDepth(); - FrameTimer frametimer = this.mc.func_181539_aj(); - int i = frametimer.func_181749_a(); - int j = frametimer.func_181750_b(); - long[] along = frametimer.func_181746_c(); - ScaledResolution scaledresolution = this.mc.scaledResolution; - int k = i; - int l = 0; - drawRect(0, scaledresolution.getScaledHeight() - 60, 240, scaledresolution.getScaledHeight(), -1873784752); + private boolean isReducedDebug() { + return this.mc.thePlayer.hasReducedDebug() || this.mc.gameSettings.reducedDebugInfo; + } + + public void renderDebugInfo(ScaledResolution scaledResolutionIn) { + playerOffset = 0; + int ww = scaledResolutionIn.getScaledWidth(); + int hh = scaledResolutionIn.getScaledHeight(); + if (this.mc.gameSettings.showDebugInfo) { + GlStateManager.pushMatrix(); + this.renderDebugInfoLeft(); + this.renderDebugInfoRight(scaledResolutionIn); + GlStateManager.popMatrix(); + if (this.mc.gameSettings.field_181657_aC) { + this.func_181554_e(); + } + } else { + int i = 2; + + if (this.mc.gameSettings.hudFps) { + drawFPS(2, i); + playerOffset = drawSingleplayerStats(scaledResolutionIn); + i += 9; + } + + if (this.mc.gameSettings.hudCoords) { + drawXYZ(2, i); + } - while (k != j) { - int i1 = frametimer.func_181748_a(along[k], 30); - int j1 = this.func_181552_c(MathHelper.clamp_int(i1, 0, 60), 0, 30, 60); - this.drawVerticalLine(l, scaledresolution.getScaledHeight(), scaledresolution.getScaledHeight() - i1, j1); - ++l; - k = frametimer.func_181751_b(k + 1); } - drawRect(1, scaledresolution.getScaledHeight() - 30 + 1, 14, scaledresolution.getScaledHeight() - 30 + 10, - -1873784752); - this.fontRenderer.drawString("60", 2, scaledresolution.getScaledHeight() - 30 + 2, 14737632); - this.drawHorizontalLine(0, 239, scaledresolution.getScaledHeight() - 30, -1); - drawRect(1, scaledresolution.getScaledHeight() - 60 + 1, 14, scaledresolution.getScaledHeight() - 60 + 10, - -1873784752); - this.fontRenderer.drawString("30", 2, scaledresolution.getScaledHeight() - 60 + 2, 14737632); - this.drawHorizontalLine(0, 239, scaledresolution.getScaledHeight() - 60, -1); - this.drawHorizontalLine(0, 239, scaledresolution.getScaledHeight() - 1, -1); - this.drawVerticalLine(0, scaledresolution.getScaledHeight() - 60, scaledresolution.getScaledHeight(), -1); - this.drawVerticalLine(239, scaledresolution.getScaledHeight() - 60, scaledresolution.getScaledHeight(), -1); - if (this.mc.gameSettings.limitFramerate <= 120) { - this.drawHorizontalLine(0, 239, - scaledresolution.getScaledHeight() - 60 + this.mc.gameSettings.limitFramerate / 2, -16711681); + if (this.mc.currentScreen == null || !(this.mc.currentScreen instanceof GuiChat)) { + if (this.mc.gameSettings.hudStats) { + drawStatsHUD(ww - 2, hh - 2); + } + + if (this.mc.gameSettings.hudWorld) { + drawWorldHUD(2, hh - 2); + } } - GlStateManager.enableDepth(); + if (this.mc.gameSettings.hudCoords && this.mc.joinWorldTickCounter < 80) { + if (this.mc.joinWorldTickCounter > 70) { + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + } + int i = this.mc.joinWorldTickCounter - 70; + if (i < 0) + i = 0; + drawHideHUD(ww / 2, hh - 70, (10 - i) * 0xFF / 10); + if (this.mc.joinWorldTickCounter > 70) { + GlStateManager.disableBlend(); + } + } } - private int func_181552_c(int parInt1, int parInt2, int parInt3, int parInt4) { - return parInt1 < parInt3 ? this.func_181553_a(-16711936, -256, (float) parInt1 / (float) parInt3) - : this.func_181553_a(-256, -65536, (float) (parInt1 - parInt3) / (float) (parInt4 - parInt3)); + protected void renderDebugInfoLeft() { + List list = this.call(); + + for (int i = 0; i < list.size(); ++i) { + String s = (String) list.get(i); + if (!Strings.isNullOrEmpty(s)) { + int j = this.fontRenderer.FONT_HEIGHT; + int k = this.fontRenderer.getStringWidth(s); + boolean flag = true; + int l = 2 + j * i; + drawRect(1, l - 1, 2 + k + 1, l + j - 1, -1873784752); + this.fontRenderer.drawString(s, 2, l, 14737632); + } + } + } - private int func_181553_a(int parInt1, int parInt2, float parFloat1) { - int i = parInt1 >> 24 & 255; - int j = parInt1 >> 16 & 255; - int k = parInt1 >> 8 & 255; - int l = parInt1 & 255; - int i1 = parInt2 >> 24 & 255; - int j1 = parInt2 >> 16 & 255; - int k1 = parInt2 >> 8 & 255; - int l1 = parInt2 & 255; - int i2 = MathHelper.clamp_int((int) ((float) i + (float) (i1 - i) * parFloat1), 0, 255); - int j2 = MathHelper.clamp_int((int) ((float) j + (float) (j1 - j) * parFloat1), 0, 255); - int k2 = MathHelper.clamp_int((int) ((float) k + (float) (k1 - k) * parFloat1), 0, 255); - int l2 = MathHelper.clamp_int((int) ((float) l + (float) (l1 - l) * parFloat1), 0, 255); - return i2 << 24 | j2 << 16 | k2 << 8 | l2; - } + protected void renderDebugInfoRight(ScaledResolution parScaledResolution) { + List list = this.getDebugInfoRight(); + + for (int i = 0; i < list.size(); ++i) { + String s = (String) list.get(i); + if (!Strings.isNullOrEmpty(s)) { + int j = this.fontRenderer.FONT_HEIGHT; + int k = this.fontRenderer.getStringWidth(s); + int l = parScaledResolution.getScaledWidth() - 2 - k; + int i1 = 2 + j * i; + drawRect(l - 1, i1 - 1, l + k + 1, i1 + j - 1, -1873784752); + this.fontRenderer.drawString(s, l, i1, 14737632); + } + } - private static long bytesToMb(long bytes) { - return bytes / 1024L / 1024L; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiPageButtonList.java b/src/game/java/net/minecraft/client/gui/GuiPageButtonList.java index c3fd2914..204625db 100644 --- a/src/game/java/net/minecraft/client/gui/GuiPageButtonList.java +++ b/src/game/java/net/minecraft/client/gui/GuiPageButtonList.java @@ -12,33 +12,279 @@ import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; import net.minecraft.client.Minecraft; import net.minecraft.util.IntHashMap; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiPageButtonList extends GuiListExtended { + public static class EditBoxEntry extends GuiPageButtonList.GuiListEntry { + private final Predicate field_178951_a; + + public EditBoxEntry(int parInt1, String parString1, boolean parFlag, Predicate parPredicate) { + super(parInt1, parString1, parFlag); + this.field_178951_a = (Predicate) Objects.firstNonNull(parPredicate, Predicates.alwaysTrue()); + } + + public Predicate func_178950_a() { + return this.field_178951_a; + } + } + + public static class GuiButtonEntry extends GuiPageButtonList.GuiListEntry { + private final boolean field_178941_a; + + public GuiButtonEntry(int parInt1, String parString1, boolean parFlag, boolean parFlag2) { + super(parInt1, parString1, parFlag); + this.field_178941_a = parFlag2; + } + + public boolean func_178940_a() { + return this.field_178941_a; + } + } + + public static class GuiEntry implements GuiListExtended.IGuiListEntry { + private static boolean stupidCheck(Gui gui, int k) { + if (gui instanceof GuiButton) { + return ((GuiButton) gui).isSliderTouchEvents() == (k == 12345); + } else { + return k != 12345; + } + } + + private final Minecraft field_178031_a = Minecraft.getMinecraft(); + private final Gui field_178029_b; + private final Gui field_178030_c; + + private Gui field_178028_d; + + public GuiEntry(Gui parGui, Gui parGui2) { + this.field_178029_b = parGui; + this.field_178030_c = parGui2; + } + + public void drawEntry(int var1, int var2, int i, int var4, int var5, int j, int k, boolean var8) { + this.func_178017_a(this.field_178029_b, i, j, k, false); + this.func_178017_a(this.field_178030_c, i, j, k, false); + } + + private void func_178016_b(Gui parGui, int parInt1, int parInt2, int parInt3) { + if (parGui != null) { + if (parGui instanceof GuiButton) { + this.func_178019_b((GuiButton) parGui, parInt1, parInt2, parInt3); + } + + } + } + + private void func_178017_a(Gui parGui, int parInt1, int parInt2, int parInt3, boolean parFlag) { + if (parGui != null) { + if (parGui instanceof GuiButton) { + this.func_178024_a((GuiButton) parGui, parInt1, parInt2, parInt3, parFlag); + } else if (parGui instanceof GuiTextField) { + this.func_178027_a((GuiTextField) parGui, parInt1, parFlag); + } else if (parGui instanceof GuiLabel) { + this.func_178025_a((GuiLabel) parGui, parInt1, parInt2, parInt3, parFlag); + } + + } + } + + private void func_178018_a(GuiTextField parGuiTextField, int parInt1, int parInt2, int parInt3) { + parGuiTextField.mouseClicked(parInt1, parInt2, parInt3); + if (parGuiTextField.isFocused()) { + this.field_178028_d = parGuiTextField; + } + + } + + private void func_178019_b(GuiButton parGuiButton, int parInt1, int parInt2, int parInt3) { + parGuiButton.mouseReleased(parInt1, parInt2); + } + + public Gui func_178021_b() { + return this.field_178030_c; + } + + public Gui func_178022_a() { + return this.field_178029_b; + } + + private boolean func_178023_a(GuiButton parGuiButton, int parInt1, int parInt2, int parInt3) { + boolean flag = parGuiButton.mousePressed(this.field_178031_a, parInt1, parInt2); + if (flag) { + this.field_178028_d = parGuiButton; + } + + return flag; + } + + private void func_178024_a(GuiButton parGuiButton, int parInt1, int parInt2, int parInt3, boolean parFlag) { + parGuiButton.yPosition = parInt1; + if (!parFlag) { + parGuiButton.drawButton(this.field_178031_a, parInt2, parInt3); + } + + } + + private void func_178025_a(GuiLabel parGuiLabel, int parInt1, int parInt2, int parInt3, boolean parFlag) { + parGuiLabel.field_146174_h = parInt1; + if (!parFlag) { + parGuiLabel.drawLabel(this.field_178031_a, parInt2, parInt3); + } + + } + + private boolean func_178026_a(Gui parGui, int parInt1, int parInt2, int parInt3) { + if (parGui == null) { + return false; + } else if (parGui instanceof GuiButton) { + return this.func_178023_a((GuiButton) parGui, parInt1, parInt2, parInt3); + } else { + if (parGui instanceof GuiTextField) { + this.func_178018_a((GuiTextField) parGui, parInt1, parInt2, parInt3); + } + + return false; + } + } + + private void func_178027_a(GuiTextField parGuiTextField, int parInt1, boolean parFlag) { + parGuiTextField.yPosition = parInt1; + if (!parFlag) { + parGuiTextField.drawTextBox(); + } + + } + + public boolean mousePressed(int var1, int i, int j, int k, int var5, int var6) { + if (k != 0 && k != 12345) + return false; + boolean touchMode = PointerInputAbstraction.isTouchMode(); + boolean flag = this.field_178029_b != null && (!touchMode || stupidCheck(this.field_178029_b, k)) + && this.func_178026_a(this.field_178029_b, i, j, k); + boolean flag1 = this.field_178030_c != null && (!touchMode || stupidCheck(this.field_178030_c, k)) + && this.func_178026_a(this.field_178030_c, i, j, k); + return flag || flag1; + } + + public void mouseReleased(int var1, int i, int j, int k, int var5, int var6) { + if (k != 0 && k != 12345) + return; + boolean touchMode = PointerInputAbstraction.isTouchMode(); + if (!touchMode || stupidCheck(field_178029_b, k)) + this.func_178016_b(this.field_178029_b, i, j, k); + if (!touchMode || stupidCheck(field_178030_c, k)) + this.func_178016_b(this.field_178030_c, i, j, k); + } + + public void setSelected(int var1, int var2, int i) { + this.func_178017_a(this.field_178029_b, i, 0, 0, true); + this.func_178017_a(this.field_178030_c, i, 0, 0, true); + } + } + + public static class GuiLabelEntry extends GuiPageButtonList.GuiListEntry { + public GuiLabelEntry(int parInt1, String parString1, boolean parFlag) { + super(parInt1, parString1, parFlag); + } + } + + public static class GuiListEntry { + private final int field_178939_a; + private final String field_178937_b; + private final boolean field_178938_c; + + public GuiListEntry(int parInt1, String parString1, boolean parFlag) { + this.field_178939_a = parInt1; + this.field_178937_b = parString1; + this.field_178938_c = parFlag; + } + + public boolean func_178934_d() { + return this.field_178938_c; + } + + public int func_178935_b() { + return this.field_178939_a; + } + + public String func_178936_c() { + return this.field_178937_b; + } + } + + public interface GuiResponder { + void func_175319_a(int var1, String var2); + + void func_175321_a(int var1, boolean var2); + + void onTick(int var1, float var2); + } + + public static class GuiSlideEntry extends GuiPageButtonList.GuiListEntry { + private final GuiSlider.FormatHelper field_178949_a; + private final float field_178947_b; + private final float field_178948_c; + private final float field_178946_d; + + public GuiSlideEntry(int parInt1, String parString1, boolean parFlag, GuiSlider.FormatHelper parFormatHelper, + float parFloat1, float parFloat2, float parFloat3) { + super(parInt1, parString1, parFlag); + this.field_178949_a = parFormatHelper; + this.field_178947_b = parFloat1; + this.field_178948_c = parFloat2; + this.field_178946_d = parFloat3; + } + + public float func_178942_g() { + return this.field_178946_d; + } + + public float func_178943_e() { + return this.field_178947_b; + } + + public float func_178944_f() { + return this.field_178948_c; + } + + public GuiSlider.FormatHelper func_178945_a() { + return this.field_178949_a; + } + } + private final List field_178074_u = Lists.newArrayList(); + private final IntHashMap field_178073_v = new IntHashMap(); + private final List field_178072_w = Lists.newArrayList(); + private final GuiPageButtonList.GuiListEntry[][] field_178078_x; + private int field_178077_y; + private GuiPageButtonList.GuiResponder field_178076_z; + private Gui field_178075_A; public GuiPageButtonList(Minecraft mcIn, int widthIn, int heightIn, int topIn, int bottomIn, int slotHeightIn, @@ -51,35 +297,10 @@ public class GuiPageButtonList extends GuiListExtended { this.func_178055_t(); } - private void func_178069_s() { - for (int n = 0; n < this.field_178078_x.length; ++n) { - GuiPageButtonList.GuiListEntry[] aguipagebuttonlist$guilistentry = this.field_178078_x[n]; - for (int i = 0; i < aguipagebuttonlist$guilistentry.length; i += 2) { - GuiPageButtonList.GuiListEntry guipagebuttonlist$guilistentry = aguipagebuttonlist$guilistentry[i]; - GuiPageButtonList.GuiListEntry guipagebuttonlist$guilistentry1 = i < aguipagebuttonlist$guilistentry.length - - 1 ? aguipagebuttonlist$guilistentry[i + 1] : null; - Gui gui = this.func_178058_a(guipagebuttonlist$guilistentry, 0, - guipagebuttonlist$guilistentry1 == null); - Gui gui1 = this.func_178058_a(guipagebuttonlist$guilistentry1, 160, - guipagebuttonlist$guilistentry == null); - GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = new GuiPageButtonList.GuiEntry(gui, gui1); - this.field_178074_u.add(guipagebuttonlist$guientry); - if (guipagebuttonlist$guilistentry != null && gui != null) { - this.field_178073_v.addKey(guipagebuttonlist$guilistentry.func_178935_b(), gui); - if (gui instanceof GuiTextField) { - this.field_178072_w.add((GuiTextField) gui); - } - } - - if (guipagebuttonlist$guilistentry1 != null && gui1 != null) { - this.field_178073_v.addKey(guipagebuttonlist$guilistentry1.func_178935_b(), gui1); - if (gui1 instanceof GuiTextField) { - this.field_178072_w.add((GuiTextField) gui1); - } - } - } + public void fireInputEvent(EnumInputEvent event, String param) { + for (GuiTextField txt : field_178072_w) { + txt.fireInputEvent(event, param); } - } private void func_178055_t() { @@ -99,44 +320,32 @@ public class GuiPageButtonList extends GuiListExtended { } - public void func_181156_c(int parInt1) { - if (parInt1 != this.field_178077_y) { - int i = this.field_178077_y; - this.field_178077_y = parInt1; - this.func_178055_t(); - this.func_178060_e(i, parInt1); - this.amountScrolled = 0.0F; - } - } - - public int func_178059_e() { - return this.field_178077_y; + public Gui func_178056_g() { + return this.field_178075_A; } public int func_178057_f() { return this.field_178078_x.length; } - public Gui func_178056_g() { - return this.field_178075_A; + private Gui func_178058_a(GuiPageButtonList.GuiListEntry parGuiListEntry, int parInt1, boolean parFlag) { + return (Gui) (parGuiListEntry instanceof GuiPageButtonList.GuiSlideEntry + ? this.func_178067_a(this.width / 2 - 155 + parInt1, 0, + (GuiPageButtonList.GuiSlideEntry) parGuiListEntry) + : (parGuiListEntry instanceof GuiPageButtonList.GuiButtonEntry + ? this.func_178065_a(this.width / 2 - 155 + parInt1, 0, + (GuiPageButtonList.GuiButtonEntry) parGuiListEntry) + : (parGuiListEntry instanceof GuiPageButtonList.EditBoxEntry + ? this.func_178068_a(this.width / 2 - 155 + parInt1, 0, + (GuiPageButtonList.EditBoxEntry) parGuiListEntry) + : (parGuiListEntry instanceof GuiPageButtonList.GuiLabelEntry + ? this.func_178063_a(this.width / 2 - 155 + parInt1, 0, + (GuiPageButtonList.GuiLabelEntry) parGuiListEntry, parFlag) + : null)))); } - public void func_178071_h() { - if (this.field_178077_y > 0) { - this.func_181156_c(this.field_178077_y - 1); - } - - } - - public void func_178064_i() { - if (this.field_178077_y < this.field_178078_x.length - 1) { - this.func_181156_c(this.field_178077_y + 1); - } - - } - - public Gui func_178061_c(int parInt1) { - return (Gui) this.field_178073_v.lookup(parInt1); + public int func_178059_e() { + return this.field_178077_y; } private void func_178060_e(int parInt1, int parInt2) { @@ -157,103 +366,8 @@ public class GuiPageButtonList extends GuiListExtended { } - private void func_178066_a(Gui parGui, boolean parFlag) { - if (parGui instanceof GuiButton) { - ((GuiButton) parGui).visible = parFlag; - } else if (parGui instanceof GuiTextField) { - ((GuiTextField) parGui).setVisible(parFlag); - } else if (parGui instanceof GuiLabel) { - ((GuiLabel) parGui).visible = parFlag; - } - - } - - private Gui func_178058_a(GuiPageButtonList.GuiListEntry parGuiListEntry, int parInt1, boolean parFlag) { - return (Gui) (parGuiListEntry instanceof GuiPageButtonList.GuiSlideEntry - ? this.func_178067_a(this.width / 2 - 155 + parInt1, 0, - (GuiPageButtonList.GuiSlideEntry) parGuiListEntry) - : (parGuiListEntry instanceof GuiPageButtonList.GuiButtonEntry - ? this.func_178065_a(this.width / 2 - 155 + parInt1, 0, - (GuiPageButtonList.GuiButtonEntry) parGuiListEntry) - : (parGuiListEntry instanceof GuiPageButtonList.EditBoxEntry - ? this.func_178068_a(this.width / 2 - 155 + parInt1, 0, - (GuiPageButtonList.EditBoxEntry) parGuiListEntry) - : (parGuiListEntry instanceof GuiPageButtonList.GuiLabelEntry - ? this.func_178063_a(this.width / 2 - 155 + parInt1, 0, - (GuiPageButtonList.GuiLabelEntry) parGuiListEntry, parFlag) - : null)))); - } - - public void func_181155_a(boolean parFlag) { - for (int i = 0, l = this.field_178074_u.size(); i < l; ++i) { - GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = this.field_178074_u.get(i); - if (guipagebuttonlist$guientry.field_178029_b instanceof GuiButton) { - ((GuiButton) guipagebuttonlist$guientry.field_178029_b).enabled = parFlag; - } - - if (guipagebuttonlist$guientry.field_178030_c instanceof GuiButton) { - ((GuiButton) guipagebuttonlist$guientry.field_178030_c).enabled = parFlag; - } - } - - } - - public boolean mouseClicked(int i, int j, int k) { - boolean flag = super.mouseClicked(i, j, k); - int l = this.getSlotIndexFromScreenCoords(i, j); - if (l >= 0) { - GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = this.getListEntry(l); - if (this.field_178075_A != guipagebuttonlist$guientry.field_178028_d && this.field_178075_A != null - && this.field_178075_A instanceof GuiTextField) { - ((GuiTextField) this.field_178075_A).setFocused(false); - } - - this.field_178075_A = guipagebuttonlist$guientry.field_178028_d; - } - - return flag; - } - - private GuiSlider func_178067_a(int parInt1, int parInt2, GuiPageButtonList.GuiSlideEntry parGuiSlideEntry) { - GuiSlider guislider = new GuiSlider(this.field_178076_z, parGuiSlideEntry.func_178935_b(), parInt1, parInt2, - parGuiSlideEntry.func_178936_c(), parGuiSlideEntry.func_178943_e(), parGuiSlideEntry.func_178944_f(), - parGuiSlideEntry.func_178942_g(), parGuiSlideEntry.func_178945_a()); - guislider.visible = parGuiSlideEntry.func_178934_d(); - return guislider; - } - - private GuiListButton func_178065_a(int parInt1, int parInt2, GuiPageButtonList.GuiButtonEntry parGuiButtonEntry) { - GuiListButton guilistbutton = new GuiListButton(this.field_178076_z, parGuiButtonEntry.func_178935_b(), parInt1, - parInt2, parGuiButtonEntry.func_178936_c(), parGuiButtonEntry.func_178940_a()); - guilistbutton.visible = parGuiButtonEntry.func_178934_d(); - return guilistbutton; - } - - private GuiTextField func_178068_a(int parInt1, int parInt2, GuiPageButtonList.EditBoxEntry parEditBoxEntry) { - GuiTextField guitextfield = new GuiTextField(parEditBoxEntry.func_178935_b(), this.mc.fontRendererObj, parInt1, - parInt2, 150, 20); - guitextfield.setText(parEditBoxEntry.func_178936_c()); - guitextfield.func_175207_a(this.field_178076_z); - guitextfield.setVisible(parEditBoxEntry.func_178934_d()); - guitextfield.func_175205_a(parEditBoxEntry.func_178950_a()); - return guitextfield; - } - - private GuiLabel func_178063_a(int parInt1, int parInt2, GuiPageButtonList.GuiLabelEntry parGuiLabelEntry, - boolean parFlag) { - GuiLabel guilabel; - if (parFlag) { - guilabel = new GuiLabel(this.mc.fontRendererObj, parGuiLabelEntry.func_178935_b(), parInt1, parInt2, - this.width - parInt1 * 2, 20, -1); - } else { - guilabel = new GuiLabel(this.mc.fontRendererObj, parGuiLabelEntry.func_178935_b(), parInt1, parInt2, 150, - 20, -1); - } - - guilabel.visible = parGuiLabelEntry.func_178934_d(); - guilabel.func_175202_a(parGuiLabelEntry.func_178936_c()); - guilabel.setCentered(); - return guilabel; + public Gui func_178061_c(int parInt1) { + return (Gui) this.field_178073_v.lookup(parInt1); } public void func_178062_a(char parChar1, int parInt1) { @@ -312,19 +426,137 @@ public class GuiPageButtonList extends GuiListExtended { } } - /**+ - * Gets the IGuiListEntry object for the given index + private GuiLabel func_178063_a(int parInt1, int parInt2, GuiPageButtonList.GuiLabelEntry parGuiLabelEntry, + boolean parFlag) { + GuiLabel guilabel; + if (parFlag) { + guilabel = new GuiLabel(this.mc.fontRendererObj, parGuiLabelEntry.func_178935_b(), parInt1, parInt2, + this.width - parInt1 * 2, 20, -1); + } else { + guilabel = new GuiLabel(this.mc.fontRendererObj, parGuiLabelEntry.func_178935_b(), parInt1, parInt2, 150, + 20, -1); + } + + guilabel.visible = parGuiLabelEntry.func_178934_d(); + guilabel.func_175202_a(parGuiLabelEntry.func_178936_c()); + guilabel.setCentered(); + return guilabel; + } + + public void func_178064_i() { + if (this.field_178077_y < this.field_178078_x.length - 1) { + this.func_181156_c(this.field_178077_y + 1); + } + + } + + private GuiListButton func_178065_a(int parInt1, int parInt2, GuiPageButtonList.GuiButtonEntry parGuiButtonEntry) { + GuiListButton guilistbutton = new GuiListButton(this.field_178076_z, parGuiButtonEntry.func_178935_b(), parInt1, + parInt2, parGuiButtonEntry.func_178936_c(), parGuiButtonEntry.func_178940_a()); + guilistbutton.visible = parGuiButtonEntry.func_178934_d(); + return guilistbutton; + } + + private void func_178066_a(Gui parGui, boolean parFlag) { + if (parGui instanceof GuiButton) { + ((GuiButton) parGui).visible = parFlag; + } else if (parGui instanceof GuiTextField) { + ((GuiTextField) parGui).setVisible(parFlag); + } else if (parGui instanceof GuiLabel) { + ((GuiLabel) parGui).visible = parFlag; + } + + } + + private GuiSlider func_178067_a(int parInt1, int parInt2, GuiPageButtonList.GuiSlideEntry parGuiSlideEntry) { + GuiSlider guislider = new GuiSlider(this.field_178076_z, parGuiSlideEntry.func_178935_b(), parInt1, parInt2, + parGuiSlideEntry.func_178936_c(), parGuiSlideEntry.func_178943_e(), parGuiSlideEntry.func_178944_f(), + parGuiSlideEntry.func_178942_g(), parGuiSlideEntry.func_178945_a()); + guislider.visible = parGuiSlideEntry.func_178934_d(); + return guislider; + } + + private GuiTextField func_178068_a(int parInt1, int parInt2, GuiPageButtonList.EditBoxEntry parEditBoxEntry) { + GuiTextField guitextfield = new GuiTextField(parEditBoxEntry.func_178935_b(), this.mc.fontRendererObj, parInt1, + parInt2, 150, 20); + guitextfield.setText(parEditBoxEntry.func_178936_c()); + guitextfield.func_175207_a(this.field_178076_z); + guitextfield.setVisible(parEditBoxEntry.func_178934_d()); + guitextfield.func_175205_a(parEditBoxEntry.func_178950_a()); + return guitextfield; + } + + private void func_178069_s() { + for (int n = 0; n < this.field_178078_x.length; ++n) { + GuiPageButtonList.GuiListEntry[] aguipagebuttonlist$guilistentry = this.field_178078_x[n]; + for (int i = 0; i < aguipagebuttonlist$guilistentry.length; i += 2) { + GuiPageButtonList.GuiListEntry guipagebuttonlist$guilistentry = aguipagebuttonlist$guilistentry[i]; + GuiPageButtonList.GuiListEntry guipagebuttonlist$guilistentry1 = i < aguipagebuttonlist$guilistentry.length + - 1 ? aguipagebuttonlist$guilistentry[i + 1] : null; + Gui gui = this.func_178058_a(guipagebuttonlist$guilistentry, 0, + guipagebuttonlist$guilistentry1 == null); + Gui gui1 = this.func_178058_a(guipagebuttonlist$guilistentry1, 160, + guipagebuttonlist$guilistentry == null); + GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = new GuiPageButtonList.GuiEntry(gui, gui1); + this.field_178074_u.add(guipagebuttonlist$guientry); + if (guipagebuttonlist$guilistentry != null && gui != null) { + this.field_178073_v.addKey(guipagebuttonlist$guilistentry.func_178935_b(), gui); + if (gui instanceof GuiTextField) { + this.field_178072_w.add((GuiTextField) gui); + } + } + + if (guipagebuttonlist$guilistentry1 != null && gui1 != null) { + this.field_178073_v.addKey(guipagebuttonlist$guilistentry1.func_178935_b(), gui1); + if (gui1 instanceof GuiTextField) { + this.field_178072_w.add((GuiTextField) gui1); + } + } + } + } + + } + + public void func_178071_h() { + if (this.field_178077_y > 0) { + this.func_181156_c(this.field_178077_y - 1); + } + + } + + public void func_181155_a(boolean parFlag) { + for (int i = 0, l = this.field_178074_u.size(); i < l; ++i) { + GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = this.field_178074_u.get(i); + if (guipagebuttonlist$guientry.field_178029_b instanceof GuiButton) { + ((GuiButton) guipagebuttonlist$guientry.field_178029_b).enabled = parFlag; + } + + if (guipagebuttonlist$guientry.field_178030_c instanceof GuiButton) { + ((GuiButton) guipagebuttonlist$guientry.field_178030_c).enabled = parFlag; + } + } + + } + + public void func_181156_c(int parInt1) { + if (parInt1 != this.field_178077_y) { + int i = this.field_178077_y; + this.field_178077_y = parInt1; + this.func_178055_t(); + this.func_178060_e(i, parInt1); + this.amountScrolled = 0.0F; + } + } + + /** + * + Gets the IGuiListEntry object for the given index */ public GuiPageButtonList.GuiEntry getListEntry(int i) { return (GuiPageButtonList.GuiEntry) this.field_178074_u.get(i); } - public int getSize() { - return this.field_178074_u.size(); - } - - /**+ - * Gets the width of the list + /** + * + Gets the width of the list */ public int getListWidth() { return 400; @@ -334,6 +566,10 @@ public class GuiPageButtonList extends GuiListExtended { return super.getScrollBarX() + 32; } + public int getSize() { + return this.field_178074_u.size(); + } + public boolean isTextFieldFocused() { for (GuiTextField txt : field_178072_w) { if (txt.isFocused()) { @@ -343,245 +579,19 @@ public class GuiPageButtonList extends GuiListExtended { return false; } - public void fireInputEvent(EnumInputEvent event, String param) { - for (GuiTextField txt : field_178072_w) { - txt.fireInputEvent(event, param); - } - } - - public static class EditBoxEntry extends GuiPageButtonList.GuiListEntry { - private final Predicate field_178951_a; - - public EditBoxEntry(int parInt1, String parString1, boolean parFlag, Predicate parPredicate) { - super(parInt1, parString1, parFlag); - this.field_178951_a = (Predicate) Objects.firstNonNull(parPredicate, Predicates.alwaysTrue()); - } - - public Predicate func_178950_a() { - return this.field_178951_a; - } - } - - public static class GuiButtonEntry extends GuiPageButtonList.GuiListEntry { - private final boolean field_178941_a; - - public GuiButtonEntry(int parInt1, String parString1, boolean parFlag, boolean parFlag2) { - super(parInt1, parString1, parFlag); - this.field_178941_a = parFlag2; - } - - public boolean func_178940_a() { - return this.field_178941_a; - } - } - - public static class GuiEntry implements GuiListExtended.IGuiListEntry { - private final Minecraft field_178031_a = Minecraft.getMinecraft(); - private final Gui field_178029_b; - private final Gui field_178030_c; - private Gui field_178028_d; - - public GuiEntry(Gui parGui, Gui parGui2) { - this.field_178029_b = parGui; - this.field_178030_c = parGui2; - } - - public Gui func_178022_a() { - return this.field_178029_b; - } - - public Gui func_178021_b() { - return this.field_178030_c; - } - - public void drawEntry(int var1, int var2, int i, int var4, int var5, int j, int k, boolean var8) { - this.func_178017_a(this.field_178029_b, i, j, k, false); - this.func_178017_a(this.field_178030_c, i, j, k, false); - } - - private void func_178017_a(Gui parGui, int parInt1, int parInt2, int parInt3, boolean parFlag) { - if (parGui != null) { - if (parGui instanceof GuiButton) { - this.func_178024_a((GuiButton) parGui, parInt1, parInt2, parInt3, parFlag); - } else if (parGui instanceof GuiTextField) { - this.func_178027_a((GuiTextField) parGui, parInt1, parFlag); - } else if (parGui instanceof GuiLabel) { - this.func_178025_a((GuiLabel) parGui, parInt1, parInt2, parInt3, parFlag); - } - - } - } - - private void func_178024_a(GuiButton parGuiButton, int parInt1, int parInt2, int parInt3, boolean parFlag) { - parGuiButton.yPosition = parInt1; - if (!parFlag) { - parGuiButton.drawButton(this.field_178031_a, parInt2, parInt3); + public boolean mouseClicked(int i, int j, int k) { + boolean flag = super.mouseClicked(i, j, k); + int l = this.getSlotIndexFromScreenCoords(i, j); + if (l >= 0) { + GuiPageButtonList.GuiEntry guipagebuttonlist$guientry = this.getListEntry(l); + if (this.field_178075_A != guipagebuttonlist$guientry.field_178028_d && this.field_178075_A != null + && this.field_178075_A instanceof GuiTextField) { + ((GuiTextField) this.field_178075_A).setFocused(false); } + this.field_178075_A = guipagebuttonlist$guientry.field_178028_d; } - private void func_178027_a(GuiTextField parGuiTextField, int parInt1, boolean parFlag) { - parGuiTextField.yPosition = parInt1; - if (!parFlag) { - parGuiTextField.drawTextBox(); - } - - } - - private void func_178025_a(GuiLabel parGuiLabel, int parInt1, int parInt2, int parInt3, boolean parFlag) { - parGuiLabel.field_146174_h = parInt1; - if (!parFlag) { - parGuiLabel.drawLabel(this.field_178031_a, parInt2, parInt3); - } - - } - - public void setSelected(int var1, int var2, int i) { - this.func_178017_a(this.field_178029_b, i, 0, 0, true); - this.func_178017_a(this.field_178030_c, i, 0, 0, true); - } - - public boolean mousePressed(int var1, int i, int j, int k, int var5, int var6) { - if (k != 0 && k != 12345) - return false; - boolean touchMode = PointerInputAbstraction.isTouchMode(); - boolean flag = this.field_178029_b != null && (!touchMode || stupidCheck(this.field_178029_b, k)) - && this.func_178026_a(this.field_178029_b, i, j, k); - boolean flag1 = this.field_178030_c != null && (!touchMode || stupidCheck(this.field_178030_c, k)) - && this.func_178026_a(this.field_178030_c, i, j, k); - return flag || flag1; - } - - private static boolean stupidCheck(Gui gui, int k) { - if (gui instanceof GuiButton) { - return ((GuiButton) gui).isSliderTouchEvents() == (k == 12345); - } else { - return k != 12345; - } - } - - private boolean func_178026_a(Gui parGui, int parInt1, int parInt2, int parInt3) { - if (parGui == null) { - return false; - } else if (parGui instanceof GuiButton) { - return this.func_178023_a((GuiButton) parGui, parInt1, parInt2, parInt3); - } else { - if (parGui instanceof GuiTextField) { - this.func_178018_a((GuiTextField) parGui, parInt1, parInt2, parInt3); - } - - return false; - } - } - - private boolean func_178023_a(GuiButton parGuiButton, int parInt1, int parInt2, int parInt3) { - boolean flag = parGuiButton.mousePressed(this.field_178031_a, parInt1, parInt2); - if (flag) { - this.field_178028_d = parGuiButton; - } - - return flag; - } - - private void func_178018_a(GuiTextField parGuiTextField, int parInt1, int parInt2, int parInt3) { - parGuiTextField.mouseClicked(parInt1, parInt2, parInt3); - if (parGuiTextField.isFocused()) { - this.field_178028_d = parGuiTextField; - } - - } - - public void mouseReleased(int var1, int i, int j, int k, int var5, int var6) { - if (k != 0 && k != 12345) - return; - boolean touchMode = PointerInputAbstraction.isTouchMode(); - if (!touchMode || stupidCheck(field_178029_b, k)) - this.func_178016_b(this.field_178029_b, i, j, k); - if (!touchMode || stupidCheck(field_178030_c, k)) - this.func_178016_b(this.field_178030_c, i, j, k); - } - - private void func_178016_b(Gui parGui, int parInt1, int parInt2, int parInt3) { - if (parGui != null) { - if (parGui instanceof GuiButton) { - this.func_178019_b((GuiButton) parGui, parInt1, parInt2, parInt3); - } - - } - } - - private void func_178019_b(GuiButton parGuiButton, int parInt1, int parInt2, int parInt3) { - parGuiButton.mouseReleased(parInt1, parInt2); - } - } - - public static class GuiLabelEntry extends GuiPageButtonList.GuiListEntry { - public GuiLabelEntry(int parInt1, String parString1, boolean parFlag) { - super(parInt1, parString1, parFlag); - } - } - - public static class GuiListEntry { - private final int field_178939_a; - private final String field_178937_b; - private final boolean field_178938_c; - - public GuiListEntry(int parInt1, String parString1, boolean parFlag) { - this.field_178939_a = parInt1; - this.field_178937_b = parString1; - this.field_178938_c = parFlag; - } - - public int func_178935_b() { - return this.field_178939_a; - } - - public String func_178936_c() { - return this.field_178937_b; - } - - public boolean func_178934_d() { - return this.field_178938_c; - } - } - - public interface GuiResponder { - void func_175321_a(int var1, boolean var2); - - void onTick(int var1, float var2); - - void func_175319_a(int var1, String var2); - } - - public static class GuiSlideEntry extends GuiPageButtonList.GuiListEntry { - private final GuiSlider.FormatHelper field_178949_a; - private final float field_178947_b; - private final float field_178948_c; - private final float field_178946_d; - - public GuiSlideEntry(int parInt1, String parString1, boolean parFlag, GuiSlider.FormatHelper parFormatHelper, - float parFloat1, float parFloat2, float parFloat3) { - super(parInt1, parString1, parFlag); - this.field_178949_a = parFormatHelper; - this.field_178947_b = parFloat1; - this.field_178948_c = parFloat2; - this.field_178946_d = parFloat3; - } - - public GuiSlider.FormatHelper func_178945_a() { - return this.field_178949_a; - } - - public float func_178943_e() { - return this.field_178947_b; - } - - public float func_178944_f() { - return this.field_178948_c; - } - - public float func_178942_g() { - return this.field_178946_d; - } + return flag; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiPlayerTabOverlay.java b/src/game/java/net/minecraft/client/gui/GuiPlayerTabOverlay.java index 7edb1f27..becb8bdd 100644 --- a/src/game/java/net/minecraft/client/gui/GuiPlayerTabOverlay.java +++ b/src/game/java/net/minecraft/client/gui/GuiPlayerTabOverlay.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.util.Comparator; import java.util.List; @@ -24,27 +25,48 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.MathHelper; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiPlayerTabOverlay extends Gui { + static class PlayerComparator implements Comparator { + private PlayerComparator() { + } + + public int compare(NetworkPlayerInfo networkplayerinfo, NetworkPlayerInfo networkplayerinfo1) { + ScorePlayerTeam scoreplayerteam = networkplayerinfo.getPlayerTeam(); + ScorePlayerTeam scoreplayerteam1 = networkplayerinfo1.getPlayerTeam(); + return ComparisonChain.start() + .compareTrueFirst(networkplayerinfo.getGameType() != WorldSettings.GameType.SPECTATOR, + networkplayerinfo1.getGameType() != WorldSettings.GameType.SPECTATOR) + .compare(scoreplayerteam != null ? scoreplayerteam.getRegisteredName() : "", + scoreplayerteam1 != null ? scoreplayerteam1.getRegisteredName() : "") + .compare(networkplayerinfo.getGameProfile().getName(), + networkplayerinfo1.getGameProfile().getName()) + .result(); + } + } + private static final Ordering field_175252_a = Ordering .from(new GuiPlayerTabOverlay.PlayerComparator()); private final Minecraft mc; @@ -52,6 +74,7 @@ public class GuiPlayerTabOverlay extends Gui { private IChatComponent footer; private IChatComponent header; private long lastTimeOpened; + private boolean isBeingRendered; public GuiPlayerTabOverlay(Minecraft mcIn, GuiIngame guiIngameIn) { @@ -59,9 +82,121 @@ public class GuiPlayerTabOverlay extends Gui { this.guiIngame = guiIngameIn; } - /**+ - * Returns the name that should be renderd for the player - * supplied + protected void drawPing(int networkPlayerInfoIn, int parInt2, int parInt3, NetworkPlayerInfo parNetworkPlayerInfo) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(icons); + byte b0 = 0; + byte b1 = 0; + if (parNetworkPlayerInfo.getResponseTime() < 0) { + b1 = 5; + } else if (parNetworkPlayerInfo.getResponseTime() < 150) { + b1 = 0; + } else if (parNetworkPlayerInfo.getResponseTime() < 300) { + b1 = 1; + } else if (parNetworkPlayerInfo.getResponseTime() < 600) { + b1 = 2; + } else if (parNetworkPlayerInfo.getResponseTime() < 1000) { + b1 = 3; + } else { + b1 = 4; + } + + this.zLevel += 100.0F; + this.drawTexturedModalRect(parInt2 + networkPlayerInfoIn - 11, parInt3, 0 + b0 * 10, 176 + b1 * 8, 10, 8); + this.zLevel -= 100.0F; + } + + private void drawScoreboardValues(ScoreObjective parScoreObjective, int parInt1, String parString1, int parInt2, + int parInt3, NetworkPlayerInfo parNetworkPlayerInfo) { + int i = parScoreObjective.getScoreboard().getValueFromObjective(parString1, parScoreObjective).getScorePoints(); + if (parScoreObjective.getRenderType() == IScoreObjectiveCriteria.EnumRenderType.HEARTS) { + this.mc.getTextureManager().bindTexture(icons); + if (this.lastTimeOpened == parNetworkPlayerInfo.func_178855_p()) { + if (i < parNetworkPlayerInfo.func_178835_l()) { + parNetworkPlayerInfo.func_178846_a(Minecraft.getSystemTime()); + parNetworkPlayerInfo.func_178844_b((long) (this.guiIngame.getUpdateCounter() + 20)); + } else if (i > parNetworkPlayerInfo.func_178835_l()) { + parNetworkPlayerInfo.func_178846_a(Minecraft.getSystemTime()); + parNetworkPlayerInfo.func_178844_b((long) (this.guiIngame.getUpdateCounter() + 10)); + } + } + + if (Minecraft.getSystemTime() - parNetworkPlayerInfo.func_178847_n() > 1000L + || this.lastTimeOpened != parNetworkPlayerInfo.func_178855_p()) { + parNetworkPlayerInfo.func_178836_b(i); + parNetworkPlayerInfo.func_178857_c(i); + parNetworkPlayerInfo.func_178846_a(Minecraft.getSystemTime()); + } + + parNetworkPlayerInfo.func_178843_c(this.lastTimeOpened); + parNetworkPlayerInfo.func_178836_b(i); + int j = MathHelper.ceiling_float_int((float) Math.max(i, parNetworkPlayerInfo.func_178860_m()) / 2.0F); + int k = Math.max(MathHelper.ceiling_float_int((float) (i / 2)), + Math.max(MathHelper.ceiling_float_int((float) (parNetworkPlayerInfo.func_178860_m() / 2)), 10)); + boolean flag = parNetworkPlayerInfo.func_178858_o() > (long) this.guiIngame.getUpdateCounter() + && (parNetworkPlayerInfo.func_178858_o() - (long) this.guiIngame.getUpdateCounter()) / 3L + % 2L == 1L; + if (j > 0) { + float f = Math.min((float) (parInt3 - parInt2 - 4) / (float) k, 9.0F); + if (f > 3.0F) { + for (int l = j; l < k; ++l) { + this.drawTexturedModalRect((float) parInt2 + (float) l * f, (float) parInt1, flag ? 25 : 16, 0, + 9, 9); + } + + for (int j1 = 0; j1 < j; ++j1) { + this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, flag ? 25 : 16, 0, + 9, 9); + if (flag) { + if (j1 * 2 + 1 < parNetworkPlayerInfo.func_178860_m()) { + this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, 70, 0, 9, + 9); + } + + if (j1 * 2 + 1 == parNetworkPlayerInfo.func_178860_m()) { + this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, 79, 0, 9, + 9); + } + } + + if (j1 * 2 + 1 < i) { + this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, + j1 >= 10 ? 160 : 52, 0, 9, 9); + } + + if (j1 * 2 + 1 == i) { + this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, + j1 >= 10 ? 169 : 61, 0, 9, 9); + } + } + } else { + float f1 = MathHelper.clamp_float((float) i / 20.0F, 0.0F, 1.0F); + int i1 = (int) ((1.0F - f1) * 255.0F) << 16 | (int) (f1 * 255.0F) << 8; + String s = "" + (float) i / 2.0F; + if (parInt3 - this.mc.fontRendererObj.getStringWidth(s + "hp") >= parInt2) { + s = s + "hp"; + } + + this.mc.fontRendererObj.drawStringWithShadow(s, + (float) ((parInt3 + parInt2) / 2 - this.mc.fontRendererObj.getStringWidth(s) / 2), + (float) parInt1, i1); + } + } + } else { + String s1 = EnumChatFormatting.YELLOW + "" + i; + this.mc.fontRendererObj.drawStringWithShadow(s1, + (float) (parInt3 - this.mc.fontRendererObj.getStringWidth(s1)), (float) parInt1, 16777215); + } + + } + + public void func_181030_a() { + this.header = null; + this.footer = null; + } + + /** + * + Returns the name that should be renderd for the player supplied */ public String getPlayerName(NetworkPlayerInfo networkPlayerInfoIn) { IChatComponent dname = networkPlayerInfoIn.getDisplayNameProfanityFilter(); @@ -70,20 +205,8 @@ public class GuiPlayerTabOverlay extends Gui { networkPlayerInfoIn.getGameProfileNameProfanityFilter()); } - /**+ - * Called by GuiIngame to update the information stored in the - * playerlist, does not actually render the list, however. - */ - public void updatePlayerList(boolean willBeRendered) { - if (willBeRendered && !this.isBeingRendered) { - this.lastTimeOpened = Minecraft.getSystemTime(); - } - - this.isBeingRendered = willBeRendered; - } - - /**+ - * Renders the playerlist, its background, headers and footers. + /** + * + Renders the playerlist, its background, headers and footers. */ public void renderPlayerlist(int width, Scoreboard scoreboardIn, ScoreObjective scoreObjectiveIn) { NetHandlerPlayClient nethandlerplayclient = this.mc.thePlayer.sendQueue; @@ -229,114 +352,6 @@ public class GuiPlayerTabOverlay extends Gui { } - protected void drawPing(int networkPlayerInfoIn, int parInt2, int parInt3, NetworkPlayerInfo parNetworkPlayerInfo) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(icons); - byte b0 = 0; - byte b1 = 0; - if (parNetworkPlayerInfo.getResponseTime() < 0) { - b1 = 5; - } else if (parNetworkPlayerInfo.getResponseTime() < 150) { - b1 = 0; - } else if (parNetworkPlayerInfo.getResponseTime() < 300) { - b1 = 1; - } else if (parNetworkPlayerInfo.getResponseTime() < 600) { - b1 = 2; - } else if (parNetworkPlayerInfo.getResponseTime() < 1000) { - b1 = 3; - } else { - b1 = 4; - } - - this.zLevel += 100.0F; - this.drawTexturedModalRect(parInt2 + networkPlayerInfoIn - 11, parInt3, 0 + b0 * 10, 176 + b1 * 8, 10, 8); - this.zLevel -= 100.0F; - } - - private void drawScoreboardValues(ScoreObjective parScoreObjective, int parInt1, String parString1, int parInt2, - int parInt3, NetworkPlayerInfo parNetworkPlayerInfo) { - int i = parScoreObjective.getScoreboard().getValueFromObjective(parString1, parScoreObjective).getScorePoints(); - if (parScoreObjective.getRenderType() == IScoreObjectiveCriteria.EnumRenderType.HEARTS) { - this.mc.getTextureManager().bindTexture(icons); - if (this.lastTimeOpened == parNetworkPlayerInfo.func_178855_p()) { - if (i < parNetworkPlayerInfo.func_178835_l()) { - parNetworkPlayerInfo.func_178846_a(Minecraft.getSystemTime()); - parNetworkPlayerInfo.func_178844_b((long) (this.guiIngame.getUpdateCounter() + 20)); - } else if (i > parNetworkPlayerInfo.func_178835_l()) { - parNetworkPlayerInfo.func_178846_a(Minecraft.getSystemTime()); - parNetworkPlayerInfo.func_178844_b((long) (this.guiIngame.getUpdateCounter() + 10)); - } - } - - if (Minecraft.getSystemTime() - parNetworkPlayerInfo.func_178847_n() > 1000L - || this.lastTimeOpened != parNetworkPlayerInfo.func_178855_p()) { - parNetworkPlayerInfo.func_178836_b(i); - parNetworkPlayerInfo.func_178857_c(i); - parNetworkPlayerInfo.func_178846_a(Minecraft.getSystemTime()); - } - - parNetworkPlayerInfo.func_178843_c(this.lastTimeOpened); - parNetworkPlayerInfo.func_178836_b(i); - int j = MathHelper.ceiling_float_int((float) Math.max(i, parNetworkPlayerInfo.func_178860_m()) / 2.0F); - int k = Math.max(MathHelper.ceiling_float_int((float) (i / 2)), - Math.max(MathHelper.ceiling_float_int((float) (parNetworkPlayerInfo.func_178860_m() / 2)), 10)); - boolean flag = parNetworkPlayerInfo.func_178858_o() > (long) this.guiIngame.getUpdateCounter() - && (parNetworkPlayerInfo.func_178858_o() - (long) this.guiIngame.getUpdateCounter()) / 3L - % 2L == 1L; - if (j > 0) { - float f = Math.min((float) (parInt3 - parInt2 - 4) / (float) k, 9.0F); - if (f > 3.0F) { - for (int l = j; l < k; ++l) { - this.drawTexturedModalRect((float) parInt2 + (float) l * f, (float) parInt1, flag ? 25 : 16, 0, - 9, 9); - } - - for (int j1 = 0; j1 < j; ++j1) { - this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, flag ? 25 : 16, 0, - 9, 9); - if (flag) { - if (j1 * 2 + 1 < parNetworkPlayerInfo.func_178860_m()) { - this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, 70, 0, 9, - 9); - } - - if (j1 * 2 + 1 == parNetworkPlayerInfo.func_178860_m()) { - this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, 79, 0, 9, - 9); - } - } - - if (j1 * 2 + 1 < i) { - this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, - j1 >= 10 ? 160 : 52, 0, 9, 9); - } - - if (j1 * 2 + 1 == i) { - this.drawTexturedModalRect((float) parInt2 + (float) j1 * f, (float) parInt1, - j1 >= 10 ? 169 : 61, 0, 9, 9); - } - } - } else { - float f1 = MathHelper.clamp_float((float) i / 20.0F, 0.0F, 1.0F); - int i1 = (int) ((1.0F - f1) * 255.0F) << 16 | (int) (f1 * 255.0F) << 8; - String s = "" + (float) i / 2.0F; - if (parInt3 - this.mc.fontRendererObj.getStringWidth(s + "hp") >= parInt2) { - s = s + "hp"; - } - - this.mc.fontRendererObj.drawStringWithShadow(s, - (float) ((parInt3 + parInt2) / 2 - this.mc.fontRendererObj.getStringWidth(s) / 2), - (float) parInt1, i1); - } - } - } else { - String s1 = EnumChatFormatting.YELLOW + "" + i; - this.mc.fontRendererObj.drawStringWithShadow(s1, - (float) (parInt3 - this.mc.fontRendererObj.getStringWidth(s1)), (float) parInt1, 16777215); - } - - } - public void setFooter(IChatComponent footerIn) { this.footer = footerIn; } @@ -345,26 +360,15 @@ public class GuiPlayerTabOverlay extends Gui { this.header = headerIn; } - public void func_181030_a() { - this.header = null; - this.footer = null; - } - - static class PlayerComparator implements Comparator { - private PlayerComparator() { + /** + * + Called by GuiIngame to update the information stored in the playerlist, + * does not actually render the list, however. + */ + public void updatePlayerList(boolean willBeRendered) { + if (willBeRendered && !this.isBeingRendered) { + this.lastTimeOpened = Minecraft.getSystemTime(); } - public int compare(NetworkPlayerInfo networkplayerinfo, NetworkPlayerInfo networkplayerinfo1) { - ScorePlayerTeam scoreplayerteam = networkplayerinfo.getPlayerTeam(); - ScorePlayerTeam scoreplayerteam1 = networkplayerinfo1.getPlayerTeam(); - return ComparisonChain.start() - .compareTrueFirst(networkplayerinfo.getGameType() != WorldSettings.GameType.SPECTATOR, - networkplayerinfo1.getGameType() != WorldSettings.GameType.SPECTATOR) - .compare(scoreplayerteam != null ? scoreplayerteam.getRegisteredName() : "", - scoreplayerteam1 != null ? scoreplayerteam1.getRegisteredName() : "") - .compare(networkplayerinfo.getGameProfile().getName(), - networkplayerinfo1.getGameProfile().getName()) - .result(); - } + this.isBeingRendered = willBeRendered; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiRenameWorld.java b/src/game/java/net/minecraft/client/gui/GuiRenameWorld.java index 60947e19..54d6c157 100644 --- a/src/game/java/net/minecraft/client/gui/GuiRenameWorld.java +++ b/src/game/java/net/minecraft/client/gui/GuiRenameWorld.java @@ -8,22 +8,25 @@ import net.minecraft.client.resources.I18n; import net.minecraft.world.storage.ISaveFormat; import net.minecraft.world.storage.WorldInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,47 +49,9 @@ public class GuiRenameWorld extends GuiScreen { this.duplicate = duplicate; } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.field_146583_f.updateCursorCounter(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, - I18n.format(duplicate ? "selectWorld.duplicateButton" : "selectWorld.renameButton", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, - I18n.format("gui.cancel", new Object[0]))); - ISaveFormat isaveformat = this.mc.getSaveLoader(); - WorldInfo worldinfo = isaveformat.getWorldInfo(this.saveName); - String s = worldinfo.getWorldName(); - if (duplicate) { - s += " copy"; - } - this.field_146583_f = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); - this.field_146583_f.setFocused(true); - this.field_146583_f.setText(s); - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -109,33 +74,9 @@ public class GuiRenameWorld extends GuiScreen { } } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - this.field_146583_f.textboxKeyTyped(parChar1, parInt1); - ((GuiButton) this.buttonList.get(0)).enabled = this.field_146583_f.getText().trim().length() > 0; - if (parInt1 == 28 || parInt1 == 156) { - this.actionPerformed((GuiButton) this.buttonList.get(0)); - } - - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - this.field_146583_f.mouseClicked(parInt1, parInt2, parInt3); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -148,14 +89,73 @@ public class GuiRenameWorld extends GuiScreen { super.drawScreen(i, j, f); } - @Override - public boolean showCopyPasteButtons() { - return field_146583_f.isFocused(); - } - @Override public void fireInputEvent(EnumInputEvent event, String param) { field_146583_f.fireInputEvent(event, param); } + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, + I18n.format(duplicate ? "selectWorld.duplicateButton" : "selectWorld.renameButton", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, + I18n.format("gui.cancel", new Object[0]))); + ISaveFormat isaveformat = this.mc.getSaveLoader(); + WorldInfo worldinfo = isaveformat.getWorldInfo(this.saveName); + String s = worldinfo.getWorldName(); + if (duplicate) { + s += " copy"; + } + this.field_146583_f = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20); + this.field_146583_f.setFocused(true); + this.field_146583_f.setText(s); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + this.field_146583_f.textboxKeyTyped(parChar1, parInt1); + ((GuiButton) this.buttonList.get(0)).enabled = this.field_146583_f.getText().trim().length() > 0; + if (parInt1 == 28 || parInt1 == 156) { + this.actionPerformed((GuiButton) this.buttonList.get(0)); + } + + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + this.field_146583_f.mouseClicked(parInt1, parInt2, parInt3); + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + + @Override + public boolean showCopyPasteButtons() { + return field_146583_f.isFocused(); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.field_146583_f.updateCursorCounter(); + } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiRepair.java b/src/game/java/net/minecraft/client/gui/GuiRepair.java index d288a61a..446c46bc 100644 --- a/src/game/java/net/minecraft/client/gui/GuiRepair.java +++ b/src/game/java/net/minecraft/client/gui/GuiRepair.java @@ -2,9 +2,9 @@ package net.minecraft.client.gui; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiContainer; @@ -21,22 +21,25 @@ import net.minecraft.network.play.client.C17PacketCustomPayload; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,38 +56,31 @@ public class GuiRepair extends GuiContainer implements ICrafting { this.anvil = (ContainerRepair) this.inventorySlots; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + public boolean blockPTTKey() { + return nameField.isFocused(); + } + + /** + * + Args : renderPartialTicks, mouseX, mouseY */ - public void initGui() { - super.initGui(); - Keyboard.enableRepeatEvents(true); + protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(anvilResource); int i = (this.width - this.xSize) / 2; int j = (this.height - this.ySize) / 2; - this.nameField = new GuiTextField(0, this.fontRendererObj, i + 62, j + 24, 103, 12); - this.nameField.setTextColor(-1); - this.nameField.setDisabledTextColour(-1); - this.nameField.setEnableBackgroundDrawing(false); - this.nameField.setMaxStringLength(30); - this.inventorySlots.removeCraftingFromCrafters(this); - this.inventorySlots.onCraftGuiOpened(this); + this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); + this.drawTexturedModalRect(i + 59, j + 20, 0, this.ySize + (this.anvil.getSlot(0).getHasStack() ? 0 : 16), 110, + 16); + if ((this.anvil.getSlot(0).getHasStack() || this.anvil.getSlot(1).getHasStack()) + && !this.anvil.getSlot(2).getHasStack()) { + this.drawTexturedModalRect(i + 99, j + 45, this.xSize, 0, 28, 21); + } + } - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - super.onGuiClosed(); - Keyboard.enableRepeatEvents(false); - this.inventorySlots.removeCraftingFromCrafters(this); - } - - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY */ protected void drawGuiContainerForegroundLayer(int var1, int var2) { GlStateManager.disableLighting(); @@ -123,11 +119,48 @@ public class GuiRepair extends GuiContainer implements ICrafting { GlStateManager.enableLighting(); } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + super.drawScreen(i, j, f); + GlStateManager.disableLighting(); + GlStateManager.disableBlend(); + this.nameField.drawTextBox(); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + nameField.fireInputEvent(event, param); + } + + public void func_175173_a(Container parContainer, IInventory parIInventory) { + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + super.initGui(); + Keyboard.enableRepeatEvents(true); + int i = (this.width - this.xSize) / 2; + int j = (this.height - this.ySize) / 2; + this.nameField = new GuiTextField(0, this.fontRendererObj, i + 62, j + 24, 103, 12); + this.nameField.setTextColor(-1); + this.nameField.setDisabledTextColour(-1); + this.nameField.setEnableBackgroundDrawing(false); + this.nameField.setMaxStringLength(30); + this.inventorySlots.removeCraftingFromCrafters(this); + this.inventorySlots.onCraftGuiOpened(this); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { if (this.nameField.textboxKeyTyped(parChar1, parInt1)) { @@ -138,6 +171,23 @@ public class GuiRepair extends GuiContainer implements ICrafting { } + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + this.nameField.mouseClicked(parInt1, parInt2, parInt3); + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + super.onGuiClosed(); + Keyboard.enableRepeatEvents(false); + this.inventorySlots.removeCraftingFromCrafters(this); + } + private void renameItem() { String s = this.nameField.getText(); Slot slot = this.anvil.getSlot(0); @@ -151,56 +201,19 @@ public class GuiRepair extends GuiContainer implements ICrafting { new C17PacketCustomPayload("MC|ItemName", (new PacketBuffer(Unpooled.buffer())).writeString(s))); } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Sends two ints to the client-side Container. Used for furnace burning time, + * smelting progress, brewing progress, and enchanting level. Normally the first + * int identifies which variable to update, and the second contains the new + * value. Both are truncated to shorts in non-local SMP. */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - this.nameField.mouseClicked(parInt1, parInt2, parInt3); + public void sendProgressBarUpdate(Container containerIn, int varToUpdate, int newValue) { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - super.drawScreen(i, j, f); - GlStateManager.disableLighting(); - GlStateManager.disableBlend(); - this.nameField.drawTextBox(); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY - */ - protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(anvilResource); - int i = (this.width - this.xSize) / 2; - int j = (this.height - this.ySize) / 2; - this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); - this.drawTexturedModalRect(i + 59, j + 20, 0, this.ySize + (this.anvil.getSlot(0).getHasStack() ? 0 : 16), 110, - 16); - if ((this.anvil.getSlot(0).getHasStack() || this.anvil.getSlot(1).getHasStack()) - && !this.anvil.getSlot(2).getHasStack()) { - this.drawTexturedModalRect(i + 99, j + 45, this.xSize, 0, 28, 21); - } - - } - - /**+ - * update the crafting window inventory with the items in the - * list - */ - public void updateCraftingInventory(Container containerToSend, List itemsList) { - this.sendSlotContents(containerToSend, 0, containerToSend.getSlot(0).getStack()); - } - - /**+ - * Sends the contents of an inventory slot to the client-side - * Container. This doesn't have to match the actual contents of - * that slot. Args: Container, slot number, slot contents + /** + * + Sends the contents of an inventory slot to the client-side Container. This + * doesn't have to match the actual contents of that slot. Args: Container, slot + * number, slot contents */ public void sendSlotContents(Container containerToSend, int slotInd, ItemStack stack) { if (slotInd == 0) { @@ -213,31 +226,16 @@ public class GuiRepair extends GuiContainer implements ICrafting { } - /**+ - * Sends two ints to the client-side Container. Used for furnace - * burning time, smelting progress, brewing progress, and - * enchanting level. Normally the first int identifies which - * variable to update, and the second contains the new value. - * Both are truncated to shorts in non-local SMP. - */ - public void sendProgressBarUpdate(Container containerIn, int varToUpdate, int newValue) { - } - - public void func_175173_a(Container parContainer, IInventory parIInventory) { - } - - public boolean blockPTTKey() { - return nameField.isFocused(); - } - @Override public boolean showCopyPasteButtons() { return nameField.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - nameField.fireInputEvent(event, param); + /** + * + update the crafting window inventory with the items in the list + */ + public void updateCraftingInventory(Container containerToSend, List itemsList) { + this.sendSlotContents(containerToSend, 0, containerToSend.getSlot(0).getStack()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiResourcePackAvailable.java b/src/game/java/net/minecraft/client/gui/GuiResourcePackAvailable.java index a20c0865..c9f71b94 100644 --- a/src/game/java/net/minecraft/client/gui/GuiResourcePackAvailable.java +++ b/src/game/java/net/minecraft/client/gui/GuiResourcePackAvailable.java @@ -6,22 +6,25 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.ResourcePackListEntry; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/GuiResourcePackList.java b/src/game/java/net/minecraft/client/gui/GuiResourcePackList.java index ada6071b..8f5b6535 100644 --- a/src/game/java/net/minecraft/client/gui/GuiResourcePackList.java +++ b/src/game/java/net/minecraft/client/gui/GuiResourcePackList.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.resources.ResourcePackListEntry; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,8 +42,8 @@ public abstract class GuiResourcePackList extends GuiListExtended { this.setHasListHeader(true, (int) ((float) mcIn.fontRendererObj.FONT_HEIGHT * 1.5F)); } - /**+ - * Handles drawing a list's header row. + /** + * + Handles drawing a list's header row. */ protected void drawListHeader(int i, int j, Tessellator var3) { String s = EnumChatFormatting.UNDERLINE + "" + EnumChatFormatting.BOLD + this.getListHeader(); @@ -48,25 +51,21 @@ public abstract class GuiResourcePackList extends GuiListExtended { Math.min(this.top + 3, j), 16777215); } - protected abstract String getListHeader(); - public List getList() { return this.field_148204_l; } - protected int getSize() { - return this.getList().size(); - } - - /**+ - * Gets the IGuiListEntry object for the given index + /** + * + Gets the IGuiListEntry object for the given index */ public ResourcePackListEntry getListEntry(int i) { return (ResourcePackListEntry) this.getList().get(i); } - /**+ - * Gets the width of the list + protected abstract String getListHeader(); + + /** + * + Gets the width of the list */ public int getListWidth() { return this.width; @@ -75,4 +74,8 @@ public abstract class GuiResourcePackList extends GuiListExtended { protected int getScrollBarX() { return this.right - 6; } + + protected int getSize() { + return this.getList().size(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiResourcePackSelected.java b/src/game/java/net/minecraft/client/gui/GuiResourcePackSelected.java index de460b7d..93917873 100644 --- a/src/game/java/net/minecraft/client/gui/GuiResourcePackSelected.java +++ b/src/game/java/net/minecraft/client/gui/GuiResourcePackSelected.java @@ -6,22 +6,25 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; import net.minecraft.client.resources.ResourcePackListEntry; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/GuiScreen.java b/src/game/java/net/minecraft/client/gui/GuiScreen.java index 13eb07ee..2803ee7a 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreen.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreen.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.io.IOException; import java.util.ArrayList; @@ -10,7 +11,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.internal.EnumTouchEvent; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Splitter; @@ -24,6 +24,7 @@ import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.PauseMenuCustomizeState; import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; import net.lax1dude.eaglercraft.v1_8.Touch; +import net.lax1dude.eaglercraft.v1_8.internal.EnumTouchEvent; import net.lax1dude.eaglercraft.v1_8.internal.KeyboardConstants; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; @@ -54,22 +55,25 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -78,114 +82,59 @@ public abstract class GuiScreen extends Gui implements GuiYesNoCallback { private static final Logger LOGGER = LogManager.getLogger(); private static final Set PROTOCOLS = Sets.newHashSet(new String[] { "http", "https" }); private static final Splitter NEWLINE_SPLITTER = Splitter.on('\n'); - protected Minecraft mc; - protected RenderItem itemRender; - public int width; - public int height; - /**+ - * A list of all the buttons in this container. - */ - protected List buttonList = Lists.newArrayList(); - /**+ - * A list of all the labels in this container. - */ - protected List labelList = Lists.newArrayList(); - public boolean allowUserInput; - protected FontRenderer fontRendererObj; - protected GuiButton selectedButton; - private int eventButton; - private long lastMouseEvent; - private int touchValue; - private String clickedLinkURI; - protected long showingCloseKey = 0; - - protected int touchModeCursorPosX = -1; - protected int touchModeCursorPosY = -1; - private long lastTouchEvent; - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float var3) { - for (int k = 0, l = this.buttonList.size(); k < l; ++k) { - ((GuiButton) this.buttonList.get(k)).drawButton(this.mc, i, j); - } - - for (int l = 0, m = this.labelList.size(); l < m; ++l) { - ((GuiLabel) this.labelList.get(l)).drawLabel(this.mc, i, j); - } - - long millis = EagRuntime.steadyTimeMillis(); - long closeKeyTimeout = millis - showingCloseKey; - if (closeKeyTimeout < 3000l) { - int alpha1 = 0xC0000000; - int alpha2 = 0xFF000000; - if (closeKeyTimeout > 2500l) { - float f = (float) (3000l - closeKeyTimeout) * 0.002f; - if (f < 0.03f) - f = 0.03f; - alpha1 = (int) (f * 192.0f) << 24; - alpha2 = (int) (f * 255.0f) << 24; - } - String str; - int k = getCloseKey(); - if (k == KeyboardConstants.KEY_GRAVE) { - str = I18n.format("gui.exitKeyRetarded"); - } else { - str = I18n.format("gui.exitKey", Keyboard.getKeyName(k)); - } - int w = fontRendererObj.getStringWidth(str); - int x = (width - w - 4) / 2; - int y = 10; - drawRect(x, y, x + w + 4, y + 12, alpha1); - if (closeKeyTimeout > 2500l) - GlStateManager.enableBlend(); - fontRendererObj.drawStringWithShadow(str, x + 2, y + 2, 0xFFAAAA | alpha2); - if (closeKeyTimeout > 2500l) - GlStateManager.disableBlend(); - } + public static int applyEaglerScale(float scaleFac, int coord, int screenDim) { + return (int) ((coord - (1.0f - scaleFac) * screenDim * 0.5f) / scaleFac); } - protected int getCloseKey() { - if (this instanceof GuiContainer) { - return this.mc.gameSettings.keyBindInventory.getKeyCode(); - } else { - return this.mc.gameSettings.keyBindClose.getKeyCode(); - } - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (!canCloseGui()) - return; - if (((this.mc.theWorld == null || this.mc.thePlayer.getHealth() <= 0.0F) && parInt1 == 1) - || parInt1 == this.mc.gameSettings.keyBindClose.getKeyCode() - || (parInt1 == 1 && (this.mc.gameSettings.keyBindClose.getKeyCode() == 0 || this.mc.areKeysLocked()))) { - this.mc.displayGuiScreen((GuiScreen) null); - if (this.mc.currentScreen == null) { - this.mc.setIngameFocus(); - } - } else if (parInt1 == 1) { - showingCloseKey = EagRuntime.steadyTimeMillis(); - } - } - - /**+ - * Returns a string stored in the system clipboard. + /** + * + Returns a string stored in the system clipboard. */ public static String getClipboardString() { return EagRuntime.getClipboard(); } - /**+ - * Stores the given string in the system clipboard + /** + * + Returns true if either alt key is down + */ + public static boolean isAltKeyDown() { + return Keyboard.isKeyDown(56) || Keyboard.isKeyDown(184); + } + + /** + * + Returns true if either windows ctrl key is down or if either mac meta key + * is down + */ + public static boolean isCtrlKeyDown() { + return Minecraft.isRunningOnMac ? Keyboard.isKeyDown(219) || Keyboard.isKeyDown(220) + : Keyboard.isKeyDown(29) || Keyboard.isKeyDown(157); + } + + public static boolean isKeyComboCtrlA(int parInt1) { + return parInt1 == 30 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + public static boolean isKeyComboCtrlC(int parInt1) { + return parInt1 == 46 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + public static boolean isKeyComboCtrlV(int parInt1) { + return parInt1 == 47 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + public static boolean isKeyComboCtrlX(int parInt1) { + return parInt1 == 45 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); + } + + /** + * + Returns true if either shift key is down + */ + public static boolean isShiftKeyDown() { + return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54); + } + + /** + * + Stores the given string in the system clipboard */ public static void setClipboardString(String copyText) { if (!StringUtils.isEmpty(copyText)) { @@ -193,36 +142,121 @@ public abstract class GuiScreen extends Gui implements GuiYesNoCallback { } } - protected void renderToolTip(ItemStack itemstack, int i, int j) { - renderToolTip0(itemstack, i, j, false); + protected Minecraft mc; + protected RenderItem itemRender; + public int width; + public int height; + + /** + * + A list of all the buttons in this container. + */ + protected List buttonList = Lists.newArrayList(); + /** + * + A list of all the labels in this container. + */ + protected List labelList = Lists.newArrayList(); + public boolean allowUserInput; + + protected FontRenderer fontRendererObj; + + protected GuiButton selectedButton; + + private int eventButton; + + private long lastMouseEvent; + + private int touchValue; + + private String clickedLinkURI; + + protected long showingCloseKey = 0; + + protected int touchModeCursorPosX = -1; + + protected int touchModeCursorPosY = -1; + + private long lastTouchEvent; + + public final Map touchStarts = new HashMap<>(); + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { } - protected void renderToolTip0(ItemStack itemstack, int i, int j, boolean eagler) { - List list = itemstack.getTooltipProfanityFilter(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + public boolean blockPTTKey() { + return false; + } - for (int k = 0, l = list.size(); k < l; ++k) { - if (k == 0) { - list.set(k, itemstack.getRarity().rarityColor + (String) list.get(k)); - } else { - list.set(k, EnumChatFormatting.GRAY + (String) list.get(k)); + public boolean canCloseGui() { + return true; + } + + public void confirmClicked(boolean flag, int i) { + if (i == 31102009) { + if (flag) { + this.openWebLink(this.clickedLinkURI); } + + this.clickedLinkURI = null; + this.mc.displayGuiScreen(this); } - this.drawHoveringText0(list, i, j, eagler); } - /**+ - * Draws the text when mouse is over creative inventory tab. - * Params: current creative tab to be checked, current mouse x - * position, current mouse y position. + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return true; + } + + /** + * + Draws the background (i is always 0 as of 1.2.2) + */ + public void drawBackground(int tint) { + GlStateManager.disableLighting(); + GlStateManager.disableFog(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.mc.getTextureManager().bindTexture(optionsBackground); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + float f = 32.0F; + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(0.0D, (double) this.height, 0.0D) + .tex(0.0D, (double) ((float) this.height / 32.0F + (float) tint)).color(64, 64, 64, 255).endVertex(); + worldrenderer.pos((double) this.width, (double) this.height, 0.0D) + .tex((double) ((float) this.width / 32.0F), (double) ((float) this.height / 32.0F + (float) tint)) + .color(64, 64, 64, 255).endVertex(); + worldrenderer.pos((double) this.width, 0.0D, 0.0D).tex((double) ((float) this.width / 32.0F), (double) tint) + .color(64, 64, 64, 255).endVertex(); + worldrenderer.pos(0.0D, 0.0D, 0.0D).tex(0.0D, (double) tint).color(64, 64, 64, 255).endVertex(); + tessellator.draw(); + } + + /** + * + Draws the text when mouse is over creative inventory tab. Params: current + * creative tab to be checked, current mouse x position, current mouse y + * position. */ protected void drawCreativeTabHoveringText(String s, int i, int j) { this.drawHoveringText(Arrays.asList(new String[] { s }), i, j); } - /**+ - * Draws a List of strings as a tooltip. Every entry is drawn on - * a seperate line. + /** + * + Draws either a gradient over the background screen (when it exists) or a + * flat gradient over background.png + */ + public void drawDefaultBackground() { + this.drawWorldBackground(0); + } + + /** + * + Draws a List of strings as a tooltip. Every entry is drawn on a seperate + * line. */ protected void drawHoveringText(List list, int i, int j) { drawHoveringText0(list, i, j, false); @@ -301,8 +335,189 @@ public abstract class GuiScreen extends Gui implements GuiYesNoCallback { } } - /**+ - * Draws the hover event specified by the given chat component + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float var3) { + for (int k = 0, l = this.buttonList.size(); k < l; ++k) { + ((GuiButton) this.buttonList.get(k)).drawButton(this.mc, i, j); + } + + for (int l = 0, m = this.labelList.size(); l < m; ++l) { + ((GuiLabel) this.labelList.get(l)).drawLabel(this.mc, i, j); + } + + long millis = EagRuntime.steadyTimeMillis(); + long closeKeyTimeout = millis - showingCloseKey; + if (closeKeyTimeout < 3000l) { + int alpha1 = 0xC0000000; + int alpha2 = 0xFF000000; + if (closeKeyTimeout > 2500l) { + float f = (float) (3000l - closeKeyTimeout) * 0.002f; + if (f < 0.03f) + f = 0.03f; + alpha1 = (int) (f * 192.0f) << 24; + alpha2 = (int) (f * 255.0f) << 24; + } + String str; + int k = getCloseKey(); + if (k == KeyboardConstants.KEY_GRAVE) { + str = I18n.format("gui.exitKeyRetarded"); + } else { + str = I18n.format("gui.exitKey", Keyboard.getKeyName(k)); + } + int w = fontRendererObj.getStringWidth(str); + int x = (width - w - 4) / 2; + int y = 10; + drawRect(x, y, x + w + 4, y + 12, alpha1); + if (closeKeyTimeout > 2500l) + GlStateManager.enableBlend(); + fontRendererObj.drawStringWithShadow(str, x + 2, y + 2, 0xFFAAAA | alpha2); + if (closeKeyTimeout > 2500l) + GlStateManager.disableBlend(); + } + + } + + public void drawWorldBackground(int i) { + if (this.mc.theWorld != null) { + boolean ingame = isPartOfPauseMenu(); + ResourceLocation loc = (ingame && PauseMenuCustomizeState.icon_background_pause != null) + ? PauseMenuCustomizeState.icon_background_pause + : PauseMenuCustomizeState.icon_background_all; + float aspect = (ingame && PauseMenuCustomizeState.icon_background_pause != null) + ? 1.0f / PauseMenuCustomizeState.icon_background_pause_aspect + : 1.0f / PauseMenuCustomizeState.icon_background_all_aspect; + if (loc != null) { + GlStateManager.disableLighting(); + GlStateManager.disableFog(); + GlStateManager.enableBlend(); + GlStateManager.disableAlpha(); + GlStateManager.enableTexture2D(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.mc.getTextureManager().bindTexture(loc); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + float f = 64.0F; + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(0.0D, (double) this.height, 0.0D).tex(0.0D, (double) ((float) this.height / f)) + .color(64, 64, 64, 192).endVertex(); + worldrenderer.pos((double) this.width, (double) this.height, 0.0D) + .tex((double) ((float) this.width / f * aspect), (double) ((float) this.height / f)) + .color(64, 64, 64, 192).endVertex(); + worldrenderer.pos((double) this.width, 0.0D, 0.0D) + .tex((double) ((float) this.width / f * aspect), (double) 0).color(64, 64, 64, 192).endVertex(); + worldrenderer.pos(0.0D, 0.0D, 0.0D).tex(0.0D, (double) 0).color(64, 64, 64, 192).endVertex(); + tessellator.draw(); + GlStateManager.enableAlpha(); + } else { + this.drawGradientRect(0, 0, this.width, this.height, -1072689136, -804253680); + } + if (!(this instanceof GuiScreenServerInfo)) { + loc = (ingame && PauseMenuCustomizeState.icon_watermark_pause != null) + ? PauseMenuCustomizeState.icon_watermark_pause + : PauseMenuCustomizeState.icon_watermark_all; + aspect = (ingame && PauseMenuCustomizeState.icon_watermark_pause != null) + ? PauseMenuCustomizeState.icon_watermark_pause_aspect + : PauseMenuCustomizeState.icon_watermark_all_aspect; + if (loc != null) { + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + mc.getTextureManager().bindTexture(loc); + GlStateManager.pushMatrix(); + GlStateManager.translate(8, height - 72, 0.0f); + float f2 = 64.0f / 256.0f; + GlStateManager.scale(f2 * aspect, f2, f2); + this.drawTexturedModalRect(0, 0, 0, 0, 256, 256); + GlStateManager.popMatrix(); + } + } + } else { + this.drawBackground(i); + } + + } + + public void fireInputEvent(EnumInputEvent event, String param) { + + } + + protected int getCloseKey() { + if (this instanceof GuiContainer) { + return this.mc.gameSettings.keyBindInventory.getKeyCode(); + } else { + return this.mc.gameSettings.keyBindClose.getKeyCode(); + } + } + + public float getEaglerScale() { + return PointerInputAbstraction.isTouchMode() ? getTouchModeScale() : 1.0f; + } + + protected float getTouchModeScale() { + return 1.0f; + } + + /** + * + Executes the click event specified by the given chat component + */ + public boolean handleComponentClick(IChatComponent parIChatComponent) { + if (parIChatComponent == null) { + return false; + } else { + ClickEvent clickevent = parIChatComponent.getChatStyle().getChatClickEvent(); + if (isShiftKeyDown()) { + if (parIChatComponent.getChatStyle().getInsertion() != null) { + this.setText(parIChatComponent.getChatStyle().getInsertion(), false); + } + } else if (clickevent != null) { + if (clickevent.getAction() == ClickEvent.Action.OPEN_URL) { + if (!this.mc.gameSettings.chatLinks) { + return false; + } + String uri = clickevent.getValue(); + + if (this.mc.gameSettings.chatLinksPrompt) { + this.clickedLinkURI = uri; + this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, clickevent.getValue(), 31102009, false)); + } else { + this.openWebLink(uri); + } + } else if (clickevent.getAction() == ClickEvent.Action.OPEN_FILE) { + // rip + } else if (clickevent.getAction() == ClickEvent.Action.SUGGEST_COMMAND) { + this.setText(clickevent.getValue(), true); + } else if (clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) { + this.sendChatMessage(clickevent.getValue(), false); + } else if (clickevent.getAction() == ClickEvent.Action.TWITCH_USER_INFO) { + /* + * ChatUserInfo chatuserinfo = + * this.mc.getTwitchStream().func_152926_a(clickevent.getValue()); if + * (chatuserinfo != null) { this.mc.displayGuiScreen(new + * GuiTwitchUserMode(this.mc.getTwitchStream(), chatuserinfo)); } else { } + */ + LOGGER.error("Tried to handle twitch user but couldn\'t find them!"); + } else if (clickevent.getAction() == ClickEvent.Action.EAGLER_PLUGIN_DOWNLOAD) { + if (EaglerXBungeeVersion.pluginFileEPK.equals(clickevent.getValue())) { + EaglerXBungeeVersion.startPluginDownload(); + } else { + LOGGER.error("Invalid plugin download from EPK was blocked: {}", + EaglerXBungeeVersion.pluginFileEPK); + } + } else { + LOGGER.error("Don\'t know how to handle " + clickevent); + } + + return true; + } + + return false; + } + } + + /** + * + Draws the hover event specified by the given chat component */ public void handleComponentHover(IChatComponent parIChatComponent, int parInt1, int parInt2) { if (parIChatComponent != null && parIChatComponent.getChatStyle().getChatHoverEvent() != null) { @@ -378,177 +593,8 @@ public abstract class GuiScreen extends Gui implements GuiYesNoCallback { } } - /**+ - * Sets the text of the chat - */ - protected void setText(String var1, boolean var2) { - } - - /**+ - * Executes the click event specified by the given chat - * component - */ - public boolean handleComponentClick(IChatComponent parIChatComponent) { - if (parIChatComponent == null) { - return false; - } else { - ClickEvent clickevent = parIChatComponent.getChatStyle().getChatClickEvent(); - if (isShiftKeyDown()) { - if (parIChatComponent.getChatStyle().getInsertion() != null) { - this.setText(parIChatComponent.getChatStyle().getInsertion(), false); - } - } else if (clickevent != null) { - if (clickevent.getAction() == ClickEvent.Action.OPEN_URL) { - if (!this.mc.gameSettings.chatLinks) { - return false; - } - String uri = clickevent.getValue(); - - if (this.mc.gameSettings.chatLinksPrompt) { - this.clickedLinkURI = uri; - this.mc.displayGuiScreen(new GuiConfirmOpenLink(this, clickevent.getValue(), 31102009, false)); - } else { - this.openWebLink(uri); - } - } else if (clickevent.getAction() == ClickEvent.Action.OPEN_FILE) { - // rip - } else if (clickevent.getAction() == ClickEvent.Action.SUGGEST_COMMAND) { - this.setText(clickevent.getValue(), true); - } else if (clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) { - this.sendChatMessage(clickevent.getValue(), false); - } else if (clickevent.getAction() == ClickEvent.Action.TWITCH_USER_INFO) { - /* - * ChatUserInfo chatuserinfo = - * this.mc.getTwitchStream().func_152926_a(clickevent.getValue()); if - * (chatuserinfo != null) { this.mc.displayGuiScreen(new - * GuiTwitchUserMode(this.mc.getTwitchStream(), chatuserinfo)); } else { } - */ - LOGGER.error("Tried to handle twitch user but couldn\'t find them!"); - } else if (clickevent.getAction() == ClickEvent.Action.EAGLER_PLUGIN_DOWNLOAD) { - if (EaglerXBungeeVersion.pluginFileEPK.equals(clickevent.getValue())) { - EaglerXBungeeVersion.startPluginDownload(); - } else { - LOGGER.error("Invalid plugin download from EPK was blocked: {}", - EaglerXBungeeVersion.pluginFileEPK); - } - } else { - LOGGER.error("Don\'t know how to handle " + clickevent); - } - - return true; - } - - return false; - } - } - - public void sendChatMessage(String msg) { - this.sendChatMessage(msg, true); - } - - public void sendChatMessage(String msg, boolean addToChat) { - if (addToChat) { - this.mc.ingameGUI.getChatGUI().addToSentMessages(msg); - } - - this.mc.thePlayer.sendChatMessage(msg); - } - - protected void touchStarted(int parInt1, int parInt2, int parInt3) { - if (shouldTouchGenerateMouseEvents()) { - this.mouseClicked(parInt1, parInt2, 12345); - } - } - - protected void touchTapped(int parInt1, int parInt2, int parInt3) { - if (shouldTouchGenerateMouseEvents()) { - this.mouseClicked(parInt1, parInt2, 0); - this.mouseReleased(parInt1, parInt2, 0); - } - } - - protected void touchMoved(int parInt1, int parInt2, int parInt3) { - } - - protected void touchEndMove(int parInt1, int parInt2, int parInt3) { - if (shouldTouchGenerateMouseEvents()) { - this.mouseReleased(parInt1, parInt2, 12345); - } - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - boolean touchMode = PointerInputAbstraction.isTouchMode(); - if (parInt3 == 0 || parInt3 == 12345) { - for (int i = 0; i < this.buttonList.size(); ++i) { - GuiButton guibutton = (GuiButton) this.buttonList.get(i); - if (touchMode && (parInt3 == 12345) != guibutton.isSliderTouchEvents()) - continue; - if (guibutton.mousePressed(this.mc, parInt1, parInt2)) { - this.selectedButton = guibutton; - guibutton.playPressSound(this.mc.getSoundHandler()); - this.actionPerformed(guibutton); - } - } - } - - } - - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton - */ - protected void mouseReleased(int i, int j, int k) { - if (this.selectedButton != null && (k == 0 || k == 12345) - && (!PointerInputAbstraction.isTouchMode() || (k == 12345) == selectedButton.isSliderTouchEvents())) { - this.selectedButton.mouseReleased(i, j); - this.selectedButton = null; - } - - } - - /**+ - * Called when a mouse button is pressed and the mouse is moved - * around. Parameters are : mouseX, mouseY, lastButtonClicked & - * timeSinceMouseClick. - */ - protected void mouseClickMove(int var1, int var2, int var3, long var4) { - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - } - - /**+ - * Causes the screen to lay out its subcomponents again. This is - * the equivalent of the Java call Container.validate() - */ - public void setWorldAndResolution(Minecraft mc, int width, int height) { - this.mc = mc; - this.itemRender = mc.getRenderItem(); - this.fontRendererObj = mc.fontRendererObj; - this.width = width; - this.height = height; - this.buttonList.clear(); - this.initGui(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - } - - /**+ - * Delegates mouse and keyboard input. + /** + * + Delegates mouse and keyboard input. */ public void handleInput() throws IOException { boolean noTouch = true; @@ -574,7 +620,48 @@ public abstract class GuiScreen extends Gui implements GuiYesNoCallback { } - public final Map touchStarts = new HashMap<>(); + /** + * + Handles keyboard input. + */ + public void handleKeyboardInput() throws IOException { + if (Keyboard.getEventKeyState()) { + this.keyTyped(Keyboard.getEventCharacter(), Keyboard.getEventKey()); + } + + this.mc.dispatchKeypresses(); + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + float f = getEaglerScale(); + int i = applyEaglerScale(f, Mouse.getEventX() * this.width / this.mc.displayWidth, this.width); + int j = applyEaglerScale(f, this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1, + this.height); + int k = Mouse.getEventButton(); + if (Mouse.getEventButtonState()) { + PointerInputAbstraction.enterMouseModeHook(); + if (this.mc.gameSettings.touchscreen && this.touchValue++ > 0) { + return; + } + + this.eventButton = k; + this.lastMouseEvent = Minecraft.getSystemTime(); + this.mouseClicked(i, j, this.eventButton); + } else if (k != -1) { + if (this.mc.gameSettings.touchscreen && --this.touchValue > 0) { + return; + } + + this.eventButton = -1; + this.mouseReleased(i, j, k); + } else if (this.eventButton != -1 && this.lastMouseEvent > 0L) { + long l = Minecraft.getSystemTime() - this.lastMouseEvent; + this.mouseClickMove(i, j, this.eventButton, l); + } + + } /** * Handles touch input. @@ -653,270 +740,193 @@ public abstract class GuiScreen extends Gui implements GuiYesNoCallback { } } - public boolean isTouchPointDragging(int uid) { - int[] ret = touchStarts.get(uid); - return ret != null && ret[2] == 1; - } - - /**+ - * Handles mouse input. + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ - public void handleMouseInput() throws IOException { - float f = getEaglerScale(); - int i = applyEaglerScale(f, Mouse.getEventX() * this.width / this.mc.displayWidth, this.width); - int j = applyEaglerScale(f, this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1, - this.height); - int k = Mouse.getEventButton(); - if (Mouse.getEventButtonState()) { - PointerInputAbstraction.enterMouseModeHook(); - if (this.mc.gameSettings.touchscreen && this.touchValue++ > 0) { - return; - } - - this.eventButton = k; - this.lastMouseEvent = Minecraft.getSystemTime(); - this.mouseClicked(i, j, this.eventButton); - } else if (k != -1) { - if (this.mc.gameSettings.touchscreen && --this.touchValue > 0) { - return; - } - - this.eventButton = -1; - this.mouseReleased(i, j, k); - } else if (this.eventButton != -1 && this.lastMouseEvent > 0L) { - long l = Minecraft.getSystemTime() - this.lastMouseEvent; - this.mouseClickMove(i, j, this.eventButton, l); - } - - } - - /**+ - * Handles keyboard input. - */ - public void handleKeyboardInput() throws IOException { - if (Keyboard.getEventKeyState()) { - this.keyTyped(Keyboard.getEventCharacter(), Keyboard.getEventKey()); - } - - this.mc.dispatchKeypresses(); - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - } - - /**+ - * Draws either a gradient over the background screen (when it - * exists) or a flat gradient over background.png - */ - public void drawDefaultBackground() { - this.drawWorldBackground(0); + public void initGui() { } protected boolean isPartOfPauseMenu() { return false; } - public void drawWorldBackground(int i) { - if (this.mc.theWorld != null) { - boolean ingame = isPartOfPauseMenu(); - ResourceLocation loc = (ingame && PauseMenuCustomizeState.icon_background_pause != null) - ? PauseMenuCustomizeState.icon_background_pause - : PauseMenuCustomizeState.icon_background_all; - float aspect = (ingame && PauseMenuCustomizeState.icon_background_pause != null) - ? 1.0f / PauseMenuCustomizeState.icon_background_pause_aspect - : 1.0f / PauseMenuCustomizeState.icon_background_all_aspect; - if (loc != null) { - GlStateManager.disableLighting(); - GlStateManager.disableFog(); - GlStateManager.enableBlend(); - GlStateManager.disableAlpha(); - GlStateManager.enableTexture2D(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - this.mc.getTextureManager().bindTexture(loc); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - float f = 64.0F; - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos(0.0D, (double) this.height, 0.0D).tex(0.0D, (double) ((float) this.height / f)) - .color(64, 64, 64, 192).endVertex(); - worldrenderer.pos((double) this.width, (double) this.height, 0.0D) - .tex((double) ((float) this.width / f * aspect), (double) ((float) this.height / f)) - .color(64, 64, 64, 192).endVertex(); - worldrenderer.pos((double) this.width, 0.0D, 0.0D) - .tex((double) ((float) this.width / f * aspect), (double) 0).color(64, 64, 64, 192).endVertex(); - worldrenderer.pos(0.0D, 0.0D, 0.0D).tex(0.0D, (double) 0).color(64, 64, 64, 192).endVertex(); - tessellator.draw(); - GlStateManager.enableAlpha(); - } else { - this.drawGradientRect(0, 0, this.width, this.height, -1072689136, -804253680); + protected boolean isTouchDraggingStateLocked(int uid) { + return false; + } + + public boolean isTouchPointDragging(int uid) { + int[] ret = touchStarts.get(uid); + return ret != null && ret[2] == 1; + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (!canCloseGui()) + return; + if (((this.mc.theWorld == null || this.mc.thePlayer.getHealth() <= 0.0F) && parInt1 == 1) + || parInt1 == this.mc.gameSettings.keyBindClose.getKeyCode() + || (parInt1 == 1 && (this.mc.gameSettings.keyBindClose.getKeyCode() == 0 || this.mc.areKeysLocked()))) { + this.mc.displayGuiScreen((GuiScreen) null); + if (this.mc.currentScreen == null) { + this.mc.setIngameFocus(); } - if (!(this instanceof GuiScreenServerInfo)) { - loc = (ingame && PauseMenuCustomizeState.icon_watermark_pause != null) - ? PauseMenuCustomizeState.icon_watermark_pause - : PauseMenuCustomizeState.icon_watermark_all; - aspect = (ingame && PauseMenuCustomizeState.icon_watermark_pause != null) - ? PauseMenuCustomizeState.icon_watermark_pause_aspect - : PauseMenuCustomizeState.icon_watermark_all_aspect; - if (loc != null) { - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - mc.getTextureManager().bindTexture(loc); - GlStateManager.pushMatrix(); - GlStateManager.translate(8, height - 72, 0.0f); - float f2 = 64.0f / 256.0f; - GlStateManager.scale(f2 * aspect, f2, f2); - this.drawTexturedModalRect(0, 0, 0, 0, 256, 256); - GlStateManager.popMatrix(); + } else if (parInt1 == 1) { + showingCloseKey = EagRuntime.steadyTimeMillis(); + } + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + boolean touchMode = PointerInputAbstraction.isTouchMode(); + if (parInt3 == 0 || parInt3 == 12345) { + for (int i = 0; i < this.buttonList.size(); ++i) { + GuiButton guibutton = (GuiButton) this.buttonList.get(i); + if (touchMode && (parInt3 == 12345) != guibutton.isSliderTouchEvents()) + continue; + if (guibutton.mousePressed(this.mc, parInt1, parInt2)) { + this.selectedButton = guibutton; + guibutton.playPressSound(this.mc.getSoundHandler()); + this.actionPerformed(guibutton); } } - } else { - this.drawBackground(i); } } - /**+ - * Draws the background (i is always 0 as of 1.2.2) + /** + * + Called when a mouse button is pressed and the mouse is moved around. + * Parameters are : mouseX, mouseY, lastButtonClicked & timeSinceMouseClick. */ - public void drawBackground(int tint) { - GlStateManager.disableLighting(); - GlStateManager.disableFog(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - this.mc.getTextureManager().bindTexture(optionsBackground); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - float f = 32.0F; - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos(0.0D, (double) this.height, 0.0D) - .tex(0.0D, (double) ((float) this.height / 32.0F + (float) tint)).color(64, 64, 64, 255).endVertex(); - worldrenderer.pos((double) this.width, (double) this.height, 0.0D) - .tex((double) ((float) this.width / 32.0F), (double) ((float) this.height / 32.0F + (float) tint)) - .color(64, 64, 64, 255).endVertex(); - worldrenderer.pos((double) this.width, 0.0D, 0.0D).tex((double) ((float) this.width / 32.0F), (double) tint) - .color(64, 64, 64, 255).endVertex(); - worldrenderer.pos(0.0D, 0.0D, 0.0D).tex(0.0D, (double) tint).color(64, 64, 64, 255).endVertex(); - tessellator.draw(); + protected void mouseClickMove(int var1, int var2, int var3, long var4) { } - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton */ - public boolean doesGuiPauseGame() { - return true; - } - - public void confirmClicked(boolean flag, int i) { - if (i == 31102009) { - if (flag) { - this.openWebLink(this.clickedLinkURI); - } - - this.clickedLinkURI = null; - this.mc.displayGuiScreen(this); + protected void mouseReleased(int i, int j, int k) { + if (this.selectedButton != null && (k == 0 || k == 12345) + && (!PointerInputAbstraction.isTouchMode() || (k == 12345) == selectedButton.isSliderTouchEvents())) { + this.selectedButton.mouseReleased(i, j); + this.selectedButton = null; } } + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + } + + /** + * + Called when the GUI is resized in order to update the world and the + * resolution + */ + public void onResize(Minecraft mcIn, int parInt1, int parInt2) { + this.setWorldAndResolution(mcIn, parInt1, parInt2); + } + private void openWebLink(String parURI) { EagRuntime.openLink(parURI); } - /**+ - * Returns true if either windows ctrl key is down or if either - * mac meta key is down + protected void renderToolTip(ItemStack itemstack, int i, int j) { + renderToolTip0(itemstack, i, j, false); + } + + protected void renderToolTip0(ItemStack itemstack, int i, int j, boolean eagler) { + List list = itemstack.getTooltipProfanityFilter(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + + for (int k = 0, l = list.size(); k < l; ++k) { + if (k == 0) { + list.set(k, itemstack.getRarity().rarityColor + (String) list.get(k)); + } else { + list.set(k, EnumChatFormatting.GRAY + (String) list.get(k)); + } + } + + this.drawHoveringText0(list, i, j, eagler); + } + + public void sendChatMessage(String msg) { + this.sendChatMessage(msg, true); + } + + public void sendChatMessage(String msg, boolean addToChat) { + if (addToChat) { + this.mc.ingameGUI.getChatGUI().addToSentMessages(msg); + } + + this.mc.thePlayer.sendChatMessage(msg); + } + + /** + * + Sets the text of the chat */ - public static boolean isCtrlKeyDown() { - return Minecraft.isRunningOnMac ? Keyboard.isKeyDown(219) || Keyboard.isKeyDown(220) - : Keyboard.isKeyDown(29) || Keyboard.isKeyDown(157); + protected void setText(String var1, boolean var2) { } - /**+ - * Returns true if either shift key is down + /** + * + Causes the screen to lay out its subcomponents again. This is the + * equivalent of the Java call Container.validate() */ - public static boolean isShiftKeyDown() { - return Keyboard.isKeyDown(42) || Keyboard.isKeyDown(54); - } - - /**+ - * Returns true if either alt key is down - */ - public static boolean isAltKeyDown() { - return Keyboard.isKeyDown(56) || Keyboard.isKeyDown(184); - } - - public static boolean isKeyComboCtrlX(int parInt1) { - return parInt1 == 45 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); - } - - public static boolean isKeyComboCtrlV(int parInt1) { - return parInt1 == 47 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); - } - - public static boolean isKeyComboCtrlC(int parInt1) { - return parInt1 == 46 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); - } - - public static boolean isKeyComboCtrlA(int parInt1) { - return parInt1 == 30 && isCtrlKeyDown() && !isShiftKeyDown() && !isAltKeyDown(); - } - - /**+ - * Called when the GUI is resized in order to update the world - * and the resolution - */ - public void onResize(Minecraft mcIn, int parInt1, int parInt2) { - this.setWorldAndResolution(mcIn, parInt1, parInt2); + public void setWorldAndResolution(Minecraft mc, int width, int height) { + this.mc = mc; + this.itemRender = mc.getRenderItem(); + this.fontRendererObj = mc.fontRendererObj; + this.width = width; + this.height = height; + this.buttonList.clear(); + this.initGui(); } public boolean shouldHangupIntegratedServer() { return true; } - public boolean blockPTTKey() { - return false; - } - - public void fireInputEvent(EnumInputEvent event, String param) { - + protected boolean shouldTouchGenerateMouseEvents() { + return true; } public boolean showCopyPasteButtons() { return false; } - public static int applyEaglerScale(float scaleFac, int coord, int screenDim) { - return (int) ((coord - (1.0f - scaleFac) * screenDim * 0.5f) / scaleFac); + protected void touchEndMove(int parInt1, int parInt2, int parInt3) { + if (shouldTouchGenerateMouseEvents()) { + this.mouseReleased(parInt1, parInt2, 12345); + } } - public float getEaglerScale() { - return PointerInputAbstraction.isTouchMode() ? getTouchModeScale() : 1.0f; + protected void touchMoved(int parInt1, int parInt2, int parInt3) { } - protected float getTouchModeScale() { - return 1.0f; + protected void touchStarted(int parInt1, int parInt2, int parInt3) { + if (shouldTouchGenerateMouseEvents()) { + this.mouseClicked(parInt1, parInt2, 12345); + } } - public boolean canCloseGui() { - return true; + protected void touchTapped(int parInt1, int parInt2, int parInt3) { + if (shouldTouchGenerateMouseEvents()) { + this.mouseClicked(parInt1, parInt2, 0); + this.mouseReleased(parInt1, parInt2, 0); + } } - protected boolean isTouchDraggingStateLocked(int uid) { - return false; - } - - protected boolean shouldTouchGenerateMouseEvents() { - return true; + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenAddServer.java b/src/game/java/net/minecraft/client/gui/GuiScreenAddServer.java index f196e709..2f107689 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenAddServer.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenAddServer.java @@ -6,22 +6,25 @@ import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,18 +43,73 @@ public class GuiScreenAddServer extends GuiScreen { this.serverData = parServerData; } - /**+ - * Called from the main game loop to update the screen. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ - public void updateScreen() { - this.serverNameField.updateCursorCounter(); - this.serverIPField.updateCursorCounter(); + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id == 3) { + this.serverData.hideAddress = !this.serverData.hideAddress; + this.hideAddress.displayString = I18n + .format(EagRuntime.getConfiguration().isEnableServerCookies() ? "addServer.hideAddr" + : "addServer.hideAddress", new Object[0]) + + ": " + I18n.format(this.serverData.hideAddress ? "gui.yes" : "gui.no", new Object[0]); + } else if (parGuiButton.id == 4) { + this.serverData.enableCookies = !this.serverData.enableCookies; + this.enableCookies.displayString = I18n.format("addServer.enableCookies") + ": " + + I18n.format(this.serverData.enableCookies ? "addServer.enableCookies.enabled" + : "addServer.enableCookies.disabled"); + } else if (parGuiButton.id == 2) { + this.serverData.setResourceMode( + ServerData.ServerResourceMode._VALUES[(this.serverData.getResourceMode().ordinal() + 1) + % ServerData.ServerResourceMode._VALUES.length]); + this.serverResourcePacks.displayString = I18n.format("addServer.resourcePack", new Object[0]) + ": " + + this.serverData.getResourceMode().getMotd().getFormattedText(); + } else if (parGuiButton.id == 1) { + this.parentScreen.confirmClicked(false, 0); + } else if (parGuiButton.id == 0) { + this.serverData.serverName = this.serverNameField.getText().trim(); + this.serverData.serverIP = this.serverIPField.getText().trim(); + this.parentScreen.confirmClicked(true, 0); + } + + } } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.title", new Object[0]), this.width / 2, 17, + 16777215); + this.drawString(this.fontRendererObj, I18n.format("addServer.enterName", new Object[0]), this.width / 2 - 100, + 53, 10526880); + this.drawString(this.fontRendererObj, I18n.format("addServer.enterIp", new Object[0]), this.width / 2 - 100, 94, + 10526880); + if (EagRuntime.requireSSL()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn1"), this.width / 2, 184, + 0xccccff); + this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn2"), this.width / 2, 196, + 0xccccff); + } + this.serverNameField.drawTextBox(); + this.serverIPField.drawTextBox(); + super.drawScreen(i, j, f); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + serverNameField.fireInputEvent(event, param); + serverIPField.fireInputEvent(event, param); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { Keyboard.enableRepeatEvents(true); @@ -94,53 +152,10 @@ public class GuiScreenAddServer extends GuiScreen { ((GuiButton) this.buttonList.get(0)).enabled = this.serverIPField.getText().trim().length() > 0; } - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id == 3) { - this.serverData.hideAddress = !this.serverData.hideAddress; - this.hideAddress.displayString = I18n - .format(EagRuntime.getConfiguration().isEnableServerCookies() ? "addServer.hideAddr" - : "addServer.hideAddress", new Object[0]) - + ": " + I18n.format(this.serverData.hideAddress ? "gui.yes" : "gui.no", new Object[0]); - } else if (parGuiButton.id == 4) { - this.serverData.enableCookies = !this.serverData.enableCookies; - this.enableCookies.displayString = I18n.format("addServer.enableCookies") + ": " - + I18n.format(this.serverData.enableCookies ? "addServer.enableCookies.enabled" - : "addServer.enableCookies.disabled"); - } else if (parGuiButton.id == 2) { - this.serverData.setResourceMode( - ServerData.ServerResourceMode._VALUES[(this.serverData.getResourceMode().ordinal() + 1) - % ServerData.ServerResourceMode._VALUES.length]); - this.serverResourcePacks.displayString = I18n.format("addServer.resourcePack", new Object[0]) + ": " - + this.serverData.getResourceMode().getMotd().getFormattedText(); - } else if (parGuiButton.id == 1) { - this.parentScreen.confirmClicked(false, 0); - } else if (parGuiButton.id == 0) { - this.serverData.serverName = this.serverNameField.getText().trim(); - this.serverData.serverIP = this.serverIPField.getText().trim(); - this.parentScreen.confirmClicked(true, 0); - } - - } - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { this.serverNameField.textboxKeyTyped(parChar1, parInt1); @@ -157,9 +172,8 @@ public class GuiScreenAddServer extends GuiScreen { ((GuiButton) this.buttonList.get(0)).enabled = this.serverIPField.getText().trim().length() > 0; } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int parInt1, int parInt2, int parInt3) { super.mouseClicked(parInt1, parInt2, parInt3); @@ -167,27 +181,11 @@ public class GuiScreenAddServer extends GuiScreen { this.serverNameField.mouseClicked(parInt1, parInt2, parInt3); } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.title", new Object[0]), this.width / 2, 17, - 16777215); - this.drawString(this.fontRendererObj, I18n.format("addServer.enterName", new Object[0]), this.width / 2 - 100, - 53, 10526880); - this.drawString(this.fontRendererObj, I18n.format("addServer.enterIp", new Object[0]), this.width / 2 - 100, 94, - 10526880); - if (EagRuntime.requireSSL()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn1"), this.width / 2, 184, - 0xccccff); - this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn2"), this.width / 2, 196, - 0xccccff); - } - this.serverNameField.drawTextBox(); - this.serverIPField.drawTextBox(); - super.drawScreen(i, j, f); + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); } @Override @@ -195,10 +193,12 @@ public class GuiScreenAddServer extends GuiScreen { return serverNameField.isFocused() || serverIPField.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - serverNameField.fireInputEvent(event, param); - serverIPField.fireInputEvent(event, param); + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.serverNameField.updateCursorCounter(); + this.serverIPField.updateCursorCounter(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenBook.java b/src/game/java/net/minecraft/client/gui/GuiScreenBook.java index 5fa22c93..be9a9a38 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenBook.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenBook.java @@ -6,11 +6,11 @@ import org.json.JSONException; import com.google.common.collect.Lists; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.minecraft.GuiScreenVisualViewport; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; @@ -30,27 +30,59 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenBook extends GuiScreenVisualViewport { + static class NextPageButton extends GuiButton { + private final boolean field_146151_o; + + public NextPageButton(int parInt1, int parInt2, int parInt3, boolean parFlag) { + super(parInt1, parInt2, parInt3, 23, 13, ""); + this.field_146151_o = parFlag; + } + + public void drawButton(Minecraft minecraft, int i, int j) { + if (this.visible) { + boolean flag = i >= this.xPosition && j >= this.yPosition && i < this.xPosition + this.width + && j < this.yPosition + this.height; + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + minecraft.getTextureManager().bindTexture(GuiScreenBook.bookGuiTextures); + int k = 0; + int l = 192; + if (flag) { + k += 23; + } + + if (!this.field_146151_o) { + l += 13; + } + + this.drawTexturedModalRect(this.xPosition, this.yPosition, k, l, 23, 13); + } + } + } + private static final Logger logger = LogManager.getLogger(); private static final ResourceLocation bookGuiTextures = new ResourceLocation("textures/gui/book.png"); private final EntityPlayer editingPlayer; @@ -72,6 +104,7 @@ public class GuiScreenBook extends GuiScreenVisualViewport { private GuiButton buttonDone; private GuiButton buttonSign; private GuiButton buttonFinalize; + private GuiButton buttonCancel; public GuiScreenBook(EntityPlayer player, ItemStack book, boolean isUnsigned) { @@ -98,108 +131,9 @@ public class GuiScreenBook extends GuiScreenVisualViewport { } - public void updateScreen0() { - super.updateScreen0(); - ++this.updateCount; - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - Keyboard.enableRepeatEvents(true); - if (this.bookIsUnsigned) { - this.buttonList.add(this.buttonSign = new GuiButton(3, this.width / 2 - 100, 4 + this.bookImageHeight, 98, - 20, I18n.format("book.signButton", new Object[0]))); - this.buttonList.add(this.buttonDone = new GuiButton(0, this.width / 2 + 2, 4 + this.bookImageHeight, 98, 20, - I18n.format("gui.done", new Object[0]))); - this.buttonList.add(this.buttonFinalize = new GuiButton(5, this.width / 2 - 100, 4 + this.bookImageHeight, - 98, 20, I18n.format("book.finalizeButton", new Object[0]))); - this.buttonList.add(this.buttonCancel = new GuiButton(4, this.width / 2 + 2, 4 + this.bookImageHeight, 98, - 20, I18n.format("gui.cancel", new Object[0]))); - } else { - this.buttonList.add(this.buttonDone = new GuiButton(0, this.width / 2 - 100, 4 + this.bookImageHeight, 200, - 20, I18n.format("gui.done", new Object[0]))); - } - - int i = (this.width - this.bookImageWidth) / 2; - byte b0 = 2; - this.buttonList.add(this.buttonNextPage = new GuiScreenBook.NextPageButton(1, i + 120, b0 + 154, true)); - this.buttonList.add(this.buttonPreviousPage = new GuiScreenBook.NextPageButton(2, i + 38, b0 + 154, false)); - this.updateButtons(); - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - private void updateButtons() { - this.buttonNextPage.visible = !this.bookGettingSigned - && (this.currPage < this.bookTotalPages - 1 || this.bookIsUnsigned); - this.buttonPreviousPage.visible = !this.bookGettingSigned && this.currPage > 0; - this.buttonDone.visible = !this.bookIsUnsigned || !this.bookGettingSigned; - if (this.bookIsUnsigned) { - this.buttonSign.visible = !this.bookGettingSigned; - this.buttonCancel.visible = this.bookGettingSigned; - this.buttonFinalize.visible = this.bookGettingSigned; - this.buttonFinalize.enabled = this.bookTitle.trim().length() > 0; - } - - } - - private void sendBookToServer(boolean publish) { - if (this.bookIsUnsigned && this.bookIsModified) { - if (this.bookPages != null) { - while (this.bookPages.tagCount() > 1) { - String s = this.bookPages.getStringTagAt(this.bookPages.tagCount() - 1); - if (s.length() != 0) { - break; - } - - this.bookPages.removeTag(this.bookPages.tagCount() - 1); - } - - if (this.bookObj.hasTagCompound()) { - NBTTagCompound nbttagcompound = this.bookObj.getTagCompound(); - nbttagcompound.setTag("pages", this.bookPages); - } else { - this.bookObj.setTagInfo("pages", this.bookPages); - } - - String s2 = "MC|BEdit"; - if (publish) { - s2 = "MC|BSign"; - this.bookObj.setTagInfo("author", new NBTTagString(this.editingPlayer.getName())); - this.bookObj.setTagInfo("title", new NBTTagString(this.bookTitle.trim())); - - for (int i = 0; i < this.bookPages.tagCount(); ++i) { - String s1 = this.bookPages.getStringTagAt(i); - ChatComponentText chatcomponenttext = new ChatComponentText(s1); - s1 = IChatComponent.Serializer.componentToJson(chatcomponenttext); - this.bookPages.set(i, new NBTTagString(s1)); - } - - this.bookObj.setItem(Items.written_book); - } - - PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); - packetbuffer.writeItemStackToBuffer(this.bookObj); - this.mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload(s2, packetbuffer)); - } - - } - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -240,112 +174,8 @@ public class GuiScreenBook extends GuiScreenVisualViewport { } } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (this.bookIsUnsigned) { - if (this.bookGettingSigned) { - this.keyTypedInTitle(parChar1, parInt1); - } else { - this.keyTypedInBook(parChar1, parInt1); - } - } - } - - /**+ - * Processes keystrokes when editing the text of a book - */ - private void keyTypedInBook(char typedChar, int keyCode) { - if (GuiScreen.isKeyComboCtrlV(keyCode)) { - this.pageInsertIntoCurrent(GuiScreen.getClipboardString()); - } else { - switch (keyCode) { - case 14: - String s = this.pageGetCurrent(); - if (s.length() > 0) { - this.pageSetCurrent(s.substring(0, s.length() - 1)); - } - - return; - case 28: - case 156: - this.pageInsertIntoCurrent("\n"); - return; - default: - if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) { - this.pageInsertIntoCurrent(Character.toString(typedChar)); - } - } - } - } - - /**+ - * Processes keystrokes when editing the title of a book - */ - private void keyTypedInTitle(char parChar1, int parInt1) { - switch (parInt1) { - case 14: - if (!this.bookTitle.isEmpty()) { - this.bookTitle = this.bookTitle.substring(0, this.bookTitle.length() - 1); - this.updateButtons(); - } - - return; - case 28: - case 156: - if (!this.bookTitle.isEmpty()) { - this.sendBookToServer(true); - this.mc.displayGuiScreen((GuiScreen) null); - } - - return; - default: - if (this.bookTitle.length() < 16 && ChatAllowedCharacters.isAllowedCharacter(parChar1)) { - this.bookTitle = this.bookTitle + Character.toString(parChar1); - this.updateButtons(); - this.bookIsModified = true; - } - - } - } - - /**+ - * Returns the entire text of the current page as determined by - * currPage - */ - private String pageGetCurrent() { - return this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount() - ? this.bookPages.getStringTagAt(this.currPage) - : ""; - } - - /**+ - * Sets the text of the current page as determined by currPage - */ - private void pageSetCurrent(String parString1) { - if (this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount()) { - this.bookPages.set(this.currPage, new NBTTagString(parString1)); - this.bookIsModified = true; - } - - } - - /**+ - * Processes any text getting inserted into the current page, - * enforcing the page size limit - */ - private void pageInsertIntoCurrent(String parString1) { - String s = this.pageGetCurrent(); - String s1 = s + parString1; - int i = this.fontRendererObj.splitStringWidth(s1 + "" + EnumChatFormatting.BLACK + "_", 118); - if (i <= 128 && s1.length() < 256) { - this.pageSetCurrent(s1); - } - + public boolean blockPTTKey() { + return this.bookIsUnsigned; } public void drawScreen0(int i, int j, float f) { @@ -434,50 +264,6 @@ public class GuiScreenBook extends GuiScreenVisualViewport { super.drawScreen0(i, j, f); } - protected void mouseClicked0(int parInt1, int parInt2, int parInt3) { - if (parInt3 == 0) { - IChatComponent ichatcomponent = this.func_175385_b(parInt1, parInt2); - if (this.handleComponentClick(ichatcomponent)) { - return; - } - } - - super.mouseClicked0(parInt1, parInt2, parInt3); - } - - /**+ - * Executes the click event specified by the given chat - * component - */ - public boolean handleComponentClick(IChatComponent ichatcomponent) { - ClickEvent clickevent = ichatcomponent == null ? null : ichatcomponent.getChatStyle().getChatClickEvent(); - if (clickevent == null) { - return false; - } else if (clickevent.getAction() == ClickEvent.Action.CHANGE_PAGE) { - String s = clickevent.getValue(); - - try { - int i = Integer.parseInt(s) - 1; - if (i >= 0 && i < this.bookTotalPages && i != this.currPage) { - this.currPage = i; - this.updateButtons(); - return true; - } - } catch (Throwable var5) { - ; - } - - return false; - } else { - boolean flag = super.handleComponentClick(ichatcomponent); - if (flag && clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) { - this.mc.displayGuiScreen((GuiScreen) null); - } - - return flag; - } - } - public IChatComponent func_175385_b(int parInt1, int parInt2) { if (this.field_175386_A == null) { return null; @@ -513,36 +299,250 @@ public class GuiScreenBook extends GuiScreenVisualViewport { } } - static class NextPageButton extends GuiButton { - private final boolean field_146151_o; + /** + * + Executes the click event specified by the given chat component + */ + public boolean handleComponentClick(IChatComponent ichatcomponent) { + ClickEvent clickevent = ichatcomponent == null ? null : ichatcomponent.getChatStyle().getChatClickEvent(); + if (clickevent == null) { + return false; + } else if (clickevent.getAction() == ClickEvent.Action.CHANGE_PAGE) { + String s = clickevent.getValue(); - public NextPageButton(int parInt1, int parInt2, int parInt3, boolean parFlag) { - super(parInt1, parInt2, parInt3, 23, 13, ""); - this.field_146151_o = parFlag; + try { + int i = Integer.parseInt(s) - 1; + if (i >= 0 && i < this.bookTotalPages && i != this.currPage) { + this.currPage = i; + this.updateButtons(); + return true; + } + } catch (Throwable var5) { + ; + } + + return false; + } else { + boolean flag = super.handleComponentClick(ichatcomponent); + if (flag && clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) { + this.mc.displayGuiScreen((GuiScreen) null); + } + + return flag; + } + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + Keyboard.enableRepeatEvents(true); + if (this.bookIsUnsigned) { + this.buttonList.add(this.buttonSign = new GuiButton(3, this.width / 2 - 100, 4 + this.bookImageHeight, 98, + 20, I18n.format("book.signButton", new Object[0]))); + this.buttonList.add(this.buttonDone = new GuiButton(0, this.width / 2 + 2, 4 + this.bookImageHeight, 98, 20, + I18n.format("gui.done", new Object[0]))); + this.buttonList.add(this.buttonFinalize = new GuiButton(5, this.width / 2 - 100, 4 + this.bookImageHeight, + 98, 20, I18n.format("book.finalizeButton", new Object[0]))); + this.buttonList.add(this.buttonCancel = new GuiButton(4, this.width / 2 + 2, 4 + this.bookImageHeight, 98, + 20, I18n.format("gui.cancel", new Object[0]))); + } else { + this.buttonList.add(this.buttonDone = new GuiButton(0, this.width / 2 - 100, 4 + this.bookImageHeight, 200, + 20, I18n.format("gui.done", new Object[0]))); } - public void drawButton(Minecraft minecraft, int i, int j) { - if (this.visible) { - boolean flag = i >= this.xPosition && j >= this.yPosition && i < this.xPosition + this.width - && j < this.yPosition + this.height; - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - minecraft.getTextureManager().bindTexture(GuiScreenBook.bookGuiTextures); - int k = 0; - int l = 192; - if (flag) { - k += 23; - } + int i = (this.width - this.bookImageWidth) / 2; + byte b0 = 2; + this.buttonList.add(this.buttonNextPage = new GuiScreenBook.NextPageButton(1, i + 120, b0 + 154, true)); + this.buttonList.add(this.buttonPreviousPage = new GuiScreenBook.NextPageButton(2, i + 38, b0 + 154, false)); + this.updateButtons(); + } - if (!this.field_146151_o) { - l += 13; - } - - this.drawTexturedModalRect(this.xPosition, this.yPosition, k, l, 23, 13); + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (this.bookIsUnsigned) { + if (this.bookGettingSigned) { + this.keyTypedInTitle(parChar1, parInt1); + } else { + this.keyTypedInBook(parChar1, parInt1); } } } - public boolean blockPTTKey() { - return this.bookIsUnsigned; + /** + * + Processes keystrokes when editing the text of a book + */ + private void keyTypedInBook(char typedChar, int keyCode) { + if (GuiScreen.isKeyComboCtrlV(keyCode)) { + this.pageInsertIntoCurrent(GuiScreen.getClipboardString()); + } else { + switch (keyCode) { + case 14: + String s = this.pageGetCurrent(); + if (s.length() > 0) { + this.pageSetCurrent(s.substring(0, s.length() - 1)); + } + + return; + case 28: + case 156: + this.pageInsertIntoCurrent("\n"); + return; + default: + if (ChatAllowedCharacters.isAllowedCharacter(typedChar)) { + this.pageInsertIntoCurrent(Character.toString(typedChar)); + } + } + } + } + + /** + * + Processes keystrokes when editing the title of a book + */ + private void keyTypedInTitle(char parChar1, int parInt1) { + switch (parInt1) { + case 14: + if (!this.bookTitle.isEmpty()) { + this.bookTitle = this.bookTitle.substring(0, this.bookTitle.length() - 1); + this.updateButtons(); + } + + return; + case 28: + case 156: + if (!this.bookTitle.isEmpty()) { + this.sendBookToServer(true); + this.mc.displayGuiScreen((GuiScreen) null); + } + + return; + default: + if (this.bookTitle.length() < 16 && ChatAllowedCharacters.isAllowedCharacter(parChar1)) { + this.bookTitle = this.bookTitle + Character.toString(parChar1); + this.updateButtons(); + this.bookIsModified = true; + } + + } + } + + protected void mouseClicked0(int parInt1, int parInt2, int parInt3) { + if (parInt3 == 0) { + IChatComponent ichatcomponent = this.func_175385_b(parInt1, parInt2); + if (this.handleComponentClick(ichatcomponent)) { + return; + } + } + + super.mouseClicked0(parInt1, parInt2, parInt3); + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + + /** + * + Returns the entire text of the current page as determined by currPage + */ + private String pageGetCurrent() { + return this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount() + ? this.bookPages.getStringTagAt(this.currPage) + : ""; + } + + /** + * + Processes any text getting inserted into the current page, enforcing the + * page size limit + */ + private void pageInsertIntoCurrent(String parString1) { + String s = this.pageGetCurrent(); + String s1 = s + parString1; + int i = this.fontRendererObj.splitStringWidth(s1 + "" + EnumChatFormatting.BLACK + "_", 118); + if (i <= 128 && s1.length() < 256) { + this.pageSetCurrent(s1); + } + + } + + /** + * + Sets the text of the current page as determined by currPage + */ + private void pageSetCurrent(String parString1) { + if (this.bookPages != null && this.currPage >= 0 && this.currPage < this.bookPages.tagCount()) { + this.bookPages.set(this.currPage, new NBTTagString(parString1)); + this.bookIsModified = true; + } + + } + + private void sendBookToServer(boolean publish) { + if (this.bookIsUnsigned && this.bookIsModified) { + if (this.bookPages != null) { + while (this.bookPages.tagCount() > 1) { + String s = this.bookPages.getStringTagAt(this.bookPages.tagCount() - 1); + if (s.length() != 0) { + break; + } + + this.bookPages.removeTag(this.bookPages.tagCount() - 1); + } + + if (this.bookObj.hasTagCompound()) { + NBTTagCompound nbttagcompound = this.bookObj.getTagCompound(); + nbttagcompound.setTag("pages", this.bookPages); + } else { + this.bookObj.setTagInfo("pages", this.bookPages); + } + + String s2 = "MC|BEdit"; + if (publish) { + s2 = "MC|BSign"; + this.bookObj.setTagInfo("author", new NBTTagString(this.editingPlayer.getName())); + this.bookObj.setTagInfo("title", new NBTTagString(this.bookTitle.trim())); + + for (int i = 0; i < this.bookPages.tagCount(); ++i) { + String s1 = this.bookPages.getStringTagAt(i); + ChatComponentText chatcomponenttext = new ChatComponentText(s1); + s1 = IChatComponent.Serializer.componentToJson(chatcomponenttext); + this.bookPages.set(i, new NBTTagString(s1)); + } + + this.bookObj.setItem(Items.written_book); + } + + PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); + packetbuffer.writeItemStackToBuffer(this.bookObj); + this.mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload(s2, packetbuffer)); + } + + } + } + + private void updateButtons() { + this.buttonNextPage.visible = !this.bookGettingSigned + && (this.currPage < this.bookTotalPages - 1 || this.bookIsUnsigned); + this.buttonPreviousPage.visible = !this.bookGettingSigned && this.currPage > 0; + this.buttonDone.visible = !this.bookIsUnsigned || !this.bookGettingSigned; + if (this.bookIsUnsigned) { + this.buttonSign.visible = !this.bookGettingSigned; + this.buttonCancel.visible = this.bookGettingSigned; + this.buttonFinalize.visible = this.bookGettingSigned; + this.buttonFinalize.enabled = this.bookTitle.trim().length() > 0; + } + + } + + public void updateScreen0() { + super.updateScreen0(); + ++this.updateCount; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenCustomizePresets.java b/src/game/java/net/minecraft/client/gui/GuiScreenCustomizePresets.java index ce5b9881..a0dee05c 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenCustomizePresets.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenCustomizePresets.java @@ -1,9 +1,10 @@ package net.minecraft.client.gui; -import com.google.common.collect.Lists; import java.io.IOException; import java.util.List; +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -14,162 +15,100 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.ResourceLocation; import net.minecraft.world.gen.ChunkProviderSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenCustomizePresets extends GuiScreen { + static class Info { + public String field_178955_a; + public ResourceLocation field_178953_b; + public ChunkProviderSettings.Factory field_178954_c; + + public Info(String parString1, ResourceLocation parResourceLocation, ChunkProviderSettings.Factory parFactory) { + this.field_178955_a = parString1; + this.field_178953_b = parResourceLocation; + this.field_178954_c = parFactory; + } + } + + class ListPreset extends GuiSlot { + public int field_178053_u = -1; + + public ListPreset() { + super(GuiScreenCustomizePresets.this.mc, GuiScreenCustomizePresets.this.width, + GuiScreenCustomizePresets.this.height, 80, GuiScreenCustomizePresets.this.height - 32, 38); + } + + protected void drawBackground() { + } + + protected void drawSlot(int i, int j, int k, int var4, int var5, int var6) { + GuiScreenCustomizePresets.Info guiscreencustomizepresets$info = (GuiScreenCustomizePresets.Info) GuiScreenCustomizePresets.field_175310_f + .get(i); + this.func_178051_a(j, k, guiscreencustomizepresets$info.field_178953_b); + GuiScreenCustomizePresets.this.fontRendererObj.drawString(guiscreencustomizepresets$info.field_178955_a, + j + 32 + 10, k + 14, 16777215); + } + + protected void elementClicked(int i, boolean var2, int var3, int var4) { + this.field_178053_u = i; + GuiScreenCustomizePresets.this.func_175304_a(); + GuiScreenCustomizePresets.this.field_175317_i + .setText(((GuiScreenCustomizePresets.Info) GuiScreenCustomizePresets.field_175310_f + .get(GuiScreenCustomizePresets.this.field_175311_g.field_178053_u)).field_178954_c + .toString()); + } + + private void func_178051_a(int parInt1, int parInt2, ResourceLocation parResourceLocation) { + int i = parInt1 + 5; + GuiScreenCustomizePresets.this.drawHorizontalLine(i - 1, i + 32, parInt2 - 1, -2039584); + GuiScreenCustomizePresets.this.drawHorizontalLine(i - 1, i + 32, parInt2 + 32, -6250336); + GuiScreenCustomizePresets.this.drawVerticalLine(i - 1, parInt2 - 1, parInt2 + 32, -2039584); + GuiScreenCustomizePresets.this.drawVerticalLine(i + 32, parInt2 - 1, parInt2 + 32, -6250336); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(parResourceLocation); + boolean flag = true; + boolean flag1 = true; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (i + 0), (double) (parInt2 + 32), 0.0D).tex(0.0D, 1.0D).endVertex(); + worldrenderer.pos((double) (i + 32), (double) (parInt2 + 32), 0.0D).tex(1.0D, 1.0D).endVertex(); + worldrenderer.pos((double) (i + 32), (double) (parInt2 + 0), 0.0D).tex(1.0D, 0.0D).endVertex(); + worldrenderer.pos((double) (i + 0), (double) (parInt2 + 0), 0.0D).tex(0.0D, 0.0D).endVertex(); + tessellator.draw(); + } + + protected int getSize() { + return GuiScreenCustomizePresets.field_175310_f.size(); + } + + protected boolean isSelected(int i) { + return i == this.field_178053_u; + } + } + private static final List field_175310_f = Lists.newArrayList(); - private GuiScreenCustomizePresets.ListPreset field_175311_g; - private GuiButton field_175316_h; - private GuiTextField field_175317_i; - private GuiCustomizeWorldScreen field_175314_r; - protected String field_175315_a = "Customize World Presets"; - private String field_175313_s; - private String field_175312_t; - - public GuiScreenCustomizePresets(GuiCustomizeWorldScreen parGuiCustomizeWorldScreen) { - this.field_175314_r = parGuiCustomizeWorldScreen; - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - Keyboard.enableRepeatEvents(true); - this.field_175315_a = I18n.format("createWorld.customize.custom.presets.title", new Object[0]); - this.field_175313_s = I18n.format("createWorld.customize.presets.share", new Object[0]); - this.field_175312_t = I18n.format("createWorld.customize.presets.list", new Object[0]); - this.field_175317_i = new GuiTextField(2, this.fontRendererObj, 50, 40, this.width - 100, 20); - this.field_175311_g = new GuiScreenCustomizePresets.ListPreset(); - this.field_175317_i.setMaxStringLength(2000); - this.field_175317_i.setText(this.field_175314_r.func_175323_a()); - this.buttonList.add(this.field_175316_h = new GuiButton(0, this.width / 2 - 102, this.height - 27, 100, 20, - I18n.format("createWorld.customize.presets.select", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 + 3, this.height - 27, 100, 20, - I18n.format("gui.cancel", new Object[0]))); - this.func_175304_a(); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.field_175311_g.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.field_175311_g.handleTouchInput(); - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - this.field_175317_i.mouseClicked(parInt1, parInt2, parInt3); - super.mouseClicked(parInt1, parInt2, parInt3); - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (!this.field_175317_i.textboxKeyTyped(parChar1, parInt1)) { - super.keyTyped(parChar1, parInt1); - } - - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - switch (parGuiButton.id) { - case 0: - this.field_175314_r.func_175324_a(this.field_175317_i.getText()); - this.mc.displayGuiScreen(this.field_175314_r); - break; - case 1: - this.mc.displayGuiScreen(this.field_175314_r); - } - - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.field_175311_g.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.field_175315_a, this.width / 2, 8, 16777215); - this.drawString(this.fontRendererObj, this.field_175313_s, 50, 30, 10526880); - this.drawString(this.fontRendererObj, this.field_175312_t, 50, 70, 10526880); - this.field_175317_i.drawTextBox(); - super.drawScreen(i, j, f); - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.field_175317_i.updateCursorCounter(); - super.updateScreen(); - } - - public void func_175304_a() { - this.field_175316_h.enabled = this.func_175305_g(); - } - - private boolean func_175305_g() { - return this.field_175311_g.field_178053_u > -1 && this.field_175311_g.field_178053_u < field_175310_f.size() - || this.field_175317_i.getText().length() > 1; - } - - @Override - public boolean showCopyPasteButtons() { - return field_175317_i.isFocused(); - } - - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - field_175317_i.fireInputEvent(event, param); - } - static { ChunkProviderSettings.Factory chunkprovidersettings$factory = ChunkProviderSettings.Factory.jsonToFactory( "{ \"coordinateScale\":684.412, \"heightScale\":684.412, \"upperLimitScale\":512.0, \"lowerLimitScale\":512.0, \"depthNoiseScaleX\":200.0, \"depthNoiseScaleZ\":200.0, \"depthNoiseScaleExponent\":0.5, \"mainNoiseScaleX\":5000.0, \"mainNoiseScaleY\":1000.0, \"mainNoiseScaleZ\":5000.0, \"baseSize\":8.5, \"stretchY\":8.0, \"biomeDepthWeight\":2.0, \"biomeDepthOffset\":0.5, \"biomeScaleWeight\":2.0, \"biomeScaleOffset\":0.375, \"useCaves\":true, \"useDungeons\":true, \"dungeonChance\":8, \"useStrongholds\":true, \"useVillages\":true, \"useMineShafts\":true, \"useTemples\":true, \"useRavines\":true, \"useWaterLakes\":true, \"waterLakeChance\":4, \"useLavaLakes\":true, \"lavaLakeChance\":80, \"useLavaOceans\":false, \"seaLevel\":255 }"); @@ -214,73 +153,137 @@ public class GuiScreenCustomizePresets extends GuiScreen { I18n.format("createWorld.customize.custom.preset.goodLuck", new Object[0]), resourcelocation, chunkprovidersettings$factory)); } + private GuiScreenCustomizePresets.ListPreset field_175311_g; + private GuiButton field_175316_h; + private GuiTextField field_175317_i; + private GuiCustomizeWorldScreen field_175314_r; - static class Info { - public String field_178955_a; - public ResourceLocation field_178953_b; - public ChunkProviderSettings.Factory field_178954_c; + protected String field_175315_a = "Customize World Presets"; - public Info(String parString1, ResourceLocation parResourceLocation, ChunkProviderSettings.Factory parFactory) { - this.field_178955_a = parString1; - this.field_178953_b = parResourceLocation; - this.field_178954_c = parFactory; - } + private String field_175313_s; + + private String field_175312_t; + + public GuiScreenCustomizePresets(GuiCustomizeWorldScreen parGuiCustomizeWorldScreen) { + this.field_175314_r = parGuiCustomizeWorldScreen; } - class ListPreset extends GuiSlot { - public int field_178053_u = -1; - - public ListPreset() { - super(GuiScreenCustomizePresets.this.mc, GuiScreenCustomizePresets.this.width, - GuiScreenCustomizePresets.this.height, 80, GuiScreenCustomizePresets.this.height - 32, 38); + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + switch (parGuiButton.id) { + case 0: + this.field_175314_r.func_175324_a(this.field_175317_i.getText()); + this.mc.displayGuiScreen(this.field_175314_r); + break; + case 1: + this.mc.displayGuiScreen(this.field_175314_r); } - protected int getSize() { - return GuiScreenCustomizePresets.field_175310_f.size(); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.field_175311_g.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.field_175315_a, this.width / 2, 8, 16777215); + this.drawString(this.fontRendererObj, this.field_175313_s, 50, 30, 10526880); + this.drawString(this.fontRendererObj, this.field_175312_t, 50, 70, 10526880); + this.field_175317_i.drawTextBox(); + super.drawScreen(i, j, f); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + field_175317_i.fireInputEvent(event, param); + } + + public void func_175304_a() { + this.field_175316_h.enabled = this.func_175305_g(); + } + + private boolean func_175305_g() { + return this.field_175311_g.field_178053_u > -1 && this.field_175311_g.field_178053_u < field_175310_f.size() + || this.field_175317_i.getText().length() > 1; + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.field_175311_g.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.field_175311_g.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + Keyboard.enableRepeatEvents(true); + this.field_175315_a = I18n.format("createWorld.customize.custom.presets.title", new Object[0]); + this.field_175313_s = I18n.format("createWorld.customize.presets.share", new Object[0]); + this.field_175312_t = I18n.format("createWorld.customize.presets.list", new Object[0]); + this.field_175317_i = new GuiTextField(2, this.fontRendererObj, 50, 40, this.width - 100, 20); + this.field_175311_g = new GuiScreenCustomizePresets.ListPreset(); + this.field_175317_i.setMaxStringLength(2000); + this.field_175317_i.setText(this.field_175314_r.func_175323_a()); + this.buttonList.add(this.field_175316_h = new GuiButton(0, this.width / 2 - 102, this.height - 27, 100, 20, + I18n.format("createWorld.customize.presets.select", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 + 3, this.height - 27, 100, 20, + I18n.format("gui.cancel", new Object[0]))); + this.func_175304_a(); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (!this.field_175317_i.textboxKeyTyped(parChar1, parInt1)) { + super.keyTyped(parChar1, parInt1); } - protected void elementClicked(int i, boolean var2, int var3, int var4) { - this.field_178053_u = i; - GuiScreenCustomizePresets.this.func_175304_a(); - GuiScreenCustomizePresets.this.field_175317_i - .setText(((GuiScreenCustomizePresets.Info) GuiScreenCustomizePresets.field_175310_f - .get(GuiScreenCustomizePresets.this.field_175311_g.field_178053_u)).field_178954_c - .toString()); - } + } - protected boolean isSelected(int i) { - return i == this.field_178053_u; - } + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + this.field_175317_i.mouseClicked(parInt1, parInt2, parInt3); + super.mouseClicked(parInt1, parInt2, parInt3); + } - protected void drawBackground() { - } + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } - private void func_178051_a(int parInt1, int parInt2, ResourceLocation parResourceLocation) { - int i = parInt1 + 5; - GuiScreenCustomizePresets.this.drawHorizontalLine(i - 1, i + 32, parInt2 - 1, -2039584); - GuiScreenCustomizePresets.this.drawHorizontalLine(i - 1, i + 32, parInt2 + 32, -6250336); - GuiScreenCustomizePresets.this.drawVerticalLine(i - 1, parInt2 - 1, parInt2 + 32, -2039584); - GuiScreenCustomizePresets.this.drawVerticalLine(i + 32, parInt2 - 1, parInt2 + 32, -6250336); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(parResourceLocation); - boolean flag = true; - boolean flag1 = true; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (i + 0), (double) (parInt2 + 32), 0.0D).tex(0.0D, 1.0D).endVertex(); - worldrenderer.pos((double) (i + 32), (double) (parInt2 + 32), 0.0D).tex(1.0D, 1.0D).endVertex(); - worldrenderer.pos((double) (i + 32), (double) (parInt2 + 0), 0.0D).tex(1.0D, 0.0D).endVertex(); - worldrenderer.pos((double) (i + 0), (double) (parInt2 + 0), 0.0D).tex(0.0D, 0.0D).endVertex(); - tessellator.draw(); - } + @Override + public boolean showCopyPasteButtons() { + return field_175317_i.isFocused(); + } - protected void drawSlot(int i, int j, int k, int var4, int var5, int var6) { - GuiScreenCustomizePresets.Info guiscreencustomizepresets$info = (GuiScreenCustomizePresets.Info) GuiScreenCustomizePresets.field_175310_f - .get(i); - this.func_178051_a(j, k, guiscreencustomizepresets$info.field_178953_b); - GuiScreenCustomizePresets.this.fontRendererObj.drawString(guiscreencustomizepresets$info.field_178955_a, - j + 32 + 10, k + 14, 16777215); - } + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.field_175317_i.updateCursorCounter(); + super.updateScreen(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenOptionsSounds.java b/src/game/java/net/minecraft/client/gui/GuiScreenOptionsSounds.java index 83a3709f..efbefc32 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenOptionsSounds.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenOptionsSounds.java @@ -10,94 +10,30 @@ import net.minecraft.client.settings.GameSettings; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenOptionsSounds extends GuiScreen { - private final GuiScreen field_146505_f; - private final GameSettings game_settings_4; - protected String field_146507_a = "Options"; - private String field_146508_h; - - public GuiScreenOptionsSounds(GuiScreen parGuiScreen, GameSettings parGameSettings) { - this.field_146505_f = parGuiScreen; - this.game_settings_4 = parGameSettings; - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - int i = 0; - this.field_146507_a = I18n.format("options.sounds.title", new Object[0]); - this.field_146508_h = I18n.format("options.off", new Object[0]); - this.buttonList.add(new GuiScreenOptionsSounds.Button(SoundCategory.MASTER.getCategoryId(), - this.width / 2 - 155 + i % 2 * 160, this.height / 6 - 12 + 24 * (i >> 1), SoundCategory.MASTER, true)); - i = i + 2; - - SoundCategory[] cats = SoundCategory._VALUES; - for (int j = 0; j < cats.length; ++j) { - SoundCategory soundcategory = cats[j]; - if (soundcategory != SoundCategory.MASTER) { - this.buttonList.add(new GuiScreenOptionsSounds.Button(soundcategory.getCategoryId(), - this.width / 2 - 155 + i % 2 * 160, this.height / 6 - 12 + 24 * (i >> 1), soundcategory, - false)); - ++i; - } - } - - this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height / 6 + 168, - I18n.format("gui.done", new Object[0]))); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id == 200) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(this.field_146505_f); - } - - } - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, this.field_146507_a, this.width / 2, 15, 16777215); - super.drawScreen(i, j, f); - } - - protected String getSoundVolume(SoundCategory parSoundCategory) { - float f = this.game_settings_4.getSoundLevel(parSoundCategory); - return f == 0.0F ? this.field_146508_h : (int) (f * 100.0F) + "%"; - } - class Button extends GuiButton { private final SoundCategory field_146153_r; private final String field_146152_s; @@ -117,6 +53,10 @@ public class GuiScreenOptionsSounds extends GuiScreen { return 0; } + public boolean isSliderTouchEvents() { + return true; + } + protected void mouseDragged(Minecraft minecraft, int i, int var3) { if (this.visible) { if (this.field_146155_p) { @@ -151,9 +91,6 @@ public class GuiScreenOptionsSounds extends GuiScreen { } } - public void playPressSound(SoundHandler var1) { - } - public void mouseReleased(int var1, int var2) { if (this.field_146155_p) { if (this.field_146153_r == SoundCategory.MASTER) { @@ -169,8 +106,75 @@ public class GuiScreenOptionsSounds extends GuiScreen { this.field_146155_p = false; } - public boolean isSliderTouchEvents() { - return true; + public void playPressSound(SoundHandler var1) { } } + + private final GuiScreen field_146505_f; + private final GameSettings game_settings_4; + protected String field_146507_a = "Options"; + + private String field_146508_h; + + public GuiScreenOptionsSounds(GuiScreen parGuiScreen, GameSettings parGameSettings) { + this.field_146505_f = parGuiScreen; + this.game_settings_4 = parGameSettings; + } + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id == 200) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(this.field_146505_f); + } + + } + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, this.field_146507_a, this.width / 2, 15, 16777215); + super.drawScreen(i, j, f); + } + + protected String getSoundVolume(SoundCategory parSoundCategory) { + float f = this.game_settings_4.getSoundLevel(parSoundCategory); + return f == 0.0F ? this.field_146508_h : (int) (f * 100.0F) + "%"; + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + int i = 0; + this.field_146507_a = I18n.format("options.sounds.title", new Object[0]); + this.field_146508_h = I18n.format("options.off", new Object[0]); + this.buttonList.add(new GuiScreenOptionsSounds.Button(SoundCategory.MASTER.getCategoryId(), + this.width / 2 - 155 + i % 2 * 160, this.height / 6 - 12 + 24 * (i >> 1), SoundCategory.MASTER, true)); + i = i + 2; + + SoundCategory[] cats = SoundCategory._VALUES; + for (int j = 0; j < cats.length; ++j) { + SoundCategory soundcategory = cats[j]; + if (soundcategory != SoundCategory.MASTER) { + this.buttonList.add(new GuiScreenOptionsSounds.Button(soundcategory.getCategoryId(), + this.width / 2 - 155 + i % 2 * 160, this.height / 6 - 12 + 24 * (i >> 1), soundcategory, + false)); + ++i; + } + } + + this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height / 6 + 168, + I18n.format("gui.done", new Object[0]))); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenResourcePacks.java b/src/game/java/net/minecraft/client/gui/GuiScreenResourcePacks.java index 3cb874ce..cbd551b9 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenResourcePacks.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenResourcePacks.java @@ -19,22 +19,25 @@ import net.minecraft.client.resources.ResourcePackListEntryDefault; import net.minecraft.client.resources.ResourcePackListEntryFound; import net.minecraft.client.resources.ResourcePackRepository; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,94 +55,9 @@ public class GuiScreenResourcePacks extends GuiScreen { this.parentScreen = parentScreenIn; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.add(new GuiOptionButton(2, this.width / 2 - 154, this.height - 48, - I18n.format("resourcePack.openFolder", new Object[0]))); - this.buttonList.add( - new GuiOptionButton(1, this.width / 2 + 4, this.height - 48, I18n.format("gui.done", new Object[0]))); - if (!this.changed) { - this.availableResourcePacks = Lists.newArrayList(); - this.selectedResourcePacks = Lists.newArrayList(); - ResourcePackRepository resourcepackrepository = this.mc.getResourcePackRepository(); - resourcepackrepository.updateRepositoryEntriesAll(); - List arraylist = Lists.newArrayList(resourcepackrepository.getRepositoryEntriesAll()); - arraylist.removeAll(resourcepackrepository.getRepositoryEntries()); - - for (int i = 0, l = arraylist.size(); i < l; ++i) { - this.availableResourcePacks - .add(new ResourcePackListEntryFound(this, (ResourcePackRepository.Entry) arraylist.get(i))); - } - - arraylist = Lists.reverse(resourcepackrepository.getRepositoryEntries()); - for (int i = 0, l = arraylist.size(); i < l; ++i) { - this.selectedResourcePacks - .add(new ResourcePackListEntryFound(this, (ResourcePackRepository.Entry) arraylist.get(i))); - } - - this.selectedResourcePacks.add(new ResourcePackListEntryDefault(this)); - } - - this.availableResourcePacksList = new GuiResourcePackAvailable(this.mc, 200, this.height, - this.availableResourcePacks); - this.availableResourcePacksList.setSlotXBoundsFromLeft(this.width / 2 - 4 - 200); - this.availableResourcePacksList.registerScrollButtons(7, 8); - this.selectedResourcePacksList = new GuiResourcePackSelected(this.mc, 200, this.height, - this.selectedResourcePacks); - this.selectedResourcePacksList.setSlotXBoundsFromLeft(this.width / 2 + 4); - this.selectedResourcePacksList.registerScrollButtons(7, 8); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.selectedResourcePacksList.handleMouseInput(); - this.availableResourcePacksList.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.selectedResourcePacksList.handleTouchInput(); - this.availableResourcePacksList.handleTouchInput(); - } - - public boolean hasResourcePackEntry(ResourcePackListEntry parResourcePackListEntry) { - return this.selectedResourcePacks.contains(parResourcePackListEntry); - } - - /**+ - * Returns the list containing the resource pack entry, returns - * the selected list if it is selected, otherwise returns the - * available list - */ - public List getListContaining(ResourcePackListEntry parResourcePackListEntry) { - return this.hasResourcePackEntry(parResourcePackListEntry) ? this.selectedResourcePacks - : this.availableResourcePacks; - } - - /**+ - * Returns a list containing the available resource packs - */ - public List getAvailableResourcePacks() { - return this.availableResourcePacks; - } - - /**+ - * Returns a list containing the selected resource packs - */ - public List getSelectedResourcePacks() { - return this.selectedResourcePacks; - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -180,6 +98,130 @@ public class GuiScreenResourcePacks extends GuiScreen { } } + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawBackground(0); + this.availableResourcePacksList.drawScreen(i, j, f); + this.selectedResourcePacksList.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, I18n.format("resourcePack.title", new Object[0]), this.width / 2, + 16, 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("resourcePack.folderInfo", new Object[0]), + this.width / 2 - 77, this.height - 26, 8421504); + super.drawScreen(i, j, f); + } + + /** + * + Returns a list containing the available resource packs + */ + public List getAvailableResourcePacks() { + return this.availableResourcePacks; + } + + /** + * + Returns the list containing the resource pack entry, returns the selected + * list if it is selected, otherwise returns the available list + */ + public List getListContaining(ResourcePackListEntry parResourcePackListEntry) { + return this.hasResourcePackEntry(parResourcePackListEntry) ? this.selectedResourcePacks + : this.availableResourcePacks; + } + + /** + * + Returns a list containing the selected resource packs + */ + public List getSelectedResourcePacks() { + return this.selectedResourcePacks; + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.selectedResourcePacksList.handleMouseInput(); + this.availableResourcePacksList.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.selectedResourcePacksList.handleTouchInput(); + this.availableResourcePacksList.handleTouchInput(); + } + + public boolean hasResourcePackEntry(ResourcePackListEntry parResourcePackListEntry) { + return this.selectedResourcePacks.contains(parResourcePackListEntry); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.add(new GuiOptionButton(2, this.width / 2 - 154, this.height - 48, + I18n.format("resourcePack.openFolder", new Object[0]))); + this.buttonList.add( + new GuiOptionButton(1, this.width / 2 + 4, this.height - 48, I18n.format("gui.done", new Object[0]))); + if (!this.changed) { + this.availableResourcePacks = Lists.newArrayList(); + this.selectedResourcePacks = Lists.newArrayList(); + ResourcePackRepository resourcepackrepository = this.mc.getResourcePackRepository(); + resourcepackrepository.updateRepositoryEntriesAll(); + List arraylist = Lists.newArrayList(resourcepackrepository.getRepositoryEntriesAll()); + arraylist.removeAll(resourcepackrepository.getRepositoryEntries()); + + for (int i = 0, l = arraylist.size(); i < l; ++i) { + this.availableResourcePacks + .add(new ResourcePackListEntryFound(this, (ResourcePackRepository.Entry) arraylist.get(i))); + } + + arraylist = Lists.reverse(resourcepackrepository.getRepositoryEntries()); + for (int i = 0, l = arraylist.size(); i < l; ++i) { + this.selectedResourcePacks + .add(new ResourcePackListEntryFound(this, (ResourcePackRepository.Entry) arraylist.get(i))); + } + + this.selectedResourcePacks.add(new ResourcePackListEntryDefault(this)); + } + + this.availableResourcePacksList = new GuiResourcePackAvailable(this.mc, 200, this.height, + this.availableResourcePacks); + this.availableResourcePacksList.setSlotXBoundsFromLeft(this.width / 2 - 4 - 200); + this.availableResourcePacksList.registerScrollButtons(7, 8); + this.selectedResourcePacksList = new GuiResourcePackSelected(this.mc, 200, this.height, + this.selectedResourcePacks); + this.selectedResourcePacksList.setSlotXBoundsFromLeft(this.width / 2 + 4); + this.selectedResourcePacksList.registerScrollButtons(7, 8); + } + + /** + * + Marks the selected resource packs list as changed to trigger a resource + * reload when the screen is closed + */ + public void markChanged() { + this.changed = true; + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + this.availableResourcePacksList.mouseClicked(parInt1, parInt2, parInt3); + this.selectedResourcePacksList.mouseClicked(parInt1, parInt2, parInt3); + } + + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton + */ + protected void mouseReleased(int i, int j, int k) { + super.mouseReleased(i, j, k); + } + public void updateScreen() { FileChooserResult packFile = null; if (EagRuntime.fileChooserHasResult()) { @@ -229,45 +271,4 @@ public class GuiScreenResourcePacks extends GuiScreen { this.initGui(); this.changed = wasChanged; } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - this.availableResourcePacksList.mouseClicked(parInt1, parInt2, parInt3); - this.selectedResourcePacksList.mouseClicked(parInt1, parInt2, parInt3); - } - - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton - */ - protected void mouseReleased(int i, int j, int k) { - super.mouseReleased(i, j, k); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawBackground(0); - this.availableResourcePacksList.drawScreen(i, j, f); - this.selectedResourcePacksList.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, I18n.format("resourcePack.title", new Object[0]), this.width / 2, - 16, 16777215); - this.drawCenteredString(this.fontRendererObj, I18n.format("resourcePack.folderInfo", new Object[0]), - this.width / 2 - 77, this.height - 26, 8421504); - super.drawScreen(i, j, f); - } - - /**+ - * Marks the selected resource packs list as changed to trigger - * a resource reload when the screen is closed - */ - public void markChanged() { - this.changed = true; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenServerList.java b/src/game/java/net/minecraft/client/gui/GuiScreenServerList.java index 46bd254c..a39e8d6b 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenServerList.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenServerList.java @@ -6,22 +6,25 @@ import net.lax1dude.eaglercraft.v1_8.minecraft.EnumInputEvent; import net.minecraft.client.multiplayer.ServerData; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,50 +39,9 @@ public class GuiScreenServerList extends GuiScreen { this.field_146301_f = parServerData; } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.field_146302_g.updateCursorCounter(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, - I18n.format("selectServer.select", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, - I18n.format("gui.cancel", new Object[0]))); - if (EagRuntime.requireSSL()) { - this.field_146302_g = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 35, - 200, 20); - } else { - this.field_146302_g = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, 116, 200, 20); - } - this.field_146302_g.setMaxStringLength(128); - this.field_146302_g.setFocused(true); - this.field_146302_g.setText(this.mc.gameSettings.lastServer); - ((GuiButton) this.buttonList.get(0)).enabled = this.field_146302_g.getText().trim().length() > 0; - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - this.mc.gameSettings.lastServer = this.field_146302_g.getText(); - this.mc.gameSettings.saveOptions(); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -93,33 +55,9 @@ public class GuiScreenServerList extends GuiScreen { } } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (this.field_146302_g.textboxKeyTyped(parChar1, parInt1)) { - ((GuiButton) this.buttonList.get(0)).enabled = this.field_146302_g.getText().trim().length() > 0; - } else if (parInt1 == 28 || parInt1 == 156) { - this.actionPerformed((GuiButton) this.buttonList.get(0)); - } - - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton - */ - protected void mouseClicked(int parInt1, int parInt2, int parInt3) { - super.mouseClicked(parInt1, parInt2, parInt3); - this.field_146302_g.mouseClicked(parInt1, parInt2, parInt3); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -140,14 +78,76 @@ public class GuiScreenServerList extends GuiScreen { super.drawScreen(i, j, f); } - @Override - public boolean showCopyPasteButtons() { - return field_146302_g.isFocused(); - } - @Override public void fireInputEvent(EnumInputEvent event, String param) { field_146302_g.fireInputEvent(event, param); } + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, + I18n.format("selectServer.select", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, + I18n.format("gui.cancel", new Object[0]))); + if (EagRuntime.requireSSL()) { + this.field_146302_g = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 35, + 200, 20); + } else { + this.field_146302_g = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, 116, 200, 20); + } + this.field_146302_g.setMaxStringLength(128); + this.field_146302_g.setFocused(true); + this.field_146302_g.setText(this.mc.gameSettings.lastServer); + ((GuiButton) this.buttonList.get(0)).enabled = this.field_146302_g.getText().trim().length() > 0; + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (this.field_146302_g.textboxKeyTyped(parChar1, parInt1)) { + ((GuiButton) this.buttonList.get(0)).enabled = this.field_146302_g.getText().trim().length() > 0; + } else if (parInt1 == 28 || parInt1 == 156) { + this.actionPerformed((GuiButton) this.buttonList.get(0)); + } + + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton + */ + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { + super.mouseClicked(parInt1, parInt2, parInt3); + this.field_146302_g.mouseClicked(parInt1, parInt2, parInt3); + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + this.mc.gameSettings.lastServer = this.field_146302_g.getText(); + this.mc.gameSettings.saveOptions(); + } + + @Override + public boolean showCopyPasteButtons() { + return field_146302_g.isFocused(); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.field_146302_g.updateCursorCounter(); + } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiScreenWorking.java b/src/game/java/net/minecraft/client/gui/GuiScreenWorking.java index c4d5875f..bf00884e 100644 --- a/src/game/java/net/minecraft/client/gui/GuiScreenWorking.java +++ b/src/game/java/net/minecraft/client/gui/GuiScreenWorking.java @@ -2,22 +2,25 @@ package net.minecraft.client.gui; import net.minecraft.util.IProgressUpdate; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,47 +31,25 @@ public class GuiScreenWorking extends GuiScreen implements IProgressUpdate { private int progress; private boolean doneWorking; - /**+ - * Shows the 'Saving level' string. - */ - public void displaySavingString(String s) { - this.resetProgressAndMessage(s); - } - - /**+ - * this string, followed by "working..." and then the "% - * complete" are the 3 lines shown. This resets progress to 0, - * and the WorkingString to "working...". - */ - public void resetProgressAndMessage(String s) { - this.field_146591_a = s; - this.displayLoadingString("Working..."); - } - - /**+ - * Displays a string on the loading screen supposed to indicate - * what is being done currently. + /** + * + Displays a string on the loading screen supposed to indicate what is being + * done currently. */ public void displayLoadingString(String s) { this.field_146589_f = s; this.setLoadingProgress(0); } - /**+ - * Updates the progress bar on the loading screen to the - * specified amount. Args: loadProgress + /** + * + Shows the 'Saving level' string. */ - public void setLoadingProgress(int i) { - this.progress = i; + public void displaySavingString(String s) { + this.resetProgressAndMessage(s); } - public void setDoneWorking() { - this.doneWorking = true; - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { if (this.doneWorking) { @@ -84,4 +65,26 @@ public class GuiScreenWorking extends GuiScreen implements IProgressUpdate { super.drawScreen(i, j, f); } } + + /** + * + this string, followed by "working..." and then the "% complete" are the 3 + * lines shown. This resets progress to 0, and the WorkingString to + * "working...". + */ + public void resetProgressAndMessage(String s) { + this.field_146591_a = s; + this.displayLoadingString("Working..."); + } + + public void setDoneWorking() { + this.doneWorking = true; + } + + /** + * + Updates the progress bar on the loading screen to the specified amount. + * Args: loadProgress + */ + public void setLoadingProgress(int i) { + this.progress = i; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiSelectWorld.java b/src/game/java/net/minecraft/client/gui/GuiSelectWorld.java index 6a13446e..07812a20 100644 --- a/src/game/java/net/minecraft/client/gui/GuiSelectWorld.java +++ b/src/game/java/net/minecraft/client/gui/GuiSelectWorld.java @@ -7,8 +7,19 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Date; +import org.apache.commons.lang3.StringUtils; + +import net.lax1dude.eaglercraft.v1_8.Mouse; +import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; +import net.lax1dude.eaglercraft.v1_8.sp.SingleplayerServerController; +import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenBackupWorldSelection; +import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenCreateWorldSelection; +import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenIntegratedServerBusy; import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenLANConnect; +import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenLANInfo; import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenLANNotSupported; import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1CIssueDetected; import net.lax1dude.eaglercraft.v1_8.sp.lan.LANServerController; @@ -20,313 +31,37 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.world.WorldSettings; import net.minecraft.world.storage.ISaveFormat; import net.minecraft.world.storage.SaveFormatComparator; -import org.apache.commons.lang3.StringUtils; -import net.lax1dude.eaglercraft.v1_8.Mouse; -import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -import net.lax1dude.eaglercraft.v1_8.sp.SingleplayerServerController; -import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenBackupWorldSelection; -import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenCreateWorldSelection; -import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenIntegratedServerBusy; -import net.lax1dude.eaglercraft.v1_8.sp.gui.GuiScreenLANInfo; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiSelectWorld extends GuiScreen implements GuiYesNoCallback { - private static final Logger logger = LogManager.getLogger(); - private final DateFormat field_146633_h = new SimpleDateFormat(); - protected GuiScreen parentScreen; - protected String field_146628_f = "Select world"; - private boolean field_146634_i; - private int field_146640_r; - private java.util.List field_146639_s; - private GuiSelectWorld.List field_146638_t; - private String field_146637_u; - private String field_146636_v; - private String[] field_146635_w = new String[4]; - private boolean field_146643_x; - private GuiButton deleteButton; - private GuiButton selectButton; - private GuiButton renameButton; - private GuiButton recreateButton; - private boolean hasRequestedWorlds = false; - private boolean waitingForWorlds = false; - private boolean ramdiskMode = false; - - public GuiSelectWorld(GuiScreen parentScreenIn) { - this.parentScreen = parentScreenIn; - this.field_146639_s = new ArrayList(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.ramdiskMode = SingleplayerServerController.isIssueDetected(IPCPacket1CIssueDetected.ISSUE_RAMDISK_MODE); - this.field_146628_f = I18n.format("selectWorld.title", new Object[0]); - this.field_146637_u = I18n.format("selectWorld.world", new Object[0]); - this.field_146636_v = I18n.format("selectWorld.conversion", new Object[0]); - this.field_146635_w[WorldSettings.GameType.SURVIVAL.getID()] = I18n.format("gameMode.survival", new Object[0]); - this.field_146635_w[WorldSettings.GameType.CREATIVE.getID()] = I18n.format("gameMode.creative", new Object[0]); - this.field_146635_w[WorldSettings.GameType.ADVENTURE.getID()] = I18n.format("gameMode.adventure", - new Object[0]); - this.field_146635_w[WorldSettings.GameType.SPECTATOR.getID()] = I18n.format("gameMode.spectator", - new Object[0]); - this.field_146638_t = new GuiSelectWorld.List(this.mc, ramdiskMode ? -10 : 0); - this.field_146638_t.registerScrollButtons(4, 5); - this.func_146618_g(); - } - - public void updateScreen() { - if (!hasRequestedWorlds && SingleplayerServerController.isReady()) { - hasRequestedWorlds = true; - waitingForWorlds = true; - this.mc.getSaveLoader().flushCache(); - this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(this, "singleplayer.busy.listingworlds", - "singleplayer.failed.listingworlds", SingleplayerServerController::isReady, (t, u) -> { - GuiScreenIntegratedServerBusy tt = (GuiScreenIntegratedServerBusy) t; - Minecraft.getMinecraft().displayGuiScreen( - GuiScreenIntegratedServerBusy.createException(parentScreen, tt.failMessage, u)); - })); - } else if (waitingForWorlds && SingleplayerServerController.isReady()) { - waitingForWorlds = false; - this.func_146627_h(); - } - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.field_146638_t.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.field_146638_t.handleTouchInput(); - } - - private void func_146627_h() { - ISaveFormat isaveformat = this.mc.getSaveLoader(); - this.field_146639_s = isaveformat.getSaveList(); - Collections.sort(this.field_146639_s); - this.field_146640_r = -1; - } - - protected String func_146621_a(int parInt1) { - return ((SaveFormatComparator) this.field_146639_s.get(parInt1)).getFileName(); - } - - protected String func_146614_d(int parInt1) { - String s = ((SaveFormatComparator) this.field_146639_s.get(parInt1)).getDisplayName(); - if (StringUtils.isEmpty(s)) { - s = I18n.format("selectWorld.world", new Object[0]) + " " + (parInt1 + 1); - } - - return s; - } - - public void func_146618_g() { - this.buttonList.add(this.selectButton = new GuiButton(1, this.width / 2 - 154, this.height - 52, 150, 20, - I18n.format("selectWorld.select", new Object[0]))); - this.buttonList.add(new GuiButton(3, this.width / 2 + 4, this.height - 52, 150, 20, - I18n.format("selectWorld.create", new Object[0]))); - this.buttonList.add(this.renameButton = new GuiButton(6, this.width / 2 - 154, this.height - 28, 72, 20, - I18n.format("selectWorld.rename", new Object[0]))); - this.buttonList.add(this.deleteButton = new GuiButton(2, this.width / 2 - 76, this.height - 28, 72, 20, - I18n.format("selectWorld.delete", new Object[0]))); - this.buttonList.add(this.recreateButton = new GuiButton(7, this.width / 2 + 4, this.height - 28, 72, 20, - I18n.format("selectWorld.backup", new Object[0]))); - this.buttonList.add(new GuiButton(0, this.width / 2 + 82, this.height - 28, 72, 20, - I18n.format("gui.cancel", new Object[0]))); - this.selectButton.enabled = false; - this.deleteButton.enabled = false; - this.renameButton.enabled = false; - this.recreateButton.enabled = false; - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id == 2) { - String s = this.func_146614_d(this.field_146640_r); - if (s != null) { - this.field_146643_x = true; - GuiYesNo guiyesno = func_152129_a(this, s, this.field_146640_r); - this.mc.displayGuiScreen(guiyesno); - } - } else if (parGuiButton.id == 1) { - this.func_146615_e(this.field_146640_r); - } else if (parGuiButton.id == 3) { - hasRequestedWorlds = false; // force refresh - this.mc.displayGuiScreen(new GuiScreenCreateWorldSelection(this)); - } else if (parGuiButton.id == 6) { - hasRequestedWorlds = false; // force refresh - this.mc.displayGuiScreen(new GuiRenameWorld(this, this.func_146621_a(this.field_146640_r))); - } else if (parGuiButton.id == 0) { - this.mc.displayGuiScreen(this.parentScreen); - } else if (parGuiButton.id == 7) { - hasRequestedWorlds = false; // force refresh - this.mc.displayGuiScreen( - new GuiScreenBackupWorldSelection(this, this.func_146621_a(this.field_146640_r), - ((SaveFormatComparator) field_146639_s.get(this.field_146640_r)).levelDat)); - } else { - this.field_146638_t.actionPerformed(parGuiButton); - } - - } - } - - public void func_146615_e(int parInt1) { - this.mc.displayGuiScreen((GuiScreen) null); - if (!this.field_146634_i) { - this.field_146634_i = true; - String s = this.func_146621_a(parInt1); - if (s == null) { - s = "World" + parInt1; - } - - String s1 = this.func_146614_d(parInt1); - if (s1 == null) { - s1 = "World" + parInt1; - } - - if (this.mc.getSaveLoader().canLoadWorld(s)) { - this.mc.launchIntegratedServer(s, s1, (WorldSettings) null); - } - - } - } - - public void confirmClicked(boolean flag, int i) { - if (this.field_146643_x) { - this.field_146643_x = false; - if (flag) { - hasRequestedWorlds = false; // force refresh - ISaveFormat isaveformat = this.mc.getSaveLoader(); - isaveformat.deleteWorldDirectory(this.func_146621_a(i)); - this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(this, "singleplayer.busy.deleting", - "singleplayer.failed.deleting", SingleplayerServerController::isReady)); - } else { - this.mc.displayGuiScreen(this); - } - } - - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.field_146638_t.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.field_146628_f, this.width / 2, 20, 16777215); - - if (ramdiskMode) { - this.drawCenteredString(this.fontRendererObj, I18n.format("selectWorld.ramdiskWarning"), this.width / 2, - height - 68, 11184810); - } - - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - - String text = I18n.format("directConnect.lanWorld"); - int w = mc.fontRendererObj.getStringWidth(text); - boolean hover = i > 1 && j > 1 && i < (w * 3 / 4) + 7 && j < 12; - if (hover) { - Mouse.showCursor(EnumCursorType.HAND); - } - - drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); - - GlStateManager.popMatrix(); - - super.drawScreen(i, j, f); - } - - @Override - public void mouseClicked(int xx, int yy, int btn) { - String text = I18n.format("directConnect.lanWorld"); - int w = mc.fontRendererObj.getStringWidth(text); - if (xx > 2 && yy > 2 && xx < (w * 3 / 4) + 5 && yy < 12) { - if (LANServerController.supported()) { - mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenLANConnect(this))); - } else { - mc.displayGuiScreen(new GuiScreenLANNotSupported(this)); - } - mc.getSoundHandler() - .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - } - super.mouseClicked(xx, yy, btn); - } - - public static GuiYesNo func_152129_a(GuiYesNoCallback parGuiYesNoCallback, String parString1, int parInt1) { - String s = I18n.format("selectWorld.deleteQuestion", new Object[0]); - String s1 = "\'" + parString1 + "\' " + I18n.format("selectWorld.deleteWarning", new Object[0]); - String s2 = I18n.format("selectWorld.deleteButton", new Object[0]); - String s3 = I18n.format("gui.cancel", new Object[0]); - GuiYesNo guiyesno = new GuiYesNo(parGuiYesNoCallback, s, s1, s2, s3, parInt1); - return guiyesno; - } - class List extends GuiSlot { public List(Minecraft mcIn, int i) { super(mcIn, GuiSelectWorld.this.width, GuiSelectWorld.this.height, 32, GuiSelectWorld.this.height - 64 + i, 36); } - protected int getSize() { - return GuiSelectWorld.this.field_146639_s.size(); - } - - protected void elementClicked(int i, boolean flag, int var3, int var4) { - GuiSelectWorld.this.field_146640_r = i; - boolean flag1 = GuiSelectWorld.this.field_146640_r >= 0 - && GuiSelectWorld.this.field_146640_r < this.getSize(); - GuiSelectWorld.this.selectButton.enabled = flag1; - GuiSelectWorld.this.deleteButton.enabled = flag1; - GuiSelectWorld.this.renameButton.enabled = flag1; - GuiSelectWorld.this.recreateButton.enabled = flag1; - if (flag && flag1) { - GuiSelectWorld.this.func_146615_e(i); - } - - } - - protected boolean isSelected(int i) { - return i == GuiSelectWorld.this.field_146640_r; - } - - protected int getContentHeight() { - return GuiSelectWorld.this.field_146639_s.size() * 36; - } - protected void drawBackground() { GuiSelectWorld.this.drawDefaultBackground(); } @@ -362,5 +97,276 @@ public class GuiSelectWorld extends GuiScreen implements GuiYesNoCallback { GuiSelectWorld.this.drawString(GuiSelectWorld.this.fontRendererObj, s1, j + 2, k + 12, 8421504); GuiSelectWorld.this.drawString(GuiSelectWorld.this.fontRendererObj, s2, j + 2, k + 12 + 10, 8421504); } + + protected void elementClicked(int i, boolean flag, int var3, int var4) { + GuiSelectWorld.this.field_146640_r = i; + boolean flag1 = GuiSelectWorld.this.field_146640_r >= 0 + && GuiSelectWorld.this.field_146640_r < this.getSize(); + GuiSelectWorld.this.selectButton.enabled = flag1; + GuiSelectWorld.this.deleteButton.enabled = flag1; + GuiSelectWorld.this.renameButton.enabled = flag1; + GuiSelectWorld.this.recreateButton.enabled = flag1; + if (flag && flag1) { + GuiSelectWorld.this.func_146615_e(i); + } + + } + + protected int getContentHeight() { + return GuiSelectWorld.this.field_146639_s.size() * 36; + } + + protected int getSize() { + return GuiSelectWorld.this.field_146639_s.size(); + } + + protected boolean isSelected(int i) { + return i == GuiSelectWorld.this.field_146640_r; + } + } + + private static final Logger logger = LogManager.getLogger(); + + public static GuiYesNo func_152129_a(GuiYesNoCallback parGuiYesNoCallback, String parString1, int parInt1) { + String s = I18n.format("selectWorld.deleteQuestion", new Object[0]); + String s1 = "\'" + parString1 + "\' " + I18n.format("selectWorld.deleteWarning", new Object[0]); + String s2 = I18n.format("selectWorld.deleteButton", new Object[0]); + String s3 = I18n.format("gui.cancel", new Object[0]); + GuiYesNo guiyesno = new GuiYesNo(parGuiYesNoCallback, s, s1, s2, s3, parInt1); + return guiyesno; + } + + private final DateFormat field_146633_h = new SimpleDateFormat(); + protected GuiScreen parentScreen; + protected String field_146628_f = "Select world"; + private boolean field_146634_i; + private int field_146640_r; + private java.util.List field_146639_s; + private GuiSelectWorld.List field_146638_t; + private String field_146637_u; + private String field_146636_v; + private String[] field_146635_w = new String[4]; + private boolean field_146643_x; + private GuiButton deleteButton; + private GuiButton selectButton; + private GuiButton renameButton; + private GuiButton recreateButton; + private boolean hasRequestedWorlds = false; + + private boolean waitingForWorlds = false; + + private boolean ramdiskMode = false; + + public GuiSelectWorld(GuiScreen parentScreenIn) { + this.parentScreen = parentScreenIn; + this.field_146639_s = new ArrayList(); + } + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id == 2) { + String s = this.func_146614_d(this.field_146640_r); + if (s != null) { + this.field_146643_x = true; + GuiYesNo guiyesno = func_152129_a(this, s, this.field_146640_r); + this.mc.displayGuiScreen(guiyesno); + } + } else if (parGuiButton.id == 1) { + this.func_146615_e(this.field_146640_r); + } else if (parGuiButton.id == 3) { + hasRequestedWorlds = false; // force refresh + this.mc.displayGuiScreen(new GuiScreenCreateWorldSelection(this)); + } else if (parGuiButton.id == 6) { + hasRequestedWorlds = false; // force refresh + this.mc.displayGuiScreen(new GuiRenameWorld(this, this.func_146621_a(this.field_146640_r))); + } else if (parGuiButton.id == 0) { + this.mc.displayGuiScreen(this.parentScreen); + } else if (parGuiButton.id == 7) { + hasRequestedWorlds = false; // force refresh + this.mc.displayGuiScreen( + new GuiScreenBackupWorldSelection(this, this.func_146621_a(this.field_146640_r), + ((SaveFormatComparator) field_146639_s.get(this.field_146640_r)).levelDat)); + } else { + this.field_146638_t.actionPerformed(parGuiButton); + } + + } + } + + public void confirmClicked(boolean flag, int i) { + if (this.field_146643_x) { + this.field_146643_x = false; + if (flag) { + hasRequestedWorlds = false; // force refresh + ISaveFormat isaveformat = this.mc.getSaveLoader(); + isaveformat.deleteWorldDirectory(this.func_146621_a(i)); + this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(this, "singleplayer.busy.deleting", + "singleplayer.failed.deleting", SingleplayerServerController::isReady)); + } else { + this.mc.displayGuiScreen(this); + } + } + + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.field_146638_t.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.field_146628_f, this.width / 2, 20, 16777215); + + if (ramdiskMode) { + this.drawCenteredString(this.fontRendererObj, I18n.format("selectWorld.ramdiskWarning"), this.width / 2, + height - 68, 11184810); + } + + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + + String text = I18n.format("directConnect.lanWorld"); + int w = mc.fontRendererObj.getStringWidth(text); + boolean hover = i > 1 && j > 1 && i < (w * 3 / 4) + 7 && j < 12; + if (hover) { + Mouse.showCursor(EnumCursorType.HAND); + } + + drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); + + GlStateManager.popMatrix(); + + super.drawScreen(i, j, f); + } + + protected String func_146614_d(int parInt1) { + String s = ((SaveFormatComparator) this.field_146639_s.get(parInt1)).getDisplayName(); + if (StringUtils.isEmpty(s)) { + s = I18n.format("selectWorld.world", new Object[0]) + " " + (parInt1 + 1); + } + + return s; + } + + public void func_146615_e(int parInt1) { + this.mc.displayGuiScreen((GuiScreen) null); + if (!this.field_146634_i) { + this.field_146634_i = true; + String s = this.func_146621_a(parInt1); + if (s == null) { + s = "World" + parInt1; + } + + String s1 = this.func_146614_d(parInt1); + if (s1 == null) { + s1 = "World" + parInt1; + } + + if (this.mc.getSaveLoader().canLoadWorld(s)) { + this.mc.launchIntegratedServer(s, s1, (WorldSettings) null); + } + + } + } + + public void func_146618_g() { + this.buttonList.add(this.selectButton = new GuiButton(1, this.width / 2 - 154, this.height - 52, 150, 20, + I18n.format("selectWorld.select", new Object[0]))); + this.buttonList.add(new GuiButton(3, this.width / 2 + 4, this.height - 52, 150, 20, + I18n.format("selectWorld.create", new Object[0]))); + this.buttonList.add(this.renameButton = new GuiButton(6, this.width / 2 - 154, this.height - 28, 72, 20, + I18n.format("selectWorld.rename", new Object[0]))); + this.buttonList.add(this.deleteButton = new GuiButton(2, this.width / 2 - 76, this.height - 28, 72, 20, + I18n.format("selectWorld.delete", new Object[0]))); + this.buttonList.add(this.recreateButton = new GuiButton(7, this.width / 2 + 4, this.height - 28, 72, 20, + I18n.format("selectWorld.backup", new Object[0]))); + this.buttonList.add(new GuiButton(0, this.width / 2 + 82, this.height - 28, 72, 20, + I18n.format("gui.cancel", new Object[0]))); + this.selectButton.enabled = false; + this.deleteButton.enabled = false; + this.renameButton.enabled = false; + this.recreateButton.enabled = false; + } + + protected String func_146621_a(int parInt1) { + return ((SaveFormatComparator) this.field_146639_s.get(parInt1)).getFileName(); + } + + private void func_146627_h() { + ISaveFormat isaveformat = this.mc.getSaveLoader(); + this.field_146639_s = isaveformat.getSaveList(); + Collections.sort(this.field_146639_s); + this.field_146640_r = -1; + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.field_146638_t.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.field_146638_t.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.ramdiskMode = SingleplayerServerController.isIssueDetected(IPCPacket1CIssueDetected.ISSUE_RAMDISK_MODE); + this.field_146628_f = I18n.format("selectWorld.title", new Object[0]); + this.field_146637_u = I18n.format("selectWorld.world", new Object[0]); + this.field_146636_v = I18n.format("selectWorld.conversion", new Object[0]); + this.field_146635_w[WorldSettings.GameType.SURVIVAL.getID()] = I18n.format("gameMode.survival", new Object[0]); + this.field_146635_w[WorldSettings.GameType.CREATIVE.getID()] = I18n.format("gameMode.creative", new Object[0]); + this.field_146635_w[WorldSettings.GameType.ADVENTURE.getID()] = I18n.format("gameMode.adventure", + new Object[0]); + this.field_146635_w[WorldSettings.GameType.SPECTATOR.getID()] = I18n.format("gameMode.spectator", + new Object[0]); + this.field_146638_t = new GuiSelectWorld.List(this.mc, ramdiskMode ? -10 : 0); + this.field_146638_t.registerScrollButtons(4, 5); + this.func_146618_g(); + } + + @Override + public void mouseClicked(int xx, int yy, int btn) { + String text = I18n.format("directConnect.lanWorld"); + int w = mc.fontRendererObj.getStringWidth(text); + if (xx > 2 && yy > 2 && xx < (w * 3 / 4) + 5 && yy < 12) { + if (LANServerController.supported()) { + mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenLANConnect(this))); + } else { + mc.displayGuiScreen(new GuiScreenLANNotSupported(this)); + } + mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } + super.mouseClicked(xx, yy, btn); + } + + public void updateScreen() { + if (!hasRequestedWorlds && SingleplayerServerController.isReady()) { + hasRequestedWorlds = true; + waitingForWorlds = true; + this.mc.getSaveLoader().flushCache(); + this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(this, "singleplayer.busy.listingworlds", + "singleplayer.failed.listingworlds", SingleplayerServerController::isReady, (t, u) -> { + GuiScreenIntegratedServerBusy tt = (GuiScreenIntegratedServerBusy) t; + Minecraft.getMinecraft().displayGuiScreen( + GuiScreenIntegratedServerBusy.createException(parentScreen, tt.failMessage, u)); + })); + } else if (waitingForWorlds && SingleplayerServerController.isReady()) { + waitingForWorlds = false; + this.func_146627_h(); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiSleepMP.java b/src/game/java/net/minecraft/client/gui/GuiSleepMP.java index 8481ec99..e32005f8 100644 --- a/src/game/java/net/minecraft/client/gui/GuiSleepMP.java +++ b/src/game/java/net/minecraft/client/gui/GuiSleepMP.java @@ -4,31 +4,47 @@ import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.client.resources.I18n; import net.minecraft.network.play.client.C0BPacketEntityAction; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiSleepMP extends GuiChat { - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 1) { + this.wakeFromSleep(); + } else { + super.actionPerformed(parGuiButton); + } + + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { super.initGui(); @@ -36,11 +52,10 @@ public class GuiSleepMP extends GuiChat { I18n.format("multiplayer.stopSleeping", new Object[0]))); } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { if (parInt1 == 1) { @@ -59,19 +74,6 @@ public class GuiSleepMP extends GuiChat { } - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == 1) { - this.wakeFromSleep(); - } else { - super.actionPerformed(parGuiButton); - } - - } - private void wakeFromSleep() { NetHandlerPlayClient nethandlerplayclient = this.mc.thePlayer.sendQueue; nethandlerplayclient.addToSendQueue( diff --git a/src/game/java/net/minecraft/client/gui/GuiSlider.java b/src/game/java/net/minecraft/client/gui/GuiSlider.java index 2461dd95..3c44f9b5 100644 --- a/src/game/java/net/minecraft/client/gui/GuiSlider.java +++ b/src/game/java/net/minecraft/client/gui/GuiSlider.java @@ -4,33 +4,41 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiSlider extends GuiButton { + public interface FormatHelper { + String getText(int var1, String var2, float var3); + } + private float sliderPosition = 1.0F; public boolean isMouseDown; private String name; private final float min; private final float max; private final GuiPageButtonList.GuiResponder responder; + private GuiSlider.FormatHelper formatHelper; public GuiSlider(GuiPageButtonList.GuiResponder guiResponder, int idIn, int x, int y, String name, float min, @@ -45,8 +53,8 @@ public class GuiSlider extends GuiButton { this.displayString = this.getDisplayString(); } - public float func_175220_c() { - return this.min + (this.max - this.min) * this.sliderPosition; + public float func_175217_d() { + return this.sliderPosition; } public void func_175218_a(float parFloat1, boolean parFlag) { @@ -58,8 +66,14 @@ public class GuiSlider extends GuiButton { } - public float func_175217_d() { - return this.sliderPosition; + public void func_175219_a(float parFloat1) { + this.sliderPosition = parFloat1; + this.displayString = this.getDisplayString(); + this.responder.onTick(this.id, this.func_175220_c()); + } + + public float func_175220_c() { + return this.min + (this.max - this.min) * this.sliderPosition; } private String getDisplayString() { @@ -67,17 +81,20 @@ public class GuiSlider extends GuiButton { : this.formatHelper.getText(this.id, I18n.format(this.name, new Object[0]), this.func_175220_c()); } - /**+ - * Returns 0 if the button is disabled, 1 if the mouse is NOT - * hovering over this button and 2 if it IS hovering over this - * button. + /** + * + Returns 0 if the button is disabled, 1 if the mouse is NOT hovering over + * this button and 2 if it IS hovering over this button. */ protected int getHoverState(boolean var1) { return 0; } - /**+ - * Fired when the mouse button is dragged. Equivalent of + public boolean isSliderTouchEvents() { + return true; + } + + /** + * + Fired when the mouse button is dragged. Equivalent of * MouseListener.mouseDragged(MouseEvent e). */ protected void mouseDragged(Minecraft var1, int i, int var3) { @@ -104,15 +121,9 @@ public class GuiSlider extends GuiButton { } } - public void func_175219_a(float parFloat1) { - this.sliderPosition = parFloat1; - this.displayString = this.getDisplayString(); - this.responder.onTick(this.id, this.func_175220_c()); - } - - /**+ - * Returns true if the mouse has been pressed on this control. - * Equivalent of MouseListener.mousePressed(MouseEvent e). + /** + * + Returns true if the mouse has been pressed on this control. Equivalent of + * MouseListener.mousePressed(MouseEvent e). */ public boolean mousePressed(Minecraft minecraft, int i, int j) { if (super.mousePressed(minecraft, i, j)) { @@ -134,19 +145,11 @@ public class GuiSlider extends GuiButton { } } - /**+ - * Fired when the mouse button is released. Equivalent of + /** + * + Fired when the mouse button is released. Equivalent of * MouseListener.mouseReleased(MouseEvent e). */ public void mouseReleased(int var1, int var2) { this.isMouseDown = false; } - - public interface FormatHelper { - String getText(int var1, String var2, float var3); - } - - public boolean isSliderTouchEvents() { - return true; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiSlot.java b/src/game/java/net/minecraft/client/gui/GuiSlot.java index 324f7334..9c85231b 100644 --- a/src/game/java/net/minecraft/client/gui/GuiSlot.java +++ b/src/game/java/net/minecraft/client/gui/GuiSlot.java @@ -1,6 +1,9 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; @@ -16,22 +19,25 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,22 +59,20 @@ public abstract class GuiSlot { protected int mouseX; protected int mouseY; protected boolean field_148163_i = true; - /**+ - * Where the mouse was in the window when you first clicked to - * scroll + /** + * + Where the mouse was in the window when you first clicked to scroll */ protected int initialClickY = -2; protected float scrollMultiplier; protected float amountScrolled; - /**+ - * The element in the list that was selected + /** + * + The element in the list that was selected */ protected int selectedElement = -1; protected long lastClicked; protected boolean field_178041_q = true; - /**+ - * Set to true if a selected element in this gui will show an - * outline box + /** + * + Set to true if a selected element in this gui will show an outline box */ protected boolean showSelectionBox = true; protected boolean hasListHeader; @@ -86,116 +90,6 @@ public abstract class GuiSlot { this.right = width; } - public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn) { - this.width = widthIn; - this.height = heightIn; - this.top = topIn; - this.bottom = bottomIn; - this.left = 0; - this.right = widthIn; - } - - public void setShowSelectionBox(boolean showSelectionBoxIn) { - this.showSelectionBox = showSelectionBoxIn; - } - - /**+ - * Sets hasListHeader and headerHeight. Params: hasListHeader, - * headerHeight. If hasListHeader is false headerHeight is set - * to 0. - */ - protected void setHasListHeader(boolean hasListHeaderIn, int headerPaddingIn) { - this.hasListHeader = hasListHeaderIn; - this.headerPadding = headerPaddingIn; - if (!hasListHeaderIn) { - this.headerPadding = 0; - } - - } - - protected abstract int getSize(); - - protected abstract void elementClicked(int var1, boolean var2, int var3, int var4); - - protected abstract boolean isSelected(int var1); - - /**+ - * Return the height of the content being scrolled - */ - protected int getContentHeight() { - return (this.getSize() + 1) * this.slotHeight + this.headerPadding; - } - - protected abstract void drawBackground(); - - protected void func_178040_a(int var1, int var2, int var3) { - } - - protected abstract void drawSlot(int var1, int var2, int var3, int var4, int var5, int var6); - - /**+ - * Handles drawing a list's header row. - */ - protected void drawListHeader(int parInt1, int parInt2, Tessellator parTessellator) { - } - - protected void func_148132_a(int parInt1, int parInt2) { - } - - protected void func_148142_b(int parInt1, int parInt2) { - } - - public int getSlotIndexFromScreenCoords(int parInt1, int parInt2) { - int i = this.left + this.width / 2 - this.getListWidth() / 2; - int j = this.left + this.width / 2 + this.getListWidth() / 2; - int k = parInt2 - this.top - this.headerPadding + (int) this.amountScrolled - 4; - int l = k / this.slotHeight; - return parInt1 < this.getScrollBarX() && parInt1 >= i && parInt1 <= j && l >= 0 && k >= 0 && l < this.getSize() - ? l - : -1; - } - - /**+ - * Registers the IDs that can be used for the scrollbar's - * up/down buttons. - */ - public void registerScrollButtons(int scrollUpButtonIDIn, int scrollDownButtonIDIn) { - this.scrollUpButtonID = scrollUpButtonIDIn; - this.scrollDownButtonID = scrollDownButtonIDIn; - } - - /**+ - * Stop the thing from scrolling out of bounds - */ - protected void bindAmountScrolled() { - this.amountScrolled = MathHelper.clamp_float(this.amountScrolled, 0.0F, (float) this.func_148135_f()); - } - - public int func_148135_f() { - return Math.max(0, this.getContentHeight() - (this.bottom - this.top - 4)); - } - - /**+ - * Returns the amountScrolled field as an integer. - */ - public int getAmountScrolled() { - return (int) this.amountScrolled; - } - - public boolean isMouseYWithinSlotBounds(int parInt1) { - return parInt1 >= this.top && parInt1 <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; - } - - /**+ - * Scrolls the slot by the given amount. A positive value - * scrolls down, and a negative value scrolls up. - */ - public void scrollBy(int amount) { - this.amountScrolled += (float) amount; - this.bindAmountScrolled(); - this.initialClickY = -2; - } - public void actionPerformed(GuiButton button) { if (button.enabled) { if (button.id == this.scrollUpButtonID) { @@ -211,6 +105,21 @@ public abstract class GuiSlot { } } + /** + * + Stop the thing from scrolling out of bounds + */ + protected void bindAmountScrolled() { + this.amountScrolled = MathHelper.clamp_float(this.amountScrolled, 0.0F, (float) this.func_148135_f()); + } + + protected abstract void drawBackground(); + + /** + * + Handles drawing a list's header row. + */ + protected void drawListHeader(int parInt1, int parInt2, Tessellator parTessellator) { + } + public void drawScreen(int mouseXIn, int mouseYIn, float parFloat1) { if (this.field_178041_q) { this.mouseX = mouseXIn; @@ -324,14 +233,120 @@ public abstract class GuiSlot { } } - public void handleMouseInput() { - handleInput(Mouse.getEventButton(), Mouse.getEventButtonState(), Mouse.getDWheel()); + /** + * + Draws the selection box around the selected slot element. + */ + protected void drawSelectionBox(int mouseXIn, int mouseYIn, int parInt3, int parInt4, int i) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + for (int j = 0; j < i; ++j) { + int k = mouseYIn + j * this.slotHeight + this.headerPadding; + int l = this.slotHeight - 4; + if (k > this.bottom || k + l < this.top) { + this.func_178040_a(j, mouseXIn, k); + } + + if (this.showSelectionBox && this.isSelected(j)) { + int i1 = this.left + (this.width / 2 - this.getListWidth() / 2); + int j1 = this.left + this.width / 2 + this.getListWidth() / 2; + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableTexture2D(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos((double) i1, (double) (k + l + 2), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255) + .endVertex(); + worldrenderer.pos((double) j1, (double) (k + l + 2), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255) + .endVertex(); + worldrenderer.pos((double) j1, (double) (k - 2), 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255) + .endVertex(); + worldrenderer.pos((double) i1, (double) (k - 2), 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255) + .endVertex(); + worldrenderer.pos((double) (i1 + 1), (double) (k + l + 1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255) + .endVertex(); + worldrenderer.pos((double) (j1 - 1), (double) (k + l + 1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255) + .endVertex(); + worldrenderer.pos((double) (j1 - 1), (double) (k - 1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255) + .endVertex(); + worldrenderer.pos((double) (i1 + 1), (double) (k - 1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255) + .endVertex(); + tessellator.draw(); + GlStateManager.enableTexture2D(); + if (parInt3 >= i1 && parInt3 <= j1 && parInt4 >= k - 2 && parInt4 <= k + l + 1) { + Mouse.showCursor(EnumCursorType.HAND); + } + } + + try { + this.drawSlot(j, mouseXIn, k, l, parInt3, parInt4); + } catch (Throwable t) { + excLogger.error( + "Exception caught rendering a slot of a list on the screen! Game will continue running due to the suspicion that this could be an intentional crash attempt, and therefore it would be inconvenient if the user were to be locked out of this gui due to repeatedly triggering a full crash report"); + excLogger.error(t); + } + } + } - public void handleTouchInput() { - mouseX = PointerInputAbstraction.getVCursorX() * width / mc.displayWidth; - mouseY = height - PointerInputAbstraction.getVCursorY() * height / mc.displayHeight - 1; - handleInput(0, Touch.getEventType() == EnumTouchEvent.TOUCHSTART, 0); + protected abstract void drawSlot(int var1, int var2, int var3, int var4, int var5, int var6); + + protected abstract void elementClicked(int var1, boolean var2, int var3, int var4); + + protected void func_148132_a(int parInt1, int parInt2) { + } + + public int func_148135_f() { + return Math.max(0, this.getContentHeight() - (this.bottom - this.top - 4)); + } + + protected void func_148142_b(int parInt1, int parInt2) { + } + + protected void func_178040_a(int var1, int var2, int var3) { + } + + /** + * + Returns the amountScrolled field as an integer. + */ + public int getAmountScrolled() { + return (int) this.amountScrolled; + } + + /** + * + Return the height of the content being scrolled + */ + protected int getContentHeight() { + return (this.getSize() + 1) * this.slotHeight + this.headerPadding; + } + + public boolean getEnabled() { + return this.enabled; + } + + /** + * + Gets the width of the list + */ + public int getListWidth() { + return 220; + } + + protected int getScrollBarX() { + return this.width / 2 + 124; + } + + protected abstract int getSize(); + + public int getSlotHeight() { + return this.slotHeight; + } + + public int getSlotIndexFromScreenCoords(int parInt1, int parInt2) { + int i = this.left + this.width / 2 - this.getListWidth() / 2; + int j = this.left + this.width / 2 + this.getListWidth() / 2; + int k = parInt2 - this.top - this.headerPadding + (int) this.amountScrolled - 4; + int l = k / this.slotHeight; + return parInt1 < this.getScrollBarX() && parInt1 >= i && parInt1 <= j && l >= 0 && k >= 0 && l < this.getSize() + ? l + : -1; } protected void handleInput(int eventButton, boolean eventState, int dWheel) { @@ -415,81 +430,24 @@ public abstract class GuiSlot { } } - public void setEnabled(boolean enabledIn) { - this.enabled = enabledIn; + public void handleMouseInput() { + handleInput(Mouse.getEventButton(), Mouse.getEventButtonState(), Mouse.getDWheel()); } - public boolean getEnabled() { - return this.enabled; + public void handleTouchInput() { + mouseX = PointerInputAbstraction.getVCursorX() * width / mc.displayWidth; + mouseY = height - PointerInputAbstraction.getVCursorY() * height / mc.displayHeight - 1; + handleInput(0, Touch.getEventType() == EnumTouchEvent.TOUCHSTART, 0); } - /**+ - * Gets the width of the list - */ - public int getListWidth() { - return 220; + public boolean isMouseYWithinSlotBounds(int parInt1) { + return parInt1 >= this.top && parInt1 <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; } - /**+ - * Draws the selection box around the selected slot element. - */ - protected void drawSelectionBox(int mouseXIn, int mouseYIn, int parInt3, int parInt4, int i) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + protected abstract boolean isSelected(int var1); - for (int j = 0; j < i; ++j) { - int k = mouseYIn + j * this.slotHeight + this.headerPadding; - int l = this.slotHeight - 4; - if (k > this.bottom || k + l < this.top) { - this.func_178040_a(j, mouseXIn, k); - } - - if (this.showSelectionBox && this.isSelected(j)) { - int i1 = this.left + (this.width / 2 - this.getListWidth() / 2); - int j1 = this.left + this.width / 2 + this.getListWidth() / 2; - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableTexture2D(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double) i1, (double) (k + l + 2), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255) - .endVertex(); - worldrenderer.pos((double) j1, (double) (k + l + 2), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255) - .endVertex(); - worldrenderer.pos((double) j1, (double) (k - 2), 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255) - .endVertex(); - worldrenderer.pos((double) i1, (double) (k - 2), 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255) - .endVertex(); - worldrenderer.pos((double) (i1 + 1), (double) (k + l + 1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255) - .endVertex(); - worldrenderer.pos((double) (j1 - 1), (double) (k + l + 1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255) - .endVertex(); - worldrenderer.pos((double) (j1 - 1), (double) (k - 1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255) - .endVertex(); - worldrenderer.pos((double) (i1 + 1), (double) (k - 1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255) - .endVertex(); - tessellator.draw(); - GlStateManager.enableTexture2D(); - if (parInt3 >= i1 && parInt3 <= j1 && parInt4 >= k - 2 && parInt4 <= k + l + 1) { - Mouse.showCursor(EnumCursorType.HAND); - } - } - - try { - this.drawSlot(j, mouseXIn, k, l, parInt3, parInt4); - } catch (Throwable t) { - excLogger.error( - "Exception caught rendering a slot of a list on the screen! Game will continue running due to the suspicion that this could be an intentional crash attempt, and therefore it would be inconvenient if the user were to be locked out of this gui due to repeatedly triggering a full crash report"); - excLogger.error(t); - } - } - - } - - protected int getScrollBarX() { - return this.width / 2 + 124; - } - - /**+ - * Overlays the background to hide scrolled items + /** + * + Overlays the background to hide scrolled items */ protected void overlayBackground(int startY, int endY, int startAlpha, int endAlpha) { Tessellator tessellator = Tessellator.getInstance(); @@ -511,16 +469,60 @@ public abstract class GuiSlot { tessellator.draw(); } - /**+ - * Sets the left and right bounds of the slot. Param is the left - * bound, right is calculated as left + width. + /** + * + Registers the IDs that can be used for the scrollbar's up/down buttons. + */ + public void registerScrollButtons(int scrollUpButtonIDIn, int scrollDownButtonIDIn) { + this.scrollUpButtonID = scrollUpButtonIDIn; + this.scrollDownButtonID = scrollDownButtonIDIn; + } + + /** + * + Scrolls the slot by the given amount. A positive value scrolls down, and a + * negative value scrolls up. + */ + public void scrollBy(int amount) { + this.amountScrolled += (float) amount; + this.bindAmountScrolled(); + this.initialClickY = -2; + } + + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn) { + this.width = widthIn; + this.height = heightIn; + this.top = topIn; + this.bottom = bottomIn; + this.left = 0; + this.right = widthIn; + } + + public void setEnabled(boolean enabledIn) { + this.enabled = enabledIn; + } + + /** + * + Sets hasListHeader and headerHeight. Params: hasListHeader, headerHeight. + * If hasListHeader is false headerHeight is set to 0. + */ + protected void setHasListHeader(boolean hasListHeaderIn, int headerPaddingIn) { + this.hasListHeader = hasListHeaderIn; + this.headerPadding = headerPaddingIn; + if (!hasListHeaderIn) { + this.headerPadding = 0; + } + + } + + public void setShowSelectionBox(boolean showSelectionBoxIn) { + this.showSelectionBox = showSelectionBoxIn; + } + + /** + * + Sets the left and right bounds of the slot. Param is the left bound, right + * is calculated as left + width. */ public void setSlotXBoundsFromLeft(int leftIn) { this.left = leftIn; this.right = leftIn + this.width; } - - public int getSlotHeight() { - return this.slotHeight; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiSpectator.java b/src/game/java/net/minecraft/client/gui/GuiSpectator.java index 7d46ce14..caca2121 100644 --- a/src/game/java/net/minecraft/client/gui/GuiSpectator.java +++ b/src/game/java/net/minecraft/client/gui/GuiSpectator.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; @@ -13,22 +14,25 @@ import net.minecraft.client.settings.GameSettings; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,36 +48,9 @@ public class GuiSpectator extends Gui implements ISpectatorMenuRecipient { this.field_175268_g = mcIn; } - public void func_175260_a(int parInt1) { - this.field_175270_h = Minecraft.getSystemTime(); - if (this.field_175271_i != null) { - this.field_175271_i.func_178644_b(parInt1); - } else { - this.field_175271_i = new SpectatorMenu(this); - } - - } - - private float func_175265_c() { - long i = this.field_175270_h - Minecraft.getSystemTime() + 5000L; - return MathHelper.clamp_float((float) i / 2000.0F, 0.0F, 1.0F); - } - - public void renderTooltip(ScaledResolution parScaledResolution, float parFloat1) { - if (this.field_175271_i != null) { - float f = this.func_175265_c(); - if (f <= 0.0F) { - this.field_175271_i.func_178641_d(); - } else { - int i = parScaledResolution.getScaledWidth() / 2; - float f1 = this.zLevel; - this.zLevel = -90.0F; - float f2 = (float) parScaledResolution.getScaledHeight() - 22.0F * f; - SpectatorDetails spectatordetails = this.field_175271_i.func_178646_f(); - this.func_175258_a(parScaledResolution, f, i, f2, spectatordetails); - this.zLevel = f1; - } - } + public void func_175257_a(SpectatorMenu parSpectatorMenu) { + this.field_175271_i = null; + this.field_175270_h = 0L; } protected void func_175258_a(ScaledResolution parScaledResolution, float parFloat1, int parInt1, float parFloat2, @@ -101,26 +78,46 @@ public class GuiSpectator extends Gui implements ISpectatorMenuRecipient { GlStateManager.disableBlend(); } - private void func_175266_a(int parInt1, int parInt2, float parFloat1, float parFloat2, - ISpectatorMenuObject parISpectatorMenuObject) { - this.field_175268_g.getTextureManager().bindTexture(field_175269_a); - if (parISpectatorMenuObject != SpectatorMenu.field_178657_a) { - int i = (int) (parFloat2 * 255.0F); - GlStateManager.pushMatrix(); - GlStateManager.translate((float) parInt2, parFloat1, 0.0F); - float f = parISpectatorMenuObject.func_178662_A_() ? 1.0F : 0.25F; - GlStateManager.color(f, f, f, parFloat2); - parISpectatorMenuObject.func_178663_a(f, i); - GlStateManager.popMatrix(); - String s = String.valueOf(GameSettings - .getKeyDisplayString(this.field_175268_g.gameSettings.keyBindsHotbar[parInt1].getKeyCode())); - if (i > 3 && parISpectatorMenuObject.func_178662_A_()) { - this.field_175268_g.fontRendererObj.drawStringWithShadow(s, - (float) (parInt2 + 19 - 2 - this.field_175268_g.fontRendererObj.getStringWidth(s)), - parFloat1 + 6.0F + 3.0F, 16777215 + (i << 24)); - } + public void func_175259_b(int parInt1) { + int i; + for (i = this.field_175271_i.func_178648_e() + parInt1; i >= 0 && i <= 8 + && (this.field_175271_i.func_178643_a(i) == SpectatorMenu.field_178657_a + || !this.field_175271_i.func_178643_a(i).func_178662_A_()); i += parInt1) { + ; } + if (i >= 0 && i <= 8) { + this.field_175271_i.func_178644_b(i); + this.field_175270_h = Minecraft.getSystemTime(); + } + + } + + public void func_175260_a(int parInt1) { + this.field_175270_h = Minecraft.getSystemTime(); + if (this.field_175271_i != null) { + this.field_175271_i.func_178644_b(parInt1); + } else { + this.field_175271_i = new SpectatorMenu(this); + } + + } + + public void func_175261_b() { + this.field_175270_h = Minecraft.getSystemTime(); + if (this.func_175262_a()) { + int i = this.field_175271_i.func_178648_e(); + if (i != -1) { + this.field_175271_i.func_178644_b(i); + } + } else { + this.field_175271_i = new SpectatorMenu(this); + } + + } + + public boolean func_175262_a() { + return this.field_175271_i != null; } public void func_175263_a(ScaledResolution parScaledResolution) { @@ -145,40 +142,47 @@ public class GuiSpectator extends Gui implements ISpectatorMenuRecipient { } - public void func_175257_a(SpectatorMenu parSpectatorMenu) { - this.field_175271_i = null; - this.field_175270_h = 0L; + private float func_175265_c() { + long i = this.field_175270_h - Minecraft.getSystemTime() + 5000L; + return MathHelper.clamp_float((float) i / 2000.0F, 0.0F, 1.0F); } - public boolean func_175262_a() { - return this.field_175271_i != null; - } - - public void func_175259_b(int parInt1) { - int i; - for (i = this.field_175271_i.func_178648_e() + parInt1; i >= 0 && i <= 8 - && (this.field_175271_i.func_178643_a(i) == SpectatorMenu.field_178657_a - || !this.field_175271_i.func_178643_a(i).func_178662_A_()); i += parInt1) { - ; - } - - if (i >= 0 && i <= 8) { - this.field_175271_i.func_178644_b(i); - this.field_175270_h = Minecraft.getSystemTime(); - } - - } - - public void func_175261_b() { - this.field_175270_h = Minecraft.getSystemTime(); - if (this.func_175262_a()) { - int i = this.field_175271_i.func_178648_e(); - if (i != -1) { - this.field_175271_i.func_178644_b(i); + private void func_175266_a(int parInt1, int parInt2, float parFloat1, float parFloat2, + ISpectatorMenuObject parISpectatorMenuObject) { + this.field_175268_g.getTextureManager().bindTexture(field_175269_a); + if (parISpectatorMenuObject != SpectatorMenu.field_178657_a) { + int i = (int) (parFloat2 * 255.0F); + GlStateManager.pushMatrix(); + GlStateManager.translate((float) parInt2, parFloat1, 0.0F); + float f = parISpectatorMenuObject.func_178662_A_() ? 1.0F : 0.25F; + GlStateManager.color(f, f, f, parFloat2); + parISpectatorMenuObject.func_178663_a(f, i); + GlStateManager.popMatrix(); + String s = String.valueOf(GameSettings + .getKeyDisplayString(this.field_175268_g.gameSettings.keyBindsHotbar[parInt1].getKeyCode())); + if (i > 3 && parISpectatorMenuObject.func_178662_A_()) { + this.field_175268_g.fontRendererObj.drawStringWithShadow(s, + (float) (parInt2 + 19 - 2 - this.field_175268_g.fontRendererObj.getStringWidth(s)), + parFloat1 + 6.0F + 3.0F, 16777215 + (i << 24)); } - } else { - this.field_175271_i = new SpectatorMenu(this); } } + + public void renderTooltip(ScaledResolution parScaledResolution, float parFloat1) { + if (this.field_175271_i != null) { + float f = this.func_175265_c(); + if (f <= 0.0F) { + this.field_175271_i.func_178641_d(); + } else { + int i = parScaledResolution.getScaledWidth() / 2; + float f1 = this.zLevel; + this.zLevel = -90.0F; + float f2 = (float) parScaledResolution.getScaledHeight() - 22.0F * f; + SpectatorDetails spectatordetails = this.field_175271_i.func_178646_f(); + this.func_175258_a(parScaledResolution, f, i, f2, spectatordetails); + this.zLevel = f1; + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiTextField.java b/src/game/java/net/minecraft/client/gui/GuiTextField.java index 041f1a28..2d28186e 100644 --- a/src/game/java/net/minecraft/client/gui/GuiTextField.java +++ b/src/game/java/net/minecraft/client/gui/GuiTextField.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_DST_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import com.google.common.base.Predicate; import com.google.common.base.Predicates; @@ -13,22 +14,25 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,22 +44,20 @@ public class GuiTextField extends Gui { public int yPosition; private final int width; private final int height; - /**+ - * Has the current text being edited on the textbox. + /** + * + Has the current text being edited on the textbox. */ protected String text = ""; private int maxStringLength = 32; private int cursorCounter; private boolean enableBackgroundDrawing = true; - /**+ - * if true the textbox can lose focus by clicking elsewhere on - * the screen + /** + * + if true the textbox can lose focus by clicking elsewhere on the screen */ private boolean canLoseFocus = true; private boolean isFocused; - /**+ - * If this value is true along with isFocused, keyTyped will - * process the keys. + /** + * + If this value is true along with isFocused, keyTyped will process the keys. */ private boolean isEnabled = true; private int lineScrollOffset; @@ -63,8 +65,8 @@ public class GuiTextField extends Gui { private int selectionEnd; private int enabledColor = 14737632; private int disabledColor = 7368816; - /**+ - * True if this textbox is visible + /** + * + True if this textbox is visible */ private boolean visible = true; private GuiPageButtonList.GuiResponder field_175210_x; @@ -79,119 +81,9 @@ public class GuiTextField extends Gui { this.height = par6Height; } - public void func_175207_a(GuiPageButtonList.GuiResponder parGuiResponder) { - this.field_175210_x = parGuiResponder; - } - - /**+ - * Increments the cursor counter - */ - public void updateCursorCounter() { - ++this.cursorCounter; - } - - /**+ - * Sets the text of the textbox - */ - public void setText(String parString1) { - if (this.field_175209_y.apply(parString1)) { - if (parString1.length() > this.maxStringLength) { - this.text = parString1.substring(0, this.maxStringLength); - } else { - this.text = parString1; - } - - this.setCursorPositionEnd(); - } - } - - public void updateText(String parString1) { - if (this.field_175209_y.apply(parString1)) { - if (parString1.length() > this.maxStringLength) { - this.text = parString1.substring(0, this.maxStringLength); - } else { - this.text = parString1; - } - - this.setCursorPosition(cursorPosition); - } - } - - /**+ - * Returns the contents of the textbox - */ - public String getText() { - return this.text; - } - - /**+ - * returns the text between the cursor and selectionEnd - */ - public String getSelectedText() { - int i = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; - int j = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; - return this.text.substring(i, j); - } - - public void func_175205_a(Predicate parPredicate) { - this.field_175209_y = parPredicate; - } - - /**+ - * replaces selected text, or inserts text at the position on - * the cursor - */ - public void writeText(String parString1) { - String s = ""; - String s1 = ChatAllowedCharacters.filterAllowedCharacters(parString1); - int i = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; - int j = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; - int k = this.maxStringLength - this.text.length() - (i - j); - int l = 0; - if (this.text.length() > 0) { - s = s + this.text.substring(0, i); - } - - if (k < s1.length()) { - s = s + s1.substring(0, k); - l = k; - } else { - s = s + s1; - l = s1.length(); - } - - if (this.text.length() > 0 && j < this.text.length()) { - s = s + this.text.substring(j); - } - - if (this.field_175209_y.apply(s)) { - this.text = s; - this.moveCursorBy(i - this.selectionEnd + l); - if (this.field_175210_x != null) { - this.field_175210_x.func_175319_a(this.id, this.text); - } - - } - } - - /**+ - * Deletes the specified number of words starting at the cursor - * position. Negative numbers will delete words left of the - * cursor. - */ - public void deleteWords(int parInt1) { - if (this.text.length() != 0) { - if (this.selectionEnd != this.cursorPosition) { - this.writeText(""); - } else { - this.deleteFromCursor(this.getNthWordFromCursor(parInt1) - this.cursorPosition); - } - } - } - - /**+ - * delete the selected text, otherwsie deletes characters from - * either side of the cursor. params: delete num + /** + * + delete the selected text, otherwsie deletes characters from either side of + * the cursor. params: delete num */ public void deleteFromCursor(int parInt1) { if (this.text.length() != 0) { @@ -225,23 +117,135 @@ public class GuiTextField extends Gui { } } - public int getId() { - return this.id; + /** + * + Deletes the specified number of words starting at the cursor position. + * Negative numbers will delete words left of the cursor. + */ + public void deleteWords(int parInt1) { + if (this.text.length() != 0) { + if (this.selectionEnd != this.cursorPosition) { + this.writeText(""); + } else { + this.deleteFromCursor(this.getNthWordFromCursor(parInt1) - this.cursorPosition); + } + } } - /**+ - * see @getNthNextWordFromPos() params: N, position + /** + * + draws the vertical line cursor in the textbox */ - public int getNthWordFromCursor(int parInt1) { - return this.getNthWordFromPos(parInt1, this.getCursorPosition()); + private void drawCursorVertical(int parInt1, int parInt2, int parInt3, int parInt4) { + if (parInt1 < parInt3) { + int i = parInt1; + parInt1 = parInt3; + parInt3 = i; + } + + if (parInt2 < parInt4) { + int j = parInt2; + parInt2 = parInt4; + parInt4 = j; + } + + if (parInt3 > this.xPosition + this.width) { + parInt3 = this.xPosition + this.width; + } + + if (parInt1 > this.xPosition + this.width) { + parInt1 = this.xPosition + this.width; + } + + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + GlStateManager.color(0.2F, 0.2F, 1.0F, 1.0F); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA); + GlStateManager.disableTexture2D(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION); + worldrenderer.pos((double) parInt1, (double) parInt4, 0.0D).endVertex(); + worldrenderer.pos((double) parInt3, (double) parInt4, 0.0D).endVertex(); + worldrenderer.pos((double) parInt3, (double) parInt2, 0.0D).endVertex(); + worldrenderer.pos((double) parInt1, (double) parInt2, 0.0D).endVertex(); + tessellator.draw(); + GlStateManager.disableBlend(); + GlStateManager.enableTexture2D(); } - /**+ - * gets the position of the nth word. N may be negative, then it - * looks backwards. params: N, position + /** + * + Draws the textbox */ - public int getNthWordFromPos(int parInt1, int parInt2) { - return this.func_146197_a(parInt1, parInt2, true); + public void drawTextBox() { + if (this.getVisible()) { + if (this.getEnableBackgroundDrawing()) { + drawRect(this.xPosition - 1, this.yPosition - 1, this.xPosition + this.width + 1, + this.yPosition + this.height + 1, -6250336); + drawRect(this.xPosition, this.yPosition, this.xPosition + this.width, this.yPosition + this.height, + -16777216); + } + + int i = this.isEnabled ? this.enabledColor : this.disabledColor; + int j = this.cursorPosition - this.lineScrollOffset; + int k = this.selectionEnd - this.lineScrollOffset; + String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), + this.getWidth()); + boolean flag = j >= 0 && j <= s.length(); + boolean flag1 = this.isFocused && this.cursorCounter / 6 % 2 == 0 && flag; + int l = this.enableBackgroundDrawing ? this.xPosition + 4 : this.xPosition; + int i1 = this.enableBackgroundDrawing ? this.yPosition + (this.height - 8) / 2 : this.yPosition; + int j1 = l; + if (k > s.length()) { + k = s.length(); + } + + if (s.length() > 0) { + String s1 = flag ? s.substring(0, j) : s; + j1 = this.fontRendererInstance.drawStringWithShadow(s1, (float) l, (float) i1, i); + } + + boolean flag2 = this.cursorPosition < this.text.length() || this.text.length() >= this.getMaxStringLength(); + int k1 = j1; + if (!flag) { + k1 = j > 0 ? l + this.width : l; + } else if (flag2) { + k1 = j1 - 1; + --j1; + } + + if (s.length() > 0 && flag && j < s.length()) { + j1 = this.fontRendererInstance.drawStringWithShadow(s.substring(j), (float) j1, (float) i1, i); + } + + if (flag1) { + if (flag2) { + Gui.drawRect(k1, i1 - 1, k1 + 1, i1 + 1 + this.fontRendererInstance.FONT_HEIGHT, -3092272); + } else { + this.fontRendererInstance.drawStringWithShadow("_", (float) k1, (float) i1, i); + } + } + + if (k != j) { + int l1 = l + this.fontRendererInstance.getStringWidth(s.substring(0, k)); + this.drawCursorVertical(k1, i1 - 1, l1 - 1, i1 + 1 + this.fontRendererInstance.FONT_HEIGHT); + } + + } + } + + public void fireInputEvent(EnumInputEvent clipboardPaste, String param) { + if (!isFocused) + return; + switch (clipboardPaste) { + case CLIPBOARD_COPY: + GuiScreen.setClipboardString(this.getSelectedText()); + break; + case CLIPBOARD_PASTE: + if (this.isEnabled) { + this.writeText(param != null ? param : GuiScreen.getClipboardString()); + } + break; + default: + break; + } } public int func_146197_a(int parInt1, int parInt2, boolean parFlag) { @@ -274,16 +278,141 @@ public class GuiTextField extends Gui { return i; } - /**+ - * Moves the text cursor by a specified number of characters and - * clears the selection + public void func_175205_a(Predicate parPredicate) { + this.field_175209_y = parPredicate; + } + + public void func_175207_a(GuiPageButtonList.GuiResponder parGuiResponder) { + this.field_175210_x = parGuiResponder; + } + + /** + * + returns the current position of the cursor + */ + public int getCursorPosition() { + return this.cursorPosition; + } + + /** + * + get enable drawing background and outline + */ + public boolean getEnableBackgroundDrawing() { + return this.enableBackgroundDrawing; + } + + public int getId() { + return this.id; + } + + /** + * + returns the maximum number of character that can be contained in this + * textbox + */ + public int getMaxStringLength() { + return this.maxStringLength; + } + + /** + * + see @getNthNextWordFromPos() params: N, position + */ + public int getNthWordFromCursor(int parInt1) { + return this.getNthWordFromPos(parInt1, this.getCursorPosition()); + } + + /** + * + gets the position of the nth word. N may be negative, then it looks + * backwards. params: N, position + */ + public int getNthWordFromPos(int parInt1, int parInt2) { + return this.func_146197_a(parInt1, parInt2, true); + } + + /** + * + returns the text between the cursor and selectionEnd + */ + public String getSelectedText() { + int i = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; + int j = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; + return this.text.substring(i, j); + } + + /** + * + the side of the selection that is not the cursor, may be the same as the + * cursor + */ + public int getSelectionEnd() { + return this.selectionEnd; + } + + /** + * + Returns the contents of the textbox + */ + public String getText() { + return this.text; + } + + /** + * + returns true if this textbox is visible + */ + public boolean getVisible() { + return this.visible; + } + + /** + * + returns the width of the textbox depending on if background drawing is + * enabled + */ + public int getWidth() { + return this.getEnableBackgroundDrawing() ? this.width - 8 : this.width; + } + + /** + * + Getter for the focused field + */ + public boolean isFocused() { + return this.isFocused; + } + + /** + * + Args: x, y, buttonClicked + */ + public void mouseClicked(int parInt1, int parInt2, int parInt3) { + boolean flag = parInt1 >= this.xPosition && parInt1 < this.xPosition + this.width && parInt2 >= this.yPosition + && parInt2 < this.yPosition + this.height; + if (this.canLoseFocus) { + this.setFocused(flag); + } + + if (this.isFocused && flag && parInt3 == 0) { + int i = parInt1 - this.xPosition; + if (this.enableBackgroundDrawing) { + i -= 4; + } + + String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), + this.getWidth()); + this.setCursorPosition(this.fontRendererInstance.trimStringToWidth(s, i).length() + this.lineScrollOffset); + } + + } + + /** + * + Moves the text cursor by a specified number of characters and clears the + * selection */ public void moveCursorBy(int parInt1) { this.setCursorPosition(this.selectionEnd + parInt1); } - /**+ - * sets the position of the cursor to the provided index + /** + * + if true the textbox can lose focus by clicking elsewhere on the screen + */ + public void setCanLoseFocus(boolean parFlag) { + this.canLoseFocus = parFlag; + } + + /** + * + sets the position of the cursor to the provided index */ public void setCursorPosition(int parInt1) { this.cursorPosition = parInt1; @@ -292,23 +421,124 @@ public class GuiTextField extends Gui { this.setSelectionPos(this.cursorPosition); } - /**+ - * sets the cursors position to the beginning - */ - public void setCursorPositionZero() { - this.setCursorPosition(0); - } - - /**+ - * sets the cursors position to after the text + /** + * + sets the cursors position to after the text */ public void setCursorPositionEnd() { this.setCursorPosition(this.text.length()); } - /**+ - * Call this method from your GuiScreen to process the keys into - * the textbox + /** + * + sets the cursors position to the beginning + */ + public void setCursorPositionZero() { + this.setCursorPosition(0); + } + + public void setDisabledTextColour(int parInt1) { + this.disabledColor = parInt1; + } + + /** + * + enable drawing background and outline + */ + public void setEnableBackgroundDrawing(boolean parFlag) { + this.enableBackgroundDrawing = parFlag; + } + + public void setEnabled(boolean parFlag) { + this.isEnabled = parFlag; + } + + /** + * + Sets focus to this gui element + */ + public void setFocused(boolean parFlag) { + if (parFlag && !this.isFocused) { + this.cursorCounter = 0; + } + + this.isFocused = parFlag; + } + + public void setMaxStringLength(int parInt1) { + this.maxStringLength = parInt1; + if (this.text.length() > parInt1) { + this.text = this.text.substring(0, parInt1); + } + + } + + /** + * + Sets the position of the selection anchor (i.e. position the selection was + * started at) + */ + public void setSelectionPos(int parInt1) { + int i = this.text.length(); + if (parInt1 > i) { + parInt1 = i; + } + + if (parInt1 < 0) { + parInt1 = 0; + } + + this.selectionEnd = parInt1; + if (this.fontRendererInstance != null) { + if (this.lineScrollOffset > i) { + this.lineScrollOffset = i; + } + + int j = this.getWidth(); + String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), j); + int k = s.length() + this.lineScrollOffset; + if (parInt1 == this.lineScrollOffset) { + this.lineScrollOffset -= this.fontRendererInstance.trimStringToWidth(this.text, j, true).length(); + } + + if (parInt1 > k) { + this.lineScrollOffset += parInt1 - k; + } else if (parInt1 <= this.lineScrollOffset) { + this.lineScrollOffset -= this.lineScrollOffset - parInt1; + } + + this.lineScrollOffset = MathHelper.clamp_int(this.lineScrollOffset, 0, i); + } + + } + + /** + * + Sets the text of the textbox + */ + public void setText(String parString1) { + if (this.field_175209_y.apply(parString1)) { + if (parString1.length() > this.maxStringLength) { + this.text = parString1.substring(0, this.maxStringLength); + } else { + this.text = parString1; + } + + this.setCursorPositionEnd(); + } + } + + /** + * + Sets the text colour for this textbox (disabled text will not use this + * colour) + */ + public void setTextColor(int parInt1) { + this.enabledColor = parInt1; + } + + /** + * + Sets whether or not this textbox is visible + */ + public void setVisible(boolean parFlag) { + this.visible = parFlag; + } + + /** + * + Call this method from your GuiScreen to process the keys into the textbox */ public boolean textboxKeyTyped(char parChar1, int parInt1) { if (!this.isFocused) { @@ -413,290 +643,58 @@ public class GuiTextField extends Gui { } } - /**+ - * Args: x, y, buttonClicked + /** + * + Increments the cursor counter */ - public void mouseClicked(int parInt1, int parInt2, int parInt3) { - boolean flag = parInt1 >= this.xPosition && parInt1 < this.xPosition + this.width && parInt2 >= this.yPosition - && parInt2 < this.yPosition + this.height; - if (this.canLoseFocus) { - this.setFocused(flag); - } - - if (this.isFocused && flag && parInt3 == 0) { - int i = parInt1 - this.xPosition; - if (this.enableBackgroundDrawing) { - i -= 4; - } - - String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), - this.getWidth()); - this.setCursorPosition(this.fontRendererInstance.trimStringToWidth(s, i).length() + this.lineScrollOffset); - } - + public void updateCursorCounter() { + ++this.cursorCounter; } - /**+ - * Draws the textbox - */ - public void drawTextBox() { - if (this.getVisible()) { - if (this.getEnableBackgroundDrawing()) { - drawRect(this.xPosition - 1, this.yPosition - 1, this.xPosition + this.width + 1, - this.yPosition + this.height + 1, -6250336); - drawRect(this.xPosition, this.yPosition, this.xPosition + this.width, this.yPosition + this.height, - -16777216); - } - - int i = this.isEnabled ? this.enabledColor : this.disabledColor; - int j = this.cursorPosition - this.lineScrollOffset; - int k = this.selectionEnd - this.lineScrollOffset; - String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), - this.getWidth()); - boolean flag = j >= 0 && j <= s.length(); - boolean flag1 = this.isFocused && this.cursorCounter / 6 % 2 == 0 && flag; - int l = this.enableBackgroundDrawing ? this.xPosition + 4 : this.xPosition; - int i1 = this.enableBackgroundDrawing ? this.yPosition + (this.height - 8) / 2 : this.yPosition; - int j1 = l; - if (k > s.length()) { - k = s.length(); - } - - if (s.length() > 0) { - String s1 = flag ? s.substring(0, j) : s; - j1 = this.fontRendererInstance.drawStringWithShadow(s1, (float) l, (float) i1, i); - } - - boolean flag2 = this.cursorPosition < this.text.length() || this.text.length() >= this.getMaxStringLength(); - int k1 = j1; - if (!flag) { - k1 = j > 0 ? l + this.width : l; - } else if (flag2) { - k1 = j1 - 1; - --j1; - } - - if (s.length() > 0 && flag && j < s.length()) { - j1 = this.fontRendererInstance.drawStringWithShadow(s.substring(j), (float) j1, (float) i1, i); - } - - if (flag1) { - if (flag2) { - Gui.drawRect(k1, i1 - 1, k1 + 1, i1 + 1 + this.fontRendererInstance.FONT_HEIGHT, -3092272); - } else { - this.fontRendererInstance.drawStringWithShadow("_", (float) k1, (float) i1, i); - } - } - - if (k != j) { - int l1 = l + this.fontRendererInstance.getStringWidth(s.substring(0, k)); - this.drawCursorVertical(k1, i1 - 1, l1 - 1, i1 + 1 + this.fontRendererInstance.FONT_HEIGHT); + public void updateText(String parString1) { + if (this.field_175209_y.apply(parString1)) { + if (parString1.length() > this.maxStringLength) { + this.text = parString1.substring(0, this.maxStringLength); + } else { + this.text = parString1; } + this.setCursorPosition(cursorPosition); } } - /**+ - * draws the vertical line cursor in the textbox + /** + * + replaces selected text, or inserts text at the position on the cursor */ - private void drawCursorVertical(int parInt1, int parInt2, int parInt3, int parInt4) { - if (parInt1 < parInt3) { - int i = parInt1; - parInt1 = parInt3; - parInt3 = i; + public void writeText(String parString1) { + String s = ""; + String s1 = ChatAllowedCharacters.filterAllowedCharacters(parString1); + int i = this.cursorPosition < this.selectionEnd ? this.cursorPosition : this.selectionEnd; + int j = this.cursorPosition < this.selectionEnd ? this.selectionEnd : this.cursorPosition; + int k = this.maxStringLength - this.text.length() - (i - j); + int l = 0; + if (this.text.length() > 0) { + s = s + this.text.substring(0, i); } - if (parInt2 < parInt4) { - int j = parInt2; - parInt2 = parInt4; - parInt4 = j; + if (k < s1.length()) { + s = s + s1.substring(0, k); + l = k; + } else { + s = s + s1; + l = s1.length(); } - if (parInt3 > this.xPosition + this.width) { - parInt3 = this.xPosition + this.width; + if (this.text.length() > 0 && j < this.text.length()) { + s = s + this.text.substring(j); } - if (parInt1 > this.xPosition + this.width) { - parInt1 = this.xPosition + this.width; - } - - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - GlStateManager.color(0.2F, 0.2F, 1.0F, 1.0F); - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_ONE_MINUS_DST_COLOR, GL_SRC_ALPHA); - GlStateManager.disableTexture2D(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION); - worldrenderer.pos((double) parInt1, (double) parInt4, 0.0D).endVertex(); - worldrenderer.pos((double) parInt3, (double) parInt4, 0.0D).endVertex(); - worldrenderer.pos((double) parInt3, (double) parInt2, 0.0D).endVertex(); - worldrenderer.pos((double) parInt1, (double) parInt2, 0.0D).endVertex(); - tessellator.draw(); - GlStateManager.disableBlend(); - GlStateManager.enableTexture2D(); - } - - public void setMaxStringLength(int parInt1) { - this.maxStringLength = parInt1; - if (this.text.length() > parInt1) { - this.text = this.text.substring(0, parInt1); - } - - } - - /**+ - * returns the maximum number of character that can be contained - * in this textbox - */ - public int getMaxStringLength() { - return this.maxStringLength; - } - - /**+ - * returns the current position of the cursor - */ - public int getCursorPosition() { - return this.cursorPosition; - } - - /**+ - * get enable drawing background and outline - */ - public boolean getEnableBackgroundDrawing() { - return this.enableBackgroundDrawing; - } - - /**+ - * enable drawing background and outline - */ - public void setEnableBackgroundDrawing(boolean parFlag) { - this.enableBackgroundDrawing = parFlag; - } - - /**+ - * Sets the text colour for this textbox (disabled text will not - * use this colour) - */ - public void setTextColor(int parInt1) { - this.enabledColor = parInt1; - } - - public void setDisabledTextColour(int parInt1) { - this.disabledColor = parInt1; - } - - /**+ - * Sets focus to this gui element - */ - public void setFocused(boolean parFlag) { - if (parFlag && !this.isFocused) { - this.cursorCounter = 0; - } - - this.isFocused = parFlag; - } - - /**+ - * Getter for the focused field - */ - public boolean isFocused() { - return this.isFocused; - } - - public void setEnabled(boolean parFlag) { - this.isEnabled = parFlag; - } - - /**+ - * the side of the selection that is not the cursor, may be the - * same as the cursor - */ - public int getSelectionEnd() { - return this.selectionEnd; - } - - /**+ - * returns the width of the textbox depending on if background - * drawing is enabled - */ - public int getWidth() { - return this.getEnableBackgroundDrawing() ? this.width - 8 : this.width; - } - - /**+ - * Sets the position of the selection anchor (i.e. position the - * selection was started at) - */ - public void setSelectionPos(int parInt1) { - int i = this.text.length(); - if (parInt1 > i) { - parInt1 = i; - } - - if (parInt1 < 0) { - parInt1 = 0; - } - - this.selectionEnd = parInt1; - if (this.fontRendererInstance != null) { - if (this.lineScrollOffset > i) { - this.lineScrollOffset = i; + if (this.field_175209_y.apply(s)) { + this.text = s; + this.moveCursorBy(i - this.selectionEnd + l); + if (this.field_175210_x != null) { + this.field_175210_x.func_175319_a(this.id, this.text); } - int j = this.getWidth(); - String s = this.fontRendererInstance.trimStringToWidth(this.text.substring(this.lineScrollOffset), j); - int k = s.length() + this.lineScrollOffset; - if (parInt1 == this.lineScrollOffset) { - this.lineScrollOffset -= this.fontRendererInstance.trimStringToWidth(this.text, j, true).length(); - } - - if (parInt1 > k) { - this.lineScrollOffset += parInt1 - k; - } else if (parInt1 <= this.lineScrollOffset) { - this.lineScrollOffset -= this.lineScrollOffset - parInt1; - } - - this.lineScrollOffset = MathHelper.clamp_int(this.lineScrollOffset, 0, i); - } - - } - - /**+ - * if true the textbox can lose focus by clicking elsewhere on - * the screen - */ - public void setCanLoseFocus(boolean parFlag) { - this.canLoseFocus = parFlag; - } - - /**+ - * returns true if this textbox is visible - */ - public boolean getVisible() { - return this.visible; - } - - /**+ - * Sets whether or not this textbox is visible - */ - public void setVisible(boolean parFlag) { - this.visible = parFlag; - } - - public void fireInputEvent(EnumInputEvent clipboardPaste, String param) { - if (!isFocused) - return; - switch (clipboardPaste) { - case CLIPBOARD_COPY: - GuiScreen.setClipboardString(this.getSelectedText()); - break; - case CLIPBOARD_PASTE: - if (this.isEnabled) { - this.writeText(param != null ? param : GuiScreen.getClipboardString()); - } - break; - default: - break; } } diff --git a/src/game/java/net/minecraft/client/gui/GuiUtilRenderComponents.java b/src/game/java/net/minecraft/client/gui/GuiUtilRenderComponents.java index fc411258..b3d1ff87 100644 --- a/src/game/java/net/minecraft/client/gui/GuiUtilRenderComponents.java +++ b/src/game/java/net/minecraft/client/gui/GuiUtilRenderComponents.java @@ -10,33 +10,30 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiUtilRenderComponents { - public static String func_178909_a(String parString1, boolean parFlag) { - return !parFlag && !Minecraft.getMinecraft().gameSettings.chatColours - ? EnumChatFormatting.getTextWithoutFormattingCodes(parString1) - : parString1; - } - /** * This function is like the FontRenderer wrap function, except for chat * components @@ -112,4 +109,10 @@ public class GuiUtilRenderComponents { arraylist.add(chatcomponenttext); return arraylist; } + + public static String func_178909_a(String parString1, boolean parFlag) { + return !parFlag && !Minecraft.getMinecraft().gameSettings.chatColours + ? EnumChatFormatting.getTextWithoutFormattingCodes(parString1) + : parString1; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiVideoSettings.java b/src/game/java/net/minecraft/client/gui/GuiVideoSettings.java index 81aa55f4..567df1a2 100644 --- a/src/game/java/net/minecraft/client/gui/GuiVideoSettings.java +++ b/src/game/java/net/minecraft/client/gui/GuiVideoSettings.java @@ -9,37 +9,35 @@ import net.lax1dude.eaglercraft.v1_8.recording.ScreenRecordingController; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiVideoSettings extends GuiScreen { - private GuiScreen parentGuiScreen; - protected String screenTitle = "Video Settings"; - private GameSettings guiGameSettings; - private GuiListExtended optionsRowList; - private boolean vsyncLock = false; /** * + An array of all of GameSettings.Options's video options. */ - /**+ - * An array of all of GameSettings.Options's video options. + /** + * + An array of all of GameSettings.Options's video options. */ private static final GameSettings.Options[] videoOptions = new GameSettings.Options[] { GameSettings.Options.GRAPHICS, GameSettings.Options.RENDER_DISTANCE, GameSettings.Options.AMBIENT_OCCLUSION, @@ -51,16 +49,59 @@ public class GuiVideoSettings extends GuiScreen { GameSettings.Options.FULLSCREEN, GameSettings.Options.FNAW_SKINS, GameSettings.Options.HUD_FPS, GameSettings.Options.HUD_COORDS, GameSettings.Options.HUD_PLAYER, GameSettings.Options.HUD_STATS, GameSettings.Options.HUD_WORLD, GameSettings.Options.HUD_24H, GameSettings.Options.CHUNK_FIX }; + private GuiScreen parentGuiScreen; + protected String screenTitle = "Video Settings"; + private GameSettings guiGameSettings; + private GuiListExtended optionsRowList; + private boolean vsyncLock = false; public GuiVideoSettings(GuiScreen parentScreenIn, GameSettings gameSettingsIn) { this.parentGuiScreen = parentScreenIn; this.guiGameSettings = gameSettingsIn; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id == 200) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(this.parentGuiScreen); + } + + } + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.optionsRowList.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 5, 16777215); + super.drawScreen(i, j, f); + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + this.optionsRowList.handleMouseInput(); + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + this.optionsRowList.handleTouchInput(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { this.screenTitle = I18n.format("options.videoTitle", new Object[0]); @@ -94,36 +135,8 @@ public class GuiVideoSettings extends GuiScreen { } } - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - this.optionsRowList.handleMouseInput(); - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - this.optionsRowList.handleTouchInput(); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id == 200) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(this.parentGuiScreen); - } - - } - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int parInt1, int parInt2, int parInt3) { int i = this.guiGameSettings.guiScale; @@ -140,9 +153,9 @@ public class GuiVideoSettings extends GuiScreen { } - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton */ protected void mouseReleased(int i, int j, int k) { int l = this.guiGameSettings.guiScale; @@ -157,17 +170,6 @@ public class GuiVideoSettings extends GuiScreen { } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.optionsRowList.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 5, 16777215); - super.drawScreen(i, j, f); - } - @Override public void updateScreen() { boolean vsyncLockEn = ScreenRecordingController.isVSyncLocked(); diff --git a/src/game/java/net/minecraft/client/gui/GuiWinGame.java b/src/game/java/net/minecraft/client/gui/GuiWinGame.java index 466a23d0..babb944b 100644 --- a/src/game/java/net/minecraft/client/gui/GuiWinGame.java +++ b/src/game/java/net/minecraft/client/gui/GuiWinGame.java @@ -1,16 +1,17 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.base.Charsets; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -24,22 +25,25 @@ import net.minecraft.network.play.client.C16PacketClientStatus; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,150 +57,17 @@ public class GuiWinGame extends GuiScreen { private int field_146579_r; private float field_146578_s = 0.5F; - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - MusicTicker musicticker = this.mc.func_181535_r(); - SoundHandler soundhandler = this.mc.getSoundHandler(); - if (this.field_146581_h == 0) { - musicticker.func_181557_a(); - musicticker.func_181558_a(MusicTicker.MusicType.CREDITS); - soundhandler.resumeSounds(); - } - - soundhandler.update(); - ++this.field_146581_h; - float f = (float) (this.field_146579_r + this.height + this.height + 24) / this.field_146578_s; - if ((float) this.field_146581_h > f) { - this.sendRespawnPacket(); - } - - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (parInt1 == 1) { - this.sendRespawnPacket(); - } - - } - - private void sendRespawnPacket() { - this.mc.thePlayer.sendQueue - .addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN)); - this.mc.displayGuiScreen((GuiScreen) null); - } - - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player */ public boolean doesGuiPauseGame() { return true; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - if (this.field_146582_i == null) { - this.field_146582_i = Lists.newArrayList(); - - try { - String s = ""; - String s1 = "" + EnumChatFormatting.WHITE + EnumChatFormatting.OBFUSCATED + EnumChatFormatting.GREEN - + EnumChatFormatting.AQUA; - short short1 = 274; - InputStream inputstream = this.mc.getResourceManager() - .getResource(new ResourceLocation("texts/end.txt")).getInputStream(); - BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream, Charsets.UTF_8)); - EaglercraftRandom random = new EaglercraftRandom(8124371L); - - while ((s = bufferedreader.readLine()) != null) { - String s2; - String s3; - for (s = s.replaceAll("PLAYERNAME", EaglerProfile.getName()); s - .contains(s1); s = s2 + EnumChatFormatting.WHITE + EnumChatFormatting.OBFUSCATED - + "XXXXXXXX".substring(0, random.nextInt(4) + 3) + s3) { - int i = s.indexOf(s1); - s2 = s.substring(0, i); - s3 = s.substring(i + s1.length()); - } - - this.field_146582_i.addAll(this.mc.fontRendererObj.listFormattedStringToWidth(s, short1)); - this.field_146582_i.add(""); - } - - inputstream.close(); - - for (int j = 0; j < 8; ++j) { - this.field_146582_i.add(""); - } - - inputstream = this.mc.getResourceManager().getResource(new ResourceLocation("texts/credits.txt")) - .getInputStream(); - bufferedreader = new BufferedReader(new InputStreamReader(inputstream, Charsets.UTF_8)); - - while ((s = bufferedreader.readLine()) != null) { - s = s.replaceAll("PLAYERNAME", EaglerProfile.getName()); - s = s.replaceAll("\t", " "); - this.field_146582_i.addAll(this.mc.fontRendererObj.listFormattedStringToWidth(s, short1)); - this.field_146582_i.add(""); - } - - inputstream.close(); - this.field_146579_r = this.field_146582_i.size() * 12; - } catch (Exception exception) { - logger.error("Couldn\'t load credits", exception); - } - - } - } - - private void drawWinGameScreen(int parInt1, int parInt2, float parFloat1) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - this.mc.getTextureManager().bindTexture(Gui.optionsBackground); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - int i = this.width; - float f = 0.0F - ((float) this.field_146581_h + parFloat1) * 0.5F * this.field_146578_s; - float f1 = (float) this.height - ((float) this.field_146581_h + parFloat1) * 0.5F * this.field_146578_s; - float f2 = 0.015625F; - float f3 = ((float) this.field_146581_h + parFloat1 - 0.0F) * 0.02F; - float f4 = (float) (this.field_146579_r + this.height + this.height + 24) / this.field_146578_s; - float f5 = (f4 - 20.0F - ((float) this.field_146581_h + parFloat1)) * 0.005F; - if (f5 < f3) { - f3 = f5; - } - - if (f3 > 1.0F) { - f3 = 1.0F; - } - - f3 = f3 * f3; - f3 = f3 * 96.0F / 255.0F; - worldrenderer.pos(0.0D, (double) this.height, (double) this.zLevel).tex(0.0D, (double) (f * f2)) - .color(f3, f3, f3, 1.0F).endVertex(); - worldrenderer.pos((double) i, (double) this.height, (double) this.zLevel) - .tex((double) ((float) i * f2), (double) (f * f2)).color(f3, f3, f3, 1.0F).endVertex(); - worldrenderer.pos((double) i, 0.0D, (double) this.zLevel).tex((double) ((float) i * f2), (double) (f1 * f2)) - .color(f3, f3, f3, 1.0F).endVertex(); - worldrenderer.pos(0.0D, 0.0D, (double) this.zLevel).tex(0.0D, (double) (f1 * f2)).color(f3, f3, f3, 1.0F) - .endVertex(); - tessellator.draw(); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawWinGameScreen(i, j, f); @@ -255,4 +126,136 @@ public class GuiWinGame extends GuiScreen { GlStateManager.disableBlend(); super.drawScreen(i, j, f); } + + private void drawWinGameScreen(int parInt1, int parInt2, float parFloat1) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.mc.getTextureManager().bindTexture(Gui.optionsBackground); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + int i = this.width; + float f = 0.0F - ((float) this.field_146581_h + parFloat1) * 0.5F * this.field_146578_s; + float f1 = (float) this.height - ((float) this.field_146581_h + parFloat1) * 0.5F * this.field_146578_s; + float f2 = 0.015625F; + float f3 = ((float) this.field_146581_h + parFloat1 - 0.0F) * 0.02F; + float f4 = (float) (this.field_146579_r + this.height + this.height + 24) / this.field_146578_s; + float f5 = (f4 - 20.0F - ((float) this.field_146581_h + parFloat1)) * 0.005F; + if (f5 < f3) { + f3 = f5; + } + + if (f3 > 1.0F) { + f3 = 1.0F; + } + + f3 = f3 * f3; + f3 = f3 * 96.0F / 255.0F; + worldrenderer.pos(0.0D, (double) this.height, (double) this.zLevel).tex(0.0D, (double) (f * f2)) + .color(f3, f3, f3, 1.0F).endVertex(); + worldrenderer.pos((double) i, (double) this.height, (double) this.zLevel) + .tex((double) ((float) i * f2), (double) (f * f2)).color(f3, f3, f3, 1.0F).endVertex(); + worldrenderer.pos((double) i, 0.0D, (double) this.zLevel).tex((double) ((float) i * f2), (double) (f1 * f2)) + .color(f3, f3, f3, 1.0F).endVertex(); + worldrenderer.pos(0.0D, 0.0D, (double) this.zLevel).tex(0.0D, (double) (f1 * f2)).color(f3, f3, f3, 1.0F) + .endVertex(); + tessellator.draw(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + if (this.field_146582_i == null) { + this.field_146582_i = Lists.newArrayList(); + + try { + String s = ""; + String s1 = "" + EnumChatFormatting.WHITE + EnumChatFormatting.OBFUSCATED + EnumChatFormatting.GREEN + + EnumChatFormatting.AQUA; + short short1 = 274; + InputStream inputstream = this.mc.getResourceManager() + .getResource(new ResourceLocation("texts/end.txt")).getInputStream(); + BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(inputstream, Charsets.UTF_8)); + EaglercraftRandom random = new EaglercraftRandom(8124371L); + + while ((s = bufferedreader.readLine()) != null) { + String s2; + String s3; + for (s = s.replaceAll("PLAYERNAME", EaglerProfile.getName()); s + .contains(s1); s = s2 + EnumChatFormatting.WHITE + EnumChatFormatting.OBFUSCATED + + "XXXXXXXX".substring(0, random.nextInt(4) + 3) + s3) { + int i = s.indexOf(s1); + s2 = s.substring(0, i); + s3 = s.substring(i + s1.length()); + } + + this.field_146582_i.addAll(this.mc.fontRendererObj.listFormattedStringToWidth(s, short1)); + this.field_146582_i.add(""); + } + + inputstream.close(); + + for (int j = 0; j < 8; ++j) { + this.field_146582_i.add(""); + } + + inputstream = this.mc.getResourceManager().getResource(new ResourceLocation("texts/credits.txt")) + .getInputStream(); + bufferedreader = new BufferedReader(new InputStreamReader(inputstream, Charsets.UTF_8)); + + while ((s = bufferedreader.readLine()) != null) { + s = s.replaceAll("PLAYERNAME", EaglerProfile.getName()); + s = s.replaceAll("\t", " "); + this.field_146582_i.addAll(this.mc.fontRendererObj.listFormattedStringToWidth(s, short1)); + this.field_146582_i.add(""); + } + + inputstream.close(); + this.field_146579_r = this.field_146582_i.size() * 12; + } catch (Exception exception) { + logger.error("Couldn\'t load credits", exception); + } + + } + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (parInt1 == 1) { + this.sendRespawnPacket(); + } + + } + + private void sendRespawnPacket() { + this.mc.thePlayer.sendQueue + .addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.PERFORM_RESPAWN)); + this.mc.displayGuiScreen((GuiScreen) null); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + MusicTicker musicticker = this.mc.func_181535_r(); + SoundHandler soundhandler = this.mc.getSoundHandler(); + if (this.field_146581_h == 0) { + musicticker.func_181557_a(); + musicticker.func_181558_a(MusicTicker.MusicType.CREDITS); + soundhandler.resumeSounds(); + } + + soundhandler.update(); + ++this.field_146581_h; + float f = (float) (this.field_146579_r + this.height + this.height + 24) / this.field_146578_s; + if ((float) this.field_146581_h > f) { + this.sendRespawnPacket(); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/GuiYesNo.java b/src/game/java/net/minecraft/client/gui/GuiYesNo.java index 2a0745de..7565de81 100644 --- a/src/game/java/net/minecraft/client/gui/GuiYesNo.java +++ b/src/game/java/net/minecraft/client/gui/GuiYesNo.java @@ -6,22 +6,25 @@ import com.google.common.collect.Lists; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,30 +59,17 @@ public class GuiYesNo extends GuiScreen { this.parentButtonClickedId = parInt1; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.add(new GuiOptionButton(0, this.width / 2 - 155, this.height / 6 + 96, this.confirmButtonText)); - this.buttonList - .add(new GuiOptionButton(1, this.width / 2 - 155 + 160, this.height / 6 + 96, this.cancelButtonText)); - this.field_175298_s.clear(); - this.field_175298_s.addAll(this.fontRendererObj.listFormattedStringToWidth(this.messageLine2, this.width - 50)); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { this.parentScreen.confirmClicked(parGuiButton.id == 0, this.parentButtonClickedId); } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { if (opaqueBackground) { @@ -98,8 +88,21 @@ public class GuiYesNo extends GuiScreen { super.drawScreen(i, j, f); } - /**+ - * Sets the number of ticks to wait before enabling the buttons. + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.add(new GuiOptionButton(0, this.width / 2 - 155, this.height / 6 + 96, this.confirmButtonText)); + this.buttonList + .add(new GuiOptionButton(1, this.width / 2 - 155 + 160, this.height / 6 + 96, this.cancelButtonText)); + this.field_175298_s.clear(); + this.field_175298_s.addAll(this.fontRendererObj.listFormattedStringToWidth(this.messageLine2, this.width - 50)); + } + + /** + * + Sets the number of ticks to wait before enabling the buttons. */ public void setButtonDelay(int parInt1) { this.ticksUntilEnable = parInt1; @@ -110,8 +113,8 @@ public class GuiYesNo extends GuiScreen { } - /**+ - * Called from the main game loop to update the screen. + /** + * + Called from the main game loop to update the screen. */ public void updateScreen() { super.updateScreen(); diff --git a/src/game/java/net/minecraft/client/gui/GuiYesNoCallback.java b/src/game/java/net/minecraft/client/gui/GuiYesNoCallback.java index 2eba26d3..e238b2ce 100644 --- a/src/game/java/net/minecraft/client/gui/GuiYesNoCallback.java +++ b/src/game/java/net/minecraft/client/gui/GuiYesNoCallback.java @@ -1,21 +1,24 @@ package net.minecraft.client.gui; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/IProgressMeter.java b/src/game/java/net/minecraft/client/gui/IProgressMeter.java index ec40c976..3c06103d 100644 --- a/src/game/java/net/minecraft/client/gui/IProgressMeter.java +++ b/src/game/java/net/minecraft/client/gui/IProgressMeter.java @@ -1,21 +1,24 @@ package net.minecraft.client.gui; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/MapItemRenderer.java b/src/game/java/net/minecraft/client/gui/MapItemRenderer.java index f604c27e..47964a40 100644 --- a/src/game/java/net/minecraft/client/gui/MapItemRenderer.java +++ b/src/game/java/net/minecraft/client/gui/MapItemRenderer.java @@ -1,6 +1,6 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; import java.util.Map; @@ -17,74 +17,30 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec4b; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapItemRenderer { - private static final ResourceLocation mapIcons = new ResourceLocation("textures/map/map_icons.png"); - private final TextureManager textureManager; - private final Map loadedMaps = Maps.newHashMap(); - - public MapItemRenderer(TextureManager textureManagerIn) { - this.textureManager = textureManagerIn; - } - - /**+ - * Updates a map texture - */ - public void updateMapTexture(MapData mapdataIn) { - this.getMapRendererInstance(mapdataIn).updateMapTexture(); - } - - public void renderMap(MapData mapdataIn, boolean parFlag) { - this.getMapRendererInstance(mapdataIn).render(parFlag); - } - - /**+ - * Returns {@link - * net.minecraft.client.gui.MapItemRenderer.Instance - * MapItemRenderer.Instance} with given map data - */ - private MapItemRenderer.Instance getMapRendererInstance(MapData mapdataIn) { - MapItemRenderer.Instance mapitemrenderer$instance = (MapItemRenderer.Instance) this.loadedMaps - .get(mapdataIn.mapName); - if (mapitemrenderer$instance == null) { - mapitemrenderer$instance = new MapItemRenderer.Instance(mapdataIn); - this.loadedMaps.put(mapdataIn.mapName, mapitemrenderer$instance); - } - - return mapitemrenderer$instance; - } - - /**+ - * Clears the currently loaded maps and removes their - * corresponding textures - */ - public void clearLoadedMaps() { - for (MapItemRenderer.Instance mapitemrenderer$instance : this.loadedMaps.values()) { - this.textureManager.deleteTexture(mapitemrenderer$instance.location); - } - - this.loadedMaps.clear(); - } - class Instance { private final MapData mapData; private final DynamicTexture mapTexture; @@ -104,24 +60,6 @@ public class MapItemRenderer { } - /**+ - * Updates a map texture - */ - private void updateMapTexture() { - for (int i = 0; i < 16384; ++i) { - int j = this.mapData.colors[i] & 255; - int c; - if (j / 4 == 0) { - c = (i + i / 128 & 1) * 8 + 16 << 24; - } else { - c = MapColor.mapColorArray[j / 4].func_151643_b(j & 3); - } - this.mapTextureData[i] = (c & 0xFF00FF00) | ((c & 0x00FF0000) >>> 16) | ((c & 0x000000FF) << 16); - } - - this.mapTexture.updateDynamicTexture(); - } - private void render(boolean noOverlayRendering) { byte b0 = 0; byte b1 = 0; @@ -184,5 +122,69 @@ public class MapItemRenderer { GlStateManager.scale(1.0F, 1.0F, 1.0F); GlStateManager.popMatrix(); } + + /** + * + Updates a map texture + */ + private void updateMapTexture() { + for (int i = 0; i < 16384; ++i) { + int j = this.mapData.colors[i] & 255; + int c; + if (j / 4 == 0) { + c = (i + i / 128 & 1) * 8 + 16 << 24; + } else { + c = MapColor.mapColorArray[j / 4].func_151643_b(j & 3); + } + this.mapTextureData[i] = (c & 0xFF00FF00) | ((c & 0x00FF0000) >>> 16) | ((c & 0x000000FF) << 16); + } + + this.mapTexture.updateDynamicTexture(); + } + } + + private static final ResourceLocation mapIcons = new ResourceLocation("textures/map/map_icons.png"); + private final TextureManager textureManager; + + private final Map loadedMaps = Maps.newHashMap(); + + public MapItemRenderer(TextureManager textureManagerIn) { + this.textureManager = textureManagerIn; + } + + /** + * + Clears the currently loaded maps and removes their corresponding textures + */ + public void clearLoadedMaps() { + for (MapItemRenderer.Instance mapitemrenderer$instance : this.loadedMaps.values()) { + this.textureManager.deleteTexture(mapitemrenderer$instance.location); + } + + this.loadedMaps.clear(); + } + + /** + * + Returns {@link net.minecraft.client.gui.MapItemRenderer.Instance + * MapItemRenderer.Instance} with given map data + */ + private MapItemRenderer.Instance getMapRendererInstance(MapData mapdataIn) { + MapItemRenderer.Instance mapitemrenderer$instance = (MapItemRenderer.Instance) this.loadedMaps + .get(mapdataIn.mapName); + if (mapitemrenderer$instance == null) { + mapitemrenderer$instance = new MapItemRenderer.Instance(mapdataIn); + this.loadedMaps.put(mapdataIn.mapName, mapitemrenderer$instance); + } + + return mapitemrenderer$instance; + } + + public void renderMap(MapData mapdataIn, boolean parFlag) { + this.getMapRendererInstance(mapdataIn).render(parFlag); + } + + /** + * + Updates a map texture + */ + public void updateMapTexture(MapData mapdataIn) { + this.getMapRendererInstance(mapdataIn).updateMapTexture(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/ScaledResolution.java b/src/game/java/net/minecraft/client/gui/ScaledResolution.java index 975526f4..8116544b 100644 --- a/src/game/java/net/minecraft/client/gui/ScaledResolution.java +++ b/src/game/java/net/minecraft/client/gui/ScaledResolution.java @@ -3,22 +3,25 @@ package net.minecraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,22 +64,22 @@ public class ScaledResolution { this.scaledHeight = MathHelper.ceiling_double_int(this.scaledHeightD); } - public int getScaledWidth() { - return this.scaledWidth; - } - public int getScaledHeight() { return this.scaledHeight; } - public double getScaledWidth_double() { - return this.scaledWidthD; - } - public double getScaledHeight_double() { return this.scaledHeightD; } + public int getScaledWidth() { + return this.scaledWidth; + } + + public double getScaledWidth_double() { + return this.scaledWidthD; + } + public int getScaleFactor() { return this.scaleFactor; } diff --git a/src/game/java/net/minecraft/client/gui/ScreenChatOptions.java b/src/game/java/net/minecraft/client/gui/ScreenChatOptions.java index bf17868f..59205ce3 100644 --- a/src/game/java/net/minecraft/client/gui/ScreenChatOptions.java +++ b/src/game/java/net/minecraft/client/gui/ScreenChatOptions.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.minecraft.client.resources.I18n; import net.minecraft.client.settings.GameSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,10 +48,40 @@ public class ScreenChatOptions extends GuiScreen { this.game_settings = gameSettingsIn; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id < 100 && parGuiButton instanceof GuiOptionButton) { + this.game_settings.setOptionValue(((GuiOptionButton) parGuiButton).returnEnumOptions(), 1); + parGuiButton.displayString = this.game_settings + .getKeyBinding(GameSettings.Options.getEnumOptions(parGuiButton.id)); + } + + if (parGuiButton.id == 200) { + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(this.parentScreen); + } + + } + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, this.field_146401_i, this.width / 2, 20, 16777215); + super.drawScreen(i, j, f); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { int i = 0; @@ -73,34 +106,4 @@ public class ScreenChatOptions extends GuiScreen { this.buttonList.add(new GuiButton(200, this.width / 2 - 100, this.height / 6 + (profanityFilterForce ? 130 : 154), I18n.format("gui.done", new Object[0]))); } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id < 100 && parGuiButton instanceof GuiOptionButton) { - this.game_settings.setOptionValue(((GuiOptionButton) parGuiButton).returnEnumOptions(), 1); - parGuiButton.displayString = this.game_settings - .getKeyBinding(GameSettings.Options.getEnumOptions(parGuiButton.id)); - } - - if (parGuiButton.id == 200) { - this.mc.gameSettings.saveOptions(); - this.mc.displayGuiScreen(this.parentScreen); - } - - } - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, this.field_146401_i, this.width / 2, 20, 16777215); - super.drawScreen(i, j, f); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/ServerListEntryNormal.java b/src/game/java/net/minecraft/client/gui/ServerListEntryNormal.java index 809016ce..e2816979 100644 --- a/src/game/java/net/minecraft/client/gui/ServerListEntryNormal.java +++ b/src/game/java/net/minecraft/client/gui/ServerListEntryNormal.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.util.List; @@ -13,22 +14,25 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -190,8 +194,12 @@ public class ServerListEntryNormal implements GuiListExtended.IGuiListEntry { return true; } - /**+ - * Returns true if the mouse has been pressed on this control. + public ServerData getServerData() { + return this.field_148301_e; + } + + /** + * + Returns true if the mouse has been pressed on this control. */ public boolean mousePressed(int i, int var2, int var3, int var4, int j, int k) { if (j <= 32) { @@ -221,17 +229,13 @@ public class ServerListEntryNormal implements GuiListExtended.IGuiListEntry { return false; } - public void setSelected(int var1, int var2, int var3) { - } - - /**+ - * Fired when the mouse button is released. Arguments: index, x, - * y, mouseEvent, relativeX, relativeY + /** + * + Fired when the mouse button is released. Arguments: index, x, y, + * mouseEvent, relativeX, relativeY */ public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { } - public ServerData getServerData() { - return this.field_148301_e; + public void setSelected(int var1, int var2, int var3) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/ServerSelectionList.java b/src/game/java/net/minecraft/client/gui/ServerSelectionList.java index af520c52..d3e2529c 100644 --- a/src/game/java/net/minecraft/client/gui/ServerSelectionList.java +++ b/src/game/java/net/minecraft/client/gui/ServerSelectionList.java @@ -11,22 +11,25 @@ import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; import net.minecraft.client.resources.I18n; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -58,59 +61,6 @@ public class ServerSelectionList extends GuiListExtended { }; } - /**+ - * Gets the IGuiListEntry object for the given index - */ - public GuiListExtended.IGuiListEntry getListEntry(int i) { - if (i < getOrigSize()) { - return (GuiListExtended.IGuiListEntry) this.field_148198_l.get(i); - } - return serverListEntryLAN; - } - - protected int getOrigSize() { - return this.field_148198_l.size(); - } - - protected int getSize() { - return this.field_148198_l.size() + GuiMultiplayer.getLanServerList().countServers(); - } - - public void setSelectedSlotIndex(int selectedSlotIndexIn) { - this.selectedSlotIndex = selectedSlotIndexIn; - } - - /**+ - * Returns true if the element passed in is currently selected - */ - protected boolean isSelected(int i) { - return i == this.selectedSlotIndex; - } - - public int func_148193_k() { - return this.selectedSlotIndex; - } - - public void func_148195_a(ServerList parServerList) { - this.field_148198_l.clear(); - - for (int i = 0; i < parServerList.countServers(); ++i) { - this.field_148198_l.add(new ServerListEntryNormal(this.owner, parServerList.getServerData(i))); - } - - } - - protected int getScrollBarX() { - return super.getScrollBarX() + 30; - } - - /**+ - * Gets the width of the list - */ - public int getListWidth() { - return super.getListWidth() + 85; - } - @Override protected void drawSelectionBox(int mouseXIn, int mouseYIn, int parInt3, int parInt4, int i) { super.drawSelectionBox(mouseXIn, mouseYIn, parInt3, parInt4, i + 1); @@ -127,6 +77,19 @@ public class ServerSelectionList extends GuiListExtended { } } + public int func_148193_k() { + return this.selectedSlotIndex; + } + + public void func_148195_a(ServerList parServerList) { + this.field_148198_l.clear(); + + for (int i = 0; i < parServerList.countServers(); ++i) { + this.field_148198_l.add(new ServerListEntryNormal(this.owner, parServerList.getServerData(i))); + } + + } + private void func_77248_b(int par1, int par2, int par3, int par4) { LANServerList.LanServer var6 = GuiMultiplayer.getLanServerList().getServer(par1 - getOrigSize()); this.owner.drawString(this.owner.fontRendererObj, I18n.format("lanServer.title"), par2 + 2, par3 + 1, 16777215); @@ -172,4 +135,44 @@ public class ServerSelectionList extends GuiListExtended { this.owner.drawCenteredString(this.owner.fontRendererObj, var6, this.owner.width / 2, par3 + 18, 8421504); } } + + /** + * + Gets the IGuiListEntry object for the given index + */ + public GuiListExtended.IGuiListEntry getListEntry(int i) { + if (i < getOrigSize()) { + return (GuiListExtended.IGuiListEntry) this.field_148198_l.get(i); + } + return serverListEntryLAN; + } + + /** + * + Gets the width of the list + */ + public int getListWidth() { + return super.getListWidth() + 85; + } + + protected int getOrigSize() { + return this.field_148198_l.size(); + } + + protected int getScrollBarX() { + return super.getScrollBarX() + 30; + } + + protected int getSize() { + return this.field_148198_l.size() + GuiMultiplayer.getLanServerList().countServers(); + } + + /** + * + Returns true if the element passed in is currently selected + */ + protected boolean isSelected(int i) { + return i == this.selectedSlotIndex; + } + + public void setSelectedSlotIndex(int selectedSlotIndexIn) { + this.selectedSlotIndex = selectedSlotIndexIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/achievement/GuiAchievement.java b/src/game/java/net/minecraft/client/gui/achievement/GuiAchievement.java index fc8efbfa..af7d7865 100644 --- a/src/game/java/net/minecraft/client/gui/achievement/GuiAchievement.java +++ b/src/game/java/net/minecraft/client/gui/achievement/GuiAchievement.java @@ -1,6 +1,8 @@ package net.minecraft.client.gui.achievement; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; @@ -12,22 +14,25 @@ import net.minecraft.client.resources.I18n; import net.minecraft.stats.Achievement; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,6 +55,11 @@ public class GuiAchievement extends Gui { this.renderItem = mc.getRenderItem(); } + public void clearAchievements() { + this.theAchievement = null; + this.notificationTime = 0L; + } + public void displayAchievement(Achievement ach) { this.achievementTitle = I18n.format("achievement.get", new Object[0]); this.achievementDescription = ach.getStatName().getUnformattedText(); @@ -66,24 +76,36 @@ public class GuiAchievement extends Gui { this.permanentNotification = true; } - private void updateAchievementWindowScale() { - GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - this.width = this.mc.displayWidth; - this.height = this.mc.displayHeight; - ScaledResolution scaledresolution = mc.scaledResolution; - this.width = scaledresolution.getScaledWidth(); - this.height = scaledresolution.getScaledHeight(); - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.ortho(0.0D, (double) this.width, (double) this.height, 0.0D, 1000.0D, 3000.0D); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - GlStateManager.translate(0.0F, 0.0F, -2000.0F); + public int getHeight() { + if (this.theAchievement != null && this.notificationTime != 0L && Minecraft.getMinecraft().thePlayer != null) { + double d0 = (double) (Minecraft.getSystemTime() - this.notificationTime) / 3000.0D; + if (!this.permanentNotification) { + if (d0 < 0.0D || d0 > 1.0D) { + this.notificationTime = 0L; + return 0; + } + } else if (d0 > 0.5D) { + d0 = 0.5D; + } + + double d1 = d0 * 2.0D; + if (d1 > 1.0D) { + d1 = 2.0D - d1; + } + + d1 = d1 * 4.0D; + d1 = 1.0D - d1; + if (d1 < 0.0D) { + d1 = 0.0D; + } + + d1 = d1 * d1; + d1 = d1 * d1; + + return 32 - (int) (d1 * 32.0D); + } else { + return 0; + } } public void updateAchievementWindow() { @@ -140,40 +162,23 @@ public class GuiAchievement extends Gui { } } - public int getHeight() { - if (this.theAchievement != null && this.notificationTime != 0L && Minecraft.getMinecraft().thePlayer != null) { - double d0 = (double) (Minecraft.getSystemTime() - this.notificationTime) / 3000.0D; - if (!this.permanentNotification) { - if (d0 < 0.0D || d0 > 1.0D) { - this.notificationTime = 0L; - return 0; - } - } else if (d0 > 0.5D) { - d0 = 0.5D; - } - - double d1 = d0 * 2.0D; - if (d1 > 1.0D) { - d1 = 2.0D - d1; - } - - d1 = d1 * 4.0D; - d1 = 1.0D - d1; - if (d1 < 0.0D) { - d1 = 0.0D; - } - - d1 = d1 * d1; - d1 = d1 * d1; - - return 32 - (int) (d1 * 32.0D); - } else { - return 0; - } - } - - public void clearAchievements() { - this.theAchievement = null; - this.notificationTime = 0L; + private void updateAchievementWindowScale() { + GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + this.width = this.mc.displayWidth; + this.height = this.mc.displayHeight; + ScaledResolution scaledresolution = mc.scaledResolution; + this.width = scaledresolution.getScaledWidth(); + this.height = scaledresolution.getScaledHeight(); + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.ortho(0.0D, (double) this.width, (double) this.height, 0.0D, 1000.0D, 3000.0D); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + GlStateManager.translate(0.0F, 0.0F, -2000.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/achievement/GuiAchievements.java b/src/game/java/net/minecraft/client/gui/achievement/GuiAchievements.java index b85603de..0fe1d502 100644 --- a/src/game/java/net/minecraft/client/gui/achievement/GuiAchievements.java +++ b/src/game/java/net/minecraft/client/gui/achievement/GuiAchievements.java @@ -1,9 +1,12 @@ package net.minecraft.client.gui.achievement; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; @@ -26,22 +29,25 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -80,22 +86,9 @@ public class GuiAchievements extends GuiScreen implements IProgressMeter { * 24 - short2 / 2); } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.mc.getNetHandler() - .addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.REQUEST_STATS)); - this.buttonList.clear(); - this.buttonList.add(new GuiOptionButton(1, this.width / 2 + 24, this.height / 2 + 74, 80, 20, - I18n.format("gui.done", new Object[0]))); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (!this.loadingAchievements) { @@ -106,92 +99,12 @@ public class GuiAchievements extends GuiScreen implements IProgressMeter { } } - protected int getCloseKey() { - return this.mc.gameSettings.keyBindInventory.getKeyCode(); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player */ - public void drawScreen(int i, int j, float f) { - if (this.loadingAchievements) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingStats", new Object[0]), - this.width / 2, this.height / 2, 16777215); - this.drawCenteredString(this.fontRendererObj, - lanSearchStates[(int) (Minecraft.getSystemTime() / 150L % (long) lanSearchStates.length)], - this.width / 2, this.height / 2 + this.fontRendererObj.FONT_HEIGHT * 2, 16777215); - } else { - if (PointerInputAbstraction.getVCursorButtonDown(0)) { - int k = (this.width - this.field_146555_f) / 2; - int l = (this.height - this.field_146557_g) / 2; - int i1 = k + 8; - int j1 = l + 17; - if ((this.field_146554_D == 0 || this.field_146554_D == 1) && i >= i1 && i < i1 + 224 && j >= j1 - && j < j1 + 155) { - if (this.field_146554_D == 0) { - this.field_146554_D = 1; - } else { - this.field_146567_u -= (double) ((float) (i - this.field_146563_h) * this.field_146570_r); - this.field_146566_v -= (double) ((float) (j - this.field_146564_i) * this.field_146570_r); - this.field_146565_w = this.field_146569_s = this.field_146567_u; - this.field_146573_x = this.field_146568_t = this.field_146566_v; - } - - this.field_146563_h = i; - this.field_146564_i = j; - } - } else { - this.field_146554_D = 0; - } - - int k1 = Mouse.getDWheel(); - float f4 = this.field_146570_r; - if (k1 < 0) { - this.field_146570_r += 0.25F; - } else if (k1 > 0) { - this.field_146570_r -= 0.25F; - } - - this.field_146570_r = MathHelper.clamp_float(this.field_146570_r, 1.0F, 2.0F); - if (this.field_146570_r != f4) { - float f6 = f4 - this.field_146570_r; - float f5 = f4 * (float) this.field_146555_f; - float f1 = f4 * (float) this.field_146557_g; - float f2 = this.field_146570_r * (float) this.field_146555_f; - float f3 = this.field_146570_r * (float) this.field_146557_g; - this.field_146567_u -= (double) ((f2 - f5) * 0.5F); - this.field_146566_v -= (double) ((f3 - f1) * 0.5F); - this.field_146565_w = this.field_146569_s = this.field_146567_u; - this.field_146573_x = this.field_146568_t = this.field_146566_v; - } - - if (this.field_146565_w < (double) field_146572_y) { - this.field_146565_w = (double) field_146572_y; - } - - if (this.field_146573_x < (double) field_146571_z) { - this.field_146573_x = (double) field_146571_z; - } - - if (this.field_146565_w >= (double) field_146559_A) { - this.field_146565_w = (double) (field_146559_A - 1); - } - - if (this.field_146573_x >= (double) field_146560_B) { - this.field_146573_x = (double) (field_146560_B - 1); - } - - this.drawDefaultBackground(); - this.drawAchievementScreen(i, j, f); - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - this.drawTitle(); - GlStateManager.disableLighting(); - GlStateManager.enableDepth(); - } - + public boolean doesGuiPauseGame() { + return !this.loadingAchievements; } public void doneLoading() { @@ -201,32 +114,6 @@ public class GuiAchievements extends GuiScreen implements IProgressMeter { } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - if (!this.loadingAchievements) { - this.field_146569_s = this.field_146567_u; - this.field_146568_t = this.field_146566_v; - double d0 = this.field_146565_w - this.field_146567_u; - double d1 = this.field_146573_x - this.field_146566_v; - if (d0 * d0 + d1 * d1 < 4.0D) { - this.field_146567_u += d0; - this.field_146566_v += d1; - } else { - this.field_146567_u += d0 * 0.85D; - this.field_146566_v += d1 * 0.85D; - } - - } - } - - protected void drawTitle() { - int i = (this.width - this.field_146555_f) / 2; - int j = (this.height - this.field_146557_g) / 2; - this.fontRendererObj.drawString(I18n.format("gui.achievements", new Object[0]), i + 15, j + 5, 4210752); - } - protected void drawAchievementScreen(int parInt1, int parInt2, float parFloat1) { int i = MathHelper .floor_double(this.field_146569_s + (this.field_146567_u - this.field_146569_s) * (double) parFloat1); @@ -475,16 +362,135 @@ public class GuiAchievements extends GuiScreen implements IProgressMeter { RenderHelper.disableStandardItemLighting(); } + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + if (this.loadingAchievements) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingStats", new Object[0]), + this.width / 2, this.height / 2, 16777215); + this.drawCenteredString(this.fontRendererObj, + lanSearchStates[(int) (Minecraft.getSystemTime() / 150L % (long) lanSearchStates.length)], + this.width / 2, this.height / 2 + this.fontRendererObj.FONT_HEIGHT * 2, 16777215); + } else { + if (PointerInputAbstraction.getVCursorButtonDown(0)) { + int k = (this.width - this.field_146555_f) / 2; + int l = (this.height - this.field_146557_g) / 2; + int i1 = k + 8; + int j1 = l + 17; + if ((this.field_146554_D == 0 || this.field_146554_D == 1) && i >= i1 && i < i1 + 224 && j >= j1 + && j < j1 + 155) { + if (this.field_146554_D == 0) { + this.field_146554_D = 1; + } else { + this.field_146567_u -= (double) ((float) (i - this.field_146563_h) * this.field_146570_r); + this.field_146566_v -= (double) ((float) (j - this.field_146564_i) * this.field_146570_r); + this.field_146565_w = this.field_146569_s = this.field_146567_u; + this.field_146573_x = this.field_146568_t = this.field_146566_v; + } + + this.field_146563_h = i; + this.field_146564_i = j; + } + } else { + this.field_146554_D = 0; + } + + int k1 = Mouse.getDWheel(); + float f4 = this.field_146570_r; + if (k1 < 0) { + this.field_146570_r += 0.25F; + } else if (k1 > 0) { + this.field_146570_r -= 0.25F; + } + + this.field_146570_r = MathHelper.clamp_float(this.field_146570_r, 1.0F, 2.0F); + if (this.field_146570_r != f4) { + float f6 = f4 - this.field_146570_r; + float f5 = f4 * (float) this.field_146555_f; + float f1 = f4 * (float) this.field_146557_g; + float f2 = this.field_146570_r * (float) this.field_146555_f; + float f3 = this.field_146570_r * (float) this.field_146557_g; + this.field_146567_u -= (double) ((f2 - f5) * 0.5F); + this.field_146566_v -= (double) ((f3 - f1) * 0.5F); + this.field_146565_w = this.field_146569_s = this.field_146567_u; + this.field_146573_x = this.field_146568_t = this.field_146566_v; + } + + if (this.field_146565_w < (double) field_146572_y) { + this.field_146565_w = (double) field_146572_y; + } + + if (this.field_146573_x < (double) field_146571_z) { + this.field_146573_x = (double) field_146571_z; + } + + if (this.field_146565_w >= (double) field_146559_A) { + this.field_146565_w = (double) (field_146559_A - 1); + } + + if (this.field_146573_x >= (double) field_146560_B) { + this.field_146573_x = (double) (field_146560_B - 1); + } + + this.drawDefaultBackground(); + this.drawAchievementScreen(i, j, f); + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + this.drawTitle(); + GlStateManager.disableLighting(); + GlStateManager.enableDepth(); + } + + } + + protected void drawTitle() { + int i = (this.width - this.field_146555_f) / 2; + int j = (this.height - this.field_146557_g) / 2; + this.fontRendererObj.drawString(I18n.format("gui.achievements", new Object[0]), i + 15, j + 5, 4210752); + } + private EaglerTextureAtlasSprite func_175371_a(Block parBlock) { return Minecraft.getMinecraft().getBlockRendererDispatcher().getBlockModelShapes() .getTexture(parBlock.getDefaultState()); } - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player + protected int getCloseKey() { + return this.mc.gameSettings.keyBindInventory.getKeyCode(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ - public boolean doesGuiPauseGame() { - return !this.loadingAchievements; + public void initGui() { + this.mc.getNetHandler() + .addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.REQUEST_STATS)); + this.buttonList.clear(); + this.buttonList.add(new GuiOptionButton(1, this.width / 2 + 24, this.height / 2 + 74, 80, 20, + I18n.format("gui.done", new Object[0]))); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + if (!this.loadingAchievements) { + this.field_146569_s = this.field_146567_u; + this.field_146568_t = this.field_146566_v; + double d0 = this.field_146565_w - this.field_146567_u; + double d1 = this.field_146573_x - this.field_146566_v; + if (d0 * d0 + d1 * d1 < 4.0D) { + this.field_146567_u += d0; + this.field_146566_v += d1; + } else { + this.field_146567_u += d0 * 0.85D; + this.field_146566_v += d1 * 0.85D; + } + + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/achievement/GuiStats.java b/src/game/java/net/minecraft/client/gui/achievement/GuiStats.java index b9273e3c..8dac2556 100644 --- a/src/game/java/net/minecraft/client/gui/achievement/GuiStats.java +++ b/src/game/java/net/minecraft/client/gui/achievement/GuiStats.java @@ -30,220 +30,30 @@ import net.minecraft.stats.StatFileWriter; import net.minecraft.stats.StatList; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiStats extends GuiScreen implements IProgressMeter { - protected GuiScreen parentScreen; - protected String screenTitle = "Select world"; - private GuiStats.StatsGeneral generalStats; - private GuiStats.StatsItem itemStats; - private GuiStats.StatsBlock blockStats; - private GuiStats.StatsMobsList mobStats; - private StatFileWriter field_146546_t; - private GuiSlot displaySlot; - /**+ - * When true, the game will be paused when the gui is shown - */ - private boolean doesGuiPauseGame = true; - - public GuiStats(GuiScreen parGuiScreen, StatFileWriter parStatFileWriter) { - this.parentScreen = parGuiScreen; - this.field_146546_t = parStatFileWriter; - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.screenTitle = I18n.format("gui.stats", new Object[0]); - this.doesGuiPauseGame = true; - this.mc.getNetHandler() - .addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.REQUEST_STATS)); - } - - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - if (this.displaySlot != null) { - this.displaySlot.handleMouseInput(); - } - - } - - public void handleTouchInput() throws IOException { - super.handleTouchInput(); - if (this.displaySlot != null) { - this.displaySlot.handleTouchInput(); - } - } - - public void func_175366_f() { - this.generalStats = new GuiStats.StatsGeneral(this.mc); - this.generalStats.registerScrollButtons(1, 1); - this.itemStats = new GuiStats.StatsItem(this.mc); - this.itemStats.registerScrollButtons(1, 1); - this.blockStats = new GuiStats.StatsBlock(this.mc); - this.blockStats.registerScrollButtons(1, 1); - this.mobStats = new GuiStats.StatsMobsList(this.mc); - this.mobStats.registerScrollButtons(1, 1); - } - - public void createButtons() { - this.buttonList.add(new GuiButton(0, this.width / 2 + 4, this.height - 28, 150, 20, - I18n.format("gui.done", new Object[0]))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 160, this.height - 52, 80, 20, - I18n.format("stat.generalButton", new Object[0]))); - GuiButton guibutton; - this.buttonList.add(guibutton = new GuiButton(2, this.width / 2 - 80, this.height - 52, 80, 20, - I18n.format("stat.blocksButton", new Object[0]))); - GuiButton guibutton1; - this.buttonList.add(guibutton1 = new GuiButton(3, this.width / 2, this.height - 52, 80, 20, - I18n.format("stat.itemsButton", new Object[0]))); - GuiButton guibutton2; - this.buttonList.add(guibutton2 = new GuiButton(4, this.width / 2 + 80, this.height - 52, 80, 20, - I18n.format("stat.mobsButton", new Object[0]))); - if (this.blockStats.getSize() == 0) { - guibutton.enabled = false; - } - - if (this.itemStats.getSize() == 0) { - guibutton1.enabled = false; - } - - if (this.mobStats.getSize() == 0) { - guibutton2.enabled = false; - } - - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - if (parGuiButton.id == 0) { - this.mc.displayGuiScreen(this.parentScreen); - } else if (parGuiButton.id == 1) { - this.displaySlot = this.generalStats; - } else if (parGuiButton.id == 3) { - this.displaySlot = this.itemStats; - } else if (parGuiButton.id == 2) { - this.displaySlot = this.blockStats; - } else if (parGuiButton.id == 4) { - this.displaySlot = this.mobStats; - } else { - this.displaySlot.actionPerformed(parGuiButton); - } - - } - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - if (this.doesGuiPauseGame) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingStats", new Object[0]), - this.width / 2, this.height / 2, 16777215); - this.drawCenteredString(this.fontRendererObj, - lanSearchStates[(int) (Minecraft.getSystemTime() / 150L % (long) lanSearchStates.length)], - this.width / 2, this.height / 2 + this.fontRendererObj.FONT_HEIGHT * 2, 16777215); - } else { - this.displaySlot.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 20, 16777215); - super.drawScreen(i, j, f); - } - - } - - public void doneLoading() { - if (this.doesGuiPauseGame) { - this.func_175366_f(); - this.createButtons(); - this.displaySlot = this.generalStats; - this.doesGuiPauseGame = false; - } - - } - - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player - */ - public boolean doesGuiPauseGame() { - return !this.doesGuiPauseGame; - } - - private void drawStatsScreen(int parInt1, int parInt2, Item parItem) { - this.drawButtonBackground(parInt1 + 1, parInt2 + 1); - GlStateManager.enableRescaleNormal(); - RenderHelper.enableGUIStandardItemLighting(); - this.itemRender.renderItemIntoGUI(new ItemStack(parItem, 1, 0), parInt1 + 2, parInt2 + 2); - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableRescaleNormal(); - } - - /**+ - * Draws a gray box that serves as a button background. - */ - private void drawButtonBackground(int parInt1, int parInt2) { - this.drawSprite(parInt1, parInt2, 0, 0); - } - - /**+ - * Draws a sprite from - * assets/textures/gui/container/stats_icons.png - */ - private void drawSprite(int parInt1, int parInt2, int parInt3, int parInt4) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(statIcons); - float f = 0.0078125F; - float f1 = 0.0078125F; - boolean flag = true; - boolean flag1 = true; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 18), (double) this.zLevel) - .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 18), (double) this.zLevel) - .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 0), (double) this.zLevel) - .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) - .endVertex(); - worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 0), (double) this.zLevel) - .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) - .endVertex(); - tessellator.draw(); - } - abstract class Stats extends GuiSlot { protected int field_148218_l = -1; protected List statsHolder; @@ -257,13 +67,6 @@ public class GuiStats extends GuiScreen implements IProgressMeter { this.setHasListHeader(true, 20); } - protected void elementClicked(int var1, boolean var2, int var3, int var4) { - } - - protected boolean isSelected(int var1) { - return false; - } - protected void drawBackground() { GuiStats.this.drawDefaultBackground(); } @@ -309,6 +112,9 @@ public class GuiStats extends GuiScreen implements IProgressMeter { } + protected void elementClicked(int var1, boolean var2, int var3, int var4) { + } + protected void func_148132_a(int i, int var2) { this.field_148218_l = -1; if (i >= 79 && i < 115) { @@ -327,31 +133,6 @@ public class GuiStats extends GuiScreen implements IProgressMeter { } - protected final int getSize() { - return this.statsHolder.size(); - } - - protected final StatCrafting func_148211_c(int parInt1) { - return (StatCrafting) this.statsHolder.get(parInt1); - } - - protected abstract String func_148210_b(int var1); - - protected void func_148209_a(StatBase parStatBase, int parInt1, int parInt2, boolean parFlag) { - if (parStatBase != null) { - String s = parStatBase.format(GuiStats.this.field_146546_t.readStat(parStatBase)); - GuiStats.this.drawString(GuiStats.this.fontRendererObj, s, - parInt1 - GuiStats.this.fontRendererObj.getStringWidth(s), parInt2 + 5, - parFlag ? 16777215 : 9474192); - } else { - String s1 = "-"; - GuiStats.this.drawString(GuiStats.this.fontRendererObj, s1, - parInt1 - GuiStats.this.fontRendererObj.getStringWidth(s1), parInt2 + 5, - parFlag ? 16777215 : 9474192); - } - - } - protected void func_148142_b(int i, int j) { if (j >= this.top && j <= this.bottom) { int k = this.getSlotIndexFromScreenCoords(i, j); @@ -391,6 +172,41 @@ public class GuiStats extends GuiScreen implements IProgressMeter { } } + protected void func_148209_a(StatBase parStatBase, int parInt1, int parInt2, boolean parFlag) { + if (parStatBase != null) { + String s = parStatBase.format(GuiStats.this.field_146546_t.readStat(parStatBase)); + GuiStats.this.drawString(GuiStats.this.fontRendererObj, s, + parInt1 - GuiStats.this.fontRendererObj.getStringWidth(s), parInt2 + 5, + parFlag ? 16777215 : 9474192); + } else { + String s1 = "-"; + GuiStats.this.drawString(GuiStats.this.fontRendererObj, s1, + parInt1 - GuiStats.this.fontRendererObj.getStringWidth(s1), parInt2 + 5, + parFlag ? 16777215 : 9474192); + } + + } + + protected abstract String func_148210_b(int var1); + + protected final StatCrafting func_148211_c(int parInt1) { + return (StatCrafting) this.statsHolder.get(parInt1); + } + + protected void func_148212_h(int parInt1) { + if (parInt1 != this.field_148217_o) { + this.field_148217_o = parInt1; + this.field_148215_p = -1; + } else if (this.field_148215_p == -1) { + this.field_148215_p = 1; + } else { + this.field_148217_o = -1; + this.field_148215_p = 0; + } + + Collections.sort(this.statsHolder, this.statSorter); + } + protected void func_148213_a(StatCrafting parStatCrafting, int parInt1, int parInt2) { if (parStatCrafting != null) { Item item = parStatCrafting.func_150959_a(); @@ -408,18 +224,12 @@ public class GuiStats extends GuiScreen implements IProgressMeter { } } - protected void func_148212_h(int parInt1) { - if (parInt1 != this.field_148217_o) { - this.field_148217_o = parInt1; - this.field_148215_p = -1; - } else if (this.field_148215_p == -1) { - this.field_148215_p = 1; - } else { - this.field_148217_o = -1; - this.field_148215_p = 0; - } + protected final int getSize() { + return this.statsHolder.size(); + } - Collections.sort(this.statsHolder, this.statSorter); + protected boolean isSelected(int var1) { + return false; } } @@ -528,21 +338,6 @@ public class GuiStats extends GuiScreen implements IProgressMeter { this.setShowSelectionBox(false); } - protected int getSize() { - return StatList.generalStats.size(); - } - - protected void elementClicked(int var1, boolean var2, int var3, int var4) { - } - - protected boolean isSelected(int var1) { - return false; - } - - protected int getContentHeight() { - return this.getSize() * 10; - } - protected void drawBackground() { GuiStats.this.drawDefaultBackground(); } @@ -556,6 +351,21 @@ public class GuiStats extends GuiScreen implements IProgressMeter { j + 2 + 213 - GuiStats.this.fontRendererObj.getStringWidth(s), k + 1, i % 2 == 0 ? 16777215 : 9474192); } + + protected void elementClicked(int var1, boolean var2, int var3, int var4) { + } + + protected int getContentHeight() { + return this.getSize() * 10; + } + + protected int getSize() { + return StatList.generalStats.size(); + } + + protected boolean isSelected(int var1) { + return false; + } } class StatsItem extends GuiStats.Stats { @@ -674,21 +484,6 @@ public class GuiStats extends GuiScreen implements IProgressMeter { } - protected int getSize() { - return this.field_148222_l.size(); - } - - protected void elementClicked(int var1, boolean var2, int var3, int var4) { - } - - protected boolean isSelected(int var1) { - return false; - } - - protected int getContentHeight() { - return this.getSize() * GuiStats.this.fontRendererObj.FONT_HEIGHT * 4; - } - protected void drawBackground() { GuiStats.this.drawDefaultBackground(); } @@ -715,5 +510,217 @@ public class GuiStats extends GuiScreen implements IProgressMeter { GuiStats.this.drawString(GuiStats.this.fontRendererObj, s2, j + 2, k + 1 + GuiStats.this.fontRendererObj.FONT_HEIGHT * 2, i1 == 0 ? 6316128 : 9474192); } + + protected void elementClicked(int var1, boolean var2, int var3, int var4) { + } + + protected int getContentHeight() { + return this.getSize() * GuiStats.this.fontRendererObj.FONT_HEIGHT * 4; + } + + protected int getSize() { + return this.field_148222_l.size(); + } + + protected boolean isSelected(int var1) { + return false; + } + } + + protected GuiScreen parentScreen; + protected String screenTitle = "Select world"; + private GuiStats.StatsGeneral generalStats; + private GuiStats.StatsItem itemStats; + + private GuiStats.StatsBlock blockStats; + + private GuiStats.StatsMobsList mobStats; + + private StatFileWriter field_146546_t; + + private GuiSlot displaySlot; + + /** + * + When true, the game will be paused when the gui is shown + */ + private boolean doesGuiPauseGame = true; + + public GuiStats(GuiScreen parGuiScreen, StatFileWriter parStatFileWriter) { + this.parentScreen = parGuiScreen; + this.field_146546_t = parStatFileWriter; + } + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + if (parGuiButton.id == 0) { + this.mc.displayGuiScreen(this.parentScreen); + } else if (parGuiButton.id == 1) { + this.displaySlot = this.generalStats; + } else if (parGuiButton.id == 3) { + this.displaySlot = this.itemStats; + } else if (parGuiButton.id == 2) { + this.displaySlot = this.blockStats; + } else if (parGuiButton.id == 4) { + this.displaySlot = this.mobStats; + } else { + this.displaySlot.actionPerformed(parGuiButton); + } + + } + } + + public void createButtons() { + this.buttonList.add(new GuiButton(0, this.width / 2 + 4, this.height - 28, 150, 20, + I18n.format("gui.done", new Object[0]))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 160, this.height - 52, 80, 20, + I18n.format("stat.generalButton", new Object[0]))); + GuiButton guibutton; + this.buttonList.add(guibutton = new GuiButton(2, this.width / 2 - 80, this.height - 52, 80, 20, + I18n.format("stat.blocksButton", new Object[0]))); + GuiButton guibutton1; + this.buttonList.add(guibutton1 = new GuiButton(3, this.width / 2, this.height - 52, 80, 20, + I18n.format("stat.itemsButton", new Object[0]))); + GuiButton guibutton2; + this.buttonList.add(guibutton2 = new GuiButton(4, this.width / 2 + 80, this.height - 52, 80, 20, + I18n.format("stat.mobsButton", new Object[0]))); + if (this.blockStats.getSize() == 0) { + guibutton.enabled = false; + } + + if (this.itemStats.getSize() == 0) { + guibutton1.enabled = false; + } + + if (this.mobStats.getSize() == 0) { + guibutton2.enabled = false; + } + + } + + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return !this.doesGuiPauseGame; + } + + public void doneLoading() { + if (this.doesGuiPauseGame) { + this.func_175366_f(); + this.createButtons(); + this.displaySlot = this.generalStats; + this.doesGuiPauseGame = false; + } + + } + + /** + * + Draws a gray box that serves as a button background. + */ + private void drawButtonBackground(int parInt1, int parInt2) { + this.drawSprite(parInt1, parInt2, 0, 0); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + if (this.doesGuiPauseGame) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("multiplayer.downloadingStats", new Object[0]), + this.width / 2, this.height / 2, 16777215); + this.drawCenteredString(this.fontRendererObj, + lanSearchStates[(int) (Minecraft.getSystemTime() / 150L % (long) lanSearchStates.length)], + this.width / 2, this.height / 2 + this.fontRendererObj.FONT_HEIGHT * 2, 16777215); + } else { + this.displaySlot.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, this.screenTitle, this.width / 2, 20, 16777215); + super.drawScreen(i, j, f); + } + + } + + /** + * + Draws a sprite from assets/textures/gui/container/stats_icons.png + */ + private void drawSprite(int parInt1, int parInt2, int parInt3, int parInt4) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(statIcons); + float f = 0.0078125F; + float f1 = 0.0078125F; + boolean flag = true; + boolean flag1 = true; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 18), (double) this.zLevel) + .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 18), (double) this.zLevel) + .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 18) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 18), (double) (parInt2 + 0), (double) this.zLevel) + .tex((double) ((float) (parInt3 + 18) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) + .endVertex(); + worldrenderer.pos((double) (parInt1 + 0), (double) (parInt2 + 0), (double) this.zLevel) + .tex((double) ((float) (parInt3 + 0) * 0.0078125F), (double) ((float) (parInt4 + 0) * 0.0078125F)) + .endVertex(); + tessellator.draw(); + } + + private void drawStatsScreen(int parInt1, int parInt2, Item parItem) { + this.drawButtonBackground(parInt1 + 1, parInt2 + 1); + GlStateManager.enableRescaleNormal(); + RenderHelper.enableGUIStandardItemLighting(); + this.itemRender.renderItemIntoGUI(new ItemStack(parItem, 1, 0), parInt1 + 2, parInt2 + 2); + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableRescaleNormal(); + } + + public void func_175366_f() { + this.generalStats = new GuiStats.StatsGeneral(this.mc); + this.generalStats.registerScrollButtons(1, 1); + this.itemStats = new GuiStats.StatsItem(this.mc); + this.itemStats.registerScrollButtons(1, 1); + this.blockStats = new GuiStats.StatsBlock(this.mc); + this.blockStats.registerScrollButtons(1, 1); + this.mobStats = new GuiStats.StatsMobsList(this.mc); + this.mobStats.registerScrollButtons(1, 1); + } + + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + if (this.displaySlot != null) { + this.displaySlot.handleMouseInput(); + } + + } + + public void handleTouchInput() throws IOException { + super.handleTouchInput(); + if (this.displaySlot != null) { + this.displaySlot.handleTouchInput(); + } + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.screenTitle = I18n.format("gui.stats", new Object[0]); + this.doesGuiPauseGame = true; + this.mc.getNetHandler() + .addToSendQueue(new C16PacketClientStatus(C16PacketClientStatus.EnumState.REQUEST_STATS)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/CreativeCrafting.java b/src/game/java/net/minecraft/client/gui/inventory/CreativeCrafting.java index 51260b50..f8055c43 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/CreativeCrafting.java +++ b/src/game/java/net/minecraft/client/gui/inventory/CreativeCrafting.java @@ -8,22 +8,25 @@ import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,32 +38,30 @@ public class CreativeCrafting implements ICrafting { this.mc = mc; } - /**+ - * update the crafting window inventory with the items in the - * list - */ - public void updateCraftingInventory(Container var1, List var2) { + public void func_175173_a(Container var1, IInventory var2) { } - /**+ - * Sends the contents of an inventory slot to the client-side - * Container. This doesn't have to match the actual contents of - * that slot. Args: Container, slot number, slot contents + /** + * + Sends two ints to the client-side Container. Used for furnace burning time, + * smelting progress, brewing progress, and enchanting level. Normally the first + * int identifies which variable to update, and the second contains the new + * value. Both are truncated to shorts in non-local SMP. + */ + public void sendProgressBarUpdate(Container var1, int var2, int var3) { + } + + /** + * + Sends the contents of an inventory slot to the client-side Container. This + * doesn't have to match the actual contents of that slot. Args: Container, slot + * number, slot contents */ public void sendSlotContents(Container var1, int i, ItemStack itemstack) { this.mc.playerController.sendSlotPacket(itemstack, i); } - /**+ - * Sends two ints to the client-side Container. Used for furnace - * burning time, smelting progress, brewing progress, and - * enchanting level. Normally the first int identifies which - * variable to update, and the second contains the new value. - * Both are truncated to shorts in non-local SMP. + /** + * + update the crafting window inventory with the items in the list */ - public void sendProgressBarUpdate(Container var1, int var2, int var3) { - } - - public void func_175173_a(Container var1, IInventory var2) { + public void updateCraftingInventory(Container var1, List var2) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiBeacon.java b/src/game/java/net/minecraft/client/gui/inventory/GuiBeacon.java index 197507db..0cd8a4cb 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiBeacon.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiBeacon.java @@ -1,10 +1,10 @@ package net.minecraft.client.gui.inventory; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; @@ -22,31 +22,135 @@ import net.minecraft.potion.Potion; import net.minecraft.tileentity.TileEntityBeacon; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiBeacon extends GuiContainer { + static class Button extends GuiButton { + private final ResourceLocation field_146145_o; + private final int field_146144_p; + private final int field_146143_q; + private boolean field_146142_r; + + protected Button(int parInt1, int parInt2, int parInt3, ResourceLocation parResourceLocation, int parInt4, + int parInt5) { + super(parInt1, parInt2, parInt3, 22, 22, ""); + this.field_146145_o = parResourceLocation; + this.field_146144_p = parInt4; + this.field_146143_q = parInt5; + } + + public void drawButton(Minecraft minecraft, int i, int j) { + if (this.visible) { + minecraft.getTextureManager().bindTexture(GuiBeacon.beaconGuiTextures); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.hovered = i >= this.xPosition && j >= this.yPosition && i < this.xPosition + this.width + && j < this.yPosition + this.height; + short short1 = 219; + int k = 0; + if (!this.enabled) { + k += this.width * 2; + } else if (this.field_146142_r) { + k += this.width * 1; + } else if (this.hovered) { + k += this.width * 3; + } + + this.drawTexturedModalRect(this.xPosition, this.yPosition, k, short1, this.width, this.height); + if (!GuiBeacon.beaconGuiTextures.equals(this.field_146145_o)) { + minecraft.getTextureManager().bindTexture(this.field_146145_o); + } + + this.drawTexturedModalRect(this.xPosition + 2, this.yPosition + 2, this.field_146144_p, + this.field_146143_q, 18, 18); + } + } + + public void func_146140_b(boolean parFlag) { + this.field_146142_r = parFlag; + } + + public boolean func_146141_c() { + return this.field_146142_r; + } + } + + class CancelButton extends GuiBeacon.Button { + public CancelButton(int parInt1, int parInt2, int parInt3) { + super(parInt1, parInt2, parInt3, GuiBeacon.beaconGuiTextures, 112, 220); + } + + public void drawButtonForegroundLayer(int i, int j) { + if (this.enabled) + Mouse.showCursor(EnumCursorType.HAND); + GuiBeacon.this.drawCreativeTabHoveringText(I18n.format("gui.cancel", new Object[0]), i, j); + } + } + + class ConfirmButton extends GuiBeacon.Button { + public ConfirmButton(int parInt1, int parInt2, int parInt3) { + super(parInt1, parInt2, parInt3, GuiBeacon.beaconGuiTextures, 90, 220); + } + + public void drawButtonForegroundLayer(int i, int j) { + if (this.enabled) + Mouse.showCursor(EnumCursorType.HAND); + GuiBeacon.this.drawCreativeTabHoveringText(I18n.format("gui.done", new Object[0]), i, j); + } + } + + class PowerButton extends GuiBeacon.Button { + private final int field_146149_p; + private final int field_146148_q; + + public PowerButton(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5) { + super(parInt1, parInt2, parInt3, GuiContainer.inventoryBackground, + 0 + Potion.potionTypes[parInt4].getStatusIconIndex() % 8 * 18, + 198 + Potion.potionTypes[parInt4].getStatusIconIndex() / 8 * 18); + this.field_146149_p = parInt4; + this.field_146148_q = parInt5; + } + + public void drawButtonForegroundLayer(int i, int j) { + if (this.enabled) + Mouse.showCursor(EnumCursorType.HAND); + String s = I18n.format(Potion.potionTypes[this.field_146149_p].getName(), new Object[0]); + if (this.field_146148_q >= 3 && this.field_146149_p != Potion.regeneration.id) { + s = s + " II"; + } + + GuiBeacon.this.drawCreativeTabHoveringText(s, i, j); + } + } + private static final Logger logger = LogManager.getLogger(); + private static final ResourceLocation beaconGuiTextures = new ResourceLocation("textures/gui/container/beacon.png"); + private IInventory tileBeacon; + private GuiBeacon.ConfirmButton beaconConfirmButton; + private boolean buttonsNotDrawn; public GuiBeacon(InventoryPlayer playerInventory, IInventory tileBeaconIn) { @@ -56,10 +160,84 @@ public class GuiBeacon extends GuiContainer { this.ySize = 219; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == -2) { + this.mc.displayGuiScreen((GuiScreen) null); + } else if (parGuiButton.id == -1) { + String s = "MC|Beacon"; + PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); + packetbuffer.writeInt(this.tileBeacon.getField(1)); + packetbuffer.writeInt(this.tileBeacon.getField(2)); + this.mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload(s, packetbuffer)); + this.mc.displayGuiScreen((GuiScreen) null); + } else if (parGuiButton instanceof GuiBeacon.PowerButton) { + if (((GuiBeacon.PowerButton) parGuiButton).func_146141_c()) { + return; + } + + int j = parGuiButton.id; + int k = j & 255; + int i = j >> 8; + if (i < 3) { + this.tileBeacon.setField(1, k); + } else { + this.tileBeacon.setField(2, k); + } + + this.buttonList.clear(); + this.initGui(); + this.updateScreen(); + } + + } + + /** + * + Args : renderPartialTicks, mouseX, mouseY + */ + protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(beaconGuiTextures); + int i = (this.width - this.xSize) / 2; + int j = (this.height - this.ySize) / 2; + this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); + this.itemRender.zLevel = 100.0F; + this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.emerald), i + 42, j + 109); + this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.diamond), i + 42 + 22, j + 109); + this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.gold_ingot), i + 42 + 44, j + 109); + this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.iron_ingot), i + 42 + 66, j + 109); + this.itemRender.zLevel = 0.0F; + } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int i, int j) { + RenderHelper.disableStandardItemLighting(); + this.drawCenteredString(this.fontRendererObj, I18n.format("tile.beacon.primary", new Object[0]), 62, 10, + 14737632); + this.drawCenteredString(this.fontRendererObj, I18n.format("tile.beacon.secondary", new Object[0]), 169, 10, + 14737632); + + for (int k = 0, l = this.buttonList.size(); k < l; ++k) { + GuiButton guibutton = this.buttonList.get(k); + if (guibutton.isMouseOver()) { + guibutton.drawButtonForegroundLayer(i - this.guiLeft, j - this.guiTop); + break; + } + } + + RenderHelper.enableGUIStandardItemLighting(); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { super.initGui(); @@ -70,8 +248,8 @@ public class GuiBeacon extends GuiContainer { this.beaconConfirmButton.enabled = false; } - /**+ - * Called from the main game loop to update the screen. + /** + * + Called from the main game loop to update the screen. */ public void updateScreen() { super.updateScreen(); @@ -128,175 +306,4 @@ public class GuiBeacon extends GuiContainer { this.beaconConfirmButton.enabled = this.tileBeacon.getStackInSlot(0) != null && j > 0; } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == -2) { - this.mc.displayGuiScreen((GuiScreen) null); - } else if (parGuiButton.id == -1) { - String s = "MC|Beacon"; - PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); - packetbuffer.writeInt(this.tileBeacon.getField(1)); - packetbuffer.writeInt(this.tileBeacon.getField(2)); - this.mc.getNetHandler().addToSendQueue(new C17PacketCustomPayload(s, packetbuffer)); - this.mc.displayGuiScreen((GuiScreen) null); - } else if (parGuiButton instanceof GuiBeacon.PowerButton) { - if (((GuiBeacon.PowerButton) parGuiButton).func_146141_c()) { - return; - } - - int j = parGuiButton.id; - int k = j & 255; - int i = j >> 8; - if (i < 3) { - this.tileBeacon.setField(1, k); - } else { - this.tileBeacon.setField(2, k); - } - - this.buttonList.clear(); - this.initGui(); - this.updateScreen(); - } - - } - - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int i, int j) { - RenderHelper.disableStandardItemLighting(); - this.drawCenteredString(this.fontRendererObj, I18n.format("tile.beacon.primary", new Object[0]), 62, 10, - 14737632); - this.drawCenteredString(this.fontRendererObj, I18n.format("tile.beacon.secondary", new Object[0]), 169, 10, - 14737632); - - for (int k = 0, l = this.buttonList.size(); k < l; ++k) { - GuiButton guibutton = this.buttonList.get(k); - if (guibutton.isMouseOver()) { - guibutton.drawButtonForegroundLayer(i - this.guiLeft, j - this.guiTop); - break; - } - } - - RenderHelper.enableGUIStandardItemLighting(); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY - */ - protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(beaconGuiTextures); - int i = (this.width - this.xSize) / 2; - int j = (this.height - this.ySize) / 2; - this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); - this.itemRender.zLevel = 100.0F; - this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.emerald), i + 42, j + 109); - this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.diamond), i + 42 + 22, j + 109); - this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.gold_ingot), i + 42 + 44, j + 109); - this.itemRender.renderItemAndEffectIntoGUI(new ItemStack(Items.iron_ingot), i + 42 + 66, j + 109); - this.itemRender.zLevel = 0.0F; - } - - static class Button extends GuiButton { - private final ResourceLocation field_146145_o; - private final int field_146144_p; - private final int field_146143_q; - private boolean field_146142_r; - - protected Button(int parInt1, int parInt2, int parInt3, ResourceLocation parResourceLocation, int parInt4, - int parInt5) { - super(parInt1, parInt2, parInt3, 22, 22, ""); - this.field_146145_o = parResourceLocation; - this.field_146144_p = parInt4; - this.field_146143_q = parInt5; - } - - public void drawButton(Minecraft minecraft, int i, int j) { - if (this.visible) { - minecraft.getTextureManager().bindTexture(GuiBeacon.beaconGuiTextures); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.hovered = i >= this.xPosition && j >= this.yPosition && i < this.xPosition + this.width - && j < this.yPosition + this.height; - short short1 = 219; - int k = 0; - if (!this.enabled) { - k += this.width * 2; - } else if (this.field_146142_r) { - k += this.width * 1; - } else if (this.hovered) { - k += this.width * 3; - } - - this.drawTexturedModalRect(this.xPosition, this.yPosition, k, short1, this.width, this.height); - if (!GuiBeacon.beaconGuiTextures.equals(this.field_146145_o)) { - minecraft.getTextureManager().bindTexture(this.field_146145_o); - } - - this.drawTexturedModalRect(this.xPosition + 2, this.yPosition + 2, this.field_146144_p, - this.field_146143_q, 18, 18); - } - } - - public boolean func_146141_c() { - return this.field_146142_r; - } - - public void func_146140_b(boolean parFlag) { - this.field_146142_r = parFlag; - } - } - - class CancelButton extends GuiBeacon.Button { - public CancelButton(int parInt1, int parInt2, int parInt3) { - super(parInt1, parInt2, parInt3, GuiBeacon.beaconGuiTextures, 112, 220); - } - - public void drawButtonForegroundLayer(int i, int j) { - if (this.enabled) - Mouse.showCursor(EnumCursorType.HAND); - GuiBeacon.this.drawCreativeTabHoveringText(I18n.format("gui.cancel", new Object[0]), i, j); - } - } - - class ConfirmButton extends GuiBeacon.Button { - public ConfirmButton(int parInt1, int parInt2, int parInt3) { - super(parInt1, parInt2, parInt3, GuiBeacon.beaconGuiTextures, 90, 220); - } - - public void drawButtonForegroundLayer(int i, int j) { - if (this.enabled) - Mouse.showCursor(EnumCursorType.HAND); - GuiBeacon.this.drawCreativeTabHoveringText(I18n.format("gui.done", new Object[0]), i, j); - } - } - - class PowerButton extends GuiBeacon.Button { - private final int field_146149_p; - private final int field_146148_q; - - public PowerButton(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5) { - super(parInt1, parInt2, parInt3, GuiContainer.inventoryBackground, - 0 + Potion.potionTypes[parInt4].getStatusIconIndex() % 8 * 18, - 198 + Potion.potionTypes[parInt4].getStatusIconIndex() / 8 * 18); - this.field_146149_p = parInt4; - this.field_146148_q = parInt5; - } - - public void drawButtonForegroundLayer(int i, int j) { - if (this.enabled) - Mouse.showCursor(EnumCursorType.HAND); - String s = I18n.format(Potion.potionTypes[this.field_146149_p].getName(), new Object[0]); - if (this.field_146148_q >= 3 && this.field_146149_p != Potion.regeneration.id) { - s = s + " II"; - } - - GuiBeacon.this.drawCreativeTabHoveringText(s, i, j); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiBrewingStand.java b/src/game/java/net/minecraft/client/gui/inventory/GuiBrewingStand.java index c32a4912..6ac59aa4 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiBrewingStand.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiBrewingStand.java @@ -6,22 +6,25 @@ import net.minecraft.inventory.ContainerBrewingStand; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,19 +41,8 @@ public class GuiBrewingStand extends GuiContainer { this.tileBrewingStand = parIInventory; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - String s = this.tileBrewingStand.getDisplayName().getUnformattedText(); - this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); - this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -95,4 +87,15 @@ public class GuiBrewingStand extends GuiContainer { } } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + String s = this.tileBrewingStand.getDisplayName().getUnformattedText(); + this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); + this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiChest.java b/src/game/java/net/minecraft/client/gui/inventory/GuiChest.java index 0cbc13aa..303d0704 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiChest.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiChest.java @@ -6,29 +6,32 @@ import net.minecraft.inventory.ContainerChest; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiChest extends GuiContainer { - /**+ - * The ResourceLocation containing the chest GUI texture. + /** + * + The ResourceLocation containing the chest GUI texture. */ private static final ResourceLocation CHEST_GUI_TEXTURE = new ResourceLocation( "textures/gui/container/generic_54.png"); @@ -47,18 +50,8 @@ public class GuiChest extends GuiContainer { this.ySize = i + this.inventoryRows * 18; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - this.fontRendererObj.drawString(this.lowerChestInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); - this.fontRendererObj.drawString(this.upperChestInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -68,4 +61,14 @@ public class GuiChest extends GuiContainer { this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.inventoryRows * 18 + 17); this.drawTexturedModalRect(i, j + this.inventoryRows * 18 + 17, 0, 126, this.xSize, 96); } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(this.lowerChestInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); + this.fontRendererObj.drawString(this.upperChestInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiContainer.java b/src/game/java/net/minecraft/client/gui/inventory/GuiContainer.java index 674e2f8c..b7275328 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiContainer.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiContainer.java @@ -23,38 +23,41 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class GuiContainer extends GuiScreen { - /**+ - * The location of the inventory background texture + /** + * + The location of the inventory background texture */ protected static final ResourceLocation inventoryBackground = new ResourceLocation( "textures/gui/container/inventory.png"); - /**+ - * The X size of the inventory window in pixels. + /** + * + The X size of the inventory window in pixels. */ protected int xSize = 176; - /**+ - * The Y size of the inventory window in pixels. + /** + * + The Y size of the inventory window in pixels. */ protected int ySize = 166; public Container inventorySlots; @@ -83,30 +86,69 @@ public abstract class GuiContainer extends GuiScreen { private boolean doubleClick; private ItemStack shiftClickedSlot; + private int primaryTouchPoint = -1; + + private int lastTouchX = -1; + + private int lastTouchY = -1; + public GuiContainer(Container inventorySlotsIn) { this.inventorySlots = inventorySlotsIn; this.ignoreMouseUp = true; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + This function is what controls the hotbar shortcut check when you press a + * number key when hovering a stack. Args : keyCode, Returns true if a Hotbar + * key is pressed, else false */ - public void initGui() { - super.initGui(); - if (primaryTouchPoint != -1 && Touch.fetchPointIdx(primaryTouchPoint) == -1) { - primaryTouchPoint = -1; - mouseReleased(lastTouchX, lastTouchY, 0); + protected boolean checkHotbarKeys(int keyCode) { + if (this.mc.thePlayer.inventory.getItemStack() == null && this.theSlot != null) { + for (int i = 0; i < 9; ++i) { + if (keyCode == this.mc.gameSettings.keyBindsHotbar[i].getKeyCode()) { + this.handleMouseClick(this.theSlot, this.theSlot.slotNumber, i, 2); + return true; + } + } } - this.mc.thePlayer.openContainer = this.inventorySlots; - this.guiLeft = (this.width - this.xSize) / 2; - this.guiTop = (this.height - this.ySize) / 2; + + return false; } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Returns true if this GUI should pause the game when it is displayed in + * single-player + */ + public boolean doesGuiPauseGame() { + return false; + } + + protected abstract void drawGuiContainerBackgroundLayer(float var1, int var2, int var3); + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { + } + + /** + * + Render an ItemStack. Args : stack, x, y, format + */ + private void drawItemStack(ItemStack stack, int x, int y, String altText) { + GlStateManager.translate(0.0F, 0.0F, 32.0F); + this.zLevel = 200.0F; + this.itemRender.zLevel = 200.0F; + this.itemRender.renderItemAndEffectIntoGUI(stack, x, y); + this.itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, stack, x, + y - (this.draggedStack == null ? 0 : 8), altText); + this.zLevel = 0.0F; + this.itemRender.zLevel = 0.0F; + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.drawDefaultBackground(); @@ -196,29 +238,6 @@ public abstract class GuiContainer extends GuiScreen { RenderHelper.enableStandardItemLighting(); } - /**+ - * Render an ItemStack. Args : stack, x, y, format - */ - private void drawItemStack(ItemStack stack, int x, int y, String altText) { - GlStateManager.translate(0.0F, 0.0F, 32.0F); - this.zLevel = 200.0F; - this.itemRender.zLevel = 200.0F; - this.itemRender.renderItemAndEffectIntoGUI(stack, x, y); - this.itemRender.renderItemOverlayIntoGUI(this.fontRendererObj, stack, x, - y - (this.draggedStack == null ? 0 : 8), altText); - this.zLevel = 0.0F; - this.itemRender.zLevel = 0.0F; - } - - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { - } - - protected abstract void drawGuiContainerBackgroundLayer(float var1, int var2, int var3); - private void drawSlot(Slot slotIn) { int i = slotIn.xDisplayPosition; int j = slotIn.yDisplayPosition; @@ -283,32 +302,8 @@ public abstract class GuiContainer extends GuiScreen { this.zLevel = 0.0F; } - private void updateDragSplitting() { - ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); - if (itemstack != null && this.dragSplitting) { - this.dragSplittingRemnant = itemstack.stackSize; - - for (Slot slot : this.dragSplittingSlots) { - ItemStack itemstack1 = itemstack.copy(); - int i = slot.getStack() == null ? 0 : slot.getStack().stackSize; - Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack1, i); - if (itemstack1.stackSize > itemstack1.getMaxStackSize()) { - itemstack1.stackSize = itemstack1.getMaxStackSize(); - } - - if (itemstack1.stackSize > slot.getItemStackLimit(itemstack1)) { - itemstack1.stackSize = slot.getItemStackLimit(itemstack1); - } - - this.dragSplittingRemnant -= itemstack1.stackSize - i; - } - - } - } - - /**+ - * Returns the slot at the given coordinates or null if there is - * none. + /** + * + Returns the slot at the given coordinates or null if there is none. */ private Slot getSlotAtPosition(int x, int y) { for (int i = 0; i < this.inventorySlots.inventorySlots.size(); ++i) { @@ -321,9 +316,87 @@ public abstract class GuiContainer extends GuiScreen { return null; } - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + protected float getTouchModeScale() { + return 1.25f; + } + + /** + * + Called when the mouse is clicked over a slot or outside the gui. + */ + protected void handleMouseClick(Slot slotIn, int slotId, int clickedButton, int clickType) { + if (slotIn != null) { + slotId = slotIn.slotNumber; + } + + this.mc.playerController.windowClick(this.inventorySlots.windowId, slotId, clickedButton, clickType, + this.mc.thePlayer); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + super.initGui(); + if (primaryTouchPoint != -1 && Touch.fetchPointIdx(primaryTouchPoint) == -1) { + primaryTouchPoint = -1; + mouseReleased(lastTouchX, lastTouchY, 0); + } + this.mc.thePlayer.openContainer = this.inventorySlots; + this.guiLeft = (this.width - this.xSize) / 2; + this.guiTop = (this.height - this.ySize) / 2; + } + + /** + * + Returns if the passed mouse position is over the specified slot. Args : + * slot, mouseX, mouseY + */ + private boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) { + return this.isPointInRegion(slotIn.xDisplayPosition, slotIn.yDisplayPosition, 16, 16, mouseX, mouseY); + } + + /** + * + Test if the 2D point is in a rectangle (relative to the GUI). Args : rectX, + * rectY, rectWidth, rectHeight, pointX, pointY + */ + protected boolean isPointInRegion(int left, int top, int right, int bottom, int pointX, int pointY) { + int i = this.guiLeft; + int j = this.guiTop; + pointX = pointX - i; + pointY = pointY - j; + return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1; + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (parInt1 == this.mc.gameSettings.keyBindClose.getKeyCode() + || parInt1 == this.mc.gameSettings.keyBindInventory.getKeyCode() + || (parInt1 == 1 && (this.mc.gameSettings.keyBindClose.getKeyCode() == 0 || this.mc.areKeysLocked()))) { + this.mc.thePlayer.closeScreen(); + if (this.mc.currentScreen == null) { + this.mc.setIngameFocus(); + } + } else if (parInt1 == 1) { + showingCloseKey = EagRuntime.steadyTimeMillis(); + } else { + this.checkHotbarKeys(parInt1); + if (this.theSlot != null && this.theSlot.getHasStack()) { + if (parInt1 == this.mc.gameSettings.keyBindPickBlock.getKeyCode()) { + this.handleMouseClick(this.theSlot, this.theSlot.slotNumber, 0, 3); + } else if (parInt1 == this.mc.gameSettings.keyBindDrop.getKeyCode()) { + this.handleMouseClick(this.theSlot, this.theSlot.slotNumber, isCtrlKeyDown() ? 1 : 0, 4); + } + } + } + } + + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int parInt1, int parInt2, int parInt3) { super.mouseClicked(parInt1, parInt2, parInt3); @@ -399,10 +472,9 @@ public abstract class GuiContainer extends GuiScreen { this.lastClickButton = parInt3; } - /**+ - * Called when a mouse button is pressed and the mouse is moved - * around. Parameters are : mouseX, mouseY, lastButtonClicked & - * timeSinceMouseClick. + /** + * + Called when a mouse button is pressed and the mouse is moved around. + * Parameters are : mouseX, mouseY, lastButtonClicked & timeSinceMouseClick. */ protected void mouseClickMove(int i, int j, int k, long var4) { Slot slot = this.getSlotAtPosition(i, j); @@ -440,9 +512,9 @@ public abstract class GuiContainer extends GuiScreen { } - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton */ protected void mouseReleased(int i, int j, int k) { Slot slot = this.getSlotAtPosition(i, j); @@ -551,88 +623,8 @@ public abstract class GuiContainer extends GuiScreen { this.dragSplitting = false; } - /**+ - * Returns if the passed mouse position is over the specified - * slot. Args : slot, mouseX, mouseY - */ - private boolean isMouseOverSlot(Slot slotIn, int mouseX, int mouseY) { - return this.isPointInRegion(slotIn.xDisplayPosition, slotIn.yDisplayPosition, 16, 16, mouseX, mouseY); - } - - /**+ - * Test if the 2D point is in a rectangle (relative to the GUI). - * Args : rectX, rectY, rectWidth, rectHeight, pointX, pointY - */ - protected boolean isPointInRegion(int left, int top, int right, int bottom, int pointX, int pointY) { - int i = this.guiLeft; - int j = this.guiTop; - pointX = pointX - i; - pointY = pointY - j; - return pointX >= left - 1 && pointX < left + right + 1 && pointY >= top - 1 && pointY < top + bottom + 1; - } - - /**+ - * Called when the mouse is clicked over a slot or outside the - * gui. - */ - protected void handleMouseClick(Slot slotIn, int slotId, int clickedButton, int clickType) { - if (slotIn != null) { - slotId = slotIn.slotNumber; - } - - this.mc.playerController.windowClick(this.inventorySlots.windowId, slotId, clickedButton, clickType, - this.mc.thePlayer); - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (parInt1 == this.mc.gameSettings.keyBindClose.getKeyCode() - || parInt1 == this.mc.gameSettings.keyBindInventory.getKeyCode() - || (parInt1 == 1 && (this.mc.gameSettings.keyBindClose.getKeyCode() == 0 || this.mc.areKeysLocked()))) { - this.mc.thePlayer.closeScreen(); - if (this.mc.currentScreen == null) { - this.mc.setIngameFocus(); - } - } else if (parInt1 == 1) { - showingCloseKey = EagRuntime.steadyTimeMillis(); - } else { - this.checkHotbarKeys(parInt1); - if (this.theSlot != null && this.theSlot.getHasStack()) { - if (parInt1 == this.mc.gameSettings.keyBindPickBlock.getKeyCode()) { - this.handleMouseClick(this.theSlot, this.theSlot.slotNumber, 0, 3); - } else if (parInt1 == this.mc.gameSettings.keyBindDrop.getKeyCode()) { - this.handleMouseClick(this.theSlot, this.theSlot.slotNumber, isCtrlKeyDown() ? 1 : 0, 4); - } - } - } - } - - /**+ - * This function is what controls the hotbar shortcut check when - * you press a number key when hovering a stack. Args : keyCode, - * Returns true if a Hotbar key is pressed, else false - */ - protected boolean checkHotbarKeys(int keyCode) { - if (this.mc.thePlayer.inventory.getItemStack() == null && this.theSlot != null) { - for (int i = 0; i < 9; ++i) { - if (keyCode == this.mc.gameSettings.keyBindsHotbar[i].getKeyCode()) { - this.handleMouseClick(this.theSlot, this.theSlot.slotNumber, i, 2); - return true; - } - } - } - - return false; - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events */ public void onGuiClosed() { if (this.mc.thePlayer != null) { @@ -640,43 +632,16 @@ public abstract class GuiContainer extends GuiScreen { } } - /**+ - * Returns true if this GUI should pause the game when it is - * displayed in single-player - */ - public boolean doesGuiPauseGame() { + protected boolean shouldTouchGenerateMouseEvents() { return false; } - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - super.updateScreen(); - if (!this.mc.thePlayer.isEntityAlive() || this.mc.thePlayer.isDead) { - this.mc.thePlayer.closeScreen(); - return; - } - if (primaryTouchPoint != -1 && Touch.fetchPointIdx(primaryTouchPoint) == -1) { + protected void touchEndMove(int touchX, int touchY, int uid) { + if (primaryTouchPoint == uid) { primaryTouchPoint = -1; - mouseReleased(lastTouchX, lastTouchY, 0); - } - } - - protected float getTouchModeScale() { - return 1.25f; - } - - private int primaryTouchPoint = -1; - private int lastTouchX = -1; - private int lastTouchY = -1; - - protected void touchStarted(int touchX, int touchY, int uid) { - if (primaryTouchPoint == -1) { - primaryTouchPoint = uid; lastTouchX = touchX; lastTouchY = touchY; - mouseClicked(touchX, touchY, 0); + mouseReleased(touchX, touchY, 0); } } @@ -688,12 +653,12 @@ public abstract class GuiContainer extends GuiScreen { } } - protected void touchEndMove(int touchX, int touchY, int uid) { - if (primaryTouchPoint == uid) { - primaryTouchPoint = -1; + protected void touchStarted(int touchX, int touchY, int uid) { + if (primaryTouchPoint == -1) { + primaryTouchPoint = uid; lastTouchX = touchX; lastTouchY = touchY; - mouseReleased(touchX, touchY, 0); + mouseClicked(touchX, touchY, 0); } } @@ -706,7 +671,41 @@ public abstract class GuiContainer extends GuiScreen { } } - protected boolean shouldTouchGenerateMouseEvents() { - return false; + private void updateDragSplitting() { + ItemStack itemstack = this.mc.thePlayer.inventory.getItemStack(); + if (itemstack != null && this.dragSplitting) { + this.dragSplittingRemnant = itemstack.stackSize; + + for (Slot slot : this.dragSplittingSlots) { + ItemStack itemstack1 = itemstack.copy(); + int i = slot.getStack() == null ? 0 : slot.getStack().stackSize; + Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack1, i); + if (itemstack1.stackSize > itemstack1.getMaxStackSize()) { + itemstack1.stackSize = itemstack1.getMaxStackSize(); + } + + if (itemstack1.stackSize > slot.getItemStackLimit(itemstack1)) { + itemstack1.stackSize = slot.getItemStackLimit(itemstack1); + } + + this.dragSplittingRemnant -= itemstack1.stackSize - i; + } + + } + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + super.updateScreen(); + if (!this.mc.thePlayer.isEntityAlive() || this.mc.thePlayer.isDead) { + this.mc.thePlayer.closeScreen(); + return; + } + if (primaryTouchPoint != -1 && Touch.fetchPointIdx(primaryTouchPoint) == -1) { + primaryTouchPoint = -1; + mouseReleased(lastTouchX, lastTouchY, 0); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiContainerCreative.java b/src/game/java/net/minecraft/client/gui/inventory/GuiContainerCreative.java index 9fcef1c9..f7cad2aa 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiContainerCreative.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiContainerCreative.java @@ -37,35 +37,164 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiContainerCreative extends InventoryEffectRenderer { - /**+ - * The location of the creative inventory tabs texture + static class ContainerCreative extends Container { + public List itemList = Lists.newArrayList(); + + public ContainerCreative(EntityPlayer parEntityPlayer) { + InventoryPlayer inventoryplayer = parEntityPlayer.inventory; + + for (int i = 0; i < 5; ++i) { + for (int j = 0; j < 9; ++j) { + this.addSlotToContainer( + new Slot(GuiContainerCreative.field_147060_v, i * 9 + j, 9 + j * 18, 18 + i * 18)); + } + } + + for (int k = 0; k < 9; ++k) { + this.addSlotToContainer(new Slot(inventoryplayer, k, 9 + k * 18, 112)); + } + + this.scrollTo(0.0F); + } + + public boolean canDragIntoSlot(Slot parSlot) { + return parSlot.inventory instanceof InventoryPlayer + || parSlot.yDisplayPosition > 90 && parSlot.xDisplayPosition <= 162; + } + + public boolean canInteractWith(EntityPlayer playerIn) { + return true; + } + + public boolean canMergeSlot(ItemStack stack, Slot parSlot) { + return parSlot.yDisplayPosition > 90; + } + + public boolean func_148328_e() { + return this.itemList.size() > 45; + } + + protected void retrySlotClick(int slotId, int clickedButton, boolean mode, EntityPlayer playerIn) { + } + + public void scrollTo(float parFloat1) { + int i = (this.itemList.size() + 9 - 1) / 9 - 5; + int j = (int) ((double) (parFloat1 * (float) i) + 0.5D); + if (j < 0) { + j = 0; + } + + for (int k = 0; k < 5; ++k) { + for (int l = 0; l < 9; ++l) { + int i1 = l + (k + j) * 9; + if (i1 >= 0 && i1 < this.itemList.size()) { + GuiContainerCreative.field_147060_v.setInventorySlotContents(l + k * 9, + (ItemStack) this.itemList.get(i1)); + } else { + GuiContainerCreative.field_147060_v.setInventorySlotContents(l + k * 9, (ItemStack) null); + } + } + } + + } + + public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { + if (index >= this.inventorySlots.size() - 9 && index < this.inventorySlots.size()) { + Slot slot = (Slot) this.inventorySlots.get(index); + if (slot != null && slot.getHasStack()) { + slot.putStack((ItemStack) null); + } + } + + return null; + } + } + + class CreativeSlot extends Slot { + private final Slot slot; + + public CreativeSlot(Slot parSlot, int parInt1) { + super(parSlot.inventory, parInt1, 0, 0); + this.slot = parSlot; + } + + public ItemStack decrStackSize(int amount) { + return this.slot.decrStackSize(amount); + } + + public boolean getHasStack() { + return this.slot.getHasStack(); + } + + public int getItemStackLimit(ItemStack stack) { + return this.slot.getItemStackLimit(stack); + } + + public int getSlotStackLimit() { + return this.slot.getSlotStackLimit(); + } + + public String getSlotTexture() { + return this.slot.getSlotTexture(); + } + + public ItemStack getStack() { + return this.slot.getStack(); + } + + public boolean isHere(IInventory inv, int slotIn) { + return this.slot.isHere(inv, slotIn); + } + + public boolean isItemValid(ItemStack stack) { + return this.slot.isItemValid(stack); + } + + public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) { + this.slot.onPickupFromSlot(playerIn, stack); + } + + public void onSlotChanged() { + this.slot.onSlotChanged(); + } + + public void putStack(ItemStack stack) { + this.slot.putStack(stack); + } + } + + /** + * + The location of the creative inventory tabs texture */ private static final ResourceLocation creativeInventoryTabs = new ResourceLocation( "textures/gui/container/creative_inventory/tabs.png"); private static InventoryBasic field_147060_v = new InventoryBasic("tmp", true, 45); - /**+ - * Currently selected creative inventory tab index. + /** + * + Currently selected creative inventory tab index. */ private static int selectedTabIndex = CreativeTabs.tabBlock.getTabIndex(); private float currentScroll; @@ -74,7 +203,9 @@ public class GuiContainerCreative extends InventoryEffectRenderer { private GuiTextField searchField; private List field_147063_B; private Slot field_147064_C; + private boolean field_147057_D; + private CreativeCrafting field_147059_E; public GuiContainerCreative(EntityPlayer parEntityPlayer) { @@ -85,20 +216,200 @@ public class GuiContainerCreative extends InventoryEffectRenderer { this.xSize = 195; } - /**+ - * Called from the main game loop to update the screen. + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ - public void updateScreen() { - if (!this.mc.playerController.isInCreativeMode()) { - this.mc.displayGuiScreen(new GuiInventory(this.mc.thePlayer)); + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + this.mc.displayGuiScreen(new GuiAchievements(this, this.mc.thePlayer.getStatFileWriter())); + } + + if (parGuiButton.id == 1) { + this.mc.displayGuiScreen(new GuiStats(this, this.mc.thePlayer.getStatFileWriter())); } - this.updateActivePotionEffects(); } - /**+ - * Called when the mouse is clicked over a slot or outside the - * gui. + public boolean blockPTTKey() { + return searchField.isFocused(); + } + + /** + * + Args : renderPartialTicks, mouseX, mouseY + */ + protected void drawGuiContainerBackgroundLayer(float var1, int i, int j) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + RenderHelper.enableGUIStandardItemLighting(); + CreativeTabs creativetabs = CreativeTabs.creativeTabArray[selectedTabIndex]; + + for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { + CreativeTabs creativetabs1 = CreativeTabs.creativeTabArray[m]; + this.mc.getTextureManager().bindTexture(creativeInventoryTabs); + if (creativetabs1.getTabIndex() != selectedTabIndex) { + this.func_147051_a(creativetabs1); + } + } + + this.mc.getTextureManager().bindTexture(new ResourceLocation( + "textures/gui/container/creative_inventory/tab_" + creativetabs.getBackgroundImageName())); + this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); + this.searchField.drawTextBox(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + int k = this.guiLeft + 175; + int l = this.guiTop + 18; + int i1 = l + 112; + this.mc.getTextureManager().bindTexture(creativeInventoryTabs); + if (creativetabs.shouldHidePlayerInventory()) { + this.drawTexturedModalRect(k, l + (int) ((float) (i1 - l - 17) * this.currentScroll), + 232 + (this.needsScrollBars() ? 0 : 12), 0, 12, 15); + } + + this.func_147051_a(creativetabs); + if (creativetabs == CreativeTabs.tabInventory) { + GuiInventory.drawEntityOnScreen(this.guiLeft + 43, this.guiTop + 45, 20, (float) (this.guiLeft + 43 - i), + (float) (this.guiTop + 45 - 30 - j), this.mc.thePlayer); + } + + } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + CreativeTabs creativetabs = CreativeTabs.creativeTabArray[selectedTabIndex]; + if (creativetabs.drawInForegroundOfTab()) { + GlStateManager.disableBlend(); + this.fontRendererObj.drawString(I18n.format(creativetabs.getTranslatedTabLabel(), new Object[0]), 8, 6, + 4210752); + } + + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + boolean flag = PointerInputAbstraction.getVCursorButtonDown(0); + int k = this.guiLeft; + int l = this.guiTop; + int i1 = k + 175; + int j1 = l + 18; + int k1 = i1 + 14; + int l1 = j1 + 112; + if (!this.wasClicking && flag && i >= i1 && j >= j1 && i < k1 && j < l1) { + this.isScrolling = this.needsScrollBars(); + } + + if (!flag) { + this.isScrolling = false; + } + + this.wasClicking = flag; + if (this.isScrolling) { + this.currentScroll = ((float) (j - j1) - 7.5F) / ((float) (l1 - j1) - 15.0F); + this.currentScroll = MathHelper.clamp_float(this.currentScroll, 0.0F, 1.0F); + ((GuiContainerCreative.ContainerCreative) this.inventorySlots).scrollTo(this.currentScroll); + } + + super.drawScreen(i, j, f); + + for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { + if (this.renderCreativeInventoryHoveringText(CreativeTabs.creativeTabArray[m], i, j)) { + Mouse.showCursor(EnumCursorType.HAND); + break; + } + } + + if (this.field_147064_C != null && selectedTabIndex == CreativeTabs.tabInventory.getTabIndex() + && this.isPointInRegion(this.field_147064_C.xDisplayPosition, this.field_147064_C.yDisplayPosition, 16, + 16, i, j)) { + this.drawCreativeTabHoveringText(I18n.format("inventory.binSlot", new Object[0]), i, j); + } + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableLighting(); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + searchField.fireInputEvent(event, param); + } + + protected boolean func_147049_a(CreativeTabs parCreativeTabs, int parInt1, int parInt2) { + int i = parCreativeTabs.getTabColumn(); + int j = 28 * i; + int k = 0; + if (i == 5) { + j = this.xSize - 28 + 2; + } else if (i > 0) { + j += i; + } + + if (parCreativeTabs.isTabInFirstRow()) { + k = k - 32; + } else { + k = k + this.ySize; + } + + return parInt1 >= j && parInt1 <= j + 28 && parInt2 >= k && parInt2 <= k + 32; + } + + protected void func_147051_a(CreativeTabs parCreativeTabs) { + boolean flag = parCreativeTabs.getTabIndex() == selectedTabIndex; + boolean flag1 = parCreativeTabs.isTabInFirstRow(); + int i = parCreativeTabs.getTabColumn(); + int j = i * 28; + int k = 0; + int l = this.guiLeft + 28 * i; + int i1 = this.guiTop; + byte b0 = 32; + if (flag) { + k += 32; + } + + if (i == 5) { + l = this.guiLeft + this.xSize - 28; + } else if (i > 0) { + l += i; + } + + if (flag1) { + i1 = i1 - 28; + } else { + k += 64; + i1 = i1 + (this.ySize - 4); + } + + GlStateManager.disableLighting(); + this.drawTexturedModalRect(l, i1, j, k, 28, b0); + this.zLevel = 100.0F; + this.itemRender.zLevel = 100.0F; + l = l + 6; + i1 = i1 + 8 + (flag1 ? 1 : -1); + GlStateManager.enableLighting(); + GlStateManager.enableRescaleNormal(); + ItemStack itemstack = parCreativeTabs.getIconItemStack(); + this.itemRender.renderItemAndEffectIntoGUI(itemstack, l, i1); + this.itemRender.renderItemOverlays(this.fontRendererObj, itemstack, l, i1); + GlStateManager.disableLighting(); + this.itemRender.zLevel = 0.0F; + this.zLevel = 0.0F; + } + + protected int getCloseKey() { + return selectedTabIndex != CreativeTabs.tabAllSearch.getTabIndex() ? super.getCloseKey() + : mc.gameSettings.keyBindClose.getKeyCode(); + } + + public int getSelectedTabIndex() { + return selectedTabIndex; + } + + /** + * + Called when the mouse is clicked over a slot or outside the gui. */ protected void handleMouseClick(Slot slot, int i, int j, int k) { this.field_147057_D = true; @@ -215,19 +526,33 @@ public class GuiContainerCreative extends InventoryEffectRenderer { } - protected void updateActivePotionEffects() { - int i = this.guiLeft; - super.updateActivePotionEffects(); - if (this.searchField != null && this.guiLeft != i) { - this.searchField.xPosition = this.guiLeft + 82; + /** + * + Handles mouse input. + */ + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + int i = Mouse.getEventDWheel(); + if (i != 0 && this.needsScrollBars()) { + int j = ((GuiContainerCreative.ContainerCreative) this.inventorySlots).itemList.size() / 9 - 5; + if (i > 0) { + i = 1; + } + + if (i < 0) { + i = -1; + } + + this.currentScroll = (float) ((double) this.currentScroll - (double) i / (double) j); + this.currentScroll = MathHelper.clamp_float(this.currentScroll, 0.0F, 1.0F); + ((GuiContainerCreative.ContainerCreative) this.inventorySlots).scrollTo(this.currentScroll); } } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. */ public void initGui() { if (this.mc.playerController.isInCreativeMode()) { @@ -251,24 +576,10 @@ public class GuiContainerCreative extends InventoryEffectRenderer { } - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - super.onGuiClosed(); - if (this.mc.thePlayer != null && this.mc.thePlayer.inventory != null) { - this.mc.thePlayer.inventoryContainer.removeCraftingFromCrafters(this.field_147059_E); - } - - Keyboard.enableRepeatEvents(false); - } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) */ protected void keyTyped(char parChar1, int parInt1) { if (selectedTabIndex != CreativeTabs.tabAllSearch.getTabIndex()) { @@ -297,69 +608,8 @@ public class GuiContainerCreative extends InventoryEffectRenderer { } } - protected int getCloseKey() { - return selectedTabIndex != CreativeTabs.tabAllSearch.getTabIndex() ? super.getCloseKey() - : mc.gameSettings.keyBindClose.getKeyCode(); - } - - private void updateCreativeSearch() { - GuiContainerCreative.ContainerCreative guicontainercreative$containercreative = (GuiContainerCreative.ContainerCreative) this.inventorySlots; - guicontainercreative$containercreative.itemList.clear(); - - for (Item item : Item.itemRegistry) { - if (item != null && item.getCreativeTab() != null) { - item.getSubItems(item, (CreativeTabs) null, guicontainercreative$containercreative.itemList); - } - } - - for (int i = 0; i < Enchantment.enchantmentsBookList.length; ++i) { - Enchantment enchantment = Enchantment.enchantmentsBookList[i]; - if (enchantment != null && enchantment.type != null) { - Items.enchanted_book.getAll(enchantment, guicontainercreative$containercreative.itemList); - } - } - - Iterator iterator = guicontainercreative$containercreative.itemList.iterator(); - String s1 = this.searchField.getText().toLowerCase(); - - while (iterator.hasNext()) { - ItemStack itemstack = (ItemStack) iterator.next(); - boolean flag = false; - - List lst = itemstack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); - for (int i = 0, l = lst.size(); i < l; ++i) { - if (EnumChatFormatting.getTextWithoutFormattingCodes(lst.get(i)).toLowerCase().contains(s1)) { - flag = true; - break; - } - } - - if (!flag) { - iterator.remove(); - } - } - - this.currentScroll = 0.0F; - guicontainercreative$containercreative.scrollTo(0.0F); - } - - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - CreativeTabs creativetabs = CreativeTabs.creativeTabArray[selectedTabIndex]; - if (creativetabs.drawInForegroundOfTab()) { - GlStateManager.disableBlend(); - this.fontRendererObj.drawString(I18n.format(creativetabs.getTranslatedTabLabel(), new Object[0]), 8, 6, - 4210752); - } - - } - - /**+ - * Called when the mouse is clicked. Args : mouseX, mouseY, - * clickedButton + /** + * + Called when the mouse is clicked. Args : mouseX, mouseY, clickedButton */ protected void mouseClicked(int parInt1, int parInt2, int parInt3) { if (parInt3 == 0) { @@ -376,9 +626,9 @@ public class GuiContainerCreative extends InventoryEffectRenderer { super.mouseClicked(parInt1, parInt2, parInt3); } - /**+ - * Called when a mouse button is released. Args : mouseX, - * mouseY, releaseButton + /** + * + Called when a mouse button is released. Args : mouseX, mouseY, + * releaseButton */ protected void mouseReleased(int i, int j, int k) { if (k == 0) { @@ -397,25 +647,9 @@ public class GuiContainerCreative extends InventoryEffectRenderer { super.mouseReleased(i, j, k); } - @Override - protected void touchTapped(int touchX, int touchY, int uid) { - int l = touchX - this.guiLeft; - int i1 = touchY - this.guiTop; - - for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { - CreativeTabs creativetabs = CreativeTabs.creativeTabArray[m]; - if (this.func_147049_a(creativetabs, l, i1)) { - this.setCurrentCreativeTab(creativetabs); - break; - } - } - - super.touchTapped(touchX, touchY, uid); - } - - /**+ - * returns (if you are not on the inventoryTab) and (the flag - * isn't set) and (you have more than 1 page of items) + /** + * + returns (if you are not on the inventoryTab) and (the flag isn't set) and + * (you have more than 1 page of items) */ private boolean needsScrollBars() { return selectedTabIndex != CreativeTabs.tabInventory.getTabIndex() @@ -423,6 +657,89 @@ public class GuiContainerCreative extends InventoryEffectRenderer { && ((GuiContainerCreative.ContainerCreative) this.inventorySlots).func_148328_e(); } + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + super.onGuiClosed(); + if (this.mc.thePlayer != null && this.mc.thePlayer.inventory != null) { + this.mc.thePlayer.inventoryContainer.removeCraftingFromCrafters(this.field_147059_E); + } + + Keyboard.enableRepeatEvents(false); + } + + /** + * + Renders the creative inventory hovering text if mouse is over it. Returns + * true if did render or false otherwise. Params: current creative tab to be + * checked, current mouse x position, current mouse y position. + */ + protected boolean renderCreativeInventoryHoveringText(CreativeTabs parCreativeTabs, int parInt1, int parInt2) { + int i = parCreativeTabs.getTabColumn(); + int j = 28 * i; + int k = 0; + if (i == 5) { + j = this.xSize - 28 + 2; + } else if (i > 0) { + j += i; + } + + if (parCreativeTabs.isTabInFirstRow()) { + k = k - 32; + } else { + k = k + this.ySize; + } + + if (this.isPointInRegion(j + 3, k + 3, 23, 27, parInt1, parInt2)) { + this.drawCreativeTabHoveringText(I18n.format(parCreativeTabs.getTranslatedTabLabel(), new Object[0]), + parInt1, parInt2); + return true; + } else { + return false; + } + } + + protected void renderToolTip(ItemStack itemstack, int i, int j) { + if (selectedTabIndex == CreativeTabs.tabAllSearch.getTabIndex()) { + List list = itemstack.getTooltipProfanityFilter(this.mc.thePlayer, + this.mc.gameSettings.advancedItemTooltips); + CreativeTabs creativetabs = itemstack.getItem().getCreativeTab(); + if (creativetabs == null && itemstack.getItem() == Items.enchanted_book) { + Map map = EnchantmentHelper.getEnchantments(itemstack); + if (map.size() == 1) { + Enchantment enchantment = Enchantment + .getEnchantmentById(((Integer) map.keySet().iterator().next()).intValue()); + + for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { + CreativeTabs creativetabs1 = CreativeTabs.creativeTabArray[m]; + if (creativetabs1.hasRelevantEnchantmentType(enchantment.type)) { + creativetabs = creativetabs1; + break; + } + } + } + } + + if (creativetabs != null) { + list.add(1, "" + EnumChatFormatting.BOLD + EnumChatFormatting.BLUE + + I18n.format(creativetabs.getTranslatedTabLabel(), new Object[0])); + } + + for (int k = 0; k < list.size(); ++k) { + if (k == 0) { + list.set(k, itemstack.getRarity().rarityColor + (String) list.get(k)); + } else { + list.set(k, EnumChatFormatting.GRAY + (String) list.get(k)); + } + } + + this.drawHoveringText(list, i, j); + } else { + super.renderToolTip(itemstack, i, j); + } + + } + private void setCurrentCreativeTab(CreativeTabs parCreativeTabs) { int i = selectedTabIndex; selectedTabIndex = parCreativeTabs.getTabIndex(); @@ -489,403 +806,86 @@ public class GuiContainerCreative extends InventoryEffectRenderer { guicontainercreative$containercreative.scrollTo(0.0F); } - /**+ - * Handles mouse input. - */ - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - int i = Mouse.getEventDWheel(); - if (i != 0 && this.needsScrollBars()) { - int j = ((GuiContainerCreative.ContainerCreative) this.inventorySlots).itemList.size() / 9 - 5; - if (i > 0) { - i = 1; - } - - if (i < 0) { - i = -1; - } - - this.currentScroll = (float) ((double) this.currentScroll - (double) i / (double) j); - this.currentScroll = MathHelper.clamp_float(this.currentScroll, 0.0F, 1.0F); - ((GuiContainerCreative.ContainerCreative) this.inventorySlots).scrollTo(this.currentScroll); - } - - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - boolean flag = PointerInputAbstraction.getVCursorButtonDown(0); - int k = this.guiLeft; - int l = this.guiTop; - int i1 = k + 175; - int j1 = l + 18; - int k1 = i1 + 14; - int l1 = j1 + 112; - if (!this.wasClicking && flag && i >= i1 && j >= j1 && i < k1 && j < l1) { - this.isScrolling = this.needsScrollBars(); - } - - if (!flag) { - this.isScrolling = false; - } - - this.wasClicking = flag; - if (this.isScrolling) { - this.currentScroll = ((float) (j - j1) - 7.5F) / ((float) (l1 - j1) - 15.0F); - this.currentScroll = MathHelper.clamp_float(this.currentScroll, 0.0F, 1.0F); - ((GuiContainerCreative.ContainerCreative) this.inventorySlots).scrollTo(this.currentScroll); - } - - super.drawScreen(i, j, f); - - for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { - if (this.renderCreativeInventoryHoveringText(CreativeTabs.creativeTabArray[m], i, j)) { - Mouse.showCursor(EnumCursorType.HAND); - break; - } - } - - if (this.field_147064_C != null && selectedTabIndex == CreativeTabs.tabInventory.getTabIndex() - && this.isPointInRegion(this.field_147064_C.xDisplayPosition, this.field_147064_C.yDisplayPosition, 16, - 16, i, j)) { - this.drawCreativeTabHoveringText(I18n.format("inventory.binSlot", new Object[0]), i, j); - } - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableLighting(); - } - - protected void renderToolTip(ItemStack itemstack, int i, int j) { - if (selectedTabIndex == CreativeTabs.tabAllSearch.getTabIndex()) { - List list = itemstack.getTooltipProfanityFilter(this.mc.thePlayer, - this.mc.gameSettings.advancedItemTooltips); - CreativeTabs creativetabs = itemstack.getItem().getCreativeTab(); - if (creativetabs == null && itemstack.getItem() == Items.enchanted_book) { - Map map = EnchantmentHelper.getEnchantments(itemstack); - if (map.size() == 1) { - Enchantment enchantment = Enchantment - .getEnchantmentById(((Integer) map.keySet().iterator().next()).intValue()); - - for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { - CreativeTabs creativetabs1 = CreativeTabs.creativeTabArray[m]; - if (creativetabs1.hasRelevantEnchantmentType(enchantment.type)) { - creativetabs = creativetabs1; - break; - } - } - } - } - - if (creativetabs != null) { - list.add(1, "" + EnumChatFormatting.BOLD + EnumChatFormatting.BLUE - + I18n.format(creativetabs.getTranslatedTabLabel(), new Object[0])); - } - - for (int k = 0; k < list.size(); ++k) { - if (k == 0) { - list.set(k, itemstack.getRarity().rarityColor + (String) list.get(k)); - } else { - list.set(k, EnumChatFormatting.GRAY + (String) list.get(k)); - } - } - - this.drawHoveringText(list, i, j); - } else { - super.renderToolTip(itemstack, i, j); - } - - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY - */ - protected void drawGuiContainerBackgroundLayer(float var1, int i, int j) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - RenderHelper.enableGUIStandardItemLighting(); - CreativeTabs creativetabs = CreativeTabs.creativeTabArray[selectedTabIndex]; - - for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { - CreativeTabs creativetabs1 = CreativeTabs.creativeTabArray[m]; - this.mc.getTextureManager().bindTexture(creativeInventoryTabs); - if (creativetabs1.getTabIndex() != selectedTabIndex) { - this.func_147051_a(creativetabs1); - } - } - - this.mc.getTextureManager().bindTexture(new ResourceLocation( - "textures/gui/container/creative_inventory/tab_" + creativetabs.getBackgroundImageName())); - this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize); - this.searchField.drawTextBox(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - int k = this.guiLeft + 175; - int l = this.guiTop + 18; - int i1 = l + 112; - this.mc.getTextureManager().bindTexture(creativeInventoryTabs); - if (creativetabs.shouldHidePlayerInventory()) { - this.drawTexturedModalRect(k, l + (int) ((float) (i1 - l - 17) * this.currentScroll), - 232 + (this.needsScrollBars() ? 0 : 12), 0, 12, 15); - } - - this.func_147051_a(creativetabs); - if (creativetabs == CreativeTabs.tabInventory) { - GuiInventory.drawEntityOnScreen(this.guiLeft + 43, this.guiTop + 45, 20, (float) (this.guiLeft + 43 - i), - (float) (this.guiTop + 45 - 30 - j), this.mc.thePlayer); - } - - } - - protected boolean func_147049_a(CreativeTabs parCreativeTabs, int parInt1, int parInt2) { - int i = parCreativeTabs.getTabColumn(); - int j = 28 * i; - int k = 0; - if (i == 5) { - j = this.xSize - 28 + 2; - } else if (i > 0) { - j += i; - } - - if (parCreativeTabs.isTabInFirstRow()) { - k = k - 32; - } else { - k = k + this.ySize; - } - - return parInt1 >= j && parInt1 <= j + 28 && parInt2 >= k && parInt2 <= k + 32; - } - - /**+ - * Renders the creative inventory hovering text if mouse is over - * it. Returns true if did render or false otherwise. Params: - * current creative tab to be checked, current mouse x position, - * current mouse y position. - */ - protected boolean renderCreativeInventoryHoveringText(CreativeTabs parCreativeTabs, int parInt1, int parInt2) { - int i = parCreativeTabs.getTabColumn(); - int j = 28 * i; - int k = 0; - if (i == 5) { - j = this.xSize - 28 + 2; - } else if (i > 0) { - j += i; - } - - if (parCreativeTabs.isTabInFirstRow()) { - k = k - 32; - } else { - k = k + this.ySize; - } - - if (this.isPointInRegion(j + 3, k + 3, 23, 27, parInt1, parInt2)) { - this.drawCreativeTabHoveringText(I18n.format(parCreativeTabs.getTranslatedTabLabel(), new Object[0]), - parInt1, parInt2); - return true; - } else { - return false; - } - } - - protected void func_147051_a(CreativeTabs parCreativeTabs) { - boolean flag = parCreativeTabs.getTabIndex() == selectedTabIndex; - boolean flag1 = parCreativeTabs.isTabInFirstRow(); - int i = parCreativeTabs.getTabColumn(); - int j = i * 28; - int k = 0; - int l = this.guiLeft + 28 * i; - int i1 = this.guiTop; - byte b0 = 32; - if (flag) { - k += 32; - } - - if (i == 5) { - l = this.guiLeft + this.xSize - 28; - } else if (i > 0) { - l += i; - } - - if (flag1) { - i1 = i1 - 28; - } else { - k += 64; - i1 = i1 + (this.ySize - 4); - } - - GlStateManager.disableLighting(); - this.drawTexturedModalRect(l, i1, j, k, 28, b0); - this.zLevel = 100.0F; - this.itemRender.zLevel = 100.0F; - l = l + 6; - i1 = i1 + 8 + (flag1 ? 1 : -1); - GlStateManager.enableLighting(); - GlStateManager.enableRescaleNormal(); - ItemStack itemstack = parCreativeTabs.getIconItemStack(); - this.itemRender.renderItemAndEffectIntoGUI(itemstack, l, i1); - this.itemRender.renderItemOverlays(this.fontRendererObj, itemstack, l, i1); - GlStateManager.disableLighting(); - this.itemRender.zLevel = 0.0F; - this.zLevel = 0.0F; - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == 0) { - this.mc.displayGuiScreen(new GuiAchievements(this, this.mc.thePlayer.getStatFileWriter())); - } - - if (parGuiButton.id == 1) { - this.mc.displayGuiScreen(new GuiStats(this, this.mc.thePlayer.getStatFileWriter())); - } - - } - - public int getSelectedTabIndex() { - return selectedTabIndex; - } - - static class ContainerCreative extends Container { - public List itemList = Lists.newArrayList(); - - public ContainerCreative(EntityPlayer parEntityPlayer) { - InventoryPlayer inventoryplayer = parEntityPlayer.inventory; - - for (int i = 0; i < 5; ++i) { - for (int j = 0; j < 9; ++j) { - this.addSlotToContainer( - new Slot(GuiContainerCreative.field_147060_v, i * 9 + j, 9 + j * 18, 18 + i * 18)); - } - } - - for (int k = 0; k < 9; ++k) { - this.addSlotToContainer(new Slot(inventoryplayer, k, 9 + k * 18, 112)); - } - - this.scrollTo(0.0F); - } - - public boolean canInteractWith(EntityPlayer playerIn) { - return true; - } - - public void scrollTo(float parFloat1) { - int i = (this.itemList.size() + 9 - 1) / 9 - 5; - int j = (int) ((double) (parFloat1 * (float) i) + 0.5D); - if (j < 0) { - j = 0; - } - - for (int k = 0; k < 5; ++k) { - for (int l = 0; l < 9; ++l) { - int i1 = l + (k + j) * 9; - if (i1 >= 0 && i1 < this.itemList.size()) { - GuiContainerCreative.field_147060_v.setInventorySlotContents(l + k * 9, - (ItemStack) this.itemList.get(i1)); - } else { - GuiContainerCreative.field_147060_v.setInventorySlotContents(l + k * 9, (ItemStack) null); - } - } - } - - } - - public boolean func_148328_e() { - return this.itemList.size() > 45; - } - - protected void retrySlotClick(int slotId, int clickedButton, boolean mode, EntityPlayer playerIn) { - } - - public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) { - if (index >= this.inventorySlots.size() - 9 && index < this.inventorySlots.size()) { - Slot slot = (Slot) this.inventorySlots.get(index); - if (slot != null && slot.getHasStack()) { - slot.putStack((ItemStack) null); - } - } - - return null; - } - - public boolean canMergeSlot(ItemStack stack, Slot parSlot) { - return parSlot.yDisplayPosition > 90; - } - - public boolean canDragIntoSlot(Slot parSlot) { - return parSlot.inventory instanceof InventoryPlayer - || parSlot.yDisplayPosition > 90 && parSlot.xDisplayPosition <= 162; - } - } - - class CreativeSlot extends Slot { - private final Slot slot; - - public CreativeSlot(Slot parSlot, int parInt1) { - super(parSlot.inventory, parInt1, 0, 0); - this.slot = parSlot; - } - - public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) { - this.slot.onPickupFromSlot(playerIn, stack); - } - - public boolean isItemValid(ItemStack stack) { - return this.slot.isItemValid(stack); - } - - public ItemStack getStack() { - return this.slot.getStack(); - } - - public boolean getHasStack() { - return this.slot.getHasStack(); - } - - public void putStack(ItemStack stack) { - this.slot.putStack(stack); - } - - public void onSlotChanged() { - this.slot.onSlotChanged(); - } - - public int getSlotStackLimit() { - return this.slot.getSlotStackLimit(); - } - - public int getItemStackLimit(ItemStack stack) { - return this.slot.getItemStackLimit(stack); - } - - public String getSlotTexture() { - return this.slot.getSlotTexture(); - } - - public ItemStack decrStackSize(int amount) { - return this.slot.decrStackSize(amount); - } - - public boolean isHere(IInventory inv, int slotIn) { - return this.slot.isHere(inv, slotIn); - } - } - - public boolean blockPTTKey() { - return searchField.isFocused(); - } - @Override public boolean showCopyPasteButtons() { return searchField.isFocused(); } @Override - public void fireInputEvent(EnumInputEvent event, String param) { - searchField.fireInputEvent(event, param); + protected void touchTapped(int touchX, int touchY, int uid) { + int l = touchX - this.guiLeft; + int i1 = touchY - this.guiTop; + + for (int m = 0; m < CreativeTabs.creativeTabArray.length; ++m) { + CreativeTabs creativetabs = CreativeTabs.creativeTabArray[m]; + if (this.func_147049_a(creativetabs, l, i1)) { + this.setCurrentCreativeTab(creativetabs); + break; + } + } + + super.touchTapped(touchX, touchY, uid); + } + + protected void updateActivePotionEffects() { + int i = this.guiLeft; + super.updateActivePotionEffects(); + if (this.searchField != null && this.guiLeft != i) { + this.searchField.xPosition = this.guiLeft + 82; + } + + } + + private void updateCreativeSearch() { + GuiContainerCreative.ContainerCreative guicontainercreative$containercreative = (GuiContainerCreative.ContainerCreative) this.inventorySlots; + guicontainercreative$containercreative.itemList.clear(); + + for (Item item : Item.itemRegistry) { + if (item != null && item.getCreativeTab() != null) { + item.getSubItems(item, (CreativeTabs) null, guicontainercreative$containercreative.itemList); + } + } + + for (int i = 0; i < Enchantment.enchantmentsBookList.length; ++i) { + Enchantment enchantment = Enchantment.enchantmentsBookList[i]; + if (enchantment != null && enchantment.type != null) { + Items.enchanted_book.getAll(enchantment, guicontainercreative$containercreative.itemList); + } + } + + Iterator iterator = guicontainercreative$containercreative.itemList.iterator(); + String s1 = this.searchField.getText().toLowerCase(); + + while (iterator.hasNext()) { + ItemStack itemstack = (ItemStack) iterator.next(); + boolean flag = false; + + List lst = itemstack.getTooltip(this.mc.thePlayer, this.mc.gameSettings.advancedItemTooltips); + for (int i = 0, l = lst.size(); i < l; ++i) { + if (EnumChatFormatting.getTextWithoutFormattingCodes(lst.get(i)).toLowerCase().contains(s1)) { + flag = true; + break; + } + } + + if (!flag) { + iterator.remove(); + } + } + + this.currentScroll = 0.0F; + guicontainercreative$containercreative.scrollTo(0.0F); + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + if (!this.mc.playerController.isInCreativeMode()) { + this.mc.displayGuiScreen(new GuiInventory(this.mc.thePlayer)); + } + + this.updateActivePotionEffects(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiCrafting.java b/src/game/java/net/minecraft/client/gui/inventory/GuiCrafting.java index adafe9c2..2265fde6 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiCrafting.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiCrafting.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,18 +43,8 @@ public class GuiCrafting extends GuiContainer { super(new ContainerWorkbench(playerInv, worldIn, blockPosition)); } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - this.fontRendererObj.drawString(I18n.format("container.crafting", new Object[0]), 28, 6, 4210752); - this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, - 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -60,4 +53,14 @@ public class GuiCrafting extends GuiContainer { int j = (this.height - this.ySize) / 2; this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(I18n.format("container.crafting", new Object[0]), 28, 6, 4210752); + this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, + 4210752); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiDispenser.java b/src/game/java/net/minecraft/client/gui/inventory/GuiDispenser.java index 2ec59da5..c617abb7 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiDispenser.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiDispenser.java @@ -6,22 +6,25 @@ import net.minecraft.inventory.ContainerDispenser; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,19 +41,8 @@ public class GuiDispenser extends GuiContainer { this.dispenserInventory = dispenserInv; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - String s = this.dispenserInventory.getDisplayName().getUnformattedText(); - this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); - this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -59,4 +51,15 @@ public class GuiDispenser extends GuiContainer { int j = (this.height - this.ySize) / 2; this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + String s = this.dispenserInventory.getDisplayName().getUnformattedText(); + this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); + this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiEditSign.java b/src/game/java/net/minecraft/client/gui/inventory/GuiEditSign.java index 873cdf33..bf7e2bf3 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiEditSign.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiEditSign.java @@ -18,22 +18,25 @@ import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.ChatAllowedCharacters; import net.minecraft.util.ChatComponentText; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,41 +51,9 @@ public class GuiEditSign extends GuiScreenVisualViewport { this.tileSign = teSign; } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - Keyboard.enableRepeatEvents(true); - this.buttonList.add(this.doneBtn = new GuiButton(0, this.width / 2 - 100, this.height / 4 + 120, - I18n.format("gui.done", new Object[0]))); - this.tileSign.setEditable(false); - } - - /**+ - * Called when the screen is unloaded. Used to disable keyboard - * repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - NetHandlerPlayClient nethandlerplayclient = this.mc.getNetHandler(); - if (nethandlerplayclient != null) { - nethandlerplayclient - .addToSendQueue(new C12PacketUpdateSign(this.tileSign.getPos(), this.tileSign.signText)); - } - - this.tileSign.setEditable(true); - } - - public void updateScreen0() { - ++this.updateCounter; - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.enabled) { @@ -94,36 +65,8 @@ public class GuiEditSign extends GuiScreenVisualViewport { } } - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - if (parInt1 == 200) { - this.editLine = this.editLine - 1 & 3; - } - - if (parInt1 == 208 || parInt1 == 28 || parInt1 == 156) { - this.editLine = this.editLine + 1 & 3; - } - - String s = this.tileSign.signText[this.editLine].getUnformattedText(); - if (parInt1 == 14 && s.length() > 0) { - s = s.substring(0, s.length() - 1); - } - - if (ChatAllowedCharacters.isAllowedCharacter(parChar1) - && this.fontRendererObj.getStringWidth(s + parChar1) <= 90) { - s = s + parChar1; - } - - this.tileSign.signText[this.editLine] = new ChatComponentText(s); - if (parInt1 == 1) { - this.actionPerformed(this.doneBtn); - } - + public boolean blockPTTKey() { + return true; } public void drawScreen0(int i, int j, float f) { @@ -179,8 +122,66 @@ public class GuiEditSign extends GuiScreenVisualViewport { super.drawScreen0(i, j, f); } - public boolean blockPTTKey() { - return true; + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + Keyboard.enableRepeatEvents(true); + this.buttonList.add(this.doneBtn = new GuiButton(0, this.width / 2 - 100, this.height / 4 + 120, + I18n.format("gui.done", new Object[0]))); + this.tileSign.setEditable(false); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + if (parInt1 == 200) { + this.editLine = this.editLine - 1 & 3; + } + + if (parInt1 == 208 || parInt1 == 28 || parInt1 == 156) { + this.editLine = this.editLine + 1 & 3; + } + + String s = this.tileSign.signText[this.editLine].getUnformattedText(); + if (parInt1 == 14 && s.length() > 0) { + s = s.substring(0, s.length() - 1); + } + + if (ChatAllowedCharacters.isAllowedCharacter(parChar1) + && this.fontRendererObj.getStringWidth(s + parChar1) <= 90) { + s = s + parChar1; + } + + this.tileSign.signText[this.editLine] = new ChatComponentText(s); + if (parInt1 == 1) { + this.actionPerformed(this.doneBtn); + } + + } + + /** + * + Called when the screen is unloaded. Used to disable keyboard repeat events + */ + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + NetHandlerPlayClient nethandlerplayclient = this.mc.getNetHandler(); + if (nethandlerplayclient != null) { + nethandlerplayclient + .addToSendQueue(new C12PacketUpdateSign(this.tileSign.getPos(), this.tileSign.signText)); + } + + this.tileSign.setEditable(true); + } + + public void updateScreen0() { + ++this.updateCounter; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiFabricator.java b/src/game/java/net/minecraft/client/gui/inventory/GuiFabricator.java new file mode 100644 index 00000000..6c4780c5 --- /dev/null +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiFabricator.java @@ -0,0 +1,66 @@ +package net.minecraft.client.gui.inventory; + +import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; +import net.minecraft.client.resources.I18n; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.inventory.ContainerWorkbench; +import net.minecraft.util.BlockPos; +import net.minecraft.util.ResourceLocation; +import net.minecraft.world.World; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class GuiFabricator extends GuiContainer { + private static final ResourceLocation craftingTableGuiTextures = new ResourceLocation( + "textures/gui/container/fabricator.png"); + + public GuiFabricator(InventoryPlayer playerInv, World worldIn) { + this(playerInv, worldIn, BlockPos.ORIGIN); + } + + public GuiFabricator(InventoryPlayer playerInv, World worldIn, BlockPos blockPosition) { + super(new ContainerWorkbench(playerInv, worldIn, blockPosition)); + } + + /** + * + Args : renderPartialTicks, mouseX, mouseY + */ + protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(craftingTableGuiTextures); + int i = (this.width - this.xSize) / 2; + int j = (this.height - this.ySize) / 2; + this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); + } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(I18n.format("container.crafting", new Object[0]), 28, 6, 4210752); + this.fontRendererObj.drawString(I18n.format("container.inventory", new Object[0]), 8, this.ySize - 96 + 2, + 4210752); + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiFurnace.java b/src/game/java/net/minecraft/client/gui/inventory/GuiFurnace.java index 893879e9..38423210 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiFurnace.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiFurnace.java @@ -7,22 +7,25 @@ import net.minecraft.inventory.IInventory; import net.minecraft.tileentity.TileEntityFurnace; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,19 +42,8 @@ public class GuiFurnace extends GuiContainer { this.tileFurnace = furnaceInv; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - String s = this.tileFurnace.getDisplayName().getUnformattedText(); - this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); - this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -68,10 +60,15 @@ public class GuiFurnace extends GuiContainer { this.drawTexturedModalRect(i + 79, j + 34, 176, 14, l + 1, 16); } - private int getCookProgressScaled(int pixels) { - int i = this.tileFurnace.getField(2); - int j = this.tileFurnace.getField(3); - return j != 0 && i != 0 ? i * pixels / j : 0; + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + String s = this.tileFurnace.getDisplayName().getUnformattedText(); + this.fontRendererObj.drawString(s, this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752); + this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); } private int getBurnLeftScaled(int pixels) { @@ -82,4 +79,10 @@ public class GuiFurnace extends GuiContainer { return this.tileFurnace.getField(0) * pixels / i; } + + private int getCookProgressScaled(int pixels) { + int i = this.tileFurnace.getField(2); + int j = this.tileFurnace.getField(3); + return j != 0 && i != 0 ? i * pixels / j : 0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiInventory.java b/src/game/java/net/minecraft/client/gui/inventory/GuiInventory.java index fbe69585..9eb124ce 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiInventory.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiInventory.java @@ -13,97 +13,33 @@ import net.minecraft.client.resources.I18n; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiInventory extends InventoryEffectRenderer { - private float oldMouseX; - private float oldMouseY; - - public GuiInventory(EntityPlayer parEntityPlayer) { - super(parEntityPlayer.inventoryContainer); - this.allowUserInput = true; - } - - /**+ - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - if (this.mc.playerController.isInCreativeMode()) { - this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.thePlayer)); - } - - this.updateActivePotionEffects(); - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - if (this.mc.playerController.isInCreativeMode()) { - this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.thePlayer)); - } else { - super.initGui(); - } - - } - - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - this.fontRendererObj.drawString(I18n.format("container.crafting", new Object[0]), 86, 16, 4210752); - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - super.drawScreen(i, j, f); - this.oldMouseX = (float) i; - this.oldMouseY = (float) j; - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY - */ - protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.mc.getTextureManager().bindTexture(inventoryBackground); - int i = this.guiLeft; - int j = this.guiTop; - this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); - GlStateManager.enableDepth(); - drawEntityOnScreen(i + 51, j + 75, 30, (float) (i + 51) - this.oldMouseX, - (float) (j + 75 - 50) - this.oldMouseY, this.mc.thePlayer); - GlStateManager.disableDepth(); - } - - /**+ - * Draws the entity to the screen. Args: xPos, yPos, scale, - * mouseX, mouseY, entityLiving + /** + * + Draws the entity to the screen. Args: xPos, yPos, scale, mouseX, mouseY, + * entityLiving */ public static void drawEntityOnScreen(int posX, int posY, int scale, float mouseX, float mouseY, EntityLivingBase ent) { @@ -145,9 +81,18 @@ public class GuiInventory extends InventoryEffectRenderer { GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); } - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) + private float oldMouseX; + + private float oldMouseY; + + public GuiInventory(EntityPlayer parEntityPlayer) { + super(parEntityPlayer.inventoryContainer); + this.allowUserInput = true; + } + + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) */ protected void actionPerformed(GuiButton parGuiButton) { if (parGuiButton.id == 0) { @@ -159,4 +104,63 @@ public class GuiInventory extends InventoryEffectRenderer { } } + + /** + * + Args : renderPartialTicks, mouseX, mouseY + */ + protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.mc.getTextureManager().bindTexture(inventoryBackground); + int i = this.guiLeft; + int j = this.guiTop; + this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); + GlStateManager.enableDepth(); + drawEntityOnScreen(i + 51, j + 75, 30, (float) (i + 51) - this.oldMouseX, + (float) (j + 75 - 50) - this.oldMouseY, this.mc.thePlayer); + GlStateManager.disableDepth(); + } + + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(I18n.format("container.crafting", new Object[0]), 86, 16, 4210752); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + super.drawScreen(i, j, f); + this.oldMouseX = (float) i; + this.oldMouseY = (float) j; + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + if (this.mc.playerController.isInCreativeMode()) { + this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.thePlayer)); + } else { + super.initGui(); + } + + } + + /** + * + Called from the main game loop to update the screen. + */ + public void updateScreen() { + if (this.mc.playerController.isInCreativeMode()) { + this.mc.displayGuiScreen(new GuiContainerCreative(this.mc.thePlayer)); + } + + this.updateActivePotionEffects(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/inventory/GuiScreenHorseInventory.java b/src/game/java/net/minecraft/client/gui/inventory/GuiScreenHorseInventory.java index 497462ee..81ad97b7 100644 --- a/src/game/java/net/minecraft/client/gui/inventory/GuiScreenHorseInventory.java +++ b/src/game/java/net/minecraft/client/gui/inventory/GuiScreenHorseInventory.java @@ -7,22 +7,25 @@ import net.minecraft.inventory.ContainerHorseInventory; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,18 +46,8 @@ public class GuiScreenHorseInventory extends GuiContainer { this.allowUserInput = false; } - /**+ - * Draw the foreground layer for the GuiContainer (everything in - * front of the items). Args : mouseX, mouseY - */ - protected void drawGuiContainerForegroundLayer(int var1, int var2) { - this.fontRendererObj.drawString(this.horseInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); - this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, - this.ySize - 96 + 2, 4210752); - } - - /**+ - * Args : renderPartialTicks, mouseX, mouseY + /** + * + Args : renderPartialTicks, mouseX, mouseY */ protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -74,9 +67,19 @@ public class GuiScreenHorseInventory extends GuiContainer { (float) (j + 75 - 50) - this.mousePosY, this.horseEntity); } - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks + /** + * + Draw the foreground layer for the GuiContainer (everything in front of the + * items). Args : mouseX, mouseY + */ + protected void drawGuiContainerForegroundLayer(int var1, int var2) { + this.fontRendererObj.drawString(this.horseInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); + this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, + this.ySize - 96 + 2, 4210752); + } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks */ public void drawScreen(int i, int j, float f) { this.mousePosx = (float) i; diff --git a/src/game/java/net/minecraft/client/gui/spectator/BaseSpectatorGroup.java b/src/game/java/net/minecraft/client/gui/spectator/BaseSpectatorGroup.java index 22892227..465fc7d1 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/BaseSpectatorGroup.java +++ b/src/game/java/net/minecraft/client/gui/spectator/BaseSpectatorGroup.java @@ -9,22 +9,25 @@ import net.minecraft.client.gui.spectator.categories.TeleportToTeam; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuObject.java b/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuObject.java index fff4a516..1f6ad22e 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuObject.java +++ b/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuObject.java @@ -2,22 +2,25 @@ package net.minecraft.client.gui.spectator; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,9 +28,9 @@ import net.minecraft.util.IChatComponent; public interface ISpectatorMenuObject { void func_178661_a(SpectatorMenu var1); - IChatComponent getSpectatorName(); + boolean func_178662_A_(); void func_178663_a(float var1, int var2); - boolean func_178662_A_(); + IChatComponent getSpectatorName(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuRecipient.java b/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuRecipient.java index f5363a6c..4a3cb9b5 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuRecipient.java +++ b/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuRecipient.java @@ -1,21 +1,24 @@ package net.minecraft.client.gui.spectator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuView.java b/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuView.java index 18e3f9e5..3aabd6cd 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuView.java +++ b/src/game/java/net/minecraft/client/gui/spectator/ISpectatorMenuView.java @@ -4,22 +4,25 @@ import java.util.List; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/spectator/PlayerMenuObject.java b/src/game/java/net/minecraft/client/gui/spectator/PlayerMenuObject.java index afaa30bd..0715cc10 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/PlayerMenuObject.java +++ b/src/game/java/net/minecraft/client/gui/spectator/PlayerMenuObject.java @@ -8,22 +8,25 @@ import net.minecraft.network.play.client.C18PacketSpectate; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,8 +42,8 @@ public class PlayerMenuObject implements ISpectatorMenuObject { Minecraft.getMinecraft().getNetHandler().addToSendQueue(new C18PacketSpectate(this.profile.getId())); } - public IChatComponent getSpectatorName() { - return new ChatComponentText(this.profile.getName()); + public boolean func_178662_A_() { + return true; } public void func_178663_a(float alpha, int parInt1) { @@ -51,7 +54,7 @@ public class PlayerMenuObject implements ISpectatorMenuObject { Gui.drawScaledCustomSizeModalRect(2, 2, 40.0F, 8.0F, 8, 8, 12, 12, 64.0F, 64.0F); } - public boolean func_178662_A_() { - return true; + public IChatComponent getSpectatorName() { + return new ChatComponentText(this.profile.getName()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/spectator/SpectatorMenu.java b/src/game/java/net/minecraft/client/gui/spectator/SpectatorMenu.java index 5a2bd1c9..1a5c1313 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/SpectatorMenu.java +++ b/src/game/java/net/minecraft/client/gui/spectator/SpectatorMenu.java @@ -13,116 +13,30 @@ import net.minecraft.client.gui.spectator.categories.SpectatorDetails; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SpectatorMenu { - private static final ISpectatorMenuObject field_178655_b = new SpectatorMenu.EndSpectatorObject(); - private static final ISpectatorMenuObject field_178656_c = new SpectatorMenu.MoveMenuObject(-1, true); - private static final ISpectatorMenuObject field_178653_d = new SpectatorMenu.MoveMenuObject(1, true); - private static final ISpectatorMenuObject field_178654_e = new SpectatorMenu.MoveMenuObject(1, false); - public static final ISpectatorMenuObject field_178657_a = new ISpectatorMenuObject() { - public void func_178661_a(SpectatorMenu var1) { - } - - public IChatComponent getSpectatorName() { - return new ChatComponentText(""); - } - - public void func_178663_a(float var1, int var2) { - } - - public boolean func_178662_A_() { - return false; - } - }; - private final ISpectatorMenuRecipient field_178651_f; - private final List field_178652_g = Lists.newArrayList(); - private ISpectatorMenuView field_178659_h = new BaseSpectatorGroup(); - private int field_178660_i = -1; - private int field_178658_j; - - public SpectatorMenu(ISpectatorMenuRecipient parISpectatorMenuRecipient) { - this.field_178651_f = parISpectatorMenuRecipient; - } - - public ISpectatorMenuObject func_178643_a(int parInt1) { - int i = parInt1 + this.field_178658_j * 6; - return this.field_178658_j > 0 && parInt1 == 0 ? field_178656_c - : (parInt1 == 7 ? (i < this.field_178659_h.func_178669_a().size() ? field_178653_d : field_178654_e) - : (parInt1 == 8 ? field_178655_b - : (i >= 0 && i < this.field_178659_h.func_178669_a().size() - ? (ISpectatorMenuObject) Objects.firstNonNull( - this.field_178659_h.func_178669_a().get(i), field_178657_a) - : field_178657_a))); - } - - public List func_178642_a() { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i <= 8; ++i) { - arraylist.add(this.func_178643_a(i)); - } - - return arraylist; - } - - public ISpectatorMenuObject func_178645_b() { - return this.func_178643_a(this.field_178660_i); - } - - public ISpectatorMenuView func_178650_c() { - return this.field_178659_h; - } - - public void func_178644_b(int parInt1) { - ISpectatorMenuObject ispectatormenuobject = this.func_178643_a(parInt1); - if (ispectatormenuobject != field_178657_a) { - if (this.field_178660_i == parInt1 && ispectatormenuobject.func_178662_A_()) { - ispectatormenuobject.func_178661_a(this); - } else { - this.field_178660_i = parInt1; - } - } - - } - - public void func_178641_d() { - this.field_178651_f.func_175257_a(this); - } - - public int func_178648_e() { - return this.field_178660_i; - } - - public void func_178647_a(ISpectatorMenuView parISpectatorMenuView) { - this.field_178652_g.add(this.func_178646_f()); - this.field_178659_h = parISpectatorMenuView; - this.field_178660_i = -1; - this.field_178658_j = 0; - } - - public SpectatorDetails func_178646_f() { - return new SpectatorDetails(this.field_178659_h, this.func_178642_a(), this.field_178660_i); - } - static class EndSpectatorObject implements ISpectatorMenuObject { private EndSpectatorObject() { } @@ -131,8 +45,8 @@ public class SpectatorMenu { spectatormenu.func_178641_d(); } - public IChatComponent getSpectatorName() { - return new ChatComponentText("Close menu"); + public boolean func_178662_A_() { + return true; } public void func_178663_a(float var1, int var2) { @@ -140,8 +54,8 @@ public class SpectatorMenu { Gui.drawModalRectWithCustomSizedTexture(0, 0, 128.0F, 0.0F, 16, 16, 256.0F, 256.0F); } - public boolean func_178662_A_() { - return true; + public IChatComponent getSpectatorName() { + return new ChatComponentText("Close menu"); } } @@ -158,9 +72,8 @@ public class SpectatorMenu { spectatormenu.field_178658_j = this.field_178666_a; } - public IChatComponent getSpectatorName() { - return this.field_178666_a < 0 ? new ChatComponentText("Previous Page") - : new ChatComponentText("Next Page"); + public boolean func_178662_A_() { + return this.field_178665_b; } public void func_178663_a(float var1, int var2) { @@ -173,8 +86,100 @@ public class SpectatorMenu { } - public boolean func_178662_A_() { - return this.field_178665_b; + public IChatComponent getSpectatorName() { + return this.field_178666_a < 0 ? new ChatComponentText("Previous Page") + : new ChatComponentText("Next Page"); } } + + private static final ISpectatorMenuObject field_178655_b = new SpectatorMenu.EndSpectatorObject(); + private static final ISpectatorMenuObject field_178656_c = new SpectatorMenu.MoveMenuObject(-1, true); + private static final ISpectatorMenuObject field_178653_d = new SpectatorMenu.MoveMenuObject(1, true); + private static final ISpectatorMenuObject field_178654_e = new SpectatorMenu.MoveMenuObject(1, false); + public static final ISpectatorMenuObject field_178657_a = new ISpectatorMenuObject() { + public void func_178661_a(SpectatorMenu var1) { + } + + public boolean func_178662_A_() { + return false; + } + + public void func_178663_a(float var1, int var2) { + } + + public IChatComponent getSpectatorName() { + return new ChatComponentText(""); + } + }; + private final ISpectatorMenuRecipient field_178651_f; + private final List field_178652_g = Lists.newArrayList(); + private ISpectatorMenuView field_178659_h = new BaseSpectatorGroup(); + + private int field_178660_i = -1; + + private int field_178658_j; + + public SpectatorMenu(ISpectatorMenuRecipient parISpectatorMenuRecipient) { + this.field_178651_f = parISpectatorMenuRecipient; + } + + public void func_178641_d() { + this.field_178651_f.func_175257_a(this); + } + + public List func_178642_a() { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i <= 8; ++i) { + arraylist.add(this.func_178643_a(i)); + } + + return arraylist; + } + + public ISpectatorMenuObject func_178643_a(int parInt1) { + int i = parInt1 + this.field_178658_j * 6; + return this.field_178658_j > 0 && parInt1 == 0 ? field_178656_c + : (parInt1 == 7 ? (i < this.field_178659_h.func_178669_a().size() ? field_178653_d : field_178654_e) + : (parInt1 == 8 ? field_178655_b + : (i >= 0 && i < this.field_178659_h.func_178669_a().size() + ? (ISpectatorMenuObject) Objects.firstNonNull( + this.field_178659_h.func_178669_a().get(i), field_178657_a) + : field_178657_a))); + } + + public void func_178644_b(int parInt1) { + ISpectatorMenuObject ispectatormenuobject = this.func_178643_a(parInt1); + if (ispectatormenuobject != field_178657_a) { + if (this.field_178660_i == parInt1 && ispectatormenuobject.func_178662_A_()) { + ispectatormenuobject.func_178661_a(this); + } else { + this.field_178660_i = parInt1; + } + } + + } + + public ISpectatorMenuObject func_178645_b() { + return this.func_178643_a(this.field_178660_i); + } + + public SpectatorDetails func_178646_f() { + return new SpectatorDetails(this.field_178659_h, this.func_178642_a(), this.field_178660_i); + } + + public void func_178647_a(ISpectatorMenuView parISpectatorMenuView) { + this.field_178652_g.add(this.func_178646_f()); + this.field_178659_h = parISpectatorMenuView; + this.field_178660_i = -1; + this.field_178658_j = 0; + } + + public int func_178648_e() { + return this.field_178660_i; + } + + public ISpectatorMenuView func_178650_c() { + return this.field_178659_h; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/spectator/categories/SpectatorDetails.java b/src/game/java/net/minecraft/client/gui/spectator/categories/SpectatorDetails.java index 07ea062e..f1115591 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/categories/SpectatorDetails.java +++ b/src/game/java/net/minecraft/client/gui/spectator/categories/SpectatorDetails.java @@ -8,22 +8,25 @@ import net.minecraft.client.gui.spectator.ISpectatorMenuObject; import net.minecraft.client.gui.spectator.ISpectatorMenuView; import net.minecraft.client.gui.spectator.SpectatorMenu; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToPlayer.java b/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToPlayer.java index 760d3e58..61c35d77 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToPlayer.java +++ b/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToPlayer.java @@ -20,22 +20,25 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -67,6 +70,19 @@ public class TeleportToPlayer implements ISpectatorMenuView, ISpectatorMenuObjec } + public void func_178661_a(SpectatorMenu spectatormenu) { + spectatormenu.func_178647_a(this); + } + + public boolean func_178662_A_() { + return !this.field_178673_b.isEmpty(); + } + + public void func_178663_a(float var1, int var2) { + Minecraft.getMinecraft().getTextureManager().bindTexture(GuiSpectator.field_175269_a); + Gui.drawModalRectWithCustomSizedTexture(0, 0, 0.0F, 0.0F, 16, 16, 256.0F, 256.0F); + } + public List func_178669_a() { return this.field_178673_b; } @@ -75,20 +91,7 @@ public class TeleportToPlayer implements ISpectatorMenuView, ISpectatorMenuObjec return new ChatComponentText("Select a player to teleport to"); } - public void func_178661_a(SpectatorMenu spectatormenu) { - spectatormenu.func_178647_a(this); - } - public IChatComponent getSpectatorName() { return new ChatComponentText("Teleport to player"); } - - public void func_178663_a(float var1, int var2) { - Minecraft.getMinecraft().getTextureManager().bindTexture(GuiSpectator.field_175269_a); - Gui.drawModalRectWithCustomSizedTexture(0, 0, 0.0F, 0.0F, 16, 16, 256.0F, 256.0F); - } - - public boolean func_178662_A_() { - return !this.field_178673_b.isEmpty(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToTeam.java b/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToTeam.java index 1ca0b6d1..28bc68d1 100644 --- a/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToTeam.java +++ b/src/game/java/net/minecraft/client/gui/spectator/categories/TeleportToTeam.java @@ -1,6 +1,7 @@ package net.minecraft.client.gui.spectator.categories; import java.util.List; + import com.google.common.collect.Lists; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -19,69 +20,30 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TeleportToTeam implements ISpectatorMenuView, ISpectatorMenuObject { - private final List field_178672_a = Lists.newArrayList(); - - public TeleportToTeam() { - Minecraft minecraft = Minecraft.getMinecraft(); - - for (ScorePlayerTeam scoreplayerteam : minecraft.theWorld.getScoreboard().getTeams()) { - this.field_178672_a.add(new TeleportToTeam.TeamSelectionObject(scoreplayerteam)); - } - - } - - public List func_178669_a() { - return this.field_178672_a; - } - - public IChatComponent func_178670_b() { - return new ChatComponentText("Select a team to teleport to"); - } - - public void func_178661_a(SpectatorMenu spectatormenu) { - spectatormenu.func_178647_a(this); - } - - public IChatComponent getSpectatorName() { - return new ChatComponentText("Teleport to team member"); - } - - public void func_178663_a(float var1, int var2) { - Minecraft.getMinecraft().getTextureManager().bindTexture(GuiSpectator.field_175269_a); - Gui.drawModalRectWithCustomSizedTexture(0, 0, 16.0F, 0.0F, 16, 16, 256.0F, 256.0F); - } - - public boolean func_178662_A_() { - for (int i = 0, l = this.field_178672_a.size(); i < l; ++i) { - if (this.field_178672_a.get(i).func_178662_A_()) { - return true; - } - } - - return false; - } - class TeamSelectionObject implements ISpectatorMenuObject { private final ScorePlayerTeam field_178676_b; private final ResourceLocation field_178677_c; @@ -118,8 +80,8 @@ public class TeleportToTeam implements ISpectatorMenuView, ISpectatorMenuObject spectatormenu.func_178647_a(new TeleportToPlayer(this.field_178675_d)); } - public IChatComponent getSpectatorName() { - return new ChatComponentText(this.field_178676_b.getTeamName()); + public boolean func_178662_A_() { + return !this.field_178675_d.isEmpty(); } public void func_178663_a(float f, int i) { @@ -142,8 +104,50 @@ public class TeleportToTeam implements ISpectatorMenuView, ISpectatorMenuObject Gui.drawScaledCustomSizeModalRect(2, 2, 40.0F, 8.0F, 8, 8, 12, 12, 64.0F, 64.0F); } - public boolean func_178662_A_() { - return !this.field_178675_d.isEmpty(); + public IChatComponent getSpectatorName() { + return new ChatComponentText(this.field_178676_b.getTeamName()); } } + + private final List field_178672_a = Lists.newArrayList(); + + public TeleportToTeam() { + Minecraft minecraft = Minecraft.getMinecraft(); + + for (ScorePlayerTeam scoreplayerteam : minecraft.theWorld.getScoreboard().getTeams()) { + this.field_178672_a.add(new TeleportToTeam.TeamSelectionObject(scoreplayerteam)); + } + + } + + public void func_178661_a(SpectatorMenu spectatormenu) { + spectatormenu.func_178647_a(this); + } + + public boolean func_178662_A_() { + for (int i = 0, l = this.field_178672_a.size(); i < l; ++i) { + if (this.field_178672_a.get(i).func_178662_A_()) { + return true; + } + } + + return false; + } + + public void func_178663_a(float var1, int var2) { + Minecraft.getMinecraft().getTextureManager().bindTexture(GuiSpectator.field_175269_a); + Gui.drawModalRectWithCustomSizedTexture(0, 0, 16.0F, 0.0F, 16, 16, 256.0F, 256.0F); + } + + public List func_178669_a() { + return this.field_178672_a; + } + + public IChatComponent func_178670_b() { + return new ChatComponentText("Select a team to teleport to"); + } + + public IChatComponent getSpectatorName() { + return new ChatComponentText("Teleport to team member"); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/main/GameConfiguration.java b/src/game/java/net/minecraft/client/main/GameConfiguration.java index 0c044962..fd0a4956 100644 --- a/src/game/java/net/minecraft/client/main/GameConfiguration.java +++ b/src/game/java/net/minecraft/client/main/GameConfiguration.java @@ -2,38 +2,30 @@ package net.minecraft.client.main; import net.minecraft.util.Session; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GameConfiguration { - public final GameConfiguration.UserInformation userInfo; - public final GameConfiguration.DisplayInformation displayInfo; - public final GameConfiguration.GameInformation gameInfo; - - public GameConfiguration(GameConfiguration.UserInformation userInfoIn, - GameConfiguration.DisplayInformation displayInfoIn, GameConfiguration.GameInformation gameInfoIn) { - this.userInfo = userInfoIn; - this.displayInfo = displayInfoIn; - this.gameInfo = gameInfoIn; - } - public static class DisplayInformation { public final int width; public final int height; @@ -65,4 +57,17 @@ public class GameConfiguration { this.session = parSession; } } + + public final GameConfiguration.UserInformation userInfo; + + public final GameConfiguration.DisplayInformation displayInfo; + + public final GameConfiguration.GameInformation gameInfo; + + public GameConfiguration(GameConfiguration.UserInformation userInfoIn, + GameConfiguration.DisplayInformation displayInfoIn, GameConfiguration.GameInformation gameInfoIn) { + this.userInfo = userInfoIn; + this.displayInfo = displayInfoIn; + this.gameInfo = gameInfoIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/main/Main.java b/src/game/java/net/minecraft/client/main/Main.java index a12151aa..3baf0b52 100644 --- a/src/game/java/net/minecraft/client/main/Main.java +++ b/src/game/java/net/minecraft/client/main/Main.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; import net.minecraft.client.Minecraft; import net.minecraft.util.Session; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/model/ModelArmorStand.java b/src/game/java/net/minecraft/client/model/ModelArmorStand.java index 6ace0e67..dc3a01a1 100644 --- a/src/game/java/net/minecraft/client/model/ModelArmorStand.java +++ b/src/game/java/net/minecraft/client/model/ModelArmorStand.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -71,12 +74,47 @@ public class ModelArmorStand extends ModelArmorStandArmor { this.standBase.setRotationPoint(0.0F, 12.0F, 0.0F); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + public void postRenderArm(float scale) { + boolean flag = this.bipedRightArm.showModel; + this.bipedRightArm.showModel = true; + super.postRenderArm(scale); + this.bipedRightArm.showModel = flag; + } + + /** + * + Sets the models various rotation angles then renders the model. + */ + public void render(Entity entityIn, float scale, float parFloat2, float parFloat3, float parFloat4, float parFloat5, + float parFloat6) { + super.render(entityIn, scale, parFloat2, parFloat3, parFloat4, parFloat5, parFloat6); + GlStateManager.pushMatrix(); + if (this.isChild) { + float f = 2.0F; + GlStateManager.scale(1.0F / f, 1.0F / f, 1.0F / f); + GlStateManager.translate(0.0F, 24.0F * parFloat6, 0.0F); + this.standRightSide.render(parFloat6); + this.standLeftSide.render(parFloat6); + this.standWaist.render(parFloat6); + this.standBase.render(parFloat6); + } else { + if (entityIn.isSneaking()) { + GlStateManager.translate(0.0F, 0.2F, 0.0F); + } + + this.standRightSide.render(parFloat6); + this.standLeftSide.render(parFloat6); + this.standWaist.render(parFloat6); + this.standBase.render(parFloat6); + } + + GlStateManager.popMatrix(); + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -107,41 +145,4 @@ public class ModelArmorStand extends ModelArmorStandArmor { this.standBase.rotateAngleZ = 0.0F; } } - - /**+ - * Sets the models various rotation angles then renders the - * model. - */ - public void render(Entity entityIn, float scale, float parFloat2, float parFloat3, float parFloat4, float parFloat5, - float parFloat6) { - super.render(entityIn, scale, parFloat2, parFloat3, parFloat4, parFloat5, parFloat6); - GlStateManager.pushMatrix(); - if (this.isChild) { - float f = 2.0F; - GlStateManager.scale(1.0F / f, 1.0F / f, 1.0F / f); - GlStateManager.translate(0.0F, 24.0F * parFloat6, 0.0F); - this.standRightSide.render(parFloat6); - this.standLeftSide.render(parFloat6); - this.standWaist.render(parFloat6); - this.standBase.render(parFloat6); - } else { - if (entityIn.isSneaking()) { - GlStateManager.translate(0.0F, 0.2F, 0.0F); - } - - this.standRightSide.render(parFloat6); - this.standLeftSide.render(parFloat6); - this.standWaist.render(parFloat6); - this.standBase.render(parFloat6); - } - - GlStateManager.popMatrix(); - } - - public void postRenderArm(float scale) { - boolean flag = this.bipedRightArm.showModel; - this.bipedRightArm.showModel = true; - super.postRenderArm(scale); - this.bipedRightArm.showModel = flag; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelArmorStandArmor.java b/src/game/java/net/minecraft/client/model/ModelArmorStandArmor.java index 00bfd91d..3707b9bc 100644 --- a/src/game/java/net/minecraft/client/model/ModelArmorStandArmor.java +++ b/src/game/java/net/minecraft/client/model/ModelArmorStandArmor.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,12 +39,11 @@ public class ModelArmorStandArmor extends ModelBiped { super(modelSize, 0.0F, textureWidthIn, textureHeightIn); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float entityIn, float parFloat2, float parFloat3, float parFloat4, float parFloat5, float parFloat6, Entity parEntity) { diff --git a/src/game/java/net/minecraft/client/model/ModelBanner.java b/src/game/java/net/minecraft/client/model/ModelBanner.java index c0e02763..15219f65 100644 --- a/src/game/java/net/minecraft/client/model/ModelBanner.java +++ b/src/game/java/net/minecraft/client/model/ModelBanner.java @@ -1,21 +1,24 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,8 @@ public class ModelBanner extends ModelBase { this.bannerTop.addBox(-10.0F, -32.0F, -1.0F, 20, 2, 2, 0.0F); } - /**+ - * Renders the banner model in. + /** + * + Renders the banner model in. */ public void renderBanner() { this.bannerSlate.rotationPointY = -32.0F; diff --git a/src/game/java/net/minecraft/client/model/ModelBase.java b/src/game/java/net/minecraft/client/model/ModelBase.java index 7879f6bf..7f3cb4d7 100644 --- a/src/game/java/net/minecraft/client/model/ModelBase.java +++ b/src/game/java/net/minecraft/client/model/ModelBase.java @@ -2,88 +2,41 @@ package net.minecraft.client.model; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class ModelBase { - public float swingProgress; - public boolean isRiding; - public boolean isChild = true; - /**+ - * This is a list of all the boxes (ModelRenderer.class) in the - * current model. - */ - public List boxList = Lists.newArrayList(); - private Map modelTextureMap = Maps.newHashMap(); - public int textureWidth = 64; - public int textureHeight = 32; - - /**+ - * Sets the models various rotation angles then renders the - * model. - */ - public void render(Entity var1, float var2, float var3, float var4, float var5, float var6, float var7) { - } - - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. - */ - public void setRotationAngles(float var1, float var2, float var3, float var4, float var5, float var6, Entity var7) { - } - - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. - */ - public void setLivingAnimations(EntityLivingBase var1, float var2, float var3, float var4) { - } - - public ModelRenderer getRandomModelBox(EaglercraftRandom rand) { - return (ModelRenderer) this.boxList.get(rand.nextInt(this.boxList.size())); - } - - protected void setTextureOffset(String partName, int x, int y) { - this.modelTextureMap.put(partName, new TextureOffset(x, y)); - } - - public TextureOffset getTextureOffset(String partName) { - return (TextureOffset) this.modelTextureMap.get(partName); - } - - /**+ - * Copies the angles from one object to another. This is used - * when objects should stay aligned with each other, like the - * hair over a players head. + /** + * + Copies the angles from one object to another. This is used when objects + * should stay aligned with each other, like the hair over a players head. */ public static void copyModelAngles(ModelRenderer source, ModelRenderer dest) { dest.rotateAngleX = source.rotateAngleX; @@ -94,9 +47,56 @@ public abstract class ModelBase { dest.rotationPointZ = source.rotationPointZ; } + public float swingProgress; + public boolean isRiding; + public boolean isChild = true; + /** + * + This is a list of all the boxes (ModelRenderer.class) in the current model. + */ + public List boxList = Lists.newArrayList(); + private Map modelTextureMap = Maps.newHashMap(); + public int textureWidth = 64; + + public int textureHeight = 32; + + public ModelRenderer getRandomModelBox(EaglercraftRandom rand) { + return (ModelRenderer) this.boxList.get(rand.nextInt(this.boxList.size())); + } + + public TextureOffset getTextureOffset(String partName) { + return (TextureOffset) this.modelTextureMap.get(partName); + } + + /** + * + Sets the models various rotation angles then renders the model. + */ + public void render(Entity var1, float var2, float var3, float var4, float var5, float var6, float var7) { + } + + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. + */ + public void setLivingAnimations(EntityLivingBase var1, float var2, float var3, float var4) { + } + public void setModelAttributes(ModelBase modelbase) { this.swingProgress = modelbase.swingProgress; this.isRiding = modelbase.isRiding; this.isChild = modelbase.isChild; } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float var1, float var2, float var3, float var4, float var5, float var6, Entity var7) { + } + + protected void setTextureOffset(String partName, int x, int y) { + this.modelTextureMap.put(partName, new TextureOffset(x, y)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelBat.java b/src/game/java/net/minecraft/client/model/ModelBat.java index f88fecb9..e3720c7c 100644 --- a/src/game/java/net/minecraft/client/model/ModelBat.java +++ b/src/game/java/net/minecraft/client/model/ModelBat.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.passive.EntityBat; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,9 +68,8 @@ public class ModelBat extends ModelBase { this.batLeftWing.addChild(this.batOuterLeftWing); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -75,12 +77,11 @@ public class ModelBat extends ModelBase { this.batBody.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float var1, float var2, float f, float f1, float f2, float var6, Entity entity) { if (((EntityBat) entity).getIsBatHanging()) { diff --git a/src/game/java/net/minecraft/client/model/ModelBiped.java b/src/game/java/net/minecraft/client/model/ModelBiped.java index ef864174..06b417da 100644 --- a/src/game/java/net/minecraft/client/model/ModelBiped.java +++ b/src/game/java/net/minecraft/client/model/ModelBiped.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -73,9 +76,12 @@ public class ModelBiped extends ModelBase { this.bipedLeftLeg.setRotationPoint(1.9F, 12.0F + parFloat1, 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + public void postRenderArm(float f) { + this.bipedRightArm.postRender(f); + } + + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -112,12 +118,33 @@ public class ModelBiped extends ModelBase { GlStateManager.popMatrix(); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + public void setInvisible(boolean invisible) { + this.bipedHead.showModel = invisible; + this.bipedHeadwear.showModel = invisible; + this.bipedBody.showModel = invisible; + this.bipedRightArm.showModel = invisible; + this.bipedLeftArm.showModel = invisible; + this.bipedRightLeg.showModel = invisible; + this.bipedLeftLeg.showModel = invisible; + } + + public void setModelAttributes(ModelBase model) { + super.setModelAttributes(model); + if (model instanceof ModelBiped) { + ModelBiped modelbiped = (ModelBiped) model; + this.heldItemLeft = modelbiped.heldItemLeft; + this.heldItemRight = modelbiped.heldItemRight; + this.isSneak = modelbiped.isSneak; + this.aimedBow = modelbiped.aimedBow; + } + + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float var6, Entity var7) { this.bipedHead.rotateAngleY = f3 / 57.295776F; @@ -225,30 +252,4 @@ public class ModelBiped extends ModelBase { copyModelAngles(this.bipedHead, this.bipedHeadwear); } - - public void setModelAttributes(ModelBase model) { - super.setModelAttributes(model); - if (model instanceof ModelBiped) { - ModelBiped modelbiped = (ModelBiped) model; - this.heldItemLeft = modelbiped.heldItemLeft; - this.heldItemRight = modelbiped.heldItemRight; - this.isSneak = modelbiped.isSneak; - this.aimedBow = modelbiped.aimedBow; - } - - } - - public void setInvisible(boolean invisible) { - this.bipedHead.showModel = invisible; - this.bipedHeadwear.showModel = invisible; - this.bipedBody.showModel = invisible; - this.bipedRightArm.showModel = invisible; - this.bipedLeftArm.showModel = invisible; - this.bipedRightLeg.showModel = invisible; - this.bipedLeftLeg.showModel = invisible; - } - - public void postRenderArm(float f) { - this.bipedRightArm.postRender(f); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelBlaze.java b/src/game/java/net/minecraft/client/model/ModelBlaze.java index d923a370..ae1fb852 100644 --- a/src/game/java/net/minecraft/client/model/ModelBlaze.java +++ b/src/game/java/net/minecraft/client/model/ModelBlaze.java @@ -3,29 +3,32 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelBlaze extends ModelBase { - /**+ - * The sticks that fly around the Blaze. + /** + * + The sticks that fly around the Blaze. */ private ModelRenderer[] blazeSticks = new ModelRenderer[12]; private ModelRenderer blazeHead; @@ -40,9 +43,8 @@ public class ModelBlaze extends ModelBase { this.blazeHead.addBox(-4.0F, -4.0F, -4.0F, 8, 8, 8); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -54,12 +56,11 @@ public class ModelBlaze extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float var1, float var2, float f, float f1, float f2, float var6, Entity var7) { float f3 = f * 3.1415927F * -0.1F; diff --git a/src/game/java/net/minecraft/client/model/ModelBoat.java b/src/game/java/net/minecraft/client/model/ModelBoat.java index 912d6e43..cd47df2d 100644 --- a/src/game/java/net/minecraft/client/model/ModelBoat.java +++ b/src/game/java/net/minecraft/client/model/ModelBoat.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -51,9 +54,8 @@ public class ModelBoat extends ModelBase { this.boatSides[3].rotateAngleY = 3.1415927F; } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity var1, float var2, float var3, float var4, float var5, float var6, float f) { for (int i = 0; i < 5; ++i) { diff --git a/src/game/java/net/minecraft/client/model/ModelBook.java b/src/game/java/net/minecraft/client/model/ModelBook.java index 97a64146..b14ee43f 100644 --- a/src/game/java/net/minecraft/client/model/ModelBook.java +++ b/src/game/java/net/minecraft/client/model/ModelBook.java @@ -3,59 +3,62 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelBook extends ModelBase { - /**+ - * Right cover renderer (when facing the book) + /** + * + Right cover renderer (when facing the book) */ public ModelRenderer coverRight = (new ModelRenderer(this)).setTextureOffset(0, 0).addBox(-6.0F, -5.0F, 0.0F, 6, 10, 0); - /**+ - * Left cover renderer (when facing the book) + /** + * + Left cover renderer (when facing the book) */ public ModelRenderer coverLeft = (new ModelRenderer(this)).setTextureOffset(16, 0).addBox(0.0F, -5.0F, 0.0F, 6, 10, 0); - /**+ - * The right pages renderer (when facing the book) + /** + * + The right pages renderer (when facing the book) */ public ModelRenderer pagesRight = (new ModelRenderer(this)).setTextureOffset(0, 10).addBox(0.0F, -4.0F, -0.99F, 5, 8, 1); - /**+ - * The left pages renderer (when facing the book) + /** + * + The left pages renderer (when facing the book) */ public ModelRenderer pagesLeft = (new ModelRenderer(this)).setTextureOffset(12, 10).addBox(0.0F, -4.0F, -0.01F, 5, 8, 1); - /**+ - * Right cover renderer (when facing the book) + /** + * + Right cover renderer (when facing the book) */ public ModelRenderer flippingPageRight = (new ModelRenderer(this)).setTextureOffset(24, 10).addBox(0.0F, -4.0F, 0.0F, 5, 8, 0); - /**+ - * Right cover renderer (when facing the book) + /** + * + Right cover renderer (when facing the book) */ public ModelRenderer flippingPageLeft = (new ModelRenderer(this)).setTextureOffset(24, 10).addBox(0.0F, -4.0F, 0.0F, 5, 8, 0); - /**+ - * The renderer of spine of the book + /** + * + The renderer of spine of the book */ public ModelRenderer bookSpine = (new ModelRenderer(this)).setTextureOffset(12, 0).addBox(-1.0F, -5.0F, 0.0F, 2, 10, 0); @@ -66,9 +69,8 @@ public class ModelBook extends ModelBase { this.bookSpine.rotateAngleY = 1.5707964F; } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -81,12 +83,11 @@ public class ModelBook extends ModelBase { this.flippingPageLeft.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float var5, float var6, Entity var7) { float f4 = (MathHelper.sin(f * 0.02F) * 0.1F + 1.25F) * f3; diff --git a/src/game/java/net/minecraft/client/model/ModelBox.java b/src/game/java/net/minecraft/client/model/ModelBox.java index 61849ed2..520e4397 100644 --- a/src/game/java/net/minecraft/client/model/ModelBox.java +++ b/src/game/java/net/minecraft/client/model/ModelBox.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/model/ModelChest.java b/src/game/java/net/minecraft/client/model/ModelChest.java index 7dc1ac4d..8bffe7bb 100644 --- a/src/game/java/net/minecraft/client/model/ModelChest.java +++ b/src/game/java/net/minecraft/client/model/ModelChest.java @@ -1,28 +1,31 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelChest extends ModelBase { - /**+ - * The chest lid in the chest's model. + /** + * + The chest lid in the chest's model. */ public ModelRenderer chestLid = (new ModelRenderer(this, 0, 0)).setTextureSize(64, 64); public ModelRenderer chestBelow; @@ -45,8 +48,8 @@ public class ModelChest extends ModelBase { this.chestBelow.rotationPointZ = 1.0F; } - /**+ - * This method renders out all parts of the chest model. + /** + * + This method renders out all parts of the chest model. */ public void renderAll() { this.chestKnob.rotateAngleX = this.chestLid.rotateAngleX; diff --git a/src/game/java/net/minecraft/client/model/ModelChicken.java b/src/game/java/net/minecraft/client/model/ModelChicken.java index 230d12df..a17592f6 100644 --- a/src/game/java/net/minecraft/client/model/ModelChicken.java +++ b/src/game/java/net/minecraft/client/model/ModelChicken.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,9 +65,8 @@ public class ModelChicken extends ModelBase { this.leftWing.setRotationPoint(4.0F, (float) (-3 + b0), 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -98,12 +100,11 @@ public class ModelChicken extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float var6, Entity var7) { this.head.rotateAngleX = f4 / 57.295776F; diff --git a/src/game/java/net/minecraft/client/model/ModelCow.java b/src/game/java/net/minecraft/client/model/ModelCow.java index a4b6b1a0..7487aec7 100644 --- a/src/game/java/net/minecraft/client/model/ModelCow.java +++ b/src/game/java/net/minecraft/client/model/ModelCow.java @@ -1,21 +1,24 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/model/ModelCreeper.java b/src/game/java/net/minecraft/client/model/ModelCreeper.java index 3a8ceca8..ab5b8012 100644 --- a/src/game/java/net/minecraft/client/model/ModelCreeper.java +++ b/src/game/java/net/minecraft/client/model/ModelCreeper.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,9 +64,8 @@ public class ModelCreeper extends ModelBase { this.leg4.setRotationPoint(2.0F, (float) (12 + b0), -4.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -75,12 +77,11 @@ public class ModelCreeper extends ModelBase { this.leg4.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { this.head.rotateAngleY = f2 / 57.295776F; diff --git a/src/game/java/net/minecraft/client/model/ModelDragon.java b/src/game/java/net/minecraft/client/model/ModelDragon.java index 428805b9..19ea9cda 100644 --- a/src/game/java/net/minecraft/client/model/ModelDragon.java +++ b/src/game/java/net/minecraft/client/model/ModelDragon.java @@ -1,6 +1,7 @@ package net.minecraft.client.model; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BACK; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRONT; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -8,22 +9,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityDragon; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -121,18 +125,8 @@ public class ModelDragon extends ModelBase { this.rearLegTip.addChild(this.rearFoot); } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. - */ - public void setLivingAnimations(EntityLivingBase var1, float var2, float var3, float f) { - this.partialTicks = f; - } - - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float var2, float var3, float var4, float var5, float var6, float f) { GlStateManager.pushMatrix(); @@ -241,11 +235,20 @@ public class ModelDragon extends ModelBase { GlStateManager.popMatrix(); } - /**+ - * Updates the rotations in the parameters for rotations greater - * than 180 degrees or less than -180 degrees. It adds or - * subtracts 360 degrees, so that the appearance is the same, - * although the numbers are then simplified to range -180 to 180 + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. + */ + public void setLivingAnimations(EntityLivingBase var1, float var2, float var3, float f) { + this.partialTicks = f; + } + + /** + * + Updates the rotations in the parameters for rotations greater than 180 + * degrees or less than -180 degrees. It adds or subtracts 360 degrees, so that + * the appearance is the same, although the numbers are then simplified to range + * -180 to 180 */ private float updateRotations(double parDouble1) { while (parDouble1 >= 180.0D) { diff --git a/src/game/java/net/minecraft/client/model/ModelEnderCrystal.java b/src/game/java/net/minecraft/client/model/ModelEnderCrystal.java index c66ecc4b..f9c5817c 100644 --- a/src/game/java/net/minecraft/client/model/ModelEnderCrystal.java +++ b/src/game/java/net/minecraft/client/model/ModelEnderCrystal.java @@ -3,30 +3,33 @@ package net.minecraft.client.model; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelEnderCrystal extends ModelBase { private ModelRenderer cube; - /**+ - * The glass model for the Ender Crystal. + /** + * + The glass model for the Ender Crystal. */ private ModelRenderer glass = new ModelRenderer(this, "glass"); private ModelRenderer base; @@ -42,9 +45,8 @@ public class ModelEnderCrystal extends ModelBase { } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity var1, float var2, float f, float f1, float var5, float var6, float f2) { GlStateManager.pushMatrix(); diff --git a/src/game/java/net/minecraft/client/model/ModelEnderMite.java b/src/game/java/net/minecraft/client/model/ModelEnderMite.java index 382151e6..643f48df 100644 --- a/src/game/java/net/minecraft/client/model/ModelEnderMite.java +++ b/src/game/java/net/minecraft/client/model/ModelEnderMite.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,9 +49,8 @@ public class ModelEnderMite extends ModelBase { } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -59,12 +61,11 @@ public class ModelEnderMite extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float var1, float var2, float f, float var4, float var5, float var6, Entity var7) { for (int i = 0; i < this.field_178713_d.length; ++i) { diff --git a/src/game/java/net/minecraft/client/model/ModelEnderman.java b/src/game/java/net/minecraft/client/model/ModelEnderman.java index 638d8cc6..3107c087 100644 --- a/src/game/java/net/minecraft/client/model/ModelEnderman.java +++ b/src/game/java/net/minecraft/client/model/ModelEnderman.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -51,12 +54,11 @@ public class ModelEnderman extends ModelBiped { this.bipedLeftLeg.setRotationPoint(2.0F, 12.0F + f, 0.0F); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelGhast.java b/src/game/java/net/minecraft/client/model/ModelGhast.java index 9538cdab..1f6343b7 100644 --- a/src/game/java/net/minecraft/client/model/ModelGhast.java +++ b/src/game/java/net/minecraft/client/model/ModelGhast.java @@ -1,27 +1,29 @@ package net.minecraft.client.model; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,23 +52,8 @@ public class ModelGhast extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. - */ - public void setRotationAngles(float var1, float var2, float f, float var4, float var5, float var6, Entity var7) { - for (int i = 0; i < this.tentacles.length; ++i) { - this.tentacles[i].rotateAngleX = 0.2F * MathHelper.sin(f * 0.3F + (float) i) + 0.4F; - } - - } - - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -80,4 +67,17 @@ public class ModelGhast extends ModelBase { GlStateManager.popMatrix(); } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float var1, float var2, float f, float var4, float var5, float var6, Entity var7) { + for (int i = 0; i < this.tentacles.length; ++i) { + this.tentacles[i].rotateAngleX = 0.2F * MathHelper.sin(f * 0.3F + (float) i) + 0.4F; + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelGuardian.java b/src/game/java/net/minecraft/client/model/ModelGuardian.java index 6d3ac9df..cf5b97a3 100644 --- a/src/game/java/net/minecraft/client/model/ModelGuardian.java +++ b/src/game/java/net/minecraft/client/model/ModelGuardian.java @@ -6,22 +6,25 @@ import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -69,21 +72,19 @@ public class ModelGuardian extends ModelBase { return 54; } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); this.guardianBody.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float var1, float var2, float f, float f1, float f2, float var6, Entity entity) { EntityGuardian entityguardian = (EntityGuardian) entity; diff --git a/src/game/java/net/minecraft/client/model/ModelHorse.java b/src/game/java/net/minecraft/client/model/ModelHorse.java index ea1e68fe..261363e4 100644 --- a/src/game/java/net/minecraft/client/model/ModelHorse.java +++ b/src/game/java/net/minecraft/client/model/ModelHorse.java @@ -6,22 +6,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -208,9 +211,8 @@ public class ModelHorse extends ModelBase { this.setBoxRotation(this.horseFaceRopes, 0.5235988F, 0.0F, 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float var2, float var3, float var4, float var5, float var6, float f) { EntityHorse entityhorse = (EntityHorse) entity; @@ -303,9 +305,8 @@ public class ModelHorse extends ModelBase { } - /**+ - * Sets the rotations for a ModelRenderer in the ModelHorse - * class. + /** + * + Sets the rotations for a ModelRenderer in the ModelHorse class. */ private void setBoxRotation(ModelRenderer parModelRenderer, float parFloat1, float parFloat2, float parFloat3) { parModelRenderer.rotateAngleX = parFloat1; @@ -313,26 +314,10 @@ public class ModelHorse extends ModelBase { parModelRenderer.rotateAngleZ = parFloat3; } - /**+ - * Fixes and offsets a rotation in the ModelHorse class. - */ - private float updateHorseRotation(float parFloat1, float parFloat2, float parFloat3) { - float f; - for (f = parFloat2 - parFloat1; f < -180.0F; f += 360.0F) { - ; - } - - while (f >= 180.0F) { - f -= 360.0F; - } - - return parFloat1 + parFloat3 * f; - } - - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbaseIn, float partialTickTime, float parFloat2, float parFloat3) { @@ -554,4 +539,20 @@ public class ModelHorse extends ModelBase { this.tailMiddle.rotateAngleX = f12; this.tailTip.rotateAngleX = -0.2618F + f12; } + + /** + * + Fixes and offsets a rotation in the ModelHorse class. + */ + private float updateHorseRotation(float parFloat1, float parFloat2, float parFloat3) { + float f; + for (f = parFloat2 - parFloat1; f < -180.0F; f += 360.0F) { + ; + } + + while (f >= 180.0F) { + f -= 360.0F; + } + + return parFloat1 + parFloat3 * f; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelHumanoidHead.java b/src/game/java/net/minecraft/client/model/ModelHumanoidHead.java index a352e61e..3a4e08b4 100644 --- a/src/game/java/net/minecraft/client/model/ModelHumanoidHead.java +++ b/src/game/java/net/minecraft/client/model/ModelHumanoidHead.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,21 +34,19 @@ public class ModelHumanoidHead extends ModelSkeletonHead { this.head.setRotationPoint(0.0F, 0.0F, 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); this.head.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelIronGolem.java b/src/game/java/net/minecraft/client/model/ModelIronGolem.java index 4d71f43d..f8390676 100644 --- a/src/game/java/net/minecraft/client/model/ModelIronGolem.java +++ b/src/game/java/net/minecraft/client/model/ModelIronGolem.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityIronGolem; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -66,9 +69,12 @@ public class ModelIronGolem extends ModelBase { this.ironGolemRightLeg.addBox(-3.5F, -3.0F, -3.0F, 6, 16, 5, parFloat1); } - /**+ - * Sets the models various rotation angles then renders the - * model. + private float func_78172_a(float parFloat1, float parFloat2) { + return (Math.abs(parFloat1 % parFloat2 - parFloat2 * 0.5F) - parFloat2 * 0.25F) / (parFloat2 * 0.25F); + } + + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -80,26 +86,10 @@ public class ModelIronGolem extends ModelBase { this.ironGolemLeftArm.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. - */ - public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { - this.ironGolemHead.rotateAngleY = f2 / 57.295776F; - this.ironGolemHead.rotateAngleX = f3 / 57.295776F; - this.ironGolemLeftLeg.rotateAngleX = -1.5F * this.func_78172_a(f, 13.0F) * f1; - this.ironGolemRightLeg.rotateAngleX = 1.5F * this.func_78172_a(f, 13.0F) * f1; - this.ironGolemLeftLeg.rotateAngleY = 0.0F; - this.ironGolemRightLeg.rotateAngleY = 0.0F; - } - - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float f, float f1, float f2) { EntityIronGolem entityirongolem = (EntityIronGolem) entitylivingbase; @@ -120,7 +110,18 @@ public class ModelIronGolem extends ModelBase { } - private float func_78172_a(float parFloat1, float parFloat2) { - return (Math.abs(parFloat1 % parFloat2 - parFloat2 * 0.5F) - parFloat2 * 0.25F) / (parFloat2 * 0.25F); + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { + this.ironGolemHead.rotateAngleY = f2 / 57.295776F; + this.ironGolemHead.rotateAngleX = f3 / 57.295776F; + this.ironGolemLeftLeg.rotateAngleX = -1.5F * this.func_78172_a(f, 13.0F) * f1; + this.ironGolemRightLeg.rotateAngleX = 1.5F * this.func_78172_a(f, 13.0F) * f1; + this.ironGolemLeftLeg.rotateAngleY = 0.0F; + this.ironGolemRightLeg.rotateAngleY = 0.0F; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelLargeChest.java b/src/game/java/net/minecraft/client/model/ModelLargeChest.java index c522654f..1ccd207c 100644 --- a/src/game/java/net/minecraft/client/model/ModelLargeChest.java +++ b/src/game/java/net/minecraft/client/model/ModelLargeChest.java @@ -1,21 +1,24 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/model/ModelLeashKnot.java b/src/game/java/net/minecraft/client/model/ModelLeashKnot.java index 717155d3..66c9931d 100644 --- a/src/game/java/net/minecraft/client/model/ModelLeashKnot.java +++ b/src/game/java/net/minecraft/client/model/ModelLeashKnot.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,21 +40,19 @@ public class ModelLeashKnot extends ModelBase { this.field_110723_a.setRotationPoint(0.0F, 0.0F, 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); this.field_110723_a.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelMagmaCube.java b/src/game/java/net/minecraft/client/model/ModelMagmaCube.java index 94afee3d..9d40c598 100644 --- a/src/game/java/net/minecraft/client/model/ModelMagmaCube.java +++ b/src/game/java/net/minecraft/client/model/ModelMagmaCube.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityMagmaCube; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,10 +51,23 @@ public class ModelMagmaCube extends ModelBase { this.core.addBox(-2.0F, 18.0F, -2.0F, 4, 4, 4); } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Sets the models various rotation angles then renders the model. + */ + public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { + this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); + this.core.render(f5); + + for (int i = 0; i < this.segments.length; ++i) { + this.segments[i].render(f5); + } + + } + + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float var2, float var3, float f) { EntityMagmaCube entitymagmacube = (EntityMagmaCube) entitylivingbase; @@ -66,18 +82,4 @@ public class ModelMagmaCube extends ModelBase { } } - - /**+ - * Sets the models various rotation angles then renders the - * model. - */ - public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); - this.core.render(f5); - - for (int i = 0; i < this.segments.length; ++i) { - this.segments[i].render(f5); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelMinecart.java b/src/game/java/net/minecraft/client/model/ModelMinecart.java index 3d4676cb..d02c55f1 100644 --- a/src/game/java/net/minecraft/client/model/ModelMinecart.java +++ b/src/game/java/net/minecraft/client/model/ModelMinecart.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,9 +58,8 @@ public class ModelMinecart extends ModelBase { this.sideModels[5].rotateAngleX = -1.5707964F; } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity var1, float var2, float var3, float f, float var5, float var6, float f1) { this.sideModels[5].rotationPointY = 4.0F - f; diff --git a/src/game/java/net/minecraft/client/model/ModelNetherCreeper.java b/src/game/java/net/minecraft/client/model/ModelNetherCreeper.java new file mode 100644 index 00000000..b3e490ce --- /dev/null +++ b/src/game/java/net/minecraft/client/model/ModelNetherCreeper.java @@ -0,0 +1,95 @@ +package net.minecraft.client.model; + +import net.minecraft.entity.Entity; +import net.minecraft.util.MathHelper; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class ModelNetherCreeper extends ModelBase { + public ModelRenderer head; + public ModelRenderer creeperArmor; + public ModelRenderer body; + public ModelRenderer leg1; + public ModelRenderer leg2; + public ModelRenderer leg3; + public ModelRenderer leg4; + + public ModelNetherCreeper() { + this(0.0F); + } + + public ModelNetherCreeper(float parFloat1) { + byte b0 = 6; + this.head = new ModelRenderer(this, 0, 0); + this.head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, parFloat1); + this.head.setRotationPoint(0.0F, (float) b0, 0.0F); + this.creeperArmor = new ModelRenderer(this, 32, 0); + this.creeperArmor.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, parFloat1 + 0.5F); + this.creeperArmor.setRotationPoint(0.0F, (float) b0, 0.0F); + this.body = new ModelRenderer(this, 16, 16); + this.body.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, parFloat1); + this.body.setRotationPoint(0.0F, (float) b0, 0.0F); + this.leg1 = new ModelRenderer(this, 0, 16); + this.leg1.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, parFloat1); + this.leg1.setRotationPoint(-2.0F, (float) (12 + b0), 4.0F); + this.leg2 = new ModelRenderer(this, 0, 16); + this.leg2.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, parFloat1); + this.leg2.setRotationPoint(2.0F, (float) (12 + b0), 4.0F); + this.leg3 = new ModelRenderer(this, 0, 16); + this.leg3.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, parFloat1); + this.leg3.setRotationPoint(-2.0F, (float) (12 + b0), -4.0F); + this.leg4 = new ModelRenderer(this, 0, 16); + this.leg4.addBox(-2.0F, 0.0F, -2.0F, 4, 6, 4, parFloat1); + this.leg4.setRotationPoint(2.0F, (float) (12 + b0), -4.0F); + + } + + /** + * + Sets the models various rotation angles then renders the model. + */ + public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { + this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); + this.head.render(f5); + this.body.render(f5); + this.leg1.render(f5); + this.leg2.render(f5); + this.leg3.render(f5); + this.leg4.render(f5); + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { + this.head.rotateAngleY = f2 / 57.295776F; + this.head.rotateAngleX = f3 / 57.295776F; + this.leg1.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.4F * f1; + this.leg2.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.4F * f1; + this.leg3.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.4F * f1; + this.leg4.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.4F * f1; + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelOcelot.java b/src/game/java/net/minecraft/client/model/ModelOcelot.java index a4794538..1d737343 100644 --- a/src/game/java/net/minecraft/client/model/ModelOcelot.java +++ b/src/game/java/net/minecraft/client/model/ModelOcelot.java @@ -6,22 +6,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityOcelot; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -72,9 +75,8 @@ public class ModelOcelot extends ModelBase { this.ocelotFrontRightLeg.setRotationPoint(-1.2F, 13.8F, -5.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -109,43 +111,10 @@ public class ModelOcelot extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. - */ - public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { - this.ocelotHead.rotateAngleX = f3 / 57.295776F; - this.ocelotHead.rotateAngleY = f2 / 57.295776F; - if (this.field_78163_i != 3) { - this.ocelotBody.rotateAngleX = 1.5707964F; - if (this.field_78163_i == 2) { - this.ocelotBackLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.0F * f1; - this.ocelotBackRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 0.3F) * 1.0F * f1; - this.ocelotFrontLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F + 0.3F) * 1.0F * f1; - this.ocelotFrontRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.0F * f1; - this.ocelotTail2.rotateAngleX = 1.7278761F + 0.31415927F * MathHelper.cos(f) * f1; - } else { - this.ocelotBackLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.0F * f1; - this.ocelotBackRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.0F * f1; - this.ocelotFrontLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.0F * f1; - this.ocelotFrontRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.0F * f1; - if (this.field_78163_i == 1) { - this.ocelotTail2.rotateAngleX = 1.7278761F + 0.7853982F * MathHelper.cos(f) * f1; - } else { - this.ocelotTail2.rotateAngleX = 1.7278761F + 0.47123894F * MathHelper.cos(f) * f1; - } - } - } - - } - - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float var2, float var3, float var4) { EntityOcelot entityocelot = (EntityOcelot) entitylivingbase; @@ -201,4 +170,36 @@ public class ModelOcelot extends ModelBase { } } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { + this.ocelotHead.rotateAngleX = f3 / 57.295776F; + this.ocelotHead.rotateAngleY = f2 / 57.295776F; + if (this.field_78163_i != 3) { + this.ocelotBody.rotateAngleX = 1.5707964F; + if (this.field_78163_i == 2) { + this.ocelotBackLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.0F * f1; + this.ocelotBackRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 0.3F) * 1.0F * f1; + this.ocelotFrontLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F + 0.3F) * 1.0F * f1; + this.ocelotFrontRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.0F * f1; + this.ocelotTail2.rotateAngleX = 1.7278761F + 0.31415927F * MathHelper.cos(f) * f1; + } else { + this.ocelotBackLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.0F * f1; + this.ocelotBackRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.0F * f1; + this.ocelotFrontLeftLeg.rotateAngleX = MathHelper.cos(f * 0.6662F + 3.1415927F) * 1.0F * f1; + this.ocelotFrontRightLeg.rotateAngleX = MathHelper.cos(f * 0.6662F) * 1.0F * f1; + if (this.field_78163_i == 1) { + this.ocelotTail2.rotateAngleX = 1.7278761F + 0.7853982F * MathHelper.cos(f) * f1; + } else { + this.ocelotTail2.rotateAngleX = 1.7278761F + 0.47123894F * MathHelper.cos(f) * f1; + } + } + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelPig.java b/src/game/java/net/minecraft/client/model/ModelPig.java index a3f4e265..1d87e209 100644 --- a/src/game/java/net/minecraft/client/model/ModelPig.java +++ b/src/game/java/net/minecraft/client/model/ModelPig.java @@ -1,21 +1,24 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/model/ModelPlayer.java b/src/game/java/net/minecraft/client/model/ModelPlayer.java index c3f2ec5a..78a487b4 100644 --- a/src/game/java/net/minecraft/client/model/ModelPlayer.java +++ b/src/game/java/net/minecraft/client/model/ModelPlayer.java @@ -1,26 +1,30 @@ package net.minecraft.client.model; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -82,9 +86,19 @@ public class ModelPlayer extends ModelBiped { this.bipedBodyWear.setRotationPoint(0.0F, 0.0F, 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + public void postRenderArm(float f) { + if (this.smallArms) { + ++this.bipedRightArm.rotationPointX; + this.bipedRightArm.postRender(f); + --this.bipedRightArm.rotationPointX; + } else { + this.bipedRightArm.postRender(f); + } + + } + + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); @@ -113,13 +127,6 @@ public class ModelPlayer extends ModelBiped { GlStateManager.popMatrix(); } - public void renderDeadmau5Head(float parFloat1) { - copyModelAngles(this.bipedHead, this.bipedDeadmau5Head); - this.bipedDeadmau5Head.rotationPointX = 0.0F; - this.bipedDeadmau5Head.rotationPointY = 0.0F; - this.bipedDeadmau5Head.render(parFloat1); - } - public void renderCape(float parFloat1) { GlStateManager.matrixMode(GL_TEXTURE); GlStateManager.pushMatrix(); @@ -131,12 +138,39 @@ public class ModelPlayer extends ModelBiped { GlStateManager.matrixMode(GL_MODELVIEW); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + public void renderDeadmau5Head(float parFloat1) { + copyModelAngles(this.bipedHead, this.bipedDeadmau5Head); + this.bipedDeadmau5Head.rotationPointX = 0.0F; + this.bipedDeadmau5Head.rotationPointY = 0.0F; + this.bipedDeadmau5Head.render(parFloat1); + } + + public void renderLeftArm() { + this.bipedLeftArm.render(0.0625F); + this.bipedLeftArmwear.render(0.0625F); + } + + public void renderRightArm() { + this.bipedRightArm.render(0.0625F); + this.bipedRightArmwear.render(0.0625F); + } + + public void setInvisible(boolean flag) { + super.setInvisible(flag); + this.bipedLeftArmwear.showModel = flag; + this.bipedRightArmwear.showModel = flag; + this.bipedLeftLegwear.showModel = flag; + this.bipedRightLegwear.showModel = flag; + this.bipedBodyWear.showModel = flag; + this.bipedCape.showModel = flag; + this.bipedDeadmau5Head.showModel = flag; + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -152,36 +186,4 @@ public class ModelPlayer extends ModelBiped { } } - - public void renderRightArm() { - this.bipedRightArm.render(0.0625F); - this.bipedRightArmwear.render(0.0625F); - } - - public void renderLeftArm() { - this.bipedLeftArm.render(0.0625F); - this.bipedLeftArmwear.render(0.0625F); - } - - public void setInvisible(boolean flag) { - super.setInvisible(flag); - this.bipedLeftArmwear.showModel = flag; - this.bipedRightArmwear.showModel = flag; - this.bipedLeftLegwear.showModel = flag; - this.bipedRightLegwear.showModel = flag; - this.bipedBodyWear.showModel = flag; - this.bipedCape.showModel = flag; - this.bipedDeadmau5Head.showModel = flag; - } - - public void postRenderArm(float f) { - if (this.smallArms) { - ++this.bipedRightArm.rotationPointX; - this.bipedRightArm.postRender(f); - --this.bipedRightArm.rotationPointX; - } else { - this.bipedRightArm.postRender(f); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelQuadruped.java b/src/game/java/net/minecraft/client/model/ModelQuadruped.java index f785c78f..80e2a92f 100644 --- a/src/game/java/net/minecraft/client/model/ModelQuadruped.java +++ b/src/game/java/net/minecraft/client/model/ModelQuadruped.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,9 +57,8 @@ public class ModelQuadruped extends ModelBase { this.leg4.setRotationPoint(3.0F, (float) (24 - parInt1), -5.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -86,12 +88,11 @@ public class ModelQuadruped extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { float f4 = 57.295776F; diff --git a/src/game/java/net/minecraft/client/model/ModelRabbit.java b/src/game/java/net/minecraft/client/model/ModelRabbit.java index 67d394f9..e75dacca 100644 --- a/src/game/java/net/minecraft/client/model/ModelRabbit.java +++ b/src/game/java/net/minecraft/client/model/ModelRabbit.java @@ -6,22 +6,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityRabbit; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -109,15 +112,8 @@ public class ModelRabbit extends ModelBase { this.setRotationOffset(this.rabbitNose, 0.0F, 0.0F, 0.0F); } - private void setRotationOffset(ModelRenderer parModelRenderer, float parFloat1, float parFloat2, float parFloat3) { - parModelRenderer.rotateAngleX = parFloat1; - parModelRenderer.rotateAngleY = parFloat2; - parModelRenderer.rotateAngleZ = parFloat3; - } - - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -159,12 +155,19 @@ public class ModelRabbit extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. + */ + public void setLivingAnimations(EntityLivingBase var1, float var2, float var3, float var4) { + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float var1, float var2, float f, float f1, float f2, float var6, Entity entity) { float f3 = f - (float) entity.ticksExisted; @@ -183,11 +186,9 @@ public class ModelRabbit extends ModelBase { * 0.017453292F; } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. - */ - public void setLivingAnimations(EntityLivingBase var1, float var2, float var3, float var4) { + private void setRotationOffset(ModelRenderer parModelRenderer, float parFloat1, float parFloat2, float parFloat3) { + parModelRenderer.rotateAngleX = parFloat1; + parModelRenderer.rotateAngleY = parFloat2; + parModelRenderer.rotateAngleZ = parFloat3; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelRenderer.java b/src/game/java/net/minecraft/client/model/ModelRenderer.java index c8981fc9..c0e9e25f 100644 --- a/src/game/java/net/minecraft/client/model/ModelRenderer.java +++ b/src/game/java/net/minecraft/client/model/ModelRenderer.java @@ -1,6 +1,6 @@ package net.minecraft.client.model; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE; import java.util.List; @@ -12,22 +12,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.Tessellator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,6 +59,15 @@ public class ModelRenderer { public float offsetY; public float offsetZ; + public ModelRenderer(ModelBase model) { + this(model, (String) null); + } + + public ModelRenderer(ModelBase model, int texOffX, int texOffY) { + this(model); + this.setTextureOffset(texOffX, texOffY); + } + public ModelRenderer(ModelBase model, String boxNameIn) { this.textureWidth = 64.0F; this.textureHeight = 32.0F; @@ -67,36 +79,40 @@ public class ModelRenderer { this.setTextureSize(model.textureWidth, model.textureHeight); } - public ModelRenderer(ModelBase model) { - this(model, (String) null); - } - - public ModelRenderer(ModelBase model, int texOffX, int texOffY) { - this(model); - this.setTextureOffset(texOffX, texOffY); - } - - /**+ - * Sets the current box's rotation points and rotation angles to - * another box. + /** + * + Creates a textured box. Args: originX, originY, originZ, width, height, + * depth, scaleFactor. */ - public void addChild(ModelRenderer renderer) { - if (this.childModels == null) { - this.childModels = Lists.newArrayList(); - } - - this.childModels.add(renderer); - } - - public ModelRenderer setTextureOffset(int x, int y) { - this.textureOffsetX = x; - this.textureOffsetY = y; + public ModelRenderer addBox(float offX, float offY, float offZ, int width, int height, int depth) { + this.cubeList.add(new ModelBox(this, this.textureOffsetX, this.textureOffsetY, offX, offY, offZ, width, height, + depth, 0.0F)); return this; } - /**+ - * Creates a textured box. Args: originX, originY, originZ, - * width, height, depth, scaleFactor. + /** + * + Creates a textured box. Args: originX, originY, originZ, width, height, + * depth, scaleFactor. + */ + public ModelRenderer addBox(float parFloat1, float parFloat2, float parFloat3, int parInt1, int parInt2, + int parInt3, boolean parFlag) { + this.cubeList.add(new ModelBox(this, this.textureOffsetX, this.textureOffsetY, parFloat1, parFloat2, parFloat3, + parInt1, parInt2, parInt3, 0.0F, parFlag)); + return this; + } + + /** + * + Creates a textured box. Args: originX, originY, originZ, width, height, + * depth, scaleFactor. + */ + public void addBox(float width, float height, float depth, int scaleFactor, int parInt2, int parInt3, + float parFloat4) { + this.cubeList.add(new ModelBox(this, this.textureOffsetX, this.textureOffsetY, width, height, depth, + scaleFactor, parInt2, parInt3, parFloat4)); + } + + /** + * + Creates a textured box. Args: originX, originY, originZ, width, height, + * depth, scaleFactor. */ public ModelRenderer addBox(String partName, float offX, float offY, float offZ, int width, int height, int depth) { partName = this.boxName + "." + partName; @@ -107,41 +123,66 @@ public class ModelRenderer { return this; } - /**+ - * Creates a textured box. Args: originX, originY, originZ, - * width, height, depth, scaleFactor. + /** + * + Sets the current box's rotation points and rotation angles to another box. */ - public ModelRenderer addBox(float offX, float offY, float offZ, int width, int height, int depth) { - this.cubeList.add(new ModelBox(this, this.textureOffsetX, this.textureOffsetY, offX, offY, offZ, width, height, - depth, 0.0F)); - return this; + public void addChild(ModelRenderer renderer) { + if (this.childModels == null) { + this.childModels = Lists.newArrayList(); + } + + this.childModels.add(renderer); } - /**+ - * Creates a textured box. Args: originX, originY, originZ, - * width, height, depth, scaleFactor. + /** + * + Compiles a GL display list for this model */ - public ModelRenderer addBox(float parFloat1, float parFloat2, float parFloat3, int parInt1, int parInt2, - int parInt3, boolean parFlag) { - this.cubeList.add(new ModelBox(this, this.textureOffsetX, this.textureOffsetY, parFloat1, parFloat2, parFloat3, - parInt1, parInt2, parInt3, 0.0F, parFlag)); - return this; + private void compileDisplayList(float scale) { + this.displayList = GLAllocation.generateDisplayLists(); + EaglercraftGPU.glNewList(this.displayList, GL_COMPILE); + WorldRenderer worldrenderer = Tessellator.getInstance().getWorldRenderer(); + + for (int i = 0; i < this.cubeList.size(); ++i) { + ((ModelBox) this.cubeList.get(i)).render(worldrenderer, scale); + } + + EaglercraftGPU.glEndList(); + this.compiled = true; } - /**+ - * Creates a textured box. Args: originX, originY, originZ, - * width, height, depth, scaleFactor. + /** + * + Allows the changing of Angles after a box has been rendered */ - public void addBox(float width, float height, float depth, int scaleFactor, int parInt2, int parInt3, - float parFloat4) { - this.cubeList.add(new ModelBox(this, this.textureOffsetX, this.textureOffsetY, width, height, depth, - scaleFactor, parInt2, parInt3, parFloat4)); - } + public void postRender(float scale) { + if (!this.isHidden) { + if (this.showModel) { + if (!this.compiled) { + this.compileDisplayList(scale); + } - public void setRotationPoint(float rotationPointXIn, float rotationPointYIn, float rotationPointZIn) { - this.rotationPointX = rotationPointXIn; - this.rotationPointY = rotationPointYIn; - this.rotationPointZ = rotationPointZIn; + if (this.rotateAngleX == 0.0F && this.rotateAngleY == 0.0F && this.rotateAngleZ == 0.0F) { + if (this.rotationPointX != 0.0F || this.rotationPointY != 0.0F || this.rotationPointZ != 0.0F) { + GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, + this.rotationPointZ * scale); + } + } else { + GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, + this.rotationPointZ * scale); + if (this.rotateAngleZ != 0.0F) { + GlStateManager.rotate(this.rotateAngleZ * 57.295776F, 0.0F, 0.0F, 1.0F); + } + + if (this.rotateAngleY != 0.0F) { + GlStateManager.rotate(this.rotateAngleY * 57.295776F, 0.0F, 1.0F, 0.0F); + } + + if (this.rotateAngleX != 0.0F) { + GlStateManager.rotate(this.rotateAngleX * 57.295776F, 1.0F, 0.0F, 0.0F); + } + } + + } + } } public void render(float parFloat1) { @@ -232,59 +273,20 @@ public class ModelRenderer { } } - /**+ - * Allows the changing of Angles after a box has been rendered - */ - public void postRender(float scale) { - if (!this.isHidden) { - if (this.showModel) { - if (!this.compiled) { - this.compileDisplayList(scale); - } - - if (this.rotateAngleX == 0.0F && this.rotateAngleY == 0.0F && this.rotateAngleZ == 0.0F) { - if (this.rotationPointX != 0.0F || this.rotationPointY != 0.0F || this.rotationPointZ != 0.0F) { - GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, - this.rotationPointZ * scale); - } - } else { - GlStateManager.translate(this.rotationPointX * scale, this.rotationPointY * scale, - this.rotationPointZ * scale); - if (this.rotateAngleZ != 0.0F) { - GlStateManager.rotate(this.rotateAngleZ * 57.295776F, 0.0F, 0.0F, 1.0F); - } - - if (this.rotateAngleY != 0.0F) { - GlStateManager.rotate(this.rotateAngleY * 57.295776F, 0.0F, 1.0F, 0.0F); - } - - if (this.rotateAngleX != 0.0F) { - GlStateManager.rotate(this.rotateAngleX * 57.295776F, 1.0F, 0.0F, 0.0F); - } - } - - } - } + public void setRotationPoint(float rotationPointXIn, float rotationPointYIn, float rotationPointZIn) { + this.rotationPointX = rotationPointXIn; + this.rotationPointY = rotationPointYIn; + this.rotationPointZ = rotationPointZIn; } - /**+ - * Compiles a GL display list for this model - */ - private void compileDisplayList(float scale) { - this.displayList = GLAllocation.generateDisplayLists(); - EaglercraftGPU.glNewList(this.displayList, GL_COMPILE); - WorldRenderer worldrenderer = Tessellator.getInstance().getWorldRenderer(); - - for (int i = 0; i < this.cubeList.size(); ++i) { - ((ModelBox) this.cubeList.get(i)).render(worldrenderer, scale); - } - - EaglercraftGPU.glEndList(); - this.compiled = true; + public ModelRenderer setTextureOffset(int x, int y) { + this.textureOffsetX = x; + this.textureOffsetY = y; + return this; } - /**+ - * Returns the model renderer with the new texture parameters. + /** + * + Returns the model renderer with the new texture parameters. */ public ModelRenderer setTextureSize(int textureWidthIn, int textureHeightIn) { this.textureWidth = (float) textureWidthIn; diff --git a/src/game/java/net/minecraft/client/model/ModelSheep1.java b/src/game/java/net/minecraft/client/model/ModelSheep1.java index 2ec77dfb..2e6edd4a 100644 --- a/src/game/java/net/minecraft/client/model/ModelSheep1.java +++ b/src/game/java/net/minecraft/client/model/ModelSheep1.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntitySheep; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,10 +53,10 @@ public class ModelSheep1 extends ModelQuadruped { this.leg4.setRotationPoint(3.0F, 12.0F, -5.0F); } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float f, float f1, float f2) { super.setLivingAnimations(entitylivingbase, f, f1, f2); @@ -61,12 +64,11 @@ public class ModelSheep1 extends ModelQuadruped { this.headRotationAngleX = ((EntitySheep) entitylivingbase).getHeadRotationAngleX(f2); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelSheep2.java b/src/game/java/net/minecraft/client/model/ModelSheep2.java index e7a7e901..f3d97cd3 100644 --- a/src/game/java/net/minecraft/client/model/ModelSheep2.java +++ b/src/game/java/net/minecraft/client/model/ModelSheep2.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntitySheep; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,10 +40,10 @@ public class ModelSheep2 extends ModelQuadruped { this.body.setRotationPoint(0.0F, 5.0F, 2.0F); } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float f, float f1, float f2) { super.setLivingAnimations(entitylivingbase, f, f1, f2); @@ -48,12 +51,11 @@ public class ModelSheep2 extends ModelQuadruped { this.headRotationAngleX = ((EntitySheep) entitylivingbase).getHeadRotationAngleX(f2); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelSign.java b/src/game/java/net/minecraft/client/model/ModelSign.java index fd6ebfcc..9bd39b1d 100644 --- a/src/game/java/net/minecraft/client/model/ModelSign.java +++ b/src/game/java/net/minecraft/client/model/ModelSign.java @@ -1,28 +1,31 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelSign extends ModelBase { - /**+ - * The board on a sign that has the writing on it. + /** + * + The board on a sign that has the writing on it. */ public ModelRenderer signBoard = new ModelRenderer(this, 0, 0); public ModelRenderer signStick; @@ -33,8 +36,8 @@ public class ModelSign extends ModelBase { this.signStick.addBox(-1.0F, -2.0F, -1.0F, 2, 14, 2, 0.0F); } - /**+ - * Renders the sign model through TileEntitySignRenderer + /** + * + Renders the sign model through TileEntitySignRenderer */ public void renderSign() { this.signBoard.render(0.0625F); diff --git a/src/game/java/net/minecraft/client/model/ModelSilverfish.java b/src/game/java/net/minecraft/client/model/ModelSilverfish.java index 5fc9233a..3240d372 100644 --- a/src/game/java/net/minecraft/client/model/ModelSilverfish.java +++ b/src/game/java/net/minecraft/client/model/ModelSilverfish.java @@ -3,44 +3,46 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelSilverfish extends ModelBase { - /**+ - * The body parts of the silverfish's model. + /** + * + The widths, heights, and lengths for the silverfish model boxes. + */ + private static final int[][] silverfishBoxLength = new int[][] { { 3, 2, 2 }, { 4, 3, 2 }, { 6, 4, 3 }, { 3, 3, 3 }, + { 2, 2, 3 }, { 2, 1, 2 }, { 1, 1, 2 } }; + /** + * + The texture positions for the silverfish's model's boxes. + */ + private static final int[][] silverfishTexturePositions = new int[][] { { 0, 0 }, { 0, 4 }, { 0, 9 }, { 0, 16 }, + { 0, 22 }, { 11, 0 }, { 13, 4 } }; + /** + * + The body parts of the silverfish's model. */ private ModelRenderer[] silverfishBodyParts = new ModelRenderer[7]; private ModelRenderer[] silverfishWings; private float[] field_78170_c = new float[7]; - /**+ - * The widths, heights, and lengths for the silverfish model - * boxes. - */ - private static final int[][] silverfishBoxLength = new int[][] { { 3, 2, 2 }, { 4, 3, 2 }, { 6, 4, 3 }, { 3, 3, 3 }, - { 2, 2, 3 }, { 2, 1, 2 }, { 1, 1, 2 } }; - /**+ - * The texture positions for the silverfish's model's boxes. - */ - private static final int[][] silverfishTexturePositions = new int[][] { { 0, 0 }, { 0, 4 }, { 0, 9 }, { 0, 16 }, - { 0, 22 }, { 11, 0 }, { 13, 4 } }; public ModelSilverfish() { float f = -3.5F; @@ -73,9 +75,8 @@ public class ModelSilverfish extends ModelBase { this.silverfishWings[2].setRotationPoint(0.0F, 19.0F, this.field_78170_c[1]); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -90,12 +91,11 @@ public class ModelSilverfish extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float var1, float var2, float f, float var4, float var5, float var6, Entity var7) { for (int i = 0; i < this.silverfishBodyParts.length; ++i) { diff --git a/src/game/java/net/minecraft/client/model/ModelSkeleton.java b/src/game/java/net/minecraft/client/model/ModelSkeleton.java index e1d16aeb..97474629 100644 --- a/src/game/java/net/minecraft/client/model/ModelSkeleton.java +++ b/src/game/java/net/minecraft/client/model/ModelSkeleton.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntitySkeleton; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,22 +53,21 @@ public class ModelSkeleton extends ModelZombie { } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float f, float f1, float f2) { this.aimedBow = ((EntitySkeleton) entitylivingbase).getSkeletonType() == 1; super.setLivingAnimations(entitylivingbase, f, f1, f2); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelSkeletonHead.java b/src/game/java/net/minecraft/client/model/ModelSkeletonHead.java index ba1aec6a..7ee1bba4 100644 --- a/src/game/java/net/minecraft/client/model/ModelSkeletonHead.java +++ b/src/game/java/net/minecraft/client/model/ModelSkeletonHead.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,21 +40,19 @@ public class ModelSkeletonHead extends ModelBase { this.skeletonHead.setRotationPoint(0.0F, 0.0F, 0.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); this.skeletonHead.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelSlime.java b/src/game/java/net/minecraft/client/model/ModelSlime.java index d1e64cb5..c887799a 100644 --- a/src/game/java/net/minecraft/client/model/ModelSlime.java +++ b/src/game/java/net/minecraft/client/model/ModelSlime.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,9 +47,8 @@ public class ModelSlime extends ModelBase { } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelSnowMan.java b/src/game/java/net/minecraft/client/model/ModelSnowMan.java index f91f4056..9c480fd0 100644 --- a/src/game/java/net/minecraft/client/model/ModelSnowMan.java +++ b/src/game/java/net/minecraft/client/model/ModelSnowMan.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,12 +53,23 @@ public class ModelSnowMan extends ModelBase { this.bottomBody.setRotationPoint(0.0F, 0.0F + f + 20.0F, 0.0F); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the models various rotation angles then renders the model. + */ + public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { + this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); + this.body.render(f5); + this.bottomBody.render(f5); + this.head.render(f5); + this.rightHand.render(f5); + this.leftHand.render(f5); + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -73,17 +87,4 @@ public class ModelSnowMan extends ModelBase { this.leftHand.rotationPointX = -f7 * 5.0F; this.leftHand.rotationPointZ = f6 * 5.0F; } - - /**+ - * Sets the models various rotation angles then renders the - * model. - */ - public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { - this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); - this.body.render(f5); - this.bottomBody.render(f5); - this.head.render(f5); - this.rightHand.render(f5); - this.leftHand.render(f5); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelSpider.java b/src/game/java/net/minecraft/client/model/ModelSpider.java index b04aec87..67339047 100644 --- a/src/game/java/net/minecraft/client/model/ModelSpider.java +++ b/src/game/java/net/minecraft/client/model/ModelSpider.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -74,9 +77,8 @@ public class ModelSpider extends ModelBase { this.spiderLeg8.setRotationPoint(4.0F, (float) b0, -1.0F); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -93,12 +95,11 @@ public class ModelSpider extends ModelBase { this.spiderLeg8.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { this.spiderHead.rotateAngleY = f2 / 57.295776F; diff --git a/src/game/java/net/minecraft/client/model/ModelSquid.java b/src/game/java/net/minecraft/client/model/ModelSquid.java index ed4ce75e..f2d8b091 100644 --- a/src/game/java/net/minecraft/client/model/ModelSquid.java +++ b/src/game/java/net/minecraft/client/model/ModelSquid.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,23 +50,8 @@ public class ModelSquid extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. - */ - public void setRotationAngles(float var1, float var2, float f, float var4, float var5, float var6, Entity var7) { - for (int i = 0; i < this.squidTentacles.length; ++i) { - this.squidTentacles[i].rotateAngleX = f; - } - - } - - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -74,4 +62,17 @@ public class ModelSquid extends ModelBase { } } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float var1, float var2, float f, float var4, float var5, float var6, Entity var7) { + for (int i = 0; i < this.squidTentacles.length; ++i) { + this.squidTentacles[i].rotateAngleX = f; + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelVillager.java b/src/game/java/net/minecraft/client/model/ModelVillager.java index e6b70aac..f203a2b7 100644 --- a/src/game/java/net/minecraft/client/model/ModelVillager.java +++ b/src/game/java/net/minecraft/client/model/ModelVillager.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,9 +64,8 @@ public class ModelVillager extends ModelBase { this.leftVillagerLeg.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, parFloat1); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -74,12 +76,11 @@ public class ModelVillager extends ModelBase { this.villagerArms.render(f5); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float var3, float f2, float f3, float var6, Entity var7) { this.villagerHead.rotateAngleY = f2 / 57.295776F; diff --git a/src/game/java/net/minecraft/client/model/ModelWitch.java b/src/game/java/net/minecraft/client/model/ModelWitch.java index f7defc4b..68509530 100644 --- a/src/game/java/net/minecraft/client/model/ModelWitch.java +++ b/src/game/java/net/minecraft/client/model/ModelWitch.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -57,12 +60,11 @@ public class ModelWitch extends ModelVillager { modelrenderer1.addChild(modelrenderer2); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelWither.java b/src/game/java/net/minecraft/client/model/ModelWither.java index 3deeed33..4e2aa449 100644 --- a/src/game/java/net/minecraft/client/model/ModelWither.java +++ b/src/game/java/net/minecraft/client/model/ModelWither.java @@ -5,22 +5,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.boss.EntityWither; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,9 +59,8 @@ public class ModelWither extends ModelBase { this.field_82904_b[2].rotationPointY = 4.0F; } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { this.setRotationAngles(f, f1, f2, f3, f4, f5, entity); @@ -73,27 +75,10 @@ public class ModelWither extends ModelBase { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. - */ - public void setRotationAngles(float var1, float var2, float f, float f1, float f2, float var6, Entity var7) { - float f3 = MathHelper.cos(f * 0.1F); - this.field_82905_a[1].rotateAngleX = (0.065F + 0.05F * f3) * 3.1415927F; - this.field_82905_a[2].setRotationPoint(-2.0F, 6.9F + MathHelper.cos(this.field_82905_a[1].rotateAngleX) * 10.0F, - -0.5F + MathHelper.sin(this.field_82905_a[1].rotateAngleX) * 10.0F); - this.field_82905_a[2].rotateAngleX = (0.265F + 0.1F * f3) * 3.1415927F; - this.field_82904_b[0].rotateAngleY = f1 / 57.295776F; - this.field_82904_b[0].rotateAngleX = f2 / 57.295776F; - } - - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float var2, float var3, float var4) { EntityWither entitywither = (EntityWither) entitylivingbase; @@ -105,4 +90,20 @@ public class ModelWither extends ModelBase { } } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. + */ + public void setRotationAngles(float var1, float var2, float f, float f1, float f2, float var6, Entity var7) { + float f3 = MathHelper.cos(f * 0.1F); + this.field_82905_a[1].rotateAngleX = (0.065F + 0.05F * f3) * 3.1415927F; + this.field_82905_a[2].setRotationPoint(-2.0F, 6.9F + MathHelper.cos(this.field_82905_a[1].rotateAngleX) * 10.0F, + -0.5F + MathHelper.sin(this.field_82905_a[1].rotateAngleX) * 10.0F); + this.field_82905_a[2].rotateAngleX = (0.265F + 0.1F * f3) * 3.1415927F; + this.field_82904_b[0].rotateAngleY = f1 / 57.295776F; + this.field_82904_b[0].rotateAngleX = f2 / 57.295776F; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/ModelWolf.java b/src/game/java/net/minecraft/client/model/ModelWolf.java index ff4fff3e..5bacb959 100644 --- a/src/game/java/net/minecraft/client/model/ModelWolf.java +++ b/src/game/java/net/minecraft/client/model/ModelWolf.java @@ -6,22 +6,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -68,9 +71,8 @@ public class ModelWolf extends ModelBase { this.wolfHeadMain.setTextureOffset(0, 10).addBox(-1.5F, 0.0F, -5.0F, 3, 3, 4, f); } - /**+ - * Sets the models various rotation angles then renders the - * model. + /** + * + Sets the models various rotation angles then renders the model. */ public void render(Entity entity, float f, float f1, float f2, float f3, float f4, float f5) { super.render(entity, f, f1, f2, f3, f4, f5); @@ -105,10 +107,10 @@ public class ModelWolf extends ModelBase { } - /**+ - * Used for easily adding entity-dependent animations. The - * second and third float params here are the same second and - * third as in the setRotationAngles method. + /** + * + Used for easily adding entity-dependent animations. The second and third + * float params here are the same second and third as in the setRotationAngles + * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbase, float f, float f1, float f2) { EntityWolf entitywolf = (EntityWolf) entitylivingbase; @@ -155,12 +157,11 @@ public class ModelWolf extends ModelBase { this.wolfTail.rotateAngleZ = entitywolf.getShakeAngle(f2, -0.2F); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelZombie.java b/src/game/java/net/minecraft/client/model/ModelZombie.java index b8e8ff80..96e96320 100644 --- a/src/game/java/net/minecraft/client/model/ModelZombie.java +++ b/src/game/java/net/minecraft/client/model/ModelZombie.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,20 +31,19 @@ public class ModelZombie extends ModelBiped { this(0.0F, true); } - protected ModelZombie(float modelSize, float parFloat1, int textureWidthIn, int textureHeightIn) { - super(modelSize, parFloat1, textureWidthIn, textureHeightIn); - } - public ModelZombie(float modelSize, boolean parFlag) { super(modelSize, 0.0F, 64, parFlag ? 64 : 32); } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + protected ModelZombie(float modelSize, float parFloat1, int textureWidthIn, int textureHeightIn) { + super(modelSize, parFloat1, textureWidthIn, textureHeightIn); + } + + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/ModelZombieVillager.java b/src/game/java/net/minecraft/client/model/ModelZombieVillager.java index 0a81507a..14cae187 100644 --- a/src/game/java/net/minecraft/client/model/ModelZombieVillager.java +++ b/src/game/java/net/minecraft/client/model/ModelZombieVillager.java @@ -3,22 +3,25 @@ package net.minecraft.client.model; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,12 +46,11 @@ public class ModelZombieVillager extends ModelBiped { } - /**+ - * Sets the model's various rotation angles. For bipeds, par1 - * and par2 are used for animating the movement of arms and - * legs, where par1 represents the time(so that arms and legs - * swing back and forth) and par2 represents how "far" arms and - * legs can swing at most. + /** + * + Sets the model's various rotation angles. For bipeds, par1 and par2 are + * used for animating the movement of arms and legs, where par1 represents the + * time(so that arms and legs swing back and forth) and par2 represents how + * "far" arms and legs can swing at most. */ public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity entity) { super.setRotationAngles(f, f1, f2, f3, f4, f5, entity); diff --git a/src/game/java/net/minecraft/client/model/PositionTextureVertex.java b/src/game/java/net/minecraft/client/model/PositionTextureVertex.java index b15f64a6..8a15b62c 100644 --- a/src/game/java/net/minecraft/client/model/PositionTextureVertex.java +++ b/src/game/java/net/minecraft/client/model/PositionTextureVertex.java @@ -2,22 +2,25 @@ package net.minecraft.client.model; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,10 +34,6 @@ public class PositionTextureVertex { this(new Vec3((double) parFloat1, (double) parFloat2, (double) parFloat3), parFloat4, parFloat5); } - public PositionTextureVertex setTexturePosition(float parFloat1, float parFloat2) { - return new PositionTextureVertex(this, parFloat1, parFloat2); - } - public PositionTextureVertex(PositionTextureVertex textureVertex, float texturePositionXIn, float texturePositionYIn) { this.vector3D = textureVertex.vector3D; @@ -47,4 +46,8 @@ public class PositionTextureVertex { this.texturePositionX = texturePositionXIn; this.texturePositionY = texturePositionYIn; } + + public PositionTextureVertex setTexturePosition(float parFloat1, float parFloat2) { + return new PositionTextureVertex(this, parFloat1, parFloat2); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/model/TextureOffset.java b/src/game/java/net/minecraft/client/model/TextureOffset.java index 0ce0baee..59f9db85 100644 --- a/src/game/java/net/minecraft/client/model/TextureOffset.java +++ b/src/game/java/net/minecraft/client/model/TextureOffset.java @@ -1,21 +1,24 @@ package net.minecraft.client.model; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/model/TexturedQuad.java b/src/game/java/net/minecraft/client/model/TexturedQuad.java index 3c7c9c86..c16d78e7 100644 --- a/src/game/java/net/minecraft/client/model/TexturedQuad.java +++ b/src/game/java/net/minecraft/client/model/TexturedQuad.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,20 +53,9 @@ public class TexturedQuad { (float) texcoordV2 / textureHeight - f1); } - public void flipFace() { - PositionTextureVertex[] apositiontexturevertex = new PositionTextureVertex[this.vertexPositions.length]; - - for (int i = 0; i < this.vertexPositions.length; ++i) { - apositiontexturevertex[i] = this.vertexPositions[this.vertexPositions.length - i - 1]; - } - - this.vertexPositions = apositiontexturevertex; - } - - /**+ - * Draw this primitve. This is typically called only once as the - * generated drawing instructions are saved by the renderer and - * reused later. + /** + * + Draw this primitve. This is typically called only once as the generated + * drawing instructions are saved by the renderer and reused later. */ public void draw(WorldRenderer renderer, float scale) { Vec3 vec3 = this.vertexPositions[1].vector3D.subtractReverse(this.vertexPositions[0].vector3D); @@ -92,4 +84,14 @@ public class TexturedQuad { Tessellator.getInstance().draw(); } + + public void flipFace() { + PositionTextureVertex[] apositiontexturevertex = new PositionTextureVertex[this.vertexPositions.length]; + + for (int i = 0; i < this.vertexPositions.length; ++i) { + apositiontexturevertex[i] = this.vertexPositions[this.vertexPositions.length - i - 1]; + } + + this.vertexPositions = apositiontexturevertex; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/multiplayer/ChunkProviderClient.java b/src/game/java/net/minecraft/client/multiplayer/ChunkProviderClient.java index 32f7cef3..ce048fa1 100644 --- a/src/game/java/net/minecraft/client/multiplayer/ChunkProviderClient.java +++ b/src/game/java/net/minecraft/client/multiplayer/ChunkProviderClient.java @@ -18,22 +18,25 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.EmptyChunk; import net.minecraft.world.chunk.IChunkProvider; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,16 +44,15 @@ import net.minecraft.world.chunk.IChunkProvider; public class ChunkProviderClient implements IChunkProvider { private static final Logger logger = LogManager.getLogger(); private Chunk blankChunk; - /**+ - * The mapping between ChunkCoordinates and Chunks that - * ChunkProviderClient maintains. + /** + * + The mapping between ChunkCoordinates and Chunks that ChunkProviderClient + * maintains. */ private LongHashMap chunkMapping = new LongHashMap(); - /**+ - * This may have been intended to be an iterable version of all - * currently loaded chunks (MultiplayerChunkCache), with - * identical contents to chunkMapping's values. However it is - * never actually added to. + /** + * + This may have been intended to be an iterable version of all currently + * loaded chunks (MultiplayerChunkCache), with identical contents to + * chunkMapping's values. However it is never actually added to. */ private List chunkListing = Lists.newArrayList(); private World worldObj; @@ -60,17 +62,101 @@ public class ChunkProviderClient implements IChunkProvider { this.worldObj = worldIn; } - /**+ - * Checks to see if a chunk exists at x, z + /** + * + Returns if the IChunkProvider supports saving. + */ + public boolean canSave() { + return false; + } + + /** + * + Checks to see if a chunk exists at x, z */ public boolean chunkExists(int var1, int var2) { return true; } - /**+ - * Unload chunk from ChunkProviderClient's hashmap. Called in - * response to a Packet50PreChunk with its mode field set to - * false + public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { + return false; + } + + public int getLoadedChunkCount() { + return this.chunkListing.size(); + } + + public List getPossibleCreatures(EnumCreatureType var1, BlockPos var2) { + return null; + } + + public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { + return null; + } + + /** + * + loads or generates the chunk at the chunk location specified + */ + public Chunk loadChunk(int parInt1, int parInt2) { + Chunk chunk = new Chunk(this.worldObj, parInt1, parInt2); + this.chunkMapping.add(ChunkCoordIntPair.chunkXZ2Int(parInt1, parInt2), chunk); + this.chunkListing.add(chunk); + chunk.setChunkLoaded(true); + return chunk; + } + + /** + * + Converts the instance data to a readable string. + */ + public String makeString() { + return "MultiplayerChunkCache: " + this.chunkMapping.getNumHashElements() + ", " + this.chunkListing.size(); + } + + /** + * + Populates chunk with ores etc etc + */ + public void populate(IChunkProvider var1, int var2, int var3) { + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(int i, int j) { + Chunk chunk = (Chunk) this.chunkMapping.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(i, j)); + return chunk == null ? this.blankChunk : chunk; + } + + public void recreateStructures(Chunk var1, int var2, int var3) { + } + + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. + */ + public boolean saveChunks(boolean var1, IProgressUpdate var2) { + return true; + } + + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. + */ + public void saveExtraData() { + } + + /** + * + Unload chunk from ChunkProviderClient's hashmap. Called in response to a + * Packet50PreChunk with its mode field set to false */ public void unloadChunk(int parInt1, int parInt2) { Chunk chunk = this.provideChunk(parInt1, parInt2); @@ -82,47 +168,9 @@ public class ChunkProviderClient implements IChunkProvider { this.chunkListing.remove(chunk); } - /**+ - * loads or generates the chunk at the chunk location specified - */ - public Chunk loadChunk(int parInt1, int parInt2) { - Chunk chunk = new Chunk(this.worldObj, parInt1, parInt2); - this.chunkMapping.add(ChunkCoordIntPair.chunkXZ2Int(parInt1, parInt2), chunk); - this.chunkListing.add(chunk); - chunk.setChunkLoaded(true); - return chunk; - } - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(int i, int j) { - Chunk chunk = (Chunk) this.chunkMapping.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(i, j)); - return chunk == null ? this.blankChunk : chunk; - } - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. - */ - public boolean saveChunks(boolean var1, IProgressUpdate var2) { - return true; - } - - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. - */ - public void saveExtraData() { - } - - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. */ public boolean unloadQueuedChunks() { long i = EagRuntime.steadyTimeMillis(); @@ -138,52 +186,4 @@ public class ChunkProviderClient implements IChunkProvider { return false; } - - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return false; - } - - /**+ - * Populates chunk with ores etc etc - */ - public void populate(IChunkProvider var1, int var2, int var3) { - } - - public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { - return false; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "MultiplayerChunkCache: " + this.chunkMapping.getNumHashElements() + ", " + this.chunkListing.size(); - } - - public List getPossibleCreatures(EnumCreatureType var1, BlockPos var2) { - return null; - } - - public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { - return null; - } - - public int getLoadedChunkCount() { - return this.chunkListing.size(); - } - - public void recreateStructures(Chunk var1, int var2, int var3) { - } - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/multiplayer/GuiConnecting.java b/src/game/java/net/minecraft/client/multiplayer/GuiConnecting.java index a1a273db..70d2467a 100644 --- a/src/game/java/net/minecraft/client/multiplayer/GuiConnecting.java +++ b/src/game/java/net/minecraft/client/multiplayer/GuiConnecting.java @@ -29,22 +29,25 @@ import net.minecraft.network.EnumConnectionState; import net.minecraft.network.play.client.C17PacketCustomPayload; import net.minecraft.util.ChatComponentText; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,6 +65,16 @@ public class GuiConnecting extends GuiScreen { private final GuiScreen previousGuiScreen; private int timer = 0; + public GuiConnecting(GuiConnecting previous, String password) { + this(previous, password, false); + } + + public GuiConnecting(GuiConnecting previous, String password, boolean allowPlaintext) { + this.mc = previous.mc; + this.previousGuiScreen = previous.previousGuiScreen; + this.connect(previous.currentAddress, password, allowPlaintext, previous.allowCookies); + } + public GuiConnecting(GuiScreen parGuiScreen, Minecraft mcIn, ServerData parServerData) { this(parGuiScreen, mcIn, parServerData, false); } @@ -116,14 +129,47 @@ public class GuiConnecting extends GuiScreen { allowCookies && EagRuntime.getConfiguration().isEnableServerCookies()); } - public GuiConnecting(GuiConnecting previous, String password) { - this(previous, password, false); + /** + * + Called by the controls from the buttonList when activated. (Mouse pressed + * for buttons) + */ + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + this.cancel = true; + if (this.networkManager != null) { + this.networkManager.closeChannel(new ChatComponentText("Aborted")); + } else if (this.webSocket != null) { + this.webSocket.close(); + } + + this.mc.displayGuiScreen(this.previousGuiScreen); + } + } - public GuiConnecting(GuiConnecting previous, String password, boolean allowPlaintext) { - this.mc = previous.mc; - this.previousGuiScreen = previous.previousGuiScreen; - this.connect(previous.currentAddress, password, allowPlaintext, previous.allowCookies); + public boolean canCloseGui() { + return false; + } + + private void checkRatelimit() { + if (this.webSocket != null) { + List strFrames = webSocket.getNextStringFrames(); + if (strFrames != null) { + for (int i = 0; i < strFrames.size(); ++i) { + String str = strFrames.get(i).getString(); + if (str.equalsIgnoreCase("BLOCKED")) { + RateLimitTracker.registerBlock(currentAddress); + mc.displayGuiScreen(GuiDisconnected.createRateLimitKick(previousGuiScreen)); + logger.info("Handshake Failure: Too Many Requests!"); + } else if (str.equalsIgnoreCase("LOCKED")) { + RateLimitTracker.registerLockOut(currentAddress); + mc.displayGuiScreen(GuiDisconnected.createRateLimitKick(previousGuiScreen)); + logger.info("Handshake Failure: Too Many Requests!"); + logger.info("Server has locked this client out"); + } + } + } + } } private void connect(String ip, String password, boolean allowPlaintext, boolean allowCookies) { @@ -133,8 +179,44 @@ public class GuiConnecting extends GuiScreen { this.allowCookies = allowCookies; } - /**+ - * Called from the main game loop to update the screen. + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + this.drawDefaultBackground(); + if (this.networkManager == null || !this.networkManager.isChannelOpen()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("connect.connecting", new Object[0]), + this.width / 2, this.height / 2 - 50, 16777215); + } else { + this.drawCenteredString(this.fontRendererObj, I18n.format("connect.authorizing", new Object[0]), + this.width / 2, this.height / 2 - 50, 16777215); + } + + super.drawScreen(i, j, f); + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + this.buttonList.clear(); + this.buttonList.add( + new GuiButton(0, this.width / 2 - 100, this.height / 2 - 10, I18n.format("gui.cancel", new Object[0]))); + } + + /** + * + Fired when a key is typed (except F11 which toggles full screen). This is + * the equivalent of KeyListener.keyTyped(KeyEvent e). Args : character + * (character on the key), keyCode (lwjgl Keyboard key code) + */ + protected void keyTyped(char parChar1, int parInt1) { + } + + /** + * + Called from the main game loop to update the screen. */ public void updateScreen() { ++timer; @@ -237,84 +319,4 @@ public class GuiConnecting extends GuiScreen { } } } - - /**+ - * Fired when a key is typed (except F11 which toggles full - * screen). This is the equivalent of - * KeyListener.keyTyped(KeyEvent e). Args : character (character - * on the key), keyCode (lwjgl Keyboard key code) - */ - protected void keyTyped(char parChar1, int parInt1) { - } - - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - this.buttonList.clear(); - this.buttonList.add( - new GuiButton(0, this.width / 2 - 100, this.height / 2 - 10, I18n.format("gui.cancel", new Object[0]))); - } - - /**+ - * Called by the controls from the buttonList when activated. - * (Mouse pressed for buttons) - */ - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.id == 0) { - this.cancel = true; - if (this.networkManager != null) { - this.networkManager.closeChannel(new ChatComponentText("Aborted")); - } else if (this.webSocket != null) { - this.webSocket.close(); - } - - this.mc.displayGuiScreen(this.previousGuiScreen); - } - - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - this.drawDefaultBackground(); - if (this.networkManager == null || !this.networkManager.isChannelOpen()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("connect.connecting", new Object[0]), - this.width / 2, this.height / 2 - 50, 16777215); - } else { - this.drawCenteredString(this.fontRendererObj, I18n.format("connect.authorizing", new Object[0]), - this.width / 2, this.height / 2 - 50, 16777215); - } - - super.drawScreen(i, j, f); - } - - private void checkRatelimit() { - if (this.webSocket != null) { - List strFrames = webSocket.getNextStringFrames(); - if (strFrames != null) { - for (int i = 0; i < strFrames.size(); ++i) { - String str = strFrames.get(i).getString(); - if (str.equalsIgnoreCase("BLOCKED")) { - RateLimitTracker.registerBlock(currentAddress); - mc.displayGuiScreen(GuiDisconnected.createRateLimitKick(previousGuiScreen)); - logger.info("Handshake Failure: Too Many Requests!"); - } else if (str.equalsIgnoreCase("LOCKED")) { - RateLimitTracker.registerLockOut(currentAddress); - mc.displayGuiScreen(GuiDisconnected.createRateLimitKick(previousGuiScreen)); - logger.info("Handshake Failure: Too Many Requests!"); - logger.info("Server has locked this client out"); - } - } - } - } - } - - public boolean canCloseGui() { - return false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/multiplayer/PlayerControllerMP.java b/src/game/java/net/minecraft/client/multiplayer/PlayerControllerMP.java index aa249042..88fe8805 100644 --- a/src/game/java/net/minecraft/client/multiplayer/PlayerControllerMP.java +++ b/src/game/java/net/minecraft/client/multiplayer/PlayerControllerMP.java @@ -34,46 +34,30 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlayerControllerMP { - private final Minecraft mc; - private final NetHandlerPlayClient netClientHandler; - private BlockPos currentBlock = new BlockPos(-1, -1, -1); - private ItemStack currentItemHittingBlock; - private float curBlockDamageMP; - private float stepSoundTickCounter; - private int blockHitDelay; - private boolean isHittingBlock; - /**+ - * Current game type for the player - */ - private WorldSettings.GameType currentGameType = WorldSettings.GameType.SURVIVAL; - private int currentPlayerItem; - - public PlayerControllerMP(Minecraft mcIn, NetHandlerPlayClient parNetHandlerPlayClient) { - this.mc = mcIn; - this.netClientHandler = parNetHandlerPlayClient; - } - public static void clickBlockCreative(Minecraft mcIn, PlayerControllerMP parPlayerControllerMP, BlockPos parBlockPos, EnumFacing parEnumFacing) { if (!mcIn.theWorld.extinguishFire(mcIn.thePlayer, parBlockPos, parEnumFacing)) { @@ -82,96 +66,40 @@ public class PlayerControllerMP { } - /**+ - * Sets player capabilities depending on current gametype. - * params: player + private final Minecraft mc; + private final NetHandlerPlayClient netClientHandler; + private BlockPos currentBlock = new BlockPos(-1, -1, -1); + private ItemStack currentItemHittingBlock; + private float curBlockDamageMP; + private float stepSoundTickCounter; + private int blockHitDelay; + private boolean isHittingBlock; + /** + * + Current game type for the player */ - public void setPlayerCapabilities(EntityPlayer parEntityPlayer) { - this.currentGameType.configurePlayerCapabilities(parEntityPlayer.capabilities); + private WorldSettings.GameType currentGameType = WorldSettings.GameType.SURVIVAL; + + private int currentPlayerItem; + + public PlayerControllerMP(Minecraft mcIn, NetHandlerPlayClient parNetHandlerPlayClient) { + this.mc = mcIn; + this.netClientHandler = parNetHandlerPlayClient; } - /**+ - * None + /** + * + Attacks an entity */ - public boolean isSpectator() { - return this.currentGameType == WorldSettings.GameType.SPECTATOR; - } - - /**+ - * Sets the game type for the player. - */ - public void setGameType(WorldSettings.GameType parGameType) { - this.currentGameType = parGameType; - this.currentGameType.configurePlayerCapabilities(this.mc.thePlayer.capabilities); - } - - /**+ - * Flips the player around. - */ - public void flipPlayer(EntityPlayer playerIn) { - playerIn.rotationYaw = -180.0F; - } - - public boolean shouldDrawHUD() { - return this.currentGameType.isSurvivalOrAdventure(); - } - - /**+ - * Called when a player completes the destruction of a block - */ - public boolean onPlayerDestroyBlock(BlockPos pos, EnumFacing side) { - if (this.currentGameType.isAdventure()) { - if (this.currentGameType == WorldSettings.GameType.SPECTATOR) { - return false; - } - - if (!this.mc.thePlayer.isAllowEdit()) { - Block block = this.mc.theWorld.getBlockState(pos).getBlock(); - ItemStack itemstack = this.mc.thePlayer.getCurrentEquippedItem(); - if (itemstack == null) { - return false; - } - - if (!itemstack.canDestroy(block)) { - return false; - } - } + public void attackEntity(EntityPlayer playerIn, Entity targetEntity) { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.ATTACK)); + if (this.currentGameType != WorldSettings.GameType.SPECTATOR) { + playerIn.attackTargetEntityWithCurrentItem(targetEntity); } - if (this.currentGameType.isCreative() && this.mc.thePlayer.getHeldItem() != null - && this.mc.thePlayer.getHeldItem().getItem() instanceof ItemSword) { - return false; - } else { - WorldClient worldclient = this.mc.theWorld; - IBlockState iblockstate = worldclient.getBlockState(pos); - Block block1 = iblockstate.getBlock(); - if (block1.getMaterial() == Material.air) { - return false; - } else { - worldclient.playAuxSFX(2001, pos, Block.getStateId(iblockstate)); - boolean flag = worldclient.setBlockToAir(pos); - if (flag) { - block1.onBlockDestroyedByPlayer(worldclient, pos, iblockstate); - } - - this.currentBlock = new BlockPos(this.currentBlock.getX(), -1, this.currentBlock.getZ()); - if (!this.currentGameType.isCreative()) { - ItemStack itemstack1 = this.mc.thePlayer.getCurrentEquippedItem(); - if (itemstack1 != null) { - itemstack1.onBlockDestroyed(worldclient, block1, pos, this.mc.thePlayer); - if (itemstack1.stackSize == 0) { - this.mc.thePlayer.destroyCurrentEquippedItem(); - } - } - } - - return flag; - } - } } - /**+ - * Called when the player is hitting a block with an item. + /** + * + Called when the player is hitting a block with an item. */ public boolean clickBlock(BlockPos loc, EnumFacing face) { if (this.currentGameType.isAdventure()) { @@ -232,18 +160,107 @@ public class PlayerControllerMP { } } - /**+ - * Resets current block damage and field_78778_j + /** + * + true for hitting entities far away. */ - public void resetBlockRemoving() { - if (this.isHittingBlock) { - this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging( - C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, EnumFacing.DOWN)); - this.isHittingBlock = false; - this.curBlockDamageMP = 0.0F; - this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, -1); + public boolean extendedReach() { + return this.currentGameType.isCreative(); + } + + /** + * + Flips the player around. + */ + public void flipPlayer(EntityPlayer playerIn) { + playerIn.rotationYaw = -180.0F; + } + + public EntityPlayerSP func_178892_a(World worldIn, StatFileWriter statWriter) { + return new EntityPlayerSP(this.mc, worldIn, this.netClientHandler, statWriter); + } + + public boolean func_178894_a(EntityPlayer parEntityPlayer, Entity parEntity, + MovingObjectPosition parMovingObjectPosition) { + this.syncCurrentPlayItem(); + Vec3 vec3 = new Vec3(parMovingObjectPosition.hitVec.xCoord - parEntity.posX, + parMovingObjectPosition.hitVec.yCoord - parEntity.posY, + parMovingObjectPosition.hitVec.zCoord - parEntity.posZ); + this.netClientHandler.addToSendQueue(new C02PacketUseEntity(parEntity, vec3)); + return this.currentGameType != WorldSettings.GameType.SPECTATOR && parEntity.interactAt(parEntityPlayer, vec3); + } + + public boolean func_181040_m() { + return this.isHittingBlock; + } + + public boolean gameIsSurvivalOrAdventure() { + return this.currentGameType.isSurvivalOrAdventure(); + } + + /** + * + player reach distance = 4F + */ + public float getBlockReachDistance() { + return this.currentGameType.isCreative() ? 5.0F : 4.5F; + } + + public WorldSettings.GameType getCurrentGameType() { + return this.currentGameType; + } + + /** + * + Send packet to server - player is interacting with another entity (left + * click) + */ + public boolean interactWithEntitySendPacket(EntityPlayer playerIn, Entity targetEntity) { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.INTERACT)); + return this.currentGameType != WorldSettings.GameType.SPECTATOR && playerIn.interactWith(targetEntity); + } + + private boolean isHittingPosition(BlockPos pos) { + ItemStack itemstack = this.mc.thePlayer.getHeldItem(); + boolean flag = this.currentItemHittingBlock == null && itemstack == null; + if (this.currentItemHittingBlock != null && itemstack != null) { + flag = itemstack.getItem() == this.currentItemHittingBlock.getItem() + && ItemStack.areItemStackTagsEqual(itemstack, this.currentItemHittingBlock) + && (itemstack.isItemStackDamageable() + || itemstack.getMetadata() == this.currentItemHittingBlock.getMetadata()); } + return pos.equals(this.currentBlock) && flag; + } + + /** + * + returns true if player is in creative mode + */ + public boolean isInCreativeMode() { + return this.currentGameType.isCreative(); + } + + /** + * + Checks if the player is not creative, used for checking if it should break + * a block instantly + */ + public boolean isNotCreative() { + return !this.currentGameType.isCreative(); + } + + /** + * + Checks if the player is riding a horse, used to chose the GUI to open + */ + public boolean isRidingHorse() { + return this.mc.thePlayer.isRiding() && this.mc.thePlayer.ridingEntity instanceof EntityHorse; + } + + /** + * + None + */ + public boolean isSpectator() { + return this.currentGameType == WorldSettings.GameType.SPECTATOR; + } + + public boolean isSpectatorMode() { + return this.currentGameType == WorldSettings.GameType.SPECTATOR; } public boolean onPlayerDamageBlock(BlockPos posBlock, EnumFacing directionFacing) { @@ -293,59 +310,58 @@ public class PlayerControllerMP { } } - /**+ - * player reach distance = 4F + /** + * + Called when a player completes the destruction of a block */ - public float getBlockReachDistance() { - return this.currentGameType.isCreative() ? 5.0F : 4.5F; - } - - public void updateController() { - this.syncCurrentPlayItem(); - if (this.netClientHandler.getNetworkManager().isChannelOpen()) { - try { - this.netClientHandler.getNetworkManager().processReceivedPackets(); - } catch (IOException ex) { - EaglercraftNetworkManager.logger - .fatal("Unhandled IOException was thrown " + "while processing multiplayer packets!"); - EaglercraftNetworkManager.logger.fatal(ex); - EaglercraftNetworkManager.logger.fatal("Disconnecting..."); - this.netClientHandler.getNetworkManager() - .closeChannel(new ChatComponentText("Exception thrown: " + ex.toString())); + public boolean onPlayerDestroyBlock(BlockPos pos, EnumFacing side) { + if (this.currentGameType.isAdventure()) { + if (this.currentGameType == WorldSettings.GameType.SPECTATOR) { + return false; } - this.netClientHandler.getSkinCache().flush(); - this.netClientHandler.getCapeCache().flush(); - this.netClientHandler.getNotifManager().runTick(); - ClientUUIDLoadingCache.update(); + + if (!this.mc.thePlayer.isAllowEdit()) { + Block block = this.mc.theWorld.getBlockState(pos).getBlock(); + ItemStack itemstack = this.mc.thePlayer.getCurrentEquippedItem(); + if (itemstack == null) { + return false; + } + + if (!itemstack.canDestroy(block)) { + return false; + } + } + } + + if (this.currentGameType.isCreative() && this.mc.thePlayer.getHeldItem() != null + && this.mc.thePlayer.getHeldItem().getItem() instanceof ItemSword) { + return false; } else { - this.netClientHandler.getNetworkManager().checkDisconnected(); + WorldClient worldclient = this.mc.theWorld; + IBlockState iblockstate = worldclient.getBlockState(pos); + Block block1 = iblockstate.getBlock(); + if (block1.getMaterial() == Material.air) { + return false; + } else { + worldclient.playAuxSFX(2001, pos, Block.getStateId(iblockstate)); + boolean flag = worldclient.setBlockToAir(pos); + if (flag) { + block1.onBlockDestroyedByPlayer(worldclient, pos, iblockstate); + } + + this.currentBlock = new BlockPos(this.currentBlock.getX(), -1, this.currentBlock.getZ()); + if (!this.currentGameType.isCreative()) { + ItemStack itemstack1 = this.mc.thePlayer.getCurrentEquippedItem(); + if (itemstack1 != null) { + itemstack1.onBlockDestroyed(worldclient, block1, pos, this.mc.thePlayer); + if (itemstack1.stackSize == 0) { + this.mc.thePlayer.destroyCurrentEquippedItem(); + } + } + } + + return flag; + } } - - } - - private boolean isHittingPosition(BlockPos pos) { - ItemStack itemstack = this.mc.thePlayer.getHeldItem(); - boolean flag = this.currentItemHittingBlock == null && itemstack == null; - if (this.currentItemHittingBlock != null && itemstack != null) { - flag = itemstack.getItem() == this.currentItemHittingBlock.getItem() - && ItemStack.areItemStackTagsEqual(itemstack, this.currentItemHittingBlock) - && (itemstack.isItemStackDamageable() - || itemstack.getMetadata() == this.currentItemHittingBlock.getMetadata()); - } - - return pos.equals(this.currentBlock) && flag; - } - - /**+ - * Syncs the current player item with the server - */ - private void syncCurrentPlayItem() { - int i = this.mc.thePlayer.inventory.currentItem; - if (i != this.currentPlayerItem) { - this.currentPlayerItem = i; - this.netClientHandler.addToSendQueue(new C09PacketHeldItemChange(this.currentPlayerItem)); - } - } public boolean onPlayerRightClick(EntityPlayerSP player, WorldClient worldIn, ItemStack heldStack, BlockPos hitPos, @@ -394,8 +410,58 @@ public class PlayerControllerMP { } } - /**+ - * Notifies the server of things like consuming food, etc... + public void onStoppedUsingItem(EntityPlayer playerIn) { + this.syncCurrentPlayItem(); + this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, + BlockPos.ORIGIN, EnumFacing.DOWN)); + playerIn.stopUsingItem(); + } + + /** + * + Resets current block damage and field_78778_j + */ + public void resetBlockRemoving() { + if (this.isHittingBlock) { + this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging( + C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK, this.currentBlock, EnumFacing.DOWN)); + this.isHittingBlock = false; + this.curBlockDamageMP = 0.0F; + this.mc.theWorld.sendBlockBreakProgress(this.mc.thePlayer.getEntityId(), this.currentBlock, -1); + } + + } + + /** + * + GuiEnchantment uses this during multiplayer to tell PlayerControllerMP to + * send a packet indicating the enchantment action the player has taken. + */ + public void sendEnchantPacket(int parInt1, int parInt2) { + this.netClientHandler.addToSendQueue(new C11PacketEnchantItem(parInt1, parInt2)); + } + + /** + * + Sends a Packet107 to the server to drop the item on the ground + */ + public void sendPacketDropItem(ItemStack itemStackIn) { + if (this.currentGameType.isCreative() && itemStackIn != null) { + this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(-1, itemStackIn)); + } + + } + + /** + * + Used in PlayerControllerMP to update the server with an ItemStack in a + * slot. + */ + public void sendSlotPacket(ItemStack itemStackIn, int slotId) { + if (this.currentGameType.isCreative()) { + this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(slotId, itemStackIn)); + } + + } + + /** + * + Notifies the server of things like consuming food, etc... */ public boolean sendUseItem(EntityPlayer playerIn, World worldIn, ItemStack itemStackIn) { if (this.currentGameType == WorldSettings.GameType.SPECTATOR) { @@ -419,44 +485,62 @@ public class PlayerControllerMP { } } - public EntityPlayerSP func_178892_a(World worldIn, StatFileWriter statWriter) { - return new EntityPlayerSP(this.mc, worldIn, this.netClientHandler, statWriter); + /** + * + Sets the game type for the player. + */ + public void setGameType(WorldSettings.GameType parGameType) { + this.currentGameType = parGameType; + this.currentGameType.configurePlayerCapabilities(this.mc.thePlayer.capabilities); } - /**+ - * Attacks an entity + /** + * + Sets player capabilities depending on current gametype. params: player */ - public void attackEntity(EntityPlayer playerIn, Entity targetEntity) { - this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.ATTACK)); - if (this.currentGameType != WorldSettings.GameType.SPECTATOR) { - playerIn.attackTargetEntityWithCurrentItem(targetEntity); + public void setPlayerCapabilities(EntityPlayer parEntityPlayer) { + this.currentGameType.configurePlayerCapabilities(parEntityPlayer.capabilities); + } + + public boolean shouldDrawHUD() { + return this.currentGameType.isSurvivalOrAdventure(); + } + + /** + * + Syncs the current player item with the server + */ + private void syncCurrentPlayItem() { + int i = this.mc.thePlayer.inventory.currentItem; + if (i != this.currentPlayerItem) { + this.currentPlayerItem = i; + this.netClientHandler.addToSendQueue(new C09PacketHeldItemChange(this.currentPlayerItem)); } } - /**+ - * Send packet to server - player is interacting with another - * entity (left click) - */ - public boolean interactWithEntitySendPacket(EntityPlayer playerIn, Entity targetEntity) { + public void updateController() { this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new C02PacketUseEntity(targetEntity, C02PacketUseEntity.Action.INTERACT)); - return this.currentGameType != WorldSettings.GameType.SPECTATOR && playerIn.interactWith(targetEntity); + if (this.netClientHandler.getNetworkManager().isChannelOpen()) { + try { + this.netClientHandler.getNetworkManager().processReceivedPackets(); + } catch (IOException ex) { + EaglercraftNetworkManager.logger + .fatal("Unhandled IOException was thrown " + "while processing multiplayer packets!"); + EaglercraftNetworkManager.logger.fatal(ex); + EaglercraftNetworkManager.logger.fatal("Disconnecting..."); + this.netClientHandler.getNetworkManager() + .closeChannel(new ChatComponentText("Exception thrown: " + ex.toString())); + } + this.netClientHandler.getSkinCache().flush(); + this.netClientHandler.getCapeCache().flush(); + this.netClientHandler.getNotifManager().runTick(); + ClientUUIDLoadingCache.update(); + } else { + this.netClientHandler.getNetworkManager().checkDisconnected(); + } + } - public boolean func_178894_a(EntityPlayer parEntityPlayer, Entity parEntity, - MovingObjectPosition parMovingObjectPosition) { - this.syncCurrentPlayItem(); - Vec3 vec3 = new Vec3(parMovingObjectPosition.hitVec.xCoord - parEntity.posX, - parMovingObjectPosition.hitVec.yCoord - parEntity.posY, - parMovingObjectPosition.hitVec.zCoord - parEntity.posZ); - this.netClientHandler.addToSendQueue(new C02PacketUseEntity(parEntity, vec3)); - return this.currentGameType != WorldSettings.GameType.SPECTATOR && parEntity.interactAt(parEntityPlayer, vec3); - } - - /**+ - * Handles slot clicks sends a packet to the server. + /** + * + Handles slot clicks sends a packet to the server. */ public ItemStack windowClick(int windowId, int slotId, int mouseButtonClicked, int mode, EntityPlayer playerIn) { short short1 = playerIn.openContainer.getNextTransactionID(playerIn.inventory); @@ -465,88 +549,4 @@ public class PlayerControllerMP { new C0EPacketClickWindow(windowId, slotId, mouseButtonClicked, mode, itemstack, short1)); return itemstack; } - - /**+ - * GuiEnchantment uses this during multiplayer to tell - * PlayerControllerMP to send a packet indicating the - * enchantment action the player has taken. - */ - public void sendEnchantPacket(int parInt1, int parInt2) { - this.netClientHandler.addToSendQueue(new C11PacketEnchantItem(parInt1, parInt2)); - } - - /**+ - * Used in PlayerControllerMP to update the server with an - * ItemStack in a slot. - */ - public void sendSlotPacket(ItemStack itemStackIn, int slotId) { - if (this.currentGameType.isCreative()) { - this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(slotId, itemStackIn)); - } - - } - - /**+ - * Sends a Packet107 to the server to drop the item on the - * ground - */ - public void sendPacketDropItem(ItemStack itemStackIn) { - if (this.currentGameType.isCreative() && itemStackIn != null) { - this.netClientHandler.addToSendQueue(new C10PacketCreativeInventoryAction(-1, itemStackIn)); - } - - } - - public void onStoppedUsingItem(EntityPlayer playerIn) { - this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, - BlockPos.ORIGIN, EnumFacing.DOWN)); - playerIn.stopUsingItem(); - } - - public boolean gameIsSurvivalOrAdventure() { - return this.currentGameType.isSurvivalOrAdventure(); - } - - /**+ - * Checks if the player is not creative, used for checking if it - * should break a block instantly - */ - public boolean isNotCreative() { - return !this.currentGameType.isCreative(); - } - - /**+ - * returns true if player is in creative mode - */ - public boolean isInCreativeMode() { - return this.currentGameType.isCreative(); - } - - /**+ - * true for hitting entities far away. - */ - public boolean extendedReach() { - return this.currentGameType.isCreative(); - } - - /**+ - * Checks if the player is riding a horse, used to chose the GUI - * to open - */ - public boolean isRidingHorse() { - return this.mc.thePlayer.isRiding() && this.mc.thePlayer.ridingEntity instanceof EntityHorse; - } - - public boolean isSpectatorMode() { - return this.currentGameType == WorldSettings.GameType.SPECTATOR; - } - - public WorldSettings.GameType getCurrentGameType() { - return this.currentGameType; - } - - public boolean func_181040_m() { - return this.isHittingBlock; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/multiplayer/ServerAddress.java b/src/game/java/net/minecraft/client/multiplayer/ServerAddress.java index 528ff6bf..caa752bf 100644 --- a/src/game/java/net/minecraft/client/multiplayer/ServerAddress.java +++ b/src/game/java/net/minecraft/client/multiplayer/ServerAddress.java @@ -1,21 +1,24 @@ package net.minecraft.client.multiplayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/multiplayer/ServerData.java b/src/game/java/net/minecraft/client/multiplayer/ServerData.java index 06fc7d3c..a6e89176 100644 --- a/src/game/java/net/minecraft/client/multiplayer/ServerData.java +++ b/src/game/java/net/minecraft/client/multiplayer/ServerData.java @@ -17,108 +17,52 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerData { - public String serverName; - public String serverIP; - /**+ - * the string indicating number of players on and capacity of - * the server that is shown on the server browser (i.e. "5/20" - * meaning 5 slots used out of 20 slots total) - */ - public String populationInfo = ""; - /**+ - * (better variable name would be 'hostname') server name as - * displayed in the server browser's second line (grey text) - */ - public String serverMOTD = ""; - /**+ - * last server ping that showed up in the server browser - */ - public long pingToServer = -1l; - public int version = 47; - /**+ - * Game version for this server. - */ - public String gameVersion = "1.8.8"; - public boolean field_78841_f; - public String playerList; - private ServerData.ServerResourceMode resourceMode = ServerData.ServerResourceMode.PROMPT; - public boolean hideAddress = false; - private boolean field_181042_l; - public IServerQuery currentQuery = null; - public final ResourceLocation iconResourceLocation; - public EaglerSkinTexture iconTextureObject = null; - public long pingSentTime = -1l; - public boolean serverIconDirty = false; - public boolean hasPing = false; - public boolean serverIconEnabled = false; - public boolean isDefault = false; - public boolean enableCookies; + public static enum ServerResourceMode { + ENABLED("enabled"), DISABLED("disabled"), PROMPT("prompt"); - private static final Logger logger = LogManager.getLogger("MOTDQuery"); + public static final ServerResourceMode[] _VALUES = values(); - private static int serverTextureId = 0; + private final IChatComponent motd; - public ServerData(String parString1, String parString2, boolean parFlag) { - this.serverName = parString1; - this.serverIP = parString2; - this.field_181042_l = parFlag; - this.iconResourceLocation = new ResourceLocation("eagler:servers/icons/tex_" + serverTextureId++); - this.enableCookies = EagRuntime.getConfiguration().isEnableServerCookies(); - } - - /**+ - * Returns an NBTTagCompound with the server's name, IP and - * maybe acceptTextures. - */ - public NBTTagCompound getNBTCompound() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("name", this.serverName); - nbttagcompound.setString("ip", this.serverIP); - - if (this.resourceMode == ServerData.ServerResourceMode.ENABLED) { - nbttagcompound.setBoolean("acceptTextures", true); - } else if (this.resourceMode == ServerData.ServerResourceMode.DISABLED) { - nbttagcompound.setBoolean("acceptTextures", false); + private ServerResourceMode(String parString2) { + this.motd = new ChatComponentTranslation("addServer.resourcePack." + parString2, new Object[0]); } - nbttagcompound.setBoolean("hideAddress", this.hideAddress); - nbttagcompound.setBoolean("enableCookies", this.enableCookies); - - return nbttagcompound; + public IChatComponent getMotd() { + return this.motd; + } } - public ServerData.ServerResourceMode getResourceMode() { - return this.resourceMode; - } + private static final Logger logger = LogManager.getLogger("MOTDQuery"); + private static int serverTextureId = 0; - public void setResourceMode(ServerData.ServerResourceMode mode) { - this.resourceMode = mode; - } - - /**+ - * Takes an NBTTagCompound with 'name' and 'ip' keys, returns a - * ServerData instance. + /** + * + Takes an NBTTagCompound with 'name' and 'ip' keys, returns a ServerData + * instance. */ public static ServerData getServerDataFromNBTCompound(NBTTagCompound nbtCompound) { ServerData serverdata = new ServerData(nbtCompound.getString("name"), nbtCompound.getString("ip"), false); @@ -148,8 +92,53 @@ public class ServerData { return serverdata; } - public boolean func_181041_d() { - return this.field_181042_l; + public String serverName; + public String serverIP; + /** + * + the string indicating number of players on and capacity of the server that + * is shown on the server browser (i.e. "5/20" meaning 5 slots used out of 20 + * slots total) + */ + public String populationInfo = ""; + /** + * + (better variable name would be 'hostname') server name as displayed in the + * server browser's second line (grey text) + */ + public String serverMOTD = ""; + /** + * + last server ping that showed up in the server browser + */ + public long pingToServer = -1l; + public int version = 47; + /** + * + Game version for this server. + */ + public String gameVersion = "1.8.8"; + public boolean field_78841_f; + public String playerList; + private ServerData.ServerResourceMode resourceMode = ServerData.ServerResourceMode.PROMPT; + public boolean hideAddress = false; + private boolean field_181042_l; + public IServerQuery currentQuery = null; + public final ResourceLocation iconResourceLocation; + public EaglerSkinTexture iconTextureObject = null; + public long pingSentTime = -1l; + public boolean serverIconDirty = false; + + public boolean hasPing = false; + + public boolean serverIconEnabled = false; + + public boolean isDefault = false; + + public boolean enableCookies; + + public ServerData(String parString1, String parString2, boolean parFlag) { + this.serverName = parString1; + this.serverIP = parString2; + this.field_181042_l = parFlag; + this.iconResourceLocation = new ResourceLocation("eagler:servers/icons/tex_" + serverTextureId++); + this.enableCookies = EagRuntime.getConfiguration().isEnableServerCookies(); } public void copyFrom(ServerData serverDataIn) { @@ -161,19 +150,59 @@ public class ServerData { this.enableCookies = serverDataIn.enableCookies; } - public static enum ServerResourceMode { - ENABLED("enabled"), DISABLED("disabled"), PROMPT("prompt"); + public boolean func_181041_d() { + return this.field_181042_l; + } - public static final ServerResourceMode[] _VALUES = values(); + /** + * + Returns an NBTTagCompound with the server's name, IP and maybe + * acceptTextures. + */ + public NBTTagCompound getNBTCompound() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("name", this.serverName); + nbttagcompound.setString("ip", this.serverIP); - private final IChatComponent motd; - - private ServerResourceMode(String parString2) { - this.motd = new ChatComponentTranslation("addServer.resourcePack." + parString2, new Object[0]); + if (this.resourceMode == ServerData.ServerResourceMode.ENABLED) { + nbttagcompound.setBoolean("acceptTextures", true); + } else if (this.resourceMode == ServerData.ServerResourceMode.DISABLED) { + nbttagcompound.setBoolean("acceptTextures", false); } - public IChatComponent getMotd() { - return this.motd; + nbttagcompound.setBoolean("hideAddress", this.hideAddress); + nbttagcompound.setBoolean("enableCookies", this.enableCookies); + + return nbttagcompound; + } + + public ServerData.ServerResourceMode getResourceMode() { + return this.resourceMode; + } + + public void setIconPacket(byte[] pkt) { + try { + if (!serverIconEnabled) { + throw new IOException("Unexpected icon packet on text-only MOTD"); + } + if (pkt.length != 16384) { + throw new IOException("MOTD icon packet is the wrong size!"); + } + int[] pixels = new int[4096]; + for (int i = 0, j; i < 4096; ++i) { + j = i << 2; + pixels[i] = ((int) pkt[j] & 0xFF) | (((int) pkt[j + 1] & 0xFF) << 8) | (((int) pkt[j + 2] & 0xFF) << 16) + | (((int) pkt[j + 3] & 0xFF) << 24); + } + if (iconTextureObject != null) { + iconTextureObject.copyPixelsIn(pixels); + } else { + iconTextureObject = new EaglerSkinTexture(pixels, 64, 64); + Minecraft.getMinecraft().getTextureManager().loadTexture(iconResourceLocation, iconTextureObject); + } + } catch (Throwable t) { + pingToServer = -1l; + logger.error("Could not decode MOTD icon from: {}", serverIP); + logger.error(t); } } @@ -220,31 +249,8 @@ public class ServerData { } } - public void setIconPacket(byte[] pkt) { - try { - if (!serverIconEnabled) { - throw new IOException("Unexpected icon packet on text-only MOTD"); - } - if (pkt.length != 16384) { - throw new IOException("MOTD icon packet is the wrong size!"); - } - int[] pixels = new int[4096]; - for (int i = 0, j; i < 4096; ++i) { - j = i << 2; - pixels[i] = ((int) pkt[j] & 0xFF) | (((int) pkt[j + 1] & 0xFF) << 8) | (((int) pkt[j + 2] & 0xFF) << 16) - | (((int) pkt[j + 3] & 0xFF) << 24); - } - if (iconTextureObject != null) { - iconTextureObject.copyPixelsIn(pixels); - } else { - iconTextureObject = new EaglerSkinTexture(pixels, 64, 64); - Minecraft.getMinecraft().getTextureManager().loadTexture(iconResourceLocation, iconTextureObject); - } - } catch (Throwable t) { - pingToServer = -1l; - logger.error("Could not decode MOTD icon from: {}", serverIP); - logger.error(t); - } + public void setResourceMode(ServerData.ServerResourceMode mode) { + this.resourceMode = mode; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/multiplayer/ServerList.java b/src/game/java/net/minecraft/client/multiplayer/ServerList.java index 54aebbf7..c875096c 100644 --- a/src/game/java/net/minecraft/client/multiplayer/ServerList.java +++ b/src/game/java/net/minecraft/client/multiplayer/ServerList.java @@ -22,63 +22,120 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerList { private static final Logger logger = LogManager.getLogger(); - private final Minecraft mc; - private final List allServers = Lists.newArrayList(); - /**+ - * List of ServerData instances. - */ - private final List servers = Lists.newArrayList(); - private static ServerList instance = null; - private ServerList(Minecraft mcIn) { - this.mc = mcIn; - this.loadServerList(); - } + public static void func_147414_b(ServerData parServerData) { + ServerList serverlist = new ServerList(Minecraft.getMinecraft()); + serverlist.loadServerList(); - public static void initServerList(Minecraft mc) { - instance = new ServerList(mc); + for (int i = 0; i < serverlist.countServers(); ++i) { + ServerData serverdata = serverlist.getServerData(i); + if (serverdata.serverName.equals(parServerData.serverName) + && serverdata.serverIP.equals(parServerData.serverIP)) { + serverlist.func_147413_a(i, parServerData); + break; + } + } + + serverlist.saveServerList(); } public static ServerList getServerList() { return instance; } - /**+ - * Loads a list of servers from servers.dat, by running - * ServerData.getServerDataFromNBTCompound on each NBT compound - * found in the "servers" tag list. + public static void initServerList(Minecraft mc) { + instance = new ServerList(mc); + } + + private final Minecraft mc; + + private final List allServers = Lists.newArrayList(); + + /** + * + List of ServerData instances. + */ + private final List servers = Lists.newArrayList(); + + private ServerList(Minecraft mcIn) { + this.mc = mcIn; + this.loadServerList(); + } + + /** + * + Adds the given ServerData instance to the list. + */ + public void addServerData(ServerData parServerData) { + this.servers.add(parServerData); + } + + /** + * + Counts the number of ServerData instances in the list. + */ + public int countServers() { + return this.servers.size(); + } + + public void freeServerIcons() { + TextureManager mgr = mc.getTextureManager(); + for (int i = 0, l = allServers.size(); i < l; ++i) { + ServerData server = allServers.get(i); + if (server.iconTextureObject != null) { + mgr.deleteTexture(server.iconResourceLocation); + server.iconTextureObject = null; + } + } + } + + public void func_147413_a(int parInt1, ServerData parServerData) { + this.servers.set(parInt1, parServerData); + } + + /** + * + Gets the ServerData instance stored for the given index in the list. + */ + public ServerData getServerData(int parInt1) { + return (ServerData) this.servers.get(parInt1); + } + + /** + * + Loads a list of servers from servers.dat, by running + * ServerData.getServerDataFromNBTCompound on each NBT compound found in the + * "servers" tag list. */ public void loadServerList() { loadServerList(EagRuntime.getStorage("s")); } - /**+ - * Loads a list of servers from servers.dat, by running - * ServerData.getServerDataFromNBTCompound on each NBT compound - * found in the "servers" tag list. + /** + * + Loads a list of servers from servers.dat, by running + * ServerData.getServerDataFromNBTCompound on each NBT compound found in the + * "servers" tag list. */ public void loadServerList(byte[] localStorage) { try { @@ -115,118 +172,6 @@ public class ServerList { } - /**+ - * Runs getNBTCompound on each ServerData instance, puts - * everything into a "servers" NBT list and writes it to - * servers.dat. - */ - public void saveServerList() { - byte[] data = writeServerList(); - if (data != null) { - EagRuntime.setStorage("s", data); - } - } - - public byte[] writeServerList() { - try { - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0, l = this.servers.size(); i < l; ++i) { - ServerData serverdata = this.servers.get(i); - if (!serverdata.isDefault) { - nbttaglist.appendTag(serverdata.getNBTCompound()); - } - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setTag("servers", nbttaglist); - - EaglerOutputStream bao = new EaglerOutputStream(); - CompressedStreamTools.writeCompressed(nbttagcompound, bao); - return bao.toByteArray(); - - } catch (Exception exception) { - logger.error("Couldn\'t save server list", exception); - return null; - } - - } - - /**+ - * Gets the ServerData instance stored for the given index in - * the list. - */ - public ServerData getServerData(int parInt1) { - return (ServerData) this.servers.get(parInt1); - } - - /**+ - * Removes the ServerData instance stored for the given index in - * the list. - */ - public void removeServerData(int parInt1) { - ServerData data = this.servers.remove(parInt1); - if (data != null && data.iconTextureObject != null) { - mc.getTextureManager().deleteTexture(data.iconResourceLocation); - data.iconTextureObject = null; - } - } - - /**+ - * Adds the given ServerData instance to the list. - */ - public void addServerData(ServerData parServerData) { - this.servers.add(parServerData); - } - - /**+ - * Counts the number of ServerData instances in the list. - */ - public int countServers() { - return this.servers.size(); - } - - /**+ - * Takes two list indexes, and swaps their order around. - */ - public void swapServers(int parInt1, int parInt2) { - ServerData serverdata = this.getServerData(parInt1); - this.servers.set(parInt1, this.getServerData(parInt2)); - this.servers.set(parInt2, serverdata); - this.saveServerList(); - } - - public void func_147413_a(int parInt1, ServerData parServerData) { - this.servers.set(parInt1, parServerData); - } - - public static void func_147414_b(ServerData parServerData) { - ServerList serverlist = new ServerList(Minecraft.getMinecraft()); - serverlist.loadServerList(); - - for (int i = 0; i < serverlist.countServers(); ++i) { - ServerData serverdata = serverlist.getServerData(i); - if (serverdata.serverName.equals(parServerData.serverName) - && serverdata.serverIP.equals(parServerData.serverIP)) { - serverlist.func_147413_a(i, parServerData); - break; - } - } - - serverlist.saveServerList(); - } - - public void freeServerIcons() { - TextureManager mgr = mc.getTextureManager(); - for (int i = 0, l = allServers.size(); i < l; ++i) { - ServerData server = allServers.get(i); - if (server.iconTextureObject != null) { - mgr.deleteTexture(server.iconResourceLocation); - server.iconTextureObject = null; - } - } - } - public void refreshServerPing() { this.servers.clear(); this.servers.addAll(this.allServers); @@ -243,6 +188,38 @@ public class ServerList { } } + /** + * + Removes the ServerData instance stored for the given index in the list. + */ + public void removeServerData(int parInt1) { + ServerData data = this.servers.remove(parInt1); + if (data != null && data.iconTextureObject != null) { + mc.getTextureManager().deleteTexture(data.iconResourceLocation); + data.iconTextureObject = null; + } + } + + /** + * + Runs getNBTCompound on each ServerData instance, puts everything into a + * "servers" NBT list and writes it to servers.dat. + */ + public void saveServerList() { + byte[] data = writeServerList(); + if (data != null) { + EagRuntime.setStorage("s", data); + } + } + + /** + * + Takes two list indexes, and swaps their order around. + */ + public void swapServers(int parInt1, int parInt2) { + ServerData serverdata = this.getServerData(parInt1); + this.servers.set(parInt1, this.getServerData(parInt2)); + this.servers.set(parInt2, serverdata); + this.saveServerList(); + } + public void updateServerPing() { int total = 0; for (int i = 0, l = this.servers.size(); i < l; ++i) { @@ -324,4 +301,29 @@ public class ServerList { } + public byte[] writeServerList() { + try { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0, l = this.servers.size(); i < l; ++i) { + ServerData serverdata = this.servers.get(i); + if (!serverdata.isDefault) { + nbttaglist.appendTag(serverdata.getNBTCompound()); + } + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setTag("servers", nbttaglist); + + EaglerOutputStream bao = new EaglerOutputStream(); + CompressedStreamTools.writeCompressed(nbttagcompound, bao); + return bao.toByteArray(); + + } catch (Exception exception) { + logger.error("Couldn\'t save server list", exception); + return null; + } + + } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/multiplayer/WorldClient.java b/src/game/java/net/minecraft/client/multiplayer/WorldClient.java index a868ac3f..9b9bc940 100644 --- a/src/game/java/net/minecraft/client/multiplayer/WorldClient.java +++ b/src/game/java/net/minecraft/client/multiplayer/WorldClient.java @@ -1,11 +1,11 @@ package net.minecraft.client.multiplayer; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Set; import java.util.concurrent.Callable; import com.google.common.collect.Sets; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; @@ -36,22 +36,25 @@ import net.minecraft.world.storage.SaveDataMemoryStorage; import net.minecraft.world.storage.SaveHandlerMP; import net.minecraft.world.storage.WorldInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -59,16 +62,14 @@ import net.minecraft.world.storage.WorldInfo; public class WorldClient extends World { private NetHandlerPlayClient sendQueue; private ChunkProviderClient clientChunkProvider; - /**+ - * Contains all entities for this client, both spawned and - * non-spawned. + /** + * + Contains all entities for this client, both spawned and non-spawned. */ private final Set entityList = Sets.newHashSet(); - /**+ - * Contains all entities for this client that were not spawned - * due to a non-present chunk. The game will attempt to spawn up - * to 10 pending entities with each subsequent tick until the - * spawn queue is empty. + /** + * + Contains all entities for this client that were not spawned due to a + * non-present chunk. The game will attempt to spawn up to 10 pending entities + * with each subsequent tick until the spawn queue is empty. */ private final Set entitySpawnQueue = Sets.newHashSet(); private final Minecraft mc = Minecraft.getMinecraft(); @@ -88,134 +89,8 @@ public class WorldClient extends World { this.calculateInitialWeather(); } - /**+ - * Runs a single tick for the world - */ - public void tick() { - super.tick(); - this.setTotalWorldTime(this.getTotalWorldTime() + 1L); - if (this.getGameRules().getBoolean("doDaylightCycle")) { - this.setWorldTime(this.getWorldTime() + 1L); - } - - for (int i = 0; i < 10 && !this.entitySpawnQueue.isEmpty(); ++i) { - Entity entity = (Entity) this.entitySpawnQueue.iterator().next(); - this.entitySpawnQueue.remove(entity); - if (!this.loadedEntityList.contains(entity)) { - this.spawnEntityInWorld(entity); - } - } - - this.clientChunkProvider.unloadQueuedChunks(); - this.updateBlocks(); - } - - /**+ - * Invalidates an AABB region of blocks from the receive queue, - * in the event that the block has been modified client-side in - * the intervening 80 receive ticks. - */ - public void invalidateBlockReceiveRegion(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, - int parInt6) { - } - - /**+ - * Creates the chunk provider for this world. Called in the - * constructor. Retrieves provider from worldProvider? - */ - protected IChunkProvider createChunkProvider() { - this.clientChunkProvider = new ChunkProviderClient(this); - return this.clientChunkProvider; - } - - protected void updateBlocks() { - super.updateBlocks(); - this.previousActiveChunkSet.retainAll(this.activeChunkSet); - if (this.previousActiveChunkSet.size() == this.activeChunkSet.size()) { - this.previousActiveChunkSet.clear(); - } - - int i = 0; - - for (ChunkCoordIntPair chunkcoordintpair : this.activeChunkSet) { - if (!this.previousActiveChunkSet.contains(chunkcoordintpair)) { - int j = chunkcoordintpair.chunkXPos * 16; - int k = chunkcoordintpair.chunkZPos * 16; - Chunk chunk = this.getChunkFromChunkCoords(chunkcoordintpair.chunkXPos, chunkcoordintpair.chunkZPos); - this.playMoodSoundAndCheckLight(j, k, chunk); - this.previousActiveChunkSet.add(chunkcoordintpair); - ++i; - if (i >= 10) { - return; - } - } - } - - } - - public void doPreChunk(int parInt1, int parInt2, boolean parFlag) { - if (parFlag) { - this.clientChunkProvider.loadChunk(parInt1, parInt2); - } else { - this.clientChunkProvider.unloadChunk(parInt1, parInt2); - } - - if (!parFlag) { - this.markBlockRangeForRenderUpdate(parInt1 * 16, 0, parInt2 * 16, parInt1 * 16 + 15, 256, - parInt2 * 16 + 15); - } - - } - - /**+ - * Called when an entity is spawned in the world. This includes - * players. - */ - public boolean spawnEntityInWorld(Entity entity) { - boolean flag = super.spawnEntityInWorld(entity); - this.entityList.add(entity); - if (!flag) { - this.entitySpawnQueue.add(entity); - } else if (entity instanceof EntityMinecart) { - this.mc.getSoundHandler().playSound(new MovingSoundMinecart((EntityMinecart) entity)); - } - - return flag; - } - - /**+ - * Schedule the entity for removal during the next tick. Marks - * the entity dead in anticipation. - */ - public void removeEntity(Entity entity) { - super.removeEntity(entity); - this.entityList.remove(entity); - } - - protected void onEntityAdded(Entity entity) { - super.onEntityAdded(entity); - if (this.entitySpawnQueue.contains(entity)) { - this.entitySpawnQueue.remove(entity); - } - - } - - protected void onEntityRemoved(Entity entity) { - super.onEntityRemoved(entity); - boolean flag = false; - if (this.entityList.contains(entity)) { - if (entity.isEntityAlive()) { - this.entitySpawnQueue.add(entity); - flag = true; - } else { - this.entityList.remove(entity); - } - } - - } - - /**+ - * Add an ID to Entity mapping to entityHashSet + /** + * + Add an ID to Entity mapping to entityHashSet */ public void addEntityToWorld(int parInt1, Entity parEntity) { Entity entity = this.getEntityByID(parInt1); @@ -232,47 +107,56 @@ public class WorldClient extends World { this.entitiesById.addKey(parInt1, parEntity); } - /**+ - * Returns the Entity with the given ID, or null if it doesn't - * exist in this World. + /** + * + Adds some basic stats of the world to the given crash report. */ - public Entity getEntityByID(int i) { - return (Entity) (i == this.mc.thePlayer.getEntityId() ? this.mc.thePlayer : super.getEntityByID(i)); + public CrashReportCategory addWorldInfoToCrashReport(CrashReport crashreport) { + CrashReportCategory crashreportcategory = super.addWorldInfoToCrashReport(crashreport); + crashreportcategory.addCrashSectionCallable("Forced entities", new Callable() { + public String call() { + return WorldClient.this.entityList.size() + " total; " + WorldClient.this.entityList.toString(); + } + }); + crashreportcategory.addCrashSectionCallable("Retry entities", new Callable() { + public String call() { + return WorldClient.this.entitySpawnQueue.size() + " total; " + + WorldClient.this.entitySpawnQueue.toString(); + } + }); + crashreportcategory.addCrashSectionCallable("Server brand", new Callable() { + public String call() throws Exception { + return WorldClient.this.mc.thePlayer.getClientBrand(); + } + }); + crashreportcategory.addCrashSectionCallable("Server type", new Callable() { + public String call() throws Exception { + return "Non-integrated multiplayer server"; + } + }); + return crashreportcategory; } - public Entity removeEntityFromWorld(int parInt1) { - Entity entity = (Entity) this.entitiesById.removeObject(parInt1); - if (entity != null) { - this.entityList.remove(entity); - this.removeEntity(entity); + /** + * + Creates the chunk provider for this world. Called in the constructor. + * Retrieves provider from worldProvider? + */ + protected IChunkProvider createChunkProvider() { + this.clientChunkProvider = new ChunkProviderClient(this); + return this.clientChunkProvider; + } + + public void doPreChunk(int parInt1, int parInt2, boolean parFlag) { + if (parFlag) { + this.clientChunkProvider.loadChunk(parInt1, parInt2); + } else { + this.clientChunkProvider.unloadChunk(parInt1, parInt2); } - return entity; - } + if (!parFlag) { + this.markBlockRangeForRenderUpdate(parInt1 * 16, 0, parInt2 * 16, parInt1 * 16 + 15, 256, + parInt2 * 16 + 15); + } - public boolean invalidateRegionAndSetBlock(BlockPos parBlockPos, IBlockState parIBlockState) { - int i = parBlockPos.getX(); - int j = parBlockPos.getY(); - int k = parBlockPos.getZ(); - this.invalidateBlockReceiveRegion(i, j, k, i, j, k); - return super.setBlockState(parBlockPos, parIBlockState, 3); - } - - /**+ - * If on MP, sends a quitting packet. - */ - public void sendQuittingDisconnectingPacket() { - this.sendQueue.getNetworkManager().closeChannel(new ChatComponentText("Quitting")); - } - - /**+ - * Updates all weather states. - */ - protected void updateWeather() { - } - - protected int getRenderDistanceChunks() { - return this.mc.gameSettings.renderDistanceChunks; } public void doVoidFogParticles(int parInt1, int parInt2, int parInt3) { @@ -298,8 +182,90 @@ public class WorldClient extends World { } - /**+ - * also releases skins. + /** + * + Returns the Entity with the given ID, or null if it doesn't exist in this + * World. + */ + public Entity getEntityByID(int i) { + return (Entity) (i == this.mc.thePlayer.getEntityId() ? this.mc.thePlayer : super.getEntityByID(i)); + } + + protected int getRenderDistanceChunks() { + return this.mc.gameSettings.renderDistanceChunks; + } + + /** + * + Invalidates an AABB region of blocks from the receive queue, in the event + * that the block has been modified client-side in the intervening 80 receive + * ticks. + */ + public void invalidateBlockReceiveRegion(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, + int parInt6) { + } + + public boolean invalidateRegionAndSetBlock(BlockPos parBlockPos, IBlockState parIBlockState) { + int i = parBlockPos.getX(); + int j = parBlockPos.getY(); + int k = parBlockPos.getZ(); + this.invalidateBlockReceiveRegion(i, j, k, i, j, k); + return super.setBlockState(parBlockPos, parIBlockState, 3); + } + + public void makeFireworks(double d0, double d1, double d2, double d3, double d4, double d5, + NBTTagCompound nbttagcompound) { + this.mc.effectRenderer.addEffect( + new EntityFirework.StarterFX(this, d0, d1, d2, d3, d4, d5, this.mc.effectRenderer, nbttagcompound)); + } + + protected void onEntityAdded(Entity entity) { + super.onEntityAdded(entity); + if (this.entitySpawnQueue.contains(entity)) { + this.entitySpawnQueue.remove(entity); + } + + } + + protected void onEntityRemoved(Entity entity) { + super.onEntityRemoved(entity); + boolean flag = false; + if (this.entityList.contains(entity)) { + if (entity.isEntityAlive()) { + this.entitySpawnQueue.add(entity); + flag = true; + } else { + this.entityList.remove(entity); + } + } + + } + + /** + * + par8 is loudness, all pars passed to minecraftInstance.sndManager.playSound + */ + public void playSound(double d0, double d1, double d2, String s, float f, float f1, boolean flag) { + double d3 = this.mc.getRenderViewEntity().getDistanceSq(d0, d1, d2); + PositionedSoundRecord positionedsoundrecord = new PositionedSoundRecord(new ResourceLocation(s), f, f1, + (float) d0, (float) d1, (float) d2); + if (flag && d3 > 100.0D) { + double d4 = Math.sqrt(d3) / 40.0D; + this.mc.getSoundHandler().playDelayedSound(positionedsoundrecord, (int) (d4 * 20.0D)); + } else { + this.mc.getSoundHandler().playSound(positionedsoundrecord); + } + + } + + /** + * + Plays a sound at the specified position. + */ + public void playSoundAtPos(BlockPos parBlockPos, String parString1, float parFloat1, float parFloat2, + boolean parFlag) { + this.playSound((double) parBlockPos.getX() + 0.5D, (double) parBlockPos.getY() + 0.5D, + (double) parBlockPos.getZ() + 0.5D, parString1, parFloat1, parFloat2, parFlag); + } + + /** + * + also releases skins. */ public void removeAllEntities() { this.loadedEntityList.removeAll(this.unloadedEntityList); @@ -344,73 +310,38 @@ public class WorldClient extends World { } - /**+ - * Adds some basic stats of the world to the given crash report. + /** + * + Schedule the entity for removal during the next tick. Marks the entity dead + * in anticipation. */ - public CrashReportCategory addWorldInfoToCrashReport(CrashReport crashreport) { - CrashReportCategory crashreportcategory = super.addWorldInfoToCrashReport(crashreport); - crashreportcategory.addCrashSectionCallable("Forced entities", new Callable() { - public String call() { - return WorldClient.this.entityList.size() + " total; " + WorldClient.this.entityList.toString(); - } - }); - crashreportcategory.addCrashSectionCallable("Retry entities", new Callable() { - public String call() { - return WorldClient.this.entitySpawnQueue.size() + " total; " - + WorldClient.this.entitySpawnQueue.toString(); - } - }); - crashreportcategory.addCrashSectionCallable("Server brand", new Callable() { - public String call() throws Exception { - return WorldClient.this.mc.thePlayer.getClientBrand(); - } - }); - crashreportcategory.addCrashSectionCallable("Server type", new Callable() { - public String call() throws Exception { - return "Non-integrated multiplayer server"; - } - }); - return crashreportcategory; + public void removeEntity(Entity entity) { + super.removeEntity(entity); + this.entityList.remove(entity); } - /**+ - * Plays a sound at the specified position. - */ - public void playSoundAtPos(BlockPos parBlockPos, String parString1, float parFloat1, float parFloat2, - boolean parFlag) { - this.playSound((double) parBlockPos.getX() + 0.5D, (double) parBlockPos.getY() + 0.5D, - (double) parBlockPos.getZ() + 0.5D, parString1, parFloat1, parFloat2, parFlag); - } - - /**+ - * par8 is loudness, all pars passed to - * minecraftInstance.sndManager.playSound - */ - public void playSound(double d0, double d1, double d2, String s, float f, float f1, boolean flag) { - double d3 = this.mc.getRenderViewEntity().getDistanceSq(d0, d1, d2); - PositionedSoundRecord positionedsoundrecord = new PositionedSoundRecord(new ResourceLocation(s), f, f1, - (float) d0, (float) d1, (float) d2); - if (flag && d3 > 100.0D) { - double d4 = Math.sqrt(d3) / 40.0D; - this.mc.getSoundHandler().playDelayedSound(positionedsoundrecord, (int) (d4 * 20.0D)); - } else { - this.mc.getSoundHandler().playSound(positionedsoundrecord); + public Entity removeEntityFromWorld(int parInt1) { + Entity entity = (Entity) this.entitiesById.removeObject(parInt1); + if (entity != null) { + this.entityList.remove(entity); + this.removeEntity(entity); } + return entity; } - public void makeFireworks(double d0, double d1, double d2, double d3, double d4, double d5, - NBTTagCompound nbttagcompound) { - this.mc.effectRenderer.addEffect( - new EntityFirework.StarterFX(this, d0, d1, d2, d3, d4, d5, this.mc.effectRenderer, nbttagcompound)); + /** + * + If on MP, sends a quitting packet. + */ + public void sendQuittingDisconnectingPacket() { + this.sendQueue.getNetworkManager().closeChannel(new ChatComponentText("Quitting")); } public void setWorldScoreboard(Scoreboard parScoreboard) { this.worldScoreboard = parScoreboard; } - /**+ - * Sets the world time. + /** + * + Sets the world time. */ public void setWorldTime(long i) { if (i < 0L) { @@ -422,4 +353,72 @@ public class WorldClient extends World { super.setWorldTime(i); } + + /** + * + Called when an entity is spawned in the world. This includes players. + */ + public boolean spawnEntityInWorld(Entity entity) { + boolean flag = super.spawnEntityInWorld(entity); + this.entityList.add(entity); + if (!flag) { + this.entitySpawnQueue.add(entity); + } else if (entity instanceof EntityMinecart) { + this.mc.getSoundHandler().playSound(new MovingSoundMinecart((EntityMinecart) entity)); + } + + return flag; + } + + /** + * + Runs a single tick for the world + */ + public void tick() { + super.tick(); + this.setTotalWorldTime(this.getTotalWorldTime() + 1L); + if (this.getGameRules().getBoolean("doDaylightCycle")) { + this.setWorldTime(this.getWorldTime() + 1L); + } + + for (int i = 0; i < 10 && !this.entitySpawnQueue.isEmpty(); ++i) { + Entity entity = (Entity) this.entitySpawnQueue.iterator().next(); + this.entitySpawnQueue.remove(entity); + if (!this.loadedEntityList.contains(entity)) { + this.spawnEntityInWorld(entity); + } + } + + this.clientChunkProvider.unloadQueuedChunks(); + this.updateBlocks(); + } + + protected void updateBlocks() { + super.updateBlocks(); + this.previousActiveChunkSet.retainAll(this.activeChunkSet); + if (this.previousActiveChunkSet.size() == this.activeChunkSet.size()) { + this.previousActiveChunkSet.clear(); + } + + int i = 0; + + for (ChunkCoordIntPair chunkcoordintpair : this.activeChunkSet) { + if (!this.previousActiveChunkSet.contains(chunkcoordintpair)) { + int j = chunkcoordintpair.chunkXPos * 16; + int k = chunkcoordintpair.chunkZPos * 16; + Chunk chunk = this.getChunkFromChunkCoords(chunkcoordintpair.chunkXPos, chunkcoordintpair.chunkZPos); + this.playMoodSoundAndCheckLight(j, k, chunk); + this.previousActiveChunkSet.add(chunkcoordintpair); + ++i; + if (i >= 10) { + return; + } + } + } + + } + + /** + * + Updates all weather states. + */ + protected void updateWeather() { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/network/NetHandlerPlayClient.java b/src/game/java/net/minecraft/client/network/NetHandlerPlayClient.java index c45575d2..ad10c99e 100644 --- a/src/game/java/net/minecraft/client/network/NetHandlerPlayClient.java +++ b/src/game/java/net/minecraft/client/network/NetHandlerPlayClient.java @@ -6,12 +6,15 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import com.google.common.collect.Maps; + import net.lax1dude.eaglercraft.v1_8.ClientUUIDLoadingCache; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - -import com.google.common.collect.Maps; - +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerFolderResourcePack; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.notifications.ServerNotificationManager; import net.lax1dude.eaglercraft.v1_8.profile.ServerCapeCache; @@ -24,10 +27,6 @@ import net.lax1dude.eaglercraft.v1_8.sp.lan.LANClientNetworkManager; import net.lax1dude.eaglercraft.v1_8.sp.socket.ClientIntegratedServerNetworkManager; import net.lax1dude.eaglercraft.v1_8.voice.VoiceClientController; import net.lax1dude.eaglercraft.v1_8.webview.WebViewOverlayController; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerFolderResourcePack; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.block.Block; import net.minecraft.client.ClientBrandRetriever; import net.minecraft.client.Minecraft; @@ -219,22 +218,25 @@ import net.minecraft.world.WorldSettings; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -251,10 +253,9 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { public int currentServerMaxPlayers = 20; private boolean field_147308_k = false; private boolean isIntegratedServer = false; - /**+ - * Just an ordinary random number generator, used to randomize - * audio pitch of item/orb pickup and randomize both - * particlespawn offset and velocity + /** + * + Just an ordinary random number generator, used to randomize audio pitch of + * item/orb pickup and randomize both particlespawn offset and velocity */ private final EaglercraftRandom avRandomizer = new EaglercraftRandom(); private final ServerSkinCache skinCache; @@ -279,9 +280,12 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { || (parNetworkManager instanceof LANClientNetworkManager); } - /**+ - * Clears the WorldClient instance associated with this - * NetHandlerPlayClient + public void addToSendQueue(Packet parPacket) { + this.netManager.sendPacket(parPacket); + } + + /** + * + Clears the WorldClient instance associated with this NetHandlerPlayClient */ public void cleanup() { this.clientWorldController = null; @@ -290,60 +294,584 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { this.notifManager.destroy(); } - public ServerSkinCache getSkinCache() { - return this.skinCache; - } - public ServerCapeCache getCapeCache() { return this.capeCache; } - public ServerNotificationManager getNotifManager() { - return this.notifManager; - } - public GameProtocolMessageController getEaglerMessageController() { return eaglerMessageController; } - public void setEaglerMessageController(GameProtocolMessageController eaglerMessageController) { - this.eaglerMessageController = eaglerMessageController; - } - public GamePluginMessageProtocol getEaglerMessageProtocol() { return eaglerMessageController != null ? eaglerMessageController.protocol : null; } - public void sendEaglerMessage(GameMessagePacket packet) { - try { - eaglerMessageController.sendPacket(packet); - } catch (IOException e) { - logger.error("Failed to send eaglercraft plugin message packet: " + packet); - logger.error(e); + public GameProfile getGameProfile() { + return this.profile; + } + + /** + * + Returns this the NetworkManager instance registered with this + * NetworkHandlerPlayClient + */ + public EaglercraftNetworkManager getNetworkManager() { + return this.netManager; + } + + public ServerNotificationManager getNotifManager() { + return this.notifManager; + } + + /** + * + Gets the client's description information about another player on the + * server. + */ + public NetworkPlayerInfo getPlayerInfo(EaglercraftUUID parUUID) { + return (NetworkPlayerInfo) this.playerInfoMap.get(parUUID); + } + + /** + * + Gets the client's description information about another player on the + * server. + */ + public NetworkPlayerInfo getPlayerInfo(String parString1) { + for (NetworkPlayerInfo networkplayerinfo : this.playerInfoMap.values()) { + if (networkplayerinfo.getGameProfile().getName().equals(parString1)) { + return networkplayerinfo; + } + } + + return null; + } + + public Collection getPlayerInfoMap() { + return this.playerInfoMap.values(); + } + + public ServerSkinCache getSkinCache() { + return this.skinCache; + } + + /** + * + Renders a specified animation: Waking up a player, a living entity swinging + * its currently held item, being hurt or receiving a critical hit by normal or + * magical means + */ + public void handleAnimation(S0BPacketAnimation packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); + if (entity != null) { + if (packetIn.getAnimationType() == 0) { + EntityLivingBase entitylivingbase = (EntityLivingBase) entity; + entitylivingbase.swingItem(); + } else if (packetIn.getAnimationType() == 1) { + entity.performHurtAnimation(); + } else if (packetIn.getAnimationType() == 2) { + EntityPlayer entityplayer = (EntityPlayer) entity; + entityplayer.wakeUpPlayer(false, false, false); + } else if (packetIn.getAnimationType() == 4) { + this.gameController.effectRenderer.emitParticleAtEntity(entity, EnumParticleTypes.CRIT); + } else if (packetIn.getAnimationType() == 5) { + this.gameController.effectRenderer.emitParticleAtEntity(entity, EnumParticleTypes.CRIT_MAGIC); + } + } } - public boolean webViewSendHandler(GameMessagePacket pkt) { - if (eaglerMessageController == null) { - return false; + /** + * + Triggers Block.onBlockEventReceived, which is implemented in + * BlockPistonBase for extension/retraction, BlockNote for setting the + * instrument (including audiovisual feedback) and in BlockContainer to set the + * number of players accessing a (Ender)Chest + */ + public void handleBlockAction(S24PacketBlockAction packetIn) { + this.gameController.theWorld.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), + packetIn.getData1(), packetIn.getData2()); + } + + /** + * + Updates all registered IWorldAccess instances with + * destroyBlockInWorldPartially + */ + public void handleBlockBreakAnim(S25PacketBlockBreakAnim packetIn) { + this.gameController.theWorld.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), + packetIn.getProgress()); + } + + /** + * + Updates the block and metadata and generates a blockupdate (and notify the + * clients) + */ + public void handleBlockChange(S23PacketBlockChange packetIn) { + this.clientWorldController.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); + } + + public void handleCamera(S43PacketCamera packetIn) { + + Entity entity = packetIn.getEntity(this.clientWorldController); + if (entity != null) { + this.gameController.setRenderViewEntity(entity); } - if (this.gameController.thePlayer == null || this.gameController.thePlayer.sendQueue != this) { - logger.error("WebView sent message on a dead handler!"); - return false; + + } + + public void handleChangeGameState(S2BPacketChangeGameState packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + int i = packetIn.getGameState(); + float f = packetIn.func_149137_d(); + int j = MathHelper.floor_float(f + 0.5F); + if (i >= 0 && i < S2BPacketChangeGameState.MESSAGE_NAMES.length + && S2BPacketChangeGameState.MESSAGE_NAMES[i] != null) { + entityplayersp.addChatComponentMessage( + new ChatComponentTranslation(S2BPacketChangeGameState.MESSAGE_NAMES[i], new Object[0])); } - if (eaglerMessageController.protocol.ver >= 4) { - sendEaglerMessage(pkt); - return true; + + if (i == 1) { + this.clientWorldController.getWorldInfo().setRaining(true); + this.clientWorldController.setRainStrength(0.0F); + } else if (i == 2) { + this.clientWorldController.getWorldInfo().setRaining(false); + this.clientWorldController.setRainStrength(1.0F); + } else if (i == 3) { + this.gameController.playerController.setGameType(WorldSettings.GameType.getByID(j)); + } else if (i == 4) { + this.gameController.displayGuiScreen(new GuiWinGame()); + } else if (i == 5) { + + // minecraft demo screen + + } else if (i == 6) { + this.clientWorldController.playSound(entityplayersp.posX, + entityplayersp.posY + (double) entityplayersp.getEyeHeight(), entityplayersp.posZ, + "random.successful_hit", 0.18F, 0.45F, false); + } else if (i == 7) { + this.clientWorldController.setRainStrength(f); + } else if (i == 8) { + this.clientWorldController.setThunderStrength(f); + } else if (i == 10) { + this.clientWorldController.spawnParticle(EnumParticleTypes.MOB_APPEARANCE, entityplayersp.posX, + entityplayersp.posY, entityplayersp.posZ, 0.0D, 0.0D, 0.0D, new int[0]); + this.clientWorldController.playSound(entityplayersp.posX, entityplayersp.posY, entityplayersp.posZ, + "mob.guardian.curse", 1.0F, 1.0F, false); + } + + } + + /** + * + Prints a chatmessage in the chat GUI + */ + public void handleChat(S02PacketChat packetIn) { + if (packetIn.getType() == 2) { + this.gameController.ingameGUI.setRecordPlaying(packetIn.getChatComponent(), false); } else { - return false; + this.gameController.ingameGUI.getChatGUI().printChatMessage(packetIn.getChatComponent()); + } + + } + + /** + * + Updates the specified chunk with the supplied data, marks it for + * re-rendering and lighting recalculation + */ + public void handleChunkData(S21PacketChunkData packetIn) { + if (packetIn.func_149274_i()) { + if (packetIn.getExtractedSize() == 0) { + this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false); + return; + } + + this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); + } + + this.clientWorldController.invalidateBlockReceiveRegion(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, + (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15); + Chunk chunk = this.clientWorldController.getChunkFromChunkCoords(packetIn.getChunkX(), packetIn.getChunkZ()); + chunk.fillChunk(packetIn.func_149272_d(), packetIn.getExtractedSize(), packetIn.func_149274_i()); + this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, + packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15); + if (!packetIn.func_149274_i() || !(this.clientWorldController.provider instanceof WorldProviderSurface)) { + chunk.resetRelightChecks(); + } + + } + + /** + * + Resets the ItemStack held in hand and closes the window that is opened + */ + public void handleCloseWindow(S2EPacketCloseWindow packetIn) { + this.gameController.thePlayer.closeScreenAndDropStack(); + } + + public void handleCollectItem(S0DPacketCollectItem packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getCollectedItemEntityID()); + Object object = (EntityLivingBase) this.clientWorldController.getEntityByID(packetIn.getEntityID()); + if (object == null) { + object = this.gameController.thePlayer; + } + + if (entity != null) { + if (entity instanceof EntityXPOrb) { + this.clientWorldController.playSoundAtEntity(entity, "random.orb", 0.2F, + ((this.avRandomizer.nextFloat() - this.avRandomizer.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } else { + this.clientWorldController.playSoundAtEntity(entity, "random.pop", 0.2F, + ((this.avRandomizer.nextFloat() - this.avRandomizer.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + + this.gameController.effectRenderer + .addEffect(new EntityPickupFX(this.clientWorldController, entity, (Entity) object, 0.5F)); + this.clientWorldController.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); + } + + } + + public void handleCombatEvent(S42PacketCombatEvent packetIn) { + + // used by twitch stream + + } + + /** + * + Verifies that the server and client are synchronized with respect to the + * inventory/container opened by the player and confirms if it is the case. + */ + public void handleConfirmTransaction(S32PacketConfirmTransaction packetIn) { + Container container = null; + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + if (packetIn.getWindowId() == 0) { + container = entityplayersp.inventoryContainer; + } else if (packetIn.getWindowId() == entityplayersp.openContainer.windowId) { + container = entityplayersp.openContainer; + } + + if (container != null && !packetIn.func_148888_e()) { + this.addToSendQueue( + new C0FPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); + } + + } + + /** + * + Handles packets that have room for a channel specification. Vanilla + * implemented channels are "MC|TrList" to acquire a MerchantRecipeList trades + * for a villager merchant, "MC|Brand" which sets the server brand? on the + * player instance and finally "MC|RPack" which the server uses to communicate + * the identifier of the default server resourcepack for the client to load. + */ + public void handleCustomPayload(S3FPacketCustomPayload packetIn) { + if ("MC|TrList".equals(packetIn.getChannelName())) { + PacketBuffer packetbuffer = packetIn.getBufferData(); + try { + int i = packetbuffer.readInt(); + GuiScreen guiscreen = this.gameController.currentScreen; + if (guiscreen != null && guiscreen instanceof GuiMerchant + && i == this.gameController.thePlayer.openContainer.windowId) { + IMerchant imerchant = ((GuiMerchant) guiscreen).getMerchant(); + MerchantRecipeList merchantrecipelist = MerchantRecipeList.readFromBuf(packetbuffer); + imerchant.setRecipes(merchantrecipelist); + } + } catch (IOException ioexception) { + logger.error("Couldn\'t load trade info", ioexception); + } + } else if ("MC|Brand".equals(packetIn.getChannelName())) { + this.gameController.thePlayer.setClientBrand(packetIn.getBufferData().readStringFromBuffer(32767)); + } else if ("MC|BOpen".equals(packetIn.getChannelName())) { + ItemStack itemstack = this.gameController.thePlayer.getCurrentEquippedItem(); + if (itemstack != null && itemstack.getItem() == Items.written_book) { + this.gameController + .displayGuiScreen(new GuiScreenBook(this.gameController.thePlayer, itemstack, false)); + } + } else { + try { + eaglerMessageController.handlePacket(packetIn.getChannelName(), packetIn.getBufferData()); + } catch (IOException e) { + logger.error("Couldn't read \"{}\" packet as an eaglercraft plugin message!", + packetIn.getChannelName()); + logger.error(e); + } } } - /**+ - * Registers some server properties - * (gametype,hardcore-mode,terraintype,difficulty,player limit), - * creates a new WorldClient and sets the player initial - * dimension + /** + * + Locally eliminates the entities. Invoked by the server when the items are + * in fact destroyed, or the player is no longer registered as required to + * monitor them. The latter happens when distance between the player and item + * increases beyond a certain treshold (typically the viewing distance) + */ + public void handleDestroyEntities(S13PacketDestroyEntities packetIn) { + for (int i = 0; i < packetIn.getEntityIDs().length; ++i) { + this.clientWorldController.removeEntityFromWorld(packetIn.getEntityIDs()[i]); + } + + } + + /** + * + Closes the network channel + */ + public void handleDisconnect(S40PacketDisconnect packetIn) { + this.netManager.closeChannel(packetIn.getReason()); + } + + /** + * + Removes or sets the ScoreObjective to be displayed at a particular + * scoreboard position (list, sidebar, below name) + */ + public void handleDisplayScoreboard(S3DPacketDisplayScoreboard packetIn) { + Scoreboard scoreboard = this.clientWorldController.getScoreboard(); + if (packetIn.func_149370_d().length() == 0) { + scoreboard.setObjectiveInDisplaySlot(packetIn.func_149371_c(), (ScoreObjective) null); + } else { + ScoreObjective scoreobjective = scoreboard.getObjective(packetIn.func_149370_d()); + scoreboard.setObjectiveInDisplaySlot(packetIn.func_149371_c(), scoreobjective); + } + + } + + public void handleEffect(S28PacketEffect packetIn) { + if (packetIn.isSoundServerwide()) { + this.gameController.theWorld.playBroadcastSound(packetIn.getSoundType(), packetIn.getSoundPos(), + packetIn.getSoundData()); + } else { + this.gameController.theWorld.playAuxSFX(packetIn.getSoundType(), packetIn.getSoundPos(), + packetIn.getSoundData()); + } + + } + + public void handleEntityAttach(S1BPacketEntityAttach packetIn) { + Object object = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + Entity entity = this.clientWorldController.getEntityByID(packetIn.getVehicleEntityId()); + if (packetIn.getLeash() == 0) { + boolean flag = false; + if (packetIn.getEntityId() == this.gameController.thePlayer.getEntityId()) { + object = this.gameController.thePlayer; + if (entity instanceof EntityBoat) { + ((EntityBoat) entity).setIsBoatEmpty(false); + } + + flag = ((Entity) object).ridingEntity == null && entity != null; + } else if (entity instanceof EntityBoat) { + ((EntityBoat) entity).setIsBoatEmpty(true); + } + + if (object == null) { + return; + } + + ((Entity) object).mountEntity(entity); + if (flag) { + GameSettings gamesettings = this.gameController.gameSettings; + this.gameController.ingameGUI.setRecordPlaying( + I18n.format("mount.onboard", + new Object[] { + GameSettings.getKeyDisplayString(gamesettings.keyBindSneak.getKeyCode()) }), + false); + } + } else if (packetIn.getLeash() == 1 && object instanceof EntityLiving) { + if (entity != null) { + ((EntityLiving) object).setLeashedToEntity(entity, false); + } else { + ((EntityLiving) object).clearLeashed(false, false); + } + } + + } + + public void handleEntityEffect(S1DPacketEntityEffect packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + if (entity instanceof EntityLivingBase) { + PotionEffect potioneffect = new PotionEffect(packetIn.getEffectId(), packetIn.getDuration(), + packetIn.getAmplifier(), false, packetIn.func_179707_f()); + potioneffect.setPotionDurationMax(packetIn.func_149429_c()); + ((EntityLivingBase) entity).addPotionEffect(potioneffect); + } + } + + public void handleEntityEquipment(S04PacketEntityEquipment packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); + if (entity != null) { + entity.setCurrentItemOrArmor(packetIn.getEquipmentSlot(), packetIn.getItemStack()); + } + + } + + /** + * + Updates the direction in which the specified entity is looking, normally + * this head rotation is independent of the rotation of the entity itself + */ + public void handleEntityHeadLook(S19PacketEntityHeadLook packetIn) { + Entity entity = packetIn.getEntity(this.clientWorldController); + if (entity != null) { + float f = (float) (packetIn.getYaw() * 360) / 256.0F; + entity.setRotationYawHead(f); + } + } + + /** + * + Invoked when the server registers new proximate objects in your watchlist + * or when objects in your watchlist have changed -> Registers any changes + * locally + */ + public void handleEntityMetadata(S1CPacketEntityMetadata packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + if (entity != null && packetIn.func_149376_c() != null) { + entity.getDataWatcher().updateWatchedObjectsFromList(packetIn.func_149376_c()); + } + + } + + /** + * + Updates the specified entity's position by the specified relative moment + * and absolute rotation. Note that subclassing of the packet allows for the + * specification of a subset of this data (e.g. only rel. position, abs. + * rotation or both). + */ + public void handleEntityMovement(S14PacketEntity packetIn) { + Entity entity = packetIn.getEntity(this.clientWorldController); + if (entity != null) { + entity.serverPosX += packetIn.func_149062_c(); + entity.serverPosY += packetIn.func_149061_d(); + entity.serverPosZ += packetIn.func_149064_e(); + double d0 = (double) entity.serverPosX / 32.0D; + double d1 = (double) entity.serverPosY / 32.0D; + double d2 = (double) entity.serverPosZ / 32.0D; + float f = packetIn.func_149060_h() ? (float) (packetIn.func_149066_f() * 360) / 256.0F : entity.rotationYaw; + float f1 = packetIn.func_149060_h() ? (float) (packetIn.func_149063_g() * 360) / 256.0F + : entity.rotationPitch; + entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, false); + entity.onGround = packetIn.getOnGround(); + } + } + + public void handleEntityNBT(S49PacketUpdateEntityNBT packetIn) { + Entity entity = packetIn.getEntity(this.clientWorldController); + if (entity != null) { + entity.clientUpdateEntityNBT(packetIn.getTagCompound()); + } + + } + + /** + * + Updates en entity's attributes and their respective modifiers, which are + * used for speed bonusses (player sprinting, animals fleeing, baby speed), + * weapon/tool attackDamage, hostiles followRange randomization, zombie + * maxHealth and knockback resistance as well as reinforcement spawning chance. + */ + public void handleEntityProperties(S20PacketEntityProperties packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + if (entity != null) { + if (!(entity instanceof EntityLivingBase)) { + throw new IllegalStateException( + "Server tried to update attributes of a non-living entity (actually: " + entity + ")"); + } else { + BaseAttributeMap baseattributemap = ((EntityLivingBase) entity).getAttributeMap(); + + List lst = packetIn.func_149441_d(); + for (int i = 0, l = lst.size(); i < l; ++i) { + S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot = lst.get(i); + IAttributeInstance iattributeinstance = baseattributemap + .getAttributeInstanceByName(s20packetentityproperties$snapshot.func_151409_a()); + if (iattributeinstance == null) { + iattributeinstance = baseattributemap.registerAttribute(new RangedAttribute((IAttribute) null, + s20packetentityproperties$snapshot.func_151409_a(), 0.0D, 2.2250738585072014E-308D, + Double.MAX_VALUE)); + } + + iattributeinstance.setBaseValue(s20packetentityproperties$snapshot.func_151410_b()); + iattributeinstance.removeAllModifiers(); + + for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c()) { + iattributeinstance.applyModifier(attributemodifier); + } + } + + } + } + } + + /** + * + Invokes the entities' handleUpdateHealth method which is implemented in + * LivingBase (hurt/death), MinecartMobSpawner (spawn delay), FireworkRocket & + * MinecartTNT (explosion), IronGolem (throwing,...), Witch (spawn particles), + * Zombie (villager transformation), Animal (breeding mode particles), Horse + * (breeding/smoke particles), Sheep (...), Tameable (...), Villager (particles + * for breeding mode, angry and happy), Wolf (...) + */ + public void handleEntityStatus(S19PacketEntityStatus packetIn) { + Entity entity = packetIn.getEntity(this.clientWorldController); + if (entity != null) { + if (packetIn.getOpCode() == 21) { + this.gameController.getSoundHandler().playSound(new GuardianSound((EntityGuardian) entity)); + } else { + entity.handleStatusUpdate(packetIn.getOpCode()); + } + } + + } + + /** + * + Updates an entity's position and rotation as specified by the packet + */ + public void handleEntityTeleport(S18PacketEntityTeleport packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + if (entity != null) { + entity.serverPosX = packetIn.getX(); + entity.serverPosY = packetIn.getY(); + entity.serverPosZ = packetIn.getZ(); + double d0 = (double) entity.serverPosX / 32.0D; + double d1 = (double) entity.serverPosY / 32.0D; + double d2 = (double) entity.serverPosZ / 32.0D; + float f = (float) (packetIn.getYaw() * 360) / 256.0F; + float f1 = (float) (packetIn.getPitch() * 360) / 256.0F; + if (Math.abs(entity.posX - d0) < 0.03125D && Math.abs(entity.posY - d1) < 0.015625D + && Math.abs(entity.posZ - d2) < 0.03125D) { + entity.setPositionAndRotation2(entity.posX, entity.posY, entity.posZ, f, f1, 3, true); + } else { + entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, true); + } + + entity.onGround = packetIn.getOnGround(); + } + } + + /** + * + Sets the velocity of the specified entity to the specified value + */ + public void handleEntityVelocity(S12PacketEntityVelocity packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); + if (entity != null) { + entity.setVelocity((double) packetIn.getMotionX() / 8000.0D, (double) packetIn.getMotionY() / 8000.0D, + (double) packetIn.getMotionZ() / 8000.0D); + } + } + + /** + * + Initiates a new explosion (sound, particles, drop spawn) for the affected + * blocks indicated by the packet. + */ + public void handleExplosion(S27PacketExplosion packetIn) { + Explosion explosion = new Explosion(this.gameController.theWorld, (Entity) null, packetIn.getX(), + packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); + explosion.doExplosionB(true); + this.gameController.thePlayer.motionX += (double) packetIn.func_149149_c(); + this.gameController.thePlayer.motionY += (double) packetIn.func_149144_d(); + this.gameController.thePlayer.motionZ += (double) packetIn.func_149147_e(); + } + + /** + * + Updates which hotbar slot of the player is currently selected + */ + public void handleHeldItemChange(S09PacketHeldItemChange packetIn) { + if (packetIn.getHeldItemHotbarIndex() >= 0 + && packetIn.getHeldItemHotbarIndex() < InventoryPlayer.getHotbarSize()) { + this.gameController.thePlayer.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); + } + + } + + /** + * + Registers some server properties + * (gametype,hardcore-mode,terraintype,difficulty,player limit), creates a new + * WorldClient and sets the player initial dimension */ public void handleJoinGame(S01PacketJoinGame packetIn) { this.gameController.playerController = new PlayerControllerMP(this.gameController, this); @@ -366,9 +894,498 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { WebViewOverlayController.setPacketSendCallback(this::webViewSendHandler); } - /**+ - * Spawns an instance of the objecttype indicated by the packet - * and sets its position and momentum + public void handleKeepAlive(S00PacketKeepAlive packetIn) { + this.addToSendQueue(new C00PacketKeepAlive(packetIn.func_149134_c())); + } + + public void handleMapChunkBulk(S26PacketMapChunkBulk packetIn) { + for (int i = 0; i < packetIn.getChunkCount(); ++i) { + int j = packetIn.getChunkX(i); + int k = packetIn.getChunkZ(i); + this.clientWorldController.doPreChunk(j, k, true); + this.clientWorldController.invalidateBlockReceiveRegion(j << 4, 0, k << 4, (j << 4) + 15, 256, + (k << 4) + 15); + Chunk chunk = this.clientWorldController.getChunkFromChunkCoords(j, k); + chunk.fillChunk(packetIn.getChunkBytes(i), packetIn.getChunkSize(i), true); + this.clientWorldController.markBlockRangeForRenderUpdate(j << 4, 0, k << 4, (j << 4) + 15, 256, + (k << 4) + 15); + if (!(this.clientWorldController.provider instanceof WorldProviderSurface)) { + chunk.resetRelightChecks(); + } + } + + } + + /** + * + Updates the worlds MapStorage with the specified MapData for the specified + * map-identifier and invokes a MapItemRenderer for it + */ + public void handleMaps(S34PacketMaps packetIn) { + MapData mapdata = ItemMap.loadMapData(packetIn.getMapId(), this.gameController.theWorld); + packetIn.setMapdataTo(mapdata); + this.gameController.entityRenderer.getMapItemRenderer().updateMapTexture(mapdata); + } + + /** + * + Received from the servers PlayerManager if between 1 and 64 blocks in a + * chunk are changed. If only one block requires an update, the server sends + * S23PacketBlockChange and if 64 or more blocks are changed, the server sends + * S21PacketChunkData + */ + public void handleMultiBlockChange(S22PacketMultiBlockChange packetIn) { + BlockUpdateData[] dat = packetIn.getChangedBlocks(); + for (int i = 0; i < dat.length; ++i) { + BlockUpdateData s22packetmultiblockchange$blockupdatedata = dat[i]; + this.clientWorldController.invalidateRegionAndSetBlock(s22packetmultiblockchange$blockupdatedata.getPos(), + s22packetmultiblockchange$blockupdatedata.getBlockState()); + } + + } + + /** + * + Displays a GUI by ID. In order starting from id 0: Chest, Workbench, + * Furnace, Dispenser, Enchanting table, Brewing stand, Villager merchant, + * Beacon, Anvil, Hopper, Dropper, Horse + */ + public void handleOpenWindow(S2DPacketOpenWindow packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + if ("minecraft:container".equals(packetIn.getGuiId())) { + entityplayersp.displayGUIChest(new InventoryBasic(packetIn.getWindowTitle(), packetIn.getSlotCount())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); + } else if ("minecraft:villager".equals(packetIn.getGuiId())) { + entityplayersp.displayVillagerTradeGui(new NpcMerchant(entityplayersp, packetIn.getWindowTitle())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); + } else if ("EntityHorse".equals(packetIn.getGuiId())) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + if (entity instanceof EntityHorse) { + entityplayersp.displayGUIHorse((EntityHorse) entity, + new AnimalChest(packetIn.getWindowTitle(), packetIn.getSlotCount())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); + } + } else if (!packetIn.hasSlots()) { + entityplayersp.displayGui(new LocalBlockIntercommunication(packetIn.getGuiId(), packetIn.getWindowTitle())); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); + } else { + ContainerLocalMenu containerlocalmenu = new ContainerLocalMenu(packetIn.getGuiId(), + packetIn.getWindowTitle(), packetIn.getSlotCount()); + entityplayersp.displayGUIChest(containerlocalmenu); + entityplayersp.openContainer.windowId = packetIn.getWindowId(); + } + + } + + /** + * + Spawns a specified number of particles at the specified location with a + * randomized displacement according to specified bounds + */ + public void handleParticles(S2APacketParticles packetIn) { + if (packetIn.getParticleCount() == 0) { + double d0 = (double) (packetIn.getParticleSpeed() * packetIn.getXOffset()); + double d2 = (double) (packetIn.getParticleSpeed() * packetIn.getYOffset()); + double d4 = (double) (packetIn.getParticleSpeed() * packetIn.getZOffset()); + + try { + this.clientWorldController.spawnParticle(packetIn.getParticleType(), packetIn.isLongDistance(), + packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, + packetIn.getParticleArgs()); + } catch (Throwable var17) { + logger.warn("Could not spawn particle effect " + packetIn.getParticleType()); + } + } else { + for (int i = 0; i < packetIn.getParticleCount(); ++i) { + double d1 = this.avRandomizer.nextGaussian() * (double) packetIn.getXOffset(); + double d3 = this.avRandomizer.nextGaussian() * (double) packetIn.getYOffset(); + double d5 = this.avRandomizer.nextGaussian() * (double) packetIn.getZOffset(); + double d6 = this.avRandomizer.nextGaussian() * (double) packetIn.getParticleSpeed(); + double d7 = this.avRandomizer.nextGaussian() * (double) packetIn.getParticleSpeed(); + double d8 = this.avRandomizer.nextGaussian() * (double) packetIn.getParticleSpeed(); + + try { + this.clientWorldController.spawnParticle(packetIn.getParticleType(), packetIn.isLongDistance(), + packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, + packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); + } catch (Throwable var16) { + logger.warn("Could not spawn particle effect " + packetIn.getParticleType()); + return; + } + } + } + + } + + public void handlePlayerAbilities(S39PacketPlayerAbilities packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + entityplayersp.capabilities.isFlying = packetIn.isFlying(); + entityplayersp.capabilities.isCreativeMode = packetIn.isCreativeMode(); + entityplayersp.capabilities.disableDamage = packetIn.isInvulnerable(); + entityplayersp.capabilities.allowFlying = packetIn.isAllowFlying(); + entityplayersp.capabilities.setFlySpeed(packetIn.getFlySpeed()); + entityplayersp.capabilities.setPlayerWalkSpeed(packetIn.getWalkSpeed()); + } + + public void handlePlayerListHeaderFooter(S47PacketPlayerListHeaderFooter packetIn) { + this.gameController.ingameGUI.getTabList() + .setHeader(packetIn.getHeader().getFormattedText().length() == 0 ? null : packetIn.getHeader()); + this.gameController.ingameGUI.getTabList() + .setFooter(packetIn.getFooter().getFormattedText().length() == 0 ? null : packetIn.getFooter()); + } + + public void handlePlayerListItem(S38PacketPlayerListItem packetIn) { + List lst = packetIn.func_179767_a(); + for (int i = 0, l = lst.size(); i < l; ++i) { + S38PacketPlayerListItem.AddPlayerData s38packetplayerlistitem$addplayerdata = lst.get(i); + if (packetIn.func_179768_b() == S38PacketPlayerListItem.Action.REMOVE_PLAYER) { + EaglercraftUUID uuid = s38packetplayerlistitem$addplayerdata.getProfile().getId(); + this.playerInfoMap.remove(uuid); + this.skinCache.evictSkin(uuid); + this.capeCache.evictCape(uuid); + ClientUUIDLoadingCache.evict(uuid); + } else { + NetworkPlayerInfo networkplayerinfo = (NetworkPlayerInfo) this.playerInfoMap + .get(s38packetplayerlistitem$addplayerdata.getProfile().getId()); + if (packetIn.func_179768_b() == S38PacketPlayerListItem.Action.ADD_PLAYER) { + networkplayerinfo = new NetworkPlayerInfo(s38packetplayerlistitem$addplayerdata); + this.playerInfoMap.put(networkplayerinfo.getGameProfile().getId(), networkplayerinfo); + } + + if (networkplayerinfo != null) { + switch (packetIn.func_179768_b()) { + case ADD_PLAYER: + networkplayerinfo.setGameType(s38packetplayerlistitem$addplayerdata.getGameMode()); + networkplayerinfo.setResponseTime(s38packetplayerlistitem$addplayerdata.getPing()); + break; + case UPDATE_GAME_MODE: + networkplayerinfo.setGameType(s38packetplayerlistitem$addplayerdata.getGameMode()); + break; + case UPDATE_LATENCY: + networkplayerinfo.setResponseTime(s38packetplayerlistitem$addplayerdata.getPing()); + break; + case UPDATE_DISPLAY_NAME: + networkplayerinfo.setDisplayName(s38packetplayerlistitem$addplayerdata.getDisplayName()); + } + } + } + } + + } + + /** + * + Handles changes in player positioning and rotation such as when travelling + * to a new dimension, (re)spawning, mounting horses etc. Seems to immediately + * reply to the server with the clients post-processing perspective on the + * player positioning + */ + public void handlePlayerPosLook(S08PacketPlayerPosLook packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + double d0 = packetIn.getX(); + double d1 = packetIn.getY(); + double d2 = packetIn.getZ(); + float f = packetIn.getYaw(); + float f1 = packetIn.getPitch(); + if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.X)) { + d0 += entityplayersp.posX; + } else { + entityplayersp.motionX = 0.0D; + } + + if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Y)) { + d1 += entityplayersp.posY; + } else { + entityplayersp.motionY = 0.0D; + } + + if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Z)) { + d2 += entityplayersp.posZ; + } else { + entityplayersp.motionZ = 0.0D; + } + + if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.X_ROT)) { + f1 += entityplayersp.rotationPitch; + } + + if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Y_ROT)) { + f += entityplayersp.rotationYaw; + } + + entityplayersp.setPositionAndRotation(d0, d1, d2, f, f1); + this.netManager.sendPacket(new C03PacketPlayer.C06PacketPlayerPosLook(entityplayersp.posX, + entityplayersp.getEntityBoundingBox().minY, entityplayersp.posZ, entityplayersp.rotationYaw, + entityplayersp.rotationPitch, false)); + if (!this.doneLoadingTerrain) { + this.gameController.thePlayer.prevPosX = this.gameController.thePlayer.posX; + this.gameController.thePlayer.prevPosY = this.gameController.thePlayer.posY; + this.gameController.thePlayer.prevPosZ = this.gameController.thePlayer.posZ; + this.doneLoadingTerrain = true; + this.gameController.displayGuiScreen((GuiScreen) null); + } + + } + + public void handleRemoveEntityEffect(S1EPacketRemoveEntityEffect packetIn) { + Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + if (entity instanceof EntityLivingBase) { + ((EntityLivingBase) entity).removePotionEffectClient(packetIn.getEffectId()); + } + + } + + public void handleResourcePack(S48PacketResourcePackSend packetIn) { + final String s = packetIn.getURL(); + final String s1 = packetIn.getHash(); + if (!EaglerFolderResourcePack.isSupported() || s.startsWith("level://")) { + this.netManager + .sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.DECLINED)); + return; + } + if (this.gameController.getCurrentServerData() != null && this.gameController.getCurrentServerData() + .getResourceMode() == ServerData.ServerResourceMode.ENABLED) { + NetHandlerPlayClient.this.netManager + .sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.ACCEPTED)); + NetHandlerPlayClient.this.gameController.getResourcePackRepository().downloadResourcePack(s, s1, + success -> { + if (success) { + NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, + C19PacketResourcePackStatus.Action.SUCCESSFULLY_LOADED)); + } else { + NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, + C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD)); + } + }); + } else if (this.gameController.getCurrentServerData() != null && this.gameController.getCurrentServerData() + .getResourceMode() != ServerData.ServerResourceMode.PROMPT) { + this.netManager + .sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.DECLINED)); + } else { + NetHandlerPlayClient.this.gameController.displayGuiScreen(new GuiYesNo(new GuiYesNoCallback() { + public void confirmClicked(boolean flag, int var2) { + NetHandlerPlayClient.this.gameController = Minecraft.getMinecraft(); + if (flag) { + if (NetHandlerPlayClient.this.gameController.getCurrentServerData() != null) { + NetHandlerPlayClient.this.gameController.getCurrentServerData() + .setResourceMode(ServerData.ServerResourceMode.ENABLED); + } + + NetHandlerPlayClient.this.netManager.sendPacket( + new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.ACCEPTED)); + NetHandlerPlayClient.this.gameController.getResourcePackRepository().downloadResourcePack(s, s1, + success -> { + if (success) { + NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus( + s1, C19PacketResourcePackStatus.Action.SUCCESSFULLY_LOADED)); + } else { + NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus( + s1, C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD)); + } + }); + } else { + if (NetHandlerPlayClient.this.gameController.getCurrentServerData() != null) { + NetHandlerPlayClient.this.gameController.getCurrentServerData() + .setResourceMode(ServerData.ServerResourceMode.DISABLED); + } + + NetHandlerPlayClient.this.netManager.sendPacket( + new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.DECLINED)); + } + + ServerList.func_147414_b(NetHandlerPlayClient.this.gameController.getCurrentServerData()); + NetHandlerPlayClient.this.gameController.displayGuiScreen((GuiScreen) null); + } + }, I18n.format("multiplayer.texturePrompt.line1", new Object[0]), + I18n.format("multiplayer.texturePrompt.line2", new Object[0]), 0)); + } + } + + public void handleRespawn(S07PacketRespawn packetIn) { + if (packetIn.getDimensionID() != this.gameController.thePlayer.dimension) { + this.doneLoadingTerrain = false; + Scoreboard scoreboard = this.clientWorldController.getScoreboard(); + this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, + this.gameController.theWorld.getWorldInfo().isHardcoreModeEnabled(), packetIn.getWorldType()), + packetIn.getDimensionID(), packetIn.getDifficulty()); + this.clientWorldController.setWorldScoreboard(scoreboard); + this.gameController.loadWorld(this.clientWorldController); + this.gameController.thePlayer.dimension = packetIn.getDimensionID(); + this.gameController.displayGuiScreen(new GuiDownloadTerrain(this)); + } + + this.gameController.setDimensionAndSpawnPlayer(packetIn.getDimensionID()); + this.gameController.playerController.setGameType(packetIn.getGameType()); + } + + /** + * + May create a scoreboard objective, remove an objective from the scoreboard + * or update an objectives' displayname + */ + public void handleScoreboardObjective(S3BPacketScoreboardObjective packetIn) { + Scoreboard scoreboard = this.clientWorldController.getScoreboard(); + if (packetIn.func_149338_e() == 0) { + ScoreObjective scoreobjective = scoreboard.addScoreObjective(packetIn.func_149339_c(), + IScoreObjectiveCriteria.DUMMY); + scoreobjective.setDisplayName(packetIn.func_149337_d()); + scoreobjective.setRenderType(packetIn.func_179817_d()); + } else { + ScoreObjective scoreobjective1 = scoreboard.getObjective(packetIn.func_149339_c()); + if (packetIn.func_149338_e() == 1) { + scoreboard.removeObjective(scoreobjective1); + } else if (packetIn.func_149338_e() == 2) { + scoreobjective1.setDisplayName(packetIn.func_149337_d()); + scoreobjective1.setRenderType(packetIn.func_179817_d()); + } + } + + } + + public void handleServerDifficulty(S41PacketServerDifficulty packetIn) { + this.gameController.theWorld.getWorldInfo().setDifficulty(packetIn.getDifficulty()); + this.gameController.theWorld.getWorldInfo().setDifficultyLocked(packetIn.isDifficultyLocked()); + } + + public void handleSetCompressionLevel(S46PacketSetCompressionLevel packetIn) { + if (!this.netManager.isLocalChannel()) { + this.netManager.setCompressionTreshold(packetIn.func_179760_a()); + } + + } + + public void handleSetExperience(S1FPacketSetExperience packetIn) { + this.gameController.thePlayer.setXPStats(packetIn.func_149397_c(), packetIn.getTotalExperience(), + packetIn.getLevel()); + } + + /** + * + Handles pickin up an ItemStack or dropping one in your inventory or an open + * (non-creative) container + */ + public void handleSetSlot(S2FPacketSetSlot packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + if (packetIn.func_149175_c() == -1) { + entityplayersp.inventory.setItemStack(packetIn.func_149174_e()); + } else { + boolean flag = false; + if (this.gameController.currentScreen instanceof GuiContainerCreative) { + GuiContainerCreative guicontainercreative = (GuiContainerCreative) this.gameController.currentScreen; + flag = guicontainercreative.getSelectedTabIndex() != CreativeTabs.tabInventory.getTabIndex(); + } + + if (packetIn.func_149175_c() == 0 && packetIn.func_149173_d() >= 36 && packetIn.func_149173_d() < 45) { + ItemStack itemstack = entityplayersp.inventoryContainer.getSlot(packetIn.func_149173_d()).getStack(); + if (packetIn.func_149174_e() != null + && (itemstack == null || itemstack.stackSize < packetIn.func_149174_e().stackSize)) { + packetIn.func_149174_e().animationsToGo = 5; + } + + entityplayersp.inventoryContainer.putStackInSlot(packetIn.func_149173_d(), packetIn.func_149174_e()); + } else if (packetIn.func_149175_c() == entityplayersp.openContainer.windowId + && (packetIn.func_149175_c() != 0 || !flag)) { + entityplayersp.openContainer.putStackInSlot(packetIn.func_149173_d(), packetIn.func_149174_e()); + } + } + + } + + /** + * + Creates a sign in the specified location if it didn't exist and opens the + * GUI to edit its text + */ + public void handleSignEditorOpen(S36PacketSignEditorOpen packetIn) { + Object object = this.clientWorldController.getTileEntity(packetIn.getSignPosition()); + if (!(object instanceof TileEntitySign)) { + object = new TileEntitySign(); + ((TileEntity) object).setWorldObj(this.clientWorldController); + ((TileEntity) object).setPos(packetIn.getSignPosition()); + } + + this.gameController.thePlayer.openEditSign((TileEntitySign) object); + } + + public void handleSoundEffect(S29PacketSoundEffect packetIn) { + this.gameController.theWorld.playSound(packetIn.getX(), packetIn.getY(), packetIn.getZ(), + packetIn.getSoundName(), packetIn.getVolume(), packetIn.getPitch(), false); + } + + /** + * + Spawns an experience orb and sets its value (amount of XP) + */ + public void handleSpawnExperienceOrb(S11PacketSpawnExperienceOrb packetIn) { + EntityXPOrb entityxporb = new EntityXPOrb(this.clientWorldController, (double) packetIn.getX() / 32.0D, + (double) packetIn.getY() / 32.0D, (double) packetIn.getZ() / 32.0D, packetIn.getXPValue()); + entityxporb.serverPosX = packetIn.getX(); + entityxporb.serverPosY = packetIn.getY(); + entityxporb.serverPosZ = packetIn.getZ(); + entityxporb.rotationYaw = 0.0F; + entityxporb.rotationPitch = 0.0F; + entityxporb.setEntityId(packetIn.getEntityID()); + this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entityxporb); + } + + /** + * + Handles globally visible entities. Used in vanilla for lightning bolts + */ + public void handleSpawnGlobalEntity(S2CPacketSpawnGlobalEntity packetIn) { + double d0 = (double) packetIn.func_149051_d() / 32.0D; + double d1 = (double) packetIn.func_149050_e() / 32.0D; + double d2 = (double) packetIn.func_149049_f() / 32.0D; + EntityLightningBolt entitylightningbolt = null; + if (packetIn.func_149053_g() == 1) { + entitylightningbolt = new EntityLightningBolt(this.clientWorldController, d0, d1, d2); + } + + if (entitylightningbolt != null) { + entitylightningbolt.serverPosX = packetIn.func_149051_d(); + entitylightningbolt.serverPosY = packetIn.func_149050_e(); + entitylightningbolt.serverPosZ = packetIn.func_149049_f(); + entitylightningbolt.rotationYaw = 0.0F; + entitylightningbolt.rotationPitch = 0.0F; + entitylightningbolt.setEntityId(packetIn.func_149052_c()); + this.clientWorldController.addWeatherEffect(entitylightningbolt); + } + + } + + /** + * + Spawns the mob entity at the specified location, with the specified + * rotation, momentum and type. Updates the entities Datawatchers with the + * entity metadata specified in the packet + */ + public void handleSpawnMob(S0FPacketSpawnMob packetIn) { + double d0 = (double) packetIn.getX() / 32.0D; + double d1 = (double) packetIn.getY() / 32.0D; + double d2 = (double) packetIn.getZ() / 32.0D; + float f = (float) (packetIn.getYaw() * 360) / 256.0F; + float f1 = (float) (packetIn.getPitch() * 360) / 256.0F; + EntityLivingBase entitylivingbase = (EntityLivingBase) EntityList.createEntityByID(packetIn.getEntityType(), + this.gameController.theWorld); + entitylivingbase.serverPosX = packetIn.getX(); + entitylivingbase.serverPosY = packetIn.getY(); + entitylivingbase.serverPosZ = packetIn.getZ(); + entitylivingbase.renderYawOffset = entitylivingbase.rotationYawHead = (float) (packetIn.getHeadPitch() * 360) + / 256.0F; + Entity[] aentity = entitylivingbase.getParts(); + if (aentity != null) { + int i = packetIn.getEntityID() - entitylivingbase.getEntityId(); + + for (int j = 0; j < aentity.length; ++j) { + aentity[j].setEntityId(aentity[j].getEntityId() + i); + } + } + + entitylivingbase.setEntityId(packetIn.getEntityID()); + entitylivingbase.setPositionAndRotation(d0, d1, d2, f, f1); + entitylivingbase.motionX = (double) ((float) packetIn.getVelocityX() / 8000.0F); + entitylivingbase.motionY = (double) ((float) packetIn.getVelocityY() / 8000.0F); + entitylivingbase.motionZ = (double) ((float) packetIn.getVelocityZ() / 8000.0F); + this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); + List list = packetIn.func_149027_c(); + if (list != null) { + entitylivingbase.getDataWatcher().updateWatchedObjectsFromList(list); + } + + } + + /** + * + Spawns an instance of the objecttype indicated by the packet and sets its + * position and momentum */ public void handleSpawnObject(S0EPacketSpawnObject packetIn) { double d0 = (double) packetIn.getX() / 32.0D; @@ -475,48 +1492,8 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { } - /**+ - * Spawns an experience orb and sets its value (amount of XP) - */ - public void handleSpawnExperienceOrb(S11PacketSpawnExperienceOrb packetIn) { - EntityXPOrb entityxporb = new EntityXPOrb(this.clientWorldController, (double) packetIn.getX() / 32.0D, - (double) packetIn.getY() / 32.0D, (double) packetIn.getZ() / 32.0D, packetIn.getXPValue()); - entityxporb.serverPosX = packetIn.getX(); - entityxporb.serverPosY = packetIn.getY(); - entityxporb.serverPosZ = packetIn.getZ(); - entityxporb.rotationYaw = 0.0F; - entityxporb.rotationPitch = 0.0F; - entityxporb.setEntityId(packetIn.getEntityID()); - this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entityxporb); - } - - /**+ - * Handles globally visible entities. Used in vanilla for - * lightning bolts - */ - public void handleSpawnGlobalEntity(S2CPacketSpawnGlobalEntity packetIn) { - double d0 = (double) packetIn.func_149051_d() / 32.0D; - double d1 = (double) packetIn.func_149050_e() / 32.0D; - double d2 = (double) packetIn.func_149049_f() / 32.0D; - EntityLightningBolt entitylightningbolt = null; - if (packetIn.func_149053_g() == 1) { - entitylightningbolt = new EntityLightningBolt(this.clientWorldController, d0, d1, d2); - } - - if (entitylightningbolt != null) { - entitylightningbolt.serverPosX = packetIn.func_149051_d(); - entitylightningbolt.serverPosY = packetIn.func_149050_e(); - entitylightningbolt.serverPosZ = packetIn.func_149049_f(); - entitylightningbolt.rotationYaw = 0.0F; - entitylightningbolt.rotationPitch = 0.0F; - entitylightningbolt.setEntityId(packetIn.func_149052_c()); - this.clientWorldController.addWeatherEffect(entitylightningbolt); - } - - } - - /**+ - * Handles the spawning of a painting object + /** + * + Handles the spawning of a painting object */ public void handleSpawnPainting(S10PacketSpawnPainting packetIn) { EntityPainting entitypainting = new EntityPainting(this.clientWorldController, packetIn.getPosition(), @@ -524,34 +1501,9 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitypainting); } - /**+ - * Sets the velocity of the specified entity to the specified - * value - */ - public void handleEntityVelocity(S12PacketEntityVelocity packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); - if (entity != null) { - entity.setVelocity((double) packetIn.getMotionX() / 8000.0D, (double) packetIn.getMotionY() / 8000.0D, - (double) packetIn.getMotionZ() / 8000.0D); - } - } - - /**+ - * Invoked when the server registers new proximate objects in - * your watchlist or when objects in your watchlist have changed - * -> Registers any changes locally - */ - public void handleEntityMetadata(S1CPacketEntityMetadata packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity != null && packetIn.func_149376_c() != null) { - entity.getDataWatcher().updateWatchedObjectsFromList(packetIn.func_149376_c()); - } - - } - - /**+ - * Handles the creation of a nearby player entity, sets the - * position and held item + /** + * + Handles the creation of a nearby player entity, sets the position and held + * item */ public void handleSpawnPlayer(S0CPacketSpawnPlayer packetIn) { double d0 = (double) packetIn.getX() / 32.0D; @@ -584,741 +1536,13 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { } - /**+ - * Updates an entity's position and rotation as specified by the - * packet - */ - public void handleEntityTeleport(S18PacketEntityTeleport packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity != null) { - entity.serverPosX = packetIn.getX(); - entity.serverPosY = packetIn.getY(); - entity.serverPosZ = packetIn.getZ(); - double d0 = (double) entity.serverPosX / 32.0D; - double d1 = (double) entity.serverPosY / 32.0D; - double d2 = (double) entity.serverPosZ / 32.0D; - float f = (float) (packetIn.getYaw() * 360) / 256.0F; - float f1 = (float) (packetIn.getPitch() * 360) / 256.0F; - if (Math.abs(entity.posX - d0) < 0.03125D && Math.abs(entity.posY - d1) < 0.015625D - && Math.abs(entity.posZ - d2) < 0.03125D) { - entity.setPositionAndRotation2(entity.posX, entity.posY, entity.posZ, f, f1, 3, true); - } else { - entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, true); - } - - entity.onGround = packetIn.getOnGround(); - } - } - - /**+ - * Updates which hotbar slot of the player is currently selected - */ - public void handleHeldItemChange(S09PacketHeldItemChange packetIn) { - if (packetIn.getHeldItemHotbarIndex() >= 0 - && packetIn.getHeldItemHotbarIndex() < InventoryPlayer.getHotbarSize()) { - this.gameController.thePlayer.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); - } - - } - - /**+ - * Updates the specified entity's position by the specified - * relative moment and absolute rotation. Note that subclassing - * of the packet allows for the specification of a subset of - * this data (e.g. only rel. position, abs. rotation or both). - */ - public void handleEntityMovement(S14PacketEntity packetIn) { - Entity entity = packetIn.getEntity(this.clientWorldController); - if (entity != null) { - entity.serverPosX += packetIn.func_149062_c(); - entity.serverPosY += packetIn.func_149061_d(); - entity.serverPosZ += packetIn.func_149064_e(); - double d0 = (double) entity.serverPosX / 32.0D; - double d1 = (double) entity.serverPosY / 32.0D; - double d2 = (double) entity.serverPosZ / 32.0D; - float f = packetIn.func_149060_h() ? (float) (packetIn.func_149066_f() * 360) / 256.0F : entity.rotationYaw; - float f1 = packetIn.func_149060_h() ? (float) (packetIn.func_149063_g() * 360) / 256.0F - : entity.rotationPitch; - entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, false); - entity.onGround = packetIn.getOnGround(); - } - } - - /**+ - * Updates the direction in which the specified entity is - * looking, normally this head rotation is independent of the - * rotation of the entity itself - */ - public void handleEntityHeadLook(S19PacketEntityHeadLook packetIn) { - Entity entity = packetIn.getEntity(this.clientWorldController); - if (entity != null) { - float f = (float) (packetIn.getYaw() * 360) / 256.0F; - entity.setRotationYawHead(f); - } - } - - /**+ - * Locally eliminates the entities. Invoked by the server when - * the items are in fact destroyed, or the player is no longer - * registered as required to monitor them. The latter happens - * when distance between the player and item increases beyond a - * certain treshold (typically the viewing distance) - */ - public void handleDestroyEntities(S13PacketDestroyEntities packetIn) { - for (int i = 0; i < packetIn.getEntityIDs().length; ++i) { - this.clientWorldController.removeEntityFromWorld(packetIn.getEntityIDs()[i]); - } - - } - - /**+ - * Handles changes in player positioning and rotation such as - * when travelling to a new dimension, (re)spawning, mounting - * horses etc. Seems to immediately reply to the server with the - * clients post-processing perspective on the player positioning - */ - public void handlePlayerPosLook(S08PacketPlayerPosLook packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - double d0 = packetIn.getX(); - double d1 = packetIn.getY(); - double d2 = packetIn.getZ(); - float f = packetIn.getYaw(); - float f1 = packetIn.getPitch(); - if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.X)) { - d0 += entityplayersp.posX; - } else { - entityplayersp.motionX = 0.0D; - } - - if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Y)) { - d1 += entityplayersp.posY; - } else { - entityplayersp.motionY = 0.0D; - } - - if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Z)) { - d2 += entityplayersp.posZ; - } else { - entityplayersp.motionZ = 0.0D; - } - - if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.X_ROT)) { - f1 += entityplayersp.rotationPitch; - } - - if (packetIn.func_179834_f().contains(S08PacketPlayerPosLook.EnumFlags.Y_ROT)) { - f += entityplayersp.rotationYaw; - } - - entityplayersp.setPositionAndRotation(d0, d1, d2, f, f1); - this.netManager.sendPacket(new C03PacketPlayer.C06PacketPlayerPosLook(entityplayersp.posX, - entityplayersp.getEntityBoundingBox().minY, entityplayersp.posZ, entityplayersp.rotationYaw, - entityplayersp.rotationPitch, false)); - if (!this.doneLoadingTerrain) { - this.gameController.thePlayer.prevPosX = this.gameController.thePlayer.posX; - this.gameController.thePlayer.prevPosY = this.gameController.thePlayer.posY; - this.gameController.thePlayer.prevPosZ = this.gameController.thePlayer.posZ; - this.doneLoadingTerrain = true; - this.gameController.displayGuiScreen((GuiScreen) null); - } - - } - - /**+ - * Received from the servers PlayerManager if between 1 and 64 - * blocks in a chunk are changed. If only one block requires an - * update, the server sends S23PacketBlockChange and if 64 or - * more blocks are changed, the server sends S21PacketChunkData - */ - public void handleMultiBlockChange(S22PacketMultiBlockChange packetIn) { - BlockUpdateData[] dat = packetIn.getChangedBlocks(); - for (int i = 0; i < dat.length; ++i) { - BlockUpdateData s22packetmultiblockchange$blockupdatedata = dat[i]; - this.clientWorldController.invalidateRegionAndSetBlock(s22packetmultiblockchange$blockupdatedata.getPos(), - s22packetmultiblockchange$blockupdatedata.getBlockState()); - } - - } - - /**+ - * Updates the specified chunk with the supplied data, marks it - * for re-rendering and lighting recalculation - */ - public void handleChunkData(S21PacketChunkData packetIn) { - if (packetIn.func_149274_i()) { - if (packetIn.getExtractedSize() == 0) { - this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false); - return; - } - - this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); - } - - this.clientWorldController.invalidateBlockReceiveRegion(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, - (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15); - Chunk chunk = this.clientWorldController.getChunkFromChunkCoords(packetIn.getChunkX(), packetIn.getChunkZ()); - chunk.fillChunk(packetIn.func_149272_d(), packetIn.getExtractedSize(), packetIn.func_149274_i()); - this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, - packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 256, (packetIn.getChunkZ() << 4) + 15); - if (!packetIn.func_149274_i() || !(this.clientWorldController.provider instanceof WorldProviderSurface)) { - chunk.resetRelightChecks(); - } - - } - - /**+ - * Updates the block and metadata and generates a blockupdate - * (and notify the clients) - */ - public void handleBlockChange(S23PacketBlockChange packetIn) { - this.clientWorldController.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); - } - - /**+ - * Closes the network channel - */ - public void handleDisconnect(S40PacketDisconnect packetIn) { - this.netManager.closeChannel(packetIn.getReason()); - } - - /**+ - * Invoked when disconnecting, the parameter is a ChatComponent - * describing the reason for termination - */ - public void onDisconnect(IChatComponent ichatcomponent) { - VoiceClientController.handleServerDisconnect(); - Minecraft.getMinecraft().getRenderManager() - .setEnableFNAWSkins(this.gameController.gameSettings.enableFNAWSkins); - if (this.gameController.theWorld != null) { - this.gameController.loadWorld((WorldClient) null); - } - if (this.guiScreenServer != null) { - this.gameController.shutdownIntegratedServer( - new GuiDisconnected(this.guiScreenServer, "disconnect.lost", ichatcomponent)); - } else { - this.gameController.shutdownIntegratedServer( - new GuiDisconnected(new GuiMultiplayer(new GuiMainMenu()), "disconnect.lost", ichatcomponent)); - } - } - - public void addToSendQueue(Packet parPacket) { - this.netManager.sendPacket(parPacket); - } - - public void handleCollectItem(S0DPacketCollectItem packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getCollectedItemEntityID()); - Object object = (EntityLivingBase) this.clientWorldController.getEntityByID(packetIn.getEntityID()); - if (object == null) { - object = this.gameController.thePlayer; - } - - if (entity != null) { - if (entity instanceof EntityXPOrb) { - this.clientWorldController.playSoundAtEntity(entity, "random.orb", 0.2F, - ((this.avRandomizer.nextFloat() - this.avRandomizer.nextFloat()) * 0.7F + 1.0F) * 2.0F); - } else { - this.clientWorldController.playSoundAtEntity(entity, "random.pop", 0.2F, - ((this.avRandomizer.nextFloat() - this.avRandomizer.nextFloat()) * 0.7F + 1.0F) * 2.0F); - } - - this.gameController.effectRenderer - .addEffect(new EntityPickupFX(this.clientWorldController, entity, (Entity) object, 0.5F)); - this.clientWorldController.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); - } - - } - - /**+ - * Prints a chatmessage in the chat GUI - */ - public void handleChat(S02PacketChat packetIn) { - if (packetIn.getType() == 2) { - this.gameController.ingameGUI.setRecordPlaying(packetIn.getChatComponent(), false); - } else { - this.gameController.ingameGUI.getChatGUI().printChatMessage(packetIn.getChatComponent()); - } - - } - - /**+ - * Renders a specified animation: Waking up a player, a living - * entity swinging its currently held item, being hurt or - * receiving a critical hit by normal or magical means - */ - public void handleAnimation(S0BPacketAnimation packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); - if (entity != null) { - if (packetIn.getAnimationType() == 0) { - EntityLivingBase entitylivingbase = (EntityLivingBase) entity; - entitylivingbase.swingItem(); - } else if (packetIn.getAnimationType() == 1) { - entity.performHurtAnimation(); - } else if (packetIn.getAnimationType() == 2) { - EntityPlayer entityplayer = (EntityPlayer) entity; - entityplayer.wakeUpPlayer(false, false, false); - } else if (packetIn.getAnimationType() == 4) { - this.gameController.effectRenderer.emitParticleAtEntity(entity, EnumParticleTypes.CRIT); - } else if (packetIn.getAnimationType() == 5) { - this.gameController.effectRenderer.emitParticleAtEntity(entity, EnumParticleTypes.CRIT_MAGIC); - } - - } - } - - /**+ - * Retrieves the player identified by the packet, puts him to - * sleep if possible (and flags whether all players are asleep) - */ - public void handleUseBed(S0APacketUseBed packetIn) { - packetIn.getPlayer(this.clientWorldController).trySleep(packetIn.getBedPosition()); - } - - /**+ - * Spawns the mob entity at the specified location, with the - * specified rotation, momentum and type. Updates the entities - * Datawatchers with the entity metadata specified in the packet - */ - public void handleSpawnMob(S0FPacketSpawnMob packetIn) { - double d0 = (double) packetIn.getX() / 32.0D; - double d1 = (double) packetIn.getY() / 32.0D; - double d2 = (double) packetIn.getZ() / 32.0D; - float f = (float) (packetIn.getYaw() * 360) / 256.0F; - float f1 = (float) (packetIn.getPitch() * 360) / 256.0F; - EntityLivingBase entitylivingbase = (EntityLivingBase) EntityList.createEntityByID(packetIn.getEntityType(), - this.gameController.theWorld); - entitylivingbase.serverPosX = packetIn.getX(); - entitylivingbase.serverPosY = packetIn.getY(); - entitylivingbase.serverPosZ = packetIn.getZ(); - entitylivingbase.renderYawOffset = entitylivingbase.rotationYawHead = (float) (packetIn.getHeadPitch() * 360) - / 256.0F; - Entity[] aentity = entitylivingbase.getParts(); - if (aentity != null) { - int i = packetIn.getEntityID() - entitylivingbase.getEntityId(); - - for (int j = 0; j < aentity.length; ++j) { - aentity[j].setEntityId(aentity[j].getEntityId() + i); - } - } - - entitylivingbase.setEntityId(packetIn.getEntityID()); - entitylivingbase.setPositionAndRotation(d0, d1, d2, f, f1); - entitylivingbase.motionX = (double) ((float) packetIn.getVelocityX() / 8000.0F); - entitylivingbase.motionY = (double) ((float) packetIn.getVelocityY() / 8000.0F); - entitylivingbase.motionZ = (double) ((float) packetIn.getVelocityZ() / 8000.0F); - this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); - List list = packetIn.func_149027_c(); - if (list != null) { - entitylivingbase.getDataWatcher().updateWatchedObjectsFromList(list); - } - - } - - public void handleTimeUpdate(S03PacketTimeUpdate packetIn) { - this.gameController.theWorld.setTotalWorldTime(packetIn.getTotalWorldTime()); - this.gameController.theWorld.setWorldTime(packetIn.getWorldTime()); - } - public void handleSpawnPosition(S05PacketSpawnPosition packetIn) { this.gameController.thePlayer.setSpawnPoint(packetIn.getSpawnPos(), true); this.gameController.theWorld.getWorldInfo().setSpawn(packetIn.getSpawnPos()); } - public void handleEntityAttach(S1BPacketEntityAttach packetIn) { - Object object = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getVehicleEntityId()); - if (packetIn.getLeash() == 0) { - boolean flag = false; - if (packetIn.getEntityId() == this.gameController.thePlayer.getEntityId()) { - object = this.gameController.thePlayer; - if (entity instanceof EntityBoat) { - ((EntityBoat) entity).setIsBoatEmpty(false); - } - - flag = ((Entity) object).ridingEntity == null && entity != null; - } else if (entity instanceof EntityBoat) { - ((EntityBoat) entity).setIsBoatEmpty(true); - } - - if (object == null) { - return; - } - - ((Entity) object).mountEntity(entity); - if (flag) { - GameSettings gamesettings = this.gameController.gameSettings; - this.gameController.ingameGUI.setRecordPlaying( - I18n.format("mount.onboard", - new Object[] { - GameSettings.getKeyDisplayString(gamesettings.keyBindSneak.getKeyCode()) }), - false); - } - } else if (packetIn.getLeash() == 1 && object instanceof EntityLiving) { - if (entity != null) { - ((EntityLiving) object).setLeashedToEntity(entity, false); - } else { - ((EntityLiving) object).clearLeashed(false, false); - } - } - - } - - /**+ - * Invokes the entities' handleUpdateHealth method which is - * implemented in LivingBase (hurt/death), MinecartMobSpawner - * (spawn delay), FireworkRocket & MinecartTNT (explosion), - * IronGolem (throwing,...), Witch (spawn particles), Zombie - * (villager transformation), Animal (breeding mode particles), - * Horse (breeding/smoke particles), Sheep (...), Tameable - * (...), Villager (particles for breeding mode, angry and - * happy), Wolf (...) - */ - public void handleEntityStatus(S19PacketEntityStatus packetIn) { - Entity entity = packetIn.getEntity(this.clientWorldController); - if (entity != null) { - if (packetIn.getOpCode() == 21) { - this.gameController.getSoundHandler().playSound(new GuardianSound((EntityGuardian) entity)); - } else { - entity.handleStatusUpdate(packetIn.getOpCode()); - } - } - - } - - public void handleUpdateHealth(S06PacketUpdateHealth packetIn) { - this.gameController.thePlayer.setPlayerSPHealth(packetIn.getHealth()); - this.gameController.thePlayer.getFoodStats().setFoodLevel(packetIn.getFoodLevel()); - this.gameController.thePlayer.getFoodStats().setFoodSaturationLevel(packetIn.getSaturationLevel()); - } - - public void handleSetExperience(S1FPacketSetExperience packetIn) { - this.gameController.thePlayer.setXPStats(packetIn.func_149397_c(), packetIn.getTotalExperience(), - packetIn.getLevel()); - } - - public void handleRespawn(S07PacketRespawn packetIn) { - if (packetIn.getDimensionID() != this.gameController.thePlayer.dimension) { - this.doneLoadingTerrain = false; - Scoreboard scoreboard = this.clientWorldController.getScoreboard(); - this.clientWorldController = new WorldClient(this, new WorldSettings(0L, packetIn.getGameType(), false, - this.gameController.theWorld.getWorldInfo().isHardcoreModeEnabled(), packetIn.getWorldType()), - packetIn.getDimensionID(), packetIn.getDifficulty()); - this.clientWorldController.setWorldScoreboard(scoreboard); - this.gameController.loadWorld(this.clientWorldController); - this.gameController.thePlayer.dimension = packetIn.getDimensionID(); - this.gameController.displayGuiScreen(new GuiDownloadTerrain(this)); - } - - this.gameController.setDimensionAndSpawnPlayer(packetIn.getDimensionID()); - this.gameController.playerController.setGameType(packetIn.getGameType()); - } - - /**+ - * Initiates a new explosion (sound, particles, drop spawn) for - * the affected blocks indicated by the packet. - */ - public void handleExplosion(S27PacketExplosion packetIn) { - Explosion explosion = new Explosion(this.gameController.theWorld, (Entity) null, packetIn.getX(), - packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); - explosion.doExplosionB(true); - this.gameController.thePlayer.motionX += (double) packetIn.func_149149_c(); - this.gameController.thePlayer.motionY += (double) packetIn.func_149144_d(); - this.gameController.thePlayer.motionZ += (double) packetIn.func_149147_e(); - } - - /**+ - * Displays a GUI by ID. In order starting from id 0: Chest, - * Workbench, Furnace, Dispenser, Enchanting table, Brewing - * stand, Villager merchant, Beacon, Anvil, Hopper, Dropper, - * Horse - */ - public void handleOpenWindow(S2DPacketOpenWindow packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - if ("minecraft:container".equals(packetIn.getGuiId())) { - entityplayersp.displayGUIChest(new InventoryBasic(packetIn.getWindowTitle(), packetIn.getSlotCount())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); - } else if ("minecraft:villager".equals(packetIn.getGuiId())) { - entityplayersp.displayVillagerTradeGui(new NpcMerchant(entityplayersp, packetIn.getWindowTitle())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); - } else if ("EntityHorse".equals(packetIn.getGuiId())) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityHorse) { - entityplayersp.displayGUIHorse((EntityHorse) entity, - new AnimalChest(packetIn.getWindowTitle(), packetIn.getSlotCount())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); - } - } else if (!packetIn.hasSlots()) { - entityplayersp.displayGui(new LocalBlockIntercommunication(packetIn.getGuiId(), packetIn.getWindowTitle())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); - } else { - ContainerLocalMenu containerlocalmenu = new ContainerLocalMenu(packetIn.getGuiId(), - packetIn.getWindowTitle(), packetIn.getSlotCount()); - entityplayersp.displayGUIChest(containerlocalmenu); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); - } - - } - - /**+ - * Handles pickin up an ItemStack or dropping one in your - * inventory or an open (non-creative) container - */ - public void handleSetSlot(S2FPacketSetSlot packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - if (packetIn.func_149175_c() == -1) { - entityplayersp.inventory.setItemStack(packetIn.func_149174_e()); - } else { - boolean flag = false; - if (this.gameController.currentScreen instanceof GuiContainerCreative) { - GuiContainerCreative guicontainercreative = (GuiContainerCreative) this.gameController.currentScreen; - flag = guicontainercreative.getSelectedTabIndex() != CreativeTabs.tabInventory.getTabIndex(); - } - - if (packetIn.func_149175_c() == 0 && packetIn.func_149173_d() >= 36 && packetIn.func_149173_d() < 45) { - ItemStack itemstack = entityplayersp.inventoryContainer.getSlot(packetIn.func_149173_d()).getStack(); - if (packetIn.func_149174_e() != null - && (itemstack == null || itemstack.stackSize < packetIn.func_149174_e().stackSize)) { - packetIn.func_149174_e().animationsToGo = 5; - } - - entityplayersp.inventoryContainer.putStackInSlot(packetIn.func_149173_d(), packetIn.func_149174_e()); - } else if (packetIn.func_149175_c() == entityplayersp.openContainer.windowId - && (packetIn.func_149175_c() != 0 || !flag)) { - entityplayersp.openContainer.putStackInSlot(packetIn.func_149173_d(), packetIn.func_149174_e()); - } - } - - } - - /**+ - * Verifies that the server and client are synchronized with - * respect to the inventory/container opened by the player and - * confirms if it is the case. - */ - public void handleConfirmTransaction(S32PacketConfirmTransaction packetIn) { - Container container = null; - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - if (packetIn.getWindowId() == 0) { - container = entityplayersp.inventoryContainer; - } else if (packetIn.getWindowId() == entityplayersp.openContainer.windowId) { - container = entityplayersp.openContainer; - } - - if (container != null && !packetIn.func_148888_e()) { - this.addToSendQueue( - new C0FPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); - } - - } - - /**+ - * Handles the placement of a specified ItemStack in a specified - * container/inventory slot - */ - public void handleWindowItems(S30PacketWindowItems packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - if (packetIn.func_148911_c() == 0) { - entityplayersp.inventoryContainer.putStacksInSlots(packetIn.getItemStacks()); - } else if (packetIn.func_148911_c() == entityplayersp.openContainer.windowId) { - entityplayersp.openContainer.putStacksInSlots(packetIn.getItemStacks()); - } - - } - - /**+ - * Creates a sign in the specified location if it didn't exist - * and opens the GUI to edit its text - */ - public void handleSignEditorOpen(S36PacketSignEditorOpen packetIn) { - Object object = this.clientWorldController.getTileEntity(packetIn.getSignPosition()); - if (!(object instanceof TileEntitySign)) { - object = new TileEntitySign(); - ((TileEntity) object).setWorldObj(this.clientWorldController); - ((TileEntity) object).setPos(packetIn.getSignPosition()); - } - - this.gameController.thePlayer.openEditSign((TileEntitySign) object); - } - - /**+ - * Updates a specified sign with the specified text lines - */ - public void handleUpdateSign(S33PacketUpdateSign packetIn) { - boolean flag = false; - if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) { - TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); - if (tileentity instanceof TileEntitySign) { - TileEntitySign tileentitysign = (TileEntitySign) tileentity; - if (tileentitysign.getIsEditable()) { - System.arraycopy(packetIn.getLines(), 0, tileentitysign.signText, 0, 4); - tileentitysign.markDirty(); - tileentitysign.clearProfanityFilterCache(); - } - - flag = true; - } - } - - if (!flag && this.gameController.thePlayer != null) { - this.gameController.thePlayer.addChatMessage(new ChatComponentText("Unable to locate sign at " - + packetIn.getPos().getX() + ", " + packetIn.getPos().getY() + ", " + packetIn.getPos().getZ())); - } - - } - - /**+ - * Updates the NBTTagCompound metadata of instances of the - * following entitytypes: Mob spawners, command blocks, beacons, - * skulls, flowerpot - */ - public void handleUpdateTileEntity(S35PacketUpdateTileEntity packetIn) { - if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) { - TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); - int i = packetIn.getTileEntityType(); - if (i == 1 && tileentity instanceof TileEntityMobSpawner - || i == 2 && tileentity instanceof TileEntityCommandBlock - || i == 3 && tileentity instanceof TileEntityBeacon - || i == 4 && tileentity instanceof TileEntitySkull - || i == 5 && tileentity instanceof TileEntityFlowerPot - || i == 6 && tileentity instanceof TileEntityBanner) { - tileentity.readFromNBT(packetIn.getNbtCompound()); - } - } - - } - - /**+ - * Sets the progressbar of the opened window to the specified - * value - */ - public void handleWindowProperty(S31PacketWindowProperty packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - if (entityplayersp.openContainer != null && entityplayersp.openContainer.windowId == packetIn.getWindowId()) { - entityplayersp.openContainer.updateProgressBar(packetIn.getVarIndex(), packetIn.getVarValue()); - } - - } - - public void handleEntityEquipment(S04PacketEntityEquipment packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); - if (entity != null) { - entity.setCurrentItemOrArmor(packetIn.getEquipmentSlot(), packetIn.getItemStack()); - } - - } - - /**+ - * Resets the ItemStack held in hand and closes the window that - * is opened - */ - public void handleCloseWindow(S2EPacketCloseWindow packetIn) { - this.gameController.thePlayer.closeScreenAndDropStack(); - } - - /**+ - * Triggers Block.onBlockEventReceived, which is implemented in - * BlockPistonBase for extension/retraction, BlockNote for - * setting the instrument (including audiovisual feedback) and - * in BlockContainer to set the number of players accessing a - * (Ender)Chest - */ - public void handleBlockAction(S24PacketBlockAction packetIn) { - this.gameController.theWorld.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), - packetIn.getData1(), packetIn.getData2()); - } - - /**+ - * Updates all registered IWorldAccess instances with - * destroyBlockInWorldPartially - */ - public void handleBlockBreakAnim(S25PacketBlockBreakAnim packetIn) { - this.gameController.theWorld.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), - packetIn.getProgress()); - } - - public void handleMapChunkBulk(S26PacketMapChunkBulk packetIn) { - for (int i = 0; i < packetIn.getChunkCount(); ++i) { - int j = packetIn.getChunkX(i); - int k = packetIn.getChunkZ(i); - this.clientWorldController.doPreChunk(j, k, true); - this.clientWorldController.invalidateBlockReceiveRegion(j << 4, 0, k << 4, (j << 4) + 15, 256, - (k << 4) + 15); - Chunk chunk = this.clientWorldController.getChunkFromChunkCoords(j, k); - chunk.fillChunk(packetIn.getChunkBytes(i), packetIn.getChunkSize(i), true); - this.clientWorldController.markBlockRangeForRenderUpdate(j << 4, 0, k << 4, (j << 4) + 15, 256, - (k << 4) + 15); - if (!(this.clientWorldController.provider instanceof WorldProviderSurface)) { - chunk.resetRelightChecks(); - } - } - - } - - public void handleChangeGameState(S2BPacketChangeGameState packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - int i = packetIn.getGameState(); - float f = packetIn.func_149137_d(); - int j = MathHelper.floor_float(f + 0.5F); - if (i >= 0 && i < S2BPacketChangeGameState.MESSAGE_NAMES.length - && S2BPacketChangeGameState.MESSAGE_NAMES[i] != null) { - entityplayersp.addChatComponentMessage( - new ChatComponentTranslation(S2BPacketChangeGameState.MESSAGE_NAMES[i], new Object[0])); - } - - if (i == 1) { - this.clientWorldController.getWorldInfo().setRaining(true); - this.clientWorldController.setRainStrength(0.0F); - } else if (i == 2) { - this.clientWorldController.getWorldInfo().setRaining(false); - this.clientWorldController.setRainStrength(1.0F); - } else if (i == 3) { - this.gameController.playerController.setGameType(WorldSettings.GameType.getByID(j)); - } else if (i == 4) { - this.gameController.displayGuiScreen(new GuiWinGame()); - } else if (i == 5) { - - // minecraft demo screen - - } else if (i == 6) { - this.clientWorldController.playSound(entityplayersp.posX, - entityplayersp.posY + (double) entityplayersp.getEyeHeight(), entityplayersp.posZ, - "random.successful_hit", 0.18F, 0.45F, false); - } else if (i == 7) { - this.clientWorldController.setRainStrength(f); - } else if (i == 8) { - this.clientWorldController.setThunderStrength(f); - } else if (i == 10) { - this.clientWorldController.spawnParticle(EnumParticleTypes.MOB_APPEARANCE, entityplayersp.posX, - entityplayersp.posY, entityplayersp.posZ, 0.0D, 0.0D, 0.0D, new int[0]); - this.clientWorldController.playSound(entityplayersp.posX, entityplayersp.posY, entityplayersp.posZ, - "mob.guardian.curse", 1.0F, 1.0F, false); - } - - } - - /**+ - * Updates the worlds MapStorage with the specified MapData for - * the specified map-identifier and invokes a MapItemRenderer - * for it - */ - public void handleMaps(S34PacketMaps packetIn) { - MapData mapdata = ItemMap.loadMapData(packetIn.getMapId(), this.gameController.theWorld); - packetIn.setMapdataTo(mapdata); - this.gameController.entityRenderer.getMapItemRenderer().updateMapTexture(mapdata); - } - - public void handleEffect(S28PacketEffect packetIn) { - if (packetIn.isSoundServerwide()) { - this.gameController.theWorld.playBroadcastSound(packetIn.getSoundType(), packetIn.getSoundPos(), - packetIn.getSoundData()); - } else { - this.gameController.theWorld.playAuxSFX(packetIn.getSoundType(), packetIn.getSoundPos(), - packetIn.getSoundData()); - } - - } - - /**+ - * Updates the players statistics or achievements + /** + * + Updates the players statistics or achievements */ public void handleStatistics(S37PacketStatistics packetIn) { boolean flag = false; @@ -1354,140 +1578,8 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { } - public void handleEntityEffect(S1DPacketEntityEffect packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityLivingBase) { - PotionEffect potioneffect = new PotionEffect(packetIn.getEffectId(), packetIn.getDuration(), - packetIn.getAmplifier(), false, packetIn.func_179707_f()); - potioneffect.setPotionDurationMax(packetIn.func_149429_c()); - ((EntityLivingBase) entity).addPotionEffect(potioneffect); - } - } - - public void handleCombatEvent(S42PacketCombatEvent packetIn) { - - // used by twitch stream - - } - - public void handleServerDifficulty(S41PacketServerDifficulty packetIn) { - this.gameController.theWorld.getWorldInfo().setDifficulty(packetIn.getDifficulty()); - this.gameController.theWorld.getWorldInfo().setDifficultyLocked(packetIn.isDifficultyLocked()); - } - - public void handleCamera(S43PacketCamera packetIn) { - - Entity entity = packetIn.getEntity(this.clientWorldController); - if (entity != null) { - this.gameController.setRenderViewEntity(entity); - } - - } - - public void handleWorldBorder(S44PacketWorldBorder packetIn) { - packetIn.func_179788_a(this.clientWorldController.getWorldBorder()); - } - - public void handleTitle(S45PacketTitle packetIn) { - S45PacketTitle.Type s45packettitle$type = packetIn.getType(); - String s = null; - String s1 = null; - String s2 = packetIn.getMessage() != null ? packetIn.getMessage().getFormattedText() : ""; - switch (s45packettitle$type) { - case TITLE: - s = s2; - break; - case SUBTITLE: - s1 = s2; - break; - case RESET: - this.gameController.ingameGUI.displayTitle("", "", -1, -1, -1); - this.gameController.ingameGUI.func_175177_a(); - return; - } - - this.gameController.ingameGUI.displayTitle(s, s1, packetIn.getFadeInTime(), packetIn.getDisplayTime(), - packetIn.getFadeOutTime()); - } - - public void handleSetCompressionLevel(S46PacketSetCompressionLevel packetIn) { - if (!this.netManager.isLocalChannel()) { - this.netManager.setCompressionTreshold(packetIn.func_179760_a()); - } - - } - - public void handlePlayerListHeaderFooter(S47PacketPlayerListHeaderFooter packetIn) { - this.gameController.ingameGUI.getTabList() - .setHeader(packetIn.getHeader().getFormattedText().length() == 0 ? null : packetIn.getHeader()); - this.gameController.ingameGUI.getTabList() - .setFooter(packetIn.getFooter().getFormattedText().length() == 0 ? null : packetIn.getFooter()); - } - - public void handleRemoveEntityEffect(S1EPacketRemoveEntityEffect packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityLivingBase) { - ((EntityLivingBase) entity).removePotionEffectClient(packetIn.getEffectId()); - } - - } - - public void handlePlayerListItem(S38PacketPlayerListItem packetIn) { - List lst = packetIn.func_179767_a(); - for (int i = 0, l = lst.size(); i < l; ++i) { - S38PacketPlayerListItem.AddPlayerData s38packetplayerlistitem$addplayerdata = lst.get(i); - if (packetIn.func_179768_b() == S38PacketPlayerListItem.Action.REMOVE_PLAYER) { - EaglercraftUUID uuid = s38packetplayerlistitem$addplayerdata.getProfile().getId(); - this.playerInfoMap.remove(uuid); - this.skinCache.evictSkin(uuid); - this.capeCache.evictCape(uuid); - ClientUUIDLoadingCache.evict(uuid); - } else { - NetworkPlayerInfo networkplayerinfo = (NetworkPlayerInfo) this.playerInfoMap - .get(s38packetplayerlistitem$addplayerdata.getProfile().getId()); - if (packetIn.func_179768_b() == S38PacketPlayerListItem.Action.ADD_PLAYER) { - networkplayerinfo = new NetworkPlayerInfo(s38packetplayerlistitem$addplayerdata); - this.playerInfoMap.put(networkplayerinfo.getGameProfile().getId(), networkplayerinfo); - } - - if (networkplayerinfo != null) { - switch (packetIn.func_179768_b()) { - case ADD_PLAYER: - networkplayerinfo.setGameType(s38packetplayerlistitem$addplayerdata.getGameMode()); - networkplayerinfo.setResponseTime(s38packetplayerlistitem$addplayerdata.getPing()); - break; - case UPDATE_GAME_MODE: - networkplayerinfo.setGameType(s38packetplayerlistitem$addplayerdata.getGameMode()); - break; - case UPDATE_LATENCY: - networkplayerinfo.setResponseTime(s38packetplayerlistitem$addplayerdata.getPing()); - break; - case UPDATE_DISPLAY_NAME: - networkplayerinfo.setDisplayName(s38packetplayerlistitem$addplayerdata.getDisplayName()); - } - } - } - } - - } - - public void handleKeepAlive(S00PacketKeepAlive packetIn) { - this.addToSendQueue(new C00PacketKeepAlive(packetIn.func_149134_c())); - } - - public void handlePlayerAbilities(S39PacketPlayerAbilities packetIn) { - EntityPlayerSP entityplayersp = this.gameController.thePlayer; - entityplayersp.capabilities.isFlying = packetIn.isFlying(); - entityplayersp.capabilities.isCreativeMode = packetIn.isCreativeMode(); - entityplayersp.capabilities.disableDamage = packetIn.isInvulnerable(); - entityplayersp.capabilities.allowFlying = packetIn.isAllowFlying(); - entityplayersp.capabilities.setFlySpeed(packetIn.getFlySpeed()); - entityplayersp.capabilities.setPlayerWalkSpeed(packetIn.getWalkSpeed()); - } - - /**+ - * Displays the available command-completion options the server - * knows of + /** + * + Displays the available command-completion options the server knows of */ public void handleTabComplete(S3APacketTabComplete packetIn) { String[] astring = packetIn.func_149630_c(); @@ -1498,191 +1590,10 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { } - public void handleSoundEffect(S29PacketSoundEffect packetIn) { - this.gameController.theWorld.playSound(packetIn.getX(), packetIn.getY(), packetIn.getZ(), - packetIn.getSoundName(), packetIn.getVolume(), packetIn.getPitch(), false); - } - - public void handleResourcePack(S48PacketResourcePackSend packetIn) { - final String s = packetIn.getURL(); - final String s1 = packetIn.getHash(); - if (!EaglerFolderResourcePack.isSupported() || s.startsWith("level://")) { - this.netManager - .sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.DECLINED)); - return; - } - if (this.gameController.getCurrentServerData() != null && this.gameController.getCurrentServerData() - .getResourceMode() == ServerData.ServerResourceMode.ENABLED) { - NetHandlerPlayClient.this.netManager - .sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.ACCEPTED)); - NetHandlerPlayClient.this.gameController.getResourcePackRepository().downloadResourcePack(s, s1, - success -> { - if (success) { - NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, - C19PacketResourcePackStatus.Action.SUCCESSFULLY_LOADED)); - } else { - NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus(s1, - C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD)); - } - }); - } else if (this.gameController.getCurrentServerData() != null && this.gameController.getCurrentServerData() - .getResourceMode() != ServerData.ServerResourceMode.PROMPT) { - this.netManager - .sendPacket(new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.DECLINED)); - } else { - NetHandlerPlayClient.this.gameController.displayGuiScreen(new GuiYesNo(new GuiYesNoCallback() { - public void confirmClicked(boolean flag, int var2) { - NetHandlerPlayClient.this.gameController = Minecraft.getMinecraft(); - if (flag) { - if (NetHandlerPlayClient.this.gameController.getCurrentServerData() != null) { - NetHandlerPlayClient.this.gameController.getCurrentServerData() - .setResourceMode(ServerData.ServerResourceMode.ENABLED); - } - - NetHandlerPlayClient.this.netManager.sendPacket( - new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.ACCEPTED)); - NetHandlerPlayClient.this.gameController.getResourcePackRepository().downloadResourcePack(s, s1, - success -> { - if (success) { - NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus( - s1, C19PacketResourcePackStatus.Action.SUCCESSFULLY_LOADED)); - } else { - NetHandlerPlayClient.this.netManager.sendPacket(new C19PacketResourcePackStatus( - s1, C19PacketResourcePackStatus.Action.FAILED_DOWNLOAD)); - } - }); - } else { - if (NetHandlerPlayClient.this.gameController.getCurrentServerData() != null) { - NetHandlerPlayClient.this.gameController.getCurrentServerData() - .setResourceMode(ServerData.ServerResourceMode.DISABLED); - } - - NetHandlerPlayClient.this.netManager.sendPacket( - new C19PacketResourcePackStatus(s1, C19PacketResourcePackStatus.Action.DECLINED)); - } - - ServerList.func_147414_b(NetHandlerPlayClient.this.gameController.getCurrentServerData()); - NetHandlerPlayClient.this.gameController.displayGuiScreen((GuiScreen) null); - } - }, I18n.format("multiplayer.texturePrompt.line1", new Object[0]), - I18n.format("multiplayer.texturePrompt.line2", new Object[0]), 0)); - } - } - - public void handleEntityNBT(S49PacketUpdateEntityNBT packetIn) { - Entity entity = packetIn.getEntity(this.clientWorldController); - if (entity != null) { - entity.clientUpdateEntityNBT(packetIn.getTagCompound()); - } - - } - - /**+ - * Handles packets that have room for a channel specification. - * Vanilla implemented channels are "MC|TrList" to acquire a - * MerchantRecipeList trades for a villager merchant, "MC|Brand" - * which sets the server brand? on the player instance and - * finally "MC|RPack" which the server uses to communicate the - * identifier of the default server resourcepack for the client - * to load. - */ - public void handleCustomPayload(S3FPacketCustomPayload packetIn) { - if ("MC|TrList".equals(packetIn.getChannelName())) { - PacketBuffer packetbuffer = packetIn.getBufferData(); - try { - int i = packetbuffer.readInt(); - GuiScreen guiscreen = this.gameController.currentScreen; - if (guiscreen != null && guiscreen instanceof GuiMerchant - && i == this.gameController.thePlayer.openContainer.windowId) { - IMerchant imerchant = ((GuiMerchant) guiscreen).getMerchant(); - MerchantRecipeList merchantrecipelist = MerchantRecipeList.readFromBuf(packetbuffer); - imerchant.setRecipes(merchantrecipelist); - } - } catch (IOException ioexception) { - logger.error("Couldn\'t load trade info", ioexception); - } - } else if ("MC|Brand".equals(packetIn.getChannelName())) { - this.gameController.thePlayer.setClientBrand(packetIn.getBufferData().readStringFromBuffer(32767)); - } else if ("MC|BOpen".equals(packetIn.getChannelName())) { - ItemStack itemstack = this.gameController.thePlayer.getCurrentEquippedItem(); - if (itemstack != null && itemstack.getItem() == Items.written_book) { - this.gameController - .displayGuiScreen(new GuiScreenBook(this.gameController.thePlayer, itemstack, false)); - } - } else { - try { - eaglerMessageController.handlePacket(packetIn.getChannelName(), packetIn.getBufferData()); - } catch (IOException e) { - logger.error("Couldn't read \"{}\" packet as an eaglercraft plugin message!", - packetIn.getChannelName()); - logger.error(e); - } - } - } - - /**+ - * May create a scoreboard objective, remove an objective from - * the scoreboard or update an objectives' displayname - */ - public void handleScoreboardObjective(S3BPacketScoreboardObjective packetIn) { - Scoreboard scoreboard = this.clientWorldController.getScoreboard(); - if (packetIn.func_149338_e() == 0) { - ScoreObjective scoreobjective = scoreboard.addScoreObjective(packetIn.func_149339_c(), - IScoreObjectiveCriteria.DUMMY); - scoreobjective.setDisplayName(packetIn.func_149337_d()); - scoreobjective.setRenderType(packetIn.func_179817_d()); - } else { - ScoreObjective scoreobjective1 = scoreboard.getObjective(packetIn.func_149339_c()); - if (packetIn.func_149338_e() == 1) { - scoreboard.removeObjective(scoreobjective1); - } else if (packetIn.func_149338_e() == 2) { - scoreobjective1.setDisplayName(packetIn.func_149337_d()); - scoreobjective1.setRenderType(packetIn.func_179817_d()); - } - } - - } - - /**+ - * Either updates the score with a specified value or removes - * the score for an objective - */ - public void handleUpdateScore(S3CPacketUpdateScore packetIn) { - Scoreboard scoreboard = this.clientWorldController.getScoreboard(); - ScoreObjective scoreobjective = scoreboard.getObjective(packetIn.getObjectiveName()); - if (packetIn.getScoreAction() == S3CPacketUpdateScore.Action.CHANGE) { - Score score = scoreboard.getValueFromObjective(packetIn.getPlayerName(), scoreobjective); - score.setScorePoints(packetIn.getScoreValue()); - } else if (packetIn.getScoreAction() == S3CPacketUpdateScore.Action.REMOVE) { - if (StringUtils.isNullOrEmpty(packetIn.getObjectiveName())) { - scoreboard.removeObjectiveFromEntity(packetIn.getPlayerName(), (ScoreObjective) null); - } else if (scoreobjective != null) { - scoreboard.removeObjectiveFromEntity(packetIn.getPlayerName(), scoreobjective); - } - } - - } - - /**+ - * Removes or sets the ScoreObjective to be displayed at a - * particular scoreboard position (list, sidebar, below name) - */ - public void handleDisplayScoreboard(S3DPacketDisplayScoreboard packetIn) { - Scoreboard scoreboard = this.clientWorldController.getScoreboard(); - if (packetIn.func_149370_d().length() == 0) { - scoreboard.setObjectiveInDisplaySlot(packetIn.func_149371_c(), (ScoreObjective) null); - } else { - ScoreObjective scoreobjective = scoreboard.getObjective(packetIn.func_149370_d()); - scoreboard.setObjectiveInDisplaySlot(packetIn.func_149371_c(), scoreobjective); - } - - } - - /**+ - * Updates a team managed by the scoreboard: Create/Remove the - * team registration, Register/Remove the - * player-team-memberships, Set team displayname/prefix/suffix - * and/or whether friendly fire is enabled + /** + * + Updates a team managed by the scoreboard: Create/Remove the team + * registration, Register/Remove the player-team-memberships, Set team + * displayname/prefix/suffix and/or whether friendly fire is enabled */ public void handleTeams(S3EPacketTeams packetIn) { Scoreboard scoreboard = this.clientWorldController.getScoreboard(); @@ -1723,125 +1634,192 @@ public class NetHandlerPlayClient implements INetHandlerPlayClient { } - /**+ - * Spawns a specified number of particles at the specified - * location with a randomized displacement according to - * specified bounds + public void handleTimeUpdate(S03PacketTimeUpdate packetIn) { + this.gameController.theWorld.setTotalWorldTime(packetIn.getTotalWorldTime()); + this.gameController.theWorld.setWorldTime(packetIn.getWorldTime()); + } + + public void handleTitle(S45PacketTitle packetIn) { + S45PacketTitle.Type s45packettitle$type = packetIn.getType(); + String s = null; + String s1 = null; + String s2 = packetIn.getMessage() != null ? packetIn.getMessage().getFormattedText() : ""; + switch (s45packettitle$type) { + case TITLE: + s = s2; + break; + case SUBTITLE: + s1 = s2; + break; + case RESET: + this.gameController.ingameGUI.displayTitle("", "", -1, -1, -1); + this.gameController.ingameGUI.func_175177_a(); + return; + } + + this.gameController.ingameGUI.displayTitle(s, s1, packetIn.getFadeInTime(), packetIn.getDisplayTime(), + packetIn.getFadeOutTime()); + } + + public void handleUpdateHealth(S06PacketUpdateHealth packetIn) { + this.gameController.thePlayer.setPlayerSPHealth(packetIn.getHealth()); + this.gameController.thePlayer.getFoodStats().setFoodLevel(packetIn.getFoodLevel()); + this.gameController.thePlayer.getFoodStats().setFoodSaturationLevel(packetIn.getSaturationLevel()); + } + + /** + * + Either updates the score with a specified value or removes the score for an + * objective */ - public void handleParticles(S2APacketParticles packetIn) { - if (packetIn.getParticleCount() == 0) { - double d0 = (double) (packetIn.getParticleSpeed() * packetIn.getXOffset()); - double d2 = (double) (packetIn.getParticleSpeed() * packetIn.getYOffset()); - double d4 = (double) (packetIn.getParticleSpeed() * packetIn.getZOffset()); - - try { - this.clientWorldController.spawnParticle(packetIn.getParticleType(), packetIn.isLongDistance(), - packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, - packetIn.getParticleArgs()); - } catch (Throwable var17) { - logger.warn("Could not spawn particle effect " + packetIn.getParticleType()); - } - } else { - for (int i = 0; i < packetIn.getParticleCount(); ++i) { - double d1 = this.avRandomizer.nextGaussian() * (double) packetIn.getXOffset(); - double d3 = this.avRandomizer.nextGaussian() * (double) packetIn.getYOffset(); - double d5 = this.avRandomizer.nextGaussian() * (double) packetIn.getZOffset(); - double d6 = this.avRandomizer.nextGaussian() * (double) packetIn.getParticleSpeed(); - double d7 = this.avRandomizer.nextGaussian() * (double) packetIn.getParticleSpeed(); - double d8 = this.avRandomizer.nextGaussian() * (double) packetIn.getParticleSpeed(); - - try { - this.clientWorldController.spawnParticle(packetIn.getParticleType(), packetIn.isLongDistance(), - packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, - packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); - } catch (Throwable var16) { - logger.warn("Could not spawn particle effect " + packetIn.getParticleType()); - return; - } + public void handleUpdateScore(S3CPacketUpdateScore packetIn) { + Scoreboard scoreboard = this.clientWorldController.getScoreboard(); + ScoreObjective scoreobjective = scoreboard.getObjective(packetIn.getObjectiveName()); + if (packetIn.getScoreAction() == S3CPacketUpdateScore.Action.CHANGE) { + Score score = scoreboard.getValueFromObjective(packetIn.getPlayerName(), scoreobjective); + score.setScorePoints(packetIn.getScoreValue()); + } else if (packetIn.getScoreAction() == S3CPacketUpdateScore.Action.REMOVE) { + if (StringUtils.isNullOrEmpty(packetIn.getObjectiveName())) { + scoreboard.removeObjectiveFromEntity(packetIn.getPlayerName(), (ScoreObjective) null); + } else if (scoreobjective != null) { + scoreboard.removeObjectiveFromEntity(packetIn.getPlayerName(), scoreobjective); } } } - /**+ - * Updates en entity's attributes and their respective - * modifiers, which are used for speed bonusses (player - * sprinting, animals fleeing, baby speed), weapon/tool - * attackDamage, hostiles followRange randomization, zombie - * maxHealth and knockback resistance as well as reinforcement - * spawning chance. + /** + * + Updates a specified sign with the specified text lines */ - public void handleEntityProperties(S20PacketEntityProperties packetIn) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - if (entity != null) { - if (!(entity instanceof EntityLivingBase)) { - throw new IllegalStateException( - "Server tried to update attributes of a non-living entity (actually: " + entity + ")"); - } else { - BaseAttributeMap baseattributemap = ((EntityLivingBase) entity).getAttributeMap(); - - List lst = packetIn.func_149441_d(); - for (int i = 0, l = lst.size(); i < l; ++i) { - S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot = lst.get(i); - IAttributeInstance iattributeinstance = baseattributemap - .getAttributeInstanceByName(s20packetentityproperties$snapshot.func_151409_a()); - if (iattributeinstance == null) { - iattributeinstance = baseattributemap.registerAttribute(new RangedAttribute((IAttribute) null, - s20packetentityproperties$snapshot.func_151409_a(), 0.0D, 2.2250738585072014E-308D, - Double.MAX_VALUE)); - } - - iattributeinstance.setBaseValue(s20packetentityproperties$snapshot.func_151410_b()); - iattributeinstance.removeAllModifiers(); - - for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c()) { - iattributeinstance.applyModifier(attributemodifier); - } + public void handleUpdateSign(S33PacketUpdateSign packetIn) { + boolean flag = false; + if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) { + TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); + if (tileentity instanceof TileEntitySign) { + TileEntitySign tileentitysign = (TileEntitySign) tileentity; + if (tileentitysign.getIsEditable()) { + System.arraycopy(packetIn.getLines(), 0, tileentitysign.signText, 0, 4); + tileentitysign.markDirty(); + tileentitysign.clearProfanityFilterCache(); } - } - } - } - - /**+ - * Returns this the NetworkManager instance registered with this - * NetworkHandlerPlayClient - */ - public EaglercraftNetworkManager getNetworkManager() { - return this.netManager; - } - - public Collection getPlayerInfoMap() { - return this.playerInfoMap.values(); - } - - /**+ - * Gets the client's description information about another - * player on the server. - */ - public NetworkPlayerInfo getPlayerInfo(EaglercraftUUID parUUID) { - return (NetworkPlayerInfo) this.playerInfoMap.get(parUUID); - } - - /**+ - * Gets the client's description information about another - * player on the server. - */ - public NetworkPlayerInfo getPlayerInfo(String parString1) { - for (NetworkPlayerInfo networkplayerinfo : this.playerInfoMap.values()) { - if (networkplayerinfo.getGameProfile().getName().equals(parString1)) { - return networkplayerinfo; + flag = true; } } - return null; + if (!flag && this.gameController.thePlayer != null) { + this.gameController.thePlayer.addChatMessage(new ChatComponentText("Unable to locate sign at " + + packetIn.getPos().getX() + ", " + packetIn.getPos().getY() + ", " + packetIn.getPos().getZ())); + } + } - public GameProfile getGameProfile() { - return this.profile; + /** + * + Updates the NBTTagCompound metadata of instances of the following + * entitytypes: Mob spawners, command blocks, beacons, skulls, flowerpot + */ + public void handleUpdateTileEntity(S35PacketUpdateTileEntity packetIn) { + if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) { + TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); + int i = packetIn.getTileEntityType(); + if (i == 1 && tileentity instanceof TileEntityMobSpawner + || i == 2 && tileentity instanceof TileEntityCommandBlock + || i == 3 && tileentity instanceof TileEntityBeacon + || i == 4 && tileentity instanceof TileEntitySkull + || i == 5 && tileentity instanceof TileEntityFlowerPot + || i == 6 && tileentity instanceof TileEntityBanner) { + tileentity.readFromNBT(packetIn.getNbtCompound()); + } + } + + } + + /** + * + Retrieves the player identified by the packet, puts him to sleep if + * possible (and flags whether all players are asleep) + */ + public void handleUseBed(S0APacketUseBed packetIn) { + packetIn.getPlayer(this.clientWorldController).trySleep(packetIn.getBedPosition()); + } + + /** + * + Handles the placement of a specified ItemStack in a specified + * container/inventory slot + */ + public void handleWindowItems(S30PacketWindowItems packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + if (packetIn.func_148911_c() == 0) { + entityplayersp.inventoryContainer.putStacksInSlots(packetIn.getItemStacks()); + } else if (packetIn.func_148911_c() == entityplayersp.openContainer.windowId) { + entityplayersp.openContainer.putStacksInSlots(packetIn.getItemStacks()); + } + + } + + /** + * + Sets the progressbar of the opened window to the specified value + */ + public void handleWindowProperty(S31PacketWindowProperty packetIn) { + EntityPlayerSP entityplayersp = this.gameController.thePlayer; + if (entityplayersp.openContainer != null && entityplayersp.openContainer.windowId == packetIn.getWindowId()) { + entityplayersp.openContainer.updateProgressBar(packetIn.getVarIndex(), packetIn.getVarValue()); + } + + } + + public void handleWorldBorder(S44PacketWorldBorder packetIn) { + packetIn.func_179788_a(this.clientWorldController.getWorldBorder()); } public boolean isClientInEaglerSingleplayerOrLAN() { return isIntegratedServer; } + + /** + * + Invoked when disconnecting, the parameter is a ChatComponent describing the + * reason for termination + */ + public void onDisconnect(IChatComponent ichatcomponent) { + VoiceClientController.handleServerDisconnect(); + Minecraft.getMinecraft().getRenderManager() + .setEnableFNAWSkins(this.gameController.gameSettings.enableFNAWSkins); + if (this.gameController.theWorld != null) { + this.gameController.loadWorld((WorldClient) null); + } + if (this.guiScreenServer != null) { + this.gameController.shutdownIntegratedServer( + new GuiDisconnected(this.guiScreenServer, "disconnect.lost", ichatcomponent)); + } else { + this.gameController.shutdownIntegratedServer( + new GuiDisconnected(new GuiMultiplayer(new GuiMainMenu()), "disconnect.lost", ichatcomponent)); + } + } + + public void sendEaglerMessage(GameMessagePacket packet) { + try { + eaglerMessageController.sendPacket(packet); + } catch (IOException e) { + logger.error("Failed to send eaglercraft plugin message packet: " + packet); + logger.error(e); + } + } + + public void setEaglerMessageController(GameProtocolMessageController eaglerMessageController) { + this.eaglerMessageController = eaglerMessageController; + } + + public boolean webViewSendHandler(GameMessagePacket pkt) { + if (eaglerMessageController == null) { + return false; + } + if (this.gameController.thePlayer == null || this.gameController.thePlayer.sendQueue != this) { + logger.error("WebView sent message on a dead handler!"); + return false; + } + if (eaglerMessageController.protocol.ver >= 4) { + sendEaglerMessage(pkt); + return true; + } else { + return false; + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/network/NetworkPlayerInfo.java b/src/game/java/net/minecraft/client/network/NetworkPlayerInfo.java index fff5c425..6fca2682 100644 --- a/src/game/java/net/minecraft/client/network/NetworkPlayerInfo.java +++ b/src/game/java/net/minecraft/client/network/NetworkPlayerInfo.java @@ -10,22 +10,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,59 +59,44 @@ public class NetworkPlayerInfo { this.displayNameProfanityFilter = null; } - /**+ - * Returns the GameProfile for the player represented by this - * NetworkPlayerInfo instance - */ - public GameProfile getGameProfile() { - return this.gameProfile; + public int func_178835_l() { + return this.field_178873_i; } - public WorldSettings.GameType getGameType() { - return this.gameType; + public void func_178836_b(int parInt1) { + this.field_178873_i = parInt1; } - public int getResponseTime() { - return this.responseTime; + public void func_178843_c(long parLong1) { + this.field_178869_m = parLong1; } - protected void setGameType(WorldSettings.GameType parGameType) { - this.gameType = parGameType; + public void func_178844_b(long parLong1) { + this.field_178868_l = parLong1; } - protected void setResponseTime(int parInt1) { - this.responseTime = parInt1; + public void func_178846_a(long parLong1) { + this.field_178871_k = parLong1; } - public boolean hasLocationSkin() { - return true; + public long func_178847_n() { + return this.field_178871_k; } - public String getSkinType() { - return Minecraft.getMinecraft().getNetHandler().getSkinCache().getSkin(this.gameProfile) - .getSkinModel().profileSkinType; + public long func_178855_p() { + return this.field_178869_m; } - public SkinModel getEaglerSkinModel() { - return Minecraft.getMinecraft().getNetHandler().getSkinCache().getSkin(this.gameProfile).getSkinModel(); + public void func_178857_c(int parInt1) { + this.field_178870_j = parInt1; } - public ResourceLocation getLocationSkin() { - return Minecraft.getMinecraft().getNetHandler().getSkinCache().getSkin(this.gameProfile).getResourceLocation(); + public long func_178858_o() { + return this.field_178868_l; } - public ResourceLocation getLocationCape() { - return Minecraft.getMinecraft().getNetHandler().getCapeCache().getCape(this.gameProfile.getId()) - .getResourceLocation(); - } - - public ScorePlayerTeam getPlayerTeam() { - return Minecraft.getMinecraft().theWorld.getScoreboard().getPlayersTeam(this.getGameProfile().getName()); - } - - public void setDisplayName(IChatComponent displayNameIn) { - this.displayName = displayNameIn; - this.displayNameProfanityFilter = null; + public int func_178860_m() { + return this.field_178870_j; } public IChatComponent getDisplayName() { @@ -131,6 +119,18 @@ public class NetworkPlayerInfo { } } + public SkinModel getEaglerSkinModel() { + return Minecraft.getMinecraft().getNetHandler().getSkinCache().getSkin(this.gameProfile).getSkinModel(); + } + + /** + * + Returns the GameProfile for the player represented by this + * NetworkPlayerInfo instance + */ + public GameProfile getGameProfile() { + return this.gameProfile; + } + public String getGameProfileNameProfanityFilter() { if (Minecraft.getMinecraft().isEnableProfanityFilter()) { if (this.gameProfileProfanityFilter == null) { @@ -143,43 +143,46 @@ public class NetworkPlayerInfo { } } - public int func_178835_l() { - return this.field_178873_i; + public WorldSettings.GameType getGameType() { + return this.gameType; } - public void func_178836_b(int parInt1) { - this.field_178873_i = parInt1; + public ResourceLocation getLocationCape() { + return Minecraft.getMinecraft().getNetHandler().getCapeCache().getCape(this.gameProfile.getId()) + .getResourceLocation(); } - public int func_178860_m() { - return this.field_178870_j; + public ResourceLocation getLocationSkin() { + return Minecraft.getMinecraft().getNetHandler().getSkinCache().getSkin(this.gameProfile).getResourceLocation(); } - public void func_178857_c(int parInt1) { - this.field_178870_j = parInt1; + public ScorePlayerTeam getPlayerTeam() { + return Minecraft.getMinecraft().theWorld.getScoreboard().getPlayersTeam(this.getGameProfile().getName()); } - public long func_178847_n() { - return this.field_178871_k; + public int getResponseTime() { + return this.responseTime; } - public void func_178846_a(long parLong1) { - this.field_178871_k = parLong1; + public String getSkinType() { + return Minecraft.getMinecraft().getNetHandler().getSkinCache().getSkin(this.gameProfile) + .getSkinModel().profileSkinType; } - public long func_178858_o() { - return this.field_178868_l; + public boolean hasLocationSkin() { + return true; } - public void func_178844_b(long parLong1) { - this.field_178868_l = parLong1; + public void setDisplayName(IChatComponent displayNameIn) { + this.displayName = displayNameIn; + this.displayNameProfanityFilter = null; } - public long func_178855_p() { - return this.field_178869_m; + protected void setGameType(WorldSettings.GameType parGameType) { + this.gameType = parGameType; } - public void func_178843_c(long parLong1) { - this.field_178869_m = parLong1; + protected void setResponseTime(int parInt1) { + this.responseTime = parInt1; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/Barrier.java b/src/game/java/net/minecraft/client/particle/Barrier.java index ce860d62..b43ae76f 100644 --- a/src/game/java/net/minecraft/client/particle/Barrier.java +++ b/src/game/java/net/minecraft/client/particle/Barrier.java @@ -8,27 +8,37 @@ import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Barrier extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, + double xSpeedIn, double ySpeedIn, double zSpeedIn, int... parArrayOfInt) { + return new Barrier(worldIn, xCoordIn, yCoordIn, zCoordIn, Item.getItemFromBlock(Blocks.barrier)); + } + } + protected Barrier(World worldIn, double parDouble1, double parDouble2, double parDouble3, Item parItem) { super(worldIn, parDouble1, parDouble2, parDouble3, 0.0D, 0.0D, 0.0D); this.setParticleIcon(Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getParticleIcon(parItem)); @@ -42,8 +52,16 @@ public class Barrier extends EntityFX { return 1; } - /**+ - * Renders the particle + public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, + float f3, float f4, float f5) { + accelerator.drawParticle(this, particleIcon.getOriginX(), particleIcon.getOriginY(), getBrightnessForRender(f), + Math.min(particleIcon.getIconWidth(), particleIcon.getIconHeight()), 0.5f, this.particleRed, + this.particleGreen, this.particleBlue, this.particleAlpha); + return true; + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer worldRendererIn, Entity entityIn, float partialTicks, float parFloat2, float parFloat3, float parFloat4, float parFloat5, float parFloat6) { @@ -79,19 +97,4 @@ public class Barrier extends EntityFX { .tex((double) f, (double) f3).color(this.particleRed, this.particleGreen, this.particleBlue, 1.0F) .lightmap(j, k).endVertex(); } - - public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, - float f3, float f4, float f5) { - accelerator.drawParticle(this, particleIcon.getOriginX(), particleIcon.getOriginY(), getBrightnessForRender(f), - Math.min(particleIcon.getIconWidth(), particleIcon.getIconHeight()), 0.5f, this.particleRed, - this.particleGreen, this.particleBlue, this.particleAlpha); - return true; - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, - double xSpeedIn, double ySpeedIn, double zSpeedIn, int... parArrayOfInt) { - return new Barrier(worldIn, xCoordIn, yCoordIn, zCoordIn, Item.getItemFromBlock(Blocks.barrier)); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EffectRenderer.java b/src/game/java/net/minecraft/client/particle/EffectRenderer.java index e90fc93f..da1db100 100644 --- a/src/game/java/net/minecraft/client/particle/EffectRenderer.java +++ b/src/game/java/net/minecraft/client/particle/EffectRenderer.java @@ -1,19 +1,22 @@ package net.minecraft.client.particle; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE2; import java.util.ArrayList; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.minecraft.AcceleratedEffectRenderer; -import net.lax1dude.eaglercraft.v1_8.minecraft.IAcceleratedParticleEngine; - import java.util.concurrent.Callable; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.minecraft.AcceleratedEffectRenderer; +import net.lax1dude.eaglercraft.v1_8.minecraft.IAcceleratedParticleEngine; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; @@ -38,22 +41,25 @@ import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,17 +68,17 @@ public class EffectRenderer { private static final ResourceLocation particleTextures = new ResourceLocation("textures/particle/particles.png"); private static final ResourceLocation particleMaterialsTextures = new ResourceLocation( "eagler:glsl/deferred/particles_s.png"); + public static final AcceleratedEffectRenderer vanillaAcceleratedParticleRenderer = new AcceleratedEffectRenderer(); protected World worldObj; private List[][] fxLayers = new List[4][]; private List particleEmitters = Lists.newArrayList(); private TextureManager renderer; - /**+ - * RNG. + /** + * + RNG. */ private EaglercraftRandom rand = new EaglercraftRandom(); - private Map particleTypes = Maps.newHashMap(); - public static final AcceleratedEffectRenderer vanillaAcceleratedParticleRenderer = new AcceleratedEffectRenderer(); + private Map particleTypes = Maps.newHashMap(); public IAcceleratedParticleEngine acceleratedParticleRenderer = null; public EffectRenderer(World worldIn, TextureManager rendererIn) { @@ -92,6 +98,148 @@ public class EffectRenderer { : null; } + public void addBlockDestroyEffects(BlockPos pos, IBlockState state) { + if (state.getBlock().getMaterial() != Material.air) { + state = state.getBlock().getActualState(state, this.worldObj, pos); + byte b0 = 4; + + for (int i = 0; i < b0; ++i) { + for (int j = 0; j < b0; ++j) { + for (int k = 0; k < b0; ++k) { + double d0 = (double) pos.getX() + ((double) i + 0.5D) / (double) b0; + double d1 = (double) pos.getY() + ((double) j + 0.5D) / (double) b0; + double d2 = (double) pos.getZ() + ((double) k + 0.5D) / (double) b0; + this.addEffect((new EntityDiggingFX(this.worldObj, d0, d1, d2, d0 - (double) pos.getX() - 0.5D, + d1 - (double) pos.getY() - 0.5D, d2 - (double) pos.getZ() - 0.5D, state)) + .func_174846_a(pos)); + } + } + } + + } + } + + /** + * + Adds block hit particles for the specified block + */ + public void addBlockHitEffects(BlockPos pos, EnumFacing side) { + IBlockState iblockstate = this.worldObj.getBlockState(pos); + Block block = iblockstate.getBlock(); + if (block.getRenderType() != -1) { + int i = pos.getX(); + int j = pos.getY(); + int k = pos.getZ(); + float f = 0.1F; + double d0 = (double) i + + this.rand.nextDouble() + * (block.getBlockBoundsMaxX() - block.getBlockBoundsMinX() - (double) (f * 2.0F)) + + (double) f + block.getBlockBoundsMinX(); + double d1 = (double) j + + this.rand.nextDouble() + * (block.getBlockBoundsMaxY() - block.getBlockBoundsMinY() - (double) (f * 2.0F)) + + (double) f + block.getBlockBoundsMinY(); + double d2 = (double) k + + this.rand.nextDouble() + * (block.getBlockBoundsMaxZ() - block.getBlockBoundsMinZ() - (double) (f * 2.0F)) + + (double) f + block.getBlockBoundsMinZ(); + if (side == EnumFacing.DOWN) { + d1 = (double) j + block.getBlockBoundsMinY() - (double) f; + } + + if (side == EnumFacing.UP) { + d1 = (double) j + block.getBlockBoundsMaxY() + (double) f; + } + + if (side == EnumFacing.NORTH) { + d2 = (double) k + block.getBlockBoundsMinZ() - (double) f; + } + + if (side == EnumFacing.SOUTH) { + d2 = (double) k + block.getBlockBoundsMaxZ() + (double) f; + } + + if (side == EnumFacing.WEST) { + d0 = (double) i + block.getBlockBoundsMinX() - (double) f; + } + + if (side == EnumFacing.EAST) { + d0 = (double) i + block.getBlockBoundsMaxX() + (double) f; + } + + this.addEffect((new EntityDiggingFX(this.worldObj, d0, d1, d2, 0.0D, 0.0D, 0.0D, iblockstate)) + .func_174846_a(pos).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); + } + } + + public void addEffect(EntityFX effect) { + int i = effect.getFXLayer(); + int j = effect.getAlpha() != 1.0F ? 0 : 1; + if (this.fxLayers[i][j].size() >= 4000) { + this.fxLayers[i][j].remove(0); + } + + this.fxLayers[i][j].add(effect); + } + + public void clearEffects(World worldIn) { + this.worldObj = worldIn; + + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 2; ++j) { + this.fxLayers[i][j].clear(); + } + } + + this.particleEmitters.clear(); + } + + public void emitParticleAtEntity(Entity entityIn, EnumParticleTypes particleTypes) { + this.particleEmitters.add(new EntityParticleEmitter(this.worldObj, entityIn, particleTypes)); + } + + public String getStatistics() { + int i = 0; + + for (int j = 0; j < 4; ++j) { + for (int k = 0; k < 2; ++k) { + i += this.fxLayers[j][k].size(); + } + } + + return "" + i; + } + + public boolean hasParticlesInAlphaLayer() { + for (int i = 0; i < 3; ++i) { + if (!this.fxLayers[i][0].isEmpty()) { + return true; + } + } + return false; + } + + public void moveToAlphaLayer(EntityFX effect) { + this.moveToLayer(effect, 1, 0); + } + + private void moveToLayer(EntityFX effect, int parInt1, int parInt2) { + for (int i = 0; i < 4; ++i) { + if (this.fxLayers[i][parInt1].contains(effect)) { + this.fxLayers[i][parInt1].remove(effect); + this.fxLayers[i][parInt2].add(effect); + } + } + + } + + public void moveToNoAlphaLayer(EntityFX effect) { + this.moveToLayer(effect, 0, 1); + } + + public void registerParticle(int id, IParticleFactory particleFactory) { + this.particleTypes.put(Integer.valueOf(id), particleFactory); + } + private void registerVanillaParticles() { this.registerParticle(EnumParticleTypes.EXPLOSION_NORMAL.getParticleID(), new EntityExplodeFX.Factory()); this.registerParticle(EnumParticleTypes.WATER_BUBBLE.getParticleID(), new EntityBubbleFX.Factory()); @@ -141,114 +289,31 @@ public class EffectRenderer { this.registerParticle(EnumParticleTypes.MOB_APPEARANCE.getParticleID(), new MobAppearance.Factory()); } - public void registerParticle(int id, IParticleFactory particleFactory) { - this.particleTypes.put(Integer.valueOf(id), particleFactory); - } + public void renderLitParticles(Entity entityIn, float parFloat1) { + float f = 0.017453292F; + float f1 = MathHelper.cos(entityIn.rotationYaw * 0.017453292F); + float f2 = MathHelper.sin(entityIn.rotationYaw * 0.017453292F); + float f3 = -f2 * MathHelper.sin(entityIn.rotationPitch * 0.017453292F); + float f4 = f1 * MathHelper.sin(entityIn.rotationPitch * 0.017453292F); + float f5 = MathHelper.cos(entityIn.rotationPitch * 0.017453292F); - public void emitParticleAtEntity(Entity entityIn, EnumParticleTypes particleTypes) { - this.particleEmitters.add(new EntityParticleEmitter(this.worldObj, entityIn, particleTypes)); - } - - /**+ - * Spawns the relevant particle according to the particle id. - */ - public EntityFX spawnEffectParticle(int particleId, double parDouble1, double parDouble2, double parDouble3, - double parDouble4, double parDouble5, double parDouble6, int... parArrayOfInt) { - IParticleFactory iparticlefactory = (IParticleFactory) this.particleTypes.get(Integer.valueOf(particleId)); - if (iparticlefactory != null) { - EntityFX entityfx = iparticlefactory.getEntityFX(particleId, this.worldObj, parDouble1, parDouble2, - parDouble3, parDouble4, parDouble5, parDouble6, parArrayOfInt); - if (entityfx != null) { - this.addEffect(entityfx); - return entityfx; - } - } - - return null; - } - - public void addEffect(EntityFX effect) { - int i = effect.getFXLayer(); - int j = effect.getAlpha() != 1.0F ? 0 : 1; - if (this.fxLayers[i][j].size() >= 4000) { - this.fxLayers[i][j].remove(0); - } - - this.fxLayers[i][j].add(effect); - } - - public void updateEffects() { - for (int i = 0; i < 4; ++i) { - this.updateEffectLayer(i); - } - - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = this.particleEmitters.size(); i < l; ++i) { - EntityParticleEmitter entityparticleemitter = this.particleEmitters.get(i); - entityparticleemitter.onUpdate(); - if (entityparticleemitter.isDead) { - arraylist.add(entityparticleemitter); - } - } - - this.particleEmitters.removeAll(arraylist); - } - - private void updateEffectLayer(int parInt1) { for (int i = 0; i < 2; ++i) { - this.updateEffectAlphaLayer(this.fxLayers[parInt1][i]); - } + List list = this.fxLayers[3][i]; + if (!list.isEmpty()) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - } - - private void updateEffectAlphaLayer(List parList) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < parList.size(); ++i) { - EntityFX entityfx = (EntityFX) parList.get(i); - this.tickParticle(entityfx); - if (entityfx.isDead) { - arraylist.add(entityfx); + for (int j = 0; j < list.size(); ++j) { + EntityFX entityfx = (EntityFX) list.get(j); + entityfx.renderParticle(worldrenderer, entityIn, parFloat1, f1, f5, f2, f3, f4); + } } } - parList.removeAll(arraylist); } - private void tickParticle(final EntityFX parEntityFX) { - try { - parEntityFX.onUpdate(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Ticking Particle"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Particle being ticked"); - final int i = parEntityFX.getFXLayer(); - crashreportcategory.addCrashSectionCallable("Particle", new Callable() { - public String call() throws Exception { - return parEntityFX.toString(); - } - }); - crashreportcategory.addCrashSectionCallable("Particle Type", new Callable() { - public String call() throws Exception { - return i == 0 ? "MISC_TEXTURE" - : (i == 1 ? "TERRAIN_TEXTURE" : (i == 3 ? "ENTITY_PARTICLE_TEXTURE" : "Unknown - " + i)); - } - }); - throw new ReportedException(crashreport); - } - } - - public boolean hasParticlesInAlphaLayer() { - for (int i = 0; i < 3; ++i) { - if (!this.fxLayers[i][0].isEmpty()) { - return true; - } - } - return false; - } - - /**+ - * Renders all current particles. Args player, partialTickTime + /** + * + Renders all current particles. Args player, partialTickTime */ public void renderParticles(Entity entityIn, float partialTicks, int pass) { float f = ActiveRenderInfo.getRotationX(); @@ -361,141 +426,82 @@ public class EffectRenderer { GlStateManager.alphaFunc(GL_GREATER, 0.1F); } - public void renderLitParticles(Entity entityIn, float parFloat1) { - float f = 0.017453292F; - float f1 = MathHelper.cos(entityIn.rotationYaw * 0.017453292F); - float f2 = MathHelper.sin(entityIn.rotationYaw * 0.017453292F); - float f3 = -f2 * MathHelper.sin(entityIn.rotationPitch * 0.017453292F); - float f4 = f1 * MathHelper.sin(entityIn.rotationPitch * 0.017453292F); - float f5 = MathHelper.cos(entityIn.rotationPitch * 0.017453292F); - - for (int i = 0; i < 2; ++i) { - List list = this.fxLayers[3][i]; - if (!list.isEmpty()) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - - for (int j = 0; j < list.size(); ++j) { - EntityFX entityfx = (EntityFX) list.get(j); - entityfx.renderParticle(worldrenderer, entityIn, parFloat1, f1, f5, f2, f3, f4); - } - } - } - - } - - public void clearEffects(World worldIn) { - this.worldObj = worldIn; - - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 2; ++j) { - this.fxLayers[i][j].clear(); - } - } - - this.particleEmitters.clear(); - } - - public void addBlockDestroyEffects(BlockPos pos, IBlockState state) { - if (state.getBlock().getMaterial() != Material.air) { - state = state.getBlock().getActualState(state, this.worldObj, pos); - byte b0 = 4; - - for (int i = 0; i < b0; ++i) { - for (int j = 0; j < b0; ++j) { - for (int k = 0; k < b0; ++k) { - double d0 = (double) pos.getX() + ((double) i + 0.5D) / (double) b0; - double d1 = (double) pos.getY() + ((double) j + 0.5D) / (double) b0; - double d2 = (double) pos.getZ() + ((double) k + 0.5D) / (double) b0; - this.addEffect((new EntityDiggingFX(this.worldObj, d0, d1, d2, d0 - (double) pos.getX() - 0.5D, - d1 - (double) pos.getY() - 0.5D, d2 - (double) pos.getZ() - 0.5D, state)) - .func_174846_a(pos)); - } - } - } - - } - } - - /**+ - * Adds block hit particles for the specified block + /** + * + Spawns the relevant particle according to the particle id. */ - public void addBlockHitEffects(BlockPos pos, EnumFacing side) { - IBlockState iblockstate = this.worldObj.getBlockState(pos); - Block block = iblockstate.getBlock(); - if (block.getRenderType() != -1) { - int i = pos.getX(); - int j = pos.getY(); - int k = pos.getZ(); - float f = 0.1F; - double d0 = (double) i - + this.rand.nextDouble() - * (block.getBlockBoundsMaxX() - block.getBlockBoundsMinX() - (double) (f * 2.0F)) - + (double) f + block.getBlockBoundsMinX(); - double d1 = (double) j - + this.rand.nextDouble() - * (block.getBlockBoundsMaxY() - block.getBlockBoundsMinY() - (double) (f * 2.0F)) - + (double) f + block.getBlockBoundsMinY(); - double d2 = (double) k - + this.rand.nextDouble() - * (block.getBlockBoundsMaxZ() - block.getBlockBoundsMinZ() - (double) (f * 2.0F)) - + (double) f + block.getBlockBoundsMinZ(); - if (side == EnumFacing.DOWN) { - d1 = (double) j + block.getBlockBoundsMinY() - (double) f; + public EntityFX spawnEffectParticle(int particleId, double parDouble1, double parDouble2, double parDouble3, + double parDouble4, double parDouble5, double parDouble6, int... parArrayOfInt) { + IParticleFactory iparticlefactory = (IParticleFactory) this.particleTypes.get(Integer.valueOf(particleId)); + if (iparticlefactory != null) { + EntityFX entityfx = iparticlefactory.getEntityFX(particleId, this.worldObj, parDouble1, parDouble2, + parDouble3, parDouble4, parDouble5, parDouble6, parArrayOfInt); + if (entityfx != null) { + this.addEffect(entityfx); + return entityfx; } + } - if (side == EnumFacing.UP) { - d1 = (double) j + block.getBlockBoundsMaxY() + (double) f; - } + return null; + } - if (side == EnumFacing.NORTH) { - d2 = (double) k + block.getBlockBoundsMinZ() - (double) f; - } - - if (side == EnumFacing.SOUTH) { - d2 = (double) k + block.getBlockBoundsMaxZ() + (double) f; - } - - if (side == EnumFacing.WEST) { - d0 = (double) i + block.getBlockBoundsMinX() - (double) f; - } - - if (side == EnumFacing.EAST) { - d0 = (double) i + block.getBlockBoundsMaxX() + (double) f; - } - - this.addEffect((new EntityDiggingFX(this.worldObj, d0, d1, d2, 0.0D, 0.0D, 0.0D, iblockstate)) - .func_174846_a(pos).multiplyVelocity(0.2F).multipleParticleScaleBy(0.6F)); + private void tickParticle(final EntityFX parEntityFX) { + try { + parEntityFX.onUpdate(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Ticking Particle"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Particle being ticked"); + final int i = parEntityFX.getFXLayer(); + crashreportcategory.addCrashSectionCallable("Particle", new Callable() { + public String call() throws Exception { + return parEntityFX.toString(); + } + }); + crashreportcategory.addCrashSectionCallable("Particle Type", new Callable() { + public String call() throws Exception { + return i == 0 ? "MISC_TEXTURE" + : (i == 1 ? "TERRAIN_TEXTURE" : (i == 3 ? "ENTITY_PARTICLE_TEXTURE" : "Unknown - " + i)); + } + }); + throw new ReportedException(crashreport); } } - public void moveToAlphaLayer(EntityFX effect) { - this.moveToLayer(effect, 1, 0); + private void updateEffectAlphaLayer(List parList) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < parList.size(); ++i) { + EntityFX entityfx = (EntityFX) parList.get(i); + this.tickParticle(entityfx); + if (entityfx.isDead) { + arraylist.add(entityfx); + } + } + + parList.removeAll(arraylist); } - public void moveToNoAlphaLayer(EntityFX effect) { - this.moveToLayer(effect, 0, 1); + private void updateEffectLayer(int parInt1) { + for (int i = 0; i < 2; ++i) { + this.updateEffectAlphaLayer(this.fxLayers[parInt1][i]); + } + } - private void moveToLayer(EntityFX effect, int parInt1, int parInt2) { + public void updateEffects() { for (int i = 0; i < 4; ++i) { - if (this.fxLayers[i][parInt1].contains(effect)) { - this.fxLayers[i][parInt1].remove(effect); - this.fxLayers[i][parInt2].add(effect); + this.updateEffectLayer(i); + } + + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = this.particleEmitters.size(); i < l; ++i) { + EntityParticleEmitter entityparticleemitter = this.particleEmitters.get(i); + entityparticleemitter.onUpdate(); + if (entityparticleemitter.isDead) { + arraylist.add(entityparticleemitter); } } - } - - public String getStatistics() { - int i = 0; - - for (int j = 0; j < 4; ++j) { - for (int k = 0; k < 2; ++k) { - i += this.fxLayers[j][k].size(); - } - } - - return "" + i; + this.particleEmitters.removeAll(arraylist); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityAuraFX.java b/src/game/java/net/minecraft/client/particle/EntityAuraFX.java index 2b407907..e0b362fd 100644 --- a/src/game/java/net/minecraft/client/particle/EntityAuraFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityAuraFX.java @@ -2,27 +2,47 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityAuraFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityAuraFX(world, d0, d1, d2, d3, d4, d5); + } + } + + public static class HappyVillagerFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + EntityAuraFX entityaurafx = new EntityAuraFX(world, d0, d1, d2, d3, d4, d5); + entityaurafx.setParticleTextureIndex(82); + entityaurafx.setRBGColorF(1.0F, 1.0F, 1.0F); + return entityaurafx; + } + } + protected EntityAuraFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double speedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, speedIn); @@ -40,8 +60,8 @@ public class EntityAuraFX extends EntityFX { this.noClip = true; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -56,21 +76,4 @@ public class EntityAuraFX extends EntityFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityAuraFX(world, d0, d1, d2, d3, d4, d5); - } - } - - public static class HappyVillagerFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - EntityAuraFX entityaurafx = new EntityAuraFX(world, d0, d1, d2, d3, d4, d5); - entityaurafx.setParticleTextureIndex(82); - entityaurafx.setRBGColorF(1.0F, 1.0F, 1.0F); - return entityaurafx; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityBlockDustFX.java b/src/game/java/net/minecraft/client/particle/EntityBlockDustFX.java index 32a52cee..3c849a25 100644 --- a/src/game/java/net/minecraft/client/particle/EntityBlockDustFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityBlockDustFX.java @@ -4,35 +4,30 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityBlockDustFX extends EntityDiggingFX { - protected EntityBlockDustFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, - double ySpeedIn, double zSpeedIn, IBlockState state) { - super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, state); - this.motionX = xSpeedIn; - this.motionY = ySpeedIn; - this.motionZ = zSpeedIn; - } - public static class Factory implements IParticleFactory { public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, double d5, int... aint) { @@ -41,4 +36,12 @@ public class EntityBlockDustFX extends EntityDiggingFX { : (new EntityBlockDustFX(world, d0, d1, d2, d3, d4, d5, iblockstate)).func_174845_l(); } } + + protected EntityBlockDustFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, + double ySpeedIn, double zSpeedIn, IBlockState state) { + super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, state); + this.motionX = xSpeedIn; + this.motionY = ySpeedIn; + this.motionZ = zSpeedIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityBreakingFX.java b/src/game/java/net/minecraft/client/particle/EntityBreakingFX.java index 9d1d921e..61cf4f65 100644 --- a/src/game/java/net/minecraft/client/particle/EntityBreakingFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityBreakingFX.java @@ -10,29 +10,50 @@ import net.minecraft.item.Item; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityBreakingFX extends EntityFX { - protected EntityBreakingFX(World worldIn, double posXIn, double posYIn, double posZIn, Item parItem) { - this(worldIn, posXIn, posYIn, posZIn, parItem, 0); + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... aint) { + int i = aint.length > 1 ? aint[1] : 0; + return new EntityBreakingFX(world, d0, d1, d2, d3, d4, d5, Item.getItemById(aint[0]), i); + } + } + + public static class SlimeFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityBreakingFX(world, d0, d1, d2, Items.slime_ball); + } + } + + public static class SnowballFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityBreakingFX(world, d0, d1, d2, Items.snowball); + } } protected EntityBreakingFX(World worldIn, double posXIn, double posYIn, double posZIn, double xSpeedIn, @@ -46,6 +67,10 @@ public class EntityBreakingFX extends EntityFX { this.motionZ += zSpeedIn; } + protected EntityBreakingFX(World worldIn, double posXIn, double posYIn, double posZIn, Item parItem) { + this(worldIn, posXIn, posYIn, posZIn, parItem, 0); + } + protected EntityBreakingFX(World worldIn, double posXIn, double posYIn, double posZIn, Item parItem, int parInt1) { super(worldIn, posXIn, posYIn, posZIn, 0.0D, 0.0D, 0.0D); this.setParticleIcon( @@ -59,8 +84,21 @@ public class EntityBreakingFX extends EntityFX { return 1; } - /**+ - * Renders the particle + public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, + float f3, float f4, float f5) { + int w = this.particleIcon.getIconWidth(); + int h = this.particleIcon.getIconHeight(); + int xOffset = MathHelper.floor_float(w * this.particleTextureJitterX * 4.0f * 0.0625f); + int yOffset = MathHelper.floor_float(h * this.particleTextureJitterY * 4.0f * 0.0625f); + int texSize = Math.min(w, h) / 4; + accelerator.drawParticle(this, this.particleIcon.getOriginX() + xOffset, + this.particleIcon.getOriginY() + yOffset, getBrightnessForRender(f), texSize, particleScale * 0.1f, + this.particleRed, this.particleGreen, this.particleBlue, 1.0f); + return true; + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer worldrenderer, Entity var2, float f, float f1, float f2, float f3, float f4, float f5) { @@ -103,39 +141,4 @@ public class EntityBreakingFX extends EntityFX { .tex((double) f7, (double) f9).color(this.particleRed, this.particleGreen, this.particleBlue, 1.0F) .lightmap(j, k).endVertex(); } - - public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, - float f3, float f4, float f5) { - int w = this.particleIcon.getIconWidth(); - int h = this.particleIcon.getIconHeight(); - int xOffset = MathHelper.floor_float(w * this.particleTextureJitterX * 4.0f * 0.0625f); - int yOffset = MathHelper.floor_float(h * this.particleTextureJitterY * 4.0f * 0.0625f); - int texSize = Math.min(w, h) / 4; - accelerator.drawParticle(this, this.particleIcon.getOriginX() + xOffset, - this.particleIcon.getOriginY() + yOffset, getBrightnessForRender(f), texSize, particleScale * 0.1f, - this.particleRed, this.particleGreen, this.particleBlue, 1.0f); - return true; - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... aint) { - int i = aint.length > 1 ? aint[1] : 0; - return new EntityBreakingFX(world, d0, d1, d2, d3, d4, d5, Item.getItemById(aint[0]), i); - } - } - - public static class SlimeFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityBreakingFX(world, d0, d1, d2, Items.slime_ball); - } - } - - public static class SnowballFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityBreakingFX(world, d0, d1, d2, Items.snowball); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityBubbleFX.java b/src/game/java/net/minecraft/client/particle/EntityBubbleFX.java index cf904c59..631c443d 100644 --- a/src/game/java/net/minecraft/client/particle/EntityBubbleFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityBubbleFX.java @@ -4,27 +4,37 @@ import net.minecraft.block.material.Material; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityBubbleFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityBubbleFX(world, d0, d1, d2, d3, d4, d5); + } + } + protected EntityBubbleFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); @@ -40,8 +50,8 @@ public class EntityBubbleFX extends EntityFX { this.particleMaxAge = (int) (8.0D / (Math.random() * 0.8D + 0.2D)); } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -61,11 +71,4 @@ public class EntityBubbleFX extends EntityFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityBubbleFX(world, d0, d1, d2, d3, d4, d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityCloudFX.java b/src/game/java/net/minecraft/client/particle/EntityCloudFX.java index 1ef9601e..b9d33b4e 100644 --- a/src/game/java/net/minecraft/client/particle/EntityCloudFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityCloudFX.java @@ -6,27 +6,37 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityCloudFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityCloudFX(world, d0, d1, d2, d3, d4, d5); + } + } + float field_70569_a; protected EntityCloudFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, @@ -49,19 +59,8 @@ public class EntityCloudFX extends EntityFX { this.noClip = false; } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.field_70569_a * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -90,10 +89,14 @@ public class EntityCloudFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityCloudFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.field_70569_a * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityCrit2FX.java b/src/game/java/net/minecraft/client/particle/EntityCrit2FX.java index e619ed07..4185483f 100644 --- a/src/game/java/net/minecraft/client/particle/EntityCrit2FX.java +++ b/src/game/java/net/minecraft/client/particle/EntityCrit2FX.java @@ -5,27 +5,48 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityCrit2FX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityCrit2FX(world, d0, d1, d2, d3, d4, d5); + } + } + + public static class MagicFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + EntityCrit2FX entitycrit2fx = new EntityCrit2FX(world, d0, d1, d2, d3, d4, d5); + entitycrit2fx.setRBGColorF(entitycrit2fx.getRedColorF() * 0.3F, entitycrit2fx.getGreenColorF() * 0.8F, + entitycrit2fx.getBlueColorF()); + entitycrit2fx.nextTextureIndexX(); + return entitycrit2fx; + } + } + float field_174839_a; protected EntityCrit2FX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, @@ -54,19 +75,8 @@ public class EntityCrit2FX extends EntityFX { this.onUpdate(); } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.field_174839_a * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -90,21 +100,14 @@ public class EntityCrit2FX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityCrit2FX(world, d0, d1, d2, d3, d4, d5); - } - } - - public static class MagicFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - EntityCrit2FX entitycrit2fx = new EntityCrit2FX(world, d0, d1, d2, d3, d4, d5); - entitycrit2fx.setRBGColorF(entitycrit2fx.getRedColorF() * 0.3F, entitycrit2fx.getGreenColorF() * 0.8F, - entitycrit2fx.getBlueColorF()); - entitycrit2fx.nextTextureIndexX(); - return entitycrit2fx; - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.field_174839_a * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityCritFX.java b/src/game/java/net/minecraft/client/particle/EntityCritFX.java index 51e5dffe..24492d34 100644 --- a/src/game/java/net/minecraft/client/particle/EntityCritFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityCritFX.java @@ -2,36 +2,39 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityCritFX extends EntitySmokeFX { - protected EntityCritFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, - double parDouble2, double parDouble3) { - super(worldIn, xCoordIn, yCoordIn, zCoordIn, parDouble1, parDouble2, parDouble3, 2.5F); - } - public static class Factory implements IParticleFactory { public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, double d5, int... var15) { return new EntityCritFX(world, d0, d1, d2, d3, d4, d5); } } + + protected EntityCritFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, + double parDouble2, double parDouble3) { + super(worldIn, xCoordIn, yCoordIn, zCoordIn, parDouble1, parDouble2, parDouble3, 2.5F); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityDiggingFX.java b/src/game/java/net/minecraft/client/particle/EntityDiggingFX.java index cef3d9e6..d612ed32 100644 --- a/src/game/java/net/minecraft/client/particle/EntityDiggingFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityDiggingFX.java @@ -12,28 +12,39 @@ import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityDiggingFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... aint) { + return (new EntityDiggingFX(world, d0, d1, d2, d3, d4, d5, Block.getStateById(aint[0]))).func_174845_l(); + } + } + private IBlockState field_174847_a; + private BlockPos field_181019_az; protected EntityDiggingFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, @@ -48,19 +59,6 @@ public class EntityDiggingFX extends EntityFX { this.particleAlpha = state.getBlock().getBlockLayer() == EnumWorldBlockLayer.TRANSLUCENT ? 0.999f : 1.0f; } - public EntityDiggingFX func_174846_a(BlockPos pos) { - this.field_181019_az = pos; - if (this.field_174847_a.getBlock() == Blocks.grass) { - return this; - } else { - int i = this.field_174847_a.getBlock().colorMultiplier(this.worldObj, pos); - this.particleRed *= (float) (i >> 16 & 255) / 255.0F; - this.particleGreen *= (float) (i >> 8 & 255) / 255.0F; - this.particleBlue *= (float) (i & 255) / 255.0F; - return this; - } - } - public EntityDiggingFX func_174845_l() { this.field_181019_az = new BlockPos(this.posX, this.posY, this.posZ); Block block = this.field_174847_a.getBlock(); @@ -75,12 +73,48 @@ public class EntityDiggingFX extends EntityFX { } } + public EntityDiggingFX func_174846_a(BlockPos pos) { + this.field_181019_az = pos; + if (this.field_174847_a.getBlock() == Blocks.grass) { + return this; + } else { + int i = this.field_174847_a.getBlock().colorMultiplier(this.worldObj, pos); + this.particleRed *= (float) (i >> 16 & 255) / 255.0F; + this.particleGreen *= (float) (i >> 8 & 255) / 255.0F; + this.particleBlue *= (float) (i & 255) / 255.0F; + return this; + } + } + + public int getBrightnessForRender(float f) { + int i = super.getBrightnessForRender(f); + int j = 0; + if (this.worldObj.isBlockLoaded(this.field_181019_az)) { + j = this.worldObj.getCombinedLight(this.field_181019_az, 0); + } + + return i == 0 ? j : i; + } + public int getFXLayer() { return 1; } - /**+ - * Renders the particle + public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, + float f3, float f4, float f5) { + int w = this.particleIcon.getIconWidth(); + int h = this.particleIcon.getIconHeight(); + int xOffset = MathHelper.floor_float(w * this.particleTextureJitterX * 4.0f * 0.0625f); + int yOffset = MathHelper.floor_float(h * this.particleTextureJitterY * 4.0f * 0.0625f); + int texSize = Math.min(w, h) / 4; + accelerator.drawParticle(this, this.particleIcon.getOriginX() + xOffset, + this.particleIcon.getOriginY() + yOffset, getBrightnessForRender(f), texSize, particleScale * 0.1f, + this.particleRed, this.particleGreen, this.particleBlue, 1.0f); + return true; + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer worldrenderer, Entity var2, float f, float f1, float f2, float f3, float f4, float f5) { @@ -123,34 +157,4 @@ public class EntityDiggingFX extends EntityFX { .tex((double) f7, (double) f9).color(this.particleRed, this.particleGreen, this.particleBlue, 1.0F) .lightmap(j, k).endVertex(); } - - public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, - float f3, float f4, float f5) { - int w = this.particleIcon.getIconWidth(); - int h = this.particleIcon.getIconHeight(); - int xOffset = MathHelper.floor_float(w * this.particleTextureJitterX * 4.0f * 0.0625f); - int yOffset = MathHelper.floor_float(h * this.particleTextureJitterY * 4.0f * 0.0625f); - int texSize = Math.min(w, h) / 4; - accelerator.drawParticle(this, this.particleIcon.getOriginX() + xOffset, - this.particleIcon.getOriginY() + yOffset, getBrightnessForRender(f), texSize, particleScale * 0.1f, - this.particleRed, this.particleGreen, this.particleBlue, 1.0f); - return true; - } - - public int getBrightnessForRender(float f) { - int i = super.getBrightnessForRender(f); - int j = 0; - if (this.worldObj.isBlockLoaded(this.field_181019_az)) { - j = this.worldObj.getCombinedLight(this.field_181019_az, 0); - } - - return i == 0 ? j : i; - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... aint) { - return (new EntityDiggingFX(world, d0, d1, d2, d3, d4, d5, Block.getStateById(aint[0]))).func_174845_l(); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityDropParticleFX.java b/src/game/java/net/minecraft/client/particle/EntityDropParticleFX.java index 05876170..e00ca3ca 100644 --- a/src/game/java/net/minecraft/client/particle/EntityDropParticleFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityDropParticleFX.java @@ -8,28 +8,46 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityDropParticleFX extends EntityFX { + public static class LavaFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityDropParticleFX(world, d0, d1, d2, Material.lava); + } + } + + public static class WaterFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityDropParticleFX(world, d0, d1, d2, Material.water); + } + } + private Material materialType; + private int bobTimer; protected EntityDropParticleFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, @@ -55,19 +73,19 @@ public class EntityDropParticleFX extends EntityFX { this.motionX = this.motionY = this.motionZ = 0.0D; } - public int getBrightnessForRender(float partialTicks) { - return this.materialType == Material.water ? super.getBrightnessForRender(partialTicks) : 257; - } - - /**+ - * Gets how bright this entity is. + /** + * + Gets how bright this entity is. */ public float getBrightness(float partialTicks) { return this.materialType == Material.water ? super.getBrightness(partialTicks) : 1.0F; } - /**+ - * Called to update the entity's position/logic. + public int getBrightnessForRender(float partialTicks) { + return this.materialType == Material.water ? super.getBrightnessForRender(partialTicks) : 257; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -131,18 +149,4 @@ public class EntityDropParticleFX extends EntityFX { } } - - public static class LavaFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityDropParticleFX(world, d0, d1, d2, Material.lava); - } - } - - public static class WaterFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityDropParticleFX(world, d0, d1, d2, Material.water); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityEnchantmentTableParticleFX.java b/src/game/java/net/minecraft/client/particle/EntityEnchantmentTableParticleFX.java index 5e862e06..685a3970 100644 --- a/src/game/java/net/minecraft/client/particle/EntityEnchantmentTableParticleFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityEnchantmentTableParticleFX.java @@ -2,30 +2,41 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityEnchantmentTableParticleFX extends EntityFX { + public static class EnchantmentTable implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityEnchantmentTableParticleFX(world, d0, d1, d2, d3, d4, d5); + } + } + private float field_70565_a; private double coordX; private double coordY; + private double coordZ; protected EntityEnchantmentTableParticleFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, @@ -50,6 +61,17 @@ public class EntityEnchantmentTableParticleFX extends EntityFX { this.setParticleTextureIndex((int) (Math.random() * 26.0D + 1.0D + 224.0D)); } + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float f) { + float f1 = super.getBrightness(f); + float f2 = (float) this.particleAge / (float) this.particleMaxAge; + f2 = f2 * f2; + f2 = f2 * f2; + return f1 * (1.0F - f2) + f2; + } + public int getBrightnessForRender(float f) { int i = super.getBrightnessForRender(f); float f1 = (float) this.particleAge / (float) this.particleMaxAge; @@ -65,19 +87,8 @@ public class EntityEnchantmentTableParticleFX extends EntityFX { return j | k << 16; } - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float f) { - float f1 = super.getBrightness(f); - float f2 = (float) this.particleAge / (float) this.particleMaxAge; - f2 = f2 * f2; - f2 = f2 * f2; - return f1 * (1.0F - f2) + f2; - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -96,11 +107,4 @@ public class EntityEnchantmentTableParticleFX extends EntityFX { } } - - public static class EnchantmentTable implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityEnchantmentTableParticleFX(world, d0, d1, d2, d3, d4, d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityExplodeFX.java b/src/game/java/net/minecraft/client/particle/EntityExplodeFX.java index 22f59cf4..cba6fcbe 100644 --- a/src/game/java/net/minecraft/client/particle/EntityExplodeFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityExplodeFX.java @@ -2,27 +2,37 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityExplodeFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityExplodeFX(world, d0, d1, d2, d3, d4, d5); + } + } + protected EntityExplodeFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); @@ -34,8 +44,8 @@ public class EntityExplodeFX extends EntityFX { this.particleMaxAge = (int) (16.0D / ((double) this.rand.nextFloat() * 0.8D + 0.2D)) + 2; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -57,11 +67,4 @@ public class EntityExplodeFX extends EntityFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityExplodeFX(world, d0, d1, d2, d3, d4, d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityFX.java b/src/game/java/net/minecraft/client/particle/EntityFX.java index c34c18f3..0414fbea 100644 --- a/src/game/java/net/minecraft/client/particle/EntityFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityFX.java @@ -9,27 +9,33 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityFX extends Entity { + public static double interpPosX; + public static double interpPosY; + public static double interpPosZ; protected int particleTextureIndexX; protected int particleTextureIndexY; protected float particleTextureJitterX; @@ -43,9 +49,6 @@ public class EntityFX extends Entity { protected float particleBlue; protected float particleAlpha; protected EaglerTextureAtlasSprite particleIcon; - public static double interpPosX; - public static double interpPosY; - public static double interpPosZ; protected EntityFX(World worldIn, double posXIn, double posYIn, double posZIn) { super(worldIn); @@ -77,58 +80,16 @@ public class EntityFX extends Entity { this.motionZ = this.motionZ / (double) f1 * (double) f * 0.4000000059604645D; } - public EntityFX multiplyVelocity(float multiplier) { - this.motionX *= (double) multiplier; - this.motionY = (this.motionY - 0.10000000149011612D) * (double) multiplier + 0.10000000149011612D; - this.motionZ *= (double) multiplier; - return this; - } - - public EntityFX multipleParticleScaleBy(float parFloat1) { - this.setSize(0.2F * parFloat1, 0.2F * parFloat1); - this.particleScale *= parFloat1; - return this; - } - - public void setRBGColorF(float particleRedIn, float particleGreenIn, float particleBlueIn) { - this.particleRed = particleRedIn; - this.particleGreen = particleGreenIn; - this.particleBlue = particleBlueIn; - } - - /**+ - * Sets the particle alpha (float) + /** + * + If returns false, the item will not inflict any damage against entities. */ - public void setAlphaF(float alpha) { - if (this.particleAlpha == 1.0F && alpha < 1.0F) { - Minecraft.getMinecraft().effectRenderer.moveToAlphaLayer(this); - } else if (this.particleAlpha < 1.0F && alpha == 1.0F) { - Minecraft.getMinecraft().effectRenderer.moveToNoAlphaLayer(this); - } - - this.particleAlpha = alpha; + public boolean canAttackWithItem() { + return false; } - public float getRedColorF() { - return this.particleRed; - } - - public float getGreenColorF() { - return this.particleGreen; - } - - public float getBlueColorF() { - return this.particleBlue; - } - - public float getAlpha() { - return this.particleAlpha; - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; @@ -137,8 +98,49 @@ public class EntityFX extends Entity { protected void entityInit() { } - /**+ - * Called to update the entity's position/logic. + public float getAlpha() { + return this.particleAlpha; + } + + public float getBlueColorF() { + return this.particleBlue; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 0.0f; + } + + public int getFXLayer() { + return 0; + } + + public float getGreenColorF() { + return this.particleGreen; + } + + public float getRedColorF() { + return this.particleRed; + } + + public EntityFX multipleParticleScaleBy(float parFloat1) { + this.setSize(0.2F * parFloat1, 0.2F * parFloat1); + this.particleScale *= parFloat1; + return this; + } + + public EntityFX multiplyVelocity(float multiplier) { + this.motionX *= (double) multiplier; + this.motionY = (this.motionY - 0.10000000149011612D) * (double) multiplier + 0.10000000149011612D; + this.motionZ *= (double) multiplier; + return this; + } + + public void nextTextureIndexX() { + ++this.particleTextureIndexX; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -160,8 +162,26 @@ public class EntityFX extends Entity { } - /**+ - * Renders the particle + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound tagCompund) { + } + + public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, + float f3, float f4, float f5) { + if (getFXLayer() == 3) { + return false; + } else { + accelerator.drawParticle(this, particleTextureIndexX * 16, particleTextureIndexY * 16, + getBrightnessForRender(f), 16, particleScale * 0.1f, this.particleRed, this.particleGreen, + this.particleBlue, this.particleAlpha); + return true; + } + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer worldrenderer, Entity var2, float f, float f1, float f2, float f3, float f4, float f5) { @@ -209,38 +229,21 @@ public class EntityFX extends Entity { .endVertex(); } - public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, float f2, - float f3, float f4, float f5) { - if (getFXLayer() == 3) { - return false; - } else { - accelerator.drawParticle(this, particleTextureIndexX * 16, particleTextureIndexY * 16, - getBrightnessForRender(f), 16, particleScale * 0.1f, this.particleRed, this.particleGreen, - this.particleBlue, this.particleAlpha); - return true; + /** + * + Sets the particle alpha (float) + */ + public void setAlphaF(float alpha) { + if (this.particleAlpha == 1.0F && alpha < 1.0F) { + Minecraft.getMinecraft().effectRenderer.moveToAlphaLayer(this); + } else if (this.particleAlpha < 1.0F && alpha == 1.0F) { + Minecraft.getMinecraft().effectRenderer.moveToNoAlphaLayer(this); } + + this.particleAlpha = alpha; } - public int getFXLayer() { - return 0; - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound tagCompound) { - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound tagCompund) { - } - - /**+ - * Sets the particle's icon. + /** + * + Sets the particle's icon. */ public void setParticleIcon(EaglerTextureAtlasSprite icon) { int i = this.getFXLayer(); @@ -251,8 +254,8 @@ public class EntityFX extends Entity { } } - /**+ - * Public method to set private field particleTextureIndex. + /** + * + Public method to set private field particleTextureIndex. */ public void setParticleTextureIndex(int particleTextureIndex) { if (this.getFXLayer() != 0) { @@ -263,16 +266,10 @@ public class EntityFX extends Entity { } } - public void nextTextureIndexX() { - ++this.particleTextureIndexX; - } - - /**+ - * If returns false, the item will not inflict any damage - * against entities. - */ - public boolean canAttackWithItem() { - return false; + public void setRBGColorF(float particleRedIn, float particleGreenIn, float particleBlueIn) { + this.particleRed = particleRedIn; + this.particleGreen = particleGreenIn; + this.particleBlue = particleBlueIn; } public String toString() { @@ -281,7 +278,9 @@ public class EntityFX extends Entity { + "), Age " + this.particleAge; } - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 0.0f; + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound tagCompound) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityFirework.java b/src/game/java/net/minecraft/client/particle/EntityFirework.java index 5f5cc477..36f4d857 100644 --- a/src/game/java/net/minecraft/client/particle/EntityFirework.java +++ b/src/game/java/net/minecraft/client/particle/EntityFirework.java @@ -11,22 +11,25 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,6 +51,15 @@ public class EntityFirework { this.particleMaxAge = 4; } + public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, + float f2, float f3, float f4, float f5) { + accelerator.drawParticle(this, 64, 32, getBrightnessForRender(f), 64, + 7.1F * MathHelper.sin(((float) this.particleAge + f - 1.0F) * 0.25F * 3.1415927F) * 0.0625f * 0.25f, + this.particleRed, this.particleGreen, this.particleBlue, + 0.6F - ((float) this.particleAge + f - 1.0F) * 0.25F * 0.5F); + return true; + } + public void renderParticle(WorldRenderer worldrenderer, Entity var2, float f, float f1, float f2, float f3, float f4, float f5) { float f6 = 0.25F; @@ -87,15 +99,6 @@ public class EntityFirework { .color(this.particleRed, this.particleGreen, this.particleBlue, this.particleAlpha).lightmap(j, k) .endVertex(); } - - public boolean renderAccelerated(IAcceleratedParticleEngine accelerator, Entity var2, float f, float f1, - float f2, float f3, float f4, float f5) { - accelerator.drawParticle(this, 64, 32, getBrightnessForRender(f), 64, - 7.1F * MathHelper.sin(((float) this.particleAge + f - 1.0F) * 0.25F * 3.1415927F) * 0.0625f * 0.25f, - this.particleRed, this.particleGreen, this.particleBlue, - 0.6F - ((float) this.particleAge + f - 1.0F) * 0.25F * 0.5F); - return true; - } } public static class SparkFX extends EntityFX { @@ -120,44 +123,20 @@ public class EntityFirework { this.noClip = false; } - public void setTrail(boolean trailIn) { - this.trail = trailIn; - } - - public void setTwinkle(boolean twinkleIn) { - this.twinkle = twinkleIn; - } - - public void setColour(int colour) { - float f = (float) ((colour & 16711680) >> 16) / 255.0F; - float f1 = (float) ((colour & '\uff00') >> 8) / 255.0F; - float f2 = (float) ((colour & 255) >> 0) / 255.0F; - float f3 = 1.0F; - this.setRBGColorF(f * f3, f1 * f3, f2 * f3); - } - - public void setFadeColour(int faceColour) { - this.fadeColourRed = (float) ((faceColour & 16711680) >> 16) / 255.0F; - this.fadeColourGreen = (float) ((faceColour & '\uff00') >> 8) / 255.0F; - this.fadeColourBlue = (float) ((faceColour & 255) >> 0) / 255.0F; - this.hasFadeColour = true; - } - - public AxisAlignedBB getCollisionBoundingBox() { - return null; - } - public boolean canBePushed() { return false; } - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - if (!this.twinkle || this.particleAge < this.particleMaxAge / 3 - || (this.particleAge + this.particleMaxAge) / 3 % 2 == 0) { - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } + public float getBrightness(float var1) { + return 1.0F; + } + public int getBrightnessForRender(float var1) { + return 15728880; + } + + public AxisAlignedBB getCollisionBoundingBox() { + return null; } public void onUpdate() { @@ -209,12 +188,36 @@ public class EntityFirework { } - public int getBrightnessForRender(float var1) { - return 15728880; + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + if (!this.twinkle || this.particleAge < this.particleMaxAge / 3 + || (this.particleAge + this.particleMaxAge) / 3 % 2 == 0) { + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); + } + } - public float getBrightness(float var1) { - return 1.0F; + public void setColour(int colour) { + float f = (float) ((colour & 16711680) >> 16) / 255.0F; + float f1 = (float) ((colour & '\uff00') >> 8) / 255.0F; + float f2 = (float) ((colour & 255) >> 0) / 255.0F; + float f3 = 1.0F; + this.setRBGColorF(f * f3, f1 * f3, f2 * f3); + } + + public void setFadeColour(int faceColour) { + this.fadeColourRed = (float) ((faceColour & 16711680) >> 16) / 255.0F; + this.fadeColourGreen = (float) ((faceColour & '\uff00') >> 8) / 255.0F; + this.fadeColourBlue = (float) ((faceColour & 255) >> 0) / 255.0F; + this.hasFadeColour = true; + } + + public void setTrail(boolean trailIn) { + this.trail = trailIn; + } + + public void setTwinkle(boolean twinkleIn) { + this.twinkle = twinkleIn; } } @@ -253,8 +256,107 @@ public class EntityFirework { } - public void renderParticle(WorldRenderer var1, Entity var2, float var3, float var4, float var5, float var6, - float var7, float var8) { + private void createBall(double speed, int size, int[] colours, int[] fadeColours, boolean trail, + boolean twinkleIn) { + double d0 = this.posX; + double d1 = this.posY; + double d2 = this.posZ; + + for (int i = -size; i <= size; ++i) { + for (int j = -size; j <= size; ++j) { + for (int k = -size; k <= size; ++k) { + double d3 = (double) j + (this.rand.nextDouble() - this.rand.nextDouble()) * 0.5D; + double d4 = (double) i + (this.rand.nextDouble() - this.rand.nextDouble()) * 0.5D; + double d5 = (double) k + (this.rand.nextDouble() - this.rand.nextDouble()) * 0.5D; + double d6 = (double) MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5) / speed + + this.rand.nextGaussian() * 0.05D; + this.createParticle(d0, d1, d2, d3 / d6, d4 / d6, d5 / d6, colours, fadeColours, trail, + twinkleIn); + if (i != -size && i != size && j != -size && j != size) { + k += size * 2 - 1; + } + } + } + } + + } + + private void createBurst(int[] colours, int[] fadeColours, boolean trail, boolean twinkleIn) { + double d0 = this.rand.nextGaussian() * 0.05D; + double d1 = this.rand.nextGaussian() * 0.05D; + + for (int i = 0; i < 70; ++i) { + double d2 = this.motionX * 0.5D + this.rand.nextGaussian() * 0.15D + d0; + double d3 = this.motionZ * 0.5D + this.rand.nextGaussian() * 0.15D + d1; + double d4 = this.motionY * 0.5D + this.rand.nextDouble() * 0.5D; + this.createParticle(this.posX, this.posY, this.posZ, d2, d4, d3, colours, fadeColours, trail, + twinkleIn); + } + + } + + private void createParticle(double parDouble1, double parDouble2, double parDouble3, double parDouble4, + double parDouble5, double parDouble6, int[] parArrayOfInt, int[] parArrayOfInt2, boolean parFlag, + boolean parFlag2) { + EntityFirework.SparkFX entityfirework$sparkfx = new EntityFirework.SparkFX(this.worldObj, parDouble1, + parDouble2, parDouble3, parDouble4, parDouble5, parDouble6, this.theEffectRenderer); + entityfirework$sparkfx.setAlphaF(0.99F); + entityfirework$sparkfx.setTrail(parFlag); + entityfirework$sparkfx.setTwinkle(parFlag2); + int i = this.rand.nextInt(parArrayOfInt.length); + entityfirework$sparkfx.setColour(parArrayOfInt[i]); + if (parArrayOfInt2 != null && parArrayOfInt2.length > 0) { + entityfirework$sparkfx.setFadeColour(parArrayOfInt2[this.rand.nextInt(parArrayOfInt2.length)]); + } + + this.theEffectRenderer.addEffect(entityfirework$sparkfx); + } + + private void createShaped(double speed, double[][] shape, int[] colours, int[] fadeColours, boolean trail, + boolean twinkleIn, boolean parFlag3) { + double d0 = shape[0][0]; + double d1 = shape[0][1]; + this.createParticle(this.posX, this.posY, this.posZ, d0 * speed, d1 * speed, 0.0D, colours, fadeColours, + trail, twinkleIn); + float f = this.rand.nextFloat() * 3.1415927F; + double d2 = parFlag3 ? 0.034D : 0.34D; + + for (int i = 0; i < 3; ++i) { + double d3 = (double) f + (double) ((float) i * 3.1415927F) * d2; + double d4 = d0; + double d5 = d1; + + for (int j = 1; j < shape.length; ++j) { + double d6 = shape[j][0]; + double d7 = shape[j][1]; + + for (double d8 = 0.25D; d8 <= 1.0D; d8 += 0.25D) { + double d9 = (d4 + (d6 - d4) * d8) * speed; + double d10 = (d5 + (d7 - d5) * d8) * speed; + double d11 = d9 * Math.sin(d3); + d9 = d9 * Math.cos(d3); + + for (double d12 = -1.0D; d12 <= 1.0D; d12 += 2.0D) { + this.createParticle(this.posX, this.posY, this.posZ, d9 * d12, d10, d11 * d12, colours, + fadeColours, trail, twinkleIn); + } + } + + d4 = d6; + d5 = d7; + } + } + + } + + private boolean func_92037_i() { + Minecraft minecraft = Minecraft.getMinecraft(); + return minecraft == null || minecraft.getRenderViewEntity() == null + || minecraft.getRenderViewEntity().getDistanceSq(this.posX, this.posY, this.posZ) >= 256.0D; + } + + public int getFXLayer() { + return 0; } public void onUpdate() { @@ -336,107 +438,8 @@ public class EntityFirework { } - private boolean func_92037_i() { - Minecraft minecraft = Minecraft.getMinecraft(); - return minecraft == null || minecraft.getRenderViewEntity() == null - || minecraft.getRenderViewEntity().getDistanceSq(this.posX, this.posY, this.posZ) >= 256.0D; - } - - private void createParticle(double parDouble1, double parDouble2, double parDouble3, double parDouble4, - double parDouble5, double parDouble6, int[] parArrayOfInt, int[] parArrayOfInt2, boolean parFlag, - boolean parFlag2) { - EntityFirework.SparkFX entityfirework$sparkfx = new EntityFirework.SparkFX(this.worldObj, parDouble1, - parDouble2, parDouble3, parDouble4, parDouble5, parDouble6, this.theEffectRenderer); - entityfirework$sparkfx.setAlphaF(0.99F); - entityfirework$sparkfx.setTrail(parFlag); - entityfirework$sparkfx.setTwinkle(parFlag2); - int i = this.rand.nextInt(parArrayOfInt.length); - entityfirework$sparkfx.setColour(parArrayOfInt[i]); - if (parArrayOfInt2 != null && parArrayOfInt2.length > 0) { - entityfirework$sparkfx.setFadeColour(parArrayOfInt2[this.rand.nextInt(parArrayOfInt2.length)]); - } - - this.theEffectRenderer.addEffect(entityfirework$sparkfx); - } - - private void createBall(double speed, int size, int[] colours, int[] fadeColours, boolean trail, - boolean twinkleIn) { - double d0 = this.posX; - double d1 = this.posY; - double d2 = this.posZ; - - for (int i = -size; i <= size; ++i) { - for (int j = -size; j <= size; ++j) { - for (int k = -size; k <= size; ++k) { - double d3 = (double) j + (this.rand.nextDouble() - this.rand.nextDouble()) * 0.5D; - double d4 = (double) i + (this.rand.nextDouble() - this.rand.nextDouble()) * 0.5D; - double d5 = (double) k + (this.rand.nextDouble() - this.rand.nextDouble()) * 0.5D; - double d6 = (double) MathHelper.sqrt_double(d3 * d3 + d4 * d4 + d5 * d5) / speed - + this.rand.nextGaussian() * 0.05D; - this.createParticle(d0, d1, d2, d3 / d6, d4 / d6, d5 / d6, colours, fadeColours, trail, - twinkleIn); - if (i != -size && i != size && j != -size && j != size) { - k += size * 2 - 1; - } - } - } - } - - } - - private void createShaped(double speed, double[][] shape, int[] colours, int[] fadeColours, boolean trail, - boolean twinkleIn, boolean parFlag3) { - double d0 = shape[0][0]; - double d1 = shape[0][1]; - this.createParticle(this.posX, this.posY, this.posZ, d0 * speed, d1 * speed, 0.0D, colours, fadeColours, - trail, twinkleIn); - float f = this.rand.nextFloat() * 3.1415927F; - double d2 = parFlag3 ? 0.034D : 0.34D; - - for (int i = 0; i < 3; ++i) { - double d3 = (double) f + (double) ((float) i * 3.1415927F) * d2; - double d4 = d0; - double d5 = d1; - - for (int j = 1; j < shape.length; ++j) { - double d6 = shape[j][0]; - double d7 = shape[j][1]; - - for (double d8 = 0.25D; d8 <= 1.0D; d8 += 0.25D) { - double d9 = (d4 + (d6 - d4) * d8) * speed; - double d10 = (d5 + (d7 - d5) * d8) * speed; - double d11 = d9 * Math.sin(d3); - d9 = d9 * Math.cos(d3); - - for (double d12 = -1.0D; d12 <= 1.0D; d12 += 2.0D) { - this.createParticle(this.posX, this.posY, this.posZ, d9 * d12, d10, d11 * d12, colours, - fadeColours, trail, twinkleIn); - } - } - - d4 = d6; - d5 = d7; - } - } - - } - - private void createBurst(int[] colours, int[] fadeColours, boolean trail, boolean twinkleIn) { - double d0 = this.rand.nextGaussian() * 0.05D; - double d1 = this.rand.nextGaussian() * 0.05D; - - for (int i = 0; i < 70; ++i) { - double d2 = this.motionX * 0.5D + this.rand.nextGaussian() * 0.15D + d0; - double d3 = this.motionZ * 0.5D + this.rand.nextGaussian() * 0.15D + d1; - double d4 = this.motionY * 0.5D + this.rand.nextDouble() * 0.5D; - this.createParticle(this.posX, this.posY, this.posZ, d2, d4, d3, colours, fadeColours, trail, - twinkleIn); - } - - } - - public int getFXLayer() { - return 0; + public void renderParticle(WorldRenderer var1, Entity var2, float var3, float var4, float var5, float var6, + float var7, float var8) { } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityFishWakeFX.java b/src/game/java/net/minecraft/client/particle/EntityFishWakeFX.java index bec833e0..80627f43 100644 --- a/src/game/java/net/minecraft/client/particle/EntityFishWakeFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityFishWakeFX.java @@ -2,27 +2,37 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityFishWakeFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityFishWakeFX(world, d0, d1, d2, d3, d4, d5); + } + } + protected EntityFishWakeFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, double parDouble2, double parDouble3) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D); @@ -41,8 +51,8 @@ public class EntityFishWakeFX extends EntityFX { this.motionZ = parDouble3; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -62,11 +72,4 @@ public class EntityFishWakeFX extends EntityFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityFishWakeFX(world, d0, d1, d2, d3, d4, d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityFlameFX.java b/src/game/java/net/minecraft/client/particle/EntityFlameFX.java index 8f1d4a67..236d9352 100644 --- a/src/game/java/net/minecraft/client/particle/EntityFlameFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityFlameFX.java @@ -5,27 +5,37 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityFlameFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityFlameFX(world, d0, d1, d2, d3, d4, d5); + } + } + private float flameScale; protected EntityFlameFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, @@ -44,14 +54,14 @@ public class EntityFlameFX extends EntityFX { this.setParticleTextureIndex(48); } - /**+ - * Renders the particle + /** + * + Gets how bright this entity is. */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge; - this.particleScale = this.flameScale * (1.0F - f6 * f6 * 0.5F); - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); + public float getBrightness(float f) { + float f1 = ((float) this.particleAge + f) / (float) this.particleMaxAge; + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + float f2 = super.getBrightness(f); + return f2 * f1 + (1.0F - f1); } public int getBrightnessForRender(float f) { @@ -68,18 +78,8 @@ public class EntityFlameFX extends EntityFX { return j | k << 16; } - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float f) { - float f1 = ((float) this.particleAge + f) / (float) this.particleMaxAge; - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - float f2 = super.getBrightness(f); - return f2 * f1 + (1.0F - f1); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -100,10 +100,13 @@ public class EntityFlameFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityFlameFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge; + this.particleScale = this.flameScale * (1.0F - f6 * f6 * 0.5F); + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityFootStepFX.java b/src/game/java/net/minecraft/client/particle/EntityFootStepFX.java index 554be45c..615a293f 100644 --- a/src/game/java/net/minecraft/client/particle/EntityFootStepFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityFootStepFX.java @@ -1,6 +1,7 @@ package net.minecraft.client.particle; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; @@ -13,30 +14,41 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityFootStepFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityFootStepFX(Minecraft.getMinecraft().getTextureManager(), world, d0, d1, d2); + } + } + private static final ResourceLocation FOOTPRINT_TEXTURE = new ResourceLocation("textures/particle/footprint.png"); private int footstepAge; private int footstepMaxAge; + private TextureManager currentFootSteps; protected EntityFootStepFX(TextureManager currentFootStepsIn, World worldIn, double xCoordIn, double yCoordIn, @@ -47,8 +59,23 @@ public class EntityFootStepFX extends EntityFX { this.footstepMaxAge = 200; } - /**+ - * Renders the particle + public int getFXLayer() { + return 3; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + ++this.footstepAge; + if (this.footstepAge == this.footstepMaxAge) { + this.setDead(); + } + + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer worldrenderer, Entity var2, float f, float var4, float var5, float var6, float var7, float var8) { @@ -82,26 +109,4 @@ public class EntityFootStepFX extends EntityFX { GlStateManager.disableBlend(); GlStateManager.enableLighting(); } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - ++this.footstepAge; - if (this.footstepAge == this.footstepMaxAge) { - this.setDead(); - } - - } - - public int getFXLayer() { - return 3; - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityFootStepFX(Minecraft.getMinecraft().getTextureManager(), world, d0, d1, d2); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityHeartFX.java b/src/game/java/net/minecraft/client/particle/EntityHeartFX.java index af8a5fb3..b3f0b98c 100644 --- a/src/game/java/net/minecraft/client/particle/EntityHeartFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityHeartFX.java @@ -5,27 +5,47 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityHeartFX extends EntityFX { + public static class AngryVillagerFactory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + EntityHeartFX entityheartfx = new EntityHeartFX(world, d0, d1 + 0.5D, d2, d3, d4, d5); + entityheartfx.setParticleTextureIndex(81); + entityheartfx.setRBGColorF(1.0F, 1.0F, 1.0F); + return entityheartfx; + } + } + + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityHeartFX(world, d0, d1, d2, d3, d4, d5); + } + } + float particleScaleOverTime; protected EntityHeartFX(World worldIn, double parDouble1, double parDouble2, double parDouble3, double parDouble4, @@ -48,19 +68,8 @@ public class EntityHeartFX extends EntityFX { this.setParticleTextureIndex(80); } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.particleScaleOverTime * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -86,20 +95,14 @@ public class EntityHeartFX extends EntityFX { } - public static class AngryVillagerFactory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - EntityHeartFX entityheartfx = new EntityHeartFX(world, d0, d1 + 0.5D, d2, d3, d4, d5); - entityheartfx.setParticleTextureIndex(81); - entityheartfx.setRBGColorF(1.0F, 1.0F, 1.0F); - return entityheartfx; - } - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityHeartFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.particleScaleOverTime * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityHugeExplodeFX.java b/src/game/java/net/minecraft/client/particle/EntityHugeExplodeFX.java index 3b90692a..37a69a90 100644 --- a/src/game/java/net/minecraft/client/particle/EntityHugeExplodeFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityHugeExplodeFX.java @@ -5,30 +5,41 @@ import net.minecraft.entity.Entity; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityHugeExplodeFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityHugeExplodeFX(world, d0, d1, d2, d3, d4, d5); + } + } + private int timeSinceStart; - /**+ - * the maximum time for the explosion + + /** + * + the maximum time for the explosion */ private int maximumTime = 8; @@ -37,15 +48,12 @@ public class EntityHugeExplodeFX extends EntityFX { super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D); } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer var1, Entity var2, float var3, float var4, float var5, float var6, - float var7, float var8) { + public int getFXLayer() { + return 1; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { for (int i = 0; i < 6; ++i) { @@ -63,14 +71,10 @@ public class EntityHugeExplodeFX extends EntityFX { } - public int getFXLayer() { - return 1; - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityHugeExplodeFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer var1, Entity var2, float var3, float var4, float var5, float var6, + float var7, float var8) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityLargeExplodeFX.java b/src/game/java/net/minecraft/client/particle/EntityLargeExplodeFX.java index 7226f9e8..952e6b12 100644 --- a/src/game/java/net/minecraft/client/particle/EntityLargeExplodeFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityLargeExplodeFX.java @@ -12,31 +12,43 @@ import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityLargeExplodeFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityLargeExplodeFX(Minecraft.getMinecraft().getTextureManager(), world, d0, d1, d2, d3, d4, + d5); + } + } + private static final ResourceLocation EXPLOSION_TEXTURE = new ResourceLocation("textures/entity/explosion.png"); private int field_70581_a; private int field_70584_aq; private TextureManager theRenderEngine; + private float field_70582_as; protected EntityLargeExplodeFX(TextureManager renderEngine, World worldIn, double xCoordIn, double yCoordIn, @@ -48,8 +60,30 @@ public class EntityLargeExplodeFX extends EntityFX { this.field_70582_as = 1.0F - (float) parDouble1 * 0.5F; } - /**+ - * Renders the particle + public int getBrightnessForRender(float var1) { + return '\uf0f0'; + } + + public int getFXLayer() { + return 3; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + ++this.field_70581_a; + if (this.field_70581_a == this.field_70584_aq) { + this.setDead(); + } + + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer worldrenderer, Entity var2, float f, float f1, float f2, float f3, float f4, float f5) { @@ -93,34 +127,4 @@ public class EntityLargeExplodeFX extends EntityFX { GlStateManager.enableLighting(); } } - - public int getBrightnessForRender(float var1) { - return '\uf0f0'; - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - ++this.field_70581_a; - if (this.field_70581_a == this.field_70584_aq) { - this.setDead(); - } - - } - - public int getFXLayer() { - return 3; - } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityLargeExplodeFX(Minecraft.getMinecraft().getTextureManager(), world, d0, d1, d2, d3, d4, - d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityLavaFX.java b/src/game/java/net/minecraft/client/particle/EntityLavaFX.java index fc2b19a3..b429c075 100644 --- a/src/game/java/net/minecraft/client/particle/EntityLavaFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityLavaFX.java @@ -6,27 +6,37 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityLavaFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityLavaFX(world, d0, d1, d2); + } + } + private float lavaParticleScale; protected EntityLavaFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn) { @@ -43,6 +53,13 @@ public class EntityLavaFX extends EntityFX { this.setParticleTextureIndex(49); } + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float var1) { + return 1.0F; + } + public int getBrightnessForRender(float f) { float f1 = ((float) this.particleAge + f) / (float) this.particleMaxAge; f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); @@ -52,25 +69,8 @@ public class EntityLavaFX extends EntityFX { return short1 | j << 16; } - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float var1) { - return 1.0F; - } - - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge; - this.particleScale = this.lavaParticleScale * (1.0F - f6 * f6); - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -98,10 +98,13 @@ public class EntityLavaFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityLavaFX(world, d0, d1, d2); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge; + this.particleScale = this.lavaParticleScale * (1.0F - f6 * f6); + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityNoteFX.java b/src/game/java/net/minecraft/client/particle/EntityNoteFX.java index c8794128..3cb5be82 100644 --- a/src/game/java/net/minecraft/client/particle/EntityNoteFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityNoteFX.java @@ -5,27 +5,37 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityNoteFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityNoteFX(world, d0, d1, d2, d3, d4, d5); + } + } + float noteParticleScale; protected EntityNoteFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, @@ -51,19 +61,8 @@ public class EntityNoteFX extends EntityFX { this.setParticleTextureIndex(64); } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.noteParticleScale * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -89,10 +88,14 @@ public class EntityNoteFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityNoteFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.noteParticleScale * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityParticleEmitter.java b/src/game/java/net/minecraft/client/particle/EntityParticleEmitter.java index adf8f477..52df3e3e 100644 --- a/src/game/java/net/minecraft/client/particle/EntityParticleEmitter.java +++ b/src/game/java/net/minecraft/client/particle/EntityParticleEmitter.java @@ -5,22 +5,25 @@ import net.minecraft.entity.Entity; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,15 +43,12 @@ public class EntityParticleEmitter extends EntityFX { this.onUpdate(); } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer var1, Entity var2, float var3, float var4, float var5, float var6, - float var7, float var8) { + public int getFXLayer() { + return 3; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { for (int i = 0; i < 16; ++i) { @@ -72,7 +72,10 @@ public class EntityParticleEmitter extends EntityFX { } - public int getFXLayer() { - return 3; + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer var1, Entity var2, float var3, float var4, float var5, float var6, + float var7, float var8) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityPickupFX.java b/src/game/java/net/minecraft/client/particle/EntityPickupFX.java index ae313d6c..7176a0ff 100644 --- a/src/game/java/net/minecraft/client/particle/EntityPickupFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityPickupFX.java @@ -8,22 +8,25 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.Entity; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,8 +48,23 @@ public class EntityPickupFX extends EntityFX { this.field_174841_aA = parFloat1; } - /**+ - * Renders the particle + public int getFXLayer() { + return 3; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + ++this.age; + if (this.age == this.maxAge) { + this.setDead(); + } + + } + + /** + * + Renders the particle */ public void renderParticle(WorldRenderer var1, Entity var2, float f, float var4, float var5, float var6, float var7, float var8) { @@ -76,19 +94,4 @@ public class EntityPickupFX extends EntityFX { this.field_174842_aB.renderEntityWithPosYaw(this.field_174840_a, (double) ((float) d6), (double) ((float) d7), (double) ((float) d8), this.field_174840_a.rotationYaw, f); } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - ++this.age; - if (this.age == this.maxAge) { - this.setDead(); - } - - } - - public int getFXLayer() { - return 3; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityPortalFX.java b/src/game/java/net/minecraft/client/particle/EntityPortalFX.java index 52d12e25..8299282e 100644 --- a/src/game/java/net/minecraft/client/particle/EntityPortalFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityPortalFX.java @@ -4,30 +4,41 @@ import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.minecraft.entity.Entity; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityPortalFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityPortalFX(world, d0, d1, d2, d3, d4, d5); + } + } + private float portalParticleScale; private double portalPosX; private double portalPosY; + private double portalPosZ; protected EntityPortalFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, @@ -49,17 +60,14 @@ public class EntityPortalFX extends EntityFX { this.setParticleTextureIndex((int) (Math.random() * 8.0D)); } - /**+ - * Renders the particle + /** + * + Gets how bright this entity is. */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge; - f6 = 1.0F - f6; - f6 = f6 * f6; - f6 = 1.0F - f6; - this.particleScale = this.portalParticleScale * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); + public float getBrightness(float f) { + float f1 = super.getBrightness(f); + float f2 = (float) this.particleAge / (float) this.particleMaxAge; + f2 = f2 * f2 * f2 * f2; + return f1 * (1.0F - f2) + f2; } public int getBrightnessForRender(float f) { @@ -77,18 +85,8 @@ public class EntityPortalFX extends EntityFX { return j | k << 16; } - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float f) { - float f1 = super.getBrightness(f); - float f2 = (float) this.particleAge / (float) this.particleMaxAge; - f2 = f2 * f2 * f2 * f2; - return f1 * (1.0F - f2) + f2; - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -106,10 +104,16 @@ public class EntityPortalFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityPortalFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge; + f6 = 1.0F - f6; + f6 = f6 * f6; + f6 = 1.0F - f6; + this.particleScale = this.portalParticleScale * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityRainFX.java b/src/game/java/net/minecraft/client/particle/EntityRainFX.java index be598142..6a4dcdd7 100644 --- a/src/game/java/net/minecraft/client/particle/EntityRainFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityRainFX.java @@ -8,27 +8,37 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityRainFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new EntityRainFX(world, d0, d1, d2); + } + } + protected EntityRainFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D); this.motionX *= 0.30000001192092896D; @@ -43,8 +53,8 @@ public class EntityRainFX extends EntityFX { this.particleMaxAge = (int) (8.0D / (Math.random() * 0.8D + 0.2D)); } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -89,11 +99,4 @@ public class EntityRainFX extends EntityFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new EntityRainFX(world, d0, d1, d2); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntityReddustFX.java b/src/game/java/net/minecraft/client/particle/EntityReddustFX.java index 9f1ce0a9..76a46bb6 100644 --- a/src/game/java/net/minecraft/client/particle/EntityReddustFX.java +++ b/src/game/java/net/minecraft/client/particle/EntityReddustFX.java @@ -5,27 +5,37 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityReddustFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntityReddustFX(world, d0, d1, d2, (float) d3, (float) d4, (float) d5); + } + } + float reddustParticleScale; protected EntityReddustFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, float parFloat1, @@ -55,19 +65,8 @@ public class EntityReddustFX extends EntityFX { this.noClip = false; } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.reddustParticleScale * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -94,10 +93,14 @@ public class EntityReddustFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntityReddustFX(world, d0, d1, d2, (float) d3, (float) d4, (float) d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.reddustParticleScale * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntitySmokeFX.java b/src/game/java/net/minecraft/client/particle/EntitySmokeFX.java index 48f0ebf1..6f955cb2 100644 --- a/src/game/java/net/minecraft/client/particle/EntitySmokeFX.java +++ b/src/game/java/net/minecraft/client/particle/EntitySmokeFX.java @@ -5,27 +5,37 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySmokeFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntitySmokeFX(world, d0, d1, d2, d3, d4, d5); + } + } + float smokeParticleScale; private EntitySmokeFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, @@ -51,19 +61,8 @@ public class EntitySmokeFX extends EntityFX { this.noClip = false; } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.smokeParticleScale * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -91,10 +90,14 @@ public class EntitySmokeFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntitySmokeFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.smokeParticleScale * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntitySnowShovelFX.java b/src/game/java/net/minecraft/client/particle/EntitySnowShovelFX.java index 7eae99fe..89ac6567 100644 --- a/src/game/java/net/minecraft/client/particle/EntitySnowShovelFX.java +++ b/src/game/java/net/minecraft/client/particle/EntitySnowShovelFX.java @@ -5,27 +5,37 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySnowShovelFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntitySnowShovelFX(world, d0, d1, d2, d3, d4, d5); + } + } + float snowDigParticleScale; protected EntitySnowShovelFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, @@ -52,19 +62,8 @@ public class EntitySnowShovelFX extends EntityFX { this.noClip = false; } - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - this.particleScale = this.snowDigParticleScale * f6; - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -87,10 +86,14 @@ public class EntitySnowShovelFX extends EntityFX { } - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntitySnowShovelFX(world, d0, d1, d2, d3, d4, d5); - } + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + this.particleScale = this.snowDigParticleScale * f6; + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntitySpellParticleFX.java b/src/game/java/net/minecraft/client/particle/EntitySpellParticleFX.java index 5e8f978b..a2c66a42 100644 --- a/src/game/java/net/minecraft/client/particle/EntitySpellParticleFX.java +++ b/src/game/java/net/minecraft/client/particle/EntitySpellParticleFX.java @@ -6,94 +6,30 @@ import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySpellParticleFX extends EntityFX { - private static final EaglercraftRandom RANDOM = new EaglercraftRandom(); - /**+ - * Base spell texture index - */ - private int baseSpellTextureIndex = 128; - - protected EntitySpellParticleFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, - double parDouble2, double parDouble3) { - super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.5D - RANDOM.nextDouble(), parDouble2, - 0.5D - RANDOM.nextDouble()); - this.motionY *= 0.20000000298023224D; - if (parDouble1 == 0.0D && parDouble3 == 0.0D) { - this.motionX *= 0.10000000149011612D; - this.motionZ *= 0.10000000149011612D; - } - - this.particleScale *= 0.75F; - this.particleMaxAge = (int) (8.0D / (Math.random() * 0.8D + 0.2D)); - this.noClip = false; - } - - /**+ - * Renders the particle - */ - public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, - float f4, float f5) { - float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; - f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); - super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - if (this.particleAge++ >= this.particleMaxAge) { - this.setDead(); - } - - this.setParticleTextureIndex(this.baseSpellTextureIndex + (7 - this.particleAge * 8 / this.particleMaxAge)); - this.motionY += 0.004D; - this.moveEntity(this.motionX, this.motionY, this.motionZ); - if (this.posY == this.prevPosY) { - this.motionX *= 1.1D; - this.motionZ *= 1.1D; - } - - this.motionX *= 0.9599999785423279D; - this.motionY *= 0.9599999785423279D; - this.motionZ *= 0.9599999785423279D; - if (this.onGround) { - this.motionX *= 0.699999988079071D; - this.motionZ *= 0.699999988079071D; - } - - } - - /**+ - * Sets the base spell texture index - */ - public void setBaseSpellTextureIndex(int baseSpellTextureIndexIn) { - this.baseSpellTextureIndex = baseSpellTextureIndexIn; - } - public static class AmbientMobFactory implements IParticleFactory { public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, double d5, int... var15) { @@ -139,4 +75,72 @@ public class EntitySpellParticleFX extends EntityFX { return entityspellparticlefx; } } + + private static final EaglercraftRandom RANDOM = new EaglercraftRandom(); + + /** + * + Base spell texture index + */ + private int baseSpellTextureIndex = 128; + + protected EntitySpellParticleFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double parDouble1, + double parDouble2, double parDouble3) { + super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.5D - RANDOM.nextDouble(), parDouble2, + 0.5D - RANDOM.nextDouble()); + this.motionY *= 0.20000000298023224D; + if (parDouble1 == 0.0D && parDouble3 == 0.0D) { + this.motionX *= 0.10000000149011612D; + this.motionZ *= 0.10000000149011612D; + } + + this.particleScale *= 0.75F; + this.particleMaxAge = (int) (8.0D / (Math.random() * 0.8D + 0.2D)); + this.noClip = false; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + if (this.particleAge++ >= this.particleMaxAge) { + this.setDead(); + } + + this.setParticleTextureIndex(this.baseSpellTextureIndex + (7 - this.particleAge * 8 / this.particleMaxAge)); + this.motionY += 0.004D; + this.moveEntity(this.motionX, this.motionY, this.motionZ); + if (this.posY == this.prevPosY) { + this.motionX *= 1.1D; + this.motionZ *= 1.1D; + } + + this.motionX *= 0.9599999785423279D; + this.motionY *= 0.9599999785423279D; + this.motionZ *= 0.9599999785423279D; + if (this.onGround) { + this.motionX *= 0.699999988079071D; + this.motionZ *= 0.699999988079071D; + } + + } + + /** + * + Renders the particle + */ + public void renderParticle(WorldRenderer worldrenderer, Entity entity, float f, float f1, float f2, float f3, + float f4, float f5) { + float f6 = ((float) this.particleAge + f) / (float) this.particleMaxAge * 32.0F; + f6 = MathHelper.clamp_float(f6, 0.0F, 1.0F); + super.renderParticle(worldrenderer, entity, f, f1, f2, f3, f4, f5); + } + + /** + * + Sets the base spell texture index + */ + public void setBaseSpellTextureIndex(int baseSpellTextureIndexIn) { + this.baseSpellTextureIndex = baseSpellTextureIndexIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntitySplashFX.java b/src/game/java/net/minecraft/client/particle/EntitySplashFX.java index 5f6c11f2..4cf29382 100644 --- a/src/game/java/net/minecraft/client/particle/EntitySplashFX.java +++ b/src/game/java/net/minecraft/client/particle/EntitySplashFX.java @@ -2,27 +2,37 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySplashFX extends EntityRainFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntitySplashFX(world, d0, d1, d2, d3, d4, d5); + } + } + protected EntitySplashFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { super(worldIn, xCoordIn, yCoordIn, zCoordIn); @@ -35,11 +45,4 @@ public class EntitySplashFX extends EntityRainFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntitySplashFX(world, d0, d1, d2, d3, d4, d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/EntitySuspendFX.java b/src/game/java/net/minecraft/client/particle/EntitySuspendFX.java index 61c7da55..a97f12dc 100644 --- a/src/game/java/net/minecraft/client/particle/EntitySuspendFX.java +++ b/src/game/java/net/minecraft/client/particle/EntitySuspendFX.java @@ -4,27 +4,37 @@ import net.minecraft.block.material.Material; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySuspendFX extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, + double d5, int... var15) { + return new EntitySuspendFX(world, d0, d1, d2, d3, d4, d5); + } + } + protected EntitySuspendFX(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn) { super(worldIn, xCoordIn, yCoordIn - 0.125D, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); @@ -40,8 +50,8 @@ public class EntitySuspendFX extends EntityFX { this.particleMaxAge = (int) (16.0D / (Math.random() * 0.8D + 0.2D)); } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -57,11 +67,4 @@ public class EntitySuspendFX extends EntityFX { } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double d3, double d4, - double d5, int... var15) { - return new EntitySuspendFX(world, d0, d1, d2, d3, d4, d5); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/particle/IParticleFactory.java b/src/game/java/net/minecraft/client/particle/IParticleFactory.java index bbe3aa11..efd92c40 100644 --- a/src/game/java/net/minecraft/client/particle/IParticleFactory.java +++ b/src/game/java/net/minecraft/client/particle/IParticleFactory.java @@ -2,22 +2,25 @@ package net.minecraft.client.particle; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/particle/MobAppearance.java b/src/game/java/net/minecraft/client/particle/MobAppearance.java index b6eb958b..1cacfb32 100644 --- a/src/game/java/net/minecraft/client/particle/MobAppearance.java +++ b/src/game/java/net/minecraft/client/particle/MobAppearance.java @@ -1,6 +1,7 @@ package net.minecraft.client.particle; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.OpenGlHelper; @@ -13,27 +14,37 @@ import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MobAppearance extends EntityFX { + public static class Factory implements IParticleFactory { + public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, + double var13, int... var15) { + return new MobAppearance(world, d0, d1, d2); + } + } + private EntityLivingBase entity; protected MobAppearance(World worldIn, double xCoordIn, double yCoordIn, double zCoordIn) { @@ -48,8 +59,8 @@ public class MobAppearance extends EntityFX { return 3; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -61,8 +72,8 @@ public class MobAppearance extends EntityFX { } - /**+ - * Renders the particle + /** + * + Renders the particle */ public void renderParticle(WorldRenderer var1, Entity entityx, float f, float var4, float var5, float var6, float var7, float var8) { @@ -92,11 +103,4 @@ public class MobAppearance extends EntityFX { GlStateManager.enableDepth(); } } - - public static class Factory implements IParticleFactory { - public EntityFX getEntityFX(int var1, World world, double d0, double d1, double d2, double var9, double var11, - double var13, int... var15) { - return new MobAppearance(world, d0, d1, d2); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/player/inventory/ContainerLocalMenu.java b/src/game/java/net/minecraft/client/player/inventory/ContainerLocalMenu.java index f4a029fc..728f10b9 100644 --- a/src/game/java/net/minecraft/client/player/inventory/ContainerLocalMenu.java +++ b/src/game/java/net/minecraft/client/player/inventory/ContainerLocalMenu.java @@ -12,22 +12,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,36 +44,36 @@ public class ContainerLocalMenu extends InventoryBasic implements ILockableConta this.guiID = id; } + public Container createContainer(InventoryPlayer var1, EntityPlayer var2) { + throw new UnsupportedOperationException(); + } + public int getField(int i) { return this.field_174895_b.containsKey(Integer.valueOf(i)) ? ((Integer) this.field_174895_b.get(Integer.valueOf(i))).intValue() : 0; } - public void setField(int i, int j) { - this.field_174895_b.put(Integer.valueOf(i), Integer.valueOf(j)); - } - public int getFieldCount() { return this.field_174895_b.size(); } - public boolean isLocked() { - return false; - } - - public void setLockCode(LockCode var1) { - } - - public LockCode getLockCode() { - return LockCode.EMPTY_CODE; - } - public String getGuiID() { return this.guiID; } - public Container createContainer(InventoryPlayer var1, EntityPlayer var2) { - throw new UnsupportedOperationException(); + public LockCode getLockCode() { + return LockCode.EMPTY_CODE; + } + + public boolean isLocked() { + return false; + } + + public void setField(int i, int j) { + this.field_174895_b.put(Integer.valueOf(i), Integer.valueOf(j)); + } + + public void setLockCode(LockCode var1) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/player/inventory/LocalBlockIntercommunication.java b/src/game/java/net/minecraft/client/player/inventory/LocalBlockIntercommunication.java index d18cdbaa..b0b5fc73 100644 --- a/src/game/java/net/minecraft/client/player/inventory/LocalBlockIntercommunication.java +++ b/src/game/java/net/minecraft/client/player/inventory/LocalBlockIntercommunication.java @@ -6,22 +6,25 @@ import net.minecraft.inventory.Container; import net.minecraft.util.IChatComponent; import net.minecraft.world.IInteractionObject; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,30 +42,30 @@ public class LocalBlockIntercommunication implements IInteractionObject { throw new UnsupportedOperationException(); } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat */ - public String getName() { - return this.displayName.getUnformattedText(); - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return true; + public IChatComponent getDisplayName() { + return this.displayName; } public String getGuiID() { return this.guiID; } - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ - public IChatComponent getDisplayName() { - return this.displayName; + public String getName() { + return this.displayName.getUnformattedText(); + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/ActiveRenderInfo.java b/src/game/java/net/minecraft/client/renderer/ActiveRenderInfo.java index 323ab3dd..e91550d7 100644 --- a/src/game/java/net/minecraft/client/renderer/ActiveRenderInfo.java +++ b/src/game/java/net/minecraft/client/renderer/ActiveRenderInfo.java @@ -1,6 +1,8 @@ package net.minecraft.client.renderer; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VIEWPORT; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -14,41 +16,44 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ActiveRenderInfo { - /**+ - * The current GL viewport + /** + * + The current GL viewport */ private static final int[] VIEWPORT = new int[4]; - /**+ - * The current GL modelview matrix + /** + * + The current GL modelview matrix */ private static final float[] MODELVIEW = new float[16]; - /**+ - * The current GL projection matrix + /** + * + The current GL projection matrix */ private static final float[] PROJECTION = new float[16]; - /**+ - * The computed view object coordinates + /** + * + The computed view object coordinates */ private static final float[] OBJECTCOORDS = new float[3]; private static Vec3 position = new Vec3(0.0D, 0.0D, 0.0D); @@ -58,38 +63,6 @@ public class ActiveRenderInfo { private static float rotationYZ; private static float rotationXY; - /**+ - * Updates the current render info and camera location based on - * entity look angles and 1st/3rd person view mode - */ - public static void updateRenderInfo(EntityPlayer entityplayerIn, boolean parFlag) { - GlStateManager.getFloat(GL_MODELVIEW_MATRIX, MODELVIEW); - GlStateManager.getFloat(GL_PROJECTION_MATRIX, PROJECTION); - EaglercraftGPU.glGetInteger(GL_VIEWPORT, VIEWPORT); - float f = (float) ((VIEWPORT[0] + VIEWPORT[2]) / 2); - float f1 = (float) ((VIEWPORT[1] + VIEWPORT[3]) / 2); - GlStateManager.gluUnProject(f, f1, 0.0F, MODELVIEW, PROJECTION, VIEWPORT, OBJECTCOORDS); - position = new Vec3((double) OBJECTCOORDS[0], (double) OBJECTCOORDS[1], (double) OBJECTCOORDS[2]); - int i = parFlag ? 1 : 0; - float f2 = entityplayerIn.rotationPitch; - float f3 = entityplayerIn.rotationYaw; - rotationX = MathHelper.cos(f3 * 3.1415927F / 180.0F) * (float) (1 - i * 2); - rotationZ = MathHelper.sin(f3 * 3.1415927F / 180.0F) * (float) (1 - i * 2); - rotationYZ = -rotationZ * MathHelper.sin(f2 * 3.1415927F / 180.0F) * (float) (1 - i * 2); - rotationXY = rotationX * MathHelper.sin(f2 * 3.1415927F / 180.0F) * (float) (1 - i * 2); - rotationXZ = MathHelper.cos(f2 * 3.1415927F / 180.0F); - } - - public static Vec3 projectViewFromEntity(Entity parEntity, double parDouble1) { - double d0 = parEntity.prevPosX + (parEntity.posX - parEntity.prevPosX) * parDouble1; - double d1 = parEntity.prevPosY + (parEntity.posY - parEntity.prevPosY) * parDouble1 + parEntity.getEyeHeight(); - double d2 = parEntity.prevPosZ + (parEntity.posZ - parEntity.prevPosZ) * parDouble1; - double d3 = d0 + position.xCoord; - double d4 = d1 + position.yCoord; - double d5 = d2 + position.zCoord; - return new Vec3(d3, d4, d5); - } - public static Block getBlockAtEntityViewpoint(World worldIn, Entity parEntity, float parFloat1) { Vec3 vec3 = projectViewFromEntity(parEntity, (double) parFloat1); BlockPos blockpos = new BlockPos(vec3); @@ -119,19 +92,51 @@ public class ActiveRenderInfo { return rotationX; } - public static float getRotationXZ() { - return rotationXZ; + public static float getRotationXY() { + return rotationXY; } - public static float getRotationZ() { - return rotationZ; + public static float getRotationXZ() { + return rotationXZ; } public static float getRotationYZ() { return rotationYZ; } - public static float getRotationXY() { - return rotationXY; + public static float getRotationZ() { + return rotationZ; + } + + public static Vec3 projectViewFromEntity(Entity parEntity, double parDouble1) { + double d0 = parEntity.prevPosX + (parEntity.posX - parEntity.prevPosX) * parDouble1; + double d1 = parEntity.prevPosY + (parEntity.posY - parEntity.prevPosY) * parDouble1 + parEntity.getEyeHeight(); + double d2 = parEntity.prevPosZ + (parEntity.posZ - parEntity.prevPosZ) * parDouble1; + double d3 = d0 + position.xCoord; + double d4 = d1 + position.yCoord; + double d5 = d2 + position.zCoord; + return new Vec3(d3, d4, d5); + } + + /** + * + Updates the current render info and camera location based on entity look + * angles and 1st/3rd person view mode + */ + public static void updateRenderInfo(EntityPlayer entityplayerIn, boolean parFlag) { + GlStateManager.getFloat(GL_MODELVIEW_MATRIX, MODELVIEW); + GlStateManager.getFloat(GL_PROJECTION_MATRIX, PROJECTION); + EaglercraftGPU.glGetInteger(GL_VIEWPORT, VIEWPORT); + float f = (float) ((VIEWPORT[0] + VIEWPORT[2]) / 2); + float f1 = (float) ((VIEWPORT[1] + VIEWPORT[3]) / 2); + GlStateManager.gluUnProject(f, f1, 0.0F, MODELVIEW, PROJECTION, VIEWPORT, OBJECTCOORDS); + position = new Vec3((double) OBJECTCOORDS[0], (double) OBJECTCOORDS[1], (double) OBJECTCOORDS[2]); + int i = parFlag ? 1 : 0; + float f2 = entityplayerIn.rotationPitch; + float f3 = entityplayerIn.rotationYaw; + rotationX = MathHelper.cos(f3 * 3.1415927F / 180.0F) * (float) (1 - i * 2); + rotationZ = MathHelper.sin(f3 * 3.1415927F / 180.0F) * (float) (1 - i * 2); + rotationYZ = -rotationZ * MathHelper.sin(f2 * 3.1415927F / 180.0F) * (float) (1 - i * 2); + rotationXY = rotationX * MathHelper.sin(f2 * 3.1415927F / 180.0F) * (float) (1 - i * 2); + rotationXZ = MathHelper.cos(f2 * 3.1415927F / 180.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/BlockFluidRenderer.java b/src/game/java/net/minecraft/client/renderer/BlockFluidRenderer.java index e69e9b6d..9f355f49 100644 --- a/src/game/java/net/minecraft/client/renderer/BlockFluidRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/BlockFluidRenderer.java @@ -16,22 +16,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +47,38 @@ public class BlockFluidRenderer { this.initAtlasSprites(); } + private float getFluidHeight(IBlockAccess blockAccess, BlockPos blockPosIn, Material blockMaterial) { + int i = 0; + float f = 0.0F; + + for (int j = 0; j < 4; ++j) { + BlockPos blockpos = blockPosIn.add(-(j & 1), 0, -(j >> 1 & 1)); + if (blockAccess.getBlockState(blockpos.up()).getBlock().getMaterial() == blockMaterial) { + return 1.0F; + } + + IBlockState iblockstate = blockAccess.getBlockState(blockpos); + Material material = iblockstate.getBlock().getMaterial(); + if (material != blockMaterial) { + if (!material.isSolid()) { + ++f; + ++i; + } + } else { + int k = ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue(); + if (k >= 8 || k == 0) { + f += BlockLiquid.getLiquidHeightPercent(k) * 10.0F; + i += 10; + } + + f += BlockLiquid.getLiquidHeightPercent(k); + ++i; + } + } + + return 1.0F - f / (float) i; + } + protected void initAtlasSprites() { TextureMap texturemap = Minecraft.getMinecraft().getTextureMapBlocks(); this.atlasSpritesLava[0] = texturemap.getAtlasSprite("minecraft:blocks/lava_still"); @@ -294,36 +329,4 @@ public class BlockFluidRenderer { return flag2; } } - - private float getFluidHeight(IBlockAccess blockAccess, BlockPos blockPosIn, Material blockMaterial) { - int i = 0; - float f = 0.0F; - - for (int j = 0; j < 4; ++j) { - BlockPos blockpos = blockPosIn.add(-(j & 1), 0, -(j >> 1 & 1)); - if (blockAccess.getBlockState(blockpos.up()).getBlock().getMaterial() == blockMaterial) { - return 1.0F; - } - - IBlockState iblockstate = blockAccess.getBlockState(blockpos); - Material material = iblockstate.getBlock().getMaterial(); - if (material != blockMaterial) { - if (!material.isSolid()) { - ++f; - ++i; - } - } else { - int k = ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue(); - if (k >= 8 || k == 0) { - f += BlockLiquid.getLiquidHeightPercent(k) * 10.0F; - i += 10; - } - - f += BlockLiquid.getLiquidHeightPercent(k); - ++i; - } - } - - return 1.0F - f / (float) i; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/BlockModelRenderer.java b/src/game/java/net/minecraft/client/renderer/BlockModelRenderer.java index 7361bd07..5078c4d5 100644 --- a/src/game/java/net/minecraft/client/renderer/BlockModelRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/BlockModelRenderer.java @@ -24,474 +24,30 @@ import net.minecraft.util.ReportedException; import net.minecraft.util.Vec3i; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockModelRenderer { - public boolean renderModel(IBlockAccess blockAccessIn, IBakedModel modelIn, IBlockState blockStateIn, - BlockPos blockPosIn, WorldRenderer worldRendererIn) { - Block block = blockStateIn.getBlock(); - block.setBlockBoundsBasedOnState(blockAccessIn, blockPosIn); - return this.renderModel(blockAccessIn, modelIn, blockStateIn, blockPosIn, worldRendererIn, true); - } - - public boolean renderModel(IBlockAccess blockAccessIn, IBakedModel modelIn, IBlockState blockStateIn, - BlockPos blockPosIn, WorldRenderer worldRendererIn, boolean checkSides) { - boolean flag = Minecraft.isAmbientOcclusionEnabled() && blockStateIn.getBlock().getLightValue() == 0 - && modelIn.isAmbientOcclusion(); - - try { - Block block = blockStateIn.getBlock(); - return flag - ? this.renderModelAmbientOcclusion(blockAccessIn, modelIn, block, blockPosIn, worldRendererIn, - checkSides) - : this.renderModelStandard(blockAccessIn, modelIn, block, blockPosIn, worldRendererIn, checkSides); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Tesselating block model"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block model being tesselated"); - CrashReportCategory.addBlockInfo(crashreportcategory, blockPosIn, blockStateIn); - crashreportcategory.addCrashSection("Using AO", Boolean.valueOf(flag)); - throw new ReportedException(crashreport); - } - } - - public boolean renderModelAmbientOcclusion(IBlockAccess blockAccessIn, IBakedModel modelIn, Block blockIn, - BlockPos blockPosIn, WorldRenderer worldRendererIn, boolean checkSides) { - boolean flag = false; - float[] afloat = new float[EnumFacing._VALUES.length * 2]; - BitSet bitset = new BitSet(3); - BlockModelRenderer.AmbientOcclusionFace blockmodelrenderer$ambientocclusionface = new BlockModelRenderer.AmbientOcclusionFace(); - - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - List list = modelIn.getFaceQuads(enumfacing); - if (!list.isEmpty()) { - BlockPos blockpos = blockPosIn.offset(enumfacing); - if (!checkSides || blockIn.shouldSideBeRendered(blockAccessIn, blockpos, enumfacing)) { - this.renderModelAmbientOcclusionQuads(blockAccessIn, blockIn, blockPosIn, worldRendererIn, list, - afloat, bitset, blockmodelrenderer$ambientocclusionface); - flag = true; - } - } - } - - List list1 = modelIn.getGeneralQuads(); - if (list1.size() > 0) { - this.renderModelAmbientOcclusionQuads(blockAccessIn, blockIn, blockPosIn, worldRendererIn, list1, afloat, - bitset, blockmodelrenderer$ambientocclusionface); - flag = true; - } - - return flag; - } - - public boolean renderModelStandard(IBlockAccess blockAccessIn, IBakedModel modelIn, Block blockIn, - BlockPos blockPosIn, WorldRenderer worldRendererIn, boolean checkSides) { - boolean isDeferred = DeferredStateManager.isDeferredRenderer(); - boolean flag = false; - float[] afloat = isDeferred ? new float[EnumFacing._VALUES.length * 2] : null; - BitSet bitset = new BitSet(3); - - BlockPos.MutableBlockPos pointer = new BlockPos.MutableBlockPos(); - EnumFacing[] facings = EnumFacing._VALUES; - for (int m = 0; m < facings.length; ++m) { - EnumFacing enumfacing = facings[m]; - List list = modelIn.getFaceQuads(enumfacing); - if (!list.isEmpty()) { - BlockPos blockpos = blockPosIn.offsetEvenFaster(enumfacing, pointer); - if (!checkSides || blockIn.shouldSideBeRendered(blockAccessIn, blockpos, enumfacing)) { - int i = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos); - this.renderModelStandardQuads(blockAccessIn, blockIn, blockPosIn, enumfacing, i, false, - worldRendererIn, list, bitset, afloat); - flag = true; - } - } - } - - List list1 = modelIn.getGeneralQuads(); - if (list1.size() > 0) { - this.renderModelStandardQuads(blockAccessIn, blockIn, blockPosIn, (EnumFacing) null, -1, true, - worldRendererIn, list1, bitset, afloat); - flag = true; - } - - return flag; - } - - private void renderModelAmbientOcclusionQuads(IBlockAccess blockAccessIn, Block blockIn, BlockPos blockPosIn, - WorldRenderer worldRendererIn, List listQuadsIn, float[] quadBounds, BitSet boundsFlags, - BlockModelRenderer.AmbientOcclusionFace aoFaceIn) { - boolean isDeferred = DeferredStateManager.isDeferredRenderer(); - boolean isDynamicLights = isDeferred || DynamicLightsStateManager.isDynamicLightsRender(); - double d0 = (double) blockPosIn.getX(); - double d1 = (double) blockPosIn.getY(); - double d2 = (double) blockPosIn.getZ(); - Block.EnumOffsetType block$enumoffsettype = blockIn.getOffsetType(); - if (block$enumoffsettype != Block.EnumOffsetType.NONE) { - long i = MathHelper.getPositionRandom(blockPosIn); - d0 += ((double) ((float) (i >> 16 & 15L) / 15.0F) - 0.5D) * 0.5D; - d2 += ((double) ((float) (i >> 24 & 15L) / 15.0F) - 0.5D) * 0.5D; - if (!isDeferred && block$enumoffsettype == Block.EnumOffsetType.XYZ) { - d1 += ((double) ((float) (i >> 20 & 15L) / 15.0F) - 1.0D) * 0.2D; - } - } - - for (int i = 0, l = listQuadsIn.size(); i < l; ++i) { - BakedQuad bakedquad = listQuadsIn.get(i); - int[] vertData = isDynamicLights ? bakedquad.getVertexDataWithNormals() : bakedquad.getVertexData(); - this.fillQuadBounds(blockIn, vertData, bakedquad.getFace(), quadBounds, boundsFlags, - isDynamicLights ? 8 : 7); - aoFaceIn.updateVertexBrightness(blockAccessIn, blockIn, blockPosIn, bakedquad.getFace(), quadBounds, - boundsFlags); - worldRendererIn.addVertexData(vertData); - worldRendererIn.putBrightness4(aoFaceIn.vertexBrightness[0], aoFaceIn.vertexBrightness[1], - aoFaceIn.vertexBrightness[2], aoFaceIn.vertexBrightness[3]); - if (bakedquad.hasTintIndex()) { - int j = blockIn.colorMultiplier(blockAccessIn, blockPosIn, bakedquad.getTintIndex()); - if (EntityRenderer.anaglyphEnable) { - j = TextureUtil.anaglyphColor(j); - } - - float f = (float) (j >> 16 & 255) / 255.0F; - float f1 = (float) (j >> 8 & 255) / 255.0F; - float f2 = (float) (j & 255) / 255.0F; - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[0] * f, - aoFaceIn.vertexColorMultiplier[0] * f1, aoFaceIn.vertexColorMultiplier[0] * f2, 4); - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[1] * f, - aoFaceIn.vertexColorMultiplier[1] * f1, aoFaceIn.vertexColorMultiplier[1] * f2, 3); - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[2] * f, - aoFaceIn.vertexColorMultiplier[2] * f1, aoFaceIn.vertexColorMultiplier[2] * f2, 2); - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[3] * f, - aoFaceIn.vertexColorMultiplier[3] * f1, aoFaceIn.vertexColorMultiplier[3] * f2, 1); - } else { - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[0], aoFaceIn.vertexColorMultiplier[0], - aoFaceIn.vertexColorMultiplier[0], 4); - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[1], aoFaceIn.vertexColorMultiplier[1], - aoFaceIn.vertexColorMultiplier[1], 3); - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[2], aoFaceIn.vertexColorMultiplier[2], - aoFaceIn.vertexColorMultiplier[2], 2); - worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[3], aoFaceIn.vertexColorMultiplier[3], - aoFaceIn.vertexColorMultiplier[3], 1); - } - - worldRendererIn.putPosition(d0, d1, d2); - } - - } - - private void fillQuadBounds(Block blockIn, int[] vertexData, EnumFacing facingIn, float[] quadBounds, - BitSet boundsFlags, int deferredStrideOverride) { - float f = 32.0F; - float f1 = 32.0F; - float f2 = 32.0F; - float f3 = -32.0F; - float f4 = -32.0F; - float f5 = -32.0F; - - for (int i = 0; i < 4; ++i) { - int j = i * deferredStrideOverride; - float f6 = Float.intBitsToFloat(vertexData[j]); - float f7 = Float.intBitsToFloat(vertexData[j + 1]); - float f8 = Float.intBitsToFloat(vertexData[j + 2]); - f = Math.min(f, f6); - f1 = Math.min(f1, f7); - f2 = Math.min(f2, f8); - f3 = Math.max(f3, f6); - f4 = Math.max(f4, f7); - f5 = Math.max(f5, f8); - } - - if (quadBounds != null) { - quadBounds[EnumFacing.WEST.getIndex()] = f; - quadBounds[EnumFacing.EAST.getIndex()] = f3; - quadBounds[EnumFacing.DOWN.getIndex()] = f1; - quadBounds[EnumFacing.UP.getIndex()] = f4; - quadBounds[EnumFacing.NORTH.getIndex()] = f2; - quadBounds[EnumFacing.SOUTH.getIndex()] = f5; - quadBounds[EnumFacing.WEST.getIndex() + EnumFacing._VALUES.length] = 1.0F - f; - quadBounds[EnumFacing.EAST.getIndex() + EnumFacing._VALUES.length] = 1.0F - f3; - quadBounds[EnumFacing.DOWN.getIndex() + EnumFacing._VALUES.length] = 1.0F - f1; - quadBounds[EnumFacing.UP.getIndex() + EnumFacing._VALUES.length] = 1.0F - f4; - quadBounds[EnumFacing.NORTH.getIndex() + EnumFacing._VALUES.length] = 1.0F - f2; - quadBounds[EnumFacing.SOUTH.getIndex() + EnumFacing._VALUES.length] = 1.0F - f5; - } - - float f9 = 1.0E-4F; - float f10 = 0.9999F; - switch (facingIn) { - case DOWN: - boundsFlags.set(1, f >= 1.0E-4F || f2 >= 1.0E-4F || f3 <= 0.9999F || f5 <= 0.9999F); - boundsFlags.set(0, (f1 < 1.0E-4F || blockIn.isFullCube()) && f1 == f4); - break; - case UP: - boundsFlags.set(1, f >= 1.0E-4F || f2 >= 1.0E-4F || f3 <= 0.9999F || f5 <= 0.9999F); - boundsFlags.set(0, (f4 > 0.9999F || blockIn.isFullCube()) && f1 == f4); - break; - case NORTH: - boundsFlags.set(1, f >= 1.0E-4F || f1 >= 1.0E-4F || f3 <= 0.9999F || f4 <= 0.9999F); - boundsFlags.set(0, (f2 < 1.0E-4F || blockIn.isFullCube()) && f2 == f5); - break; - case SOUTH: - boundsFlags.set(1, f >= 1.0E-4F || f1 >= 1.0E-4F || f3 <= 0.9999F || f4 <= 0.9999F); - boundsFlags.set(0, (f5 > 0.9999F || blockIn.isFullCube()) && f2 == f5); - break; - case WEST: - boundsFlags.set(1, f1 >= 1.0E-4F || f2 >= 1.0E-4F || f4 <= 0.9999F || f5 <= 0.9999F); - boundsFlags.set(0, (f < 1.0E-4F || blockIn.isFullCube()) && f == f3); - break; - case EAST: - boundsFlags.set(1, f1 >= 1.0E-4F || f2 >= 1.0E-4F || f4 <= 0.9999F || f5 <= 0.9999F); - boundsFlags.set(0, (f3 > 0.9999F || blockIn.isFullCube()) && f == f3); - } - - } - - private final BlockPos blockpos0 = new BlockPos(0, 0, 0); - private final BlockPos blockpos1 = new BlockPos(0, 0, 0); - private final BlockPos blockpos2 = new BlockPos(0, 0, 0); - private final BlockPos blockpos3 = new BlockPos(0, 0, 0); - private final BlockPos blockpos4 = new BlockPos(0, 0, 0); - private final BlockPos blockpos5 = new BlockPos(0, 0, 0); - - private void renderModelStandardQuads(IBlockAccess blockAccessIn, Block blockIn, BlockPos blockPosIn, - EnumFacing faceIn, int brightnessIn, boolean ownBrightness, WorldRenderer worldRendererIn, - List listQuadsIn, BitSet boundsFlags, float[] quadBounds) { - boolean isDeferred = DeferredStateManager.isDeferredRenderer(); - boolean isDynamicLights = isDeferred || DynamicLightsStateManager.isDynamicLightsRender(); - double d0 = (double) blockPosIn.getX(); - double d1 = (double) blockPosIn.getY(); - double d2 = (double) blockPosIn.getZ(); - Block.EnumOffsetType block$enumoffsettype = blockIn.getOffsetType(); - if (block$enumoffsettype != Block.EnumOffsetType.NONE) { - int i = blockPosIn.getX(); - int j = blockPosIn.getZ(); - long k = (long) (i * 3129871) ^ (long) j * 116129781L; - k = k * k * 42317861L + k * 11L; - d0 += ((double) ((float) (k >> 16 & 15L) / 15.0F) - 0.5D) * 0.5D; - d2 += ((double) ((float) (k >> 24 & 15L) / 15.0F) - 0.5D) * 0.5D; - if (!isDeferred && block$enumoffsettype == Block.EnumOffsetType.XYZ) { - d1 += ((double) ((float) (k >> 20 & 15L) / 15.0F) - 1.0D) * 0.2D; - } - } - - for (int m = 0, n = listQuadsIn.size(); m < n; ++m) { - BakedQuad bakedquad = listQuadsIn.get(m); - EnumFacing facingIn = bakedquad.getFace(); - int[] vertData = isDynamicLights ? bakedquad.getVertexDataWithNormals() : bakedquad.getVertexData(); - blockPosIn.offsetEvenFaster(facingIn, blockpos0); - this.fillQuadBounds(blockIn, vertData, facingIn, quadBounds, boundsFlags, isDynamicLights ? 8 : 7); - boolean boundsFlags0 = boundsFlags.get(0); - if (ownBrightness) { - brightnessIn = boundsFlags0 ? blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos0) - : blockIn.getMixedBrightnessForBlock(blockAccessIn, blockPosIn); - } - - worldRendererIn.addVertexData(vertData); - - if (isDeferred) { - BlockModelRenderer.EnumNeighborInfo blockmodelrenderer$enumneighborinfo = BlockModelRenderer.EnumNeighborInfo - .getNeighbourInfo(facingIn); - BlockPos blockPosIn2 = boundsFlags0 ? blockpos0 : blockPosIn; - blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[0], blockpos1); - int i = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos1); - blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[1], blockpos2); - int j = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos2); - blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[2], blockpos3); - int k = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos3); - blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[3], blockpos4); - int l = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos4); - - blockpos1.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[2], blockpos5); - int i1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); - - blockpos1.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[3], blockpos5); - int j1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); - - blockpos2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[2], blockpos5); - int k1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); - - blockpos2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[3], blockpos5); - int l1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); - - int[] b = new int[4]; - - boolean upIsOpaque = !blockAccessIn.getBlockState(blockpos0).getBlock().isOpaqueCube(); - int i3; - if (boundsFlags0 || upIsOpaque) { - i3 = (ownBrightness && boundsFlags0) ? brightnessIn - : blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos0); - } else { - i3 = (ownBrightness && !boundsFlags0) ? brightnessIn - : blockIn.getMixedBrightnessForBlock(blockAccessIn, blockPosIn); - } - - BlockModelRenderer.VertexTranslations blockmodelrenderer$vertextranslations = BlockModelRenderer.VertexTranslations - .getVertexTranslations(facingIn); - if (boundsFlags.get(1) && blockmodelrenderer$enumneighborinfo.field_178289_i) { - float f13 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[0].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[1].field_178229_m]; - float f14 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[2].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[3].field_178229_m]; - float f15 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[4].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[5].field_178229_m]; - float f16 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[6].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[7].field_178229_m]; - float f17 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[0].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[1].field_178229_m]; - float f18 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[2].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[3].field_178229_m]; - float f19 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[4].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[5].field_178229_m]; - float f20 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[6].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[7].field_178229_m]; - float f21 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[0].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[1].field_178229_m]; - float f22 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[2].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[3].field_178229_m]; - float f23 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[4].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[5].field_178229_m]; - float f24 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[6].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[7].field_178229_m]; - float f25 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[0].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[1].field_178229_m]; - float f26 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[2].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[3].field_178229_m]; - float f27 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[4].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[5].field_178229_m]; - float f28 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[6].field_178229_m] - * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[7].field_178229_m]; - int i2 = getAoBrightness(l, i, j1, i3); - int j2 = getAoBrightness(k, i, i1, i3); - int k2 = getAoBrightness(k, j, k1, i3); - int l2 = getAoBrightness(l, j, l1, i3); - b[blockmodelrenderer$vertextranslations.field_178191_g] = getVertexBrightness(i2, j2, k2, l2, f13, - f14, f15, f16); - b[blockmodelrenderer$vertextranslations.field_178200_h] = getVertexBrightness(i2, j2, k2, l2, f17, - f18, f19, f20); - b[blockmodelrenderer$vertextranslations.field_178201_i] = getVertexBrightness(i2, j2, k2, l2, f21, - f22, f23, f24); - b[blockmodelrenderer$vertextranslations.field_178198_j] = getVertexBrightness(i2, j2, k2, l2, f25, - f26, f27, f28); - } else { - b[blockmodelrenderer$vertextranslations.field_178191_g] = getAoBrightness(l, i, j1, i3); - b[blockmodelrenderer$vertextranslations.field_178200_h] = getAoBrightness(k, i, i1, i3); - b[blockmodelrenderer$vertextranslations.field_178201_i] = getAoBrightness(k, j, k1, i3); - b[blockmodelrenderer$vertextranslations.field_178198_j] = getAoBrightness(l, j, l1, i3); - } - worldRendererIn.putBrightness4(b[0], b[1], b[2], b[3]); - } else { - worldRendererIn.putBrightness4(brightnessIn, brightnessIn, brightnessIn, brightnessIn); - } - - if (bakedquad.hasTintIndex()) { - int l = blockIn.colorMultiplier(blockAccessIn, blockPosIn, bakedquad.getTintIndex()); - if (EntityRenderer.anaglyphEnable) { - l = TextureUtil.anaglyphColor(l); - } - - float f = (float) (l >> 16 & 255) / 255.0F; - float f1 = (float) (l >> 8 & 255) / 255.0F; - float f2 = (float) (l & 255) / 255.0F; - worldRendererIn.putColorMultiplier(f, f1, f2, 4); - worldRendererIn.putColorMultiplier(f, f1, f2, 3); - worldRendererIn.putColorMultiplier(f, f1, f2, 2); - worldRendererIn.putColorMultiplier(f, f1, f2, 1); - } - - worldRendererIn.putPosition(d0, d1, d2); - } - - } - - private static int getAoBrightness(int parInt1, int parInt2, int parInt3, int parInt4) { - if (parInt1 == 0) { - parInt1 = parInt4; - } - - if (parInt2 == 0) { - parInt2 = parInt4; - } - - if (parInt3 == 0) { - parInt3 = parInt4; - } - - return parInt1 + parInt2 + parInt3 + parInt4 >> 2 & 16711935; - } - - public void renderModelBrightnessColor(IBakedModel bakedModel, float parFloat1, float parFloat2, float parFloat3, - float parFloat4) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - this.renderModelBrightnessColorQuads(parFloat1, parFloat2, parFloat3, parFloat4, - bakedModel.getFaceQuads(enumfacing)); - } - - this.renderModelBrightnessColorQuads(parFloat1, parFloat2, parFloat3, parFloat4, bakedModel.getGeneralQuads()); - } - - public void renderModelBrightness(IBakedModel parIBakedModel, IBlockState parIBlockState, float parFloat1, - boolean parFlag) { - Block block = parIBlockState.getBlock(); - block.setBlockBoundsForItemRender(); - GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - int i = block.getRenderColor(block.getStateForEntityRender(parIBlockState)); - if (EntityRenderer.anaglyphEnable) { - i = TextureUtil.anaglyphColor(i); - } - - float f = (float) (i >> 16 & 255) / 255.0F; - float f1 = (float) (i >> 8 & 255) / 255.0F; - float f2 = (float) (i & 255) / 255.0F; - if (!parFlag) { - GlStateManager.color(parFloat1, parFloat1, parFloat1, 1.0F); - } - - this.renderModelBrightnessColor(parIBakedModel, parFloat1, f, f1, f2); - } - - private void renderModelBrightnessColorQuads(float parFloat1, float parFloat2, float parFloat3, float parFloat4, - List parList) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - - for (int i = 0, l = parList.size(); i < l; ++i) { - BakedQuad bakedquad = parList.get(i); - worldrenderer.begin(7, DefaultVertexFormats.ITEM); - worldrenderer.addVertexData(bakedquad.getVertexData()); - if (bakedquad.hasTintIndex()) { - worldrenderer.putColorRGB_F4(parFloat2 * parFloat1, parFloat3 * parFloat1, parFloat4 * parFloat1); - } else { - worldrenderer.putColorRGB_F4(parFloat1, parFloat1, parFloat1); - } - - Vec3i vec3i = bakedquad.getFace().getDirectionVec(); - worldrenderer.putNormal((float) vec3i.getX(), (float) vec3i.getY(), (float) vec3i.getZ(), - VertexMarkerState.markId); - tessellator.draw(); - } - - } - class AmbientOcclusionFace { private final float[] vertexColorMultiplier = new float[4]; private final int[] vertexBrightness = new int[4]; @@ -666,15 +222,6 @@ public class BlockModelRenderer { } } - private static int getVertexBrightness(int parInt1, int parInt2, int parInt3, int parInt4, float parFloat1, - float parFloat2, float parFloat3, float parFloat4) { - int i = (int) ((float) (parInt1 >> 16 & 255) * parFloat1 + (float) (parInt2 >> 16 & 255) * parFloat2 - + (float) (parInt3 >> 16 & 255) * parFloat3 + (float) (parInt4 >> 16 & 255) * parFloat4) & 255; - int j = (int) ((float) (parInt1 & 255) * parFloat1 + (float) (parInt2 & 255) * parFloat2 - + (float) (parInt3 & 255) * parFloat3 + (float) (parInt4 & 255) * parFloat4) & 255; - return i << 16 | j; - } - public static enum EnumNeighborInfo { DOWN(new EnumFacing[] { EnumFacing.WEST, EnumFacing.EAST, EnumFacing.NORTH, EnumFacing.SOUTH }, 0.5F, false, new BlockModelRenderer.Orientation[0], new BlockModelRenderer.Orientation[0], @@ -767,14 +314,29 @@ public class BlockModelRenderer { BlockModelRenderer.Orientation.FLIP_SOUTH, BlockModelRenderer.Orientation.UP, BlockModelRenderer.Orientation.SOUTH }); + private static final BlockModelRenderer.EnumNeighborInfo[] field_178282_n = new BlockModelRenderer.EnumNeighborInfo[6]; + static { + field_178282_n[EnumFacing.DOWN.getIndex()] = DOWN; + field_178282_n[EnumFacing.UP.getIndex()] = UP; + field_178282_n[EnumFacing.NORTH.getIndex()] = NORTH; + field_178282_n[EnumFacing.SOUTH.getIndex()] = SOUTH; + field_178282_n[EnumFacing.WEST.getIndex()] = WEST; + field_178282_n[EnumFacing.EAST.getIndex()] = EAST; + } + + public static BlockModelRenderer.EnumNeighborInfo getNeighbourInfo(EnumFacing parEnumFacing) { + return field_178282_n[parEnumFacing.getIndex()]; + } + protected final EnumFacing[] field_178276_g; protected final float field_178288_h; protected final boolean field_178289_i; protected final BlockModelRenderer.Orientation[] field_178286_j; protected final BlockModelRenderer.Orientation[] field_178287_k; + protected final BlockModelRenderer.Orientation[] field_178284_l; + protected final BlockModelRenderer.Orientation[] field_178285_m; - private static final BlockModelRenderer.EnumNeighborInfo[] field_178282_n = new BlockModelRenderer.EnumNeighborInfo[6]; private EnumNeighborInfo(EnumFacing[] parArrayOfEnumFacing, float parFloat1, boolean parFlag, BlockModelRenderer.Orientation[] parArrayOfOrientation, @@ -789,19 +351,6 @@ public class BlockModelRenderer { this.field_178284_l = parArrayOfOrientation_3; this.field_178285_m = parArrayOfOrientation_4; } - - public static BlockModelRenderer.EnumNeighborInfo getNeighbourInfo(EnumFacing parEnumFacing) { - return field_178282_n[parEnumFacing.getIndex()]; - } - - static { - field_178282_n[EnumFacing.DOWN.getIndex()] = DOWN; - field_178282_n[EnumFacing.UP.getIndex()] = UP; - field_178282_n[EnumFacing.NORTH.getIndex()] = NORTH; - field_178282_n[EnumFacing.SOUTH.getIndex()] = SOUTH; - field_178282_n[EnumFacing.WEST.getIndex()] = WEST; - field_178282_n[EnumFacing.EAST.getIndex()] = EAST; - } } public static enum Orientation { @@ -820,23 +369,7 @@ public class BlockModelRenderer { static enum VertexTranslations { DOWN(0, 1, 2, 3), UP(2, 3, 0, 1), NORTH(3, 0, 1, 2), SOUTH(0, 1, 2, 3), WEST(3, 0, 1, 2), EAST(1, 2, 3, 0); - private final int field_178191_g; - private final int field_178200_h; - private final int field_178201_i; - private final int field_178198_j; private static final BlockModelRenderer.VertexTranslations[] field_178199_k = new BlockModelRenderer.VertexTranslations[6]; - - private VertexTranslations(int parInt2, int parInt3, int parInt4, int parInt5) { - this.field_178191_g = parInt2; - this.field_178200_h = parInt3; - this.field_178201_i = parInt4; - this.field_178198_j = parInt5; - } - - public static BlockModelRenderer.VertexTranslations getVertexTranslations(EnumFacing parEnumFacing) { - return field_178199_k[parEnumFacing.getIndex()]; - } - static { field_178199_k[EnumFacing.DOWN.getIndex()] = DOWN; field_178199_k[EnumFacing.UP.getIndex()] = UP; @@ -845,5 +378,479 @@ public class BlockModelRenderer { field_178199_k[EnumFacing.WEST.getIndex()] = WEST; field_178199_k[EnumFacing.EAST.getIndex()] = EAST; } + + public static BlockModelRenderer.VertexTranslations getVertexTranslations(EnumFacing parEnumFacing) { + return field_178199_k[parEnumFacing.getIndex()]; + } + + private final int field_178191_g; + private final int field_178200_h; + + private final int field_178201_i; + + private final int field_178198_j; + + private VertexTranslations(int parInt2, int parInt3, int parInt4, int parInt5) { + this.field_178191_g = parInt2; + this.field_178200_h = parInt3; + this.field_178201_i = parInt4; + this.field_178198_j = parInt5; + } + } + + private static int getAoBrightness(int parInt1, int parInt2, int parInt3, int parInt4) { + if (parInt1 == 0) { + parInt1 = parInt4; + } + + if (parInt2 == 0) { + parInt2 = parInt4; + } + + if (parInt3 == 0) { + parInt3 = parInt4; + } + + return parInt1 + parInt2 + parInt3 + parInt4 >> 2 & 16711935; + } + + private static int getVertexBrightness(int parInt1, int parInt2, int parInt3, int parInt4, float parFloat1, + float parFloat2, float parFloat3, float parFloat4) { + int i = (int) ((float) (parInt1 >> 16 & 255) * parFloat1 + (float) (parInt2 >> 16 & 255) * parFloat2 + + (float) (parInt3 >> 16 & 255) * parFloat3 + (float) (parInt4 >> 16 & 255) * parFloat4) & 255; + int j = (int) ((float) (parInt1 & 255) * parFloat1 + (float) (parInt2 & 255) * parFloat2 + + (float) (parInt3 & 255) * parFloat3 + (float) (parInt4 & 255) * parFloat4) & 255; + return i << 16 | j; + } + + private final BlockPos blockpos0 = new BlockPos(0, 0, 0); + private final BlockPos blockpos1 = new BlockPos(0, 0, 0); + private final BlockPos blockpos2 = new BlockPos(0, 0, 0); + private final BlockPos blockpos3 = new BlockPos(0, 0, 0); + private final BlockPos blockpos4 = new BlockPos(0, 0, 0); + private final BlockPos blockpos5 = new BlockPos(0, 0, 0); + + private void fillQuadBounds(Block blockIn, int[] vertexData, EnumFacing facingIn, float[] quadBounds, + BitSet boundsFlags, int deferredStrideOverride) { + float f = 32.0F; + float f1 = 32.0F; + float f2 = 32.0F; + float f3 = -32.0F; + float f4 = -32.0F; + float f5 = -32.0F; + + for (int i = 0; i < 4; ++i) { + int j = i * deferredStrideOverride; + float f6 = Float.intBitsToFloat(vertexData[j]); + float f7 = Float.intBitsToFloat(vertexData[j + 1]); + float f8 = Float.intBitsToFloat(vertexData[j + 2]); + f = Math.min(f, f6); + f1 = Math.min(f1, f7); + f2 = Math.min(f2, f8); + f3 = Math.max(f3, f6); + f4 = Math.max(f4, f7); + f5 = Math.max(f5, f8); + } + + if (quadBounds != null) { + quadBounds[EnumFacing.WEST.getIndex()] = f; + quadBounds[EnumFacing.EAST.getIndex()] = f3; + quadBounds[EnumFacing.DOWN.getIndex()] = f1; + quadBounds[EnumFacing.UP.getIndex()] = f4; + quadBounds[EnumFacing.NORTH.getIndex()] = f2; + quadBounds[EnumFacing.SOUTH.getIndex()] = f5; + quadBounds[EnumFacing.WEST.getIndex() + EnumFacing._VALUES.length] = 1.0F - f; + quadBounds[EnumFacing.EAST.getIndex() + EnumFacing._VALUES.length] = 1.0F - f3; + quadBounds[EnumFacing.DOWN.getIndex() + EnumFacing._VALUES.length] = 1.0F - f1; + quadBounds[EnumFacing.UP.getIndex() + EnumFacing._VALUES.length] = 1.0F - f4; + quadBounds[EnumFacing.NORTH.getIndex() + EnumFacing._VALUES.length] = 1.0F - f2; + quadBounds[EnumFacing.SOUTH.getIndex() + EnumFacing._VALUES.length] = 1.0F - f5; + } + + float f9 = 1.0E-4F; + float f10 = 0.9999F; + switch (facingIn) { + case DOWN: + boundsFlags.set(1, f >= 1.0E-4F || f2 >= 1.0E-4F || f3 <= 0.9999F || f5 <= 0.9999F); + boundsFlags.set(0, (f1 < 1.0E-4F || blockIn.isFullCube()) && f1 == f4); + break; + case UP: + boundsFlags.set(1, f >= 1.0E-4F || f2 >= 1.0E-4F || f3 <= 0.9999F || f5 <= 0.9999F); + boundsFlags.set(0, (f4 > 0.9999F || blockIn.isFullCube()) && f1 == f4); + break; + case NORTH: + boundsFlags.set(1, f >= 1.0E-4F || f1 >= 1.0E-4F || f3 <= 0.9999F || f4 <= 0.9999F); + boundsFlags.set(0, (f2 < 1.0E-4F || blockIn.isFullCube()) && f2 == f5); + break; + case SOUTH: + boundsFlags.set(1, f >= 1.0E-4F || f1 >= 1.0E-4F || f3 <= 0.9999F || f4 <= 0.9999F); + boundsFlags.set(0, (f5 > 0.9999F || blockIn.isFullCube()) && f2 == f5); + break; + case WEST: + boundsFlags.set(1, f1 >= 1.0E-4F || f2 >= 1.0E-4F || f4 <= 0.9999F || f5 <= 0.9999F); + boundsFlags.set(0, (f < 1.0E-4F || blockIn.isFullCube()) && f == f3); + break; + case EAST: + boundsFlags.set(1, f1 >= 1.0E-4F || f2 >= 1.0E-4F || f4 <= 0.9999F || f5 <= 0.9999F); + boundsFlags.set(0, (f3 > 0.9999F || blockIn.isFullCube()) && f == f3); + } + + } + + public boolean renderModel(IBlockAccess blockAccessIn, IBakedModel modelIn, IBlockState blockStateIn, + BlockPos blockPosIn, WorldRenderer worldRendererIn) { + Block block = blockStateIn.getBlock(); + block.setBlockBoundsBasedOnState(blockAccessIn, blockPosIn); + return this.renderModel(blockAccessIn, modelIn, blockStateIn, blockPosIn, worldRendererIn, true); + } + + public boolean renderModel(IBlockAccess blockAccessIn, IBakedModel modelIn, IBlockState blockStateIn, + BlockPos blockPosIn, WorldRenderer worldRendererIn, boolean checkSides) { + boolean flag = Minecraft.isAmbientOcclusionEnabled() && blockStateIn.getBlock().getLightValue() == 0 + && modelIn.isAmbientOcclusion(); + + try { + Block block = blockStateIn.getBlock(); + return flag + ? this.renderModelAmbientOcclusion(blockAccessIn, modelIn, block, blockPosIn, worldRendererIn, + checkSides) + : this.renderModelStandard(blockAccessIn, modelIn, block, blockPosIn, worldRendererIn, checkSides); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Tesselating block model"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Block model being tesselated"); + CrashReportCategory.addBlockInfo(crashreportcategory, blockPosIn, blockStateIn); + crashreportcategory.addCrashSection("Using AO", Boolean.valueOf(flag)); + throw new ReportedException(crashreport); + } + } + + public boolean renderModelAmbientOcclusion(IBlockAccess blockAccessIn, IBakedModel modelIn, Block blockIn, + BlockPos blockPosIn, WorldRenderer worldRendererIn, boolean checkSides) { + boolean flag = false; + float[] afloat = new float[EnumFacing._VALUES.length * 2]; + BitSet bitset = new BitSet(3); + BlockModelRenderer.AmbientOcclusionFace blockmodelrenderer$ambientocclusionface = new BlockModelRenderer.AmbientOcclusionFace(); + + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + List list = modelIn.getFaceQuads(enumfacing); + if (!list.isEmpty()) { + BlockPos blockpos = blockPosIn.offset(enumfacing); + if (!checkSides || blockIn.shouldSideBeRendered(blockAccessIn, blockpos, enumfacing)) { + this.renderModelAmbientOcclusionQuads(blockAccessIn, blockIn, blockPosIn, worldRendererIn, list, + afloat, bitset, blockmodelrenderer$ambientocclusionface); + flag = true; + } + } + } + + List list1 = modelIn.getGeneralQuads(); + if (list1.size() > 0) { + this.renderModelAmbientOcclusionQuads(blockAccessIn, blockIn, blockPosIn, worldRendererIn, list1, afloat, + bitset, blockmodelrenderer$ambientocclusionface); + flag = true; + } + + return flag; + } + + private void renderModelAmbientOcclusionQuads(IBlockAccess blockAccessIn, Block blockIn, BlockPos blockPosIn, + WorldRenderer worldRendererIn, List listQuadsIn, float[] quadBounds, BitSet boundsFlags, + BlockModelRenderer.AmbientOcclusionFace aoFaceIn) { + boolean isDeferred = DeferredStateManager.isDeferredRenderer(); + boolean isDynamicLights = isDeferred || DynamicLightsStateManager.isDynamicLightsRender(); + double d0 = (double) blockPosIn.getX(); + double d1 = (double) blockPosIn.getY(); + double d2 = (double) blockPosIn.getZ(); + Block.EnumOffsetType block$enumoffsettype = blockIn.getOffsetType(); + if (block$enumoffsettype != Block.EnumOffsetType.NONE) { + long i = MathHelper.getPositionRandom(blockPosIn); + d0 += ((double) ((float) (i >> 16 & 15L) / 15.0F) - 0.5D) * 0.5D; + d2 += ((double) ((float) (i >> 24 & 15L) / 15.0F) - 0.5D) * 0.5D; + if (!isDeferred && block$enumoffsettype == Block.EnumOffsetType.XYZ) { + d1 += ((double) ((float) (i >> 20 & 15L) / 15.0F) - 1.0D) * 0.2D; + } + } + + for (int i = 0, l = listQuadsIn.size(); i < l; ++i) { + BakedQuad bakedquad = listQuadsIn.get(i); + int[] vertData = isDynamicLights ? bakedquad.getVertexDataWithNormals() : bakedquad.getVertexData(); + this.fillQuadBounds(blockIn, vertData, bakedquad.getFace(), quadBounds, boundsFlags, + isDynamicLights ? 8 : 7); + aoFaceIn.updateVertexBrightness(blockAccessIn, blockIn, blockPosIn, bakedquad.getFace(), quadBounds, + boundsFlags); + worldRendererIn.addVertexData(vertData); + worldRendererIn.putBrightness4(aoFaceIn.vertexBrightness[0], aoFaceIn.vertexBrightness[1], + aoFaceIn.vertexBrightness[2], aoFaceIn.vertexBrightness[3]); + if (bakedquad.hasTintIndex()) { + int j = blockIn.colorMultiplier(blockAccessIn, blockPosIn, bakedquad.getTintIndex()); + if (EntityRenderer.anaglyphEnable) { + j = TextureUtil.anaglyphColor(j); + } + + float f = (float) (j >> 16 & 255) / 255.0F; + float f1 = (float) (j >> 8 & 255) / 255.0F; + float f2 = (float) (j & 255) / 255.0F; + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[0] * f, + aoFaceIn.vertexColorMultiplier[0] * f1, aoFaceIn.vertexColorMultiplier[0] * f2, 4); + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[1] * f, + aoFaceIn.vertexColorMultiplier[1] * f1, aoFaceIn.vertexColorMultiplier[1] * f2, 3); + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[2] * f, + aoFaceIn.vertexColorMultiplier[2] * f1, aoFaceIn.vertexColorMultiplier[2] * f2, 2); + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[3] * f, + aoFaceIn.vertexColorMultiplier[3] * f1, aoFaceIn.vertexColorMultiplier[3] * f2, 1); + } else { + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[0], aoFaceIn.vertexColorMultiplier[0], + aoFaceIn.vertexColorMultiplier[0], 4); + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[1], aoFaceIn.vertexColorMultiplier[1], + aoFaceIn.vertexColorMultiplier[1], 3); + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[2], aoFaceIn.vertexColorMultiplier[2], + aoFaceIn.vertexColorMultiplier[2], 2); + worldRendererIn.putColorMultiplier(aoFaceIn.vertexColorMultiplier[3], aoFaceIn.vertexColorMultiplier[3], + aoFaceIn.vertexColorMultiplier[3], 1); + } + + worldRendererIn.putPosition(d0, d1, d2); + } + + } + + public void renderModelBrightness(IBakedModel parIBakedModel, IBlockState parIBlockState, float parFloat1, + boolean parFlag) { + Block block = parIBlockState.getBlock(); + block.setBlockBoundsForItemRender(); + GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); + int i = block.getRenderColor(block.getStateForEntityRender(parIBlockState)); + if (EntityRenderer.anaglyphEnable) { + i = TextureUtil.anaglyphColor(i); + } + + float f = (float) (i >> 16 & 255) / 255.0F; + float f1 = (float) (i >> 8 & 255) / 255.0F; + float f2 = (float) (i & 255) / 255.0F; + if (!parFlag) { + GlStateManager.color(parFloat1, parFloat1, parFloat1, 1.0F); + } + + this.renderModelBrightnessColor(parIBakedModel, parFloat1, f, f1, f2); + } + + public void renderModelBrightnessColor(IBakedModel bakedModel, float parFloat1, float parFloat2, float parFloat3, + float parFloat4) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + this.renderModelBrightnessColorQuads(parFloat1, parFloat2, parFloat3, parFloat4, + bakedModel.getFaceQuads(enumfacing)); + } + + this.renderModelBrightnessColorQuads(parFloat1, parFloat2, parFloat3, parFloat4, bakedModel.getGeneralQuads()); + } + + private void renderModelBrightnessColorQuads(float parFloat1, float parFloat2, float parFloat3, float parFloat4, + List parList) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + for (int i = 0, l = parList.size(); i < l; ++i) { + BakedQuad bakedquad = parList.get(i); + worldrenderer.begin(7, DefaultVertexFormats.ITEM); + worldrenderer.addVertexData(bakedquad.getVertexData()); + if (bakedquad.hasTintIndex()) { + worldrenderer.putColorRGB_F4(parFloat2 * parFloat1, parFloat3 * parFloat1, parFloat4 * parFloat1); + } else { + worldrenderer.putColorRGB_F4(parFloat1, parFloat1, parFloat1); + } + + Vec3i vec3i = bakedquad.getFace().getDirectionVec(); + worldrenderer.putNormal((float) vec3i.getX(), (float) vec3i.getY(), (float) vec3i.getZ(), + VertexMarkerState.markId); + tessellator.draw(); + } + + } + + public boolean renderModelStandard(IBlockAccess blockAccessIn, IBakedModel modelIn, Block blockIn, + BlockPos blockPosIn, WorldRenderer worldRendererIn, boolean checkSides) { + boolean isDeferred = DeferredStateManager.isDeferredRenderer(); + boolean flag = false; + float[] afloat = isDeferred ? new float[EnumFacing._VALUES.length * 2] : null; + BitSet bitset = new BitSet(3); + + BlockPos.MutableBlockPos pointer = new BlockPos.MutableBlockPos(); + EnumFacing[] facings = EnumFacing._VALUES; + for (int m = 0; m < facings.length; ++m) { + EnumFacing enumfacing = facings[m]; + List list = modelIn.getFaceQuads(enumfacing); + if (!list.isEmpty()) { + BlockPos blockpos = blockPosIn.offsetEvenFaster(enumfacing, pointer); + if (!checkSides || blockIn.shouldSideBeRendered(blockAccessIn, blockpos, enumfacing)) { + int i = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos); + this.renderModelStandardQuads(blockAccessIn, blockIn, blockPosIn, enumfacing, i, false, + worldRendererIn, list, bitset, afloat); + flag = true; + } + } + } + + List list1 = modelIn.getGeneralQuads(); + if (list1.size() > 0) { + this.renderModelStandardQuads(blockAccessIn, blockIn, blockPosIn, (EnumFacing) null, -1, true, + worldRendererIn, list1, bitset, afloat); + flag = true; + } + + return flag; + } + + private void renderModelStandardQuads(IBlockAccess blockAccessIn, Block blockIn, BlockPos blockPosIn, + EnumFacing faceIn, int brightnessIn, boolean ownBrightness, WorldRenderer worldRendererIn, + List listQuadsIn, BitSet boundsFlags, float[] quadBounds) { + boolean isDeferred = DeferredStateManager.isDeferredRenderer(); + boolean isDynamicLights = isDeferred || DynamicLightsStateManager.isDynamicLightsRender(); + double d0 = (double) blockPosIn.getX(); + double d1 = (double) blockPosIn.getY(); + double d2 = (double) blockPosIn.getZ(); + Block.EnumOffsetType block$enumoffsettype = blockIn.getOffsetType(); + if (block$enumoffsettype != Block.EnumOffsetType.NONE) { + int i = blockPosIn.getX(); + int j = blockPosIn.getZ(); + long k = (long) (i * 3129871) ^ (long) j * 116129781L; + k = k * k * 42317861L + k * 11L; + d0 += ((double) ((float) (k >> 16 & 15L) / 15.0F) - 0.5D) * 0.5D; + d2 += ((double) ((float) (k >> 24 & 15L) / 15.0F) - 0.5D) * 0.5D; + if (!isDeferred && block$enumoffsettype == Block.EnumOffsetType.XYZ) { + d1 += ((double) ((float) (k >> 20 & 15L) / 15.0F) - 1.0D) * 0.2D; + } + } + + for (int m = 0, n = listQuadsIn.size(); m < n; ++m) { + BakedQuad bakedquad = listQuadsIn.get(m); + EnumFacing facingIn = bakedquad.getFace(); + int[] vertData = isDynamicLights ? bakedquad.getVertexDataWithNormals() : bakedquad.getVertexData(); + blockPosIn.offsetEvenFaster(facingIn, blockpos0); + this.fillQuadBounds(blockIn, vertData, facingIn, quadBounds, boundsFlags, isDynamicLights ? 8 : 7); + boolean boundsFlags0 = boundsFlags.get(0); + if (ownBrightness) { + brightnessIn = boundsFlags0 ? blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos0) + : blockIn.getMixedBrightnessForBlock(blockAccessIn, blockPosIn); + } + + worldRendererIn.addVertexData(vertData); + + if (isDeferred) { + BlockModelRenderer.EnumNeighborInfo blockmodelrenderer$enumneighborinfo = BlockModelRenderer.EnumNeighborInfo + .getNeighbourInfo(facingIn); + BlockPos blockPosIn2 = boundsFlags0 ? blockpos0 : blockPosIn; + blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[0], blockpos1); + int i = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos1); + blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[1], blockpos2); + int j = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos2); + blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[2], blockpos3); + int k = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos3); + blockPosIn2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[3], blockpos4); + int l = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos4); + + blockpos1.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[2], blockpos5); + int i1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); + + blockpos1.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[3], blockpos5); + int j1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); + + blockpos2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[2], blockpos5); + int k1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); + + blockpos2.offsetEvenFaster(blockmodelrenderer$enumneighborinfo.field_178276_g[3], blockpos5); + int l1 = blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos5); + + int[] b = new int[4]; + + boolean upIsOpaque = !blockAccessIn.getBlockState(blockpos0).getBlock().isOpaqueCube(); + int i3; + if (boundsFlags0 || upIsOpaque) { + i3 = (ownBrightness && boundsFlags0) ? brightnessIn + : blockIn.getMixedBrightnessForBlock(blockAccessIn, blockpos0); + } else { + i3 = (ownBrightness && !boundsFlags0) ? brightnessIn + : blockIn.getMixedBrightnessForBlock(blockAccessIn, blockPosIn); + } + + BlockModelRenderer.VertexTranslations blockmodelrenderer$vertextranslations = BlockModelRenderer.VertexTranslations + .getVertexTranslations(facingIn); + if (boundsFlags.get(1) && blockmodelrenderer$enumneighborinfo.field_178289_i) { + float f13 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[0].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[1].field_178229_m]; + float f14 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[2].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[3].field_178229_m]; + float f15 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[4].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[5].field_178229_m]; + float f16 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[6].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178286_j[7].field_178229_m]; + float f17 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[0].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[1].field_178229_m]; + float f18 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[2].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[3].field_178229_m]; + float f19 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[4].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[5].field_178229_m]; + float f20 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[6].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178287_k[7].field_178229_m]; + float f21 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[0].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[1].field_178229_m]; + float f22 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[2].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[3].field_178229_m]; + float f23 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[4].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[5].field_178229_m]; + float f24 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[6].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178284_l[7].field_178229_m]; + float f25 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[0].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[1].field_178229_m]; + float f26 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[2].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[3].field_178229_m]; + float f27 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[4].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[5].field_178229_m]; + float f28 = quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[6].field_178229_m] + * quadBounds[blockmodelrenderer$enumneighborinfo.field_178285_m[7].field_178229_m]; + int i2 = getAoBrightness(l, i, j1, i3); + int j2 = getAoBrightness(k, i, i1, i3); + int k2 = getAoBrightness(k, j, k1, i3); + int l2 = getAoBrightness(l, j, l1, i3); + b[blockmodelrenderer$vertextranslations.field_178191_g] = getVertexBrightness(i2, j2, k2, l2, f13, + f14, f15, f16); + b[blockmodelrenderer$vertextranslations.field_178200_h] = getVertexBrightness(i2, j2, k2, l2, f17, + f18, f19, f20); + b[blockmodelrenderer$vertextranslations.field_178201_i] = getVertexBrightness(i2, j2, k2, l2, f21, + f22, f23, f24); + b[blockmodelrenderer$vertextranslations.field_178198_j] = getVertexBrightness(i2, j2, k2, l2, f25, + f26, f27, f28); + } else { + b[blockmodelrenderer$vertextranslations.field_178191_g] = getAoBrightness(l, i, j1, i3); + b[blockmodelrenderer$vertextranslations.field_178200_h] = getAoBrightness(k, i, i1, i3); + b[blockmodelrenderer$vertextranslations.field_178201_i] = getAoBrightness(k, j, k1, i3); + b[blockmodelrenderer$vertextranslations.field_178198_j] = getAoBrightness(l, j, l1, i3); + } + worldRendererIn.putBrightness4(b[0], b[1], b[2], b[3]); + } else { + worldRendererIn.putBrightness4(brightnessIn, brightnessIn, brightnessIn, brightnessIn); + } + + if (bakedquad.hasTintIndex()) { + int l = blockIn.colorMultiplier(blockAccessIn, blockPosIn, bakedquad.getTintIndex()); + if (EntityRenderer.anaglyphEnable) { + l = TextureUtil.anaglyphColor(l); + } + + float f = (float) (l >> 16 & 255) / 255.0F; + float f1 = (float) (l >> 8 & 255) / 255.0F; + float f2 = (float) (l & 255) / 255.0F; + worldRendererIn.putColorMultiplier(f, f1, f2, 4); + worldRendererIn.putColorMultiplier(f, f1, f2, 3); + worldRendererIn.putColorMultiplier(f, f1, f2, 2); + worldRendererIn.putColorMultiplier(f, f1, f2, 1); + } + + worldRendererIn.putPosition(d0, d1, d2); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/BlockModelShapes.java b/src/game/java/net/minecraft/client/renderer/BlockModelShapes.java index a713b633..770d5272 100644 --- a/src/game/java/net/minecraft/client/renderer/BlockModelShapes.java +++ b/src/game/java/net/minecraft/client/renderer/BlockModelShapes.java @@ -59,22 +59,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -93,6 +96,19 @@ public class BlockModelShapes { return this.blockStateMapper; } + public IBakedModel getModelForState(IBlockState state) { + IBakedModel ibakedmodel = (IBakedModel) this.bakedModelStore.get(state); + if (ibakedmodel == null) { + ibakedmodel = this.modelManager.getMissingModel(); + } + + return ibakedmodel; + } + + public ModelManager getModelManager() { + return this.modelManager; + } + public EaglerTextureAtlasSprite getTexture(IBlockState state) { Block block = state.getBlock(); IBakedModel ibakedmodel = this.getModelForState(state); @@ -131,37 +147,6 @@ public class BlockModelShapes { return ibakedmodel.getParticleTexture(); } - public IBakedModel getModelForState(IBlockState state) { - IBakedModel ibakedmodel = (IBakedModel) this.bakedModelStore.get(state); - if (ibakedmodel == null) { - ibakedmodel = this.modelManager.getMissingModel(); - } - - return ibakedmodel; - } - - public ModelManager getModelManager() { - return this.modelManager; - } - - public void reloadModels() { - this.bakedModelStore.clear(); - - for (Entry entry : this.blockStateMapper.putAllStateModelLocations().entrySet()) { - this.bakedModelStore.put((IBlockState) entry.getKey(), - this.modelManager.getModel((ModelResourceLocation) entry.getValue())); - } - - } - - public void registerBlockWithStateMapper(Block assoc, IStateMapper stateMapper) { - this.blockStateMapper.registerBlockStateMapper(assoc, stateMapper); - } - - public void registerBuiltInBlocks(Block... builtIns) { - this.blockStateMapper.registerBuiltInBlocks(builtIns); - } - private void registerAllBlocks() { this.registerBuiltInBlocks(new Block[] { Blocks.air, Blocks.flowing_water, Blocks.water, Blocks.flowing_lava, Blocks.lava, Blocks.piston_extension, Blocks.chest, Blocks.ender_chest, Blocks.trapped_chest, @@ -354,4 +339,22 @@ public class BlockModelShapes { } }); } + + public void registerBlockWithStateMapper(Block assoc, IStateMapper stateMapper) { + this.blockStateMapper.registerBlockStateMapper(assoc, stateMapper); + } + + public void registerBuiltInBlocks(Block... builtIns) { + this.blockStateMapper.registerBuiltInBlocks(builtIns); + } + + public void reloadModels() { + this.bakedModelStore.clear(); + + for (Entry entry : this.blockStateMapper.putAllStateModelLocations().entrySet()) { + this.bakedModelStore.put((IBlockState) entry.getKey(), + this.modelManager.getModel((ModelResourceLocation) entry.getValue())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/BlockRendererDispatcher.java b/src/game/java/net/minecraft/client/renderer/BlockRendererDispatcher.java index f2960504..24f54eea 100644 --- a/src/game/java/net/minecraft/client/renderer/BlockRendererDispatcher.java +++ b/src/game/java/net/minecraft/client/renderer/BlockRendererDispatcher.java @@ -17,22 +17,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,21 +52,50 @@ public class BlockRendererDispatcher implements IResourceManagerReloadListener { this.gameSettings = gameSettingsIn; } + private IBakedModel getBakedModel(IBlockState state, BlockPos pos) { + IBakedModel ibakedmodel = this.blockModelShapes.getModelForState(state); + if (pos != null && this.gameSettings.allowBlockAlternatives && ibakedmodel instanceof WeightedBakedModel) { + ibakedmodel = ((WeightedBakedModel) ibakedmodel).getAlternativeModel(MathHelper.getPositionRandom(pos)); + } + + return ibakedmodel; + } + + public BlockModelRenderer getBlockModelRenderer() { + return this.blockModelRenderer; + } + public BlockModelShapes getBlockModelShapes() { return this.blockModelShapes; } - public void renderBlockDamage(IBlockState state, BlockPos pos, EaglerTextureAtlasSprite texture, - IBlockAccess blockAccess) { + public IBakedModel getModelFromBlockState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { Block block = state.getBlock(); - int i = block.getRenderType(); - if (i == 3) { - state = block.getActualState(state, blockAccess, pos); - IBakedModel ibakedmodel = this.blockModelShapes.getModelForState(state); - IBakedModel ibakedmodel1 = (new SimpleBakedModel.Builder(ibakedmodel, texture)).makeBakedModel(); - this.blockModelRenderer.renderModel(blockAccess, ibakedmodel1, state, pos, - Tessellator.getInstance().getWorldRenderer()); + + try { + state = block.getActualState(state, worldIn, pos); + } catch (Exception eeeee) { } + + IBakedModel ibakedmodel = this.blockModelShapes.getModelForState(state); + if (pos != null && this.gameSettings.allowBlockAlternatives && ibakedmodel instanceof WeightedBakedModel) { + ibakedmodel = ((WeightedBakedModel) ibakedmodel).getAlternativeModel(MathHelper.getPositionRandom(pos)); + } + + return ibakedmodel; + } + + public boolean isRenderTypeChest(Block parBlock, int parInt1) { + if (parBlock == null) { + return false; + } else { + int i = parBlock.getRenderType(); + return i == 3 ? false : i == 2; + } + } + + public void onResourceManagerReload(IResourceManager var1) { + this.fluidRenderer.initAtlasSprites(); } public boolean renderBlock(IBlockState state, BlockPos pos, IBlockAccess blockAccess, @@ -94,35 +126,6 @@ public class BlockRendererDispatcher implements IResourceManagerReloadListener { } } - public BlockModelRenderer getBlockModelRenderer() { - return this.blockModelRenderer; - } - - private IBakedModel getBakedModel(IBlockState state, BlockPos pos) { - IBakedModel ibakedmodel = this.blockModelShapes.getModelForState(state); - if (pos != null && this.gameSettings.allowBlockAlternatives && ibakedmodel instanceof WeightedBakedModel) { - ibakedmodel = ((WeightedBakedModel) ibakedmodel).getAlternativeModel(MathHelper.getPositionRandom(pos)); - } - - return ibakedmodel; - } - - public IBakedModel getModelFromBlockState(IBlockState state, IBlockAccess worldIn, BlockPos pos) { - Block block = state.getBlock(); - - try { - state = block.getActualState(state, worldIn, pos); - } catch (Exception eeeee) { - } - - IBakedModel ibakedmodel = this.blockModelShapes.getModelForState(state); - if (pos != null && this.gameSettings.allowBlockAlternatives && ibakedmodel instanceof WeightedBakedModel) { - ibakedmodel = ((WeightedBakedModel) ibakedmodel).getAlternativeModel(MathHelper.getPositionRandom(pos)); - } - - return ibakedmodel; - } - public void renderBlockBrightness(IBlockState state, float brightness) { int i = state.getBlock().getRenderType(); if (i != -1) { @@ -141,16 +144,16 @@ public class BlockRendererDispatcher implements IResourceManagerReloadListener { } } - public boolean isRenderTypeChest(Block parBlock, int parInt1) { - if (parBlock == null) { - return false; - } else { - int i = parBlock.getRenderType(); - return i == 3 ? false : i == 2; + public void renderBlockDamage(IBlockState state, BlockPos pos, EaglerTextureAtlasSprite texture, + IBlockAccess blockAccess) { + Block block = state.getBlock(); + int i = block.getRenderType(); + if (i == 3) { + state = block.getActualState(state, blockAccess, pos); + IBakedModel ibakedmodel = this.blockModelShapes.getModelForState(state); + IBakedModel ibakedmodel1 = (new SimpleBakedModel.Builder(ibakedmodel, texture)).makeBakedModel(); + this.blockModelRenderer.renderModel(blockAccess, ibakedmodel1, state, pos, + Tessellator.getInstance().getWorldRenderer()); } } - - public void onResourceManagerReload(IResourceManager var1) { - this.fluidRenderer.initAtlasSprites(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/ChestRenderer.java b/src/game/java/net/minecraft/client/renderer/ChestRenderer.java index acd521fd..6d4be370 100644 --- a/src/game/java/net/minecraft/client/renderer/ChestRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/ChestRenderer.java @@ -5,22 +5,25 @@ import net.minecraft.block.Block; import net.minecraft.client.renderer.tileentity.TileEntityItemStackRenderer; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/ChunkRenderContainer.java b/src/game/java/net/minecraft/client/renderer/ChunkRenderContainer.java index 6997fa12..3471bf07 100644 --- a/src/game/java/net/minecraft/client/renderer/ChunkRenderContainer.java +++ b/src/game/java/net/minecraft/client/renderer/ChunkRenderContainer.java @@ -12,22 +12,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,6 +42,10 @@ public abstract class ChunkRenderContainer { protected List renderChunks = Lists.newArrayListWithCapacity(17424); protected boolean initialized; + public void addRenderChunk(RenderChunk renderChunkIn, EnumWorldBlockLayer layer) { + this.renderChunks.add(renderChunkIn); + } + public void initialize(double viewEntityXIn, double viewEntityYIn, double viewEntityZIn) { this.initialized = true; this.renderChunks.clear(); @@ -66,9 +73,5 @@ public abstract class ChunkRenderContainer { } } - public void addRenderChunk(RenderChunk renderChunkIn, EnumWorldBlockLayer layer) { - this.renderChunks.add(renderChunkIn); - } - public abstract void renderChunkLayer(EnumWorldBlockLayer var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/DestroyBlockProgress.java b/src/game/java/net/minecraft/client/renderer/DestroyBlockProgress.java index d6a96303..c97ff1f2 100644 --- a/src/game/java/net/minecraft/client/renderer/DestroyBlockProgress.java +++ b/src/game/java/net/minecraft/client/renderer/DestroyBlockProgress.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,14 +36,31 @@ public class DestroyBlockProgress { this.position = positionIn; } + /** + * + retrieves the 'date' at which the PartiallyDestroyedBlock was created + */ + public int getCreationCloudUpdateTick() { + return this.createdAtCloudUpdateTick; + } + + public int getPartialBlockDamage() { + return this.partialBlockProgress; + } + public BlockPos getPosition() { return this.position; } - /**+ - * inserts damage value into this partially destroyed Block. -1 - * causes client renderer to delete it, otherwise ranges from 1 - * to 10 + /** + * + saves the current Cloud update tick into the PartiallyDestroyedBlock + */ + public void setCloudUpdateTick(int createdAtCloudUpdateTickIn) { + this.createdAtCloudUpdateTick = createdAtCloudUpdateTickIn; + } + + /** + * + inserts damage value into this partially destroyed Block. -1 causes client + * renderer to delete it, otherwise ranges from 1 to 10 */ public void setPartialBlockDamage(int damage) { if (damage > 10) { @@ -49,24 +69,4 @@ public class DestroyBlockProgress { this.partialBlockProgress = damage; } - - public int getPartialBlockDamage() { - return this.partialBlockProgress; - } - - /**+ - * saves the current Cloud update tick into the - * PartiallyDestroyedBlock - */ - public void setCloudUpdateTick(int createdAtCloudUpdateTickIn) { - this.createdAtCloudUpdateTick = createdAtCloudUpdateTickIn; - } - - /**+ - * retrieves the 'date' at which the PartiallyDestroyedBlock was - * created - */ - public int getCreationCloudUpdateTick() { - return this.createdAtCloudUpdateTick; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/EntityRenderer.java b/src/game/java/net/minecraft/client/renderer/EntityRenderer.java index c90b4ca3..b7cb3050 100644 --- a/src/game/java/net/minecraft/client/renderer/EntityRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/EntityRenderer.java @@ -1,15 +1,31 @@ package net.minecraft.client.renderer; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EXP; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FOG_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE1; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; import java.util.Arrays; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.HString; -import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; - import java.util.concurrent.Callable; import com.google.common.base.Predicate; @@ -17,6 +33,10 @@ import com.google.common.base.Predicates; import net.lax1dude.eaglercraft.v1_8.Display; import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; @@ -36,9 +56,9 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ShadersRenderPassFuture import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.gui.GuiShaderConfig; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.texture.EmissiveItems; import net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights.DynamicLightsStateManager; +import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; import net.lax1dude.eaglercraft.v1_8.vector.Vector4f; import net.lax1dude.eaglercraft.v1_8.voice.VoiceTagRenderer; -import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; import net.minecraft.block.Block; import net.minecraft.block.BlockBed; import net.minecraft.block.material.Material; @@ -91,22 +111,25 @@ import net.minecraft.util.Vec3i; import net.minecraft.world.WorldSettings; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -117,6 +140,66 @@ public class EntityRenderer implements IResourceManagerReloadListener { private static final ResourceLocation locationSnowPng = new ResourceLocation("textures/environment/snow.png"); public static boolean anaglyphEnable; public static int anaglyphField; + private static final Vector4f tmpVec4f_1 = new Vector4f(); + private static final Matrix4f tmpMat4f_1 = new Matrix4f(); + private static final Matrix4f matrixToBounds_tmpMat4f_1 = new Matrix4f(); + private static final Vector4f matrixToBounds_tmpVec4f_1 = new Vector4f(); + private static final Vector4f[] matrixToBounds_tmpVec4f_array = new Vector4f[] { new Vector4f(-1, -1, -1, 1), + new Vector4f(-1, -1, 1, 1), new Vector4f(-1, 1, -1, 1), new Vector4f(-1, 1, 1, 1), + new Vector4f(1, -1, -1, 1), new Vector4f(1, -1, 1, 1), new Vector4f(1, 1, -1, 1), + new Vector4f(1, 1, 1, 1) }; + + public static void disableLightmapStatic() { + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.disableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + } + + public static void enableLightmapStatic() { + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.enableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + } + + private static AxisAlignedBB matrixToBounds(Matrix4f matrixIn, double x, double y, double z) { + Matrix4f.invert(matrixIn, matrixToBounds_tmpMat4f_1); + + float minX = Integer.MAX_VALUE; + float minY = Integer.MAX_VALUE; + float minZ = Integer.MAX_VALUE; + float maxX = Integer.MIN_VALUE; + float maxY = Integer.MIN_VALUE; + float maxZ = Integer.MIN_VALUE; + Vector4f tmpVec = matrixToBounds_tmpVec4f_1; + float vx, vy, vz; + for (int i = 0; i < 8; ++i) { + Matrix4f.transform(matrixToBounds_tmpMat4f_1, matrixToBounds_tmpVec4f_array[i], tmpVec); + vx = tmpVec.x; + vy = tmpVec.y; + vz = tmpVec.z; + if (vx < minX) + minX = vx; + if (vy < minY) + minY = vy; + if (vz < minZ) + minZ = vz; + if (vx > maxX) + maxX = vx; + if (vy > maxY) + maxY = vy; + if (vz > maxZ) + maxZ = vz; + } + + return new AxisAlignedBB(minX + x, minY + y, minZ + z, maxX + x, maxY + y, maxZ + z); + } + + public static void setupSunCameraTransform(float celestialAngle) { + GlStateManager.rotate(celestialAngle + 90.0f, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(-DeferredStateManager.sunAngle, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); + } + private Minecraft mc; private final IResourceManager resourceManager; private EaglercraftRandom random = new EaglercraftRandom(); @@ -128,8 +211,8 @@ public class EntityRenderer implements IResourceManagerReloadListener { private MouseFilter mouseFilterXAxis = new MouseFilter(); private MouseFilter mouseFilterYAxis = new MouseFilter(); private float thirdPersonDistance = 4.0F; - /**+ - * Third person distance temp + /** + * + Third person distance temp */ private float thirdPersonDistanceTemp = 4.0F; private float smoothCamYaw; @@ -144,8 +227,8 @@ public class EntityRenderer implements IResourceManagerReloadListener { private boolean cloudFog; private boolean renderHand = true; private boolean drawBlockOutline = true; - /**+ - * Previous frame time in milliseconds + /** + * + Previous frame time in milliseconds */ private long prevFrameTime = Minecraft.getSystemTime(); private long renderEndNanoTime; @@ -158,8 +241,8 @@ public class EntityRenderer implements IResourceManagerReloadListener { private int rainSoundCounter; private float[] rainXCoords = new float[1024]; private float[] rainYCoords = new float[1024]; - /**+ - * Fog color buffer + /** + * + Fog color buffer */ private FloatBuffer fogColorBuffer = GLAllocation.createDirectFloatBuffer(16); private float fogColorRed; @@ -168,18 +251,35 @@ public class EntityRenderer implements IResourceManagerReloadListener { private float fogColor2; private float fogColor1; private int debugViewDirection = 0; + private boolean debugView = false; + private double cameraZoom = 1.0D; + private double cameraYaw; + private double cameraPitch; + private int shaderIndex; + private boolean useShader; + private int frameCount; + private GameOverlayFramebuffer overlayFramebuffer; + private float eagPartialTicks = 0.0f; public float currentProjMatrixFOV = 0.0f; + private int shadowFrameIndex = 0; + + private double blockWaveOffsetX = 0.0; + + private double blockWaveOffsetY = 0.0; + + private double blockWaveOffsetZ = 0.0; + public EntityRenderer(Minecraft mcIn, IResourceManager resourceManagerIn) { this.useShader = false; this.frameCount = 0; @@ -213,1169 +313,9 @@ public class EntityRenderer implements IResourceManagerReloadListener { } - public boolean isShaderActive() { - return false; - } - - public void func_181022_b() { - } - - public void switchUseShader() { - this.useShader = !this.useShader; - } - - /**+ - * What shader to use when spectating this entity - */ - public void loadEntityShader(Entity entityIn) { - } - public void activateNextShader() { } - private void loadShader(ResourceLocation resourceLocationIn) { - this.useShader = false; - } - - public void onResourceManagerReload(IResourceManager var1) { - } - - /**+ - * Updates the entity renderer - */ - public void updateRenderer() { - this.updateFovModifierHand(); - this.updateTorchFlicker(); - this.fogColor2 = this.fogColor1; - this.thirdPersonDistanceTemp = this.thirdPersonDistance; - if (this.mc.gameSettings.smoothCamera) { - float f = this.mc.gameSettings.mouseSensitivity * 0.6F + 0.2F; - float f1 = f * f * f * 8.0F; - this.smoothCamFilterX = this.mouseFilterXAxis.smooth(this.smoothCamYaw, 0.05F * f1); - this.smoothCamFilterY = this.mouseFilterYAxis.smooth(this.smoothCamPitch, 0.05F * f1); - this.smoothCamPartialTicks = 0.0F; - this.smoothCamYaw = 0.0F; - this.smoothCamPitch = 0.0F; - } else { - this.smoothCamFilterX = 0.0F; - this.smoothCamFilterY = 0.0F; - this.mouseFilterXAxis.reset(); - this.mouseFilterYAxis.reset(); - } - - if (this.mc.getRenderViewEntity() == null) { - this.mc.setRenderViewEntity(this.mc.thePlayer); - } - - float f3 = this.mc.theWorld.getLightBrightness( - DeferredStateManager.isDeferredRenderer() ? new BlockPos(this.mc.getRenderViewEntity()).up() - : new BlockPos(this.mc.getRenderViewEntity())); - float f4 = (float) this.mc.gameSettings.renderDistanceChunks / 32.0F; - float f2 = f3 * (1.0F - f4) + f4; - this.fogColor1 += (f2 - this.fogColor1) * 0.1F; - ++this.rendererUpdateCount; - this.itemRenderer.updateEquippedItem(); - this.addRainParticles(); - this.bossColorModifierPrev = this.bossColorModifier; - if (BossStatus.hasColorModifier) { - this.bossColorModifier += 0.05F; - if (this.bossColorModifier > 1.0F) { - this.bossColorModifier = 1.0F; - } - - BossStatus.hasColorModifier = false; - } else if (this.bossColorModifier > 0.0F) { - this.bossColorModifier -= 0.0125F; - } - - } - - public void updateShaderGroupSize(int width, int height) { - } - - /**+ - * Finds what block or object the mouse is over at the specified - * partial tick time. Args: partialTickTime - */ - public void getMouseOver(float partialTicks) { - Entity entity = this.mc.getRenderViewEntity(); - if (entity != null) { - if (this.mc.theWorld != null) { - this.mc.pointedEntity = null; - double d0 = (double) this.mc.playerController.getBlockReachDistance(); - this.mc.objectMouseOver = entity.rayTrace(d0, partialTicks); - double d1 = d0; - Vec3 vec3 = entity.getPositionEyes(partialTicks); - boolean flag = false; - boolean flag1 = true; - if (this.mc.playerController.extendedReach()) { - d0 = 6.0D; - d1 = 6.0D; - } else { - if (d0 > 3.0D) { - flag = true; - } - - d0 = d0; - } - - if (this.mc.objectMouseOver != null) { - d1 = this.mc.objectMouseOver.hitVec.distanceTo(vec3); - } - - Vec3 vec31 = entity.getLook(partialTicks); - Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0); - this.pointedEntity = null; - Vec3 vec33 = null; - float f = 1.0F; - List list = this.mc.theWorld.getEntitiesInAABBexcluding(entity, - entity.getEntityBoundingBox().addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0) - .expand((double) f, (double) f, (double) f), - Predicates.and(EntitySelectors.NOT_SPECTATING, new Predicate() { - public boolean apply(Entity entity2) { - return entity2.canBeCollidedWith(); - } - })); - double d2 = d1; - - for (int i = 0; i < list.size(); ++i) { - Entity entity1 = (Entity) list.get(i); - float f1 = entity1.getCollisionBorderSize(); - AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expand((double) f1, (double) f1, - (double) f1); - MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32); - if (axisalignedbb.isVecInside(vec3)) { - if (d2 >= 0.0D) { - this.pointedEntity = entity1; - vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec; - d2 = 0.0D; - } - } else if (movingobjectposition != null) { - double d3 = vec3.distanceTo(movingobjectposition.hitVec); - if (d3 < d2 || d2 == 0.0D) { - if (entity1 == entity.ridingEntity) { - if (d2 == 0.0D) { - this.pointedEntity = entity1; - vec33 = movingobjectposition.hitVec; - } - } else { - this.pointedEntity = entity1; - vec33 = movingobjectposition.hitVec; - d2 = d3; - } - } - } - } - - if (this.pointedEntity != null && flag && vec3.distanceTo(vec33) > 3.0D) { - this.pointedEntity = null; - this.mc.objectMouseOver = new MovingObjectPosition(MovingObjectPosition.MovingObjectType.MISS, - vec33, (EnumFacing) null, new BlockPos(vec33)); - } - - if (this.pointedEntity != null && (d2 < d1 || this.mc.objectMouseOver == null)) { - this.mc.objectMouseOver = new MovingObjectPosition(this.pointedEntity, vec33); - if (this.pointedEntity instanceof EntityLivingBase - || this.pointedEntity instanceof EntityItemFrame) { - this.mc.pointedEntity = this.pointedEntity; - } - } - } - } - } - - /**+ - * Update FOV modifier hand - */ - private void updateFovModifierHand() { - float f = 1.0F; - if (this.mc.getRenderViewEntity() instanceof AbstractClientPlayer) { - AbstractClientPlayer abstractclientplayer = (AbstractClientPlayer) this.mc.getRenderViewEntity(); - f = abstractclientplayer.getFovModifier(); - } - - this.fovModifierHandPrev = this.fovModifierHand; - this.fovModifierHand += (f - this.fovModifierHand) * 0.5F; - if (this.fovModifierHand > 1.5F) { - this.fovModifierHand = 1.5F; - } - - if (this.fovModifierHand < 0.1F) { - this.fovModifierHand = 0.1F; - } - - } - - /**+ - * Changes the field of view of the player depending on if they - * are underwater or not - */ - public float getFOVModifier(float partialTicks, boolean parFlag) { - if (this.debugView) { - return 90.0F; - } else { - Entity entity = this.mc.getRenderViewEntity(); - float f = 70.0F; - if (parFlag) { - f = this.mc.isZoomKey ? this.mc.adjustedZoomValue : this.mc.gameSettings.fovSetting; - f = f * (this.fovModifierHandPrev + (this.fovModifierHand - this.fovModifierHandPrev) * partialTicks); - } - - if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).getHealth() <= 0.0F) { - float f1 = (float) ((EntityLivingBase) entity).deathTime + partialTicks; - f /= (1.0F - 500.0F / (f1 + 500.0F)) * 2.0F + 1.0F; - } - - Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.mc.theWorld, entity, partialTicks); - if (block.getMaterial() == Material.water) { - f = f * 60.0F / 70.0F; - } - - return f; - } - } - - private void hurtCameraEffect(float partialTicks) { - if (this.mc.getRenderViewEntity() instanceof EntityLivingBase) { - EntityLivingBase entitylivingbase = (EntityLivingBase) this.mc.getRenderViewEntity(); - float f = (float) entitylivingbase.hurtTime - partialTicks; - if (entitylivingbase.getHealth() <= 0.0F) { - float f1 = (float) entitylivingbase.deathTime + partialTicks; - GlStateManager.rotate(40.0F - 8000.0F / (f1 + 200.0F), 0.0F, 0.0F, 1.0F); - } - - if (f < 0.0F) { - return; - } - - f = f / (float) entitylivingbase.maxHurtTime; - f = MathHelper.sin(f * f * f * f * 3.1415927F); - float f2 = entitylivingbase.attackedAtYaw; - GlStateManager.rotate(-f2, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(-f * 14.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(f2, 0.0F, 1.0F, 0.0F); - } - - } - - /**+ - * Setups all the GL settings for view bobbing. Args: - * partialTickTime - */ - private void setupViewBobbing(float partialTicks) { - if (this.mc.getRenderViewEntity() instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) this.mc.getRenderViewEntity(); - float f = entityplayer.distanceWalkedModified - entityplayer.prevDistanceWalkedModified; - float f1 = -(entityplayer.distanceWalkedModified + f * partialTicks); - float f2 = entityplayer.prevCameraYaw - + (entityplayer.cameraYaw - entityplayer.prevCameraYaw) * partialTicks; - float f3 = entityplayer.prevCameraPitch - + (entityplayer.cameraPitch - entityplayer.prevCameraPitch) * partialTicks; - GlStateManager.translate(MathHelper.sin(f1 * 3.1415927F) * f2 * 0.5F, - -Math.abs(MathHelper.cos(f1 * 3.1415927F) * f2), 0.0F); - GlStateManager.rotate(MathHelper.sin(f1 * 3.1415927F) * f2 * 3.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(Math.abs(MathHelper.cos(f1 * 3.1415927F - 0.2F) * f2) * 5.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(f3, 1.0F, 0.0F, 0.0F); - } - } - - /**+ - * sets up player's eye (or camera in third person mode) - */ - private void orientCamera(float partialTicks) { - Entity entity = this.mc.getRenderViewEntity(); - float f = entity.getEyeHeight(); - double d0 = entity.prevPosX + (entity.posX - entity.prevPosX) * (double) partialTicks; - double d1 = entity.prevPosY + (entity.posY - entity.prevPosY) * (double) partialTicks + (double) f; - double d2 = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * (double) partialTicks; - if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPlayerSleeping()) { - f = (float) ((double) f + 1.0D); - GlStateManager.translate(0.0F, 0.3F, 0.0F); - if (!this.mc.gameSettings.debugCamEnable) { - BlockPos blockpos = new BlockPos(entity); - IBlockState iblockstate = this.mc.theWorld.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - if (block == Blocks.bed) { - int j = ((EnumFacing) iblockstate.getValue(BlockBed.FACING)).getHorizontalIndex(); - GlStateManager.rotate((float) (j * 90), 0.0F, 1.0F, 0.0F); - } - - GlStateManager.rotate( - entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks + 180.0F, - 0.0F, -1.0F, 0.0F); - GlStateManager.rotate( - entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * partialTicks, - -1.0F, 0.0F, 0.0F); - } - } else if (this.mc.gameSettings.thirdPersonView > 0) { - double d3 = (double) (this.thirdPersonDistanceTemp - + (this.thirdPersonDistance - this.thirdPersonDistanceTemp) * partialTicks); - if (this.mc.gameSettings.debugCamEnable) { - GlStateManager.translate(0.0F, 0.0F, (float) (-d3)); - } else { - float f1 = entity.rotationYaw; - float f2 = entity.rotationPitch; - if (this.mc.gameSettings.thirdPersonView == 2) { - f2 += 180.0F; - } - - double d4 = (double) (-MathHelper.sin(f1 / 180.0F * 3.1415927F) - * MathHelper.cos(f2 / 180.0F * 3.1415927F)) * d3; - double d5 = (double) (MathHelper.cos(f1 / 180.0F * 3.1415927F) - * MathHelper.cos(f2 / 180.0F * 3.1415927F)) * d3; - double d6 = (double) (-MathHelper.sin(f2 / 180.0F * 3.1415927F)) * d3; - - for (int i = 0; i < 8; ++i) { - float f3 = (float) ((i & 1) * 2 - 1); - float f4 = (float) ((i >> 1 & 1) * 2 - 1); - float f5 = (float) ((i >> 2 & 1) * 2 - 1); - f3 = f3 * 0.1F; - f4 = f4 * 0.1F; - f5 = f5 * 0.1F; - MovingObjectPosition movingobjectposition = this.mc.theWorld - .rayTraceBlocks(new Vec3(d0 + (double) f3, d1 + (double) f4, d2 + (double) f5), new Vec3( - d0 - d4 + (double) f3 + (double) f5, d1 - d6 + (double) f4, d2 - d5 + (double) f5)); - if (movingobjectposition != null) { - double d7 = movingobjectposition.hitVec.distanceTo(new Vec3(d0, d1, d2)); - if (d7 < d3) { - d3 = d7; - } - } - } - - if (this.mc.gameSettings.thirdPersonView == 2) { - GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); - } - - GlStateManager.rotate(entity.rotationPitch - f2, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(entity.rotationYaw - f1, 0.0F, 1.0F, 0.0F); - GlStateManager.translate(0.0F, 0.0F, (float) (-d3)); - GlStateManager.rotate(f1 - entity.rotationYaw, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(f2 - entity.rotationPitch, 1.0F, 0.0F, 0.0F); - } - } else { - GlStateManager.translate(0.0F, 0.0F, -0.1F); - } - - if (!this.mc.gameSettings.debugCamEnable) { - GlStateManager.rotate( - entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * partialTicks, 1.0F, - 0.0F, 0.0F); - if (entity instanceof EntityAnimal) { - EntityAnimal entityanimal = (EntityAnimal) entity; - GlStateManager.rotate(entityanimal.prevRotationYawHead - + (entityanimal.rotationYawHead - entityanimal.prevRotationYawHead) * partialTicks + 180.0F, - 0.0F, 1.0F, 0.0F); - } else { - GlStateManager.rotate( - entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks + 180.0F, - 0.0F, 1.0F, 0.0F); - } - } - - GlStateManager.translate(0.0F, -f, 0.0F); - d0 = entity.prevPosX + (entity.posX - entity.prevPosX) * (double) partialTicks; - d1 = entity.prevPosY + (entity.posY - entity.prevPosY) * (double) partialTicks + (double) f; - d2 = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * (double) partialTicks; - this.cloudFog = this.mc.renderGlobal.hasCloudFog(d0, d1, d2, partialTicks); - } - - /**+ - * sets up projection, view effects, camera position/rotation - */ - private void setupCameraTransform(float partialTicks, int pass) { - this.farPlaneDistance = (float) (this.mc.gameSettings.renderDistanceChunks * 16); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - float f = 0.07F; - if (this.mc.gameSettings.anaglyph) { - GlStateManager.translate((float) (-(pass * 2 - 1)) * f, 0.0F, 0.0F); - } - - if (this.cameraZoom != 1.0D) { - GlStateManager.translate((float) this.cameraYaw, (float) (-this.cameraPitch), 0.0F); - GlStateManager.scale(this.cameraZoom, this.cameraZoom, 1.0D); - } - - float farPlane = this.farPlaneDistance * 2.0f * MathHelper.SQRT_2; - GlStateManager.gluPerspective(currentProjMatrixFOV = this.getFOVModifier(partialTicks, true), - (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, farPlane); - DeferredStateManager.setGBufferNearFarPlanes(0.05f, farPlane); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - if (this.mc.gameSettings.anaglyph) { - GlStateManager.translate((float) (pass * 2 - 1) * 0.1F, 0.0F, 0.0F); - } - - this.hurtCameraEffect(partialTicks); - if (this.mc.gameSettings.viewBobbing) { - this.setupViewBobbing(partialTicks); - } - - float f1 = this.mc.thePlayer.prevTimeInPortal - + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * partialTicks; - if (f1 > 0.0F) { - byte b0 = 20; - if (this.mc.thePlayer.isPotionActive(Potion.confusion)) { - b0 = 7; - } - - float f2 = 5.0F / (f1 * f1 + 5.0F) - f1 * 0.04F; - f2 = f2 * f2; - GlStateManager.rotate(((float) this.rendererUpdateCount + partialTicks) * (float) b0, 0.0F, 1.0F, 1.0F); - GlStateManager.scale(1.0F / f2, 1.0F, 1.0F); - GlStateManager.rotate(-((float) this.rendererUpdateCount + partialTicks) * (float) b0, 0.0F, 1.0F, 1.0F); - } - - this.orientCamera(partialTicks); - if (this.debugView) { - switch (this.debugViewDirection) { - case 0: - GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - break; - case 1: - GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); - break; - case 2: - GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); - break; - case 3: - GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); - break; - case 4: - GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F); - } - } - - } - - /**+ - * Render player hand - */ - private void renderHand(float partialTicks, int xOffset) { - if (!this.debugView) { - if (DynamicLightsStateManager.isInDynamicLightsPass()) { - DynamicLightsStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); - } - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - float f = 0.07F; - if (this.mc.gameSettings.anaglyph) { - GlStateManager.translate((float) (-(xOffset * 2 - 1)) * f, 0.0F, 0.0F); - } - - GlStateManager.gluPerspective(this.getFOVModifier(partialTicks, false), - (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, this.farPlaneDistance * 2.0F); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - if (this.mc.gameSettings.anaglyph) { - GlStateManager.translate((float) (xOffset * 2 - 1) * 0.1F, 0.0F, 0.0F); - } - - GlStateManager.pushMatrix(); - this.hurtCameraEffect(partialTicks); - if (this.mc.gameSettings.viewBobbing) { - this.setupViewBobbing(partialTicks); - } - - boolean flag = this.mc.getRenderViewEntity() instanceof EntityLivingBase - && ((EntityLivingBase) this.mc.getRenderViewEntity()).isPlayerSleeping(); - if (this.mc.gameSettings.thirdPersonView == 0 && !flag && !this.mc.gameSettings.hideGUI - && !this.mc.playerController.isSpectator()) { - this.enableLightmap(); - this.itemRenderer.renderItemInFirstPerson(partialTicks); - this.disableLightmap(); - } - - GlStateManager.popMatrix(); - if (this.mc.gameSettings.thirdPersonView == 0 && !flag) { - this.itemRenderer.renderOverlays(partialTicks); - this.hurtCameraEffect(partialTicks); - } - - if (this.mc.gameSettings.viewBobbing) { - this.setupViewBobbing(partialTicks); - } - - } - } - - public void disableLightmap() { - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.disableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - } - - public void enableLightmap() { - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.enableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - } - - public static void disableLightmapStatic() { - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.disableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - } - - public static void enableLightmapStatic() { - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.enableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - } - - /**+ - * Recompute a random value that is applied to block color in - * updateLightmap() - */ - private void updateTorchFlicker() { - this.torchFlickerDX = (float) ((double) this.torchFlickerDX - + (Math.random() - Math.random()) * Math.random() * Math.random()); - this.torchFlickerDX = (float) ((double) this.torchFlickerDX * 0.9D); - this.torchFlickerX += (this.torchFlickerDX - this.torchFlickerX) * 1.0F; - this.lightmapUpdateNeeded = true; - } - - private void updateLightmap(float partialTicks) { - if (this.lightmapUpdateNeeded) { - WorldClient worldclient = this.mc.theWorld; - if (worldclient != null) { - float f = worldclient.getSunBrightness(1.0F); - float f1 = f * 0.95F + 0.05F; - - for (int i = 0; i < 256; ++i) { - float f2 = worldclient.provider.getLightBrightnessTable()[i / 16] * f1; - float f3 = worldclient.provider.getLightBrightnessTable()[i % 16] - * (this.torchFlickerX * 0.1F + 1.5F); - if (worldclient.getLastLightningBolt() > 0) { - f2 = worldclient.provider.getLightBrightnessTable()[i / 16]; - } - - float f4 = f2 * (f * 0.65F + 0.35F); - float f5 = f2 * (f * 0.65F + 0.35F); - float f6 = f3 * ((f3 * 0.6F + 0.4F) * 0.6F + 0.4F); - float f7 = f3 * (f3 * f3 * 0.6F + 0.4F); - float f8 = f4 + f3; - float f9 = f5 + f6; - float f10 = f2 + f7; - f8 = f8 * 0.96F + 0.03F; - f9 = f9 * 0.96F + 0.03F; - f10 = f10 * 0.96F + 0.03F; - if (this.bossColorModifier > 0.0F) { - float f11 = this.bossColorModifierPrev - + (this.bossColorModifier - this.bossColorModifierPrev) * partialTicks; - f8 = f8 * (1.0F - f11) + f8 * 0.7F * f11; - f9 = f9 * (1.0F - f11) + f9 * 0.6F * f11; - f10 = f10 * (1.0F - f11) + f10 * 0.6F * f11; - } - - if (worldclient.provider.getDimensionId() == 1) { - f8 = 0.22F + f3 * 0.75F; - f9 = 0.28F + f6 * 0.75F; - f10 = 0.25F + f7 * 0.75F; - } - - if (this.mc.thePlayer.isPotionActive(Potion.nightVision)) { - float f15 = this.getNightVisionBrightness(this.mc.thePlayer, partialTicks); - float f12 = 1.0F / f8; - if (f12 > 1.0F / f9) { - f12 = 1.0F / f9; - } - - if (f12 > 1.0F / f10) { - f12 = 1.0F / f10; - } - - f8 = f8 * (1.0F - f15) + f8 * f12 * f15; - f9 = f9 * (1.0F - f15) + f9 * f12 * f15; - f10 = f10 * (1.0F - f15) + f10 * f12 * f15; - } - - if (f8 > 1.0F) { - f8 = 1.0F; - } - - if (f9 > 1.0F) { - f9 = 1.0F; - } - - if (f10 > 1.0F) { - f10 = 1.0F; - } - - float f16 = this.mc.gameSettings.gammaSetting; - float f17 = 1.0F - f8; - float f13 = 1.0F - f9; - float f14 = 1.0F - f10; - f17 = 1.0F - f17 * f17 * f17 * f17; - f13 = 1.0F - f13 * f13 * f13 * f13; - f14 = 1.0F - f14 * f14 * f14 * f14; - f8 = f8 * (1.0F - f16) + f17 * f16; - f9 = f9 * (1.0F - f16) + f13 * f16; - f10 = f10 * (1.0F - f16) + f14 * f16; - f8 = f8 * 0.96F + 0.03F; - f9 = f9 * 0.96F + 0.03F; - f10 = f10 * 0.96F + 0.03F; - if (f8 > 1.0F) { - f8 = 1.0F; - } - - if (f9 > 1.0F) { - f9 = 1.0F; - } - - if (f10 > 1.0F) { - f10 = 1.0F; - } - - if (f8 < 0.0F) { - f8 = 0.0F; - } - - if (f9 < 0.0F) { - f9 = 0.0F; - } - - if (f10 < 0.0F) { - f10 = 0.0F; - } - - short short1 = 255; - int j = (int) (f8 * 255.0F); - int k = (int) (f9 * 255.0F); - int l = (int) (f10 * 255.0F); - this.lightmapColors[i] = short1 << 24 | j | k << 8 | l << 16; - } - - this.lightmapTexture.updateDynamicTexture(); - - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - this.mc.getTextureManager().bindTexture(this.locationLightMap); - if (mc.gameSettings.fancyGraphics || mc.gameSettings.ambientOcclusion > 0 - || DynamicLightsStateManager.isDynamicLightsRender()) { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } else { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - - this.lightmapUpdateNeeded = false; - } - } - } - - private float getNightVisionBrightness(EntityLivingBase entitylivingbaseIn, float partialTicks) { - int i = entitylivingbaseIn.getActivePotionEffect(Potion.nightVision).getDuration(); - return i > 200 ? 1.0F : 0.7F + MathHelper.sin(((float) i - partialTicks) * 3.1415927F * 0.2F) * 0.3F; - } - - public void func_181560_a(float parFloat1, long parLong1) { - boolean flag = Display.isActive() || mc.gameSettings.touchscreen; - if (!flag && this.mc.gameSettings.pauseOnLostFocus - && (!this.mc.gameSettings.touchscreen || !PointerInputAbstraction.getVCursorButtonDown(1))) { - if (Minecraft.getSystemTime() - this.prevFrameTime > 500L) { - this.mc.displayInGameMenu(); - } - } else { - this.prevFrameTime = Minecraft.getSystemTime(); - } - - if (this.mc.inGameHasFocus && flag) { - this.mc.mouseHelper.mouseXYChange(); - float f = this.mc.gameSettings.mouseSensitivity * 0.6F + 0.2F; - if (this.mc.gameSettings.keyBindZoomCamera.isKeyDown()) { - f *= 0.7f; - } - float f1 = f * f * f * 8.0F; - float f2 = (float) this.mc.mouseHelper.deltaX * f1; - float f3 = (float) this.mc.mouseHelper.deltaY * f1; - byte b0 = 1; - if (this.mc.gameSettings.invertMouse) { - b0 = -1; - } - - if (this.mc.gameSettings.smoothCamera) { - this.smoothCamYaw += f2; - this.smoothCamPitch += f3; - float f4 = parFloat1 - this.smoothCamPartialTicks; - this.smoothCamPartialTicks = parFloat1; - f2 = this.smoothCamFilterX * f4; - f3 = this.smoothCamFilterY * f4; - this.mc.thePlayer.setAngles(f2, f3 * (float) b0); - } else { - this.smoothCamYaw = 0.0F; - this.smoothCamPitch = 0.0F; - this.mc.thePlayer.setAngles(f2, f3 * (float) b0); - } - } - - if (!this.mc.skipRenderWorld) { - anaglyphEnable = this.mc.gameSettings.anaglyph; - final ScaledResolution scaledresolution = mc.scaledResolution; - int l = scaledresolution.getScaledWidth(); - int i1 = scaledresolution.getScaledHeight(); - final int j1 = PointerInputAbstraction.getVCursorX() * l / this.mc.displayWidth; - final int k1 = i1 - PointerInputAbstraction.getVCursorY() * i1 / this.mc.displayHeight - 1; - int l1 = this.mc.gameSettings.limitFramerate; - if (this.mc.theWorld != null) { - int i = Math.min(Minecraft.getDebugFPS(), l1); - i = Math.max(i, 60); - long j = System.nanoTime() - parLong1; - long k = Math.max((long) (1000000000 / i / 4) - j, 0L); - this.renderWorld(parFloat1, System.nanoTime() + k); - this.renderEndNanoTime = System.nanoTime(); - final boolean b = !this.mc.gameSettings.hideGUI || this.mc.currentScreen != null; - if (b) { - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - long framebufferAge = this.overlayFramebuffer.getAge(); - if (framebufferAge == -1l || framebufferAge > (Minecraft.getDebugFPS() < 25 ? 125l : 75l)) { - this.overlayFramebuffer.beginRender(mc.displayWidth, mc.displayHeight); - GlStateManager.colorMask(true, true, true, true); - GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GlStateManager.enableOverlayFramebufferBlending(); - if (b) { - this.mc.ingameGUI.renderGameOverlay(parFloat1); - } - GlStateManager.disableOverlayFramebufferBlending(); - this.overlayFramebuffer.endRender(); - } - } - if (b) { - this.setupOverlayRendering(); - GlStateManager.disableLighting(); - GlStateManager.enableBlend(); - if (Minecraft.isFancyGraphicsEnabled()) { - this.mc.ingameGUI.renderVignette(this.mc.thePlayer.getBrightness(parFloat1), l, i1); - } - this.mc.ingameGUI.renderGameOverlayCrosshairs(l, i1); - GlStateManager.bindTexture(this.overlayFramebuffer.getTexture()); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.enableAlpha(); - GlStateManager.disableDepth(); - GlStateManager.depthMask(false); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(0.0D, (double) i1, -90.0D).tex(0.0D, 0.0D).endVertex(); - worldrenderer.pos((double) l, (double) i1, -90.0D).tex(1.0D, 0.0D).endVertex(); - worldrenderer.pos((double) l, 0.0D, -90.0D).tex(1.0D, 1.0D).endVertex(); - worldrenderer.pos(0.0D, 0.0D, -90.0D).tex(0.0D, 1.0D).endVertex(); - tessellator.draw(); - GlStateManager.depthMask(true); - GlStateManager.enableDepth(); - GlStateManager.disableBlend(); - if (this.mc.gameSettings.hudPlayer) { // give the player model HUD good fps - this.mc.ingameGUI.drawEaglerPlayerOverlay(l - 3, - 3 + this.mc.ingameGUI.overlayDebug.playerOffset, parFloat1); - } - } - } else { - GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - this.setupOverlayRendering(); - this.renderEndNanoTime = System.nanoTime(); - } - - this.mc.notifRenderer.renderOverlay(j1, k1); - - if (this.mc.currentScreen != null) { - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - float f = 1.0f; - final float[] ff = new float[] { 1.0f }; - - try { - f = mc.currentScreen.getEaglerScale(); - int mx, my; - if (f == 1.0f) { - mx = j1; - my = k1; - } else { - mx = GuiScreen.applyEaglerScale(f, j1, l); - my = GuiScreen.applyEaglerScale(f, k1, i1); - GlStateManager.pushMatrix(); - float fff = (1.0f - f) * 0.5f; - GlStateManager.translate(fff * l, fff * i1, 0.0f); - GlStateManager.scale(f, f, f); - } - ff[0] = f; - this.mc.currentScreen.drawScreen(mx, my, parFloat1); - if (f != 1.0f) { - GlStateManager.popMatrix(); - } - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Rendering screen"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Screen render details"); - crashreportcategory.addCrashSectionCallable("Screen name", new Callable() { - public String call() throws Exception { - return EntityRenderer.this.mc.currentScreen.getClass().getName(); - } - }); - crashreportcategory.addCrashSectionCallable("Mouse location", new Callable() { - public String call() throws Exception { - return HString.format("Scaled: (%d, %d). Absolute: (%d, %d)", - new Object[] { Integer.valueOf(j1), Integer.valueOf(k1), - Integer.valueOf(PointerInputAbstraction.getVCursorX()), - Integer.valueOf(PointerInputAbstraction.getVCursorY()) }); - } - }); - crashreportcategory.addCrashSectionCallable("Screen size", new Callable() { - public String call() throws Exception { - return HString.format("Scaled: (%d, %d). Absolute: (%d, %d). Scale factor of %d", - new Object[] { Integer.valueOf(scaledresolution.getScaledWidth()), - Integer.valueOf(scaledresolution.getScaledHeight()), - Integer.valueOf(EntityRenderer.this.mc.displayWidth), - Integer.valueOf(EntityRenderer.this.mc.displayHeight), - Integer.valueOf(scaledresolution.getScaleFactor()) }); - } - }); - crashreportcategory.addCrashSectionCallable("Eagler Scale", new Callable() { - public String call() throws Exception { - return "" + ff[0]; - } - }); - throw new ReportedException(crashreport); - } - - this.mc.voiceOverlay.drawOverlay(); - } - } - } - - public void renderStreamIndicator(float partialTicks) { - } - - private boolean isDrawBlockOutline() { - if (!this.drawBlockOutline) { - return false; - } else { - Entity entity = this.mc.getRenderViewEntity(); - boolean flag = entity instanceof EntityPlayer && !this.mc.gameSettings.hideGUI; - if (flag && !((EntityPlayer) entity).capabilities.allowEdit) { - ItemStack itemstack = ((EntityPlayer) entity).getCurrentEquippedItem(); - if (this.mc.objectMouseOver != null - && this.mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - BlockPos blockpos = this.mc.objectMouseOver.getBlockPos(); - Block block = this.mc.theWorld.getBlockState(blockpos).getBlock(); - if (this.mc.playerController.getCurrentGameType() == WorldSettings.GameType.SPECTATOR) { - flag = block.hasTileEntity() && this.mc.theWorld.getTileEntity(blockpos) instanceof IInventory; - } else { - flag = itemstack != null && (itemstack.canDestroy(block) || itemstack.canPlaceOn(block)); - } - } - } - - return flag; - } - } - - private void renderWorldDirections(float partialTicks) { - if (this.mc.gameSettings.showDebugInfo && !this.mc.gameSettings.hideGUI && !this.mc.thePlayer.hasReducedDebug() - && !this.mc.gameSettings.reducedDebugInfo) { - Entity entity = this.mc.getRenderViewEntity(); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - EaglercraftGPU.glLineWidth(1.0F); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - GlStateManager.pushMatrix(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - this.orientCamera(partialTicks); - GlStateManager.translate(0.0F, entity.getEyeHeight(), 0.0F); - RenderGlobal.func_181563_a(new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.005D, 1.0E-4D, 1.0E-4D), 255, 0, 0, 255); - RenderGlobal.func_181563_a(new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0E-4D, 1.0E-4D, 0.005D), 0, 0, 255, 255); - RenderGlobal.func_181563_a(new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0E-4D, 0.0033D, 1.0E-4D), 0, 255, 0, 255); - GlStateManager.popMatrix(); - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - } - - public void renderWorld(float partialTicks, long finishTimeNano) { - this.updateLightmap(partialTicks); - if (this.mc.getRenderViewEntity() == null) { - this.mc.setRenderViewEntity(this.mc.thePlayer); - } - - this.getMouseOver(partialTicks); - - boolean fxaa = !this.mc.gameSettings.shaders - && ((this.mc.gameSettings.fxaa == 0 && this.mc.gameSettings.fancyGraphics) - || this.mc.gameSettings.fxaa == 1); - if (fxaa) { - EffectPipelineFXAA.begin(this.mc.displayWidth, this.mc.displayHeight); - } - - VoiceTagRenderer.clearTagsDrawnSet(); - - GlStateManager.enableDepth(); - GlStateManager.enableAlpha(); - GlStateManager.alphaFunc(GL_GREATER, 0.5F); - boolean dlights = DynamicLightsStateManager.isDynamicLightsRender(); - if (dlights) { - updateDynamicLightListEagler(partialTicks); - } - if (this.mc.gameSettings.anaglyph && !this.mc.gameSettings.shaders) { - if (dlights) { - GlStateManager.enableExtensionPipeline(); - } - try { - anaglyphField = 0; - GlStateManager.colorMask(false, true, true, false); - this.renderWorldPass(0, partialTicks, finishTimeNano); - anaglyphField = 1; - GlStateManager.colorMask(true, false, false, false); - this.renderWorldPass(1, partialTicks, finishTimeNano); - GlStateManager.colorMask(true, true, true, false); - } finally { - if (dlights) { - GlStateManager.disableExtensionPipeline(); - } - } - } else { - if (this.mc.gameSettings.shaders) { - try { - this.eaglercraftShaders(partialTicks, finishTimeNano); - } catch (Throwable t) { - logger.error("Exception caught running deferred render!"); - logger.error(t); - EaglerDeferredPipeline.instance.resetContextStateAfterException(); - logger.error("Suspending shaders..."); - EaglerDeferredPipeline.isSuspended = true; - - } - mc.effectRenderer.acceleratedParticleRenderer = EffectRenderer.vanillaAcceleratedParticleRenderer; - } else { - mc.effectRenderer.acceleratedParticleRenderer = EaglercraftGPU.checkInstancingCapable() - ? EffectRenderer.vanillaAcceleratedParticleRenderer - : null; - if (dlights) { - GlStateManager.enableExtensionPipeline(); - } - try { - this.renderWorldPass(2, partialTicks, finishTimeNano); - } finally { - if (dlights) { - GlStateManager.disableExtensionPipeline(); - } - } - } - } - - if (fxaa) { - EffectPipelineFXAA.end(); - } - } - - private void renderWorldPass(int pass, float partialTicks, long finishTimeNano) { - RenderGlobal renderglobal = this.mc.renderGlobal; - EffectRenderer effectrenderer = this.mc.effectRenderer; - boolean flag = this.isDrawBlockOutline(); - GlStateManager.enableCull(); - GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); - this.updateFogColor(partialTicks); - GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - this.setupCameraTransform(partialTicks, pass); - boolean isDynamicLights = DynamicLightsStateManager.isDynamicLightsRender(); - if (isDynamicLights) { - DynamicLightsStateManager.setupInverseViewMatrix(); - } - ActiveRenderInfo.updateRenderInfo(this.mc.thePlayer, this.mc.gameSettings.thirdPersonView == 2); - Frustum frustum = new Frustum(); - Entity entity = this.mc.getRenderViewEntity(); - double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; - double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; - double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; - TileEntityRendererDispatcher.staticPlayerX = d0; // hack, needed for some eagler stuff - TileEntityRendererDispatcher.staticPlayerY = d1; - TileEntityRendererDispatcher.staticPlayerZ = d2; - frustum.setPosition(d0, d1, d2); - if (this.mc.gameSettings.renderDistanceChunks >= 4) { - this.setupFog(-1, partialTicks); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - float vigg = this.getFOVModifier(partialTicks, true); - GlStateManager.gluPerspective(vigg, (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, - this.farPlaneDistance * 4.0F); - GlStateManager.matrixMode(GL_MODELVIEW); - renderglobal.renderSky(partialTicks, pass); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.gluPerspective(vigg, (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, - this.farPlaneDistance * MathHelper.SQRT_2); - GlStateManager.matrixMode(GL_MODELVIEW); - } - - this.setupFog(0, partialTicks); - GlStateManager.shadeModel(GL_SMOOTH); - if (entity.posY + (double) entity.getEyeHeight() < 128.0D) { - this.renderCloudsCheck(renderglobal, partialTicks, pass); - } - - this.setupFog(0, partialTicks); - this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - RenderHelper.disableStandardItemLighting(); - renderglobal.setupTerrain(entity, (double) partialTicks, frustum, this.frameCount++, - this.mc.thePlayer.isSpectator()); - if (pass == 0 || pass == 2) { - this.mc.renderGlobal.updateChunks(finishTimeNano); - } - - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.pushMatrix(); - GlStateManager.disableAlpha(); - GlStateManager.disableBlend(); - renderglobal.renderBlockLayer(EnumWorldBlockLayer.SOLID, (double) partialTicks, pass, entity); - GlStateManager.enableAlpha(); - renderglobal.renderBlockLayer(EnumWorldBlockLayer.CUTOUT_MIPPED, (double) partialTicks, pass, entity); - this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); - renderglobal.renderBlockLayer(EnumWorldBlockLayer.CUTOUT, (double) partialTicks, pass, entity); - this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - GlStateManager.shadeModel(GL_FLAT); - if (!this.debugView) { - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.popMatrix(); - GlStateManager.pushMatrix(); - RenderHelper.enableStandardItemLighting(); - renderglobal.renderEntities(entity, frustum, partialTicks); - RenderHelper.disableStandardItemLighting(); - this.disableLightmap(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.popMatrix(); - GlStateManager.pushMatrix(); - if (this.mc.objectMouseOver != null && entity.isInsideOfMaterial(Material.water) && flag) { - EntityPlayer entityplayer = (EntityPlayer) entity; - GlStateManager.disableAlpha(); - if (isDynamicLights) { - GlStateManager.disableExtensionPipeline(); - } - renderglobal.drawSelectionBox(entityplayer, this.mc.objectMouseOver, 0, partialTicks); - GlStateManager.enableAlpha(); - if (isDynamicLights) { - GlStateManager.enableExtensionPipeline(); - } - } - } - - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.popMatrix(); - if (flag && this.mc.objectMouseOver != null && !entity.isInsideOfMaterial(Material.water)) { - EntityPlayer entityplayer1 = (EntityPlayer) entity; - GlStateManager.disableAlpha(); - if (isDynamicLights) { - GlStateManager.disableExtensionPipeline(); - } - renderglobal.drawSelectionBox(entityplayer1, this.mc.objectMouseOver, 0, partialTicks); - GlStateManager.enableAlpha(); - if (isDynamicLights) { - GlStateManager.enableExtensionPipeline(); - } - } - - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, 1, 1, 0); - this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); - renderglobal.drawBlockDamageTexture(Tessellator.getInstance(), Tessellator.getInstance().getWorldRenderer(), - entity, partialTicks); - this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); - GlStateManager.disableBlend(); - if (!this.debugView) { - this.enableLightmap(); - effectrenderer.renderLitParticles(entity, partialTicks); - RenderHelper.disableStandardItemLighting(); - this.setupFog(0, partialTicks); - if (isDynamicLights) { - DynamicLightsStateManager.bindAcceleratedEffectRenderer(effectrenderer); - DynamicLightsStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); - } - effectrenderer.renderParticles(entity, partialTicks, 2); - if (isDynamicLights) { - effectrenderer.acceleratedParticleRenderer = null; - } - this.disableLightmap(); - } - - GlStateManager.depthMask(false); - GlStateManager.enableCull(); - this.renderRainSnow(partialTicks); - GlStateManager.depthMask(true); - renderglobal.renderWorldBorder(entity, partialTicks); - GlStateManager.disableBlend(); - GlStateManager.enableCull(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - this.setupFog(0, partialTicks); - GlStateManager.enableBlend(); - GlStateManager.depthMask(false); - this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - GlStateManager.shadeModel(GL_SMOOTH); - renderglobal.renderBlockLayer(EnumWorldBlockLayer.TRANSLUCENT, (double) partialTicks, pass, entity); - GlStateManager.shadeModel(GL_FLAT); - GlStateManager.depthMask(true); - GlStateManager.enableCull(); - GlStateManager.disableBlend(); - GlStateManager.disableFog(); - if (entity.posY + (double) entity.getEyeHeight() >= 128.0D) { - this.renderCloudsCheck(renderglobal, partialTicks, pass); - } - - if (this.renderHand) { - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - this.renderHand(partialTicks, pass); - this.renderWorldDirections(partialTicks); - } - - } - - private void updateDynamicLightListEagler(float partialTicks) { - DynamicLightsStateManager.clearRenderList(); - Entity entity = this.mc.getRenderViewEntity(); - double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; - double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; - double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; - AxisAlignedBB entityAABB = new AxisAlignedBB(d0 - 48.0, d1 - 32.0, d2 - 48.0, d0 + 48.0, d1 + 32.0, d2 + 48.0); - List entities = this.mc.theWorld.getEntitiesWithinAABB(Entity.class, entityAABB); - for (int i = 0, l = entities.size(); i < l; ++i) { - entities.get(i).renderDynamicLightsEaglerSimple(partialTicks); - } - DynamicLightsStateManager.commitLightSourceBuckets(d0, d1, d2); - } - - private void renderCloudsCheck(RenderGlobal renderGlobalIn, float partialTicks, int pass) { - if (this.mc.gameSettings.func_181147_e() != 0) { - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.gluPerspective(this.getFOVModifier(partialTicks, true), - (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, this.farPlaneDistance * 4.0F); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.pushMatrix(); - this.setupFog(0, partialTicks); - renderGlobalIn.renderClouds(partialTicks, pass); - GlStateManager.disableFog(); - GlStateManager.popMatrix(); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.gluPerspective(this.getFOVModifier(partialTicks, true), - (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, - this.farPlaneDistance * MathHelper.SQRT_2); - GlStateManager.matrixMode(GL_MODELVIEW); - } - - } - private void addRainParticles() { float f = this.mc.theWorld.getRainStrength(1.0F); if (!this.mc.gameSettings.fancyGraphics) { @@ -1446,453 +386,12 @@ public class EntityRenderer implements IResourceManagerReloadListener { } } - /**+ - * Render rain and snow - */ - protected void renderRainSnow(float partialTicks) { - float f = this.mc.theWorld.getRainStrength(partialTicks); - if (f > 0.0F) { - boolean df = DeferredStateManager.isInDeferredPass(); - this.enableLightmap(); - Entity entity = this.mc.getRenderViewEntity(); - WorldClient worldclient = this.mc.theWorld; - int i = MathHelper.floor_double(entity.posX); - int j = MathHelper.floor_double(entity.posY); - int k = MathHelper.floor_double(entity.posZ); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - GlStateManager.disableCull(); - if (!df) { - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - if (DynamicLightsStateManager.isInDynamicLightsPass()) { - DynamicLightsStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); - } - } else { - GlStateManager.enableAlpha(); - DeferredStateManager.setHDRTranslucentPassBlendFunc(); - DeferredStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); - GlStateManager.alphaFunc(GL_GREATER, 0.01F); - GlStateManager.depthMask(false); - GlStateManager.enableDepth(); - EaglerDeferredPipeline.instance.setForwardRenderLightFactors(0.65f, - 4.75f - MathHelper.clamp_float(DeferredStateManager.getSunHeight() * 8.0f - 3.0f, 0.0f, 4.0f), - 1.0f, 0.03f); - } - EaglercraftGPU.glNormal3f(0.0F, 1.0F, 0.0F); - double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; - double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; - double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; - int l = MathHelper.floor_double(d1); - byte b0 = 5; - if (df) { - b0 = 8; - } else if (this.mc.gameSettings.fancyGraphics) { - b0 = 10; - } - - byte b1 = -1; - float f1 = (float) this.rendererUpdateCount + partialTicks; - worldrenderer.setTranslation(-d0, -d1, -d2); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int i1 = k - b0; i1 <= k + b0; ++i1) { - for (int j1 = i - b0; j1 <= i + b0; ++j1) { - int k1 = (i1 - k + 16) * 32 + j1 - i + 16; - double d3 = (double) this.rainXCoords[k1] * 0.5D; - double d4 = (double) this.rainYCoords[k1] * 0.5D; - blockpos$mutableblockpos.func_181079_c(j1, 0, i1); - BiomeGenBase biomegenbase = worldclient.getBiomeGenForCoords(blockpos$mutableblockpos); - if (biomegenbase.canSpawnLightningBolt() || biomegenbase.getEnableSnow()) { - int l1 = worldclient.getPrecipitationHeight(blockpos$mutableblockpos).getY(); - int i2 = j - b0; - int j2 = j + b0; - if (i2 < l1) { - i2 = l1; - } - - if (j2 < l1) { - j2 = l1; - } - - int k2 = l1; - if (l1 < l) { - k2 = l; - } - - if (i2 != j2) { - this.random - .setSeed((long) (j1 * j1 * 3121 + j1 * 45238971 ^ i1 * i1 * 418711 + i1 * 13761)); - blockpos$mutableblockpos.func_181079_c(j1, i2, i1); - float f2 = biomegenbase.getFloatTemperature(blockpos$mutableblockpos); - if (f2 >= 0.15F) { - if (b1 != 0) { - if (b1 >= 0) { - tessellator.draw(); - } - - b1 = 0; - this.mc.getTextureManager() - .bindTexture(df ? new ResourceLocation("eagler:glsl/deferred/rain.png") - : locationRainPng); - if (df) { - DeferredStateManager.setRoughnessConstant(0.5f); - DeferredStateManager.setMetalnessConstant(0.05f); - DeferredStateManager.setEmissionConstant(1.0f); - GlStateManager.color(0.8F, 0.8F, 1.0F, 0.25F); - } - worldrenderer.begin(7, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP); - } - - double d5 = ((double) (this.rendererUpdateCount + j1 * j1 * 3121 + j1 * 45238971 - + i1 * i1 * 418711 + i1 * 13761 & 31) + (double) partialTicks) / 32.0D - * (3.0D + this.random.nextDouble()); - double d6 = (double) ((float) j1 + 0.5F) - entity.posX; - double d7 = (double) ((float) i1 + 0.5F) - entity.posZ; - float f3 = MathHelper.sqrt_double(d6 * d6 + d7 * d7) / (float) b0; - float f4 = ((1.0F - f3 * f3) * 0.5F + 0.5F) * f; - blockpos$mutableblockpos.func_181079_c(j1, k2, i1); - int l2 = worldclient.getCombinedLight(blockpos$mutableblockpos, 0); - int i3 = l2 >> 16 & '\uffff'; - int j3 = l2 & '\uffff'; - worldrenderer.pos((double) j1 - d3 + 0.5D, (double) i2, (double) i1 - d4 + 0.5D) - .tex(0.0D, (double) i2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) - .lightmap(i3, j3).endVertex(); - worldrenderer.pos((double) j1 + d3 + 0.5D, (double) i2, (double) i1 + d4 + 0.5D) - .tex(1.0D, (double) i2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) - .lightmap(i3, j3).endVertex(); - worldrenderer.pos((double) j1 + d3 + 0.5D, (double) j2, (double) i1 + d4 + 0.5D) - .tex(1.0D, (double) j2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) - .lightmap(i3, j3).endVertex(); - worldrenderer.pos((double) j1 - d3 + 0.5D, (double) j2, (double) i1 - d4 + 0.5D) - .tex(0.0D, (double) j2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) - .lightmap(i3, j3).endVertex(); - } else { - if (b1 != 1) { - if (b1 >= 0) { - tessellator.draw(); - } - - b1 = 1; - this.mc.getTextureManager().bindTexture(locationSnowPng); - if (df) { - DeferredStateManager.setRoughnessConstant(0.7f); - DeferredStateManager.setMetalnessConstant(0.05f); - DeferredStateManager.setEmissionConstant(1.0f); - GlStateManager.color(1.3F, 1.3F, 1.3F, 0.5F); - } - worldrenderer.begin(7, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP); - } - - double d8 = (double) (((float) (this.rendererUpdateCount & 511) + partialTicks) - / 512.0F); - double d9 = this.random.nextDouble() - + (double) f1 * 0.01D * (double) ((float) this.random.nextGaussian()); - double d10 = this.random.nextDouble() - + (double) (f1 * (float) this.random.nextGaussian()) * 0.001D; - double d11 = (double) ((float) j1 + 0.5F) - entity.posX; - double d12 = (double) ((float) i1 + 0.5F) - entity.posZ; - float f6 = MathHelper.sqrt_double(d11 * d11 + d12 * d12) / (float) b0; - float f5 = ((1.0F - f6 * f6) * 0.3F + 0.5F) * f; - blockpos$mutableblockpos.func_181079_c(j1, k2, i1); - int k3 = (worldclient.getCombinedLight(blockpos$mutableblockpos, 0) * 3 + 15728880) / 4; - int l3 = k3 >> 16 & '\uffff'; - int i4 = k3 & '\uffff'; - worldrenderer.pos((double) j1 - d3 + 0.5D, (double) i2, (double) i1 - d4 + 0.5D) - .tex(0.0D + d9, (double) i2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) - .lightmap(l3, i4).endVertex(); - worldrenderer.pos((double) j1 + d3 + 0.5D, (double) i2, (double) i1 + d4 + 0.5D) - .tex(1.0D + d9, (double) i2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) - .lightmap(l3, i4).endVertex(); - worldrenderer.pos((double) j1 + d3 + 0.5D, (double) j2, (double) i1 + d4 + 0.5D) - .tex(1.0D + d9, (double) j2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) - .lightmap(l3, i4).endVertex(); - worldrenderer.pos((double) j1 - d3 + 0.5D, (double) j2, (double) i1 - d4 + 0.5D) - .tex(0.0D + d9, (double) j2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) - .lightmap(l3, i4).endVertex(); - } - } - } - } - } - - if (b1 >= 0) { - tessellator.draw(); - } - - worldrenderer.setTranslation(0.0D, 0.0D, 0.0D); - GlStateManager.enableCull(); - if (!df) { - GlStateManager.disableBlend(); - } else { - GlStateManager.disableAlpha(); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - DeferredStateManager.setDefaultMaterialConstants(); - GlStateManager.depthMask(true); - GlStateManager.disableDepth(); - EaglerDeferredPipeline.instance.setForwardRenderLightFactors(1.0f, 1.0f, 1.0f, 1.0f); - } - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - this.disableLightmap(); - } + public void disableLightmap() { + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.disableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); } - /**+ - * Setup orthogonal projection for rendering GUI screen overlays - */ - public void setupOverlayRendering() { - ScaledResolution scaledresolution = mc.scaledResolution; - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.loadIdentity(); - GlStateManager.ortho(0.0D, scaledresolution.getScaledWidth_double(), scaledresolution.getScaledHeight_double(), - 0.0D, 1000.0D, 3000.0D); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.loadIdentity(); - GlStateManager.translate(0.0F, 0.0F, -2000.0F); - } - - /**+ - * calculates fog and calls glClearColor - */ - private void updateFogColor(float partialTicks) { - WorldClient worldclient = this.mc.theWorld; - Entity entity = this.mc.getRenderViewEntity(); - float f = 0.25F + 0.75F * (float) this.mc.gameSettings.renderDistanceChunks / 32.0F; - f = 1.0F - (float) Math.pow((double) f, 0.25D); - Vec3 vec3 = worldclient.getSkyColor(this.mc.getRenderViewEntity(), partialTicks); - float f1 = (float) vec3.xCoord; - float f2 = (float) vec3.yCoord; - float f3 = (float) vec3.zCoord; - Vec3 vec31 = worldclient.getFogColor(partialTicks); - this.fogColorRed = (float) vec31.xCoord; - this.fogColorGreen = (float) vec31.yCoord; - this.fogColorBlue = (float) vec31.zCoord; - if (this.mc.gameSettings.renderDistanceChunks >= 4) { - double d0 = -1.0D; - Vec3 vec32 = MathHelper.sin(worldclient.getCelestialAngleRadians(partialTicks)) > 0.0F - ? new Vec3(d0, 0.0D, 0.0D) - : new Vec3(1.0D, 0.0D, 0.0D); - float f5 = (float) entity.getLook(partialTicks).dotProduct(vec32); - if (f5 < 0.0F) { - f5 = 0.0F; - } - - if (f5 > 0.0F) { - float[] afloat = worldclient.provider - .calcSunriseSunsetColors(worldclient.getCelestialAngle(partialTicks), partialTicks); - if (afloat != null) { - f5 = f5 * afloat[3]; - this.fogColorRed = this.fogColorRed * (1.0F - f5) + afloat[0] * f5; - this.fogColorGreen = this.fogColorGreen * (1.0F - f5) + afloat[1] * f5; - this.fogColorBlue = this.fogColorBlue * (1.0F - f5) + afloat[2] * f5; - } - } - } - - this.fogColorRed += (f1 - this.fogColorRed) * f; - this.fogColorGreen += (f2 - this.fogColorGreen) * f; - this.fogColorBlue += (f3 - this.fogColorBlue) * f; - float f8 = worldclient.getRainStrength(partialTicks); - if (f8 > 0.0F) { - float f4 = 1.0F - f8 * 0.5F; - float f10 = 1.0F - f8 * 0.4F; - this.fogColorRed *= f4; - this.fogColorGreen *= f4; - this.fogColorBlue *= f10; - } - - float f9 = worldclient.getThunderStrength(partialTicks); - if (f9 > 0.0F) { - float f11 = 1.0F - f9 * 0.5F; - this.fogColorRed *= f11; - this.fogColorGreen *= f11; - this.fogColorBlue *= f11; - } - - Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.mc.theWorld, entity, partialTicks); - if (this.cloudFog) { - Vec3 vec33 = worldclient.getCloudColour(partialTicks); - this.fogColorRed = (float) vec33.xCoord; - this.fogColorGreen = (float) vec33.yCoord; - this.fogColorBlue = (float) vec33.zCoord; - } else if (block.getMaterial() == Material.water) { - float f12 = (float) EnchantmentHelper.getRespiration(entity) * 0.2F; - if (entity instanceof EntityLivingBase - && ((EntityLivingBase) entity).isPotionActive(Potion.waterBreathing)) { - f12 = f12 * 0.3F + 0.6F; - } - - this.fogColorRed = 0.02F + f12; - this.fogColorGreen = 0.02F + f12; - this.fogColorBlue = 0.2F + f12; - } else if (block.getMaterial() == Material.lava) { - this.fogColorRed = 0.6F; - this.fogColorGreen = 0.1F; - this.fogColorBlue = 0.0F; - } - - float f13 = this.fogColor2 + (this.fogColor1 - this.fogColor2) * partialTicks; - this.fogColorRed *= f13; - this.fogColorGreen *= f13; - this.fogColorBlue *= f13; - double d1 = (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks) - * worldclient.provider.getVoidFogYFactor(); - if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(Potion.blindness)) { - int i = ((EntityLivingBase) entity).getActivePotionEffect(Potion.blindness).getDuration(); - if (i < 20) { - d1 *= (double) (1.0F - (float) i / 20.0F); - } else { - d1 = 0.0D; - } - } - - if (d1 < 1.0D) { - if (d1 < 0.0D) { - d1 = 0.0D; - } - - d1 = d1 * d1; - this.fogColorRed = (float) ((double) this.fogColorRed * d1); - this.fogColorGreen = (float) ((double) this.fogColorGreen * d1); - this.fogColorBlue = (float) ((double) this.fogColorBlue * d1); - } - - if (this.bossColorModifier > 0.0F) { - float f14 = this.bossColorModifierPrev - + (this.bossColorModifier - this.bossColorModifierPrev) * partialTicks; - this.fogColorRed = this.fogColorRed * (1.0F - f14) + this.fogColorRed * 0.7F * f14; - this.fogColorGreen = this.fogColorGreen * (1.0F - f14) + this.fogColorGreen * 0.6F * f14; - this.fogColorBlue = this.fogColorBlue * (1.0F - f14) + this.fogColorBlue * 0.6F * f14; - } - - if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(Potion.nightVision)) { - float f15 = this.getNightVisionBrightness((EntityLivingBase) entity, partialTicks); - float f6 = 1.0F / this.fogColorRed; - if (f6 > 1.0F / this.fogColorGreen) { - f6 = 1.0F / this.fogColorGreen; - } - - if (f6 > 1.0F / this.fogColorBlue) { - f6 = 1.0F / this.fogColorBlue; - } - - this.fogColorRed = this.fogColorRed * (1.0F - f15) + this.fogColorRed * f6 * f15; - this.fogColorGreen = this.fogColorGreen * (1.0F - f15) + this.fogColorGreen * f6 * f15; - this.fogColorBlue = this.fogColorBlue * (1.0F - f15) + this.fogColorBlue * f6 * f15; - } - - if (this.mc.gameSettings.anaglyph) { - float f16 = (this.fogColorRed * 30.0F + this.fogColorGreen * 59.0F + this.fogColorBlue * 11.0F) / 100.0F; - float f17 = (this.fogColorRed * 30.0F + this.fogColorGreen * 70.0F) / 100.0F; - float f7 = (this.fogColorRed * 30.0F + this.fogColorBlue * 70.0F) / 100.0F; - this.fogColorRed = f16; - this.fogColorGreen = f17; - this.fogColorBlue = f7; - } - - GlStateManager.clearColor(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 1.0F); - } - - /**+ - * Sets up the fog to be rendered. If the arg passed in is -1 - * the fog starts at 0 and goes to 80% of far plane distance and - * is used for sky rendering. - */ - private void setupFog(int partialTicks, float parFloat1) { - Entity entity = this.mc.getRenderViewEntity(); - boolean flag = false; - if (entity instanceof EntityPlayer) { - flag = ((EntityPlayer) entity).capabilities.isCreativeMode; - } - - EaglercraftGPU.glFog(GL_FOG_COLOR, - this.setFogColorBuffer(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 1.0F)); - EaglercraftGPU.glNormal3f(0.0F, -1.0F, 0.0F); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.mc.theWorld, entity, parFloat1); - if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(Potion.blindness)) { - float f1 = 5.0F; - int i = ((EntityLivingBase) entity).getActivePotionEffect(Potion.blindness).getDuration(); - if (i < 20) { - f1 = 5.0F + (this.farPlaneDistance - 5.0F) * (1.0F - (float) i / 20.0F); - } - - GlStateManager.setFog(GL_LINEAR); - if (partialTicks == -1) { - GlStateManager.setFogStart(0.0F); - GlStateManager.setFogEnd(f1 * 0.8F); - } else { - GlStateManager.setFogStart(f1 * 0.25F); - GlStateManager.setFogEnd(f1); - } - EaglercraftGPU.glFogi('\u855a', '\u855b'); - } else if (this.cloudFog) { - GlStateManager.setFog(GL_EXP); - GlStateManager.setFogDensity(0.1F); - } else if (block.getMaterial() == Material.water) { - GlStateManager.setFog(GL_EXP); - if (entity instanceof EntityLivingBase - && ((EntityLivingBase) entity).isPotionActive(Potion.waterBreathing)) { - GlStateManager.setFogDensity(0.01F); - } else { - GlStateManager.setFogDensity(0.1F - (float) EnchantmentHelper.getRespiration(entity) * 0.03F); - } - } else if (block.getMaterial() == Material.lava) { - GlStateManager.setFog(GL_EXP); - GlStateManager.setFogDensity(2.0F); - } else if (partialTicks != -1 && !this.mc.gameSettings.fog) { - GlStateManager.setFog(GL_EXP); - GlStateManager.setFogDensity(0.0F); - } else { - GlStateManager.setFogDensity(0.001F); - float f = this.farPlaneDistance; - GlStateManager.setFog(GL_LINEAR); - if (partialTicks == -1) { - GlStateManager.setFogStart(0.0F); - GlStateManager.setFogEnd(f); - } else { - GlStateManager.setFogStart(f * 0.75F); - GlStateManager.setFogEnd(f); - } - - EaglercraftGPU.glFogi('\u855a', '\u855b'); - - if (this.mc.theWorld.provider.doesXZShowFog((int) entity.posX, (int) entity.posZ)) { - GlStateManager.setFogStart(f * 0.05F); - GlStateManager.setFogEnd(Math.min(f, 192.0F) * 0.5F); - } - } - - GlStateManager.enableColorMaterial(); - GlStateManager.enableFog(); - } - - /**+ - * Update and return fogColorBuffer with the RGBA values passed - * as arguments - */ - private FloatBuffer setFogColorBuffer(float red, float green, float blue, float alpha) { - this.fogColorBuffer.clear(); - this.fogColorBuffer.put(red).put(green).put(blue).put(alpha); - this.fogColorBuffer.flip(); - return this.fogColorBuffer; - } - - public MapItemRenderer getMapItemRenderer() { - return this.theMapItemRenderer; - } - - private static final Vector4f tmpVec4f_1 = new Vector4f(); - private static final Matrix4f tmpMat4f_1 = new Matrix4f(); - private int shadowFrameIndex = 0; - - private double blockWaveOffsetX = 0.0; - private double blockWaveOffsetY = 0.0; - private double blockWaveOffsetZ = 0.0; - private void eaglercraftShaders(float partialTicks, long finishTimeNano) { if ((EaglerDeferredPipeline.isSuspended || EaglerDeferredPipeline.instance == null) || (mc.currentScreen != null && mc.currentScreen instanceof GuiShaderConfig)) { @@ -2722,6 +1221,560 @@ public class EntityRenderer implements IResourceManagerReloadListener { } } + public void enableLightmap() { + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.enableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + } + + public void func_181022_b() { + } + + public void func_181560_a(float parFloat1, long parLong1) { + boolean flag = Display.isActive() || mc.gameSettings.touchscreen; + if (!flag && this.mc.gameSettings.pauseOnLostFocus + && (!this.mc.gameSettings.touchscreen || !PointerInputAbstraction.getVCursorButtonDown(1))) { + if (Minecraft.getSystemTime() - this.prevFrameTime > 500L) { + this.mc.displayInGameMenu(); + } + } else { + this.prevFrameTime = Minecraft.getSystemTime(); + } + + if (this.mc.inGameHasFocus && flag) { + this.mc.mouseHelper.mouseXYChange(); + float f = this.mc.gameSettings.mouseSensitivity * 0.6F + 0.2F; + if (this.mc.gameSettings.keyBindZoomCamera.isKeyDown()) { + f *= 0.7f; + } + float f1 = f * f * f * 8.0F; + float f2 = (float) this.mc.mouseHelper.deltaX * f1; + float f3 = (float) this.mc.mouseHelper.deltaY * f1; + byte b0 = 1; + if (this.mc.gameSettings.invertMouse) { + b0 = -1; + } + + if (this.mc.gameSettings.smoothCamera) { + this.smoothCamYaw += f2; + this.smoothCamPitch += f3; + float f4 = parFloat1 - this.smoothCamPartialTicks; + this.smoothCamPartialTicks = parFloat1; + f2 = this.smoothCamFilterX * f4; + f3 = this.smoothCamFilterY * f4; + this.mc.thePlayer.setAngles(f2, f3 * (float) b0); + } else { + this.smoothCamYaw = 0.0F; + this.smoothCamPitch = 0.0F; + this.mc.thePlayer.setAngles(f2, f3 * (float) b0); + } + } + + if (!this.mc.skipRenderWorld) { + anaglyphEnable = this.mc.gameSettings.anaglyph; + final ScaledResolution scaledresolution = mc.scaledResolution; + int l = scaledresolution.getScaledWidth(); + int i1 = scaledresolution.getScaledHeight(); + final int j1 = PointerInputAbstraction.getVCursorX() * l / this.mc.displayWidth; + final int k1 = i1 - PointerInputAbstraction.getVCursorY() * i1 / this.mc.displayHeight - 1; + int l1 = this.mc.gameSettings.limitFramerate; + if (this.mc.theWorld != null) { + int i = Math.min(Minecraft.getDebugFPS(), l1); + i = Math.max(i, 60); + long j = System.nanoTime() - parLong1; + long k = Math.max((long) (1000000000 / i / 4) - j, 0L); + this.renderWorld(parFloat1, System.nanoTime() + k); + this.renderEndNanoTime = System.nanoTime(); + final boolean b = !this.mc.gameSettings.hideGUI || this.mc.currentScreen != null; + if (b) { + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + long framebufferAge = this.overlayFramebuffer.getAge(); + if (framebufferAge == -1l || framebufferAge > (Minecraft.getDebugFPS() < 25 ? 125l : 75l)) { + this.overlayFramebuffer.beginRender(mc.displayWidth, mc.displayHeight); + GlStateManager.colorMask(true, true, true, true); + GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GlStateManager.enableOverlayFramebufferBlending(); + if (b) { + this.mc.ingameGUI.renderGameOverlay(parFloat1); + } + GlStateManager.disableOverlayFramebufferBlending(); + this.overlayFramebuffer.endRender(); + } + } + if (b) { + this.setupOverlayRendering(); + GlStateManager.disableLighting(); + GlStateManager.enableBlend(); + if (Minecraft.isFancyGraphicsEnabled()) { + this.mc.ingameGUI.renderVignette(this.mc.thePlayer.getBrightness(parFloat1), l, i1); + } + this.mc.ingameGUI.renderGameOverlayCrosshairs(l, i1); + GlStateManager.bindTexture(this.overlayFramebuffer.getTexture()); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableAlpha(); + GlStateManager.disableDepth(); + GlStateManager.depthMask(false); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos(0.0D, (double) i1, -90.0D).tex(0.0D, 0.0D).endVertex(); + worldrenderer.pos((double) l, (double) i1, -90.0D).tex(1.0D, 0.0D).endVertex(); + worldrenderer.pos((double) l, 0.0D, -90.0D).tex(1.0D, 1.0D).endVertex(); + worldrenderer.pos(0.0D, 0.0D, -90.0D).tex(0.0D, 1.0D).endVertex(); + tessellator.draw(); + GlStateManager.depthMask(true); + GlStateManager.enableDepth(); + GlStateManager.disableBlend(); + if (this.mc.gameSettings.hudPlayer) { // give the player model HUD good fps + this.mc.ingameGUI.drawEaglerPlayerOverlay(l - 3, + 3 + this.mc.ingameGUI.overlayDebug.playerOffset, parFloat1); + } + } + } else { + GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + this.setupOverlayRendering(); + this.renderEndNanoTime = System.nanoTime(); + } + + this.mc.notifRenderer.renderOverlay(j1, k1); + + if (this.mc.currentScreen != null) { + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + float f = 1.0f; + final float[] ff = new float[] { 1.0f }; + + try { + f = mc.currentScreen.getEaglerScale(); + int mx, my; + if (f == 1.0f) { + mx = j1; + my = k1; + } else { + mx = GuiScreen.applyEaglerScale(f, j1, l); + my = GuiScreen.applyEaglerScale(f, k1, i1); + GlStateManager.pushMatrix(); + float fff = (1.0f - f) * 0.5f; + GlStateManager.translate(fff * l, fff * i1, 0.0f); + GlStateManager.scale(f, f, f); + } + ff[0] = f; + this.mc.currentScreen.drawScreen(mx, my, parFloat1); + if (f != 1.0f) { + GlStateManager.popMatrix(); + } + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Rendering screen"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Screen render details"); + crashreportcategory.addCrashSectionCallable("Screen name", new Callable() { + public String call() throws Exception { + return EntityRenderer.this.mc.currentScreen.getClass().getName(); + } + }); + crashreportcategory.addCrashSectionCallable("Mouse location", new Callable() { + public String call() throws Exception { + return HString.format("Scaled: (%d, %d). Absolute: (%d, %d)", + new Object[] { Integer.valueOf(j1), Integer.valueOf(k1), + Integer.valueOf(PointerInputAbstraction.getVCursorX()), + Integer.valueOf(PointerInputAbstraction.getVCursorY()) }); + } + }); + crashreportcategory.addCrashSectionCallable("Screen size", new Callable() { + public String call() throws Exception { + return HString.format("Scaled: (%d, %d). Absolute: (%d, %d). Scale factor of %d", + new Object[] { Integer.valueOf(scaledresolution.getScaledWidth()), + Integer.valueOf(scaledresolution.getScaledHeight()), + Integer.valueOf(EntityRenderer.this.mc.displayWidth), + Integer.valueOf(EntityRenderer.this.mc.displayHeight), + Integer.valueOf(scaledresolution.getScaleFactor()) }); + } + }); + crashreportcategory.addCrashSectionCallable("Eagler Scale", new Callable() { + public String call() throws Exception { + return "" + ff[0]; + } + }); + throw new ReportedException(crashreport); + } + + this.mc.voiceOverlay.drawOverlay(); + } + } + } + + /** + * + Changes the field of view of the player depending on if they are underwater + * or not + */ + public float getFOVModifier(float partialTicks, boolean parFlag) { + if (this.debugView) { + return 90.0F; + } else { + Entity entity = this.mc.getRenderViewEntity(); + float f = 70.0F; + if (parFlag) { + f = this.mc.isZoomKey ? this.mc.adjustedZoomValue : this.mc.gameSettings.fovSetting; + f = f * (this.fovModifierHandPrev + (this.fovModifierHand - this.fovModifierHandPrev) * partialTicks); + } + + if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).getHealth() <= 0.0F) { + float f1 = (float) ((EntityLivingBase) entity).deathTime + partialTicks; + f /= (1.0F - 500.0F / (f1 + 500.0F)) * 2.0F + 1.0F; + } + + Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.mc.theWorld, entity, partialTicks); + if (block.getMaterial() == Material.water) { + f = f * 60.0F / 70.0F; + } + + return f; + } + } + + public MapItemRenderer getMapItemRenderer() { + return this.theMapItemRenderer; + } + + /** + * + Finds what block or object the mouse is over at the specified partial tick + * time. Args: partialTickTime + */ + public void getMouseOver(float partialTicks) { + Entity entity = this.mc.getRenderViewEntity(); + if (entity != null) { + if (this.mc.theWorld != null) { + this.mc.pointedEntity = null; + double d0 = (double) this.mc.playerController.getBlockReachDistance(); + this.mc.objectMouseOver = entity.rayTrace(d0, partialTicks); + double d1 = d0; + Vec3 vec3 = entity.getPositionEyes(partialTicks); + boolean flag = false; + boolean flag1 = true; + if (this.mc.playerController.extendedReach()) { + d0 = 6.0D; + d1 = 6.0D; + } else { + if (d0 > 3.0D) { + flag = true; + } + + d0 = d0; + } + + if (this.mc.objectMouseOver != null) { + d1 = this.mc.objectMouseOver.hitVec.distanceTo(vec3); + } + + Vec3 vec31 = entity.getLook(partialTicks); + Vec3 vec32 = vec3.addVector(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0); + this.pointedEntity = null; + Vec3 vec33 = null; + float f = 1.0F; + List list = this.mc.theWorld.getEntitiesInAABBexcluding(entity, + entity.getEntityBoundingBox().addCoord(vec31.xCoord * d0, vec31.yCoord * d0, vec31.zCoord * d0) + .expand((double) f, (double) f, (double) f), + Predicates.and(EntitySelectors.NOT_SPECTATING, new Predicate() { + public boolean apply(Entity entity2) { + return entity2.canBeCollidedWith(); + } + })); + double d2 = d1; + + for (int i = 0; i < list.size(); ++i) { + Entity entity1 = (Entity) list.get(i); + float f1 = entity1.getCollisionBorderSize(); + AxisAlignedBB axisalignedbb = entity1.getEntityBoundingBox().expand((double) f1, (double) f1, + (double) f1); + MovingObjectPosition movingobjectposition = axisalignedbb.calculateIntercept(vec3, vec32); + if (axisalignedbb.isVecInside(vec3)) { + if (d2 >= 0.0D) { + this.pointedEntity = entity1; + vec33 = movingobjectposition == null ? vec3 : movingobjectposition.hitVec; + d2 = 0.0D; + } + } else if (movingobjectposition != null) { + double d3 = vec3.distanceTo(movingobjectposition.hitVec); + if (d3 < d2 || d2 == 0.0D) { + if (entity1 == entity.ridingEntity) { + if (d2 == 0.0D) { + this.pointedEntity = entity1; + vec33 = movingobjectposition.hitVec; + } + } else { + this.pointedEntity = entity1; + vec33 = movingobjectposition.hitVec; + d2 = d3; + } + } + } + } + + if (this.pointedEntity != null && flag && vec3.distanceTo(vec33) > 3.0D) { + this.pointedEntity = null; + this.mc.objectMouseOver = new MovingObjectPosition(MovingObjectPosition.MovingObjectType.MISS, + vec33, (EnumFacing) null, new BlockPos(vec33)); + } + + if (this.pointedEntity != null && (d2 < d1 || this.mc.objectMouseOver == null)) { + this.mc.objectMouseOver = new MovingObjectPosition(this.pointedEntity, vec33); + if (this.pointedEntity instanceof EntityLivingBase + || this.pointedEntity instanceof EntityItemFrame) { + this.mc.pointedEntity = this.pointedEntity; + } + } + } + } + } + + private float getNightVisionBrightness(EntityLivingBase entitylivingbaseIn, float partialTicks) { + int i = entitylivingbaseIn.getActivePotionEffect(Potion.nightVision).getDuration(); + return i > 200 ? 1.0F : 0.7F + MathHelper.sin(((float) i - partialTicks) * 3.1415927F * 0.2F) * 0.3F; + } + + private void hurtCameraEffect(float partialTicks) { + if (this.mc.getRenderViewEntity() instanceof EntityLivingBase) { + EntityLivingBase entitylivingbase = (EntityLivingBase) this.mc.getRenderViewEntity(); + float f = (float) entitylivingbase.hurtTime - partialTicks; + if (entitylivingbase.getHealth() <= 0.0F) { + float f1 = (float) entitylivingbase.deathTime + partialTicks; + GlStateManager.rotate(40.0F - 8000.0F / (f1 + 200.0F), 0.0F, 0.0F, 1.0F); + } + + if (f < 0.0F) { + return; + } + + f = f / (float) entitylivingbase.maxHurtTime; + f = MathHelper.sin(f * f * f * f * 3.1415927F); + float f2 = entitylivingbase.attackedAtYaw; + GlStateManager.rotate(-f2, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(-f * 14.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(f2, 0.0F, 1.0F, 0.0F); + } + + } + + private boolean isDrawBlockOutline() { + if (!this.drawBlockOutline) { + return false; + } else { + Entity entity = this.mc.getRenderViewEntity(); + boolean flag = entity instanceof EntityPlayer && !this.mc.gameSettings.hideGUI; + if (flag && !((EntityPlayer) entity).capabilities.allowEdit) { + ItemStack itemstack = ((EntityPlayer) entity).getCurrentEquippedItem(); + if (this.mc.objectMouseOver != null + && this.mc.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + BlockPos blockpos = this.mc.objectMouseOver.getBlockPos(); + Block block = this.mc.theWorld.getBlockState(blockpos).getBlock(); + if (this.mc.playerController.getCurrentGameType() == WorldSettings.GameType.SPECTATOR) { + flag = block.hasTileEntity() && this.mc.theWorld.getTileEntity(blockpos) instanceof IInventory; + } else { + flag = itemstack != null && (itemstack.canDestroy(block) || itemstack.canPlaceOn(block)); + } + } + } + + return flag; + } + } + + public boolean isShaderActive() { + return false; + } + + /** + * + What shader to use when spectating this entity + */ + public void loadEntityShader(Entity entityIn) { + } + + private void loadShader(ResourceLocation resourceLocationIn) { + this.useShader = false; + } + + public void onResourceManagerReload(IResourceManager var1) { + } + + /** + * + sets up player's eye (or camera in third person mode) + */ + private void orientCamera(float partialTicks) { + Entity entity = this.mc.getRenderViewEntity(); + float f = entity.getEyeHeight(); + double d0 = entity.prevPosX + (entity.posX - entity.prevPosX) * (double) partialTicks; + double d1 = entity.prevPosY + (entity.posY - entity.prevPosY) * (double) partialTicks + (double) f; + double d2 = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * (double) partialTicks; + if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPlayerSleeping()) { + f = (float) ((double) f + 1.0D); + GlStateManager.translate(0.0F, 0.3F, 0.0F); + if (!this.mc.gameSettings.debugCamEnable) { + BlockPos blockpos = new BlockPos(entity); + IBlockState iblockstate = this.mc.theWorld.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + if (block == Blocks.bed) { + int j = ((EnumFacing) iblockstate.getValue(BlockBed.FACING)).getHorizontalIndex(); + GlStateManager.rotate((float) (j * 90), 0.0F, 1.0F, 0.0F); + } + + GlStateManager.rotate( + entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks + 180.0F, + 0.0F, -1.0F, 0.0F); + GlStateManager.rotate( + entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * partialTicks, + -1.0F, 0.0F, 0.0F); + } + } else if (this.mc.gameSettings.thirdPersonView > 0) { + double d3 = (double) (this.thirdPersonDistanceTemp + + (this.thirdPersonDistance - this.thirdPersonDistanceTemp) * partialTicks); + if (this.mc.gameSettings.debugCamEnable) { + GlStateManager.translate(0.0F, 0.0F, (float) (-d3)); + } else { + float f1 = entity.rotationYaw; + float f2 = entity.rotationPitch; + if (this.mc.gameSettings.thirdPersonView == 2) { + f2 += 180.0F; + } + + double d4 = (double) (-MathHelper.sin(f1 / 180.0F * 3.1415927F) + * MathHelper.cos(f2 / 180.0F * 3.1415927F)) * d3; + double d5 = (double) (MathHelper.cos(f1 / 180.0F * 3.1415927F) + * MathHelper.cos(f2 / 180.0F * 3.1415927F)) * d3; + double d6 = (double) (-MathHelper.sin(f2 / 180.0F * 3.1415927F)) * d3; + + for (int i = 0; i < 8; ++i) { + float f3 = (float) ((i & 1) * 2 - 1); + float f4 = (float) ((i >> 1 & 1) * 2 - 1); + float f5 = (float) ((i >> 2 & 1) * 2 - 1); + f3 = f3 * 0.1F; + f4 = f4 * 0.1F; + f5 = f5 * 0.1F; + MovingObjectPosition movingobjectposition = this.mc.theWorld + .rayTraceBlocks(new Vec3(d0 + (double) f3, d1 + (double) f4, d2 + (double) f5), new Vec3( + d0 - d4 + (double) f3 + (double) f5, d1 - d6 + (double) f4, d2 - d5 + (double) f5)); + if (movingobjectposition != null) { + double d7 = movingobjectposition.hitVec.distanceTo(new Vec3(d0, d1, d2)); + if (d7 < d3) { + d3 = d7; + } + } + } + + if (this.mc.gameSettings.thirdPersonView == 2) { + GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); + } + + GlStateManager.rotate(entity.rotationPitch - f2, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(entity.rotationYaw - f1, 0.0F, 1.0F, 0.0F); + GlStateManager.translate(0.0F, 0.0F, (float) (-d3)); + GlStateManager.rotate(f1 - entity.rotationYaw, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(f2 - entity.rotationPitch, 1.0F, 0.0F, 0.0F); + } + } else { + GlStateManager.translate(0.0F, 0.0F, -0.1F); + } + + if (!this.mc.gameSettings.debugCamEnable) { + GlStateManager.rotate( + entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * partialTicks, 1.0F, + 0.0F, 0.0F); + if (entity instanceof EntityAnimal) { + EntityAnimal entityanimal = (EntityAnimal) entity; + GlStateManager.rotate(entityanimal.prevRotationYawHead + + (entityanimal.rotationYawHead - entityanimal.prevRotationYawHead) * partialTicks + 180.0F, + 0.0F, 1.0F, 0.0F); + } else { + GlStateManager.rotate( + entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks + 180.0F, + 0.0F, 1.0F, 0.0F); + } + } + + GlStateManager.translate(0.0F, -f, 0.0F); + d0 = entity.prevPosX + (entity.posX - entity.prevPosX) * (double) partialTicks; + d1 = entity.prevPosY + (entity.posY - entity.prevPosY) * (double) partialTicks + (double) f; + d2 = entity.prevPosZ + (entity.posZ - entity.prevPosZ) * (double) partialTicks; + this.cloudFog = this.mc.renderGlobal.hasCloudFog(d0, d1, d2, partialTicks); + } + + private void renderCloudsCheck(RenderGlobal renderGlobalIn, float partialTicks, int pass) { + if (this.mc.gameSettings.func_181147_e() != 0) { + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.gluPerspective(this.getFOVModifier(partialTicks, true), + (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, this.farPlaneDistance * 4.0F); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.pushMatrix(); + this.setupFog(0, partialTicks); + renderGlobalIn.renderClouds(partialTicks, pass); + GlStateManager.disableFog(); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.gluPerspective(this.getFOVModifier(partialTicks, true), + (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, + this.farPlaneDistance * MathHelper.SQRT_2); + GlStateManager.matrixMode(GL_MODELVIEW); + } + + } + + /** + * + Render player hand + */ + private void renderHand(float partialTicks, int xOffset) { + if (!this.debugView) { + if (DynamicLightsStateManager.isInDynamicLightsPass()) { + DynamicLightsStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); + } + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + float f = 0.07F; + if (this.mc.gameSettings.anaglyph) { + GlStateManager.translate((float) (-(xOffset * 2 - 1)) * f, 0.0F, 0.0F); + } + + GlStateManager.gluPerspective(this.getFOVModifier(partialTicks, false), + (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, this.farPlaneDistance * 2.0F); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + if (this.mc.gameSettings.anaglyph) { + GlStateManager.translate((float) (xOffset * 2 - 1) * 0.1F, 0.0F, 0.0F); + } + + GlStateManager.pushMatrix(); + this.hurtCameraEffect(partialTicks); + if (this.mc.gameSettings.viewBobbing) { + this.setupViewBobbing(partialTicks); + } + + boolean flag = this.mc.getRenderViewEntity() instanceof EntityLivingBase + && ((EntityLivingBase) this.mc.getRenderViewEntity()).isPlayerSleeping(); + if (this.mc.gameSettings.thirdPersonView == 0 && !flag && !this.mc.gameSettings.hideGUI + && !this.mc.playerController.isSpectator()) { + this.enableLightmap(); + this.itemRenderer.renderItemInFirstPerson(partialTicks); + this.disableLightmap(); + } + + GlStateManager.popMatrix(); + if (this.mc.gameSettings.thirdPersonView == 0 && !flag) { + this.itemRenderer.renderOverlays(partialTicks); + this.hurtCameraEffect(partialTicks); + } + + if (this.mc.gameSettings.viewBobbing) { + this.setupViewBobbing(partialTicks); + } + + } + } + public boolean renderHeldItemLight(EntityLivingBase entityLiving, float mag) { if (DynamicLightManager.isRenderingLights()) { ItemStack itemStack = entityLiving.getHeldItem(); @@ -2779,49 +1832,1026 @@ public class EntityRenderer implements IResourceManagerReloadListener { return false; } - private static final Matrix4f matrixToBounds_tmpMat4f_1 = new Matrix4f(); - private static final Vector4f matrixToBounds_tmpVec4f_1 = new Vector4f(); - private static final Vector4f[] matrixToBounds_tmpVec4f_array = new Vector4f[] { new Vector4f(-1, -1, -1, 1), - new Vector4f(-1, -1, 1, 1), new Vector4f(-1, 1, -1, 1), new Vector4f(-1, 1, 1, 1), - new Vector4f(1, -1, -1, 1), new Vector4f(1, -1, 1, 1), new Vector4f(1, 1, -1, 1), - new Vector4f(1, 1, 1, 1) }; + /** + * + Render rain and snow + */ + protected void renderRainSnow(float partialTicks) { + float f = this.mc.theWorld.getRainStrength(partialTicks); + if (f > 0.0F) { + boolean df = DeferredStateManager.isInDeferredPass(); + this.enableLightmap(); + Entity entity = this.mc.getRenderViewEntity(); + WorldClient worldclient = this.mc.theWorld; + int i = MathHelper.floor_double(entity.posX); + int j = MathHelper.floor_double(entity.posY); + int k = MathHelper.floor_double(entity.posZ); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + GlStateManager.disableCull(); + if (!df) { + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + if (DynamicLightsStateManager.isInDynamicLightsPass()) { + DynamicLightsStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); + } + } else { + GlStateManager.enableAlpha(); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + DeferredStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); + GlStateManager.alphaFunc(GL_GREATER, 0.01F); + GlStateManager.depthMask(false); + GlStateManager.enableDepth(); + EaglerDeferredPipeline.instance.setForwardRenderLightFactors(0.65f, + 4.75f - MathHelper.clamp_float(DeferredStateManager.getSunHeight() * 8.0f - 3.0f, 0.0f, 4.0f), + 1.0f, 0.03f); + } + EaglercraftGPU.glNormal3f(0.0F, 1.0F, 0.0F); + double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; + double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; + double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; + int l = MathHelper.floor_double(d1); + byte b0 = 5; + if (df) { + b0 = 8; + } else if (this.mc.gameSettings.fancyGraphics) { + b0 = 10; + } - private static AxisAlignedBB matrixToBounds(Matrix4f matrixIn, double x, double y, double z) { - Matrix4f.invert(matrixIn, matrixToBounds_tmpMat4f_1); + byte b1 = -1; + float f1 = (float) this.rendererUpdateCount + partialTicks; + worldrenderer.setTranslation(-d0, -d1, -d2); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - float minX = Integer.MAX_VALUE; - float minY = Integer.MAX_VALUE; - float minZ = Integer.MAX_VALUE; - float maxX = Integer.MIN_VALUE; - float maxY = Integer.MIN_VALUE; - float maxZ = Integer.MIN_VALUE; - Vector4f tmpVec = matrixToBounds_tmpVec4f_1; - float vx, vy, vz; - for (int i = 0; i < 8; ++i) { - Matrix4f.transform(matrixToBounds_tmpMat4f_1, matrixToBounds_tmpVec4f_array[i], tmpVec); - vx = tmpVec.x; - vy = tmpVec.y; - vz = tmpVec.z; - if (vx < minX) - minX = vx; - if (vy < minY) - minY = vy; - if (vz < minZ) - minZ = vz; - if (vx > maxX) - maxX = vx; - if (vy > maxY) - maxY = vy; - if (vz > maxZ) - maxZ = vz; + for (int i1 = k - b0; i1 <= k + b0; ++i1) { + for (int j1 = i - b0; j1 <= i + b0; ++j1) { + int k1 = (i1 - k + 16) * 32 + j1 - i + 16; + double d3 = (double) this.rainXCoords[k1] * 0.5D; + double d4 = (double) this.rainYCoords[k1] * 0.5D; + blockpos$mutableblockpos.func_181079_c(j1, 0, i1); + BiomeGenBase biomegenbase = worldclient.getBiomeGenForCoords(blockpos$mutableblockpos); + if (biomegenbase.canSpawnLightningBolt() || biomegenbase.getEnableSnow()) { + int l1 = worldclient.getPrecipitationHeight(blockpos$mutableblockpos).getY(); + int i2 = j - b0; + int j2 = j + b0; + if (i2 < l1) { + i2 = l1; + } + + if (j2 < l1) { + j2 = l1; + } + + int k2 = l1; + if (l1 < l) { + k2 = l; + } + + if (i2 != j2) { + this.random + .setSeed((long) (j1 * j1 * 3121 + j1 * 45238971 ^ i1 * i1 * 418711 + i1 * 13761)); + blockpos$mutableblockpos.func_181079_c(j1, i2, i1); + float f2 = biomegenbase.getFloatTemperature(blockpos$mutableblockpos); + if (f2 >= 0.15F) { + if (b1 != 0) { + if (b1 >= 0) { + tessellator.draw(); + } + + b1 = 0; + this.mc.getTextureManager() + .bindTexture(df ? new ResourceLocation("eagler:glsl/deferred/rain.png") + : locationRainPng); + if (df) { + DeferredStateManager.setRoughnessConstant(0.5f); + DeferredStateManager.setMetalnessConstant(0.05f); + DeferredStateManager.setEmissionConstant(1.0f); + GlStateManager.color(0.8F, 0.8F, 1.0F, 0.25F); + } + worldrenderer.begin(7, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP); + } + + double d5 = ((double) (this.rendererUpdateCount + j1 * j1 * 3121 + j1 * 45238971 + + i1 * i1 * 418711 + i1 * 13761 & 31) + (double) partialTicks) / 32.0D + * (3.0D + this.random.nextDouble()); + double d6 = (double) ((float) j1 + 0.5F) - entity.posX; + double d7 = (double) ((float) i1 + 0.5F) - entity.posZ; + float f3 = MathHelper.sqrt_double(d6 * d6 + d7 * d7) / (float) b0; + float f4 = ((1.0F - f3 * f3) * 0.5F + 0.5F) * f; + blockpos$mutableblockpos.func_181079_c(j1, k2, i1); + int l2 = worldclient.getCombinedLight(blockpos$mutableblockpos, 0); + int i3 = l2 >> 16 & '\uffff'; + int j3 = l2 & '\uffff'; + worldrenderer.pos((double) j1 - d3 + 0.5D, (double) i2, (double) i1 - d4 + 0.5D) + .tex(0.0D, (double) i2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) + .lightmap(i3, j3).endVertex(); + worldrenderer.pos((double) j1 + d3 + 0.5D, (double) i2, (double) i1 + d4 + 0.5D) + .tex(1.0D, (double) i2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) + .lightmap(i3, j3).endVertex(); + worldrenderer.pos((double) j1 + d3 + 0.5D, (double) j2, (double) i1 + d4 + 0.5D) + .tex(1.0D, (double) j2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) + .lightmap(i3, j3).endVertex(); + worldrenderer.pos((double) j1 - d3 + 0.5D, (double) j2, (double) i1 - d4 + 0.5D) + .tex(0.0D, (double) j2 * 0.25D + d5).color(1.0F, 1.0F, 1.0F, f4) + .lightmap(i3, j3).endVertex(); + } else { + if (b1 != 1) { + if (b1 >= 0) { + tessellator.draw(); + } + + b1 = 1; + this.mc.getTextureManager().bindTexture(locationSnowPng); + if (df) { + DeferredStateManager.setRoughnessConstant(0.7f); + DeferredStateManager.setMetalnessConstant(0.05f); + DeferredStateManager.setEmissionConstant(1.0f); + GlStateManager.color(1.3F, 1.3F, 1.3F, 0.5F); + } + worldrenderer.begin(7, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP); + } + + double d8 = (double) (((float) (this.rendererUpdateCount & 511) + partialTicks) + / 512.0F); + double d9 = this.random.nextDouble() + + (double) f1 * 0.01D * (double) ((float) this.random.nextGaussian()); + double d10 = this.random.nextDouble() + + (double) (f1 * (float) this.random.nextGaussian()) * 0.001D; + double d11 = (double) ((float) j1 + 0.5F) - entity.posX; + double d12 = (double) ((float) i1 + 0.5F) - entity.posZ; + float f6 = MathHelper.sqrt_double(d11 * d11 + d12 * d12) / (float) b0; + float f5 = ((1.0F - f6 * f6) * 0.3F + 0.5F) * f; + blockpos$mutableblockpos.func_181079_c(j1, k2, i1); + int k3 = (worldclient.getCombinedLight(blockpos$mutableblockpos, 0) * 3 + 15728880) / 4; + int l3 = k3 >> 16 & '\uffff'; + int i4 = k3 & '\uffff'; + worldrenderer.pos((double) j1 - d3 + 0.5D, (double) i2, (double) i1 - d4 + 0.5D) + .tex(0.0D + d9, (double) i2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) + .lightmap(l3, i4).endVertex(); + worldrenderer.pos((double) j1 + d3 + 0.5D, (double) i2, (double) i1 + d4 + 0.5D) + .tex(1.0D + d9, (double) i2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) + .lightmap(l3, i4).endVertex(); + worldrenderer.pos((double) j1 + d3 + 0.5D, (double) j2, (double) i1 + d4 + 0.5D) + .tex(1.0D + d9, (double) j2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) + .lightmap(l3, i4).endVertex(); + worldrenderer.pos((double) j1 - d3 + 0.5D, (double) j2, (double) i1 - d4 + 0.5D) + .tex(0.0D + d9, (double) j2 * 0.25D + d8 + d10).color(1.0F, 1.0F, 1.0F, f5) + .lightmap(l3, i4).endVertex(); + } + } + } + } + } + + if (b1 >= 0) { + tessellator.draw(); + } + + worldrenderer.setTranslation(0.0D, 0.0D, 0.0D); + GlStateManager.enableCull(); + if (!df) { + GlStateManager.disableBlend(); + } else { + GlStateManager.disableAlpha(); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + DeferredStateManager.setDefaultMaterialConstants(); + GlStateManager.depthMask(true); + GlStateManager.disableDepth(); + EaglerDeferredPipeline.instance.setForwardRenderLightFactors(1.0f, 1.0f, 1.0f, 1.0f); + } + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + this.disableLightmap(); + } + } + + public void renderStreamIndicator(float partialTicks) { + } + + public void renderWorld(float partialTicks, long finishTimeNano) { + this.updateLightmap(partialTicks); + if (this.mc.getRenderViewEntity() == null) { + this.mc.setRenderViewEntity(this.mc.thePlayer); } - return new AxisAlignedBB(minX + x, minY + y, minZ + z, maxX + x, maxY + y, maxZ + z); + this.getMouseOver(partialTicks); + + boolean fxaa = !this.mc.gameSettings.shaders + && ((this.mc.gameSettings.fxaa == 0 && this.mc.gameSettings.fancyGraphics) + || this.mc.gameSettings.fxaa == 1); + if (fxaa) { + EffectPipelineFXAA.begin(this.mc.displayWidth, this.mc.displayHeight); + } + + VoiceTagRenderer.clearTagsDrawnSet(); + + GlStateManager.enableDepth(); + GlStateManager.enableAlpha(); + GlStateManager.alphaFunc(GL_GREATER, 0.5F); + boolean dlights = DynamicLightsStateManager.isDynamicLightsRender(); + if (dlights) { + updateDynamicLightListEagler(partialTicks); + } + if (this.mc.gameSettings.anaglyph && !this.mc.gameSettings.shaders) { + if (dlights) { + GlStateManager.enableExtensionPipeline(); + } + try { + anaglyphField = 0; + GlStateManager.colorMask(false, true, true, false); + this.renderWorldPass(0, partialTicks, finishTimeNano); + anaglyphField = 1; + GlStateManager.colorMask(true, false, false, false); + this.renderWorldPass(1, partialTicks, finishTimeNano); + GlStateManager.colorMask(true, true, true, false); + } finally { + if (dlights) { + GlStateManager.disableExtensionPipeline(); + } + } + } else { + if (this.mc.gameSettings.shaders) { + try { + this.eaglercraftShaders(partialTicks, finishTimeNano); + } catch (Throwable t) { + logger.error("Exception caught running deferred render!"); + logger.error(t); + EaglerDeferredPipeline.instance.resetContextStateAfterException(); + logger.error("Suspending shaders..."); + EaglerDeferredPipeline.isSuspended = true; + + } + mc.effectRenderer.acceleratedParticleRenderer = EffectRenderer.vanillaAcceleratedParticleRenderer; + } else { + mc.effectRenderer.acceleratedParticleRenderer = EaglercraftGPU.checkInstancingCapable() + ? EffectRenderer.vanillaAcceleratedParticleRenderer + : null; + if (dlights) { + GlStateManager.enableExtensionPipeline(); + } + try { + this.renderWorldPass(2, partialTicks, finishTimeNano); + } finally { + if (dlights) { + GlStateManager.disableExtensionPipeline(); + } + } + } + } + + if (fxaa) { + EffectPipelineFXAA.end(); + } } - public static void setupSunCameraTransform(float celestialAngle) { - GlStateManager.rotate(celestialAngle + 90.0f, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(-DeferredStateManager.sunAngle, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); + private void renderWorldDirections(float partialTicks) { + if (this.mc.gameSettings.showDebugInfo && !this.mc.gameSettings.hideGUI && !this.mc.thePlayer.hasReducedDebug() + && !this.mc.gameSettings.reducedDebugInfo) { + Entity entity = this.mc.getRenderViewEntity(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + EaglercraftGPU.glLineWidth(1.0F); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + GlStateManager.pushMatrix(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + this.orientCamera(partialTicks); + GlStateManager.translate(0.0F, entity.getEyeHeight(), 0.0F); + RenderGlobal.func_181563_a(new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.005D, 1.0E-4D, 1.0E-4D), 255, 0, 0, 255); + RenderGlobal.func_181563_a(new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0E-4D, 1.0E-4D, 0.005D), 0, 0, 255, 255); + RenderGlobal.func_181563_a(new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0E-4D, 0.0033D, 1.0E-4D), 0, 255, 0, 255); + GlStateManager.popMatrix(); + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + } + + private void renderWorldPass(int pass, float partialTicks, long finishTimeNano) { + RenderGlobal renderglobal = this.mc.renderGlobal; + EffectRenderer effectrenderer = this.mc.effectRenderer; + boolean flag = this.isDrawBlockOutline(); + GlStateManager.enableCull(); + GlStateManager.viewport(0, 0, this.mc.displayWidth, this.mc.displayHeight); + this.updateFogColor(partialTicks); + GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + this.setupCameraTransform(partialTicks, pass); + boolean isDynamicLights = DynamicLightsStateManager.isDynamicLightsRender(); + if (isDynamicLights) { + DynamicLightsStateManager.setupInverseViewMatrix(); + } + ActiveRenderInfo.updateRenderInfo(this.mc.thePlayer, this.mc.gameSettings.thirdPersonView == 2); + Frustum frustum = new Frustum(); + Entity entity = this.mc.getRenderViewEntity(); + double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; + double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; + double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; + TileEntityRendererDispatcher.staticPlayerX = d0; // hack, needed for some eagler stuff + TileEntityRendererDispatcher.staticPlayerY = d1; + TileEntityRendererDispatcher.staticPlayerZ = d2; + frustum.setPosition(d0, d1, d2); + if (this.mc.gameSettings.renderDistanceChunks >= 4) { + this.setupFog(-1, partialTicks); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + float vigg = this.getFOVModifier(partialTicks, true); + GlStateManager.gluPerspective(vigg, (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, + this.farPlaneDistance * 4.0F); + GlStateManager.matrixMode(GL_MODELVIEW); + renderglobal.renderSky(partialTicks, pass); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.gluPerspective(vigg, (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, + this.farPlaneDistance * MathHelper.SQRT_2); + GlStateManager.matrixMode(GL_MODELVIEW); + } + + this.setupFog(0, partialTicks); + GlStateManager.shadeModel(GL_SMOOTH); + if (entity.posY + (double) entity.getEyeHeight() < 128.0D) { + this.renderCloudsCheck(renderglobal, partialTicks, pass); + } + + this.setupFog(0, partialTicks); + this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + RenderHelper.disableStandardItemLighting(); + renderglobal.setupTerrain(entity, (double) partialTicks, frustum, this.frameCount++, + this.mc.thePlayer.isSpectator()); + if (pass == 0 || pass == 2) { + this.mc.renderGlobal.updateChunks(finishTimeNano); + } + + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.pushMatrix(); + GlStateManager.disableAlpha(); + GlStateManager.disableBlend(); + renderglobal.renderBlockLayer(EnumWorldBlockLayer.SOLID, (double) partialTicks, pass, entity); + GlStateManager.enableAlpha(); + renderglobal.renderBlockLayer(EnumWorldBlockLayer.CUTOUT_MIPPED, (double) partialTicks, pass, entity); + this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); + renderglobal.renderBlockLayer(EnumWorldBlockLayer.CUTOUT, (double) partialTicks, pass, entity); + this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + GlStateManager.shadeModel(GL_FLAT); + if (!this.debugView) { + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.popMatrix(); + GlStateManager.pushMatrix(); + RenderHelper.enableStandardItemLighting(); + renderglobal.renderEntities(entity, frustum, partialTicks); + RenderHelper.disableStandardItemLighting(); + this.disableLightmap(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.popMatrix(); + GlStateManager.pushMatrix(); + if (this.mc.objectMouseOver != null && entity.isInsideOfMaterial(Material.water) && flag) { + EntityPlayer entityplayer = (EntityPlayer) entity; + GlStateManager.disableAlpha(); + if (isDynamicLights) { + GlStateManager.disableExtensionPipeline(); + } + renderglobal.drawSelectionBox(entityplayer, this.mc.objectMouseOver, 0, partialTicks); + GlStateManager.enableAlpha(); + if (isDynamicLights) { + GlStateManager.enableExtensionPipeline(); + } + } + } + + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.popMatrix(); + if (flag && this.mc.objectMouseOver != null && !entity.isInsideOfMaterial(Material.water)) { + EntityPlayer entityplayer1 = (EntityPlayer) entity; + GlStateManager.disableAlpha(); + if (isDynamicLights) { + GlStateManager.disableExtensionPipeline(); + } + renderglobal.drawSelectionBox(entityplayer1, this.mc.objectMouseOver, 0, partialTicks); + GlStateManager.enableAlpha(); + if (isDynamicLights) { + GlStateManager.enableExtensionPipeline(); + } + } + + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, 1, 1, 0); + this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); + renderglobal.drawBlockDamageTexture(Tessellator.getInstance(), Tessellator.getInstance().getWorldRenderer(), + entity, partialTicks); + this.mc.getTextureManager().getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); + GlStateManager.disableBlend(); + if (!this.debugView) { + this.enableLightmap(); + effectrenderer.renderLitParticles(entity, partialTicks); + RenderHelper.disableStandardItemLighting(); + this.setupFog(0, partialTicks); + if (isDynamicLights) { + DynamicLightsStateManager.bindAcceleratedEffectRenderer(effectrenderer); + DynamicLightsStateManager.reportForwardRenderObjectPosition2(0.0f, 0.0f, 0.0f); + } + effectrenderer.renderParticles(entity, partialTicks, 2); + if (isDynamicLights) { + effectrenderer.acceleratedParticleRenderer = null; + } + this.disableLightmap(); + } + + GlStateManager.depthMask(false); + GlStateManager.enableCull(); + this.renderRainSnow(partialTicks); + GlStateManager.depthMask(true); + renderglobal.renderWorldBorder(entity, partialTicks); + GlStateManager.disableBlend(); + GlStateManager.enableCull(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + this.setupFog(0, partialTicks); + GlStateManager.enableBlend(); + GlStateManager.depthMask(false); + this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + GlStateManager.shadeModel(GL_SMOOTH); + renderglobal.renderBlockLayer(EnumWorldBlockLayer.TRANSLUCENT, (double) partialTicks, pass, entity); + GlStateManager.shadeModel(GL_FLAT); + GlStateManager.depthMask(true); + GlStateManager.enableCull(); + GlStateManager.disableBlend(); + GlStateManager.disableFog(); + if (entity.posY + (double) entity.getEyeHeight() >= 128.0D) { + this.renderCloudsCheck(renderglobal, partialTicks, pass); + } + + if (this.renderHand) { + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + this.renderHand(partialTicks, pass); + this.renderWorldDirections(partialTicks); + } + + } + + /** + * + Update and return fogColorBuffer with the RGBA values passed as arguments + */ + private FloatBuffer setFogColorBuffer(float red, float green, float blue, float alpha) { + this.fogColorBuffer.clear(); + this.fogColorBuffer.put(red).put(green).put(blue).put(alpha); + this.fogColorBuffer.flip(); + return this.fogColorBuffer; + } + + /** + * + sets up projection, view effects, camera position/rotation + */ + private void setupCameraTransform(float partialTicks, int pass) { + this.farPlaneDistance = (float) (this.mc.gameSettings.renderDistanceChunks * 16); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + float f = 0.07F; + if (this.mc.gameSettings.anaglyph) { + GlStateManager.translate((float) (-(pass * 2 - 1)) * f, 0.0F, 0.0F); + } + + if (this.cameraZoom != 1.0D) { + GlStateManager.translate((float) this.cameraYaw, (float) (-this.cameraPitch), 0.0F); + GlStateManager.scale(this.cameraZoom, this.cameraZoom, 1.0D); + } + + float farPlane = this.farPlaneDistance * 2.0f * MathHelper.SQRT_2; + GlStateManager.gluPerspective(currentProjMatrixFOV = this.getFOVModifier(partialTicks, true), + (float) this.mc.displayWidth / (float) this.mc.displayHeight, 0.05F, farPlane); + DeferredStateManager.setGBufferNearFarPlanes(0.05f, farPlane); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + if (this.mc.gameSettings.anaglyph) { + GlStateManager.translate((float) (pass * 2 - 1) * 0.1F, 0.0F, 0.0F); + } + + this.hurtCameraEffect(partialTicks); + if (this.mc.gameSettings.viewBobbing) { + this.setupViewBobbing(partialTicks); + } + + float f1 = this.mc.thePlayer.prevTimeInPortal + + (this.mc.thePlayer.timeInPortal - this.mc.thePlayer.prevTimeInPortal) * partialTicks; + if (f1 > 0.0F) { + byte b0 = 20; + if (this.mc.thePlayer.isPotionActive(Potion.confusion)) { + b0 = 7; + } + + float f2 = 5.0F / (f1 * f1 + 5.0F) - f1 * 0.04F; + f2 = f2 * f2; + GlStateManager.rotate(((float) this.rendererUpdateCount + partialTicks) * (float) b0, 0.0F, 1.0F, 1.0F); + GlStateManager.scale(1.0F / f2, 1.0F, 1.0F); + GlStateManager.rotate(-((float) this.rendererUpdateCount + partialTicks) * (float) b0, 0.0F, 1.0F, 1.0F); + } + + this.orientCamera(partialTicks); + if (this.debugView) { + switch (this.debugViewDirection) { + case 0: + GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); + break; + case 1: + GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); + break; + case 2: + GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); + break; + case 3: + GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); + break; + case 4: + GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F); + } + } + + } + + /** + * + Sets up the fog to be rendered. If the arg passed in is -1 the fog starts + * at 0 and goes to 80% of far plane distance and is used for sky rendering. + */ + private void setupFog(int partialTicks, float parFloat1) { + Entity entity = this.mc.getRenderViewEntity(); + boolean flag = false; + if (entity instanceof EntityPlayer) { + flag = ((EntityPlayer) entity).capabilities.isCreativeMode; + } + + EaglercraftGPU.glFog(GL_FOG_COLOR, + this.setFogColorBuffer(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 1.0F)); + EaglercraftGPU.glNormal3f(0.0F, -1.0F, 0.0F); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.mc.theWorld, entity, parFloat1); + if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(Potion.blindness)) { + float f1 = 5.0F; + int i = ((EntityLivingBase) entity).getActivePotionEffect(Potion.blindness).getDuration(); + if (i < 20) { + f1 = 5.0F + (this.farPlaneDistance - 5.0F) * (1.0F - (float) i / 20.0F); + } + + GlStateManager.setFog(GL_LINEAR); + if (partialTicks == -1) { + GlStateManager.setFogStart(0.0F); + GlStateManager.setFogEnd(f1 * 0.8F); + } else { + GlStateManager.setFogStart(f1 * 0.25F); + GlStateManager.setFogEnd(f1); + } + EaglercraftGPU.glFogi('\u855a', '\u855b'); + } else if (this.cloudFog) { + GlStateManager.setFog(GL_EXP); + GlStateManager.setFogDensity(0.1F); + } else if (block.getMaterial() == Material.water) { + GlStateManager.setFog(GL_EXP); + if (entity instanceof EntityLivingBase + && ((EntityLivingBase) entity).isPotionActive(Potion.waterBreathing)) { + GlStateManager.setFogDensity(0.01F); + } else { + GlStateManager.setFogDensity(0.1F - (float) EnchantmentHelper.getRespiration(entity) * 0.03F); + } + } else if (block.getMaterial() == Material.lava) { + GlStateManager.setFog(GL_EXP); + GlStateManager.setFogDensity(2.0F); + } else if (partialTicks != -1 && !this.mc.gameSettings.fog) { + GlStateManager.setFog(GL_EXP); + GlStateManager.setFogDensity(0.0F); + } else { + GlStateManager.setFogDensity(0.001F); + float f = this.farPlaneDistance; + GlStateManager.setFog(GL_LINEAR); + if (partialTicks == -1) { + GlStateManager.setFogStart(0.0F); + GlStateManager.setFogEnd(f); + } else { + GlStateManager.setFogStart(f * 0.75F); + GlStateManager.setFogEnd(f); + } + + EaglercraftGPU.glFogi('\u855a', '\u855b'); + + if (this.mc.theWorld.provider.doesXZShowFog((int) entity.posX, (int) entity.posZ)) { + GlStateManager.setFogStart(f * 0.05F); + GlStateManager.setFogEnd(Math.min(f, 192.0F) * 0.5F); + } + } + + GlStateManager.enableColorMaterial(); + GlStateManager.enableFog(); + } + + /** + * + Setup orthogonal projection for rendering GUI screen overlays + */ + public void setupOverlayRendering() { + ScaledResolution scaledresolution = mc.scaledResolution; + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.loadIdentity(); + GlStateManager.ortho(0.0D, scaledresolution.getScaledWidth_double(), scaledresolution.getScaledHeight_double(), + 0.0D, 1000.0D, 3000.0D); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.loadIdentity(); + GlStateManager.translate(0.0F, 0.0F, -2000.0F); + } + + /** + * + Setups all the GL settings for view bobbing. Args: partialTickTime + */ + private void setupViewBobbing(float partialTicks) { + if (this.mc.getRenderViewEntity() instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) this.mc.getRenderViewEntity(); + float f = entityplayer.distanceWalkedModified - entityplayer.prevDistanceWalkedModified; + float f1 = -(entityplayer.distanceWalkedModified + f * partialTicks); + float f2 = entityplayer.prevCameraYaw + + (entityplayer.cameraYaw - entityplayer.prevCameraYaw) * partialTicks; + float f3 = entityplayer.prevCameraPitch + + (entityplayer.cameraPitch - entityplayer.prevCameraPitch) * partialTicks; + GlStateManager.translate(MathHelper.sin(f1 * 3.1415927F) * f2 * 0.5F, + -Math.abs(MathHelper.cos(f1 * 3.1415927F) * f2), 0.0F); + GlStateManager.rotate(MathHelper.sin(f1 * 3.1415927F) * f2 * 3.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(Math.abs(MathHelper.cos(f1 * 3.1415927F - 0.2F) * f2) * 5.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(f3, 1.0F, 0.0F, 0.0F); + } + } + + public void switchUseShader() { + this.useShader = !this.useShader; + } + + private void updateDynamicLightListEagler(float partialTicks) { + DynamicLightsStateManager.clearRenderList(); + Entity entity = this.mc.getRenderViewEntity(); + double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; + double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; + double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; + AxisAlignedBB entityAABB = new AxisAlignedBB(d0 - 48.0, d1 - 32.0, d2 - 48.0, d0 + 48.0, d1 + 32.0, d2 + 48.0); + List entities = this.mc.theWorld.getEntitiesWithinAABB(Entity.class, entityAABB); + for (int i = 0, l = entities.size(); i < l; ++i) { + entities.get(i).renderDynamicLightsEaglerSimple(partialTicks); + } + DynamicLightsStateManager.commitLightSourceBuckets(d0, d1, d2); + } + + /** + * + calculates fog and calls glClearColor + */ + private void updateFogColor(float partialTicks) { + WorldClient worldclient = this.mc.theWorld; + Entity entity = this.mc.getRenderViewEntity(); + float f = 0.25F + 0.75F * (float) this.mc.gameSettings.renderDistanceChunks / 32.0F; + f = 1.0F - (float) Math.pow((double) f, 0.25D); + Vec3 vec3 = worldclient.getSkyColor(this.mc.getRenderViewEntity(), partialTicks); + float f1 = (float) vec3.xCoord; + float f2 = (float) vec3.yCoord; + float f3 = (float) vec3.zCoord; + Vec3 vec31 = worldclient.getFogColor(partialTicks); + this.fogColorRed = (float) vec31.xCoord; + this.fogColorGreen = (float) vec31.yCoord; + this.fogColorBlue = (float) vec31.zCoord; + if (this.mc.gameSettings.renderDistanceChunks >= 4) { + double d0 = -1.0D; + Vec3 vec32 = MathHelper.sin(worldclient.getCelestialAngleRadians(partialTicks)) > 0.0F + ? new Vec3(d0, 0.0D, 0.0D) + : new Vec3(1.0D, 0.0D, 0.0D); + float f5 = (float) entity.getLook(partialTicks).dotProduct(vec32); + if (f5 < 0.0F) { + f5 = 0.0F; + } + + if (f5 > 0.0F) { + float[] afloat = worldclient.provider + .calcSunriseSunsetColors(worldclient.getCelestialAngle(partialTicks), partialTicks); + if (afloat != null) { + f5 = f5 * afloat[3]; + this.fogColorRed = this.fogColorRed * (1.0F - f5) + afloat[0] * f5; + this.fogColorGreen = this.fogColorGreen * (1.0F - f5) + afloat[1] * f5; + this.fogColorBlue = this.fogColorBlue * (1.0F - f5) + afloat[2] * f5; + } + } + } + + this.fogColorRed += (f1 - this.fogColorRed) * f; + this.fogColorGreen += (f2 - this.fogColorGreen) * f; + this.fogColorBlue += (f3 - this.fogColorBlue) * f; + float f8 = worldclient.getRainStrength(partialTicks); + if (f8 > 0.0F) { + float f4 = 1.0F - f8 * 0.5F; + float f10 = 1.0F - f8 * 0.4F; + this.fogColorRed *= f4; + this.fogColorGreen *= f4; + this.fogColorBlue *= f10; + } + + float f9 = worldclient.getThunderStrength(partialTicks); + if (f9 > 0.0F) { + float f11 = 1.0F - f9 * 0.5F; + this.fogColorRed *= f11; + this.fogColorGreen *= f11; + this.fogColorBlue *= f11; + } + + Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.mc.theWorld, entity, partialTicks); + if (this.cloudFog) { + Vec3 vec33 = worldclient.getCloudColour(partialTicks); + this.fogColorRed = (float) vec33.xCoord; + this.fogColorGreen = (float) vec33.yCoord; + this.fogColorBlue = (float) vec33.zCoord; + } else if (block.getMaterial() == Material.water) { + float f12 = (float) EnchantmentHelper.getRespiration(entity) * 0.2F; + if (entity instanceof EntityLivingBase + && ((EntityLivingBase) entity).isPotionActive(Potion.waterBreathing)) { + f12 = f12 * 0.3F + 0.6F; + } + + this.fogColorRed = 0.02F + f12; + this.fogColorGreen = 0.02F + f12; + this.fogColorBlue = 0.2F + f12; + } else if (block.getMaterial() == Material.lava) { + this.fogColorRed = 0.6F; + this.fogColorGreen = 0.1F; + this.fogColorBlue = 0.0F; + } + + float f13 = this.fogColor2 + (this.fogColor1 - this.fogColor2) * partialTicks; + this.fogColorRed *= f13; + this.fogColorGreen *= f13; + this.fogColorBlue *= f13; + double d1 = (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks) + * worldclient.provider.getVoidFogYFactor(); + if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(Potion.blindness)) { + int i = ((EntityLivingBase) entity).getActivePotionEffect(Potion.blindness).getDuration(); + if (i < 20) { + d1 *= (double) (1.0F - (float) i / 20.0F); + } else { + d1 = 0.0D; + } + } + + if (d1 < 1.0D) { + if (d1 < 0.0D) { + d1 = 0.0D; + } + + d1 = d1 * d1; + this.fogColorRed = (float) ((double) this.fogColorRed * d1); + this.fogColorGreen = (float) ((double) this.fogColorGreen * d1); + this.fogColorBlue = (float) ((double) this.fogColorBlue * d1); + } + + if (this.bossColorModifier > 0.0F) { + float f14 = this.bossColorModifierPrev + + (this.bossColorModifier - this.bossColorModifierPrev) * partialTicks; + this.fogColorRed = this.fogColorRed * (1.0F - f14) + this.fogColorRed * 0.7F * f14; + this.fogColorGreen = this.fogColorGreen * (1.0F - f14) + this.fogColorGreen * 0.6F * f14; + this.fogColorBlue = this.fogColorBlue * (1.0F - f14) + this.fogColorBlue * 0.6F * f14; + } + + if (entity instanceof EntityLivingBase && ((EntityLivingBase) entity).isPotionActive(Potion.nightVision)) { + float f15 = this.getNightVisionBrightness((EntityLivingBase) entity, partialTicks); + float f6 = 1.0F / this.fogColorRed; + if (f6 > 1.0F / this.fogColorGreen) { + f6 = 1.0F / this.fogColorGreen; + } + + if (f6 > 1.0F / this.fogColorBlue) { + f6 = 1.0F / this.fogColorBlue; + } + + this.fogColorRed = this.fogColorRed * (1.0F - f15) + this.fogColorRed * f6 * f15; + this.fogColorGreen = this.fogColorGreen * (1.0F - f15) + this.fogColorGreen * f6 * f15; + this.fogColorBlue = this.fogColorBlue * (1.0F - f15) + this.fogColorBlue * f6 * f15; + } + + if (this.mc.gameSettings.anaglyph) { + float f16 = (this.fogColorRed * 30.0F + this.fogColorGreen * 59.0F + this.fogColorBlue * 11.0F) / 100.0F; + float f17 = (this.fogColorRed * 30.0F + this.fogColorGreen * 70.0F) / 100.0F; + float f7 = (this.fogColorRed * 30.0F + this.fogColorBlue * 70.0F) / 100.0F; + this.fogColorRed = f16; + this.fogColorGreen = f17; + this.fogColorBlue = f7; + } + + GlStateManager.clearColor(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 1.0F); + } + + /** + * + Update FOV modifier hand + */ + private void updateFovModifierHand() { + float f = 1.0F; + if (this.mc.getRenderViewEntity() instanceof AbstractClientPlayer) { + AbstractClientPlayer abstractclientplayer = (AbstractClientPlayer) this.mc.getRenderViewEntity(); + f = abstractclientplayer.getFovModifier(); + } + + this.fovModifierHandPrev = this.fovModifierHand; + this.fovModifierHand += (f - this.fovModifierHand) * 0.5F; + if (this.fovModifierHand > 1.5F) { + this.fovModifierHand = 1.5F; + } + + if (this.fovModifierHand < 0.1F) { + this.fovModifierHand = 0.1F; + } + + } + + private void updateLightmap(float partialTicks) { + if (this.lightmapUpdateNeeded) { + WorldClient worldclient = this.mc.theWorld; + if (worldclient != null) { + float f = worldclient.getSunBrightness(1.0F); + float f1 = f * 0.95F + 0.05F; + + for (int i = 0; i < 256; ++i) { + float f2 = worldclient.provider.getLightBrightnessTable()[i / 16] * f1; + float f3 = worldclient.provider.getLightBrightnessTable()[i % 16] + * (this.torchFlickerX * 0.1F + 1.5F); + if (worldclient.getLastLightningBolt() > 0) { + f2 = worldclient.provider.getLightBrightnessTable()[i / 16]; + } + + float f4 = f2 * (f * 0.65F + 0.35F); + float f5 = f2 * (f * 0.65F + 0.35F); + float f6 = f3 * ((f3 * 0.6F + 0.4F) * 0.6F + 0.4F); + float f7 = f3 * (f3 * f3 * 0.6F + 0.4F); + float f8 = f4 + f3; + float f9 = f5 + f6; + float f10 = f2 + f7; + f8 = f8 * 0.96F + 0.03F; + f9 = f9 * 0.96F + 0.03F; + f10 = f10 * 0.96F + 0.03F; + if (this.bossColorModifier > 0.0F) { + float f11 = this.bossColorModifierPrev + + (this.bossColorModifier - this.bossColorModifierPrev) * partialTicks; + f8 = f8 * (1.0F - f11) + f8 * 0.7F * f11; + f9 = f9 * (1.0F - f11) + f9 * 0.6F * f11; + f10 = f10 * (1.0F - f11) + f10 * 0.6F * f11; + } + + if (worldclient.provider.getDimensionId() == 1) { + f8 = 0.22F + f3 * 0.75F; + f9 = 0.28F + f6 * 0.75F; + f10 = 0.25F + f7 * 0.75F; + } + + if (this.mc.thePlayer.isPotionActive(Potion.nightVision)) { + float f15 = this.getNightVisionBrightness(this.mc.thePlayer, partialTicks); + float f12 = 1.0F / f8; + if (f12 > 1.0F / f9) { + f12 = 1.0F / f9; + } + + if (f12 > 1.0F / f10) { + f12 = 1.0F / f10; + } + + f8 = f8 * (1.0F - f15) + f8 * f12 * f15; + f9 = f9 * (1.0F - f15) + f9 * f12 * f15; + f10 = f10 * (1.0F - f15) + f10 * f12 * f15; + } + + if (f8 > 1.0F) { + f8 = 1.0F; + } + + if (f9 > 1.0F) { + f9 = 1.0F; + } + + if (f10 > 1.0F) { + f10 = 1.0F; + } + + float f16 = this.mc.gameSettings.gammaSetting; + float f17 = 1.0F - f8; + float f13 = 1.0F - f9; + float f14 = 1.0F - f10; + f17 = 1.0F - f17 * f17 * f17 * f17; + f13 = 1.0F - f13 * f13 * f13 * f13; + f14 = 1.0F - f14 * f14 * f14 * f14; + f8 = f8 * (1.0F - f16) + f17 * f16; + f9 = f9 * (1.0F - f16) + f13 * f16; + f10 = f10 * (1.0F - f16) + f14 * f16; + f8 = f8 * 0.96F + 0.03F; + f9 = f9 * 0.96F + 0.03F; + f10 = f10 * 0.96F + 0.03F; + if (f8 > 1.0F) { + f8 = 1.0F; + } + + if (f9 > 1.0F) { + f9 = 1.0F; + } + + if (f10 > 1.0F) { + f10 = 1.0F; + } + + if (f8 < 0.0F) { + f8 = 0.0F; + } + + if (f9 < 0.0F) { + f9 = 0.0F; + } + + if (f10 < 0.0F) { + f10 = 0.0F; + } + + short short1 = 255; + int j = (int) (f8 * 255.0F); + int k = (int) (f9 * 255.0F); + int l = (int) (f10 * 255.0F); + this.lightmapColors[i] = short1 << 24 | j | k << 8 | l << 16; + } + + this.lightmapTexture.updateDynamicTexture(); + + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + this.mc.getTextureManager().bindTexture(this.locationLightMap); + if (mc.gameSettings.fancyGraphics || mc.gameSettings.ambientOcclusion > 0 + || DynamicLightsStateManager.isDynamicLightsRender()) { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } else { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + + this.lightmapUpdateNeeded = false; + } + } + } + + /** + * + Updates the entity renderer + */ + public void updateRenderer() { + this.updateFovModifierHand(); + this.updateTorchFlicker(); + this.fogColor2 = this.fogColor1; + this.thirdPersonDistanceTemp = this.thirdPersonDistance; + if (this.mc.gameSettings.smoothCamera) { + float f = this.mc.gameSettings.mouseSensitivity * 0.6F + 0.2F; + float f1 = f * f * f * 8.0F; + this.smoothCamFilterX = this.mouseFilterXAxis.smooth(this.smoothCamYaw, 0.05F * f1); + this.smoothCamFilterY = this.mouseFilterYAxis.smooth(this.smoothCamPitch, 0.05F * f1); + this.smoothCamPartialTicks = 0.0F; + this.smoothCamYaw = 0.0F; + this.smoothCamPitch = 0.0F; + } else { + this.smoothCamFilterX = 0.0F; + this.smoothCamFilterY = 0.0F; + this.mouseFilterXAxis.reset(); + this.mouseFilterYAxis.reset(); + } + + if (this.mc.getRenderViewEntity() == null) { + this.mc.setRenderViewEntity(this.mc.thePlayer); + } + + float f3 = this.mc.theWorld.getLightBrightness( + DeferredStateManager.isDeferredRenderer() ? new BlockPos(this.mc.getRenderViewEntity()).up() + : new BlockPos(this.mc.getRenderViewEntity())); + float f4 = (float) this.mc.gameSettings.renderDistanceChunks / 32.0F; + float f2 = f3 * (1.0F - f4) + f4; + this.fogColor1 += (f2 - this.fogColor1) * 0.1F; + ++this.rendererUpdateCount; + this.itemRenderer.updateEquippedItem(); + this.addRainParticles(); + this.bossColorModifierPrev = this.bossColorModifier; + if (BossStatus.hasColorModifier) { + this.bossColorModifier += 0.05F; + if (this.bossColorModifier > 1.0F) { + this.bossColorModifier = 1.0F; + } + + BossStatus.hasColorModifier = false; + } else if (this.bossColorModifier > 0.0F) { + this.bossColorModifier -= 0.0125F; + } + + } + + public void updateShaderGroupSize(int width, int height) { + } + + /** + * + Recompute a random value that is applied to block color in updateLightmap() + */ + private void updateTorchFlicker() { + this.torchFlickerDX = (float) ((double) this.torchFlickerDX + + (Math.random() - Math.random()) * Math.random() * Math.random()); + this.torchFlickerDX = (float) ((double) this.torchFlickerDX * 0.9D); + this.torchFlickerX += (this.torchFlickerDX - this.torchFlickerX) * 1.0F; + this.lightmapUpdateNeeded = true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/EnumFaceDirection.java b/src/game/java/net/minecraft/client/renderer/EnumFaceDirection.java index e0634481..9c6934b7 100644 --- a/src/game/java/net/minecraft/client/renderer/EnumFaceDirection.java +++ b/src/game/java/net/minecraft/client/renderer/EnumFaceDirection.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -78,30 +81,6 @@ public enum EnumFaceDirection { new EnumFaceDirection.VertexInformation(EnumFaceDirection.Constants.EAST_INDEX, EnumFaceDirection.Constants.UP_INDEX, EnumFaceDirection.Constants.NORTH_INDEX) }); - private static final EnumFaceDirection[] facings = new EnumFaceDirection[6]; - private final EnumFaceDirection.VertexInformation[] vertexInfos; - - public static EnumFaceDirection getFacing(EnumFacing facing) { - return facings[facing.getIndex()]; - } - - private EnumFaceDirection(EnumFaceDirection.VertexInformation[] vertexInfosIn) { - this.vertexInfos = vertexInfosIn; - } - - public EnumFaceDirection.VertexInformation func_179025_a(int parInt1) { - return this.vertexInfos[parInt1]; - } - - static { - facings[EnumFaceDirection.Constants.DOWN_INDEX] = DOWN; - facings[EnumFaceDirection.Constants.UP_INDEX] = UP; - facings[EnumFaceDirection.Constants.NORTH_INDEX] = NORTH; - facings[EnumFaceDirection.Constants.SOUTH_INDEX] = SOUTH; - facings[EnumFaceDirection.Constants.WEST_INDEX] = WEST; - facings[EnumFaceDirection.Constants.EAST_INDEX] = EAST; - } - public static final class Constants { public static final int SOUTH_INDEX = EnumFacing.SOUTH.getIndex(); public static final int UP_INDEX = EnumFacing.UP.getIndex(); @@ -122,4 +101,29 @@ public enum EnumFaceDirection { this.field_179183_c = parInt3; } } + + private static final EnumFaceDirection[] facings = new EnumFaceDirection[6]; + + static { + facings[EnumFaceDirection.Constants.DOWN_INDEX] = DOWN; + facings[EnumFaceDirection.Constants.UP_INDEX] = UP; + facings[EnumFaceDirection.Constants.NORTH_INDEX] = NORTH; + facings[EnumFaceDirection.Constants.SOUTH_INDEX] = SOUTH; + facings[EnumFaceDirection.Constants.WEST_INDEX] = WEST; + facings[EnumFaceDirection.Constants.EAST_INDEX] = EAST; + } + + public static EnumFaceDirection getFacing(EnumFacing facing) { + return facings[facing.getIndex()]; + } + + private final EnumFaceDirection.VertexInformation[] vertexInfos; + + private EnumFaceDirection(EnumFaceDirection.VertexInformation[] vertexInfosIn) { + this.vertexInfos = vertexInfosIn; + } + + public EnumFaceDirection.VertexInformation func_179025_a(int parInt1) { + return this.vertexInfos[parInt1]; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/GLAllocation.java b/src/game/java/net/minecraft/client/renderer/GLAllocation.java index 1416e570..30ef1cb5 100644 --- a/src/game/java/net/minecraft/client/renderer/GLAllocation.java +++ b/src/game/java/net/minecraft/client/renderer/GLAllocation.java @@ -1,66 +1,68 @@ package net.minecraft.client.renderer; +import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; - -import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GLAllocation { - /**+ - * Generates the specified number of display lists and returns - * the first index. + /** + * + Creates and returns a direct byte buffer with the specified capacity. + * Applies native ordering to speed up access. */ - public static int generateDisplayLists() { - return EaglercraftGPU.glGenLists(); + public static ByteBuffer createDirectByteBuffer(int capacity) { + return EagRuntime.allocateByteBuffer(capacity); + } + + /** + * + Creates and returns a direct float buffer with the specified capacity. + * Applies native ordering to speed up access. + */ + public static FloatBuffer createDirectFloatBuffer(int capacity) { + return EagRuntime.allocateFloatBuffer(capacity); + } + + /** + * + Creates and returns a direct int buffer with the specified capacity. + * Applies native ordering to speed up access. + */ + public static IntBuffer createDirectIntBuffer(int capacity) { + return EagRuntime.allocateIntBuffer(capacity); } public static void deleteDisplayLists(int list) { EaglercraftGPU.glDeleteLists(list); } - /**+ - * Creates and returns a direct byte buffer with the specified - * capacity. Applies native ordering to speed up access. + /** + * + Generates the specified number of display lists and returns the first + * index. */ - public static ByteBuffer createDirectByteBuffer(int capacity) { - return EagRuntime.allocateByteBuffer(capacity); - } - - /**+ - * Creates and returns a direct int buffer with the specified - * capacity. Applies native ordering to speed up access. - */ - public static IntBuffer createDirectIntBuffer(int capacity) { - return EagRuntime.allocateIntBuffer(capacity); - } - - /**+ - * Creates and returns a direct float buffer with the specified - * capacity. Applies native ordering to speed up access. - */ - public static FloatBuffer createDirectFloatBuffer(int capacity) { - return EagRuntime.allocateFloatBuffer(capacity); + public static int generateDisplayLists() { + return EaglercraftGPU.glGenLists(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/IImageBuffer.java b/src/game/java/net/minecraft/client/renderer/IImageBuffer.java index 13025f70..79a6cfcb 100644 --- a/src/game/java/net/minecraft/client/renderer/IImageBuffer.java +++ b/src/game/java/net/minecraft/client/renderer/IImageBuffer.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer; import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/ImageBufferDownload.java b/src/game/java/net/minecraft/client/renderer/ImageBufferDownload.java index 625fa4f0..7f1261ec 100644 --- a/src/game/java/net/minecraft/client/renderer/ImageBufferDownload.java +++ b/src/game/java/net/minecraft/client/renderer/ImageBufferDownload.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer; import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,6 +30,22 @@ public class ImageBufferDownload implements IImageBuffer { private int imageWidth; private int imageHeight; + /** + * + Returns true if the given area of the image contains transparent pixels + */ + private boolean hasTransparency(int parInt1, int parInt2, int parInt3, int parInt4) { + for (int i = parInt1; i < parInt3; ++i) { + for (int j = parInt2; j < parInt4; ++j) { + int k = this.imageData[i + j * this.imageWidth]; + if ((k >> 24 & 255) < 128) { + return true; + } + } + } + + return false; + } + public ImageData parseUserSkin(ImageData bufferedimage) { if (bufferedimage == null) { return null; @@ -65,15 +84,23 @@ public class ImageBufferDownload implements IImageBuffer { } } - public void skinAvailable() { + /** + * + Makes the given area of the image opaque + */ + private void setAreaOpaque(int parInt1, int parInt2, int parInt3, int parInt4) { + for (int i = parInt1; i < parInt3; ++i) { + for (int j = parInt2; j < parInt4; ++j) { + this.imageData[i + j * this.imageWidth] |= -16777216; + } + } + } - /**+ - * Makes the given area of the image transparent if it was - * previously completely opaque (used to remove the outer layer - * of a skin around the head if it was saved all opaque; this - * would be redundant so it's assumed that the skin maker is - * just using an image editor without an alpha channel) + /** + * + Makes the given area of the image transparent if it was previously + * completely opaque (used to remove the outer layer of a skin around the head + * if it was saved all opaque; this would be redundant so it's assumed that the + * skin maker is just using an image editor without an alpha channel) */ private void setAreaTransparent(int parInt1, int parInt2, int parInt3, int parInt4) { if (!this.hasTransparency(parInt1, parInt2, parInt3, parInt4)) { @@ -86,32 +113,6 @@ public class ImageBufferDownload implements IImageBuffer { } } - /**+ - * Makes the given area of the image opaque - */ - private void setAreaOpaque(int parInt1, int parInt2, int parInt3, int parInt4) { - for (int i = parInt1; i < parInt3; ++i) { - for (int j = parInt2; j < parInt4; ++j) { - this.imageData[i + j * this.imageWidth] |= -16777216; - } - } - - } - - /**+ - * Returns true if the given area of the image contains - * transparent pixels - */ - private boolean hasTransparency(int parInt1, int parInt2, int parInt3, int parInt4) { - for (int i = parInt1; i < parInt3; ++i) { - for (int j = parInt2; j < parInt4; ++j) { - int k = this.imageData[i + j * this.imageWidth]; - if ((k >> 24 & 255) < 128) { - return true; - } - } - } - - return false; + public void skinAvailable() { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/InventoryEffectRenderer.java b/src/game/java/net/minecraft/client/renderer/InventoryEffectRenderer.java index 1aa56d1c..d0e1971f 100644 --- a/src/game/java/net/minecraft/client/renderer/InventoryEffectRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/InventoryEffectRenderer.java @@ -9,22 +9,25 @@ import net.minecraft.inventory.Container; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,41 +39,8 @@ public abstract class InventoryEffectRenderer extends GuiContainer { super(inventorySlotsIn); } - /**+ - * Adds the buttons (and other controls) to the screen in - * question. Called when the GUI is displayed and when the - * window resizes, the buttonList is cleared beforehand. - */ - public void initGui() { - super.initGui(); - this.updateActivePotionEffects(); - } - - protected void updateActivePotionEffects() { - if (!this.mc.thePlayer.getActivePotionEffects().isEmpty()) { - this.guiLeft = 160 + (this.width - this.xSize - 200) / 2; - this.hasActivePotionEffects = true; - } else { - this.guiLeft = (this.width - this.xSize) / 2; - this.hasActivePotionEffects = false; - } - - } - - /**+ - * Draws the screen and all the components in it. Args : mouseX, - * mouseY, renderPartialTicks - */ - public void drawScreen(int i, int j, float f) { - super.drawScreen(i, j, f); - if (this.hasActivePotionEffects) { - this.drawActivePotionEffects(); - } - - } - - /**+ - * Display the potion effects list + /** + * + Display the potion effects list */ private void drawActivePotionEffects() { int i = this.guiLeft - 124; @@ -113,4 +83,37 @@ public abstract class InventoryEffectRenderer extends GuiContainer { } } + + /** + * + Draws the screen and all the components in it. Args : mouseX, mouseY, + * renderPartialTicks + */ + public void drawScreen(int i, int j, float f) { + super.drawScreen(i, j, f); + if (this.hasActivePotionEffects) { + this.drawActivePotionEffects(); + } + + } + + /** + * + Adds the buttons (and other controls) to the screen in question. Called + * when the GUI is displayed and when the window resizes, the buttonList is + * cleared beforehand. + */ + public void initGui() { + super.initGui(); + this.updateActivePotionEffects(); + } + + protected void updateActivePotionEffects() { + if (!this.mc.thePlayer.getActivePotionEffects().isEmpty()) { + this.guiLeft = 160 + (this.width - this.xSize - 200) / 2; + this.hasActivePotionEffects = true; + } else { + this.guiLeft = (this.width - this.xSize) / 2; + this.hasActivePotionEffects = false; + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/ItemMeshDefinition.java b/src/game/java/net/minecraft/client/renderer/ItemMeshDefinition.java index 6f61cab1..b1182c91 100644 --- a/src/game/java/net/minecraft/client/renderer/ItemMeshDefinition.java +++ b/src/game/java/net/minecraft/client/renderer/ItemMeshDefinition.java @@ -3,22 +3,25 @@ package net.minecraft.client.renderer; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/ItemModelMesher.java b/src/game/java/net/minecraft/client/renderer/ItemModelMesher.java index 367c91f0..94696734 100644 --- a/src/game/java/net/minecraft/client/renderer/ItemModelMesher.java +++ b/src/game/java/net/minecraft/client/renderer/ItemModelMesher.java @@ -12,22 +12,25 @@ import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,12 +45,12 @@ public class ItemModelMesher { this.modelManager = modelManager; } - public EaglerTextureAtlasSprite getParticleIcon(Item item) { - return this.getParticleIcon(item, 0); + private int getIndex(Item item, int meta) { + return Item.getIdFromItem(item) << 16 | meta; } - public EaglerTextureAtlasSprite getParticleIcon(Item item, int meta) { - return this.getItemModel(new ItemStack(item, 1, meta)).getParticleTexture(); + protected IBakedModel getItemModel(Item item, int meta) { + return (IBakedModel) this.simpleShapesCache.get(Integer.valueOf(this.getIndex(item, meta))); } public IBakedModel getItemModel(ItemStack stack) { @@ -71,27 +74,18 @@ public class ItemModelMesher { return stack.isItemStackDamageable() ? 0 : stack.getMetadata(); } - protected IBakedModel getItemModel(Item item, int meta) { - return (IBakedModel) this.simpleShapesCache.get(Integer.valueOf(this.getIndex(item, meta))); - } - - private int getIndex(Item item, int meta) { - return Item.getIdFromItem(item) << 16 | meta; - } - - public void register(Item item, int meta, ModelResourceLocation location) { - this.simpleShapes.put(Integer.valueOf(this.getIndex(item, meta)), location); - this.simpleShapesCache.put(Integer.valueOf(this.getIndex(item, meta)), this.modelManager.getModel(location)); - } - - public void register(Item item, ItemMeshDefinition definition) { - this.shapers.put(item, definition); - } - public ModelManager getModelManager() { return this.modelManager; } + public EaglerTextureAtlasSprite getParticleIcon(Item item) { + return this.getParticleIcon(item, 0); + } + + public EaglerTextureAtlasSprite getParticleIcon(Item item, int meta) { + return this.getItemModel(new ItemStack(item, 1, meta)).getParticleTexture(); + } + public void rebuildCache() { this.simpleShapesCache.clear(); @@ -101,4 +95,13 @@ public class ItemModelMesher { } } + + public void register(Item item, int meta, ModelResourceLocation location) { + this.simpleShapes.put(Integer.valueOf(this.getIndex(item, meta)), location); + this.simpleShapesCache.put(Integer.valueOf(this.getIndex(item, meta)), this.modelManager.getModel(location)); + } + + public void register(Item item, ItemMeshDefinition definition) { + this.shapers.put(item, definition); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/ItemRenderer.java b/src/game/java/net/minecraft/client/renderer/ItemRenderer.java index c5733a3e..e0a95133 100644 --- a/src/game/java/net/minecraft/client/renderer/ItemRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/ItemRenderer.java @@ -1,6 +1,9 @@ package net.minecraft.client.renderer; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ALWAYS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; @@ -8,7 +11,6 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.OpenGlHelper; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.minecraft.block.Block; -import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.AbstractClientPlayer; @@ -31,38 +33,41 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemRenderer { private static final ResourceLocation RES_MAP_BACKGROUND = new ResourceLocation("textures/map/map_background.png"); - private static final ResourceLocation RES_UNDERWATER_OVERLAY = new ResourceLocation("textures/misc/underwater.png"); + // private static final ResourceLocation RES_UNDERWATER_OVERLAY = new + // ResourceLocation("textures/misc/underwater.png"); private final Minecraft mc; private ItemStack itemToRender; private float equippedProgress; private float prevEquippedProgress; private final RenderManager renderManager; private final RenderItem itemRenderer; - /**+ - * The index of the currently held item (0-8, or -1 if not yet - * updated) + /** + * + The index of the currently held item (0-8, or -1 if not yet updated) */ private int equippedItemSlot = -1; @@ -72,141 +77,6 @@ public class ItemRenderer { this.itemRenderer = mcIn.getRenderItem(); } - public void renderItem(EntityLivingBase entityIn, ItemStack heldStack, - ItemCameraTransforms.TransformType transform) { - if (heldStack != null) { - Item item = heldStack.getItem(); - Block block = Block.getBlockFromItem(item); - GlStateManager.pushMatrix(); - if (this.itemRenderer.shouldRenderItemIn3D(heldStack)) { - GlStateManager.scale(2.0F, 2.0F, 2.0F); -// if (this.isBlockTranslucent(block)) { //TODO: figure out why this code exists, it breaks slime blocks -// GlStateManager.depthMask(false); -// } - } - - this.itemRenderer.renderItemModelForEntity(heldStack, entityIn, transform); -// if (this.isBlockTranslucent(block)) { -// GlStateManager.depthMask(true); -// } - - GlStateManager.popMatrix(); - } - } - - /**+ - * Returns true if given block is translucent - */ - private boolean isBlockTranslucent(Block blockIn) { - return blockIn != null && blockIn.getBlockLayer() == EnumWorldBlockLayer.TRANSLUCENT; - } - - private void func_178101_a(float angle, float parFloat2) { - GlStateManager.pushMatrix(); - GlStateManager.rotate(angle, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(parFloat2, 0.0F, 1.0F, 0.0F); - RenderHelper.enableStandardItemLighting(); - GlStateManager.popMatrix(); - } - - private void func_178109_a(AbstractClientPlayer clientPlayer) { - int i = this.mc.theWorld.getCombinedLight(new BlockPos(clientPlayer.posX, - clientPlayer.posY + (double) clientPlayer.getEyeHeight(), clientPlayer.posZ), 0); - float f = (float) (i & '\uffff'); - float f1 = (float) (i >> 16); - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, f, f1); - } - - private void func_178110_a(EntityPlayerSP entityplayerspIn, float partialTicks) { - float f = entityplayerspIn.prevRenderArmPitch - + (entityplayerspIn.renderArmPitch - entityplayerspIn.prevRenderArmPitch) * partialTicks; - float f1 = entityplayerspIn.prevRenderArmYaw - + (entityplayerspIn.renderArmYaw - entityplayerspIn.prevRenderArmYaw) * partialTicks; - GlStateManager.rotate((entityplayerspIn.rotationPitch - f) * 0.1F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate((entityplayerspIn.rotationYaw - f1) * 0.1F, 0.0F, 1.0F, 0.0F); - } - - private float func_178100_c(float parFloat1) { - float f = 1.0F - parFloat1 / 45.0F + 0.1F; - f = MathHelper.clamp_float(f, 0.0F, 1.0F); - f = -MathHelper.cos(f * 3.1415927F) * 0.5F + 0.5F; - return f; - } - - private void renderRightArm(RenderPlayer renderPlayerIn) { - GlStateManager.pushMatrix(); - GlStateManager.rotate(54.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(64.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(-62.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.translate(0.25F, -0.85F, 0.75F); - renderPlayerIn.renderRightArm(this.mc.thePlayer); - GlStateManager.popMatrix(); - } - - private void renderLeftArm(RenderPlayer renderPlayerIn) { - GlStateManager.pushMatrix(); - GlStateManager.rotate(92.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(45.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(41.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.translate(-0.3F, -1.1F, 0.45F); - renderPlayerIn.renderLeftArm(this.mc.thePlayer); - GlStateManager.popMatrix(); - } - - private void renderPlayerArms(AbstractClientPlayer clientPlayer) { - this.mc.getTextureManager().bindTexture(clientPlayer.getLocationSkin()); - Render render = this.renderManager.getEntityRenderObject(this.mc.thePlayer); - RenderPlayer renderplayer = (RenderPlayer) render; - if (!clientPlayer.isInvisible()) { - GlStateManager.disableCull(); - this.renderRightArm(renderplayer); - this.renderLeftArm(renderplayer); - GlStateManager.enableCull(); - } - - } - - private void renderItemMap(AbstractClientPlayer clientPlayer, float parFloat1, float parFloat2, float parFloat3) { - float f = -0.4F * MathHelper.sin(MathHelper.sqrt_float(parFloat3) * 3.1415927F); - float f1 = 0.2F * MathHelper.sin(MathHelper.sqrt_float(parFloat3) * 3.1415927F * 2.0F); - float f2 = -0.2F * MathHelper.sin(parFloat3 * 3.1415927F); - GlStateManager.translate(f, f1, f2); - float f3 = this.func_178100_c(parFloat1); - GlStateManager.translate(0.0F, 0.04F, -0.72F); - GlStateManager.translate(0.0F, parFloat2 * -1.2F, 0.0F); - GlStateManager.translate(0.0F, f3 * -0.5F, 0.0F); - GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(f3 * -85.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(0.0F, 1.0F, 0.0F, 0.0F); - this.renderPlayerArms(clientPlayer); - float f4 = MathHelper.sin(parFloat3 * parFloat3 * 3.1415927F); - float f5 = MathHelper.sin(MathHelper.sqrt_float(parFloat3) * 3.1415927F); - GlStateManager.rotate(f4 * -20.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(f5 * -20.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(f5 * -80.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.scale(0.38F, 0.38F, 0.38F); - GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(0.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.translate(-1.0F, -1.0F, 0.0F); - GlStateManager.scale(0.015625F, 0.015625F, 0.015625F); - this.mc.getTextureManager().bindTexture(RES_MAP_BACKGROUND); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - EaglercraftGPU.glNormal3f(0.0F, 0.0F, -1.0F); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(-7.0D, 135.0D, 0.0D).tex(0.0D, 1.0D).endVertex(); - worldrenderer.pos(135.0D, 135.0D, 0.0D).tex(1.0D, 1.0D).endVertex(); - worldrenderer.pos(135.0D, -7.0D, 0.0D).tex(1.0D, 0.0D).endVertex(); - worldrenderer.pos(-7.0D, -7.0D, 0.0D).tex(0.0D, 0.0D).endVertex(); - tessellator.draw(); - MapData mapdata = Items.filled_map.getMapData(this.itemToRender, this.mc.theWorld); - if (mapdata != null) { - this.mc.entityRenderer.getMapItemRenderer().renderMap(mapdata, false); - } - - } - private void func_178095_a(AbstractClientPlayer clientPlayer, float parFloat1, float parFloat2) { float f = -0.3F * MathHelper.sin(MathHelper.sqrt_float(parFloat2) * 3.1415927F); float f1 = 0.4F * MathHelper.sin(MathHelper.sqrt_float(parFloat2) * 3.1415927F * 2.0F); @@ -233,45 +103,6 @@ public class ItemRenderer { GlStateManager.enableCull(); } - private void func_178105_d(float parFloat1) { - float f = -0.4F * MathHelper.sin(MathHelper.sqrt_float(parFloat1) * 3.1415927F); - float f1 = 0.2F * MathHelper.sin(MathHelper.sqrt_float(parFloat1) * 3.1415927F * 2.0F); - float f2 = -0.2F * MathHelper.sin(parFloat1 * 3.1415927F); - GlStateManager.translate(f, f1, f2); - } - - private void func_178104_a(AbstractClientPlayer clientPlayer, float parFloat1) { - float f = (float) clientPlayer.getItemInUseCount() - parFloat1 + 1.0F; - float f1 = f / (float) this.itemToRender.getMaxItemUseDuration(); - float f2 = MathHelper.abs(MathHelper.cos(f / 4.0F * 3.1415927F) * 0.1F); - if (f1 >= 0.8F) { - f2 = 0.0F; - } - - GlStateManager.translate(0.0F, f2, 0.0F); - float f3 = 1.0F - (float) Math.pow((double) f1, 27.0D); - GlStateManager.translate(f3 * 0.6F, f3 * -0.5F, f3 * 0.0F); - GlStateManager.rotate(f3 * 90.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(f3 * 10.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(f3 * 30.0F, 0.0F, 0.0F, 1.0F); - } - - /**+ - * Performs transformations prior to the rendering of a held - * item in first person. - */ - private void transformFirstPersonItem(float equipProgress, float swingProgress) { - GlStateManager.translate(0.56F, -0.52F, -0.71999997F); - GlStateManager.translate(0.0F, equipProgress * -0.6F, 0.0F); - GlStateManager.rotate(45.0F, 0.0F, 1.0F, 0.0F); - float f = MathHelper.sin(swingProgress * swingProgress * 3.1415927F); - float f1 = MathHelper.sin(MathHelper.sqrt_float(swingProgress) * 3.1415927F); - GlStateManager.rotate(f * -20.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(f1 * -20.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(f1 * -80.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.scale(0.4F, 0.4F, 0.4F); - } - private void func_178098_a(float clientPlayer, AbstractClientPlayer parAbstractClientPlayer) { GlStateManager.rotate(-18.0F, 0.0F, 0.0F, 1.0F); GlStateManager.rotate(-12.0F, 0.0F, 1.0F, 0.0F); @@ -296,6 +127,21 @@ public class ItemRenderer { GlStateManager.scale(1.0F, 1.0F, 1.0F + f1 * 0.2F); } + private float func_178100_c(float parFloat1) { + float f = 1.0F - parFloat1 / 45.0F + 0.1F; + f = MathHelper.clamp_float(f, 0.0F, 1.0F); + f = -MathHelper.cos(f * 3.1415927F) * 0.5F + 0.5F; + return f; + } + + private void func_178101_a(float angle, float parFloat2) { + GlStateManager.pushMatrix(); + GlStateManager.rotate(angle, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(parFloat2, 0.0F, 1.0F, 0.0F); + RenderHelper.enableStandardItemLighting(); + GlStateManager.popMatrix(); + } + private void func_178103_d() { GlStateManager.translate(-0.5F, 0.2F, 0.0F); GlStateManager.rotate(30.0F, 0.0F, 1.0F, 0.0F); @@ -303,9 +149,148 @@ public class ItemRenderer { GlStateManager.rotate(60.0F, 0.0F, 1.0F, 0.0F); } - /**+ - * Renders the active item in the player's hand when in first - * person mode. Args: partialTickTime + private void func_178104_a(AbstractClientPlayer clientPlayer, float parFloat1) { + float f = (float) clientPlayer.getItemInUseCount() - parFloat1 + 1.0F; + float f1 = f / (float) this.itemToRender.getMaxItemUseDuration(); + float f2 = MathHelper.abs(MathHelper.cos(f / 4.0F * 3.1415927F) * 0.1F); + if (f1 >= 0.8F) { + f2 = 0.0F; + } + + GlStateManager.translate(0.0F, f2, 0.0F); + float f3 = 1.0F - (float) Math.pow((double) f1, 27.0D); + GlStateManager.translate(f3 * 0.6F, f3 * -0.5F, f3 * 0.0F); + GlStateManager.rotate(f3 * 90.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(f3 * 10.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(f3 * 30.0F, 0.0F, 0.0F, 1.0F); + } + + private void func_178105_d(float parFloat1) { + float f = -0.4F * MathHelper.sin(MathHelper.sqrt_float(parFloat1) * 3.1415927F); + float f1 = 0.2F * MathHelper.sin(MathHelper.sqrt_float(parFloat1) * 3.1415927F * 2.0F); + float f2 = -0.2F * MathHelper.sin(parFloat1 * 3.1415927F); + GlStateManager.translate(f, f1, f2); + } + + private void func_178108_a(float parFloat1, EaglerTextureAtlasSprite parTextureAtlasSprite) { + this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + float f = 0.1F; + GlStateManager.color(0.1F, 0.1F, 0.1F, 0.5F); + GlStateManager.pushMatrix(); + float f1 = -1.0F; + float f2 = 1.0F; + float f3 = -1.0F; + float f4 = 1.0F; + float f5 = -0.5F; + float f6 = parTextureAtlasSprite.getMinU(); + float f7 = parTextureAtlasSprite.getMaxU(); + float f8 = parTextureAtlasSprite.getMinV(); + float f9 = parTextureAtlasSprite.getMaxV(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos(-1.0D, -1.0D, -0.5D).tex((double) f7, (double) f9).endVertex(); + worldrenderer.pos(1.0D, -1.0D, -0.5D).tex((double) f6, (double) f9).endVertex(); + worldrenderer.pos(1.0D, 1.0D, -0.5D).tex((double) f6, (double) f8).endVertex(); + worldrenderer.pos(-1.0D, 1.0D, -0.5D).tex((double) f7, (double) f8).endVertex(); + tessellator.draw(); + GlStateManager.popMatrix(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + + private void func_178109_a(AbstractClientPlayer clientPlayer) { + int i = this.mc.theWorld.getCombinedLight(new BlockPos(clientPlayer.posX, + clientPlayer.posY + (double) clientPlayer.getEyeHeight(), clientPlayer.posZ), 0); + float f = (float) (i & '\uffff'); + float f1 = (float) (i >> 16); + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, f, f1); + } + + private void func_178110_a(EntityPlayerSP entityplayerspIn, float partialTicks) { + float f = entityplayerspIn.prevRenderArmPitch + + (entityplayerspIn.renderArmPitch - entityplayerspIn.prevRenderArmPitch) * partialTicks; + float f1 = entityplayerspIn.prevRenderArmYaw + + (entityplayerspIn.renderArmYaw - entityplayerspIn.prevRenderArmYaw) * partialTicks; + GlStateManager.rotate((entityplayerspIn.rotationPitch - f) * 0.1F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate((entityplayerspIn.rotationYaw - f1) * 0.1F, 0.0F, 1.0F, 0.0F); + } + + /** + * + Returns true if given block is translucent + */ + private boolean isBlockTranslucent(Block blockIn) { + return blockIn != null && blockIn.getBlockLayer() == EnumWorldBlockLayer.TRANSLUCENT; + } + + /** + * + Renders the fire on the screen for first person mode. Arg: partialTickTime + */ + private void renderFireInFirstPerson(float parFloat1) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 0.9F); + GlStateManager.depthFunc(GL_ALWAYS); + GlStateManager.depthMask(false); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + float f = 1.0F; + + for (int i = 0; i < 2; ++i) { + GlStateManager.pushMatrix(); + EaglerTextureAtlasSprite textureatlassprite = this.mc.getTextureMapBlocks() + .getAtlasSprite("minecraft:blocks/fire_layer_1"); + this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + float f1 = textureatlassprite.getMinU(); + float f2 = textureatlassprite.getMaxU(); + float f3 = textureatlassprite.getMinV(); + float f4 = textureatlassprite.getMaxV(); + float f5 = (0.0F - f) / 2.0F; + float f6 = f5 + f; + float f7 = 0.0F - f / 2.0F; + float f8 = f7 + f; + float f9 = -0.5F; + GlStateManager.translate((float) (-(i * 2 - 1)) * 0.24F, -0.3F, 0.0F); + GlStateManager.rotate((float) (i * 2 - 1) * 10.0F, 0.0F, 1.0F, 0.0F); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) f5, (double) f7, (double) f9).tex((double) f2, (double) f4).endVertex(); + worldrenderer.pos((double) f6, (double) f7, (double) f9).tex((double) f1, (double) f4).endVertex(); + worldrenderer.pos((double) f6, (double) f8, (double) f9).tex((double) f1, (double) f3).endVertex(); + worldrenderer.pos((double) f5, (double) f8, (double) f9).tex((double) f2, (double) f3).endVertex(); + tessellator.draw(); + GlStateManager.popMatrix(); + } + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableBlend(); + GlStateManager.depthMask(true); + GlStateManager.depthFunc(GL_LEQUAL); + } + + public void renderItem(EntityLivingBase entityIn, ItemStack heldStack, + ItemCameraTransforms.TransformType transform) { + if (heldStack != null) { + Item item = heldStack.getItem(); + Block block = Block.getBlockFromItem(item); + GlStateManager.pushMatrix(); + if (this.itemRenderer.shouldRenderItemIn3D(heldStack)) { + GlStateManager.scale(2.0F, 2.0F, 2.0F); +// if (this.isBlockTranslucent(block)) { //TODO: figure out why this code exists, it breaks slime blocks +// GlStateManager.depthMask(false); +// } + } + + this.itemRenderer.renderItemModelForEntity(heldStack, entityIn, transform); +// if (this.isBlockTranslucent(block)) { +// GlStateManager.depthMask(true); +// } + + GlStateManager.popMatrix(); + } + } + + /** + * + Renders the active item in the player's hand when in first person mode. + * Args: partialTickTime */ public void renderItemInFirstPerson(float partialTicks) { float f = 1.0F @@ -358,8 +343,59 @@ public class ItemRenderer { RenderHelper.disableStandardItemLighting(); } - /**+ - * Renders all the overlays that are in first person mode. Args: + private void renderItemMap(AbstractClientPlayer clientPlayer, float parFloat1, float parFloat2, float parFloat3) { + float f = -0.4F * MathHelper.sin(MathHelper.sqrt_float(parFloat3) * 3.1415927F); + float f1 = 0.2F * MathHelper.sin(MathHelper.sqrt_float(parFloat3) * 3.1415927F * 2.0F); + float f2 = -0.2F * MathHelper.sin(parFloat3 * 3.1415927F); + GlStateManager.translate(f, f1, f2); + float f3 = this.func_178100_c(parFloat1); + GlStateManager.translate(0.0F, 0.04F, -0.72F); + GlStateManager.translate(0.0F, parFloat2 * -1.2F, 0.0F); + GlStateManager.translate(0.0F, f3 * -0.5F, 0.0F); + GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(f3 * -85.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(0.0F, 1.0F, 0.0F, 0.0F); + this.renderPlayerArms(clientPlayer); + float f4 = MathHelper.sin(parFloat3 * parFloat3 * 3.1415927F); + float f5 = MathHelper.sin(MathHelper.sqrt_float(parFloat3) * 3.1415927F); + GlStateManager.rotate(f4 * -20.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(f5 * -20.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(f5 * -80.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.scale(0.38F, 0.38F, 0.38F); + GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(0.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.translate(-1.0F, -1.0F, 0.0F); + GlStateManager.scale(0.015625F, 0.015625F, 0.015625F); + this.mc.getTextureManager().bindTexture(RES_MAP_BACKGROUND); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + EaglercraftGPU.glNormal3f(0.0F, 0.0F, -1.0F); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos(-7.0D, 135.0D, 0.0D).tex(0.0D, 1.0D).endVertex(); + worldrenderer.pos(135.0D, 135.0D, 0.0D).tex(1.0D, 1.0D).endVertex(); + worldrenderer.pos(135.0D, -7.0D, 0.0D).tex(1.0D, 0.0D).endVertex(); + worldrenderer.pos(-7.0D, -7.0D, 0.0D).tex(0.0D, 0.0D).endVertex(); + tessellator.draw(); + MapData mapdata = Items.filled_map.getMapData(this.itemToRender, this.mc.theWorld); + if (mapdata != null) { + this.mc.entityRenderer.getMapItemRenderer().renderMap(mapdata, false); + } + + } + + private void renderLeftArm(RenderPlayer renderPlayerIn) { + GlStateManager.pushMatrix(); + GlStateManager.rotate(92.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(45.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(41.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.translate(-0.3F, -1.1F, 0.45F); + renderPlayerIn.renderLeftArm(this.mc.thePlayer); + GlStateManager.popMatrix(); + } + + /** + * + Renders all the overlays that are in first person mode. Args: * partialTickTime */ public void renderOverlays(float partialTicks) { @@ -388,9 +424,10 @@ public class ItemRenderer { } if (!this.mc.thePlayer.isSpectator()) { - if (this.mc.thePlayer.isInsideOfMaterial(Material.water)) { - this.renderWaterOverlayTexture(partialTicks); - } + /* + * if (this.mc.thePlayer.isInsideOfMaterial(Material.water)) { + * this.renderWaterOverlayTexture(partialTicks); } + */ if (this.mc.thePlayer.isBurning()) { this.renderFireInFirstPerson(partialTicks); @@ -400,108 +437,84 @@ public class ItemRenderer { GlStateManager.enableAlpha(); } - private void func_178108_a(float parFloat1, EaglerTextureAtlasSprite parTextureAtlasSprite) { - this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - float f = 0.1F; - GlStateManager.color(0.1F, 0.1F, 0.1F, 0.5F); - GlStateManager.pushMatrix(); - float f1 = -1.0F; - float f2 = 1.0F; - float f3 = -1.0F; - float f4 = 1.0F; - float f5 = -0.5F; - float f6 = parTextureAtlasSprite.getMinU(); - float f7 = parTextureAtlasSprite.getMaxU(); - float f8 = parTextureAtlasSprite.getMinV(); - float f9 = parTextureAtlasSprite.getMaxV(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(-1.0D, -1.0D, -0.5D).tex((double) f7, (double) f9).endVertex(); - worldrenderer.pos(1.0D, -1.0D, -0.5D).tex((double) f6, (double) f9).endVertex(); - worldrenderer.pos(1.0D, 1.0D, -0.5D).tex((double) f6, (double) f8).endVertex(); - worldrenderer.pos(-1.0D, 1.0D, -0.5D).tex((double) f7, (double) f8).endVertex(); - tessellator.draw(); - GlStateManager.popMatrix(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - } - - /**+ - * Renders a texture that warps around based on the direction - * the player is looking. Texture needs to be bound before being - * called. Used for the water overlay. Args: parialTickTime - */ - private void renderWaterOverlayTexture(float parFloat1) { - this.mc.getTextureManager().bindTexture(RES_UNDERWATER_OVERLAY); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - float f = this.mc.thePlayer.getBrightness(parFloat1); - GlStateManager.color(f, f, f, 0.5F); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.pushMatrix(); - float f1 = 4.0F; - float f2 = -1.0F; - float f3 = 1.0F; - float f4 = -1.0F; - float f5 = 1.0F; - float f6 = -0.5F; - float f7 = -this.mc.thePlayer.rotationYaw / 64.0F; - float f8 = this.mc.thePlayer.rotationPitch / 64.0F; - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(-1.0D, -1.0D, -0.5D).tex((double) (4.0F + f7), (double) (4.0F + f8)).endVertex(); - worldrenderer.pos(1.0D, -1.0D, -0.5D).tex((double) (0.0F + f7), (double) (4.0F + f8)).endVertex(); - worldrenderer.pos(1.0D, 1.0D, -0.5D).tex((double) (0.0F + f7), (double) (0.0F + f8)).endVertex(); - worldrenderer.pos(-1.0D, 1.0D, -0.5D).tex((double) (4.0F + f7), (double) (0.0F + f8)).endVertex(); - tessellator.draw(); - GlStateManager.popMatrix(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableBlend(); - } - - /**+ - * Renders the fire on the screen for first person mode. Arg: - * partialTickTime - */ - private void renderFireInFirstPerson(float parFloat1) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 0.9F); - GlStateManager.depthFunc(GL_ALWAYS); - GlStateManager.depthMask(false); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - float f = 1.0F; - - for (int i = 0; i < 2; ++i) { - GlStateManager.pushMatrix(); - EaglerTextureAtlasSprite textureatlassprite = this.mc.getTextureMapBlocks() - .getAtlasSprite("minecraft:blocks/fire_layer_1"); - this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - float f1 = textureatlassprite.getMinU(); - float f2 = textureatlassprite.getMaxU(); - float f3 = textureatlassprite.getMinV(); - float f4 = textureatlassprite.getMaxV(); - float f5 = (0.0F - f) / 2.0F; - float f6 = f5 + f; - float f7 = 0.0F - f / 2.0F; - float f8 = f7 + f; - float f9 = -0.5F; - GlStateManager.translate((float) (-(i * 2 - 1)) * 0.24F, -0.3F, 0.0F); - GlStateManager.rotate((float) (i * 2 - 1) * 10.0F, 0.0F, 1.0F, 0.0F); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) f5, (double) f7, (double) f9).tex((double) f2, (double) f4).endVertex(); - worldrenderer.pos((double) f6, (double) f7, (double) f9).tex((double) f1, (double) f4).endVertex(); - worldrenderer.pos((double) f6, (double) f8, (double) f9).tex((double) f1, (double) f3).endVertex(); - worldrenderer.pos((double) f5, (double) f8, (double) f9).tex((double) f2, (double) f3).endVertex(); - tessellator.draw(); - GlStateManager.popMatrix(); + private void renderPlayerArms(AbstractClientPlayer clientPlayer) { + this.mc.getTextureManager().bindTexture(clientPlayer.getLocationSkin()); + Render render = this.renderManager.getEntityRenderObject(this.mc.thePlayer); + RenderPlayer renderplayer = (RenderPlayer) render; + if (!clientPlayer.isInvisible()) { + GlStateManager.disableCull(); + this.renderRightArm(renderplayer); + this.renderLeftArm(renderplayer); + GlStateManager.enableCull(); } - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - GlStateManager.depthFunc(GL_LEQUAL); + } + + private void renderRightArm(RenderPlayer renderPlayerIn) { + GlStateManager.pushMatrix(); + GlStateManager.rotate(54.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(64.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(-62.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.translate(0.25F, -0.85F, 0.75F); + renderPlayerIn.renderRightArm(this.mc.thePlayer); + GlStateManager.popMatrix(); + } + + /** + * + Renders a texture that warps around based on the direction the player is + * looking. Texture needs to be bound before being called. Used for the water + * overlay. Args: parialTickTime + */ + /* + * private void renderWaterOverlayTexture(float parFloat1) { + * this.mc.getTextureManager().bindTexture(RES_UNDERWATER_OVERLAY); Tessellator + * tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = + * tessellator.getWorldRenderer(); float f = + * this.mc.thePlayer.getBrightness(parFloat1); GlStateManager.color(f, f, f, + * 0.5F); GlStateManager.enableBlend(); + * GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, + * 0); GlStateManager.pushMatrix(); float f1 = 4.0F; float f2 = -1.0F; float f3 + * = 1.0F; float f4 = -1.0F; float f5 = 1.0F; float f6 = -0.5F; float f7 = + * -this.mc.thePlayer.rotationYaw / 64.0F; float f8 = + * this.mc.thePlayer.rotationPitch / 64.0F; worldrenderer.begin(7, + * DefaultVertexFormats.POSITION_TEX); worldrenderer.pos(-1.0D, -1.0D, + * -0.5D).tex((double) (4.0F + f7), (double) (4.0F + f8)).endVertex(); + * worldrenderer.pos(1.0D, -1.0D, -0.5D).tex((double) (0.0F + f7), (double) + * (4.0F + f8)).endVertex(); worldrenderer.pos(1.0D, 1.0D, -0.5D).tex((double) + * (0.0F + f7), (double) (0.0F + f8)).endVertex(); worldrenderer.pos(-1.0D, + * 1.0D, -0.5D).tex((double) (4.0F + f7), (double) (0.0F + f8)).endVertex(); + * tessellator.draw(); GlStateManager.popMatrix(); GlStateManager.color(1.0F, + * 1.0F, 1.0F, 1.0F); GlStateManager.disableBlend(); } + */ + + /** + * + Resets equippedProgress + */ + public void resetEquippedProgress() { + this.equippedProgress = 0.0F; + } + + /** + * + Resets equippedProgress + */ + public void resetEquippedProgress2() { + this.equippedProgress = 0.0F; + } + + /** + * + Performs transformations prior to the rendering of a held item in first + * person. + */ + private void transformFirstPersonItem(float equipProgress, float swingProgress) { + GlStateManager.translate(0.56F, -0.52F, -0.71999997F); + GlStateManager.translate(0.0F, equipProgress * -0.6F, 0.0F); + GlStateManager.rotate(45.0F, 0.0F, 1.0F, 0.0F); + float f = MathHelper.sin(swingProgress * swingProgress * 3.1415927F); + float f1 = MathHelper.sin(MathHelper.sqrt_float(swingProgress) * 3.1415927F); + GlStateManager.rotate(f * -20.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(f1 * -20.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(f1 * -80.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.scale(0.4F, 0.4F, 0.4F); } public void updateEquippedItem() { @@ -529,18 +542,4 @@ public class ItemRenderer { } } - - /**+ - * Resets equippedProgress - */ - public void resetEquippedProgress() { - this.equippedProgress = 0.0F; - } - - /**+ - * Resets equippedProgress - */ - public void resetEquippedProgress2() { - this.equippedProgress = 0.0F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/RegionRenderCache.java b/src/game/java/net/minecraft/client/renderer/RegionRenderCache.java index 5f3b6394..c9027859 100644 --- a/src/game/java/net/minecraft/client/renderer/RegionRenderCache.java +++ b/src/game/java/net/minecraft/client/renderer/RegionRenderCache.java @@ -11,22 +11,25 @@ import net.minecraft.world.ChunkCache; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,23 +49,6 @@ public class RegionRenderCache extends ChunkCache { this.blockStates = new IBlockState[8000]; } - public TileEntity getTileEntity(BlockPos blockpos) { - int i = (blockpos.getX() >> 4) - this.chunkX; - int j = (blockpos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getTileEntity(blockpos, Chunk.EnumCreateEntityType.QUEUED); - } - - public int getCombinedLight(BlockPos blockpos, int i) { - int j = this.getPositionIndex(blockpos); - int k = this.combinedLights[j]; - if (k == -1) { - k = super.getCombinedLight(blockpos, i); - this.combinedLights[j] = k; - } - - return k; - } - public IBlockState getBlockState(BlockPos blockpos) { int i = this.getPositionIndex(blockpos); IBlockState iblockstate = this.blockStates[i]; @@ -111,6 +97,17 @@ public class RegionRenderCache extends ChunkCache { } } + public int getCombinedLight(BlockPos blockpos, int i) { + int j = this.getPositionIndex(blockpos); + int k = this.combinedLights[j]; + if (k == -1) { + k = super.getCombinedLight(blockpos, i); + this.combinedLights[j] = k; + } + + return k; + } + private int getPositionIndex(BlockPos parBlockPos) { int i = parBlockPos.getX() - this.position.getX(); int j = parBlockPos.getY() - this.position.getY(); @@ -127,4 +124,10 @@ public class RegionRenderCache extends ChunkCache { int k = parBlockPos.z - this.position.z; return i * 400 + k * 20 + j; } + + public TileEntity getTileEntity(BlockPos blockpos) { + int i = (blockpos.getX() >> 4) - this.chunkX; + int j = (blockpos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getTileEntity(blockpos, Chunk.EnumCreateEntityType.QUEUED); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/RegionRenderCacheBuilder.java b/src/game/java/net/minecraft/client/renderer/RegionRenderCacheBuilder.java index c9bb09d4..ba30a146 100644 --- a/src/game/java/net/minecraft/client/renderer/RegionRenderCacheBuilder.java +++ b/src/game/java/net/minecraft/client/renderer/RegionRenderCacheBuilder.java @@ -3,22 +3,25 @@ package net.minecraft.client.renderer; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/RenderGlobal.java b/src/game/java/net/minecraft/client/renderer/RenderGlobal.java index d913c314..ac9314e9 100644 --- a/src/game/java/net/minecraft/client/renderer/RenderGlobal.java +++ b/src/game/java/net/minecraft/client/renderer/RenderGlobal.java @@ -1,6 +1,17 @@ package net.minecraft.client.renderer; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DST_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; import java.util.Collection; import java.util.EnumSet; @@ -8,12 +19,6 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; - -import net.lax1dude.eaglercraft.v1_8.EagRuntime; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.HString; -import net.lax1dude.eaglercraft.v1_8.Keyboard; - import java.util.Set; import java.util.concurrent.Callable; @@ -21,6 +26,10 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.minecraft.ChunkUpdateManager; @@ -98,27 +107,56 @@ import net.minecraft.world.IWorldAccess; import net.minecraft.world.border.WorldBorder; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListener { + public static interface ChunkCullAdapter { + boolean shouldCull(RenderChunk chunk); + } + + class ContainerLocalRenderInformation { + final RenderChunk renderChunk; + final EnumFacing facing; + final Set setFacing; + final int counter; + + private ContainerLocalRenderInformation(RenderChunk renderChunkIn, EnumFacing facingIn, int counterIn) { + this.setFacing = EnumSet.noneOf(EnumFacing.class); + this.renderChunk = renderChunkIn; + this.facing = facingIn; + this.counter = counterIn; + } + } + + public static interface EntityChunkCullAdapter { + boolean shouldCull(RenderChunk renderChunk); + } + + public static interface EntityObjectCullAdapter { + boolean shouldCull(RenderChunk renderChunk, RenderManager renderManager, Entity entity); + } + private static final Logger logger = LogManager.getLogger(); private static final ResourceLocation locationMoonPhasesPng = new ResourceLocation( "textures/environment/moon_phases.png"); @@ -126,27 +164,105 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene private static final ResourceLocation locationCloudsPng = new ResourceLocation("textures/environment/clouds.png"); private static final ResourceLocation locationEndSkyPng = new ResourceLocation("textures/environment/end_sky.png"); private static final ResourceLocation locationForcefieldPng = new ResourceLocation("textures/misc/forcefield.png"); + + public static void func_181561_a(AxisAlignedBB parAxisAlignedBB) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(3, DefaultVertexFormats.POSITION); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); + tessellator.draw(); + worldrenderer.begin(3, DefaultVertexFormats.POSITION); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); + tessellator.draw(); + worldrenderer.begin(1, DefaultVertexFormats.POSITION); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); + tessellator.draw(); + } + + public static void func_181563_a(AxisAlignedBB parAxisAlignedBB, int parInt1, int parInt2, int parInt3, + int parInt4) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(3, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + tessellator.draw(); + worldrenderer.begin(3, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + tessellator.draw(); + worldrenderer.begin(1, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) + .color(parInt1, parInt2, parInt3, parInt4).endVertex(); + tessellator.draw(); + } + private final Minecraft mc; private final TextureManager renderEngine; private final RenderManager renderManager; private WorldClient theWorld; private Set chunksToUpdate = Sets.newLinkedHashSet(); - /**+ - * List of OpenGL lists for the current render pass + /** + * + List of OpenGL lists for the current render pass */ private List renderInfos = Lists.newArrayListWithCapacity(69696); private final Set field_181024_n = Sets.newHashSet(); private ViewFrustum viewFrustum; - /**+ - * The star GL Call list + /** + * + The star GL Call list */ private int starGLCallList = -1; - /**+ - * OpenGL sky list + /** + * + OpenGL sky list */ private int glSkyList = -1; - /**+ - * OpenGL sky list 2 + /** + * + OpenGL sky list 2 */ private int glSkyList2 = -1; private int cloudTickCounter; @@ -168,8 +284,8 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene private final ChunkUpdateManager renderDispatcher = new ChunkUpdateManager(); private ChunkRenderContainer renderContainer; private int renderDistanceChunks = -1; - /**+ - * Render entities startup counter (init value=2) + /** + * + Render entities startup counter (init value=2) */ private int renderEntitiesStartupCounter = 2; private int countEntitiesTotal; @@ -179,11 +295,17 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene private ClippingHelper debugFixedClippingHelper; private final Vector4f[] debugTerrainMatrix = new Vector4f[8]; private final Vector3d debugTerrainFrustumPosition = new Vector3d(); + private boolean vboEnabled = false; + IRenderChunkFactory renderChunkFactory; + private double prevRenderSortX; + private double prevRenderSortY; + private double prevRenderSortZ; + private boolean displayListEntitiesDirty = true; public RenderGlobal(Minecraft mcIn) { @@ -203,50 +325,189 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene this.generateSky2(); } - public void onResourceManagerReload(IResourceManager var1) { - this.updateDestroyBlockIcons(); + public void broadcastSound(int i, BlockPos blockpos, int var3) { + switch (i) { + case 1013: + case 1018: + if (this.mc.getRenderViewEntity() != null) { + double d0 = (double) blockpos.getX() - this.mc.getRenderViewEntity().posX; + double d1 = (double) blockpos.getY() - this.mc.getRenderViewEntity().posY; + double d2 = (double) blockpos.getZ() - this.mc.getRenderViewEntity().posZ; + double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + double d4 = this.mc.getRenderViewEntity().posX; + double d5 = this.mc.getRenderViewEntity().posY; + double d6 = this.mc.getRenderViewEntity().posZ; + if (d3 > 0.0D) { + d4 += d0 / d3 * 2.0D; + d5 += d1 / d3 * 2.0D; + d6 += d2 / d3 * 2.0D; + } + + if (i == 1013) { + this.theWorld.playSound(d4, d5, d6, "mob.wither.spawn", 1.0F, 1.0F, false); + } else { + this.theWorld.playSound(d4, d5, d6, "mob.enderdragon.end", 5.0F, 1.0F, false); + } + } + default: + } } - private void updateDestroyBlockIcons() { - TextureMap texturemap = this.mc.getTextureMapBlocks(); - - for (int i = 0; i < this.destroyBlockIcons.length; ++i) { - this.destroyBlockIcons[i] = texturemap.getAtlasSprite("minecraft:blocks/destroy_stage_" + i); + private void cleanupDamagedBlocks(Iterator iteratorIn) { + while (iteratorIn.hasNext()) { + DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress) iteratorIn.next(); + int i = destroyblockprogress.getCreationCloudUpdateTick(); + if (this.cloudTickCounter - i > 400) { + iteratorIn.remove(); + } } } - /**+ - * Creates the entity outline shader to be stored in - * RenderGlobal.entityOutlineShader + public void createBindEntityOutlineFbs(int parInt1, int parInt2) { + + } + + /** + * + Deletes all display lists */ - public void makeEntityOutlineShader() { - + public void deleteAllDisplayLists() { } - public void renderEntityOutlineFramebuffer() { + public void drawBlockDamageTexture(Tessellator tessellatorIn, WorldRenderer worldRendererIn, Entity entityIn, + float partialTicks) { + double d0 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double) partialTicks; + double d1 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double) partialTicks; + double d2 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; + if (!this.damagedBlocks.isEmpty()) { + this.renderEngine.bindTexture(TextureMap.locationBlocksTexture); + this.preRenderDamagedBlocks(); + worldRendererIn.begin(7, + (DeferredStateManager.isDeferredRenderer() || DynamicLightsStateManager.isDynamicLightsRender()) + ? VertexFormat.BLOCK_SHADERS + : DefaultVertexFormats.BLOCK); + worldRendererIn.setTranslation(-d0, -d1, -d2); + worldRendererIn.markDirty(); + Iterator iterator = this.damagedBlocks.values().iterator(); - } + while (iterator.hasNext()) { + DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress) iterator.next(); + BlockPos blockpos = destroyblockprogress.getPosition(); + double d3 = (double) blockpos.getX() - d0; + double d4 = (double) blockpos.getY() - d1; + double d5 = (double) blockpos.getZ() - d2; + Block block = this.theWorld.getBlockState(blockpos).getBlock(); + if (!(block instanceof BlockChest) && !(block instanceof BlockEnderChest) + && !(block instanceof BlockSign) && !(block instanceof BlockSkull)) { + if (d3 * d3 + d4 * d4 + d5 * d5 > 1024.0D) { + iterator.remove(); + } else { + IBlockState iblockstate = this.theWorld.getBlockState(blockpos); + if (iblockstate.getBlock().getMaterial() != Material.air) { + int i = destroyblockprogress.getPartialBlockDamage(); + EaglerTextureAtlasSprite textureatlassprite = this.destroyBlockIcons[i]; + BlockRendererDispatcher blockrendererdispatcher = this.mc.getBlockRendererDispatcher(); + if (DynamicLightsStateManager.isInDynamicLightsPass()) { + DynamicLightsStateManager.reportForwardRenderObjectPosition2(blockpos.x, blockpos.y, + blockpos.z); + } + blockrendererdispatcher.renderBlockDamage(iblockstate, blockpos, textureatlassprite, + this.theWorld); + } + } + } + } - protected boolean isRenderEntityOutlines() { - return false; - } - - private void generateSky2() { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - - if (this.glSkyList2 >= 0) { - GLAllocation.deleteDisplayLists(this.glSkyList2); - this.glSkyList2 = -1; + tessellatorIn.draw(); + worldRendererIn.setTranslation(0.0D, 0.0D, 0.0D); + this.postRenderDamagedBlocks(); } - this.glSkyList2 = GLAllocation.generateDisplayLists(); - EaglercraftGPU.glNewList(this.glSkyList2, GL_COMPILE); - this.renderSky(worldrenderer, -16.0F, true); - tessellator.draw(); - EaglercraftGPU.glEndList(); + } + /** + * + Draws the selection box for the player. Args: entityPlayer, rayTraceHit, i, + * itemStack, partialTickTime + */ + public void drawSelectionBox(EntityPlayer player, MovingObjectPosition movingObjectPositionIn, int partialTicks, + float parFloat1) { + if (partialTicks == 0 && movingObjectPositionIn != null + && movingObjectPositionIn.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + GlStateManager.color(0.0F, 0.0F, 0.0F, 0.4F); + EaglercraftGPU.glLineWidth(2.0F); + GlStateManager.disableTexture2D(); + GlStateManager.depthMask(false); + float f = 0.002F; + BlockPos blockpos = movingObjectPositionIn.getBlockPos(); + Block block = this.theWorld.getBlockState(blockpos).getBlock(); + if (block.getMaterial() != Material.air && this.theWorld.getWorldBorder().contains(blockpos)) { + block.setBlockBoundsBasedOnState(this.theWorld, blockpos); + double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) parFloat1; + double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) parFloat1; + double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) parFloat1; + func_181561_a(block.getSelectedBoundingBox(this.theWorld, blockpos) + .expand(0.0020000000949949026D, 0.0020000000949949026D, 0.0020000000949949026D) + .offset(-d0, -d1, -d2)); + } + + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + } + + } + + private void fixTerrainFrustum(double x, double y, double z) { + this.debugFixedClippingHelper = new ClippingHelperImpl(); + ((ClippingHelperImpl) this.debugFixedClippingHelper).init(); + ((ClippingHelperImpl) this.debugFixedClippingHelper).destroy(); + Matrix4f matrix4f = new Matrix4f(this.debugFixedClippingHelper.modelviewMatrix); + matrix4f.transpose(); + Matrix4f matrix4f1 = new Matrix4f(this.debugFixedClippingHelper.projectionMatrix); + matrix4f1.transpose(); + Matrix4f matrix4f2 = new Matrix4f(); + Matrix4f.mul(matrix4f1, matrix4f, matrix4f2); + matrix4f2.invert(); + this.debugTerrainFrustumPosition.field_181059_a = x; + this.debugTerrainFrustumPosition.field_181060_b = y; + this.debugTerrainFrustumPosition.field_181061_c = z; + this.debugTerrainMatrix[0] = new Vector4f(-1.0F, -1.0F, -1.0F, 1.0F); + this.debugTerrainMatrix[1] = new Vector4f(1.0F, -1.0F, -1.0F, 1.0F); + this.debugTerrainMatrix[2] = new Vector4f(1.0F, 1.0F, -1.0F, 1.0F); + this.debugTerrainMatrix[3] = new Vector4f(-1.0F, 1.0F, -1.0F, 1.0F); + this.debugTerrainMatrix[4] = new Vector4f(-1.0F, -1.0F, 1.0F, 1.0F); + this.debugTerrainMatrix[5] = new Vector4f(1.0F, -1.0F, 1.0F, 1.0F); + this.debugTerrainMatrix[6] = new Vector4f(1.0F, 1.0F, 1.0F, 1.0F); + this.debugTerrainMatrix[7] = new Vector4f(-1.0F, 1.0F, 1.0F, 1.0F); + + for (int i = 0; i < 8; ++i) { + Matrix4f.transform(matrix4f2, this.debugTerrainMatrix[i], this.debugTerrainMatrix[i]); + this.debugTerrainMatrix[i].x /= this.debugTerrainMatrix[i].w; + this.debugTerrainMatrix[i].y /= this.debugTerrainMatrix[i].w; + this.debugTerrainMatrix[i].z /= this.debugTerrainMatrix[i].w; + this.debugTerrainMatrix[i].w = 1.0F; + } + + } + + public void func_181023_a(Collection parCollection, Collection parCollection2) { + synchronized (this.field_181024_n) { + this.field_181024_n.removeAll(parCollection); + this.field_181024_n.addAll(parCollection2); + } + } + + private RenderChunk func_181562_a(BlockPos parBlockPos, RenderChunk parRenderChunk, EnumFacing parEnumFacing) { + BlockPos blockpos = parRenderChunk.func_181701_a(parEnumFacing); + return MathHelper + .abs_int(parBlockPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 + ? null + : (blockpos.getY() >= 0 && blockpos.getY() < 256 + ? (MathHelper.abs_int(parBlockPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks + * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) + : null); } private void generateSky() { @@ -266,27 +527,21 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene } - private void renderSky(WorldRenderer worldRendererIn, float parFloat1, boolean parFlag) { - boolean flag = true; - boolean flag1 = true; - worldRendererIn.begin(7, DefaultVertexFormats.POSITION); + private void generateSky2() { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - for (int i = -384; i <= 384; i += 64) { - for (int j = -384; j <= 384; j += 64) { - float f = (float) i; - float f1 = (float) (i + 64); - if (parFlag) { - f1 = (float) i; - f = (float) (i + 64); - } - - worldRendererIn.pos((double) f, (double) parFloat1, (double) j).endVertex(); - worldRendererIn.pos((double) f1, (double) parFloat1, (double) j).endVertex(); - worldRendererIn.pos((double) f1, (double) parFloat1, (double) (j + 64)).endVertex(); - worldRendererIn.pos((double) f, (double) parFloat1, (double) (j + 64)).endVertex(); - } + if (this.glSkyList2 >= 0) { + GLAllocation.deleteDisplayLists(this.glSkyList2); + this.glSkyList2 = -1; } + this.glSkyList2 = GLAllocation.generateDisplayLists(); + EaglercraftGPU.glNewList(this.glSkyList2, GL_COMPILE); + this.renderSky(worldrenderer, -16.0F, true); + tessellator.draw(); + EaglercraftGPU.glEndList(); + } private void generateStars() { @@ -308,77 +563,115 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene } - private void renderStars(WorldRenderer worldRendererIn) { - EaglercraftRandom random = new EaglercraftRandom(10842L); - worldRendererIn.begin(7, DefaultVertexFormats.POSITION); + /** + * + Gets the entities info for use on the Debug screen + */ + public String getDebugInfoEntities() { + return "E: " + this.countEntitiesRendered + "/" + this.countEntitiesTotal + ", B: " + this.countEntitiesHidden + + ", I: " + (this.countEntitiesTotal - this.countEntitiesHidden - this.countEntitiesRendered); + } - for (int i = 0; i < 1500; ++i) { - double d0 = (double) (random.nextFloat() * 2.0F - 1.0F); - double d1 = (double) (random.nextFloat() * 2.0F - 1.0F); - double d2 = (double) (random.nextFloat() * 2.0F - 1.0F); - double d3 = (double) (0.15F + random.nextFloat() * 0.1F); - double d4 = d0 * d0 + d1 * d1 + d2 * d2; - if (d4 < 1.0D && d4 > 0.01D) { - d4 = 1.0D / Math.sqrt(d4); - d0 = d0 * d4; - d1 = d1 * d4; - d2 = d2 * d4; - double d5 = d0 * 100.0D; - double d6 = d1 * 100.0D; - double d7 = d2 * 100.0D; - double d8 = Math.atan2(d0, d2); - double d9 = Math.sin(d8); - double d10 = Math.cos(d8); - double d11 = Math.atan2(Math.sqrt(d0 * d0 + d2 * d2), d1); - double d12 = Math.sin(d11); - double d13 = Math.cos(d11); - double d14 = random.nextDouble() * 3.141592653589793D * 2.0D; - double d15 = Math.sin(d14); - double d16 = Math.cos(d14); + /** + * + Gets the render info for use on the Debug screen + */ + public String getDebugInfoRenders() { + int i = this.viewFrustum.renderChunks.length; + int j = 0; - for (int j = 0; j < 4; ++j) { - double d17 = 0.0D; - double d18 = (double) ((j & 2) - 1) * d3; - double d19 = (double) ((j + 1 & 2) - 1) * d3; - double d20 = 0.0D; - double d21 = d18 * d16 - d19 * d15; - double d22 = d19 * d16 + d18 * d15; - double d23 = d21 * d12 + 0.0D * d13; - double d24 = 0.0D * d12 - d21 * d13; - double d25 = d24 * d9 - d22 * d10; - double d26 = d22 * d9 + d24 * d10; - worldRendererIn.pos(d5 + d25, d6 + d23, d7 + d26).endVertex(); - } + for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = this.renderInfos + .get(ii); + CompiledChunk compiledchunk = renderglobal$containerlocalrenderinformation.renderChunk.compiledChunk; + if (compiledchunk != CompiledChunk.DUMMY && !compiledchunk.isEmpty()) { + ++j; } } + return HString.format("C: %d/%d %sD: %d, %s", + new Object[] { Integer.valueOf(j), Integer.valueOf(i), this.mc.renderChunksMany ? "(s) " : "", + Integer.valueOf(this.renderDistanceChunks), this.renderDispatcher.getDebugInfo() }); } - /**+ - * set null to clear + public String getDebugInfoShort() { + int i = this.viewFrustum.renderChunks.length; + int j = 0; + int k = 0; + + for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = this.renderInfos + .get(ii); + CompiledChunk compiledchunk = renderglobal$containerlocalrenderinformation.renderChunk.compiledChunk; + if (compiledchunk != CompiledChunk.DUMMY && !compiledchunk.isEmpty()) { + ++j; + k += compiledchunk.getTileEntities().size(); + } + } + + return "" + Minecraft.getDebugFPS() + "fps | C: " + j + "/" + i + ", E: " + this.countEntitiesRendered + "+" + k + + ", " + renderDispatcher.getDebugInfo(); + } + + protected Vector3f getViewVector(Entity entityIn, double partialTicks) { + float f = (float) ((double) entityIn.prevRotationPitch + + (double) (entityIn.rotationPitch - entityIn.prevRotationPitch) * partialTicks); + float f1 = (float) ((double) entityIn.prevRotationYaw + + (double) (entityIn.rotationYaw - entityIn.prevRotationYaw) * partialTicks); + if (Minecraft.getMinecraft().gameSettings.thirdPersonView == 2) { + f += 180.0F; + } + + float f2 = MathHelper.cos(-f1 * 0.017453292F - 3.1415927F); + float f3 = MathHelper.sin(-f1 * 0.017453292F - 3.1415927F); + float f4 = -MathHelper.cos(-f * 0.017453292F); + float f5 = MathHelper.sin(-f * 0.017453292F); + return new Vector3f(f3 * f4, f5, f2 * f4); + } + + private Set getVisibleFacings(BlockPos pos) { + VisGraph visgraph = new VisGraph(); + BlockPos blockpos = new BlockPos(pos.getX() >> 4 << 4, pos.getY() >> 4 << 4, pos.getZ() >> 4 << 4); + Chunk chunk = this.theWorld.getChunkFromBlockCoords(blockpos); + + for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, + blockpos.add(15, 15, 15))) { + if (chunk.getBlock(blockpos$mutableblockpos).isOpaqueCube()) { + visgraph.func_178606_a(blockpos$mutableblockpos); + } + } + + return visgraph.func_178609_b(pos); + } + + /** + * + Checks if the given position is to be rendered with cloud fog */ - public void setWorldAndLoadRenderers(WorldClient worldClientIn) { - if (this.theWorld != null) { - this.theWorld.removeWorldAccess(this); - } - - this.frustumUpdatePosX = Double.MIN_VALUE; - this.frustumUpdatePosY = Double.MIN_VALUE; - this.frustumUpdatePosZ = Double.MIN_VALUE; - this.frustumUpdatePosChunkX = Integer.MIN_VALUE; - this.frustumUpdatePosChunkY = Integer.MIN_VALUE; - this.frustumUpdatePosChunkZ = Integer.MIN_VALUE; - this.renderManager.set(worldClientIn); - this.theWorld = worldClientIn; - if (worldClientIn != null) { - worldClientIn.addWorldAccess(this); - this.loadRenderers(); - } - + public boolean hasCloudFog(double x, double y, double z, float partialTicks) { + return false; } - /**+ - * Loads all the renderers and sets up the basic settings usage + private boolean isPositionInRenderChunk(BlockPos pos, RenderChunk renderChunkIn) { + BlockPos blockpos = renderChunkIn.getPosition(); + return MathHelper.abs_int(pos.getX() - blockpos.getX()) > 16 ? false + : (MathHelper.abs_int(pos.getY() - blockpos.getY()) > 16 ? false + : MathHelper.abs_int(pos.getZ() - blockpos.getZ()) <= 16); + } + + /** + * WARNING: use only in the above "build near" logic + */ + private boolean isPositionInRenderChunkHack(BlockPos pos, RenderChunk renderChunkIn) { + BlockPos blockpos = renderChunkIn.getPosition(); + return MathHelper.abs_int(pos.getX() - blockpos.getX() - 8) > 11 ? false + : (MathHelper.abs_int(pos.getY() - blockpos.getY() - 8) > 11 ? false + : MathHelper.abs_int(pos.getZ() - blockpos.getZ() - 8) <= 11); + } + + protected boolean isRenderEntityOutlines() { + return false; + } + + /** + * + Loads all the renderers and sets up the basic settings usage */ public void loadRenderers() { if (this.theWorld != null) { @@ -482,580 +775,309 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene } } - protected void stopChunkUpdates() { - this.chunksToUpdate.clear(); - this.renderDispatcher.stopChunkUpdates(); - } - - public void createBindEntityOutlineFbs(int parInt1, int parInt2) { - - } - - public void renderEntities(Entity renderViewEntity, ICamera camera, float partialTicks) { - if (this.renderEntitiesStartupCounter > 0) { - --this.renderEntitiesStartupCounter; - } else { - boolean light = DynamicLightManager.isRenderingLights(); - double d0 = renderViewEntity.prevPosX - + (renderViewEntity.posX - renderViewEntity.prevPosX) * (double) partialTicks; - double d1 = renderViewEntity.prevPosY - + (renderViewEntity.posY - renderViewEntity.prevPosY) * (double) partialTicks; - double d2 = renderViewEntity.prevPosZ - + (renderViewEntity.posZ - renderViewEntity.prevPosZ) * (double) partialTicks; - TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(this.theWorld, this.mc.getTextureManager(), - this.mc.fontRendererObj, this.mc.getRenderViewEntity(), partialTicks); - this.renderManager.cacheActiveRenderInfo(this.theWorld, this.mc.fontRendererObj, - this.mc.getRenderViewEntity(), this.mc.pointedEntity, this.mc.gameSettings, partialTicks); - this.countEntitiesTotal = 0; - this.countEntitiesRendered = 0; - this.countEntitiesHidden = 0; - Entity entity = this.mc.getRenderViewEntity(); - double d3 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; - double d4 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; - double d5 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; - TileEntityRendererDispatcher.staticPlayerX = d3; - TileEntityRendererDispatcher.staticPlayerY = d4; - TileEntityRendererDispatcher.staticPlayerZ = d5; - this.renderManager.setRenderPosition(d3, d4, d5); - this.mc.entityRenderer.enableLightmap(); - List list = this.theWorld.getLoadedEntityList(); - this.countEntitiesTotal = list.size(); - - if (!DeferredStateManager.isDeferredRenderer()) { - for (int i = 0; i < this.theWorld.weatherEffects.size(); ++i) { - Entity entity1 = (Entity) this.theWorld.weatherEffects.get(i); - ++this.countEntitiesRendered; - if (entity1.isInRangeToRender3d(d0, d1, d2)) { - if (light) { - entity1.renderDynamicLightsEagler(partialTicks, true); - } - this.renderManager.renderEntitySimple(entity1, partialTicks); - } - } - } - - label738: for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = this.renderInfos - .get(ii); - Chunk chunk = this.theWorld.getChunkFromBlockCoords( - renderglobal$containerlocalrenderinformation.renderChunk.getPosition()); - ClassInheritanceMultiMap classinheritancemultimap = chunk - .getEntityLists()[renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() - / 16]; - if (!classinheritancemultimap.isEmpty()) { - Iterator iterator = classinheritancemultimap.iterator(); - - while (true) { - Entity entity2; - boolean flag2; - while (true) { - if (!iterator.hasNext()) { - continue label738; - } - - entity2 = (Entity) iterator.next(); - flag2 = this.renderManager.shouldRender(entity2, camera, d0, d1, d2) - || entity2.riddenByEntity == this.mc.thePlayer; - if (light) { - entity2.renderDynamicLightsEagler(partialTicks, flag2); - } - if (!flag2) { - break; - } - - boolean flag3 = this.mc.getRenderViewEntity() instanceof EntityLivingBase - ? ((EntityLivingBase) this.mc.getRenderViewEntity()).isPlayerSleeping() - : false; - if ((entity2 != this.mc.getRenderViewEntity() || this.mc.gameSettings.thirdPersonView != 0 - || flag3) - && (entity2.posY < 0.0D || entity2.posY >= 256.0D - || this.theWorld.isBlockLoaded(new BlockPos(entity2)))) { - ++this.countEntitiesRendered; - this.renderManager.renderEntitySimple(entity2, partialTicks); - break; - } - } - - if (!flag2 && entity2 instanceof EntityWitherSkull) { - this.mc.getRenderManager().renderWitherSkull(entity2, partialTicks); - } - } - } - } - - RenderHelper.enableStandardItemLighting(); - - for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation1 = this.renderInfos - .get(ii); - List list1 = renderglobal$containerlocalrenderinformation1.renderChunk.getCompiledChunk() - .getTileEntities(); - if (!list1.isEmpty()) { - for (int m = 0, n = list1.size(); m < n; ++m) { - TileEntityRendererDispatcher.instance.renderTileEntity((TileEntity) list1.get(m), partialTicks, - -1); - } - } - } - - synchronized (this.field_181024_n) { - for (TileEntity tileentity : this.field_181024_n) { - TileEntityRendererDispatcher.instance.renderTileEntity(tileentity, partialTicks, -1); - } - } - - this.preRenderDamagedBlocks(); - - for (DestroyBlockProgress destroyblockprogress : this.damagedBlocks.values()) { - BlockPos blockpos = destroyblockprogress.getPosition(); - TileEntity tileentity1 = this.theWorld.getTileEntity(blockpos); - if (tileentity1 instanceof TileEntityChest) { - TileEntityChest tileentitychest = (TileEntityChest) tileentity1; - if (tileentitychest.adjacentChestXNeg != null) { - blockpos = blockpos.offset(EnumFacing.WEST); - tileentity1 = this.theWorld.getTileEntity(blockpos); - } else if (tileentitychest.adjacentChestZNeg != null) { - blockpos = blockpos.offset(EnumFacing.NORTH); - tileentity1 = this.theWorld.getTileEntity(blockpos); - } - } - - Block block = this.theWorld.getBlockState(blockpos).getBlock(); - if (tileentity1 != null && (block instanceof BlockChest || block instanceof BlockEnderChest - || block instanceof BlockSign || block instanceof BlockSkull)) { - TileEntityRendererDispatcher.instance.renderTileEntity(tileentity1, partialTicks, - destroyblockprogress.getPartialBlockDamage()); - } - } - - this.postRenderDamagedBlocks(); - this.mc.entityRenderer.disableLightmap(); - } - } - - public static interface EntityChunkCullAdapter { - boolean shouldCull(RenderChunk renderChunk); - } - - public static interface EntityObjectCullAdapter { - boolean shouldCull(RenderChunk renderChunk, RenderManager renderManager, Entity entity); - } - - public void renderShadowLODEntities(Entity renderViewEntity, float partialTicks, - EntityChunkCullAdapter entityChunkCull, EntityObjectCullAdapter entityObjectCull) { // TODO - if (renderEntitiesStartupCounter <= 0) { - TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(theWorld, mc.getTextureManager(), - mc.fontRendererObj, renderViewEntity, partialTicks); - renderManager.cacheActiveRenderInfo(theWorld, mc.fontRendererObj, renderViewEntity, mc.pointedEntity, - mc.gameSettings, partialTicks); - - double d3 = renderViewEntity.lastTickPosX - + (renderViewEntity.posX - renderViewEntity.lastTickPosX) * (double) partialTicks; - double d4 = renderViewEntity.lastTickPosY - + (renderViewEntity.posY - renderViewEntity.lastTickPosY) * (double) partialTicks; - double d5 = renderViewEntity.lastTickPosZ - + (renderViewEntity.posZ - renderViewEntity.lastTickPosZ) * (double) partialTicks; - TileEntityRendererDispatcher.staticPlayerX = d3; - TileEntityRendererDispatcher.staticPlayerY = d4; - TileEntityRendererDispatcher.staticPlayerZ = d5; - renderManager.setRenderPosition(d3, d4, d5); - - for (RenderGlobal.ContainerLocalRenderInformation containerlocalrenderinformation : this.renderInfos) { - RenderChunk currentRenderChunk = containerlocalrenderinformation.renderChunk; - - if (!entityChunkCull.shouldCull(currentRenderChunk)) { - Chunk chunk = this.theWorld - .getChunkFromBlockCoords(containerlocalrenderinformation.renderChunk.getPosition()); - ClassInheritanceMultiMap classinheritancemultimap = chunk - .getEntityLists()[containerlocalrenderinformation.renderChunk.getPosition().getY() / 16]; - if (!classinheritancemultimap.isEmpty()) { - Iterator iterator = classinheritancemultimap.iterator(); - while (iterator.hasNext()) { - Entity entity2 = iterator.next(); - if (!entityObjectCull.shouldCull(currentRenderChunk, renderManager, entity2) - || entity2.riddenByEntity == this.mc.thePlayer) { - if (entity2.posY < 0.0D || entity2.posY >= 256.0D - || this.theWorld.isBlockLoaded(new BlockPos(entity2))) { - ++this.countEntitiesRendered; - this.renderManager.renderEntitySimple(entity2, partialTicks); - mc.entityRenderer.disableLightmap(); - GlStateManager.disableShaderBlendAdd(); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - } - } - - } - - // TODO: why? - // if (!flag2 && entity2 instanceof EntityWitherSkull) { - // this.mc.getRenderManager().renderWitherSkull(entity2, partialTicks); - // } - } - - List tileEntities = currentRenderChunk.compiledChunk.getTileEntities(); - for (int i = 0, l = tileEntities.size(); i < l; ++i) { - TileEntityRendererDispatcher.instance.renderTileEntity(tileEntities.get(i), partialTicks, -1); - mc.entityRenderer.disableLightmap(); - GlStateManager.disableShaderBlendAdd(); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - } - } - } - - synchronized (this.field_181024_n) { - for (TileEntity tileentity : this.field_181024_n) { - TileEntityRendererDispatcher.instance.renderTileEntity(tileentity, partialTicks, -1); - mc.entityRenderer.disableLightmap(); - GlStateManager.disableShaderBlendAdd(); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - } - } - } - } - - public void renderParaboloidTileEntities(Entity renderViewEntity, float partialTicks, int up) { - if (renderEntitiesStartupCounter <= 0) { - TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(theWorld, mc.getTextureManager(), - mc.fontRendererObj, renderViewEntity, partialTicks); - renderManager.cacheActiveRenderInfo(theWorld, mc.fontRendererObj, renderViewEntity, mc.pointedEntity, - mc.gameSettings, partialTicks); - - double d3 = renderViewEntity.lastTickPosX - + (renderViewEntity.posX - renderViewEntity.lastTickPosX) * (double) partialTicks; - double d4 = renderViewEntity.lastTickPosY - + (renderViewEntity.posY - renderViewEntity.lastTickPosY) * (double) partialTicks; - double d5 = renderViewEntity.lastTickPosZ - + (renderViewEntity.posZ - renderViewEntity.lastTickPosZ) * (double) partialTicks; - TileEntityRendererDispatcher.staticPlayerX = d3; - TileEntityRendererDispatcher.staticPlayerY = d4; - TileEntityRendererDispatcher.staticPlayerZ = d5; - renderManager.setRenderPosition(d3, d4, d5); - - double rad = 8.0; - - int minX = (int) (d3 - rad); - int minY = (int) d4; - if (up == -1) { - minY -= rad; - } - int minZ = (int) (d5 - rad); - - int maxX = (int) (d3 + rad); - int maxY = (int) d4; - if (up == 1) { - maxY += rad; - } - int maxZ = (int) (d5 + rad); - - BlockPos tmp = new BlockPos(0, 0, 0); - minX = MathHelper.floor_double(minX / 16.0) * 16; - minY = MathHelper.floor_double(minY / 16.0) * 16; - minZ = MathHelper.floor_double(minZ / 16.0) * 16; - maxX = MathHelper.floor_double(maxX / 16.0) * 16; - maxY = MathHelper.floor_double(maxY / 16.0) * 16; - maxZ = MathHelper.floor_double(maxZ / 16.0) * 16; - - for (int cx = minX; cx <= maxX; cx += 16) { - for (int cz = minZ; cz <= maxZ; cz += 16) { - for (int cy = minY; cy <= maxY; cy += 16) { - tmp.x = cx; - tmp.y = cy; - tmp.z = cz; - RenderChunk ch = viewFrustum.getRenderChunk(tmp); - CompiledChunk cch; - if (ch != null && (cch = ch.compiledChunk) != null) { - List tileEntities = cch.getTileEntities(); - for (int i = 0, l = tileEntities.size(); i < l; ++i) { - mc.entityRenderer.enableLightmap(); - TileEntityRendererDispatcher.instance.renderTileEntity(tileEntities.get(i), - partialTicks, -1); - GlStateManager.disableShaderBlendAdd(); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - } - } - } - } - } - mc.entityRenderer.disableLightmap(); - } - } - - /**+ - * Gets the render info for use on the Debug screen + /** + * + Creates the entity outline shader to be stored in + * RenderGlobal.entityOutlineShader */ - public String getDebugInfoRenders() { - int i = this.viewFrustum.renderChunks.length; - int j = 0; + public void makeEntityOutlineShader() { - for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = this.renderInfos - .get(ii); - CompiledChunk compiledchunk = renderglobal$containerlocalrenderinformation.renderChunk.compiledChunk; - if (compiledchunk != CompiledChunk.DUMMY && !compiledchunk.isEmpty()) { - ++j; - } - } - - return HString.format("C: %d/%d %sD: %d, %s", - new Object[] { Integer.valueOf(j), Integer.valueOf(i), this.mc.renderChunksMany ? "(s) " : "", - Integer.valueOf(this.renderDistanceChunks), this.renderDispatcher.getDebugInfo() }); } - /**+ - * Gets the entities info for use on the Debug screen - */ - public String getDebugInfoEntities() { - return "E: " + this.countEntitiesRendered + "/" + this.countEntitiesTotal + ", B: " + this.countEntitiesHidden - + ", I: " + (this.countEntitiesTotal - this.countEntitiesHidden - this.countEntitiesRendered); - } - - public void setupTerrain(Entity viewEntity, double partialTicks, ICamera camera, int frameCount, - boolean playerSpectator) { - if (this.mc.gameSettings.renderDistanceChunks != this.renderDistanceChunks) { - this.loadRenderers(); - } - - double d0 = viewEntity.posX - this.frustumUpdatePosX; - double d1 = viewEntity.posY - this.frustumUpdatePosY; - double d2 = viewEntity.posZ - this.frustumUpdatePosZ; - if (this.frustumUpdatePosChunkX != viewEntity.chunkCoordX - || this.frustumUpdatePosChunkY != viewEntity.chunkCoordY - || this.frustumUpdatePosChunkZ != viewEntity.chunkCoordZ || d0 * d0 + d1 * d1 + d2 * d2 > 16.0D) { - this.frustumUpdatePosX = viewEntity.posX; - this.frustumUpdatePosY = viewEntity.posY; - this.frustumUpdatePosZ = viewEntity.posZ; - this.frustumUpdatePosChunkX = viewEntity.chunkCoordX; - this.frustumUpdatePosChunkY = viewEntity.chunkCoordY; - this.frustumUpdatePosChunkZ = viewEntity.chunkCoordZ; - this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posZ); - } - - double d3 = viewEntity.lastTickPosX + (viewEntity.posX - viewEntity.lastTickPosX) * partialTicks; - double d4 = viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks; - double d5 = viewEntity.lastTickPosZ + (viewEntity.posZ - viewEntity.lastTickPosZ) * partialTicks; - this.renderContainer.initialize(d3, d4, d5); - if (this.debugFixedClippingHelper != null) { - Frustum frustum = new Frustum(this.debugFixedClippingHelper); - frustum.setPosition(this.debugTerrainFrustumPosition.field_181059_a, - this.debugTerrainFrustumPosition.field_181060_b, this.debugTerrainFrustumPosition.field_181061_c); - camera = frustum; - } - - BlockPos blockpos1 = new BlockPos(d3, d4 + (double) viewEntity.getEyeHeight(), d5); - RenderChunk renderchunk = this.viewFrustum.getRenderChunk(blockpos1); - BlockPos blockpos = new BlockPos(MathHelper.floor_double(d3 / 16.0D) * 16, - MathHelper.floor_double(d4 / 16.0D) * 16, MathHelper.floor_double(d5 / 16.0D) * 16); - this.displayListEntitiesDirty = this.displayListEntitiesDirty || !this.chunksToUpdate.isEmpty() - || viewEntity.posX != this.lastViewEntityX || viewEntity.posY != this.lastViewEntityY - || viewEntity.posZ != this.lastViewEntityZ - || (double) viewEntity.rotationPitch != this.lastViewEntityPitch - || (double) viewEntity.rotationYaw != this.lastViewEntityYaw - || this.mc.entityRenderer.currentProjMatrixFOV != this.lastViewProjMatrixFOV; - this.lastViewEntityX = viewEntity.posX; - this.lastViewEntityY = viewEntity.posY; - this.lastViewEntityZ = viewEntity.posZ; - this.lastViewEntityPitch = (double) viewEntity.rotationPitch; - this.lastViewEntityYaw = (double) viewEntity.rotationYaw; - this.lastViewProjMatrixFOV = this.mc.entityRenderer.currentProjMatrixFOV; - boolean flag = this.debugFixedClippingHelper != null; - if (!flag && this.displayListEntitiesDirty) { - this.displayListEntitiesDirty = false; - this.renderInfos = Lists.newArrayList(); - LinkedList linkedlist = Lists.newLinkedList(); - boolean flag1 = this.mc.renderChunksMany; - if (renderchunk != null) { - boolean flag2 = false; - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation3 = new RenderGlobal.ContainerLocalRenderInformation( - renderchunk, (EnumFacing) null, 0); - Set set1 = this.getVisibleFacings(blockpos1); - if (set1.size() == 1) { - Vector3f vector3f = this.getViewVector(viewEntity, partialTicks); - EnumFacing enumfacing = EnumFacing.getFacingFromVector(vector3f.x, vector3f.y, vector3f.z) - .getOpposite(); - set1.remove(enumfacing); - } - - if (set1.isEmpty()) { - flag2 = true; - } - - if (flag2 && !playerSpectator) { - this.renderInfos.add(renderglobal$containerlocalrenderinformation3); - } else { - if (playerSpectator && this.theWorld.getBlockState(blockpos1).getBlock().isOpaqueCube()) { - flag1 = false; - } - - renderchunk.setFrameIndex(frameCount); - linkedlist.add(renderglobal$containerlocalrenderinformation3); - } - } else { - int i = blockpos1.getY() > 0 ? 248 : 8; - - for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j) { - for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k) { - RenderChunk renderchunk1 = this.viewFrustum - .getRenderChunk(new BlockPos((j << 4) + 8, i, (k << 4) + 8)); - if (renderchunk1 != null - && ((ICamera) camera).isBoundingBoxInFrustum(renderchunk1.boundingBox)) { - renderchunk1.setFrameIndex(frameCount); - linkedlist.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, - (EnumFacing) null, 0)); - } - } - } - } - - while (!linkedlist.isEmpty()) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation1 = (RenderGlobal.ContainerLocalRenderInformation) linkedlist - .poll(); - RenderChunk renderchunk3 = renderglobal$containerlocalrenderinformation1.renderChunk; - EnumFacing enumfacing2 = renderglobal$containerlocalrenderinformation1.facing; - BlockPos blockpos2 = renderchunk3.getPosition(); - this.renderInfos.add(renderglobal$containerlocalrenderinformation1); - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing1 = facings[i]; - RenderChunk renderchunk2 = this.func_181562_a(blockpos, renderchunk3, enumfacing1); - if ((!flag1 || !renderglobal$containerlocalrenderinformation1.setFacing // TODO: - .contains(enumfacing1.getOpposite())) - && (!flag1 || enumfacing2 == null - || renderchunk3.getCompiledChunk().isVisible(enumfacing2.getOpposite(), - enumfacing1)) - && renderchunk2 != null && renderchunk2.setFrameIndex(frameCount) - && ((ICamera) camera).isBoundingBoxInFrustum(renderchunk2.boundingBox)) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = new RenderGlobal.ContainerLocalRenderInformation( - renderchunk2, enumfacing1, renderglobal$containerlocalrenderinformation1.counter + 1); - renderglobal$containerlocalrenderinformation.setFacing - .addAll(renderglobal$containerlocalrenderinformation1.setFacing); - renderglobal$containerlocalrenderinformation.setFacing.add(enumfacing1); - linkedlist.add(renderglobal$containerlocalrenderinformation); - } - } - } - } - - if (this.debugFixTerrainFrustum) { - this.fixTerrainFrustum(d3, d4, d5); - this.debugFixTerrainFrustum = false; - } - - Set set = this.chunksToUpdate; - this.chunksToUpdate = Sets.newLinkedHashSet(); - - for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation2 = this.renderInfos - .get(ii); - RenderChunk renderchunk4 = renderglobal$containerlocalrenderinformation2.renderChunk; - if (renderchunk4.isNeedsUpdate() || set.contains(renderchunk4)) { - this.displayListEntitiesDirty = true; - if (this.mc.gameSettings.chunkFix ? this.isPositionInRenderChunkHack(blockpos1, renderchunk4) - : this.isPositionInRenderChunk(blockpos, renderchunk4)) { - this.renderDispatcher.updateChunkNow(renderchunk4); - renderchunk4.setNeedsUpdate(false); - } else { - this.chunksToUpdate.add(renderchunk4); - } - } - } - - this.chunksToUpdate.addAll(set); - } - - private boolean isPositionInRenderChunk(BlockPos pos, RenderChunk renderChunkIn) { - BlockPos blockpos = renderChunkIn.getPosition(); - return MathHelper.abs_int(pos.getX() - blockpos.getX()) > 16 ? false - : (MathHelper.abs_int(pos.getY() - blockpos.getY()) > 16 ? false - : MathHelper.abs_int(pos.getZ() - blockpos.getZ()) <= 16); + public void markBlockForUpdate(BlockPos blockpos) { + int i = blockpos.getX(); + int j = blockpos.getY(); + int k = blockpos.getZ(); + this.markBlocksForUpdate(i - 1, j - 1, k - 1, i + 1, j + 1, k + 1); } /** - * WARNING: use only in the above "build near" logic + * + On the client, re-renders all blocks in this range, inclusive. On the + * server, does nothing. Args: min x, min y, min z, max x, max y, max z */ - private boolean isPositionInRenderChunkHack(BlockPos pos, RenderChunk renderChunkIn) { - BlockPos blockpos = renderChunkIn.getPosition(); - return MathHelper.abs_int(pos.getX() - blockpos.getX() - 8) > 11 ? false - : (MathHelper.abs_int(pos.getY() - blockpos.getY() - 8) > 11 ? false - : MathHelper.abs_int(pos.getZ() - blockpos.getZ() - 8) <= 11); + public void markBlockRangeForRenderUpdate(int i, int j, int k, int l, int i1, int j1) { + this.markBlocksForUpdate(i - 1, j - 1, k - 1, l + 1, i1 + 1, j1 + 1); } - private Set getVisibleFacings(BlockPos pos) { - VisGraph visgraph = new VisGraph(); - BlockPos blockpos = new BlockPos(pos.getX() >> 4 << 4, pos.getY() >> 4 << 4, pos.getZ() >> 4 << 4); - Chunk chunk = this.theWorld.getChunkFromBlockCoords(blockpos); + /** + * + Marks the blocks in the given range for update + */ + private void markBlocksForUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { + this.viewFrustum.markBlocksForUpdate(x1, y1, z1, x2, y2, z2); + } - for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, - blockpos.add(15, 15, 15))) { - if (chunk.getBlock(blockpos$mutableblockpos).isOpaqueCube()) { - visgraph.func_178606_a(blockpos$mutableblockpos); + public void notifyLightSet(BlockPos blockpos) { + int i = blockpos.getX(); + int j = blockpos.getY(); + int k = blockpos.getZ(); + this.markBlocksForUpdate(i - 1, j - 1, k - 1, i + 1, j + 1, k + 1); + } + + /** + * + Called on all IWorldAccesses when an entity is created or loaded. On client + * worlds, starts downloading any necessary textures. On server worlds, adds the + * entity to the entity tracker. + */ + public void onEntityAdded(Entity var1) { + } + + /** + * + Called on all IWorldAccesses when an entity is unloaded or destroyed. On + * client worlds, releases any downloaded textures. On server worlds, removes + * the entity from the entity tracker. + */ + public void onEntityRemoved(Entity var1) { + } + + public void onResourceManagerReload(IResourceManager var1) { + this.updateDestroyBlockIcons(); + } + + public void playAuxSFX(EntityPlayer var1, int i, BlockPos blockpos, int j) { + EaglercraftRandom random = this.theWorld.rand; + switch (i) { + case 1000: + this.theWorld.playSoundAtPos(blockpos, "random.click", 1.0F, 1.0F, false); + break; + case 1001: + this.theWorld.playSoundAtPos(blockpos, "random.click", 1.0F, 1.2F, false); + break; + case 1002: + this.theWorld.playSoundAtPos(blockpos, "random.bow", 1.0F, 1.2F, false); + break; + case 1003: + this.theWorld.playSoundAtPos(blockpos, "random.door_open", 1.0F, + this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); + break; + case 1004: + this.theWorld.playSoundAtPos(blockpos, "random.fizz", 0.5F, + 2.6F + (random.nextFloat() - random.nextFloat()) * 0.8F, false); + break; + case 1005: + if (Item.getItemById(j) instanceof ItemRecord) { + this.theWorld.playRecord(blockpos, "records." + ((ItemRecord) Item.getItemById(j)).recordName); + } else { + this.theWorld.playRecord(blockpos, (String) null); } - } + break; + case 1006: + this.theWorld.playSoundAtPos(blockpos, "random.door_close", 1.0F, + this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); + break; + case 1007: + this.theWorld.playSoundAtPos(blockpos, "mob.ghast.charge", 10.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1008: + this.theWorld.playSoundAtPos(blockpos, "mob.ghast.fireball", 10.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1009: + this.theWorld.playSoundAtPos(blockpos, "mob.ghast.fireball", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1010: + this.theWorld.playSoundAtPos(blockpos, "mob.zombie.wood", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1011: + this.theWorld.playSoundAtPos(blockpos, "mob.zombie.metal", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1012: + this.theWorld.playSoundAtPos(blockpos, "mob.zombie.woodbreak", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1014: + this.theWorld.playSoundAtPos(blockpos, "mob.wither.shoot", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1015: + this.theWorld.playSoundAtPos(blockpos, "mob.bat.takeoff", 0.05F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1016: + this.theWorld.playSoundAtPos(blockpos, "mob.zombie.infect", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1017: + this.theWorld.playSoundAtPos(blockpos, "mob.zombie.unfect", 2.0F, + (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); + break; + case 1020: + this.theWorld.playSoundAtPos(blockpos, "random.anvil_break", 1.0F, + this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); + break; + case 1021: + this.theWorld.playSoundAtPos(blockpos, "random.anvil_use", 1.0F, + this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); + break; + case 1022: + this.theWorld.playSoundAtPos(blockpos, "random.anvil_land", 0.3F, + this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); + break; + case 2000: + int j1 = j % 3 - 1; + int k = j / 3 % 3 - 1; + double d15 = (double) blockpos.getX() + (double) j1 * 0.6D + 0.5D; + double d17 = (double) blockpos.getY() + 0.5D; + double d19 = (double) blockpos.getZ() + (double) k * 0.6D + 0.5D; - return visgraph.func_178609_b(pos); - } + for (int i2 = 0; i2 < 10; ++i2) { + double d20 = random.nextDouble() * 0.2D + 0.01D; + double d21 = d15 + (double) j1 * 0.01D + (random.nextDouble() - 0.5D) * (double) k * 0.5D; + double d4 = d17 + (random.nextDouble() - 0.5D) * 0.5D; + double d6 = d19 + (double) k * 0.01D + (random.nextDouble() - 0.5D) * (double) j1 * 0.5D; + double d8 = (double) j1 * d20 + random.nextGaussian() * 0.01D; + double d10 = -0.03D + random.nextGaussian() * 0.01D; + double d12 = (double) k * d20 + random.nextGaussian() * 0.01D; + this.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d21, d4, d6, d8, d10, d12, new int[0]); + } - private RenderChunk func_181562_a(BlockPos parBlockPos, RenderChunk parRenderChunk, EnumFacing parEnumFacing) { - BlockPos blockpos = parRenderChunk.func_181701_a(parEnumFacing); - return MathHelper - .abs_int(parBlockPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 - ? null - : (blockpos.getY() >= 0 && blockpos.getY() < 256 - ? (MathHelper.abs_int(parBlockPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks - * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) - : null); - } + return; + case 2001: + Block block = Block.getBlockById(j & 4095); + if (block.getMaterial() != Material.air) { + this.mc.getSoundHandler() + .playSound(new PositionedSoundRecord(new ResourceLocation(block.stepSound.getBreakSound()), + (block.stepSound.getVolume() + 1.0F) / 2.0F, block.stepSound.getFrequency() * 0.8F, + (float) blockpos.getX() + 0.5F, (float) blockpos.getY() + 0.5F, + (float) blockpos.getZ() + 0.5F)); + } - private void fixTerrainFrustum(double x, double y, double z) { - this.debugFixedClippingHelper = new ClippingHelperImpl(); - ((ClippingHelperImpl) this.debugFixedClippingHelper).init(); - ((ClippingHelperImpl) this.debugFixedClippingHelper).destroy(); - Matrix4f matrix4f = new Matrix4f(this.debugFixedClippingHelper.modelviewMatrix); - matrix4f.transpose(); - Matrix4f matrix4f1 = new Matrix4f(this.debugFixedClippingHelper.projectionMatrix); - matrix4f1.transpose(); - Matrix4f matrix4f2 = new Matrix4f(); - Matrix4f.mul(matrix4f1, matrix4f, matrix4f2); - matrix4f2.invert(); - this.debugTerrainFrustumPosition.field_181059_a = x; - this.debugTerrainFrustumPosition.field_181060_b = y; - this.debugTerrainFrustumPosition.field_181061_c = z; - this.debugTerrainMatrix[0] = new Vector4f(-1.0F, -1.0F, -1.0F, 1.0F); - this.debugTerrainMatrix[1] = new Vector4f(1.0F, -1.0F, -1.0F, 1.0F); - this.debugTerrainMatrix[2] = new Vector4f(1.0F, 1.0F, -1.0F, 1.0F); - this.debugTerrainMatrix[3] = new Vector4f(-1.0F, 1.0F, -1.0F, 1.0F); - this.debugTerrainMatrix[4] = new Vector4f(-1.0F, -1.0F, 1.0F, 1.0F); - this.debugTerrainMatrix[5] = new Vector4f(1.0F, -1.0F, 1.0F, 1.0F); - this.debugTerrainMatrix[6] = new Vector4f(1.0F, 1.0F, 1.0F, 1.0F); - this.debugTerrainMatrix[7] = new Vector4f(-1.0F, 1.0F, 1.0F, 1.0F); + this.mc.effectRenderer.addBlockDestroyEffects(blockpos, block.getStateFromMeta(j >> 12 & 255)); + break; + case 2002: + double d13 = (double) blockpos.getX(); + double d14 = (double) blockpos.getY(); + double d16 = (double) blockpos.getZ(); - for (int i = 0; i < 8; ++i) { - Matrix4f.transform(matrix4f2, this.debugTerrainMatrix[i], this.debugTerrainMatrix[i]); - this.debugTerrainMatrix[i].x /= this.debugTerrainMatrix[i].w; - this.debugTerrainMatrix[i].y /= this.debugTerrainMatrix[i].w; - this.debugTerrainMatrix[i].z /= this.debugTerrainMatrix[i].w; - this.debugTerrainMatrix[i].w = 1.0F; + for (int k1 = 0; k1 < 8; ++k1) { + this.spawnParticle(EnumParticleTypes.ITEM_CRACK, d13, d14, d16, random.nextGaussian() * 0.15D, + random.nextDouble() * 0.2D, random.nextGaussian() * 0.15D, + new int[] { Item.getIdFromItem(Items.potionitem), j }); + } + + int l1 = Items.potionitem.getColorFromDamage(j); + float f = (float) (l1 >> 16 & 255) / 255.0F; + float f1 = (float) (l1 >> 8 & 255) / 255.0F; + float f2 = (float) (l1 >> 0 & 255) / 255.0F; + EnumParticleTypes enumparticletypes = EnumParticleTypes.SPELL; + if (Items.potionitem.isEffectInstant(j)) { + enumparticletypes = EnumParticleTypes.SPELL_INSTANT; + } + + for (int j2 = 0; j2 < 100; ++j2) { + double d22 = random.nextDouble() * 4.0D; + double d23 = random.nextDouble() * 3.141592653589793D * 2.0D; + double d24 = Math.cos(d23) * d22; + double d9 = 0.01D + random.nextDouble() * 0.5D; + double d11 = Math.sin(d23) * d22; + EntityFX entityfx = this.spawnEntityFX(enumparticletypes.getParticleID(), + enumparticletypes.getShouldIgnoreRange(), d13 + d24 * 0.1D, d14 + 0.3D, d16 + d11 * 0.1D, d24, + d9, d11, new int[0]); + if (entityfx != null) { + float f3 = 0.75F + random.nextFloat() * 0.25F; + entityfx.setRBGColorF(f * f3, f1 * f3, f2 * f3); + entityfx.multiplyVelocity((float) d22); + } + } + + this.theWorld.playSoundAtPos(blockpos, "game.potion.smash", 1.0F, + this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); + break; + case 2003: + double d0 = (double) blockpos.getX() + 0.5D; + double d1 = (double) blockpos.getY(); + double d2 = (double) blockpos.getZ() + 0.5D; + + for (int l = 0; l < 8; ++l) { + this.spawnParticle(EnumParticleTypes.ITEM_CRACK, d0, d1, d2, random.nextGaussian() * 0.15D, + random.nextDouble() * 0.2D, random.nextGaussian() * 0.15D, + new int[] { Item.getIdFromItem(Items.ender_eye) }); + } + + for (double d18 = 0.0D; d18 < 6.283185307179586D; d18 += 0.15707963267948966D) { + this.spawnParticle(EnumParticleTypes.PORTAL, d0 + Math.cos(d18) * 5.0D, d1 - 0.4D, + d2 + Math.sin(d18) * 5.0D, Math.cos(d18) * -5.0D, 0.0D, Math.sin(d18) * -5.0D, new int[0]); + this.spawnParticle(EnumParticleTypes.PORTAL, d0 + Math.cos(d18) * 5.0D, d1 - 0.4D, + d2 + Math.sin(d18) * 5.0D, Math.cos(d18) * -7.0D, 0.0D, Math.sin(d18) * -7.0D, new int[0]); + } + + return; + case 2004: + for (int i1 = 0; i1 < 20; ++i1) { + double d3 = (double) blockpos.getX() + 0.5D + ((double) this.theWorld.rand.nextFloat() - 0.5D) * 2.0D; + double d5 = (double) blockpos.getY() + 0.5D + ((double) this.theWorld.rand.nextFloat() - 0.5D) * 2.0D; + double d7 = (double) blockpos.getZ() + 0.5D + ((double) this.theWorld.rand.nextFloat() - 0.5D) * 2.0D; + this.theWorld.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d3, d5, d7, 0.0D, 0.0D, 0.0D, new int[0]); + this.theWorld.spawnParticle(EnumParticleTypes.FLAME, d3, d5, d7, 0.0D, 0.0D, 0.0D, new int[0]); + } + + return; + case 2005: + ItemDye.spawnBonemealParticles(this.theWorld, blockpos, j); } } - protected Vector3f getViewVector(Entity entityIn, double partialTicks) { - float f = (float) ((double) entityIn.prevRotationPitch - + (double) (entityIn.rotationPitch - entityIn.prevRotationPitch) * partialTicks); - float f1 = (float) ((double) entityIn.prevRotationYaw - + (double) (entityIn.rotationYaw - entityIn.prevRotationYaw) * partialTicks); - if (Minecraft.getMinecraft().gameSettings.thirdPersonView == 2) { - f += 180.0F; + public void playRecord(String s, BlockPos blockpos) { + ISound isound = (ISound) this.mapSoundPositions.get(blockpos); + if (isound != null) { + this.mc.getSoundHandler().stopSound(isound); + this.mapSoundPositions.remove(blockpos); } - float f2 = MathHelper.cos(-f1 * 0.017453292F - 3.1415927F); - float f3 = MathHelper.sin(-f1 * 0.017453292F - 3.1415927F); - float f4 = -MathHelper.cos(-f * 0.017453292F); - float f5 = MathHelper.sin(-f * 0.017453292F); - return new Vector3f(f3 * f4, f5, f2 * f4); + if (s != null) { + ItemRecord itemrecord = ItemRecord.getRecord(s); + if (itemrecord != null) { + this.mc.ingameGUI.setRecordPlayingMessage(itemrecord.getRecordNameLocal()); + } + + PositionedSoundRecord positionedsoundrecord = PositionedSoundRecord.create(new ResourceLocation(s), + (float) blockpos.getX(), (float) blockpos.getY(), (float) blockpos.getZ()); + this.mapSoundPositions.put(blockpos, positionedsoundrecord); + this.mc.getSoundHandler().playSound(positionedsoundrecord); + } + + } + + /** + * + Plays the specified sound. Arg: soundName, x, y, z, volume, pitch + */ + public void playSound(String var1, double var2, double var4, double var6, float var8, float var9) { + } + + /** + * + Plays sound to all near players except the player reference given + */ + public void playSoundToNearExcept(EntityPlayer var1, String var2, double var3, double var5, double var7, float var9, + float var10) { + } + + private void postRenderDamagedBlocks() { + GlStateManager.disableAlpha(); + GlStateManager.doPolygonOffset(0.0F, 0.0F); + GlStateManager.disablePolygonOffset(); + GlStateManager.enableAlpha(); + GlStateManager.depthMask(true); + GlStateManager.popMatrix(); + } + + private void preRenderDamagedBlocks() { + GlStateManager.tryBlendFuncSeparate(GL_DST_COLOR, GL_SRC_COLOR, 1, 0); + GlStateManager.enableBlend(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 0.5F); + GlStateManager.doPolygonOffset(-3.0F, -3.0F); + GlStateManager.enablePolygonOffset(); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + GlStateManager.enableAlpha(); + GlStateManager.pushMatrix(); + } + + private void renderBlockLayer(EnumWorldBlockLayer blockLayerIn) { + this.mc.entityRenderer.enableLightmap(); + this.renderContainer.renderChunkLayer(blockLayerIn); + this.mc.entityRenderer.disableLightmap(); } public int renderBlockLayer(EnumWorldBlockLayer blockLayerIn, double partialTicks, int pass, Entity entityIn) { @@ -1101,10 +1123,6 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene return l; } - public static interface ChunkCullAdapter { - boolean shouldCull(RenderChunk chunk); - } - public int renderBlockLayerShadow(EnumWorldBlockLayer blockLayerIn, AxisAlignedBB boundingBox, ChunkCullAdapter cullAdapter) { int i = 0; @@ -1137,297 +1155,6 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene return i; } - private void renderBlockLayer(EnumWorldBlockLayer blockLayerIn) { - this.mc.entityRenderer.enableLightmap(); - this.renderContainer.renderChunkLayer(blockLayerIn); - this.mc.entityRenderer.disableLightmap(); - } - - public int renderParaboloidBlockLayer(EnumWorldBlockLayer blockLayerIn, double partialTicks, int up, - Entity entityIn) { - double rad = 8.0; - - int minX = (int) (entityIn.posX - rad); - int minY = (int) entityIn.posY; - if (up == -1) { - minY -= rad * 0.75; - } else { - minY += 1.0; - } - int minZ = (int) (entityIn.posZ - rad); - - int maxX = (int) (entityIn.posX + rad); - int maxY = (int) entityIn.posY; - if (up == 1) { - maxY += rad; - } else { - maxY += 2.0; - } - int maxZ = (int) (entityIn.posZ + rad); - - BlockPos tmp = new BlockPos(0, 0, 0); - minX = MathHelper.floor_double(minX / 16.0) * 16; - minY = MathHelper.floor_double(minY / 16.0) * 16; - minZ = MathHelper.floor_double(minZ / 16.0) * 16; - maxX = MathHelper.floor_double(maxX / 16.0) * 16; - maxY = MathHelper.floor_double(maxY / 16.0) * 16; - maxZ = MathHelper.floor_double(maxZ / 16.0) * 16; - - int i = 0; - for (int cx = minX; cx <= maxX; cx += 16) { - for (int cz = minZ; cz <= maxZ; cz += 16) { - for (int cy = minY; cy <= maxY; cy += 16) { - tmp.x = cx; - tmp.y = cy; - tmp.z = cz; - RenderChunk ch = viewFrustum.getRenderChunk(tmp); - CompiledChunk cch; - if (ch != null && (cch = ch.getCompiledChunk()) != null && !cch.isLayerEmpty(blockLayerIn)) { - this.renderContainer.addRenderChunk(ch, blockLayerIn); - ++i; - } - } - } - } - if (i > 0) { - this.mc.entityRenderer.enableLightmap(); - this.renderContainer.renderChunkLayer(blockLayerIn); - this.mc.entityRenderer.disableLightmap(); - } - return i; - } - - private void cleanupDamagedBlocks(Iterator iteratorIn) { - while (iteratorIn.hasNext()) { - DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress) iteratorIn.next(); - int i = destroyblockprogress.getCreationCloudUpdateTick(); - if (this.cloudTickCounter - i > 400) { - iteratorIn.remove(); - } - } - - } - - public void updateClouds() { - ++this.cloudTickCounter; - if (this.cloudTickCounter % 20 == 0) { - this.cleanupDamagedBlocks(this.damagedBlocks.values().iterator()); - } - - } - - private void renderSkyEnd() { - GlStateManager.disableFog(); - GlStateManager.disableAlpha(); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - RenderHelper.disableStandardItemLighting(); - GlStateManager.depthMask(false); - this.renderEngine.bindTexture(locationEndSkyPng); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - - for (int i = 0; i < 6; ++i) { - GlStateManager.pushMatrix(); - if (i == 1) { - GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); - } - - if (i == 2) { - GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F); - } - - if (i == 3) { - GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F); - } - - if (i == 4) { - GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F); - } - - if (i == 5) { - GlStateManager.rotate(-90.0F, 0.0F, 0.0F, 1.0F); - } - - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos(-100.0D, -100.0D, -100.0D).tex(0.0D, 0.0D).color(40, 40, 40, 255).endVertex(); - worldrenderer.pos(-100.0D, -100.0D, 100.0D).tex(0.0D, 16.0D).color(40, 40, 40, 255).endVertex(); - worldrenderer.pos(100.0D, -100.0D, 100.0D).tex(16.0D, 16.0D).color(40, 40, 40, 255).endVertex(); - worldrenderer.pos(100.0D, -100.0D, -100.0D).tex(16.0D, 0.0D).color(40, 40, 40, 255).endVertex(); - tessellator.draw(); - GlStateManager.popMatrix(); - } - - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.enableAlpha(); - } - - public void renderSky(float partialTicks, int pass) { - if (this.mc.theWorld.provider.getDimensionId() == 1) { - this.renderSkyEnd(); - } else if (this.mc.theWorld.provider.isSurfaceWorld()) { - GlStateManager.disableTexture2D(); - Vec3 vec3 = this.theWorld.getSkyColor(this.mc.getRenderViewEntity(), partialTicks); - float f = (float) vec3.xCoord; - float f1 = (float) vec3.yCoord; - float f2 = (float) vec3.zCoord; - if (pass != 2) { - float f3 = (f * 30.0F + f1 * 59.0F + f2 * 11.0F) / 100.0F; - float f4 = (f * 30.0F + f1 * 70.0F) / 100.0F; - float f5 = (f * 30.0F + f2 * 70.0F) / 100.0F; - f = f3; - f1 = f4; - f2 = f5; - } - - GlStateManager.color(f, f1, f2); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - GlStateManager.depthMask(false); - GlStateManager.enableFog(); - GlStateManager.color(f, f1, f2); - GlStateManager.callList(this.glSkyList); - - GlStateManager.disableFog(); - GlStateManager.disableAlpha(); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - RenderHelper.disableStandardItemLighting(); - float[] afloat = this.theWorld.provider - .calcSunriseSunsetColors(this.theWorld.getCelestialAngle(partialTicks), partialTicks); - if (afloat != null) { - GlStateManager.disableTexture2D(); - GlStateManager.shadeModel(GL_SMOOTH); - GlStateManager.pushMatrix(); - GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate( - MathHelper.sin(this.theWorld.getCelestialAngleRadians(partialTicks)) < 0.0F ? 180.0F : 0.0F, - 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F); - float f6 = afloat[0]; - float f7 = afloat[1]; - float f8 = afloat[2]; - if (pass != 2) { - float f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F; - float f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F; - float f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F; - f6 = f9; - f7 = f10; - f8 = f11; - } - - worldrenderer.begin(6, DefaultVertexFormats.POSITION_COLOR); - worldrenderer.pos(0.0D, 100.0D, 0.0D).color(f6, f7, f8, afloat[3]).endVertex(); - boolean flag = true; - - for (int k = 0; k <= 16; ++k) { - float f21 = (float) k * 3.1415927F * 2.0F / 16.0F; - float f12 = MathHelper.sin(f21); - float f13 = MathHelper.cos(f21); - worldrenderer - .pos((double) (f12 * 120.0F), (double) (f13 * 120.0F), (double) (f13 * 40.0F * afloat[3])) - .color(afloat[0], afloat[1], afloat[2], 0.0F).endVertex(); - } - - tessellator.draw(); - GlStateManager.popMatrix(); - GlStateManager.shadeModel(GL_FLAT); - } - - GlStateManager.enableTexture2D(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, 1, 1, 0); - GlStateManager.pushMatrix(); - float f16 = 1.0F - this.theWorld.getRainStrength(partialTicks); - GlStateManager.color(1.0F, 1.0F, 1.0F, f16); - GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(this.theWorld.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F); - float f17 = 30.0F; - this.renderEngine.bindTexture(locationSunPng); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (-f17), 100.0D, (double) (-f17)).tex(0.0D, 0.0D).endVertex(); - worldrenderer.pos((double) f17, 100.0D, (double) (-f17)).tex(1.0D, 0.0D).endVertex(); - worldrenderer.pos((double) f17, 100.0D, (double) f17).tex(1.0D, 1.0D).endVertex(); - worldrenderer.pos((double) (-f17), 100.0D, (double) f17).tex(0.0D, 1.0D).endVertex(); - tessellator.draw(); - f17 = 20.0F; - this.renderEngine.bindTexture(locationMoonPhasesPng); - int i = this.theWorld.getMoonPhase(); - int j = i % 4; - int l = i / 4 % 2; - float f22 = (float) (j + 0) / 4.0F; - float f23 = (float) (l + 0) / 2.0F; - float f24 = (float) (j + 1) / 4.0F; - float f14 = (float) (l + 1) / 2.0F; - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (-f17), -100.0D, (double) f17).tex((double) f24, (double) f14).endVertex(); - worldrenderer.pos((double) f17, -100.0D, (double) f17).tex((double) f22, (double) f14).endVertex(); - worldrenderer.pos((double) f17, -100.0D, (double) (-f17)).tex((double) f22, (double) f23).endVertex(); - worldrenderer.pos((double) (-f17), -100.0D, (double) (-f17)).tex((double) f24, (double) f23).endVertex(); - tessellator.draw(); - GlStateManager.disableTexture2D(); - float f15 = this.theWorld.getStarBrightness(partialTicks) * f16; - if (f15 > 0.0F) { - GlStateManager.color(f15, f15, f15, f15); - GlStateManager.callList(this.starGLCallList); - } - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableBlend(); - GlStateManager.enableAlpha(); - GlStateManager.enableFog(); - GlStateManager.popMatrix(); - GlStateManager.disableTexture2D(); - GlStateManager.color(0.0F, 0.0F, 0.0F); - double d0 = this.mc.thePlayer.getPositionEyes(partialTicks).yCoord - this.theWorld.getHorizon(); - if (d0 < 0.0D) { - GlStateManager.pushMatrix(); - GlStateManager.translate(0.0F, 12.0F, 0.0F); - GlStateManager.callList(this.glSkyList2); - - GlStateManager.popMatrix(); - float f18 = 1.0F; - float f19 = -((float) (d0 + 65.0D)); - float f20 = -1.0F; - worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); - worldrenderer.pos(-1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(-1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos(1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); - tessellator.draw(); - } - - if (this.theWorld.provider.isSkyColored()) { - GlStateManager.color(f * 0.2F + 0.04F, f1 * 0.2F + 0.04F, f2 * 0.6F + 0.1F); - } else { - GlStateManager.color(f, f1, f2); - } - - GlStateManager.pushMatrix(); - GlStateManager.translate(0.0F, -((float) (d0 - 16.0D)), 0.0F); - GlStateManager.callList(this.glSkyList2); - GlStateManager.popMatrix(); - GlStateManager.enableTexture2D(); - GlStateManager.depthMask(true); - } - } - public void renderClouds(float partialTicks, int pass) { if (this.mc.theWorld.provider.isSurfaceWorld()) { if (this.mc.gameSettings.func_181147_e() == 2) { @@ -1504,13 +1231,6 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene } } - /**+ - * Checks if the given position is to be rendered with cloud fog - */ - public boolean hasCloudFog(double x, double y, double z, float partialTicks) { - return false; - } - private void renderCloudsFancy(float partialTicks, int pass) { GlStateManager.disableCull(); float f = (float) (this.mc.getRenderViewEntity().lastTickPosY @@ -1758,25 +1478,628 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene GlStateManager.enableCull(); } - public void updateChunks(long finishTimeNano) { - this.displayListEntitiesDirty |= this.renderDispatcher.updateChunks(finishTimeNano); - if (!this.chunksToUpdate.isEmpty()) { - Iterator iterator = this.chunksToUpdate.iterator(); + public void renderEntities(Entity renderViewEntity, ICamera camera, float partialTicks) { + if (this.renderEntitiesStartupCounter > 0) { + --this.renderEntitiesStartupCounter; + } else { + boolean light = DynamicLightManager.isRenderingLights(); + double d0 = renderViewEntity.prevPosX + + (renderViewEntity.posX - renderViewEntity.prevPosX) * (double) partialTicks; + double d1 = renderViewEntity.prevPosY + + (renderViewEntity.posY - renderViewEntity.prevPosY) * (double) partialTicks; + double d2 = renderViewEntity.prevPosZ + + (renderViewEntity.posZ - renderViewEntity.prevPosZ) * (double) partialTicks; + TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(this.theWorld, this.mc.getTextureManager(), + this.mc.fontRendererObj, this.mc.getRenderViewEntity(), partialTicks); + this.renderManager.cacheActiveRenderInfo(this.theWorld, this.mc.fontRendererObj, + this.mc.getRenderViewEntity(), this.mc.pointedEntity, this.mc.gameSettings, partialTicks); + this.countEntitiesTotal = 0; + this.countEntitiesRendered = 0; + this.countEntitiesHidden = 0; + Entity entity = this.mc.getRenderViewEntity(); + double d3 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; + double d4 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; + double d5 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; + TileEntityRendererDispatcher.staticPlayerX = d3; + TileEntityRendererDispatcher.staticPlayerY = d4; + TileEntityRendererDispatcher.staticPlayerZ = d5; + this.renderManager.setRenderPosition(d3, d4, d5); + this.mc.entityRenderer.enableLightmap(); + List list = this.theWorld.getLoadedEntityList(); + this.countEntitiesTotal = list.size(); - while (iterator.hasNext()) { - RenderChunk renderchunk = (RenderChunk) iterator.next(); - if (!this.renderDispatcher.updateChunkLater(renderchunk)) { - break; + if (!DeferredStateManager.isDeferredRenderer()) { + for (int i = 0; i < this.theWorld.weatherEffects.size(); ++i) { + Entity entity1 = (Entity) this.theWorld.weatherEffects.get(i); + ++this.countEntitiesRendered; + if (entity1.isInRangeToRender3d(d0, d1, d2)) { + if (light) { + entity1.renderDynamicLightsEagler(partialTicks, true); + } + this.renderManager.renderEntitySimple(entity1, partialTicks); + } + } + } + + label738: for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = this.renderInfos + .get(ii); + Chunk chunk = this.theWorld.getChunkFromBlockCoords( + renderglobal$containerlocalrenderinformation.renderChunk.getPosition()); + ClassInheritanceMultiMap classinheritancemultimap = chunk + .getEntityLists()[renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() + / 16]; + if (!classinheritancemultimap.isEmpty()) { + Iterator iterator = classinheritancemultimap.iterator(); + + while (true) { + Entity entity2; + boolean flag2; + while (true) { + if (!iterator.hasNext()) { + continue label738; + } + + entity2 = (Entity) iterator.next(); + flag2 = this.renderManager.shouldRender(entity2, camera, d0, d1, d2) + || entity2.riddenByEntity == this.mc.thePlayer; + if (light) { + entity2.renderDynamicLightsEagler(partialTicks, flag2); + } + if (!flag2) { + break; + } + + boolean flag3 = this.mc.getRenderViewEntity() instanceof EntityLivingBase + ? ((EntityLivingBase) this.mc.getRenderViewEntity()).isPlayerSleeping() + : false; + if ((entity2 != this.mc.getRenderViewEntity() || this.mc.gameSettings.thirdPersonView != 0 + || flag3) + && (entity2.posY < 0.0D || entity2.posY >= 256.0D + || this.theWorld.isBlockLoaded(new BlockPos(entity2)))) { + ++this.countEntitiesRendered; + this.renderManager.renderEntitySimple(entity2, partialTicks); + break; + } + } + + if (!flag2 && entity2 instanceof EntityWitherSkull) { + this.mc.getRenderManager().renderWitherSkull(entity2, partialTicks); + } + } + } + } + + RenderHelper.enableStandardItemLighting(); + + for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation1 = this.renderInfos + .get(ii); + List list1 = renderglobal$containerlocalrenderinformation1.renderChunk.getCompiledChunk() + .getTileEntities(); + if (!list1.isEmpty()) { + for (int m = 0, n = list1.size(); m < n; ++m) { + TileEntityRendererDispatcher.instance.renderTileEntity((TileEntity) list1.get(m), partialTicks, + -1); + } + } + } + + synchronized (this.field_181024_n) { + for (TileEntity tileentity : this.field_181024_n) { + TileEntityRendererDispatcher.instance.renderTileEntity(tileentity, partialTicks, -1); + } + } + + this.preRenderDamagedBlocks(); + + for (DestroyBlockProgress destroyblockprogress : this.damagedBlocks.values()) { + BlockPos blockpos = destroyblockprogress.getPosition(); + TileEntity tileentity1 = this.theWorld.getTileEntity(blockpos); + if (tileentity1 instanceof TileEntityChest) { + TileEntityChest tileentitychest = (TileEntityChest) tileentity1; + if (tileentitychest.adjacentChestXNeg != null) { + blockpos = blockpos.offset(EnumFacing.WEST); + tileentity1 = this.theWorld.getTileEntity(blockpos); + } else if (tileentitychest.adjacentChestZNeg != null) { + blockpos = blockpos.offset(EnumFacing.NORTH); + tileentity1 = this.theWorld.getTileEntity(blockpos); + } } - renderchunk.setNeedsUpdate(false); - iterator.remove(); - long i = finishTimeNano - EagRuntime.nanoTime(); - if (i < 0L) { - break; + Block block = this.theWorld.getBlockState(blockpos).getBlock(); + if (tileentity1 != null && (block instanceof BlockChest || block instanceof BlockEnderChest + || block instanceof BlockSign || block instanceof BlockSkull)) { + TileEntityRendererDispatcher.instance.renderTileEntity(tileentity1, partialTicks, + destroyblockprogress.getPartialBlockDamage()); + } + } + + this.postRenderDamagedBlocks(); + this.mc.entityRenderer.disableLightmap(); + } + } + + public void renderEntityOutlineFramebuffer() { + + } + + public int renderParaboloidBlockLayer(EnumWorldBlockLayer blockLayerIn, double partialTicks, int up, + Entity entityIn) { + double rad = 8.0; + + int minX = (int) (entityIn.posX - rad); + int minY = (int) entityIn.posY; + if (up == -1) { + minY -= rad * 0.75; + } else { + minY += 1.0; + } + int minZ = (int) (entityIn.posZ - rad); + + int maxX = (int) (entityIn.posX + rad); + int maxY = (int) entityIn.posY; + if (up == 1) { + maxY += rad; + } else { + maxY += 2.0; + } + int maxZ = (int) (entityIn.posZ + rad); + + BlockPos tmp = new BlockPos(0, 0, 0); + minX = MathHelper.floor_double(minX / 16.0) * 16; + minY = MathHelper.floor_double(minY / 16.0) * 16; + minZ = MathHelper.floor_double(minZ / 16.0) * 16; + maxX = MathHelper.floor_double(maxX / 16.0) * 16; + maxY = MathHelper.floor_double(maxY / 16.0) * 16; + maxZ = MathHelper.floor_double(maxZ / 16.0) * 16; + + int i = 0; + for (int cx = minX; cx <= maxX; cx += 16) { + for (int cz = minZ; cz <= maxZ; cz += 16) { + for (int cy = minY; cy <= maxY; cy += 16) { + tmp.x = cx; + tmp.y = cy; + tmp.z = cz; + RenderChunk ch = viewFrustum.getRenderChunk(tmp); + CompiledChunk cch; + if (ch != null && (cch = ch.getCompiledChunk()) != null && !cch.isLayerEmpty(blockLayerIn)) { + this.renderContainer.addRenderChunk(ch, blockLayerIn); + ++i; + } } } } + if (i > 0) { + this.mc.entityRenderer.enableLightmap(); + this.renderContainer.renderChunkLayer(blockLayerIn); + this.mc.entityRenderer.disableLightmap(); + } + return i; + } + + public void renderParaboloidTileEntities(Entity renderViewEntity, float partialTicks, int up) { + if (renderEntitiesStartupCounter <= 0) { + TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(theWorld, mc.getTextureManager(), + mc.fontRendererObj, renderViewEntity, partialTicks); + renderManager.cacheActiveRenderInfo(theWorld, mc.fontRendererObj, renderViewEntity, mc.pointedEntity, + mc.gameSettings, partialTicks); + + double d3 = renderViewEntity.lastTickPosX + + (renderViewEntity.posX - renderViewEntity.lastTickPosX) * (double) partialTicks; + double d4 = renderViewEntity.lastTickPosY + + (renderViewEntity.posY - renderViewEntity.lastTickPosY) * (double) partialTicks; + double d5 = renderViewEntity.lastTickPosZ + + (renderViewEntity.posZ - renderViewEntity.lastTickPosZ) * (double) partialTicks; + TileEntityRendererDispatcher.staticPlayerX = d3; + TileEntityRendererDispatcher.staticPlayerY = d4; + TileEntityRendererDispatcher.staticPlayerZ = d5; + renderManager.setRenderPosition(d3, d4, d5); + + double rad = 8.0; + + int minX = (int) (d3 - rad); + int minY = (int) d4; + if (up == -1) { + minY -= rad; + } + int minZ = (int) (d5 - rad); + + int maxX = (int) (d3 + rad); + int maxY = (int) d4; + if (up == 1) { + maxY += rad; + } + int maxZ = (int) (d5 + rad); + + BlockPos tmp = new BlockPos(0, 0, 0); + minX = MathHelper.floor_double(minX / 16.0) * 16; + minY = MathHelper.floor_double(minY / 16.0) * 16; + minZ = MathHelper.floor_double(minZ / 16.0) * 16; + maxX = MathHelper.floor_double(maxX / 16.0) * 16; + maxY = MathHelper.floor_double(maxY / 16.0) * 16; + maxZ = MathHelper.floor_double(maxZ / 16.0) * 16; + + for (int cx = minX; cx <= maxX; cx += 16) { + for (int cz = minZ; cz <= maxZ; cz += 16) { + for (int cy = minY; cy <= maxY; cy += 16) { + tmp.x = cx; + tmp.y = cy; + tmp.z = cz; + RenderChunk ch = viewFrustum.getRenderChunk(tmp); + CompiledChunk cch; + if (ch != null && (cch = ch.compiledChunk) != null) { + List tileEntities = cch.getTileEntities(); + for (int i = 0, l = tileEntities.size(); i < l; ++i) { + mc.entityRenderer.enableLightmap(); + TileEntityRendererDispatcher.instance.renderTileEntity(tileEntities.get(i), + partialTicks, -1); + GlStateManager.disableShaderBlendAdd(); + GlStateManager.disableBlend(); + GlStateManager.depthMask(true); + } + } + } + } + } + mc.entityRenderer.disableLightmap(); + } + } + + public void renderShadowLODEntities(Entity renderViewEntity, float partialTicks, + EntityChunkCullAdapter entityChunkCull, EntityObjectCullAdapter entityObjectCull) { // TODO + if (renderEntitiesStartupCounter <= 0) { + TileEntityRendererDispatcher.instance.cacheActiveRenderInfo(theWorld, mc.getTextureManager(), + mc.fontRendererObj, renderViewEntity, partialTicks); + renderManager.cacheActiveRenderInfo(theWorld, mc.fontRendererObj, renderViewEntity, mc.pointedEntity, + mc.gameSettings, partialTicks); + + double d3 = renderViewEntity.lastTickPosX + + (renderViewEntity.posX - renderViewEntity.lastTickPosX) * (double) partialTicks; + double d4 = renderViewEntity.lastTickPosY + + (renderViewEntity.posY - renderViewEntity.lastTickPosY) * (double) partialTicks; + double d5 = renderViewEntity.lastTickPosZ + + (renderViewEntity.posZ - renderViewEntity.lastTickPosZ) * (double) partialTicks; + TileEntityRendererDispatcher.staticPlayerX = d3; + TileEntityRendererDispatcher.staticPlayerY = d4; + TileEntityRendererDispatcher.staticPlayerZ = d5; + renderManager.setRenderPosition(d3, d4, d5); + + for (RenderGlobal.ContainerLocalRenderInformation containerlocalrenderinformation : this.renderInfos) { + RenderChunk currentRenderChunk = containerlocalrenderinformation.renderChunk; + + if (!entityChunkCull.shouldCull(currentRenderChunk)) { + Chunk chunk = this.theWorld + .getChunkFromBlockCoords(containerlocalrenderinformation.renderChunk.getPosition()); + ClassInheritanceMultiMap classinheritancemultimap = chunk + .getEntityLists()[containerlocalrenderinformation.renderChunk.getPosition().getY() / 16]; + if (!classinheritancemultimap.isEmpty()) { + Iterator iterator = classinheritancemultimap.iterator(); + while (iterator.hasNext()) { + Entity entity2 = iterator.next(); + if (!entityObjectCull.shouldCull(currentRenderChunk, renderManager, entity2) + || entity2.riddenByEntity == this.mc.thePlayer) { + if (entity2.posY < 0.0D || entity2.posY >= 256.0D + || this.theWorld.isBlockLoaded(new BlockPos(entity2))) { + ++this.countEntitiesRendered; + this.renderManager.renderEntitySimple(entity2, partialTicks); + mc.entityRenderer.disableLightmap(); + GlStateManager.disableShaderBlendAdd(); + GlStateManager.disableBlend(); + GlStateManager.depthMask(true); + } + } + + } + + // TODO: why? + // if (!flag2 && entity2 instanceof EntityWitherSkull) { + // this.mc.getRenderManager().renderWitherSkull(entity2, partialTicks); + // } + } + + List tileEntities = currentRenderChunk.compiledChunk.getTileEntities(); + for (int i = 0, l = tileEntities.size(); i < l; ++i) { + TileEntityRendererDispatcher.instance.renderTileEntity(tileEntities.get(i), partialTicks, -1); + mc.entityRenderer.disableLightmap(); + GlStateManager.disableShaderBlendAdd(); + GlStateManager.disableBlend(); + GlStateManager.depthMask(true); + } + } + } + + synchronized (this.field_181024_n) { + for (TileEntity tileentity : this.field_181024_n) { + TileEntityRendererDispatcher.instance.renderTileEntity(tileentity, partialTicks, -1); + mc.entityRenderer.disableLightmap(); + GlStateManager.disableShaderBlendAdd(); + GlStateManager.disableBlend(); + GlStateManager.depthMask(true); + } + } + } + } + + public void renderSky(float partialTicks, int pass) { + if (this.mc.theWorld.provider.getDimensionId() == 1) { + this.renderSkyEnd(); + } else if (this.mc.theWorld.provider.isSurfaceWorld()) { + GlStateManager.disableTexture2D(); + Vec3 vec3 = this.theWorld.getSkyColor(this.mc.getRenderViewEntity(), partialTicks); + float f = (float) vec3.xCoord; + float f1 = (float) vec3.yCoord; + float f2 = (float) vec3.zCoord; + if (pass != 2) { + float f3 = (f * 30.0F + f1 * 59.0F + f2 * 11.0F) / 100.0F; + float f4 = (f * 30.0F + f1 * 70.0F) / 100.0F; + float f5 = (f * 30.0F + f2 * 70.0F) / 100.0F; + f = f3; + f1 = f4; + f2 = f5; + } + + GlStateManager.color(f, f1, f2); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + GlStateManager.depthMask(false); + GlStateManager.enableFog(); + GlStateManager.color(f, f1, f2); + GlStateManager.callList(this.glSkyList); + + GlStateManager.disableFog(); + GlStateManager.disableAlpha(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + RenderHelper.disableStandardItemLighting(); + float[] afloat = this.theWorld.provider + .calcSunriseSunsetColors(this.theWorld.getCelestialAngle(partialTicks), partialTicks); + if (afloat != null) { + GlStateManager.disableTexture2D(); + GlStateManager.shadeModel(GL_SMOOTH); + GlStateManager.pushMatrix(); + GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate( + MathHelper.sin(this.theWorld.getCelestialAngleRadians(partialTicks)) < 0.0F ? 180.0F : 0.0F, + 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F); + float f6 = afloat[0]; + float f7 = afloat[1]; + float f8 = afloat[2]; + if (pass != 2) { + float f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F; + float f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F; + float f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F; + f6 = f9; + f7 = f10; + f8 = f11; + } + + worldrenderer.begin(6, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(0.0D, 100.0D, 0.0D).color(f6, f7, f8, afloat[3]).endVertex(); + boolean flag = true; + + for (int k = 0; k <= 16; ++k) { + float f21 = (float) k * 3.1415927F * 2.0F / 16.0F; + float f12 = MathHelper.sin(f21); + float f13 = MathHelper.cos(f21); + worldrenderer + .pos((double) (f12 * 120.0F), (double) (f13 * 120.0F), (double) (f13 * 40.0F * afloat[3])) + .color(afloat[0], afloat[1], afloat[2], 0.0F).endVertex(); + } + + tessellator.draw(); + GlStateManager.popMatrix(); + GlStateManager.shadeModel(GL_FLAT); + } + + GlStateManager.enableTexture2D(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, 1, 1, 0); + GlStateManager.pushMatrix(); + float f16 = 1.0F - this.theWorld.getRainStrength(partialTicks); + GlStateManager.color(1.0F, 1.0F, 1.0F, f16); + GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(this.theWorld.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F); + float f17 = 30.0F; + this.renderEngine.bindTexture(locationSunPng); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (-f17), 100.0D, (double) (-f17)).tex(0.0D, 0.0D).endVertex(); + worldrenderer.pos((double) f17, 100.0D, (double) (-f17)).tex(1.0D, 0.0D).endVertex(); + worldrenderer.pos((double) f17, 100.0D, (double) f17).tex(1.0D, 1.0D).endVertex(); + worldrenderer.pos((double) (-f17), 100.0D, (double) f17).tex(0.0D, 1.0D).endVertex(); + tessellator.draw(); + f17 = 20.0F; + this.renderEngine.bindTexture(locationMoonPhasesPng); + int i = this.theWorld.getMoonPhase(); + int j = i % 4; + int l = i / 4 % 2; + float f22 = (float) (j + 0) / 4.0F; + float f23 = (float) (l + 0) / 2.0F; + float f24 = (float) (j + 1) / 4.0F; + float f14 = (float) (l + 1) / 2.0F; + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (-f17), -100.0D, (double) f17).tex((double) f24, (double) f14).endVertex(); + worldrenderer.pos((double) f17, -100.0D, (double) f17).tex((double) f22, (double) f14).endVertex(); + worldrenderer.pos((double) f17, -100.0D, (double) (-f17)).tex((double) f22, (double) f23).endVertex(); + worldrenderer.pos((double) (-f17), -100.0D, (double) (-f17)).tex((double) f24, (double) f23).endVertex(); + tessellator.draw(); + GlStateManager.disableTexture2D(); + float f15 = this.theWorld.getStarBrightness(partialTicks) * f16; + if (f15 > 0.0F) { + GlStateManager.color(f15, f15, f15, f15); + GlStateManager.callList(this.starGLCallList); + } + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableBlend(); + GlStateManager.enableAlpha(); + GlStateManager.enableFog(); + GlStateManager.popMatrix(); + GlStateManager.disableTexture2D(); + GlStateManager.color(0.0F, 0.0F, 0.0F); + double d0 = this.mc.thePlayer.getPositionEyes(partialTicks).yCoord - this.theWorld.getHorizon(); + if (d0 < 0.0D) { + GlStateManager.pushMatrix(); + GlStateManager.translate(0.0F, 12.0F, 0.0F); + GlStateManager.callList(this.glSkyList2); + + GlStateManager.popMatrix(); + float f18 = 1.0F; + float f19 = -((float) (d0 + 65.0D)); + float f20 = -1.0F; + worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); + worldrenderer.pos(-1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, (double) f19, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, (double) f19, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(-1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, -1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); + worldrenderer.pos(1.0D, -1.0D, -1.0D).color(0, 0, 0, 255).endVertex(); + tessellator.draw(); + } + + if (this.theWorld.provider.isSkyColored()) { + GlStateManager.color(f * 0.2F + 0.04F, f1 * 0.2F + 0.04F, f2 * 0.6F + 0.1F); + } else { + GlStateManager.color(f, f1, f2); + } + + GlStateManager.pushMatrix(); + GlStateManager.translate(0.0F, -((float) (d0 - 16.0D)), 0.0F); + GlStateManager.callList(this.glSkyList2); + GlStateManager.popMatrix(); + GlStateManager.enableTexture2D(); + GlStateManager.depthMask(true); + } + } + + private void renderSky(WorldRenderer worldRendererIn, float parFloat1, boolean parFlag) { + boolean flag = true; + boolean flag1 = true; + worldRendererIn.begin(7, DefaultVertexFormats.POSITION); + + for (int i = -384; i <= 384; i += 64) { + for (int j = -384; j <= 384; j += 64) { + float f = (float) i; + float f1 = (float) (i + 64); + if (parFlag) { + f1 = (float) i; + f = (float) (i + 64); + } + + worldRendererIn.pos((double) f, (double) parFloat1, (double) j).endVertex(); + worldRendererIn.pos((double) f1, (double) parFloat1, (double) j).endVertex(); + worldRendererIn.pos((double) f1, (double) parFloat1, (double) (j + 64)).endVertex(); + worldRendererIn.pos((double) f, (double) parFloat1, (double) (j + 64)).endVertex(); + } + } + + } + + private void renderSkyEnd() { + GlStateManager.disableFog(); + GlStateManager.disableAlpha(); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + RenderHelper.disableStandardItemLighting(); + GlStateManager.depthMask(false); + this.renderEngine.bindTexture(locationEndSkyPng); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + + for (int i = 0; i < 6; ++i) { + GlStateManager.pushMatrix(); + if (i == 1) { + GlStateManager.rotate(90.0F, 1.0F, 0.0F, 0.0F); + } + + if (i == 2) { + GlStateManager.rotate(-90.0F, 1.0F, 0.0F, 0.0F); + } + + if (i == 3) { + GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F); + } + + if (i == 4) { + GlStateManager.rotate(90.0F, 0.0F, 0.0F, 1.0F); + } + + if (i == 5) { + GlStateManager.rotate(-90.0F, 0.0F, 0.0F, 1.0F); + } + + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + worldrenderer.pos(-100.0D, -100.0D, -100.0D).tex(0.0D, 0.0D).color(40, 40, 40, 255).endVertex(); + worldrenderer.pos(-100.0D, -100.0D, 100.0D).tex(0.0D, 16.0D).color(40, 40, 40, 255).endVertex(); + worldrenderer.pos(100.0D, -100.0D, 100.0D).tex(16.0D, 16.0D).color(40, 40, 40, 255).endVertex(); + worldrenderer.pos(100.0D, -100.0D, -100.0D).tex(16.0D, 0.0D).color(40, 40, 40, 255).endVertex(); + tessellator.draw(); + GlStateManager.popMatrix(); + } + + GlStateManager.depthMask(true); + GlStateManager.enableTexture2D(); + GlStateManager.enableAlpha(); + } + + private void renderStars(WorldRenderer worldRendererIn) { + EaglercraftRandom random = new EaglercraftRandom(10842L); + worldRendererIn.begin(7, DefaultVertexFormats.POSITION); + + for (int i = 0; i < 1500; ++i) { + double d0 = (double) (random.nextFloat() * 2.0F - 1.0F); + double d1 = (double) (random.nextFloat() * 2.0F - 1.0F); + double d2 = (double) (random.nextFloat() * 2.0F - 1.0F); + double d3 = (double) (0.15F + random.nextFloat() * 0.1F); + double d4 = d0 * d0 + d1 * d1 + d2 * d2; + if (d4 < 1.0D && d4 > 0.01D) { + d4 = 1.0D / Math.sqrt(d4); + d0 = d0 * d4; + d1 = d1 * d4; + d2 = d2 * d4; + double d5 = d0 * 100.0D; + double d6 = d1 * 100.0D; + double d7 = d2 * 100.0D; + double d8 = Math.atan2(d0, d2); + double d9 = Math.sin(d8); + double d10 = Math.cos(d8); + double d11 = Math.atan2(Math.sqrt(d0 * d0 + d2 * d2), d1); + double d12 = Math.sin(d11); + double d13 = Math.cos(d11); + double d14 = random.nextDouble() * 3.141592653589793D * 2.0D; + double d15 = Math.sin(d14); + double d16 = Math.cos(d14); + + for (int j = 0; j < 4; ++j) { + double d17 = 0.0D; + double d18 = (double) ((j & 2) - 1) * d3; + double d19 = (double) ((j + 1 & 2) - 1) * d3; + double d20 = 0.0D; + double d21 = d18 * d16 - d19 * d15; + double d22 = d19 * d16 + d18 * d15; + double d23 = d21 * d12 + 0.0D * d13; + double d24 = 0.0D * d12 - d21 * d13; + double d25 = d24 * d9 - d22 * d10; + double d26 = d22 * d9 + d24 * d10; + worldRendererIn.pos(d5 + d25, d6 + d23, d7 + d26).endVertex(); + } + } + } + } public void renderWorldBorder(Entity partialTicks, float parFloat1) { @@ -1904,279 +2227,203 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene } } - private void preRenderDamagedBlocks() { - GlStateManager.tryBlendFuncSeparate(GL_DST_COLOR, GL_SRC_COLOR, 1, 0); - GlStateManager.enableBlend(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 0.5F); - GlStateManager.doPolygonOffset(-3.0F, -3.0F); - GlStateManager.enablePolygonOffset(); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - GlStateManager.enableAlpha(); - GlStateManager.pushMatrix(); + public void sendBlockBreakProgress(int i, BlockPos blockpos, int j) { + if (j >= 0 && j < 10) { + DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress) this.damagedBlocks + .get(Integer.valueOf(i)); + if (destroyblockprogress == null || destroyblockprogress.getPosition().getX() != blockpos.getX() + || destroyblockprogress.getPosition().getY() != blockpos.getY() + || destroyblockprogress.getPosition().getZ() != blockpos.getZ()) { + destroyblockprogress = new DestroyBlockProgress(i, blockpos); + this.damagedBlocks.put(Integer.valueOf(i), destroyblockprogress); + } + + destroyblockprogress.setPartialBlockDamage(j); + destroyblockprogress.setCloudUpdateTick(this.cloudTickCounter); + } else { + this.damagedBlocks.remove(Integer.valueOf(i)); + } + } - private void postRenderDamagedBlocks() { - GlStateManager.disableAlpha(); - GlStateManager.doPolygonOffset(0.0F, 0.0F); - GlStateManager.disablePolygonOffset(); - GlStateManager.enableAlpha(); - GlStateManager.depthMask(true); - GlStateManager.popMatrix(); + public void setDisplayListEntitiesDirty() { + this.displayListEntitiesDirty = true; } - public void drawBlockDamageTexture(Tessellator tessellatorIn, WorldRenderer worldRendererIn, Entity entityIn, - float partialTicks) { - double d0 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double) partialTicks; - double d1 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double) partialTicks; - double d2 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; - if (!this.damagedBlocks.isEmpty()) { - this.renderEngine.bindTexture(TextureMap.locationBlocksTexture); - this.preRenderDamagedBlocks(); - worldRendererIn.begin(7, - (DeferredStateManager.isDeferredRenderer() || DynamicLightsStateManager.isDynamicLightsRender()) - ? VertexFormat.BLOCK_SHADERS - : DefaultVertexFormats.BLOCK); - worldRendererIn.setTranslation(-d0, -d1, -d2); - worldRendererIn.markDirty(); - Iterator iterator = this.damagedBlocks.values().iterator(); + public void setupTerrain(Entity viewEntity, double partialTicks, ICamera camera, int frameCount, + boolean playerSpectator) { + if (this.mc.gameSettings.renderDistanceChunks != this.renderDistanceChunks) { + this.loadRenderers(); + } - while (iterator.hasNext()) { - DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress) iterator.next(); - BlockPos blockpos = destroyblockprogress.getPosition(); - double d3 = (double) blockpos.getX() - d0; - double d4 = (double) blockpos.getY() - d1; - double d5 = (double) blockpos.getZ() - d2; - Block block = this.theWorld.getBlockState(blockpos).getBlock(); - if (!(block instanceof BlockChest) && !(block instanceof BlockEnderChest) - && !(block instanceof BlockSign) && !(block instanceof BlockSkull)) { - if (d3 * d3 + d4 * d4 + d5 * d5 > 1024.0D) { - iterator.remove(); - } else { - IBlockState iblockstate = this.theWorld.getBlockState(blockpos); - if (iblockstate.getBlock().getMaterial() != Material.air) { - int i = destroyblockprogress.getPartialBlockDamage(); - EaglerTextureAtlasSprite textureatlassprite = this.destroyBlockIcons[i]; - BlockRendererDispatcher blockrendererdispatcher = this.mc.getBlockRendererDispatcher(); - if (DynamicLightsStateManager.isInDynamicLightsPass()) { - DynamicLightsStateManager.reportForwardRenderObjectPosition2(blockpos.x, blockpos.y, - blockpos.z); - } - blockrendererdispatcher.renderBlockDamage(iblockstate, blockpos, textureatlassprite, - this.theWorld); + double d0 = viewEntity.posX - this.frustumUpdatePosX; + double d1 = viewEntity.posY - this.frustumUpdatePosY; + double d2 = viewEntity.posZ - this.frustumUpdatePosZ; + if (this.frustumUpdatePosChunkX != viewEntity.chunkCoordX + || this.frustumUpdatePosChunkY != viewEntity.chunkCoordY + || this.frustumUpdatePosChunkZ != viewEntity.chunkCoordZ || d0 * d0 + d1 * d1 + d2 * d2 > 16.0D) { + this.frustumUpdatePosX = viewEntity.posX; + this.frustumUpdatePosY = viewEntity.posY; + this.frustumUpdatePosZ = viewEntity.posZ; + this.frustumUpdatePosChunkX = viewEntity.chunkCoordX; + this.frustumUpdatePosChunkY = viewEntity.chunkCoordY; + this.frustumUpdatePosChunkZ = viewEntity.chunkCoordZ; + this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posZ); + } + + double d3 = viewEntity.lastTickPosX + (viewEntity.posX - viewEntity.lastTickPosX) * partialTicks; + double d4 = viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks; + double d5 = viewEntity.lastTickPosZ + (viewEntity.posZ - viewEntity.lastTickPosZ) * partialTicks; + this.renderContainer.initialize(d3, d4, d5); + if (this.debugFixedClippingHelper != null) { + Frustum frustum = new Frustum(this.debugFixedClippingHelper); + frustum.setPosition(this.debugTerrainFrustumPosition.field_181059_a, + this.debugTerrainFrustumPosition.field_181060_b, this.debugTerrainFrustumPosition.field_181061_c); + camera = frustum; + } + + BlockPos blockpos1 = new BlockPos(d3, d4 + (double) viewEntity.getEyeHeight(), d5); + RenderChunk renderchunk = this.viewFrustum.getRenderChunk(blockpos1); + BlockPos blockpos = new BlockPos(MathHelper.floor_double(d3 / 16.0D) * 16, + MathHelper.floor_double(d4 / 16.0D) * 16, MathHelper.floor_double(d5 / 16.0D) * 16); + this.displayListEntitiesDirty = this.displayListEntitiesDirty || !this.chunksToUpdate.isEmpty() + || viewEntity.posX != this.lastViewEntityX || viewEntity.posY != this.lastViewEntityY + || viewEntity.posZ != this.lastViewEntityZ + || (double) viewEntity.rotationPitch != this.lastViewEntityPitch + || (double) viewEntity.rotationYaw != this.lastViewEntityYaw + || this.mc.entityRenderer.currentProjMatrixFOV != this.lastViewProjMatrixFOV; + this.lastViewEntityX = viewEntity.posX; + this.lastViewEntityY = viewEntity.posY; + this.lastViewEntityZ = viewEntity.posZ; + this.lastViewEntityPitch = (double) viewEntity.rotationPitch; + this.lastViewEntityYaw = (double) viewEntity.rotationYaw; + this.lastViewProjMatrixFOV = this.mc.entityRenderer.currentProjMatrixFOV; + boolean flag = this.debugFixedClippingHelper != null; + if (!flag && this.displayListEntitiesDirty) { + this.displayListEntitiesDirty = false; + this.renderInfos = Lists.newArrayList(); + LinkedList linkedlist = Lists.newLinkedList(); + boolean flag1 = this.mc.renderChunksMany; + if (renderchunk != null) { + boolean flag2 = false; + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation3 = new RenderGlobal.ContainerLocalRenderInformation( + renderchunk, (EnumFacing) null, 0); + Set set1 = this.getVisibleFacings(blockpos1); + if (set1.size() == 1) { + Vector3f vector3f = this.getViewVector(viewEntity, partialTicks); + EnumFacing enumfacing = EnumFacing.getFacingFromVector(vector3f.x, vector3f.y, vector3f.z) + .getOpposite(); + set1.remove(enumfacing); + } + + if (set1.isEmpty()) { + flag2 = true; + } + + if (flag2 && !playerSpectator) { + this.renderInfos.add(renderglobal$containerlocalrenderinformation3); + } else { + if (playerSpectator && this.theWorld.getBlockState(blockpos1).getBlock().isOpaqueCube()) { + flag1 = false; + } + + renderchunk.setFrameIndex(frameCount); + linkedlist.add(renderglobal$containerlocalrenderinformation3); + } + } else { + int i = blockpos1.getY() > 0 ? 248 : 8; + + for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j) { + for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k) { + RenderChunk renderchunk1 = this.viewFrustum + .getRenderChunk(new BlockPos((j << 4) + 8, i, (k << 4) + 8)); + if (renderchunk1 != null + && ((ICamera) camera).isBoundingBoxInFrustum(renderchunk1.boundingBox)) { + renderchunk1.setFrameIndex(frameCount); + linkedlist.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, + (EnumFacing) null, 0)); } } } } - tessellatorIn.draw(); - worldRendererIn.setTranslation(0.0D, 0.0D, 0.0D); - this.postRenderDamagedBlocks(); - } - - } - - /**+ - * Draws the selection box for the player. Args: entityPlayer, - * rayTraceHit, i, itemStack, partialTickTime - */ - public void drawSelectionBox(EntityPlayer player, MovingObjectPosition movingObjectPositionIn, int partialTicks, - float parFloat1) { - if (partialTicks == 0 && movingObjectPositionIn != null - && movingObjectPositionIn.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.color(0.0F, 0.0F, 0.0F, 0.4F); - EaglercraftGPU.glLineWidth(2.0F); - GlStateManager.disableTexture2D(); - GlStateManager.depthMask(false); - float f = 0.002F; - BlockPos blockpos = movingObjectPositionIn.getBlockPos(); - Block block = this.theWorld.getBlockState(blockpos).getBlock(); - if (block.getMaterial() != Material.air && this.theWorld.getWorldBorder().contains(blockpos)) { - block.setBlockBoundsBasedOnState(this.theWorld, blockpos); - double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double) parFloat1; - double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double) parFloat1; - double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double) parFloat1; - func_181561_a(block.getSelectedBoundingBox(this.theWorld, blockpos) - .expand(0.0020000000949949026D, 0.0020000000949949026D, 0.0020000000949949026D) - .offset(-d0, -d1, -d2)); - } - - GlStateManager.depthMask(true); - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - } - - } - - public static void func_181561_a(AxisAlignedBB parAxisAlignedBB) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(3, DefaultVertexFormats.POSITION); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); - tessellator.draw(); - worldrenderer.begin(3, DefaultVertexFormats.POSITION); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); - tessellator.draw(); - worldrenderer.begin(1, DefaultVertexFormats.POSITION); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ).endVertex(); - tessellator.draw(); - } - - public static void func_181563_a(AxisAlignedBB parAxisAlignedBB, int parInt1, int parInt2, int parInt3, - int parInt4) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(3, DefaultVertexFormats.POSITION_COLOR); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - tessellator.draw(); - worldrenderer.begin(3, DefaultVertexFormats.POSITION_COLOR); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - tessellator.draw(); - worldrenderer.begin(1, DefaultVertexFormats.POSITION_COLOR); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.minZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.maxX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.minY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - worldrenderer.pos(parAxisAlignedBB.minX, parAxisAlignedBB.maxY, parAxisAlignedBB.maxZ) - .color(parInt1, parInt2, parInt3, parInt4).endVertex(); - tessellator.draw(); - } - - /**+ - * Marks the blocks in the given range for update - */ - private void markBlocksForUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { - this.viewFrustum.markBlocksForUpdate(x1, y1, z1, x2, y2, z2); - } - - public void markBlockForUpdate(BlockPos blockpos) { - int i = blockpos.getX(); - int j = blockpos.getY(); - int k = blockpos.getZ(); - this.markBlocksForUpdate(i - 1, j - 1, k - 1, i + 1, j + 1, k + 1); - } - - public void notifyLightSet(BlockPos blockpos) { - int i = blockpos.getX(); - int j = blockpos.getY(); - int k = blockpos.getZ(); - this.markBlocksForUpdate(i - 1, j - 1, k - 1, i + 1, j + 1, k + 1); - } - - /**+ - * On the client, re-renders all blocks in this range, - * inclusive. On the server, does nothing. Args: min x, min y, - * min z, max x, max y, max z - */ - public void markBlockRangeForRenderUpdate(int i, int j, int k, int l, int i1, int j1) { - this.markBlocksForUpdate(i - 1, j - 1, k - 1, l + 1, i1 + 1, j1 + 1); - } - - public void playRecord(String s, BlockPos blockpos) { - ISound isound = (ISound) this.mapSoundPositions.get(blockpos); - if (isound != null) { - this.mc.getSoundHandler().stopSound(isound); - this.mapSoundPositions.remove(blockpos); - } - - if (s != null) { - ItemRecord itemrecord = ItemRecord.getRecord(s); - if (itemrecord != null) { - this.mc.ingameGUI.setRecordPlayingMessage(itemrecord.getRecordNameLocal()); - } - - PositionedSoundRecord positionedsoundrecord = PositionedSoundRecord.create(new ResourceLocation(s), - (float) blockpos.getX(), (float) blockpos.getY(), (float) blockpos.getZ()); - this.mapSoundPositions.put(blockpos, positionedsoundrecord); - this.mc.getSoundHandler().playSound(positionedsoundrecord); - } - - } - - /**+ - * Plays the specified sound. Arg: soundName, x, y, z, volume, - * pitch - */ - public void playSound(String var1, double var2, double var4, double var6, float var8, float var9) { - } - - /**+ - * Plays sound to all near players except the player reference - * given - */ - public void playSoundToNearExcept(EntityPlayer var1, String var2, double var3, double var5, double var7, float var9, - float var10) { - } - - public void spawnParticle(int i, boolean flag, final double d0, final double d1, final double d2, double d3, - double d4, double d5, int... aint) { - try { - this.spawnEntityFX(i, flag, d0, d1, d2, d3, d4, d5, aint); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while adding particle"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Particle being added"); - crashreportcategory.addCrashSection("ID", Integer.valueOf(i)); - if (aint != null) { - crashreportcategory.addCrashSection("Parameters", aint); - } - - crashreportcategory.addCrashSectionCallable("Position", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo(d0, d1, d2); + while (!linkedlist.isEmpty()) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation1 = (RenderGlobal.ContainerLocalRenderInformation) linkedlist + .poll(); + RenderChunk renderchunk3 = renderglobal$containerlocalrenderinformation1.renderChunk; + EnumFacing enumfacing2 = renderglobal$containerlocalrenderinformation1.facing; + BlockPos blockpos2 = renderchunk3.getPosition(); + this.renderInfos.add(renderglobal$containerlocalrenderinformation1); + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing1 = facings[i]; + RenderChunk renderchunk2 = this.func_181562_a(blockpos, renderchunk3, enumfacing1); + if ((!flag1 || !renderglobal$containerlocalrenderinformation1.setFacing // TODO: + .contains(enumfacing1.getOpposite())) + && (!flag1 || enumfacing2 == null + || renderchunk3.getCompiledChunk().isVisible(enumfacing2.getOpposite(), + enumfacing1)) + && renderchunk2 != null && renderchunk2.setFrameIndex(frameCount) + && ((ICamera) camera).isBoundingBoxInFrustum(renderchunk2.boundingBox)) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = new RenderGlobal.ContainerLocalRenderInformation( + renderchunk2, enumfacing1, renderglobal$containerlocalrenderinformation1.counter + 1); + renderglobal$containerlocalrenderinformation.setFacing + .addAll(renderglobal$containerlocalrenderinformation1.setFacing); + renderglobal$containerlocalrenderinformation.setFacing.add(enumfacing1); + linkedlist.add(renderglobal$containerlocalrenderinformation); + } } - }); - throw new ReportedException(crashreport); + } } + + if (this.debugFixTerrainFrustum) { + this.fixTerrainFrustum(d3, d4, d5); + this.debugFixTerrainFrustum = false; + } + + Set set = this.chunksToUpdate; + this.chunksToUpdate = Sets.newLinkedHashSet(); + + for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { + RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation2 = this.renderInfos + .get(ii); + RenderChunk renderchunk4 = renderglobal$containerlocalrenderinformation2.renderChunk; + if (renderchunk4.isNeedsUpdate() || set.contains(renderchunk4)) { + this.displayListEntitiesDirty = true; + if (this.mc.gameSettings.chunkFix ? this.isPositionInRenderChunkHack(blockpos1, renderchunk4) + : this.isPositionInRenderChunk(blockpos, renderchunk4)) { + this.renderDispatcher.updateChunkNow(renderchunk4); + renderchunk4.setNeedsUpdate(false); + } else { + this.chunksToUpdate.add(renderchunk4); + } + } + } + + this.chunksToUpdate.addAll(set); } - private void spawnParticle(EnumParticleTypes particleIn, double parDouble1, double parDouble2, double parDouble3, - double parDouble4, double parDouble5, double parDouble6, int... parArrayOfInt) { - this.spawnParticle(particleIn.getParticleID(), particleIn.getShouldIgnoreRange(), parDouble1, parDouble2, - parDouble3, parDouble4, parDouble5, parDouble6, parArrayOfInt); + /** + * + set null to clear + */ + public void setWorldAndLoadRenderers(WorldClient worldClientIn) { + if (this.theWorld != null) { + this.theWorld.removeWorldAccess(this); + } + + this.frustumUpdatePosX = Double.MIN_VALUE; + this.frustumUpdatePosY = Double.MIN_VALUE; + this.frustumUpdatePosZ = Double.MIN_VALUE; + this.frustumUpdatePosChunkX = Integer.MIN_VALUE; + this.frustumUpdatePosChunkY = Integer.MIN_VALUE; + this.frustumUpdatePosChunkZ = Integer.MIN_VALUE; + this.renderManager.set(worldClientIn); + this.theWorld = worldClientIn; + if (worldClientIn != null) { + worldClientIn.addWorldAccess(this); + this.loadRenderers(); + } + } private EntityFX spawnEntityFX(int ignoreRange, boolean parFlag, double parDouble1, double parDouble2, @@ -2205,306 +2452,73 @@ public class RenderGlobal implements IWorldAccess, IResourceManagerReloadListene } } - /**+ - * Called on all IWorldAccesses when an entity is created or - * loaded. On client worlds, starts downloading any necessary - * textures. On server worlds, adds the entity to the entity - * tracker. - */ - public void onEntityAdded(Entity var1) { + private void spawnParticle(EnumParticleTypes particleIn, double parDouble1, double parDouble2, double parDouble3, + double parDouble4, double parDouble5, double parDouble6, int... parArrayOfInt) { + this.spawnParticle(particleIn.getParticleID(), particleIn.getShouldIgnoreRange(), parDouble1, parDouble2, + parDouble3, parDouble4, parDouble5, parDouble6, parArrayOfInt); } - /**+ - * Called on all IWorldAccesses when an entity is unloaded or - * destroyed. On client worlds, releases any downloaded - * textures. On server worlds, removes the entity from the - * entity tracker. - */ - public void onEntityRemoved(Entity var1) { + public void spawnParticle(int i, boolean flag, final double d0, final double d1, final double d2, double d3, + double d4, double d5, int... aint) { + try { + this.spawnEntityFX(i, flag, d0, d1, d2, d3, d4, d5, aint); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while adding particle"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Particle being added"); + crashreportcategory.addCrashSection("ID", Integer.valueOf(i)); + if (aint != null) { + crashreportcategory.addCrashSection("Parameters", aint); + } + + crashreportcategory.addCrashSectionCallable("Position", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo(d0, d1, d2); + } + }); + throw new ReportedException(crashreport); + } } - /**+ - * Deletes all display lists - */ - public void deleteAllDisplayLists() { + protected void stopChunkUpdates() { + this.chunksToUpdate.clear(); + this.renderDispatcher.stopChunkUpdates(); } - public void broadcastSound(int i, BlockPos blockpos, int var3) { - switch (i) { - case 1013: - case 1018: - if (this.mc.getRenderViewEntity() != null) { - double d0 = (double) blockpos.getX() - this.mc.getRenderViewEntity().posX; - double d1 = (double) blockpos.getY() - this.mc.getRenderViewEntity().posY; - double d2 = (double) blockpos.getZ() - this.mc.getRenderViewEntity().posZ; - double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - double d4 = this.mc.getRenderViewEntity().posX; - double d5 = this.mc.getRenderViewEntity().posY; - double d6 = this.mc.getRenderViewEntity().posZ; - if (d3 > 0.0D) { - d4 += d0 / d3 * 2.0D; - d5 += d1 / d3 * 2.0D; - d6 += d2 / d3 * 2.0D; + public void updateChunks(long finishTimeNano) { + this.displayListEntitiesDirty |= this.renderDispatcher.updateChunks(finishTimeNano); + if (!this.chunksToUpdate.isEmpty()) { + Iterator iterator = this.chunksToUpdate.iterator(); + + while (iterator.hasNext()) { + RenderChunk renderchunk = (RenderChunk) iterator.next(); + if (!this.renderDispatcher.updateChunkLater(renderchunk)) { + break; } - if (i == 1013) { - this.theWorld.playSound(d4, d5, d6, "mob.wither.spawn", 1.0F, 1.0F, false); - } else { - this.theWorld.playSound(d4, d5, d6, "mob.enderdragon.end", 5.0F, 1.0F, false); + renderchunk.setNeedsUpdate(false); + iterator.remove(); + long i = finishTimeNano - EagRuntime.nanoTime(); + if (i < 0L) { + break; } } - default: } } - public void playAuxSFX(EntityPlayer var1, int i, BlockPos blockpos, int j) { - EaglercraftRandom random = this.theWorld.rand; - switch (i) { - case 1000: - this.theWorld.playSoundAtPos(blockpos, "random.click", 1.0F, 1.0F, false); - break; - case 1001: - this.theWorld.playSoundAtPos(blockpos, "random.click", 1.0F, 1.2F, false); - break; - case 1002: - this.theWorld.playSoundAtPos(blockpos, "random.bow", 1.0F, 1.2F, false); - break; - case 1003: - this.theWorld.playSoundAtPos(blockpos, "random.door_open", 1.0F, - this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); - break; - case 1004: - this.theWorld.playSoundAtPos(blockpos, "random.fizz", 0.5F, - 2.6F + (random.nextFloat() - random.nextFloat()) * 0.8F, false); - break; - case 1005: - if (Item.getItemById(j) instanceof ItemRecord) { - this.theWorld.playRecord(blockpos, "records." + ((ItemRecord) Item.getItemById(j)).recordName); - } else { - this.theWorld.playRecord(blockpos, (String) null); - } - break; - case 1006: - this.theWorld.playSoundAtPos(blockpos, "random.door_close", 1.0F, - this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); - break; - case 1007: - this.theWorld.playSoundAtPos(blockpos, "mob.ghast.charge", 10.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1008: - this.theWorld.playSoundAtPos(blockpos, "mob.ghast.fireball", 10.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1009: - this.theWorld.playSoundAtPos(blockpos, "mob.ghast.fireball", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1010: - this.theWorld.playSoundAtPos(blockpos, "mob.zombie.wood", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1011: - this.theWorld.playSoundAtPos(blockpos, "mob.zombie.metal", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1012: - this.theWorld.playSoundAtPos(blockpos, "mob.zombie.woodbreak", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1014: - this.theWorld.playSoundAtPos(blockpos, "mob.wither.shoot", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1015: - this.theWorld.playSoundAtPos(blockpos, "mob.bat.takeoff", 0.05F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1016: - this.theWorld.playSoundAtPos(blockpos, "mob.zombie.infect", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1017: - this.theWorld.playSoundAtPos(blockpos, "mob.zombie.unfect", 2.0F, - (random.nextFloat() - random.nextFloat()) * 0.2F + 1.0F, false); - break; - case 1020: - this.theWorld.playSoundAtPos(blockpos, "random.anvil_break", 1.0F, - this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); - break; - case 1021: - this.theWorld.playSoundAtPos(blockpos, "random.anvil_use", 1.0F, - this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); - break; - case 1022: - this.theWorld.playSoundAtPos(blockpos, "random.anvil_land", 0.3F, - this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); - break; - case 2000: - int j1 = j % 3 - 1; - int k = j / 3 % 3 - 1; - double d15 = (double) blockpos.getX() + (double) j1 * 0.6D + 0.5D; - double d17 = (double) blockpos.getY() + 0.5D; - double d19 = (double) blockpos.getZ() + (double) k * 0.6D + 0.5D; - - for (int i2 = 0; i2 < 10; ++i2) { - double d20 = random.nextDouble() * 0.2D + 0.01D; - double d21 = d15 + (double) j1 * 0.01D + (random.nextDouble() - 0.5D) * (double) k * 0.5D; - double d4 = d17 + (random.nextDouble() - 0.5D) * 0.5D; - double d6 = d19 + (double) k * 0.01D + (random.nextDouble() - 0.5D) * (double) j1 * 0.5D; - double d8 = (double) j1 * d20 + random.nextGaussian() * 0.01D; - double d10 = -0.03D + random.nextGaussian() * 0.01D; - double d12 = (double) k * d20 + random.nextGaussian() * 0.01D; - this.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d21, d4, d6, d8, d10, d12, new int[0]); - } - - return; - case 2001: - Block block = Block.getBlockById(j & 4095); - if (block.getMaterial() != Material.air) { - this.mc.getSoundHandler() - .playSound(new PositionedSoundRecord(new ResourceLocation(block.stepSound.getBreakSound()), - (block.stepSound.getVolume() + 1.0F) / 2.0F, block.stepSound.getFrequency() * 0.8F, - (float) blockpos.getX() + 0.5F, (float) blockpos.getY() + 0.5F, - (float) blockpos.getZ() + 0.5F)); - } - - this.mc.effectRenderer.addBlockDestroyEffects(blockpos, block.getStateFromMeta(j >> 12 & 255)); - break; - case 2002: - double d13 = (double) blockpos.getX(); - double d14 = (double) blockpos.getY(); - double d16 = (double) blockpos.getZ(); - - for (int k1 = 0; k1 < 8; ++k1) { - this.spawnParticle(EnumParticleTypes.ITEM_CRACK, d13, d14, d16, random.nextGaussian() * 0.15D, - random.nextDouble() * 0.2D, random.nextGaussian() * 0.15D, - new int[] { Item.getIdFromItem(Items.potionitem), j }); - } - - int l1 = Items.potionitem.getColorFromDamage(j); - float f = (float) (l1 >> 16 & 255) / 255.0F; - float f1 = (float) (l1 >> 8 & 255) / 255.0F; - float f2 = (float) (l1 >> 0 & 255) / 255.0F; - EnumParticleTypes enumparticletypes = EnumParticleTypes.SPELL; - if (Items.potionitem.isEffectInstant(j)) { - enumparticletypes = EnumParticleTypes.SPELL_INSTANT; - } - - for (int j2 = 0; j2 < 100; ++j2) { - double d22 = random.nextDouble() * 4.0D; - double d23 = random.nextDouble() * 3.141592653589793D * 2.0D; - double d24 = Math.cos(d23) * d22; - double d9 = 0.01D + random.nextDouble() * 0.5D; - double d11 = Math.sin(d23) * d22; - EntityFX entityfx = this.spawnEntityFX(enumparticletypes.getParticleID(), - enumparticletypes.getShouldIgnoreRange(), d13 + d24 * 0.1D, d14 + 0.3D, d16 + d11 * 0.1D, d24, - d9, d11, new int[0]); - if (entityfx != null) { - float f3 = 0.75F + random.nextFloat() * 0.25F; - entityfx.setRBGColorF(f * f3, f1 * f3, f2 * f3); - entityfx.multiplyVelocity((float) d22); - } - } - - this.theWorld.playSoundAtPos(blockpos, "game.potion.smash", 1.0F, - this.theWorld.rand.nextFloat() * 0.1F + 0.9F, false); - break; - case 2003: - double d0 = (double) blockpos.getX() + 0.5D; - double d1 = (double) blockpos.getY(); - double d2 = (double) blockpos.getZ() + 0.5D; - - for (int l = 0; l < 8; ++l) { - this.spawnParticle(EnumParticleTypes.ITEM_CRACK, d0, d1, d2, random.nextGaussian() * 0.15D, - random.nextDouble() * 0.2D, random.nextGaussian() * 0.15D, - new int[] { Item.getIdFromItem(Items.ender_eye) }); - } - - for (double d18 = 0.0D; d18 < 6.283185307179586D; d18 += 0.15707963267948966D) { - this.spawnParticle(EnumParticleTypes.PORTAL, d0 + Math.cos(d18) * 5.0D, d1 - 0.4D, - d2 + Math.sin(d18) * 5.0D, Math.cos(d18) * -5.0D, 0.0D, Math.sin(d18) * -5.0D, new int[0]); - this.spawnParticle(EnumParticleTypes.PORTAL, d0 + Math.cos(d18) * 5.0D, d1 - 0.4D, - d2 + Math.sin(d18) * 5.0D, Math.cos(d18) * -7.0D, 0.0D, Math.sin(d18) * -7.0D, new int[0]); - } - - return; - case 2004: - for (int i1 = 0; i1 < 20; ++i1) { - double d3 = (double) blockpos.getX() + 0.5D + ((double) this.theWorld.rand.nextFloat() - 0.5D) * 2.0D; - double d5 = (double) blockpos.getY() + 0.5D + ((double) this.theWorld.rand.nextFloat() - 0.5D) * 2.0D; - double d7 = (double) blockpos.getZ() + 0.5D + ((double) this.theWorld.rand.nextFloat() - 0.5D) * 2.0D; - this.theWorld.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d3, d5, d7, 0.0D, 0.0D, 0.0D, new int[0]); - this.theWorld.spawnParticle(EnumParticleTypes.FLAME, d3, d5, d7, 0.0D, 0.0D, 0.0D, new int[0]); - } - - return; - case 2005: - ItemDye.spawnBonemealParticles(this.theWorld, blockpos, j); + public void updateClouds() { + ++this.cloudTickCounter; + if (this.cloudTickCounter % 20 == 0) { + this.cleanupDamagedBlocks(this.damagedBlocks.values().iterator()); } } - public void sendBlockBreakProgress(int i, BlockPos blockpos, int j) { - if (j >= 0 && j < 10) { - DestroyBlockProgress destroyblockprogress = (DestroyBlockProgress) this.damagedBlocks - .get(Integer.valueOf(i)); - if (destroyblockprogress == null || destroyblockprogress.getPosition().getX() != blockpos.getX() - || destroyblockprogress.getPosition().getY() != blockpos.getY() - || destroyblockprogress.getPosition().getZ() != blockpos.getZ()) { - destroyblockprogress = new DestroyBlockProgress(i, blockpos); - this.damagedBlocks.put(Integer.valueOf(i), destroyblockprogress); - } + private void updateDestroyBlockIcons() { + TextureMap texturemap = this.mc.getTextureMapBlocks(); - destroyblockprogress.setPartialBlockDamage(j); - destroyblockprogress.setCloudUpdateTick(this.cloudTickCounter); - } else { - this.damagedBlocks.remove(Integer.valueOf(i)); + for (int i = 0; i < this.destroyBlockIcons.length; ++i) { + this.destroyBlockIcons[i] = texturemap.getAtlasSprite("minecraft:blocks/destroy_stage_" + i); } } - - public void setDisplayListEntitiesDirty() { - this.displayListEntitiesDirty = true; - } - - public void func_181023_a(Collection parCollection, Collection parCollection2) { - synchronized (this.field_181024_n) { - this.field_181024_n.removeAll(parCollection); - this.field_181024_n.addAll(parCollection2); - } - } - - class ContainerLocalRenderInformation { - final RenderChunk renderChunk; - final EnumFacing facing; - final Set setFacing; - final int counter; - - private ContainerLocalRenderInformation(RenderChunk renderChunkIn, EnumFacing facingIn, int counterIn) { - this.setFacing = EnumSet.noneOf(EnumFacing.class); - this.renderChunk = renderChunkIn; - this.facing = facingIn; - this.counter = counterIn; - } - } - - public String getDebugInfoShort() { - int i = this.viewFrustum.renderChunks.length; - int j = 0; - int k = 0; - - for (int ii = 0, ll = this.renderInfos.size(); ii < ll; ++ii) { - RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation = this.renderInfos - .get(ii); - CompiledChunk compiledchunk = renderglobal$containerlocalrenderinformation.renderChunk.compiledChunk; - if (compiledchunk != CompiledChunk.DUMMY && !compiledchunk.isEmpty()) { - ++j; - k += compiledchunk.getTileEntities().size(); - } - } - - return "" + Minecraft.getDebugFPS() + "fps | C: " + j + "/" + i + ", E: " + this.countEntitiesRendered + "+" + k - + ", " + renderDispatcher.getDebugInfo(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/RenderHelper.java b/src/game/java/net/minecraft/client/renderer/RenderHelper.java index da492635..3fb0ca8b 100644 --- a/src/game/java/net/minecraft/client/renderer/RenderHelper.java +++ b/src/game/java/net/minecraft/client/renderer/RenderHelper.java @@ -1,41 +1,43 @@ package net.minecraft.client.renderer; import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RenderHelper { - /**+ - * Float buffer used to set OpenGL material colors + /** + * + Float buffer used to set OpenGL material colors */ private static FloatBuffer colorBuffer = GLAllocation.createDirectFloatBuffer(16); private static final Vec3 LIGHT0_POS = (new Vec3(0.20000000298023224D, 1.0D, -0.699999988079071D)).normalize(); private static final Vec3 LIGHT1_POS = (new Vec3(-0.20000000298023224D, 1.0D, 0.699999988079071D)).normalize(); - /**+ - * Disables the OpenGL lighting properties enabled by + /** + * + Disables the OpenGL lighting properties enabled by * enableStandardItemLighting */ public static void disableStandardItemLighting() { @@ -47,9 +49,23 @@ public class RenderHelper { } } - /**+ - * Sets the OpenGL lighting properties to the values used when - * rendering blocks as items + /** + * + Sets OpenGL lighting for rendering blocks as items inside GUI screens (such + * as containers). + */ + public static void enableGUIStandardItemLighting() { + if (!DeferredStateManager.isInDeferredPass()) { + GlStateManager.pushMatrix(); + GlStateManager.rotate(-30.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(165.0F, 1.0F, 0.0F, 0.0F); + enableStandardItemLighting(); + GlStateManager.popMatrix(); + } + } + + /** + * + Sets the OpenGL lighting properties to the values used when rendering + * blocks as items */ public static void enableStandardItemLighting() { if (!DeferredStateManager.isInDeferredPass()) { @@ -61,22 +77,19 @@ public class RenderHelper { } } - /**+ - * Update and return colorBuffer with the RGBA values passed as - * arguments + /** + * + Update and return colorBuffer with the RGBA values passed as arguments */ private static FloatBuffer setColorBuffer(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { - /**+ - * Update and return colorBuffer with the RGBA values passed as - * arguments + /** + * + Update and return colorBuffer with the RGBA values passed as arguments */ return setColorBuffer((float) parDouble1, (float) parDouble2, (float) parDouble3, (float) parDouble4); } - /**+ - * Update and return colorBuffer with the RGBA values passed as - * arguments + /** + * + Update and return colorBuffer with the RGBA values passed as arguments */ private static FloatBuffer setColorBuffer(float parFloat1, float parFloat2, float parFloat3, float parFloat4) { colorBuffer.clear(); @@ -84,18 +97,4 @@ public class RenderHelper { colorBuffer.flip(); return colorBuffer; } - - /**+ - * Sets OpenGL lighting for rendering blocks as items inside GUI - * screens (such as containers). - */ - public static void enableGUIStandardItemLighting() { - if (!DeferredStateManager.isInDeferredPass()) { - GlStateManager.pushMatrix(); - GlStateManager.rotate(-30.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(165.0F, 1.0F, 0.0F, 0.0F); - enableStandardItemLighting(); - GlStateManager.popMatrix(); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/RenderList.java b/src/game/java/net/minecraft/client/renderer/RenderList.java index 089a816a..2f7e3d50 100644 --- a/src/game/java/net/minecraft/client/renderer/RenderList.java +++ b/src/game/java/net/minecraft/client/renderer/RenderList.java @@ -5,22 +5,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.renderer.chunk.ListedRenderChunk; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/StitcherException.java b/src/game/java/net/minecraft/client/renderer/StitcherException.java index 95381b54..938a4a43 100644 --- a/src/game/java/net/minecraft/client/renderer/StitcherException.java +++ b/src/game/java/net/minecraft/client/renderer/StitcherException.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer; import net.minecraft.client.renderer.texture.Stitcher; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/Tessellator.java b/src/game/java/net/minecraft/client/renderer/Tessellator.java index 2111ea97..876d9b3b 100644 --- a/src/game/java/net/minecraft/client/renderer/Tessellator.java +++ b/src/game/java/net/minecraft/client/renderer/Tessellator.java @@ -4,40 +4,40 @@ import net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.lax1dude.eaglercraft.v1_8.opengl.WorldVertexBufferUploader; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Tessellator { - private WorldRenderer worldRenderer; - private WorldVertexBufferUploader vboUploader = new WorldVertexBufferUploader(); - public static final int GL_TRIANGLES = RealOpenGLEnums.GL_TRIANGLES; public static final int GL_TRIANGLE_STRIP = RealOpenGLEnums.GL_TRIANGLE_STRIP; + public static final int GL_TRIANGLE_FAN = RealOpenGLEnums.GL_TRIANGLE_FAN; public static final int GL_QUADS = RealOpenGLEnums.GL_QUADS; public static final int GL_LINES = RealOpenGLEnums.GL_LINES; public static final int GL_LINE_STRIP = RealOpenGLEnums.GL_LINE_STRIP; public static final int GL_LINE_LOOP = RealOpenGLEnums.GL_LINE_LOOP; - - /**+ - * The static instance of the Tessellator. + /** + * + The static instance of the Tessellator. */ private static final Tessellator instance = new Tessellator(2097152); @@ -45,13 +45,17 @@ public class Tessellator { return instance; } + private WorldRenderer worldRenderer; + + private WorldVertexBufferUploader vboUploader = new WorldVertexBufferUploader(); + public Tessellator(int bufferSize) { this.worldRenderer = new WorldRenderer(bufferSize); } - /**+ - * Draws the data set up in this tessellator and resets the - * state to prepare for new drawing. + /** + * + Draws the data set up in this tessellator and resets the state to prepare + * for new drawing. */ public void draw() { this.worldRenderer.finishDrawing(); diff --git a/src/game/java/net/minecraft/client/renderer/ViewFrustum.java b/src/game/java/net/minecraft/client/renderer/ViewFrustum.java index 9871072a..359d94cb 100644 --- a/src/game/java/net/minecraft/client/renderer/ViewFrustum.java +++ b/src/game/java/net/minecraft/client/renderer/ViewFrustum.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -67,37 +70,6 @@ public class ViewFrustum { } - protected void setCountChunksXYZ(int renderDistanceChunks) { - int i = renderDistanceChunks * 2 + 1; - this.countChunksX = i; - this.countChunksY = 16; - this.countChunksZ = i; - } - - public void updateChunkPositions(double viewEntityX, double viewEntityZ) { - int i = MathHelper.floor_double(viewEntityX) - 8; - int j = MathHelper.floor_double(viewEntityZ) - 8; - int k = this.countChunksX * 16; - - for (int l = 0; l < this.countChunksX; ++l) { - int i1 = this.func_178157_a(i, k, l); - - for (int j1 = 0; j1 < this.countChunksZ; ++j1) { - int k1 = this.func_178157_a(j, k, j1); - - for (int l1 = 0; l1 < this.countChunksY; ++l1) { - int i2 = l1 * 16; - RenderChunk renderchunk = this.renderChunks[(j1 * this.countChunksY + l1) * this.countChunksX + l]; - BlockPos blockpos = new BlockPos(i1, i2, k1); - if (!blockpos.equals(renderchunk.getPosition())) { - renderchunk.setPosition(blockpos); - } - } - } - } - - } - private int func_178157_a(int parInt1, int parInt2, int parInt3) { int i = parInt3 * 16; int j = i - parInt1 + parInt2 / 2; @@ -108,6 +80,28 @@ public class ViewFrustum { return i - j / parInt2 * parInt2; } + protected RenderChunk getRenderChunk(BlockPos pos) { + int i = MathHelper.bucketInt(pos.getX(), 16); + int j = MathHelper.bucketInt(pos.getY(), 16); + int k = MathHelper.bucketInt(pos.getZ(), 16); + if (j >= 0 && j < this.countChunksY) { + i = i % this.countChunksX; + if (i < 0) { + i += this.countChunksX; + } + + k = k % this.countChunksZ; + if (k < 0) { + k += this.countChunksZ; + } + + int l = (k * this.countChunksY + j) * this.countChunksX + i; + return this.renderChunks[l]; + } else { + return null; + } + } + public void markBlocksForUpdate(int fromX, int fromY, int fromZ, int toX, int toY, int toZ) { int i = MathHelper.bucketInt(fromX, 16); int j = MathHelper.bucketInt(fromY, 16); @@ -143,25 +137,34 @@ public class ViewFrustum { } - protected RenderChunk getRenderChunk(BlockPos pos) { - int i = MathHelper.bucketInt(pos.getX(), 16); - int j = MathHelper.bucketInt(pos.getY(), 16); - int k = MathHelper.bucketInt(pos.getZ(), 16); - if (j >= 0 && j < this.countChunksY) { - i = i % this.countChunksX; - if (i < 0) { - i += this.countChunksX; - } + protected void setCountChunksXYZ(int renderDistanceChunks) { + int i = renderDistanceChunks * 2 + 1; + this.countChunksX = i; + this.countChunksY = 16; + this.countChunksZ = i; + } - k = k % this.countChunksZ; - if (k < 0) { - k += this.countChunksZ; - } + public void updateChunkPositions(double viewEntityX, double viewEntityZ) { + int i = MathHelper.floor_double(viewEntityX) - 8; + int j = MathHelper.floor_double(viewEntityZ) - 8; + int k = this.countChunksX * 16; - int l = (k * this.countChunksY + j) * this.countChunksX + i; - return this.renderChunks[l]; - } else { - return null; + for (int l = 0; l < this.countChunksX; ++l) { + int i1 = this.func_178157_a(i, k, l); + + for (int j1 = 0; j1 < this.countChunksZ; ++j1) { + int k1 = this.func_178157_a(j, k, j1); + + for (int l1 = 0; l1 < this.countChunksY; ++l1) { + int i2 = l1 * 16; + RenderChunk renderchunk = this.renderChunks[(j1 * this.countChunksY + l1) * this.countChunksX + l]; + BlockPos blockpos = new BlockPos(i1, i2, k1); + if (!blockpos.equals(renderchunk.getPosition())) { + renderchunk.setPosition(blockpos); + } + } + } } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/BakedQuad.java b/src/game/java/net/minecraft/client/renderer/block/model/BakedQuad.java index ec2d02e5..0558dcea 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/BakedQuad.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/BakedQuad.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer.block.model; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,6 +45,14 @@ public class BakedQuad { this.face = faceIn; } + public EnumFacing getFace() { + return this.face; + } + + public int getTintIndex() { + return this.tintIndex; + } + public int[] getVertexData() { return this.vertexData; } @@ -53,12 +64,4 @@ public class BakedQuad { public boolean hasTintIndex() { return this.tintIndex != -1; } - - public int getTintIndex() { - return this.tintIndex; - } - - public EnumFacing getFace() { - return this.face; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/BlockFaceUV.java b/src/game/java/net/minecraft/client/renderer/block/model/BlockFaceUV.java index 80476231..6b48103d 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/BlockFaceUV.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/BlockFaceUV.java @@ -6,68 +6,30 @@ import org.json.JSONObject; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeDeserializer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockFaceUV { - public float[] uvs; - public final int rotation; - - public BlockFaceUV(float[] uvsIn, int rotationIn) { - this.uvs = uvsIn; - this.rotation = rotationIn; - } - - public float func_178348_a(int parInt1) { - if (this.uvs == null) { - throw new NullPointerException("uvs"); - } else { - int i = this.func_178347_d(parInt1); - return i != 0 && i != 1 ? this.uvs[2] : this.uvs[0]; - } - } - - public float func_178346_b(int parInt1) { - if (this.uvs == null) { - throw new NullPointerException("uvs"); - } else { - int i = this.func_178347_d(parInt1); - return i != 0 && i != 3 ? this.uvs[3] : this.uvs[1]; - } - } - - private int func_178347_d(int parInt1) { - return (parInt1 + this.rotation / 90) % 4; - } - - public int func_178345_c(int parInt1) { - return (parInt1 + (4 - this.rotation / 90)) % 4; - } - - public void setUvs(float[] uvsIn) { - if (this.uvs == null) { - this.uvs = uvsIn; - } - - } - public static class Deserializer implements JSONTypeDeserializer { public BlockFaceUV deserialize(JSONObject jsonobject) throws JSONException { float[] afloat = this.parseUV(jsonobject); @@ -103,4 +65,46 @@ public class BlockFaceUV { } } } + + public float[] uvs; + + public final int rotation; + + public BlockFaceUV(float[] uvsIn, int rotationIn) { + this.uvs = uvsIn; + this.rotation = rotationIn; + } + + public int func_178345_c(int parInt1) { + return (parInt1 + (4 - this.rotation / 90)) % 4; + } + + public float func_178346_b(int parInt1) { + if (this.uvs == null) { + throw new NullPointerException("uvs"); + } else { + int i = this.func_178347_d(parInt1); + return i != 0 && i != 3 ? this.uvs[3] : this.uvs[1]; + } + } + + private int func_178347_d(int parInt1) { + return (parInt1 + this.rotation / 90) % 4; + } + + public float func_178348_a(int parInt1) { + if (this.uvs == null) { + throw new NullPointerException("uvs"); + } else { + int i = this.func_178347_d(parInt1); + return i != 0 && i != 1 ? this.uvs[2] : this.uvs[0]; + } + } + + public void setUvs(float[] uvsIn) { + if (this.uvs == null) { + this.uvs = uvsIn; + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/BlockPart.java b/src/game/java/net/minecraft/client/renderer/block/model/BlockPart.java index acc47043..90f7f836 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/BlockPart.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/BlockPart.java @@ -16,31 +16,150 @@ import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPart { + public static class Deserializer implements JSONTypeDeserializer { + public BlockPart deserialize(JSONObject jsonobject) throws JSONException { + Vector3f vector3f = this.parsePositionFrom(jsonobject); + Vector3f vector3f1 = this.parsePositionTo(jsonobject); + BlockPartRotation blockpartrotation = this.parseRotation(jsonobject); + Map map = this.parseFacesCheck(jsonobject); + if (jsonobject.has("shade") && !(jsonobject.get("shade") instanceof Boolean)) { + throw new JSONException("Expected shade to be a Boolean"); + } else { + boolean flag = jsonobject.optBoolean("shade", true); + return new BlockPart(vector3f, vector3f1, map, blockpartrotation, flag); + } + } + + private float parseAngle(JSONObject parJsonObject) { + float f = parJsonObject.getFloat("angle"); + if (f != 0.0F && MathHelper.abs(f) != 22.5F && MathHelper.abs(f) != 45.0F) { + throw new JSONException("Invalid rotation " + f + " found, only -45/-22.5/0/22.5/45 allowed"); + } else { + return f; + } + } + + private EnumFacing.Axis parseAxis(JSONObject parJsonObject) { + String s = parJsonObject.getString("axis"); + EnumFacing.Axis enumfacing$axis = EnumFacing.Axis.byName(s.toLowerCase()); + if (enumfacing$axis == null) { + throw new JSONException("Invalid rotation axis: " + s); + } else { + return enumfacing$axis; + } + } + + private EnumFacing parseEnumFacing(String name) { + EnumFacing enumfacing = EnumFacing.byName(name); + if (enumfacing == null) { + throw new JSONException("Unknown facing: " + name); + } else { + return enumfacing; + } + } + + private Map parseFaces(JSONObject parJsonObject) { + EnumMap enummap = Maps.newEnumMap(EnumFacing.class); + JSONObject jsonobject = parJsonObject.getJSONObject("faces"); + + for (String entry : jsonobject.keySet()) { + EnumFacing enumfacing = this.parseEnumFacing(entry); + enummap.put(enumfacing, + JSONTypeProvider.deserialize(jsonobject.getJSONObject(entry), BlockPartFace.class)); + } + + return enummap; + } + + private Map parseFacesCheck(JSONObject parJsonObject) { + Map map = this.parseFaces(parJsonObject); + if (map.isEmpty()) { + throw new JSONException("Expected between 1 and 6 unique faces, got 0"); + } else { + return map; + } + } + + private Vector3f parsePosition(JSONObject parJsonObject, String parString1) { + JSONArray jsonarray = parJsonObject.getJSONArray(parString1); + if (jsonarray.length() != 3) { + throw new JSONException("Expected 3 " + parString1 + " values, found: " + jsonarray.length()); + } else { + float[] afloat = new float[3]; + + for (int i = 0; i < afloat.length; ++i) { + afloat[i] = jsonarray.getFloat(i); + } + + return new Vector3f(afloat[0], afloat[1], afloat[2]); + } + } + + private Vector3f parsePositionFrom(JSONObject parJsonObject) { + Vector3f vector3f = this.parsePosition(parJsonObject, "from"); + if (vector3f.x >= -16.0F && vector3f.y >= -16.0F && vector3f.z >= -16.0F && vector3f.x <= 32.0F + && vector3f.y <= 32.0F && vector3f.z <= 32.0F) { + return vector3f; + } else { + throw new JSONException("\'from\' specifier exceeds the allowed boundaries: " + vector3f); + } + } + + private Vector3f parsePositionTo(JSONObject parJsonObject) { + Vector3f vector3f = this.parsePosition(parJsonObject, "to"); + if (vector3f.x >= -16.0F && vector3f.y >= -16.0F && vector3f.z >= -16.0F && vector3f.x <= 32.0F + && vector3f.y <= 32.0F && vector3f.z <= 32.0F) { + return vector3f; + } else { + throw new JSONException("\'to\' specifier exceeds the allowed boundaries: " + vector3f); + } + } + + private BlockPartRotation parseRotation(JSONObject parJsonObject) { + BlockPartRotation blockpartrotation = null; + if (parJsonObject.has("rotation")) { + JSONObject jsonobject = parJsonObject.getJSONObject("rotation"); + Vector3f vector3f = this.parsePosition(jsonobject, "origin"); + vector3f.scale(0.0625F); + EnumFacing.Axis enumfacing$axis = this.parseAxis(jsonobject); + float f = this.parseAngle(jsonobject); + boolean flag = jsonobject.optBoolean("rescale", false); + blockpartrotation = new BlockPartRotation(vector3f, enumfacing$axis, f, flag); + } + + return blockpartrotation; + } + } + public final Vector3f positionFrom; public final Vector3f positionTo; public final Map mapFaces; public final BlockPartRotation partRotation; + public final boolean shade; public BlockPart(Vector3f positionFromIn, Vector3f positionToIn, Map mapFacesIn, @@ -53,14 +172,6 @@ public class BlockPart { this.setDefaultUvs(); } - private void setDefaultUvs() { - for (Entry entry : this.mapFaces.entrySet()) { - float[] afloat = this.getFaceUvs((EnumFacing) entry.getKey()); - ((BlockPartFace) entry.getValue()).blockFaceUV.setUvs(afloat); - } - - } - private float[] getFaceUvs(EnumFacing parEnumFacing) { float[] afloat; switch (parEnumFacing) { @@ -85,118 +196,11 @@ public class BlockPart { return afloat; } - public static class Deserializer implements JSONTypeDeserializer { - public BlockPart deserialize(JSONObject jsonobject) throws JSONException { - Vector3f vector3f = this.parsePositionFrom(jsonobject); - Vector3f vector3f1 = this.parsePositionTo(jsonobject); - BlockPartRotation blockpartrotation = this.parseRotation(jsonobject); - Map map = this.parseFacesCheck(jsonobject); - if (jsonobject.has("shade") && !(jsonobject.get("shade") instanceof Boolean)) { - throw new JSONException("Expected shade to be a Boolean"); - } else { - boolean flag = jsonobject.optBoolean("shade", true); - return new BlockPart(vector3f, vector3f1, map, blockpartrotation, flag); - } + private void setDefaultUvs() { + for (Entry entry : this.mapFaces.entrySet()) { + float[] afloat = this.getFaceUvs((EnumFacing) entry.getKey()); + ((BlockPartFace) entry.getValue()).blockFaceUV.setUvs(afloat); } - private BlockPartRotation parseRotation(JSONObject parJsonObject) { - BlockPartRotation blockpartrotation = null; - if (parJsonObject.has("rotation")) { - JSONObject jsonobject = parJsonObject.getJSONObject("rotation"); - Vector3f vector3f = this.parsePosition(jsonobject, "origin"); - vector3f.scale(0.0625F); - EnumFacing.Axis enumfacing$axis = this.parseAxis(jsonobject); - float f = this.parseAngle(jsonobject); - boolean flag = jsonobject.optBoolean("rescale", false); - blockpartrotation = new BlockPartRotation(vector3f, enumfacing$axis, f, flag); - } - - return blockpartrotation; - } - - private float parseAngle(JSONObject parJsonObject) { - float f = parJsonObject.getFloat("angle"); - if (f != 0.0F && MathHelper.abs(f) != 22.5F && MathHelper.abs(f) != 45.0F) { - throw new JSONException("Invalid rotation " + f + " found, only -45/-22.5/0/22.5/45 allowed"); - } else { - return f; - } - } - - private EnumFacing.Axis parseAxis(JSONObject parJsonObject) { - String s = parJsonObject.getString("axis"); - EnumFacing.Axis enumfacing$axis = EnumFacing.Axis.byName(s.toLowerCase()); - if (enumfacing$axis == null) { - throw new JSONException("Invalid rotation axis: " + s); - } else { - return enumfacing$axis; - } - } - - private Map parseFacesCheck(JSONObject parJsonObject) { - Map map = this.parseFaces(parJsonObject); - if (map.isEmpty()) { - throw new JSONException("Expected between 1 and 6 unique faces, got 0"); - } else { - return map; - } - } - - private Map parseFaces(JSONObject parJsonObject) { - EnumMap enummap = Maps.newEnumMap(EnumFacing.class); - JSONObject jsonobject = parJsonObject.getJSONObject("faces"); - - for (String entry : jsonobject.keySet()) { - EnumFacing enumfacing = this.parseEnumFacing(entry); - enummap.put(enumfacing, - JSONTypeProvider.deserialize(jsonobject.getJSONObject(entry), BlockPartFace.class)); - } - - return enummap; - } - - private EnumFacing parseEnumFacing(String name) { - EnumFacing enumfacing = EnumFacing.byName(name); - if (enumfacing == null) { - throw new JSONException("Unknown facing: " + name); - } else { - return enumfacing; - } - } - - private Vector3f parsePositionTo(JSONObject parJsonObject) { - Vector3f vector3f = this.parsePosition(parJsonObject, "to"); - if (vector3f.x >= -16.0F && vector3f.y >= -16.0F && vector3f.z >= -16.0F && vector3f.x <= 32.0F - && vector3f.y <= 32.0F && vector3f.z <= 32.0F) { - return vector3f; - } else { - throw new JSONException("\'to\' specifier exceeds the allowed boundaries: " + vector3f); - } - } - - private Vector3f parsePositionFrom(JSONObject parJsonObject) { - Vector3f vector3f = this.parsePosition(parJsonObject, "from"); - if (vector3f.x >= -16.0F && vector3f.y >= -16.0F && vector3f.z >= -16.0F && vector3f.x <= 32.0F - && vector3f.y <= 32.0F && vector3f.z <= 32.0F) { - return vector3f; - } else { - throw new JSONException("\'from\' specifier exceeds the allowed boundaries: " + vector3f); - } - } - - private Vector3f parsePosition(JSONObject parJsonObject, String parString1) { - JSONArray jsonarray = parJsonObject.getJSONArray(parString1); - if (jsonarray.length() != 3) { - throw new JSONException("Expected 3 " + parString1 + " values, found: " + jsonarray.length()); - } else { - float[] afloat = new float[3]; - - for (int i = 0; i < afloat.length; ++i) { - afloat[i] = jsonarray.getFloat(i); - } - - return new Vector3f(afloat[0], afloat[1], afloat[2]); - } - } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/BlockPartFace.java b/src/game/java/net/minecraft/client/renderer/block/model/BlockPartFace.java index d07e7fe0..588a1415 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/BlockPartFace.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/BlockPartFace.java @@ -7,40 +7,30 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeDeserializer; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPartFace { - public static final EnumFacing FACING_DEFAULT = null; - public final EnumFacing cullFace; - public final int tintIndex; - public final String texture; - public final BlockFaceUV blockFaceUV; - - public BlockPartFace(EnumFacing cullFaceIn, int tintIndexIn, String textureIn, BlockFaceUV blockFaceUVIn) { - this.cullFace = cullFaceIn; - this.tintIndex = tintIndexIn; - this.texture = textureIn; - this.blockFaceUV = blockFaceUVIn; - } - public static class Deserializer implements JSONTypeDeserializer { public BlockPartFace deserialize(JSONObject jsonobject) throws JSONException { EnumFacing enumfacing = this.parseCullFace(jsonobject); @@ -50,17 +40,31 @@ public class BlockPartFace { return new BlockPartFace(enumfacing, i, s, blockfaceuv); } - protected int parseTintIndex(JSONObject parJsonObject) { - return parJsonObject.optInt("tintindex", -1); + private EnumFacing parseCullFace(JSONObject parJsonObject) { + String s = parJsonObject.optString("cullface", ""); + return EnumFacing.byName(s); } private String parseTexture(JSONObject parJsonObject) { return parJsonObject.getString("texture"); } - private EnumFacing parseCullFace(JSONObject parJsonObject) { - String s = parJsonObject.optString("cullface", ""); - return EnumFacing.byName(s); + protected int parseTintIndex(JSONObject parJsonObject) { + return parJsonObject.optInt("tintindex", -1); } } + + public static final EnumFacing FACING_DEFAULT = null; + public final EnumFacing cullFace; + public final int tintIndex; + public final String texture; + + public final BlockFaceUV blockFaceUV; + + public BlockPartFace(EnumFacing cullFaceIn, int tintIndexIn, String textureIn, BlockFaceUV blockFaceUVIn) { + this.cullFace = cullFaceIn; + this.tintIndex = tintIndexIn; + this.texture = textureIn; + this.blockFaceUV = blockFaceUVIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/BlockPartRotation.java b/src/game/java/net/minecraft/client/renderer/block/model/BlockPartRotation.java index 2d869907..373685e1 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/BlockPartRotation.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/BlockPartRotation.java @@ -3,22 +3,25 @@ package net.minecraft.client.renderer.block.model; import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/block/model/BreakingFour.java b/src/game/java/net/minecraft/client/renderer/block/model/BreakingFour.java index e7dc3057..fe1f4387 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/BreakingFour.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/BreakingFour.java @@ -4,22 +4,25 @@ import java.util.Arrays; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,13 +38,6 @@ public class BreakingFour extends BakedQuad { this.func_178217_e(); } - private void func_178217_e() { - for (int i = 0; i < 4; ++i) { - this.func_178216_a(i); - } - - } - private void func_178216_a(int parInt1) { int i = 7 * parInt1; float f = Float.intBitsToFloat(this.vertexData[i]); @@ -84,4 +80,11 @@ public class BreakingFour extends BakedQuad { } } + + private void func_178217_e() { + for (int i = 0; i < 4; ++i) { + this.func_178216_a(i); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/FaceBakery.java b/src/game/java/net/minecraft/client/renderer/block/model/FaceBakery.java index e7b0821f..39a2283c 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/FaceBakery.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/FaceBakery.java @@ -12,22 +12,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3i; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,86 +39,52 @@ public class FaceBakery { private static final float field_178418_a = 1.0F / (float) Math.cos(0.39269909262657166D) - 1.0F; private static final float field_178417_b = 1.0F / (float) Math.cos(0.7853981852531433D) - 1.0F; + public static EnumFacing getFacingFromVertexData(Vector3f normal) { + EnumFacing enumfacing = null; + float f1 = 0.0F; + + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing1 = facings[i]; + Vec3i vec3i = enumfacing1.getDirectionVec(); + Vector3f vector3f6 = new Vector3f((float) vec3i.getX(), (float) vec3i.getY(), (float) vec3i.getZ()); + float f2 = Vector3f.dot(normal, vector3f6); + if (f2 >= 0.0F && f2 > f1) { + f1 = f2; + enumfacing = enumfacing1; + } + } + + if (enumfacing == null) { + return EnumFacing.UP; + } else { + return enumfacing; + } + } + + public static Vector3f getNormalFromVertexData(int[] faceData) { + Vector3f vector3f = new Vector3f(Float.intBitsToFloat(faceData[0]), Float.intBitsToFloat(faceData[1]), + Float.intBitsToFloat(faceData[2])); + Vector3f vector3f1 = new Vector3f(Float.intBitsToFloat(faceData[7]), Float.intBitsToFloat(faceData[8]), + Float.intBitsToFloat(faceData[9])); + Vector3f vector3f2 = new Vector3f(Float.intBitsToFloat(faceData[14]), Float.intBitsToFloat(faceData[15]), + Float.intBitsToFloat(faceData[16])); + Vector3f vector3f3 = new Vector3f(); + Vector3f vector3f4 = new Vector3f(); + Vector3f vector3f5 = new Vector3f(); + Vector3f.sub(vector3f, vector3f1, vector3f3); + Vector3f.sub(vector3f2, vector3f1, vector3f4); + Vector3f.cross(vector3f4, vector3f3, vector3f5); + float f = (float) Math + .sqrt((double) (vector3f5.x * vector3f5.x + vector3f5.y * vector3f5.y + vector3f5.z * vector3f5.z)); + vector3f5.x /= f; + vector3f5.y /= f; + vector3f5.z /= f; + return vector3f5; + } + private int stride = 7; - public BakedQuad makeBakedQuad(Vector3f posFrom, Vector3f posTo, BlockPartFace face, - EaglerTextureAtlasSprite sprite, EnumFacing facing, ModelRotation modelRotationIn, - BlockPartRotation partRotation, boolean uvLocked, boolean shade) { - stride = 7; - int[] aint = this.makeQuadVertexData(face, sprite, facing, this.getPositionsDiv16(posFrom, posTo), - modelRotationIn, partRotation, uvLocked, shade, null); - Vector3f calcNormal = getNormalFromVertexData(aint); - EnumFacing enumfacing = getFacingFromVertexData(calcNormal); - if (uvLocked) { - this.func_178409_a(aint, enumfacing, face.blockFaceUV, sprite); - } - - if (partRotation == null) { - this.func_178408_a(aint, enumfacing); - } - - stride = 8; - int[] aint2 = this.makeQuadVertexData(face, sprite, facing, this.getPositionsDiv16(posFrom, posTo), - modelRotationIn, partRotation, uvLocked, shade, calcNormal); - if (uvLocked) { - this.func_178409_a(aint2, enumfacing, face.blockFaceUV, sprite); - } - - if (partRotation == null) { - this.func_178408_a(aint2, enumfacing); - } - stride = 7; - - return new BakedQuad(aint, aint2, face.tintIndex, enumfacing); - } - - private int[] makeQuadVertexData(BlockPartFace partFace, EaglerTextureAtlasSprite sprite, EnumFacing facing, - float[] modelRotationIn, ModelRotation partRotation, BlockPartRotation uvLocked, boolean shade, - boolean parFlag2, Vector3f calcNormal) { - int[] aint = new int[stride * 4]; - - for (int i = 0; i < 4; ++i) { - this.fillVertexData(aint, i, facing, partFace, modelRotationIn, sprite, partRotation, uvLocked, shade, - parFlag2, calcNormal); - } - - return aint; - } - - private int getFaceShadeColor(EnumFacing facing) { - float f = this.getFaceBrightness(facing); - int i = MathHelper.clamp_int((int) (f * 255.0F), 0, 255); - return -16777216 | i << 16 | i << 8 | i; - } - - private float getFaceBrightness(EnumFacing facing) { - switch (facing) { - case DOWN: - return 0.5F; - case UP: - return 1.0F; - case NORTH: - case SOUTH: - return 0.8F; - case WEST: - case EAST: - return 0.6F; - default: - return 1.0F; - } - } - - private float[] getPositionsDiv16(Vector3f pos1, Vector3f pos2) { - float[] afloat = new float[EnumFacing._VALUES.length]; - afloat[EnumFaceDirection.Constants.WEST_INDEX] = pos1.x / 16.0F; - afloat[EnumFaceDirection.Constants.DOWN_INDEX] = pos1.y / 16.0F; - afloat[EnumFaceDirection.Constants.NORTH_INDEX] = pos1.z / 16.0F; - afloat[EnumFaceDirection.Constants.EAST_INDEX] = pos2.x / 16.0F; - afloat[EnumFaceDirection.Constants.UP_INDEX] = pos2.y / 16.0F; - afloat[EnumFaceDirection.Constants.SOUTH_INDEX] = pos2.z / 16.0F; - return afloat; - } - private void fillVertexData(int[] faceData, int vertexIndex, EnumFacing facing, BlockPartFace partFace, float[] sprite, EaglerTextureAtlasSprite modelRotationIn, ModelRotation partRotation, BlockPartRotation uvLocked, boolean shade, boolean parFlag2, Vector3f calcNormal) { @@ -134,42 +103,55 @@ public class FaceBakery { calcNormal); } - private void storeVertexData(int[] faceData, int storeIndex, int vertexIndex, Vector3f position, int shadeColor, - EaglerTextureAtlasSprite sprite, BlockFaceUV faceUV, EnumFacing facing, Vector3f calcNormal) { - int i = storeIndex * stride; - faceData[i + 3] = shadeColor; - faceData[i + 4] = Float.floatToRawIntBits(sprite.getInterpolatedU((double) faceUV.func_178348_a(vertexIndex))); - faceData[i + 4 + 1] = Float - .floatToRawIntBits(sprite.getInterpolatedV((double) faceUV.func_178346_b(vertexIndex))); - if (stride == 8) { - if (!Minecraft.getMinecraft().gameSettings.shaders) { - faceData[i] = Float.floatToRawIntBits(position.x); - faceData[i + 1] = Float.floatToRawIntBits(position.y); - faceData[i + 2] = Float.floatToRawIntBits(position.z); - } else { - faceData[i] = Float.floatToRawIntBits(position.x * VertexMarkerState.localCoordDeriveHackX); - faceData[i + 1] = Float.floatToRawIntBits(position.y * VertexMarkerState.localCoordDeriveHackY); - faceData[i + 2] = Float.floatToRawIntBits(position.z * VertexMarkerState.localCoordDeriveHackZ); - } - if (calcNormal != null) { - int x = (byte) ((int) (calcNormal.x * 127.0F)) & 255; - int y = (byte) ((int) (calcNormal.y * 127.0F)) & 255; - int z = (byte) ((int) (calcNormal.z * 127.0F)) & 255; - int l = x | y << 8 | z << 16 | ((byte) VertexMarkerState.markId) << 24; - faceData[i + 6] = l; - } else { - Vec3i vec = facing.getDirectionVec(); - int x = (byte) ((int) (vec.x * 127.0F)) & 255; - int y = (byte) ((int) (vec.y * 127.0F)) & 255; - int z = (byte) ((int) (vec.z * 127.0F)) & 255; - int l = x | y << 8 | z << 16 | ((byte) VertexMarkerState.markId) << 24; - faceData[i + 6] = l; - } - } else { - faceData[i] = Float.floatToRawIntBits(position.x); - faceData[i + 1] = Float.floatToRawIntBits(position.y); - faceData[i + 2] = Float.floatToRawIntBits(position.z); + private void func_178401_a(int facing, int[] parArrayOfInt, EnumFacing parEnumFacing, BlockFaceUV parBlockFaceUV, + EaglerTextureAtlasSprite parTextureAtlasSprite) { + int i = stride * facing; + float f = Float.intBitsToFloat(parArrayOfInt[i]); + float f1 = Float.intBitsToFloat(parArrayOfInt[i + 1]); + float f2 = Float.intBitsToFloat(parArrayOfInt[i + 2]); + if (f < -0.1F || f >= 1.1F) { + f -= (float) MathHelper.floor_float(f); } + + if (f1 < -0.1F || f1 >= 1.1F) { + f1 -= (float) MathHelper.floor_float(f1); + } + + if (f2 < -0.1F || f2 >= 1.1F) { + f2 -= (float) MathHelper.floor_float(f2); + } + + float f3 = 0.0F; + float f4 = 0.0F; + switch (parEnumFacing) { + case DOWN: + f3 = f * 16.0F; + f4 = (1.0F - f2) * 16.0F; + break; + case UP: + f3 = f * 16.0F; + f4 = f2 * 16.0F; + break; + case NORTH: + f3 = (1.0F - f) * 16.0F; + f4 = (1.0F - f1) * 16.0F; + break; + case SOUTH: + f3 = f * 16.0F; + f4 = (1.0F - f1) * 16.0F; + break; + case WEST: + f3 = f2 * 16.0F; + f4 = (1.0F - f1) * 16.0F; + break; + case EAST: + f3 = (1.0F - f2) * 16.0F; + f4 = (1.0F - f1) * 16.0F; + } + + int j = parBlockFaceUV.func_178345_c(facing) * stride; + parArrayOfInt[j + 4] = Float.floatToRawIntBits(parTextureAtlasSprite.getInterpolatedU((double) f3)); + parArrayOfInt[j + 4 + 1] = Float.floatToRawIntBits(parTextureAtlasSprite.getInterpolatedV((double) f4)); } private void func_178407_a(Vector3f partRotation, BlockPartRotation parBlockPartRotation) { @@ -209,85 +191,6 @@ public class FaceBakery { } } - public int rotateVertex(Vector3f position, EnumFacing facing, int vertexIndex, ModelRotation modelRotationIn, - boolean uvLocked) { - if (modelRotationIn == ModelRotation.X0_Y0) { - return vertexIndex; - } else { - this.rotateScale(position, new Vector3f(0.5F, 0.5F, 0.5F), modelRotationIn.getMatrix4d(), - new Vector3f(1.0F, 1.0F, 1.0F)); - return modelRotationIn.rotateVertex(facing, vertexIndex); - } - } - - private void rotateScale(Vector3f position, Vector3f rotationOrigin, Matrix4f rotationMatrix, Vector3f scale) { - Vector4f vector4f = new Vector4f(position.x - rotationOrigin.x, position.y - rotationOrigin.y, - position.z - rotationOrigin.z, 1.0F); - Matrix4f.transform(rotationMatrix, vector4f, vector4f); - vector4f.x *= scale.x; - vector4f.y *= scale.y; - vector4f.z *= scale.z; - position.set(vector4f.x + rotationOrigin.x, vector4f.y + rotationOrigin.y, vector4f.z + rotationOrigin.z); - } - - private Matrix4f getMatrixIdentity() { - Matrix4f matrix4f = new Matrix4f(); - matrix4f.setIdentity(); - return matrix4f; - } - - public static Vector3f getNormalFromVertexData(int[] faceData) { - Vector3f vector3f = new Vector3f(Float.intBitsToFloat(faceData[0]), Float.intBitsToFloat(faceData[1]), - Float.intBitsToFloat(faceData[2])); - Vector3f vector3f1 = new Vector3f(Float.intBitsToFloat(faceData[7]), Float.intBitsToFloat(faceData[8]), - Float.intBitsToFloat(faceData[9])); - Vector3f vector3f2 = new Vector3f(Float.intBitsToFloat(faceData[14]), Float.intBitsToFloat(faceData[15]), - Float.intBitsToFloat(faceData[16])); - Vector3f vector3f3 = new Vector3f(); - Vector3f vector3f4 = new Vector3f(); - Vector3f vector3f5 = new Vector3f(); - Vector3f.sub(vector3f, vector3f1, vector3f3); - Vector3f.sub(vector3f2, vector3f1, vector3f4); - Vector3f.cross(vector3f4, vector3f3, vector3f5); - float f = (float) Math - .sqrt((double) (vector3f5.x * vector3f5.x + vector3f5.y * vector3f5.y + vector3f5.z * vector3f5.z)); - vector3f5.x /= f; - vector3f5.y /= f; - vector3f5.z /= f; - return vector3f5; - } - - public static EnumFacing getFacingFromVertexData(Vector3f normal) { - EnumFacing enumfacing = null; - float f1 = 0.0F; - - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing1 = facings[i]; - Vec3i vec3i = enumfacing1.getDirectionVec(); - Vector3f vector3f6 = new Vector3f((float) vec3i.getX(), (float) vec3i.getY(), (float) vec3i.getZ()); - float f2 = Vector3f.dot(normal, vector3f6); - if (f2 >= 0.0F && f2 > f1) { - f1 = f2; - enumfacing = enumfacing1; - } - } - - if (enumfacing == null) { - return EnumFacing.UP; - } else { - return enumfacing; - } - } - - public void func_178409_a(int[] facing, EnumFacing parEnumFacing, BlockFaceUV parBlockFaceUV, - EaglerTextureAtlasSprite parTextureAtlasSprite) { - for (int i = 0; i < 4; ++i) { - this.func_178401_a(i, facing, parEnumFacing, parBlockFaceUV, parTextureAtlasSprite); - } - - } - private void func_178408_a(int[] parArrayOfInt, EnumFacing parEnumFacing) { int[] aint = new int[parArrayOfInt.length]; System.arraycopy(parArrayOfInt, 0, aint, 0, parArrayOfInt.length); @@ -357,54 +260,154 @@ public class FaceBakery { } - private void func_178401_a(int facing, int[] parArrayOfInt, EnumFacing parEnumFacing, BlockFaceUV parBlockFaceUV, + public void func_178409_a(int[] facing, EnumFacing parEnumFacing, BlockFaceUV parBlockFaceUV, EaglerTextureAtlasSprite parTextureAtlasSprite) { - int i = stride * facing; - float f = Float.intBitsToFloat(parArrayOfInt[i]); - float f1 = Float.intBitsToFloat(parArrayOfInt[i + 1]); - float f2 = Float.intBitsToFloat(parArrayOfInt[i + 2]); - if (f < -0.1F || f >= 1.1F) { - f -= (float) MathHelper.floor_float(f); + for (int i = 0; i < 4; ++i) { + this.func_178401_a(i, facing, parEnumFacing, parBlockFaceUV, parTextureAtlasSprite); } - if (f1 < -0.1F || f1 >= 1.1F) { - f1 -= (float) MathHelper.floor_float(f1); - } + } - if (f2 < -0.1F || f2 >= 1.1F) { - f2 -= (float) MathHelper.floor_float(f2); - } - - float f3 = 0.0F; - float f4 = 0.0F; - switch (parEnumFacing) { + private float getFaceBrightness(EnumFacing facing) { + switch (facing) { case DOWN: - f3 = f * 16.0F; - f4 = (1.0F - f2) * 16.0F; - break; + return 0.5F; case UP: - f3 = f * 16.0F; - f4 = f2 * 16.0F; - break; + return 1.0F; case NORTH: - f3 = (1.0F - f) * 16.0F; - f4 = (1.0F - f1) * 16.0F; - break; case SOUTH: - f3 = f * 16.0F; - f4 = (1.0F - f1) * 16.0F; - break; + return 0.8F; case WEST: - f3 = f2 * 16.0F; - f4 = (1.0F - f1) * 16.0F; - break; case EAST: - f3 = (1.0F - f2) * 16.0F; - f4 = (1.0F - f1) * 16.0F; + return 0.6F; + default: + return 1.0F; + } + } + + private int getFaceShadeColor(EnumFacing facing) { + float f = this.getFaceBrightness(facing); + int i = MathHelper.clamp_int((int) (f * 255.0F), 0, 255); + return -16777216 | i << 16 | i << 8 | i; + } + + private Matrix4f getMatrixIdentity() { + Matrix4f matrix4f = new Matrix4f(); + matrix4f.setIdentity(); + return matrix4f; + } + + private float[] getPositionsDiv16(Vector3f pos1, Vector3f pos2) { + float[] afloat = new float[EnumFacing._VALUES.length]; + afloat[EnumFaceDirection.Constants.WEST_INDEX] = pos1.x / 16.0F; + afloat[EnumFaceDirection.Constants.DOWN_INDEX] = pos1.y / 16.0F; + afloat[EnumFaceDirection.Constants.NORTH_INDEX] = pos1.z / 16.0F; + afloat[EnumFaceDirection.Constants.EAST_INDEX] = pos2.x / 16.0F; + afloat[EnumFaceDirection.Constants.UP_INDEX] = pos2.y / 16.0F; + afloat[EnumFaceDirection.Constants.SOUTH_INDEX] = pos2.z / 16.0F; + return afloat; + } + + public BakedQuad makeBakedQuad(Vector3f posFrom, Vector3f posTo, BlockPartFace face, + EaglerTextureAtlasSprite sprite, EnumFacing facing, ModelRotation modelRotationIn, + BlockPartRotation partRotation, boolean uvLocked, boolean shade) { + stride = 7; + int[] aint = this.makeQuadVertexData(face, sprite, facing, this.getPositionsDiv16(posFrom, posTo), + modelRotationIn, partRotation, uvLocked, shade, null); + Vector3f calcNormal = getNormalFromVertexData(aint); + EnumFacing enumfacing = getFacingFromVertexData(calcNormal); + if (uvLocked) { + this.func_178409_a(aint, enumfacing, face.blockFaceUV, sprite); } - int j = parBlockFaceUV.func_178345_c(facing) * stride; - parArrayOfInt[j + 4] = Float.floatToRawIntBits(parTextureAtlasSprite.getInterpolatedU((double) f3)); - parArrayOfInt[j + 4 + 1] = Float.floatToRawIntBits(parTextureAtlasSprite.getInterpolatedV((double) f4)); + if (partRotation == null) { + this.func_178408_a(aint, enumfacing); + } + + stride = 8; + int[] aint2 = this.makeQuadVertexData(face, sprite, facing, this.getPositionsDiv16(posFrom, posTo), + modelRotationIn, partRotation, uvLocked, shade, calcNormal); + if (uvLocked) { + this.func_178409_a(aint2, enumfacing, face.blockFaceUV, sprite); + } + + if (partRotation == null) { + this.func_178408_a(aint2, enumfacing); + } + stride = 7; + + return new BakedQuad(aint, aint2, face.tintIndex, enumfacing); + } + + private int[] makeQuadVertexData(BlockPartFace partFace, EaglerTextureAtlasSprite sprite, EnumFacing facing, + float[] modelRotationIn, ModelRotation partRotation, BlockPartRotation uvLocked, boolean shade, + boolean parFlag2, Vector3f calcNormal) { + int[] aint = new int[stride * 4]; + + for (int i = 0; i < 4; ++i) { + this.fillVertexData(aint, i, facing, partFace, modelRotationIn, sprite, partRotation, uvLocked, shade, + parFlag2, calcNormal); + } + + return aint; + } + + private void rotateScale(Vector3f position, Vector3f rotationOrigin, Matrix4f rotationMatrix, Vector3f scale) { + Vector4f vector4f = new Vector4f(position.x - rotationOrigin.x, position.y - rotationOrigin.y, + position.z - rotationOrigin.z, 1.0F); + Matrix4f.transform(rotationMatrix, vector4f, vector4f); + vector4f.x *= scale.x; + vector4f.y *= scale.y; + vector4f.z *= scale.z; + position.set(vector4f.x + rotationOrigin.x, vector4f.y + rotationOrigin.y, vector4f.z + rotationOrigin.z); + } + + public int rotateVertex(Vector3f position, EnumFacing facing, int vertexIndex, ModelRotation modelRotationIn, + boolean uvLocked) { + if (modelRotationIn == ModelRotation.X0_Y0) { + return vertexIndex; + } else { + this.rotateScale(position, new Vector3f(0.5F, 0.5F, 0.5F), modelRotationIn.getMatrix4d(), + new Vector3f(1.0F, 1.0F, 1.0F)); + return modelRotationIn.rotateVertex(facing, vertexIndex); + } + } + + private void storeVertexData(int[] faceData, int storeIndex, int vertexIndex, Vector3f position, int shadeColor, + EaglerTextureAtlasSprite sprite, BlockFaceUV faceUV, EnumFacing facing, Vector3f calcNormal) { + int i = storeIndex * stride; + faceData[i + 3] = shadeColor; + faceData[i + 4] = Float.floatToRawIntBits(sprite.getInterpolatedU((double) faceUV.func_178348_a(vertexIndex))); + faceData[i + 4 + 1] = Float + .floatToRawIntBits(sprite.getInterpolatedV((double) faceUV.func_178346_b(vertexIndex))); + if (stride == 8) { + if (!Minecraft.getMinecraft().gameSettings.shaders) { + faceData[i] = Float.floatToRawIntBits(position.x); + faceData[i + 1] = Float.floatToRawIntBits(position.y); + faceData[i + 2] = Float.floatToRawIntBits(position.z); + } else { + faceData[i] = Float.floatToRawIntBits(position.x * VertexMarkerState.localCoordDeriveHackX); + faceData[i + 1] = Float.floatToRawIntBits(position.y * VertexMarkerState.localCoordDeriveHackY); + faceData[i + 2] = Float.floatToRawIntBits(position.z * VertexMarkerState.localCoordDeriveHackZ); + } + if (calcNormal != null) { + int x = (byte) ((int) (calcNormal.x * 127.0F)) & 255; + int y = (byte) ((int) (calcNormal.y * 127.0F)) & 255; + int z = (byte) ((int) (calcNormal.z * 127.0F)) & 255; + int l = x | y << 8 | z << 16 | ((byte) VertexMarkerState.markId) << 24; + faceData[i + 6] = l; + } else { + Vec3i vec = facing.getDirectionVec(); + int x = (byte) ((int) (vec.x * 127.0F)) & 255; + int y = (byte) ((int) (vec.y * 127.0F)) & 255; + int z = (byte) ((int) (vec.z * 127.0F)) & 255; + int l = x | y << 8 | z << 16 | ((byte) VertexMarkerState.markId) << 24; + faceData[i + 6] = l; + } + } else { + faceData[i] = Float.floatToRawIntBits(position.x); + faceData[i + 1] = Float.floatToRawIntBits(position.y); + faceData[i + 2] = Float.floatToRawIntBits(position.z); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/ItemCameraTransforms.java b/src/game/java/net/minecraft/client/renderer/block/model/ItemCameraTransforms.java index 78bb9a74..5aeb6477 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/ItemCameraTransforms.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/ItemCameraTransforms.java @@ -7,27 +7,53 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeDeserializer; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemCameraTransforms { + public static class Deserializer implements JSONTypeDeserializer { + public ItemCameraTransforms deserialize(JSONObject jsonobject) throws JSONException { + ItemTransformVec3f itemtransformvec3f = this.func_181683_a(jsonobject, "thirdperson"); + ItemTransformVec3f itemtransformvec3f1 = this.func_181683_a(jsonobject, "firstperson"); + ItemTransformVec3f itemtransformvec3f2 = this.func_181683_a(jsonobject, "head"); + ItemTransformVec3f itemtransformvec3f3 = this.func_181683_a(jsonobject, "gui"); + ItemTransformVec3f itemtransformvec3f4 = this.func_181683_a(jsonobject, "ground"); + ItemTransformVec3f itemtransformvec3f5 = this.func_181683_a(jsonobject, "fixed"); + return new ItemCameraTransforms(itemtransformvec3f, itemtransformvec3f1, itemtransformvec3f2, + itemtransformvec3f3, itemtransformvec3f4, itemtransformvec3f5); + } + + private ItemTransformVec3f func_181683_a(JSONObject parJsonObject, String parString1) { + return parJsonObject.has(parString1) + ? JSONTypeProvider.deserialize(parJsonObject.get(parString1), ItemTransformVec3f.class) + : ItemTransformVec3f.DEFAULT; + } + } + + public static enum TransformType { + NONE, THIRD_PERSON, FIRST_PERSON, HEAD, GUI, GROUND, FIXED; + } + public static final ItemCameraTransforms DEFAULT = new ItemCameraTransforms(); public static float field_181690_b = 0.0F; public static float field_181691_c = 0.0F; @@ -42,7 +68,9 @@ public class ItemCameraTransforms { public final ItemTransformVec3f firstPerson; public final ItemTransformVec3f head; public final ItemTransformVec3f gui; + public final ItemTransformVec3f ground; + public final ItemTransformVec3f fixed; private ItemCameraTransforms() { @@ -85,6 +113,10 @@ public class ItemCameraTransforms { } + public boolean func_181687_c(ItemCameraTransforms.TransformType parTransformType) { + return !this.getTransform(parTransformType).equals(ItemTransformVec3f.DEFAULT); + } + public ItemTransformVec3f getTransform(ItemCameraTransforms.TransformType parTransformType) { switch (parTransformType) { case THIRD_PERSON: @@ -103,31 +135,4 @@ public class ItemCameraTransforms { return ItemTransformVec3f.DEFAULT; } } - - public boolean func_181687_c(ItemCameraTransforms.TransformType parTransformType) { - return !this.getTransform(parTransformType).equals(ItemTransformVec3f.DEFAULT); - } - - public static class Deserializer implements JSONTypeDeserializer { - public ItemCameraTransforms deserialize(JSONObject jsonobject) throws JSONException { - ItemTransformVec3f itemtransformvec3f = this.func_181683_a(jsonobject, "thirdperson"); - ItemTransformVec3f itemtransformvec3f1 = this.func_181683_a(jsonobject, "firstperson"); - ItemTransformVec3f itemtransformvec3f2 = this.func_181683_a(jsonobject, "head"); - ItemTransformVec3f itemtransformvec3f3 = this.func_181683_a(jsonobject, "gui"); - ItemTransformVec3f itemtransformvec3f4 = this.func_181683_a(jsonobject, "ground"); - ItemTransformVec3f itemtransformvec3f5 = this.func_181683_a(jsonobject, "fixed"); - return new ItemCameraTransforms(itemtransformvec3f, itemtransformvec3f1, itemtransformvec3f2, - itemtransformvec3f3, itemtransformvec3f4, itemtransformvec3f5); - } - - private ItemTransformVec3f func_181683_a(JSONObject parJsonObject, String parString1) { - return parJsonObject.has(parString1) - ? JSONTypeProvider.deserialize(parJsonObject.get(parString1), ItemTransformVec3f.class) - : ItemTransformVec3f.DEFAULT; - } - } - - public static enum TransformType { - NONE, THIRD_PERSON, FIRST_PERSON, HEAD, GUI, GROUND, FIXED; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/ItemModelGenerator.java b/src/game/java/net/minecraft/client/renderer/block/model/ItemModelGenerator.java index a592c1f0..37184afa 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/ItemModelGenerator.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/ItemModelGenerator.java @@ -13,54 +13,129 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemModelGenerator { + static class Span { + private final ItemModelGenerator.SpanFacing spanFacing; + private int field_178387_b; + private int field_178388_c; + private final int field_178386_d; + + public Span(ItemModelGenerator.SpanFacing spanFacingIn, int parInt1, int parInt2) { + this.spanFacing = spanFacingIn; + this.field_178387_b = parInt1; + this.field_178388_c = parInt1; + this.field_178386_d = parInt2; + } + + public int func_178381_d() { + return this.field_178386_d; + } + + public void func_178382_a(int parInt1) { + if (parInt1 < this.field_178387_b) { + this.field_178387_b = parInt1; + } else if (parInt1 > this.field_178388_c) { + this.field_178388_c = parInt1; + } + + } + + public ItemModelGenerator.SpanFacing func_178383_a() { + return this.spanFacing; + } + + public int func_178384_c() { + return this.field_178388_c; + } + + public int func_178385_b() { + return this.field_178387_b; + } + } + + static enum SpanFacing { + UP(EnumFacing.UP, 0, -1), DOWN(EnumFacing.DOWN, 0, 1), LEFT(EnumFacing.EAST, -1, 0), + RIGHT(EnumFacing.WEST, 1, 0); + + private final EnumFacing facing; + private final int field_178373_f; + private final int field_178374_g; + + private SpanFacing(EnumFacing facing, int parInt2, int parInt3) { + this.facing = facing; + this.field_178373_f = parInt2; + this.field_178374_g = parInt3; + } + + private boolean func_178369_d() { + return this == DOWN || this == UP; + } + + public int func_178371_c() { + return this.field_178374_g; + } + + public int func_178372_b() { + return this.field_178373_f; + } + + public EnumFacing getFacing() { + return this.facing; + } + } + public static final List LAYERS = Lists .newArrayList(new String[] { "layer0", "layer1", "layer2", "layer3", "layer4" }); - public ModelBlock makeItemModel(TextureMap textureMapIn, ModelBlock blockModel) { - HashMap hashmap = Maps.newHashMap(); + private boolean func_178391_a(int[] parArrayOfInt, int parInt1, int parInt2, int parInt3, int parInt4) { + return parInt1 >= 0 && parInt2 >= 0 && parInt1 < parInt3 && parInt2 < parInt4 + ? (parArrayOfInt[parInt2 * parInt3 + parInt1] >> 24 & 255) == 0 + : true; + } + + private List func_178393_a(EaglerTextureAtlasSprite parTextureAtlasSprite) { + int i = parTextureAtlasSprite.getIconWidth(); + int j = parTextureAtlasSprite.getIconHeight(); ArrayList arraylist = Lists.newArrayList(); - for (int i = 0; i < LAYERS.size(); ++i) { - String s = (String) LAYERS.get(i); - if (!blockModel.isTexturePresent(s)) { - break; + for (int k = 0; k < parTextureAtlasSprite.getFrameCount(); ++k) { + int[] aint = parTextureAtlasSprite.getFrameTextureData(k)[0]; + + for (int l = 0; l < j; ++l) { + for (int i1 = 0; i1 < i; ++i1) { + boolean flag = !this.func_178391_a(aint, i1, l, i, j); + this.func_178396_a(ItemModelGenerator.SpanFacing.UP, arraylist, aint, i1, l, i, j, flag); + this.func_178396_a(ItemModelGenerator.SpanFacing.DOWN, arraylist, aint, i1, l, i, j, flag); + this.func_178396_a(ItemModelGenerator.SpanFacing.LEFT, arraylist, aint, i1, l, i, j, flag); + this.func_178396_a(ItemModelGenerator.SpanFacing.RIGHT, arraylist, aint, i1, l, i, j, flag); + } } - - String s1 = blockModel.resolveTextureName(s); - hashmap.put(s, s1); - EaglerTextureAtlasSprite textureatlassprite = textureMapIn - .getAtlasSprite((new ResourceLocation(s1)).toString()); - arraylist.addAll(this.func_178394_a(i, s, textureatlassprite)); } - if (arraylist.isEmpty()) { - return null; - } else { - hashmap.put("particle", blockModel.isTexturePresent("particle") ? blockModel.resolveTextureName("particle") - : (String) hashmap.get("layer0")); - return new ModelBlock(arraylist, hashmap, false, false, blockModel.func_181682_g()); - } + return arraylist; } private List func_178394_a(int parInt1, String parString1, @@ -77,6 +152,41 @@ public class ItemModelGenerator { return arraylist; } + private void func_178395_a(List parList, ItemModelGenerator.SpanFacing parSpanFacing, + int parInt1, int parInt2) { + ItemModelGenerator.Span itemmodelgenerator$span = null; + + for (int j = 0, l = parList.size(); j < l; ++j) { + ItemModelGenerator.Span itemmodelgenerator$span1 = parList.get(j); + if (itemmodelgenerator$span1.func_178383_a() == parSpanFacing) { + int i = parSpanFacing.func_178369_d() ? parInt2 : parInt1; + if (itemmodelgenerator$span1.func_178381_d() == i) { + itemmodelgenerator$span = itemmodelgenerator$span1; + break; + } + } + } + + int j = parSpanFacing.func_178369_d() ? parInt2 : parInt1; + int k = parSpanFacing.func_178369_d() ? parInt1 : parInt2; + if (itemmodelgenerator$span == null) { + parList.add(new ItemModelGenerator.Span(parSpanFacing, k, j)); + } else { + itemmodelgenerator$span.func_178382_a(k); + } + + } + + private void func_178396_a(ItemModelGenerator.SpanFacing parSpanFacing, List parList, + int[] parArrayOfInt, int parInt1, int parInt2, int parInt3, int parInt4, boolean parFlag) { + boolean flag = this.func_178391_a(parArrayOfInt, parInt1 + parSpanFacing.func_178372_b(), + parInt2 + parSpanFacing.func_178371_c(), parInt3, parInt4) && parFlag; + if (flag) { + this.func_178395_a(parList, parSpanFacing, parInt1, parInt2); + } + + } + private List func_178397_a(EaglerTextureAtlasSprite parTextureAtlasSprite, String parString1, int parInt1) { float f = (float) parTextureAtlasSprite.getIconWidth(); @@ -183,136 +293,29 @@ public class ItemModelGenerator { return arraylist; } - private List func_178393_a(EaglerTextureAtlasSprite parTextureAtlasSprite) { - int i = parTextureAtlasSprite.getIconWidth(); - int j = parTextureAtlasSprite.getIconHeight(); + public ModelBlock makeItemModel(TextureMap textureMapIn, ModelBlock blockModel) { + HashMap hashmap = Maps.newHashMap(); ArrayList arraylist = Lists.newArrayList(); - for (int k = 0; k < parTextureAtlasSprite.getFrameCount(); ++k) { - int[] aint = parTextureAtlasSprite.getFrameTextureData(k)[0]; - - for (int l = 0; l < j; ++l) { - for (int i1 = 0; i1 < i; ++i1) { - boolean flag = !this.func_178391_a(aint, i1, l, i, j); - this.func_178396_a(ItemModelGenerator.SpanFacing.UP, arraylist, aint, i1, l, i, j, flag); - this.func_178396_a(ItemModelGenerator.SpanFacing.DOWN, arraylist, aint, i1, l, i, j, flag); - this.func_178396_a(ItemModelGenerator.SpanFacing.LEFT, arraylist, aint, i1, l, i, j, flag); - this.func_178396_a(ItemModelGenerator.SpanFacing.RIGHT, arraylist, aint, i1, l, i, j, flag); - } + for (int i = 0; i < LAYERS.size(); ++i) { + String s = (String) LAYERS.get(i); + if (!blockModel.isTexturePresent(s)) { + break; } + + String s1 = blockModel.resolveTextureName(s); + hashmap.put(s, s1); + EaglerTextureAtlasSprite textureatlassprite = textureMapIn + .getAtlasSprite((new ResourceLocation(s1)).toString()); + arraylist.addAll(this.func_178394_a(i, s, textureatlassprite)); } - return arraylist; - } - - private void func_178396_a(ItemModelGenerator.SpanFacing parSpanFacing, List parList, - int[] parArrayOfInt, int parInt1, int parInt2, int parInt3, int parInt4, boolean parFlag) { - boolean flag = this.func_178391_a(parArrayOfInt, parInt1 + parSpanFacing.func_178372_b(), - parInt2 + parSpanFacing.func_178371_c(), parInt3, parInt4) && parFlag; - if (flag) { - this.func_178395_a(parList, parSpanFacing, parInt1, parInt2); - } - - } - - private void func_178395_a(List parList, ItemModelGenerator.SpanFacing parSpanFacing, - int parInt1, int parInt2) { - ItemModelGenerator.Span itemmodelgenerator$span = null; - - for (int j = 0, l = parList.size(); j < l; ++j) { - ItemModelGenerator.Span itemmodelgenerator$span1 = parList.get(j); - if (itemmodelgenerator$span1.func_178383_a() == parSpanFacing) { - int i = parSpanFacing.func_178369_d() ? parInt2 : parInt1; - if (itemmodelgenerator$span1.func_178381_d() == i) { - itemmodelgenerator$span = itemmodelgenerator$span1; - break; - } - } - } - - int j = parSpanFacing.func_178369_d() ? parInt2 : parInt1; - int k = parSpanFacing.func_178369_d() ? parInt1 : parInt2; - if (itemmodelgenerator$span == null) { - parList.add(new ItemModelGenerator.Span(parSpanFacing, k, j)); + if (arraylist.isEmpty()) { + return null; } else { - itemmodelgenerator$span.func_178382_a(k); - } - - } - - private boolean func_178391_a(int[] parArrayOfInt, int parInt1, int parInt2, int parInt3, int parInt4) { - return parInt1 >= 0 && parInt2 >= 0 && parInt1 < parInt3 && parInt2 < parInt4 - ? (parArrayOfInt[parInt2 * parInt3 + parInt1] >> 24 & 255) == 0 - : true; - } - - static class Span { - private final ItemModelGenerator.SpanFacing spanFacing; - private int field_178387_b; - private int field_178388_c; - private final int field_178386_d; - - public Span(ItemModelGenerator.SpanFacing spanFacingIn, int parInt1, int parInt2) { - this.spanFacing = spanFacingIn; - this.field_178387_b = parInt1; - this.field_178388_c = parInt1; - this.field_178386_d = parInt2; - } - - public void func_178382_a(int parInt1) { - if (parInt1 < this.field_178387_b) { - this.field_178387_b = parInt1; - } else if (parInt1 > this.field_178388_c) { - this.field_178388_c = parInt1; - } - - } - - public ItemModelGenerator.SpanFacing func_178383_a() { - return this.spanFacing; - } - - public int func_178385_b() { - return this.field_178387_b; - } - - public int func_178384_c() { - return this.field_178388_c; - } - - public int func_178381_d() { - return this.field_178386_d; - } - } - - static enum SpanFacing { - UP(EnumFacing.UP, 0, -1), DOWN(EnumFacing.DOWN, 0, 1), LEFT(EnumFacing.EAST, -1, 0), - RIGHT(EnumFacing.WEST, 1, 0); - - private final EnumFacing facing; - private final int field_178373_f; - private final int field_178374_g; - - private SpanFacing(EnumFacing facing, int parInt2, int parInt3) { - this.facing = facing; - this.field_178373_f = parInt2; - this.field_178374_g = parInt3; - } - - public EnumFacing getFacing() { - return this.facing; - } - - public int func_178372_b() { - return this.field_178373_f; - } - - public int func_178371_c() { - return this.field_178374_g; - } - - private boolean func_178369_d() { - return this == DOWN || this == UP; + hashmap.put("particle", blockModel.isTexturePresent("particle") ? blockModel.resolveTextureName("particle") + : (String) hashmap.get("layer0")); + return new ModelBlock(arraylist, hashmap, false, false, blockModel.func_181682_g()); } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/ItemTransformVec3f.java b/src/game/java/net/minecraft/client/renderer/block/model/ItemTransformVec3f.java index 9d7f9727..ba112eba 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/ItemTransformVec3f.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/ItemTransformVec3f.java @@ -8,59 +8,30 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeDeserializer; import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemTransformVec3f { - public static final ItemTransformVec3f DEFAULT = new ItemTransformVec3f(new Vector3f(), new Vector3f(), - new Vector3f(1.0F, 1.0F, 1.0F)); - public final Vector3f rotation; - public final Vector3f translation; - public final Vector3f scale; - - public ItemTransformVec3f(Vector3f rotation, Vector3f translation, Vector3f scale) { - this.rotation = new Vector3f(rotation); - this.translation = new Vector3f(translation); - this.scale = new Vector3f(scale); - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (this.getClass() != object.getClass()) { - return false; - } else { - ItemTransformVec3f itemtransformvec3f = (ItemTransformVec3f) object; - return !this.rotation.equals(itemtransformvec3f.rotation) ? false - : (!this.scale.equals(itemtransformvec3f.scale) ? false - : this.translation.equals(itemtransformvec3f.translation)); - } - } - - public int hashCode() { - int i = this.rotation.hashCode(); - i = 31 * i + this.translation.hashCode(); - i = 31 * i + this.scale.hashCode(); - return i; - } - public static class Deserializer implements JSONTypeDeserializer { private static final Vector3f ROTATION_DEFAULT = new Vector3f(0.0F, 0.0F, 0.0F); private static final Vector3f TRANSLATION_DEFAULT = new Vector3f(0.0F, 0.0F, 0.0F); @@ -99,4 +70,37 @@ public class ItemTransformVec3f { } } } + + public static final ItemTransformVec3f DEFAULT = new ItemTransformVec3f(new Vector3f(), new Vector3f(), + new Vector3f(1.0F, 1.0F, 1.0F)); + public final Vector3f rotation; + public final Vector3f translation; + + public final Vector3f scale; + + public ItemTransformVec3f(Vector3f rotation, Vector3f translation, Vector3f scale) { + this.rotation = new Vector3f(rotation); + this.translation = new Vector3f(translation); + this.scale = new Vector3f(scale); + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (this.getClass() != object.getClass()) { + return false; + } else { + ItemTransformVec3f itemtransformvec3f = (ItemTransformVec3f) object; + return !this.rotation.equals(itemtransformvec3f.rotation) ? false + : (!this.scale.equals(itemtransformvec3f.scale) ? false + : this.translation.equals(itemtransformvec3f.translation)); + } + } + + public int hashCode() { + int i = this.rotation.hashCode(); + i = 31 * i + this.translation.hashCode(); + i = 31 * i + this.scale.hashCode(); + return i; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/ModelBlock.java b/src/game/java/net/minecraft/client/renderer/block/model/ModelBlock.java index ea8cf0f3..7707c334 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/ModelBlock.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/ModelBlock.java @@ -5,6 +5,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; + import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; @@ -18,52 +19,143 @@ import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelBlock { + static final class Bookkeep { + public final ModelBlock model; + public ModelBlock modelExt; + + private Bookkeep(ModelBlock parModelBlock) { + this.model = parModelBlock; + } + } + + public static class Deserializer implements JSONTypeDeserializer { + public ModelBlock deserialize(JSONObject jsonobject) throws JSONException { + List list = this.getModelElements(jsonobject); + String s = this.getParent(jsonobject); + boolean flag = StringUtils.isEmpty(s); + boolean flag1 = list.isEmpty(); + if (flag1 && flag) { + throw new JSONException("BlockModel requires either elements or parent, found neither"); + } else if (!flag && !flag1) { + throw new JSONException("BlockModel requires either elements or parent, found both"); + } else { + Map map = this.getTextures(jsonobject); + boolean flag2 = this.getAmbientOcclusionEnabled(jsonobject); + ItemCameraTransforms itemcameratransforms = ItemCameraTransforms.DEFAULT; + if (jsonobject.has("display")) { + JSONObject jsonobject1 = jsonobject.getJSONObject("display"); + itemcameratransforms = JSONTypeProvider.deserialize(jsonobject1, ItemCameraTransforms.class); + } + + return flag1 ? new ModelBlock(new ResourceLocation(s), map, flag2, true, itemcameratransforms) + : new ModelBlock(list, map, flag2, true, itemcameratransforms); + } + } + + protected boolean getAmbientOcclusionEnabled(JSONObject parJsonObject) { + return parJsonObject.optBoolean("ambientocclusion", true); + } + + protected List getModelElements(JSONObject parJsonObject) { + ArrayList arraylist = Lists.newArrayList(); + if (parJsonObject.has("elements")) { + for (Object jsonelement : parJsonObject.getJSONArray("elements")) { + arraylist.add((BlockPart) JSONTypeProvider.deserialize(jsonelement, BlockPart.class)); + } + } + + return arraylist; + } + + private String getParent(JSONObject parJsonObject) { + return parJsonObject.optString("parent", ""); + } + + private Map getTextures(JSONObject parJsonObject) { + HashMap hashmap = Maps.newHashMap(); + if (parJsonObject.has("textures")) { + JSONObject jsonobject = parJsonObject.getJSONObject("textures"); + + for (String entry : jsonobject.keySet()) { + hashmap.put(entry, jsonobject.getString(entry)); + } + } + + return hashmap; + } + } + + public static class LoopException extends RuntimeException { + } + private static final Logger LOGGER = LogManager.getLogger(); - private final List elements; - private final boolean gui3d; - private final boolean ambientOcclusion; - private ItemCameraTransforms cameraTransforms; - public String name; - protected final Map textures; - protected ModelBlock parent; - protected ResourceLocation parentLocation; + public static void checkModelHierarchy(Map parMap) { + for (ModelBlock modelblock : parMap.values()) { + try { + ModelBlock modelblock1 = modelblock.parent; + + for (ModelBlock modelblock2 = modelblock1.parent; modelblock1 != modelblock2; modelblock2 = modelblock2.parent.parent) { + modelblock1 = modelblock1.parent; + } + + throw new ModelBlock.LoopException(); + } catch (ModelBlock.LoopException var5) { + throw var5; + } catch (Throwable var6) { + ; + } + } + + } public static ModelBlock deserialize(String parString1) { return (ModelBlock) JSONTypeProvider.deserialize(new JSONObject(parString1), ModelBlock.class); } + private final List elements; + private final boolean gui3d; + private final boolean ambientOcclusion; + + private ItemCameraTransforms cameraTransforms; + + public String name; + + protected final Map textures; + + protected ModelBlock parent; + + protected ResourceLocation parentLocation; + protected ModelBlock(List parList, Map parMap, boolean parFlag, boolean parFlag2, ItemCameraTransforms parItemCameraTransforms) { this((ResourceLocation) null, parList, parMap, parFlag, parFlag2, parItemCameraTransforms); } - protected ModelBlock(ResourceLocation parResourceLocation, Map parMap, boolean parFlag, - boolean parFlag2, ItemCameraTransforms parItemCameraTransforms) { - this(parResourceLocation, Collections.emptyList(), parMap, parFlag, parFlag2, parItemCameraTransforms); - } - private ModelBlock(ResourceLocation parentLocationIn, List elementsIn, Map texturesIn, boolean ambientOcclusionIn, boolean gui3dIn, ItemCameraTransforms cameraTransformsIn) { this.name = ""; @@ -75,10 +167,47 @@ public class ModelBlock { this.cameraTransforms = cameraTransformsIn; } + protected ModelBlock(ResourceLocation parResourceLocation, Map parMap, boolean parFlag, + boolean parFlag2, ItemCameraTransforms parItemCameraTransforms) { + this(parResourceLocation, Collections.emptyList(), parMap, parFlag, parFlag2, parItemCameraTransforms); + } + + private ItemTransformVec3f func_181681_a(ItemCameraTransforms.TransformType parTransformType) { + return this.parent != null && !this.cameraTransforms.func_181687_c(parTransformType) + ? this.parent.func_181681_a(parTransformType) + : this.cameraTransforms.getTransform(parTransformType); + } + + public ItemCameraTransforms func_181682_g() { + ItemTransformVec3f itemtransformvec3f = this.func_181681_a(ItemCameraTransforms.TransformType.THIRD_PERSON); + ItemTransformVec3f itemtransformvec3f1 = this.func_181681_a(ItemCameraTransforms.TransformType.FIRST_PERSON); + ItemTransformVec3f itemtransformvec3f2 = this.func_181681_a(ItemCameraTransforms.TransformType.HEAD); + ItemTransformVec3f itemtransformvec3f3 = this.func_181681_a(ItemCameraTransforms.TransformType.GUI); + ItemTransformVec3f itemtransformvec3f4 = this.func_181681_a(ItemCameraTransforms.TransformType.GROUND); + ItemTransformVec3f itemtransformvec3f5 = this.func_181681_a(ItemCameraTransforms.TransformType.FIXED); + return new ItemCameraTransforms(itemtransformvec3f, itemtransformvec3f1, itemtransformvec3f2, + itemtransformvec3f3, itemtransformvec3f4, itemtransformvec3f5); + } + public List getElements() { return this.hasParent() ? this.parent.getElements() : this.elements; } + public void getParentFromMap(Map parMap) { + if (this.parentLocation != null) { + this.parent = (ModelBlock) parMap.get(this.parentLocation); + } + + } + + public ResourceLocation getParentLocation() { + return this.parentLocation; + } + + public ModelBlock getRootModel() { + return this.hasParent() ? this.parent.getRootModel() : this; + } + private boolean hasParent() { return this.parent != null; } @@ -95,13 +224,6 @@ public class ModelBlock { return this.parentLocation == null || this.parent != null && this.parent.isResolved(); } - public void getParentFromMap(Map parMap) { - if (this.parentLocation != null) { - this.parent = (ModelBlock) parMap.get(this.parentLocation); - } - - } - public boolean isTexturePresent(String textureName) { return !"missingno".equals(this.resolveTextureName(textureName)); } @@ -140,117 +262,4 @@ public class ModelBlock { private boolean startsWithHash(String hash) { return hash.charAt(0) == 35; } - - public ResourceLocation getParentLocation() { - return this.parentLocation; - } - - public ModelBlock getRootModel() { - return this.hasParent() ? this.parent.getRootModel() : this; - } - - public ItemCameraTransforms func_181682_g() { - ItemTransformVec3f itemtransformvec3f = this.func_181681_a(ItemCameraTransforms.TransformType.THIRD_PERSON); - ItemTransformVec3f itemtransformvec3f1 = this.func_181681_a(ItemCameraTransforms.TransformType.FIRST_PERSON); - ItemTransformVec3f itemtransformvec3f2 = this.func_181681_a(ItemCameraTransforms.TransformType.HEAD); - ItemTransformVec3f itemtransformvec3f3 = this.func_181681_a(ItemCameraTransforms.TransformType.GUI); - ItemTransformVec3f itemtransformvec3f4 = this.func_181681_a(ItemCameraTransforms.TransformType.GROUND); - ItemTransformVec3f itemtransformvec3f5 = this.func_181681_a(ItemCameraTransforms.TransformType.FIXED); - return new ItemCameraTransforms(itemtransformvec3f, itemtransformvec3f1, itemtransformvec3f2, - itemtransformvec3f3, itemtransformvec3f4, itemtransformvec3f5); - } - - private ItemTransformVec3f func_181681_a(ItemCameraTransforms.TransformType parTransformType) { - return this.parent != null && !this.cameraTransforms.func_181687_c(parTransformType) - ? this.parent.func_181681_a(parTransformType) - : this.cameraTransforms.getTransform(parTransformType); - } - - public static void checkModelHierarchy(Map parMap) { - for (ModelBlock modelblock : parMap.values()) { - try { - ModelBlock modelblock1 = modelblock.parent; - - for (ModelBlock modelblock2 = modelblock1.parent; modelblock1 != modelblock2; modelblock2 = modelblock2.parent.parent) { - modelblock1 = modelblock1.parent; - } - - throw new ModelBlock.LoopException(); - } catch (ModelBlock.LoopException var5) { - throw var5; - } catch (Throwable var6) { - ; - } - } - - } - - static final class Bookkeep { - public final ModelBlock model; - public ModelBlock modelExt; - - private Bookkeep(ModelBlock parModelBlock) { - this.model = parModelBlock; - } - } - - public static class Deserializer implements JSONTypeDeserializer { - public ModelBlock deserialize(JSONObject jsonobject) throws JSONException { - List list = this.getModelElements(jsonobject); - String s = this.getParent(jsonobject); - boolean flag = StringUtils.isEmpty(s); - boolean flag1 = list.isEmpty(); - if (flag1 && flag) { - throw new JSONException("BlockModel requires either elements or parent, found neither"); - } else if (!flag && !flag1) { - throw new JSONException("BlockModel requires either elements or parent, found both"); - } else { - Map map = this.getTextures(jsonobject); - boolean flag2 = this.getAmbientOcclusionEnabled(jsonobject); - ItemCameraTransforms itemcameratransforms = ItemCameraTransforms.DEFAULT; - if (jsonobject.has("display")) { - JSONObject jsonobject1 = jsonobject.getJSONObject("display"); - itemcameratransforms = JSONTypeProvider.deserialize(jsonobject1, ItemCameraTransforms.class); - } - - return flag1 ? new ModelBlock(new ResourceLocation(s), map, flag2, true, itemcameratransforms) - : new ModelBlock(list, map, flag2, true, itemcameratransforms); - } - } - - private Map getTextures(JSONObject parJsonObject) { - HashMap hashmap = Maps.newHashMap(); - if (parJsonObject.has("textures")) { - JSONObject jsonobject = parJsonObject.getJSONObject("textures"); - - for (String entry : jsonobject.keySet()) { - hashmap.put(entry, jsonobject.getString(entry)); - } - } - - return hashmap; - } - - private String getParent(JSONObject parJsonObject) { - return parJsonObject.optString("parent", ""); - } - - protected boolean getAmbientOcclusionEnabled(JSONObject parJsonObject) { - return parJsonObject.optBoolean("ambientocclusion", true); - } - - protected List getModelElements(JSONObject parJsonObject) { - ArrayList arraylist = Lists.newArrayList(); - if (parJsonObject.has("elements")) { - for (Object jsonelement : parJsonObject.getJSONArray("elements")) { - arraylist.add((BlockPart) JSONTypeProvider.deserialize(jsonelement, BlockPart.class)); - } - } - - return arraylist; - } - } - - public static class LoopException extends RuntimeException { - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/model/ModelBlockDefinition.java b/src/game/java/net/minecraft/client/renderer/block/model/ModelBlockDefinition.java index 580124f0..d7858174 100644 --- a/src/game/java/net/minecraft/client/renderer/block/model/ModelBlockDefinition.java +++ b/src/game/java/net/minecraft/client/renderer/block/model/ModelBlockDefinition.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; + import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; @@ -17,90 +18,37 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.minecraft.client.resources.model.ModelRotation; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelBlockDefinition { - private final Map mapVariants = Maps.newHashMap(); - - public static ModelBlockDefinition parseFromReader(Reader parReader) { - return (ModelBlockDefinition) JSONTypeProvider.deserialize(parReader, ModelBlockDefinition.class); - } - - public ModelBlockDefinition(Collection parCollection) { - for (ModelBlockDefinition.Variants modelblockdefinition$variants : parCollection) { - this.mapVariants.put(modelblockdefinition$variants.name, modelblockdefinition$variants); - } - - } - - public ModelBlockDefinition(List parList) { - for (int i = 0, l = parList.size(); i < l; ++i) { - this.mapVariants.putAll(parList.get(i).mapVariants); - } - - } - - public ModelBlockDefinition.Variants getVariants(String parString1) { - ModelBlockDefinition.Variants modelblockdefinition$variants = (ModelBlockDefinition.Variants) this.mapVariants - .get(parString1); - if (modelblockdefinition$variants == null) { - throw new ModelBlockDefinition.MissingVariantException(); - } else { - return modelblockdefinition$variants; - } - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (object instanceof ModelBlockDefinition) { - ModelBlockDefinition modelblockdefinition = (ModelBlockDefinition) object; - return this.mapVariants.equals(modelblockdefinition.mapVariants); - } else { - return false; - } - } - - public int hashCode() { - return this.mapVariants.hashCode(); - } - public static class Deserializer implements JSONTypeDeserializer { public ModelBlockDefinition deserialize(JSONObject jsonobject) throws JSONException { List list = this.parseVariantsList(jsonobject); return new ModelBlockDefinition((Collection) list); } - protected List parseVariantsList(JSONObject parJsonObject) { - JSONObject jsonobject = parJsonObject.getJSONObject("variants"); - ArrayList arraylist = Lists.newArrayList(); - - for (String entry : jsonobject.keySet()) { - arraylist.add(this.parseVariants(entry, jsonobject.get(entry))); - } - - return arraylist; - } - protected ModelBlockDefinition.Variants parseVariants(String s, Object jsonelement) { ArrayList arraylist = Lists.newArrayList(); if (jsonelement instanceof JSONArray) { @@ -113,61 +61,23 @@ public class ModelBlockDefinition { return new ModelBlockDefinition.Variants(s, arraylist); } + + protected List parseVariantsList(JSONObject parJsonObject) { + JSONObject jsonobject = parJsonObject.getJSONObject("variants"); + ArrayList arraylist = Lists.newArrayList(); + + for (String entry : jsonobject.keySet()) { + arraylist.add(this.parseVariants(entry, jsonobject.get(entry))); + } + + return arraylist; + } } public class MissingVariantException extends RuntimeException { } public static class Variant { - private final ResourceLocation modelLocation; - private final ModelRotation modelRotation; - private final boolean uvLock; - private final int weight; - - public Variant(ResourceLocation modelLocationIn, ModelRotation modelRotationIn, boolean uvLockIn, - int weightIn) { - this.modelLocation = modelLocationIn; - this.modelRotation = modelRotationIn; - this.uvLock = uvLockIn; - this.weight = weightIn; - } - - public ResourceLocation getModelLocation() { - return this.modelLocation; - } - - public ModelRotation getRotation() { - return this.modelRotation; - } - - public boolean isUvLocked() { - return this.uvLock; - } - - public int getWeight() { - return this.weight; - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof ModelBlockDefinition.Variant)) { - return false; - } else { - ModelBlockDefinition.Variant modelblockdefinition$variant = (ModelBlockDefinition.Variant) object; - return this.modelLocation.equals(modelblockdefinition$variant.modelLocation) - && this.modelRotation == modelblockdefinition$variant.modelRotation - && this.uvLock == modelblockdefinition$variant.uvLock; - } - } - - public int hashCode() { - int i = this.modelLocation.hashCode(); - i = 31 * i + (this.modelRotation != null ? this.modelRotation.hashCode() : 0); - i = 31 * i + (this.uvLock ? 1 : 0); - return i; - } - public static class Deserializer implements JSONTypeDeserializer { public ModelBlockDefinition.Variant deserialize(JSONObject jsonobject) throws JSONException { String s = this.parseModel(jsonobject); @@ -184,8 +94,8 @@ public class ModelBlockDefinition { return resourcelocation; } - private boolean parseUvLock(JSONObject parJsonObject) { - return parJsonObject.optBoolean("uvlock", false); + protected String parseModel(JSONObject parJsonObject) { + return parJsonObject.getString("model"); } protected ModelRotation parseRotation(JSONObject parJsonObject) { @@ -199,14 +109,64 @@ public class ModelBlockDefinition { } } - protected String parseModel(JSONObject parJsonObject) { - return parJsonObject.getString("model"); + private boolean parseUvLock(JSONObject parJsonObject) { + return parJsonObject.optBoolean("uvlock", false); } protected int parseWeight(JSONObject parJsonObject) { return parJsonObject.optInt("weight", 1); } } + + private final ResourceLocation modelLocation; + private final ModelRotation modelRotation; + private final boolean uvLock; + + private final int weight; + + public Variant(ResourceLocation modelLocationIn, ModelRotation modelRotationIn, boolean uvLockIn, + int weightIn) { + this.modelLocation = modelLocationIn; + this.modelRotation = modelRotationIn; + this.uvLock = uvLockIn; + this.weight = weightIn; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ModelBlockDefinition.Variant)) { + return false; + } else { + ModelBlockDefinition.Variant modelblockdefinition$variant = (ModelBlockDefinition.Variant) object; + return this.modelLocation.equals(modelblockdefinition$variant.modelLocation) + && this.modelRotation == modelblockdefinition$variant.modelRotation + && this.uvLock == modelblockdefinition$variant.uvLock; + } + } + + public ResourceLocation getModelLocation() { + return this.modelLocation; + } + + public ModelRotation getRotation() { + return this.modelRotation; + } + + public int getWeight() { + return this.weight; + } + + public int hashCode() { + int i = this.modelLocation.hashCode(); + i = 31 * i + (this.modelRotation != null ? this.modelRotation.hashCode() : 0); + i = 31 * i + (this.uvLock ? 1 : 0); + return i; + } + + public boolean isUvLocked() { + return this.uvLock; + } } public static class Variants { @@ -218,10 +178,6 @@ public class ModelBlockDefinition { this.listVariants = listVariantsIn; } - public List getVariants() { - return this.listVariants; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -234,10 +190,59 @@ public class ModelBlockDefinition { } } + public List getVariants() { + return this.listVariants; + } + public int hashCode() { int i = this.name.hashCode(); i = 31 * i + this.listVariants.hashCode(); return i; } } + + public static ModelBlockDefinition parseFromReader(Reader parReader) { + return (ModelBlockDefinition) JSONTypeProvider.deserialize(parReader, ModelBlockDefinition.class); + } + + private final Map mapVariants = Maps.newHashMap(); + + public ModelBlockDefinition(Collection parCollection) { + for (ModelBlockDefinition.Variants modelblockdefinition$variants : parCollection) { + this.mapVariants.put(modelblockdefinition$variants.name, modelblockdefinition$variants); + } + + } + + public ModelBlockDefinition(List parList) { + for (int i = 0, l = parList.size(); i < l; ++i) { + this.mapVariants.putAll(parList.get(i).mapVariants); + } + + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (object instanceof ModelBlockDefinition) { + ModelBlockDefinition modelblockdefinition = (ModelBlockDefinition) object; + return this.mapVariants.equals(modelblockdefinition.mapVariants); + } else { + return false; + } + } + + public ModelBlockDefinition.Variants getVariants(String parString1) { + ModelBlockDefinition.Variants modelblockdefinition$variants = (ModelBlockDefinition.Variants) this.mapVariants + .get(parString1); + if (modelblockdefinition$variants == null) { + throw new ModelBlockDefinition.MissingVariantException(); + } else { + return modelblockdefinition$variants; + } + } + + public int hashCode() { + return this.mapVariants.hashCode(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/statemap/BlockStateMapper.java b/src/game/java/net/minecraft/client/renderer/block/statemap/BlockStateMapper.java index 3f4fd431..de14ece1 100644 --- a/src/game/java/net/minecraft/client/renderer/block/statemap/BlockStateMapper.java +++ b/src/game/java/net/minecraft/client/renderer/block/statemap/BlockStateMapper.java @@ -13,22 +13,25 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.model.ModelResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,14 +40,6 @@ public class BlockStateMapper { private Map blockStateMap = Maps.newIdentityHashMap(); private Set setBuiltInBlocks = Sets.newIdentityHashSet(); - public void registerBlockStateMapper(Block parBlock, IStateMapper parIStateMapper) { - this.blockStateMap.put(parBlock, parIStateMapper); - } - - public void registerBuiltInBlocks(Block... parArrayOfBlock) { - Collections.addAll(this.setBuiltInBlocks, parArrayOfBlock); - } - public Map putAllStateModelLocations() { IdentityHashMap identityhashmap = Maps.newIdentityHashMap(); @@ -58,4 +53,12 @@ public class BlockStateMapper { return identityhashmap; } + + public void registerBlockStateMapper(Block parBlock, IStateMapper parIStateMapper) { + this.blockStateMap.put(parBlock, parIStateMapper); + } + + public void registerBuiltInBlocks(Block... parArrayOfBlock) { + Collections.addAll(this.setBuiltInBlocks, parArrayOfBlock); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/statemap/DefaultStateMapper.java b/src/game/java/net/minecraft/client/renderer/block/statemap/DefaultStateMapper.java index 248480ce..2ea12312 100644 --- a/src/game/java/net/minecraft/client/renderer/block/statemap/DefaultStateMapper.java +++ b/src/game/java/net/minecraft/client/renderer/block/statemap/DefaultStateMapper.java @@ -5,22 +5,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/block/statemap/IStateMapper.java b/src/game/java/net/minecraft/client/renderer/block/statemap/IStateMapper.java index d232fe04..87e08b16 100644 --- a/src/game/java/net/minecraft/client/renderer/block/statemap/IStateMapper.java +++ b/src/game/java/net/minecraft/client/renderer/block/statemap/IStateMapper.java @@ -6,22 +6,25 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.model.ModelResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/block/statemap/StateMap.java b/src/game/java/net/minecraft/client/renderer/block/statemap/StateMap.java index 5cfea372..d4b52e5e 100644 --- a/src/game/java/net/minecraft/client/renderer/block/statemap/StateMap.java +++ b/src/game/java/net/minecraft/client/renderer/block/statemap/StateMap.java @@ -13,29 +13,58 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.model.ModelResourceLocation; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StateMap extends StateMapperBase { + public static class Builder { + private IProperty name; + private String suffix; + private final List> ignored = Lists.newArrayList(); + + public StateMap build() { + return new StateMap(this.name, this.suffix, this.ignored); + } + + public StateMap.Builder ignore(IProperty... parArrayOfIProperty) { + Collections.addAll(this.ignored, parArrayOfIProperty); + return this; + } + + public StateMap.Builder withName(IProperty builderPropertyIn) { + this.name = builderPropertyIn; + return this; + } + + public StateMap.Builder withSuffix(String builderSuffixIn) { + this.suffix = builderSuffixIn; + return this; + } + } + private final IProperty name; private final String suffix; + private final List> ignored; private StateMap(IProperty name, String suffix, List> ignored) { @@ -63,29 +92,4 @@ public class StateMap extends StateMapperBase { return new ModelResourceLocation(s, this.getPropertyString(linkedhashmap)); } - - public static class Builder { - private IProperty name; - private String suffix; - private final List> ignored = Lists.newArrayList(); - - public StateMap.Builder withName(IProperty builderPropertyIn) { - this.name = builderPropertyIn; - return this; - } - - public StateMap.Builder withSuffix(String builderSuffixIn) { - this.suffix = builderSuffixIn; - return this; - } - - public StateMap.Builder ignore(IProperty... parArrayOfIProperty) { - Collections.addAll(this.ignored, parArrayOfIProperty); - return this; - } - - public StateMap build() { - return new StateMap(this.name, this.suffix, this.ignored); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/block/statemap/StateMapperBase.java b/src/game/java/net/minecraft/client/renderer/block/statemap/StateMapperBase.java index 6b41307d..4ece79a6 100644 --- a/src/game/java/net/minecraft/client/renderer/block/statemap/StateMapperBase.java +++ b/src/game/java/net/minecraft/client/renderer/block/statemap/StateMapperBase.java @@ -10,22 +10,25 @@ import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.client.resources.model.ModelResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,6 +36,8 @@ import net.minecraft.client.resources.model.ModelResourceLocation; public abstract class StateMapperBase implements IStateMapper { protected Map mapStateModelLocations = Maps.newLinkedHashMap(); + protected abstract ModelResourceLocation getModelResourceLocation(IBlockState var1); + public String getPropertyString(Map parMap) { StringBuilder stringbuilder = new StringBuilder(); @@ -62,6 +67,4 @@ public abstract class StateMapperBase implements IStateMapper { return this.mapStateModelLocations; } - - protected abstract ModelResourceLocation getModelResourceLocation(IBlockState var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/chunk/ChunkCompileTaskGenerator.java b/src/game/java/net/minecraft/client/renderer/chunk/ChunkCompileTaskGenerator.java index c148e257..ec19af17 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/ChunkCompileTaskGenerator.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/ChunkCompileTaskGenerator.java @@ -8,27 +8,38 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; import net.minecraft.client.renderer.RegionRenderCacheBuilder; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChunkCompileTaskGenerator { + public static enum Status { + PENDING, COMPILING, UPLOADING, DONE; + } + + public static enum Type { + REBUILD_CHUNK, RESORT_TRANSPARENCY; + } + private final RenderChunk renderChunk; private final List listFinishRunnables = Lists.newArrayList(); private final ChunkCompileTaskGenerator.Type type; @@ -36,7 +47,9 @@ public class ChunkCompileTaskGenerator { private CompiledChunk compiledChunk; private ChunkCompileTaskGenerator.Status status = ChunkCompileTaskGenerator.Status.PENDING; private boolean finished; + public long goddamnFuckingTimeout = 0l; + public long time = 0; public ChunkCompileTaskGenerator(RenderChunk renderChunkIn, ChunkCompileTaskGenerator.Type typeIn) { @@ -44,48 +57,6 @@ public class ChunkCompileTaskGenerator { this.type = typeIn; } - public ChunkCompileTaskGenerator.Status getStatus() { - return this.status; - } - - public RenderChunk getRenderChunk() { - return this.renderChunk; - } - - public CompiledChunk getCompiledChunk() { - return this.compiledChunk; - } - - public void setCompiledChunk(CompiledChunk compiledChunkIn) { - this.compiledChunk = compiledChunkIn; - } - - public RegionRenderCacheBuilder getRegionRenderCacheBuilder() { - return this.regionRenderCacheBuilder; - } - - public void setRegionRenderCacheBuilder(RegionRenderCacheBuilder regionRenderCacheBuilderIn) { - this.regionRenderCacheBuilder = regionRenderCacheBuilderIn; - } - - public void setStatus(ChunkCompileTaskGenerator.Status statusIn) { - this.status = statusIn; - } - - public void finish() { - if (this.type == ChunkCompileTaskGenerator.Type.REBUILD_CHUNK - && this.status != ChunkCompileTaskGenerator.Status.DONE) { - this.renderChunk.setNeedsUpdate(true); - } - - this.finished = true; - this.status = ChunkCompileTaskGenerator.Status.DONE; - - for (int i = 0, l = this.listFinishRunnables.size(); i < l; ++i) { - this.listFinishRunnables.get(i).run(); - } - } - public void addFinishRunnable(Runnable parRunnable) { this.listFinishRunnables.add(parRunnable); if (this.finished) { @@ -93,14 +64,6 @@ public class ChunkCompileTaskGenerator { } } - public ChunkCompileTaskGenerator.Type getType() { - return this.type; - } - - public boolean isFinished() { - return this.finished; - } - public boolean canExecuteYet() { if (this.type == ChunkCompileTaskGenerator.Type.RESORT_TRANSPARENCY) { CompiledChunk ch = this.renderChunk.getCompiledChunk(); @@ -115,11 +78,53 @@ public class ChunkCompileTaskGenerator { } } - public static enum Status { - PENDING, COMPILING, UPLOADING, DONE; + public void finish() { + if (this.type == ChunkCompileTaskGenerator.Type.REBUILD_CHUNK + && this.status != ChunkCompileTaskGenerator.Status.DONE) { + this.renderChunk.setNeedsUpdate(true); + } + + this.finished = true; + this.status = ChunkCompileTaskGenerator.Status.DONE; + + for (int i = 0, l = this.listFinishRunnables.size(); i < l; ++i) { + this.listFinishRunnables.get(i).run(); + } } - public static enum Type { - REBUILD_CHUNK, RESORT_TRANSPARENCY; + public CompiledChunk getCompiledChunk() { + return this.compiledChunk; + } + + public RegionRenderCacheBuilder getRegionRenderCacheBuilder() { + return this.regionRenderCacheBuilder; + } + + public RenderChunk getRenderChunk() { + return this.renderChunk; + } + + public ChunkCompileTaskGenerator.Status getStatus() { + return this.status; + } + + public ChunkCompileTaskGenerator.Type getType() { + return this.type; + } + + public boolean isFinished() { + return this.finished; + } + + public void setCompiledChunk(CompiledChunk compiledChunkIn) { + this.compiledChunk = compiledChunkIn; + } + + public void setRegionRenderCacheBuilder(RegionRenderCacheBuilder regionRenderCacheBuilderIn) { + this.regionRenderCacheBuilder = regionRenderCacheBuilderIn; + } + + public void setStatus(ChunkCompileTaskGenerator.Status statusIn) { + this.status = statusIn; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/chunk/ChunkRenderWorker.java b/src/game/java/net/minecraft/client/renderer/chunk/ChunkRenderWorker.java index 9da706f0..796cf2b5 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/ChunkRenderWorker.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/ChunkRenderWorker.java @@ -9,22 +9,25 @@ import net.minecraft.client.renderer.RegionRenderCacheBuilder; import net.minecraft.entity.Entity; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +47,14 @@ public class ChunkRenderWorker { this.regionRenderCacheBuilder = regionRenderCacheBuilderIn; } + private void freeRenderBuilder(ChunkCompileTaskGenerator taskGenerator) { + + } + + private RegionRenderCacheBuilder getRegionRenderCacheBuilder() throws InterruptedException { + return this.regionRenderCacheBuilder; + } + protected void processTask(final ChunkCompileTaskGenerator generator) throws InterruptedException { if (generator.getStatus() != ChunkCompileTaskGenerator.Status.PENDING) { if (!generator.isFinished()) { @@ -113,12 +124,4 @@ public class ChunkRenderWorker { } } - - private RegionRenderCacheBuilder getRegionRenderCacheBuilder() throws InterruptedException { - return this.regionRenderCacheBuilder; - } - - private void freeRenderBuilder(ChunkCompileTaskGenerator taskGenerator) { - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/chunk/CompiledChunk.java b/src/game/java/net/minecraft/client/renderer/chunk/CompiledChunk.java index 91ef903d..5e3198f9 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/CompiledChunk.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/CompiledChunk.java @@ -9,38 +9,41 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CompiledChunk { public static final CompiledChunk DUMMY = new CompiledChunk() { - protected void setLayerUsed(EnumWorldBlockLayer layer) { - throw new UnsupportedOperationException(); + public boolean isVisible(EnumFacing facing, EnumFacing facing2) { + return true; } public void setLayerStarted(EnumWorldBlockLayer layer) { throw new UnsupportedOperationException(); } - public boolean isVisible(EnumFacing facing, EnumFacing facing2) { - return true; + protected void setLayerUsed(EnumWorldBlockLayer layer) { + throw new UnsupportedOperationException(); } }; private final boolean[] layersUsed = new boolean[EnumWorldBlockLayer._VALUES.length]; @@ -51,56 +54,56 @@ public class CompiledChunk { private WorldRenderer.State state; private WorldRenderer.State stateWater; + public void addTileEntity(TileEntity tileEntityIn) { + this.tileEntities.add(tileEntityIn); + } + + public WorldRenderer.State getState() { + return this.state; + } + + public WorldRenderer.State getStateRealisticWater() { + return this.stateWater; + } + + public List getTileEntities() { + return this.tileEntities; + } + public boolean isEmpty() { return this.empty; } + public boolean isLayerEmpty(EnumWorldBlockLayer layer) { + return !this.layersUsed[layer.ordinal()]; + } + + public boolean isLayerStarted(EnumWorldBlockLayer layer) { + return this.layersStarted[layer.ordinal()]; + } + + public boolean isVisible(EnumFacing enumfacing, EnumFacing enumfacing1) { + return this.setVisibility.isVisible(enumfacing, enumfacing1); + } + + public void setLayerStarted(EnumWorldBlockLayer enumworldblocklayer) { + this.layersStarted[enumworldblocklayer.ordinal()] = true; + } + protected void setLayerUsed(EnumWorldBlockLayer enumworldblocklayer) { this.empty = false; this.layersUsed[enumworldblocklayer.ordinal()] = true; } - public boolean isLayerEmpty(EnumWorldBlockLayer layer) { - return !this.layersUsed[layer.ordinal()]; - } - - public void setLayerStarted(EnumWorldBlockLayer enumworldblocklayer) { - this.layersStarted[enumworldblocklayer.ordinal()] = true; - } - - public boolean isLayerStarted(EnumWorldBlockLayer layer) { - return this.layersStarted[layer.ordinal()]; - } - - public List getTileEntities() { - return this.tileEntities; - } - - public void addTileEntity(TileEntity tileEntityIn) { - this.tileEntities.add(tileEntityIn); - } - - public boolean isVisible(EnumFacing enumfacing, EnumFacing enumfacing1) { - return this.setVisibility.isVisible(enumfacing, enumfacing1); - } - - public void setVisibility(SetVisibility visibility) { - this.setVisibility = visibility; - } - - public WorldRenderer.State getState() { - return this.state; - } - public void setState(WorldRenderer.State stateIn) { this.state = stateIn; } - public WorldRenderer.State getStateRealisticWater() { - return this.stateWater; - } - public void setStateRealisticWater(WorldRenderer.State stateIn) { this.stateWater = stateIn; } + + public void setVisibility(SetVisibility visibility) { + this.setVisibility = visibility; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/chunk/IRenderChunkFactory.java b/src/game/java/net/minecraft/client/renderer/chunk/IRenderChunkFactory.java index 58974d63..731d52ca 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/IRenderChunkFactory.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/IRenderChunkFactory.java @@ -4,22 +4,25 @@ import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/chunk/ListChunkFactory.java b/src/game/java/net/minecraft/client/renderer/chunk/ListChunkFactory.java index bccfeaca..1e65c866 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/ListChunkFactory.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/ListChunkFactory.java @@ -4,22 +4,25 @@ import net.minecraft.client.renderer.RenderGlobal; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/chunk/ListedRenderChunk.java b/src/game/java/net/minecraft/client/renderer/chunk/ListedRenderChunk.java index ebf04262..27d8681a 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/ListedRenderChunk.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/ListedRenderChunk.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,10 +41,6 @@ public class ListedRenderChunk extends RenderChunk { } } - public int getDisplayList(EnumWorldBlockLayer layer, CompiledChunk parCompiledChunk) { - return !parCompiledChunk.isLayerEmpty(layer) ? this.baseDisplayList[layer.ordinal()] : -1; - } - public void deleteGlResources() { super.deleteGlResources(); for (int i = 0; i < this.baseDisplayList.length; ++i) { @@ -49,6 +48,10 @@ public class ListedRenderChunk extends RenderChunk { } } + public int getDisplayList(EnumWorldBlockLayer layer, CompiledChunk parCompiledChunk) { + return !parCompiledChunk.isLayerEmpty(layer) ? this.baseDisplayList[layer.ordinal()] : -1; + } + public void rebuildChunk(float x, float y, float z, ChunkCompileTaskGenerator generator) { super.rebuildChunk(x, y, z, generator); EnumWorldBlockLayer[] layers = EnumWorldBlockLayer._VALUES; diff --git a/src/game/java/net/minecraft/client/renderer/chunk/RenderChunk.java b/src/game/java/net/minecraft/client/renderer/chunk/RenderChunk.java index 16290aad..16b1428f 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/RenderChunk.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/RenderChunk.java @@ -1,6 +1,6 @@ package net.minecraft.client.renderer.chunk; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW_MATRIX; import java.util.EnumMap; import java.util.HashSet; @@ -30,22 +30,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,9 +58,9 @@ public class RenderChunk { OUTSIDE, OUTSIDE_BB, INTERSECT, INSIDE } + public static int renderChunksUpdated; private World world; private final RenderGlobal renderGlobal; - public static int renderChunksUpdated; private BlockPos position; public CompiledChunk compiledChunk = CompiledChunk.DUMMY; private ChunkCompileTaskGenerator compileTask = null; @@ -85,49 +88,84 @@ public class RenderChunk { } - public boolean setFrameIndex(int frameIndexIn) { - if (this.frameIndex == frameIndexIn) { - return false; - } else { - this.frameIndex = frameIndexIn; - return true; - } - } - - public void setPosition(BlockPos pos) { + public void deleteGlResources() { this.stopCompileTask(); - this.position = pos; - this.boundingBox = new AxisAlignedBB(pos, pos.add(16, 16, 16)); - - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - this.field_181702_p.put(facings[i], pos.offset(facings[i], 16)); - } - - this.initModelviewMatrix(); + this.world = null; } - public void resortTransparency(float x, float y, float z, ChunkCompileTaskGenerator generator) { - CompiledChunk compiledchunk = generator.getCompiledChunk(); - if (compiledchunk.getState() != null && !compiledchunk.isLayerEmpty(EnumWorldBlockLayer.TRANSLUCENT)) { - this.preRenderBlocks( - generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT), - this.position); - generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT) - .setVertexState(compiledchunk.getState()); - this.postRenderBlocks(EnumWorldBlockLayer.TRANSLUCENT, x, y, z, - generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT), - compiledchunk); + protected void finishCompileTask() { + if (this.compileTask != null && this.compileTask.getStatus() != ChunkCompileTaskGenerator.Status.DONE) { + this.compileTask.finish(); + this.compileTask = null; } - if (DeferredStateManager.isRenderingRealisticWater() && compiledchunk.getStateRealisticWater() != null - && !compiledchunk.isLayerEmpty(EnumWorldBlockLayer.REALISTIC_WATER)) { - this.preRenderBlocks(generator.getRegionRenderCacheBuilder() - .getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER), this.position); - generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER) - .setVertexState(compiledchunk.getStateRealisticWater()); - this.postRenderBlocks(EnumWorldBlockLayer.REALISTIC_WATER, x, y, z, generator.getRegionRenderCacheBuilder() - .getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER), compiledchunk); + } + + public BlockPos func_181701_a(EnumFacing parEnumFacing) { + return (BlockPos) this.field_181702_p.get(parEnumFacing); + } + + public CompiledChunk getCompiledChunk() { + return this.compiledChunk; + } + + public BlockPos getPosition() { + return this.position; + } + + private void initModelviewMatrix() { + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); + float f = 1.000001F; + GlStateManager.translate(-8.0F, -8.0F, -8.0F); + GlStateManager.scale(f, f, f); + GlStateManager.translate(8.0F, 8.0F, 8.0F); + GlStateManager.getFloat(GL_MODELVIEW_MATRIX, this.modelviewMatrix); + GlStateManager.popMatrix(); + } + + public boolean isNeedsUpdate() { + return this.needsUpdate; + } + + public ChunkCompileTaskGenerator makeCompileTaskChunk() { + ChunkCompileTaskGenerator chunkcompiletaskgenerator; + this.finishCompileTask(); + this.compileTask = new ChunkCompileTaskGenerator(this, ChunkCompileTaskGenerator.Type.REBUILD_CHUNK); + chunkcompiletaskgenerator = this.compileTask; + return chunkcompiletaskgenerator; + } + + public ChunkCompileTaskGenerator makeCompileTaskTransparency() { + this.compileTask = new ChunkCompileTaskGenerator(this, ChunkCompileTaskGenerator.Type.RESORT_TRANSPARENCY); + this.compileTask.setCompiledChunk(this.compiledChunk); + return this.compileTask; + } + + public void multModelviewMatrix() { + GlStateManager.multMatrix(this.modelviewMatrix); + } + + private void postRenderBlocks(EnumWorldBlockLayer layer, float x, float y, float z, WorldRenderer worldRendererIn, + CompiledChunk compiledChunkIn) { + if ((layer == EnumWorldBlockLayer.TRANSLUCENT || layer == EnumWorldBlockLayer.REALISTIC_WATER) + && !compiledChunkIn.isLayerEmpty(layer)) { + worldRendererIn.func_181674_a(x, y, z); + if (layer == EnumWorldBlockLayer.REALISTIC_WATER) { + compiledChunkIn.setStateRealisticWater(worldRendererIn.func_181672_a()); + } else { + compiledChunkIn.setState(worldRendererIn.func_181672_a()); + } } + + worldRendererIn.finishDrawing(); + } + + private void preRenderBlocks(WorldRenderer worldRendererIn, BlockPos pos) { + worldRendererIn.begin(7, + (DeferredStateManager.isDeferredRenderer() || DynamicLightsStateManager.isDynamicLightsRender()) + ? VertexFormat.BLOCK_SHADERS + : DefaultVertexFormats.BLOCK); + worldRendererIn.setTranslation((double) (-pos.getX()), (double) (-pos.getY()), (double) (-pos.getZ())); } public void rebuildChunk(float x, float y, float z, ChunkCompileTaskGenerator generator) { @@ -224,96 +262,61 @@ public class RenderChunk { } - protected void finishCompileTask() { - if (this.compileTask != null && this.compileTask.getStatus() != ChunkCompileTaskGenerator.Status.DONE) { - this.compileTask.finish(); - this.compileTask = null; + public void resortTransparency(float x, float y, float z, ChunkCompileTaskGenerator generator) { + CompiledChunk compiledchunk = generator.getCompiledChunk(); + if (compiledchunk.getState() != null && !compiledchunk.isLayerEmpty(EnumWorldBlockLayer.TRANSLUCENT)) { + this.preRenderBlocks( + generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT), + this.position); + generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT) + .setVertexState(compiledchunk.getState()); + this.postRenderBlocks(EnumWorldBlockLayer.TRANSLUCENT, x, y, z, + generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT), + compiledchunk); } - } - - public ChunkCompileTaskGenerator makeCompileTaskChunk() { - ChunkCompileTaskGenerator chunkcompiletaskgenerator; - this.finishCompileTask(); - this.compileTask = new ChunkCompileTaskGenerator(this, ChunkCompileTaskGenerator.Type.REBUILD_CHUNK); - chunkcompiletaskgenerator = this.compileTask; - return chunkcompiletaskgenerator; - } - - public ChunkCompileTaskGenerator makeCompileTaskTransparency() { - this.compileTask = new ChunkCompileTaskGenerator(this, ChunkCompileTaskGenerator.Type.RESORT_TRANSPARENCY); - this.compileTask.setCompiledChunk(this.compiledChunk); - return this.compileTask; - } - - private void preRenderBlocks(WorldRenderer worldRendererIn, BlockPos pos) { - worldRendererIn.begin(7, - (DeferredStateManager.isDeferredRenderer() || DynamicLightsStateManager.isDynamicLightsRender()) - ? VertexFormat.BLOCK_SHADERS - : DefaultVertexFormats.BLOCK); - worldRendererIn.setTranslation((double) (-pos.getX()), (double) (-pos.getY()), (double) (-pos.getZ())); - } - - private void postRenderBlocks(EnumWorldBlockLayer layer, float x, float y, float z, WorldRenderer worldRendererIn, - CompiledChunk compiledChunkIn) { - if ((layer == EnumWorldBlockLayer.TRANSLUCENT || layer == EnumWorldBlockLayer.REALISTIC_WATER) - && !compiledChunkIn.isLayerEmpty(layer)) { - worldRendererIn.func_181674_a(x, y, z); - if (layer == EnumWorldBlockLayer.REALISTIC_WATER) { - compiledChunkIn.setStateRealisticWater(worldRendererIn.func_181672_a()); - } else { - compiledChunkIn.setState(worldRendererIn.func_181672_a()); - } + if (DeferredStateManager.isRenderingRealisticWater() && compiledchunk.getStateRealisticWater() != null + && !compiledchunk.isLayerEmpty(EnumWorldBlockLayer.REALISTIC_WATER)) { + this.preRenderBlocks(generator.getRegionRenderCacheBuilder() + .getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER), this.position); + generator.getRegionRenderCacheBuilder().getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER) + .setVertexState(compiledchunk.getStateRealisticWater()); + this.postRenderBlocks(EnumWorldBlockLayer.REALISTIC_WATER, x, y, z, generator.getRegionRenderCacheBuilder() + .getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER), compiledchunk); } - - worldRendererIn.finishDrawing(); - } - - private void initModelviewMatrix() { - GlStateManager.pushMatrix(); - GlStateManager.loadIdentity(); - float f = 1.000001F; - GlStateManager.translate(-8.0F, -8.0F, -8.0F); - GlStateManager.scale(f, f, f); - GlStateManager.translate(8.0F, 8.0F, 8.0F); - GlStateManager.getFloat(GL_MODELVIEW_MATRIX, this.modelviewMatrix); - GlStateManager.popMatrix(); - } - - public void multModelviewMatrix() { - GlStateManager.multMatrix(this.modelviewMatrix); - } - - public CompiledChunk getCompiledChunk() { - return this.compiledChunk; } public void setCompiledChunk(CompiledChunk compiledChunkIn) { this.compiledChunk = compiledChunkIn; } - public void stopCompileTask() { - this.finishCompileTask(); - this.compiledChunk = CompiledChunk.DUMMY; - } - - public void deleteGlResources() { - this.stopCompileTask(); - this.world = null; - } - - public BlockPos getPosition() { - return this.position; + public boolean setFrameIndex(int frameIndexIn) { + if (this.frameIndex == frameIndexIn) { + return false; + } else { + this.frameIndex = frameIndexIn; + return true; + } } public void setNeedsUpdate(boolean needsUpdateIn) { this.needsUpdate = needsUpdateIn; } - public boolean isNeedsUpdate() { - return this.needsUpdate; + public void setPosition(BlockPos pos) { + this.stopCompileTask(); + this.position = pos; + this.boundingBox = new AxisAlignedBB(pos, pos.add(16, 16, 16)); + + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + this.field_181702_p.put(facings[i], pos.offset(facings[i], 16)); + } + + this.initModelviewMatrix(); } - public BlockPos func_181701_a(EnumFacing parEnumFacing) { - return (BlockPos) this.field_181702_p.get(parEnumFacing); + public void stopCompileTask() { + this.finishCompileTask(); + this.compiledChunk = CompiledChunk.DUMMY; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/chunk/SetVisibility.java b/src/game/java/net/minecraft/client/renderer/chunk/SetVisibility.java index a00a8d34..7357c94b 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/SetVisibility.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/SetVisibility.java @@ -5,22 +5,25 @@ import java.util.Set; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,6 +36,14 @@ public class SetVisibility { this.bitSet = new BitSet(COUNT_FACES * COUNT_FACES); } + public boolean isVisible(EnumFacing facing, EnumFacing facing2) { + return this.bitSet.get(facing.ordinal() + facing2.ordinal() * COUNT_FACES); + } + + public void setAllVisible(boolean visible) { + this.bitSet.set(0, this.bitSet.size(), visible); + } + public void setManyVisible(Set parSet) { EnumFacing[] facings = EnumFacing._VALUES; for (int i = 0; i < facings.length; ++i) { @@ -48,14 +59,6 @@ public class SetVisibility { this.bitSet.set(facing2.ordinal() + facing.ordinal() * COUNT_FACES, parFlag); } - public void setAllVisible(boolean visible) { - this.bitSet.set(0, this.bitSet.size(), visible); - } - - public boolean isVisible(EnumFacing facing, EnumFacing facing2) { - return this.bitSet.get(facing.ordinal() + facing2.ordinal() * COUNT_FACES); - } - public String toString() { StringBuilder stringbuilder = new StringBuilder(); stringbuilder.append(' '); diff --git a/src/game/java/net/minecraft/client/renderer/chunk/VisGraph.java b/src/game/java/net/minecraft/client/renderer/chunk/VisGraph.java index 4c6c27d0..9103ea92 100644 --- a/src/game/java/net/minecraft/client/renderer/chunk/VisGraph.java +++ b/src/game/java/net/minecraft/client/renderer/chunk/VisGraph.java @@ -11,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.IntegerCache; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,13 +38,22 @@ public class VisGraph { private static final int field_178616_a = (int) Math.pow(16.0D, 0.0D); private static final int field_178614_b = (int) Math.pow(16.0D, 1.0D); private static final int field_178615_c = (int) Math.pow(16.0D, 2.0D); - private final BitSet field_178612_d = new BitSet(4096); private static final int[] field_178613_e = new int[1352]; - private int field_178611_f = 4096; + static { + boolean flag = false; + boolean flag1 = true; + int i = 0; + + for (int j = 0; j < 16; ++j) { + for (int k = 0; k < 16; ++k) { + for (int l = 0; l < 16; ++l) { + if (j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) { + field_178613_e[i++] = getIndex(j, k, l); + } + } + } + } - public void func_178606_a(BlockPos pos) { - this.field_178612_d.set(getIndex(pos), true); - --this.field_178611_f; } private static int getIndex(BlockPos pos) { @@ -52,6 +64,10 @@ public class VisGraph { return x << 0 | y << 8 | z << 4; } + private final BitSet field_178612_d = new BitSet(4096); + + private int field_178611_f = 4096; + public SetVisibility computeVisibility() { SetVisibility setvisibility = new SetVisibility(); if (4096 - this.field_178611_f < 256) { @@ -69,58 +85,6 @@ public class VisGraph { return setvisibility; } - public Set func_178609_b(BlockPos pos) { - return this.func_178604_a(getIndex(pos)); - } - - private Set func_178604_a(int parInt1) { - EnumSet enumset = EnumSet.noneOf(EnumFacing.class); - LinkedList linkedlist = Lists.newLinkedList(); - linkedlist.add(IntegerCache.func_181756_a(parInt1)); - this.field_178612_d.set(parInt1, true); - - while (!linkedlist.isEmpty()) { - int i = ((Integer) linkedlist.poll()).intValue(); - this.func_178610_a(i, enumset); - - EnumFacing[] facings = EnumFacing._VALUES; - for (int k = 0; k < facings.length; ++k) { - EnumFacing enumfacing = facings[k]; - int j = this.func_178603_a(i, enumfacing); - if (j >= 0 && !this.field_178612_d.get(j)) { - this.field_178612_d.set(j, true); - linkedlist.add(IntegerCache.func_181756_a(j)); - } - } - } - - return enumset; - } - - private void func_178610_a(int parInt1, Set parSet) { - int i = parInt1 >> 0 & 15; - if (i == 0) { - parSet.add(EnumFacing.WEST); - } else if (i == 15) { - parSet.add(EnumFacing.EAST); - } - - int j = parInt1 >> 8 & 15; - if (j == 0) { - parSet.add(EnumFacing.DOWN); - } else if (j == 15) { - parSet.add(EnumFacing.UP); - } - - int k = parInt1 >> 4 & 15; - if (k == 0) { - parSet.add(EnumFacing.NORTH); - } else if (k == 15) { - parSet.add(EnumFacing.SOUTH); - } - - } - private int func_178603_a(int parInt1, EnumFacing parEnumFacing) { switch (parEnumFacing) { case DOWN: @@ -164,20 +128,60 @@ public class VisGraph { } } - static { - boolean flag = false; - boolean flag1 = true; - int i = 0; + private Set func_178604_a(int parInt1) { + EnumSet enumset = EnumSet.noneOf(EnumFacing.class); + LinkedList linkedlist = Lists.newLinkedList(); + linkedlist.add(IntegerCache.func_181756_a(parInt1)); + this.field_178612_d.set(parInt1, true); - for (int j = 0; j < 16; ++j) { - for (int k = 0; k < 16; ++k) { - for (int l = 0; l < 16; ++l) { - if (j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) { - field_178613_e[i++] = getIndex(j, k, l); - } + while (!linkedlist.isEmpty()) { + int i = ((Integer) linkedlist.poll()).intValue(); + this.func_178610_a(i, enumset); + + EnumFacing[] facings = EnumFacing._VALUES; + for (int k = 0; k < facings.length; ++k) { + EnumFacing enumfacing = facings[k]; + int j = this.func_178603_a(i, enumfacing); + if (j >= 0 && !this.field_178612_d.get(j)) { + this.field_178612_d.set(j, true); + linkedlist.add(IntegerCache.func_181756_a(j)); } } } + return enumset; + } + + public void func_178606_a(BlockPos pos) { + this.field_178612_d.set(getIndex(pos), true); + --this.field_178611_f; + } + + public Set func_178609_b(BlockPos pos) { + return this.func_178604_a(getIndex(pos)); + } + + private void func_178610_a(int parInt1, Set parSet) { + int i = parInt1 >> 0 & 15; + if (i == 0) { + parSet.add(EnumFacing.WEST); + } else if (i == 15) { + parSet.add(EnumFacing.EAST); + } + + int j = parInt1 >> 8 & 15; + if (j == 0) { + parSet.add(EnumFacing.DOWN); + } else if (j == 15) { + parSet.add(EnumFacing.UP); + } + + int k = parInt1 >> 4 & 15; + if (k == 0) { + parSet.add(EnumFacing.NORTH); + } else if (k == 15) { + parSet.add(EnumFacing.SOUTH); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/culling/ClippingHelper.java b/src/game/java/net/minecraft/client/renderer/culling/ClippingHelper.java index c0c25938..d4c529a6 100644 --- a/src/game/java/net/minecraft/client/renderer/culling/ClippingHelper.java +++ b/src/game/java/net/minecraft/client/renderer/culling/ClippingHelper.java @@ -1,21 +1,24 @@ package net.minecraft.client.renderer.culling; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,9 +34,9 @@ public class ClippingHelper { + (double) parArrayOfFloat[2] * parDouble3 + (double) parArrayOfFloat[3]; } - /**+ - * Returns true if the box is inside all 6 clipping planes, - * otherwise returns false. + /** + * + Returns true if the box is inside all 6 clipping planes, otherwise returns + * false. */ public boolean isBoxInFrustum(double parDouble1, double parDouble2, double parDouble3, double parDouble4, double parDouble5, double parDouble6) { diff --git a/src/game/java/net/minecraft/client/renderer/culling/ClippingHelperImpl.java b/src/game/java/net/minecraft/client/renderer/culling/ClippingHelperImpl.java index 2ecbc13c..993b7332 100644 --- a/src/game/java/net/minecraft/client/renderer/culling/ClippingHelperImpl.java +++ b/src/game/java/net/minecraft/client/renderer/culling/ClippingHelperImpl.java @@ -1,26 +1,30 @@ package net.minecraft.client.renderer.culling; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION_MATRIX; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,9 +32,8 @@ import net.minecraft.util.MathHelper; public class ClippingHelperImpl extends ClippingHelper { private static ClippingHelperImpl instance = new ClippingHelperImpl(); - /**+ - * Initialises the ClippingHelper object then returns an - * instance of it. + /** + * + Initialises the ClippingHelper object then returns an instance of it. */ public static ClippingHelper getInstance() { instance.init(); @@ -38,13 +41,7 @@ public class ClippingHelperImpl extends ClippingHelper { return instance; } - private void normalize(float[] parArrayOfFloat) { - float f = MathHelper.sqrt_float(parArrayOfFloat[0] * parArrayOfFloat[0] - + parArrayOfFloat[1] * parArrayOfFloat[1] + parArrayOfFloat[2] * parArrayOfFloat[2]); - parArrayOfFloat[0] /= f; - parArrayOfFloat[1] /= f; - parArrayOfFloat[2] /= f; - parArrayOfFloat[3] /= f; + public void destroy() { } public void init() { @@ -122,7 +119,13 @@ public class ClippingHelperImpl extends ClippingHelper { this.normalize(afloat7); } - public void destroy() { + private void normalize(float[] parArrayOfFloat) { + float f = MathHelper.sqrt_float(parArrayOfFloat[0] * parArrayOfFloat[0] + + parArrayOfFloat[1] * parArrayOfFloat[1] + parArrayOfFloat[2] * parArrayOfFloat[2]); + parArrayOfFloat[0] /= f; + parArrayOfFloat[1] /= f; + parArrayOfFloat[2] /= f; + parArrayOfFloat[3] /= f; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/culling/Frustum.java b/src/game/java/net/minecraft/client/renderer/culling/Frustum.java index 29f231b9..b2833537 100644 --- a/src/game/java/net/minecraft/client/renderer/culling/Frustum.java +++ b/src/game/java/net/minecraft/client/renderer/culling/Frustum.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer.culling; import net.minecraft.util.AxisAlignedBB; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,15 +39,18 @@ public class Frustum implements ICamera { this.clippingHelper = parClippingHelper; } - public void setPosition(double d0, double d1, double d2) { - this.xPosition = d0; - this.yPosition = d1; - this.zPosition = d2; + /** + * + Returns true if the bounding box is inside all 6 clipping planes, otherwise + * returns false. + */ + public boolean isBoundingBoxInFrustum(AxisAlignedBB axisalignedbb) { + return this.isBoxInFrustum(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ, axisalignedbb.maxX, + axisalignedbb.maxY, axisalignedbb.maxZ); } - /**+ - * Calls the clipping helper. Returns true if the box is inside - * all 6 clipping planes, otherwise returns false. + /** + * + Calls the clipping helper. Returns true if the box is inside all 6 clipping + * planes, otherwise returns false. */ public boolean isBoxInFrustum(double parDouble1, double parDouble2, double parDouble3, double parDouble4, double parDouble5, double parDouble6) { @@ -53,12 +59,9 @@ public class Frustum implements ICamera { parDouble6 - this.zPosition); } - /**+ - * Returns true if the bounding box is inside all 6 clipping - * planes, otherwise returns false. - */ - public boolean isBoundingBoxInFrustum(AxisAlignedBB axisalignedbb) { - return this.isBoxInFrustum(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ, axisalignedbb.maxX, - axisalignedbb.maxY, axisalignedbb.maxZ); + public void setPosition(double d0, double d1, double d2) { + this.xPosition = d0; + this.yPosition = d1; + this.zPosition = d2; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/culling/ICamera.java b/src/game/java/net/minecraft/client/renderer/culling/ICamera.java index 07ff32aa..ede89a59 100644 --- a/src/game/java/net/minecraft/client/renderer/culling/ICamera.java +++ b/src/game/java/net/minecraft/client/renderer/culling/ICamera.java @@ -2,30 +2,33 @@ package net.minecraft.client.renderer.culling; import net.minecraft.util.AxisAlignedBB; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ICamera { - /**+ - * Returns true if the bounding box is inside all 6 clipping - * planes, otherwise returns false. + /** + * + Returns true if the bounding box is inside all 6 clipping planes, otherwise + * returns false. */ boolean isBoundingBoxInFrustum(AxisAlignedBB var1); diff --git a/src/game/java/net/minecraft/client/renderer/entity/ArmorStandRenderer.java b/src/game/java/net/minecraft/client/renderer/entity/ArmorStandRenderer.java index 265f797e..452f80f5 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/ArmorStandRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/entity/ArmorStandRenderer.java @@ -9,30 +9,33 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ArmorStandRenderer extends RendererLivingEntity { - /**+ - * A constant instance of the armor stand texture, wrapped - * inside a ResourceLocation wrapper. + /** + * + A constant instance of the armor stand texture, wrapped inside a + * ResourceLocation wrapper. */ public static final ResourceLocation TEXTURE_ARMOR_STAND = new ResourceLocation( "textures/entity/armorstand/wood.png"); @@ -50,9 +53,13 @@ public class ArmorStandRenderer extends RendererLivingEntity { this.addLayer(new LayerCustomHead(this.getMainModel().bipedHead)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + protected boolean canRenderName(EntityArmorStand entityarmorstand) { + return entityarmorstand.getAlwaysRenderNameTag(); + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityArmorStand var1) { return TEXTURE_ARMOR_STAND; @@ -65,8 +72,4 @@ public class ArmorStandRenderer extends RendererLivingEntity { protected void rotateCorpse(EntityArmorStand var1, float var2, float f, float var4) { GlStateManager.rotate(180.0F - f, 0.0F, 1.0F, 0.0F); } - - protected boolean canRenderName(EntityArmorStand entityarmorstand) { - return entityarmorstand.getAlwaysRenderNameTag(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/Render.java b/src/game/java/net/minecraft/client/renderer/entity/Render.java index 5650ed71..b5346102 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/Render.java +++ b/src/game/java/net/minecraft/client/renderer/entity/Render.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; @@ -28,33 +29,83 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class Render { private static final ResourceLocation shadowTextures = new ResourceLocation("textures/misc/shadow.png"); + + public static void renderNameAdapter(Render r, Entity e, double x, double y, double z) { + r.renderName(e, x, y, z); + } + + /** + * + Renders a white box with the bounds of the AABB translated by the offset. + * Args: aabb, x, y, z + */ + public static void renderOffsetAABB(AxisAlignedBB boundingBox, double x, double y, double z) { + GlStateManager.disableTexture2D(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + worldrenderer.setTranslation(x, y, z); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_NORMAL); + worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).normal(0.0F, -1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).normal(0.0F, -1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, -1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, -1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 1.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).normal(1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).normal(1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).normal(1.0F, 0.0F, 0.0F).endVertex(); + worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).normal(1.0F, 0.0F, 0.0F).endVertex(); + tessellator.draw(); + worldrenderer.setTranslation(0.0D, 0.0D, 0.0D); + GlStateManager.enableTexture2D(); + } + protected final RenderManager renderManager; + protected float shadowSize; - /**+ - * Determines the darkness of the object's shadow. Higher value - * makes a darker shadow. + + /** + * + Determines the darkness of the object's shadow. Higher value makes a darker + * shadow. */ protected float shadowOpaque = 1.0F; @@ -62,55 +113,6 @@ public abstract class Render { this.renderManager = renderManager; } - public boolean shouldRender(T livingEntity, ICamera camera, double camX, double camY, double camZ) { - if (DeferredStateManager.isEnableShadowRender()) { - return true; - } - AxisAlignedBB axisalignedbb = livingEntity.getEntityBoundingBox(); - if (axisalignedbb.func_181656_b() || axisalignedbb.getAverageEdgeLength() == 0.0D) { - axisalignedbb = new AxisAlignedBB(livingEntity.posX - 2.0D, livingEntity.posY - 2.0D, - livingEntity.posZ - 2.0D, livingEntity.posX + 2.0D, livingEntity.posY + 2.0D, - livingEntity.posZ + 2.0D); - } - - return livingEntity.isInRangeToRender3d(camX, camY, camZ) - && (livingEntity.ignoreFrustumCheck || camera.isBoundingBoxInFrustum(axisalignedbb)); - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe - */ - public void doRender(T entity, double d0, double d1, double d2, float var8, float var9) { - this.renderName(entity, d0, d1, d2); - } - - protected void renderName(T entity, double x, double y, double z) { - if (this.canRenderName(entity)) { - this.renderLivingLabel(entity, entity.getDisplayNameProfanityFilter().getFormattedText(), x, y, z, 64); - } - } - - public static void renderNameAdapter(Render r, Entity e, double x, double y, double z) { - r.renderName(e, x, y, z); - } - - protected boolean canRenderName(T entity) { - return entity.getAlwaysRenderNameTagForRender() && entity.hasCustomName(); - } - - protected void renderOffsetLivingLabel(T entityIn, double x, double y, double z, String str, float parFloat1, - double parDouble4) { - this.renderLivingLabel(entityIn, str, x, y, z, 64); - } - - protected abstract ResourceLocation getEntityTexture(T var1); - protected boolean bindEntityTexture(T entity) { ResourceLocation resourcelocation = this.getEntityTexture(entity); if (resourcelocation == null) { @@ -125,9 +127,100 @@ public abstract class Render { this.renderManager.renderEngine.bindTexture(location); } - /**+ - * Renders fire on top of the entity. Args: entity, x, y, z, - * partialTickTime + protected boolean canRenderName(T entity) { + return entity.getAlwaysRenderNameTagForRender() && entity.hasCustomName(); + } + + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe + */ + public void doRender(T entity, double d0, double d1, double d2, float var8, float var9) { + this.renderName(entity, d0, d1, d2); + } + + /** + * + Renders the entity's shadow and fire (if its on fire). Args: entity, x, y, + * z, yaw, partialTickTime + */ + public void doRenderShadowAndFire(Entity entityIn, double x, double y, double z, float yaw, float partialTicks) { + if (this.renderManager.options != null) { + if (!DeferredStateManager.isInDeferredPass() && this.renderManager.options.field_181151_V + && this.shadowSize > 0.0F && !entityIn.isInvisible() && this.renderManager.isRenderShadow()) { + double d0 = this.renderManager.getDistanceToCamera(entityIn.posX, entityIn.posY, entityIn.posZ); + float f = (float) ((1.0D - d0 / 256.0D) * (double) this.shadowOpaque); + if (f > 0.0F) { + this.renderShadow(entityIn, x, y, z, f, partialTicks); + } + } + + if (entityIn.canRenderOnFire() + && (!(entityIn instanceof EntityPlayer) || !((EntityPlayer) entityIn).isSpectator())) { + this.renderEntityOnFire(entityIn, x, y, z, partialTicks); + } + + } + } + + private void func_180549_a(Block blockIn, double pos, double parDouble2, double parDouble3, BlockPos parBlockPos, + float parFloat1, float parFloat2, double parDouble4, double parDouble5, double parDouble6) { + if (blockIn.isFullCube()) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + double d0 = ((double) parFloat1 - (parDouble2 - ((double) parBlockPos.getY() + parDouble5)) / 2.0D) * 0.5D + * (double) this.getWorldFromRenderManager().getLightBrightness(parBlockPos); + if (d0 >= 0.0D) { + if (d0 > 1.0D) { + d0 = 1.0D; + } + + double d1 = (double) parBlockPos.getX() + blockIn.getBlockBoundsMinX() + parDouble4; + double d2 = (double) parBlockPos.getX() + blockIn.getBlockBoundsMaxX() + parDouble4; + double d3 = (double) parBlockPos.getY() + blockIn.getBlockBoundsMinY() + parDouble5 + 0.015625D; + double d4 = (double) parBlockPos.getZ() + blockIn.getBlockBoundsMinZ() + parDouble6; + double d5 = (double) parBlockPos.getZ() + blockIn.getBlockBoundsMaxZ() + parDouble6; + float f = (float) ((pos - d1) / 2.0D / (double) parFloat2 + 0.5D); + float f1 = (float) ((pos - d2) / 2.0D / (double) parFloat2 + 0.5D); + float f2 = (float) ((parDouble3 - d4) / 2.0D / (double) parFloat2 + 0.5D); + float f3 = (float) ((parDouble3 - d5) / 2.0D / (double) parFloat2 + 0.5D); + worldrenderer.pos(d1, d3, d4).tex((double) f, (double) f2).color(1.0F, 1.0F, 1.0F, (float) d0) + .endVertex(); + worldrenderer.pos(d1, d3, d5).tex((double) f, (double) f3).color(1.0F, 1.0F, 1.0F, (float) d0) + .endVertex(); + worldrenderer.pos(d2, d3, d5).tex((double) f1, (double) f3).color(1.0F, 1.0F, 1.0F, (float) d0) + .endVertex(); + worldrenderer.pos(d2, d3, d4).tex((double) f1, (double) f2).color(1.0F, 1.0F, 1.0F, (float) d0) + .endVertex(); + } + } + } + + protected abstract ResourceLocation getEntityTexture(T var1); + + /** + * + Returns the font renderer from the set render manager + */ + public FontRenderer getFontRendererFromRenderManager() { + return this.renderManager.getFontRenderer(); + } + + public RenderManager getRenderManager() { + return this.renderManager; + } + + /** + * + Returns the render manager's world object + */ + private World getWorldFromRenderManager() { + return this.renderManager.worldObj; + } + + /** + * + Renders fire on top of the entity. Args: entity, x, y, z, partialTickTime */ private void renderEntityOnFire(Entity entity, double x, double y, double z, float partialTicks) { if (entity.width == 0 || entity.height == 0) { @@ -187,167 +280,8 @@ public abstract class Render { GlStateManager.enableLighting(); } - /**+ - * Renders the entity shadows at the position, shadow alpha and - * partialTickTime. Args: entity, x, y, z, shadowAlpha, - * partialTickTime - */ - private void renderShadow(Entity entityIn, double x, double y, double z, float shadowAlpha, float partialTicks) { - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - this.renderManager.renderEngine.bindTexture(shadowTextures); - World world = this.getWorldFromRenderManager(); - GlStateManager.depthMask(false); - float f = this.shadowSize; - if (entityIn instanceof EntityLiving) { - EntityLiving entityliving = (EntityLiving) entityIn; - f *= entityliving.getRenderSizeModifier(); - if (entityliving.isChild()) { - f *= 0.5F; - } - } - - double d5 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double) partialTicks; - double d0 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double) partialTicks; - double d1 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; - int i = MathHelper.floor_double(d5 - (double) f); - int j = MathHelper.floor_double(d5 + (double) f); - int k = MathHelper.floor_double(d0 - (double) f); - int l = MathHelper.floor_double(d0); - int i1 = MathHelper.floor_double(d1 - (double) f); - int j1 = MathHelper.floor_double(d1 + (double) f); - double d2 = x - d5; - double d3 = y - d0; - double d4 = z - d1; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); - - for (BlockPos blockpos : BlockPos.getAllInBoxMutable(new BlockPos(i, k, i1), new BlockPos(j, l, j1))) { - Block block = world.getBlockState(blockpos.down()).getBlock(); - if (block.getRenderType() != -1 && world.getLightFromNeighbors(blockpos) > 3) { - this.func_180549_a(block, x, y, z, blockpos, shadowAlpha, f, d2, d3, d4); - } - } - - tessellator.draw(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.disableBlend(); - GlStateManager.depthMask(true); - } - - /**+ - * Returns the render manager's world object - */ - private World getWorldFromRenderManager() { - return this.renderManager.worldObj; - } - - private void func_180549_a(Block blockIn, double pos, double parDouble2, double parDouble3, BlockPos parBlockPos, - float parFloat1, float parFloat2, double parDouble4, double parDouble5, double parDouble6) { - if (blockIn.isFullCube()) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - double d0 = ((double) parFloat1 - (parDouble2 - ((double) parBlockPos.getY() + parDouble5)) / 2.0D) * 0.5D - * (double) this.getWorldFromRenderManager().getLightBrightness(parBlockPos); - if (d0 >= 0.0D) { - if (d0 > 1.0D) { - d0 = 1.0D; - } - - double d1 = (double) parBlockPos.getX() + blockIn.getBlockBoundsMinX() + parDouble4; - double d2 = (double) parBlockPos.getX() + blockIn.getBlockBoundsMaxX() + parDouble4; - double d3 = (double) parBlockPos.getY() + blockIn.getBlockBoundsMinY() + parDouble5 + 0.015625D; - double d4 = (double) parBlockPos.getZ() + blockIn.getBlockBoundsMinZ() + parDouble6; - double d5 = (double) parBlockPos.getZ() + blockIn.getBlockBoundsMaxZ() + parDouble6; - float f = (float) ((pos - d1) / 2.0D / (double) parFloat2 + 0.5D); - float f1 = (float) ((pos - d2) / 2.0D / (double) parFloat2 + 0.5D); - float f2 = (float) ((parDouble3 - d4) / 2.0D / (double) parFloat2 + 0.5D); - float f3 = (float) ((parDouble3 - d5) / 2.0D / (double) parFloat2 + 0.5D); - worldrenderer.pos(d1, d3, d4).tex((double) f, (double) f2).color(1.0F, 1.0F, 1.0F, (float) d0) - .endVertex(); - worldrenderer.pos(d1, d3, d5).tex((double) f, (double) f3).color(1.0F, 1.0F, 1.0F, (float) d0) - .endVertex(); - worldrenderer.pos(d2, d3, d5).tex((double) f1, (double) f3).color(1.0F, 1.0F, 1.0F, (float) d0) - .endVertex(); - worldrenderer.pos(d2, d3, d4).tex((double) f1, (double) f2).color(1.0F, 1.0F, 1.0F, (float) d0) - .endVertex(); - } - } - } - - /**+ - * Renders a white box with the bounds of the AABB translated by - * the offset. Args: aabb, x, y, z - */ - public static void renderOffsetAABB(AxisAlignedBB boundingBox, double x, double y, double z) { - GlStateManager.disableTexture2D(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - worldrenderer.setTranslation(x, y, z); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_NORMAL); - worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).normal(0.0F, 0.0F, -1.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 0.0F, 1.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).normal(0.0F, -1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).normal(0.0F, -1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, -1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).normal(0.0F, -1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).normal(0.0F, 1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).normal(0.0F, 1.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).normal(-1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).normal(1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).normal(1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).normal(1.0F, 0.0F, 0.0F).endVertex(); - worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).normal(1.0F, 0.0F, 0.0F).endVertex(); - tessellator.draw(); - worldrenderer.setTranslation(0.0D, 0.0D, 0.0D); - GlStateManager.enableTexture2D(); - } - - /**+ - * Renders the entity's shadow and fire (if its on fire). Args: - * entity, x, y, z, yaw, partialTickTime - */ - public void doRenderShadowAndFire(Entity entityIn, double x, double y, double z, float yaw, float partialTicks) { - if (this.renderManager.options != null) { - if (!DeferredStateManager.isInDeferredPass() && this.renderManager.options.field_181151_V - && this.shadowSize > 0.0F && !entityIn.isInvisible() && this.renderManager.isRenderShadow()) { - double d0 = this.renderManager.getDistanceToCamera(entityIn.posX, entityIn.posY, entityIn.posZ); - float f = (float) ((1.0D - d0 / 256.0D) * (double) this.shadowOpaque); - if (f > 0.0F) { - this.renderShadow(entityIn, x, y, z, f, partialTicks); - } - } - - if (entityIn.canRenderOnFire() - && (!(entityIn instanceof EntityPlayer) || !((EntityPlayer) entityIn).isSpectator())) { - this.renderEntityOnFire(entityIn, x, y, z, partialTicks); - } - - } - } - - /**+ - * Returns the font renderer from the set render manager - */ - public FontRenderer getFontRendererFromRenderManager() { - return this.renderManager.getFontRenderer(); - } - - /**+ - * Renders an entity's name above its head + /** + * + Renders an entity's name above its head */ public void renderLivingLabel(T entityIn, String str, double x, double y, double z, int maxDistance) { double d0 = entityIn.getDistanceSqToEntity(this.renderManager.livingPlayer); @@ -404,7 +338,77 @@ public abstract class Render { } } - public RenderManager getRenderManager() { - return this.renderManager; + protected void renderName(T entity, double x, double y, double z) { + if (this.canRenderName(entity)) { + this.renderLivingLabel(entity, entity.getDisplayNameProfanityFilter().getFormattedText(), x, y, z, 64); + } + } + + protected void renderOffsetLivingLabel(T entityIn, double x, double y, double z, String str, float parFloat1, + double parDouble4) { + this.renderLivingLabel(entityIn, str, x, y, z, 64); + } + + /** + * + Renders the entity shadows at the position, shadow alpha and + * partialTickTime. Args: entity, x, y, z, shadowAlpha, partialTickTime + */ + private void renderShadow(Entity entityIn, double x, double y, double z, float shadowAlpha, float partialTicks) { + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + this.renderManager.renderEngine.bindTexture(shadowTextures); + World world = this.getWorldFromRenderManager(); + GlStateManager.depthMask(false); + float f = this.shadowSize; + if (entityIn instanceof EntityLiving) { + EntityLiving entityliving = (EntityLiving) entityIn; + f *= entityliving.getRenderSizeModifier(); + if (entityliving.isChild()) { + f *= 0.5F; + } + } + + double d5 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double) partialTicks; + double d0 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double) partialTicks; + double d1 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; + int i = MathHelper.floor_double(d5 - (double) f); + int j = MathHelper.floor_double(d5 + (double) f); + int k = MathHelper.floor_double(d0 - (double) f); + int l = MathHelper.floor_double(d0); + int i1 = MathHelper.floor_double(d1 - (double) f); + int j1 = MathHelper.floor_double(d1 + (double) f); + double d2 = x - d5; + double d3 = y - d0; + double d4 = z - d1; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX_COLOR); + + for (BlockPos blockpos : BlockPos.getAllInBoxMutable(new BlockPos(i, k, i1), new BlockPos(j, l, j1))) { + Block block = world.getBlockState(blockpos.down()).getBlock(); + if (block.getRenderType() != -1 && world.getLightFromNeighbors(blockpos) > 3) { + this.func_180549_a(block, x, y, z, blockpos, shadowAlpha, f, d2, d3, d4); + } + } + + tessellator.draw(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.disableBlend(); + GlStateManager.depthMask(true); + } + + public boolean shouldRender(T livingEntity, ICamera camera, double camX, double camY, double camZ) { + if (DeferredStateManager.isEnableShadowRender()) { + return true; + } + AxisAlignedBB axisalignedbb = livingEntity.getEntityBoundingBox(); + if (axisalignedbb.func_181656_b() || axisalignedbb.getAverageEdgeLength() == 0.0D) { + axisalignedbb = new AxisAlignedBB(livingEntity.posX - 2.0D, livingEntity.posY - 2.0D, + livingEntity.posZ - 2.0D, livingEntity.posX + 2.0D, livingEntity.posY + 2.0D, + livingEntity.posZ + 2.0D); + } + + return livingEntity.isInRangeToRender3d(camX, camY, camZ) + && (livingEntity.ignoreFrustumCheck || camera.isBoundingBoxInFrustum(axisalignedbb)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderArrow.java b/src/game/java/net/minecraft/client/renderer/entity/RenderArrow.java index 4ece5ba4..16f32596 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderArrow.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderArrow.java @@ -9,22 +9,25 @@ import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,14 +39,13 @@ public class RenderArrow extends Render { super(renderManagerIn); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityArrow entityarrow, double d0, double d1, double d2, float f, float f1) { this.bindEntityTexture(entityarrow); @@ -109,9 +111,9 @@ public class RenderArrow extends Render { super.doRender(entityarrow, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityArrow var1) { return arrowTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderBat.java b/src/game/java/net/minecraft/client/renderer/entity/RenderBat.java index aa5c5ee1..1fe63607 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderBat.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderBat.java @@ -6,22 +6,25 @@ import net.minecraft.entity.passive.EntityBat; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,18 +36,17 @@ public class RenderBat extends RenderLiving { super(renderManagerIn, new ModelBat(), 0.25F); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityBat var1) { return batTextures; } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityBat var1, float var2) { GlStateManager.scale(0.35F, 0.35F, 0.35F); diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderBiped.java b/src/game/java/net/minecraft/client/renderer/entity/RenderBiped.java index 1fa42ffd..d20603ad 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderBiped.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderBiped.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.entity.EntityLiving; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,9 +47,9 @@ public class RenderBiped extends RenderLiving { this.addLayer(new LayerCustomHead(modelBipedIn.bipedHead)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(T var1) { return DEFAULT_RES_LOC; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderBlaze.java b/src/game/java/net/minecraft/client/renderer/entity/RenderBlaze.java index 9277a25c..753050b0 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderBlaze.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderBlaze.java @@ -5,22 +5,25 @@ import net.minecraft.client.model.ModelBlaze; import net.minecraft.entity.monster.EntityBlaze; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,14 +35,6 @@ public class RenderBlaze extends RenderLiving { super(renderManagerIn, new ModelBlaze(), 0.5F); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntityBlaze var1) { - return blazeTextures; - } - public void doRender(EntityBlaze entityliving, double d0, double d1, double d2, float f, float f1) { if (DeferredStateManager.isInDeferredPass()) { DeferredStateManager.setEmissionConstant(1.0f); @@ -52,4 +47,12 @@ public class RenderBlaze extends RenderLiving { super.doRender(entityliving, d0, d1, d2, f, f1); } } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntityBlaze var1) { + return blazeTextures; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderBoat.java b/src/game/java/net/minecraft/client/renderer/entity/RenderBoat.java index d2793293..e3e5ef72 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderBoat.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderBoat.java @@ -7,30 +7,33 @@ import net.minecraft.entity.item.EntityBoat; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RenderBoat extends Render { private static final ResourceLocation boatTextures = new ResourceLocation("textures/entity/boat.png"); - /**+ - * instance of ModelBoat for rendering + /** + * + instance of ModelBoat for rendering */ protected ModelBase modelBoat = new ModelBoat(); @@ -39,14 +42,13 @@ public class RenderBoat extends Render { this.shadowSize = 0.5F; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityBoat entityboat, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -73,9 +75,9 @@ public class RenderBoat extends Render { super.doRender(entityboat, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityBoat var1) { return boatTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderCaveSpider.java b/src/game/java/net/minecraft/client/renderer/entity/RenderCaveSpider.java index de4ca5ec..f288a392 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderCaveSpider.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderCaveSpider.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.monster.EntityCaveSpider; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,20 +36,19 @@ public class RenderCaveSpider extends RenderSpider { this.shadowSize *= 0.7F; } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime - */ - protected void preRenderCallback(EntityCaveSpider var1, float var2) { - GlStateManager.scale(0.7F, 0.7F, 0.7F); - } - - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityCaveSpider var1) { return caveSpiderTextures; } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime + */ + protected void preRenderCallback(EntityCaveSpider var1, float var2) { + GlStateManager.scale(0.7F, 0.7F, 0.7F); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderChicken.java b/src/game/java/net/minecraft/client/renderer/entity/RenderChicken.java index 27327e86..db7f4195 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderChicken.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderChicken.java @@ -5,22 +5,25 @@ import net.minecraft.entity.passive.EntityChicken; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,17 +35,16 @@ public class RenderChicken extends RenderLiving { super(renderManagerIn, modelBaseIn, shadowSizeIn); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityChicken var1) { return chickenTextures; } - /**+ - * Defines what float the third param in setRotationAngles of - * ModelBase is + /** + * + Defines what float the third param in setRotationAngles of ModelBase is */ protected float handleRotationFloat(EntityChicken livingBase, float partialTicks) { float f = livingBase.field_70888_h + (livingBase.wingRotation - livingBase.field_70888_h) * partialTicks; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderCow.java b/src/game/java/net/minecraft/client/renderer/entity/RenderCow.java index 0c698c8f..b02e0a19 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderCow.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderCow.java @@ -4,22 +4,25 @@ import net.minecraft.client.model.ModelBase; import net.minecraft.entity.passive.EntityCow; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,9 +34,9 @@ public class RenderCow extends RenderLiving { super(renderManagerIn, modelBaseIn, shadowSizeIn); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityCow var1) { return cowTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderCreeper.java b/src/game/java/net/minecraft/client/renderer/entity/RenderCreeper.java index 51e81d33..b714072e 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderCreeper.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderCreeper.java @@ -8,22 +8,25 @@ import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,37 +39,6 @@ public class RenderCreeper extends RenderLiving { this.addLayer(new LayerCreeperCharge(this)); } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime - */ - protected void preRenderCallback(EntityCreeper entitycreeper, float f) { - float f1 = entitycreeper.getCreeperFlashIntensity(f); - float f2 = 1.0F + MathHelper.sin(f1 * 100.0F) * f1 * 0.01F; - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - f1 = f1 * f1; - f1 = f1 * f1; - float f3 = (1.0F + f1 * 0.4F) * f2; - float f4 = (1.0F + f1 * 0.1F) / f2; - GlStateManager.scale(f3, f4, f3); - } - - /**+ - * Returns an ARGB int color back. Args: entityLiving, - * lightBrightness, partialTickTime - */ - protected int getColorMultiplier(EntityCreeper entitycreeper, float var2, float f) { - float f1 = entitycreeper.getCreeperFlashIntensity(f); - if ((int) (f1 * 10.0F) % 2 == 0) { - return 0; - } else { - int i = (int) (f1 * 0.2F * 255.0F); - i = MathHelper.clamp_int(i, 0, 255); - return i << 24 | 16777215; - } - } - public void doRender(EntityCreeper entitycreeper, double d0, double d1, double d2, float f, float f1) { float ff = entitycreeper.getCreeperFlashIntensity(f); if ((int) (ff * 10.0F) % 2 != 0) { @@ -79,11 +51,41 @@ public class RenderCreeper extends RenderLiving { } } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns an ARGB int color back. Args: entityLiving, lightBrightness, + * partialTickTime + */ + protected int getColorMultiplier(EntityCreeper entitycreeper, float var2, float f) { + float f1 = entitycreeper.getCreeperFlashIntensity(f); + if ((int) (f1 * 10.0F) % 2 == 0) { + return 0; + } else { + int i = (int) (f1 * 0.2F * 255.0F); + i = MathHelper.clamp_int(i, 0, 255); + return i << 24 | 16777215; + } + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityCreeper var1) { return creeperTextures; } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime + */ + protected void preRenderCallback(EntityCreeper entitycreeper, float f) { + float f1 = entitycreeper.getCreeperFlashIntensity(f); + float f2 = 1.0F + MathHelper.sin(f1 * 100.0F) * f1 * 0.01F; + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + f1 = f1 * f1; + f1 = f1 * f1; + float f3 = (1.0F + f1 * 0.4F) * f2; + float f4 = (1.0F + f1 * 0.1F) / f2; + GlStateManager.scale(f3, f4, f3); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderDragon.java b/src/game/java/net/minecraft/client/renderer/entity/RenderDragon.java index 3d2120fa..32f42fd6 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderDragon.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderDragon.java @@ -1,6 +1,12 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; @@ -16,22 +22,25 @@ import net.minecraft.entity.boss.EntityDragon; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,26 +61,84 @@ public class RenderDragon extends RenderLiving { this.addLayer(new LayerEnderDragonDeath()); } - protected void rotateCorpse(EntityDragon entitydragon, float var2, float var3, float f) { - float f1 = (float) entitydragon.getMovementOffsets(7, f)[0]; - float f2 = (float) (entitydragon.getMovementOffsets(5, f)[1] - entitydragon.getMovementOffsets(10, f)[1]); - GlStateManager.rotate(-f1, 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(f2 * 10.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.translate(0.0F, 0.0F, 1.0F); - if (entitydragon.deathTime > 0) { - float f3 = ((float) entitydragon.deathTime + f - 1.0F) / 20.0F * 1.6F; - f3 = MathHelper.sqrt_float(f3); - if (f3 > 1.0F) { - f3 = 1.0F; - } - - GlStateManager.rotate(f3 * this.getDeathMaxRotation(entitydragon), 0.0F, 0.0F, 1.0F); + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe + */ + public void doRender(EntityDragon entitydragon, double d0, double d1, double d2, float f, float f1) { + BossStatus.setBossStatus(entitydragon, false); + super.doRender(entitydragon, d0, d1, d2, f, f1); + if (entitydragon.healingEnderCrystal != null) { + this.drawRechargeRay(entitydragon, d0, d1, d2, f1); } } - /**+ - * Renders the model in RenderLiving + /** + * + Draws the ray from the dragon to it's crystal + */ + protected void drawRechargeRay(EntityDragon dragon, double parDouble1, double parDouble2, double parDouble3, + float parFloat1) { + float f = (float) dragon.healingEnderCrystal.innerRotation + parFloat1; + float f1 = MathHelper.sin(f * 0.2F) / 2.0F + 0.5F; + f1 = (f1 * f1 + f1) * 0.2F; + float f2 = (float) (dragon.healingEnderCrystal.posX - dragon.posX + - (dragon.prevPosX - dragon.posX) * (double) (1.0F - parFloat1)); + float f3 = (float) ((double) f1 + dragon.healingEnderCrystal.posY - 1.0D - dragon.posY + - (dragon.prevPosY - dragon.posY) * (double) (1.0F - parFloat1)); + float f4 = (float) (dragon.healingEnderCrystal.posZ - dragon.posZ + - (dragon.prevPosZ - dragon.posZ) * (double) (1.0F - parFloat1)); + float f5 = MathHelper.sqrt_float(f2 * f2 + f4 * f4); + float f6 = MathHelper.sqrt_float(f2 * f2 + f3 * f3 + f4 * f4); + GlStateManager.pushMatrix(); + GlStateManager.translate((float) parDouble1, (float) parDouble2 + 2.0F, (float) parDouble3); + GlStateManager.rotate((float) (-Math.atan2((double) f4, (double) f2)) * 180.0F / 3.1415927F - 90.0F, 0.0F, 1.0F, + 0.0F); + GlStateManager.rotate((float) (-Math.atan2((double) f5, (double) f3)) * 180.0F / 3.1415927F - 90.0F, 1.0F, 0.0F, + 0.0F); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + RenderHelper.disableStandardItemLighting(); + GlStateManager.disableCull(); + this.bindTexture(enderDragonCrystalBeamTextures); + GlStateManager.shadeModel(GL_SMOOTH); + float f7 = 0.0F - ((float) dragon.ticksExisted + parFloat1) * 0.01F; + float f8 = MathHelper.sqrt_float(f2 * f2 + f3 * f3 + f4 * f4) / 32.0F + - ((float) dragon.ticksExisted + parFloat1) * 0.01F; + worldrenderer.begin(5, DefaultVertexFormats.POSITION_TEX_COLOR); + boolean flag = true; + + for (int i = 0; i <= 8; ++i) { + float f9 = MathHelper.sin((float) (i % 8) * 3.1415927F * 2.0F / 8.0F) * 0.75F; + float f10 = MathHelper.cos((float) (i % 8) * 3.1415927F * 2.0F / 8.0F) * 0.75F; + float f11 = (float) (i % 8) * 1.0F / 8.0F; + worldrenderer.pos((double) (f9 * 0.2F), (double) (f10 * 0.2F), 0.0D).tex((double) f11, (double) f8) + .color(0, 0, 0, 255).endVertex(); + worldrenderer.pos((double) f9, (double) f10, (double) f6).tex((double) f11, (double) f7) + .color(255, 255, 255, 255).endVertex(); + } + + tessellator.draw(); + GlStateManager.enableCull(); + GlStateManager.shadeModel(GL_FLAT); + RenderHelper.enableStandardItemLighting(); + GlStateManager.popMatrix(); + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntityDragon var1) { + return enderDragonTextures; + } + + /** + * + Renders the model in RenderLiving */ protected void renderModel(EntityDragon entitydragon, float f, float f1, float f2, float f3, float f4, float f5) { if (DeferredStateManager.isDeferredRenderer()) { @@ -125,80 +192,21 @@ public class RenderDragon extends RenderLiving { } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe - */ - public void doRender(EntityDragon entitydragon, double d0, double d1, double d2, float f, float f1) { - BossStatus.setBossStatus(entitydragon, false); - super.doRender(entitydragon, d0, d1, d2, f, f1); - if (entitydragon.healingEnderCrystal != null) { - this.drawRechargeRay(entitydragon, d0, d1, d2, f1); + protected void rotateCorpse(EntityDragon entitydragon, float var2, float var3, float f) { + float f1 = (float) entitydragon.getMovementOffsets(7, f)[0]; + float f2 = (float) (entitydragon.getMovementOffsets(5, f)[1] - entitydragon.getMovementOffsets(10, f)[1]); + GlStateManager.rotate(-f1, 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(f2 * 10.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.translate(0.0F, 0.0F, 1.0F); + if (entitydragon.deathTime > 0) { + float f3 = ((float) entitydragon.deathTime + f - 1.0F) / 20.0F * 1.6F; + f3 = MathHelper.sqrt_float(f3); + if (f3 > 1.0F) { + f3 = 1.0F; + } + + GlStateManager.rotate(f3 * this.getDeathMaxRotation(entitydragon), 0.0F, 0.0F, 1.0F); } } - - /**+ - * Draws the ray from the dragon to it's crystal - */ - protected void drawRechargeRay(EntityDragon dragon, double parDouble1, double parDouble2, double parDouble3, - float parFloat1) { - float f = (float) dragon.healingEnderCrystal.innerRotation + parFloat1; - float f1 = MathHelper.sin(f * 0.2F) / 2.0F + 0.5F; - f1 = (f1 * f1 + f1) * 0.2F; - float f2 = (float) (dragon.healingEnderCrystal.posX - dragon.posX - - (dragon.prevPosX - dragon.posX) * (double) (1.0F - parFloat1)); - float f3 = (float) ((double) f1 + dragon.healingEnderCrystal.posY - 1.0D - dragon.posY - - (dragon.prevPosY - dragon.posY) * (double) (1.0F - parFloat1)); - float f4 = (float) (dragon.healingEnderCrystal.posZ - dragon.posZ - - (dragon.prevPosZ - dragon.posZ) * (double) (1.0F - parFloat1)); - float f5 = MathHelper.sqrt_float(f2 * f2 + f4 * f4); - float f6 = MathHelper.sqrt_float(f2 * f2 + f3 * f3 + f4 * f4); - GlStateManager.pushMatrix(); - GlStateManager.translate((float) parDouble1, (float) parDouble2 + 2.0F, (float) parDouble3); - GlStateManager.rotate((float) (-Math.atan2((double) f4, (double) f2)) * 180.0F / 3.1415927F - 90.0F, 0.0F, 1.0F, - 0.0F); - GlStateManager.rotate((float) (-Math.atan2((double) f5, (double) f3)) * 180.0F / 3.1415927F - 90.0F, 1.0F, 0.0F, - 0.0F); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - RenderHelper.disableStandardItemLighting(); - GlStateManager.disableCull(); - this.bindTexture(enderDragonCrystalBeamTextures); - GlStateManager.shadeModel(GL_SMOOTH); - float f7 = 0.0F - ((float) dragon.ticksExisted + parFloat1) * 0.01F; - float f8 = MathHelper.sqrt_float(f2 * f2 + f3 * f3 + f4 * f4) / 32.0F - - ((float) dragon.ticksExisted + parFloat1) * 0.01F; - worldrenderer.begin(5, DefaultVertexFormats.POSITION_TEX_COLOR); - boolean flag = true; - - for (int i = 0; i <= 8; ++i) { - float f9 = MathHelper.sin((float) (i % 8) * 3.1415927F * 2.0F / 8.0F) * 0.75F; - float f10 = MathHelper.cos((float) (i % 8) * 3.1415927F * 2.0F / 8.0F) * 0.75F; - float f11 = (float) (i % 8) * 1.0F / 8.0F; - worldrenderer.pos((double) (f9 * 0.2F), (double) (f10 * 0.2F), 0.0D).tex((double) f11, (double) f8) - .color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double) f9, (double) f10, (double) f6).tex((double) f11, (double) f7) - .color(255, 255, 255, 255).endVertex(); - } - - tessellator.draw(); - GlStateManager.enableCull(); - GlStateManager.shadeModel(GL_FLAT); - RenderHelper.enableStandardItemLighting(); - GlStateManager.popMatrix(); - } - - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntityDragon var1) { - return enderDragonTextures; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderEnderman.java b/src/game/java/net/minecraft/client/renderer/entity/RenderEnderman.java index 2c426c16..a78aaf87 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderEnderman.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderEnderman.java @@ -8,22 +8,25 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldBlock; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,14 +44,13 @@ public class RenderEnderman extends RenderLiving { this.addLayer(new LayerHeldBlock(this)); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityEnderman entityenderman, double d0, double d1, double d2, float f, float f1) { this.endermanModel.isCarrying = entityenderman.getHeldBlockState().getBlock().getMaterial() != Material.air; @@ -62,9 +64,9 @@ public class RenderEnderman extends RenderLiving { super.doRender(entityenderman, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityEnderman var1) { return endermanTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderEndermite.java b/src/game/java/net/minecraft/client/renderer/entity/RenderEndermite.java index 3de62917..4af52edc 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderEndermite.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderEndermite.java @@ -4,22 +4,25 @@ import net.minecraft.client.model.ModelEnderMite; import net.minecraft.entity.monster.EntityEndermite; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,9 +38,9 @@ public class RenderEndermite extends RenderLiving { return 180.0F; } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityEndermite var1) { return ENDERMITE_TEXTURES; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderEntity.java b/src/game/java/net/minecraft/client/renderer/entity/RenderEntity.java index 01292a77..6a87534b 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderEntity.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderEntity.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,14 +32,13 @@ public class RenderEntity extends Render { super(renderManagerIn); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(Entity entity, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -46,9 +48,9 @@ public class RenderEntity extends Render { super.doRender(entity, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(Entity var1) { return null; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderEntityItem.java b/src/game/java/net/minecraft/client/renderer/entity/RenderEntityItem.java index 17271649..db300c63 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderEntityItem.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderEntityItem.java @@ -1,9 +1,10 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; @@ -15,22 +16,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,60 +50,13 @@ public class RenderEntityItem extends Render { this.shadowOpaque = 0.75F; } - private int func_177077_a(EntityItem itemIn, double parDouble1, double parDouble2, double parDouble3, - float parFloat1, IBakedModel parIBakedModel) { - ItemStack itemstack = itemIn.getEntityItem(); - Item item = itemstack.getItem(); - if (item == null) { - return 0; - } else { - boolean flag = parIBakedModel.isGui3d(); - int i = this.func_177078_a(itemstack); - float f = 0.25F; - float f1 = MathHelper.sin(((float) itemIn.getAge() + parFloat1) / 10.0F + itemIn.hoverStart) * 0.1F + 0.1F; - float f2 = parIBakedModel.getItemCameraTransforms() - .getTransform(ItemCameraTransforms.TransformType.GROUND).scale.y; - GlStateManager.translate((float) parDouble1, (float) parDouble2 + f1 + 0.25F * f2, (float) parDouble3); - if (flag || this.renderManager.options != null) { - float f3 = (((float) itemIn.getAge() + parFloat1) / 20.0F + itemIn.hoverStart) * 57.295776F; - GlStateManager.rotate(f3, 0.0F, 1.0F, 0.0F); - } - - if (!flag) { - float f6 = 0.0F * (float) (i - 1) * 0.5F; - float f4 = 0.0F * (float) (i - 1) * 0.5F; - float f5 = -0.046875F * (float) (i - 1) * 0.5F; - GlStateManager.translate(f6, f4, f5); - } - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - return i; - } - } - - private int func_177078_a(ItemStack stack) { - byte b0 = 1; - if (stack.stackSize > 48) { - b0 = 5; - } else if (stack.stackSize > 32) { - b0 = 4; - } else if (stack.stackSize > 16) { - b0 = 3; - } else if (stack.stackSize > 1) { - b0 = 2; - } - - return b0; - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityItem entityitem, double d0, double d1, double d2, float f, float f1) { boolean emissive = entityitem.eaglerEmissiveFlag; @@ -163,9 +120,55 @@ public class RenderEntityItem extends Render { } } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + private int func_177077_a(EntityItem itemIn, double parDouble1, double parDouble2, double parDouble3, + float parFloat1, IBakedModel parIBakedModel) { + ItemStack itemstack = itemIn.getEntityItem(); + Item item = itemstack.getItem(); + if (item == null) { + return 0; + } else { + boolean flag = parIBakedModel.isGui3d(); + int i = this.func_177078_a(itemstack); + float f = 0.25F; + float f1 = MathHelper.sin(((float) itemIn.getAge() + parFloat1) / 10.0F + itemIn.hoverStart) * 0.1F + 0.1F; + float f2 = parIBakedModel.getItemCameraTransforms() + .getTransform(ItemCameraTransforms.TransformType.GROUND).scale.y; + GlStateManager.translate((float) parDouble1, (float) parDouble2 + f1 + 0.25F * f2, (float) parDouble3); + if (flag || this.renderManager.options != null) { + float f3 = (((float) itemIn.getAge() + parFloat1) / 20.0F + itemIn.hoverStart) * 57.295776F; + GlStateManager.rotate(f3, 0.0F, 1.0F, 0.0F); + } + + if (!flag) { + float f6 = 0.0F * (float) (i - 1) * 0.5F; + float f4 = 0.0F * (float) (i - 1) * 0.5F; + float f5 = -0.046875F * (float) (i - 1) * 0.5F; + GlStateManager.translate(f6, f4, f5); + } + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + return i; + } + } + + private int func_177078_a(ItemStack stack) { + byte b0 = 1; + if (stack.stackSize > 48) { + b0 = 5; + } else if (stack.stackSize > 32) { + b0 = 4; + } else if (stack.stackSize > 16) { + b0 = 3; + } else if (stack.stackSize > 1) { + b0 = 2; + } + + return b0; + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityItem var1) { return TextureMap.locationBlocksTexture; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderFallingBlock.java b/src/game/java/net/minecraft/client/renderer/entity/RenderFallingBlock.java index e04be7d7..4c211c8c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderFallingBlock.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderFallingBlock.java @@ -18,22 +18,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,14 +47,13 @@ public class RenderFallingBlock extends Render { this.shadowSize = 0.5F; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityFallingBlock entityfallingblock, double d0, double d1, double d2, float f, float f1) { if (entityfallingblock.getBlock() != null) { @@ -92,9 +94,9 @@ public class RenderFallingBlock extends Render { } } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityFallingBlock var1) { return TextureMap.locationBlocksTexture; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderFireball.java b/src/game/java/net/minecraft/client/renderer/entity/RenderFireball.java index b5752a81..abac1377 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderFireball.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderFireball.java @@ -11,22 +11,25 @@ import net.minecraft.entity.projectile.EntityFireball; import net.minecraft.init.Items; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,14 +42,13 @@ public class RenderFireball extends Render { this.scale = scaleIn; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityFireball entityfireball, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -78,9 +80,9 @@ public class RenderFireball extends Render { super.doRender(entityfireball, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityFireball var1) { return TextureMap.locationBlocksTexture; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderFish.java b/src/game/java/net/minecraft/client/renderer/entity/RenderFish.java index 9cd0e04f..a0d74272 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderFish.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderFish.java @@ -10,22 +10,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,14 +40,13 @@ public class RenderFish extends Render { super(renderManagerIn); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityFishHook entityfishhook, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -137,9 +139,9 @@ public class RenderFish extends Render { } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityFishHook var1) { return FISH_PARTICLES; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderGhast.java b/src/game/java/net/minecraft/client/renderer/entity/RenderGhast.java index ece6d157..2407eff9 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderGhast.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderGhast.java @@ -5,22 +5,25 @@ import net.minecraft.client.model.ModelGhast; import net.minecraft.entity.monster.EntityGhast; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,18 +37,17 @@ public class RenderGhast extends RenderLiving { super(renderManagerIn, new ModelGhast(), 0.5F); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityGhast entityghast) { return entityghast.isAttacking() ? ghastShootingTextures : ghastTextures; } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityGhast var1, float var2) { float f = 1.0F; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderGiantZombie.java b/src/game/java/net/minecraft/client/renderer/entity/RenderGiantZombie.java index 9322957d..945d5f53 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderGiantZombie.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderGiantZombie.java @@ -8,22 +8,25 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.entity.monster.EntityGiantZombie; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,24 +47,23 @@ public class RenderGiantZombie extends RenderLiving { }); } - public void transformHeldFull3DItemLayer() { - GlStateManager.translate(0.0F, 0.1875F, 0.0F); + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntityGiantZombie var1) { + return zombieTextures; } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityGiantZombie var1, float var2) { GlStateManager.scale(this.scale, this.scale, this.scale); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntityGiantZombie var1) { - return zombieTextures; + public void transformHeldFull3DItemLayer() { + GlStateManager.translate(0.0F, 0.1875F, 0.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderGuardian.java b/src/game/java/net/minecraft/client/renderer/entity/RenderGuardian.java index 61aa7409..5f981ba3 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderGuardian.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderGuardian.java @@ -1,6 +1,9 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -16,22 +19,25 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,44 +55,13 @@ public class RenderGuardian extends RenderLiving { this.field_177115_a = ((ModelGuardian) this.mainModel).func_178706_a(); } - public boolean shouldRender(EntityGuardian entityguardian, ICamera icamera, double d0, double d1, double d2) { - if (super.shouldRender(entityguardian, icamera, d0, d1, d2)) { - return true; - } else { - if (entityguardian.hasTargetedEntity()) { - EntityLivingBase entitylivingbase = entityguardian.getTargetedEntity(); - if (entitylivingbase != null) { - Vec3 vec3 = this.func_177110_a(entitylivingbase, (double) entitylivingbase.height * 0.5D, 1.0F); - Vec3 vec31 = this.func_177110_a(entityguardian, (double) entityguardian.getEyeHeight(), 1.0F); - if (icamera.isBoundingBoxInFrustum(AxisAlignedBB.fromBounds(vec31.xCoord, vec31.yCoord, - vec31.zCoord, vec3.xCoord, vec3.yCoord, vec3.zCoord))) { - return true; - } - } - } - - return false; - } - } - - private Vec3 func_177110_a(EntityLivingBase entityLivingBaseIn, double parDouble1, float parFloat1) { - double d0 = entityLivingBaseIn.lastTickPosX - + (entityLivingBaseIn.posX - entityLivingBaseIn.lastTickPosX) * (double) parFloat1; - double d1 = parDouble1 + entityLivingBaseIn.lastTickPosY - + (entityLivingBaseIn.posY - entityLivingBaseIn.lastTickPosY) * (double) parFloat1; - double d2 = entityLivingBaseIn.lastTickPosZ - + (entityLivingBaseIn.posZ - entityLivingBaseIn.lastTickPosZ) * (double) parFloat1; - return new Vec3(d0, d1, d2); - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityGuardian entityguardian, double d0, double d1, double d2, float f, float f1) { if (this.field_177115_a != ((ModelGuardian) this.mainModel).func_178706_a()) { @@ -176,10 +151,27 @@ public class RenderGuardian extends RenderLiving { } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + private Vec3 func_177110_a(EntityLivingBase entityLivingBaseIn, double parDouble1, float parFloat1) { + double d0 = entityLivingBaseIn.lastTickPosX + + (entityLivingBaseIn.posX - entityLivingBaseIn.lastTickPosX) * (double) parFloat1; + double d1 = parDouble1 + entityLivingBaseIn.lastTickPosY + + (entityLivingBaseIn.posY - entityLivingBaseIn.lastTickPosY) * (double) parFloat1; + double d2 = entityLivingBaseIn.lastTickPosZ + + (entityLivingBaseIn.posZ - entityLivingBaseIn.lastTickPosZ) * (double) parFloat1; + return new Vec3(d0, d1, d2); + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntityGuardian entityguardian) { + return entityguardian.isElder() ? GUARDIAN_ELDER_TEXTURE : GUARDIAN_TEXTURE; + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityGuardian entityguardian, float var2) { if (entityguardian.isElder()) { @@ -188,11 +180,23 @@ public class RenderGuardian extends RenderLiving { } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntityGuardian entityguardian) { - return entityguardian.isElder() ? GUARDIAN_ELDER_TEXTURE : GUARDIAN_TEXTURE; + public boolean shouldRender(EntityGuardian entityguardian, ICamera icamera, double d0, double d1, double d2) { + if (super.shouldRender(entityguardian, icamera, d0, d1, d2)) { + return true; + } else { + if (entityguardian.hasTargetedEntity()) { + EntityLivingBase entitylivingbase = entityguardian.getTargetedEntity(); + if (entitylivingbase != null) { + Vec3 vec3 = this.func_177110_a(entitylivingbase, (double) entitylivingbase.height * 0.5D, 1.0F); + Vec3 vec31 = this.func_177110_a(entityguardian, (double) entityguardian.getEyeHeight(), 1.0F); + if (icamera.isBoundingBoxInFrustum(AxisAlignedBB.fromBounds(vec31.xCoord, vec31.yCoord, + vec31.zCoord, vec3.xCoord, vec3.yCoord, vec3.zCoord))) { + return true; + } + } + } + + return false; + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderHorse.java b/src/game/java/net/minecraft/client/renderer/entity/RenderHorse.java index 2f786a86..0b34e788 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderHorse.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderHorse.java @@ -11,22 +11,25 @@ import net.minecraft.client.renderer.texture.LayeredTexture; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,27 +49,26 @@ public class RenderHorse extends RenderLiving { super(rendermanagerIn, model, shadowSizeIn); } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime - */ - protected void preRenderCallback(EntityHorse entityhorse, float f) { - float f1 = 1.0F; - int i = entityhorse.getHorseType(); - if (i == 1) { - f1 *= 0.87F; - } else if (i == 2) { - f1 *= 0.92F; - } + private ResourceLocation func_110848_b(EntityHorse horse) { + String s = horse.getHorseTexture(); + if (!horse.func_175507_cI()) { + return null; + } else { + ResourceLocation resourcelocation = (ResourceLocation) field_110852_a.get(s); + if (resourcelocation == null) { + resourcelocation = new ResourceLocation(s); + Minecraft.getMinecraft().getTextureManager().loadTexture(resourcelocation, + new LayeredTexture(horse.getVariantTexturePaths())); + field_110852_a.put(s, resourcelocation); + } - GlStateManager.scale(f1, f1, f1); - super.preRenderCallback(entityhorse, f); + return resourcelocation; + } } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityHorse entityhorse) { if (!entityhorse.func_110239_cn()) { @@ -88,20 +90,20 @@ public class RenderHorse extends RenderLiving { } } - private ResourceLocation func_110848_b(EntityHorse horse) { - String s = horse.getHorseTexture(); - if (!horse.func_175507_cI()) { - return null; - } else { - ResourceLocation resourcelocation = (ResourceLocation) field_110852_a.get(s); - if (resourcelocation == null) { - resourcelocation = new ResourceLocation(s); - Minecraft.getMinecraft().getTextureManager().loadTexture(resourcelocation, - new LayeredTexture(horse.getVariantTexturePaths())); - field_110852_a.put(s, resourcelocation); - } - - return resourcelocation; + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime + */ + protected void preRenderCallback(EntityHorse entityhorse, float f) { + float f1 = 1.0F; + int i = entityhorse.getHorseType(); + if (i == 1) { + f1 *= 0.87F; + } else if (i == 2) { + f1 *= 0.92F; } + + GlStateManager.scale(f1, f1, f1); + super.preRenderCallback(entityhorse, f); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderIronGolem.java b/src/game/java/net/minecraft/client/renderer/entity/RenderIronGolem.java index 476345bc..23dceb13 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderIronGolem.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderIronGolem.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.entity.layers.LayerIronGolemFlower; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,9 +37,9 @@ public class RenderIronGolem extends RenderLiving { this.addLayer(new LayerIronGolemFlower(this)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityIronGolem var1) { return ironGolemTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderItem.java b/src/game/java/net/minecraft/client/renderer/entity/RenderItem.java index da275a4d..e2b9e7ed 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderItem.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderItem.java @@ -1,6 +1,17 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BACK; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRONT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import java.util.List; import java.util.concurrent.Callable; @@ -16,6 +27,7 @@ import net.minecraft.block.BlockDirt; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.BlockFlower; import net.minecraft.block.BlockHugeMushroom; +import net.minecraft.block.BlockMosaic; import net.minecraft.block.BlockPlanks; import net.minecraft.block.BlockPrismarine; import net.minecraft.block.BlockQuartz; @@ -67,22 +79,25 @@ import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3i; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -90,9 +105,22 @@ import net.minecraft.util.Vec3i; public class RenderItem implements IResourceManagerReloadListener { private static final ResourceLocation RES_ITEM_GLINT = new ResourceLocation( "textures/misc/enchanted_item_glint.png"); + public static float renderPosX = 0.0f; + public static float renderPosY = 0.0f; + public static float renderPosZ = 0.0f; + + private static boolean isTransparentItem(ItemStack stack) { + Item itm = stack.getItem(); + return itm instanceof ItemBlock + && ((ItemBlock) itm).getBlock().getBlockLayer() == EnumWorldBlockLayer.TRANSLUCENT; + } + private boolean field_175058_l = true; + public float zLevel; + private final ItemModelMesher itemModelMesher; + private final TextureManager textureManager; public RenderItem(TextureManager textureManager, ModelManager modelManager) { @@ -105,226 +133,6 @@ public class RenderItem implements IResourceManagerReloadListener { this.field_175058_l = parFlag; } - public ItemModelMesher getItemModelMesher() { - return this.itemModelMesher; - } - - protected void registerItem(Item itm, int subType, String identifier) { - this.itemModelMesher.register(itm, subType, new ModelResourceLocation(identifier, "inventory")); - } - - protected void registerBlock(Block blk, int subType, String identifier) { - this.registerItem(Item.getItemFromBlock(blk), subType, identifier); - } - - private void registerBlock(Block blk, String identifier) { - this.registerBlock(blk, 0, identifier); - } - - private void registerItem(Item itm, String identifier) { - this.registerItem(itm, 0, identifier); - } - - private void renderModel(IBakedModel model, ItemStack stack) { - this.renderModel(model, -1, stack); - } - - private void renderModel(IBakedModel model, int color) { - this.renderModel(model, color, (ItemStack) null); - } - - private void renderModel(IBakedModel model, int color, ItemStack stack) { - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.ITEM); - - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - this.renderQuads(worldrenderer, model.getFaceQuads(enumfacing), color, stack); - } - - this.renderQuads(worldrenderer, model.getGeneralQuads(), color, stack); - tessellator.draw(); - } - - public static float renderPosX = 0.0f; - public static float renderPosY = 0.0f; - public static float renderPosZ = 0.0f; - - public void renderItem(ItemStack stack, IBakedModel model) { - if (stack != null) { - GlStateManager.pushMatrix(); - GlStateManager.scale(0.5F, 0.5F, 0.5F); - if (model.isBuiltInRenderer()) { - GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.translate(-0.5F, -0.5F, -0.5F); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - GlStateManager.enableRescaleNormal(); - TileEntityItemStackRenderer.instance.renderByItem(stack); - } else { - GlStateManager.translate(-0.5F, -0.5F, -0.5F); - if (DeferredStateManager.isInDeferredPass() && isTransparentItem(stack)) { - if (DeferredStateManager.forwardCallbackHandler != null) { - final Matrix4f mat = new Matrix4f(GlStateManager.getModelViewReference()); - final float lx = GlStateManager.getTexCoordX(1), ly = GlStateManager.getTexCoordY(1); - DeferredStateManager.forwardCallbackHandler.push(new ShadersRenderPassFuture(renderPosX, - renderPosY, renderPosZ, EaglerDeferredPipeline.instance.getPartialTicks()) { - @Override - public void draw(PassType pass) { - if (pass == PassType.MAIN) { - DeferredStateManager.reportForwardRenderObjectPosition2(x, y, z); - } - EntityRenderer.enableLightmapStatic(); - GlStateManager.pushMatrix(); - GlStateManager.loadMatrix(mat); - GlStateManager.texCoords2DDirect(1, lx, ly); - Minecraft.getMinecraft().getTextureManager() - .bindTexture(TextureMap.locationBlocksTexture); - RenderItem.this.renderModel(model, stack); - if (pass != PassType.SHADOW && stack.hasEffect()) { - GlStateManager.color(1.5F, 0.5F, 1.5F, 1.0F); - DeferredStateManager.setDefaultMaterialConstants(); - DeferredStateManager.setRoughnessConstant(0.05f); - DeferredStateManager.setMetalnessConstant(0.01f); - GlStateManager.blendFunc(GL_SRC_COLOR, GL_ONE); - renderEffect(model); - DeferredStateManager.setHDRTranslucentPassBlendFunc(); - } - GlStateManager.popMatrix(); - EntityRenderer.disableLightmapStatic(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - } - }); - } - } else { - this.renderModel(model, stack); - if (stack.hasEffect()) { - if (DeferredStateManager.isInDeferredPass()) { - if (DeferredStateManager.forwardCallbackHandler != null - && !DeferredStateManager.isEnableShadowRender()) { - final Matrix4f mat = new Matrix4f(GlStateManager.getModelViewReference()); - final float lx = GlStateManager.getTexCoordX(1), ly = GlStateManager.getTexCoordY(1); - DeferredStateManager.forwardCallbackHandler.push(new ShadersRenderPassFuture(renderPosX, - renderPosY, renderPosZ, EaglerDeferredPipeline.instance.getPartialTicks()) { - @Override - public void draw(PassType pass) { - if (pass == PassType.MAIN) { - DeferredStateManager.reportForwardRenderObjectPosition2(x, y, z); - } - EntityRenderer.enableLightmapStatic(); - GlStateManager.color(1.5F, 0.5F, 1.5F, 1.0F); - DeferredStateManager.setDefaultMaterialConstants(); - DeferredStateManager.setRoughnessConstant(0.05f); - DeferredStateManager.setMetalnessConstant(0.01f); - GlStateManager.pushMatrix(); - GlStateManager.loadMatrix(mat); - GlStateManager.texCoords2DDirect(1, lx, ly); - GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE, GL_ZERO, GL_ONE); - renderEffect(model); - DeferredStateManager.setHDRTranslucentPassBlendFunc(); - GlStateManager.popMatrix(); - EntityRenderer.disableLightmapStatic(); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - } - }); - } - } else { - GlStateManager.blendFunc(GL_SRC_COLOR, GL_ONE); - this.renderEffect(model); - } - } - } - } - - GlStateManager.popMatrix(); - } - } - - private static boolean isTransparentItem(ItemStack stack) { - Item itm = stack.getItem(); - return itm instanceof ItemBlock - && ((ItemBlock) itm).getBlock().getBlockLayer() == EnumWorldBlockLayer.TRANSLUCENT; - } - - private void renderEffect(IBakedModel model) { - GlStateManager.depthMask(false); - GlStateManager.depthFunc(GL_EQUAL); - GlStateManager.disableLighting(); - this.textureManager.bindTexture(RES_ITEM_GLINT); - GlStateManager.matrixMode(GL_TEXTURE); - GlStateManager.pushMatrix(); - GlStateManager.scale(8.0F, 8.0F, 8.0F); - float f = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F; - GlStateManager.translate(f, 0.0F, 0.0F); - GlStateManager.rotate(-50.0F, 0.0F, 0.0F, 1.0F); - this.renderModel(model, -8372020); - GlStateManager.popMatrix(); - GlStateManager.pushMatrix(); - GlStateManager.scale(8.0F, 8.0F, 8.0F); - float f1 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F / 8.0F; - GlStateManager.translate(-f1, 0.0F, 0.0F); - GlStateManager.rotate(10.0F, 0.0F, 0.0F, 1.0F); - this.renderModel(model, -8372020); - GlStateManager.popMatrix(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.enableLighting(); - GlStateManager.depthFunc(GL_LEQUAL); - GlStateManager.depthMask(true); - this.textureManager.bindTexture(TextureMap.locationBlocksTexture); - } - - private void putQuadNormal(WorldRenderer renderer, BakedQuad quad) { - Vec3i vec3i = quad.getFace().getDirectionVec(); - renderer.putNormal((float) vec3i.getX(), (float) vec3i.getY(), (float) vec3i.getZ()); - } - - private void renderQuad(WorldRenderer renderer, BakedQuad quad, int color) { - renderer.addVertexData(quad.getVertexData()); - renderer.putColor4(color); - this.putQuadNormal(renderer, quad); - } - - private void renderQuads(WorldRenderer renderer, List quads, int color, ItemStack stack) { - boolean flag = color == -1 && stack != null; - int i = 0; - - for (int j = quads.size(); i < j; ++i) { - BakedQuad bakedquad = (BakedQuad) quads.get(i); - int k = color; - if (flag && bakedquad.hasTintIndex()) { - k = stack.getItem().getColorFromItemStack(stack, bakedquad.getTintIndex()); - if (EntityRenderer.anaglyphEnable) { - k = TextureUtil.anaglyphColor(k); - } - - k = k | -16777216; - } - - this.renderQuad(renderer, bakedquad, k); - } - - } - - public boolean shouldRenderItemIn3D(ItemStack stack) { - IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); - return ibakedmodel == null ? false : ibakedmodel.isGui3d(); - } - - private void preTransform(ItemStack stack) { - IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); - Item item = stack.getItem(); - if (item != null) { - boolean flag = ibakedmodel.isGui3d(); - if (!flag) { - GlStateManager.scale(2.0F, 2.0F, 2.0F); - } - - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - } - } - public void func_181564_a(ItemStack parItemStack, ItemCameraTransforms.TransformType parTransformType) { if (parItemStack != null) { IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(parItemStack); @@ -332,193 +140,6 @@ public class RenderItem implements IResourceManagerReloadListener { } } - public void renderItemModelForEntity(ItemStack stack, EntityLivingBase entityToRenderFor, - ItemCameraTransforms.TransformType cameraTransformType) { - if (stack != null && entityToRenderFor != null) { - IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); - if (entityToRenderFor instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entityToRenderFor; - Item item = stack.getItem(); - ModelResourceLocation modelresourcelocation = null; - if (item == Items.fishing_rod && entityplayer.fishEntity != null) { - modelresourcelocation = new ModelResourceLocation("fishing_rod_cast", "inventory"); - } else if (item == Items.bow && entityplayer.getItemInUse() != null) { - int i = stack.getMaxItemUseDuration() - entityplayer.getItemInUseCount(); - if (i >= 18) { - modelresourcelocation = new ModelResourceLocation("bow_pulling_2", "inventory"); - } else if (i > 13) { - modelresourcelocation = new ModelResourceLocation("bow_pulling_1", "inventory"); - } else if (i > 0) { - modelresourcelocation = new ModelResourceLocation("bow_pulling_0", "inventory"); - } - } - - if (modelresourcelocation != null) { - ibakedmodel = this.itemModelMesher.getModelManager().getModel(modelresourcelocation); - } - } - - this.renderItemModelTransform(stack, ibakedmodel, cameraTransformType); - } - } - - protected void renderItemModelTransform(ItemStack stack, IBakedModel model, - ItemCameraTransforms.TransformType cameraTransformType) { - this.textureManager.bindTexture(TextureMap.locationBlocksTexture); - this.textureManager.getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); - this.preTransform(stack); - GlStateManager.enableRescaleNormal(); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - GlStateManager.pushMatrix(); - ItemCameraTransforms itemcameratransforms = model.getItemCameraTransforms(); - itemcameratransforms.applyTransform(cameraTransformType); - boolean flag = DeferredStateManager.isEnableShadowRender(); - if (this.func_183005_a(itemcameratransforms.getTransform(cameraTransformType))) { - GlStateManager.cullFace(flag ? GL_BACK : GL_FRONT); - } - - this.renderItem(stack, model); - GlStateManager.cullFace(flag ? GL_FRONT : GL_BACK); - GlStateManager.popMatrix(); - GlStateManager.disableRescaleNormal(); - GlStateManager.disableBlend(); - this.textureManager.bindTexture(TextureMap.locationBlocksTexture); - this.textureManager.getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); - } - - private boolean func_183005_a(ItemTransformVec3f parItemTransformVec3f) { - return parItemTransformVec3f.scale.x < 0.0F ^ parItemTransformVec3f.scale.y < 0.0F - ^ parItemTransformVec3f.scale.z < 0.0F; - } - - public void renderItemIntoGUI(ItemStack stack, int x, int y) { - IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); - GlStateManager.pushMatrix(); - this.textureManager.bindTexture(TextureMap.locationBlocksTexture); - this.textureManager.getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); - GlStateManager.enableRescaleNormal(); - GlStateManager.enableAlpha(); - GlStateManager.alphaFunc(GL_GREATER, 0.1F); - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.setupGuiTransform(x, y, ibakedmodel.isGui3d()); - ibakedmodel.getItemCameraTransforms().applyTransform(ItemCameraTransforms.TransformType.GUI); - this.renderItem(stack, ibakedmodel); - GlStateManager.disableAlpha(); - GlStateManager.disableRescaleNormal(); - GlStateManager.disableLighting(); - GlStateManager.popMatrix(); - this.textureManager.bindTexture(TextureMap.locationBlocksTexture); - this.textureManager.getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); - } - - private void setupGuiTransform(int xPosition, int yPosition, boolean isGui3d) { - GlStateManager.translate((float) xPosition, (float) yPosition, 100.0F + this.zLevel); - GlStateManager.translate(8.0F, 8.0F, 0.0F); - GlStateManager.scale(1.0F, 1.0F, -1.0F); - GlStateManager.scale(0.5F, 0.5F, 0.5F); - if (isGui3d) { - GlStateManager.scale(40.0F, 40.0F, 40.0F); - GlStateManager.rotate(210.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.rotate(-135.0F, 0.0F, 1.0F, 0.0F); - GlStateManager.enableLighting(); - } else { - GlStateManager.scale(64.0F, 64.0F, 64.0F); - GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F); - GlStateManager.disableLighting(); - } - - } - - public void renderItemAndEffectIntoGUI(final ItemStack stack, int xPosition, int yPosition) { - if (stack != null && stack.getItem() != null) { - this.zLevel += 50.0F; - - try { - this.renderItemIntoGUI(stack, xPosition, yPosition); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Rendering item"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Item being rendered"); - crashreportcategory.addCrashSectionCallable("Item Type", new Callable() { - public String call() throws Exception { - return String.valueOf(stack.getItem()); - } - }); - crashreportcategory.addCrashSectionCallable("Item Aux", new Callable() { - public String call() throws Exception { - return String.valueOf(stack.getMetadata()); - } - }); - crashreportcategory.addCrashSectionCallable("Item NBT", new Callable() { - public String call() throws Exception { - return String.valueOf(stack.getTagCompound()); - } - }); - crashreportcategory.addCrashSectionCallable("Item Foil", new Callable() { - public String call() throws Exception { - return String.valueOf(stack.hasEffect()); - } - }); - throw new ReportedException(crashreport); - } - - this.zLevel -= 50.0F; - } - } - - public void renderItemOverlays(FontRenderer fr, ItemStack stack, int xPosition, int yPosition) { - this.renderItemOverlayIntoGUI(fr, stack, xPosition, yPosition, (String) null); - } - - /**+ - * Renders the stack size and/or damage bar for the given - * ItemStack. - */ - public void renderItemOverlayIntoGUI(FontRenderer fr, ItemStack stack, int xPosition, int yPosition, String text) { - if (stack != null) { - if (stack.stackSize != 1 || text != null) { - String s = text == null ? String.valueOf(stack.stackSize) : text; - if (text == null && stack.stackSize < 1) { - s = EnumChatFormatting.RED + String.valueOf(stack.stackSize); - } - - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableBlend(); - fr.drawStringWithShadow(s, (float) (xPosition + 19 - 2 - fr.getStringWidth(s)), - (float) (yPosition + 6 + 3), 16777215); - GlStateManager.enableLighting(); - GlStateManager.enableDepth(); - } - - if (stack.isItemDamaged()) { - int j = (int) Math - .round(13.0D - (double) stack.getItemDamage() * 13.0D / (double) stack.getMaxDamage()); - int i = (int) Math - .round(255.0D - (double) stack.getItemDamage() * 255.0D / (double) stack.getMaxDamage()); - GlStateManager.disableLighting(); - GlStateManager.disableDepth(); - GlStateManager.disableTexture2D(); - GlStateManager.disableAlpha(); - GlStateManager.disableBlend(); - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - this.func_181565_a(worldrenderer, xPosition + 2, yPosition + 13, 13, 2, 0, 0, 0, 255); - this.func_181565_a(worldrenderer, xPosition + 2, yPosition + 13, 12, 1, (255 - i) / 4, 64, 0, 255); - this.func_181565_a(worldrenderer, xPosition + 2, yPosition + 13, j, 1, 255 - i, i, 0, 255); - GlStateManager.enableBlend(); - GlStateManager.enableAlpha(); - GlStateManager.enableTexture2D(); - GlStateManager.enableLighting(); - GlStateManager.enableDepth(); - } - - } - } - private void func_181565_a(WorldRenderer parWorldRenderer, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, int parInt7, int parInt8) { parWorldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); @@ -533,6 +154,53 @@ public class RenderItem implements IResourceManagerReloadListener { Tessellator.getInstance().draw(); } + private boolean func_183005_a(ItemTransformVec3f parItemTransformVec3f) { + return parItemTransformVec3f.scale.x < 0.0F ^ parItemTransformVec3f.scale.y < 0.0F + ^ parItemTransformVec3f.scale.z < 0.0F; + } + + public ItemModelMesher getItemModelMesher() { + return this.itemModelMesher; + } + + public void onResourceManagerReload(IResourceManager var1) { + this.itemModelMesher.rebuildCache(); + } + + private void preTransform(ItemStack stack) { + IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); + Item item = stack.getItem(); + if (item != null) { + boolean flag = ibakedmodel.isGui3d(); + if (!flag) { + GlStateManager.scale(2.0F, 2.0F, 2.0F); + } + + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + } + + private void putQuadNormal(WorldRenderer renderer, BakedQuad quad) { + Vec3i vec3i = quad.getFace().getDirectionVec(); + renderer.putNormal((float) vec3i.getX(), (float) vec3i.getY(), (float) vec3i.getZ()); + } + + protected void registerBlock(Block blk, int subType, String identifier) { + this.registerItem(Item.getItemFromBlock(blk), subType, identifier); + } + + private void registerBlock(Block blk, String identifier) { + this.registerBlock(blk, 0, identifier); + } + + protected void registerItem(Item itm, int subType, String identifier) { + this.itemModelMesher.register(itm, subType, new ModelResourceLocation(identifier, "inventory")); + } + + private void registerItem(Item itm, String identifier) { + this.registerItem(itm, 0, identifier); + } + private void registerItems() { this.registerBlock(Blocks.anvil, "anvil_intact"); this.registerBlock(Blocks.anvil, 1, "anvil_slightly_damaged"); @@ -997,7 +665,7 @@ public class RenderItem implements IResourceManagerReloadListener { this.registerItem(Items.blaze_rod, "blaze_rod"); this.registerItem(Items.ghast_tear, "ghast_tear"); this.registerItem(Items.gold_nugget, "gold_nugget"); - + this.registerItem(Items.nether_wart, "nether_wart"); this.itemModelMesher.register(Items.potionitem, new ItemMeshDefinition() { public ModelResourceLocation getModelLocation(ItemStack itemstack) { @@ -1093,17 +761,393 @@ public class RenderItem implements IResourceManagerReloadListener { this.registerBlock(Blocks.red_mushroom_block, BlockHugeMushroom.EnumType.ALL_INSIDE.getMetadata(), "red_mushroom_block"); this.registerBlock(Blocks.dragon_egg, "dragon_egg"); - this.registerBlock(Blocks.iron_grate, "starlike:iron_grate"); + + this.registerBlock(Blocks.deepstone, "starlike:deepstone"); + this.registerBlock(Blocks.cobbled_deepstone, "starlike:cobbled_deepstone"); + this.registerBlock(Blocks.steel_block, "starlike:steel_block"); + this.registerBlock(Blocks.steel_grate, "starlike:steel_grate"); this.registerBlock(Blocks.platinum_ore, "starlike:platinum_ore"); this.registerBlock(Blocks.platinum_block, "starlike:platinum_block"); + this.registerBlock(Blocks.titanium_ore, "starlike:titanium_ore"); + this.registerBlock(Blocks.titanium_block, "starlike:titanium_block"); + this.registerBlock(Blocks.uranium_ore, "starlike:uranium_ore"); + this.registerBlock(Blocks.uranium_block, "starlike:uranium_block"); + this.registerBlock(Blocks.mosaic, BlockMosaic.EnumType.OAK.getMetadata(), "starlike:oak_mosaic"); + this.registerBlock(Blocks.mosaic, BlockMosaic.EnumType.SPRUCE.getMetadata(), "starlike:spruce_mosaic"); + this.registerBlock(Blocks.mosaic, BlockMosaic.EnumType.BIRCH.getMetadata(), "starlike:birch_mosaic"); + this.registerBlock(Blocks.mosaic, BlockMosaic.EnumType.JUNGLE.getMetadata(), "starlike:jungle_mosaic"); + this.registerBlock(Blocks.mosaic, BlockMosaic.EnumType.ACACIA.getMetadata(), "starlike:acacia_mosaic"); + this.registerBlock(Blocks.mosaic, BlockMosaic.EnumType.DARK_OAK.getMetadata(), "starlike:dark_oak_mosaic"); + this.registerBlock(Blocks.fabricator, "starlike:fabricator"); + + this.registerItem(Items.steel, "starlike:steel"); this.registerItem(Items.platinum_ingot, "starlike:platinum_ingot"); this.registerItem(Items.platinum_sword, "starlike:platinum_sword"); this.registerItem(Items.platinum_pickaxe, "starlike:platinum_pickaxe"); - this.registerBlock(Blocks.uranium_ore, "starlike:uranium_ore"); - this.registerItem(Items.normal_drill, "starlike:normal_drill"); + this.registerItem(Items.platinum_shovel, "starlike:platinum_shovel"); + this.registerItem(Items.platinum_axe, "starlike:platinum_axe"); + this.registerItem(Items.platinum_hoe, "starlike:platinum_hoe"); + this.registerItem(Items.platinum_helmet, "starlike:platinum_helmet"); + this.registerItem(Items.platinum_chestplate, "starlike:platinum_chestplate"); + this.registerItem(Items.platinum_leggings, "starlike:platinum_leggings"); + this.registerItem(Items.platinum_boots, "starlike:platinum_boots"); + this.registerItem(Items.titanium_ingot, "starlike:titanium_ingot"); + this.registerItem(Items.uranium_crystal, "starlike:uranium_crystal"); + this.registerItem(Items.uranium_rod, "starlike:uranium_rod"); + this.registerItem(Items.platinum_drill, "starlike:platinum_drill"); + this.registerItem(Items.titanium_drill, "starlike:titanium_drill"); } - public void onResourceManagerReload(IResourceManager var1) { - this.itemModelMesher.rebuildCache(); + private void renderEffect(IBakedModel model) { + GlStateManager.depthMask(false); + GlStateManager.depthFunc(GL_EQUAL); + GlStateManager.disableLighting(); + this.textureManager.bindTexture(RES_ITEM_GLINT); + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.pushMatrix(); + GlStateManager.scale(8.0F, 8.0F, 8.0F); + float f = (float) (Minecraft.getSystemTime() % 3000L) / 3000.0F / 8.0F; + GlStateManager.translate(f, 0.0F, 0.0F); + GlStateManager.rotate(-50.0F, 0.0F, 0.0F, 1.0F); + this.renderModel(model, -8372020); + GlStateManager.popMatrix(); + GlStateManager.pushMatrix(); + GlStateManager.scale(8.0F, 8.0F, 8.0F); + float f1 = (float) (Minecraft.getSystemTime() % 4873L) / 4873.0F / 8.0F; + GlStateManager.translate(-f1, 0.0F, 0.0F); + GlStateManager.rotate(10.0F, 0.0F, 0.0F, 1.0F); + this.renderModel(model, -8372020); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.enableLighting(); + GlStateManager.depthFunc(GL_LEQUAL); + GlStateManager.depthMask(true); + this.textureManager.bindTexture(TextureMap.locationBlocksTexture); } -} \ No newline at end of file + + public void renderItem(ItemStack stack, IBakedModel model) { + if (stack != null) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.5F, 0.5F, 0.5F); + if (model.isBuiltInRenderer()) { + GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.translate(-0.5F, -0.5F, -0.5F); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + GlStateManager.enableRescaleNormal(); + TileEntityItemStackRenderer.instance.renderByItem(stack); + } else { + GlStateManager.translate(-0.5F, -0.5F, -0.5F); + if (DeferredStateManager.isInDeferredPass() && isTransparentItem(stack)) { + if (DeferredStateManager.forwardCallbackHandler != null) { + final Matrix4f mat = new Matrix4f(GlStateManager.getModelViewReference()); + final float lx = GlStateManager.getTexCoordX(1), ly = GlStateManager.getTexCoordY(1); + DeferredStateManager.forwardCallbackHandler.push(new ShadersRenderPassFuture(renderPosX, + renderPosY, renderPosZ, EaglerDeferredPipeline.instance.getPartialTicks()) { + @Override + public void draw(PassType pass) { + if (pass == PassType.MAIN) { + DeferredStateManager.reportForwardRenderObjectPosition2(x, y, z); + } + EntityRenderer.enableLightmapStatic(); + GlStateManager.pushMatrix(); + GlStateManager.loadMatrix(mat); + GlStateManager.texCoords2DDirect(1, lx, ly); + Minecraft.getMinecraft().getTextureManager() + .bindTexture(TextureMap.locationBlocksTexture); + RenderItem.this.renderModel(model, stack); + if (pass != PassType.SHADOW && stack.hasEffect()) { + GlStateManager.color(1.5F, 0.5F, 1.5F, 1.0F); + DeferredStateManager.setDefaultMaterialConstants(); + DeferredStateManager.setRoughnessConstant(0.05f); + DeferredStateManager.setMetalnessConstant(0.01f); + GlStateManager.blendFunc(GL_SRC_COLOR, GL_ONE); + renderEffect(model); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + } + GlStateManager.popMatrix(); + EntityRenderer.disableLightmapStatic(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + }); + } + } else { + this.renderModel(model, stack); + if (stack.hasEffect()) { + if (DeferredStateManager.isInDeferredPass()) { + if (DeferredStateManager.forwardCallbackHandler != null + && !DeferredStateManager.isEnableShadowRender()) { + final Matrix4f mat = new Matrix4f(GlStateManager.getModelViewReference()); + final float lx = GlStateManager.getTexCoordX(1), ly = GlStateManager.getTexCoordY(1); + DeferredStateManager.forwardCallbackHandler.push(new ShadersRenderPassFuture(renderPosX, + renderPosY, renderPosZ, EaglerDeferredPipeline.instance.getPartialTicks()) { + @Override + public void draw(PassType pass) { + if (pass == PassType.MAIN) { + DeferredStateManager.reportForwardRenderObjectPosition2(x, y, z); + } + EntityRenderer.enableLightmapStatic(); + GlStateManager.color(1.5F, 0.5F, 1.5F, 1.0F); + DeferredStateManager.setDefaultMaterialConstants(); + DeferredStateManager.setRoughnessConstant(0.05f); + DeferredStateManager.setMetalnessConstant(0.01f); + GlStateManager.pushMatrix(); + GlStateManager.loadMatrix(mat); + GlStateManager.texCoords2DDirect(1, lx, ly); + GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE, GL_ZERO, GL_ONE); + renderEffect(model); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + GlStateManager.popMatrix(); + EntityRenderer.disableLightmapStatic(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + }); + } + } else { + GlStateManager.blendFunc(GL_SRC_COLOR, GL_ONE); + this.renderEffect(model); + } + } + } + } + + GlStateManager.popMatrix(); + } + } + + public void renderItemAndEffectIntoGUI(final ItemStack stack, int xPosition, int yPosition) { + if (stack != null && stack.getItem() != null) { + this.zLevel += 50.0F; + + try { + this.renderItemIntoGUI(stack, xPosition, yPosition); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Rendering item"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Item being rendered"); + crashreportcategory.addCrashSectionCallable("Item Type", new Callable() { + public String call() throws Exception { + return String.valueOf(stack.getItem()); + } + }); + crashreportcategory.addCrashSectionCallable("Item Aux", new Callable() { + public String call() throws Exception { + return String.valueOf(stack.getMetadata()); + } + }); + crashreportcategory.addCrashSectionCallable("Item NBT", new Callable() { + public String call() throws Exception { + return String.valueOf(stack.getTagCompound()); + } + }); + crashreportcategory.addCrashSectionCallable("Item Foil", new Callable() { + public String call() throws Exception { + return String.valueOf(stack.hasEffect()); + } + }); + throw new ReportedException(crashreport); + } + + this.zLevel -= 50.0F; + } + } + + public void renderItemIntoGUI(ItemStack stack, int x, int y) { + IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); + GlStateManager.pushMatrix(); + this.textureManager.bindTexture(TextureMap.locationBlocksTexture); + this.textureManager.getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); + GlStateManager.enableRescaleNormal(); + GlStateManager.enableAlpha(); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + this.setupGuiTransform(x, y, ibakedmodel.isGui3d()); + ibakedmodel.getItemCameraTransforms().applyTransform(ItemCameraTransforms.TransformType.GUI); + this.renderItem(stack, ibakedmodel); + GlStateManager.disableAlpha(); + GlStateManager.disableRescaleNormal(); + GlStateManager.disableLighting(); + GlStateManager.popMatrix(); + this.textureManager.bindTexture(TextureMap.locationBlocksTexture); + this.textureManager.getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); + } + + public void renderItemModelForEntity(ItemStack stack, EntityLivingBase entityToRenderFor, + ItemCameraTransforms.TransformType cameraTransformType) { + if (stack != null && entityToRenderFor != null) { + IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); + if (entityToRenderFor instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) entityToRenderFor; + Item item = stack.getItem(); + ModelResourceLocation modelresourcelocation = null; + if (item == Items.fishing_rod && entityplayer.fishEntity != null) { + modelresourcelocation = new ModelResourceLocation("fishing_rod_cast", "inventory"); + } else if (item == Items.bow && entityplayer.getItemInUse() != null) { + int i = stack.getMaxItemUseDuration() - entityplayer.getItemInUseCount(); + if (i >= 18) { + modelresourcelocation = new ModelResourceLocation("bow_pulling_2", "inventory"); + } else if (i > 13) { + modelresourcelocation = new ModelResourceLocation("bow_pulling_1", "inventory"); + } else if (i > 0) { + modelresourcelocation = new ModelResourceLocation("bow_pulling_0", "inventory"); + } + } + + if (modelresourcelocation != null) { + ibakedmodel = this.itemModelMesher.getModelManager().getModel(modelresourcelocation); + } + } + + this.renderItemModelTransform(stack, ibakedmodel, cameraTransformType); + } + } + + protected void renderItemModelTransform(ItemStack stack, IBakedModel model, + ItemCameraTransforms.TransformType cameraTransformType) { + this.textureManager.bindTexture(TextureMap.locationBlocksTexture); + this.textureManager.getTexture(TextureMap.locationBlocksTexture).setBlurMipmap(false, false); + this.preTransform(stack); + GlStateManager.enableRescaleNormal(); + GlStateManager.alphaFunc(GL_GREATER, 0.1F); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + GlStateManager.pushMatrix(); + ItemCameraTransforms itemcameratransforms = model.getItemCameraTransforms(); + itemcameratransforms.applyTransform(cameraTransformType); + boolean flag = DeferredStateManager.isEnableShadowRender(); + if (this.func_183005_a(itemcameratransforms.getTransform(cameraTransformType))) { + GlStateManager.cullFace(flag ? GL_BACK : GL_FRONT); + } + + this.renderItem(stack, model); + GlStateManager.cullFace(flag ? GL_FRONT : GL_BACK); + GlStateManager.popMatrix(); + GlStateManager.disableRescaleNormal(); + GlStateManager.disableBlend(); + this.textureManager.bindTexture(TextureMap.locationBlocksTexture); + this.textureManager.getTexture(TextureMap.locationBlocksTexture).restoreLastBlurMipmap(); + } + + /** + * + Renders the stack size and/or damage bar for the given ItemStack. + */ + public void renderItemOverlayIntoGUI(FontRenderer fr, ItemStack stack, int xPosition, int yPosition, String text) { + if (stack != null) { + if (stack.stackSize != 1 || text != null) { + String s = text == null ? String.valueOf(stack.stackSize) : text; + if (text == null && stack.stackSize < 1) { + s = EnumChatFormatting.RED + String.valueOf(stack.stackSize); + } + + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableBlend(); + fr.drawStringWithShadow(s, (float) (xPosition + 19 - 2 - fr.getStringWidth(s)), + (float) (yPosition + 6 + 3), 16777215); + GlStateManager.enableLighting(); + GlStateManager.enableDepth(); + } + + if (stack.isItemDamaged()) { + int j = (int) Math + .round(13.0D - (double) stack.getItemDamage() * 13.0D / (double) stack.getMaxDamage()); + int i = (int) Math + .round(255.0D - (double) stack.getItemDamage() * 255.0D / (double) stack.getMaxDamage()); + GlStateManager.disableLighting(); + GlStateManager.disableDepth(); + GlStateManager.disableTexture2D(); + GlStateManager.disableAlpha(); + GlStateManager.disableBlend(); + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + this.func_181565_a(worldrenderer, xPosition + 2, yPosition + 13, 13, 2, 0, 0, 0, 255); + this.func_181565_a(worldrenderer, xPosition + 2, yPosition + 13, 12, 1, (255 - i) / 4, 64, 0, 255); + this.func_181565_a(worldrenderer, xPosition + 2, yPosition + 13, j, 1, 255 - i, i, 0, 255); + GlStateManager.enableBlend(); + GlStateManager.enableAlpha(); + GlStateManager.enableTexture2D(); + GlStateManager.enableLighting(); + GlStateManager.enableDepth(); + } + + } + } + + public void renderItemOverlays(FontRenderer fr, ItemStack stack, int xPosition, int yPosition) { + this.renderItemOverlayIntoGUI(fr, stack, xPosition, yPosition, (String) null); + } + + private void renderModel(IBakedModel model, int color) { + this.renderModel(model, color, (ItemStack) null); + } + + private void renderModel(IBakedModel model, int color, ItemStack stack) { + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.ITEM); + + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + this.renderQuads(worldrenderer, model.getFaceQuads(enumfacing), color, stack); + } + + this.renderQuads(worldrenderer, model.getGeneralQuads(), color, stack); + tessellator.draw(); + } + + private void renderModel(IBakedModel model, ItemStack stack) { + this.renderModel(model, -1, stack); + } + + private void renderQuad(WorldRenderer renderer, BakedQuad quad, int color) { + renderer.addVertexData(quad.getVertexData()); + renderer.putColor4(color); + this.putQuadNormal(renderer, quad); + } + + private void renderQuads(WorldRenderer renderer, List quads, int color, ItemStack stack) { + boolean flag = color == -1 && stack != null; + int i = 0; + + for (int j = quads.size(); i < j; ++i) { + BakedQuad bakedquad = (BakedQuad) quads.get(i); + int k = color; + if (flag && bakedquad.hasTintIndex()) { + k = stack.getItem().getColorFromItemStack(stack, bakedquad.getTintIndex()); + if (EntityRenderer.anaglyphEnable) { + k = TextureUtil.anaglyphColor(k); + } + + k = k | -16777216; + } + + this.renderQuad(renderer, bakedquad, k); + } + + } + + private void setupGuiTransform(int xPosition, int yPosition, boolean isGui3d) { + GlStateManager.translate((float) xPosition, (float) yPosition, 100.0F + this.zLevel); + GlStateManager.translate(8.0F, 8.0F, 0.0F); + GlStateManager.scale(1.0F, 1.0F, -1.0F); + GlStateManager.scale(0.5F, 0.5F, 0.5F); + if (isGui3d) { + GlStateManager.scale(40.0F, 40.0F, 40.0F); + GlStateManager.rotate(210.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.rotate(-135.0F, 0.0F, 1.0F, 0.0F); + GlStateManager.enableLighting(); + } else { + GlStateManager.scale(64.0F, 64.0F, 64.0F); + GlStateManager.rotate(180.0F, 1.0F, 0.0F, 0.0F); + GlStateManager.disableLighting(); + } + + } + + public boolean shouldRenderItemIn3D(ItemStack stack) { + IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); + return ibakedmodel == null ? false : ibakedmodel.isGui3d(); + } +} diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderLeashKnot.java b/src/game/java/net/minecraft/client/renderer/entity/RenderLeashKnot.java index 92da97f2..a7115cfc 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderLeashKnot.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderLeashKnot.java @@ -5,22 +5,25 @@ import net.minecraft.client.model.ModelLeashKnot; import net.minecraft.entity.EntityLeashKnot; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,14 +36,13 @@ public class RenderLeashKnot extends Render { super(renderManagerIn); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityLeashKnot entityleashknot, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -56,9 +58,9 @@ public class RenderLeashKnot extends Render { super.doRender(entityleashknot, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityLeashKnot var1) { return leashKnotTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java b/src/game/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java index 1a3fa82b..ff5eba58 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderLightningBolt.java @@ -1,9 +1,11 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -13,22 +15,25 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,14 +43,13 @@ public class RenderLightningBolt extends Render { super(renderManagerIn); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityLightningBolt entitylightningbolt, double d0, double d1, double d2, float var8, float var9) { @@ -167,9 +171,9 @@ public class RenderLightningBolt extends Render { GlStateManager.enableTexture2D(); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityLightningBolt var1) { return null; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderLiving.java b/src/game/java/net/minecraft/client/renderer/entity/RenderLiving.java index 1177f459..b51c1d3c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderLiving.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderLiving.java @@ -11,22 +11,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityHanging; import net.minecraft.entity.EntityLiving; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,25 +44,13 @@ public abstract class RenderLiving extends RendererLivin || entityliving.hasCustomName() && entityliving == this.renderManager.pointedEntity); } - public boolean shouldRender(T entityliving, ICamera icamera, double d0, double d1, double d2) { - if (super.shouldRender(entityliving, icamera, d0, d1, d2)) { - return true; - } else if (entityliving.getLeashed() && entityliving.getLeashedToEntity() != null) { - Entity entity = entityliving.getLeashedToEntity(); - return icamera.isBoundingBoxInFrustum(entity.getEntityBoundingBox()); - } else { - return false; - } - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(T entityliving, double d0, double d1, double d2, float f, float f1) { super.doRender(entityliving, d0, d1, d2, f, f1); @@ -73,8 +64,8 @@ public abstract class RenderLiving extends RendererLivin OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); } - /**+ - * Gets the value between start and end according to pct + /** + * + Gets the value between start and end according to pct */ private double interpolateValue(double start, double end, double pct) { return start + (end - start) * pct; @@ -185,4 +176,15 @@ public abstract class RenderLiving extends RendererLivin } } + + public boolean shouldRender(T entityliving, ICamera icamera, double d0, double d1, double d2) { + if (super.shouldRender(entityliving, icamera, d0, d1, d2)) { + return true; + } else if (entityliving.getLeashed() && entityliving.getLeashedToEntity() != null) { + Entity entity = entityliving.getLeashedToEntity(); + return icamera.isBoundingBoxInFrustum(entity.getEntityBoundingBox()); + } else { + return false; + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderMagmaCube.java b/src/game/java/net/minecraft/client/renderer/entity/RenderMagmaCube.java index 25b862c8..0088f2ac 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderMagmaCube.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderMagmaCube.java @@ -5,22 +5,25 @@ import net.minecraft.client.model.ModelMagmaCube; import net.minecraft.entity.monster.EntityMagmaCube; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,18 +36,17 @@ public class RenderMagmaCube extends RenderLiving { super(renderManagerIn, new ModelMagmaCube(), 0.25F); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityMagmaCube var1) { return magmaCubeTextures; } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityMagmaCube entitymagmacube, float f) { int i = entitymagmacube.getSlimeSize(); diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderManager.java b/src/game/java/net/minecraft/client/renderer/entity/RenderManager.java index 2085f3c4..3dba39df 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderManager.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderManager.java @@ -71,6 +71,7 @@ import net.minecraft.entity.monster.EntityGiantZombie; import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.entity.monster.EntityMagmaCube; +import net.minecraft.entity.monster.EntityNetherCreeper; import net.minecraft.entity.monster.EntityPigZombie; import net.minecraft.entity.monster.EntitySilverfish; import net.minecraft.entity.monster.EntitySkeleton; @@ -108,27 +109,41 @@ import net.minecraft.util.ReportedException; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RenderManager { + public static void setupLightmapCoords(Entity entity, float partialTicks) { + int i = entity.getBrightnessForRender(partialTicks); + if (entity.isBurning()) { + DeferredStateManager.setEmissionConstant(1.0f); + i = 15728880; + } + int j = i % 65536; + int k = i / 65536; + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); + } + private Map, Render> entityRenderMap = Maps.newHashMap(); private Map skinMap = Maps.newHashMap(); private RenderPlayer playerRenderer; @@ -149,8 +164,9 @@ public class RenderManager { public double viewerPosZ; private boolean renderOutlines = false; private boolean renderShadow = true; - /**+ - * whether bounding box should be rendered or not + + /** + * + whether bounding box should be rendered or not */ private boolean debugBoundingBox = false; @@ -216,6 +232,8 @@ public class RenderManager { this.entityRenderMap.put(EntityFishHook.class, new RenderFish(this)); this.entityRenderMap.put(EntityHorse.class, new RenderHorse(this, new ModelHorse(), 0.75F)); this.entityRenderMap.put(EntityLightningBolt.class, new RenderLightningBolt(this)); + this.entityRenderMap.put(EntityNetherCreeper.class, new RenderNetherCreeper(this)); + this.playerRenderer = new RenderPlayer(this); this.skinMap.put("default", this.playerRenderer); this.skinMap.put("slim", new RenderPlayer(this, true, false)); @@ -230,36 +248,6 @@ public class RenderManager { Minecraft.getMinecraft().gameSettings.enableFNAWSkins ? this.eaglerRenderer : this.playerRenderer); } - public void setEnableFNAWSkins(boolean en) { - this.skinMap.put("eagler", en ? this.eaglerRenderer : this.playerRenderer); - } - - public void setRenderPosition(double renderPosXIn, double renderPosYIn, double renderPosZIn) { - this.renderPosX = renderPosXIn; - this.renderPosY = renderPosYIn; - this.renderPosZ = renderPosZIn; - } - - public Render getEntityClassRenderObject(Class parClass1) { - Render render = (Render) this.entityRenderMap.get(parClass1); - if (render == null && parClass1 != Entity.class) { - render = this.getEntityClassRenderObject((Class) parClass1.getSuperclass()); - this.entityRenderMap.put(parClass1, render); - } - - return render; - } - - public Render getEntityRenderObject(Entity entityIn) { - if (entityIn instanceof AbstractClientPlayer) { - String s = ((AbstractClientPlayer) entityIn).getSkinType(); - RenderPlayer renderplayer = (RenderPlayer) this.skinMap.get(s); - return renderplayer != null ? renderplayer : this.playerRenderer; - } else { - return this.getEntityClassRenderObject(entityIn.getClass()); - } - } - public void cacheActiveRenderInfo(World worldIn, FontRenderer textRendererIn, Entity livingPlayerIn, Entity pointedEntityIn, GameSettings optionsIn, float partialTicks) { this.worldObj = worldIn; @@ -294,104 +282,6 @@ public class RenderManager { + (livingPlayerIn.posZ - livingPlayerIn.lastTickPosZ) * (double) partialTicks; } - public void setPlayerViewY(float playerViewYIn) { - this.playerViewY = playerViewYIn; - } - - public boolean isRenderShadow() { - return this.renderShadow; - } - - public void setRenderShadow(boolean renderShadowIn) { - this.renderShadow = renderShadowIn; - } - - public void setDebugBoundingBox(boolean debugBoundingBoxIn) { - this.debugBoundingBox = debugBoundingBoxIn; - } - - public boolean isDebugBoundingBox() { - return this.debugBoundingBox; - } - - public boolean renderEntitySimple(Entity entityIn, float partialTicks) { - return this.renderEntityStatic(entityIn, partialTicks, false); - } - - public boolean shouldRender(Entity entityIn, ICamera camera, double camX, double camY, double camZ) { - Render render = this.getEntityRenderObject(entityIn); - return render != null && render.shouldRender(entityIn, camera, camX, camY, camZ); - } - - public boolean renderEntityStatic(Entity entity, float partialTicks, boolean parFlag) { - if (entity.ticksExisted == 0) { - entity.lastTickPosX = entity.posX; - entity.lastTickPosY = entity.posY; - entity.lastTickPosZ = entity.posZ; - } - - double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; - double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; - double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; - if (DynamicLightsStateManager.isInDynamicLightsPass()) { - DynamicLightsStateManager.reportForwardRenderObjectPosition2((float) (d0 - viewerPosX), - (float) (d1 - viewerPosY), (float) (d2 - viewerPosZ)); - } - float f = entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks; - int i = entity.getBrightnessForRender(partialTicks); - if (entity.isBurning()) { - DeferredStateManager.setEmissionConstant(1.0f); - i = 15728880; - } - - int j = i % 65536; - int k = i / 65536; - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - try { - return this.doRenderEntity(entity, d0 - this.renderPosX, d1 - this.renderPosY, d2 - this.renderPosZ, f, - partialTicks, parFlag); - } finally { - DeferredStateManager.setEmissionConstant(0.0f); - } - } - - public static void setupLightmapCoords(Entity entity, float partialTicks) { - int i = entity.getBrightnessForRender(partialTicks); - if (entity.isBurning()) { - DeferredStateManager.setEmissionConstant(1.0f); - i = 15728880; - } - int j = i % 65536; - int k = i / 65536; - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); - } - - public void renderWitherSkull(Entity entityIn, float partialTicks) { - double d0 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double) partialTicks; - double d1 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double) partialTicks; - double d2 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; - Render render = this.getEntityRenderObject(entityIn); - if (render != null && this.renderEngine != null) { - int i = entityIn.getBrightnessForRender(partialTicks); - int j = i % 65536; - int k = i / 65536; - OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); - GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - render.renderName(entityIn, d0 - this.renderPosX, d1 - this.renderPosY, d2 - this.renderPosZ); - } - - } - - public boolean renderEntityWithPosYaw(Entity entityIn, double x, double y, double z, float entityYaw, - float partialTicks) { - try { - return this.doRenderEntity(entityIn, x, y, z, entityYaw, partialTicks, false); - } finally { - DeferredStateManager.setEmissionConstant(0.0f); - } - } - public boolean doRenderEntity(Entity entity, double x, double y, double z, float entityYaw, float partialTicks, boolean parFlag) { Render render = null; @@ -448,9 +338,50 @@ public class RenderManager { } } - /**+ - * Renders the bounding box around an entity when F3+B is - * pressed + public double getDistanceToCamera(double parDouble1, double parDouble2, double parDouble3) { + double d0 = parDouble1 - this.viewerPosX; + double d1 = parDouble2 - this.viewerPosY; + double d2 = parDouble3 - this.viewerPosZ; + return d0 * d0 + d1 * d1 + d2 * d2; + } + + public Render getEntityClassRenderObject(Class parClass1) { + Render render = (Render) this.entityRenderMap.get(parClass1); + if (render == null && parClass1 != Entity.class) { + render = this.getEntityClassRenderObject((Class) parClass1.getSuperclass()); + this.entityRenderMap.put(parClass1, render); + } + + return render; + } + + public Render getEntityRenderObject(Entity entityIn) { + if (entityIn instanceof AbstractClientPlayer) { + String s = ((AbstractClientPlayer) entityIn).getSkinType(); + RenderPlayer renderplayer = (RenderPlayer) this.skinMap.get(s); + return renderplayer != null ? renderplayer : this.playerRenderer; + } else { + return this.getEntityClassRenderObject(entityIn.getClass()); + } + } + + /** + * + Returns the font renderer + */ + public FontRenderer getFontRenderer() { + return this.textRenderer; + } + + public boolean isDebugBoundingBox() { + return this.debugBoundingBox; + } + + public boolean isRenderShadow() { + return this.renderShadow; + } + + /** + * + Renders the bounding box around an entity when F3+B is pressed */ private void renderDebugBoundingBox(Entity entityIn, double parDouble1, double parDouble2, double parDouble3, float parFloat1, float parFloat2) { @@ -491,29 +422,103 @@ public class RenderManager { GlStateManager.depthMask(true); } - /**+ - * World sets this RenderManager's worldObj to the world - * provided + public boolean renderEntitySimple(Entity entityIn, float partialTicks) { + return this.renderEntityStatic(entityIn, partialTicks, false); + } + + public boolean renderEntityStatic(Entity entity, float partialTicks, boolean parFlag) { + if (entity.ticksExisted == 0) { + entity.lastTickPosX = entity.posX; + entity.lastTickPosY = entity.posY; + entity.lastTickPosZ = entity.posZ; + } + + double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double) partialTicks; + double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double) partialTicks; + double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double) partialTicks; + if (DynamicLightsStateManager.isInDynamicLightsPass()) { + DynamicLightsStateManager.reportForwardRenderObjectPosition2((float) (d0 - viewerPosX), + (float) (d1 - viewerPosY), (float) (d2 - viewerPosZ)); + } + float f = entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * partialTicks; + int i = entity.getBrightnessForRender(partialTicks); + if (entity.isBurning()) { + DeferredStateManager.setEmissionConstant(1.0f); + i = 15728880; + } + + int j = i % 65536; + int k = i / 65536; + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + try { + return this.doRenderEntity(entity, d0 - this.renderPosX, d1 - this.renderPosY, d2 - this.renderPosZ, f, + partialTicks, parFlag); + } finally { + DeferredStateManager.setEmissionConstant(0.0f); + } + } + + public boolean renderEntityWithPosYaw(Entity entityIn, double x, double y, double z, float entityYaw, + float partialTicks) { + try { + return this.doRenderEntity(entityIn, x, y, z, entityYaw, partialTicks, false); + } finally { + DeferredStateManager.setEmissionConstant(0.0f); + } + } + + public void renderWitherSkull(Entity entityIn, float partialTicks) { + double d0 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double) partialTicks; + double d1 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double) partialTicks; + double d2 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; + Render render = this.getEntityRenderObject(entityIn); + if (render != null && this.renderEngine != null) { + int i = entityIn.getBrightnessForRender(partialTicks); + int j = i % 65536; + int k = i / 65536; + OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) j / 1.0F, (float) k / 1.0F); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + render.renderName(entityIn, d0 - this.renderPosX, d1 - this.renderPosY, d2 - this.renderPosZ); + } + + } + + /** + * + World sets this RenderManager's worldObj to the world provided */ public void set(World worldIn) { this.worldObj = worldIn; } - public double getDistanceToCamera(double parDouble1, double parDouble2, double parDouble3) { - double d0 = parDouble1 - this.viewerPosX; - double d1 = parDouble2 - this.viewerPosY; - double d2 = parDouble3 - this.viewerPosZ; - return d0 * d0 + d1 * d1 + d2 * d2; + public void setDebugBoundingBox(boolean debugBoundingBoxIn) { + this.debugBoundingBox = debugBoundingBoxIn; } - /**+ - * Returns the font renderer - */ - public FontRenderer getFontRenderer() { - return this.textRenderer; + public void setEnableFNAWSkins(boolean en) { + this.skinMap.put("eagler", en ? this.eaglerRenderer : this.playerRenderer); + } + + public void setPlayerViewY(float playerViewYIn) { + this.playerViewY = playerViewYIn; } public void setRenderOutlines(boolean renderOutlinesIn) { this.renderOutlines = renderOutlinesIn; } + + public void setRenderPosition(double renderPosXIn, double renderPosYIn, double renderPosZIn) { + this.renderPosX = renderPosXIn; + this.renderPosY = renderPosYIn; + this.renderPosZ = renderPosZIn; + } + + public void setRenderShadow(boolean renderShadowIn) { + this.renderShadow = renderShadowIn; + } + + public boolean shouldRender(Entity entityIn, ICamera camera, double camX, double camY, double camZ) { + Render render = this.getEntityRenderObject(entityIn); + return render != null && render.shouldRender(entityIn, camera, camX, camY, camZ); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderMinecart.java b/src/game/java/net/minecraft/client/renderer/entity/RenderMinecart.java index d34fe835..7fd3cc46 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderMinecart.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderMinecart.java @@ -11,30 +11,33 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RenderMinecart extends Render { private static final ResourceLocation minecartTextures = new ResourceLocation("textures/entity/minecart.png"); - /**+ - * instance of ModelMinecart for rendering + /** + * + instance of ModelMinecart for rendering */ protected ModelBase modelMinecart = new ModelMinecart(); @@ -43,14 +46,13 @@ public class RenderMinecart extends Render { this.shadowSize = 0.5F; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(T entityminecart, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -124,18 +126,18 @@ public class RenderMinecart extends Render { super.doRender(entityminecart, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(T var1) { - return minecartTextures; - } - protected void func_180560_a(T minecart, float partialTicks, IBlockState state) { GlStateManager.pushMatrix(); Minecraft.getMinecraft().getBlockRendererDispatcher().renderBlockBrightness(state, minecart.getBrightness(partialTicks)); GlStateManager.popMatrix(); } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(T var1) { + return minecartTextures; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderMinecartMobSpawner.java b/src/game/java/net/minecraft/client/renderer/entity/RenderMinecartMobSpawner.java index 8b73cec4..94547407 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderMinecartMobSpawner.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderMinecartMobSpawner.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.tileentity.TileEntityMobSpawnerRenderer; import net.minecraft.entity.ai.EntityMinecartMobSpawner; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderMooshroom.java b/src/game/java/net/minecraft/client/renderer/entity/RenderMooshroom.java index 087ad524..90bbde33 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderMooshroom.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderMooshroom.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.entity.layers.LayerMooshroomMushroom; import net.minecraft.entity.passive.EntityMooshroom; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +36,9 @@ public class RenderMooshroom extends RenderLiving { this.addLayer(new LayerMooshroomMushroom(this)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityMooshroom var1) { return mooshroomTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderNetherCreeper.java b/src/game/java/net/minecraft/client/renderer/entity/RenderNetherCreeper.java new file mode 100644 index 00000000..068ee42d --- /dev/null +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderNetherCreeper.java @@ -0,0 +1,92 @@ +package net.minecraft.client.renderer.entity; + +import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; +import net.minecraft.client.model.ModelNetherCreeper; +import net.minecraft.client.renderer.entity.layers.LayerNetherCreeperCharge; +import net.minecraft.entity.monster.EntityNetherCreeper; +import net.minecraft.util.MathHelper; +import net.minecraft.util.ResourceLocation; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class RenderNetherCreeper extends RenderLiving { + private static final ResourceLocation creeperTextures = new ResourceLocation( + "starlike:textures/entity/nethercreeper/creeper.png"); + + public RenderNetherCreeper(RenderManager renderManagerIn) { + super(renderManagerIn, new ModelNetherCreeper(), 0.5F); + this.addLayer(new LayerNetherCreeperCharge(this)); + } + + public void doRender(EntityNetherCreeper entitycreeper, double d0, double d1, double d2, float f, float f1) { + float ff = entitycreeper.getCreeperFlashIntensity(f); + if ((int) (ff * 10.0F) % 2 != 0) { + DeferredStateManager.setEmissionConstant(1.0f); + } + try { + super.doRender(entitycreeper, d0, d1, d2, f, f1); + } finally { + DeferredStateManager.setEmissionConstant(0.0f); + } + } + + /** + * + Returns an ARGB int color back. Args: entityLiving, lightBrightness, + * partialTickTime + */ + protected int getColorMultiplier(EntityNetherCreeper entitycreeper, float var2, float f) { + float f1 = entitycreeper.getCreeperFlashIntensity(f); + if ((int) (f1 * 10.0F) % 2 == 0) { + return 0; + } else { + int i = (int) (f1 * 0.2F * 255.0F); + i = MathHelper.clamp_int(i, 0, 255); + return i << 24 | 16777215; + } + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntityNetherCreeper var1) { + return creeperTextures; + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime + */ + protected void preRenderCallback(EntityNetherCreeper entitycreeper, float f) { + float f1 = entitycreeper.getCreeperFlashIntensity(f); + float f2 = 1.0F + MathHelper.sin(f1 * 100.0F) * f1 * 0.01F; + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + f1 = f1 * f1; + f1 = f1 * f1; + float f3 = (1.0F + f1 * 0.4F) * f2; + float f4 = (1.0F + f1 * 0.1F) / f2; + GlStateManager.scale(f3, f4, f3); + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderOcelot.java b/src/game/java/net/minecraft/client/renderer/entity/RenderOcelot.java index 31897ea0..db687add 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderOcelot.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderOcelot.java @@ -5,22 +5,25 @@ import net.minecraft.client.model.ModelBase; import net.minecraft.entity.passive.EntityOcelot; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,9 +39,9 @@ public class RenderOcelot extends RenderLiving { super(renderManagerIn, modelBaseIn, shadowSizeIn); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityOcelot entityocelot) { switch (entityocelot.getTameSkin()) { @@ -54,10 +57,9 @@ public class RenderOcelot extends RenderLiving { } } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityOcelot entityocelot, float f) { super.preRenderCallback(entityocelot, f); diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderPainting.java b/src/game/java/net/minecraft/client/renderer/entity/RenderPainting.java index 2e4d0341..aa873b03 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderPainting.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderPainting.java @@ -11,22 +11,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,14 +42,13 @@ public class RenderPainting extends Render { super(renderManagerIn); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityPainting entitypainting, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -64,9 +66,9 @@ public class RenderPainting extends Render { super.doRender(entitypainting, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityPainting var1) { return KRISTOFFER_PAINTING_TEXTURE; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderPig.java b/src/game/java/net/minecraft/client/renderer/entity/RenderPig.java index 03d9c3a5..8a20067b 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderPig.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderPig.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.entity.layers.LayerSaddle; import net.minecraft.entity.passive.EntityPig; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +36,9 @@ public class RenderPig extends RenderLiving { this.addLayer(new LayerSaddle(this)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityPig var1) { return pigTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderPigZombie.java b/src/game/java/net/minecraft/client/renderer/entity/RenderPigZombie.java index 601f19cc..96b2cf7e 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderPigZombie.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderPigZombie.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.entity.monster.EntityPigZombie; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,9 +44,9 @@ public class RenderPigZombie extends RenderBiped { }); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityPigZombie var1) { return ZOMBIE_PIGMAN_TEXTURE; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderPlayer.java b/src/game/java/net/minecraft/client/renderer/entity/RenderPlayer.java index 44f21993..8ffbc064 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderPlayer.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderPlayer.java @@ -21,22 +21,25 @@ import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,18 +68,13 @@ public class RenderPlayer extends RendererLivingEntity { super(renderManager, modelBase, size); } - public ModelBiped getMainModel() { - return (ModelBiped) super.getMainModel(); - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2, float f, float f1) { @@ -91,6 +89,93 @@ public class RenderPlayer extends RendererLivingEntity { } } + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(AbstractClientPlayer abstractclientplayer) { + return abstractclientplayer.getLocationSkin(); + } + + public ModelBiped getMainModel() { + return (ModelBiped) super.getMainModel(); + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime + */ + protected void preRenderCallback(AbstractClientPlayer var1, float var2) { + float f = 0.9375F; + GlStateManager.scale(f, f, f); + } + + public void renderLeftArm(AbstractClientPlayer clientPlayer) { + if (!zombieModel) { + float f = 1.0F; + GlStateManager.color(f, f, f); + ModelBiped modelplayer = this.getMainModel(); + this.setModelVisibilities(clientPlayer); + modelplayer.isSneak = false; + modelplayer.swingProgress = 0.0F; + modelplayer.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F, clientPlayer); + ((ModelPlayer) modelplayer).renderLeftArm(); + } + } + + /** + * + Sets a simple glTranslate on a LivingEntity. + */ + public void renderLivingAt(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2) { + if (abstractclientplayer.isEntityAlive() && abstractclientplayer.isPlayerSleeping()) { + super.renderLivingAt(abstractclientplayer, d0 + (double) abstractclientplayer.renderOffsetX, + d1 + (double) abstractclientplayer.renderOffsetY, d2 + (double) abstractclientplayer.renderOffsetZ); + } else { + super.renderLivingAt(abstractclientplayer, d0, d1, d2); + } + + } + + protected void renderOffsetLivingLabel(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2, + String s, float f, double d3) { + if (d3 < 100.0D) { + Scoreboard scoreboard = abstractclientplayer.getWorldScoreboard(); + ScoreObjective scoreobjective = scoreboard.getObjectiveInDisplaySlot(2); + if (scoreobjective != null) { + Score score = scoreboard.getValueFromObjective(abstractclientplayer.getName(), scoreobjective); + this.renderLivingLabel(abstractclientplayer, + score.getScorePoints() + " " + scoreobjective.getDisplayNameProfanityFilter(), d0, d1, d2, 64); + d1 += (double) ((float) this.getFontRendererFromRenderManager().FONT_HEIGHT * 1.15F * f); + } + } + + super.renderOffsetLivingLabel(abstractclientplayer, d0, d1, d2, s, f, d3); + } + + public void renderRightArm(AbstractClientPlayer clientPlayer) { + if (!zombieModel) { + float f = 1.0F; + GlStateManager.color(f, f, f); + ModelBiped modelplayer = this.getMainModel(); + this.setModelVisibilities(clientPlayer); + modelplayer.swingProgress = 0.0F; + modelplayer.isSneak = false; + modelplayer.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F, clientPlayer); + ((ModelPlayer) modelplayer).renderRightArm(); + } + } + + protected void rotateCorpse(AbstractClientPlayer abstractclientplayer, float f, float f1, float f2) { + if (abstractclientplayer.isEntityAlive() && abstractclientplayer.isPlayerSleeping()) { + GlStateManager.rotate(abstractclientplayer.getBedOrientationInDegrees(), 0.0F, 1.0F, 0.0F); + GlStateManager.rotate(this.getDeathMaxRotation(abstractclientplayer), 0.0F, 0.0F, 1.0F); + GlStateManager.rotate(270.0F, 0.0F, 1.0F, 0.0F); + } else { + super.rotateCorpse(abstractclientplayer, f, f1, f2); + } + + } + private void setModelVisibilities(AbstractClientPlayer clientPlayer) { ModelBiped modelplayer = this.getMainModel(); if (clientPlayer.isSpectator()) { @@ -129,91 +214,7 @@ public class RenderPlayer extends RendererLivingEntity { } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(AbstractClientPlayer abstractclientplayer) { - return abstractclientplayer.getLocationSkin(); - } - public void transformHeldFull3DItemLayer() { GlStateManager.translate(0.0F, 0.1875F, 0.0F); } - - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime - */ - protected void preRenderCallback(AbstractClientPlayer var1, float var2) { - float f = 0.9375F; - GlStateManager.scale(f, f, f); - } - - protected void renderOffsetLivingLabel(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2, - String s, float f, double d3) { - if (d3 < 100.0D) { - Scoreboard scoreboard = abstractclientplayer.getWorldScoreboard(); - ScoreObjective scoreobjective = scoreboard.getObjectiveInDisplaySlot(2); - if (scoreobjective != null) { - Score score = scoreboard.getValueFromObjective(abstractclientplayer.getName(), scoreobjective); - this.renderLivingLabel(abstractclientplayer, - score.getScorePoints() + " " + scoreobjective.getDisplayNameProfanityFilter(), d0, d1, d2, 64); - d1 += (double) ((float) this.getFontRendererFromRenderManager().FONT_HEIGHT * 1.15F * f); - } - } - - super.renderOffsetLivingLabel(abstractclientplayer, d0, d1, d2, s, f, d3); - } - - public void renderRightArm(AbstractClientPlayer clientPlayer) { - if (!zombieModel) { - float f = 1.0F; - GlStateManager.color(f, f, f); - ModelBiped modelplayer = this.getMainModel(); - this.setModelVisibilities(clientPlayer); - modelplayer.swingProgress = 0.0F; - modelplayer.isSneak = false; - modelplayer.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F, clientPlayer); - ((ModelPlayer) modelplayer).renderRightArm(); - } - } - - public void renderLeftArm(AbstractClientPlayer clientPlayer) { - if (!zombieModel) { - float f = 1.0F; - GlStateManager.color(f, f, f); - ModelBiped modelplayer = this.getMainModel(); - this.setModelVisibilities(clientPlayer); - modelplayer.isSneak = false; - modelplayer.swingProgress = 0.0F; - modelplayer.setRotationAngles(0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0625F, clientPlayer); - ((ModelPlayer) modelplayer).renderLeftArm(); - } - } - - /**+ - * Sets a simple glTranslate on a LivingEntity. - */ - public void renderLivingAt(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2) { - if (abstractclientplayer.isEntityAlive() && abstractclientplayer.isPlayerSleeping()) { - super.renderLivingAt(abstractclientplayer, d0 + (double) abstractclientplayer.renderOffsetX, - d1 + (double) abstractclientplayer.renderOffsetY, d2 + (double) abstractclientplayer.renderOffsetZ); - } else { - super.renderLivingAt(abstractclientplayer, d0, d1, d2); - } - - } - - protected void rotateCorpse(AbstractClientPlayer abstractclientplayer, float f, float f1, float f2) { - if (abstractclientplayer.isEntityAlive() && abstractclientplayer.isPlayerSleeping()) { - GlStateManager.rotate(abstractclientplayer.getBedOrientationInDegrees(), 0.0F, 1.0F, 0.0F); - GlStateManager.rotate(this.getDeathMaxRotation(abstractclientplayer), 0.0F, 0.0F, 1.0F); - GlStateManager.rotate(270.0F, 0.0F, 1.0F, 0.0F); - } else { - super.rotateCorpse(abstractclientplayer, f, f1, f2); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderPotion.java b/src/game/java/net/minecraft/client/renderer/entity/RenderPotion.java index 3461f653..a5670e8a 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderPotion.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderPotion.java @@ -4,22 +4,25 @@ import net.minecraft.entity.projectile.EntityPotion; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderRabbit.java b/src/game/java/net/minecraft/client/renderer/entity/RenderRabbit.java index 17e6707d..ad818e77 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderRabbit.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderRabbit.java @@ -5,22 +5,25 @@ import net.minecraft.entity.passive.EntityRabbit; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,9 +43,9 @@ public class RenderRabbit extends RenderLiving { super(renderManagerIn, modelBaseIn, shadowSizeIn); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityRabbit entityrabbit) { String s = EnumChatFormatting.getTextWithoutFormattingCodes(entityrabbit.getName()); diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSheep.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSheep.java index 0dedf5ce..416fb10c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSheep.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSheep.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.entity.layers.LayerSheepWool; import net.minecraft.entity.passive.EntitySheep; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,9 +37,9 @@ public class RenderSheep extends RenderLiving { this.addLayer(new LayerSheepWool(this)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntitySheep var1) { return shearedSheepTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSilverfish.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSilverfish.java index b11b0b12..42e7125a 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSilverfish.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSilverfish.java @@ -4,22 +4,25 @@ import net.minecraft.client.model.ModelSilverfish; import net.minecraft.entity.monster.EntitySilverfish; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,9 +38,9 @@ public class RenderSilverfish extends RenderLiving { return 180.0F; } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntitySilverfish var1) { return silverfishTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSkeleton.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSkeleton.java index da12fda4..53b84aa7 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSkeleton.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSkeleton.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.entity.monster.EntitySkeleton; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,10 +47,17 @@ public class RenderSkeleton extends RenderBiped { }); } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntitySkeleton entityskeleton) { + return entityskeleton.getSkeletonType() == 1 ? witherSkeletonTextures : skeletonTextures; + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntitySkeleton entityskeleton, float var2) { if (entityskeleton.getSkeletonType() == 1) { @@ -59,12 +69,4 @@ public class RenderSkeleton extends RenderBiped { public void transformHeldFull3DItemLayer() { GlStateManager.translate(0.09375F, 0.1875F, 0.0F); } - - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntitySkeleton entityskeleton) { - return entityskeleton.getSkeletonType() == 1 ? witherSkeletonTextures : skeletonTextures; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSlime.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSlime.java index 3d170bbc..247d4c9d 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSlime.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSlime.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.entity.layers.LayerSlimeGel; import net.minecraft.entity.monster.EntitySlime; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,24 +37,30 @@ public class RenderSlime extends RenderLiving { this.addLayer(new LayerSlimeGel(this)); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntitySlime entityslime, double d0, double d1, double d2, float f, float f1) { this.shadowSize = 0.25F * (float) entityslime.getSlimeSize(); super.doRender(entityslime, d0, d1, d2, f, f1); } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntitySlime var1) { + return slimeTextures; + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntitySlime entityslime, float f) { float f1 = (float) entityslime.getSlimeSize(); @@ -60,12 +69,4 @@ public class RenderSlime extends RenderLiving { float f3 = 1.0F / (f2 + 1.0F); GlStateManager.scale(f3 * f1, 1.0F / f3 * f1, f3 * f1); } - - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntitySlime var1) { - return slimeTextures; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSnowMan.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSnowMan.java index 5908f441..11e1e394 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSnowMan.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSnowMan.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.entity.layers.LayerSnowmanHead; import net.minecraft.entity.monster.EntitySnowman; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +36,9 @@ public class RenderSnowMan extends RenderLiving { this.addLayer(new LayerSnowmanHead(this)); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntitySnowman var1) { return snowManTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSnowball.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSnowball.java index b521468a..40bb185f 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSnowball.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSnowball.java @@ -10,22 +10,25 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,14 +43,13 @@ public class RenderSnowball extends Render { this.field_177083_e = parRenderItem; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(T entity, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -76,9 +78,9 @@ public class RenderSnowball extends Render { return new ItemStack(this.field_177084_a, 1, 0); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(Entity var1) { return TextureMap.locationBlocksTexture; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSpider.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSpider.java index 3904d5c9..a8177f25 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSpider.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSpider.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.entity.layers.LayerSpiderEyes; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,9 +40,9 @@ public class RenderSpider extends RenderLiving { return 180.0F; } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(T var1) { return spiderTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderSquid.java b/src/game/java/net/minecraft/client/renderer/entity/RenderSquid.java index 88b82010..e0228642 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderSquid.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderSquid.java @@ -5,22 +5,25 @@ import net.minecraft.client.model.ModelBase; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,14 +35,21 @@ public class RenderSquid extends RenderLiving { super(renderManagerIn, modelBaseIn, shadowSizeIn); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntitySquid var1) { return squidTextures; } + /** + * + Defines what float the third param in setRotationAngles of ModelBase is + */ + protected float handleRotationFloat(EntitySquid entitysquid, float f) { + return entitysquid.lastTentacleAngle + (entitysquid.tentacleAngle - entitysquid.lastTentacleAngle) * f; + } + protected void rotateCorpse(EntitySquid entitysquid, float var2, float f, float f1) { float f2 = entitysquid.prevSquidPitch + (entitysquid.squidPitch - entitysquid.prevSquidPitch) * f1; float f3 = entitysquid.prevSquidYaw + (entitysquid.squidYaw - entitysquid.prevSquidYaw) * f1; @@ -49,12 +59,4 @@ public class RenderSquid extends RenderLiving { GlStateManager.rotate(f3, 0.0F, 1.0F, 0.0F); GlStateManager.translate(0.0F, -1.2F, 0.0F); } - - /**+ - * Defines what float the third param in setRotationAngles of - * ModelBase is - */ - protected float handleRotationFloat(EntitySquid entitysquid, float f) { - return entitysquid.lastTentacleAngle + (entitysquid.tentacleAngle - entitysquid.lastTentacleAngle) * f; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderTNTPrimed.java b/src/game/java/net/minecraft/client/renderer/entity/RenderTNTPrimed.java index 84e25a98..52c8223c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderTNTPrimed.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderTNTPrimed.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DST_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -12,22 +13,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,14 +42,13 @@ public class RenderTNTPrimed extends Render { this.shadowSize = 0.5F; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityTNTPrimed entitytntprimed, double d0, double d1, double d2, float f, float f1) { BlockRendererDispatcher blockrendererdispatcher = Minecraft.getMinecraft().getBlockRendererDispatcher(); @@ -101,9 +104,9 @@ public class RenderTNTPrimed extends Render { } } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityTNTPrimed var1) { return TextureMap.locationBlocksTexture; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderTntMinecart.java b/src/game/java/net/minecraft/client/renderer/entity/RenderTntMinecart.java index 75cc411a..dbd137d6 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderTntMinecart.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderTntMinecart.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DST_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.block.state.IBlockState; @@ -10,22 +11,25 @@ import net.minecraft.entity.item.EntityMinecartTNT; import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderVillager.java b/src/game/java/net/minecraft/client/renderer/entity/RenderVillager.java index b0a47d5b..6c22ad74 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderVillager.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderVillager.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.entity.layers.LayerCustomHead; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,13 +48,9 @@ public class RenderVillager extends RenderLiving { this.addLayer(new LayerCustomHead(this.getMainModel().villagerHead)); } - public ModelVillager getMainModel() { - return (ModelVillager) super.getMainModel(); - } - - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityVillager entityvillager) { switch (entityvillager.getProfession()) { @@ -70,10 +69,13 @@ public class RenderVillager extends RenderLiving { } } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + public ModelVillager getMainModel() { + return (ModelVillager) super.getMainModel(); + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityVillager entityvillager, float var2) { float f = 0.9375F; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderWitch.java b/src/game/java/net/minecraft/client/renderer/entity/RenderWitch.java index 60fa308c..4f604969 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderWitch.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderWitch.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.entity.layers.LayerHeldItemWitch; import net.minecraft.entity.monster.EntityWitch; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,39 +37,37 @@ public class RenderWitch extends RenderLiving { this.addLayer(new LayerHeldItemWitch(this)); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityWitch entitywitch, double d0, double d1, double d2, float f, float f1) { ((ModelWitch) this.mainModel).field_82900_g = entitywitch.getHeldItem() != null; super.doRender(entitywitch, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityWitch var1) { return witchTextures; } - public void transformHeldFull3DItemLayer() { - GlStateManager.translate(0.0F, 0.1875F, 0.0F); - } - - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityWitch var1, float var2) { float f = 0.9375F; GlStateManager.scale(f, f, f); } + + public void transformHeldFull3DItemLayer() { + GlStateManager.translate(0.0F, 0.1875F, 0.0F); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderWither.java b/src/game/java/net/minecraft/client/renderer/entity/RenderWither.java index d84e0d8b..92861c7a 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderWither.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderWither.java @@ -7,22 +7,25 @@ import net.minecraft.entity.boss.BossStatus; import net.minecraft.entity.boss.EntityWither; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,33 +40,31 @@ public class RenderWither extends RenderLiving { this.addLayer(new LayerWitherAura(this)); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityWither entitywither, double d0, double d1, double d2, float f, float f1) { BossStatus.setBossStatus(entitywither, true); super.doRender(entitywither, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityWither entitywither) { int i = entitywither.getInvulTime(); return i > 0 && (i > 80 || i / 5 % 2 != 1) ? invulnerableWitherTextures : witherTextures; } - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime */ protected void preRenderCallback(EntityWither entitywither, float f) { float f1 = 2.0F; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderWolf.java b/src/game/java/net/minecraft/client/renderer/entity/RenderWolf.java index 7935ec6d..918c305c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderWolf.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderWolf.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.entity.layers.LayerWolfCollar; import net.minecraft.entity.passive.EntityWolf; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,22 +41,13 @@ public class RenderWolf extends RenderLiving { this.addLayer(new LayerWolfCollar(this)); } - /**+ - * Defines what float the third param in setRotationAngles of - * ModelBase is - */ - protected float handleRotationFloat(EntityWolf entitywolf, float var2) { - return entitywolf.getTailRotation(); - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityWolf entitywolf, double d0, double d1, double d2, float f, float f1) { if (entitywolf.isWolfWet()) { @@ -64,11 +58,18 @@ public class RenderWolf extends RenderLiving { super.doRender(entitywolf, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityWolf entitywolf) { return entitywolf.isTamed() ? tamedWolfTextures : (entitywolf.isAngry() ? anrgyWolfTextures : wolfTextures); } + + /** + * + Defines what float the third param in setRotationAngles of ModelBase is + */ + protected float handleRotationFloat(EntityWolf entitywolf, float var2) { + return entitywolf.getTailRotation(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderXPOrb.java b/src/game/java/net/minecraft/client/renderer/entity/RenderXPOrb.java index 3a50c953..ff7dff3c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderXPOrb.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderXPOrb.java @@ -9,22 +9,25 @@ import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,14 +42,13 @@ public class RenderXPOrb extends Render { this.shadowOpaque = 0.75F; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityXPOrb entityxporb, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -92,9 +94,9 @@ public class RenderXPOrb extends Render { super.doRender(entityxporb, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityXPOrb var1) { return experienceOrbTextures; diff --git a/src/game/java/net/minecraft/client/renderer/entity/RenderZombie.java b/src/game/java/net/minecraft/client/renderer/entity/RenderZombie.java index 2c2d4ba2..4a36e3a6 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RenderZombie.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RenderZombie.java @@ -15,22 +15,25 @@ import net.minecraft.client.renderer.entity.layers.LayerVillagerArmor; import net.minecraft.entity.monster.EntityZombie; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -68,28 +71,19 @@ public class RenderZombie extends RenderBiped { this.field_177121_n = Lists.newArrayList(this.layerRenderers); } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityZombie entityzombie, double d0, double d1, double d2, float f, float f1) { this.func_82427_a(entityzombie); super.doRender(entityzombie, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. - */ - protected ResourceLocation getEntityTexture(EntityZombie entityzombie) { - return entityzombie.isVillager() ? zombieVillagerTextures : zombieTextures; - } - private void func_82427_a(EntityZombie zombie) { if (zombie.isVillager()) { this.mainModel = this.zombieVillagerModel; @@ -102,6 +96,14 @@ public class RenderZombie extends RenderBiped { this.modelBipedMain = (ModelBiped) this.mainModel; } + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. + */ + protected ResourceLocation getEntityTexture(EntityZombie entityzombie) { + return entityzombie.isVillager() ? zombieVillagerTextures : zombieTextures; + } + protected void rotateCorpse(EntityZombie entityzombie, float f, float f1, float f2) { if (entityzombie.isConverting()) { f1 += (float) (Math.cos((double) entityzombie.ticksExisted * 3.25D) * 3.141592653589793D * 0.25D); diff --git a/src/game/java/net/minecraft/client/renderer/entity/RendererLivingEntity.java b/src/game/java/net/minecraft/client/renderer/entity/RendererLivingEntity.java index ad85eabb..6d9a454b 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/RendererLivingEntity.java +++ b/src/game/java/net/minecraft/client/renderer/entity/RendererLivingEntity.java @@ -1,12 +1,14 @@ package net.minecraft.client.renderer.entity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import java.util.List; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; @@ -37,22 +39,25 @@ import net.minecraft.scoreboard.Team; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,9 +65,19 @@ import net.minecraft.util.MathHelper; public abstract class RendererLivingEntity extends Render { private static final Logger logger = LogManager.getLogger(); private static final DynamicTexture field_177096_e = new DynamicTexture(16, 16); + static { + int[] aint = field_177096_e.getTextureData(); + + for (int i = 0; i < 256; ++i) { + aint[i] = -1; + } + + field_177096_e.updateDynamicTexture(); + } protected ModelBase mainModel; protected FloatBuffer brightnessBuffer = GLAllocation.createDirectFloatBuffer(4); protected List> layerRenderers = Lists.newArrayList(); + protected boolean renderOutlines = false; public RendererLivingEntity(RenderManager renderManagerIn, ModelBase modelBaseIn, float shadowSizeIn) { @@ -75,45 +90,39 @@ public abstract class RendererLivingEntity extends R return this.layerRenderers.add((LayerRenderer) layer); } - protected > boolean removeLayer(U layer) { - return this.layerRenderers.remove(layer); - } - - public ModelBase getMainModel() { - return this.mainModel; - } - - /**+ - * Returns a rotation angle that is inbetween two other rotation - * angles. par1 and par2 are the angles between which to - * interpolate, par3 is probably a float between 0.0 and 1.0 - * that tells us where "between" the two angles we are. Example: - * par1 = 30, par2 = 50, par3 = 0.5, then return = 40 - */ - protected float interpolateRotation(float par1, float par2, float par3) { - float f; - for (f = par2 - par1; f < -180.0F; f += 360.0F) { - ; + protected boolean canRenderName(T entitylivingbase) { + EntityPlayerSP entityplayersp = Minecraft.getMinecraft().thePlayer; + if (entitylivingbase instanceof EntityPlayer && entitylivingbase != entityplayersp) { + Team team = entitylivingbase.getTeam(); + Team team1 = entityplayersp.getTeam(); + if (team != null) { + Team.EnumVisible team$enumvisible = team.getNameTagVisibility(); + switch (team$enumvisible) { + case ALWAYS: + return true; + case NEVER: + return false; + case HIDE_FOR_OTHER_TEAMS: + return team1 == null || team.isSameTeam(team1); + case HIDE_FOR_OWN_TEAM: + return team1 == null || !team.isSameTeam(team1); + default: + return true; + } + } } - while (f >= 180.0F) { - f -= 360.0F; - } - - return par1 + par3 * f; + return Minecraft.isGuiEnabled() && entitylivingbase != this.renderManager.livingPlayer + && !entitylivingbase.isInvisibleToPlayer(entityplayersp) && entitylivingbase.riddenByEntity == null; } - public void transformHeldFull3DItemLayer() { - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(T entitylivingbase, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -207,42 +216,90 @@ public abstract class RendererLivingEntity extends R } } - protected boolean setScoreTeamColor(T entityLivingBaseIn) { - int i = 16777215; - if (entityLivingBaseIn instanceof EntityPlayer) { - ScorePlayerTeam scoreplayerteam = (ScorePlayerTeam) entityLivingBaseIn.getTeam(); - if (scoreplayerteam != null) { - String s = FontRenderer.getFormatFromString(scoreplayerteam.getColorPrefix()); - if (s.length() >= 2) { - i = this.getFontRendererFromRenderManager().getColorCode(s.charAt(1)); - } + /** + * + Returns an ARGB int color back. Args: entityLiving, lightBrightness, + * partialTickTime + */ + protected int getColorMultiplier(T var1, float var2, float var3) { + return 0; + } + + protected float getDeathMaxRotation(T var1) { + return 90.0F; + } + + public ModelBase getMainModel() { + return this.mainModel; + } + + /** + * + Returns where in the swing animation the living entity is (from 0 to 1). + * Args : entity, partialTickTime + */ + protected float getSwingProgress(T livingBase, float partialTickTime) { + return livingBase.getSwingProgress(partialTickTime); + } + + /** + * + Defines what float the third param in setRotationAngles of ModelBase is + */ + protected float handleRotationFloat(T entitylivingbase, float f) { + return (float) entitylivingbase.ticksExisted + f; + } + + /** + * + Returns a rotation angle that is inbetween two other rotation angles. par1 + * and par2 are the angles between which to interpolate, par3 is probably a + * float between 0.0 and 1.0 that tells us where "between" the two angles we + * are. Example: par1 = 30, par2 = 50, par3 = 0.5, then return = 40 + */ + protected float interpolateRotation(float par1, float par2, float par3) { + float f; + for (f = par2 - par1; f < -180.0F; f += 360.0F) { + ; + } + + while (f >= 180.0F) { + f -= 360.0F; + } + + return par1 + par3 * f; + } + + /** + * + Allows the render to do any OpenGL state modifications necessary before the + * model is rendered. Args: entityLiving, partialTickTime + */ + protected void preRenderCallback(T var1, float var2) { + } + + protected > boolean removeLayer(U layer) { + return this.layerRenderers.remove(layer); + } + + protected void renderLayers(T entitylivingbaseIn, float partialTicks, float parFloat2, float parFloat3, + float parFloat4, float parFloat5, float parFloat6, float parFloat7) { + for (int i = 0, l = this.layerRenderers.size(); i < l; ++i) { + LayerRenderer layerrenderer = this.layerRenderers.get(i); + boolean flag = this.setBrightness(entitylivingbaseIn, parFloat3, layerrenderer.shouldCombineTextures()); + layerrenderer.doRenderLayer(entitylivingbaseIn, partialTicks, parFloat2, parFloat3, parFloat4, parFloat5, + parFloat6, parFloat7); + if (flag) { + this.unsetBrightness(); } } - float f1 = (float) (i >> 16 & 255) / 255.0F; - float f2 = (float) (i >> 8 & 255) / 255.0F; - float f = (float) (i & 255) / 255.0F; - GlStateManager.disableLighting(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - GlStateManager.color(f1, f2, f, 1.0F); - GlStateManager.disableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.disableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - return true; } - protected void unsetScoreTeamColor() { - GlStateManager.enableLighting(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); - GlStateManager.enableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); - GlStateManager.enableTexture2D(); - GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + /** + * + Sets a simple glTranslate on a LivingEntity. + */ + public void renderLivingAt(T entityLivingBaseIn, double x, double y, double z) { + GlStateManager.translate((float) x, (float) y, (float) z); } - /**+ - * Renders the model in RenderLiving + /** + * + Renders the model in RenderLiving */ protected void renderModel(T entitylivingbase, float f, float f1, float f2, float f3, float f4, float f5) { // f8, // f7, @@ -336,114 +393,6 @@ public abstract class RendererLivingEntity extends R } - protected boolean setDoRenderBrightness(T entityLivingBaseIn, float partialTicks) { - return this.setBrightness(entityLivingBaseIn, partialTicks, true); - } - - public boolean setBrightness(T entitylivingbaseIn, float partialTicks, boolean combineTextures) { - float f = entitylivingbaseIn.getBrightness(partialTicks); - int i = this.getColorMultiplier(entitylivingbaseIn, f, partialTicks); - boolean flag = (i >> 24 & 255) > 0; - boolean flag1 = entitylivingbaseIn.hurtTime > 0 || entitylivingbaseIn.deathTime > 0; - if (!flag && !flag1) { - return false; - } else if (!flag && !combineTextures) { - return false; - } else { - GlStateManager.enableShaderBlendAdd(); - float f1 = 1.0F - (float) (i >>> 24 & 255) / 255.0F; - float f2 = (float) (i >>> 16 & 255) / 255.0F; - float f3 = (float) (i >>> 8 & 255) / 255.0F; - float f4 = (float) (i & 255) / 255.0F; - GlStateManager.setShaderBlendSrc(f1, f1, f1, 1.0F); - GlStateManager.setShaderBlendAdd(f2 * f1 + 0.4F, f3 * f1, f4 * f1, 0.0f); - return true; - } - } - - public void unsetBrightness() { - GlStateManager.disableShaderBlendAdd(); - } - - /**+ - * Sets a simple glTranslate on a LivingEntity. - */ - public void renderLivingAt(T entityLivingBaseIn, double x, double y, double z) { - GlStateManager.translate((float) x, (float) y, (float) z); - } - - protected void rotateCorpse(T entitylivingbase, float var2, float f, float f1) { - GlStateManager.rotate(180.0F - f, 0.0F, 1.0F, 0.0F); - if (entitylivingbase.deathTime > 0) { - float f2 = ((float) entitylivingbase.deathTime + f1 - 1.0F) / 20.0F * 1.6F; - f2 = MathHelper.sqrt_float(f2); - if (f2 > 1.0F) { - f2 = 1.0F; - } - - GlStateManager.rotate(f2 * this.getDeathMaxRotation(entitylivingbase), 0.0F, 0.0F, 1.0F); - } else { - String s = EnumChatFormatting.getTextWithoutFormattingCodes(entitylivingbase.getName()); - if (s != null && (s.equals("Dinnerbone") || s.equals("Grumm")) - && (!(entitylivingbase instanceof EntityPlayer) - || ((EntityPlayer) entitylivingbase).isWearing(EnumPlayerModelParts.CAPE))) { - GlStateManager.translate(0.0F, entitylivingbase.height + 0.1F, 0.0F); - GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); - } - } - - } - - /**+ - * Returns where in the swing animation the living entity is - * (from 0 to 1). Args : entity, partialTickTime - */ - protected float getSwingProgress(T livingBase, float partialTickTime) { - return livingBase.getSwingProgress(partialTickTime); - } - - /**+ - * Defines what float the third param in setRotationAngles of - * ModelBase is - */ - protected float handleRotationFloat(T entitylivingbase, float f) { - return (float) entitylivingbase.ticksExisted + f; - } - - protected void renderLayers(T entitylivingbaseIn, float partialTicks, float parFloat2, float parFloat3, - float parFloat4, float parFloat5, float parFloat6, float parFloat7) { - for (int i = 0, l = this.layerRenderers.size(); i < l; ++i) { - LayerRenderer layerrenderer = this.layerRenderers.get(i); - boolean flag = this.setBrightness(entitylivingbaseIn, parFloat3, layerrenderer.shouldCombineTextures()); - layerrenderer.doRenderLayer(entitylivingbaseIn, partialTicks, parFloat2, parFloat3, parFloat4, parFloat5, - parFloat6, parFloat7); - if (flag) { - this.unsetBrightness(); - } - } - - } - - protected float getDeathMaxRotation(T var1) { - return 90.0F; - } - - /**+ - * Returns an ARGB int color back. Args: entityLiving, - * lightBrightness, partialTickTime - */ - protected int getColorMultiplier(T var1, float var2, float var3) { - return 0; - } - - /**+ - * Allows the render to do any OpenGL state modifications - * necessary before the model is rendered. Args: entityLiving, - * partialTickTime - */ - protected void preRenderCallback(T var1, float var2) { - } - public void renderName(T entitylivingbase, double d0, double d1, double d2) { if (this.canRenderName(entitylivingbase)) { double d3 = entitylivingbase.getDistanceSqToEntity(this.renderManager.livingPlayer); @@ -497,43 +446,95 @@ public abstract class RendererLivingEntity extends R } } - protected boolean canRenderName(T entitylivingbase) { - EntityPlayerSP entityplayersp = Minecraft.getMinecraft().thePlayer; - if (entitylivingbase instanceof EntityPlayer && entitylivingbase != entityplayersp) { - Team team = entitylivingbase.getTeam(); - Team team1 = entityplayersp.getTeam(); - if (team != null) { - Team.EnumVisible team$enumvisible = team.getNameTagVisibility(); - switch (team$enumvisible) { - case ALWAYS: - return true; - case NEVER: - return false; - case HIDE_FOR_OTHER_TEAMS: - return team1 == null || team.isSameTeam(team1); - case HIDE_FOR_OWN_TEAM: - return team1 == null || !team.isSameTeam(team1); - default: - return true; - } + protected void rotateCorpse(T entitylivingbase, float var2, float f, float f1) { + GlStateManager.rotate(180.0F - f, 0.0F, 1.0F, 0.0F); + if (entitylivingbase.deathTime > 0) { + float f2 = ((float) entitylivingbase.deathTime + f1 - 1.0F) / 20.0F * 1.6F; + f2 = MathHelper.sqrt_float(f2); + if (f2 > 1.0F) { + f2 = 1.0F; + } + + GlStateManager.rotate(f2 * this.getDeathMaxRotation(entitylivingbase), 0.0F, 0.0F, 1.0F); + } else { + String s = EnumChatFormatting.getTextWithoutFormattingCodes(entitylivingbase.getName()); + if (s != null && (s.equals("Dinnerbone") || s.equals("Grumm")) + && (!(entitylivingbase instanceof EntityPlayer) + || ((EntityPlayer) entitylivingbase).isWearing(EnumPlayerModelParts.CAPE))) { + GlStateManager.translate(0.0F, entitylivingbase.height + 0.1F, 0.0F); + GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F); } } - return Minecraft.isGuiEnabled() && entitylivingbase != this.renderManager.livingPlayer - && !entitylivingbase.isInvisibleToPlayer(entityplayersp) && entitylivingbase.riddenByEntity == null; + } + + public boolean setBrightness(T entitylivingbaseIn, float partialTicks, boolean combineTextures) { + float f = entitylivingbaseIn.getBrightness(partialTicks); + int i = this.getColorMultiplier(entitylivingbaseIn, f, partialTicks); + boolean flag = (i >> 24 & 255) > 0; + boolean flag1 = entitylivingbaseIn.hurtTime > 0 || entitylivingbaseIn.deathTime > 0; + if (!flag && !flag1) { + return false; + } else if (!flag && !combineTextures) { + return false; + } else { + GlStateManager.enableShaderBlendAdd(); + float f1 = 1.0F - (float) (i >>> 24 & 255) / 255.0F; + float f2 = (float) (i >>> 16 & 255) / 255.0F; + float f3 = (float) (i >>> 8 & 255) / 255.0F; + float f4 = (float) (i & 255) / 255.0F; + GlStateManager.setShaderBlendSrc(f1, f1, f1, 1.0F); + GlStateManager.setShaderBlendAdd(f2 * f1 + 0.4F, f3 * f1, f4 * f1, 0.0f); + return true; + } + } + + protected boolean setDoRenderBrightness(T entityLivingBaseIn, float partialTicks) { + return this.setBrightness(entityLivingBaseIn, partialTicks, true); } public void setRenderOutlines(boolean renderOutlinesIn) { this.renderOutlines = renderOutlinesIn; } - static { - int[] aint = field_177096_e.getTextureData(); - - for (int i = 0; i < 256; ++i) { - aint[i] = -1; + protected boolean setScoreTeamColor(T entityLivingBaseIn) { + int i = 16777215; + if (entityLivingBaseIn instanceof EntityPlayer) { + ScorePlayerTeam scoreplayerteam = (ScorePlayerTeam) entityLivingBaseIn.getTeam(); + if (scoreplayerteam != null) { + String s = FontRenderer.getFormatFromString(scoreplayerteam.getColorPrefix()); + if (s.length() >= 2) { + i = this.getFontRendererFromRenderManager().getColorCode(s.charAt(1)); + } + } } - field_177096_e.updateDynamicTexture(); + float f1 = (float) (i >> 16 & 255) / 255.0F; + float f2 = (float) (i >> 8 & 255) / 255.0F; + float f = (float) (i & 255) / 255.0F; + GlStateManager.disableLighting(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + GlStateManager.color(f1, f2, f, 1.0F); + GlStateManager.disableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.disableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + return true; + } + + public void transformHeldFull3DItemLayer() { + } + + public void unsetBrightness() { + GlStateManager.disableShaderBlendAdd(); + } + + protected void unsetScoreTeamColor() { + GlStateManager.enableLighting(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); + GlStateManager.enableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.lightmapTexUnit); + GlStateManager.enableTexture2D(); + GlStateManager.setActiveTexture(OpenGlHelper.defaultTexUnit); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArmorBase.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArmorBase.java index 7dea1abb..3e64f85d 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArmorBase.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArmorBase.java @@ -1,7 +1,14 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; +import java.io.IOException; import java.util.Map; import com.google.common.collect.Maps; @@ -12,6 +19,7 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.EaglerDeferredPipeline; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ShadersRenderPassFuture; import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; +import net.minecraft.client.Minecraft; import net.minecraft.client.model.ModelBase; import net.minecraft.client.renderer.EntityRenderer; import net.minecraft.client.renderer.entity.RendererLivingEntity; @@ -20,22 +28,25 @@ import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,6 +54,7 @@ import net.minecraft.util.ResourceLocation; public abstract class LayerArmorBase implements LayerRenderer { protected static final ResourceLocation ENCHANTED_ITEM_GLINT_RES = new ResourceLocation( "textures/misc/enchanted_item_glint.png"); + private static final Map ARMOR_TEXTURE_RES_MAP = Maps.newHashMap(); protected T field_177189_c; protected T field_177186_d; private final RendererLivingEntity renderer; @@ -51,7 +63,6 @@ public abstract class LayerArmorBase implements LayerRender private float colorG = 1.0F; private float colorB = 1.0F; private boolean field_177193_i; - private static final Map ARMOR_TEXTURE_RES_MAP = Maps.newHashMap(); public LayerArmorBase(RendererLivingEntity rendererIn) { this.renderer = rendererIn; @@ -70,8 +81,92 @@ public abstract class LayerArmorBase implements LayerRender 1); } - public boolean shouldCombineTextures() { - return false; + public T func_177175_a(int parInt1) { + return (T) (this.isSlotForLeggings(parInt1) ? this.field_177189_c : this.field_177186_d); + } + + protected abstract void func_177179_a(T var1, int var2); + + private void func_177183_a(EntityLivingBase entitylivingbaseIn, T modelbaseIn, float parFloat1, float parFloat2, + float parFloat3, float parFloat4, float parFloat5, float parFloat6, float parFloat7) { + float f = (float) entitylivingbaseIn.ticksExisted + parFloat3; + this.renderer.bindTexture(ENCHANTED_ITEM_GLINT_RES); + GlStateManager.enableBlend(); + GlStateManager.depthFunc(GL_EQUAL); + GlStateManager.depthMask(false); + float f1 = 0.5F; + boolean d = !DeferredStateManager.isInDeferredPass(); + if (d) { + GlStateManager.color(f1, f1, f1, 1.0F); + } + + for (int i = 0; i < 2; ++i) { + GlStateManager.disableLighting(); + float f2 = 0.76F; + if (d) { + GlStateManager.blendFunc(GL_SRC_COLOR, GL_ONE); + GlStateManager.color(0.5F * f2, 0.25F * f2, 0.8F * f2, 1.0F); + } + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.loadIdentity(); + float f3 = 0.33333334F; + GlStateManager.scale(f3, f3, f3); + GlStateManager.rotate(30.0F - (float) i * 60.0F, 0.0F, 0.0F, 1.0F); + GlStateManager.translate(0.0F, f * (0.001F + (float) i * 0.003F) * 20.0F, 0.0F); + GlStateManager.matrixMode(GL_MODELVIEW); + modelbaseIn.render(entitylivingbaseIn, parFloat1, parFloat2, parFloat4, parFloat5, parFloat6, parFloat7); + } + + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.loadIdentity(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.enableLighting(); + GlStateManager.depthMask(true); + GlStateManager.depthFunc(GL_LEQUAL); + GlStateManager.disableBlend(); + } + + private ResourceLocation getArmorResource(ItemArmor parItemArmor, boolean parFlag) { + return this.getArmorResource(parItemArmor, parFlag, (String) null); + } + + private ResourceLocation getArmorResource(ItemArmor parItemArmor, boolean parFlag, String parString1) { + String s1 = HString.format("textures/models/armor/%s_layer_%d%s.png", + new Object[] { parItemArmor.getArmorMaterial().getName(), Integer.valueOf(parFlag ? 2 : 1), + parString1 == null ? "" : HString.format("_%s", new Object[] { parString1 }) }); + String s2 = HString.format("starlike:textures/models/armor/%s_layer_%d%s.png", + new Object[] { parItemArmor.getArmorMaterial().getName(), Integer.valueOf(parFlag ? 2 : 1), + parString1 == null ? "" : HString.format("_%s", new Object[] { parString1 }) }); + ResourceLocation resourcelocation1 = (ResourceLocation) ARMOR_TEXTURE_RES_MAP.get(s1); + ResourceLocation resourcelocation2 = (ResourceLocation) ARMOR_TEXTURE_RES_MAP.get(s2); + if (resourcelocation1 != null) { + return resourcelocation1; + } else if (resourcelocation2 != null) { + return resourcelocation2; + } else { + resourcelocation1 = new ResourceLocation(s1); + resourcelocation2 = new ResourceLocation(s2); + if (resourceExists(resourcelocation1)) { + ARMOR_TEXTURE_RES_MAP.put(s1, resourcelocation1); + return resourcelocation1; + } else if (resourceExists(resourcelocation2)) { + ARMOR_TEXTURE_RES_MAP.put(s2, resourcelocation2); + return resourcelocation2; + } else { + ARMOR_TEXTURE_RES_MAP.put(s1, resourcelocation1); + return resourcelocation1; + } + } + } + + public ItemStack getCurrentArmor(EntityLivingBase entitylivingbaseIn, int armorSlot) { + return entitylivingbaseIn.getCurrentArmor(armorSlot - 1); + } + + protected abstract void initArmor(); + + private boolean isSlotForLeggings(int armorSlot) { + return armorSlot == 2; } private void renderLayer(EntityLivingBase entitylivingbaseIn, float armorSlot, float parFloat2, float parFloat3, @@ -100,6 +195,10 @@ public abstract class LayerArmorBase implements LayerRender DeferredStateManager.setRoughnessConstant(0.078f); DeferredStateManager.setMetalnessConstant(0.588f); break; + case PLATINUM: + DeferredStateManager.setRoughnessConstant(0.129f); + DeferredStateManager.setMetalnessConstant(0.913f); + break; default: break; } @@ -116,6 +215,7 @@ public abstract class LayerArmorBase implements LayerRender case IRON: case GOLD: case DIAMOND: + case PLATINUM: GlStateManager.color(this.colorR, this.colorG, this.colorB, this.alpha); modelbase.render(entitylivingbaseIn, armorSlot, parFloat2, parFloat4, parFloat5, parFloat6, parFloat7); DeferredStateManager.setDefaultMaterialConstants(); @@ -167,75 +267,16 @@ public abstract class LayerArmorBase implements LayerRender } } - public ItemStack getCurrentArmor(EntityLivingBase entitylivingbaseIn, int armorSlot) { - return entitylivingbaseIn.getCurrentArmor(armorSlot - 1); - } - - public T func_177175_a(int parInt1) { - return (T) (this.isSlotForLeggings(parInt1) ? this.field_177189_c : this.field_177186_d); - } - - private boolean isSlotForLeggings(int armorSlot) { - return armorSlot == 2; - } - - private void func_177183_a(EntityLivingBase entitylivingbaseIn, T modelbaseIn, float parFloat1, float parFloat2, - float parFloat3, float parFloat4, float parFloat5, float parFloat6, float parFloat7) { - float f = (float) entitylivingbaseIn.ticksExisted + parFloat3; - this.renderer.bindTexture(ENCHANTED_ITEM_GLINT_RES); - GlStateManager.enableBlend(); - GlStateManager.depthFunc(GL_EQUAL); - GlStateManager.depthMask(false); - float f1 = 0.5F; - boolean d = !DeferredStateManager.isInDeferredPass(); - if (d) { - GlStateManager.color(f1, f1, f1, 1.0F); + private boolean resourceExists(ResourceLocation resourcelocation) { + try { + Minecraft.getMinecraft().getResourceManager().getResource(resourcelocation); + return true; + } catch (IOException e) { + return false; } - - for (int i = 0; i < 2; ++i) { - GlStateManager.disableLighting(); - float f2 = 0.76F; - if (d) { - GlStateManager.blendFunc(GL_SRC_COLOR, GL_ONE); - GlStateManager.color(0.5F * f2, 0.25F * f2, 0.8F * f2, 1.0F); - } - GlStateManager.matrixMode(GL_TEXTURE); - GlStateManager.loadIdentity(); - float f3 = 0.33333334F; - GlStateManager.scale(f3, f3, f3); - GlStateManager.rotate(30.0F - (float) i * 60.0F, 0.0F, 0.0F, 1.0F); - GlStateManager.translate(0.0F, f * (0.001F + (float) i * 0.003F) * 20.0F, 0.0F); - GlStateManager.matrixMode(GL_MODELVIEW); - modelbaseIn.render(entitylivingbaseIn, parFloat1, parFloat2, parFloat4, parFloat5, parFloat6, parFloat7); - } - - GlStateManager.matrixMode(GL_TEXTURE); - GlStateManager.loadIdentity(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.enableLighting(); - GlStateManager.depthMask(true); - GlStateManager.depthFunc(GL_LEQUAL); - GlStateManager.disableBlend(); } - private ResourceLocation getArmorResource(ItemArmor parItemArmor, boolean parFlag) { - return this.getArmorResource(parItemArmor, parFlag, (String) null); + public boolean shouldCombineTextures() { + return false; } - - private ResourceLocation getArmorResource(ItemArmor parItemArmor, boolean parFlag, String parString1) { - String s = HString.format("textures/models/armor/%s_layer_%d%s.png", - new Object[] { parItemArmor.getArmorMaterial().getName(), Integer.valueOf(parFlag ? 2 : 1), - parString1 == null ? "" : HString.format("_%s", new Object[] { parString1 }) }); - ResourceLocation resourcelocation = (ResourceLocation) ARMOR_TEXTURE_RES_MAP.get(s); - if (resourcelocation == null) { - resourcelocation = new ResourceLocation(s); - ARMOR_TEXTURE_RES_MAP.put(s, resourcelocation); - } - - return resourcelocation; - } - - protected abstract void initArmor(); - - protected abstract void func_177179_a(T var1, int var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArrow.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArrow.java index 426664fa..81889bee 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArrow.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerArrow.java @@ -1,7 +1,6 @@ package net.minecraft.client.renderer.entity.layers; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.model.ModelBox; import net.minecraft.client.model.ModelRenderer; @@ -10,22 +9,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerBipedArmor.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerBipedArmor.java index 16eed850..f10ebcd0 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerBipedArmor.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerBipedArmor.java @@ -3,22 +3,25 @@ package net.minecraft.client.renderer.entity.layers; import net.minecraft.client.model.ModelBiped; import net.minecraft.client.renderer.entity.RendererLivingEntity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,6 @@ public class LayerBipedArmor extends LayerArmorBase { super(rendererIn); } - protected void initArmor() { - this.field_177189_c = new ModelBiped(0.5F); - this.field_177186_d = new ModelBiped(1.0F); - } - protected void func_177179_a(ModelBiped modelbiped, int i) { this.func_177194_a(modelbiped); switch (i) { @@ -60,4 +58,9 @@ public class LayerBipedArmor extends LayerArmorBase { protected void func_177194_a(ModelBiped parModelBiped) { parModelBiped.setInvisible(false); } + + protected void initArmor() { + this.field_177189_c = new ModelBiped(0.5F); + this.field_177186_d = new ModelBiped(1.0F); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCape.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCape.java index 6b01a8a1..0d6ff4cc 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCape.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCape.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.entity.RenderPlayer; import net.minecraft.entity.player.EnumPlayerModelParts; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCreeperCharge.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCreeperCharge.java index e341bcf8..dc6bb95f 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCreeperCharge.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCreeperCharge.java @@ -1,6 +1,9 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -12,22 +15,25 @@ import net.minecraft.client.renderer.entity.RenderCreeper; import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCustomHead.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCustomHead.java index 10aab24c..a5483329 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCustomHead.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerCustomHead.java @@ -1,7 +1,6 @@ package net.minecraft.client.renderer.entity.layers; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.minecraft.client.Minecraft; @@ -21,22 +20,25 @@ import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.EnumFacing; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerDeadmau5Head.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerDeadmau5Head.java index 4b00c832..3e35bfe9 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerDeadmau5Head.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerDeadmau5Head.java @@ -5,22 +5,25 @@ import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.model.ModelPlayer; import net.minecraft.client.renderer.entity.RenderPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonDeath.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonDeath.java index a5cb40ad..a084a007 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonDeath.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonDeath.java @@ -1,9 +1,12 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -16,22 +19,25 @@ import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.boss.EntityDragon; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonEyes.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonEyes.java index 3d2f6127..66986443 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonEyes.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEnderDragonEyes.java @@ -1,6 +1,8 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.OpenGlHelper; @@ -9,22 +11,25 @@ import net.minecraft.client.renderer.entity.RenderDragon; import net.minecraft.entity.boss.EntityDragon; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEndermanEyes.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEndermanEyes.java index 72dd974d..fa5f5761 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEndermanEyes.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerEndermanEyes.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.OpenGlHelper; @@ -13,22 +14,25 @@ import net.minecraft.client.renderer.entity.RenderEnderman; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldBlock.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldBlock.java index b15739f1..cf7b858d 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldBlock.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldBlock.java @@ -15,22 +15,25 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.util.EnumWorldBlockLayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItem.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItem.java index 02a99ca8..1ef0d849 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItem.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItem.java @@ -13,22 +13,25 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItemWitch.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItemWitch.java index f74b6bbb..8bf24652 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItemWitch.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerHeldItemWitch.java @@ -12,22 +12,25 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerIronGolemFlower.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerIronGolemFlower.java index 07346bef..538f7e9c 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerIronGolemFlower.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerIronGolemFlower.java @@ -10,22 +10,25 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerMooshroomMushroom.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerMooshroomMushroom.java index 0ceaa762..64e21bed 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerMooshroomMushroom.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerMooshroomMushroom.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BACK; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRONT; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -12,22 +13,25 @@ import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.passive.EntityMooshroom; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerNetherCreeperCharge.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerNetherCreeperCharge.java new file mode 100644 index 00000000..4a3e7c5d --- /dev/null +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerNetherCreeperCharge.java @@ -0,0 +1,136 @@ +package net.minecraft.client.renderer.entity.layers; + +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; + +import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ShadersRenderPassFuture; +import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; +import net.minecraft.client.model.ModelNetherCreeper; +import net.minecraft.client.renderer.EntityRenderer; +import net.minecraft.client.renderer.entity.RenderNetherCreeper; +import net.minecraft.entity.monster.EntityNetherCreeper; +import net.minecraft.util.ResourceLocation; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class LayerNetherCreeperCharge implements LayerRenderer { + private static final ResourceLocation LIGHTNING_TEXTURE = new ResourceLocation( + "textures/entity/nethercreeper/creeper_armor.png"); + private final RenderNetherCreeper creeperRenderer; + private final ModelNetherCreeper creeperModel = new ModelNetherCreeper(2.0F); + + public LayerNetherCreeperCharge(RenderNetherCreeper renderNetherCreeper) { + this.creeperRenderer = renderNetherCreeper; + } + + public void doRenderLayer(EntityNetherCreeper entitycreeper, float f, float f1, float f2, float f3, float f4, + float f5, float f6) { + if (entitycreeper.getPowered()) { + if (DeferredStateManager.isInDeferredPass()) { + if (DeferredStateManager.forwardCallbackHandler != null + && !DeferredStateManager.isEnableShadowRender()) { + final Matrix4f mat = new Matrix4f(GlStateManager.getModelViewReference()); + DeferredStateManager.forwardCallbackHandler.push(new ShadersRenderPassFuture(entitycreeper) { + @Override + public void draw(PassType pass) { + if (pass == PassType.MAIN) { + DeferredStateManager.reportForwardRenderObjectPosition2(x, y, z); + } + boolean flag = entitycreeper.isInvisible(); + DeferredStateManager.setDefaultMaterialConstants(); + DeferredStateManager.setRoughnessConstant(0.3f); + DeferredStateManager.setMetalnessConstant(0.1f); + DeferredStateManager.setEmissionConstant(0.9f); + EntityRenderer.disableLightmapStatic(); + GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE, GL_ZERO, GL_ZERO); + GlStateManager.color(0.5F, 0.5F, 0.5F, 1.0F); + if (flag) { + GlStateManager.depthMask(false); + } + GlStateManager.pushMatrix(); + GlStateManager.loadMatrix(mat); + GlStateManager.disableCull(); + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); + float f7 = (float) entitycreeper.ticksExisted + f2; + GlStateManager.translate(f7 * 0.01F, f7 * 0.01F, 0.0F); + GlStateManager.matrixMode(GL_MODELVIEW); + LayerNetherCreeperCharge.this.creeperRenderer.bindTexture(LIGHTNING_TEXTURE); + LayerNetherCreeperCharge.this.creeperModel + .setModelAttributes(LayerNetherCreeperCharge.this.creeperRenderer.getMainModel()); + LayerNetherCreeperCharge.this.creeperModel.setLivingAnimations(entitycreeper, f, f1, f1); + LayerNetherCreeperCharge.this.creeperModel.render(entitycreeper, f, f1, f3, f4, f5, f6); + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.popMatrix(); + if (flag) { + GlStateManager.depthMask(true); + } + GlStateManager.enableCull(); + DeferredStateManager.setDefaultMaterialConstants(); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); + } + }); + } + return; + } + boolean flag = entitycreeper.isInvisible(); + if (flag) { + GlStateManager.depthMask(false); + } + this.creeperRenderer.bindTexture(LIGHTNING_TEXTURE); + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.loadIdentity(); + float f7 = (float) entitycreeper.ticksExisted + f2; + GlStateManager.translate(f7 * 0.01F, f7 * 0.01F, 0.0F); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.enableBlend(); + float f8 = 0.5F; + GlStateManager.color(f8, f8, f8, 1.0F); + GlStateManager.disableLighting(); + GlStateManager.blendFunc(GL_ONE, GL_ONE); + this.creeperModel.setModelAttributes(this.creeperRenderer.getMainModel()); + this.creeperModel.render(entitycreeper, f, f1, f3, f4, f5, f6); + GlStateManager.matrixMode(GL_TEXTURE); + GlStateManager.loadIdentity(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.enableLighting(); + GlStateManager.disableBlend(); + if (flag) { + GlStateManager.depthMask(true); + } + } + } + + public boolean shouldCombineTextures() { + return false; + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerRenderer.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerRenderer.java index 9e8d936e..632cfa42 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerRenderer.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer.entity.layers; import net.minecraft.entity.EntityLivingBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSaddle.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSaddle.java index b3cb8f49..e3907137 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSaddle.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSaddle.java @@ -5,22 +5,25 @@ import net.minecraft.client.renderer.entity.RenderPig; import net.minecraft.entity.passive.EntityPig; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSheepWool.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSheepWool.java index ed00ac35..2d6ead8e 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSheepWool.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSheepWool.java @@ -7,22 +7,25 @@ import net.minecraft.entity.passive.EntitySheep; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSlimeGel.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSlimeGel.java index 54594e2a..d53634c6 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSlimeGel.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSlimeGel.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -13,22 +14,25 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.entity.RenderSlime; import net.minecraft.entity.monster.EntitySlime; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSnowmanHead.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSnowmanHead.java index 2b0cfb54..0fe742d6 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSnowmanHead.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSnowmanHead.java @@ -8,22 +8,25 @@ import net.minecraft.entity.monster.EntitySnowman; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSpiderEyes.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSpiderEyes.java index b23af182..50f2b941 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSpiderEyes.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerSpiderEyes.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.OpenGlHelper; @@ -13,22 +14,25 @@ import net.minecraft.client.renderer.entity.RenderSpider; import net.minecraft.entity.monster.EntitySpider; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerVillagerArmor.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerVillagerArmor.java index e15cb280..85bfe0a5 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerVillagerArmor.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerVillagerArmor.java @@ -3,22 +3,25 @@ package net.minecraft.client.renderer.entity.layers; import net.minecraft.client.model.ModelZombieVillager; import net.minecraft.client.renderer.entity.RendererLivingEntity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWitherAura.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWitherAura.java index 528a848f..41ecb91f 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWitherAura.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWitherAura.java @@ -1,6 +1,9 @@ package net.minecraft.client.renderer.entity.layers; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -13,22 +16,25 @@ import net.minecraft.entity.boss.EntityWither; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWolfCollar.java b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWolfCollar.java index be295f5e..14db51db 100644 --- a/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWolfCollar.java +++ b/src/game/java/net/minecraft/client/renderer/entity/layers/LayerWolfCollar.java @@ -7,22 +7,25 @@ import net.minecraft.entity.passive.EntityWolf; import net.minecraft.item.EnumDyeColor; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/AbstractTexture.java b/src/game/java/net/minecraft/client/renderer/texture/AbstractTexture.java index d2fe87b1..19eaca14 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/AbstractTexture.java +++ b/src/game/java/net/minecraft/client/renderer/texture/AbstractTexture.java @@ -1,25 +1,30 @@ package net.minecraft.client.renderer.texture; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,6 +37,49 @@ public abstract class AbstractTexture implements ITextureObject { protected boolean mipmapLast; protected boolean hasAllocated; + public void deleteGlTexture() { + if (this.glTextureId != -1) { + TextureUtil.deleteTexture(this.glTextureId); + this.glTextureId = -1; + } + + } + + public int getGlTextureId() { + if (this.glTextureId == -1) { + this.glTextureId = TextureUtil.glGenTextures(); + hasAllocated = false; + } + + return this.glTextureId; + } + + /** + * This function is needed due to EaglercraftX's use of glTexStorage2D to + * allocate memory for textures, some OpenGL implementations don't like it when + * you call glTexStorage2D on the same texture object more than once + */ + protected void regenerateIfNotAllocated() { + if (this.glTextureId != -1) { + if (hasAllocated) { + if (EaglercraftGPU.checkTexStorageCapable()) { + EaglercraftGPU.regenerateTexture(glTextureId); + } + } + hasAllocated = true; + } + } + + public void restoreLastBlurMipmap() { + this.setBlurMipmapDirect(this.blurLast, this.mipmapLast); + } + + public void setBlurMipmap(boolean parFlag, boolean parFlag2) { + this.blurLast = this.blur; + this.mipmapLast = this.mipmap; + this.setBlurMipmapDirect(parFlag, parFlag2); + } + public void setBlurMipmapDirect(boolean parFlag, boolean parFlag2) { if (blur != parFlag || mipmap != parFlag2) { this.blur = parFlag; @@ -54,47 +102,4 @@ public abstract class AbstractTexture implements ITextureObject { EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, i); EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, short1); } - - public void setBlurMipmap(boolean parFlag, boolean parFlag2) { - this.blurLast = this.blur; - this.mipmapLast = this.mipmap; - this.setBlurMipmapDirect(parFlag, parFlag2); - } - - public void restoreLastBlurMipmap() { - this.setBlurMipmapDirect(this.blurLast, this.mipmapLast); - } - - public int getGlTextureId() { - if (this.glTextureId == -1) { - this.glTextureId = TextureUtil.glGenTextures(); - hasAllocated = false; - } - - return this.glTextureId; - } - - public void deleteGlTexture() { - if (this.glTextureId != -1) { - TextureUtil.deleteTexture(this.glTextureId); - this.glTextureId = -1; - } - - } - - /** - * This function is needed due to EaglercraftX's use of glTexStorage2D to - * allocate memory for textures, some OpenGL implementations don't like it when - * you call glTexStorage2D on the same texture object more than once - */ - protected void regenerateIfNotAllocated() { - if (this.glTextureId != -1) { - if (hasAllocated) { - if (EaglercraftGPU.checkTexStorageCapable()) { - EaglercraftGPU.regenerateTexture(glTextureId); - } - } - hasAllocated = true; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/texture/DynamicTexture.java b/src/game/java/net/minecraft/client/renderer/texture/DynamicTexture.java index dd739585..e2b63e89 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/DynamicTexture.java +++ b/src/game/java/net/minecraft/client/renderer/texture/DynamicTexture.java @@ -5,22 +5,25 @@ import java.io.IOException; import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; import net.minecraft.client.resources.IResourceManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,14 +47,14 @@ public class DynamicTexture extends AbstractTexture { TextureUtil.allocateTexture(this.getGlTextureId(), textureWidth, textureHeight); } + public int[] getTextureData() { + return this.dynamicTextureData; + } + public void loadTexture(IResourceManager resourceManager) throws IOException { } public void updateDynamicTexture() { TextureUtil.uploadTexture(this.getGlTextureId(), this.dynamicTextureData, this.width, this.height); } - - public int[] getTextureData() { - return this.dynamicTextureData; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/texture/IIconCreator.java b/src/game/java/net/minecraft/client/renderer/texture/IIconCreator.java index 1fb7b6cc..16ac1fc1 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/IIconCreator.java +++ b/src/game/java/net/minecraft/client/renderer/texture/IIconCreator.java @@ -1,21 +1,24 @@ package net.minecraft.client.renderer.texture; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/ITextureObject.java b/src/game/java/net/minecraft/client/renderer/texture/ITextureObject.java index 9856cb99..89d0a4c9 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/ITextureObject.java +++ b/src/game/java/net/minecraft/client/renderer/texture/ITextureObject.java @@ -4,32 +4,35 @@ import java.io.IOException; import net.minecraft.client.resources.IResourceManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ITextureObject { - void setBlurMipmap(boolean var1, boolean var2); - - void restoreLastBlurMipmap(); + int getGlTextureId(); void loadTexture(IResourceManager var1) throws IOException; - int getGlTextureId(); + void restoreLastBlurMipmap(); + + void setBlurMipmap(boolean var1, boolean var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/texture/ITickable.java b/src/game/java/net/minecraft/client/renderer/texture/ITickable.java index 11238878..581dcbcb 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/ITickable.java +++ b/src/game/java/net/minecraft/client/renderer/texture/ITickable.java @@ -1,21 +1,24 @@ package net.minecraft.client.renderer.texture; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/ITickableTextureObject.java b/src/game/java/net/minecraft/client/renderer/texture/ITickableTextureObject.java index 4787346b..1503d289 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/ITickableTextureObject.java +++ b/src/game/java/net/minecraft/client/renderer/texture/ITickableTextureObject.java @@ -1,21 +1,24 @@ package net.minecraft.client.renderer.texture; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/LayeredColorMaskTexture.java b/src/game/java/net/minecraft/client/renderer/texture/LayeredColorMaskTexture.java index 1dfbad1c..831bd5b1 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/LayeredColorMaskTexture.java +++ b/src/game/java/net/minecraft/client/renderer/texture/LayeredColorMaskTexture.java @@ -13,29 +13,32 @@ import net.minecraft.item.EnumDyeColor; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LayeredColorMaskTexture extends AbstractTexture { - /**+ - * Access to the Logger, for all your logging needs. + /** + * + Access to the Logger, for all your logging needs. */ private static final Logger LOG = LogManager.getLogger(); private final ResourceLocation textureLocation; diff --git a/src/game/java/net/minecraft/client/renderer/texture/LayeredTexture.java b/src/game/java/net/minecraft/client/renderer/texture/LayeredTexture.java index f6fd6ce4..3ebfa0f5 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/LayeredTexture.java +++ b/src/game/java/net/minecraft/client/renderer/texture/LayeredTexture.java @@ -12,22 +12,25 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/SimpleTexture.java b/src/game/java/net/minecraft/client/renderer/texture/SimpleTexture.java index ca18cf5d..a81e9dfa 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/SimpleTexture.java +++ b/src/game/java/net/minecraft/client/renderer/texture/SimpleTexture.java @@ -11,22 +11,25 @@ import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.data.TextureMetadataSection; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/Stitcher.java b/src/game/java/net/minecraft/client/renderer/texture/Stitcher.java index a2e20a93..3df2442f 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/Stitcher.java +++ b/src/game/java/net/minecraft/client/renderer/texture/Stitcher.java @@ -5,203 +5,38 @@ import java.util.Arrays; import java.util.List; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.HString; -import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; - import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; import net.minecraft.client.renderer.StitcherException; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Stitcher { - private final int mipmapLevelStitcher; - private final Set setStitchHolders = Sets.newHashSetWithExpectedSize(256); - private final List stitchSlots = Lists.newArrayListWithCapacity(256); - private int currentWidth; - private int currentHeight; - private final int maxWidth; - private final int maxHeight; - private final boolean forcePowerOf2; - private final int maxTileDimension; - - public Stitcher(int maxTextureWidth, int maxTextureHeight, boolean parFlag, int parInt1, int mipmapLevel) { - this.mipmapLevelStitcher = mipmapLevel; - this.maxWidth = maxTextureWidth; - this.maxHeight = maxTextureHeight; - this.forcePowerOf2 = parFlag; - this.maxTileDimension = parInt1; - } - - public int getCurrentWidth() { - return this.currentWidth; - } - - public int getCurrentHeight() { - return this.currentHeight; - } - - public void addSprite(EaglerTextureAtlasSprite parTextureAtlasSprite) { - Stitcher.Holder stitcher$holder = new Stitcher.Holder(parTextureAtlasSprite, this.mipmapLevelStitcher); - if (this.maxTileDimension > 0) { - stitcher$holder.setNewDimension(this.maxTileDimension); - } - - this.setStitchHolders.add(stitcher$holder); - } - - public void doStitch() { - Stitcher.Holder[] astitcher$holder = (Stitcher.Holder[]) this.setStitchHolders - .toArray(new Stitcher.Holder[this.setStitchHolders.size()]); - Arrays.sort(astitcher$holder); - - for (int i = 0; i < astitcher$holder.length; ++i) { - Stitcher.Holder stitcher$holder = astitcher$holder[i]; - if (!this.allocateSlot(stitcher$holder)) { - String s = HString.format("Unable to fit: %s - size: %dx%d - Maybe try a lowerresolution resourcepack?", - new Object[] { stitcher$holder.getAtlasSprite().getIconName(), - Integer.valueOf(stitcher$holder.getAtlasSprite().getIconWidth()), - Integer.valueOf(stitcher$holder.getAtlasSprite().getIconHeight()) }); - throw new StitcherException(stitcher$holder, s); - } - } - - if (this.forcePowerOf2) { - this.currentWidth = MathHelper.roundUpToPowerOfTwo(this.currentWidth); - this.currentHeight = MathHelper.roundUpToPowerOfTwo(this.currentHeight); - } - - } - - public List getStichSlots() { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = this.stitchSlots.size(); i < l; ++i) { - this.stitchSlots.get(i).getAllStitchSlots(arraylist); - } - - ArrayList arraylist1 = Lists.newArrayList(); - - for (int i = 0, l = arraylist.size(); i < l; ++i) { - Stitcher.Slot stitcher$slot1 = arraylist.get(i); - Stitcher.Holder stitcher$holder = stitcher$slot1.getStitchHolder(); - EaglerTextureAtlasSprite textureatlassprite = stitcher$holder.getAtlasSprite(); - textureatlassprite.initSprite(this.currentWidth, this.currentHeight, stitcher$slot1.getOriginX(), - stitcher$slot1.getOriginY(), stitcher$holder.isRotated()); - arraylist1.add(textureatlassprite); - } - - return arraylist1; - } - - private static int getMipmapDimension(int parInt1, int parInt2) { - return (parInt1 >> parInt2) + ((parInt1 & (1 << parInt2) - 1) == 0 ? 0 : 1) << parInt2; - } - - /**+ - * Attempts to find space for specified tile - */ - private boolean allocateSlot(Stitcher.Holder parHolder) { - for (int i = 0; i < this.stitchSlots.size(); ++i) { - if (((Stitcher.Slot) this.stitchSlots.get(i)).addSlot(parHolder)) { - return true; - } - - parHolder.rotate(); - if (((Stitcher.Slot) this.stitchSlots.get(i)).addSlot(parHolder)) { - return true; - } - - parHolder.rotate(); - } - - return this.expandAndAllocateSlot(parHolder); - } - - /**+ - * Expand stitched texture in order to make space for specified - * tile - */ - private boolean expandAndAllocateSlot(Stitcher.Holder parHolder) { - int i = Math.min(parHolder.getWidth(), parHolder.getHeight()); - boolean flag = this.currentWidth == 0 && this.currentHeight == 0; - boolean flag1; - if (this.forcePowerOf2) { - int j = MathHelper.roundUpToPowerOfTwo(this.currentWidth); - int k = MathHelper.roundUpToPowerOfTwo(this.currentHeight); - int l = MathHelper.roundUpToPowerOfTwo(this.currentWidth + i); - int i1 = MathHelper.roundUpToPowerOfTwo(this.currentHeight + i); - boolean flag2 = l <= this.maxWidth; - boolean flag3 = i1 <= this.maxHeight; - if (!flag2 && !flag3) { - return false; - } - - boolean flag4 = j != l; - boolean flag5 = k != i1; - if (flag4 ^ flag5) { - flag1 = !flag4; - } else { - flag1 = flag2 && j <= k; - } - } else { - boolean flag6 = this.currentWidth + i <= this.maxWidth; - boolean flag7 = this.currentHeight + i <= this.maxHeight; - if (!flag6 && !flag7) { - return false; - } - - flag1 = flag6 && (flag || this.currentWidth <= this.currentHeight); - } - - int j1 = Math.max(parHolder.getWidth(), parHolder.getHeight()); - if (MathHelper.roundUpToPowerOfTwo( - (flag1 ? this.currentHeight : this.currentWidth) + j1) > (flag1 ? this.maxHeight : this.maxWidth)) { - return false; - } else { - Stitcher.Slot stitcher$slot; - if (flag1) { - if (parHolder.getWidth() > parHolder.getHeight()) { - parHolder.rotate(); - } - - if (this.currentHeight == 0) { - this.currentHeight = parHolder.getHeight(); - } - - stitcher$slot = new Stitcher.Slot(this.currentWidth, 0, parHolder.getWidth(), this.currentHeight); - this.currentWidth += parHolder.getWidth(); - } else { - stitcher$slot = new Stitcher.Slot(0, this.currentHeight, this.currentWidth, parHolder.getHeight()); - this.currentHeight += parHolder.getHeight(); - } - - stitcher$slot.addSlot(parHolder); - this.stitchSlots.add(stitcher$slot); - return true; - } - } - public static class Holder implements Comparable { private final EaglerTextureAtlasSprite theTexture; private final int width; @@ -219,43 +54,6 @@ public class Stitcher { parInt1); } - public EaglerTextureAtlasSprite getAtlasSprite() { - return this.theTexture; - } - - public int getWidth() { - return this.rotated - ? Stitcher.getMipmapDimension((int) ((float) this.height * this.scaleFactor), - this.mipmapLevelHolder) - : Stitcher.getMipmapDimension((int) ((float) this.width * this.scaleFactor), - this.mipmapLevelHolder); - } - - public int getHeight() { - return this.rotated - ? Stitcher.getMipmapDimension((int) ((float) this.width * this.scaleFactor), this.mipmapLevelHolder) - : Stitcher.getMipmapDimension((int) ((float) this.height * this.scaleFactor), - this.mipmapLevelHolder); - } - - public void rotate() { - this.rotated = !this.rotated; - } - - public boolean isRotated() { - return this.rotated; - } - - public void setNewDimension(int parInt1) { - if (this.width > parInt1 && this.height > parInt1) { - this.scaleFactor = (float) parInt1 / (float) Math.min(this.width, this.height); - } - } - - public String toString() { - return "Holder{width=" + this.width + ", height=" + this.height + '}'; - } - public int compareTo(Stitcher.Holder stitcher$holder) { int i; if (this.getHeight() == stitcher$holder.getHeight()) { @@ -274,6 +72,43 @@ public class Stitcher { return i; } + + public EaglerTextureAtlasSprite getAtlasSprite() { + return this.theTexture; + } + + public int getHeight() { + return this.rotated + ? Stitcher.getMipmapDimension((int) ((float) this.width * this.scaleFactor), this.mipmapLevelHolder) + : Stitcher.getMipmapDimension((int) ((float) this.height * this.scaleFactor), + this.mipmapLevelHolder); + } + + public int getWidth() { + return this.rotated + ? Stitcher.getMipmapDimension((int) ((float) this.height * this.scaleFactor), + this.mipmapLevelHolder) + : Stitcher.getMipmapDimension((int) ((float) this.width * this.scaleFactor), + this.mipmapLevelHolder); + } + + public boolean isRotated() { + return this.rotated; + } + + public void rotate() { + this.rotated = !this.rotated; + } + + public void setNewDimension(int parInt1) { + if (this.width > parInt1 && this.height > parInt1) { + this.scaleFactor = (float) parInt1 / (float) Math.min(this.width, this.height); + } + } + + public String toString() { + return "Holder{width=" + this.width + ", height=" + this.height + '}'; + } } public static class Slot { @@ -291,18 +126,6 @@ public class Stitcher { this.height = heightIn; } - public Stitcher.Holder getStitchHolder() { - return this.holder; - } - - public int getOriginX() { - return this.originX; - } - - public int getOriginY() { - return this.originY; - } - public boolean addSlot(Stitcher.Holder holderIn) { if (this.holder != null) { return false; @@ -362,9 +185,190 @@ public class Stitcher { } + public int getOriginX() { + return this.originX; + } + + public int getOriginY() { + return this.originY; + } + + public Stitcher.Holder getStitchHolder() { + return this.holder; + } + public String toString() { return "Slot{originX=" + this.originX + ", originY=" + this.originY + ", width=" + this.width + ", height=" + this.height + ", texture=" + this.holder + ", subSlots=" + this.subSlots + '}'; } } + + private static int getMipmapDimension(int parInt1, int parInt2) { + return (parInt1 >> parInt2) + ((parInt1 & (1 << parInt2) - 1) == 0 ? 0 : 1) << parInt2; + } + + private final int mipmapLevelStitcher; + private final Set setStitchHolders = Sets.newHashSetWithExpectedSize(256); + private final List stitchSlots = Lists.newArrayListWithCapacity(256); + private int currentWidth; + private int currentHeight; + private final int maxWidth; + + private final int maxHeight; + + private final boolean forcePowerOf2; + + private final int maxTileDimension; + + public Stitcher(int maxTextureWidth, int maxTextureHeight, boolean parFlag, int parInt1, int mipmapLevel) { + this.mipmapLevelStitcher = mipmapLevel; + this.maxWidth = maxTextureWidth; + this.maxHeight = maxTextureHeight; + this.forcePowerOf2 = parFlag; + this.maxTileDimension = parInt1; + } + + public void addSprite(EaglerTextureAtlasSprite parTextureAtlasSprite) { + Stitcher.Holder stitcher$holder = new Stitcher.Holder(parTextureAtlasSprite, this.mipmapLevelStitcher); + if (this.maxTileDimension > 0) { + stitcher$holder.setNewDimension(this.maxTileDimension); + } + + this.setStitchHolders.add(stitcher$holder); + } + + /** + * + Attempts to find space for specified tile + */ + private boolean allocateSlot(Stitcher.Holder parHolder) { + for (int i = 0; i < this.stitchSlots.size(); ++i) { + if (((Stitcher.Slot) this.stitchSlots.get(i)).addSlot(parHolder)) { + return true; + } + + parHolder.rotate(); + if (((Stitcher.Slot) this.stitchSlots.get(i)).addSlot(parHolder)) { + return true; + } + + parHolder.rotate(); + } + + return this.expandAndAllocateSlot(parHolder); + } + + public void doStitch() { + Stitcher.Holder[] astitcher$holder = (Stitcher.Holder[]) this.setStitchHolders + .toArray(new Stitcher.Holder[this.setStitchHolders.size()]); + Arrays.sort(astitcher$holder); + + for (int i = 0; i < astitcher$holder.length; ++i) { + Stitcher.Holder stitcher$holder = astitcher$holder[i]; + if (!this.allocateSlot(stitcher$holder)) { + String s = HString.format("Unable to fit: %s - size: %dx%d - Maybe try a lowerresolution resourcepack?", + new Object[] { stitcher$holder.getAtlasSprite().getIconName(), + Integer.valueOf(stitcher$holder.getAtlasSprite().getIconWidth()), + Integer.valueOf(stitcher$holder.getAtlasSprite().getIconHeight()) }); + throw new StitcherException(stitcher$holder, s); + } + } + + if (this.forcePowerOf2) { + this.currentWidth = MathHelper.roundUpToPowerOfTwo(this.currentWidth); + this.currentHeight = MathHelper.roundUpToPowerOfTwo(this.currentHeight); + } + + } + + /** + * + Expand stitched texture in order to make space for specified tile + */ + private boolean expandAndAllocateSlot(Stitcher.Holder parHolder) { + int i = Math.min(parHolder.getWidth(), parHolder.getHeight()); + boolean flag = this.currentWidth == 0 && this.currentHeight == 0; + boolean flag1; + if (this.forcePowerOf2) { + int j = MathHelper.roundUpToPowerOfTwo(this.currentWidth); + int k = MathHelper.roundUpToPowerOfTwo(this.currentHeight); + int l = MathHelper.roundUpToPowerOfTwo(this.currentWidth + i); + int i1 = MathHelper.roundUpToPowerOfTwo(this.currentHeight + i); + boolean flag2 = l <= this.maxWidth; + boolean flag3 = i1 <= this.maxHeight; + if (!flag2 && !flag3) { + return false; + } + + boolean flag4 = j != l; + boolean flag5 = k != i1; + if (flag4 ^ flag5) { + flag1 = !flag4; + } else { + flag1 = flag2 && j <= k; + } + } else { + boolean flag6 = this.currentWidth + i <= this.maxWidth; + boolean flag7 = this.currentHeight + i <= this.maxHeight; + if (!flag6 && !flag7) { + return false; + } + + flag1 = flag6 && (flag || this.currentWidth <= this.currentHeight); + } + + int j1 = Math.max(parHolder.getWidth(), parHolder.getHeight()); + if (MathHelper.roundUpToPowerOfTwo( + (flag1 ? this.currentHeight : this.currentWidth) + j1) > (flag1 ? this.maxHeight : this.maxWidth)) { + return false; + } else { + Stitcher.Slot stitcher$slot; + if (flag1) { + if (parHolder.getWidth() > parHolder.getHeight()) { + parHolder.rotate(); + } + + if (this.currentHeight == 0) { + this.currentHeight = parHolder.getHeight(); + } + + stitcher$slot = new Stitcher.Slot(this.currentWidth, 0, parHolder.getWidth(), this.currentHeight); + this.currentWidth += parHolder.getWidth(); + } else { + stitcher$slot = new Stitcher.Slot(0, this.currentHeight, this.currentWidth, parHolder.getHeight()); + this.currentHeight += parHolder.getHeight(); + } + + stitcher$slot.addSlot(parHolder); + this.stitchSlots.add(stitcher$slot); + return true; + } + } + + public int getCurrentHeight() { + return this.currentHeight; + } + + public int getCurrentWidth() { + return this.currentWidth; + } + + public List getStichSlots() { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = this.stitchSlots.size(); i < l; ++i) { + this.stitchSlots.get(i).getAllStitchSlots(arraylist); + } + + ArrayList arraylist1 = Lists.newArrayList(); + + for (int i = 0, l = arraylist.size(); i < l; ++i) { + Stitcher.Slot stitcher$slot1 = arraylist.get(i); + Stitcher.Holder stitcher$holder = stitcher$slot1.getStitchHolder(); + EaglerTextureAtlasSprite textureatlassprite = stitcher$holder.getAtlasSprite(); + textureatlassprite.initSprite(this.currentWidth, this.currentHeight, stitcher$slot1.getOriginX(), + stitcher$slot1.getOriginY(), stitcher$holder.isRotated()); + arraylist1.add(textureatlassprite); + } + + return arraylist1; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/texture/TextureClock.java b/src/game/java/net/minecraft/client/renderer/texture/TextureClock.java index 544db687..ee294ff7 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/TextureClock.java +++ b/src/game/java/net/minecraft/client/renderer/texture/TextureClock.java @@ -5,22 +5,25 @@ import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerTextureAtlasSprite; import net.minecraft.client.Minecraft; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/renderer/texture/TextureCompass.java b/src/game/java/net/minecraft/client/renderer/texture/TextureCompass.java index d39d5e7d..cb10b7f2 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/TextureCompass.java +++ b/src/game/java/net/minecraft/client/renderer/texture/TextureCompass.java @@ -7,30 +7,33 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TextureCompass extends EaglerTextureAtlasSprite { + public static String field_176608_l; public double currentAngle; public double angleDelta; - public static String field_176608_l; public TextureCompass(String iconName) { super(iconName); @@ -48,9 +51,8 @@ public class TextureCompass extends EaglerTextureAtlasSprite { } - /**+ - * Updates the compass based on the given x,z coords and camera - * direction + /** + * + Updates the compass based on the given x,z coords and camera direction */ public void updateCompass(World worldIn, double parDouble1, double parDouble2, double parDouble3, boolean parFlag, boolean parFlag2, IFramebufferGL[] copyColorFramebuffer) { diff --git a/src/game/java/net/minecraft/client/renderer/texture/TextureManager.java b/src/game/java/net/minecraft/client/renderer/texture/TextureManager.java index f01159d4..e3fdcc06 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/TextureManager.java +++ b/src/game/java/net/minecraft/client/renderer/texture/TextureManager.java @@ -1,6 +1,6 @@ package net.minecraft.client.renderer.texture; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE2; import java.io.IOException; import java.util.List; @@ -24,22 +24,25 @@ import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -83,12 +86,34 @@ public class TextureManager implements ITickable, IResourceManagerReloadListener } } - public boolean loadTickableTexture(ResourceLocation textureLocation, ITickableTextureObject textureObj) { - if (this.loadTexture(textureLocation, textureObj)) { - this.listTickables.add(textureObj); - return true; + public void deleteTexture(ResourceLocation textureLocation) { + ITextureObject itextureobject = this.mapTextureObjects.remove(textureLocation); + if (itextureobject != null) { + TextureUtil.deleteTexture(itextureobject.getGlTextureId()); + } + } + + public ResourceLocation getDynamicTextureLocation(String name, DynamicTexture texture) { + Integer integer = (Integer) this.mapTextureCounters.get(name); + if (integer == null) { + integer = Integer.valueOf(1); } else { - return false; + integer = Integer.valueOf(integer.intValue() + 1); + } + + this.mapTextureCounters.put(name, integer); + ResourceLocation resourcelocation = new ResourceLocation( + HString.format("dynamic/%s_%d", new Object[] { name, integer })); + this.loadTexture(resourcelocation, texture); + return resourcelocation; + } + + public ITextureObject getTexture(ResourceLocation textureLocation) { + if (textureLocation.cachedPointerType == ResourceLocation.CACHED_POINTER_TEXTURE) { + return (ITextureObject) textureLocation.cachedPointer; + } else { + textureLocation.cachedPointerType = ResourceLocation.CACHED_POINTER_TEXTURE; + return (ITextureObject) (textureLocation.cachedPointer = this.mapTextureObjects.get(textureLocation)); } } @@ -121,41 +146,12 @@ public class TextureManager implements ITickable, IResourceManagerReloadListener return flag; } - public ITextureObject getTexture(ResourceLocation textureLocation) { - if (textureLocation.cachedPointerType == ResourceLocation.CACHED_POINTER_TEXTURE) { - return (ITextureObject) textureLocation.cachedPointer; + public boolean loadTickableTexture(ResourceLocation textureLocation, ITickableTextureObject textureObj) { + if (this.loadTexture(textureLocation, textureObj)) { + this.listTickables.add(textureObj); + return true; } else { - textureLocation.cachedPointerType = ResourceLocation.CACHED_POINTER_TEXTURE; - return (ITextureObject) (textureLocation.cachedPointer = this.mapTextureObjects.get(textureLocation)); - } - } - - public ResourceLocation getDynamicTextureLocation(String name, DynamicTexture texture) { - Integer integer = (Integer) this.mapTextureCounters.get(name); - if (integer == null) { - integer = Integer.valueOf(1); - } else { - integer = Integer.valueOf(integer.intValue() + 1); - } - - this.mapTextureCounters.put(name, integer); - ResourceLocation resourcelocation = new ResourceLocation( - HString.format("dynamic/%s_%d", new Object[] { name, integer })); - this.loadTexture(resourcelocation, texture); - return resourcelocation; - } - - public void tick() { - for (int i = 0, l = this.listTickables.size(); i < l; ++i) { - this.listTickables.get(i).tick(); - } - - } - - public void deleteTexture(ResourceLocation textureLocation) { - ITextureObject itextureobject = this.mapTextureObjects.remove(textureLocation); - if (itextureobject != null) { - TextureUtil.deleteTexture(itextureobject.getGlTextureId()); + return false; } } @@ -165,4 +161,11 @@ public class TextureManager implements ITickable, IResourceManagerReloadListener } } + + public void tick() { + for (int i = 0, l = this.listTickables.size(); i < l; ++i) { + this.listTickables.get(i).tick(); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/texture/TextureMap.java b/src/game/java/net/minecraft/client/renderer/texture/TextureMap.java index 794bfa14..6aa4eb44 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/TextureMap.java +++ b/src/game/java/net/minecraft/client/renderer/texture/TextureMap.java @@ -1,6 +1,12 @@ package net.minecraft.client.renderer.texture; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE2; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; import java.io.IOException; import java.util.Collection; @@ -36,24 +42,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,6 +69,8 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec private static final Logger logger = LogManager.getLogger(); public static final ResourceLocation LOCATION_MISSING_TEXTURE = new ResourceLocation("missingno"); public static final ResourceLocation locationBlocksTexture = new ResourceLocation("textures/atlas/blocks.png"); + public static final int _GL_FRAMEBUFFER = 0x8D40; + public static final int _GL_COLOR_ATTACHMENT0 = 0x8CE0; private final List listAnimatedSprites; private final Map mapRegisteredSprites; private final Map mapUploadedSprites; @@ -74,12 +83,10 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec private int height; private boolean isEaglerPBRMode = false; public int eaglerPBRMaterialTexture = -1; + private boolean hasAllocatedEaglerPBRMaterialTexture = false; private boolean isGLES2 = false; - public static final int _GL_FRAMEBUFFER = 0x8D40; - public static final int _GL_COLOR_ATTACHMENT0 = 0x8CE0; - private IFramebufferGL[] copyColorFramebuffer = null; private IFramebufferGL[] copyMaterialFramebuffer = null; @@ -98,6 +105,61 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec this.isGLES2 = EaglercraftGPU.checkOpenGLESVersion() == 200; } + private ResourceLocation completeResourceLocation(ResourceLocation location, int parInt1) { + return parInt1 == 0 + ? new ResourceLocation(location.getResourceDomain(), + HString.format("%s/%s%s", new Object[] { this.basePath, location.getResourcePath(), ".png" })) + : new ResourceLocation(location.getResourceDomain(), HString.format("%s/mipmaps/%s.%d%s", + new Object[] { this.basePath, location.getResourcePath(), Integer.valueOf(parInt1), ".png" })); + } + + public void deleteGlTexture() { + super.deleteGlTexture(); + if (eaglerPBRMaterialTexture != -1) { + GlStateManager.deleteTexture(eaglerPBRMaterialTexture); + eaglerPBRMaterialTexture = -1; + } + if (copyColorFramebuffer != null) { + for (int i = 0; i < copyColorFramebuffer.length; ++i) { + _wglDeleteFramebuffer(copyColorFramebuffer[i]); + } + copyColorFramebuffer = null; + } + if (copyMaterialFramebuffer != null) { + for (int i = 0; i < copyMaterialFramebuffer.length; ++i) { + _wglDeleteFramebuffer(copyMaterialFramebuffer[i]); + } + copyMaterialFramebuffer = null; + } + } + + private void destroyAnimationCaches() { + for (int i = 0, l = this.listAnimatedSprites.size(); i < l; ++i) { + this.listAnimatedSprites.get(i).clearFramesTextureData(); + } + } + + public EaglerTextureAtlasSprite getAtlasSprite(String iconName) { + EaglerTextureAtlasSprite textureatlassprite = (EaglerTextureAtlasSprite) this.mapUploadedSprites.get(iconName); + if (textureatlassprite == null) { + textureatlassprite = isEaglerPBRMode ? missingImagePBR : missingImage; + } + + return textureatlassprite; + } + + public int getHeight() { + return height; + } + + public EaglerTextureAtlasSprite getMissingSprite() { + return isEaglerPBRMode ? missingImagePBR : missingImage; + } + + public int getWidth() { + return width; + } + private void initMissingImage() { int[] aint = TextureUtil.missingTextureData; this.missingImage.setIconWidth(16); @@ -123,12 +185,6 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec Lists.newArrayList(new int[][][] { aint2[1] }), Lists.newArrayList(new int[][][] { aint2[2] }) }); } - public void loadTexture(IResourceManager parIResourceManager) throws IOException { - if (this.iconCreator != null) { - this.loadSprites(parIResourceManager, this.iconCreator); - } - } - public void loadSprites(IResourceManager resourceManager, IIconCreator parIIconCreator) { destroyAnimationCaches(); this.mapRegisteredSprites.clear(); @@ -138,23 +194,9 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec this.loadTextureAtlas(resourceManager); } - public void deleteGlTexture() { - super.deleteGlTexture(); - if (eaglerPBRMaterialTexture != -1) { - GlStateManager.deleteTexture(eaglerPBRMaterialTexture); - eaglerPBRMaterialTexture = -1; - } - if (copyColorFramebuffer != null) { - for (int i = 0; i < copyColorFramebuffer.length; ++i) { - _wglDeleteFramebuffer(copyColorFramebuffer[i]); - } - copyColorFramebuffer = null; - } - if (copyMaterialFramebuffer != null) { - for (int i = 0; i < copyMaterialFramebuffer.length; ++i) { - _wglDeleteFramebuffer(copyMaterialFramebuffer[i]); - } - copyMaterialFramebuffer = null; + public void loadTexture(IResourceManager parIResourceManager) throws IOException { + if (this.iconCreator != null) { + this.loadSprites(parIResourceManager, this.iconCreator); } } @@ -498,46 +540,6 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec _wglBindFramebuffer(_GL_FRAMEBUFFER, null); } - private ResourceLocation completeResourceLocation(ResourceLocation location, int parInt1) { - return parInt1 == 0 - ? new ResourceLocation(location.getResourceDomain(), - HString.format("%s/%s%s", new Object[] { this.basePath, location.getResourcePath(), ".png" })) - : new ResourceLocation(location.getResourceDomain(), HString.format("%s/mipmaps/%s.%d%s", - new Object[] { this.basePath, location.getResourcePath(), Integer.valueOf(parInt1), ".png" })); - } - - public EaglerTextureAtlasSprite getAtlasSprite(String iconName) { - EaglerTextureAtlasSprite textureatlassprite = (EaglerTextureAtlasSprite) this.mapUploadedSprites.get(iconName); - if (textureatlassprite == null) { - textureatlassprite = isEaglerPBRMode ? missingImagePBR : missingImage; - } - - return textureatlassprite; - } - - public void updateAnimations() { - if (isEaglerPBRMode) { - for (int i = 0, l = this.listAnimatedSprites.size(); i < l; ++i) { - this.listAnimatedSprites.get(i).updateAnimationPBR(copyColorFramebuffer, copyMaterialFramebuffer, - height); - } - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - return; - } - - for (int i = 0, l = this.listAnimatedSprites.size(); i < l; ++i) { - this.listAnimatedSprites.get(i).updateAnimation(copyColorFramebuffer); - } - - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - } - - private void destroyAnimationCaches() { - for (int i = 0, l = this.listAnimatedSprites.size(); i < l; ++i) { - this.listAnimatedSprites.get(i).clearFramesTextureData(); - } - } - public EaglerTextureAtlasSprite registerSprite(ResourceLocation location) { if (location == null) { throw new IllegalArgumentException("Location cannot be null!"); @@ -557,35 +559,6 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec } } - public void tick() { - this.updateAnimations(); - } - - public void setMipmapLevels(int mipmapLevelsIn) { - if (!isGLES2) { - this.mipmapLevels = mipmapLevelsIn; - } else { - this.mipmapLevels = 0; // Due to limitations in OpenGL ES 2.0 texture completeness, its easier to just - // make this zero - } - } - - public EaglerTextureAtlasSprite getMissingSprite() { - return isEaglerPBRMode ? missingImagePBR : missingImage; - } - - public int getWidth() { - return width; - } - - public int getHeight() { - return height; - } - - public void setEnablePBREagler(boolean enable) { - isEaglerPBRMode = enable; - } - public void setBlurMipmapDirect0(boolean parFlag, boolean parFlag2) { if (isGLES2) { super.setBlurMipmapDirect0(parFlag, false); @@ -599,4 +572,38 @@ public class TextureMap extends AbstractTexture implements ITickableTextureObjec } } } + + public void setEnablePBREagler(boolean enable) { + isEaglerPBRMode = enable; + } + + public void setMipmapLevels(int mipmapLevelsIn) { + if (!isGLES2) { + this.mipmapLevels = mipmapLevelsIn; + } else { + this.mipmapLevels = 0; // Due to limitations in OpenGL ES 2.0 texture completeness, its easier to just + // make this zero + } + } + + public void tick() { + this.updateAnimations(); + } + + public void updateAnimations() { + if (isEaglerPBRMode) { + for (int i = 0, l = this.listAnimatedSprites.size(); i < l; ++i) { + this.listAnimatedSprites.get(i).updateAnimationPBR(copyColorFramebuffer, copyMaterialFramebuffer, + height); + } + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + return; + } + + for (int i = 0, l = this.listAnimatedSprites.size(); i < l; ++i) { + this.listAnimatedSprites.get(i).updateAnimation(copyColorFramebuffer); + } + + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/texture/TextureUtil.java b/src/game/java/net/minecraft/client/renderer/texture/TextureUtil.java index bfd29deb..c1681170 100644 --- a/src/game/java/net/minecraft/client/renderer/texture/TextureUtil.java +++ b/src/game/java/net/minecraft/client/renderer/texture/TextureUtil.java @@ -1,12 +1,23 @@ package net.minecraft.client.renderer.texture; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; import java.io.IOException; import java.io.InputStream; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import net.lax1dude.eaglercraft.v1_8.IOUtils; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; @@ -17,22 +28,25 @@ import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,60 +58,63 @@ public class TextureUtil { public static final int[] missingTextureData = missingTexture.getTextureData(); private static final int[] mipmapBuffer; - public static int glGenTextures() { - return GlStateManager.generateTexture(); - } + static { + int i = -16777216; + int j = -524040; + int[] aint = new int[] { -524040, -524040, -524040, -524040, -524040, -524040, -524040, -524040 }; + int[] aint1 = new int[] { -16777216, -16777216, -16777216, -16777216, -16777216, -16777216, -16777216, + -16777216 }; + int k = aint.length; - public static void deleteTexture(int textureId) { - GlStateManager.deleteTexture(textureId); - } - - public static int uploadTextureImage(int parInt1, ImageData parBufferedImage) { - return uploadTextureImageAllocate(parInt1, parBufferedImage, false, false); - } - - public static void uploadTexture(int textureId, int[] parArrayOfInt, int parInt2, int parInt3) { - bindTexture(textureId); - uploadTextureSub(0, parArrayOfInt, parInt2, parInt3, 0, 0, false, false, false); - } - - public static int[][] generateMipmapData(int parInt1, int parInt2, int[][] parArrayOfarray) { - int[][] aint = new int[parInt1 + 1][]; - aint[0] = parArrayOfarray[0]; - if (parInt1 > 0) { - boolean flag = false; - - for (int i = 0; i < parArrayOfarray.length; ++i) { - if (parArrayOfarray[0][i] >> 24 == 0) { - flag = true; - break; - } - } - - for (int l1 = 1; l1 <= parInt1; ++l1) { - if (parArrayOfarray[l1] != null) { - aint[l1] = parArrayOfarray[l1]; - } else { - int[] aint1 = aint[l1 - 1]; - int[] aint2 = new int[aint1.length >> 2]; - int j = parInt2 >> l1; - int k = aint2.length / j; - int l = j << 1; - - for (int i1 = 0; i1 < j; ++i1) { - for (int j1 = 0; j1 < k; ++j1) { - int k1 = 2 * (i1 + j1 * l); - aint2[i1 + j1 * j] = blendColors(aint1[k1 + 0], aint1[k1 + 1], aint1[k1 + 0 + l], - aint1[k1 + 1 + l], flag); - } - } - - aint[l1] = aint2; - } - } + for (int l = 0; l < 16; ++l) { + System.arraycopy(l < k ? aint : aint1, 0, missingTextureData, 16 * l, k); + System.arraycopy(l < k ? aint1 : aint, 0, missingTextureData, 16 * l + k, k); } - return aint; + missingTexture.updateDynamicTexture(); + mipmapBuffer = new int[4]; + } + + public static void allocateTexture(int parInt1, int parInt2, int parInt3) { + allocateTextureImpl(parInt1, 0, parInt2, parInt3); + } + + public static void allocateTextureImpl(int parInt1, int parInt2, int parInt3, int parInt4) { + // deleteTexture(parInt1); //TODO: why + bindTexture(parInt1); + if (parInt2 >= 0) { + if (EaglercraftGPU.checkOpenGLESVersion() >= 300) { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, '\u813d', parInt2); + EaglercraftGPU.glTexParameterf(GL_TEXTURE_2D, '\u813a', 0.0F); + EaglercraftGPU.glTexParameterf(GL_TEXTURE_2D, '\u813b', (float) parInt2); + // EaglercraftGPU.glTexParameterf(GL_TEXTURE_2D, '\u8501', 0.0F); + } + } + EaglercraftGPU.glTexStorage2D(GL_TEXTURE_2D, parInt2 + 1, GL_RGBA8, parInt3, parInt4); + } + + public static int anaglyphColor(int parInt1) { + int i = parInt1 >> 24 & 255; + int j = parInt1 >> 16 & 255; + int k = parInt1 >> 8 & 255; + int l = parInt1 & 255; + int i1 = (j * 30 + k * 59 + l * 11) / 100; + int j1 = (j * 30 + k * 70) / 100; + int k1 = (j * 30 + l * 70) / 100; + return i << 24 | i1 << 16 | j1 << 8 | k1; + } + + static void bindTexture(int parInt1) { + GlStateManager.bindTexture(parInt1); + } + + private static int blendColorComponent(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5) { + float f = (float) Math.pow((double) ((float) (parInt1 >> parInt5 & 255) / 255.0F), 2.2D); + float f1 = (float) Math.pow((double) ((float) (parInt2 >> parInt5 & 255) / 255.0F), 2.2D); + float f2 = (float) Math.pow((double) ((float) (parInt3 >> parInt5 & 255) / 255.0F), 2.2D); + float f3 = (float) Math.pow((double) ((float) (parInt4 >> parInt5 & 255) / 255.0F), 2.2D); + float f4 = (float) Math.pow((double) (f + f1 + f2 + f3) * 0.25D, 0.45454545454545453D); + return (int) ((double) f4 * 255.0D); } private static int blendColors(int parInt1, int parInt2, int parInt3, int parInt4, boolean parFlag) { @@ -142,46 +159,147 @@ public class TextureUtil { } } - private static int blendColorComponent(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5) { - float f = (float) Math.pow((double) ((float) (parInt1 >> parInt5 & 255) / 255.0F), 2.2D); - float f1 = (float) Math.pow((double) ((float) (parInt2 >> parInt5 & 255) / 255.0F), 2.2D); - float f2 = (float) Math.pow((double) ((float) (parInt3 >> parInt5 & 255) / 255.0F), 2.2D); - float f3 = (float) Math.pow((double) ((float) (parInt4 >> parInt5 & 255) / 255.0F), 2.2D); - float f4 = (float) Math.pow((double) (f + f1 + f2 + f3) * 0.25D, 0.45454545454545453D); - return (int) ((double) f4 * 255.0D); + public static int[] convertComponentOrder(int[] arr) { + for (int i = 0; i < arr.length; ++i) { + int j = arr[i]; + arr[i] = ((j >> 16) & 0xFF) | (j & 0xFF00FF00) | ((j << 16) & 0xFF0000); + } + return arr; } - public static void uploadTextureMipmap(int[][] parArrayOfarray, int parInt1, int parInt2, int parInt3, int parInt4, - boolean parFlag, boolean parFlag2) { - for (int i = 0; i < parArrayOfarray.length; ++i) { - int[] aint = parArrayOfarray[i]; - uploadTextureSub(i, aint, parInt1 >> i, parInt2 >> i, parInt3 >> i, parInt4 >> i, parFlag, parFlag2, - parArrayOfarray.length > 1); + private static void copyToBuffer(int[] parArrayOfInt, int parInt1) { + copyToBufferPos(parArrayOfInt, 0, parInt1); + } + + private static void copyToBufferPos(int[] parArrayOfInt, int parInt1, int parInt2) { + int[] aint = parArrayOfInt; + if (Minecraft.getMinecraft().gameSettings.anaglyph) { + aint = updateAnaglyph(parArrayOfInt); + } + + dataBuffer.clear(); + dataBuffer.put(aint, parInt1, parInt2); + dataBuffer.position(0).limit(parInt2); + } + + public static void deleteTexture(int textureId) { + GlStateManager.deleteTexture(textureId); + } + + public static int[][] generateMipmapData(int parInt1, int parInt2, int[][] parArrayOfarray) { + int[][] aint = new int[parInt1 + 1][]; + aint[0] = parArrayOfarray[0]; + if (parInt1 > 0) { + boolean flag = false; + + for (int i = 0; i < parArrayOfarray.length; ++i) { + if (parArrayOfarray[0][i] >> 24 == 0) { + flag = true; + break; + } + } + + for (int l1 = 1; l1 <= parInt1; ++l1) { + if (parArrayOfarray[l1] != null) { + aint[l1] = parArrayOfarray[l1]; + } else { + int[] aint1 = aint[l1 - 1]; + int[] aint2 = new int[aint1.length >> 2]; + int j = parInt2 >> l1; + int k = aint2.length / j; + int l = j << 1; + + for (int i1 = 0; i1 < j; ++i1) { + for (int j1 = 0; j1 < k; ++j1) { + int k1 = 2 * (i1 + j1 * l); + aint2[i1 + j1 * j] = blendColors(aint1[k1 + 0], aint1[k1 + 1], aint1[k1 + 0 + l], + aint1[k1 + 1 + l], flag); + } + } + + aint[l1] = aint2; + } + } + } + + return aint; + } + + public static int glGenTextures() { + return GlStateManager.generateTexture(); + } + + public static void processPixelValues(int[] parArrayOfInt, int parInt1, int parInt2) { + int[] aint = new int[parInt1]; + int i = parInt2 / 2; + + for (int j = 0; j < i; ++j) { + System.arraycopy(parArrayOfInt, j * parInt1, aint, 0, parInt1); + System.arraycopy(parArrayOfInt, (parInt2 - 1 - j) * parInt1, parArrayOfInt, j * parInt1, parInt1); + System.arraycopy(aint, 0, parArrayOfInt, (parInt2 - 1 - j) * parInt1, parInt1); } } - private static void uploadTextureSub(int parInt1, int[] parArrayOfInt, int parInt2, int parInt3, int parInt4, - int parInt5, boolean parFlag, boolean parFlag2, boolean parFlag3) { - int i = 4194304 / parInt2; - setTextureBlurMipmap(parFlag, parFlag3); - if (!parFlag2 && !EaglercraftGPU.checkNPOTCapable() && ImageData.isNPOTStatic(parInt2, parInt3)) { - parFlag2 = true; - logger.warn( - "An NPOT (non-power-of-two) texture was allocated with GL_REPEAT wrapping in an OpenGL context where that isn't supported, changing to GL_CLAMP_TO_EDGE to avoid errors"); - } - setTextureClamped(parFlag2); - - int l; - for (int j = 0; j < parInt2 * parInt3; j += parInt2 * l) { - int k = j / parInt2; - l = Math.min(i, parInt3 - k); - int i1 = parInt2 * l; - copyToBufferPos(parArrayOfInt, j, i1); - EaglercraftGPU.glTexSubImage2D(GL_TEXTURE_2D, parInt1, parInt4, parInt5 + k, parInt2, l, GL_RGBA, - GL_UNSIGNED_BYTE, dataBuffer); + public static ImageData readBufferedImage(InputStream imageStream) throws IOException { + ImageData bufferedimage; + try { + bufferedimage = ImageData.loadImageFile(imageStream); + } finally { + IOUtils.closeQuietly(imageStream); } + return bufferedimage; + } + + public static int[] readImageData(IResourceManager resourceManager, ResourceLocation imageLocation) + throws IOException { + return readBufferedImage(resourceManager.getResource(imageLocation).getInputStream()).pixels; + } + + private static void setTextureBlurMipmap(boolean parFlag, boolean parFlag2) { + if (parFlag) { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, parFlag2 ? 9987 : 9729); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } else { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, parFlag2 ? 9986 : 9728); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } + + } + + private static void setTextureBlurred(boolean parFlag) { + setTextureBlurMipmap(parFlag, false); + } + + private static void setTextureClamped(boolean parFlag) { + if (parFlag) { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } else { + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + + } + + public static int[] updateAnaglyph(int[] parArrayOfInt) { + int[] aint = new int[parArrayOfInt.length]; + + for (int i = 0; i < parArrayOfInt.length; ++i) { + aint[i] = anaglyphColor(parArrayOfInt[i]); + } + + return aint; + } + + public static void uploadTexture(int textureId, int[] parArrayOfInt, int parInt2, int parInt3) { + bindTexture(textureId); + uploadTextureSub(0, parArrayOfInt, parInt2, parInt3, 0, 0, false, false, false); + } + + public static int uploadTextureImage(int parInt1, ImageData parBufferedImage) { + return uploadTextureImageAllocate(parInt1, parBufferedImage, false, false); } public static int uploadTextureImageAllocate(int parInt1, ImageData parBufferedImage, boolean parFlag, @@ -190,24 +308,6 @@ public class TextureUtil { return uploadTextureImageSub(parInt1, parBufferedImage, 0, 0, parFlag, parFlag2); } - public static void allocateTexture(int parInt1, int parInt2, int parInt3) { - allocateTextureImpl(parInt1, 0, parInt2, parInt3); - } - - public static void allocateTextureImpl(int parInt1, int parInt2, int parInt3, int parInt4) { - // deleteTexture(parInt1); //TODO: why - bindTexture(parInt1); - if (parInt2 >= 0) { - if (EaglercraftGPU.checkOpenGLESVersion() >= 300) { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, '\u813d', parInt2); - EaglercraftGPU.glTexParameterf(GL_TEXTURE_2D, '\u813a', 0.0F); - EaglercraftGPU.glTexParameterf(GL_TEXTURE_2D, '\u813b', (float) parInt2); - // EaglercraftGPU.glTexParameterf(GL_TEXTURE_2D, '\u8501', 0.0F); - } - } - EaglercraftGPU.glTexStorage2D(GL_TEXTURE_2D, parInt2 + 1, GL_RGBA8, parInt3, parInt4); - } - public static int uploadTextureImageSub(int textureId, ImageData parBufferedImage, int parInt2, int parInt3, boolean parFlag, boolean parFlag2) { bindTexture(textureId); @@ -241,122 +341,36 @@ public class TextureUtil { } - private static void setTextureClamped(boolean parFlag) { - if (parFlag) { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } else { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + public static void uploadTextureMipmap(int[][] parArrayOfarray, int parInt1, int parInt2, int parInt3, int parInt4, + boolean parFlag, boolean parFlag2) { + for (int i = 0; i < parArrayOfarray.length; ++i) { + int[] aint = parArrayOfarray[i]; + uploadTextureSub(i, aint, parInt1 >> i, parInt2 >> i, parInt3 >> i, parInt4 >> i, parFlag, parFlag2, + parArrayOfarray.length > 1); } } - private static void setTextureBlurred(boolean parFlag) { - setTextureBlurMipmap(parFlag, false); - } + private static void uploadTextureSub(int parInt1, int[] parArrayOfInt, int parInt2, int parInt3, int parInt4, + int parInt5, boolean parFlag, boolean parFlag2, boolean parFlag3) { + int i = 4194304 / parInt2; + setTextureBlurMipmap(parFlag, parFlag3); + if (!parFlag2 && !EaglercraftGPU.checkNPOTCapable() && ImageData.isNPOTStatic(parInt2, parInt3)) { + parFlag2 = true; + logger.warn( + "An NPOT (non-power-of-two) texture was allocated with GL_REPEAT wrapping in an OpenGL context where that isn't supported, changing to GL_CLAMP_TO_EDGE to avoid errors"); + } + setTextureClamped(parFlag2); - private static void setTextureBlurMipmap(boolean parFlag, boolean parFlag2) { - if (parFlag) { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, parFlag2 ? 9987 : 9729); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } else { - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, parFlag2 ? 9986 : 9728); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + int l; + for (int j = 0; j < parInt2 * parInt3; j += parInt2 * l) { + int k = j / parInt2; + l = Math.min(i, parInt3 - k); + int i1 = parInt2 * l; + copyToBufferPos(parArrayOfInt, j, i1); + EaglercraftGPU.glTexSubImage2D(GL_TEXTURE_2D, parInt1, parInt4, parInt5 + k, parInt2, l, GL_RGBA, + GL_UNSIGNED_BYTE, dataBuffer); } } - - private static void copyToBuffer(int[] parArrayOfInt, int parInt1) { - copyToBufferPos(parArrayOfInt, 0, parInt1); - } - - private static void copyToBufferPos(int[] parArrayOfInt, int parInt1, int parInt2) { - int[] aint = parArrayOfInt; - if (Minecraft.getMinecraft().gameSettings.anaglyph) { - aint = updateAnaglyph(parArrayOfInt); - } - - dataBuffer.clear(); - dataBuffer.put(aint, parInt1, parInt2); - dataBuffer.position(0).limit(parInt2); - } - - static void bindTexture(int parInt1) { - GlStateManager.bindTexture(parInt1); - } - - public static int[] readImageData(IResourceManager resourceManager, ResourceLocation imageLocation) - throws IOException { - return readBufferedImage(resourceManager.getResource(imageLocation).getInputStream()).pixels; - } - - public static ImageData readBufferedImage(InputStream imageStream) throws IOException { - ImageData bufferedimage; - try { - bufferedimage = ImageData.loadImageFile(imageStream); - } finally { - IOUtils.closeQuietly(imageStream); - } - - return bufferedimage; - } - - public static int[] updateAnaglyph(int[] parArrayOfInt) { - int[] aint = new int[parArrayOfInt.length]; - - for (int i = 0; i < parArrayOfInt.length; ++i) { - aint[i] = anaglyphColor(parArrayOfInt[i]); - } - - return aint; - } - - public static int anaglyphColor(int parInt1) { - int i = parInt1 >> 24 & 255; - int j = parInt1 >> 16 & 255; - int k = parInt1 >> 8 & 255; - int l = parInt1 & 255; - int i1 = (j * 30 + k * 59 + l * 11) / 100; - int j1 = (j * 30 + k * 70) / 100; - int k1 = (j * 30 + l * 70) / 100; - return i << 24 | i1 << 16 | j1 << 8 | k1; - } - - public static void processPixelValues(int[] parArrayOfInt, int parInt1, int parInt2) { - int[] aint = new int[parInt1]; - int i = parInt2 / 2; - - for (int j = 0; j < i; ++j) { - System.arraycopy(parArrayOfInt, j * parInt1, aint, 0, parInt1); - System.arraycopy(parArrayOfInt, (parInt2 - 1 - j) * parInt1, parArrayOfInt, j * parInt1, parInt1); - System.arraycopy(aint, 0, parArrayOfInt, (parInt2 - 1 - j) * parInt1, parInt1); - } - - } - - public static int[] convertComponentOrder(int[] arr) { - for (int i = 0; i < arr.length; ++i) { - int j = arr[i]; - arr[i] = ((j >> 16) & 0xFF) | (j & 0xFF00FF00) | ((j << 16) & 0xFF0000); - } - return arr; - } - - static { - int i = -16777216; - int j = -524040; - int[] aint = new int[] { -524040, -524040, -524040, -524040, -524040, -524040, -524040, -524040 }; - int[] aint1 = new int[] { -16777216, -16777216, -16777216, -16777216, -16777216, -16777216, -16777216, - -16777216 }; - int k = aint.length; - - for (int l = 0; l < 16; ++l) { - System.arraycopy(l < k ? aint : aint1, 0, missingTextureData, 16 * l, k); - System.arraycopy(l < k ? aint1 : aint, 0, missingTextureData, 16 * l + k, k); - } - - missingTexture.updateDynamicTexture(); - mipmapBuffer = new int[4]; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/RenderEnderCrystal.java b/src/game/java/net/minecraft/client/renderer/tileentity/RenderEnderCrystal.java index 9c1bd408..1e12f07a 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/RenderEnderCrystal.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/RenderEnderCrystal.java @@ -9,22 +9,25 @@ import net.minecraft.entity.item.EntityEnderCrystal; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,14 +42,13 @@ public class RenderEnderCrystal extends Render { this.shadowSize = 0.5F; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityEnderCrystal entityendercrystal, double d0, double d1, double d2, float f, float f1) { float f2 = (float) entityendercrystal.innerRotation + f1; @@ -60,9 +62,9 @@ public class RenderEnderCrystal extends Render { super.doRender(entityendercrystal, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityEnderCrystal var1) { return enderCrystalTextures; diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/RenderItemFrame.java b/src/game/java/net/minecraft/client/renderer/tileentity/RenderItemFrame.java index 2e32a17e..71bd7b0e 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/RenderItemFrame.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/RenderItemFrame.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.tileentity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -31,22 +32,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -64,14 +68,13 @@ public class RenderItemFrame extends Render { this.itemRenderer = itemRendererIn; } - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityItemFrame entityitemframe, double d0, double d1, double d2, float var8, float var9) { GlStateManager.pushMatrix(); @@ -108,9 +111,9 @@ public class RenderItemFrame extends Render { GlStateManager.enableColorMaterial(); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityItemFrame var1) { return null; diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/RenderWitherSkull.java b/src/game/java/net/minecraft/client/renderer/tileentity/RenderWitherSkull.java index 167dc900..f1d62e47 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/RenderWitherSkull.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/RenderWitherSkull.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.projectile.EntityWitherSkull; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +34,8 @@ public class RenderWitherSkull extends Render { private static final ResourceLocation invulnerableWitherTextures = new ResourceLocation( "textures/entity/wither/wither_invulnerable.png"); private static final ResourceLocation witherTextures = new ResourceLocation("textures/entity/wither/wither.png"); - /**+ - * The Skeleton's head model. + /** + * + The Skeleton's head model. */ private final ModelSkeletonHead skeletonHeadModel = new ModelSkeletonHead(); @@ -40,27 +43,13 @@ public class RenderWitherSkull extends Render { super(renderManagerIn); } - private float func_82400_a(float parFloat1, float parFloat2, float parFloat3) { - float f; - for (f = parFloat2 - parFloat1; f < -180.0F; f += 360.0F) { - ; - } - - while (f >= 180.0F) { - f -= 360.0F; - } - - return parFloat1 + parFloat3 * f; - } - - /**+ - * Actually renders the given argument. This is a synthetic - * bridge method, always casting down its argument and then - * handing it off to a worker function which does the actual - * work. In all probabilty, the class Render is generic - * (Render) and this method has signature - * public void func_76986_a(T entity, double d, double d1, - * double d2, float f, float f1). But JAD is pre 1.5 so doe + /** + * + Actually renders the given argument. This is a synthetic bridge method, + * always casting down its argument and then handing it off to a worker function + * which does the actual work. In all probabilty, the class Render is generic + * (Render) and this method has signature public void + * func_76986_a(T entity, double d, double d1, double d2, float f, float f1). + * But JAD is pre 1.5 so doe */ public void doRender(EntityWitherSkull entitywitherskull, double d0, double d1, double d2, float f, float f1) { GlStateManager.pushMatrix(); @@ -79,9 +68,22 @@ public class RenderWitherSkull extends Render { super.doRender(entitywitherskull, d0, d1, d2, f, f1); } - /**+ - * Returns the location of an entity's texture. Doesn't seem to - * be called unless you call Render.bindEntityTexture. + private float func_82400_a(float parFloat1, float parFloat2, float parFloat3) { + float f; + for (f = parFloat2 - parFloat1; f < -180.0F; f += 360.0F) { + ; + } + + while (f >= 180.0F) { + f -= 360.0F; + } + + return parFloat1 + parFloat3 * f; + } + + /** + * + Returns the location of an entity's texture. Doesn't seem to be called + * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityWitherSkull entitywitherskull) { return entitywitherskull.isInvulnerable() ? invulnerableWitherTextures : witherTextures; diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBannerRenderer.java b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBannerRenderer.java index 20dcd237..9fee9ae1 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBannerRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBannerRenderer.java @@ -19,31 +19,93 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityBannerRenderer extends TileEntitySpecialRenderer { + static class TimedBannerTexture { + public long systemTime; + public ResourceLocation bannerTexture; + + private TimedBannerTexture() { + } + } + private static final Map DESIGNS = Maps.newHashMap(); private static final ResourceLocation BANNERTEXTURES = new ResourceLocation("textures/entity/banner_base.png"); + private ModelBanner bannerModel = new ModelBanner(); + private ResourceLocation func_178463_a(TileEntityBanner bannerObj) { + String s = bannerObj.func_175116_e(); + if (s.isEmpty()) { + return null; + } else { + TileEntityBannerRenderer.TimedBannerTexture tileentitybannerrenderer$timedbannertexture = (TileEntityBannerRenderer.TimedBannerTexture) DESIGNS + .get(s); + if (tileentitybannerrenderer$timedbannertexture == null) { + if (DESIGNS.size() >= 256) { + long i = EagRuntime.steadyTimeMillis(); + Iterator iterator = DESIGNS.keySet().iterator(); + + while (iterator.hasNext()) { + String s1 = (String) iterator.next(); + TileEntityBannerRenderer.TimedBannerTexture tileentitybannerrenderer$timedbannertexture1 = (TileEntityBannerRenderer.TimedBannerTexture) DESIGNS + .get(s1); + if (i - tileentitybannerrenderer$timedbannertexture1.systemTime > 60000L) { + Minecraft.getMinecraft().getTextureManager() + .deleteTexture(tileentitybannerrenderer$timedbannertexture1.bannerTexture); + iterator.remove(); + } + } + + if (DESIGNS.size() >= 256) { + return null; + } + } + + List list1 = bannerObj.getPatternList(); + List list = bannerObj.getColorList(); + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = list1.size(); i < l; ++i) { + arraylist.add("textures/entity/banner/" + + ((TileEntityBanner.EnumBannerPattern) list1.get(i)).getPatternName() + ".png"); + } + + tileentitybannerrenderer$timedbannertexture = new TileEntityBannerRenderer.TimedBannerTexture(); + tileentitybannerrenderer$timedbannertexture.bannerTexture = new ResourceLocation(s); + Minecraft.getMinecraft().getTextureManager().loadTexture( + tileentitybannerrenderer$timedbannertexture.bannerTexture, + new LayeredColorMaskTexture(BANNERTEXTURES, arraylist, list)); + DESIGNS.put(s, tileentitybannerrenderer$timedbannertexture); + } + + tileentitybannerrenderer$timedbannertexture.systemTime = EagRuntime.steadyTimeMillis(); + return tileentitybannerrenderer$timedbannertexture.bannerTexture; + } + } + public void renderTileEntityAt(TileEntityBanner te, double x, double y, double z, float partialTicks, int destroyStage) { boolean flag = te.getWorld() != null; @@ -95,62 +157,4 @@ public class TileEntityBannerRenderer extends TileEntitySpecialRenderer= 256) { - long i = EagRuntime.steadyTimeMillis(); - Iterator iterator = DESIGNS.keySet().iterator(); - - while (iterator.hasNext()) { - String s1 = (String) iterator.next(); - TileEntityBannerRenderer.TimedBannerTexture tileentitybannerrenderer$timedbannertexture1 = (TileEntityBannerRenderer.TimedBannerTexture) DESIGNS - .get(s1); - if (i - tileentitybannerrenderer$timedbannertexture1.systemTime > 60000L) { - Minecraft.getMinecraft().getTextureManager() - .deleteTexture(tileentitybannerrenderer$timedbannertexture1.bannerTexture); - iterator.remove(); - } - } - - if (DESIGNS.size() >= 256) { - return null; - } - } - - List list1 = bannerObj.getPatternList(); - List list = bannerObj.getColorList(); - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = list1.size(); i < l; ++i) { - arraylist.add("textures/entity/banner/" - + ((TileEntityBanner.EnumBannerPattern) list1.get(i)).getPatternName() + ".png"); - } - - tileentitybannerrenderer$timedbannertexture = new TileEntityBannerRenderer.TimedBannerTexture(); - tileentitybannerrenderer$timedbannertexture.bannerTexture = new ResourceLocation(s); - Minecraft.getMinecraft().getTextureManager().loadTexture( - tileentitybannerrenderer$timedbannertexture.bannerTexture, - new LayeredColorMaskTexture(BANNERTEXTURES, arraylist, list)); - DESIGNS.put(s, tileentitybannerrenderer$timedbannertexture); - } - - tileentitybannerrenderer$timedbannertexture.systemTime = EagRuntime.steadyTimeMillis(); - return tileentitybannerrenderer$timedbannertexture.bannerTexture; - } - } - - static class TimedBannerTexture { - public long systemTime; - public ResourceLocation bannerTexture; - - private TimedBannerTexture() { - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBeaconRenderer.java b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBeaconRenderer.java index 0f929be2..842872cf 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBeaconRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityBeaconRenderer.java @@ -1,6 +1,11 @@ package net.minecraft.client.renderer.tileentity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; import java.util.List; @@ -17,22 +22,25 @@ import net.minecraft.tileentity.TileEntityBeacon; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,6 +48,10 @@ import net.minecraft.util.ResourceLocation; public class TileEntityBeaconRenderer extends TileEntitySpecialRenderer { private static final ResourceLocation beaconBeam = new ResourceLocation("textures/entity/beacon_beam.png"); + public boolean func_181055_a() { + return true; + } + public void renderTileEntityAt(TileEntityBeacon tileentitybeacon, double d0, double d1, double d2, float f, int var9) { if (DeferredStateManager.isEnableShadowRender()) @@ -291,8 +303,4 @@ public class TileEntityBeaconRenderer extends TileEntitySpecialRenderer { - /**+ - * The texture for the book above the enchantment table. + /** + * + The texture for the book above the enchantment table. */ private static final ResourceLocation TEXTURE_BOOK = new ResourceLocation( "textures/entity/enchanting_table_book.png"); diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityEndPortalRenderer.java b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityEndPortalRenderer.java index fb2fac08..fe7f65e5 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityEndPortalRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntityEndPortalRenderer.java @@ -1,10 +1,18 @@ package net.minecraft.client.renderer.tileentity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EYE_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EYE_PLANE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_OBJECT_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_OBJECT_PLANE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.opengl.WorldRenderer; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; @@ -17,22 +25,25 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.tileentity.TileEntityEndPortal; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,6 +54,13 @@ public class TileEntityEndPortalRenderer extends TileEntitySpecialRenderer { - public void renderTileEntityAt(TileEntityMobSpawner tileentitymobspawner, double d0, double d1, double d2, float f, - int var9) { - GlStateManager.pushMatrix(); - GlStateManager.translate((float) d0 + 0.5F, (float) d1, (float) d2 + 0.5F); - renderMob(tileentitymobspawner.getSpawnerBaseLogic(), d0, d1, d2, f); - GlStateManager.popMatrix(); - } - - /**+ - * Render the mob inside the mob spawner. + /** + * + Render the mob inside the mob spawner. */ public static void renderMob(MobSpawnerBaseLogic mobSpawnerLogic, double posX, double posY, double posZ, float partialTicks) { @@ -56,4 +51,12 @@ public class TileEntityMobSpawnerRenderer extends TileEntitySpecialRenderer, TileEntitySpecialRenderer> mapSpecialRenderers = Maps - .newHashMap(); public static TileEntityRendererDispatcher instance = new TileEntityRendererDispatcher(); - private FontRenderer fontRenderer; public static double staticPlayerX; public static double staticPlayerY; public static double staticPlayerZ; + private Map, TileEntitySpecialRenderer> mapSpecialRenderers = Maps + .newHashMap(); + private FontRenderer fontRenderer; public TextureManager renderEngine; public World worldObj; public Entity entity; @@ -82,23 +85,6 @@ public class TileEntityRendererDispatcher { } - public TileEntitySpecialRenderer getSpecialRendererByClass( - Class teClass) { - TileEntitySpecialRenderer tileentityspecialrenderer = (TileEntitySpecialRenderer) this.mapSpecialRenderers - .get(teClass); - if (tileentityspecialrenderer == null && teClass != TileEntity.class) { - tileentityspecialrenderer = this - .getSpecialRendererByClass((Class) teClass.getSuperclass()); - this.mapSpecialRenderers.put(teClass, tileentityspecialrenderer); - } - - return tileentityspecialrenderer; - } - - public TileEntitySpecialRenderer getSpecialRenderer(TileEntity tileEntityIn) { - return tileEntityIn == null ? null : this.getSpecialRendererByClass(tileEntityIn.getClass()); - } - public void cacheActiveRenderInfo(World worldIn, TextureManager textureManagerIn, FontRenderer fontrendererIn, Entity entityIn, float partialTicks) { if (this.worldObj != worldIn) { @@ -116,6 +102,27 @@ public class TileEntityRendererDispatcher { this.entityZ = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double) partialTicks; } + public FontRenderer getFontRenderer() { + return this.fontRenderer; + } + + public TileEntitySpecialRenderer getSpecialRenderer(TileEntity tileEntityIn) { + return tileEntityIn == null ? null : this.getSpecialRendererByClass(tileEntityIn.getClass()); + } + + public TileEntitySpecialRenderer getSpecialRendererByClass( + Class teClass) { + TileEntitySpecialRenderer tileentityspecialrenderer = (TileEntitySpecialRenderer) this.mapSpecialRenderers + .get(teClass); + if (tileentityspecialrenderer == null && teClass != TileEntity.class) { + tileentityspecialrenderer = this + .getSpecialRendererByClass((Class) teClass.getSuperclass()); + this.mapSpecialRenderers.put(teClass, tileentityspecialrenderer); + } + + return tileentityspecialrenderer; + } + public void renderTileEntity(TileEntity tileentityIn, float partialTicks, int destroyStage) { if (tileentityIn.getDistanceSq(this.entityX, this.entityY, this.entityZ) < tileentityIn .getMaxRenderDistanceSquared()) { @@ -132,15 +139,15 @@ public class TileEntityRendererDispatcher { } - /**+ - * Render this TileEntity at a given set of coordinates + /** + * + Render this TileEntity at a given set of coordinates */ public void renderTileEntityAt(TileEntity tileEntityIn, double x, double y, double z, float partialTicks) { this.renderTileEntityAt(tileEntityIn, x, y, z, partialTicks, -1); } - /**+ - * Render this TileEntity at a given set of coordinates + /** + * + Render this TileEntity at a given set of coordinates */ public void renderTileEntityAt(TileEntity tileEntityIn, double x, double y, double z, float partialTicks, int destroyStage) { @@ -164,8 +171,4 @@ public class TileEntityRendererDispatcher { public void setWorld(World worldIn) { this.worldObj = worldIn; } - - public FontRenderer getFontRenderer() { - return this.fontRenderer; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySignRenderer.java b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySignRenderer.java index 027cce6d..afee2729 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySignRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySignRenderer.java @@ -1,9 +1,9 @@ package net.minecraft.client.renderer.tileentity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawBuffers; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT0; import java.util.List; @@ -20,35 +20,38 @@ import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntitySignRenderer extends TileEntitySpecialRenderer { private static final ResourceLocation SIGN_TEXTURE = new ResourceLocation("textures/entity/sign.png"); - /**+ - * The ModelSign instance for use in this renderer + public static boolean disableProfanityFilter = false; + + /** + * + The ModelSign instance for use in this renderer */ private final ModelSign model = new ModelSign(); - public static boolean disableProfanityFilter = false; - public void renderTileEntityAt(TileEntitySign tileentitysign, double d0, double d1, double d2, float var8, int i) { Block block = tileentitysign.getBlockType(); GlStateManager.pushMatrix(); diff --git a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySkullRenderer.java b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySkullRenderer.java index 6c12ee2f..657c0bc8 100644 --- a/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySkullRenderer.java +++ b/src/game/java/net/minecraft/client/renderer/tileentity/TileEntitySkullRenderer.java @@ -1,6 +1,7 @@ package net.minecraft.client.renderer.tileentity; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; @@ -14,22 +15,25 @@ import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,19 +50,6 @@ public class TileEntitySkullRenderer extends TileEntitySpecialRenderer { new ResourceLocation("textures/blocks/destroy_stage_9.png") }; protected TileEntityRendererDispatcher rendererDispatcher; - public abstract void renderTileEntityAt(T var1, double var2, double var4, double var6, float var8, int var9); - protected void bindTexture(ResourceLocation location) { TextureManager texturemanager = this.rendererDispatcher.renderEngine; if (texturemanager != null) { @@ -50,19 +51,21 @@ public abstract class TileEntitySpecialRenderer { } - protected World getWorld() { - return this.rendererDispatcher.worldObj; - } - - public void setRendererDispatcher(TileEntityRendererDispatcher rendererDispatcherIn) { - this.rendererDispatcher = rendererDispatcherIn; + public boolean func_181055_a() { + return false; } public FontRenderer getFontRenderer() { return this.rendererDispatcher.getFontRenderer(); } - public boolean func_181055_a() { - return false; + protected World getWorld() { + return this.rendererDispatcher.worldObj; + } + + public abstract void renderTileEntityAt(T var1, double var2, double var4, double var6, float var8, int var9); + + public void setRendererDispatcher(TileEntityRendererDispatcher rendererDispatcherIn) { + this.rendererDispatcher = rendererDispatcherIn; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/renderer/vertex/DefaultVertexFormats.java b/src/game/java/net/minecraft/client/renderer/vertex/DefaultVertexFormats.java index a9d4297d..14fba96d 100644 --- a/src/game/java/net/minecraft/client/renderer/vertex/DefaultVertexFormats.java +++ b/src/game/java/net/minecraft/client/renderer/vertex/DefaultVertexFormats.java @@ -2,22 +2,25 @@ package net.minecraft.client.renderer.vertex; import net.lax1dude.eaglercraft.v1_8.opengl.VertexFormat; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/AbstractResourcePack.java b/src/game/java/net/minecraft/client/resources/AbstractResourcePack.java index 559cb5ab..2b1fda7b 100644 --- a/src/game/java/net/minecraft/client/resources/AbstractResourcePack.java +++ b/src/game/java/net/minecraft/client/resources/AbstractResourcePack.java @@ -7,8 +7,8 @@ import java.nio.charset.StandardCharsets; import org.json.JSONException; import org.json.JSONObject; -import net.lax1dude.eaglercraft.v1_8.IOUtils; import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.IOUtils; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.minecraft.EaglerFolderResourcePack; @@ -18,68 +18,37 @@ import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class AbstractResourcePack implements IResourcePack { private static final Logger resourceLog = LogManager.getLogger(); - protected final String resourcePackFile; - - public AbstractResourcePack(String resourcePackFileIn) { - this.resourcePackFile = resourcePackFileIn; - } private static String locationToName(ResourceLocation location) { return HString.format("%s/%s/%s", new Object[] { "assets", location.getResourceDomain(), location.getResourcePath() }); } - public InputStream getInputStream(ResourceLocation location) throws IOException { - return this.getInputStreamByName(locationToName(location)); - } - - public boolean resourceExists(ResourceLocation location) { - return this.hasResourceName(locationToName(location)); - } - - protected abstract InputStream getInputStreamByName(String var1) throws IOException; - - protected abstract boolean hasResourceName(String var1); - - protected void logNameNotLowercase(String parString1) { - resourceLog.warn("ResourcePack: ignored non-lowercase namespace: %s in %s", - new Object[] { parString1, this.resourcePackFile }); - } - - public T getPackMetadata(IMetadataSerializer parIMetadataSerializer, String parString1) - throws IOException { - try { - return readMetadata(parIMetadataSerializer, this.getInputStreamByName("pack.mcmeta"), parString1); - } catch (JSONException e) { - if (this instanceof EaglerFolderResourcePack) { - EaglerFolderResourcePack.deleteResourcePack((EaglerFolderResourcePack) this); - } - throw e; - } - } - static T readMetadata(IMetadataSerializer parIMetadataSerializer, InputStream parInputStream, String parString1) { JSONObject jsonobject = null; @@ -95,11 +64,46 @@ public abstract class AbstractResourcePack implements IResourcePack { return parIMetadataSerializer.parseMetadataSection(parString1, jsonobject); } + protected final String resourcePackFile; + + public AbstractResourcePack(String resourcePackFileIn) { + this.resourcePackFile = resourcePackFileIn; + } + + public InputStream getInputStream(ResourceLocation location) throws IOException { + return this.getInputStreamByName(locationToName(location)); + } + + protected abstract InputStream getInputStreamByName(String var1) throws IOException; + public ImageData getPackImage() throws IOException { return TextureUtil.readBufferedImage(this.getInputStreamByName("pack.png")); } + public T getPackMetadata(IMetadataSerializer parIMetadataSerializer, String parString1) + throws IOException { + try { + return readMetadata(parIMetadataSerializer, this.getInputStreamByName("pack.mcmeta"), parString1); + } catch (JSONException e) { + if (this instanceof EaglerFolderResourcePack) { + EaglerFolderResourcePack.deleteResourcePack((EaglerFolderResourcePack) this); + } + throw e; + } + } + public String getPackName() { return this.resourcePackFile; } + + protected abstract boolean hasResourceName(String var1); + + protected void logNameNotLowercase(String parString1) { + resourceLog.warn("ResourcePack: ignored non-lowercase namespace: %s in %s", + new Object[] { parString1, this.resourcePackFile }); + } + + public boolean resourceExists(ResourceLocation location) { + return this.hasResourceName(locationToName(location)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/DefaultPlayerSkin.java b/src/game/java/net/minecraft/client/resources/DefaultPlayerSkin.java index 02fd9fd4..19d2413d 100644 --- a/src/game/java/net/minecraft/client/resources/DefaultPlayerSkin.java +++ b/src/game/java/net/minecraft/client/resources/DefaultPlayerSkin.java @@ -1,74 +1,76 @@ package net.minecraft.client.resources; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DefaultPlayerSkin { - /**+ - * The default skin for the Steve model. + /** + * + The default skin for the Steve model. */ private static final ResourceLocation TEXTURE_STEVE = new ResourceLocation("textures/entity/steve.png"); - /**+ - * The default skin for the Alex model. + /** + * + The default skin for the Alex model. */ private static final ResourceLocation TEXTURE_ALEX = new ResourceLocation("textures/entity/alex.png"); - /**+ - * Returns the default skind for versions prior to 1.8, which is - * always the Steve texture. + /** + * + Retrieves the default skin for this player. Depending on the model used + * this will be Alex or Steve. + */ + public static ResourceLocation getDefaultSkin(EaglercraftUUID playerUUID) { + /** + * + Checks if a players skin model is slim or the default. The Alex model is + * slime while the Steve model is default. + */ + return isSlimSkin(playerUUID) ? TEXTURE_ALEX : TEXTURE_STEVE; + } + + /** + * + Returns the default skind for versions prior to 1.8, which is always the + * Steve texture. */ public static ResourceLocation getDefaultSkinLegacy() { return TEXTURE_STEVE; } - /**+ - * Retrieves the default skin for this player. Depending on the - * model used this will be Alex or Steve. - */ - public static ResourceLocation getDefaultSkin(EaglercraftUUID playerUUID) { - /**+ - * Checks if a players skin model is slim or the default. The - * Alex model is slime while the Steve model is default. - */ - return isSlimSkin(playerUUID) ? TEXTURE_ALEX : TEXTURE_STEVE; - } - - /**+ - * Retrieves the type of skin that a player is using. The Alex - * model is slim while the Steve model is default. + /** + * + Retrieves the type of skin that a player is using. The Alex model is slim + * while the Steve model is default. */ public static String getSkinType(EaglercraftUUID playerUUID) { - /**+ - * Checks if a players skin model is slim or the default. The - * Alex model is slime while the Steve model is default. + /** + * + Checks if a players skin model is slim or the default. The Alex model is + * slime while the Steve model is default. */ return isSlimSkin(playerUUID) ? "slim" : "default"; } - /**+ - * Checks if a players skin model is slim or the default. The - * Alex model is slime while the Steve model is default. + /** + * + Checks if a players skin model is slim or the default. The Alex model is + * slime while the Steve model is default. */ private static boolean isSlimSkin(EaglercraftUUID playerUUID) { return (playerUUID.hashCode() & 1) == 1; diff --git a/src/game/java/net/minecraft/client/resources/DefaultResourcePack.java b/src/game/java/net/minecraft/client/resources/DefaultResourcePack.java index cc802f9a..a929c059 100644 --- a/src/game/java/net/minecraft/client/resources/DefaultResourcePack.java +++ b/src/game/java/net/minecraft/client/resources/DefaultResourcePack.java @@ -14,22 +14,25 @@ import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,18 +58,8 @@ public class DefaultResourcePack implements IResourcePack { return null; } - private InputStream getResourceStream(ResourceLocation location) { - return EagRuntime - .getResourceStream("/assets/" + location.getResourceDomain() + "/" + location.getResourcePath()); - } - - public boolean resourceExists(ResourceLocation location) { - return EagRuntime - .getResourceExists("/assets/" + location.getResourceDomain() + "/" + location.getResourcePath()); - } - - public Set getResourceDomains() { - return defaultResourceDomains; + public ImageData getPackImage() throws IOException { + return TextureUtil.readBufferedImage(EagRuntime.getRequiredResourceStream("pack.png")); } public T getPackMetadata(IMetadataSerializer parIMetadataSerializer, String parString1) @@ -79,11 +72,21 @@ public class DefaultResourcePack implements IResourcePack { } } - public ImageData getPackImage() throws IOException { - return TextureUtil.readBufferedImage(EagRuntime.getRequiredResourceStream("pack.png")); - } - public String getPackName() { return "Default"; } + + public Set getResourceDomains() { + return defaultResourceDomains; + } + + private InputStream getResourceStream(ResourceLocation location) { + return EagRuntime + .getResourceStream("/assets/" + location.getResourceDomain() + "/" + location.getResourcePath()); + } + + public boolean resourceExists(ResourceLocation location) { + return EagRuntime + .getResourceExists("/assets/" + location.getResourceDomain() + "/" + location.getResourcePath()); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/FallbackResourceManager.java b/src/game/java/net/minecraft/client/resources/FallbackResourceManager.java index 73d49fa0..88365dcb 100644 --- a/src/game/java/net/minecraft/client/resources/FallbackResourceManager.java +++ b/src/game/java/net/minecraft/client/resources/FallbackResourceManager.java @@ -14,29 +14,38 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FallbackResourceManager implements IResourceManager { private static final Logger logger = LogManager.getLogger(); + + static ResourceLocation getLocationMcmeta(ResourceLocation location) { + return new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + ".mcmeta"); + } + protected final List resourcePacks = Lists.newArrayList(); + private final IMetadataSerializer frmMetadataSerializer; public FallbackResourceManager(IMetadataSerializer frmMetadataSerializerIn) { @@ -47,8 +56,30 @@ public class FallbackResourceManager implements IResourceManager { this.resourcePacks.add(resourcePack); } - public Set getResourceDomains() { - return null; + public List getAllResources(ResourceLocation location) throws IOException { + ArrayList arraylist = Lists.newArrayList(); + ResourceLocation resourcelocation = getLocationMcmeta(location); + + for (int i = 0, l = this.resourcePacks.size(); i < l; ++i) { + IResourcePack iresourcepack = this.resourcePacks.get(i); + if (iresourcepack.resourceExists(location)) { + InputStream inputstream = iresourcepack.resourceExists(resourcelocation) + ? this.getInputStream(resourcelocation, iresourcepack) + : null; + arraylist.add(new SimpleResource(iresourcepack.getPackName(), location, + this.getInputStream(location, iresourcepack), inputstream, this.frmMetadataSerializer)); + } + } + + if (arraylist.isEmpty()) { + throw new FileNotFoundException(location.toString()); + } else { + return arraylist; + } + } + + protected InputStream getInputStream(ResourceLocation location, IResourcePack resourcePack) throws IOException { + return resourcePack.getInputStream(location); } public IResource getResource(ResourceLocation location) throws IOException { @@ -75,34 +106,8 @@ public class FallbackResourceManager implements IResourceManager { throw new FileNotFoundException(location.toString()); } - protected InputStream getInputStream(ResourceLocation location, IResourcePack resourcePack) throws IOException { - return resourcePack.getInputStream(location); - } - - public List getAllResources(ResourceLocation location) throws IOException { - ArrayList arraylist = Lists.newArrayList(); - ResourceLocation resourcelocation = getLocationMcmeta(location); - - for (int i = 0, l = this.resourcePacks.size(); i < l; ++i) { - IResourcePack iresourcepack = this.resourcePacks.get(i); - if (iresourcepack.resourceExists(location)) { - InputStream inputstream = iresourcepack.resourceExists(resourcelocation) - ? this.getInputStream(resourcelocation, iresourcepack) - : null; - arraylist.add(new SimpleResource(iresourcepack.getPackName(), location, - this.getInputStream(location, iresourcepack), inputstream, this.frmMetadataSerializer)); - } - } - - if (arraylist.isEmpty()) { - throw new FileNotFoundException(location.toString()); - } else { - return arraylist; - } - } - - static ResourceLocation getLocationMcmeta(ResourceLocation location) { - return new ResourceLocation(location.getResourceDomain(), location.getResourcePath() + ".mcmeta"); + public Set getResourceDomains() { + return null; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/FoliageColorReloadListener.java b/src/game/java/net/minecraft/client/resources/FoliageColorReloadListener.java index 8488e5ad..b854d5a5 100644 --- a/src/game/java/net/minecraft/client/resources/FoliageColorReloadListener.java +++ b/src/game/java/net/minecraft/client/resources/FoliageColorReloadListener.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import net.minecraft.world.ColorizerFoliage; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/GrassColorReloadListener.java b/src/game/java/net/minecraft/client/resources/GrassColorReloadListener.java index e4b05b40..11a03842 100644 --- a/src/game/java/net/minecraft/client/resources/GrassColorReloadListener.java +++ b/src/game/java/net/minecraft/client/resources/GrassColorReloadListener.java @@ -6,22 +6,25 @@ import net.minecraft.client.renderer.texture.TextureUtil; import net.minecraft.util.ResourceLocation; import net.minecraft.world.ColorizerGrass; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/I18n.java b/src/game/java/net/minecraft/client/resources/I18n.java index 669c55cc..f8333cec 100644 --- a/src/game/java/net/minecraft/client/resources/I18n.java +++ b/src/game/java/net/minecraft/client/resources/I18n.java @@ -1,21 +1,24 @@ package net.minecraft.client.resources; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,15 +26,15 @@ package net.minecraft.client.resources; public class I18n { private static Locale i18nLocale; - static void setLocale(Locale i18nLocaleIn) { - i18nLocale = i18nLocaleIn; - } - - /**+ - * format(a, b) is equivalent to String.format(translate(a), b). - * Args: translationKey, params... + /** + * + format(a, b) is equivalent to String.format(translate(a), b). Args: + * translationKey, params... */ public static String format(String translateKey, Object... parameters) { return i18nLocale.formatMessage(translateKey, parameters); } + + static void setLocale(Locale i18nLocaleIn) { + i18nLocale = i18nLocaleIn; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/IReloadableResourceManager.java b/src/game/java/net/minecraft/client/resources/IReloadableResourceManager.java index eb89a994..ef462818 100644 --- a/src/game/java/net/minecraft/client/resources/IReloadableResourceManager.java +++ b/src/game/java/net/minecraft/client/resources/IReloadableResourceManager.java @@ -2,28 +2,31 @@ package net.minecraft.client.resources; import java.util.List; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IReloadableResourceManager extends IResourceManager { - void reloadResources(List var1); - void registerReloadListener(IResourceManagerReloadListener var1); + + void reloadResources(List var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/IResource.java b/src/game/java/net/minecraft/client/resources/IResource.java index e344c580..2ded972c 100644 --- a/src/game/java/net/minecraft/client/resources/IResource.java +++ b/src/game/java/net/minecraft/client/resources/IResource.java @@ -5,34 +5,37 @@ import java.io.InputStream; import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IResource { - ResourceLocation getResourceLocation(); - InputStream getInputStream(); - boolean hasMetadata(); - T getMetadata(String var1); + ResourceLocation getResourceLocation(); + String getResourcePackName(); + + boolean hasMetadata(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/IResourceManager.java b/src/game/java/net/minecraft/client/resources/IResourceManager.java index 9a8db5c0..2d768b23 100644 --- a/src/game/java/net/minecraft/client/resources/IResourceManager.java +++ b/src/game/java/net/minecraft/client/resources/IResourceManager.java @@ -6,30 +6,33 @@ import java.util.Set; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IResourceManager { - Set getResourceDomains(); + List getAllResources(ResourceLocation var1) throws IOException; IResource getResource(ResourceLocation var1) throws IOException; - List getAllResources(ResourceLocation var1) throws IOException; + Set getResourceDomains(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/IResourceManagerReloadListener.java b/src/game/java/net/minecraft/client/resources/IResourceManagerReloadListener.java index 0671798b..9334c927 100644 --- a/src/game/java/net/minecraft/client/resources/IResourceManagerReloadListener.java +++ b/src/game/java/net/minecraft/client/resources/IResourceManagerReloadListener.java @@ -1,21 +1,24 @@ package net.minecraft.client.resources; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/IResourcePack.java b/src/game/java/net/minecraft/client/resources/IResourcePack.java index 37650528..2dc95767 100644 --- a/src/game/java/net/minecraft/client/resources/IResourcePack.java +++ b/src/game/java/net/minecraft/client/resources/IResourcePack.java @@ -9,22 +9,25 @@ import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,13 +35,13 @@ import net.minecraft.util.ResourceLocation; public interface IResourcePack { InputStream getInputStream(ResourceLocation var1) throws IOException; - boolean resourceExists(ResourceLocation var1); - - Set getResourceDomains(); + ImageData getPackImage() throws IOException; T getPackMetadata(IMetadataSerializer var1, String var2) throws IOException; - ImageData getPackImage() throws IOException; - String getPackName(); + + Set getResourceDomains(); + + boolean resourceExists(ResourceLocation var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/Language.java b/src/game/java/net/minecraft/client/resources/Language.java index bb26bf81..bc641163 100644 --- a/src/game/java/net/minecraft/client/resources/Language.java +++ b/src/game/java/net/minecraft/client/resources/Language.java @@ -2,22 +2,25 @@ package net.minecraft.client.resources; import net.lax1dude.eaglercraft.v1_8.HString; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,10 +38,23 @@ public class Language implements Comparable { this.bidirectional = bidirectionalIn; } + public int compareTo(Language language) { + return this.languageCode.compareTo(language.languageCode); + } + + public boolean equals(Object object) { + return this == object ? true + : (!(object instanceof Language) ? false : this.languageCode.equals(((Language) object).languageCode)); + } + public String getLanguageCode() { return this.languageCode; } + public int hashCode() { + return this.languageCode.hashCode(); + } + public boolean isBidirectional() { return this.bidirectional; } @@ -46,17 +62,4 @@ public class Language implements Comparable { public String toString() { return HString.format("%s (%s)", new Object[] { this.name, this.region }); } - - public boolean equals(Object object) { - return this == object ? true - : (!(object instanceof Language) ? false : this.languageCode.equals(((Language) object).languageCode)); - } - - public int hashCode() { - return this.languageCode.hashCode(); - } - - public int compareTo(Language language) { - return this.languageCode.compareTo(language.languageCode); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/LanguageManager.java b/src/game/java/net/minecraft/client/resources/LanguageManager.java index 80120423..b6202692 100644 --- a/src/game/java/net/minecraft/client/resources/LanguageManager.java +++ b/src/game/java/net/minecraft/client/resources/LanguageManager.java @@ -16,31 +16,34 @@ import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.client.resources.data.LanguageMetadataSection; import net.minecraft.util.StringTranslate; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LanguageManager implements IResourceManagerReloadListener { private static final Logger logger = LogManager.getLogger(); + protected static final Locale currentLocale = new Locale(); private final IMetadataSerializer theMetadataSerializer; private String currentLanguage; - protected static final Locale currentLocale = new Locale(); private Map languageMap = Maps.newHashMap(); public LanguageManager(IMetadataSerializer theMetadataSerializerIn, String currentLanguageIn) { @@ -49,6 +52,34 @@ public class LanguageManager implements IResourceManagerReloadListener { I18n.setLocale(currentLocale); } + public Language getCurrentLanguage() { + return this.languageMap.containsKey(this.currentLanguage) + ? (Language) this.languageMap.get(this.currentLanguage) + : (Language) this.languageMap.get("en_US"); + } + + public SortedSet getLanguages() { + return Sets.newTreeSet(this.languageMap.values()); + } + + public boolean isCurrentLanguageBidirectional() { + return this.getCurrentLanguage() != null && this.getCurrentLanguage().isBidirectional(); + } + + public boolean isCurrentLocaleUnicode() { + return currentLocale.isUnicode(); + } + + public void onResourceManagerReload(IResourceManager iresourcemanager) { + ArrayList arraylist = Lists.newArrayList(new String[] { "en_US" }); + if (!"en_US".equals(this.currentLanguage)) { + arraylist.add(this.currentLanguage); + } + + currentLocale.loadLocaleDataFiles(iresourcemanager, arraylist); + StringTranslate.replaceWith(currentLocale.properties); + } + public void parseLanguageMetadata(List parList) { this.languageMap.clear(); @@ -75,35 +106,7 @@ public class LanguageManager implements IResourceManagerReloadListener { } - public void onResourceManagerReload(IResourceManager iresourcemanager) { - ArrayList arraylist = Lists.newArrayList(new String[] { "en_US" }); - if (!"en_US".equals(this.currentLanguage)) { - arraylist.add(this.currentLanguage); - } - - currentLocale.loadLocaleDataFiles(iresourcemanager, arraylist); - StringTranslate.replaceWith(currentLocale.properties); - } - - public boolean isCurrentLocaleUnicode() { - return currentLocale.isUnicode(); - } - - public boolean isCurrentLanguageBidirectional() { - return this.getCurrentLanguage() != null && this.getCurrentLanguage().isBidirectional(); - } - public void setCurrentLanguage(Language currentLanguageIn) { this.currentLanguage = currentLanguageIn.getLanguageCode(); } - - public Language getCurrentLanguage() { - return this.languageMap.containsKey(this.currentLanguage) - ? (Language) this.languageMap.get(this.currentLanguage) - : (Language) this.languageMap.get("en_US"); - } - - public SortedSet getLanguages() { - return Sets.newTreeSet(this.languageMap.values()); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/Locale.java b/src/game/java/net/minecraft/client/resources/Locale.java index bc372d53..fca21d20 100644 --- a/src/game/java/net/minecraft/client/resources/Locale.java +++ b/src/game/java/net/minecraft/client/resources/Locale.java @@ -19,40 +19,117 @@ import net.lax1dude.eaglercraft.v1_8.HString; import net.lax1dude.eaglercraft.v1_8.IOUtils; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Locale { - /**+ - * Splits on "=" + /** + * + Splits on "=" */ private static final Splitter splitter = Splitter.on('=').limit(2); private static final Pattern pattern = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); + private static final Set hasShownMissing = new HashSet<>(); Map properties = Maps.newHashMap(); + private boolean unicode; - private static final Set hasShownMissing = new HashSet<>(); + private void checkUnicode() { + this.unicode = false; + int i = 0; + int j = 0; - /**+ - * par2 is a list of languages. For each language $L and domain - * $D, attempts to load the resource $D:lang/$L.lang + for (String s : this.properties.values()) { + int k = s.length(); + j += k; + + for (int l = 0; l < k; ++l) { + if (s.charAt(l) >= 256) { + ++i; + } + } + } + + float f = (float) i / (float) j; + this.unicode = (double) f > 0.1D; + } + + /** + * + Calls String.format(translateKey(key), params) + */ + public String formatMessage(String translateKey, Object[] parameters) { + String s = this.translateKeyPrivate(translateKey); + + try { + return HString.format(s, parameters); + } catch (IllegalFormatException var5) { + return "Format error: " + s; + } + } + + public boolean isUnicode() { + return this.unicode; + } + + /** + * + par1 is a list of Resources + */ + private void loadLocaleData(InputStream parInputStream) throws IOException { + for (String s : IOUtils.readLines(parInputStream, Charsets.UTF_8)) { + if (!s.isEmpty() && s.charAt(0) != 35) { + String[] astring = (String[]) Iterables.toArray(splitter.split(s), String.class); + if (astring != null && astring.length == 2) { + String s1 = astring[0]; + String s2 = pattern.matcher(astring[1]).replaceAll("%s"); // TODO: originally "%$1s" but must be + // "%s" to work with TeaVM (why?) + this.properties.put(s1, s2); + if (s1.startsWith("eaglercraft.")) { + this.properties.put(s1.substring(12), s2); + } + } + } + } + + } + + /** + * + par1 is a list of Resources + */ + private void loadLocaleData(List parList) throws IOException { + for (IResource iresource : parList) { + InputStream inputstream = iresource.getInputStream(); + + try { + this.loadLocaleData(inputstream); + } finally { + IOUtils.closeQuietly(inputstream); + } + } + + } + + /** + * + par2 is a list of languages. For each language $L and domain $D, attempts + * to load the resource $D:lang/$L.lang */ public synchronized void loadLocaleDataFiles(IResourceManager resourceManager, List parList) { this.properties.clear(); @@ -81,86 +158,12 @@ public class Locale { this.checkUnicode(); } - public boolean isUnicode() { - return this.unicode; - } - - private void checkUnicode() { - this.unicode = false; - int i = 0; - int j = 0; - - for (String s : this.properties.values()) { - int k = s.length(); - j += k; - - for (int l = 0; l < k; ++l) { - if (s.charAt(l) >= 256) { - ++i; - } - } - } - - float f = (float) i / (float) j; - this.unicode = (double) f > 0.1D; - } - - /**+ - * par1 is a list of Resources - */ - private void loadLocaleData(List parList) throws IOException { - for (IResource iresource : parList) { - InputStream inputstream = iresource.getInputStream(); - - try { - this.loadLocaleData(inputstream); - } finally { - IOUtils.closeQuietly(inputstream); - } - } - - } - - /**+ - * par1 is a list of Resources - */ - private void loadLocaleData(InputStream parInputStream) throws IOException { - for (String s : IOUtils.readLines(parInputStream, Charsets.UTF_8)) { - if (!s.isEmpty() && s.charAt(0) != 35) { - String[] astring = (String[]) Iterables.toArray(splitter.split(s), String.class); - if (astring != null && astring.length == 2) { - String s1 = astring[0]; - String s2 = pattern.matcher(astring[1]).replaceAll("%s"); // TODO: originally "%$1s" but must be - // "%s" to work with TeaVM (why?) - this.properties.put(s1, s2); - if (s1.startsWith("eaglercraft.")) { - this.properties.put(s1.substring(12), s2); - } - } - } - } - - } - - /**+ - * Returns the translation, or the key itself if the key could - * not be translated. + /** + * + Returns the translation, or the key itself if the key could not be + * translated. */ private String translateKeyPrivate(String parString1) { String s = (String) this.properties.get(parString1); return s == null ? parString1 : s; } - - /**+ - * Calls String.format(translateKey(key), params) - */ - public String formatMessage(String translateKey, Object[] parameters) { - String s = this.translateKeyPrivate(translateKey); - - try { - return HString.format(s, parameters); - } catch (IllegalFormatException var5) { - return "Format error: " + s; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/ResourcePackFileNotFoundException.java b/src/game/java/net/minecraft/client/resources/ResourcePackFileNotFoundException.java index a1b854af..ea6f5f1f 100644 --- a/src/game/java/net/minecraft/client/resources/ResourcePackFileNotFoundException.java +++ b/src/game/java/net/minecraft/client/resources/ResourcePackFileNotFoundException.java @@ -5,22 +5,25 @@ import java.io.FileNotFoundException; import net.lax1dude.eaglercraft.v1_8.HString; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/ResourcePackListEntry.java b/src/game/java/net/minecraft/client/resources/ResourcePackListEntry.java index a412d7b9..897182f4 100644 --- a/src/game/java/net/minecraft/client/resources/ResourcePackListEntry.java +++ b/src/game/java/net/minecraft/client/resources/ResourcePackListEntry.java @@ -16,22 +16,25 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -128,7 +131,23 @@ public abstract class ResourcePackListEntry implements GuiListExtended.IGuiListE } - protected abstract int func_183019_a(); + protected boolean func_148307_h() { + List list = this.resourcePacksGUI.getListContaining(this); + int i = list.indexOf(this); + return i >= 0 && i < list.size() - 1 && ((ResourcePackListEntry) list.get(i + 1)).func_148310_d(); + } + + protected boolean func_148308_f() { + return this.resourcePacksGUI.hasResourcePackEntry(this); + } + + protected boolean func_148309_e() { + return !this.resourcePacksGUI.hasResourcePackEntry(this); + } + + protected boolean func_148310_d() { + return true; + } protected abstract String func_148311_a(); @@ -136,64 +155,18 @@ public abstract class ResourcePackListEntry implements GuiListExtended.IGuiListE protected abstract void func_148313_c(); - protected abstract String getEaglerFolderName(); - - protected boolean func_148310_d() { - return true; - } - - protected boolean func_148309_e() { - return !this.resourcePacksGUI.hasResourcePackEntry(this); - } - - protected boolean func_148308_f() { - return this.resourcePacksGUI.hasResourcePackEntry(this); - } - protected boolean func_148314_g() { List list = this.resourcePacksGUI.getListContaining(this); int i = list.indexOf(this); return i > 0 && ((ResourcePackListEntry) list.get(i - 1)).func_148310_d(); } - protected boolean func_148307_h() { - List list = this.resourcePacksGUI.getListContaining(this); - int i = list.indexOf(this); - return i >= 0 && i < list.size() - 1 && ((ResourcePackListEntry) list.get(i + 1)).func_148310_d(); - } + protected abstract int func_183019_a(); - private void proceedWithBs(int l, boolean deleteInstead) { - if (!deleteInstead && l != 1) { - String s1 = I18n.format("resourcePack.incompatible.confirm.title", new Object[0]); - String s = I18n.format("resourcePack.incompatible.confirm." + (l > 1 ? "new" : "old"), new Object[0]); - this.mc.displayGuiScreen(new GuiYesNo(new GuiYesNoCallback() { - public void confirmClicked(boolean flag, int var2) { - List list2 = ResourcePackListEntry.this.resourcePacksGUI - .getListContaining(ResourcePackListEntry.this); - ResourcePackListEntry.this.mc.displayGuiScreen(ResourcePackListEntry.this.resourcePacksGUI); - if (flag) { - list2.remove(ResourcePackListEntry.this); - ResourcePackListEntry.this.resourcePacksGUI.getSelectedResourcePacks().add(0, - ResourcePackListEntry.this); - } + protected abstract String getEaglerFolderName(); - } - }, s1, s, 0).withOpaqueBackground()); - } else { - this.mc.displayGuiScreen(this.resourcePacksGUI); - this.resourcePacksGUI.getListContaining(this).remove(this); - if (deleteInstead) { - this.mc.loadingScreen.eaglerShow(I18n.format("resourcePack.load.deleting"), this.func_148312_b()); - EaglerFolderResourcePack.deleteResourcePack(EaglerFolderResourcePack.RESOURCE_PACKS, - this.getEaglerFolderName()); - } else { - this.resourcePacksGUI.getSelectedResourcePacks().add(0, this); - } - } - } - - /**+ - * Returns true if the mouse has been pressed on this control. + /** + * + Returns true if the mouse has been pressed on this control. */ public boolean mousePressed(int var1, int var2, int var3, int var4, int i, int j) { if (this.func_148310_d() && i <= 32) { @@ -246,13 +219,43 @@ public abstract class ResourcePackListEntry implements GuiListExtended.IGuiListE return false; } - public void setSelected(int var1, int var2, int var3) { - } - - /**+ - * Fired when the mouse button is released. Arguments: index, x, - * y, mouseEvent, relativeX, relativeY + /** + * + Fired when the mouse button is released. Arguments: index, x, y, + * mouseEvent, relativeX, relativeY */ public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { } + + private void proceedWithBs(int l, boolean deleteInstead) { + if (!deleteInstead && l != 1) { + String s1 = I18n.format("resourcePack.incompatible.confirm.title", new Object[0]); + String s = I18n.format("resourcePack.incompatible.confirm." + (l > 1 ? "new" : "old"), new Object[0]); + this.mc.displayGuiScreen(new GuiYesNo(new GuiYesNoCallback() { + public void confirmClicked(boolean flag, int var2) { + List list2 = ResourcePackListEntry.this.resourcePacksGUI + .getListContaining(ResourcePackListEntry.this); + ResourcePackListEntry.this.mc.displayGuiScreen(ResourcePackListEntry.this.resourcePacksGUI); + if (flag) { + list2.remove(ResourcePackListEntry.this); + ResourcePackListEntry.this.resourcePacksGUI.getSelectedResourcePacks().add(0, + ResourcePackListEntry.this); + } + + } + }, s1, s, 0).withOpaqueBackground()); + } else { + this.mc.displayGuiScreen(this.resourcePacksGUI); + this.resourcePacksGUI.getListContaining(this).remove(this); + if (deleteInstead) { + this.mc.loadingScreen.eaglerShow(I18n.format("resourcePack.load.deleting"), this.func_148312_b()); + EaglerFolderResourcePack.deleteResourcePack(EaglerFolderResourcePack.RESOURCE_PACKS, + this.getEaglerFolderName()); + } else { + this.resourcePacksGUI.getSelectedResourcePacks().add(0, this); + } + } + } + + public void setSelected(int var1, int var2, int var3) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/ResourcePackListEntryDefault.java b/src/game/java/net/minecraft/client/resources/ResourcePackListEntryDefault.java index 2eab788f..45a09925 100644 --- a/src/game/java/net/minecraft/client/resources/ResourcePackListEntryDefault.java +++ b/src/game/java/net/minecraft/client/resources/ResourcePackListEntryDefault.java @@ -13,22 +13,25 @@ import net.minecraft.client.resources.data.PackMetadataSection; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,8 +56,20 @@ public class ResourcePackListEntryDefault extends ResourcePackListEntry { dynamictexture); } - protected int func_183019_a() { - return 1; + protected boolean func_148307_h() { + return false; + } + + protected boolean func_148308_f() { + return false; + } + + protected boolean func_148309_e() { + return false; + } + + protected boolean func_148310_d() { + return false; } protected String func_148311_a() { @@ -73,22 +88,6 @@ public class ResourcePackListEntryDefault extends ResourcePackListEntry { return EnumChatFormatting.RED + "Missing " + "pack.mcmeta" + " :("; } - protected boolean func_148309_e() { - return false; - } - - protected boolean func_148308_f() { - return false; - } - - protected boolean func_148314_g() { - return false; - } - - protected boolean func_148307_h() { - return false; - } - protected String func_148312_b() { return "Default"; } @@ -97,10 +96,14 @@ public class ResourcePackListEntryDefault extends ResourcePackListEntry { this.mc.getTextureManager().bindTexture(this.resourcePackIcon); } - protected boolean func_148310_d() { + protected boolean func_148314_g() { return false; } + protected int func_183019_a() { + return 1; + } + @Override protected String getEaglerFolderName() { return null; diff --git a/src/game/java/net/minecraft/client/resources/ResourcePackListEntryFound.java b/src/game/java/net/minecraft/client/resources/ResourcePackListEntryFound.java index acd72797..571da2ff 100644 --- a/src/game/java/net/minecraft/client/resources/ResourcePackListEntryFound.java +++ b/src/game/java/net/minecraft/client/resources/ResourcePackListEntryFound.java @@ -2,22 +2,25 @@ package net.minecraft.client.resources; import net.minecraft.client.gui.GuiScreenResourcePacks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,14 +34,6 @@ public class ResourcePackListEntryFound extends ResourcePackListEntry { this.field_148319_c = parEntry; } - protected void func_148313_c() { - this.field_148319_c.bindTexturePackIcon(this.mc.getTextureManager()); - } - - protected int func_183019_a() { - return this.field_148319_c.func_183027_f(); - } - protected String func_148311_a() { return this.field_148319_c.getTexturePackDescription(); } @@ -47,10 +42,18 @@ public class ResourcePackListEntryFound extends ResourcePackListEntry { return this.field_148319_c.getResourcePackEaglerDisplayName(); } + protected void func_148313_c() { + this.field_148319_c.bindTexturePackIcon(this.mc.getTextureManager()); + } + public ResourcePackRepository.Entry func_148318_i() { return this.field_148319_c; } + protected int func_183019_a() { + return this.field_148319_c.func_183027_f(); + } + @Override protected String getEaglerFolderName() { return field_148319_c.getResourcePackName(); diff --git a/src/game/java/net/minecraft/client/resources/ResourcePackRepository.java b/src/game/java/net/minecraft/client/resources/ResourcePackRepository.java index 78a9e486..0368fffe 100644 --- a/src/game/java/net/minecraft/client/resources/ResourcePackRepository.java +++ b/src/game/java/net/minecraft/client/resources/ResourcePackRepository.java @@ -24,33 +24,124 @@ import net.minecraft.client.settings.GameSettings; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ResourcePackRepository { + public class Entry { + private EaglerFolderResourcePack reResourcePack; + private PackMetadataSection rePackMetadataSection; + private ImageData texturePackIcon; + private ResourceLocation locationTexturePackIcon; + private TextureManager iconTextureManager; + + private Entry(EaglerFolderResourcePack resourcePackFileIn) { + this.reResourcePack = resourcePackFileIn; + } + + public void bindTexturePackIcon(TextureManager textureManagerIn) { + if (this.locationTexturePackIcon == null) { + this.iconTextureManager = textureManagerIn; + this.locationTexturePackIcon = textureManagerIn.getDynamicTextureLocation("texturepackicon", + new DynamicTexture(this.texturePackIcon)); + } + + textureManagerIn.bindTexture(this.locationTexturePackIcon); + } + + public void closeResourcePack() { + if (this.locationTexturePackIcon != null) { + this.iconTextureManager.deleteTexture(this.locationTexturePackIcon); + this.locationTexturePackIcon = null; + } + if (this.reResourcePack instanceof Closeable) { + IOUtils.closeQuietly((Closeable) this.reResourcePack); + } + + } + + public boolean equals(Object object) { + return this == object ? true + : (object instanceof ResourcePackRepository.Entry ? this.toString().equals(object.toString()) + : false); + } + + public int func_183027_f() { + return this.rePackMetadataSection.getPackFormat(); + } + + public IResourcePack getResourcePack() { + return this.reResourcePack; + } + + public String getResourcePackEaglerDisplayName() { + return this.reResourcePack.getDisplayName(); + } + + public String getResourcePackName() { + return this.reResourcePack.getPackName(); + } + + public String getTexturePackDescription() { + return this.rePackMetadataSection == null + ? EnumChatFormatting.RED + "Invalid pack.mcmeta (or missing \'pack\' section)" + : this.rePackMetadataSection.getPackDescription().getFormattedText(); + } + + public int hashCode() { + return this.toString().hashCode(); + } + + public String toString() { + return this.reResourcePack.resourcePackFile; + } + + public void updateResourcePack() throws IOException { + this.rePackMetadataSection = (PackMetadataSection) this.reResourcePack + .getPackMetadata(ResourcePackRepository.this.rprMetadataSerializer, "pack"); + + try { + this.texturePackIcon = this.reResourcePack.getPackImage(); + } catch (Throwable var2) { + logger.error("Failed to load resource pack icon for \"{}\"!", reResourcePack.resourcePackFile); + logger.error(var2); + } + + if (this.texturePackIcon == null) { + this.texturePackIcon = ResourcePackRepository.this.rprDefaultResourcePack.getPackImage(); + } + + this.closeResourcePack(); + } + } + private static final Logger logger = LogManager.getLogger(); public final IResourcePack rprDefaultResourcePack; public final IMetadataSerializer rprMetadataSerializer; private IResourcePack resourcePackInstance; private ListenableFuture field_177322_i; private List repositoryEntriesAll = Lists.newArrayList(); + private List repositoryEntries = Lists.newArrayList(); public ResourcePackRepository(IResourcePack rprDefaultResourcePackIn, IMetadataSerializer rprMetadataSerializerIn, @@ -60,6 +151,46 @@ public class ResourcePackRepository { reconstruct(settings); } + public void downloadResourcePack(String s1, String s2, Consumer cb) { + EaglerFolderResourcePack.loadRemoteResourcePack(s1, s2, res -> { + if (res != null) { + ResourcePackRepository.this.resourcePackInstance = res; + Minecraft.getMinecraft().scheduleResourcesRefresh(); + cb.accept(true); + return; + } + cb.accept(false); + }, runnable -> { + Minecraft.getMinecraft().addScheduledTask(runnable); + }, () -> { + Minecraft.getMinecraft().loadingScreen.eaglerShow(I18n.format("resourcePack.load.loading"), + "Server resource pack"); + }); + } + + public void func_148529_f() { + if (this.resourcePackInstance != null) { + this.resourcePackInstance = null; + Minecraft.getMinecraft().scheduleResourcesRefresh(); + } + } + + public List getRepositoryEntries() { + return ImmutableList.copyOf(this.repositoryEntries); + } + + public List getRepositoryEntriesAll() { + return ImmutableList.copyOf(this.repositoryEntriesAll); + } + + /** + * + Getter for the IResourcePack instance associated with this + * ResourcePackRepository + */ + public IResourcePack getResourcePackInstance() { + return this.resourcePackInstance; + } + public void reconstruct(GameSettings settings) { this.repositoryEntriesAll.clear(); this.repositoryEntries.clear(); @@ -87,6 +218,11 @@ public class ResourcePackRepository { } + public void setRepositories(List parList) { + this.repositoryEntries.clear(); + this.repositoryEntries.addAll(parList); + } + public void updateRepositoryEntriesAll() { List list = Lists.newArrayList(); @@ -122,136 +258,4 @@ public class ResourcePackRepository { this.repositoryEntriesAll = list; } - - public List getRepositoryEntriesAll() { - return ImmutableList.copyOf(this.repositoryEntriesAll); - } - - public List getRepositoryEntries() { - return ImmutableList.copyOf(this.repositoryEntries); - } - - public void setRepositories(List parList) { - this.repositoryEntries.clear(); - this.repositoryEntries.addAll(parList); - } - - public void downloadResourcePack(String s1, String s2, Consumer cb) { - EaglerFolderResourcePack.loadRemoteResourcePack(s1, s2, res -> { - if (res != null) { - ResourcePackRepository.this.resourcePackInstance = res; - Minecraft.getMinecraft().scheduleResourcesRefresh(); - cb.accept(true); - return; - } - cb.accept(false); - }, runnable -> { - Minecraft.getMinecraft().addScheduledTask(runnable); - }, () -> { - Minecraft.getMinecraft().loadingScreen.eaglerShow(I18n.format("resourcePack.load.loading"), - "Server resource pack"); - }); - } - - /**+ - * Getter for the IResourcePack instance associated with this - * ResourcePackRepository - */ - public IResourcePack getResourcePackInstance() { - return this.resourcePackInstance; - } - - public void func_148529_f() { - if (this.resourcePackInstance != null) { - this.resourcePackInstance = null; - Minecraft.getMinecraft().scheduleResourcesRefresh(); - } - } - - public class Entry { - private EaglerFolderResourcePack reResourcePack; - private PackMetadataSection rePackMetadataSection; - private ImageData texturePackIcon; - private ResourceLocation locationTexturePackIcon; - private TextureManager iconTextureManager; - - private Entry(EaglerFolderResourcePack resourcePackFileIn) { - this.reResourcePack = resourcePackFileIn; - } - - public void updateResourcePack() throws IOException { - this.rePackMetadataSection = (PackMetadataSection) this.reResourcePack - .getPackMetadata(ResourcePackRepository.this.rprMetadataSerializer, "pack"); - - try { - this.texturePackIcon = this.reResourcePack.getPackImage(); - } catch (Throwable var2) { - logger.error("Failed to load resource pack icon for \"{}\"!", reResourcePack.resourcePackFile); - logger.error(var2); - } - - if (this.texturePackIcon == null) { - this.texturePackIcon = ResourcePackRepository.this.rprDefaultResourcePack.getPackImage(); - } - - this.closeResourcePack(); - } - - public void bindTexturePackIcon(TextureManager textureManagerIn) { - if (this.locationTexturePackIcon == null) { - this.iconTextureManager = textureManagerIn; - this.locationTexturePackIcon = textureManagerIn.getDynamicTextureLocation("texturepackicon", - new DynamicTexture(this.texturePackIcon)); - } - - textureManagerIn.bindTexture(this.locationTexturePackIcon); - } - - public void closeResourcePack() { - if (this.locationTexturePackIcon != null) { - this.iconTextureManager.deleteTexture(this.locationTexturePackIcon); - this.locationTexturePackIcon = null; - } - if (this.reResourcePack instanceof Closeable) { - IOUtils.closeQuietly((Closeable) this.reResourcePack); - } - - } - - public IResourcePack getResourcePack() { - return this.reResourcePack; - } - - public String getResourcePackName() { - return this.reResourcePack.getPackName(); - } - - public String getResourcePackEaglerDisplayName() { - return this.reResourcePack.getDisplayName(); - } - - public String getTexturePackDescription() { - return this.rePackMetadataSection == null - ? EnumChatFormatting.RED + "Invalid pack.mcmeta (or missing \'pack\' section)" - : this.rePackMetadataSection.getPackDescription().getFormattedText(); - } - - public int func_183027_f() { - return this.rePackMetadataSection.getPackFormat(); - } - - public boolean equals(Object object) { - return this == object ? true - : (object instanceof ResourcePackRepository.Entry ? this.toString().equals(object.toString()) - : false); - } - - public int hashCode() { - return this.toString().hashCode(); - } - - public String toString() { - return this.reResourcePack.resourcePackFile; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/SimpleReloadableResourceManager.java b/src/game/java/net/minecraft/client/resources/SimpleReloadableResourceManager.java index 97c2c739..e44c816d 100644 --- a/src/game/java/net/minecraft/client/resources/SimpleReloadableResourceManager.java +++ b/src/game/java/net/minecraft/client/resources/SimpleReloadableResourceManager.java @@ -18,22 +18,25 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,6 +53,47 @@ public class SimpleReloadableResourceManager implements IReloadableResourceManag this.rmMetadataSerializer = rmMetadataSerializerIn; } + private void clearResources() { + this.domainResourceManagers.clear(); + this.setResourceDomains.clear(); + } + + public List getAllResources(ResourceLocation parResourceLocation) throws IOException { + IResourceManager iresourcemanager = (IResourceManager) this.domainResourceManagers + .get(parResourceLocation.getResourceDomain()); + if (iresourcemanager != null) { + return iresourcemanager.getAllResources(parResourceLocation); + } else { + throw new FileNotFoundException(parResourceLocation.toString()); + } + } + + public IResource getResource(ResourceLocation parResourceLocation) throws IOException { + IResourceManager iresourcemanager = (IResourceManager) this.domainResourceManagers + .get(parResourceLocation.getResourceDomain()); + if (iresourcemanager != null) { + return iresourcemanager.getResource(parResourceLocation); + } else { + throw new FileNotFoundException(parResourceLocation.toString()); + } + } + + public Set getResourceDomains() { + return this.setResourceDomains; + } + + private void notifyReloadListeners() { + for (IResourceManagerReloadListener iresourcemanagerreloadlistener : this.reloadListeners) { + iresourcemanagerreloadlistener.onResourceManagerReload(this); + } + + } + + public void registerReloadListener(IResourceManagerReloadListener iresourcemanagerreloadlistener) { + this.reloadListeners.add(iresourcemanagerreloadlistener); + iresourcemanagerreloadlistener.onResourceManagerReload(this); + } + public void reloadResourcePack(IResourcePack resourcePack) { for (String s : resourcePack.getResourceDomains()) { this.setResourceDomains.add(s); @@ -65,35 +109,6 @@ public class SimpleReloadableResourceManager implements IReloadableResourceManag } - public Set getResourceDomains() { - return this.setResourceDomains; - } - - public IResource getResource(ResourceLocation parResourceLocation) throws IOException { - IResourceManager iresourcemanager = (IResourceManager) this.domainResourceManagers - .get(parResourceLocation.getResourceDomain()); - if (iresourcemanager != null) { - return iresourcemanager.getResource(parResourceLocation); - } else { - throw new FileNotFoundException(parResourceLocation.toString()); - } - } - - public List getAllResources(ResourceLocation parResourceLocation) throws IOException { - IResourceManager iresourcemanager = (IResourceManager) this.domainResourceManagers - .get(parResourceLocation.getResourceDomain()); - if (iresourcemanager != null) { - return iresourcemanager.getAllResources(parResourceLocation); - } else { - throw new FileNotFoundException(parResourceLocation.toString()); - } - } - - private void clearResources() { - this.domainResourceManagers.clear(); - this.setResourceDomains.clear(); - } - public void reloadResources(List list) { this.clearResources(); logger.info("Reloading ResourceManager: " @@ -109,16 +124,4 @@ public class SimpleReloadableResourceManager implements IReloadableResourceManag this.notifyReloadListeners(); } - - public void registerReloadListener(IResourceManagerReloadListener iresourcemanagerreloadlistener) { - this.reloadListeners.add(iresourcemanagerreloadlistener); - iresourcemanagerreloadlistener.onResourceManagerReload(this); - } - - private void notifyReloadListeners() { - for (IResourceManagerReloadListener iresourcemanagerreloadlistener : this.reloadListeners) { - iresourcemanagerreloadlistener.onResourceManagerReload(this); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/SimpleResource.java b/src/game/java/net/minecraft/client/resources/SimpleResource.java index 36f18e29..e19f039d 100644 --- a/src/game/java/net/minecraft/client/resources/SimpleResource.java +++ b/src/game/java/net/minecraft/client/resources/SimpleResource.java @@ -15,22 +15,25 @@ import net.minecraft.client.resources.data.IMetadataSection; import net.minecraft.client.resources.data.IMetadataSerializer; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,48 +58,6 @@ public class SimpleResource implements IResource { this.srMetadataSerializer = srMetadataSerializerIn; } - public ResourceLocation getResourceLocation() { - return this.srResourceLocation; - } - - public InputStream getInputStream() { - return this.resourceInputStream; - } - - public boolean hasMetadata() { - return this.mcmetaInputStream != null; - } - - public T getMetadata(String s) { - if (!this.hasMetadata()) { - return (T) null; - } else { - if (this.mcmetaJson == null && !this.mcmetaJsonChecked) { - this.mcmetaJsonChecked = true; - - try { - this.mcmetaJson = new JSONObject( - IOUtils.inputStreamToString(this.mcmetaInputStream, StandardCharsets.UTF_8)); - } catch (IOException e) { - throw new JSONException(e); - } finally { - IOUtils.closeQuietly(this.mcmetaInputStream); - } - } - - IMetadataSection imetadatasection = (IMetadataSection) this.mapMetadataSections.get(s); - if (imetadatasection == null) { - imetadatasection = this.srMetadataSerializer.parseMetadataSection(s, this.mcmetaJson); - } - - return (T) imetadatasection; - } - } - - public String getResourcePackName() { - return this.resourcePackName; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -124,9 +85,51 @@ public class SimpleResource implements IResource { } } + public InputStream getInputStream() { + return this.resourceInputStream; + } + + public T getMetadata(String s) { + if (!this.hasMetadata()) { + return (T) null; + } else { + if (this.mcmetaJson == null && !this.mcmetaJsonChecked) { + this.mcmetaJsonChecked = true; + + try { + this.mcmetaJson = new JSONObject( + IOUtils.inputStreamToString(this.mcmetaInputStream, StandardCharsets.UTF_8)); + } catch (IOException e) { + throw new JSONException(e); + } finally { + IOUtils.closeQuietly(this.mcmetaInputStream); + } + } + + IMetadataSection imetadatasection = (IMetadataSection) this.mapMetadataSections.get(s); + if (imetadatasection == null) { + imetadatasection = this.srMetadataSerializer.parseMetadataSection(s, this.mcmetaJson); + } + + return (T) imetadatasection; + } + } + + public ResourceLocation getResourceLocation() { + return this.srResourceLocation; + } + + public String getResourcePackName() { + return this.resourcePackName; + } + public int hashCode() { int i = this.resourcePackName != null ? this.resourcePackName.hashCode() : 0; i = 31 * i + (this.srResourceLocation != null ? this.srResourceLocation.hashCode() : 0); return i; } + + public boolean hasMetadata() { + return this.mcmetaInputStream != null; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/AnimationFrame.java b/src/game/java/net/minecraft/client/resources/data/AnimationFrame.java index f02fe104..2a35a41b 100644 --- a/src/game/java/net/minecraft/client/resources/data/AnimationFrame.java +++ b/src/game/java/net/minecraft/client/resources/data/AnimationFrame.java @@ -1,21 +1,24 @@ package net.minecraft.client.resources.data; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,15 +36,15 @@ public class AnimationFrame { this.frameTime = parInt2; } - public boolean hasNoTime() { - return this.frameTime == -1; + public int getFrameIndex() { + return this.frameIndex; } public int getFrameTime() { return this.frameTime; } - public int getFrameIndex() { - return this.frameIndex; + public boolean hasNoTime() { + return this.frameTime == -1; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSection.java b/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSection.java index 8c674a59..50cadc8f 100644 --- a/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSection.java +++ b/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSection.java @@ -6,22 +6,25 @@ import java.util.Set; import com.google.common.collect.Sets; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,37 +45,20 @@ public class AnimationMetadataSection implements IMetadataSection { this.interpolate = parFlag; } - public int getFrameHeight() { - return this.frameHeight; - } - - public int getFrameWidth() { - return this.frameWidth; - } - - public int getFrameCount() { - return this.animationFrames.size(); - } - - public int getFrameTime() { - return this.frameTime; - } - - public boolean isInterpolate() { - return this.interpolate; + public boolean frameHasTime(int parInt1) { + return !((AnimationFrame) this.animationFrames.get(parInt1)).hasNoTime(); } private AnimationFrame getAnimationFrame(int parInt1) { return (AnimationFrame) this.animationFrames.get(parInt1); } - public int getFrameTimeSingle(int parInt1) { - AnimationFrame animationframe = this.getAnimationFrame(parInt1); - return animationframe.hasNoTime() ? this.frameTime : animationframe.getFrameTime(); + public int getFrameCount() { + return this.animationFrames.size(); } - public boolean frameHasTime(int parInt1) { - return !((AnimationFrame) this.animationFrames.get(parInt1)).hasNoTime(); + public int getFrameHeight() { + return this.frameHeight; } public int getFrameIndex(int parInt1) { @@ -88,4 +74,21 @@ public class AnimationMetadataSection implements IMetadataSection { return hashset; } + + public int getFrameTime() { + return this.frameTime; + } + + public int getFrameTimeSingle(int parInt1) { + AnimationFrame animationframe = this.getAnimationFrame(parInt1); + return animationframe.hasNoTime() ? this.frameTime : animationframe.getFrameTime(); + } + + public int getFrameWidth() { + return this.frameWidth; + } + + public boolean isInterpolate() { + return this.interpolate; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSectionSerializer.java index 60ac3d3f..f4c59bef 100644 --- a/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/AnimationMetadataSectionSerializer.java @@ -11,22 +11,25 @@ import com.google.common.collect.Lists; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeSerializer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -70,6 +73,13 @@ public class AnimationMetadataSectionSerializer extends BaseMetadataSectionSeria return new AnimationMetadataSection(arraylist, k, l, i, flag); } + /** + * + The name of this section type as it appears in JSON. + */ + public String getSectionName() { + return "animation"; + } + private AnimationFrame parseAnimationFrame(int parInt1, Object parJsonElement) { if (parJsonElement instanceof Number) { return new AnimationFrame(((Number) parJsonElement).intValue()); @@ -118,11 +128,4 @@ public class AnimationMetadataSectionSerializer extends BaseMetadataSectionSeria return jsonobject; } - - /**+ - * The name of this section type as it appears in JSON. - */ - public String getSectionName() { - return "animation"; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/BaseMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/BaseMetadataSectionSerializer.java index 1969b40e..4ec3c0d4 100644 --- a/src/game/java/net/minecraft/client/resources/data/BaseMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/BaseMetadataSectionSerializer.java @@ -1,21 +1,24 @@ package net.minecraft.client.resources.data; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/data/FontMetadataSection.java b/src/game/java/net/minecraft/client/resources/data/FontMetadataSection.java index d9b5f513..d6f23c17 100644 --- a/src/game/java/net/minecraft/client/resources/data/FontMetadataSection.java +++ b/src/game/java/net/minecraft/client/resources/data/FontMetadataSection.java @@ -1,21 +1,24 @@ package net.minecraft.client.resources.data; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/data/FontMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/FontMetadataSectionSerializer.java index c4cc56b4..907b57c4 100644 --- a/src/game/java/net/minecraft/client/resources/data/FontMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/FontMetadataSectionSerializer.java @@ -4,22 +4,25 @@ import org.apache.commons.lang3.Validate; import org.json.JSONException; import org.json.JSONObject; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -77,8 +80,8 @@ public class FontMetadataSectionSerializer extends BaseMetadataSectionSerializer return new FontMetadataSection(afloat, afloat2, afloat1); } - /**+ - * The name of this section type as it appears in JSON. + /** + * + The name of this section type as it appears in JSON. */ public String getSectionName() { return "font"; diff --git a/src/game/java/net/minecraft/client/resources/data/IMetadataSection.java b/src/game/java/net/minecraft/client/resources/data/IMetadataSection.java index 0e058a92..83bb2b7e 100644 --- a/src/game/java/net/minecraft/client/resources/data/IMetadataSection.java +++ b/src/game/java/net/minecraft/client/resources/data/IMetadataSection.java @@ -1,21 +1,24 @@ package net.minecraft.client.resources.data; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/data/IMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/IMetadataSectionSerializer.java index e410fe5e..1538d4db 100644 --- a/src/game/java/net/minecraft/client/resources/data/IMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/IMetadataSectionSerializer.java @@ -4,29 +4,32 @@ import org.json.JSONObject; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeDeserializer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IMetadataSectionSerializer extends JSONTypeDeserializer { - /**+ - * The name of this section type as it appears in JSON. + /** + * + The name of this section type as it appears in JSON. */ String getSectionName(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/IMetadataSerializer.java b/src/game/java/net/minecraft/client/resources/data/IMetadataSerializer.java index b906bfdd..972d2ee0 100644 --- a/src/game/java/net/minecraft/client/resources/data/IMetadataSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/IMetadataSerializer.java @@ -6,35 +6,42 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.minecraft.util.IRegistry; import net.minecraft.util.RegistrySimple; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IMetadataSerializer { - private final IRegistry> metadataSectionSerializerRegistry = new RegistrySimple(); + class Registration { + final IMetadataSectionSerializer field_110502_a; + final Class field_110500_b; - public void registerMetadataSectionType( - IMetadataSectionSerializer parIMetadataSectionSerializer, Class parClass1) { - this.metadataSectionSerializerRegistry.putObject(parIMetadataSectionSerializer.getSectionName(), - new IMetadataSerializer.Registration(parIMetadataSectionSerializer, parClass1)); + private Registration(IMetadataSectionSerializer parIMetadataSectionSerializer, Class parClass1) { + this.field_110502_a = parIMetadataSectionSerializer; + this.field_110500_b = parClass1; + } } + private final IRegistry> metadataSectionSerializerRegistry = new RegistrySimple(); + public T parseMetadataSection(String parString1, JSONObject parJsonObject) { if (parString1 == null) { throw new IllegalArgumentException("Metadata section name cannot be null"); @@ -55,13 +62,9 @@ public class IMetadataSerializer { } } - class Registration { - final IMetadataSectionSerializer field_110502_a; - final Class field_110500_b; - - private Registration(IMetadataSectionSerializer parIMetadataSectionSerializer, Class parClass1) { - this.field_110502_a = parIMetadataSectionSerializer; - this.field_110500_b = parClass1; - } + public void registerMetadataSectionType( + IMetadataSectionSerializer parIMetadataSectionSerializer, Class parClass1) { + this.metadataSectionSerializerRegistry.putObject(parIMetadataSectionSerializer.getSectionName(), + new IMetadataSerializer.Registration(parIMetadataSectionSerializer, parClass1)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSection.java b/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSection.java index bf34f53b..c367c02c 100644 --- a/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSection.java +++ b/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSection.java @@ -4,22 +4,25 @@ import java.util.Collection; import net.minecraft.client.resources.Language; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSectionSerializer.java index e1471f2d..fdd222db 100644 --- a/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/LanguageMetadataSectionSerializer.java @@ -9,22 +9,25 @@ import com.google.common.collect.Sets; import net.minecraft.client.resources.Language; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,8 +57,8 @@ public class LanguageMetadataSectionSerializer extends BaseMetadataSectionSerial return new LanguageMetadataSection(hashset); } - /**+ - * The name of this section type as it appears in JSON. + /** + * + The name of this section type as it appears in JSON. */ public String getSectionName() { return "language"; diff --git a/src/game/java/net/minecraft/client/resources/data/PackMetadataSection.java b/src/game/java/net/minecraft/client/resources/data/PackMetadataSection.java index 30086fa2..a6f9e6f3 100644 --- a/src/game/java/net/minecraft/client/resources/data/PackMetadataSection.java +++ b/src/game/java/net/minecraft/client/resources/data/PackMetadataSection.java @@ -2,22 +2,25 @@ package net.minecraft.client.resources.data; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/client/resources/data/PackMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/PackMetadataSectionSerializer.java index bcd1c2ab..aab1e811 100644 --- a/src/game/java/net/minecraft/client/resources/data/PackMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/PackMetadataSectionSerializer.java @@ -3,26 +3,29 @@ package net.minecraft.client.resources.data; import org.json.JSONException; import org.json.JSONObject; -import net.lax1dude.eaglercraft.v1_8.json.JSONTypeSerializer; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; +import net.lax1dude.eaglercraft.v1_8.json.JSONTypeSerializer; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,6 +43,13 @@ public class PackMetadataSectionSerializer extends BaseMetadataSectionSerializer } } + /** + * + The name of this section type as it appears in JSON. + */ + public String getSectionName() { + return "pack"; + } + public JSONObject serialize(PackMetadataSection packmetadatasection) { JSONObject jsonobject = new JSONObject(); jsonobject.put("pack_format", packmetadatasection.getPackFormat()); @@ -47,11 +57,4 @@ public class PackMetadataSectionSerializer extends BaseMetadataSectionSerializer (JSONObject) JSONTypeProvider.serialize(packmetadatasection.getPackDescription())); return jsonobject; } - - /**+ - * The name of this section type as it appears in JSON. - */ - public String getSectionName() { - return "pack"; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/TextureMetadataSection.java b/src/game/java/net/minecraft/client/resources/data/TextureMetadataSection.java index 4dba70f0..fd1e6b6c 100644 --- a/src/game/java/net/minecraft/client/resources/data/TextureMetadataSection.java +++ b/src/game/java/net/minecraft/client/resources/data/TextureMetadataSection.java @@ -3,22 +3,25 @@ package net.minecraft.client.resources.data; import java.util.Collections; import java.util.List; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,6 +37,10 @@ public class TextureMetadataSection implements IMetadataSection { this.listMipmaps = parList; } + public List getListMipmaps() { + return Collections.unmodifiableList(this.listMipmaps); + } + public boolean getTextureBlur() { return this.textureBlur; } @@ -41,8 +48,4 @@ public class TextureMetadataSection implements IMetadataSection { public boolean getTextureClamp() { return this.textureClamp; } - - public List getListMipmaps() { - return Collections.unmodifiableList(this.listMipmaps); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/data/TextureMetadataSectionSerializer.java b/src/game/java/net/minecraft/client/resources/data/TextureMetadataSectionSerializer.java index fafb960b..bf2d372b 100644 --- a/src/game/java/net/minecraft/client/resources/data/TextureMetadataSectionSerializer.java +++ b/src/game/java/net/minecraft/client/resources/data/TextureMetadataSectionSerializer.java @@ -8,22 +8,25 @@ import org.json.JSONObject; import com.google.common.collect.Lists; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,8 +64,8 @@ public class TextureMetadataSectionSerializer extends BaseMetadataSectionSeriali return new TextureMetadataSection(flag, flag1, arraylist); } - /**+ - * The name of this section type as it appears in JSON. + /** + * + The name of this section type as it appears in JSON. */ public String getSectionName() { return "texture"; diff --git a/src/game/java/net/minecraft/client/resources/model/BuiltInModel.java b/src/game/java/net/minecraft/client/resources/model/BuiltInModel.java index d57e3feb..c60b30da 100644 --- a/src/game/java/net/minecraft/client/resources/model/BuiltInModel.java +++ b/src/game/java/net/minecraft/client/resources/model/BuiltInModel.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,23 +45,23 @@ public class BuiltInModel implements IBakedModel { return null; } - public boolean isAmbientOcclusion() { - return false; - } - - public boolean isGui3d() { - return true; - } - - public boolean isBuiltInRenderer() { - return true; + public ItemCameraTransforms getItemCameraTransforms() { + return this.cameraTransforms; } public EaglerTextureAtlasSprite getParticleTexture() { return null; } - public ItemCameraTransforms getItemCameraTransforms() { - return this.cameraTransforms; + public boolean isAmbientOcclusion() { + return false; + } + + public boolean isBuiltInRenderer() { + return true; + } + + public boolean isGui3d() { + return true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/model/IBakedModel.java b/src/game/java/net/minecraft/client/resources/model/IBakedModel.java index 11ab9dd3..58bb2eac 100644 --- a/src/game/java/net/minecraft/client/resources/model/IBakedModel.java +++ b/src/game/java/net/minecraft/client/resources/model/IBakedModel.java @@ -7,22 +7,25 @@ import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,13 +35,13 @@ public interface IBakedModel { List getGeneralQuads(); - boolean isAmbientOcclusion(); - - boolean isGui3d(); - - boolean isBuiltInRenderer(); + ItemCameraTransforms getItemCameraTransforms(); EaglerTextureAtlasSprite getParticleTexture(); - ItemCameraTransforms getItemCameraTransforms(); + boolean isAmbientOcclusion(); + + boolean isBuiltInRenderer(); + + boolean isGui3d(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/model/ModelBakery.java b/src/game/java/net/minecraft/client/resources/model/ModelBakery.java index 7e50b530..f875b54d 100644 --- a/src/game/java/net/minecraft/client/resources/model/ModelBakery.java +++ b/src/game/java/net/minecraft/client/resources/model/ModelBakery.java @@ -48,22 +48,25 @@ import net.minecraft.util.IRegistry; import net.minecraft.util.RegistrySimple; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -86,6 +89,22 @@ public class ModelBakery { "missing"); private static final Map BUILT_IN_MODELS = Maps.newHashMap(); private static final Joiner JOINER = Joiner.on(" -> "); + private static final ModelBlock MODEL_GENERATED = ModelBlock.deserialize( + "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); + private static final ModelBlock MODEL_COMPASS = ModelBlock.deserialize( + "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); + private static final ModelBlock MODEL_CLOCK = ModelBlock.deserialize( + "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); + private static final ModelBlock MODEL_ENTITY = ModelBlock.deserialize( + "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); + static { + BUILT_IN_MODELS.put("missing", + "{ \"textures\": { \"particle\": \"missingno\", \"missingno\": \"missingno\"}, \"elements\": [ { \"from\": [ 0, 0, 0 ], \"to\": [ 16, 16, 16 ], \"faces\": { \"down\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"down\", \"texture\": \"#missingno\" }, \"up\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"up\", \"texture\": \"#missingno\" }, \"north\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"north\", \"texture\": \"#missingno\" }, \"south\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"south\", \"texture\": \"#missingno\" }, \"west\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"west\", \"texture\": \"#missingno\" }, \"east\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"east\", \"texture\": \"#missingno\" } }}]}"); + MODEL_GENERATED.name = "generation marker"; + MODEL_COMPASS.name = "compass generation marker"; + MODEL_CLOCK.name = "class generation marker"; + MODEL_ENTITY.name = "block entity marker"; + } private final IResourceManager resourceManager; private final Map sprites = Maps.newHashMap(); private final Map models = Maps.newLinkedHashMap(); @@ -95,16 +114,9 @@ public class ModelBakery { private final FaceBakery faceBakery = new FaceBakery(); private final ItemModelGenerator itemModelGenerator = new ItemModelGenerator(); private RegistrySimple bakedRegistry = new RegistrySimple(); - private static final ModelBlock MODEL_GENERATED = ModelBlock.deserialize( - "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); - private static final ModelBlock MODEL_COMPASS = ModelBlock.deserialize( - "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); - private static final ModelBlock MODEL_CLOCK = ModelBlock.deserialize( - "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); - private static final ModelBlock MODEL_ENTITY = ModelBlock.deserialize( - "{\"elements\":[{ \"from\": [0, 0, 0], \"to\": [16, 16, 16], \"faces\": { \"down\": {\"uv\": [0, 0, 16, 16], \"texture\":\"\"} }}]}"); private Map itemLocations = Maps.newLinkedHashMap(); private final Map blockDefinitions = Maps.newHashMap(); + private Map> variantNames = Maps.newIdentityHashMap(); public ModelBakery(IResourceManager parIResourceManager, TextureMap parTextureMap, @@ -114,54 +126,170 @@ public class ModelBakery { this.blockModelShapes = parBlockModelShapes; } - public IRegistry setupModelRegistry() { - this.loadVariantItemModels(); - this.loadModelsCheck(); - this.loadSprites(); - this.bakeItemModels(); - this.bakeBlockModels(); - return this.bakedRegistry; - } + private void bakeBlockModels() { + boolean deferred = Minecraft.getMinecraft().gameSettings.shaders; + for (ModelResourceLocation modelresourcelocation : this.variants.keySet()) { + WeightedBakedModel.Builder weightedbakedmodel$builder = new WeightedBakedModel.Builder(); + int i = 0; - private void loadVariantItemModels() { - this.loadVariants(this.blockModelShapes.getBlockStateMapper().putAllStateModelLocations().values()); - this.variants.put(MODEL_MISSING, - new ModelBlockDefinition.Variants(MODEL_MISSING.getVariant(), - Lists.newArrayList(new ModelBlockDefinition.Variant[] { - new ModelBlockDefinition.Variant(new ResourceLocation(MODEL_MISSING.getResourcePath()), - ModelRotation.X0_Y0, false, 1) }))); - ResourceLocation resourcelocation = new ResourceLocation("item_frame"); - ModelBlockDefinition modelblockdefinition = this.getModelBlockDefinition(resourcelocation); - this.registerVariant(modelblockdefinition, new ModelResourceLocation(resourcelocation, "normal")); - this.registerVariant(modelblockdefinition, new ModelResourceLocation(resourcelocation, "map")); - this.loadVariantModels(); - this.loadItemModels(); - } - - private void loadVariants(Collection parCollection) { - for (ModelResourceLocation modelresourcelocation : parCollection) { - try { - ModelBlockDefinition modelblockdefinition = this.getModelBlockDefinition(modelresourcelocation); - - try { - this.registerVariant(modelblockdefinition, modelresourcelocation); - } catch (Exception var6) { - LOGGER.warn("Unable to load variant: " + modelresourcelocation.getVariant() + " from " - + modelresourcelocation); - LOGGER.warn(var6); + for (ModelBlockDefinition.Variant modelblockdefinition$variant : ((ModelBlockDefinition.Variants) this.variants + .get(modelresourcelocation)).getVariants()) { + ModelBlock modelblock = (ModelBlock) this.models.get(modelblockdefinition$variant.getModelLocation()); + if (modelblock != null && modelblock.isResolved()) { + ++i; + if (deferred) { + ModelBlock currentBlockModel = modelblock; + ResourceLocation currentResourceLocation = modelblockdefinition$variant.getModelLocation(); + Integer blockId = null; + do { + blockId = BlockVertexIDs.modelToID.get(currentResourceLocation.toString()); + if (blockId != null) { + break; + } + currentResourceLocation = currentBlockModel.getParentLocation(); + currentBlockModel = models.get(currentResourceLocation); + } while (currentBlockModel != null); + if (blockId != null) { + VertexMarkerState.markId = blockId.intValue(); + try { + weightedbakedmodel$builder.add( + this.bakeModel(modelblock, modelblockdefinition$variant.getRotation(), + modelblockdefinition$variant.isUvLocked()), + modelblockdefinition$variant.getWeight()); + } finally { + VertexMarkerState.markId = 0; + } + continue; + } + } + weightedbakedmodel$builder.add( + this.bakeModel(modelblock, modelblockdefinition$variant.getRotation(), + modelblockdefinition$variant.isUvLocked()), + modelblockdefinition$variant.getWeight()); + } else { + LOGGER.warn("Missing model for: " + modelresourcelocation); } - } catch (Exception exception) { - LOGGER.warn("Unable to load definition " + modelresourcelocation); - LOGGER.warn(exception); + } + + if (i == 0) { + LOGGER.warn("No weighted models for: " + modelresourcelocation); + } else if (i == 1) { + this.bakedRegistry.putObject(modelresourcelocation, weightedbakedmodel$builder.first()); + } else { + this.bakedRegistry.putObject(modelresourcelocation, weightedbakedmodel$builder.build()); + } + } + + for (Entry entry : this.itemLocations.entrySet()) { + ResourceLocation resourcelocation = (ResourceLocation) entry.getValue(); + ModelResourceLocation modelresourcelocation1 = new ModelResourceLocation((String) entry.getKey(), + "inventory"); + ModelBlock modelblock1 = (ModelBlock) this.models.get(resourcelocation); + if (modelblock1 != null && modelblock1.isResolved()) { + if (this.isCustomRenderer(modelblock1)) { + this.bakedRegistry.putObject(modelresourcelocation1, new BuiltInModel(modelblock1.func_181682_g())); + } else { + this.bakedRegistry.putObject(modelresourcelocation1, + this.bakeModel(modelblock1, ModelRotation.X0_Y0, false)); + } + } else { + LOGGER.warn("Missing model for: " + resourcelocation); } } } - private void registerVariant(ModelBlockDefinition parModelBlockDefinition, - ModelResourceLocation parModelResourceLocation) { - this.variants.put(parModelResourceLocation, - parModelBlockDefinition.getVariants(parModelResourceLocation.getVariant())); + private void bakeItemModels() { + for (ResourceLocation resourcelocation : this.itemLocations.values()) { + ModelBlock modelblock = (ModelBlock) this.models.get(resourcelocation); + if (this.hasItemModel(modelblock)) { + ModelBlock modelblock1 = this.makeItemModel(modelblock); + if (modelblock1 != null) { + modelblock1.name = resourcelocation.toString(); + } + + this.models.put(resourcelocation, modelblock1); + } else if (this.isCustomRenderer(modelblock)) { + this.models.put(resourcelocation, modelblock); + } + } + + for (EaglerTextureAtlasSprite textureatlassprite : this.sprites.values()) { + if (!textureatlassprite.hasAnimationMetadata()) { + textureatlassprite.clearFramesTextureData(); + } + } + + } + + private IBakedModel bakeModel(ModelBlock modelBlockIn, ModelRotation modelRotationIn, boolean uvLocked) { + EaglerTextureAtlasSprite textureatlassprite = (EaglerTextureAtlasSprite) this.sprites + .get(new ResourceLocation(modelBlockIn.resolveTextureName("particle"))); + SimpleBakedModel.Builder simplebakedmodel$builder = (new SimpleBakedModel.Builder(modelBlockIn)) + .setTexture(textureatlassprite); + + for (BlockPart blockpart : modelBlockIn.getElements()) { + for (EnumFacing enumfacing : blockpart.mapFaces.keySet()) { + BlockPartFace blockpartface = (BlockPartFace) blockpart.mapFaces.get(enumfacing); + EaglerTextureAtlasSprite textureatlassprite1 = (EaglerTextureAtlasSprite) this.sprites + .get(new ResourceLocation(modelBlockIn.resolveTextureName(blockpartface.texture))); + if (blockpartface.cullFace == null) { + simplebakedmodel$builder.addGeneralQuad(this.makeBakedQuad(blockpart, blockpartface, + textureatlassprite1, enumfacing, modelRotationIn, uvLocked)); + } else { + simplebakedmodel$builder.addFaceQuad(modelRotationIn.rotateFace(blockpartface.cullFace), + this.makeBakedQuad(blockpart, blockpartface, textureatlassprite1, enumfacing, + modelRotationIn, uvLocked)); + } + } + } + + return simplebakedmodel$builder.makeBakedModel(); + } + + private ResourceLocation getBlockStateLocation(ResourceLocation parResourceLocation) { + return new ResourceLocation(parResourceLocation.getResourceDomain(), + "blockstates/" + parResourceLocation.getResourcePath() + ".json"); + } + + private ResourceLocation getItemLocation(String parString1) { + ResourceLocation resourcelocation = new ResourceLocation(parString1); + return new ResourceLocation(resourcelocation.getResourceDomain(), "item/" + resourcelocation.getResourcePath()); + } + + private Set getItemsTextureLocations() { + HashSet hashset = Sets.newHashSet(); + + for (ResourceLocation resourcelocation : this.itemLocations.values()) { + ModelBlock modelblock = (ModelBlock) this.models.get(resourcelocation); + if (modelblock != null) { + hashset.add(new ResourceLocation(modelblock.resolveTextureName("particle"))); + if (this.hasItemModel(modelblock)) { + for (String s : ItemModelGenerator.LAYERS) { + ResourceLocation resourcelocation2 = new ResourceLocation(modelblock.resolveTextureName(s)); + if (modelblock.getRootModel() == MODEL_COMPASS + && !TextureMap.LOCATION_MISSING_TEXTURE.equals(resourcelocation2)) { + EaglerTextureAtlasSprite.setLocationNameCompass(resourcelocation2.toString()); + } else if (modelblock.getRootModel() == MODEL_CLOCK + && !TextureMap.LOCATION_MISSING_TEXTURE.equals(resourcelocation2)) { + EaglerTextureAtlasSprite.setLocationNameClock(resourcelocation2.toString()); + } + + hashset.add(resourcelocation2); + } + } else if (!this.isCustomRenderer(modelblock)) { + for (BlockPart blockpart : modelblock.getElements()) { + for (BlockPartFace blockpartface : blockpart.mapFaces.values()) { + ResourceLocation resourcelocation1 = new ResourceLocation( + modelblock.resolveTextureName(blockpartface.texture)); + hashset.add(resourcelocation1); + } + } + } + } + } + + return hashset; } private ModelBlockDefinition getModelBlockDefinition(ResourceLocation parResourceLocation) { @@ -199,23 +327,119 @@ public class ModelBakery { return modelblockdefinition; } - private ResourceLocation getBlockStateLocation(ResourceLocation parResourceLocation) { + private ResourceLocation getModelLocation(ResourceLocation parResourceLocation) { return new ResourceLocation(parResourceLocation.getResourceDomain(), - "blockstates/" + parResourceLocation.getResourcePath() + ".json"); + "models/" + parResourceLocation.getResourcePath() + ".json"); } - private void loadVariantModels() { - for (ModelResourceLocation modelresourcelocation : this.variants.keySet()) { - for (ModelBlockDefinition.Variant modelblockdefinition$variant : ((ModelBlockDefinition.Variants) this.variants - .get(modelresourcelocation)).getVariants()) { - ResourceLocation resourcelocation = modelblockdefinition$variant.getModelLocation(); + private ResourceLocation getParentLocation(ResourceLocation parResourceLocation) { + for (Entry entry : this.models.entrySet()) { + ModelBlock modelblock = (ModelBlock) entry.getValue(); + if (modelblock != null && parResourceLocation.equals(modelblock.getParentLocation())) { + return (ResourceLocation) entry.getKey(); + } + } + + return null; + } + + private List getParentPath(ResourceLocation parResourceLocation) { + ArrayList arraylist = Lists.newArrayList(new ResourceLocation[] { parResourceLocation }); + ResourceLocation resourcelocation = parResourceLocation; + + while ((resourcelocation = this.getParentLocation(resourcelocation)) != null) { + arraylist.add(0, resourcelocation); + } + + return arraylist; + } + + private Set getTextureLocations(ModelBlock parModelBlock) { + HashSet hashset = Sets.newHashSet(); + + for (BlockPart blockpart : parModelBlock.getElements()) { + for (BlockPartFace blockpartface : blockpart.mapFaces.values()) { + ResourceLocation resourcelocation = new ResourceLocation( + parModelBlock.resolveTextureName(blockpartface.texture)); + hashset.add(resourcelocation); + } + } + + hashset.add(new ResourceLocation(parModelBlock.resolveTextureName("particle"))); + return hashset; + } + + private List getVariantNames(Item parItem) { + List list = (List) this.variantNames.get(parItem); + if (list == null) { + list = Collections + .singletonList(((ResourceLocation) Item.itemRegistry.getNameForObject(parItem)).toString()); + } + + return list; + } + + private Set getVariantsTextureLocations() { + HashSet hashset = Sets.newHashSet(); + ArrayList arraylist = Lists.newArrayList(this.variants.keySet()); + Collections.sort(arraylist, new Comparator() { + public int compare(ModelResourceLocation modelresourcelocation1, + ModelResourceLocation modelresourcelocation2) { + return modelresourcelocation1.toString().compareTo(modelresourcelocation2.toString()); + } + }); + + for (ModelResourceLocation modelresourcelocation : (List) arraylist) { + ModelBlockDefinition.Variants modelblockdefinition$variants = (ModelBlockDefinition.Variants) this.variants + .get(modelresourcelocation); + + for (ModelBlockDefinition.Variant modelblockdefinition$variant : modelblockdefinition$variants + .getVariants()) { + ModelBlock modelblock = (ModelBlock) this.models.get(modelblockdefinition$variant.getModelLocation()); + if (modelblock == null) { + LOGGER.warn("Missing model for: " + modelresourcelocation); + } else { + hashset.addAll(this.getTextureLocations(modelblock)); + } + } + } + + hashset.addAll(LOCATIONS_BUILTIN_TEXTURES); + return hashset; + } + + private boolean hasItemModel(ModelBlock parModelBlock) { + if (parModelBlock == null) { + return false; + } else { + ModelBlock modelblock = parModelBlock.getRootModel(); + return modelblock == MODEL_GENERATED || modelblock == MODEL_COMPASS || modelblock == MODEL_CLOCK; + } + } + + private boolean isCustomRenderer(ModelBlock parModelBlock) { + if (parModelBlock == null) { + return false; + } else { + ModelBlock modelblock = parModelBlock.getRootModel(); + return modelblock == MODEL_ENTITY; + } + } + + private void loadItemModels() { + this.registerVariantNames(); + + for (Item item : Item.itemRegistry) { + for (String s : this.getVariantNames(item)) { + ResourceLocation resourcelocation = this.getItemLocation(s); + this.itemLocations.put(s, resourcelocation); if (this.models.get(resourcelocation) == null) { try { ModelBlock modelblock = this.loadModel(resourcelocation); this.models.put(resourcelocation, modelblock); } catch (Exception exception) { - LOGGER.warn("Unable to load block model: \'" + resourcelocation + "\' for variant: \'" - + modelresourcelocation + "\'"); + LOGGER.warn("Unable to load item model: \'" + resourcelocation + "\' for item: \'" + + Item.itemRegistry.getNameForObject(item) + "\'"); LOGGER.warn(exception); } } @@ -256,25 +480,97 @@ public class ModelBakery { } } - private ResourceLocation getModelLocation(ResourceLocation parResourceLocation) { - return new ResourceLocation(parResourceLocation.getResourceDomain(), - "models/" + parResourceLocation.getResourcePath() + ".json"); + private void loadModels() { + List arraydeque = Lists.newLinkedList(); + HashSet hashset = Sets.newHashSet(); + + for (ResourceLocation resourcelocation : this.models.keySet()) { + hashset.add(resourcelocation); + ResourceLocation resourcelocation1 = ((ModelBlock) this.models.get(resourcelocation)).getParentLocation(); + if (resourcelocation1 != null) { + arraydeque.add(resourcelocation1); + } + } + + while (!arraydeque.isEmpty()) { + ResourceLocation resourcelocation2 = (ResourceLocation) arraydeque.remove(0); + + try { + if (this.models.get(resourcelocation2) != null) { + continue; + } + + ModelBlock modelblock = this.loadModel(resourcelocation2); + this.models.put(resourcelocation2, modelblock); + ResourceLocation resourcelocation3 = modelblock.getParentLocation(); + if (resourcelocation3 != null && !hashset.contains(resourcelocation3)) { + arraydeque.add(resourcelocation3); + } + } catch (Exception exception) { + LOGGER.warn("In parent chain: " + JOINER.join(this.getParentPath(resourcelocation2)) + + "; unable to load model: \'" + resourcelocation2 + "\'"); + LOGGER.warn(exception); + } + + hashset.add(resourcelocation2); + } + } - private void loadItemModels() { - this.registerVariantNames(); + private void loadModelsCheck() { + this.loadModels(); - for (Item item : Item.itemRegistry) { - for (String s : this.getVariantNames(item)) { - ResourceLocation resourcelocation = this.getItemLocation(s); - this.itemLocations.put(s, resourcelocation); + for (ModelBlock modelblock : this.models.values()) { + modelblock.getParentFromMap(this.models); + } + + ModelBlock.checkModelHierarchy(this.models); + } + + private void loadSprites() { + final Set set = this.getVariantsTextureLocations(); + set.addAll(this.getItemsTextureLocations()); + set.remove(TextureMap.LOCATION_MISSING_TEXTURE); + IIconCreator iiconcreator = new IIconCreator() { + public void registerSprites(TextureMap texturemap) { + for (ResourceLocation resourcelocation : (Set) set) { + EaglerTextureAtlasSprite textureatlassprite = texturemap.registerSprite(resourcelocation); + ModelBakery.this.sprites.put(resourcelocation, textureatlassprite); + } + + } + }; + this.textureMap.loadSprites(this.resourceManager, iiconcreator); + this.sprites.put(new ResourceLocation("missingno"), this.textureMap.getMissingSprite()); + } + + private void loadVariantItemModels() { + this.loadVariants(this.blockModelShapes.getBlockStateMapper().putAllStateModelLocations().values()); + this.variants.put(MODEL_MISSING, + new ModelBlockDefinition.Variants(MODEL_MISSING.getVariant(), + Lists.newArrayList(new ModelBlockDefinition.Variant[] { + new ModelBlockDefinition.Variant(new ResourceLocation(MODEL_MISSING.getResourcePath()), + ModelRotation.X0_Y0, false, 1) }))); + ResourceLocation resourcelocation = new ResourceLocation("item_frame"); + ModelBlockDefinition modelblockdefinition = this.getModelBlockDefinition(resourcelocation); + this.registerVariant(modelblockdefinition, new ModelResourceLocation(resourcelocation, "normal")); + this.registerVariant(modelblockdefinition, new ModelResourceLocation(resourcelocation, "map")); + this.loadVariantModels(); + this.loadItemModels(); + } + + private void loadVariantModels() { + for (ModelResourceLocation modelresourcelocation : this.variants.keySet()) { + for (ModelBlockDefinition.Variant modelblockdefinition$variant : ((ModelBlockDefinition.Variants) this.variants + .get(modelresourcelocation)).getVariants()) { + ResourceLocation resourcelocation = modelblockdefinition$variant.getModelLocation(); if (this.models.get(resourcelocation) == null) { try { ModelBlock modelblock = this.loadModel(resourcelocation); this.models.put(resourcelocation, modelblock); } catch (Exception exception) { - LOGGER.warn("Unable to load item model: \'" + resourcelocation + "\' for item: \'" - + Item.itemRegistry.getNameForObject(item) + "\'"); + LOGGER.warn("Unable to load block model: \'" + resourcelocation + "\' for variant: \'" + + modelresourcelocation + "\'"); LOGGER.warn(exception); } } @@ -283,6 +579,44 @@ public class ModelBakery { } + private void loadVariants(Collection parCollection) { + for (ModelResourceLocation modelresourcelocation : parCollection) { + try { + ModelBlockDefinition modelblockdefinition = this.getModelBlockDefinition(modelresourcelocation); + + try { + this.registerVariant(modelblockdefinition, modelresourcelocation); + } catch (Exception var6) { + LOGGER.warn("Unable to load variant: " + modelresourcelocation.getVariant() + " from " + + modelresourcelocation); + LOGGER.warn(var6); + } + } catch (Exception exception) { + LOGGER.warn("Unable to load definition " + modelresourcelocation); + LOGGER.warn(exception); + } + } + + } + + private BakedQuad makeBakedQuad(BlockPart parBlockPart, BlockPartFace parBlockPartFace, + EaglerTextureAtlasSprite parTextureAtlasSprite, EnumFacing parEnumFacing, ModelRotation parModelRotation, + boolean parFlag) { + return this.faceBakery.makeBakedQuad(parBlockPart.positionFrom, parBlockPart.positionTo, parBlockPartFace, + parTextureAtlasSprite, parEnumFacing, parModelRotation, parBlockPart.partRotation, parFlag, + parBlockPart.shade); + } + + private ModelBlock makeItemModel(ModelBlock parModelBlock) { + return this.itemModelGenerator.makeItemModel(this.textureMap, parModelBlock); + } + + private void registerVariant(ModelBlockDefinition parModelBlockDefinition, + ModelResourceLocation parModelResourceLocation) { + this.variants.put(parModelResourceLocation, + parModelBlockDefinition.getVariants(parModelResourceLocation.getVariant())); + } + private void registerVariantNames() { this.variantNames.put(Item.getItemFromBlock(Blocks.stone), Lists.newArrayList(new String[] { "stone", "granite", "granite_smooth", "diorite", "diorite_smooth", "andesite", "andesite_smooth" })); @@ -390,345 +724,19 @@ public class ModelBakery { this.variantNames.put(Item.getItemFromBlock(Blocks.oak_fence), Lists.newArrayList(new String[] { "oak_fence" })); this.variantNames.put(Items.oak_door, Lists.newArrayList(new String[] { "oak_door" })); + + this.variantNames.put(Item.getItemFromBlock(Blocks.mosaic), + Lists.newArrayList( + new String[] { "starlike:oak_mosaic", "starlike:spruce_mosaic", "starlike:birch_mosaic", + "starlike:jungle_mosaic", "starlike:acacia_mosaic", "starlike:dark_oak_mosaic" })); } - private List getVariantNames(Item parItem) { - List list = (List) this.variantNames.get(parItem); - if (list == null) { - list = Collections - .singletonList(((ResourceLocation) Item.itemRegistry.getNameForObject(parItem)).toString()); - } - - return list; - } - - private ResourceLocation getItemLocation(String parString1) { - ResourceLocation resourcelocation = new ResourceLocation(parString1); - return new ResourceLocation(resourcelocation.getResourceDomain(), "item/" + resourcelocation.getResourcePath()); - } - - private void bakeBlockModels() { - boolean deferred = Minecraft.getMinecraft().gameSettings.shaders; - for (ModelResourceLocation modelresourcelocation : this.variants.keySet()) { - WeightedBakedModel.Builder weightedbakedmodel$builder = new WeightedBakedModel.Builder(); - int i = 0; - - for (ModelBlockDefinition.Variant modelblockdefinition$variant : ((ModelBlockDefinition.Variants) this.variants - .get(modelresourcelocation)).getVariants()) { - ModelBlock modelblock = (ModelBlock) this.models.get(modelblockdefinition$variant.getModelLocation()); - if (modelblock != null && modelblock.isResolved()) { - ++i; - if (deferred) { - ModelBlock currentBlockModel = modelblock; - ResourceLocation currentResourceLocation = modelblockdefinition$variant.getModelLocation(); - Integer blockId = null; - do { - blockId = BlockVertexIDs.modelToID.get(currentResourceLocation.toString()); - if (blockId != null) { - break; - } - currentResourceLocation = currentBlockModel.getParentLocation(); - currentBlockModel = models.get(currentResourceLocation); - } while (currentBlockModel != null); - if (blockId != null) { - VertexMarkerState.markId = blockId.intValue(); - try { - weightedbakedmodel$builder.add( - this.bakeModel(modelblock, modelblockdefinition$variant.getRotation(), - modelblockdefinition$variant.isUvLocked()), - modelblockdefinition$variant.getWeight()); - } finally { - VertexMarkerState.markId = 0; - } - continue; - } - } - weightedbakedmodel$builder.add( - this.bakeModel(modelblock, modelblockdefinition$variant.getRotation(), - modelblockdefinition$variant.isUvLocked()), - modelblockdefinition$variant.getWeight()); - } else { - LOGGER.warn("Missing model for: " + modelresourcelocation); - } - } - - if (i == 0) { - LOGGER.warn("No weighted models for: " + modelresourcelocation); - } else if (i == 1) { - this.bakedRegistry.putObject(modelresourcelocation, weightedbakedmodel$builder.first()); - } else { - this.bakedRegistry.putObject(modelresourcelocation, weightedbakedmodel$builder.build()); - } - } - - for (Entry entry : this.itemLocations.entrySet()) { - ResourceLocation resourcelocation = (ResourceLocation) entry.getValue(); - ModelResourceLocation modelresourcelocation1 = new ModelResourceLocation((String) entry.getKey(), - "inventory"); - ModelBlock modelblock1 = (ModelBlock) this.models.get(resourcelocation); - if (modelblock1 != null && modelblock1.isResolved()) { - if (this.isCustomRenderer(modelblock1)) { - this.bakedRegistry.putObject(modelresourcelocation1, new BuiltInModel(modelblock1.func_181682_g())); - } else { - this.bakedRegistry.putObject(modelresourcelocation1, - this.bakeModel(modelblock1, ModelRotation.X0_Y0, false)); - } - } else { - LOGGER.warn("Missing model for: " + resourcelocation); - } - } - - } - - private Set getVariantsTextureLocations() { - HashSet hashset = Sets.newHashSet(); - ArrayList arraylist = Lists.newArrayList(this.variants.keySet()); - Collections.sort(arraylist, new Comparator() { - public int compare(ModelResourceLocation modelresourcelocation1, - ModelResourceLocation modelresourcelocation2) { - return modelresourcelocation1.toString().compareTo(modelresourcelocation2.toString()); - } - }); - - for (ModelResourceLocation modelresourcelocation : (List) arraylist) { - ModelBlockDefinition.Variants modelblockdefinition$variants = (ModelBlockDefinition.Variants) this.variants - .get(modelresourcelocation); - - for (ModelBlockDefinition.Variant modelblockdefinition$variant : modelblockdefinition$variants - .getVariants()) { - ModelBlock modelblock = (ModelBlock) this.models.get(modelblockdefinition$variant.getModelLocation()); - if (modelblock == null) { - LOGGER.warn("Missing model for: " + modelresourcelocation); - } else { - hashset.addAll(this.getTextureLocations(modelblock)); - } - } - } - - hashset.addAll(LOCATIONS_BUILTIN_TEXTURES); - return hashset; - } - - private IBakedModel bakeModel(ModelBlock modelBlockIn, ModelRotation modelRotationIn, boolean uvLocked) { - EaglerTextureAtlasSprite textureatlassprite = (EaglerTextureAtlasSprite) this.sprites - .get(new ResourceLocation(modelBlockIn.resolveTextureName("particle"))); - SimpleBakedModel.Builder simplebakedmodel$builder = (new SimpleBakedModel.Builder(modelBlockIn)) - .setTexture(textureatlassprite); - - for (BlockPart blockpart : modelBlockIn.getElements()) { - for (EnumFacing enumfacing : blockpart.mapFaces.keySet()) { - BlockPartFace blockpartface = (BlockPartFace) blockpart.mapFaces.get(enumfacing); - EaglerTextureAtlasSprite textureatlassprite1 = (EaglerTextureAtlasSprite) this.sprites - .get(new ResourceLocation(modelBlockIn.resolveTextureName(blockpartface.texture))); - if (blockpartface.cullFace == null) { - simplebakedmodel$builder.addGeneralQuad(this.makeBakedQuad(blockpart, blockpartface, - textureatlassprite1, enumfacing, modelRotationIn, uvLocked)); - } else { - simplebakedmodel$builder.addFaceQuad(modelRotationIn.rotateFace(blockpartface.cullFace), - this.makeBakedQuad(blockpart, blockpartface, textureatlassprite1, enumfacing, - modelRotationIn, uvLocked)); - } - } - } - - return simplebakedmodel$builder.makeBakedModel(); - } - - private BakedQuad makeBakedQuad(BlockPart parBlockPart, BlockPartFace parBlockPartFace, - EaglerTextureAtlasSprite parTextureAtlasSprite, EnumFacing parEnumFacing, ModelRotation parModelRotation, - boolean parFlag) { - return this.faceBakery.makeBakedQuad(parBlockPart.positionFrom, parBlockPart.positionTo, parBlockPartFace, - parTextureAtlasSprite, parEnumFacing, parModelRotation, parBlockPart.partRotation, parFlag, - parBlockPart.shade); - } - - private void loadModelsCheck() { - this.loadModels(); - - for (ModelBlock modelblock : this.models.values()) { - modelblock.getParentFromMap(this.models); - } - - ModelBlock.checkModelHierarchy(this.models); - } - - private void loadModels() { - List arraydeque = Lists.newLinkedList(); - HashSet hashset = Sets.newHashSet(); - - for (ResourceLocation resourcelocation : this.models.keySet()) { - hashset.add(resourcelocation); - ResourceLocation resourcelocation1 = ((ModelBlock) this.models.get(resourcelocation)).getParentLocation(); - if (resourcelocation1 != null) { - arraydeque.add(resourcelocation1); - } - } - - while (!arraydeque.isEmpty()) { - ResourceLocation resourcelocation2 = (ResourceLocation) arraydeque.remove(0); - - try { - if (this.models.get(resourcelocation2) != null) { - continue; - } - - ModelBlock modelblock = this.loadModel(resourcelocation2); - this.models.put(resourcelocation2, modelblock); - ResourceLocation resourcelocation3 = modelblock.getParentLocation(); - if (resourcelocation3 != null && !hashset.contains(resourcelocation3)) { - arraydeque.add(resourcelocation3); - } - } catch (Exception exception) { - LOGGER.warn("In parent chain: " + JOINER.join(this.getParentPath(resourcelocation2)) - + "; unable to load model: \'" + resourcelocation2 + "\'"); - LOGGER.warn(exception); - } - - hashset.add(resourcelocation2); - } - - } - - private List getParentPath(ResourceLocation parResourceLocation) { - ArrayList arraylist = Lists.newArrayList(new ResourceLocation[] { parResourceLocation }); - ResourceLocation resourcelocation = parResourceLocation; - - while ((resourcelocation = this.getParentLocation(resourcelocation)) != null) { - arraylist.add(0, resourcelocation); - } - - return arraylist; - } - - private ResourceLocation getParentLocation(ResourceLocation parResourceLocation) { - for (Entry entry : this.models.entrySet()) { - ModelBlock modelblock = (ModelBlock) entry.getValue(); - if (modelblock != null && parResourceLocation.equals(modelblock.getParentLocation())) { - return (ResourceLocation) entry.getKey(); - } - } - - return null; - } - - private Set getTextureLocations(ModelBlock parModelBlock) { - HashSet hashset = Sets.newHashSet(); - - for (BlockPart blockpart : parModelBlock.getElements()) { - for (BlockPartFace blockpartface : blockpart.mapFaces.values()) { - ResourceLocation resourcelocation = new ResourceLocation( - parModelBlock.resolveTextureName(blockpartface.texture)); - hashset.add(resourcelocation); - } - } - - hashset.add(new ResourceLocation(parModelBlock.resolveTextureName("particle"))); - return hashset; - } - - private void loadSprites() { - final Set set = this.getVariantsTextureLocations(); - set.addAll(this.getItemsTextureLocations()); - set.remove(TextureMap.LOCATION_MISSING_TEXTURE); - IIconCreator iiconcreator = new IIconCreator() { - public void registerSprites(TextureMap texturemap) { - for (ResourceLocation resourcelocation : (Set) set) { - EaglerTextureAtlasSprite textureatlassprite = texturemap.registerSprite(resourcelocation); - ModelBakery.this.sprites.put(resourcelocation, textureatlassprite); - } - - } - }; - this.textureMap.loadSprites(this.resourceManager, iiconcreator); - this.sprites.put(new ResourceLocation("missingno"), this.textureMap.getMissingSprite()); - } - - private Set getItemsTextureLocations() { - HashSet hashset = Sets.newHashSet(); - - for (ResourceLocation resourcelocation : this.itemLocations.values()) { - ModelBlock modelblock = (ModelBlock) this.models.get(resourcelocation); - if (modelblock != null) { - hashset.add(new ResourceLocation(modelblock.resolveTextureName("particle"))); - if (this.hasItemModel(modelblock)) { - for (String s : ItemModelGenerator.LAYERS) { - ResourceLocation resourcelocation2 = new ResourceLocation(modelblock.resolveTextureName(s)); - if (modelblock.getRootModel() == MODEL_COMPASS - && !TextureMap.LOCATION_MISSING_TEXTURE.equals(resourcelocation2)) { - EaglerTextureAtlasSprite.setLocationNameCompass(resourcelocation2.toString()); - } else if (modelblock.getRootModel() == MODEL_CLOCK - && !TextureMap.LOCATION_MISSING_TEXTURE.equals(resourcelocation2)) { - EaglerTextureAtlasSprite.setLocationNameClock(resourcelocation2.toString()); - } - - hashset.add(resourcelocation2); - } - } else if (!this.isCustomRenderer(modelblock)) { - for (BlockPart blockpart : modelblock.getElements()) { - for (BlockPartFace blockpartface : blockpart.mapFaces.values()) { - ResourceLocation resourcelocation1 = new ResourceLocation( - modelblock.resolveTextureName(blockpartface.texture)); - hashset.add(resourcelocation1); - } - } - } - } - } - - return hashset; - } - - private boolean hasItemModel(ModelBlock parModelBlock) { - if (parModelBlock == null) { - return false; - } else { - ModelBlock modelblock = parModelBlock.getRootModel(); - return modelblock == MODEL_GENERATED || modelblock == MODEL_COMPASS || modelblock == MODEL_CLOCK; - } - } - - private boolean isCustomRenderer(ModelBlock parModelBlock) { - if (parModelBlock == null) { - return false; - } else { - ModelBlock modelblock = parModelBlock.getRootModel(); - return modelblock == MODEL_ENTITY; - } - } - - private void bakeItemModels() { - for (ResourceLocation resourcelocation : this.itemLocations.values()) { - ModelBlock modelblock = (ModelBlock) this.models.get(resourcelocation); - if (this.hasItemModel(modelblock)) { - ModelBlock modelblock1 = this.makeItemModel(modelblock); - if (modelblock1 != null) { - modelblock1.name = resourcelocation.toString(); - } - - this.models.put(resourcelocation, modelblock1); - } else if (this.isCustomRenderer(modelblock)) { - this.models.put(resourcelocation, modelblock); - } - } - - for (EaglerTextureAtlasSprite textureatlassprite : this.sprites.values()) { - if (!textureatlassprite.hasAnimationMetadata()) { - textureatlassprite.clearFramesTextureData(); - } - } - - } - - private ModelBlock makeItemModel(ModelBlock parModelBlock) { - return this.itemModelGenerator.makeItemModel(this.textureMap, parModelBlock); - } - - static { - BUILT_IN_MODELS.put("missing", - "{ \"textures\": { \"particle\": \"missingno\", \"missingno\": \"missingno\"}, \"elements\": [ { \"from\": [ 0, 0, 0 ], \"to\": [ 16, 16, 16 ], \"faces\": { \"down\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"down\", \"texture\": \"#missingno\" }, \"up\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"up\", \"texture\": \"#missingno\" }, \"north\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"north\", \"texture\": \"#missingno\" }, \"south\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"south\", \"texture\": \"#missingno\" }, \"west\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"west\", \"texture\": \"#missingno\" }, \"east\": { \"uv\": [ 0, 0, 16, 16 ], \"cullface\": \"east\", \"texture\": \"#missingno\" } }}]}"); - MODEL_GENERATED.name = "generation marker"; - MODEL_COMPASS.name = "compass generation marker"; - MODEL_CLOCK.name = "class generation marker"; - MODEL_ENTITY.name = "block entity marker"; + public IRegistry setupModelRegistry() { + this.loadVariantItemModels(); + this.loadModelsCheck(); + this.loadSprites(); + this.bakeItemModels(); + this.bakeBlockModels(); + return this.bakedRegistry; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/model/ModelManager.java b/src/game/java/net/minecraft/client/resources/model/ModelManager.java index 9fab93a9..005a5ebe 100644 --- a/src/game/java/net/minecraft/client/resources/model/ModelManager.java +++ b/src/game/java/net/minecraft/client/resources/model/ModelManager.java @@ -6,22 +6,25 @@ import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.util.IRegistry; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,11 +40,12 @@ public class ModelManager implements IResourceManagerReloadListener { this.modelProvider = new BlockModelShapes(this); } - public void onResourceManagerReload(IResourceManager iresourcemanager) { - ModelBakery modelbakery = new ModelBakery(iresourcemanager, this.texMap, this.modelProvider); - this.modelRegistry = modelbakery.setupModelRegistry(); - this.defaultModel = (IBakedModel) this.modelRegistry.getObject(ModelBakery.MODEL_MISSING); - this.modelProvider.reloadModels(); + public BlockModelShapes getBlockModelShapes() { + return this.modelProvider; + } + + public IBakedModel getMissingModel() { + return this.defaultModel; } public IBakedModel getModel(ModelResourceLocation modelLocation) { @@ -53,15 +57,14 @@ public class ModelManager implements IResourceManagerReloadListener { } } - public IBakedModel getMissingModel() { - return this.defaultModel; - } - public TextureMap getTextureMap() { return this.texMap; } - public BlockModelShapes getBlockModelShapes() { - return this.modelProvider; + public void onResourceManagerReload(IResourceManager iresourcemanager) { + ModelBakery modelbakery = new ModelBakery(iresourcemanager, this.texMap, this.modelProvider); + this.modelRegistry = modelbakery.setupModelRegistry(); + this.defaultModel = (IBakedModel) this.modelRegistry.getObject(ModelBakery.MODEL_MISSING); + this.modelProvider.reloadModels(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/model/ModelResourceLocation.java b/src/game/java/net/minecraft/client/resources/model/ModelResourceLocation.java index e8a0372d..9f20d117 100644 --- a/src/game/java/net/minecraft/client/resources/model/ModelResourceLocation.java +++ b/src/game/java/net/minecraft/client/resources/model/ModelResourceLocation.java @@ -4,46 +4,30 @@ import org.apache.commons.lang3.StringUtils; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ModelResourceLocation extends ResourceLocation { - private final String variant; - - protected ModelResourceLocation(int parInt1, String... parArrayOfString) { - super(0, new String[] { parArrayOfString[0], parArrayOfString[1] }); - this.variant = StringUtils.isEmpty(parArrayOfString[2]) ? "normal" : parArrayOfString[2].toLowerCase(); - } - - public ModelResourceLocation(String parString1) { - this(0, parsePathString(parString1)); - } - - public ModelResourceLocation(ResourceLocation parResourceLocation, String parString1) { - this(parResourceLocation.toString(), parString1); - } - - public ModelResourceLocation(String parString1, String parString2) { - this(0, parsePathString(parString1 + '#' + (parString2 == null ? "normal" : parString2))); - } - protected static String[] parsePathString(String parString1) { String[] astring = new String[] { null, parString1, null }; int i = parString1.indexOf(35); @@ -59,8 +43,23 @@ public class ModelResourceLocation extends ResourceLocation { return astring; } - public String getVariant() { - return this.variant; + private final String variant; + + protected ModelResourceLocation(int parInt1, String... parArrayOfString) { + super(0, new String[] { parArrayOfString[0], parArrayOfString[1] }); + this.variant = StringUtils.isEmpty(parArrayOfString[2]) ? "normal" : parArrayOfString[2].toLowerCase(); + } + + public ModelResourceLocation(ResourceLocation parResourceLocation, String parString1) { + this(parResourceLocation.toString(), parString1); + } + + public ModelResourceLocation(String parString1) { + this(0, parsePathString(parString1)); + } + + public ModelResourceLocation(String parString1, String parString2) { + this(0, parsePathString(parString1 + '#' + (parString2 == null ? "normal" : parString2))); } public boolean equals(Object object) { @@ -74,6 +73,10 @@ public class ModelResourceLocation extends ResourceLocation { } } + public String getVariant() { + return this.variant; + } + public int hashCode() { return 31 * super.hashCode() + this.variant.hashCode(); } diff --git a/src/game/java/net/minecraft/client/resources/model/ModelRotation.java b/src/game/java/net/minecraft/client/resources/model/ModelRotation.java index 803d984e..31498015 100644 --- a/src/game/java/net/minecraft/client/resources/model/ModelRotation.java +++ b/src/game/java/net/minecraft/client/resources/model/ModelRotation.java @@ -9,22 +9,25 @@ import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,15 +38,31 @@ public enum ModelRotation { X270_Y90(270, 90), X270_Y180(270, 180), X270_Y270(270, 270); private static final Map mapRotations = Maps.newHashMap(); - private final int combinedXY; - private final Matrix4f matrix4d; - private final int quartersX; - private final int quartersY; + static { + ModelRotation[] lst = values(); + for (int i = 0; i < lst.length; ++i) { + mapRotations.put(Integer.valueOf(lst[i].combinedXY), lst[i]); + } + + } private static int combineXY(int parInt1, int parInt2) { return parInt1 * 360 + parInt2; } + public static ModelRotation getModelRotation(int parInt1, int parInt2) { + return (ModelRotation) mapRotations.get(Integer + .valueOf(combineXY(MathHelper.normalizeAngle(parInt1, 360), MathHelper.normalizeAngle(parInt2, 360)))); + } + + private final int combinedXY; + + private final Matrix4f matrix4d; + + private final int quartersX; + + private final int quartersY; + private ModelRotation(int parInt2, int parInt3) { this.combinedXY = combineXY(parInt2, parInt3); this.matrix4d = new Matrix4f(); @@ -96,17 +115,4 @@ public enum ModelRotation { return i; } - - public static ModelRotation getModelRotation(int parInt1, int parInt2) { - return (ModelRotation) mapRotations.get(Integer - .valueOf(combineXY(MathHelper.normalizeAngle(parInt1, 360), MathHelper.normalizeAngle(parInt2, 360)))); - } - - static { - ModelRotation[] lst = values(); - for (int i = 0; i < lst.length; ++i) { - mapRotations.put(Integer.valueOf(lst[i].combinedXY), lst[i]); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/model/SimpleBakedModel.java b/src/game/java/net/minecraft/client/resources/model/SimpleBakedModel.java index 66d43beb..93d5906d 100644 --- a/src/game/java/net/minecraft/client/resources/model/SimpleBakedModel.java +++ b/src/game/java/net/minecraft/client/resources/model/SimpleBakedModel.java @@ -11,32 +11,118 @@ import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.client.renderer.block.model.ModelBlock; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SimpleBakedModel implements IBakedModel { + public static class Builder { + private final List builderGeneralQuads; + private final List> builderFaceQuads; + private final boolean builderAmbientOcclusion; + private EaglerTextureAtlasSprite builderTexture; + private boolean builderGui3d; + private ItemCameraTransforms builderCameraTransforms; + + private Builder(boolean parFlag, boolean parFlag2, ItemCameraTransforms parItemCameraTransforms) { + this.builderGeneralQuads = Lists.newArrayList(); + this.builderFaceQuads = Lists.newArrayListWithCapacity(6); + + for (int i = 0, l = EnumFacing._VALUES.length; i < l; ++i) { + this.builderFaceQuads.add(Lists.newArrayList()); + } + + this.builderAmbientOcclusion = parFlag; + this.builderGui3d = parFlag2; + this.builderCameraTransforms = parItemCameraTransforms; + } + + public Builder(IBakedModel parIBakedModel, EaglerTextureAtlasSprite parTextureAtlasSprite) { + this(parIBakedModel.isAmbientOcclusion(), parIBakedModel.isGui3d(), + parIBakedModel.getItemCameraTransforms()); + this.builderTexture = parIBakedModel.getParticleTexture(); + + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + this.addFaceBreakingFours(parIBakedModel, parTextureAtlasSprite, facings[i]); + } + + this.addGeneralBreakingFours(parIBakedModel, parTextureAtlasSprite); + } + + public Builder(ModelBlock parModelBlock) { + this(parModelBlock.isAmbientOcclusion(), parModelBlock.isGui3d(), parModelBlock.func_181682_g()); + } + + private void addFaceBreakingFours(IBakedModel parIBakedModel, EaglerTextureAtlasSprite parTextureAtlasSprite, + EnumFacing parEnumFacing) { + List quads = parIBakedModel.getFaceQuads(parEnumFacing); + for (int i = 0, l = quads.size(); i < l; ++i) { + this.addFaceQuad(parEnumFacing, new BreakingFour(quads.get(i), parTextureAtlasSprite)); + } + + } + + public SimpleBakedModel.Builder addFaceQuad(EnumFacing parEnumFacing, BakedQuad parBakedQuad) { + ((List) this.builderFaceQuads.get(parEnumFacing.ordinal())).add(parBakedQuad); + return this; + } + + private void addGeneralBreakingFours(IBakedModel parIBakedModel, + EaglerTextureAtlasSprite parTextureAtlasSprite) { + List quads = parIBakedModel.getGeneralQuads(); + for (int i = 0, l = quads.size(); i < l; ++i) { + this.addGeneralQuad(new BreakingFour(quads.get(i), parTextureAtlasSprite)); + } + + } + + public SimpleBakedModel.Builder addGeneralQuad(BakedQuad parBakedQuad) { + this.builderGeneralQuads.add(parBakedQuad); + return this; + } + + public IBakedModel makeBakedModel() { + if (this.builderTexture == null) { + throw new RuntimeException("Missing particle!"); + } else { + return new SimpleBakedModel(this.builderGeneralQuads, this.builderFaceQuads, + this.builderAmbientOcclusion, this.builderGui3d, this.builderTexture, + this.builderCameraTransforms); + } + } + + public SimpleBakedModel.Builder setTexture(EaglerTextureAtlasSprite parTextureAtlasSprite) { + this.builderTexture = parTextureAtlasSprite; + return this; + } + } + protected final List generalQuads; protected final List> faceQuads; protected final boolean ambientOcclusion; protected final boolean gui3d; protected final EaglerTextureAtlasSprite texture; + protected final ItemCameraTransforms cameraTransforms; public SimpleBakedModel(List parList, List> parList2, boolean parFlag, boolean parFlag2, @@ -57,105 +143,23 @@ public class SimpleBakedModel implements IBakedModel { return this.generalQuads; } - public boolean isAmbientOcclusion() { - return this.ambientOcclusion; - } - - public boolean isGui3d() { - return this.gui3d; - } - - public boolean isBuiltInRenderer() { - return false; + public ItemCameraTransforms getItemCameraTransforms() { + return this.cameraTransforms; } public EaglerTextureAtlasSprite getParticleTexture() { return this.texture; } - public ItemCameraTransforms getItemCameraTransforms() { - return this.cameraTransforms; + public boolean isAmbientOcclusion() { + return this.ambientOcclusion; } - public static class Builder { - private final List builderGeneralQuads; - private final List> builderFaceQuads; - private final boolean builderAmbientOcclusion; - private EaglerTextureAtlasSprite builderTexture; - private boolean builderGui3d; - private ItemCameraTransforms builderCameraTransforms; + public boolean isBuiltInRenderer() { + return false; + } - public Builder(ModelBlock parModelBlock) { - this(parModelBlock.isAmbientOcclusion(), parModelBlock.isGui3d(), parModelBlock.func_181682_g()); - } - - public Builder(IBakedModel parIBakedModel, EaglerTextureAtlasSprite parTextureAtlasSprite) { - this(parIBakedModel.isAmbientOcclusion(), parIBakedModel.isGui3d(), - parIBakedModel.getItemCameraTransforms()); - this.builderTexture = parIBakedModel.getParticleTexture(); - - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - this.addFaceBreakingFours(parIBakedModel, parTextureAtlasSprite, facings[i]); - } - - this.addGeneralBreakingFours(parIBakedModel, parTextureAtlasSprite); - } - - private void addFaceBreakingFours(IBakedModel parIBakedModel, EaglerTextureAtlasSprite parTextureAtlasSprite, - EnumFacing parEnumFacing) { - List quads = parIBakedModel.getFaceQuads(parEnumFacing); - for (int i = 0, l = quads.size(); i < l; ++i) { - this.addFaceQuad(parEnumFacing, new BreakingFour(quads.get(i), parTextureAtlasSprite)); - } - - } - - private void addGeneralBreakingFours(IBakedModel parIBakedModel, - EaglerTextureAtlasSprite parTextureAtlasSprite) { - List quads = parIBakedModel.getGeneralQuads(); - for (int i = 0, l = quads.size(); i < l; ++i) { - this.addGeneralQuad(new BreakingFour(quads.get(i), parTextureAtlasSprite)); - } - - } - - private Builder(boolean parFlag, boolean parFlag2, ItemCameraTransforms parItemCameraTransforms) { - this.builderGeneralQuads = Lists.newArrayList(); - this.builderFaceQuads = Lists.newArrayListWithCapacity(6); - - for (int i = 0, l = EnumFacing._VALUES.length; i < l; ++i) { - this.builderFaceQuads.add(Lists.newArrayList()); - } - - this.builderAmbientOcclusion = parFlag; - this.builderGui3d = parFlag2; - this.builderCameraTransforms = parItemCameraTransforms; - } - - public SimpleBakedModel.Builder addFaceQuad(EnumFacing parEnumFacing, BakedQuad parBakedQuad) { - ((List) this.builderFaceQuads.get(parEnumFacing.ordinal())).add(parBakedQuad); - return this; - } - - public SimpleBakedModel.Builder addGeneralQuad(BakedQuad parBakedQuad) { - this.builderGeneralQuads.add(parBakedQuad); - return this; - } - - public SimpleBakedModel.Builder setTexture(EaglerTextureAtlasSprite parTextureAtlasSprite) { - this.builderTexture = parTextureAtlasSprite; - return this; - } - - public IBakedModel makeBakedModel() { - if (this.builderTexture == null) { - throw new RuntimeException("Missing particle!"); - } else { - return new SimpleBakedModel(this.builderGeneralQuads, this.builderFaceQuads, - this.builderAmbientOcclusion, this.builderGui3d, this.builderTexture, - this.builderCameraTransforms); - } - } + public boolean isGui3d() { + return this.gui3d; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/resources/model/WeightedBakedModel.java b/src/game/java/net/minecraft/client/resources/model/WeightedBakedModel.java index dce7a300..4265f774 100644 --- a/src/game/java/net/minecraft/client/resources/model/WeightedBakedModel.java +++ b/src/game/java/net/minecraft/client/resources/model/WeightedBakedModel.java @@ -12,70 +12,30 @@ import net.minecraft.client.renderer.block.model.ItemCameraTransforms; import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WeightedBakedModel implements IBakedModel { - private final int totalWeight; - private final List models; - private final IBakedModel baseModel; - - public WeightedBakedModel(List parList) { - this.models = parList; - this.totalWeight = WeightedRandom.getTotalWeight(parList); - this.baseModel = ((WeightedBakedModel.MyWeighedRandomItem) parList.get(0)).model; - } - - public List getFaceQuads(EnumFacing enumfacing) { - return this.baseModel.getFaceQuads(enumfacing); - } - - public List getGeneralQuads() { - return this.baseModel.getGeneralQuads(); - } - - public boolean isAmbientOcclusion() { - return this.baseModel.isAmbientOcclusion(); - } - - public boolean isGui3d() { - return this.baseModel.isGui3d(); - } - - public boolean isBuiltInRenderer() { - return this.baseModel.isBuiltInRenderer(); - } - - public EaglerTextureAtlasSprite getParticleTexture() { - return this.baseModel.getParticleTexture(); - } - - public ItemCameraTransforms getItemCameraTransforms() { - return this.baseModel.getItemCameraTransforms(); - } - - public IBakedModel getAlternativeModel(long parLong1) { - return ((WeightedBakedModel.MyWeighedRandomItem) WeightedRandom.getRandomItem(this.models, - Math.abs((int) parLong1 >> 16) % this.totalWeight)).model; - } - public static class Builder { private List listItems = Lists.newArrayList(); @@ -123,4 +83,49 @@ public class WeightedBakedModel implements IBakedModel { return "MyWeighedRandomItem{weight=" + this.itemWeight + ", model=" + this.model + '}'; } } + + private final int totalWeight; + + private final List models; + + private final IBakedModel baseModel; + + public WeightedBakedModel(List parList) { + this.models = parList; + this.totalWeight = WeightedRandom.getTotalWeight(parList); + this.baseModel = ((WeightedBakedModel.MyWeighedRandomItem) parList.get(0)).model; + } + + public IBakedModel getAlternativeModel(long parLong1) { + return ((WeightedBakedModel.MyWeighedRandomItem) WeightedRandom.getRandomItem(this.models, + Math.abs((int) parLong1 >> 16) % this.totalWeight)).model; + } + + public List getFaceQuads(EnumFacing enumfacing) { + return this.baseModel.getFaceQuads(enumfacing); + } + + public List getGeneralQuads() { + return this.baseModel.getGeneralQuads(); + } + + public ItemCameraTransforms getItemCameraTransforms() { + return this.baseModel.getItemCameraTransforms(); + } + + public EaglerTextureAtlasSprite getParticleTexture() { + return this.baseModel.getParticleTexture(); + } + + public boolean isAmbientOcclusion() { + return this.baseModel.isAmbientOcclusion(); + } + + public boolean isBuiltInRenderer() { + return this.baseModel.isBuiltInRenderer(); + } + + public boolean isGui3d() { + return this.baseModel.isGui3d(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/settings/GameSettings.java b/src/game/java/net/minecraft/client/settings/GameSettings.java index 9f586fcd..7082cad5 100644 --- a/src/game/java/net/minecraft/client/settings/GameSettings.java +++ b/src/game/java/net/minecraft/client/settings/GameSettings.java @@ -8,9 +8,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayManager; -import net.lax1dude.eaglercraft.v1_8.voice.VoiceClientController; - import org.json.JSONArray; import com.google.common.collect.ImmutableSet; @@ -35,6 +32,8 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.EaglerDeferredPipeline; import net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights.DynamicLightsStateManager; import net.lax1dude.eaglercraft.v1_8.recording.EnumScreenRecordingCodec; import net.lax1dude.eaglercraft.v1_8.recording.ScreenRecordingController; +import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayManager; +import net.lax1dude.eaglercraft.v1_8.voice.VoiceClientController; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.SoundCategory; import net.minecraft.client.gui.GuiNewChat; @@ -46,31 +45,153 @@ import net.minecraft.network.play.client.C15PacketClientSettings; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumDifficulty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GameSettings { - private static final Logger logger = LogManager.getLogger(); + public static enum Options { + INVERT_MOUSE("options.invertMouse", false, true), SENSITIVITY("options.sensitivity", true, false), + FOV("options.fov", true, false, 30.0F, 110.0F, 1.0F), GAMMA("options.gamma", true, false), + SATURATION("options.saturation", true, false), + RENDER_DISTANCE("options.renderDistance", true, false, 1.0F, 18.0F, 1.0F), + VIEW_BOBBING("options.viewBobbing", false, true), ANAGLYPH("options.anaglyph", false, true), + FRAMERATE_LIMIT("options.framerateLimit", true, false, 10.0F, 260.0F, 10.0F), + FBO_ENABLE("options.fboEnable", false, true), RENDER_CLOUDS("options.renderClouds", false, false), + GRAPHICS("options.graphics", false, false), AMBIENT_OCCLUSION("options.ao", false, false), + GUI_SCALE("options.guiScale", false, false), PARTICLES("options.particles", false, false), + CHAT_VISIBILITY("options.chat.visibility", false, false), CHAT_COLOR("options.chat.color", false, true), + CHAT_LINKS("options.chat.links", false, true), CHAT_OPACITY("options.chat.opacity", true, false), + CHAT_LINKS_PROMPT("options.chat.links.prompt", false, true), SNOOPER_ENABLED("options.snooper", false, true), + CHAT_SCALE("options.chat.scale", true, false), CHAT_WIDTH("options.chat.width", true, false), + CHAT_HEIGHT_FOCUSED("options.chat.height.focused", true, false), + CHAT_HEIGHT_UNFOCUSED("options.chat.height.unfocused", true, false), + MIPMAP_LEVELS("options.mipmapLevels", true, false, 0.0F, 4.0F, 1.0F), + FORCE_UNICODE_FONT("options.forceUnicodeFont", false, true), + STREAM_BYTES_PER_PIXEL("options.stream.bytesPerPixel", true, false), + STREAM_VOLUME_MIC("options.stream.micVolumne", true, false), + STREAM_VOLUME_SYSTEM("options.stream.systemVolume", true, false), + STREAM_KBPS("options.stream.kbps", true, false), STREAM_FPS("options.stream.fps", true, false), + STREAM_COMPRESSION("options.stream.compression", false, false), + STREAM_SEND_METADATA("options.stream.sendMetadata", false, true), + STREAM_CHAT_ENABLED("options.stream.chat.enabled", false, false), + STREAM_CHAT_USER_FILTER("options.stream.chat.userFilter", false, false), + STREAM_MIC_TOGGLE_BEHAVIOR("options.stream.micToggleBehavior", false, false), + BLOCK_ALTERNATIVES("options.blockAlternatives", false, true), + REDUCED_DEBUG_INFO("options.reducedDebugInfo", false, true), + ENTITY_SHADOWS("options.entityShadows", false, true), HUD_FPS("options.hud.fps", false, true), + HUD_COORDS("options.hud.coords", false, true), HUD_STATS("options.hud.stats", false, true), + HUD_WORLD("options.hud.world", false, true), HUD_PLAYER("options.hud.player", false, true), + HUD_24H("options.hud.24h", false, true), CHUNK_FIX("options.chunkFix", false, true), + FOG("options.fog", false, true), FXAA("options.fxaa", false, false), + FULLSCREEN("options.fullscreen", false, true), + FNAW_SKINS("options.skinCustomisation.enableFNAWSkins", false, true), + EAGLER_VSYNC("options.vsync", false, true), EAGLER_DYNAMIC_LIGHTS("options.dynamicLights", false, true), + EAGLER_PROFANITY_FILTER("options.profanityFilterButton", false, true), + EAGLER_TOUCH_CONTROL_OPACITY("options.touchControlOpacity", true, false); - /**+ - * GUI scale values + public static GameSettings.Options getEnumOptions(int parInt1) { + for (GameSettings.Options gamesettings$options : values()) { + if (gamesettings$options.returnEnumOrdinal() == parInt1) { + return gamesettings$options; + } + } + + return null; + } + + private final boolean enumFloat; + private final boolean enumBoolean; + private final String enumString; + private final float valueStep; + private float valueMin; + + private float valueMax; + + private Options(String parString2, boolean parFlag, boolean parFlag2) { + this(parString2, parFlag, parFlag2, 0.0F, 1.0F, 0.0F); + } + + private Options(String parString2, boolean parFlag, boolean parFlag2, float parFloat1, float parFloat2, + float parFloat3) { + this.enumString = parString2; + this.enumFloat = parFlag; + this.enumBoolean = parFlag2; + this.valueMin = parFloat1; + this.valueMax = parFloat2; + this.valueStep = parFloat3; + } + + public float denormalizeValue(float parFloat1) { + return this.snapToStepClamp( + this.valueMin + (this.valueMax - this.valueMin) * MathHelper.clamp_float(parFloat1, 0.0F, 1.0F)); + } + + public boolean getEnumBoolean() { + return this.enumBoolean; + } + + public boolean getEnumFloat() { + return this.enumFloat; + } + + public String getEnumString() { + return this.enumString; + } + + public float getValueMax() { + return this.valueMax; + } + + public float normalizeValue(float parFloat1) { + return MathHelper.clamp_float( + (this.snapToStepClamp(parFloat1) - this.valueMin) / (this.valueMax - this.valueMin), 0.0F, 1.0F); + } + + public int returnEnumOrdinal() { + return this.ordinal(); + } + + public void setValueMax(float parFloat1) { + this.valueMax = parFloat1; + } + + protected float snapToStep(float parFloat1) { + if (this.valueStep > 0.0F) { + parFloat1 = this.valueStep * (float) Math.round(parFloat1 / this.valueStep); + } + + return parFloat1; + } + + public float snapToStepClamp(float parFloat1) { + parFloat1 = this.snapToStep(parFloat1); + return MathHelper.clamp_float(parFloat1, this.valueMin, this.valueMax); + } + } + + private static final Logger logger = LogManager.getLogger(); + /** + * + GUI scale values */ private static final String[] GUISCALES = new String[] { "options.guiScale.auto", "options.guiScale.small", "options.guiScale.normal", "options.guiScale.large" }; @@ -88,6 +209,40 @@ public class GameSettings { "options.stream.mic_toggle.talk" }; private static final String[] field_181149_aW = new String[] { "options.off", "options.graphics.fast", "options.graphics.fancy" }; + + /** + * + Represents a key or mouse button as a string. Args: key + */ + public static String getKeyDisplayString(int parInt1) { + return parInt1 < 0 ? I18n.format("key.mouseButton", new Object[] { Integer.valueOf(parInt1 + 101) }) + : (parInt1 < 256 ? Keyboard.getKeyName(parInt1) + : HString.format("%c", new Object[] { Character.valueOf((char) (parInt1 - 256)) }) + .toUpperCase()); + } + + /** + * + Returns the translation of the given index in the given String array. If + * the index is smaller than 0 or greater than/equal to the length of the String + * array, it is changed to 0. + */ + private static String getTranslation(String[] parArrayOfString, int parInt1) { + if (parInt1 < 0 || parInt1 >= parArrayOfString.length) { + parInt1 = 0; + } + + return I18n.format(parArrayOfString[parInt1], new Object[0]); + } + + /** + * + Returns whether the specified key binding is currently being pressed. + */ + public static boolean isKeyDown(KeyBinding parKeyBinding) { + return parKeyBinding.getKeyCode() == 0 ? false + : (parKeyBinding.getKeyCode() < 0 + ? PointerInputAbstraction.getVCursorButtonDown(parKeyBinding.getKeyCode() + 100) + : Keyboard.isKeyDown(parKeyBinding.getKeyCode())); + } + public float mouseSensitivity = 0.5F; public boolean invertMouse; public int renderDistanceChunks = -1; @@ -95,13 +250,13 @@ public class GameSettings { public boolean anaglyph; public boolean fboEnable = true; public int limitFramerate = 260; - /**+ - * Clouds flag + /** + * + Clouds flag */ public int clouds = 1; public boolean fancyGraphics = false; - /**+ - * Smooth Lighting + /** + * + Smooth Lighting */ public int ambientOcclusion = 0; public List resourcePacks = Lists.newArrayList(); @@ -117,8 +272,8 @@ public class GameSettings { public boolean reducedDebugInfo = false; public boolean hideServerAddress; public boolean advancedItemTooltips; - /**+ - * Whether to pause when the game loses focus, toggled by F3+P + /** + * + Whether to pause when the game loses focus, toggled by F3+P */ public boolean pauseOnLostFocus = true; private final Set setModelParts = Sets.newHashSet(EnumPlayerModelParts._VALUES); @@ -185,8 +340,8 @@ public class GameSettings { public float fovSetting; public float gammaSetting; public float saturation; - /**+ - * GUI scale + /** + * + GUI scale */ public int guiScale = 3; public int particleSetting; @@ -208,21 +363,26 @@ public class GameSettings { public boolean enableFNAWSkins = true; public boolean enableDynamicLights = false; public boolean hasHiddenPhishWarning = false; + public boolean enableProfanityFilter = false; public boolean hasShownProfanityFilter = false; public float touchControlOpacity = 1.0f; + public boolean hideDefaultUsernameWarning = false; public int voiceListenRadius = 16; public float voiceListenVolume = 0.5f; public float voiceSpeakVolume = 0.5f; public int voicePTTKey = 47; // V - public EnumScreenRecordingCodec screenRecordCodec; public int screenRecordFPS = ScreenRecordingController.DEFAULT_FPS; public int screenRecordResolution = ScreenRecordingController.DEFAULT_RESOLUTION; + public int screenRecordAudioBitrate = ScreenRecordingController.DEFAULT_AUDIO_BITRATE; + public int screenRecordVideoBitrate = ScreenRecordingController.DEFAULT_VIDEO_BITRATE; + public float screenRecordGameVolume = ScreenRecordingController.DEFAULT_GAME_VOLUME; + public float screenRecordMicVolume = ScreenRecordingController.DEFAULT_MIC_VOLUME; public GameSettings(Minecraft mcIn) { @@ -246,352 +406,16 @@ public class GameSettings { this.loadOptions(); } - /**+ - * Represents a key or mouse button as a string. Args: key - */ - public static String getKeyDisplayString(int parInt1) { - return parInt1 < 0 ? I18n.format("key.mouseButton", new Object[] { Integer.valueOf(parInt1 + 101) }) - : (parInt1 < 256 ? Keyboard.getKeyName(parInt1) - : HString.format("%c", new Object[] { Character.valueOf((char) (parInt1 - 256)) }) - .toUpperCase()); + public int func_181147_e() { + return this.renderDistanceChunks >= 4 ? this.clouds : 0; } - /**+ - * Returns whether the specified key binding is currently being - * pressed. - */ - public static boolean isKeyDown(KeyBinding parKeyBinding) { - return parKeyBinding.getKeyCode() == 0 ? false - : (parKeyBinding.getKeyCode() < 0 - ? PointerInputAbstraction.getVCursorButtonDown(parKeyBinding.getKeyCode() + 100) - : Keyboard.isKeyDown(parKeyBinding.getKeyCode())); + public boolean func_181148_f() { + return this.field_181150_U; } - /**+ - * Sets a key binding and then saves all settings. - */ - public void setOptionKeyBinding(KeyBinding parKeyBinding, int parInt1) { - parKeyBinding.setKeyCode(parInt1); - this.saveOptions(); - } - - /**+ - * If the specified option is controlled by a slider (float - * value), this will set the float value. - */ - public void setOptionFloatValue(GameSettings.Options parOptions, float parFloat1) { - if (parOptions == GameSettings.Options.SENSITIVITY) { - this.mouseSensitivity = parFloat1; - } - - if (parOptions == GameSettings.Options.FOV) { - this.fovSetting = parFloat1; - } - - if (parOptions == GameSettings.Options.GAMMA) { - this.gammaSetting = parFloat1; - } - - if (parOptions == GameSettings.Options.FRAMERATE_LIMIT) { - this.limitFramerate = (int) parFloat1; - } - - if (parOptions == GameSettings.Options.CHAT_OPACITY) { - this.chatOpacity = parFloat1; - this.mc.ingameGUI.getChatGUI().refreshChat(); - } - - if (parOptions == GameSettings.Options.CHAT_HEIGHT_FOCUSED) { - this.chatHeightFocused = parFloat1; - this.mc.ingameGUI.getChatGUI().refreshChat(); - } - - if (parOptions == GameSettings.Options.CHAT_HEIGHT_UNFOCUSED) { - this.chatHeightUnfocused = parFloat1; - this.mc.ingameGUI.getChatGUI().refreshChat(); - } - - if (parOptions == GameSettings.Options.CHAT_WIDTH) { - this.chatWidth = parFloat1; - this.mc.ingameGUI.getChatGUI().refreshChat(); - } - - if (parOptions == GameSettings.Options.CHAT_SCALE) { - this.chatScale = parFloat1; - this.mc.ingameGUI.getChatGUI().refreshChat(); - } - - if (parOptions == GameSettings.Options.MIPMAP_LEVELS) { - int i = this.mipmapLevels; - this.mipmapLevels = (int) parFloat1; - if ((float) i != parFloat1) { - this.mc.getTextureMapBlocks().setMipmapLevels(this.mipmapLevels); - this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); - this.mc.getTextureMapBlocks().setBlurMipmapDirect(false, this.mipmapLevels > 0); - this.mc.scheduleResourcesRefresh(); - } - } - - if (parOptions == GameSettings.Options.BLOCK_ALTERNATIVES) { - this.allowBlockAlternatives = !this.allowBlockAlternatives; - this.mc.renderGlobal.loadRenderers(); - } - - if (parOptions == GameSettings.Options.RENDER_DISTANCE) { - this.renderDistanceChunks = (int) parFloat1; - this.mc.renderGlobal.setDisplayListEntitiesDirty(); - } - - if (parOptions == GameSettings.Options.EAGLER_TOUCH_CONTROL_OPACITY) { - this.touchControlOpacity = parFloat1; - } - } - - /**+ - * For non-float options. Toggles the option on/off, or cycles - * through the list i.e. render distances. - */ - public void setOptionValue(GameSettings.Options parOptions, int parInt1) { - if (parOptions == GameSettings.Options.INVERT_MOUSE) { - this.invertMouse = !this.invertMouse; - } - - if (parOptions == GameSettings.Options.GUI_SCALE) { - this.guiScale = this.guiScale + parInt1 & 3; - } - - if (parOptions == GameSettings.Options.PARTICLES) { - this.particleSetting = (this.particleSetting + parInt1) % 3; - } - - if (parOptions == GameSettings.Options.VIEW_BOBBING) { - this.viewBobbing = !this.viewBobbing; - } - - if (parOptions == GameSettings.Options.RENDER_CLOUDS) { - this.clouds = (this.clouds + parInt1) % 3; - } - - if (parOptions == GameSettings.Options.FORCE_UNICODE_FONT) { - this.forceUnicodeFont = !this.forceUnicodeFont; - this.mc.fontRendererObj - .setUnicodeFlag(this.mc.getLanguageManager().isCurrentLocaleUnicode() || this.forceUnicodeFont); - } - - if (parOptions == GameSettings.Options.FBO_ENABLE) { - this.fboEnable = !this.fboEnable; - } - - if (parOptions == GameSettings.Options.ANAGLYPH) { - this.anaglyph = !this.anaglyph; - this.mc.loadingScreen.eaglerShow(I18n.format("resourcePack.load.refreshing"), - I18n.format("resourcePack.load.pleaseWait")); - this.mc.refreshResources(); - } - - if (parOptions == GameSettings.Options.GRAPHICS) { - this.fancyGraphics = !this.fancyGraphics; - this.mc.renderGlobal.loadRenderers(); - } - - if (parOptions == GameSettings.Options.AMBIENT_OCCLUSION) { - this.ambientOcclusion = (this.ambientOcclusion + parInt1) % 3; - this.mc.renderGlobal.loadRenderers(); - } - - if (parOptions == GameSettings.Options.CHAT_VISIBILITY) { - this.chatVisibility = EntityPlayer.EnumChatVisibility - .getEnumChatVisibility((this.chatVisibility.getChatVisibility() + parInt1) % 3); - } - - if (parOptions == GameSettings.Options.CHAT_COLOR) { - this.chatColours = !this.chatColours; - } - - if (parOptions == GameSettings.Options.CHAT_LINKS) { - this.chatLinks = !this.chatLinks; - } - - if (parOptions == GameSettings.Options.CHAT_LINKS_PROMPT) { - this.chatLinksPrompt = !this.chatLinksPrompt; - } - - if (parOptions == GameSettings.Options.SNOOPER_ENABLED) { - this.snooperEnabled = !this.snooperEnabled; - } - - if (parOptions == GameSettings.Options.BLOCK_ALTERNATIVES) { - this.allowBlockAlternatives = !this.allowBlockAlternatives; - this.mc.renderGlobal.loadRenderers(); - } - - if (parOptions == GameSettings.Options.REDUCED_DEBUG_INFO) { - this.reducedDebugInfo = !this.reducedDebugInfo; - } - - if (parOptions == GameSettings.Options.ENTITY_SHADOWS) { - this.field_181151_V = !this.field_181151_V; - } - - if (parOptions == GameSettings.Options.HUD_FPS) { - this.hudFps = !this.hudFps; - } - - if (parOptions == GameSettings.Options.HUD_COORDS) { - this.hudCoords = !this.hudCoords; - } - - if (parOptions == GameSettings.Options.HUD_PLAYER) { - this.hudPlayer = !this.hudPlayer; - } - - if (parOptions == GameSettings.Options.HUD_STATS) { - this.hudStats = !this.hudStats; - } - - if (parOptions == GameSettings.Options.HUD_WORLD) { - this.hudWorld = !this.hudWorld; - } - - if (parOptions == GameSettings.Options.HUD_24H) { - this.hud24h = !this.hud24h; - } - - if (parOptions == GameSettings.Options.CHUNK_FIX) { - this.chunkFix = !this.chunkFix; - } - - if (parOptions == GameSettings.Options.FOG) { - this.fog = !this.fog; - } - - if (parOptions == GameSettings.Options.FXAA) { - this.fxaa = (this.fxaa + parInt1) % 3; - } - - if (parOptions == GameSettings.Options.FULLSCREEN) { - this.mc.toggleFullscreen(); - } - - if (parOptions == GameSettings.Options.FNAW_SKINS) { - this.enableFNAWSkins = !this.enableFNAWSkins; - this.mc.getRenderManager().setEnableFNAWSkins(this.mc.getEnableFNAWSkins()); - } - - if (parOptions == GameSettings.Options.EAGLER_VSYNC) { - this.enableVsync = !this.enableVsync; - } - - if (parOptions == GameSettings.Options.EAGLER_DYNAMIC_LIGHTS) { - this.enableDynamicLights = !this.enableDynamicLights; - this.mc.renderGlobal.loadRenderers(); - } - - if (parOptions == GameSettings.Options.EAGLER_PROFANITY_FILTER) { - this.enableProfanityFilter = !this.enableProfanityFilter; - } - - this.saveOptions(); - } - - public float getOptionFloatValue(GameSettings.Options parOptions) { - return parOptions == GameSettings.Options.FOV ? this.fovSetting - : (parOptions == GameSettings.Options.GAMMA ? this.gammaSetting - : (parOptions == GameSettings.Options.SATURATION ? this.saturation - : (parOptions == GameSettings.Options.SENSITIVITY ? this.mouseSensitivity - : (parOptions == GameSettings.Options.CHAT_OPACITY ? this.chatOpacity - : (parOptions == GameSettings.Options.CHAT_HEIGHT_FOCUSED - ? this.chatHeightFocused - : (parOptions == GameSettings.Options.CHAT_HEIGHT_UNFOCUSED - ? this.chatHeightUnfocused - : (parOptions == GameSettings.Options.CHAT_SCALE - ? this.chatScale - : (parOptions == GameSettings.Options.CHAT_WIDTH - ? this.chatWidth - : (parOptions == GameSettings.Options.FRAMERATE_LIMIT - ? (float) this.limitFramerate - : (parOptions == GameSettings.Options.MIPMAP_LEVELS - ? (float) this.mipmapLevels - : (parOptions == GameSettings.Options.RENDER_DISTANCE - ? (float) this.renderDistanceChunks - : (parOptions == GameSettings.Options.EAGLER_TOUCH_CONTROL_OPACITY - ? this.touchControlOpacity - : 0.0F)))))))))))); - } - - public boolean getOptionOrdinalValue(GameSettings.Options parOptions) { - switch (parOptions) { - case INVERT_MOUSE: - return this.invertMouse; - case VIEW_BOBBING: - return this.viewBobbing; - case ANAGLYPH: - return this.anaglyph; - case FBO_ENABLE: - return this.fboEnable; - case CHAT_COLOR: - return this.chatColours; - case CHAT_LINKS: - return this.chatLinks; - case CHAT_LINKS_PROMPT: - return this.chatLinksPrompt; - case SNOOPER_ENABLED: - return this.snooperEnabled; - case FORCE_UNICODE_FONT: - return this.forceUnicodeFont; - case BLOCK_ALTERNATIVES: - return this.allowBlockAlternatives; - case REDUCED_DEBUG_INFO: - return this.reducedDebugInfo; - case ENTITY_SHADOWS: - return this.field_181151_V; - case HUD_COORDS: - return this.hudCoords; - case HUD_FPS: - return this.hudFps; - case HUD_PLAYER: - return this.hudPlayer; - case HUD_STATS: - return this.hudStats; - case HUD_WORLD: - return this.hudWorld; - case HUD_24H: - return this.hud24h; - case CHUNK_FIX: - return this.chunkFix; - case FOG: - return this.fog; - case FULLSCREEN: - return this.mc.isFullScreen(); - case FNAW_SKINS: - return this.enableFNAWSkins; - case EAGLER_VSYNC: - return this.enableVsync; - case EAGLER_DYNAMIC_LIGHTS: - return this.enableDynamicLights; - case EAGLER_PROFANITY_FILTER: - return this.enableProfanityFilter; - default: - return false; - } - } - - /**+ - * Returns the translation of the given index in the given - * String array. If the index is smaller than 0 or greater - * than/equal to the length of the String array, it is changed - * to 0. - */ - private static String getTranslation(String[] parArrayOfString, int parInt1) { - if (parInt1 < 0 || parInt1 >= parArrayOfString.length) { - parInt1 = 0; - } - - return I18n.format(parArrayOfString[parInt1], new Object[0]); - } - - /**+ - * Gets a key binding. + /** + * + Gets a key binding. */ public String getKeyBinding(GameSettings.Options parOptions) { String s = I18n.format(parOptions.getEnumString(), new Object[0]) + ": "; @@ -690,9 +514,101 @@ public class GameSettings { } } - /**+ - * Loads the options from the options file. It appears that this - * has replaced the previous 'loadOptions' + public Set getModelParts() { + return ImmutableSet.copyOf(this.setModelParts); + } + + public float getOptionFloatValue(GameSettings.Options parOptions) { + return parOptions == GameSettings.Options.FOV ? this.fovSetting + : (parOptions == GameSettings.Options.GAMMA ? this.gammaSetting + : (parOptions == GameSettings.Options.SATURATION ? this.saturation + : (parOptions == GameSettings.Options.SENSITIVITY ? this.mouseSensitivity + : (parOptions == GameSettings.Options.CHAT_OPACITY ? this.chatOpacity + : (parOptions == GameSettings.Options.CHAT_HEIGHT_FOCUSED + ? this.chatHeightFocused + : (parOptions == GameSettings.Options.CHAT_HEIGHT_UNFOCUSED + ? this.chatHeightUnfocused + : (parOptions == GameSettings.Options.CHAT_SCALE + ? this.chatScale + : (parOptions == GameSettings.Options.CHAT_WIDTH + ? this.chatWidth + : (parOptions == GameSettings.Options.FRAMERATE_LIMIT + ? (float) this.limitFramerate + : (parOptions == GameSettings.Options.MIPMAP_LEVELS + ? (float) this.mipmapLevels + : (parOptions == GameSettings.Options.RENDER_DISTANCE + ? (float) this.renderDistanceChunks + : (parOptions == GameSettings.Options.EAGLER_TOUCH_CONTROL_OPACITY + ? this.touchControlOpacity + : 0.0F)))))))))))); + } + + public boolean getOptionOrdinalValue(GameSettings.Options parOptions) { + switch (parOptions) { + case INVERT_MOUSE: + return this.invertMouse; + case VIEW_BOBBING: + return this.viewBobbing; + case ANAGLYPH: + return this.anaglyph; + case FBO_ENABLE: + return this.fboEnable; + case CHAT_COLOR: + return this.chatColours; + case CHAT_LINKS: + return this.chatLinks; + case CHAT_LINKS_PROMPT: + return this.chatLinksPrompt; + case SNOOPER_ENABLED: + return this.snooperEnabled; + case FORCE_UNICODE_FONT: + return this.forceUnicodeFont; + case BLOCK_ALTERNATIVES: + return this.allowBlockAlternatives; + case REDUCED_DEBUG_INFO: + return this.reducedDebugInfo; + case ENTITY_SHADOWS: + return this.field_181151_V; + case HUD_COORDS: + return this.hudCoords; + case HUD_FPS: + return this.hudFps; + case HUD_PLAYER: + return this.hudPlayer; + case HUD_STATS: + return this.hudStats; + case HUD_WORLD: + return this.hudWorld; + case HUD_24H: + return this.hud24h; + case CHUNK_FIX: + return this.chunkFix; + case FOG: + return this.fog; + case FULLSCREEN: + return this.mc.isFullScreen(); + case FNAW_SKINS: + return this.enableFNAWSkins; + case EAGLER_VSYNC: + return this.enableVsync; + case EAGLER_DYNAMIC_LIGHTS: + return this.enableDynamicLights; + case EAGLER_PROFANITY_FILTER: + return this.enableProfanityFilter; + default: + return false; + } + } + + public float getSoundLevel(SoundCategory parSoundCategory) { + return this.mapSoundLevels.containsKey(parSoundCategory) + ? ((Float) this.mapSoundLevels.get(parSoundCategory)).floatValue() + : 1.0F; + } + + /** + * + Loads the options from the options file. It appears that this has replaced + * the previous 'loadOptions' */ public void loadOptions() { byte[] options = EagRuntime.getStorage("g"); @@ -702,9 +618,9 @@ public class GameSettings { loadOptions(options); } - /**+ - * Loads the options from the options file. It appears that this - * has replaced the previous 'loadOptions' + /** + * + Loads the options from the options file. It appears that this has replaced + * the previous 'loadOptions' */ public void loadOptions(byte[] data) { try { @@ -1072,6 +988,10 @@ public class GameSettings { touchControlOpacity = parseFloat(astring[1]); } + if (astring[0].equals("hideDefaultUsernameWarning")) { + this.hideDefaultUsernameWarning = astring[1].equals("true"); + } + deferredShaderConf.readOption(astring[0], astring[1]); } catch (Exception var8) { logger.warn("Skipping bad option: " + s); @@ -1103,15 +1023,15 @@ public class GameSettings { } - /**+ - * Parses a string into a float. + /** + * + Parses a string into a float. */ private float parseFloat(String parString1) { return parString1.equals("true") ? 1.0F : (parString1.equals("false") ? 0.0F : Float.parseFloat(parString1)); } - /**+ - * Saves the options to the options file. + /** + * + Saves the options to the options file. */ public void saveOptions() { byte[] data = writeOptions(); @@ -1122,6 +1042,283 @@ public class GameSettings { this.sendSettingsToServer(); } + /** + * + Send a client info packet with settings information to the server + */ + public void sendSettingsToServer() { + if (this.mc.thePlayer != null) { + int i = 0; + + for (EnumPlayerModelParts enumplayermodelparts : this.setModelParts) { + i |= enumplayermodelparts.getPartMask(); + } + + this.mc.thePlayer.sendQueue.addToSendQueue(new C15PacketClientSettings(this.language, + Math.max(this.renderDistanceChunks, 2), this.chatVisibility, this.chatColours, i)); + } + + } + + public void setModelPartEnabled(EnumPlayerModelParts parEnumPlayerModelParts, boolean parFlag) { + if (parFlag) { + this.setModelParts.add(parEnumPlayerModelParts); + } else { + this.setModelParts.remove(parEnumPlayerModelParts); + } + + this.sendSettingsToServer(); + } + + /** + * + If the specified option is controlled by a slider (float value), this will + * set the float value. + */ + public void setOptionFloatValue(GameSettings.Options parOptions, float parFloat1) { + if (parOptions == GameSettings.Options.SENSITIVITY) { + this.mouseSensitivity = parFloat1; + } + + if (parOptions == GameSettings.Options.FOV) { + this.fovSetting = parFloat1; + } + + if (parOptions == GameSettings.Options.GAMMA) { + this.gammaSetting = parFloat1; + } + + if (parOptions == GameSettings.Options.FRAMERATE_LIMIT) { + this.limitFramerate = (int) parFloat1; + } + + if (parOptions == GameSettings.Options.CHAT_OPACITY) { + this.chatOpacity = parFloat1; + this.mc.ingameGUI.getChatGUI().refreshChat(); + } + + if (parOptions == GameSettings.Options.CHAT_HEIGHT_FOCUSED) { + this.chatHeightFocused = parFloat1; + this.mc.ingameGUI.getChatGUI().refreshChat(); + } + + if (parOptions == GameSettings.Options.CHAT_HEIGHT_UNFOCUSED) { + this.chatHeightUnfocused = parFloat1; + this.mc.ingameGUI.getChatGUI().refreshChat(); + } + + if (parOptions == GameSettings.Options.CHAT_WIDTH) { + this.chatWidth = parFloat1; + this.mc.ingameGUI.getChatGUI().refreshChat(); + } + + if (parOptions == GameSettings.Options.CHAT_SCALE) { + this.chatScale = parFloat1; + this.mc.ingameGUI.getChatGUI().refreshChat(); + } + + if (parOptions == GameSettings.Options.MIPMAP_LEVELS) { + int i = this.mipmapLevels; + this.mipmapLevels = (int) parFloat1; + if ((float) i != parFloat1) { + this.mc.getTextureMapBlocks().setMipmapLevels(this.mipmapLevels); + this.mc.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); + this.mc.getTextureMapBlocks().setBlurMipmapDirect(false, this.mipmapLevels > 0); + this.mc.scheduleResourcesRefresh(); + } + } + + if (parOptions == GameSettings.Options.BLOCK_ALTERNATIVES) { + this.allowBlockAlternatives = !this.allowBlockAlternatives; + this.mc.renderGlobal.loadRenderers(); + } + + if (parOptions == GameSettings.Options.RENDER_DISTANCE) { + this.renderDistanceChunks = (int) parFloat1; + this.mc.renderGlobal.setDisplayListEntitiesDirty(); + } + + if (parOptions == GameSettings.Options.EAGLER_TOUCH_CONTROL_OPACITY) { + this.touchControlOpacity = parFloat1; + } + } + + /** + * + Sets a key binding and then saves all settings. + */ + public void setOptionKeyBinding(KeyBinding parKeyBinding, int parInt1) { + parKeyBinding.setKeyCode(parInt1); + this.saveOptions(); + } + + /** + * + For non-float options. Toggles the option on/off, or cycles through the + * list i.e. render distances. + */ + public void setOptionValue(GameSettings.Options parOptions, int parInt1) { + if (parOptions == GameSettings.Options.INVERT_MOUSE) { + this.invertMouse = !this.invertMouse; + } + + if (parOptions == GameSettings.Options.GUI_SCALE) { + this.guiScale = this.guiScale + parInt1 & 3; + } + + if (parOptions == GameSettings.Options.PARTICLES) { + this.particleSetting = (this.particleSetting + parInt1) % 3; + } + + if (parOptions == GameSettings.Options.VIEW_BOBBING) { + this.viewBobbing = !this.viewBobbing; + } + + if (parOptions == GameSettings.Options.RENDER_CLOUDS) { + this.clouds = (this.clouds + parInt1) % 3; + } + + if (parOptions == GameSettings.Options.FORCE_UNICODE_FONT) { + this.forceUnicodeFont = !this.forceUnicodeFont; + this.mc.fontRendererObj + .setUnicodeFlag(this.mc.getLanguageManager().isCurrentLocaleUnicode() || this.forceUnicodeFont); + } + + if (parOptions == GameSettings.Options.FBO_ENABLE) { + this.fboEnable = !this.fboEnable; + } + + if (parOptions == GameSettings.Options.ANAGLYPH) { + this.anaglyph = !this.anaglyph; + this.mc.loadingScreen.eaglerShow(I18n.format("resourcePack.load.refreshing"), + I18n.format("resourcePack.load.pleaseWait")); + this.mc.refreshResources(); + } + + if (parOptions == GameSettings.Options.GRAPHICS) { + this.fancyGraphics = !this.fancyGraphics; + this.mc.renderGlobal.loadRenderers(); + } + + if (parOptions == GameSettings.Options.AMBIENT_OCCLUSION) { + this.ambientOcclusion = (this.ambientOcclusion + parInt1) % 3; + this.mc.renderGlobal.loadRenderers(); + } + + if (parOptions == GameSettings.Options.CHAT_VISIBILITY) { + this.chatVisibility = EntityPlayer.EnumChatVisibility + .getEnumChatVisibility((this.chatVisibility.getChatVisibility() + parInt1) % 3); + } + + if (parOptions == GameSettings.Options.CHAT_COLOR) { + this.chatColours = !this.chatColours; + } + + if (parOptions == GameSettings.Options.CHAT_LINKS) { + this.chatLinks = !this.chatLinks; + } + + if (parOptions == GameSettings.Options.CHAT_LINKS_PROMPT) { + this.chatLinksPrompt = !this.chatLinksPrompt; + } + + if (parOptions == GameSettings.Options.SNOOPER_ENABLED) { + this.snooperEnabled = !this.snooperEnabled; + } + + if (parOptions == GameSettings.Options.BLOCK_ALTERNATIVES) { + this.allowBlockAlternatives = !this.allowBlockAlternatives; + this.mc.renderGlobal.loadRenderers(); + } + + if (parOptions == GameSettings.Options.REDUCED_DEBUG_INFO) { + this.reducedDebugInfo = !this.reducedDebugInfo; + } + + if (parOptions == GameSettings.Options.ENTITY_SHADOWS) { + this.field_181151_V = !this.field_181151_V; + } + + if (parOptions == GameSettings.Options.HUD_FPS) { + this.hudFps = !this.hudFps; + } + + if (parOptions == GameSettings.Options.HUD_COORDS) { + this.hudCoords = !this.hudCoords; + } + + if (parOptions == GameSettings.Options.HUD_PLAYER) { + this.hudPlayer = !this.hudPlayer; + } + + if (parOptions == GameSettings.Options.HUD_STATS) { + this.hudStats = !this.hudStats; + } + + if (parOptions == GameSettings.Options.HUD_WORLD) { + this.hudWorld = !this.hudWorld; + } + + if (parOptions == GameSettings.Options.HUD_24H) { + this.hud24h = !this.hud24h; + } + + if (parOptions == GameSettings.Options.CHUNK_FIX) { + this.chunkFix = !this.chunkFix; + } + + if (parOptions == GameSettings.Options.FOG) { + this.fog = !this.fog; + } + + if (parOptions == GameSettings.Options.FXAA) { + this.fxaa = (this.fxaa + parInt1) % 3; + } + + if (parOptions == GameSettings.Options.FULLSCREEN) { + this.mc.toggleFullscreen(); + } + + if (parOptions == GameSettings.Options.FNAW_SKINS) { + this.enableFNAWSkins = !this.enableFNAWSkins; + this.mc.getRenderManager().setEnableFNAWSkins(this.mc.getEnableFNAWSkins()); + } + + if (parOptions == GameSettings.Options.EAGLER_VSYNC) { + this.enableVsync = !this.enableVsync; + } + + if (parOptions == GameSettings.Options.EAGLER_DYNAMIC_LIGHTS) { + this.enableDynamicLights = !this.enableDynamicLights; + this.mc.renderGlobal.loadRenderers(); + } + + if (parOptions == GameSettings.Options.EAGLER_PROFANITY_FILTER) { + this.enableProfanityFilter = !this.enableProfanityFilter; + } + + this.saveOptions(); + } + + public void setSoundLevel(SoundCategory parSoundCategory, float parFloat1) { + this.mc.getSoundHandler().setSoundLevel(parSoundCategory, parFloat1); + this.mapSoundLevels.put(parSoundCategory, Float.valueOf(parFloat1)); + } + + public void switchModelPartEnabled(EnumPlayerModelParts parEnumPlayerModelParts) { + if (!this.getModelParts().contains(parEnumPlayerModelParts)) { + this.setModelParts.add(parEnumPlayerModelParts); + } else { + this.setModelParts.remove(parEnumPlayerModelParts); + } + + this.sendSettingsToServer(); + } + + private String toJSONArray(List e) { + JSONArray arr = new JSONArray(); + for (String s : e) { + arr.put(s); + } + return arr.toString(); + } + public byte[] writeOptions() { try { EaglerOutputStream bao = new EaglerOutputStream(); @@ -1213,6 +1410,7 @@ public class GameSettings { printwriter.println("screenRecordGameVolume:" + this.screenRecordGameVolume); printwriter.println("screenRecordMicVolume:" + this.screenRecordMicVolume); printwriter.println("touchControlOpacity:" + this.touchControlOpacity); + printwriter.println("hideDefaultUsernameWarning:" + this.hideDefaultUsernameWarning); for (KeyBinding keybinding : this.keyBindings) { printwriter.println("key_" + keybinding.getKeyDescription() + ":" + keybinding.getKeyCode()); @@ -1241,192 +1439,4 @@ public class GameSettings { } } - - public float getSoundLevel(SoundCategory parSoundCategory) { - return this.mapSoundLevels.containsKey(parSoundCategory) - ? ((Float) this.mapSoundLevels.get(parSoundCategory)).floatValue() - : 1.0F; - } - - public void setSoundLevel(SoundCategory parSoundCategory, float parFloat1) { - this.mc.getSoundHandler().setSoundLevel(parSoundCategory, parFloat1); - this.mapSoundLevels.put(parSoundCategory, Float.valueOf(parFloat1)); - } - - /**+ - * Send a client info packet with settings information to the - * server - */ - public void sendSettingsToServer() { - if (this.mc.thePlayer != null) { - int i = 0; - - for (EnumPlayerModelParts enumplayermodelparts : this.setModelParts) { - i |= enumplayermodelparts.getPartMask(); - } - - this.mc.thePlayer.sendQueue.addToSendQueue(new C15PacketClientSettings(this.language, - Math.max(this.renderDistanceChunks, 2), this.chatVisibility, this.chatColours, i)); - } - - } - - public Set getModelParts() { - return ImmutableSet.copyOf(this.setModelParts); - } - - public void setModelPartEnabled(EnumPlayerModelParts parEnumPlayerModelParts, boolean parFlag) { - if (parFlag) { - this.setModelParts.add(parEnumPlayerModelParts); - } else { - this.setModelParts.remove(parEnumPlayerModelParts); - } - - this.sendSettingsToServer(); - } - - public void switchModelPartEnabled(EnumPlayerModelParts parEnumPlayerModelParts) { - if (!this.getModelParts().contains(parEnumPlayerModelParts)) { - this.setModelParts.add(parEnumPlayerModelParts); - } else { - this.setModelParts.remove(parEnumPlayerModelParts); - } - - this.sendSettingsToServer(); - } - - public int func_181147_e() { - return this.renderDistanceChunks >= 4 ? this.clouds : 0; - } - - public boolean func_181148_f() { - return this.field_181150_U; - } - - private String toJSONArray(List e) { - JSONArray arr = new JSONArray(); - for (String s : e) { - arr.put(s); - } - return arr.toString(); - } - - public static enum Options { - INVERT_MOUSE("options.invertMouse", false, true), SENSITIVITY("options.sensitivity", true, false), - FOV("options.fov", true, false, 30.0F, 110.0F, 1.0F), GAMMA("options.gamma", true, false), - SATURATION("options.saturation", true, false), - RENDER_DISTANCE("options.renderDistance", true, false, 1.0F, 18.0F, 1.0F), - VIEW_BOBBING("options.viewBobbing", false, true), ANAGLYPH("options.anaglyph", false, true), - FRAMERATE_LIMIT("options.framerateLimit", true, false, 10.0F, 260.0F, 10.0F), - FBO_ENABLE("options.fboEnable", false, true), RENDER_CLOUDS("options.renderClouds", false, false), - GRAPHICS("options.graphics", false, false), AMBIENT_OCCLUSION("options.ao", false, false), - GUI_SCALE("options.guiScale", false, false), PARTICLES("options.particles", false, false), - CHAT_VISIBILITY("options.chat.visibility", false, false), CHAT_COLOR("options.chat.color", false, true), - CHAT_LINKS("options.chat.links", false, true), CHAT_OPACITY("options.chat.opacity", true, false), - CHAT_LINKS_PROMPT("options.chat.links.prompt", false, true), SNOOPER_ENABLED("options.snooper", false, true), - CHAT_SCALE("options.chat.scale", true, false), CHAT_WIDTH("options.chat.width", true, false), - CHAT_HEIGHT_FOCUSED("options.chat.height.focused", true, false), - CHAT_HEIGHT_UNFOCUSED("options.chat.height.unfocused", true, false), - MIPMAP_LEVELS("options.mipmapLevels", true, false, 0.0F, 4.0F, 1.0F), - FORCE_UNICODE_FONT("options.forceUnicodeFont", false, true), - STREAM_BYTES_PER_PIXEL("options.stream.bytesPerPixel", true, false), - STREAM_VOLUME_MIC("options.stream.micVolumne", true, false), - STREAM_VOLUME_SYSTEM("options.stream.systemVolume", true, false), - STREAM_KBPS("options.stream.kbps", true, false), STREAM_FPS("options.stream.fps", true, false), - STREAM_COMPRESSION("options.stream.compression", false, false), - STREAM_SEND_METADATA("options.stream.sendMetadata", false, true), - STREAM_CHAT_ENABLED("options.stream.chat.enabled", false, false), - STREAM_CHAT_USER_FILTER("options.stream.chat.userFilter", false, false), - STREAM_MIC_TOGGLE_BEHAVIOR("options.stream.micToggleBehavior", false, false), - BLOCK_ALTERNATIVES("options.blockAlternatives", false, true), - REDUCED_DEBUG_INFO("options.reducedDebugInfo", false, true), - ENTITY_SHADOWS("options.entityShadows", false, true), HUD_FPS("options.hud.fps", false, true), - HUD_COORDS("options.hud.coords", false, true), HUD_STATS("options.hud.stats", false, true), - HUD_WORLD("options.hud.world", false, true), HUD_PLAYER("options.hud.player", false, true), - HUD_24H("options.hud.24h", false, true), CHUNK_FIX("options.chunkFix", false, true), - FOG("options.fog", false, true), FXAA("options.fxaa", false, false), - FULLSCREEN("options.fullscreen", false, true), - FNAW_SKINS("options.skinCustomisation.enableFNAWSkins", false, true), - EAGLER_VSYNC("options.vsync", false, true), EAGLER_DYNAMIC_LIGHTS("options.dynamicLights", false, true), - EAGLER_PROFANITY_FILTER("options.profanityFilterButton", false, true), - EAGLER_TOUCH_CONTROL_OPACITY("options.touchControlOpacity", true, false); - - private final boolean enumFloat; - private final boolean enumBoolean; - private final String enumString; - private final float valueStep; - private float valueMin; - private float valueMax; - - public static GameSettings.Options getEnumOptions(int parInt1) { - for (GameSettings.Options gamesettings$options : values()) { - if (gamesettings$options.returnEnumOrdinal() == parInt1) { - return gamesettings$options; - } - } - - return null; - } - - private Options(String parString2, boolean parFlag, boolean parFlag2) { - this(parString2, parFlag, parFlag2, 0.0F, 1.0F, 0.0F); - } - - private Options(String parString2, boolean parFlag, boolean parFlag2, float parFloat1, float parFloat2, - float parFloat3) { - this.enumString = parString2; - this.enumFloat = parFlag; - this.enumBoolean = parFlag2; - this.valueMin = parFloat1; - this.valueMax = parFloat2; - this.valueStep = parFloat3; - } - - public boolean getEnumFloat() { - return this.enumFloat; - } - - public boolean getEnumBoolean() { - return this.enumBoolean; - } - - public int returnEnumOrdinal() { - return this.ordinal(); - } - - public String getEnumString() { - return this.enumString; - } - - public float getValueMax() { - return this.valueMax; - } - - public void setValueMax(float parFloat1) { - this.valueMax = parFloat1; - } - - public float normalizeValue(float parFloat1) { - return MathHelper.clamp_float( - (this.snapToStepClamp(parFloat1) - this.valueMin) / (this.valueMax - this.valueMin), 0.0F, 1.0F); - } - - public float denormalizeValue(float parFloat1) { - return this.snapToStepClamp( - this.valueMin + (this.valueMax - this.valueMin) * MathHelper.clamp_float(parFloat1, 0.0F, 1.0F)); - } - - public float snapToStepClamp(float parFloat1) { - parFloat1 = this.snapToStep(parFloat1); - return MathHelper.clamp_float(parFloat1, this.valueMin, this.valueMax); - } - - protected float snapToStep(float parFloat1) { - if (this.valueStep > 0.0F) { - parFloat1 = this.valueStep * (float) Math.round(parFloat1 / this.valueStep); - } - - return parFloat1; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/settings/KeyBinding.java b/src/game/java/net/minecraft/client/settings/KeyBinding.java index 39c2a2a3..417f6ce0 100644 --- a/src/game/java/net/minecraft/client/settings/KeyBinding.java +++ b/src/game/java/net/minecraft/client/settings/KeyBinding.java @@ -9,22 +9,25 @@ import com.google.common.collect.Sets; import net.minecraft.client.resources.I18n; import net.minecraft.util.IntHashMap; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,12 +36,10 @@ public class KeyBinding implements Comparable { private static final List keybindArray = Lists.newArrayList(); private static final IntHashMap hash = new IntHashMap(); private static final Set keybindSet = Sets.newHashSet(); - private final String keyDescription; - private final int keyCodeDefault; - private final String keyCategory; - private int keyCode; - private boolean pressed; - private int pressTime; + + public static Set getKeybinds() { + return keybindSet; + } public static void onTick(int keyCode) { if (keyCode != 0) { @@ -50,6 +51,16 @@ public class KeyBinding implements Comparable { } } + public static void resetKeyBindingArrayAndHash() { + hash.clearMap(); + + for (int i = 0, l = keybindArray.size(); i < l; ++i) { + KeyBinding keybinding = keybindArray.get(i); + hash.addKey(keybinding.keyCode, keybinding); + } + + } + public static void setKeyBindState(int keyCode, boolean pressed) { if (keyCode != 0) { KeyBinding keybinding = (KeyBinding) hash.lookup(keyCode); @@ -67,19 +78,17 @@ public class KeyBinding implements Comparable { } - public static void resetKeyBindingArrayAndHash() { - hash.clearMap(); + private final String keyDescription; - for (int i = 0, l = keybindArray.size(); i < l; ++i) { - KeyBinding keybinding = keybindArray.get(i); - hash.addKey(keybinding.keyCode, keybinding); - } + private final int keyCodeDefault; - } + private final String keyCategory; - public static Set getKeybinds() { - return keybindSet; - } + private int keyCode; + + private boolean pressed; + + private int pressTime; public KeyBinding(String description, int keyCode, String category) { this.keyDescription = description; @@ -91,53 +100,6 @@ public class KeyBinding implements Comparable { keybindSet.add(category); } - /**+ - * Returns true if the key is pressed (used for continuous - * querying). Should be used in tickers. - */ - public boolean isKeyDown() { - return this.pressed; - } - - public String getKeyCategory() { - return this.keyCategory; - } - - /**+ - * Returns true on the initial key press. For continuous - * querying use {@link isKeyDown()}. Should be used in key - * events. - */ - public boolean isPressed() { - if (this.pressTime == 0) { - return false; - } else { - --this.pressTime; - return true; - } - } - - private void unpressKey() { - this.pressTime = 0; - this.pressed = false; - } - - public String getKeyDescription() { - return this.keyDescription; - } - - public int getKeyCodeDefault() { - return this.keyCodeDefault; - } - - public int getKeyCode() { - return this.keyCode; - } - - public void setKeyCode(int keyCode) { - this.keyCode = keyCode; - } - public int compareTo(KeyBinding keybinding) { int i = I18n.format(this.keyCategory, new Object[0]) .compareTo(I18n.format(keybinding.keyCategory, new Object[0])); @@ -148,4 +110,50 @@ public class KeyBinding implements Comparable { return i; } + + public String getKeyCategory() { + return this.keyCategory; + } + + public int getKeyCode() { + return this.keyCode; + } + + public int getKeyCodeDefault() { + return this.keyCodeDefault; + } + + public String getKeyDescription() { + return this.keyDescription; + } + + /** + * + Returns true if the key is pressed (used for continuous querying). Should + * be used in tickers. + */ + public boolean isKeyDown() { + return this.pressed; + } + + /** + * + Returns true on the initial key press. For continuous querying use + * {@link isKeyDown()}. Should be used in key events. + */ + public boolean isPressed() { + if (this.pressTime == 0) { + return false; + } else { + --this.pressTime; + return true; + } + } + + public void setKeyCode(int keyCode) { + this.keyCode = keyCode; + } + + private void unpressKey() { + this.pressTime = 0; + this.pressed = false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/stream/IStream.java b/src/game/java/net/minecraft/client/stream/IStream.java index 51834e33..b1399267 100644 --- a/src/game/java/net/minecraft/client/stream/IStream.java +++ b/src/game/java/net/minecraft/client/stream/IStream.java @@ -1,88 +1,91 @@ package net.minecraft.client.stream; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IStream { - /**+ - * Shuts down a steam - */ - void shutdownStream(); + public static enum AuthFailureReason { + ERROR, INVALID_TOKEN; + } - void func_152935_j(); + boolean func_152908_z(); + + void func_152909_x(); + + boolean func_152913_F(); + + void func_152917_b(String var1); + + IStream.AuthFailureReason func_152918_H(); + + int func_152920_A(); + + String func_152921_C(); void func_152922_k(); - boolean func_152936_l(); + boolean func_152927_B(); - boolean isReadyToBroadcast(); + boolean func_152928_D(); + + boolean func_152929_G(); + + void func_152930_t(); + + void func_152935_j(); + + boolean func_152936_l(); boolean isBroadcasting(); boolean isPaused(); - void requestCommercial(); + boolean isReadyToBroadcast(); - /**+ - * pauses a stream + /** + * + mutes or unmutes the microphone based on the boolean parameter passed into + * the method + */ + void muteMicrophone(boolean var1); + + /** + * + pauses a stream */ void pause(); - /**+ - * unpauses a stream + void requestCommercial(); + + /** + * + Shuts down a steam + */ + void shutdownStream(); + + void stopBroadcasting(); + + /** + * + unpauses a stream */ void unpause(); void updateStreamVolume(); - - void func_152930_t(); - - void stopBroadcasting(); - - void func_152909_x(); - - boolean func_152908_z(); - - int func_152920_A(); - - boolean func_152927_B(); - - String func_152921_C(); - - void func_152917_b(String var1); - - boolean func_152928_D(); - - boolean func_152913_F(); - - /**+ - * mutes or unmutes the microphone based on the boolean - * parameter passed into the method - */ - void muteMicrophone(boolean var1); - - boolean func_152929_G(); - - IStream.AuthFailureReason func_152918_H(); - - public static enum AuthFailureReason { - ERROR, INVALID_TOKEN; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/util/JsonBlendingMode.java b/src/game/java/net/minecraft/client/util/JsonBlendingMode.java index e2acc306..3361c4c3 100644 --- a/src/game/java/net/minecraft/client/util/JsonBlendingMode.java +++ b/src/game/java/net/minecraft/client/util/JsonBlendingMode.java @@ -5,112 +5,58 @@ import org.json.JSONObject; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JsonBlendingMode { private static JsonBlendingMode field_148118_a = null; - private final int field_148116_b; - private final int field_148117_c; - private final int field_148114_d; - private final int field_148115_e; - private final int field_148112_f; - private final boolean field_148113_g; - private final boolean field_148119_h; - private JsonBlendingMode(boolean parFlag, boolean parFlag2, int parInt1, int parInt2, int parInt3, int parInt4, - int parInt5) { - this.field_148113_g = parFlag; - this.field_148116_b = parInt1; - this.field_148114_d = parInt2; - this.field_148117_c = parInt3; - this.field_148115_e = parInt4; - this.field_148119_h = parFlag2; - this.field_148112_f = parInt5; + private static int func_148107_b(String parString1) { + String s = parString1.trim().toLowerCase(); + s = s.replaceAll("_", ""); + s = s.replaceAll("one", "1"); + s = s.replaceAll("zero", "0"); + s = s.replaceAll("minus", "-"); + return s.equals("0") ? 0 + : (s.equals("1") ? 1 + : (s.equals("srccolor") ? 768 + : (s.equals("1-srccolor") ? 769 + : (s.equals("dstcolor") ? 774 + : (s.equals("1-dstcolor") ? 775 + : (s.equals("srcalpha") ? 770 + : (s.equals("1-srcalpha") ? 771 + : (s.equals("dstalpha") ? 772 + : (s.equals("1-dstalpha") ? 773 + : -1))))))))); } - public JsonBlendingMode() { - this(false, true, 1, 0, 1, 0, '\u8006'); - } - - public JsonBlendingMode(int parInt1, int parInt2, int parInt3) { - this(false, false, parInt1, parInt2, parInt1, parInt2, parInt3); - } - - public JsonBlendingMode(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5) { - this(true, false, parInt1, parInt2, parInt3, parInt4, parInt5); - } - - public void func_148109_a() { - if (!this.equals(field_148118_a)) { - if (field_148118_a == null || this.field_148119_h != field_148118_a.func_148111_b()) { - field_148118_a = this; - if (this.field_148119_h) { - GlStateManager.disableBlend(); - return; - } - - GlStateManager.enableBlend(); - } - - EaglercraftGPU.glBlendEquation(this.field_148112_f); - if (this.field_148113_g) { - GlStateManager.tryBlendFuncSeparate(this.field_148116_b, this.field_148114_d, this.field_148117_c, - this.field_148115_e); - } else { - GlStateManager.blendFunc(this.field_148116_b, this.field_148114_d); - } - - } - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof JsonBlendingMode)) { - return false; - } else { - JsonBlendingMode jsonblendingmode = (JsonBlendingMode) object; - return this.field_148112_f != jsonblendingmode.field_148112_f ? false - : (this.field_148115_e != jsonblendingmode.field_148115_e ? false - : (this.field_148114_d != jsonblendingmode.field_148114_d ? false - : (this.field_148119_h != jsonblendingmode.field_148119_h ? false - : (this.field_148113_g != jsonblendingmode.field_148113_g ? false - : (this.field_148117_c != jsonblendingmode.field_148117_c ? false - : this.field_148116_b == jsonblendingmode.field_148116_b))))); - } - } - - public int hashCode() { - int i = this.field_148116_b; - i = 31 * i + this.field_148117_c; - i = 31 * i + this.field_148114_d; - i = 31 * i + this.field_148115_e; - i = 31 * i + this.field_148112_f; - i = 31 * i + (this.field_148113_g ? 1 : 0); - i = 31 * i + (this.field_148119_h ? 1 : 0); - return i; - } - - public boolean func_148111_b() { - return this.field_148119_h; + private static int func_148108_a(String parString1) { + String s = parString1.trim().toLowerCase(); + return s.equals("add") ? '\u8006' + : (s.equals("subtract") ? '\u800a' + : (s.equals("reversesubtract") ? '\u800b' + : (s.equals("reverse_subtract") ? '\u800b' + : (s.equals("min") ? '\u8007' : (s.equals("max") ? '\u8008' : '\u8006'))))); } public static JsonBlendingMode func_148110_a(JSONObject parJsonObject) { @@ -168,31 +114,92 @@ public class JsonBlendingMode { } } - private static int func_148108_a(String parString1) { - String s = parString1.trim().toLowerCase(); - return s.equals("add") ? '\u8006' - : (s.equals("subtract") ? '\u800a' - : (s.equals("reversesubtract") ? '\u800b' - : (s.equals("reverse_subtract") ? '\u800b' - : (s.equals("min") ? '\u8007' : (s.equals("max") ? '\u8008' : '\u8006'))))); + private final int field_148116_b; + private final int field_148117_c; + private final int field_148114_d; + private final int field_148115_e; + + private final int field_148112_f; + + private final boolean field_148113_g; + + private final boolean field_148119_h; + + public JsonBlendingMode() { + this(false, true, 1, 0, 1, 0, '\u8006'); } - private static int func_148107_b(String parString1) { - String s = parString1.trim().toLowerCase(); - s = s.replaceAll("_", ""); - s = s.replaceAll("one", "1"); - s = s.replaceAll("zero", "0"); - s = s.replaceAll("minus", "-"); - return s.equals("0") ? 0 - : (s.equals("1") ? 1 - : (s.equals("srccolor") ? 768 - : (s.equals("1-srccolor") ? 769 - : (s.equals("dstcolor") ? 774 - : (s.equals("1-dstcolor") ? 775 - : (s.equals("srcalpha") ? 770 - : (s.equals("1-srcalpha") ? 771 - : (s.equals("dstalpha") ? 772 - : (s.equals("1-dstalpha") ? 773 - : -1))))))))); + private JsonBlendingMode(boolean parFlag, boolean parFlag2, int parInt1, int parInt2, int parInt3, int parInt4, + int parInt5) { + this.field_148113_g = parFlag; + this.field_148116_b = parInt1; + this.field_148114_d = parInt2; + this.field_148117_c = parInt3; + this.field_148115_e = parInt4; + this.field_148119_h = parFlag2; + this.field_148112_f = parInt5; + } + + public JsonBlendingMode(int parInt1, int parInt2, int parInt3) { + this(false, false, parInt1, parInt2, parInt1, parInt2, parInt3); + } + + public JsonBlendingMode(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5) { + this(true, false, parInt1, parInt2, parInt3, parInt4, parInt5); + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof JsonBlendingMode)) { + return false; + } else { + JsonBlendingMode jsonblendingmode = (JsonBlendingMode) object; + return this.field_148112_f != jsonblendingmode.field_148112_f ? false + : (this.field_148115_e != jsonblendingmode.field_148115_e ? false + : (this.field_148114_d != jsonblendingmode.field_148114_d ? false + : (this.field_148119_h != jsonblendingmode.field_148119_h ? false + : (this.field_148113_g != jsonblendingmode.field_148113_g ? false + : (this.field_148117_c != jsonblendingmode.field_148117_c ? false + : this.field_148116_b == jsonblendingmode.field_148116_b))))); + } + } + + public void func_148109_a() { + if (!this.equals(field_148118_a)) { + if (field_148118_a == null || this.field_148119_h != field_148118_a.func_148111_b()) { + field_148118_a = this; + if (this.field_148119_h) { + GlStateManager.disableBlend(); + return; + } + + GlStateManager.enableBlend(); + } + + EaglercraftGPU.glBlendEquation(this.field_148112_f); + if (this.field_148113_g) { + GlStateManager.tryBlendFuncSeparate(this.field_148116_b, this.field_148114_d, this.field_148117_c, + this.field_148115_e); + } else { + GlStateManager.blendFunc(this.field_148116_b, this.field_148114_d); + } + + } + } + + public boolean func_148111_b() { + return this.field_148119_h; + } + + public int hashCode() { + int i = this.field_148116_b; + i = 31 * i + this.field_148117_c; + i = 31 * i + this.field_148114_d; + i = 31 * i + this.field_148115_e; + i = 31 * i + this.field_148112_f; + i = 31 * i + (this.field_148113_g ? 1 : 0); + i = 31 * i + (this.field_148119_h ? 1 : 0); + return i; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/client/util/JsonException.java b/src/game/java/net/minecraft/client/util/JsonException.java index ba546fa4..d7860156 100644 --- a/src/game/java/net/minecraft/client/util/JsonException.java +++ b/src/game/java/net/minecraft/client/util/JsonException.java @@ -8,28 +8,70 @@ import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JsonException extends IOException { + public static class Entry { + private String field_151376_a; + private final List field_151375_b; + + private Entry() { + this.field_151376_a = null; + this.field_151375_b = Lists.newArrayList(); + } + + public String func_151372_b() { + return StringUtils.join(this.field_151375_b, "->"); + } + + private void func_151373_a(String parString1) { + this.field_151375_b.add(0, parString1); + } + + public String toString() { + return this.field_151376_a != null + ? (!this.field_151375_b.isEmpty() ? this.field_151376_a + " " + this.func_151372_b() + : this.field_151376_a) + : (!this.field_151375_b.isEmpty() ? "(Unknown file) " + this.func_151372_b() : "(Unknown file)"); + } + } + + public static JsonException func_151379_a(Exception parException) { + if (parException instanceof JsonException) { + return (JsonException) parException; + } else { + String s = parException.getMessage(); + if (parException instanceof FileNotFoundException) { + s = "File not found"; + } + + return new JsonException(s, parException); + } + } + private final List field_151383_a = Lists.newArrayList(); + private final String field_151382_b; public JsonException(String parString1) { @@ -56,42 +98,4 @@ public class JsonException extends IOException { return "Invalid " + ((JsonException.Entry) this.field_151383_a.get(this.field_151383_a.size() - 1)).toString() + ": " + this.field_151382_b; } - - public static JsonException func_151379_a(Exception parException) { - if (parException instanceof JsonException) { - return (JsonException) parException; - } else { - String s = parException.getMessage(); - if (parException instanceof FileNotFoundException) { - s = "File not found"; - } - - return new JsonException(s, parException); - } - } - - public static class Entry { - private String field_151376_a; - private final List field_151375_b; - - private Entry() { - this.field_151376_a = null; - this.field_151375_b = Lists.newArrayList(); - } - - private void func_151373_a(String parString1) { - this.field_151375_b.add(0, parString1); - } - - public String func_151372_b() { - return StringUtils.join(this.field_151375_b, "->"); - } - - public String toString() { - return this.field_151376_a != null - ? (!this.field_151375_b.isEmpty() ? this.field_151376_a + " " + this.func_151372_b() - : this.field_151376_a) - : (!this.field_151375_b.isEmpty() ? "(Unknown file) " + this.func_151372_b() : "(Unknown file)"); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandBase.java b/src/game/java/net/minecraft/command/CommandBase.java index 17f6c57b..62685712 100644 --- a/src/game/java/net/minecraft/command/CommandBase.java +++ b/src/game/java/net/minecraft/command/CommandBase.java @@ -1,15 +1,16 @@ package net.minecraft.command; -import com.google.common.base.Functions; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.primitives.Doubles; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; + +import com.google.common.base.Functions; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.primitives.Doubles; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -21,220 +22,81 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class CommandBase implements ICommand { + public static class CoordinateArg { + private final double field_179633_a; + private final double field_179631_b; + private final boolean field_179632_c; + + protected CoordinateArg(double parDouble1, double parDouble2, boolean parFlag) { + this.field_179633_a = parDouble1; + this.field_179631_b = parDouble2; + this.field_179632_c = parFlag; + } + + public double func_179628_a() { + return this.field_179633_a; + } + + public double func_179629_b() { + return this.field_179631_b; + } + + public boolean func_179630_c() { + return this.field_179632_c; + } + } + private static IAdminCommand theAdmin; - /**+ - * Return the required permission level for this command. + /** + * + Builds a string starting at startPos */ - public int getRequiredPermissionLevel() { - return 4; - } + public static String buildString(String[] args, int startPos) { + StringBuilder stringbuilder = new StringBuilder(); - /**+ - * Gets a list of aliases for this command - */ - public List getCommandAliases() { - return Collections.emptyList(); - } - - /**+ - * Returns true if the given command sender is allowed to use - * this command. - */ - public boolean canCommandSenderUseCommand(ICommandSender icommandsender) { - return icommandsender.canCommandSenderUseCommand(this.getRequiredPermissionLevel(), this.getCommandName()); - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] var2, BlockPos var3) { - return null; - } - - public static int parseInt(String input) throws NumberInvalidException { - try { - return Integer.parseInt(input); - } catch (NumberFormatException var2) { - throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); - } - } - - public static int parseInt(String input, int min) throws NumberInvalidException { - return parseInt(input, min, Integer.MAX_VALUE); - } - - public static int parseInt(String input, int min, int max) throws NumberInvalidException { - int i = parseInt(input); - if (i < min) { - throw new NumberInvalidException("commands.generic.num.tooSmall", - new Object[] { Integer.valueOf(i), Integer.valueOf(min) }); - } else if (i > max) { - throw new NumberInvalidException("commands.generic.num.tooBig", - new Object[] { Integer.valueOf(i), Integer.valueOf(max) }); - } else { - return i; - } - } - - public static long parseLong(String input) throws NumberInvalidException { - try { - return Long.parseLong(input); - } catch (NumberFormatException var2) { - throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); - } - } - - public static long parseLong(String input, long min, long max) throws NumberInvalidException { - long i = parseLong(input); - if (i < min) { - throw new NumberInvalidException("commands.generic.num.tooSmall", - new Object[] { Long.valueOf(i), Long.valueOf(min) }); - } else if (i > max) { - throw new NumberInvalidException("commands.generic.num.tooBig", - new Object[] { Long.valueOf(i), Long.valueOf(max) }); - } else { - return i; - } - } - - public static BlockPos parseBlockPos(ICommandSender sender, String[] args, int startIndex, boolean centerBlock) - throws NumberInvalidException { - BlockPos blockpos = sender.getPosition(); - return new BlockPos(parseDouble((double) blockpos.getX(), args[startIndex], -30000000, 30000000, centerBlock), - parseDouble((double) blockpos.getY(), args[startIndex + 1], 0, 256, false), - parseDouble((double) blockpos.getZ(), args[startIndex + 2], -30000000, 30000000, centerBlock)); - } - - public static double parseDouble(String input) throws NumberInvalidException { - try { - double d0 = Double.parseDouble(input); - if (!Doubles.isFinite(d0)) { - throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); - } else { - return d0; + for (int i = startPos; i < args.length; ++i) { + if (i > startPos) { + stringbuilder.append(" "); } - } catch (NumberFormatException var3) { - throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); + + String s = args[i]; + stringbuilder.append(s); } + + return stringbuilder.toString(); } - public static double parseDouble(String input, double min) throws NumberInvalidException { - return parseDouble(input, min, Double.MAX_VALUE); - } - - public static double parseDouble(String input, double min, double max) throws NumberInvalidException { - double d0 = parseDouble(input); - if (d0 < min) { - throw new NumberInvalidException("commands.generic.double.tooSmall", - new Object[] { Double.valueOf(d0), Double.valueOf(min) }); - } else if (d0 > max) { - throw new NumberInvalidException("commands.generic.double.tooBig", - new Object[] { Double.valueOf(d0), Double.valueOf(max) }); - } else { - return d0; - } - } - - public static boolean parseBoolean(String input) throws CommandException { - if (!input.equals("true") && !input.equals("1")) { - if (!input.equals("false") && !input.equals("0")) { - throw new CommandException("commands.generic.boolean.invalid", new Object[] { input }); - } else { - return false; - } - } else { - return true; - } - } - - /**+ - * Returns the given ICommandSender as a EntityPlayer or throw - * an exception. + /** + * + Returns true if the given substring is exactly equal to the start of the + * given string (case insensitive). */ - public static EntityPlayerMP getCommandSenderAsPlayer(ICommandSender sender) throws PlayerNotFoundException { - if (sender instanceof EntityPlayerMP) { - return (EntityPlayerMP) sender; - } else { - throw new PlayerNotFoundException("You must specify which player you wish to perform this action on.", - new Object[0]); - } - } - - public static EntityPlayerMP getPlayer(ICommandSender sender, String username) throws PlayerNotFoundException { - EntityPlayerMP entityplayermp = PlayerSelector.matchOnePlayer(sender, username); - if (entityplayermp == null) { - try { - entityplayermp = MinecraftServer.getServer().getConfigurationManager() - .getPlayerByUUID(EaglercraftUUID.fromString(username)); - } catch (IllegalArgumentException var4) { - ; - } - } - - if (entityplayermp == null) { - entityplayermp = MinecraftServer.getServer().getConfigurationManager().getPlayerByUsername(username); - } - - if (entityplayermp == null) { - throw new PlayerNotFoundException(); - } else { - return entityplayermp; - } - } - - public static Entity func_175768_b(ICommandSender parICommandSender, String parString1) - throws EntityNotFoundException { - return getEntity(parICommandSender, parString1, Entity.class); - } - - public static T getEntity(ICommandSender commandSender, String parString1, - Class parClass1) throws EntityNotFoundException { - Object object = PlayerSelector.matchOneEntity(commandSender, parString1, parClass1); - MinecraftServer minecraftserver = MinecraftServer.getServer(); - if (object == null) { - object = minecraftserver.getConfigurationManager().getPlayerByUsername(parString1); - } - - if (object == null) { - try { - EaglercraftUUID uuid = EaglercraftUUID.fromString(parString1); - object = minecraftserver.getEntityFromUuid(uuid); - if (object == null) { - object = minecraftserver.getConfigurationManager().getPlayerByUUID(uuid); - } - } catch (IllegalArgumentException var6) { - throw new EntityNotFoundException("commands.generic.entity.invalidUuid", new Object[0]); - } - } - - if (object != null && parClass1.isAssignableFrom(object.getClass())) { - return (T) object; - } else { - throw new EntityNotFoundException(); - } + public static boolean doesStringStartWith(String original, String region) { + return region.regionMatches(true, 0, original, 0, original.length()); } public static List func_175763_c(ICommandSender parICommandSender, String parString1) @@ -244,36 +106,69 @@ public abstract class CommandBase implements ICommand { : Lists.newArrayList(new Entity[] { func_175768_b(parICommandSender, parString1) })); } - public static String getPlayerName(ICommandSender sender, String query) throws PlayerNotFoundException { - try { - return getPlayer(sender, query).getName(); - } catch (PlayerNotFoundException playernotfoundexception) { - if (PlayerSelector.hasArguments(query)) { - throw playernotfoundexception; + public static Entity func_175768_b(ICommandSender parICommandSender, String parString1) + throws EntityNotFoundException { + return getEntity(parICommandSender, parString1, Entity.class); + } + + public static List func_175771_a(String[] parArrayOfString, int parInt1, BlockPos parBlockPos) { + if (parBlockPos == null) { + return null; + } else { + int i = parArrayOfString.length - 1; + String s; + if (i == parInt1) { + s = Integer.toString(parBlockPos.getX()); + } else if (i == parInt1 + 1) { + s = Integer.toString(parBlockPos.getY()); } else { - return query; + if (i != parInt1 + 2) { + return null; + } + + s = Integer.toString(parBlockPos.getZ()); } + + return Lists.newArrayList(new String[] { s }); } } - /**+ - * Attempts to retrieve an entity's name, first assuming that - * the entity is a player, and then exhausting all other - * possibilities. - */ - public static String getEntityName(ICommandSender parICommandSender, String parString1) - throws EntityNotFoundException { - try { - return getPlayer(parICommandSender, parString1).getName(); - } catch (PlayerNotFoundException var5) { - try { - return func_175768_b(parICommandSender, parString1).getUniqueID().toString(); - } catch (EntityNotFoundException entitynotfoundexception) { - if (PlayerSelector.hasArguments(parString1)) { - throw entitynotfoundexception; - } else { - return parString1; + public static List func_181043_b(String[] parArrayOfString, int parInt1, BlockPos parBlockPos) { + if (parBlockPos == null) { + return null; + } else { + int i = parArrayOfString.length - 1; + String s; + if (i == parInt1) { + s = Integer.toString(parBlockPos.getX()); + } else { + if (i != parInt1 + 1) { + return null; } + + s = Integer.toString(parBlockPos.getZ()); + } + + return Lists.newArrayList(new String[] { s }); + } + } + + /** + * + Gets the Block specified by the given text string. First checks the block + * registry, then tries by parsing the string as an integer ID (deprecated). + * Warns the sender if we matched by parsing the ID. Throws if the block wasn't + * found. Returns the block if it was found. + */ + public static Block getBlockByText(ICommandSender sender, String id) throws NumberInvalidException { + ResourceLocation resourcelocation = new ResourceLocation(id); + if (!Block.blockRegistry.containsKey(resourcelocation)) { + throw new NumberInvalidException("commands.give.block.notFound", new Object[] { resourcelocation }); + } else { + Block block = (Block) Block.blockRegistry.getObject(resourcelocation); + if (block == null) { + throw new NumberInvalidException("commands.give.block.notFound", new Object[] { resourcelocation }); + } else { + return block; } } } @@ -310,24 +205,245 @@ public abstract class CommandBase implements ICommand { return chatcomponenttext; } - /**+ - * Builds a string starting at startPos + /** + * + Returns the given ICommandSender as a EntityPlayer or throw an exception. */ - public static String buildString(String[] args, int startPos) { - StringBuilder stringbuilder = new StringBuilder(); + public static EntityPlayerMP getCommandSenderAsPlayer(ICommandSender sender) throws PlayerNotFoundException { + if (sender instanceof EntityPlayerMP) { + return (EntityPlayerMP) sender; + } else { + throw new PlayerNotFoundException("You must specify which player you wish to perform this action on.", + new Object[0]); + } + } - for (int i = startPos; i < args.length; ++i) { - if (i > startPos) { - stringbuilder.append(" "); + public static T getEntity(ICommandSender commandSender, String parString1, + Class parClass1) throws EntityNotFoundException { + Object object = PlayerSelector.matchOneEntity(commandSender, parString1, parClass1); + MinecraftServer minecraftserver = MinecraftServer.getServer(); + if (object == null) { + object = minecraftserver.getConfigurationManager().getPlayerByUsername(parString1); + } + + if (object == null) { + try { + EaglercraftUUID uuid = EaglercraftUUID.fromString(parString1); + object = minecraftserver.getEntityFromUuid(uuid); + if (object == null) { + object = minecraftserver.getConfigurationManager().getPlayerByUUID(uuid); + } + } catch (IllegalArgumentException var6) { + throw new EntityNotFoundException("commands.generic.entity.invalidUuid", new Object[0]); + } + } + + if (object != null && parClass1.isAssignableFrom(object.getClass())) { + return (T) object; + } else { + throw new EntityNotFoundException(); + } + } + + /** + * + Attempts to retrieve an entity's name, first assuming that the entity is a + * player, and then exhausting all other possibilities. + */ + public static String getEntityName(ICommandSender parICommandSender, String parString1) + throws EntityNotFoundException { + try { + return getPlayer(parICommandSender, parString1).getName(); + } catch (PlayerNotFoundException var5) { + try { + return func_175768_b(parICommandSender, parString1).getUniqueID().toString(); + } catch (EntityNotFoundException entitynotfoundexception) { + if (PlayerSelector.hasArguments(parString1)) { + throw entitynotfoundexception; + } else { + return parString1; + } + } + } + } + + /** + * + Gets the Item specified by the given text string. First checks the item + * registry, then tries by parsing the string as an integer ID (deprecated). + * Warns the sender if we matched by parsing the ID. Throws if the item wasn't + * found. Returns the item if it was found. + */ + public static Item getItemByText(ICommandSender sender, String id) throws NumberInvalidException { + ResourceLocation resourcelocation = new ResourceLocation(id); + Item item = (Item) Item.itemRegistry.getObject(resourcelocation); + if (item == null) { + throw new NumberInvalidException("commands.give.item.notFound", new Object[] { resourcelocation }); + } else { + return item; + } + } + + /** + * + Returns a List of strings (chosen from the given strings) which the last + * word in the given string array is a beginning-match for. (Tab completion). + */ + public static List getListOfStringsMatchingLastWord(String[] parArrayOfString, + Collection parCollection) { + String s = parArrayOfString[parArrayOfString.length - 1]; + ArrayList arraylist = Lists.newArrayList(); + if (!parCollection.isEmpty()) { + for (String s1 : Iterables.transform(parCollection, Functions.toStringFunction())) { + if (doesStringStartWith(s, s1)) { + arraylist.add(s1); + } + } + + if (arraylist.isEmpty()) { + for (Object object : parCollection) { + if (object instanceof ResourceLocation + && doesStringStartWith(s, ((ResourceLocation) object).getResourcePath())) { + arraylist.add(String.valueOf(object)); + } + } + } + } + + return arraylist; + } + + /** + * + Returns a List of strings (chosen from the given strings) which the last + * word in the given string array is a beginning-match for. (Tab completion). + */ + public static List getListOfStringsMatchingLastWord(String[] args, String... possibilities) { + /** + * + Returns a List of strings (chosen from the given strings) which the last + * word in the given string array is a beginning-match for. (Tab completion). + */ + return getListOfStringsMatchingLastWord(args, (Collection) Arrays.asList(possibilities)); + } + + public static EntityPlayerMP getPlayer(ICommandSender sender, String username) throws PlayerNotFoundException { + EntityPlayerMP entityplayermp = PlayerSelector.matchOnePlayer(sender, username); + if (entityplayermp == null) { + try { + entityplayermp = MinecraftServer.getServer().getConfigurationManager() + .getPlayerByUUID(EaglercraftUUID.fromString(username)); + } catch (IllegalArgumentException var4) { + ; + } + } + + if (entityplayermp == null) { + entityplayermp = MinecraftServer.getServer().getConfigurationManager().getPlayerByUsername(username); + } + + if (entityplayermp == null) { + throw new PlayerNotFoundException(); + } else { + return entityplayermp; + } + } + + public static String getPlayerName(ICommandSender sender, String query) throws PlayerNotFoundException { + try { + return getPlayer(sender, query).getName(); + } catch (PlayerNotFoundException playernotfoundexception) { + if (PlayerSelector.hasArguments(query)) { + throw playernotfoundexception; + } else { + return query; + } + } + } + + public static IChatComponent join(List components) { + ChatComponentText chatcomponenttext = new ChatComponentText(""); + + for (int i = 0; i < components.size(); ++i) { + if (i > 0) { + if (i == components.size() - 1) { + chatcomponenttext.appendText(" and "); + } else if (i > 0) { + chatcomponenttext.appendText(", "); + } + } + + chatcomponenttext.appendSibling((IChatComponent) components.get(i)); + } + + return chatcomponenttext; + } + + /** + * + Creates a linguistic series joining the input objects together. Examples: + * 1) {} --> "", 2) {"Steve"} --> "Steve", 3) {"Steve", "Phil"} --> "Steve and + * Phil", 4) {"Steve", "Phil", "Mark"} --> "Steve, Phil and Mark" + */ + public static String joinNiceString(Object[] elements) { + StringBuilder stringbuilder = new StringBuilder(); + + for (int i = 0; i < elements.length; ++i) { + String s = elements[i].toString(); + if (i > 0) { + if (i == elements.length - 1) { + stringbuilder.append(" and "); + } else { + stringbuilder.append(", "); + } } - String s = args[i]; stringbuilder.append(s); } return stringbuilder.toString(); } + /** + * + Creates a linguistic series joining together the elements of the given + * collection. Examples: 1) {} --> "", 2) {"Steve"} --> "Steve", 3) {"Steve", + * "Phil"} --> "Steve and Phil", 4) {"Steve", "Phil", "Mark"} --> "Steve, Phil + * and Mark" + */ + public static String joinNiceStringFromCollection(Collection strings) { + /** + * + Creates a linguistic series joining the input objects together. Examples: + * 1) {} --> "", 2) {"Steve"} --> "Steve", 3) {"Steve", "Phil"} --> "Steve and + * Phil", 4) {"Steve", "Phil", "Mark"} --> "Steve, Phil and Mark" + */ + return joinNiceString(strings.toArray(new String[strings.size()])); + } + + public static void notifyOperators(ICommandSender sender, ICommand command, int msgFormat, String msgParams, + Object... parArrayOfObject) { + if (theAdmin != null) { + theAdmin.notifyOperators(sender, command, msgFormat, msgParams, parArrayOfObject); + } + + } + + public static void notifyOperators(ICommandSender sender, ICommand command, String msgFormat, Object... msgParams) { + notifyOperators(sender, command, 0, msgFormat, msgParams); + } + + public static BlockPos parseBlockPos(ICommandSender sender, String[] args, int startIndex, boolean centerBlock) + throws NumberInvalidException { + BlockPos blockpos = sender.getPosition(); + return new BlockPos(parseDouble((double) blockpos.getX(), args[startIndex], -30000000, 30000000, centerBlock), + parseDouble((double) blockpos.getY(), args[startIndex + 1], 0, 256, false), + parseDouble((double) blockpos.getZ(), args[startIndex + 2], -30000000, 30000000, centerBlock)); + } + + public static boolean parseBoolean(String input) throws CommandException { + if (!input.equals("true") && !input.equals("1")) { + if (!input.equals("false") && !input.equals("0")) { + throw new CommandException("commands.generic.boolean.invalid", new Object[] { input }); + } else { + return false; + } + } else { + return true; + } + } + public static CommandBase.CoordinateArg parseCoordinate(double base, String centerBlock, boolean parFlag) throws NumberInvalidException { return parseCoordinate(base, centerBlock, -30000000, 30000000, parFlag); @@ -407,248 +523,126 @@ public abstract class CommandBase implements ICommand { } } - /**+ - * Gets the Item specified by the given text string. First - * checks the item registry, then tries by parsing the string as - * an integer ID (deprecated). Warns the sender if we matched by - * parsing the ID. Throws if the item wasn't found. Returns the - * item if it was found. - */ - public static Item getItemByText(ICommandSender sender, String id) throws NumberInvalidException { - ResourceLocation resourcelocation = new ResourceLocation(id); - Item item = (Item) Item.itemRegistry.getObject(resourcelocation); - if (item == null) { - throw new NumberInvalidException("commands.give.item.notFound", new Object[] { resourcelocation }); - } else { - return item; - } - } - - /**+ - * Gets the Block specified by the given text string. First - * checks the block registry, then tries by parsing the string - * as an integer ID (deprecated). Warns the sender if we matched - * by parsing the ID. Throws if the block wasn't found. Returns - * the block if it was found. - */ - public static Block getBlockByText(ICommandSender sender, String id) throws NumberInvalidException { - ResourceLocation resourcelocation = new ResourceLocation(id); - if (!Block.blockRegistry.containsKey(resourcelocation)) { - throw new NumberInvalidException("commands.give.block.notFound", new Object[] { resourcelocation }); - } else { - Block block = (Block) Block.blockRegistry.getObject(resourcelocation); - if (block == null) { - throw new NumberInvalidException("commands.give.block.notFound", new Object[] { resourcelocation }); + public static double parseDouble(String input) throws NumberInvalidException { + try { + double d0 = Double.parseDouble(input); + if (!Doubles.isFinite(d0)) { + throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); } else { - return block; + return d0; } + } catch (NumberFormatException var3) { + throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); } } - /**+ - * Creates a linguistic series joining the input objects - * together. Examples: 1) {} --> "", 2) {"Steve"} --> "Steve", - * 3) {"Steve", "Phil"} --> "Steve and Phil", 4) {"Steve", - * "Phil", "Mark"} --> "Steve, Phil and Mark" - */ - public static String joinNiceString(Object[] elements) { - StringBuilder stringbuilder = new StringBuilder(); - - for (int i = 0; i < elements.length; ++i) { - String s = elements[i].toString(); - if (i > 0) { - if (i == elements.length - 1) { - stringbuilder.append(" and "); - } else { - stringbuilder.append(", "); - } - } - - stringbuilder.append(s); - } - - return stringbuilder.toString(); + public static double parseDouble(String input, double min) throws NumberInvalidException { + return parseDouble(input, min, Double.MAX_VALUE); } - public static IChatComponent join(List components) { - ChatComponentText chatcomponenttext = new ChatComponentText(""); - - for (int i = 0; i < components.size(); ++i) { - if (i > 0) { - if (i == components.size() - 1) { - chatcomponenttext.appendText(" and "); - } else if (i > 0) { - chatcomponenttext.appendText(", "); - } - } - - chatcomponenttext.appendSibling((IChatComponent) components.get(i)); - } - - return chatcomponenttext; - } - - /**+ - * Creates a linguistic series joining together the elements of - * the given collection. Examples: 1) {} --> "", 2) {"Steve"} - * --> "Steve", 3) {"Steve", "Phil"} --> "Steve and Phil", 4) - * {"Steve", "Phil", "Mark"} --> "Steve, Phil and Mark" - */ - public static String joinNiceStringFromCollection(Collection strings) { - /**+ - * Creates a linguistic series joining the input objects - * together. Examples: 1) {} --> "", 2) {"Steve"} --> "Steve", - * 3) {"Steve", "Phil"} --> "Steve and Phil", 4) {"Steve", - * "Phil", "Mark"} --> "Steve, Phil and Mark" - */ - return joinNiceString(strings.toArray(new String[strings.size()])); - } - - public static List func_175771_a(String[] parArrayOfString, int parInt1, BlockPos parBlockPos) { - if (parBlockPos == null) { - return null; + public static double parseDouble(String input, double min, double max) throws NumberInvalidException { + double d0 = parseDouble(input); + if (d0 < min) { + throw new NumberInvalidException("commands.generic.double.tooSmall", + new Object[] { Double.valueOf(d0), Double.valueOf(min) }); + } else if (d0 > max) { + throw new NumberInvalidException("commands.generic.double.tooBig", + new Object[] { Double.valueOf(d0), Double.valueOf(max) }); } else { - int i = parArrayOfString.length - 1; - String s; - if (i == parInt1) { - s = Integer.toString(parBlockPos.getX()); - } else if (i == parInt1 + 1) { - s = Integer.toString(parBlockPos.getY()); - } else { - if (i != parInt1 + 2) { - return null; - } - - s = Integer.toString(parBlockPos.getZ()); - } - - return Lists.newArrayList(new String[] { s }); + return d0; } } - public static List func_181043_b(String[] parArrayOfString, int parInt1, BlockPos parBlockPos) { - if (parBlockPos == null) { - return null; + public static int parseInt(String input) throws NumberInvalidException { + try { + return Integer.parseInt(input); + } catch (NumberFormatException var2) { + throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); + } + } + + public static int parseInt(String input, int min) throws NumberInvalidException { + return parseInt(input, min, Integer.MAX_VALUE); + } + + public static int parseInt(String input, int min, int max) throws NumberInvalidException { + int i = parseInt(input); + if (i < min) { + throw new NumberInvalidException("commands.generic.num.tooSmall", + new Object[] { Integer.valueOf(i), Integer.valueOf(min) }); + } else if (i > max) { + throw new NumberInvalidException("commands.generic.num.tooBig", + new Object[] { Integer.valueOf(i), Integer.valueOf(max) }); } else { - int i = parArrayOfString.length - 1; - String s; - if (i == parInt1) { - s = Integer.toString(parBlockPos.getX()); - } else { - if (i != parInt1 + 1) { - return null; - } - - s = Integer.toString(parBlockPos.getZ()); - } - - return Lists.newArrayList(new String[] { s }); + return i; } } - /**+ - * Returns true if the given substring is exactly equal to the - * start of the given string (case insensitive). - */ - public static boolean doesStringStartWith(String original, String region) { - return region.regionMatches(true, 0, original, 0, original.length()); - } - - /**+ - * Returns a List of strings (chosen from the given strings) - * which the last word in the given string array is a - * beginning-match for. (Tab completion). - */ - public static List getListOfStringsMatchingLastWord(String[] args, String... possibilities) { - /**+ - * Returns a List of strings (chosen from the given strings) - * which the last word in the given string array is a - * beginning-match for. (Tab completion). - */ - return getListOfStringsMatchingLastWord(args, (Collection) Arrays.asList(possibilities)); - } - - /**+ - * Returns a List of strings (chosen from the given strings) - * which the last word in the given string array is a - * beginning-match for. (Tab completion). - */ - public static List getListOfStringsMatchingLastWord(String[] parArrayOfString, - Collection parCollection) { - String s = parArrayOfString[parArrayOfString.length - 1]; - ArrayList arraylist = Lists.newArrayList(); - if (!parCollection.isEmpty()) { - for (String s1 : Iterables.transform(parCollection, Functions.toStringFunction())) { - if (doesStringStartWith(s, s1)) { - arraylist.add(s1); - } - } - - if (arraylist.isEmpty()) { - for (Object object : parCollection) { - if (object instanceof ResourceLocation - && doesStringStartWith(s, ((ResourceLocation) object).getResourcePath())) { - arraylist.add(String.valueOf(object)); - } - } - } + public static long parseLong(String input) throws NumberInvalidException { + try { + return Long.parseLong(input); + } catch (NumberFormatException var2) { + throw new NumberInvalidException("commands.generic.num.invalid", new Object[] { input }); } - - return arraylist; } - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int var2) { - return false; - } - - public static void notifyOperators(ICommandSender sender, ICommand command, String msgFormat, Object... msgParams) { - notifyOperators(sender, command, 0, msgFormat, msgParams); - } - - public static void notifyOperators(ICommandSender sender, ICommand command, int msgFormat, String msgParams, - Object... parArrayOfObject) { - if (theAdmin != null) { - theAdmin.notifyOperators(sender, command, msgFormat, msgParams, parArrayOfObject); + public static long parseLong(String input, long min, long max) throws NumberInvalidException { + long i = parseLong(input); + if (i < min) { + throw new NumberInvalidException("commands.generic.num.tooSmall", + new Object[] { Long.valueOf(i), Long.valueOf(min) }); + } else if (i > max) { + throw new NumberInvalidException("commands.generic.num.tooBig", + new Object[] { Long.valueOf(i), Long.valueOf(max) }); + } else { + return i; } - } - /**+ - * Sets the static IAdminCommander. + /** + * + Sets the static IAdminCommander. */ public static void setAdminCommander(IAdminCommand command) { theAdmin = command; } + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] var2, BlockPos var3) { + return null; + } + + /** + * + Returns true if the given command sender is allowed to use this command. + */ + public boolean canCommandSenderUseCommand(ICommandSender icommandsender) { + return icommandsender.canCommandSenderUseCommand(this.getRequiredPermissionLevel(), this.getCommandName()); + } + public int compareTo(ICommand icommand) { return this.getCommandName().compareTo(icommand.getCommandName()); } - public static class CoordinateArg { - private final double field_179633_a; - private final double field_179631_b; - private final boolean field_179632_c; + /** + * + Gets a list of aliases for this command + */ + public List getCommandAliases() { + return Collections.emptyList(); + } - protected CoordinateArg(double parDouble1, double parDouble2, boolean parFlag) { - this.field_179633_a = parDouble1; - this.field_179631_b = parDouble2; - this.field_179632_c = parFlag; - } + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 4; + } - public double func_179628_a() { - return this.field_179633_a; - } - - public double func_179629_b() { - return this.field_179631_b; - } - - public boolean func_179630_c() { - return this.field_179632_c; - } + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int var2) { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandBlockData.java b/src/game/java/net/minecraft/command/CommandBlockData.java index f589a1da..6b979d61 100644 --- a/src/game/java/net/minecraft/command/CommandBlockData.java +++ b/src/game/java/net/minecraft/command/CommandBlockData.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; import net.minecraft.nbt.NBTTagCompound; @@ -8,51 +9,61 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandBlockData extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "blockdata"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.blockdata.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 4) { @@ -101,11 +112,4 @@ public class CommandBlockData extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandClearInventory.java b/src/game/java/net/minecraft/command/CommandClearInventory.java index 3e61158a..a82906d7 100644 --- a/src/game/java/net/minecraft/command/CommandClearInventory.java +++ b/src/game/java/net/minecraft/command/CommandClearInventory.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; import net.minecraft.nbt.JsonToNBT; @@ -10,51 +11,74 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandClearInventory extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.func_147209_d()) + : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Item.itemRegistry.getKeys()) : null); + } + + protected String[] func_147209_d() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "clear"; } - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.clear.usage"; } - /**+ - * Return the required permission level for this command. + /** + * + Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 2; } - /**+ - * Callback when the command is invoked + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { EntityPlayerMP entityplayermp = parArrayOfString.length == 0 ? getCommandSenderAsPlayer(parICommandSender) @@ -95,24 +119,4 @@ public class CommandClearInventory extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.func_147209_d()) - : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Item.itemRegistry.getKeys()) : null); - } - - protected String[] func_147209_d() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandClone.java b/src/game/java/net/minecraft/command/CommandClone.java index dea0022a..f1d8a715 100644 --- a/src/game/java/net/minecraft/command/CommandClone.java +++ b/src/game/java/net/minecraft/command/CommandClone.java @@ -1,9 +1,11 @@ package net.minecraft.command; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -15,51 +17,90 @@ import net.minecraft.world.NextTickListEntry; import net.minecraft.world.World; import net.minecraft.world.gen.structure.StructureBoundingBox; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandClone extends CommandBase { - /**+ - * Gets the name of the command + static class StaticCloneData { + public final BlockPos field_179537_a; + public final IBlockState blockState; + public final NBTTagCompound field_179536_c; + + public StaticCloneData(BlockPos parBlockPos, IBlockState parIBlockState, NBTTagCompound parNBTTagCompound) { + this.field_179537_a = parBlockPos; + this.blockState = parIBlockState; + this.field_179536_c = parNBTTagCompound; + } + } + + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 + && astring.length <= 3 + ? func_175771_a(astring, 0, blockpos) + : (astring.length > 3 + && astring.length <= 6 + ? func_175771_a(astring, 3, blockpos) + : (astring.length > 6 && astring.length <= 9 + ? func_175771_a(astring, 6, blockpos) + : (astring.length == 10 + ? getListOfStringsMatchingLastWord(astring, + new String[] { "replace", "masked", "filtered" }) + : (astring.length == 11 + ? getListOfStringsMatchingLastWord(astring, + new String[] { "normal", "force", "move" }) + : (astring.length == 12 && "filtered".equals(astring[9]) + ? getListOfStringsMatchingLastWord(astring, + Block.blockRegistry.getKeys()) + : null))))); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "clone"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.clone.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 9) { @@ -251,40 +292,4 @@ public class CommandClone extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 - && astring.length <= 3 - ? func_175771_a(astring, 0, blockpos) - : (astring.length > 3 - && astring.length <= 6 - ? func_175771_a(astring, 3, blockpos) - : (astring.length > 6 && astring.length <= 9 - ? func_175771_a(astring, 6, blockpos) - : (astring.length == 10 - ? getListOfStringsMatchingLastWord(astring, - new String[] { "replace", "masked", "filtered" }) - : (astring.length == 11 - ? getListOfStringsMatchingLastWord(astring, - new String[] { "normal", "force", "move" }) - : (astring.length == 12 && "filtered".equals(astring[9]) - ? getListOfStringsMatchingLastWord(astring, - Block.blockRegistry.getKeys()) - : null))))); - } - - static class StaticCloneData { - public final BlockPos field_179537_a; - public final IBlockState blockState; - public final NBTTagCompound field_179536_c; - - public StaticCloneData(BlockPos parBlockPos, IBlockState parIBlockState, NBTTagCompound parNBTTagCompound) { - this.field_179537_a = parBlockPos; - this.blockState = parIBlockState; - this.field_179536_c = parNBTTagCompound; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandCompare.java b/src/game/java/net/minecraft/command/CommandCompare.java index 1dd6d314..ca1f4a3e 100644 --- a/src/game/java/net/minecraft/command/CommandCompare.java +++ b/src/game/java/net/minecraft/command/CommandCompare.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.nbt.NBTTagCompound; @@ -9,51 +10,66 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.structure.StructureBoundingBox; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandCompare extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) + : (astring.length > 3 && astring.length <= 6 ? func_175771_a(astring, 3, blockpos) + : (astring.length > 6 && astring.length <= 9 ? func_175771_a(astring, 6, blockpos) + : (astring.length == 10 + ? getListOfStringsMatchingLastWord(astring, new String[] { "masked", "all" }) + : null))); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "testforblocks"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.compare.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 9) { @@ -139,16 +155,4 @@ public class CommandCompare extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) - : (astring.length > 3 && astring.length <= 6 ? func_175771_a(astring, 3, blockpos) - : (astring.length > 6 && astring.length <= 9 ? func_175771_a(astring, 6, blockpos) - : (astring.length == 10 - ? getListOfStringsMatchingLastWord(astring, new String[] { "masked", "all" }) - : null))); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandDefaultGameMode.java b/src/game/java/net/minecraft/command/CommandDefaultGameMode.java index 47ba49d9..f0e847ed 100644 --- a/src/game/java/net/minecraft/command/CommandDefaultGameMode.java +++ b/src/game/java/net/minecraft/command/CommandDefaultGameMode.java @@ -7,44 +7,47 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandDefaultGameMode extends CommandGameMode { - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "defaultgamemode"; } - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.defaultgamemode.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length <= 0) { diff --git a/src/game/java/net/minecraft/command/CommandDifficulty.java b/src/game/java/net/minecraft/command/CommandDifficulty.java index b1f7c136..427daf87 100644 --- a/src/game/java/net/minecraft/command/CommandDifficulty.java +++ b/src/game/java/net/minecraft/command/CommandDifficulty.java @@ -1,68 +1,60 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.EnumDifficulty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandDifficulty extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, new String[] { "peaceful", "easy", "normal", "hard" }) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "difficulty"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.difficulty.usage"; } - /**+ - * Callback when the command is invoked - */ - public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { - if (parArrayOfString.length <= 0) { - throw new WrongUsageException("commands.difficulty.usage", new Object[0]); - } else { - EnumDifficulty enumdifficulty = this.getDifficultyFromCommand(parArrayOfString[0]); - MinecraftServer.getServer().setDifficultyForAllWorlds(enumdifficulty); - notifyOperators(parICommandSender, this, "commands.difficulty.success", new Object[] { - new ChatComponentTranslation(enumdifficulty.getDifficultyResourceKey(), new Object[0]) }); - } - } - protected EnumDifficulty getDifficultyFromCommand(String parString1) throws NumberInvalidException { return !parString1.equalsIgnoreCase("peaceful") && !parString1.equalsIgnoreCase("p") ? (!parString1.equalsIgnoreCase("easy") && !parString1.equalsIgnoreCase("e") @@ -75,12 +67,24 @@ public class CommandDifficulty extends CommandBase { : EnumDifficulty.PEACEFUL; } - /**+ - * Return a list of options when the user types TAB + /** + * + Return the required permission level for this command. */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, new String[] { "peaceful", "easy", "normal", "hard" }) - : null; + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked + */ + public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { + if (parArrayOfString.length <= 0) { + throw new WrongUsageException("commands.difficulty.usage", new Object[0]); + } else { + EnumDifficulty enumdifficulty = this.getDifficultyFromCommand(parArrayOfString[0]); + MinecraftServer.getServer().setDifficultyForAllWorlds(enumdifficulty); + notifyOperators(parICommandSender, this, "commands.difficulty.success", new Object[] { + new ChatComponentTranslation(enumdifficulty.getDifficultyResourceKey(), new Object[0]) }); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandEffect.java b/src/game/java/net/minecraft/command/CommandEffect.java index 02999585..904bbdf0 100644 --- a/src/game/java/net/minecraft/command/CommandEffect.java +++ b/src/game/java/net/minecraft/command/CommandEffect.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.EntityLivingBase; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; @@ -8,51 +9,77 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandEffect extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.getAllUsernames()) + : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Potion.func_181168_c()) + : (astring.length == 5 + ? getListOfStringsMatchingLastWord(astring, new String[] { "true", "false" }) + : null)); + } + + protected String[] getAllUsernames() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "effect"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.effect.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -131,27 +158,4 @@ public class CommandEffect extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.getAllUsernames()) - : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Potion.func_181168_c()) - : (astring.length == 5 - ? getListOfStringsMatchingLastWord(astring, new String[] { "true", "false" }) - : null)); - } - - protected String[] getAllUsernames() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandEnchant.java b/src/game/java/net/minecraft/command/CommandEnchant.java index 8da91fb9..73c21c2e 100644 --- a/src/game/java/net/minecraft/command/CommandEnchant.java +++ b/src/game/java/net/minecraft/command/CommandEnchant.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.enchantment.Enchantment; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; @@ -8,51 +9,74 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandEnchant extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.getListOfPlayers()) + : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Enchantment.func_181077_c()) : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "enchant"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.enchant.usage"; } - /**+ - * Callback when the command is invoked + protected String[] getListOfPlayers() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] args, int index) { + return index == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -113,24 +137,4 @@ public class CommandEnchant extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.getListOfPlayers()) - : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Enchantment.func_181077_c()) : null); - } - - protected String[] getListOfPlayers() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] args, int index) { - return index == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandEntityData.java b/src/game/java/net/minecraft/command/CommandEntityData.java index 262ca6c1..99cacca7 100644 --- a/src/game/java/net/minecraft/command/CommandEntityData.java +++ b/src/game/java/net/minecraft/command/CommandEntityData.java @@ -6,51 +6,62 @@ import net.minecraft.nbt.JsonToNBT; import net.minecraft.nbt.NBTException; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandEntityData extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "entitydata"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.entitydata.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -87,12 +98,4 @@ public class CommandEntityData extends CommandBase { } } } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandException.java b/src/game/java/net/minecraft/command/CommandException.java index 760c22ef..41257485 100644 --- a/src/game/java/net/minecraft/command/CommandException.java +++ b/src/game/java/net/minecraft/command/CommandException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/CommandExecuteAt.java b/src/game/java/net/minecraft/command/CommandExecuteAt.java index 75086f7a..1bc26548 100644 --- a/src/game/java/net/minecraft/command/CommandExecuteAt.java +++ b/src/game/java/net/minecraft/command/CommandExecuteAt.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; @@ -10,51 +11,76 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandExecuteAt extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) + : (astring.length > 5 && astring.length <= 8 && "detect".equals(astring[4]) + ? func_175771_a(astring, 5, blockpos) + : (astring.length == 9 && "detect".equals(astring[4]) + ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) + : null))); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "execute"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.execute.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(final ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { @@ -86,14 +112,6 @@ public class CommandExecuteAt extends CommandBase { String s = buildString(parArrayOfString, b0); ICommandSender icommandsender = new ICommandSender() { - public String getName() { - return entity.getName(); - } - - public IChatComponent getDisplayName() { - return entity.getDisplayName(); - } - public void addChatMessage(IChatComponent component) { parICommandSender.addChatMessage(component); } @@ -102,20 +120,28 @@ public class CommandExecuteAt extends CommandBase { return parICommandSender.canCommandSenderUseCommand(permLevel, commandName); } - public BlockPos getPosition() { - return blockpos; + public Entity getCommandSenderEntity() { + return entity; } - public Vec3 getPositionVector() { - return new Vec3(d0, d1, d2); + public IChatComponent getDisplayName() { + return entity.getDisplayName(); } public World getEntityWorld() { return entity.worldObj; } - public Entity getCommandSenderEntity() { - return entity; + public String getName() { + return entity.getName(); + } + + public BlockPos getPosition() { + return blockpos; + } + + public Vec3 getPositionVector() { + return new Vec3(d0, d1, d2); } public boolean sendCommandFeedback() { @@ -140,26 +166,4 @@ public class CommandExecuteAt extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) - : (astring.length > 5 && astring.length <= 8 && "detect".equals(astring[4]) - ? func_175771_a(astring, 5, blockpos) - : (astring.length == 9 && "detect".equals(astring[4]) - ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) - : null))); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandFill.java b/src/game/java/net/minecraft/command/CommandFill.java index 5a33be9d..457cb80d 100644 --- a/src/game/java/net/minecraft/command/CommandFill.java +++ b/src/game/java/net/minecraft/command/CommandFill.java @@ -1,8 +1,10 @@ package net.minecraft.command; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; @@ -14,51 +16,74 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandFill extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 + && astring.length <= 3 + ? func_175771_a(astring, 0, blockpos) + : (astring.length > 3 && astring.length <= 6 ? func_175771_a(astring, 3, blockpos) + : (astring.length == 7 + ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) + : (astring.length == 9 + ? getListOfStringsMatchingLastWord(astring, + new String[] { "replace", "destroy", "keep", "hollow", + "outline" }) + : (astring.length == 10 && "replace".equals(astring[8]) + ? getListOfStringsMatchingLastWord(astring, + Block.blockRegistry.getKeys()) + : null)))); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "fill"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.fill.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 7) { @@ -195,24 +220,4 @@ public class CommandFill extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 - && astring.length <= 3 - ? func_175771_a(astring, 0, blockpos) - : (astring.length > 3 && astring.length <= 6 ? func_175771_a(astring, 3, blockpos) - : (astring.length == 7 - ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) - : (astring.length == 9 - ? getListOfStringsMatchingLastWord(astring, - new String[] { "replace", "destroy", "keep", "hollow", - "outline" }) - : (astring.length == 10 && "replace".equals(astring[8]) - ? getListOfStringsMatchingLastWord(astring, - Block.blockRegistry.getKeys()) - : null)))); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandGameMode.java b/src/game/java/net/minecraft/command/CommandGameMode.java index 498c8481..cdb8803b 100644 --- a/src/game/java/net/minecraft/command/CommandGameMode.java +++ b/src/game/java/net/minecraft/command/CommandGameMode.java @@ -1,57 +1,111 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandGameMode extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, + new String[] { "survival", "creative", "adventure", "spectator" }) + : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, this.getListOfPlayerUsernames()) + : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "gamemode"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.gamemode.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Gets the Game Mode specified in the command. + */ + protected WorldSettings.GameType getGameModeFromCommand(ICommandSender parICommandSender, String parString1) + throws NumberInvalidException { + return !parString1.equalsIgnoreCase(WorldSettings.GameType.SURVIVAL.getName()) + && !parString1.equalsIgnoreCase("s") + ? (!parString1.equalsIgnoreCase(WorldSettings.GameType.CREATIVE.getName()) + && !parString1.equalsIgnoreCase("c") + ? (!parString1.equalsIgnoreCase(WorldSettings.GameType.ADVENTURE.getName()) + && !parString1.equalsIgnoreCase("a") + ? (!parString1.equalsIgnoreCase( + WorldSettings.GameType.SPECTATOR.getName()) + && !parString1.equalsIgnoreCase("sp") + ? WorldSettings.getGameTypeById(parseInt( + parString1, 0, + WorldSettings.GameType._VALUES.length + - 2)) + : WorldSettings.GameType.SPECTATOR) + : WorldSettings.GameType.ADVENTURE) + : WorldSettings.GameType.CREATIVE) + : WorldSettings.GameType.SURVIVAL; + } + + /** + * + Returns String array containing all player usernames in the server. + */ + protected String[] getListOfPlayerUsernames() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 1; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length <= 0) { @@ -80,55 +134,4 @@ public class CommandGameMode extends CommandBase { } } - - /**+ - * Gets the Game Mode specified in the command. - */ - protected WorldSettings.GameType getGameModeFromCommand(ICommandSender parICommandSender, String parString1) - throws NumberInvalidException { - return !parString1.equalsIgnoreCase(WorldSettings.GameType.SURVIVAL.getName()) - && !parString1.equalsIgnoreCase("s") - ? (!parString1.equalsIgnoreCase(WorldSettings.GameType.CREATIVE.getName()) - && !parString1.equalsIgnoreCase("c") - ? (!parString1.equalsIgnoreCase(WorldSettings.GameType.ADVENTURE.getName()) - && !parString1.equalsIgnoreCase("a") - ? (!parString1.equalsIgnoreCase( - WorldSettings.GameType.SPECTATOR.getName()) - && !parString1.equalsIgnoreCase("sp") - ? WorldSettings.getGameTypeById(parseInt( - parString1, 0, - WorldSettings.GameType._VALUES.length - - 2)) - : WorldSettings.GameType.SPECTATOR) - : WorldSettings.GameType.ADVENTURE) - : WorldSettings.GameType.CREATIVE) - : WorldSettings.GameType.SURVIVAL; - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, - new String[] { "survival", "creative", "adventure", "spectator" }) - : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, this.getListOfPlayerUsernames()) - : null); - } - - /**+ - * Returns String array containing all player usernames in the - * server. - */ - protected String[] getListOfPlayerUsernames() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandGameRule.java b/src/game/java/net/minecraft/command/CommandGameRule.java index e325f133..2709f9bc 100644 --- a/src/game/java/net/minecraft/command/CommandGameRule.java +++ b/src/game/java/net/minecraft/command/CommandGameRule.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S19PacketEntityStatus; import net.minecraft.server.MinecraftServer; @@ -8,51 +9,92 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentText; import net.minecraft.world.GameRules; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandGameRule extends CommandBase { - /**+ - * Gets the name of the command + public static void func_175773_a(GameRules parGameRules, String parString1) { + if ("reducedDebugInfo".equals(parString1)) { + int i = parGameRules.getBoolean(parString1) ? 22 : 23; + + List lst = MinecraftServer.getServer().getConfigurationManager().func_181057_v(); + for (int j = 0, l = lst.size(); j < l; ++j) { + EntityPlayerMP entityplayermp = lst.get(j); + entityplayermp.playerNetServerHandler.sendPacket(new S19PacketEntityStatus(entityplayermp, (byte) i)); + } + } + + } + + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + if (astring.length == 1) { + return getListOfStringsMatchingLastWord(astring, this.getGameRules().getRules()); + } else { + if (astring.length == 2) { + GameRules gamerules = this.getGameRules(); + if (gamerules.areSameType(astring[0], GameRules.ValueType.BOOLEAN_VALUE)) { + return getListOfStringsMatchingLastWord(astring, new String[] { "true", "false" }); + } + } + + return null; + } + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "gamerule"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.gamerule.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the game rule set this command should be able to manipulate. + */ + private GameRules getGameRules() { + return MinecraftServer.getServer().worldServerForDimension(0).getGameRules(); + } + + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { GameRules gamerules = this.getGameRules(); @@ -83,43 +125,4 @@ public class CommandGameRule extends CommandBase { } } - - public static void func_175773_a(GameRules parGameRules, String parString1) { - if ("reducedDebugInfo".equals(parString1)) { - int i = parGameRules.getBoolean(parString1) ? 22 : 23; - - List lst = MinecraftServer.getServer().getConfigurationManager().func_181057_v(); - for (int j = 0, l = lst.size(); j < l; ++j) { - EntityPlayerMP entityplayermp = lst.get(j); - entityplayermp.playerNetServerHandler.sendPacket(new S19PacketEntityStatus(entityplayermp, (byte) i)); - } - } - - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - if (astring.length == 1) { - return getListOfStringsMatchingLastWord(astring, this.getGameRules().getRules()); - } else { - if (astring.length == 2) { - GameRules gamerules = this.getGameRules(); - if (gamerules.areSameType(astring[0], GameRules.ValueType.BOOLEAN_VALUE)) { - return getListOfStringsMatchingLastWord(astring, new String[] { "true", "false" }); - } - } - - return null; - } - } - - /**+ - * Return the game rule set this command should be able to - * manipulate. - */ - private GameRules getGameRules() { - return MinecraftServer.getServer().worldServerForDimension(0).getGameRules(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandGive.java b/src/game/java/net/minecraft/command/CommandGive.java index 6b93ef48..6ed01733 100644 --- a/src/game/java/net/minecraft/command/CommandGive.java +++ b/src/game/java/net/minecraft/command/CommandGive.java @@ -1,6 +1,7 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.Item; @@ -10,51 +11,74 @@ import net.minecraft.nbt.NBTException; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandGive extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.getPlayers()) + : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Item.itemRegistry.getKeys()) : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "give"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.give.usage"; } - /**+ - * Callback when the command is invoked + protected String[] getPlayers() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -103,24 +127,4 @@ public class CommandGive extends CommandBase { new Object[] { itemstack.getChatComponent(), Integer.valueOf(i), entityplayermp.getName() }); } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, this.getPlayers()) - : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, Item.itemRegistry.getKeys()) : null); - } - - protected String[] getPlayers() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandGm.java b/src/game/java/net/minecraft/command/CommandGm.java new file mode 100644 index 00000000..0cf306f8 --- /dev/null +++ b/src/game/java/net/minecraft/command/CommandGm.java @@ -0,0 +1,57 @@ +package net.minecraft.command; + +import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.world.WorldSettings; + +public class CommandGm extends CommandBase { + public int gmId; + public String gmName; + + public CommandGm(int id) { + this.gmId = id; + this.gmName = gmId == 0 ? "s" : gmId == 1 ? "c" : gmId == 2 ? "a" : gmId == 3 ? "sp" : null; + } + + public String getCommandName() { + return "gm" + this.gmName; + } + + public String getCommandUsage(ICommandSender var1) { + return (new ChatComponentTranslation("commands.gm.usage", new Object[] { this.gmName }).getUnformattedText()); + } + + public int getRequiredPermissionLevel() { + return 2; + } + + public boolean isUsernameIndex(String[] args, int index) { + return index == 1; + } + + public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { + if (parArrayOfString.length < 0) { + throw new WrongUsageException("commands.gm.usage", new Object[] { this.gmName }); + } else { + WorldSettings.GameType worldsettings$gametype = WorldSettings.GameType.getByID(this.gmId); + EntityPlayerMP entityplayermp = parArrayOfString.length >= 1 + ? getPlayer(parICommandSender, parArrayOfString[0]) + : getCommandSenderAsPlayer(parICommandSender); + entityplayermp.setGameType(worldsettings$gametype); + entityplayermp.fallDistance = 0.0F; + if (parICommandSender.getEntityWorld().getGameRules().getBoolean("sendCommandFeedback")) { + entityplayermp.addChatMessage(new ChatComponentTranslation("gameMode.changed", new Object[0])); + } + + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + "gameMode." + worldsettings$gametype.getName(), new Object[0]); + if (entityplayermp != parICommandSender) { + notifyOperators(parICommandSender, this, 1, "commands.gm.success.other", + new Object[] { entityplayermp.getName(), chatcomponenttranslation }); + } else { + notifyOperators(parICommandSender, this, 1, "commands.gm.success.self", + new Object[] { chatcomponenttranslation }); + } + } + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandHandler.java b/src/game/java/net/minecraft/command/CommandHandler.java index 666497c1..26c7fea6 100644 --- a/src/game/java/net/minecraft/command/CommandHandler.java +++ b/src/game/java/net/minecraft/command/CommandHandler.java @@ -1,36 +1,41 @@ package net.minecraft.command; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.Entity; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,9 +43,21 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; public class CommandHandler implements ICommandManager { private static final Logger logger = LogManager.getLogger(); + + /** + * + creates a new array and sets elements 0..n-2 to be 0..n-1 of the input (n + * elements) + */ + private static String[] dropFirstString(String[] input) { + String[] astring = new String[input.length - 1]; + System.arraycopy(input, 1, astring, 0, input.length - 1); + return astring; + } + private final Map commandMap = Maps.newHashMap(); - /**+ - * The set of ICommand objects currently loaded. + + /** + * + The set of ICommand objects currently loaded. */ private final Set commandSet = Sets.newHashSet(); @@ -92,58 +109,23 @@ public class CommandHandler implements ICommandManager { return j; } - protected boolean tryExecute(ICommandSender sender, String[] args, ICommand command, String input) { - try { - command.processCommand(sender, args); - return true; - } catch (WrongUsageException wrongusageexception) { - ChatComponentTranslation chatcomponenttranslation2 = new ChatComponentTranslation("commands.generic.usage", - new Object[] { new ChatComponentTranslation(wrongusageexception.getMessage(), - wrongusageexception.getErrorObjects()) }); - chatcomponenttranslation2.getChatStyle().setColor(EnumChatFormatting.RED); - sender.addChatMessage(chatcomponenttranslation2); - } catch (CommandException commandexception) { - ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation( - commandexception.getMessage(), commandexception.getErrorObjects()); - chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.RED); - sender.addChatMessage(chatcomponenttranslation1); - } catch (Throwable var9) { - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( - "commands.generic.exception", new Object[0]); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); - sender.addChatMessage(chatcomponenttranslation); - logger.warn("Couldn\'t process command: \'" + input + "\'"); - } - - return false; + public Map getCommands() { + return this.commandMap; } - /**+ - * adds the command and any aliases it has to the internal map - * of available commands + /** + * + returns all commands that the commandSender can use */ - public ICommand registerCommand(ICommand command) { - this.commandMap.put(command.getCommandName(), command); - this.commandSet.add(command); + public List getPossibleCommands(ICommandSender sender) { + ArrayList arraylist = Lists.newArrayList(); - for (String s : command.getCommandAliases()) { - ICommand icommand = (ICommand) this.commandMap.get(s); - if (icommand == null || !icommand.getCommandName().equals(s)) { - this.commandMap.put(s, command); + for (ICommand icommand : this.commandSet) { + if (icommand.canCommandSenderUseCommand(sender)) { + arraylist.add(icommand); } } - return command; - } - - /**+ - * creates a new array and sets elements 0..n-2 to be 0..n-1 of - * the input (n elements) - */ - private static String[] dropFirstString(String[] input) { - String[] astring = new String[input.length - 1]; - System.arraycopy(input, 1, astring, 0, input.length - 1); - return astring; + return arraylist; } public List getTabCompletionOptions(ICommandSender sender, String input, BlockPos pos) { @@ -172,28 +154,8 @@ public class CommandHandler implements ICommandManager { } } - /**+ - * returns all commands that the commandSender can use - */ - public List getPossibleCommands(ICommandSender sender) { - ArrayList arraylist = Lists.newArrayList(); - - for (ICommand icommand : this.commandSet) { - if (icommand.canCommandSenderUseCommand(sender)) { - arraylist.add(icommand); - } - } - - return arraylist; - } - - public Map getCommands() { - return this.commandMap; - } - - /**+ - * Return a command's first parameter index containing a valid - * username. + /** + * + Return a command's first parameter index containing a valid username. */ private int getUsernameIndex(ICommand command, String[] args) { if (command == null) { @@ -208,4 +170,48 @@ public class CommandHandler implements ICommandManager { return -1; } } + + /** + * + adds the command and any aliases it has to the internal map of available + * commands + */ + public ICommand registerCommand(ICommand command) { + this.commandMap.put(command.getCommandName(), command); + this.commandSet.add(command); + + for (String s : command.getCommandAliases()) { + ICommand icommand = (ICommand) this.commandMap.get(s); + if (icommand == null || !icommand.getCommandName().equals(s)) { + this.commandMap.put(s, command); + } + } + + return command; + } + + protected boolean tryExecute(ICommandSender sender, String[] args, ICommand command, String input) { + try { + command.processCommand(sender, args); + return true; + } catch (WrongUsageException wrongusageexception) { + ChatComponentTranslation chatcomponenttranslation2 = new ChatComponentTranslation("commands.generic.usage", + new Object[] { new ChatComponentTranslation(wrongusageexception.getMessage(), + wrongusageexception.getErrorObjects()) }); + chatcomponenttranslation2.getChatStyle().setColor(EnumChatFormatting.RED); + sender.addChatMessage(chatcomponenttranslation2); + } catch (CommandException commandexception) { + ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation( + commandexception.getMessage(), commandexception.getErrorObjects()); + chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.RED); + sender.addChatMessage(chatcomponenttranslation1); + } catch (Throwable var9) { + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + "commands.generic.exception", new Object[0]); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); + sender.addChatMessage(chatcomponenttranslation); + logger.warn("Couldn\'t process command: \'" + input + "\'"); + } + + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandHelp.java b/src/game/java/net/minecraft/command/CommandHelp.java index 0ab441fd..ddfb0c87 100644 --- a/src/game/java/net/minecraft/command/CommandHelp.java +++ b/src/game/java/net/minecraft/command/CommandHelp.java @@ -5,6 +5,7 @@ import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.event.ClickEvent; import net.minecraft.server.MinecraftServer; @@ -13,58 +14,87 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandHelp extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB */ - public String getCommandName() { - return "help"; + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + if (astring.length == 1) { + Set set = this.getCommands().keySet(); + return getListOfStringsMatchingLastWord(astring, (String[]) set.toArray(new String[set.size()])); + } else { + return null; + } } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 0; - } - - /**+ - * Gets the usage string for the command. - */ - public String getCommandUsage(ICommandSender var1) { - return "commands.help.usage"; - } - - /**+ - * Gets a list of aliases for this command + /** + * + Gets a list of aliases for this command */ public List getCommandAliases() { return Arrays.asList(new String[] { "?" }); } - /**+ - * Callback when the command is invoked + /** + * + Gets the name of the command + */ + public String getCommandName() { + return "help"; + } + + protected Map getCommands() { + return MinecraftServer.getServer().getCommandManager().getCommands(); + } + + /** + * + Gets the usage string for the command. + */ + public String getCommandUsage(ICommandSender var1) { + return "commands.help.usage"; + } + + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 0; + } + + /** + * + Returns a sorted list of all possible commands for the given + * ICommandSender. + */ + protected List getSortedPossibleCommands(ICommandSender parICommandSender) { + List list = MinecraftServer.getServer().getCommandManager().getPossibleCommands(parICommandSender); + Collections.sort(list); + return list; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { List list = this.getSortedPossibleCommands(parICommandSender); @@ -111,30 +141,4 @@ public class CommandHelp extends CommandBase { } } - - /**+ - * Returns a sorted list of all possible commands for the given - * ICommandSender. - */ - protected List getSortedPossibleCommands(ICommandSender parICommandSender) { - List list = MinecraftServer.getServer().getCommandManager().getPossibleCommands(parICommandSender); - Collections.sort(list); - return list; - } - - protected Map getCommands() { - return MinecraftServer.getServer().getCommandManager().getCommands(); - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - if (astring.length == 1) { - Set set = this.getCommands().keySet(); - return getListOfStringsMatchingLastWord(astring, (String[]) set.toArray(new String[set.size()])); - } else { - return null; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandKill.java b/src/game/java/net/minecraft/command/CommandKill.java index 73297cf3..0aec4d68 100644 --- a/src/game/java/net/minecraft/command/CommandKill.java +++ b/src/game/java/net/minecraft/command/CommandKill.java @@ -1,56 +1,77 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandKill extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "kill"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.kill.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length == 0) { @@ -65,21 +86,4 @@ public class CommandKill extends CommandBase { new Object[] { entity.getDisplayName() }); } } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandNotFoundException.java b/src/game/java/net/minecraft/command/CommandNotFoundException.java index 1a6d696e..4b8b0cf4 100644 --- a/src/game/java/net/minecraft/command/CommandNotFoundException.java +++ b/src/game/java/net/minecraft/command/CommandNotFoundException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/CommandParticle.java b/src/game/java/net/minecraft/command/CommandParticle.java index 130a55d7..2abfd8aa 100644 --- a/src/game/java/net/minecraft/command/CommandParticle.java +++ b/src/game/java/net/minecraft/command/CommandParticle.java @@ -1,57 +1,72 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandParticle extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, EnumParticleTypes.getParticleNames()) + : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) + : (astring.length == 10 + ? getListOfStringsMatchingLastWord(astring, new String[] { "normal", "force" }) + : null)); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "particle"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.particle.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 8) { @@ -123,15 +138,4 @@ public class CommandParticle extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, EnumParticleTypes.getParticleNames()) - : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) - : (astring.length == 10 - ? getListOfStringsMatchingLastWord(astring, new String[] { "normal", "force" }) - : null)); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandPlaySound.java b/src/game/java/net/minecraft/command/CommandPlaySound.java index 9c8ae28f..3d174a1f 100644 --- a/src/game/java/net/minecraft/command/CommandPlaySound.java +++ b/src/game/java/net/minecraft/command/CommandPlaySound.java @@ -1,57 +1,78 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S29PacketSoundEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandPlaySound extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 2 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : (astring.length > 2 && astring.length <= 5 ? func_175771_a(astring, 2, blockpos) : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "playsound"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.playsound.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 1; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -118,21 +139,4 @@ public class CommandPlaySound extends CommandBase { new Object[] { s, entityplayermp.getName() }); } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 2 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : (astring.length > 2 && astring.length <= 5 ? func_175771_a(astring, 2, blockpos) : null); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandReplaceItem.java b/src/game/java/net/minecraft/command/CommandReplaceItem.java index 83da458d..3fd49a66 100644 --- a/src/game/java/net/minecraft/command/CommandReplaceItem.java +++ b/src/game/java/net/minecraft/command/CommandReplaceItem.java @@ -1,8 +1,10 @@ package net.minecraft.command; -import com.google.common.collect.Maps; import java.util.List; import java.util.Map; + +import com.google.common.collect.Maps; + import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; @@ -17,22 +19,25 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,29 +46,103 @@ public class CommandReplaceItem extends CommandBase { private static final Map SHORTCUTS = Maps.newHashMap(); - /**+ - * Gets the name of the command + static { + for (int i = 0; i < 54; ++i) { + SHORTCUTS.put("slot.container." + i, Integer.valueOf(i)); + } + + for (int j = 0; j < 9; ++j) { + SHORTCUTS.put("slot.hotbar." + j, Integer.valueOf(j)); + } + + for (int k = 0; k < 27; ++k) { + SHORTCUTS.put("slot.inventory." + k, Integer.valueOf(9 + k)); + } + + for (int l = 0; l < 27; ++l) { + SHORTCUTS.put("slot.enderchest." + l, Integer.valueOf(200 + l)); + } + + for (int i1 = 0; i1 < 8; ++i1) { + SHORTCUTS.put("slot.villager." + i1, Integer.valueOf(300 + i1)); + } + + for (int j1 = 0; j1 < 15; ++j1) { + SHORTCUTS.put("slot.horse." + j1, Integer.valueOf(500 + j1)); + } + + SHORTCUTS.put("slot.weapon", Integer.valueOf(99)); + SHORTCUTS.put("slot.armor.head", Integer.valueOf(103)); + SHORTCUTS.put("slot.armor.chest", Integer.valueOf(102)); + SHORTCUTS.put("slot.armor.legs", Integer.valueOf(101)); + SHORTCUTS.put("slot.armor.feet", Integer.valueOf(100)); + SHORTCUTS.put("slot.horse.saddle", Integer.valueOf(400)); + SHORTCUTS.put("slot.horse.armor", Integer.valueOf(401)); + SHORTCUTS.put("slot.horse.chest", Integer.valueOf(499)); + } + + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, new String[] { "entity", "block" }) + : (astring.length == 2 && astring[0].equals("entity") + ? getListOfStringsMatchingLastWord(astring, this.getUsernames()) + : (astring.length >= 2 && astring.length <= 4 && astring[0].equals("block") + ? func_175771_a(astring, 1, blockpos) + : ((astring.length != 3 || !astring[0].equals("entity")) + && (astring.length != 5 || !astring[0].equals("block")) + ? ((astring.length != 4 || !astring[0].equals("entity")) + && (astring.length != 6 || !astring[0].equals("block")) + ? null + : getListOfStringsMatchingLastWord(astring, + Item.itemRegistry.getKeys())) + : getListOfStringsMatchingLastWord(astring, SHORTCUTS.keySet())))); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "replaceitem"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.replaceitem.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + private int getSlotForShortcut(String shortcut) throws CommandException { + if (!SHORTCUTS.containsKey(shortcut)) { + throw new CommandException("commands.generic.parameter.invalid", new Object[] { shortcut }); + } else { + return ((Integer) SHORTCUTS.get(shortcut)).intValue(); + } + } + + protected String[] getUsernames() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] astring, int i) { + return astring.length > 0 && astring[0].equals("entity") && i == 1; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 1) { @@ -164,78 +243,4 @@ public class CommandReplaceItem extends CommandBase { Integer.valueOf(k), itemstack == null ? "Air" : itemstack.getChatComponent() }); } } - - private int getSlotForShortcut(String shortcut) throws CommandException { - if (!SHORTCUTS.containsKey(shortcut)) { - throw new CommandException("commands.generic.parameter.invalid", new Object[] { shortcut }); - } else { - return ((Integer) SHORTCUTS.get(shortcut)).intValue(); - } - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, new String[] { "entity", "block" }) - : (astring.length == 2 && astring[0].equals("entity") - ? getListOfStringsMatchingLastWord(astring, this.getUsernames()) - : (astring.length >= 2 && astring.length <= 4 && astring[0].equals("block") - ? func_175771_a(astring, 1, blockpos) - : ((astring.length != 3 || !astring[0].equals("entity")) - && (astring.length != 5 || !astring[0].equals("block")) - ? ((astring.length != 4 || !astring[0].equals("entity")) - && (astring.length != 6 || !astring[0].equals("block")) - ? null - : getListOfStringsMatchingLastWord(astring, - Item.itemRegistry.getKeys())) - : getListOfStringsMatchingLastWord(astring, SHORTCUTS.keySet())))); - } - - protected String[] getUsernames() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] astring, int i) { - return astring.length > 0 && astring[0].equals("entity") && i == 1; - } - - static { - for (int i = 0; i < 54; ++i) { - SHORTCUTS.put("slot.container." + i, Integer.valueOf(i)); - } - - for (int j = 0; j < 9; ++j) { - SHORTCUTS.put("slot.hotbar." + j, Integer.valueOf(j)); - } - - for (int k = 0; k < 27; ++k) { - SHORTCUTS.put("slot.inventory." + k, Integer.valueOf(9 + k)); - } - - for (int l = 0; l < 27; ++l) { - SHORTCUTS.put("slot.enderchest." + l, Integer.valueOf(200 + l)); - } - - for (int i1 = 0; i1 < 8; ++i1) { - SHORTCUTS.put("slot.villager." + i1, Integer.valueOf(300 + i1)); - } - - for (int j1 = 0; j1 < 15; ++j1) { - SHORTCUTS.put("slot.horse." + j1, Integer.valueOf(500 + j1)); - } - - SHORTCUTS.put("slot.weapon", Integer.valueOf(99)); - SHORTCUTS.put("slot.armor.head", Integer.valueOf(103)); - SHORTCUTS.put("slot.armor.chest", Integer.valueOf(102)); - SHORTCUTS.put("slot.armor.legs", Integer.valueOf(101)); - SHORTCUTS.put("slot.armor.feet", Integer.valueOf(100)); - SHORTCUTS.put("slot.horse.saddle", Integer.valueOf(400)); - SHORTCUTS.put("slot.horse.armor", Integer.valueOf(401)); - SHORTCUTS.put("slot.horse.chest", Integer.valueOf(499)); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandResultStats.java b/src/game/java/net/minecraft/command/CommandResultStats.java index f8bb3ea1..439ab751 100644 --- a/src/game/java/net/minecraft/command/CommandResultStats.java +++ b/src/game/java/net/minecraft/command/CommandResultStats.java @@ -10,34 +10,127 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandResultStats { - /**+ - * The number of result command result types that are possible. + public static enum Type { + SUCCESS_COUNT(0, "SuccessCount"), AFFECTED_BLOCKS(1, "AffectedBlocks"), + AFFECTED_ENTITIES(2, "AffectedEntities"), AFFECTED_ITEMS(3, "AffectedItems"), QUERY_RESULT(4, "QueryResult"); + + public static final Type[] _VALUES = values(); + + public static CommandResultStats.Type getTypeByName(String name) { + CommandResultStats.Type[] types = _VALUES; + for (int i = 0; i < types.length; ++i) { + CommandResultStats.Type commandresultstats$type = types[i]; + if (commandresultstats$type.getTypeName().equals(name)) { + return commandresultstats$type; + } + } + + return null; + } + + public static String[] getTypeNames() { + String[] astring = new String[_VALUES.length]; + int i = 0; + + CommandResultStats.Type[] types = _VALUES; + for (int j = 0; j < types.length; ++j) { + astring[i++] = types[j].getTypeName(); + } + + return astring; + } + + final int typeID; + + final String typeName; + + private Type(int id, String name) { + this.typeID = id; + this.typeName = name; + } + + public int getTypeID() { + return this.typeID; + } + + public String getTypeName() { + return this.typeName; + } + } + + /** + * + The number of result command result types that are possible. */ private static final int NUM_RESULT_TYPES = CommandResultStats.Type._VALUES.length; private static final String[] STRING_RESULT_TYPES = new String[NUM_RESULT_TYPES]; + + public static void func_179667_a(CommandResultStats stats, CommandResultStats.Type resultType, String parString1, + String parString2) { + if (parString1 != null && parString1.length() != 0 && parString2 != null && parString2.length() != 0) { + if (stats.field_179675_c == STRING_RESULT_TYPES || stats.field_179673_d == STRING_RESULT_TYPES) { + stats.field_179675_c = new String[NUM_RESULT_TYPES]; + stats.field_179673_d = new String[NUM_RESULT_TYPES]; + } + + stats.field_179675_c[resultType.getTypeID()] = parString1; + stats.field_179673_d[resultType.getTypeID()] = parString2; + } else { + func_179669_a(stats, resultType); + } + } + + private static void func_179669_a(CommandResultStats resultStatsIn, CommandResultStats.Type resultTypeIn) { + if (resultStatsIn.field_179675_c != STRING_RESULT_TYPES + && resultStatsIn.field_179673_d != STRING_RESULT_TYPES) { + resultStatsIn.field_179675_c[resultTypeIn.getTypeID()] = null; + resultStatsIn.field_179673_d[resultTypeIn.getTypeID()] = null; + boolean flag = true; + + CommandResultStats.Type[] types = CommandResultStats.Type.values(); + for (int i = 0; i < types.length; ++i) { + CommandResultStats.Type commandresultstats$type = types[i]; + if (resultStatsIn.field_179675_c[commandresultstats$type.getTypeID()] != null + && resultStatsIn.field_179673_d[commandresultstats$type.getTypeID()] != null) { + flag = false; + break; + } + } + + if (flag) { + resultStatsIn.field_179675_c = STRING_RESULT_TYPES; + resultStatsIn.field_179673_d = STRING_RESULT_TYPES; + } + + } + } + private String[] field_179675_c; + private String[] field_179673_d; public CommandResultStats() { @@ -45,18 +138,21 @@ public class CommandResultStats { this.field_179673_d = STRING_RESULT_TYPES; } + public void func_179671_a(CommandResultStats resultStatsIn) { + CommandResultStats.Type[] types = CommandResultStats.Type.values(); + for (int i = 0; i < types.length; ++i) { + CommandResultStats.Type commandresultstats$type = types[i]; + func_179667_a(this, commandresultstats$type, + resultStatsIn.field_179675_c[commandresultstats$type.getTypeID()], + resultStatsIn.field_179673_d[commandresultstats$type.getTypeID()]); + } + + } + public void func_179672_a(final ICommandSender sender, CommandResultStats.Type resultTypeIn, int parInt1) { String s = this.field_179675_c[resultTypeIn.getTypeID()]; if (s != null) { ICommandSender icommandsender = new ICommandSender() { - public String getName() { - return sender.getName(); - } - - public IChatComponent getDisplayName() { - return sender.getDisplayName(); - } - public void addChatMessage(IChatComponent ichatcomponent) { sender.addChatMessage(ichatcomponent); } @@ -65,20 +161,28 @@ public class CommandResultStats { return true; } - public BlockPos getPosition() { - return sender.getPosition(); + public Entity getCommandSenderEntity() { + return sender.getCommandSenderEntity(); } - public Vec3 getPositionVector() { - return sender.getPositionVector(); + public IChatComponent getDisplayName() { + return sender.getDisplayName(); } public World getEntityWorld() { return sender.getEntityWorld(); } - public Entity getCommandSenderEntity() { - return sender.getCommandSenderEntity(); + public String getName() { + return sender.getName(); + } + + public BlockPos getPosition() { + return sender.getPosition(); + } + + public Vec3 getPositionVector() { + return sender.getPositionVector(); } public boolean sendCommandFeedback() { @@ -149,102 +253,4 @@ public class CommandResultStats { } } - - public static void func_179667_a(CommandResultStats stats, CommandResultStats.Type resultType, String parString1, - String parString2) { - if (parString1 != null && parString1.length() != 0 && parString2 != null && parString2.length() != 0) { - if (stats.field_179675_c == STRING_RESULT_TYPES || stats.field_179673_d == STRING_RESULT_TYPES) { - stats.field_179675_c = new String[NUM_RESULT_TYPES]; - stats.field_179673_d = new String[NUM_RESULT_TYPES]; - } - - stats.field_179675_c[resultType.getTypeID()] = parString1; - stats.field_179673_d[resultType.getTypeID()] = parString2; - } else { - func_179669_a(stats, resultType); - } - } - - private static void func_179669_a(CommandResultStats resultStatsIn, CommandResultStats.Type resultTypeIn) { - if (resultStatsIn.field_179675_c != STRING_RESULT_TYPES - && resultStatsIn.field_179673_d != STRING_RESULT_TYPES) { - resultStatsIn.field_179675_c[resultTypeIn.getTypeID()] = null; - resultStatsIn.field_179673_d[resultTypeIn.getTypeID()] = null; - boolean flag = true; - - CommandResultStats.Type[] types = CommandResultStats.Type.values(); - for (int i = 0; i < types.length; ++i) { - CommandResultStats.Type commandresultstats$type = types[i]; - if (resultStatsIn.field_179675_c[commandresultstats$type.getTypeID()] != null - && resultStatsIn.field_179673_d[commandresultstats$type.getTypeID()] != null) { - flag = false; - break; - } - } - - if (flag) { - resultStatsIn.field_179675_c = STRING_RESULT_TYPES; - resultStatsIn.field_179673_d = STRING_RESULT_TYPES; - } - - } - } - - public void func_179671_a(CommandResultStats resultStatsIn) { - CommandResultStats.Type[] types = CommandResultStats.Type.values(); - for (int i = 0; i < types.length; ++i) { - CommandResultStats.Type commandresultstats$type = types[i]; - func_179667_a(this, commandresultstats$type, - resultStatsIn.field_179675_c[commandresultstats$type.getTypeID()], - resultStatsIn.field_179673_d[commandresultstats$type.getTypeID()]); - } - - } - - public static enum Type { - SUCCESS_COUNT(0, "SuccessCount"), AFFECTED_BLOCKS(1, "AffectedBlocks"), - AFFECTED_ENTITIES(2, "AffectedEntities"), AFFECTED_ITEMS(3, "AffectedItems"), QUERY_RESULT(4, "QueryResult"); - - public static final Type[] _VALUES = values(); - - final int typeID; - final String typeName; - - private Type(int id, String name) { - this.typeID = id; - this.typeName = name; - } - - public int getTypeID() { - return this.typeID; - } - - public String getTypeName() { - return this.typeName; - } - - public static String[] getTypeNames() { - String[] astring = new String[_VALUES.length]; - int i = 0; - - CommandResultStats.Type[] types = _VALUES; - for (int j = 0; j < types.length; ++j) { - astring[i++] = types[j].getTypeName(); - } - - return astring; - } - - public static CommandResultStats.Type getTypeByName(String name) { - CommandResultStats.Type[] types = _VALUES; - for (int i = 0; i < types.length; ++i) { - CommandResultStats.Type commandresultstats$type = types[i]; - if (commandresultstats$type.getTypeName().equals(name)) { - return commandresultstats$type; - } - } - - return null; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandServerKick.java b/src/game/java/net/minecraft/command/CommandServerKick.java index 8ee27cd0..b76f8491 100644 --- a/src/game/java/net/minecraft/command/CommandServerKick.java +++ b/src/game/java/net/minecraft/command/CommandServerKick.java @@ -1,56 +1,69 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandServerKick extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length >= 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "kick"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 3; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.kick.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 3; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length > 0 && parArrayOfString[0].length() > 1) { @@ -84,13 +97,4 @@ public class CommandServerKick extends CommandBase { throw new WrongUsageException("commands.kick.usage", new Object[0]); } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length >= 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandSetPlayerTimeout.java b/src/game/java/net/minecraft/command/CommandSetPlayerTimeout.java index 891950e5..df9bb7de 100644 --- a/src/game/java/net/minecraft/command/CommandSetPlayerTimeout.java +++ b/src/game/java/net/minecraft/command/CommandSetPlayerTimeout.java @@ -2,51 +2,54 @@ package net.minecraft.command; import net.minecraft.server.MinecraftServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandSetPlayerTimeout extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "setidletimeout"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 3; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.setidletimeout.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 3; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length != 1) { diff --git a/src/game/java/net/minecraft/command/CommandSetSpawnpoint.java b/src/game/java/net/minecraft/command/CommandSetSpawnpoint.java index 67179bce..01070a13 100644 --- a/src/game/java/net/minecraft/command/CommandSetSpawnpoint.java +++ b/src/game/java/net/minecraft/command/CommandSetSpawnpoint.java @@ -1,55 +1,76 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandSetSpawnpoint extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "spawnpoint"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.spawnpoint.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length > 1 && parArrayOfString.length < 4) { @@ -70,21 +91,4 @@ public class CommandSetSpawnpoint extends CommandBase { } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) : null); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandShowSeed.java b/src/game/java/net/minecraft/command/CommandShowSeed.java index 01071669..c0ed1479 100644 --- a/src/game/java/net/minecraft/command/CommandShowSeed.java +++ b/src/game/java/net/minecraft/command/CommandShowSeed.java @@ -5,59 +5,61 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandShowSeed extends CommandBase { - /**+ - * Returns true if the given command sender is allowed to use - * this command. + /** + * + Returns true if the given command sender is allowed to use this command. */ public boolean canCommandSenderUseCommand(ICommandSender icommandsender) { return MinecraftServer.getServer().isSinglePlayer() || super.canCommandSenderUseCommand(icommandsender); } - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "seed"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.seed.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { Object object = parICommandSender instanceof EntityPlayer ? ((EntityPlayer) parICommandSender).worldObj diff --git a/src/game/java/net/minecraft/command/CommandSpreadPlayers.java b/src/game/java/net/minecraft/command/CommandSpreadPlayers.java index dce94478..2a405cfa 100644 --- a/src/game/java/net/minecraft/command/CommandSpreadPlayers.java +++ b/src/game/java/net/minecraft/command/CommandSpreadPlayers.java @@ -1,12 +1,14 @@ package net.minecraft.command; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.HString; import net.lax1dude.eaglercraft.v1_8.ThreadLocalRandom; @@ -21,120 +23,125 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandSpreadPlayers extends CommandBase { - /**+ - * Gets the name of the command - */ - public String getCommandName() { - return "spreadplayers"; - } + static class Position { + double field_111101_a; + double field_111100_b; - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } + Position() { + } - /**+ - * Gets the usage string for the command. - */ - public String getCommandUsage(ICommandSender var1) { - return "commands.spreadplayers.usage"; - } + Position(double parDouble1, double parDouble2) { + this.field_111101_a = parDouble1; + this.field_111100_b = parDouble2; + } - /**+ - * Callback when the command is invoked - */ - public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { - if (parArrayOfString.length < 6) { - throw new WrongUsageException("commands.spreadplayers.usage", new Object[0]); - } else { - int i = 0; - BlockPos blockpos = parICommandSender.getPosition(); - double d0 = parseDouble((double) blockpos.getX(), parArrayOfString[i++], true); - double d1 = parseDouble((double) blockpos.getZ(), parArrayOfString[i++], true); - double d2 = parseDouble(parArrayOfString[i++], 0.0D); - double d3 = parseDouble(parArrayOfString[i++], d2 + 1.0D); - boolean flag = parseBoolean(parArrayOfString[i++]); - ArrayList arraylist = Lists.newArrayList(); + public int func_111092_a(World worldIn) { + BlockPos blockpos = new BlockPos(this.field_111101_a, 256.0D, this.field_111100_b); - while (i < parArrayOfString.length) { - String s = parArrayOfString[i++]; - if (PlayerSelector.hasArguments(s)) { - List list = PlayerSelector.matchEntities(parICommandSender, s, Entity.class); - if (list.size() == 0) { - throw new EntityNotFoundException(); - } - - arraylist.addAll(list); - } else { - EntityPlayerMP entityplayermp = MinecraftServer.getServer().getConfigurationManager() - .getPlayerByUsername(s); - if (entityplayermp == null) { - throw new PlayerNotFoundException(); - } - - arraylist.add(entityplayermp); + while (blockpos.getY() > 0) { + blockpos = blockpos.down(); + if (worldIn.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { + return blockpos.getY() + 1; } } - parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, arraylist.size()); - if (arraylist.isEmpty()) { - throw new EntityNotFoundException(); - } else { - parICommandSender.addChatMessage( - new ChatComponentTranslation("commands.spreadplayers.spreading." + (flag ? "teams" : "players"), - new Object[] { Integer.valueOf(arraylist.size()), Double.valueOf(d3), - Double.valueOf(d0), Double.valueOf(d1), Double.valueOf(d2) })); - this.func_110669_a(parICommandSender, arraylist, new CommandSpreadPlayers.Position(d0, d1), d2, d3, - ((Entity) arraylist.get(0)).worldObj, flag); + return 257; + } + + public boolean func_111093_a(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { + boolean flag = false; + if (this.field_111101_a < parDouble1) { + this.field_111101_a = parDouble1; + flag = true; + } else if (this.field_111101_a > parDouble3) { + this.field_111101_a = parDouble3; + flag = true; } + + if (this.field_111100_b < parDouble2) { + this.field_111100_b = parDouble2; + flag = true; + } else if (this.field_111100_b > parDouble4) { + this.field_111100_b = parDouble4; + flag = true; + } + + return flag; + } + + public void func_111094_b(CommandSpreadPlayers.Position parPosition) { + this.field_111101_a -= parPosition.field_111101_a; + this.field_111100_b -= parPosition.field_111100_b; + } + + void func_111095_a() { + double d0 = (double) this.func_111096_b(); + this.field_111101_a /= d0; + this.field_111100_b /= d0; + } + + float func_111096_b() { + return MathHelper + .sqrt_double(this.field_111101_a * this.field_111101_a + this.field_111100_b * this.field_111100_b); + } + + public void func_111097_a(EaglercraftRandom parRandom, double parDouble1, double parDouble2, double parDouble3, + double parDouble4) { + this.field_111101_a = MathHelper.getRandomDoubleInRange(parRandom, parDouble1, parDouble3); + this.field_111100_b = MathHelper.getRandomDoubleInRange(parRandom, parDouble2, parDouble4); + } + + public boolean func_111098_b(World worldIn) { + BlockPos blockpos = new BlockPos(this.field_111101_a, 256.0D, this.field_111100_b); + + while (blockpos.getY() > 0) { + blockpos = blockpos.down(); + Material material = worldIn.getBlockState(blockpos).getBlock().getMaterial(); + if (material != Material.air) { + return !material.isLiquid() && material != Material.fire; + } + } + + return false; + } + + double func_111099_a(CommandSpreadPlayers.Position parPosition) { + double d0 = this.field_111101_a - parPosition.field_111101_a; + double d1 = this.field_111100_b - parPosition.field_111100_b; + return Math.sqrt(d0 * d0 + d1 * d1); } } - private void func_110669_a(ICommandSender worldIn, List parList, CommandSpreadPlayers.Position parPosition, - double parDouble1, double parDouble2, World parWorld, boolean parFlag) throws CommandException { - EaglercraftRandom random = ThreadLocalRandom.current(); - double d0 = parPosition.field_111101_a - parDouble2; - double d1 = parPosition.field_111100_b - parDouble2; - double d2 = parPosition.field_111101_a + parDouble2; - double d3 = parPosition.field_111100_b + parDouble2; - CommandSpreadPlayers.Position[] acommandspreadplayers$position = this.func_110670_a(random, - parFlag ? this.func_110667_a(parList) : parList.size(), d0, d1, d2, d3); - int i = this.func_110668_a(parPosition, parDouble1, parWorld, random, d0, d1, d2, d3, - acommandspreadplayers$position, parFlag); - double d4 = this.func_110671_a(parList, parWorld, acommandspreadplayers$position, parFlag); - notifyOperators(worldIn, this, "commands.spreadplayers.success." + (parFlag ? "teams" : "players"), - new Object[] { Integer.valueOf(acommandspreadplayers$position.length), - Double.valueOf(parPosition.field_111101_a), Double.valueOf(parPosition.field_111100_b) }); - if (acommandspreadplayers$position.length > 1) { - worldIn.addChatMessage(new ChatComponentTranslation( - "commands.spreadplayers.info." + (parFlag ? "teams" : "players"), - new Object[] { HString.format("%.2f", new Object[] { Double.valueOf(d4) }), Integer.valueOf(i) })); - } - + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length >= 1 && astring.length <= 2 ? func_181043_b(astring, 0, blockpos) : null; } private int func_110667_a(List parList) { @@ -223,6 +230,42 @@ public class CommandSpreadPlayers extends CommandBase { } } + private void func_110669_a(ICommandSender worldIn, List parList, CommandSpreadPlayers.Position parPosition, + double parDouble1, double parDouble2, World parWorld, boolean parFlag) throws CommandException { + EaglercraftRandom random = ThreadLocalRandom.current(); + double d0 = parPosition.field_111101_a - parDouble2; + double d1 = parPosition.field_111100_b - parDouble2; + double d2 = parPosition.field_111101_a + parDouble2; + double d3 = parPosition.field_111100_b + parDouble2; + CommandSpreadPlayers.Position[] acommandspreadplayers$position = this.func_110670_a(random, + parFlag ? this.func_110667_a(parList) : parList.size(), d0, d1, d2, d3); + int i = this.func_110668_a(parPosition, parDouble1, parWorld, random, d0, d1, d2, d3, + acommandspreadplayers$position, parFlag); + double d4 = this.func_110671_a(parList, parWorld, acommandspreadplayers$position, parFlag); + notifyOperators(worldIn, this, "commands.spreadplayers.success." + (parFlag ? "teams" : "players"), + new Object[] { Integer.valueOf(acommandspreadplayers$position.length), + Double.valueOf(parPosition.field_111101_a), Double.valueOf(parPosition.field_111100_b) }); + if (acommandspreadplayers$position.length > 1) { + worldIn.addChatMessage(new ChatComponentTranslation( + "commands.spreadplayers.info." + (parFlag ? "teams" : "players"), + new Object[] { HString.format("%.2f", new Object[] { Double.valueOf(d4) }), Integer.valueOf(i) })); + } + + } + + private CommandSpreadPlayers.Position[] func_110670_a(EaglercraftRandom parRandom, int parInt1, double parDouble1, + double parDouble2, double parDouble3, double parDouble4) { + CommandSpreadPlayers.Position[] acommandspreadplayers$position = new CommandSpreadPlayers.Position[parInt1]; + + for (int i = 0; i < acommandspreadplayers$position.length; ++i) { + CommandSpreadPlayers.Position commandspreadplayers$position = new CommandSpreadPlayers.Position(); + commandspreadplayers$position.func_111097_a(parRandom, parDouble1, parDouble2, parDouble3, parDouble4); + acommandspreadplayers$position[i] = commandspreadplayers$position; + } + + return acommandspreadplayers$position; + } + private double func_110671_a(List worldIn, World parWorld, CommandSpreadPlayers.Position[] parArrayOfPosition, boolean parFlag) { double d0 = 0.0D; @@ -263,112 +306,74 @@ public class CommandSpreadPlayers extends CommandBase { return d0; } - private CommandSpreadPlayers.Position[] func_110670_a(EaglercraftRandom parRandom, int parInt1, double parDouble1, - double parDouble2, double parDouble3, double parDouble4) { - CommandSpreadPlayers.Position[] acommandspreadplayers$position = new CommandSpreadPlayers.Position[parInt1]; - - for (int i = 0; i < acommandspreadplayers$position.length; ++i) { - CommandSpreadPlayers.Position commandspreadplayers$position = new CommandSpreadPlayers.Position(); - commandspreadplayers$position.func_111097_a(parRandom, parDouble1, parDouble2, parDouble3, parDouble4); - acommandspreadplayers$position[i] = commandspreadplayers$position; - } - - return acommandspreadplayers$position; - } - - /**+ - * Return a list of options when the user types TAB + /** + * + Gets the name of the command */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length >= 1 && astring.length <= 2 ? func_181043_b(astring, 0, blockpos) : null; + public String getCommandName() { + return "spreadplayers"; } - static class Position { - double field_111101_a; - double field_111100_b; + /** + * + Gets the usage string for the command. + */ + public String getCommandUsage(ICommandSender var1) { + return "commands.spreadplayers.usage"; + } - Position() { - } + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } - Position(double parDouble1, double parDouble2) { - this.field_111101_a = parDouble1; - this.field_111100_b = parDouble2; - } + /** + * + Callback when the command is invoked + */ + public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { + if (parArrayOfString.length < 6) { + throw new WrongUsageException("commands.spreadplayers.usage", new Object[0]); + } else { + int i = 0; + BlockPos blockpos = parICommandSender.getPosition(); + double d0 = parseDouble((double) blockpos.getX(), parArrayOfString[i++], true); + double d1 = parseDouble((double) blockpos.getZ(), parArrayOfString[i++], true); + double d2 = parseDouble(parArrayOfString[i++], 0.0D); + double d3 = parseDouble(parArrayOfString[i++], d2 + 1.0D); + boolean flag = parseBoolean(parArrayOfString[i++]); + ArrayList arraylist = Lists.newArrayList(); - double func_111099_a(CommandSpreadPlayers.Position parPosition) { - double d0 = this.field_111101_a - parPosition.field_111101_a; - double d1 = this.field_111100_b - parPosition.field_111100_b; - return Math.sqrt(d0 * d0 + d1 * d1); - } + while (i < parArrayOfString.length) { + String s = parArrayOfString[i++]; + if (PlayerSelector.hasArguments(s)) { + List list = PlayerSelector.matchEntities(parICommandSender, s, Entity.class); + if (list.size() == 0) { + throw new EntityNotFoundException(); + } - void func_111095_a() { - double d0 = (double) this.func_111096_b(); - this.field_111101_a /= d0; - this.field_111100_b /= d0; - } + arraylist.addAll(list); + } else { + EntityPlayerMP entityplayermp = MinecraftServer.getServer().getConfigurationManager() + .getPlayerByUsername(s); + if (entityplayermp == null) { + throw new PlayerNotFoundException(); + } - float func_111096_b() { - return MathHelper - .sqrt_double(this.field_111101_a * this.field_111101_a + this.field_111100_b * this.field_111100_b); - } - - public void func_111094_b(CommandSpreadPlayers.Position parPosition) { - this.field_111101_a -= parPosition.field_111101_a; - this.field_111100_b -= parPosition.field_111100_b; - } - - public boolean func_111093_a(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { - boolean flag = false; - if (this.field_111101_a < parDouble1) { - this.field_111101_a = parDouble1; - flag = true; - } else if (this.field_111101_a > parDouble3) { - this.field_111101_a = parDouble3; - flag = true; - } - - if (this.field_111100_b < parDouble2) { - this.field_111100_b = parDouble2; - flag = true; - } else if (this.field_111100_b > parDouble4) { - this.field_111100_b = parDouble4; - flag = true; - } - - return flag; - } - - public int func_111092_a(World worldIn) { - BlockPos blockpos = new BlockPos(this.field_111101_a, 256.0D, this.field_111100_b); - - while (blockpos.getY() > 0) { - blockpos = blockpos.down(); - if (worldIn.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { - return blockpos.getY() + 1; + arraylist.add(entityplayermp); } } - return 257; - } - - public boolean func_111098_b(World worldIn) { - BlockPos blockpos = new BlockPos(this.field_111101_a, 256.0D, this.field_111100_b); - - while (blockpos.getY() > 0) { - blockpos = blockpos.down(); - Material material = worldIn.getBlockState(blockpos).getBlock().getMaterial(); - if (material != Material.air) { - return !material.isLiquid() && material != Material.fire; - } + parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, arraylist.size()); + if (arraylist.isEmpty()) { + throw new EntityNotFoundException(); + } else { + parICommandSender.addChatMessage( + new ChatComponentTranslation("commands.spreadplayers.spreading." + (flag ? "teams" : "players"), + new Object[] { Integer.valueOf(arraylist.size()), Double.valueOf(d3), + Double.valueOf(d0), Double.valueOf(d1), Double.valueOf(d2) })); + this.func_110669_a(parICommandSender, arraylist, new CommandSpreadPlayers.Position(d0, d1), d2, d3, + ((Entity) arraylist.get(0)).worldObj, flag); } - - return false; - } - - public void func_111097_a(EaglercraftRandom parRandom, double parDouble1, double parDouble2, double parDouble3, - double parDouble4) { - this.field_111101_a = MathHelper.getRandomDoubleInRange(parRandom, parDouble1, parDouble3); - this.field_111100_b = MathHelper.getRandomDoubleInRange(parRandom, parDouble2, parDouble4); } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandStats.java b/src/game/java/net/minecraft/command/CommandStats.java index 0ece8d6b..fd104183 100644 --- a/src/game/java/net/minecraft/command/CommandStats.java +++ b/src/game/java/net/minecraft/command/CommandStats.java @@ -1,9 +1,11 @@ package net.minecraft.command; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Collection; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.entity.Entity; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.server.MinecraftServer; @@ -13,51 +15,106 @@ import net.minecraft.tileentity.TileEntitySign; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandStats extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, new String[] { "entity", "block" }) + : (astring.length == 2 && astring[0].equals("entity") + ? getListOfStringsMatchingLastWord(astring, this.func_175776_d()) + : (astring.length >= 2 && astring.length <= 4 && astring[0].equals("block") + ? func_175771_a(astring, 1, blockpos) + : ((astring.length != 3 || !astring[0].equals("entity")) + && (astring.length != 5 || !astring[0].equals("block")) + ? ((astring.length != 4 || !astring[0].equals("entity")) + && (astring.length != 6 || !astring[0].equals("block")) + ? ((astring.length != 6 || !astring[0].equals("entity")) + && (astring.length != 8 + || !astring[0].equals("block")) + ? null + : getListOfStringsMatchingLastWord( + astring, + this.func_175777_e())) + : getListOfStringsMatchingLastWord(astring, + CommandResultStats.Type.getTypeNames())) + : getListOfStringsMatchingLastWord(astring, + new String[] { "set", "clear" })))); + } + + protected String[] func_175776_d() { + return MinecraftServer.getServer().getAllUsernames(); + } + + protected List func_175777_e() { + Collection collection = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard() + .getScoreObjectives(); + ArrayList arraylist = Lists.newArrayList(); + + for (ScoreObjective scoreobjective : (Collection) collection) { + if (!scoreobjective.getCriteria().isReadOnly()) { + arraylist.add(scoreobjective.getName()); + } + } + + return arraylist; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "stats"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.stats.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] astring, int i) { + return astring.length > 0 && astring[0].equals("entity") && i == 1; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 1) { @@ -170,56 +227,4 @@ public class CommandStats extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, new String[] { "entity", "block" }) - : (astring.length == 2 && astring[0].equals("entity") - ? getListOfStringsMatchingLastWord(astring, this.func_175776_d()) - : (astring.length >= 2 && astring.length <= 4 && astring[0].equals("block") - ? func_175771_a(astring, 1, blockpos) - : ((astring.length != 3 || !astring[0].equals("entity")) - && (astring.length != 5 || !astring[0].equals("block")) - ? ((astring.length != 4 || !astring[0].equals("entity")) - && (astring.length != 6 || !astring[0].equals("block")) - ? ((astring.length != 6 || !astring[0].equals("entity")) - && (astring.length != 8 - || !astring[0].equals("block")) - ? null - : getListOfStringsMatchingLastWord( - astring, - this.func_175777_e())) - : getListOfStringsMatchingLastWord(astring, - CommandResultStats.Type.getTypeNames())) - : getListOfStringsMatchingLastWord(astring, - new String[] { "set", "clear" })))); - } - - protected String[] func_175776_d() { - return MinecraftServer.getServer().getAllUsernames(); - } - - protected List func_175777_e() { - Collection collection = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard() - .getScoreObjectives(); - ArrayList arraylist = Lists.newArrayList(); - - for (ScoreObjective scoreobjective : (Collection) collection) { - if (!scoreobjective.getCriteria().isReadOnly()) { - arraylist.add(scoreobjective.getName()); - } - } - - return arraylist; - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] astring, int i) { - return astring.length > 0 && astring[0].equals("entity") && i == 1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandTime.java b/src/game/java/net/minecraft/command/CommandTime.java index 7aa6b56a..37042d9e 100644 --- a/src/game/java/net/minecraft/command/CommandTime.java +++ b/src/game/java/net/minecraft/command/CommandTime.java @@ -1,55 +1,82 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandTime extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, new String[] { "set", "add", "query" }) + : (astring.length == 2 && astring[0].equals("set") + ? getListOfStringsMatchingLastWord(astring, new String[] { "day", "night" }) + : (astring.length == 2 && astring[0].equals("query") + ? getListOfStringsMatchingLastWord(astring, new String[] { "daytime", "gametime" }) + : null)); + } + + /** + * + Adds (or removes) time in the server object. + */ + protected void addTime(ICommandSender parICommandSender, int parInt1) { + for (int i = 0; i < MinecraftServer.getServer().worldServers.length; ++i) { + WorldServer worldserver = MinecraftServer.getServer().worldServers[i]; + worldserver.setWorldTime(worldserver.getWorldTime() + (long) parInt1); + } + + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "time"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.time.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length > 1) { @@ -97,20 +124,8 @@ public class CommandTime extends CommandBase { throw new WrongUsageException("commands.time.usage", new Object[0]); } - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, new String[] { "set", "add", "query" }) - : (astring.length == 2 && astring[0].equals("set") - ? getListOfStringsMatchingLastWord(astring, new String[] { "day", "night" }) - : (astring.length == 2 && astring[0].equals("query") - ? getListOfStringsMatchingLastWord(astring, new String[] { "daytime", "gametime" }) - : null)); - } - - /**+ - * Set the time in the server object. + /** + * + Set the time in the server object. */ protected void setTime(ICommandSender parICommandSender, int parInt1) { for (int i = 0; i < MinecraftServer.getServer().worldServers.length; ++i) { @@ -118,15 +133,4 @@ public class CommandTime extends CommandBase { } } - - /**+ - * Adds (or removes) time in the server object. - */ - protected void addTime(ICommandSender parICommandSender, int parInt1) { - for (int i = 0; i < MinecraftServer.getServer().worldServers.length; ++i) { - WorldServer worldserver = MinecraftServer.getServer().worldServers[i]; - worldserver.setWorldTime(worldserver.getWorldTime() + (long) parInt1); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandTitle.java b/src/game/java/net/minecraft/command/CommandTitle.java index 32c64493..12fd9aa0 100644 --- a/src/game/java/net/minecraft/command/CommandTitle.java +++ b/src/game/java/net/minecraft/command/CommandTitle.java @@ -4,32 +4,35 @@ import java.util.List; import org.json.JSONException; +import net.lax1dude.eaglercraft.v1_8.ExceptionUtils; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S45PacketTitle; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentProcessor; import net.minecraft.util.IChatComponent; -import net.lax1dude.eaglercraft.v1_8.ExceptionUtils; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,29 +41,47 @@ public class CommandTitle extends CommandBase { private static final Logger LOGGER = LogManager.getLogger(); - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, S45PacketTitle.Type.getNames()) + : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "title"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.title.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -118,22 +139,4 @@ public class CommandTitle extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : (astring.length == 2 ? getListOfStringsMatchingLastWord(astring, S45PacketTitle.Type.getNames()) - : null); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandToggleDownfall.java b/src/game/java/net/minecraft/command/CommandToggleDownfall.java index fe1e4ef3..35960164 100644 --- a/src/game/java/net/minecraft/command/CommandToggleDownfall.java +++ b/src/game/java/net/minecraft/command/CommandToggleDownfall.java @@ -3,59 +3,62 @@ package net.minecraft.command; import net.minecraft.server.MinecraftServer; import net.minecraft.world.storage.WorldInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandToggleDownfall extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "toggledownfall"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.downfall.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { this.toggleDownfall(); notifyOperators(parICommandSender, this, "commands.downfall.success", new Object[0]); } - /**+ - * Toggle rain and enable thundering. + /** + * + Toggle rain and enable thundering. */ protected void toggleDownfall() { WorldInfo worldinfo = MinecraftServer.getServer().worldServers[0].getWorldInfo(); diff --git a/src/game/java/net/minecraft/command/CommandTrigger.java b/src/game/java/net/minecraft/command/CommandTrigger.java index 4a143475..52294c29 100644 --- a/src/game/java/net/minecraft/command/CommandTrigger.java +++ b/src/game/java/net/minecraft/command/CommandTrigger.java @@ -1,8 +1,10 @@ package net.minecraft.command; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.scoreboard.IScoreObjectiveCriteria; @@ -12,51 +14,76 @@ import net.minecraft.scoreboard.Scoreboard; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandTrigger extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + if (astring.length == 1) { + Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); + ArrayList arraylist = Lists.newArrayList(); + + for (ScoreObjective scoreobjective : scoreboard.getScoreObjectives()) { + if (scoreobjective.getCriteria() == IScoreObjectiveCriteria.TRIGGER) { + arraylist.add(scoreobjective.getName()); + } + } + + return getListOfStringsMatchingLastWord(astring, + (String[]) arraylist.toArray(new String[arraylist.size()])); + } else { + return astring.length == 2 ? getListOfStringsMatchingLastWord(astring, new String[] { "add", "set" }) + : null; + } + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "trigger"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 0; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.trigger.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 3) { @@ -110,26 +137,4 @@ public class CommandTrigger extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - if (astring.length == 1) { - Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); - ArrayList arraylist = Lists.newArrayList(); - - for (ScoreObjective scoreobjective : scoreboard.getScoreObjectives()) { - if (scoreobjective.getCriteria() == IScoreObjectiveCriteria.TRIGGER) { - arraylist.add(scoreobjective.getName()); - } - } - - return getListOfStringsMatchingLastWord(astring, - (String[]) arraylist.toArray(new String[arraylist.size()])); - } else { - return astring.length == 2 ? getListOfStringsMatchingLastWord(astring, new String[] { "add", "set" }) - : null; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandWeather.java b/src/game/java/net/minecraft/command/CommandWeather.java index d355a704..225a3076 100644 --- a/src/game/java/net/minecraft/command/CommandWeather.java +++ b/src/game/java/net/minecraft/command/CommandWeather.java @@ -8,51 +8,63 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.WorldServer; import net.minecraft.world.storage.WorldInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandWeather extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, new String[] { "clear", "rain", "thunder" }) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "weather"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.weather.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length >= 1 && parArrayOfString.length <= 2) { @@ -94,13 +106,4 @@ public class CommandWeather extends CommandBase { throw new WrongUsageException("commands.weather.usage", new Object[0]); } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, new String[] { "clear", "rain", "thunder" }) - : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandWorldBorder.java b/src/game/java/net/minecraft/command/CommandWorldBorder.java index 5ced3eab..a96820a2 100644 --- a/src/game/java/net/minecraft/command/CommandWorldBorder.java +++ b/src/game/java/net/minecraft/command/CommandWorldBorder.java @@ -9,51 +9,74 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.MathHelper; import net.minecraft.world.border.WorldBorder; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandWorldBorder extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, + new String[] { "set", "center", "damage", "warning", "add", "get" }) + : (astring.length == 2 && astring[0].equals("damage") + ? getListOfStringsMatchingLastWord(astring, new String[] { "buffer", "amount" }) + : (astring.length >= 2 && astring.length <= 3 && astring[0].equals("center") + ? func_181043_b(astring, 1, blockpos) + : (astring.length == 2 && astring[0].equals("warning") + ? getListOfStringsMatchingLastWord(astring, new String[] { "time", "distance" }) + : null))); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "worldborder"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.worldborder.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + protected WorldBorder getWorldBorder() { + return MinecraftServer.getServer().worldServers[0].getWorldBorder(); + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 1) { @@ -195,24 +218,4 @@ public class CommandWorldBorder extends CommandBase { } } - - protected WorldBorder getWorldBorder() { - return MinecraftServer.getServer().worldServers[0].getWorldBorder(); - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, - new String[] { "set", "center", "damage", "warning", "add", "get" }) - : (astring.length == 2 && astring[0].equals("damage") - ? getListOfStringsMatchingLastWord(astring, new String[] { "buffer", "amount" }) - : (astring.length >= 2 && astring.length <= 3 && astring[0].equals("center") - ? func_181043_b(astring, 1, blockpos) - : (astring.length == 2 && astring[0].equals("warning") - ? getListOfStringsMatchingLastWord(astring, new String[] { "time", "distance" }) - : null))); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/CommandXP.java b/src/game/java/net/minecraft/command/CommandXP.java index 124ddb2d..ab8c4800 100644 --- a/src/game/java/net/minecraft/command/CommandXP.java +++ b/src/game/java/net/minecraft/command/CommandXP.java @@ -1,55 +1,78 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandXP extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 2 ? getListOfStringsMatchingLastWord(astring, this.getAllUsernames()) : null; + } + + protected String[] getAllUsernames() { + return MinecraftServer.getServer().getAllUsernames(); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "xp"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.xp.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 1; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length <= 0) { @@ -94,23 +117,4 @@ public class CommandXP extends CommandBase { } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 2 ? getListOfStringsMatchingLastWord(astring, this.getAllUsernames()) : null; - } - - protected String[] getAllUsernames() { - return MinecraftServer.getServer().getAllUsernames(); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/EntityNotFoundException.java b/src/game/java/net/minecraft/command/EntityNotFoundException.java index e68a162c..fc396ce9 100644 --- a/src/game/java/net/minecraft/command/EntityNotFoundException.java +++ b/src/game/java/net/minecraft/command/EntityNotFoundException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/IAdminCommand.java b/src/game/java/net/minecraft/command/IAdminCommand.java index 22677468..a1b221d6 100644 --- a/src/game/java/net/minecraft/command/IAdminCommand.java +++ b/src/game/java/net/minecraft/command/IAdminCommand.java @@ -1,28 +1,31 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IAdminCommand { - /**+ - * Send an informative message to the server operators + /** + * + Send an informative message to the server operators */ void notifyOperators(ICommandSender var1, ICommand var2, int var3, String var4, Object... var5); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/ICommand.java b/src/game/java/net/minecraft/command/ICommand.java index a4c137f4..21ffc7c2 100644 --- a/src/game/java/net/minecraft/command/ICommand.java +++ b/src/game/java/net/minecraft/command/ICommand.java @@ -1,63 +1,66 @@ package net.minecraft.command; import java.util.List; + import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ICommand extends Comparable { - /**+ - * Gets the name of the command - */ - String getCommandName(); - - /**+ - * Gets the usage string for the command. - */ - String getCommandUsage(ICommandSender var1); - - /**+ - * Gets a list of aliases for this command - */ - List getCommandAliases(); - - /**+ - * Callback when the command is invoked - */ - void processCommand(ICommandSender var1, String[] var2) throws CommandException; - - /**+ - * Returns true if the given command sender is allowed to use - * this command. - */ - boolean canCommandSenderUseCommand(ICommandSender var1); - - /**+ - * Return a list of options when the user types TAB + /** + * + Return a list of options when the user types TAB */ List addTabCompletionOptions(ICommandSender var1, String[] var2, BlockPos var3); - /**+ - * Return whether the specified command parameter index is a - * username parameter. + /** + * + Returns true if the given command sender is allowed to use this command. + */ + boolean canCommandSenderUseCommand(ICommandSender var1); + + /** + * + Gets a list of aliases for this command + */ + List getCommandAliases(); + + /** + * + Gets the name of the command + */ + String getCommandName(); + + /** + * + Gets the usage string for the command. + */ + String getCommandUsage(ICommandSender var1); + + /** + * + Return whether the specified command parameter index is a username + * parameter. */ boolean isUsernameIndex(String[] var1, int var2); + + /** + * + Callback when the command is invoked + */ + void processCommand(ICommandSender var1, String[] var2) throws CommandException; } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/ICommandManager.java b/src/game/java/net/minecraft/command/ICommandManager.java index d31794f0..82337c54 100644 --- a/src/game/java/net/minecraft/command/ICommandManager.java +++ b/src/game/java/net/minecraft/command/ICommandManager.java @@ -2,24 +2,28 @@ package net.minecraft.command; import java.util.List; import java.util.Map; + import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,12 +31,12 @@ import net.minecraft.util.BlockPos; public interface ICommandManager { int executeCommand(ICommandSender var1, String var2); - List getTabCompletionOptions(ICommandSender var1, String var2, BlockPos var3); + Map getCommands(); - /**+ - * returns all commands that the commandSender can use + /** + * + returns all commands that the commandSender can use */ List getPossibleCommands(ICommandSender var1); - Map getCommands(); + List getTabCompletionOptions(ICommandSender var1, String var2, BlockPos var3); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/ICommandSender.java b/src/game/java/net/minecraft/command/ICommandSender.java index bdfbd568..ea9222bb 100644 --- a/src/game/java/net/minecraft/command/ICommandSender.java +++ b/src/game/java/net/minecraft/command/ICommandSender.java @@ -6,80 +6,79 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ICommandSender { - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - String getName(); - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - IChatComponent getDisplayName(); - - /**+ - * Send a chat message to the CommandSender + /** + * + Send a chat message to the CommandSender */ void addChatMessage(IChatComponent var1); - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not + /** + * + Returns {@code true} if the CommandSender is allowed to execute the + * command, {@code false} if not */ boolean canCommandSenderUseCommand(int var1, String var2); - /**+ - * Get the position in the world. {@code null} is not - * allowed! If you are not an entity in the world, return - * the coordinates 0, 0, 0 - */ - BlockPos getPosition(); - - /**+ - * Get the position vector. {@code null} is not allowed! - * If you are not an entity in the world, return 0.0D, 0.0D, - * 0.0D - */ - Vec3 getPositionVector(); - - /**+ - * Get the world, if available. {@code null} is not - * allowed! If you are not an entity in the world, return - * the overworld - */ - World getEntityWorld(); - - /**+ - * Returns the entity associated with the command sender. MAY BE - * NULL! + /** + * + Returns the entity associated with the command sender. MAY BE NULL! */ Entity getCommandSenderEntity(); - /**+ - * Returns true if the command sender should be sent feedback - * about executed commands + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + IChatComponent getDisplayName(); + + /** + * + Get the world, if available. {@code null} is not allowed! If you are + * not an entity in the world, return the overworld + */ + World getEntityWorld(); + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + String getName(); + + /** + * + Get the position in the world. {@code null} is not allowed! If you + * are not an entity in the world, return the coordinates 0, 0, 0 + */ + BlockPos getPosition(); + + /** + * + Get the position vector. {@code null} is not allowed! If you are not + * an entity in the world, return 0.0D, 0.0D, 0.0D + */ + Vec3 getPositionVector(); + + /** + * + Returns true if the command sender should be sent feedback about executed + * commands */ boolean sendCommandFeedback(); diff --git a/src/game/java/net/minecraft/command/NumberInvalidException.java b/src/game/java/net/minecraft/command/NumberInvalidException.java index 946dfea9..585824c7 100644 --- a/src/game/java/net/minecraft/command/NumberInvalidException.java +++ b/src/game/java/net/minecraft/command/NumberInvalidException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/PlayerNotFoundException.java b/src/game/java/net/minecraft/command/PlayerNotFoundException.java index 44dd6f42..3122a831 100644 --- a/src/game/java/net/minecraft/command/PlayerNotFoundException.java +++ b/src/game/java/net/minecraft/command/PlayerNotFoundException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/PlayerSelector.java b/src/game/java/net/minecraft/command/PlayerSelector.java index 20347166..ced7b363 100644 --- a/src/game/java/net/minecraft/command/PlayerSelector.java +++ b/src/game/java/net/minecraft/command/PlayerSelector.java @@ -1,21 +1,23 @@ package net.minecraft.command; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Map.Entry; -import java.util.regex.Matcher; -import java.util.regex.Pattern; + import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLivingBase; @@ -36,354 +38,52 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlayerSelector { - /**+ - * This matches the at-tokens introduced for command blocks, - * including their arguments, if any. + /** + * + This matches the at-tokens introduced for command blocks, including their + * arguments, if any. */ private static final Pattern tokenPattern = Pattern.compile("^@([pare])(?:\\[([\\w=,!-]*)\\])?$"); - /**+ - * This matches things like "-1,,4", and is used for getting - * x,y,z,range from the token's argument list. + /** + * + This matches things like "-1,,4", and is used for getting x,y,z,range from + * the token's argument list. */ private static final Pattern intListPattern = Pattern.compile("\\G([-!]?[\\w-]*)(?:$|,)"); - /**+ - * This matches things like "rm=4,c=2" and is used for handling - * named token arguments. + /** + * + This matches things like "rm=4,c=2" and is used for handling named token + * arguments. */ private static final Pattern keyValueListPattern = Pattern.compile("\\G(\\w+)=([-!]?[\\w-]*)(?:$|,)"); - /**+ - * A set of arguments that will change the selector's world list - * to the sender's world instead of all the worlds when present + /** + * + A set of arguments that will change the selector's world list to the + * sender's world instead of all the worlds when present */ private static final Set WORLD_BINDING_ARGS = Sets .newHashSet(new String[] { "x", "y", "z", "dx", "dy", "dz", "rm", "r" }); - /**+ - * Returns the one player that matches the given at-token. - * Returns null if more than one player matches. - */ - public static EntityPlayerMP matchOnePlayer(ICommandSender sender, String token) { - return (EntityPlayerMP) matchOneEntity(sender, token, EntityPlayerMP.class); - } - - public static T matchOneEntity(ICommandSender sender, String token, - Class targetClass) { - List list = matchEntities(sender, token, targetClass); - return (T) (list.size() == 1 ? (Entity) list.get(0) : null); - } - - public static IChatComponent matchEntitiesToChatComponent(ICommandSender sender, String token) { - List list = matchEntities(sender, token, Entity.class); - if (list.isEmpty()) { - return null; - } else { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = list.size(); i < l; ++i) { - arraylist.add(list.get(i).getDisplayName()); - } - - return CommandBase.join(arraylist); - } - } - - public static List matchEntities(ICommandSender sender, String token, - Class targetClass) { - Matcher matcher = tokenPattern.matcher(token); - if (matcher.matches() && sender.canCommandSenderUseCommand(1, "@")) { - Map map = getArgumentMap(matcher.group(2)); - if (!isEntityTypeValid(sender, map)) { - return Collections.emptyList(); - } else { - String s = matcher.group(1); - BlockPos blockpos = func_179664_b(map, sender.getPosition()); - List list = getWorlds(sender, map); - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = list.size(); i < l; ++i) { - World world = list.get(i); - if (world != null) { - ArrayList arraylist1 = Lists.newArrayList(); - arraylist1.addAll(func_179663_a(map, s)); - arraylist1.addAll(func_179648_b(map)); - arraylist1.addAll(func_179649_c(map)); - arraylist1.addAll(func_179659_d(map)); - arraylist1.addAll(func_179657_e(map)); - arraylist1.addAll(func_179647_f(map)); - arraylist1.addAll(func_180698_a(map, blockpos)); - arraylist1.addAll(func_179662_g(map)); - arraylist.addAll(filterResults(map, targetClass, arraylist1, s, world, blockpos)); - } - } - - return func_179658_a(arraylist, map, sender, targetClass, s, blockpos); - } - } else { - return Collections.emptyList(); - } - } - - /**+ - * Returns the worlds to match the entities in for the specified - * command sender and token. This returns the sender's world if - * the selector specifies a location or all currently loaded - * worlds on the server if not. - */ - private static List getWorlds(ICommandSender sender, Map argumentMap) { - ArrayList arraylist = Lists.newArrayList(); - if (func_179665_h(argumentMap)) { - arraylist.add(sender.getEntityWorld()); - } else { - Collections.addAll(arraylist, MinecraftServer.getServer().worldServers); - } - - return arraylist; - } - - private static boolean isEntityTypeValid(ICommandSender commandSender, - Map params) { - String s = func_179651_b(params, "type"); - s = s != null && s.startsWith("!") ? s.substring(1) : s; - if (s != null && !EntityList.isStringValidEntityName(s)) { - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( - "commands.generic.entity.invalidType", new Object[] { s }); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); - commandSender.addChatMessage(chatcomponenttranslation); - return false; - } else { - return true; - } - } - - private static List> func_179663_a(Map parMap, String parString1) { - ArrayList arraylist = Lists.newArrayList(); - String s = func_179651_b(parMap, "type"); - final boolean flag = s != null && s.startsWith("!"); - if (flag) { - s = s.substring(1); - } - - boolean flag1 = !parString1.equals("e"); - boolean flag2 = parString1.equals("r") && s != null; - if ((s == null || !parString1.equals("e")) && !flag2) { - if (flag1) { - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - return entity instanceof EntityPlayer; - } - }); - } - } else { - final String ss = s; - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - return EntityList.isStringEntityName(entity, ss) != flag; - } - }); - } - - return arraylist; - } - - private static List> func_179648_b(Map parMap) { - ArrayList arraylist = Lists.newArrayList(); - final int i = parseIntWithDefault(parMap, "lm", -1); - final int j = parseIntWithDefault(parMap, "l", -1); - if (i > -1 || j > -1) { - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - if (!(entity instanceof EntityPlayerMP)) { - return false; - } else { - EntityPlayerMP entityplayermp = (EntityPlayerMP) entity; - return (i <= -1 || entityplayermp.experienceLevel >= i) - && (j <= -1 || entityplayermp.experienceLevel <= j); - } - } - }); - } - - return arraylist; - } - - private static List> func_179649_c(Map parMap) { - ArrayList arraylist = Lists.newArrayList(); - final int i = parseIntWithDefault(parMap, "m", WorldSettings.GameType.NOT_SET.getID()); - if (i != WorldSettings.GameType.NOT_SET.getID()) { - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - if (!(entity instanceof EntityPlayerMP)) { - return false; - } else { - EntityPlayerMP entityplayermp = (EntityPlayerMP) entity; - return entityplayermp.theItemInWorldManager.getGameType().getID() == i; - } - } - }); - } - - return arraylist; - } - - private static List> func_179659_d(Map parMap) { - ArrayList arraylist = Lists.newArrayList(); - String s = func_179651_b(parMap, "team"); - final boolean flag = s != null && s.startsWith("!"); - if (flag) { - s = s.substring(1); - } - - if (s != null) { - final String ss = s; - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - if (!(entity instanceof EntityLivingBase)) { - return false; - } else { - EntityLivingBase entitylivingbase = (EntityLivingBase) entity; - Team team = entitylivingbase.getTeam(); - String s1 = team == null ? "" : team.getRegisteredName(); - return s1.equals(ss) != flag; - } - } - }); - } - - return arraylist; - } - - private static List> func_179657_e(Map parMap) { - ArrayList arraylist = Lists.newArrayList(); - final Map map = func_96560_a(parMap); - if (map != null && map.size() > 0) { - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); - - for (Entry entry : (Set) map.entrySet()) { - String s = (String) entry.getKey(); - boolean flag = false; - if (s.endsWith("_min") && s.length() > 4) { - flag = true; - s = s.substring(0, s.length() - 4); - } - - ScoreObjective scoreobjective = scoreboard.getObjective(s); - if (scoreobjective == null) { - return false; - } - - String s1 = entity instanceof EntityPlayerMP ? entity.getName() - : entity.getUniqueID().toString(); - if (!scoreboard.entityHasObjective(s1, scoreobjective)) { - return false; - } - - Score score = scoreboard.getValueFromObjective(s1, scoreobjective); - int i = score.getScorePoints(); - if (i < ((Integer) entry.getValue()).intValue() && flag) { - return false; - } - - if (i > ((Integer) entry.getValue()).intValue() && !flag) { - return false; - } - } - - return true; - } - }); - } - - return arraylist; - } - - private static List> func_179647_f(Map parMap) { - ArrayList arraylist = Lists.newArrayList(); - String s = func_179651_b(parMap, "name"); - final boolean flag = s != null && s.startsWith("!"); - if (flag) { - s = s.substring(1); - } - - if (s != null) { - final String ss = s; - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - return entity.getName().equals(ss) != flag; - } - }); - } - - return arraylist; - } - - private static List> func_180698_a(Map parMap, final BlockPos parBlockPos) { - ArrayList arraylist = Lists.newArrayList(); - final int i = parseIntWithDefault(parMap, "rm", -1); - final int j = parseIntWithDefault(parMap, "r", -1); - if (parBlockPos != null && (i >= 0 || j >= 0)) { - final int k = i * i; - final int l = j * j; - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - int i1 = (int) entity.getDistanceSqToCenter(parBlockPos); - return (i < 0 || i1 >= k) && (j < 0 || i1 <= l); - } - }); - } - - return arraylist; - } - - private static List> func_179662_g(Map parMap) { - ArrayList arraylist = Lists.newArrayList(); - if (parMap.containsKey("rym") || parMap.containsKey("ry")) { - final int i = func_179650_a(parseIntWithDefault(parMap, "rym", 0)); - final int j = func_179650_a(parseIntWithDefault(parMap, "ry", 359)); - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - int i1 = PlayerSelector.func_179650_a((int) Math.floor((double) entity.rotationYaw)); - return i > j ? i1 >= i || i1 <= j : i1 >= i && i1 <= j; - } - }); - } - - if (parMap.containsKey("rxm") || parMap.containsKey("rx")) { - final int k = func_179650_a(parseIntWithDefault(parMap, "rxm", 0)); - final int l = func_179650_a(parseIntWithDefault(parMap, "rx", 359)); - arraylist.add(new Predicate() { - public boolean apply(Entity entity) { - int i1 = PlayerSelector.func_179650_a((int) Math.floor((double) entity.rotationPitch)); - return k > l ? i1 >= k || i1 <= l : i1 >= k && i1 <= l; - } - }); - } - - return arraylist; - } - private static List filterResults(Map params, Class entityClass, List> inputList, String type, World worldIn, BlockPos position) { ArrayList arraylist = Lists.newArrayList(); @@ -447,6 +147,129 @@ public class PlayerSelector { return arraylist; } + private static List> func_179647_f(Map parMap) { + ArrayList arraylist = Lists.newArrayList(); + String s = func_179651_b(parMap, "name"); + final boolean flag = s != null && s.startsWith("!"); + if (flag) { + s = s.substring(1); + } + + if (s != null) { + final String ss = s; + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + return entity.getName().equals(ss) != flag; + } + }); + } + + return arraylist; + } + + private static List> func_179648_b(Map parMap) { + ArrayList arraylist = Lists.newArrayList(); + final int i = parseIntWithDefault(parMap, "lm", -1); + final int j = parseIntWithDefault(parMap, "l", -1); + if (i > -1 || j > -1) { + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + if (!(entity instanceof EntityPlayerMP)) { + return false; + } else { + EntityPlayerMP entityplayermp = (EntityPlayerMP) entity; + return (i <= -1 || entityplayermp.experienceLevel >= i) + && (j <= -1 || entityplayermp.experienceLevel <= j); + } + } + }); + } + + return arraylist; + } + + private static List> func_179649_c(Map parMap) { + ArrayList arraylist = Lists.newArrayList(); + final int i = parseIntWithDefault(parMap, "m", WorldSettings.GameType.NOT_SET.getID()); + if (i != WorldSettings.GameType.NOT_SET.getID()) { + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + if (!(entity instanceof EntityPlayerMP)) { + return false; + } else { + EntityPlayerMP entityplayermp = (EntityPlayerMP) entity; + return entityplayermp.theItemInWorldManager.getGameType().getID() == i; + } + } + }); + } + + return arraylist; + } + + public static int func_179650_a(int parInt1) { + parInt1 = parInt1 % 360; + if (parInt1 >= 160) { + parInt1 -= 360; + } + + if (parInt1 < 0) { + parInt1 += 360; + } + + return parInt1; + } + + private static String func_179651_b(Map parMap, String parString1) { + return (String) parMap.get(parString1); + } + + private static List> func_179657_e(Map parMap) { + ArrayList arraylist = Lists.newArrayList(); + final Map map = func_96560_a(parMap); + if (map != null && map.size() > 0) { + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + Scoreboard scoreboard = MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); + + for (Entry entry : (Set) map.entrySet()) { + String s = (String) entry.getKey(); + boolean flag = false; + if (s.endsWith("_min") && s.length() > 4) { + flag = true; + s = s.substring(0, s.length() - 4); + } + + ScoreObjective scoreobjective = scoreboard.getObjective(s); + if (scoreobjective == null) { + return false; + } + + String s1 = entity instanceof EntityPlayerMP ? entity.getName() + : entity.getUniqueID().toString(); + if (!scoreboard.entityHasObjective(s1, scoreobjective)) { + return false; + } + + Score score = scoreboard.getValueFromObjective(s1, scoreobjective); + int i = score.getScorePoints(); + if (i < ((Integer) entry.getValue()).intValue() && flag) { + return false; + } + + if (i > ((Integer) entry.getValue()).intValue() && !flag) { + return false; + } + } + + return true; + } + }); + } + + return arraylist; + } + private static List func_179658_a(List parList, Map parMap, ICommandSender parICommandSender, Class parClass1, String parString1, final BlockPos parBlockPos) { @@ -481,6 +304,33 @@ public class PlayerSelector { return (List) parList; } + private static List> func_179659_d(Map parMap) { + ArrayList arraylist = Lists.newArrayList(); + String s = func_179651_b(parMap, "team"); + final boolean flag = s != null && s.startsWith("!"); + if (flag) { + s = s.substring(1); + } + + if (s != null) { + final String ss = s; + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + if (!(entity instanceof EntityLivingBase)) { + return false; + } else { + EntityLivingBase entitylivingbase = (EntityLivingBase) entity; + Team team = entitylivingbase.getTeam(); + String s1 = team == null ? "" : team.getRegisteredName(); + return s1.equals(ss) != flag; + } + } + }); + } + + return arraylist; + } + private static AxisAlignedBB func_179661_a(BlockPos parBlockPos, int parInt1, int parInt2, int parInt3) { boolean flag = parInt1 < 0; boolean flag1 = parInt2 < 0; @@ -494,17 +344,61 @@ public class PlayerSelector { return new AxisAlignedBB((double) i, (double) j, (double) k, (double) l, (double) i1, (double) j1); } - public static int func_179650_a(int parInt1) { - parInt1 = parInt1 % 360; - if (parInt1 >= 160) { - parInt1 -= 360; + private static List> func_179662_g(Map parMap) { + ArrayList arraylist = Lists.newArrayList(); + if (parMap.containsKey("rym") || parMap.containsKey("ry")) { + final int i = func_179650_a(parseIntWithDefault(parMap, "rym", 0)); + final int j = func_179650_a(parseIntWithDefault(parMap, "ry", 359)); + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + int i1 = PlayerSelector.func_179650_a((int) Math.floor((double) entity.rotationYaw)); + return i > j ? i1 >= i || i1 <= j : i1 >= i && i1 <= j; + } + }); } - if (parInt1 < 0) { - parInt1 += 360; + if (parMap.containsKey("rxm") || parMap.containsKey("rx")) { + final int k = func_179650_a(parseIntWithDefault(parMap, "rxm", 0)); + final int l = func_179650_a(parseIntWithDefault(parMap, "rx", 359)); + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + int i1 = PlayerSelector.func_179650_a((int) Math.floor((double) entity.rotationPitch)); + return k > l ? i1 >= k || i1 <= l : i1 >= k && i1 <= l; + } + }); } - return parInt1; + return arraylist; + } + + private static List> func_179663_a(Map parMap, String parString1) { + ArrayList arraylist = Lists.newArrayList(); + String s = func_179651_b(parMap, "type"); + final boolean flag = s != null && s.startsWith("!"); + if (flag) { + s = s.substring(1); + } + + boolean flag1 = !parString1.equals("e"); + boolean flag2 = parString1.equals("r") && s != null; + if ((s == null || !parString1.equals("e")) && !flag2) { + if (flag1) { + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + return entity instanceof EntityPlayer; + } + }); + } + } else { + final String ss = s; + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + return EntityList.isStringEntityName(entity, ss) != flag; + } + }); + } + + return arraylist; } private static BlockPos func_179664_b(Map parMap, BlockPos parBlockPos) { @@ -523,13 +417,22 @@ public class PlayerSelector { return false; } - private static int parseIntWithDefault(Map parMap, String parString1, int parInt1) { - return parMap.containsKey(parString1) ? MathHelper.parseIntWithDefault((String) parMap.get(parString1), parInt1) - : parInt1; - } + private static List> func_180698_a(Map parMap, final BlockPos parBlockPos) { + ArrayList arraylist = Lists.newArrayList(); + final int i = parseIntWithDefault(parMap, "rm", -1); + final int j = parseIntWithDefault(parMap, "r", -1); + if (parBlockPos != null && (i >= 0 || j >= 0)) { + final int k = i * i; + final int l = j * j; + arraylist.add(new Predicate() { + public boolean apply(Entity entity) { + int i1 = (int) entity.getDistanceSqToCenter(parBlockPos); + return (i < 0 || i1 >= k) && (j < 0 || i1 <= l); + } + }); + } - private static String func_179651_b(Map parMap, String parString1) { - return (String) parMap.get(parString1); + return arraylist; } public static Map func_96560_a(Map parMap) { @@ -545,29 +448,6 @@ public class PlayerSelector { return hashmap; } - /**+ - * Returns whether the given pattern can match more than one - * player. - */ - public static boolean matchesMultiplePlayers(String parString1) { - Matcher matcher = tokenPattern.matcher(parString1); - if (!matcher.matches()) { - return false; - } else { - Map map = getArgumentMap(matcher.group(2)); - String s = matcher.group(1); - int i = !"a".equals(s) && !"e".equals(s) ? 1 : 0; - return parseIntWithDefault(map, "c", i) != 1; - } - } - - /**+ - * Returns whether the given token has any arguments set. - */ - public static boolean hasArguments(String parString1) { - return tokenPattern.matcher(parString1).matches(); - } - private static Map getArgumentMap(String argumentString) { HashMap hashmap = Maps.newHashMap(); if (argumentString == null) { @@ -608,4 +488,127 @@ public class PlayerSelector { return hashmap; } } + + /** + * + Returns the worlds to match the entities in for the specified command + * sender and token. This returns the sender's world if the selector specifies a + * location or all currently loaded worlds on the server if not. + */ + private static List getWorlds(ICommandSender sender, Map argumentMap) { + ArrayList arraylist = Lists.newArrayList(); + if (func_179665_h(argumentMap)) { + arraylist.add(sender.getEntityWorld()); + } else { + Collections.addAll(arraylist, MinecraftServer.getServer().worldServers); + } + + return arraylist; + } + + /** + * + Returns whether the given token has any arguments set. + */ + public static boolean hasArguments(String parString1) { + return tokenPattern.matcher(parString1).matches(); + } + + private static boolean isEntityTypeValid(ICommandSender commandSender, + Map params) { + String s = func_179651_b(params, "type"); + s = s != null && s.startsWith("!") ? s.substring(1) : s; + if (s != null && !EntityList.isStringValidEntityName(s)) { + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + "commands.generic.entity.invalidType", new Object[] { s }); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); + commandSender.addChatMessage(chatcomponenttranslation); + return false; + } else { + return true; + } + } + + public static List matchEntities(ICommandSender sender, String token, + Class targetClass) { + Matcher matcher = tokenPattern.matcher(token); + if (matcher.matches() && sender.canCommandSenderUseCommand(1, "@")) { + Map map = getArgumentMap(matcher.group(2)); + if (!isEntityTypeValid(sender, map)) { + return Collections.emptyList(); + } else { + String s = matcher.group(1); + BlockPos blockpos = func_179664_b(map, sender.getPosition()); + List list = getWorlds(sender, map); + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = list.size(); i < l; ++i) { + World world = list.get(i); + if (world != null) { + ArrayList arraylist1 = Lists.newArrayList(); + arraylist1.addAll(func_179663_a(map, s)); + arraylist1.addAll(func_179648_b(map)); + arraylist1.addAll(func_179649_c(map)); + arraylist1.addAll(func_179659_d(map)); + arraylist1.addAll(func_179657_e(map)); + arraylist1.addAll(func_179647_f(map)); + arraylist1.addAll(func_180698_a(map, blockpos)); + arraylist1.addAll(func_179662_g(map)); + arraylist.addAll(filterResults(map, targetClass, arraylist1, s, world, blockpos)); + } + } + + return func_179658_a(arraylist, map, sender, targetClass, s, blockpos); + } + } else { + return Collections.emptyList(); + } + } + + public static IChatComponent matchEntitiesToChatComponent(ICommandSender sender, String token) { + List list = matchEntities(sender, token, Entity.class); + if (list.isEmpty()) { + return null; + } else { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = list.size(); i < l; ++i) { + arraylist.add(list.get(i).getDisplayName()); + } + + return CommandBase.join(arraylist); + } + } + + /** + * + Returns whether the given pattern can match more than one player. + */ + public static boolean matchesMultiplePlayers(String parString1) { + Matcher matcher = tokenPattern.matcher(parString1); + if (!matcher.matches()) { + return false; + } else { + Map map = getArgumentMap(matcher.group(2)); + String s = matcher.group(1); + int i = !"a".equals(s) && !"e".equals(s) ? 1 : 0; + return parseIntWithDefault(map, "c", i) != 1; + } + } + + public static T matchOneEntity(ICommandSender sender, String token, + Class targetClass) { + List list = matchEntities(sender, token, targetClass); + return (T) (list.size() == 1 ? (Entity) list.get(0) : null); + } + + /** + * + Returns the one player that matches the given at-token. Returns null if + * more than one player matches. + */ + public static EntityPlayerMP matchOnePlayer(ICommandSender sender, String token) { + return (EntityPlayerMP) matchOneEntity(sender, token, EntityPlayerMP.class); + } + + private static int parseIntWithDefault(Map parMap, String parString1, int parInt1) { + return parMap.containsKey(parString1) ? MathHelper.parseIntWithDefault((String) parMap.get(parString1), parInt1) + : parInt1; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/ServerCommandManager.java b/src/game/java/net/minecraft/command/ServerCommandManager.java index bb3dbe3c..9023a958 100644 --- a/src/game/java/net/minecraft/command/ServerCommandManager.java +++ b/src/game/java/net/minecraft/command/ServerCommandManager.java @@ -1,5 +1,8 @@ package net.minecraft.command; +import java.util.List; + +import net.lax1dude.eaglercraft.v1_8.sp.server.ClientCommandDummy; import net.minecraft.command.server.CommandAchievement; import net.minecraft.command.server.CommandBlockLogic; import net.minecraft.command.server.CommandBroadcast; @@ -19,26 +22,25 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; -import java.util.List; - -import net.lax1dude.eaglercraft.v1_8.sp.server.ClientCommandDummy; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -92,11 +94,15 @@ public class ServerCommandManager extends CommandHandler implements IAdminComman this.registerCommand(new CommandListPlayers()); this.registerCommand(new CommandSetPlayerTimeout()); this.registerCommand(new ClientCommandDummy("eagskull", 2, "command.skull.usage")); + this.registerCommand(new CommandGm(0)); + this.registerCommand(new CommandGm(1)); + this.registerCommand(new CommandGm(2)); + this.registerCommand(new CommandGm(3)); CommandBase.setAdminCommander(this); } - /**+ - * Send an informative message to the server operators + /** + * + Send an informative message to the server operators */ public void notifyOperators(ICommandSender sender, ICommand command, int flags, String msgFormat, Object... msgParams) { diff --git a/src/game/java/net/minecraft/command/SyntaxErrorException.java b/src/game/java/net/minecraft/command/SyntaxErrorException.java index cb726523..2cf91d18 100644 --- a/src/game/java/net/minecraft/command/SyntaxErrorException.java +++ b/src/game/java/net/minecraft/command/SyntaxErrorException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/WrongUsageException.java b/src/game/java/net/minecraft/command/WrongUsageException.java index 0db9162a..05532371 100644 --- a/src/game/java/net/minecraft/command/WrongUsageException.java +++ b/src/game/java/net/minecraft/command/WrongUsageException.java @@ -1,21 +1,24 @@ package net.minecraft.command; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/command/server/CommandAchievement.java b/src/game/java/net/minecraft/command/server/CommandAchievement.java index 7275259c..545a8963 100644 --- a/src/game/java/net/minecraft/command/server/CommandAchievement.java +++ b/src/game/java/net/minecraft/command/server/CommandAchievement.java @@ -1,10 +1,12 @@ package net.minecraft.command.server; +import java.util.ArrayList; +import java.util.List; + import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -import java.util.ArrayList; -import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -17,51 +19,83 @@ import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandAchievement extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + if (astring.length == 1) { + return getListOfStringsMatchingLastWord(astring, new String[] { "give", "take" }); + } else if (astring.length != 2) { + return astring.length == 3 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : null; + } else { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = StatList.allStats.size(); i < l; ++i) { + arraylist.add(StatList.allStats.get(i).statId); + } + + return getListOfStringsMatchingLastWord(astring, arraylist); + } + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "achievement"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.achievement.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -170,33 +204,4 @@ public class CommandAchievement extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - if (astring.length == 1) { - return getListOfStringsMatchingLastWord(astring, new String[] { "give", "take" }); - } else if (astring.length != 2) { - return astring.length == 3 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : null; - } else { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = StatList.allStats.size(); i < l; ++i) { - arraylist.add(StatList.allStats.get(i).statId); - } - - return getListOfStringsMatchingLastWord(astring, arraylist); - } - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 2; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandBlockLogic.java b/src/game/java/net/minecraft/command/server/CommandBlockLogic.java index f4ed8d42..5fa69114 100644 --- a/src/game/java/net/minecraft/command/server/CommandBlockLogic.java +++ b/src/game/java/net/minecraft/command/server/CommandBlockLogic.java @@ -1,10 +1,10 @@ package net.minecraft.command.server; -import net.lax1dude.eaglercraft.v1_8.netty.ByteBuf; - import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Callable; + +import net.lax1dude.eaglercraft.v1_8.netty.ByteBuf; import net.minecraft.command.CommandResultStats; import net.minecraft.command.ICommandManager; import net.minecraft.command.ICommandSender; @@ -18,78 +18,117 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.ReportedException; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class CommandBlockLogic implements ICommandSender { - /**+ - * The formatting for the timestamp on commands run. + /** + * + The formatting for the timestamp on commands run. */ private static final SimpleDateFormat timestampFormat = new SimpleDateFormat("HH:mm:ss"); private int successCount; private boolean trackOutput = true; - /**+ - * The previously run command. + /** + * + The previously run command. */ private IChatComponent lastOutput = null; - /**+ - * The command stored in the command block. + /** + * + The command stored in the command block. */ private String commandStored = ""; - /**+ - * The custom name of the command block. (defaults to "@") + /** + * + The custom name of the command block. (defaults to "@") */ private String customName = "@"; private final CommandResultStats resultStats = new CommandResultStats(); - /**+ - * returns the successCount int. + /** + * + Send a chat message to the CommandSender */ - public int getSuccessCount() { - return this.successCount; + public void addChatMessage(IChatComponent ichatcomponent) { + if (this.trackOutput && this.getEntityWorld() != null && !this.getEntityWorld().isRemote) { + this.lastOutput = (new ChatComponentText("[" + timestampFormat.format(new Date()) + "] ")) + .appendSibling(ichatcomponent); + this.updateCommand(); + } + } - /**+ - * Returns the lastOutput. + /** + * + Returns {@code true} if the CommandSender is allowed to execute the + * command, {@code false} if not + */ + public boolean canCommandSenderUseCommand(int i, String var2) { + return i <= 2; + } + + public abstract int func_145751_f(); + + public abstract void func_145757_a(ByteBuf var1); + + /** + * + Returns the command of the command block. + */ + public String getCommand() { + return this.commandStored; + } + + public CommandResultStats getCommandResultStats() { + return this.resultStats; + } + + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return new ChatComponentText(this.getName()); + } + + /** + * + Returns the lastOutput. */ public IChatComponent getLastOutput() { return this.lastOutput; } - /**+ - * Stores data to NBT format. + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ - public void writeDataToNBT(NBTTagCompound tagCompound) { - tagCompound.setString("Command", this.commandStored); - tagCompound.setInteger("SuccessCount", this.successCount); - tagCompound.setString("CustomName", this.customName); - tagCompound.setBoolean("TrackOutput", this.trackOutput); - if (this.lastOutput != null && this.trackOutput) { - tagCompound.setString("LastOutput", IChatComponent.Serializer.componentToJson(this.lastOutput)); - } - - this.resultStats.writeStatsToNBT(tagCompound); + public String getName() { + return this.customName; } - /**+ - * Reads NBT formatting and stored data into variables. + /** + * + returns the successCount int. + */ + public int getSuccessCount() { + return this.successCount; + } + + /** + * + Reads NBT formatting and stored data into variables. */ public void readDataFromNBT(NBTTagCompound nbt) { this.commandStored = nbt.getString("Command"); @@ -109,27 +148,42 @@ public abstract class CommandBlockLogic implements ICommandSender { this.resultStats.readStatsFromNBT(nbt); } - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not + /** + * + Returns true if the command sender should be sent feedback about executed + * commands */ - public boolean canCommandSenderUseCommand(int i, String var2) { - return i <= 2; + public boolean sendCommandFeedback() { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + return minecraftserver == null + || minecraftserver.worldServers[0].getGameRules().getBoolean("commandBlockOutput"); } - /**+ - * Sets the command. + /** + * + Sets the command. */ public void setCommand(String command) { this.commandStored = command; this.successCount = 0; } - /**+ - * Returns the command of the command block. - */ - public String getCommand() { - return this.commandStored; + public void setCommandStat(CommandResultStats.Type commandresultstats$type, int i) { + this.resultStats.func_179672_a(this, commandresultstats$type, i); + } + + public void setLastOutput(IChatComponent lastOutputMessage) { + this.lastOutput = lastOutputMessage; + } + + public void setName(String parString1) { + this.customName = parString1; + } + + public void setTrackOutput(boolean shouldTrackOutput) { + this.trackOutput = shouldTrackOutput; + } + + public boolean shouldTrackOutput() { + return this.trackOutput; } public void trigger(World worldIn) { @@ -165,70 +219,6 @@ public abstract class CommandBlockLogic implements ICommandSender { } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.customName; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return new ChatComponentText(this.getName()); - } - - public void setName(String parString1) { - this.customName = parString1; - } - - /**+ - * Send a chat message to the CommandSender - */ - public void addChatMessage(IChatComponent ichatcomponent) { - if (this.trackOutput && this.getEntityWorld() != null && !this.getEntityWorld().isRemote) { - this.lastOutput = (new ChatComponentText("[" + timestampFormat.format(new Date()) + "] ")) - .appendSibling(ichatcomponent); - this.updateCommand(); - } - - } - - /**+ - * Returns true if the command sender should be sent feedback - * about executed commands - */ - public boolean sendCommandFeedback() { - MinecraftServer minecraftserver = MinecraftServer.getServer(); - return minecraftserver == null - || minecraftserver.worldServers[0].getGameRules().getBoolean("commandBlockOutput"); - } - - public void setCommandStat(CommandResultStats.Type commandresultstats$type, int i) { - this.resultStats.func_179672_a(this, commandresultstats$type, i); - } - - public abstract void updateCommand(); - - public abstract int func_145751_f(); - - public abstract void func_145757_a(ByteBuf var1); - - public void setLastOutput(IChatComponent lastOutputMessage) { - this.lastOutput = lastOutputMessage; - } - - public void setTrackOutput(boolean shouldTrackOutput) { - this.trackOutput = shouldTrackOutput; - } - - public boolean shouldTrackOutput() { - return this.trackOutput; - } - public boolean tryOpenEditCommandBlock(EntityPlayer playerIn) { if (!playerIn.capabilities.isCreativeMode) { return false; @@ -241,7 +231,20 @@ public abstract class CommandBlockLogic implements ICommandSender { } } - public CommandResultStats getCommandResultStats() { - return this.resultStats; + public abstract void updateCommand(); + + /** + * + Stores data to NBT format. + */ + public void writeDataToNBT(NBTTagCompound tagCompound) { + tagCompound.setString("Command", this.commandStored); + tagCompound.setInteger("SuccessCount", this.successCount); + tagCompound.setString("CustomName", this.customName); + tagCompound.setBoolean("TrackOutput", this.trackOutput); + if (this.lastOutput != null && this.trackOutput) { + tagCompound.setString("LastOutput", IChatComponent.Serializer.componentToJson(this.lastOutput)); + } + + this.resultStats.writeStatsToNBT(tagCompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandBroadcast.java b/src/game/java/net/minecraft/command/server/CommandBroadcast.java index 8cde89c1..bf0a3a86 100644 --- a/src/game/java/net/minecraft/command/server/CommandBroadcast.java +++ b/src/game/java/net/minecraft/command/server/CommandBroadcast.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -12,51 +13,63 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandBroadcast extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length >= 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "say"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 1; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.say.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 1; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length > 0 && parArrayOfString[0].length() > 0) { @@ -72,13 +85,4 @@ public class CommandBroadcast extends CommandBase { throw new WrongUsageException("commands.say.usage", new Object[0]); } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length >= 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandEmote.java b/src/game/java/net/minecraft/command/server/CommandEmote.java index 2e19e006..07ec4505 100644 --- a/src/game/java/net/minecraft/command/server/CommandEmote.java +++ b/src/game/java/net/minecraft/command/server/CommandEmote.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -13,51 +14,61 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandEmote extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { + return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "me"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 0; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender sender) { return "commands.me.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender sender, String[] args) throws CommandException { if (args.length <= 0) { @@ -74,11 +85,4 @@ public class CommandEmote extends CommandBase { "chat.type.emote", new Object[] { sender.getDisplayName(), ichatcomponent })); } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender sender, String[] args, BlockPos pos) { - return getListOfStringsMatchingLastWord(args, MinecraftServer.getServer().getAllUsernames()); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandListPlayers.java b/src/game/java/net/minecraft/command/server/CommandListPlayers.java index ff33d10f..70384234 100644 --- a/src/game/java/net/minecraft/command/server/CommandListPlayers.java +++ b/src/game/java/net/minecraft/command/server/CommandListPlayers.java @@ -8,51 +8,54 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandListPlayers extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "list"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 0; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.players.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { int i = MinecraftServer.getServer().getCurrentPlayerCount(); diff --git a/src/game/java/net/minecraft/command/server/CommandMessage.java b/src/game/java/net/minecraft/command/server/CommandMessage.java index 5f4993af..ea9f1f49 100644 --- a/src/game/java/net/minecraft/command/server/CommandMessage.java +++ b/src/game/java/net/minecraft/command/server/CommandMessage.java @@ -2,6 +2,7 @@ package net.minecraft.command.server; import java.util.Arrays; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -17,58 +18,76 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandMessage extends CommandBase { - /**+ - * Gets a list of aliases for this command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); + } + + /** + * + Gets a list of aliases for this command */ public List getCommandAliases() { return Arrays.asList(new String[] { "w", "msg" }); } - /**+ - * Gets the name of the command + /** + * + Gets the name of the command */ public String getCommandName() { return "tell"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 0; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.message.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 0; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -100,19 +119,4 @@ public class CommandMessage extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandMessageRaw.java b/src/game/java/net/minecraft/command/server/CommandMessageRaw.java index 4762f0dd..a96d41e2 100644 --- a/src/game/java/net/minecraft/command/server/CommandMessageRaw.java +++ b/src/game/java/net/minecraft/command/server/CommandMessageRaw.java @@ -16,51 +16,71 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ChatComponentProcessor; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandMessageRaw extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "tellraw"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.tellraw.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 2) { @@ -80,21 +100,4 @@ public class CommandMessageRaw extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : null; - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandScoreboard.java b/src/game/java/net/minecraft/command/server/CommandScoreboard.java index 76bcf473..12df9965 100644 --- a/src/game/java/net/minecraft/command/server/CommandScoreboard.java +++ b/src/game/java/net/minecraft/command/server/CommandScoreboard.java @@ -1,7 +1,5 @@ package net.minecraft.command.server; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -9,6 +7,10 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.CommandResultStats; @@ -33,51 +35,707 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandScoreboard extends CommandBase { - /**+ - * Gets the name of the command + protected void addObjective(ICommandSender sender, String[] args, int index) throws CommandException { + String s = args[index++]; + String s1 = args[index++]; + Scoreboard scoreboard = this.getScoreboard(); + IScoreObjectiveCriteria iscoreobjectivecriteria = (IScoreObjectiveCriteria) IScoreObjectiveCriteria.INSTANCES + .get(s1); + if (iscoreobjectivecriteria == null) { + throw new WrongUsageException("commands.scoreboard.objectives.add.wrongType", new Object[] { s1 }); + } else if (scoreboard.getObjective(s) != null) { + throw new CommandException("commands.scoreboard.objectives.add.alreadyExists", new Object[] { s }); + } else if (s.length() > 16) { + throw new SyntaxErrorException("commands.scoreboard.objectives.add.tooLong", + new Object[] { s, Integer.valueOf(16) }); + } else if (s.length() == 0) { + throw new WrongUsageException("commands.scoreboard.objectives.add.usage", new Object[0]); + } else { + if (args.length > index) { + String s2 = getChatComponentFromNthArg(sender, args, index).getUnformattedText(); + if (s2.length() > 32) { + throw new SyntaxErrorException("commands.scoreboard.objectives.add.displayTooLong", + new Object[] { s2, Integer.valueOf(32) }); + } + + if (s2.length() > 0) { + scoreboard.addScoreObjective(s, iscoreobjectivecriteria).setDisplayName(s2); + } else { + scoreboard.addScoreObjective(s, iscoreobjectivecriteria); + } + } else { + scoreboard.addScoreObjective(s, iscoreobjectivecriteria); + } + + notifyOperators(sender, this, "commands.scoreboard.objectives.add.success", new Object[] { s }); + } + } + + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + if (astring.length == 1) { + return getListOfStringsMatchingLastWord(astring, new String[] { "objectives", "players", "teams" }); + } else { + if (astring[0].equalsIgnoreCase("objectives")) { + if (astring.length == 2) { + return getListOfStringsMatchingLastWord(astring, + new String[] { "list", "add", "remove", "setdisplay" }); + } + + if (astring[1].equalsIgnoreCase("add")) { + if (astring.length == 4) { + Set set = IScoreObjectiveCriteria.INSTANCES.keySet(); + return getListOfStringsMatchingLastWord(astring, set); + } + } else if (astring[1].equalsIgnoreCase("remove")) { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); + } + } else if (astring[1].equalsIgnoreCase("setdisplay")) { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, Scoreboard.getDisplaySlotStrings()); + } + + if (astring.length == 4) { + return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); + } + } + } else if (astring[0].equalsIgnoreCase("players")) { + if (astring.length == 2) { + return getListOfStringsMatchingLastWord(astring, + new String[] { "set", "add", "remove", "reset", "list", "enable", "test", "operation" }); + } + + if (!astring[1].equalsIgnoreCase("set") && !astring[1].equalsIgnoreCase("add") + && !astring[1].equalsIgnoreCase("remove") && !astring[1].equalsIgnoreCase("reset")) { + if (astring[1].equalsIgnoreCase("enable")) { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, + MinecraftServer.getServer().getAllUsernames()); + } + + if (astring.length == 4) { + return getListOfStringsMatchingLastWord(astring, this.func_175782_e()); + } + } else if (!astring[1].equalsIgnoreCase("list") && !astring[1].equalsIgnoreCase("test")) { + if (astring[1].equalsIgnoreCase("operation")) { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, + this.getScoreboard().getObjectiveNames()); + } + + if (astring.length == 4) { + return getListOfStringsMatchingLastWord(astring, this.func_147184_a(true)); + } + + if (astring.length == 5) { + return getListOfStringsMatchingLastWord(astring, + new String[] { "+=", "-=", "*=", "/=", "%=", "=", "<", ">", "><" }); + } + + if (astring.length == 6) { + return getListOfStringsMatchingLastWord(astring, + MinecraftServer.getServer().getAllUsernames()); + } + + if (astring.length == 7) { + return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); + } + } + } else { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getObjectiveNames()); + } + + if (astring.length == 4 && astring[1].equalsIgnoreCase("test")) { + return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); + } + } + } else { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); + } + + if (astring.length == 4) { + return getListOfStringsMatchingLastWord(astring, this.func_147184_a(true)); + } + } + } else if (astring[0].equalsIgnoreCase("teams")) { + if (astring.length == 2) { + return getListOfStringsMatchingLastWord(astring, + new String[] { "add", "remove", "join", "leave", "empty", "list", "option" }); + } + + if (astring[1].equalsIgnoreCase("join")) { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getTeamNames()); + } + + if (astring.length >= 4) { + return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); + } + } else { + if (astring[1].equalsIgnoreCase("leave")) { + return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); + } + + if (!astring[1].equalsIgnoreCase("empty") && !astring[1].equalsIgnoreCase("list") + && !astring[1].equalsIgnoreCase("remove")) { + if (astring[1].equalsIgnoreCase("option")) { + if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getTeamNames()); + } + + if (astring.length == 4) { + return getListOfStringsMatchingLastWord(astring, new String[] { "color", "friendlyfire", + "seeFriendlyInvisibles", "nametagVisibility", "deathMessageVisibility" }); + } + + if (astring.length == 5) { + if (astring[3].equalsIgnoreCase("color")) { + return getListOfStringsMatchingLastWord(astring, + EnumChatFormatting.getValidValues(true, false)); + } + + if (astring[3].equalsIgnoreCase("nametagVisibility") + || astring[3].equalsIgnoreCase("deathMessageVisibility")) { + return getListOfStringsMatchingLastWord(astring, Team.EnumVisible.func_178825_a()); + } + + if (astring[3].equalsIgnoreCase("friendlyfire") + || astring[3].equalsIgnoreCase("seeFriendlyInvisibles")) { + return getListOfStringsMatchingLastWord(astring, new String[] { "true", "false" }); + } + } + } + } else if (astring.length == 3) { + return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getTeamNames()); + } + } + } + + return null; + } + } + + protected void addTeam(ICommandSender sender, String[] args, int index) throws CommandException { + String s = args[index++]; + Scoreboard scoreboard = this.getScoreboard(); + if (scoreboard.getTeam(s) != null) { + throw new CommandException("commands.scoreboard.teams.add.alreadyExists", new Object[] { s }); + } else if (s.length() > 16) { + throw new SyntaxErrorException("commands.scoreboard.teams.add.tooLong", + new Object[] { s, Integer.valueOf(16) }); + } else if (s.length() == 0) { + throw new WrongUsageException("commands.scoreboard.teams.add.usage", new Object[0]); + } else { + if (args.length > index) { + String s1 = getChatComponentFromNthArg(sender, args, index).getUnformattedText(); + if (s1.length() > 32) { + throw new SyntaxErrorException("commands.scoreboard.teams.add.displayTooLong", + new Object[] { s1, Integer.valueOf(32) }); + } + + if (s1.length() > 0) { + scoreboard.createTeam(s).setTeamName(s1); + } else { + scoreboard.createTeam(s); + } + } else { + scoreboard.createTeam(s); + } + + notifyOperators(sender, this, "commands.scoreboard.teams.add.success", new Object[] { s }); + } + } + + protected void emptyTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + ScorePlayerTeam scoreplayerteam = this.getTeam(parArrayOfString[parInt1]); + if (scoreplayerteam != null) { + ArrayList arraylist = Lists.newArrayList(scoreplayerteam.getMembershipCollection()); + parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, arraylist.size()); + if (arraylist.isEmpty()) { + throw new CommandException("commands.scoreboard.teams.empty.alreadyEmpty", + new Object[] { scoreplayerteam.getRegisteredName() }); + } else { + for (int i = 0, l = arraylist.size(); i < l; ++i) { + scoreboard.removePlayerFromTeam(arraylist.get(i), scoreplayerteam); + } + + notifyOperators(parICommandSender, this, "commands.scoreboard.teams.empty.success", + new Object[] { Integer.valueOf(arraylist.size()), scoreplayerteam.getRegisteredName() }); + } + } + } + + protected List func_147184_a(boolean parFlag) { + Collection collection = this.getScoreboard().getScoreObjectives(); + ArrayList arraylist = Lists.newArrayList(); + + for (ScoreObjective scoreobjective : (Collection) collection) { + if (!parFlag || !scoreobjective.getCriteria().isReadOnly()) { + arraylist.add(scoreobjective.getName()); + } + } + + return arraylist; + } + + protected void func_175778_p(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + String s = getEntityName(parICommandSender, parArrayOfString[parInt1++]); + ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], true); + String s1 = parArrayOfString[parInt1++]; + String s2 = getEntityName(parICommandSender, parArrayOfString[parInt1++]); + ScoreObjective scoreobjective1 = this.getObjective(parArrayOfString[parInt1], false); + if (s.length() > 40) { + throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", + new Object[] { s, Integer.valueOf(40) }); + } else if (s2.length() > 40) { + throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", + new Object[] { s2, Integer.valueOf(40) }); + } else { + Score score = scoreboard.getValueFromObjective(s, scoreobjective); + if (!scoreboard.entityHasObjective(s2, scoreobjective1)) { + throw new CommandException("commands.scoreboard.players.operation.notFound", + new Object[] { scoreobjective1.getName(), s2 }); + } else { + Score score1 = scoreboard.getValueFromObjective(s2, scoreobjective1); + if (s1.equals("+=")) { + score.setScorePoints(score.getScorePoints() + score1.getScorePoints()); + } else if (s1.equals("-=")) { + score.setScorePoints(score.getScorePoints() - score1.getScorePoints()); + } else if (s1.equals("*=")) { + score.setScorePoints(score.getScorePoints() * score1.getScorePoints()); + } else if (s1.equals("/=")) { + if (score1.getScorePoints() != 0) { + score.setScorePoints(score.getScorePoints() / score1.getScorePoints()); + } + } else if (s1.equals("%=")) { + if (score1.getScorePoints() != 0) { + score.setScorePoints(score.getScorePoints() % score1.getScorePoints()); + } + } else if (s1.equals("=")) { + score.setScorePoints(score1.getScorePoints()); + } else if (s1.equals("<")) { + score.setScorePoints(Math.min(score.getScorePoints(), score1.getScorePoints())); + } else if (s1.equals(">")) { + score.setScorePoints(Math.max(score.getScorePoints(), score1.getScorePoints())); + } else { + if (!s1.equals("><")) { + throw new CommandException("commands.scoreboard.players.operation.invalidOperation", + new Object[] { s1 }); + } + + int i = score.getScorePoints(); + score.setScorePoints(score1.getScorePoints()); + score1.setScorePoints(i); + } + + notifyOperators(parICommandSender, this, "commands.scoreboard.players.operation.success", + new Object[0]); + } + } + } + + protected void func_175779_n(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + String s = getPlayerName(parICommandSender, parArrayOfString[parInt1++]); + if (s.length() > 40) { + throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", + new Object[] { s, Integer.valueOf(40) }); + } else { + ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1], false); + if (scoreobjective.getCriteria() != IScoreObjectiveCriteria.TRIGGER) { + throw new CommandException("commands.scoreboard.players.enable.noTrigger", + new Object[] { scoreobjective.getName() }); + } else { + Score score = scoreboard.getValueFromObjective(s, scoreobjective); + score.setLocked(false); + notifyOperators(parICommandSender, this, "commands.scoreboard.players.enable.success", + new Object[] { scoreobjective.getName(), s }); + } + } + } + + private boolean func_175780_b(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { + int i = -1; + + for (int j = 0; j < parArrayOfString.length; ++j) { + if (this.isUsernameIndex(parArrayOfString, j) && "*".equals(parArrayOfString[j])) { + if (i >= 0) { + throw new CommandException("commands.scoreboard.noMultiWildcard", new Object[0]); + } + + i = j; + } + } + + if (i < 0) { + return false; + } else { + ArrayList arraylist1 = Lists.newArrayList(this.getScoreboard().getObjectiveNames()); + String s = parArrayOfString[i]; + ArrayList arraylist = Lists.newArrayList(); + + for (int j = 0, l = arraylist1.size(); j < l; ++j) { + String s1 = (String) arraylist1.get(j); + parArrayOfString[i] = s1; + + try { + this.processCommand(parICommandSender, parArrayOfString); + arraylist.add(s1); + } catch (CommandException commandexception) { + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + commandexception.getMessage(), commandexception.getErrorObjects()); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); + parICommandSender.addChatMessage(chatcomponenttranslation); + } + } + + parArrayOfString[i] = s; + parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, arraylist.size()); + if (arraylist.size() == 0) { + throw new WrongUsageException("commands.scoreboard.allMatchesFailed", new Object[0]); + } else { + return true; + } + } + } + + protected void func_175781_o(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + String s = getEntityName(parICommandSender, parArrayOfString[parInt1++]); + if (s.length() > 40) { + throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", + new Object[] { s, Integer.valueOf(40) }); + } else { + ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], false); + if (!scoreboard.entityHasObjective(s, scoreobjective)) { + throw new CommandException("commands.scoreboard.players.test.notFound", + new Object[] { scoreobjective.getName(), s }); + } else { + int i = parArrayOfString[parInt1].equals("*") ? Integer.MIN_VALUE : parseInt(parArrayOfString[parInt1]); + ++parInt1; + int j = parInt1 < parArrayOfString.length && !parArrayOfString[parInt1].equals("*") + ? parseInt(parArrayOfString[parInt1], i) + : Integer.MAX_VALUE; + Score score = scoreboard.getValueFromObjective(s, scoreobjective); + if (score.getScorePoints() >= i && score.getScorePoints() <= j) { + notifyOperators(parICommandSender, this, "commands.scoreboard.players.test.success", new Object[] { + Integer.valueOf(score.getScorePoints()), Integer.valueOf(i), Integer.valueOf(j) }); + } else { + throw new CommandException("commands.scoreboard.players.test.failed", new Object[] { + Integer.valueOf(score.getScorePoints()), Integer.valueOf(i), Integer.valueOf(j) }); + } + } + } + } + + protected List func_175782_e() { + Collection collection = this.getScoreboard().getScoreObjectives(); + ArrayList arraylist = Lists.newArrayList(); + + for (ScoreObjective scoreobjective : (Collection) collection) { + if (scoreobjective.getCriteria() == IScoreObjectiveCriteria.TRIGGER) { + arraylist.add(scoreobjective.getName()); + } + } + + return arraylist; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "scoreboard"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.scoreboard.usage"; } - /**+ - * Callback when the command is invoked + protected ScoreObjective getObjective(String name, boolean edit) throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + ScoreObjective scoreobjective = scoreboard.getObjective(name); + if (scoreobjective == null) { + throw new CommandException("commands.scoreboard.objectiveNotFound", new Object[] { name }); + } else if (edit && scoreobjective.getCriteria().isReadOnly()) { + throw new CommandException("commands.scoreboard.objectiveReadOnly", new Object[] { name }); + } else { + return scoreobjective; + } + } + + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + protected Scoreboard getScoreboard() { + return MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); + } + + protected ScorePlayerTeam getTeam(String name) throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + ScorePlayerTeam scoreplayerteam = scoreboard.getTeam(name); + if (scoreplayerteam == null) { + throw new CommandException("commands.scoreboard.teamNotFound", new Object[] { name }); + } else { + return scoreplayerteam; + } + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] astring, int i) { + return !astring[0].equalsIgnoreCase("players") ? (astring[0].equalsIgnoreCase("teams") ? i == 2 : false) + : (astring.length > 1 && astring[1].equalsIgnoreCase("operation") ? i == 2 || i == 5 : i == 2); + } + + protected void joinTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + String s = parArrayOfString[parInt1++]; + HashSet hashset = Sets.newHashSet(); + HashSet hashset1 = Sets.newHashSet(); + if (parICommandSender instanceof EntityPlayer && parInt1 == parArrayOfString.length) { + String s4 = getCommandSenderAsPlayer(parICommandSender).getName(); + if (scoreboard.addPlayerToTeam(s4, s)) { + hashset.add(s4); + } else { + hashset1.add(s4); + } + } else { + while (parInt1 < parArrayOfString.length) { + String s1 = parArrayOfString[parInt1++]; + if (s1.startsWith("@")) { + List lst = func_175763_c(parICommandSender, s1); + for (int i = 0, l = lst.size(); i < l; ++i) { + Entity entity = lst.get(i); + String s3 = getEntityName(parICommandSender, entity.getUniqueID().toString()); + if (scoreboard.addPlayerToTeam(s3, s)) { + hashset.add(s3); + } else { + hashset1.add(s3); + } + } + } else { + String s2 = getEntityName(parICommandSender, s1); + if (scoreboard.addPlayerToTeam(s2, s)) { + hashset.add(s2); + } else { + hashset1.add(s2); + } + } + } + } + + if (!hashset.isEmpty()) { + parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, hashset.size()); + notifyOperators(parICommandSender, this, "commands.scoreboard.teams.join.success", new Object[] { + Integer.valueOf(hashset.size()), s, joinNiceString(hashset.toArray(new String[hashset.size()])) }); + } + + if (!hashset1.isEmpty()) { + throw new CommandException("commands.scoreboard.teams.join.failure", + new Object[] { Integer.valueOf(hashset1.size()), s, + joinNiceString(hashset1.toArray(new String[hashset1.size()])) }); + } + } + + protected void leaveTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + HashSet hashset = Sets.newHashSet(); + HashSet hashset1 = Sets.newHashSet(); + if (parICommandSender instanceof EntityPlayer && parInt1 == parArrayOfString.length) { + String s3 = getCommandSenderAsPlayer(parICommandSender).getName(); + if (scoreboard.removePlayerFromTeams(s3)) { + hashset.add(s3); + } else { + hashset1.add(s3); + } + } else { + while (parInt1 < parArrayOfString.length) { + String s = parArrayOfString[parInt1++]; + if (s.startsWith("@")) { + List lst = func_175763_c(parICommandSender, s); + for (int i = 0, l = lst.size(); i < l; ++i) { + Entity entity = lst.get(i); + String s2 = getEntityName(parICommandSender, entity.getUniqueID().toString()); + if (scoreboard.removePlayerFromTeams(s2)) { + hashset.add(s2); + } else { + hashset1.add(s2); + } + } + } else { + String s1 = getEntityName(parICommandSender, s); + if (scoreboard.removePlayerFromTeams(s1)) { + hashset.add(s1); + } else { + hashset1.add(s1); + } + } + } + } + + if (!hashset.isEmpty()) { + parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, hashset.size()); + notifyOperators(parICommandSender, this, "commands.scoreboard.teams.leave.success", new Object[] { + Integer.valueOf(hashset.size()), joinNiceString(hashset.toArray(new String[hashset.size()])) }); + } + + if (!hashset1.isEmpty()) { + throw new CommandException("commands.scoreboard.teams.leave.failure", new Object[] { + Integer.valueOf(hashset1.size()), joinNiceString(hashset1.toArray(new String[hashset1.size()])) }); + } + } + + protected void listObjectives(ICommandSender parICommandSender) throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + Collection collection = scoreboard.getScoreObjectives(); + if (collection.size() <= 0) { + throw new CommandException("commands.scoreboard.objectives.list.empty", new Object[0]); + } else { + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + "commands.scoreboard.objectives.list.count", new Object[] { Integer.valueOf(collection.size()) }); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); + parICommandSender.addChatMessage(chatcomponenttranslation); + + for (ScoreObjective scoreobjective : (Collection) collection) { + parICommandSender.addChatMessage(new ChatComponentTranslation( + "commands.scoreboard.objectives.list.entry", new Object[] { scoreobjective.getName(), + scoreobjective.getDisplayName(), scoreobjective.getCriteria().getName() })); + } + + } + } + + protected void listPlayers(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + if (parArrayOfString.length > parInt1) { + String s = getEntityName(parICommandSender, parArrayOfString[parInt1]); + Map map = scoreboard.getObjectivesForEntity(s); + parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, map.size()); + if (map.size() <= 0) { + throw new CommandException("commands.scoreboard.players.list.player.empty", new Object[] { s }); + } + + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + "commands.scoreboard.players.list.player.count", new Object[] { Integer.valueOf(map.size()), s }); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); + parICommandSender.addChatMessage(chatcomponenttranslation); + + for (Score score : (Collection) map.values()) { + parICommandSender + .addChatMessage(new ChatComponentTranslation("commands.scoreboard.players.list.player.entry", + new Object[] { Integer.valueOf(score.getScorePoints()), + score.getObjective().getDisplayName(), score.getObjective().getName() })); + } + } else { + Collection collection = scoreboard.getObjectiveNames(); + parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection.size()); + if (collection.size() <= 0) { + throw new CommandException("commands.scoreboard.players.list.empty", new Object[0]); + } + + ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation( + "commands.scoreboard.players.list.count", new Object[] { Integer.valueOf(collection.size()) }); + chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); + parICommandSender.addChatMessage(chatcomponenttranslation1); + parICommandSender.addChatMessage(new ChatComponentText(joinNiceString(collection.toArray()))); + } + + } + + protected void listTeams(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + if (parArrayOfString.length > parInt1) { + ScorePlayerTeam scoreplayerteam = this.getTeam(parArrayOfString[parInt1]); + if (scoreplayerteam == null) { + return; + } + + Collection collection = scoreplayerteam.getMembershipCollection(); + parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection.size()); + if (collection.size() <= 0) { + throw new CommandException("commands.scoreboard.teams.list.player.empty", + new Object[] { scoreplayerteam.getRegisteredName() }); + } + + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( + "commands.scoreboard.teams.list.player.count", + new Object[] { Integer.valueOf(collection.size()), scoreplayerteam.getRegisteredName() }); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); + parICommandSender.addChatMessage(chatcomponenttranslation); + parICommandSender.addChatMessage(new ChatComponentText(joinNiceString(collection.toArray()))); + } else { + Collection collection1 = scoreboard.getTeams(); + parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection1.size()); + if (collection1.size() <= 0) { + throw new CommandException("commands.scoreboard.teams.list.empty", new Object[0]); + } + + ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation( + "commands.scoreboard.teams.list.count", new Object[] { Integer.valueOf(collection1.size()) }); + chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); + parICommandSender.addChatMessage(chatcomponenttranslation1); + + for (ScorePlayerTeam scoreplayerteam1 : (Collection) collection1) { + parICommandSender.addChatMessage(new ChatComponentTranslation("commands.scoreboard.teams.list.entry", + new Object[] { scoreplayerteam1.getRegisteredName(), scoreplayerteam1.getTeamName(), + Integer.valueOf(scoreplayerteam1.getMembershipCollection().size()) })); + } + } + + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (!this.func_175780_b(parICommandSender, parArrayOfString)) { @@ -236,141 +894,106 @@ public class CommandScoreboard extends CommandBase { } } - private boolean func_175780_b(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { - int i = -1; + protected void removeObjective(ICommandSender parICommandSender, String parString1) throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + ScoreObjective scoreobjective = this.getObjective(parString1, false); + scoreboard.removeObjective(scoreobjective); + notifyOperators(parICommandSender, this, "commands.scoreboard.objectives.remove.success", + new Object[] { parString1 }); + } - for (int j = 0; j < parArrayOfString.length; ++j) { - if (this.isUsernameIndex(parArrayOfString, j) && "*".equals(parArrayOfString[j])) { - if (i >= 0) { - throw new CommandException("commands.scoreboard.noMultiWildcard", new Object[0]); - } + protected void removeTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + ScorePlayerTeam scoreplayerteam = this.getTeam(parArrayOfString[parInt1]); + if (scoreplayerteam != null) { + scoreboard.removeTeam(scoreplayerteam); + notifyOperators(parICommandSender, this, "commands.scoreboard.teams.remove.success", + new Object[] { scoreplayerteam.getRegisteredName() }); + } + } - i = j; - } + protected void resetPlayers(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + String s = getEntityName(parICommandSender, parArrayOfString[parInt1++]); + if (parArrayOfString.length > parInt1) { + ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], false); + scoreboard.removeObjectiveFromEntity(s, scoreobjective); + notifyOperators(parICommandSender, this, "commands.scoreboard.players.resetscore.success", + new Object[] { scoreobjective.getName(), s }); + } else { + scoreboard.removeObjectiveFromEntity(s, (ScoreObjective) null); + notifyOperators(parICommandSender, this, "commands.scoreboard.players.reset.success", new Object[] { s }); + } + + } + + protected void setObjectiveDisplay(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + Scoreboard scoreboard = this.getScoreboard(); + String s = parArrayOfString[parInt1++]; + int i = Scoreboard.getObjectiveDisplaySlotNumber(s); + ScoreObjective scoreobjective = null; + if (parArrayOfString.length == 4) { + scoreobjective = this.getObjective(parArrayOfString[parInt1], false); } if (i < 0) { - return false; + throw new CommandException("commands.scoreboard.objectives.setdisplay.invalidSlot", new Object[] { s }); } else { - ArrayList arraylist1 = Lists.newArrayList(this.getScoreboard().getObjectiveNames()); - String s = parArrayOfString[i]; - ArrayList arraylist = Lists.newArrayList(); + scoreboard.setObjectiveInDisplaySlot(i, scoreobjective); + if (scoreobjective != null) { + notifyOperators(parICommandSender, this, "commands.scoreboard.objectives.setdisplay.successSet", + new Object[] { Scoreboard.getObjectiveDisplaySlot(i), scoreobjective.getName() }); + } else { + notifyOperators(parICommandSender, this, "commands.scoreboard.objectives.setdisplay.successCleared", + new Object[] { Scoreboard.getObjectiveDisplaySlot(i) }); + } - for (int j = 0, l = arraylist1.size(); j < l; ++j) { - String s1 = (String) arraylist1.get(j); - parArrayOfString[i] = s1; + } + } + + protected void setPlayer(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) + throws CommandException { + String s = parArrayOfString[parInt1 - 1]; + int i = parInt1; + String s1 = getEntityName(parICommandSender, parArrayOfString[parInt1++]); + if (s1.length() > 40) { + throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", + new Object[] { s1, Integer.valueOf(40) }); + } else { + ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], true); + int j = s.equalsIgnoreCase("set") ? parseInt(parArrayOfString[parInt1++]) + : parseInt(parArrayOfString[parInt1++], 0); + if (parArrayOfString.length > parInt1) { + Entity entity = func_175768_b(parICommandSender, parArrayOfString[i]); try { - this.processCommand(parICommandSender, parArrayOfString); - arraylist.add(s1); - } catch (CommandException commandexception) { - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( - commandexception.getMessage(), commandexception.getErrorObjects()); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); - parICommandSender.addChatMessage(chatcomponenttranslation); + NBTTagCompound nbttagcompound = JsonToNBT.getTagFromJson(buildString(parArrayOfString, parInt1)); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + entity.writeToNBT(nbttagcompound1); + if (!NBTUtil.func_181123_a(nbttagcompound, nbttagcompound1, true)) { + throw new CommandException("commands.scoreboard.players.set.tagMismatch", new Object[] { s1 }); + } + } catch (NBTException nbtexception) { + throw new CommandException("commands.scoreboard.players.set.tagError", + new Object[] { nbtexception.getMessage() }); } } - parArrayOfString[i] = s; - parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, arraylist.size()); - if (arraylist.size() == 0) { - throw new WrongUsageException("commands.scoreboard.allMatchesFailed", new Object[0]); + Scoreboard scoreboard = this.getScoreboard(); + Score score = scoreboard.getValueFromObjective(s1, scoreobjective); + if (s.equalsIgnoreCase("set")) { + score.setScorePoints(j); + } else if (s.equalsIgnoreCase("add")) { + score.increseScore(j); } else { - return true; - } - } - } - - protected Scoreboard getScoreboard() { - return MinecraftServer.getServer().worldServerForDimension(0).getScoreboard(); - } - - protected ScoreObjective getObjective(String name, boolean edit) throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - ScoreObjective scoreobjective = scoreboard.getObjective(name); - if (scoreobjective == null) { - throw new CommandException("commands.scoreboard.objectiveNotFound", new Object[] { name }); - } else if (edit && scoreobjective.getCriteria().isReadOnly()) { - throw new CommandException("commands.scoreboard.objectiveReadOnly", new Object[] { name }); - } else { - return scoreobjective; - } - } - - protected ScorePlayerTeam getTeam(String name) throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - ScorePlayerTeam scoreplayerteam = scoreboard.getTeam(name); - if (scoreplayerteam == null) { - throw new CommandException("commands.scoreboard.teamNotFound", new Object[] { name }); - } else { - return scoreplayerteam; - } - } - - protected void addObjective(ICommandSender sender, String[] args, int index) throws CommandException { - String s = args[index++]; - String s1 = args[index++]; - Scoreboard scoreboard = this.getScoreboard(); - IScoreObjectiveCriteria iscoreobjectivecriteria = (IScoreObjectiveCriteria) IScoreObjectiveCriteria.INSTANCES - .get(s1); - if (iscoreobjectivecriteria == null) { - throw new WrongUsageException("commands.scoreboard.objectives.add.wrongType", new Object[] { s1 }); - } else if (scoreboard.getObjective(s) != null) { - throw new CommandException("commands.scoreboard.objectives.add.alreadyExists", new Object[] { s }); - } else if (s.length() > 16) { - throw new SyntaxErrorException("commands.scoreboard.objectives.add.tooLong", - new Object[] { s, Integer.valueOf(16) }); - } else if (s.length() == 0) { - throw new WrongUsageException("commands.scoreboard.objectives.add.usage", new Object[0]); - } else { - if (args.length > index) { - String s2 = getChatComponentFromNthArg(sender, args, index).getUnformattedText(); - if (s2.length() > 32) { - throw new SyntaxErrorException("commands.scoreboard.objectives.add.displayTooLong", - new Object[] { s2, Integer.valueOf(32) }); - } - - if (s2.length() > 0) { - scoreboard.addScoreObjective(s, iscoreobjectivecriteria).setDisplayName(s2); - } else { - scoreboard.addScoreObjective(s, iscoreobjectivecriteria); - } - } else { - scoreboard.addScoreObjective(s, iscoreobjectivecriteria); + score.decreaseScore(j); } - notifyOperators(sender, this, "commands.scoreboard.objectives.add.success", new Object[] { s }); - } - } - - protected void addTeam(ICommandSender sender, String[] args, int index) throws CommandException { - String s = args[index++]; - Scoreboard scoreboard = this.getScoreboard(); - if (scoreboard.getTeam(s) != null) { - throw new CommandException("commands.scoreboard.teams.add.alreadyExists", new Object[] { s }); - } else if (s.length() > 16) { - throw new SyntaxErrorException("commands.scoreboard.teams.add.tooLong", - new Object[] { s, Integer.valueOf(16) }); - } else if (s.length() == 0) { - throw new WrongUsageException("commands.scoreboard.teams.add.usage", new Object[0]); - } else { - if (args.length > index) { - String s1 = getChatComponentFromNthArg(sender, args, index).getUnformattedText(); - if (s1.length() > 32) { - throw new SyntaxErrorException("commands.scoreboard.teams.add.displayTooLong", - new Object[] { s1, Integer.valueOf(32) }); - } - - if (s1.length() > 0) { - scoreboard.createTeam(s).setTeamName(s1); - } else { - scoreboard.createTeam(s); - } - } else { - scoreboard.createTeam(s); - } - - notifyOperators(sender, this, "commands.scoreboard.teams.add.success", new Object[] { s }); + notifyOperators(parICommandSender, this, "commands.scoreboard.players.set.success", + new Object[] { scoreobjective.getName(), s1, Integer.valueOf(score.getScorePoints()) }); } } @@ -446,622 +1069,4 @@ public class CommandScoreboard extends CommandBase { } } } - - protected void removeTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - ScorePlayerTeam scoreplayerteam = this.getTeam(parArrayOfString[parInt1]); - if (scoreplayerteam != null) { - scoreboard.removeTeam(scoreplayerteam); - notifyOperators(parICommandSender, this, "commands.scoreboard.teams.remove.success", - new Object[] { scoreplayerteam.getRegisteredName() }); - } - } - - protected void listTeams(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - if (parArrayOfString.length > parInt1) { - ScorePlayerTeam scoreplayerteam = this.getTeam(parArrayOfString[parInt1]); - if (scoreplayerteam == null) { - return; - } - - Collection collection = scoreplayerteam.getMembershipCollection(); - parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection.size()); - if (collection.size() <= 0) { - throw new CommandException("commands.scoreboard.teams.list.player.empty", - new Object[] { scoreplayerteam.getRegisteredName() }); - } - - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( - "commands.scoreboard.teams.list.player.count", - new Object[] { Integer.valueOf(collection.size()), scoreplayerteam.getRegisteredName() }); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); - parICommandSender.addChatMessage(chatcomponenttranslation); - parICommandSender.addChatMessage(new ChatComponentText(joinNiceString(collection.toArray()))); - } else { - Collection collection1 = scoreboard.getTeams(); - parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection1.size()); - if (collection1.size() <= 0) { - throw new CommandException("commands.scoreboard.teams.list.empty", new Object[0]); - } - - ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation( - "commands.scoreboard.teams.list.count", new Object[] { Integer.valueOf(collection1.size()) }); - chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); - parICommandSender.addChatMessage(chatcomponenttranslation1); - - for (ScorePlayerTeam scoreplayerteam1 : (Collection) collection1) { - parICommandSender.addChatMessage(new ChatComponentTranslation("commands.scoreboard.teams.list.entry", - new Object[] { scoreplayerteam1.getRegisteredName(), scoreplayerteam1.getTeamName(), - Integer.valueOf(scoreplayerteam1.getMembershipCollection().size()) })); - } - } - - } - - protected void joinTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - String s = parArrayOfString[parInt1++]; - HashSet hashset = Sets.newHashSet(); - HashSet hashset1 = Sets.newHashSet(); - if (parICommandSender instanceof EntityPlayer && parInt1 == parArrayOfString.length) { - String s4 = getCommandSenderAsPlayer(parICommandSender).getName(); - if (scoreboard.addPlayerToTeam(s4, s)) { - hashset.add(s4); - } else { - hashset1.add(s4); - } - } else { - while (parInt1 < parArrayOfString.length) { - String s1 = parArrayOfString[parInt1++]; - if (s1.startsWith("@")) { - List lst = func_175763_c(parICommandSender, s1); - for (int i = 0, l = lst.size(); i < l; ++i) { - Entity entity = lst.get(i); - String s3 = getEntityName(parICommandSender, entity.getUniqueID().toString()); - if (scoreboard.addPlayerToTeam(s3, s)) { - hashset.add(s3); - } else { - hashset1.add(s3); - } - } - } else { - String s2 = getEntityName(parICommandSender, s1); - if (scoreboard.addPlayerToTeam(s2, s)) { - hashset.add(s2); - } else { - hashset1.add(s2); - } - } - } - } - - if (!hashset.isEmpty()) { - parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, hashset.size()); - notifyOperators(parICommandSender, this, "commands.scoreboard.teams.join.success", new Object[] { - Integer.valueOf(hashset.size()), s, joinNiceString(hashset.toArray(new String[hashset.size()])) }); - } - - if (!hashset1.isEmpty()) { - throw new CommandException("commands.scoreboard.teams.join.failure", - new Object[] { Integer.valueOf(hashset1.size()), s, - joinNiceString(hashset1.toArray(new String[hashset1.size()])) }); - } - } - - protected void leaveTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - HashSet hashset = Sets.newHashSet(); - HashSet hashset1 = Sets.newHashSet(); - if (parICommandSender instanceof EntityPlayer && parInt1 == parArrayOfString.length) { - String s3 = getCommandSenderAsPlayer(parICommandSender).getName(); - if (scoreboard.removePlayerFromTeams(s3)) { - hashset.add(s3); - } else { - hashset1.add(s3); - } - } else { - while (parInt1 < parArrayOfString.length) { - String s = parArrayOfString[parInt1++]; - if (s.startsWith("@")) { - List lst = func_175763_c(parICommandSender, s); - for (int i = 0, l = lst.size(); i < l; ++i) { - Entity entity = lst.get(i); - String s2 = getEntityName(parICommandSender, entity.getUniqueID().toString()); - if (scoreboard.removePlayerFromTeams(s2)) { - hashset.add(s2); - } else { - hashset1.add(s2); - } - } - } else { - String s1 = getEntityName(parICommandSender, s); - if (scoreboard.removePlayerFromTeams(s1)) { - hashset.add(s1); - } else { - hashset1.add(s1); - } - } - } - } - - if (!hashset.isEmpty()) { - parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, hashset.size()); - notifyOperators(parICommandSender, this, "commands.scoreboard.teams.leave.success", new Object[] { - Integer.valueOf(hashset.size()), joinNiceString(hashset.toArray(new String[hashset.size()])) }); - } - - if (!hashset1.isEmpty()) { - throw new CommandException("commands.scoreboard.teams.leave.failure", new Object[] { - Integer.valueOf(hashset1.size()), joinNiceString(hashset1.toArray(new String[hashset1.size()])) }); - } - } - - protected void emptyTeam(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - ScorePlayerTeam scoreplayerteam = this.getTeam(parArrayOfString[parInt1]); - if (scoreplayerteam != null) { - ArrayList arraylist = Lists.newArrayList(scoreplayerteam.getMembershipCollection()); - parICommandSender.setCommandStat(CommandResultStats.Type.AFFECTED_ENTITIES, arraylist.size()); - if (arraylist.isEmpty()) { - throw new CommandException("commands.scoreboard.teams.empty.alreadyEmpty", - new Object[] { scoreplayerteam.getRegisteredName() }); - } else { - for (int i = 0, l = arraylist.size(); i < l; ++i) { - scoreboard.removePlayerFromTeam(arraylist.get(i), scoreplayerteam); - } - - notifyOperators(parICommandSender, this, "commands.scoreboard.teams.empty.success", - new Object[] { Integer.valueOf(arraylist.size()), scoreplayerteam.getRegisteredName() }); - } - } - } - - protected void removeObjective(ICommandSender parICommandSender, String parString1) throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - ScoreObjective scoreobjective = this.getObjective(parString1, false); - scoreboard.removeObjective(scoreobjective); - notifyOperators(parICommandSender, this, "commands.scoreboard.objectives.remove.success", - new Object[] { parString1 }); - } - - protected void listObjectives(ICommandSender parICommandSender) throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - Collection collection = scoreboard.getScoreObjectives(); - if (collection.size() <= 0) { - throw new CommandException("commands.scoreboard.objectives.list.empty", new Object[0]); - } else { - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( - "commands.scoreboard.objectives.list.count", new Object[] { Integer.valueOf(collection.size()) }); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); - parICommandSender.addChatMessage(chatcomponenttranslation); - - for (ScoreObjective scoreobjective : (Collection) collection) { - parICommandSender.addChatMessage(new ChatComponentTranslation( - "commands.scoreboard.objectives.list.entry", new Object[] { scoreobjective.getName(), - scoreobjective.getDisplayName(), scoreobjective.getCriteria().getName() })); - } - - } - } - - protected void setObjectiveDisplay(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - String s = parArrayOfString[parInt1++]; - int i = Scoreboard.getObjectiveDisplaySlotNumber(s); - ScoreObjective scoreobjective = null; - if (parArrayOfString.length == 4) { - scoreobjective = this.getObjective(parArrayOfString[parInt1], false); - } - - if (i < 0) { - throw new CommandException("commands.scoreboard.objectives.setdisplay.invalidSlot", new Object[] { s }); - } else { - scoreboard.setObjectiveInDisplaySlot(i, scoreobjective); - if (scoreobjective != null) { - notifyOperators(parICommandSender, this, "commands.scoreboard.objectives.setdisplay.successSet", - new Object[] { Scoreboard.getObjectiveDisplaySlot(i), scoreobjective.getName() }); - } else { - notifyOperators(parICommandSender, this, "commands.scoreboard.objectives.setdisplay.successCleared", - new Object[] { Scoreboard.getObjectiveDisplaySlot(i) }); - } - - } - } - - protected void listPlayers(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - if (parArrayOfString.length > parInt1) { - String s = getEntityName(parICommandSender, parArrayOfString[parInt1]); - Map map = scoreboard.getObjectivesForEntity(s); - parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, map.size()); - if (map.size() <= 0) { - throw new CommandException("commands.scoreboard.players.list.player.empty", new Object[] { s }); - } - - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation( - "commands.scoreboard.players.list.player.count", new Object[] { Integer.valueOf(map.size()), s }); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); - parICommandSender.addChatMessage(chatcomponenttranslation); - - for (Score score : (Collection) map.values()) { - parICommandSender - .addChatMessage(new ChatComponentTranslation("commands.scoreboard.players.list.player.entry", - new Object[] { Integer.valueOf(score.getScorePoints()), - score.getObjective().getDisplayName(), score.getObjective().getName() })); - } - } else { - Collection collection = scoreboard.getObjectiveNames(); - parICommandSender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, collection.size()); - if (collection.size() <= 0) { - throw new CommandException("commands.scoreboard.players.list.empty", new Object[0]); - } - - ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation( - "commands.scoreboard.players.list.count", new Object[] { Integer.valueOf(collection.size()) }); - chatcomponenttranslation1.getChatStyle().setColor(EnumChatFormatting.DARK_GREEN); - parICommandSender.addChatMessage(chatcomponenttranslation1); - parICommandSender.addChatMessage(new ChatComponentText(joinNiceString(collection.toArray()))); - } - - } - - protected void setPlayer(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - String s = parArrayOfString[parInt1 - 1]; - int i = parInt1; - String s1 = getEntityName(parICommandSender, parArrayOfString[parInt1++]); - if (s1.length() > 40) { - throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", - new Object[] { s1, Integer.valueOf(40) }); - } else { - ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], true); - int j = s.equalsIgnoreCase("set") ? parseInt(parArrayOfString[parInt1++]) - : parseInt(parArrayOfString[parInt1++], 0); - if (parArrayOfString.length > parInt1) { - Entity entity = func_175768_b(parICommandSender, parArrayOfString[i]); - - try { - NBTTagCompound nbttagcompound = JsonToNBT.getTagFromJson(buildString(parArrayOfString, parInt1)); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - entity.writeToNBT(nbttagcompound1); - if (!NBTUtil.func_181123_a(nbttagcompound, nbttagcompound1, true)) { - throw new CommandException("commands.scoreboard.players.set.tagMismatch", new Object[] { s1 }); - } - } catch (NBTException nbtexception) { - throw new CommandException("commands.scoreboard.players.set.tagError", - new Object[] { nbtexception.getMessage() }); - } - } - - Scoreboard scoreboard = this.getScoreboard(); - Score score = scoreboard.getValueFromObjective(s1, scoreobjective); - if (s.equalsIgnoreCase("set")) { - score.setScorePoints(j); - } else if (s.equalsIgnoreCase("add")) { - score.increseScore(j); - } else { - score.decreaseScore(j); - } - - notifyOperators(parICommandSender, this, "commands.scoreboard.players.set.success", - new Object[] { scoreobjective.getName(), s1, Integer.valueOf(score.getScorePoints()) }); - } - } - - protected void resetPlayers(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - String s = getEntityName(parICommandSender, parArrayOfString[parInt1++]); - if (parArrayOfString.length > parInt1) { - ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], false); - scoreboard.removeObjectiveFromEntity(s, scoreobjective); - notifyOperators(parICommandSender, this, "commands.scoreboard.players.resetscore.success", - new Object[] { scoreobjective.getName(), s }); - } else { - scoreboard.removeObjectiveFromEntity(s, (ScoreObjective) null); - notifyOperators(parICommandSender, this, "commands.scoreboard.players.reset.success", new Object[] { s }); - } - - } - - protected void func_175779_n(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - String s = getPlayerName(parICommandSender, parArrayOfString[parInt1++]); - if (s.length() > 40) { - throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", - new Object[] { s, Integer.valueOf(40) }); - } else { - ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1], false); - if (scoreobjective.getCriteria() != IScoreObjectiveCriteria.TRIGGER) { - throw new CommandException("commands.scoreboard.players.enable.noTrigger", - new Object[] { scoreobjective.getName() }); - } else { - Score score = scoreboard.getValueFromObjective(s, scoreobjective); - score.setLocked(false); - notifyOperators(parICommandSender, this, "commands.scoreboard.players.enable.success", - new Object[] { scoreobjective.getName(), s }); - } - } - } - - protected void func_175781_o(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - String s = getEntityName(parICommandSender, parArrayOfString[parInt1++]); - if (s.length() > 40) { - throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", - new Object[] { s, Integer.valueOf(40) }); - } else { - ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], false); - if (!scoreboard.entityHasObjective(s, scoreobjective)) { - throw new CommandException("commands.scoreboard.players.test.notFound", - new Object[] { scoreobjective.getName(), s }); - } else { - int i = parArrayOfString[parInt1].equals("*") ? Integer.MIN_VALUE : parseInt(parArrayOfString[parInt1]); - ++parInt1; - int j = parInt1 < parArrayOfString.length && !parArrayOfString[parInt1].equals("*") - ? parseInt(parArrayOfString[parInt1], i) - : Integer.MAX_VALUE; - Score score = scoreboard.getValueFromObjective(s, scoreobjective); - if (score.getScorePoints() >= i && score.getScorePoints() <= j) { - notifyOperators(parICommandSender, this, "commands.scoreboard.players.test.success", new Object[] { - Integer.valueOf(score.getScorePoints()), Integer.valueOf(i), Integer.valueOf(j) }); - } else { - throw new CommandException("commands.scoreboard.players.test.failed", new Object[] { - Integer.valueOf(score.getScorePoints()), Integer.valueOf(i), Integer.valueOf(j) }); - } - } - } - } - - protected void func_175778_p(ICommandSender parICommandSender, String[] parArrayOfString, int parInt1) - throws CommandException { - Scoreboard scoreboard = this.getScoreboard(); - String s = getEntityName(parICommandSender, parArrayOfString[parInt1++]); - ScoreObjective scoreobjective = this.getObjective(parArrayOfString[parInt1++], true); - String s1 = parArrayOfString[parInt1++]; - String s2 = getEntityName(parICommandSender, parArrayOfString[parInt1++]); - ScoreObjective scoreobjective1 = this.getObjective(parArrayOfString[parInt1], false); - if (s.length() > 40) { - throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", - new Object[] { s, Integer.valueOf(40) }); - } else if (s2.length() > 40) { - throw new SyntaxErrorException("commands.scoreboard.players.name.tooLong", - new Object[] { s2, Integer.valueOf(40) }); - } else { - Score score = scoreboard.getValueFromObjective(s, scoreobjective); - if (!scoreboard.entityHasObjective(s2, scoreobjective1)) { - throw new CommandException("commands.scoreboard.players.operation.notFound", - new Object[] { scoreobjective1.getName(), s2 }); - } else { - Score score1 = scoreboard.getValueFromObjective(s2, scoreobjective1); - if (s1.equals("+=")) { - score.setScorePoints(score.getScorePoints() + score1.getScorePoints()); - } else if (s1.equals("-=")) { - score.setScorePoints(score.getScorePoints() - score1.getScorePoints()); - } else if (s1.equals("*=")) { - score.setScorePoints(score.getScorePoints() * score1.getScorePoints()); - } else if (s1.equals("/=")) { - if (score1.getScorePoints() != 0) { - score.setScorePoints(score.getScorePoints() / score1.getScorePoints()); - } - } else if (s1.equals("%=")) { - if (score1.getScorePoints() != 0) { - score.setScorePoints(score.getScorePoints() % score1.getScorePoints()); - } - } else if (s1.equals("=")) { - score.setScorePoints(score1.getScorePoints()); - } else if (s1.equals("<")) { - score.setScorePoints(Math.min(score.getScorePoints(), score1.getScorePoints())); - } else if (s1.equals(">")) { - score.setScorePoints(Math.max(score.getScorePoints(), score1.getScorePoints())); - } else { - if (!s1.equals("><")) { - throw new CommandException("commands.scoreboard.players.operation.invalidOperation", - new Object[] { s1 }); - } - - int i = score.getScorePoints(); - score.setScorePoints(score1.getScorePoints()); - score1.setScorePoints(i); - } - - notifyOperators(parICommandSender, this, "commands.scoreboard.players.operation.success", - new Object[0]); - } - } - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - if (astring.length == 1) { - return getListOfStringsMatchingLastWord(astring, new String[] { "objectives", "players", "teams" }); - } else { - if (astring[0].equalsIgnoreCase("objectives")) { - if (astring.length == 2) { - return getListOfStringsMatchingLastWord(astring, - new String[] { "list", "add", "remove", "setdisplay" }); - } - - if (astring[1].equalsIgnoreCase("add")) { - if (astring.length == 4) { - Set set = IScoreObjectiveCriteria.INSTANCES.keySet(); - return getListOfStringsMatchingLastWord(astring, set); - } - } else if (astring[1].equalsIgnoreCase("remove")) { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); - } - } else if (astring[1].equalsIgnoreCase("setdisplay")) { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, Scoreboard.getDisplaySlotStrings()); - } - - if (astring.length == 4) { - return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); - } - } - } else if (astring[0].equalsIgnoreCase("players")) { - if (astring.length == 2) { - return getListOfStringsMatchingLastWord(astring, - new String[] { "set", "add", "remove", "reset", "list", "enable", "test", "operation" }); - } - - if (!astring[1].equalsIgnoreCase("set") && !astring[1].equalsIgnoreCase("add") - && !astring[1].equalsIgnoreCase("remove") && !astring[1].equalsIgnoreCase("reset")) { - if (astring[1].equalsIgnoreCase("enable")) { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, - MinecraftServer.getServer().getAllUsernames()); - } - - if (astring.length == 4) { - return getListOfStringsMatchingLastWord(astring, this.func_175782_e()); - } - } else if (!astring[1].equalsIgnoreCase("list") && !astring[1].equalsIgnoreCase("test")) { - if (astring[1].equalsIgnoreCase("operation")) { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, - this.getScoreboard().getObjectiveNames()); - } - - if (astring.length == 4) { - return getListOfStringsMatchingLastWord(astring, this.func_147184_a(true)); - } - - if (astring.length == 5) { - return getListOfStringsMatchingLastWord(astring, - new String[] { "+=", "-=", "*=", "/=", "%=", "=", "<", ">", "><" }); - } - - if (astring.length == 6) { - return getListOfStringsMatchingLastWord(astring, - MinecraftServer.getServer().getAllUsernames()); - } - - if (astring.length == 7) { - return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); - } - } - } else { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getObjectiveNames()); - } - - if (astring.length == 4 && astring[1].equalsIgnoreCase("test")) { - return getListOfStringsMatchingLastWord(astring, this.func_147184_a(false)); - } - } - } else { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); - } - - if (astring.length == 4) { - return getListOfStringsMatchingLastWord(astring, this.func_147184_a(true)); - } - } - } else if (astring[0].equalsIgnoreCase("teams")) { - if (astring.length == 2) { - return getListOfStringsMatchingLastWord(astring, - new String[] { "add", "remove", "join", "leave", "empty", "list", "option" }); - } - - if (astring[1].equalsIgnoreCase("join")) { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getTeamNames()); - } - - if (astring.length >= 4) { - return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); - } - } else { - if (astring[1].equalsIgnoreCase("leave")) { - return getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); - } - - if (!astring[1].equalsIgnoreCase("empty") && !astring[1].equalsIgnoreCase("list") - && !astring[1].equalsIgnoreCase("remove")) { - if (astring[1].equalsIgnoreCase("option")) { - if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getTeamNames()); - } - - if (astring.length == 4) { - return getListOfStringsMatchingLastWord(astring, new String[] { "color", "friendlyfire", - "seeFriendlyInvisibles", "nametagVisibility", "deathMessageVisibility" }); - } - - if (astring.length == 5) { - if (astring[3].equalsIgnoreCase("color")) { - return getListOfStringsMatchingLastWord(astring, - EnumChatFormatting.getValidValues(true, false)); - } - - if (astring[3].equalsIgnoreCase("nametagVisibility") - || astring[3].equalsIgnoreCase("deathMessageVisibility")) { - return getListOfStringsMatchingLastWord(astring, Team.EnumVisible.func_178825_a()); - } - - if (astring[3].equalsIgnoreCase("friendlyfire") - || astring[3].equalsIgnoreCase("seeFriendlyInvisibles")) { - return getListOfStringsMatchingLastWord(astring, new String[] { "true", "false" }); - } - } - } - } else if (astring.length == 3) { - return getListOfStringsMatchingLastWord(astring, this.getScoreboard().getTeamNames()); - } - } - } - - return null; - } - } - - protected List func_147184_a(boolean parFlag) { - Collection collection = this.getScoreboard().getScoreObjectives(); - ArrayList arraylist = Lists.newArrayList(); - - for (ScoreObjective scoreobjective : (Collection) collection) { - if (!parFlag || !scoreobjective.getCriteria().isReadOnly()) { - arraylist.add(scoreobjective.getName()); - } - } - - return arraylist; - } - - protected List func_175782_e() { - Collection collection = this.getScoreboard().getScoreObjectives(); - ArrayList arraylist = Lists.newArrayList(); - - for (ScoreObjective scoreobjective : (Collection) collection) { - if (scoreobjective.getCriteria() == IScoreObjectiveCriteria.TRIGGER) { - arraylist.add(scoreobjective.getName()); - } - } - - return arraylist; - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] astring, int i) { - return !astring[0].equalsIgnoreCase("players") ? (astring[0].equalsIgnoreCase("teams") ? i == 2 : false) - : (astring.length > 1 && astring[1].equalsIgnoreCase("operation") ? i == 2 || i == 5 : i == 2); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandSetBlock.java b/src/game/java/net/minecraft/command/server/CommandSetBlock.java index fade72c3..6e4b97b8 100644 --- a/src/game/java/net/minecraft/command/server/CommandSetBlock.java +++ b/src/game/java/net/minecraft/command/server/CommandSetBlock.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.command.CommandBase; @@ -17,51 +18,66 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandSetBlock extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) + : (astring.length == 4 ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) + : (astring.length == 6 + ? getListOfStringsMatchingLastWord(astring, + new String[] { "replace", "destroy", "keep" }) + : null)); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "setblock"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.setblock.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 4) { @@ -135,16 +151,4 @@ public class CommandSetBlock extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) - : (astring.length == 4 ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) - : (astring.length == 6 - ? getListOfStringsMatchingLastWord(astring, - new String[] { "replace", "destroy", "keep" }) - : null)); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandSetDefaultSpawnpoint.java b/src/game/java/net/minecraft/command/server/CommandSetDefaultSpawnpoint.java index 7c845886..0ec2a4fb 100644 --- a/src/game/java/net/minecraft/command/server/CommandSetDefaultSpawnpoint.java +++ b/src/game/java/net/minecraft/command/server/CommandSetDefaultSpawnpoint.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -9,51 +10,61 @@ import net.minecraft.network.play.server.S05PacketSpawnPosition; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandSetDefaultSpawnpoint extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "setworldspawn"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.setworldspawn.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { BlockPos blockpos; @@ -73,11 +84,4 @@ public class CommandSetDefaultSpawnpoint extends CommandBase { notifyOperators(parICommandSender, this, "commands.setworldspawn.success", new Object[] { Integer.valueOf(blockpos.getX()), Integer.valueOf(blockpos.getY()), Integer.valueOf(blockpos.getZ()) }); } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandSummon.java b/src/game/java/net/minecraft/command/server/CommandSummon.java index cf1f40a8..38de667a 100644 --- a/src/game/java/net/minecraft/command/server/CommandSummon.java +++ b/src/game/java/net/minecraft/command/server/CommandSummon.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -18,51 +19,62 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandSummon extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, EntityList.getEntityNameList()) + : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "summon"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.summon.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 1) { @@ -141,12 +153,4 @@ public class CommandSummon extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length == 1 ? getListOfStringsMatchingLastWord(astring, EntityList.getEntityNameList()) - : (astring.length > 1 && astring.length <= 4 ? func_175771_a(astring, 1, blockpos) : null); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandTeleport.java b/src/game/java/net/minecraft/command/server/CommandTeleport.java index ee584ba2..6a3fa244 100644 --- a/src/game/java/net/minecraft/command/server/CommandTeleport.java +++ b/src/game/java/net/minecraft/command/server/CommandTeleport.java @@ -2,6 +2,7 @@ package net.minecraft.command.server; import java.util.EnumSet; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -13,51 +14,70 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandTeleport extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length != 1 && astring.length != 2 ? null + : getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "tp"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.tp.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 1) { @@ -171,20 +191,4 @@ public class CommandTeleport extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length != 1 && astring.length != 2 ? null - : getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()); - } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandTestFor.java b/src/game/java/net/minecraft/command/server/CommandTestFor.java index 76d56273..0fcd5513 100644 --- a/src/game/java/net/minecraft/command/server/CommandTestFor.java +++ b/src/game/java/net/minecraft/command/server/CommandTestFor.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.command.CommandBase; import net.minecraft.command.CommandException; import net.minecraft.command.ICommandSender; @@ -13,51 +14,71 @@ import net.minecraft.nbt.NBTUtil; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandTestFor extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { + return astring.length == 1 + ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) + : null; + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "testfor"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.testfor.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Return whether the specified command parameter index is a username + * parameter. + */ + public boolean isUsernameIndex(String[] var1, int i) { + return i == 0; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 1) { @@ -84,21 +105,4 @@ public class CommandTestFor extends CommandBase { notifyOperators(parICommandSender, this, "commands.testfor.success", new Object[] { entity.getName() }); } } - - /**+ - * Return whether the specified command parameter index is a - * username parameter. - */ - public boolean isUsernameIndex(String[] var1, int i) { - return i == 0; - } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos var3) { - return astring.length == 1 - ? getListOfStringsMatchingLastWord(astring, MinecraftServer.getServer().getAllUsernames()) - : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/command/server/CommandTestForBlock.java b/src/game/java/net/minecraft/command/server/CommandTestForBlock.java index 6aab3a77..cc7fc5cf 100644 --- a/src/game/java/net/minecraft/command/server/CommandTestForBlock.java +++ b/src/game/java/net/minecraft/command/server/CommandTestForBlock.java @@ -1,6 +1,7 @@ package net.minecraft.command.server; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.command.CommandBase; @@ -17,51 +18,63 @@ import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CommandTestForBlock extends CommandBase { - /**+ - * Gets the name of the command + /** + * + Return a list of options when the user types TAB + */ + public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { + return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) + : (astring.length == 4 ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) + : null); + } + + /** + * + Gets the name of the command */ public String getCommandName() { return "testforblock"; } - /**+ - * Return the required permission level for this command. - */ - public int getRequiredPermissionLevel() { - return 2; - } - - /**+ - * Gets the usage string for the command. + /** + * + Gets the usage string for the command. */ public String getCommandUsage(ICommandSender var1) { return "commands.testforblock.usage"; } - /**+ - * Callback when the command is invoked + /** + * + Return the required permission level for this command. + */ + public int getRequiredPermissionLevel() { + return 2; + } + + /** + * + Callback when the command is invoked */ public void processCommand(ICommandSender parICommandSender, String[] parArrayOfString) throws CommandException { if (parArrayOfString.length < 4) { @@ -141,13 +154,4 @@ public class CommandTestForBlock extends CommandBase { } } } - - /**+ - * Return a list of options when the user types TAB - */ - public List addTabCompletionOptions(ICommandSender var1, String[] astring, BlockPos blockpos) { - return astring.length > 0 && astring.length <= 3 ? func_175771_a(astring, 0, blockpos) - : (astring.length == 4 ? getListOfStringsMatchingLastWord(astring, Block.blockRegistry.getKeys()) - : null); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/crash/CrashReport.java b/src/game/java/net/minecraft/crash/CrashReport.java index bea9fa8d..b79e112a 100644 --- a/src/game/java/net/minecraft/crash/CrashReport.java +++ b/src/game/java/net/minecraft/crash/CrashReport.java @@ -14,39 +14,66 @@ import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.util.ReportedException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CrashReport { private static final Logger logger = LogManager.getLogger(); + + /** + * + Gets a random witty comment for inclusion in this CrashReport + */ + private static String getWittyComment() { + return "eagler"; + } + + /** + * + Creates a crash report for the exception + */ + public static CrashReport makeCrashReport(Throwable causeIn, String descriptionIn) { + CrashReport crashreport; + if (causeIn instanceof ReportedException) { + crashreport = ((ReportedException) causeIn).getCrashReport(); + } else { + crashreport = new CrashReport(descriptionIn, causeIn); + } + + return crashreport; + } + private final String description; private final Throwable cause; - /**+ - * Category of crash + /** + * + Category of crash */ private final CrashReportCategory theReportCategory = new CrashReportCategory(this, "System Details"); - /**+ - * Holds the keys and values of all crash report sections. + /** + * + Holds the keys and values of all crash report sections. */ private final List crashReportSections = Lists.newArrayList(); + private boolean field_85059_f = true; + private String[] stacktrace; public CrashReport(String descriptionIn, Throwable causeThrowable) { @@ -56,67 +83,79 @@ public class CrashReport { this.populateEnvironment(); } - /**+ - * Populates this crash report with initial information about - * the running server and operating system / java environment + public CrashReportCategory getCategory() { + return this.theReportCategory; + } + + /** + * + Gets the stack trace of the Throwable that caused this crash report, or if + * that fails, the cause .toString(). */ - private void populateEnvironment() { - this.theReportCategory.addCrashSectionCallable("Minecraft Version", new Callable() { - public String call() { - return "1.8.8"; - } - }); - this.theReportCategory.addCrashSectionCallable("Operating System", new Callable() { - public String call() { - return System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " - + System.getProperty("os.version"); - } - }); - this.theReportCategory.addCrashSectionCallable("Java Version", new Callable() { - public String call() { - return System.getProperty("java.version") + ", " + System.getProperty("java.vendor"); - } - }); - this.theReportCategory.addCrashSectionCallable("Java VM Version", new Callable() { - public String call() { - return System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " - + System.getProperty("java.vm.vendor"); - } - }); - if (EagRuntime.getPlatformType() != EnumPlatformType.JAVASCRIPT) { - this.theReportCategory.addCrashSectionCallable("Memory", new Callable() { - public String call() { - long i = EagRuntime.maxMemory(); - long j = EagRuntime.totalMemory(); - long k = EagRuntime.freeMemory(); - long l = i / 1024L / 1024L; - long i1 = j / 1024L / 1024L; - long j1 = k / 1024L / 1024L; - return k + " bytes (" + j1 + " MB) / " + j + " bytes (" + i1 + " MB) up to " + i + " bytes (" + l - + " MB)"; - } - }); + public String getCauseStackTraceOrString() { + StringBuilder stackTrace = new StringBuilder(); + + if ((this.cause.getMessage() == null || this.cause.getMessage().length() == 0) + && ((this.cause instanceof NullPointerException) || (this.cause instanceof StackOverflowError) + || (this.cause instanceof OutOfMemoryError))) { + stackTrace.append(this.cause.getClass().getName()).append(": "); + stackTrace.append(this.description).append('\n'); + } else { + stackTrace.append(this.cause.toString()).append('\n'); } + + EagRuntime.getStackTrace(this.cause, (s) -> { + stackTrace.append("\tat ").append(s).append('\n'); + }); + + return stackTrace.toString(); } - /**+ - * Returns the description of the Crash Report. + /** + * + Gets the complete report with headers, stack trace, and different sections + * as a string. */ - public String getDescription() { - return this.description; + public String getCompleteReport() { + StringBuilder stringbuilder = new StringBuilder(); + stringbuilder.append("---- Minecraft Crash Report ----\n"); + stringbuilder.append("// "); + stringbuilder.append(getWittyComment()); + stringbuilder.append("\n\n"); + stringbuilder.append("Time: "); + stringbuilder.append((new SimpleDateFormat()).format(new Date())); + stringbuilder.append("\n"); + stringbuilder.append("Description: "); + stringbuilder.append(this.description); + stringbuilder.append("\n\n"); + stringbuilder.append(this.getCauseStackTraceOrString()); + stringbuilder.append( + "\n\nA detailed walkthrough of the error, its code path and all known details is as follows:\n"); + + for (int i = 0; i < 87; ++i) { + stringbuilder.append("-"); + } + + stringbuilder.append("\n\n"); + this.getSectionsInStringBuilder(stringbuilder); + return stringbuilder.toString(); } - /**+ - * Returns the Throwable object that is the cause for the crash - * and Crash Report. + /** + * + Returns the Throwable object that is the cause for the crash and Crash + * Report. */ public Throwable getCrashCause() { return this.cause; } - /**+ - * Gets the various sections of the crash report into the given - * StringBuilder + /** + * + Returns the description of the Crash Report. + */ + public String getDescription() { + return this.description; + } + + /** + * + Gets the various sections of the crash report into the given StringBuilder */ public void getSectionsInStringBuilder(StringBuilder builder) { if ((this.stacktrace == null || this.stacktrace.length <= 0) && this.crashReportSections.size() > 0) { @@ -144,71 +183,15 @@ public class CrashReport { this.theReportCategory.appendToStringBuilder(builder); } - /**+ - * Gets the stack trace of the Throwable that caused this crash - * report, or if that fails, the cause .toString(). - */ - public String getCauseStackTraceOrString() { - StringBuilder stackTrace = new StringBuilder(); - - if ((this.cause.getMessage() == null || this.cause.getMessage().length() == 0) - && ((this.cause instanceof NullPointerException) || (this.cause instanceof StackOverflowError) - || (this.cause instanceof OutOfMemoryError))) { - stackTrace.append(this.cause.getClass().getName()).append(": "); - stackTrace.append(this.description).append('\n'); - } else { - stackTrace.append(this.cause.toString()).append('\n'); - } - - EagRuntime.getStackTrace(this.cause, (s) -> { - stackTrace.append("\tat ").append(s).append('\n'); - }); - - return stackTrace.toString(); - } - - /**+ - * Gets the complete report with headers, stack trace, and - * different sections as a string. - */ - public String getCompleteReport() { - StringBuilder stringbuilder = new StringBuilder(); - stringbuilder.append("---- Minecraft Crash Report ----\n"); - stringbuilder.append("// "); - stringbuilder.append(getWittyComment()); - stringbuilder.append("\n\n"); - stringbuilder.append("Time: "); - stringbuilder.append((new SimpleDateFormat()).format(new Date())); - stringbuilder.append("\n"); - stringbuilder.append("Description: "); - stringbuilder.append(this.description); - stringbuilder.append("\n\n"); - stringbuilder.append(this.getCauseStackTraceOrString()); - stringbuilder.append( - "\n\nA detailed walkthrough of the error, its code path and all known details is as follows:\n"); - - for (int i = 0; i < 87; ++i) { - stringbuilder.append("-"); - } - - stringbuilder.append("\n\n"); - this.getSectionsInStringBuilder(stringbuilder); - return stringbuilder.toString(); - } - - public CrashReportCategory getCategory() { - return this.theReportCategory; - } - - /**+ - * Creates a CrashReportCategory + /** + * + Creates a CrashReportCategory */ public CrashReportCategory makeCategory(String name) { return this.makeCategoryDepth(name, 1); } - /**+ - * Creates a CrashReportCategory for the given stack trace depth + /** + * + Creates a CrashReportCategory for the given stack trace depth */ public CrashReportCategory makeCategoryDepth(String categoryName, int stacktraceLength) { CrashReportCategory crashreportcategory = new CrashReportCategory(this, categoryName); @@ -249,24 +232,46 @@ public class CrashReport { return crashreportcategory; } - /**+ - * Gets a random witty comment for inclusion in this CrashReport + /** + * + Populates this crash report with initial information about the running + * server and operating system / java environment */ - private static String getWittyComment() { - return "eagler"; - } - - /**+ - * Creates a crash report for the exception - */ - public static CrashReport makeCrashReport(Throwable causeIn, String descriptionIn) { - CrashReport crashreport; - if (causeIn instanceof ReportedException) { - crashreport = ((ReportedException) causeIn).getCrashReport(); - } else { - crashreport = new CrashReport(descriptionIn, causeIn); + private void populateEnvironment() { + this.theReportCategory.addCrashSectionCallable("Minecraft Version", new Callable() { + public String call() { + return "1.8.8"; + } + }); + this.theReportCategory.addCrashSectionCallable("Operating System", new Callable() { + public String call() { + return System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ") version " + + System.getProperty("os.version"); + } + }); + this.theReportCategory.addCrashSectionCallable("Java Version", new Callable() { + public String call() { + return System.getProperty("java.version") + ", " + System.getProperty("java.vendor"); + } + }); + this.theReportCategory.addCrashSectionCallable("Java VM Version", new Callable() { + public String call() { + return System.getProperty("java.vm.name") + " (" + System.getProperty("java.vm.info") + "), " + + System.getProperty("java.vm.vendor"); + } + }); + if (EagRuntime.getPlatformType() != EnumPlatformType.JAVASCRIPT) { + this.theReportCategory.addCrashSectionCallable("Memory", new Callable() { + public String call() { + long i = EagRuntime.maxMemory(); + long j = EagRuntime.totalMemory(); + long k = EagRuntime.freeMemory(); + long l = i / 1024L / 1024L; + long i1 = j / 1024L / 1024L; + long j1 = k / 1024L / 1024L; + return k + " bytes (" + j1 + " MB) / " + j + " bytes (" + i1 + " MB) up to " + i + " bytes (" + l + + " MB)"; + } + }); } - - return crashreport; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/crash/CrashReportCategory.java b/src/game/java/net/minecraft/crash/CrashReportCategory.java index 024719f2..b01cdadb 100644 --- a/src/game/java/net/minecraft/crash/CrashReportCategory.java +++ b/src/game/java/net/minecraft/crash/CrashReportCategory.java @@ -11,40 +11,98 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CrashReportCategory { - private final CrashReport crashReport; - private final String name; - private final List children = Lists.newArrayList(); - private String[] stackTrace = new String[0]; + static class Entry { + private final String key; + private final String value; - public CrashReportCategory(CrashReport report, String name) { - this.crashReport = report; - this.name = name; + public Entry(String key, Object value) { + this.key = key; + if (value == null) { + this.value = "~~NULL~~"; + } else if (value instanceof Throwable) { + Throwable throwable = (Throwable) value; + this.value = "~~ERROR~~ " + throwable.getClass().getName() + ": " + throwable.getMessage(); + } else { + this.value = value.toString(); + } + + } + + public String getKey() { + return this.key; + } + + public String getValue() { + return this.value; + } } - public static String getCoordinateInfo(double x, double y, double z) { - return HString.format("%.2f,%.2f,%.2f - %s", new Object[] { Double.valueOf(x), Double.valueOf(y), - Double.valueOf(z), getCoordinateInfo(new BlockPos(x, y, z)) }); + public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final Block blockIn, + final int blockData) { + final int i = Block.getIdFromBlock(blockIn); + category.addCrashSectionCallable("Block type", new Callable() { + public String call() throws Exception { + try { + return HString.format("ID #%d (%s // %s)", new Object[] { Integer.valueOf(i), + blockIn.getUnlocalizedName(), blockIn.getClass().getName() }); + } catch (Throwable var2) { + return "ID #" + i; + } + } + }); + category.addCrashSectionCallable("Block data value", new Callable() { + public String call() throws Exception { + if (blockData < 0) { + return "Unknown? (Got " + blockData + ")"; + } else { + String s = HString.format("%4s", new Object[] { Integer.toBinaryString(blockData) }).replace(" ", + "0"); + return HString.format("%1$d / 0x%1$X / 0b%2$s", new Object[] { Integer.valueOf(blockData), s }); + } + } + }); + category.addCrashSectionCallable("Block location", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo(pos); + } + }); + } + + public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final IBlockState state) { + category.addCrashSectionCallable("Block", new Callable() { + public String call() throws Exception { + return state.toString(); + } + }); + category.addCrashSectionCallable("Block location", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo(pos); + } + }); } public static String getCoordinateInfo(BlockPos pos) { @@ -105,9 +163,35 @@ public class CrashReportCategory { return stringbuilder.toString(); } - /**+ - * Adds a Crashreport section with the given name with the value - * set to the result of the given Callable; + public static String getCoordinateInfo(double x, double y, double z) { + return HString.format("%.2f,%.2f,%.2f - %s", new Object[] { Double.valueOf(x), Double.valueOf(y), + Double.valueOf(z), getCoordinateInfo(new BlockPos(x, y, z)) }); + } + + private final CrashReport crashReport; + + private final String name; + + private final List children = Lists.newArrayList(); + + private String[] stackTrace = new String[0]; + + public CrashReportCategory(CrashReport report, String name) { + this.crashReport = report; + this.name = name; + } + + /** + * + Adds a Crashreport section with the given name with the given value + * (convered .toString()) + */ + public void addCrashSection(String sectionName, Object value) { + this.children.add(new CrashReportCategory.Entry(sectionName, value)); + } + + /** + * + Adds a Crashreport section with the given name with the value set to the + * result of the given Callable; */ public void addCrashSectionCallable(String sectionName, Callable callable) { try { @@ -118,73 +202,13 @@ public class CrashReportCategory { } - /**+ - * Adds a Crashreport section with the given name with the given - * value (convered .toString()) - */ - public void addCrashSection(String sectionName, Object value) { - this.children.add(new CrashReportCategory.Entry(sectionName, value)); - } - - /**+ - * Adds a Crashreport section with the given name with the given - * Throwable + /** + * + Adds a Crashreport section with the given name with the given Throwable */ public void addCrashSectionThrowable(String sectionName, Throwable throwable) { this.addCrashSection(sectionName, throwable); } - /**+ - * Resets our stack trace according to the current trace, - * pruning the deepest 3 entries. The parameter indicates how - * many additional deepest entries to prune. Returns the number - * of entries in the resulting pruned stack trace. - */ - public int getPrunedStackTrace(int size) { - String[] astacktraceelement = EagRuntime.getStackTraceElements(new Exception()); - if (astacktraceelement.length - 3 - size <= 0) { - return 0; - } else { - this.stackTrace = new String[astacktraceelement.length - 3 - size]; - System.arraycopy(astacktraceelement, 3 + size, this.stackTrace, 0, this.stackTrace.length); - return this.stackTrace.length; - } - } - - /**+ - * Do the deepest two elements of our saved stack trace match - * the given elements, in order from the deepest? - */ - public boolean firstTwoElementsOfStackTraceMatch(String s1, String s2) { - if (this.stackTrace.length != 0 && s1 != null) { - String stacktraceelement = this.stackTrace[0]; - if (s1.equals(stacktraceelement)) { - if (s2 != null != this.stackTrace.length > 1) { - return false; - } else if (s2 != null && !this.stackTrace[1].equals(s2)) { - return false; - } else { - this.stackTrace[0] = s1; - return true; - } - } else { - return false; - } - } else { - return false; - } - } - - /**+ - * Removes the given number entries from the bottom of the stack - * trace. - */ - public void trimStackTraceEntriesFromBottom(int amount) { - String[] astacktraceelement = new String[this.stackTrace.length - amount]; - System.arraycopy(this.stackTrace, 0, astacktraceelement, 0, astacktraceelement.length); - this.stackTrace = astacktraceelement; - } - public void appendToStringBuilder(StringBuilder builder) { builder.append("-- ").append(this.name).append(" --\n"); builder.append("Details:"); @@ -208,77 +232,56 @@ public class CrashReportCategory { } + /** + * + Do the deepest two elements of our saved stack trace match the given + * elements, in order from the deepest? + */ + public boolean firstTwoElementsOfStackTraceMatch(String s1, String s2) { + if (this.stackTrace.length != 0 && s1 != null) { + String stacktraceelement = this.stackTrace[0]; + if (s1.equals(stacktraceelement)) { + if (s2 != null != this.stackTrace.length > 1) { + return false; + } else if (s2 != null && !this.stackTrace[1].equals(s2)) { + return false; + } else { + this.stackTrace[0] = s1; + return true; + } + } else { + return false; + } + } else { + return false; + } + } + + /** + * + Resets our stack trace according to the current trace, pruning the deepest + * 3 entries. The parameter indicates how many additional deepest entries to + * prune. Returns the number of entries in the resulting pruned stack trace. + */ + public int getPrunedStackTrace(int size) { + String[] astacktraceelement = EagRuntime.getStackTraceElements(new Exception()); + if (astacktraceelement.length - 3 - size <= 0) { + return 0; + } else { + this.stackTrace = new String[astacktraceelement.length - 3 - size]; + System.arraycopy(astacktraceelement, 3 + size, this.stackTrace, 0, this.stackTrace.length); + return this.stackTrace.length; + } + } + public String[] getStackTrace() { return this.stackTrace; } - public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final Block blockIn, - final int blockData) { - final int i = Block.getIdFromBlock(blockIn); - category.addCrashSectionCallable("Block type", new Callable() { - public String call() throws Exception { - try { - return HString.format("ID #%d (%s // %s)", new Object[] { Integer.valueOf(i), - blockIn.getUnlocalizedName(), blockIn.getClass().getName() }); - } catch (Throwable var2) { - return "ID #" + i; - } - } - }); - category.addCrashSectionCallable("Block data value", new Callable() { - public String call() throws Exception { - if (blockData < 0) { - return "Unknown? (Got " + blockData + ")"; - } else { - String s = HString.format("%4s", new Object[] { Integer.toBinaryString(blockData) }).replace(" ", - "0"); - return HString.format("%1$d / 0x%1$X / 0b%2$s", new Object[] { Integer.valueOf(blockData), s }); - } - } - }); - category.addCrashSectionCallable("Block location", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo(pos); - } - }); - } - - public static void addBlockInfo(CrashReportCategory category, final BlockPos pos, final IBlockState state) { - category.addCrashSectionCallable("Block", new Callable() { - public String call() throws Exception { - return state.toString(); - } - }); - category.addCrashSectionCallable("Block location", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo(pos); - } - }); - } - - static class Entry { - private final String key; - private final String value; - - public Entry(String key, Object value) { - this.key = key; - if (value == null) { - this.value = "~~NULL~~"; - } else if (value instanceof Throwable) { - Throwable throwable = (Throwable) value; - this.value = "~~ERROR~~ " + throwable.getClass().getName() + ": " + throwable.getMessage(); - } else { - this.value = value.toString(); - } - - } - - public String getKey() { - return this.key; - } - - public String getValue() { - return this.value; - } + /** + * + Removes the given number entries from the bottom of the stack trace. + */ + public void trimStackTraceEntriesFromBottom(int amount) { + String[] astacktraceelement = new String[this.stackTrace.length - amount]; + System.arraycopy(this.stackTrace, 0, astacktraceelement, 0, astacktraceelement.length); + this.stackTrace = astacktraceelement; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/creativetab/CreativeTabs.java b/src/game/java/net/minecraft/creativetab/CreativeTabs.java index fec83a69..2bd517a7 100644 --- a/src/game/java/net/minecraft/creativetab/CreativeTabs.java +++ b/src/game/java/net/minecraft/creativetab/CreativeTabs.java @@ -11,41 +11,44 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class CreativeTabs { - public static final CreativeTabs[] creativeTabArray = new CreativeTabs[12]; + public static final CreativeTabs[] creativeTabArray = new CreativeTabs[13]; public static final CreativeTabs tabBlock = new CreativeTabs(0, "buildingBlocks") { public Item getTabIconItem() { return Item.getItemFromBlock(Blocks.brick_block); } }; public static final CreativeTabs tabDecorations = new CreativeTabs(1, "decorations") { - public Item getTabIconItem() { - return Item.getItemFromBlock(Blocks.double_plant); - } - public int getIconItemDamage() { return BlockDoublePlant.EnumPlantType.PAEONIA.getMeta(); } + + public Item getTabIconItem() { + return Item.getItemFromBlock(Blocks.double_plant); + } }; public static final CreativeTabs tabRedstone = new CreativeTabs(2, "redstone") { public Item getTabIconItem() { @@ -100,16 +103,20 @@ public abstract class CreativeTabs { return Item.getItemFromBlock(Blocks.chest); } }).setBackgroundImageName("inventory.png").setNoScrollbar().setNoTitle(); + public static final CreativeTabs tabStarlike = new CreativeTabs(12, "starlike") { + public Item getTabIconItem() { + return null; + } + }; private final int tabIndex; private final String tabLabel; - /**+ - * Texture to use. + /** + * + Texture to use. */ private String theTexture = "items.png"; private boolean hasScrollbar = true; - /**+ - * Whether to draw the title in the foreground of the creative - * GUI + /** + * + Whether to draw the title in the foreground of the creative GUI */ private boolean drawTitle = true; private EnumEnchantmentType[] enchantmentTypes; @@ -121,125 +128,9 @@ public abstract class CreativeTabs { creativeTabArray[index] = this; } - public int getTabIndex() { - return this.tabIndex; - } - - public String getTabLabel() { - return this.tabLabel; - } - - /**+ - * Gets the translated Label. - */ - public String getTranslatedTabLabel() { - return "itemGroup." + this.getTabLabel(); - } - - public ItemStack getIconItemStack() { - if (this.iconItemStack == null) { - this.iconItemStack = new ItemStack(this.getTabIconItem(), 1, this.getIconItemDamage()); - } - - return this.iconItemStack; - } - - public abstract Item getTabIconItem(); - - public int getIconItemDamage() { - return 0; - } - - public String getBackgroundImageName() { - return this.theTexture; - } - - public CreativeTabs setBackgroundImageName(String texture) { - this.theTexture = texture; - return this; - } - - public boolean drawInForegroundOfTab() { - return this.drawTitle; - } - - public CreativeTabs setNoTitle() { - this.drawTitle = false; - return this; - } - - public boolean shouldHidePlayerInventory() { - return this.hasScrollbar; - } - - public CreativeTabs setNoScrollbar() { - this.hasScrollbar = false; - return this; - } - - /**+ - * returns index % 6 - */ - public int getTabColumn() { - return this.tabIndex % 6; - } - - /**+ - * returns tabIndex < 6 - */ - public boolean isTabInFirstRow() { - return this.tabIndex < 6; - } - - /**+ - * Returns the enchantment types relevant to this tab - */ - public EnumEnchantmentType[] getRelevantEnchantmentTypes() { - return this.enchantmentTypes; - } - - /**+ - * Sets the enchantment types for populating this tab with - * enchanting books - */ - public CreativeTabs setRelevantEnchantmentTypes(EnumEnchantmentType... types) { - this.enchantmentTypes = types; - return this; - } - - public boolean hasRelevantEnchantmentType(EnumEnchantmentType enchantmentType) { - if (this.enchantmentTypes == null) { - return false; - } else { - for (int i = 0; i < this.enchantmentTypes.length; ++i) { - if (this.enchantmentTypes[i] == enchantmentType) { - return true; - } - } - - return false; - } - } - - /**+ - * only shows items which have tabToDisplayOn == this - */ - public void displayAllReleventItems(List parList) { - for (Item item : Item.itemRegistry) { - if (item != null && item.getCreativeTab() == this) { - item.getSubItems(item, this, parList); - } - } - - if (this.getRelevantEnchantmentTypes() != null) { - this.addEnchantmentBooksToList(parList, this.getRelevantEnchantmentTypes()); - } - - } - - /**+ - * Adds the enchantment books from the supplied - * EnumEnchantmentType to the given list. + /** + * + Adds the enchantment books from the supplied EnumEnchantmentType to the + * given list. */ public void addEnchantmentBooksToList(List itemList, EnumEnchantmentType... enchantmentType) { for (int i = 0; i < Enchantment.enchantmentsBookList.length; ++i) { @@ -261,4 +152,119 @@ public abstract class CreativeTabs { } } + + /** + * + only shows items which have tabToDisplayOn == this + */ + public void displayAllReleventItems(List parList) { + for (Item item : Item.itemRegistry) { + if (item != null && item.getCreativeTab() == this) { + item.getSubItems(item, this, parList); + } + } + + if (this.getRelevantEnchantmentTypes() != null) { + this.addEnchantmentBooksToList(parList, this.getRelevantEnchantmentTypes()); + } + + } + + public boolean drawInForegroundOfTab() { + return this.drawTitle; + } + + public String getBackgroundImageName() { + return this.theTexture; + } + + public int getIconItemDamage() { + return 0; + } + + public ItemStack getIconItemStack() { + if (this.iconItemStack == null) { + this.iconItemStack = new ItemStack(this.getTabIconItem(), 1, this.getIconItemDamage()); + } + + return this.iconItemStack; + } + + /** + * + Returns the enchantment types relevant to this tab + */ + public EnumEnchantmentType[] getRelevantEnchantmentTypes() { + return this.enchantmentTypes; + } + + /** + * + returns index % 6 + */ + public int getTabColumn() { + return this.tabIndex % 6; + } + + public abstract Item getTabIconItem(); + + public int getTabIndex() { + return this.tabIndex; + } + + public String getTabLabel() { + return this.tabLabel; + } + + /** + * + Gets the translated Label. + */ + public String getTranslatedTabLabel() { + return "itemGroup." + this.getTabLabel(); + } + + public boolean hasRelevantEnchantmentType(EnumEnchantmentType enchantmentType) { + if (this.enchantmentTypes == null) { + return false; + } else { + for (int i = 0; i < this.enchantmentTypes.length; ++i) { + if (this.enchantmentTypes[i] == enchantmentType) { + return true; + } + } + + return false; + } + } + + /** + * + returns tabIndex < 6 + */ + public boolean isTabInFirstRow() { + return this.tabIndex < 6; + } + + public CreativeTabs setBackgroundImageName(String texture) { + this.theTexture = texture; + return this; + } + + public CreativeTabs setNoScrollbar() { + this.hasScrollbar = false; + return this; + } + + public CreativeTabs setNoTitle() { + this.drawTitle = false; + return this; + } + + /** + * + Sets the enchantment types for populating this tab with enchanting books + */ + public CreativeTabs setRelevantEnchantmentTypes(EnumEnchantmentType... types) { + this.enchantmentTypes = types; + return this; + } + + public boolean shouldHidePlayerInventory() { + return this.hasScrollbar; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/dispenser/BehaviorDefaultDispenseItem.java b/src/game/java/net/minecraft/dispenser/BehaviorDefaultDispenseItem.java index 92aa888b..605b01db 100644 --- a/src/game/java/net/minecraft/dispenser/BehaviorDefaultDispenseItem.java +++ b/src/game/java/net/minecraft/dispenser/BehaviorDefaultDispenseItem.java @@ -6,49 +6,30 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BehaviorDefaultDispenseItem implements IBehaviorDispenseItem { - /**+ - * Dispenses the specified ItemStack from a dispenser. - */ - public final ItemStack dispense(IBlockSource source, ItemStack stack) { - ItemStack itemstack = this.dispenseStack(source, stack); - this.playDispenseSound(source); - this.spawnDispenseParticles(source, BlockDispenser.getFacing(source.getBlockMetadata())); - return itemstack; - } - - /**+ - * Dispense the specified stack, play the dispense sound and - * spawn particles. - */ - protected ItemStack dispenseStack(IBlockSource iblocksource, ItemStack itemstack) { - EnumFacing enumfacing = BlockDispenser.getFacing(iblocksource.getBlockMetadata()); - IPosition iposition = BlockDispenser.getDispensePosition(iblocksource); - ItemStack itemstack1 = itemstack.splitStack(1); - doDispense(iblocksource.getWorld(), itemstack1, 6, enumfacing, iposition); - return itemstack; - } - public static void doDispense(World worldIn, ItemStack stack, int speed, EnumFacing facing, IPosition position) { double d0 = position.getX(); double d1 = position.getY(); @@ -70,22 +51,43 @@ public class BehaviorDefaultDispenseItem implements IBehaviorDispenseItem { worldIn.spawnEntityInWorld(entityitem); } - /**+ - * Play the dispense sound from the specified block. + /** + * + Dispenses the specified ItemStack from a dispenser. */ - protected void playDispenseSound(IBlockSource iblocksource) { - iblocksource.getWorld().playAuxSFX(1000, iblocksource.getBlockPos(), 0); + public final ItemStack dispense(IBlockSource source, ItemStack stack) { + ItemStack itemstack = this.dispenseStack(source, stack); + this.playDispenseSound(source); + this.spawnDispenseParticles(source, BlockDispenser.getFacing(source.getBlockMetadata())); + return itemstack; } - /**+ - * Order clients to display dispense particles from the - * specified block and facing. + /** + * + Dispense the specified stack, play the dispense sound and spawn particles. */ - protected void spawnDispenseParticles(IBlockSource source, EnumFacing facingIn) { - source.getWorld().playAuxSFX(2000, source.getBlockPos(), this.func_82488_a(facingIn)); + protected ItemStack dispenseStack(IBlockSource iblocksource, ItemStack itemstack) { + EnumFacing enumfacing = BlockDispenser.getFacing(iblocksource.getBlockMetadata()); + IPosition iposition = BlockDispenser.getDispensePosition(iblocksource); + ItemStack itemstack1 = itemstack.splitStack(1); + doDispense(iblocksource.getWorld(), itemstack1, 6, enumfacing, iposition); + return itemstack; } private int func_82488_a(EnumFacing facingIn) { return facingIn.getFrontOffsetX() + 1 + (facingIn.getFrontOffsetZ() + 1) * 3; } + + /** + * + Play the dispense sound from the specified block. + */ + protected void playDispenseSound(IBlockSource iblocksource) { + iblocksource.getWorld().playAuxSFX(1000, iblocksource.getBlockPos(), 0); + } + + /** + * + Order clients to display dispense particles from the specified block and + * facing. + */ + protected void spawnDispenseParticles(IBlockSource source, EnumFacing facingIn) { + source.getWorld().playAuxSFX(2000, source.getBlockPos(), this.func_82488_a(facingIn)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/dispenser/BehaviorProjectileDispense.java b/src/game/java/net/minecraft/dispenser/BehaviorProjectileDispense.java index 0d1f70e8..14772010 100644 --- a/src/game/java/net/minecraft/dispenser/BehaviorProjectileDispense.java +++ b/src/game/java/net/minecraft/dispenser/BehaviorProjectileDispense.java @@ -7,30 +7,32 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BehaviorProjectileDispense extends BehaviorDefaultDispenseItem { - /**+ - * Dispense the specified stack, play the dispense sound and - * spawn particles. + /** + * + Dispense the specified stack, play the dispense sound and spawn particles. */ public ItemStack dispenseStack(IBlockSource iblocksource, ItemStack itemstack) { World world = iblocksource.getWorld(); @@ -45,15 +47,6 @@ public abstract class BehaviorProjectileDispense extends BehaviorDefaultDispense return itemstack; } - /**+ - * Play the dispense sound from the specified block. - */ - protected void playDispenseSound(IBlockSource iblocksource) { - iblocksource.getWorld().playAuxSFX(1002, iblocksource.getBlockPos(), 0); - } - - protected abstract IProjectile getProjectileEntity(World var1, IPosition var2); - protected float func_82498_a() { return 6.0F; } @@ -61,4 +54,13 @@ public abstract class BehaviorProjectileDispense extends BehaviorDefaultDispense protected float func_82500_b() { return 1.1F; } + + protected abstract IProjectile getProjectileEntity(World var1, IPosition var2); + + /** + * + Play the dispense sound from the specified block. + */ + protected void playDispenseSound(IBlockSource iblocksource) { + iblocksource.getWorld().playAuxSFX(1002, iblocksource.getBlockPos(), 0); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/dispenser/IBehaviorDispenseItem.java b/src/game/java/net/minecraft/dispenser/IBehaviorDispenseItem.java index 861d9ef4..a8caa058 100644 --- a/src/game/java/net/minecraft/dispenser/IBehaviorDispenseItem.java +++ b/src/game/java/net/minecraft/dispenser/IBehaviorDispenseItem.java @@ -2,38 +2,41 @@ package net.minecraft.dispenser; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IBehaviorDispenseItem { IBehaviorDispenseItem itemDispenseBehaviorProvider = new IBehaviorDispenseItem() { - /**+ - * Dispenses the specified ItemStack from a dispenser. + /** + * + Dispenses the specified ItemStack from a dispenser. */ public ItemStack dispense(IBlockSource var1, ItemStack itemstack) { return itemstack; } }; - /**+ - * Dispenses the specified ItemStack from a dispenser. + /** + * + Dispenses the specified ItemStack from a dispenser. */ ItemStack dispense(IBlockSource var1, ItemStack var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/dispenser/IBlockSource.java b/src/game/java/net/minecraft/dispenser/IBlockSource.java index ff30a6c2..257d702a 100644 --- a/src/game/java/net/minecraft/dispenser/IBlockSource.java +++ b/src/game/java/net/minecraft/dispenser/IBlockSource.java @@ -3,36 +3,39 @@ package net.minecraft.dispenser; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IBlockSource extends ILocatableSource { + int getBlockMetadata(); + + BlockPos getBlockPos(); + + T getBlockTileEntity(); + double getX(); double getY(); double getZ(); - - BlockPos getBlockPos(); - - int getBlockMetadata(); - - T getBlockTileEntity(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/dispenser/ILocatableSource.java b/src/game/java/net/minecraft/dispenser/ILocatableSource.java index 5c05413b..0ea918fa 100644 --- a/src/game/java/net/minecraft/dispenser/ILocatableSource.java +++ b/src/game/java/net/minecraft/dispenser/ILocatableSource.java @@ -1,21 +1,24 @@ package net.minecraft.dispenser; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/dispenser/ILocation.java b/src/game/java/net/minecraft/dispenser/ILocation.java index fa08a189..540ea7d6 100644 --- a/src/game/java/net/minecraft/dispenser/ILocation.java +++ b/src/game/java/net/minecraft/dispenser/ILocation.java @@ -2,22 +2,25 @@ package net.minecraft.dispenser; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/dispenser/IPosition.java b/src/game/java/net/minecraft/dispenser/IPosition.java index 6cfabc2d..4e3f6a8d 100644 --- a/src/game/java/net/minecraft/dispenser/IPosition.java +++ b/src/game/java/net/minecraft/dispenser/IPosition.java @@ -1,21 +1,24 @@ package net.minecraft.dispenser; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/dispenser/PositionImpl.java b/src/game/java/net/minecraft/dispenser/PositionImpl.java index 63a69670..49f55a66 100644 --- a/src/game/java/net/minecraft/dispenser/PositionImpl.java +++ b/src/game/java/net/minecraft/dispenser/PositionImpl.java @@ -1,21 +1,24 @@ package net.minecraft.dispenser; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/enchantment/Enchantment.java b/src/game/java/net/minecraft/enchantment/Enchantment.java index dff247e3..2157cc34 100644 --- a/src/game/java/net/minecraft/enchantment/Enchantment.java +++ b/src/game/java/net/minecraft/enchantment/Enchantment.java @@ -15,22 +15,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,23 +44,23 @@ public abstract class Enchantment { private static final Map locationEnchantments = Maps.newHashMap(); public static final Enchantment protection = new EnchantmentProtection(0, new ResourceLocation("protection"), 10, 0); - /**+ - * Protection against fire + /** + * + Protection against fire */ public static final Enchantment fireProtection = new EnchantmentProtection(1, new ResourceLocation("fire_protection"), 5, 1); public static final Enchantment featherFalling = new EnchantmentProtection(2, new ResourceLocation("feather_falling"), 5, 2); - /**+ - * Protection against explosions + /** + * + Protection against explosions */ public static final Enchantment blastProtection = new EnchantmentProtection(3, new ResourceLocation("blast_protection"), 2, 3); public static final Enchantment projectileProtection = new EnchantmentProtection(4, new ResourceLocation("projectile_protection"), 5, 4); public static final Enchantment respiration = new EnchantmentOxygen(5, new ResourceLocation("respiration"), 2); - /**+ - * Increases underwater mining rate + /** + * + Increases underwater mining rate */ public static final Enchantment aquaAffinity = new EnchantmentWaterWorker(6, new ResourceLocation("aqua_affinity"), 2); @@ -69,70 +72,95 @@ public abstract class Enchantment { public static final Enchantment baneOfArthropods = new EnchantmentDamage(18, new ResourceLocation("bane_of_arthropods"), 5, 2); public static final Enchantment knockback = new EnchantmentKnockback(19, new ResourceLocation("knockback"), 5); - /**+ - * Lights mobs on fire + /** + * + Lights mobs on fire */ public static final Enchantment fireAspect = new EnchantmentFireAspect(20, new ResourceLocation("fire_aspect"), 2); - /**+ - * Mobs have a chance to drop more loot + /** + * + Mobs have a chance to drop more loot */ public static final Enchantment looting = new EnchantmentLootBonus(21, new ResourceLocation("looting"), 2, EnumEnchantmentType.WEAPON); - /**+ - * Faster resource gathering while in use + /** + * + Faster resource gathering while in use */ public static final Enchantment efficiency = new EnchantmentDigging(32, new ResourceLocation("efficiency"), 10); - /**+ - * Blocks mined will drop themselves, even if it should drop - * something else (e.g. stone will drop stone, not cobblestone) + /** + * + Blocks mined will drop themselves, even if it should drop something else + * (e.g. stone will drop stone, not cobblestone) */ public static final Enchantment silkTouch = new EnchantmentUntouching(33, new ResourceLocation("silk_touch"), 1); - /**+ - * Sometimes, the tool's durability will not be spent when the - * tool is used + /** + * + Sometimes, the tool's durability will not be spent when the tool is used */ public static final Enchantment unbreaking = new EnchantmentDurability(34, new ResourceLocation("unbreaking"), 5); - /**+ - * Can multiply the drop rate of items from blocks + /** + * + Can multiply the drop rate of items from blocks */ public static final Enchantment fortune = new EnchantmentLootBonus(35, new ResourceLocation("fortune"), 2, EnumEnchantmentType.DIGGER); - /**+ - * Power enchantment for bows, add's extra damage to arrows. + /** + * + Power enchantment for bows, add's extra damage to arrows. */ public static final Enchantment power = new EnchantmentArrowDamage(48, new ResourceLocation("power"), 10); - /**+ - * Knockback enchantments for bows, the arrows will knockback - * the target when hit. + /** + * + Knockback enchantments for bows, the arrows will knockback the target when + * hit. */ public static final Enchantment punch = new EnchantmentArrowKnockback(49, new ResourceLocation("punch"), 2); - /**+ - * Flame enchantment for bows. Arrows fired by the bow will be - * on fire. Any target hit will also set on fire. + /** + * + Flame enchantment for bows. Arrows fired by the bow will be on fire. Any + * target hit will also set on fire. */ public static final Enchantment flame = new EnchantmentArrowFire(50, new ResourceLocation("flame"), 2); - /**+ - * Infinity enchantment for bows. The bow will not consume - * arrows anymore, but will still required at least one arrow on - * inventory use the bow. + /** + * + Infinity enchantment for bows. The bow will not consume arrows anymore, but + * will still required at least one arrow on inventory use the bow. */ public static final Enchantment infinity = new EnchantmentArrowInfinite(51, new ResourceLocation("infinity"), 1); public static final Enchantment luckOfTheSea = new EnchantmentLootBonus(61, new ResourceLocation("luck_of_the_sea"), 2, EnumEnchantmentType.FISHING_ROD); public static final Enchantment lure = new EnchantmentFishingSpeed(62, new ResourceLocation("lure"), 2, EnumEnchantmentType.FISHING_ROD); - public final int effectId; - private final int weight; - public EnumEnchantmentType type; - protected String name; + static { + ArrayList arraylist = Lists.newArrayList(); - /**+ - * Retrieves an Enchantment from the enchantmentsList + for (int i = 0; i < enchantmentsList.length; ++i) { + Enchantment enchantment = enchantmentsList[i]; + if (enchantment != null) { + arraylist.add(enchantment); + } + } + + enchantmentsBookList = (Enchantment[]) arraylist.toArray(new Enchantment[arraylist.size()]); + } + + public static Set func_181077_c() { + return locationEnchantments.keySet(); + } + + /** + * + Retrieves an Enchantment from the enchantmentsList */ public static Enchantment getEnchantmentById(int enchID) { return enchID >= 0 && enchID < enchantmentsList.length ? enchantmentsList[enchID] : null; } + /** + * + Retrieves an enchantment by using its location name. + */ + public static Enchantment getEnchantmentByLocation(String location) { + return (Enchantment) locationEnchantments.get(new ResourceLocation(location)); + } + + public final int effectId; + + private final int weight; + + public EnumEnchantmentType type; + + protected String name; + protected Enchantment(int enchID, ResourceLocation enchName, int enchWeight, EnumEnchantmentType enchType) { this.effectId = enchID; this.weight = enchWeight; @@ -145,139 +173,111 @@ public abstract class Enchantment { } } - /**+ - * Retrieves an enchantment by using its location name. - */ - public static Enchantment getEnchantmentByLocation(String location) { - return (Enchantment) locationEnchantments.get(new ResourceLocation(location)); - } - - public static Set func_181077_c() { - return locationEnchantments.keySet(); - } - - /**+ - * Retrieves the weight value of an Enchantment. This weight - * value is used within vanilla to determine how rare an - * enchantment is. - */ - public int getWeight() { - return this.weight; - } - - /**+ - * Returns the minimum level that the enchantment can have. - */ - public int getMinLevel() { - return 1; - } - - /**+ - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() { - return 1; - } - - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 1 + i * 10; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. - */ - public int getMaxEnchantability(int i) { - return this.getMinEnchantability(i) + 5; - } - - /**+ - * Calculates the damage protection of the enchantment based on - * level and damage source passed. - */ - public int calcModifierDamage(int level, DamageSource source) { - return 0; - } - - /**+ - * Calculates the additional damage that will be dealt by an - * item with this enchantment. This alternative to - * calcModifierDamage is sensitive to the targets - * EnumCreatureAttribute. + /** + * + Calculates the additional damage that will be dealt by an item with this + * enchantment. This alternative to calcModifierDamage is sensitive to the + * targets EnumCreatureAttribute. */ public float calcDamageByCreature(int var1, EnumCreatureAttribute var2) { return 0.0F; } - /**+ - * Determines if the enchantment passed can be applyied together - * with this enchantment. + /** + * + Calculates the damage protection of the enchantment based on level and + * damage source passed. + */ + public int calcModifierDamage(int level, DamageSource source) { + return 0; + } + + /** + * + Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack itemstack) { + return this.type.canEnchantItem(itemstack.getItem()); + } + + /** + * + Determines if the enchantment passed can be applyied together with this + * enchantment. */ public boolean canApplyTogether(Enchantment enchantment) { return this != enchantment; } - /**+ - * Sets the enchantment name + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ - public Enchantment setName(String enchName) { - this.name = enchName; - return this; + public int getMaxEnchantability(int i) { + return this.getMinEnchantability(i) + 5; } - /**+ - * Return the name of key in translation table of this - * enchantment. + /** + * + Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() { + return 1; + } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 1 + i * 10; + } + + /** + * + Returns the minimum level that the enchantment can have. + */ + public int getMinLevel() { + return 1; + } + + /** + * + Return the name of key in translation table of this enchantment. */ public String getName() { return "enchantment." + this.name; } - /**+ - * Returns the correct traslated name of the enchantment and the - * level in roman numbers. + /** + * + Returns the correct traslated name of the enchantment and the level in + * roman numbers. */ public String getTranslatedName(int level) { String s = StatCollector.translateToLocal(this.getName()); return s + " " + StatCollector.translateToLocal("enchantment.level." + level); } - /**+ - * Determines if this enchantment can be applied to a specific - * ItemStack. + /** + * + Retrieves the weight value of an Enchantment. This weight value is used + * within vanilla to determine how rare an enchantment is. */ - public boolean canApply(ItemStack itemstack) { - return this.type.canEnchantItem(itemstack.getItem()); + public int getWeight() { + return this.weight; } - /**+ - * Called whenever a mob is damaged with an item that has this - * enchantment on it. + /** + * + Called whenever a mob is damaged with an item that has this enchantment on + * it. */ public void onEntityDamaged(EntityLivingBase var1, Entity var2, int var3) { } - /**+ - * Whenever an entity that has this enchantment on one of its - * associated items is damaged this method will be called. + /** + * + Whenever an entity that has this enchantment on one of its associated items + * is damaged this method will be called. */ public void onUserHurt(EntityLivingBase user, Entity attacker, int level) { } - static { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < enchantmentsList.length; ++i) { - Enchantment enchantment = enchantmentsList[i]; - if (enchantment != null) { - arraylist.add(enchantment); - } - } - - enchantmentsBookList = (Enchantment[]) arraylist.toArray(new Enchantment[arraylist.size()]); + /** + * + Sets the enchantment name + */ + public Enchantment setName(String enchName) { + this.name = enchName; + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentArrowDamage.java b/src/game/java/net/minecraft/enchantment/EnchantmentArrowDamage.java index 40b75cc0..56eb8195 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentArrowDamage.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentArrowDamage.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentArrowDamage extends Enchantment { this.setName("arrowDamage"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) { - return 1 + (enchantmentLevel - 1) * 10; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int enchantmentLevel) { return this.getMinEnchantability(enchantmentLevel) + 15; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 5; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int enchantmentLevel) { + return 1 + (enchantmentLevel - 1) * 10; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentArrowFire.java b/src/game/java/net/minecraft/enchantment/EnchantmentArrowFire.java index 998c6dd8..ba44cb87 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentArrowFire.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentArrowFire.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentArrowFire extends Enchantment { this.setName("arrowFire"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int var1) { - return 20; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int var1) { return 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 1; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int var1) { + return 20; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentArrowInfinite.java b/src/game/java/net/minecraft/enchantment/EnchantmentArrowInfinite.java index 81dca09f..0eea3f5c 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentArrowInfinite.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentArrowInfinite.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentArrowInfinite extends Enchantment { this.setName("arrowInfinite"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int var1) { - return 20; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int var1) { return 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 1; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int var1) { + return 20; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentArrowKnockback.java b/src/game/java/net/minecraft/enchantment/EnchantmentArrowKnockback.java index 537a6789..d8f18a2a 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentArrowKnockback.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentArrowKnockback.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentArrowKnockback extends Enchantment { this.setName("arrowKnockback"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 12 + (i - 1) * 20; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return this.getMinEnchantability(i) + 25; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 2; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 12 + (i - 1) * 20; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentDamage.java b/src/game/java/net/minecraft/enchantment/EnchantmentDamage.java index 259454a6..a0d8af66 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentDamage.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentDamage.java @@ -9,44 +9,47 @@ import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EnchantmentDamage extends Enchantment { - /**+ - * Holds the name to be translated of each protection type. + /** + * + Holds the name to be translated of each protection type. */ private static final String[] protectionName = new String[] { "all", "undead", "arthropods" }; - /**+ - * Holds the base factor of enchantability needed to be able to - * use the enchant. + /** + * + Holds the base factor of enchantability needed to be able to use the + * enchant. */ private static final int[] baseEnchantability = new int[] { 1, 5, 5 }; - /**+ - * Holds how much each level increased the enchantability factor - * to be able to use this enchant. + /** + * + Holds how much each level increased the enchantability factor to be able to + * use this enchant. */ private static final int[] levelEnchantability = new int[] { 11, 8, 8 }; - /**+ - * Used on the formula of base enchantability, this is the - * 'window' factor of values to be able to use thing enchant. + /** + * + Used on the formula of base enchantability, this is the 'window' factor of + * values to be able to use thing enchant. */ private static final int[] thresholdEnchantability = new int[] { 20, 20, 20 }; public final int damageType; @@ -56,34 +59,10 @@ public class EnchantmentDamage extends Enchantment { this.damageType = classification; } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return baseEnchantability[this.damageType] + (i - 1) * levelEnchantability[this.damageType]; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. - */ - public int getMaxEnchantability(int i) { - return this.getMinEnchantability(i) + thresholdEnchantability[this.damageType]; - } - - /**+ - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() { - return 5; - } - - /**+ - * Calculates the additional damage that will be dealt by an - * item with this enchantment. This alternative to - * calcModifierDamage is sensitive to the targets - * EnumCreatureAttribute. + /** + * + Calculates the additional damage that will be dealt by an item with this + * enchantment. This alternative to calcModifierDamage is sensitive to the + * targets EnumCreatureAttribute. */ public float calcDamageByCreature(int level, EnumCreatureAttribute creatureType) { return this.damageType == 0 ? (float) level * 1.25F @@ -93,33 +72,54 @@ public class EnchantmentDamage extends Enchantment { : 0.0F)); } - /**+ - * Return the name of key in translation table of this - * enchantment. - */ - public String getName() { - return "enchantment.damage." + protectionName[this.damageType]; - } - - /**+ - * Determines if the enchantment passed can be applyied together - * with this enchantment. - */ - public boolean canApplyTogether(Enchantment ench) { - return !(ench instanceof EnchantmentDamage); - } - - /**+ - * Determines if this enchantment can be applied to a specific - * ItemStack. + /** + * + Determines if this enchantment can be applied to a specific ItemStack. */ public boolean canApply(ItemStack stack) { return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); } - /**+ - * Called whenever a mob is damaged with an item that has this - * enchantment on it. + /** + * + Determines if the enchantment passed can be applyied together with this + * enchantment. + */ + public boolean canApplyTogether(Enchantment ench) { + return !(ench instanceof EnchantmentDamage); + } + + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. + */ + public int getMaxEnchantability(int i) { + return this.getMinEnchantability(i) + thresholdEnchantability[this.damageType]; + } + + /** + * + Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() { + return 5; + } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return baseEnchantability[this.damageType] + (i - 1) * levelEnchantability[this.damageType]; + } + + /** + * + Return the name of key in translation table of this enchantment. + */ + public String getName() { + return "enchantment.damage." + protectionName[this.damageType]; + } + + /** + * + Called whenever a mob is damaged with an item that has this enchantment on + * it. */ public void onEntityDamaged(EntityLivingBase user, Entity target, int level) { if (target instanceof EntityLivingBase) { diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentData.java b/src/game/java/net/minecraft/enchantment/EnchantmentData.java index cfb4e0af..7a4ada78 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentData.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentData.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.WeightedRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentDigging.java b/src/game/java/net/minecraft/enchantment/EnchantmentDigging.java index 88b5ed38..a83f5489 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentDigging.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentDigging.java @@ -4,22 +4,25 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,34 +33,33 @@ public class EnchantmentDigging extends Enchantment { this.setName("digging"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. + /** + * + Determines if this enchantment can be applied to a specific ItemStack. */ - public int getMinEnchantability(int i) { - return 1 + 10 * (i - 1); + public boolean canApply(ItemStack itemstack) { + return itemstack.getItem() == Items.shears ? true : super.canApply(itemstack); } - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return super.getMinEnchantability(i) + 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 5; } - /**+ - * Determines if this enchantment can be applied to a specific - * ItemStack. + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. */ - public boolean canApply(ItemStack itemstack) { - return itemstack.getItem() == Items.shears ? true : super.canApply(itemstack); + public int getMinEnchantability(int i) { + return 1 + 10 * (i - 1); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentDurability.java b/src/game/java/net/minecraft/enchantment/EnchantmentDurability.java index 347b3e9f..282743ea 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentDurability.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentDurability.java @@ -1,78 +1,78 @@ package net.minecraft.enchantment; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EnchantmentDurability extends Enchantment { - protected EnchantmentDurability(int enchID, ResourceLocation enchName, int enchWeight) { - super(enchID, enchName, enchWeight, EnumEnchantmentType.BREAKABLE); - this.setName("durability"); - } - - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 5 + (i - 1) * 8; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. - */ - public int getMaxEnchantability(int i) { - return super.getMinEnchantability(i) + 50; - } - - /**+ - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() { - return 3; - } - - /**+ - * Determines if this enchantment can be applied to a specific - * ItemStack. - */ - public boolean canApply(ItemStack itemstack) { - return itemstack.isItemStackDamageable() ? true : super.canApply(itemstack); - } - - /**+ - * Used by ItemStack.attemptDamageItem. Randomly determines if a - * point of damage should be negated using the enchantment level - * (par1). If the ItemStack is Armor then there is a flat 60% - * chance for damage to be negated no matter the enchantment - * level, otherwise there is a 1-(par/1) chance for damage to be + /** + * + Used by ItemStack.attemptDamageItem. Randomly determines if a point of + * damage should be negated using the enchantment level (par1). If the ItemStack + * is Armor then there is a flat 60% chance for damage to be negated no matter + * the enchantment level, otherwise there is a 1-(par/1) chance for damage to be * negated. */ public static boolean negateDamage(ItemStack parItemStack, int parInt1, EaglercraftRandom parRandom) { return parItemStack.getItem() instanceof ItemArmor && parRandom.nextFloat() < 0.6F ? false : parRandom.nextInt(parInt1 + 1) > 0; } + + protected EnchantmentDurability(int enchID, ResourceLocation enchName, int enchWeight) { + super(enchID, enchName, enchWeight, EnumEnchantmentType.BREAKABLE); + this.setName("durability"); + } + + /** + * + Determines if this enchantment can be applied to a specific ItemStack. + */ + public boolean canApply(ItemStack itemstack) { + return itemstack.isItemStackDamageable() ? true : super.canApply(itemstack); + } + + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. + */ + public int getMaxEnchantability(int i) { + return super.getMinEnchantability(i) + 50; + } + + /** + * + Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() { + return 3; + } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 5 + (i - 1) * 8; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentFireAspect.java b/src/game/java/net/minecraft/enchantment/EnchantmentFireAspect.java index e565b65b..74872289 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentFireAspect.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentFireAspect.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentFireAspect extends Enchantment { this.setName("fire"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 10 + 20 * (i - 1); - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return super.getMinEnchantability(i) + 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 2; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 10 + 20 * (i - 1); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentFishingSpeed.java b/src/game/java/net/minecraft/enchantment/EnchantmentFishingSpeed.java index 5dc1d304..ccecf478 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentFishingSpeed.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentFishingSpeed.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,26 +32,26 @@ public class EnchantmentFishingSpeed extends Enchantment { this.setName("fishingSpeed"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 15 + (i - 1) * 9; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return super.getMinEnchantability(i) + 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 3; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 15 + (i - 1) * 9; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentHelper.java b/src/game/java/net/minecraft/enchantment/EnchantmentHelper.java index 5569d698..0ddaadd0 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentHelper.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentHelper.java @@ -6,11 +6,11 @@ import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; import com.google.common.collect.Maps; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.EnumCreatureAttribute; @@ -23,374 +23,106 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.util.DamageSource; import net.minecraft.util.WeightedRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EnchantmentHelper { - /**+ - * Is the random seed of enchantment effects. + static final class DamageIterator implements EnchantmentHelper.IModifier { + public EntityLivingBase user; + public Entity target; + + private DamageIterator() { + } + + public void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel) { + enchantmentIn.onEntityDamaged(this.user, this.target, enchantmentLevel); + } + } + + static final class HurtIterator implements EnchantmentHelper.IModifier { + public EntityLivingBase user; + public Entity attacker; + + private HurtIterator() { + } + + public void calculateModifier(Enchantment enchantment, int i) { + enchantment.onUserHurt(this.user, this.attacker, i); + } + } + + interface IModifier { + void calculateModifier(Enchantment var1, int var2); + } + + static final class ModifierDamage implements EnchantmentHelper.IModifier { + public int damageModifier; + public DamageSource source; + + private ModifierDamage() { + } + + public void calculateModifier(Enchantment enchantment, int i) { + this.damageModifier += enchantment.calcModifierDamage(i, this.source); + } + } + + static final class ModifierLiving implements EnchantmentHelper.IModifier { + public float livingModifier; + public EnumCreatureAttribute entityLiving; + + private ModifierLiving() { + } + + public void calculateModifier(Enchantment enchantment, int i) { + this.livingModifier += enchantment.calcDamageByCreature(i, this.entityLiving); + } + } + + /** + * + Is the random seed of enchantment effects. */ private static final EaglercraftRandom enchantmentRand = new EaglercraftRandom(); - /**+ - * Used to calculate the extra armor of enchantments on armors - * equipped on player. + + /** + * + Used to calculate the extra armor of enchantments on armors equipped on + * player. */ private static final EnchantmentHelper.ModifierDamage enchantmentModifierDamage = new EnchantmentHelper.ModifierDamage(); - /**+ - * Used to calculate the (magic) extra damage done by - * enchantments on current equipped item of player. + + /** + * + Used to calculate the (magic) extra damage done by enchantments on current + * equipped item of player. */ private static final EnchantmentHelper.ModifierLiving enchantmentModifierLiving = new EnchantmentHelper.ModifierLiving(); + private static final EnchantmentHelper.HurtIterator ENCHANTMENT_ITERATOR_HURT = new EnchantmentHelper.HurtIterator(); + private static final EnchantmentHelper.DamageIterator ENCHANTMENT_ITERATOR_DAMAGE = new EnchantmentHelper.DamageIterator(); - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - public static int getEnchantmentLevel(int enchID, ItemStack stack) { - if (stack == null) { - return 0; - } else { - NBTTagList nbttaglist = stack.getEnchantmentTagList(); - if (nbttaglist == null) { - return 0; - } else { - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); - short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - if (short1 == enchID) { - return short2; - } - } - - return 0; - } - } - } - - public static Map getEnchantments(ItemStack stack) { - LinkedHashMap linkedhashmap = Maps.newLinkedHashMap(); - NBTTagList nbttaglist = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) - : stack.getEnchantmentTagList(); - if (nbttaglist != null) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); - short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - linkedhashmap.put(Integer.valueOf(short1), Integer.valueOf(short2)); - } - } - - return linkedhashmap; - } - - /**+ - * Set the enchantments for the specified stack. - */ - public static void setEnchantments(Map enchMap, ItemStack stack) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = enchMap.keySet().iterator(); - - while (iterator.hasNext()) { - int i = ((Integer) iterator.next()).intValue(); - Enchantment enchantment = Enchantment.getEnchantmentById(i); - if (enchantment != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setShort("id", (short) i); - nbttagcompound.setShort("lvl", (short) ((Integer) enchMap.get(Integer.valueOf(i))).intValue()); - nbttaglist.appendTag(nbttagcompound); - if (stack.getItem() == Items.enchanted_book) { - Items.enchanted_book.addEnchantment(stack, - new EnchantmentData(enchantment, ((Integer) enchMap.get(Integer.valueOf(i))).intValue())); - } - } - } - - if (nbttaglist.tagCount() > 0) { - if (stack.getItem() != Items.enchanted_book) { - stack.setTagInfo("ench", nbttaglist); - } - } else if (stack.hasTagCompound()) { - stack.getTagCompound().removeTag("ench"); - } - - } - - /**+ - * Returns the biggest level of the enchantment on the array of - * ItemStack passed. - */ - public static int getMaxEnchantmentLevel(int enchID, ItemStack[] stacks) { - if (stacks == null) { - return 0; - } else { - int i = 0; - - for (int k = 0; k < stacks.length; ++k) { - int j = getEnchantmentLevel(enchID, stacks[k]); - if (j > i) { - i = j; - } - } - - return i; - } - } - - /**+ - * Executes the enchantment modifier on the ItemStack passed. - */ - private static void applyEnchantmentModifier(EnchantmentHelper.IModifier modifier, ItemStack stack) { - if (stack != null) { - NBTTagList nbttaglist = stack.getEnchantmentTagList(); - if (nbttaglist != null) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); - short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - if (Enchantment.getEnchantmentById(short1) != null) { - modifier.calculateModifier(Enchantment.getEnchantmentById(short1), short2); - } - } - - } - } - } - - /**+ - * Executes the enchantment modifier on the array of ItemStack - * passed. - */ - private static void applyEnchantmentModifierArray(EnchantmentHelper.IModifier modifier, ItemStack[] stacks) { - for (int k = 0; k < stacks.length; ++k) { - applyEnchantmentModifier(modifier, stacks[k]); - } - - } - - /**+ - * Returns the modifier of protection enchantments on armors - * equipped on player. - */ - public static int getEnchantmentModifierDamage(ItemStack[] stacks, DamageSource source) { - enchantmentModifierDamage.damageModifier = 0; - enchantmentModifierDamage.source = source; - applyEnchantmentModifierArray(enchantmentModifierDamage, stacks); - if (enchantmentModifierDamage.damageModifier > 25) { - enchantmentModifierDamage.damageModifier = 25; - } else if (enchantmentModifierDamage.damageModifier < 0) { - enchantmentModifierDamage.damageModifier = 0; - } - - return (enchantmentModifierDamage.damageModifier + 1 >> 1) - + enchantmentRand.nextInt((enchantmentModifierDamage.damageModifier >> 1) + 1); - } - - public static float func_152377_a(ItemStack parItemStack, EnumCreatureAttribute parEnumCreatureAttribute) { - enchantmentModifierLiving.livingModifier = 0.0F; - enchantmentModifierLiving.entityLiving = parEnumCreatureAttribute; - applyEnchantmentModifier(enchantmentModifierLiving, parItemStack); - return enchantmentModifierLiving.livingModifier; - } - - public static void applyThornEnchantments(EntityLivingBase parEntityLivingBase, Entity parEntity) { - ENCHANTMENT_ITERATOR_HURT.attacker = parEntity; - ENCHANTMENT_ITERATOR_HURT.user = parEntityLivingBase; - if (parEntityLivingBase != null) { - applyEnchantmentModifierArray(ENCHANTMENT_ITERATOR_HURT, parEntityLivingBase.getInventory()); - } - - if (parEntity instanceof EntityPlayer) { - applyEnchantmentModifier(ENCHANTMENT_ITERATOR_HURT, parEntityLivingBase.getHeldItem()); - } - - } - - public static void applyArthropodEnchantments(EntityLivingBase parEntityLivingBase, Entity parEntity) { - ENCHANTMENT_ITERATOR_DAMAGE.user = parEntityLivingBase; - ENCHANTMENT_ITERATOR_DAMAGE.target = parEntity; - if (parEntityLivingBase != null) { - applyEnchantmentModifierArray(ENCHANTMENT_ITERATOR_DAMAGE, parEntityLivingBase.getInventory()); - } - - if (parEntityLivingBase instanceof EntityPlayer) { - applyEnchantmentModifier(ENCHANTMENT_ITERATOR_DAMAGE, parEntityLivingBase.getHeldItem()); - } - - } - - /**+ - * Returns the Knockback modifier of the enchantment on the - * players held item. - */ - public static int getKnockbackModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.knockback.effectId, player.getHeldItem()); - } - - /**+ - * Returns the fire aspect modifier of the players held item. - */ - public static int getFireAspectModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.fireAspect.effectId, player.getHeldItem()); - } - - /**+ - * Returns the 'Water Breathing' modifier of enchantments on - * player equipped armors. - */ - public static int getRespiration(Entity player) { - /**+ - * Returns the biggest level of the enchantment on the array of - * ItemStack passed. - */ - return getMaxEnchantmentLevel(Enchantment.respiration.effectId, player.getInventory()); - } - - /**+ - * Returns the level of the Depth Strider enchantment. - */ - public static int getDepthStriderModifier(Entity player) { - /**+ - * Returns the biggest level of the enchantment on the array of - * ItemStack passed. - */ - return getMaxEnchantmentLevel(Enchantment.depthStrider.effectId, player.getInventory()); - } - - /**+ - * Return the extra efficiency of tools based on enchantments on - * equipped player item. - */ - public static int getEfficiencyModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.efficiency.effectId, player.getHeldItem()); - } - - /**+ - * Returns the silk touch status of enchantments on current - * equipped item of player. - */ - public static boolean getSilkTouchModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.silkTouch.effectId, player.getHeldItem()) > 0; - } - - /**+ - * Returns the fortune enchantment modifier of the current - * equipped item of player. - */ - public static int getFortuneModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.fortune.effectId, player.getHeldItem()); - } - - /**+ - * Returns the level of the 'Luck Of The Sea' enchantment. - */ - public static int getLuckOfSeaModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.luckOfTheSea.effectId, player.getHeldItem()); - } - - /**+ - * Returns the level of the 'Lure' enchantment on the players - * held item. - */ - public static int getLureModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.lure.effectId, player.getHeldItem()); - } - - /**+ - * Returns the looting enchantment modifier of the current - * equipped item of player. - */ - public static int getLootingModifier(EntityLivingBase player) { - /**+ - * Returns the level of enchantment on the ItemStack passed. - */ - return getEnchantmentLevel(Enchantment.looting.effectId, player.getHeldItem()); - } - - /**+ - * Returns the aqua affinity status of enchantments on current - * equipped item of player. - */ - public static boolean getAquaAffinityModifier(EntityLivingBase player) { - /**+ - * Returns the biggest level of the enchantment on the array of - * ItemStack passed. - */ - return getMaxEnchantmentLevel(Enchantment.aquaAffinity.effectId, player.getInventory()) > 0; - } - - public static ItemStack getEnchantedItem(Enchantment parEnchantment, EntityLivingBase parEntityLivingBase) { - ItemStack[] stacks = parEntityLivingBase.getInventory(); - for (int k = 0; k < stacks.length; ++k) { - ItemStack itemstack = stacks[k]; - if (itemstack != null && getEnchantmentLevel(parEnchantment.effectId, itemstack) > 0) { - return itemstack; - } - } - - return null; - } - - /**+ - * Returns the enchantability of itemstack, it's uses a singular - * formula for each index (2nd parameter: 0, 1 and 2), cutting - * to the max enchantability power of the table (3rd parameter) - */ - public static int calcItemStackEnchantability(EaglercraftRandom parRandom, int parInt1, int parInt2, - ItemStack parItemStack) { - Item item = parItemStack.getItem(); - int i = item.getItemEnchantability(); - if (i <= 0) { - return 0; - } else { - if (parInt2 > 15) { - parInt2 = 15; - } - - int j = parRandom.nextInt(8) + 1 + (parInt2 >> 1) + parRandom.nextInt(parInt2 + 1); - return parInt1 == 0 ? Math.max(j / 3, 1) : (parInt1 == 1 ? j * 2 / 3 + 1 : Math.max(j, parInt2 * 2)); - } - } - - /**+ - * Adds a random enchantment to the specified item. Args: - * random, itemStack, enchantabilityLevel + /** + * + Adds a random enchantment to the specified item. Args: random, itemStack, + * enchantabilityLevel */ public static ItemStack addRandomEnchantment(EaglercraftRandom parRandom, ItemStack parItemStack, int parInt1) { List list = buildEnchantmentList(parRandom, parItemStack, parInt1); @@ -413,10 +145,65 @@ public class EnchantmentHelper { return parItemStack; } - /**+ - * Create a list of random EnchantmentData (enchantments) that - * can be added together to the ItemStack, the 3rd parameter is - * the total enchantability level. + public static void applyArthropodEnchantments(EntityLivingBase parEntityLivingBase, Entity parEntity) { + ENCHANTMENT_ITERATOR_DAMAGE.user = parEntityLivingBase; + ENCHANTMENT_ITERATOR_DAMAGE.target = parEntity; + if (parEntityLivingBase != null) { + applyEnchantmentModifierArray(ENCHANTMENT_ITERATOR_DAMAGE, parEntityLivingBase.getInventory()); + } + + if (parEntityLivingBase instanceof EntityPlayer) { + applyEnchantmentModifier(ENCHANTMENT_ITERATOR_DAMAGE, parEntityLivingBase.getHeldItem()); + } + + } + + /** + * + Executes the enchantment modifier on the ItemStack passed. + */ + private static void applyEnchantmentModifier(EnchantmentHelper.IModifier modifier, ItemStack stack) { + if (stack != null) { + NBTTagList nbttaglist = stack.getEnchantmentTagList(); + if (nbttaglist != null) { + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); + short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + if (Enchantment.getEnchantmentById(short1) != null) { + modifier.calculateModifier(Enchantment.getEnchantmentById(short1), short2); + } + } + + } + } + } + + /** + * + Executes the enchantment modifier on the array of ItemStack passed. + */ + private static void applyEnchantmentModifierArray(EnchantmentHelper.IModifier modifier, ItemStack[] stacks) { + for (int k = 0; k < stacks.length; ++k) { + applyEnchantmentModifier(modifier, stacks[k]); + } + + } + + public static void applyThornEnchantments(EntityLivingBase parEntityLivingBase, Entity parEntity) { + ENCHANTMENT_ITERATOR_HURT.attacker = parEntity; + ENCHANTMENT_ITERATOR_HURT.user = parEntityLivingBase; + if (parEntityLivingBase != null) { + applyEnchantmentModifierArray(ENCHANTMENT_ITERATOR_HURT, parEntityLivingBase.getInventory()); + } + + if (parEntity instanceof EntityPlayer) { + applyEnchantmentModifier(ENCHANTMENT_ITERATOR_HURT, parEntityLivingBase.getHeldItem()); + } + + } + + /** + * + Create a list of random EnchantmentData (enchantments) that can be added + * together to the ItemStack, the 3rd parameter is the total enchantability + * level. */ public static List buildEnchantmentList(EaglercraftRandom randomIn, ItemStack itemStackIn, int parInt1) { @@ -477,6 +264,243 @@ public class EnchantmentHelper { } } + /** + * + Returns the enchantability of itemstack, it's uses a singular formula for + * each index (2nd parameter: 0, 1 and 2), cutting to the max enchantability + * power of the table (3rd parameter) + */ + public static int calcItemStackEnchantability(EaglercraftRandom parRandom, int parInt1, int parInt2, + ItemStack parItemStack) { + Item item = parItemStack.getItem(); + int i = item.getItemEnchantability(); + if (i <= 0) { + return 0; + } else { + if (parInt2 > 15) { + parInt2 = 15; + } + + int j = parRandom.nextInt(8) + 1 + (parInt2 >> 1) + parRandom.nextInt(parInt2 + 1); + return parInt1 == 0 ? Math.max(j / 3, 1) : (parInt1 == 1 ? j * 2 / 3 + 1 : Math.max(j, parInt2 * 2)); + } + } + + public static float func_152377_a(ItemStack parItemStack, EnumCreatureAttribute parEnumCreatureAttribute) { + enchantmentModifierLiving.livingModifier = 0.0F; + enchantmentModifierLiving.entityLiving = parEnumCreatureAttribute; + applyEnchantmentModifier(enchantmentModifierLiving, parItemStack); + return enchantmentModifierLiving.livingModifier; + } + + /** + * + Returns the aqua affinity status of enchantments on current equipped item + * of player. + */ + public static boolean getAquaAffinityModifier(EntityLivingBase player) { + /** + * + Returns the biggest level of the enchantment on the array of ItemStack + * passed. + */ + return getMaxEnchantmentLevel(Enchantment.aquaAffinity.effectId, player.getInventory()) > 0; + } + + /** + * + Returns the level of the Depth Strider enchantment. + */ + public static int getDepthStriderModifier(Entity player) { + /** + * + Returns the biggest level of the enchantment on the array of ItemStack + * passed. + */ + return getMaxEnchantmentLevel(Enchantment.depthStrider.effectId, player.getInventory()); + } + + /** + * + Return the extra efficiency of tools based on enchantments on equipped + * player item. + */ + public static int getEfficiencyModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.efficiency.effectId, player.getHeldItem()); + } + + public static ItemStack getEnchantedItem(Enchantment parEnchantment, EntityLivingBase parEntityLivingBase) { + ItemStack[] stacks = parEntityLivingBase.getInventory(); + for (int k = 0; k < stacks.length; ++k) { + ItemStack itemstack = stacks[k]; + if (itemstack != null && getEnchantmentLevel(parEnchantment.effectId, itemstack) > 0) { + return itemstack; + } + } + + return null; + } + + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + public static int getEnchantmentLevel(int enchID, ItemStack stack) { + if (stack == null) { + return 0; + } else { + NBTTagList nbttaglist = stack.getEnchantmentTagList(); + if (nbttaglist == null) { + return 0; + } else { + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); + short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + if (short1 == enchID) { + return short2; + } + } + + return 0; + } + } + } + + /** + * + Returns the modifier of protection enchantments on armors equipped on + * player. + */ + public static int getEnchantmentModifierDamage(ItemStack[] stacks, DamageSource source) { + enchantmentModifierDamage.damageModifier = 0; + enchantmentModifierDamage.source = source; + applyEnchantmentModifierArray(enchantmentModifierDamage, stacks); + if (enchantmentModifierDamage.damageModifier > 25) { + enchantmentModifierDamage.damageModifier = 25; + } else if (enchantmentModifierDamage.damageModifier < 0) { + enchantmentModifierDamage.damageModifier = 0; + } + + return (enchantmentModifierDamage.damageModifier + 1 >> 1) + + enchantmentRand.nextInt((enchantmentModifierDamage.damageModifier >> 1) + 1); + } + + public static Map getEnchantments(ItemStack stack) { + LinkedHashMap linkedhashmap = Maps.newLinkedHashMap(); + NBTTagList nbttaglist = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) + : stack.getEnchantmentTagList(); + if (nbttaglist != null) { + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); + short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + linkedhashmap.put(Integer.valueOf(short1), Integer.valueOf(short2)); + } + } + + return linkedhashmap; + } + + /** + * + Returns the fire aspect modifier of the players held item. + */ + public static int getFireAspectModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.fireAspect.effectId, player.getHeldItem()); + } + + /** + * + Returns the fortune enchantment modifier of the current equipped item of + * player. + */ + public static int getFortuneModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.fortune.effectId, player.getHeldItem()); + } + + /** + * + Returns the Knockback modifier of the enchantment on the players held item. + */ + public static int getKnockbackModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.knockback.effectId, player.getHeldItem()); + } + + /** + * + Returns the looting enchantment modifier of the current equipped item of + * player. + */ + public static int getLootingModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.looting.effectId, player.getHeldItem()); + } + + /** + * + Returns the level of the 'Luck Of The Sea' enchantment. + */ + public static int getLuckOfSeaModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.luckOfTheSea.effectId, player.getHeldItem()); + } + + /** + * + Returns the level of the 'Lure' enchantment on the players held item. + */ + public static int getLureModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.lure.effectId, player.getHeldItem()); + } + + /** + * + Returns the biggest level of the enchantment on the array of ItemStack + * passed. + */ + public static int getMaxEnchantmentLevel(int enchID, ItemStack[] stacks) { + if (stacks == null) { + return 0; + } else { + int i = 0; + + for (int k = 0; k < stacks.length; ++k) { + int j = getEnchantmentLevel(enchID, stacks[k]); + if (j > i) { + i = j; + } + } + + return i; + } + } + + /** + * + Returns the 'Water Breathing' modifier of enchantments on player equipped + * armors. + */ + public static int getRespiration(Entity player) { + /** + * + Returns the biggest level of the enchantment on the array of ItemStack + * passed. + */ + return getMaxEnchantmentLevel(Enchantment.respiration.effectId, player.getInventory()); + } + + /** + * + Returns the silk touch status of enchantments on current equipped item of + * player. + */ + public static boolean getSilkTouchModifier(EntityLivingBase player) { + /** + * + Returns the level of enchantment on the ItemStack passed. + */ + return getEnchantmentLevel(Enchantment.silkTouch.effectId, player.getHeldItem()) > 0; + } + public static Map mapEnchantmentData(int parInt1, ItemStack parItemStack) { Item item = parItemStack.getItem(); HashMap hashmap = null; @@ -501,55 +525,35 @@ public class EnchantmentHelper { return hashmap; } - static final class DamageIterator implements EnchantmentHelper.IModifier { - public EntityLivingBase user; - public Entity target; + /** + * + Set the enchantments for the specified stack. + */ + public static void setEnchantments(Map enchMap, ItemStack stack) { + NBTTagList nbttaglist = new NBTTagList(); + Iterator iterator = enchMap.keySet().iterator(); - private DamageIterator() { + while (iterator.hasNext()) { + int i = ((Integer) iterator.next()).intValue(); + Enchantment enchantment = Enchantment.getEnchantmentById(i); + if (enchantment != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setShort("id", (short) i); + nbttagcompound.setShort("lvl", (short) ((Integer) enchMap.get(Integer.valueOf(i))).intValue()); + nbttaglist.appendTag(nbttagcompound); + if (stack.getItem() == Items.enchanted_book) { + Items.enchanted_book.addEnchantment(stack, + new EnchantmentData(enchantment, ((Integer) enchMap.get(Integer.valueOf(i))).intValue())); + } + } } - public void calculateModifier(Enchantment enchantmentIn, int enchantmentLevel) { - enchantmentIn.onEntityDamaged(this.user, this.target, enchantmentLevel); - } - } - - static final class HurtIterator implements EnchantmentHelper.IModifier { - public EntityLivingBase user; - public Entity attacker; - - private HurtIterator() { + if (nbttaglist.tagCount() > 0) { + if (stack.getItem() != Items.enchanted_book) { + stack.setTagInfo("ench", nbttaglist); + } + } else if (stack.hasTagCompound()) { + stack.getTagCompound().removeTag("ench"); } - public void calculateModifier(Enchantment enchantment, int i) { - enchantment.onUserHurt(this.user, this.attacker, i); - } - } - - interface IModifier { - void calculateModifier(Enchantment var1, int var2); - } - - static final class ModifierDamage implements EnchantmentHelper.IModifier { - public int damageModifier; - public DamageSource source; - - private ModifierDamage() { - } - - public void calculateModifier(Enchantment enchantment, int i) { - this.damageModifier += enchantment.calcModifierDamage(i, this.source); - } - } - - static final class ModifierLiving implements EnchantmentHelper.IModifier { - public float livingModifier; - public EnumCreatureAttribute entityLiving; - - private ModifierLiving() { - } - - public void calculateModifier(Enchantment enchantment, int i) { - this.livingModifier += enchantment.calcDamageByCreature(i, this.entityLiving); - } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentKnockback.java b/src/game/java/net/minecraft/enchantment/EnchantmentKnockback.java index 75f73a60..c01aab6e 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentKnockback.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentKnockback.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentKnockback extends Enchantment { this.setName("knockback"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 5 + 20 * (i - 1); - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return super.getMinEnchantability(i) + 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 2; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 5 + 20 * (i - 1); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentLootBonus.java b/src/game/java/net/minecraft/enchantment/EnchantmentLootBonus.java index df45d6c8..c4db2c11 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentLootBonus.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentLootBonus.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,34 +39,34 @@ public class EnchantmentLootBonus extends Enchantment { } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. + /** + * + Determines if the enchantment passed can be applyied together with this + * enchantment. */ - public int getMinEnchantability(int i) { - return 15 + (i - 1) * 9; + public boolean canApplyTogether(Enchantment enchantment) { + return super.canApplyTogether(enchantment) && enchantment.effectId != silkTouch.effectId; } - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return super.getMinEnchantability(i) + 50; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 3; } - /**+ - * Determines if the enchantment passed can be applyied together - * with this enchantment. + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. */ - public boolean canApplyTogether(Enchantment enchantment) { - return super.canApplyTogether(enchantment) && enchantment.effectId != silkTouch.effectId; + public int getMinEnchantability(int i) { + return 15 + (i - 1) * 9; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentOxygen.java b/src/game/java/net/minecraft/enchantment/EnchantmentOxygen.java index cc3f5b1b..61b7b0d0 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentOxygen.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentOxygen.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentOxygen extends Enchantment { this.setName("oxygen"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 10 * i; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return this.getMinEnchantability(i) + 30; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 3; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 10 * i; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentProtection.java b/src/game/java/net/minecraft/enchantment/EnchantmentProtection.java index 845eae49..e3634a6d 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentProtection.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentProtection.java @@ -5,46 +5,73 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EnchantmentProtection extends Enchantment { - /**+ - * Holds the name to be translated of each protection type. + /** + * + Holds the name to be translated of each protection type. */ private static final String[] protectionName = new String[] { "all", "fire", "fall", "explosion", "projectile" }; - /**+ - * Holds the base factor of enchantability needed to be able to - * use the enchant. + /** + * + Holds the base factor of enchantability needed to be able to use the + * enchant. */ private static final int[] baseEnchantability = new int[] { 1, 10, 5, 5, 3 }; - /**+ - * Holds how much each level increased the enchantability factor - * to be able to use this enchant. + /** + * + Holds how much each level increased the enchantability factor to be able to + * use this enchant. */ private static final int[] levelEnchantability = new int[] { 11, 8, 6, 8, 6 }; - /**+ - * Used on the formula of base enchantability, this is the - * 'window' factor of values to be able to use thing enchant. + /** + * + Used on the formula of base enchantability, this is the 'window' factor of + * values to be able to use thing enchant. */ private static final int[] thresholdEnchantability = new int[] { 20, 12, 10, 12, 15 }; + + public static double func_92092_a(Entity parEntity, double parDouble1) { + int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.blastProtection.effectId, + parEntity.getInventory()); + if (i > 0) { + parDouble1 -= (double) MathHelper.floor_double(parDouble1 * (double) ((float) i * 0.15F)); + } + + return parDouble1; + } + + /** + * + Gets the amount of ticks an entity should be set fire, adjusted for fire + * protection. + */ + public static int getFireTimeForEntity(Entity parEntity, int parInt1) { + int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.fireProtection.effectId, parEntity.getInventory()); + if (i > 0) { + parInt1 -= MathHelper.floor_float((float) parInt1 * (float) i * 0.15F); + } + + return parInt1; + } + public final int protectionType; public EnchantmentProtection(int parInt1, ResourceLocation parResourceLocation, int parInt2, int parInt3) { @@ -56,32 +83,9 @@ public class EnchantmentProtection extends Enchantment { } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return baseEnchantability[this.protectionType] + (i - 1) * levelEnchantability[this.protectionType]; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. - */ - public int getMaxEnchantability(int i) { - return this.getMinEnchantability(i) + thresholdEnchantability[this.protectionType]; - } - - /**+ - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() { - return 4; - } - - /**+ - * Calculates the damage protection of the enchantment based on - * level and damage source passed. + /** + * + Calculates the damage protection of the enchantment based on level and + * damage source passed. */ public int calcModifierDamage(int i, DamageSource damagesource) { if (damagesource.canHarmInCreative()) { @@ -100,18 +104,10 @@ public class EnchantmentProtection extends Enchantment { } } - /**+ - * Return the name of key in translation table of this + /** + * + Determines if the enchantment passed can be applyied together with this * enchantment. */ - public String getName() { - return "enchantment.protect." + protectionName[this.protectionType]; - } - - /**+ - * Determines if the enchantment passed can be applyied together - * with this enchantment. - */ public boolean canApplyTogether(Enchantment enchantment) { if (enchantment instanceof EnchantmentProtection) { EnchantmentProtection enchantmentprotection = (EnchantmentProtection) enchantment; @@ -122,26 +118,33 @@ public class EnchantmentProtection extends Enchantment { } } - /**+ - * Gets the amount of ticks an entity should be set fire, - * adjusted for fire protection. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ - public static int getFireTimeForEntity(Entity parEntity, int parInt1) { - int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.fireProtection.effectId, parEntity.getInventory()); - if (i > 0) { - parInt1 -= MathHelper.floor_float((float) parInt1 * (float) i * 0.15F); - } - - return parInt1; + public int getMaxEnchantability(int i) { + return this.getMinEnchantability(i) + thresholdEnchantability[this.protectionType]; } - public static double func_92092_a(Entity parEntity, double parDouble1) { - int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.blastProtection.effectId, - parEntity.getInventory()); - if (i > 0) { - parDouble1 -= (double) MathHelper.floor_double(parDouble1 * (double) ((float) i * 0.15F)); - } + /** + * + Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() { + return 4; + } - return parDouble1; + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return baseEnchantability[this.protectionType] + (i - 1) * levelEnchantability[this.protectionType]; + } + + /** + * + Return the name of key in translation table of this enchantment. + */ + public String getName() { + return "enchantment.protect." + protectionName[this.protectionType]; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentThorns.java b/src/game/java/net/minecraft/enchantment/EnchantmentThorns.java index 92d96a41..055622a5 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentThorns.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentThorns.java @@ -1,7 +1,6 @@ package net.minecraft.enchantment; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemArmor; @@ -9,66 +8,76 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EnchantmentThorns extends Enchantment { + public static boolean func_92094_a(int parInt1, EaglercraftRandom parRandom) { + return parInt1 <= 0 ? false : parRandom.nextFloat() < 0.15F * (float) parInt1; + } + + public static int func_92095_b(int parInt1, EaglercraftRandom parRandom) { + return parInt1 > 10 ? parInt1 - 10 : 1 + parRandom.nextInt(4); + } + public EnchantmentThorns(int parInt1, ResourceLocation parResourceLocation, int parInt2) { super(parInt1, parResourceLocation, parInt2, EnumEnchantmentType.ARMOR_TORSO); this.setName("thorns"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return 10 + 20 * (i - 1); - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. - */ - public int getMaxEnchantability(int i) { - return super.getMinEnchantability(i) + 50; - } - - /**+ - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() { - return 3; - } - - /**+ - * Determines if this enchantment can be applied to a specific - * ItemStack. + /** + * + Determines if this enchantment can be applied to a specific ItemStack. */ public boolean canApply(ItemStack itemstack) { return itemstack.getItem() instanceof ItemArmor ? true : super.canApply(itemstack); } - /**+ - * Whenever an entity that has this enchantment on one of its - * associated items is damaged this method will be called. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. + */ + public int getMaxEnchantability(int i) { + return super.getMinEnchantability(i) + 50; + } + + /** + * + Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() { + return 3; + } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return 10 + 20 * (i - 1); + } + + /** + * + Whenever an entity that has this enchantment on one of its associated items + * is damaged this method will be called. */ public void onUserHurt(EntityLivingBase entitylivingbase, Entity entity, int i) { EaglercraftRandom random = entitylivingbase.getRNG(); @@ -88,12 +97,4 @@ public class EnchantmentThorns extends Enchantment { } } - - public static boolean func_92094_a(int parInt1, EaglercraftRandom parRandom) { - return parInt1 <= 0 ? false : parRandom.nextFloat() < 0.15F * (float) parInt1; - } - - public static int func_92095_b(int parInt1, EaglercraftRandom parRandom) { - return parInt1 > 10 ? parInt1 - 10 : 1 + parRandom.nextInt(4); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentUntouching.java b/src/game/java/net/minecraft/enchantment/EnchantmentUntouching.java index 0c2f4215..925779ca 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentUntouching.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentUntouching.java @@ -4,22 +4,25 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,42 +33,41 @@ public class EnchantmentUntouching extends Enchantment { this.setName("untouching"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. + /** + * + Determines if this enchantment can be applied to a specific ItemStack. */ - public int getMinEnchantability(int var1) { - return 15; + public boolean canApply(ItemStack itemstack) { + return itemstack.getItem() == Items.shears ? true : super.canApply(itemstack); } - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. - */ - public int getMaxEnchantability(int i) { - return super.getMinEnchantability(i) + 50; - } - - /**+ - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() { - return 1; - } - - /**+ - * Determines if the enchantment passed can be applyied together - * with this enchantment. + /** + * + Determines if the enchantment passed can be applyied together with this + * enchantment. */ public boolean canApplyTogether(Enchantment enchantment) { return super.canApplyTogether(enchantment) && enchantment.effectId != fortune.effectId; } - /**+ - * Determines if this enchantment can be applied to a specific - * ItemStack. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ - public boolean canApply(ItemStack itemstack) { - return itemstack.getItem() == Items.shears ? true : super.canApply(itemstack); + public int getMaxEnchantability(int i) { + return super.getMinEnchantability(i) + 50; + } + + /** + * + Returns the maximum level that the enchantment can have. + */ + public int getMaxLevel() { + return 1; + } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int var1) { + return 15; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentWaterWalker.java b/src/game/java/net/minecraft/enchantment/EnchantmentWaterWalker.java index 1cfa9246..cc95b3d0 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentWaterWalker.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentWaterWalker.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentWaterWalker extends Enchantment { this.setName("waterWalker"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int i) { - return i * 10; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return this.getMinEnchantability(i) + 15; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 3; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int i) { + return i * 10; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnchantmentWaterWorker.java b/src/game/java/net/minecraft/enchantment/EnchantmentWaterWorker.java index ac80ec6e..064f7eb1 100644 --- a/src/game/java/net/minecraft/enchantment/EnchantmentWaterWorker.java +++ b/src/game/java/net/minecraft/enchantment/EnchantmentWaterWorker.java @@ -2,22 +2,25 @@ package net.minecraft.enchantment; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,26 +31,26 @@ public class EnchantmentWaterWorker extends Enchantment { this.setName("waterWorker"); } - /**+ - * Returns the minimal value of enchantability needed on the - * enchantment level passed. - */ - public int getMinEnchantability(int var1) { - return 1; - } - - /**+ - * Returns the maximum value of enchantability nedded on the - * enchantment level passed. + /** + * + Returns the maximum value of enchantability nedded on the enchantment level + * passed. */ public int getMaxEnchantability(int i) { return this.getMinEnchantability(i) + 40; } - /**+ - * Returns the maximum level that the enchantment can have. + /** + * + Returns the maximum level that the enchantment can have. */ public int getMaxLevel() { return 1; } + + /** + * + Returns the minimal value of enchantability needed on the enchantment level + * passed. + */ + public int getMinEnchantability(int var1) { + return 1; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/enchantment/EnumEnchantmentType.java b/src/game/java/net/minecraft/enchantment/EnumEnchantmentType.java index f000b978..b48990be 100644 --- a/src/game/java/net/minecraft/enchantment/EnumEnchantmentType.java +++ b/src/game/java/net/minecraft/enchantment/EnumEnchantmentType.java @@ -7,22 +7,25 @@ import net.minecraft.item.ItemFishingRod; import net.minecraft.item.ItemSword; import net.minecraft.item.ItemTool; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,9 +33,9 @@ import net.minecraft.item.ItemTool; public enum EnumEnchantmentType { ALL, ARMOR, ARMOR_FEET, ARMOR_LEGS, ARMOR_TORSO, ARMOR_HEAD, WEAPON, DIGGER, FISHING_ROD, BREAKABLE, BOW; - /**+ - * Return true if the item passed can be enchanted by a - * enchantment of this type. + /** + * + Return true if the item passed can be enchanted by a enchantment of this + * type. */ public boolean canEnchantItem(Item parItem) { if (this == ALL) { diff --git a/src/game/java/net/minecraft/entity/DataWatcher.java b/src/game/java/net/minecraft/entity/DataWatcher.java index fed71c23..1b9cb8ca 100644 --- a/src/game/java/net/minecraft/entity/DataWatcher.java +++ b/src/game/java/net/minecraft/entity/DataWatcher.java @@ -18,251 +18,84 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ReportedException; import net.minecraft.util.Rotations; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DataWatcher { - private final Entity owner; - /**+ - * When isBlank is true the DataWatcher is not watching any - * objects - */ - private boolean isBlank = true; + public static class WatchableObject { + private final int objectType; + private final int dataValueId; + private Object watchedObject; + private boolean watched; + + public WatchableObject(int type, int id, Object object) { + this.dataValueId = id; + this.watchedObject = object; + this.objectType = type; + this.watched = true; + } + + public int getDataValueId() { + return this.dataValueId; + } + + public Object getObject() { + return this.watchedObject; + } + + public int getObjectType() { + return this.objectType; + } + + public boolean isWatched() { + return this.watched; + } + + public void setObject(Object object) { + this.watchedObject = object; + } + + public void setWatched(boolean watched) { + this.watched = watched; + } + } + private static final Map, Integer> dataTypes = Maps.newHashMap(); - private final Map watchedObjects = Maps.newHashMap(); - private boolean objectChanged; - - public DataWatcher(Entity owner) { - this.owner = owner; + static { + dataTypes.put(Byte.class, Integer.valueOf(0)); + dataTypes.put(Short.class, Integer.valueOf(1)); + dataTypes.put(Integer.class, Integer.valueOf(2)); + dataTypes.put(Float.class, Integer.valueOf(3)); + dataTypes.put(String.class, Integer.valueOf(4)); + dataTypes.put(ItemStack.class, Integer.valueOf(5)); + dataTypes.put(BlockPos.class, Integer.valueOf(6)); + dataTypes.put(Rotations.class, Integer.valueOf(7)); } - public void addObject(int id, T object) { - Integer integer = (Integer) dataTypes.get(object.getClass()); - if (integer == null) { - throw new IllegalArgumentException("Unknown data type: " + object.getClass()); - } else if (id > 31) { - throw new IllegalArgumentException("Data value id is too big with " + id + "! (Max is " + 31 + ")"); - } else if (this.watchedObjects.containsKey(Integer.valueOf(id))) { - throw new IllegalArgumentException("Duplicate id value for " + id + "!"); - } else { - DataWatcher.WatchableObject datawatcher$watchableobject = new DataWatcher.WatchableObject( - integer.intValue(), id, object); - this.watchedObjects.put(Integer.valueOf(id), datawatcher$watchableobject); - this.isBlank = false; - } - } - - /**+ - * Add a new object for the DataWatcher to watch, using the - * specified data type. - */ - public void addObjectByDataType(int id, int type) { - DataWatcher.WatchableObject datawatcher$watchableobject = new DataWatcher.WatchableObject(type, id, - (Object) null); - this.watchedObjects.put(Integer.valueOf(id), datawatcher$watchableobject); - this.isBlank = false; - } - - /**+ - * gets the bytevalue of a watchable object - */ - public byte getWatchableObjectByte(int id) { - return ((Byte) this.getWatchedObject(id).getObject()).byteValue(); - } - - public short getWatchableObjectShort(int id) { - return ((Short) this.getWatchedObject(id).getObject()).shortValue(); - } - - /**+ - * gets a watchable object and returns it as a Integer - */ - public int getWatchableObjectInt(int id) { - return ((Integer) this.getWatchedObject(id).getObject()).intValue(); - } - - public float getWatchableObjectFloat(int id) { - return ((Float) this.getWatchedObject(id).getObject()).floatValue(); - } - - /**+ - * gets a watchable object and returns it as a String - */ - public String getWatchableObjectString(int id) { - return (String) this.getWatchedObject(id).getObject(); - } - - /**+ - * Get a watchable object as an ItemStack. - */ - public ItemStack getWatchableObjectItemStack(int id) { - return (ItemStack) this.getWatchedObject(id).getObject(); - } - - /**+ - * is threadsafe, unless it throws an exception, then - */ - private DataWatcher.WatchableObject getWatchedObject(int id) { - DataWatcher.WatchableObject datawatcher$watchableobject; - try { - datawatcher$watchableobject = (DataWatcher.WatchableObject) this.watchedObjects.get(Integer.valueOf(id)); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting synched entity data"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Synched entity data"); - crashreportcategory.addCrashSection("Data ID", Integer.valueOf(id)); - throw new ReportedException(crashreport); - } - return datawatcher$watchableobject; - } - - public Rotations getWatchableObjectRotations(int id) { - return (Rotations) this.getWatchedObject(id).getObject(); - } - - public void updateObject(int id, T newData) { - DataWatcher.WatchableObject datawatcher$watchableobject = this.getWatchedObject(id); - if (ObjectUtils.notEqual(newData, datawatcher$watchableobject.getObject())) { - datawatcher$watchableobject.setObject(newData); - this.owner.onDataWatcherUpdate(id); - datawatcher$watchableobject.setWatched(true); - this.objectChanged = true; - } - - } - - public void setObjectWatched(int id) { - this.getWatchedObject(id).watched = true; - this.objectChanged = true; - } - - /**+ - * true if one or more object was changed - */ - public boolean hasObjectChanged() { - return this.objectChanged; - } - - /**+ - * Writes the list of watched objects (entity attribute of type - * {byte, short, int, float, string, ItemStack, - * ChunkCoordinates}) to the specified PacketBuffer - */ - public static void writeWatchedListToPacketBuffer(List objectsList, - PacketBuffer buffer) throws IOException { - if (objectsList != null) { - for (int i = 0, l = objectsList.size(); i < l; ++i) { - writeWatchableObjectToPacketBuffer(buffer, objectsList.get(i)); - } - } - - buffer.writeByte(127); - } - - public List getChanged() { - ArrayList arraylist = null; - if (this.objectChanged) { - for (DataWatcher.WatchableObject datawatcher$watchableobject : this.watchedObjects.values()) { - if (datawatcher$watchableobject.isWatched()) { - datawatcher$watchableobject.setWatched(false); - if (arraylist == null) { - arraylist = Lists.newArrayList(); - } - - arraylist.add(datawatcher$watchableobject); - } - } - } - - this.objectChanged = false; - return arraylist; - } - - public void writeTo(PacketBuffer buffer) throws IOException { - for (DataWatcher.WatchableObject datawatcher$watchableobject : this.watchedObjects.values()) { - writeWatchableObjectToPacketBuffer(buffer, datawatcher$watchableobject); - } - buffer.writeByte(127); - } - - public List getAllWatched() { - ArrayList arraylist = null; - - for (DataWatcher.WatchableObject datawatcher$watchableobject : this.watchedObjects.values()) { - if (arraylist == null) { - arraylist = Lists.newArrayList(); - } - - arraylist.add(datawatcher$watchableobject); - } - - return arraylist; - } - - /**+ - * Writes a watchable object (entity attribute of type {byte, - * short, int, float, string, ItemStack, ChunkCoordinates}) to - * the specified PacketBuffer - */ - private static void writeWatchableObjectToPacketBuffer(PacketBuffer buffer, DataWatcher.WatchableObject object) - throws IOException { - int i = (object.getObjectType() << 5 | object.getDataValueId() & 31) & 255; - buffer.writeByte(i); - switch (object.getObjectType()) { - case 0: - buffer.writeByte(((Byte) object.getObject()).byteValue()); - break; - case 1: - buffer.writeShort(((Short) object.getObject()).shortValue()); - break; - case 2: - buffer.writeInt(((Integer) object.getObject()).intValue()); - break; - case 3: - buffer.writeFloat(((Float) object.getObject()).floatValue()); - break; - case 4: - buffer.writeString((String) object.getObject()); - break; - case 5: - ItemStack itemstack = (ItemStack) object.getObject(); - buffer.writeItemStackToBuffer(itemstack); - break; - case 6: - BlockPos blockpos = (BlockPos) object.getObject(); - buffer.writeInt(blockpos.getX()); - buffer.writeInt(blockpos.getY()); - buffer.writeInt(blockpos.getZ()); - break; - case 7: - Rotations rotations = (Rotations) object.getObject(); - buffer.writeFloat(rotations.getX()); - buffer.writeFloat(rotations.getY()); - buffer.writeFloat(rotations.getZ()); - } - - } - - /**+ - * Reads a list of watched objects (entity attribute of type - * {byte, short, int, float, string, ItemStack, - * ChunkCoordinates}) from the supplied PacketBuffer + /** + * + Reads a list of watched objects (entity attribute of type {byte, short, + * int, float, string, ItemStack, ChunkCoordinates}) from the supplied + * PacketBuffer */ public static List readWatchedListFromPacketBuffer(PacketBuffer buffer) throws IOException { @@ -314,6 +147,227 @@ public class DataWatcher { return arraylist; } + /** + * + Writes a watchable object (entity attribute of type {byte, short, int, + * float, string, ItemStack, ChunkCoordinates}) to the specified PacketBuffer + */ + private static void writeWatchableObjectToPacketBuffer(PacketBuffer buffer, DataWatcher.WatchableObject object) + throws IOException { + int i = (object.getObjectType() << 5 | object.getDataValueId() & 31) & 255; + buffer.writeByte(i); + switch (object.getObjectType()) { + case 0: + buffer.writeByte(((Byte) object.getObject()).byteValue()); + break; + case 1: + buffer.writeShort(((Short) object.getObject()).shortValue()); + break; + case 2: + buffer.writeInt(((Integer) object.getObject()).intValue()); + break; + case 3: + buffer.writeFloat(((Float) object.getObject()).floatValue()); + break; + case 4: + buffer.writeString((String) object.getObject()); + break; + case 5: + ItemStack itemstack = (ItemStack) object.getObject(); + buffer.writeItemStackToBuffer(itemstack); + break; + case 6: + BlockPos blockpos = (BlockPos) object.getObject(); + buffer.writeInt(blockpos.getX()); + buffer.writeInt(blockpos.getY()); + buffer.writeInt(blockpos.getZ()); + break; + case 7: + Rotations rotations = (Rotations) object.getObject(); + buffer.writeFloat(rotations.getX()); + buffer.writeFloat(rotations.getY()); + buffer.writeFloat(rotations.getZ()); + } + + } + + /** + * + Writes the list of watched objects (entity attribute of type {byte, short, + * int, float, string, ItemStack, ChunkCoordinates}) to the specified + * PacketBuffer + */ + public static void writeWatchedListToPacketBuffer(List objectsList, + PacketBuffer buffer) throws IOException { + if (objectsList != null) { + for (int i = 0, l = objectsList.size(); i < l; ++i) { + writeWatchableObjectToPacketBuffer(buffer, objectsList.get(i)); + } + } + + buffer.writeByte(127); + } + + private final Entity owner; + + /** + * + When isBlank is true the DataWatcher is not watching any objects + */ + private boolean isBlank = true; + + private final Map watchedObjects = Maps.newHashMap(); + + private boolean objectChanged; + + public DataWatcher(Entity owner) { + this.owner = owner; + } + + public void addObject(int id, T object) { + Integer integer = (Integer) dataTypes.get(object.getClass()); + if (integer == null) { + throw new IllegalArgumentException("Unknown data type: " + object.getClass()); + } else if (id > 31) { + throw new IllegalArgumentException("Data value id is too big with " + id + "! (Max is " + 31 + ")"); + } else if (this.watchedObjects.containsKey(Integer.valueOf(id))) { + throw new IllegalArgumentException("Duplicate id value for " + id + "!"); + } else { + DataWatcher.WatchableObject datawatcher$watchableobject = new DataWatcher.WatchableObject( + integer.intValue(), id, object); + this.watchedObjects.put(Integer.valueOf(id), datawatcher$watchableobject); + this.isBlank = false; + } + } + + /** + * + Add a new object for the DataWatcher to watch, using the specified data + * type. + */ + public void addObjectByDataType(int id, int type) { + DataWatcher.WatchableObject datawatcher$watchableobject = new DataWatcher.WatchableObject(type, id, + (Object) null); + this.watchedObjects.put(Integer.valueOf(id), datawatcher$watchableobject); + this.isBlank = false; + } + + public void func_111144_e() { + this.objectChanged = false; + } + + public List getAllWatched() { + ArrayList arraylist = null; + + for (DataWatcher.WatchableObject datawatcher$watchableobject : this.watchedObjects.values()) { + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } + + arraylist.add(datawatcher$watchableobject); + } + + return arraylist; + } + + public List getChanged() { + ArrayList arraylist = null; + if (this.objectChanged) { + for (DataWatcher.WatchableObject datawatcher$watchableobject : this.watchedObjects.values()) { + if (datawatcher$watchableobject.isWatched()) { + datawatcher$watchableobject.setWatched(false); + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } + + arraylist.add(datawatcher$watchableobject); + } + } + } + + this.objectChanged = false; + return arraylist; + } + + public boolean getIsBlank() { + return this.isBlank; + } + + /** + * + gets the bytevalue of a watchable object + */ + public byte getWatchableObjectByte(int id) { + return ((Byte) this.getWatchedObject(id).getObject()).byteValue(); + } + + public float getWatchableObjectFloat(int id) { + return ((Float) this.getWatchedObject(id).getObject()).floatValue(); + } + + /** + * + gets a watchable object and returns it as a Integer + */ + public int getWatchableObjectInt(int id) { + return ((Integer) this.getWatchedObject(id).getObject()).intValue(); + } + + /** + * + Get a watchable object as an ItemStack. + */ + public ItemStack getWatchableObjectItemStack(int id) { + return (ItemStack) this.getWatchedObject(id).getObject(); + } + + public Rotations getWatchableObjectRotations(int id) { + return (Rotations) this.getWatchedObject(id).getObject(); + } + + public short getWatchableObjectShort(int id) { + return ((Short) this.getWatchedObject(id).getObject()).shortValue(); + } + + /** + * + gets a watchable object and returns it as a String + */ + public String getWatchableObjectString(int id) { + return (String) this.getWatchedObject(id).getObject(); + } + + /** + * + is threadsafe, unless it throws an exception, then + */ + private DataWatcher.WatchableObject getWatchedObject(int id) { + DataWatcher.WatchableObject datawatcher$watchableobject; + try { + datawatcher$watchableobject = (DataWatcher.WatchableObject) this.watchedObjects.get(Integer.valueOf(id)); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting synched entity data"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Synched entity data"); + crashreportcategory.addCrashSection("Data ID", Integer.valueOf(id)); + throw new ReportedException(crashreport); + } + return datawatcher$watchableobject; + } + + /** + * + true if one or more object was changed + */ + public boolean hasObjectChanged() { + return this.objectChanged; + } + + public void setObjectWatched(int id) { + this.getWatchedObject(id).watched = true; + this.objectChanged = true; + } + + public void updateObject(int id, T newData) { + DataWatcher.WatchableObject datawatcher$watchableobject = this.getWatchedObject(id); + if (ObjectUtils.notEqual(newData, datawatcher$watchableobject.getObject())) { + datawatcher$watchableobject.setObject(newData); + this.owner.onDataWatcherUpdate(id); + datawatcher$watchableobject.setWatched(true); + this.objectChanged = true; + } + + } + public void updateWatchedObjectsFromList(List parList) { for (int i = 0, l = parList.size(); i < l; ++i) { @@ -329,60 +383,10 @@ public class DataWatcher { this.objectChanged = true; } - public boolean getIsBlank() { - return this.isBlank; - } - - public void func_111144_e() { - this.objectChanged = false; - } - - static { - dataTypes.put(Byte.class, Integer.valueOf(0)); - dataTypes.put(Short.class, Integer.valueOf(1)); - dataTypes.put(Integer.class, Integer.valueOf(2)); - dataTypes.put(Float.class, Integer.valueOf(3)); - dataTypes.put(String.class, Integer.valueOf(4)); - dataTypes.put(ItemStack.class, Integer.valueOf(5)); - dataTypes.put(BlockPos.class, Integer.valueOf(6)); - dataTypes.put(Rotations.class, Integer.valueOf(7)); - } - - public static class WatchableObject { - private final int objectType; - private final int dataValueId; - private Object watchedObject; - private boolean watched; - - public WatchableObject(int type, int id, Object object) { - this.dataValueId = id; - this.watchedObject = object; - this.objectType = type; - this.watched = true; - } - - public int getDataValueId() { - return this.dataValueId; - } - - public void setObject(Object object) { - this.watchedObject = object; - } - - public Object getObject() { - return this.watchedObject; - } - - public int getObjectType() { - return this.objectType; - } - - public boolean isWatched() { - return this.watched; - } - - public void setWatched(boolean watched) { - this.watched = watched; + public void writeTo(PacketBuffer buffer) throws IOException { + for (DataWatcher.WatchableObject datawatcher$watchableobject : this.watchedObjects.values()) { + writeWatchableObjectToPacketBuffer(buffer, datawatcher$watchableobject); } + buffer.writeByte(127); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/Entity.java b/src/game/java/net/minecraft/entity/Entity.java index 10306e12..3d237967 100644 --- a/src/game/java/net/minecraft/entity/Entity.java +++ b/src/game/java/net/minecraft/entity/Entity.java @@ -1,15 +1,14 @@ package net.minecraft.entity; import java.util.List; +import java.util.concurrent.Callable; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.HString; import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DynamicLightManager; import net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights.DynamicLightsStateManager; import net.lax1dude.eaglercraft.v1_8.profanity_filter.ProfanityFilter; - -import java.util.concurrent.Callable; - import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; @@ -55,22 +54,25 @@ import net.minecraft.world.Explosion; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -151,20 +153,9 @@ public abstract class Entity implements ICommandSender { protected EaglercraftUUID entityUniqueID; private final CommandResultStats cmdResultStats; - public int getEntityId() { - return this.entityId; - } + private String lastNameTagForFilter = null; - public void setEntityId(int id) { - this.entityId = id; - } - - /**+ - * Called by the /kill command. - */ - public void onKillCommand() { - this.setDead(); - } + private String lastFilteredNameTagForFilter = null; public Entity(World worldIn) { this.entityId = nextEntityID++; @@ -193,263 +184,1047 @@ public abstract class Entity implements ICommandSender { this.entityInit(); } + /** + * + Send a chat message to the CommandSender + */ + public void addChatMessage(IChatComponent var1) { + } + + public void addEntityCrashInfo(CrashReportCategory category) { + category.addCrashSectionCallable("Entity Type", new Callable() { + public String call() throws Exception { + return EntityList.getEntityString(Entity.this) + " (" + Entity.this.getClass().getCanonicalName() + ")"; + } + }); + category.addCrashSection("Entity ID", Integer.valueOf(this.entityId)); + category.addCrashSectionCallable("Entity Name", new Callable() { + public String call() throws Exception { + return Entity.this.getName(); + } + }); + category.addCrashSection("Entity\'s Exact location", String.format("%.2f, %.2f, %.2f", + new Object[] { Double.valueOf(this.posX), Double.valueOf(this.posY), Double.valueOf(this.posZ) })); + category.addCrashSection("Entity\'s Block location", + CrashReportCategory.getCoordinateInfo((double) MathHelper.floor_double(this.posX), + (double) MathHelper.floor_double(this.posY), (double) MathHelper.floor_double(this.posZ))); + category.addCrashSection("Entity\'s Momentum", String.format("%.2f, %.2f, %.2f", new Object[] { + Double.valueOf(this.motionX), Double.valueOf(this.motionY), Double.valueOf(this.motionZ) })); + category.addCrashSectionCallable("Entity\'s Rider", new Callable() { + public String call() throws Exception { + return Entity.this.riddenByEntity.toString(); + } + }); + category.addCrashSectionCallable("Entity\'s Vehicle", new Callable() { + public String call() throws Exception { + return Entity.this.ridingEntity.toString(); + } + }); + } + + /** + * + Adds a value to the player score. Currently not actually used and the + * entity passed in does nothing. Args: entity, scoreToAdd + */ + public void addToPlayerScore(Entity entityIn, int amount) { + } + + /** + * + Adds to the current velocity of the entity. Args: x, y, z + */ + public void addVelocity(double x, double y, double z) { + this.motionX += x; + this.motionY += y; + this.motionZ += z; + this.isAirBorne = true; + } + + protected void applyEnchantments(EntityLivingBase entityLivingBaseIn, Entity entityIn) { + if (entityIn instanceof EntityLivingBase) { + EnchantmentHelper.applyThornEnchantments((EntityLivingBase) entityIn, entityLivingBaseIn); + } + + EnchantmentHelper.applyArthropodEnchantments(entityLivingBaseIn, entityIn); + } + + /** + * + Applies a velocity to each of the entities pushing them away from each + * other. Args: entity + */ + public void applyEntityCollision(Entity entityIn) { + if (entityIn.riddenByEntity != this && entityIn.ridingEntity != this) { + if (!entityIn.noClip && !this.noClip) { + double d0 = entityIn.posX - this.posX; + double d1 = entityIn.posZ - this.posZ; + double d2 = MathHelper.abs_max(d0, d1); + if (d2 >= 0.009999999776482582D) { + d2 = (double) MathHelper.sqrt_double(d2); + d0 = d0 / d2; + d1 = d1 / d2; + double d3 = 1.0D / d2; + if (d3 > 1.0D) { + d3 = 1.0D; + } + + d0 = d0 * d3; + d1 = d1 * d3; + d0 = d0 * 0.05000000074505806D; + d1 = d1 * 0.05000000074505806D; + d0 = d0 * (double) (1.0F - this.entityCollisionReduction); + d1 = d1 * (double) (1.0F - this.entityCollisionReduction); + if (this.riddenByEntity == null) { + this.addVelocity(-d0, 0.0D, -d1); + } + + if (entityIn.riddenByEntity == null) { + entityIn.addVelocity(d0, 0.0D, d1); + } + } + + } + } + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float var2) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + this.setBeenAttacked(); + return false; + } + } + + /** + * + If returns false, the item will not inflict any damage against entities. + */ + public boolean canAttackWithItem() { + return true; + } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return false; + } + + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. + */ + public boolean canBePushed() { + return false; + } + + /** + * + Returns {@code true} if the CommandSender is allowed to execute the + * command, {@code false} if not + */ + public boolean canCommandSenderUseCommand(int var1, String var2) { + return true; + } + + /** + * + Return whether this entity should be rendered as on fire. + */ + public boolean canRenderOnFire() { + return this.isBurning(); + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return true; + } + + /** + * + Called when client receives entity's NBTTagCompound from server. + */ + public void clientUpdateEntityNBT(NBTTagCompound compound) { + } + + /** + * + Prepares this entity in new dimension by copying NBT data from entity in + * old dimension + */ + public void copyDataFromOld(Entity entityIn) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + entityIn.writeToNBT(nbttagcompound); + this.readFromNBT(nbttagcompound); + this.timeUntilPortal = entityIn.timeUntilPortal; + this.field_181016_an = entityIn.field_181016_an; + this.field_181017_ao = entityIn.field_181017_ao; + this.field_181018_ap = entityIn.field_181018_ap; + } + + /** + * + Sets this entity's location and angles to the location and angles of the + * passed in entity. + */ + public void copyLocationAndAnglesFrom(Entity entityIn) { + this.setLocationAndAngles(entityIn.posX, entityIn.posY, entityIn.posZ, entityIn.rotationYaw, + entityIn.rotationPitch); + } + + protected void createRunningParticles() { + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); + int k = MathHelper.floor_double(this.posZ); + BlockPos blockpos = new BlockPos(i, j, k); + IBlockState iblockstate = this.worldObj.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + if (block.getRenderType() != -1) { + this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, + this.posX + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, + this.getEntityBoundingBox().minY + 0.1D, + this.posZ + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, -this.motionX * 4.0D, + 1.5D, -this.motionZ * 4.0D, new int[] { Block.getStateId(iblockstate) }); + } + + } + + /** + * + Will deal the specified amount of damage to the entity if the entity isn't + * immune to fire damage. Args: amountDamage + */ + protected void dealFireDamage(int amount) { + if (!this.isImmuneToFire) { + this.attackEntityFrom(DamageSource.inFire, (float) amount); + } + + } + + protected void doBlockCollisions() { + BlockPos blockpos = new BlockPos(this.getEntityBoundingBox().minX + 0.001D, + this.getEntityBoundingBox().minY + 0.001D, this.getEntityBoundingBox().minZ + 0.001D); + BlockPos blockpos1 = new BlockPos(this.getEntityBoundingBox().maxX - 0.001D, + this.getEntityBoundingBox().maxY - 0.001D, this.getEntityBoundingBox().maxZ - 0.001D); + if (this.worldObj.isAreaLoaded(blockpos, blockpos1)) { + for (int i = blockpos.getX(); i <= blockpos1.getX(); ++i) { + for (int j = blockpos.getY(); j <= blockpos1.getY(); ++j) { + for (int k = blockpos.getZ(); k <= blockpos1.getZ(); ++k) { + BlockPos blockpos2 = new BlockPos(i, j, k); + IBlockState iblockstate = this.worldObj.getBlockState(blockpos2); + + try { + iblockstate.getBlock().onEntityCollidedWithBlock(this.worldObj, blockpos2, iblockstate, + this); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, + "Colliding entity with block"); + CrashReportCategory crashreportcategory = crashreport + .makeCategory("Block being collided with"); + CrashReportCategory.addBlockInfo(crashreportcategory, blockpos2, iblockstate); + throw new ReportedException(crashreport); + } + } + } + } + } + + } + + /** + * + Return whether this entity should NOT trigger a pressure plate or a + * tripwire. + */ + public boolean doesEntityNotTriggerPressurePlate() { + return false; + } + + public EntityItem dropItem(Item itemIn, int size) { + return this.dropItemWithOffset(itemIn, size, 0.0F); + } + + public EntityItem dropItemWithOffset(Item itemIn, int size, float offsetY) { + return this.entityDropItem(new ItemStack(itemIn, size, 0), offsetY); + } + + /** + * + Drops an item at the position of the entity. + */ + public EntityItem entityDropItem(ItemStack itemStackIn, float offsetY) { + if (itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { + EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY + (double) offsetY, this.posZ, + itemStackIn); + entityitem.setDefaultPickupDelay(); + this.worldObj.spawnEntityInWorld(entityitem); + return entityitem; + } else { + return null; + } + } + protected abstract void entityInit(); + public boolean equals(Object object) { + return object instanceof Entity ? ((Entity) object).entityId == this.entityId : false; + } + + /** + * + Removes fire from entity. + */ + public void extinguish() { + this.fire = 0; + } + + public void fall(float distance, float damageMultiplier) { + if (this.riddenByEntity != null) { + this.riddenByEntity.fall(distance, damageMultiplier); + } + + } + + public void func_174817_o(Entity entityIn) { + this.cmdResultStats.func_179671_a(entityIn.getCommandStats()); + } + + public EnumFacing func_181012_aH() { + return this.field_181018_ap; + } + + public void func_181013_g(float parFloat1) { + } + + public Vec3 func_181014_aG() { + return this.field_181017_ao; + } + + public void func_181015_d(BlockPos parBlockPos) { + if (this.timeUntilPortal > 0) { + this.timeUntilPortal = this.getPortalCooldown(); + } else { + if (!this.worldObj.isRemote && !parBlockPos.equals(this.field_181016_an)) { + this.field_181016_an = parBlockPos; + BlockPattern.PatternHelper blockpattern$patternhelper = Blocks.portal.func_181089_f(this.worldObj, + parBlockPos); + double d0 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X + ? (double) blockpattern$patternhelper.func_181117_a().getZ() + : (double) blockpattern$patternhelper.func_181117_a().getX(); + double d1 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X ? this.posZ + : this.posX; + d1 = Math.abs(MathHelper.func_181160_c( + d1 - (double) (blockpattern$patternhelper.getFinger().rotateY() + .getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? 1 : 0), + d0, d0 - (double) blockpattern$patternhelper.func_181118_d())); + double d2 = MathHelper.func_181160_c(this.posY - 1.0D, + (double) blockpattern$patternhelper.func_181117_a().getY(), + (double) (blockpattern$patternhelper.func_181117_a().getY() + - blockpattern$patternhelper.func_181119_e())); + this.field_181017_ao = new Vec3(d1, d2, 0.0D); + this.field_181018_ap = blockpattern$patternhelper.getFinger(); + } + + this.inPortal = true; + } + } + + public int getAir() { + return this.dataWatcher.getWatchableObjectShort(1); + } + + public boolean getAlwaysRenderNameTag() { + return this.dataWatcher.getWatchableObjectByte(3) == 1; + } + + public boolean getAlwaysRenderNameTagForRender() { + return this.getAlwaysRenderNameTag(); + } + + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float var1) { + BlockPos blockpos = new BlockPos(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); + float f = this.worldObj.isBlockLoaded(blockpos) ? this.worldObj.getLightBrightness(blockpos) : 0.0F; + if (DynamicLightsStateManager.isDynamicLightsRender()) { + f = Math.min(f + getEaglerDynamicLightsValueSimple(var1), 1.0f); + } + return f; + } + + public int getBrightnessForRender(float var1) { + BlockPos blockpos = new BlockPos(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); + int i = 0; + if (DynamicLightsStateManager.isDynamicLightsRender()) { + i += (int) (getEaglerDynamicLightsValueSimple(var1) * 15.0f); + } + return this.worldObj.isBlockLoaded(blockpos) ? this.worldObj.getCombinedLight(blockpos, -i) + : (i > 15 ? 240 : (i << 4)); + } + + public float getCollisionBorderSize() { + return 0.1F; + } + + /** + * + Returns the collision bounding box for this entity + */ + public AxisAlignedBB getCollisionBoundingBox() { + return null; + } + + /** + * + Returns a boundingBox used to collide the entity with other entities and + * blocks. This enables the entity to be pushable on contact, like boats or + * minecarts. + */ + public AxisAlignedBB getCollisionBox(Entity entityIn) { + return null; + } + + /** + * + Returns the entity associated with the command sender. MAY BE NULL! + */ + public Entity getCommandSenderEntity() { + return this; + } + + public CommandResultStats getCommandStats() { + return this.cmdResultStats; + } + + public String getCustomNameTag() { + return this.dataWatcher.getWatchableObjectString(2); + } + + public String getCustomNameTagProfanityFilter() { + if (Minecraft.getMinecraft().isEnableProfanityFilter()) { + String str = getCustomNameTag(); + if (str != null) { + if (!str.equals(lastNameTagForFilter)) { + lastNameTagForFilter = str; + lastFilteredNameTagForFilter = ProfanityFilter.getInstance().profanityFilterString(str); + } + return lastFilteredNameTagForFilter; + } else { + return null; + } + } else { + return getCustomNameTag(); + } + } + public DataWatcher getDataWatcher() { return this.dataWatcher; } - public boolean equals(Object object) { - return object instanceof Entity ? ((Entity) object).entityId == this.entityId : false; + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + ChatComponentText chatcomponenttext = new ChatComponentText(this.getName()); + chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); + chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); + return chatcomponenttext; + } + + public IChatComponent getDisplayNameProfanityFilter() { + ChatComponentText chatcomponenttext = new ChatComponentText(this.getNameProfanityFilter()); + chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); + chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); + return chatcomponenttext; + } + + /** + * + Gets the distance to the position. Args: x, y, z + */ + public double getDistance(double x, double y, double z) { + double d0 = this.posX - x; + double d1 = this.posY - y; + double d2 = this.posZ - z; + return (double) MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); + } + + /** + * + Gets the squared distance to the position. Args: x, y, z + */ + public double getDistanceSq(BlockPos pos) { + return pos.distanceSq(this.posX, this.posY, this.posZ); + } + + /** + * + Gets the squared distance to the position. Args: x, y, z + */ + public double getDistanceSq(double x, double y, double z) { + double d0 = this.posX - x; + double d1 = this.posY - y; + double d2 = this.posZ - z; + return d0 * d0 + d1 * d1 + d2 * d2; + } + + public double getDistanceSqToCenter(BlockPos pos) { + return pos.distanceSqToCenter(this.posX, this.posY, this.posZ); + } + + /** + * + Returns the squared distance to the entity. Args: entity + */ + public double getDistanceSqToEntity(Entity entityIn) { + double d0 = this.posX - entityIn.posX; + double d1 = this.posY - entityIn.posY; + double d2 = this.posZ - entityIn.posZ; + return d0 * d0 + d1 * d1 + d2 * d2; + } + + /** + * + Returns the distance to the entity. Args: entity + */ + public float getDistanceToEntity(Entity entityIn) { + float f = (float) (this.posX - entityIn.posX); + float f1 = (float) (this.posY - entityIn.posY); + float f2 = (float) (this.posZ - entityIn.posZ); + return MathHelper.sqrt_float(f * f + f1 * f1 + f2 * f2); + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float size = Math.max(width, height); + if (size < 1.0f) { + return 0.0f; + } + if (this.isBurning()) { + return size / 2.0f; + } + return 0.0f; + } + + public AxisAlignedBB getEntityBoundingBox() { + return this.boundingBox; + } + + public int getEntityId() { + return this.entityId; + } + + /** + * + Returns the string that identifies this Entity's class + */ + protected final String getEntityString() { + return EntityList.getEntityString(this); + } + + /** + * + Get the world, if available. {@code null} is not allowed! If you are + * not an entity in the world, return the overworld + */ + public World getEntityWorld() { + return this.worldObj; + } + + /** + * + Explosion resistance of a block relative to this entity + */ + public float getExplosionResistance(Explosion explosionIn, World worldIn, BlockPos pos, IBlockState blockStateIn) { + return blockStateIn.getBlock().getExplosionResistance(this); + } + + public float getEyeHeight() { + return this.height * 0.85F; + } + + /** + * + Returns true if the flag is active for the entity. Known flags: 0) is + * burning; 1) is sneaking; 2) is riding something; 3) is sprinting; 4) is + * eating + */ + protected boolean getFlag(int flag) { + return (this.dataWatcher.getWatchableObjectByte(0) & 1 << flag) != 0; + } + + public EnumFacing getHorizontalFacing() { + return EnumFacing + .getHorizontal(MathHelper.floor_double((double) (this.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3); + } + + protected HoverEvent getHoverEvent() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + String s = EntityList.getEntityString(this); + nbttagcompound.setString("id", this.getUniqueID().toString()); + if (s != null) { + nbttagcompound.setString("type", s); + } + + nbttagcompound.setString("name", this.getName()); + return new HoverEvent(HoverEvent.Action.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); + } + + /** + * + returns the inventory of this entity (only used in EntityPlayerMP it seems) + */ + public ItemStack[] getInventory() { + return null; + } + + /** + * + interpolated look vector + */ + public Vec3 getLook(float partialTicks) { + if (partialTicks == 1.0F) { + return this.getVectorForRotation(this.rotationPitch, this.rotationYaw); + } else { + float f = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * partialTicks; + float f1 = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * partialTicks; + return this.getVectorForRotation(f, f1); + } + } + + /** + * + returns a (normalized) vector of where this entity is looking + */ + public Vec3 getLookVec() { + return null; + } + + /** + * + The maximum height from where the entity is alowed to jump (used in + * pathfinder) + */ + public int getMaxFallHeight() { + return 3; + } + + /** + * + Return the amount of time this entity should stay in a portal before being + * transported. + */ + public int getMaxInPortalTime() { + return 0; + } + + /** + * + Returns the Y offset from the entity's position for any entity riding this + * one. + */ + public double getMountedYOffset() { + return (double) this.height * 0.75D; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + if (this.hasCustomName()) { + return this.getCustomNameTag(); + } else { + String s = EntityList.getEntityString(this); + if (s == null) { + s = "generic"; + } + + return StatCollector.translateToLocal("entity." + s + ".name"); + } + } + + public String getNameProfanityFilter() { + if (this.hasCustomName()) { + return this.getCustomNameTagProfanityFilter(); + } else { + String s = EntityList.getEntityString(this); + if (s == null) { + s = "generic"; + } + + return StatCollector.translateToLocal("entity." + s + ".name"); + } + } + + public NBTTagCompound getNBTTagCompound() { + return null; + } + + /** + * + Return the Entity parts making up this Entity (currently only for dragons) + */ + public Entity[] getParts() { + return null; + } + + /** + * + Return the amount of cooldown before this entity can use a portal again. + */ + public int getPortalCooldown() { + return 300; + } + + /** + * + Get the position in the world. {@code null} is not allowed! If you + * are not an entity in the world, return the coordinates 0, 0, 0 + */ + public BlockPos getPosition() { + return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); + } + + public Vec3 getPositionEyes(float partialTicks) { + if (partialTicks == 1.0F) { + return new Vec3(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); + } else { + double d0 = this.prevPosX + (this.posX - this.prevPosX) * (double) partialTicks; + double d1 = this.prevPosY + (this.posY - this.prevPosY) * (double) partialTicks + + (double) this.getEyeHeight(); + double d2 = this.prevPosZ + (this.posZ - this.prevPosZ) * (double) partialTicks; + return new Vec3(d0, d1, d2); + } + } + + /** + * + Get the position vector. {@code null} is not allowed! If you are not + * an entity in the world, return 0.0D, 0.0D, 0.0D + */ + public Vec3 getPositionVector() { + return new Vec3(this.posX, this.posY, this.posZ); + } + + public float getRotationYawHead() { + return 0.0F; + } + + protected String getSplashSound() { + return "game.neutral.swim.splash"; + } + + protected String getSwimSound() { + return "game.neutral.swim"; + } + + public EaglercraftUUID getUniqueID() { + return this.entityUniqueID; + } + + /** + * + Creates a Vec3 using the pitch and yaw of the entities rotation. + */ + protected final Vec3 getVectorForRotation(float pitch, float yaw) { + float f = MathHelper.cos(-yaw * 0.017453292F - 3.1415927F); + float f1 = MathHelper.sin(-yaw * 0.017453292F - 3.1415927F); + float f2 = -MathHelper.cos(-pitch * 0.017453292F); + float f3 = MathHelper.sin(-pitch * 0.017453292F); + return new Vec3((double) (f1 * f2), (double) f3, (double) (f * f2)); + } + + /** + * + Returns the Y Offset of this entity. + */ + public double getYOffset() { + return 0.0D; + } + + public void handleStatusUpdate(byte id) { + } + + /** + * + Returns if this entity is in water and will end up adding the waters + * velocity to the entity + */ + public boolean handleWaterMovement() { + if (this.worldObj.handleMaterialAcceleration( + this.getEntityBoundingBox().expand(0.0D, -0.4000000059604645D, 0.0D).contract(0.001D, 0.001D, 0.001D), + Material.water, this)) { + if (!this.inWater && !this.firstUpdate) { + this.resetHeight(); + } + + this.fallDistance = 0.0F; + this.inWater = true; + this.fire = 0; + } else { + this.inWater = false; + } + + return this.inWater; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.dataWatcher.getWatchableObjectString(2).length() > 0; } public int hashCode() { return this.entityId; } - /**+ - * Keeps moving the entity up so it isn't colliding with blocks - * and other requirements for this entity to be spawned (only - * actually used on players though its also on Entity) + /** + * + Called when a player attacks an entity. If this returns true the attack + * will not happen. */ - protected void preparePlayerToSpawn() { - if (this.worldObj != null) { - while (this.posY > 0.0D && this.posY < 256.0D) { - this.setPosition(this.posX, this.posY, this.posZ); - if (this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty()) { - break; - } - - ++this.posY; - } - - this.motionX = this.motionY = this.motionZ = 0.0D; - this.rotationPitch = 0.0F; - } + public boolean hitByEntity(Entity entityIn) { + return false; } - /**+ - * Will get destroyed next tick. + /** + * + New version of interactWith that includes vector information on where + * precisely the player targeted. */ - public void setDead() { - this.isDead = true; + public boolean interactAt(EntityPlayer player, Vec3 targetVec3) { + return false; } - /**+ - * Sets the width and height of the entity. Args: width, height + /** + * + First layer of player interaction */ - protected void setSize(float f, float f1) { - if (f != this.width || f1 != this.height) { - float f2 = this.width; - this.width = f; - this.height = f1; - this.setEntityBoundingBox( - new AxisAlignedBB(this.getEntityBoundingBox().minX, this.getEntityBoundingBox().minY, - this.getEntityBoundingBox().minZ, this.getEntityBoundingBox().minX + (double) this.width, - this.getEntityBoundingBox().minY + (double) this.height, - this.getEntityBoundingBox().minZ + (double) this.width)); - if (this.width > f2 && !this.firstUpdate && !this.worldObj.isRemote) { - this.moveEntity((double) (f2 - this.width), 0.0D, (double) (f2 - this.width)); - } - } - + public boolean interactFirst(EntityPlayer playerIn) { + return false; } - /**+ - * Sets the rotation of the entity. Args: yaw, pitch (both in - * degrees) + /** + * + Returns true if the entity is on fire. Used by render to add the fire + * effect on rendering. */ - protected void setRotation(float yaw, float pitch) { - this.rotationYaw = yaw % 360.0F; - this.rotationPitch = pitch % 360.0F; + public boolean isBurning() { + boolean flag = this.worldObj != null && this.worldObj.isRemote; + return !this.isImmuneToFire && (this.fire > 0 || flag && this.getFlag(0)); } - /**+ - * Sets the x,y,z of the entity from the given parameters. Also - * seems to set up a bounding box. - */ - public void setPosition(double x, double y, double z) { - this.posX = x; - this.posY = y; - this.posZ = z; - float f = this.width / 2.0F; - float f1 = this.height; - this.setEntityBoundingBox( - new AxisAlignedBB(x - (double) f, y, z - (double) f, x + (double) f, y + (double) f1, z + (double) f)); + public boolean isEating() { + return this.getFlag(4); } - /**+ - * Adds 15% to the entity's yaw and subtracts 15% from the - * pitch. Clamps pitch from -90 to 90. Both arguments in - * degrees. + /** + * + Checks whether target entity is alive. */ - public void setAngles(float yaw, float pitch) { - float f = this.rotationPitch; - float f1 = this.rotationYaw; - this.rotationYaw = (float) ((double) this.rotationYaw + (double) yaw * 0.15D); - this.rotationPitch = (float) ((double) this.rotationPitch - (double) pitch * 0.15D); - this.rotationPitch = MathHelper.clamp_float(this.rotationPitch, -90.0F, 90.0F); - this.prevRotationPitch += this.rotationPitch - f; - this.prevRotationYaw += this.rotationYaw - f1; + public boolean isEntityAlive() { + return !this.isDead; } - /**+ - * Called to update the entity's position/logic. + /** + * + Returns true if Entity argument is equal to this Entity */ - public void onUpdate() { - this.onEntityUpdate(); + public boolean isEntityEqual(Entity entityIn) { + return this == entityIn; } - /**+ - * Gets called every tick from main Entity class + /** + * + Checks if this entity is inside of an opaque block */ - public void onEntityUpdate() { - if (this.ridingEntity != null && this.ridingEntity.isDead) { - this.ridingEntity = null; - } + public boolean isEntityInsideOpaqueBlock() { + if (this.noClip) { + return false; + } else { + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(Integer.MIN_VALUE, + Integer.MIN_VALUE, Integer.MIN_VALUE); - this.prevDistanceWalkedModified = this.distanceWalkedModified; - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.prevRotationPitch = this.rotationPitch; - this.prevRotationYaw = this.rotationYaw; - if (!this.worldObj.isRemote && this.worldObj instanceof WorldServer) { - MinecraftServer minecraftserver = ((WorldServer) this.worldObj).getMinecraftServer(); - int i = this.getMaxInPortalTime(); - if (this.inPortal) { - if (minecraftserver.getAllowNether()) { - if (this.ridingEntity == null && this.portalCounter++ >= i) { - this.portalCounter = i; - this.timeUntilPortal = this.getPortalCooldown(); - byte b0; - if (this.worldObj.provider.getDimensionId() == -1) { - b0 = 0; - } else { - b0 = -1; - } - - this.travelToDimension(b0); + for (int i = 0; i < 8; ++i) { + int j = MathHelper.floor_double( + this.posY + (double) (((float) ((i >> 0) % 2) - 0.5F) * 0.1F) + (double) this.getEyeHeight()); + int k = MathHelper + .floor_double(this.posX + (double) (((float) ((i >> 1) % 2) - 0.5F) * this.width * 0.8F)); + int l = MathHelper + .floor_double(this.posZ + (double) (((float) ((i >> 2) % 2) - 0.5F) * this.width * 0.8F)); + if (blockpos$mutableblockpos.getX() != k || blockpos$mutableblockpos.getY() != j + || blockpos$mutableblockpos.getZ() != l) { + blockpos$mutableblockpos.func_181079_c(k, j, l); + if (this.worldObj.getBlockState(blockpos$mutableblockpos).getBlock().isVisuallyOpaque()) { + return true; } - - this.inPortal = false; - } - } else { - if (this.portalCounter > 0) { - this.portalCounter -= 4; - } - - if (this.portalCounter < 0) { - this.portalCounter = 0; } } - if (this.timeUntilPortal > 0) { - --this.timeUntilPortal; - } + return false; } - - this.spawnRunningParticles(); - this.handleWaterMovement(); - if (this.worldObj.isRemote) { - this.fire = 0; - } else if (this.fire > 0) { - if (this.isImmuneToFire) { - this.fire -= 4; - if (this.fire < 0) { - this.fire = 0; - } - } else { - if (this.fire % 20 == 0) { - this.attackEntityFrom(DamageSource.onFire, 1.0F); - } - - --this.fire; - } - } - - if (this.isInLava()) { - this.setOnFireFromLava(); - this.fallDistance *= 0.5F; - } - - if (this.posY < -64.0D) { - this.kill(); - } - - if (!this.worldObj.isRemote) { - this.setFlag(0, this.fire > 0); - } - - this.firstUpdate = false; } - /**+ - * Return the amount of time this entity should stay in a portal - * before being transported. + public boolean isEntityInvulnerable(DamageSource source) { + return this.invulnerable && source != DamageSource.outOfWorld && !source.isCreativePlayer(); + } + + public boolean isImmuneToExplosions() { + return false; + } + + public final boolean isImmuneToFire() { + return this.isImmuneToFire; + } + + public boolean isInLava() { + return this.worldObj.isMaterialInBB( + this.getEntityBoundingBox().expand(-0.10000000149011612D, -0.4000000059604645D, -0.10000000149011612D), + Material.lava); + } + + public boolean isInRangeToRender3d(double x, double y, double z) { + double d0 = this.posX - x; + double d1 = this.posY - y; + double d2 = this.posZ - z; + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + return this.isInRangeToRenderDist(d3); + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance */ - public int getMaxInPortalTime() { - return 0; + public boolean isInRangeToRenderDist(double distance) { + double d0 = this.getEntityBoundingBox().getAverageEdgeLength(); + if (Double.isNaN(d0)) { + d0 = 1.0D; + } + + d0 = d0 * 64.0D * this.renderDistanceWeight; + return distance < d0 * d0; } - /**+ - * Called whenever the entity is walking inside of lava. + /** + * + Checks if the current block the entity is within of the specified material + * type */ - protected void setOnFireFromLava() { - if (!this.isImmuneToFire) { - this.attackEntityFrom(DamageSource.lava, 4.0F); - this.setFire(15); + public boolean isInsideOfMaterial(Material materialIn) { + double d0 = this.posY + (double) this.getEyeHeight(); + BlockPos blockpos = new BlockPos(this.posX, d0, this.posZ); + IBlockState iblockstate = this.worldObj.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + if (block.getMaterial() == materialIn) { + float f = BlockLiquid.getLiquidHeightPercent(iblockstate.getBlock().getMetaFromState(iblockstate)) + - 0.11111111F; + float f1 = (float) (blockpos.getY() + 1) - f; + boolean flag = d0 < (double) f1; + return !flag && this instanceof EntityPlayer ? false : flag; + } else { + return false; } } - /**+ - * Sets entity to burn for x amount of seconds, cannot lower - * amount of existing fire. - */ - public void setFire(int seconds) { - int i = seconds * 20; - i = EnchantmentProtection.getFireTimeForEntity(this, i); - if (this.fire < i) { - this.fire = i; - } - + public boolean isInvisible() { + return this.getFlag(5); } - /**+ - * Removes fire from entity. + /** + * + Only used by renderer in EntityLivingBase subclasses.\nDetermines if an + * entity is visible or not to a specfic player, if the entity is normally + * invisible.\nFor EntityLivingBase subclasses, returning false when invisible + * will render the entity semitransparent. */ - public void extinguish() { - this.fire = 0; + public boolean isInvisibleToPlayer(EntityPlayer player) { + return player.isSpectator() ? false : this.isInvisible(); } - /**+ - * sets the dead flag. Used when you fall off the bottom of the - * world. + /** + * + Checks if this entity is inside water (if inWater field is true as a result + * of handleWaterMovement() returning true) */ - protected void kill() { - this.setDead(); + public boolean isInWater() { + return this.inWater; } - /**+ - * Checks if the offset position from the entity's current - * position is inside of liquid. Args: x, y, z + /** + * + Determines if a liquid is present within the specified AxisAlignedBB. + */ + private boolean isLiquidPresentInAABB(AxisAlignedBB bb) { + return this.worldObj.getCollidingBoundingBoxes(this, bb).isEmpty() && !this.worldObj.isAnyLiquid(bb); + } + + /** + * + Checks if the offset position from the entity's current position is inside + * of liquid. Args: x, y, z */ public boolean isOffsetPositionInLiquid(double x, double y, double z) { AxisAlignedBB axisalignedbb = this.getEntityBoundingBox().offset(x, y, z); return this.isLiquidPresentInAABB(axisalignedbb); } - /**+ - * Determines if a liquid is present within the specified - * AxisAlignedBB. - */ - private boolean isLiquidPresentInAABB(AxisAlignedBB bb) { - return this.worldObj.getCollidingBoundingBoxes(this, bb).isEmpty() && !this.worldObj.isAnyLiquid(bb); + public boolean isOutsideBorder() { + return this.isOutsideBorder; } - /**+ - * Tries to moves the entity by the passed in displacement. - * Args: x, y, z + public boolean isPushedByWater() { + return true; + } + + /** + * + Returns true if the entity is riding another entity, used by render to + * rotate the legs to be in 'sit' position for players. + */ + public boolean isRiding() { + return this.ridingEntity != null; + } + + /** + * + + * + * @return True if this entity will not play sounds + */ + public boolean isSilent() { + return this.dataWatcher.getWatchableObjectByte(4) == 1; + } + + /** + * + Returns if this entity is sneaking. + */ + public boolean isSneaking() { + return this.getFlag(1); + } + + public boolean isSpectatedByPlayer(EntityPlayerMP var1) { + return true; + } + + /** + * + Get if the Entity is sprinting. + */ + public boolean isSprinting() { + return this.getFlag(3); + } + + /** + * + Checks if this entity is either in water or on an open air block in rain + * (used in wolves). + */ + public boolean isWet() { + return this.inWater || this.worldObj.canLightningStrike(new BlockPos(this.posX, this.posY, this.posZ)) + || this.worldObj + .canLightningStrike(new BlockPos(this.posX, this.posY + (double) this.height, this.posZ)); + } + + /** + * + sets the dead flag. Used when you fall off the bottom of the world. + */ + protected void kill() { + this.setDead(); + } + + /** + * + Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. + */ + public void mountEntity(Entity entity) { + this.entityRiderPitchDelta = 0.0D; + this.entityRiderYawDelta = 0.0D; + if (entity == null) { + if (this.ridingEntity != null) { + this.setLocationAndAngles(this.ridingEntity.posX, + this.ridingEntity.getEntityBoundingBox().minY + (double) this.ridingEntity.height, + this.ridingEntity.posZ, this.rotationYaw, this.rotationPitch); + this.ridingEntity.riddenByEntity = null; + } + + this.ridingEntity = null; + } else { + if (this.ridingEntity != null) { + this.ridingEntity.riddenByEntity = null; + } + + if (entity != null) { + for (Entity entity1 = entity.ridingEntity; entity1 != null; entity1 = entity1.ridingEntity) { + if (entity1 == this) { + return; + } + } + } + + this.ridingEntity = entity; + entity.riddenByEntity = this; + } + } + + /** + * + Tries to moves the entity by the passed in displacement. Args: x, y, z */ public void moveEntity(double x, double y, double z) { if (this.noClip) { @@ -721,270 +1496,8 @@ public abstract class Entity implements ICommandSender { } } - /**+ - * Resets the entity's position to the center (planar) and - * bottom (vertical) points of its bounding box. - */ - private void resetPositionToBB() { - this.posX = (this.getEntityBoundingBox().minX + this.getEntityBoundingBox().maxX) / 2.0D; - this.posY = this.getEntityBoundingBox().minY; - this.posZ = (this.getEntityBoundingBox().minZ + this.getEntityBoundingBox().maxZ) / 2.0D; - } - - protected String getSwimSound() { - return "game.neutral.swim"; - } - - protected void doBlockCollisions() { - BlockPos blockpos = new BlockPos(this.getEntityBoundingBox().minX + 0.001D, - this.getEntityBoundingBox().minY + 0.001D, this.getEntityBoundingBox().minZ + 0.001D); - BlockPos blockpos1 = new BlockPos(this.getEntityBoundingBox().maxX - 0.001D, - this.getEntityBoundingBox().maxY - 0.001D, this.getEntityBoundingBox().maxZ - 0.001D); - if (this.worldObj.isAreaLoaded(blockpos, blockpos1)) { - for (int i = blockpos.getX(); i <= blockpos1.getX(); ++i) { - for (int j = blockpos.getY(); j <= blockpos1.getY(); ++j) { - for (int k = blockpos.getZ(); k <= blockpos1.getZ(); ++k) { - BlockPos blockpos2 = new BlockPos(i, j, k); - IBlockState iblockstate = this.worldObj.getBlockState(blockpos2); - - try { - iblockstate.getBlock().onEntityCollidedWithBlock(this.worldObj, blockpos2, iblockstate, - this); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, - "Colliding entity with block"); - CrashReportCategory crashreportcategory = crashreport - .makeCategory("Block being collided with"); - CrashReportCategory.addBlockInfo(crashreportcategory, blockpos2, iblockstate); - throw new ReportedException(crashreport); - } - } - } - } - } - - } - - protected void playStepSound(BlockPos pos, Block blockIn) { - Block.SoundType block$soundtype = blockIn.stepSound; - if (this.worldObj.getBlockState(pos.up()).getBlock() == Blocks.snow_layer) { - block$soundtype = Blocks.snow_layer.stepSound; - this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.15F, - block$soundtype.getFrequency()); - } else if (!blockIn.getMaterial().isLiquid()) { - this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.15F, - block$soundtype.getFrequency()); - } - - } - - public void playSound(String s, float f, float f1) { - if (!this.isSilent()) { - this.worldObj.playSoundAtEntity(this, s, f, f1); - } - - } - - /**+ - * @return True if this entity will not play sounds - */ - public boolean isSilent() { - return this.dataWatcher.getWatchableObjectByte(4) == 1; - } - - /**+ - * When set to true the entity will not play sounds. - */ - public void setSilent(boolean isSilent) { - this.dataWatcher.updateObject(4, Byte.valueOf((byte) (isSilent ? 1 : 0))); - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return true; - } - - protected void updateFallState(double d0, boolean flag, Block block, BlockPos blockpos) { - if (flag) { - if (this.fallDistance > 0.0F) { - if (block != null) { - block.onFallenUpon(this.worldObj, blockpos, this, this.fallDistance); - } else { - this.fall(this.fallDistance, 1.0F); - } - - this.fallDistance = 0.0F; - } - } else if (d0 < 0.0D) { - this.fallDistance = (float) ((double) this.fallDistance - d0); - } - - } - - /**+ - * Returns the collision bounding box for this entity - */ - public AxisAlignedBB getCollisionBoundingBox() { - return null; - } - - /**+ - * Will deal the specified amount of damage to the entity if the - * entity isn't immune to fire damage. Args: amountDamage - */ - protected void dealFireDamage(int amount) { - if (!this.isImmuneToFire) { - this.attackEntityFrom(DamageSource.inFire, (float) amount); - } - - } - - public final boolean isImmuneToFire() { - return this.isImmuneToFire; - } - - public void fall(float distance, float damageMultiplier) { - if (this.riddenByEntity != null) { - this.riddenByEntity.fall(distance, damageMultiplier); - } - - } - - /**+ - * Checks if this entity is either in water or on an open air - * block in rain (used in wolves). - */ - public boolean isWet() { - return this.inWater || this.worldObj.canLightningStrike(new BlockPos(this.posX, this.posY, this.posZ)) - || this.worldObj - .canLightningStrike(new BlockPos(this.posX, this.posY + (double) this.height, this.posZ)); - } - - /**+ - * Checks if this entity is inside water (if inWater field is - * true as a result of handleWaterMovement() returning true) - */ - public boolean isInWater() { - return this.inWater; - } - - /**+ - * Returns if this entity is in water and will end up adding the - * waters velocity to the entity - */ - public boolean handleWaterMovement() { - if (this.worldObj.handleMaterialAcceleration( - this.getEntityBoundingBox().expand(0.0D, -0.4000000059604645D, 0.0D).contract(0.001D, 0.001D, 0.001D), - Material.water, this)) { - if (!this.inWater && !this.firstUpdate) { - this.resetHeight(); - } - - this.fallDistance = 0.0F; - this.inWater = true; - this.fire = 0; - } else { - this.inWater = false; - } - - return this.inWater; - } - - /**+ - * sets the players height back to normal after doing things - * like sleeping and dieing - */ - protected void resetHeight() { - float f = MathHelper.sqrt_double(this.motionX * this.motionX * 0.20000000298023224D - + this.motionY * this.motionY + this.motionZ * this.motionZ * 0.20000000298023224D) * 0.2F; - if (f > 1.0F) { - f = 1.0F; - } - - this.playSound(this.getSplashSound(), f, 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.4F); - float f1 = (float) MathHelper.floor_double(this.getEntityBoundingBox().minY); - - for (int i = 0; (float) i < 1.0F + this.width * 20.0F; ++i) { - float f2 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; - float f3 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; - this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + (double) f2, (double) (f1 + 1.0F), - this.posZ + (double) f3, this.motionX, this.motionY - (double) (this.rand.nextFloat() * 0.2F), - this.motionZ, new int[0]); - } - - for (int j = 0; (float) j < 1.0F + this.width * 20.0F; ++j) { - float f4 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; - float f5 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; - this.worldObj.spawnParticle(EnumParticleTypes.WATER_SPLASH, this.posX + (double) f4, (double) (f1 + 1.0F), - this.posZ + (double) f5, this.motionX, this.motionY, this.motionZ, new int[0]); - } - - } - - /**+ - * Attempts to create sprinting particles if the entity is - * sprinting and not in water. - */ - public void spawnRunningParticles() { - if (this.isSprinting() && !this.isInWater()) { - this.createRunningParticles(); - } - - } - - protected void createRunningParticles() { - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); - int k = MathHelper.floor_double(this.posZ); - BlockPos blockpos = new BlockPos(i, j, k); - IBlockState iblockstate = this.worldObj.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - if (block.getRenderType() != -1) { - this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, - this.posX + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, - this.getEntityBoundingBox().minY + 0.1D, - this.posZ + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, -this.motionX * 4.0D, - 1.5D, -this.motionZ * 4.0D, new int[] { Block.getStateId(iblockstate) }); - } - - } - - protected String getSplashSound() { - return "game.neutral.swim.splash"; - } - - /**+ - * Checks if the current block the entity is within of the - * specified material type - */ - public boolean isInsideOfMaterial(Material materialIn) { - double d0 = this.posY + (double) this.getEyeHeight(); - BlockPos blockpos = new BlockPos(this.posX, d0, this.posZ); - IBlockState iblockstate = this.worldObj.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - if (block.getMaterial() == materialIn) { - float f = BlockLiquid.getLiquidHeightPercent(iblockstate.getBlock().getMetaFromState(iblockstate)) - - 0.11111111F; - float f1 = (float) (blockpos.getY() + 1) - f; - boolean flag = d0 < (double) f1; - return !flag && this instanceof EntityPlayer ? false : flag; - } else { - return false; - } - } - - public boolean isInLava() { - return this.worldObj.isMaterialInBB( - this.getEntityBoundingBox().expand(-0.10000000149011612D, -0.4000000059604645D, -0.10000000149011612D), - Material.lava); - } - - /**+ - * Used in both water and by flying objects + /** + * + Used in both water and by flying objects */ public void moveFlying(float strafe, float forward, float friction) { float f = strafe * strafe + forward * forward; @@ -1004,232 +1517,271 @@ public abstract class Entity implements ICommandSender { } } - public int getBrightnessForRender(float var1) { - BlockPos blockpos = new BlockPos(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); - int i = 0; - if (DynamicLightsStateManager.isDynamicLightsRender()) { - i += (int) (getEaglerDynamicLightsValueSimple(var1) * 15.0f); - } - return this.worldObj.isBlockLoaded(blockpos) ? this.worldObj.getCombinedLight(blockpos, -i) - : (i > 15 ? 240 : (i << 4)); - } - - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float var1) { - BlockPos blockpos = new BlockPos(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); - float f = this.worldObj.isBlockLoaded(blockpos) ? this.worldObj.getLightBrightness(blockpos) : 0.0F; - if (DynamicLightsStateManager.isDynamicLightsRender()) { - f = Math.min(f + getEaglerDynamicLightsValueSimple(var1), 1.0f); - } - return f; - } - - /**+ - * Sets the reference to the World object. - */ - public void setWorld(World worldIn) { - this.worldObj = worldIn; - } - - /**+ - * Sets the entity's position and rotation. - */ - public void setPositionAndRotation(double x, double y, double z, float yaw, float pitch) { - this.prevPosX = this.posX = x; - this.prevPosY = this.posY = y; - this.prevPosZ = this.posZ = z; - this.prevRotationYaw = this.rotationYaw = yaw; - this.prevRotationPitch = this.rotationPitch = pitch; - double d0 = (double) (this.prevRotationYaw - yaw); - if (d0 < -180.0D) { - this.prevRotationYaw += 360.0F; - } - - if (d0 >= 180.0D) { - this.prevRotationYaw -= 360.0F; - } - - this.setPosition(this.posX, this.posY, this.posZ); - this.setRotation(yaw, pitch); - } - public void moveToBlockPosAndAngles(BlockPos pos, float rotationYawIn, float rotationPitchIn) { this.setLocationAndAngles((double) pos.getX() + 0.5D, (double) pos.getY(), (double) pos.getZ() + 0.5D, rotationYawIn, rotationPitchIn); } - /**+ - * Sets the location and Yaw/Pitch of an entity in the world + /** + * + creates a NBT list from the array of doubles passed to this function */ - public void setLocationAndAngles(double x, double y, double z, float yaw, float pitch) { - this.lastTickPosX = this.prevPosX = this.posX = x; - this.lastTickPosY = this.prevPosY = this.posY = y; - this.lastTickPosZ = this.prevPosZ = this.posZ = z; - this.rotationYaw = yaw; - this.rotationPitch = pitch; - this.setPosition(this.posX, this.posY, this.posZ); + protected NBTTagList newDoubleNBTList(double... numbers) { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < numbers.length; ++i) { + nbttaglist.appendTag(new NBTTagDouble(numbers[i])); + } + + return nbttaglist; } - /**+ - * Returns the distance to the entity. Args: entity + /** + * + Returns a new NBTTagList filled with the specified floats */ - public float getDistanceToEntity(Entity entityIn) { - float f = (float) (this.posX - entityIn.posX); - float f1 = (float) (this.posY - entityIn.posY); - float f2 = (float) (this.posZ - entityIn.posZ); - return MathHelper.sqrt_float(f * f + f1 * f1 + f2 * f2); + protected NBTTagList newFloatNBTList(float... numbers) { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < numbers.length; ++i) { + nbttaglist.appendTag(new NBTTagFloat(numbers[i])); + } + + return nbttaglist; } - /**+ - * Gets the squared distance to the position. Args: x, y, z - */ - public double getDistanceSq(double x, double y, double z) { - double d0 = this.posX - x; - double d1 = this.posY - y; - double d2 = this.posZ - z; - return d0 * d0 + d1 * d1 + d2 * d2; + public void onChunkLoad() { } - /**+ - * Gets the squared distance to the position. Args: x, y, z - */ - public double getDistanceSq(BlockPos pos) { - return pos.distanceSq(this.posX, this.posY, this.posZ); - } - - public double getDistanceSqToCenter(BlockPos pos) { - return pos.distanceSqToCenter(this.posX, this.posY, this.posZ); - } - - /**+ - * Gets the distance to the position. Args: x, y, z - */ - public double getDistance(double x, double y, double z) { - double d0 = this.posX - x; - double d1 = this.posY - y; - double d2 = this.posZ - z; - return (double) MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); - } - - /**+ - * Returns the squared distance to the entity. Args: entity - */ - public double getDistanceSqToEntity(Entity entityIn) { - double d0 = this.posX - entityIn.posX; - double d1 = this.posY - entityIn.posY; - double d2 = this.posZ - entityIn.posZ; - return d0 * d0 + d1 * d1 + d2 * d2; - } - - /**+ - * Called by a player entity when they collide with an entity + /** + * + Called by a player entity when they collide with an entity */ public void onCollideWithPlayer(EntityPlayer parEntityPlayer) { } - /**+ - * Applies a velocity to each of the entities pushing them away - * from each other. Args: entity + public void onDataWatcherUpdate(int dataID) { + } + + /** + * + Gets called every tick from main Entity class */ - public void applyEntityCollision(Entity entityIn) { - if (entityIn.riddenByEntity != this && entityIn.ridingEntity != this) { - if (!entityIn.noClip && !this.noClip) { - double d0 = entityIn.posX - this.posX; - double d1 = entityIn.posZ - this.posZ; - double d2 = MathHelper.abs_max(d0, d1); - if (d2 >= 0.009999999776482582D) { - d2 = (double) MathHelper.sqrt_double(d2); - d0 = d0 / d2; - d1 = d1 / d2; - double d3 = 1.0D / d2; - if (d3 > 1.0D) { - d3 = 1.0D; + public void onEntityUpdate() { + if (this.ridingEntity != null && this.ridingEntity.isDead) { + this.ridingEntity = null; + } + + this.prevDistanceWalkedModified = this.distanceWalkedModified; + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.prevRotationPitch = this.rotationPitch; + this.prevRotationYaw = this.rotationYaw; + if (!this.worldObj.isRemote && this.worldObj instanceof WorldServer) { + MinecraftServer minecraftserver = ((WorldServer) this.worldObj).getMinecraftServer(); + int i = this.getMaxInPortalTime(); + if (this.inPortal) { + if (minecraftserver.getAllowNether()) { + if (this.ridingEntity == null && this.portalCounter++ >= i) { + this.portalCounter = i; + this.timeUntilPortal = this.getPortalCooldown(); + byte b0; + if (this.worldObj.provider.getDimensionId() == -1) { + b0 = 0; + } else { + b0 = -1; + } + + this.travelToDimension(b0); } - d0 = d0 * d3; - d1 = d1 * d3; - d0 = d0 * 0.05000000074505806D; - d1 = d1 * 0.05000000074505806D; - d0 = d0 * (double) (1.0F - this.entityCollisionReduction); - d1 = d1 * (double) (1.0F - this.entityCollisionReduction); - if (this.riddenByEntity == null) { - this.addVelocity(-d0, 0.0D, -d1); - } - - if (entityIn.riddenByEntity == null) { - entityIn.addVelocity(d0, 0.0D, d1); - } + this.inPortal = false; + } + } else { + if (this.portalCounter > 0) { + this.portalCounter -= 4; } + if (this.portalCounter < 0) { + this.portalCounter = 0; + } + } + + if (this.timeUntilPortal > 0) { + --this.timeUntilPortal; } } + + this.spawnRunningParticles(); + this.handleWaterMovement(); + if (this.worldObj.isRemote) { + this.fire = 0; + } else if (this.fire > 0) { + if (this.isImmuneToFire) { + this.fire -= 4; + if (this.fire < 0) { + this.fire = 0; + } + } else { + if (this.fire % 20 == 0) { + this.attackEntityFrom(DamageSource.onFire, 1.0F); + } + + --this.fire; + } + } + + if (this.isInLava()) { + this.setOnFireFromLava(); + this.fallDistance *= 0.5F; + } + + if (this.posY < -64.0D) { + this.kill(); + } + + if (!this.worldObj.isRemote) { + this.setFlag(0, this.fire > 0); + } + + this.firstUpdate = false; } - /**+ - * Adds to the current velocity of the entity. Args: x, y, z + /** + * + Called by the /kill command. */ - public void addVelocity(double x, double y, double z) { - this.motionX += x; - this.motionY += y; - this.motionZ += z; - this.isAirBorne = true; + public void onKillCommand() { + this.setDead(); } - /**+ - * Sets that this entity has been attacked. + /** + * + This method gets called when the entity kills another one. */ - protected void setBeenAttacked() { - this.velocityChanged = true; + public void onKillEntity(EntityLivingBase entityLivingIn) { } - /**+ - * Called when the entity is attacked. + /** + * + Called when a lightning bolt hits the entity. */ - public boolean attackEntityFrom(DamageSource damagesource, float var2) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - this.setBeenAttacked(); - return false; + public void onStruckByLightning(EntityLightningBolt lightningBolt) { + this.attackEntityFrom(DamageSource.lightningBolt, 5.0F); + ++this.fire; + if (this.fire == 0) { + this.setFire(8); + } + + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.onEntityUpdate(); + } + + /** + * + Setups the entity to do the hurt animation. Only used by packets in + * multiplayer. + */ + public void performHurtAnimation() { + } + + public void playSound(String s, float f, float f1) { + if (!this.isSilent()) { + this.worldObj.playSoundAtEntity(this, s, f, f1); + } + + } + + protected void playStepSound(BlockPos pos, Block blockIn) { + Block.SoundType block$soundtype = blockIn.stepSound; + if (this.worldObj.getBlockState(pos.up()).getBlock() == Blocks.snow_layer) { + block$soundtype = Blocks.snow_layer.stepSound; + this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.15F, + block$soundtype.getFrequency()); + } else if (!blockIn.getMaterial().isLiquid()) { + this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.15F, + block$soundtype.getFrequency()); + } + + } + + /** + * + Keeps moving the entity up so it isn't colliding with blocks and other + * requirements for this entity to be spawned (only actually used on players + * though its also on Entity) + */ + protected void preparePlayerToSpawn() { + if (this.worldObj != null) { + while (this.posY > 0.0D && this.posY < 256.0D) { + this.setPosition(this.posX, this.posY, this.posZ); + if (this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty()) { + break; + } + + ++this.posY; + } + + this.motionX = this.motionY = this.motionZ = 0.0D; + this.rotationPitch = 0.0F; } } - /**+ - * interpolated look vector - */ - public Vec3 getLook(float partialTicks) { - if (partialTicks == 1.0F) { - return this.getVectorForRotation(this.rotationPitch, this.rotationYaw); + protected boolean pushOutOfBlocks(double d0, double d1, double d2) { + BlockPos blockpos = new BlockPos(d0, d1, d2); + double d3 = d0 - (double) blockpos.getX(); + double d4 = d1 - (double) blockpos.getY(); + double d5 = d2 - (double) blockpos.getZ(); + List list = this.worldObj.func_147461_a(this.getEntityBoundingBox()); + if (list.isEmpty() && !this.worldObj.isBlockFullCube(blockpos)) { + return false; } else { - float f = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * partialTicks; - float f1 = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * partialTicks; - return this.getVectorForRotation(f, f1); - } - } + byte b0 = 3; + double d6 = 9999.0D; + if (!this.worldObj.isBlockFullCube(blockpos.west()) && d3 < d6) { + d6 = d3; + b0 = 0; + } - /**+ - * Creates a Vec3 using the pitch and yaw of the entities - * rotation. - */ - protected final Vec3 getVectorForRotation(float pitch, float yaw) { - float f = MathHelper.cos(-yaw * 0.017453292F - 3.1415927F); - float f1 = MathHelper.sin(-yaw * 0.017453292F - 3.1415927F); - float f2 = -MathHelper.cos(-pitch * 0.017453292F); - float f3 = MathHelper.sin(-pitch * 0.017453292F); - return new Vec3((double) (f1 * f2), (double) f3, (double) (f * f2)); - } + if (!this.worldObj.isBlockFullCube(blockpos.east()) && 1.0D - d3 < d6) { + d6 = 1.0D - d3; + b0 = 1; + } - public Vec3 getPositionEyes(float partialTicks) { - if (partialTicks == 1.0F) { - return new Vec3(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); - } else { - double d0 = this.prevPosX + (this.posX - this.prevPosX) * (double) partialTicks; - double d1 = this.prevPosY + (this.posY - this.prevPosY) * (double) partialTicks - + (double) this.getEyeHeight(); - double d2 = this.prevPosZ + (this.posZ - this.prevPosZ) * (double) partialTicks; - return new Vec3(d0, d1, d2); + if (!this.worldObj.isBlockFullCube(blockpos.up()) && 1.0D - d4 < d6) { + d6 = 1.0D - d4; + b0 = 3; + } + + if (!this.worldObj.isBlockFullCube(blockpos.north()) && d5 < d6) { + d6 = d5; + b0 = 4; + } + + if (!this.worldObj.isBlockFullCube(blockpos.south()) && 1.0D - d5 < d6) { + d6 = 1.0D - d5; + b0 = 5; + } + + float f = this.rand.nextFloat() * 0.2F + 0.1F; + if (b0 == 0) { + this.motionX = (double) (-f); + } + + if (b0 == 1) { + this.motionX = (double) f; + } + + if (b0 == 3) { + this.motionY = (double) f; + } + + if (b0 == 4) { + this.motionZ = (double) (-f); + } + + if (b0 == 5) { + this.motionZ = (double) f; + } + + return true; } } @@ -1241,133 +1793,11 @@ public abstract class Entity implements ICommandSender { return this.worldObj.rayTraceBlocks(vec3, vec32, false, false, true); } - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return false; - } + protected abstract void readEntityFromNBT(NBTTagCompound var1); - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. - */ - public boolean canBePushed() { - return false; - } - - /**+ - * Adds a value to the player score. Currently not actually used - * and the entity passed in does nothing. Args: entity, - * scoreToAdd - */ - public void addToPlayerScore(Entity entityIn, int amount) { - } - - public boolean isInRangeToRender3d(double x, double y, double z) { - double d0 = this.posX - x; - double d1 = this.posY - y; - double d2 = this.posZ - z; - double d3 = d0 * d0 + d1 * d1 + d2 * d2; - return this.isInRangeToRenderDist(d3); - } - - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double distance) { - double d0 = this.getEntityBoundingBox().getAverageEdgeLength(); - if (Double.isNaN(d0)) { - d0 = 1.0D; - } - - d0 = d0 * 64.0D * this.renderDistanceWeight; - return distance < d0 * d0; - } - - /**+ - * Like writeToNBTOptional but does not check if the entity is - * ridden. Used for saving ridden entities with their riders. - */ - public boolean writeMountToNBT(NBTTagCompound tagCompund) { - String s = this.getEntityString(); - if (!this.isDead && s != null) { - tagCompund.setString("id", s); - this.writeToNBT(tagCompund); - return true; - } else { - return false; - } - } - - /**+ - * Either write this entity to the NBT tag given and return - * true, or return false without doing anything. If this returns - * false the entity is not saved on disk. Ridden entities return - * false here as they are saved with their rider. - */ - public boolean writeToNBTOptional(NBTTagCompound tagCompund) { - String s = this.getEntityString(); - if (!this.isDead && s != null && this.riddenByEntity == null) { - tagCompund.setString("id", s); - this.writeToNBT(tagCompund); - return true; - } else { - return false; - } - } - - /**+ - * Save the entity to NBT (calls an abstract helper method to - * write extra data) - */ - public void writeToNBT(NBTTagCompound tagCompund) { - try { - tagCompund.setTag("Pos", this.newDoubleNBTList(new double[] { this.posX, this.posY, this.posZ })); - tagCompund.setTag("Motion", - this.newDoubleNBTList(new double[] { this.motionX, this.motionY, this.motionZ })); - tagCompund.setTag("Rotation", this.newFloatNBTList(new float[] { this.rotationYaw, this.rotationPitch })); - tagCompund.setFloat("FallDistance", this.fallDistance); - tagCompund.setShort("Fire", (short) this.fire); - tagCompund.setShort("Air", (short) this.getAir()); - tagCompund.setBoolean("OnGround", this.onGround); - tagCompund.setInteger("Dimension", this.dimension); - tagCompund.setBoolean("Invulnerable", this.invulnerable); - tagCompund.setInteger("PortalCooldown", this.timeUntilPortal); - tagCompund.setLong("UUIDMost", this.getUniqueID().getMostSignificantBits()); - tagCompund.setLong("UUIDLeast", this.getUniqueID().getLeastSignificantBits()); - if (this.getCustomNameTag() != null && this.getCustomNameTag().length() > 0) { - tagCompund.setString("CustomName", this.getCustomNameTag()); - tagCompund.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); - } - - this.cmdResultStats.writeStatsToNBT(tagCompund); - if (this.isSilent()) { - tagCompund.setBoolean("Silent", this.isSilent()); - } - - this.writeEntityToNBT(tagCompund); - if (this.ridingEntity != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - if (this.ridingEntity.writeMountToNBT(nbttagcompound)) { - tagCompund.setTag("Riding", nbttagcompound); - } - } - - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Saving entity NBT"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being saved"); - this.addEntityCrashInfo(crashreportcategory); - throw new ReportedException(crashreport); - } - } - - /**+ - * Reads the entity from NBT (calls an abstract helper method to - * read specialized data) + /** + * + Reads the entity from NBT (calls an abstract helper method to read + * specialized data) */ public void readFromNBT(NBTTagCompound tagCompund) { try { @@ -1432,129 +1862,443 @@ public abstract class Entity implements ICommandSender { } } + public void renderDynamicLightsEagler(float partialTicks, boolean isInFrustum) { + double entityX = prevPosX + (posX - prevPosX) * (double) partialTicks; + double entityY = prevPosY + (posY - prevPosY) * (double) partialTicks; + double entityZ = prevPosZ + (posZ - prevPosZ) * (double) partialTicks; + double entityX2 = entityX - TileEntityRendererDispatcher.staticPlayerX; + double entityY2 = entityY - TileEntityRendererDispatcher.staticPlayerY; + double entityZ2 = entityZ - TileEntityRendererDispatcher.staticPlayerZ; + if (entityX2 * entityX2 + entityY2 * entityY2 + + entityZ2 * entityZ2 < (isInFrustum ? (64.0 * 64.0) : (24.0 * 24.0))) { + renderDynamicLightsEaglerAt(entityX, entityY, entityZ, entityX2, entityY2, entityZ2, partialTicks, + isInFrustum); + } + } + + protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, + double renderY, double renderZ, float partialTicks, boolean isInFrustum) { + float size = Math.max(width, height); + if (size < 1.0f && !isInFrustum) { + return; + } + if (this.isBurning()) { + float mag = 5.0f * size; + DynamicLightManager.renderDynamicLight("entity_" + entityId + "_fire", entityX, entityY + height * 0.75, + entityZ, mag, 0.487f * mag, 0.1411f * mag, false); + } + } + + public void renderDynamicLightsEaglerSimple(float partialTicks) { + double entityX = prevPosX + (posX - prevPosX) * (double) partialTicks; + double entityY = prevPosY + (posY - prevPosY) * (double) partialTicks; + double entityZ = prevPosZ + (posZ - prevPosZ) * (double) partialTicks; + renderDynamicLightsEaglerSimpleAt(entityX, entityY, entityZ, partialTicks); + } + + protected void renderDynamicLightsEaglerSimpleAt(double entityX, double entityY, double entityZ, + float partialTicks) { + float renderBrightness = this.getEaglerDynamicLightsValueSimple(partialTicks); + if (renderBrightness > 0.1f) { + DynamicLightsStateManager.renderDynamicLight("entity_" + entityId + "_lightmap", entityX, + entityY + height * 0.85, entityZ, renderBrightness * 13.0f); + } + } + + public boolean replaceItemInInventory(int inventorySlot, ItemStack itemStackIn) { + return false; + } + + /** + * + sets the players height back to normal after doing things like sleeping and + * dieing + */ + protected void resetHeight() { + float f = MathHelper.sqrt_double(this.motionX * this.motionX * 0.20000000298023224D + + this.motionY * this.motionY + this.motionZ * this.motionZ * 0.20000000298023224D) * 0.2F; + if (f > 1.0F) { + f = 1.0F; + } + + this.playSound(this.getSplashSound(), f, 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.4F); + float f1 = (float) MathHelper.floor_double(this.getEntityBoundingBox().minY); + + for (int i = 0; (float) i < 1.0F + this.width * 20.0F; ++i) { + float f2 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; + float f3 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; + this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + (double) f2, (double) (f1 + 1.0F), + this.posZ + (double) f3, this.motionX, this.motionY - (double) (this.rand.nextFloat() * 0.2F), + this.motionZ, new int[0]); + } + + for (int j = 0; (float) j < 1.0F + this.width * 20.0F; ++j) { + float f4 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; + float f5 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width; + this.worldObj.spawnParticle(EnumParticleTypes.WATER_SPLASH, this.posX + (double) f4, (double) (f1 + 1.0F), + this.posZ + (double) f5, this.motionX, this.motionY, this.motionZ, new int[0]); + } + + } + + /** + * + Resets the entity's position to the center (planar) and bottom (vertical) + * points of its bounding box. + */ + private void resetPositionToBB() { + this.posX = (this.getEntityBoundingBox().minX + this.getEntityBoundingBox().maxX) / 2.0D; + this.posY = this.getEntityBoundingBox().minY; + this.posZ = (this.getEntityBoundingBox().minZ + this.getEntityBoundingBox().maxZ) / 2.0D; + } + + /** + * + Returns true if the command sender should be sent feedback about executed + * commands + */ + public boolean sendCommandFeedback() { + return false; + } + + public void setAir(int air) { + this.dataWatcher.updateObject(1, Short.valueOf((short) air)); + } + + public void setAlwaysRenderNameTag(boolean alwaysRenderNameTag) { + this.dataWatcher.updateObject(3, Byte.valueOf((byte) (alwaysRenderNameTag ? 1 : 0))); + } + + /** + * + Adds 15% to the entity's yaw and subtracts 15% from the pitch. Clamps pitch + * from -90 to 90. Both arguments in degrees. + */ + public void setAngles(float yaw, float pitch) { + float f = this.rotationPitch; + float f1 = this.rotationYaw; + this.rotationYaw = (float) ((double) this.rotationYaw + (double) yaw * 0.15D); + this.rotationPitch = (float) ((double) this.rotationPitch - (double) pitch * 0.15D); + this.rotationPitch = MathHelper.clamp_float(this.rotationPitch, -90.0F, 90.0F); + this.prevRotationPitch += this.rotationPitch - f; + this.prevRotationYaw += this.rotationYaw - f1; + } + + /** + * + Sets that this entity has been attacked. + */ + protected void setBeenAttacked() { + this.velocityChanged = true; + } + + public void setCommandStat(CommandResultStats.Type commandresultstats$type, int i) { + this.cmdResultStats.func_179672_a(this, commandresultstats$type, i); + } + + /** + * + Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is + * armor. Params: Item, slot + */ + public void setCurrentItemOrArmor(int var1, ItemStack var2) { + } + + /** + * + Sets the custom name tag for this entity + */ + public void setCustomNameTag(String name) { + this.dataWatcher.updateObject(2, name); + } + + /** + * + Will get destroyed next tick. + */ + public void setDead() { + this.isDead = true; + } + + public void setEating(boolean eating) { + this.setFlag(4, eating); + } + + public void setEntityBoundingBox(AxisAlignedBB bb) { + this.boundingBox = bb; + } + + public void setEntityId(int id) { + this.entityId = id; + } + + /** + * + Sets entity to burn for x amount of seconds, cannot lower amount of + * existing fire. + */ + public void setFire(int seconds) { + int i = seconds * 20; + i = EnchantmentProtection.getFireTimeForEntity(this, i); + if (this.fire < i) { + this.fire = i; + } + + } + + /** + * + Enable or disable a entity flag, see getEntityFlag to read the know flags. + */ + protected void setFlag(int flag, boolean set) { + byte b0 = this.dataWatcher.getWatchableObjectByte(0); + if (set) { + this.dataWatcher.updateObject(0, Byte.valueOf((byte) (b0 | 1 << flag))); + } else { + this.dataWatcher.updateObject(0, Byte.valueOf((byte) (b0 & ~(1 << flag)))); + } + + } + + public void setInvisible(boolean invisible) { + this.setFlag(5, invisible); + } + + /** + * + Sets the Entity inside a web block. + */ + public void setInWeb() { + this.isInWeb = true; + this.fallDistance = 0.0F; + } + + /** + * + Sets the location and Yaw/Pitch of an entity in the world + */ + public void setLocationAndAngles(double x, double y, double z, float yaw, float pitch) { + this.lastTickPosX = this.prevPosX = this.posX = x; + this.lastTickPosY = this.prevPosY = this.posY = y; + this.lastTickPosZ = this.prevPosZ = this.posZ = z; + this.rotationYaw = yaw; + this.rotationPitch = pitch; + this.setPosition(this.posX, this.posY, this.posZ); + } + + /** + * + Called whenever the entity is walking inside of lava. + */ + protected void setOnFireFromLava() { + if (!this.isImmuneToFire) { + this.attackEntityFrom(DamageSource.lava, 4.0F); + this.setFire(15); + } + } + + public void setOutsideBorder(boolean outsideBorder) { + this.isOutsideBorder = outsideBorder; + } + + /** + * + Sets the x,y,z of the entity from the given parameters. Also seems to set + * up a bounding box. + */ + public void setPosition(double x, double y, double z) { + this.posX = x; + this.posY = y; + this.posZ = z; + float f = this.width / 2.0F; + float f1 = this.height; + this.setEntityBoundingBox( + new AxisAlignedBB(x - (double) f, y, z - (double) f, x + (double) f, y + (double) f1, z + (double) f)); + } + + /** + * + Sets the entity's position and rotation. + */ + public void setPositionAndRotation(double x, double y, double z, float yaw, float pitch) { + this.prevPosX = this.posX = x; + this.prevPosY = this.posY = y; + this.prevPosZ = this.posZ = z; + this.prevRotationYaw = this.rotationYaw = yaw; + this.prevRotationPitch = this.rotationPitch = pitch; + double d0 = (double) (this.prevRotationYaw - yaw); + if (d0 < -180.0D) { + this.prevRotationYaw += 360.0F; + } + + if (d0 >= 180.0D) { + this.prevRotationYaw -= 360.0F; + } + + this.setPosition(this.posX, this.posY, this.posZ); + this.setRotation(yaw, pitch); + } + + public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int var9, boolean var10) { + this.setPosition(d0, d1, d2); + this.setRotation(f, f1); + List list = this.worldObj.getCollidingBoundingBoxes(this, + this.getEntityBoundingBox().contract(0.03125D, 0.0D, 0.03125D)); + if (!list.isEmpty()) { + double d3 = 0.0D; + + for (AxisAlignedBB axisalignedbb : (List) list) { + if (axisalignedbb.maxY > d3) { + d3 = axisalignedbb.maxY; + } + } + + d1 = d1 + (d3 - this.getEntityBoundingBox().minY); + this.setPosition(d0, d1, d2); + } + + } + + /** + * + Sets the position of the entity and updates the 'last' variables + */ + public void setPositionAndUpdate(double d0, double d1, double d2) { + this.setLocationAndAngles(d0, d1, d2, this.rotationYaw, this.rotationPitch); + } + + /** + * + Sets the rotation of the entity. Args: yaw, pitch (both in degrees) + */ + protected void setRotation(float yaw, float pitch) { + this.rotationYaw = yaw % 360.0F; + this.rotationPitch = pitch % 360.0F; + } + + /** + * + Sets the head's yaw rotation of the entity. + */ + public void setRotationYawHead(float rotation) { + } + + /** + * + When set to true the entity will not play sounds. + */ + public void setSilent(boolean isSilent) { + this.dataWatcher.updateObject(4, Byte.valueOf((byte) (isSilent ? 1 : 0))); + } + + /** + * + Sets the width and height of the entity. Args: width, height + */ + protected void setSize(float f, float f1) { + if (f != this.width || f1 != this.height) { + float f2 = this.width; + this.width = f; + this.height = f1; + this.setEntityBoundingBox( + new AxisAlignedBB(this.getEntityBoundingBox().minX, this.getEntityBoundingBox().minY, + this.getEntityBoundingBox().minZ, this.getEntityBoundingBox().minX + (double) this.width, + this.getEntityBoundingBox().minY + (double) this.height, + this.getEntityBoundingBox().minZ + (double) this.width)); + if (this.width > f2 && !this.firstUpdate && !this.worldObj.isRemote) { + this.moveEntity((double) (f2 - this.width), 0.0D, (double) (f2 - this.width)); + } + } + + } + + /** + * + Sets the sneaking flag. + */ + public void setSneaking(boolean sneaking) { + this.setFlag(1, sneaking); + } + + /** + * + Set sprinting switch for Entity. + */ + public void setSprinting(boolean flag) { + this.setFlag(3, flag); + } + + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double x, double y, double z) { + this.motionX = x; + this.motionY = y; + this.motionZ = z; + } + + /** + * + Sets the reference to the World object. + */ + public void setWorld(World worldIn) { + this.worldObj = worldIn; + } + protected boolean shouldSetPosAfterLoading() { return true; } - /**+ - * Returns the string that identifies this Entity's class + /** + * + Attempts to create sprinting particles if the entity is sprinting and not + * in water. */ - protected final String getEntityString() { - return EntityList.getEntityString(this); - } - - protected abstract void readEntityFromNBT(NBTTagCompound var1); - - protected abstract void writeEntityToNBT(NBTTagCompound var1); - - public void onChunkLoad() { - } - - /**+ - * creates a NBT list from the array of doubles passed to this - * function - */ - protected NBTTagList newDoubleNBTList(double... numbers) { - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < numbers.length; ++i) { - nbttaglist.appendTag(new NBTTagDouble(numbers[i])); + public void spawnRunningParticles() { + if (this.isSprinting() && !this.isInWater()) { + this.createRunningParticles(); } - return nbttaglist; } - /**+ - * Returns a new NBTTagList filled with the specified floats + public String toString() { + return HString.format("%s[\'%s\'/%d, l=\'%s\', x=%.2f, y=%.2f, z=%.2f]", + new Object[] { this.getClass().getSimpleName(), this.getName(), Integer.valueOf(this.entityId), + this.worldObj == null ? "~NULL~" : this.worldObj.getWorldInfo().getWorldName(), + Double.valueOf(this.posX), Double.valueOf(this.posY), Double.valueOf(this.posZ) }); + } + + /** + * + Teleports the entity to another dimension. Params: Dimension number to + * teleport to */ - protected NBTTagList newFloatNBTList(float... numbers) { - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < numbers.length; ++i) { - nbttaglist.appendTag(new NBTTagFloat(numbers[i])); - } - - return nbttaglist; - } - - public EntityItem dropItem(Item itemIn, int size) { - return this.dropItemWithOffset(itemIn, size, 0.0F); - } - - public EntityItem dropItemWithOffset(Item itemIn, int size, float offsetY) { - return this.entityDropItem(new ItemStack(itemIn, size, 0), offsetY); - } - - /**+ - * Drops an item at the position of the entity. - */ - public EntityItem entityDropItem(ItemStack itemStackIn, float offsetY) { - if (itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { - EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY + (double) offsetY, this.posZ, - itemStackIn); - entityitem.setDefaultPickupDelay(); - this.worldObj.spawnEntityInWorld(entityitem); - return entityitem; - } else { - return null; - } - } - - /**+ - * Checks whether target entity is alive. - */ - public boolean isEntityAlive() { - return !this.isDead; - } - - /**+ - * Checks if this entity is inside of an opaque block - */ - public boolean isEntityInsideOpaqueBlock() { - if (this.noClip) { - return false; - } else { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(Integer.MIN_VALUE, - Integer.MIN_VALUE, Integer.MIN_VALUE); - - for (int i = 0; i < 8; ++i) { - int j = MathHelper.floor_double( - this.posY + (double) (((float) ((i >> 0) % 2) - 0.5F) * 0.1F) + (double) this.getEyeHeight()); - int k = MathHelper - .floor_double(this.posX + (double) (((float) ((i >> 1) % 2) - 0.5F) * this.width * 0.8F)); - int l = MathHelper - .floor_double(this.posZ + (double) (((float) ((i >> 2) % 2) - 0.5F) * this.width * 0.8F)); - if (blockpos$mutableblockpos.getX() != k || blockpos$mutableblockpos.getY() != j - || blockpos$mutableblockpos.getZ() != l) { - blockpos$mutableblockpos.func_181079_c(k, j, l); - if (this.worldObj.getBlockState(blockpos$mutableblockpos).getBlock().isVisuallyOpaque()) { - return true; - } - } + public void travelToDimension(int i) { + if (!this.worldObj.isRemote && !this.isDead) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + int j = this.dimension; + WorldServer worldserver = minecraftserver.worldServerForDimension(j); + WorldServer worldserver1 = minecraftserver.worldServerForDimension(i); + this.dimension = i; + if (j == 1 && i == 1) { + worldserver1 = minecraftserver.worldServerForDimension(0); + this.dimension = 0; } - return false; + this.worldObj.removeEntity(this); + this.isDead = false; + minecraftserver.getConfigurationManager().transferEntityToWorld(this, j, worldserver, worldserver1); + Entity entity = EntityList.createEntityByName(EntityList.getEntityString(this), worldserver1); + if (entity != null) { + entity.copyDataFromOld(this); + if (j == 1 && i == 1) { + BlockPos blockpos = this.worldObj.getTopSolidOrLiquidBlock(worldserver1.getSpawnPoint()); + entity.moveToBlockPosAndAngles(blockpos, entity.rotationYaw, entity.rotationPitch); + } + + worldserver1.spawnEntityInWorld(entity); + } + + this.isDead = true; + worldserver.resetUpdateEntityTick(); + worldserver1.resetUpdateEntityTick(); } } - /**+ - * First layer of player interaction - */ - public boolean interactFirst(EntityPlayer playerIn) { - return false; + protected void updateFallState(double d0, boolean flag, Block block, BlockPos blockpos) { + if (flag) { + if (this.fallDistance > 0.0F) { + if (block != null) { + block.onFallenUpon(this.worldObj, blockpos, this, this.fallDistance); + } else { + this.fall(this.fallDistance, 1.0F); + } + + this.fallDistance = 0.0F; + } + } else if (d0 < 0.0D) { + this.fallDistance = (float) ((double) this.fallDistance - d0); + } + } - /**+ - * Returns a boundingBox used to collide the entity with other - * entities and blocks. This enables the entity to be pushable - * on contact, like boats or minecarts. - */ - public AxisAlignedBB getCollisionBox(Entity entityIn) { - return null; - } - - /**+ - * Handles updating while being ridden by an entity + /** + * + Handles updating while being ridden by an entity */ public void updateRidden() { if (this.ridingEntity.isDead) { @@ -1618,849 +2362,87 @@ public abstract class Entity implements ICommandSender { } } - /**+ - * Returns the Y Offset of this entity. - */ - public double getYOffset() { - return 0.0D; - } - - /**+ - * Returns the Y offset from the entity's position for any - * entity riding this one. - */ - public double getMountedYOffset() { - return (double) this.height * 0.75D; - } - - /**+ - * Called when a player mounts an entity. e.g. mounts a pig, - * mounts a boat. - */ - public void mountEntity(Entity entity) { - this.entityRiderPitchDelta = 0.0D; - this.entityRiderYawDelta = 0.0D; - if (entity == null) { - if (this.ridingEntity != null) { - this.setLocationAndAngles(this.ridingEntity.posX, - this.ridingEntity.getEntityBoundingBox().minY + (double) this.ridingEntity.height, - this.ridingEntity.posZ, this.rotationYaw, this.rotationPitch); - this.ridingEntity.riddenByEntity = null; - } - - this.ridingEntity = null; - } else { - if (this.ridingEntity != null) { - this.ridingEntity.riddenByEntity = null; - } - - if (entity != null) { - for (Entity entity1 = entity.ridingEntity; entity1 != null; entity1 = entity1.ridingEntity) { - if (entity1 == this) { - return; - } - } - } - - this.ridingEntity = entity; - entity.riddenByEntity = this; - } - } - - public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int var9, boolean var10) { - this.setPosition(d0, d1, d2); - this.setRotation(f, f1); - List list = this.worldObj.getCollidingBoundingBoxes(this, - this.getEntityBoundingBox().contract(0.03125D, 0.0D, 0.03125D)); - if (!list.isEmpty()) { - double d3 = 0.0D; - - for (AxisAlignedBB axisalignedbb : (List) list) { - if (axisalignedbb.maxY > d3) { - d3 = axisalignedbb.maxY; - } - } - - d1 = d1 + (d3 - this.getEntityBoundingBox().minY); - this.setPosition(d0, d1, d2); - } - - } - - public float getCollisionBorderSize() { - return 0.1F; - } - - /**+ - * returns a (normalized) vector of where this entity is looking - */ - public Vec3 getLookVec() { - return null; - } - - public void func_181015_d(BlockPos parBlockPos) { - if (this.timeUntilPortal > 0) { - this.timeUntilPortal = this.getPortalCooldown(); - } else { - if (!this.worldObj.isRemote && !parBlockPos.equals(this.field_181016_an)) { - this.field_181016_an = parBlockPos; - BlockPattern.PatternHelper blockpattern$patternhelper = Blocks.portal.func_181089_f(this.worldObj, - parBlockPos); - double d0 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X - ? (double) blockpattern$patternhelper.func_181117_a().getZ() - : (double) blockpattern$patternhelper.func_181117_a().getX(); - double d1 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X ? this.posZ - : this.posX; - d1 = Math.abs(MathHelper.func_181160_c( - d1 - (double) (blockpattern$patternhelper.getFinger().rotateY() - .getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE ? 1 : 0), - d0, d0 - (double) blockpattern$patternhelper.func_181118_d())); - double d2 = MathHelper.func_181160_c(this.posY - 1.0D, - (double) blockpattern$patternhelper.func_181117_a().getY(), - (double) (blockpattern$patternhelper.func_181117_a().getY() - - blockpattern$patternhelper.func_181119_e())); - this.field_181017_ao = new Vec3(d1, d2, 0.0D); - this.field_181018_ap = blockpattern$patternhelper.getFinger(); - } - - this.inPortal = true; - } - } - - /**+ - * Return the amount of cooldown before this entity can use a - * portal again. - */ - public int getPortalCooldown() { - return 300; - } - - /**+ - * Sets the velocity to the args. Args: x, y, z - */ - public void setVelocity(double x, double y, double z) { - this.motionX = x; - this.motionY = y; - this.motionZ = z; - } - - public void handleStatusUpdate(byte id) { - } - - /**+ - * Setups the entity to do the hurt animation. Only used by - * packets in multiplayer. - */ - public void performHurtAnimation() { - } - - /**+ - * returns the inventory of this entity (only used in - * EntityPlayerMP it seems) - */ - public ItemStack[] getInventory() { - return null; - } - - /**+ - * Sets the held item, or an armor slot. Slot 0 is held item. - * Slot 1-4 is armor. Params: Item, slot - */ - public void setCurrentItemOrArmor(int var1, ItemStack var2) { - } - - /**+ - * Returns true if the entity is on fire. Used by render to add - * the fire effect on rendering. - */ - public boolean isBurning() { - boolean flag = this.worldObj != null && this.worldObj.isRemote; - return !this.isImmuneToFire && (this.fire > 0 || flag && this.getFlag(0)); - } - - /**+ - * Returns true if the entity is riding another entity, used by - * render to rotate the legs to be in 'sit' position for - * players. - */ - public boolean isRiding() { - return this.ridingEntity != null; - } - - /**+ - * Returns if this entity is sneaking. - */ - public boolean isSneaking() { - return this.getFlag(1); - } - - /**+ - * Sets the sneaking flag. - */ - public void setSneaking(boolean sneaking) { - this.setFlag(1, sneaking); - } - - /**+ - * Get if the Entity is sprinting. - */ - public boolean isSprinting() { - return this.getFlag(3); - } - - /**+ - * Set sprinting switch for Entity. - */ - public void setSprinting(boolean flag) { - this.setFlag(3, flag); - } - - public boolean isInvisible() { - return this.getFlag(5); - } - - /**+ - * Only used by renderer in EntityLivingBase - * subclasses.\nDetermines if an entity is visible or not to a - * specfic player, if the entity is normally invisible.\nFor - * EntityLivingBase subclasses, returning false when invisible - * will render the entity semitransparent. - */ - public boolean isInvisibleToPlayer(EntityPlayer player) { - return player.isSpectator() ? false : this.isInvisible(); - } - - public void setInvisible(boolean invisible) { - this.setFlag(5, invisible); - } - - public boolean isEating() { - return this.getFlag(4); - } - - public void setEating(boolean eating) { - this.setFlag(4, eating); - } - - /**+ - * Returns true if the flag is active for the entity. Known - * flags: 0) is burning; 1) is sneaking; 2) is riding something; - * 3) is sprinting; 4) is eating - */ - protected boolean getFlag(int flag) { - return (this.dataWatcher.getWatchableObjectByte(0) & 1 << flag) != 0; - } - - /**+ - * Enable or disable a entity flag, see getEntityFlag to read - * the know flags. - */ - protected void setFlag(int flag, boolean set) { - byte b0 = this.dataWatcher.getWatchableObjectByte(0); - if (set) { - this.dataWatcher.updateObject(0, Byte.valueOf((byte) (b0 | 1 << flag))); - } else { - this.dataWatcher.updateObject(0, Byte.valueOf((byte) (b0 & ~(1 << flag)))); - } - - } - - public int getAir() { - return this.dataWatcher.getWatchableObjectShort(1); - } - - public void setAir(int air) { - this.dataWatcher.updateObject(1, Short.valueOf((short) air)); - } - - /**+ - * Called when a lightning bolt hits the entity. - */ - public void onStruckByLightning(EntityLightningBolt lightningBolt) { - this.attackEntityFrom(DamageSource.lightningBolt, 5.0F); - ++this.fire; - if (this.fire == 0) { - this.setFire(8); - } - - } - - /**+ - * This method gets called when the entity kills another one. - */ - public void onKillEntity(EntityLivingBase entityLivingIn) { - } - - protected boolean pushOutOfBlocks(double d0, double d1, double d2) { - BlockPos blockpos = new BlockPos(d0, d1, d2); - double d3 = d0 - (double) blockpos.getX(); - double d4 = d1 - (double) blockpos.getY(); - double d5 = d2 - (double) blockpos.getZ(); - List list = this.worldObj.func_147461_a(this.getEntityBoundingBox()); - if (list.isEmpty() && !this.worldObj.isBlockFullCube(blockpos)) { - return false; - } else { - byte b0 = 3; - double d6 = 9999.0D; - if (!this.worldObj.isBlockFullCube(blockpos.west()) && d3 < d6) { - d6 = d3; - b0 = 0; - } - - if (!this.worldObj.isBlockFullCube(blockpos.east()) && 1.0D - d3 < d6) { - d6 = 1.0D - d3; - b0 = 1; - } - - if (!this.worldObj.isBlockFullCube(blockpos.up()) && 1.0D - d4 < d6) { - d6 = 1.0D - d4; - b0 = 3; - } - - if (!this.worldObj.isBlockFullCube(blockpos.north()) && d5 < d6) { - d6 = d5; - b0 = 4; - } - - if (!this.worldObj.isBlockFullCube(blockpos.south()) && 1.0D - d5 < d6) { - d6 = 1.0D - d5; - b0 = 5; - } - - float f = this.rand.nextFloat() * 0.2F + 0.1F; - if (b0 == 0) { - this.motionX = (double) (-f); - } - - if (b0 == 1) { - this.motionX = (double) f; - } - - if (b0 == 3) { - this.motionY = (double) f; - } - - if (b0 == 4) { - this.motionZ = (double) (-f); - } - - if (b0 == 5) { - this.motionZ = (double) f; - } - - return true; - } - } - - /**+ - * Sets the Entity inside a web block. - */ - public void setInWeb() { - this.isInWeb = true; - this.fallDistance = 0.0F; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - if (this.hasCustomName()) { - return this.getCustomNameTag(); - } else { - String s = EntityList.getEntityString(this); - if (s == null) { - s = "generic"; - } - - return StatCollector.translateToLocal("entity." + s + ".name"); - } - } - - public String getNameProfanityFilter() { - if (this.hasCustomName()) { - return this.getCustomNameTagProfanityFilter(); - } else { - String s = EntityList.getEntityString(this); - if (s == null) { - s = "generic"; - } - - return StatCollector.translateToLocal("entity." + s + ".name"); - } - } - - /**+ - * Return the Entity parts making up this Entity (currently only - * for dragons) - */ - public Entity[] getParts() { - return null; - } - - /**+ - * Returns true if Entity argument is equal to this Entity - */ - public boolean isEntityEqual(Entity entityIn) { - return this == entityIn; - } - - public float getRotationYawHead() { - return 0.0F; - } - - /**+ - * Sets the head's yaw rotation of the entity. - */ - public void setRotationYawHead(float rotation) { - } - - public void func_181013_g(float parFloat1) { - } - - /**+ - * If returns false, the item will not inflict any damage - * against entities. - */ - public boolean canAttackWithItem() { - return true; - } - - /**+ - * Called when a player attacks an entity. If this returns true - * the attack will not happen. - */ - public boolean hitByEntity(Entity entityIn) { - return false; - } - - public String toString() { - return HString.format("%s[\'%s\'/%d, l=\'%s\', x=%.2f, y=%.2f, z=%.2f]", - new Object[] { this.getClass().getSimpleName(), this.getName(), Integer.valueOf(this.entityId), - this.worldObj == null ? "~NULL~" : this.worldObj.getWorldInfo().getWorldName(), - Double.valueOf(this.posX), Double.valueOf(this.posY), Double.valueOf(this.posZ) }); - } - - public boolean isEntityInvulnerable(DamageSource source) { - return this.invulnerable && source != DamageSource.outOfWorld && !source.isCreativePlayer(); - } - - /**+ - * Sets this entity's location and angles to the location and - * angles of the passed in entity. - */ - public void copyLocationAndAnglesFrom(Entity entityIn) { - this.setLocationAndAngles(entityIn.posX, entityIn.posY, entityIn.posZ, entityIn.rotationYaw, - entityIn.rotationPitch); - } - - /**+ - * Prepares this entity in new dimension by copying NBT data - * from entity in old dimension - */ - public void copyDataFromOld(Entity entityIn) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - entityIn.writeToNBT(nbttagcompound); - this.readFromNBT(nbttagcompound); - this.timeUntilPortal = entityIn.timeUntilPortal; - this.field_181016_an = entityIn.field_181016_an; - this.field_181017_ao = entityIn.field_181017_ao; - this.field_181018_ap = entityIn.field_181018_ap; - } - - /**+ - * Teleports the entity to another dimension. Params: Dimension - * number to teleport to - */ - public void travelToDimension(int i) { - if (!this.worldObj.isRemote && !this.isDead) { - MinecraftServer minecraftserver = MinecraftServer.getServer(); - int j = this.dimension; - WorldServer worldserver = minecraftserver.worldServerForDimension(j); - WorldServer worldserver1 = minecraftserver.worldServerForDimension(i); - this.dimension = i; - if (j == 1 && i == 1) { - worldserver1 = minecraftserver.worldServerForDimension(0); - this.dimension = 0; - } - - this.worldObj.removeEntity(this); - this.isDead = false; - minecraftserver.getConfigurationManager().transferEntityToWorld(this, j, worldserver, worldserver1); - Entity entity = EntityList.createEntityByName(EntityList.getEntityString(this), worldserver1); - if (entity != null) { - entity.copyDataFromOld(this); - if (j == 1 && i == 1) { - BlockPos blockpos = this.worldObj.getTopSolidOrLiquidBlock(worldserver1.getSpawnPoint()); - entity.moveToBlockPosAndAngles(blockpos, entity.rotationYaw, entity.rotationPitch); - } - - worldserver1.spawnEntityInWorld(entity); - } - - this.isDead = true; - worldserver.resetUpdateEntityTick(); - worldserver1.resetUpdateEntityTick(); - } - } - - /**+ - * Explosion resistance of a block relative to this entity - */ - public float getExplosionResistance(Explosion explosionIn, World worldIn, BlockPos pos, IBlockState blockStateIn) { - return blockStateIn.getBlock().getExplosionResistance(this); - } - public boolean verifyExplosion(Explosion explosionIn, World worldIn, BlockPos pos, IBlockState blockStateIn, float parFloat1) { return true; } - /**+ - * The maximum height from where the entity is alowed to jump - * (used in pathfinder) + protected abstract void writeEntityToNBT(NBTTagCompound var1); + + /** + * + Like writeToNBTOptional but does not check if the entity is ridden. Used + * for saving ridden entities with their riders. */ - public int getMaxFallHeight() { - return 3; - } - - public Vec3 func_181014_aG() { - return this.field_181017_ao; - } - - public EnumFacing func_181012_aH() { - return this.field_181018_ap; - } - - /**+ - * Return whether this entity should NOT trigger a pressure - * plate or a tripwire. - */ - public boolean doesEntityNotTriggerPressurePlate() { - return false; - } - - public void addEntityCrashInfo(CrashReportCategory category) { - category.addCrashSectionCallable("Entity Type", new Callable() { - public String call() throws Exception { - return EntityList.getEntityString(Entity.this) + " (" + Entity.this.getClass().getCanonicalName() + ")"; - } - }); - category.addCrashSection("Entity ID", Integer.valueOf(this.entityId)); - category.addCrashSectionCallable("Entity Name", new Callable() { - public String call() throws Exception { - return Entity.this.getName(); - } - }); - category.addCrashSection("Entity\'s Exact location", String.format("%.2f, %.2f, %.2f", - new Object[] { Double.valueOf(this.posX), Double.valueOf(this.posY), Double.valueOf(this.posZ) })); - category.addCrashSection("Entity\'s Block location", - CrashReportCategory.getCoordinateInfo((double) MathHelper.floor_double(this.posX), - (double) MathHelper.floor_double(this.posY), (double) MathHelper.floor_double(this.posZ))); - category.addCrashSection("Entity\'s Momentum", String.format("%.2f, %.2f, %.2f", new Object[] { - Double.valueOf(this.motionX), Double.valueOf(this.motionY), Double.valueOf(this.motionZ) })); - category.addCrashSectionCallable("Entity\'s Rider", new Callable() { - public String call() throws Exception { - return Entity.this.riddenByEntity.toString(); - } - }); - category.addCrashSectionCallable("Entity\'s Vehicle", new Callable() { - public String call() throws Exception { - return Entity.this.ridingEntity.toString(); - } - }); - } - - /**+ - * Return whether this entity should be rendered as on fire. - */ - public boolean canRenderOnFire() { - return this.isBurning(); - } - - public EaglercraftUUID getUniqueID() { - return this.entityUniqueID; - } - - public boolean isPushedByWater() { - return true; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - ChatComponentText chatcomponenttext = new ChatComponentText(this.getName()); - chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); - chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); - return chatcomponenttext; - } - - public IChatComponent getDisplayNameProfanityFilter() { - ChatComponentText chatcomponenttext = new ChatComponentText(this.getNameProfanityFilter()); - chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); - chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); - return chatcomponenttext; - } - - /**+ - * Sets the custom name tag for this entity - */ - public void setCustomNameTag(String name) { - this.dataWatcher.updateObject(2, name); - } - - public String getCustomNameTag() { - return this.dataWatcher.getWatchableObjectString(2); - } - - private String lastNameTagForFilter = null; - private String lastFilteredNameTagForFilter = null; - - public String getCustomNameTagProfanityFilter() { - if (Minecraft.getMinecraft().isEnableProfanityFilter()) { - String str = getCustomNameTag(); - if (str != null) { - if (!str.equals(lastNameTagForFilter)) { - lastNameTagForFilter = str; - lastFilteredNameTagForFilter = ProfanityFilter.getInstance().profanityFilterString(str); - } - return lastFilteredNameTagForFilter; - } else { - return null; - } + public boolean writeMountToNBT(NBTTagCompound tagCompund) { + String s = this.getEntityString(); + if (!this.isDead && s != null) { + tagCompund.setString("id", s); + this.writeToNBT(tagCompund); + return true; } else { - return getCustomNameTag(); + return false; } } - /**+ - * Returns true if this thing is named + /** + * + Save the entity to NBT (calls an abstract helper method to write extra + * data) */ - public boolean hasCustomName() { - return this.dataWatcher.getWatchableObjectString(2).length() > 0; - } + public void writeToNBT(NBTTagCompound tagCompund) { + try { + tagCompund.setTag("Pos", this.newDoubleNBTList(new double[] { this.posX, this.posY, this.posZ })); + tagCompund.setTag("Motion", + this.newDoubleNBTList(new double[] { this.motionX, this.motionY, this.motionZ })); + tagCompund.setTag("Rotation", this.newFloatNBTList(new float[] { this.rotationYaw, this.rotationPitch })); + tagCompund.setFloat("FallDistance", this.fallDistance); + tagCompund.setShort("Fire", (short) this.fire); + tagCompund.setShort("Air", (short) this.getAir()); + tagCompund.setBoolean("OnGround", this.onGround); + tagCompund.setInteger("Dimension", this.dimension); + tagCompund.setBoolean("Invulnerable", this.invulnerable); + tagCompund.setInteger("PortalCooldown", this.timeUntilPortal); + tagCompund.setLong("UUIDMost", this.getUniqueID().getMostSignificantBits()); + tagCompund.setLong("UUIDLeast", this.getUniqueID().getLeastSignificantBits()); + if (this.getCustomNameTag() != null && this.getCustomNameTag().length() > 0) { + tagCompund.setString("CustomName", this.getCustomNameTag()); + tagCompund.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); + } - public void setAlwaysRenderNameTag(boolean alwaysRenderNameTag) { - this.dataWatcher.updateObject(3, Byte.valueOf((byte) (alwaysRenderNameTag ? 1 : 0))); - } + this.cmdResultStats.writeStatsToNBT(tagCompund); + if (this.isSilent()) { + tagCompund.setBoolean("Silent", this.isSilent()); + } - public boolean getAlwaysRenderNameTag() { - return this.dataWatcher.getWatchableObjectByte(3) == 1; - } + this.writeEntityToNBT(tagCompund); + if (this.ridingEntity != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + if (this.ridingEntity.writeMountToNBT(nbttagcompound)) { + tagCompund.setTag("Riding", nbttagcompound); + } + } - /**+ - * Sets the position of the entity and updates the 'last' - * variables - */ - public void setPositionAndUpdate(double d0, double d1, double d2) { - this.setLocationAndAngles(d0, d1, d2, this.rotationYaw, this.rotationPitch); - } - - public boolean getAlwaysRenderNameTagForRender() { - return this.getAlwaysRenderNameTag(); - } - - public void onDataWatcherUpdate(int dataID) { - } - - public EnumFacing getHorizontalFacing() { - return EnumFacing - .getHorizontal(MathHelper.floor_double((double) (this.rotationYaw * 4.0F / 360.0F) + 0.5D) & 3); - } - - protected HoverEvent getHoverEvent() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - String s = EntityList.getEntityString(this); - nbttagcompound.setString("id", this.getUniqueID().toString()); - if (s != null) { - nbttagcompound.setString("type", s); - } - - nbttagcompound.setString("name", this.getName()); - return new HoverEvent(HoverEvent.Action.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); - } - - public boolean isSpectatedByPlayer(EntityPlayerMP var1) { - return true; - } - - public AxisAlignedBB getEntityBoundingBox() { - return this.boundingBox; - } - - public void setEntityBoundingBox(AxisAlignedBB bb) { - this.boundingBox = bb; - } - - public float getEyeHeight() { - return this.height * 0.85F; - } - - public boolean isOutsideBorder() { - return this.isOutsideBorder; - } - - public void setOutsideBorder(boolean outsideBorder) { - this.isOutsideBorder = outsideBorder; - } - - public boolean replaceItemInInventory(int inventorySlot, ItemStack itemStackIn) { - return false; - } - - /**+ - * Send a chat message to the CommandSender - */ - public void addChatMessage(IChatComponent var1) { - } - - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not - */ - public boolean canCommandSenderUseCommand(int var1, String var2) { - return true; - } - - /**+ - * Get the position in the world. {@code null} is not - * allowed! If you are not an entity in the world, return - * the coordinates 0, 0, 0 - */ - public BlockPos getPosition() { - return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); - } - - /**+ - * Get the position vector. {@code null} is not allowed! - * If you are not an entity in the world, return 0.0D, 0.0D, - * 0.0D - */ - public Vec3 getPositionVector() { - return new Vec3(this.posX, this.posY, this.posZ); - } - - /**+ - * Get the world, if available. {@code null} is not - * allowed! If you are not an entity in the world, return - * the overworld - */ - public World getEntityWorld() { - return this.worldObj; - } - - /**+ - * Returns the entity associated with the command sender. MAY BE - * NULL! - */ - public Entity getCommandSenderEntity() { - return this; - } - - /**+ - * Returns true if the command sender should be sent feedback - * about executed commands - */ - public boolean sendCommandFeedback() { - return false; - } - - public void setCommandStat(CommandResultStats.Type commandresultstats$type, int i) { - this.cmdResultStats.func_179672_a(this, commandresultstats$type, i); - } - - public CommandResultStats getCommandStats() { - return this.cmdResultStats; - } - - public void func_174817_o(Entity entityIn) { - this.cmdResultStats.func_179671_a(entityIn.getCommandStats()); - } - - public NBTTagCompound getNBTTagCompound() { - return null; - } - - /**+ - * Called when client receives entity's NBTTagCompound from - * server. - */ - public void clientUpdateEntityNBT(NBTTagCompound compound) { - } - - /**+ - * New version of interactWith that includes vector information - * on where precisely the player targeted. - */ - public boolean interactAt(EntityPlayer player, Vec3 targetVec3) { - return false; - } - - public boolean isImmuneToExplosions() { - return false; - } - - protected void applyEnchantments(EntityLivingBase entityLivingBaseIn, Entity entityIn) { - if (entityIn instanceof EntityLivingBase) { - EnchantmentHelper.applyThornEnchantments((EntityLivingBase) entityIn, entityLivingBaseIn); - } - - EnchantmentHelper.applyArthropodEnchantments(entityLivingBaseIn, entityIn); - } - - public void renderDynamicLightsEagler(float partialTicks, boolean isInFrustum) { - double entityX = prevPosX + (posX - prevPosX) * (double) partialTicks; - double entityY = prevPosY + (posY - prevPosY) * (double) partialTicks; - double entityZ = prevPosZ + (posZ - prevPosZ) * (double) partialTicks; - double entityX2 = entityX - TileEntityRendererDispatcher.staticPlayerX; - double entityY2 = entityY - TileEntityRendererDispatcher.staticPlayerY; - double entityZ2 = entityZ - TileEntityRendererDispatcher.staticPlayerZ; - if (entityX2 * entityX2 + entityY2 * entityY2 - + entityZ2 * entityZ2 < (isInFrustum ? (64.0 * 64.0) : (24.0 * 24.0))) { - renderDynamicLightsEaglerAt(entityX, entityY, entityZ, entityX2, entityY2, entityZ2, partialTicks, - isInFrustum); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Saving entity NBT"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity being saved"); + this.addEntityCrashInfo(crashreportcategory); + throw new ReportedException(crashreport); } } - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, - double renderY, double renderZ, float partialTicks, boolean isInFrustum) { - float size = Math.max(width, height); - if (size < 1.0f && !isInFrustum) { - return; + /** + * + Either write this entity to the NBT tag given and return true, or return + * false without doing anything. If this returns false the entity is not saved + * on disk. Ridden entities return false here as they are saved with their + * rider. + */ + public boolean writeToNBTOptional(NBTTagCompound tagCompund) { + String s = this.getEntityString(); + if (!this.isDead && s != null && this.riddenByEntity == null) { + tagCompund.setString("id", s); + this.writeToNBT(tagCompund); + return true; + } else { + return false; } - if (this.isBurning()) { - float mag = 5.0f * size; - DynamicLightManager.renderDynamicLight("entity_" + entityId + "_fire", entityX, entityY + height * 0.75, - entityZ, mag, 0.487f * mag, 0.1411f * mag, false); - } - } - - public void renderDynamicLightsEaglerSimple(float partialTicks) { - double entityX = prevPosX + (posX - prevPosX) * (double) partialTicks; - double entityY = prevPosY + (posY - prevPosY) * (double) partialTicks; - double entityZ = prevPosZ + (posZ - prevPosZ) * (double) partialTicks; - renderDynamicLightsEaglerSimpleAt(entityX, entityY, entityZ, partialTicks); - } - - protected void renderDynamicLightsEaglerSimpleAt(double entityX, double entityY, double entityZ, - float partialTicks) { - float renderBrightness = this.getEaglerDynamicLightsValueSimple(partialTicks); - if (renderBrightness > 0.1f) { - DynamicLightsStateManager.renderDynamicLight("entity_" + entityId + "_lightmap", entityX, - entityY + height * 0.85, entityZ, renderBrightness * 13.0f); - } - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float size = Math.max(width, height); - if (size < 1.0f) { - return 0.0f; - } - if (this.isBurning()) { - return size / 2.0f; - } - return 0.0f; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityAgeable.java b/src/game/java/net/minecraft/entity/EntityAgeable.java index 74e1acbf..e2f7015c 100644 --- a/src/game/java/net/minecraft/entity/EntityAgeable.java +++ b/src/game/java/net/minecraft/entity/EntityAgeable.java @@ -8,22 +8,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,11 +42,61 @@ public abstract class EntityAgeable extends EntityCreature { super(worldIn); } + /** + * + "Adds the value of the parameter times 20 to the age of this entity. If the + * entity is an adult (if the entity's age is greater than 0), it will have no + * effect." + */ + public void addGrowth(int growth) { + this.func_175501_a(growth, false); + } + public abstract EntityAgeable createChild(EntityAgeable var1); - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(12, Byte.valueOf((byte) 0)); + } + + public void func_175501_a(int parInt1, boolean parFlag) { + int i = this.getGrowingAge(); + int j = i; + i = i + parInt1 * 20; + if (i > 0) { + i = 0; + if (j < 0) { + this.onGrowingAdult(); + } + } + + int k = i - j; + this.setGrowingAge(i); + if (parFlag) { + this.field_175502_b += k; + if (this.field_175503_c == 0) { + this.field_175503_c = 40; + } + } + + if (this.getGrowingAge() == 0) { + this.setGrowingAge(this.field_175502_b); + } + + } + + /** + * + The age value may be negative or positive or zero. If it's negative, it + * get's incremented on each tick, if it's positive, it get's decremented each + * tick. Don't confuse this with EntityLiving.getAge. With a negative value the + * Entity is considered a child. + */ + public int getGrowingAge() { + return this.worldObj.isRemote ? this.dataWatcher.getWatchableObjectByte(12) : this.growingAge; + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer player) { ItemStack itemstack = player.inventory.getCurrentItem(); @@ -77,93 +130,24 @@ public abstract class EntityAgeable extends EntityCreature { } } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(12, Byte.valueOf((byte) 0)); - } - - /**+ - * The age value may be negative or positive or zero. If it's - * negative, it get's incremented on each tick, if it's - * positive, it get's decremented each tick. Don't confuse this - * with EntityLiving.getAge. With a negative value the Entity is - * considered a child. + /** + * + If Animal, checks if the age timer is negative */ - public int getGrowingAge() { - return this.worldObj.isRemote ? this.dataWatcher.getWatchableObjectByte(12) : this.growingAge; + public boolean isChild() { + return this.getGrowingAge() < 0; } - public void func_175501_a(int parInt1, boolean parFlag) { - int i = this.getGrowingAge(); - int j = i; - i = i + parInt1 * 20; - if (i > 0) { - i = 0; - if (j < 0) { - this.onGrowingAdult(); - } - } - - int k = i - j; - this.setGrowingAge(i); - if (parFlag) { - this.field_175502_b += k; - if (this.field_175503_c == 0) { - this.field_175503_c = 40; - } - } - - if (this.getGrowingAge() == 0) { - this.setGrowingAge(this.field_175502_b); - } - - } - - /**+ - * "Adds the value of the parameter times 20 to the age of this - * entity. If the entity is an adult (if the entity's age is - * greater than 0), it will have no effect." + /** + * + This is called when Entity's growing age timer reaches 0 (negative values + * are considered as a child, positive as an adult) */ - public void addGrowth(int growth) { - this.func_175501_a(growth, false); + protected void onGrowingAdult() { } - /**+ - * The age value may be negative or positive or zero. If it's - * negative, it get's incremented on each tick, if it's - * positive, it get's decremented each tick. With a negative - * value the Entity is considered a child. - */ - public void setGrowingAge(int age) { - this.dataWatcher.updateObject(12, Byte.valueOf((byte) MathHelper.clamp_int(age, -1, 1))); - this.growingAge = age; - this.setScaleForAge(this.isChild()); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("Age", this.getGrowingAge()); - nbttagcompound.setInteger("ForcedAge", this.field_175502_b); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setGrowingAge(nbttagcompound.getInteger("Age")); - this.field_175502_b = nbttagcompound.getInteger("ForcedAge"); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); @@ -197,31 +181,40 @@ public abstract class EntityAgeable extends EntityCreature { } - /**+ - * This is called when Entity's growing age timer reaches 0 - * (negative values are considered as a child, positive as an - * adult) + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void onGrowingAdult() { + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setGrowingAge(nbttagcompound.getInteger("Age")); + this.field_175502_b = nbttagcompound.getInteger("ForcedAge"); } - /**+ - * If Animal, checks if the age timer is negative + /** + * + The age value may be negative or positive or zero. If it's negative, it + * get's incremented on each tick, if it's positive, it get's decremented each + * tick. With a negative value the Entity is considered a child. */ - public boolean isChild() { - return this.getGrowingAge() < 0; + public void setGrowingAge(int age) { + this.dataWatcher.updateObject(12, Byte.valueOf((byte) MathHelper.clamp_int(age, -1, 1))); + this.growingAge = age; + this.setScaleForAge(this.isChild()); } - /**+ - * "Sets the scale for an ageable entity according to the - * boolean parameter, which says if it's a child." + protected final void setScale(float scale) { + super.setSize(this.ageWidth * scale, this.ageHeight * scale); + } + + /** + * + "Sets the scale for an ageable entity according to the boolean parameter, + * which says if it's a child." */ public void setScaleForAge(boolean parFlag) { this.setScale(parFlag ? 0.5F : 1.0F); } - /**+ - * Sets the width and height of the entity. Args: width, height + /** + * + Sets the width and height of the entity. Args: width, height */ protected final void setSize(float width, float height) { boolean flag = this.ageWidth > 0.0F; @@ -233,7 +226,12 @@ public abstract class EntityAgeable extends EntityCreature { } - protected final void setScale(float scale) { - super.setSize(this.ageWidth * scale, this.ageHeight * scale); + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("Age", this.getGrowingAge()); + nbttagcompound.setInteger("ForcedAge", this.field_175502_b); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityBodyHelper.java b/src/game/java/net/minecraft/entity/EntityBodyHelper.java index ae8b5507..2d2f970e 100644 --- a/src/game/java/net/minecraft/entity/EntityBodyHelper.java +++ b/src/game/java/net/minecraft/entity/EntityBodyHelper.java @@ -2,22 +2,25 @@ package net.minecraft.entity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +34,25 @@ public class EntityBodyHelper { this.theLiving = parEntityLivingBase; } - /**+ - * Update the Head and Body rendenring angles + /** + * + Return the new angle2 such that the difference between angle1 and angle2 is + * lower than angleMax. Args : angle1, angle2, angleMax + */ + private float computeAngleWithBound(float parFloat1, float parFloat2, float parFloat3) { + float f = MathHelper.wrapAngleTo180_float(parFloat1 - parFloat2); + if (f < -parFloat3) { + f = -parFloat3; + } + + if (f >= parFloat3) { + f = parFloat3; + } + + return parFloat1 - f; + } + + /** + * + Update the Head and Body rendenring angles */ public void updateRenderAngles() { double d0 = this.theLiving.posX - this.theLiving.prevPosX; @@ -60,22 +80,4 @@ public class EntityBodyHelper { this.theLiving.renderYawOffset, f); } } - - /**+ - * Return the new angle2 such that the difference between angle1 - * and angle2 is lower than angleMax. Args : angle1, angle2, - * angleMax - */ - private float computeAngleWithBound(float parFloat1, float parFloat2, float parFloat3) { - float f = MathHelper.wrapAngleTo180_float(parFloat1 - parFloat2); - if (f < -parFloat3) { - f = -parFloat3; - } - - if (f >= parFloat3) { - f = parFloat3; - } - - return parFloat1 - f; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityCreature.java b/src/game/java/net/minecraft/entity/EntityCreature.java index 0e74deb6..3ea3595b 100644 --- a/src/game/java/net/minecraft/entity/EntityCreature.java +++ b/src/game/java/net/minecraft/entity/EntityCreature.java @@ -1,7 +1,6 @@ package net.minecraft.entity; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.ai.EntityAIMoveTowardsRestriction; import net.minecraft.entity.ai.attributes.AttributeModifier; @@ -10,22 +9,25 @@ import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +38,8 @@ public abstract class EntityCreature extends EntityLiving { public static final AttributeModifier FLEEING_SPEED_MODIFIER = (new AttributeModifier(FLEEING_SPEED_MODIFIER_UUID, "Fleeing speed bonus", 2.0D, 2)).setSaved(false); private BlockPos homePosition = BlockPos.ORIGIN; - /**+ - * If -1 there is no maximum distance + /** + * + If -1 there is no maximum distance */ private float maximumHomeDistance = -1.0F; private EntityAIBase aiBase = new EntityAIMoveTowardsRestriction(this, 1.0D); @@ -47,21 +49,43 @@ public abstract class EntityCreature extends EntityLiving { super(worldIn); } + public void detachHome() { + this.maximumHomeDistance = -1.0F; + } + + protected void func_142017_o(float parFloat1) { + } + public float getBlockPathWeight(BlockPos pos) { return 0.0F; } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. */ public boolean getCanSpawnHere() { return super.getCanSpawnHere() && this .getBlockPathWeight(new BlockPos(this.posX, this.getEntityBoundingBox().minY, this.posZ)) >= 0.0F; } - /**+ - * if the entity got a PathEntity it returns true, else false + public BlockPos getHomePosition() { + return this.homePosition; + } + + public float getMaximumHomeDistance() { + return this.maximumHomeDistance; + } + + /** + * + Returns whether a home area is defined for this entity. + */ + public boolean hasHome() { + return this.maximumHomeDistance != -1.0F; + } + + /** + * + if the entity got a PathEntity it returns true, else false */ public boolean hasPath() { return !this.navigator.noPath(); @@ -76,36 +100,17 @@ public abstract class EntityCreature extends EntityLiving { : this.homePosition.distanceSq(pos) < (double) (this.maximumHomeDistance * this.maximumHomeDistance); } - /**+ - * Sets home position and max distance for it + /** + * + Sets home position and max distance for it */ public void setHomePosAndDistance(BlockPos pos, int distance) { this.homePosition = pos; this.maximumHomeDistance = (float) distance; } - public BlockPos getHomePosition() { - return this.homePosition; - } - - public float getMaximumHomeDistance() { - return this.maximumHomeDistance; - } - - public void detachHome() { - this.maximumHomeDistance = -1.0F; - } - - /**+ - * Returns whether a home area is defined for this entity. - */ - public boolean hasHome() { - return this.maximumHomeDistance != -1.0F; - } - - /**+ - * Applies logic related to leashes, for example dragging the - * entity or breaking the leash. + /** + * + Applies logic related to leashes, for example dragging the entity or + * breaking the leash. */ protected void updateLeashedState() { super.updateLeashedState(); @@ -159,7 +164,4 @@ public abstract class EntityCreature extends EntityLiving { } } - - protected void func_142017_o(float parFloat1) { - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityFlying.java b/src/game/java/net/minecraft/entity/EntityFlying.java index d5a30a62..85949bd2 100644 --- a/src/game/java/net/minecraft/entity/EntityFlying.java +++ b/src/game/java/net/minecraft/entity/EntityFlying.java @@ -5,22 +5,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,12 +36,15 @@ public abstract class EntityFlying extends EntityLiving { public void fall(float var1, float var2) { } - protected void updateFallState(double var1, boolean var3, Block var4, BlockPos var5) { + /** + * + returns true if this entity is by a ladder, false otherwise + */ + public boolean isOnLadder() { + return false; } - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward + /** + * + Moves the entity based on the specified heading. Args: strafe, forward */ public void moveEntityWithHeading(float strafe, float forward) { if (this.isInWater()) { @@ -88,10 +94,6 @@ public abstract class EntityFlying extends EntityLiving { this.limbSwing += this.limbSwingAmount; } - /**+ - * returns true if this entity is by a ladder, false otherwise - */ - public boolean isOnLadder() { - return false; + protected void updateFallState(double var1, boolean var3, Block var4, BlockPos var5) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityHanging.java b/src/game/java/net/minecraft/entity/EntityHanging.java index 4227ad7e..114b3aff 100644 --- a/src/game/java/net/minecraft/entity/EntityHanging.java +++ b/src/game/java/net/minecraft/entity/EntityHanging.java @@ -1,5 +1,9 @@ package net.minecraft.entity; +import java.util.List; + +import org.apache.commons.lang3.Validate; + import net.minecraft.block.Block; import net.minecraft.block.BlockRedstoneDiode; import net.minecraft.entity.player.EntityPlayer; @@ -10,26 +14,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -import java.util.List; - -import org.apache.commons.lang3.Validate; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,22 +52,176 @@ public abstract class EntityHanging extends Entity { this.hangingPosition = hangingPositionIn; } + /** + * + Adds to the current velocity of the entity. Args: x, y, z + */ + public void addVelocity(double d0, double d1, double d2) { + if (!this.worldObj.isRemote && !this.isDead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { + this.setDead(); + this.onBroken((Entity) null); + } + + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float var2) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + if (!this.isDead && !this.worldObj.isRemote) { + this.setDead(); + this.setBeenAttacked(); + this.onBroken(damagesource.getEntity()); + } + + return true; + } + } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return true; + } + protected void entityInit() { } - /**+ - * Updates facing and bounding box based on it - */ - protected void updateFacingWithBoundingBox(EnumFacing facingDirectionIn) { - Validate.notNull(facingDirectionIn); - Validate.isTrue(facingDirectionIn.getAxis().isHorizontal()); - this.facingDirection = facingDirectionIn; - this.prevRotationYaw = this.rotationYaw = (float) (this.facingDirection.getHorizontalIndex() * 90); - this.updateBoundingBox(); + private double func_174858_a(int parInt1) { + return parInt1 % 32 == 0 ? 0.5D : 0.0D; } - /**+ - * Updates the entity bounding box based on current facing + public BlockPos getHangingPosition() { + return this.hangingPosition; + } + + public abstract int getHeightPixels(); + + public EnumFacing getHorizontalFacing() { + return this.facingDirection; + } + + public abstract int getWidthPixels(); + + /** + * + Called when a player attacks an entity. If this returns true the attack + * will not happen. + */ + public boolean hitByEntity(Entity entity) { + return entity instanceof EntityPlayer + ? this.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) entity), 0.0F) + : false; + } + + /** + * + Tries to moves the entity by the passed in displacement. Args: x, y, z + */ + public void moveEntity(double d0, double d1, double d2) { + if (!this.worldObj.isRemote && !this.isDead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { + this.setDead(); + this.onBroken((Entity) null); + } + + } + + public abstract void onBroken(Entity var1); + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + if (this.tickCounter1++ == 100 && !this.worldObj.isRemote) { + this.tickCounter1 = 0; + if (!this.isDead && !this.onValidSurface()) { + this.setDead(); + this.onBroken((Entity) null); + } + } + + } + + /** + * + checks to make sure painting can be placed there + */ + public boolean onValidSurface() { + if (!this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty()) { + return false; + } else { + int i = Math.max(1, this.getWidthPixels() / 16); + int j = Math.max(1, this.getHeightPixels() / 16); + BlockPos blockpos = this.hangingPosition.offset(this.facingDirection.getOpposite()); + EnumFacing enumfacing = this.facingDirection.rotateYCCW(); + + for (int k = 0; k < i; ++k) { + for (int l = 0; l < j; ++l) { + BlockPos blockpos1 = blockpos.offset(enumfacing, k).up(l); + Block block = this.worldObj.getBlockState(blockpos1).getBlock(); + if (!block.getMaterial().isSolid() && !BlockRedstoneDiode.isRedstoneRepeaterBlockID(block)) { + return false; + } + } + } + + List lst = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox()); + for (int k = 0, l = lst.size(); k < l; ++k) { + if (lst.get(k) instanceof EntityHanging) { + return false; + } + } + + return true; + } + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + this.hangingPosition = new BlockPos(nbttagcompound.getInteger("TileX"), nbttagcompound.getInteger("TileY"), + nbttagcompound.getInteger("TileZ")); + EnumFacing enumfacing; + if (nbttagcompound.hasKey("Direction", 99)) { + enumfacing = EnumFacing.getHorizontal(nbttagcompound.getByte("Direction")); + this.hangingPosition = this.hangingPosition.offset(enumfacing); + } else if (nbttagcompound.hasKey("Facing", 99)) { + enumfacing = EnumFacing.getHorizontal(nbttagcompound.getByte("Facing")); + } else { + enumfacing = EnumFacing.getHorizontal(nbttagcompound.getByte("Dir")); + } + + this.updateFacingWithBoundingBox(enumfacing); + } + + /** + * + Sets the x,y,z of the entity from the given parameters. Also seems to set + * up a bounding box. + */ + public void setPosition(double d0, double d1, double d2) { + this.posX = d0; + this.posY = d1; + this.posZ = d2; + BlockPos blockpos = this.hangingPosition; + this.hangingPosition = new BlockPos(d0, d1, d2); + if (!this.hangingPosition.equals(blockpos)) { + this.updateBoundingBox(); + this.isAirBorne = true; + } + + } + + protected boolean shouldSetPosAfterLoading() { + return false; + } + + /** + * + Updates the entity bounding box based on current facing */ private void updateBoundingBox() { if (this.facingDirection != null) { @@ -99,125 +256,19 @@ public abstract class EntityHanging extends Entity { } } - private double func_174858_a(int parInt1) { - return parInt1 % 32 == 0 ? 0.5D : 0.0D; - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Updates facing and bounding box based on it */ - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - if (this.tickCounter1++ == 100 && !this.worldObj.isRemote) { - this.tickCounter1 = 0; - if (!this.isDead && !this.onValidSurface()) { - this.setDead(); - this.onBroken((Entity) null); - } - } - + protected void updateFacingWithBoundingBox(EnumFacing facingDirectionIn) { + Validate.notNull(facingDirectionIn); + Validate.isTrue(facingDirectionIn.getAxis().isHorizontal()); + this.facingDirection = facingDirectionIn; + this.prevRotationYaw = this.rotationYaw = (float) (this.facingDirection.getHorizontalIndex() * 90); + this.updateBoundingBox(); } - /**+ - * checks to make sure painting can be placed there - */ - public boolean onValidSurface() { - if (!this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty()) { - return false; - } else { - int i = Math.max(1, this.getWidthPixels() / 16); - int j = Math.max(1, this.getHeightPixels() / 16); - BlockPos blockpos = this.hangingPosition.offset(this.facingDirection.getOpposite()); - EnumFacing enumfacing = this.facingDirection.rotateYCCW(); - - for (int k = 0; k < i; ++k) { - for (int l = 0; l < j; ++l) { - BlockPos blockpos1 = blockpos.offset(enumfacing, k).up(l); - Block block = this.worldObj.getBlockState(blockpos1).getBlock(); - if (!block.getMaterial().isSolid() && !BlockRedstoneDiode.isRedstoneRepeaterBlockID(block)) { - return false; - } - } - } - - List lst = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox()); - for (int k = 0, l = lst.size(); k < l; ++k) { - if (lst.get(k) instanceof EntityHanging) { - return false; - } - } - - return true; - } - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return true; - } - - /**+ - * Called when a player attacks an entity. If this returns true - * the attack will not happen. - */ - public boolean hitByEntity(Entity entity) { - return entity instanceof EntityPlayer - ? this.attackEntityFrom(DamageSource.causePlayerDamage((EntityPlayer) entity), 0.0F) - : false; - } - - public EnumFacing getHorizontalFacing() { - return this.facingDirection; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float var2) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - if (!this.isDead && !this.worldObj.isRemote) { - this.setDead(); - this.setBeenAttacked(); - this.onBroken(damagesource.getEntity()); - } - - return true; - } - } - - /**+ - * Tries to moves the entity by the passed in displacement. - * Args: x, y, z - */ - public void moveEntity(double d0, double d1, double d2) { - if (!this.worldObj.isRemote && !this.isDead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { - this.setDead(); - this.onBroken((Entity) null); - } - - } - - /**+ - * Adds to the current velocity of the entity. Args: x, y, z - */ - public void addVelocity(double d0, double d1, double d2) { - if (!this.worldObj.isRemote && !this.isDead && d0 * d0 + d1 * d1 + d2 * d2 > 0.0D) { - this.setDead(); - this.onBroken((Entity) null); - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setByte("Facing", (byte) this.facingDirection.getHorizontalIndex()); @@ -225,55 +276,4 @@ public abstract class EntityHanging extends Entity { nbttagcompound.setInteger("TileY", this.getHangingPosition().getY()); nbttagcompound.setInteger("TileZ", this.getHangingPosition().getZ()); } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - this.hangingPosition = new BlockPos(nbttagcompound.getInteger("TileX"), nbttagcompound.getInteger("TileY"), - nbttagcompound.getInteger("TileZ")); - EnumFacing enumfacing; - if (nbttagcompound.hasKey("Direction", 99)) { - enumfacing = EnumFacing.getHorizontal(nbttagcompound.getByte("Direction")); - this.hangingPosition = this.hangingPosition.offset(enumfacing); - } else if (nbttagcompound.hasKey("Facing", 99)) { - enumfacing = EnumFacing.getHorizontal(nbttagcompound.getByte("Facing")); - } else { - enumfacing = EnumFacing.getHorizontal(nbttagcompound.getByte("Dir")); - } - - this.updateFacingWithBoundingBox(enumfacing); - } - - public abstract int getWidthPixels(); - - public abstract int getHeightPixels(); - - public abstract void onBroken(Entity var1); - - protected boolean shouldSetPosAfterLoading() { - return false; - } - - /**+ - * Sets the x,y,z of the entity from the given parameters. Also - * seems to set up a bounding box. - */ - public void setPosition(double d0, double d1, double d2) { - this.posX = d0; - this.posY = d1; - this.posZ = d2; - BlockPos blockpos = this.hangingPosition; - this.hangingPosition = new BlockPos(d0, d1, d2); - if (!this.hangingPosition.equals(blockpos)) { - this.updateBoundingBox(); - this.isAirBorne = true; - } - - } - - public BlockPos getHangingPosition() { - return this.hangingPosition; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityLeashKnot.java b/src/game/java/net/minecraft/entity/EntityLeashKnot.java index 91891ae4..5a1c1a27 100644 --- a/src/game/java/net/minecraft/entity/EntityLeashKnot.java +++ b/src/game/java/net/minecraft/entity/EntityLeashKnot.java @@ -12,27 +12,55 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityLeashKnot extends EntityHanging { + public static EntityLeashKnot createKnot(World worldIn, BlockPos fence) { + EntityLeashKnot entityleashknot = new EntityLeashKnot(worldIn, fence); + entityleashknot.forceSpawn = true; + worldIn.spawnEntityInWorld(entityleashknot); + return entityleashknot; + } + + public static EntityLeashKnot getKnotForPosition(World worldIn, BlockPos pos) { + int i = pos.getX(); + int j = pos.getY(); + int k = pos.getZ(); + + List entities = worldIn.getEntitiesWithinAABB(EntityLeashKnot.class, + new AxisAlignedBB((double) i - 1.0D, (double) j - 1.0D, (double) k - 1.0D, (double) i + 1.0D, + (double) j + 1.0D, (double) k + 1.0D)); + for (int m = 0, l = entities.size(); m < l; ++m) { + EntityLeashKnot entityleashknot = entities.get(m); + if (entityleashknot.getHangingPosition().equals(pos)) { + return entityleashknot; + } + } + + return null; + } + public EntityLeashKnot(World worldIn) { super(worldIn); } @@ -52,66 +80,20 @@ public class EntityLeashKnot extends EntityHanging { super.entityInit(); } - /**+ - * Updates facing and bounding box based on it - */ - public void updateFacingWithBoundingBox(EnumFacing var1) { - } - - public int getWidthPixels() { - return 9; + public float getEyeHeight() { + return -0.0625F; } public int getHeightPixels() { return 9; } - public float getEyeHeight() { - return -0.0625F; + public int getWidthPixels() { + return 9; } - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double d0) { - return d0 < 1024.0D; - } - - /**+ - * Called when this entity is broken. Entity parameter may be - * null. - */ - public void onBroken(Entity var1) { - } - - /**+ - * Either write this entity to the NBT tag given and return - * true, or return false without doing anything. If this returns - * false the entity is not saved on disk. Ridden entities return - * false here as they are saved with their rider. - */ - public boolean writeToNBTOptional(NBTTagCompound var1) { - return false; - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound var1) { - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound var1) { - } - - /**+ - * First layer of player interaction + /** + * + First layer of player interaction */ public boolean interactFirst(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.getHeldItem(); @@ -150,35 +132,53 @@ public class EntityLeashKnot extends EntityHanging { return true; } - /**+ - * checks to make sure painting can be placed there + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance + */ + public boolean isInRangeToRenderDist(double d0) { + return d0 < 1024.0D; + } + + /** + * + Called when this entity is broken. Entity parameter may be null. + */ + public void onBroken(Entity var1) { + } + + /** + * + checks to make sure painting can be placed there */ public boolean onValidSurface() { return this.worldObj.getBlockState(this.hangingPosition).getBlock() instanceof BlockFence; } - public static EntityLeashKnot createKnot(World worldIn, BlockPos fence) { - EntityLeashKnot entityleashknot = new EntityLeashKnot(worldIn, fence); - entityleashknot.forceSpawn = true; - worldIn.spawnEntityInWorld(entityleashknot); - return entityleashknot; + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound var1) { } - public static EntityLeashKnot getKnotForPosition(World worldIn, BlockPos pos) { - int i = pos.getX(); - int j = pos.getY(); - int k = pos.getZ(); + /** + * + Updates facing and bounding box based on it + */ + public void updateFacingWithBoundingBox(EnumFacing var1) { + } - List entities = worldIn.getEntitiesWithinAABB(EntityLeashKnot.class, - new AxisAlignedBB((double) i - 1.0D, (double) j - 1.0D, (double) k - 1.0D, (double) i + 1.0D, - (double) j + 1.0D, (double) k + 1.0D)); - for (int m = 0, l = entities.size(); m < l; ++m) { - EntityLeashKnot entityleashknot = entities.get(m); - if (entityleashknot.getHangingPosition().equals(pos)) { - return entityleashknot; - } - } + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound var1) { + } - return null; + /** + * + Either write this entity to the NBT tag given and return true, or return + * false without doing anything. If this returns false the entity is not saved + * on disk. Ridden entities return false here as they are saved with their + * rider. + */ + public boolean writeToNBTOptional(NBTTagCompound var1) { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityList.java b/src/game/java/net/minecraft/entity/EntityList.java index 5a863c16..6a182578 100644 --- a/src/game/java/net/minecraft/entity/EntityList.java +++ b/src/game/java/net/minecraft/entity/EntityList.java @@ -45,6 +45,7 @@ import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.entity.monster.EntityMagmaCube; import net.minecraft.entity.monster.EntityMob; +import net.minecraft.entity.monster.EntityNetherCreeper; import net.minecraft.entity.monster.EntityPigZombie; import net.minecraft.entity.monster.EntitySilverfish; import net.minecraft.entity.monster.EntitySkeleton; @@ -78,27 +79,46 @@ import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityList { + public static class EntityEggInfo { + public final int spawnedID; + public final int primaryColor; + public final int secondaryColor; + public final StatBase field_151512_d; + public final StatBase field_151513_e; + + public EntityEggInfo(int id, int baseColor, int spotColor) { + this.spawnedID = id; + this.primaryColor = baseColor; + this.secondaryColor = spotColor; + this.field_151512_d = StatList.getStatKillEntity(this); + this.field_151513_e = StatList.getStatEntityKilledBy(this); + } + } + private static final Logger logger = LogManager.getLogger(); private static final Map> stringToClassMapping = Maps.newHashMap(); private static final Map> stringToConstructorMapping = Maps @@ -110,210 +130,9 @@ public class EntityList { private static final Map, EntityConstructor> classToConstructorMapping = Maps .newHashMap(); private static final Map stringToIDMapping = Maps.newHashMap(); + public static final Map entityEggs = Maps.newLinkedHashMap(); - /**+ - * adds a mapping between Entity classes and both a string - * representation and an ID - */ - private static void addMapping(Class entityClass, - EntityConstructor entityConstructor, String entityName, int id) { - if (stringToClassMapping.containsKey(entityName)) { - throw new IllegalArgumentException("ID is already registered: " + entityName); - } else if (idToClassMapping.containsKey(Integer.valueOf(id))) { - throw new IllegalArgumentException("ID is already registered: " + id); - } else if (id == 0) { - throw new IllegalArgumentException("Cannot register to reserved id: " + id); - } else if (entityClass == null) { - throw new IllegalArgumentException("Cannot register null clazz for id: " + id); - } else { - stringToClassMapping.put(entityName, entityClass); - stringToConstructorMapping.put(entityName, entityConstructor); - classToStringMapping.put(entityClass, entityName); - idToClassMapping.put(Integer.valueOf(id), entityClass); - idToConstructorMapping.put(Integer.valueOf(id), entityConstructor); - classToIDMapping.put(entityClass, Integer.valueOf(id)); - classToConstructorMapping.put(entityClass, entityConstructor); - stringToIDMapping.put(entityName, Integer.valueOf(id)); - } - } - - /**+ - * adds a mapping between Entity classes and both a string - * representation and an ID - */ - private static void addMapping(Class entityClass, - EntityConstructor entityConstructor, String entityName, int entityID, int baseColor, - int spotColor) { - addMapping(entityClass, entityConstructor, entityName, entityID); - entityEggs.put(Integer.valueOf(entityID), new EntityList.EntityEggInfo(entityID, baseColor, spotColor)); - } - - /**+ - * Create a new instance of an entity in the world by using the - * entity name. - */ - public static Entity createEntityByName(String entityName, World worldIn) { - Entity entity = null; - - try { - EntityConstructor constructor = stringToConstructorMapping.get(entityName); - if (constructor != null) { - entity = constructor.createEntity(worldIn); - } - } catch (Exception exception) { - logger.error("Could not create entity", exception); - } - - return entity; - } - - public static Entity createEntityByClass(Class entityClass, World worldIn) { - Entity entity = null; - - try { - EntityConstructor constructor = classToConstructorMapping.get(entityClass); - if (constructor != null) { - entity = constructor.createEntity(worldIn); - } - } catch (Exception exception) { - logger.error("Could not create entity", exception); - } - - return entity; - } - - public static Entity createEntityByClassUnsafe(Class entityClass, World worldIn) { - EntityConstructor constructor = classToConstructorMapping.get(entityClass); - if (constructor != null) { - return constructor.createEntity(worldIn); - } - return null; - } - - /**+ - * create a new instance of an entity from NBT store - */ - public static Entity createEntityFromNBT(NBTTagCompound nbt, World worldIn) { - Entity entity = null; - if ("Minecart".equals(nbt.getString("id"))) { - nbt.setString("id", EntityMinecart.EnumMinecartType.byNetworkID(nbt.getInteger("Type")).getName()); - nbt.removeTag("Type"); - } - - try { - EntityConstructor constructor = stringToConstructorMapping.get(nbt.getString("id")); - if (constructor != null) { - entity = constructor.createEntity(worldIn); - } - } catch (Exception exception) { - logger.error("Could not create entity", exception); - } - - if (entity != null) { - entity.readFromNBT(nbt); - } else { - logger.warn("Skipping Entity with id " + nbt.getString("id")); - } - - return entity; - } - - /**+ - * Create a new instance of an entity in the world by using an - * entity ID. - */ - public static Entity createEntityByID(int entityID, World worldIn) { - Entity entity = null; - - try { - EntityConstructor constructor = getConstructorFromID(entityID); - if (constructor != null) { - entity = constructor.createEntity(worldIn); - } - } catch (Exception exception) { - logger.error("Could not create entity", exception); - } - - if (entity == null) { - logger.warn("Skipping Entity with id " + entityID); - } - - return entity; - } - - /**+ - * gets the entityID of a specific entity - */ - public static int getEntityID(Entity entityIn) { - Integer integer = (Integer) classToIDMapping.get(entityIn.getClass()); - return integer == null ? 0 : integer.intValue(); - } - - public static Class getClassFromID(int entityID) { - return (Class) idToClassMapping.get(Integer.valueOf(entityID)); - } - - public static EntityConstructor getConstructorFromID(int entityID) { - return idToConstructorMapping.get(Integer.valueOf(entityID)); - } - - /**+ - * Gets the string representation of a specific entity. - */ - public static String getEntityString(Entity entityIn) { - return (String) classToStringMapping.get(entityIn.getClass()); - } - - /**+ - * Returns the ID assigned to it's string representation - */ - public static int getIDFromString(String entityName) { - Integer integer = (Integer) stringToIDMapping.get(entityName); - return integer == null ? 90 : integer.intValue(); - } - - /**+ - * Finds the class using IDtoClassMapping and - * classToStringMapping - */ - public static String getStringFromID(int entityID) { - return (String) classToStringMapping.get(getClassFromID(entityID)); - } - - public static void func_151514_a() { - } - - public static List getEntityNameList() { - Set set = stringToClassMapping.keySet(); - ArrayList arraylist = Lists.newArrayList(); - - for (String s : set) { - Class oclass = (Class) stringToClassMapping.get(s); - if ((oclass.getModifiers() & 1024) != 1024) { - arraylist.add(s); - } - } - - arraylist.add("LightningBolt"); - return arraylist; - } - - public static boolean isStringEntityName(Entity entityIn, String entityName) { - String s = getEntityString(entityIn); - if (s == null && entityIn instanceof EntityPlayer) { - s = "Player"; - } else if (s == null && entityIn instanceof EntityLightningBolt) { - s = "LightningBolt"; - } - - return entityName.equals(s); - } - - public static boolean isStringValidEntityName(String entityName) { - return "Player".equals(entityName) || getEntityNameList().contains(entityName); - } - static { addMapping(EntityItem.class, EntityItem::new, "Item", 1); addMapping(EntityXPOrb.class, EntityXPOrb::new, "XPOrb", 2); @@ -383,21 +202,207 @@ public class EntityList { addMapping(EntityRabbit.class, EntityRabbit::new, "Rabbit", 101, 10051392, 7555121); addMapping(EntityVillager.class, EntityVillager::new, "Villager", 120, 5651507, 12422002); addMapping(EntityEnderCrystal.class, EntityEnderCrystal::new, "EnderCrystal", 200); + // Starlike + addMapping(EntityNetherCreeper.class, EntityNetherCreeper::new, "NetherCreeper", 201, 894731, 0); + } - public static class EntityEggInfo { - public final int spawnedID; - public final int primaryColor; - public final int secondaryColor; - public final StatBase field_151512_d; - public final StatBase field_151513_e; - - public EntityEggInfo(int id, int baseColor, int spotColor) { - this.spawnedID = id; - this.primaryColor = baseColor; - this.secondaryColor = spotColor; - this.field_151512_d = StatList.getStatKillEntity(this); - this.field_151513_e = StatList.getStatEntityKilledBy(this); + /** + * + adds a mapping between Entity classes and both a string representation and + * an ID + */ + private static void addMapping(Class entityClass, + EntityConstructor entityConstructor, String entityName, int id) { + if (stringToClassMapping.containsKey(entityName)) { + throw new IllegalArgumentException("ID is already registered: " + entityName); + } else if (idToClassMapping.containsKey(Integer.valueOf(id))) { + throw new IllegalArgumentException("ID is already registered: " + id); + } else if (id == 0) { + throw new IllegalArgumentException("Cannot register to reserved id: " + id); + } else if (entityClass == null) { + throw new IllegalArgumentException("Cannot register null clazz for id: " + id); + } else { + stringToClassMapping.put(entityName, entityClass); + stringToConstructorMapping.put(entityName, entityConstructor); + classToStringMapping.put(entityClass, entityName); + idToClassMapping.put(Integer.valueOf(id), entityClass); + idToConstructorMapping.put(Integer.valueOf(id), entityConstructor); + classToIDMapping.put(entityClass, Integer.valueOf(id)); + classToConstructorMapping.put(entityClass, entityConstructor); + stringToIDMapping.put(entityName, Integer.valueOf(id)); } } + + /** + * + adds a mapping between Entity classes and both a string representation and + * an ID + */ + private static void addMapping(Class entityClass, + EntityConstructor entityConstructor, String entityName, int entityID, int baseColor, + int spotColor) { + addMapping(entityClass, entityConstructor, entityName, entityID); + entityEggs.put(Integer.valueOf(entityID), new EntityList.EntityEggInfo(entityID, baseColor, spotColor)); + } + + public static Entity createEntityByClass(Class entityClass, World worldIn) { + Entity entity = null; + + try { + EntityConstructor constructor = classToConstructorMapping.get(entityClass); + if (constructor != null) { + entity = constructor.createEntity(worldIn); + } + } catch (Exception exception) { + logger.error("Could not create entity", exception); + } + + return entity; + } + + public static Entity createEntityByClassUnsafe(Class entityClass, World worldIn) { + EntityConstructor constructor = classToConstructorMapping.get(entityClass); + if (constructor != null) { + return constructor.createEntity(worldIn); + } + return null; + } + + /** + * + Create a new instance of an entity in the world by using an entity ID. + */ + public static Entity createEntityByID(int entityID, World worldIn) { + Entity entity = null; + + try { + EntityConstructor constructor = getConstructorFromID(entityID); + if (constructor != null) { + entity = constructor.createEntity(worldIn); + } + } catch (Exception exception) { + logger.error("Could not create entity", exception); + } + + if (entity == null) { + logger.warn("Skipping Entity with id " + entityID); + } + + return entity; + } + + /** + * + Create a new instance of an entity in the world by using the entity name. + */ + public static Entity createEntityByName(String entityName, World worldIn) { + Entity entity = null; + + try { + EntityConstructor constructor = stringToConstructorMapping.get(entityName); + if (constructor != null) { + entity = constructor.createEntity(worldIn); + } + } catch (Exception exception) { + logger.error("Could not create entity", exception); + } + + return entity; + } + + /** + * + create a new instance of an entity from NBT store + */ + public static Entity createEntityFromNBT(NBTTagCompound nbt, World worldIn) { + Entity entity = null; + if ("Minecart".equals(nbt.getString("id"))) { + nbt.setString("id", EntityMinecart.EnumMinecartType.byNetworkID(nbt.getInteger("Type")).getName()); + nbt.removeTag("Type"); + } + + try { + EntityConstructor constructor = stringToConstructorMapping.get(nbt.getString("id")); + if (constructor != null) { + entity = constructor.createEntity(worldIn); + } + } catch (Exception exception) { + logger.error("Could not create entity", exception); + } + + if (entity != null) { + entity.readFromNBT(nbt); + } else { + logger.warn("Skipping Entity with id " + nbt.getString("id")); + } + + return entity; + } + + public static void func_151514_a() { + } + + public static Class getClassFromID(int entityID) { + return (Class) idToClassMapping.get(Integer.valueOf(entityID)); + } + + public static EntityConstructor getConstructorFromID(int entityID) { + return idToConstructorMapping.get(Integer.valueOf(entityID)); + } + + /** + * + gets the entityID of a specific entity + */ + public static int getEntityID(Entity entityIn) { + Integer integer = (Integer) classToIDMapping.get(entityIn.getClass()); + return integer == null ? 0 : integer.intValue(); + } + + public static List getEntityNameList() { + Set set = stringToClassMapping.keySet(); + ArrayList arraylist = Lists.newArrayList(); + + for (String s : set) { + Class oclass = (Class) stringToClassMapping.get(s); + if ((oclass.getModifiers() & 1024) != 1024) { + arraylist.add(s); + } + } + + arraylist.add("LightningBolt"); + return arraylist; + } + + /** + * + Gets the string representation of a specific entity. + */ + public static String getEntityString(Entity entityIn) { + return (String) classToStringMapping.get(entityIn.getClass()); + } + + /** + * + Returns the ID assigned to it's string representation + */ + public static int getIDFromString(String entityName) { + Integer integer = (Integer) stringToIDMapping.get(entityName); + return integer == null ? 90 : integer.intValue(); + } + + /** + * + Finds the class using IDtoClassMapping and classToStringMapping + */ + public static String getStringFromID(int entityID) { + return (String) classToStringMapping.get(getClassFromID(entityID)); + } + + public static boolean isStringEntityName(Entity entityIn, String entityName) { + String s = getEntityString(entityIn); + if (s == null && entityIn instanceof EntityPlayer) { + s = "Player"; + } else if (s == null && entityIn instanceof EntityLightningBolt) { + s = "LightningBolt"; + } + + return entityName.equals(s); + } + + public static boolean isStringValidEntityName(String entityName) { + return "Player".equals(entityName) || getEntityNameList().contains(entityName); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityLiving.java b/src/game/java/net/minecraft/entity/EntityLiving.java index d243878d..0c232565 100644 --- a/src/game/java/net/minecraft/entity/EntityLiving.java +++ b/src/game/java/net/minecraft/entity/EntityLiving.java @@ -38,27 +38,114 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class EntityLiving extends EntityLivingBase { + public static enum SpawnPlacementType { + ON_GROUND, IN_AIR, IN_WATER; + } + + /** + * + Gets the vanilla armor Item that can go in the slot specified for the given + * tier. + */ + public static Item getArmorItemForSlot(int armorSlot, int itemTier) { + switch (armorSlot) { + case 4: + if (itemTier == 0) { + return Items.leather_helmet; + } else if (itemTier == 1) { + return Items.golden_helmet; + } else if (itemTier == 2) { + return Items.chainmail_helmet; + } else if (itemTier == 3) { + return Items.iron_helmet; + } else if (itemTier == 4) { + return Items.diamond_helmet; + } + case 3: + if (itemTier == 0) { + return Items.leather_chestplate; + } else if (itemTier == 1) { + return Items.golden_chestplate; + } else if (itemTier == 2) { + return Items.chainmail_chestplate; + } else if (itemTier == 3) { + return Items.iron_chestplate; + } else if (itemTier == 4) { + return Items.diamond_chestplate; + } + case 2: + if (itemTier == 0) { + return Items.leather_leggings; + } else if (itemTier == 1) { + return Items.golden_leggings; + } else if (itemTier == 2) { + return Items.chainmail_leggings; + } else if (itemTier == 3) { + return Items.iron_leggings; + } else if (itemTier == 4) { + return Items.diamond_leggings; + } + case 1: + if (itemTier == 0) { + return Items.leather_boots; + } else if (itemTier == 1) { + return Items.golden_boots; + } else if (itemTier == 2) { + return Items.chainmail_boots; + } else if (itemTier == 3) { + return Items.iron_boots; + } else if (itemTier == 4) { + return Items.diamond_boots; + } + default: + return null; + } + } + + public static int getArmorPosition(ItemStack stack) { + if (stack.getItem() != Item.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull) { + if (stack.getItem() instanceof ItemArmor) { + switch (((ItemArmor) stack.getItem()).armorType) { + case 0: + return 4; + case 1: + return 3; + case 2: + return 2; + case 3: + return 1; + } + } + + return 0; + } else { + return 4; + } + } + public int livingSoundTime; protected int experienceValue; private EntityLookHelper lookHelper; @@ -70,19 +157,21 @@ public abstract class EntityLiving extends EntityLivingBase { protected final EntityAITasks targetTasks; private EntityLivingBase attackTarget; private EntitySenses senses; - /**+ - * Equipment (armor and held item) for this entity. + /** + * + Equipment (armor and held item) for this entity. */ private ItemStack[] equipment = new ItemStack[5]; - /**+ - * Chances for each equipment piece from dropping when this - * entity dies. + /** + * + Chances for each equipment piece from dropping when this entity dies. */ protected float[] equipmentDropChances = new float[5]; private boolean canPickUpLoot; private boolean persistenceRequired; + private boolean isLeashed; + private Entity leashedToEntity; + private NBTTagCompound leashNBTTag; public EntityLiving(World worldIn) { @@ -102,108 +191,226 @@ public abstract class EntityLiving extends EntityLivingBase { } + public boolean allowLeashing() { + return !this.getLeashed() && !(this instanceof IMob); + } + protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getAttributeMap().registerAttribute(SharedMonsterAttributes.followRange).setBaseValue(16.0D); } - /**+ - * Returns new PathNavigateGround instance - */ - protected PathNavigate getNewNavigator(World worldIn) { - return new PathNavigateGround(this, worldIn); - } - - public EntityLookHelper getLookHelper() { - return this.lookHelper; - } - - public EntityMoveHelper getMoveHelper() { - return this.moveHelper; - } - - public EntityJumpHelper getJumpHelper() { - return this.jumpHelper; - } - - public PathNavigate getNavigator() { - return this.navigator; - } - - /**+ - * returns the EntitySenses Object for the EntityLiving - */ - public EntitySenses getEntitySenses() { - return this.senses; - } - - /**+ - * Gets the active target the Task system uses for tracking - */ - public EntityLivingBase getAttackTarget() { - return this.attackTarget; - } - - /**+ - * Sets the active target the Task system uses for tracking - */ - public void setAttackTarget(EntityLivingBase entitylivingbaseIn) { - this.attackTarget = entitylivingbaseIn; - } - - /**+ - * Returns true if this entity can attack entities of the - * specified class. + /** + * + Returns true if this entity can attack entities of the specified class. */ public boolean canAttackClass(Class cls) { return cls != EntityGhast.class; } - /**+ - * This function applies the benefits of growing back wool and - * faster growing up to the acting entity. (This function is - * used in the AIEatGrass) + /** + * + returns true if all the conditions for steering the entity are met. For + * pigs, this is true if it is being ridden by a player and the player is + * holding a carrot-on-a-stick + */ + public boolean canBeSteered() { + return false; + } + + /** + * + Determines if an entity can be despawned, used on idle far away entities + */ + protected boolean canDespawn() { + return true; + } + + public boolean canPickUpLoot() { + return this.canPickUpLoot; + } + + /** + * + Removes the leash from this entity + */ + public void clearLeashed(boolean sendPacket, boolean dropLead) { + if (this.isLeashed) { + this.isLeashed = false; + this.leashedToEntity = null; + if (!this.worldObj.isRemote && dropLead) { + this.dropItem(Items.lead, 1); + } + + if (!this.worldObj.isRemote && sendPacket && this.worldObj instanceof WorldServer) { + ((WorldServer) this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, + new S1BPacketEntityAttach(1, this, (Entity) null)); + } + } + + } + + /** + * + Makes the entity despawn if requirements are reached + */ + protected void despawnEntity() { + if (this.persistenceRequired) { + this.entityAge = 0; + } else { + EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, -1.0D); + if (entityplayer != null) { + double d0 = entityplayer.posX - this.posX; + double d1 = entityplayer.posY - this.posY; + double d2 = entityplayer.posZ - this.posZ; + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + if (this.canDespawn() && d3 > 16384.0D) { + this.setDead(); + } + + if (this.entityAge > 600 && this.rand.nextInt(800) == 0 && d3 > 1024.0D && this.canDespawn()) { + this.setDead(); + } else if (d3 < 1024.0D) { + this.entityAge = 0; + } + } + + } + } + + /** + * + Drop the equipment for this entity. + */ + protected void dropEquipment(boolean flag, int i) { + for (int j = 0; j < this.getInventory().length; ++j) { + ItemStack itemstack = this.getEquipmentInSlot(j); + boolean flag1 = this.equipmentDropChances[j] > 1.0F; + if (itemstack != null && (flag || flag1) + && this.rand.nextFloat() - (float) i * 0.01F < this.equipmentDropChances[j]) { + if (!flag1 && itemstack.isItemStackDamageable()) { + int k = Math.max(itemstack.getMaxDamage() - 25, 1); + int l = itemstack.getMaxDamage() - this.rand.nextInt(this.rand.nextInt(k) + 1); + if (l > k) { + l = k; + } + + if (l < 1) { + l = 1; + } + + itemstack.setItemDamage(l); + } + + this.entityDropItem(itemstack, 0.0F); + } + } + + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + Item item = this.getDropItem(); + if (item != null) { + int j = this.rand.nextInt(3); + if (i > 0) { + j += this.rand.nextInt(i + 1); + } + + for (int k = 0; k < j; ++k) { + this.dropItem(item, 1); + } + } + + } + + /** + * + This function applies the benefits of growing back wool and faster growing + * up to the acting entity. (This function is used in the AIEatGrass) */ public void eatGrassBonus() { } + /** + * + Enable the Entity persistence + */ + public void enablePersistence() { + this.persistenceRequired = true; + } + protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(15, Byte.valueOf((byte) 0)); } - /**+ - * Get number of ticks, at least during which the living entity - * will be silent. + /** + * + Changes pitch and yaw so that the entity calling the function is facing the + * entity provided as an argument. */ - public int getTalkInterval() { - return 80; - } - - /**+ - * Plays living's sound at its position - */ - public void playLivingSound() { - String s = this.getLivingSound(); - if (s != null) { - this.playSound(s, this.getSoundVolume(), this.getSoundPitch()); + public void faceEntity(Entity entityIn, float parFloat1, float parFloat2) { + double d0 = entityIn.posX - this.posX; + double d2 = entityIn.posZ - this.posZ; + double d1; + if (entityIn instanceof EntityLivingBase) { + EntityLivingBase entitylivingbase = (EntityLivingBase) entityIn; + d1 = entitylivingbase.posY + (double) entitylivingbase.getEyeHeight() + - (this.posY + (double) this.getEyeHeight()); + } else { + d1 = (entityIn.getEntityBoundingBox().minY + entityIn.getEntityBoundingBox().maxY) / 2.0D + - (this.posY + (double) this.getEyeHeight()); } + double d3 = (double) MathHelper.sqrt_double(d0 * d0 + d2 * d2); + float f = (float) (MathHelper.func_181159_b(d2, d0) * 180.0D / 3.1415927410125732D) - 90.0F; + float f1 = (float) (-(MathHelper.func_181159_b(d1, d3) * 180.0D / 3.1415927410125732D)); + this.rotationPitch = this.updateRotation(this.rotationPitch, f1, parFloat2); + this.rotationYaw = this.updateRotation(this.rotationYaw, f, parFloat1); } - /**+ - * Gets called every tick from main Entity class + protected float func_110146_f(float var1, float f) { + this.bodyHelper.updateRenderAngles(); + return f; + } + + protected boolean func_175448_a(ItemStack stack) { + return true; + } + + /** + * + Gets the active target the Task system uses for tracking */ - public void onEntityUpdate() { - super.onEntityUpdate(); - if (this.isEntityAlive() && this.rand.nextInt(1000) < this.livingSoundTime++) { - this.livingSoundTime = -this.getTalkInterval(); - this.playLivingSound(); - } + public EntityLivingBase getAttackTarget() { + return this.attackTarget; } - /**+ - * Get the experience points the entity currently has. + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return true; + } + + public ItemStack getCurrentArmor(int i) { + return this.equipment[i + 1]; + } + + protected Item getDropItem() { + return null; + } + + /** + * + returns the EntitySenses Object for the EntityLiving + */ + public EntitySenses getEntitySenses() { + return this.senses; + } + + /** + * + 0: Tool in Hand; 1-4: Armor + */ + public ItemStack getEquipmentInSlot(int i) { + return this.equipment[i]; + } + + /** + * + Get the experience points the entity currently has. */ protected int getExperiencePoints(EntityPlayer var1) { if (this.experienceValue > 0) { @@ -222,27 +429,104 @@ public abstract class EntityLiving extends EntityLivingBase { } } - /**+ - * Spawns an explosion particle around the Entity's location + /** + * + Returns the item that this EntityLiving is holding, if any. */ - public void spawnExplosionParticle() { - if (this.worldObj.isRemote) { - for (int i = 0; i < 20; ++i) { - double d0 = this.rand.nextGaussian() * 0.02D; - double d1 = this.rand.nextGaussian() * 0.02D; - double d2 = this.rand.nextGaussian() * 0.02D; - double d3 = 10.0D; - this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width - - d0 * d3, - this.posY + (double) (this.rand.nextFloat() * this.height) - d1 * d3, this.posZ - + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width - d2 * d3, - d0, d1, d2, new int[0]); - } - } else { - this.worldObj.setEntityState(this, (byte) 20); - } + public ItemStack getHeldItem() { + return this.equipment[0]; + } + /** + * + returns the inventory of this entity (only used in EntityPlayerMP it seems) + */ + public ItemStack[] getInventory() { + return this.equipment; + } + + public EntityJumpHelper getJumpHelper() { + return this.jumpHelper; + } + + public boolean getLeashed() { + return this.isLeashed; + } + + public Entity getLeashedToEntity() { + return this.leashedToEntity; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return null; + } + + public EntityLookHelper getLookHelper() { + return this.lookHelper; + } + + /** + * + The maximum height from where the entity is alowed to jump (used in + * pathfinder) + */ + public int getMaxFallHeight() { + if (this.getAttackTarget() == null) { + return 3; + } else { + int i = (int) (this.getHealth() - this.getMaxHealth() * 0.33F); + i = i - (3 - this.worldObj.getDifficulty().getDifficultyId()) * 4; + if (i < 0) { + i = 0; + } + + return i + 3; + } + } + + /** + * + Will return how many at most can spawn in a chunk at once. + */ + public int getMaxSpawnedInChunk() { + return 4; + } + + public EntityMoveHelper getMoveHelper() { + return this.moveHelper; + } + + public PathNavigate getNavigator() { + return this.navigator; + } + + /** + * + Returns new PathNavigateGround instance + */ + protected PathNavigate getNewNavigator(World worldIn) { + return new PathNavigateGround(this, worldIn); + } + + /** + * + Returns render size modifier + */ + public float getRenderSizeModifier() { + return 1.0F; + } + + /** + * + Get number of ticks, at least during which the living entity will be + * silent. + */ + public int getTalkInterval() { + return 80; + } + + /** + * + The speed it takes to move the entityliving's rotationPitch through the + * faceEntity method. This is only currently use in wolves. + */ + public int getVerticalFaceSpeed() { + return 40; } public void handleStatusUpdate(byte b0) { @@ -254,8 +538,116 @@ public abstract class EntityLiving extends EntityLivingBase { } - /**+ - * Called to update the entity's position/logic. + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + protected boolean interact(EntityPlayer var1) { + return false; + } + + /** + * + First layer of player interaction + */ + public final boolean interactFirst(EntityPlayer entityplayer) { + if (this.getLeashed() && this.getLeashedToEntity() == entityplayer) { + this.clearLeashed(true, !entityplayer.capabilities.isCreativeMode); + return true; + } else { + ItemStack itemstack = entityplayer.inventory.getCurrentItem(); + if (itemstack != null && itemstack.getItem() == Items.lead && this.allowLeashing()) { + if (!(this instanceof EntityTameable) || !((EntityTameable) this).isTamed()) { + this.setLeashedToEntity(entityplayer, true); + --itemstack.stackSize; + return true; + } + + if (((EntityTameable) this).isOwner(entityplayer)) { + this.setLeashedToEntity(entityplayer, true); + --itemstack.stackSize; + return true; + } + } + + if (this.interact(entityplayer)) { + return true; + } else { + return super.interactFirst(entityplayer); + } + } + } + + /** + * + Get whether this Entity's AI is disabled + */ + public boolean isAIDisabled() { + return this.dataWatcher.getWatchableObjectByte(15) != 0; + } + + public boolean isNoDespawnRequired() { + return this.persistenceRequired; + } + + /** + * + Checks that the entity is not colliding with any blocks / liquids + */ + public boolean isNotColliding() { + return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) + && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() + && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); + } + + /** + * + Returns whether the entity is in a server world + */ + public boolean isServerWorld() { + return super.isServerWorld() && !this.isAIDisabled(); + } + + /** + * + Gets called every tick from main Entity class + */ + public void onEntityUpdate() { + super.onEntityUpdate(); + if (this.isEntityAlive() && this.rand.nextInt(1000) < this.livingSoundTime++) { + this.livingSoundTime = -this.getTalkInterval(); + this.playLivingSound(); + } + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData livingdata) { + this.getEntityAttribute(SharedMonsterAttributes.followRange) + .applyModifier(new AttributeModifier("Random spawn bonus", this.rand.nextGaussian() * 0.05D, 1)); + return livingdata; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + super.onLivingUpdate(); + if (!this.worldObj.isRemote && this.canPickUpLoot() && !this.dead + && this.worldObj.getGameRules().getBoolean("mobGriefing")) { + List lst = this.worldObj.getEntitiesWithinAABB(EntityItem.class, + this.getEntityBoundingBox().expand(1.0D, 0.0D, 1.0D)); + for (int i = 0, l = lst.size(); i < l; ++i) { + EntityItem entityitem = lst.get(i); + if (!entityitem.isDead && entityitem.getEntityItem() != null && !entityitem.cannotPickup()) { + this.updateEquipmentIfNeeded(entityitem); + } + } + } + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -265,92 +657,19 @@ public abstract class EntityLiving extends EntityLivingBase { } - protected float func_110146_f(float var1, float f) { - this.bodyHelper.updateRenderAngles(); - return f; - } - - /**+ - * Returns the sound this mob makes while it's alive. + /** + * + Plays living's sound at its position */ - protected String getLivingSound() { - return null; - } - - protected Item getDropItem() { - return null; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - Item item = this.getDropItem(); - if (item != null) { - int j = this.rand.nextInt(3); - if (i > 0) { - j += this.rand.nextInt(i + 1); - } - - for (int k = 0; k < j; ++k) { - this.dropItem(item, 1); - } + public void playLivingSound() { + String s = this.getLivingSound(); + if (s != null) { + this.playSound(s, this.getSoundVolume(), this.getSoundPitch()); } } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("CanPickUpLoot", this.canPickUpLoot()); - nbttagcompound.setBoolean("PersistenceRequired", this.persistenceRequired); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.equipment.length; ++i) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - if (this.equipment[i] != null) { - this.equipment[i].writeToNBT(nbttagcompound1); - } - - nbttaglist.appendTag(nbttagcompound1); - } - - nbttagcompound.setTag("Equipment", nbttaglist); - NBTTagList nbttaglist1 = new NBTTagList(); - - for (int j = 0; j < this.equipmentDropChances.length; ++j) { - nbttaglist1.appendTag(new NBTTagFloat(this.equipmentDropChances[j])); - } - - nbttagcompound.setTag("DropChances", nbttaglist1); - nbttagcompound.setBoolean("Leashed", this.isLeashed); - if (this.leashedToEntity != null) { - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - if (this.leashedToEntity instanceof EntityLivingBase) { - nbttagcompound2.setLong("UUIDMost", this.leashedToEntity.getUniqueID().getMostSignificantBits()); - nbttagcompound2.setLong("UUIDLeast", this.leashedToEntity.getUniqueID().getLeastSignificantBits()); - } else if (this.leashedToEntity instanceof EntityHanging) { - BlockPos blockpos = ((EntityHanging) this.leashedToEntity).getHangingPosition(); - nbttagcompound2.setInteger("X", blockpos.getX()); - nbttagcompound2.setInteger("Y", blockpos.getY()); - nbttagcompound2.setInteger("Z", blockpos.getZ()); - } - - nbttagcompound.setTag("Leash", nbttagcompound2); - } - - if (this.isAIDisabled()) { - nbttagcompound.setBoolean("NoAI", this.isAIDisabled()); - } - - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -383,42 +702,212 @@ public abstract class EntityLiving extends EntityLivingBase { this.setNoAI(nbttagcompound.getBoolean("NoAI")); } - public void setMoveForward(float parFloat1) { - this.moveForward = parFloat1; + private void recreateLeash() { + if (this.isLeashed && this.leashNBTTag != null) { + if (this.leashNBTTag.hasKey("UUIDMost", 4) && this.leashNBTTag.hasKey("UUIDLeast", 4)) { + EaglercraftUUID uuid = new EaglercraftUUID(this.leashNBTTag.getLong("UUIDMost"), + this.leashNBTTag.getLong("UUIDLeast")); + + List entities = this.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, + this.getEntityBoundingBox().expand(10.0D, 10.0D, 10.0D)); + for (int i = 0, l = entities.size(); i < l; ++i) { + EntityLivingBase entitylivingbase = entities.get(i); + if (entitylivingbase.getUniqueID().equals(uuid)) { + this.leashedToEntity = entitylivingbase; + break; + } + } + } else if (this.leashNBTTag.hasKey("X", 99) && this.leashNBTTag.hasKey("Y", 99) + && this.leashNBTTag.hasKey("Z", 99)) { + BlockPos blockpos = new BlockPos(this.leashNBTTag.getInteger("X"), this.leashNBTTag.getInteger("Y"), + this.leashNBTTag.getInteger("Z")); + EntityLeashKnot entityleashknot = EntityLeashKnot.getKnotForPosition(this.worldObj, blockpos); + if (entityleashknot == null) { + entityleashknot = EntityLeashKnot.createKnot(this.worldObj, blockpos); + } + + this.leashedToEntity = entityleashknot; + } else { + this.clearLeashed(false, true); + } + } + + this.leashNBTTag = null; } - /**+ - * set the movespeed used for the new AI system + public boolean replaceItemInInventory(int i, ItemStack itemstack) { + int j; + if (i == 99) { + j = 0; + } else { + j = i - 100 + 1; + if (j < 0 || j >= this.equipment.length) { + return false; + } + } + + if (itemstack != null && getArmorPosition(itemstack) != j + && (j != 4 || !(itemstack.getItem() instanceof ItemBlock))) { + return false; + } else { + this.setCurrentItemOrArmor(j, itemstack); + return true; + } + } + + /** + * + set the movespeed used for the new AI system */ public void setAIMoveSpeed(float f) { super.setAIMoveSpeed(f); this.setMoveForward(f); } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Sets the active target the Task system uses for tracking */ - public void onLivingUpdate() { - super.onLivingUpdate(); - if (!this.worldObj.isRemote && this.canPickUpLoot() && !this.dead - && this.worldObj.getGameRules().getBoolean("mobGriefing")) { - List lst = this.worldObj.getEntitiesWithinAABB(EntityItem.class, - this.getEntityBoundingBox().expand(1.0D, 0.0D, 1.0D)); - for (int i = 0, l = lst.size(); i < l; ++i) { - EntityItem entityitem = lst.get(i); - if (!entityitem.isDead && entityitem.getEntityItem() != null && !entityitem.cannotPickup()) { - this.updateEquipmentIfNeeded(entityitem); + public void setAttackTarget(EntityLivingBase entitylivingbaseIn) { + this.attackTarget = entitylivingbaseIn; + } + + public void setCanPickUpLoot(boolean canPickup) { + this.canPickUpLoot = canPickup; + } + + /** + * + Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is + * armor. Params: Item, slot + */ + public void setCurrentItemOrArmor(int i, ItemStack itemstack) { + this.equipment[i] = itemstack; + } + + /** + * + Enchants Entity's current equipments based on given DifficultyInstance + */ + protected void setEnchantmentBasedOnDifficulty(DifficultyInstance difficulty) { + float f = difficulty.getClampedAdditionalDifficulty(); + if (this.getHeldItem() != null && this.rand.nextFloat() < 0.25F * f) { + EnchantmentHelper.addRandomEnchantment(this.rand, this.getHeldItem(), + (int) (5.0F + f * (float) this.rand.nextInt(18))); + } + + for (int i = 0; i < 4; ++i) { + ItemStack itemstack = this.getCurrentArmor(i); + if (itemstack != null && this.rand.nextFloat() < 0.5F * f) { + EnchantmentHelper.addRandomEnchantment(this.rand, itemstack, + (int) (5.0F + f * (float) this.rand.nextInt(18))); + } + } + + } + + /** + * + Gives armor or weapon for entity based on given DifficultyInstance + */ + protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficulty) { + if (this.rand.nextFloat() < 0.15F * difficulty.getClampedAdditionalDifficulty()) { + int i = this.rand.nextInt(2); + float f = this.worldObj.getDifficulty() == EnumDifficulty.HARD ? 0.1F : 0.25F; + if (this.rand.nextFloat() < 0.095F) { + ++i; + } + + if (this.rand.nextFloat() < 0.095F) { + ++i; + } + + if (this.rand.nextFloat() < 0.095F) { + ++i; + } + + for (int j = 3; j >= 0; --j) { + ItemStack itemstack = this.getCurrentArmor(j); + if (j < 3 && this.rand.nextFloat() < f) { + break; + } + + if (itemstack == null) { + Item item = getArmorItemForSlot(j + 1, i); + if (item != null) { + this.setCurrentItemOrArmor(j + 1, new ItemStack(item)); + } } } } + } - /**+ - * Tests if this entity should pickup a weapon or an armor. - * Entity drops current weapon or armor if the new one is - * better. + public void setEquipmentDropChance(int slotIn, float chance) { + this.equipmentDropChances[slotIn] = chance; + } + + /** + * + Sets the entity to be leashed to. + */ + public void setLeashedToEntity(Entity entityIn, boolean sendAttachNotification) { + this.isLeashed = true; + this.leashedToEntity = entityIn; + if (!this.worldObj.isRemote && sendAttachNotification && this.worldObj instanceof WorldServer) { + ((WorldServer) this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, + new S1BPacketEntityAttach(1, this, this.leashedToEntity)); + } + + } + + public void setMoveForward(float parFloat1) { + this.moveForward = parFloat1; + } + + /** + * + Set whether this Entity's AI is disabled + */ + public void setNoAI(boolean disable) { + this.dataWatcher.updateObject(15, Byte.valueOf((byte) (disable ? 1 : 0))); + } + + /** + * + Spawns an explosion particle around the Entity's location + */ + public void spawnExplosionParticle() { + if (this.worldObj.isRemote) { + for (int i = 0; i < 20; ++i) { + double d0 = this.rand.nextGaussian() * 0.02D; + double d1 = this.rand.nextGaussian() * 0.02D; + double d2 = this.rand.nextGaussian() * 0.02D; + double d3 = 10.0D; + this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width + - d0 * d3, + this.posY + (double) (this.rand.nextFloat() * this.height) - d1 * d3, this.posZ + + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width - d2 * d3, + d0, d1, d2, new int[0]); + } + } else { + this.worldObj.setEntityState(this, (byte) 20); + } + + } + + protected void updateAITasks() { + } + + protected final void updateEntityActionState() { + ++this.entityAge; + this.despawnEntity(); + this.senses.clearSensingCache(); + this.targetTasks.onUpdateTasks(); + this.tasks.onUpdateTasks(); + this.navigator.onUpdateNavigation(); + this.updateAITasks(); + this.moveHelper.onUpdateMoveHelper(); + this.lookHelper.onUpdateLook(); + this.jumpHelper.doJump(); + } + + /** + * + Tests if this entity should pickup a weapon or an armor. Entity drops + * current weapon or armor if the new one is better. */ protected void updateEquipmentIfNeeded(EntityItem itemEntity) { ItemStack itemstack = itemEntity.getEntityItem(); @@ -482,448 +971,9 @@ public abstract class EntityLiving extends EntityLivingBase { } - protected boolean func_175448_a(ItemStack stack) { - return true; - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return true; - } - - /**+ - * Makes the entity despawn if requirements are reached - */ - protected void despawnEntity() { - if (this.persistenceRequired) { - this.entityAge = 0; - } else { - EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, -1.0D); - if (entityplayer != null) { - double d0 = entityplayer.posX - this.posX; - double d1 = entityplayer.posY - this.posY; - double d2 = entityplayer.posZ - this.posZ; - double d3 = d0 * d0 + d1 * d1 + d2 * d2; - if (this.canDespawn() && d3 > 16384.0D) { - this.setDead(); - } - - if (this.entityAge > 600 && this.rand.nextInt(800) == 0 && d3 > 1024.0D && this.canDespawn()) { - this.setDead(); - } else if (d3 < 1024.0D) { - this.entityAge = 0; - } - } - - } - } - - protected final void updateEntityActionState() { - ++this.entityAge; - this.despawnEntity(); - this.senses.clearSensingCache(); - this.targetTasks.onUpdateTasks(); - this.tasks.onUpdateTasks(); - this.navigator.onUpdateNavigation(); - this.updateAITasks(); - this.moveHelper.onUpdateMoveHelper(); - this.lookHelper.onUpdateLook(); - this.jumpHelper.doJump(); - } - - protected void updateAITasks() { - } - - /**+ - * The speed it takes to move the entityliving's rotationPitch - * through the faceEntity method. This is only currently use in - * wolves. - */ - public int getVerticalFaceSpeed() { - return 40; - } - - /**+ - * Changes pitch and yaw so that the entity calling the function - * is facing the entity provided as an argument. - */ - public void faceEntity(Entity entityIn, float parFloat1, float parFloat2) { - double d0 = entityIn.posX - this.posX; - double d2 = entityIn.posZ - this.posZ; - double d1; - if (entityIn instanceof EntityLivingBase) { - EntityLivingBase entitylivingbase = (EntityLivingBase) entityIn; - d1 = entitylivingbase.posY + (double) entitylivingbase.getEyeHeight() - - (this.posY + (double) this.getEyeHeight()); - } else { - d1 = (entityIn.getEntityBoundingBox().minY + entityIn.getEntityBoundingBox().maxY) / 2.0D - - (this.posY + (double) this.getEyeHeight()); - } - - double d3 = (double) MathHelper.sqrt_double(d0 * d0 + d2 * d2); - float f = (float) (MathHelper.func_181159_b(d2, d0) * 180.0D / 3.1415927410125732D) - 90.0F; - float f1 = (float) (-(MathHelper.func_181159_b(d1, d3) * 180.0D / 3.1415927410125732D)); - this.rotationPitch = this.updateRotation(this.rotationPitch, f1, parFloat2); - this.rotationYaw = this.updateRotation(this.rotationYaw, f, parFloat1); - } - - /**+ - * Arguments: current rotation, intended rotation, max - * increment. - */ - private float updateRotation(float parFloat1, float parFloat2, float parFloat3) { - float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); - if (f > parFloat3) { - f = parFloat3; - } - - if (f < -parFloat3) { - f = -parFloat3; - } - - return parFloat1 + f; - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return true; - } - - /**+ - * Checks that the entity is not colliding with any blocks / - * liquids - */ - public boolean isNotColliding() { - return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) - && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() - && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); - } - - /**+ - * Returns render size modifier - */ - public float getRenderSizeModifier() { - return 1.0F; - } - - /**+ - * Will return how many at most can spawn in a chunk at once. - */ - public int getMaxSpawnedInChunk() { - return 4; - } - - /**+ - * The maximum height from where the entity is alowed to jump - * (used in pathfinder) - */ - public int getMaxFallHeight() { - if (this.getAttackTarget() == null) { - return 3; - } else { - int i = (int) (this.getHealth() - this.getMaxHealth() * 0.33F); - i = i - (3 - this.worldObj.getDifficulty().getDifficultyId()) * 4; - if (i < 0) { - i = 0; - } - - return i + 3; - } - } - - /**+ - * Returns the item that this EntityLiving is holding, if any. - */ - public ItemStack getHeldItem() { - return this.equipment[0]; - } - - /**+ - * 0: Tool in Hand; 1-4: Armor - */ - public ItemStack getEquipmentInSlot(int i) { - return this.equipment[i]; - } - - public ItemStack getCurrentArmor(int i) { - return this.equipment[i + 1]; - } - - /**+ - * Sets the held item, or an armor slot. Slot 0 is held item. - * Slot 1-4 is armor. Params: Item, slot - */ - public void setCurrentItemOrArmor(int i, ItemStack itemstack) { - this.equipment[i] = itemstack; - } - - /**+ - * returns the inventory of this entity (only used in - * EntityPlayerMP it seems) - */ - public ItemStack[] getInventory() { - return this.equipment; - } - - /**+ - * Drop the equipment for this entity. - */ - protected void dropEquipment(boolean flag, int i) { - for (int j = 0; j < this.getInventory().length; ++j) { - ItemStack itemstack = this.getEquipmentInSlot(j); - boolean flag1 = this.equipmentDropChances[j] > 1.0F; - if (itemstack != null && (flag || flag1) - && this.rand.nextFloat() - (float) i * 0.01F < this.equipmentDropChances[j]) { - if (!flag1 && itemstack.isItemStackDamageable()) { - int k = Math.max(itemstack.getMaxDamage() - 25, 1); - int l = itemstack.getMaxDamage() - this.rand.nextInt(this.rand.nextInt(k) + 1); - if (l > k) { - l = k; - } - - if (l < 1) { - l = 1; - } - - itemstack.setItemDamage(l); - } - - this.entityDropItem(itemstack, 0.0F); - } - } - - } - - /**+ - * Gives armor or weapon for entity based on given - * DifficultyInstance - */ - protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficulty) { - if (this.rand.nextFloat() < 0.15F * difficulty.getClampedAdditionalDifficulty()) { - int i = this.rand.nextInt(2); - float f = this.worldObj.getDifficulty() == EnumDifficulty.HARD ? 0.1F : 0.25F; - if (this.rand.nextFloat() < 0.095F) { - ++i; - } - - if (this.rand.nextFloat() < 0.095F) { - ++i; - } - - if (this.rand.nextFloat() < 0.095F) { - ++i; - } - - for (int j = 3; j >= 0; --j) { - ItemStack itemstack = this.getCurrentArmor(j); - if (j < 3 && this.rand.nextFloat() < f) { - break; - } - - if (itemstack == null) { - Item item = getArmorItemForSlot(j + 1, i); - if (item != null) { - this.setCurrentItemOrArmor(j + 1, new ItemStack(item)); - } - } - } - } - - } - - public static int getArmorPosition(ItemStack stack) { - if (stack.getItem() != Item.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull) { - if (stack.getItem() instanceof ItemArmor) { - switch (((ItemArmor) stack.getItem()).armorType) { - case 0: - return 4; - case 1: - return 3; - case 2: - return 2; - case 3: - return 1; - } - } - - return 0; - } else { - return 4; - } - } - - /**+ - * Gets the vanilla armor Item that can go in the slot specified - * for the given tier. - */ - public static Item getArmorItemForSlot(int armorSlot, int itemTier) { - switch (armorSlot) { - case 4: - if (itemTier == 0) { - return Items.leather_helmet; - } else if (itemTier == 1) { - return Items.golden_helmet; - } else if (itemTier == 2) { - return Items.chainmail_helmet; - } else if (itemTier == 3) { - return Items.iron_helmet; - } else if (itemTier == 4) { - return Items.diamond_helmet; - } - case 3: - if (itemTier == 0) { - return Items.leather_chestplate; - } else if (itemTier == 1) { - return Items.golden_chestplate; - } else if (itemTier == 2) { - return Items.chainmail_chestplate; - } else if (itemTier == 3) { - return Items.iron_chestplate; - } else if (itemTier == 4) { - return Items.diamond_chestplate; - } - case 2: - if (itemTier == 0) { - return Items.leather_leggings; - } else if (itemTier == 1) { - return Items.golden_leggings; - } else if (itemTier == 2) { - return Items.chainmail_leggings; - } else if (itemTier == 3) { - return Items.iron_leggings; - } else if (itemTier == 4) { - return Items.diamond_leggings; - } - case 1: - if (itemTier == 0) { - return Items.leather_boots; - } else if (itemTier == 1) { - return Items.golden_boots; - } else if (itemTier == 2) { - return Items.chainmail_boots; - } else if (itemTier == 3) { - return Items.iron_boots; - } else if (itemTier == 4) { - return Items.diamond_boots; - } - default: - return null; - } - } - - /**+ - * Enchants Entity's current equipments based on given - * DifficultyInstance - */ - protected void setEnchantmentBasedOnDifficulty(DifficultyInstance difficulty) { - float f = difficulty.getClampedAdditionalDifficulty(); - if (this.getHeldItem() != null && this.rand.nextFloat() < 0.25F * f) { - EnchantmentHelper.addRandomEnchantment(this.rand, this.getHeldItem(), - (int) (5.0F + f * (float) this.rand.nextInt(18))); - } - - for (int i = 0; i < 4; ++i) { - ItemStack itemstack = this.getCurrentArmor(i); - if (itemstack != null && this.rand.nextFloat() < 0.5F * f) { - EnchantmentHelper.addRandomEnchantment(this.rand, itemstack, - (int) (5.0F + f * (float) this.rand.nextInt(18))); - } - } - - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData livingdata) { - this.getEntityAttribute(SharedMonsterAttributes.followRange) - .applyModifier(new AttributeModifier("Random spawn bonus", this.rand.nextGaussian() * 0.05D, 1)); - return livingdata; - } - - /**+ - * returns true if all the conditions for steering the entity - * are met. For pigs, this is true if it is being ridden by a - * player and the player is holding a carrot-on-a-stick - */ - public boolean canBeSteered() { - return false; - } - - /**+ - * Enable the Entity persistence - */ - public void enablePersistence() { - this.persistenceRequired = true; - } - - public void setEquipmentDropChance(int slotIn, float chance) { - this.equipmentDropChances[slotIn] = chance; - } - - public boolean canPickUpLoot() { - return this.canPickUpLoot; - } - - public void setCanPickUpLoot(boolean canPickup) { - this.canPickUpLoot = canPickup; - } - - public boolean isNoDespawnRequired() { - return this.persistenceRequired; - } - - /**+ - * First layer of player interaction - */ - public final boolean interactFirst(EntityPlayer entityplayer) { - if (this.getLeashed() && this.getLeashedToEntity() == entityplayer) { - this.clearLeashed(true, !entityplayer.capabilities.isCreativeMode); - return true; - } else { - ItemStack itemstack = entityplayer.inventory.getCurrentItem(); - if (itemstack != null && itemstack.getItem() == Items.lead && this.allowLeashing()) { - if (!(this instanceof EntityTameable) || !((EntityTameable) this).isTamed()) { - this.setLeashedToEntity(entityplayer, true); - --itemstack.stackSize; - return true; - } - - if (((EntityTameable) this).isOwner(entityplayer)) { - this.setLeashedToEntity(entityplayer, true); - --itemstack.stackSize; - return true; - } - } - - if (this.interact(entityplayer)) { - return true; - } else { - return super.interactFirst(entityplayer); - } - } - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. - */ - protected boolean interact(EntityPlayer var1) { - return false; - } - - /**+ - * Applies logic related to leashes, for example dragging the - * entity or breaking the leash. + /** + * + Applies logic related to leashes, for example dragging the entity or + * breaking the leash. */ protected void updateLeashedState() { if (this.leashNBTTag != null) { @@ -941,125 +991,67 @@ public abstract class EntityLiving extends EntityLivingBase { } } - /**+ - * Removes the leash from this entity + /** + * + Arguments: current rotation, intended rotation, max increment. */ - public void clearLeashed(boolean sendPacket, boolean dropLead) { - if (this.isLeashed) { - this.isLeashed = false; - this.leashedToEntity = null; - if (!this.worldObj.isRemote && dropLead) { - this.dropItem(Items.lead, 1); + private float updateRotation(float parFloat1, float parFloat2, float parFloat3) { + float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); + if (f > parFloat3) { + f = parFloat3; + } + + if (f < -parFloat3) { + f = -parFloat3; + } + + return parFloat1 + f; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("CanPickUpLoot", this.canPickUpLoot()); + nbttagcompound.setBoolean("PersistenceRequired", this.persistenceRequired); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.equipment.length; ++i) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + if (this.equipment[i] != null) { + this.equipment[i].writeToNBT(nbttagcompound1); } - if (!this.worldObj.isRemote && sendPacket && this.worldObj instanceof WorldServer) { - ((WorldServer) this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, - new S1BPacketEntityAttach(1, this, (Entity) null)); + nbttaglist.appendTag(nbttagcompound1); + } + + nbttagcompound.setTag("Equipment", nbttaglist); + NBTTagList nbttaglist1 = new NBTTagList(); + + for (int j = 0; j < this.equipmentDropChances.length; ++j) { + nbttaglist1.appendTag(new NBTTagFloat(this.equipmentDropChances[j])); + } + + nbttagcompound.setTag("DropChances", nbttaglist1); + nbttagcompound.setBoolean("Leashed", this.isLeashed); + if (this.leashedToEntity != null) { + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + if (this.leashedToEntity instanceof EntityLivingBase) { + nbttagcompound2.setLong("UUIDMost", this.leashedToEntity.getUniqueID().getMostSignificantBits()); + nbttagcompound2.setLong("UUIDLeast", this.leashedToEntity.getUniqueID().getLeastSignificantBits()); + } else if (this.leashedToEntity instanceof EntityHanging) { + BlockPos blockpos = ((EntityHanging) this.leashedToEntity).getHangingPosition(); + nbttagcompound2.setInteger("X", blockpos.getX()); + nbttagcompound2.setInteger("Y", blockpos.getY()); + nbttagcompound2.setInteger("Z", blockpos.getZ()); } + + nbttagcompound.setTag("Leash", nbttagcompound2); } - } - - public boolean allowLeashing() { - return !this.getLeashed() && !(this instanceof IMob); - } - - public boolean getLeashed() { - return this.isLeashed; - } - - public Entity getLeashedToEntity() { - return this.leashedToEntity; - } - - /**+ - * Sets the entity to be leashed to. - */ - public void setLeashedToEntity(Entity entityIn, boolean sendAttachNotification) { - this.isLeashed = true; - this.leashedToEntity = entityIn; - if (!this.worldObj.isRemote && sendAttachNotification && this.worldObj instanceof WorldServer) { - ((WorldServer) this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, - new S1BPacketEntityAttach(1, this, this.leashedToEntity)); + if (this.isAIDisabled()) { + nbttagcompound.setBoolean("NoAI", this.isAIDisabled()); } } - - private void recreateLeash() { - if (this.isLeashed && this.leashNBTTag != null) { - if (this.leashNBTTag.hasKey("UUIDMost", 4) && this.leashNBTTag.hasKey("UUIDLeast", 4)) { - EaglercraftUUID uuid = new EaglercraftUUID(this.leashNBTTag.getLong("UUIDMost"), - this.leashNBTTag.getLong("UUIDLeast")); - - List entities = this.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, - this.getEntityBoundingBox().expand(10.0D, 10.0D, 10.0D)); - for (int i = 0, l = entities.size(); i < l; ++i) { - EntityLivingBase entitylivingbase = entities.get(i); - if (entitylivingbase.getUniqueID().equals(uuid)) { - this.leashedToEntity = entitylivingbase; - break; - } - } - } else if (this.leashNBTTag.hasKey("X", 99) && this.leashNBTTag.hasKey("Y", 99) - && this.leashNBTTag.hasKey("Z", 99)) { - BlockPos blockpos = new BlockPos(this.leashNBTTag.getInteger("X"), this.leashNBTTag.getInteger("Y"), - this.leashNBTTag.getInteger("Z")); - EntityLeashKnot entityleashknot = EntityLeashKnot.getKnotForPosition(this.worldObj, blockpos); - if (entityleashknot == null) { - entityleashknot = EntityLeashKnot.createKnot(this.worldObj, blockpos); - } - - this.leashedToEntity = entityleashknot; - } else { - this.clearLeashed(false, true); - } - } - - this.leashNBTTag = null; - } - - public boolean replaceItemInInventory(int i, ItemStack itemstack) { - int j; - if (i == 99) { - j = 0; - } else { - j = i - 100 + 1; - if (j < 0 || j >= this.equipment.length) { - return false; - } - } - - if (itemstack != null && getArmorPosition(itemstack) != j - && (j != 4 || !(itemstack.getItem() instanceof ItemBlock))) { - return false; - } else { - this.setCurrentItemOrArmor(j, itemstack); - return true; - } - } - - /**+ - * Returns whether the entity is in a server world - */ - public boolean isServerWorld() { - return super.isServerWorld() && !this.isAIDisabled(); - } - - /**+ - * Set whether this Entity's AI is disabled - */ - public void setNoAI(boolean disable) { - this.dataWatcher.updateObject(15, Byte.valueOf((byte) (disable ? 1 : 0))); - } - - /**+ - * Get whether this Entity's AI is disabled - */ - public boolean isAIDisabled() { - return this.dataWatcher.getWatchableObjectByte(15) != 0; - } - - public static enum SpawnPlacementType { - ON_GROUND, IN_AIR, IN_WATER; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityLivingBase.java b/src/game/java/net/minecraft/entity/EntityLivingBase.java index 8d5e59b2..a34e5597 100644 --- a/src/game/java/net/minecraft/entity/EntityLivingBase.java +++ b/src/game/java/net/minecraft/entity/EntityLivingBase.java @@ -1,13 +1,14 @@ package net.minecraft.entity; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; -import com.google.common.collect.Maps; - import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Maps; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.Block; @@ -53,22 +54,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -81,9 +85,8 @@ public abstract class EntityLivingBase extends Entity { private BaseAttributeMap attributeMap; private final CombatTracker _combatTracker = new CombatTracker(this); private final Map activePotionsMap = Maps.newHashMap(); - /**+ - * The equipment this mob was previously wearing, used for - * syncing. + /** + * + The equipment this mob was previously wearing, used for syncing. */ private final ItemStack[] previousEquipment = new ItemStack[5]; public boolean isSwingInProgress; @@ -107,9 +110,9 @@ public abstract class EntityLivingBase extends Entity { public float prevRenderYawOffset; public float rotationYawHead; public float prevRotationYawHead; - /**+ - * A factor used to determine how far this entity will move each - * tick if it is jumping or falling. + /** + * + A factor used to determine how far this entity will move each tick if it is + * jumping or falling. */ public float jumpMovementFactor = 0.02F; protected EntityPlayer attackingPlayer; @@ -133,9 +136,8 @@ public abstract class EntityLivingBase extends Entity { protected double newPosZ; protected double newRotationYaw; protected double newRotationPitch; - /**+ - * Whether the DataWatcher needs to be updated with the active - * potions + /** + * + Whether the DataWatcher needs to be updated with the active potions */ private boolean potionsNeedUpdate = true; private EntityLivingBase entityLivingToAttack; @@ -146,13 +148,6 @@ public abstract class EntityLivingBase extends Entity { private int jumpTicks; private float absorptionAmount; - /**+ - * Called by the /kill command. - */ - public void onKillCommand() { - this.attackEntityFrom(DamageSource.outOfWorld, Float.MAX_VALUE); - } - public EntityLivingBase(World worldIn) { super(worldIn); this.applyEntityAttributes(); @@ -166,451 +161,8 @@ public abstract class EntityLivingBase extends Entity { this.stepHeight = 0.6F; } - protected void entityInit() { - this.dataWatcher.addObject(7, Integer.valueOf(0)); - this.dataWatcher.addObject(8, Byte.valueOf((byte) 0)); - this.dataWatcher.addObject(9, Byte.valueOf((byte) 0)); - this.dataWatcher.addObject(6, Float.valueOf(1.0F)); - } - - protected void applyEntityAttributes() { - this.getAttributeMap().registerAttribute(SharedMonsterAttributes.maxHealth); - this.getAttributeMap().registerAttribute(SharedMonsterAttributes.knockbackResistance); - this.getAttributeMap().registerAttribute(SharedMonsterAttributes.movementSpeed); - } - - protected void updateFallState(double d0, boolean flag, Block block, BlockPos blockpos) { - if (!this.isInWater()) { - this.handleWaterMovement(); - } - - if (!this.worldObj.isRemote && this.fallDistance > 3.0F && flag) { - IBlockState iblockstate = this.worldObj.getBlockState(blockpos); - Block block1 = iblockstate.getBlock(); - float f = (float) MathHelper.ceiling_float_int(this.fallDistance - 3.0F); - if (block1.getMaterial() != Material.air) { - double d1 = (double) Math.min(0.2F + f / 15.0F, 10.0F); - if (d1 > 2.5D) { - d1 = 2.5D; - } - - int i = (int) (150.0D * d1); - ((WorldServer) this.worldObj).spawnParticle(EnumParticleTypes.BLOCK_DUST, this.posX, this.posY, - this.posZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D, - new int[] { Block.getStateId(iblockstate) }); - } - } - - super.updateFallState(d0, flag, block, blockpos); - } - - public boolean canBreatheUnderwater() { - return false; - } - - /**+ - * Gets called every tick from main Entity class - */ - public void onEntityUpdate() { - this.prevSwingProgress = this.swingProgress; - super.onEntityUpdate(); - boolean flag = this instanceof EntityPlayer; - if (this.isEntityAlive()) { - if (this.isEntityInsideOpaqueBlock()) { - this.attackEntityFrom(DamageSource.inWall, 1.0F); - } else if (flag && !this.worldObj.getWorldBorder().contains(this.getEntityBoundingBox())) { - double d0 = this.worldObj.getWorldBorder().getClosestDistance(this) - + this.worldObj.getWorldBorder().getDamageBuffer(); - if (d0 < 0.0D) { - this.attackEntityFrom(DamageSource.inWall, (float) Math.max(1, - MathHelper.floor_double(-d0 * this.worldObj.getWorldBorder().getDamageAmount()))); - } - } - } - - if (this.isImmuneToFire() || this.worldObj.isRemote) { - this.extinguish(); - } - - boolean flag1 = flag && ((EntityPlayer) this).capabilities.disableDamage; - if (this.isEntityAlive()) { - if (this.isInsideOfMaterial(Material.water)) { - if (!this.canBreatheUnderwater() && !this.isPotionActive(Potion.waterBreathing.id) && !flag1) { - this.setAir(this.decreaseAirSupply(this.getAir())); - if (this.getAir() == -20) { - this.setAir(0); - - for (int i = 0; i < 8; ++i) { - float f = this.rand.nextFloat() - this.rand.nextFloat(); - float f1 = this.rand.nextFloat() - this.rand.nextFloat(); - float f2 = this.rand.nextFloat() - this.rand.nextFloat(); - this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + (double) f, - this.posY + (double) f1, this.posZ + (double) f2, this.motionX, this.motionY, - this.motionZ, new int[0]); - } - - this.attackEntityFrom(DamageSource.drown, 2.0F); - } - } - - if (!this.worldObj.isRemote && this.isRiding() && this.ridingEntity instanceof EntityLivingBase) { - this.mountEntity((Entity) null); - } - } else { - this.setAir(300); - } - } - - if (this.isEntityAlive() && this.isWet()) { - this.extinguish(); - } - - this.prevCameraPitch = this.cameraPitch; - if (this.hurtTime > 0) { - --this.hurtTime; - } - - if (this.hurtResistantTime > 0 && !(this instanceof EntityPlayerMP)) { - --this.hurtResistantTime; - } - - if (this.getHealth() <= 0.0F) { - this.onDeathUpdate(); - } - - if (this.recentlyHit > 0) { - --this.recentlyHit; - } else { - this.attackingPlayer = null; - } - - if (this.lastAttacker != null && !this.lastAttacker.isEntityAlive()) { - this.lastAttacker = null; - } - - if (this.entityLivingToAttack != null) { - if (!this.entityLivingToAttack.isEntityAlive()) { - this.setRevengeTarget((EntityLivingBase) null); - } else if (this.ticksExisted - this.revengeTimer > 100) { - this.setRevengeTarget((EntityLivingBase) null); - } - } - - this.updatePotionEffects(); - this.prevMovedDistance = this.movedDistance; - this.prevRenderYawOffset = this.renderYawOffset; - this.prevRotationYawHead = this.rotationYawHead; - this.prevRotationYaw = this.rotationYaw; - this.prevRotationPitch = this.rotationPitch; - } - - /**+ - * If Animal, checks if the age timer is negative - */ - public boolean isChild() { - return false; - } - - /**+ - * handles entity death timer, experience orb and particle - * creation - */ - protected void onDeathUpdate() { - ++this.deathTime; - if (this.deathTime == 20) { - if (!this.worldObj.isRemote && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() - && this.worldObj.getGameRules().getBoolean("doMobLoot")) { - int i = this.getExperiencePoints(this.attackingPlayer); - - while (i > 0) { - int j = EntityXPOrb.getXPSplit(i); - i -= j; - this.worldObj - .spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, j)); - } - } - - this.setDead(); - - for (int k = 0; k < 20; ++k) { - double d2 = this.rand.nextGaussian() * 0.02D; - double d0 = this.rand.nextGaussian() * 0.02D; - double d1 = this.rand.nextGaussian() * 0.02D; - this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, - this.posY + (double) (this.rand.nextFloat() * this.height), - this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d2, d0, - d1, new int[0]); - } - } - - } - - /**+ - * Entity won't drop items or experience points if this returns - * false - */ - protected boolean canDropLoot() { - return !this.isChild(); - } - - /**+ - * Decrements the entity's air supply when underwater - */ - protected int decreaseAirSupply(int parInt1) { - int i = EnchantmentHelper.getRespiration(this); - return i > 0 && this.rand.nextInt(i + 1) > 0 ? parInt1 : parInt1 - 1; - } - - /**+ - * Get the experience points the entity currently has. - */ - protected int getExperiencePoints(EntityPlayer player) { - return 0; - } - - /**+ - * Only use is to identify if class is an instance of player for - * experience dropping - */ - protected boolean isPlayer() { - return false; - } - - public EaglercraftRandom getRNG() { - return this.rand; - } - - public EntityLivingBase getAITarget() { - return this.entityLivingToAttack; - } - - public int getRevengeTimer() { - return this.revengeTimer; - } - - public void setRevengeTarget(EntityLivingBase livingBase) { - this.entityLivingToAttack = livingBase; - this.revengeTimer = this.ticksExisted; - } - - public EntityLivingBase getLastAttacker() { - return this.lastAttacker; - } - - public int getLastAttackerTime() { - return this.lastAttackerTime; - } - - public void setLastAttacker(Entity entityIn) { - if (entityIn instanceof EntityLivingBase) { - this.lastAttacker = (EntityLivingBase) entityIn; - } else { - this.lastAttacker = null; - } - - this.lastAttackerTime = this.ticksExisted; - } - - public int getAge() { - return this.entityAge; - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setFloat("HealF", this.getHealth()); - nbttagcompound.setShort("Health", (short) ((int) Math.ceil((double) this.getHealth()))); - nbttagcompound.setShort("HurtTime", (short) this.hurtTime); - nbttagcompound.setInteger("HurtByTimestamp", this.revengeTimer); - nbttagcompound.setShort("DeathTime", (short) this.deathTime); - nbttagcompound.setFloat("AbsorptionAmount", this.getAbsorptionAmount()); - - ItemStack[] inv = this.getInventory(); - for (int i = 0; i < inv.length; ++i) { - ItemStack itemstack = inv[i]; - if (itemstack != null) { - this.attributeMap.removeAttributeModifiers(itemstack.getAttributeModifiers()); - } - } - - nbttagcompound.setTag("Attributes", SharedMonsterAttributes.writeBaseAttributeMapToNBT(this.getAttributeMap())); - - for (int i = 0; i < inv.length; ++i) { - ItemStack itemstack1 = inv[i]; - if (itemstack1 != null) { - this.attributeMap.applyAttributeModifiers(itemstack1.getAttributeModifiers()); - } - } - - if (!this.activePotionsMap.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); - - for (PotionEffect potioneffect : this.activePotionsMap.values()) { - nbttaglist.appendTag(potioneffect.writeCustomPotionEffectToNBT(new NBTTagCompound())); - } - - nbttagcompound.setTag("ActiveEffects", nbttaglist); - } - - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - this.setAbsorptionAmount(nbttagcompound.getFloat("AbsorptionAmount")); - if (nbttagcompound.hasKey("Attributes", 9) && this.worldObj != null && !this.worldObj.isRemote) { - SharedMonsterAttributes.func_151475_a(this.getAttributeMap(), nbttagcompound.getTagList("Attributes", 10)); - } - - if (nbttagcompound.hasKey("ActiveEffects", 9)) { - NBTTagList nbttaglist = nbttagcompound.getTagList("ActiveEffects", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound1); - if (potioneffect != null) { - this.activePotionsMap.put(Integer.valueOf(potioneffect.getPotionID()), potioneffect); - } - } - } - - if (nbttagcompound.hasKey("HealF", 99)) { - this.setHealth(nbttagcompound.getFloat("HealF")); - } else { - NBTBase nbtbase = nbttagcompound.getTag("Health"); - if (nbtbase == null) { - this.setHealth(this.getMaxHealth()); - } else if (nbtbase.getId() == 5) { - this.setHealth(((NBTTagFloat) nbtbase).getFloat()); - } else if (nbtbase.getId() == 2) { - this.setHealth((float) ((NBTTagShort) nbtbase).getShort()); - } - } - - this.hurtTime = nbttagcompound.getShort("HurtTime"); - this.deathTime = nbttagcompound.getShort("DeathTime"); - this.revengeTimer = nbttagcompound.getInteger("HurtByTimestamp"); - } - - protected void updatePotionEffects() { - Iterator iterator = this.activePotionsMap.keySet().iterator(); - - while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); - PotionEffect potioneffect = (PotionEffect) this.activePotionsMap.get(integer); - if (!potioneffect.onUpdate(this)) { - if (!this.worldObj.isRemote) { - iterator.remove(); - this.onFinishedPotionEffect(potioneffect); - } - } else if (potioneffect.getDuration() % 600 == 0) { - this.onChangedPotionEffect(potioneffect, false); - } - } - - if (this.potionsNeedUpdate) { - if (!this.worldObj.isRemote) { - this.updatePotionMetadata(); - } - - this.potionsNeedUpdate = false; - } - - int i = this.dataWatcher.getWatchableObjectInt(7); - boolean flag1 = this.dataWatcher.getWatchableObjectByte(8) > 0; - if (i > 0) { - boolean flag = false; - if (!this.isInvisible()) { - flag = this.rand.nextBoolean(); - } else { - flag = this.rand.nextInt(15) == 0; - } - - if (flag1) { - flag &= this.rand.nextInt(5) == 0; - } - - if (flag && i > 0) { - double d0 = (double) (i >> 16 & 255) / 255.0D; - double d1 = (double) (i >> 8 & 255) / 255.0D; - double d2 = (double) (i >> 0 & 255) / 255.0D; - this.worldObj.spawnParticle(flag1 ? EnumParticleTypes.SPELL_MOB_AMBIENT : EnumParticleTypes.SPELL_MOB, - this.posX + (this.rand.nextDouble() - 0.5D) * (double) this.width, - this.posY + this.rand.nextDouble() * (double) this.height, - this.posZ + (this.rand.nextDouble() - 0.5D) * (double) this.width, d0, d1, d2, new int[0]); - } - } - - } - - /**+ - * Clears potion metadata values if the entity has no potion - * effects. Otherwise, updates potion effect color, ambience, - * and invisibility metadata values - */ - protected void updatePotionMetadata() { - if (this.activePotionsMap.isEmpty()) { - this.resetPotionEffectMetadata(); - this.setInvisible(false); - } else { - int i = PotionHelper.calcPotionLiquidColor(this.activePotionsMap.values()); - this.dataWatcher.updateObject(8, - Byte.valueOf((byte) (PotionHelper.getAreAmbient(this.activePotionsMap.values()) ? 1 : 0))); - this.dataWatcher.updateObject(7, Integer.valueOf(i)); - this.setInvisible(this.isPotionActive(Potion.invisibility.id)); - } - - } - - /**+ - * Resets the potion effect color and ambience metadata values - */ - protected void resetPotionEffectMetadata() { - this.dataWatcher.updateObject(8, Byte.valueOf((byte) 0)); - this.dataWatcher.updateObject(7, Integer.valueOf(0)); - } - - public void clearActivePotions() { - Iterator iterator = this.activePotionsMap.keySet().iterator(); - - while (iterator.hasNext()) { - Integer integer = (Integer) iterator.next(); - PotionEffect potioneffect = (PotionEffect) this.activePotionsMap.get(integer); - if (!this.worldObj.isRemote) { - iterator.remove(); - this.onFinishedPotionEffect(potioneffect); - } - } - - } - - public Collection getActivePotionEffects() { - return this.activePotionsMap.values(); - } - - public boolean isPotionActive(int potionId) { - return this.activePotionsMap.containsKey(Integer.valueOf(potionId)); - } - - public boolean isPotionActive(Potion potionIn) { - return this.activePotionsMap.containsKey(Integer.valueOf(potionIn.id)); - } - - /**+ - * returns the PotionEffect for the supplied Potion if it is - * active, null otherwise. - */ - public PotionEffect getActivePotionEffect(Potion potionIn) { - return (PotionEffect) this.activePotionsMap.get(Integer.valueOf(potionIn.id)); - } - - /**+ - * adds a PotionEffect to the entity + /** + * + adds a PotionEffect to the entity */ public void addPotionEffect(PotionEffect potioneffectIn) { if (this.isPotionApplicable(potioneffectIn)) { @@ -627,92 +179,72 @@ public abstract class EntityLivingBase extends Entity { } } - public boolean isPotionApplicable(PotionEffect potioneffectIn) { - if (this.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD) { - int i = potioneffectIn.getPotionID(); - if (i == Potion.regeneration.id || i == Potion.poison.id) { - return false; + /** + * + Causes this Entity to drop a random item. + */ + protected void addRandomDrop() { + } + + /** + * + Reduces damage, depending on armor + */ + protected float applyArmorCalculations(DamageSource source, float damage) { + if (!source.isUnblockable()) { + int i = 25 - this.getTotalArmorValue(); + float f = damage * (float) i; + this.damageArmor(damage); + damage = f / 25.0F; + } + + return damage; + } + + protected void applyEntityAttributes() { + this.getAttributeMap().registerAttribute(SharedMonsterAttributes.maxHealth); + this.getAttributeMap().registerAttribute(SharedMonsterAttributes.knockbackResistance); + this.getAttributeMap().registerAttribute(SharedMonsterAttributes.movementSpeed); + } + + /** + * + Reduces damage, depending on potions + */ + protected float applyPotionDamageCalculations(DamageSource source, float damage) { + if (source.isDamageAbsolute()) { + return damage; + } else { + if (this.isPotionActive(Potion.resistance) && source != DamageSource.outOfWorld) { + int i = (this.getActivePotionEffect(Potion.resistance).getAmplifier() + 1) * 5; + int j = 25 - i; + float f = damage * (float) j; + damage = f / 25.0F; + } + + if (damage <= 0.0F) { + return 0.0F; + } else { + int k = EnchantmentHelper.getEnchantmentModifierDamage(this.getInventory(), source); + if (k > 20) { + k = 20; + } + + if (k > 0 && k <= 20) { + int l = 25 - k; + float f1 = damage * (float) l; + damage = f1 / 25.0F; + } + + return damage; } } - - return true; } - /**+ - * Returns true if this entity is undead. - */ - public boolean isEntityUndead() { - return this.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD; + public boolean attackEntityAsMob(Entity entityIn) { + this.setLastAttacker(entityIn); + return false; } - /**+ - * Remove the speified potion effect from this entity. - */ - public void removePotionEffectClient(int potionId) { - this.activePotionsMap.remove(Integer.valueOf(potionId)); - } - - /**+ - * Remove the specified potion effect from this entity. - */ - public void removePotionEffect(int potionId) { - PotionEffect potioneffect = (PotionEffect) this.activePotionsMap.remove(Integer.valueOf(potionId)); - if (potioneffect != null) { - this.onFinishedPotionEffect(potioneffect); - } - - } - - protected void onNewPotionEffect(PotionEffect potioneffect) { - this.potionsNeedUpdate = true; - if (!this.worldObj.isRemote) { - Potion.potionTypes[potioneffect.getPotionID()].applyAttributesModifiersToEntity(this, - this.getAttributeMap(), potioneffect.getAmplifier()); - } - - } - - protected void onChangedPotionEffect(PotionEffect potioneffect, boolean flag) { - this.potionsNeedUpdate = true; - if (flag && !this.worldObj.isRemote) { - Potion.potionTypes[potioneffect.getPotionID()].removeAttributesModifiersFromEntity(this, - this.getAttributeMap(), potioneffect.getAmplifier()); - Potion.potionTypes[potioneffect.getPotionID()].applyAttributesModifiersToEntity(this, - this.getAttributeMap(), potioneffect.getAmplifier()); - } - - } - - protected void onFinishedPotionEffect(PotionEffect potioneffect) { - this.potionsNeedUpdate = true; - if (!this.worldObj.isRemote) { - Potion.potionTypes[potioneffect.getPotionID()].removeAttributesModifiersFromEntity(this, - this.getAttributeMap(), potioneffect.getAmplifier()); - } - - } - - /**+ - * Heal living entity (param: amount of half-hearts) - */ - public void heal(float f) { - float f1 = this.getHealth(); - if (f1 > 0.0F) { - this.setHealth(f1 + f); - } - - } - - public final float getHealth() { - return this.dataWatcher.getWatchableObjectFloat(6); - } - - public void setHealth(float health) { - this.dataWatcher.updateObject(6, Float.valueOf(MathHelper.clamp_float(health, 0.0F, this.getMaxHealth()))); - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (this.isEntityInvulnerable(damagesource)) { @@ -810,239 +342,83 @@ public abstract class EntityLivingBase extends Entity { } } - /**+ - * Renders broken item particles using the given ItemStack + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. */ - public void renderBrokenItemStack(ItemStack stack) { - this.playSound("random.break", 0.8F, 0.8F + this.worldObj.rand.nextFloat() * 0.4F); - - for (int i = 0; i < 5; ++i) { - Vec3 vec3 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); - vec3 = vec3.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); - vec3 = vec3.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); - double d0 = (double) (-this.rand.nextFloat()) * 0.6D - 0.3D; - Vec3 vec31 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); - vec31 = vec31.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); - vec31 = vec31.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); - vec31 = vec31.addVector(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); - this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, - vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, new int[] { Item.getIdFromItem(stack.getItem()) }); - } - + public boolean canBeCollidedWith() { + return !this.isDead; } - /**+ - * Called when the mob's health reaches 0. + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. */ - public void onDeath(DamageSource damagesource) { - Entity entity = damagesource.getEntity(); - EntityLivingBase entitylivingbase = this.func_94060_bK(); - if (this.scoreValue >= 0 && entitylivingbase != null) { - entitylivingbase.addToPlayerScore(this, this.scoreValue); - } - - if (entity != null) { - entity.onKillEntity(this); - } - - this.dead = true; - this.getCombatTracker().reset(); - if (!this.worldObj.isRemote) { - int i = 0; - if (entity instanceof EntityPlayer) { - i = EnchantmentHelper.getLootingModifier((EntityLivingBase) entity); - } - - if (this.canDropLoot() && this.worldObj.getGameRules().getBoolean("doMobLoot")) { - this.dropFewItems(this.recentlyHit > 0, i); - this.dropEquipment(this.recentlyHit > 0, i); - if (this.recentlyHit > 0 && this.rand.nextFloat() < 0.025F + (float) i * 0.01F) { - this.addRandomDrop(); - } - } - } - - this.worldObj.setEntityState(this, (byte) 3); + public boolean canBePushed() { + return !this.isDead; } - /**+ - * Drop the equipment for this entity. - */ - protected void dropEquipment(boolean parFlag, int parInt1) { + public boolean canBreatheUnderwater() { + return false; } - /**+ - * knocks back this entity + /** + * + Entity won't drop items or experience points if this returns false */ - public void knockBack(Entity entityIn, float parFloat1, double parDouble1, double parDouble2) { - if (this.rand.nextDouble() >= this.getEntityAttribute(SharedMonsterAttributes.knockbackResistance) - .getAttributeValue()) { - this.isAirBorne = true; - float f = MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble2 * parDouble2); - float f1 = 0.4F; - this.motionX /= 2.0D; - this.motionY /= 2.0D; - this.motionZ /= 2.0D; - this.motionX -= parDouble1 / (double) f * (double) f1; - this.motionY += (double) f1; - this.motionZ -= parDouble2 / (double) f * (double) f1; - if (this.motionY > 0.4000000059604645D) { - this.motionY = 0.4000000059604645D; - } - - } + protected boolean canDropLoot() { + return !this.isChild(); } - /**+ - * Returns the sound this mob makes when it is hurt. + /** + * + returns true if the entity provided in the argument can be seen. (Raytrace) */ - protected String getHurtSound() { - return "game.neutral.hurt"; + public boolean canEntityBeSeen(Entity entityIn) { + return this.worldObj.rayTraceBlocks(new Vec3(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ), + new Vec3(entityIn.posX, entityIn.posY + (double) entityIn.getEyeHeight(), entityIn.posZ)) == null; } - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "game.neutral.die"; - } + public void clearActivePotions() { + Iterator iterator = this.activePotionsMap.keySet().iterator(); - /**+ - * Causes this Entity to drop a random item. - */ - protected void addRandomDrop() { - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean parFlag, int parInt1) { - } - - /**+ - * returns true if this entity is by a ladder, false otherwise - */ - public boolean isOnLadder() { - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.getEntityBoundingBox().minY); - int k = MathHelper.floor_double(this.posZ); - Block block = this.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock(); - return (block == Blocks.ladder || block == Blocks.vine) - && (!(this instanceof EntityPlayer) || !((EntityPlayer) this).isSpectator()); - } - - /**+ - * Checks whether target entity is alive. - */ - public boolean isEntityAlive() { - return !this.isDead && this.getHealth() > 0.0F; - } - - public void fall(float f, float f1) { - super.fall(f, f1); - PotionEffect potioneffect = this.getActivePotionEffect(Potion.jump); - float f2 = potioneffect != null ? (float) (potioneffect.getAmplifier() + 1) : 0.0F; - int i = MathHelper.ceiling_float_int((f - 3.0F - f2) * f1); - if (i > 0) { - this.playSound(this.getFallSoundString(i), 1.0F, 1.0F); - this.attackEntityFrom(DamageSource.fall, (float) i); - int j = MathHelper.floor_double(this.posX); - int k = MathHelper.floor_double(this.posY - 0.20000000298023224D); - int l = MathHelper.floor_double(this.posZ); - Block block = this.worldObj.getBlockState(new BlockPos(j, k, l)).getBlock(); - if (block.getMaterial() != Material.air) { - Block.SoundType block$soundtype = block.stepSound; - this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.5F, - block$soundtype.getFrequency() * 0.75F); + while (iterator.hasNext()) { + Integer integer = (Integer) iterator.next(); + PotionEffect potioneffect = (PotionEffect) this.activePotionsMap.get(integer); + if (!this.worldObj.isRemote) { + iterator.remove(); + this.onFinishedPotionEffect(potioneffect); } } } - protected String getFallSoundString(int damageValue) { - return damageValue > 4 ? "game.neutral.hurt.fall.big" : "game.neutral.hurt.fall.small"; + protected void collideWithEntity(Entity parEntity) { + parEntity.applyEntityCollision(this); } - /**+ - * Setups the entity to do the hurt animation. Only used by - * packets in multiplayer. - */ - public void performHurtAnimation() { - this.hurtTime = this.maxHurtTime = 10; - this.attackedAtYaw = 0.0F; - } - - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - int i = 0; - - for (ItemStack itemstack : this.getInventory()) { - if (itemstack != null && itemstack.getItem() instanceof ItemArmor) { - int j = ((ItemArmor) itemstack.getItem()).damageReduceAmount; - i += j; + protected void collideWithNearbyEntities() { + List list = this.worldObj.getEntitiesInAABBexcluding(this, + this.getEntityBoundingBox().expand(0.20000000298023224D, 0.0D, 0.20000000298023224D), + Predicates.and(EntitySelectors.NOT_SPECTATING, new Predicate() { + public boolean apply(Entity entity1) { + return entity1.canBePushed(); + } + })); + if (!list.isEmpty()) { + for (int i = 0; i < list.size(); ++i) { + Entity entity = (Entity) list.get(i); + this.collideWithEntity(entity); } } - return i; } protected void damageArmor(float parFloat1) { } - /**+ - * Reduces damage, depending on armor - */ - protected float applyArmorCalculations(DamageSource source, float damage) { - if (!source.isUnblockable()) { - int i = 25 - this.getTotalArmorValue(); - float f = damage * (float) i; - this.damageArmor(damage); - damage = f / 25.0F; - } - - return damage; - } - - /**+ - * Reduces damage, depending on potions - */ - protected float applyPotionDamageCalculations(DamageSource source, float damage) { - if (source.isDamageAbsolute()) { - return damage; - } else { - if (this.isPotionActive(Potion.resistance) && source != DamageSource.outOfWorld) { - int i = (this.getActivePotionEffect(Potion.resistance).getAmplifier() + 1) * 5; - int j = 25 - i; - float f = damage * (float) j; - damage = f / 25.0F; - } - - if (damage <= 0.0F) { - return 0.0F; - } else { - int k = EnchantmentHelper.getEnchantmentModifierDamage(this.getInventory(), source); - if (k > 20) { - k = 20; - } - - if (k > 0 && k <= 20) { - int l = 25 - k; - float f1 = damage * (float) l; - damage = f1 / 25.0F; - } - - return damage; - } - } - } - - /**+ - * Deals damage to the entity. If its a EntityPlayer then will - * take damage from the armor first and then health second with - * the reduced value. Args: damageAmount + /** + * + Deals damage to the entity. If its a EntityPlayer then will take damage + * from the armor first and then health second with the reduced value. Args: + * damageAmount */ protected void damageEntity(DamageSource damagesource, float f) { if (!this.isEntityInvulnerable(damagesource)) { @@ -1060,190 +436,16 @@ public abstract class EntityLivingBase extends Entity { } } - public CombatTracker getCombatTracker() { - return this._combatTracker; - } - - public EntityLivingBase func_94060_bK() { - return (EntityLivingBase) (this._combatTracker.func_94550_c() != null ? this._combatTracker.func_94550_c() - : (this.attackingPlayer != null ? this.attackingPlayer - : (this.entityLivingToAttack != null ? this.entityLivingToAttack : null))); - } - - public final float getMaxHealth() { - return (float) this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getAttributeValue(); - } - - /**+ - * counts the amount of arrows stuck in the entity. getting hit - * by arrows increases this, used in rendering + /** + * + Decrements the entity's air supply when underwater */ - public final int getArrowCountInEntity() { - return this.dataWatcher.getWatchableObjectByte(9); + protected int decreaseAirSupply(int parInt1) { + int i = EnchantmentHelper.getRespiration(this); + return i > 0 && this.rand.nextInt(i + 1) > 0 ? parInt1 : parInt1 - 1; } - /**+ - * sets the amount of arrows stuck in the entity. used for - * rendering those - */ - public final void setArrowCountInEntity(int count) { - this.dataWatcher.updateObject(9, Byte.valueOf((byte) count)); - } - - /**+ - * Returns an integer indicating the end point of the swing - * animation, used by {@link #swingProgress} to provide a - * progress indicator. Takes dig speed enchantments into - * account. - */ - private int getArmSwingAnimationEnd() { - return this.isPotionActive(Potion.digSpeed) - ? 6 - (1 + this.getActivePotionEffect(Potion.digSpeed).getAmplifier()) * 1 - : (this.isPotionActive(Potion.digSlowdown) - ? 6 + (1 + this.getActivePotionEffect(Potion.digSlowdown).getAmplifier()) * 2 - : 6); - } - - /**+ - * Swings the item the player is holding. - */ - public void swingItem() { - if (!this.isSwingInProgress || this.swingProgressInt >= this.getArmSwingAnimationEnd() / 2 - || this.swingProgressInt < 0) { - this.swingProgressInt = -1; - this.isSwingInProgress = true; - if (this.worldObj instanceof WorldServer) { - ((WorldServer) this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, - new S0BPacketAnimation(this, 0)); - } - } - - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 2) { - this.limbSwingAmount = 1.5F; - this.hurtResistantTime = this.maxHurtResistantTime; - this.hurtTime = this.maxHurtTime = 10; - this.attackedAtYaw = 0.0F; - String s = this.getHurtSound(); - if (s != null) { - this.playSound(this.getHurtSound(), this.getSoundVolume(), - (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); - } - - this.attackEntityFrom(DamageSource.generic, 0.0F); - } else if (b0 == 3) { - String s1 = this.getDeathSound(); - if (s1 != null) { - this.playSound(this.getDeathSound(), this.getSoundVolume(), - (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); - } - - this.setHealth(0.0F); - this.onDeath(DamageSource.generic); - } else { - super.handleStatusUpdate(b0); - } - - } - - /**+ - * sets the dead flag. Used when you fall off the bottom of the - * world. - */ - protected void kill() { - this.attackEntityFrom(DamageSource.outOfWorld, 4.0F); - } - - /**+ - * Updates the arm swing progress counters and animation - * progress - */ - protected void updateArmSwingProgress() { - int i = this.getArmSwingAnimationEnd(); - if (this.isSwingInProgress) { - ++this.swingProgressInt; - if (this.swingProgressInt >= i) { - this.swingProgressInt = 0; - this.isSwingInProgress = false; - } - } else { - this.swingProgressInt = 0; - } - - this.swingProgress = (float) this.swingProgressInt / (float) i; - } - - public IAttributeInstance getEntityAttribute(IAttribute attribute) { - return this.getAttributeMap().getAttributeInstance(attribute); - } - - public BaseAttributeMap getAttributeMap() { - if (this.attributeMap == null) { - this.attributeMap = new ServersideAttributeMap(); - } - - return this.attributeMap; - } - - /**+ - * Get this Entity's EnumCreatureAttribute - */ - public EnumCreatureAttribute getCreatureAttribute() { - return EnumCreatureAttribute.UNDEFINED; - } - - public abstract ItemStack getHeldItem(); - - public abstract ItemStack getEquipmentInSlot(int var1); - - public abstract ItemStack getCurrentArmor(int var1); - - public abstract void setCurrentItemOrArmor(int var1, ItemStack var2); - - /**+ - * Set sprinting switch for Entity. - */ - public void setSprinting(boolean flag) { - super.setSprinting(flag); - IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); - if (iattributeinstance.getModifier(sprintingSpeedBoostModifierUUID) != null) { - iattributeinstance.removeModifier(sprintingSpeedBoostModifier); - } - - if (flag) { - iattributeinstance.applyModifier(sprintingSpeedBoostModifier); - } - - } - - public abstract ItemStack[] getInventory(); - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 1.0F; - } - - /**+ - * Gets the pitch of living sounds in living entities. - */ - protected float getSoundPitch() { - return this.isChild() ? (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.5F - : (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F; - } - - /**+ - * Dead and sleeping entities cannot move - */ - protected boolean isMovementBlocked() { - return this.getHealth() <= 0.0F; - } - - /**+ - * Moves the entity to a position out of the way of its mount. + /** + * + Moves the entity to a position out of the way of its mount. */ public void dismountEntity(Entity parEntity) { double d0 = parEntity.posX; @@ -1278,16 +480,444 @@ public abstract class EntityLivingBase extends Entity { this.setPositionAndUpdate(d0, d1, d2); } + /** + * + Drop the equipment for this entity. + */ + protected void dropEquipment(boolean parFlag, int parInt1) { + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean parFlag, int parInt1) { + } + + protected void entityInit() { + this.dataWatcher.addObject(7, Integer.valueOf(0)); + this.dataWatcher.addObject(8, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(9, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(6, Float.valueOf(1.0F)); + } + + public void fall(float f, float f1) { + super.fall(f, f1); + PotionEffect potioneffect = this.getActivePotionEffect(Potion.jump); + float f2 = potioneffect != null ? (float) (potioneffect.getAmplifier() + 1) : 0.0F; + int i = MathHelper.ceiling_float_int((f - 3.0F - f2) * f1); + if (i > 0) { + this.playSound(this.getFallSoundString(i), 1.0F, 1.0F); + this.attackEntityFrom(DamageSource.fall, (float) i); + int j = MathHelper.floor_double(this.posX); + int k = MathHelper.floor_double(this.posY - 0.20000000298023224D); + int l = MathHelper.floor_double(this.posZ); + Block block = this.worldObj.getBlockState(new BlockPos(j, k, l)).getBlock(); + if (block.getMaterial() != Material.air) { + Block.SoundType block$soundtype = block.stepSound; + this.playSound(block$soundtype.getStepSound(), block$soundtype.getVolume() * 0.5F, + block$soundtype.getFrequency() * 0.75F); + } + } + + } + + protected float func_110146_f(float parFloat1, float parFloat2) { + float f = MathHelper.wrapAngleTo180_float(parFloat1 - this.renderYawOffset); + this.renderYawOffset += f * 0.3F; + float f1 = MathHelper.wrapAngleTo180_float(this.rotationYaw - this.renderYawOffset); + boolean flag = f1 < -90.0F || f1 >= 90.0F; + if (f1 < -75.0F) { + f1 = -75.0F; + } + + if (f1 >= 75.0F) { + f1 = 75.0F; + } + + this.renderYawOffset = this.rotationYaw - f1; + if (f1 * f1 > 2500.0F) { + this.renderYawOffset += f1 * 0.2F; + } + + if (flag) { + parFloat2 *= -1.0F; + } + + return parFloat2; + } + + public void func_181013_g(float f) { + this.renderYawOffset = f; + } + + public EntityLivingBase func_94060_bK() { + return (EntityLivingBase) (this._combatTracker.func_94550_c() != null ? this._combatTracker.func_94550_c() + : (this.attackingPlayer != null ? this.attackingPlayer + : (this.entityLivingToAttack != null ? this.entityLivingToAttack : null))); + } + + public float getAbsorptionAmount() { + return this.absorptionAmount; + } + + /** + * + returns the PotionEffect for the supplied Potion if it is active, null + * otherwise. + */ + public PotionEffect getActivePotionEffect(Potion potionIn) { + return (PotionEffect) this.activePotionsMap.get(Integer.valueOf(potionIn.id)); + } + + public Collection getActivePotionEffects() { + return this.activePotionsMap.values(); + } + + public int getAge() { + return this.entityAge; + } + + /** + * + the movespeed used for the new AI system + */ + public float getAIMoveSpeed() { + return this.landMovementFactor; + } + + public EntityLivingBase getAITarget() { + return this.entityLivingToAttack; + } + public boolean getAlwaysRenderNameTagForRender() { return false; } + /** + * + Returns an integer indicating the end point of the swing animation, used by + * {@link #swingProgress} to provide a progress indicator. Takes dig speed + * enchantments into account. + */ + private int getArmSwingAnimationEnd() { + return this.isPotionActive(Potion.digSpeed) + ? 6 - (1 + this.getActivePotionEffect(Potion.digSpeed).getAmplifier()) * 1 + : (this.isPotionActive(Potion.digSlowdown) + ? 6 + (1 + this.getActivePotionEffect(Potion.digSlowdown).getAmplifier()) * 2 + : 6); + } + + /** + * + counts the amount of arrows stuck in the entity. getting hit by arrows + * increases this, used in rendering + */ + public final int getArrowCountInEntity() { + return this.dataWatcher.getWatchableObjectByte(9); + } + + public BaseAttributeMap getAttributeMap() { + if (this.attributeMap == null) { + this.attributeMap = new ServersideAttributeMap(); + } + + return this.attributeMap; + } + + public CombatTracker getCombatTracker() { + return this._combatTracker; + } + + /** + * + Get this Entity's EnumCreatureAttribute + */ + public EnumCreatureAttribute getCreatureAttribute() { + return EnumCreatureAttribute.UNDEFINED; + } + + public abstract ItemStack getCurrentArmor(int var1); + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "game.neutral.die"; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + ItemStack itm = this.getHeldItem(); + if (itm != null && itm.stackSize > 0) { + Item item = itm.getItem(); + if (item != null) { + float f2 = item.getHeldItemBrightnessEagler(itm); + f = Math.min(f + f2 * 0.5f, 1.0f) + f2 * 0.5f; + } + } + return f; + } + + public IAttributeInstance getEntityAttribute(IAttribute attribute) { + return this.getAttributeMap().getAttributeInstance(attribute); + } + + public abstract ItemStack getEquipmentInSlot(int var1); + + /** + * + Get the experience points the entity currently has. + */ + protected int getExperiencePoints(EntityPlayer player) { + return 0; + } + + protected String getFallSoundString(int damageValue) { + return damageValue > 4 ? "game.neutral.hurt.fall.big" : "game.neutral.hurt.fall.small"; + } + + public final float getHealth() { + return this.dataWatcher.getWatchableObjectFloat(6); + } + + public abstract ItemStack getHeldItem(); + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "game.neutral.hurt"; + } + + public abstract ItemStack[] getInventory(); + protected float getJumpUpwardsMotion() { return 0.42F; } - /**+ - * Causes this entity to do an upwards motion (jumping). + public EntityLivingBase getLastAttacker() { + return this.lastAttacker; + } + + public int getLastAttackerTime() { + return this.lastAttackerTime; + } + + /** + * + interpolated look vector + */ + public Vec3 getLook(float f) { + if (f == 1.0F) { + return this.getVectorForRotation(this.rotationPitch, this.rotationYawHead); + } else { + float f1 = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * f; + float f2 = this.prevRotationYawHead + (this.rotationYawHead - this.prevRotationYawHead) * f; + return this.getVectorForRotation(f1, f2); + } + } + + /** + * + returns a (normalized) vector of where this entity is looking + */ + public Vec3 getLookVec() { + return this.getLook(1.0F); + } + + public final float getMaxHealth() { + return (float) this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getAttributeValue(); + } + + public int getRevengeTimer() { + return this.revengeTimer; + } + + public EaglercraftRandom getRNG() { + return this.rand; + } + + public float getRotationYawHead() { + return this.rotationYawHead; + } + + /** + * + Gets the pitch of living sounds in living entities. + */ + protected float getSoundPitch() { + return this.isChild() ? (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.5F + : (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 1.0F; + } + + /** + * + Returns where in the swing animation the living entity is (from 0 to 1). + * Args: partialTickTime + */ + public float getSwingProgress(float partialTickTime) { + float f = this.swingProgress - this.prevSwingProgress; + if (f < 0.0F) { + ++f; + } + + return this.prevSwingProgress + f * partialTickTime; + } + + public Team getTeam() { + return this.worldObj.getScoreboard().getPlayersTeam(this.getUniqueID().toString()); + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue + */ + public int getTotalArmorValue() { + int i = 0; + + for (ItemStack itemstack : this.getInventory()) { + if (itemstack != null && itemstack.getItem() instanceof ItemArmor) { + int j = ((ItemArmor) itemstack.getItem()).damageReduceAmount; + i += j; + } + } + + return i; + } + + protected void handleJumpLava() { + this.motionY += 0.03999999910593033D; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 2) { + this.limbSwingAmount = 1.5F; + this.hurtResistantTime = this.maxHurtResistantTime; + this.hurtTime = this.maxHurtTime = 10; + this.attackedAtYaw = 0.0F; + String s = this.getHurtSound(); + if (s != null) { + this.playSound(this.getHurtSound(), this.getSoundVolume(), + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); + } + + this.attackEntityFrom(DamageSource.generic, 0.0F); + } else if (b0 == 3) { + String s1 = this.getDeathSound(); + if (s1 != null) { + this.playSound(this.getDeathSound(), this.getSoundVolume(), + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); + } + + this.setHealth(0.0F); + this.onDeath(DamageSource.generic); + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Heal living entity (param: amount of half-hearts) + */ + public void heal(float f) { + float f1 = this.getHealth(); + if (f1 > 0.0F) { + this.setHealth(f1 + f); + } + + } + + /** + * + If Animal, checks if the age timer is negative + */ + public boolean isChild() { + return false; + } + + /** + * + Checks whether target entity is alive. + */ + public boolean isEntityAlive() { + return !this.isDead && this.getHealth() > 0.0F; + } + + /** + * + Returns true if this entity is undead. + */ + public boolean isEntityUndead() { + return this.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD; + } + + /** + * + Dead and sleeping entities cannot move + */ + protected boolean isMovementBlocked() { + return this.getHealth() <= 0.0F; + } + + /** + * + returns true if this entity is by a ladder, false otherwise + */ + public boolean isOnLadder() { + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.getEntityBoundingBox().minY); + int k = MathHelper.floor_double(this.posZ); + Block block = this.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock(); + return (block == Blocks.ladder || block == Blocks.vine) + && (!(this instanceof EntityPlayer) || !((EntityPlayer) this).isSpectator()); + } + + public boolean isOnSameTeam(EntityLivingBase otherEntity) { + return this.isOnTeam(otherEntity.getTeam()); + } + + /** + * + Returns true if the entity is on a specific team. + */ + public boolean isOnTeam(Team parTeam) { + return this.getTeam() != null ? this.getTeam().isSameTeam(parTeam) : false; + } + + /** + * + Only use is to identify if class is an instance of player for experience + * dropping + */ + protected boolean isPlayer() { + return false; + } + + /** + * + Returns whether player is sleeping or not + */ + public boolean isPlayerSleeping() { + return false; + } + + public boolean isPotionActive(int potionId) { + return this.activePotionsMap.containsKey(Integer.valueOf(potionId)); + } + + public boolean isPotionActive(Potion potionIn) { + return this.activePotionsMap.containsKey(Integer.valueOf(potionIn.id)); + } + + public boolean isPotionApplicable(PotionEffect potioneffectIn) { + if (this.getCreatureAttribute() == EnumCreatureAttribute.UNDEAD) { + int i = potioneffectIn.getPotionID(); + if (i == Potion.regeneration.id || i == Potion.poison.id) { + return false; + } + } + + return true; + } + + /** + * + Returns whether the entity is in a server world + */ + public boolean isServerWorld() { + return !this.worldObj.isRemote; + } + + /** + * + Causes this entity to do an upwards motion (jumping). */ protected void jump() { this.motionY = (double) this.getJumpUpwardsMotion(); @@ -1304,20 +934,60 @@ public abstract class EntityLivingBase extends Entity { this.isAirBorne = true; } - /**+ - * main AI tick function, replaces updateEntityActionState + /** + * + sets the dead flag. Used when you fall off the bottom of the world. */ - protected void updateAITick() { - this.motionY += 0.03999999910593033D; + protected void kill() { + this.attackEntityFrom(DamageSource.outOfWorld, 4.0F); } - protected void handleJumpLava() { - this.motionY += 0.03999999910593033D; + /** + * + knocks back this entity + */ + public void knockBack(Entity entityIn, float parFloat1, double parDouble1, double parDouble2) { + if (this.rand.nextDouble() >= this.getEntityAttribute(SharedMonsterAttributes.knockbackResistance) + .getAttributeValue()) { + this.isAirBorne = true; + float f = MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble2 * parDouble2); + float f1 = 0.4F; + this.motionX /= 2.0D; + this.motionY /= 2.0D; + this.motionZ /= 2.0D; + this.motionX -= parDouble1 / (double) f * (double) f1; + this.motionY += (double) f1; + this.motionZ -= parDouble2 / (double) f * (double) f1; + if (this.motionY > 0.4000000059604645D) { + this.motionY = 0.4000000059604645D; + } + + } } - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward + protected void markPotionsDirty() { + this.potionsNeedUpdate = true; + } + + /** + * + Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. + */ + public void mountEntity(Entity entity) { + if (this.ridingEntity != null && entity == null) { + if (!this.worldObj.isRemote) { + this.dismountEntity(this.ridingEntity); + } + + if (this.ridingEntity != null) { + this.ridingEntity.riddenByEntity = null; + } + + this.ridingEntity = null; + } else { + super.mountEntity(entity); + } + } + + /** + * + Moves the entity based on the specified heading. Args: strafe, forward */ public void moveEntityWithHeading(float f, float f1) { if (this.isServerWorld()) { @@ -1439,34 +1109,303 @@ public abstract class EntityLivingBase extends Entity { this.limbSwing += this.limbSwingAmount; } - /**+ - * the movespeed used for the new AI system + protected void onChangedPotionEffect(PotionEffect potioneffect, boolean flag) { + this.potionsNeedUpdate = true; + if (flag && !this.worldObj.isRemote) { + Potion.potionTypes[potioneffect.getPotionID()].removeAttributesModifiersFromEntity(this, + this.getAttributeMap(), potioneffect.getAmplifier()); + Potion.potionTypes[potioneffect.getPotionID()].applyAttributesModifiersToEntity(this, + this.getAttributeMap(), potioneffect.getAmplifier()); + } + + } + + /** + * + Called when the mob's health reaches 0. */ - public float getAIMoveSpeed() { - return this.landMovementFactor; + public void onDeath(DamageSource damagesource) { + Entity entity = damagesource.getEntity(); + EntityLivingBase entitylivingbase = this.func_94060_bK(); + if (this.scoreValue >= 0 && entitylivingbase != null) { + entitylivingbase.addToPlayerScore(this, this.scoreValue); + } + + if (entity != null) { + entity.onKillEntity(this); + } + + this.dead = true; + this.getCombatTracker().reset(); + if (!this.worldObj.isRemote) { + int i = 0; + if (entity instanceof EntityPlayer) { + i = EnchantmentHelper.getLootingModifier((EntityLivingBase) entity); + } + + if (this.canDropLoot() && this.worldObj.getGameRules().getBoolean("doMobLoot")) { + this.dropFewItems(this.recentlyHit > 0, i); + this.dropEquipment(this.recentlyHit > 0, i); + if (this.recentlyHit > 0 && this.rand.nextFloat() < 0.025F + (float) i * 0.01F) { + this.addRandomDrop(); + } + } + } + + this.worldObj.setEntityState(this, (byte) 3); } - /**+ - * set the movespeed used for the new AI system + /** + * + handles entity death timer, experience orb and particle creation */ - public void setAIMoveSpeed(float speedIn) { - this.landMovementFactor = speedIn; + protected void onDeathUpdate() { + ++this.deathTime; + if (this.deathTime == 20) { + if (!this.worldObj.isRemote && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() + && this.worldObj.getGameRules().getBoolean("doMobLoot")) { + int i = this.getExperiencePoints(this.attackingPlayer); + + while (i > 0) { + int j = EntityXPOrb.getXPSplit(i); + i -= j; + this.worldObj + .spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, j)); + } + } + + this.setDead(); + + for (int k = 0; k < 20; ++k) { + double d2 = this.rand.nextGaussian() * 0.02D; + double d0 = this.rand.nextGaussian() * 0.02D; + double d1 = this.rand.nextGaussian() * 0.02D; + this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, + this.posY + (double) (this.rand.nextFloat() * this.height), + this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d2, d0, + d1, new int[0]); + } + } + } - public boolean attackEntityAsMob(Entity entityIn) { - this.setLastAttacker(entityIn); - return false; - } - - /**+ - * Returns whether player is sleeping or not + /** + * + Gets called every tick from main Entity class */ - public boolean isPlayerSleeping() { - return false; + public void onEntityUpdate() { + this.prevSwingProgress = this.swingProgress; + super.onEntityUpdate(); + boolean flag = this instanceof EntityPlayer; + if (this.isEntityAlive()) { + if (this.isEntityInsideOpaqueBlock()) { + this.attackEntityFrom(DamageSource.inWall, 1.0F); + } else if (flag && !this.worldObj.getWorldBorder().contains(this.getEntityBoundingBox())) { + double d0 = this.worldObj.getWorldBorder().getClosestDistance(this) + + this.worldObj.getWorldBorder().getDamageBuffer(); + if (d0 < 0.0D) { + this.attackEntityFrom(DamageSource.inWall, (float) Math.max(1, + MathHelper.floor_double(-d0 * this.worldObj.getWorldBorder().getDamageAmount()))); + } + } + } + + if (this.isImmuneToFire() || this.worldObj.isRemote) { + this.extinguish(); + } + + boolean flag1 = flag && ((EntityPlayer) this).capabilities.disableDamage; + if (this.isEntityAlive()) { + if (this.isInsideOfMaterial(Material.water)) { + if (!this.canBreatheUnderwater() && !this.isPotionActive(Potion.waterBreathing.id) && !flag1) { + this.setAir(this.decreaseAirSupply(this.getAir())); + if (this.getAir() == -20) { + this.setAir(0); + + for (int i = 0; i < 8; ++i) { + float f = this.rand.nextFloat() - this.rand.nextFloat(); + float f1 = this.rand.nextFloat() - this.rand.nextFloat(); + float f2 = this.rand.nextFloat() - this.rand.nextFloat(); + this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + (double) f, + this.posY + (double) f1, this.posZ + (double) f2, this.motionX, this.motionY, + this.motionZ, new int[0]); + } + + this.attackEntityFrom(DamageSource.drown, 2.0F); + } + } + + if (!this.worldObj.isRemote && this.isRiding() && this.ridingEntity instanceof EntityLivingBase) { + this.mountEntity((Entity) null); + } + } else { + this.setAir(300); + } + } + + if (this.isEntityAlive() && this.isWet()) { + this.extinguish(); + } + + this.prevCameraPitch = this.cameraPitch; + if (this.hurtTime > 0) { + --this.hurtTime; + } + + if (this.hurtResistantTime > 0 && !(this instanceof EntityPlayerMP)) { + --this.hurtResistantTime; + } + + if (this.getHealth() <= 0.0F) { + this.onDeathUpdate(); + } + + if (this.recentlyHit > 0) { + --this.recentlyHit; + } else { + this.attackingPlayer = null; + } + + if (this.lastAttacker != null && !this.lastAttacker.isEntityAlive()) { + this.lastAttacker = null; + } + + if (this.entityLivingToAttack != null) { + if (!this.entityLivingToAttack.isEntityAlive()) { + this.setRevengeTarget((EntityLivingBase) null); + } else if (this.ticksExisted - this.revengeTimer > 100) { + this.setRevengeTarget((EntityLivingBase) null); + } + } + + this.updatePotionEffects(); + this.prevMovedDistance = this.movedDistance; + this.prevRenderYawOffset = this.renderYawOffset; + this.prevRotationYawHead = this.rotationYawHead; + this.prevRotationYaw = this.rotationYaw; + this.prevRotationPitch = this.rotationPitch; } - /**+ - * Called to update the entity's position/logic. + protected void onFinishedPotionEffect(PotionEffect potioneffect) { + this.potionsNeedUpdate = true; + if (!this.worldObj.isRemote) { + Potion.potionTypes[potioneffect.getPotionID()].removeAttributesModifiersFromEntity(this, + this.getAttributeMap(), potioneffect.getAmplifier()); + } + + } + + /** + * + Called whenever an item is picked up from walking over it. Args: + * pickedUpEntity, stackSize + */ + public void onItemPickup(Entity entity, int var2) { + if (!entity.isDead && !this.worldObj.isRemote) { + EntityTracker entitytracker = ((WorldServer) this.worldObj).getEntityTracker(); + if (entity instanceof EntityItem) { + entitytracker.sendToAllTrackingEntity(entity, + new S0DPacketCollectItem(entity.getEntityId(), this.getEntityId())); + } + + if (entity instanceof EntityArrow) { + entitytracker.sendToAllTrackingEntity(entity, + new S0DPacketCollectItem(entity.getEntityId(), this.getEntityId())); + } + + if (entity instanceof EntityXPOrb) { + entitytracker.sendToAllTrackingEntity(entity, + new S0DPacketCollectItem(entity.getEntityId(), this.getEntityId())); + } + } + + } + + /** + * + Called by the /kill command. + */ + public void onKillCommand() { + this.attackEntityFrom(DamageSource.outOfWorld, Float.MAX_VALUE); + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + if (this.jumpTicks > 0) { + --this.jumpTicks; + } + + if (this.newPosRotationIncrements > 0) { + double d0 = this.posX + (this.newPosX - this.posX) / (double) this.newPosRotationIncrements; + double d1 = this.posY + (this.newPosY - this.posY) / (double) this.newPosRotationIncrements; + double d2 = this.posZ + (this.newPosZ - this.posZ) / (double) this.newPosRotationIncrements; + double d3 = MathHelper.wrapAngleTo180_double(this.newRotationYaw - (double) this.rotationYaw); + this.rotationYaw = (float) ((double) this.rotationYaw + d3 / (double) this.newPosRotationIncrements); + this.rotationPitch = (float) ((double) this.rotationPitch + + (this.newRotationPitch - (double) this.rotationPitch) / (double) this.newPosRotationIncrements); + --this.newPosRotationIncrements; + this.setPosition(d0, d1, d2); + this.setRotation(this.rotationYaw, this.rotationPitch); + } else if (!this.isServerWorld()) { + this.motionX *= 0.98D; + this.motionY *= 0.98D; + this.motionZ *= 0.98D; + } + + if (Math.abs(this.motionX) < 0.005D) { + this.motionX = 0.0D; + } + + if (Math.abs(this.motionY) < 0.005D) { + this.motionY = 0.0D; + } + + if (Math.abs(this.motionZ) < 0.005D) { + this.motionZ = 0.0D; + } + + if (this.isMovementBlocked()) { + this.isJumping = false; + this.moveStrafing = 0.0F; + this.moveForward = 0.0F; + this.randomYawVelocity = 0.0F; + } else if (this.isServerWorld()) { + this.updateEntityActionState(); + } + + if (this.isJumping) { + if (this.isInWater()) { + this.updateAITick(); + } else if (this.isInLava()) { + this.handleJumpLava(); + } else if (this.onGround && this.jumpTicks == 0) { + this.jump(); + this.jumpTicks = 10; + } + } else { + this.jumpTicks = 0; + } + + this.moveStrafing *= 0.98F; + this.moveForward *= 0.98F; + this.randomYawVelocity *= 0.9F; + this.moveEntityWithHeading(this.moveStrafing, this.moveForward); + if (!this.worldObj.isRemote) { + this.collideWithNearbyEntities(); + } + } + + protected void onNewPotionEffect(PotionEffect potioneffect) { + this.potionsNeedUpdate = true; + if (!this.worldObj.isRemote) { + Potion.potionTypes[potioneffect.getPotionID()].applyAttributesModifiersToEntity(this, + this.getAttributeMap(), potioneffect.getAmplifier()); + } + + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -1566,322 +1505,91 @@ public abstract class EntityLivingBase extends Entity { this.movedDistance += f2; } - protected float func_110146_f(float parFloat1, float parFloat2) { - float f = MathHelper.wrapAngleTo180_float(parFloat1 - this.renderYawOffset); - this.renderYawOffset += f * 0.3F; - float f1 = MathHelper.wrapAngleTo180_float(this.rotationYaw - this.renderYawOffset); - boolean flag = f1 < -90.0F || f1 >= 90.0F; - if (f1 < -75.0F) { - f1 = -75.0F; - } - - if (f1 >= 75.0F) { - f1 = 75.0F; - } - - this.renderYawOffset = this.rotationYaw - f1; - if (f1 * f1 > 2500.0F) { - this.renderYawOffset += f1 * 0.2F; - } - - if (flag) { - parFloat2 *= -1.0F; - } - - return parFloat2; + /** + * + Setups the entity to do the hurt animation. Only used by packets in + * multiplayer. + */ + public void performHurtAnimation() { + this.hurtTime = this.maxHurtTime = 10; + this.attackedAtYaw = 0.0F; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ - public void onLivingUpdate() { - if (this.jumpTicks > 0) { - --this.jumpTicks; + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + this.setAbsorptionAmount(nbttagcompound.getFloat("AbsorptionAmount")); + if (nbttagcompound.hasKey("Attributes", 9) && this.worldObj != null && !this.worldObj.isRemote) { + SharedMonsterAttributes.func_151475_a(this.getAttributeMap(), nbttagcompound.getTagList("Attributes", 10)); } - if (this.newPosRotationIncrements > 0) { - double d0 = this.posX + (this.newPosX - this.posX) / (double) this.newPosRotationIncrements; - double d1 = this.posY + (this.newPosY - this.posY) / (double) this.newPosRotationIncrements; - double d2 = this.posZ + (this.newPosZ - this.posZ) / (double) this.newPosRotationIncrements; - double d3 = MathHelper.wrapAngleTo180_double(this.newRotationYaw - (double) this.rotationYaw); - this.rotationYaw = (float) ((double) this.rotationYaw + d3 / (double) this.newPosRotationIncrements); - this.rotationPitch = (float) ((double) this.rotationPitch - + (this.newRotationPitch - (double) this.rotationPitch) / (double) this.newPosRotationIncrements); - --this.newPosRotationIncrements; - this.setPosition(d0, d1, d2); - this.setRotation(this.rotationYaw, this.rotationPitch); - } else if (!this.isServerWorld()) { - this.motionX *= 0.98D; - this.motionY *= 0.98D; - this.motionZ *= 0.98D; - } + if (nbttagcompound.hasKey("ActiveEffects", 9)) { + NBTTagList nbttaglist = nbttagcompound.getTagList("ActiveEffects", 10); - if (Math.abs(this.motionX) < 0.005D) { - this.motionX = 0.0D; - } - - if (Math.abs(this.motionY) < 0.005D) { - this.motionY = 0.0D; - } - - if (Math.abs(this.motionZ) < 0.005D) { - this.motionZ = 0.0D; - } - - if (this.isMovementBlocked()) { - this.isJumping = false; - this.moveStrafing = 0.0F; - this.moveForward = 0.0F; - this.randomYawVelocity = 0.0F; - } else if (this.isServerWorld()) { - this.updateEntityActionState(); - } - - if (this.isJumping) { - if (this.isInWater()) { - this.updateAITick(); - } else if (this.isInLava()) { - this.handleJumpLava(); - } else if (this.onGround && this.jumpTicks == 0) { - this.jump(); - this.jumpTicks = 10; + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound1); + if (potioneffect != null) { + this.activePotionsMap.put(Integer.valueOf(potioneffect.getPotionID()), potioneffect); + } } + } + + if (nbttagcompound.hasKey("HealF", 99)) { + this.setHealth(nbttagcompound.getFloat("HealF")); } else { - this.jumpTicks = 0; - } - - this.moveStrafing *= 0.98F; - this.moveForward *= 0.98F; - this.randomYawVelocity *= 0.9F; - this.moveEntityWithHeading(this.moveStrafing, this.moveForward); - if (!this.worldObj.isRemote) { - this.collideWithNearbyEntities(); - } - } - - protected void updateEntityActionState() { - } - - protected void collideWithNearbyEntities() { - List list = this.worldObj.getEntitiesInAABBexcluding(this, - this.getEntityBoundingBox().expand(0.20000000298023224D, 0.0D, 0.20000000298023224D), - Predicates.and(EntitySelectors.NOT_SPECTATING, new Predicate() { - public boolean apply(Entity entity1) { - return entity1.canBePushed(); - } - })); - if (!list.isEmpty()) { - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - this.collideWithEntity(entity); + NBTBase nbtbase = nbttagcompound.getTag("Health"); + if (nbtbase == null) { + this.setHealth(this.getMaxHealth()); + } else if (nbtbase.getId() == 5) { + this.setHealth(((NBTTagFloat) nbtbase).getFloat()); + } else if (nbtbase.getId() == 2) { + this.setHealth((float) ((NBTTagShort) nbtbase).getShort()); } } + this.hurtTime = nbttagcompound.getShort("HurtTime"); + this.deathTime = nbttagcompound.getShort("DeathTime"); + this.revengeTimer = nbttagcompound.getInteger("HurtByTimestamp"); } - protected void collideWithEntity(Entity parEntity) { - parEntity.applyEntityCollision(this); - } - - /**+ - * Called when a player mounts an entity. e.g. mounts a pig, - * mounts a boat. + /** + * + Remove the specified potion effect from this entity. */ - public void mountEntity(Entity entity) { - if (this.ridingEntity != null && entity == null) { - if (!this.worldObj.isRemote) { - this.dismountEntity(this.ridingEntity); - } - - if (this.ridingEntity != null) { - this.ridingEntity.riddenByEntity = null; - } - - this.ridingEntity = null; - } else { - super.mountEntity(entity); - } - } - - /**+ - * Handles updating while being ridden by an entity - */ - public void updateRidden() { - super.updateRidden(); - this.prevOnGroundSpeedFactor = this.onGroundSpeedFactor; - this.onGroundSpeedFactor = 0.0F; - this.fallDistance = 0.0F; - } - - public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean var10) { - this.newPosX = d0; - this.newPosY = d1; - this.newPosZ = d2; - this.newRotationYaw = (double) f; - this.newRotationPitch = (double) f1; - this.newPosRotationIncrements = i; - } - - public void setJumping(boolean parFlag) { - this.isJumping = parFlag; - } - - /**+ - * Called whenever an item is picked up from walking over it. - * Args: pickedUpEntity, stackSize - */ - public void onItemPickup(Entity entity, int var2) { - if (!entity.isDead && !this.worldObj.isRemote) { - EntityTracker entitytracker = ((WorldServer) this.worldObj).getEntityTracker(); - if (entity instanceof EntityItem) { - entitytracker.sendToAllTrackingEntity(entity, - new S0DPacketCollectItem(entity.getEntityId(), this.getEntityId())); - } - - if (entity instanceof EntityArrow) { - entitytracker.sendToAllTrackingEntity(entity, - new S0DPacketCollectItem(entity.getEntityId(), this.getEntityId())); - } - - if (entity instanceof EntityXPOrb) { - entitytracker.sendToAllTrackingEntity(entity, - new S0DPacketCollectItem(entity.getEntityId(), this.getEntityId())); - } + public void removePotionEffect(int potionId) { + PotionEffect potioneffect = (PotionEffect) this.activePotionsMap.remove(Integer.valueOf(potionId)); + if (potioneffect != null) { + this.onFinishedPotionEffect(potioneffect); } } - /**+ - * returns true if the entity provided in the argument can be - * seen. (Raytrace) + /** + * + Remove the speified potion effect from this entity. */ - public boolean canEntityBeSeen(Entity entityIn) { - return this.worldObj.rayTraceBlocks(new Vec3(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ), - new Vec3(entityIn.posX, entityIn.posY + (double) entityIn.getEyeHeight(), entityIn.posZ)) == null; + public void removePotionEffectClient(int potionId) { + this.activePotionsMap.remove(Integer.valueOf(potionId)); } - /**+ - * returns a (normalized) vector of where this entity is looking + /** + * + Renders broken item particles using the given ItemStack */ - public Vec3 getLookVec() { - return this.getLook(1.0F); - } + public void renderBrokenItemStack(ItemStack stack) { + this.playSound("random.break", 0.8F, 0.8F + this.worldObj.rand.nextFloat() * 0.4F); - /**+ - * interpolated look vector - */ - public Vec3 getLook(float f) { - if (f == 1.0F) { - return this.getVectorForRotation(this.rotationPitch, this.rotationYawHead); - } else { - float f1 = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * f; - float f2 = this.prevRotationYawHead + (this.rotationYawHead - this.prevRotationYawHead) * f; - return this.getVectorForRotation(f1, f2); - } - } - - /**+ - * Returns where in the swing animation the living entity is - * (from 0 to 1). Args: partialTickTime - */ - public float getSwingProgress(float partialTickTime) { - float f = this.swingProgress - this.prevSwingProgress; - if (f < 0.0F) { - ++f; + for (int i = 0; i < 5; ++i) { + Vec3 vec3 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); + vec3 = vec3.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); + vec3 = vec3.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); + double d0 = (double) (-this.rand.nextFloat()) * 0.6D - 0.3D; + Vec3 vec31 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); + vec31 = vec31.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); + vec31 = vec31.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); + vec31 = vec31.addVector(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); + this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, + vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, new int[] { Item.getIdFromItem(stack.getItem()) }); } - return this.prevSwingProgress + f * partialTickTime; - } - - /**+ - * Returns whether the entity is in a server world - */ - public boolean isServerWorld() { - return !this.worldObj.isRemote; - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return !this.isDead; - } - - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. - */ - public boolean canBePushed() { - return !this.isDead; - } - - /**+ - * Sets that this entity has been attacked. - */ - protected void setBeenAttacked() { - this.velocityChanged = this.rand.nextDouble() >= this - .getEntityAttribute(SharedMonsterAttributes.knockbackResistance).getAttributeValue(); - } - - public float getRotationYawHead() { - return this.rotationYawHead; - } - - /**+ - * Sets the head's yaw rotation of the entity. - */ - public void setRotationYawHead(float f) { - this.rotationYawHead = f; - } - - public void func_181013_g(float f) { - this.renderYawOffset = f; - } - - public float getAbsorptionAmount() { - return this.absorptionAmount; - } - - public void setAbsorptionAmount(float amount) { - if (amount < 0.0F) { - amount = 0.0F; - } - - this.absorptionAmount = amount; - } - - public Team getTeam() { - return this.worldObj.getScoreboard().getPlayersTeam(this.getUniqueID().toString()); - } - - public boolean isOnSameTeam(EntityLivingBase otherEntity) { - return this.isOnTeam(otherEntity.getTeam()); - } - - /**+ - * Returns true if the entity is on a specific team. - */ - public boolean isOnTeam(Team parTeam) { - return this.getTeam() != null ? this.getTeam().isSameTeam(parTeam) : false; - } - - /**+ - * Sends an ENTER_COMBAT packet to the client - */ - public void sendEnterCombat() { - } - - /**+ - * Sends an END_COMBAT packet to the client - */ - public void sendEndCombat() { - } - - protected void markPotionsDirty() { - this.potionsNeedUpdate = true; } protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, @@ -1894,16 +1602,299 @@ public abstract class EntityLivingBase extends Entity { } } - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float f = super.getEaglerDynamicLightsValueSimple(partialTicks); - ItemStack itm = this.getHeldItem(); - if (itm != null && itm.stackSize > 0) { - Item item = itm.getItem(); - if (item != null) { - float f2 = item.getHeldItemBrightnessEagler(itm); - f = Math.min(f + f2 * 0.5f, 1.0f) + f2 * 0.5f; + /** + * + Resets the potion effect color and ambience metadata values + */ + protected void resetPotionEffectMetadata() { + this.dataWatcher.updateObject(8, Byte.valueOf((byte) 0)); + this.dataWatcher.updateObject(7, Integer.valueOf(0)); + } + + /** + * + Sends an END_COMBAT packet to the client + */ + public void sendEndCombat() { + } + + /** + * + Sends an ENTER_COMBAT packet to the client + */ + public void sendEnterCombat() { + } + + public void setAbsorptionAmount(float amount) { + if (amount < 0.0F) { + amount = 0.0F; + } + + this.absorptionAmount = amount; + } + + /** + * + set the movespeed used for the new AI system + */ + public void setAIMoveSpeed(float speedIn) { + this.landMovementFactor = speedIn; + } + + /** + * + sets the amount of arrows stuck in the entity. used for rendering those + */ + public final void setArrowCountInEntity(int count) { + this.dataWatcher.updateObject(9, Byte.valueOf((byte) count)); + } + + /** + * + Sets that this entity has been attacked. + */ + protected void setBeenAttacked() { + this.velocityChanged = this.rand.nextDouble() >= this + .getEntityAttribute(SharedMonsterAttributes.knockbackResistance).getAttributeValue(); + } + + public abstract void setCurrentItemOrArmor(int var1, ItemStack var2); + + public void setHealth(float health) { + this.dataWatcher.updateObject(6, Float.valueOf(MathHelper.clamp_float(health, 0.0F, this.getMaxHealth()))); + } + + public void setJumping(boolean parFlag) { + this.isJumping = parFlag; + } + + public void setLastAttacker(Entity entityIn) { + if (entityIn instanceof EntityLivingBase) { + this.lastAttacker = (EntityLivingBase) entityIn; + } else { + this.lastAttacker = null; + } + + this.lastAttackerTime = this.ticksExisted; + } + + public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean var10) { + this.newPosX = d0; + this.newPosY = d1; + this.newPosZ = d2; + this.newRotationYaw = (double) f; + this.newRotationPitch = (double) f1; + this.newPosRotationIncrements = i; + } + + public void setRevengeTarget(EntityLivingBase livingBase) { + this.entityLivingToAttack = livingBase; + this.revengeTimer = this.ticksExisted; + } + + /** + * + Sets the head's yaw rotation of the entity. + */ + public void setRotationYawHead(float f) { + this.rotationYawHead = f; + } + + /** + * + Set sprinting switch for Entity. + */ + public void setSprinting(boolean flag) { + super.setSprinting(flag); + IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); + if (iattributeinstance.getModifier(sprintingSpeedBoostModifierUUID) != null) { + iattributeinstance.removeModifier(sprintingSpeedBoostModifier); + } + + if (flag) { + iattributeinstance.applyModifier(sprintingSpeedBoostModifier); + } + + } + + /** + * + Swings the item the player is holding. + */ + public void swingItem() { + if (!this.isSwingInProgress || this.swingProgressInt >= this.getArmSwingAnimationEnd() / 2 + || this.swingProgressInt < 0) { + this.swingProgressInt = -1; + this.isSwingInProgress = true; + if (this.worldObj instanceof WorldServer) { + ((WorldServer) this.worldObj).getEntityTracker().sendToAllTrackingEntity(this, + new S0BPacketAnimation(this, 0)); } } - return f; + + } + + /** + * + main AI tick function, replaces updateEntityActionState + */ + protected void updateAITick() { + this.motionY += 0.03999999910593033D; + } + + /** + * + Updates the arm swing progress counters and animation progress + */ + protected void updateArmSwingProgress() { + int i = this.getArmSwingAnimationEnd(); + if (this.isSwingInProgress) { + ++this.swingProgressInt; + if (this.swingProgressInt >= i) { + this.swingProgressInt = 0; + this.isSwingInProgress = false; + } + } else { + this.swingProgressInt = 0; + } + + this.swingProgress = (float) this.swingProgressInt / (float) i; + } + + protected void updateEntityActionState() { + } + + protected void updateFallState(double d0, boolean flag, Block block, BlockPos blockpos) { + if (!this.isInWater()) { + this.handleWaterMovement(); + } + + if (!this.worldObj.isRemote && this.fallDistance > 3.0F && flag) { + IBlockState iblockstate = this.worldObj.getBlockState(blockpos); + Block block1 = iblockstate.getBlock(); + float f = (float) MathHelper.ceiling_float_int(this.fallDistance - 3.0F); + if (block1.getMaterial() != Material.air) { + double d1 = (double) Math.min(0.2F + f / 15.0F, 10.0F); + if (d1 > 2.5D) { + d1 = 2.5D; + } + + int i = (int) (150.0D * d1); + ((WorldServer) this.worldObj).spawnParticle(EnumParticleTypes.BLOCK_DUST, this.posX, this.posY, + this.posZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D, + new int[] { Block.getStateId(iblockstate) }); + } + } + + super.updateFallState(d0, flag, block, blockpos); + } + + protected void updatePotionEffects() { + Iterator iterator = this.activePotionsMap.keySet().iterator(); + + while (iterator.hasNext()) { + Integer integer = (Integer) iterator.next(); + PotionEffect potioneffect = (PotionEffect) this.activePotionsMap.get(integer); + if (!potioneffect.onUpdate(this)) { + if (!this.worldObj.isRemote) { + iterator.remove(); + this.onFinishedPotionEffect(potioneffect); + } + } else if (potioneffect.getDuration() % 600 == 0) { + this.onChangedPotionEffect(potioneffect, false); + } + } + + if (this.potionsNeedUpdate) { + if (!this.worldObj.isRemote) { + this.updatePotionMetadata(); + } + + this.potionsNeedUpdate = false; + } + + int i = this.dataWatcher.getWatchableObjectInt(7); + boolean flag1 = this.dataWatcher.getWatchableObjectByte(8) > 0; + if (i > 0) { + boolean flag = false; + if (!this.isInvisible()) { + flag = this.rand.nextBoolean(); + } else { + flag = this.rand.nextInt(15) == 0; + } + + if (flag1) { + flag &= this.rand.nextInt(5) == 0; + } + + if (flag && i > 0) { + double d0 = (double) (i >> 16 & 255) / 255.0D; + double d1 = (double) (i >> 8 & 255) / 255.0D; + double d2 = (double) (i >> 0 & 255) / 255.0D; + this.worldObj.spawnParticle(flag1 ? EnumParticleTypes.SPELL_MOB_AMBIENT : EnumParticleTypes.SPELL_MOB, + this.posX + (this.rand.nextDouble() - 0.5D) * (double) this.width, + this.posY + this.rand.nextDouble() * (double) this.height, + this.posZ + (this.rand.nextDouble() - 0.5D) * (double) this.width, d0, d1, d2, new int[0]); + } + } + + } + + /** + * + Clears potion metadata values if the entity has no potion effects. + * Otherwise, updates potion effect color, ambience, and invisibility metadata + * values + */ + protected void updatePotionMetadata() { + if (this.activePotionsMap.isEmpty()) { + this.resetPotionEffectMetadata(); + this.setInvisible(false); + } else { + int i = PotionHelper.calcPotionLiquidColor(this.activePotionsMap.values()); + this.dataWatcher.updateObject(8, + Byte.valueOf((byte) (PotionHelper.getAreAmbient(this.activePotionsMap.values()) ? 1 : 0))); + this.dataWatcher.updateObject(7, Integer.valueOf(i)); + this.setInvisible(this.isPotionActive(Potion.invisibility.id)); + } + + } + + /** + * + Handles updating while being ridden by an entity + */ + public void updateRidden() { + super.updateRidden(); + this.prevOnGroundSpeedFactor = this.onGroundSpeedFactor; + this.onGroundSpeedFactor = 0.0F; + this.fallDistance = 0.0F; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setFloat("HealF", this.getHealth()); + nbttagcompound.setShort("Health", (short) ((int) Math.ceil((double) this.getHealth()))); + nbttagcompound.setShort("HurtTime", (short) this.hurtTime); + nbttagcompound.setInteger("HurtByTimestamp", this.revengeTimer); + nbttagcompound.setShort("DeathTime", (short) this.deathTime); + nbttagcompound.setFloat("AbsorptionAmount", this.getAbsorptionAmount()); + + ItemStack[] inv = this.getInventory(); + for (int i = 0; i < inv.length; ++i) { + ItemStack itemstack = inv[i]; + if (itemstack != null) { + this.attributeMap.removeAttributeModifiers(itemstack.getAttributeModifiers()); + } + } + + nbttagcompound.setTag("Attributes", SharedMonsterAttributes.writeBaseAttributeMapToNBT(this.getAttributeMap())); + + for (int i = 0; i < inv.length; ++i) { + ItemStack itemstack1 = inv[i]; + if (itemstack1 != null) { + this.attributeMap.applyAttributeModifiers(itemstack1.getAttributeModifiers()); + } + } + + if (!this.activePotionsMap.isEmpty()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (PotionEffect potioneffect : this.activePotionsMap.values()) { + nbttaglist.appendTag(potioneffect.writeCustomPotionEffectToNBT(new NBTTagCompound())); + } + + nbttagcompound.setTag("ActiveEffects", nbttaglist); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityMinecartCommandBlock.java b/src/game/java/net/minecraft/entity/EntityMinecartCommandBlock.java index 57f8cdc6..a4b7a5a6 100644 --- a/src/game/java/net/minecraft/entity/EntityMinecartCommandBlock.java +++ b/src/game/java/net/minecraft/entity/EntityMinecartCommandBlock.java @@ -12,34 +12,31 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityMinecartCommandBlock extends EntityMinecart { private final CommandBlockLogic commandBlockLogic = new CommandBlockLogic() { - public void updateCommand() { - EntityMinecartCommandBlock.this.getDataWatcher().updateObject(23, this.getCommand()); - EntityMinecartCommandBlock.this.getDataWatcher().updateObject(24, - IChatComponent.Serializer.componentToJson(this.getLastOutput())); - } - public int func_145751_f() { return 1; } @@ -48,6 +45,14 @@ public class EntityMinecartCommandBlock extends EntityMinecart { bytebuf.writeInt(EntityMinecartCommandBlock.this.getEntityId()); } + public Entity getCommandSenderEntity() { + return EntityMinecartCommandBlock.this; + } + + public World getEntityWorld() { + return EntityMinecartCommandBlock.this.worldObj; + } + public BlockPos getPosition() { return new BlockPos(EntityMinecartCommandBlock.this.posX, EntityMinecartCommandBlock.this.posY + 0.5D, EntityMinecartCommandBlock.this.posZ); @@ -58,16 +63,14 @@ public class EntityMinecartCommandBlock extends EntityMinecart { EntityMinecartCommandBlock.this.posZ); } - public World getEntityWorld() { - return EntityMinecartCommandBlock.this.worldObj; - } - - public Entity getCommandSenderEntity() { - return EntityMinecartCommandBlock.this; + public void updateCommand() { + EntityMinecartCommandBlock.this.getDataWatcher().updateObject(23, this.getCommand()); + EntityMinecartCommandBlock.this.getDataWatcher().updateObject(24, + IChatComponent.Serializer.componentToJson(this.getLastOutput())); } }; - /**+ - * Cooldown before command block logic runs again in ticks + /** + * + Cooldown before command block logic runs again in ticks */ private int activatorRailCooldown = 0; @@ -85,42 +88,29 @@ public class EntityMinecartCommandBlock extends EntityMinecart { this.getDataWatcher().addObject(24, ""); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.commandBlockLogic.readDataFromNBT(nbttagcompound); - this.getDataWatcher().updateObject(23, this.getCommandBlockLogic().getCommand()); - this.getDataWatcher().updateObject(24, - IChatComponent.Serializer.componentToJson(this.getCommandBlockLogic().getLastOutput())); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - this.commandBlockLogic.writeDataToNBT(nbttagcompound); - } - - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.COMMAND_BLOCK; + public CommandBlockLogic getCommandBlockLogic() { + return this.commandBlockLogic; } public IBlockState getDefaultDisplayTile() { return Blocks.command_block.getDefaultState(); } - public CommandBlockLogic getCommandBlockLogic() { - return this.commandBlockLogic; + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.COMMAND_BLOCK; } - /**+ - * Called every tick the minecart is on an activator rail. Args: - * x, y, z, is the rail receiving power + /** + * + First layer of player interaction + */ + public boolean interactFirst(EntityPlayer entityplayer) { + this.commandBlockLogic.tryOpenEditCommandBlock(entityplayer); + return false; + } + + /** + * + Called every tick the minecart is on an activator rail. Args: x, y, z, is + * the rail receiving power */ public void onActivatorRailPass(int var1, int var2, int var3, boolean flag) { if (flag && this.ticksExisted - this.activatorRailCooldown >= 4) { @@ -130,14 +120,6 @@ public class EntityMinecartCommandBlock extends EntityMinecart { } - /**+ - * First layer of player interaction - */ - public boolean interactFirst(EntityPlayer entityplayer) { - this.commandBlockLogic.tryOpenEditCommandBlock(entityplayer); - return false; - } - public void onDataWatcherUpdate(int i) { super.onDataWatcherUpdate(i); if (i == 24) { @@ -152,4 +134,23 @@ public class EntityMinecartCommandBlock extends EntityMinecart { } } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.commandBlockLogic.readDataFromNBT(nbttagcompound); + this.getDataWatcher().updateObject(23, this.getCommandBlockLogic().getCommand()); + this.getDataWatcher().updateObject(24, + IChatComponent.Serializer.componentToJson(this.getCommandBlockLogic().getLastOutput())); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + this.commandBlockLogic.writeDataToNBT(nbttagcompound); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntitySpawnPlacementRegistry.java b/src/game/java/net/minecraft/entity/EntitySpawnPlacementRegistry.java index 97ef50f2..59ee8069 100644 --- a/src/game/java/net/minecraft/entity/EntitySpawnPlacementRegistry.java +++ b/src/game/java/net/minecraft/entity/EntitySpawnPlacementRegistry.java @@ -37,22 +37,25 @@ import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.passive.EntityWolf; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,10 +63,6 @@ import net.minecraft.entity.passive.EntityWolf; public class EntitySpawnPlacementRegistry { private static final HashMap ENTITY_PLACEMENTS = Maps.newHashMap(); - public static EntityLiving.SpawnPlacementType getPlacementForEntity(Class entityClass) { - return (EntityLiving.SpawnPlacementType) ENTITY_PLACEMENTS.get(entityClass); - } - static { ENTITY_PLACEMENTS.put(EntityBat.class, EntityLiving.SpawnPlacementType.ON_GROUND); ENTITY_PLACEMENTS.put(EntityChicken.class, EntityLiving.SpawnPlacementType.ON_GROUND); @@ -98,4 +97,8 @@ public class EntitySpawnPlacementRegistry { ENTITY_PLACEMENTS.put(EntityWitch.class, EntityLiving.SpawnPlacementType.ON_GROUND); ENTITY_PLACEMENTS.put(EntityZombie.class, EntityLiving.SpawnPlacementType.ON_GROUND); } + + public static EntityLiving.SpawnPlacementType getPlacementForEntity(Class entityClass) { + return (EntityLiving.SpawnPlacementType) ENTITY_PLACEMENTS.get(entityClass); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityTracker.java b/src/game/java/net/minecraft/entity/EntityTracker.java index 77bb999d..b5a34102 100644 --- a/src/game/java/net/minecraft/entity/EntityTracker.java +++ b/src/game/java/net/minecraft/entity/EntityTracker.java @@ -1,10 +1,14 @@ package net.minecraft.entity; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Set; import java.util.concurrent.Callable; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.boss.EntityDragon; @@ -37,25 +41,26 @@ import net.minecraft.util.IntHashMap; import net.minecraft.util.ReportedException; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -63,13 +68,13 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; public class EntityTracker { private static final Logger logger = LogManager.getLogger(); private final WorldServer theWorld; - /**+ - * List of tracked entities, used for iteration operations on - * tracked entities. + /** + * + List of tracked entities, used for iteration operations on tracked + * entities. */ private Set trackedEntities = Sets.newHashSet(); - /**+ - * Used for identity lookup of tracked entities. + /** + * + Used for identity lookup of tracked entities. */ private IntHashMap trackedEntityHashTable = new IntHashMap(); private int maxTrackingDistanceThreshold; @@ -80,6 +85,100 @@ public class EntityTracker { .getEntityViewDistance(); } + /** + * + Args : Entity, trackingRange, updateFrequency, sendVelocityUpdates + */ + public void addEntityToTracker(Entity entityIn, int trackingRange, final int updateFrequency, + boolean sendVelocityUpdates) { + if (trackingRange > this.maxTrackingDistanceThreshold) { + trackingRange = this.maxTrackingDistanceThreshold; + } + + try { + if (this.trackedEntityHashTable.containsItem(entityIn.getEntityId())) { + throw new IllegalStateException("Entity is already tracked!"); + } + + EntityTrackerEntry entitytrackerentry = new EntityTrackerEntry(entityIn, trackingRange, updateFrequency, + sendVelocityUpdates); + this.trackedEntities.add(entitytrackerentry); + this.trackedEntityHashTable.addKey(entityIn.getEntityId(), entitytrackerentry); + entitytrackerentry.updatePlayerEntities(this.theWorld.playerEntities); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Adding entity to track"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity To Track"); + crashreportcategory.addCrashSection("Tracking range", trackingRange + " blocks"); + crashreportcategory.addCrashSectionCallable("Update interval", new Callable() { + public String call() throws Exception { + String s = "Once per " + updateFrequency + " ticks"; + if (updateFrequency == Integer.MAX_VALUE) { + s = "Maximum (" + s + ")"; + } + + return s; + } + }); + entityIn.addEntityCrashInfo(crashreportcategory); + CrashReportCategory crashreportcategory1 = crashreport.makeCategory("Entity That Is Already Tracked"); + ((EntityTrackerEntry) this.trackedEntityHashTable.lookup(entityIn.getEntityId())).trackedEntity + .addEntityCrashInfo(crashreportcategory1); + + try { + throw new ReportedException(crashreport); + } catch (ReportedException reportedexception) { + logger.error("\"Silently\" catching entity tracking error.", reportedexception); + } + } + + } + + public void func_151248_b(Entity entityIn, Packet parPacket) { + EntityTrackerEntry entitytrackerentry = (EntityTrackerEntry) this.trackedEntityHashTable + .lookup(entityIn.getEntityId()); + if (entitytrackerentry != null) { + entitytrackerentry.func_151261_b(parPacket); + } + + } + + public void func_180245_a(EntityPlayerMP parEntityPlayerMP) { + for (EntityTrackerEntry entitytrackerentry : this.trackedEntities) { + if (entitytrackerentry.trackedEntity == parEntityPlayerMP) { + entitytrackerentry.updatePlayerEntities(this.theWorld.playerEntities); + } else { + entitytrackerentry.updatePlayerEntity(parEntityPlayerMP); + } + } + + } + + public void func_85172_a(EntityPlayerMP parEntityPlayerMP, Chunk parChunk) { + for (EntityTrackerEntry entitytrackerentry : this.trackedEntities) { + if (entitytrackerentry.trackedEntity != parEntityPlayerMP + && entitytrackerentry.trackedEntity.chunkCoordX == parChunk.xPosition + && entitytrackerentry.trackedEntity.chunkCoordZ == parChunk.zPosition) { + entitytrackerentry.updatePlayerEntity(parEntityPlayerMP); + } + } + + } + + public void removePlayerFromTrackers(EntityPlayerMP parEntityPlayerMP) { + for (EntityTrackerEntry entitytrackerentry : this.trackedEntities) { + entitytrackerentry.removeTrackedPlayerSymmetric(parEntityPlayerMP); + } + + } + + public void sendToAllTrackingEntity(Entity entityIn, Packet parPacket) { + EntityTrackerEntry entitytrackerentry = (EntityTrackerEntry) this.trackedEntityHashTable + .lookup(entityIn.getEntityId()); + if (entitytrackerentry != null) { + entitytrackerentry.sendPacketToTrackedPlayers(parPacket); + } + + } + public void trackEntity(Entity parEntity) { if (parEntity instanceof EntityPlayerMP) { this.trackEntity(parEntity, 512, 2); @@ -148,54 +247,6 @@ public class EntityTracker { this.addEntityToTracker(entityIn, trackingRange, updateFrequency, false); } - /**+ - * Args : Entity, trackingRange, updateFrequency, - * sendVelocityUpdates - */ - public void addEntityToTracker(Entity entityIn, int trackingRange, final int updateFrequency, - boolean sendVelocityUpdates) { - if (trackingRange > this.maxTrackingDistanceThreshold) { - trackingRange = this.maxTrackingDistanceThreshold; - } - - try { - if (this.trackedEntityHashTable.containsItem(entityIn.getEntityId())) { - throw new IllegalStateException("Entity is already tracked!"); - } - - EntityTrackerEntry entitytrackerentry = new EntityTrackerEntry(entityIn, trackingRange, updateFrequency, - sendVelocityUpdates); - this.trackedEntities.add(entitytrackerentry); - this.trackedEntityHashTable.addKey(entityIn.getEntityId(), entitytrackerentry); - entitytrackerentry.updatePlayerEntities(this.theWorld.playerEntities); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Adding entity to track"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Entity To Track"); - crashreportcategory.addCrashSection("Tracking range", trackingRange + " blocks"); - crashreportcategory.addCrashSectionCallable("Update interval", new Callable() { - public String call() throws Exception { - String s = "Once per " + updateFrequency + " ticks"; - if (updateFrequency == Integer.MAX_VALUE) { - s = "Maximum (" + s + ")"; - } - - return s; - } - }); - entityIn.addEntityCrashInfo(crashreportcategory); - CrashReportCategory crashreportcategory1 = crashreport.makeCategory("Entity That Is Already Tracked"); - ((EntityTrackerEntry) this.trackedEntityHashTable.lookup(entityIn.getEntityId())).trackedEntity - .addEntityCrashInfo(crashreportcategory1); - - try { - throw new ReportedException(crashreport); - } catch (ReportedException reportedexception) { - logger.error("\"Silently\" catching entity tracking error.", reportedexception); - } - } - - } - public void untrackEntity(Entity entityIn) { if (entityIn instanceof EntityPlayerMP) { EntityPlayerMP entityplayermp = (EntityPlayerMP) entityIn; @@ -236,51 +287,4 @@ public class EntityTracker { } } - - public void func_180245_a(EntityPlayerMP parEntityPlayerMP) { - for (EntityTrackerEntry entitytrackerentry : this.trackedEntities) { - if (entitytrackerentry.trackedEntity == parEntityPlayerMP) { - entitytrackerentry.updatePlayerEntities(this.theWorld.playerEntities); - } else { - entitytrackerentry.updatePlayerEntity(parEntityPlayerMP); - } - } - - } - - public void sendToAllTrackingEntity(Entity entityIn, Packet parPacket) { - EntityTrackerEntry entitytrackerentry = (EntityTrackerEntry) this.trackedEntityHashTable - .lookup(entityIn.getEntityId()); - if (entitytrackerentry != null) { - entitytrackerentry.sendPacketToTrackedPlayers(parPacket); - } - - } - - public void func_151248_b(Entity entityIn, Packet parPacket) { - EntityTrackerEntry entitytrackerentry = (EntityTrackerEntry) this.trackedEntityHashTable - .lookup(entityIn.getEntityId()); - if (entitytrackerentry != null) { - entitytrackerentry.func_151261_b(parPacket); - } - - } - - public void removePlayerFromTrackers(EntityPlayerMP parEntityPlayerMP) { - for (EntityTrackerEntry entitytrackerentry : this.trackedEntities) { - entitytrackerentry.removeTrackedPlayerSymmetric(parEntityPlayerMP); - } - - } - - public void func_85172_a(EntityPlayerMP parEntityPlayerMP, Chunk parChunk) { - for (EntityTrackerEntry entitytrackerentry : this.trackedEntities) { - if (entitytrackerentry.trackedEntity != parEntityPlayerMP - && entitytrackerentry.trackedEntity.chunkCoordX == parChunk.xPosition - && entitytrackerentry.trackedEntity.chunkCoordZ == parChunk.zPosition) { - entitytrackerentry.updatePlayerEntity(parEntityPlayerMP); - } - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EntityTrackerEntry.java b/src/game/java/net/minecraft/entity/EntityTrackerEntry.java index efd1c782..11c4705b 100644 --- a/src/game/java/net/minecraft/entity/EntityTrackerEntry.java +++ b/src/game/java/net/minecraft/entity/EntityTrackerEntry.java @@ -1,9 +1,13 @@ package net.minecraft.entity; -import com.google.common.collect.Sets; import java.util.Collection; import java.util.List; import java.util.Set; + +import com.google.common.collect.Sets; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.block.Block; import net.minecraft.entity.ai.attributes.ServersideAttributeMap; import net.minecraft.entity.item.EntityArmorStand; @@ -56,25 +60,26 @@ import net.minecraft.potion.PotionEffect; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.storage.MapData; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -104,9 +109,9 @@ public class EntityTrackerEntry { private boolean ridingEntity; private boolean onGround; public boolean playerEntitiesUpdated; - /**+ - * Holds references to all the players that are currently - * receiving position updates for this entity. + /** + * + Holds references to all the players that are currently receiving position + * updates for this entity. */ public Set trackingPlayers = Sets.newHashSet(); @@ -131,10 +136,279 @@ public class EntityTrackerEntry { : false; } + private Packet func_151260_c() { + if (this.trackedEntity.isDead) { + logger.warn("Fetching addPacket for removed entity"); + } + + if (this.trackedEntity instanceof EntityItem) { + return new S0EPacketSpawnObject(this.trackedEntity, 2, 1); + } else if (this.trackedEntity instanceof EntityPlayerMP) { + return new S0CPacketSpawnPlayer((EntityPlayer) this.trackedEntity); + } else if (this.trackedEntity instanceof EntityMinecart) { + EntityMinecart entityminecart = (EntityMinecart) this.trackedEntity; + return new S0EPacketSpawnObject(this.trackedEntity, 10, entityminecart.getMinecartType().getNetworkID()); + } else if (this.trackedEntity instanceof EntityBoat) { + return new S0EPacketSpawnObject(this.trackedEntity, 1); + } else if (this.trackedEntity instanceof IAnimals) { + this.lastHeadMotion = MathHelper.floor_float(this.trackedEntity.getRotationYawHead() * 256.0F / 360.0F); + return new S0FPacketSpawnMob((EntityLivingBase) this.trackedEntity); + } else if (this.trackedEntity instanceof EntityFishHook) { + EntityPlayer entityplayer = ((EntityFishHook) this.trackedEntity).angler; + return new S0EPacketSpawnObject(this.trackedEntity, 90, + entityplayer != null ? entityplayer.getEntityId() : this.trackedEntity.getEntityId()); + } else if (this.trackedEntity instanceof EntityArrow) { + Entity entity = ((EntityArrow) this.trackedEntity).shootingEntity; + return new S0EPacketSpawnObject(this.trackedEntity, 60, + entity != null ? entity.getEntityId() : this.trackedEntity.getEntityId()); + } else if (this.trackedEntity instanceof EntitySnowball) { + return new S0EPacketSpawnObject(this.trackedEntity, 61); + } else if (this.trackedEntity instanceof EntityPotion) { + return new S0EPacketSpawnObject(this.trackedEntity, 73, + ((EntityPotion) this.trackedEntity).getPotionDamage()); + } else if (this.trackedEntity instanceof EntityExpBottle) { + return new S0EPacketSpawnObject(this.trackedEntity, 75); + } else if (this.trackedEntity instanceof EntityEnderPearl) { + return new S0EPacketSpawnObject(this.trackedEntity, 65); + } else if (this.trackedEntity instanceof EntityEnderEye) { + return new S0EPacketSpawnObject(this.trackedEntity, 72); + } else if (this.trackedEntity instanceof EntityFireworkRocket) { + return new S0EPacketSpawnObject(this.trackedEntity, 76); + } else if (this.trackedEntity instanceof EntityFireball) { + EntityFireball entityfireball = (EntityFireball) this.trackedEntity; + S0EPacketSpawnObject s0epacketspawnobject2 = null; + byte b0 = 63; + if (this.trackedEntity instanceof EntitySmallFireball) { + b0 = 64; + } else if (this.trackedEntity instanceof EntityWitherSkull) { + b0 = 66; + } + + if (entityfireball.shootingEntity != null) { + s0epacketspawnobject2 = new S0EPacketSpawnObject(this.trackedEntity, b0, + ((EntityFireball) this.trackedEntity).shootingEntity.getEntityId()); + } else { + s0epacketspawnobject2 = new S0EPacketSpawnObject(this.trackedEntity, b0, + this.trackedEntity.getEntityId()); + } + + s0epacketspawnobject2.setSpeedX((int) (entityfireball.accelerationX * 8000.0D)); + s0epacketspawnobject2.setSpeedY((int) (entityfireball.accelerationY * 8000.0D)); + s0epacketspawnobject2.setSpeedZ((int) (entityfireball.accelerationZ * 8000.0D)); + return s0epacketspawnobject2; + } else if (this.trackedEntity instanceof EntityEgg) { + return new S0EPacketSpawnObject(this.trackedEntity, 62); + } else if (this.trackedEntity instanceof EntityTNTPrimed) { + return new S0EPacketSpawnObject(this.trackedEntity, 50); + } else if (this.trackedEntity instanceof EntityEnderCrystal) { + return new S0EPacketSpawnObject(this.trackedEntity, 51); + } else if (this.trackedEntity instanceof EntityFallingBlock) { + EntityFallingBlock entityfallingblock = (EntityFallingBlock) this.trackedEntity; + return new S0EPacketSpawnObject(this.trackedEntity, 70, Block.getStateId(entityfallingblock.getBlock())); + } else if (this.trackedEntity instanceof EntityArmorStand) { + return new S0EPacketSpawnObject(this.trackedEntity, 78); + } else if (this.trackedEntity instanceof EntityPainting) { + return new S10PacketSpawnPainting((EntityPainting) this.trackedEntity); + } else if (this.trackedEntity instanceof EntityItemFrame) { + EntityItemFrame entityitemframe = (EntityItemFrame) this.trackedEntity; + S0EPacketSpawnObject s0epacketspawnobject1 = new S0EPacketSpawnObject(this.trackedEntity, 71, + entityitemframe.facingDirection.getHorizontalIndex()); + BlockPos blockpos1 = entityitemframe.getHangingPosition(); + s0epacketspawnobject1.setX(MathHelper.floor_float((float) (blockpos1.getX() * 32))); + s0epacketspawnobject1.setY(MathHelper.floor_float((float) (blockpos1.getY() * 32))); + s0epacketspawnobject1.setZ(MathHelper.floor_float((float) (blockpos1.getZ() * 32))); + return s0epacketspawnobject1; + } else if (this.trackedEntity instanceof EntityLeashKnot) { + EntityLeashKnot entityleashknot = (EntityLeashKnot) this.trackedEntity; + S0EPacketSpawnObject s0epacketspawnobject = new S0EPacketSpawnObject(this.trackedEntity, 77); + BlockPos blockpos = entityleashknot.getHangingPosition(); + s0epacketspawnobject.setX(MathHelper.floor_float((float) (blockpos.getX() * 32))); + s0epacketspawnobject.setY(MathHelper.floor_float((float) (blockpos.getY() * 32))); + s0epacketspawnobject.setZ(MathHelper.floor_float((float) (blockpos.getZ() * 32))); + return s0epacketspawnobject; + } else if (this.trackedEntity instanceof EntityXPOrb) { + return new S11PacketSpawnExperienceOrb((EntityXPOrb) this.trackedEntity); + } else { + throw new IllegalArgumentException("Don\'t know how to add " + this.trackedEntity.getClass() + "!"); + } + } + + public void func_151261_b(Packet packetIn) { + this.sendPacketToTrackedPlayers(packetIn); + if (this.trackedEntity instanceof EntityPlayerMP) { + ((EntityPlayerMP) this.trackedEntity).playerNetServerHandler.sendPacket(packetIn); + } + + } + + public boolean func_180233_c(EntityPlayerMP playerMP) { + double d0 = playerMP.posX - (double) (this.encodedPosX / 32); + double d1 = playerMP.posZ - (double) (this.encodedPosZ / 32); + return d0 >= (double) (-this.trackingDistanceThreshold) && d0 <= (double) this.trackingDistanceThreshold + && d1 >= (double) (-this.trackingDistanceThreshold) && d1 <= (double) this.trackingDistanceThreshold + && this.trackedEntity.isSpectatedByPlayer(playerMP); + } + public int hashCode() { return this.trackedEntity.getEntityId(); } + private boolean isPlayerWatchingThisChunk(EntityPlayerMP playerMP) { + return playerMP.getServerForPlayer().getPlayerManager().isPlayerWatchingChunk(playerMP, + this.trackedEntity.chunkCoordX, this.trackedEntity.chunkCoordZ); + } + + public void removeFromTrackedPlayers(EntityPlayerMP playerMP) { + if (this.trackingPlayers.contains(playerMP)) { + playerMP.removeEntity(this.trackedEntity); + this.trackingPlayers.remove(playerMP); + } + + } + + /** + * + Remove a tracked player from our list and tell the tracked player to + * destroy us from their world. + */ + public void removeTrackedPlayerSymmetric(EntityPlayerMP playerMP) { + if (this.trackingPlayers.contains(playerMP)) { + this.trackingPlayers.remove(playerMP); + playerMP.removeEntity(this.trackedEntity); + } + + } + + public void sendDestroyEntityPacketToTrackedPlayers() { + for (EntityPlayerMP entityplayermp : this.trackingPlayers) { + entityplayermp.removeEntity(this.trackedEntity); + } + + } + + /** + * + Sends the entity metadata (DataWatcher) and attributes to all players + * tracking this entity, including the entity itself if a player. + */ + private void sendMetadataToAllAssociatedPlayers() { + DataWatcher datawatcher = this.trackedEntity.getDataWatcher(); + if (datawatcher.hasObjectChanged()) { + this.func_151261_b(new S1CPacketEntityMetadata(this.trackedEntity.getEntityId(), datawatcher, false)); + } + + if (this.trackedEntity instanceof EntityLivingBase) { + ServersideAttributeMap serversideattributemap = (ServersideAttributeMap) ((EntityLivingBase) this.trackedEntity) + .getAttributeMap(); + Set set = serversideattributemap.getAttributeInstanceSet(); + if (!set.isEmpty()) { + this.func_151261_b(new S20PacketEntityProperties(this.trackedEntity.getEntityId(), set)); + } + + set.clear(); + } + + } + + /** + * + Send the given packet to all players tracking this entity. + */ + public void sendPacketToTrackedPlayers(Packet packetIn) { + for (EntityPlayerMP entityplayermp : this.trackingPlayers) { + entityplayermp.playerNetServerHandler.sendPacket(packetIn); + } + + } + + public void updatePlayerEntities(List parList) { + for (int i = 0; i < parList.size(); ++i) { + this.updatePlayerEntity((EntityPlayerMP) parList.get(i)); + } + + } + + public void updatePlayerEntity(EntityPlayerMP playerMP) { + if (playerMP != this.trackedEntity) { + if (this.func_180233_c(playerMP)) { + if (!this.trackingPlayers.contains(playerMP) + && (this.isPlayerWatchingThisChunk(playerMP) || this.trackedEntity.forceSpawn)) { + this.trackingPlayers.add(playerMP); + Packet packet = this.func_151260_c(); + playerMP.playerNetServerHandler.sendPacket(packet); + if (!this.trackedEntity.getDataWatcher().getIsBlank()) { + playerMP.playerNetServerHandler.sendPacket(new S1CPacketEntityMetadata( + this.trackedEntity.getEntityId(), this.trackedEntity.getDataWatcher(), true)); + } + + NBTTagCompound nbttagcompound = this.trackedEntity.getNBTTagCompound(); + if (nbttagcompound != null) { + playerMP.playerNetServerHandler.sendPacket( + new S49PacketUpdateEntityNBT(this.trackedEntity.getEntityId(), nbttagcompound)); + } + + if (this.trackedEntity instanceof EntityLivingBase) { + ServersideAttributeMap serversideattributemap = (ServersideAttributeMap) ((EntityLivingBase) this.trackedEntity) + .getAttributeMap(); + Collection collection = serversideattributemap.getWatchedAttributes(); + if (!collection.isEmpty()) { + playerMP.playerNetServerHandler.sendPacket( + new S20PacketEntityProperties(this.trackedEntity.getEntityId(), collection)); + } + } + + this.lastTrackedEntityMotionX = this.trackedEntity.motionX; + this.lastTrackedEntityMotionY = this.trackedEntity.motionY; + this.motionZ = this.trackedEntity.motionZ; + if (this.sendVelocityUpdates && !(packet instanceof S0FPacketSpawnMob)) { + playerMP.playerNetServerHandler.sendPacket(new S12PacketEntityVelocity( + this.trackedEntity.getEntityId(), this.trackedEntity.motionX, + this.trackedEntity.motionY, this.trackedEntity.motionZ)); + } + + if (this.trackedEntity.ridingEntity != null) { + playerMP.playerNetServerHandler.sendPacket( + new S1BPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.ridingEntity)); + } + + if (this.trackedEntity instanceof EntityLiving + && ((EntityLiving) this.trackedEntity).getLeashedToEntity() != null) { + playerMP.playerNetServerHandler.sendPacket(new S1BPacketEntityAttach(1, this.trackedEntity, + ((EntityLiving) this.trackedEntity).getLeashedToEntity())); + } + + if (this.trackedEntity instanceof EntityLivingBase) { + for (int i = 0; i < 5; ++i) { + ItemStack itemstack = ((EntityLivingBase) this.trackedEntity).getEquipmentInSlot(i); + if (itemstack != null) { + playerMP.playerNetServerHandler.sendPacket( + new S04PacketEntityEquipment(this.trackedEntity.getEntityId(), i, itemstack)); + } + } + } + + if (this.trackedEntity instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) this.trackedEntity; + if (entityplayer.isPlayerSleeping()) { + playerMP.playerNetServerHandler + .sendPacket(new S0APacketUseBed(entityplayer, new BlockPos(this.trackedEntity))); + } + } + + if (this.trackedEntity instanceof EntityLivingBase) { + EntityLivingBase entitylivingbase = (EntityLivingBase) this.trackedEntity; + + for (PotionEffect potioneffect : entitylivingbase.getActivePotionEffects()) { + playerMP.playerNetServerHandler.sendPacket( + new S1DPacketEntityEffect(this.trackedEntity.getEntityId(), potioneffect)); + } + } + } + } else if (this.trackingPlayers.contains(playerMP)) { + this.trackingPlayers.remove(playerMP); + playerMP.removeEntity(this.trackedEntity); + } + + } + } + public void updatePlayerList(List parList) { this.playerEntitiesUpdated = false; if (!this.firstUpdateDone || this.trackedEntity.getDistanceSq(this.lastTrackedEntityPosX, @@ -283,274 +557,4 @@ public class EntityTrackerEntry { } } - - /**+ - * Sends the entity metadata (DataWatcher) and attributes to all - * players tracking this entity, including the entity itself if - * a player. - */ - private void sendMetadataToAllAssociatedPlayers() { - DataWatcher datawatcher = this.trackedEntity.getDataWatcher(); - if (datawatcher.hasObjectChanged()) { - this.func_151261_b(new S1CPacketEntityMetadata(this.trackedEntity.getEntityId(), datawatcher, false)); - } - - if (this.trackedEntity instanceof EntityLivingBase) { - ServersideAttributeMap serversideattributemap = (ServersideAttributeMap) ((EntityLivingBase) this.trackedEntity) - .getAttributeMap(); - Set set = serversideattributemap.getAttributeInstanceSet(); - if (!set.isEmpty()) { - this.func_151261_b(new S20PacketEntityProperties(this.trackedEntity.getEntityId(), set)); - } - - set.clear(); - } - - } - - /**+ - * Send the given packet to all players tracking this entity. - */ - public void sendPacketToTrackedPlayers(Packet packetIn) { - for (EntityPlayerMP entityplayermp : this.trackingPlayers) { - entityplayermp.playerNetServerHandler.sendPacket(packetIn); - } - - } - - public void func_151261_b(Packet packetIn) { - this.sendPacketToTrackedPlayers(packetIn); - if (this.trackedEntity instanceof EntityPlayerMP) { - ((EntityPlayerMP) this.trackedEntity).playerNetServerHandler.sendPacket(packetIn); - } - - } - - public void sendDestroyEntityPacketToTrackedPlayers() { - for (EntityPlayerMP entityplayermp : this.trackingPlayers) { - entityplayermp.removeEntity(this.trackedEntity); - } - - } - - public void removeFromTrackedPlayers(EntityPlayerMP playerMP) { - if (this.trackingPlayers.contains(playerMP)) { - playerMP.removeEntity(this.trackedEntity); - this.trackingPlayers.remove(playerMP); - } - - } - - public void updatePlayerEntity(EntityPlayerMP playerMP) { - if (playerMP != this.trackedEntity) { - if (this.func_180233_c(playerMP)) { - if (!this.trackingPlayers.contains(playerMP) - && (this.isPlayerWatchingThisChunk(playerMP) || this.trackedEntity.forceSpawn)) { - this.trackingPlayers.add(playerMP); - Packet packet = this.func_151260_c(); - playerMP.playerNetServerHandler.sendPacket(packet); - if (!this.trackedEntity.getDataWatcher().getIsBlank()) { - playerMP.playerNetServerHandler.sendPacket(new S1CPacketEntityMetadata( - this.trackedEntity.getEntityId(), this.trackedEntity.getDataWatcher(), true)); - } - - NBTTagCompound nbttagcompound = this.trackedEntity.getNBTTagCompound(); - if (nbttagcompound != null) { - playerMP.playerNetServerHandler.sendPacket( - new S49PacketUpdateEntityNBT(this.trackedEntity.getEntityId(), nbttagcompound)); - } - - if (this.trackedEntity instanceof EntityLivingBase) { - ServersideAttributeMap serversideattributemap = (ServersideAttributeMap) ((EntityLivingBase) this.trackedEntity) - .getAttributeMap(); - Collection collection = serversideattributemap.getWatchedAttributes(); - if (!collection.isEmpty()) { - playerMP.playerNetServerHandler.sendPacket( - new S20PacketEntityProperties(this.trackedEntity.getEntityId(), collection)); - } - } - - this.lastTrackedEntityMotionX = this.trackedEntity.motionX; - this.lastTrackedEntityMotionY = this.trackedEntity.motionY; - this.motionZ = this.trackedEntity.motionZ; - if (this.sendVelocityUpdates && !(packet instanceof S0FPacketSpawnMob)) { - playerMP.playerNetServerHandler.sendPacket(new S12PacketEntityVelocity( - this.trackedEntity.getEntityId(), this.trackedEntity.motionX, - this.trackedEntity.motionY, this.trackedEntity.motionZ)); - } - - if (this.trackedEntity.ridingEntity != null) { - playerMP.playerNetServerHandler.sendPacket( - new S1BPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.ridingEntity)); - } - - if (this.trackedEntity instanceof EntityLiving - && ((EntityLiving) this.trackedEntity).getLeashedToEntity() != null) { - playerMP.playerNetServerHandler.sendPacket(new S1BPacketEntityAttach(1, this.trackedEntity, - ((EntityLiving) this.trackedEntity).getLeashedToEntity())); - } - - if (this.trackedEntity instanceof EntityLivingBase) { - for (int i = 0; i < 5; ++i) { - ItemStack itemstack = ((EntityLivingBase) this.trackedEntity).getEquipmentInSlot(i); - if (itemstack != null) { - playerMP.playerNetServerHandler.sendPacket( - new S04PacketEntityEquipment(this.trackedEntity.getEntityId(), i, itemstack)); - } - } - } - - if (this.trackedEntity instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) this.trackedEntity; - if (entityplayer.isPlayerSleeping()) { - playerMP.playerNetServerHandler - .sendPacket(new S0APacketUseBed(entityplayer, new BlockPos(this.trackedEntity))); - } - } - - if (this.trackedEntity instanceof EntityLivingBase) { - EntityLivingBase entitylivingbase = (EntityLivingBase) this.trackedEntity; - - for (PotionEffect potioneffect : entitylivingbase.getActivePotionEffects()) { - playerMP.playerNetServerHandler.sendPacket( - new S1DPacketEntityEffect(this.trackedEntity.getEntityId(), potioneffect)); - } - } - } - } else if (this.trackingPlayers.contains(playerMP)) { - this.trackingPlayers.remove(playerMP); - playerMP.removeEntity(this.trackedEntity); - } - - } - } - - public boolean func_180233_c(EntityPlayerMP playerMP) { - double d0 = playerMP.posX - (double) (this.encodedPosX / 32); - double d1 = playerMP.posZ - (double) (this.encodedPosZ / 32); - return d0 >= (double) (-this.trackingDistanceThreshold) && d0 <= (double) this.trackingDistanceThreshold - && d1 >= (double) (-this.trackingDistanceThreshold) && d1 <= (double) this.trackingDistanceThreshold - && this.trackedEntity.isSpectatedByPlayer(playerMP); - } - - private boolean isPlayerWatchingThisChunk(EntityPlayerMP playerMP) { - return playerMP.getServerForPlayer().getPlayerManager().isPlayerWatchingChunk(playerMP, - this.trackedEntity.chunkCoordX, this.trackedEntity.chunkCoordZ); - } - - public void updatePlayerEntities(List parList) { - for (int i = 0; i < parList.size(); ++i) { - this.updatePlayerEntity((EntityPlayerMP) parList.get(i)); - } - - } - - private Packet func_151260_c() { - if (this.trackedEntity.isDead) { - logger.warn("Fetching addPacket for removed entity"); - } - - if (this.trackedEntity instanceof EntityItem) { - return new S0EPacketSpawnObject(this.trackedEntity, 2, 1); - } else if (this.trackedEntity instanceof EntityPlayerMP) { - return new S0CPacketSpawnPlayer((EntityPlayer) this.trackedEntity); - } else if (this.trackedEntity instanceof EntityMinecart) { - EntityMinecart entityminecart = (EntityMinecart) this.trackedEntity; - return new S0EPacketSpawnObject(this.trackedEntity, 10, entityminecart.getMinecartType().getNetworkID()); - } else if (this.trackedEntity instanceof EntityBoat) { - return new S0EPacketSpawnObject(this.trackedEntity, 1); - } else if (this.trackedEntity instanceof IAnimals) { - this.lastHeadMotion = MathHelper.floor_float(this.trackedEntity.getRotationYawHead() * 256.0F / 360.0F); - return new S0FPacketSpawnMob((EntityLivingBase) this.trackedEntity); - } else if (this.trackedEntity instanceof EntityFishHook) { - EntityPlayer entityplayer = ((EntityFishHook) this.trackedEntity).angler; - return new S0EPacketSpawnObject(this.trackedEntity, 90, - entityplayer != null ? entityplayer.getEntityId() : this.trackedEntity.getEntityId()); - } else if (this.trackedEntity instanceof EntityArrow) { - Entity entity = ((EntityArrow) this.trackedEntity).shootingEntity; - return new S0EPacketSpawnObject(this.trackedEntity, 60, - entity != null ? entity.getEntityId() : this.trackedEntity.getEntityId()); - } else if (this.trackedEntity instanceof EntitySnowball) { - return new S0EPacketSpawnObject(this.trackedEntity, 61); - } else if (this.trackedEntity instanceof EntityPotion) { - return new S0EPacketSpawnObject(this.trackedEntity, 73, - ((EntityPotion) this.trackedEntity).getPotionDamage()); - } else if (this.trackedEntity instanceof EntityExpBottle) { - return new S0EPacketSpawnObject(this.trackedEntity, 75); - } else if (this.trackedEntity instanceof EntityEnderPearl) { - return new S0EPacketSpawnObject(this.trackedEntity, 65); - } else if (this.trackedEntity instanceof EntityEnderEye) { - return new S0EPacketSpawnObject(this.trackedEntity, 72); - } else if (this.trackedEntity instanceof EntityFireworkRocket) { - return new S0EPacketSpawnObject(this.trackedEntity, 76); - } else if (this.trackedEntity instanceof EntityFireball) { - EntityFireball entityfireball = (EntityFireball) this.trackedEntity; - S0EPacketSpawnObject s0epacketspawnobject2 = null; - byte b0 = 63; - if (this.trackedEntity instanceof EntitySmallFireball) { - b0 = 64; - } else if (this.trackedEntity instanceof EntityWitherSkull) { - b0 = 66; - } - - if (entityfireball.shootingEntity != null) { - s0epacketspawnobject2 = new S0EPacketSpawnObject(this.trackedEntity, b0, - ((EntityFireball) this.trackedEntity).shootingEntity.getEntityId()); - } else { - s0epacketspawnobject2 = new S0EPacketSpawnObject(this.trackedEntity, b0, - this.trackedEntity.getEntityId()); - } - - s0epacketspawnobject2.setSpeedX((int) (entityfireball.accelerationX * 8000.0D)); - s0epacketspawnobject2.setSpeedY((int) (entityfireball.accelerationY * 8000.0D)); - s0epacketspawnobject2.setSpeedZ((int) (entityfireball.accelerationZ * 8000.0D)); - return s0epacketspawnobject2; - } else if (this.trackedEntity instanceof EntityEgg) { - return new S0EPacketSpawnObject(this.trackedEntity, 62); - } else if (this.trackedEntity instanceof EntityTNTPrimed) { - return new S0EPacketSpawnObject(this.trackedEntity, 50); - } else if (this.trackedEntity instanceof EntityEnderCrystal) { - return new S0EPacketSpawnObject(this.trackedEntity, 51); - } else if (this.trackedEntity instanceof EntityFallingBlock) { - EntityFallingBlock entityfallingblock = (EntityFallingBlock) this.trackedEntity; - return new S0EPacketSpawnObject(this.trackedEntity, 70, Block.getStateId(entityfallingblock.getBlock())); - } else if (this.trackedEntity instanceof EntityArmorStand) { - return new S0EPacketSpawnObject(this.trackedEntity, 78); - } else if (this.trackedEntity instanceof EntityPainting) { - return new S10PacketSpawnPainting((EntityPainting) this.trackedEntity); - } else if (this.trackedEntity instanceof EntityItemFrame) { - EntityItemFrame entityitemframe = (EntityItemFrame) this.trackedEntity; - S0EPacketSpawnObject s0epacketspawnobject1 = new S0EPacketSpawnObject(this.trackedEntity, 71, - entityitemframe.facingDirection.getHorizontalIndex()); - BlockPos blockpos1 = entityitemframe.getHangingPosition(); - s0epacketspawnobject1.setX(MathHelper.floor_float((float) (blockpos1.getX() * 32))); - s0epacketspawnobject1.setY(MathHelper.floor_float((float) (blockpos1.getY() * 32))); - s0epacketspawnobject1.setZ(MathHelper.floor_float((float) (blockpos1.getZ() * 32))); - return s0epacketspawnobject1; - } else if (this.trackedEntity instanceof EntityLeashKnot) { - EntityLeashKnot entityleashknot = (EntityLeashKnot) this.trackedEntity; - S0EPacketSpawnObject s0epacketspawnobject = new S0EPacketSpawnObject(this.trackedEntity, 77); - BlockPos blockpos = entityleashknot.getHangingPosition(); - s0epacketspawnobject.setX(MathHelper.floor_float((float) (blockpos.getX() * 32))); - s0epacketspawnobject.setY(MathHelper.floor_float((float) (blockpos.getY() * 32))); - s0epacketspawnobject.setZ(MathHelper.floor_float((float) (blockpos.getZ() * 32))); - return s0epacketspawnobject; - } else if (this.trackedEntity instanceof EntityXPOrb) { - return new S11PacketSpawnExperienceOrb((EntityXPOrb) this.trackedEntity); - } else { - throw new IllegalArgumentException("Don\'t know how to add " + this.trackedEntity.getClass() + "!"); - } - } - - /**+ - * Remove a tracked player from our list and tell the tracked - * player to destroy us from their world. - */ - public void removeTrackedPlayerSymmetric(EntityPlayerMP playerMP) { - if (this.trackingPlayers.contains(playerMP)) { - this.trackingPlayers.remove(playerMP); - playerMP.removeEntity(this.trackedEntity); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/EnumCreatureAttribute.java b/src/game/java/net/minecraft/entity/EnumCreatureAttribute.java index aa6bf7c9..56119a77 100644 --- a/src/game/java/net/minecraft/entity/EnumCreatureAttribute.java +++ b/src/game/java/net/minecraft/entity/EnumCreatureAttribute.java @@ -1,21 +1,24 @@ package net.minecraft.entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/EnumCreatureType.java b/src/game/java/net/minecraft/entity/EnumCreatureType.java index dddecd10..fd2a8eb1 100644 --- a/src/game/java/net/minecraft/entity/EnumCreatureType.java +++ b/src/game/java/net/minecraft/entity/EnumCreatureType.java @@ -7,22 +7,25 @@ import net.minecraft.entity.passive.EntityAnimal; import net.minecraft.entity.passive.EntityWaterMob; import net.minecraft.entity.passive.IAnimals; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,6 +52,13 @@ public enum EnumCreatureType { this.isAnimal = isAnimalIn; } + /** + * + Return whether this creature type is an animal. + */ + public boolean getAnimal() { + return this.isAnimal; + } + public Class getCreatureClass() { return this.creatureClass; } @@ -57,17 +67,10 @@ public enum EnumCreatureType { return this.maxNumberOfCreature; } - /**+ - * Gets whether or not this creature type is peaceful. + /** + * + Gets whether or not this creature type is peaceful. */ public boolean getPeacefulCreature() { return this.isPeacefulCreature; } - - /**+ - * Return whether this creature type is an animal. - */ - public boolean getAnimal() { - return this.isAnimal; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/IEntityLivingData.java b/src/game/java/net/minecraft/entity/IEntityLivingData.java index 5540e12e..313555cc 100644 --- a/src/game/java/net/minecraft/entity/IEntityLivingData.java +++ b/src/game/java/net/minecraft/entity/IEntityLivingData.java @@ -1,21 +1,24 @@ package net.minecraft.entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/IEntityMultiPart.java b/src/game/java/net/minecraft/entity/IEntityMultiPart.java index 37f820bd..e5928bee 100644 --- a/src/game/java/net/minecraft/entity/IEntityMultiPart.java +++ b/src/game/java/net/minecraft/entity/IEntityMultiPart.java @@ -4,28 +4,31 @@ import net.minecraft.entity.boss.EntityDragonPart; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IEntityMultiPart { - World getWorld(); - boolean attackEntityFromPart(EntityDragonPart var1, DamageSource var2, float var3); + + World getWorld(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/IEntityOwnable.java b/src/game/java/net/minecraft/entity/IEntityOwnable.java index 2a5e65f8..e714a908 100644 --- a/src/game/java/net/minecraft/entity/IEntityOwnable.java +++ b/src/game/java/net/minecraft/entity/IEntityOwnable.java @@ -1,27 +1,30 @@ package net.minecraft.entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IEntityOwnable { - String getOwnerId(); - Entity getOwner(); + + String getOwnerId(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/IMerchant.java b/src/game/java/net/minecraft/entity/IMerchant.java index 8100f386..b0b7470c 100644 --- a/src/game/java/net/minecraft/entity/IMerchant.java +++ b/src/game/java/net/minecraft/entity/IMerchant.java @@ -6,47 +6,50 @@ import net.minecraft.util.IChatComponent; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IMerchant { - void setCustomer(EntityPlayer var1); - EntityPlayer getCustomer(); + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + IChatComponent getDisplayName(); + MerchantRecipeList getRecipes(EntityPlayer var1); + void setCustomer(EntityPlayer var1); + void setRecipes(MerchantRecipeList var1); void useRecipe(MerchantRecipe var1); - /**+ - * Notifies the merchant of a possible merchantrecipe being - * fulfilled or not. Usually, this is just a sound byte being - * played depending if the suggested itemstack is not null. + /** + * + Notifies the merchant of a possible merchantrecipe being fulfilled or not. + * Usually, this is just a sound byte being played depending if the suggested + * itemstack is not null. */ void verifySellingItem(ItemStack var1); - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - IChatComponent getDisplayName(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/INpc.java b/src/game/java/net/minecraft/entity/INpc.java index 49340336..02df28e2 100644 --- a/src/game/java/net/minecraft/entity/INpc.java +++ b/src/game/java/net/minecraft/entity/INpc.java @@ -2,22 +2,25 @@ package net.minecraft.entity; import net.minecraft.entity.passive.IAnimals; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/IProjectile.java b/src/game/java/net/minecraft/entity/IProjectile.java index 4657da93..f934419a 100644 --- a/src/game/java/net/minecraft/entity/IProjectile.java +++ b/src/game/java/net/minecraft/entity/IProjectile.java @@ -1,29 +1,32 @@ package net.minecraft.entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IProjectile { - /**+ - * Similar to setArrowHeading, it's point the throwable entity - * to a x, y, z direction. + /** + * + Similar to setArrowHeading, it's point the throwable entity to a x, y, z + * direction. */ void setThrowableHeading(double var1, double var3, double var5, float var7, float var8); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/IRangedAttackMob.java b/src/game/java/net/minecraft/entity/IRangedAttackMob.java index 960ed002..7e930b82 100644 --- a/src/game/java/net/minecraft/entity/IRangedAttackMob.java +++ b/src/game/java/net/minecraft/entity/IRangedAttackMob.java @@ -1,28 +1,31 @@ package net.minecraft.entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IRangedAttackMob { - /**+ - * Attack the specified entity using a ranged attack. + /** + * + Attack the specified entity using a ranged attack. */ void attackEntityWithRangedAttack(EntityLivingBase var1, float var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/NpcMerchant.java b/src/game/java/net/minecraft/entity/NpcMerchant.java index f1199a29..acb70e79 100644 --- a/src/game/java/net/minecraft/entity/NpcMerchant.java +++ b/src/game/java/net/minecraft/entity/NpcMerchant.java @@ -8,22 +8,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,13 +47,22 @@ public class NpcMerchant implements IMerchant { return this.customer; } - public void setCustomer(EntityPlayer var1) { + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.field_175548_d != null ? this.field_175548_d + : new ChatComponentTranslation("entity.Villager.name", new Object[0])); } public MerchantRecipeList getRecipes(EntityPlayer var1) { return this.recipeList; } + public void setCustomer(EntityPlayer var1) { + } + public void setRecipes(MerchantRecipeList merchantrecipelist) { this.recipeList = merchantrecipelist; } @@ -59,20 +71,11 @@ public class NpcMerchant implements IMerchant { merchantrecipe.incrementToolUses(); } - /**+ - * Notifies the merchant of a possible merchantrecipe being - * fulfilled or not. Usually, this is just a sound byte being - * played depending if the suggested itemstack is not null. + /** + * + Notifies the merchant of a possible merchantrecipe being fulfilled or not. + * Usually, this is just a sound byte being played depending if the suggested + * itemstack is not null. */ public void verifySellingItem(ItemStack var1) { } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.field_175548_d != null ? this.field_175548_d - : new ChatComponentTranslation("entity.Villager.name", new Object[0])); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/SharedMonsterAttributes.java b/src/game/java/net/minecraft/entity/SharedMonsterAttributes.java index 76c5aa82..49447244 100644 --- a/src/game/java/net/minecraft/entity/SharedMonsterAttributes.java +++ b/src/game/java/net/minecraft/entity/SharedMonsterAttributes.java @@ -1,8 +1,8 @@ package net.minecraft.entity; import java.util.Collection; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.ai.attributes.AttributeModifier; @@ -13,22 +13,25 @@ import net.minecraft.entity.ai.attributes.RangedAttribute; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,72 +49,6 @@ public class SharedMonsterAttributes { public static final IAttribute attackDamage = new RangedAttribute((IAttribute) null, "generic.attackDamage", 2.0D, 0.0D, 2048.0D); - /**+ - * Creates an NBTTagList from a BaseAttributeMap, including all - * its AttributeInstances - */ - public static NBTTagList writeBaseAttributeMapToNBT(BaseAttributeMap parBaseAttributeMap) { - NBTTagList nbttaglist = new NBTTagList(); - - for (IAttributeInstance iattributeinstance : parBaseAttributeMap.getAllAttributes()) { - nbttaglist.appendTag(writeAttributeInstanceToNBT(iattributeinstance)); - } - - return nbttaglist; - } - - /**+ - * Creates an NBTTagCompound from an AttributeInstance, - * including its AttributeModifiers - */ - private static NBTTagCompound writeAttributeInstanceToNBT(IAttributeInstance parIAttributeInstance) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - IAttribute iattribute = parIAttributeInstance.getAttribute(); - nbttagcompound.setString("Name", iattribute.getAttributeUnlocalizedName()); - nbttagcompound.setDouble("Base", parIAttributeInstance.getBaseValue()); - Collection collection = parIAttributeInstance.func_111122_c(); - if (collection != null && !collection.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); - - for (AttributeModifier attributemodifier : (Collection) collection) { - if (attributemodifier.isSaved()) { - nbttaglist.appendTag(writeAttributeModifierToNBT(attributemodifier)); - } - } - - nbttagcompound.setTag("Modifiers", nbttaglist); - } - - return nbttagcompound; - } - - /**+ - * Creates an NBTTagCompound from an AttributeModifier - */ - private static NBTTagCompound writeAttributeModifierToNBT(AttributeModifier parAttributeModifier) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("Name", parAttributeModifier.getName()); - nbttagcompound.setDouble("Amount", parAttributeModifier.getAmount()); - nbttagcompound.setInteger("Operation", parAttributeModifier.getOperation()); - nbttagcompound.setLong("UUIDMost", parAttributeModifier.getID().getMostSignificantBits()); - nbttagcompound.setLong("UUIDLeast", parAttributeModifier.getID().getLeastSignificantBits()); - return nbttagcompound; - } - - public static void func_151475_a(BaseAttributeMap parBaseAttributeMap, NBTTagList parNBTTagList) { - for (int i = 0; i < parNBTTagList.tagCount(); ++i) { - NBTTagCompound nbttagcompound = parNBTTagList.getCompoundTagAt(i); - IAttributeInstance iattributeinstance = parBaseAttributeMap - .getAttributeInstanceByName(nbttagcompound.getString("Name")); - if (iattributeinstance != null) { - applyModifiersToAttributeInstance(iattributeinstance, nbttagcompound); - } else { - logger.warn("Ignoring unknown attribute \'" + nbttagcompound.getString("Name") + "\'"); - } - } - - } - private static void applyModifiersToAttributeInstance(IAttributeInstance parIAttributeInstance, NBTTagCompound parNBTTagCompound) { parIAttributeInstance.setBaseValue(parNBTTagCompound.getDouble("Base")); @@ -133,8 +70,22 @@ public class SharedMonsterAttributes { } - /**+ - * Creates an AttributeModifier from an NBTTagCompound + public static void func_151475_a(BaseAttributeMap parBaseAttributeMap, NBTTagList parNBTTagList) { + for (int i = 0; i < parNBTTagList.tagCount(); ++i) { + NBTTagCompound nbttagcompound = parNBTTagList.getCompoundTagAt(i); + IAttributeInstance iattributeinstance = parBaseAttributeMap + .getAttributeInstanceByName(nbttagcompound.getString("Name")); + if (iattributeinstance != null) { + applyModifiersToAttributeInstance(iattributeinstance, nbttagcompound); + } else { + logger.warn("Ignoring unknown attribute \'" + nbttagcompound.getString("Name") + "\'"); + } + } + + } + + /** + * + Creates an AttributeModifier from an NBTTagCompound */ public static AttributeModifier readAttributeModifierFromNBT(NBTTagCompound parNBTTagCompound) { EaglercraftUUID uuid = new EaglercraftUUID(parNBTTagCompound.getLong("UUIDMost"), @@ -148,4 +99,56 @@ public class SharedMonsterAttributes { return null; } } + + /** + * + Creates an NBTTagCompound from an AttributeInstance, including its + * AttributeModifiers + */ + private static NBTTagCompound writeAttributeInstanceToNBT(IAttributeInstance parIAttributeInstance) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + IAttribute iattribute = parIAttributeInstance.getAttribute(); + nbttagcompound.setString("Name", iattribute.getAttributeUnlocalizedName()); + nbttagcompound.setDouble("Base", parIAttributeInstance.getBaseValue()); + Collection collection = parIAttributeInstance.func_111122_c(); + if (collection != null && !collection.isEmpty()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (AttributeModifier attributemodifier : (Collection) collection) { + if (attributemodifier.isSaved()) { + nbttaglist.appendTag(writeAttributeModifierToNBT(attributemodifier)); + } + } + + nbttagcompound.setTag("Modifiers", nbttaglist); + } + + return nbttagcompound; + } + + /** + * + Creates an NBTTagCompound from an AttributeModifier + */ + private static NBTTagCompound writeAttributeModifierToNBT(AttributeModifier parAttributeModifier) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("Name", parAttributeModifier.getName()); + nbttagcompound.setDouble("Amount", parAttributeModifier.getAmount()); + nbttagcompound.setInteger("Operation", parAttributeModifier.getOperation()); + nbttagcompound.setLong("UUIDMost", parAttributeModifier.getID().getMostSignificantBits()); + nbttagcompound.setLong("UUIDLeast", parAttributeModifier.getID().getLeastSignificantBits()); + return nbttagcompound; + } + + /** + * + Creates an NBTTagList from a BaseAttributeMap, including all its + * AttributeInstances + */ + public static NBTTagList writeBaseAttributeMapToNBT(BaseAttributeMap parBaseAttributeMap) { + NBTTagList nbttaglist = new NBTTagList(); + + for (IAttributeInstance iattributeinstance : parBaseAttributeMap.getAllAttributes()) { + nbttaglist.appendTag(writeAttributeInstanceToNBT(iattributeinstance)); + } + + return nbttaglist; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIArrowAttack.java b/src/game/java/net/minecraft/entity/ai/EntityAIArrowAttack.java index fcc25a81..bbddaf0f 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIArrowAttack.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIArrowAttack.java @@ -5,22 +5,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.IRangedAttackMob; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -58,8 +61,24 @@ public class EntityAIArrowAttack extends EntityAIBase { } } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.shouldExecute() || !this.entityHost.getNavigator().noPath(); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.attackTarget = null; + this.field_75318_f = 0; + this.rangedAttackTime = -1; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.entityHost.getAttackTarget(); @@ -71,25 +90,8 @@ public class EntityAIArrowAttack extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.shouldExecute() || !this.entityHost.getNavigator().noPath(); - } - - /**+ - * Resets the task - */ - public void resetTask() { - this.attackTarget = null; - this.field_75318_f = 0; - this.rangedAttackTime = -1; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { double d0 = this.entityHost.getDistanceSq(this.attackTarget.posX, this.attackTarget.getEntityBoundingBox().minY, diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIAttackOnCollide.java b/src/game/java/net/minecraft/entity/ai/EntityAIAttackOnCollide.java index ab226db9..5b4a53f1 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIAttackOnCollide.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIAttackOnCollide.java @@ -7,22 +7,25 @@ import net.minecraft.pathfinding.PathEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,8 +57,30 @@ public class EntityAIAttackOnCollide extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + EntityLivingBase entitylivingbase = this.attacker.getAttackTarget(); + return entitylivingbase == null ? false + : (!entitylivingbase.isEntityAlive() ? false + : (!this.longMemory ? !this.attacker.getNavigator().noPath() + : this.attacker.isWithinHomeDistanceFromPosition(new BlockPos(entitylivingbase)))); + } + + protected double func_179512_a(EntityLivingBase attackTarget) { + return (double) (this.attacker.width * 2.0F * this.attacker.width * 2.0F + attackTarget.width); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.attacker.getNavigator().clearPathEntity(); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.attacker.getAttackTarget(); @@ -71,35 +96,16 @@ public class EntityAIAttackOnCollide extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - EntityLivingBase entitylivingbase = this.attacker.getAttackTarget(); - return entitylivingbase == null ? false - : (!entitylivingbase.isEntityAlive() ? false - : (!this.longMemory ? !this.attacker.getNavigator().noPath() - : this.attacker.isWithinHomeDistanceFromPosition(new BlockPos(entitylivingbase)))); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.attacker.getNavigator().setPath(this.entityPathEntity, this.speedTowardsTarget); this.delayCounter = 0; } - /**+ - * Resets the task - */ - public void resetTask() { - this.attacker.getNavigator().clearPathEntity(); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { EntityLivingBase entitylivingbase = this.attacker.getAttackTarget(); @@ -138,8 +144,4 @@ public class EntityAIAttackOnCollide extends EntityAIBase { } } - - protected double func_179512_a(EntityLivingBase attackTarget) { - return (double) (this.attacker.width * 2.0F * this.attacker.width * 2.0F + attackTarget.width); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIAvoidEntity.java b/src/game/java/net/minecraft/entity/ai/EntityAIAvoidEntity.java index 0d1ebe53..a731329a 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIAvoidEntity.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIAvoidEntity.java @@ -1,8 +1,10 @@ package net.minecraft.entity.ai; +import java.util.List; + import com.google.common.base.Predicate; import com.google.common.base.Predicates; -import java.util.List; + import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.pathfinding.PathEntity; @@ -10,22 +12,25 @@ import net.minecraft.pathfinding.PathNavigate; import net.minecraft.util.EntitySelectors; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -64,8 +69,22 @@ public class EntityAIAvoidEntity extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.entityPathNavigate.noPath(); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.closestLivingEntity = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { List list = this.theEntity.worldObj.getEntitiesWithinAABB(this.field_181064_i, @@ -91,30 +110,15 @@ public class EntityAIAvoidEntity extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.entityPathNavigate.noPath(); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.entityPathNavigate.setPath(this.entityPathEntity, this.farSpeed); } - /**+ - * Resets the task - */ - public void resetTask() { - this.closestLivingEntity = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { if (this.theEntity.getDistanceSqToEntity(this.closestLivingEntity) < 49.0D) { diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIBase.java b/src/game/java/net/minecraft/entity/ai/EntityAIBase.java index df18f300..87b8980e 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIBase.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIBase.java @@ -1,21 +1,24 @@ package net.minecraft.entity.ai; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,60 +26,56 @@ package net.minecraft.entity.ai; public abstract class EntityAIBase { private int mutexBits; - public abstract boolean shouldExecute(); - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return this.shouldExecute(); } - /**+ - * Determine if this AI Task is interruptible by a higher (= - * lower value) priority task. All vanilla AITask have this - * value set to true. + /** + * + Get a bitmask telling which other tasks may not run concurrently. The test + * is a simple bitwise AND - if it yields zero, the two tasks may run + * concurrently, if not - they must run exclusively from each other. + */ + public int getMutexBits() { + return this.mutexBits; + } + + /** + * + Determine if this AI Task is interruptible by a higher (= lower value) + * priority task. All vanilla AITask have this value set to true. */ public boolean isInterruptible() { return true; } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - } - - /**+ - * Resets the task + /** + * + Resets the task */ public void resetTask() { } - /**+ - * Updates the task - */ - public void updateTask() { - } - - /**+ - * Sets a bitmask telling which other tasks may not run - * concurrently. The test is a simple bitwise AND - if it yields - * zero, the two tasks may run concurrently, if not - they must - * run exclusively from each other. + /** + * + Sets a bitmask telling which other tasks may not run concurrently. The test + * is a simple bitwise AND - if it yields zero, the two tasks may run + * concurrently, if not - they must run exclusively from each other. */ public void setMutexBits(int mutexBitsIn) { this.mutexBits = mutexBitsIn; } - /**+ - * Get a bitmask telling which other tasks may not run - * concurrently. The test is a simple bitwise AND - if it yields - * zero, the two tasks may run concurrently, if not - they must - * run exclusively from each other. + public abstract boolean shouldExecute(); + + /** + * + Execute a one shot task or start executing a continuous task */ - public int getMutexBits() { - return this.mutexBits; + public void startExecuting() { + } + + /** + * + Updates the task + */ + public void updateTask() { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIBeg.java b/src/game/java/net/minecraft/entity/ai/EntityAIBeg.java index f46f4efb..512bee7e 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIBeg.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIBeg.java @@ -6,22 +6,25 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,17 +43,8 @@ public class EntityAIBeg extends EntityAIBase { this.setMutexBits(2); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - this.thePlayer = this.worldObject.getClosestPlayerToEntity(this.theWolf, (double) this.minPlayerDistance); - return this.thePlayer == null ? false : this.hasPlayerGotBoneInHand(this.thePlayer); - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return !this.thePlayer.isEntityAlive() ? false @@ -59,34 +53,8 @@ public class EntityAIBeg extends EntityAIBase { : this.timeoutCounter > 0 && this.hasPlayerGotBoneInHand(this.thePlayer)); } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - this.theWolf.setBegging(true); - this.timeoutCounter = 40 + this.theWolf.getRNG().nextInt(40); - } - - /**+ - * Resets the task - */ - public void resetTask() { - this.theWolf.setBegging(false); - this.thePlayer = null; - } - - /**+ - * Updates the task - */ - public void updateTask() { - this.theWolf.getLookHelper().setLookPosition(this.thePlayer.posX, - this.thePlayer.posY + (double) this.thePlayer.getEyeHeight(), this.thePlayer.posZ, 10.0F, - (float) this.theWolf.getVerticalFaceSpeed()); - --this.timeoutCounter; - } - - /**+ - * Gets if the Player has the Bone in the hand. + /** + * + Gets if the Player has the Bone in the hand. */ private boolean hasPlayerGotBoneInHand(EntityPlayer player) { ItemStack itemstack = player.inventory.getCurrentItem(); @@ -94,4 +62,38 @@ public class EntityAIBeg extends EntityAIBase { : (!this.theWolf.isTamed() && itemstack.getItem() == Items.bone ? true : this.theWolf.isBreedingItem(itemstack)); } + + /** + * + Resets the task + */ + public void resetTask() { + this.theWolf.setBegging(false); + this.thePlayer = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + this.thePlayer = this.worldObject.getClosestPlayerToEntity(this.theWolf, (double) this.minPlayerDistance); + return this.thePlayer == null ? false : this.hasPlayerGotBoneInHand(this.thePlayer); + } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.theWolf.setBegging(true); + this.timeoutCounter = 40 + this.theWolf.getRNG().nextInt(40); + } + + /** + * + Updates the task + */ + public void updateTask() { + this.theWolf.getLookHelper().setLookPosition(this.thePlayer.posX, + this.thePlayer.posY + (double) this.thePlayer.getEyeHeight(), this.thePlayer.posZ, 10.0F, + (float) this.theWolf.getVerticalFaceSpeed()); + --this.timeoutCounter; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIBreakDoor.java b/src/game/java/net/minecraft/entity/ai/EntityAIBreakDoor.java index e4a74aa9..9fa3ef0b 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIBreakDoor.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIBreakDoor.java @@ -5,22 +5,25 @@ import net.minecraft.block.BlockDoor; import net.minecraft.entity.EntityLiving; import net.minecraft.world.EnumDifficulty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,31 +36,8 @@ public class EntityAIBreakDoor extends EntityAIDoorInteract { super(entityIn); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - if (!super.shouldExecute()) { - return false; - } else if (!this.theEntity.worldObj.getGameRules().getBoolean("mobGriefing")) { - return false; - } else { - BlockDoor blockdoor = this.doorBlock; - return !BlockDoor.isOpen(this.theEntity.worldObj, this.doorPosition); - } - } - - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - super.startExecuting(); - this.breakingTime = 0; - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { double d0 = this.theEntity.getDistanceSq(this.doorPosition); @@ -74,16 +54,38 @@ public class EntityAIBreakDoor extends EntityAIDoorInteract { return flag; } - /**+ - * Resets the task + /** + * + Resets the task */ public void resetTask() { super.resetTask(); this.theEntity.worldObj.sendBlockBreakProgress(this.theEntity.getEntityId(), this.doorPosition, -1); } - /**+ - * Updates the task + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + if (!super.shouldExecute()) { + return false; + } else if (!this.theEntity.worldObj.getGameRules().getBoolean("mobGriefing")) { + return false; + } else { + BlockDoor blockdoor = this.doorBlock; + return !BlockDoor.isOpen(this.theEntity.worldObj, this.doorPosition); + } + } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + super.startExecuting(); + this.breakingTime = 0; + } + + /** + * + Updates the task */ public void updateTask() { super.updateTask(); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIControlledByPlayer.java b/src/game/java/net/minecraft/entity/ai/EntityAIControlledByPlayer.java index d926bc46..1f2ac762 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIControlledByPlayer.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIControlledByPlayer.java @@ -13,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.pathfinder.WalkNodeProcessor; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,23 +50,46 @@ public class EntityAIControlledByPlayer extends EntityAIBase { this.setMutexBits(7); } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Boost the entity's movement speed. */ - public void startExecuting() { - this.currentSpeed = 0.0F; + public void boostSpeed() { + this.speedBoosted = true; + this.speedBoostTime = 0; + this.maxSpeedBoostTime = this.thisEntity.getRNG().nextInt(841) + 140; } - /**+ - * Resets the task + /** + * + Return whether the entity is being controlled by a player. + */ + public boolean isControlledByPlayer() { + return !this.isSpeedBoosted() && this.currentSpeed > this.maxSpeed * 0.3F; + } + + /** + * + Return whether the entity's speed is boosted. + */ + public boolean isSpeedBoosted() { + return this.speedBoosted; + } + + /** + * + True if the block is a stair block or a slab block + */ + private boolean isStairOrSlab(Block blockIn) { + return blockIn instanceof BlockStairs || blockIn instanceof BlockSlab; + } + + /** + * + Resets the task */ public void resetTask() { this.speedBoosted = false; this.currentSpeed = 0.0F; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { return this.thisEntity.isEntityAlive() && this.thisEntity.riddenByEntity != null @@ -71,8 +97,15 @@ public class EntityAIControlledByPlayer extends EntityAIBase { && (this.speedBoosted || this.thisEntity.canBeSteered()); } - /**+ - * Updates the task + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.currentSpeed = 0.0F; + } + + /** + * + Updates the task */ public void updateTask() { EntityPlayer entityplayer = (EntityPlayer) this.thisEntity.riddenByEntity; @@ -180,34 +213,4 @@ public class EntityAIControlledByPlayer extends EntityAIBase { this.thisEntity.moveEntityWithHeading(0.0F, f1); } - - /**+ - * True if the block is a stair block or a slab block - */ - private boolean isStairOrSlab(Block blockIn) { - return blockIn instanceof BlockStairs || blockIn instanceof BlockSlab; - } - - /**+ - * Return whether the entity's speed is boosted. - */ - public boolean isSpeedBoosted() { - return this.speedBoosted; - } - - /**+ - * Boost the entity's movement speed. - */ - public void boostSpeed() { - this.speedBoosted = true; - this.speedBoostTime = 0; - this.maxSpeedBoostTime = this.thisEntity.getRNG().nextInt(841) + 140; - } - - /**+ - * Return whether the entity is being controlled by a player. - */ - public boolean isControlledByPlayer() { - return !this.isSpeedBoosted() && this.currentSpeed > this.maxSpeed * 0.3F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAICreeperSwell.java b/src/game/java/net/minecraft/entity/ai/EntityAICreeperSwell.java index c6b87291..87426dd4 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAICreeperSwell.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAICreeperSwell.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.monster.EntityCreeper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +35,15 @@ public class EntityAICreeperSwell extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Resets the task + */ + public void resetTask() { + this.creeperAttackTarget = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.swellingCreeper.getAttackTarget(); @@ -41,23 +51,16 @@ public class EntityAICreeperSwell extends EntityAIBase { || entitylivingbase != null && this.swellingCreeper.getDistanceSqToEntity(entitylivingbase) < 9.0D; } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.swellingCreeper.getNavigator().clearPathEntity(); this.creeperAttackTarget = this.swellingCreeper.getAttackTarget(); } - /**+ - * Resets the task - */ - public void resetTask() { - this.creeperAttackTarget = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { if (this.creeperAttackTarget == null) { diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIDefendVillage.java b/src/game/java/net/minecraft/entity/ai/EntityAIDefendVillage.java index 8dcc208f..9f68a79c 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIDefendVillage.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIDefendVillage.java @@ -5,22 +5,25 @@ import net.minecraft.entity.monster.EntityCreeper; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.village.Village; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,8 +38,8 @@ public class EntityAIDefendVillage extends EntityAITarget { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { Village village = this.irongolem.getVillage(); @@ -59,8 +62,8 @@ public class EntityAIDefendVillage extends EntityAITarget { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.irongolem.setAttackTarget(this.villageAgressorTarget); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIDoorInteract.java b/src/game/java/net/minecraft/entity/ai/EntityAIDoorInteract.java index 3e192d59..72578eaa 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIDoorInteract.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIDoorInteract.java @@ -9,22 +9,25 @@ import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.pathfinding.PathPoint; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,8 +47,20 @@ public abstract class EntityAIDoorInteract extends EntityAIBase { } } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.hasStoppedDoorInteraction; + } + + private BlockDoor getBlockDoor(BlockPos pos) { + Block block = this.theEntity.worldObj.getBlockState(pos).getBlock(); + return block instanceof BlockDoor && block.getMaterial() == Material.wood ? (BlockDoor) block : null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.theEntity.isCollidedHorizontally) { @@ -76,16 +91,8 @@ public abstract class EntityAIDoorInteract extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.hasStoppedDoorInteraction; - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.hasStoppedDoorInteraction = false; @@ -93,8 +100,8 @@ public abstract class EntityAIDoorInteract extends EntityAIBase { this.entityPositionZ = (float) ((double) ((float) this.doorPosition.getZ() + 0.5F) - this.theEntity.posZ); } - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { float f = (float) ((double) ((float) this.doorPosition.getX() + 0.5F) - this.theEntity.posX); @@ -105,9 +112,4 @@ public abstract class EntityAIDoorInteract extends EntityAIBase { } } - - private BlockDoor getBlockDoor(BlockPos pos) { - Block block = this.theEntity.worldObj.getBlockState(pos).getBlock(); - return block instanceof BlockDoor && block.getMaterial() == Material.wood ? (BlockDoor) block : null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIEatGrass.java b/src/game/java/net/minecraft/entity/ai/EntityAIEatGrass.java index 878dfb49..ebfb91f4 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIEatGrass.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIEatGrass.java @@ -2,6 +2,7 @@ package net.minecraft.entity.ai; import com.google.common.base.Predicate; import com.google.common.base.Predicates; + import net.minecraft.block.Block; import net.minecraft.block.BlockTallGrass; import net.minecraft.block.state.IBlockState; @@ -11,22 +12,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,8 +48,29 @@ public class EntityAIEatGrass extends EntityAIBase { this.setMutexBits(7); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.eatingGrassTimer > 0; + } + + /** + * + Number of ticks since the entity started to eat grass + */ + public int getEatingGrassTimer() { + return this.eatingGrassTimer; + } + + /** + * + Resets the task + */ + public void resetTask() { + this.eatingGrassTimer = 0; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.grassEaterEntity.getRNG().nextInt(this.grassEaterEntity.isChild() ? 50 : 1000) != 0) { @@ -58,8 +83,8 @@ public class EntityAIEatGrass extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.eatingGrassTimer = 40; @@ -67,30 +92,8 @@ public class EntityAIEatGrass extends EntityAIBase { this.grassEaterEntity.getNavigator().clearPathEntity(); } - /**+ - * Resets the task - */ - public void resetTask() { - this.eatingGrassTimer = 0; - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.eatingGrassTimer > 0; - } - - /**+ - * Number of ticks since the entity started to eat grass - */ - public int getEatingGrassTimer() { - return this.eatingGrassTimer; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.eatingGrassTimer = Math.max(0, this.eatingGrassTimer - 1); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearest.java b/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearest.java index 97e8ac29..6b7db41c 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearest.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearest.java @@ -1,33 +1,38 @@ package net.minecraft.entity.ai; -import com.google.common.base.Predicate; import java.util.Collections; import java.util.List; + +import com.google.common.base.Predicate; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayerMP; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -64,25 +69,8 @@ public class EntityAIFindEntityNearest extends EntityAIBase { this.field_179440_d = new EntityAINearestAttackableTarget.Sorter(parEntityLiving); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - double d0 = this.func_179438_f(); - List list = this.field_179442_b.worldObj.getEntitiesWithinAABB(this.field_179439_f, - this.field_179442_b.getEntityBoundingBox().expand(d0, 4.0D, d0), this.field_179443_c); - Collections.sort(list, this.field_179440_d); - if (list.isEmpty()) { - return false; - } else { - this.field_179441_e = (EntityLivingBase) list.get(0); - return true; - } - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { EntityLivingBase entitylivingbase = this.field_179442_b.getAttackTarget(); @@ -98,25 +86,41 @@ public class EntityAIFindEntityNearest extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - this.field_179442_b.setAttackTarget(this.field_179441_e); - super.startExecuting(); + protected double func_179438_f() { + IAttributeInstance iattributeinstance = this.field_179442_b + .getEntityAttribute(SharedMonsterAttributes.followRange); + return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); } - /**+ - * Resets the task + /** + * + Resets the task */ public void resetTask() { this.field_179442_b.setAttackTarget((EntityLivingBase) null); super.startExecuting(); } - protected double func_179438_f() { - IAttributeInstance iattributeinstance = this.field_179442_b - .getEntityAttribute(SharedMonsterAttributes.followRange); - return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + double d0 = this.func_179438_f(); + List list = this.field_179442_b.worldObj.getEntitiesWithinAABB(this.field_179439_f, + this.field_179442_b.getEntityBoundingBox().expand(d0, 4.0D, d0), this.field_179443_c); + Collections.sort(list, this.field_179440_d); + if (list.isEmpty()) { + return false; + } else { + this.field_179441_e = (EntityLivingBase) list.get(0); + return true; + } + } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.field_179442_b.setAttackTarget(this.field_179441_e); + super.startExecuting(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearestPlayer.java b/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearestPlayer.java index 3a7e0df1..5be58c2e 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearestPlayer.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIFindEntityNearestPlayer.java @@ -1,8 +1,12 @@ package net.minecraft.entity.ai; -import com.google.common.base.Predicate; import java.util.Collections; import java.util.List; + +import com.google.common.base.Predicate; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLiving; @@ -12,25 +16,26 @@ import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.scoreboard.Team; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -79,25 +84,8 @@ public class EntityAIFindEntityNearestPlayer extends EntityAIBase { this.field_179432_d = new EntityAINearestAttackableTarget.Sorter(parEntityLiving); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - double d0 = this.func_179431_f(); - List list = this.field_179434_b.worldObj.getEntitiesWithinAABB(EntityPlayer.class, - this.field_179434_b.getEntityBoundingBox().expand(d0, 4.0D, d0), this.field_179435_c); - Collections.sort(list, this.field_179432_d); - if (list.isEmpty()) { - return false; - } else { - this.field_179433_e = (EntityLivingBase) list.get(0); - return true; - } - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { EntityLivingBase entitylivingbase = this.field_179434_b.getAttackTarget(); @@ -122,25 +110,41 @@ public class EntityAIFindEntityNearestPlayer extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - this.field_179434_b.setAttackTarget(this.field_179433_e); - super.startExecuting(); + protected double func_179431_f() { + IAttributeInstance iattributeinstance = this.field_179434_b + .getEntityAttribute(SharedMonsterAttributes.followRange); + return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); } - /**+ - * Resets the task + /** + * + Resets the task */ public void resetTask() { this.field_179434_b.setAttackTarget((EntityLivingBase) null); super.startExecuting(); } - protected double func_179431_f() { - IAttributeInstance iattributeinstance = this.field_179434_b - .getEntityAttribute(SharedMonsterAttributes.followRange); - return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + double d0 = this.func_179431_f(); + List list = this.field_179434_b.worldObj.getEntitiesWithinAABB(EntityPlayer.class, + this.field_179434_b.getEntityBoundingBox().expand(d0, 4.0D, d0), this.field_179435_c); + Collections.sort(list, this.field_179432_d); + if (list.isEmpty()) { + return false; + } else { + this.field_179433_e = (EntityLivingBase) list.get(0); + return true; + } + } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.field_179434_b.setAttackTarget(this.field_179433_e); + super.startExecuting(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIFleeSun.java b/src/game/java/net/minecraft/entity/ai/EntityAIFleeSun.java index 95d894ed..7b47499b 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIFleeSun.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIFleeSun.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,8 +44,30 @@ public class EntityAIFleeSun extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.theCreature.getNavigator().noPath(); + } + + private Vec3 findPossibleShelter() { + EaglercraftRandom random = this.theCreature.getRNG(); + BlockPos blockpos = new BlockPos(this.theCreature.posX, this.theCreature.getEntityBoundingBox().minY, + this.theCreature.posZ); + + for (int i = 0; i < 10; ++i) { + BlockPos blockpos1 = blockpos.add(random.nextInt(20) - 10, random.nextInt(6) - 3, random.nextInt(20) - 10); + if (!this.theWorld.canSeeSky(blockpos1) && this.theCreature.getBlockPathWeight(blockpos1) < 0.0F) { + return new Vec3((double) blockpos1.getX(), (double) blockpos1.getY(), (double) blockpos1.getZ()); + } + } + + return null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.theWorld.isDaytime()) { @@ -65,33 +90,10 @@ public class EntityAIFleeSun extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.theCreature.getNavigator().noPath(); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.theCreature.getNavigator().tryMoveToXYZ(this.shelterX, this.shelterY, this.shelterZ, this.movementSpeed); } - - private Vec3 findPossibleShelter() { - EaglercraftRandom random = this.theCreature.getRNG(); - BlockPos blockpos = new BlockPos(this.theCreature.posX, this.theCreature.getEntityBoundingBox().minY, - this.theCreature.posZ); - - for (int i = 0; i < 10; ++i) { - BlockPos blockpos1 = blockpos.add(random.nextInt(20) - 10, random.nextInt(6) - 3, random.nextInt(20) - 10); - if (!this.theWorld.canSeeSky(blockpos1) && this.theCreature.getBlockPathWeight(blockpos1) < 0.0F) { - return new Vec3((double) blockpos1.getX(), (double) blockpos1.getY(), (double) blockpos1.getZ()); - } - } - - return null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIFollowGolem.java b/src/game/java/net/minecraft/entity/ai/EntityAIFollowGolem.java index e5594d45..561b9d60 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIFollowGolem.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIFollowGolem.java @@ -1,25 +1,29 @@ package net.minecraft.entity.ai; import java.util.List; + import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.entity.passive.EntityVillager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,8 +39,23 @@ public class EntityAIFollowGolem extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.theGolem.getHoldRoseTick() > 0; + } + + /** + * + Resets the task + */ + public void resetTask() { + this.theGolem = null; + this.theVillager.getNavigator().clearPathEntity(); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.theVillager.getGrowingAge() >= 0) { @@ -62,16 +81,8 @@ public class EntityAIFollowGolem extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.theGolem.getHoldRoseTick() > 0; - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.takeGolemRoseTick = this.theVillager.getRNG().nextInt(320); @@ -79,16 +90,8 @@ public class EntityAIFollowGolem extends EntityAIBase { this.theGolem.getNavigator().clearPathEntity(); } - /**+ - * Resets the task - */ - public void resetTask() { - this.theGolem = null; - this.theVillager.getNavigator().clearPathEntity(); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.theVillager.getLookHelper().setLookPositionWithEntity(this.theGolem, 30.0F, 30.0F); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIFollowOwner.java b/src/game/java/net/minecraft/entity/ai/EntityAIFollowOwner.java index 0d47a30f..9aaa8257 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIFollowOwner.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIFollowOwner.java @@ -12,22 +12,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,8 +59,32 @@ public class EntityAIFollowOwner extends EntityAIBase { } } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.petPathfinder.noPath() + && this.thePet.getDistanceSqToEntity(this.theOwner) > (double) (this.maxDist * this.maxDist) + && !this.thePet.isSitting(); + } + + private boolean func_181065_a(BlockPos parBlockPos) { + IBlockState iblockstate = this.theWorld.getBlockState(parBlockPos); + Block block = iblockstate.getBlock(); + return block == Blocks.air ? true : !block.isFullCube(); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.theOwner = null; + this.petPathfinder.clearPathEntity(); + ((PathNavigateGround) this.thePet.getNavigator()).setAvoidsWater(true); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.thePet.getOwner(); @@ -75,18 +102,8 @@ public class EntityAIFollowOwner extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.petPathfinder.noPath() - && this.thePet.getDistanceSqToEntity(this.theOwner) > (double) (this.maxDist * this.maxDist) - && !this.thePet.isSitting(); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.field_75343_h = 0; @@ -94,23 +111,8 @@ public class EntityAIFollowOwner extends EntityAIBase { ((PathNavigateGround) this.thePet.getNavigator()).setAvoidsWater(false); } - /**+ - * Resets the task - */ - public void resetTask() { - this.theOwner = null; - this.petPathfinder.clearPathEntity(); - ((PathNavigateGround) this.thePet.getNavigator()).setAvoidsWater(true); - } - - private boolean func_181065_a(BlockPos parBlockPos) { - IBlockState iblockstate = this.theWorld.getBlockState(parBlockPos); - Block block = iblockstate.getBlock(); - return block == Blocks.air ? true : !block.isFullCube(); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.thePet.getLookHelper().setLookPositionWithEntity(this.theOwner, 10.0F, diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIFollowParent.java b/src/game/java/net/minecraft/entity/ai/EntityAIFollowParent.java index 3e08a974..2ca5cd59 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIFollowParent.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIFollowParent.java @@ -1,24 +1,28 @@ package net.minecraft.entity.ai; import java.util.List; + import net.minecraft.entity.passive.EntityAnimal; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +38,29 @@ public class EntityAIFollowParent extends EntityAIBase { this.moveSpeed = speed; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + if (this.childAnimal.getGrowingAge() >= 0) { + return false; + } else if (!this.parentAnimal.isEntityAlive()) { + return false; + } else { + double d0 = this.childAnimal.getDistanceSqToEntity(this.parentAnimal); + return d0 >= 9.0D && d0 <= 256.0D; + } + } + + /** + * + Resets the task + */ + public void resetTask() { + this.parentAnimal = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.childAnimal.getGrowingAge() >= 0) { @@ -68,37 +93,15 @@ public class EntityAIFollowParent extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - if (this.childAnimal.getGrowingAge() >= 0) { - return false; - } else if (!this.parentAnimal.isEntityAlive()) { - return false; - } else { - double d0 = this.childAnimal.getDistanceSqToEntity(this.parentAnimal); - return d0 >= 9.0D && d0 <= 256.0D; - } - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.delayCounter = 0; } - /**+ - * Resets the task - */ - public void resetTask() { - this.parentAnimal = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { if (--this.delayCounter <= 0) { diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIHarvestFarmland.java b/src/game/java/net/minecraft/entity/ai/EntityAIHarvestFarmland.java index 56f421d5..199347c4 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIHarvestFarmland.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIHarvestFarmland.java @@ -11,22 +11,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,8 +45,22 @@ public class EntityAIHarvestFarmland extends EntityAIMoveToBlock { this.theVillager = theVillagerIn; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.field_179501_f >= 0 && super.continueExecuting(); + } + + /** + * + Resets the task + */ + public void resetTask() { + super.resetTask(); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.runDelay <= 0) { @@ -59,30 +76,39 @@ public class EntityAIHarvestFarmland extends EntityAIMoveToBlock { return super.shouldExecute(); } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Return true to set given position as destination */ - public boolean continueExecuting() { - return this.field_179501_f >= 0 && super.continueExecuting(); + protected boolean shouldMoveTo(World worldIn, BlockPos pos) { + Block block = worldIn.getBlockState(pos).getBlock(); + if (block == Blocks.farmland) { + pos = pos.up(); + IBlockState iblockstate = worldIn.getBlockState(pos); + block = iblockstate.getBlock(); + if (block instanceof BlockCrops && ((Integer) iblockstate.getValue(BlockCrops.AGE)).intValue() == 7 + && this.field_179503_e && (this.field_179501_f == 0 || this.field_179501_f < 0)) { + this.field_179501_f = 0; + return true; + } + + if (block == Blocks.air && this.hasFarmItem && (this.field_179501_f == 1 || this.field_179501_f < 0)) { + this.field_179501_f = 1; + return true; + } + } + + return false; } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { super.startExecuting(); } - /**+ - * Resets the task - */ - public void resetTask() { - super.resetTask(); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { super.updateTask(); @@ -131,28 +157,4 @@ public class EntityAIHarvestFarmland extends EntityAIMoveToBlock { } } - - /**+ - * Return true to set given position as destination - */ - protected boolean shouldMoveTo(World worldIn, BlockPos pos) { - Block block = worldIn.getBlockState(pos).getBlock(); - if (block == Blocks.farmland) { - pos = pos.up(); - IBlockState iblockstate = worldIn.getBlockState(pos); - block = iblockstate.getBlock(); - if (block instanceof BlockCrops && ((Integer) iblockstate.getValue(BlockCrops.AGE)).intValue() == 7 - && this.field_179503_e && (this.field_179501_f == 0 || this.field_179501_f < 0)) { - this.field_179501_f = 0; - return true; - } - - if (block == Blocks.air && this.hasFarmItem && (this.field_179501_f == 1 || this.field_179501_f < 0)) { - this.field_179501_f = 1; - return true; - } - } - - return false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIHurtByTarget.java b/src/game/java/net/minecraft/entity/ai/EntityAIHurtByTarget.java index 08cbec7a..1ddc846c 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIHurtByTarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIHurtByTarget.java @@ -6,22 +6,25 @@ import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.AxisAlignedBB; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,16 +41,20 @@ public class EntityAIHurtByTarget extends EntityAITarget { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + protected void setEntityAttackTarget(EntityCreature creatureIn, EntityLivingBase entityLivingBaseIn) { + creatureIn.setAttackTarget(entityLivingBaseIn); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { int i = this.taskOwner.getRevengeTimer(); return i != this.revengeTimerOld && this.isSuitableTarget(this.taskOwner.getAITarget(), false); } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.taskOwner.setAttackTarget(this.taskOwner.getAITarget()); @@ -58,7 +65,7 @@ public class EntityAIHurtByTarget extends EntityAITarget { List lst = this.taskOwner.worldObj.getEntitiesWithinAABB(this.taskOwner.getClass(), (new AxisAlignedBB(this.taskOwner.posX, this.taskOwner.posY, this.taskOwner.posZ, this.taskOwner.posX + 1.0D, this.taskOwner.posY + 1.0D, this.taskOwner.posZ + 1.0D)) - .expand(d0, 10.0D, d0)); + .expand(d0, 10.0D, d0)); for (int i = 0, l = lst.size(); i < l; ++i) { EntityCreature entitycreature = lst.get(i); if (this.taskOwner != entitycreature && entitycreature.getAttackTarget() == null @@ -81,8 +88,4 @@ public class EntityAIHurtByTarget extends EntityAITarget { super.startExecuting(); } - - protected void setEntityAttackTarget(EntityCreature creatureIn, EntityLivingBase entityLivingBaseIn) { - creatureIn.setAttackTarget(entityLivingBaseIn); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAILeapAtTarget.java b/src/game/java/net/minecraft/entity/ai/EntityAILeapAtTarget.java index e2edc2bc..26ce5401 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAILeapAtTarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAILeapAtTarget.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,8 +38,15 @@ public class EntityAILeapAtTarget extends EntityAIBase { this.setMutexBits(5); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.leaper.onGround; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { this.leapTarget = this.leaper.getAttackTarget(); @@ -49,16 +59,8 @@ public class EntityAILeapAtTarget extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.leaper.onGround; - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { double d0 = this.leapTarget.posX - this.leaper.posX; diff --git a/src/game/java/net/minecraft/entity/ai/EntityAILookAtTradePlayer.java b/src/game/java/net/minecraft/entity/ai/EntityAILookAtTradePlayer.java index 4bd24dba..d61b8556 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAILookAtTradePlayer.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAILookAtTradePlayer.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +34,8 @@ public class EntityAILookAtTradePlayer extends EntityAIWatchClosest { this.theMerchant = theMerchantIn; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.theMerchant.isTrading()) { diff --git a/src/game/java/net/minecraft/entity/ai/EntityAILookAtVillager.java b/src/game/java/net/minecraft/entity/ai/EntityAILookAtVillager.java index 4f4e0c87..3eabfcdb 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAILookAtVillager.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAILookAtVillager.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.monster.EntityIronGolem; import net.minecraft.entity.passive.EntityVillager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +36,23 @@ public class EntityAILookAtVillager extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.lookTime > 0; + } + + /** + * + Resets the task + */ + public void resetTask() { + this.theGolem.setHoldingRose(false); + this.theVillager = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.theGolem.worldObj.isDaytime()) { @@ -48,32 +66,16 @@ public class EntityAILookAtVillager extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.lookTime > 0; - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.lookTime = 400; this.theGolem.setHoldingRose(true); } - /**+ - * Resets the task - */ - public void resetTask() { - this.theGolem.setHoldingRose(false); - this.theVillager = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.theGolem.getLookHelper().setLookPositionWithEntity(this.theVillager, 30.0F, 30.0F); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAILookIdle.java b/src/game/java/net/minecraft/entity/ai/EntityAILookIdle.java index 0dfd75be..a8f6f3b7 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAILookIdle.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAILookIdle.java @@ -2,22 +2,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLiving; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,23 +36,22 @@ public class EntityAILookIdle extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - return this.idleEntity.getRNG().nextFloat() < 0.02F; - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return this.idleTime >= 0; } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + return this.idleEntity.getRNG().nextFloat() < 0.02F; + } + + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { double d0 = 6.283185307179586D * this.idleEntity.getRNG().nextDouble(); @@ -58,8 +60,8 @@ public class EntityAILookIdle extends EntityAIBase { this.idleTime = 20 + this.idleEntity.getRNG().nextInt(20); } - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { --this.idleTime; diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIMate.java b/src/game/java/net/minecraft/entity/ai/EntityAIMate.java index 3e33112a..de2bbd4a 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIMate.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIMate.java @@ -1,6 +1,7 @@ package net.minecraft.entity.ai; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.entity.EntityAgeable; import net.minecraft.entity.item.EntityXPOrb; @@ -12,22 +13,25 @@ import net.minecraft.stats.StatList; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,52 +50,16 @@ public class EntityAIMate extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - if (!this.theAnimal.isInLove()) { - return false; - } else { - this.targetMate = this.getNearbyMate(); - return this.targetMate != null; - } - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return this.targetMate.isEntityAlive() && this.targetMate.isInLove() && this.spawnBabyDelay < 60; } - /**+ - * Resets the task - */ - public void resetTask() { - this.targetMate = null; - this.spawnBabyDelay = 0; - } - - /**+ - * Updates the task - */ - public void updateTask() { - this.theAnimal.getLookHelper().setLookPositionWithEntity(this.targetMate, 10.0F, - (float) this.theAnimal.getVerticalFaceSpeed()); - this.theAnimal.getNavigator().tryMoveToEntityLiving(this.targetMate, this.moveSpeed); - ++this.spawnBabyDelay; - if (this.spawnBabyDelay >= 60 && this.theAnimal.getDistanceSqToEntity(this.targetMate) < 9.0D) { - this.spawnBaby(); - } - - } - - /**+ - * Loops through nearby animals and finds another animal of the - * same type that can be mated with. Returns the first valid - * mate found. + /** + * + Loops through nearby animals and finds another animal of the same type that + * can be mated with. Returns the first valid mate found. */ private EntityAnimal getNearbyMate() { float f = 8.0F; @@ -111,8 +79,28 @@ public class EntityAIMate extends EntityAIBase { return entityanimal; } - /**+ - * Spawns a baby animal of the same type. + /** + * + Resets the task + */ + public void resetTask() { + this.targetMate = null; + this.spawnBabyDelay = 0; + } + + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + if (!this.theAnimal.isInLove()) { + return false; + } else { + this.targetMate = this.getNearbyMate(); + return this.targetMate != null; + } + } + + /** + * + Spawns a baby animal of the same type. */ private void spawnBaby() { EntityAgeable entityageable = this.theAnimal.createChild(this.targetMate); @@ -157,4 +145,18 @@ public class EntityAIMate extends EntityAIBase { } } + + /** + * + Updates the task + */ + public void updateTask() { + this.theAnimal.getLookHelper().setLookPositionWithEntity(this.targetMate, 10.0F, + (float) this.theAnimal.getVerticalFaceSpeed()); + this.theAnimal.getNavigator().tryMoveToEntityLiving(this.targetMate, this.moveSpeed); + ++this.spawnBabyDelay; + if (this.spawnBabyDelay >= 60 && this.theAnimal.getDistanceSqToEntity(this.targetMate) < 9.0D) { + this.spawnBaby(); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIMoveIndoors.java b/src/game/java/net/minecraft/entity/ai/EntityAIMoveIndoors.java index e8c36054..dfb2b3dd 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIMoveIndoors.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIMoveIndoors.java @@ -6,22 +6,25 @@ import net.minecraft.util.Vec3; import net.minecraft.village.Village; import net.minecraft.village.VillageDoorInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,24 @@ public class EntityAIMoveIndoors extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.entityObj.getNavigator().noPath(); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.insidePosX = this.doorInfo.getInsideBlockPos().getX(); + this.insidePosZ = this.doorInfo.getInsideBlockPos().getZ(); + this.doorInfo = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { BlockPos blockpos = new BlockPos(this.entityObj); @@ -64,16 +83,8 @@ public class EntityAIMoveIndoors extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.entityObj.getNavigator().noPath(); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.insidePosX = -1; @@ -92,13 +103,4 @@ public class EntityAIMoveIndoors extends EntityAIBase { } } - - /**+ - * Resets the task - */ - public void resetTask() { - this.insidePosX = this.doorInfo.getInsideBlockPos().getX(); - this.insidePosZ = this.doorInfo.getInsideBlockPos().getZ(); - this.doorInfo = null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIMoveThroughVillage.java b/src/game/java/net/minecraft/entity/ai/EntityAIMoveThroughVillage.java index 2022c6dd..19aacd38 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIMoveThroughVillage.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIMoveThroughVillage.java @@ -1,7 +1,9 @@ package net.minecraft.entity.ai; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.entity.EntityCreature; import net.minecraft.pathfinding.PathEntity; import net.minecraft.pathfinding.PathNavigateGround; @@ -11,22 +13,25 @@ import net.minecraft.util.Vec3; import net.minecraft.village.Village; import net.minecraft.village.VillageDoorInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,8 +54,67 @@ public class EntityAIMoveThroughVillage extends EntityAIBase { } } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + if (this.theEntity.getNavigator().noPath()) { + return false; + } else { + float f = this.theEntity.width + 4.0F; + return this.theEntity.getDistanceSq(this.doorInfo.getDoorBlockPos()) > (double) (f * f); + } + } + + private boolean doesDoorListContain(VillageDoorInfo doorInfoIn) { + for (int i = 0, l = this.doorList.size(); i < l; ++i) { + VillageDoorInfo villagedoorinfo = this.doorList.get(i); + if (doorInfoIn.getDoorBlockPos().equals(villagedoorinfo.getDoorBlockPos())) { + return true; + } + } + + return false; + } + + private VillageDoorInfo findNearestDoor(Village villageIn) { + VillageDoorInfo villagedoorinfo = null; + int i = Integer.MAX_VALUE; + + List lst = villageIn.getVillageDoorInfoList(); + for (int k = 0, l = lst.size(); k < l; ++k) { + VillageDoorInfo villagedoorinfo1 = lst.get(k); + int j = villagedoorinfo1.getDistanceSquared(MathHelper.floor_double(this.theEntity.posX), + MathHelper.floor_double(this.theEntity.posY), MathHelper.floor_double(this.theEntity.posZ)); + if (j < i && !this.doesDoorListContain(villagedoorinfo1)) { + villagedoorinfo = villagedoorinfo1; + i = j; + } + } + + return villagedoorinfo; + } + + /** + * + Resets the task + */ + public void resetTask() { + if (this.theEntity.getNavigator().noPath() + || this.theEntity.getDistanceSq(this.doorInfo.getDoorBlockPos()) < 16.0D) { + this.doorList.add(this.doorInfo); + } + + } + + private void resizeDoorList() { + if (this.doorList.size() > 15) { + this.doorList.remove(0); + } + + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { this.resizeDoorList(); @@ -93,70 +157,10 @@ public class EntityAIMoveThroughVillage extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - if (this.theEntity.getNavigator().noPath()) { - return false; - } else { - float f = this.theEntity.width + 4.0F; - return this.theEntity.getDistanceSq(this.doorInfo.getDoorBlockPos()) > (double) (f * f); - } - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.theEntity.getNavigator().setPath(this.entityPathNavigate, this.movementSpeed); } - - /**+ - * Resets the task - */ - public void resetTask() { - if (this.theEntity.getNavigator().noPath() - || this.theEntity.getDistanceSq(this.doorInfo.getDoorBlockPos()) < 16.0D) { - this.doorList.add(this.doorInfo); - } - - } - - private VillageDoorInfo findNearestDoor(Village villageIn) { - VillageDoorInfo villagedoorinfo = null; - int i = Integer.MAX_VALUE; - - List lst = villageIn.getVillageDoorInfoList(); - for (int k = 0, l = lst.size(); k < l; ++k) { - VillageDoorInfo villagedoorinfo1 = lst.get(k); - int j = villagedoorinfo1.getDistanceSquared(MathHelper.floor_double(this.theEntity.posX), - MathHelper.floor_double(this.theEntity.posY), MathHelper.floor_double(this.theEntity.posZ)); - if (j < i && !this.doesDoorListContain(villagedoorinfo1)) { - villagedoorinfo = villagedoorinfo1; - i = j; - } - } - - return villagedoorinfo; - } - - private boolean doesDoorListContain(VillageDoorInfo doorInfoIn) { - for (int i = 0, l = this.doorList.size(); i < l; ++i) { - VillageDoorInfo villagedoorinfo = this.doorList.get(i); - if (doorInfoIn.getDoorBlockPos().equals(villagedoorinfo.getDoorBlockPos())) { - return true; - } - } - - return false; - } - - private void resizeDoorList() { - if (this.doorList.size() > 15) { - this.doorList.remove(0); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIMoveToBlock.java b/src/game/java/net/minecraft/entity/ai/EntityAIMoveToBlock.java index 7a727850..ef21e826 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIMoveToBlock.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIMoveToBlock.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityCreature; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,8 +33,8 @@ public abstract class EntityAIMoveToBlock extends EntityAIBase { protected int runDelay; private int timeoutCounter; private int field_179490_f; - /**+ - * Block to move to + /** + * + Block to move to */ protected BlockPos destinationBlock = BlockPos.ORIGIN; private boolean isAboveDestination; @@ -44,74 +47,29 @@ public abstract class EntityAIMoveToBlock extends EntityAIBase { this.setMutexBits(5); } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - if (this.runDelay > 0) { - --this.runDelay; - return false; - } else { - this.runDelay = 200 + this.theEntity.getRNG().nextInt(200); - return this.searchForDestination(); - } - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return this.timeoutCounter >= -this.field_179490_f && this.timeoutCounter <= 1200 && this.shouldMoveTo(this.theEntity.worldObj, this.destinationBlock); } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - this.theEntity.getNavigator().tryMoveToXYZ((double) ((float) this.destinationBlock.getX()) + 0.5D, - (double) (this.destinationBlock.getY() + 1), (double) ((float) this.destinationBlock.getZ()) + 0.5D, - this.movementSpeed); - this.timeoutCounter = 0; - this.field_179490_f = this.theEntity.getRNG().nextInt(this.theEntity.getRNG().nextInt(1200) + 1200) + 1200; - } - - /**+ - * Resets the task - */ - public void resetTask() { - } - - /**+ - * Updates the task - */ - public void updateTask() { - if (this.theEntity.getDistanceSqToCenter(this.destinationBlock.up()) > 1.0D) { - this.isAboveDestination = false; - ++this.timeoutCounter; - if (this.timeoutCounter % 40 == 0) { - this.theEntity.getNavigator().tryMoveToXYZ((double) ((float) this.destinationBlock.getX()) + 0.5D, - (double) (this.destinationBlock.getY() + 1), - (double) ((float) this.destinationBlock.getZ()) + 0.5D, this.movementSpeed); - } - } else { - this.isAboveDestination = true; - --this.timeoutCounter; - } - - } - protected boolean getIsAboveDestination() { return this.isAboveDestination; } - /**+ - * Searches and sets new destination block and returns true if a - * suitable block (specified in {@link - * net.minecraft.entity.ai.EntityAIMoveToBlock#shouldMoveTo(World, - * BlockPos) EntityAIMoveToBlock#shouldMoveTo(World, BlockPos)}) - * can be found. + /** + * + Resets the task + */ + public void resetTask() { + } + + /** + * + Searches and sets new destination block and returns true if a suitable + * block (specified in + * {@link net.minecraft.entity.ai.EntityAIMoveToBlock#shouldMoveTo(World, BlockPos) + * EntityAIMoveToBlock#shouldMoveTo(World, BlockPos)}) can be found. */ private boolean searchForDestination() { int i = this.searchLength; @@ -136,5 +94,48 @@ public abstract class EntityAIMoveToBlock extends EntityAIBase { return false; } + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + if (this.runDelay > 0) { + --this.runDelay; + return false; + } else { + this.runDelay = 200 + this.theEntity.getRNG().nextInt(200); + return this.searchForDestination(); + } + } + protected abstract boolean shouldMoveTo(World var1, BlockPos var2); + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.theEntity.getNavigator().tryMoveToXYZ((double) ((float) this.destinationBlock.getX()) + 0.5D, + (double) (this.destinationBlock.getY() + 1), (double) ((float) this.destinationBlock.getZ()) + 0.5D, + this.movementSpeed); + this.timeoutCounter = 0; + this.field_179490_f = this.theEntity.getRNG().nextInt(this.theEntity.getRNG().nextInt(1200) + 1200) + 1200; + } + + /** + * + Updates the task + */ + public void updateTask() { + if (this.theEntity.getDistanceSqToCenter(this.destinationBlock.up()) > 1.0D) { + this.isAboveDestination = false; + ++this.timeoutCounter; + if (this.timeoutCounter % 40 == 0) { + this.theEntity.getNavigator().tryMoveToXYZ((double) ((float) this.destinationBlock.getX()) + 0.5D, + (double) (this.destinationBlock.getY() + 1), + (double) ((float) this.destinationBlock.getZ()) + 0.5D, this.movementSpeed); + } + } else { + this.isAboveDestination = true; + --this.timeoutCounter; + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsRestriction.java b/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsRestriction.java index b63f9b27..68ee5d7a 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsRestriction.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsRestriction.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityCreature; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,15 @@ public class EntityAIMoveTowardsRestriction extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.theEntity.getNavigator().noPath(); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.theEntity.isWithinHomeDistanceCurrentPosition()) { @@ -58,16 +68,8 @@ public class EntityAIMoveTowardsRestriction extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.theEntity.getNavigator().noPath(); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.theEntity.getNavigator().tryMoveToXYZ(this.movePosX, this.movePosY, this.movePosZ, this.movementSpeed); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsTarget.java b/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsTarget.java index 857200a2..471e9747 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsTarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIMoveTowardsTarget.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,8 +43,23 @@ public class EntityAIMoveTowardsTarget extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.theEntity.getNavigator().noPath() && this.targetEntity.isEntityAlive() && this.targetEntity + .getDistanceSqToEntity(this.theEntity) < (double) (this.maxTargetDistance * this.maxTargetDistance); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.targetEntity = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { this.targetEntity = this.theEntity.getAttackTarget(); @@ -64,24 +82,8 @@ public class EntityAIMoveTowardsTarget extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.theEntity.getNavigator().noPath() && this.targetEntity.isEntityAlive() && this.targetEntity - .getDistanceSqToEntity(this.theEntity) < (double) (this.maxTargetDistance * this.maxTargetDistance); - } - - /**+ - * Resets the task - */ - public void resetTask() { - this.targetEntity = null; - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.theEntity.getNavigator().tryMoveToXYZ(this.movePosX, this.movePosY, this.movePosZ, this.speed); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAINearestAttackableTarget.java b/src/game/java/net/minecraft/entity/ai/EntityAINearestAttackableTarget.java index 559aa298..c9b1143d 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAINearestAttackableTarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAINearestAttackableTarget.java @@ -1,41 +1,61 @@ package net.minecraft.entity.ai; -import com.google.common.base.Predicate; -import com.google.common.base.Predicates; import java.util.Collections; import java.util.Comparator; import java.util.List; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; + import net.minecraft.entity.Entity; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EntitySelectors; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityAINearestAttackableTarget extends EntityAITarget { + public static class Sorter implements Comparator { + private final Entity theEntity; + + public Sorter(Entity theEntityIn) { + this.theEntity = theEntityIn; + } + + public int compare(Entity entity, Entity entity1) { + double d0 = this.theEntity.getDistanceSqToEntity(entity); + double d1 = this.theEntity.getDistanceSqToEntity(entity1); + return d0 < d1 ? -1 : (d0 > d1 ? 1 : 0); + } + } + protected final Class targetClass; private final int targetChance; protected final EntityAINearestAttackableTarget.Sorter theNearestAttackableTargetSorter; protected Predicate targetEntitySelector; + protected EntityLivingBase targetEntity; public EntityAINearestAttackableTarget(EntityCreature creature, Class classTarget, boolean checkSight) { @@ -86,8 +106,8 @@ public class EntityAINearestAttackableTarget extends }; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.targetChance > 0 && this.taskOwner.getRNG().nextInt(this.targetChance) != 0) { @@ -107,25 +127,11 @@ public class EntityAINearestAttackableTarget extends } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.taskOwner.setAttackTarget(this.targetEntity); super.startExecuting(); } - - public static class Sorter implements Comparator { - private final Entity theEntity; - - public Sorter(Entity theEntityIn) { - this.theEntity = theEntityIn; - } - - public int compare(Entity entity, Entity entity1) { - double d0 = this.theEntity.getDistanceSqToEntity(entity); - double d1 = this.theEntity.getDistanceSqToEntity(entity1); - return d0 < d1 ? -1 : (d0 > d1 ? 1 : 0); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAINetherCreeperSwell.java b/src/game/java/net/minecraft/entity/ai/EntityAINetherCreeperSwell.java new file mode 100644 index 00000000..7b5abb75 --- /dev/null +++ b/src/game/java/net/minecraft/entity/ai/EntityAINetherCreeperSwell.java @@ -0,0 +1,76 @@ +package net.minecraft.entity.ai; + +import net.minecraft.entity.EntityLivingBase; +import net.minecraft.entity.monster.EntityNetherCreeper; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class EntityAINetherCreeperSwell extends EntityAIBase { + EntityNetherCreeper swellingCreeper; + EntityLivingBase creeperAttackTarget; + + public EntityAINetherCreeperSwell(EntityNetherCreeper entityNetherCreeper) { + this.swellingCreeper = entityNetherCreeper; + this.setMutexBits(1); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.creeperAttackTarget = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + EntityLivingBase entitylivingbase = this.swellingCreeper.getAttackTarget(); + return this.swellingCreeper.getCreeperState() > 0 + || entitylivingbase != null && this.swellingCreeper.getDistanceSqToEntity(entitylivingbase) < 9.0D; + } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.swellingCreeper.getNavigator().clearPathEntity(); + this.creeperAttackTarget = this.swellingCreeper.getAttackTarget(); + } + + /** + * + Updates the task + */ + public void updateTask() { + if (this.creeperAttackTarget == null) { + this.swellingCreeper.setCreeperState(-1); + } else if (this.swellingCreeper.getDistanceSqToEntity(this.creeperAttackTarget) > 49.0D) { + this.swellingCreeper.setCreeperState(-1); + } else if (!this.swellingCreeper.getEntitySenses().canSee(this.creeperAttackTarget)) { + this.swellingCreeper.setCreeperState(-1); + } else { + this.swellingCreeper.setCreeperState(1); + } + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIOcelotAttack.java b/src/game/java/net/minecraft/entity/ai/EntityAIOcelotAttack.java index e53e9328..5c5a5161 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIOcelotAttack.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIOcelotAttack.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,25 @@ public class EntityAIOcelotAttack extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.theVictim.isEntityAlive() ? false + : (this.theEntity.getDistanceSqToEntity(this.theVictim) > 225.0D ? false + : !this.theEntity.getNavigator().noPath() || this.shouldExecute()); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.theVictim = null; + this.theEntity.getNavigator().clearPathEntity(); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.theEntity.getAttackTarget(); @@ -49,26 +69,8 @@ public class EntityAIOcelotAttack extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.theVictim.isEntityAlive() ? false - : (this.theEntity.getDistanceSqToEntity(this.theVictim) > 225.0D ? false - : !this.theEntity.getNavigator().noPath() || this.shouldExecute()); - } - - /**+ - * Resets the task - */ - public void resetTask() { - this.theVictim = null; - this.theEntity.getNavigator().clearPathEntity(); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.theEntity.getLookHelper().setLookPositionWithEntity(this.theVictim, 30.0F, 30.0F); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIOcelotSit.java b/src/game/java/net/minecraft/entity/ai/EntityAIOcelotSit.java index d940717b..0f68816f 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIOcelotSit.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIOcelotSit.java @@ -10,22 +10,25 @@ import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,53 +41,30 @@ public class EntityAIOcelotSit extends EntityAIMoveToBlock { this.field_151493_a = parEntityOcelot; } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - return this.field_151493_a.isTamed() && !this.field_151493_a.isSitting() && super.shouldExecute(); - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return super.continueExecuting(); } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - super.startExecuting(); - this.field_151493_a.getAISit().setSitting(false); - } - - /**+ - * Resets the task + /** + * + Resets the task */ public void resetTask() { super.resetTask(); this.field_151493_a.setSitting(false); } - /**+ - * Updates the task + /** + * + Returns whether the EntityAIBase should begin execution. */ - public void updateTask() { - super.updateTask(); - this.field_151493_a.getAISit().setSitting(false); - if (!this.getIsAboveDestination()) { - this.field_151493_a.setSitting(false); - } else if (!this.field_151493_a.isSitting()) { - this.field_151493_a.setSitting(true); - } - + public boolean shouldExecute() { + return this.field_151493_a.isTamed() && !this.field_151493_a.isSitting() && super.shouldExecute(); } - /**+ - * Return true to set given position as destination + /** + * + Return true to set given position as destination */ protected boolean shouldMoveTo(World world, BlockPos blockpos) { if (!world.isAirBlock(blockpos.up())) { @@ -110,4 +90,26 @@ public class EntityAIOcelotSit extends EntityAIMoveToBlock { return false; } } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + super.startExecuting(); + this.field_151493_a.getAISit().setSitting(false); + } + + /** + * + Updates the task + */ + public void updateTask() { + super.updateTask(); + this.field_151493_a.getAISit().setSitting(false); + if (!this.getIsAboveDestination()) { + this.field_151493_a.setSitting(false); + } else if (!this.field_151493_a.isSitting()) { + this.field_151493_a.setSitting(true); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIOpenDoor.java b/src/game/java/net/minecraft/entity/ai/EntityAIOpenDoor.java index 459b630d..58b083ce 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIOpenDoor.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIOpenDoor.java @@ -2,22 +2,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLiving; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,24 +35,15 @@ public class EntityAIOpenDoor extends EntityAIDoorInteract { this.closeDoor = shouldClose; } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { return this.closeDoor && this.closeDoorTemporisation > 0 && super.continueExecuting(); } - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - this.closeDoorTemporisation = 20; - this.doorBlock.toggleDoor(this.theEntity.worldObj, this.doorPosition, true); - } - - /**+ - * Resets the task + /** + * + Resets the task */ public void resetTask() { if (this.closeDoor) { @@ -58,8 +52,16 @@ public class EntityAIOpenDoor extends EntityAIDoorInteract { } - /**+ - * Updates the task + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.closeDoorTemporisation = 20; + this.doorBlock.toggleDoor(this.theEntity.worldObj, this.doorPosition, true); + } + + /** + * + Updates the task */ public void updateTask() { --this.closeDoorTemporisation; diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtByTarget.java b/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtByTarget.java index 236bd090..edd55448 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtByTarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtByTarget.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +37,8 @@ public class EntityAIOwnerHurtByTarget extends EntityAITarget { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.theDefendingTameable.isTamed()) { @@ -53,8 +56,8 @@ public class EntityAIOwnerHurtByTarget extends EntityAITarget { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.taskOwner.setAttackTarget(this.theOwnerAttacker); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtTarget.java b/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtTarget.java index 7d6f1151..32a1c3f3 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtTarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIOwnerHurtTarget.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +37,8 @@ public class EntityAIOwnerHurtTarget extends EntityAITarget { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.theEntityTameable.isTamed()) { @@ -53,8 +56,8 @@ public class EntityAIOwnerHurtTarget extends EntityAITarget { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.taskOwner.setAttackTarget(this.theTarget); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIPanic.java b/src/game/java/net/minecraft/entity/ai/EntityAIPanic.java index a30d3b7f..ca429da1 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIPanic.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIPanic.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityCreature; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,15 @@ public class EntityAIPanic extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.theEntityCreature.getNavigator().noPath(); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.theEntityCreature.getAITarget() == null && !this.theEntityCreature.isBurning()) { @@ -55,18 +65,10 @@ public class EntityAIPanic extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.theEntityCreature.getNavigator().tryMoveToXYZ(this.randPosX, this.randPosY, this.randPosZ, this.speed); } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.theEntityCreature.getNavigator().noPath(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIPlay.java b/src/game/java/net/minecraft/entity/ai/EntityAIPlay.java index 058bf86b..d6f12826 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIPlay.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIPlay.java @@ -1,26 +1,30 @@ package net.minecraft.entity.ai; import java.util.List; + import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +41,23 @@ public class EntityAIPlay extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.playTime > 0; + } + + /** + * + Resets the task + */ + public void resetTask() { + this.villagerObj.setPlaying(false); + this.targetVillager = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.villagerObj.getGrowingAge() >= 0) { @@ -73,16 +92,8 @@ public class EntityAIPlay extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.playTime > 0; - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { if (this.targetVillager != null) { @@ -92,16 +103,8 @@ public class EntityAIPlay extends EntityAIBase { this.playTime = 1000; } - /**+ - * Resets the task - */ - public void resetTask() { - this.villagerObj.setPlaying(false); - this.targetVillager = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { --this.playTime; diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIRestrictOpenDoor.java b/src/game/java/net/minecraft/entity/ai/EntityAIRestrictOpenDoor.java index 5ed5fc70..3d9b3378 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIRestrictOpenDoor.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIRestrictOpenDoor.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.village.Village; import net.minecraft.village.VillageDoorInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,26 @@ public class EntityAIRestrictOpenDoor extends EntityAIBase { } } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.entityObj.worldObj.isDaytime() ? false + : !this.frontDoor.getIsDetachedFromVillageFlag() + && this.frontDoor.func_179850_c(new BlockPos(this.entityObj)); + } + + /** + * + Resets the task + */ + public void resetTask() { + ((PathNavigateGround) this.entityObj.getNavigator()).setBreakDoors(true); + ((PathNavigateGround) this.entityObj.getNavigator()).setEnterDoors(true); + this.frontDoor = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.entityObj.worldObj.isDaytime()) { @@ -56,35 +77,16 @@ public class EntityAIRestrictOpenDoor extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.entityObj.worldObj.isDaytime() ? false - : !this.frontDoor.getIsDetachedFromVillageFlag() - && this.frontDoor.func_179850_c(new BlockPos(this.entityObj)); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { ((PathNavigateGround) this.entityObj.getNavigator()).setBreakDoors(false); ((PathNavigateGround) this.entityObj.getNavigator()).setEnterDoors(false); } - /**+ - * Resets the task - */ - public void resetTask() { - ((PathNavigateGround) this.entityObj.getNavigator()).setBreakDoors(true); - ((PathNavigateGround) this.entityObj.getNavigator()).setEnterDoors(true); - this.frontDoor = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.frontDoor.incrementDoorOpeningRestrictionCounter(); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIRestrictSun.java b/src/game/java/net/minecraft/entity/ai/EntityAIRestrictSun.java index 4c1603fd..34ac84a3 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIRestrictSun.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIRestrictSun.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityCreature; import net.minecraft.pathfinding.PathNavigateGround; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,24 +33,24 @@ public class EntityAIRestrictSun extends EntityAIBase { this.theEntity = parEntityCreature; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Resets the task + */ + public void resetTask() { + ((PathNavigateGround) this.theEntity.getNavigator()).setAvoidSun(false); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { return this.theEntity.worldObj.isDaytime(); } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { ((PathNavigateGround) this.theEntity.getNavigator()).setAvoidSun(true); } - - /**+ - * Resets the task - */ - public void resetTask() { - ((PathNavigateGround) this.theEntity.getNavigator()).setAvoidSun(false); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIRunAroundLikeCrazy.java b/src/game/java/net/minecraft/entity/ai/EntityAIRunAroundLikeCrazy.java index 35acf88d..d98f8377 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIRunAroundLikeCrazy.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIRunAroundLikeCrazy.java @@ -5,22 +5,25 @@ import net.minecraft.entity.passive.EntityHorse; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,8 +41,15 @@ public class EntityAIRunAroundLikeCrazy extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.horseHost.getNavigator().noPath() && this.horseHost.riddenByEntity != null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.horseHost.isTame() && this.horseHost.riddenByEntity != null) { @@ -57,23 +67,15 @@ public class EntityAIRunAroundLikeCrazy extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.horseHost.getNavigator().tryMoveToXYZ(this.targetX, this.targetY, this.targetZ, this.speed); } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.horseHost.getNavigator().noPath() && this.horseHost.riddenByEntity != null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { if (this.horseHost.getRNG().nextInt(50) == 0) { diff --git a/src/game/java/net/minecraft/entity/ai/EntityAISit.java b/src/game/java/net/minecraft/entity/ai/EntityAISit.java index 2cc6621d..eae7f0e5 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAISit.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAISit.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +35,22 @@ public class EntityAISit extends EntityAIBase { this.setMutexBits(5); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Resets the task + */ + public void resetTask() { + this.theEntity.setSitting(false); + } + + /** + * + Sets the sitting flag. + */ + public void setSitting(boolean sitting) { + this.isSitting = sitting; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.theEntity.isTamed()) { @@ -50,25 +67,11 @@ public class EntityAISit extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.theEntity.getNavigator().clearPathEntity(); this.theEntity.setSitting(true); } - - /**+ - * Resets the task - */ - public void resetTask() { - this.theEntity.setSitting(false); - } - - /**+ - * Sets the sitting flag. - */ - public void setSitting(boolean sitting) { - this.isSitting = sitting; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAISwimming.java b/src/game/java/net/minecraft/entity/ai/EntityAISwimming.java index a64d4dbd..f5b3dd8c 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAISwimming.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAISwimming.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLiving; import net.minecraft.pathfinding.PathNavigateGround; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,15 +35,15 @@ public class EntityAISwimming extends EntityAIBase { ((PathNavigateGround) entitylivingIn.getNavigator()).setCanSwim(true); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { return this.theEntity.isInWater() || this.theEntity.isInLava(); } - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { if (this.theEntity.getRNG().nextFloat() < 0.8F) { diff --git a/src/game/java/net/minecraft/entity/ai/EntityAITarget.java b/src/game/java/net/minecraft/entity/ai/EntityAITarget.java index 8c40b353..186e95a0 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAITarget.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAITarget.java @@ -1,5 +1,7 @@ package net.minecraft.entity.ai; +import org.apache.commons.lang3.StringUtils; + import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; @@ -13,106 +15,33 @@ import net.minecraft.scoreboard.Team; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; -import org.apache.commons.lang3.StringUtils; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class EntityAITarget extends EntityAIBase { - protected final EntityCreature taskOwner; - protected boolean shouldCheckSight; - private boolean nearbyOnly; - private int targetSearchStatus; - private int targetSearchDelay; - private int targetUnseenTicks; - - public EntityAITarget(EntityCreature creature, boolean checkSight) { - this(creature, checkSight, false); - } - - public EntityAITarget(EntityCreature creature, boolean checkSight, boolean onlyNearby) { - this.taskOwner = creature; - this.shouldCheckSight = checkSight; - this.nearbyOnly = onlyNearby; - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - EntityLivingBase entitylivingbase = this.taskOwner.getAttackTarget(); - if (entitylivingbase == null) { - return false; - } else if (!entitylivingbase.isEntityAlive()) { - return false; - } else { - Team team = this.taskOwner.getTeam(); - Team team1 = entitylivingbase.getTeam(); - if (team != null && team1 == team) { - return false; - } else { - double d0 = this.getTargetDistance(); - if (this.taskOwner.getDistanceSqToEntity(entitylivingbase) > d0 * d0) { - return false; - } else { - if (this.shouldCheckSight) { - if (this.taskOwner.getEntitySenses().canSee(entitylivingbase)) { - this.targetUnseenTicks = 0; - } else if (++this.targetUnseenTicks > 60) { - return false; - } - } - - return !(entitylivingbase instanceof EntityPlayer) - || !((EntityPlayer) entitylivingbase).capabilities.disableDamage; - } - } - } - } - - protected double getTargetDistance() { - IAttributeInstance iattributeinstance = this.taskOwner.getEntityAttribute(SharedMonsterAttributes.followRange); - return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); - } - - /**+ - * Execute a one shot task or start executing a continuous task - */ - public void startExecuting() { - this.targetSearchStatus = 0; - this.targetSearchDelay = 0; - this.targetUnseenTicks = 0; - } - - /**+ - * Resets the task - */ - public void resetTask() { - this.taskOwner.setAttackTarget((EntityLivingBase) null); - } - - /**+ - * A method used to see if an entity is a suitable target - * through a number of checks. Args : entity, - * canTargetInvinciblePlayer + /** + * + A method used to see if an entity is a suitable target through a number of + * checks. Args : entity, canTargetInvinciblePlayer */ public static boolean isSuitableTarget(EntityLiving attacker, EntityLivingBase target, boolean includeInvincibles, boolean checkSight) { @@ -150,10 +79,86 @@ public abstract class EntityAITarget extends EntityAIBase { } } - /**+ - * A method used to see if an entity is a suitable target - * through a number of checks. Args : entity, - * canTargetInvinciblePlayer + protected final EntityCreature taskOwner; + protected boolean shouldCheckSight; + private boolean nearbyOnly; + private int targetSearchStatus; + private int targetSearchDelay; + + private int targetUnseenTicks; + + public EntityAITarget(EntityCreature creature, boolean checkSight) { + this(creature, checkSight, false); + } + + public EntityAITarget(EntityCreature creature, boolean checkSight, boolean onlyNearby) { + this.taskOwner = creature; + this.shouldCheckSight = checkSight; + this.nearbyOnly = onlyNearby; + } + + /** + * + Checks to see if this entity can find a short path to the given target. + */ + private boolean canEasilyReach(EntityLivingBase parEntityLivingBase) { + this.targetSearchDelay = 10 + this.taskOwner.getRNG().nextInt(5); + PathEntity pathentity = this.taskOwner.getNavigator().getPathToEntityLiving(parEntityLivingBase); + if (pathentity == null) { + return false; + } else { + PathPoint pathpoint = pathentity.getFinalPathPoint(); + if (pathpoint == null) { + return false; + } else { + int i = pathpoint.xCoord - MathHelper.floor_double(parEntityLivingBase.posX); + int j = pathpoint.zCoord - MathHelper.floor_double(parEntityLivingBase.posZ); + return (double) (i * i + j * j) <= 2.25D; + } + } + } + + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + EntityLivingBase entitylivingbase = this.taskOwner.getAttackTarget(); + if (entitylivingbase == null) { + return false; + } else if (!entitylivingbase.isEntityAlive()) { + return false; + } else { + Team team = this.taskOwner.getTeam(); + Team team1 = entitylivingbase.getTeam(); + if (team != null && team1 == team) { + return false; + } else { + double d0 = this.getTargetDistance(); + if (this.taskOwner.getDistanceSqToEntity(entitylivingbase) > d0 * d0) { + return false; + } else { + if (this.shouldCheckSight) { + if (this.taskOwner.getEntitySenses().canSee(entitylivingbase)) { + this.targetUnseenTicks = 0; + } else if (++this.targetUnseenTicks > 60) { + return false; + } + } + + return !(entitylivingbase instanceof EntityPlayer) + || !((EntityPlayer) entitylivingbase).capabilities.disableDamage; + } + } + } + } + + protected double getTargetDistance() { + IAttributeInstance iattributeinstance = this.taskOwner.getEntityAttribute(SharedMonsterAttributes.followRange); + return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); + } + + /** + * + A method used to see if an entity is a suitable target through a number of + * checks. Args : entity, canTargetInvinciblePlayer */ protected boolean isSuitableTarget(EntityLivingBase target, boolean includeInvincibles) { if (!isSuitableTarget(this.taskOwner, target, includeInvincibles, this.shouldCheckSight)) { @@ -179,24 +184,19 @@ public abstract class EntityAITarget extends EntityAIBase { } } - /**+ - * Checks to see if this entity can find a short path to the - * given target. + /** + * + Resets the task */ - private boolean canEasilyReach(EntityLivingBase parEntityLivingBase) { - this.targetSearchDelay = 10 + this.taskOwner.getRNG().nextInt(5); - PathEntity pathentity = this.taskOwner.getNavigator().getPathToEntityLiving(parEntityLivingBase); - if (pathentity == null) { - return false; - } else { - PathPoint pathpoint = pathentity.getFinalPathPoint(); - if (pathpoint == null) { - return false; - } else { - int i = pathpoint.xCoord - MathHelper.floor_double(parEntityLivingBase.posX); - int j = pathpoint.zCoord - MathHelper.floor_double(parEntityLivingBase.posZ); - return (double) (i * i + j * j) <= 2.25D; - } - } + public void resetTask() { + this.taskOwner.setAttackTarget((EntityLivingBase) null); + } + + /** + * + Execute a one shot task or start executing a continuous task + */ + public void startExecuting() { + this.targetSearchStatus = 0; + this.targetSearchDelay = 0; + this.targetUnseenTicks = 0; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAITargetNonTamed.java b/src/game/java/net/minecraft/entity/ai/EntityAITargetNonTamed.java index 0c683303..27e3ea6f 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAITargetNonTamed.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAITargetNonTamed.java @@ -1,25 +1,29 @@ package net.minecraft.entity.ai; import com.google.common.base.Predicate; + import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityTameable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +37,8 @@ public class EntityAITargetNonTamed extends EntityAI this.theTameable = entityIn; } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { return !this.theTameable.isTamed() && super.shouldExecute(); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAITasks.java b/src/game/java/net/minecraft/entity/ai/EntityAITasks.java index 5e9757fd..191dff54 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAITasks.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAITasks.java @@ -1,72 +1,105 @@ package net.minecraft.entity.ai; -import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityAITasks { + class EntityAITaskEntry { + public EntityAIBase action; + public int priority; + + public EntityAITaskEntry(int priorityIn, EntityAIBase task) { + this.priority = priorityIn; + this.action = task; + } + } + private static final Logger logger = LogManager.getLogger(); - /**+ - * A list of EntityAITaskEntrys in EntityAITasks. + /** + * + A list of EntityAITaskEntrys in EntityAITasks. */ private List taskEntries = Lists.newArrayList(); - /**+ - * A list of EntityAITaskEntrys that are currently being - * executed. + /** + * + A list of EntityAITaskEntrys that are currently being executed. */ private List executingTaskEntries = Lists.newArrayList(); private int tickCount; + private int tickRate = 3; - /**+ - * Add a now AITask. Args : priority, task + /** + * + Add a now AITask. Args : priority, task */ public void addTask(int priority, EntityAIBase task) { this.taskEntries.add(new EntityAITasks.EntityAITaskEntry(priority, task)); } - /**+ - * removes the indicated task from the entity's AI tasks. + /** + * + Returns whether two EntityAITaskEntries can be executed concurrently */ - public void removeTask(EntityAIBase task) { - Iterator iterator = this.taskEntries.iterator(); + private boolean areTasksCompatible(EntityAITasks.EntityAITaskEntry taskEntry1, + EntityAITasks.EntityAITaskEntry taskEntry2) { + return (taskEntry1.action.getMutexBits() & taskEntry2.action.getMutexBits()) == 0; + } - while (iterator.hasNext()) { - EntityAITasks.EntityAITaskEntry entityaitasks$entityaitaskentry = (EntityAITasks.EntityAITaskEntry) iterator - .next(); - EntityAIBase entityaibase = entityaitasks$entityaitaskentry.action; - if (entityaibase == task) { - if (this.executingTaskEntries.contains(entityaitasks$entityaitaskentry)) { - entityaibase.resetTask(); - this.executingTaskEntries.remove(entityaitasks$entityaitaskentry); + /** + * + Determine if a specific AI Task should continue being executed. + */ + private boolean canContinue(EntityAITasks.EntityAITaskEntry taskEntry) { + boolean flag = taskEntry.action.continueExecuting(); + return flag; + } + + /** + * + Determine if a specific AI Task can be executed, which means that all + * running higher (= lower int value) priority tasks are compatible with it or + * all lower priority tasks can be interrupted. + */ + private boolean canUse(EntityAITasks.EntityAITaskEntry taskEntry) { + for (int i = 0, l = this.taskEntries.size(); i < l; ++i) { + EntityAITasks.EntityAITaskEntry entityaitasks$entityaitaskentry = this.taskEntries.get(i); + if (entityaitasks$entityaitaskentry != taskEntry) { + if (taskEntry.priority >= entityaitasks$entityaitaskentry.priority) { + if (!this.areTasksCompatible(taskEntry, entityaitasks$entityaitaskentry) + && this.executingTaskEntries.contains(entityaitasks$entityaitaskentry)) { + return false; + } + } else if (!entityaitasks$entityaitaskentry.action.isInterruptible() + && this.executingTaskEntries.contains(entityaitasks$entityaitaskentry)) { + return false; } - - iterator.remove(); } } + return true; } public void onUpdateTasks() { @@ -118,56 +151,25 @@ public class EntityAITasks { } } - /**+ - * Determine if a specific AI Task should continue being - * executed. + /** + * + removes the indicated task from the entity's AI tasks. */ - private boolean canContinue(EntityAITasks.EntityAITaskEntry taskEntry) { - boolean flag = taskEntry.action.continueExecuting(); - return flag; - } + public void removeTask(EntityAIBase task) { + Iterator iterator = this.taskEntries.iterator(); - /**+ - * Determine if a specific AI Task can be executed, which means - * that all running higher (= lower int value) priority tasks - * are compatible with it or all lower priority tasks can be - * interrupted. - */ - private boolean canUse(EntityAITasks.EntityAITaskEntry taskEntry) { - for (int i = 0, l = this.taskEntries.size(); i < l; ++i) { - EntityAITasks.EntityAITaskEntry entityaitasks$entityaitaskentry = this.taskEntries.get(i); - if (entityaitasks$entityaitaskentry != taskEntry) { - if (taskEntry.priority >= entityaitasks$entityaitaskentry.priority) { - if (!this.areTasksCompatible(taskEntry, entityaitasks$entityaitaskentry) - && this.executingTaskEntries.contains(entityaitasks$entityaitaskentry)) { - return false; - } - } else if (!entityaitasks$entityaitaskentry.action.isInterruptible() - && this.executingTaskEntries.contains(entityaitasks$entityaitaskentry)) { - return false; + while (iterator.hasNext()) { + EntityAITasks.EntityAITaskEntry entityaitasks$entityaitaskentry = (EntityAITasks.EntityAITaskEntry) iterator + .next(); + EntityAIBase entityaibase = entityaitasks$entityaitaskentry.action; + if (entityaibase == task) { + if (this.executingTaskEntries.contains(entityaitasks$entityaitaskentry)) { + entityaibase.resetTask(); + this.executingTaskEntries.remove(entityaitasks$entityaitaskentry); } + + iterator.remove(); } } - return true; - } - - /**+ - * Returns whether two EntityAITaskEntries can be executed - * concurrently - */ - private boolean areTasksCompatible(EntityAITasks.EntityAITaskEntry taskEntry1, - EntityAITasks.EntityAITaskEntry taskEntry2) { - return (taskEntry1.action.getMutexBits() & taskEntry2.action.getMutexBits()) == 0; - } - - class EntityAITaskEntry { - public EntityAIBase action; - public int priority; - - public EntityAITaskEntry(int priorityIn, EntityAIBase task) { - this.priority = priorityIn; - this.action = task; - } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAITempt.java b/src/game/java/net/minecraft/entity/ai/EntityAITempt.java index fd5b07a7..051289aa 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAITempt.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAITempt.java @@ -6,22 +6,25 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.pathfinding.PathNavigateGround; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,27 +56,8 @@ public class EntityAITempt extends EntityAIBase { } } - /**+ - * Returns whether the EntityAIBase should begin execution. - */ - public boolean shouldExecute() { - if (this.delayTemptCounter > 0) { - --this.delayTemptCounter; - return false; - } else { - this.temptingPlayer = this.temptedEntity.worldObj.getClosestPlayerToEntity(this.temptedEntity, 10.0D); - if (this.temptingPlayer == null) { - return false; - } else { - ItemStack itemstack = this.temptingPlayer.getCurrentEquippedItem(); - return itemstack == null ? false : itemstack.getItem() == this.temptItem; - } - } - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing + /** + * + Returns whether an in-progress EntityAIBase should continue executing */ public boolean continueExecuting() { if (this.scaredByPlayerMovement) { @@ -100,8 +84,46 @@ public class EntityAITempt extends EntityAIBase { return this.shouldExecute(); } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + + * + * @see #isRunning + */ + public boolean isRunning() { + return this.isRunning; + } + + /** + * + Resets the task + */ + public void resetTask() { + this.temptingPlayer = null; + this.temptedEntity.getNavigator().clearPathEntity(); + this.delayTemptCounter = 100; + this.isRunning = false; + ((PathNavigateGround) this.temptedEntity.getNavigator()).setAvoidsWater(this.avoidWater); + } + + /** + * + Returns whether the EntityAIBase should begin execution. + */ + public boolean shouldExecute() { + if (this.delayTemptCounter > 0) { + --this.delayTemptCounter; + return false; + } else { + this.temptingPlayer = this.temptedEntity.worldObj.getClosestPlayerToEntity(this.temptedEntity, 10.0D); + if (this.temptingPlayer == null) { + return false; + } else { + ItemStack itemstack = this.temptingPlayer.getCurrentEquippedItem(); + return itemstack == null ? false : itemstack.getItem() == this.temptItem; + } + } + } + + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.targetX = this.temptingPlayer.posX; @@ -112,19 +134,8 @@ public class EntityAITempt extends EntityAIBase { ((PathNavigateGround) this.temptedEntity.getNavigator()).setAvoidsWater(false); } - /**+ - * Resets the task - */ - public void resetTask() { - this.temptingPlayer = null; - this.temptedEntity.getNavigator().clearPathEntity(); - this.delayTemptCounter = 100; - this.isRunning = false; - ((PathNavigateGround) this.temptedEntity.getNavigator()).setAvoidsWater(this.avoidWater); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.temptedEntity.getLookHelper().setLookPositionWithEntity(this.temptingPlayer, 30.0F, @@ -136,11 +147,4 @@ public class EntityAITempt extends EntityAIBase { } } - - /**+ - * @see #isRunning - */ - public boolean isRunning() { - return this.isRunning; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAITradePlayer.java b/src/game/java/net/minecraft/entity/ai/EntityAITradePlayer.java index d20d0ebc..18ae3f9a 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAITradePlayer.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAITradePlayer.java @@ -4,22 +4,25 @@ import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +35,15 @@ public class EntityAITradePlayer extends EntityAIBase { this.setMutexBits(5); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Resets the task + */ + public void resetTask() { + this.villager.setCustomer((EntityPlayer) null); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.villager.isEntityAlive()) { @@ -52,17 +62,10 @@ public class EntityAITradePlayer extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.villager.getNavigator().clearPathEntity(); } - - /**+ - * Resets the task - */ - public void resetTask() { - this.villager.setCustomer((EntityPlayer) null); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIVillagerInteract.java b/src/game/java/net/minecraft/entity/ai/EntityAIVillagerInteract.java index 8e62eac3..3471eaf3 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIVillagerInteract.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIVillagerInteract.java @@ -8,22 +8,25 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,8 @@ public class EntityAIVillagerInteract extends EntityAIWatchClosest2 { this.villager = villagerIn; } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { super.startExecuting(); @@ -51,8 +54,8 @@ public class EntityAIVillagerInteract extends EntityAIWatchClosest2 { } - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { super.updateTask(); diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIVillagerMate.java b/src/game/java/net/minecraft/entity/ai/EntityAIVillagerMate.java index 48cb5529..8213c14a 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIVillagerMate.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIVillagerMate.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.village.Village; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,8 +42,47 @@ public class EntityAIVillagerMate extends EntityAIBase { this.setMutexBits(3); } - /**+ - * Returns whether the EntityAIBase should begin execution. + private boolean checkSufficientDoorsPresentForNewVillager() { + if (!this.villageObj.isMatingSeason()) { + return false; + } else { + int i = (int) ((double) ((float) this.villageObj.getNumVillageDoors()) * 0.35D); + return this.villageObj.getNumVillagers() < i; + } + } + + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return this.matingTimeout >= 0 && this.checkSufficientDoorsPresentForNewVillager() + && this.villagerObj.getGrowingAge() == 0 && this.villagerObj.getIsWillingToMate(false); + } + + private void giveBirth() { + EntityVillager entityvillager = this.villagerObj.createChild(this.mate); + this.mate.setGrowingAge(6000); + this.villagerObj.setGrowingAge(6000); + this.mate.setIsWillingToMate(false); + this.villagerObj.setIsWillingToMate(false); + entityvillager.setGrowingAge(-24000); + entityvillager.setLocationAndAngles(this.villagerObj.posX, this.villagerObj.posY, this.villagerObj.posZ, 0.0F, + 0.0F); + this.worldObj.spawnEntityInWorld(entityvillager); + this.worldObj.setEntityState(entityvillager, (byte) 12); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.villageObj = null; + this.mate = null; + this.villagerObj.setMating(false); + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.villagerObj.getGrowingAge() != 0) { @@ -66,34 +108,16 @@ public class EntityAIVillagerMate extends EntityAIBase { } } - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.matingTimeout = 300; this.villagerObj.setMating(true); } - /**+ - * Resets the task - */ - public void resetTask() { - this.villageObj = null; - this.mate = null; - this.villagerObj.setMating(false); - } - - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return this.matingTimeout >= 0 && this.checkSufficientDoorsPresentForNewVillager() - && this.villagerObj.getGrowingAge() == 0 && this.villagerObj.getIsWillingToMate(false); - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { --this.matingTimeout; @@ -109,26 +133,4 @@ public class EntityAIVillagerMate extends EntityAIBase { } } - - private boolean checkSufficientDoorsPresentForNewVillager() { - if (!this.villageObj.isMatingSeason()) { - return false; - } else { - int i = (int) ((double) ((float) this.villageObj.getNumVillageDoors()) * 0.35D); - return this.villageObj.getNumVillagers() < i; - } - } - - private void giveBirth() { - EntityVillager entityvillager = this.villagerObj.createChild(this.mate); - this.mate.setGrowingAge(6000); - this.villagerObj.setGrowingAge(6000); - this.mate.setIsWillingToMate(false); - this.villagerObj.setIsWillingToMate(false); - entityvillager.setGrowingAge(-24000); - entityvillager.setLocationAndAngles(this.villagerObj.posX, this.villagerObj.posY, this.villagerObj.posZ, 0.0F, - 0.0F); - this.worldObj.spawnEntityInWorld(entityvillager); - this.worldObj.setEntityState(entityvillager, (byte) 12); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIWander.java b/src/game/java/net/minecraft/entity/ai/EntityAIWander.java index 5b5136c3..227443a1 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIWander.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIWander.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityCreature; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,8 +46,29 @@ public class EntityAIWander extends EntityAIBase { this.setMutexBits(1); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.entity.getNavigator().noPath(); + } + + /** + * + Makes task to bypass chance + */ + public void makeUpdate() { + this.mustUpdate = true; + } + + /** + * + Changes task random possibility for execution + */ + public void setExecutionChance(int newchance) { + this.executionChance = newchance; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (!this.mustUpdate) { @@ -69,32 +93,10 @@ public class EntityAIWander extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.entity.getNavigator().noPath(); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.entity.getNavigator().tryMoveToXYZ(this.xPosition, this.yPosition, this.zPosition, this.speed); } - - /**+ - * Makes task to bypass chance - */ - public void makeUpdate() { - this.mustUpdate = true; - } - - /**+ - * Changes task random possibility for execution - */ - public void setExecutionChance(int newchance) { - this.executionChance = newchance; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest.java b/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest.java index 3512c111..601866c4 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,8 +53,25 @@ public class EntityAIWatchClosest extends EntityAIBase { this.setMutexBits(2); } - /**+ - * Returns whether the EntityAIBase should begin execution. + /** + * + Returns whether an in-progress EntityAIBase should continue executing + */ + public boolean continueExecuting() { + return !this.closestEntity.isEntityAlive() ? false + : (this.theWatcher.getDistanceSqToEntity( + this.closestEntity) > (double) (this.maxDistanceForPlayer * this.maxDistanceForPlayer) ? false + : this.lookTime > 0); + } + + /** + * + Resets the task + */ + public void resetTask() { + this.closestEntity = null; + } + + /** + * + Returns whether the EntityAIBase should begin execution. */ public boolean shouldExecute() { if (this.theWatcher.getRNG().nextFloat() >= this.chance) { @@ -75,33 +95,15 @@ public class EntityAIWatchClosest extends EntityAIBase { } } - /**+ - * Returns whether an in-progress EntityAIBase should continue - * executing - */ - public boolean continueExecuting() { - return !this.closestEntity.isEntityAlive() ? false - : (this.theWatcher.getDistanceSqToEntity( - this.closestEntity) > (double) (this.maxDistanceForPlayer * this.maxDistanceForPlayer) ? false - : this.lookTime > 0); - } - - /**+ - * Execute a one shot task or start executing a continuous task + /** + * + Execute a one shot task or start executing a continuous task */ public void startExecuting() { this.lookTime = 40 + this.theWatcher.getRNG().nextInt(40); } - /**+ - * Resets the task - */ - public void resetTask() { - this.closestEntity = null; - } - - /**+ - * Updates the task + /** + * + Updates the task */ public void updateTask() { this.theWatcher.getLookHelper().setLookPosition(this.closestEntity.posX, diff --git a/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest2.java b/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest2.java index df35b8f9..54c06fd4 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest2.java +++ b/src/game/java/net/minecraft/entity/ai/EntityAIWatchClosest2.java @@ -3,22 +3,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/ai/EntityJumpHelper.java b/src/game/java/net/minecraft/entity/ai/EntityJumpHelper.java index f6d76742..5b690129 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityJumpHelper.java +++ b/src/game/java/net/minecraft/entity/ai/EntityJumpHelper.java @@ -2,22 +2,25 @@ package net.minecraft.entity.ai; import net.minecraft.entity.EntityLiving; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,15 +33,15 @@ public class EntityJumpHelper { this.entity = entityIn; } - public void setJumping() { - this.isJumping = true; - } - - /**+ - * Called to actually make the entity jump if isJumping is true. + /** + * + Called to actually make the entity jump if isJumping is true. */ public void doJump() { this.entity.setJumping(this.isJumping); this.isJumping = false; } + + public void setJumping() { + this.isJumping = true; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityLookHelper.java b/src/game/java/net/minecraft/entity/ai/EntityLookHelper.java index 710fda03..3dfb4356 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityLookHelper.java +++ b/src/game/java/net/minecraft/entity/ai/EntityLookHelper.java @@ -5,22 +5,25 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,37 +41,24 @@ public class EntityLookHelper { this.entity = entitylivingIn; } - /**+ - * Sets position to look at using entity - */ - public void setLookPositionWithEntity(Entity entityIn, float deltaYaw, float deltaPitch) { - this.posX = entityIn.posX; - if (entityIn instanceof EntityLivingBase) { - this.posY = entityIn.posY + (double) entityIn.getEyeHeight(); - } else { - this.posY = (entityIn.getEntityBoundingBox().minY + entityIn.getEntityBoundingBox().maxY) / 2.0D; - } - - this.posZ = entityIn.posZ; - this.deltaLookYaw = deltaYaw; - this.deltaLookPitch = deltaPitch; - this.isLooking = true; + public boolean getIsLooking() { + return this.isLooking; } - /**+ - * Sets position to look at - */ - public void setLookPosition(double x, double y, double z, float deltaYaw, float deltaPitch) { - this.posX = x; - this.posY = y; - this.posZ = z; - this.deltaLookYaw = deltaYaw; - this.deltaLookPitch = deltaPitch; - this.isLooking = true; + public double getLookPosX() { + return this.posX; } - /**+ - * Updates look + public double getLookPosY() { + return this.posY; + } + + public double getLookPosZ() { + return this.posZ; + } + + /** + * + Updates look */ public void onUpdateLook() { this.entity.rotationPitch = 0.0F; @@ -100,6 +90,35 @@ public class EntityLookHelper { } + /** + * + Sets position to look at + */ + public void setLookPosition(double x, double y, double z, float deltaYaw, float deltaPitch) { + this.posX = x; + this.posY = y; + this.posZ = z; + this.deltaLookYaw = deltaYaw; + this.deltaLookPitch = deltaPitch; + this.isLooking = true; + } + + /** + * + Sets position to look at using entity + */ + public void setLookPositionWithEntity(Entity entityIn, float deltaYaw, float deltaPitch) { + this.posX = entityIn.posX; + if (entityIn instanceof EntityLivingBase) { + this.posY = entityIn.posY + (double) entityIn.getEyeHeight(); + } else { + this.posY = (entityIn.getEntityBoundingBox().minY + entityIn.getEntityBoundingBox().maxY) / 2.0D; + } + + this.posZ = entityIn.posZ; + this.deltaLookYaw = deltaYaw; + this.deltaLookPitch = deltaPitch; + this.isLooking = true; + } + private float updateRotation(float parFloat1, float parFloat2, float parFloat3) { float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); if (f > parFloat3) { @@ -112,20 +131,4 @@ public class EntityLookHelper { return parFloat1 + f; } - - public boolean getIsLooking() { - return this.isLooking; - } - - public double getLookPosX() { - return this.posX; - } - - public double getLookPosY() { - return this.posY; - } - - public double getLookPosZ() { - return this.posZ; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityMinecartMobSpawner.java b/src/game/java/net/minecraft/entity/ai/EntityMinecartMobSpawner.java index e6a5ec03..25dabdd5 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityMinecartMobSpawner.java +++ b/src/game/java/net/minecraft/entity/ai/EntityMinecartMobSpawner.java @@ -8,42 +8,45 @@ import net.minecraft.tileentity.MobSpawnerBaseLogic; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityMinecartMobSpawner extends EntityMinecart { - /**+ - * Mob spawner logic for this spawner minecart. + /** + * + Mob spawner logic for this spawner minecart. */ private final MobSpawnerBaseLogic mobSpawnerLogic = new MobSpawnerBaseLogic() { public void func_98267_a(int i) { EntityMinecartMobSpawner.this.worldObj.setEntityState(EntityMinecartMobSpawner.this, (byte) i); } - public World getSpawnerWorld() { - return EntityMinecartMobSpawner.this.worldObj; - } - public BlockPos getSpawnerPosition() { return new BlockPos(EntityMinecartMobSpawner.this); } + + public World getSpawnerWorld() { + return EntityMinecartMobSpawner.this.worldObj; + } }; public EntityMinecartMobSpawner(World worldIn) { @@ -54,45 +57,43 @@ public class EntityMinecartMobSpawner extends EntityMinecart { super(worldIn, parDouble1, parDouble2, parDouble3); } - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.SPAWNER; + public MobSpawnerBaseLogic func_98039_d() { + return this.mobSpawnerLogic; } public IBlockState getDefaultDisplayTile() { return Blocks.mob_spawner.getDefaultState(); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.mobSpawnerLogic.readFromNBT(nbttagcompound); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - this.mobSpawnerLogic.writeToNBT(nbttagcompound); + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.SPAWNER; } public void handleStatusUpdate(byte b0) { this.mobSpawnerLogic.setDelayToMin(b0); } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); this.mobSpawnerLogic.updateSpawner(); } - public MobSpawnerBaseLogic func_98039_d() { - return this.mobSpawnerLogic; + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.mobSpawnerLogic.readFromNBT(nbttagcompound); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + this.mobSpawnerLogic.writeToNBT(nbttagcompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntityMoveHelper.java b/src/game/java/net/minecraft/entity/ai/EntityMoveHelper.java index e6c1977d..740c3be9 100644 --- a/src/game/java/net/minecraft/entity/ai/EntityMoveHelper.java +++ b/src/game/java/net/minecraft/entity/ai/EntityMoveHelper.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,23 +42,47 @@ public class EntityMoveHelper { this.posZ = entitylivingIn.posZ; } - public boolean isUpdating() { - return this.update; - } - public double getSpeed() { return this.speed; } - /**+ - * Sets the speed and location to move to + public double getX() { + return this.posX; + } + + public double getY() { + return this.posY; + } + + public double getZ() { + return this.posZ; + } + + public boolean isUpdating() { + return this.update; + } + + /** + * + Limits the given angle to a upper and lower limit. */ - public void setMoveTo(double x, double y, double z, double speedIn) { - this.posX = x; - this.posY = y; - this.posZ = z; - this.speed = speedIn; - this.update = true; + protected float limitAngle(float parFloat1, float parFloat2, float parFloat3) { + float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); + if (f > parFloat3) { + f = parFloat3; + } + + if (f < -parFloat3) { + f = -parFloat3; + } + + float f1 = parFloat1 + f; + if (f1 < 0.0F) { + f1 += 360.0F; + } else if (f1 > 360.0F) { + f1 -= 360.0F; + } + + return f1; } public void onUpdateMoveHelper() { @@ -80,38 +107,14 @@ public class EntityMoveHelper { } } - /**+ - * Limits the given angle to a upper and lower limit. + /** + * + Sets the speed and location to move to */ - protected float limitAngle(float parFloat1, float parFloat2, float parFloat3) { - float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); - if (f > parFloat3) { - f = parFloat3; - } - - if (f < -parFloat3) { - f = -parFloat3; - } - - float f1 = parFloat1 + f; - if (f1 < 0.0F) { - f1 += 360.0F; - } else if (f1 > 360.0F) { - f1 -= 360.0F; - } - - return f1; - } - - public double getX() { - return this.posX; - } - - public double getY() { - return this.posY; - } - - public double getZ() { - return this.posZ; + public void setMoveTo(double x, double y, double z, double speedIn) { + this.posX = x; + this.posY = y; + this.posZ = z; + this.speed = speedIn; + this.update = true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/EntitySenses.java b/src/game/java/net/minecraft/entity/ai/EntitySenses.java index 6a1cd10a..0d17bc1b 100644 --- a/src/game/java/net/minecraft/entity/ai/EntitySenses.java +++ b/src/game/java/net/minecraft/entity/ai/EntitySenses.java @@ -1,26 +1,31 @@ package net.minecraft.entity.ai; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,17 +39,9 @@ public class EntitySenses { this.entityObj = entityObjIn; } - /**+ - * Clears canSeeCachePositive and canSeeCacheNegative. - */ - public void clearSensingCache() { - this.seenEntities.clear(); - this.unseenEntities.clear(); - } - - /**+ - * Checks, whether 'our' entity can see the entity given as - * argument (true) or not (false), caching the result. + /** + * + Checks, whether 'our' entity can see the entity given as argument (true) or + * not (false), caching the result. */ public boolean canSee(Entity entityIn) { if (this.seenEntities.contains(entityIn)) { @@ -62,4 +59,12 @@ public class EntitySenses { return flag; } } + + /** + * + Clears canSeeCachePositive and canSeeCacheNegative. + */ + public void clearSensingCache() { + this.seenEntities.clear(); + this.unseenEntities.clear(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/RandomPositionGenerator.java b/src/game/java/net/minecraft/entity/ai/RandomPositionGenerator.java index aaac5584..6ece1ac8 100644 --- a/src/game/java/net/minecraft/entity/ai/RandomPositionGenerator.java +++ b/src/game/java/net/minecraft/entity/ai/RandomPositionGenerator.java @@ -6,83 +6,53 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RandomPositionGenerator { - /**+ - * used to store a driection when the user passes a point to - * move towards or away from. WARNING: NEVER THREAD SAFE. - * MULTIPLE findTowards and findAway calls, will share this var + /** + * + used to store a driection when the user passes a point to move towards or + * away from. WARNING: NEVER THREAD SAFE. MULTIPLE findTowards and findAway + * calls, will share this var */ private static Vec3 staticVector = new Vec3(0.0D, 0.0D, 0.0D); - /**+ - * finds a random target within par1(x,z) and par2 (y) blocks + /** + * + finds a random target within par1(x,z) and par2 (y) blocks */ public static Vec3 findRandomTarget(EntityCreature entitycreatureIn, int xz, int y) { - /**+ - * searches 10 blocks at random in a within par1(x,z) and par2 - * (y) distance, ignores those not in the direction of par3Vec3, - * then points to the tile for which creature.getBlockPathWeight - * returns the highest number + /** + * + searches 10 blocks at random in a within par1(x,z) and par2 (y) distance, + * ignores those not in the direction of par3Vec3, then points to the tile for + * which creature.getBlockPathWeight returns the highest number */ return findRandomTargetBlock(entitycreatureIn, xz, y, (Vec3) null); } - /**+ - * finds a random target within par1(x,z) and par2 (y) blocks in - * the direction of the point par3 - */ - public static Vec3 findRandomTargetBlockTowards(EntityCreature entitycreatureIn, int xz, int y, Vec3 targetVec3) { - staticVector = targetVec3.subtract(entitycreatureIn.posX, entitycreatureIn.posY, entitycreatureIn.posZ); - /**+ - * searches 10 blocks at random in a within par1(x,z) and par2 - * (y) distance, ignores those not in the direction of par3Vec3, - * then points to the tile for which creature.getBlockPathWeight - * returns the highest number - */ - return findRandomTargetBlock(entitycreatureIn, xz, y, staticVector); - } - - /**+ - * finds a random target within par1(x,z) and par2 (y) blocks in - * the reverse direction of the point par3 - */ - public static Vec3 findRandomTargetBlockAwayFrom(EntityCreature entitycreatureIn, int xz, int y, Vec3 targetVec3) { - staticVector = (new Vec3(entitycreatureIn.posX, entitycreatureIn.posY, entitycreatureIn.posZ)) - .subtract(targetVec3); - /**+ - * searches 10 blocks at random in a within par1(x,z) and par2 - * (y) distance, ignores those not in the direction of par3Vec3, - * then points to the tile for which creature.getBlockPathWeight - * returns the highest number - */ - return findRandomTargetBlock(entitycreatureIn, xz, y, staticVector); - } - - /**+ - * searches 10 blocks at random in a within par1(x,z) and par2 - * (y) distance, ignores those not in the direction of par3Vec3, - * then points to the tile for which creature.getBlockPathWeight - * returns the highest number + /** + * + searches 10 blocks at random in a within par1(x,z) and par2 (y) distance, + * ignores those not in the direction of par3Vec3, then points to the tile for + * which creature.getBlockPathWeight returns the highest number */ private static Vec3 findRandomTargetBlock(EntityCreature entitycreatureIn, int xz, int y, Vec3 targetVec3) { EaglercraftRandom random = entitycreatureIn.getRNG(); @@ -146,4 +116,33 @@ public class RandomPositionGenerator { return null; } } + + /** + * + finds a random target within par1(x,z) and par2 (y) blocks in the reverse + * direction of the point par3 + */ + public static Vec3 findRandomTargetBlockAwayFrom(EntityCreature entitycreatureIn, int xz, int y, Vec3 targetVec3) { + staticVector = (new Vec3(entitycreatureIn.posX, entitycreatureIn.posY, entitycreatureIn.posZ)) + .subtract(targetVec3); + /** + * + searches 10 blocks at random in a within par1(x,z) and par2 (y) distance, + * ignores those not in the direction of par3Vec3, then points to the tile for + * which creature.getBlockPathWeight returns the highest number + */ + return findRandomTargetBlock(entitycreatureIn, xz, y, staticVector); + } + + /** + * + finds a random target within par1(x,z) and par2 (y) blocks in the direction + * of the point par3 + */ + public static Vec3 findRandomTargetBlockTowards(EntityCreature entitycreatureIn, int xz, int y, Vec3 targetVec3) { + staticVector = targetVec3.subtract(entitycreatureIn.posX, entitycreatureIn.posY, entitycreatureIn.posZ); + /** + * + searches 10 blocks at random in a within par1(x,z) and par2 (y) distance, + * ignores those not in the direction of par3Vec3, then points to the tile for + * which creature.getBlockPathWeight returns the highest number + */ + return findRandomTargetBlock(entitycreatureIn, xz, y, staticVector); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/AttributeModifier.java b/src/game/java/net/minecraft/entity/ai/attributes/AttributeModifier.java index 95f6a8ff..92f19038 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/AttributeModifier.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/AttributeModifier.java @@ -1,28 +1,30 @@ package net.minecraft.entity.ai.attributes; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import org.apache.commons.lang3.Validate; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.ThreadLocalRandom; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,10 +36,6 @@ public class AttributeModifier { private final EaglercraftUUID id; private boolean isSaved; - public AttributeModifier(String nameIn, double amountIn, int operationIn) { - this(MathHelper.getRandomUuid(ThreadLocalRandom.current()), nameIn, amountIn, operationIn); - } - public AttributeModifier(EaglercraftUUID idIn, String nameIn, double amountIn, int operationIn) { this.isSaved = true; this.id = idIn; @@ -48,35 +46,8 @@ public class AttributeModifier { Validate.inclusiveBetween(0L, 2L, (long) operationIn, "Invalid operation"); } - public EaglercraftUUID getID() { - return this.id; - } - - public String getName() { - return this.name; - } - - public int getOperation() { - return this.operation; - } - - public double getAmount() { - return this.amount; - } - - /**+ - * @see #isSaved - */ - public boolean isSaved() { - return this.isSaved; - } - - /**+ - * @see #isSaved - */ - public AttributeModifier setSaved(boolean saved) { - this.isSaved = saved; - return this; + public AttributeModifier(String nameIn, double amountIn, int operationIn) { + this(MathHelper.getRandomUuid(ThreadLocalRandom.current()), nameIn, amountIn, operationIn); } public boolean equals(Object object) { @@ -98,10 +69,45 @@ public class AttributeModifier { } } + public double getAmount() { + return this.amount; + } + + public EaglercraftUUID getID() { + return this.id; + } + + public String getName() { + return this.name; + } + + public int getOperation() { + return this.operation; + } + public int hashCode() { return this.id != null ? this.id.hashCode() : 0; } + /** + * + + * + * @see #isSaved + */ + public boolean isSaved() { + return this.isSaved; + } + + /** + * + + * + * @see #isSaved + */ + public AttributeModifier setSaved(boolean saved) { + this.isSaved = saved; + return this; + } + public String toString() { return "AttributeModifier{amount=" + this.amount + ", operation=" + this.operation + ", name=\'" + this.name + '\'' + ", id=" + this.id + ", serialize=" + this.isSaved + '}'; diff --git a/src/game/java/net/minecraft/entity/ai/attributes/BaseAttribute.java b/src/game/java/net/minecraft/entity/ai/attributes/BaseAttribute.java index 525b8c04..128a826f 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/BaseAttribute.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/BaseAttribute.java @@ -1,21 +1,24 @@ package net.minecraft.entity.ai.attributes; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +38,15 @@ public abstract class BaseAttribute implements IAttribute { } } + public boolean equals(Object object) { + return object instanceof IAttribute + && this.unlocalizedName.equals(((IAttribute) object).getAttributeUnlocalizedName()); + } + + public IAttribute func_180372_d() { + return this.field_180373_a; + } + public String getAttributeUnlocalizedName() { return this.unlocalizedName; } @@ -47,21 +59,12 @@ public abstract class BaseAttribute implements IAttribute { return this.shouldWatch; } - public BaseAttribute setShouldWatch(boolean shouldWatchIn) { - this.shouldWatch = shouldWatchIn; - return this; - } - - public IAttribute func_180372_d() { - return this.field_180373_a; - } - public int hashCode() { return this.unlocalizedName.hashCode(); } - public boolean equals(Object object) { - return object instanceof IAttribute - && this.unlocalizedName.equals(((IAttribute) object).getAttributeUnlocalizedName()); + public BaseAttribute setShouldWatch(boolean shouldWatchIn) { + this.shouldWatch = shouldWatchIn; + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/BaseAttributeMap.java b/src/game/java/net/minecraft/entity/ai/attributes/BaseAttributeMap.java index 4661b20b..0ced1660 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/BaseAttributeMap.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/BaseAttributeMap.java @@ -10,22 +10,25 @@ import com.google.common.collect.Multimap; import net.minecraft.server.management.LowerStringMap; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +38,26 @@ public abstract class BaseAttributeMap { protected final Map attributesByName = new LowerStringMap(); protected final Multimap field_180377_c = HashMultimap.create(); + public void applyAttributeModifiers(Multimap parMultimap) { + for (Entry entry : parMultimap.entries()) { + IAttributeInstance iattributeinstance = this.getAttributeInstanceByName((String) entry.getKey()); + if (iattributeinstance != null) { + iattributeinstance.removeModifier((AttributeModifier) entry.getValue()); + iattributeinstance.applyModifier((AttributeModifier) entry.getValue()); + } + } + + } + + protected abstract IAttributeInstance func_180376_c(IAttribute var1); + + public void func_180794_a(IAttributeInstance parIAttributeInstance) { + } + + public Collection getAllAttributes() { + return this.attributesByName.values(); + } + public IAttributeInstance getAttributeInstance(IAttribute attribute) { return (IAttributeInstance) this.attributes.get(attribute); } @@ -43,9 +66,9 @@ public abstract class BaseAttributeMap { return (IAttributeInstance) this.attributesByName.get(attributeName); } - /**+ - * Registers an attribute with this AttributeMap, returns a - * modifiable AttributeInstance associated with this map + /** + * + Registers an attribute with this AttributeMap, returns a modifiable + * AttributeInstance associated with this map */ public IAttributeInstance registerAttribute(IAttribute attribute) { if (this.attributesByName.containsKey(attribute.getAttributeUnlocalizedName())) { @@ -64,15 +87,6 @@ public abstract class BaseAttributeMap { } } - protected abstract IAttributeInstance func_180376_c(IAttribute var1); - - public Collection getAllAttributes() { - return this.attributesByName.values(); - } - - public void func_180794_a(IAttributeInstance parIAttributeInstance) { - } - public void removeAttributeModifiers(Multimap parMultimap) { for (Entry entry : parMultimap.entries()) { IAttributeInstance iattributeinstance = this.getAttributeInstanceByName((String) entry.getKey()); @@ -82,15 +96,4 @@ public abstract class BaseAttributeMap { } } - - public void applyAttributeModifiers(Multimap parMultimap) { - for (Entry entry : parMultimap.entries()) { - IAttributeInstance iattributeinstance = this.getAttributeInstanceByName((String) entry.getKey()); - if (iattributeinstance != null) { - iattributeinstance.removeModifier((AttributeModifier) entry.getValue()); - iattributeinstance.applyModifier((AttributeModifier) entry.getValue()); - } - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/IAttribute.java b/src/game/java/net/minecraft/entity/ai/attributes/IAttribute.java index 02356041..34614004 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/IAttribute.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/IAttribute.java @@ -1,33 +1,36 @@ package net.minecraft.entity.ai.attributes; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IAttribute { - String getAttributeUnlocalizedName(); - double clampValue(double var1); + IAttribute func_180372_d(); + + String getAttributeUnlocalizedName(); + double getDefaultValue(); boolean getShouldWatch(); - - IAttribute func_180372_d(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/IAttributeInstance.java b/src/game/java/net/minecraft/entity/ai/attributes/IAttributeInstance.java index 605f06e8..de22093e 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/IAttributeInstance.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/IAttributeInstance.java @@ -1,54 +1,58 @@ package net.minecraft.entity.ai.attributes; import java.util.Collection; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IAttributeInstance { - /**+ - * Get the Attribute this is an instance of - */ - IAttribute getAttribute(); - - double getBaseValue(); - - void setBaseValue(double var1); - - Collection getModifiersByOperation(int var1); + void applyModifier(AttributeModifier var1); Collection func_111122_c(); - boolean hasModifier(AttributeModifier var1); + /** + * + Get the Attribute this is an instance of + */ + IAttribute getAttribute(); - /**+ - * Returns attribute modifier, if any, by the given UUID + double getAttributeValue(); + + double getBaseValue(); + + /** + * + Returns attribute modifier, if any, by the given UUID */ AttributeModifier getModifier(EaglercraftUUID var1); - void applyModifier(AttributeModifier var1); + Collection getModifiersByOperation(int var1); - void removeModifier(AttributeModifier var1); + boolean hasModifier(AttributeModifier var1); void removeAllModifiers(); - double getAttributeValue(); + void removeModifier(AttributeModifier var1); + + void setBaseValue(double var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/ModifiableAttributeInstance.java b/src/game/java/net/minecraft/entity/ai/attributes/ModifiableAttributeInstance.java index 85a02b66..42d787fc 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/ModifiableAttributeInstance.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/ModifiableAttributeInstance.java @@ -5,28 +5,32 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,49 +56,6 @@ public class ModifiableAttributeInstance implements IAttributeInstance { } - /**+ - * Get the Attribute this is an instance of - */ - public IAttribute getAttribute() { - return this.genericAttribute; - } - - public double getBaseValue() { - return this.baseValue; - } - - public void setBaseValue(double d0) { - if (d0 != this.getBaseValue()) { - this.baseValue = d0; - this.flagForUpdate(); - } - } - - public Collection getModifiersByOperation(int i) { - return (Collection) this.mapByOperation.get(Integer.valueOf(i)); - } - - public Collection func_111122_c() { - HashSet hashset = Sets.newHashSet(); - - for (int i = 0; i < 3; ++i) { - hashset.addAll(this.getModifiersByOperation(i)); - } - - return hashset; - } - - /**+ - * Returns attribute modifier, if any, by the given UUID - */ - public AttributeModifier getModifier(EaglercraftUUID uuid) { - return (AttributeModifier) this.mapByUUID.get(uuid); - } - - public boolean hasModifier(AttributeModifier attributemodifier) { - return this.mapByUUID.get(attributemodifier.getID()) != null; - } - public void applyModifier(AttributeModifier attributemodifier) { if (this.getModifier(attributemodifier.getID()) != null) { throw new IllegalArgumentException("Modifier is already applied on this attribute!"); @@ -112,48 +73,6 @@ public class ModifiableAttributeInstance implements IAttributeInstance { } } - protected void flagForUpdate() { - this.needsUpdate = true; - this.attributeMap.func_180794_a(this); - } - - public void removeModifier(AttributeModifier attributemodifier) { - for (int i = 0; i < 3; ++i) { - Set set = (Set) this.mapByOperation.get(Integer.valueOf(i)); - set.remove(attributemodifier); - } - - Set set1 = (Set) this.mapByName.get(attributemodifier.getName()); - if (set1 != null) { - set1.remove(attributemodifier); - if (set1.isEmpty()) { - this.mapByName.remove(attributemodifier.getName()); - } - } - - this.mapByUUID.remove(attributemodifier.getID()); - this.flagForUpdate(); - } - - public void removeAllModifiers() { - Collection collection = this.func_111122_c(); - if (collection != null) { - for (AttributeModifier attributemodifier : (List) Lists.newArrayList(collection)) { - this.removeModifier(attributemodifier); - } - - } - } - - public double getAttributeValue() { - if (this.needsUpdate) { - this.cachedValue = this.computeValue(); - this.needsUpdate = false; - } - - return this.cachedValue; - } - private double computeValue() { double d0 = this.getBaseValue(); @@ -174,6 +93,21 @@ public class ModifiableAttributeInstance implements IAttributeInstance { return this.genericAttribute.clampValue(d1); } + protected void flagForUpdate() { + this.needsUpdate = true; + this.attributeMap.func_180794_a(this); + } + + public Collection func_111122_c() { + HashSet hashset = Sets.newHashSet(); + + for (int i = 0; i < 3; ++i) { + hashset.addAll(this.getModifiersByOperation(i)); + } + + return hashset; + } + private Collection func_180375_b(int parInt1) { HashSet hashset = Sets.newHashSet(this.getModifiersByOperation(parInt1)); @@ -187,4 +121,74 @@ public class ModifiableAttributeInstance implements IAttributeInstance { return hashset; } + + /** + * + Get the Attribute this is an instance of + */ + public IAttribute getAttribute() { + return this.genericAttribute; + } + + public double getAttributeValue() { + if (this.needsUpdate) { + this.cachedValue = this.computeValue(); + this.needsUpdate = false; + } + + return this.cachedValue; + } + + public double getBaseValue() { + return this.baseValue; + } + + /** + * + Returns attribute modifier, if any, by the given UUID + */ + public AttributeModifier getModifier(EaglercraftUUID uuid) { + return (AttributeModifier) this.mapByUUID.get(uuid); + } + + public Collection getModifiersByOperation(int i) { + return (Collection) this.mapByOperation.get(Integer.valueOf(i)); + } + + public boolean hasModifier(AttributeModifier attributemodifier) { + return this.mapByUUID.get(attributemodifier.getID()) != null; + } + + public void removeAllModifiers() { + Collection collection = this.func_111122_c(); + if (collection != null) { + for (AttributeModifier attributemodifier : (List) Lists.newArrayList(collection)) { + this.removeModifier(attributemodifier); + } + + } + } + + public void removeModifier(AttributeModifier attributemodifier) { + for (int i = 0; i < 3; ++i) { + Set set = (Set) this.mapByOperation.get(Integer.valueOf(i)); + set.remove(attributemodifier); + } + + Set set1 = (Set) this.mapByName.get(attributemodifier.getName()); + if (set1 != null) { + set1.remove(attributemodifier); + if (set1.isEmpty()) { + this.mapByName.remove(attributemodifier.getName()); + } + } + + this.mapByUUID.remove(attributemodifier.getID()); + this.flagForUpdate(); + } + + public void setBaseValue(double d0) { + if (d0 != this.getBaseValue()) { + this.baseValue = d0; + this.flagForUpdate(); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/RangedAttribute.java b/src/game/java/net/minecraft/entity/ai/attributes/RangedAttribute.java index 39820370..ea34b569 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/RangedAttribute.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/RangedAttribute.java @@ -2,22 +2,25 @@ package net.minecraft.entity.ai.attributes; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,17 +44,17 @@ public class RangedAttribute extends BaseAttribute { } } - public RangedAttribute setDescription(String descriptionIn) { - this.description = descriptionIn; - return this; + public double clampValue(double d0) { + d0 = MathHelper.clamp_double(d0, this.minimumValue, this.maximumValue); + return d0; } public String getDescription() { return this.description; } - public double clampValue(double d0) { - d0 = MathHelper.clamp_double(d0, this.minimumValue, this.maximumValue); - return d0; + public RangedAttribute setDescription(String descriptionIn) { + this.description = descriptionIn; + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/ai/attributes/ServersideAttributeMap.java b/src/game/java/net/minecraft/entity/ai/attributes/ServersideAttributeMap.java index 4e8e0b3f..c0192bbc 100644 --- a/src/game/java/net/minecraft/entity/ai/attributes/ServersideAttributeMap.java +++ b/src/game/java/net/minecraft/entity/ai/attributes/ServersideAttributeMap.java @@ -1,28 +1,33 @@ package net.minecraft.entity.ai.attributes; -import com.google.common.collect.Sets; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; + +import com.google.common.collect.Sets; + import net.minecraft.server.management.LowerStringMap; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,33 +36,6 @@ public class ServersideAttributeMap extends BaseAttributeMap { private final Set attributeInstanceSet = Sets.newHashSet(); protected final Map descriptionToAttributeInstanceMap = new LowerStringMap(); - public ModifiableAttributeInstance getAttributeInstance(IAttribute iattribute) { - return (ModifiableAttributeInstance) super.getAttributeInstance(iattribute); - } - - public ModifiableAttributeInstance getAttributeInstanceByName(String s) { - IAttributeInstance iattributeinstance = super.getAttributeInstanceByName(s); - if (iattributeinstance == null) { - iattributeinstance = (IAttributeInstance) this.descriptionToAttributeInstanceMap.get(s); - } - - return (ModifiableAttributeInstance) iattributeinstance; - } - - /**+ - * Registers an attribute with this AttributeMap, returns a - * modifiable AttributeInstance associated with this map - */ - public IAttributeInstance registerAttribute(IAttribute iattribute) { - IAttributeInstance iattributeinstance = super.registerAttribute(iattribute); - if (iattribute instanceof RangedAttribute && ((RangedAttribute) iattribute).getDescription() != null) { - this.descriptionToAttributeInstanceMap.put(((RangedAttribute) iattribute).getDescription(), - iattributeinstance); - } - - return iattributeinstance; - } - protected IAttributeInstance func_180376_c(IAttribute iattribute) { return new ModifiableAttributeInstance(this, iattribute); } @@ -76,6 +54,19 @@ public class ServersideAttributeMap extends BaseAttributeMap { } + public ModifiableAttributeInstance getAttributeInstance(IAttribute iattribute) { + return (ModifiableAttributeInstance) super.getAttributeInstance(iattribute); + } + + public ModifiableAttributeInstance getAttributeInstanceByName(String s) { + IAttributeInstance iattributeinstance = super.getAttributeInstanceByName(s); + if (iattributeinstance == null) { + iattributeinstance = (IAttributeInstance) this.descriptionToAttributeInstanceMap.get(s); + } + + return (ModifiableAttributeInstance) iattributeinstance; + } + public Set getAttributeInstanceSet() { return this.attributeInstanceSet; } @@ -91,4 +82,18 @@ public class ServersideAttributeMap extends BaseAttributeMap { return hashset; } + + /** + * + Registers an attribute with this AttributeMap, returns a modifiable + * AttributeInstance associated with this map + */ + public IAttributeInstance registerAttribute(IAttribute iattribute) { + IAttributeInstance iattributeinstance = super.registerAttribute(iattribute); + if (iattribute instanceof RangedAttribute && ((RangedAttribute) iattribute).getDescription() != null) { + this.descriptionToAttributeInstanceMap.put(((RangedAttribute) iattribute).getDescription(), + iattributeinstance); + } + + return iattributeinstance; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/boss/BossStatus.java b/src/game/java/net/minecraft/entity/boss/BossStatus.java index ae59218b..75f0cb75 100644 --- a/src/game/java/net/minecraft/entity/boss/BossStatus.java +++ b/src/game/java/net/minecraft/entity/boss/BossStatus.java @@ -1,21 +1,24 @@ package net.minecraft.entity.boss; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/boss/EntityDragon.java b/src/game/java/net/minecraft/entity/boss/EntityDragon.java index 8f4b0c00..fa8b43cc 100644 --- a/src/game/java/net/minecraft/entity/boss/EntityDragon.java +++ b/src/game/java/net/minecraft/entity/boss/EntityDragon.java @@ -1,9 +1,11 @@ package net.minecraft.entity.boss; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Iterator; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.BlockTorch; import net.minecraft.block.material.Material; @@ -28,22 +30,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.Explosion; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,14 +57,14 @@ public class EntityDragon extends EntityLiving implements IBossDisplayData, IEnt public double targetX; public double targetY; public double targetZ; - /**+ - * Ring buffer array for the last 64 Y-positions and yaw - * rotations. Used to calculate offsets for the animations. + /** + * + Ring buffer array for the last 64 Y-positions and yaw rotations. Used to + * calculate offsets for the animations. */ public double[][] ringBuffer = new double[64][3]; - /**+ - * Index into the ring buffer. Incremented once per tick and - * restarts at 0 once it reaches the end of the buffer. + /** + * + Index into the ring buffer. Incremented once per tick and restarts at 0 + * once it reaches the end of the buffer. */ public int ringBufferIndex = -1; public EntityDragonPart[] dragonPartArray; @@ -101,15 +106,205 @@ public class EntityDragon extends EntityLiving implements IBossDisplayData, IEnt this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(200.0D); } + /** + * + Provides a way to cause damage to an ender dragon. + */ + protected boolean attackDragonFrom(DamageSource source, float amount) { + return super.attackEntityFrom(source, amount); + } + + /** + * + Attacks all entities inside this list, dealing 5 hearts of damage. + */ + private void attackEntitiesInList(List parList) { + for (int i = 0, l = parList.size(); i < l; ++i) { + Entity entity = (Entity) parList.get(i); + if (entity instanceof EntityLivingBase) { + entity.attackEntityFrom(DamageSource.causeMobDamage(this), 10.0F); + this.applyEnchantments(this, entity); + } + } + + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (damagesource instanceof EntityDamageSource && ((EntityDamageSource) damagesource).getIsThornsDamage()) { + this.attackDragonFrom(damagesource, f); + } + + return false; + } + + public boolean attackEntityFromPart(EntityDragonPart entitydragonpart, DamageSource damagesource, float f) { + if (entitydragonpart != this.dragonPartHead) { + f = f / 4.0F + 1.0F; + } + + float f1 = this.rotationYaw * 3.1415927F / 180.0F; + float f2 = MathHelper.sin(f1); + float f3 = MathHelper.cos(f1); + this.targetX = this.posX + (double) (f2 * 5.0F) + (double) ((this.rand.nextFloat() - 0.5F) * 2.0F); + this.targetY = this.posY + (double) (this.rand.nextFloat() * 3.0F) + 1.0D; + this.targetZ = this.posZ - (double) (f3 * 5.0F) + (double) ((this.rand.nextFloat() - 0.5F) * 2.0F); + this.target = null; + if (damagesource.getEntity() instanceof EntityPlayer || damagesource.isExplosion()) { + this.attackDragonFrom(damagesource, f); + } + + return true; + } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return false; + } + + /** + * + Pushes all entities inside the list away from the enderdragon. + */ + private void collideWithEntities(List parList) { + double d0 = (this.dragonPartBody.getEntityBoundingBox().minX + this.dragonPartBody.getEntityBoundingBox().maxX) + / 2.0D; + double d1 = (this.dragonPartBody.getEntityBoundingBox().minZ + this.dragonPartBody.getEntityBoundingBox().maxZ) + / 2.0D; + + for (int i = 0, l = parList.size(); i < l; ++i) { + Entity entity = parList.get(i); + if (entity instanceof EntityLivingBase) { + double d2 = entity.posX - d0; + double d3 = entity.posZ - d1; + double d4 = d2 * d2 + d3 * d3; + entity.addVelocity(d2 / d4 * 4.0D, 0.20000000298023224D, d3 / d4 * 4.0D); + } + } + + } + + /** + * + Makes the entity despawn if requirements are reached + */ + protected void despawnEntity() { + } + + /** + * + Destroys all blocks that aren't associated with 'The End' inside the given + * bounding box. + */ + private boolean destroyBlocksInAABB(AxisAlignedBB parAxisAlignedBB) { + int i = MathHelper.floor_double(parAxisAlignedBB.minX); + int j = MathHelper.floor_double(parAxisAlignedBB.minY); + int k = MathHelper.floor_double(parAxisAlignedBB.minZ); + int l = MathHelper.floor_double(parAxisAlignedBB.maxX); + int i1 = MathHelper.floor_double(parAxisAlignedBB.maxY); + int j1 = MathHelper.floor_double(parAxisAlignedBB.maxZ); + boolean flag = false; + boolean flag1 = false; + + for (int k1 = i; k1 <= l; ++k1) { + for (int l1 = j; l1 <= i1; ++l1) { + for (int i2 = k; i2 <= j1; ++i2) { + BlockPos blockpos = new BlockPos(k1, l1, i2); + Block block = this.worldObj.getBlockState(blockpos).getBlock(); + if (block.getMaterial() != Material.air) { + if (block != Blocks.barrier && block != Blocks.obsidian && block != Blocks.end_stone + && block != Blocks.bedrock && block != Blocks.command_block + && this.worldObj.getGameRules().getBoolean("mobGriefing")) { + flag1 = this.worldObj.setBlockToAir(blockpos) || flag1; + } else { + flag = true; + } + } + } + } + } + + if (flag1) { + double d0 = parAxisAlignedBB.minX + + (parAxisAlignedBB.maxX - parAxisAlignedBB.minX) * (double) this.rand.nextFloat(); + double d1 = parAxisAlignedBB.minY + + (parAxisAlignedBB.maxY - parAxisAlignedBB.minY) * (double) this.rand.nextFloat(); + double d2 = parAxisAlignedBB.minZ + + (parAxisAlignedBB.maxZ - parAxisAlignedBB.minZ) * (double) this.rand.nextFloat(); + this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); + } + + return flag; + } + protected void entityInit() { super.entityInit(); } - /**+ - * Returns a double[3] array with movement offsets, used to - * calculate trailing tail/neck positions. [0] = yaw offset, [1] - * = y offset, [2] = unused, always 0. Parameters: buffer index - * offset, partial ticks. + /** + * + Generate the portal when the dragon dies + */ + private void generatePortal(BlockPos pos) { + boolean flag = true; + double d0 = 12.25D; + double d1 = 6.25D; + + for (int i = -1; i <= 32; ++i) { + for (int j = -4; j <= 4; ++j) { + for (int k = -4; k <= 4; ++k) { + double d2 = (double) (j * j + k * k); + if (d2 <= 12.25D) { + BlockPos blockpos = pos.add(j, i, k); + if (i < 0) { + if (d2 <= 6.25D) { + this.worldObj.setBlockState(blockpos, Blocks.bedrock.getDefaultState()); + } + } else if (i > 0) { + this.worldObj.setBlockState(blockpos, Blocks.air.getDefaultState()); + } else if (d2 > 6.25D) { + this.worldObj.setBlockState(blockpos, Blocks.bedrock.getDefaultState()); + } else { + this.worldObj.setBlockState(blockpos, Blocks.end_portal.getDefaultState()); + } + } + } + } + } + + this.worldObj.setBlockState(pos, Blocks.bedrock.getDefaultState()); + this.worldObj.setBlockState(pos.up(), Blocks.bedrock.getDefaultState()); + BlockPos blockpos1 = pos.up(2); + this.worldObj.setBlockState(blockpos1, Blocks.bedrock.getDefaultState()); + this.worldObj.setBlockState(blockpos1.west(), + Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.EAST)); + this.worldObj.setBlockState(blockpos1.east(), + Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.WEST)); + this.worldObj.setBlockState(blockpos1.north(), + Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.SOUTH)); + this.worldObj.setBlockState(blockpos1.south(), + Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.NORTH)); + this.worldObj.setBlockState(pos.up(3), Blocks.bedrock.getDefaultState()); + this.worldObj.setBlockState(pos.up(4), Blocks.dragon_egg.getDefaultState()); + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.enderdragon.hit"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.enderdragon.growl"; + } + + /** + * + Returns a double[3] array with movement offsets, used to calculate trailing + * tail/neck positions. [0] = yaw offset, [1] = y offset, [2] = unused, always + * 0. Parameters: buffer index offset, partial ticks. */ public double[] getMovementOffsets(int parInt1, float parFloat1) { if (this.getHealth() <= 0.0F) { @@ -130,10 +325,86 @@ public class EntityDragon extends EntityLiving implements IBossDisplayData, IEnt return adouble; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Return the Entity parts making up this Entity (currently only for dragons) + */ + public Entity[] getParts() { + return this.dragonPartArray; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 5.0F; + } + + public World getWorld() { + return this.worldObj; + } + + /** + * + handles entity death timer, experience orb and particle creation + */ + protected void onDeathUpdate() { + ++this.deathTicks; + if (this.deathTicks >= 180 && this.deathTicks <= 200) { + float f = (this.rand.nextFloat() - 0.5F) * 8.0F; + float f1 = (this.rand.nextFloat() - 0.5F) * 4.0F; + float f2 = (this.rand.nextFloat() - 0.5F) * 8.0F; + this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_HUGE, this.posX + (double) f, + this.posY + 2.0D + (double) f1, this.posZ + (double) f2, 0.0D, 0.0D, 0.0D, new int[0]); + } + + boolean flag = this.worldObj.getGameRules().getBoolean("doMobLoot"); + if (!this.worldObj.isRemote) { + if (this.deathTicks > 150 && this.deathTicks % 5 == 0 && flag) { + int i = 1000; + + while (i > 0) { + int k = EntityXPOrb.getXPSplit(i); + i -= k; + this.worldObj + .spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, k)); + } + } + + if (this.deathTicks == 1) { + this.worldObj.playBroadcastSound(1018, new BlockPos(this), 0); + } + } + + this.moveEntity(0.0D, 0.10000000149011612D, 0.0D); + this.renderYawOffset = this.rotationYaw += 20.0F; + if (this.deathTicks == 200 && !this.worldObj.isRemote) { + if (flag) { + int j = 2000; + + while (j > 0) { + int l = EntityXPOrb.getXPSplit(j); + j -= l; + this.worldObj + .spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, l)); + } + } + + this.generatePortal(new BlockPos(this.posX, 64.0D, this.posZ)); + this.setDead(); + } + + } + + /** + * + Called by the /kill command. + */ + public void onKillCommand() { + this.setDead(); + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (this.worldObj.isRemote) { @@ -360,84 +631,9 @@ public class EntityDragon extends EntityLiving implements IBossDisplayData, IEnt } } - /**+ - * Updates the state of the enderdragon's current endercrystal. - */ - private void updateDragonEnderCrystal() { - if (this.healingEnderCrystal != null) { - if (this.healingEnderCrystal.isDead) { - if (!this.worldObj.isRemote) { - this.attackEntityFromPart(this.dragonPartHead, DamageSource.setExplosionSource((Explosion) null), - 10.0F); - } - - this.healingEnderCrystal = null; - } else if (this.ticksExisted % 10 == 0 && this.getHealth() < this.getMaxHealth()) { - this.setHealth(this.getHealth() + 1.0F); - } - } - - if (this.rand.nextInt(10) == 0) { - float f = 32.0F; - List list = this.worldObj.getEntitiesWithinAABB(EntityEnderCrystal.class, - this.getEntityBoundingBox().expand((double) f, (double) f, (double) f)); - EntityEnderCrystal entityendercrystal = null; - double d0 = Double.MAX_VALUE; - - for (int i = 0, l = list.size(); i < l; ++i) { - EntityEnderCrystal entityendercrystal1 = list.get(i); - double d1 = entityendercrystal1.getDistanceSqToEntity(this); - if (d1 < d0) { - d0 = d1; - entityendercrystal = entityendercrystal1; - } - } - - this.healingEnderCrystal = entityendercrystal; - } - - } - - /**+ - * Pushes all entities inside the list away from the - * enderdragon. - */ - private void collideWithEntities(List parList) { - double d0 = (this.dragonPartBody.getEntityBoundingBox().minX + this.dragonPartBody.getEntityBoundingBox().maxX) - / 2.0D; - double d1 = (this.dragonPartBody.getEntityBoundingBox().minZ + this.dragonPartBody.getEntityBoundingBox().maxZ) - / 2.0D; - - for (int i = 0, l = parList.size(); i < l; ++i) { - Entity entity = parList.get(i); - if (entity instanceof EntityLivingBase) { - double d2 = entity.posX - d0; - double d3 = entity.posZ - d1; - double d4 = d2 * d2 + d3 * d3; - entity.addVelocity(d2 / d4 * 4.0D, 0.20000000298023224D, d3 / d4 * 4.0D); - } - } - - } - - /**+ - * Attacks all entities inside this list, dealing 5 hearts of - * damage. - */ - private void attackEntitiesInList(List parList) { - for (int i = 0, l = parList.size(); i < l; ++i) { - Entity entity = (Entity) parList.get(i); - if (entity instanceof EntityLivingBase) { - entity.attackEntityFrom(DamageSource.causeMobDamage(this), 10.0F); - this.applyEnchantments(this, entity); - } - } - - } - - /**+ - * Sets a new target for the flight AI. It can be a random - * coordinate or a nearby player. + /** + * + Sets a new target for the flight AI. It can be a random coordinate or a + * nearby player. */ private void setNewTarget() { this.forceNewTarget = false; @@ -473,245 +669,49 @@ public class EntityDragon extends EntityLiving implements IBossDisplayData, IEnt } - /**+ - * Simplifies the value of a number by adding/subtracting 180 to - * the point that the number is between -180 and 180. + /** + * + Simplifies the value of a number by adding/subtracting 180 to the point + * that the number is between -180 and 180. */ private float simplifyAngle(double parDouble1) { return (float) MathHelper.wrapAngleTo180_double(parDouble1); } - /**+ - * Destroys all blocks that aren't associated with 'The End' - * inside the given bounding box. + /** + * + Updates the state of the enderdragon's current endercrystal. */ - private boolean destroyBlocksInAABB(AxisAlignedBB parAxisAlignedBB) { - int i = MathHelper.floor_double(parAxisAlignedBB.minX); - int j = MathHelper.floor_double(parAxisAlignedBB.minY); - int k = MathHelper.floor_double(parAxisAlignedBB.minZ); - int l = MathHelper.floor_double(parAxisAlignedBB.maxX); - int i1 = MathHelper.floor_double(parAxisAlignedBB.maxY); - int j1 = MathHelper.floor_double(parAxisAlignedBB.maxZ); - boolean flag = false; - boolean flag1 = false; - - for (int k1 = i; k1 <= l; ++k1) { - for (int l1 = j; l1 <= i1; ++l1) { - for (int i2 = k; i2 <= j1; ++i2) { - BlockPos blockpos = new BlockPos(k1, l1, i2); - Block block = this.worldObj.getBlockState(blockpos).getBlock(); - if (block.getMaterial() != Material.air) { - if (block != Blocks.barrier && block != Blocks.obsidian && block != Blocks.end_stone - && block != Blocks.bedrock && block != Blocks.command_block - && this.worldObj.getGameRules().getBoolean("mobGriefing")) { - flag1 = this.worldObj.setBlockToAir(blockpos) || flag1; - } else { - flag = true; - } - } + private void updateDragonEnderCrystal() { + if (this.healingEnderCrystal != null) { + if (this.healingEnderCrystal.isDead) { + if (!this.worldObj.isRemote) { + this.attackEntityFromPart(this.dragonPartHead, DamageSource.setExplosionSource((Explosion) null), + 10.0F); } + + this.healingEnderCrystal = null; + } else if (this.ticksExisted % 10 == 0 && this.getHealth() < this.getMaxHealth()) { + this.setHealth(this.getHealth() + 1.0F); } } - if (flag1) { - double d0 = parAxisAlignedBB.minX - + (parAxisAlignedBB.maxX - parAxisAlignedBB.minX) * (double) this.rand.nextFloat(); - double d1 = parAxisAlignedBB.minY - + (parAxisAlignedBB.maxY - parAxisAlignedBB.minY) * (double) this.rand.nextFloat(); - double d2 = parAxisAlignedBB.minZ - + (parAxisAlignedBB.maxZ - parAxisAlignedBB.minZ) * (double) this.rand.nextFloat(); - this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_LARGE, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); - } + if (this.rand.nextInt(10) == 0) { + float f = 32.0F; + List list = this.worldObj.getEntitiesWithinAABB(EntityEnderCrystal.class, + this.getEntityBoundingBox().expand((double) f, (double) f, (double) f)); + EntityEnderCrystal entityendercrystal = null; + double d0 = Double.MAX_VALUE; - return flag; - } - - public boolean attackEntityFromPart(EntityDragonPart entitydragonpart, DamageSource damagesource, float f) { - if (entitydragonpart != this.dragonPartHead) { - f = f / 4.0F + 1.0F; - } - - float f1 = this.rotationYaw * 3.1415927F / 180.0F; - float f2 = MathHelper.sin(f1); - float f3 = MathHelper.cos(f1); - this.targetX = this.posX + (double) (f2 * 5.0F) + (double) ((this.rand.nextFloat() - 0.5F) * 2.0F); - this.targetY = this.posY + (double) (this.rand.nextFloat() * 3.0F) + 1.0D; - this.targetZ = this.posZ - (double) (f3 * 5.0F) + (double) ((this.rand.nextFloat() - 0.5F) * 2.0F); - this.target = null; - if (damagesource.getEntity() instanceof EntityPlayer || damagesource.isExplosion()) { - this.attackDragonFrom(damagesource, f); - } - - return true; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (damagesource instanceof EntityDamageSource && ((EntityDamageSource) damagesource).getIsThornsDamage()) { - this.attackDragonFrom(damagesource, f); - } - - return false; - } - - /**+ - * Provides a way to cause damage to an ender dragon. - */ - protected boolean attackDragonFrom(DamageSource source, float amount) { - return super.attackEntityFrom(source, amount); - } - - /**+ - * Called by the /kill command. - */ - public void onKillCommand() { - this.setDead(); - } - - /**+ - * handles entity death timer, experience orb and particle - * creation - */ - protected void onDeathUpdate() { - ++this.deathTicks; - if (this.deathTicks >= 180 && this.deathTicks <= 200) { - float f = (this.rand.nextFloat() - 0.5F) * 8.0F; - float f1 = (this.rand.nextFloat() - 0.5F) * 4.0F; - float f2 = (this.rand.nextFloat() - 0.5F) * 8.0F; - this.worldObj.spawnParticle(EnumParticleTypes.EXPLOSION_HUGE, this.posX + (double) f, - this.posY + 2.0D + (double) f1, this.posZ + (double) f2, 0.0D, 0.0D, 0.0D, new int[0]); - } - - boolean flag = this.worldObj.getGameRules().getBoolean("doMobLoot"); - if (!this.worldObj.isRemote) { - if (this.deathTicks > 150 && this.deathTicks % 5 == 0 && flag) { - int i = 1000; - - while (i > 0) { - int k = EntityXPOrb.getXPSplit(i); - i -= k; - this.worldObj - .spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, k)); + for (int i = 0, l = list.size(); i < l; ++i) { + EntityEnderCrystal entityendercrystal1 = list.get(i); + double d1 = entityendercrystal1.getDistanceSqToEntity(this); + if (d1 < d0) { + d0 = d1; + entityendercrystal = entityendercrystal1; } } - if (this.deathTicks == 1) { - this.worldObj.playBroadcastSound(1018, new BlockPos(this), 0); - } + this.healingEnderCrystal = entityendercrystal; } - this.moveEntity(0.0D, 0.10000000149011612D, 0.0D); - this.renderYawOffset = this.rotationYaw += 20.0F; - if (this.deathTicks == 200 && !this.worldObj.isRemote) { - if (flag) { - int j = 2000; - - while (j > 0) { - int l = EntityXPOrb.getXPSplit(j); - j -= l; - this.worldObj - .spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY, this.posZ, l)); - } - } - - this.generatePortal(new BlockPos(this.posX, 64.0D, this.posZ)); - this.setDead(); - } - - } - - /**+ - * Generate the portal when the dragon dies - */ - private void generatePortal(BlockPos pos) { - boolean flag = true; - double d0 = 12.25D; - double d1 = 6.25D; - - for (int i = -1; i <= 32; ++i) { - for (int j = -4; j <= 4; ++j) { - for (int k = -4; k <= 4; ++k) { - double d2 = (double) (j * j + k * k); - if (d2 <= 12.25D) { - BlockPos blockpos = pos.add(j, i, k); - if (i < 0) { - if (d2 <= 6.25D) { - this.worldObj.setBlockState(blockpos, Blocks.bedrock.getDefaultState()); - } - } else if (i > 0) { - this.worldObj.setBlockState(blockpos, Blocks.air.getDefaultState()); - } else if (d2 > 6.25D) { - this.worldObj.setBlockState(blockpos, Blocks.bedrock.getDefaultState()); - } else { - this.worldObj.setBlockState(blockpos, Blocks.end_portal.getDefaultState()); - } - } - } - } - } - - this.worldObj.setBlockState(pos, Blocks.bedrock.getDefaultState()); - this.worldObj.setBlockState(pos.up(), Blocks.bedrock.getDefaultState()); - BlockPos blockpos1 = pos.up(2); - this.worldObj.setBlockState(blockpos1, Blocks.bedrock.getDefaultState()); - this.worldObj.setBlockState(blockpos1.west(), - Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.EAST)); - this.worldObj.setBlockState(blockpos1.east(), - Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.WEST)); - this.worldObj.setBlockState(blockpos1.north(), - Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.SOUTH)); - this.worldObj.setBlockState(blockpos1.south(), - Blocks.torch.getDefaultState().withProperty(BlockTorch.FACING, EnumFacing.NORTH)); - this.worldObj.setBlockState(pos.up(3), Blocks.bedrock.getDefaultState()); - this.worldObj.setBlockState(pos.up(4), Blocks.dragon_egg.getDefaultState()); - } - - /**+ - * Makes the entity despawn if requirements are reached - */ - protected void despawnEntity() { - } - - /**+ - * Return the Entity parts making up this Entity (currently only - * for dragons) - */ - public Entity[] getParts() { - return this.dragonPartArray; - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return false; - } - - public World getWorld() { - return this.worldObj; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.enderdragon.growl"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.enderdragon.hit"; - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 5.0F; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/boss/EntityDragonPart.java b/src/game/java/net/minecraft/entity/boss/EntityDragonPart.java index 7a56a653..637f6707 100644 --- a/src/game/java/net/minecraft/entity/boss/EntityDragonPart.java +++ b/src/game/java/net/minecraft/entity/boss/EntityDragonPart.java @@ -5,22 +5,25 @@ import net.minecraft.entity.IEntityMultiPart; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,43 +39,41 @@ public class EntityDragonPart extends Entity { this.partName = partName; } - protected void entityInit() { - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - protected void readEntityFromNBT(NBTTagCompound var1) { - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound var1) { - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return true; - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { return this.isEntityInvulnerable(damagesource) ? false : this.entityDragonObj.attackEntityFromPart(this, damagesource, f); } - /**+ - * Returns true if Entity argument is equal to this Entity + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return true; + } + + protected void entityInit() { + } + + /** + * + Returns true if Entity argument is equal to this Entity */ public boolean isEntityEqual(Entity entity) { return this == entity || this.entityDragonObj == entity; } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + protected void readEntityFromNBT(NBTTagCompound var1) { + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound var1) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/boss/EntityWither.java b/src/game/java/net/minecraft/entity/boss/EntityWither.java index f1299adb..0d2b0a66 100644 --- a/src/game/java/net/minecraft/entity/boss/EntityWither.java +++ b/src/game/java/net/minecraft/entity/boss/EntityWither.java @@ -1,8 +1,10 @@ package net.minecraft.entity.boss; +import java.util.List; + import com.google.common.base.Predicate; import com.google.common.base.Predicates; -import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; @@ -37,37 +39,32 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityWither extends EntityMob implements IBossDisplayData, IRangedAttackMob { - private float[] field_82220_d = new float[2]; - private float[] field_82221_e = new float[2]; - private float[] field_82217_f = new float[2]; - private float[] field_82218_g = new float[2]; - private int[] field_82223_h = new int[2]; - private int[] field_82224_i = new int[2]; - private int blockBreakCounter; - /**+ - * Selector used to determine the entities a wither boss should - * attack. + /** + * + Selector used to determine the entities a wither boss should attack. */ private static final Predicate attackEntitySelector = new Predicate() { public boolean apply(Entity entity) { @@ -76,6 +73,20 @@ public class EntityWither extends EntityMob implements IBossDisplayData, IRanged } }; + public static boolean func_181033_a(Block parBlock) { + return parBlock != Blocks.bedrock && parBlock != Blocks.end_portal && parBlock != Blocks.end_portal_frame + && parBlock != Blocks.command_block && parBlock != Blocks.barrier; + } + + private float[] field_82220_d = new float[2]; + private float[] field_82221_e = new float[2]; + private float[] field_82217_f = new float[2]; + private float[] field_82218_g = new float[2]; + private int[] field_82223_h = new int[2]; + private int[] field_82224_i = new int[2]; + + private int blockBreakCounter; + public EntityWither(World worldIn) { super(worldIn); this.setHealth(this.getMaxHealth()); @@ -93,6 +104,90 @@ public class EntityWither extends EntityMob implements IBossDisplayData, IRanged this.experienceValue = 50; } + /** + * + adds a PotionEffect to the entity + */ + public void addPotionEffect(PotionEffect var1) { + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(300.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D); + this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(40.0D); + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else if (damagesource != DamageSource.drown && !(damagesource.getEntity() instanceof EntityWither)) { + if (this.getInvulTime() > 0 && damagesource != DamageSource.outOfWorld) { + return false; + } else { + if (this.isArmored()) { + Entity entity = damagesource.getSourceOfDamage(); + if (entity instanceof EntityArrow) { + return false; + } + } + + Entity entity1 = damagesource.getEntity(); + if (entity1 != null && !(entity1 instanceof EntityPlayer) && entity1 instanceof EntityLivingBase + && ((EntityLivingBase) entity1).getCreatureAttribute() == this.getCreatureAttribute()) { + return false; + } else { + if (this.blockBreakCounter <= 0) { + this.blockBreakCounter = 20; + } + + for (int i = 0; i < this.field_82224_i.length; ++i) { + this.field_82224_i[i] += 3; + } + + return super.attackEntityFrom(damagesource, f); + } + } + } else { + return false; + } + } + + /** + * + Attack the specified entity using a ranged attack. + */ + public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float var2) { + this.launchWitherSkullToEntity(0, entitylivingbase); + } + + /** + * + Makes the entity despawn if requirements are reached + */ + protected void despawnEntity() { + this.entityAge = 0; + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int var2) { + EntityItem entityitem = this.dropItem(Items.nether_star, 1); + if (entityitem != null) { + entityitem.setNoDespawn(); + } + + if (!this.worldObj.isRemote) { + List lst = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, + this.getEntityBoundingBox().expand(50.0D, 100.0D, 50.0D)); + for (int i = 0, l = lst.size(); i < l; ++i) { + lst.get(i).triggerAchievement(AchievementList.killWither); + } + } + + } + protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(17, Integer.valueOf(0)); @@ -101,49 +196,162 @@ public class EntityWither extends EntityMob implements IBossDisplayData, IRanged this.dataWatcher.addObject(20, Integer.valueOf(0)); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("Invul", this.getInvulTime()); + public void fall(float var1, float var2) { } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setInvulTime(nbttagcompound.getInteger("Invul")); + private float func_82204_b(float parFloat1, float parFloat2, float parFloat3) { + float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); + if (f > parFloat3) { + f = parFloat3; + } + + if (f < -parFloat3) { + f = -parFloat3; + } + + return parFloat1 + f; } - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.wither.idle"; + public void func_82206_m() { + this.setInvulTime(220); + this.setHealth(this.getMaxHealth() / 3.0F); } - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.wither.hurt"; + public float func_82207_a(int parInt1) { + return this.field_82221_e[parInt1]; } - /**+ - * Returns the sound this mob makes on death. + private double func_82208_v(int parInt1) { + return parInt1 <= 0 ? this.posY + 3.0D : this.posY + 2.2D; + } + + public float func_82210_r(int parInt1) { + return this.field_82220_d[parInt1]; + } + + private double func_82213_w(int parInt1) { + if (parInt1 <= 0) { + return this.posZ; + } else { + float f = (this.renderYawOffset + (float) (180 * (parInt1 - 1))) / 180.0F * 3.1415927F; + float f1 = MathHelper.sin(f); + return this.posZ + (double) f1 * 1.3D; + } + } + + private double func_82214_u(int parInt1) { + if (parInt1 <= 0) { + return this.posX; + } else { + float f = (this.renderYawOffset + (float) (180 * (parInt1 - 1))) / 180.0F * 3.1415927F; + float f1 = MathHelper.cos(f); + return this.posX + (double) f1 * 1.3D; + } + } + + public int getBrightnessForRender(float var1) { + return 15728880; + } + + /** + * + Get this Entity's EnumCreatureAttribute + */ + public EnumCreatureAttribute getCreatureAttribute() { + return EnumCreatureAttribute.UNDEAD; + } + + /** + * + Returns the sound this mob makes on death. */ protected String getDeathSound() { return "mob.wither.death"; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 1.0f; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.wither.hurt"; + } + + public int getInvulTime() { + return this.dataWatcher.getWatchableObjectInt(20); + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.wither.idle"; + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue + */ + public int getTotalArmorValue() { + return 4; + } + + /** + * + Returns the target entity ID if present, or -1 if not @param par1 The + * target offset, should be from 0-2 + */ + public int getWatchedTargetId(int parInt1) { + return this.dataWatcher.getWatchableObjectInt(17 + parInt1); + } + + /** + * + Returns whether the wither is armored with its boss armor or not by + * checking whether its health is below half of its maximum. + */ + public boolean isArmored() { + return this.getHealth() <= this.getMaxHealth() / 2.0F; + } + + /** + * + Launches a Wither skull toward (par2, par4, par6) + */ + private void launchWitherSkullToCoords(int x, double y, double z, double invulnerable, boolean parFlag) { + this.worldObj.playAuxSFXAtEntity((EntityPlayer) null, 1014, new BlockPos(this), 0); + double d0 = this.func_82214_u(x); + double d1 = this.func_82208_v(x); + double d2 = this.func_82213_w(x); + double d3 = y - d0; + double d4 = z - d1; + double d5 = invulnerable - d2; + EntityWitherSkull entitywitherskull = new EntityWitherSkull(this.worldObj, this, d3, d4, d5); + if (parFlag) { + entitywitherskull.setInvulnerable(true); + } + + entitywitherskull.posY = d1; + entitywitherskull.posX = d0; + entitywitherskull.posZ = d2; + this.worldObj.spawnEntityInWorld(entitywitherskull); + } + + private void launchWitherSkullToEntity(int parInt1, EntityLivingBase parEntityLivingBase) { + this.launchWitherSkullToCoords(parInt1, parEntityLivingBase.posX, + parEntityLivingBase.posY + (double) parEntityLivingBase.getEyeHeight() * 0.5D, parEntityLivingBase.posZ, + parInt1 == 0 && this.rand.nextFloat() < 0.001F); + } + + /** + * + Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. + */ + public void mountEntity(Entity var1) { + this.ridingEntity = null; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { this.motionY *= 0.6000000238418579D; @@ -234,6 +442,24 @@ public class EntityWither extends EntityMob implements IBossDisplayData, IRanged } + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setInvulTime(nbttagcompound.getInteger("Invul")); + } + + public void setInvulTime(int parInt1) { + this.dataWatcher.updateObject(20, Integer.valueOf(parInt1)); + } + + /** + * + Sets the Entity inside a web block. + */ + public void setInWeb() { + } + protected void updateAITasks() { if (this.getInvulTime() > 0) { int j1 = this.getInvulTime() - 1; @@ -356,242 +582,18 @@ public class EntityWither extends EntityMob implements IBossDisplayData, IRanged } } - public static boolean func_181033_a(Block parBlock) { - return parBlock != Blocks.bedrock && parBlock != Blocks.end_portal && parBlock != Blocks.end_portal_frame - && parBlock != Blocks.command_block && parBlock != Blocks.barrier; - } - - public void func_82206_m() { - this.setInvulTime(220); - this.setHealth(this.getMaxHealth() / 3.0F); - } - - /**+ - * Sets the Entity inside a web block. - */ - public void setInWeb() { - } - - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - return 4; - } - - private double func_82214_u(int parInt1) { - if (parInt1 <= 0) { - return this.posX; - } else { - float f = (this.renderYawOffset + (float) (180 * (parInt1 - 1))) / 180.0F * 3.1415927F; - float f1 = MathHelper.cos(f); - return this.posX + (double) f1 * 1.3D; - } - } - - private double func_82208_v(int parInt1) { - return parInt1 <= 0 ? this.posY + 3.0D : this.posY + 2.2D; - } - - private double func_82213_w(int parInt1) { - if (parInt1 <= 0) { - return this.posZ; - } else { - float f = (this.renderYawOffset + (float) (180 * (parInt1 - 1))) / 180.0F * 3.1415927F; - float f1 = MathHelper.sin(f); - return this.posZ + (double) f1 * 1.3D; - } - } - - private float func_82204_b(float parFloat1, float parFloat2, float parFloat3) { - float f = MathHelper.wrapAngleTo180_float(parFloat2 - parFloat1); - if (f > parFloat3) { - f = parFloat3; - } - - if (f < -parFloat3) { - f = -parFloat3; - } - - return parFloat1 + f; - } - - private void launchWitherSkullToEntity(int parInt1, EntityLivingBase parEntityLivingBase) { - this.launchWitherSkullToCoords(parInt1, parEntityLivingBase.posX, - parEntityLivingBase.posY + (double) parEntityLivingBase.getEyeHeight() * 0.5D, parEntityLivingBase.posZ, - parInt1 == 0 && this.rand.nextFloat() < 0.001F); - } - - /**+ - * Launches a Wither skull toward (par2, par4, par6) - */ - private void launchWitherSkullToCoords(int x, double y, double z, double invulnerable, boolean parFlag) { - this.worldObj.playAuxSFXAtEntity((EntityPlayer) null, 1014, new BlockPos(this), 0); - double d0 = this.func_82214_u(x); - double d1 = this.func_82208_v(x); - double d2 = this.func_82213_w(x); - double d3 = y - d0; - double d4 = z - d1; - double d5 = invulnerable - d2; - EntityWitherSkull entitywitherskull = new EntityWitherSkull(this.worldObj, this, d3, d4, d5); - if (parFlag) { - entitywitherskull.setInvulnerable(true); - } - - entitywitherskull.posY = d1; - entitywitherskull.posX = d0; - entitywitherskull.posZ = d2; - this.worldObj.spawnEntityInWorld(entitywitherskull); - } - - /**+ - * Attack the specified entity using a ranged attack. - */ - public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float var2) { - this.launchWitherSkullToEntity(0, entitylivingbase); - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else if (damagesource != DamageSource.drown && !(damagesource.getEntity() instanceof EntityWither)) { - if (this.getInvulTime() > 0 && damagesource != DamageSource.outOfWorld) { - return false; - } else { - if (this.isArmored()) { - Entity entity = damagesource.getSourceOfDamage(); - if (entity instanceof EntityArrow) { - return false; - } - } - - Entity entity1 = damagesource.getEntity(); - if (entity1 != null && !(entity1 instanceof EntityPlayer) && entity1 instanceof EntityLivingBase - && ((EntityLivingBase) entity1).getCreatureAttribute() == this.getCreatureAttribute()) { - return false; - } else { - if (this.blockBreakCounter <= 0) { - this.blockBreakCounter = 20; - } - - for (int i = 0; i < this.field_82224_i.length; ++i) { - this.field_82224_i[i] += 3; - } - - return super.attackEntityFrom(damagesource, f); - } - } - } else { - return false; - } - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int var2) { - EntityItem entityitem = this.dropItem(Items.nether_star, 1); - if (entityitem != null) { - entityitem.setNoDespawn(); - } - - if (!this.worldObj.isRemote) { - List lst = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, - this.getEntityBoundingBox().expand(50.0D, 100.0D, 50.0D)); - for (int i = 0, l = lst.size(); i < l; ++i) { - lst.get(i).triggerAchievement(AchievementList.killWither); - } - } - - } - - /**+ - * Makes the entity despawn if requirements are reached - */ - protected void despawnEntity() { - this.entityAge = 0; - } - - public int getBrightnessForRender(float var1) { - return 15728880; - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 1.0f; - } - - public void fall(float var1, float var2) { - } - - /**+ - * adds a PotionEffect to the entity - */ - public void addPotionEffect(PotionEffect var1) { - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(300.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.6000000238418579D); - this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(40.0D); - } - - public float func_82207_a(int parInt1) { - return this.field_82221_e[parInt1]; - } - - public float func_82210_r(int parInt1) { - return this.field_82220_d[parInt1]; - } - - public int getInvulTime() { - return this.dataWatcher.getWatchableObjectInt(20); - } - - public void setInvulTime(int parInt1) { - this.dataWatcher.updateObject(20, Integer.valueOf(parInt1)); - } - - /**+ - * Returns the target entity ID if present, or -1 if not @param - * par1 The target offset, should be from 0-2 - */ - public int getWatchedTargetId(int parInt1) { - return this.dataWatcher.getWatchableObjectInt(17 + parInt1); - } - - /**+ - * Updates the target entity ID + /** + * + Updates the target entity ID */ public void updateWatchedTargetId(int targetOffset, int newId) { this.dataWatcher.updateObject(17 + targetOffset, Integer.valueOf(newId)); } - /**+ - * Returns whether the wither is armored with its boss armor or - * not by checking whether its health is below half of its - * maximum. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean isArmored() { - return this.getHealth() <= this.getMaxHealth() / 2.0F; - } - - /**+ - * Get this Entity's EnumCreatureAttribute - */ - public EnumCreatureAttribute getCreatureAttribute() { - return EnumCreatureAttribute.UNDEAD; - } - - /**+ - * Called when a player mounts an entity. e.g. mounts a pig, - * mounts a boat. - */ - public void mountEntity(Entity var1) { - this.ridingEntity = null; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("Invul", this.getInvulTime()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/boss/IBossDisplayData.java b/src/game/java/net/minecraft/entity/boss/IBossDisplayData.java index 0bb5a14a..df84047a 100644 --- a/src/game/java/net/minecraft/entity/boss/IBossDisplayData.java +++ b/src/game/java/net/minecraft/entity/boss/IBossDisplayData.java @@ -2,34 +2,37 @@ package net.minecraft.entity.boss; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IBossDisplayData { - float getMaxHealth(); + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + IChatComponent getDisplayName(); float getHealth(); - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - IChatComponent getDisplayName(); + float getMaxHealth(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/effect/EntityLightningBolt.java b/src/game/java/net/minecraft/entity/effect/EntityLightningBolt.java index 1a3732ea..b8962171 100644 --- a/src/game/java/net/minecraft/entity/effect/EntityLightningBolt.java +++ b/src/game/java/net/minecraft/entity/effect/EntityLightningBolt.java @@ -1,6 +1,7 @@ package net.minecraft.entity.effect; import java.util.List; + import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; @@ -10,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,8 +66,11 @@ public class EntityLightningBolt extends EntityWeatherEffect { } - /**+ - * Called to update the entity's position/logic. + protected void entityInit() { + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -109,19 +116,14 @@ public class EntityLightningBolt extends EntityWeatherEffect { } - protected void entityInit() { - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound var1) { } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ protected void writeEntityToNBT(NBTTagCompound var1) { } diff --git a/src/game/java/net/minecraft/entity/effect/EntityWeatherEffect.java b/src/game/java/net/minecraft/entity/effect/EntityWeatherEffect.java index 9160c543..6a0f2413 100644 --- a/src/game/java/net/minecraft/entity/effect/EntityWeatherEffect.java +++ b/src/game/java/net/minecraft/entity/effect/EntityWeatherEffect.java @@ -3,22 +3,25 @@ package net.minecraft.entity.effect; import net.minecraft.entity.Entity; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/item/EntityArmorStand.java b/src/game/java/net/minecraft/entity/item/EntityArmorStand.java index 6eddbea7..af7752d8 100644 --- a/src/game/java/net/minecraft/entity/item/EntityArmorStand.java +++ b/src/game/java/net/minecraft/entity/item/EntityArmorStand.java @@ -1,6 +1,7 @@ package net.minecraft.entity.item; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; @@ -23,22 +24,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -81,221 +85,78 @@ public class EntityArmorStand extends EntityLivingBase { this.setPosition(posX, posY, posZ); } - /**+ - * Returns whether the entity is in a server world + /** + * + Called when the entity is attacked. */ - public boolean isServerWorld() { - return super.isServerWorld() && !this.hasNoGravity(); - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(10, Byte.valueOf((byte) 0)); - this.dataWatcher.addObject(11, DEFAULT_HEAD_ROTATION); - this.dataWatcher.addObject(12, DEFAULT_BODY_ROTATION); - this.dataWatcher.addObject(13, DEFAULT_LEFTARM_ROTATION); - this.dataWatcher.addObject(14, DEFAULT_RIGHTARM_ROTATION); - this.dataWatcher.addObject(15, DEFAULT_LEFTLEG_ROTATION); - this.dataWatcher.addObject(16, DEFAULT_RIGHTLEG_ROTATION); - } - - /**+ - * Returns the item that this EntityLiving is holding, if any. - */ - public ItemStack getHeldItem() { - return this.contents[0]; - } - - /**+ - * 0: Tool in Hand; 1-4: Armor - */ - public ItemStack getEquipmentInSlot(int i) { - return this.contents[i]; - } - - public ItemStack getCurrentArmor(int i) { - return this.contents[i + 1]; - } - - /**+ - * Sets the held item, or an armor slot. Slot 0 is held item. - * Slot 1-4 is armor. Params: Item, slot - */ - public void setCurrentItemOrArmor(int i, ItemStack itemstack) { - this.contents[i] = itemstack; - } - - /**+ - * returns the inventory of this entity (only used in - * EntityPlayerMP it seems) - */ - public ItemStack[] getInventory() { - return this.contents; - } - - public boolean replaceItemInInventory(int i, ItemStack itemstack) { - int j; - if (i == 99) { - j = 0; - } else { - j = i - 100 + 1; - if (j < 0 || j >= this.contents.length) { - return false; - } - } - - if (itemstack != null && EntityLiving.getArmorPosition(itemstack) != j - && (j != 4 || !(itemstack.getItem() instanceof ItemBlock))) { + public boolean attackEntityFrom(DamageSource damagesource, float var2) { + if (this.worldObj.isRemote) { return false; - } else { - this.setCurrentItemOrArmor(j, itemstack); - return true; - } - } + } else if (DamageSource.outOfWorld.equals(damagesource)) { + this.setDead(); + return false; + } else if (!this.isEntityInvulnerable(damagesource) && !this.canInteract && !this.func_181026_s()) { + if (damagesource.isExplosion()) { + this.dropContents(); + this.setDead(); + return false; + } else if (DamageSource.inFire.equals(damagesource)) { + if (!this.isBurning()) { + this.setFire(5); + } else { + this.damageArmorStand(0.15F); + } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); + return false; + } else if (DamageSource.onFire.equals(damagesource) && this.getHealth() > 0.5F) { + this.damageArmorStand(4.0F); + return false; + } else { + boolean flag = "arrow".equals(damagesource.getDamageType()); + boolean flag1 = "player".equals(damagesource.getDamageType()); + if (!flag1 && !flag) { + return false; + } else { + if (damagesource.getSourceOfDamage() instanceof EntityArrow) { + damagesource.getSourceOfDamage().setDead(); + } - for (int i = 0; i < this.contents.length; ++i) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - if (this.contents[i] != null) { - this.contents[i].writeToNBT(nbttagcompound1); + if (damagesource.getEntity() instanceof EntityPlayer + && !((EntityPlayer) damagesource.getEntity()).capabilities.allowEdit) { + return false; + } else if (damagesource.isCreativePlayer()) { + this.playParticles(); + this.setDead(); + return false; + } else { + long i = this.worldObj.getTotalWorldTime(); + if (i - this.punchCooldown > 5L && !flag) { + this.punchCooldown = i; + } else { + this.dropBlock(); + this.playParticles(); + this.setDead(); + } + + return false; + } + } } - - nbttaglist.appendTag(nbttagcompound1); + } else { + return false; } - - nbttagcompound.setTag("Equipment", nbttaglist); - if (this.getAlwaysRenderNameTag() - && (this.getCustomNameTag() == null || this.getCustomNameTag().length() == 0)) { - nbttagcompound.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); - } - - nbttagcompound.setBoolean("Invisible", this.isInvisible()); - nbttagcompound.setBoolean("Small", this.isSmall()); - nbttagcompound.setBoolean("ShowArms", this.getShowArms()); - nbttagcompound.setInteger("DisabledSlots", this.disabledSlots); - nbttagcompound.setBoolean("NoGravity", this.hasNoGravity()); - nbttagcompound.setBoolean("NoBasePlate", this.hasNoBasePlate()); - if (this.func_181026_s()) { - nbttagcompound.setBoolean("Marker", this.func_181026_s()); - } - - nbttagcompound.setTag("Pose", this.readPoseFromNBT()); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("Equipment", 9)) { - NBTTagList nbttaglist = nbttagcompound.getTagList("Equipment", 10); - - for (int i = 0; i < this.contents.length; ++i) { - this.contents[i] = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); - } - } - - this.setInvisible(nbttagcompound.getBoolean("Invisible")); - this.setSmall(nbttagcompound.getBoolean("Small")); - this.setShowArms(nbttagcompound.getBoolean("ShowArms")); - this.disabledSlots = nbttagcompound.getInteger("DisabledSlots"); - this.setNoGravity(nbttagcompound.getBoolean("NoGravity")); - this.setNoBasePlate(nbttagcompound.getBoolean("NoBasePlate")); - this.func_181027_m(nbttagcompound.getBoolean("Marker")); - this.field_181028_bj = !this.func_181026_s(); - this.noClip = this.hasNoGravity(); - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Pose"); - this.writePoseToNBT(nbttagcompound1); + public boolean canBeCollidedWith() { + return super.canBeCollidedWith() && !this.func_181026_s(); } - /**+ - * Saves the pose to an NBTTagCompound. - */ - private void writePoseToNBT(NBTTagCompound tagCompound) { - NBTTagList nbttaglist = tagCompound.getTagList("Head", 5); - if (nbttaglist.tagCount() > 0) { - this.setHeadRotation(new Rotations(nbttaglist)); - } else { - this.setHeadRotation(DEFAULT_HEAD_ROTATION); - } - - NBTTagList nbttaglist1 = tagCompound.getTagList("Body", 5); - if (nbttaglist1.tagCount() > 0) { - this.setBodyRotation(new Rotations(nbttaglist1)); - } else { - this.setBodyRotation(DEFAULT_BODY_ROTATION); - } - - NBTTagList nbttaglist2 = tagCompound.getTagList("LeftArm", 5); - if (nbttaglist2.tagCount() > 0) { - this.setLeftArmRotation(new Rotations(nbttaglist2)); - } else { - this.setLeftArmRotation(DEFAULT_LEFTARM_ROTATION); - } - - NBTTagList nbttaglist3 = tagCompound.getTagList("RightArm", 5); - if (nbttaglist3.tagCount() > 0) { - this.setRightArmRotation(new Rotations(nbttaglist3)); - } else { - this.setRightArmRotation(DEFAULT_RIGHTARM_ROTATION); - } - - NBTTagList nbttaglist4 = tagCompound.getTagList("LeftLeg", 5); - if (nbttaglist4.tagCount() > 0) { - this.setLeftLegRotation(new Rotations(nbttaglist4)); - } else { - this.setLeftLegRotation(DEFAULT_LEFTLEG_ROTATION); - } - - NBTTagList nbttaglist5 = tagCompound.getTagList("RightLeg", 5); - if (nbttaglist5.tagCount() > 0) { - this.setRightLegRotation(new Rotations(nbttaglist5)); - } else { - this.setRightLegRotation(DEFAULT_RIGHTLEG_ROTATION); - } - - } - - private NBTTagCompound readPoseFromNBT() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - if (!DEFAULT_HEAD_ROTATION.equals(this.headRotation)) { - nbttagcompound.setTag("Head", this.headRotation.writeToNBT()); - } - - if (!DEFAULT_BODY_ROTATION.equals(this.bodyRotation)) { - nbttagcompound.setTag("Body", this.bodyRotation.writeToNBT()); - } - - if (!DEFAULT_LEFTARM_ROTATION.equals(this.leftArmRotation)) { - nbttagcompound.setTag("LeftArm", this.leftArmRotation.writeToNBT()); - } - - if (!DEFAULT_RIGHTARM_ROTATION.equals(this.rightArmRotation)) { - nbttagcompound.setTag("RightArm", this.rightArmRotation.writeToNBT()); - } - - if (!DEFAULT_LEFTLEG_ROTATION.equals(this.leftLegRotation)) { - nbttagcompound.setTag("LeftLeg", this.leftLegRotation.writeToNBT()); - } - - if (!DEFAULT_RIGHTLEG_ROTATION.equals(this.rightLegRotation)) { - nbttagcompound.setTag("RightLeg", this.rightLegRotation.writeToNBT()); - } - - return nbttagcompound; - } - - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. */ public boolean canBePushed() { return false; @@ -319,9 +180,176 @@ public class EntityArmorStand extends EntityLivingBase { } - /**+ - * New version of interactWith that includes vector information - * on where precisely the player targeted. + private void damageArmorStand(float parFloat1) { + float f = this.getHealth(); + f = f - parFloat1; + if (f <= 0.5F) { + this.dropContents(); + this.setDead(); + } else { + this.setHealth(f); + } + + } + + private void dropBlock() { + Block.spawnAsEntity(this.worldObj, new BlockPos(this), new ItemStack(Items.armor_stand)); + this.dropContents(); + } + + private void dropContents() { + for (int i = 0; i < this.contents.length; ++i) { + if (this.contents[i] != null && this.contents[i].stackSize > 0) { + if (this.contents[i] != null) { + Block.spawnAsEntity(this.worldObj, (new BlockPos(this)).up(), this.contents[i]); + } + + this.contents[i] = null; + } + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(10, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(11, DEFAULT_HEAD_ROTATION); + this.dataWatcher.addObject(12, DEFAULT_BODY_ROTATION); + this.dataWatcher.addObject(13, DEFAULT_LEFTARM_ROTATION); + this.dataWatcher.addObject(14, DEFAULT_RIGHTARM_ROTATION); + this.dataWatcher.addObject(15, DEFAULT_LEFTLEG_ROTATION); + this.dataWatcher.addObject(16, DEFAULT_RIGHTLEG_ROTATION); + } + + protected float func_110146_f(float var1, float var2) { + this.prevRenderYawOffset = this.prevRotationYaw; + this.renderYawOffset = this.rotationYaw; + return 0.0F; + } + + private void func_175422_a(EntityPlayer parEntityPlayer, int parInt1) { + ItemStack itemstack = this.contents[parInt1]; + if (itemstack == null || (this.disabledSlots & 1 << parInt1 + 8) == 0) { + if (itemstack != null || (this.disabledSlots & 1 << parInt1 + 16) == 0) { + int i = parEntityPlayer.inventory.currentItem; + ItemStack itemstack1 = parEntityPlayer.inventory.getStackInSlot(i); + if (parEntityPlayer.capabilities.isCreativeMode + && (itemstack == null || itemstack.getItem() == Item.getItemFromBlock(Blocks.air)) + && itemstack1 != null) { + ItemStack itemstack3 = itemstack1.copy(); + itemstack3.stackSize = 1; + this.setCurrentItemOrArmor(parInt1, itemstack3); + } else if (itemstack1 != null && itemstack1.stackSize > 1) { + if (itemstack == null) { + ItemStack itemstack2 = itemstack1.copy(); + itemstack2.stackSize = 1; + this.setCurrentItemOrArmor(parInt1, itemstack2); + --itemstack1.stackSize; + } + } else { + this.setCurrentItemOrArmor(parInt1, itemstack1); + parEntityPlayer.inventory.setInventorySlotContents(i, itemstack); + } + } + } + } + + public boolean func_181026_s() { + return (this.dataWatcher.getWatchableObjectByte(10) & 16) != 0; + } + + private void func_181027_m(boolean parFlag) { + byte b0 = this.dataWatcher.getWatchableObjectByte(10); + if (parFlag) { + b0 = (byte) (b0 | 16); + } else { + b0 = (byte) (b0 & -17); + } + + this.dataWatcher.updateObject(10, Byte.valueOf(b0)); + } + + private void func_181550_a(boolean parFlag) { + double d0 = this.posX; + double d1 = this.posY; + double d2 = this.posZ; + if (parFlag) { + this.setSize(0.5F, 1.975F); + } else { + this.setSize(0.0F, 0.0F); + } + + this.setPosition(d0, d1, d2); + } + + public Rotations getBodyRotation() { + return this.bodyRotation; + } + + public ItemStack getCurrentArmor(int i) { + return this.contents[i + 1]; + } + + /** + * + 0: Tool in Hand; 1-4: Armor + */ + public ItemStack getEquipmentInSlot(int i) { + return this.contents[i]; + } + + public float getEyeHeight() { + return this.isChild() ? this.height * 0.5F : this.height * 0.9F; + } + + public Rotations getHeadRotation() { + return this.headRotation; + } + + /** + * + Returns the item that this EntityLiving is holding, if any. + */ + public ItemStack getHeldItem() { + return this.contents[0]; + } + + /** + * + returns the inventory of this entity (only used in EntityPlayerMP it seems) + */ + public ItemStack[] getInventory() { + return this.contents; + } + + public Rotations getLeftArmRotation() { + return this.leftArmRotation; + } + + public Rotations getLeftLegRotation() { + return this.leftLegRotation; + } + + public Rotations getRightArmRotation() { + return this.rightArmRotation; + } + + public Rotations getRightLegRotation() { + return this.rightLegRotation; + } + + public boolean getShowArms() { + return (this.dataWatcher.getWatchableObjectByte(10) & 4) != 0; + } + + public boolean hasNoBasePlate() { + return (this.dataWatcher.getWatchableObjectByte(10) & 8) != 0; + } + + public boolean hasNoGravity() { + return (this.dataWatcher.getWatchableObjectByte(10) & 2) != 0; + } + + /** + * + New version of interactWith that includes vector information on where + * precisely the player targeted. */ public boolean interactAt(EntityPlayer entityplayer, Vec3 vec3) { if (this.func_181026_s()) { @@ -394,98 +422,21 @@ public class EntityArmorStand extends EntityLivingBase { } } - private void func_175422_a(EntityPlayer parEntityPlayer, int parInt1) { - ItemStack itemstack = this.contents[parInt1]; - if (itemstack == null || (this.disabledSlots & 1 << parInt1 + 8) == 0) { - if (itemstack != null || (this.disabledSlots & 1 << parInt1 + 16) == 0) { - int i = parEntityPlayer.inventory.currentItem; - ItemStack itemstack1 = parEntityPlayer.inventory.getStackInSlot(i); - if (parEntityPlayer.capabilities.isCreativeMode - && (itemstack == null || itemstack.getItem() == Item.getItemFromBlock(Blocks.air)) - && itemstack1 != null) { - ItemStack itemstack3 = itemstack1.copy(); - itemstack3.stackSize = 1; - this.setCurrentItemOrArmor(parInt1, itemstack3); - } else if (itemstack1 != null && itemstack1.stackSize > 1) { - if (itemstack == null) { - ItemStack itemstack2 = itemstack1.copy(); - itemstack2.stackSize = 1; - this.setCurrentItemOrArmor(parInt1, itemstack2); - --itemstack1.stackSize; - } - } else { - this.setCurrentItemOrArmor(parInt1, itemstack1); - parEntityPlayer.inventory.setInventorySlotContents(i, itemstack); - } - } - } - } - - /**+ - * Called when the entity is attacked. + /** + * + If Animal, checks if the age timer is negative */ - public boolean attackEntityFrom(DamageSource damagesource, float var2) { - if (this.worldObj.isRemote) { - return false; - } else if (DamageSource.outOfWorld.equals(damagesource)) { - this.setDead(); - return false; - } else if (!this.isEntityInvulnerable(damagesource) && !this.canInteract && !this.func_181026_s()) { - if (damagesource.isExplosion()) { - this.dropContents(); - this.setDead(); - return false; - } else if (DamageSource.inFire.equals(damagesource)) { - if (!this.isBurning()) { - this.setFire(5); - } else { - this.damageArmorStand(0.15F); - } - - return false; - } else if (DamageSource.onFire.equals(damagesource) && this.getHealth() > 0.5F) { - this.damageArmorStand(4.0F); - return false; - } else { - boolean flag = "arrow".equals(damagesource.getDamageType()); - boolean flag1 = "player".equals(damagesource.getDamageType()); - if (!flag1 && !flag) { - return false; - } else { - if (damagesource.getSourceOfDamage() instanceof EntityArrow) { - damagesource.getSourceOfDamage().setDead(); - } - - if (damagesource.getEntity() instanceof EntityPlayer - && !((EntityPlayer) damagesource.getEntity()).capabilities.allowEdit) { - return false; - } else if (damagesource.isCreativePlayer()) { - this.playParticles(); - this.setDead(); - return false; - } else { - long i = this.worldObj.getTotalWorldTime(); - if (i - this.punchCooldown > 5L && !flag) { - this.punchCooldown = i; - } else { - this.dropBlock(); - this.playParticles(); - this.setDead(); - } - - return false; - } - } - } - } else { - return false; - } + public boolean isChild() { + return this.isSmall(); } - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance + public boolean isImmuneToExplosions() { + return this.isInvisible(); + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance */ public boolean isInRangeToRenderDist(double d0) { double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; @@ -497,59 +448,19 @@ public class EntityArmorStand extends EntityLivingBase { return d0 < d1 * d1; } - private void playParticles() { - if (this.worldObj instanceof WorldServer) { - ((WorldServer) this.worldObj).spawnParticle(EnumParticleTypes.BLOCK_DUST, this.posX, - this.posY + (double) this.height / 1.5D, this.posZ, 10, (double) (this.width / 4.0F), - (double) (this.height / 4.0F), (double) (this.width / 4.0F), 0.05D, - new int[] { Block.getStateId(Blocks.planks.getDefaultState()) }); - } - + /** + * + Returns whether the entity is in a server world + */ + public boolean isServerWorld() { + return super.isServerWorld() && !this.hasNoGravity(); } - private void damageArmorStand(float parFloat1) { - float f = this.getHealth(); - f = f - parFloat1; - if (f <= 0.5F) { - this.dropContents(); - this.setDead(); - } else { - this.setHealth(f); - } - + public boolean isSmall() { + return (this.dataWatcher.getWatchableObjectByte(10) & 1) != 0; } - private void dropBlock() { - Block.spawnAsEntity(this.worldObj, new BlockPos(this), new ItemStack(Items.armor_stand)); - this.dropContents(); - } - - private void dropContents() { - for (int i = 0; i < this.contents.length; ++i) { - if (this.contents[i] != null && this.contents[i].stackSize > 0) { - if (this.contents[i] != null) { - Block.spawnAsEntity(this.worldObj, (new BlockPos(this)).up(), this.contents[i]); - } - - this.contents[i] = null; - } - } - - } - - protected float func_110146_f(float var1, float var2) { - this.prevRenderYawOffset = this.prevRotationYaw; - this.renderYawOffset = this.rotationYaw; - return 0.0F; - } - - public float getEyeHeight() { - return this.isChild() ? this.height * 0.5F : this.height * 0.9F; - } - - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward + /** + * + Moves the entity based on the specified heading. Args: strafe, forward */ public void moveEntityWithHeading(float f, float f1) { if (!this.hasNoGravity()) { @@ -557,8 +468,15 @@ public class EntityArmorStand extends EntityLivingBase { } } - /**+ - * Called to update the entity's position/logic. + /** + * + Called by the /kill command. + */ + public void onKillCommand() { + this.setDead(); + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -606,26 +524,107 @@ public class EntityArmorStand extends EntityLivingBase { this.field_181028_bj = flag; } - private void func_181550_a(boolean parFlag) { - double d0 = this.posX; - double d1 = this.posY; - double d2 = this.posZ; - if (parFlag) { - this.setSize(0.5F, 1.975F); - } else { - this.setSize(0.0F, 0.0F); + private void playParticles() { + if (this.worldObj instanceof WorldServer) { + ((WorldServer) this.worldObj).spawnParticle(EnumParticleTypes.BLOCK_DUST, this.posX, + this.posY + (double) this.height / 1.5D, this.posZ, 10, (double) (this.width / 4.0F), + (double) (this.height / 4.0F), (double) (this.width / 4.0F), 0.05D, + new int[] { Block.getStateId(Blocks.planks.getDefaultState()) }); } - this.setPosition(d0, d1, d2); } - /**+ - * Clears potion metadata values if the entity has no potion - * effects. Otherwise, updates potion effect color, ambience, - * and invisibility metadata values + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void updatePotionMetadata() { - this.setInvisible(this.canInteract); + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + if (nbttagcompound.hasKey("Equipment", 9)) { + NBTTagList nbttaglist = nbttagcompound.getTagList("Equipment", 10); + + for (int i = 0; i < this.contents.length; ++i) { + this.contents[i] = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); + } + } + + this.setInvisible(nbttagcompound.getBoolean("Invisible")); + this.setSmall(nbttagcompound.getBoolean("Small")); + this.setShowArms(nbttagcompound.getBoolean("ShowArms")); + this.disabledSlots = nbttagcompound.getInteger("DisabledSlots"); + this.setNoGravity(nbttagcompound.getBoolean("NoGravity")); + this.setNoBasePlate(nbttagcompound.getBoolean("NoBasePlate")); + this.func_181027_m(nbttagcompound.getBoolean("Marker")); + this.field_181028_bj = !this.func_181026_s(); + this.noClip = this.hasNoGravity(); + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Pose"); + this.writePoseToNBT(nbttagcompound1); + } + + private NBTTagCompound readPoseFromNBT() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + if (!DEFAULT_HEAD_ROTATION.equals(this.headRotation)) { + nbttagcompound.setTag("Head", this.headRotation.writeToNBT()); + } + + if (!DEFAULT_BODY_ROTATION.equals(this.bodyRotation)) { + nbttagcompound.setTag("Body", this.bodyRotation.writeToNBT()); + } + + if (!DEFAULT_LEFTARM_ROTATION.equals(this.leftArmRotation)) { + nbttagcompound.setTag("LeftArm", this.leftArmRotation.writeToNBT()); + } + + if (!DEFAULT_RIGHTARM_ROTATION.equals(this.rightArmRotation)) { + nbttagcompound.setTag("RightArm", this.rightArmRotation.writeToNBT()); + } + + if (!DEFAULT_LEFTLEG_ROTATION.equals(this.leftLegRotation)) { + nbttagcompound.setTag("LeftLeg", this.leftLegRotation.writeToNBT()); + } + + if (!DEFAULT_RIGHTLEG_ROTATION.equals(this.rightLegRotation)) { + nbttagcompound.setTag("RightLeg", this.rightLegRotation.writeToNBT()); + } + + return nbttagcompound; + } + + public boolean replaceItemInInventory(int i, ItemStack itemstack) { + int j; + if (i == 99) { + j = 0; + } else { + j = i - 100 + 1; + if (j < 0 || j >= this.contents.length) { + return false; + } + } + + if (itemstack != null && EntityLiving.getArmorPosition(itemstack) != j + && (j != 4 || !(itemstack.getItem() instanceof ItemBlock))) { + return false; + } else { + this.setCurrentItemOrArmor(j, itemstack); + return true; + } + } + + public void setBodyRotation(Rotations parRotations) { + this.bodyRotation = parRotations; + this.dataWatcher.updateObject(12, parRotations); + } + + /** + * + Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is + * armor. Params: Item, slot + */ + public void setCurrentItemOrArmor(int i, ItemStack itemstack) { + this.contents[i] = itemstack; + } + + public void setHeadRotation(Rotations parRotations) { + this.headRotation = parRotations; + this.dataWatcher.updateObject(11, parRotations); } public void setInvisible(boolean flag) { @@ -633,67 +632,14 @@ public class EntityArmorStand extends EntityLivingBase { super.setInvisible(flag); } - /**+ - * If Animal, checks if the age timer is negative - */ - public boolean isChild() { - return this.isSmall(); + public void setLeftArmRotation(Rotations parRotations) { + this.leftArmRotation = parRotations; + this.dataWatcher.updateObject(13, parRotations); } - /**+ - * Called by the /kill command. - */ - public void onKillCommand() { - this.setDead(); - } - - public boolean isImmuneToExplosions() { - return this.isInvisible(); - } - - private void setSmall(boolean parFlag) { - byte b0 = this.dataWatcher.getWatchableObjectByte(10); - if (parFlag) { - b0 = (byte) (b0 | 1); - } else { - b0 = (byte) (b0 & -2); - } - - this.dataWatcher.updateObject(10, Byte.valueOf(b0)); - } - - public boolean isSmall() { - return (this.dataWatcher.getWatchableObjectByte(10) & 1) != 0; - } - - private void setNoGravity(boolean parFlag) { - byte b0 = this.dataWatcher.getWatchableObjectByte(10); - if (parFlag) { - b0 = (byte) (b0 | 2); - } else { - b0 = (byte) (b0 & -3); - } - - this.dataWatcher.updateObject(10, Byte.valueOf(b0)); - } - - public boolean hasNoGravity() { - return (this.dataWatcher.getWatchableObjectByte(10) & 2) != 0; - } - - private void setShowArms(boolean parFlag) { - byte b0 = this.dataWatcher.getWatchableObjectByte(10); - if (parFlag) { - b0 = (byte) (b0 | 4); - } else { - b0 = (byte) (b0 & -5); - } - - this.dataWatcher.updateObject(10, Byte.valueOf(b0)); - } - - public boolean getShowArms() { - return (this.dataWatcher.getWatchableObjectByte(10) & 4) != 0; + public void setLeftLegRotation(Rotations parRotations) { + this.leftLegRotation = parRotations; + this.dataWatcher.updateObject(15, parRotations); } private void setNoBasePlate(boolean parFlag) { @@ -707,84 +653,138 @@ public class EntityArmorStand extends EntityLivingBase { this.dataWatcher.updateObject(10, Byte.valueOf(b0)); } - public boolean hasNoBasePlate() { - return (this.dataWatcher.getWatchableObjectByte(10) & 8) != 0; - } - - private void func_181027_m(boolean parFlag) { + private void setNoGravity(boolean parFlag) { byte b0 = this.dataWatcher.getWatchableObjectByte(10); if (parFlag) { - b0 = (byte) (b0 | 16); + b0 = (byte) (b0 | 2); } else { - b0 = (byte) (b0 & -17); + b0 = (byte) (b0 & -3); } this.dataWatcher.updateObject(10, Byte.valueOf(b0)); } - public boolean func_181026_s() { - return (this.dataWatcher.getWatchableObjectByte(10) & 16) != 0; - } - - public void setHeadRotation(Rotations parRotations) { - this.headRotation = parRotations; - this.dataWatcher.updateObject(11, parRotations); - } - - public void setBodyRotation(Rotations parRotations) { - this.bodyRotation = parRotations; - this.dataWatcher.updateObject(12, parRotations); - } - - public void setLeftArmRotation(Rotations parRotations) { - this.leftArmRotation = parRotations; - this.dataWatcher.updateObject(13, parRotations); - } - public void setRightArmRotation(Rotations parRotations) { this.rightArmRotation = parRotations; this.dataWatcher.updateObject(14, parRotations); } - public void setLeftLegRotation(Rotations parRotations) { - this.leftLegRotation = parRotations; - this.dataWatcher.updateObject(15, parRotations); - } - public void setRightLegRotation(Rotations parRotations) { this.rightLegRotation = parRotations; this.dataWatcher.updateObject(16, parRotations); } - public Rotations getHeadRotation() { - return this.headRotation; + private void setShowArms(boolean parFlag) { + byte b0 = this.dataWatcher.getWatchableObjectByte(10); + if (parFlag) { + b0 = (byte) (b0 | 4); + } else { + b0 = (byte) (b0 & -5); + } + + this.dataWatcher.updateObject(10, Byte.valueOf(b0)); } - public Rotations getBodyRotation() { - return this.bodyRotation; + private void setSmall(boolean parFlag) { + byte b0 = this.dataWatcher.getWatchableObjectByte(10); + if (parFlag) { + b0 = (byte) (b0 | 1); + } else { + b0 = (byte) (b0 & -2); + } + + this.dataWatcher.updateObject(10, Byte.valueOf(b0)); } - public Rotations getLeftArmRotation() { - return this.leftArmRotation; - } - - public Rotations getRightArmRotation() { - return this.rightArmRotation; - } - - public Rotations getLeftLegRotation() { - return this.leftLegRotation; - } - - public Rotations getRightLegRotation() { - return this.rightLegRotation; - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. + /** + * + Clears potion metadata values if the entity has no potion effects. + * Otherwise, updates potion effect color, ambience, and invisibility metadata + * values */ - public boolean canBeCollidedWith() { - return super.canBeCollidedWith() && !this.func_181026_s(); + protected void updatePotionMetadata() { + this.setInvisible(this.canInteract); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.contents.length; ++i) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + if (this.contents[i] != null) { + this.contents[i].writeToNBT(nbttagcompound1); + } + + nbttaglist.appendTag(nbttagcompound1); + } + + nbttagcompound.setTag("Equipment", nbttaglist); + if (this.getAlwaysRenderNameTag() + && (this.getCustomNameTag() == null || this.getCustomNameTag().length() == 0)) { + nbttagcompound.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); + } + + nbttagcompound.setBoolean("Invisible", this.isInvisible()); + nbttagcompound.setBoolean("Small", this.isSmall()); + nbttagcompound.setBoolean("ShowArms", this.getShowArms()); + nbttagcompound.setInteger("DisabledSlots", this.disabledSlots); + nbttagcompound.setBoolean("NoGravity", this.hasNoGravity()); + nbttagcompound.setBoolean("NoBasePlate", this.hasNoBasePlate()); + if (this.func_181026_s()) { + nbttagcompound.setBoolean("Marker", this.func_181026_s()); + } + + nbttagcompound.setTag("Pose", this.readPoseFromNBT()); + } + + /** + * + Saves the pose to an NBTTagCompound. + */ + private void writePoseToNBT(NBTTagCompound tagCompound) { + NBTTagList nbttaglist = tagCompound.getTagList("Head", 5); + if (nbttaglist.tagCount() > 0) { + this.setHeadRotation(new Rotations(nbttaglist)); + } else { + this.setHeadRotation(DEFAULT_HEAD_ROTATION); + } + + NBTTagList nbttaglist1 = tagCompound.getTagList("Body", 5); + if (nbttaglist1.tagCount() > 0) { + this.setBodyRotation(new Rotations(nbttaglist1)); + } else { + this.setBodyRotation(DEFAULT_BODY_ROTATION); + } + + NBTTagList nbttaglist2 = tagCompound.getTagList("LeftArm", 5); + if (nbttaglist2.tagCount() > 0) { + this.setLeftArmRotation(new Rotations(nbttaglist2)); + } else { + this.setLeftArmRotation(DEFAULT_LEFTARM_ROTATION); + } + + NBTTagList nbttaglist3 = tagCompound.getTagList("RightArm", 5); + if (nbttaglist3.tagCount() > 0) { + this.setRightArmRotation(new Rotations(nbttaglist3)); + } else { + this.setRightArmRotation(DEFAULT_RIGHTARM_ROTATION); + } + + NBTTagList nbttaglist4 = tagCompound.getTagList("LeftLeg", 5); + if (nbttaglist4.tagCount() > 0) { + this.setLeftLegRotation(new Rotations(nbttaglist4)); + } else { + this.setLeftLegRotation(DEFAULT_LEFTLEG_ROTATION); + } + + NBTTagList nbttaglist5 = tagCompound.getTagList("RightLeg", 5); + if (nbttaglist5.tagCount() > 0) { + this.setRightLegRotation(new Rotations(nbttaglist5)); + } else { + this.setRightLegRotation(DEFAULT_RIGHTLEG_ROTATION); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityBoat.java b/src/game/java/net/minecraft/entity/item/EntityBoat.java index f72a57ab..c1ebfb22 100644 --- a/src/game/java/net/minecraft/entity/item/EntityBoat.java +++ b/src/game/java/net/minecraft/entity/item/EntityBoat.java @@ -1,6 +1,7 @@ package net.minecraft.entity.item; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; @@ -18,22 +19,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -59,45 +63,6 @@ public class EntityBoat extends Entity { this.setSize(1.5F, 0.6F); } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - - protected void entityInit() { - this.dataWatcher.addObject(17, Integer.valueOf(0)); - this.dataWatcher.addObject(18, Integer.valueOf(1)); - this.dataWatcher.addObject(19, Float.valueOf(0.0F)); - } - - /**+ - * Returns a boundingBox used to collide the entity with other - * entities and blocks. This enables the entity to be pushable - * on contact, like boats or minecarts. - */ - public AxisAlignedBB getCollisionBox(Entity entity) { - return entity.getEntityBoundingBox(); - } - - /**+ - * Returns the collision bounding box for this entity - */ - public AxisAlignedBB getCollisionBoundingBox() { - return this.getEntityBoundingBox(); - } - - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. - */ - public boolean canBePushed() { - return true; - } - public EntityBoat(World worldIn, double parDouble1, double parDouble2, double parDouble3) { this(worldIn); this.setPosition(parDouble1, parDouble2, parDouble3); @@ -109,16 +74,8 @@ public class EntityBoat extends Entity { this.prevPosZ = parDouble3; } - /**+ - * Returns the Y offset from the entity's position for any - * entity riding this one. - */ - public double getMountedYOffset() { - return -0.3D; - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (this.isEntityInvulnerable(damagesource)) { @@ -153,73 +110,99 @@ public class EntityBoat extends Entity { } } - /**+ - * Setups the entity to do the hurt animation. Only used by - * packets in multiplayer. - */ - public void performHurtAnimation() { - this.setForwardDirection(-this.getForwardDirection()); - this.setTimeSinceHit(10); - this.setDamageTaken(this.getDamageTaken() * 11.0F); - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. */ public boolean canBeCollidedWith() { return !this.isDead; } - public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean flag) { - if (flag && this.riddenByEntity != null) { - this.prevPosX = this.posX = d0; - this.prevPosY = this.posY = d1; - this.prevPosZ = this.posZ = d2; - this.rotationYaw = f; - this.rotationPitch = f1; - this.boatPosRotationIncrements = 0; - this.setPosition(d0, d1, d2); - this.motionX = this.velocityX = 0.0D; - this.motionY = this.velocityY = 0.0D; - this.motionZ = this.velocityZ = 0.0D; - } else { - if (this.isBoatEmpty) { - this.boatPosRotationIncrements = i + 5; - } else { - double d3 = d0 - this.posX; - double d4 = d1 - this.posY; - double d5 = d2 - this.posZ; - double d6 = d3 * d3 + d4 * d4 + d5 * d5; - if (d6 <= 1.0D) { - return; - } + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. + */ + public boolean canBePushed() { + return true; + } - this.boatPosRotationIncrements = 3; + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + + protected void entityInit() { + this.dataWatcher.addObject(17, Integer.valueOf(0)); + this.dataWatcher.addObject(18, Integer.valueOf(1)); + this.dataWatcher.addObject(19, Float.valueOf(0.0F)); + } + + /** + * + Returns the collision bounding box for this entity + */ + public AxisAlignedBB getCollisionBoundingBox() { + return this.getEntityBoundingBox(); + } + + /** + * + Returns a boundingBox used to collide the entity with other entities and + * blocks. This enables the entity to be pushable on contact, like boats or + * minecarts. + */ + public AxisAlignedBB getCollisionBox(Entity entity) { + return entity.getEntityBoundingBox(); + } + + /** + * + Gets the damage taken from the last hit. + */ + public float getDamageTaken() { + return this.dataWatcher.getWatchableObjectFloat(19); + } + + /** + * + Gets the forward direction of the entity. + */ + public int getForwardDirection() { + return this.dataWatcher.getWatchableObjectInt(18); + } + + /** + * + Returns the Y offset from the entity's position for any entity riding this + * one. + */ + public double getMountedYOffset() { + return -0.3D; + } + + /** + * + Gets the time since the last hit. + */ + public int getTimeSinceHit() { + return this.dataWatcher.getWatchableObjectInt(17); + } + + /** + * + First layer of player interaction + */ + public boolean interactFirst(EntityPlayer entityplayer) { + if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityPlayer + && this.riddenByEntity != entityplayer) { + return true; + } else { + if (!this.worldObj.isRemote) { + entityplayer.mountEntity(this); } - this.boatX = d0; - this.boatY = d1; - this.boatZ = d2; - this.boatYaw = (double) f; - this.boatPitch = (double) f1; - this.motionX = this.velocityX; - this.motionY = this.velocityY; - this.motionZ = this.velocityZ; + return true; } } - /**+ - * Sets the velocity to the args. Args: x, y, z - */ - public void setVelocity(double d0, double d1, double d2) { - this.velocityX = this.motionX = d0; - this.velocityY = this.motionY = d1; - this.velocityZ = this.motionZ = d2; - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -428,45 +411,97 @@ public class EntityBoat extends Entity { } } - public void updateRiderPosition() { - if (this.riddenByEntity != null) { - double d0 = Math.cos((double) this.rotationYaw * 3.141592653589793D / 180.0D) * 0.4D; - double d1 = Math.sin((double) this.rotationYaw * 3.141592653589793D / 180.0D) * 0.4D; - this.riddenByEntity.setPosition(this.posX + d0, - this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset(), this.posZ + d1); - } - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Setups the entity to do the hurt animation. Only used by packets in + * multiplayer. */ - protected void writeEntityToNBT(NBTTagCompound var1) { + public void performHurtAnimation() { + this.setForwardDirection(-this.getForwardDirection()); + this.setTimeSinceHit(10); + this.setDamageTaken(this.getDamageTaken() * 11.0F); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound var1) { } - /**+ - * First layer of player interaction + /** + * + Sets the damage taken from the last hit. */ - public boolean interactFirst(EntityPlayer entityplayer) { - if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityPlayer - && this.riddenByEntity != entityplayer) { - return true; + public void setDamageTaken(float parFloat1) { + this.dataWatcher.updateObject(19, Float.valueOf(parFloat1)); + } + + /** + * + Sets the forward direction of the entity. + */ + public void setForwardDirection(int parInt1) { + this.dataWatcher.updateObject(18, Integer.valueOf(parInt1)); + } + + /** + * + true if no player in boat + */ + public void setIsBoatEmpty(boolean parFlag) { + this.isBoatEmpty = parFlag; + } + + public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean flag) { + if (flag && this.riddenByEntity != null) { + this.prevPosX = this.posX = d0; + this.prevPosY = this.posY = d1; + this.prevPosZ = this.posZ = d2; + this.rotationYaw = f; + this.rotationPitch = f1; + this.boatPosRotationIncrements = 0; + this.setPosition(d0, d1, d2); + this.motionX = this.velocityX = 0.0D; + this.motionY = this.velocityY = 0.0D; + this.motionZ = this.velocityZ = 0.0D; } else { - if (!this.worldObj.isRemote) { - entityplayer.mountEntity(this); + if (this.isBoatEmpty) { + this.boatPosRotationIncrements = i + 5; + } else { + double d3 = d0 - this.posX; + double d4 = d1 - this.posY; + double d5 = d2 - this.posZ; + double d6 = d3 * d3 + d4 * d4 + d5 * d5; + if (d6 <= 1.0D) { + return; + } + + this.boatPosRotationIncrements = 3; } - return true; + this.boatX = d0; + this.boatY = d1; + this.boatZ = d2; + this.boatYaw = (double) f; + this.boatPitch = (double) f1; + this.motionX = this.velocityX; + this.motionY = this.velocityY; + this.motionZ = this.velocityZ; } } + /** + * + Sets the time to count down from since the last time entity was hit. + */ + public void setTimeSinceHit(int parInt1) { + this.dataWatcher.updateObject(17, Integer.valueOf(parInt1)); + } + + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double d0, double d1, double d2) { + this.velocityX = this.motionX = d0; + this.velocityY = this.motionY = d1; + this.velocityZ = this.motionZ = d2; + } + protected void updateFallState(double d0, boolean flag, Block var4, BlockPos var5) { if (flag) { if (this.fallDistance > 3.0F) { @@ -493,53 +528,18 @@ public class EntityBoat extends Entity { } - /**+ - * Sets the damage taken from the last hit. - */ - public void setDamageTaken(float parFloat1) { - this.dataWatcher.updateObject(19, Float.valueOf(parFloat1)); + public void updateRiderPosition() { + if (this.riddenByEntity != null) { + double d0 = Math.cos((double) this.rotationYaw * 3.141592653589793D / 180.0D) * 0.4D; + double d1 = Math.sin((double) this.rotationYaw * 3.141592653589793D / 180.0D) * 0.4D; + this.riddenByEntity.setPosition(this.posX + d0, + this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset(), this.posZ + d1); + } } - /**+ - * Gets the damage taken from the last hit. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public float getDamageTaken() { - return this.dataWatcher.getWatchableObjectFloat(19); - } - - /**+ - * Sets the time to count down from since the last time entity - * was hit. - */ - public void setTimeSinceHit(int parInt1) { - this.dataWatcher.updateObject(17, Integer.valueOf(parInt1)); - } - - /**+ - * Gets the time since the last hit. - */ - public int getTimeSinceHit() { - return this.dataWatcher.getWatchableObjectInt(17); - } - - /**+ - * Sets the forward direction of the entity. - */ - public void setForwardDirection(int parInt1) { - this.dataWatcher.updateObject(18, Integer.valueOf(parInt1)); - } - - /**+ - * Gets the forward direction of the entity. - */ - public int getForwardDirection() { - return this.dataWatcher.getWatchableObjectInt(18); - } - - /**+ - * true if no player in boat - */ - public void setIsBoatEmpty(boolean parFlag) { - this.isBoatEmpty = parFlag; + protected void writeEntityToNBT(NBTTagCompound var1) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityEnderCrystal.java b/src/game/java/net/minecraft/entity/item/EntityEnderCrystal.java index 4d52a24f..b2f9a7c0 100644 --- a/src/game/java/net/minecraft/entity/item/EntityEnderCrystal.java +++ b/src/game/java/net/minecraft/entity/item/EntityEnderCrystal.java @@ -9,22 +9,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.WorldProviderEnd; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,62 +49,8 @@ public class EntityEnderCrystal extends Entity { this.setPosition(parDouble1, parDouble2, parDouble3); } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - - protected void entityInit() { - this.dataWatcher.addObject(8, Integer.valueOf(this.health)); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - ++this.innerRotation; - this.dataWatcher.updateObject(8, Integer.valueOf(this.health)); - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.posY); - int k = MathHelper.floor_double(this.posZ); - if (this.worldObj.provider instanceof WorldProviderEnd - && this.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock() != Blocks.fire) { - this.worldObj.setBlockState(new BlockPos(i, j, k), Blocks.fire.getDefaultState()); - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound var1) { - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - protected void readEntityFromNBT(NBTTagCompound var1) { - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return true; - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float var2) { if (this.isEntityInvulnerable(damagesource)) { @@ -120,4 +69,55 @@ public class EntityEnderCrystal extends Entity { return true; } } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return true; + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + + protected void entityInit() { + this.dataWatcher.addObject(8, Integer.valueOf(this.health)); + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + ++this.innerRotation; + this.dataWatcher.updateObject(8, Integer.valueOf(this.health)); + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.posY); + int k = MathHelper.floor_double(this.posZ); + if (this.worldObj.provider instanceof WorldProviderEnd + && this.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock() != Blocks.fire) { + this.worldObj.setBlockState(new BlockPos(i, j, k), Blocks.fire.getDefaultState()); + } + + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + protected void readEntityFromNBT(NBTTagCompound var1) { + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound var1) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityEnderEye.java b/src/game/java/net/minecraft/entity/item/EntityEnderEye.java index 7d0802ce..3ecd0f77 100644 --- a/src/game/java/net/minecraft/entity/item/EntityEnderEye.java +++ b/src/game/java/net/minecraft/entity/item/EntityEnderEye.java @@ -10,22 +10,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,13 +45,42 @@ public class EntityEnderEye extends Entity { this.setSize(0.25F, 0.25F); } + public EntityEnderEye(World worldIn, double x, double y, double z) { + super(worldIn); + this.despawnTimer = 0; + this.setSize(0.25F, 0.25F); + this.setPosition(x, y, z); + } + + /** + * + If returns false, the item will not inflict any damage against entities. + */ + public boolean canAttackWithItem() { + return false; + } + protected void entityInit() { } - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float var1) { + return 1.0F; + } + + public int getBrightnessForRender(float var1) { + return 15728880; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 0.5f; + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance */ public boolean isInRangeToRenderDist(double d0) { double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; @@ -60,13 +92,6 @@ public class EntityEnderEye extends Entity { return d0 < d1 * d1; } - public EntityEnderEye(World worldIn, double x, double y, double z) { - super(worldIn); - this.despawnTimer = 0; - this.setSize(0.25F, 0.25F); - this.setPosition(x, y, z); - } - public void moveTowards(BlockPos parBlockPos) { double d0 = (double) parBlockPos.getX(); int i = parBlockPos.getY(); @@ -88,25 +113,8 @@ public class EntityEnderEye extends Entity { this.shatterOrDrop = this.rand.nextInt(5) > 0; } - /**+ - * Sets the velocity to the args. Args: x, y, z - */ - public void setVelocity(double d0, double d1, double d2) { - this.motionX = d0; - this.motionY = d1; - this.motionZ = d2; - if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { - float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); - this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D - / 3.1415927410125732D); - } - - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.lastTickPosX = this.posX; @@ -191,31 +199,12 @@ public class EntityEnderEye extends Entity { } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound var1) { - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound var1) { } - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float var1) { - return 1.0F; - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 0.5f; - } - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, double renderY, double renderZ, float partialTicks, boolean isInFrustum) { super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, @@ -227,15 +216,26 @@ public class EntityEnderEye extends Entity { } } - public int getBrightnessForRender(float var1) { - return 15728880; + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double d0, double d1, double d2) { + this.motionX = d0; + this.motionY = d1; + this.motionZ = d2; + if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { + float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); + this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D + / 3.1415927410125732D); + } + } - /**+ - * If returns false, the item will not inflict any damage - * against entities. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean canAttackWithItem() { - return false; + public void writeEntityToNBT(NBTTagCompound var1) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityEnderPearl.java b/src/game/java/net/minecraft/entity/item/EntityEnderPearl.java index ff3a89d0..fed7ae9d 100644 --- a/src/game/java/net/minecraft/entity/item/EntityEnderPearl.java +++ b/src/game/java/net/minecraft/entity/item/EntityEnderPearl.java @@ -11,22 +11,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,17 +41,17 @@ public class EntityEnderPearl extends EntityThrowable { super(parWorld); } + public EntityEnderPearl(World worldIn, double parDouble1, double parDouble2, double parDouble3) { + super(worldIn, parDouble1, parDouble2, parDouble3); + } + public EntityEnderPearl(World worldIn, EntityLivingBase parEntityLivingBase) { super(worldIn, parEntityLivingBase); this.field_181555_c = parEntityLivingBase; } - public EntityEnderPearl(World worldIn, double parDouble1, double parDouble2, double parDouble3) { - super(worldIn, parDouble1, parDouble2, parDouble3); - } - - /**+ - * Called when this EntityThrowable hits a block or entity. + /** + * + Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { EntityLivingBase entitylivingbase = this.getThrower(); @@ -97,8 +100,8 @@ public class EntityEnderPearl extends EntityThrowable { } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { EntityLivingBase entitylivingbase = this.getThrower(); diff --git a/src/game/java/net/minecraft/entity/item/EntityExpBottle.java b/src/game/java/net/minecraft/entity/item/EntityExpBottle.java index 291a3805..8a8b103c 100644 --- a/src/game/java/net/minecraft/entity/item/EntityExpBottle.java +++ b/src/game/java/net/minecraft/entity/item/EntityExpBottle.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,32 +34,31 @@ public class EntityExpBottle extends EntityThrowable { super(worldIn); } - public EntityExpBottle(World worldIn, EntityLivingBase parEntityLivingBase) { - super(worldIn, parEntityLivingBase); - } - public EntityExpBottle(World worldIn, double parDouble1, double parDouble2, double parDouble3) { super(worldIn, parDouble1, parDouble2, parDouble3); } - /**+ - * Gets the amount of gravity to apply to the thrown entity with - * each tick. + public EntityExpBottle(World worldIn, EntityLivingBase parEntityLivingBase) { + super(worldIn, parEntityLivingBase); + } + + /** + * + Gets the amount of gravity to apply to the thrown entity with each tick. */ protected float getGravityVelocity() { return 0.07F; } - protected float getVelocity() { - return 0.7F; - } - protected float getInaccuracy() { return -20.0F; } - /**+ - * Called when this EntityThrowable hits a block or entity. + protected float getVelocity() { + return 0.7F; + } + + /** + * + Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition var1) { if (!this.worldObj.isRemote) { diff --git a/src/game/java/net/minecraft/entity/item/EntityFallingBlock.java b/src/game/java/net/minecraft/entity/item/EntityFallingBlock.java index a032defb..7f79c7b1 100644 --- a/src/game/java/net/minecraft/entity/item/EntityFallingBlock.java +++ b/src/game/java/net/minecraft/entity/item/EntityFallingBlock.java @@ -1,7 +1,9 @@ package net.minecraft.entity.item; -import com.google.common.collect.Lists; import java.util.ArrayList; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.BlockAnvil; import net.minecraft.block.BlockFalling; @@ -22,22 +24,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -70,10 +75,35 @@ public class EntityFallingBlock extends Entity { this.prevPosZ = z; } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops + public void addEntityCrashInfo(CrashReportCategory crashreportcategory) { + super.addEntityCrashInfo(crashreportcategory); + if (this.fallTile != null) { + Block block = this.fallTile.getBlock(); + crashreportcategory.addCrashSection("Immitating block ID", Integer.valueOf(Block.getIdFromBlock(block))); + crashreportcategory.addCrashSection("Immitating block data", + Integer.valueOf(block.getMetaFromState(this.fallTile))); + } + + } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return !this.isDead; + } + + /** + * + Return whether this entity should be rendered as on fire. + */ + public boolean canRenderOnFire() { + return false; + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; @@ -82,16 +112,45 @@ public class EntityFallingBlock extends Entity { protected void entityInit() { } - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return !this.isDead; + public void fall(float f, float var2) { + Block block = this.fallTile.getBlock(); + if (this.hurtEntities) { + int i = MathHelper.ceiling_float_int(f - 1.0F); + if (i > 0) { + ArrayList arraylist = Lists.newArrayList( + this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox())); + boolean flag = block == Blocks.anvil; + DamageSource damagesource = flag ? DamageSource.anvil : DamageSource.fallingBlock; + + for (int j = 0, l = arraylist.size(); j < l; ++j) { + arraylist.get(j).attackEntityFrom(damagesource, (float) Math + .min(MathHelper.floor_float((float) i * this.fallHurtAmount), this.fallHurtMax)); + } + + if (flag && (double) this.rand.nextFloat() < 0.05000000074505806D + (double) i * 0.05D) { + int j = ((Integer) this.fallTile.getValue(BlockAnvil.DAMAGE)).intValue(); + ++j; + if (j > 2) { + this.canSetAsBlock = true; + } else { + this.fallTile = this.fallTile.withProperty(BlockAnvil.DAMAGE, Integer.valueOf(j)); + } + } + } + } + } - /**+ - * Called to update the entity's position/logic. + public IBlockState getBlock() { + return this.fallTile; + } + + public World getWorldObj() { + return this.worldObj; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { Block block = this.fallTile.getBlock(); @@ -168,58 +227,8 @@ public class EntityFallingBlock extends Entity { } } - public void fall(float f, float var2) { - Block block = this.fallTile.getBlock(); - if (this.hurtEntities) { - int i = MathHelper.ceiling_float_int(f - 1.0F); - if (i > 0) { - ArrayList arraylist = Lists.newArrayList( - this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox())); - boolean flag = block == Blocks.anvil; - DamageSource damagesource = flag ? DamageSource.anvil : DamageSource.fallingBlock; - - for (int j = 0, l = arraylist.size(); j < l; ++j) { - arraylist.get(j).attackEntityFrom(damagesource, (float) Math - .min(MathHelper.floor_float((float) i * this.fallHurtAmount), this.fallHurtMax)); - } - - if (flag && (double) this.rand.nextFloat() < 0.05000000074505806D + (double) i * 0.05D) { - int j = ((Integer) this.fallTile.getValue(BlockAnvil.DAMAGE)).intValue(); - ++j; - if (j > 2) { - this.canSetAsBlock = true; - } else { - this.fallTile = this.fallTile.withProperty(BlockAnvil.DAMAGE, Integer.valueOf(j)); - } - } - } - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - Block block = this.fallTile != null ? this.fallTile.getBlock() : Blocks.air; - ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(block); - nbttagcompound.setString("Block", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound.setByte("Data", (byte) block.getMetaFromState(this.fallTile)); - nbttagcompound.setByte("Time", (byte) this.fallTime); - nbttagcompound.setBoolean("DropItem", this.shouldDropItem); - nbttagcompound.setBoolean("HurtEntities", this.hurtEntities); - nbttagcompound.setFloat("FallHurtAmount", this.fallHurtAmount); - nbttagcompound.setInteger("FallHurtMax", this.fallHurtMax); - if (this.tileEntityData != null) { - nbttagcompound.setTag("TileEntityData", this.tileEntityData); - } - - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { int i = nbttagcompound.getByte("Data") & 255; @@ -255,33 +264,26 @@ public class EntityFallingBlock extends Entity { } - public World getWorldObj() { - return this.worldObj; - } - public void setHurtEntities(boolean parFlag) { this.hurtEntities = parFlag; } - /**+ - * Return whether this entity should be rendered as on fire. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean canRenderOnFire() { - return false; - } - - public void addEntityCrashInfo(CrashReportCategory crashreportcategory) { - super.addEntityCrashInfo(crashreportcategory); - if (this.fallTile != null) { - Block block = this.fallTile.getBlock(); - crashreportcategory.addCrashSection("Immitating block ID", Integer.valueOf(Block.getIdFromBlock(block))); - crashreportcategory.addCrashSection("Immitating block data", - Integer.valueOf(block.getMetaFromState(this.fallTile))); + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + Block block = this.fallTile != null ? this.fallTile.getBlock() : Blocks.air; + ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(block); + nbttagcompound.setString("Block", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound.setByte("Data", (byte) block.getMetaFromState(this.fallTile)); + nbttagcompound.setByte("Time", (byte) this.fallTime); + nbttagcompound.setBoolean("DropItem", this.shouldDropItem); + nbttagcompound.setBoolean("HurtEntities", this.hurtEntities); + nbttagcompound.setFloat("FallHurtAmount", this.fallHurtAmount); + nbttagcompound.setInteger("FallHurtMax", this.fallHurtMax); + if (this.tileEntityData != null) { + nbttagcompound.setTag("TileEntityData", this.tileEntityData); } } - - public IBlockState getBlock() { - return this.fallTile; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityFireworkRocket.java b/src/game/java/net/minecraft/entity/item/EntityFireworkRocket.java index fecc8cf9..25f1c6a5 100644 --- a/src/game/java/net/minecraft/entity/item/EntityFireworkRocket.java +++ b/src/game/java/net/minecraft/entity/item/EntityFireworkRocket.java @@ -7,22 +7,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,19 +39,6 @@ public class EntityFireworkRocket extends Entity { this.setSize(0.25F, 0.25F); } - protected void entityInit() { - this.dataWatcher.addObjectByDataType(8, 5); - } - - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double d0) { - return d0 < 4096.0D; - } - public EntityFireworkRocket(World worldIn, double x, double y, double z, ItemStack givenItem) { super(worldIn); this.fireworkAge = 0; @@ -70,25 +60,58 @@ public class EntityFireworkRocket extends Entity { this.lifetime = 10 * i + this.rand.nextInt(6) + this.rand.nextInt(7); } - /**+ - * Sets the velocity to the args. Args: x, y, z + /** + * + If returns false, the item will not inflict any damage against entities. */ - public void setVelocity(double d0, double d1, double d2) { - this.motionX = d0; - this.motionY = d1; - this.motionZ = d2; - if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { - float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); - this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D - / 3.1415927410125732D); - } - + public boolean canAttackWithItem() { + return false; } - /**+ - * Called to update the entity's position/logic. + protected void entityInit() { + this.dataWatcher.addObjectByDataType(8, 5); + } + + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float f) { + return super.getBrightness(f); + } + + public int getBrightnessForRender(float f) { + return super.getBrightnessForRender(f); + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 1.0f; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 17 && this.worldObj.isRemote) { + ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); + NBTTagCompound nbttagcompound = null; + if (itemstack != null && itemstack.hasTagCompound()) { + nbttagcompound = itemstack.getTagCompound().getCompoundTag("Fireworks"); + } + + this.worldObj.makeFireworks(this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ, + nbttagcompound); + } + + super.handleStatusUpdate(b0); + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance + */ + public boolean isInRangeToRenderDist(double d0) { + return d0 < 4096.0D; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.lastTickPosX = this.posX; @@ -141,40 +164,8 @@ public class EntityFireworkRocket extends Entity { } - public void handleStatusUpdate(byte b0) { - if (b0 == 17 && this.worldObj.isRemote) { - ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); - NBTTagCompound nbttagcompound = null; - if (itemstack != null && itemstack.hasTagCompound()) { - nbttagcompound = itemstack.getTagCompound().getCompoundTag("Fireworks"); - } - - this.worldObj.makeFireworks(this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ, - nbttagcompound); - } - - super.handleStatusUpdate(b0); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("Life", this.fireworkAge); - nbttagcompound.setInteger("LifeTime", this.lifetime); - ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); - if (itemstack != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - itemstack.writeToNBT(nbttagcompound1); - nbttagcompound.setTag("FireworksItem", nbttagcompound1); - } - - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.fireworkAge = nbttagcompound.getInteger("Life"); @@ -189,26 +180,35 @@ public class EntityFireworkRocket extends Entity { } - /**+ - * Gets how bright this entity is. + /** + * + Sets the velocity to the args. Args: x, y, z */ - public float getBrightness(float f) { - return super.getBrightness(f); + public void setVelocity(double d0, double d1, double d2) { + this.motionX = d0; + this.motionY = d1; + this.motionZ = d2; + if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { + float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); + this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D + / 3.1415927410125732D); + } + } - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 1.0f; - } - - public int getBrightnessForRender(float f) { - return super.getBrightnessForRender(f); - } - - /**+ - * If returns false, the item will not inflict any damage - * against entities. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean canAttackWithItem() { - return false; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("Life", this.fireworkAge); + nbttagcompound.setInteger("LifeTime", this.lifetime); + ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); + if (itemstack != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + itemstack.writeToNBT(nbttagcompound1); + nbttagcompound.setTag("FireworksItem", nbttagcompound1); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityItem.java b/src/game/java/net/minecraft/entity/item/EntityItem.java index 4638cadb..00657f3c 100644 --- a/src/game/java/net/minecraft/entity/item/EntityItem.java +++ b/src/game/java/net/minecraft/entity/item/EntityItem.java @@ -20,22 +20,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,6 +52,16 @@ public class EntityItem extends Entity { private String owner; public float hoverStart; + public boolean eaglerEmissiveFlag = false; + + public EntityItem(World worldIn) { + super(worldIn); + this.health = 5; + this.hoverStart = (float) (Math.random() * 3.141592653589793D * 2.0D); + this.setSize(0.25F, 0.25F); + this.setEntityItemStack(new ItemStack(Blocks.air, 0)); + } + public EntityItem(World worldIn, double x, double y, double z) { super(worldIn); this.health = 5; @@ -66,29 +79,232 @@ public class EntityItem extends Entity { this.setEntityItemStack(stack); } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else if (this.getEntityItem() != null && this.getEntityItem().getItem() == Items.nether_star + && damagesource.isExplosion()) { + return false; + } else { + this.setBeenAttacked(); + this.health = (int) ((float) this.health - f); + if (this.health <= 0) { + this.setDead(); + } + + return false; + } + } + + /** + * + If returns false, the item will not inflict any damage against entities. + */ + public boolean canAttackWithItem() { + return false; + } + + public boolean cannotPickup() { + return this.delayBeforeCanPickup > 0; + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } - public EntityItem(World worldIn) { - super(worldIn); - this.health = 5; - this.hoverStart = (float) (Math.random() * 3.141592653589793D * 2.0D); - this.setSize(0.25F, 0.25F); - this.setEntityItemStack(new ItemStack(Blocks.air, 0)); + /** + * + Tries to merge this item with the item passed as the parameter. Returns + * true if successful. Either this item or the other item will be removed from + * the world. + */ + private boolean combineItems(EntityItem other) { + if (other == this) { + return false; + } else if (other.isEntityAlive() && this.isEntityAlive()) { + ItemStack itemstack = this.getEntityItem(); + ItemStack itemstack1 = other.getEntityItem(); + if (this.delayBeforeCanPickup != 32767 && other.delayBeforeCanPickup != 32767) { + if (this.age != -32768 && other.age != -32768) { + if (itemstack1.getItem() != itemstack.getItem()) { + return false; + } else if (itemstack1.hasTagCompound() ^ itemstack.hasTagCompound()) { + return false; + } else if (itemstack1.hasTagCompound() + && !itemstack1.getTagCompound().equals(itemstack.getTagCompound())) { + return false; + } else if (itemstack1.getItem() == null) { + return false; + } else if (itemstack1.getItem().getHasSubtypes() + && itemstack1.getMetadata() != itemstack.getMetadata()) { + return false; + } else if (itemstack1.stackSize < itemstack.stackSize) { + return other.combineItems(this); + } else if (itemstack1.stackSize + itemstack.stackSize > itemstack1.getMaxStackSize()) { + return false; + } else { + itemstack1.stackSize += itemstack.stackSize; + other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup); + other.age = Math.min(other.age, this.age); + other.setEntityItemStack(itemstack1); + this.setDead(); + return true; + } + } else { + return false; + } + } else { + return false; + } + } else { + return false; + } + } + + /** + * + Will deal the specified amount of damage to the entity if the entity isn't + * immune to fire damage. Args: amountDamage + */ + protected void dealFireDamage(int i) { + this.attackEntityFrom(DamageSource.inFire, (float) i); } protected void entityInit() { this.getDataWatcher().addObjectByDataType(10, 5); } - /**+ - * Called to update the entity's position/logic. + public void func_174870_v() { + this.setInfinitePickupDelay(); + this.age = 5999; + } + + public int getAge() { + return this.age; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + ItemStack itm = this.getEntityItem(); + if (itm != null && itm.stackSize > 0) { + Item item = itm.getItem(); + if (item != null) { + float f2 = item.getHeldItemBrightnessEagler(itm) * 0.75f; + f = Math.min(f + f2 * 0.5f, 1.0f) + f2 * 0.5f; + } + } + return f; + } + + /** + * + Returns the ItemStack corresponding to the Entity (Note: if no item exists, + * will log an error but still return an ItemStack containing Block.stone) + */ + public ItemStack getEntityItem() { + ItemStack itemstack = this.getDataWatcher().getWatchableObjectItemStack(10); + if (itemstack == null) { + if (this.worldObj != null) { + logger.error("Item entity " + this.getEntityId() + " has no item?!"); + } + + return new ItemStack(Blocks.stone); + } else { + return itemstack; + } + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.hasCustomName() ? this.getCustomNameTag() + : StatCollector.translateToLocal("item." + this.getEntityItem().getUnlocalizedName()); + } + + public String getOwner() { + return this.owner; + } + + public String getThrower() { + return this.thrower; + } + + /** + * + Returns if this entity is in water and will end up adding the waters + * velocity to the entity + */ + public boolean handleWaterMovement() { + if (this.worldObj.handleMaterialAcceleration(this.getEntityBoundingBox(), Material.water, this)) { + if (!this.inWater && !this.firstUpdate) { + this.resetHeight(); + } + + this.inWater = true; + } else { + this.inWater = false; + } + + return this.inWater; + } + + /** + * + Called by a player entity when they collide with an entity + */ + public void onCollideWithPlayer(EntityPlayer entityplayer) { + if (!this.worldObj.isRemote) { + ItemStack itemstack = this.getEntityItem(); + int i = itemstack.stackSize; + if (this.delayBeforeCanPickup == 0 + && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityplayer.getName())) + && entityplayer.inventory.addItemStackToInventory(itemstack)) { + if (itemstack.getItem() == Item.getItemFromBlock(Blocks.log)) { + entityplayer.triggerAchievement(AchievementList.mineWood); + } + + if (itemstack.getItem() == Item.getItemFromBlock(Blocks.log2)) { + entityplayer.triggerAchievement(AchievementList.mineWood); + } + + if (itemstack.getItem() == Items.leather) { + entityplayer.triggerAchievement(AchievementList.killCow); + } + + if (itemstack.getItem() == Items.diamond) { + entityplayer.triggerAchievement(AchievementList.diamonds); + } + + if (itemstack.getItem() == Items.blaze_rod) { + entityplayer.triggerAchievement(AchievementList.blazeRod); + } + + if (itemstack.getItem() == Items.diamond && this.getThrower() != null) { + EntityPlayer entityplayer1 = this.worldObj.getPlayerEntityByName(this.getThrower()); + if (entityplayer1 != null && entityplayer1 != entityplayer) { + entityplayer1.triggerAchievement(AchievementList.diamondsToYou); + } + } + + if (!this.isSilent()) { + this.worldObj.playSoundAtEntity(entityplayer, "random.pop", 0.2F, + ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); + } + + entityplayer.onItemPickup(this, i); + if (itemstack.stackSize <= 0) { + this.setDead(); + } + } + + } + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { if (this.getEntityItem() == null) { @@ -147,147 +363,8 @@ public class EntityItem extends Entity { } } - /**+ - * Looks for other itemstacks nearby and tries to stack them - * together - */ - private void searchForOtherItemsNearby() { - List lst = this.worldObj.getEntitiesWithinAABB(EntityItem.class, - this.getEntityBoundingBox().expand(0.5D, 0.0D, 0.5D)); - for (int i = 0, l = lst.size(); i < l; ++i) { - this.combineItems(lst.get(i)); - } - - } - - /**+ - * Tries to merge this item with the item passed as the - * parameter. Returns true if successful. Either this item or - * the other item will be removed from the world. - */ - private boolean combineItems(EntityItem other) { - if (other == this) { - return false; - } else if (other.isEntityAlive() && this.isEntityAlive()) { - ItemStack itemstack = this.getEntityItem(); - ItemStack itemstack1 = other.getEntityItem(); - if (this.delayBeforeCanPickup != 32767 && other.delayBeforeCanPickup != 32767) { - if (this.age != -32768 && other.age != -32768) { - if (itemstack1.getItem() != itemstack.getItem()) { - return false; - } else if (itemstack1.hasTagCompound() ^ itemstack.hasTagCompound()) { - return false; - } else if (itemstack1.hasTagCompound() - && !itemstack1.getTagCompound().equals(itemstack.getTagCompound())) { - return false; - } else if (itemstack1.getItem() == null) { - return false; - } else if (itemstack1.getItem().getHasSubtypes() - && itemstack1.getMetadata() != itemstack.getMetadata()) { - return false; - } else if (itemstack1.stackSize < itemstack.stackSize) { - return other.combineItems(this); - } else if (itemstack1.stackSize + itemstack.stackSize > itemstack1.getMaxStackSize()) { - return false; - } else { - itemstack1.stackSize += itemstack.stackSize; - other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup); - other.age = Math.min(other.age, this.age); - other.setEntityItemStack(itemstack1); - this.setDead(); - return true; - } - } else { - return false; - } - } else { - return false; - } - } else { - return false; - } - } - - /**+ - * sets the age of the item so that it'll despawn one minute - * after it has been dropped (instead of five). Used when items - * are dropped from players in creative mode - */ - public void setAgeToCreativeDespawnTime() { - this.age = 4800; - } - - /**+ - * Returns if this entity is in water and will end up adding the - * waters velocity to the entity - */ - public boolean handleWaterMovement() { - if (this.worldObj.handleMaterialAcceleration(this.getEntityBoundingBox(), Material.water, this)) { - if (!this.inWater && !this.firstUpdate) { - this.resetHeight(); - } - - this.inWater = true; - } else { - this.inWater = false; - } - - return this.inWater; - } - - /**+ - * Will deal the specified amount of damage to the entity if the - * entity isn't immune to fire damage. Args: amountDamage - */ - protected void dealFireDamage(int i) { - this.attackEntityFrom(DamageSource.inFire, (float) i); - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else if (this.getEntityItem() != null && this.getEntityItem().getItem() == Items.nether_star - && damagesource.isExplosion()) { - return false; - } else { - this.setBeenAttacked(); - this.health = (int) ((float) this.health - f); - if (this.health <= 0) { - this.setDead(); - } - - return false; - } - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("Health", (short) ((byte) this.health)); - nbttagcompound.setShort("Age", (short) this.age); - nbttagcompound.setShort("PickupDelay", (short) this.delayBeforeCanPickup); - if (this.getThrower() != null) { - nbttagcompound.setString("Thrower", this.thrower); - } - - if (this.getOwner() != null) { - nbttagcompound.setString("Owner", this.owner); - } - - if (this.getEntityItem() != null) { - nbttagcompound.setTag("Item", this.getEntityItem().writeToNBT(new NBTTagCompound())); - } - - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.health = nbttagcompound.getShort("Health") & 255; @@ -312,77 +389,73 @@ public class EntityItem extends Entity { } - /**+ - * Called by a player entity when they collide with an entity + protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, + double renderY, double renderZ, float partialTicks, boolean isInFrustum) { + super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, + isInFrustum); + eaglerEmissiveFlag = Minecraft.getMinecraft().entityRenderer.renderItemEntityLight(this, 0.1f); + } + + /** + * + Looks for other itemstacks nearby and tries to stack them together */ - public void onCollideWithPlayer(EntityPlayer entityplayer) { - if (!this.worldObj.isRemote) { - ItemStack itemstack = this.getEntityItem(); - int i = itemstack.stackSize; - if (this.delayBeforeCanPickup == 0 - && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityplayer.getName())) - && entityplayer.inventory.addItemStackToInventory(itemstack)) { - if (itemstack.getItem() == Item.getItemFromBlock(Blocks.log)) { - entityplayer.triggerAchievement(AchievementList.mineWood); - } - - if (itemstack.getItem() == Item.getItemFromBlock(Blocks.log2)) { - entityplayer.triggerAchievement(AchievementList.mineWood); - } - - if (itemstack.getItem() == Items.leather) { - entityplayer.triggerAchievement(AchievementList.killCow); - } - - if (itemstack.getItem() == Items.diamond) { - entityplayer.triggerAchievement(AchievementList.diamonds); - } - - if (itemstack.getItem() == Items.blaze_rod) { - entityplayer.triggerAchievement(AchievementList.blazeRod); - } - - if (itemstack.getItem() == Items.diamond && this.getThrower() != null) { - EntityPlayer entityplayer1 = this.worldObj.getPlayerEntityByName(this.getThrower()); - if (entityplayer1 != null && entityplayer1 != entityplayer) { - entityplayer1.triggerAchievement(AchievementList.diamondsToYou); - } - } - - if (!this.isSilent()) { - this.worldObj.playSoundAtEntity(entityplayer, "random.pop", 0.2F, - ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); - } - - entityplayer.onItemPickup(this, i); - if (itemstack.stackSize <= 0) { - this.setDead(); - } - } - + private void searchForOtherItemsNearby() { + List lst = this.worldObj.getEntitiesWithinAABB(EntityItem.class, + this.getEntityBoundingBox().expand(0.5D, 0.0D, 0.5D)); + for (int i = 0, l = lst.size(); i < l; ++i) { + this.combineItems(lst.get(i)); } + } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + /** + * + sets the age of the item so that it'll despawn one minute after it has been + * dropped (instead of five). Used when items are dropped from players in + * creative mode */ - public String getName() { - return this.hasCustomName() ? this.getCustomNameTag() - : StatCollector.translateToLocal("item." + this.getEntityItem().getUnlocalizedName()); + public void setAgeToCreativeDespawnTime() { + this.age = 4800; } - /**+ - * If returns false, the item will not inflict any damage - * against entities. + public void setDefaultPickupDelay() { + this.delayBeforeCanPickup = 10; + } + + /** + * + Sets the ItemStack for this entity */ - public boolean canAttackWithItem() { - return false; + public void setEntityItemStack(ItemStack stack) { + this.getDataWatcher().updateObject(10, stack); + this.getDataWatcher().setObjectWatched(10); } - /**+ - * Teleports the entity to another dimension. Params: Dimension - * number to teleport to + public void setInfinitePickupDelay() { + this.delayBeforeCanPickup = 32767; + } + + public void setNoDespawn() { + this.age = -6000; + } + + public void setNoPickupDelay() { + this.delayBeforeCanPickup = 0; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public void setPickupDelay(int ticks) { + this.delayBeforeCanPickup = ticks; + } + + public void setThrower(String thrower) { + this.thrower = thrower; + } + + /** + * + Teleports the entity to another dimension. Params: Dimension number to + * teleport to */ public void travelToDimension(int i) { super.travelToDimension(i); @@ -392,100 +465,24 @@ public class EntityItem extends Entity { } - /**+ - * Returns the ItemStack corresponding to the Entity (Note: if - * no item exists, will log an error but still return an - * ItemStack containing Block.stone) + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public ItemStack getEntityItem() { - ItemStack itemstack = this.getDataWatcher().getWatchableObjectItemStack(10); - if (itemstack == null) { - if (this.worldObj != null) { - logger.error("Item entity " + this.getEntityId() + " has no item?!"); - } - - return new ItemStack(Blocks.stone); - } else { - return itemstack; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("Health", (short) ((byte) this.health)); + nbttagcompound.setShort("Age", (short) this.age); + nbttagcompound.setShort("PickupDelay", (short) this.delayBeforeCanPickup); + if (this.getThrower() != null) { + nbttagcompound.setString("Thrower", this.thrower); } - } - /**+ - * Sets the ItemStack for this entity - */ - public void setEntityItemStack(ItemStack stack) { - this.getDataWatcher().updateObject(10, stack); - this.getDataWatcher().setObjectWatched(10); - } - - public String getOwner() { - return this.owner; - } - - public void setOwner(String owner) { - this.owner = owner; - } - - public String getThrower() { - return this.thrower; - } - - public void setThrower(String thrower) { - this.thrower = thrower; - } - - public int getAge() { - return this.age; - } - - public void setDefaultPickupDelay() { - this.delayBeforeCanPickup = 10; - } - - public void setNoPickupDelay() { - this.delayBeforeCanPickup = 0; - } - - public void setInfinitePickupDelay() { - this.delayBeforeCanPickup = 32767; - } - - public void setPickupDelay(int ticks) { - this.delayBeforeCanPickup = ticks; - } - - public boolean cannotPickup() { - return this.delayBeforeCanPickup > 0; - } - - public void setNoDespawn() { - this.age = -6000; - } - - public void func_174870_v() { - this.setInfinitePickupDelay(); - this.age = 5999; - } - - public boolean eaglerEmissiveFlag = false; - - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, - double renderY, double renderZ, float partialTicks, boolean isInFrustum) { - super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, - isInFrustum); - eaglerEmissiveFlag = Minecraft.getMinecraft().entityRenderer.renderItemEntityLight(this, 0.1f); - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float f = super.getEaglerDynamicLightsValueSimple(partialTicks); - ItemStack itm = this.getEntityItem(); - if (itm != null && itm.stackSize > 0) { - Item item = itm.getItem(); - if (item != null) { - float f2 = item.getHeldItemBrightnessEagler(itm) * 0.75f; - f = Math.min(f + f2 * 0.5f, 1.0f) + f2 * 0.5f; - } + if (this.getOwner() != null) { + nbttagcompound.setString("Owner", this.owner); } - return f; + + if (this.getEntityItem() != null) { + nbttagcompound.setTag("Item", this.getEntityItem().writeToNBT(new NBTTagCompound())); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityItemFrame.java b/src/game/java/net/minecraft/entity/item/EntityItemFrame.java index 3d4ce3bd..f7a63dc2 100644 --- a/src/game/java/net/minecraft/entity/item/EntityItemFrame.java +++ b/src/game/java/net/minecraft/entity/item/EntityItemFrame.java @@ -16,32 +16,37 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityItemFrame extends EntityHanging { - /**+ - * Chance for this item frame's item to drop from the frame. + /** + * + Chance for this item frame's item to drop from the frame. */ private float itemDropChance = 1.0F; + public boolean eaglerEmissiveFlag = false; + public EntityItemFrame(World worldIn) { super(worldIn); } @@ -51,17 +56,8 @@ public class EntityItemFrame extends EntityHanging { this.updateFacingWithBoundingBox(parEnumFacing); } - protected void entityInit() { - this.getDataWatcher().addObjectByDataType(8, 5); - this.getDataWatcher().addObject(9, Byte.valueOf((byte) 0)); - } - - public float getCollisionBorderSize() { - return 0.0F; - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (this.isEntityInvulnerable(damagesource)) { @@ -78,33 +74,6 @@ public class EntityItemFrame extends EntityHanging { } } - public int getWidthPixels() { - return 12; - } - - public int getHeightPixels() { - return 12; - } - - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double d0) { - double d1 = 16.0D; - d1 = d1 * 64.0D * this.renderDistanceWeight; - return d0 < d1 * d1; - } - - /**+ - * Called when this entity is broken. Entity parameter may be - * null. - */ - public void onBroken(Entity entity) { - this.dropItemOrSelf(entity, true); - } - public void dropItemOrSelf(Entity parEntity, boolean parFlag) { if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { ItemStack itemstack = this.getDisplayedItem(); @@ -129,9 +98,120 @@ public class EntityItemFrame extends EntityHanging { } } - /**+ - * Removes the dot representing this frame's position from the - * map when the item frame is broken. + protected void entityInit() { + this.getDataWatcher().addObjectByDataType(8, 5); + this.getDataWatcher().addObject(9, Byte.valueOf((byte) 0)); + } + + private void func_174865_a(int parInt1, boolean parFlag) { + this.getDataWatcher().updateObject(9, Byte.valueOf((byte) (parInt1 % 8))); + if (parFlag && this.hangingPosition != null) { + this.worldObj.updateComparatorOutputLevel(this.hangingPosition, Blocks.air); + } + + } + + public int func_174866_q() { + return this.getDisplayedItem() == null ? 0 : this.getRotation() % 8 + 1; + } + + public float getCollisionBorderSize() { + return 0.0F; + } + + public ItemStack getDisplayedItem() { + return this.getDataWatcher().getWatchableObjectItemStack(8); + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + ItemStack itm = this.getDisplayedItem(); + if (itm != null && itm.stackSize > 0) { + Item item = itm.getItem(); + if (item != null) { + float f2 = item.getHeldItemBrightnessEagler(itm) * 0.75f; + f = Math.min(f + f2 * 0.5f, 1.0f) + f2 * 0.5f; + } + } + return f; + } + + public int getHeightPixels() { + return 12; + } + + /** + * + Return the rotation of the item currently on this frame. + */ + public int getRotation() { + return this.getDataWatcher().getWatchableObjectByte(9); + } + + public int getWidthPixels() { + return 12; + } + + /** + * + First layer of player interaction + */ + public boolean interactFirst(EntityPlayer entityplayer) { + if (this.getDisplayedItem() == null) { + ItemStack itemstack = entityplayer.getHeldItem(); + if (itemstack != null && !this.worldObj.isRemote) { + this.setDisplayedItem(itemstack); + if (!entityplayer.capabilities.isCreativeMode && --itemstack.stackSize <= 0) { + entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, + (ItemStack) null); + } + } + } else if (!this.worldObj.isRemote) { + this.setItemRotation(this.getRotation() + 1); + } + + return true; + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance + */ + public boolean isInRangeToRenderDist(double d0) { + double d1 = 16.0D; + d1 = d1 * 64.0D * this.renderDistanceWeight; + return d0 < d1 * d1; + } + + /** + * + Called when this entity is broken. Entity parameter may be null. + */ + public void onBroken(Entity entity) { + this.dropItemOrSelf(entity, true); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Item"); + if (nbttagcompound1 != null && !nbttagcompound1.hasNoTags()) { + this.setDisplayedItemWithUpdate(ItemStack.loadItemStackFromNBT(nbttagcompound1), false); + this.func_174865_a(nbttagcompound.getByte("ItemRotation"), false); + if (nbttagcompound.hasKey("ItemDropChance", 99)) { + this.itemDropChance = nbttagcompound.getFloat("ItemDropChance"); + } + + if (nbttagcompound.hasKey("Direction")) { + this.func_174865_a(this.getRotation() * 2, false); + } + } + + super.readEntityFromNBT(nbttagcompound); + } + + /** + * + Removes the dot representing this frame's position from the map when the + * item frame is broken. */ private void removeFrameFromMap(ItemStack parItemStack) { if (parItemStack != null) { @@ -144,8 +224,11 @@ public class EntityItemFrame extends EntityHanging { } } - public ItemStack getDisplayedItem() { - return this.getDataWatcher().getWatchableObjectItemStack(8); + protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, + double renderY, double renderZ, float partialTicks, boolean isInFrustum) { + super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, + isInFrustum); + eaglerEmissiveFlag = Minecraft.getMinecraft().entityRenderer.renderItemEntityLight(this, 0.1f); } public void setDisplayedItem(ItemStack parItemStack) { @@ -167,28 +250,12 @@ public class EntityItemFrame extends EntityHanging { } - /**+ - * Return the rotation of the item currently on this frame. - */ - public int getRotation() { - return this.getDataWatcher().getWatchableObjectByte(9); - } - public void setItemRotation(int parInt1) { this.func_174865_a(parInt1, true); } - private void func_174865_a(int parInt1, boolean parFlag) { - this.getDataWatcher().updateObject(9, Byte.valueOf((byte) (parInt1 % 8))); - if (parFlag && this.hangingPosition != null) { - this.worldObj.updateComparatorOutputLevel(this.hangingPosition, Blocks.air); - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { if (this.getDisplayedItem() != null) { @@ -199,71 +266,4 @@ public class EntityItemFrame extends EntityHanging { super.writeEntityToNBT(nbttagcompound); } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Item"); - if (nbttagcompound1 != null && !nbttagcompound1.hasNoTags()) { - this.setDisplayedItemWithUpdate(ItemStack.loadItemStackFromNBT(nbttagcompound1), false); - this.func_174865_a(nbttagcompound.getByte("ItemRotation"), false); - if (nbttagcompound.hasKey("ItemDropChance", 99)) { - this.itemDropChance = nbttagcompound.getFloat("ItemDropChance"); - } - - if (nbttagcompound.hasKey("Direction")) { - this.func_174865_a(this.getRotation() * 2, false); - } - } - - super.readEntityFromNBT(nbttagcompound); - } - - /**+ - * First layer of player interaction - */ - public boolean interactFirst(EntityPlayer entityplayer) { - if (this.getDisplayedItem() == null) { - ItemStack itemstack = entityplayer.getHeldItem(); - if (itemstack != null && !this.worldObj.isRemote) { - this.setDisplayedItem(itemstack); - if (!entityplayer.capabilities.isCreativeMode && --itemstack.stackSize <= 0) { - entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, - (ItemStack) null); - } - } - } else if (!this.worldObj.isRemote) { - this.setItemRotation(this.getRotation() + 1); - } - - return true; - } - - public int func_174866_q() { - return this.getDisplayedItem() == null ? 0 : this.getRotation() % 8 + 1; - } - - public boolean eaglerEmissiveFlag = false; - - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, - double renderY, double renderZ, float partialTicks, boolean isInFrustum) { - super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, - isInFrustum); - eaglerEmissiveFlag = Minecraft.getMinecraft().entityRenderer.renderItemEntityLight(this, 0.1f); - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float f = super.getEaglerDynamicLightsValueSimple(partialTicks); - ItemStack itm = this.getDisplayedItem(); - if (itm != null && itm.stackSize > 0) { - Item item = itm.getItem(); - if (item != null) { - float f2 = item.getHeldItemBrightnessEagler(itm) * 0.75f; - f = Math.min(f + f2 * 0.5f, 1.0f) + f2 * 0.5f; - } - } - return f; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecart.java b/src/game/java/net/minecraft/entity/item/EntityMinecart.java index e2432d12..951e7b32 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecart.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecart.java @@ -33,51 +33,79 @@ import net.minecraft.world.IWorldNameable; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class EntityMinecart extends Entity implements IWorldNameable { - private boolean isInReverse; - private String entityName; - /**+ - * Minecart rotational logic matrix + public static enum EnumMinecartType { + RIDEABLE(0, "MinecartRideable"), CHEST(1, "MinecartChest"), FURNACE(2, "MinecartFurnace"), + TNT(3, "MinecartTNT"), SPAWNER(4, "MinecartSpawner"), HOPPER(5, "MinecartHopper"), + COMMAND_BLOCK(6, "MinecartCommandBlock"); + + private static final Map ID_LOOKUP = Maps.newHashMap(); + static { + EntityMinecart.EnumMinecartType[] types = values(); + for (int i = 0; i < types.length; ++i) { + ID_LOOKUP.put(Integer.valueOf(types[i].getNetworkID()), types[i]); + } + + } + + public static EntityMinecart.EnumMinecartType byNetworkID(int id) { + EntityMinecart.EnumMinecartType entityminecart$enumminecarttype = (EntityMinecart.EnumMinecartType) ID_LOOKUP + .get(Integer.valueOf(id)); + return entityminecart$enumminecarttype == null ? RIDEABLE : entityminecart$enumminecarttype; + } + + private final int networkID; + + private final String name; + + private EnumMinecartType(int networkID, String name) { + this.networkID = networkID; + this.name = name; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.name; + } + + public int getNetworkID() { + return this.networkID; + } + } + + /** + * + Minecart rotational logic matrix */ private static final int[][][] matrix = new int[][][] { { { 0, 0, -1 }, { 0, 0, 1 } }, { { -1, 0, 0 }, { 1, 0, 0 } }, { { -1, -1, 0 }, { 1, 0, 0 } }, { { -1, 0, 0 }, { 1, -1, 0 } }, { { 0, 0, -1 }, { 0, -1, 1 } }, { { 0, -1, -1 }, { 0, 0, 1 } }, { { 0, 0, 1 }, { 1, 0, 0 } }, { { 0, 0, 1 }, { -1, 0, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 } }, { { 0, 0, -1 }, { 1, 0, 0 } } }; - private int turnProgress; - private double minecartX; - private double minecartY; - private double minecartZ; - private double minecartYaw; - private double minecartPitch; - private double velocityX; - private double velocityY; - private double velocityZ; - - public EntityMinecart(World worldIn) { - super(worldIn); - this.preventEntitySpawning = true; - this.setSize(0.98F, 0.7F); - } public static EntityMinecart func_180458_a(World worldIn, double parDouble1, double parDouble2, double parDouble3, EntityMinecart.EnumMinecartType parEnumMinecartType) { @@ -99,46 +127,24 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { } } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } + private boolean isInReverse; + private String entityName; + private int turnProgress; + private double minecartX; + private double minecartY; + private double minecartZ; + private double minecartYaw; + private double minecartPitch; + private double velocityX; - protected void entityInit() { - this.dataWatcher.addObject(17, Integer.valueOf(0)); - this.dataWatcher.addObject(18, Integer.valueOf(1)); - this.dataWatcher.addObject(19, Float.valueOf(0.0F)); - this.dataWatcher.addObject(20, Integer.valueOf(0)); - this.dataWatcher.addObject(21, Integer.valueOf(6)); - this.dataWatcher.addObject(22, Byte.valueOf((byte) 0)); - } + private double velocityY; - /**+ - * Returns a boundingBox used to collide the entity with other - * entities and blocks. This enables the entity to be pushable - * on contact, like boats or minecarts. - */ - public AxisAlignedBB getCollisionBox(Entity entity) { - return entity.canBePushed() ? entity.getEntityBoundingBox() : null; - } + private double velocityZ; - /**+ - * Returns the collision bounding box for this entity - */ - public AxisAlignedBB getCollisionBoundingBox() { - return null; - } - - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. - */ - public boolean canBePushed() { - return true; + public EntityMinecart(World worldIn) { + super(worldIn); + this.preventEntitySpawning = true; + this.setSize(0.98F, 0.7F); } public EntityMinecart(World worldIn, double x, double y, double z) { @@ -152,16 +158,106 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { this.prevPosZ = z; } - /**+ - * Returns the Y offset from the entity's position for any - * entity riding this one. - */ - public double getMountedYOffset() { - return 0.0D; + protected void applyDrag() { + if (this.riddenByEntity != null) { + this.motionX *= 0.996999979019165D; + this.motionY *= 0.0D; + this.motionZ *= 0.996999979019165D; + } else { + this.motionX *= 0.9599999785423279D; + this.motionY *= 0.0D; + this.motionZ *= 0.9599999785423279D; + } + } - /**+ - * Called when the entity is attacked. + /** + * + Applies a velocity to each of the entities pushing them away from each + * other. Args: entity + */ + public void applyEntityCollision(Entity entity) { + if (!this.worldObj.isRemote) { + if (!entity.noClip && !this.noClip) { + if (entity != this.riddenByEntity) { + if (entity instanceof EntityLivingBase && !(entity instanceof EntityPlayer) + && !(entity instanceof EntityIronGolem) + && this.getMinecartType() == EntityMinecart.EnumMinecartType.RIDEABLE + && this.motionX * this.motionX + this.motionZ * this.motionZ > 0.01D + && this.riddenByEntity == null && entity.ridingEntity == null) { + entity.mountEntity(this); + } + + double d0 = entity.posX - this.posX; + double d1 = entity.posZ - this.posZ; + double d2 = d0 * d0 + d1 * d1; + if (d2 >= 9.999999747378752E-5D) { + d2 = (double) MathHelper.sqrt_double(d2); + d0 = d0 / d2; + d1 = d1 / d2; + double d3 = 1.0D / d2; + if (d3 > 1.0D) { + d3 = 1.0D; + } + + d0 = d0 * d3; + d1 = d1 * d3; + d0 = d0 * 0.10000000149011612D; + d1 = d1 * 0.10000000149011612D; + d0 = d0 * (double) (1.0F - this.entityCollisionReduction); + d1 = d1 * (double) (1.0F - this.entityCollisionReduction); + d0 = d0 * 0.5D; + d1 = d1 * 0.5D; + if (entity instanceof EntityMinecart) { + double d4 = entity.posX - this.posX; + double d5 = entity.posZ - this.posZ; + Vec3 vec3 = (new Vec3(d4, 0.0D, d5)).normalize(); + Vec3 vec31 = (new Vec3((double) MathHelper.cos(this.rotationYaw * 3.1415927F / 180.0F), + 0.0D, (double) MathHelper.sin(this.rotationYaw * 3.1415927F / 180.0F))).normalize(); + double d6 = Math.abs(vec3.dotProduct(vec31)); + if (d6 < 0.800000011920929D) { + return; + } + + double d7 = entity.motionX + this.motionX; + double d8 = entity.motionZ + this.motionZ; + if (((EntityMinecart) entity).getMinecartType() == EntityMinecart.EnumMinecartType.FURNACE + && this.getMinecartType() != EntityMinecart.EnumMinecartType.FURNACE) { + this.motionX *= 0.20000000298023224D; + this.motionZ *= 0.20000000298023224D; + this.addVelocity(entity.motionX - d0, 0.0D, entity.motionZ - d1); + entity.motionX *= 0.949999988079071D; + entity.motionZ *= 0.949999988079071D; + } else if (((EntityMinecart) entity) + .getMinecartType() != EntityMinecart.EnumMinecartType.FURNACE + && this.getMinecartType() == EntityMinecart.EnumMinecartType.FURNACE) { + entity.motionX *= 0.20000000298023224D; + entity.motionZ *= 0.20000000298023224D; + entity.addVelocity(this.motionX + d0, 0.0D, this.motionZ + d1); + this.motionX *= 0.949999988079071D; + this.motionZ *= 0.949999988079071D; + } else { + d7 = d7 / 2.0D; + d8 = d8 / 2.0D; + this.motionX *= 0.20000000298023224D; + this.motionZ *= 0.20000000298023224D; + this.addVelocity(d7 - d0, 0.0D, d8 - d1); + entity.motionX *= 0.20000000298023224D; + entity.motionZ *= 0.20000000298023224D; + entity.addVelocity(d7 + d0, 0.0D, d8 + d1); + } + } else { + this.addVelocity(-d0, 0.0D, -d1); + entity.addVelocity(d0 / 4.0D, 0.0D, d1 / 4.0D); + } + } + + } + } + } + } + + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (!this.worldObj.isRemote && !this.isDead) { @@ -193,210 +289,42 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { } } - public void killMinecart(DamageSource parDamageSource) { - this.setDead(); - if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - ItemStack itemstack = new ItemStack(Items.minecart, 1); - if (this.entityName != null) { - itemstack.setStackDisplayName(this.entityName); - } - - this.entityDropItem(itemstack, 0.0F); - } - - } - - /**+ - * Setups the entity to do the hurt animation. Only used by - * packets in multiplayer. - */ - public void performHurtAnimation() { - this.setRollingDirection(-this.getRollingDirection()); - this.setRollingAmplitude(10); - this.setDamage(this.getDamage() + this.getDamage() * 10.0F); - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. */ public boolean canBeCollidedWith() { return !this.isDead; } - /**+ - * Will get destroyed next tick. + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. */ - public void setDead() { - super.setDead(); + public boolean canBePushed() { + return true; } - /**+ - * Called to update the entity's position/logic. + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ - public void onUpdate() { - if (this.getRollingAmplitude() > 0) { - this.setRollingAmplitude(this.getRollingAmplitude() - 1); - } - - if (this.getDamage() > 0.0F) { - this.setDamage(this.getDamage() - 1.0F); - } - - if (this.posY < -64.0D) { - this.kill(); - } - - if (!this.worldObj.isRemote && this.worldObj instanceof WorldServer) { - MinecraftServer minecraftserver = ((WorldServer) this.worldObj).getMinecraftServer(); - int i = this.getMaxInPortalTime(); - if (this.inPortal) { - if (minecraftserver.getAllowNether()) { - if (this.ridingEntity == null && this.portalCounter++ >= i) { - this.portalCounter = i; - this.timeUntilPortal = this.getPortalCooldown(); - byte b0; - if (this.worldObj.provider.getDimensionId() == -1) { - b0 = 0; - } else { - b0 = -1; - } - - this.travelToDimension(b0); - } - - this.inPortal = false; - } - } else { - if (this.portalCounter > 0) { - this.portalCounter -= 4; - } - - if (this.portalCounter < 0) { - this.portalCounter = 0; - } - } - - if (this.timeUntilPortal > 0) { - --this.timeUntilPortal; - } - } - - if (this.worldObj.isRemote) { - if (this.turnProgress > 0) { - double d4 = this.posX + (this.minecartX - this.posX) / (double) this.turnProgress; - double d5 = this.posY + (this.minecartY - this.posY) / (double) this.turnProgress; - double d6 = this.posZ + (this.minecartZ - this.posZ) / (double) this.turnProgress; - double d1 = MathHelper.wrapAngleTo180_double(this.minecartYaw - (double) this.rotationYaw); - this.rotationYaw = (float) ((double) this.rotationYaw + d1 / (double) this.turnProgress); - this.rotationPitch = (float) ((double) this.rotationPitch - + (this.minecartPitch - (double) this.rotationPitch) / (double) this.turnProgress); - --this.turnProgress; - this.setPosition(d4, d5, d6); - this.setRotation(this.rotationYaw, this.rotationPitch); - } else { - this.setPosition(this.posX, this.posY, this.posZ); - this.setRotation(this.rotationYaw, this.rotationPitch); - } - - } else { - this.prevPosX = this.posX; - this.prevPosY = this.posY; - this.prevPosZ = this.posZ; - this.motionY -= 0.03999999910593033D; - int j = MathHelper.floor_double(this.posX); - int k = MathHelper.floor_double(this.posY); - int l = MathHelper.floor_double(this.posZ); - if (BlockRailBase.isRailBlock(this.worldObj, new BlockPos(j, k - 1, l))) { - --k; - } - - BlockPos blockpos = new BlockPos(j, k, l); - IBlockState iblockstate = this.worldObj.getBlockState(blockpos); - if (BlockRailBase.isRailBlock(iblockstate)) { - this.func_180460_a(blockpos, iblockstate); - if (iblockstate.getBlock() == Blocks.activator_rail) { - this.onActivatorRailPass(j, k, l, - ((Boolean) iblockstate.getValue(BlockRailPowered.POWERED)).booleanValue()); - } - } else { - this.moveDerailedMinecart(); - } - - this.doBlockCollisions(); - this.rotationPitch = 0.0F; - double d0 = this.prevPosX - this.posX; - double d2 = this.prevPosZ - this.posZ; - if (d0 * d0 + d2 * d2 > 0.001D) { - this.rotationYaw = (float) (MathHelper.func_181159_b(d2, d0) * 180.0D / 3.141592653589793D); - if (this.isInReverse) { - this.rotationYaw += 180.0F; - } - } - - double d3 = (double) MathHelper.wrapAngleTo180_float(this.rotationYaw - this.prevRotationYaw); - if (d3 < -170.0D || d3 >= 170.0D) { - this.rotationYaw += 180.0F; - this.isInReverse = !this.isInReverse; - } - - this.setRotation(this.rotationYaw, this.rotationPitch); - - List lst = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, - this.getEntityBoundingBox().expand(0.20000000298023224D, 0.0D, 0.20000000298023224D)); - for (int i = 0, m = lst.size(); i < m; ++i) { - Entity entity = lst.get(i); - if (entity != this.riddenByEntity && entity.canBePushed() && entity instanceof EntityMinecart) { - entity.applyEntityCollision(this); - } - } - - if (this.riddenByEntity != null && this.riddenByEntity.isDead) { - if (this.riddenByEntity.ridingEntity == this) { - this.riddenByEntity.ridingEntity = null; - } - - this.riddenByEntity = null; - } - - this.handleWaterMovement(); - } + protected boolean canTriggerWalking() { + return false; } - /**+ - * Get's the maximum speed for a minecart - */ - protected double getMaximumSpeed() { - return 0.4D; + protected void entityInit() { + this.dataWatcher.addObject(17, Integer.valueOf(0)); + this.dataWatcher.addObject(18, Integer.valueOf(1)); + this.dataWatcher.addObject(19, Float.valueOf(0.0F)); + this.dataWatcher.addObject(20, Integer.valueOf(0)); + this.dataWatcher.addObject(21, Integer.valueOf(6)); + this.dataWatcher.addObject(22, Byte.valueOf((byte) 0)); } - /**+ - * Called every tick the minecart is on an activator rail. Args: - * x, y, z, is the rail receiving power - */ - public void onActivatorRailPass(int x, int y, int z, boolean receivingPower) { - } - - /**+ - * Moves a minecart that is not attached to a rail - */ - protected void moveDerailedMinecart() { - double d0 = this.getMaximumSpeed(); - this.motionX = MathHelper.clamp_double(this.motionX, -d0, d0); - this.motionZ = MathHelper.clamp_double(this.motionZ, -d0, d0); - if (this.onGround) { - this.motionX *= 0.5D; - this.motionY *= 0.5D; - this.motionZ *= 0.5D; - } - - this.moveEntity(this.motionX, this.motionY, this.motionZ); - if (!this.onGround) { - this.motionX *= 0.949999988079071D; - this.motionY *= 0.949999988079071D; - this.motionZ *= 0.949999988079071D; - } - + public void func_174899_a(IBlockState parIBlockState) { + this.getDataWatcher().updateObject(20, Integer.valueOf(Block.getStateId(parIBlockState))); + this.setHasDisplayTile(true); } protected void func_180460_a(BlockPos parBlockPos, IBlockState parIBlockState) { @@ -561,72 +489,6 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { } - protected void applyDrag() { - if (this.riddenByEntity != null) { - this.motionX *= 0.996999979019165D; - this.motionY *= 0.0D; - this.motionZ *= 0.996999979019165D; - } else { - this.motionX *= 0.9599999785423279D; - this.motionY *= 0.0D; - this.motionZ *= 0.9599999785423279D; - } - - } - - /**+ - * Sets the x,y,z of the entity from the given parameters. Also - * seems to set up a bounding box. - */ - public void setPosition(double d0, double d1, double d2) { - this.posX = d0; - this.posY = d1; - this.posZ = d2; - float f = this.width / 2.0F; - float f1 = this.height; - this.setEntityBoundingBox(new AxisAlignedBB(d0 - (double) f, d1, d2 - (double) f, d0 + (double) f, - d1 + (double) f1, d2 + (double) f)); - } - - public Vec3 func_70495_a(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { - int i = MathHelper.floor_double(parDouble1); - int j = MathHelper.floor_double(parDouble2); - int k = MathHelper.floor_double(parDouble3); - if (BlockRailBase.isRailBlock(this.worldObj, new BlockPos(i, j - 1, k))) { - --j; - } - - IBlockState iblockstate = this.worldObj.getBlockState(new BlockPos(i, j, k)); - if (BlockRailBase.isRailBlock(iblockstate)) { - BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection) iblockstate - .getValue(((BlockRailBase) iblockstate.getBlock()).getShapeProperty()); - parDouble2 = (double) j; - if (blockrailbase$enumraildirection.isAscending()) { - parDouble2 = (double) (j + 1); - } - - int[][] aint = matrix[blockrailbase$enumraildirection.getMetadata()]; - double d0 = (double) (aint[1][0] - aint[0][0]); - double d1 = (double) (aint[1][2] - aint[0][2]); - double d2 = Math.sqrt(d0 * d0 + d1 * d1); - d0 = d0 / d2; - d1 = d1 / d2; - parDouble1 = parDouble1 + d0 * parDouble4; - parDouble3 = parDouble3 + d1 * parDouble4; - if (aint[0][1] != 0 && MathHelper.floor_double(parDouble1) - i == aint[0][0] - && MathHelper.floor_double(parDouble3) - k == aint[0][2]) { - parDouble2 += (double) aint[0][1]; - } else if (aint[1][1] != 0 && MathHelper.floor_double(parDouble1) - i == aint[1][0] - && MathHelper.floor_double(parDouble3) - k == aint[1][2]) { - parDouble2 += (double) aint[1][1]; - } - - return this.func_70489_a(parDouble1, parDouble2, parDouble3); - } else { - return null; - } - } - public Vec3 func_70489_a(double parDouble1, double parDouble2, double parDouble3) { int i = MathHelper.floor_double(parDouble1); int j = MathHelper.floor_double(parDouble2); @@ -679,9 +541,363 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { } } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + public Vec3 func_70495_a(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { + int i = MathHelper.floor_double(parDouble1); + int j = MathHelper.floor_double(parDouble2); + int k = MathHelper.floor_double(parDouble3); + if (BlockRailBase.isRailBlock(this.worldObj, new BlockPos(i, j - 1, k))) { + --j; + } + + IBlockState iblockstate = this.worldObj.getBlockState(new BlockPos(i, j, k)); + if (BlockRailBase.isRailBlock(iblockstate)) { + BlockRailBase.EnumRailDirection blockrailbase$enumraildirection = (BlockRailBase.EnumRailDirection) iblockstate + .getValue(((BlockRailBase) iblockstate.getBlock()).getShapeProperty()); + parDouble2 = (double) j; + if (blockrailbase$enumraildirection.isAscending()) { + parDouble2 = (double) (j + 1); + } + + int[][] aint = matrix[blockrailbase$enumraildirection.getMetadata()]; + double d0 = (double) (aint[1][0] - aint[0][0]); + double d1 = (double) (aint[1][2] - aint[0][2]); + double d2 = Math.sqrt(d0 * d0 + d1 * d1); + d0 = d0 / d2; + d1 = d1 / d2; + parDouble1 = parDouble1 + d0 * parDouble4; + parDouble3 = parDouble3 + d1 * parDouble4; + if (aint[0][1] != 0 && MathHelper.floor_double(parDouble1) - i == aint[0][0] + && MathHelper.floor_double(parDouble3) - k == aint[0][2]) { + parDouble2 += (double) aint[0][1]; + } else if (aint[1][1] != 0 && MathHelper.floor_double(parDouble1) - i == aint[1][0] + && MathHelper.floor_double(parDouble3) - k == aint[1][2]) { + parDouble2 += (double) aint[1][1]; + } + + return this.func_70489_a(parDouble1, parDouble2, parDouble3); + } else { + return null; + } + } + + /** + * + Returns the collision bounding box for this entity + */ + public AxisAlignedBB getCollisionBoundingBox() { + return null; + } + + /** + * + Returns a boundingBox used to collide the entity with other entities and + * blocks. This enables the entity to be pushable on contact, like boats or + * minecarts. + */ + public AxisAlignedBB getCollisionBox(Entity entity) { + return entity.canBePushed() ? entity.getEntityBoundingBox() : null; + } + + public String getCustomNameTag() { + return this.entityName; + } + + /** + * + Gets the current amount of damage the minecart has taken. Decreases over + * time. The cart breaks when this is over 40. + */ + public float getDamage() { + return this.dataWatcher.getWatchableObjectFloat(19); + } + + public IBlockState getDefaultDisplayTile() { + return Blocks.air.getDefaultState(); + } + + public int getDefaultDisplayTileOffset() { + return 6; + } + + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + if (this.hasCustomName()) { + ChatComponentText chatcomponenttext = new ChatComponentText(this.entityName); + chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); + chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); + return chatcomponenttext; + } else { + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(this.getName(), + new Object[0]); + chatcomponenttranslation.getChatStyle().setChatHoverEvent(this.getHoverEvent()); + chatcomponenttranslation.getChatStyle().setInsertion(this.getUniqueID().toString()); + return chatcomponenttranslation; + } + } + + public IChatComponent getDisplayNameProfanityFilter() { + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + return getDisplayName(); + } + + public IBlockState getDisplayTile() { + return !this.hasDisplayTile() ? this.getDefaultDisplayTile() + : Block.getStateById(this.getDataWatcher().getWatchableObjectInt(20)); + } + + public int getDisplayTileOffset() { + return !this.hasDisplayTile() ? this.getDefaultDisplayTileOffset() + : this.getDataWatcher().getWatchableObjectInt(21); + } + + /** + * + Get's the maximum speed for a minecart + */ + protected double getMaximumSpeed() { + return 0.4D; + } + + public abstract EntityMinecart.EnumMinecartType getMinecartType(); + + /** + * + Returns the Y offset from the entity's position for any entity riding this + * one. + */ + public double getMountedYOffset() { + return 0.0D; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.entityName != null ? this.entityName : super.getName(); + } + + public String getNameProfanityFilter() { + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + return getName(); + } + + /** + * + Gets the rolling amplitude the cart rolls while being attacked. + */ + public int getRollingAmplitude() { + return this.dataWatcher.getWatchableObjectInt(17); + } + + /** + * + Gets the rolling direction the cart rolls while being attacked. Can be 1 or + * -1. + */ + public int getRollingDirection() { + return this.dataWatcher.getWatchableObjectInt(18); + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.entityName != null; + } + + public boolean hasDisplayTile() { + return this.getDataWatcher().getWatchableObjectByte(22) == 1; + } + + public void killMinecart(DamageSource parDamageSource) { + this.setDead(); + if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + ItemStack itemstack = new ItemStack(Items.minecart, 1); + if (this.entityName != null) { + itemstack.setStackDisplayName(this.entityName); + } + + this.entityDropItem(itemstack, 0.0F); + } + + } + + /** + * + Moves a minecart that is not attached to a rail + */ + protected void moveDerailedMinecart() { + double d0 = this.getMaximumSpeed(); + this.motionX = MathHelper.clamp_double(this.motionX, -d0, d0); + this.motionZ = MathHelper.clamp_double(this.motionZ, -d0, d0); + if (this.onGround) { + this.motionX *= 0.5D; + this.motionY *= 0.5D; + this.motionZ *= 0.5D; + } + + this.moveEntity(this.motionX, this.motionY, this.motionZ); + if (!this.onGround) { + this.motionX *= 0.949999988079071D; + this.motionY *= 0.949999988079071D; + this.motionZ *= 0.949999988079071D; + } + + } + + /** + * + Called every tick the minecart is on an activator rail. Args: x, y, z, is + * the rail receiving power + */ + public void onActivatorRailPass(int x, int y, int z, boolean receivingPower) { + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + if (this.getRollingAmplitude() > 0) { + this.setRollingAmplitude(this.getRollingAmplitude() - 1); + } + + if (this.getDamage() > 0.0F) { + this.setDamage(this.getDamage() - 1.0F); + } + + if (this.posY < -64.0D) { + this.kill(); + } + + if (!this.worldObj.isRemote && this.worldObj instanceof WorldServer) { + MinecraftServer minecraftserver = ((WorldServer) this.worldObj).getMinecraftServer(); + int i = this.getMaxInPortalTime(); + if (this.inPortal) { + if (minecraftserver.getAllowNether()) { + if (this.ridingEntity == null && this.portalCounter++ >= i) { + this.portalCounter = i; + this.timeUntilPortal = this.getPortalCooldown(); + byte b0; + if (this.worldObj.provider.getDimensionId() == -1) { + b0 = 0; + } else { + b0 = -1; + } + + this.travelToDimension(b0); + } + + this.inPortal = false; + } + } else { + if (this.portalCounter > 0) { + this.portalCounter -= 4; + } + + if (this.portalCounter < 0) { + this.portalCounter = 0; + } + } + + if (this.timeUntilPortal > 0) { + --this.timeUntilPortal; + } + } + + if (this.worldObj.isRemote) { + if (this.turnProgress > 0) { + double d4 = this.posX + (this.minecartX - this.posX) / (double) this.turnProgress; + double d5 = this.posY + (this.minecartY - this.posY) / (double) this.turnProgress; + double d6 = this.posZ + (this.minecartZ - this.posZ) / (double) this.turnProgress; + double d1 = MathHelper.wrapAngleTo180_double(this.minecartYaw - (double) this.rotationYaw); + this.rotationYaw = (float) ((double) this.rotationYaw + d1 / (double) this.turnProgress); + this.rotationPitch = (float) ((double) this.rotationPitch + + (this.minecartPitch - (double) this.rotationPitch) / (double) this.turnProgress); + --this.turnProgress; + this.setPosition(d4, d5, d6); + this.setRotation(this.rotationYaw, this.rotationPitch); + } else { + this.setPosition(this.posX, this.posY, this.posZ); + this.setRotation(this.rotationYaw, this.rotationPitch); + } + + } else { + this.prevPosX = this.posX; + this.prevPosY = this.posY; + this.prevPosZ = this.posZ; + this.motionY -= 0.03999999910593033D; + int j = MathHelper.floor_double(this.posX); + int k = MathHelper.floor_double(this.posY); + int l = MathHelper.floor_double(this.posZ); + if (BlockRailBase.isRailBlock(this.worldObj, new BlockPos(j, k - 1, l))) { + --k; + } + + BlockPos blockpos = new BlockPos(j, k, l); + IBlockState iblockstate = this.worldObj.getBlockState(blockpos); + if (BlockRailBase.isRailBlock(iblockstate)) { + this.func_180460_a(blockpos, iblockstate); + if (iblockstate.getBlock() == Blocks.activator_rail) { + this.onActivatorRailPass(j, k, l, + ((Boolean) iblockstate.getValue(BlockRailPowered.POWERED)).booleanValue()); + } + } else { + this.moveDerailedMinecart(); + } + + this.doBlockCollisions(); + this.rotationPitch = 0.0F; + double d0 = this.prevPosX - this.posX; + double d2 = this.prevPosZ - this.posZ; + if (d0 * d0 + d2 * d2 > 0.001D) { + this.rotationYaw = (float) (MathHelper.func_181159_b(d2, d0) * 180.0D / 3.141592653589793D); + if (this.isInReverse) { + this.rotationYaw += 180.0F; + } + } + + double d3 = (double) MathHelper.wrapAngleTo180_float(this.rotationYaw - this.prevRotationYaw); + if (d3 < -170.0D || d3 >= 170.0D) { + this.rotationYaw += 180.0F; + this.isInReverse = !this.isInReverse; + } + + this.setRotation(this.rotationYaw, this.rotationPitch); + + List lst = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, + this.getEntityBoundingBox().expand(0.20000000298023224D, 0.0D, 0.20000000298023224D)); + for (int i = 0, m = lst.size(); i < m; ++i) { + Entity entity = lst.get(i); + if (entity != this.riddenByEntity && entity.canBePushed() && entity instanceof EntityMinecart) { + entity.applyEntityCollision(this); + } + } + + if (this.riddenByEntity != null && this.riddenByEntity.isDead) { + if (this.riddenByEntity.ridingEntity == this) { + this.riddenByEntity.ridingEntity = null; + } + + this.riddenByEntity = null; + } + + this.handleWaterMovement(); + } + } + + /** + * + Setups the entity to do the hurt animation. Only used by packets in + * multiplayer. + */ + public void performHurtAnimation() { + this.setRollingDirection(-this.getRollingDirection()); + this.setRollingAmplitude(10); + this.setDamage(this.getDamage() + this.getDamage() * 10.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { if (nbttagcompound.getBoolean("CustomDisplayTile")) { @@ -711,9 +927,89 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Sets the custom name tag for this entity + */ + public void setCustomNameTag(String s) { + this.entityName = s; + } + + /** + * + Sets the current amount of damage the minecart has taken. Decreases over + * time. The cart breaks when this is over 40. + */ + public void setDamage(float parFloat1) { + this.dataWatcher.updateObject(19, Float.valueOf(parFloat1)); + } + + /** + * + Will get destroyed next tick. + */ + public void setDead() { + super.setDead(); + } + + public void setDisplayTileOffset(int parInt1) { + this.getDataWatcher().updateObject(21, Integer.valueOf(parInt1)); + this.setHasDisplayTile(true); + } + + public void setHasDisplayTile(boolean parFlag) { + this.getDataWatcher().updateObject(22, Byte.valueOf((byte) (parFlag ? 1 : 0))); + } + + /** + * + Sets the x,y,z of the entity from the given parameters. Also seems to set + * up a bounding box. + */ + public void setPosition(double d0, double d1, double d2) { + this.posX = d0; + this.posY = d1; + this.posZ = d2; + float f = this.width / 2.0F; + float f1 = this.height; + this.setEntityBoundingBox(new AxisAlignedBB(d0 - (double) f, d1, d2 - (double) f, d0 + (double) f, + d1 + (double) f1, d2 + (double) f)); + } + + public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean var10) { + this.minecartX = d0; + this.minecartY = d1; + this.minecartZ = d2; + this.minecartYaw = (double) f; + this.minecartPitch = (double) f1; + this.turnProgress = i + 2; + this.motionX = this.velocityX; + this.motionY = this.velocityY; + this.motionZ = this.velocityZ; + } + + /** + * + Sets the rolling amplitude the cart rolls while being attacked. + */ + public void setRollingAmplitude(int parInt1) { + this.dataWatcher.updateObject(17, Integer.valueOf(parInt1)); + } + + /** + * + Sets the rolling direction the cart rolls while being attacked. Can be 1 or + * -1. + */ + public void setRollingDirection(int parInt1) { + this.dataWatcher.updateObject(18, Integer.valueOf(parInt1)); + } + + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double d0, double d1, double d2) { + this.velocityX = this.motionX = d0; + this.velocityY = this.motionY = d1; + this.velocityZ = this.motionZ = d2; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { if (this.hasDisplayTile()) { @@ -731,298 +1027,4 @@ public abstract class EntityMinecart extends Entity implements IWorldNameable { } } - - /**+ - * Applies a velocity to each of the entities pushing them away - * from each other. Args: entity - */ - public void applyEntityCollision(Entity entity) { - if (!this.worldObj.isRemote) { - if (!entity.noClip && !this.noClip) { - if (entity != this.riddenByEntity) { - if (entity instanceof EntityLivingBase && !(entity instanceof EntityPlayer) - && !(entity instanceof EntityIronGolem) - && this.getMinecartType() == EntityMinecart.EnumMinecartType.RIDEABLE - && this.motionX * this.motionX + this.motionZ * this.motionZ > 0.01D - && this.riddenByEntity == null && entity.ridingEntity == null) { - entity.mountEntity(this); - } - - double d0 = entity.posX - this.posX; - double d1 = entity.posZ - this.posZ; - double d2 = d0 * d0 + d1 * d1; - if (d2 >= 9.999999747378752E-5D) { - d2 = (double) MathHelper.sqrt_double(d2); - d0 = d0 / d2; - d1 = d1 / d2; - double d3 = 1.0D / d2; - if (d3 > 1.0D) { - d3 = 1.0D; - } - - d0 = d0 * d3; - d1 = d1 * d3; - d0 = d0 * 0.10000000149011612D; - d1 = d1 * 0.10000000149011612D; - d0 = d0 * (double) (1.0F - this.entityCollisionReduction); - d1 = d1 * (double) (1.0F - this.entityCollisionReduction); - d0 = d0 * 0.5D; - d1 = d1 * 0.5D; - if (entity instanceof EntityMinecart) { - double d4 = entity.posX - this.posX; - double d5 = entity.posZ - this.posZ; - Vec3 vec3 = (new Vec3(d4, 0.0D, d5)).normalize(); - Vec3 vec31 = (new Vec3((double) MathHelper.cos(this.rotationYaw * 3.1415927F / 180.0F), - 0.0D, (double) MathHelper.sin(this.rotationYaw * 3.1415927F / 180.0F))).normalize(); - double d6 = Math.abs(vec3.dotProduct(vec31)); - if (d6 < 0.800000011920929D) { - return; - } - - double d7 = entity.motionX + this.motionX; - double d8 = entity.motionZ + this.motionZ; - if (((EntityMinecart) entity).getMinecartType() == EntityMinecart.EnumMinecartType.FURNACE - && this.getMinecartType() != EntityMinecart.EnumMinecartType.FURNACE) { - this.motionX *= 0.20000000298023224D; - this.motionZ *= 0.20000000298023224D; - this.addVelocity(entity.motionX - d0, 0.0D, entity.motionZ - d1); - entity.motionX *= 0.949999988079071D; - entity.motionZ *= 0.949999988079071D; - } else if (((EntityMinecart) entity) - .getMinecartType() != EntityMinecart.EnumMinecartType.FURNACE - && this.getMinecartType() == EntityMinecart.EnumMinecartType.FURNACE) { - entity.motionX *= 0.20000000298023224D; - entity.motionZ *= 0.20000000298023224D; - entity.addVelocity(this.motionX + d0, 0.0D, this.motionZ + d1); - this.motionX *= 0.949999988079071D; - this.motionZ *= 0.949999988079071D; - } else { - d7 = d7 / 2.0D; - d8 = d8 / 2.0D; - this.motionX *= 0.20000000298023224D; - this.motionZ *= 0.20000000298023224D; - this.addVelocity(d7 - d0, 0.0D, d8 - d1); - entity.motionX *= 0.20000000298023224D; - entity.motionZ *= 0.20000000298023224D; - entity.addVelocity(d7 + d0, 0.0D, d8 + d1); - } - } else { - this.addVelocity(-d0, 0.0D, -d1); - entity.addVelocity(d0 / 4.0D, 0.0D, d1 / 4.0D); - } - } - - } - } - } - } - - public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean var10) { - this.minecartX = d0; - this.minecartY = d1; - this.minecartZ = d2; - this.minecartYaw = (double) f; - this.minecartPitch = (double) f1; - this.turnProgress = i + 2; - this.motionX = this.velocityX; - this.motionY = this.velocityY; - this.motionZ = this.velocityZ; - } - - /**+ - * Sets the velocity to the args. Args: x, y, z - */ - public void setVelocity(double d0, double d1, double d2) { - this.velocityX = this.motionX = d0; - this.velocityY = this.motionY = d1; - this.velocityZ = this.motionZ = d2; - } - - /**+ - * Sets the current amount of damage the minecart has taken. - * Decreases over time. The cart breaks when this is over 40. - */ - public void setDamage(float parFloat1) { - this.dataWatcher.updateObject(19, Float.valueOf(parFloat1)); - } - - /**+ - * Gets the current amount of damage the minecart has taken. - * Decreases over time. The cart breaks when this is over 40. - */ - public float getDamage() { - return this.dataWatcher.getWatchableObjectFloat(19); - } - - /**+ - * Sets the rolling amplitude the cart rolls while being - * attacked. - */ - public void setRollingAmplitude(int parInt1) { - this.dataWatcher.updateObject(17, Integer.valueOf(parInt1)); - } - - /**+ - * Gets the rolling amplitude the cart rolls while being - * attacked. - */ - public int getRollingAmplitude() { - return this.dataWatcher.getWatchableObjectInt(17); - } - - /**+ - * Sets the rolling direction the cart rolls while being - * attacked. Can be 1 or -1. - */ - public void setRollingDirection(int parInt1) { - this.dataWatcher.updateObject(18, Integer.valueOf(parInt1)); - } - - /**+ - * Gets the rolling direction the cart rolls while being - * attacked. Can be 1 or -1. - */ - public int getRollingDirection() { - return this.dataWatcher.getWatchableObjectInt(18); - } - - public abstract EntityMinecart.EnumMinecartType getMinecartType(); - - public IBlockState getDisplayTile() { - return !this.hasDisplayTile() ? this.getDefaultDisplayTile() - : Block.getStateById(this.getDataWatcher().getWatchableObjectInt(20)); - } - - public IBlockState getDefaultDisplayTile() { - return Blocks.air.getDefaultState(); - } - - public int getDisplayTileOffset() { - return !this.hasDisplayTile() ? this.getDefaultDisplayTileOffset() - : this.getDataWatcher().getWatchableObjectInt(21); - } - - public int getDefaultDisplayTileOffset() { - return 6; - } - - public void func_174899_a(IBlockState parIBlockState) { - this.getDataWatcher().updateObject(20, Integer.valueOf(Block.getStateId(parIBlockState))); - this.setHasDisplayTile(true); - } - - public void setDisplayTileOffset(int parInt1) { - this.getDataWatcher().updateObject(21, Integer.valueOf(parInt1)); - this.setHasDisplayTile(true); - } - - public boolean hasDisplayTile() { - return this.getDataWatcher().getWatchableObjectByte(22) == 1; - } - - public void setHasDisplayTile(boolean parFlag) { - this.getDataWatcher().updateObject(22, Byte.valueOf((byte) (parFlag ? 1 : 0))); - } - - /**+ - * Sets the custom name tag for this entity - */ - public void setCustomNameTag(String s) { - this.entityName = s; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.entityName != null ? this.entityName : super.getName(); - } - - public String getNameProfanityFilter() { - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - return getName(); - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.entityName != null; - } - - public String getCustomNameTag() { - return this.entityName; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - if (this.hasCustomName()) { - ChatComponentText chatcomponenttext = new ChatComponentText(this.entityName); - chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); - chatcomponenttext.getChatStyle().setInsertion(this.getUniqueID().toString()); - return chatcomponenttext; - } else { - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(this.getName(), - new Object[0]); - chatcomponenttranslation.getChatStyle().setChatHoverEvent(this.getHoverEvent()); - chatcomponenttranslation.getChatStyle().setInsertion(this.getUniqueID().toString()); - return chatcomponenttranslation; - } - } - - public IChatComponent getDisplayNameProfanityFilter() { - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - return getDisplayName(); - } - - public static enum EnumMinecartType { - RIDEABLE(0, "MinecartRideable"), CHEST(1, "MinecartChest"), FURNACE(2, "MinecartFurnace"), - TNT(3, "MinecartTNT"), SPAWNER(4, "MinecartSpawner"), HOPPER(5, "MinecartHopper"), - COMMAND_BLOCK(6, "MinecartCommandBlock"); - - private static final Map ID_LOOKUP = Maps.newHashMap(); - private final int networkID; - private final String name; - - private EnumMinecartType(int networkID, String name) { - this.networkID = networkID; - this.name = name; - } - - public int getNetworkID() { - return this.networkID; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.name; - } - - public static EntityMinecart.EnumMinecartType byNetworkID(int id) { - EntityMinecart.EnumMinecartType entityminecart$enumminecarttype = (EntityMinecart.EnumMinecartType) ID_LOOKUP - .get(Integer.valueOf(id)); - return entityminecart$enumminecarttype == null ? RIDEABLE : entityminecart$enumminecarttype; - } - - static { - EntityMinecart.EnumMinecartType[] types = values(); - for (int i = 0; i < types.length; ++i) { - ID_LOOKUP.put(Integer.valueOf(types[i].getNetworkID()), types[i]); - } - - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecartChest.java b/src/game/java/net/minecraft/entity/item/EntityMinecartChest.java index 7914ce1c..20524ea1 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecartChest.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecartChest.java @@ -12,22 +12,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,23 +44,8 @@ public class EntityMinecartChest extends EntityMinecartContainer { super(worldIn, parDouble1, parDouble2, parDouble3); } - public void killMinecart(DamageSource damagesource) { - super.killMinecart(damagesource); - if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - this.dropItemWithOffset(Item.getItemFromBlock(Blocks.chest), 1, 0.0F); - } - - } - - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return 27; - } - - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.CHEST; + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { + return new ContainerChest(inventoryplayer, this, entityplayer); } public IBlockState getDefaultDisplayTile() { @@ -72,7 +60,22 @@ public class EntityMinecartChest extends EntityMinecartContainer { return "minecraft:chest"; } - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { - return new ContainerChest(inventoryplayer, this, entityplayer); + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.CHEST; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return 27; + } + + public void killMinecart(DamageSource damagesource) { + super.killMinecart(damagesource); + if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + this.dropItemWithOffset(Item.getItemFromBlock(Blocks.chest), 1, 0.0F); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecartContainer.java b/src/game/java/net/minecraft/entity/item/EntityMinecartContainer.java index a5101f66..d94e1490 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecartContainer.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecartContainer.java @@ -11,32 +11,35 @@ import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class EntityMinecartContainer extends EntityMinecart implements ILockableContainer { private ItemStack[] minecartContainerItems = new ItemStack[36]; - /**+ - * When set to true, the minecart will drop all items when - * setDead() is called. When false (such as when travelling - * dimensions) it preserves its contents. + /** + * + When set to true, the minecart will drop all items when setDead() is + * called. When false (such as when travelling dimensions) it preserves its + * contents. */ private boolean dropContentsWhenDead = true; @@ -48,24 +51,27 @@ public abstract class EntityMinecartContainer extends EntityMinecart implements super(worldIn, parDouble1, parDouble2, parDouble3); } - public void killMinecart(DamageSource damagesource) { - super.killMinecart(damagesource); - if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - InventoryHelper.func_180176_a(this.worldObj, this, this); + protected void applyDrag() { + int i = 15 - Container.calcRedstoneFromInventory(this); + float f = 0.98F + (float) i * 0.001F; + this.motionX *= (double) f; + this.motionY *= 0.0D; + this.motionZ *= (double) f; + } + + public void clear() { + for (int i = 0; i < this.minecartContainerItems.length; ++i) { + this.minecartContainerItems[i] = null; } } - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return this.minecartContainerItems[i]; + public void closeInventory(EntityPlayer var1) { } - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.minecartContainerItems[i] != null) { @@ -86,120 +92,92 @@ public abstract class EntityMinecartContainer extends EntityMinecart implements } } - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (this.minecartContainerItems[i] != null) { - ItemStack itemstack = this.minecartContainerItems[i]; - this.minecartContainerItems[i] = null; - return itemstack; - } else { - return null; - } + public int getField(int var1) { + return 0; } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - this.minecartContainerItems[i] = itemstack; - if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { - itemstack.stackSize = this.getInventoryStackLimit(); - } - + public int getFieldCount() { + return 0; } - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.isDead ? false : entityplayer.getDistanceSqToEntity(this) <= 64.0D; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.hasCustomName() ? this.getCustomNameTag() : "container.minecart"; - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. */ public int getInventoryStackLimit() { return 64; } - /**+ - * Teleports the entity to another dimension. Params: Dimension - * number to teleport to - */ - public void travelToDimension(int i) { - this.dropContentsWhenDead = false; - super.travelToDimension(i); + public LockCode getLockCode() { + return LockCode.EMPTY_CODE; } - /**+ - * Will get destroyed next tick. + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ - public void setDead() { - if (this.dropContentsWhenDead) { + public String getName() { + return this.hasCustomName() ? this.getCustomNameTag() : "container.minecart"; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return this.minecartContainerItems[i]; + } + + /** + * + First layer of player interaction + */ + public boolean interactFirst(EntityPlayer entityplayer) { + if (!this.worldObj.isRemote) { + entityplayer.displayGUIChest(this); + } + + return true; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + public boolean isLocked() { + return false; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.isDead ? false : entityplayer.getDistanceSqToEntity(this) <= 64.0D; + } + + public void killMinecart(DamageSource damagesource) { + super.killMinecart(damagesource); + if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { InventoryHelper.func_180176_a(this.worldObj, this, this); } - super.setDead(); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.minecartContainerItems.length; ++i) { - if (this.minecartContainerItems[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - this.minecartContainerItems[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - - nbttagcompound.setTag("Items", nbttaglist); + public void markDirty() { } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + public void openInventory(EntityPlayer var1) { + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -216,51 +194,73 @@ public abstract class EntityMinecartContainer extends EntityMinecart implements } - /**+ - * First layer of player interaction + /** + * + Removes a stack from the given slot and returns it. */ - public boolean interactFirst(EntityPlayer entityplayer) { - if (!this.worldObj.isRemote) { - entityplayer.displayGUIChest(this); + public ItemStack removeStackFromSlot(int i) { + if (this.minecartContainerItems[i] != null) { + ItemStack itemstack = this.minecartContainerItems[i]; + this.minecartContainerItems[i] = null; + return itemstack; + } else { + return null; + } + } + + /** + * + Will get destroyed next tick. + */ + public void setDead() { + if (this.dropContentsWhenDead) { + InventoryHelper.func_180176_a(this.worldObj, this, this); } - return true; - } - - protected void applyDrag() { - int i = 15 - Container.calcRedstoneFromInventory(this); - float f = 0.98F + (float) i * 0.001F; - this.motionX *= (double) f; - this.motionY *= 0.0D; - this.motionZ *= (double) f; - } - - public int getField(int var1) { - return 0; + super.setDead(); } public void setField(int var1, int var2) { } - public int getFieldCount() { - return 0; - } + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + this.minecartContainerItems[i] = itemstack; + if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { + itemstack.stackSize = this.getInventoryStackLimit(); + } - public boolean isLocked() { - return false; } public void setLockCode(LockCode var1) { } - public LockCode getLockCode() { - return LockCode.EMPTY_CODE; + /** + * + Teleports the entity to another dimension. Params: Dimension number to + * teleport to + */ + public void travelToDimension(int i) { + this.dropContentsWhenDead = false; + super.travelToDimension(i); } - public void clear() { + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + for (int i = 0; i < this.minecartContainerItems.length; ++i) { - this.minecartContainerItems[i] = null; + if (this.minecartContainerItems[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + this.minecartContainerItems[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } } + nbttagcompound.setTag("Items", nbttaglist); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecartEmpty.java b/src/game/java/net/minecraft/entity/item/EntityMinecartEmpty.java index 3d2d47b4..d3230f1f 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecartEmpty.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecartEmpty.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +36,12 @@ public class EntityMinecartEmpty extends EntityMinecart { super(worldIn, parDouble1, parDouble2, parDouble3); } - /**+ - * First layer of player interaction + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.RIDEABLE; + } + + /** + * + First layer of player interaction */ public boolean interactFirst(EntityPlayer entityplayer) { if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityPlayer @@ -51,9 +58,9 @@ public class EntityMinecartEmpty extends EntityMinecart { } } - /**+ - * Called every tick the minecart is on an activator rail. Args: - * x, y, z, is the rail receiving power + /** + * + Called every tick the minecart is on an activator rail. Args: x, y, z, is + * the rail receiving power */ public void onActivatorRailPass(int var1, int var2, int var3, boolean flag) { if (flag) { @@ -70,8 +77,4 @@ public class EntityMinecartEmpty extends EntityMinecart { } } - - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.RIDEABLE; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecartFurnace.java b/src/game/java/net/minecraft/entity/item/EntityMinecartFurnace.java index 6602d621..cf4926be 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecartFurnace.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecartFurnace.java @@ -14,22 +14,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,70 +50,6 @@ public class EntityMinecartFurnace extends EntityMinecart { super(worldIn, parDouble1, parDouble2, parDouble3); } - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.FURNACE; - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - super.onUpdate(); - if (this.fuel > 0) { - --this.fuel; - } - - if (this.fuel <= 0) { - this.pushX = this.pushZ = 0.0D; - } - - this.setMinecartPowered(this.fuel > 0); - if (this.isMinecartPowered() && this.rand.nextInt(4) == 0) { - this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_LARGE, this.posX, this.posY + 0.8D, this.posZ, 0.0D, - 0.0D, 0.0D, new int[0]); - } - - } - - /**+ - * Get's the maximum speed for a minecart - */ - protected double getMaximumSpeed() { - return 0.2D; - } - - public void killMinecart(DamageSource damagesource) { - super.killMinecart(damagesource); - if (!damagesource.isExplosion() && this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - this.entityDropItem(new ItemStack(Blocks.furnace, 1), 0.0F); - } - - } - - protected void func_180460_a(BlockPos blockpos, IBlockState iblockstate) { - super.func_180460_a(blockpos, iblockstate); - double d0 = this.pushX * this.pushX + this.pushZ * this.pushZ; - if (d0 > 1.0E-4D && this.motionX * this.motionX + this.motionZ * this.motionZ > 0.001D) { - d0 = (double) MathHelper.sqrt_double(d0); - this.pushX /= d0; - this.pushZ /= d0; - if (this.pushX * this.motionX + this.pushZ * this.motionZ < 0.0D) { - this.pushX = 0.0D; - this.pushZ = 0.0D; - } else { - double d1 = d0 / this.getMaximumSpeed(); - this.pushX *= d1; - this.pushZ *= d1; - } - } - - } - protected void applyDrag() { double d0 = this.pushX * this.pushX + this.pushZ * this.pushZ; if (d0 > 1.0E-4D) { @@ -132,8 +71,48 @@ public class EntityMinecartFurnace extends EntityMinecart { super.applyDrag(); } - /**+ - * First layer of player interaction + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + protected void func_180460_a(BlockPos blockpos, IBlockState iblockstate) { + super.func_180460_a(blockpos, iblockstate); + double d0 = this.pushX * this.pushX + this.pushZ * this.pushZ; + if (d0 > 1.0E-4D && this.motionX * this.motionX + this.motionZ * this.motionZ > 0.001D) { + d0 = (double) MathHelper.sqrt_double(d0); + this.pushX /= d0; + this.pushZ /= d0; + if (this.pushX * this.motionX + this.pushZ * this.motionZ < 0.0D) { + this.pushX = 0.0D; + this.pushZ = 0.0D; + } else { + double d1 = d0 / this.getMaximumSpeed(); + this.pushX *= d1; + this.pushZ *= d1; + } + } + + } + + public IBlockState getDefaultDisplayTile() { + return (this.isMinecartPowered() ? Blocks.lit_furnace : Blocks.furnace).getDefaultState() + .withProperty(BlockFurnace.FACING, EnumFacing.NORTH); + } + + /** + * + Get's the maximum speed for a minecart + */ + protected double getMaximumSpeed() { + return 0.2D; + } + + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.FURNACE; + } + + /** + * + First layer of player interaction */ public boolean interactFirst(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -150,20 +129,41 @@ public class EntityMinecartFurnace extends EntityMinecart { return true; } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setDouble("PushX", this.pushX); - nbttagcompound.setDouble("PushZ", this.pushZ); - nbttagcompound.setShort("Fuel", (short) this.fuel); + protected boolean isMinecartPowered() { + return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + public void killMinecart(DamageSource damagesource) { + super.killMinecart(damagesource); + if (!damagesource.isExplosion() && this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + this.entityDropItem(new ItemStack(Blocks.furnace, 1), 0.0F); + } + + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + super.onUpdate(); + if (this.fuel > 0) { + --this.fuel; + } + + if (this.fuel <= 0) { + this.pushX = this.pushZ = 0.0D; + } + + this.setMinecartPowered(this.fuel > 0); + if (this.isMinecartPowered() && this.rand.nextInt(4) == 0) { + this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_LARGE, this.posX, this.posY + 0.8D, this.posZ, 0.0D, + 0.0D, 0.0D, new int[0]); + } + + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -172,10 +172,6 @@ public class EntityMinecartFurnace extends EntityMinecart { this.fuel = nbttagcompound.getShort("Fuel"); } - protected boolean isMinecartPowered() { - return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; - } - protected void setMinecartPowered(boolean parFlag) { if (parFlag) { this.dataWatcher.updateObject(16, Byte.valueOf((byte) (this.dataWatcher.getWatchableObjectByte(16) | 1))); @@ -185,8 +181,13 @@ public class EntityMinecartFurnace extends EntityMinecart { } - public IBlockState getDefaultDisplayTile() { - return (this.isMinecartPowered() ? Blocks.lit_furnace : Blocks.furnace).getDefaultState() - .withProperty(BlockFurnace.FACING, EnumFacing.NORTH); + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setDouble("PushX", this.pushX); + nbttagcompound.setDouble("PushZ", this.pushZ); + nbttagcompound.setShort("Fuel", (short) this.fuel); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecartHopper.java b/src/game/java/net/minecraft/entity/item/EntityMinecartHopper.java index ee526935..be1fa8de 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecartHopper.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecartHopper.java @@ -17,30 +17,32 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.EntitySelectors; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityMinecartHopper extends EntityMinecartContainer implements IHopper { - /**+ - * Whether this hopper minecart is being blocked by an activator - * rail. + /** + * + Whether this hopper minecart is being blocked by an activator rail. */ private boolean isBlocked = true; private int transferTicker = -1; @@ -54,8 +56,36 @@ public class EntityMinecartHopper extends EntityMinecartContainer implements IHo super(worldIn, parDouble1, parDouble2, parDouble3); } - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.HOPPER; + /** + * + Returns whether the hopper cart can currently transfer an item. + */ + public boolean canTransfer() { + return this.transferTicker > 0; + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { + return new ContainerHopper(inventoryplayer, this, entityplayer); + } + + public boolean func_96112_aD() { + if (TileEntityHopper.captureDroppedItems(this)) { + return true; + } else { + List list = this.worldObj.getEntitiesWithinAABB(EntityItem.class, + this.getEntityBoundingBox().expand(0.25D, 0.0D, 0.25D), EntitySelectors.selectAnything); + if (list.size() > 0) { + TileEntityHopper.putDropInInventoryAllSlots(this, (EntityItem) list.get(0)); + } + + return false; + } + } + + /** + * + Get whether this hopper minecart is being blocked by an activator rail. + */ + public boolean getBlocked() { + return this.isBlocked; } public IBlockState getDefaultDisplayTile() { @@ -66,15 +96,51 @@ public class EntityMinecartHopper extends EntityMinecartContainer implements IHo return 1; } - /**+ - * Returns the number of slots in the inventory. + public String getGuiID() { + return "minecraft:hopper"; + } + + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.HOPPER; + } + + /** + * + Returns the number of slots in the inventory. */ public int getSizeInventory() { return 5; } - /**+ - * First layer of player interaction + /** + * + Returns the worldObj for this tileEntity. + */ + public World getWorld() { + return this.worldObj; + } + + /** + * + Gets the world X position for this hopper entity. + */ + public double getXPos() { + return this.posX; + } + + /** + * + Gets the world Y position for this hopper entity. + */ + public double getYPos() { + return this.posY + 0.5D; + } + + /** + * + Gets the world Z position for this hopper entity. + */ + public double getZPos() { + return this.posZ; + } + + /** + * + First layer of player interaction */ public boolean interactFirst(EntityPlayer entityplayer) { if (!this.worldObj.isRemote) { @@ -84,9 +150,17 @@ public class EntityMinecartHopper extends EntityMinecartContainer implements IHo return true; } - /**+ - * Called every tick the minecart is on an activator rail. Args: - * x, y, z, is the rail receiving power + public void killMinecart(DamageSource damagesource) { + super.killMinecart(damagesource); + if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + this.dropItemWithOffset(Item.getItemFromBlock(Blocks.hopper), 1, 0.0F); + } + + } + + /** + * + Called every tick the minecart is on an activator rail. Args: x, y, z, is + * the rail receiving power */ public void onActivatorRailPass(int var1, int var2, int var3, boolean flag) { boolean flag1 = !flag; @@ -96,52 +170,8 @@ public class EntityMinecartHopper extends EntityMinecartContainer implements IHo } - /**+ - * Get whether this hopper minecart is being blocked by an - * activator rail. - */ - public boolean getBlocked() { - return this.isBlocked; - } - - /**+ - * Set whether this hopper minecart is being blocked by an - * activator rail. - */ - public void setBlocked(boolean parFlag) { - this.isBlocked = parFlag; - } - - /**+ - * Returns the worldObj for this tileEntity. - */ - public World getWorld() { - return this.worldObj; - } - - /**+ - * Gets the world X position for this hopper entity. - */ - public double getXPos() { - return this.posX; - } - - /**+ - * Gets the world Y position for this hopper entity. - */ - public double getYPos() { - return this.posY + 0.5D; - } - - /**+ - * Gets the world Z position for this hopper entity. - */ - public double getZPos() { - return this.posZ; - } - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -164,67 +194,33 @@ public class EntityMinecartHopper extends EntityMinecartContainer implements IHo } - public boolean func_96112_aD() { - if (TileEntityHopper.captureDroppedItems(this)) { - return true; - } else { - List list = this.worldObj.getEntitiesWithinAABB(EntityItem.class, - this.getEntityBoundingBox().expand(0.25D, 0.0D, 0.25D), EntitySelectors.selectAnything); - if (list.size() > 0) { - TileEntityHopper.putDropInInventoryAllSlots(this, (EntityItem) list.get(0)); - } - - return false; - } - } - - public void killMinecart(DamageSource damagesource) { - super.killMinecart(damagesource); - if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - this.dropItemWithOffset(Item.getItemFromBlock(Blocks.hopper), 1, 0.0F); - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("TransferCooldown", this.transferTicker); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); this.transferTicker = nbttagcompound.getInteger("TransferCooldown"); } - /**+ - * Sets the transfer ticker, used to determine the delay between - * transfers. + /** + * + Set whether this hopper minecart is being blocked by an activator rail. + */ + public void setBlocked(boolean parFlag) { + this.isBlocked = parFlag; + } + + /** + * + Sets the transfer ticker, used to determine the delay between transfers. */ public void setTransferTicker(int parInt1) { this.transferTicker = parInt1; } - /**+ - * Returns whether the hopper cart can currently transfer an - * item. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean canTransfer() { - return this.transferTicker > 0; - } - - public String getGuiID() { - return "minecraft:hopper"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { - return new ContainerHopper(inventoryplayer, this, entityplayer); + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("TransferCooldown", this.transferTicker); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityMinecartTNT.java b/src/game/java/net/minecraft/entity/item/EntityMinecartTNT.java index b75af38d..2aee2e8d 100644 --- a/src/game/java/net/minecraft/entity/item/EntityMinecartTNT.java +++ b/src/game/java/net/minecraft/entity/item/EntityMinecartTNT.java @@ -14,22 +14,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.Explosion; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,38 +48,8 @@ public class EntityMinecartTNT extends EntityMinecart { super(worldIn, parDouble1, parDouble2, parDouble3); } - public EntityMinecart.EnumMinecartType getMinecartType() { - return EntityMinecart.EnumMinecartType.TNT; - } - - public IBlockState getDefaultDisplayTile() { - return Blocks.tnt.getDefaultState(); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - super.onUpdate(); - if (this.minecartTNTFuse > 0) { - --this.minecartTNTFuse; - this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY + 0.5D, this.posZ, 0.0D, - 0.0D, 0.0D, new int[0]); - } else if (this.minecartTNTFuse == 0) { - this.explodeCart(this.motionX * this.motionX + this.motionZ * this.motionZ); - } - - if (this.isCollidedHorizontally) { - double d0 = this.motionX * this.motionX + this.motionZ * this.motionZ; - if (d0 >= 0.009999999776482582D) { - this.explodeCart(d0); - } - } - - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { Entity entity = damagesource.getSourceOfDamage(); @@ -91,21 +64,8 @@ public class EntityMinecartTNT extends EntityMinecart { return super.attackEntityFrom(damagesource, f); } - public void killMinecart(DamageSource damagesource) { - super.killMinecart(damagesource); - double d0 = this.motionX * this.motionX + this.motionZ * this.motionZ; - if (!damagesource.isExplosion() && this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - this.entityDropItem(new ItemStack(Blocks.tnt, 1), 0.0F); - } - - if (damagesource.isFireDamage() || damagesource.isExplosion() || d0 >= 0.009999999776482582D) { - this.explodeCart(d0); - } - - } - - /**+ - * Makes the minecart explode. + /** + * + Makes the minecart explode. */ protected void explodeCart(double parDouble1) { if (!this.worldObj.isRemote) { @@ -130,15 +90,37 @@ public class EntityMinecartTNT extends EntityMinecart { super.fall(f, f1); } - /**+ - * Called every tick the minecart is on an activator rail. Args: - * x, y, z, is the rail receiving power - */ - public void onActivatorRailPass(int var1, int var2, int var3, boolean flag) { - if (flag && this.minecartTNTFuse < 0) { - this.ignite(); - } + public IBlockState getDefaultDisplayTile() { + return Blocks.tnt.getDefaultState(); + } + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + if (minecartTNTFuse > -1 && minecartTNTFuse / 5 % 2 == 0) { + f = Math.min(f + 0.75f, 1.25f); + } + return f; + } + + /** + * + Explosion resistance of a block relative to this entity + */ + public float getExplosionResistance(Explosion explosion, World world, BlockPos blockpos, IBlockState iblockstate) { + return !this.isIgnited() + || !BlockRailBase.isRailBlock(iblockstate) && !BlockRailBase.isRailBlock(world, blockpos.up()) + ? super.getExplosionResistance(explosion, world, blockpos, iblockstate) + : 0.0F; + } + + /** + * + Gets the remaining fuse time in ticks. + */ + public int getFuseTicks() { + return this.minecartTNTFuse; + } + + public EntityMinecart.EnumMinecartType getMinecartType() { + return EntityMinecart.EnumMinecartType.TNT; } public void handleStatusUpdate(byte b0) { @@ -150,8 +132,8 @@ public class EntityMinecartTNT extends EntityMinecart { } - /**+ - * Ignites this TNT cart. + /** + * + Ignites this TNT cart. */ public void ignite() { this.minecartTNTFuse = 80; @@ -164,41 +146,61 @@ public class EntityMinecartTNT extends EntityMinecart { } - /**+ - * Gets the remaining fuse time in ticks. - */ - public int getFuseTicks() { - return this.minecartTNTFuse; - } - - /**+ - * Returns true if the TNT minecart is ignited. + /** + * + Returns true if the TNT minecart is ignited. */ public boolean isIgnited() { return this.minecartTNTFuse > -1; } - /**+ - * Explosion resistance of a block relative to this entity + public void killMinecart(DamageSource damagesource) { + super.killMinecart(damagesource); + double d0 = this.motionX * this.motionX + this.motionZ * this.motionZ; + if (!damagesource.isExplosion() && this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + this.entityDropItem(new ItemStack(Blocks.tnt, 1), 0.0F); + } + + if (damagesource.isFireDamage() || damagesource.isExplosion() || d0 >= 0.009999999776482582D) { + this.explodeCart(d0); + } + + } + + /** + * + Called every tick the minecart is on an activator rail. Args: x, y, z, is + * the rail receiving power */ - public float getExplosionResistance(Explosion explosion, World world, BlockPos blockpos, IBlockState iblockstate) { - return !this.isIgnited() - || !BlockRailBase.isRailBlock(iblockstate) && !BlockRailBase.isRailBlock(world, blockpos.up()) - ? super.getExplosionResistance(explosion, world, blockpos, iblockstate) - : 0.0F; + public void onActivatorRailPass(int var1, int var2, int var3, boolean flag) { + if (flag && this.minecartTNTFuse < 0) { + this.ignite(); + } + } - public boolean verifyExplosion(Explosion explosion, World world, BlockPos blockpos, IBlockState iblockstate, - float f) { - return !this.isIgnited() - || !BlockRailBase.isRailBlock(iblockstate) && !BlockRailBase.isRailBlock(world, blockpos.up()) - ? super.verifyExplosion(explosion, world, blockpos, iblockstate, f) - : false; + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + super.onUpdate(); + if (this.minecartTNTFuse > 0) { + --this.minecartTNTFuse; + this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, this.posX, this.posY + 0.5D, this.posZ, 0.0D, + 0.0D, 0.0D, new int[0]); + } else if (this.minecartTNTFuse == 0) { + this.explodeCart(this.motionX * this.motionX + this.motionZ * this.motionZ); + } + + if (this.isCollidedHorizontally) { + double d0 = this.motionX * this.motionX + this.motionZ * this.motionZ; + if (d0 >= 0.009999999776482582D) { + this.explodeCart(d0); + } + } + } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -208,15 +210,6 @@ public class EntityMinecartTNT extends EntityMinecart { } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("TNTFuse", this.minecartTNTFuse); - } - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, double renderY, double renderZ, float partialTicks, boolean isInFrustum) { super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, @@ -228,11 +221,19 @@ public class EntityMinecartTNT extends EntityMinecart { } } - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float f = super.getEaglerDynamicLightsValueSimple(partialTicks); - if (minecartTNTFuse > -1 && minecartTNTFuse / 5 % 2 == 0) { - f = Math.min(f + 0.75f, 1.25f); - } - return f; + public boolean verifyExplosion(Explosion explosion, World world, BlockPos blockpos, IBlockState iblockstate, + float f) { + return !this.isIgnited() + || !BlockRailBase.isRailBlock(iblockstate) && !BlockRailBase.isRailBlock(world, blockpos.up()) + ? super.verifyExplosion(explosion, world, blockpos, iblockstate, f) + : false; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("TNTFuse", this.minecartTNTFuse); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityPainting.java b/src/game/java/net/minecraft/entity/item/EntityPainting.java index 504abe6b..5ca6f013 100644 --- a/src/game/java/net/minecraft/entity/item/EntityPainting.java +++ b/src/game/java/net/minecraft/entity/item/EntityPainting.java @@ -14,27 +14,60 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityPainting extends EntityHanging { + public static enum EnumArt { + KEBAB("Kebab", 16, 16, 0, 0), AZTEC("Aztec", 16, 16, 16, 0), ALBAN("Alban", 16, 16, 32, 0), + AZTEC_2("Aztec2", 16, 16, 48, 0), BOMB("Bomb", 16, 16, 64, 0), PLANT("Plant", 16, 16, 80, 0), + WASTELAND("Wasteland", 16, 16, 96, 0), POOL("Pool", 32, 16, 0, 32), COURBET("Courbet", 32, 16, 32, 32), + SEA("Sea", 32, 16, 64, 32), SUNSET("Sunset", 32, 16, 96, 32), CREEBET("Creebet", 32, 16, 128, 32), + WANDERER("Wanderer", 16, 32, 0, 64), GRAHAM("Graham", 16, 32, 16, 64), MATCH("Match", 32, 32, 0, 128), + BUST("Bust", 32, 32, 32, 128), STAGE("Stage", 32, 32, 64, 128), VOID("Void", 32, 32, 96, 128), + SKULL_AND_ROSES("SkullAndRoses", 32, 32, 128, 128), WITHER("Wither", 32, 32, 160, 128), + FIGHTERS("Fighters", 64, 32, 0, 96), POINTER("Pointer", 64, 64, 0, 192), PIGSCENE("Pigscene", 64, 64, 64, 192), + BURNING_SKULL("BurningSkull", 64, 64, 128, 192), SKELETON("Skeleton", 64, 48, 192, 64), + DONKEY_KONG("DonkeyKong", 64, 48, 192, 112); + + public static final EnumArt[] _VALUES = values(); + + public static final int field_180001_A = "SkullAndRoses".length(); + public final String title; + public final int sizeX; + public final int sizeY; + public final int offsetX; + public final int offsetY; + + private EnumArt(String titleIn, int width, int height, int textureU, int textureV) { + this.title = titleIn; + this.sizeX = width; + this.sizeY = height; + this.offsetX = textureU; + this.offsetY = textureV; + } + } + public EntityPainting.EnumArt art; public EntityPainting(World worldIn) { @@ -76,18 +109,32 @@ public class EntityPainting extends EntityHanging { this.updateFacingWithBoundingBox(facing); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setString("Motive", this.art.title); - super.writeEntityToNBT(nbttagcompound); + public int getHeightPixels() { + return this.art.sizeY; } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + public int getWidthPixels() { + return this.art.sizeX; + } + + /** + * + Called when this entity is broken. Entity parameter may be null. + */ + public void onBroken(Entity entity) { + if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { + if (entity instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) entity; + if (entityplayer.capabilities.isCreativeMode) { + return; + } + } + + this.entityDropItem(new ItemStack(Items.painting), 0.0F); + } + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { String s = nbttagcompound.getString("Motive"); @@ -107,33 +154,8 @@ public class EntityPainting extends EntityHanging { super.readEntityFromNBT(nbttagcompound); } - public int getWidthPixels() { - return this.art.sizeX; - } - - public int getHeightPixels() { - return this.art.sizeY; - } - - /**+ - * Called when this entity is broken. Entity parameter may be - * null. - */ - public void onBroken(Entity entity) { - if (this.worldObj.getGameRules().getBoolean("doEntityDrops")) { - if (entity instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entity; - if (entityplayer.capabilities.isCreativeMode) { - return; - } - } - - this.entityDropItem(new ItemStack(Items.painting), 0.0F); - } - } - - /**+ - * Sets the location and Yaw/Pitch of an entity in the world + /** + * + Sets the location and Yaw/Pitch of an entity in the world */ public void setLocationAndAngles(double d0, double d1, double d2, float var7, float var8) { BlockPos blockpos = this.hangingPosition.add(d0 - this.posX, d1 - this.posY, d2 - this.posZ); @@ -146,33 +168,11 @@ public class EntityPainting extends EntityHanging { this.setPosition((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); } - public static enum EnumArt { - KEBAB("Kebab", 16, 16, 0, 0), AZTEC("Aztec", 16, 16, 16, 0), ALBAN("Alban", 16, 16, 32, 0), - AZTEC_2("Aztec2", 16, 16, 48, 0), BOMB("Bomb", 16, 16, 64, 0), PLANT("Plant", 16, 16, 80, 0), - WASTELAND("Wasteland", 16, 16, 96, 0), POOL("Pool", 32, 16, 0, 32), COURBET("Courbet", 32, 16, 32, 32), - SEA("Sea", 32, 16, 64, 32), SUNSET("Sunset", 32, 16, 96, 32), CREEBET("Creebet", 32, 16, 128, 32), - WANDERER("Wanderer", 16, 32, 0, 64), GRAHAM("Graham", 16, 32, 16, 64), MATCH("Match", 32, 32, 0, 128), - BUST("Bust", 32, 32, 32, 128), STAGE("Stage", 32, 32, 64, 128), VOID("Void", 32, 32, 96, 128), - SKULL_AND_ROSES("SkullAndRoses", 32, 32, 128, 128), WITHER("Wither", 32, 32, 160, 128), - FIGHTERS("Fighters", 64, 32, 0, 96), POINTER("Pointer", 64, 64, 0, 192), PIGSCENE("Pigscene", 64, 64, 64, 192), - BURNING_SKULL("BurningSkull", 64, 64, 128, 192), SKELETON("Skeleton", 64, 48, 192, 64), - DONKEY_KONG("DonkeyKong", 64, 48, 192, 112); - - public static final EnumArt[] _VALUES = values(); - - public static final int field_180001_A = "SkullAndRoses".length(); - public final String title; - public final int sizeX; - public final int sizeY; - public final int offsetX; - public final int offsetY; - - private EnumArt(String titleIn, int width, int height, int textureU, int textureV) { - this.title = titleIn; - this.sizeX = width; - this.sizeY = height; - this.offsetX = textureU; - this.offsetY = textureV; - } + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("Motive", this.art.title); + super.writeEntityToNBT(nbttagcompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityTNTPrimed.java b/src/game/java/net/minecraft/entity/item/EntityTNTPrimed.java index a03ac75b..451aea66 100644 --- a/src/game/java/net/minecraft/entity/item/EntityTNTPrimed.java +++ b/src/game/java/net/minecraft/entity/item/EntityTNTPrimed.java @@ -7,22 +7,25 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,28 +55,51 @@ public class EntityTNTPrimed extends Entity { this.tntPlacedBy = parEntityLivingBase; } - protected void entityInit() { - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. */ public boolean canBeCollidedWith() { return !this.isDead; } - /**+ - * Called to update the entity's position/logic. + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + + protected void entityInit() { + } + + private void explode() { + float f = 4.0F; + this.worldObj.createExplosion(this, this.posX, this.posY + (double) (this.height / 16.0F), this.posZ, f, true); + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + if (fuse / 5 % 2 == 0) { + f = Math.min(f + 0.75f, 1.25f); + } + return f; + } + + public float getEyeHeight() { + return 0.0F; + } + + /** + * + returns null or the entityliving it was placed or ignited by + */ + public EntityLivingBase getTntPlacedBy() { + return this.tntPlacedBy; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.prevPosX = this.posX; @@ -103,38 +129,13 @@ public class EntityTNTPrimed extends Entity { } - private void explode() { - float f = 4.0F; - this.worldObj.createExplosion(this, this.posX, this.posY + (double) (this.height / 16.0F), this.posZ, f, true); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setByte("Fuse", (byte) this.fuse); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ protected void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.fuse = nbttagcompound.getByte("Fuse"); } - /**+ - * returns null or the entityliving it was placed or ignited by - */ - public EntityLivingBase getTntPlacedBy() { - return this.tntPlacedBy; - } - - public float getEyeHeight() { - return 0.0F; - } - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, double renderY, double renderZ, float partialTicks, boolean isInFrustum) { super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, @@ -146,11 +147,10 @@ public class EntityTNTPrimed extends Entity { } } - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float f = super.getEaglerDynamicLightsValueSimple(partialTicks); - if (fuse / 5 % 2 == 0) { - f = Math.min(f + 0.75f, 1.25f); - } - return f; + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + protected void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setByte("Fuse", (byte) this.fuse); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/item/EntityXPOrb.java b/src/game/java/net/minecraft/entity/item/EntityXPOrb.java index aac19ccc..e8fed248 100644 --- a/src/game/java/net/minecraft/entity/item/EntityXPOrb.java +++ b/src/game/java/net/minecraft/entity/item/EntityXPOrb.java @@ -10,38 +10,64 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityXPOrb extends Entity { + /** + * + Get a fragment of the maximum experience points value for the supplied + * value of experience points value. + */ + public static int getXPSplit(int expValue) { + return expValue >= 2477 ? 2477 + : (expValue >= 1237 ? 1237 + : (expValue >= 617 ? 617 + : (expValue >= 307 ? 307 + : (expValue >= 149 ? 149 + : (expValue >= 73 ? 73 + : (expValue >= 37 ? 37 + : (expValue >= 17 ? 17 + : (expValue >= 7 ? 7 + : (expValue >= 3 ? 3 : 1))))))))); + } + public int xpColor; public int xpOrbAge; public int delayBeforeCanPickup; - /**+ - * The health of this XP orb. + /** + * + The health of this XP orb. */ private int xpOrbHealth = 5; private int xpValue; private EntityPlayer closestPlayer; + private int xpTargetColor; + public EntityXPOrb(World worldIn) { + super(worldIn); + this.setSize(0.25F, 0.25F); + } + public EntityXPOrb(World worldIn, double x, double y, double z, int expValue) { super(worldIn); this.setSize(0.5F, 0.5F); @@ -53,18 +79,44 @@ public class EntityXPOrb extends Entity { this.xpValue = expValue; } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + this.setBeenAttacked(); + this.xpOrbHealth = (int) ((float) this.xpOrbHealth - f); + if (this.xpOrbHealth <= 0) { + this.setDead(); + } + + return false; + } + } + + /** + * + If returns false, the item will not inflict any damage against entities. + */ + public boolean canAttackWithItem() { + return false; + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } - public EntityXPOrb(World worldIn) { - super(worldIn); - this.setSize(0.25F, 0.25F); + /** + * + Will deal the specified amount of damage to the entity if the entity isn't + * immune to fire damage. Args: amountDamage + */ + protected void dealFireDamage(int i) { + this.attackEntityFrom(DamageSource.inFire, (float) i); } protected void entityInit() { @@ -88,8 +140,57 @@ public class EntityXPOrb extends Entity { return 0.25f; } - /**+ - * Called to update the entity's position/logic. + /** + * + Returns a number from 1 to 10 based on how much XP this orb is worth. This + * is used by RenderXPOrb to determine what texture to use. + */ + public int getTextureByXP() { + return this.xpValue >= 2477 ? 10 + : (this.xpValue >= 1237 ? 9 + : (this.xpValue >= 617 ? 8 + : (this.xpValue >= 307 ? 7 + : (this.xpValue >= 149 ? 6 + : (this.xpValue >= 73 ? 5 + : (this.xpValue >= 37 ? 4 + : (this.xpValue >= 17 ? 3 + : (this.xpValue >= 7 ? 2 + : (this.xpValue >= 3 ? 1 : 0))))))))); + } + + /** + * + Returns the XP value of this XP orb. + */ + public int getXpValue() { + return this.xpValue; + } + + /** + * + Returns if this entity is in water and will end up adding the waters + * velocity to the entity + */ + public boolean handleWaterMovement() { + return this.worldObj.handleMaterialAcceleration(this.getEntityBoundingBox(), Material.water, this); + } + + /** + * + Called by a player entity when they collide with an entity + */ + public void onCollideWithPlayer(EntityPlayer entityplayer) { + if (!this.worldObj.isRemote) { + if (this.delayBeforeCanPickup == 0 && entityplayer.xpCooldown == 0) { + entityplayer.xpCooldown = 2; + this.worldObj.playSoundAtEntity(entityplayer, "random.orb", 0.1F, + 0.5F * ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.8F)); + entityplayer.onItemPickup(this, 1); + entityplayer.addExperience(this.xpValue); + this.setDead(); + } + + } + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -160,52 +261,8 @@ public class EntityXPOrb extends Entity { } - /**+ - * Returns if this entity is in water and will end up adding the - * waters velocity to the entity - */ - public boolean handleWaterMovement() { - return this.worldObj.handleMaterialAcceleration(this.getEntityBoundingBox(), Material.water, this); - } - - /**+ - * Will deal the specified amount of damage to the entity if the - * entity isn't immune to fire damage. Args: amountDamage - */ - protected void dealFireDamage(int i) { - this.attackEntityFrom(DamageSource.inFire, (float) i); - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - this.setBeenAttacked(); - this.xpOrbHealth = (int) ((float) this.xpOrbHealth - f); - if (this.xpOrbHealth <= 0) { - this.setDead(); - } - - return false; - } - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("Health", (short) ((byte) this.xpOrbHealth)); - nbttagcompound.setShort("Age", (short) this.xpOrbAge); - nbttagcompound.setShort("Value", (short) this.xpValue); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.xpOrbHealth = nbttagcompound.getShort("Health") & 255; @@ -213,73 +270,6 @@ public class EntityXPOrb extends Entity { this.xpValue = nbttagcompound.getShort("Value"); } - /**+ - * Called by a player entity when they collide with an entity - */ - public void onCollideWithPlayer(EntityPlayer entityplayer) { - if (!this.worldObj.isRemote) { - if (this.delayBeforeCanPickup == 0 && entityplayer.xpCooldown == 0) { - entityplayer.xpCooldown = 2; - this.worldObj.playSoundAtEntity(entityplayer, "random.orb", 0.1F, - 0.5F * ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.8F)); - entityplayer.onItemPickup(this, 1); - entityplayer.addExperience(this.xpValue); - this.setDead(); - } - - } - } - - /**+ - * Returns the XP value of this XP orb. - */ - public int getXpValue() { - return this.xpValue; - } - - /**+ - * Returns a number from 1 to 10 based on how much XP this orb - * is worth. This is used by RenderXPOrb to determine what - * texture to use. - */ - public int getTextureByXP() { - return this.xpValue >= 2477 ? 10 - : (this.xpValue >= 1237 ? 9 - : (this.xpValue >= 617 ? 8 - : (this.xpValue >= 307 ? 7 - : (this.xpValue >= 149 ? 6 - : (this.xpValue >= 73 ? 5 - : (this.xpValue >= 37 ? 4 - : (this.xpValue >= 17 ? 3 - : (this.xpValue >= 7 ? 2 - : (this.xpValue >= 3 ? 1 : 0))))))))); - } - - /**+ - * Get a fragment of the maximum experience points value for the - * supplied value of experience points value. - */ - public static int getXPSplit(int expValue) { - return expValue >= 2477 ? 2477 - : (expValue >= 1237 ? 1237 - : (expValue >= 617 ? 617 - : (expValue >= 307 ? 307 - : (expValue >= 149 ? 149 - : (expValue >= 73 ? 73 - : (expValue >= 37 ? 37 - : (expValue >= 17 ? 17 - : (expValue >= 7 ? 7 - : (expValue >= 3 ? 3 : 1))))))))); - } - - /**+ - * If returns false, the item will not inflict any damage - * against entities. - */ - public boolean canAttackWithItem() { - return false; - } - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, double renderY, double renderZ, float partialTicks, boolean isInFrustum) { super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, @@ -290,4 +280,13 @@ public class EntityXPOrb extends Entity { mag * 0.3f, mag, mag * 0.2f, false); } } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("Health", (short) ((byte) this.xpOrbHealth)); + nbttagcompound.setShort("Age", (short) this.xpOrbAge); + nbttagcompound.setShort("Value", (short) this.xpValue); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityBlaze.java b/src/game/java/net/minecraft/entity/monster/EntityBlaze.java index 344f931b..07056ecf 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityBlaze.java +++ b/src/game/java/net/minecraft/entity/monster/EntityBlaze.java @@ -20,195 +20,30 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityBlaze extends EntityMob { - /**+ - * Random offset used in floating behaviour - */ - private float heightOffset = 0.5F; - private int heightOffsetUpdateTime; - - public EntityBlaze(World worldIn) { - super(worldIn); - this.isImmuneToFire = true; - this.experienceValue = 10; - this.tasks.addTask(4, new EntityBlaze.AIFireballAttack(this)); - this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 1.0D)); - this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); - this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); - this.tasks.addTask(8, new EntityAILookIdle(this)); - this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true, new Class[0])); - this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(6.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.23000000417232513D); - this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(48.0D); - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.blaze.breathe"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.blaze.hit"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.blaze.death"; - } - - public int getBrightnessForRender(float var1) { - return 15728880; - } - - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float var1) { - return 1.0F; - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 1.0f; - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - if (!this.onGround && this.motionY < 0.0D) { - this.motionY *= 0.6D; - } - - if (this.worldObj.isRemote) { - if (this.rand.nextInt(24) == 0 && !this.isSilent()) { - this.worldObj.playSound(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.fire", - 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F, false); - } - - for (int i = 0; i < 2; ++i) { - this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_LARGE, - this.posX + (this.rand.nextDouble() - 0.5D) * (double) this.width, - this.posY + this.rand.nextDouble() * (double) this.height, - this.posZ + (this.rand.nextDouble() - 0.5D) * (double) this.width, 0.0D, 0.0D, 0.0D, - new int[0]); - } - } - - super.onLivingUpdate(); - } - - protected void updateAITasks() { - if (this.isWet()) { - this.attackEntityFrom(DamageSource.drown, 1.0F); - } - - --this.heightOffsetUpdateTime; - if (this.heightOffsetUpdateTime <= 0) { - this.heightOffsetUpdateTime = 100; - this.heightOffset = 0.5F + (float) this.rand.nextGaussian() * 3.0F; - } - - EntityLivingBase entitylivingbase = this.getAttackTarget(); - if (entitylivingbase != null && entitylivingbase.posY + (double) entitylivingbase.getEyeHeight() > this.posY - + (double) this.getEyeHeight() + (double) this.heightOffset) { - this.motionY += (0.30000001192092896D - this.motionY) * 0.30000001192092896D; - this.isAirBorne = true; - } - - super.updateAITasks(); - } - - public void fall(float var1, float var2) { - } - - protected Item getDropItem() { - return Items.blaze_rod; - } - - /**+ - * Returns true if the entity is on fire. Used by render to add - * the fire effect on rendering. - */ - public boolean isBurning() { - return this.func_70845_n(); - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean flag, int i) { - if (flag) { - int j = this.rand.nextInt(2 + i); - - for (int k = 0; k < j; ++k) { - this.dropItem(Items.blaze_rod, 1); - } - } - - } - - public boolean func_70845_n() { - return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; - } - - public void setOnFire(boolean onFire) { - byte b0 = this.dataWatcher.getWatchableObjectByte(16); - if (onFire) { - b0 = (byte) (b0 | 1); - } else { - b0 = (byte) (b0 & -2); - } - - this.dataWatcher.updateObject(16, Byte.valueOf(b0)); - } - - /**+ - * Checks to make sure the light is not too bright where the mob - * is spawning - */ - protected boolean isValidLightLevel() { - return true; - } - static class AIFireballAttack extends EntityAIBase { private EntityBlaze blaze; private int field_179467_b; @@ -219,6 +54,10 @@ public class EntityBlaze extends EntityMob { this.setMutexBits(3); } + public void resetTask() { + this.blaze.setOnFire(false); + } + public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.blaze.getAttackTarget(); return entitylivingbase != null && entitylivingbase.isEntityAlive(); @@ -228,10 +67,6 @@ public class EntityBlaze extends EntityMob { this.field_179467_b = 0; } - public void resetTask() { - this.blaze.setOnFire(false); - } - public void updateTask() { --this.field_179468_c; EntityLivingBase entitylivingbase = this.blaze.getAttackTarget(); @@ -288,10 +123,178 @@ public class EntityBlaze extends EntityMob { } } + /** + * + Random offset used in floating behaviour + */ + private float heightOffset = 0.5F; + + private int heightOffsetUpdateTime; + + public EntityBlaze(World worldIn) { + super(worldIn); + this.isImmuneToFire = true; + this.experienceValue = 10; + this.tasks.addTask(4, new EntityBlaze.AIFireballAttack(this)); + this.tasks.addTask(5, new EntityAIMoveTowardsRestriction(this, 1.0D)); + this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); + this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); + this.tasks.addTask(8, new EntityAILookIdle(this)); + this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true, new Class[0])); + this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(6.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.23000000417232513D); + this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(48.0D); + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean flag, int i) { + if (flag) { + int j = this.rand.nextInt(2 + i); + + for (int k = 0; k < j; ++k) { + this.dropItem(Items.blaze_rod, 1); + } + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + public void fall(float var1, float var2) { + } + + public boolean func_70845_n() { + return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; + } + + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float var1) { + return 1.0F; + } + + public int getBrightnessForRender(float var1) { + return 15728880; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.blaze.death"; + } + + protected Item getDropItem() { + return Items.blaze_rod; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 1.0f; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.blaze.hit"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.blaze.breathe"; + } + + /** + * + Returns true if the entity is on fire. Used by render to add the fire + * effect on rendering. + */ + public boolean isBurning() { + return this.func_70845_n(); + } + + /** + * + Checks to make sure the light is not too bright where the mob is spawning + */ + protected boolean isValidLightLevel() { + return true; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + if (!this.onGround && this.motionY < 0.0D) { + this.motionY *= 0.6D; + } + + if (this.worldObj.isRemote) { + if (this.rand.nextInt(24) == 0 && !this.isSilent()) { + this.worldObj.playSound(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.fire", + 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F, false); + } + + for (int i = 0; i < 2; ++i) { + this.worldObj.spawnParticle(EnumParticleTypes.SMOKE_LARGE, + this.posX + (this.rand.nextDouble() - 0.5D) * (double) this.width, + this.posY + this.rand.nextDouble() * (double) this.height, + this.posZ + (this.rand.nextDouble() - 0.5D) * (double) this.width, 0.0D, 0.0D, 0.0D, + new int[0]); + } + } + + super.onLivingUpdate(); + } + protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, double renderY, double renderZ, float partialTicks, boolean isInFrustum) { float mag = 5.0f; DynamicLightManager.renderDynamicLight("entity_" + getEntityId() + "_blaze", entityX, entityY + 0.75, entityZ, mag, 0.487f * mag, 0.1411f * mag, false); } + + public void setOnFire(boolean onFire) { + byte b0 = this.dataWatcher.getWatchableObjectByte(16); + if (onFire) { + b0 = (byte) (b0 | 1); + } else { + b0 = (byte) (b0 & -2); + } + + this.dataWatcher.updateObject(16, Byte.valueOf(b0)); + } + + protected void updateAITasks() { + if (this.isWet()) { + this.attackEntityFrom(DamageSource.drown, 1.0F); + } + + --this.heightOffsetUpdateTime; + if (this.heightOffsetUpdateTime <= 0) { + this.heightOffsetUpdateTime = 100; + this.heightOffset = 0.5F + (float) this.rand.nextGaussian() * 3.0F; + } + + EntityLivingBase entitylivingbase = this.getAttackTarget(); + if (entitylivingbase != null && entitylivingbase.posY + (double) entitylivingbase.getEyeHeight() > this.posY + + (double) this.getEyeHeight() + (double) this.heightOffset) { + this.motionY += (0.30000001192092896D - this.motionY) * 0.30000001192092896D; + this.isAirBorne = true; + } + + super.updateAITasks(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityCaveSpider.java b/src/game/java/net/minecraft/entity/monster/EntityCaveSpider.java index 77b2e22f..b2933b22 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityCaveSpider.java +++ b/src/game/java/net/minecraft/entity/monster/EntityCaveSpider.java @@ -10,22 +10,25 @@ import net.minecraft.world.DifficultyInstance; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,17 +65,16 @@ public class EntityCaveSpider extends EntitySpider { } } - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory + public float getEyeHeight() { + return 0.45F; + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory */ public IEntityLivingData onInitialSpawn(DifficultyInstance var1, IEntityLivingData ientitylivingdata) { return ientitylivingdata; } - - public float getEyeHeight() { - return 0.45F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityCreeper.java b/src/game/java/net/minecraft/entity/monster/EntityCreeper.java index 6ef39eec..f8c33400 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityCreeper.java +++ b/src/game/java/net/minecraft/entity/monster/EntityCreeper.java @@ -23,22 +23,25 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,8 +50,8 @@ public class EntityCreeper extends EntityMob { private int lastActiveTime; private int timeSinceIgnited; private int fuseTime = 30; - /**+ - * Explosion radius for this creeper. + /** + * + Explosion radius for this creeper. */ private int explosionRadius = 3; private int field_175494_bm = 0; @@ -71,12 +74,30 @@ public class EntityCreeper extends EntityMob { this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); } - /**+ - * The maximum height from where the entity is alowed to jump - * (used in pathfinder) + public boolean attackEntityAsMob(Entity var1) { + return true; + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) -1)); + this.dataWatcher.addObject(17, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); + } + + /** + * + Creates an explosion as determined by this creeper's power and explosion + * radius. */ - public int getMaxFallHeight() { - return this.getAttackTarget() == null ? 3 : 3 + (int) (this.getHealth() - 1.0F); + private void explode() { + if (!this.worldObj.isRemote) { + boolean flag = this.worldObj.getGameRules().getBoolean("mobGriefing"); + float f = this.getPowered() ? 2.0F : 1.0F; + this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, (float) this.explosionRadius * f, + flag); + this.setDead(); + } + } public void fall(float f, float f1) { @@ -88,51 +109,132 @@ public class EntityCreeper extends EntityMob { } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) -1)); - this.dataWatcher.addObject(17, Byte.valueOf((byte) 0)); - this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); + public void func_175493_co() { + ++this.field_175494_bm; } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Params: (Float)Render tick. Returns the intensity of the creeper's flash + * when it is ignited. */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - if (this.dataWatcher.getWatchableObjectByte(17) == 1) { - nbttagcompound.setBoolean("powered", true); - } - - nbttagcompound.setShort("Fuse", (short) this.fuseTime); - nbttagcompound.setByte("ExplosionRadius", (byte) this.explosionRadius); - nbttagcompound.setBoolean("ignited", this.hasIgnited()); + public float getCreeperFlashIntensity(float parFloat1) { + return ((float) this.lastActiveTime + (float) (this.timeSinceIgnited - this.lastActiveTime) * parFloat1) + / (float) (this.fuseTime - 2); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + Returns the current state of creeper, -1 is idle, 1 is 'in fuse' */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.dataWatcher.updateObject(17, Byte.valueOf((byte) (nbttagcompound.getBoolean("powered") ? 1 : 0))); - if (nbttagcompound.hasKey("Fuse", 99)) { - this.fuseTime = nbttagcompound.getShort("Fuse"); + public int getCreeperState() { + return this.dataWatcher.getWatchableObjectByte(16); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.creeper.death"; + } + + protected Item getDropItem() { + return Items.gunpowder; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + float ff = getCreeperFlashIntensity(partialTicks); + if ((int) (ff * 10.0F) % 2 != 0) { + f = Math.min(f + 0.5f, 1.15f); + } + return f; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.creeper.say"; + } + + /** + * + The maximum height from where the entity is alowed to jump (used in + * pathfinder) + */ + public int getMaxFallHeight() { + return this.getAttackTarget() == null ? 3 : 3 + (int) (this.getHealth() - 1.0F); + } + + /** + * + Returns true if the creeper is powered by a lightning bolt. + */ + public boolean getPowered() { + return this.dataWatcher.getWatchableObjectByte(17) == 1; + } + + public boolean hasIgnited() { + return this.dataWatcher.getWatchableObjectByte(18) != 0; + } + + public void ignite() { + this.dataWatcher.updateObject(18, Byte.valueOf((byte) 1)); + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + protected boolean interact(EntityPlayer entityplayer) { + ItemStack itemstack = entityplayer.inventory.getCurrentItem(); + if (itemstack != null && itemstack.getItem() == Items.flint_and_steel) { + this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.ignite", 1.0F, + this.rand.nextFloat() * 0.4F + 0.8F); + entityplayer.swingItem(); + if (!this.worldObj.isRemote) { + this.ignite(); + itemstack.damageItem(1, entityplayer); + return true; + } } - if (nbttagcompound.hasKey("ExplosionRadius", 99)) { - this.explosionRadius = nbttagcompound.getByte("ExplosionRadius"); - } + return super.interact(entityplayer); + } - if (nbttagcompound.getBoolean("ignited")) { - this.ignite(); + /** + * + Returns true if the newer Entity AI code should be run + */ + public boolean isAIEnabled() { + return this.field_175494_bm < 1 && this.worldObj.getGameRules().getBoolean("doMobLoot"); + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + super.onDeath(damagesource); + if (damagesource.getEntity() instanceof EntitySkeleton) { + int i = Item.getIdFromItem(Items.record_13); + int j = Item.getIdFromItem(Items.record_wait); + int k = i + this.rand.nextInt(j - i + 1); + this.dropItem(Item.getItemById(k), 1); + } else if (damagesource.getEntity() instanceof EntityCreeper && damagesource.getEntity() != this + && ((EntityCreeper) damagesource.getEntity()).getPowered() + && ((EntityCreeper) damagesource.getEntity()).isAIEnabled()) { + ((EntityCreeper) damagesource.getEntity()).func_175493_co(); + this.entityDropItem(new ItemStack(Items.skull, 1, 4), 0.0F); } } - /**+ - * Called to update the entity's position/logic. + /** + * + Called when a lightning bolt hits the entity. + */ + public void onStruckByLightning(EntityLightningBolt entitylightningbolt) { + super.onStruckByLightning(entitylightningbolt); + this.dataWatcher.updateObject(17, Byte.valueOf((byte) 1)); + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { if (this.isEntityAlive()) { @@ -160,140 +262,26 @@ public class EntityCreeper extends EntityMob { super.onUpdate(); } - /**+ - * Returns the sound this mob makes when it is hurt. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ - protected String getHurtSound() { - return "mob.creeper.say"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.creeper.death"; - } - - /**+ - * Called when the mob's health reaches 0. - */ - public void onDeath(DamageSource damagesource) { - super.onDeath(damagesource); - if (damagesource.getEntity() instanceof EntitySkeleton) { - int i = Item.getIdFromItem(Items.record_13); - int j = Item.getIdFromItem(Items.record_wait); - int k = i + this.rand.nextInt(j - i + 1); - this.dropItem(Item.getItemById(k), 1); - } else if (damagesource.getEntity() instanceof EntityCreeper && damagesource.getEntity() != this - && ((EntityCreeper) damagesource.getEntity()).getPowered() - && ((EntityCreeper) damagesource.getEntity()).isAIEnabled()) { - ((EntityCreeper) damagesource.getEntity()).func_175493_co(); - this.entityDropItem(new ItemStack(Items.skull, 1, 4), 0.0F); + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.dataWatcher.updateObject(17, Byte.valueOf((byte) (nbttagcompound.getBoolean("powered") ? 1 : 0))); + if (nbttagcompound.hasKey("Fuse", 99)) { + this.fuseTime = nbttagcompound.getShort("Fuse"); } - } - - public boolean attackEntityAsMob(Entity var1) { - return true; - } - - /**+ - * Returns true if the creeper is powered by a lightning bolt. - */ - public boolean getPowered() { - return this.dataWatcher.getWatchableObjectByte(17) == 1; - } - - /**+ - * Params: (Float)Render tick. Returns the intensity of the - * creeper's flash when it is ignited. - */ - public float getCreeperFlashIntensity(float parFloat1) { - return ((float) this.lastActiveTime + (float) (this.timeSinceIgnited - this.lastActiveTime) * parFloat1) - / (float) (this.fuseTime - 2); - } - - protected Item getDropItem() { - return Items.gunpowder; - } - - /**+ - * Returns the current state of creeper, -1 is idle, 1 is 'in - * fuse' - */ - public int getCreeperState() { - return this.dataWatcher.getWatchableObjectByte(16); - } - - /**+ - * Sets the state of creeper, -1 to idle and 1 to be 'in fuse' - */ - public void setCreeperState(int state) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) state)); - } - - /**+ - * Called when a lightning bolt hits the entity. - */ - public void onStruckByLightning(EntityLightningBolt entitylightningbolt) { - super.onStruckByLightning(entitylightningbolt); - this.dataWatcher.updateObject(17, Byte.valueOf((byte) 1)); - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. - */ - protected boolean interact(EntityPlayer entityplayer) { - ItemStack itemstack = entityplayer.inventory.getCurrentItem(); - if (itemstack != null && itemstack.getItem() == Items.flint_and_steel) { - this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.ignite", 1.0F, - this.rand.nextFloat() * 0.4F + 0.8F); - entityplayer.swingItem(); - if (!this.worldObj.isRemote) { - this.ignite(); - itemstack.damageItem(1, entityplayer); - return true; - } + if (nbttagcompound.hasKey("ExplosionRadius", 99)) { + this.explosionRadius = nbttagcompound.getByte("ExplosionRadius"); } - return super.interact(entityplayer); - } - - /**+ - * Creates an explosion as determined by this creeper's power - * and explosion radius. - */ - private void explode() { - if (!this.worldObj.isRemote) { - boolean flag = this.worldObj.getGameRules().getBoolean("mobGriefing"); - float f = this.getPowered() ? 2.0F : 1.0F; - this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, (float) this.explosionRadius * f, - flag); - this.setDead(); + if (nbttagcompound.getBoolean("ignited")) { + this.ignite(); } } - public boolean hasIgnited() { - return this.dataWatcher.getWatchableObjectByte(18) != 0; - } - - public void ignite() { - this.dataWatcher.updateObject(18, Byte.valueOf((byte) 1)); - } - - /**+ - * Returns true if the newer Entity AI code should be run - */ - public boolean isAIEnabled() { - return this.field_175494_bm < 1 && this.worldObj.getGameRules().getBoolean("doMobLoot"); - } - - public void func_175493_co() { - ++this.field_175494_bm; - } - protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, double renderY, double renderZ, float partialTicks, boolean isInFrustum) { super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, @@ -307,12 +295,24 @@ public class EntityCreeper extends EntityMob { } } - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - float f = super.getEaglerDynamicLightsValueSimple(partialTicks); - float ff = getCreeperFlashIntensity(partialTicks); - if ((int) (ff * 10.0F) % 2 != 0) { - f = Math.min(f + 0.5f, 1.15f); + /** + * + Sets the state of creeper, -1 to idle and 1 to be 'in fuse' + */ + public void setCreeperState(int state) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) state)); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + if (this.dataWatcher.getWatchableObjectByte(17) == 1) { + nbttagcompound.setBoolean("powered", true); } - return f; + + nbttagcompound.setShort("Fuse", (short) this.fuseTime); + nbttagcompound.setByte("ExplosionRadius", (byte) this.explosionRadius); + nbttagcompound.setBoolean("ignited", this.hasIgnited()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityEnderman.java b/src/game/java/net/minecraft/entity/monster/EntityEnderman.java index 40f33636..38d16b11 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityEnderman.java +++ b/src/game/java/net/minecraft/entity/monster/EntityEnderman.java @@ -1,11 +1,13 @@ package net.minecraft.entity.monster; +import java.util.Collections; +import java.util.List; +import java.util.Set; + import com.google.common.base.Predicate; import com.google.common.collect.Sets; -import java.util.Collections; -import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import java.util.Set; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.Block; import net.minecraft.block.material.Material; @@ -39,32 +41,207 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityEnderman extends EntityMob { + static class AIFindPlayer extends EntityAINearestAttackableTarget { + private EntityPlayer player; + private int field_179450_h; + private int field_179451_i; + private EntityEnderman enderman; + + public AIFindPlayer(EntityEnderman parEntityEnderman) { + super(parEntityEnderman, EntityPlayer.class, true); + this.enderman = parEntityEnderman; + } + + public boolean continueExecuting() { + if (this.player != null) { + if (!this.enderman.shouldAttackPlayer(this.player)) { + return false; + } else { + this.enderman.isAggressive = true; + this.enderman.faceEntity(this.player, 10.0F, 10.0F); + return true; + } + } else { + return super.continueExecuting(); + } + } + + public void resetTask() { + this.player = null; + this.enderman.setScreaming(false); + IAttributeInstance iattributeinstance = this.enderman + .getEntityAttribute(SharedMonsterAttributes.movementSpeed); + iattributeinstance.removeModifier(EntityEnderman.attackingSpeedBoostModifier); + super.resetTask(); + } + + public boolean shouldExecute() { + double d0 = this.getTargetDistance(); + List list = this.taskOwner.worldObj.getEntitiesWithinAABB(EntityPlayer.class, + this.taskOwner.getEntityBoundingBox().expand(d0, 4.0D, d0), this.targetEntitySelector); + Collections.sort(list, this.theNearestAttackableTargetSorter); + if (list.isEmpty()) { + return false; + } else { + this.player = (EntityPlayer) list.get(0); + return true; + } + } + + public void startExecuting() { + this.field_179450_h = 5; + this.field_179451_i = 0; + } + + public void updateTask() { + if (this.player != null) { + if (--this.field_179450_h <= 0) { + this.targetEntity = this.player; + this.player = null; + super.startExecuting(); + this.enderman.playSound("mob.endermen.stare", 1.0F, 1.0F); + this.enderman.setScreaming(true); + IAttributeInstance iattributeinstance = this.enderman + .getEntityAttribute(SharedMonsterAttributes.movementSpeed); + iattributeinstance.applyModifier(EntityEnderman.attackingSpeedBoostModifier); + } + } else { + if (this.targetEntity != null) { + if (this.targetEntity instanceof EntityPlayer + && this.enderman.shouldAttackPlayer((EntityPlayer) this.targetEntity)) { + if (this.targetEntity.getDistanceSqToEntity(this.enderman) < 16.0D) { + this.enderman.teleportRandomly(); + } + + this.field_179451_i = 0; + } else if (this.targetEntity.getDistanceSqToEntity(this.enderman) > 256.0D + && this.field_179451_i++ >= 30 && this.enderman.teleportToEntity(this.targetEntity)) { + this.field_179451_i = 0; + } + } + + super.updateTask(); + } + + } + } + + static class AIPlaceBlock extends EntityAIBase { + private EntityEnderman enderman; + + public AIPlaceBlock(EntityEnderman parEntityEnderman) { + this.enderman = parEntityEnderman; + } + + private boolean func_179474_a(World worldIn, BlockPos parBlockPos, Block parBlock, Block parBlock2, + Block parBlock3) { + return !parBlock.canPlaceBlockAt(worldIn, parBlockPos) ? false + : (parBlock2.getMaterial() != Material.air ? false + : (parBlock3.getMaterial() == Material.air ? false : parBlock3.isFullCube())); + } + + public boolean shouldExecute() { + return !this.enderman.worldObj.getGameRules().getBoolean("mobGriefing") ? false + : (this.enderman.getHeldBlockState().getBlock().getMaterial() == Material.air ? false + : this.enderman.getRNG().nextInt(2000) == 0); + } + + public void updateTask() { + EaglercraftRandom random = this.enderman.getRNG(); + World world = this.enderman.worldObj; + int i = MathHelper.floor_double(this.enderman.posX - 1.0D + random.nextDouble() * 2.0D); + int j = MathHelper.floor_double(this.enderman.posY + random.nextDouble() * 2.0D); + int k = MathHelper.floor_double(this.enderman.posZ - 1.0D + random.nextDouble() * 2.0D); + BlockPos blockpos = new BlockPos(i, j, k); + Block block = world.getBlockState(blockpos).getBlock(); + Block block1 = world.getBlockState(blockpos.down()).getBlock(); + if (this.func_179474_a(world, blockpos, this.enderman.getHeldBlockState().getBlock(), block, block1)) { + world.setBlockState(blockpos, this.enderman.getHeldBlockState(), 3); + this.enderman.setHeldBlockState(Blocks.air.getDefaultState()); + } + + } + } + + static class AITakeBlock extends EntityAIBase { + private EntityEnderman enderman; + + public AITakeBlock(EntityEnderman parEntityEnderman) { + this.enderman = parEntityEnderman; + } + + public boolean shouldExecute() { + return !this.enderman.worldObj.getGameRules().getBoolean("mobGriefing") ? false + : (this.enderman.getHeldBlockState().getBlock().getMaterial() != Material.air ? false + : this.enderman.getRNG().nextInt(20) == 0); + } + + public void updateTask() { + EaglercraftRandom random = this.enderman.getRNG(); + World world = this.enderman.worldObj; + int i = MathHelper.floor_double(this.enderman.posX - 2.0D + random.nextDouble() * 4.0D); + int j = MathHelper.floor_double(this.enderman.posY + random.nextDouble() * 3.0D); + int k = MathHelper.floor_double(this.enderman.posZ - 2.0D + random.nextDouble() * 4.0D); + BlockPos blockpos = new BlockPos(i, j, k); + IBlockState iblockstate = world.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + if (EntityEnderman.carriableBlocks.contains(block)) { + this.enderman.setHeldBlockState(iblockstate); + world.setBlockState(blockpos, Blocks.air.getDefaultState()); + } + + } + } + private static final EaglercraftUUID attackingSpeedBoostModifierUUID = EaglercraftUUID .fromString("020E0DFB-87AE-4653-9556-831010E291A0"); + private static final AttributeModifier attackingSpeedBoostModifier = (new AttributeModifier( attackingSpeedBoostModifierUUID, "Attacking speed boost", 0.15000000596046448D, 0)).setSaved(false); + private static final Set carriableBlocks = Sets.newIdentityHashSet(); + + public static void bootstrap() { + carriableBlocks.add(Blocks.grass); + carriableBlocks.add(Blocks.dirt); + carriableBlocks.add(Blocks.sand); + carriableBlocks.add(Blocks.gravel); + carriableBlocks.add(Blocks.yellow_flower); + carriableBlocks.add(Blocks.red_flower); + carriableBlocks.add(Blocks.brown_mushroom); + carriableBlocks.add(Blocks.red_mushroom); + carriableBlocks.add(Blocks.tnt); + carriableBlocks.add(Blocks.cactus); + carriableBlocks.add(Blocks.clay); + carriableBlocks.add(Blocks.pumpkin); + carriableBlocks.add(Blocks.melon_block); + carriableBlocks.add(Blocks.mycelium); + } + private boolean isAggressive; public EntityEnderman(World worldIn) { @@ -96,6 +273,64 @@ public class EntityEnderman extends EntityMob { this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(64.0D); } + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + if (damagesource.getEntity() == null || !(damagesource.getEntity() instanceof EntityEndermite)) { + if (!this.worldObj.isRemote) { + this.setScreaming(true); + } + + if (damagesource instanceof EntityDamageSource && damagesource.getEntity() instanceof EntityPlayer) { + if (damagesource.getEntity() instanceof EntityPlayerMP + && ((EntityPlayerMP) damagesource.getEntity()).theItemInWorldManager.isCreative()) { + this.setScreaming(false); + } else { + this.isAggressive = true; + } + } + + if (damagesource instanceof EntityDamageSourceIndirect) { + this.isAggressive = false; + + for (int i = 0; i < 64; ++i) { + if (this.teleportRandomly()) { + return true; + } + } + + return false; + } + } + + boolean flag = super.attackEntityFrom(damagesource, f); + if (damagesource.isUnblockable() && this.rand.nextInt(10) != 0) { + this.teleportRandomly(); + } + + return flag; + } + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + Item item = this.getDropItem(); + if (item != null) { + int j = this.rand.nextInt(2 + i); + + for (int k = 0; k < j; ++k) { + this.dropItem(item, 1); + } + } + + } + protected void entityInit() { super.entityInit(); this.dataWatcher.addObject(16, Short.valueOf((short) 0)); @@ -103,63 +338,50 @@ public class EntityEnderman extends EntityMob { this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Returns the sound this mob makes on death. */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - IBlockState iblockstate = this.getHeldBlockState(); - nbttagcompound.setShort("carried", (short) Block.getIdFromBlock(iblockstate.getBlock())); - nbttagcompound.setShort("carriedData", (short) iblockstate.getBlock().getMetaFromState(iblockstate)); + protected String getDeathSound() { + return "mob.endermen.death"; } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - IBlockState iblockstate; - if (nbttagcompound.hasKey("carried", 8)) { - iblockstate = Block.getBlockFromName(nbttagcompound.getString("carried")) - .getStateFromMeta(nbttagcompound.getShort("carriedData") & '\uffff'); - } else { - iblockstate = Block.getBlockById(nbttagcompound.getShort("carried")) - .getStateFromMeta(nbttagcompound.getShort("carriedData") & '\uffff'); - } - - this.setHeldBlockState(iblockstate); - } - - /**+ - * Checks to see if this enderman should be attacking this - * player - */ - private boolean shouldAttackPlayer(EntityPlayer player) { - ItemStack itemstack = player.inventory.armorInventory[3]; - if (itemstack != null && itemstack.getItem() == Item.getItemFromBlock(Blocks.pumpkin)) { - return false; - } else { - Vec3 vec3 = player.getLook(1.0F).normalize(); - Vec3 vec31 = new Vec3(this.posX - player.posX, this.getEntityBoundingBox().minY - + (double) (this.height / 2.0F) - (player.posY + (double) player.getEyeHeight()), - this.posZ - player.posZ); - double d0 = vec31.lengthVector(); - vec31 = vec31.normalize(); - double d1 = vec3.dotProduct(vec31); - return d1 > 1.0D - 0.025D / d0 ? player.canEntityBeSeen(this) : false; - } + protected Item getDropItem() { + return Items.ender_pearl; } public float getEyeHeight() { return 2.55F; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Gets this enderman's held block state + */ + public IBlockState getHeldBlockState() { + return Block.getStateById(this.dataWatcher.getWatchableObjectShort(16) & '\uffff'); + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.endermen.hit"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return this.isScreaming() ? "mob.endermen.scream" : "mob.endermen.idle"; + } + + public boolean isScreaming() { + return this.dataWatcher.getWatchableObjectByte(18) > 0; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (this.worldObj.isRemote) { @@ -177,31 +399,55 @@ public class EntityEnderman extends EntityMob { super.onLivingUpdate(); } - protected void updateAITasks() { - if (this.isWet()) { - this.attackEntityFrom(DamageSource.drown, 1.0F); + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + IBlockState iblockstate; + if (nbttagcompound.hasKey("carried", 8)) { + iblockstate = Block.getBlockFromName(nbttagcompound.getString("carried")) + .getStateFromMeta(nbttagcompound.getShort("carriedData") & '\uffff'); + } else { + iblockstate = Block.getBlockById(nbttagcompound.getShort("carried")) + .getStateFromMeta(nbttagcompound.getShort("carriedData") & '\uffff'); } - if (this.isScreaming() && !this.isAggressive && this.rand.nextInt(100) == 0) { - this.setScreaming(false); - } - - if (this.worldObj.isDaytime()) { - float f = this.getBrightness(1.0F); - if (f > 0.5F && this.worldObj.canSeeSky(new BlockPos(this)) - && this.rand.nextFloat() * 30.0F < (f - 0.4F) * 2.0F) { - this.setAttackTarget((EntityLivingBase) null); - this.setScreaming(false); - this.isAggressive = false; - this.teleportRandomly(); - } - } - - super.updateAITasks(); + this.setHeldBlockState(iblockstate); } - /**+ - * Teleport the enderman to a random nearby position + /** + * + Sets this enderman's held block state + */ + public void setHeldBlockState(IBlockState state) { + this.dataWatcher.updateObject(16, Short.valueOf((short) (Block.getStateId(state) & '\uffff'))); + } + + public void setScreaming(boolean screaming) { + this.dataWatcher.updateObject(18, Byte.valueOf((byte) (screaming ? 1 : 0))); + } + + /** + * + Checks to see if this enderman should be attacking this player + */ + private boolean shouldAttackPlayer(EntityPlayer player) { + ItemStack itemstack = player.inventory.armorInventory[3]; + if (itemstack != null && itemstack.getItem() == Item.getItemFromBlock(Blocks.pumpkin)) { + return false; + } else { + Vec3 vec3 = player.getLook(1.0F).normalize(); + Vec3 vec31 = new Vec3(this.posX - player.posX, this.getEntityBoundingBox().minY + + (double) (this.height / 2.0F) - (player.posY + (double) player.getEyeHeight()), + this.posZ - player.posZ); + double d0 = vec31.lengthVector(); + vec31 = vec31.normalize(); + double d1 = vec3.dotProduct(vec31); + return d1 > 1.0D - 0.025D / d0 ? player.canEntityBeSeen(this) : false; + } + } + + /** + * + Teleport the enderman to a random nearby position */ protected boolean teleportRandomly() { double d0 = this.posX + (this.rand.nextDouble() - 0.5D) * 64.0D; @@ -210,23 +456,8 @@ public class EntityEnderman extends EntityMob { return this.teleportTo(d0, d1, d2); } - /**+ - * Teleport the enderman to another entity - */ - protected boolean teleportToEntity(Entity parEntity) { - Vec3 vec3 = new Vec3(this.posX - parEntity.posX, this.getEntityBoundingBox().minY - + (double) (this.height / 2.0F) - parEntity.posY + (double) parEntity.getEyeHeight(), - this.posZ - parEntity.posZ); - vec3 = vec3.normalize(); - double d0 = 16.0D; - double d1 = this.posX + (this.rand.nextDouble() - 0.5D) * 8.0D - vec3.xCoord * d0; - double d2 = this.posY + (double) (this.rand.nextInt(16) - 8) - vec3.yCoord * d0; - double d3 = this.posZ + (this.rand.nextDouble() - 0.5D) * 8.0D - vec3.zCoord * d0; - return this.teleportTo(d1, d2, d3); - } - - /**+ - * Teleport the enderman + /** + * + Teleport the enderman */ protected boolean teleportTo(double x, double y, double z) { double d0 = this.posX; @@ -284,277 +515,51 @@ public class EntityEnderman extends EntityMob { } } - /**+ - * Returns the sound this mob makes while it's alive. + /** + * + Teleport the enderman to another entity */ - protected String getLivingSound() { - return this.isScreaming() ? "mob.endermen.scream" : "mob.endermen.idle"; + protected boolean teleportToEntity(Entity parEntity) { + Vec3 vec3 = new Vec3(this.posX - parEntity.posX, this.getEntityBoundingBox().minY + + (double) (this.height / 2.0F) - parEntity.posY + (double) parEntity.getEyeHeight(), + this.posZ - parEntity.posZ); + vec3 = vec3.normalize(); + double d0 = 16.0D; + double d1 = this.posX + (this.rand.nextDouble() - 0.5D) * 8.0D - vec3.xCoord * d0; + double d2 = this.posY + (double) (this.rand.nextInt(16) - 8) - vec3.yCoord * d0; + double d3 = this.posZ + (this.rand.nextDouble() - 0.5D) * 8.0D - vec3.zCoord * d0; + return this.teleportTo(d1, d2, d3); } - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.endermen.hit"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.endermen.death"; - } - - protected Item getDropItem() { - return Items.ender_pearl; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - Item item = this.getDropItem(); - if (item != null) { - int j = this.rand.nextInt(2 + i); - - for (int k = 0; k < j; ++k) { - this.dropItem(item, 1); - } + protected void updateAITasks() { + if (this.isWet()) { + this.attackEntityFrom(DamageSource.drown, 1.0F); } - } + if (this.isScreaming() && !this.isAggressive && this.rand.nextInt(100) == 0) { + this.setScreaming(false); + } - /**+ - * Sets this enderman's held block state - */ - public void setHeldBlockState(IBlockState state) { - this.dataWatcher.updateObject(16, Short.valueOf((short) (Block.getStateId(state) & '\uffff'))); - } - - /**+ - * Gets this enderman's held block state - */ - public IBlockState getHeldBlockState() { - return Block.getStateById(this.dataWatcher.getWatchableObjectShort(16) & '\uffff'); - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - if (damagesource.getEntity() == null || !(damagesource.getEntity() instanceof EntityEndermite)) { - if (!this.worldObj.isRemote) { - this.setScreaming(true); - } - - if (damagesource instanceof EntityDamageSource && damagesource.getEntity() instanceof EntityPlayer) { - if (damagesource.getEntity() instanceof EntityPlayerMP - && ((EntityPlayerMP) damagesource.getEntity()).theItemInWorldManager.isCreative()) { - this.setScreaming(false); - } else { - this.isAggressive = true; - } - } - - if (damagesource instanceof EntityDamageSourceIndirect) { - this.isAggressive = false; - - for (int i = 0; i < 64; ++i) { - if (this.teleportRandomly()) { - return true; - } - } - - return false; - } - } - - boolean flag = super.attackEntityFrom(damagesource, f); - if (damagesource.isUnblockable() && this.rand.nextInt(10) != 0) { + if (this.worldObj.isDaytime()) { + float f = this.getBrightness(1.0F); + if (f > 0.5F && this.worldObj.canSeeSky(new BlockPos(this)) + && this.rand.nextFloat() * 30.0F < (f - 0.4F) * 2.0F) { + this.setAttackTarget((EntityLivingBase) null); + this.setScreaming(false); + this.isAggressive = false; this.teleportRandomly(); } - - return flag; } + + super.updateAITasks(); } - public boolean isScreaming() { - return this.dataWatcher.getWatchableObjectByte(18) > 0; - } - - public void setScreaming(boolean screaming) { - this.dataWatcher.updateObject(18, Byte.valueOf((byte) (screaming ? 1 : 0))); - } - - public static void bootstrap() { - carriableBlocks.add(Blocks.grass); - carriableBlocks.add(Blocks.dirt); - carriableBlocks.add(Blocks.sand); - carriableBlocks.add(Blocks.gravel); - carriableBlocks.add(Blocks.yellow_flower); - carriableBlocks.add(Blocks.red_flower); - carriableBlocks.add(Blocks.brown_mushroom); - carriableBlocks.add(Blocks.red_mushroom); - carriableBlocks.add(Blocks.tnt); - carriableBlocks.add(Blocks.cactus); - carriableBlocks.add(Blocks.clay); - carriableBlocks.add(Blocks.pumpkin); - carriableBlocks.add(Blocks.melon_block); - carriableBlocks.add(Blocks.mycelium); - } - - static class AIFindPlayer extends EntityAINearestAttackableTarget { - private EntityPlayer player; - private int field_179450_h; - private int field_179451_i; - private EntityEnderman enderman; - - public AIFindPlayer(EntityEnderman parEntityEnderman) { - super(parEntityEnderman, EntityPlayer.class, true); - this.enderman = parEntityEnderman; - } - - public boolean shouldExecute() { - double d0 = this.getTargetDistance(); - List list = this.taskOwner.worldObj.getEntitiesWithinAABB(EntityPlayer.class, - this.taskOwner.getEntityBoundingBox().expand(d0, 4.0D, d0), this.targetEntitySelector); - Collections.sort(list, this.theNearestAttackableTargetSorter); - if (list.isEmpty()) { - return false; - } else { - this.player = (EntityPlayer) list.get(0); - return true; - } - } - - public void startExecuting() { - this.field_179450_h = 5; - this.field_179451_i = 0; - } - - public void resetTask() { - this.player = null; - this.enderman.setScreaming(false); - IAttributeInstance iattributeinstance = this.enderman - .getEntityAttribute(SharedMonsterAttributes.movementSpeed); - iattributeinstance.removeModifier(EntityEnderman.attackingSpeedBoostModifier); - super.resetTask(); - } - - public boolean continueExecuting() { - if (this.player != null) { - if (!this.enderman.shouldAttackPlayer(this.player)) { - return false; - } else { - this.enderman.isAggressive = true; - this.enderman.faceEntity(this.player, 10.0F, 10.0F); - return true; - } - } else { - return super.continueExecuting(); - } - } - - public void updateTask() { - if (this.player != null) { - if (--this.field_179450_h <= 0) { - this.targetEntity = this.player; - this.player = null; - super.startExecuting(); - this.enderman.playSound("mob.endermen.stare", 1.0F, 1.0F); - this.enderman.setScreaming(true); - IAttributeInstance iattributeinstance = this.enderman - .getEntityAttribute(SharedMonsterAttributes.movementSpeed); - iattributeinstance.applyModifier(EntityEnderman.attackingSpeedBoostModifier); - } - } else { - if (this.targetEntity != null) { - if (this.targetEntity instanceof EntityPlayer - && this.enderman.shouldAttackPlayer((EntityPlayer) this.targetEntity)) { - if (this.targetEntity.getDistanceSqToEntity(this.enderman) < 16.0D) { - this.enderman.teleportRandomly(); - } - - this.field_179451_i = 0; - } else if (this.targetEntity.getDistanceSqToEntity(this.enderman) > 256.0D - && this.field_179451_i++ >= 30 && this.enderman.teleportToEntity(this.targetEntity)) { - this.field_179451_i = 0; - } - } - - super.updateTask(); - } - - } - } - - static class AIPlaceBlock extends EntityAIBase { - private EntityEnderman enderman; - - public AIPlaceBlock(EntityEnderman parEntityEnderman) { - this.enderman = parEntityEnderman; - } - - public boolean shouldExecute() { - return !this.enderman.worldObj.getGameRules().getBoolean("mobGriefing") ? false - : (this.enderman.getHeldBlockState().getBlock().getMaterial() == Material.air ? false - : this.enderman.getRNG().nextInt(2000) == 0); - } - - public void updateTask() { - EaglercraftRandom random = this.enderman.getRNG(); - World world = this.enderman.worldObj; - int i = MathHelper.floor_double(this.enderman.posX - 1.0D + random.nextDouble() * 2.0D); - int j = MathHelper.floor_double(this.enderman.posY + random.nextDouble() * 2.0D); - int k = MathHelper.floor_double(this.enderman.posZ - 1.0D + random.nextDouble() * 2.0D); - BlockPos blockpos = new BlockPos(i, j, k); - Block block = world.getBlockState(blockpos).getBlock(); - Block block1 = world.getBlockState(blockpos.down()).getBlock(); - if (this.func_179474_a(world, blockpos, this.enderman.getHeldBlockState().getBlock(), block, block1)) { - world.setBlockState(blockpos, this.enderman.getHeldBlockState(), 3); - this.enderman.setHeldBlockState(Blocks.air.getDefaultState()); - } - - } - - private boolean func_179474_a(World worldIn, BlockPos parBlockPos, Block parBlock, Block parBlock2, - Block parBlock3) { - return !parBlock.canPlaceBlockAt(worldIn, parBlockPos) ? false - : (parBlock2.getMaterial() != Material.air ? false - : (parBlock3.getMaterial() == Material.air ? false : parBlock3.isFullCube())); - } - } - - static class AITakeBlock extends EntityAIBase { - private EntityEnderman enderman; - - public AITakeBlock(EntityEnderman parEntityEnderman) { - this.enderman = parEntityEnderman; - } - - public boolean shouldExecute() { - return !this.enderman.worldObj.getGameRules().getBoolean("mobGriefing") ? false - : (this.enderman.getHeldBlockState().getBlock().getMaterial() != Material.air ? false - : this.enderman.getRNG().nextInt(20) == 0); - } - - public void updateTask() { - EaglercraftRandom random = this.enderman.getRNG(); - World world = this.enderman.worldObj; - int i = MathHelper.floor_double(this.enderman.posX - 2.0D + random.nextDouble() * 4.0D); - int j = MathHelper.floor_double(this.enderman.posY + random.nextDouble() * 3.0D); - int k = MathHelper.floor_double(this.enderman.posZ - 2.0D + random.nextDouble() * 4.0D); - BlockPos blockpos = new BlockPos(i, j, k); - IBlockState iblockstate = world.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - if (EntityEnderman.carriableBlocks.contains(block)) { - this.enderman.setHeldBlockState(iblockstate); - world.setBlockState(blockpos, Blocks.air.getDefaultState()); - } - - } + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + IBlockState iblockstate = this.getHeldBlockState(); + nbttagcompound.setShort("carried", (short) Block.getIdFromBlock(iblockstate.getBlock())); + nbttagcompound.setShort("carriedData", (short) iblockstate.getBlock().getMetaFromState(iblockstate)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityEndermite.java b/src/game/java/net/minecraft/entity/monster/EntityEndermite.java index 6b515fde..c982717d 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityEndermite.java +++ b/src/game/java/net/minecraft/entity/monster/EntityEndermite.java @@ -17,22 +17,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,10 +57,6 @@ public class EntityEndermite extends EntityMob { this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); } - public float getEyeHeight() { - return 0.1F; - } - protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D); @@ -65,87 +64,78 @@ public class EntityEndermite extends EntityMob { this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(2.0D); } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } - /**+ - * Returns the sound this mob makes while it's alive. + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. */ - protected String getLivingSound() { - return "mob.silverfish.say"; + public boolean getCanSpawnHere() { + if (super.getCanSpawnHere()) { + EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D); + return entityplayer == null; + } else { + return false; + } } - /**+ - * Returns the sound this mob makes when it is hurt. + /** + * + Get this Entity's EnumCreatureAttribute */ - protected String getHurtSound() { - return "mob.silverfish.hit"; + public EnumCreatureAttribute getCreatureAttribute() { + return EnumCreatureAttribute.ARTHROPOD; } - /**+ - * Returns the sound this mob makes on death. + /** + * + Returns the sound this mob makes on death. */ protected String getDeathSound() { return "mob.silverfish.kill"; } - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.silverfish.step", 0.15F, 1.0F); - } - protected Item getDropItem() { return null; } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.lifetime = nbttagcompound.getInteger("Lifetime"); - this.playerSpawned = nbttagcompound.getBoolean("PlayerSpawned"); + public float getEyeHeight() { + return 0.1F; } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Returns the sound this mob makes when it is hurt. */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("Lifetime", this.lifetime); - nbttagcompound.setBoolean("PlayerSpawned", this.playerSpawned); + protected String getHurtSound() { + return "mob.silverfish.hit"; } - /**+ - * Called to update the entity's position/logic. + /** + * + Returns the sound this mob makes while it's alive. */ - public void onUpdate() { - this.renderYawOffset = this.rotationYaw; - super.onUpdate(); + protected String getLivingSound() { + return "mob.silverfish.say"; } public boolean isSpawnedByPlayer() { return this.playerSpawned; } - /**+ - * Sets if this mob was spawned by a player or not. + /** + * + Checks to make sure the light is not too bright where the mob is spawning */ - public void setSpawnedByPlayer(boolean spawnedByPlayer) { - this.playerSpawned = spawnedByPlayer; + protected boolean isValidLightLevel() { + return true; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); @@ -170,31 +160,40 @@ public class EntityEndermite extends EntityMob { } - /**+ - * Checks to make sure the light is not too bright where the mob - * is spawning + /** + * + Called to update the entity's position/logic. */ - protected boolean isValidLightLevel() { - return true; + public void onUpdate() { + this.renderYawOffset = this.rotationYaw; + super.onUpdate(); } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - if (super.getCanSpawnHere()) { - EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D); - return entityplayer == null; - } else { - return false; - } + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.silverfish.step", 0.15F, 1.0F); } - /**+ - * Get this Entity's EnumCreatureAttribute + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ - public EnumCreatureAttribute getCreatureAttribute() { - return EnumCreatureAttribute.ARTHROPOD; + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.lifetime = nbttagcompound.getInteger("Lifetime"); + this.playerSpawned = nbttagcompound.getBoolean("PlayerSpawned"); + } + + /** + * + Sets if this mob was spawned by a player or not. + */ + public void setSpawnedByPlayer(boolean spawnedByPlayer) { + this.playerSpawned = spawnedByPlayer; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("Lifetime", this.lifetime); + nbttagcompound.setBoolean("PlayerSpawned", this.playerSpawned); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityGhast.java b/src/game/java/net/minecraft/entity/monster/EntityGhast.java index 82c4c080..a6df9efe 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityGhast.java +++ b/src/game/java/net/minecraft/entity/monster/EntityGhast.java @@ -21,185 +21,30 @@ import net.minecraft.util.Vec3; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityGhast extends EntityFlying implements IMob { - /**+ - * The explosion radius of spawned fireballs. - */ - private int explosionStrength = 1; - - public EntityGhast(World worldIn) { - super(worldIn); - this.setSize(4.0F, 4.0F); - this.isImmuneToFire = true; - this.experienceValue = 5; - this.moveHelper = new EntityGhast.GhastMoveHelper(this); - this.tasks.addTask(5, new EntityGhast.AIRandomFly(this)); - this.tasks.addTask(7, new EntityGhast.AILookAround(this)); - this.tasks.addTask(7, new EntityGhast.AIFireballAttack(this)); - this.targetTasks.addTask(1, new EntityAIFindEntityNearestPlayer(this)); - } - - public boolean isAttacking() { - return this.dataWatcher.getWatchableObjectByte(16) != 0; - } - - public void setAttacking(boolean parFlag) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (parFlag ? 1 : 0))); - } - - public int getFireballStrength() { - return this.explosionStrength; - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - super.onUpdate(); - if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL) { - this.setDead(); - } - - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else if ("fireball".equals(damagesource.getDamageType()) - && damagesource.getEntity() instanceof EntityPlayer) { - super.attackEntityFrom(damagesource, 1000.0F); - ((EntityPlayer) damagesource.getEntity()).triggerAchievement(AchievementList.ghast); - return true; - } else { - return super.attackEntityFrom(damagesource, f); - } - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); - this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(100.0D); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.ghast.moan"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.ghast.scream"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.ghast.death"; - } - - protected Item getDropItem() { - return Items.gunpowder; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - int j = this.rand.nextInt(2) + this.rand.nextInt(1 + i); - - for (int k = 0; k < j; ++k) { - this.dropItem(Items.ghast_tear, 1); - } - - j = this.rand.nextInt(3) + this.rand.nextInt(1 + i); - - for (int l = 0; l < j; ++l) { - this.dropItem(Items.gunpowder, 1); - } - - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 10.0F; - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return this.rand.nextInt(20) == 0 && super.getCanSpawnHere() - && this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL; - } - - /**+ - * Will return how many at most can spawn in a chunk at once. - */ - public int getMaxSpawnedInChunk() { - return 1; - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("ExplosionPower", this.explosionStrength); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("ExplosionPower", 99)) { - this.explosionStrength = nbttagcompound.getInteger("ExplosionPower"); - } - - } - - public float getEyeHeight() { - return 2.6F; - } - static class AIFireballAttack extends EntityAIBase { private EntityGhast parentEntity; public int attackTimer; @@ -208,6 +53,10 @@ public class EntityGhast extends EntityFlying implements IMob { this.parentEntity = parEntityGhast; } + public void resetTask() { + this.parentEntity.setAttacking(false); + } + public boolean shouldExecute() { return this.parentEntity.getAttackTarget() != null; } @@ -216,10 +65,6 @@ public class EntityGhast extends EntityFlying implements IMob { this.attackTimer = 0; } - public void resetTask() { - this.parentEntity.setAttacking(false); - } - public void updateTask() { EntityLivingBase entitylivingbase = this.parentEntity.getAttackTarget(); double d0 = 64.0D; @@ -295,6 +140,10 @@ public class EntityGhast extends EntityFlying implements IMob { this.setMutexBits(1); } + public boolean continueExecuting() { + return false; + } + public boolean shouldExecute() { EntityMoveHelper entitymovehelper = this.parentEntity.getMoveHelper(); if (!entitymovehelper.isUpdating()) { @@ -308,10 +157,6 @@ public class EntityGhast extends EntityFlying implements IMob { } } - public boolean continueExecuting() { - return false; - } - public void startExecuting() { EaglercraftRandom random = this.parentEntity.getRNG(); double d0 = this.parentEntity.posX + (double) ((random.nextFloat() * 2.0F - 1.0F) * 16.0F); @@ -330,6 +175,22 @@ public class EntityGhast extends EntityFlying implements IMob { this.parentEntity = parEntityGhast; } + private boolean isNotColliding(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { + double d0 = (parDouble1 - this.parentEntity.posX) / parDouble4; + double d1 = (parDouble2 - this.parentEntity.posY) / parDouble4; + double d2 = (parDouble3 - this.parentEntity.posZ) / parDouble4; + AxisAlignedBB axisalignedbb = this.parentEntity.getEntityBoundingBox(); + + for (int i = 1; (double) i < parDouble4; ++i) { + axisalignedbb = axisalignedbb.offset(d0, d1, d2); + if (!this.parentEntity.worldObj.getCollidingBoundingBoxes(this.parentEntity, axisalignedbb).isEmpty()) { + return false; + } + } + + return true; + } + public void onUpdateMoveHelper() { if (this.update) { double d0 = this.posX - this.parentEntity.posX; @@ -350,21 +211,161 @@ public class EntityGhast extends EntityFlying implements IMob { } } + } - private boolean isNotColliding(double parDouble1, double parDouble2, double parDouble3, double parDouble4) { - double d0 = (parDouble1 - this.parentEntity.posX) / parDouble4; - double d1 = (parDouble2 - this.parentEntity.posY) / parDouble4; - double d2 = (parDouble3 - this.parentEntity.posZ) / parDouble4; - AxisAlignedBB axisalignedbb = this.parentEntity.getEntityBoundingBox(); + /** + * + The explosion radius of spawned fireballs. + */ + private int explosionStrength = 1; - for (int i = 1; (double) i < parDouble4; ++i) { - axisalignedbb = axisalignedbb.offset(d0, d1, d2); - if (!this.parentEntity.worldObj.getCollidingBoundingBoxes(this.parentEntity, axisalignedbb).isEmpty()) { - return false; - } - } + public EntityGhast(World worldIn) { + super(worldIn); + this.setSize(4.0F, 4.0F); + this.isImmuneToFire = true; + this.experienceValue = 5; + this.moveHelper = new EntityGhast.GhastMoveHelper(this); + this.tasks.addTask(5, new EntityGhast.AIRandomFly(this)); + this.tasks.addTask(7, new EntityGhast.AILookAround(this)); + this.tasks.addTask(7, new EntityGhast.AIFireballAttack(this)); + this.targetTasks.addTask(1, new EntityAIFindEntityNearestPlayer(this)); + } + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); + this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(100.0D); + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else if ("fireball".equals(damagesource.getDamageType()) + && damagesource.getEntity() instanceof EntityPlayer) { + super.attackEntityFrom(damagesource, 1000.0F); + ((EntityPlayer) damagesource.getEntity()).triggerAchievement(AchievementList.ghast); return true; + } else { + return super.attackEntityFrom(damagesource, f); } } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + int j = this.rand.nextInt(2) + this.rand.nextInt(1 + i); + + for (int k = 0; k < j; ++k) { + this.dropItem(Items.ghast_tear, 1); + } + + j = this.rand.nextInt(3) + this.rand.nextInt(1 + i); + + for (int l = 0; l < j; ++l) { + this.dropItem(Items.gunpowder, 1); + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return this.rand.nextInt(20) == 0 && super.getCanSpawnHere() + && this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.ghast.death"; + } + + protected Item getDropItem() { + return Items.gunpowder; + } + + public float getEyeHeight() { + return 2.6F; + } + + public int getFireballStrength() { + return this.explosionStrength; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.ghast.scream"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.ghast.moan"; + } + + /** + * + Will return how many at most can spawn in a chunk at once. + */ + public int getMaxSpawnedInChunk() { + return 1; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 10.0F; + } + + public boolean isAttacking() { + return this.dataWatcher.getWatchableObjectByte(16) != 0; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + super.onUpdate(); + if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL) { + this.setDead(); + } + + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + if (nbttagcompound.hasKey("ExplosionPower", 99)) { + this.explosionStrength = nbttagcompound.getInteger("ExplosionPower"); + } + + } + + public void setAttacking(boolean parFlag) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (parFlag ? 1 : 0))); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("ExplosionPower", this.explosionStrength); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityGiantZombie.java b/src/game/java/net/minecraft/entity/monster/EntityGiantZombie.java index 5c624406..87309586 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityGiantZombie.java +++ b/src/game/java/net/minecraft/entity/monster/EntityGiantZombie.java @@ -4,34 +4,34 @@ import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ -public class EntityGiantZombie extends EntityMob { +public class EntityGiantZombie extends EntityZombie { public EntityGiantZombie(World worldIn) { super(worldIn); - this.setSize(this.width * 6.0F, this.height * 6.0F); - } - public float getEyeHeight() { - return 10.440001F; + this.setSize(this.width * 6.0F, this.height * 6.0F); } protected void applyEntityAttributes() { @@ -44,4 +44,8 @@ public class EntityGiantZombie extends EntityMob { public float getBlockPathWeight(BlockPos blockpos) { return this.worldObj.getLightBrightness(blockpos) - 0.5F; } + + public float getEyeHeight() { + return 10.440001F; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityGolem.java b/src/game/java/net/minecraft/entity/monster/EntityGolem.java index 7a70b93e..84d26f40 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityGolem.java +++ b/src/game/java/net/minecraft/entity/monster/EntityGolem.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityCreature; import net.minecraft.entity.passive.IAnimals; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,43 +32,42 @@ public abstract class EntityGolem extends EntityCreature implements IAnimals { super(worldIn); } + /** + * + Determines if an entity can be despawned, used on idle far away entities + */ + protected boolean canDespawn() { + return false; + } + public void fall(float var1, float var2) { } - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "none"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "none"; - } - - /**+ - * Returns the sound this mob makes on death. + /** + * + Returns the sound this mob makes on death. */ protected String getDeathSound() { return "none"; } - /**+ - * Get number of ticks, at least during which the living entity - * will be silent. + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "none"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "none"; + } + + /** + * + Get number of ticks, at least during which the living entity will be + * silent. */ public int getTalkInterval() { return 120; } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityGuardian.java b/src/game/java/net/minecraft/entity/monster/EntityGuardian.java index 86358298..229101c5 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityGuardian.java +++ b/src/game/java/net/minecraft/entity/monster/EntityGuardian.java @@ -3,6 +3,7 @@ package net.minecraft.entity.monster; import java.util.List; import com.google.common.base.Predicate; + import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; @@ -39,497 +40,30 @@ import net.minecraft.util.WeightedRandomFishable; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityGuardian extends EntityMob { - private float field_175482_b; - private float field_175484_c; - private float field_175483_bk; - private float field_175485_bl; - private float field_175486_bm; - private EntityLivingBase targetedEntity; - private int field_175479_bo; - private boolean field_175480_bp; - private EntityAIWander wander; - - public EntityGuardian(World worldIn) { - super(worldIn); - this.experienceValue = 10; - this.setSize(0.85F, 0.85F); - this.tasks.addTask(4, new EntityGuardian.AIGuardianAttack(this)); - EntityAIMoveTowardsRestriction entityaimovetowardsrestriction; - this.tasks.addTask(5, entityaimovetowardsrestriction = new EntityAIMoveTowardsRestriction(this, 1.0D)); - this.tasks.addTask(7, this.wander = new EntityAIWander(this, 1.0D, 80)); - this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); - this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityGuardian.class, 12.0F, 0.01F)); - this.tasks.addTask(9, new EntityAILookIdle(this)); - this.wander.setMutexBits(3); - entityaimovetowardsrestriction.setMutexBits(3); - this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityLivingBase.class, 10, true, false, - new EntityGuardian.GuardianTargetSelector(this))); - this.moveHelper = new EntityGuardian.GuardianMoveHelper(this); - this.field_175484_c = this.field_175482_b = this.rand.nextFloat(); - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(6.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5D); - this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(16.0D); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(30.0D); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setElder(nbttagcompound.getBoolean("Elder")); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("Elder", this.isElder()); - } - - /**+ - * Returns new PathNavigateGround instance - */ - protected PathNavigate getNewNavigator(World world) { - return new PathNavigateSwimmer(this, world); - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Integer.valueOf(0)); - this.dataWatcher.addObject(17, Integer.valueOf(0)); - } - - /**+ - * Returns true if given flag is set - */ - private boolean isSyncedFlagSet(int flagId) { - return (this.dataWatcher.getWatchableObjectInt(16) & flagId) != 0; - } - - /**+ - * Sets a flag state "on/off" on both sides (client/server) by - * using DataWatcher - */ - private void setSyncedFlag(int flagId, boolean state) { - int i = this.dataWatcher.getWatchableObjectInt(16); - if (state) { - this.dataWatcher.updateObject(16, Integer.valueOf(i | flagId)); - } else { - this.dataWatcher.updateObject(16, Integer.valueOf(i & ~flagId)); - } - - } - - public boolean func_175472_n() { - return this.isSyncedFlagSet(2); - } - - private void func_175476_l(boolean parFlag) { - this.setSyncedFlag(2, parFlag); - } - - public int func_175464_ck() { - return this.isElder() ? 60 : 80; - } - - public boolean isElder() { - return this.isSyncedFlagSet(4); - } - - /**+ - * Sets this Guardian to be an elder or not. - */ - public void setElder(boolean elder) { - this.setSyncedFlag(4, elder); - if (elder) { - this.setSize(1.9975F, 1.9975F); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); - this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(8.0D); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(80.0D); - this.enablePersistence(); - this.wander.setExecutionChance(400); - } - - } - - /**+ - * Sets this Guardian to be an elder or not. - */ - public void setElder() { - this.setElder(true); - this.field_175486_bm = this.field_175485_bl = 1.0F; - } - - private void setTargetedEntity(int entityId) { - this.dataWatcher.updateObject(17, Integer.valueOf(entityId)); - } - - public boolean hasTargetedEntity() { - return this.dataWatcher.getWatchableObjectInt(17) != 0; - } - - public EntityLivingBase getTargetedEntity() { - if (!this.hasTargetedEntity()) { - return null; - } else if (this.worldObj.isRemote) { - if (this.targetedEntity != null) { - return this.targetedEntity; - } else { - Entity entity = this.worldObj.getEntityByID(this.dataWatcher.getWatchableObjectInt(17)); - if (entity instanceof EntityLivingBase) { - this.targetedEntity = (EntityLivingBase) entity; - return this.targetedEntity; - } else { - return null; - } - } - } else { - return this.getAttackTarget(); - } - } - - public void onDataWatcherUpdate(int i) { - super.onDataWatcherUpdate(i); - if (i == 16) { - if (this.isElder() && this.width < 1.0F) { - this.setSize(1.9975F, 1.9975F); - } - } else if (i == 17) { - this.field_175479_bo = 0; - this.targetedEntity = null; - } - - } - - /**+ - * Get number of ticks, at least during which the living entity - * will be silent. - */ - public int getTalkInterval() { - return 160; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return !this.isInWater() ? "mob.guardian.land.idle" - : (this.isElder() ? "mob.guardian.elder.idle" : "mob.guardian.idle"); - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return !this.isInWater() ? "mob.guardian.land.hit" - : (this.isElder() ? "mob.guardian.elder.hit" : "mob.guardian.hit"); - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return !this.isInWater() ? "mob.guardian.land.death" - : (this.isElder() ? "mob.guardian.elder.death" : "mob.guardian.death"); - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - - public float getEyeHeight() { - return this.height * 0.5F; - } - - public float getBlockPathWeight(BlockPos blockpos) { - return this.worldObj.getBlockState(blockpos).getBlock().getMaterial() == Material.water - ? 10.0F + this.worldObj.getLightBrightness(blockpos) - 0.5F - : super.getBlockPathWeight(blockpos); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - if (this.worldObj.isRemote) { - this.field_175484_c = this.field_175482_b; - if (!this.isInWater()) { - this.field_175483_bk = 2.0F; - if (this.motionY > 0.0D && this.field_175480_bp && !this.isSilent()) { - this.worldObj.playSound(this.posX, this.posY, this.posZ, "mob.guardian.flop", 1.0F, 1.0F, false); - } - - this.field_175480_bp = this.motionY < 0.0D - && this.worldObj.isBlockNormalCube((new BlockPos(this)).down(), false); - } else if (this.func_175472_n()) { - if (this.field_175483_bk < 0.5F) { - this.field_175483_bk = 4.0F; - } else { - this.field_175483_bk += (0.5F - this.field_175483_bk) * 0.1F; - } - } else { - this.field_175483_bk += (0.125F - this.field_175483_bk) * 0.2F; - } - - this.field_175482_b += this.field_175483_bk; - this.field_175486_bm = this.field_175485_bl; - if (!this.isInWater()) { - this.field_175485_bl = this.rand.nextFloat(); - } else if (this.func_175472_n()) { - this.field_175485_bl += (0.0F - this.field_175485_bl) * 0.25F; - } else { - this.field_175485_bl += (1.0F - this.field_175485_bl) * 0.06F; - } - - if (this.func_175472_n() && this.isInWater()) { - Vec3 vec3 = this.getLook(0.0F); - - for (int i = 0; i < 2; ++i) { - this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, - this.posX + (this.rand.nextDouble() - 0.5D) * (double) this.width - vec3.xCoord * 1.5D, - this.posY + this.rand.nextDouble() * (double) this.height - vec3.yCoord * 1.5D, - this.posZ + (this.rand.nextDouble() - 0.5D) * (double) this.width - vec3.zCoord * 1.5D, - 0.0D, 0.0D, 0.0D, new int[0]); - } - } - - if (this.hasTargetedEntity()) { - if (this.field_175479_bo < this.func_175464_ck()) { - ++this.field_175479_bo; - } - - EntityLivingBase entitylivingbase = this.getTargetedEntity(); - if (entitylivingbase != null) { - this.getLookHelper().setLookPositionWithEntity(entitylivingbase, 90.0F, 90.0F); - this.getLookHelper().onUpdateLook(); - double d5 = (double) this.func_175477_p(0.0F); - double d0 = entitylivingbase.posX - this.posX; - double d1 = entitylivingbase.posY + (double) (entitylivingbase.height * 0.5F) - - (this.posY + (double) this.getEyeHeight()); - double d2 = entitylivingbase.posZ - this.posZ; - double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); - d0 = d0 / d3; - d1 = d1 / d3; - d2 = d2 / d3; - double d4 = this.rand.nextDouble(); - - while (d4 < d3) { - d4 += 1.8D - d5 + this.rand.nextDouble() * (1.7D - d5); - this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + d0 * d4, - this.posY + d1 * d4 + (double) this.getEyeHeight(), this.posZ + d2 * d4, 0.0D, 0.0D, - 0.0D, new int[0]); - } - } - } - } - - if (this.inWater) { - this.setAir(300); - } else if (this.onGround) { - this.motionY += 0.5D; - this.motionX += (double) ((this.rand.nextFloat() * 2.0F - 1.0F) * 0.4F); - this.motionZ += (double) ((this.rand.nextFloat() * 2.0F - 1.0F) * 0.4F); - this.rotationYaw = this.rand.nextFloat() * 360.0F; - this.onGround = false; - this.isAirBorne = true; - } - - if (this.hasTargetedEntity()) { - this.rotationYaw = this.rotationYawHead; - } - - super.onLivingUpdate(); - } - - public float func_175471_a(float parFloat1) { - return this.field_175484_c + (this.field_175482_b - this.field_175484_c) * parFloat1; - } - - public float func_175469_o(float parFloat1) { - return this.field_175486_bm + (this.field_175485_bl - this.field_175486_bm) * parFloat1; - } - - public float func_175477_p(float parFloat1) { - return ((float) this.field_175479_bo + parFloat1) / (float) this.func_175464_ck(); - } - - protected void updateAITasks() { - super.updateAITasks(); - if (this.isElder()) { - boolean flag = true; - boolean flag1 = true; - boolean flag2 = true; - boolean flag3 = true; - if ((this.ticksExisted + this.getEntityId()) % 1200 == 0) { - Potion potion = Potion.digSlowdown; - - List lst = this.worldObj.getPlayers(EntityPlayerMP.class, - new Predicate() { - public boolean apply(EntityPlayerMP entityplayermp1) { - return EntityGuardian.this.getDistanceSqToEntity(entityplayermp1) < 2500.0D - && entityplayermp1.theItemInWorldManager.survivalOrAdventure(); - } - }); - for (int i = 0, l = lst.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = lst.get(i); - if (!entityplayermp.isPotionActive(potion) - || entityplayermp.getActivePotionEffect(potion).getAmplifier() < 2 - || entityplayermp.getActivePotionEffect(potion).getDuration() < 1200) { - entityplayermp.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(10, 0.0F)); - entityplayermp.addPotionEffect(new PotionEffect(potion.id, 6000, 2)); - } - } - } - - if (!this.hasHome()) { - this.setHomePosAndDistance(new BlockPos(this), 16); - } - } - - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean flag, int i) { - int j = this.rand.nextInt(3) + this.rand.nextInt(i + 1); - if (j > 0) { - this.entityDropItem(new ItemStack(Items.prismarine_shard, j, 0), 1.0F); - } - - if (this.rand.nextInt(3 + i) > 1) { - this.entityDropItem(new ItemStack(Items.fish, 1, ItemFishFood.FishType.COD.getMetadata()), 1.0F); - } else if (this.rand.nextInt(3 + i) > 1) { - this.entityDropItem(new ItemStack(Items.prismarine_crystals, 1, 0), 1.0F); - } - - if (flag && this.isElder()) { - this.entityDropItem(new ItemStack(Blocks.sponge, 1, 1), 1.0F); - } - - } - - /**+ - * Causes this Entity to drop a random item. - */ - protected void addRandomDrop() { - ItemStack itemstack = ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, - EntityFishHook.func_174855_j())).getItemStack(this.rand); - this.entityDropItem(itemstack, 1.0F); - } - - /**+ - * Checks to make sure the light is not too bright where the mob - * is spawning - */ - protected boolean isValidLightLevel() { - return true; - } - - /**+ - * Checks that the entity is not colliding with any blocks / - * liquids - */ - public boolean isNotColliding() { - return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) - && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty(); - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return (this.rand.nextInt(20) == 0 || !this.worldObj.canBlockSeeSky(new BlockPos(this))) - && super.getCanSpawnHere(); - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (!this.func_175472_n() && !damagesource.isMagicDamage() - && damagesource.getSourceOfDamage() instanceof EntityLivingBase) { - EntityLivingBase entitylivingbase = (EntityLivingBase) damagesource.getSourceOfDamage(); - if (!damagesource.isExplosion()) { - entitylivingbase.attackEntityFrom(DamageSource.causeThornsDamage(this), 2.0F); - entitylivingbase.playSound("damage.thorns", 0.5F, 1.0F); - } - } - - this.wander.makeUpdate(); - return super.attackEntityFrom(damagesource, f); - } - - /**+ - * The speed it takes to move the entityliving's rotationPitch - * through the faceEntity method. This is only currently use in - * wolves. - */ - public int getVerticalFaceSpeed() { - return 180; - } - - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward - */ - public void moveEntityWithHeading(float f, float f1) { - if (this.isServerWorld()) { - if (this.isInWater()) { - this.moveFlying(f, f1, 0.1F); - this.moveEntity(this.motionX, this.motionY, this.motionZ); - this.motionX *= 0.8999999761581421D; - this.motionY *= 0.8999999761581421D; - this.motionZ *= 0.8999999761581421D; - if (!this.func_175472_n() && this.getAttackTarget() == null) { - this.motionY -= 0.005D; - } - } else { - super.moveEntityWithHeading(f, f1); - } - } else { - super.moveEntityWithHeading(f, f1); - } - - } - static class AIGuardianAttack extends EntityAIBase { private EntityGuardian theEntity; private int tickCounter; @@ -539,16 +73,22 @@ public class EntityGuardian extends EntityMob { this.setMutexBits(3); } - public boolean shouldExecute() { - EntityLivingBase entitylivingbase = this.theEntity.getAttackTarget(); - return entitylivingbase != null && entitylivingbase.isEntityAlive(); - } - public boolean continueExecuting() { return super.continueExecuting() && (this.theEntity.isElder() || this.theEntity.getDistanceSqToEntity(this.theEntity.getAttackTarget()) > 9.0D); } + public void resetTask() { + this.theEntity.setTargetedEntity(0); + this.theEntity.setAttackTarget((EntityLivingBase) null); + this.theEntity.wander.makeUpdate(); + } + + public boolean shouldExecute() { + EntityLivingBase entitylivingbase = this.theEntity.getAttackTarget(); + return entitylivingbase != null && entitylivingbase.isEntityAlive(); + } + public void startExecuting() { this.tickCounter = -10; this.theEntity.getNavigator().clearPathEntity(); @@ -556,12 +96,6 @@ public class EntityGuardian extends EntityMob { this.theEntity.isAirBorne = true; } - public void resetTask() { - this.theEntity.setTargetedEntity(0); - this.theEntity.setAttackTarget((EntityLivingBase) null); - this.theEntity.wander.makeUpdate(); - } - public void updateTask() { EntityLivingBase entitylivingbase = this.theEntity.getAttackTarget(); this.theEntity.getNavigator().clearPathEntity(); @@ -666,4 +200,470 @@ public class EntityGuardian extends EntityMob { && entitylivingbase.getDistanceSqToEntity(this.parentEntity) > 9.0D; } } + + private float field_175482_b; + private float field_175484_c; + private float field_175483_bk; + private float field_175485_bl; + private float field_175486_bm; + private EntityLivingBase targetedEntity; + + private int field_175479_bo; + + private boolean field_175480_bp; + + private EntityAIWander wander; + + public EntityGuardian(World worldIn) { + super(worldIn); + this.experienceValue = 10; + this.setSize(0.85F, 0.85F); + this.tasks.addTask(4, new EntityGuardian.AIGuardianAttack(this)); + EntityAIMoveTowardsRestriction entityaimovetowardsrestriction; + this.tasks.addTask(5, entityaimovetowardsrestriction = new EntityAIMoveTowardsRestriction(this, 1.0D)); + this.tasks.addTask(7, this.wander = new EntityAIWander(this, 1.0D, 80)); + this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); + this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityGuardian.class, 12.0F, 0.01F)); + this.tasks.addTask(9, new EntityAILookIdle(this)); + this.wander.setMutexBits(3); + entityaimovetowardsrestriction.setMutexBits(3); + this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityLivingBase.class, 10, true, false, + new EntityGuardian.GuardianTargetSelector(this))); + this.moveHelper = new EntityGuardian.GuardianMoveHelper(this); + this.field_175484_c = this.field_175482_b = this.rand.nextFloat(); + } + + /** + * + Causes this Entity to drop a random item. + */ + protected void addRandomDrop() { + ItemStack itemstack = ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, + EntityFishHook.func_174855_j())).getItemStack(this.rand); + this.entityDropItem(itemstack, 1.0F); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(6.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5D); + this.getEntityAttribute(SharedMonsterAttributes.followRange).setBaseValue(16.0D); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(30.0D); + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (!this.func_175472_n() && !damagesource.isMagicDamage() + && damagesource.getSourceOfDamage() instanceof EntityLivingBase) { + EntityLivingBase entitylivingbase = (EntityLivingBase) damagesource.getSourceOfDamage(); + if (!damagesource.isExplosion()) { + entitylivingbase.attackEntityFrom(DamageSource.causeThornsDamage(this), 2.0F); + entitylivingbase.playSound("damage.thorns", 0.5F, 1.0F); + } + } + + this.wander.makeUpdate(); + return super.attackEntityFrom(damagesource, f); + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean flag, int i) { + int j = this.rand.nextInt(3) + this.rand.nextInt(i + 1); + if (j > 0) { + this.entityDropItem(new ItemStack(Items.prismarine_shard, j, 0), 1.0F); + } + + if (this.rand.nextInt(3 + i) > 1) { + this.entityDropItem(new ItemStack(Items.fish, 1, ItemFishFood.FishType.COD.getMetadata()), 1.0F); + } else if (this.rand.nextInt(3 + i) > 1) { + this.entityDropItem(new ItemStack(Items.prismarine_crystals, 1, 0), 1.0F); + } + + if (flag && this.isElder()) { + this.entityDropItem(new ItemStack(Blocks.sponge, 1, 1), 1.0F); + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Integer.valueOf(0)); + this.dataWatcher.addObject(17, Integer.valueOf(0)); + } + + public int func_175464_ck() { + return this.isElder() ? 60 : 80; + } + + public float func_175469_o(float parFloat1) { + return this.field_175486_bm + (this.field_175485_bl - this.field_175486_bm) * parFloat1; + } + + public float func_175471_a(float parFloat1) { + return this.field_175484_c + (this.field_175482_b - this.field_175484_c) * parFloat1; + } + + public boolean func_175472_n() { + return this.isSyncedFlagSet(2); + } + + private void func_175476_l(boolean parFlag) { + this.setSyncedFlag(2, parFlag); + } + + public float func_175477_p(float parFloat1) { + return ((float) this.field_175479_bo + parFloat1) / (float) this.func_175464_ck(); + } + + public float getBlockPathWeight(BlockPos blockpos) { + return this.worldObj.getBlockState(blockpos).getBlock().getMaterial() == Material.water + ? 10.0F + this.worldObj.getLightBrightness(blockpos) - 0.5F + : super.getBlockPathWeight(blockpos); + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return (this.rand.nextInt(20) == 0 || !this.worldObj.canBlockSeeSky(new BlockPos(this))) + && super.getCanSpawnHere(); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return !this.isInWater() ? "mob.guardian.land.death" + : (this.isElder() ? "mob.guardian.elder.death" : "mob.guardian.death"); + } + + public float getEyeHeight() { + return this.height * 0.5F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return !this.isInWater() ? "mob.guardian.land.hit" + : (this.isElder() ? "mob.guardian.elder.hit" : "mob.guardian.hit"); + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return !this.isInWater() ? "mob.guardian.land.idle" + : (this.isElder() ? "mob.guardian.elder.idle" : "mob.guardian.idle"); + } + + /** + * + Returns new PathNavigateGround instance + */ + protected PathNavigate getNewNavigator(World world) { + return new PathNavigateSwimmer(this, world); + } + + /** + * + Get number of ticks, at least during which the living entity will be + * silent. + */ + public int getTalkInterval() { + return 160; + } + + public EntityLivingBase getTargetedEntity() { + if (!this.hasTargetedEntity()) { + return null; + } else if (this.worldObj.isRemote) { + if (this.targetedEntity != null) { + return this.targetedEntity; + } else { + Entity entity = this.worldObj.getEntityByID(this.dataWatcher.getWatchableObjectInt(17)); + if (entity instanceof EntityLivingBase) { + this.targetedEntity = (EntityLivingBase) entity; + return this.targetedEntity; + } else { + return null; + } + } + } else { + return this.getAttackTarget(); + } + } + + /** + * + The speed it takes to move the entityliving's rotationPitch through the + * faceEntity method. This is only currently use in wolves. + */ + public int getVerticalFaceSpeed() { + return 180; + } + + public boolean hasTargetedEntity() { + return this.dataWatcher.getWatchableObjectInt(17) != 0; + } + + public boolean isElder() { + return this.isSyncedFlagSet(4); + } + + /** + * + Checks that the entity is not colliding with any blocks / liquids + */ + public boolean isNotColliding() { + return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) + && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty(); + } + + /** + * + Returns true if given flag is set + */ + private boolean isSyncedFlagSet(int flagId) { + return (this.dataWatcher.getWatchableObjectInt(16) & flagId) != 0; + } + + /** + * + Checks to make sure the light is not too bright where the mob is spawning + */ + protected boolean isValidLightLevel() { + return true; + } + + /** + * + Moves the entity based on the specified heading. Args: strafe, forward + */ + public void moveEntityWithHeading(float f, float f1) { + if (this.isServerWorld()) { + if (this.isInWater()) { + this.moveFlying(f, f1, 0.1F); + this.moveEntity(this.motionX, this.motionY, this.motionZ); + this.motionX *= 0.8999999761581421D; + this.motionY *= 0.8999999761581421D; + this.motionZ *= 0.8999999761581421D; + if (!this.func_175472_n() && this.getAttackTarget() == null) { + this.motionY -= 0.005D; + } + } else { + super.moveEntityWithHeading(f, f1); + } + } else { + super.moveEntityWithHeading(f, f1); + } + + } + + public void onDataWatcherUpdate(int i) { + super.onDataWatcherUpdate(i); + if (i == 16) { + if (this.isElder() && this.width < 1.0F) { + this.setSize(1.9975F, 1.9975F); + } + } else if (i == 17) { + this.field_175479_bo = 0; + this.targetedEntity = null; + } + + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + if (this.worldObj.isRemote) { + this.field_175484_c = this.field_175482_b; + if (!this.isInWater()) { + this.field_175483_bk = 2.0F; + if (this.motionY > 0.0D && this.field_175480_bp && !this.isSilent()) { + this.worldObj.playSound(this.posX, this.posY, this.posZ, "mob.guardian.flop", 1.0F, 1.0F, false); + } + + this.field_175480_bp = this.motionY < 0.0D + && this.worldObj.isBlockNormalCube((new BlockPos(this)).down(), false); + } else if (this.func_175472_n()) { + if (this.field_175483_bk < 0.5F) { + this.field_175483_bk = 4.0F; + } else { + this.field_175483_bk += (0.5F - this.field_175483_bk) * 0.1F; + } + } else { + this.field_175483_bk += (0.125F - this.field_175483_bk) * 0.2F; + } + + this.field_175482_b += this.field_175483_bk; + this.field_175486_bm = this.field_175485_bl; + if (!this.isInWater()) { + this.field_175485_bl = this.rand.nextFloat(); + } else if (this.func_175472_n()) { + this.field_175485_bl += (0.0F - this.field_175485_bl) * 0.25F; + } else { + this.field_175485_bl += (1.0F - this.field_175485_bl) * 0.06F; + } + + if (this.func_175472_n() && this.isInWater()) { + Vec3 vec3 = this.getLook(0.0F); + + for (int i = 0; i < 2; ++i) { + this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, + this.posX + (this.rand.nextDouble() - 0.5D) * (double) this.width - vec3.xCoord * 1.5D, + this.posY + this.rand.nextDouble() * (double) this.height - vec3.yCoord * 1.5D, + this.posZ + (this.rand.nextDouble() - 0.5D) * (double) this.width - vec3.zCoord * 1.5D, + 0.0D, 0.0D, 0.0D, new int[0]); + } + } + + if (this.hasTargetedEntity()) { + if (this.field_175479_bo < this.func_175464_ck()) { + ++this.field_175479_bo; + } + + EntityLivingBase entitylivingbase = this.getTargetedEntity(); + if (entitylivingbase != null) { + this.getLookHelper().setLookPositionWithEntity(entitylivingbase, 90.0F, 90.0F); + this.getLookHelper().onUpdateLook(); + double d5 = (double) this.func_175477_p(0.0F); + double d0 = entitylivingbase.posX - this.posX; + double d1 = entitylivingbase.posY + (double) (entitylivingbase.height * 0.5F) + - (this.posY + (double) this.getEyeHeight()); + double d2 = entitylivingbase.posZ - this.posZ; + double d3 = Math.sqrt(d0 * d0 + d1 * d1 + d2 * d2); + d0 = d0 / d3; + d1 = d1 / d3; + d2 = d2 / d3; + double d4 = this.rand.nextDouble(); + + while (d4 < d3) { + d4 += 1.8D - d5 + this.rand.nextDouble() * (1.7D - d5); + this.worldObj.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX + d0 * d4, + this.posY + d1 * d4 + (double) this.getEyeHeight(), this.posZ + d2 * d4, 0.0D, 0.0D, + 0.0D, new int[0]); + } + } + } + } + + if (this.inWater) { + this.setAir(300); + } else if (this.onGround) { + this.motionY += 0.5D; + this.motionX += (double) ((this.rand.nextFloat() * 2.0F - 1.0F) * 0.4F); + this.motionZ += (double) ((this.rand.nextFloat() * 2.0F - 1.0F) * 0.4F); + this.rotationYaw = this.rand.nextFloat() * 360.0F; + this.onGround = false; + this.isAirBorne = true; + } + + if (this.hasTargetedEntity()) { + this.rotationYaw = this.rotationYawHead; + } + + super.onLivingUpdate(); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setElder(nbttagcompound.getBoolean("Elder")); + } + + /** + * + Sets this Guardian to be an elder or not. + */ + public void setElder() { + this.setElder(true); + this.field_175486_bm = this.field_175485_bl = 1.0F; + } + + /** + * + Sets this Guardian to be an elder or not. + */ + public void setElder(boolean elder) { + this.setSyncedFlag(4, elder); + if (elder) { + this.setSize(1.9975F, 1.9975F); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); + this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(8.0D); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(80.0D); + this.enablePersistence(); + this.wander.setExecutionChance(400); + } + + } + + /** + * + Sets a flag state "on/off" on both sides (client/server) by using + * DataWatcher + */ + private void setSyncedFlag(int flagId, boolean state) { + int i = this.dataWatcher.getWatchableObjectInt(16); + if (state) { + this.dataWatcher.updateObject(16, Integer.valueOf(i | flagId)); + } else { + this.dataWatcher.updateObject(16, Integer.valueOf(i & ~flagId)); + } + + } + + private void setTargetedEntity(int entityId) { + this.dataWatcher.updateObject(17, Integer.valueOf(entityId)); + } + + protected void updateAITasks() { + super.updateAITasks(); + if (this.isElder()) { + boolean flag = true; + boolean flag1 = true; + boolean flag2 = true; + boolean flag3 = true; + if ((this.ticksExisted + this.getEntityId()) % 1200 == 0) { + Potion potion = Potion.digSlowdown; + + List lst = this.worldObj.getPlayers(EntityPlayerMP.class, + new Predicate() { + public boolean apply(EntityPlayerMP entityplayermp1) { + return EntityGuardian.this.getDistanceSqToEntity(entityplayermp1) < 2500.0D + && entityplayermp1.theItemInWorldManager.survivalOrAdventure(); + } + }); + for (int i = 0, l = lst.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = lst.get(i); + if (!entityplayermp.isPotionActive(potion) + || entityplayermp.getActivePotionEffect(potion).getAmplifier() < 2 + || entityplayermp.getActivePotionEffect(potion).getDuration() < 1200) { + entityplayermp.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(10, 0.0F)); + entityplayermp.addPotionEffect(new PotionEffect(potion.id, 6000, 2)); + } + } + } + + if (!this.hasHome()) { + this.setHomePosAndDistance(new BlockPos(this), 16); + } + } + + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("Elder", this.isElder()); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityIronGolem.java b/src/game/java/net/minecraft/entity/monster/EntityIronGolem.java index e3b46c53..74e55cf8 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityIronGolem.java +++ b/src/game/java/net/minecraft/entity/monster/EntityIronGolem.java @@ -1,6 +1,7 @@ package net.minecraft.entity.monster; import com.google.common.base.Predicate; + import net.minecraft.block.Block; import net.minecraft.block.BlockFlower; import net.minecraft.block.material.Material; @@ -34,256 +35,30 @@ import net.minecraft.util.MathHelper; import net.minecraft.village.Village; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityIronGolem extends EntityGolem { - private int homeCheckTimer; - Village villageObj; - private int attackTimer; - private int holdRoseTick; - - public EntityIronGolem(World worldIn) { - super(worldIn); - this.setSize(1.4F, 2.9F); - ((PathNavigateGround) this.getNavigator()).setAvoidsWater(true); - this.tasks.addTask(1, new EntityAIAttackOnCollide(this, 1.0D, true)); - this.tasks.addTask(2, new EntityAIMoveTowardsTarget(this, 0.9D, 32.0F)); - this.tasks.addTask(3, new EntityAIMoveThroughVillage(this, 0.6D, true)); - this.tasks.addTask(4, new EntityAIMoveTowardsRestriction(this, 1.0D)); - this.tasks.addTask(5, new EntityAILookAtVillager(this)); - this.tasks.addTask(6, new EntityAIWander(this, 0.6D)); - this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); - this.tasks.addTask(8, new EntityAILookIdle(this)); - this.targetTasks.addTask(1, new EntityAIDefendVillage(this)); - this.targetTasks.addTask(2, new EntityAIHurtByTarget(this, false, new Class[0])); - this.targetTasks.addTask(3, new EntityIronGolem.AINearestAttackableTargetNonCreeper(this, EntityLiving.class, - 10, false, true, IMob.VISIBLE_MOB_SELECTOR)); - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); - } - - protected void updateAITasks() { - if (--this.homeCheckTimer <= 0) { - this.homeCheckTimer = 70 + this.rand.nextInt(50); - this.villageObj = this.worldObj.getVillageCollection().getNearestVillage(new BlockPos(this), 32); - if (this.villageObj == null) { - this.detachHome(); - } else { - BlockPos blockpos = this.villageObj.getCenter(); - this.setHomePosAndDistance(blockpos, (int) ((float) this.villageObj.getVillageRadius() * 0.6F)); - } - } - - super.updateAITasks(); - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(100.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); - } - - /**+ - * Decrements the entity's air supply when underwater - */ - protected int decreaseAirSupply(int i) { - return i; - } - - protected void collideWithEntity(Entity entity) { - if (entity instanceof IMob && !(entity instanceof EntityCreeper) && this.getRNG().nextInt(20) == 0) { - this.setAttackTarget((EntityLivingBase) entity); - } - - super.collideWithEntity(entity); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - super.onLivingUpdate(); - if (this.attackTimer > 0) { - --this.attackTimer; - } - - if (this.holdRoseTick > 0) { - --this.holdRoseTick; - } - - if (this.motionX * this.motionX + this.motionZ * this.motionZ > 2.500000277905201E-7D - && this.rand.nextInt(5) == 0) { - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); - int k = MathHelper.floor_double(this.posZ); - IBlockState iblockstate = this.worldObj.getBlockState(new BlockPos(i, j, k)); - Block block = iblockstate.getBlock(); - if (block.getMaterial() != Material.air) { - this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, - this.posX + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, - this.getEntityBoundingBox().minY + 0.1D, - this.posZ + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, - 4.0D * ((double) this.rand.nextFloat() - 0.5D), 0.5D, - ((double) this.rand.nextFloat() - 0.5D) * 4.0D, new int[] { Block.getStateId(iblockstate) }); - } - } - - } - - /**+ - * Returns true if this entity can attack entities of the - * specified class. - */ - public boolean canAttackClass(Class oclass) { - return this.isPlayerCreated() && EntityPlayer.class.isAssignableFrom(oclass) ? false - : (oclass == EntityCreeper.class ? false : super.canAttackClass(oclass)); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("PlayerCreated", this.isPlayerCreated()); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setPlayerCreated(nbttagcompound.getBoolean("PlayerCreated")); - } - - public boolean attackEntityAsMob(Entity entity) { - this.attackTimer = 10; - this.worldObj.setEntityState(this, (byte) 4); - boolean flag = entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float) (7 + this.rand.nextInt(15))); - if (flag) { - entity.motionY += 0.4000000059604645D; - this.applyEnchantments(this, entity); - } - - this.playSound("mob.irongolem.throw", 1.0F, 1.0F); - return flag; - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 4) { - this.attackTimer = 10; - this.playSound("mob.irongolem.throw", 1.0F, 1.0F); - } else if (b0 == 11) { - this.holdRoseTick = 400; - } else { - super.handleStatusUpdate(b0); - } - - } - - public Village getVillage() { - return this.villageObj; - } - - public int getAttackTimer() { - return this.attackTimer; - } - - public void setHoldingRose(boolean parFlag) { - this.holdRoseTick = parFlag ? 400 : 0; - this.worldObj.setEntityState(this, (byte) 11); - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.irongolem.hit"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.irongolem.death"; - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.irongolem.walk", 1.0F, 1.0F); - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int var2) { - int i = this.rand.nextInt(3); - - for (int j = 0; j < i; ++j) { - this.dropItemWithOffset(Item.getItemFromBlock(Blocks.red_flower), 1, - (float) BlockFlower.EnumFlowerType.POPPY.getMeta()); - } - - int l = 3 + this.rand.nextInt(3); - - for (int k = 0; k < l; ++k) { - this.dropItem(Items.iron_ingot, 1); - } - - } - - public int getHoldRoseTick() { - return this.holdRoseTick; - } - - public boolean isPlayerCreated() { - return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; - } - - public void setPlayerCreated(boolean parFlag) { - byte b0 = this.dataWatcher.getWatchableObjectByte(16); - if (parFlag) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1))); - } else { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2))); - } - - } - - /**+ - * Called when the mob's health reaches 0. - */ - public void onDeath(DamageSource damagesource) { - if (!this.isPlayerCreated() && this.attackingPlayer != null && this.villageObj != null) { - this.villageObj.setReputationForPlayer(this.attackingPlayer.getName(), -5); - } - - super.onDeath(damagesource); - } - static class AINearestAttackableTargetNonCreeper extends EntityAINearestAttackableTarget { public AINearestAttackableTargetNonCreeper(final EntityCreature creature, Class classTarget, int chance, @@ -322,4 +97,231 @@ public class EntityIronGolem extends EntityGolem { }; } } + + private int homeCheckTimer; + Village villageObj; + private int attackTimer; + + private int holdRoseTick; + + public EntityIronGolem(World worldIn) { + super(worldIn); + this.setSize(1.4F, 2.9F); + ((PathNavigateGround) this.getNavigator()).setAvoidsWater(true); + this.tasks.addTask(1, new EntityAIAttackOnCollide(this, 1.0D, true)); + this.tasks.addTask(2, new EntityAIMoveTowardsTarget(this, 0.9D, 32.0F)); + this.tasks.addTask(3, new EntityAIMoveThroughVillage(this, 0.6D, true)); + this.tasks.addTask(4, new EntityAIMoveTowardsRestriction(this, 1.0D)); + this.tasks.addTask(5, new EntityAILookAtVillager(this)); + this.tasks.addTask(6, new EntityAIWander(this, 0.6D)); + this.tasks.addTask(7, new EntityAIWatchClosest(this, EntityPlayer.class, 6.0F)); + this.tasks.addTask(8, new EntityAILookIdle(this)); + this.targetTasks.addTask(1, new EntityAIDefendVillage(this)); + this.targetTasks.addTask(2, new EntityAIHurtByTarget(this, false, new Class[0])); + this.targetTasks.addTask(3, new EntityIronGolem.AINearestAttackableTargetNonCreeper(this, EntityLiving.class, + 10, false, true, IMob.VISIBLE_MOB_SELECTOR)); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(100.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); + } + + public boolean attackEntityAsMob(Entity entity) { + this.attackTimer = 10; + this.worldObj.setEntityState(this, (byte) 4); + boolean flag = entity.attackEntityFrom(DamageSource.causeMobDamage(this), (float) (7 + this.rand.nextInt(15))); + if (flag) { + entity.motionY += 0.4000000059604645D; + this.applyEnchantments(this, entity); + } + + this.playSound("mob.irongolem.throw", 1.0F, 1.0F); + return flag; + } + + /** + * + Returns true if this entity can attack entities of the specified class. + */ + public boolean canAttackClass(Class oclass) { + return this.isPlayerCreated() && EntityPlayer.class.isAssignableFrom(oclass) ? false + : (oclass == EntityCreeper.class ? false : super.canAttackClass(oclass)); + } + + protected void collideWithEntity(Entity entity) { + if (entity instanceof IMob && !(entity instanceof EntityCreeper) && this.getRNG().nextInt(20) == 0) { + this.setAttackTarget((EntityLivingBase) entity); + } + + super.collideWithEntity(entity); + } + + /** + * + Decrements the entity's air supply when underwater + */ + protected int decreaseAirSupply(int i) { + return i; + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int var2) { + int i = this.rand.nextInt(3); + + for (int j = 0; j < i; ++j) { + this.dropItemWithOffset(Item.getItemFromBlock(Blocks.red_flower), 1, + (float) BlockFlower.EnumFlowerType.POPPY.getMeta()); + } + + int l = 3 + this.rand.nextInt(3); + + for (int k = 0; k < l; ++k) { + this.dropItem(Items.iron_ingot, 1); + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + public int getAttackTimer() { + return this.attackTimer; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.irongolem.death"; + } + + public int getHoldRoseTick() { + return this.holdRoseTick; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.irongolem.hit"; + } + + public Village getVillage() { + return this.villageObj; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 4) { + this.attackTimer = 10; + this.playSound("mob.irongolem.throw", 1.0F, 1.0F); + } else if (b0 == 11) { + this.holdRoseTick = 400; + } else { + super.handleStatusUpdate(b0); + } + + } + + public boolean isPlayerCreated() { + return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + if (!this.isPlayerCreated() && this.attackingPlayer != null && this.villageObj != null) { + this.villageObj.setReputationForPlayer(this.attackingPlayer.getName(), -5); + } + + super.onDeath(damagesource); + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + super.onLivingUpdate(); + if (this.attackTimer > 0) { + --this.attackTimer; + } + + if (this.holdRoseTick > 0) { + --this.holdRoseTick; + } + + if (this.motionX * this.motionX + this.motionZ * this.motionZ > 2.500000277905201E-7D + && this.rand.nextInt(5) == 0) { + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); + int k = MathHelper.floor_double(this.posZ); + IBlockState iblockstate = this.worldObj.getBlockState(new BlockPos(i, j, k)); + Block block = iblockstate.getBlock(); + if (block.getMaterial() != Material.air) { + this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, + this.posX + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, + this.getEntityBoundingBox().minY + 0.1D, + this.posZ + ((double) this.rand.nextFloat() - 0.5D) * (double) this.width, + 4.0D * ((double) this.rand.nextFloat() - 0.5D), 0.5D, + ((double) this.rand.nextFloat() - 0.5D) * 4.0D, new int[] { Block.getStateId(iblockstate) }); + } + } + + } + + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.irongolem.walk", 1.0F, 1.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setPlayerCreated(nbttagcompound.getBoolean("PlayerCreated")); + } + + public void setHoldingRose(boolean parFlag) { + this.holdRoseTick = parFlag ? 400 : 0; + this.worldObj.setEntityState(this, (byte) 11); + } + + public void setPlayerCreated(boolean parFlag) { + byte b0 = this.dataWatcher.getWatchableObjectByte(16); + if (parFlag) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1))); + } else { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2))); + } + + } + + protected void updateAITasks() { + if (--this.homeCheckTimer <= 0) { + this.homeCheckTimer = 70 + this.rand.nextInt(50); + this.villageObj = this.worldObj.getVillageCollection().getNearestVillage(new BlockPos(this), 32); + if (this.villageObj == null) { + this.detachHome(); + } else { + BlockPos blockpos = this.villageObj.getCenter(); + this.setHomePosAndDistance(blockpos, (int) ((float) this.villageObj.getVillageRadius() * 0.6F)); + } + } + + super.updateAITasks(); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("PlayerCreated", this.isPlayerCreated()); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityMagmaCube.java b/src/game/java/net/minecraft/entity/monster/EntityMagmaCube.java index d24c74db..2a577c4e 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityMagmaCube.java +++ b/src/game/java/net/minecraft/entity/monster/EntityMagmaCube.java @@ -7,22 +7,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,66 +36,29 @@ public class EntityMagmaCube extends EntitySlime { this.isImmuneToFire = true; } + protected void alterSquishAmount() { + this.squishAmount *= 0.9F; + } + protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. + /** + * + Indicates weather the slime is able to damage the player (based upon the + * slime's size) */ - public boolean getCanSpawnHere() { - return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL; - } - - /**+ - * Checks that the entity is not colliding with any blocks / - * liquids - */ - public boolean isNotColliding() { - return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) - && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() - && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); - } - - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - return this.getSlimeSize() * 3; - } - - public int getBrightnessForRender(float var1) { - return 15728880; - } - - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float var1) { - return 1.0F; - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 1.0f; - } - - protected EnumParticleTypes getParticleType() { - return EnumParticleTypes.FLAME; + protected boolean canDamagePlayer() { + return true; } protected EntitySlime createInstance() { return new EntityMagmaCube(this.worldObj); } - protected Item getDropItem() { - return Items.magma_cream; - } - - /**+ - * Drop 0-2 items of this living's type + /** + * + Drop 0-2 items of this living's type */ protected void dropFewItems(boolean var1, int i) { Item item = this.getDropItem(); @@ -109,32 +75,67 @@ public class EntityMagmaCube extends EntitySlime { } - /**+ - * Returns true if the entity is on fire. Used by render to add - * the fire effect on rendering. - */ - public boolean isBurning() { - return false; + public void fall(float var1, float var2) { } - /**+ - * Gets the amount of time the slime needs to wait between - * jumps. + /** + * + Gets the amount of damage dealt to the player when "attacked" by the slime. + */ + protected int getAttackStrength() { + return super.getAttackStrength() + 2; + } + + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float var1) { + return 1.0F; + } + + public int getBrightnessForRender(float var1) { + return 15728880; + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL; + } + + protected Item getDropItem() { + return Items.magma_cream; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 1.0f; + } + + /** + * + Gets the amount of time the slime needs to wait between jumps. */ protected int getJumpDelay() { return super.getJumpDelay() * 4; } - protected void alterSquishAmount() { - this.squishAmount *= 0.9F; + /** + * + Returns the name of the sound played when the slime jumps. + */ + protected String getJumpSound() { + return this.getSlimeSize() > 1 ? "mob.magmacube.big" : "mob.magmacube.small"; } - /**+ - * Causes this entity to do an upwards motion (jumping). + protected EnumParticleTypes getParticleType() { + return EnumParticleTypes.FLAME; + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue */ - protected void jump() { - this.motionY = (double) (0.42F + (float) this.getSlimeSize() * 0.1F); - this.isAirBorne = true; + public int getTotalArmorValue() { + return this.getSlimeSize() * 3; } protected void handleJumpLava() { @@ -142,35 +143,34 @@ public class EntityMagmaCube extends EntitySlime { this.isAirBorne = true; } - public void fall(float var1, float var2) { - } - - /**+ - * Indicates weather the slime is able to damage the player - * (based upon the slime's size) + /** + * + Returns true if the entity is on fire. Used by render to add the fire + * effect on rendering. */ - protected boolean canDamagePlayer() { - return true; + public boolean isBurning() { + return false; } - /**+ - * Gets the amount of damage dealt to the player when "attacked" - * by the slime. + /** + * + Checks that the entity is not colliding with any blocks / liquids */ - protected int getAttackStrength() { - return super.getAttackStrength() + 2; + public boolean isNotColliding() { + return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) + && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() + && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); } - /**+ - * Returns the name of the sound played when the slime jumps. + /** + * + Causes this entity to do an upwards motion (jumping). */ - protected String getJumpSound() { - return this.getSlimeSize() > 1 ? "mob.magmacube.big" : "mob.magmacube.small"; + protected void jump() { + this.motionY = (double) (0.42F + (float) this.getSlimeSize() * 0.1F); + this.isAirBorne = true; } - /**+ - * Returns true if the slime makes a sound when it lands after a - * jump (based upon the slime's size) + /** + * + Returns true if the slime makes a sound when it lands after a jump (based + * upon the slime's size) */ protected boolean makesSoundOnLand() { return true; diff --git a/src/game/java/net/minecraft/entity/monster/EntityMob.java b/src/game/java/net/minecraft/entity/monster/EntityMob.java index 264a580d..df724c70 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityMob.java +++ b/src/game/java/net/minecraft/entity/monster/EntityMob.java @@ -12,22 +12,25 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,70 +41,9 @@ public abstract class EntityMob extends EntityCreature implements IMob { this.experienceValue = 5; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - this.updateArmSwingProgress(); - float f = this.getBrightness(1.0F); - if (f > 0.5F) { - this.entityAge += 2; - } - - super.onLivingUpdate(); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - super.onUpdate(); - if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL) { - this.setDead(); - } - - } - - protected String getSwimSound() { - return "game.hostile.swim"; - } - - protected String getSplashSound() { - return "game.hostile.swim.splash"; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else if (super.attackEntityFrom(damagesource, f)) { - Entity entity = damagesource.getEntity(); - return this.riddenByEntity != entity && this.ridingEntity != entity ? true : true; - } else { - return false; - } - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "game.hostile.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "game.hostile.die"; - } - - protected String getFallSoundString(int i) { - return i > 4 ? "game.hostile.hurt.fall.big" : "game.hostile.hurt.fall.small"; + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage); } public boolean attackEntityAsMob(Entity entity) { @@ -134,13 +76,68 @@ public abstract class EntityMob extends EntityCreature implements IMob { return flag; } + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else if (super.attackEntityFrom(damagesource, f)) { + Entity entity = damagesource.getEntity(); + return this.riddenByEntity != entity && this.ridingEntity != entity ? true : true; + } else { + return false; + } + } + + /** + * + Entity won't drop items or experience points if this returns false + */ + protected boolean canDropLoot() { + return true; + } + public float getBlockPathWeight(BlockPos blockpos) { return 0.5F - this.worldObj.getLightBrightness(blockpos); } - /**+ - * Checks to make sure the light is not too bright where the mob - * is spawning + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL && this.isValidLightLevel() + && super.getCanSpawnHere(); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "game.hostile.die"; + } + + protected String getFallSoundString(int i) { + return i > 4 ? "game.hostile.hurt.fall.big" : "game.hostile.hurt.fall.small"; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "game.hostile.hurt"; + } + + protected String getSplashSound() { + return "game.hostile.swim.splash"; + } + + protected String getSwimSound() { + return "game.hostile.swim"; + } + + /** + * + Checks to make sure the light is not too bright where the mob is spawning */ protected boolean isValidLightLevel() { BlockPos blockpos = new BlockPos(this.posX, this.getEntityBoundingBox().minY, this.posZ); @@ -159,25 +156,29 @@ public abstract class EntityMob extends EntityCreature implements IMob { } } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ - public boolean getCanSpawnHere() { - return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL && this.isValidLightLevel() - && super.getCanSpawnHere(); + public void onLivingUpdate() { + this.updateArmSwingProgress(); + float f = this.getBrightness(1.0F); + if (f > 0.5F) { + this.entityAge += 2; + } + + super.onLivingUpdate(); } - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage); - } - - /**+ - * Entity won't drop items or experience points if this returns - * false + /** + * + Called to update the entity's position/logic. */ - protected boolean canDropLoot() { - return true; + public void onUpdate() { + super.onUpdate(); + if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL) { + this.setDead(); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityNetherCreeper.java b/src/game/java/net/minecraft/entity/monster/EntityNetherCreeper.java new file mode 100644 index 00000000..4bdfe90a --- /dev/null +++ b/src/game/java/net/minecraft/entity/monster/EntityNetherCreeper.java @@ -0,0 +1,319 @@ +package net.minecraft.entity.monster; + +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DynamicLightManager; +import net.minecraft.entity.Entity; +import net.minecraft.entity.SharedMonsterAttributes; +import net.minecraft.entity.ai.EntityAIAttackOnCollide; +import net.minecraft.entity.ai.EntityAIAvoidEntity; +import net.minecraft.entity.ai.EntityAIHurtByTarget; +import net.minecraft.entity.ai.EntityAILookIdle; +import net.minecraft.entity.ai.EntityAINearestAttackableTarget; +import net.minecraft.entity.ai.EntityAINetherCreeperSwell; +import net.minecraft.entity.ai.EntityAISwimming; +import net.minecraft.entity.ai.EntityAIWander; +import net.minecraft.entity.ai.EntityAIWatchClosest; +import net.minecraft.entity.effect.EntityLightningBolt; +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.init.Items; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.DamageSource; +import net.minecraft.world.World; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class EntityNetherCreeper extends EntityMob { + private int lastActiveTime; + private int timeSinceIgnited; + private int fuseTime = 25; + /** + * + Explosion radius for this creeper. + */ + private int explosionRadius = 5; + private int field_175494_bm = 0; + + public EntityNetherCreeper(World worldIn) { + super(worldIn); + this.tasks.addTask(1, new EntityAISwimming(this)); + this.tasks.addTask(2, new EntityAINetherCreeperSwell(this)); + this.tasks.addTask(3, new EntityAIAvoidEntity(this, EntityPigZombie.class, 6.0F, 1.0D, 1.2D)); + this.tasks.addTask(4, new EntityAIAttackOnCollide(this, 1.0D, false)); + this.tasks.addTask(5, new EntityAIWander(this, 0.8D)); + this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); + this.tasks.addTask(6, new EntityAILookIdle(this)); + this.tasks.addTask(7, new EntityAIAvoidEntity(this, EntityPigZombie.class, 6.0F, 1.0D, 1.2D)); + + this.targetTasks.addTask(1, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); + this.targetTasks.addTask(2, new EntityAIHurtByTarget(this, false, new Class[0])); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.3D); + } + + public boolean attackEntityAsMob(Entity var1) { + return true; + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) -1)); + this.dataWatcher.addObject(17, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); + } + + /** + * + Creates an explosion as determined by this creeper's power and explosion + * radius. + */ + private void explode() { + if (!this.worldObj.isRemote) { + boolean flag = this.worldObj.getGameRules().getBoolean("mobGriefing"); + float f = this.getPowered() ? 3.0F : 1.0F; + this.worldObj.createExplosion(this, this.posX, this.posY, this.posZ, (float) this.explosionRadius * f, + flag); + this.setDead(); + } + + } + + public void fall(float f, float f1) { + super.fall(f, f1); + this.timeSinceIgnited = (int) ((float) this.timeSinceIgnited + f * 1.5F); + if (this.timeSinceIgnited > this.fuseTime - 5) { + this.timeSinceIgnited = this.fuseTime - 5; + } + + } + + public void func_175493_co() { + ++this.field_175494_bm; + } + + /** + * + Params: (Float)Render tick. Returns the intensity of the creeper's flash + * when it is ignited. + */ + public float getCreeperFlashIntensity(float parFloat1) { + return ((float) this.lastActiveTime + (float) (this.timeSinceIgnited - this.lastActiveTime) * parFloat1) + / (float) (this.fuseTime - 2); + } + + /** + * + Returns the current state of creeper, -1 is idle, 1 is 'in fuse' + */ + public int getCreeperState() { + return this.dataWatcher.getWatchableObjectByte(16); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.creeper.death"; + } + + protected Item getDropItem() { + return Items.blaze_powder; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + float f = super.getEaglerDynamicLightsValueSimple(partialTicks); + float ff = getCreeperFlashIntensity(partialTicks); + if ((int) (ff * 10.0F) % 2 != 0) { + f = Math.min(f + 0.5f, 1.15f); + } + return f; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.creeper.say"; + } + + /** + * + The maximum height from where the entity is alowed to jump (used in + * pathfinder) + */ + public int getMaxFallHeight() { + return this.getAttackTarget() == null ? 3 : 3 + (int) (this.getHealth() - 1.0F); + } + + /** + * + Returns true if the creeper is powered by a lightning bolt. + */ + public boolean getPowered() { + return this.dataWatcher.getWatchableObjectByte(17) == 1; + } + + public boolean hasIgnited() { + return this.dataWatcher.getWatchableObjectByte(18) != 0; + } + + public void ignite() { + this.dataWatcher.updateObject(18, Byte.valueOf((byte) 1)); + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + protected boolean interact(EntityPlayer entityplayer) { + ItemStack itemstack = entityplayer.inventory.getCurrentItem(); + if (itemstack != null && itemstack.getItem() == Items.flint_and_steel) { + this.worldObj.playSoundEffect(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "fire.ignite", 1.0F, + this.rand.nextFloat() * 0.4F + 0.8F); + entityplayer.swingItem(); + if (!this.worldObj.isRemote) { + this.ignite(); + itemstack.damageItem(1, entityplayer); + return true; + } + } + + return super.interact(entityplayer); + } + + /** + * + Returns true if the newer Entity AI code should be run + */ + public boolean isAIEnabled() { + return this.field_175494_bm < 1 && this.worldObj.getGameRules().getBoolean("doMobLoot"); + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + super.onDeath(damagesource); + if (damagesource.getEntity() instanceof EntitySkeleton) { + int i = Item.getIdFromItem(Items.record_13); + int j = Item.getIdFromItem(Items.record_wait); + int k = i + this.rand.nextInt(j - i + 1); + this.dropItem(Item.getItemById(k), 1); + } else if (damagesource.getEntity() instanceof EntityNetherCreeper && damagesource.getEntity() != this + && ((EntityNetherCreeper) damagesource.getEntity()).getPowered() + && ((EntityNetherCreeper) damagesource.getEntity()).isAIEnabled()) { + ((EntityNetherCreeper) damagesource.getEntity()).func_175493_co(); + this.entityDropItem(new ItemStack(Items.skull, 1, 4), 0.0F); + } + + } + + /** + * + Called when a lightning bolt hits the entity. + */ + public void onStruckByLightning(EntityLightningBolt entitylightningbolt) { + super.onStruckByLightning(entitylightningbolt); + this.dataWatcher.updateObject(17, Byte.valueOf((byte) 1)); + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + if (this.isEntityAlive()) { + this.lastActiveTime = this.timeSinceIgnited; + if (this.hasIgnited()) { + this.setCreeperState(1); + } + + int i = this.getCreeperState(); + if (i > 0 && this.timeSinceIgnited == 0) { + this.playSound("creeper.primed", 1.0F, 0.5F); + } + + this.timeSinceIgnited += i; + if (this.timeSinceIgnited < 0) { + this.timeSinceIgnited = 0; + } + + if (this.timeSinceIgnited >= this.fuseTime) { + this.timeSinceIgnited = this.fuseTime; + this.explode(); + } + } + + super.onUpdate(); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.dataWatcher.updateObject(17, Byte.valueOf((byte) (nbttagcompound.getBoolean("powered") ? 1 : 0))); + if (nbttagcompound.hasKey("Fuse", 99)) { + this.fuseTime = nbttagcompound.getShort("Fuse"); + } + + if (nbttagcompound.hasKey("ExplosionRadius", 99)) { + this.explosionRadius = nbttagcompound.getByte("ExplosionRadius"); + } + + if (nbttagcompound.getBoolean("ignited")) { + this.ignite(); + } + + } + + protected void renderDynamicLightsEaglerAt(double entityX, double entityY, double entityZ, double renderX, + double renderY, double renderZ, float partialTicks, boolean isInFrustum) { + super.renderDynamicLightsEaglerAt(entityX, entityY, entityZ, renderX, renderY, renderZ, partialTicks, + isInFrustum); + float ff = getCreeperFlashIntensity(partialTicks); + if ((int) (ff * 10.0F) % 2 != 0) { + float dynamicLightMag = 7.0f; + DynamicLightManager.renderDynamicLight("entity_" + getEntityId() + "_creeper_flash", entityX, entityY + 1.0, + entityZ, dynamicLightMag, dynamicLightMag * 0.7792f, dynamicLightMag * 0.618f, false); + DeferredStateManager.setEmissionConstant(1.0f); + } + } + + /** + * + Sets the state of creeper, -1 to idle and 1 to be 'in fuse' + */ + public void setCreeperState(int state) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) state)); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + if (this.dataWatcher.getWatchableObjectByte(17) == 1) { + nbttagcompound.setBoolean("powered", true); + } + + nbttagcompound.setShort("Fuse", (short) this.fuseTime); + nbttagcompound.setByte("ExplosionRadius", (byte) this.explosionRadius); + nbttagcompound.setBoolean("ignited", this.hasIgnited()); + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityPigZombie.java b/src/game/java/net/minecraft/entity/monster/EntityPigZombie.java index 06c21c99..6ebc3775 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityPigZombie.java +++ b/src/game/java/net/minecraft/entity/monster/EntityPigZombie.java @@ -19,33 +19,62 @@ import net.minecraft.world.DifficultyInstance; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityPigZombie extends EntityZombie { + static class AIHurtByAggressor extends EntityAIHurtByTarget { + public AIHurtByAggressor(EntityPigZombie parEntityPigZombie) { + super(parEntityPigZombie, true, new Class[0]); + } + + protected void setEntityAttackTarget(EntityCreature entitycreature, EntityLivingBase entitylivingbase) { + super.setEntityAttackTarget(entitycreature, entitylivingbase); + if (entitycreature instanceof EntityPigZombie) { + ((EntityPigZombie) entitycreature).becomeAngryAt(entitylivingbase); + } + + } + } + + static class AITargetAggressor extends EntityAINearestAttackableTarget { + public AITargetAggressor(EntityPigZombie parEntityPigZombie) { + super(parEntityPigZombie, EntityPlayer.class, true); + } + + public boolean shouldExecute() { + return ((EntityPigZombie) this.taskOwner).isAngry() && super.shouldExecute(); + } + } + private static final EaglercraftUUID ATTACK_SPEED_BOOST_MODIFIER_UUID = EaglercraftUUID .fromString("49455A49-7EC5-45BA-B886-3B90B23A1718"); private static final AttributeModifier ATTACK_SPEED_BOOST_MODIFIER = (new AttributeModifier( ATTACK_SPEED_BOOST_MODIFIER_UUID, "Attacking speed boost", 0.05D, 0)).setSaved(false); private int angerLevel; + private int randomSoundDelay; + private EaglercraftUUID angerTargetUUID; public EntityPigZombie(World worldIn) { @@ -53,17 +82,18 @@ public class EntityPigZombie extends EntityZombie { this.isImmuneToFire = true; } - public void setRevengeTarget(EntityLivingBase entitylivingbase) { - super.setRevengeTarget(entitylivingbase); - if (entitylivingbase != null) { - this.angerTargetUUID = entitylivingbase.getUniqueID(); - } - + /** + * + Causes this Entity to drop a random item. + */ + protected void addRandomDrop() { + this.dropItem(Items.gold_ingot, 1); } protected void applyEntityAI() { + this.targetTasks.addTask(1, new EntityPigZombie.AIHurtByAggressor(this)); this.targetTasks.addTask(2, new EntityPigZombie.AITargetAggressor(this)); + } protected void applyEntityAttributes() { @@ -73,13 +103,156 @@ public class EntityPigZombie extends EntityZombie { this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(5.0D); } - /**+ - * Called to update the entity's position/logic. + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + Entity entity = damagesource.getEntity(); + if (entity instanceof EntityPlayer) { + this.becomeAngryAt(entity); + } + + return super.attackEntityFrom(damagesource, f); + } + } + + /** + * + Causes this PigZombie to become angry at the supplied Entity (which will be + * a player). + */ + private void becomeAngryAt(Entity parEntity) { + this.angerLevel = 400 + this.rand.nextInt(400); + this.randomSoundDelay = this.rand.nextInt(40); + if (parEntity instanceof EntityLivingBase) { + this.setRevengeTarget((EntityLivingBase) parEntity); + } + + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + int j = this.rand.nextInt(2 + i); + + for (int k = 0; k < j; ++k) { + this.dropItem(Items.rotten_flesh, 1); + } + + j = this.rand.nextInt(2 + i); + + for (int l = 0; l < j; ++l) { + this.dropItem(Items.gold_nugget, 1); + } + + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.zombiepig.zpigdeath"; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.zombiepig.zpighurt"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.zombiepig.zpig"; + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + public boolean interact(EntityPlayer var1) { + return false; + } + + public boolean isAngry() { + return this.angerLevel > 0; + } + + /** + * + Checks that the entity is not colliding with any blocks / liquids + */ + public boolean isNotColliding() { + return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) + && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() + && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + super.onInitialSpawn(difficultyinstance, ientitylivingdata); + this.setVillager(false); + return ientitylivingdata; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); } + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.angerLevel = nbttagcompound.getShort("Anger"); + String s = nbttagcompound.getString("HurtBy"); + if (s.length() > 0) { + this.angerTargetUUID = EaglercraftUUID.fromString(s); + EntityPlayer entityplayer = this.worldObj.getPlayerEntityByUUID(this.angerTargetUUID); + this.setRevengeTarget(entityplayer); + if (entityplayer != null) { + this.attackingPlayer = entityplayer; + this.recentlyHit = this.getRevengeTimer(); + } + } + + } + + /** + * + Gives armor or weapon for entity based on given DifficultyInstance + */ + protected void setEquipmentBasedOnDifficulty(DifficultyInstance var1) { + this.setCurrentItemOrArmor(0, new ItemStack(Items.golden_sword)); + } + + public void setRevengeTarget(EntityLivingBase entitylivingbase) { + super.setRevengeTarget(entitylivingbase); + if (entitylivingbase != null) { + this.angerTargetUUID = entitylivingbase.getUniqueID(); + } + + } + protected void updateAITasks() { IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); if (this.isAngry()) { @@ -107,27 +280,8 @@ public class EntityPigZombie extends EntityZombie { super.updateAITasks(); } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL; - } - - /**+ - * Checks that the entity is not colliding with any blocks / - * liquids - */ - public boolean isNotColliding() { - return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) - && this.worldObj.getCollidingBoundingBoxes(this, this.getEntityBoundingBox()).isEmpty() - && !this.worldObj.isAnyLiquid(this.getEntityBoundingBox()); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); @@ -139,156 +293,4 @@ public class EntityPigZombie extends EntityZombie { } } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.angerLevel = nbttagcompound.getShort("Anger"); - String s = nbttagcompound.getString("HurtBy"); - if (s.length() > 0) { - this.angerTargetUUID = EaglercraftUUID.fromString(s); - EntityPlayer entityplayer = this.worldObj.getPlayerEntityByUUID(this.angerTargetUUID); - this.setRevengeTarget(entityplayer); - if (entityplayer != null) { - this.attackingPlayer = entityplayer; - this.recentlyHit = this.getRevengeTimer(); - } - } - - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - Entity entity = damagesource.getEntity(); - if (entity instanceof EntityPlayer) { - this.becomeAngryAt(entity); - } - - return super.attackEntityFrom(damagesource, f); - } - } - - /**+ - * Causes this PigZombie to become angry at the supplied Entity - * (which will be a player). - */ - private void becomeAngryAt(Entity parEntity) { - this.angerLevel = 400 + this.rand.nextInt(400); - this.randomSoundDelay = this.rand.nextInt(40); - if (parEntity instanceof EntityLivingBase) { - this.setRevengeTarget((EntityLivingBase) parEntity); - } - - } - - public boolean isAngry() { - return this.angerLevel > 0; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.zombiepig.zpig"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.zombiepig.zpighurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.zombiepig.zpigdeath"; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - int j = this.rand.nextInt(2 + i); - - for (int k = 0; k < j; ++k) { - this.dropItem(Items.rotten_flesh, 1); - } - - j = this.rand.nextInt(2 + i); - - for (int l = 0; l < j; ++l) { - this.dropItem(Items.gold_nugget, 1); - } - - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. - */ - public boolean interact(EntityPlayer var1) { - return false; - } - - /**+ - * Causes this Entity to drop a random item. - */ - protected void addRandomDrop() { - this.dropItem(Items.gold_ingot, 1); - } - - /**+ - * Gives armor or weapon for entity based on given - * DifficultyInstance - */ - protected void setEquipmentBasedOnDifficulty(DifficultyInstance var1) { - this.setCurrentItemOrArmor(0, new ItemStack(Items.golden_sword)); - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - super.onInitialSpawn(difficultyinstance, ientitylivingdata); - this.setVillager(false); - return ientitylivingdata; - } - - static class AIHurtByAggressor extends EntityAIHurtByTarget { - public AIHurtByAggressor(EntityPigZombie parEntityPigZombie) { - super(parEntityPigZombie, true, new Class[0]); - } - - protected void setEntityAttackTarget(EntityCreature entitycreature, EntityLivingBase entitylivingbase) { - super.setEntityAttackTarget(entitycreature, entitylivingbase); - if (entitycreature instanceof EntityPigZombie) { - ((EntityPigZombie) entitycreature).becomeAngryAt(entitylivingbase); - } - - } - } - - static class AITargetAggressor extends EntityAINearestAttackableTarget { - public AITargetAggressor(EntityPigZombie parEntityPigZombie) { - super(parEntityPigZombie, EntityPlayer.class, true); - } - - public boolean shouldExecute() { - return ((EntityPigZombie) this.taskOwner).isAngry() && super.shouldExecute(); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntitySilverfish.java b/src/game/java/net/minecraft/entity/monster/EntitySilverfish.java index 4dfd9d97..71271e9c 100644 --- a/src/game/java/net/minecraft/entity/monster/EntitySilverfish.java +++ b/src/game/java/net/minecraft/entity/monster/EntitySilverfish.java @@ -21,152 +21,30 @@ import net.minecraft.util.EntityDamageSource; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySilverfish extends EntityMob { - private EntitySilverfish.AISummonSilverfish summonSilverfish; - - public EntitySilverfish(World worldIn) { - super(worldIn); - this.setSize(0.4F, 0.3F); - this.tasks.addTask(1, new EntityAISwimming(this)); - this.tasks.addTask(3, this.summonSilverfish = new EntitySilverfish.AISummonSilverfish(this)); - this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false)); - this.tasks.addTask(5, new EntitySilverfish.AIHideInStone(this)); - this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true, new Class[0])); - this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); - } - - /**+ - * Returns the Y Offset of this entity. - */ - public double getYOffset() { - return 0.2D; - } - - public float getEyeHeight() { - return 0.1F; - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); - this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(1.0D); - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.silverfish.say"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.silverfish.hit"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.silverfish.kill"; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - if (damagesource instanceof EntityDamageSource || damagesource == DamageSource.magic) { - this.summonSilverfish.func_179462_f(); - } - - return super.attackEntityFrom(damagesource, f); - } - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.silverfish.step", 0.15F, 1.0F); - } - - protected Item getDropItem() { - return null; - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.renderYawOffset = this.rotationYaw; - super.onUpdate(); - } - - public float getBlockPathWeight(BlockPos blockpos) { - return this.worldObj.getBlockState(blockpos.down()).getBlock() == Blocks.stone ? 10.0F - : super.getBlockPathWeight(blockpos); - } - - /**+ - * Checks to make sure the light is not too bright where the mob - * is spawning - */ - protected boolean isValidLightLevel() { - return true; - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - if (super.getCanSpawnHere()) { - EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D); - return entityplayer == null; - } else { - return false; - } - } - - /**+ - * Get this Entity's EnumCreatureAttribute - */ - public EnumCreatureAttribute getCreatureAttribute() { - return EnumCreatureAttribute.ARTHROPOD; - } - static class AIHideInStone extends EntityAIWander { private final EntitySilverfish field_179485_a; private EnumFacing facing; @@ -178,6 +56,10 @@ public class EntitySilverfish extends EntityMob { this.setMutexBits(1); } + public boolean continueExecuting() { + return this.field_179484_c ? false : super.continueExecuting(); + } + public boolean shouldExecute() { if (this.field_179485_a.getAttackTarget() != null) { return false; @@ -201,10 +83,6 @@ public class EntitySilverfish extends EntityMob { } } - public boolean continueExecuting() { - return this.field_179484_c ? false : super.continueExecuting(); - } - public void startExecuting() { if (!this.field_179484_c) { super.startExecuting(); @@ -276,4 +154,127 @@ public class EntitySilverfish extends EntityMob { } } + + private EntitySilverfish.AISummonSilverfish summonSilverfish; + + public EntitySilverfish(World worldIn) { + super(worldIn); + this.setSize(0.4F, 0.3F); + this.tasks.addTask(1, new EntityAISwimming(this)); + this.tasks.addTask(3, this.summonSilverfish = new EntitySilverfish.AISummonSilverfish(this)); + this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityPlayer.class, 1.0D, false)); + this.tasks.addTask(5, new EntitySilverfish.AIHideInStone(this)); + this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, true, new Class[0])); + this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); + this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(1.0D); + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + if (damagesource instanceof EntityDamageSource || damagesource == DamageSource.magic) { + this.summonSilverfish.func_179462_f(); + } + + return super.attackEntityFrom(damagesource, f); + } + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + + public float getBlockPathWeight(BlockPos blockpos) { + return this.worldObj.getBlockState(blockpos.down()).getBlock() == Blocks.stone ? 10.0F + : super.getBlockPathWeight(blockpos); + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + if (super.getCanSpawnHere()) { + EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 5.0D); + return entityplayer == null; + } else { + return false; + } + } + + /** + * + Get this Entity's EnumCreatureAttribute + */ + public EnumCreatureAttribute getCreatureAttribute() { + return EnumCreatureAttribute.ARTHROPOD; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.silverfish.kill"; + } + + protected Item getDropItem() { + return null; + } + + public float getEyeHeight() { + return 0.1F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.silverfish.hit"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.silverfish.say"; + } + + /** + * + Returns the Y Offset of this entity. + */ + public double getYOffset() { + return 0.2D; + } + + /** + * + Checks to make sure the light is not too bright where the mob is spawning + */ + protected boolean isValidLightLevel() { + return true; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.renderYawOffset = this.rotationYaw; + super.onUpdate(); + } + + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.silverfish.step", 0.15F, 1.0F); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntitySkeleton.java b/src/game/java/net/minecraft/entity/monster/EntitySkeleton.java index 4f852926..c27ff7cf 100644 --- a/src/game/java/net/minecraft/entity/monster/EntitySkeleton.java +++ b/src/game/java/net/minecraft/entity/monster/EntitySkeleton.java @@ -1,6 +1,7 @@ package net.minecraft.entity.monster; import java.util.Calendar; + import net.minecraft.block.Block; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; @@ -39,22 +40,25 @@ import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; import net.minecraft.world.WorldProviderHell; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -82,41 +86,21 @@ public class EntitySkeleton extends EntityMob implements IRangedAttackMob { } + /** + * + Causes this Entity to drop a random item. + */ + protected void addRandomDrop() { + if (this.getSkeletonType() == 1) { + this.entityDropItem(new ItemStack(Items.skull, 1, 1), 0.0F); + } + + } + protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(13, Byte.valueOf((byte) 0)); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.skeleton.say"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.skeleton.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.skeleton.death"; - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.skeleton.step", 0.15F, 1.0F); - } - public boolean attackEntityAsMob(Entity entity) { if (super.attackEntityAsMob(entity)) { if (this.getSkeletonType() == 1 && entity instanceof EntityLivingBase) { @@ -129,17 +113,172 @@ public class EntitySkeleton extends EntityMob implements IRangedAttackMob { } } - /**+ - * Get this Entity's EnumCreatureAttribute + /** + * + Attack the specified entity using a ranged attack. + */ + public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float f) { + EntityArrow entityarrow = new EntityArrow(this.worldObj, this, entitylivingbase, 1.6F, + (float) (14 - this.worldObj.getDifficulty().getDifficultyId() * 4)); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem()); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem()); + entityarrow.setDamage((double) (f * 2.0F) + this.rand.nextGaussian() * 0.25D + + (double) ((float) this.worldObj.getDifficulty().getDifficultyId() * 0.11F)); + if (i > 0) { + entityarrow.setDamage(entityarrow.getDamage() + (double) i * 0.5D + 0.5D); + } + + if (j > 0) { + entityarrow.setKnockbackStrength(j); + } + + if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, this.getHeldItem()) > 0 + || this.getSkeletonType() == 1) { + entityarrow.setFire(100); + } + + this.playSound("random.bow", 1.0F, 1.0F / (this.getRNG().nextFloat() * 0.4F + 0.8F)); + this.worldObj.spawnEntityInWorld(entityarrow); + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + if (this.getSkeletonType() == 1) { + int j = this.rand.nextInt(3 + i) - 1; + + for (int k = 0; k < j; ++k) { + this.dropItem(Items.coal, 1); + } + } else { + int l = this.rand.nextInt(3 + i); + + for (int j1 = 0; j1 < l; ++j1) { + this.dropItem(Items.arrow, 1); + } + } + + int i1 = this.rand.nextInt(3 + i); + + for (int k1 = 0; k1 < i1; ++k1) { + this.dropItem(Items.bone, 1); + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(13, Byte.valueOf((byte) 0)); + } + + /** + * + Get this Entity's EnumCreatureAttribute */ public EnumCreatureAttribute getCreatureAttribute() { return EnumCreatureAttribute.UNDEAD; } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.skeleton.death"; + } + + protected Item getDropItem() { + return Items.arrow; + } + + public float getEyeHeight() { + return this.getSkeletonType() == 1 ? super.getEyeHeight() : 1.74F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.skeleton.hurt"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.skeleton.say"; + } + + /** + * + Return this skeleton's type. + */ + public int getSkeletonType() { + return this.dataWatcher.getWatchableObjectByte(13); + } + + /** + * + Returns the Y Offset of this entity. + */ + public double getYOffset() { + return this.isChild() ? 0.0D : -0.35D; + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + super.onDeath(damagesource); + if (damagesource.getSourceOfDamage() instanceof EntityArrow + && damagesource.getEntity() instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) damagesource.getEntity(); + double d0 = entityplayer.posX - this.posX; + double d1 = entityplayer.posZ - this.posZ; + if (d0 * d0 + d1 * d1 >= 2500.0D) { + entityplayer.triggerAchievement(AchievementList.snipeSkeleton); + } + } else if (damagesource.getEntity() instanceof EntityCreeper + && ((EntityCreeper) damagesource.getEntity()).getPowered() + && ((EntityCreeper) damagesource.getEntity()).isAIEnabled()) { + ((EntityCreeper) damagesource.getEntity()).func_175493_co(); + this.entityDropItem(new ItemStack(Items.skull, 1, this.getSkeletonType() == 1 ? 1 : 0), 0.0F); + } + + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); + if (this.worldObj.provider instanceof WorldProviderHell && this.getRNG().nextInt(5) > 0) { + this.tasks.addTask(4, this.aiAttackOnCollide); + this.setSkeletonType(1); + this.setCurrentItemOrArmor(0, new ItemStack(Items.stone_sword)); + this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(4.0D); + } else { + this.tasks.addTask(4, this.aiArrowAttack); + this.setEquipmentBasedOnDifficulty(difficultyinstance); + this.setEnchantmentBasedOnDifficulty(difficultyinstance); + } + + this.setCanPickUpLoot(this.rand.nextFloat() < 0.55F * difficultyinstance.getClampedAdditionalDifficulty()); + if (this.getEquipmentInSlot(4) == null) { + Calendar calendar = this.worldObj.getCurrentDate(); + if (calendar.get(2) + 1 == 10 && calendar.get(5) == 31 && this.rand.nextFloat() < 0.25F) { + this.setCurrentItemOrArmor(4, + new ItemStack(this.rand.nextFloat() < 0.1F ? Blocks.lit_pumpkin : Blocks.pumpkin)); + this.equipmentDropChances[4] = 0.0F; + } + } + + return ientitylivingdata; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (this.worldObj.isDaytime() && !this.worldObj.isRemote) { @@ -173,124 +312,25 @@ public class EntitySkeleton extends EntityMob implements IRangedAttackMob { super.onLivingUpdate(); } - /**+ - * Handles updating while being ridden by an entity + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.skeleton.step", 0.15F, 1.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ - public void updateRidden() { - super.updateRidden(); - if (this.ridingEntity instanceof EntityCreature) { - EntityCreature entitycreature = (EntityCreature) this.ridingEntity; - this.renderYawOffset = entitycreature.renderYawOffset; + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + if (nbttagcompound.hasKey("SkeletonType", 99)) { + byte b0 = nbttagcompound.getByte("SkeletonType"); + this.setSkeletonType(b0); } + this.setCombatTask(); } - /**+ - * Called when the mob's health reaches 0. - */ - public void onDeath(DamageSource damagesource) { - super.onDeath(damagesource); - if (damagesource.getSourceOfDamage() instanceof EntityArrow - && damagesource.getEntity() instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) damagesource.getEntity(); - double d0 = entityplayer.posX - this.posX; - double d1 = entityplayer.posZ - this.posZ; - if (d0 * d0 + d1 * d1 >= 2500.0D) { - entityplayer.triggerAchievement(AchievementList.snipeSkeleton); - } - } else if (damagesource.getEntity() instanceof EntityCreeper - && ((EntityCreeper) damagesource.getEntity()).getPowered() - && ((EntityCreeper) damagesource.getEntity()).isAIEnabled()) { - ((EntityCreeper) damagesource.getEntity()).func_175493_co(); - this.entityDropItem(new ItemStack(Items.skull, 1, this.getSkeletonType() == 1 ? 1 : 0), 0.0F); - } - - } - - protected Item getDropItem() { - return Items.arrow; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - if (this.getSkeletonType() == 1) { - int j = this.rand.nextInt(3 + i) - 1; - - for (int k = 0; k < j; ++k) { - this.dropItem(Items.coal, 1); - } - } else { - int l = this.rand.nextInt(3 + i); - - for (int j1 = 0; j1 < l; ++j1) { - this.dropItem(Items.arrow, 1); - } - } - - int i1 = this.rand.nextInt(3 + i); - - for (int k1 = 0; k1 < i1; ++k1) { - this.dropItem(Items.bone, 1); - } - - } - - /**+ - * Causes this Entity to drop a random item. - */ - protected void addRandomDrop() { - if (this.getSkeletonType() == 1) { - this.entityDropItem(new ItemStack(Items.skull, 1, 1), 0.0F); - } - - } - - /**+ - * Gives armor or weapon for entity based on given - * DifficultyInstance - */ - protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficultyinstance) { - super.setEquipmentBasedOnDifficulty(difficultyinstance); - this.setCurrentItemOrArmor(0, new ItemStack(Items.bow)); - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); - if (this.worldObj.provider instanceof WorldProviderHell && this.getRNG().nextInt(5) > 0) { - this.tasks.addTask(4, this.aiAttackOnCollide); - this.setSkeletonType(1); - this.setCurrentItemOrArmor(0, new ItemStack(Items.stone_sword)); - this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(4.0D); - } else { - this.tasks.addTask(4, this.aiArrowAttack); - this.setEquipmentBasedOnDifficulty(difficultyinstance); - this.setEnchantmentBasedOnDifficulty(difficultyinstance); - } - - this.setCanPickUpLoot(this.rand.nextFloat() < 0.55F * difficultyinstance.getClampedAdditionalDifficulty()); - if (this.getEquipmentInSlot(4) == null) { - Calendar calendar = this.worldObj.getCurrentDate(); - if (calendar.get(2) + 1 == 10 && calendar.get(5) == 31 && this.rand.nextFloat() < 0.25F) { - this.setCurrentItemOrArmor(4, - new ItemStack(this.rand.nextFloat() < 0.1F ? Blocks.lit_pumpkin : Blocks.pumpkin)); - this.equipmentDropChances[4] = 0.0F; - } - } - - return ientitylivingdata; - } - - /**+ - * sets this entity's combat AI. + /** + * + sets this entity's combat AI. */ public void setCombatTask() { this.tasks.removeTask(this.aiAttackOnCollide); @@ -304,42 +344,28 @@ public class EntitySkeleton extends EntityMob implements IRangedAttackMob { } - /**+ - * Attack the specified entity using a ranged attack. + /** + * + Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is + * armor. Params: Item, slot */ - public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float f) { - EntityArrow entityarrow = new EntityArrow(this.worldObj, this, entitylivingbase, 1.6F, - (float) (14 - this.worldObj.getDifficulty().getDifficultyId() * 4)); - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem()); - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem()); - entityarrow.setDamage((double) (f * 2.0F) + this.rand.nextGaussian() * 0.25D - + (double) ((float) this.worldObj.getDifficulty().getDifficultyId() * 0.11F)); - if (i > 0) { - entityarrow.setDamage(entityarrow.getDamage() + (double) i * 0.5D + 0.5D); + public void setCurrentItemOrArmor(int i, ItemStack itemstack) { + super.setCurrentItemOrArmor(i, itemstack); + if (!this.worldObj.isRemote && i == 0) { + this.setCombatTask(); } - if (j > 0) { - entityarrow.setKnockbackStrength(j); - } - - if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, this.getHeldItem()) > 0 - || this.getSkeletonType() == 1) { - entityarrow.setFire(100); - } - - this.playSound("random.bow", 1.0F, 1.0F / (this.getRNG().nextFloat() * 0.4F + 0.8F)); - this.worldObj.spawnEntityInWorld(entityarrow); } - /**+ - * Return this skeleton's type. + /** + * + Gives armor or weapon for entity based on given DifficultyInstance */ - public int getSkeletonType() { - return this.dataWatcher.getWatchableObjectByte(13); + protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficultyinstance) { + super.setEquipmentBasedOnDifficulty(difficultyinstance); + this.setCurrentItemOrArmor(0, new ItemStack(Items.bow)); } - /**+ - * Set this skeleton's type. + /** + * + Set this skeleton's type. */ public void setSkeletonType(int parInt1) { this.dataWatcher.updateObject(13, Byte.valueOf((byte) parInt1)); @@ -352,49 +378,23 @@ public class EntitySkeleton extends EntityMob implements IRangedAttackMob { } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + Handles updating while being ridden by an entity */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("SkeletonType", 99)) { - byte b0 = nbttagcompound.getByte("SkeletonType"); - this.setSkeletonType(b0); + public void updateRidden() { + super.updateRidden(); + if (this.ridingEntity instanceof EntityCreature) { + EntityCreature entitycreature = (EntityCreature) this.ridingEntity; + this.renderYawOffset = entitycreature.renderYawOffset; } - this.setCombatTask(); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); nbttagcompound.setByte("SkeletonType", (byte) this.getSkeletonType()); } - - /**+ - * Sets the held item, or an armor slot. Slot 0 is held item. - * Slot 1-4 is armor. Params: Item, slot - */ - public void setCurrentItemOrArmor(int i, ItemStack itemstack) { - super.setCurrentItemOrArmor(i, itemstack); - if (!this.worldObj.isRemote && i == 0) { - this.setCombatTask(); - } - - } - - public float getEyeHeight() { - return this.getSkeletonType() == 1 ? super.getEyeHeight() : 1.74F; - } - - /**+ - * Returns the Y Offset of this entity. - */ - public double getYOffset() { - return this.isChild() ? 0.0D : -0.35D; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntitySlime.java b/src/game/java/net/minecraft/entity/monster/EntitySlime.java index 757dfcd7..45574867 100644 --- a/src/game/java/net/minecraft/entity/monster/EntitySlime.java +++ b/src/game/java/net/minecraft/entity/monster/EntitySlime.java @@ -25,363 +25,30 @@ import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySlime extends EntityLiving implements IMob { - public float squishAmount; - public float squishFactor; - public float prevSquishFactor; - private boolean wasOnGround; - - public EntitySlime(World worldIn) { - super(worldIn); - this.moveHelper = new EntitySlime.SlimeMoveHelper(this); - this.tasks.addTask(1, new EntitySlime.AISlimeFloat(this)); - this.tasks.addTask(2, new EntitySlime.AISlimeAttack(this)); - this.tasks.addTask(3, new EntitySlime.AISlimeFaceRandom(this)); - this.tasks.addTask(5, new EntitySlime.AISlimeHop(this)); - this.targetTasks.addTask(1, new EntityAIFindEntityNearestPlayer(this)); - this.targetTasks.addTask(3, new EntityAIFindEntityNearest(this, EntityIronGolem.class)); - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 1)); - } - - protected void setSlimeSize(int size) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) size)); - this.setSize(0.51000005F * (float) size, 0.51000005F * (float) size); - this.setPosition(this.posX, this.posY, this.posZ); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue((double) (size * size)); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed) - .setBaseValue((double) (0.2F + 0.1F * (float) size)); - this.setHealth(this.getMaxHealth()); - this.experienceValue = size; - } - - /**+ - * Returns the size of the slime. - */ - public int getSlimeSize() { - return this.dataWatcher.getWatchableObjectByte(16); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("Size", this.getSlimeSize() - 1); - nbttagcompound.setBoolean("wasOnGround", this.wasOnGround); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - int i = nbttagcompound.getInteger("Size"); - if (i < 0) { - i = 0; - } - - this.setSlimeSize(i + 1); - this.wasOnGround = nbttagcompound.getBoolean("wasOnGround"); - } - - protected EnumParticleTypes getParticleType() { - return EnumParticleTypes.SLIME; - } - - /**+ - * Returns the name of the sound played when the slime jumps. - */ - protected String getJumpSound() { - return "mob.slime." + (this.getSlimeSize() > 1 ? "big" : "small"); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL - && this.getSlimeSize() > 0) { - this.isDead = true; - } - - this.squishFactor += (this.squishAmount - this.squishFactor) * 0.5F; - this.prevSquishFactor = this.squishFactor; - super.onUpdate(); - if (this.onGround && !this.wasOnGround) { - int i = this.getSlimeSize(); - - for (int j = 0; j < i * 8; ++j) { - float f = this.rand.nextFloat() * 3.1415927F * 2.0F; - float f1 = this.rand.nextFloat() * 0.5F + 0.5F; - float f2 = MathHelper.sin(f) * (float) i * 0.5F * f1; - float f3 = MathHelper.cos(f) * (float) i * 0.5F * f1; - World world = this.worldObj; - EnumParticleTypes enumparticletypes = this.getParticleType(); - double d0 = this.posX + (double) f2; - double d1 = this.posZ + (double) f3; - world.spawnParticle(enumparticletypes, d0, this.getEntityBoundingBox().minY, d1, 0.0D, 0.0D, 0.0D, - new int[0]); - } - - if (this.makesSoundOnLand()) { - this.playSound(this.getJumpSound(), this.getSoundVolume(), - ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F) / 0.8F); - } - - this.squishAmount = -0.5F; - } else if (!this.onGround && this.wasOnGround) { - this.squishAmount = 1.0F; - } - - this.wasOnGround = this.onGround; - this.alterSquishAmount(); - } - - protected void alterSquishAmount() { - this.squishAmount *= 0.6F; - } - - /**+ - * Gets the amount of time the slime needs to wait between - * jumps. - */ - protected int getJumpDelay() { - return this.rand.nextInt(20) + 10; - } - - protected EntitySlime createInstance() { - return new EntitySlime(this.worldObj); - } - - public void onDataWatcherUpdate(int i) { - if (i == 16) { - int j = this.getSlimeSize(); - this.setSize(0.51000005F * (float) j, 0.51000005F * (float) j); - this.rotationYaw = this.rotationYawHead; - this.renderYawOffset = this.rotationYawHead; - if (this.isInWater() && this.rand.nextInt(20) == 0) { - this.resetHeight(); - } - } - - super.onDataWatcherUpdate(i); - } - - /**+ - * Will get destroyed next tick. - */ - public void setDead() { - int i = this.getSlimeSize(); - if (!this.worldObj.isRemote && i > 1 && this.getHealth() <= 0.0F) { - int j = 2 + this.rand.nextInt(3); - - for (int k = 0; k < j; ++k) { - float f = ((float) (k % 2) - 0.5F) * (float) i / 4.0F; - float f1 = ((float) (k / 2) - 0.5F) * (float) i / 4.0F; - EntitySlime entityslime = this.createInstance(); - if (this.hasCustomName()) { - entityslime.setCustomNameTag(this.getCustomNameTag()); - } - - if (this.isNoDespawnRequired()) { - entityslime.enablePersistence(); - } - - entityslime.setSlimeSize(i / 2); - entityslime.setLocationAndAngles(this.posX + (double) f, this.posY + 0.5D, this.posZ + (double) f1, - this.rand.nextFloat() * 360.0F, 0.0F); - this.worldObj.spawnEntityInWorld(entityslime); - } - } - - super.setDead(); - } - - /**+ - * Applies a velocity to each of the entities pushing them away - * from each other. Args: entity - */ - public void applyEntityCollision(Entity entity) { - super.applyEntityCollision(entity); - if (entity instanceof EntityIronGolem && this.canDamagePlayer()) { - this.func_175451_e((EntityLivingBase) entity); - } - - } - - /**+ - * Called by a player entity when they collide with an entity - */ - public void onCollideWithPlayer(EntityPlayer entityplayer) { - if (this.canDamagePlayer()) { - this.func_175451_e(entityplayer); - } - - } - - protected void func_175451_e(EntityLivingBase parEntityLivingBase) { - int i = this.getSlimeSize(); - if (this.canEntityBeSeen(parEntityLivingBase) - && this.getDistanceSqToEntity(parEntityLivingBase) < 0.6D * (double) i * 0.6D * (double) i - && parEntityLivingBase.attackEntityFrom(DamageSource.causeMobDamage(this), - (float) this.getAttackStrength())) { - this.playSound("mob.attack", 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); - this.applyEnchantments(this, parEntityLivingBase); - } - - } - - public float getEyeHeight() { - return 0.625F * this.height; - } - - /**+ - * Indicates weather the slime is able to damage the player - * (based upon the slime's size) - */ - protected boolean canDamagePlayer() { - return this.getSlimeSize() > 1; - } - - /**+ - * Gets the amount of damage dealt to the player when "attacked" - * by the slime. - */ - protected int getAttackStrength() { - return this.getSlimeSize(); - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.slime." + (this.getSlimeSize() > 1 ? "big" : "small"); - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.slime." + (this.getSlimeSize() > 1 ? "big" : "small"); - } - - protected Item getDropItem() { - return this.getSlimeSize() == 1 ? Items.slime_ball : null; - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - BlockPos blockpos = new BlockPos(MathHelper.floor_double(this.posX), 0, MathHelper.floor_double(this.posZ)); - Chunk chunk = this.worldObj.getChunkFromBlockCoords(blockpos); - if (this.worldObj.getWorldInfo().getTerrainType() == WorldType.FLAT && this.rand.nextInt(4) != 1) { - return false; - } else { - if (this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL) { - BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); - if (biomegenbase == BiomeGenBase.swampland && this.posY > 50.0D && this.posY < 70.0D - && this.rand.nextFloat() < 0.5F - && this.rand.nextFloat() < this.worldObj.getCurrentMoonPhaseFactor() - && this.worldObj.getLightFromNeighbors(new BlockPos(this)) <= this.rand.nextInt(8)) { - return super.getCanSpawnHere(); - } - - if (this.rand.nextInt(10) == 0 && chunk.getRandomWithSeed(987234911L).nextInt(10) == 0 - && this.posY < 40.0D) { - return super.getCanSpawnHere(); - } - } - - return false; - } - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 0.4F * (float) this.getSlimeSize(); - } - - /**+ - * The speed it takes to move the entityliving's rotationPitch - * through the faceEntity method. This is only currently use in - * wolves. - */ - public int getVerticalFaceSpeed() { - return 0; - } - - /**+ - * Returns true if the slime makes a sound when it jumps (based - * upon the slime's size) - */ - protected boolean makesSoundOnJump() { - return this.getSlimeSize() > 0; - } - - /**+ - * Returns true if the slime makes a sound when it lands after a - * jump (based upon the slime's size) - */ - protected boolean makesSoundOnLand() { - return this.getSlimeSize() > 2; - } - - /**+ - * Causes this entity to do an upwards motion (jumping). - */ - protected void jump() { - this.motionY = 0.41999998688697815D; - this.isAirBorne = true; - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - int i = this.rand.nextInt(3); - if (i < 2 && this.rand.nextFloat() < 0.5F * difficultyinstance.getClampedAdditionalDifficulty()) { - ++i; - } - - int j = 1 << i; - this.setSlimeSize(j); - return super.onInitialSpawn(difficultyinstance, ientitylivingdata); - } - static class AISlimeAttack extends EntityAIBase { private EntitySlime slime; private int field_179465_b; @@ -391,6 +58,15 @@ public class EntitySlime extends EntityLiving implements IMob { this.setMutexBits(2); } + public boolean continueExecuting() { + EntityLivingBase entitylivingbase = this.slime.getAttackTarget(); + return entitylivingbase == null ? false + : (!entitylivingbase.isEntityAlive() ? false + : (entitylivingbase instanceof EntityPlayer + && ((EntityPlayer) entitylivingbase).capabilities.disableDamage ? false + : --this.field_179465_b > 0)); + } + public boolean shouldExecute() { EntityLivingBase entitylivingbase = this.slime.getAttackTarget(); return entitylivingbase == null ? false @@ -404,15 +80,6 @@ public class EntitySlime extends EntityLiving implements IMob { super.startExecuting(); } - public boolean continueExecuting() { - EntityLivingBase entitylivingbase = this.slime.getAttackTarget(); - return entitylivingbase == null ? false - : (!entitylivingbase.isEntityAlive() ? false - : (entitylivingbase instanceof EntityPlayer - && ((EntityPlayer) entitylivingbase).capabilities.disableDamage ? false - : --this.field_179465_b > 0)); - } - public void updateTask() { this.slime.faceEntity(this.slime.getAttackTarget(), 10.0F, 10.0F); ((EntitySlime.SlimeMoveHelper) this.slime.getMoveHelper()).func_179920_a(this.slime.rotationYaw, @@ -500,11 +167,6 @@ public class EntitySlime extends EntityLiving implements IMob { this.field_179923_j = parFlag; } - public void setSpeed(double speedIn) { - this.speed = speedIn; - this.update = true; - } - public void onUpdateMoveHelper() { this.entity.rotationYaw = this.limitAngle(this.entity.rotationYaw, this.field_179922_g, 30.0F); this.entity.rotationYawHead = this.entity.rotationYaw; @@ -539,5 +201,343 @@ public class EntitySlime extends EntityLiving implements IMob { } } + + public void setSpeed(double speedIn) { + this.speed = speedIn; + this.update = true; + } + } + + public float squishAmount; + + public float squishFactor; + + public float prevSquishFactor; + + private boolean wasOnGround; + + public EntitySlime(World worldIn) { + super(worldIn); + this.moveHelper = new EntitySlime.SlimeMoveHelper(this); + this.tasks.addTask(1, new EntitySlime.AISlimeFloat(this)); + this.tasks.addTask(2, new EntitySlime.AISlimeAttack(this)); + this.tasks.addTask(3, new EntitySlime.AISlimeFaceRandom(this)); + this.tasks.addTask(5, new EntitySlime.AISlimeHop(this)); + this.targetTasks.addTask(1, new EntityAIFindEntityNearestPlayer(this)); + this.targetTasks.addTask(3, new EntityAIFindEntityNearest(this, EntityIronGolem.class)); + } + + protected void alterSquishAmount() { + this.squishAmount *= 0.6F; + } + + /** + * + Applies a velocity to each of the entities pushing them away from each + * other. Args: entity + */ + public void applyEntityCollision(Entity entity) { + super.applyEntityCollision(entity); + if (entity instanceof EntityIronGolem && this.canDamagePlayer()) { + this.func_175451_e((EntityLivingBase) entity); + } + + } + + /** + * + Indicates weather the slime is able to damage the player (based upon the + * slime's size) + */ + protected boolean canDamagePlayer() { + return this.getSlimeSize() > 1; + } + + protected EntitySlime createInstance() { + return new EntitySlime(this.worldObj); + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 1)); + } + + protected void func_175451_e(EntityLivingBase parEntityLivingBase) { + int i = this.getSlimeSize(); + if (this.canEntityBeSeen(parEntityLivingBase) + && this.getDistanceSqToEntity(parEntityLivingBase) < 0.6D * (double) i * 0.6D * (double) i + && parEntityLivingBase.attackEntityFrom(DamageSource.causeMobDamage(this), + (float) this.getAttackStrength())) { + this.playSound("mob.attack", 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); + this.applyEnchantments(this, parEntityLivingBase); + } + + } + + /** + * + Gets the amount of damage dealt to the player when "attacked" by the slime. + */ + protected int getAttackStrength() { + return this.getSlimeSize(); + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + BlockPos blockpos = new BlockPos(MathHelper.floor_double(this.posX), 0, MathHelper.floor_double(this.posZ)); + Chunk chunk = this.worldObj.getChunkFromBlockCoords(blockpos); + if (this.worldObj.getWorldInfo().getTerrainType() == WorldType.FLAT && this.rand.nextInt(4) != 1) { + return false; + } else { + if (this.worldObj.getDifficulty() != EnumDifficulty.PEACEFUL) { + BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); + if (biomegenbase == BiomeGenBase.swampland && this.posY > 50.0D && this.posY < 70.0D + && this.rand.nextFloat() < 0.5F + && this.rand.nextFloat() < this.worldObj.getCurrentMoonPhaseFactor() + && this.worldObj.getLightFromNeighbors(new BlockPos(this)) <= this.rand.nextInt(8)) { + return super.getCanSpawnHere(); + } + + if (this.rand.nextInt(10) == 0 && chunk.getRandomWithSeed(987234911L).nextInt(10) == 0 + && this.posY < 40.0D) { + return super.getCanSpawnHere(); + } + } + + return false; + } + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.slime." + (this.getSlimeSize() > 1 ? "big" : "small"); + } + + protected Item getDropItem() { + return this.getSlimeSize() == 1 ? Items.slime_ball : null; + } + + public float getEyeHeight() { + return 0.625F * this.height; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.slime." + (this.getSlimeSize() > 1 ? "big" : "small"); + } + + /** + * + Gets the amount of time the slime needs to wait between jumps. + */ + protected int getJumpDelay() { + return this.rand.nextInt(20) + 10; + } + + /** + * + Returns the name of the sound played when the slime jumps. + */ + protected String getJumpSound() { + return "mob.slime." + (this.getSlimeSize() > 1 ? "big" : "small"); + } + + protected EnumParticleTypes getParticleType() { + return EnumParticleTypes.SLIME; + } + + /** + * + Returns the size of the slime. + */ + public int getSlimeSize() { + return this.dataWatcher.getWatchableObjectByte(16); + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.4F * (float) this.getSlimeSize(); + } + + /** + * + The speed it takes to move the entityliving's rotationPitch through the + * faceEntity method. This is only currently use in wolves. + */ + public int getVerticalFaceSpeed() { + return 0; + } + + /** + * + Causes this entity to do an upwards motion (jumping). + */ + protected void jump() { + this.motionY = 0.41999998688697815D; + this.isAirBorne = true; + } + + /** + * + Returns true if the slime makes a sound when it jumps (based upon the + * slime's size) + */ + protected boolean makesSoundOnJump() { + return this.getSlimeSize() > 0; + } + + /** + * + Returns true if the slime makes a sound when it lands after a jump (based + * upon the slime's size) + */ + protected boolean makesSoundOnLand() { + return this.getSlimeSize() > 2; + } + + /** + * + Called by a player entity when they collide with an entity + */ + public void onCollideWithPlayer(EntityPlayer entityplayer) { + if (this.canDamagePlayer()) { + this.func_175451_e(entityplayer); + } + + } + + public void onDataWatcherUpdate(int i) { + if (i == 16) { + int j = this.getSlimeSize(); + this.setSize(0.51000005F * (float) j, 0.51000005F * (float) j); + this.rotationYaw = this.rotationYawHead; + this.renderYawOffset = this.rotationYawHead; + if (this.isInWater() && this.rand.nextInt(20) == 0) { + this.resetHeight(); + } + } + + super.onDataWatcherUpdate(i); + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + int i = this.rand.nextInt(3); + if (i < 2 && this.rand.nextFloat() < 0.5F * difficultyinstance.getClampedAdditionalDifficulty()) { + ++i; + } + + int j = 1 << i; + this.setSlimeSize(j); + return super.onInitialSpawn(difficultyinstance, ientitylivingdata); + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + if (!this.worldObj.isRemote && this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL + && this.getSlimeSize() > 0) { + this.isDead = true; + } + + this.squishFactor += (this.squishAmount - this.squishFactor) * 0.5F; + this.prevSquishFactor = this.squishFactor; + super.onUpdate(); + if (this.onGround && !this.wasOnGround) { + int i = this.getSlimeSize(); + + for (int j = 0; j < i * 8; ++j) { + float f = this.rand.nextFloat() * 3.1415927F * 2.0F; + float f1 = this.rand.nextFloat() * 0.5F + 0.5F; + float f2 = MathHelper.sin(f) * (float) i * 0.5F * f1; + float f3 = MathHelper.cos(f) * (float) i * 0.5F * f1; + World world = this.worldObj; + EnumParticleTypes enumparticletypes = this.getParticleType(); + double d0 = this.posX + (double) f2; + double d1 = this.posZ + (double) f3; + world.spawnParticle(enumparticletypes, d0, this.getEntityBoundingBox().minY, d1, 0.0D, 0.0D, 0.0D, + new int[0]); + } + + if (this.makesSoundOnLand()) { + this.playSound(this.getJumpSound(), this.getSoundVolume(), + ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F) / 0.8F); + } + + this.squishAmount = -0.5F; + } else if (!this.onGround && this.wasOnGround) { + this.squishAmount = 1.0F; + } + + this.wasOnGround = this.onGround; + this.alterSquishAmount(); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + int i = nbttagcompound.getInteger("Size"); + if (i < 0) { + i = 0; + } + + this.setSlimeSize(i + 1); + this.wasOnGround = nbttagcompound.getBoolean("wasOnGround"); + } + + /** + * + Will get destroyed next tick. + */ + public void setDead() { + int i = this.getSlimeSize(); + if (!this.worldObj.isRemote && i > 1 && this.getHealth() <= 0.0F) { + int j = 2 + this.rand.nextInt(3); + + for (int k = 0; k < j; ++k) { + float f = ((float) (k % 2) - 0.5F) * (float) i / 4.0F; + float f1 = ((float) (k / 2) - 0.5F) * (float) i / 4.0F; + EntitySlime entityslime = this.createInstance(); + if (this.hasCustomName()) { + entityslime.setCustomNameTag(this.getCustomNameTag()); + } + + if (this.isNoDespawnRequired()) { + entityslime.enablePersistence(); + } + + entityslime.setSlimeSize(i / 2); + entityslime.setLocationAndAngles(this.posX + (double) f, this.posY + 0.5D, this.posZ + (double) f1, + this.rand.nextFloat() * 360.0F, 0.0F); + this.worldObj.spawnEntityInWorld(entityslime); + } + } + + super.setDead(); + } + + protected void setSlimeSize(int size) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) size)); + this.setSize(0.51000005F * (float) size, 0.51000005F * (float) size); + this.setPosition(this.posX, this.posY, this.posZ); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue((double) (size * size)); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed) + .setBaseValue((double) (0.2F + 0.1F * (float) size)); + this.setHealth(this.getMaxHealth()); + this.experienceValue = size; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("Size", this.getSlimeSize() - 1); + nbttagcompound.setBoolean("wasOnGround", this.wasOnGround); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntitySnowman.java b/src/game/java/net/minecraft/entity/monster/EntitySnowman.java index f964bb5f..3688982d 100644 --- a/src/game/java/net/minecraft/entity/monster/EntitySnowman.java +++ b/src/game/java/net/minecraft/entity/monster/EntitySnowman.java @@ -21,22 +21,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,10 +63,45 @@ public class EntitySnowman extends EntityGolem implements IRangedAttackMob { this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Attack the specified entity using a ranged attack. + */ + public void attackEntityWithRangedAttack(EntityLivingBase parEntityLivingBase, float parFloat1) { + EntitySnowball entitysnowball = new EntitySnowball(this.worldObj, this); + double d0 = parEntityLivingBase.posY + (double) parEntityLivingBase.getEyeHeight() - 1.100000023841858D; + double d1 = parEntityLivingBase.posX - this.posX; + double d2 = d0 - entitysnowball.posY; + double d3 = parEntityLivingBase.posZ - this.posZ; + float f = MathHelper.sqrt_double(d1 * d1 + d3 * d3) * 0.2F; + entitysnowball.setThrowableHeading(d1, d2 + (double) f, d3, 1.6F, 12.0F); + this.playSound("random.bow", 1.0F, 1.0F / (this.getRNG().nextFloat() * 0.4F + 0.8F)); + this.worldObj.spawnEntityInWorld(entitysnowball); + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int var2) { + int i = this.rand.nextInt(16); + + for (int j = 0; j < i; ++j) { + this.dropItem(Items.snowball, 1); + } + + } + + protected Item getDropItem() { + return Items.snowball; + } + + public float getEyeHeight() { + return 1.7F; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); @@ -95,39 +133,4 @@ public class EntitySnowman extends EntityGolem implements IRangedAttackMob { } } - - protected Item getDropItem() { - return Items.snowball; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int var2) { - int i = this.rand.nextInt(16); - - for (int j = 0; j < i; ++j) { - this.dropItem(Items.snowball, 1); - } - - } - - /**+ - * Attack the specified entity using a ranged attack. - */ - public void attackEntityWithRangedAttack(EntityLivingBase parEntityLivingBase, float parFloat1) { - EntitySnowball entitysnowball = new EntitySnowball(this.worldObj, this); - double d0 = parEntityLivingBase.posY + (double) parEntityLivingBase.getEyeHeight() - 1.100000023841858D; - double d1 = parEntityLivingBase.posX - this.posX; - double d2 = d0 - entitysnowball.posY; - double d3 = parEntityLivingBase.posZ - this.posZ; - float f = MathHelper.sqrt_double(d1 * d1 + d3 * d3) * 0.2F; - entitysnowball.setThrowableHeading(d1, d2 + (double) f, d3, 1.6F, 12.0F); - this.playSound("random.bow", 1.0F, 1.0F / (this.getRNG().nextFloat() * 0.4F + 0.8F)); - this.worldObj.spawnEntityInWorld(entitysnowball); - } - - public float getEyeHeight() { - return 1.7F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntitySpider.java b/src/game/java/net/minecraft/entity/monster/EntitySpider.java index 63cae72b..03898382 100644 --- a/src/game/java/net/minecraft/entity/monster/EntitySpider.java +++ b/src/game/java/net/minecraft/entity/monster/EntitySpider.java @@ -27,206 +27,30 @@ import net.minecraft.world.DifficultyInstance; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySpider extends EntityMob { - public EntitySpider(World worldIn) { - super(worldIn); - this.setSize(1.4F, 0.9F); - this.tasks.addTask(1, new EntityAISwimming(this)); - this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F)); - this.tasks.addTask(4, new EntitySpider.AISpiderAttack(this, EntityPlayer.class)); - this.tasks.addTask(4, new EntitySpider.AISpiderAttack(this, EntityIronGolem.class)); - this.tasks.addTask(5, new EntityAIWander(this, 0.8D)); - this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); - this.tasks.addTask(6, new EntityAILookIdle(this)); - this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0])); - this.targetTasks.addTask(2, new EntitySpider.AISpiderTarget(this, EntityPlayer.class)); - this.targetTasks.addTask(3, new EntitySpider.AISpiderTarget(this, EntityIronGolem.class)); - } - - /**+ - * Returns the Y offset from the entity's position for any - * entity riding this one. - */ - public double getMountedYOffset() { - return (double) (this.height * 0.5F); - } - - /**+ - * Returns new PathNavigateGround instance - */ - protected PathNavigate getNewNavigator(World world) { - return new PathNavigateClimber(this, world); - } - - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - super.onUpdate(); - if (!this.worldObj.isRemote) { - this.setBesideClimbableBlock(this.isCollidedHorizontally); - } - - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(16.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.spider.say"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.spider.say"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.spider.death"; - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.spider.step", 0.15F, 1.0F); - } - - protected Item getDropItem() { - return Items.string; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean flag, int i) { - super.dropFewItems(flag, i); - if (flag && (this.rand.nextInt(3) == 0 || this.rand.nextInt(1 + i) > 0)) { - this.dropItem(Items.spider_eye, 1); - } - - } - - /**+ - * returns true if this entity is by a ladder, false otherwise - */ - public boolean isOnLadder() { - return this.isBesideClimbableBlock(); - } - - /**+ - * Sets the Entity inside a web block. - */ - public void setInWeb() { - } - - /**+ - * Get this Entity's EnumCreatureAttribute - */ - public EnumCreatureAttribute getCreatureAttribute() { - return EnumCreatureAttribute.ARTHROPOD; - } - - public boolean isPotionApplicable(PotionEffect potioneffect) { - return potioneffect.getPotionID() == Potion.poison.id ? false : super.isPotionApplicable(potioneffect); - } - - /**+ - * Returns true if the WatchableObject (Byte) is 0x01 otherwise - * returns false. The WatchableObject is updated using - * setBesideClimableBlock. - */ - public boolean isBesideClimbableBlock() { - return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; - } - - /**+ - * Updates the WatchableObject (Byte) created in entityInit(), - * setting it to 0x01 if par1 is true or 0x00 if it is false. - */ - public void setBesideClimbableBlock(boolean parFlag) { - byte b0 = this.dataWatcher.getWatchableObjectByte(16); - if (parFlag) { - b0 = (byte) (b0 | 1); - } else { - b0 = (byte) (b0 & -2); - } - - this.dataWatcher.updateObject(16, Byte.valueOf(b0)); - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); - if (this.worldObj.rand.nextInt(100) == 0) { - EntitySkeleton entityskeleton = new EntitySkeleton(this.worldObj); - entityskeleton.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0F); - entityskeleton.onInitialSpawn(difficultyinstance, (IEntityLivingData) null); - this.worldObj.spawnEntityInWorld(entityskeleton); - entityskeleton.mountEntity(this); - } - - if (ientitylivingdata == null) { - ientitylivingdata = new EntitySpider.GroupData(); - if (this.worldObj.getDifficulty() == EnumDifficulty.HARD - && this.worldObj.rand.nextFloat() < 0.1F * difficultyinstance.getClampedAdditionalDifficulty()) { - ((EntitySpider.GroupData) ientitylivingdata).func_111104_a(this.worldObj.rand); - } - } - - if (ientitylivingdata instanceof EntitySpider.GroupData) { - int i = ((EntitySpider.GroupData) ientitylivingdata).potionEffectId; - if (i > 0 && Potion.potionTypes[i] != null) { - this.addPotionEffect(new PotionEffect(i, Integer.MAX_VALUE)); - } - } - - return ientitylivingdata; - } - - public float getEyeHeight() { - return 0.65F; - } - static class AISpiderAttack extends EntityAIAttackOnCollide { public AISpiderAttack(EntitySpider parEntitySpider, Class targetClass) { super(parEntitySpider, targetClass, 1.0D, true); @@ -275,4 +99,181 @@ public class EntitySpider extends EntityMob { } } + + public EntitySpider(World worldIn) { + super(worldIn); + this.setSize(1.4F, 0.9F); + this.tasks.addTask(1, new EntityAISwimming(this)); + this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F)); + this.tasks.addTask(4, new EntitySpider.AISpiderAttack(this, EntityPlayer.class)); + this.tasks.addTask(4, new EntitySpider.AISpiderAttack(this, EntityIronGolem.class)); + this.tasks.addTask(5, new EntityAIWander(this, 0.8D)); + this.tasks.addTask(6, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); + this.tasks.addTask(6, new EntityAILookIdle(this)); + this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0])); + this.targetTasks.addTask(2, new EntitySpider.AISpiderTarget(this, EntityPlayer.class)); + this.targetTasks.addTask(3, new EntitySpider.AISpiderTarget(this, EntityIronGolem.class)); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(16.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean flag, int i) { + super.dropFewItems(flag, i); + if (flag && (this.rand.nextInt(3) == 0 || this.rand.nextInt(1 + i) > 0)) { + this.dropItem(Items.spider_eye, 1); + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + /** + * + Get this Entity's EnumCreatureAttribute + */ + public EnumCreatureAttribute getCreatureAttribute() { + return EnumCreatureAttribute.ARTHROPOD; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.spider.death"; + } + + protected Item getDropItem() { + return Items.string; + } + + public float getEyeHeight() { + return 0.65F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.spider.say"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.spider.say"; + } + + /** + * + Returns the Y offset from the entity's position for any entity riding this + * one. + */ + public double getMountedYOffset() { + return (double) (this.height * 0.5F); + } + + /** + * + Returns new PathNavigateGround instance + */ + protected PathNavigate getNewNavigator(World world) { + return new PathNavigateClimber(this, world); + } + + /** + * + Returns true if the WatchableObject (Byte) is 0x01 otherwise returns false. + * The WatchableObject is updated using setBesideClimableBlock. + */ + public boolean isBesideClimbableBlock() { + return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; + } + + /** + * + returns true if this entity is by a ladder, false otherwise + */ + public boolean isOnLadder() { + return this.isBesideClimbableBlock(); + } + + public boolean isPotionApplicable(PotionEffect potioneffect) { + return potioneffect.getPotionID() == Potion.poison.id ? false : super.isPotionApplicable(potioneffect); + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); + if (this.worldObj.rand.nextInt(100) == 0) { + EntitySkeleton entityskeleton = new EntitySkeleton(this.worldObj); + entityskeleton.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0F); + entityskeleton.onInitialSpawn(difficultyinstance, (IEntityLivingData) null); + this.worldObj.spawnEntityInWorld(entityskeleton); + entityskeleton.mountEntity(this); + } + + if (ientitylivingdata == null) { + ientitylivingdata = new EntitySpider.GroupData(); + if (this.worldObj.getDifficulty() == EnumDifficulty.HARD + && this.worldObj.rand.nextFloat() < 0.1F * difficultyinstance.getClampedAdditionalDifficulty()) { + ((EntitySpider.GroupData) ientitylivingdata).func_111104_a(this.worldObj.rand); + } + } + + if (ientitylivingdata instanceof EntitySpider.GroupData) { + int i = ((EntitySpider.GroupData) ientitylivingdata).potionEffectId; + if (i > 0 && Potion.potionTypes[i] != null) { + this.addPotionEffect(new PotionEffect(i, Integer.MAX_VALUE)); + } + } + + return ientitylivingdata; + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + super.onUpdate(); + if (!this.worldObj.isRemote) { + this.setBesideClimbableBlock(this.isCollidedHorizontally); + } + + } + + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.spider.step", 0.15F, 1.0F); + } + + /** + * + Updates the WatchableObject (Byte) created in entityInit(), setting it to + * 0x01 if par1 is true or 0x00 if it is false. + */ + public void setBesideClimbableBlock(boolean parFlag) { + byte b0 = this.dataWatcher.getWatchableObjectByte(16); + if (parFlag) { + b0 = (byte) (b0 | 1); + } else { + b0 = (byte) (b0 & -2); + } + + this.dataWatcher.updateObject(16, Byte.valueOf(b0)); + } + + /** + * + Sets the Entity inside a web block. + */ + public void setInWeb() { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityWitch.java b/src/game/java/net/minecraft/entity/monster/EntityWitch.java index c05d5f34..71e9df74 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityWitch.java +++ b/src/game/java/net/minecraft/entity/monster/EntityWitch.java @@ -1,6 +1,7 @@ package net.minecraft.entity.monster; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.material.Material; import net.minecraft.entity.EntityLivingBase; @@ -27,22 +28,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,8 +56,8 @@ public class EntityWitch extends EntityMob implements IRangedAttackMob { .fromString("5CD17E52-A79A-43D3-A529-90FDE04B181E"); private static final AttributeModifier MODIFIER = (new AttributeModifier(MODIFIER_UUID, "Drinking speed penalty", -0.25D, 0)).setSaved(false); - /**+ - * List of items a witch should drop on death. + /** + * + List of items a witch should drop on death. */ private static final Item[] witchDrops = new Item[] { Items.glowstone_dust, Items.sugar, Items.redstone, Items.spider_eye, Items.glass_bottle, Items.gunpowder, Items.stick, Items.stick }; @@ -71,56 +75,129 @@ public class EntityWitch extends EntityMob implements IRangedAttackMob { this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); } - protected void entityInit() { - super.entityInit(); - this.getDataWatcher().addObject(21, Byte.valueOf((byte) 0)); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return null; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return null; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return null; - } - - /**+ - * Set whether this witch is aggressive at an entity. - */ - public void setAggressive(boolean aggressive) { - this.getDataWatcher().updateObject(21, Byte.valueOf((byte) (aggressive ? 1 : 0))); - } - - /**+ - * Return whether this witch is aggressive at an entity. - */ - public boolean getAggressive() { - return this.getDataWatcher().getWatchableObjectByte(21) == 1; - } - protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(26.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Reduces damage, depending on potions + */ + protected float applyPotionDamageCalculations(DamageSource damagesource, float f) { + f = super.applyPotionDamageCalculations(damagesource, f); + if (damagesource.getEntity() == this) { + f = 0.0F; + } + + if (damagesource.isMagicDamage()) { + f = (float) ((double) f * 0.15D); + } + + return f; + } + + /** + * + Attack the specified entity using a ranged attack. + */ + public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float var2) { + if (!this.getAggressive()) { + EntityPotion entitypotion = new EntityPotion(this.worldObj, this, 32732); + double d0 = entitylivingbase.posY + (double) entitylivingbase.getEyeHeight() - 1.100000023841858D; + entitypotion.rotationPitch -= -20.0F; + double d1 = entitylivingbase.posX + entitylivingbase.motionX - this.posX; + double d2 = d0 - this.posY; + double d3 = entitylivingbase.posZ + entitylivingbase.motionZ - this.posZ; + float f = MathHelper.sqrt_double(d1 * d1 + d3 * d3); + if (f >= 8.0F && !entitylivingbase.isPotionActive(Potion.moveSlowdown)) { + entitypotion.setPotionDamage(32698); + } else if (entitylivingbase.getHealth() >= 8.0F && !entitylivingbase.isPotionActive(Potion.poison)) { + entitypotion.setPotionDamage(32660); + } else if (f <= 3.0F && !entitylivingbase.isPotionActive(Potion.weakness) + && this.rand.nextFloat() < 0.25F) { + entitypotion.setPotionDamage(32696); + } + + entitypotion.setThrowableHeading(d1, d2 + (double) (f * 0.2F), d3, 0.75F, 8.0F); + this.worldObj.spawnEntityInWorld(entitypotion); + } + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + int j = this.rand.nextInt(3) + 1; + + for (int k = 0; k < j; ++k) { + int l = this.rand.nextInt(3); + Item item = witchDrops[this.rand.nextInt(witchDrops.length)]; + if (i > 0) { + l += this.rand.nextInt(i + 1); + } + + for (int i1 = 0; i1 < l; ++i1) { + this.dropItem(item, 1); + } + } + + } + + protected void entityInit() { + super.entityInit(); + this.getDataWatcher().addObject(21, Byte.valueOf((byte) 0)); + } + + /** + * + Return whether this witch is aggressive at an entity. + */ + public boolean getAggressive() { + return this.getDataWatcher().getWatchableObjectByte(21) == 1; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return null; + } + + public float getEyeHeight() { + return 1.62F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return null; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return null; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 15) { + for (int i = 0; i < this.rand.nextInt(35) + 10; ++i) { + this.worldObj.spawnParticle(EnumParticleTypes.SPELL_WITCH, + this.posX + this.rand.nextGaussian() * 0.12999999523162842D, + this.getEntityBoundingBox().maxY + 0.5D + this.rand.nextGaussian() * 0.12999999523162842D, + this.posZ + this.rand.nextGaussian() * 0.12999999523162842D, 0.0D, 0.0D, 0.0D, new int[0]); + } + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (!this.worldObj.isRemote) { @@ -179,83 +256,10 @@ public class EntityWitch extends EntityMob implements IRangedAttackMob { super.onLivingUpdate(); } - public void handleStatusUpdate(byte b0) { - if (b0 == 15) { - for (int i = 0; i < this.rand.nextInt(35) + 10; ++i) { - this.worldObj.spawnParticle(EnumParticleTypes.SPELL_WITCH, - this.posX + this.rand.nextGaussian() * 0.12999999523162842D, - this.getEntityBoundingBox().maxY + 0.5D + this.rand.nextGaussian() * 0.12999999523162842D, - this.posZ + this.rand.nextGaussian() * 0.12999999523162842D, 0.0D, 0.0D, 0.0D, new int[0]); - } - } else { - super.handleStatusUpdate(b0); - } - - } - - /**+ - * Reduces damage, depending on potions + /** + * + Set whether this witch is aggressive at an entity. */ - protected float applyPotionDamageCalculations(DamageSource damagesource, float f) { - f = super.applyPotionDamageCalculations(damagesource, f); - if (damagesource.getEntity() == this) { - f = 0.0F; - } - - if (damagesource.isMagicDamage()) { - f = (float) ((double) f * 0.15D); - } - - return f; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - int j = this.rand.nextInt(3) + 1; - - for (int k = 0; k < j; ++k) { - int l = this.rand.nextInt(3); - Item item = witchDrops[this.rand.nextInt(witchDrops.length)]; - if (i > 0) { - l += this.rand.nextInt(i + 1); - } - - for (int i1 = 0; i1 < l; ++i1) { - this.dropItem(item, 1); - } - } - - } - - /**+ - * Attack the specified entity using a ranged attack. - */ - public void attackEntityWithRangedAttack(EntityLivingBase entitylivingbase, float var2) { - if (!this.getAggressive()) { - EntityPotion entitypotion = new EntityPotion(this.worldObj, this, 32732); - double d0 = entitylivingbase.posY + (double) entitylivingbase.getEyeHeight() - 1.100000023841858D; - entitypotion.rotationPitch -= -20.0F; - double d1 = entitylivingbase.posX + entitylivingbase.motionX - this.posX; - double d2 = d0 - this.posY; - double d3 = entitylivingbase.posZ + entitylivingbase.motionZ - this.posZ; - float f = MathHelper.sqrt_double(d1 * d1 + d3 * d3); - if (f >= 8.0F && !entitylivingbase.isPotionActive(Potion.moveSlowdown)) { - entitypotion.setPotionDamage(32698); - } else if (entitylivingbase.getHealth() >= 8.0F && !entitylivingbase.isPotionActive(Potion.poison)) { - entitypotion.setPotionDamage(32660); - } else if (f <= 3.0F && !entitylivingbase.isPotionActive(Potion.weakness) - && this.rand.nextFloat() < 0.25F) { - entitypotion.setPotionDamage(32696); - } - - entitypotion.setThrowableHeading(d1, d2 + (double) (f * 0.2F), d3, 0.75F, 8.0F); - this.worldObj.spawnEntityInWorld(entitypotion); - } - } - - public float getEyeHeight() { - return 1.62F; + public void setAggressive(boolean aggressive) { + this.getDataWatcher().updateObject(21, Byte.valueOf((byte) (aggressive ? 1 : 0))); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/EntityZombie.java b/src/game/java/net/minecraft/entity/monster/EntityZombie.java index d69718cc..2c818f01 100644 --- a/src/game/java/net/minecraft/entity/monster/EntityZombie.java +++ b/src/game/java/net/minecraft/entity/monster/EntityZombie.java @@ -2,6 +2,7 @@ package net.minecraft.entity.monster; import java.util.Calendar; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -43,30 +44,45 @@ import net.minecraft.world.DifficultyInstance; import net.minecraft.world.EnumDifficulty; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityZombie extends EntityMob { - /**+ - * The attribute which determines the chance that this mob will - * spawn reinforcements + class GroupData implements IEntityLivingData { + public boolean isChild; + public boolean isVillager; + + private GroupData(boolean isBaby, boolean isVillagerZombie) { + this.isChild = false; + this.isVillager = false; + this.isChild = isBaby; + this.isVillager = isVillagerZombie; + } + } + + /** + * + The attribute which determines the chance that this mob will spawn + * reinforcements */ protected static final IAttribute reinforcementChance = (new RangedAttribute((IAttribute) null, "zombie.spawnReinforcements", 0.0D, 0.0D, 1.0D)).setDescription("Spawn Reinforcements Chance"); @@ -77,10 +93,11 @@ public class EntityZombie extends EntityMob { private final EntityAIBreakDoor breakDoor = new EntityAIBreakDoor(this); private int conversionTime; private boolean isBreakDoorsTaskSet = false; - /**+ - * The width of the entity + /** + * + The width of the entity */ private float zombieWidth = -1.0F; + private float zombieHeight; public EntityZombie(World worldIn) { @@ -92,10 +109,29 @@ public class EntityZombie extends EntityMob { this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); this.tasks.addTask(8, new EntityAIWatchClosest(this, EntityPlayer.class, 8.0F)); this.tasks.addTask(8, new EntityAILookIdle(this)); + this.tasks.addTask(9, new EntityAINearestAttackableTarget(this, EntityNetherCreeper.class, true)); + this.applyEntityAI(); this.setSize(0.6F, 1.95F); } + /** + * + Causes this Entity to drop a random item. + */ + protected void addRandomDrop() { + switch (this.rand.nextInt(3)) { + case 0: + this.dropItem(Items.iron_ingot, 1); + break; + case 1: + this.dropItem(Items.carrot, 1); + break; + case 2: + this.dropItem(Items.potato, 1); + } + + } + protected void applyEntityAI() { this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityVillager.class, 1.0D, true)); this.tasks.addTask(4, new EntityAIAttackOnCollide(this, EntityIronGolem.class, 1.0D, true)); @@ -115,132 +151,20 @@ public class EntityZombie extends EntityMob { .setBaseValue(this.rand.nextDouble() * 0.10000000149011612D); } - protected void entityInit() { - super.entityInit(); - this.getDataWatcher().addObject(12, Byte.valueOf((byte) 0)); - this.getDataWatcher().addObject(13, Byte.valueOf((byte) 0)); - this.getDataWatcher().addObject(14, Byte.valueOf((byte) 0)); - } - - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - int i = super.getTotalArmorValue() + 2; - if (i > 20) { - i = 20; - } - - return i; - } - - public boolean isBreakDoorsTaskSet() { - return this.isBreakDoorsTaskSet; - } - - /**+ - * Sets or removes EntityAIBreakDoor task - */ - public void setBreakDoorsAItask(boolean par1) { - if (this.isBreakDoorsTaskSet != par1) { - this.isBreakDoorsTaskSet = par1; - if (par1) { - this.tasks.addTask(1, this.breakDoor); - } else { - this.tasks.removeTask(this.breakDoor); + public boolean attackEntityAsMob(Entity entity) { + boolean flag = super.attackEntityAsMob(entity); + if (flag) { + int i = this.worldObj.getDifficulty().getDifficultyId(); + if (this.getHeldItem() == null && this.isBurning() && this.rand.nextFloat() < (float) i * 0.3F) { + entity.setFire(2 * i); } } + return flag; } - /**+ - * If Animal, checks if the age timer is negative - */ - public boolean isChild() { - return this.getDataWatcher().getWatchableObjectByte(12) == 1; - } - - /**+ - * Get the experience points the entity currently has. - */ - protected int getExperiencePoints(EntityPlayer entityplayer) { - if (this.isChild()) { - this.experienceValue = (int) ((float) this.experienceValue * 2.5F); - } - - return super.getExperiencePoints(entityplayer); - } - - /**+ - * Set whether this zombie is a child. - */ - public void setChild(boolean childZombie) { - this.getDataWatcher().updateObject(12, Byte.valueOf((byte) (childZombie ? 1 : 0))); - if (this.worldObj != null && !this.worldObj.isRemote) { - IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); - iattributeinstance.removeModifier(babySpeedBoostModifier); - if (childZombie) { - iattributeinstance.applyModifier(babySpeedBoostModifier); - } - } - - this.setChildSize(childZombie); - } - - /**+ - * Return whether this zombie is a villager. - */ - public boolean isVillager() { - return this.getDataWatcher().getWatchableObjectByte(13) == 1; - } - - /**+ - * Set whether this zombie is a villager. - */ - public void setVillager(boolean villager) { - this.getDataWatcher().updateObject(13, Byte.valueOf((byte) (villager ? 1 : 0))); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - if (this.worldObj.isDaytime() && !this.worldObj.isRemote && !this.isChild()) { - float f = this.getBrightness(1.0F); - BlockPos blockpos = new BlockPos(this.posX, (double) Math.round(this.posY), this.posZ); - if (f > 0.5F && this.rand.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.worldObj.canSeeSky(blockpos)) { - boolean flag = true; - ItemStack itemstack = this.getEquipmentInSlot(4); - if (itemstack != null) { - if (itemstack.isItemStackDamageable()) { - itemstack.setItemDamage(itemstack.getItemDamage() + this.rand.nextInt(2)); - if (itemstack.getItemDamage() >= itemstack.getMaxDamage()) { - this.renderBrokenItemStack(itemstack); - this.setCurrentItemOrArmor(4, (ItemStack) null); - } - } - - flag = false; - } - - if (flag) { - this.setFire(8); - } - } - } - - if (this.isRiding() && this.getAttackTarget() != null && this.ridingEntity instanceof EntityChicken) { - ((EntityLiving) this.ridingEntity).getNavigator().setPath(this.getNavigator().getPath(), 1.5D); - } - - super.onLivingUpdate(); - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (super.attackEntityFrom(damagesource, f)) { @@ -295,176 +219,107 @@ public class EntityZombie extends EntityMob { } } - /**+ - * Called to update the entity's position/logic. + /** + * + Determines if an entity can be despawned, used on idle far away entities */ - public void onUpdate() { - if (!this.worldObj.isRemote && this.isConverting()) { - int i = this.getConversionTimeBoost(); - this.conversionTime -= i; - if (this.conversionTime <= 0) { - this.convertToVillager(); + protected boolean canDespawn() { + return !this.isConverting(); + } + + /** + * + Convert this zombie into a villager. + */ + protected void convertToVillager() { + EntityVillager entityvillager = new EntityVillager(this.worldObj); + entityvillager.copyLocationAndAnglesFrom(this); + entityvillager.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entityvillager)), + (IEntityLivingData) null); + entityvillager.setLookingForHome(); + if (this.isChild()) { + entityvillager.setGrowingAge(-24000); + } + + this.worldObj.removeEntity(this); + entityvillager.setNoAI(this.isAIDisabled()); + if (this.hasCustomName()) { + entityvillager.setCustomNameTag(this.getCustomNameTag()); + entityvillager.setAlwaysRenderNameTag(this.getAlwaysRenderNameTag()); + } + + this.worldObj.spawnEntityInWorld(entityvillager); + entityvillager.addPotionEffect(new PotionEffect(Potion.confusion.id, 200, 0)); + this.worldObj.playAuxSFXAtEntity((EntityPlayer) null, 1017, + new BlockPos((int) this.posX, (int) this.posY, (int) this.posZ), 0); + } + + protected void entityInit() { + super.entityInit(); + this.getDataWatcher().addObject(12, Byte.valueOf((byte) 0)); + this.getDataWatcher().addObject(13, Byte.valueOf((byte) 0)); + this.getDataWatcher().addObject(14, Byte.valueOf((byte) 0)); + } + + protected boolean func_175448_a(ItemStack itemstack) { + return itemstack.getItem() == Items.egg && this.isChild() && this.isRiding() ? false + : super.func_175448_a(itemstack); + } + + /** + * + Return the amount of time decremented from conversionTime every tick. + */ + protected int getConversionTimeBoost() { + int i = 1; + if (this.rand.nextFloat() < 0.01F) { + int j = 0; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k = (int) this.posX - 4; k < (int) this.posX + 4 && j < 14; ++k) { + for (int l = (int) this.posY - 4; l < (int) this.posY + 4 && j < 14; ++l) { + for (int i1 = (int) this.posZ - 4; i1 < (int) this.posZ + 4 && j < 14; ++i1) { + Block block = this.worldObj.getBlockState(blockpos$mutableblockpos.func_181079_c(k, l, i1)) + .getBlock(); + if (block == Blocks.iron_bars || block == Blocks.bed) { + if (this.rand.nextFloat() < 0.3F) { + ++i; + } + + ++j; + } + } + } } } - super.onUpdate(); + return i; } - public boolean attackEntityAsMob(Entity entity) { - boolean flag = super.attackEntityAsMob(entity); - if (flag) { - int i = this.worldObj.getDifficulty().getDifficultyId(); - if (this.getHeldItem() == null && this.isBurning() && this.rand.nextFloat() < (float) i * 0.3F) { - entity.setFire(2 * i); - } - } - - return flag; - } - - /**+ - * Returns the sound this mob makes while it's alive. + /** + * + Get this Entity's EnumCreatureAttribute */ - protected String getLivingSound() { - return "mob.zombie.say"; + public EnumCreatureAttribute getCreatureAttribute() { + return EnumCreatureAttribute.UNDEAD; } - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.zombie.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. + /** + * + Returns the sound this mob makes on death. */ protected String getDeathSound() { return "mob.zombie.death"; } - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.zombie.step", 0.15F, 1.0F); - } - protected Item getDropItem() { return Items.rotten_flesh; } - /**+ - * Get this Entity's EnumCreatureAttribute + /** + * + Get the experience points the entity currently has. */ - public EnumCreatureAttribute getCreatureAttribute() { - return EnumCreatureAttribute.UNDEAD; - } - - /**+ - * Causes this Entity to drop a random item. - */ - protected void addRandomDrop() { - switch (this.rand.nextInt(3)) { - case 0: - this.dropItem(Items.iron_ingot, 1); - break; - case 1: - this.dropItem(Items.carrot, 1); - break; - case 2: - this.dropItem(Items.potato, 1); - } - - } - - /**+ - * Gives armor or weapon for entity based on given - * DifficultyInstance - */ - protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficultyinstance) { - super.setEquipmentBasedOnDifficulty(difficultyinstance); - if (this.rand.nextFloat() < (this.worldObj.getDifficulty() == EnumDifficulty.HARD ? 0.05F : 0.01F)) { - int i = this.rand.nextInt(3); - if (i == 0) { - this.setCurrentItemOrArmor(0, new ItemStack(Items.iron_sword)); - } else { - this.setCurrentItemOrArmor(0, new ItemStack(Items.iron_shovel)); - } - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); + protected int getExperiencePoints(EntityPlayer entityplayer) { if (this.isChild()) { - nbttagcompound.setBoolean("IsBaby", true); - } - - if (this.isVillager()) { - nbttagcompound.setBoolean("IsVillager", true); - } - - nbttagcompound.setInteger("ConversionTime", this.isConverting() ? this.conversionTime : -1); - nbttagcompound.setBoolean("CanBreakDoors", this.isBreakDoorsTaskSet()); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - if (nbttagcompound.getBoolean("IsBaby")) { - this.setChild(true); - } - - if (nbttagcompound.getBoolean("IsVillager")) { - this.setVillager(true); - } - - if (nbttagcompound.hasKey("ConversionTime", 99) && nbttagcompound.getInteger("ConversionTime") > -1) { - this.startConversion(nbttagcompound.getInteger("ConversionTime")); - } - - this.setBreakDoorsAItask(nbttagcompound.getBoolean("CanBreakDoors")); - } - - /**+ - * This method gets called when the entity kills another one. - */ - public void onKillEntity(EntityLivingBase entitylivingbase) { - super.onKillEntity(entitylivingbase); - if ((this.worldObj.getDifficulty() == EnumDifficulty.NORMAL - || this.worldObj.getDifficulty() == EnumDifficulty.HARD) - && entitylivingbase instanceof EntityVillager) { - if (this.worldObj.getDifficulty() != EnumDifficulty.HARD && this.rand.nextBoolean()) { - return; - } - - EntityLiving entityliving = (EntityLiving) entitylivingbase; - EntityZombie entityzombie = new EntityZombie(this.worldObj); - entityzombie.copyLocationAndAnglesFrom(entitylivingbase); - this.worldObj.removeEntity(entitylivingbase); - entityzombie.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entityzombie)), - (IEntityLivingData) null); - entityzombie.setVillager(true); - if (entitylivingbase.isChild()) { - entityzombie.setChild(true); - } - - entityzombie.setNoAI(entityliving.isAIDisabled()); - if (entityliving.hasCustomName()) { - entityzombie.setCustomNameTag(entityliving.getCustomNameTag()); - entityzombie.setAlwaysRenderNameTag(entityliving.getAlwaysRenderNameTag()); - } - - this.worldObj.spawnEntityInWorld(entityzombie); - this.worldObj.playAuxSFXAtEntity((EntityPlayer) null, 1016, - new BlockPos((int) this.posX, (int) this.posY, (int) this.posZ), 0); + this.experienceValue = (int) ((float) this.experienceValue * 2.5F); } + return super.getExperiencePoints(entityplayer); } public float getEyeHeight() { @@ -476,16 +331,128 @@ public class EntityZombie extends EntityMob { return f; } - protected boolean func_175448_a(ItemStack itemstack) { - return itemstack.getItem() == Items.egg && this.isChild() && this.isRiding() ? false - : super.func_175448_a(itemstack); + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.zombie.hurt"; } - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.zombie.say"; + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue + */ + public int getTotalArmorValue() { + int i = super.getTotalArmorValue() + 2; + if (i > 20) { + i = 20; + } + + return i; + } + + /** + * + Returns the Y Offset of this entity. + */ + public double getYOffset() { + return this.isChild() ? 0.0D : -0.35D; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 16) { + if (!this.isSilent()) { + this.worldObj.playSound(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "mob.zombie.remedy", + 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F, false); + } + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + public boolean interact(EntityPlayer entityplayer) { + ItemStack itemstack = entityplayer.getCurrentEquippedItem(); + if (itemstack != null && itemstack.getItem() == Items.golden_apple && itemstack.getMetadata() == 0 + && this.isVillager() && this.isPotionActive(Potion.weakness)) { + if (!entityplayer.capabilities.isCreativeMode) { + --itemstack.stackSize; + } + + if (itemstack.stackSize <= 0) { + entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, (ItemStack) null); + } + + if (!this.worldObj.isRemote) { + this.startConversion(this.rand.nextInt(2401) + 3600); + } + + return true; + } else { + return false; + } + } + + public boolean isBreakDoorsTaskSet() { + return this.isBreakDoorsTaskSet; + } + + /** + * + If Animal, checks if the age timer is negative + */ + public boolean isChild() { + return this.getDataWatcher().getWatchableObjectByte(12) == 1; + } + + /** + * + Returns whether this zombie is in the process of converting to a villager + */ + public boolean isConverting() { + return this.getDataWatcher().getWatchableObjectByte(14) == 1; + } + + /** + * + Return whether this zombie is a villager. + */ + public boolean isVillager() { + return this.getDataWatcher().getWatchableObjectByte(13) == 1; + } + + /** + * + Multiplies the height and width by the provided float. + */ + protected final void multiplySize(float size) { + super.setSize(this.zombieWidth * size, this.zombieHeight * size); + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + super.onDeath(damagesource); + if (damagesource.getEntity() instanceof EntityCreeper && !(this instanceof EntityPigZombie) + && ((EntityCreeper) damagesource.getEntity()).getPowered() + && ((EntityCreeper) damagesource.getEntity()).isAIEnabled()) { + ((EntityCreeper) damagesource.getEntity()).func_175493_co(); + this.entityDropItem(new ItemStack(Items.skull, 1, 2), 0.0F); + } + + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory */ public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, IEntityLivingData ientitylivingdata) { @@ -555,139 +522,174 @@ public class EntityZombie extends EntityMob { return ientitylivingdata; } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + /** + * + This method gets called when the entity kills another one. */ - public boolean interact(EntityPlayer entityplayer) { - ItemStack itemstack = entityplayer.getCurrentEquippedItem(); - if (itemstack != null && itemstack.getItem() == Items.golden_apple && itemstack.getMetadata() == 0 - && this.isVillager() && this.isPotionActive(Potion.weakness)) { - if (!entityplayer.capabilities.isCreativeMode) { - --itemstack.stackSize; + public void onKillEntity(EntityLivingBase entitylivingbase) { + super.onKillEntity(entitylivingbase); + if ((this.worldObj.getDifficulty() == EnumDifficulty.NORMAL + || this.worldObj.getDifficulty() == EnumDifficulty.HARD) + && entitylivingbase instanceof EntityVillager) { + if (this.worldObj.getDifficulty() != EnumDifficulty.HARD && this.rand.nextBoolean()) { + return; } - if (itemstack.stackSize <= 0) { - entityplayer.inventory.setInventorySlotContents(entityplayer.inventory.currentItem, (ItemStack) null); + EntityLiving entityliving = (EntityLiving) entitylivingbase; + EntityZombie entityzombie = new EntityZombie(this.worldObj); + entityzombie.copyLocationAndAnglesFrom(entitylivingbase); + this.worldObj.removeEntity(entitylivingbase); + entityzombie.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entityzombie)), + (IEntityLivingData) null); + entityzombie.setVillager(true); + if (entitylivingbase.isChild()) { + entityzombie.setChild(true); } - if (!this.worldObj.isRemote) { - this.startConversion(this.rand.nextInt(2401) + 3600); + entityzombie.setNoAI(entityliving.isAIDisabled()); + if (entityliving.hasCustomName()) { + entityzombie.setCustomNameTag(entityliving.getCustomNameTag()); + entityzombie.setAlwaysRenderNameTag(entityliving.getAlwaysRenderNameTag()); } - return true; - } else { - return false; - } - } - - /**+ - * Starts converting this zombie into a villager. The zombie - * converts into a villager after the specified time in ticks. - */ - protected void startConversion(int ticks) { - this.conversionTime = ticks; - this.getDataWatcher().updateObject(14, Byte.valueOf((byte) 1)); - this.removePotionEffect(Potion.weakness.id); - this.addPotionEffect(new PotionEffect(Potion.damageBoost.id, ticks, - Math.min(this.worldObj.getDifficulty().getDifficultyId() - 1, 0))); - this.worldObj.setEntityState(this, (byte) 16); - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 16) { - if (!this.isSilent()) { - this.worldObj.playSound(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, "mob.zombie.remedy", - 1.0F + this.rand.nextFloat(), this.rand.nextFloat() * 0.7F + 0.3F, false); - } - } else { - super.handleStatusUpdate(b0); + this.worldObj.spawnEntityInWorld(entityzombie); + this.worldObj.playAuxSFXAtEntity((EntityPlayer) null, 1016, + new BlockPos((int) this.posX, (int) this.posY, (int) this.posZ), 0); } } - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ - protected boolean canDespawn() { - return !this.isConverting(); - } - - /**+ - * Returns whether this zombie is in the process of converting - * to a villager - */ - public boolean isConverting() { - return this.getDataWatcher().getWatchableObjectByte(14) == 1; - } - - /**+ - * Convert this zombie into a villager. - */ - protected void convertToVillager() { - EntityVillager entityvillager = new EntityVillager(this.worldObj); - entityvillager.copyLocationAndAnglesFrom(this); - entityvillager.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entityvillager)), - (IEntityLivingData) null); - entityvillager.setLookingForHome(); - if (this.isChild()) { - entityvillager.setGrowingAge(-24000); - } - - this.worldObj.removeEntity(this); - entityvillager.setNoAI(this.isAIDisabled()); - if (this.hasCustomName()) { - entityvillager.setCustomNameTag(this.getCustomNameTag()); - entityvillager.setAlwaysRenderNameTag(this.getAlwaysRenderNameTag()); - } - - this.worldObj.spawnEntityInWorld(entityvillager); - entityvillager.addPotionEffect(new PotionEffect(Potion.confusion.id, 200, 0)); - this.worldObj.playAuxSFXAtEntity((EntityPlayer) null, 1017, - new BlockPos((int) this.posX, (int) this.posY, (int) this.posZ), 0); - } - - /**+ - * Return the amount of time decremented from conversionTime - * every tick. - */ - protected int getConversionTimeBoost() { - int i = 1; - if (this.rand.nextFloat() < 0.01F) { - int j = 0; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k = (int) this.posX - 4; k < (int) this.posX + 4 && j < 14; ++k) { - for (int l = (int) this.posY - 4; l < (int) this.posY + 4 && j < 14; ++l) { - for (int i1 = (int) this.posZ - 4; i1 < (int) this.posZ + 4 && j < 14; ++i1) { - Block block = this.worldObj.getBlockState(blockpos$mutableblockpos.func_181079_c(k, l, i1)) - .getBlock(); - if (block == Blocks.iron_bars || block == Blocks.bed) { - if (this.rand.nextFloat() < 0.3F) { - ++i; - } - - ++j; + public void onLivingUpdate() { + if (this.worldObj.isDaytime() && !this.worldObj.isRemote && !this.isChild()) { + float f = this.getBrightness(1.0F); + BlockPos blockpos = new BlockPos(this.posX, (double) Math.round(this.posY), this.posZ); + if (f > 0.5F && this.rand.nextFloat() * 30.0F < (f - 0.4F) * 2.0F && this.worldObj.canSeeSky(blockpos)) { + boolean flag = true; + ItemStack itemstack = this.getEquipmentInSlot(4); + if (itemstack != null) { + if (itemstack.isItemStackDamageable()) { + itemstack.setItemDamage(itemstack.getItemDamage() + this.rand.nextInt(2)); + if (itemstack.getItemDamage() >= itemstack.getMaxDamage()) { + this.renderBrokenItemStack(itemstack); + this.setCurrentItemOrArmor(4, (ItemStack) null); } } + + flag = false; + } + + if (flag) { + this.setFire(8); } } } - return i; + if (this.isRiding() && this.getAttackTarget() != null && this.ridingEntity instanceof EntityChicken) { + ((EntityLiving) this.ridingEntity).getNavigator().setPath(this.getNavigator().getPath(), 1.5D); + } + + super.onLivingUpdate(); } - /**+ - * sets the size of the entity to be half of its current size if - * true. + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + if (!this.worldObj.isRemote && this.isConverting()) { + int i = this.getConversionTimeBoost(); + this.conversionTime -= i; + if (this.conversionTime <= 0) { + this.convertToVillager(); + } + } + + super.onUpdate(); + } + + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.zombie.step", 0.15F, 1.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + if (nbttagcompound.getBoolean("IsBaby")) { + this.setChild(true); + } + + if (nbttagcompound.getBoolean("IsVillager")) { + this.setVillager(true); + } + + if (nbttagcompound.hasKey("ConversionTime", 99) && nbttagcompound.getInteger("ConversionTime") > -1) { + this.startConversion(nbttagcompound.getInteger("ConversionTime")); + } + + this.setBreakDoorsAItask(nbttagcompound.getBoolean("CanBreakDoors")); + } + + /** + * + Sets or removes EntityAIBreakDoor task + */ + public void setBreakDoorsAItask(boolean par1) { + if (this.isBreakDoorsTaskSet != par1) { + this.isBreakDoorsTaskSet = par1; + if (par1) { + this.tasks.addTask(1, this.breakDoor); + } else { + this.tasks.removeTask(this.breakDoor); + } + } + + } + + /** + * + Set whether this zombie is a child. + */ + public void setChild(boolean childZombie) { + this.getDataWatcher().updateObject(12, Byte.valueOf((byte) (childZombie ? 1 : 0))); + if (this.worldObj != null && !this.worldObj.isRemote) { + IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); + iattributeinstance.removeModifier(babySpeedBoostModifier); + if (childZombie) { + iattributeinstance.applyModifier(babySpeedBoostModifier); + } + } + + this.setChildSize(childZombie); + } + + /** + * + sets the size of the entity to be half of its current size if true. */ public void setChildSize(boolean isChild) { this.multiplySize(isChild ? 0.5F : 1.0F); } - /**+ - * Sets the width and height of the entity. Args: width, height + /** + * + Gives armor or weapon for entity based on given DifficultyInstance + */ + protected void setEquipmentBasedOnDifficulty(DifficultyInstance difficultyinstance) { + super.setEquipmentBasedOnDifficulty(difficultyinstance); + if (this.rand.nextFloat() < (this.worldObj.getDifficulty() == EnumDifficulty.HARD ? 0.05F : 0.01F)) { + int i = this.rand.nextInt(3); + if (i == 0) { + this.setCurrentItemOrArmor(0, new ItemStack(Items.iron_sword)); + } else { + this.setCurrentItemOrArmor(0, new ItemStack(Items.iron_shovel)); + } + } + + } + + /** + * + Sets the width and height of the entity. Args: width, height */ protected final void setSize(float f, float f1) { boolean flag = this.zombieWidth > 0.0F && this.zombieHeight > 0.0F; @@ -699,43 +701,40 @@ public class EntityZombie extends EntityMob { } - /**+ - * Multiplies the height and width by the provided float. + /** + * + Set whether this zombie is a villager. */ - protected final void multiplySize(float size) { - super.setSize(this.zombieWidth * size, this.zombieHeight * size); + public void setVillager(boolean villager) { + this.getDataWatcher().updateObject(13, Byte.valueOf((byte) (villager ? 1 : 0))); } - /**+ - * Returns the Y Offset of this entity. + /** + * + Starts converting this zombie into a villager. The zombie converts into a + * villager after the specified time in ticks. */ - public double getYOffset() { - return this.isChild() ? 0.0D : -0.35D; + protected void startConversion(int ticks) { + this.conversionTime = ticks; + this.getDataWatcher().updateObject(14, Byte.valueOf((byte) 1)); + this.removePotionEffect(Potion.weakness.id); + this.addPotionEffect(new PotionEffect(Potion.damageBoost.id, ticks, + Math.min(this.worldObj.getDifficulty().getDifficultyId() - 1, 0))); + this.worldObj.setEntityState(this, (byte) 16); } - /**+ - * Called when the mob's health reaches 0. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public void onDeath(DamageSource damagesource) { - super.onDeath(damagesource); - if (damagesource.getEntity() instanceof EntityCreeper && !(this instanceof EntityPigZombie) - && ((EntityCreeper) damagesource.getEntity()).getPowered() - && ((EntityCreeper) damagesource.getEntity()).isAIEnabled()) { - ((EntityCreeper) damagesource.getEntity()).func_175493_co(); - this.entityDropItem(new ItemStack(Items.skull, 1, 2), 0.0F); + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + if (this.isChild()) { + nbttagcompound.setBoolean("IsBaby", true); } - } - - class GroupData implements IEntityLivingData { - public boolean isChild; - public boolean isVillager; - - private GroupData(boolean isBaby, boolean isVillagerZombie) { - this.isChild = false; - this.isVillager = false; - this.isChild = isBaby; - this.isVillager = isVillagerZombie; + if (this.isVillager()) { + nbttagcompound.setBoolean("IsVillager", true); } + + nbttagcompound.setInteger("ConversionTime", this.isConverting() ? this.conversionTime : -1); + nbttagcompound.setBoolean("CanBreakDoors", this.isBreakDoorsTaskSet()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/monster/IMob.java b/src/game/java/net/minecraft/entity/monster/IMob.java index 2e1c0450..2851a9ff 100644 --- a/src/game/java/net/minecraft/entity/monster/IMob.java +++ b/src/game/java/net/minecraft/entity/monster/IMob.java @@ -5,22 +5,25 @@ import com.google.common.base.Predicate; import net.minecraft.entity.Entity; import net.minecraft.entity.passive.IAnimals; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/passive/EntityAmbientCreature.java b/src/game/java/net/minecraft/entity/passive/EntityAmbientCreature.java index 27036e96..90c68a0e 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityAmbientCreature.java +++ b/src/game/java/net/minecraft/entity/passive/EntityAmbientCreature.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +36,9 @@ public abstract class EntityAmbientCreature extends EntityLiving implements IAni return false; } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ protected boolean interact(EntityPlayer var1) { return false; diff --git a/src/game/java/net/minecraft/entity/passive/EntityAnimal.java b/src/game/java/net/minecraft/entity/passive/EntityAnimal.java index eb5bfc17..61bc19c7 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityAnimal.java +++ b/src/game/java/net/minecraft/entity/passive/EntityAnimal.java @@ -13,22 +13,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,18 +45,143 @@ public abstract class EntityAnimal extends EntityAgeable implements IAnimals { super(worldIn); } - protected void updateAITasks() { - if (this.getGrowingAge() != 0) { + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { this.inLove = 0; + return super.attackEntityFrom(damagesource, f); } - - super.updateAITasks(); } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Determines if an entity can be despawned, used on idle far away entities + */ + protected boolean canDespawn() { + return false; + } + + /** + * + Returns true if the mob is currently able to mate with the specified mob. + */ + public boolean canMateWith(EntityAnimal otherAnimal) { + return otherAnimal == this ? false + : (otherAnimal.getClass() != this.getClass() ? false : this.isInLove() && otherAnimal.isInLove()); + } + + /** + * + Decreases ItemStack size by one + */ + protected void consumeItemFromStack(EntityPlayer player, ItemStack stack) { + if (!player.capabilities.isCreativeMode) { + --stack.stackSize; + if (stack.stackSize <= 0) { + player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack) null); + } + } + + } + + public float getBlockPathWeight(BlockPos blockpos) { + return this.worldObj.getBlockState(blockpos.down()).getBlock() == Blocks.grass ? 10.0F + : this.worldObj.getLightBrightness(blockpos) - 0.5F; + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.getEntityBoundingBox().minY); + int k = MathHelper.floor_double(this.posZ); + BlockPos blockpos = new BlockPos(i, j, k); + return this.worldObj.getBlockState(blockpos.down()).getBlock() == this.spawnableBlock + && this.worldObj.getLight(blockpos) > 8 && super.getCanSpawnHere(); + } + + /** + * + Get the experience points the entity currently has. + */ + protected int getExperiencePoints(EntityPlayer var1) { + return 1 + this.worldObj.rand.nextInt(3); + } + + public EntityPlayer getPlayerInLove() { + return this.playerInLove; + } + + /** + * + Get number of ticks, at least during which the living entity will be + * silent. + */ + public int getTalkInterval() { + return 120; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 18) { + for (int i = 0; i < 7; ++i) { + double d0 = this.rand.nextGaussian() * 0.02D; + double d1 = this.rand.nextGaussian() * 0.02D; + double d2 = this.rand.nextGaussian() * 0.02D; + this.worldObj.spawnParticle(EnumParticleTypes.HEART, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, + this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), + this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, + d2, new int[0]); + } + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + public boolean interact(EntityPlayer entityplayer) { + ItemStack itemstack = entityplayer.inventory.getCurrentItem(); + if (itemstack != null) { + if (this.isBreedingItem(itemstack) && this.getGrowingAge() == 0 && this.inLove <= 0) { + this.consumeItemFromStack(entityplayer, itemstack); + this.setInLove(entityplayer); + return true; + } + + if (this.isChild() && this.isBreedingItem(itemstack)) { + this.consumeItemFromStack(entityplayer, itemstack); + this.func_175501_a((int) ((float) (-this.getGrowingAge() / 20) * 0.1F), true); + return true; + } + } + + return super.interact(entityplayer); + } + + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) + */ + public boolean isBreedingItem(ItemStack stack) { + return stack == null ? false : stack.getItem() == Items.wheat; + } + + /** + * + Returns if the entity is currently in 'love mode'. + */ + public boolean isInLove() { + return this.inLove > 0; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); @@ -77,120 +205,16 @@ public abstract class EntityAnimal extends EntityAgeable implements IAnimals { } - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - this.inLove = 0; - return super.attackEntityFrom(damagesource, f); - } - } - - public float getBlockPathWeight(BlockPos blockpos) { - return this.worldObj.getBlockState(blockpos.down()).getBlock() == Blocks.grass ? 10.0F - : this.worldObj.getLightBrightness(blockpos) - 0.5F; - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("InLove", this.inLove); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); this.inLove = nbttagcompound.getInteger("InLove"); } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.getEntityBoundingBox().minY); - int k = MathHelper.floor_double(this.posZ); - BlockPos blockpos = new BlockPos(i, j, k); - return this.worldObj.getBlockState(blockpos.down()).getBlock() == this.spawnableBlock - && this.worldObj.getLight(blockpos) > 8 && super.getCanSpawnHere(); - } - - /**+ - * Get number of ticks, at least during which the living entity - * will be silent. - */ - public int getTalkInterval() { - return 120; - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return false; - } - - /**+ - * Get the experience points the entity currently has. - */ - protected int getExperiencePoints(EntityPlayer var1) { - return 1 + this.worldObj.rand.nextInt(3); - } - - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) - */ - public boolean isBreedingItem(ItemStack stack) { - return stack == null ? false : stack.getItem() == Items.wheat; - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. - */ - public boolean interact(EntityPlayer entityplayer) { - ItemStack itemstack = entityplayer.inventory.getCurrentItem(); - if (itemstack != null) { - if (this.isBreedingItem(itemstack) && this.getGrowingAge() == 0 && this.inLove <= 0) { - this.consumeItemFromStack(entityplayer, itemstack); - this.setInLove(entityplayer); - return true; - } - - if (this.isChild() && this.isBreedingItem(itemstack)) { - this.consumeItemFromStack(entityplayer, itemstack); - this.func_175501_a((int) ((float) (-this.getGrowingAge() / 20) * 0.1F), true); - return true; - } - } - - return super.interact(entityplayer); - } - - /**+ - * Decreases ItemStack size by one - */ - protected void consumeItemFromStack(EntityPlayer player, ItemStack stack) { - if (!player.capabilities.isCreativeMode) { - --stack.stackSize; - if (stack.stackSize <= 0) { - player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack) null); - } - } - + public void resetInLove() { + this.inLove = 0; } public void setInLove(EntityPlayer player) { @@ -199,45 +223,19 @@ public abstract class EntityAnimal extends EntityAgeable implements IAnimals { this.worldObj.setEntityState(this, (byte) 18); } - public EntityPlayer getPlayerInLove() { - return this.playerInLove; - } - - /**+ - * Returns if the entity is currently in 'love mode'. - */ - public boolean isInLove() { - return this.inLove > 0; - } - - public void resetInLove() { - this.inLove = 0; - } - - /**+ - * Returns true if the mob is currently able to mate with the - * specified mob. - */ - public boolean canMateWith(EntityAnimal otherAnimal) { - return otherAnimal == this ? false - : (otherAnimal.getClass() != this.getClass() ? false : this.isInLove() && otherAnimal.isInLove()); - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 18) { - for (int i = 0; i < 7; ++i) { - double d0 = this.rand.nextGaussian() * 0.02D; - double d1 = this.rand.nextGaussian() * 0.02D; - double d2 = this.rand.nextGaussian() * 0.02D; - this.worldObj.spawnParticle(EnumParticleTypes.HEART, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, - this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), - this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, - d2, new int[0]); - } - } else { - super.handleStatusUpdate(b0); + protected void updateAITasks() { + if (this.getGrowingAge() != 0) { + this.inLove = 0; } + super.updateAITasks(); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("InLove", this.inLove); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityBat.java b/src/game/java/net/minecraft/entity/passive/EntityBat.java index b7fedd12..473d1d3c 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityBat.java +++ b/src/game/java/net/minecraft/entity/passive/EntityBat.java @@ -1,6 +1,7 @@ package net.minecraft.entity.passive; import java.util.Calendar; + import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.SharedMonsterAttributes; @@ -11,22 +12,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,81 +44,135 @@ public class EntityBat extends EntityAmbientCreature { this.setIsBatHanging(true); } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(6.0D); } - /**+ - * Returns the volume for the sounds this mob makes. + /** + * + Called when the entity is attacked. */ - protected float getSoundVolume() { - return 0.1F; + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + if (!this.worldObj.isRemote && this.getIsBatHanging()) { + this.setIsBatHanging(false); + } + + return super.attackEntityFrom(damagesource, f); + } } - /**+ - * Gets the pitch of living sounds in living entities. - */ - protected float getSoundPitch() { - return super.getSoundPitch() * 0.95F; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return this.getIsBatHanging() && this.rand.nextInt(4) != 0 ? null : "mob.bat.idle"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.bat.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.bat.death"; - } - - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. */ public boolean canBePushed() { return false; } + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + protected void collideWithEntity(Entity var1) { } protected void collideWithNearbyEntities() { } - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(6.0D); + /** + * + Return whether this entity should NOT trigger a pressure plate or a + * tripwire. + */ + public boolean doesEntityNotTriggerPressurePlate() { + return true; + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + public void fall(float var1, float var2) { + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + BlockPos blockpos = new BlockPos(this.posX, this.getEntityBoundingBox().minY, this.posZ); + if (blockpos.getY() >= this.worldObj.func_181545_F()) { + return false; + } else { + int i = this.worldObj.getLightFromNeighbors(blockpos); + byte b0 = 4; + if (this.isDateAroundHalloween(this.worldObj.getCurrentDate())) { + b0 = 7; + } else if (this.rand.nextBoolean()) { + return false; + } + + return i > this.rand.nextInt(b0) ? false : super.getCanSpawnHere(); + } + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.bat.death"; + } + + public float getEyeHeight() { + return this.height / 2.0F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.bat.hurt"; } public boolean getIsBatHanging() { return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; } - public void setIsBatHanging(boolean isHanging) { - byte b0 = this.dataWatcher.getWatchableObjectByte(16); - if (isHanging) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1))); - } else { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2))); - } - + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return this.getIsBatHanging() && this.rand.nextInt(4) != 0 ? null : "mob.bat.idle"; } - /**+ - * Called to update the entity's position/logic. + /** + * + Gets the pitch of living sounds in living entities. + */ + protected float getSoundPitch() { + return super.getSoundPitch() * 0.95F; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.1F; + } + + private boolean isDateAroundHalloween(Calendar parCalendar) { + return parCalendar.get(2) + 1 == 10 && parCalendar.get(5) >= 20 + || parCalendar.get(2) + 1 == 11 && parCalendar.get(5) <= 3; + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -127,6 +185,24 @@ public class EntityBat extends EntityAmbientCreature { } + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.dataWatcher.updateObject(16, Byte.valueOf(nbttagcompound.getByte("BatFlags"))); + } + + public void setIsBatHanging(boolean isHanging) { + byte b0 = this.dataWatcher.getWatchableObjectByte(16); + if (isHanging) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1))); + } else { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2))); + } + + } + protected void updateAITasks() { super.updateAITasks(); BlockPos blockpos = new BlockPos(this); @@ -177,89 +253,14 @@ public class EntityBat extends EntityAmbientCreature { } - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - - public void fall(float var1, float var2) { - } - protected void updateFallState(double var1, boolean var3, Block var4, BlockPos var5) { } - /**+ - * Return whether this entity should NOT trigger a pressure - * plate or a tripwire. - */ - public boolean doesEntityNotTriggerPressurePlate() { - return true; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - if (!this.worldObj.isRemote && this.getIsBatHanging()) { - this.setIsBatHanging(false); - } - - return super.attackEntityFrom(damagesource, f); - } - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.dataWatcher.updateObject(16, Byte.valueOf(nbttagcompound.getByte("BatFlags"))); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); nbttagcompound.setByte("BatFlags", this.dataWatcher.getWatchableObjectByte(16)); } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - BlockPos blockpos = new BlockPos(this.posX, this.getEntityBoundingBox().minY, this.posZ); - if (blockpos.getY() >= this.worldObj.func_181545_F()) { - return false; - } else { - int i = this.worldObj.getLightFromNeighbors(blockpos); - byte b0 = 4; - if (this.isDateAroundHalloween(this.worldObj.getCurrentDate())) { - b0 = 7; - } else if (this.rand.nextBoolean()) { - return false; - } - - return i > this.rand.nextInt(b0) ? false : super.getCanSpawnHere(); - } - } - - private boolean isDateAroundHalloween(Calendar parCalendar) { - return parCalendar.get(2) + 1 == 10 && parCalendar.get(5) >= 20 - || parCalendar.get(2) + 1 == 11 && parCalendar.get(5) <= 3; - } - - public float getEyeHeight() { - return this.height / 2.0F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityChicken.java b/src/game/java/net/minecraft/entity/passive/EntityChicken.java index 65536544..6700866a 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityChicken.java +++ b/src/game/java/net/minecraft/entity/passive/EntityChicken.java @@ -21,22 +21,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -64,20 +67,99 @@ public class EntityChicken extends EntityAnimal { this.tasks.addTask(7, new EntityAILookIdle(this)); } - public float getEyeHeight() { - return this.height; - } - protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(4.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Determines if an entity can be despawned, used on idle far away entities + */ + protected boolean canDespawn() { + return this.isChickenJockey() && this.riddenByEntity == null; + } + + public EntityChicken createChild(EntityAgeable var1) { + return new EntityChicken(this.worldObj); + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + int j = this.rand.nextInt(3) + this.rand.nextInt(1 + i); + + for (int k = 0; k < j; ++k) { + this.dropItem(Items.feather, 1); + } + + if (this.isBurning()) { + this.dropItem(Items.cooked_chicken, 1); + } else { + this.dropItem(Items.chicken, 1); + } + + } + + public void fall(float var1, float var2) { + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.chicken.hurt"; + } + + protected Item getDropItem() { + return Items.feather; + } + + /** + * + Get the experience points the entity currently has. + */ + protected int getExperiencePoints(EntityPlayer entityplayer) { + return this.isChickenJockey() ? 10 : super.getExperiencePoints(entityplayer); + } + + public float getEyeHeight() { + return this.height; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.chicken.hurt"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.chicken.say"; + } + + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) + */ + public boolean isBreedingItem(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == Items.wheat_seeds; + } + + /** + * + Determines if this chicken is a jokey with a zombie riding it. + */ + public boolean isChickenJockey() { + return this.chickenJockey; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); @@ -103,72 +185,12 @@ public class EntityChicken extends EntityAnimal { } - public void fall(float var1, float var2) { - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.chicken.say"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.chicken.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.chicken.hurt"; - } - protected void playStepSound(BlockPos var1, Block var2) { this.playSound("mob.chicken.step", 0.15F, 1.0F); } - protected Item getDropItem() { - return Items.feather; - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - int j = this.rand.nextInt(3) + this.rand.nextInt(1 + i); - - for (int k = 0; k < j; ++k) { - this.dropItem(Items.feather, 1); - } - - if (this.isBurning()) { - this.dropItem(Items.cooked_chicken, 1); - } else { - this.dropItem(Items.chicken, 1); - } - - } - - public EntityChicken createChild(EntityAgeable var1) { - return new EntityChicken(this.worldObj); - } - - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) - */ - public boolean isBreedingItem(ItemStack itemstack) { - return itemstack != null && itemstack.getItem() == Items.wheat_seeds; - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -179,29 +201,11 @@ public class EntityChicken extends EntityAnimal { } - /**+ - * Get the experience points the entity currently has. + /** + * + Sets whether this chicken is a jockey or not. */ - protected int getExperiencePoints(EntityPlayer entityplayer) { - return this.isChickenJockey() ? 10 : super.getExperiencePoints(entityplayer); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("IsChickenJockey", this.chickenJockey); - nbttagcompound.setInteger("EggLayTime", this.timeUntilNextEgg); - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return this.isChickenJockey() && this.riddenByEntity == null; + public void setChickenJockey(boolean jockey) { + this.chickenJockey = jockey; } public void updateRiderPosition() { @@ -219,18 +223,12 @@ public class EntityChicken extends EntityAnimal { } - /**+ - * Determines if this chicken is a jokey with a zombie riding - * it. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean isChickenJockey() { - return this.chickenJockey; - } - - /**+ - * Sets whether this chicken is a jockey or not. - */ - public void setChickenJockey(boolean jockey) { - this.chickenJockey = jockey; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("IsChickenJockey", this.chickenJockey); + nbttagcompound.setInteger("EggLayTime", this.timeUntilNextEgg); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityCow.java b/src/game/java/net/minecraft/entity/passive/EntityCow.java index 9b726597..a4444849 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityCow.java +++ b/src/game/java/net/minecraft/entity/passive/EntityCow.java @@ -19,22 +19,25 @@ import net.minecraft.pathfinding.PathNavigateGround; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,44 +63,12 @@ public class EntityCow extends EntityAnimal { this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); } - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.cow.say"; + public EntityCow createChild(EntityAgeable var1) { + return new EntityCow(this.worldObj); } - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.cow.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.cow.hurt"; - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.cow.step", 0.15F, 1.0F); - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 0.4F; - } - - protected Item getDropItem() { - return Items.leather; - } - - /**+ - * Drop 0-2 items of this living's type + /** + * + Drop 0-2 items of this living's type */ protected void dropFewItems(boolean var1, int i) { int j = this.rand.nextInt(3) + this.rand.nextInt(1 + i); @@ -118,9 +89,45 @@ public class EntityCow extends EntityAnimal { } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.cow.hurt"; + } + + protected Item getDropItem() { + return Items.leather; + } + + public float getEyeHeight() { + return this.height; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.cow.hurt"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.cow.say"; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.4F; + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -139,11 +146,7 @@ public class EntityCow extends EntityAnimal { } } - public EntityCow createChild(EntityAgeable var1) { - return new EntityCow(this.worldObj); - } - - public float getEyeHeight() { - return this.height; + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.cow.step", 0.15F, 1.0F); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityHorse.java b/src/game/java/net/minecraft/entity/passive/EntityHorse.java index 775bc450..9baeacf8 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityHorse.java +++ b/src/game/java/net/minecraft/entity/passive/EntityHorse.java @@ -43,27 +43,40 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityHorse extends EntityAnimal implements IInvBasic { + public static class GroupData implements IEntityLivingData { + public int horseType; + public int horseVariant; + + public GroupData(int type, int variant) { + this.horseType = type; + this.horseVariant = variant; + } + } + private static final Predicate horseBreedingSelector = new Predicate() { public boolean apply(Entity entity) { return entity instanceof EntityHorse && ((EntityHorse) entity).isBreeding(); @@ -87,6 +100,15 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { "textures/entity/horse/horse_markings_whitedots.png", "textures/entity/horse/horse_markings_blackdots.png" }; private static final String[] HORSE_MARKING_TEXTURES_ABBR = new String[] { "", "wo_", "wmo", "wdo", "bdo" }; + + /** + * + Returns true if given item is horse armor + */ + public static boolean isArmorItem(Item parItem) { + return parItem == Items.iron_horse_armor || parItem == Items.golden_horse_armor + || parItem == Items.diamond_horse_armor; + } + private int eatingHaystackCounter; private int openMouthCounter; private int jumpRearingCounter; @@ -106,7 +128,9 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { private float prevMouthOpenness; private int gallopTime; private String texturePrefix; + private String[] horseTexturesArray = new String[3]; + private boolean field_175508_bO = false; public EntityHorse(World worldIn) { @@ -126,229 +150,19 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { this.initHorseChest(); } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Integer.valueOf(0)); - this.dataWatcher.addObject(19, Byte.valueOf((byte) 0)); - this.dataWatcher.addObject(20, Integer.valueOf(0)); - this.dataWatcher.addObject(21, String.valueOf("")); - this.dataWatcher.addObject(22, Integer.valueOf(0)); - } - - public void setHorseType(int type) { - this.dataWatcher.updateObject(19, Byte.valueOf((byte) type)); - this.resetTexturePrefix(); - } - - /**+ - * Returns the horse type. 0 = Normal, 1 = Donkey, 2 = Mule, 3 = - * Undead Horse, 4 = Skeleton Horse - */ - public int getHorseType() { - return this.dataWatcher.getWatchableObjectByte(19); - } - - public void setHorseVariant(int variant) { - this.dataWatcher.updateObject(20, Integer.valueOf(variant)); - this.resetTexturePrefix(); - } - - public int getHorseVariant() { - return this.dataWatcher.getWatchableObjectInt(20); - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return getNameImpl(false); - } - - public String getNameProfanityFilter() { - return getNameImpl(true); - } - - private String getNameImpl(boolean filter) { - if (this.hasCustomName()) { - return filter ? this.getCustomNameTagProfanityFilter() : this.getCustomNameTag(); - } else { - int i = this.getHorseType(); - switch (i) { - case 0: - default: - return StatCollector.translateToLocal("entity.horse.name"); - case 1: - return StatCollector.translateToLocal("entity.donkey.name"); - case 2: - return StatCollector.translateToLocal("entity.mule.name"); - case 3: - return StatCollector.translateToLocal("entity.zombiehorse.name"); - case 4: - return StatCollector.translateToLocal("entity.skeletonhorse.name"); - } - } - } - - private boolean getHorseWatchableBoolean(int parInt1) { - return (this.dataWatcher.getWatchableObjectInt(16) & parInt1) != 0; - } - - private void setHorseWatchableBoolean(int parInt1, boolean parFlag) { - int i = this.dataWatcher.getWatchableObjectInt(16); - if (parFlag) { - this.dataWatcher.updateObject(16, Integer.valueOf(i | parInt1)); - } else { - this.dataWatcher.updateObject(16, Integer.valueOf(i & ~parInt1)); - } - - } - - public boolean isAdultHorse() { - return !this.isChild(); - } - - public boolean isTame() { - return this.getHorseWatchableBoolean(2); - } - - public boolean func_110253_bW() { - return this.isAdultHorse(); - } - - /**+ - * Gets the horse's owner - */ - public String getOwnerId() { - return this.dataWatcher.getWatchableObjectString(21); - } - - public void setOwnerId(String id) { - this.dataWatcher.updateObject(21, id); - } - - public float getHorseSize() { - return 0.5F; - } - - /**+ - * "Sets the scale for an ageable entity according to the - * boolean parameter, which says if it's a child." - */ - public void setScaleForAge(boolean flag) { - if (flag) { - this.setScale(this.getHorseSize()); - } else { - this.setScale(1.0F); - } - - } - - public boolean isHorseJumping() { - return this.horseJumping; - } - - public void setHorseTamed(boolean tamed) { - this.setHorseWatchableBoolean(2, tamed); - } - - public void setHorseJumping(boolean jumping) { - this.horseJumping = jumping; - } - public boolean allowLeashing() { return !this.isUndead() && super.allowLeashing(); } - protected void func_142017_o(float f) { - if (f > 6.0F && this.isEatingHaystack()) { - this.setEatingHaystack(false); - } - + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getAttributeMap().registerAttribute(horseJumpStrength); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(53.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.22499999403953552D); } - public boolean isChested() { - return this.getHorseWatchableBoolean(8); - } - - /**+ - * Returns type of armor from DataWatcher (0 = iron, 1 = gold, 2 - * = diamond) - */ - public int getHorseArmorIndexSynced() { - return this.dataWatcher.getWatchableObjectInt(22); - } - - /**+ - * 0 = iron, 1 = gold, 2 = diamond - */ - private int getHorseArmorIndex(ItemStack itemStackIn) { - if (itemStackIn == null) { - return 0; - } else { - Item item = itemStackIn.getItem(); - return item == Items.iron_horse_armor ? 1 - : (item == Items.golden_horse_armor ? 2 : (item == Items.diamond_horse_armor ? 3 : 0)); - } - } - - public boolean isEatingHaystack() { - return this.getHorseWatchableBoolean(32); - } - - public boolean isRearing() { - return this.getHorseWatchableBoolean(64); - } - - public boolean isBreeding() { - return this.getHorseWatchableBoolean(16); - } - - public boolean getHasReproduced() { - return this.hasReproduced; - } - - /**+ - * Set horse armor stack (for example: new - * ItemStack(Items.iron_horse_armor)) - */ - public void setHorseArmorStack(ItemStack itemStackIn) { - this.dataWatcher.updateObject(22, Integer.valueOf(this.getHorseArmorIndex(itemStackIn))); - this.resetTexturePrefix(); - } - - public void setBreeding(boolean breeding) { - this.setHorseWatchableBoolean(16, breeding); - } - - public void setChested(boolean chested) { - this.setHorseWatchableBoolean(8, chested); - } - - public void setHasReproduced(boolean hasReproducedIn) { - this.hasReproduced = hasReproducedIn; - } - - public void setHorseSaddled(boolean saddled) { - this.setHorseWatchableBoolean(4, saddled); - } - - public int getTemper() { - return this.temper; - } - - public void setTemper(int temperIn) { - this.temper = temperIn; - } - - public int increaseTemper(int parInt1) { - int i = MathHelper.clamp_int(this.getTemper() + parInt1, 0, this.getMaxTemper()); - this.setTemper(i); - return i; - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { Entity entity = damagesource.getEntity(); @@ -356,27 +170,111 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { : super.attackEntityFrom(damagesource, f); } - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - return armorValues[this.getHorseArmorIndexSynced()]; - } - - /**+ - * Returns true if this entity should push and be pushed by - * other entities when colliding. + /** + * + Returns true if this entity should push and be pushed by other entities + * when colliding. */ public boolean canBePushed() { return this.riddenByEntity == null; } - public boolean prepareChunkForSpawn() { - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.posZ); - this.worldObj.getBiomeGenForCoords(new BlockPos(i, 0, j)); - return true; + /** + * + Return true if the horse entity can carry a chest. + */ + public boolean canCarryChest() { + int i = this.getHorseType(); + return i == 2 || i == 1; + } + + /** + * + Return true if the horse entity ready to mate. (no rider, not riding, tame, + * adult, not steril...) + */ + private boolean canMate() { + return this.riddenByEntity == null && this.ridingEntity == null && this.isTame() && this.isAdultHorse() + && !this.isSterile() && this.getHealth() >= this.getMaxHealth() && this.isInLove(); + } + + /** + * + Returns true if the mob is currently able to mate with the specified mob. + */ + public boolean canMateWith(EntityAnimal entityanimal) { + if (entityanimal == this) { + return false; + } else if (entityanimal.getClass() != this.getClass()) { + return false; + } else { + EntityHorse entityhorse = (EntityHorse) entityanimal; + if (this.canMate() && entityhorse.canMate()) { + int i = this.getHorseType(); + int j = entityhorse.getHorseType(); + return i == j || i == 0 && j == 1 || i == 1 && j == 0; + } else { + return false; + } + } + } + + /** + * + Return true if the horse entity can wear an armor + */ + public boolean canWearArmor() { + return this.getHorseType() == 0; + } + + public EntityAgeable createChild(EntityAgeable entityageable) { + EntityHorse entityhorse = (EntityHorse) entityageable; + EntityHorse entityhorse1 = new EntityHorse(this.worldObj); + int i = this.getHorseType(); + int j = entityhorse.getHorseType(); + int k = 0; + if (i == j) { + k = i; + } else if (i == 0 && j == 1 || i == 1 && j == 0) { + k = 2; + } + + if (k == 0) { + int i1 = this.rand.nextInt(9); + int l; + if (i1 < 4) { + l = this.getHorseVariant() & 255; + } else if (i1 < 8) { + l = entityhorse.getHorseVariant() & 255; + } else { + l = this.rand.nextInt(7); + } + + int j1 = this.rand.nextInt(5); + if (j1 < 2) { + l = l | this.getHorseVariant() & '\uff00'; + } else if (j1 < 4) { + l = l | entityhorse.getHorseVariant() & '\uff00'; + } else { + l = l | this.rand.nextInt(5) << 8 & '\uff00'; + } + + entityhorse1.setHorseVariant(l); + } + + entityhorse1.setHorseType(k); + double d1 = this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue() + + entityageable.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue() + + (double) this.getModifiedMaxHealth(); + entityhorse1.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(d1 / 3.0D); + double d2 = this.getEntityAttribute(horseJumpStrength).getBaseValue() + + entityageable.getEntityAttribute(horseJumpStrength).getBaseValue() + this.getModifiedJumpStrength(); + entityhorse1.getEntityAttribute(horseJumpStrength).setBaseValue(d2 / 3.0D); + double d0 = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getBaseValue() + + entityageable.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getBaseValue() + + this.getModifiedMovementSpeed(); + entityhorse1.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(d0 / 3.0D); + return entityhorse1; + } + + public void dropChestItems() { + this.dropItemsInChest(this, this.horseChest); + this.dropChests(); } public void dropChests() { @@ -386,13 +284,25 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } } - private void func_110266_cB() { - this.openHorseMouth(); - if (!this.isSilent()) { - this.worldObj.playSoundAtEntity(this, "eating", 1.0F, - 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F); - } + private void dropItemsInChest(Entity entityIn, AnimalChest animalChestIn) { + if (animalChestIn != null && !this.worldObj.isRemote) { + for (int i = 0; i < animalChestIn.getSizeInventory(); ++i) { + ItemStack itemstack = animalChestIn.getStackInSlot(i); + if (itemstack != null) { + this.entityDropItem(itemstack, 0.0F); + } + } + } + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Integer.valueOf(0)); + this.dataWatcher.addObject(19, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(20, Integer.valueOf(0)); + this.dataWatcher.addObject(21, String.valueOf("")); + this.dataWatcher.addObject(22, Integer.valueOf(0)); } public void fall(float f, float f1) { @@ -419,14 +329,324 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } } - /**+ - * Returns number of slots depending horse type + private void func_110210_cH() { + this.field_110278_bp = 1; + } + + public boolean func_110239_cn() { + return this.getHorseType() == 0 || this.getHorseArmorIndexSynced() > 0; + } + + public boolean func_110253_bW() { + return this.isAdultHorse(); + } + + private void func_110266_cB() { + this.openHorseMouth(); + if (!this.isSilent()) { + this.worldObj.playSoundAtEntity(this, "eating", 1.0F, + 1.0F + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F); + } + + } + + protected void func_142017_o(float f) { + if (f > 6.0F && this.isEatingHaystack()) { + this.setEatingHaystack(false); + } + + } + + public boolean func_175507_cI() { + return this.field_175508_bO; + } + + protected String getAngrySoundName() { + this.openHorseMouth(); + this.makeHorseRear(); + int i = this.getHorseType(); + return i != 3 && i != 4 ? (i != 1 && i != 2 ? "mob.horse.angry" : "mob.horse.donkey.angry") : null; + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + this.prepareChunkForSpawn(); + return super.getCanSpawnHere(); + } + + /** + * + Returns number of slots depending horse type */ private int getChestSize() { int i = this.getHorseType(); return !this.isChested() || i != 1 && i != 2 ? 2 : 17; } + protected EntityHorse getClosestHorse(Entity entityIn, double distance) { + double d0 = Double.MAX_VALUE; + Entity entity = null; + + List lst = this.worldObj.getEntitiesInAABBexcluding(entityIn, + entityIn.getEntityBoundingBox().addCoord(distance, distance, distance), horseBreedingSelector); + for (int i = 0, l = lst.size(); i < l; ++i) { + Entity entity1 = lst.get(i); + double d1 = entity1.getDistanceSq(entityIn.posX, entityIn.posY, entityIn.posZ); + if (d1 < d0) { + entity = entity1; + d0 = d1; + } + } + + return (EntityHorse) entity; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + this.openHorseMouth(); + int i = this.getHorseType(); + return i == 3 ? "mob.horse.zombie.death" + : (i == 4 ? "mob.horse.skeleton.death" + : (i != 1 && i != 2 ? "mob.horse.death" : "mob.horse.donkey.death")); + } + + protected Item getDropItem() { + boolean flag = this.rand.nextInt(4) == 0; + int i = this.getHorseType(); + return i == 4 ? Items.bone : (i == 3 ? (flag ? null : Items.rotten_flesh) : Items.leather); + } + + public float getEyeHeight() { + return this.height; + } + + public float getGrassEatingAmount(float parFloat1) { + return this.prevHeadLean + (this.headLean - this.prevHeadLean) * parFloat1; + } + + public boolean getHasReproduced() { + return this.hasReproduced; + } + + /** + * + 0 = iron, 1 = gold, 2 = diamond + */ + private int getHorseArmorIndex(ItemStack itemStackIn) { + if (itemStackIn == null) { + return 0; + } else { + Item item = itemStackIn.getItem(); + return item == Items.iron_horse_armor ? 1 + : (item == Items.golden_horse_armor ? 2 : (item == Items.diamond_horse_armor ? 3 : 0)); + } + } + + /** + * + Returns type of armor from DataWatcher (0 = iron, 1 = gold, 2 = diamond) + */ + public int getHorseArmorIndexSynced() { + return this.dataWatcher.getWatchableObjectInt(22); + } + + public double getHorseJumpStrength() { + return this.getEntityAttribute(horseJumpStrength).getAttributeValue(); + } + + public float getHorseSize() { + return 0.5F; + } + + public String getHorseTexture() { + if (this.texturePrefix == null) { + this.setHorseTexturePaths(); + } + + return this.texturePrefix; + } + + /** + * + Returns the horse type. 0 = Normal, 1 = Donkey, 2 = Mule, 3 = Undead Horse, + * 4 = Skeleton Horse + */ + public int getHorseType() { + return this.dataWatcher.getWatchableObjectByte(19); + } + + public int getHorseVariant() { + return this.dataWatcher.getWatchableObjectInt(20); + } + + private boolean getHorseWatchableBoolean(int parInt1) { + return (this.dataWatcher.getWatchableObjectInt(16) & parInt1) != 0; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + this.openHorseMouth(); + if (this.rand.nextInt(3) == 0) { + this.makeHorseRear(); + } + + int i = this.getHorseType(); + return i == 3 ? "mob.horse.zombie.hit" + : (i == 4 ? "mob.horse.skeleton.hit" : (i != 1 && i != 2 ? "mob.horse.hit" : "mob.horse.donkey.hit")); + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + this.openHorseMouth(); + if (this.rand.nextInt(10) == 0 && !this.isMovementBlocked()) { + this.makeHorseRear(); + } + + int i = this.getHorseType(); + return i == 3 ? "mob.horse.zombie.idle" + : (i == 4 ? "mob.horse.skeleton.idle" + : (i != 1 && i != 2 ? "mob.horse.idle" : "mob.horse.donkey.idle")); + } + + /** + * + Will return how many at most can spawn in a chunk at once. + */ + public int getMaxSpawnedInChunk() { + return 6; + } + + public int getMaxTemper() { + return 100; + } + + /** + * + Returns randomized jump strength + */ + private double getModifiedJumpStrength() { + return 0.4000000059604645D + this.rand.nextDouble() * 0.2D + this.rand.nextDouble() * 0.2D + + this.rand.nextDouble() * 0.2D; + } + + /** + * + Returns randomized max health + */ + private float getModifiedMaxHealth() { + return 15.0F + (float) this.rand.nextInt(8) + (float) this.rand.nextInt(9); + } + + /** + * + Returns randomized movement speed + */ + private double getModifiedMovementSpeed() { + return (0.44999998807907104D + this.rand.nextDouble() * 0.3D + this.rand.nextDouble() * 0.3D + + this.rand.nextDouble() * 0.3D) * 0.25D; + } + + public float getMouthOpennessAngle(float parFloat1) { + return this.prevMouthOpenness + (this.mouthOpenness - this.prevMouthOpenness) * parFloat1; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return getNameImpl(false); + } + + private String getNameImpl(boolean filter) { + if (this.hasCustomName()) { + return filter ? this.getCustomNameTagProfanityFilter() : this.getCustomNameTag(); + } else { + int i = this.getHorseType(); + switch (i) { + case 0: + default: + return StatCollector.translateToLocal("entity.horse.name"); + case 1: + return StatCollector.translateToLocal("entity.donkey.name"); + case 2: + return StatCollector.translateToLocal("entity.mule.name"); + case 3: + return StatCollector.translateToLocal("entity.zombiehorse.name"); + case 4: + return StatCollector.translateToLocal("entity.skeletonhorse.name"); + } + } + } + + public String getNameProfanityFilter() { + return getNameImpl(true); + } + + /** + * + Gets the horse's owner + */ + public String getOwnerId() { + return this.dataWatcher.getWatchableObjectString(21); + } + + public float getRearingAmount(float parFloat1) { + return this.prevRearingAmount + (this.rearingAmount - this.prevRearingAmount) * parFloat1; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.8F; + } + + /** + * + Get number of ticks, at least during which the living entity will be + * silent. + */ + public int getTalkInterval() { + return 400; + } + + public int getTemper() { + return this.temper; + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue + */ + public int getTotalArmorValue() { + return armorValues[this.getHorseArmorIndexSynced()]; + } + + public String[] getVariantTexturePaths() { + if (this.texturePrefix == null) { + this.setHorseTexturePaths(); + } + + return this.horseTexturesArray; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 7) { + this.spawnHorseParticles(true); + } else if (b0 == 6) { + this.spawnHorseParticles(false); + } else { + super.handleStatusUpdate(b0); + } + + } + + public int increaseTemper(int parInt1) { + int i = MathHelper.clamp_int(this.getTemper() + parInt1, 0, this.getMaxTemper()); + this.setTemper(i); + return i; + } + private void initHorseChest() { AnimalChest animalchest = this.horseChest; this.horseChest = new AnimalChest("HorseChest", this.getChestSize()); @@ -447,272 +667,9 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { this.updateHorseSlots(); } - /**+ - * Updates the items in the saddle and armor slots of the - * horse's inventory. - */ - private void updateHorseSlots() { - if (!this.worldObj.isRemote) { - this.setHorseSaddled(this.horseChest.getStackInSlot(0) != null); - if (this.canWearArmor()) { - this.setHorseArmorStack(this.horseChest.getStackInSlot(1)); - } - } - - } - - /**+ - * Called by InventoryBasic.onInventoryChanged() on a array that - * is never filled. - */ - public void onInventoryChanged(InventoryBasic var1) { - int i = this.getHorseArmorIndexSynced(); - boolean flag = this.isHorseSaddled(); - this.updateHorseSlots(); - if (this.ticksExisted > 20) { - if (i == 0 && i != this.getHorseArmorIndexSynced()) { - this.playSound("mob.horse.armor", 0.5F, 1.0F); - } else if (i != this.getHorseArmorIndexSynced()) { - this.playSound("mob.horse.armor", 0.5F, 1.0F); - } - - if (!flag && this.isHorseSaddled()) { - this.playSound("mob.horse.leather", 0.5F, 1.0F); - } - } - - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - this.prepareChunkForSpawn(); - return super.getCanSpawnHere(); - } - - protected EntityHorse getClosestHorse(Entity entityIn, double distance) { - double d0 = Double.MAX_VALUE; - Entity entity = null; - - List lst = this.worldObj.getEntitiesInAABBexcluding(entityIn, - entityIn.getEntityBoundingBox().addCoord(distance, distance, distance), horseBreedingSelector); - for (int i = 0, l = lst.size(); i < l; ++i) { - Entity entity1 = lst.get(i); - double d1 = entity1.getDistanceSq(entityIn.posX, entityIn.posY, entityIn.posZ); - if (d1 < d0) { - entity = entity1; - d0 = d1; - } - } - - return (EntityHorse) entity; - } - - public double getHorseJumpStrength() { - return this.getEntityAttribute(horseJumpStrength).getAttributeValue(); - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - this.openHorseMouth(); - int i = this.getHorseType(); - return i == 3 ? "mob.horse.zombie.death" - : (i == 4 ? "mob.horse.skeleton.death" - : (i != 1 && i != 2 ? "mob.horse.death" : "mob.horse.donkey.death")); - } - - protected Item getDropItem() { - boolean flag = this.rand.nextInt(4) == 0; - int i = this.getHorseType(); - return i == 4 ? Items.bone : (i == 3 ? (flag ? null : Items.rotten_flesh) : Items.leather); - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - this.openHorseMouth(); - if (this.rand.nextInt(3) == 0) { - this.makeHorseRear(); - } - - int i = this.getHorseType(); - return i == 3 ? "mob.horse.zombie.hit" - : (i == 4 ? "mob.horse.skeleton.hit" : (i != 1 && i != 2 ? "mob.horse.hit" : "mob.horse.donkey.hit")); - } - - public boolean isHorseSaddled() { - return this.getHorseWatchableBoolean(4); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - this.openHorseMouth(); - if (this.rand.nextInt(10) == 0 && !this.isMovementBlocked()) { - this.makeHorseRear(); - } - - int i = this.getHorseType(); - return i == 3 ? "mob.horse.zombie.idle" - : (i == 4 ? "mob.horse.skeleton.idle" - : (i != 1 && i != 2 ? "mob.horse.idle" : "mob.horse.donkey.idle")); - } - - protected String getAngrySoundName() { - this.openHorseMouth(); - this.makeHorseRear(); - int i = this.getHorseType(); - return i != 3 && i != 4 ? (i != 1 && i != 2 ? "mob.horse.angry" : "mob.horse.donkey.angry") : null; - } - - protected void playStepSound(BlockPos blockpos, Block block) { - Block.SoundType block$soundtype = block.stepSound; - if (this.worldObj.getBlockState(blockpos.up()).getBlock() == Blocks.snow_layer) { - block$soundtype = Blocks.snow_layer.stepSound; - } - - if (!block.getMaterial().isLiquid()) { - int i = this.getHorseType(); - if (this.riddenByEntity != null && i != 1 && i != 2) { - ++this.gallopTime; - if (this.gallopTime > 5 && this.gallopTime % 3 == 0) { - this.playSound("mob.horse.gallop", block$soundtype.getVolume() * 0.15F, - block$soundtype.getFrequency()); - if (i == 0 && this.rand.nextInt(10) == 0) { - this.playSound("mob.horse.breathe", block$soundtype.getVolume() * 0.6F, - block$soundtype.getFrequency()); - } - } else if (this.gallopTime <= 5) { - this.playSound("mob.horse.wood", block$soundtype.getVolume() * 0.15F, - block$soundtype.getFrequency()); - } - } else if (block$soundtype == Block.soundTypeWood) { - this.playSound("mob.horse.wood", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency()); - } else { - this.playSound("mob.horse.soft", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency()); - } - } - - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getAttributeMap().registerAttribute(horseJumpStrength); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(53.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.22499999403953552D); - } - - /**+ - * Will return how many at most can spawn in a chunk at once. - */ - public int getMaxSpawnedInChunk() { - return 6; - } - - public int getMaxTemper() { - return 100; - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 0.8F; - } - - /**+ - * Get number of ticks, at least during which the living entity - * will be silent. - */ - public int getTalkInterval() { - return 400; - } - - public boolean func_110239_cn() { - return this.getHorseType() == 0 || this.getHorseArmorIndexSynced() > 0; - } - - private void resetTexturePrefix() { - this.texturePrefix = null; - } - - public boolean func_175507_cI() { - return this.field_175508_bO; - } - - private void setHorseTexturePaths() { - this.texturePrefix = "horse/"; - this.horseTexturesArray[0] = null; - this.horseTexturesArray[1] = null; - this.horseTexturesArray[2] = null; - int i = this.getHorseType(); - int j = this.getHorseVariant(); - if (i == 0) { - int k = j & 255; - int l = (j & '\uff00') >> 8; - if (k >= horseTextures.length) { - this.field_175508_bO = false; - return; - } - - this.horseTexturesArray[0] = horseTextures[k]; - this.texturePrefix = this.texturePrefix + HORSE_TEXTURES_ABBR[k]; - if (l >= horseMarkingTextures.length) { - this.field_175508_bO = false; - return; - } - - this.horseTexturesArray[1] = horseMarkingTextures[l]; - this.texturePrefix = this.texturePrefix + HORSE_MARKING_TEXTURES_ABBR[l]; - } else { - this.horseTexturesArray[0] = ""; - this.texturePrefix = this.texturePrefix + "_" + i + "_"; - } - - int i1 = this.getHorseArmorIndexSynced(); - if (i1 >= horseArmorTextures.length) { - this.field_175508_bO = false; - } else { - this.horseTexturesArray[2] = horseArmorTextures[i1]; - this.texturePrefix = this.texturePrefix + HORSE_ARMOR_TEXTURES_ABBR[i1]; - this.field_175508_bO = true; - } - } - - public String getHorseTexture() { - if (this.texturePrefix == null) { - this.setHorseTexturePaths(); - } - - return this.texturePrefix; - } - - public String[] getVariantTexturePaths() { - if (this.texturePrefix == null) { - this.setHorseTexturePaths(); - } - - return this.horseTexturesArray; - } - - public void openGUI(EntityPlayer playerEntity) { - if (!this.worldObj.isRemote && (this.riddenByEntity == null || this.riddenByEntity == playerEntity) - && this.isTame()) { - this.horseChest.setCustomName(this.getName()); - playerEntity.displayGUIHorse(this, this.horseChest); - } - - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -852,6 +809,94 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } } + public boolean isAdultHorse() { + return !this.isChild(); + } + + public boolean isBreeding() { + return this.getHorseWatchableBoolean(16); + } + + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) + */ + public boolean isBreedingItem(ItemStack var1) { + return false; + } + + public boolean isChested() { + return this.getHorseWatchableBoolean(8); + } + + public boolean isEatingHaystack() { + return this.getHorseWatchableBoolean(32); + } + + public boolean isHorseJumping() { + return this.horseJumping; + } + + public boolean isHorseSaddled() { + return this.getHorseWatchableBoolean(4); + } + + /** + * + Dead and sleeping entities cannot move + */ + protected boolean isMovementBlocked() { + return this.riddenByEntity != null && this.isHorseSaddled() ? true + : this.isEatingHaystack() || this.isRearing(); + } + + /** + * + returns true if this entity is by a ladder, false otherwise + */ + public boolean isOnLadder() { + return false; + } + + public boolean isRearing() { + return this.getHorseWatchableBoolean(64); + } + + /** + * + Return true if the horse entity is sterile (Undead || Mule) + */ + public boolean isSterile() { + return this.isUndead() || this.getHorseType() == 2; + } + + public boolean isTame() { + return this.getHorseWatchableBoolean(2); + } + + /** + * + Used to know if the horse can be leashed, if he can mate, or if we can + * interact with him + */ + public boolean isUndead() { + int i = this.getHorseType(); + return i == 3 || i == 4; + } + + private void makeHorseRear() { + if (!this.worldObj.isRemote) { + this.jumpRearingCounter = 1; + this.setRearing(true); + } + + } + + public void makeHorseRearWithSound() { + this.makeHorseRear(); + String s = this.getAngrySoundName(); + if (s != null) { + this.playSound(s, this.getSoundVolume(), this.getSoundPitch()); + } + + } + private void mountTo(EntityPlayer player) { player.rotationYaw = this.rotationYaw; player.rotationPitch = this.rotationPitch; @@ -863,60 +908,79 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } - /**+ - * Return true if the horse entity can wear an armor + /** + * + Moves the entity based on the specified heading. Args: strafe, forward */ - public boolean canWearArmor() { - return this.getHorseType() == 0; + public void moveEntityWithHeading(float f, float f1) { + if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityLivingBase && this.isHorseSaddled()) { + this.prevRotationYaw = this.rotationYaw = this.riddenByEntity.rotationYaw; + this.rotationPitch = this.riddenByEntity.rotationPitch * 0.5F; + this.setRotation(this.rotationYaw, this.rotationPitch); + this.rotationYawHead = this.renderYawOffset = this.rotationYaw; + f = ((EntityLivingBase) this.riddenByEntity).moveStrafing * 0.5F; + f1 = ((EntityLivingBase) this.riddenByEntity).moveForward; + if (f1 <= 0.0F) { + f1 *= 0.25F; + this.gallopTime = 0; + } + + if (this.onGround && this.jumpPower == 0.0F && this.isRearing() && !this.field_110294_bI) { + f = 0.0F; + f1 = 0.0F; + } + + if (this.jumpPower > 0.0F && !this.isHorseJumping() && this.onGround) { + this.motionY = this.getHorseJumpStrength() * (double) this.jumpPower; + if (this.isPotionActive(Potion.jump)) { + this.motionY += (double) ((float) (this.getActivePotionEffect(Potion.jump).getAmplifier() + 1) + * 0.1F); + } + + this.setHorseJumping(true); + this.isAirBorne = true; + if (f1 > 0.0F) { + float f2 = MathHelper.sin(this.rotationYaw * 3.1415927F / 180.0F); + float f3 = MathHelper.cos(this.rotationYaw * 3.1415927F / 180.0F); + this.motionX += (double) (-0.4F * f2 * this.jumpPower); + this.motionZ += (double) (0.4F * f3 * this.jumpPower); + this.playSound("mob.horse.jump", 0.4F, 1.0F); + } + + this.jumpPower = 0.0F; + } + + this.stepHeight = 1.0F; + this.jumpMovementFactor = this.getAIMoveSpeed() * 0.1F; + if (!this.worldObj.isRemote) { + this.setAIMoveSpeed( + (float) this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue()); + super.moveEntityWithHeading(f, f1); + } + + if (this.onGround) { + this.jumpPower = 0.0F; + this.setHorseJumping(false); + } + + this.prevLimbSwingAmount = this.limbSwingAmount; + double d1 = this.posX - this.prevPosX; + double d0 = this.posZ - this.prevPosZ; + float f4 = MathHelper.sqrt_double(d1 * d1 + d0 * d0) * 4.0F; + if (f4 > 1.0F) { + f4 = 1.0F; + } + + this.limbSwingAmount += (f4 - this.limbSwingAmount) * 0.4F; + this.limbSwing += this.limbSwingAmount; + } else { + this.stepHeight = 0.5F; + this.jumpMovementFactor = 0.02F; + super.moveEntityWithHeading(f, f1); + } } - /**+ - * Return true if the horse entity can carry a chest. - */ - public boolean canCarryChest() { - int i = this.getHorseType(); - return i == 2 || i == 1; - } - - /**+ - * Dead and sleeping entities cannot move - */ - protected boolean isMovementBlocked() { - return this.riddenByEntity != null && this.isHorseSaddled() ? true - : this.isEatingHaystack() || this.isRearing(); - } - - /**+ - * Used to know if the horse can be leashed, if he can mate, or - * if we can interact with him - */ - public boolean isUndead() { - int i = this.getHorseType(); - return i == 3 || i == 4; - } - - /**+ - * Return true if the horse entity is sterile (Undead || Mule) - */ - public boolean isSterile() { - return this.isUndead() || this.getHorseType() == 2; - } - - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) - */ - public boolean isBreedingItem(ItemStack var1) { - return false; - } - - private void func_110210_cH() { - this.field_110278_bp = 1; - } - - /**+ - * Called when the mob's health reaches 0. + /** + * + Called when the mob's health reaches 0. */ public void onDeath(DamageSource damagesource) { super.onDeath(damagesource); @@ -926,10 +990,88 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); + int i = 0; + int j = 0; + if (ientitylivingdata instanceof EntityHorse.GroupData) { + i = ((EntityHorse.GroupData) ientitylivingdata).horseType; + j = ((EntityHorse.GroupData) ientitylivingdata).horseVariant & 255 | this.rand.nextInt(5) << 8; + } else { + if (this.rand.nextInt(10) == 0) { + i = 1; + } else { + int k = this.rand.nextInt(7); + int l = this.rand.nextInt(5); + i = 0; + j = k | l << 8; + } + + ientitylivingdata = new EntityHorse.GroupData(i, j); + } + + this.setHorseType(i); + this.setHorseVariant(j); + if (this.rand.nextInt(5) == 0) { + this.setGrowingAge(-24000); + } + + if (i != 4 && i != 3) { + this.getEntityAttribute(SharedMonsterAttributes.maxHealth) + .setBaseValue((double) this.getModifiedMaxHealth()); + if (i == 0) { + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed) + .setBaseValue(this.getModifiedMovementSpeed()); + } else { + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.17499999701976776D); + } + } else { + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(15.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); + } + + if (i != 2 && i != 1) { + this.getEntityAttribute(horseJumpStrength).setBaseValue(this.getModifiedJumpStrength()); + } else { + this.getEntityAttribute(horseJumpStrength).setBaseValue(0.5D); + } + + this.setHealth(this.getMaxHealth()); + return ientitylivingdata; + } + + /** + * + Called by InventoryBasic.onInventoryChanged() on a array that is never + * filled. + */ + public void onInventoryChanged(InventoryBasic var1) { + int i = this.getHorseArmorIndexSynced(); + boolean flag = this.isHorseSaddled(); + this.updateHorseSlots(); + if (this.ticksExisted > 20) { + if (i == 0 && i != this.getHorseArmorIndexSynced()) { + this.playSound("mob.horse.armor", 0.5F, 1.0F); + } else if (i != this.getHorseArmorIndexSynced()) { + this.playSound("mob.horse.armor", 0.5F, 1.0F); + } + + if (!flag && this.isHorseSaddled()) { + this.playSound("mob.horse.leather", 0.5F, 1.0F); + } + } + + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { if (this.rand.nextInt(200) == 0) { @@ -965,8 +1107,8 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -1040,6 +1182,15 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } + public void openGUI(EntityPlayer playerEntity) { + if (!this.worldObj.isRemote && (this.riddenByEntity == null || this.riddenByEntity == playerEntity) + && this.isTame()) { + this.horseChest.setCustomName(this.getName()); + playerEntity.displayGUIHorse(this, this.horseChest); + } + + } + private void openHorseMouth() { if (!this.worldObj.isRemote) { this.openMouthCounter = 1; @@ -1048,191 +1199,45 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } - /**+ - * Return true if the horse entity ready to mate. (no rider, not - * riding, tame, adult, not steril...) - */ - private boolean canMate() { - return this.riddenByEntity == null && this.ridingEntity == null && this.isTame() && this.isAdultHorse() - && !this.isSterile() && this.getHealth() >= this.getMaxHealth() && this.isInLove(); - } - - public void setEating(boolean flag) { - this.setHorseWatchableBoolean(32, flag); - } - - public void setEatingHaystack(boolean parFlag) { - this.setEating(parFlag); - } - - public void setRearing(boolean rearing) { - if (rearing) { - this.setEatingHaystack(false); + protected void playStepSound(BlockPos blockpos, Block block) { + Block.SoundType block$soundtype = block.stepSound; + if (this.worldObj.getBlockState(blockpos.up()).getBlock() == Blocks.snow_layer) { + block$soundtype = Blocks.snow_layer.stepSound; } - this.setHorseWatchableBoolean(64, rearing); - } - - private void makeHorseRear() { - if (!this.worldObj.isRemote) { - this.jumpRearingCounter = 1; - this.setRearing(true); - } - - } - - public void makeHorseRearWithSound() { - this.makeHorseRear(); - String s = this.getAngrySoundName(); - if (s != null) { - this.playSound(s, this.getSoundVolume(), this.getSoundPitch()); - } - - } - - public void dropChestItems() { - this.dropItemsInChest(this, this.horseChest); - this.dropChests(); - } - - private void dropItemsInChest(Entity entityIn, AnimalChest animalChestIn) { - if (animalChestIn != null && !this.worldObj.isRemote) { - for (int i = 0; i < animalChestIn.getSizeInventory(); ++i) { - ItemStack itemstack = animalChestIn.getStackInSlot(i); - if (itemstack != null) { - this.entityDropItem(itemstack, 0.0F); + if (!block.getMaterial().isLiquid()) { + int i = this.getHorseType(); + if (this.riddenByEntity != null && i != 1 && i != 2) { + ++this.gallopTime; + if (this.gallopTime > 5 && this.gallopTime % 3 == 0) { + this.playSound("mob.horse.gallop", block$soundtype.getVolume() * 0.15F, + block$soundtype.getFrequency()); + if (i == 0 && this.rand.nextInt(10) == 0) { + this.playSound("mob.horse.breathe", block$soundtype.getVolume() * 0.6F, + block$soundtype.getFrequency()); + } + } else if (this.gallopTime <= 5) { + this.playSound("mob.horse.wood", block$soundtype.getVolume() * 0.15F, + block$soundtype.getFrequency()); } + } else if (block$soundtype == Block.soundTypeWood) { + this.playSound("mob.horse.wood", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency()); + } else { + this.playSound("mob.horse.soft", block$soundtype.getVolume() * 0.15F, block$soundtype.getFrequency()); } - } + } - public boolean setTamedBy(EntityPlayer player) { - this.setOwnerId(player.getUniqueID().toString()); - this.setHorseTamed(true); + public boolean prepareChunkForSpawn() { + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.posZ); + this.worldObj.getBiomeGenForCoords(new BlockPos(i, 0, j)); return true; } - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward - */ - public void moveEntityWithHeading(float f, float f1) { - if (this.riddenByEntity != null && this.riddenByEntity instanceof EntityLivingBase && this.isHorseSaddled()) { - this.prevRotationYaw = this.rotationYaw = this.riddenByEntity.rotationYaw; - this.rotationPitch = this.riddenByEntity.rotationPitch * 0.5F; - this.setRotation(this.rotationYaw, this.rotationPitch); - this.rotationYawHead = this.renderYawOffset = this.rotationYaw; - f = ((EntityLivingBase) this.riddenByEntity).moveStrafing * 0.5F; - f1 = ((EntityLivingBase) this.riddenByEntity).moveForward; - if (f1 <= 0.0F) { - f1 *= 0.25F; - this.gallopTime = 0; - } - - if (this.onGround && this.jumpPower == 0.0F && this.isRearing() && !this.field_110294_bI) { - f = 0.0F; - f1 = 0.0F; - } - - if (this.jumpPower > 0.0F && !this.isHorseJumping() && this.onGround) { - this.motionY = this.getHorseJumpStrength() * (double) this.jumpPower; - if (this.isPotionActive(Potion.jump)) { - this.motionY += (double) ((float) (this.getActivePotionEffect(Potion.jump).getAmplifier() + 1) - * 0.1F); - } - - this.setHorseJumping(true); - this.isAirBorne = true; - if (f1 > 0.0F) { - float f2 = MathHelper.sin(this.rotationYaw * 3.1415927F / 180.0F); - float f3 = MathHelper.cos(this.rotationYaw * 3.1415927F / 180.0F); - this.motionX += (double) (-0.4F * f2 * this.jumpPower); - this.motionZ += (double) (0.4F * f3 * this.jumpPower); - this.playSound("mob.horse.jump", 0.4F, 1.0F); - } - - this.jumpPower = 0.0F; - } - - this.stepHeight = 1.0F; - this.jumpMovementFactor = this.getAIMoveSpeed() * 0.1F; - if (!this.worldObj.isRemote) { - this.setAIMoveSpeed( - (float) this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue()); - super.moveEntityWithHeading(f, f1); - } - - if (this.onGround) { - this.jumpPower = 0.0F; - this.setHorseJumping(false); - } - - this.prevLimbSwingAmount = this.limbSwingAmount; - double d1 = this.posX - this.prevPosX; - double d0 = this.posZ - this.prevPosZ; - float f4 = MathHelper.sqrt_double(d1 * d1 + d0 * d0) * 4.0F; - if (f4 > 1.0F) { - f4 = 1.0F; - } - - this.limbSwingAmount += (f4 - this.limbSwingAmount) * 0.4F; - this.limbSwing += this.limbSwingAmount; - } else { - this.stepHeight = 0.5F; - this.jumpMovementFactor = 0.02F; - super.moveEntityWithHeading(f, f1); - } - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("EatingHaystack", this.isEatingHaystack()); - nbttagcompound.setBoolean("ChestedHorse", this.isChested()); - nbttagcompound.setBoolean("HasReproduced", this.getHasReproduced()); - nbttagcompound.setBoolean("Bred", this.isBreeding()); - nbttagcompound.setInteger("Type", this.getHorseType()); - nbttagcompound.setInteger("Variant", this.getHorseVariant()); - nbttagcompound.setInteger("Temper", this.getTemper()); - nbttagcompound.setBoolean("Tame", this.isTame()); - if (worldObj.isRemote && !SingleplayerServerController.isClientInEaglerSingleplayerOrLAN()) { - nbttagcompound.setString("OwnerUUID", this.getOwnerId()); - } else { - nbttagcompound.setString("Owner", this.getOwnerId()); - } - if (this.isChested()) { - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 2; i < this.horseChest.getSizeInventory(); ++i) { - ItemStack itemstack = this.horseChest.getStackInSlot(i); - if (itemstack != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - itemstack.writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - - nbttagcompound.setTag("Items", nbttaglist); - } - - if (this.horseChest.getStackInSlot(1) != null) { - nbttagcompound.setTag("ArmorItem", this.horseChest.getStackInSlot(1).writeToNBT(new NBTTagCompound())); - } - - if (this.horseChest.getStackInSlot(0) != null) { - nbttagcompound.setTag("SaddleItem", this.horseChest.getStackInSlot(0).writeToNBT(new NBTTagCompound())); - } - - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -1297,254 +1302,6 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { this.updateHorseSlots(); } - /**+ - * Returns true if the mob is currently able to mate with the - * specified mob. - */ - public boolean canMateWith(EntityAnimal entityanimal) { - if (entityanimal == this) { - return false; - } else if (entityanimal.getClass() != this.getClass()) { - return false; - } else { - EntityHorse entityhorse = (EntityHorse) entityanimal; - if (this.canMate() && entityhorse.canMate()) { - int i = this.getHorseType(); - int j = entityhorse.getHorseType(); - return i == j || i == 0 && j == 1 || i == 1 && j == 0; - } else { - return false; - } - } - } - - public EntityAgeable createChild(EntityAgeable entityageable) { - EntityHorse entityhorse = (EntityHorse) entityageable; - EntityHorse entityhorse1 = new EntityHorse(this.worldObj); - int i = this.getHorseType(); - int j = entityhorse.getHorseType(); - int k = 0; - if (i == j) { - k = i; - } else if (i == 0 && j == 1 || i == 1 && j == 0) { - k = 2; - } - - if (k == 0) { - int i1 = this.rand.nextInt(9); - int l; - if (i1 < 4) { - l = this.getHorseVariant() & 255; - } else if (i1 < 8) { - l = entityhorse.getHorseVariant() & 255; - } else { - l = this.rand.nextInt(7); - } - - int j1 = this.rand.nextInt(5); - if (j1 < 2) { - l = l | this.getHorseVariant() & '\uff00'; - } else if (j1 < 4) { - l = l | entityhorse.getHorseVariant() & '\uff00'; - } else { - l = l | this.rand.nextInt(5) << 8 & '\uff00'; - } - - entityhorse1.setHorseVariant(l); - } - - entityhorse1.setHorseType(k); - double d1 = this.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue() - + entityageable.getEntityAttribute(SharedMonsterAttributes.maxHealth).getBaseValue() - + (double) this.getModifiedMaxHealth(); - entityhorse1.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(d1 / 3.0D); - double d2 = this.getEntityAttribute(horseJumpStrength).getBaseValue() - + entityageable.getEntityAttribute(horseJumpStrength).getBaseValue() + this.getModifiedJumpStrength(); - entityhorse1.getEntityAttribute(horseJumpStrength).setBaseValue(d2 / 3.0D); - double d0 = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getBaseValue() - + entityageable.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getBaseValue() - + this.getModifiedMovementSpeed(); - entityhorse1.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(d0 / 3.0D); - return entityhorse1; - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); - int i = 0; - int j = 0; - if (ientitylivingdata instanceof EntityHorse.GroupData) { - i = ((EntityHorse.GroupData) ientitylivingdata).horseType; - j = ((EntityHorse.GroupData) ientitylivingdata).horseVariant & 255 | this.rand.nextInt(5) << 8; - } else { - if (this.rand.nextInt(10) == 0) { - i = 1; - } else { - int k = this.rand.nextInt(7); - int l = this.rand.nextInt(5); - i = 0; - j = k | l << 8; - } - - ientitylivingdata = new EntityHorse.GroupData(i, j); - } - - this.setHorseType(i); - this.setHorseVariant(j); - if (this.rand.nextInt(5) == 0) { - this.setGrowingAge(-24000); - } - - if (i != 4 && i != 3) { - this.getEntityAttribute(SharedMonsterAttributes.maxHealth) - .setBaseValue((double) this.getModifiedMaxHealth()); - if (i == 0) { - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed) - .setBaseValue(this.getModifiedMovementSpeed()); - } else { - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.17499999701976776D); - } - } else { - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(15.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.20000000298023224D); - } - - if (i != 2 && i != 1) { - this.getEntityAttribute(horseJumpStrength).setBaseValue(this.getModifiedJumpStrength()); - } else { - this.getEntityAttribute(horseJumpStrength).setBaseValue(0.5D); - } - - this.setHealth(this.getMaxHealth()); - return ientitylivingdata; - } - - public float getGrassEatingAmount(float parFloat1) { - return this.prevHeadLean + (this.headLean - this.prevHeadLean) * parFloat1; - } - - public float getRearingAmount(float parFloat1) { - return this.prevRearingAmount + (this.rearingAmount - this.prevRearingAmount) * parFloat1; - } - - public float getMouthOpennessAngle(float parFloat1) { - return this.prevMouthOpenness + (this.mouthOpenness - this.prevMouthOpenness) * parFloat1; - } - - public void setJumpPower(int jumpPowerIn) { - if (this.isHorseSaddled()) { - if (jumpPowerIn < 0) { - jumpPowerIn = 0; - } else { - this.field_110294_bI = true; - this.makeHorseRear(); - } - - if (jumpPowerIn >= 90) { - this.jumpPower = 1.0F; - } else { - this.jumpPower = 0.4F + 0.4F * (float) jumpPowerIn / 90.0F; - } - } - - } - - /**+ - * "Spawns particles for the horse entity. par1 tells whether to - * spawn hearts. If it is false, it spawns smoke." - */ - protected void spawnHorseParticles(boolean parFlag) { - EnumParticleTypes enumparticletypes = parFlag ? EnumParticleTypes.HEART : EnumParticleTypes.SMOKE_NORMAL; - - for (int i = 0; i < 7; ++i) { - double d0 = this.rand.nextGaussian() * 0.02D; - double d1 = this.rand.nextGaussian() * 0.02D; - double d2 = this.rand.nextGaussian() * 0.02D; - this.worldObj.spawnParticle(enumparticletypes, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, - this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), - this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, - new int[0]); - } - - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 7) { - this.spawnHorseParticles(true); - } else if (b0 == 6) { - this.spawnHorseParticles(false); - } else { - super.handleStatusUpdate(b0); - } - - } - - public void updateRiderPosition() { - super.updateRiderPosition(); - if (this.prevRearingAmount > 0.0F) { - float f = MathHelper.sin(this.renderYawOffset * 3.1415927F / 180.0F); - float f1 = MathHelper.cos(this.renderYawOffset * 3.1415927F / 180.0F); - float f2 = 0.7F * this.prevRearingAmount; - float f3 = 0.15F * this.prevRearingAmount; - this.riddenByEntity.setPosition(this.posX + (double) (f2 * f), - this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset() + (double) f3, - this.posZ - (double) (f2 * f1)); - if (this.riddenByEntity instanceof EntityLivingBase) { - ((EntityLivingBase) this.riddenByEntity).renderYawOffset = this.renderYawOffset; - } - } - - } - - /**+ - * Returns randomized max health - */ - private float getModifiedMaxHealth() { - return 15.0F + (float) this.rand.nextInt(8) + (float) this.rand.nextInt(9); - } - - /**+ - * Returns randomized jump strength - */ - private double getModifiedJumpStrength() { - return 0.4000000059604645D + this.rand.nextDouble() * 0.2D + this.rand.nextDouble() * 0.2D - + this.rand.nextDouble() * 0.2D; - } - - /**+ - * Returns randomized movement speed - */ - private double getModifiedMovementSpeed() { - return (0.44999998807907104D + this.rand.nextDouble() * 0.3D + this.rand.nextDouble() * 0.3D - + this.rand.nextDouble() * 0.3D) * 0.25D; - } - - /**+ - * Returns true if given item is horse armor - */ - public static boolean isArmorItem(Item parItem) { - return parItem == Items.iron_horse_armor || parItem == Items.golden_horse_armor - || parItem == Items.diamond_horse_armor; - } - - /**+ - * returns true if this entity is by a ladder, false otherwise - */ - public boolean isOnLadder() { - return false; - } - - public float getEyeHeight() { - return this.height; - } - public boolean replaceItemInInventory(int i, ItemStack itemstack) { if (i == 499 && this.canCarryChest()) { if (itemstack == null && this.isChested()) { @@ -1582,13 +1339,253 @@ public class EntityHorse extends EntityAnimal implements IInvBasic { } } - public static class GroupData implements IEntityLivingData { - public int horseType; - public int horseVariant; + private void resetTexturePrefix() { + this.texturePrefix = null; + } - public GroupData(int type, int variant) { - this.horseType = type; - this.horseVariant = variant; + public void setBreeding(boolean breeding) { + this.setHorseWatchableBoolean(16, breeding); + } + + public void setChested(boolean chested) { + this.setHorseWatchableBoolean(8, chested); + } + + public void setEating(boolean flag) { + this.setHorseWatchableBoolean(32, flag); + } + + public void setEatingHaystack(boolean parFlag) { + this.setEating(parFlag); + } + + public void setHasReproduced(boolean hasReproducedIn) { + this.hasReproduced = hasReproducedIn; + } + + /** + * + Set horse armor stack (for example: new ItemStack(Items.iron_horse_armor)) + */ + public void setHorseArmorStack(ItemStack itemStackIn) { + this.dataWatcher.updateObject(22, Integer.valueOf(this.getHorseArmorIndex(itemStackIn))); + this.resetTexturePrefix(); + } + + public void setHorseJumping(boolean jumping) { + this.horseJumping = jumping; + } + + public void setHorseSaddled(boolean saddled) { + this.setHorseWatchableBoolean(4, saddled); + } + + public void setHorseTamed(boolean tamed) { + this.setHorseWatchableBoolean(2, tamed); + } + + private void setHorseTexturePaths() { + this.texturePrefix = "horse/"; + this.horseTexturesArray[0] = null; + this.horseTexturesArray[1] = null; + this.horseTexturesArray[2] = null; + int i = this.getHorseType(); + int j = this.getHorseVariant(); + if (i == 0) { + int k = j & 255; + int l = (j & '\uff00') >> 8; + if (k >= horseTextures.length) { + this.field_175508_bO = false; + return; + } + + this.horseTexturesArray[0] = horseTextures[k]; + this.texturePrefix = this.texturePrefix + HORSE_TEXTURES_ABBR[k]; + if (l >= horseMarkingTextures.length) { + this.field_175508_bO = false; + return; + } + + this.horseTexturesArray[1] = horseMarkingTextures[l]; + this.texturePrefix = this.texturePrefix + HORSE_MARKING_TEXTURES_ABBR[l]; + } else { + this.horseTexturesArray[0] = ""; + this.texturePrefix = this.texturePrefix + "_" + i + "_"; + } + + int i1 = this.getHorseArmorIndexSynced(); + if (i1 >= horseArmorTextures.length) { + this.field_175508_bO = false; + } else { + this.horseTexturesArray[2] = horseArmorTextures[i1]; + this.texturePrefix = this.texturePrefix + HORSE_ARMOR_TEXTURES_ABBR[i1]; + this.field_175508_bO = true; } } + + public void setHorseType(int type) { + this.dataWatcher.updateObject(19, Byte.valueOf((byte) type)); + this.resetTexturePrefix(); + } + + public void setHorseVariant(int variant) { + this.dataWatcher.updateObject(20, Integer.valueOf(variant)); + this.resetTexturePrefix(); + } + + private void setHorseWatchableBoolean(int parInt1, boolean parFlag) { + int i = this.dataWatcher.getWatchableObjectInt(16); + if (parFlag) { + this.dataWatcher.updateObject(16, Integer.valueOf(i | parInt1)); + } else { + this.dataWatcher.updateObject(16, Integer.valueOf(i & ~parInt1)); + } + + } + + public void setJumpPower(int jumpPowerIn) { + if (this.isHorseSaddled()) { + if (jumpPowerIn < 0) { + jumpPowerIn = 0; + } else { + this.field_110294_bI = true; + this.makeHorseRear(); + } + + if (jumpPowerIn >= 90) { + this.jumpPower = 1.0F; + } else { + this.jumpPower = 0.4F + 0.4F * (float) jumpPowerIn / 90.0F; + } + } + + } + + public void setOwnerId(String id) { + this.dataWatcher.updateObject(21, id); + } + + public void setRearing(boolean rearing) { + if (rearing) { + this.setEatingHaystack(false); + } + + this.setHorseWatchableBoolean(64, rearing); + } + + /** + * + "Sets the scale for an ageable entity according to the boolean parameter, + * which says if it's a child." + */ + public void setScaleForAge(boolean flag) { + if (flag) { + this.setScale(this.getHorseSize()); + } else { + this.setScale(1.0F); + } + + } + + public boolean setTamedBy(EntityPlayer player) { + this.setOwnerId(player.getUniqueID().toString()); + this.setHorseTamed(true); + return true; + } + + public void setTemper(int temperIn) { + this.temper = temperIn; + } + + /** + * + "Spawns particles for the horse entity. par1 tells whether to spawn hearts. + * If it is false, it spawns smoke." + */ + protected void spawnHorseParticles(boolean parFlag) { + EnumParticleTypes enumparticletypes = parFlag ? EnumParticleTypes.HEART : EnumParticleTypes.SMOKE_NORMAL; + + for (int i = 0; i < 7; ++i) { + double d0 = this.rand.nextGaussian() * 0.02D; + double d1 = this.rand.nextGaussian() * 0.02D; + double d2 = this.rand.nextGaussian() * 0.02D; + this.worldObj.spawnParticle(enumparticletypes, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, + this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), + this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, + new int[0]); + } + + } + + /** + * + Updates the items in the saddle and armor slots of the horse's inventory. + */ + private void updateHorseSlots() { + if (!this.worldObj.isRemote) { + this.setHorseSaddled(this.horseChest.getStackInSlot(0) != null); + if (this.canWearArmor()) { + this.setHorseArmorStack(this.horseChest.getStackInSlot(1)); + } + } + + } + + public void updateRiderPosition() { + super.updateRiderPosition(); + if (this.prevRearingAmount > 0.0F) { + float f = MathHelper.sin(this.renderYawOffset * 3.1415927F / 180.0F); + float f1 = MathHelper.cos(this.renderYawOffset * 3.1415927F / 180.0F); + float f2 = 0.7F * this.prevRearingAmount; + float f3 = 0.15F * this.prevRearingAmount; + this.riddenByEntity.setPosition(this.posX + (double) (f2 * f), + this.posY + this.getMountedYOffset() + this.riddenByEntity.getYOffset() + (double) f3, + this.posZ - (double) (f2 * f1)); + if (this.riddenByEntity instanceof EntityLivingBase) { + ((EntityLivingBase) this.riddenByEntity).renderYawOffset = this.renderYawOffset; + } + } + + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("EatingHaystack", this.isEatingHaystack()); + nbttagcompound.setBoolean("ChestedHorse", this.isChested()); + nbttagcompound.setBoolean("HasReproduced", this.getHasReproduced()); + nbttagcompound.setBoolean("Bred", this.isBreeding()); + nbttagcompound.setInteger("Type", this.getHorseType()); + nbttagcompound.setInteger("Variant", this.getHorseVariant()); + nbttagcompound.setInteger("Temper", this.getTemper()); + nbttagcompound.setBoolean("Tame", this.isTame()); + if (worldObj.isRemote && !SingleplayerServerController.isClientInEaglerSingleplayerOrLAN()) { + nbttagcompound.setString("OwnerUUID", this.getOwnerId()); + } else { + nbttagcompound.setString("Owner", this.getOwnerId()); + } + if (this.isChested()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 2; i < this.horseChest.getSizeInventory(); ++i) { + ItemStack itemstack = this.horseChest.getStackInSlot(i); + if (itemstack != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + itemstack.writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + + nbttagcompound.setTag("Items", nbttaglist); + } + + if (this.horseChest.getStackInSlot(1) != null) { + nbttagcompound.setTag("ArmorItem", this.horseChest.getStackInSlot(1).writeToNBT(new NBTTagCompound())); + } + + if (this.horseChest.getStackInSlot(0) != null) { + nbttagcompound.setTag("SaddleItem", this.horseChest.getStackInSlot(0).writeToNBT(new NBTTagCompound())); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityMooshroom.java b/src/game/java/net/minecraft/entity/passive/EntityMooshroom.java index 6b0bfff0..c968cd0e 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityMooshroom.java +++ b/src/game/java/net/minecraft/entity/passive/EntityMooshroom.java @@ -9,22 +9,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,9 +39,13 @@ public class EntityMooshroom extends EntityCow { this.spawnableBlock = Blocks.mycelium; } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + public EntityMooshroom createChild(EntityAgeable var1) { + return new EntityMooshroom(this.worldObj); + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -85,8 +92,4 @@ public class EntityMooshroom extends EntityCow { return super.interact(entityplayer); } } - - public EntityMooshroom createChild(EntityAgeable var1) { - return new EntityMooshroom(this.worldObj); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityOcelot.java b/src/game/java/net/minecraft/entity/passive/EntityOcelot.java index e25dcfab..e968b922 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityOcelot.java +++ b/src/game/java/net/minecraft/entity/passive/EntityOcelot.java @@ -1,6 +1,7 @@ package net.minecraft.entity.passive; import com.google.common.base.Predicate; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; @@ -31,22 +32,25 @@ import net.minecraft.util.StatCollector; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -72,106 +76,18 @@ public class EntityOcelot extends EntityTameable { this.targetTasks.addTask(1, new EntityAITargetNonTamed(this, EntityChicken.class, false, (Predicate) null)); } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); - } - - public void updateAITasks() { - if (this.getMoveHelper().isUpdating()) { - double d0 = this.getMoveHelper().getSpeed(); - if (d0 == 0.6D) { - this.setSneaking(true); - this.setSprinting(false); - } else if (d0 == 1.33D) { - this.setSneaking(false); - this.setSprinting(true); - } else { - this.setSneaking(false); - this.setSprinting(false); - } - } else { - this.setSneaking(false); - this.setSprinting(false); - } - - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return !this.isTamed() && this.ticksExisted > 2400; - } - protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); } - public void fall(float var1, float var2) { - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("CatType", this.getTameSkin()); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setTameSkin(nbttagcompound.getInteger("CatType")); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return this.isTamed() - ? (this.isInLove() ? "mob.cat.purr" : (this.rand.nextInt(4) == 0 ? "mob.cat.purreow" : "mob.cat.meow")) - : ""; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.cat.hitt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.cat.hitt"; - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 0.4F; - } - - protected Item getDropItem() { - return Items.leather; - } - public boolean attackEntityAsMob(Entity entity) { return entity.attackEntityFrom(DamageSource.causeMobDamage(this), 3.0F); } - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (this.isEntityInvulnerable(damagesource)) { @@ -182,15 +98,121 @@ public class EntityOcelot extends EntityTameable { } } - /**+ - * Drop 0-2 items of this living's type + /** + * + Determines if an entity can be despawned, used on idle far away entities + */ + protected boolean canDespawn() { + return !this.isTamed() && this.ticksExisted > 2400; + } + + /** + * + Returns true if the mob is currently able to mate with the specified mob. + */ + public boolean canMateWith(EntityAnimal entityanimal) { + if (entityanimal == this) { + return false; + } else if (!this.isTamed()) { + return false; + } else if (!(entityanimal instanceof EntityOcelot)) { + return false; + } else { + EntityOcelot entityocelot = (EntityOcelot) entityanimal; + return !entityocelot.isTamed() ? false : this.isInLove() && entityocelot.isInLove(); + } + } + + public EntityOcelot createChild(EntityAgeable var1) { + EntityOcelot entityocelot = new EntityOcelot(this.worldObj); + if (this.isTamed()) { + entityocelot.setOwnerId(this.getOwnerId()); + entityocelot.setTamed(true); + entityocelot.setTameSkin(this.getTameSkin()); + } + + return entityocelot; + } + + /** + * + Drop 0-2 items of this living's type */ protected void dropFewItems(boolean var1, int var2) { } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); + } + + public void fall(float var1, float var2) { + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return this.worldObj.rand.nextInt(3) != 0; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.cat.hitt"; + } + + protected Item getDropItem() { + return Items.leather; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.cat.hitt"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return this.isTamed() + ? (this.isInLove() ? "mob.cat.purr" : (this.rand.nextInt(4) == 0 ? "mob.cat.purreow" : "mob.cat.meow")) + : ""; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return getNameImpl(false); + } + + private String getNameImpl(boolean filter) { + return this.hasCustomName() ? (filter ? this.getCustomNameTagProfanityFilter() : this.getCustomNameTag()) + : (this.isTamed() ? StatCollector.translateToLocal("entity.Cat.name") + : (filter ? super.getNameProfanityFilter() : super.getName())); + } + + public String getNameProfanityFilter() { + return getNameImpl(true); + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.4F; + } + + public int getTameSkin() { + return this.dataWatcher.getWatchableObjectByte(18); + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -228,62 +250,16 @@ public class EntityOcelot extends EntityTameable { return super.interact(entityplayer); } - public EntityOcelot createChild(EntityAgeable var1) { - EntityOcelot entityocelot = new EntityOcelot(this.worldObj); - if (this.isTamed()) { - entityocelot.setOwnerId(this.getOwnerId()); - entityocelot.setTamed(true); - entityocelot.setTameSkin(this.getTameSkin()); - } - - return entityocelot; - } - - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) */ public boolean isBreedingItem(ItemStack itemstack) { return itemstack != null && itemstack.getItem() == Items.fish; } - /**+ - * Returns true if the mob is currently able to mate with the - * specified mob. - */ - public boolean canMateWith(EntityAnimal entityanimal) { - if (entityanimal == this) { - return false; - } else if (!this.isTamed()) { - return false; - } else if (!(entityanimal instanceof EntityOcelot)) { - return false; - } else { - EntityOcelot entityocelot = (EntityOcelot) entityanimal; - return !entityocelot.isTamed() ? false : this.isInLove() && entityocelot.isInLove(); - } - } - - public int getTameSkin() { - return this.dataWatcher.getWatchableObjectByte(18); - } - - public void setTameSkin(int skinId) { - this.dataWatcher.updateObject(18, Byte.valueOf((byte) skinId)); - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return this.worldObj.rand.nextInt(3) != 0; - } - - /**+ - * Checks that the entity is not colliding with any blocks / - * liquids + /** + * + Checks that the entity is not colliding with any blocks / liquids */ public boolean isNotColliding() { if (this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this) @@ -303,45 +279,10 @@ public class EntityOcelot extends EntityTameable { return false; } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return getNameImpl(false); - } - - public String getNameProfanityFilter() { - return getNameImpl(true); - } - - private String getNameImpl(boolean filter) { - return this.hasCustomName() ? (filter ? this.getCustomNameTagProfanityFilter() : this.getCustomNameTag()) - : (this.isTamed() ? StatCollector.translateToLocal("entity.Cat.name") - : (filter ? super.getNameProfanityFilter() : super.getName())); - } - - public void setTamed(boolean flag) { - super.setTamed(flag); - } - - protected void setupTamedAI() { - if (this.avoidEntity == null) { - this.avoidEntity = new EntityAIAvoidEntity(this, EntityPlayer.class, 16.0F, 0.8D, 1.33D); - } - - this.tasks.removeTask(this.avoidEntity); - if (!this.isTamed()) { - this.tasks.addTask(4, this.avoidEntity); - } - - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory */ public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, IEntityLivingData ientitylivingdata) { @@ -357,4 +298,60 @@ public class EntityOcelot extends EntityTameable { return ientitylivingdata; } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setTameSkin(nbttagcompound.getInteger("CatType")); + } + + public void setTamed(boolean flag) { + super.setTamed(flag); + } + + public void setTameSkin(int skinId) { + this.dataWatcher.updateObject(18, Byte.valueOf((byte) skinId)); + } + + protected void setupTamedAI() { + if (this.avoidEntity == null) { + this.avoidEntity = new EntityAIAvoidEntity(this, EntityPlayer.class, 16.0F, 0.8D, 1.33D); + } + + this.tasks.removeTask(this.avoidEntity); + if (!this.isTamed()) { + this.tasks.addTask(4, this.avoidEntity); + } + + } + + public void updateAITasks() { + if (this.getMoveHelper().isUpdating()) { + double d0 = this.getMoveHelper().getSpeed(); + if (d0 == 0.6D) { + this.setSneaking(true); + this.setSprinting(false); + } else if (d0 == 1.33D) { + this.setSneaking(false); + this.setSprinting(true); + } else { + this.setSneaking(false); + this.setSprinting(false); + } + } else { + this.setSneaking(false); + this.setSprinting(false); + } + + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("CatType", this.getTameSkin()); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityPig.java b/src/game/java/net/minecraft/entity/passive/EntityPig.java index 7f5bcb32..73c1095a 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityPig.java +++ b/src/game/java/net/minecraft/entity/passive/EntityPig.java @@ -24,22 +24,25 @@ import net.minecraft.stats.AchievementList; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -69,86 +72,22 @@ public class EntityPig extends EntityAnimal { this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.25D); } - /**+ - * returns true if all the conditions for steering the entity - * are met. For pigs, this is true if it is being ridden by a - * player and the player is holding a carrot-on-a-stick + /** + * + returns true if all the conditions for steering the entity are met. For + * pigs, this is true if it is being ridden by a player and the player is + * holding a carrot-on-a-stick */ public boolean canBeSteered() { ItemStack itemstack = ((EntityPlayer) this.riddenByEntity).getHeldItem(); return itemstack != null && itemstack.getItem() == Items.carrot_on_a_stick; } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + public EntityPig createChild(EntityAgeable var1) { + return new EntityPig(this.worldObj); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("Saddle", this.getSaddled()); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setSaddled(nbttagcompound.getBoolean("Saddle")); - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.pig.say"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.pig.say"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.pig.death"; - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.pig.step", 0.15F, 1.0F); - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. - */ - public boolean interact(EntityPlayer entityplayer) { - if (super.interact(entityplayer)) { - return true; - } else if (!this.getSaddled() || this.worldObj.isRemote - || this.riddenByEntity != null && this.riddenByEntity != entityplayer) { - return false; - } else { - entityplayer.mountEntity(this); - return true; - } - } - - protected Item getDropItem() { - return this.isBurning() ? Items.cooked_porkchop : Items.porkchop; - } - - /**+ - * Drop 0-2 items of this living's type + /** + * + Drop 0-2 items of this living's type */ protected void dropFewItems(boolean var1, int i) { int j = this.rand.nextInt(3) + 1 + this.rand.nextInt(1 + i); @@ -167,27 +106,84 @@ public class EntityPig extends EntityAnimal { } - /**+ - * Returns true if the pig is saddled. + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + public void fall(float f, float f1) { + super.fall(f, f1); + if (f > 5.0F && this.riddenByEntity instanceof EntityPlayer) { + ((EntityPlayer) this.riddenByEntity).triggerAchievement(AchievementList.flyPig); + } + + } + + /** + * + Return the AI task for player control. + */ + public EntityAIControlledByPlayer getAIControlledByPlayer() { + return this.aiControlledByPlayer; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.pig.death"; + } + + protected Item getDropItem() { + return this.isBurning() ? Items.cooked_porkchop : Items.porkchop; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.pig.say"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.pig.say"; + } + + /** + * + Returns true if the pig is saddled. */ public boolean getSaddled() { return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; } - /**+ - * Set or remove the saddle of the pig. + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ - public void setSaddled(boolean saddled) { - if (saddled) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) 1)); + public boolean interact(EntityPlayer entityplayer) { + if (super.interact(entityplayer)) { + return true; + } else if (!this.getSaddled() || this.worldObj.isRemote + || this.riddenByEntity != null && this.riddenByEntity != entityplayer) { + return false; } else { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) 0)); + entityplayer.mountEntity(this); + return true; } - } - /**+ - * Called when a lightning bolt hits the entity. + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) + */ + public boolean isBreedingItem(ItemStack itemstack) { + return itemstack != null && itemstack.getItem() == Items.carrot; + } + + /** + * + Called when a lightning bolt hits the entity. */ public void onStruckByLightning(EntityLightningBolt var1) { if (!this.worldObj.isRemote && !this.isDead) { @@ -205,31 +201,35 @@ public class EntityPig extends EntityAnimal { } } - public void fall(float f, float f1) { - super.fall(f, f1); - if (f > 5.0F && this.riddenByEntity instanceof EntityPlayer) { - ((EntityPlayer) this.riddenByEntity).triggerAchievement(AchievementList.flyPig); + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.pig.step", 0.15F, 1.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setSaddled(nbttagcompound.getBoolean("Saddle")); + } + + /** + * + Set or remove the saddle of the pig. + */ + public void setSaddled(boolean saddled) { + if (saddled) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) 1)); + } else { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) 0)); } } - public EntityPig createChild(EntityAgeable var1) { - return new EntityPig(this.worldObj); - } - - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean isBreedingItem(ItemStack itemstack) { - return itemstack != null && itemstack.getItem() == Items.carrot; - } - - /**+ - * Return the AI task for player control. - */ - public EntityAIControlledByPlayer getAIControlledByPlayer() { - return this.aiControlledByPlayer; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("Saddle", this.getSaddled()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityRabbit.java b/src/game/java/net/minecraft/entity/passive/EntityRabbit.java index 80925ec3..8f3d0032 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityRabbit.java +++ b/src/game/java/net/minecraft/entity/passive/EntityRabbit.java @@ -38,35 +38,247 @@ import net.minecraft.util.Vec3; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityRabbit extends EntityAnimal { + static class AIAvoidEntity extends EntityAIAvoidEntity { + private EntityRabbit entityInstance; + + public AIAvoidEntity(EntityRabbit parEntityRabbit, Class parClass1, float parFloat1, double parDouble1, + double parDouble2) { + super(parEntityRabbit, parClass1, parFloat1, parDouble1, parDouble2); + this.entityInstance = parEntityRabbit; + } + + public void updateTask() { + super.updateTask(); + } + } + + static class AIEvilAttack extends EntityAIAttackOnCollide { + public AIEvilAttack(EntityRabbit parEntityRabbit) { + super(parEntityRabbit, EntityLivingBase.class, 1.4D, true); + } + + protected double func_179512_a(EntityLivingBase entitylivingbase) { + return (double) (4.0F + entitylivingbase.width); + } + } + + static class AIPanic extends EntityAIPanic { + private EntityRabbit theEntity; + + public AIPanic(EntityRabbit parEntityRabbit, double speedIn) { + super(parEntityRabbit, speedIn); + this.theEntity = parEntityRabbit; + } + + public void updateTask() { + super.updateTask(); + this.theEntity.setMovementSpeed(this.speed); + } + } + + static class AIRaidFarm extends EntityAIMoveToBlock { + private final EntityRabbit field_179500_c; + private boolean field_179498_d; + private boolean field_179499_e = false; + + public AIRaidFarm(EntityRabbit parEntityRabbit) { + super(parEntityRabbit, 0.699999988079071D, 16); + this.field_179500_c = parEntityRabbit; + } + + public boolean continueExecuting() { + return this.field_179499_e && super.continueExecuting(); + } + + public void resetTask() { + super.resetTask(); + } + + public boolean shouldExecute() { + if (this.runDelay <= 0) { + if (!this.field_179500_c.worldObj.getGameRules().getBoolean("mobGriefing")) { + return false; + } + + this.field_179499_e = false; + this.field_179498_d = this.field_179500_c.isCarrotEaten(); + } + + return super.shouldExecute(); + } + + protected boolean shouldMoveTo(World world, BlockPos blockpos) { + Block block = world.getBlockState(blockpos).getBlock(); + if (block == Blocks.farmland) { + blockpos = blockpos.up(); + IBlockState iblockstate = world.getBlockState(blockpos); + block = iblockstate.getBlock(); + if (block instanceof BlockCarrot && ((Integer) iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7 + && this.field_179498_d && !this.field_179499_e) { + this.field_179499_e = true; + return true; + } + } + + return false; + } + + public void startExecuting() { + super.startExecuting(); + } + + public void updateTask() { + super.updateTask(); + this.field_179500_c.getLookHelper().setLookPosition((double) this.destinationBlock.getX() + 0.5D, + (double) (this.destinationBlock.getY() + 1), (double) this.destinationBlock.getZ() + 0.5D, 10.0F, + (float) this.field_179500_c.getVerticalFaceSpeed()); + if (this.getIsAboveDestination()) { + World world = this.field_179500_c.worldObj; + BlockPos blockpos = this.destinationBlock.up(); + IBlockState iblockstate = world.getBlockState(blockpos); + Block block = iblockstate.getBlock(); + if (this.field_179499_e && block instanceof BlockCarrot + && ((Integer) iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7) { + world.setBlockState(blockpos, Blocks.air.getDefaultState(), 2); + world.destroyBlock(blockpos, true); + this.field_179500_c.createEatingParticles(); + } + + this.field_179499_e = false; + this.runDelay = 10; + } + + } + } + + static enum EnumMoveType { + NONE(0.0F, 0.0F, 30, 1), HOP(0.8F, 0.2F, 20, 10), STEP(1.0F, 0.45F, 14, 14), SPRINT(1.75F, 0.4F, 1, 8), + ATTACK(2.0F, 0.7F, 7, 8); + + private final float speed; + private final float field_180077_g; + private final int duration; + private final int field_180085_i; + + private EnumMoveType(float typeSpeed, float parFloat1, int typeDuration, int parInt1) { + this.speed = typeSpeed; + this.field_180077_g = parFloat1; + this.duration = typeDuration; + this.field_180085_i = parInt1; + } + + public int func_180073_d() { + return this.field_180085_i; + } + + public float func_180074_b() { + return this.field_180077_g; + } + + public int getDuration() { + return this.duration; + } + + public float getSpeed() { + return this.speed; + } + } + + public class RabbitJumpHelper extends EntityJumpHelper { + private EntityRabbit theEntity; + private boolean field_180068_d = false; + + public RabbitJumpHelper(EntityRabbit rabbit) { + super(rabbit); + this.theEntity = rabbit; + } + + public void doJump() { + if (this.isJumping) { + this.theEntity.doMovementAction(EntityRabbit.EnumMoveType.STEP); + this.isJumping = false; + } + + } + + public boolean func_180065_d() { + return this.field_180068_d; + } + + public void func_180066_a(boolean parFlag) { + this.field_180068_d = parFlag; + } + + public boolean getIsJumping() { + return this.isJumping; + } + } + + static class RabbitMoveHelper extends EntityMoveHelper { + private EntityRabbit theEntity; + + public RabbitMoveHelper(EntityRabbit parEntityRabbit) { + super(parEntityRabbit); + this.theEntity = parEntityRabbit; + } + + public void onUpdateMoveHelper() { + if (this.theEntity.onGround && !this.theEntity.func_175523_cj()) { + this.theEntity.setMovementSpeed(0.0D); + } + + super.onUpdateMoveHelper(); + } + } + + public static class RabbitTypeData implements IEntityLivingData { + public int typeData; + + public RabbitTypeData(int type) { + this.typeData = type; + } + } + private EntityRabbit.AIAvoidEntity aiAvoidWolves; + private int field_175540_bm = 0; + private int field_175535_bn = 0; + private boolean field_175536_bo = false; + private boolean field_175537_bp = false; + private int currentMoveTypeDuration = 0; + private EntityRabbit.EnumMoveType moveType = EntityRabbit.EnumMoveType.HOP; + private int carrotTicks = 0; + private EntityPlayer field_175543_bt = null; public EntityRabbit(World worldIn) { @@ -90,13 +302,103 @@ public class EntityRabbit extends EntityAnimal { this.setMovementSpeed(0.0D); } - protected float getJumpUpwardsMotion() { - return this.moveHelper.isUpdating() && this.moveHelper.getY() > this.posY + 0.5D ? 0.5F - : this.moveType.func_180074_b(); + /** + * + Causes this Entity to drop a random item. + */ + protected void addRandomDrop() { + this.entityDropItem(new ItemStack(Items.rabbit_foot, 1), 0.0F); } - public void setMoveType(EntityRabbit.EnumMoveType type) { - this.moveType = type; + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); + } + + public boolean attackEntityAsMob(Entity entity) { + if (this.getRabbitType() == 99) { + this.playSound("mob.attack", 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); + return entity.attackEntityFrom(DamageSource.causeMobDamage(this), 8.0F); + } else { + return entity.attackEntityFrom(DamageSource.causeMobDamage(this), 3.0F); + } + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + return this.isEntityInvulnerable(damagesource) ? false : super.attackEntityFrom(damagesource, f); + } + + private void calculateRotationYaw(double x, double z) { + this.rotationYaw = (float) (MathHelper.func_181159_b(z - this.posZ, x - this.posX) * 180.0D + / 3.1415927410125732D) - 90.0F; + } + + public EntityRabbit createChild(EntityAgeable entityageable) { + EntityRabbit entityrabbit = new EntityRabbit(this.worldObj); + if (entityageable instanceof EntityRabbit) { + entityrabbit.setRabbitType( + this.rand.nextBoolean() ? this.getRabbitType() : ((EntityRabbit) entityageable).getRabbitType()); + } + + return entityrabbit; + } + + protected void createEatingParticles() { + this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_DUST, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, + this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), + this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, 0.0D, 0.0D, + 0.0D, new int[] { Block.getStateId(Blocks.carrots.getStateFromMeta(7)) }); + this.carrotTicks = 100; + } + + public void doMovementAction(EntityRabbit.EnumMoveType movetype) { + this.setJumping(true, movetype); + this.field_175535_bn = movetype.func_180073_d(); + this.field_175540_bm = 0; + } + + /** + * + Drop 0-2 items of this living's type + */ + protected void dropFewItems(boolean var1, int i) { + int j = this.rand.nextInt(2) + this.rand.nextInt(1 + i); + + for (int k = 0; k < j; ++k) { + this.dropItem(Items.rabbit_hide, 1); + } + + j = this.rand.nextInt(2); + + for (int l = 0; l < j; ++l) { + if (this.isBurning()) { + this.dropItem(Items.cooked_rabbit, 1); + } else { + this.dropItem(Items.rabbit, 1); + } + } + + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); + } + + private void func_175517_cu() { + this.updateMoveTypeDuration(); + this.func_175520_cs(); + } + + private void func_175518_cr() { + ((EntityRabbit.RabbitJumpHelper) this.jumpHelper).func_180066_a(true); + } + + private void func_175520_cs() { + ((EntityRabbit.RabbitJumpHelper) this.jumpHelper).func_180066_a(false); } public float func_175521_o(float parFloat1) { @@ -104,9 +406,145 @@ public class EntityRabbit extends EntityAnimal { : ((float) this.field_175540_bm + parFloat1) / (float) this.field_175535_bn; } - public void setMovementSpeed(double newSpeed) { - this.getNavigator().setSpeed(newSpeed); - this.moveHelper.setMoveTo(this.moveHelper.getX(), this.moveHelper.getY(), this.moveHelper.getZ(), newSpeed); + public boolean func_175523_cj() { + return this.field_175536_bo; + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.rabbit.death"; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.rabbit.hurt"; + } + + protected String getJumpingSound() { + return "mob.rabbit.hop"; + } + + protected float getJumpUpwardsMotion() { + return this.moveHelper.isUpdating() && this.moveHelper.getY() > this.posY + 0.5D ? 0.5F + : this.moveType.func_180074_b(); + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.rabbit.idle"; + } + + /** + * + Returns duration of the current + * {@link net.minecraft.entity.passive.EntityRabbit.EnumMoveType move type} + */ + protected int getMoveTypeDuration() { + return this.moveType.getDuration(); + } + + public int getRabbitType() { + return this.dataWatcher.getWatchableObjectByte(18); + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue + */ + public int getTotalArmorValue() { + return this.getRabbitType() == 99 ? 8 : super.getTotalArmorValue(); + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 1) { + this.createRunningParticles(); + this.field_175535_bn = 10; + this.field_175540_bm = 0; + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) + */ + public boolean isBreedingItem(ItemStack itemstack) { + return itemstack != null && this.isRabbitBreedingItem(itemstack.getItem()); + } + + /** + * + Returns true if + * {@link net.minecraft.entity.passive.EntityRabbit#carrotTicks carrotTicks} has + * reached zero + */ + private boolean isCarrotEaten() { + return this.carrotTicks == 0; + } + + private boolean isRabbitBreedingItem(Item itemIn) { + return itemIn == Items.carrot || itemIn == Items.golden_carrot + || itemIn == Item.getItemFromBlock(Blocks.yellow_flower); + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); + int i = this.rand.nextInt(6); + boolean flag = false; + if (ientitylivingdata instanceof EntityRabbit.RabbitTypeData) { + i = ((EntityRabbit.RabbitTypeData) ientitylivingdata).typeData; + flag = true; + } else { + ientitylivingdata = new EntityRabbit.RabbitTypeData(i); + } + + this.setRabbitType(i); + if (flag) { + this.setGrowingAge(-24000); + } + + return ientitylivingdata; + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + super.onLivingUpdate(); + if (this.field_175540_bm != this.field_175535_bn) { + if (this.field_175540_bm == 0 && !this.worldObj.isRemote) { + this.worldObj.setEntityState(this, (byte) 1); + } + + ++this.field_175540_bm; + } else if (this.field_175535_bn != 0) { + this.field_175540_bm = 0; + this.field_175535_bn = 0; + } + + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setRabbitType(nbttagcompound.getInteger("RabbitType")); + this.carrotTicks = nbttagcompound.getInteger("MoreCarrotTicks"); } public void setJumping(boolean jump, EntityRabbit.EnumMoveType moveTypeIn) { @@ -124,19 +562,35 @@ public class EntityRabbit extends EntityAnimal { this.field_175536_bo = jump; } - public void doMovementAction(EntityRabbit.EnumMoveType movetype) { - this.setJumping(true, movetype); - this.field_175535_bn = movetype.func_180073_d(); - this.field_175540_bm = 0; + public void setMovementSpeed(double newSpeed) { + this.getNavigator().setSpeed(newSpeed); + this.moveHelper.setMoveTo(this.moveHelper.getX(), this.moveHelper.getY(), this.moveHelper.getZ(), newSpeed); } - public boolean func_175523_cj() { - return this.field_175536_bo; + public void setMoveType(EntityRabbit.EnumMoveType type) { + this.moveType = type; } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(18, Byte.valueOf((byte) 0)); + public void setRabbitType(int rabbitTypeId) { + if (rabbitTypeId == 99) { + this.tasks.removeTask(this.aiAvoidWolves); + this.tasks.addTask(4, new EntityRabbit.AIEvilAttack(this)); + this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0])); + this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); + this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityWolf.class, true)); + if (!this.hasCustomName()) { + this.setCustomNameTag(StatCollector.translateToLocal("entity.KillerBunny.name")); + } + } + + this.dataWatcher.updateObject(18, Byte.valueOf((byte) rabbitTypeId)); + } + + /** + * + Attempts to create sprinting particles if the entity is sprinting and not + * in water. + */ + public void spawnRunningParticles() { } public void updateAITasks() { @@ -194,464 +648,16 @@ public class EntityRabbit extends EntityAnimal { this.field_175537_bp = this.onGround; } - /**+ - * Attempts to create sprinting particles if the entity is - * sprinting and not in water. - */ - public void spawnRunningParticles() { - } - - private void calculateRotationYaw(double x, double z) { - this.rotationYaw = (float) (MathHelper.func_181159_b(z - this.posZ, x - this.posX) * 180.0D - / 3.1415927410125732D) - 90.0F; - } - - private void func_175518_cr() { - ((EntityRabbit.RabbitJumpHelper) this.jumpHelper).func_180066_a(true); - } - - private void func_175520_cs() { - ((EntityRabbit.RabbitJumpHelper) this.jumpHelper).func_180066_a(false); - } - private void updateMoveTypeDuration() { this.currentMoveTypeDuration = this.getMoveTypeDuration(); } - private void func_175517_cu() { - this.updateMoveTypeDuration(); - this.func_175520_cs(); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - super.onLivingUpdate(); - if (this.field_175540_bm != this.field_175535_bn) { - if (this.field_175540_bm == 0 && !this.worldObj.isRemote) { - this.worldObj.setEntityState(this, (byte) 1); - } - - ++this.field_175540_bm; - } else if (this.field_175535_bn != 0) { - this.field_175540_bm = 0; - this.field_175535_bn = 0; - } - - } - - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); nbttagcompound.setInteger("RabbitType", this.getRabbitType()); nbttagcompound.setInteger("MoreCarrotTicks", this.carrotTicks); } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setRabbitType(nbttagcompound.getInteger("RabbitType")); - this.carrotTicks = nbttagcompound.getInteger("MoreCarrotTicks"); - } - - protected String getJumpingSound() { - return "mob.rabbit.hop"; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.rabbit.idle"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.rabbit.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.rabbit.death"; - } - - public boolean attackEntityAsMob(Entity entity) { - if (this.getRabbitType() == 99) { - this.playSound("mob.attack", 1.0F, (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); - return entity.attackEntityFrom(DamageSource.causeMobDamage(this), 8.0F); - } else { - return entity.attackEntityFrom(DamageSource.causeMobDamage(this), 3.0F); - } - } - - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - return this.getRabbitType() == 99 ? 8 : super.getTotalArmorValue(); - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - return this.isEntityInvulnerable(damagesource) ? false : super.attackEntityFrom(damagesource, f); - } - - /**+ - * Causes this Entity to drop a random item. - */ - protected void addRandomDrop() { - this.entityDropItem(new ItemStack(Items.rabbit_foot, 1), 0.0F); - } - - /**+ - * Drop 0-2 items of this living's type - */ - protected void dropFewItems(boolean var1, int i) { - int j = this.rand.nextInt(2) + this.rand.nextInt(1 + i); - - for (int k = 0; k < j; ++k) { - this.dropItem(Items.rabbit_hide, 1); - } - - j = this.rand.nextInt(2); - - for (int l = 0; l < j; ++l) { - if (this.isBurning()) { - this.dropItem(Items.cooked_rabbit, 1); - } else { - this.dropItem(Items.rabbit, 1); - } - } - - } - - private boolean isRabbitBreedingItem(Item itemIn) { - return itemIn == Items.carrot || itemIn == Items.golden_carrot - || itemIn == Item.getItemFromBlock(Blocks.yellow_flower); - } - - public EntityRabbit createChild(EntityAgeable entityageable) { - EntityRabbit entityrabbit = new EntityRabbit(this.worldObj); - if (entityageable instanceof EntityRabbit) { - entityrabbit.setRabbitType( - this.rand.nextBoolean() ? this.getRabbitType() : ((EntityRabbit) entityageable).getRabbitType()); - } - - return entityrabbit; - } - - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) - */ - public boolean isBreedingItem(ItemStack itemstack) { - return itemstack != null && this.isRabbitBreedingItem(itemstack.getItem()); - } - - public int getRabbitType() { - return this.dataWatcher.getWatchableObjectByte(18); - } - - public void setRabbitType(int rabbitTypeId) { - if (rabbitTypeId == 99) { - this.tasks.removeTask(this.aiAvoidWolves); - this.tasks.addTask(4, new EntityRabbit.AIEvilAttack(this)); - this.targetTasks.addTask(1, new EntityAIHurtByTarget(this, false, new Class[0])); - this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityPlayer.class, true)); - this.targetTasks.addTask(2, new EntityAINearestAttackableTarget(this, EntityWolf.class, true)); - if (!this.hasCustomName()) { - this.setCustomNameTag(StatCollector.translateToLocal("entity.KillerBunny.name")); - } - } - - this.dataWatcher.updateObject(18, Byte.valueOf((byte) rabbitTypeId)); - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); - int i = this.rand.nextInt(6); - boolean flag = false; - if (ientitylivingdata instanceof EntityRabbit.RabbitTypeData) { - i = ((EntityRabbit.RabbitTypeData) ientitylivingdata).typeData; - flag = true; - } else { - ientitylivingdata = new EntityRabbit.RabbitTypeData(i); - } - - this.setRabbitType(i); - if (flag) { - this.setGrowingAge(-24000); - } - - return ientitylivingdata; - } - - /**+ - * Returns true if {@link - * net.minecraft.entity.passive.EntityRabbit#carrotTicks - * carrotTicks} has reached zero - */ - private boolean isCarrotEaten() { - return this.carrotTicks == 0; - } - - /**+ - * Returns duration of the current {@link - * net.minecraft.entity.passive.EntityRabbit.EnumMoveType move - * type} - */ - protected int getMoveTypeDuration() { - return this.moveType.getDuration(); - } - - protected void createEatingParticles() { - this.worldObj.spawnParticle(EnumParticleTypes.BLOCK_DUST, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, - this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), - this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, 0.0D, 0.0D, - 0.0D, new int[] { Block.getStateId(Blocks.carrots.getStateFromMeta(7)) }); - this.carrotTicks = 100; - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 1) { - this.createRunningParticles(); - this.field_175535_bn = 10; - this.field_175540_bm = 0; - } else { - super.handleStatusUpdate(b0); - } - - } - - static class AIAvoidEntity extends EntityAIAvoidEntity { - private EntityRabbit entityInstance; - - public AIAvoidEntity(EntityRabbit parEntityRabbit, Class parClass1, float parFloat1, double parDouble1, - double parDouble2) { - super(parEntityRabbit, parClass1, parFloat1, parDouble1, parDouble2); - this.entityInstance = parEntityRabbit; - } - - public void updateTask() { - super.updateTask(); - } - } - - static class AIEvilAttack extends EntityAIAttackOnCollide { - public AIEvilAttack(EntityRabbit parEntityRabbit) { - super(parEntityRabbit, EntityLivingBase.class, 1.4D, true); - } - - protected double func_179512_a(EntityLivingBase entitylivingbase) { - return (double) (4.0F + entitylivingbase.width); - } - } - - static class AIPanic extends EntityAIPanic { - private EntityRabbit theEntity; - - public AIPanic(EntityRabbit parEntityRabbit, double speedIn) { - super(parEntityRabbit, speedIn); - this.theEntity = parEntityRabbit; - } - - public void updateTask() { - super.updateTask(); - this.theEntity.setMovementSpeed(this.speed); - } - } - - static class AIRaidFarm extends EntityAIMoveToBlock { - private final EntityRabbit field_179500_c; - private boolean field_179498_d; - private boolean field_179499_e = false; - - public AIRaidFarm(EntityRabbit parEntityRabbit) { - super(parEntityRabbit, 0.699999988079071D, 16); - this.field_179500_c = parEntityRabbit; - } - - public boolean shouldExecute() { - if (this.runDelay <= 0) { - if (!this.field_179500_c.worldObj.getGameRules().getBoolean("mobGriefing")) { - return false; - } - - this.field_179499_e = false; - this.field_179498_d = this.field_179500_c.isCarrotEaten(); - } - - return super.shouldExecute(); - } - - public boolean continueExecuting() { - return this.field_179499_e && super.continueExecuting(); - } - - public void startExecuting() { - super.startExecuting(); - } - - public void resetTask() { - super.resetTask(); - } - - public void updateTask() { - super.updateTask(); - this.field_179500_c.getLookHelper().setLookPosition((double) this.destinationBlock.getX() + 0.5D, - (double) (this.destinationBlock.getY() + 1), (double) this.destinationBlock.getZ() + 0.5D, 10.0F, - (float) this.field_179500_c.getVerticalFaceSpeed()); - if (this.getIsAboveDestination()) { - World world = this.field_179500_c.worldObj; - BlockPos blockpos = this.destinationBlock.up(); - IBlockState iblockstate = world.getBlockState(blockpos); - Block block = iblockstate.getBlock(); - if (this.field_179499_e && block instanceof BlockCarrot - && ((Integer) iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7) { - world.setBlockState(blockpos, Blocks.air.getDefaultState(), 2); - world.destroyBlock(blockpos, true); - this.field_179500_c.createEatingParticles(); - } - - this.field_179499_e = false; - this.runDelay = 10; - } - - } - - protected boolean shouldMoveTo(World world, BlockPos blockpos) { - Block block = world.getBlockState(blockpos).getBlock(); - if (block == Blocks.farmland) { - blockpos = blockpos.up(); - IBlockState iblockstate = world.getBlockState(blockpos); - block = iblockstate.getBlock(); - if (block instanceof BlockCarrot && ((Integer) iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7 - && this.field_179498_d && !this.field_179499_e) { - this.field_179499_e = true; - return true; - } - } - - return false; - } - } - - static enum EnumMoveType { - NONE(0.0F, 0.0F, 30, 1), HOP(0.8F, 0.2F, 20, 10), STEP(1.0F, 0.45F, 14, 14), SPRINT(1.75F, 0.4F, 1, 8), - ATTACK(2.0F, 0.7F, 7, 8); - - private final float speed; - private final float field_180077_g; - private final int duration; - private final int field_180085_i; - - private EnumMoveType(float typeSpeed, float parFloat1, int typeDuration, int parInt1) { - this.speed = typeSpeed; - this.field_180077_g = parFloat1; - this.duration = typeDuration; - this.field_180085_i = parInt1; - } - - public float getSpeed() { - return this.speed; - } - - public float func_180074_b() { - return this.field_180077_g; - } - - public int getDuration() { - return this.duration; - } - - public int func_180073_d() { - return this.field_180085_i; - } - } - - public class RabbitJumpHelper extends EntityJumpHelper { - private EntityRabbit theEntity; - private boolean field_180068_d = false; - - public RabbitJumpHelper(EntityRabbit rabbit) { - super(rabbit); - this.theEntity = rabbit; - } - - public boolean getIsJumping() { - return this.isJumping; - } - - public boolean func_180065_d() { - return this.field_180068_d; - } - - public void func_180066_a(boolean parFlag) { - this.field_180068_d = parFlag; - } - - public void doJump() { - if (this.isJumping) { - this.theEntity.doMovementAction(EntityRabbit.EnumMoveType.STEP); - this.isJumping = false; - } - - } - } - - static class RabbitMoveHelper extends EntityMoveHelper { - private EntityRabbit theEntity; - - public RabbitMoveHelper(EntityRabbit parEntityRabbit) { - super(parEntityRabbit); - this.theEntity = parEntityRabbit; - } - - public void onUpdateMoveHelper() { - if (this.theEntity.onGround && !this.theEntity.func_175523_cj()) { - this.theEntity.setMovementSpeed(0.0D); - } - - super.onUpdateMoveHelper(); - } - } - - public static class RabbitTypeData implements IEntityLivingData { - public int typeData; - - public RabbitTypeData(int type) { - this.typeData = type; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntitySheep.java b/src/game/java/net/minecraft/entity/passive/EntitySheep.java index 1b3f2acc..e7d04ec5 100644 --- a/src/game/java/net/minecraft/entity/passive/EntitySheep.java +++ b/src/game/java/net/minecraft/entity/passive/EntitySheep.java @@ -1,7 +1,9 @@ package net.minecraft.entity.passive; -import com.google.common.collect.Maps; import java.util.Map; + +import com.google.common.collect.Maps; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.entity.EntityAgeable; @@ -33,44 +35,79 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySheep extends EntityAnimal { - /**+ - * Internal crafting inventory used to check the result of - * mixing dyes corresponding to the fleece color when breeding - * sheep. + private static final Map DYE_TO_RGB = Maps.newEnumMap(EnumDyeColor.class); + static { + DYE_TO_RGB.put(EnumDyeColor.WHITE, new float[] { 1.0F, 1.0F, 1.0F }); + DYE_TO_RGB.put(EnumDyeColor.ORANGE, new float[] { 0.85F, 0.5F, 0.2F }); + DYE_TO_RGB.put(EnumDyeColor.MAGENTA, new float[] { 0.7F, 0.3F, 0.85F }); + DYE_TO_RGB.put(EnumDyeColor.LIGHT_BLUE, new float[] { 0.4F, 0.6F, 0.85F }); + DYE_TO_RGB.put(EnumDyeColor.YELLOW, new float[] { 0.9F, 0.9F, 0.2F }); + DYE_TO_RGB.put(EnumDyeColor.LIME, new float[] { 0.5F, 0.8F, 0.1F }); + DYE_TO_RGB.put(EnumDyeColor.PINK, new float[] { 0.95F, 0.5F, 0.65F }); + DYE_TO_RGB.put(EnumDyeColor.GRAY, new float[] { 0.3F, 0.3F, 0.3F }); + DYE_TO_RGB.put(EnumDyeColor.SILVER, new float[] { 0.6F, 0.6F, 0.6F }); + DYE_TO_RGB.put(EnumDyeColor.CYAN, new float[] { 0.3F, 0.5F, 0.6F }); + DYE_TO_RGB.put(EnumDyeColor.PURPLE, new float[] { 0.5F, 0.25F, 0.7F }); + DYE_TO_RGB.put(EnumDyeColor.BLUE, new float[] { 0.2F, 0.3F, 0.7F }); + DYE_TO_RGB.put(EnumDyeColor.BROWN, new float[] { 0.4F, 0.3F, 0.2F }); + DYE_TO_RGB.put(EnumDyeColor.GREEN, new float[] { 0.4F, 0.5F, 0.2F }); + DYE_TO_RGB.put(EnumDyeColor.RED, new float[] { 0.6F, 0.2F, 0.2F }); + DYE_TO_RGB.put(EnumDyeColor.BLACK, new float[] { 0.1F, 0.1F, 0.1F }); + } + + public static float[] func_175513_a(EnumDyeColor dyeColor) { + return (float[]) DYE_TO_RGB.get(dyeColor); + } + + /** + * + Chooses a "vanilla" sheep color based on the provided random. + */ + public static EnumDyeColor getRandomSheepColor(EaglercraftRandom random) { + int i = random.nextInt(100); + return i < 5 ? EnumDyeColor.BLACK + : (i < 10 ? EnumDyeColor.GRAY + : (i < 15 ? EnumDyeColor.SILVER + : (i < 18 ? EnumDyeColor.BROWN + : (random.nextInt(500) == 0 ? EnumDyeColor.PINK : EnumDyeColor.WHITE)))); + } + + /** + * + Internal crafting inventory used to check the result of mixing dyes + * corresponding to the fleece color when breeding sheep. */ private final InventoryCrafting inventoryCrafting = new InventoryCrafting(new Container() { public boolean canInteractWith(EntityPlayer var1) { return false; } }, 2, 1); - private static final Map DYE_TO_RGB = Maps.newEnumMap(EnumDyeColor.class); - private int sheepTimer; - private EntityAIEatGrass entityAIEatGrass = new EntityAIEatGrass(this); - public static float[] func_175513_a(EnumDyeColor dyeColor) { - return (float[]) DYE_TO_RGB.get(dyeColor); - } + private int sheepTimer; + + private EntityAIEatGrass entityAIEatGrass = new EntityAIEatGrass(this); public EntitySheep(World worldIn) { super(worldIn); @@ -89,37 +126,21 @@ public class EntitySheep extends EntityAnimal { this.inventoryCrafting.setInventorySlotContents(1, new ItemStack(Items.dye, 1, 0)); } - protected void updateAITasks() { - this.sheepTimer = this.entityAIEatGrass.getEatingGrassTimer(); - super.updateAITasks(); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - if (this.worldObj.isRemote) { - this.sheepTimer = Math.max(0, this.sheepTimer - 1); - } - - super.onLivingUpdate(); - } - protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.23000000417232513D); } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + public EntitySheep createChild(EntityAgeable entityageable) { + EntitySheep entitysheep = (EntitySheep) entityageable; + EntitySheep entitysheep1 = new EntitySheep(this.worldObj); + entitysheep1.setFleeceColor(this.getDyeColorMixFromParents(this, entitysheep)); + return entitysheep1; } - /**+ - * Drop 0-2 items of this living's type + /** + * + Drop 0-2 items of this living's type */ protected void dropFewItems(boolean var1, int i) { if (!this.getSheared()) { @@ -139,24 +160,63 @@ public class EntitySheep extends EntityAnimal { } - protected Item getDropItem() { - return Item.getItemFromBlock(Blocks.wool); - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 10) { - this.sheepTimer = 40; - } else { - super.handleStatusUpdate(b0); + /** + * + This function applies the benefits of growing back wool and faster growing + * up to the acting entity. (This function is used in the AIEatGrass) + */ + public void eatGrassBonus() { + this.setSheared(false); + if (this.isChild()) { + this.addGrowth(60); } } - public float getHeadRotationPointY(float parFloat1) { - return this.sheepTimer <= 0 ? 0.0F - : (this.sheepTimer >= 4 && this.sheepTimer <= 36 ? 1.0F - : (this.sheepTimer < 4 ? ((float) this.sheepTimer - parFloat1) / 4.0F - : -((float) (this.sheepTimer - 40) - parFloat1) / 4.0F)); + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "mob.sheep.say"; + } + + protected Item getDropItem() { + return Item.getItemFromBlock(Blocks.wool); + } + + /** + * + Attempts to mix both parent sheep to come up with a mixed dye color. + */ + private EnumDyeColor getDyeColorMixFromParents(EntityAnimal father, EntityAnimal mother) { + int i = ((EntitySheep) father).getFleeceColor().getDyeDamage(); + int j = ((EntitySheep) mother).getFleeceColor().getDyeDamage(); + this.inventoryCrafting.getStackInSlot(0).setItemDamage(i); + this.inventoryCrafting.getStackInSlot(1).setItemDamage(j); + ItemStack itemstack = CraftingManager.getInstance().findMatchingRecipe(this.inventoryCrafting, + ((EntitySheep) father).worldObj); + int k; + if (itemstack != null && itemstack.getItem() == Items.dye) { + k = itemstack.getMetadata(); + } else { + k = this.worldObj.rand.nextBoolean() ? i : j; + } + + return EnumDyeColor.byDyeDamage(k); + } + + public float getEyeHeight() { + return 0.95F * this.height; + } + + /** + * + Gets the wool color of this sheep. + */ + public EnumDyeColor getFleeceColor() { + return EnumDyeColor.byMetadata(this.dataWatcher.getWatchableObjectByte(16) & 15); } public float getHeadRotationAngleX(float parFloat1) { @@ -168,9 +228,46 @@ public class EntitySheep extends EntityAnimal { } } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + public float getHeadRotationPointY(float parFloat1) { + return this.sheepTimer <= 0 ? 0.0F + : (this.sheepTimer >= 4 && this.sheepTimer <= 36 ? 1.0F + : (this.sheepTimer < 4 ? ((float) this.sheepTimer - parFloat1) / 4.0F + : -((float) (this.sheepTimer - 40) - parFloat1) / 4.0F)); + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.sheep.say"; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return "mob.sheep.say"; + } + + /** + * + returns true if a sheeps wool has been sheared + */ + public boolean getSheared() { + return (this.dataWatcher.getWatchableObjectByte(16) & 16) != 0; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 10) { + this.sheepTimer = 40; + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -196,19 +293,37 @@ public class EntitySheep extends EntityAnimal { return super.interact(entityplayer); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("Sheared", this.getSheared()); - nbttagcompound.setByte("Color", (byte) this.getFleeceColor().getMetadata()); + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); + this.setFleeceColor(getRandomSheepColor(this.worldObj.rand)); + return ientitylivingdata; } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + if (this.worldObj.isRemote) { + this.sheepTimer = Math.max(0, this.sheepTimer - 1); + } + + super.onLivingUpdate(); + } + + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.sheep.step", 0.15F, 1.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -216,55 +331,16 @@ public class EntitySheep extends EntityAnimal { this.setFleeceColor(EnumDyeColor.byMetadata(nbttagcompound.getByte("Color"))); } - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return "mob.sheep.say"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.sheep.say"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.sheep.say"; - } - - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.sheep.step", 0.15F, 1.0F); - } - - /**+ - * Gets the wool color of this sheep. - */ - public EnumDyeColor getFleeceColor() { - return EnumDyeColor.byMetadata(this.dataWatcher.getWatchableObjectByte(16) & 15); - } - - /**+ - * Sets the wool color of this sheep + /** + * + Sets the wool color of this sheep */ public void setFleeceColor(EnumDyeColor color) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & 240 | color.getMetadata() & 15))); } - /**+ - * returns true if a sheeps wool has been sheared - */ - public boolean getSheared() { - return (this.dataWatcher.getWatchableObjectByte(16) & 16) != 0; - } - - /**+ - * make a sheep sheared if set to true + /** + * + make a sheep sheared if set to true */ public void setSheared(boolean sheared) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); @@ -276,92 +352,17 @@ public class EntitySheep extends EntityAnimal { } - /**+ - * Chooses a "vanilla" sheep color based on the provided random. + protected void updateAITasks() { + this.sheepTimer = this.entityAIEatGrass.getEatingGrassTimer(); + super.updateAITasks(); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public static EnumDyeColor getRandomSheepColor(EaglercraftRandom random) { - int i = random.nextInt(100); - return i < 5 ? EnumDyeColor.BLACK - : (i < 10 ? EnumDyeColor.GRAY - : (i < 15 ? EnumDyeColor.SILVER - : (i < 18 ? EnumDyeColor.BROWN - : (random.nextInt(500) == 0 ? EnumDyeColor.PINK : EnumDyeColor.WHITE)))); - } - - public EntitySheep createChild(EntityAgeable entityageable) { - EntitySheep entitysheep = (EntitySheep) entityageable; - EntitySheep entitysheep1 = new EntitySheep(this.worldObj); - entitysheep1.setFleeceColor(this.getDyeColorMixFromParents(this, entitysheep)); - return entitysheep1; - } - - /**+ - * This function applies the benefits of growing back wool and - * faster growing up to the acting entity. (This function is - * used in the AIEatGrass) - */ - public void eatGrassBonus() { - this.setSheared(false); - if (this.isChild()) { - this.addGrowth(60); - } - - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); - this.setFleeceColor(getRandomSheepColor(this.worldObj.rand)); - return ientitylivingdata; - } - - /**+ - * Attempts to mix both parent sheep to come up with a mixed dye - * color. - */ - private EnumDyeColor getDyeColorMixFromParents(EntityAnimal father, EntityAnimal mother) { - int i = ((EntitySheep) father).getFleeceColor().getDyeDamage(); - int j = ((EntitySheep) mother).getFleeceColor().getDyeDamage(); - this.inventoryCrafting.getStackInSlot(0).setItemDamage(i); - this.inventoryCrafting.getStackInSlot(1).setItemDamage(j); - ItemStack itemstack = CraftingManager.getInstance().findMatchingRecipe(this.inventoryCrafting, - ((EntitySheep) father).worldObj); - int k; - if (itemstack != null && itemstack.getItem() == Items.dye) { - k = itemstack.getMetadata(); - } else { - k = this.worldObj.rand.nextBoolean() ? i : j; - } - - return EnumDyeColor.byDyeDamage(k); - } - - public float getEyeHeight() { - return 0.95F * this.height; - } - - static { - DYE_TO_RGB.put(EnumDyeColor.WHITE, new float[] { 1.0F, 1.0F, 1.0F }); - DYE_TO_RGB.put(EnumDyeColor.ORANGE, new float[] { 0.85F, 0.5F, 0.2F }); - DYE_TO_RGB.put(EnumDyeColor.MAGENTA, new float[] { 0.7F, 0.3F, 0.85F }); - DYE_TO_RGB.put(EnumDyeColor.LIGHT_BLUE, new float[] { 0.4F, 0.6F, 0.85F }); - DYE_TO_RGB.put(EnumDyeColor.YELLOW, new float[] { 0.9F, 0.9F, 0.2F }); - DYE_TO_RGB.put(EnumDyeColor.LIME, new float[] { 0.5F, 0.8F, 0.1F }); - DYE_TO_RGB.put(EnumDyeColor.PINK, new float[] { 0.95F, 0.5F, 0.65F }); - DYE_TO_RGB.put(EnumDyeColor.GRAY, new float[] { 0.3F, 0.3F, 0.3F }); - DYE_TO_RGB.put(EnumDyeColor.SILVER, new float[] { 0.6F, 0.6F, 0.6F }); - DYE_TO_RGB.put(EnumDyeColor.CYAN, new float[] { 0.3F, 0.5F, 0.6F }); - DYE_TO_RGB.put(EnumDyeColor.PURPLE, new float[] { 0.5F, 0.25F, 0.7F }); - DYE_TO_RGB.put(EnumDyeColor.BLUE, new float[] { 0.2F, 0.3F, 0.7F }); - DYE_TO_RGB.put(EnumDyeColor.BROWN, new float[] { 0.4F, 0.3F, 0.2F }); - DYE_TO_RGB.put(EnumDyeColor.GREEN, new float[] { 0.4F, 0.5F, 0.2F }); - DYE_TO_RGB.put(EnumDyeColor.RED, new float[] { 0.6F, 0.2F, 0.2F }); - DYE_TO_RGB.put(EnumDyeColor.BLACK, new float[] { 0.1F, 0.1F, 0.1F }); + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("Sheared", this.getSheared()); + nbttagcompound.setByte("Color", (byte) this.getFleeceColor().getMetadata()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntitySquid.java b/src/game/java/net/minecraft/entity/passive/EntitySquid.java index 03b7e3c3..0ed7096d 100644 --- a/src/game/java/net/minecraft/entity/passive/EntitySquid.java +++ b/src/game/java/net/minecraft/entity/passive/EntitySquid.java @@ -10,27 +10,56 @@ import net.minecraft.item.ItemStack; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntitySquid extends EntityWaterMob { + static class AIMoveRandom extends EntityAIBase { + private EntitySquid squid; + + public AIMoveRandom(EntitySquid parEntitySquid) { + this.squid = parEntitySquid; + } + + public boolean shouldExecute() { + return true; + } + + public void updateTask() { + int i = this.squid.getAge(); + if (i > 100) { + this.squid.func_175568_b(0.0F, 0.0F, 0.0F); + } else if (this.squid.getRNG().nextInt(50) == 0 || !this.squid.inWater || !this.squid.func_175567_n()) { + float f = this.squid.getRNG().nextFloat() * 3.1415927F * 2.0F; + float f1 = MathHelper.cos(f) * 0.2F; + float f2 = -0.1F + this.squid.getRNG().nextFloat() * 0.2F; + float f3 = MathHelper.sin(f) * 0.2F; + this.squid.func_175568_b(f1, f2, f3); + } + + } + } + public float squidPitch; public float prevSquidPitch; public float squidYaw; @@ -44,6 +73,7 @@ public class EntitySquid extends EntityWaterMob { private float field_70871_bB; private float randomMotionVecX; private float randomMotionVecY; + private float randomMotionVecZ; public EntitySquid(World worldIn) { @@ -59,53 +89,16 @@ public class EntitySquid extends EntityWaterMob { this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(10.0D); } - public float getEyeHeight() { - return this.height * 0.5F; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return null; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return null; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return null; - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 0.4F; - } - - protected Item getDropItem() { - return null; - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops */ protected boolean canTriggerWalking() { return false; } - /**+ - * Drop 0-2 items of this living's type + /** + * + Drop 0-2 items of this living's type */ protected void dropFewItems(boolean var1, int i) { int j = this.rand.nextInt(3 + i) + 1; @@ -116,19 +109,89 @@ public class EntitySquid extends EntityWaterMob { } - /**+ - * Checks if this entity is inside water (if inWater field is - * true as a result of handleWaterMovement() returning true) + public boolean func_175567_n() { + return this.randomMotionVecX != 0.0F || this.randomMotionVecY != 0.0F || this.randomMotionVecZ != 0.0F; + } + + public void func_175568_b(float randomMotionVecXIn, float randomMotionVecYIn, float randomMotionVecZIn) { + this.randomMotionVecX = randomMotionVecXIn; + this.randomMotionVecY = randomMotionVecYIn; + this.randomMotionVecZ = randomMotionVecZIn; + } + + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return this.posY > 45.0D && this.posY < (double) this.worldObj.func_181545_F() && super.getCanSpawnHere(); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return null; + } + + protected Item getDropItem() { + return null; + } + + public float getEyeHeight() { + return this.height * 0.5F; + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return null; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return null; + } + + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.4F; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 19) { + this.squidRotation = 0.0F; + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Checks if this entity is inside water (if inWater field is true as a result + * of handleWaterMovement() returning true) */ public boolean isInWater() { return this.worldObj.handleMaterialAcceleration( this.getEntityBoundingBox().expand(0.0D, -0.6000000238418579D, 0.0D), Material.water, this); } - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. + /** + * + Moves the entity based on the specified heading. Args: strafe, forward + */ + public void moveEntityWithHeading(float var1, float var2) { + this.moveEntity(this.motionX, this.motionY, this.motionZ); + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ public void onLivingUpdate() { super.onLivingUpdate(); @@ -192,65 +255,4 @@ public class EntitySquid extends EntityWaterMob { } } - - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward - */ - public void moveEntityWithHeading(float var1, float var2) { - this.moveEntity(this.motionX, this.motionY, this.motionZ); - } - - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return this.posY > 45.0D && this.posY < (double) this.worldObj.func_181545_F() && super.getCanSpawnHere(); - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 19) { - this.squidRotation = 0.0F; - } else { - super.handleStatusUpdate(b0); - } - - } - - public void func_175568_b(float randomMotionVecXIn, float randomMotionVecYIn, float randomMotionVecZIn) { - this.randomMotionVecX = randomMotionVecXIn; - this.randomMotionVecY = randomMotionVecYIn; - this.randomMotionVecZ = randomMotionVecZIn; - } - - public boolean func_175567_n() { - return this.randomMotionVecX != 0.0F || this.randomMotionVecY != 0.0F || this.randomMotionVecZ != 0.0F; - } - - static class AIMoveRandom extends EntityAIBase { - private EntitySquid squid; - - public AIMoveRandom(EntitySquid parEntitySquid) { - this.squid = parEntitySquid; - } - - public boolean shouldExecute() { - return true; - } - - public void updateTask() { - int i = this.squid.getAge(); - if (i > 100) { - this.squid.func_175568_b(0.0F, 0.0F, 0.0F); - } else if (this.squid.getRNG().nextInt(50) == 0 || !this.squid.inWater || !this.squid.func_175567_n()) { - float f = this.squid.getRNG().nextFloat() * 3.1415927F * 2.0F; - float f1 = MathHelper.cos(f) * 0.2F; - float f2 = -0.1F + this.squid.getRNG().nextFloat() * 0.2F; - float f3 = MathHelper.sin(f) * 0.2F; - this.squid.func_175568_b(f1, f2, f3); - } - - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityTameable.java b/src/game/java/net/minecraft/entity/passive/EntityTameable.java index e779cc1b..094fd6f3 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityTameable.java +++ b/src/game/java/net/minecraft/entity/passive/EntityTameable.java @@ -14,22 +14,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,32 +52,115 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna this.dataWatcher.addObject(17, ""); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Returns the AITask responsible of the sit logic */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - if (worldObj.isRemote && !SingleplayerServerController.isClientInEaglerSingleplayerOrLAN()) { - if (this.getOwnerId() == null) { - nbttagcompound.setString("OwnerUUID", ""); - } else { - nbttagcompound.setString("OwnerUUID", this.getOwnerId()); - } - } else { - if (this.getOwnerId() == null) { - nbttagcompound.setString("Owner", ""); - } else { - nbttagcompound.setString("Owner", this.getOwnerId()); + public EntityAISit getAISit() { + return this.aiSit; + } + + public EntityLivingBase getOwner() { + String ownerName = this.getOwnerId(); + if (StringUtils.isEmpty(ownerName)) { + return null; + } + try { + EaglercraftUUID uuid = EaglercraftUUID.fromString(ownerName); + return uuid == null ? null : this.worldObj.getPlayerEntityByUUID(uuid); + } catch (IllegalArgumentException var2) { + return this.worldObj.getPlayerEntityByName(ownerName); + } + } + + public String getOwnerId() { + return this.dataWatcher.getWatchableObjectString(17); + } + + public Team getTeam() { + if (this.isTamed()) { + EntityLivingBase entitylivingbase = this.getOwner(); + if (entitylivingbase != null) { + return entitylivingbase.getTeam(); } } - nbttagcompound.setBoolean("Sitting", this.isSitting()); + return super.getTeam(); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + public void handleStatusUpdate(byte b0) { + if (b0 == 7) { + this.playTameEffect(true); + } else if (b0 == 6) { + this.playTameEffect(false); + } else { + super.handleStatusUpdate(b0); + } + + } + + public boolean isOnSameTeam(EntityLivingBase entitylivingbase) { + if (this.isTamed()) { + EntityLivingBase entitylivingbase1 = this.getOwner(); + if (entitylivingbase == entitylivingbase1) { + return true; + } + + if (entitylivingbase1 != null) { + return entitylivingbase1.isOnSameTeam(entitylivingbase); + } + } + + return super.isOnSameTeam(entitylivingbase); + } + + public boolean isOwner(EntityLivingBase entityIn) { + return entityIn == this.getOwner(); + } + + public boolean isSitting() { + return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; + } + + public boolean isTamed() { + return (this.dataWatcher.getWatchableObjectByte(16) & 4) != 0; + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + if (!this.worldObj.isRemote && this.worldObj.getGameRules().getBoolean("showDeathMessages") + && this.hasCustomName() && this.getOwner() instanceof EntityPlayerMP) { + ((EntityPlayerMP) this.getOwner()).addChatMessage(this.getCombatTracker().getDeathMessage()); + } + + super.onDeath(damagesource); + } + + /** + * + Play the taming effect, will either be hearts or smoke depending on status + */ + protected void playTameEffect(boolean play) { + EnumParticleTypes enumparticletypes = EnumParticleTypes.HEART; + if (!play) { + enumparticletypes = EnumParticleTypes.SMOKE_NORMAL; + } + + for (int i = 0; i < 7; ++i) { + double d0 = this.rand.nextGaussian() * 0.02D; + double d1 = this.rand.nextGaussian() * 0.02D; + double d2 = this.rand.nextGaussian() * 0.02D; + this.worldObj.spawnParticle(enumparticletypes, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, + this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), + this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, + new int[0]); + } + + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -98,44 +184,20 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna this.setSitting(nbttagcompound.getBoolean("Sitting")); } - /**+ - * Play the taming effect, will either be hearts or smoke - * depending on status - */ - protected void playTameEffect(boolean play) { - EnumParticleTypes enumparticletypes = EnumParticleTypes.HEART; - if (!play) { - enumparticletypes = EnumParticleTypes.SMOKE_NORMAL; - } - - for (int i = 0; i < 7; ++i) { - double d0 = this.rand.nextGaussian() * 0.02D; - double d1 = this.rand.nextGaussian() * 0.02D; - double d2 = this.rand.nextGaussian() * 0.02D; - this.worldObj.spawnParticle(enumparticletypes, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, - this.posY + 0.5D + (double) (this.rand.nextFloat() * this.height), - this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, - new int[0]); - } - + public void setOwnerId(String ownerUuid) { + this.dataWatcher.updateObject(17, ownerUuid); } - public void handleStatusUpdate(byte b0) { - if (b0 == 7) { - this.playTameEffect(true); - } else if (b0 == 6) { - this.playTameEffect(false); + public void setSitting(boolean sitting) { + byte b0 = this.dataWatcher.getWatchableObjectByte(16); + if (sitting) { + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1))); } else { - super.handleStatusUpdate(b0); + this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2))); } } - public boolean isTamed() { - return (this.dataWatcher.getWatchableObjectByte(16) & 4) != 0; - } - public void setTamed(boolean tamed) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); if (tamed) { @@ -150,91 +212,29 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna protected void setupTamedAI() { } - public boolean isSitting() { - return (this.dataWatcher.getWatchableObjectByte(16) & 1) != 0; - } - - public void setSitting(boolean sitting) { - byte b0 = this.dataWatcher.getWatchableObjectByte(16); - if (sitting) { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 | 1))); - } else { - this.dataWatcher.updateObject(16, Byte.valueOf((byte) (b0 & -2))); - } - - } - - public String getOwnerId() { - return this.dataWatcher.getWatchableObjectString(17); - } - - public void setOwnerId(String ownerUuid) { - this.dataWatcher.updateObject(17, ownerUuid); - } - - public EntityLivingBase getOwner() { - String ownerName = this.getOwnerId(); - if (StringUtils.isEmpty(ownerName)) { - return null; - } - try { - EaglercraftUUID uuid = EaglercraftUUID.fromString(ownerName); - return uuid == null ? null : this.worldObj.getPlayerEntityByUUID(uuid); - } catch (IllegalArgumentException var2) { - return this.worldObj.getPlayerEntityByName(ownerName); - } - } - - public boolean isOwner(EntityLivingBase entityIn) { - return entityIn == this.getOwner(); - } - - /**+ - * Returns the AITask responsible of the sit logic - */ - public EntityAISit getAISit() { - return this.aiSit; - } - public boolean shouldAttackEntity(EntityLivingBase parEntityLivingBase, EntityLivingBase parEntityLivingBase2) { return true; } - public Team getTeam() { - if (this.isTamed()) { - EntityLivingBase entitylivingbase = this.getOwner(); - if (entitylivingbase != null) { - return entitylivingbase.getTeam(); - } - } - - return super.getTeam(); - } - - public boolean isOnSameTeam(EntityLivingBase entitylivingbase) { - if (this.isTamed()) { - EntityLivingBase entitylivingbase1 = this.getOwner(); - if (entitylivingbase == entitylivingbase1) { - return true; - } - - if (entitylivingbase1 != null) { - return entitylivingbase1.isOnSameTeam(entitylivingbase); - } - } - - return super.isOnSameTeam(entitylivingbase); - } - - /**+ - * Called when the mob's health reaches 0. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public void onDeath(DamageSource damagesource) { - if (!this.worldObj.isRemote && this.worldObj.getGameRules().getBoolean("showDeathMessages") - && this.hasCustomName() && this.getOwner() instanceof EntityPlayerMP) { - ((EntityPlayerMP) this.getOwner()).addChatMessage(this.getCombatTracker().getDeathMessage()); + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + if (worldObj.isRemote && !SingleplayerServerController.isClientInEaglerSingleplayerOrLAN()) { + if (this.getOwnerId() == null) { + nbttagcompound.setString("OwnerUUID", ""); + } else { + nbttagcompound.setString("OwnerUUID", this.getOwnerId()); + } + } else { + if (this.getOwnerId() == null) { + nbttagcompound.setString("Owner", ""); + } else { + nbttagcompound.setString("Owner", this.getOwnerId()); + } } - super.onDeath(damagesource); + nbttagcompound.setBoolean("Sitting", this.isSitting()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityVillager.java b/src/game/java/net/minecraft/entity/passive/EntityVillager.java index b0532bfd..bd1ee510 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityVillager.java +++ b/src/game/java/net/minecraft/entity/passive/EntityVillager.java @@ -64,46 +64,173 @@ import net.minecraft.village.Village; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { - private int randomTickDivider; - private boolean isMating; - private boolean isPlaying; - Village villageObj; - private EntityPlayer buyingPlayer; - private MerchantRecipeList buyingList; - private int timeUntilReset; - private boolean needsInitilization; - private boolean isWillingToMate; - private int wealth; - private String lastBuyingPlayer; - private int careerId; - private int careerLevel; - private boolean isLookingForHome; - private boolean areAdditionalTasksSet; - private InventoryBasic villagerInventory; - /**+ - * A multi-dimensional array mapping the various professions, - * careers and career levels that a Villager may offer + static class EmeraldForItems implements EntityVillager.ITradeList { + public Item sellItem; + public EntityVillager.PriceInfo price; + + public EmeraldForItems(Item itemIn, EntityVillager.PriceInfo priceIn) { + this.sellItem = itemIn; + this.price = priceIn; + } + + public void modifyMerchantRecipeList(MerchantRecipeList recipeList, EaglercraftRandom random) { + int i = 1; + if (this.price != null) { + i = this.price.getPrice(random); + } + + recipeList.add(new MerchantRecipe(new ItemStack(this.sellItem, i, 0), Items.emerald)); + } + } + + static class ItemAndEmeraldToItem implements EntityVillager.ITradeList { + public ItemStack field_179411_a; + public EntityVillager.PriceInfo field_179409_b; + public ItemStack field_179410_c; + public EntityVillager.PriceInfo field_179408_d; + + public ItemAndEmeraldToItem(Item parItem, EntityVillager.PriceInfo parPriceInfo, Item parItem2, + EntityVillager.PriceInfo parPriceInfo2) { + this.field_179411_a = new ItemStack(parItem); + this.field_179409_b = parPriceInfo; + this.field_179410_c = new ItemStack(parItem2); + this.field_179408_d = parPriceInfo2; + } + + public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { + int i = 1; + if (this.field_179409_b != null) { + i = this.field_179409_b.getPrice(random); + } + + int j = 1; + if (this.field_179408_d != null) { + j = this.field_179408_d.getPrice(random); + } + + merchantrecipelist.add(new MerchantRecipe( + new ItemStack(this.field_179411_a.getItem(), i, this.field_179411_a.getMetadata()), + new ItemStack(Items.emerald), + new ItemStack(this.field_179410_c.getItem(), j, this.field_179410_c.getMetadata()))); + } + } + + interface ITradeList { + void modifyMerchantRecipeList(MerchantRecipeList var1, EaglercraftRandom var2); + } + + static class ListEnchantedBookForEmeralds implements EntityVillager.ITradeList { + public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { + Enchantment enchantment = Enchantment.enchantmentsBookList[random + .nextInt(Enchantment.enchantmentsBookList.length)]; + int i = MathHelper.getRandomIntegerInRange(random, enchantment.getMinLevel(), enchantment.getMaxLevel()); + ItemStack itemstack = Items.enchanted_book.getEnchantedItemStack(new EnchantmentData(enchantment, i)); + int j = 2 + random.nextInt(5 + i * 10) + 3 * i; + if (j > 64) { + j = 64; + } + + merchantrecipelist + .add(new MerchantRecipe(new ItemStack(Items.book), new ItemStack(Items.emerald, j), itemstack)); + } + } + + static class ListEnchantedItemForEmeralds implements EntityVillager.ITradeList { + public ItemStack field_179407_a; + public EntityVillager.PriceInfo field_179406_b; + + public ListEnchantedItemForEmeralds(Item parItem, EntityVillager.PriceInfo parPriceInfo) { + this.field_179407_a = new ItemStack(parItem); + this.field_179406_b = parPriceInfo; + } + + public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { + int i = 1; + if (this.field_179406_b != null) { + i = this.field_179406_b.getPrice(random); + } + + ItemStack itemstack = new ItemStack(Items.emerald, i, 0); + ItemStack itemstack1 = new ItemStack(this.field_179407_a.getItem(), 1, this.field_179407_a.getMetadata()); + itemstack1 = EnchantmentHelper.addRandomEnchantment(random, itemstack1, 5 + random.nextInt(15)); + merchantrecipelist.add(new MerchantRecipe(itemstack, itemstack1)); + } + } + + static class ListItemForEmeralds implements EntityVillager.ITradeList { + public ItemStack field_179403_a; + public EntityVillager.PriceInfo field_179402_b; + + public ListItemForEmeralds(Item par1Item, EntityVillager.PriceInfo priceInfo) { + this.field_179403_a = new ItemStack(par1Item); + this.field_179402_b = priceInfo; + } + + public ListItemForEmeralds(ItemStack stack, EntityVillager.PriceInfo priceInfo) { + this.field_179403_a = stack; + this.field_179402_b = priceInfo; + } + + public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { + int i = 1; + if (this.field_179402_b != null) { + i = this.field_179402_b.getPrice(random); + } + + ItemStack itemstack; + ItemStack itemstack1; + if (i < 0) { + itemstack = new ItemStack(Items.emerald, 1, 0); + itemstack1 = new ItemStack(this.field_179403_a.getItem(), -i, this.field_179403_a.getMetadata()); + } else { + itemstack = new ItemStack(Items.emerald, i, 0); + itemstack1 = new ItemStack(this.field_179403_a.getItem(), 1, this.field_179403_a.getMetadata()); + } + + merchantrecipelist.add(new MerchantRecipe(itemstack, itemstack1)); + } + } + + static class PriceInfo extends Tuple { + public PriceInfo(int parInt1, int parInt2) { + super(Integer.valueOf(parInt1), Integer.valueOf(parInt2)); + } + + public int getPrice(EaglercraftRandom rand) { + return ((Integer) this.getFirst()).intValue() >= ((Integer) this.getSecond()).intValue() + ? ((Integer) this.getFirst()).intValue() + : ((Integer) this.getFirst()).intValue() + rand.nextInt( + ((Integer) this.getSecond()).intValue() - ((Integer) this.getFirst()).intValue() + 1); + } + } + + /** + * + A multi-dimensional array mapping the various professions, careers and + * career levels that a Villager may offer */ private static List>>> DEFAULT_TRADE_LIST_MAP = null; @@ -312,6 +439,31 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { new EntityVillager.PriceInfo(8, 10)))))); } + private int randomTickDivider; + private boolean isMating; + private boolean isPlaying; + Village villageObj; + private EntityPlayer buyingPlayer; + private MerchantRecipeList buyingList; + private int timeUntilReset; + private boolean needsInitilization; + + private boolean isWillingToMate; + + private int wealth; + + private String lastBuyingPlayer; + + private int careerId; + + private int careerLevel; + + private boolean isLookingForHome; + + private boolean areAdditionalTasksSet; + + private InventoryBasic villagerInventory; + public EntityVillager(World worldIn) { this(worldIn, 0); } @@ -340,29 +492,8 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { this.setCanPickUpLoot(true); } - private void setAdditionalAItasks() { - if (!this.areAdditionalTasksSet) { - this.areAdditionalTasksSet = true; - if (this.isChild()) { - this.tasks.addTask(8, new EntityAIPlay(this, 0.32D)); - } else if (this.getProfession() == 0) { - this.tasks.addTask(6, new EntityAIHarvestFarmland(this, 0.6D)); - } - - } - } - - /**+ - * This is called when Entity's growing age timer reaches 0 - * (negative values are considered as a child, positive as an - * adult) - */ - protected void onGrowingAdult() { - if (this.getProfession() == 0) { - this.tasks.addTask(8, new EntityAIHarvestFarmland(this, 0.6D)); - } - - super.onGrowingAdult(); + public boolean allowLeashing() { + return false; } protected void applyEntityAttributes() { @@ -370,68 +501,32 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5D); } - protected void updateAITasks() { - if (--this.randomTickDivider <= 0) { - BlockPos blockpos = new BlockPos(this); - this.worldObj.getVillageCollection().addToVillagerPositionList(blockpos); - this.randomTickDivider = 70 + this.rand.nextInt(50); - this.villageObj = this.worldObj.getVillageCollection().getNearestVillage(blockpos, 32); - if (this.villageObj == null) { - this.detachHome(); - } else { - BlockPos blockpos1 = this.villageObj.getCenter(); - this.setHomePosAndDistance(blockpos1, (int) ((float) this.villageObj.getVillageRadius() * 1.0F)); - if (this.isLookingForHome) { - this.isLookingForHome = false; - this.villageObj.setDefaultPlayerReputation(5); - } - } - } - - if (!this.isTrading() && this.timeUntilReset > 0) { - --this.timeUntilReset; - if (this.timeUntilReset <= 0) { - if (this.needsInitilization) { - for (int i = 0, l = this.buyingList.size(); i < l; ++i) { - MerchantRecipe merchantrecipe = this.buyingList.get(i); - if (merchantrecipe.isRecipeDisabled()) { - merchantrecipe.increaseMaxTradeUses(this.rand.nextInt(6) + this.rand.nextInt(6) + 2); - } - } - - this.populateBuyingList(); - this.needsInitilization = false; - if (this.villageObj != null && this.lastBuyingPlayer != null) { - this.worldObj.setEntityState(this, (byte) 14); - this.villageObj.setReputationForPlayer(this.lastBuyingPlayer, 1); - } - } - - this.addPotionEffect(new PotionEffect(Potion.regeneration.id, 200, 0)); - } - } - - super.updateAITasks(); + /** + * + Used by {@link net.minecraft.entity.ai.EntityAIVillagerInteract + * EntityAIVillagerInteract} to check if the villager can give some items from + * an inventory to another villager. + */ + public boolean canAbondonItems() { + return this.hasEnoughItems(2); } - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + /** + * + Determines if an entity can be despawned, used on idle far away entities */ - public boolean interact(EntityPlayer entityplayer) { - ItemStack itemstack = entityplayer.inventory.getCurrentItem(); - boolean flag = itemstack != null && itemstack.getItem() == Items.spawn_egg; - if (!flag && this.isEntityAlive() && !this.isTrading() && !this.isChild()) { - if (!this.worldObj.isRemote && (this.buyingList == null || this.buyingList.size() > 0)) { - this.setCustomer(entityplayer); - entityplayer.displayVillagerTradeGui(this); - } + protected boolean canDespawn() { + return false; + } - entityplayer.triggerAchievement(StatList.timesTalkedToVillagerStat); - return true; - } else { - return super.interact(entityplayer); - } + private boolean canVillagerPickupItem(Item itemIn) { + return itemIn == Items.bread || itemIn == Items.potato || itemIn == Items.carrot || itemIn == Items.wheat + || itemIn == Items.wheat_seeds; + } + + public EntityVillager createChild(EntityAgeable var1) { + EntityVillager entityvillager = new EntityVillager(this.worldObj); + entityvillager.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entityvillager)), + (IEntityLivingData) null); + return entityvillager; } protected void entityInit() { @@ -439,303 +534,34 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { this.dataWatcher.addObject(16, Integer.valueOf(0)); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("Profession", this.getProfession()); - nbttagcompound.setInteger("Riches", this.wealth); - nbttagcompound.setInteger("Career", this.careerId); - nbttagcompound.setInteger("CareerLevel", this.careerLevel); - nbttagcompound.setBoolean("Willing", this.isWillingToMate); - if (this.buyingList != null) { - try { - nbttagcompound.setTag("Offers", this.buyingList.getRecipiesAsTags()); - } catch (Throwable t) { - this.buyingList = null; // workaround - } - } - - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.villagerInventory.getSizeInventory(); ++i) { - ItemStack itemstack = this.villagerInventory.getStackInSlot(i); - if (itemstack != null) { - nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound())); - } - } - - nbttagcompound.setTag("Inventory", nbttaglist); + public boolean func_175553_cp() { + return this.hasEnoughItems(1); } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setProfession(nbttagcompound.getInteger("Profession")); - this.wealth = nbttagcompound.getInteger("Riches"); - this.careerId = nbttagcompound.getInteger("Career"); - this.careerLevel = nbttagcompound.getInteger("CareerLevel"); - this.isWillingToMate = nbttagcompound.getBoolean("Willing"); - if (nbttagcompound.hasKey("Offers", 10)) { - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Offers"); - this.buyingList = new MerchantRecipeList(nbttagcompound1); - } - - NBTTagList nbttaglist = nbttagcompound.getTagList("Inventory", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); - if (itemstack != null) { - this.villagerInventory.func_174894_a(itemstack); - } - } - - this.setCanPickUpLoot(true); - this.setAdditionalAItasks(); - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return false; - } - - /**+ - * Returns the sound this mob makes while it's alive. - */ - protected String getLivingSound() { - return this.isTrading() ? "mob.villager.haggle" : "mob.villager.idle"; - } - - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "mob.villager.hit"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.villager.death"; - } - - public void setProfession(int professionId) { - this.dataWatcher.updateObject(16, Integer.valueOf(professionId)); - } - - public int getProfession() { - return Math.max(this.dataWatcher.getWatchableObjectInt(16) % 5, 0); - } - - public boolean isMating() { - return this.isMating; - } - - public void setMating(boolean mating) { - this.isMating = mating; - } - - public void setPlaying(boolean playing) { - this.isPlaying = playing; - } - - public boolean isPlaying() { - return this.isPlaying; - } - - public void setRevengeTarget(EntityLivingBase entitylivingbase) { - super.setRevengeTarget(entitylivingbase); - if (this.villageObj != null && entitylivingbase != null) { - this.villageObj.addOrRenewAgressor(entitylivingbase); - if (entitylivingbase instanceof EntityPlayer) { - byte b0 = -1; - if (this.isChild()) { - b0 = -3; - } - - this.villageObj.setReputationForPlayer(entitylivingbase.getName(), b0); - if (this.isEntityAlive()) { - this.worldObj.setEntityState(this, (byte) 13); - } - } - } - - } - - /**+ - * Called when the mob's health reaches 0. - */ - public void onDeath(DamageSource damagesource) { - if (this.villageObj != null) { - Entity entity = damagesource.getEntity(); - if (entity != null) { - if (entity instanceof EntityPlayer) { - this.villageObj.setReputationForPlayer(entity.getName(), -2); - } else if (entity instanceof IMob) { - this.villageObj.endMatingSeason(); - } - } else { - EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 16.0D); - if (entityplayer != null) { - this.villageObj.endMatingSeason(); - } - } - } - - super.onDeath(damagesource); - } - - public void setCustomer(EntityPlayer entityplayer) { - this.buyingPlayer = entityplayer; + public boolean func_175557_cr() { + boolean flag = this.getProfession() == 0; + return flag ? !this.hasEnoughItems(5) : !this.hasEnoughItems(1); } public EntityPlayer getCustomer() { return this.buyingPlayer; } - public boolean isTrading() { - return this.buyingPlayer != null; - } - - /**+ - * Returns current or updated value of {@link #isWillingToMate} + /** + * + Returns the sound this mob makes on death. */ - public boolean getIsWillingToMate(boolean updateFirst) { - if (!this.isWillingToMate && updateFirst && this.func_175553_cp()) { - boolean flag = false; - - for (int i = 0; i < this.villagerInventory.getSizeInventory(); ++i) { - ItemStack itemstack = this.villagerInventory.getStackInSlot(i); - if (itemstack != null) { - if (itemstack.getItem() == Items.bread && itemstack.stackSize >= 3) { - flag = true; - this.villagerInventory.decrStackSize(i, 3); - } else if ((itemstack.getItem() == Items.potato || itemstack.getItem() == Items.carrot) - && itemstack.stackSize >= 12) { - flag = true; - this.villagerInventory.decrStackSize(i, 12); - } - } - - if (flag) { - this.worldObj.setEntityState(this, (byte) 18); - this.isWillingToMate = true; - break; - } - } - } - - return this.isWillingToMate; + protected String getDeathSound() { + return "mob.villager.death"; } - public void setIsWillingToMate(boolean willingToTrade) { - this.isWillingToMate = willingToTrade; - } - - public void useRecipe(MerchantRecipe merchantrecipe) { - merchantrecipe.incrementToolUses(); - this.livingSoundTime = -this.getTalkInterval(); - this.playSound("mob.villager.yes", this.getSoundVolume(), this.getSoundPitch()); - int i = 3 + this.rand.nextInt(4); - if (merchantrecipe.getToolUses() == 1 || this.rand.nextInt(5) == 0) { - this.timeUntilReset = 40; - this.needsInitilization = true; - this.isWillingToMate = true; - if (this.buyingPlayer != null) { - this.lastBuyingPlayer = this.buyingPlayer.getName(); - } else { - this.lastBuyingPlayer = null; - } - - i += 5; - } - - if (merchantrecipe.getItemToBuy().getItem() == Items.emerald) { - this.wealth += merchantrecipe.getItemToBuy().stackSize; - } - - if (merchantrecipe.getRewardsExp()) { - this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY + 0.5D, this.posZ, i)); - } - - } - - /**+ - * Notifies the merchant of a possible merchantrecipe being - * fulfilled or not. Usually, this is just a sound byte being - * played depending if the suggested itemstack is not null. - */ - public void verifySellingItem(ItemStack itemstack) { - if (!this.worldObj.isRemote && this.livingSoundTime > -this.getTalkInterval() + 20) { - this.livingSoundTime = -this.getTalkInterval(); - if (itemstack != null) { - this.playSound("mob.villager.yes", this.getSoundVolume(), this.getSoundPitch()); - } else { - this.playSound("mob.villager.no", this.getSoundVolume(), this.getSoundPitch()); - } - } - - } - - public MerchantRecipeList getRecipes(EntityPlayer var1) { - if (this.buyingList == null) { - this.populateBuyingList(); - } - - return this.buyingList; - } - - private void populateBuyingList() { - List>> aentityvillager$itradelist = DEFAULT_TRADE_LIST_MAP - .get(this.getProfession()); - if (this.careerId != 0 && this.careerLevel != 0) { - ++this.careerLevel; - } else { - this.careerId = this.rand.nextInt(aentityvillager$itradelist.size()) + 1; - this.careerLevel = 1; - } - - if (this.buyingList == null) { - this.buyingList = new MerchantRecipeList(); - } - - int i = this.careerId - 1; - int j = this.careerLevel - 1; - List> aentityvillager$itradelist1 = aentityvillager$itradelist.get(i); - if (j >= 0 && j < aentityvillager$itradelist1.size()) { - List aentityvillager$itradelist2 = aentityvillager$itradelist1.get(j); - - for (int k = 0, l = aentityvillager$itradelist2.size(); k < l; ++k) { - aentityvillager$itradelist2.get(k).modifyMerchantRecipeList(this.buyingList, this.rand); - } - } - - } - - public void setRecipes(MerchantRecipeList var1) { - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat */ public IChatComponent getDisplayName() { return getDisplayNameImpl(false); } - public IChatComponent getDisplayNameProfanityFilter() { - return getDisplayNameImpl(true); - } - private IChatComponent getDisplayNameImpl(boolean filter) { String s = filter ? this.getCustomNameTagProfanityFilter() : this.getCustomNameTag(); if (s != null && s.length() > 0) { @@ -796,6 +622,10 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { } } + public IChatComponent getDisplayNameProfanityFilter() { + return getDisplayNameImpl(true); + } + public float getEyeHeight() { float f = 1.62F; if (this.isChild()) { @@ -805,6 +635,67 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { return f; } + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "mob.villager.hit"; + } + + /** + * + Returns current or updated value of {@link #isWillingToMate} + */ + public boolean getIsWillingToMate(boolean updateFirst) { + if (!this.isWillingToMate && updateFirst && this.func_175553_cp()) { + boolean flag = false; + + for (int i = 0; i < this.villagerInventory.getSizeInventory(); ++i) { + ItemStack itemstack = this.villagerInventory.getStackInSlot(i); + if (itemstack != null) { + if (itemstack.getItem() == Items.bread && itemstack.stackSize >= 3) { + flag = true; + this.villagerInventory.decrStackSize(i, 3); + } else if ((itemstack.getItem() == Items.potato || itemstack.getItem() == Items.carrot) + && itemstack.stackSize >= 12) { + flag = true; + this.villagerInventory.decrStackSize(i, 12); + } + } + + if (flag) { + this.worldObj.setEntityState(this, (byte) 18); + this.isWillingToMate = true; + break; + } + } + } + + return this.isWillingToMate; + } + + /** + * + Returns the sound this mob makes while it's alive. + */ + protected String getLivingSound() { + return this.isTrading() ? "mob.villager.haggle" : "mob.villager.idle"; + } + + public int getProfession() { + return Math.max(this.dataWatcher.getWatchableObjectInt(16) % 5, 0); + } + + public MerchantRecipeList getRecipes(EntityPlayer var1) { + if (this.buyingList == null) { + this.populateBuyingList(); + } + + return this.buyingList; + } + + public InventoryBasic getVillagerInventory() { + return this.villagerInventory; + } + public void handleStatusUpdate(byte b0) { if (b0 == 12) { this.spawnParticles(EnumParticleTypes.HEART); @@ -818,118 +709,8 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { } - private void spawnParticles(EnumParticleTypes particleType) { - for (int i = 0; i < 5; ++i) { - double d0 = this.rand.nextGaussian() * 0.02D; - double d1 = this.rand.nextGaussian() * 0.02D; - double d2 = this.rand.nextGaussian() * 0.02D; - this.worldObj.spawnParticle(particleType, - this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, - this.posY + 1.0D + (double) (this.rand.nextFloat() * this.height), - this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, - new int[0]); - } - - } - - /**+ - * Called only once on an entity when first time spawned, via - * egg, mob spawner, natural spawning etc, but not called when - * entity is reloaded from nbt. Mainly used for initializing - * attributes and inventory - */ - public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, - IEntityLivingData ientitylivingdata) { - ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); - this.setProfession(this.worldObj.rand.nextInt(5)); - this.setAdditionalAItasks(); - return ientitylivingdata; - } - - public void setLookingForHome() { - this.isLookingForHome = true; - } - - public EntityVillager createChild(EntityAgeable var1) { - EntityVillager entityvillager = new EntityVillager(this.worldObj); - entityvillager.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entityvillager)), - (IEntityLivingData) null); - return entityvillager; - } - - public boolean allowLeashing() { - return false; - } - - /**+ - * Called when a lightning bolt hits the entity. - */ - public void onStruckByLightning(EntityLightningBolt var1) { - if (!this.worldObj.isRemote && !this.isDead) { - EntityWitch entitywitch = new EntityWitch(this.worldObj); - entitywitch.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); - entitywitch.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entitywitch)), - (IEntityLivingData) null); - entitywitch.setNoAI(this.isAIDisabled()); - if (this.hasCustomName()) { - entitywitch.setCustomNameTag(this.getCustomNameTag()); - entitywitch.setAlwaysRenderNameTag(this.getAlwaysRenderNameTag()); - } - - this.worldObj.spawnEntityInWorld(entitywitch); - this.setDead(); - } - } - - public InventoryBasic getVillagerInventory() { - return this.villagerInventory; - } - - /**+ - * Tests if this entity should pickup a weapon or an armor. - * Entity drops current weapon or armor if the new one is - * better. - */ - protected void updateEquipmentIfNeeded(EntityItem entityitem) { - ItemStack itemstack = entityitem.getEntityItem(); - Item item = itemstack.getItem(); - if (this.canVillagerPickupItem(item)) { - ItemStack itemstack1 = this.villagerInventory.func_174894_a(itemstack); - if (itemstack1 == null) { - entityitem.setDead(); - } else { - itemstack.stackSize = itemstack1.stackSize; - } - } - - } - - private boolean canVillagerPickupItem(Item itemIn) { - return itemIn == Items.bread || itemIn == Items.potato || itemIn == Items.carrot || itemIn == Items.wheat - || itemIn == Items.wheat_seeds; - } - - public boolean func_175553_cp() { - return this.hasEnoughItems(1); - } - - /**+ - * Used by {@link - * net.minecraft.entity.ai.EntityAIVillagerInteract - * EntityAIVillagerInteract} to check if the villager can give - * some items from an inventory to another villager. - */ - public boolean canAbondonItems() { - return this.hasEnoughItems(2); - } - - public boolean func_175557_cr() { - boolean flag = this.getProfession() == 0; - return flag ? !this.hasEnoughItems(5) : !this.hasEnoughItems(1); - } - - /**+ - * Returns true if villager has enough items in inventory + /** + * + Returns true if villager has enough items in inventory */ private boolean hasEnoughItems(int multiplier) { boolean flag = this.getProfession() == 0; @@ -952,9 +733,28 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { return false; } - /**+ - * Returns true if villager has seeds, potatoes or carrots in - * inventory + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. + */ + public boolean interact(EntityPlayer entityplayer) { + ItemStack itemstack = entityplayer.inventory.getCurrentItem(); + boolean flag = itemstack != null && itemstack.getItem() == Items.spawn_egg; + if (!flag && this.isEntityAlive() && !this.isTrading() && !this.isChild()) { + if (!this.worldObj.isRemote && (this.buyingList == null || this.buyingList.size() > 0)) { + this.setCustomer(entityplayer); + entityplayer.displayVillagerTradeGui(this); + } + + entityplayer.triggerAchievement(StatList.timesTalkedToVillagerStat); + return true; + } else { + return super.interact(entityplayer); + } + } + + /** + * + Returns true if villager has seeds, potatoes or carrots in inventory */ public boolean isFarmItemInInventory() { for (int i = 0; i < this.villagerInventory.getSizeInventory(); ++i) { @@ -968,6 +768,141 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { return false; } + public boolean isMating() { + return this.isMating; + } + + public boolean isPlaying() { + return this.isPlaying; + } + + public boolean isTrading() { + return this.buyingPlayer != null; + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + if (this.villageObj != null) { + Entity entity = damagesource.getEntity(); + if (entity != null) { + if (entity instanceof EntityPlayer) { + this.villageObj.setReputationForPlayer(entity.getName(), -2); + } else if (entity instanceof IMob) { + this.villageObj.endMatingSeason(); + } + } else { + EntityPlayer entityplayer = this.worldObj.getClosestPlayerToEntity(this, 16.0D); + if (entityplayer != null) { + this.villageObj.endMatingSeason(); + } + } + } + + super.onDeath(damagesource); + } + + /** + * + This is called when Entity's growing age timer reaches 0 (negative values + * are considered as a child, positive as an adult) + */ + protected void onGrowingAdult() { + if (this.getProfession() == 0) { + this.tasks.addTask(8, new EntityAIHarvestFarmland(this, 0.6D)); + } + + super.onGrowingAdult(); + } + + /** + * + Called only once on an entity when first time spawned, via egg, mob + * spawner, natural spawning etc, but not called when entity is reloaded from + * nbt. Mainly used for initializing attributes and inventory + */ + public IEntityLivingData onInitialSpawn(DifficultyInstance difficultyinstance, + IEntityLivingData ientitylivingdata) { + ientitylivingdata = super.onInitialSpawn(difficultyinstance, ientitylivingdata); + this.setProfession(this.worldObj.rand.nextInt(5)); + this.setAdditionalAItasks(); + return ientitylivingdata; + } + + /** + * + Called when a lightning bolt hits the entity. + */ + public void onStruckByLightning(EntityLightningBolt var1) { + if (!this.worldObj.isRemote && !this.isDead) { + EntityWitch entitywitch = new EntityWitch(this.worldObj); + entitywitch.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); + entitywitch.onInitialSpawn(this.worldObj.getDifficultyForLocation(new BlockPos(entitywitch)), + (IEntityLivingData) null); + entitywitch.setNoAI(this.isAIDisabled()); + if (this.hasCustomName()) { + entitywitch.setCustomNameTag(this.getCustomNameTag()); + entitywitch.setAlwaysRenderNameTag(this.getAlwaysRenderNameTag()); + } + + this.worldObj.spawnEntityInWorld(entitywitch); + this.setDead(); + } + } + + private void populateBuyingList() { + List>> aentityvillager$itradelist = DEFAULT_TRADE_LIST_MAP + .get(this.getProfession()); + if (this.careerId != 0 && this.careerLevel != 0) { + ++this.careerLevel; + } else { + this.careerId = this.rand.nextInt(aentityvillager$itradelist.size()) + 1; + this.careerLevel = 1; + } + + if (this.buyingList == null) { + this.buyingList = new MerchantRecipeList(); + } + + int i = this.careerId - 1; + int j = this.careerLevel - 1; + List> aentityvillager$itradelist1 = aentityvillager$itradelist.get(i); + if (j >= 0 && j < aentityvillager$itradelist1.size()) { + List aentityvillager$itradelist2 = aentityvillager$itradelist1.get(j); + + for (int k = 0, l = aentityvillager$itradelist2.size(); k < l; ++k) { + aentityvillager$itradelist2.get(k).modifyMerchantRecipeList(this.buyingList, this.rand); + } + } + + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setProfession(nbttagcompound.getInteger("Profession")); + this.wealth = nbttagcompound.getInteger("Riches"); + this.careerId = nbttagcompound.getInteger("Career"); + this.careerLevel = nbttagcompound.getInteger("CareerLevel"); + this.isWillingToMate = nbttagcompound.getBoolean("Willing"); + if (nbttagcompound.hasKey("Offers", 10)) { + NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Offers"); + this.buyingList = new MerchantRecipeList(nbttagcompound1); + } + + NBTTagList nbttaglist = nbttagcompound.getTagList("Inventory", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); + if (itemstack != null) { + this.villagerInventory.func_174894_a(itemstack); + } + } + + this.setCanPickUpLoot(true); + this.setAdditionalAItasks(); + } + public boolean replaceItemInInventory(int i, ItemStack itemstack) { if (super.replaceItemInInventory(i, itemstack)) { return true; @@ -982,143 +917,212 @@ public class EntityVillager extends EntityAgeable implements IMerchant, INpc { } } - static class EmeraldForItems implements EntityVillager.ITradeList { - public Item sellItem; - public EntityVillager.PriceInfo price; - - public EmeraldForItems(Item itemIn, EntityVillager.PriceInfo priceIn) { - this.sellItem = itemIn; - this.price = priceIn; - } - - public void modifyMerchantRecipeList(MerchantRecipeList recipeList, EaglercraftRandom random) { - int i = 1; - if (this.price != null) { - i = this.price.getPrice(random); + private void setAdditionalAItasks() { + if (!this.areAdditionalTasksSet) { + this.areAdditionalTasksSet = true; + if (this.isChild()) { + this.tasks.addTask(8, new EntityAIPlay(this, 0.32D)); + } else if (this.getProfession() == 0) { + this.tasks.addTask(6, new EntityAIHarvestFarmland(this, 0.6D)); } - recipeList.add(new MerchantRecipe(new ItemStack(this.sellItem, i, 0), Items.emerald)); } } - interface ITradeList { - void modifyMerchantRecipeList(MerchantRecipeList var1, EaglercraftRandom var2); + public void setCustomer(EntityPlayer entityplayer) { + this.buyingPlayer = entityplayer; } - static class ItemAndEmeraldToItem implements EntityVillager.ITradeList { - public ItemStack field_179411_a; - public EntityVillager.PriceInfo field_179409_b; - public ItemStack field_179410_c; - public EntityVillager.PriceInfo field_179408_d; - - public ItemAndEmeraldToItem(Item parItem, EntityVillager.PriceInfo parPriceInfo, Item parItem2, - EntityVillager.PriceInfo parPriceInfo2) { - this.field_179411_a = new ItemStack(parItem); - this.field_179409_b = parPriceInfo; - this.field_179410_c = new ItemStack(parItem2); - this.field_179408_d = parPriceInfo2; - } - - public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { - int i = 1; - if (this.field_179409_b != null) { - i = this.field_179409_b.getPrice(random); - } - - int j = 1; - if (this.field_179408_d != null) { - j = this.field_179408_d.getPrice(random); - } - - merchantrecipelist.add(new MerchantRecipe( - new ItemStack(this.field_179411_a.getItem(), i, this.field_179411_a.getMetadata()), - new ItemStack(Items.emerald), - new ItemStack(this.field_179410_c.getItem(), j, this.field_179410_c.getMetadata()))); - } + public void setIsWillingToMate(boolean willingToTrade) { + this.isWillingToMate = willingToTrade; } - static class ListEnchantedBookForEmeralds implements EntityVillager.ITradeList { - public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { - Enchantment enchantment = Enchantment.enchantmentsBookList[random - .nextInt(Enchantment.enchantmentsBookList.length)]; - int i = MathHelper.getRandomIntegerInRange(random, enchantment.getMinLevel(), enchantment.getMaxLevel()); - ItemStack itemstack = Items.enchanted_book.getEnchantedItemStack(new EnchantmentData(enchantment, i)); - int j = 2 + random.nextInt(5 + i * 10) + 3 * i; - if (j > 64) { - j = 64; - } - - merchantrecipelist - .add(new MerchantRecipe(new ItemStack(Items.book), new ItemStack(Items.emerald, j), itemstack)); - } + public void setLookingForHome() { + this.isLookingForHome = true; } - static class ListEnchantedItemForEmeralds implements EntityVillager.ITradeList { - public ItemStack field_179407_a; - public EntityVillager.PriceInfo field_179406_b; - - public ListEnchantedItemForEmeralds(Item parItem, EntityVillager.PriceInfo parPriceInfo) { - this.field_179407_a = new ItemStack(parItem); - this.field_179406_b = parPriceInfo; - } - - public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { - int i = 1; - if (this.field_179406_b != null) { - i = this.field_179406_b.getPrice(random); - } - - ItemStack itemstack = new ItemStack(Items.emerald, i, 0); - ItemStack itemstack1 = new ItemStack(this.field_179407_a.getItem(), 1, this.field_179407_a.getMetadata()); - itemstack1 = EnchantmentHelper.addRandomEnchantment(random, itemstack1, 5 + random.nextInt(15)); - merchantrecipelist.add(new MerchantRecipe(itemstack, itemstack1)); - } + public void setMating(boolean mating) { + this.isMating = mating; } - static class ListItemForEmeralds implements EntityVillager.ITradeList { - public ItemStack field_179403_a; - public EntityVillager.PriceInfo field_179402_b; + public void setPlaying(boolean playing) { + this.isPlaying = playing; + } - public ListItemForEmeralds(Item par1Item, EntityVillager.PriceInfo priceInfo) { - this.field_179403_a = new ItemStack(par1Item); - this.field_179402_b = priceInfo; - } + public void setProfession(int professionId) { + this.dataWatcher.updateObject(16, Integer.valueOf(professionId)); + } - public ListItemForEmeralds(ItemStack stack, EntityVillager.PriceInfo priceInfo) { - this.field_179403_a = stack; - this.field_179402_b = priceInfo; - } + public void setRecipes(MerchantRecipeList var1) { + } - public void modifyMerchantRecipeList(MerchantRecipeList merchantrecipelist, EaglercraftRandom random) { - int i = 1; - if (this.field_179402_b != null) { - i = this.field_179402_b.getPrice(random); + public void setRevengeTarget(EntityLivingBase entitylivingbase) { + super.setRevengeTarget(entitylivingbase); + if (this.villageObj != null && entitylivingbase != null) { + this.villageObj.addOrRenewAgressor(entitylivingbase); + if (entitylivingbase instanceof EntityPlayer) { + byte b0 = -1; + if (this.isChild()) { + b0 = -3; + } + + this.villageObj.setReputationForPlayer(entitylivingbase.getName(), b0); + if (this.isEntityAlive()) { + this.worldObj.setEntityState(this, (byte) 13); + } } + } - ItemStack itemstack; - ItemStack itemstack1; - if (i < 0) { - itemstack = new ItemStack(Items.emerald, 1, 0); - itemstack1 = new ItemStack(this.field_179403_a.getItem(), -i, this.field_179403_a.getMetadata()); + } + + private void spawnParticles(EnumParticleTypes particleType) { + for (int i = 0; i < 5; ++i) { + double d0 = this.rand.nextGaussian() * 0.02D; + double d1 = this.rand.nextGaussian() * 0.02D; + double d2 = this.rand.nextGaussian() * 0.02D; + this.worldObj.spawnParticle(particleType, + this.posX + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, + this.posY + 1.0D + (double) (this.rand.nextFloat() * this.height), + this.posZ + (double) (this.rand.nextFloat() * this.width * 2.0F) - (double) this.width, d0, d1, d2, + new int[0]); + } + + } + + protected void updateAITasks() { + if (--this.randomTickDivider <= 0) { + BlockPos blockpos = new BlockPos(this); + this.worldObj.getVillageCollection().addToVillagerPositionList(blockpos); + this.randomTickDivider = 70 + this.rand.nextInt(50); + this.villageObj = this.worldObj.getVillageCollection().getNearestVillage(blockpos, 32); + if (this.villageObj == null) { + this.detachHome(); } else { - itemstack = new ItemStack(Items.emerald, i, 0); - itemstack1 = new ItemStack(this.field_179403_a.getItem(), 1, this.field_179403_a.getMetadata()); + BlockPos blockpos1 = this.villageObj.getCenter(); + this.setHomePosAndDistance(blockpos1, (int) ((float) this.villageObj.getVillageRadius() * 1.0F)); + if (this.isLookingForHome) { + this.isLookingForHome = false; + this.villageObj.setDefaultPlayerReputation(5); + } } - - merchantrecipelist.add(new MerchantRecipe(itemstack, itemstack1)); } + + if (!this.isTrading() && this.timeUntilReset > 0) { + --this.timeUntilReset; + if (this.timeUntilReset <= 0) { + if (this.needsInitilization) { + for (int i = 0, l = this.buyingList.size(); i < l; ++i) { + MerchantRecipe merchantrecipe = this.buyingList.get(i); + if (merchantrecipe.isRecipeDisabled()) { + merchantrecipe.increaseMaxTradeUses(this.rand.nextInt(6) + this.rand.nextInt(6) + 2); + } + } + + this.populateBuyingList(); + this.needsInitilization = false; + if (this.villageObj != null && this.lastBuyingPlayer != null) { + this.worldObj.setEntityState(this, (byte) 14); + this.villageObj.setReputationForPlayer(this.lastBuyingPlayer, 1); + } + } + + this.addPotionEffect(new PotionEffect(Potion.regeneration.id, 200, 0)); + } + } + + super.updateAITasks(); } - static class PriceInfo extends Tuple { - public PriceInfo(int parInt1, int parInt2) { - super(Integer.valueOf(parInt1), Integer.valueOf(parInt2)); + /** + * + Tests if this entity should pickup a weapon or an armor. Entity drops + * current weapon or armor if the new one is better. + */ + protected void updateEquipmentIfNeeded(EntityItem entityitem) { + ItemStack itemstack = entityitem.getEntityItem(); + Item item = itemstack.getItem(); + if (this.canVillagerPickupItem(item)) { + ItemStack itemstack1 = this.villagerInventory.func_174894_a(itemstack); + if (itemstack1 == null) { + entityitem.setDead(); + } else { + itemstack.stackSize = itemstack1.stackSize; + } } - public int getPrice(EaglercraftRandom rand) { - return ((Integer) this.getFirst()).intValue() >= ((Integer) this.getSecond()).intValue() - ? ((Integer) this.getFirst()).intValue() - : ((Integer) this.getFirst()).intValue() + rand.nextInt( - ((Integer) this.getSecond()).intValue() - ((Integer) this.getFirst()).intValue() + 1); + } + + public void useRecipe(MerchantRecipe merchantrecipe) { + merchantrecipe.incrementToolUses(); + this.livingSoundTime = -this.getTalkInterval(); + this.playSound("mob.villager.yes", this.getSoundVolume(), this.getSoundPitch()); + int i = 3 + this.rand.nextInt(4); + if (merchantrecipe.getToolUses() == 1 || this.rand.nextInt(5) == 0) { + this.timeUntilReset = 40; + this.needsInitilization = true; + this.isWillingToMate = true; + if (this.buyingPlayer != null) { + this.lastBuyingPlayer = this.buyingPlayer.getName(); + } else { + this.lastBuyingPlayer = null; + } + + i += 5; } + + if (merchantrecipe.getItemToBuy().getItem() == Items.emerald) { + this.wealth += merchantrecipe.getItemToBuy().stackSize; + } + + if (merchantrecipe.getRewardsExp()) { + this.worldObj.spawnEntityInWorld(new EntityXPOrb(this.worldObj, this.posX, this.posY + 0.5D, this.posZ, i)); + } + + } + + /** + * + Notifies the merchant of a possible merchantrecipe being fulfilled or not. + * Usually, this is just a sound byte being played depending if the suggested + * itemstack is not null. + */ + public void verifySellingItem(ItemStack itemstack) { + if (!this.worldObj.isRemote && this.livingSoundTime > -this.getTalkInterval() + 20) { + this.livingSoundTime = -this.getTalkInterval(); + if (itemstack != null) { + this.playSound("mob.villager.yes", this.getSoundVolume(), this.getSoundPitch()); + } else { + this.playSound("mob.villager.no", this.getSoundVolume(), this.getSoundPitch()); + } + } + + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("Profession", this.getProfession()); + nbttagcompound.setInteger("Riches", this.wealth); + nbttagcompound.setInteger("Career", this.careerId); + nbttagcompound.setInteger("CareerLevel", this.careerLevel); + nbttagcompound.setBoolean("Willing", this.isWillingToMate); + if (this.buyingList != null) { + try { + nbttagcompound.setTag("Offers", this.buyingList.getRecipiesAsTags()); + } catch (Throwable t) { + this.buyingList = null; // workaround + } + } + + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.villagerInventory.getSizeInventory(); ++i) { + ItemStack itemstack = this.villagerInventory.getStackInSlot(i); + if (itemstack != null) { + nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound())); + } + } + + nbttagcompound.setTag("Inventory", nbttaglist); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityWaterMob.java b/src/game/java/net/minecraft/entity/passive/EntityWaterMob.java index 803ce629..a2857d2d 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityWaterMob.java +++ b/src/game/java/net/minecraft/entity/passive/EntityWaterMob.java @@ -5,22 +5,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.DamageSource; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,47 +37,49 @@ public abstract class EntityWaterMob extends EntityLiving implements IAnimals { return true; } - /**+ - * Checks if the entity's current position is a valid location - * to spawn this entity. - */ - public boolean getCanSpawnHere() { - return true; - } - - /**+ - * Checks that the entity is not colliding with any blocks / - * liquids - */ - public boolean isNotColliding() { - return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this); - } - - /**+ - * Get number of ticks, at least during which the living entity - * will be silent. - */ - public int getTalkInterval() { - return 120; - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities + /** + * + Determines if an entity can be despawned, used on idle far away entities */ protected boolean canDespawn() { return true; } - /**+ - * Get the experience points the entity currently has. + /** + * + Checks if the entity's current position is a valid location to spawn this + * entity. + */ + public boolean getCanSpawnHere() { + return true; + } + + /** + * + Get the experience points the entity currently has. */ protected int getExperiencePoints(EntityPlayer var1) { return 1 + this.worldObj.rand.nextInt(3); } - /**+ - * Gets called every tick from main Entity class + /** + * + Get number of ticks, at least during which the living entity will be + * silent. + */ + public int getTalkInterval() { + return 120; + } + + /** + * + Checks that the entity is not colliding with any blocks / liquids + */ + public boolean isNotColliding() { + return this.worldObj.checkNoEntityCollision(this.getEntityBoundingBox(), this); + } + + public boolean isPushedByWater() { + return false; + } + + /** + * + Gets called every tick from main Entity class */ public void onEntityUpdate() { int i = this.getAir(); @@ -91,8 +96,4 @@ public abstract class EntityWaterMob extends EntityLiving implements IAnimals { } } - - public boolean isPushedByWater() { - return false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/EntityWolf.java b/src/game/java/net/minecraft/entity/passive/EntityWolf.java index 9e8abd88..4214e13f 100644 --- a/src/game/java/net/minecraft/entity/passive/EntityWolf.java +++ b/src/game/java/net/minecraft/entity/passive/EntityWolf.java @@ -1,6 +1,7 @@ package net.minecraft.entity.passive; import com.google.common.base.Predicate; + import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityAgeable; @@ -38,22 +39,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -93,6 +97,10 @@ public class EntityWolf extends EntityTameable { this.setTamed(false); } + public boolean allowLeashing() { + return !this.isAngry() && super.allowLeashing(); + } + protected void applyEntityAttributes() { super.applyEntityAttributes(); this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.30000001192092896D); @@ -106,21 +114,66 @@ public class EntityWolf extends EntityTameable { this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(2.0D); } - /**+ - * Sets the active target the Task system uses for tracking - */ - public void setAttackTarget(EntityLivingBase entitylivingbase) { - super.setAttackTarget(entitylivingbase); - if (entitylivingbase == null) { - this.setAngry(false); - } else if (!this.isTamed()) { - this.setAngry(true); + public boolean attackEntityAsMob(Entity entity) { + boolean flag = entity.attackEntityFrom(DamageSource.causeMobDamage(this), + (float) ((int) this.getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue())); + if (flag) { + this.applyEnchantments(this, entity); } + return flag; } - protected void updateAITasks() { - this.dataWatcher.updateObject(18, Float.valueOf(this.getHealth())); + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + Entity entity = damagesource.getEntity(); + this.aiSit.setSitting(false); + if (entity != null && !(entity instanceof EntityPlayer) && !(entity instanceof EntityArrow)) { + f = (f + 1.0F) / 2.0F; + } + + return super.attackEntityFrom(damagesource, f); + } + } + + /** + * + Determines if an entity can be despawned, used on idle far away entities + */ + protected boolean canDespawn() { + return !this.isTamed() && this.ticksExisted > 2400; + } + + /** + * + Returns true if the mob is currently able to mate with the specified mob. + */ + public boolean canMateWith(EntityAnimal entityanimal) { + if (entityanimal == this) { + return false; + } else if (!this.isTamed()) { + return false; + } else if (!(entityanimal instanceof EntityWolf)) { + return false; + } else { + EntityWolf entitywolf = (EntityWolf) entityanimal; + return !entitywolf.isTamed() ? false + : (entitywolf.isSitting() ? false : this.isInLove() && entitywolf.isInLove()); + } + } + + public EntityWolf createChild(EntityAgeable var1) { + EntityWolf entitywolf = new EntityWolf(this.worldObj); + String s = this.getOwnerId(); + if (s != null && s.trim().length() > 0) { + entitywolf.setOwnerId(s); + entitywolf.setTamed(true); + } + + return entitywolf; } protected void entityInit() { @@ -130,35 +183,39 @@ public class EntityWolf extends EntityTameable { this.dataWatcher.addObject(20, Byte.valueOf((byte) EnumDyeColor.RED.getMetadata())); } - protected void playStepSound(BlockPos var1, Block var2) { - this.playSound("mob.wolf.step", 0.15F, 1.0F); + public EnumDyeColor getCollarColor() { + return EnumDyeColor.byDyeDamage(this.dataWatcher.getWatchableObjectByte(20) & 15); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Returns the sound this mob makes on death. */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setBoolean("Angry", this.isAngry()); - nbttagcompound.setByte("CollarColor", (byte) this.getCollarColor().getDyeDamage()); + protected String getDeathSound() { + return "mob.wolf.death"; } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + protected Item getDropItem() { + return Item.getItemById(-1); + } + + public float getEyeHeight() { + return this.height * 0.8F; + } + + /** + * + Returns the sound this mob makes when it is hurt. */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.setAngry(nbttagcompound.getBoolean("Angry")); - if (nbttagcompound.hasKey("CollarColor", 99)) { - this.setCollarColor(EnumDyeColor.byDyeDamage(nbttagcompound.getByte("CollarColor"))); - } - + protected String getHurtSound() { + return "mob.wolf.hurt"; } - /**+ - * Returns the sound this mob makes while it's alive. + public float getInterestedAngle(float parFloat1) { + return (this.headRotationCourseOld + (this.headRotationCourse - this.headRotationCourseOld) * parFloat1) * 0.15F + * 3.1415927F; + } + + /** + * + Returns the sound this mob makes while it's alive. */ protected String getLivingSound() { return this.isAngry() ? "mob.wolf.growl" @@ -168,109 +225,15 @@ public class EntityWolf extends EntityTameable { : "mob.wolf.bark"); } - /**+ - * Returns the sound this mob makes when it is hurt. + /** + * + Will return how many at most can spawn in a chunk at once. */ - protected String getHurtSound() { - return "mob.wolf.hurt"; + public int getMaxSpawnedInChunk() { + return 8; } - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "mob.wolf.death"; - } - - /**+ - * Returns the volume for the sounds this mob makes. - */ - protected float getSoundVolume() { - return 0.4F; - } - - protected Item getDropItem() { - return Item.getItemById(-1); - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - super.onLivingUpdate(); - if (!this.worldObj.isRemote && this.isWet && !this.isShaking && !this.hasPath() && this.onGround) { - this.isShaking = true; - this.timeWolfIsShaking = 0.0F; - this.prevTimeWolfIsShaking = 0.0F; - this.worldObj.setEntityState(this, (byte) 8); - } - - if (!this.worldObj.isRemote && this.getAttackTarget() == null && this.isAngry()) { - this.setAngry(false); - } - - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - super.onUpdate(); - this.headRotationCourseOld = this.headRotationCourse; - if (this.isBegging()) { - this.headRotationCourse += (1.0F - this.headRotationCourse) * 0.4F; - } else { - this.headRotationCourse += (0.0F - this.headRotationCourse) * 0.4F; - } - - if (this.isWet()) { - this.isWet = true; - this.isShaking = false; - this.timeWolfIsShaking = 0.0F; - this.prevTimeWolfIsShaking = 0.0F; - } else if ((this.isWet || this.isShaking) && this.isShaking) { - if (this.timeWolfIsShaking == 0.0F) { - this.playSound("mob.wolf.shake", this.getSoundVolume(), - (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); - } - - this.prevTimeWolfIsShaking = this.timeWolfIsShaking; - this.timeWolfIsShaking += 0.05F; - if (this.prevTimeWolfIsShaking >= 2.0F) { - this.isWet = false; - this.isShaking = false; - this.prevTimeWolfIsShaking = 0.0F; - this.timeWolfIsShaking = 0.0F; - } - - if (this.timeWolfIsShaking > 0.4F) { - float f = (float) this.getEntityBoundingBox().minY; - int i = (int) (MathHelper.sin((this.timeWolfIsShaking - 0.4F) * 3.1415927F) * 7.0F); - - for (int j = 0; j < i; ++j) { - float f1 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F; - float f2 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F; - this.worldObj.spawnParticle(EnumParticleTypes.WATER_SPLASH, this.posX + (double) f1, - (double) (f + 0.8F), this.posZ + (double) f2, this.motionX, this.motionY, this.motionZ, - new int[0]); - } - } - } - - } - - /**+ - * True if the wolf is wet - */ - public boolean isWolfWet() { - return this.isWet; - } - - /**+ - * Used when calculating the amount of shading to apply while - * the wolf is wet. + /** + * + Used when calculating the amount of shading to apply while the wolf is wet. */ public float getShadingWhileWet(float parFloat1) { return 0.75F + (this.prevTimeWolfIsShaking + (this.timeWolfIsShaking - this.prevTimeWolfIsShaking) * parFloat1) @@ -289,65 +252,42 @@ public class EntityWolf extends EntityTameable { return MathHelper.sin(f * 3.1415927F) * MathHelper.sin(f * 3.1415927F * 11.0F) * 0.15F * 3.1415927F; } - public float getInterestedAngle(float parFloat1) { - return (this.headRotationCourseOld + (this.headRotationCourse - this.headRotationCourseOld) * parFloat1) * 0.15F - * 3.1415927F; + /** + * + Returns the volume for the sounds this mob makes. + */ + protected float getSoundVolume() { + return 0.4F; } - public float getEyeHeight() { - return this.height * 0.8F; + public float getTailRotation() { + return this.isAngry() ? 1.5393804F + : (this.isTamed() + ? (0.55F - (20.0F - this.dataWatcher.getWatchableObjectFloat(18)) * 0.02F) * 3.1415927F + : 0.62831855F); } - /**+ - * The speed it takes to move the entityliving's rotationPitch - * through the faceEntity method. This is only currently use in - * wolves. + /** + * + The speed it takes to move the entityliving's rotationPitch through the + * faceEntity method. This is only currently use in wolves. */ public int getVerticalFaceSpeed() { return this.isSitting() ? 20 : super.getVerticalFaceSpeed(); } - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; + public void handleStatusUpdate(byte b0) { + if (b0 == 8) { + this.isShaking = true; + this.timeWolfIsShaking = 0.0F; + this.prevTimeWolfIsShaking = 0.0F; } else { - Entity entity = damagesource.getEntity(); - this.aiSit.setSitting(false); - if (entity != null && !(entity instanceof EntityPlayer) && !(entity instanceof EntityArrow)) { - f = (f + 1.0F) / 2.0F; - } - - return super.attackEntityFrom(damagesource, f); - } - } - - public boolean attackEntityAsMob(Entity entity) { - boolean flag = entity.attackEntityFrom(DamageSource.causeMobDamage(this), - (float) ((int) this.getEntityAttribute(SharedMonsterAttributes.attackDamage).getAttributeValue())); - if (flag) { - this.applyEnchantments(this, entity); + super.handleStatusUpdate(b0); } - return flag; } - public void setTamed(boolean flag) { - super.setTamed(flag); - if (flag) { - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(20.0D); - } else { - this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D); - } - - this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(4.0D); - } - - /**+ - * Called when a player interacts with a mob. e.g. gets milk - * from a cow, gets into the saddle on a pig. + /** + * + Called when a player interacts with a mob. e.g. gets milk from a cow, gets + * into the saddle on a pig. */ public boolean interact(EntityPlayer entityplayer) { ItemStack itemstack = entityplayer.inventory.getCurrentItem(); @@ -419,28 +359,20 @@ public class EntityWolf extends EntityTameable { return super.interact(entityplayer); } - public void handleStatusUpdate(byte b0) { - if (b0 == 8) { - this.isShaking = true; - this.timeWolfIsShaking = 0.0F; - this.prevTimeWolfIsShaking = 0.0F; - } else { - super.handleStatusUpdate(b0); - } - + /** + * + Determines whether this wolf is angry or not. + */ + public boolean isAngry() { + return (this.dataWatcher.getWatchableObjectByte(16) & 2) != 0; } - public float getTailRotation() { - return this.isAngry() ? 1.5393804F - : (this.isTamed() - ? (0.55F - (20.0F - this.dataWatcher.getWatchableObjectFloat(18)) * 0.02F) * 3.1415927F - : 0.62831855F); + public boolean isBegging() { + return this.dataWatcher.getWatchableObjectByte(19) == 1; } - /**+ - * Checks if the parameter is an item which this animal can be - * fed to breed it (wheat, carrots or seeds depending on the - * animal type) + /** + * + Checks if the parameter is an item which this animal can be fed to breed it + * (wheat, carrots or seeds depending on the animal type) */ public boolean isBreedingItem(ItemStack itemstack) { return itemstack == null ? false @@ -448,22 +380,99 @@ public class EntityWolf extends EntityTameable { : ((ItemFood) itemstack.getItem()).isWolfsFavoriteMeat()); } - /**+ - * Will return how many at most can spawn in a chunk at once. + /** + * + True if the wolf is wet */ - public int getMaxSpawnedInChunk() { - return 8; + public boolean isWolfWet() { + return this.isWet; } - /**+ - * Determines whether this wolf is angry or not. + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. */ - public boolean isAngry() { - return (this.dataWatcher.getWatchableObjectByte(16) & 2) != 0; + public void onLivingUpdate() { + super.onLivingUpdate(); + if (!this.worldObj.isRemote && this.isWet && !this.isShaking && !this.hasPath() && this.onGround) { + this.isShaking = true; + this.timeWolfIsShaking = 0.0F; + this.prevTimeWolfIsShaking = 0.0F; + this.worldObj.setEntityState(this, (byte) 8); + } + + if (!this.worldObj.isRemote && this.getAttackTarget() == null && this.isAngry()) { + this.setAngry(false); + } + } - /**+ - * Sets whether this wolf is angry or not. + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + super.onUpdate(); + this.headRotationCourseOld = this.headRotationCourse; + if (this.isBegging()) { + this.headRotationCourse += (1.0F - this.headRotationCourse) * 0.4F; + } else { + this.headRotationCourse += (0.0F - this.headRotationCourse) * 0.4F; + } + + if (this.isWet()) { + this.isWet = true; + this.isShaking = false; + this.timeWolfIsShaking = 0.0F; + this.prevTimeWolfIsShaking = 0.0F; + } else if ((this.isWet || this.isShaking) && this.isShaking) { + if (this.timeWolfIsShaking == 0.0F) { + this.playSound("mob.wolf.shake", this.getSoundVolume(), + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); + } + + this.prevTimeWolfIsShaking = this.timeWolfIsShaking; + this.timeWolfIsShaking += 0.05F; + if (this.prevTimeWolfIsShaking >= 2.0F) { + this.isWet = false; + this.isShaking = false; + this.prevTimeWolfIsShaking = 0.0F; + this.timeWolfIsShaking = 0.0F; + } + + if (this.timeWolfIsShaking > 0.4F) { + float f = (float) this.getEntityBoundingBox().minY; + int i = (int) (MathHelper.sin((this.timeWolfIsShaking - 0.4F) * 3.1415927F) * 7.0F); + + for (int j = 0; j < i; ++j) { + float f1 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F; + float f2 = (this.rand.nextFloat() * 2.0F - 1.0F) * this.width * 0.5F; + this.worldObj.spawnParticle(EnumParticleTypes.WATER_SPLASH, this.posX + (double) f1, + (double) (f + 0.8F), this.posZ + (double) f2, this.motionX, this.motionY, this.motionZ, + new int[0]); + } + } + } + + } + + protected void playStepSound(BlockPos var1, Block var2) { + this.playSound("mob.wolf.step", 0.15F, 1.0F); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.setAngry(nbttagcompound.getBoolean("Angry")); + if (nbttagcompound.hasKey("CollarColor", 99)) { + this.setCollarColor(EnumDyeColor.byDyeDamage(nbttagcompound.getByte("CollarColor"))); + } + + } + + /** + * + Sets whether this wolf is angry or not. */ public void setAngry(boolean angry) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); @@ -475,23 +484,17 @@ public class EntityWolf extends EntityTameable { } - public EnumDyeColor getCollarColor() { - return EnumDyeColor.byDyeDamage(this.dataWatcher.getWatchableObjectByte(20) & 15); - } - - public void setCollarColor(EnumDyeColor collarcolor) { - this.dataWatcher.updateObject(20, Byte.valueOf((byte) (collarcolor.getDyeDamage() & 15))); - } - - public EntityWolf createChild(EntityAgeable var1) { - EntityWolf entitywolf = new EntityWolf(this.worldObj); - String s = this.getOwnerId(); - if (s != null && s.trim().length() > 0) { - entitywolf.setOwnerId(s); - entitywolf.setTamed(true); + /** + * + Sets the active target the Task system uses for tracking + */ + public void setAttackTarget(EntityLivingBase entitylivingbase) { + super.setAttackTarget(entitylivingbase); + if (entitylivingbase == null) { + this.setAngry(false); + } else if (!this.isTamed()) { + this.setAngry(true); } - return entitywolf; } public void setBegging(boolean beg) { @@ -503,34 +506,19 @@ public class EntityWolf extends EntityTameable { } - /**+ - * Returns true if the mob is currently able to mate with the - * specified mob. - */ - public boolean canMateWith(EntityAnimal entityanimal) { - if (entityanimal == this) { - return false; - } else if (!this.isTamed()) { - return false; - } else if (!(entityanimal instanceof EntityWolf)) { - return false; + public void setCollarColor(EnumDyeColor collarcolor) { + this.dataWatcher.updateObject(20, Byte.valueOf((byte) (collarcolor.getDyeDamage() & 15))); + } + + public void setTamed(boolean flag) { + super.setTamed(flag); + if (flag) { + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(20.0D); } else { - EntityWolf entitywolf = (EntityWolf) entityanimal; - return !entitywolf.isTamed() ? false - : (entitywolf.isSitting() ? false : this.isInLove() && entitywolf.isInLove()); + this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(8.0D); } - } - public boolean isBegging() { - return this.dataWatcher.getWatchableObjectByte(19) == 1; - } - - /**+ - * Determines if an entity can be despawned, used on idle far - * away entities - */ - protected boolean canDespawn() { - return !this.isTamed() && this.ticksExisted > 2400; + this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(4.0D); } public boolean shouldAttackEntity(EntityLivingBase entitylivingbase, EntityLivingBase entitylivingbase1) { @@ -550,7 +538,16 @@ public class EntityWolf extends EntityTameable { } } - public boolean allowLeashing() { - return !this.isAngry() && super.allowLeashing(); + protected void updateAITasks() { + this.dataWatcher.updateObject(18, Float.valueOf(this.getHealth())); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setBoolean("Angry", this.isAngry()); + nbttagcompound.setByte("CollarColor", (byte) this.getCollarColor().getDyeDamage()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/passive/IAnimals.java b/src/game/java/net/minecraft/entity/passive/IAnimals.java index 830aeca3..052bb8c2 100644 --- a/src/game/java/net/minecraft/entity/passive/IAnimals.java +++ b/src/game/java/net/minecraft/entity/passive/IAnimals.java @@ -1,21 +1,24 @@ package net.minecraft.entity.passive; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/entity/player/EntityPlayer.java b/src/game/java/net/minecraft/entity/player/EntityPlayer.java index d606d345..ee8530d4 100644 --- a/src/game/java/net/minecraft/entity/player/EntityPlayer.java +++ b/src/game/java/net/minecraft/entity/player/EntityPlayer.java @@ -1,12 +1,13 @@ package net.minecraft.entity.player; -import com.google.common.base.Charsets; -import com.google.common.collect.Lists; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; - import java.util.Collection; import java.util.List; + +import com.google.common.base.Charsets; +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.block.Block; import net.minecraft.block.BlockBed; import net.minecraft.block.BlockDirectional; @@ -77,36 +78,112 @@ import net.minecraft.world.LockCode; import net.minecraft.world.World; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class EntityPlayer extends EntityLivingBase implements ICommandSender { - /**+ - * Inventory of the player + public static enum EnumChatVisibility { + FULL(0, "options.chat.visibility.full"), SYSTEM(1, "options.chat.visibility.system"), + HIDDEN(2, "options.chat.visibility.hidden"); + + private static final EntityPlayer.EnumChatVisibility[] ID_LOOKUP = new EntityPlayer.EnumChatVisibility[3]; + static { + EntityPlayer.EnumChatVisibility[] lst = values(); + for (int i = 0; i < lst.length; ++i) { + ID_LOOKUP[lst[i].chatVisibility] = lst[i]; + } + + } + + public static EntityPlayer.EnumChatVisibility getEnumChatVisibility(int id) { + return ID_LOOKUP[id % ID_LOOKUP.length]; + } + + private final int chatVisibility; + + private final String resourceKey; + + private EnumChatVisibility(int id, String resourceKey) { + this.chatVisibility = id; + this.resourceKey = resourceKey; + } + + public int getChatVisibility() { + return this.chatVisibility; + } + + public String getResourceKey() { + return this.resourceKey; + } + } + + public static enum EnumStatus { + OK, NOT_POSSIBLE_HERE, NOT_POSSIBLE_NOW, TOO_FAR_AWAY, OTHER_PROBLEM, NOT_SAFE; + } + + /** + * + Return null if bed is invalid + */ + public static BlockPos getBedSpawnLocation(World worldIn, BlockPos bedLocation, boolean forceSpawn) { + Block block = worldIn.getBlockState(bedLocation).getBlock(); + if (block != Blocks.bed) { + if (!forceSpawn) { + return null; + } else { + boolean flag = block.func_181623_g(); + boolean flag1 = worldIn.getBlockState(bedLocation.up()).getBlock().func_181623_g(); + return flag && flag1 ? bedLocation : null; + } + } else { + return BlockBed.getSafeExitLocation(worldIn, bedLocation, 0); + } + } + + public static EaglercraftUUID getOfflineUUID(String username) { + return EaglercraftUUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(Charsets.UTF_8)); + } + + /** + * + Gets a players UUID given their GameProfie + */ + public static EaglercraftUUID getUUID(GameProfile profile) { + EaglercraftUUID uuid = profile.getId(); + if (uuid == null) { + uuid = getOfflineUUID(profile.getName()); + } + + return uuid; + } + + /** + * + Inventory of the player */ public InventoryPlayer inventory = new InventoryPlayer(this); private InventoryEnderChest theInventoryEnderChest = new InventoryEnderChest(); public Container inventoryContainer; public Container openContainer; - /**+ - * The food object of the player, the general hunger logic. + /** + * + The food object of the player, the general hunger logic. */ protected FoodStats foodStats = new FoodStats(); protected int flyToggleTimer; @@ -128,8 +205,8 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS private BlockPos spawnChunk; private boolean spawnForced; private BlockPos startMinecartRidingCoordinate; - /**+ - * The player's capabilities. (See class PlayerCapabilities) + /** + * + The player's capabilities. (See class PlayerCapabilities) */ public PlayerCapabilities capabilities = new PlayerCapabilities(); public int experienceLevel; @@ -139,10 +216,15 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS private ItemStack itemInUse; private int itemInUseCount; protected float speedOnGround = 0.1F; + protected float speedInAir = 0.02F; + private int lastXPSound; + private final GameProfile gameProfile; + private boolean hasReducedDebug = false; + public EntityFishHook fishEntity; public EntityPlayer(World worldIn, GameProfile gameProfileIn) { @@ -158,489 +240,154 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS this.fireResistance = 20; } - protected void applyEntityAttributes() { - super.applyEntityAttributes(); - this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(1.0D); - this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.10000000149011612D); + public void addChatComponentMessage(IChatComponent var1) { } - protected void entityInit() { - super.entityInit(); - this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); - this.dataWatcher.addObject(17, Float.valueOf(0.0F)); - this.dataWatcher.addObject(18, Integer.valueOf(0)); - this.dataWatcher.addObject(10, Byte.valueOf((byte) 0)); - } - - /**+ - * returns the ItemStack containing the itemInUse + /** + * + increases exhaustion level by supplied amount */ - public ItemStack getItemInUse() { - return this.itemInUse; - } - - /**+ - * Returns the item in use count - */ - public int getItemInUseCount() { - return this.itemInUseCount; - } - - /**+ - * Checks if the entity is currently using an item (e.g., bow, - * food, sword) by holding down the useItemButton - */ - public boolean isUsingItem() { - return this.itemInUse != null; - } - - public boolean getItemShouldUseOnTouchEagler() { - if (itemInUse != null) { - return itemInUse.getItem().shouldUseOnTouchEagler(itemInUse); - } else { - ItemStack st = getHeldItem(); - return st != null && st.getItem().shouldUseOnTouchEagler(st); - } - } - - /**+ - * gets the duration for how long the current itemInUse has been - * in use - */ - public int getItemInUseDuration() { - return this.isUsingItem() ? this.itemInUse.getMaxItemUseDuration() - this.itemInUseCount : 0; - } - - public void stopUsingItem() { - if (this.itemInUse != null) { - this.itemInUse.onPlayerStoppedUsing(this.worldObj, this, this.itemInUseCount); - } - - this.clearItemInUse(); - } - - public void clearItemInUse() { - this.itemInUse = null; - this.itemInUseCount = 0; - if (!this.worldObj.isRemote) { - this.setEating(false); - } - - } - - public boolean isBlocking() { - return this.isUsingItem() && this.itemInUse.getItem().getItemUseAction(this.itemInUse) == EnumAction.BLOCK; - } - - /**+ - * Called to update the entity's position/logic. - */ - public void onUpdate() { - this.noClip = this.isSpectator(); - if (this.isSpectator()) { - this.onGround = false; - } - - if (this.itemInUse != null) { - ItemStack itemstack = this.inventory.getCurrentItem(); - if (itemstack == this.itemInUse) { - if (this.itemInUseCount <= 25 && this.itemInUseCount % 4 == 0) { - this.updateItemUse(itemstack, 5); - } - - if (--this.itemInUseCount == 0 && !this.worldObj.isRemote) { - this.onItemUseFinish(); - } - } else { - this.clearItemInUse(); - } - } - - if (this.xpCooldown > 0) { - --this.xpCooldown; - } - - if (this.isPlayerSleeping()) { - ++this.sleepTimer; - if (this.sleepTimer > 100) { - this.sleepTimer = 100; - } - + public void addExhaustion(float parFloat1) { + if (!this.capabilities.disableDamage) { if (!this.worldObj.isRemote) { - if (!this.isInBed()) { - this.wakeUpPlayer(true, true, false); - } else if (this.worldObj.isDaytime()) { - this.wakeUpPlayer(false, true, true); + this.foodStats.addExhaustion(parFloat1); + } + + } + } + + /** + * + Add experience points to player. + */ + public void addExperience(int amount) { + this.addScore(amount); + int i = Integer.MAX_VALUE - this.experienceTotal; + if (amount > i) { + amount = i; + } + + this.experience += (float) amount / (float) this.xpBarCap(); + + for (this.experienceTotal += amount; this.experience >= 1.0F; this.experience /= (float) this.xpBarCap()) { + this.experience = (this.experience - 1.0F) * (float) this.xpBarCap(); + this.addExperienceLevel(1); + } + + } + + /** + * + Add experience levels to this player. + */ + public void addExperienceLevel(int i) { + this.experienceLevel += i; + if (this.experienceLevel < 0) { + this.experienceLevel = 0; + this.experience = 0.0F; + this.experienceTotal = 0; + } + + if (i > 0 && this.experienceLevel % 5 == 0 && (float) this.lastXPSound < (float) this.ticksExisted - 100.0F) { + float f = this.experienceLevel > 30 ? 1.0F : (float) this.experienceLevel / 30.0F; + this.worldObj.playSoundAtEntity(this, "random.levelup", f * 0.75F, 1.0F); + this.lastXPSound = this.ticksExisted; + } + + } + + /** + * + Adds a value to a mounted movement statistic field - by minecart, boat, or + * pig. + */ + private void addMountedMovementStat(double parDouble1, double parDouble2, double parDouble3) { + if (this.ridingEntity != null) { + int i = Math.round( + MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble2 * parDouble2 + parDouble3 * parDouble3) + * 100.0F); + if (i > 0) { + if (this.ridingEntity instanceof EntityMinecart) { + this.addStat(StatList.distanceByMinecartStat, i); + if (this.startMinecartRidingCoordinate == null) { + this.startMinecartRidingCoordinate = new BlockPos(this); + } else if (this.startMinecartRidingCoordinate.distanceSq( + (double) MathHelper.floor_double(this.posX), (double) MathHelper.floor_double(this.posY), + (double) MathHelper.floor_double(this.posZ)) >= 1000000.0D) { + this.triggerAchievement(AchievementList.onARail); + } + } else if (this.ridingEntity instanceof EntityBoat) { + this.addStat(StatList.distanceByBoatStat, i); + } else if (this.ridingEntity instanceof EntityPig) { + this.addStat(StatList.distanceByPigStat, i); + } else if (this.ridingEntity instanceof EntityHorse) { + this.addStat(StatList.distanceByHorseStat, i); } } - } else if (this.sleepTimer > 0) { - ++this.sleepTimer; - if (this.sleepTimer >= 110) { - this.sleepTimer = 0; - } } - super.onUpdate(); - if (!this.worldObj.isRemote && this.openContainer != null && !this.openContainer.canInteractWith(this)) { - this.closeScreen(); - this.openContainer = this.inventoryContainer; - } + } - if (this.isBurning() && this.capabilities.disableDamage) { - this.extinguish(); - } - - this.prevChasingPosX = this.chasingPosX; - this.prevChasingPosY = this.chasingPosY; - this.prevChasingPosZ = this.chasingPosZ; - double d5 = this.posX - this.chasingPosX; - double d0 = this.posY - this.chasingPosY; - double d1 = this.posZ - this.chasingPosZ; - double d2 = 10.0D; - if (d5 > d2) { - this.prevChasingPosX = this.chasingPosX = this.posX; - } - - if (d1 > d2) { - this.prevChasingPosZ = this.chasingPosZ = this.posZ; - } - - if (d0 > d2) { - this.prevChasingPosY = this.chasingPosY = this.posY; - } - - if (d5 < -d2) { - this.prevChasingPosX = this.chasingPosX = this.posX; - } - - if (d1 < -d2) { - this.prevChasingPosZ = this.chasingPosZ = this.posZ; - } - - if (d0 < -d2) { - this.prevChasingPosY = this.chasingPosY = this.posY; - } - - this.chasingPosX += d5 * 0.25D; - this.chasingPosZ += d1 * 0.25D; - this.chasingPosY += d0 * 0.25D; + /** + * + Adds a value to a movement statistic field - like run, walk, swin or climb. + */ + public void addMovementStat(double parDouble1, double parDouble2, double parDouble3) { if (this.ridingEntity == null) { - this.startMinecartRidingCoordinate = null; - } - - if (!this.worldObj.isRemote) { - this.foodStats.onUpdate(this); - this.triggerAchievement(StatList.minutesPlayedStat); - if (this.isEntityAlive()) { - this.triggerAchievement(StatList.timeSinceDeathStat); - } - } - - int i = 29999999; - double d3 = MathHelper.clamp_double(this.posX, -2.9999999E7D, 2.9999999E7D); - double d4 = MathHelper.clamp_double(this.posZ, -2.9999999E7D, 2.9999999E7D); - if (d3 != this.posX || d4 != this.posZ) { - this.setPosition(d3, this.posY, d4); - } - - } - - /**+ - * Return the amount of time this entity should stay in a portal - * before being transported. - */ - public int getMaxInPortalTime() { - return this.capabilities.disableDamage ? 0 : 80; - } - - protected String getSwimSound() { - return "game.player.swim"; - } - - protected String getSplashSound() { - return "game.player.swim.splash"; - } - - /**+ - * Return the amount of cooldown before this entity can use a - * portal again. - */ - public int getPortalCooldown() { - return 10; - } - - public void playSound(String s, float f, float f1) { - this.worldObj.playSoundToNearExcept(this, s, f, f1); - } - - /**+ - * Plays sounds and makes particles for item in use state - */ - protected void updateItemUse(ItemStack itemStackIn, int parInt1) { - if (itemStackIn.getItemUseAction() == EnumAction.DRINK) { - this.playSound("random.drink", 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F); - } - - if (itemStackIn.getItemUseAction() == EnumAction.EAT) { - for (int i = 0; i < parInt1; ++i) { - Vec3 vec3 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); - vec3 = vec3.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); - vec3 = vec3.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); - double d0 = (double) (-this.rand.nextFloat()) * 0.6D - 0.3D; - Vec3 vec31 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); - vec31 = vec31.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); - vec31 = vec31.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); - vec31 = vec31.addVector(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); - if (itemStackIn.getHasSubtypes()) { - this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, - vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, - new int[] { Item.getIdFromItem(itemStackIn.getItem()), itemStackIn.getMetadata() }); - } else { - this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, - vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, - new int[] { Item.getIdFromItem(itemStackIn.getItem()) }); + if (this.isInsideOfMaterial(Material.water)) { + int i = Math.round(MathHelper.sqrt_double( + parDouble1 * parDouble1 + parDouble2 * parDouble2 + parDouble3 * parDouble3) * 100.0F); + if (i > 0) { + this.addStat(StatList.distanceDoveStat, i); + this.addExhaustion(0.015F * (float) i * 0.01F); } - } - - this.playSound("random.eat", 0.5F + 0.5F * (float) this.rand.nextInt(2), - (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); - } - - } - - /**+ - * Used for when item use count runs out, ie: eating completed - */ - protected void onItemUseFinish() { - if (this.itemInUse != null) { - this.updateItemUse(this.itemInUse, 16); - int i = this.itemInUse.stackSize; - ItemStack itemstack = this.itemInUse.onItemUseFinish(this.worldObj, this); - if (itemstack != this.itemInUse || itemstack != null && itemstack.stackSize != i) { - this.inventory.mainInventory[this.inventory.currentItem] = itemstack; - if (itemstack.stackSize == 0) { - this.inventory.mainInventory[this.inventory.currentItem] = null; + } else if (this.isInWater()) { + int j = Math.round(MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble3 * parDouble3) * 100.0F); + if (j > 0) { + this.addStat(StatList.distanceSwumStat, j); + this.addExhaustion(0.015F * (float) j * 0.01F); } - } + } else if (this.isOnLadder()) { + if (parDouble2 > 0.0D) { + this.addStat(StatList.distanceClimbedStat, (int) Math.round(parDouble2 * 100.0D)); + } + } else if (this.onGround) { + int k = Math.round(MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble3 * parDouble3) * 100.0F); + if (k > 0) { + this.addStat(StatList.distanceWalkedStat, k); + if (this.isSprinting()) { + this.addStat(StatList.distanceSprintedStat, k); + this.addExhaustion(0.099999994F * (float) k * 0.01F); + } else { + if (this.isSneaking()) { + this.addStat(StatList.distanceCrouchedStat, k); + } - this.clearItemInUse(); - } - - } - - public void handleStatusUpdate(byte b0) { - if (b0 == 9) { - this.onItemUseFinish(); - } else if (b0 == 23) { - this.hasReducedDebug = false; - } else if (b0 == 22) { - this.hasReducedDebug = true; - } else { - super.handleStatusUpdate(b0); - } - - } - - /**+ - * Dead and sleeping entities cannot move - */ - protected boolean isMovementBlocked() { - return this.getHealth() <= 0.0F || this.isPlayerSleeping(); - } - - /**+ - * set current crafting inventory back to the 2x2 square - */ - protected void closeScreen() { - this.openContainer = this.inventoryContainer; - } - - /**+ - * Handles updating while being ridden by an entity - */ - public void updateRidden() { - if (!this.worldObj.isRemote && this.isSneaking()) { - this.mountEntity((Entity) null); - this.setSneaking(false); - } else { - double d0 = this.posX; - double d1 = this.posY; - double d2 = this.posZ; - float f = this.rotationYaw; - float f1 = this.rotationPitch; - super.updateRidden(); - this.prevCameraYaw = this.cameraYaw; - this.cameraYaw = 0.0F; - this.addMountedMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); - if (this.ridingEntity instanceof EntityPig) { - this.rotationPitch = f1; - this.rotationYaw = f; - this.renderYawOffset = ((EntityPig) this.ridingEntity).renderYawOffset; - } - - } - } - - /**+ - * Keeps moving the entity up so it isn't colliding with blocks - * and other requirements for this entity to be spawned (only - * actually used on players though its also on Entity) - */ - public void preparePlayerToSpawn() { - this.setSize(0.6F, 1.8F); - super.preparePlayerToSpawn(); - this.setHealth(this.getMaxHealth()); - this.deathTime = 0; - } - - protected void updateEntityActionState() { - super.updateEntityActionState(); - this.updateArmSwingProgress(); - this.rotationYawHead = this.rotationYaw; - } - - /**+ - * Called frequently so the entity can update its state every - * tick as required. For example, zombies and skeletons use this - * to react to sunlight and start to burn. - */ - public void onLivingUpdate() { - if (this.flyToggleTimer > 0) { - --this.flyToggleTimer; - } - - if (this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL - && this.worldObj.getGameRules().getBoolean("naturalRegeneration")) { - if (this.getHealth() < this.getMaxHealth() && this.ticksExisted % 20 == 0) { - this.heal(1.0F); - } - - if (this.foodStats.needFood() && this.ticksExisted % 10 == 0) { - this.foodStats.setFoodLevel(this.foodStats.getFoodLevel() + 1); - } - } - - this.inventory.decrementAnimations(); - this.prevCameraYaw = this.cameraYaw; - super.onLivingUpdate(); - IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); - if (!this.worldObj.isRemote) { - iattributeinstance.setBaseValue((double) this.capabilities.getWalkSpeed()); - } - - this.jumpMovementFactor = this.speedInAir; - if (this.isSprinting()) { - this.jumpMovementFactor = (float) ((double) this.jumpMovementFactor + (double) this.speedInAir * 0.3D); - } - - this.setAIMoveSpeed((float) iattributeinstance.getAttributeValue()); - float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); - float f1 = (float) (Math.atan(-this.motionY * 0.20000000298023224D) * 15.0D); - if (f > 0.1F) { - f = 0.1F; - } - - if (!this.onGround || this.getHealth() <= 0.0F) { - f = 0.0F; - } - - if (this.onGround || this.getHealth() <= 0.0F) { - f1 = 0.0F; - } - - this.cameraYaw += (f - this.cameraYaw) * 0.4F; - this.cameraPitch += (f1 - this.cameraPitch) * 0.8F; - if (this.getHealth() > 0.0F && !this.isSpectator()) { - AxisAlignedBB axisalignedbb = null; - if (this.ridingEntity != null && !this.ridingEntity.isDead) { - axisalignedbb = this.getEntityBoundingBox().union(this.ridingEntity.getEntityBoundingBox()).expand(1.0D, - 0.0D, 1.0D); + this.addExhaustion(0.01F * (float) k * 0.01F); + } + } } else { - axisalignedbb = this.getEntityBoundingBox().expand(1.0D, 0.5D, 1.0D); - } - - List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, axisalignedbb); - - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - if (!entity.isDead) { - this.collideWithPlayer(entity); + int l = Math.round(MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble3 * parDouble3) * 100.0F); + if (l > 25) { + this.addStat(StatList.distanceFlownStat, l); } } + } - } - private void collideWithPlayer(Entity parEntity) { - parEntity.onCollideWithPlayer(this); - } - - public int getScore() { - return this.dataWatcher.getWatchableObjectInt(18); - } - - /**+ - * Set player's score - */ - public void setScore(int parInt1) { - this.dataWatcher.updateObject(18, Integer.valueOf(parInt1)); - } - - /**+ - * Add to player's score + /** + * + Add to player's score */ public void addScore(int parInt1) { int i = this.getScore(); this.dataWatcher.updateObject(18, Integer.valueOf(i + parInt1)); } - /**+ - * Called when the mob's health reaches 0. + /** + * + Adds a value to a statistic field. */ - public void onDeath(DamageSource damagesource) { - super.onDeath(damagesource); - this.setSize(0.2F, 0.2F); - this.setPosition(this.posX, this.posY, this.posZ); - this.motionY = 0.10000000149011612D; - if (this.getName().equals("Notch")) { - this.dropItem(new ItemStack(Items.apple, 1), true, false); - } - - if (!this.worldObj.getGameRules().getBoolean("keepInventory")) { - this.inventory.dropAllItems(); - } - - if (damagesource != null) { - this.motionX = (double) (-MathHelper.cos((this.attackedAtYaw + this.rotationYaw) * 3.1415927F / 180.0F) - * 0.1F); - this.motionZ = (double) (-MathHelper.sin((this.attackedAtYaw + this.rotationYaw) * 3.1415927F / 180.0F) - * 0.1F); - } else { - this.motionX = this.motionZ = 0.0D; - } - - this.triggerAchievement(StatList.deathsStat); - this.func_175145_a(StatList.timeSinceDeathStat); + public void addStat(StatBase var1, int var2) { } - /**+ - * Returns the sound this mob makes when it is hurt. - */ - protected String getHurtSound() { - return "game.player.hurt"; - } - - /**+ - * Returns the sound this mob makes on death. - */ - protected String getDeathSound() { - return "game.player.die"; - } - - /**+ - * Adds a value to the player score. Currently not actually used - * and the entity passed in does nothing. Args: entity, - * scoreToAdd + /** + * + Adds a value to the player score. Currently not actually used and the + * entity passed in does nothing. Args: entity, scoreToAdd */ public void addToPlayerScore(Entity entity, int i) { this.addScore(i); @@ -662,229 +409,14 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS } - private Collection func_175137_e(Entity parEntity) { - ScorePlayerTeam scoreplayerteam = this.getWorldScoreboard().getPlayersTeam(this.getName()); - if (scoreplayerteam != null) { - int i = scoreplayerteam.getChatFormat().getColorIndex(); - if (i >= 0 && i < IScoreObjectiveCriteria.field_178793_i.length) { - for (ScoreObjective scoreobjective : this.getWorldScoreboard() - .getObjectivesFromCriteria(IScoreObjectiveCriteria.field_178793_i[i])) { - Score score = this.getWorldScoreboard().getValueFromObjective(parEntity.getName(), scoreobjective); - score.func_96648_a(); - } - } - } - - ScorePlayerTeam scoreplayerteam1 = this.getWorldScoreboard().getPlayersTeam(parEntity.getName()); - if (scoreplayerteam1 != null) { - int j = scoreplayerteam1.getChatFormat().getColorIndex(); - if (j >= 0 && j < IScoreObjectiveCriteria.field_178792_h.length) { - return this.getWorldScoreboard().getObjectivesFromCriteria(IScoreObjectiveCriteria.field_178792_h[j]); - } - } - - return Lists.newArrayList(); + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.getAttributeMap().registerAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(1.0D); + this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.10000000149011612D); } - /**+ - * Called when player presses the drop item key - */ - public EntityItem dropOneItem(boolean flag) { - return this.dropItem(this.inventory.decrStackSize(this.inventory.currentItem, - flag && this.inventory.getCurrentItem() != null ? this.inventory.getCurrentItem().stackSize : 1), false, - true); - } - - /**+ - * Args: itemstack, flag - */ - public EntityItem dropPlayerItemWithRandomChoice(ItemStack itemStackIn, boolean unused) { - return this.dropItem(itemStackIn, false, false); - } - - public EntityItem dropItem(ItemStack droppedItem, boolean dropAround, boolean traceItem) { - if (droppedItem == null) { - return null; - } else if (droppedItem.stackSize == 0) { - return null; - } else { - double d0 = this.posY - 0.30000001192092896D + (double) this.getEyeHeight(); - EntityItem entityitem = new EntityItem(this.worldObj, this.posX, d0, this.posZ, droppedItem); - entityitem.setPickupDelay(40); - if (traceItem) { - entityitem.setThrower(this.getName()); - } - - if (dropAround) { - float f = this.rand.nextFloat() * 0.5F; - float f1 = this.rand.nextFloat() * 3.1415927F * 2.0F; - entityitem.motionX = (double) (-MathHelper.sin(f1) * f); - entityitem.motionZ = (double) (MathHelper.cos(f1) * f); - entityitem.motionY = 0.20000000298023224D; - } else { - float f2 = 0.3F; - entityitem.motionX = (double) (-MathHelper.sin(this.rotationYaw / 180.0F * 3.1415927F) - * MathHelper.cos(this.rotationPitch / 180.0F * 3.1415927F) * f2); - entityitem.motionZ = (double) (MathHelper.cos(this.rotationYaw / 180.0F * 3.1415927F) - * MathHelper.cos(this.rotationPitch / 180.0F * 3.1415927F) * f2); - entityitem.motionY = (double) (-MathHelper.sin(this.rotationPitch / 180.0F * 3.1415927F) * f2 + 0.1F); - float f3 = this.rand.nextFloat() * 3.1415927F * 2.0F; - f2 = 0.02F * this.rand.nextFloat(); - entityitem.motionX += Math.cos((double) f3) * (double) f2; - entityitem.motionY += (double) ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F); - entityitem.motionZ += Math.sin((double) f3) * (double) f2; - } - - this.joinEntityItemWithWorld(entityitem); - if (traceItem) { - this.triggerAchievement(StatList.dropStat); - } - - return entityitem; - } - } - - /**+ - * Joins the passed in entity item with the world. Args: - * entityItem - */ - protected void joinEntityItemWithWorld(EntityItem entityitem) { - this.worldObj.spawnEntityInWorld(entityitem); - } - - /**+ - * Block hardness will be further counted in - * net/minecraft/block/Block.getPlayerRelativeBlockHardness - */ - public float getToolDigEfficiency(Block parBlock) { - float f = this.inventory.getStrVsBlock(parBlock); - if (f > 1.0F) { - int i = EnchantmentHelper.getEfficiencyModifier(this); - ItemStack itemstack = this.inventory.getCurrentItem(); - if (i > 0 && itemstack != null) { - f += (float) (i * i + 1); - } - } - - if (this.isPotionActive(Potion.digSpeed)) { - f *= 1.0F + (float) (this.getActivePotionEffect(Potion.digSpeed).getAmplifier() + 1) * 0.2F; - } - - if (this.isPotionActive(Potion.digSlowdown)) { - float f1 = 1.0F; - switch (this.getActivePotionEffect(Potion.digSlowdown).getAmplifier()) { - case 0: - f1 = 0.3F; - break; - case 1: - f1 = 0.09F; - break; - case 2: - f1 = 0.0027F; - break; - case 3: - default: - f1 = 8.1E-4F; - } - - f *= f1; - } - - if (this.isInsideOfMaterial(Material.water) && !EnchantmentHelper.getAquaAffinityModifier(this)) { - f /= 5.0F; - } - - if (!this.onGround) { - f /= 5.0F; - } - - return f; - } - - /**+ - * Checks if the player has the ability to harvest a block - * (checks current inventory item for a tool if necessary) - */ - public boolean canHarvestBlock(Block blockToHarvest) { - return this.inventory.canHeldItemHarvest(blockToHarvest); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - this.entityUniqueID = getUUID(this.gameProfile); - NBTTagList nbttaglist = nbttagcompound.getTagList("Inventory", 10); - this.inventory.readFromNBT(nbttaglist); - this.inventory.currentItem = nbttagcompound.getInteger("SelectedItemSlot"); - this.sleeping = nbttagcompound.getBoolean("Sleeping"); - this.sleepTimer = nbttagcompound.getShort("SleepTimer"); - this.experience = nbttagcompound.getFloat("XpP"); - this.experienceLevel = nbttagcompound.getInteger("XpLevel"); - this.experienceTotal = nbttagcompound.getInteger("XpTotal"); - this.xpSeed = nbttagcompound.getInteger("XpSeed"); - if (this.xpSeed == 0) { - this.xpSeed = this.rand.nextInt(); - } - - this.setScore(nbttagcompound.getInteger("Score")); - if (this.sleeping) { - this.playerLocation = new BlockPos(this); - this.wakeUpPlayer(true, true, false); - } - - if (nbttagcompound.hasKey("SpawnX", 99) && nbttagcompound.hasKey("SpawnY", 99) - && nbttagcompound.hasKey("SpawnZ", 99)) { - this.spawnChunk = new BlockPos(nbttagcompound.getInteger("SpawnX"), nbttagcompound.getInteger("SpawnY"), - nbttagcompound.getInteger("SpawnZ")); - this.spawnForced = nbttagcompound.getBoolean("SpawnForced"); - } - - this.foodStats.readNBT(nbttagcompound); - this.capabilities.readCapabilitiesFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("EnderItems", 9)) { - NBTTagList nbttaglist1 = nbttagcompound.getTagList("EnderItems", 10); - this.theInventoryEnderChest.loadInventoryFromNBT(nbttaglist1); - } - - } - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setTag("Inventory", this.inventory.writeToNBT(new NBTTagList())); - nbttagcompound.setInteger("SelectedItemSlot", this.inventory.currentItem); - nbttagcompound.setBoolean("Sleeping", this.sleeping); - nbttagcompound.setShort("SleepTimer", (short) this.sleepTimer); - nbttagcompound.setFloat("XpP", this.experience); - nbttagcompound.setInteger("XpLevel", this.experienceLevel); - nbttagcompound.setInteger("XpTotal", this.experienceTotal); - nbttagcompound.setInteger("XpSeed", this.xpSeed); - nbttagcompound.setInteger("Score", this.getScore()); - if (this.spawnChunk != null) { - nbttagcompound.setInteger("SpawnX", this.spawnChunk.getX()); - nbttagcompound.setInteger("SpawnY", this.spawnChunk.getY()); - nbttagcompound.setInteger("SpawnZ", this.spawnChunk.getZ()); - nbttagcompound.setBoolean("SpawnForced", this.spawnForced); - } - - this.foodStats.writeNBT(nbttagcompound); - this.capabilities.writeCapabilitiesToNBT(nbttagcompound); - nbttagcompound.setTag("EnderItems", this.theInventoryEnderChest.saveInventoryToNBT()); - ItemStack itemstack = this.inventory.getCurrentItem(); - if (itemstack != null && itemstack.getItem() != null) { - nbttagcompound.setTag("SelectedItem", itemstack.writeToNBT(new NBTTagCompound())); - } - - } - - /**+ - * Called when the entity is attacked. + /** + * + Called when the entity is attacked. */ public boolean attackEntityFrom(DamageSource damagesource, float f) { if (this.isEntityInvulnerable(damagesource)) { @@ -928,176 +460,9 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS } } - public boolean canAttackPlayer(EntityPlayer entityplayer) { - Team team = this.getTeam(); - Team team1 = entityplayer.getTeam(); - return team == null ? true : (!team.isSameTeam(team1) ? true : team.getAllowFriendlyFire()); - } - - protected void damageArmor(float f) { - this.inventory.damageArmor(f); - } - - /**+ - * Returns the current armor value as determined by a call to - * InventoryPlayer.getTotalArmorValue - */ - public int getTotalArmorValue() { - return this.inventory.getTotalArmorValue(); - } - - /**+ - * When searching for vulnerable players, if a player is - * invisible, the return value of this is the chance of seeing - * them anyway. - */ - public float getArmorVisibility() { - int i = 0; - - ItemStack[] stack = this.inventory.armorInventory; - for (int j = 0; j < stack.length; ++j) { - if (stack[j] != null) { - ++i; - } - } - - return (float) i / (float) this.inventory.armorInventory.length; - } - - /**+ - * Deals damage to the entity. If its a EntityPlayer then will - * take damage from the armor first and then health second with - * the reduced value. Args: damageAmount - */ - protected void damageEntity(DamageSource damagesource, float f) { - if (!this.isEntityInvulnerable(damagesource)) { - if (!damagesource.isUnblockable() && this.isBlocking() && f > 0.0F) { - f = (1.0F + f) * 0.5F; - } - - f = this.applyArmorCalculations(damagesource, f); - f = this.applyPotionDamageCalculations(damagesource, f); - float f1 = f; - f = Math.max(f - this.getAbsorptionAmount(), 0.0F); - this.setAbsorptionAmount(this.getAbsorptionAmount() - (f1 - f)); - if (f != 0.0F) { - this.addExhaustion(damagesource.getHungerDamage()); - float f2 = this.getHealth(); - this.setHealth(this.getHealth() - f); - this.getCombatTracker().trackDamage(damagesource, f2, f); - if (f < 3.4028235E37F) { - this.addStat(StatList.damageTakenStat, Math.round(f * 10.0F)); - } - - } - } - } - - public void openEditSign(TileEntitySign var1) { - } - - public void openEditCommandBlock(CommandBlockLogic var1) { - } - - public void displayVillagerTradeGui(IMerchant var1) { - } - - /**+ - * Displays the GUI for interacting with a chest inventory. - * Args: chestInventory - */ - public void displayGUIChest(IInventory var1) { - } - - public void displayGUIHorse(EntityHorse var1, IInventory var2) { - } - - public void displayGui(IInteractionObject var1) { - } - - /**+ - * Displays the GUI for interacting with a book. - */ - public void displayGUIBook(ItemStack var1) { - } - - public boolean interactWith(Entity parEntity) { - if (this.isSpectator()) { - if (parEntity instanceof IInventory) { - this.displayGUIChest((IInventory) parEntity); - } - - return false; - } else { - ItemStack itemstack = this.getCurrentEquippedItem(); - ItemStack itemstack1 = itemstack != null ? itemstack.copy() : null; - if (!parEntity.interactFirst(this)) { - if (itemstack != null && parEntity instanceof EntityLivingBase) { - if (this.capabilities.isCreativeMode) { - itemstack = itemstack1; - } - - if (itemstack.interactWithEntity(this, (EntityLivingBase) parEntity)) { - if (itemstack.stackSize <= 0 && !this.capabilities.isCreativeMode) { - this.destroyCurrentEquippedItem(); - } - - return true; - } - } else if (!this.worldObj.isRemote && MinecraftServer.getServer().worldServers[0].getWorldInfo() - .getGameRulesInstance().getBoolean("clickToRide") && itemstack == null - && parEntity instanceof EntityPlayer) { - EntityPlayer otherPlayer = (EntityPlayer) parEntity; - while (otherPlayer.riddenByEntity instanceof EntityPlayer) { - otherPlayer = (EntityPlayer) otherPlayer.riddenByEntity; - } - if (otherPlayer.riddenByEntity == null && otherPlayer != this) { - mountEntity(otherPlayer); - return true; - } - } - - return false; - } else { - if (itemstack != null && itemstack == this.getCurrentEquippedItem()) { - if (itemstack.stackSize <= 0 && !this.capabilities.isCreativeMode) { - this.destroyCurrentEquippedItem(); - } else if (itemstack.stackSize < itemstack1.stackSize && this.capabilities.isCreativeMode) { - itemstack.stackSize = itemstack1.stackSize; - } - } - - return true; - } - } - } - - /**+ - * Returns the currently being used item by the player. - */ - public ItemStack getCurrentEquippedItem() { - return this.inventory.getCurrentItem(); - } - - /**+ - * Destroys the currently equipped item from the player's - * inventory. - */ - public void destroyCurrentEquippedItem() { - this.inventory.setInventorySlotContents(this.inventory.currentItem, (ItemStack) null); - } - - /**+ - * Returns the Y Offset of this entity. - */ - public double getYOffset() { - return -0.35D; - } - - /**+ - * Attacks for the player the targeted entity with the currently - * equipped item. The equipped item has hitEntity called on it. - * Args: targetEntity + /** + * + Attacks for the player the targeted entity with the currently equipped + * item. The equipped item has hitEntity called on it. Args: targetEntity */ public void attackTargetEntityWithCurrentItem(Entity entity) { if (entity.canAttackWithItem()) { @@ -1209,21 +574,1226 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS } } - /**+ - * Called when the player performs a critical hit on the Entity. - * Args: entity that was hit critically + public boolean canAttackPlayer(EntityPlayer entityplayer) { + Team team = this.getTeam(); + Team team1 = entityplayer.getTeam(); + return team == null ? true : (!team.isSameTeam(team1) ? true : team.getAllowFriendlyFire()); + } + + public boolean canEat(boolean ignoreHunger) { + return (ignoreHunger || this.foodStats.needFood()) && !this.capabilities.disableDamage; + } + + /** + * + Checks if the player has the ability to harvest a block (checks current + * inventory item for a tool if necessary) + */ + public boolean canHarvestBlock(Block blockToHarvest) { + return this.inventory.canHeldItemHarvest(blockToHarvest); + } + + /** + * + Check whether this player can open an inventory locked with the given + * LockCode. + */ + public boolean canOpen(LockCode code) { + if (code.isEmpty()) { + return true; + } else { + ItemStack itemstack = this.getCurrentEquippedItem(); + return itemstack != null && itemstack.hasDisplayName() ? itemstack.getDisplayName().equals(code.getLock()) + : false; + } + } + + public boolean canPlayerEdit(BlockPos parBlockPos, EnumFacing parEnumFacing, ItemStack parItemStack) { + if (this.capabilities.allowEdit) { + return true; + } else if (parItemStack == null) { + return false; + } else { + BlockPos blockpos = parBlockPos.offset(parEnumFacing.getOpposite()); + Block block = this.worldObj.getBlockState(blockpos).getBlock(); + return parItemStack.canPlaceOn(block) || parItemStack.canEditBlocks(); + } + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return !this.capabilities.isFlying; + } + + public void clearItemInUse() { + this.itemInUse = null; + this.itemInUseCount = 0; + if (!this.worldObj.isRemote) { + this.setEating(false); + } + + } + + /** + * + Copies the values from the given player into this player if boolean par2 is + * true. Always clones Ender Chest Inventory. + */ + public void clonePlayer(EntityPlayer entityplayer, boolean flag) { + if (flag) { + this.inventory.copyInventory(entityplayer.inventory); + this.setHealth(entityplayer.getHealth()); + this.foodStats = entityplayer.foodStats; + this.experienceLevel = entityplayer.experienceLevel; + this.experienceTotal = entityplayer.experienceTotal; + this.experience = entityplayer.experience; + this.setScore(entityplayer.getScore()); + this.field_181016_an = entityplayer.field_181016_an; + this.field_181017_ao = entityplayer.field_181017_ao; + this.field_181018_ap = entityplayer.field_181018_ap; + } else if (this.worldObj.getGameRules().getBoolean("keepInventory")) { + this.inventory.copyInventory(entityplayer.inventory); + this.experienceLevel = entityplayer.experienceLevel; + this.experienceTotal = entityplayer.experienceTotal; + this.experience = entityplayer.experience; + this.setScore(entityplayer.getScore()); + } + + this.xpSeed = entityplayer.xpSeed; + this.theInventoryEnderChest = entityplayer.theInventoryEnderChest; + this.getDataWatcher().updateObject(10, Byte.valueOf(entityplayer.getDataWatcher().getWatchableObjectByte(10))); + } + + /** + * + set current crafting inventory back to the 2x2 square + */ + protected void closeScreen() { + this.openContainer = this.inventoryContainer; + } + + private void collideWithPlayer(Entity parEntity) { + parEntity.onCollideWithPlayer(this); + } + + protected void damageArmor(float f) { + this.inventory.damageArmor(f); + } + + /** + * + Deals damage to the entity. If its a EntityPlayer then will take damage + * from the armor first and then health second with the reduced value. Args: + * damageAmount + */ + protected void damageEntity(DamageSource damagesource, float f) { + if (!this.isEntityInvulnerable(damagesource)) { + if (!damagesource.isUnblockable() && this.isBlocking() && f > 0.0F) { + f = (1.0F + f) * 0.5F; + } + + f = this.applyArmorCalculations(damagesource, f); + f = this.applyPotionDamageCalculations(damagesource, f); + float f1 = f; + f = Math.max(f - this.getAbsorptionAmount(), 0.0F); + this.setAbsorptionAmount(this.getAbsorptionAmount() - (f1 - f)); + if (f != 0.0F) { + this.addExhaustion(damagesource.getHungerDamage()); + float f2 = this.getHealth(); + this.setHealth(this.getHealth() - f); + this.getCombatTracker().trackDamage(damagesource, f2, f); + if (f < 3.4028235E37F) { + this.addStat(StatList.damageTakenStat, Math.round(f * 10.0F)); + } + + } + } + } + + /** + * + Destroys the currently equipped item from the player's inventory. + */ + public void destroyCurrentEquippedItem() { + this.inventory.setInventorySlotContents(this.inventory.currentItem, (ItemStack) null); + } + + public void displayGui(IInteractionObject var1) { + } + + /** + * + Displays the GUI for interacting with a book. + */ + public void displayGUIBook(ItemStack var1) { + } + + /** + * + Displays the GUI for interacting with a chest inventory. Args: + * chestInventory + */ + public void displayGUIChest(IInventory var1) { + } + + public void displayGUIHorse(EntityHorse var1, IInventory var2) { + } + + public void displayVillagerTradeGui(IMerchant var1) { + } + + public EntityItem dropItem(ItemStack droppedItem, boolean dropAround, boolean traceItem) { + if (droppedItem == null) { + return null; + } else if (droppedItem.stackSize == 0) { + return null; + } else { + double d0 = this.posY - 0.30000001192092896D + (double) this.getEyeHeight(); + EntityItem entityitem = new EntityItem(this.worldObj, this.posX, d0, this.posZ, droppedItem); + entityitem.setPickupDelay(40); + if (traceItem) { + entityitem.setThrower(this.getName()); + } + + if (dropAround) { + float f = this.rand.nextFloat() * 0.5F; + float f1 = this.rand.nextFloat() * 3.1415927F * 2.0F; + entityitem.motionX = (double) (-MathHelper.sin(f1) * f); + entityitem.motionZ = (double) (MathHelper.cos(f1) * f); + entityitem.motionY = 0.20000000298023224D; + } else { + float f2 = 0.3F; + entityitem.motionX = (double) (-MathHelper.sin(this.rotationYaw / 180.0F * 3.1415927F) + * MathHelper.cos(this.rotationPitch / 180.0F * 3.1415927F) * f2); + entityitem.motionZ = (double) (MathHelper.cos(this.rotationYaw / 180.0F * 3.1415927F) + * MathHelper.cos(this.rotationPitch / 180.0F * 3.1415927F) * f2); + entityitem.motionY = (double) (-MathHelper.sin(this.rotationPitch / 180.0F * 3.1415927F) * f2 + 0.1F); + float f3 = this.rand.nextFloat() * 3.1415927F * 2.0F; + f2 = 0.02F * this.rand.nextFloat(); + entityitem.motionX += Math.cos((double) f3) * (double) f2; + entityitem.motionY += (double) ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.1F); + entityitem.motionZ += Math.sin((double) f3) * (double) f2; + } + + this.joinEntityItemWithWorld(entityitem); + if (traceItem) { + this.triggerAchievement(StatList.dropStat); + } + + return entityitem; + } + } + + /** + * + Called when player presses the drop item key + */ + public EntityItem dropOneItem(boolean flag) { + return this.dropItem(this.inventory.decrStackSize(this.inventory.currentItem, + flag && this.inventory.getCurrentItem() != null ? this.inventory.getCurrentItem().stackSize : 1), false, + true); + } + + /** + * + Args: itemstack, flag + */ + public EntityItem dropPlayerItemWithRandomChoice(ItemStack itemStackIn, boolean unused) { + return this.dropItem(itemStackIn, false, false); + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); + this.dataWatcher.addObject(17, Float.valueOf(0.0F)); + this.dataWatcher.addObject(18, Integer.valueOf(0)); + this.dataWatcher.addObject(10, Byte.valueOf((byte) 0)); + } + + public void fall(float f, float f1) { + if (!this.capabilities.allowFlying) { + if (f >= 2.0F) { + this.addStat(StatList.distanceFallenStat, (int) Math.round((double) f * 100.0D)); + } + + super.fall(f, f1); + } + } + + private Collection func_175137_e(Entity parEntity) { + ScorePlayerTeam scoreplayerteam = this.getWorldScoreboard().getPlayersTeam(this.getName()); + if (scoreplayerteam != null) { + int i = scoreplayerteam.getChatFormat().getColorIndex(); + if (i >= 0 && i < IScoreObjectiveCriteria.field_178793_i.length) { + for (ScoreObjective scoreobjective : this.getWorldScoreboard() + .getObjectivesFromCriteria(IScoreObjectiveCriteria.field_178793_i[i])) { + Score score = this.getWorldScoreboard().getValueFromObjective(parEntity.getName(), scoreobjective); + score.func_96648_a(); + } + } + } + + ScorePlayerTeam scoreplayerteam1 = this.getWorldScoreboard().getPlayersTeam(parEntity.getName()); + if (scoreplayerteam1 != null) { + int j = scoreplayerteam1.getChatFormat().getColorIndex(); + if (j >= 0 && j < IScoreObjectiveCriteria.field_178792_h.length) { + return this.getWorldScoreboard().getObjectivesFromCriteria(IScoreObjectiveCriteria.field_178792_h[j]); + } + } + + return Lists.newArrayList(); + } + + private void func_175139_a(EnumFacing parEnumFacing) { + this.renderOffsetX = 0.0F; + this.renderOffsetZ = 0.0F; + switch (parEnumFacing) { + case SOUTH: + this.renderOffsetZ = -1.8F; + break; + case NORTH: + this.renderOffsetZ = 1.8F; + break; + case WEST: + this.renderOffsetX = 1.8F; + break; + case EAST: + this.renderOffsetX = -1.8F; + } + + } + + public void func_175145_a(StatBase var1) { + } + + public float getAbsorptionAmount() { + return this.getDataWatcher().getWatchableObjectFloat(17); + } + + /** + * + the movespeed used for the new AI system + */ + public float getAIMoveSpeed() { + return (float) this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue(); + } + + public boolean getAlwaysRenderNameTagForRender() { + return true; + } + + /** + * + When searching for vulnerable players, if a player is invisible, the return + * value of this is the chance of seeing them anyway. + */ + public float getArmorVisibility() { + int i = 0; + + ItemStack[] stack = this.inventory.armorInventory; + for (int j = 0; j < stack.length; ++j) { + if (stack[j] != null) { + ++i; + } + } + + return (float) i / (float) this.inventory.armorInventory.length; + } + + public BlockPos getBedLocation() { + return this.spawnChunk; + } + + /** + * + Returns the orientation of the bed in degrees. + */ + public float getBedOrientationInDegrees() { + if (this.playerLocation != null) { + EnumFacing enumfacing = (EnumFacing) this.worldObj.getBlockState(this.playerLocation) + .getValue(BlockDirectional.FACING); + switch (enumfacing) { + case SOUTH: + return 90.0F; + case NORTH: + return 270.0F; + case WEST: + return 0.0F; + case EAST: + return 180.0F; + } + } + + return 0.0F; + } + + public ItemStack getCurrentArmor(int i) { + return this.inventory.armorItemInSlot(i); + } + + /** + * + Returns the currently being used item by the player. + */ + public ItemStack getCurrentEquippedItem() { + return this.inventory.getCurrentItem(); + } + + /** + * + Returns the sound this mob makes on death. + */ + protected String getDeathSound() { + return "game.player.die"; + } + + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + ChatComponentText chatcomponenttext = new ChatComponentText( + ScorePlayerTeam.formatPlayerName(this.getTeam(), this.getName())); + chatcomponenttext.getChatStyle() + .setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/msg " + this.getName() + " ")); + chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); + chatcomponenttext.getChatStyle().setInsertion(this.getName()); + return chatcomponenttext; + } + + /** + * + 0: Tool in Hand; 1-4: Armor + */ + public ItemStack getEquipmentInSlot(int i) { + return i == 0 ? this.inventory.getCurrentItem() : this.inventory.armorInventory[i - 1]; + } + + /** + * + Get the experience points the entity currently has. + */ + protected int getExperiencePoints(EntityPlayer var1) { + if (this.worldObj.getGameRules().getBoolean("keepInventory")) { + return 0; + } else { + int i = this.experienceLevel * 7; + return i > 100 ? 100 : i; + } + } + + public float getEyeHeight() { + float f = 1.62F; + if (this.isPlayerSleeping()) { + f = 0.2F; + } + + if (this.isSneaking()) { + f -= 0.08F; + } + + return f; + } + + protected String getFallSoundString(int i) { + return i > 4 ? "game.player.hurt.fall.big" : "game.player.hurt.fall.small"; + } + + /** + * + Returns the player's FoodStats object. + */ + public FoodStats getFoodStats() { + return this.foodStats; + } + + /** + * + Returns the GameProfile for this player + */ + public GameProfile getGameProfile() { + return this.gameProfile; + } + + /** + * + Returns the item that this EntityLiving is holding, if any. + */ + public ItemStack getHeldItem() { + return this.inventory.getCurrentItem(); + } + + /** + * + Returns the sound this mob makes when it is hurt. + */ + protected String getHurtSound() { + return "game.player.hurt"; + } + + /** + * + returns the inventory of this entity (only used in EntityPlayerMP it seems) + */ + public ItemStack[] getInventory() { + return this.inventory.armorInventory; + } + + /** + * + Returns the InventoryEnderChest of this player. + */ + public InventoryEnderChest getInventoryEnderChest() { + return this.theInventoryEnderChest; + } + + /** + * + returns the ItemStack containing the itemInUse + */ + public ItemStack getItemInUse() { + return this.itemInUse; + } + + /** + * + Returns the item in use count + */ + public int getItemInUseCount() { + return this.itemInUseCount; + } + + /** + * + gets the duration for how long the current itemInUse has been in use + */ + public int getItemInUseDuration() { + return this.isUsingItem() ? this.itemInUse.getMaxItemUseDuration() - this.itemInUseCount : 0; + } + + public boolean getItemShouldUseOnTouchEagler() { + if (itemInUse != null) { + return itemInUse.getItem().shouldUseOnTouchEagler(itemInUse); + } else { + ItemStack st = getHeldItem(); + return st != null && st.getItem().shouldUseOnTouchEagler(st); + } + } + + /** + * + Return the amount of time this entity should stay in a portal before being + * transported. + */ + public int getMaxInPortalTime() { + return this.capabilities.disableDamage ? 0 : 80; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.gameProfile.getName(); + } + + /** + * + Return the amount of cooldown before this entity can use a portal again. + */ + public int getPortalCooldown() { + return 10; + } + + public int getScore() { + return this.dataWatcher.getWatchableObjectInt(18); + } + + public int getSleepTimer() { + return this.sleepTimer; + } + + protected String getSplashSound() { + return "game.player.swim.splash"; + } + + protected String getSwimSound() { + return "game.player.swim"; + } + + public Team getTeam() { + return this.getWorldScoreboard().getPlayersTeam(this.getName()); + } + + /** + * + Block hardness will be further counted in + * net/minecraft/block/Block.getPlayerRelativeBlockHardness + */ + public float getToolDigEfficiency(Block parBlock) { + float f = this.inventory.getStrVsBlock(parBlock); + if (f > 1.0F) { + int i = EnchantmentHelper.getEfficiencyModifier(this); + ItemStack itemstack = this.inventory.getCurrentItem(); + if (i > 0 && itemstack != null) { + f += (float) (i * i + 1); + } + } + + if (this.isPotionActive(Potion.digSpeed)) { + f *= 1.0F + (float) (this.getActivePotionEffect(Potion.digSpeed).getAmplifier() + 1) * 0.2F; + } + + if (this.isPotionActive(Potion.digSlowdown)) { + float f1 = 1.0F; + switch (this.getActivePotionEffect(Potion.digSlowdown).getAmplifier()) { + case 0: + f1 = 0.3F; + break; + case 1: + f1 = 0.09F; + break; + case 2: + f1 = 0.0027F; + break; + case 3: + default: + f1 = 8.1E-4F; + } + + f *= f1; + } + + if (this.isInsideOfMaterial(Material.water) && !EnchantmentHelper.getAquaAffinityModifier(this)) { + f /= 5.0F; + } + + if (!this.onGround) { + f /= 5.0F; + } + + return f; + } + + /** + * + Returns the current armor value as determined by a call to + * InventoryPlayer.getTotalArmorValue + */ + public int getTotalArmorValue() { + return this.inventory.getTotalArmorValue(); + } + + public Scoreboard getWorldScoreboard() { + return this.worldObj.getScoreboard(); + } + + public int getXPSeed() { + return this.xpSeed; + } + + /** + * + Returns the Y Offset of this entity. + */ + public double getYOffset() { + return -0.35D; + } + + public void handleStatusUpdate(byte b0) { + if (b0 == 9) { + this.onItemUseFinish(); + } else if (b0 == 23) { + this.hasReducedDebug = false; + } else if (b0 == 22) { + this.hasReducedDebug = true; + } else { + super.handleStatusUpdate(b0); + } + + } + + /** + * + Whether the "reducedDebugInfo" option is active for this player. + */ + public boolean hasReducedDebug() { + return this.hasReducedDebug; + } + + public boolean interactWith(Entity parEntity) { + if (this.isSpectator()) { + if (parEntity instanceof IInventory) { + this.displayGUIChest((IInventory) parEntity); + } + + return false; + } else { + ItemStack itemstack = this.getCurrentEquippedItem(); + ItemStack itemstack1 = itemstack != null ? itemstack.copy() : null; + if (!parEntity.interactFirst(this)) { + if (itemstack != null && parEntity instanceof EntityLivingBase) { + if (this.capabilities.isCreativeMode) { + itemstack = itemstack1; + } + + if (itemstack.interactWithEntity(this, (EntityLivingBase) parEntity)) { + if (itemstack.stackSize <= 0 && !this.capabilities.isCreativeMode) { + this.destroyCurrentEquippedItem(); + } + + return true; + } + } else if (!this.worldObj.isRemote && MinecraftServer.getServer().worldServers[0].getWorldInfo() + .getGameRulesInstance().getBoolean("clickToRide") && itemstack == null + && parEntity instanceof EntityPlayer) { + EntityPlayer otherPlayer = (EntityPlayer) parEntity; + while (otherPlayer.riddenByEntity instanceof EntityPlayer) { + otherPlayer = (EntityPlayer) otherPlayer.riddenByEntity; + } + if (otherPlayer.riddenByEntity == null && otherPlayer != this) { + mountEntity(otherPlayer); + return true; + } + } + + return false; + } else { + if (itemstack != null && itemstack == this.getCurrentEquippedItem()) { + if (itemstack.stackSize <= 0 && !this.capabilities.isCreativeMode) { + this.destroyCurrentEquippedItem(); + } else if (itemstack.stackSize < itemstack1.stackSize && this.capabilities.isCreativeMode) { + itemstack.stackSize = itemstack1.stackSize; + } + } + + return true; + } + } + } + + public boolean isAllowEdit() { + return this.capabilities.allowEdit; + } + + public boolean isBlocking() { + return this.isUsingItem() && this.itemInUse.getItem().getItemUseAction(this.itemInUse) == EnumAction.BLOCK; + } + + /** + * + Checks if this entity is inside of an opaque block + */ + public boolean isEntityInsideOpaqueBlock() { + return !this.sleeping && super.isEntityInsideOpaqueBlock(); + } + + private boolean isInBed() { + return this.worldObj.getBlockState(this.playerLocation).getBlock() == Blocks.bed; + } + + /** + * + Only used by renderer in EntityLivingBase subclasses.\nDetermines if an + * entity is visible or not to a specfic player, if the entity is normally + * invisible.\nFor EntityLivingBase subclasses, returning false when invisible + * will render the entity semitransparent. + */ + public boolean isInvisibleToPlayer(EntityPlayer entityplayer) { + if (!this.isInvisible()) { + return false; + } else if (entityplayer.isSpectator()) { + return false; + } else { + Team team = this.getTeam(); + return team == null || entityplayer == null || entityplayer.getTeam() != team + || !team.getSeeFriendlyInvisiblesEnabled(); + } + } + + /** + * + Dead and sleeping entities cannot move + */ + protected boolean isMovementBlocked() { + return this.getHealth() <= 0.0F || this.isPlayerSleeping(); + } + + /** + * + Only use is to identify if class is an instance of player for experience + * dropping + */ + protected boolean isPlayer() { + return true; + } + + /** + * + Returns whether or not the player is asleep and the screen has fully faded. + */ + public boolean isPlayerFullyAsleep() { + return this.sleeping && this.sleepTimer >= 100; + } + + /** + * + Returns whether player is sleeping or not + */ + public boolean isPlayerSleeping() { + return this.sleeping; + } + + public boolean isPushedByWater() { + return !this.capabilities.isFlying; + } + + public boolean isSpawnForced() { + return this.spawnForced; + } + + public abstract boolean isSpectator(); + + /** + * + returns true if this is an EntityPlayerSP, or the logged in player. + */ + public boolean isUser() { + return false; + } + + /** + * + Checks if the entity is currently using an item (e.g., bow, food, sword) by + * holding down the useItemButton + */ + public boolean isUsingItem() { + return this.itemInUse != null; + } + + public boolean isWearing(EnumPlayerModelParts parEnumPlayerModelParts) { + return (this.getDataWatcher().getWatchableObjectByte(10) + & parEnumPlayerModelParts.getPartMask()) == parEnumPlayerModelParts.getPartMask(); + } + + /** + * + Joins the passed in entity item with the world. Args: entityItem + */ + protected void joinEntityItemWithWorld(EntityItem entityitem) { + this.worldObj.spawnEntityInWorld(entityitem); + } + + /** + * + Causes this entity to do an upwards motion (jumping). + */ + public void jump() { + super.jump(); + this.triggerAchievement(StatList.jumpStat); + if (this.isSprinting()) { + this.addExhaustion(0.8F); + } else { + this.addExhaustion(0.2F); + } + + } + + /** + * + Moves the entity based on the specified heading. Args: strafe, forward + */ + public void moveEntityWithHeading(float f, float f1) { + double d0 = this.posX; + double d1 = this.posY; + double d2 = this.posZ; + if (this.capabilities.isFlying && this.ridingEntity == null) { + double d3 = this.motionY; + float f2 = this.jumpMovementFactor; + this.jumpMovementFactor = this.capabilities.getFlySpeed() * (float) (this.isSprinting() ? 2 : 1); + super.moveEntityWithHeading(f, f1); + this.motionY = d3 * 0.6D; + this.jumpMovementFactor = f2; + } else { + super.moveEntityWithHeading(f, f1); + } + + this.addMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); + } + + /** + * + Called when the player performs a critical hit on the Entity. Args: entity + * that was hit critically */ public void onCriticalHit(Entity var1) { } + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource damagesource) { + super.onDeath(damagesource); + this.setSize(0.2F, 0.2F); + this.setPosition(this.posX, this.posY, this.posZ); + this.motionY = 0.10000000149011612D; + if (this.getName().equals("Notch")) { + this.dropItem(new ItemStack(Items.apple, 1), true, false); + } + + if (!this.worldObj.getGameRules().getBoolean("keepInventory")) { + this.inventory.dropAllItems(); + } + + if (damagesource != null) { + this.motionX = (double) (-MathHelper.cos((this.attackedAtYaw + this.rotationYaw) * 3.1415927F / 180.0F) + * 0.1F); + this.motionZ = (double) (-MathHelper.sin((this.attackedAtYaw + this.rotationYaw) * 3.1415927F / 180.0F) + * 0.1F); + } else { + this.motionX = this.motionZ = 0.0D; + } + + this.triggerAchievement(StatList.deathsStat); + this.func_175145_a(StatList.timeSinceDeathStat); + } + public void onEnchantmentCritical(Entity var1) { } + /** + * + Used for when item use count runs out, ie: eating completed + */ + protected void onItemUseFinish() { + if (this.itemInUse != null) { + this.updateItemUse(this.itemInUse, 16); + int i = this.itemInUse.stackSize; + ItemStack itemstack = this.itemInUse.onItemUseFinish(this.worldObj, this); + if (itemstack != this.itemInUse || itemstack != null && itemstack.stackSize != i) { + this.inventory.mainInventory[this.inventory.currentItem] = itemstack; + if (itemstack.stackSize == 0) { + this.inventory.mainInventory[this.inventory.currentItem] = null; + } + } + + this.clearItemInUse(); + } + + } + + /** + * + This method gets called when the entity kills another one. + */ + public void onKillEntity(EntityLivingBase entitylivingbase) { + if (entitylivingbase instanceof IMob) { + this.triggerAchievement(AchievementList.killEnemy); + } + + EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs + .get(Integer.valueOf(EntityList.getEntityID(entitylivingbase))); + if (entitylist$entityegginfo != null) { + this.triggerAchievement(entitylist$entityegginfo.field_151512_d); + } + + } + + /** + * + Called frequently so the entity can update its state every tick as + * required. For example, zombies and skeletons use this to react to sunlight + * and start to burn. + */ + public void onLivingUpdate() { + if (this.flyToggleTimer > 0) { + --this.flyToggleTimer; + } + + if (this.worldObj.getDifficulty() == EnumDifficulty.PEACEFUL + && this.worldObj.getGameRules().getBoolean("naturalRegeneration")) { + if (this.getHealth() < this.getMaxHealth() && this.ticksExisted % 20 == 0) { + this.heal(1.0F); + } + + if (this.foodStats.needFood() && this.ticksExisted % 10 == 0) { + this.foodStats.setFoodLevel(this.foodStats.getFoodLevel() + 1); + } + } + + this.inventory.decrementAnimations(); + this.prevCameraYaw = this.cameraYaw; + super.onLivingUpdate(); + IAttributeInstance iattributeinstance = this.getEntityAttribute(SharedMonsterAttributes.movementSpeed); + if (!this.worldObj.isRemote) { + iattributeinstance.setBaseValue((double) this.capabilities.getWalkSpeed()); + } + + this.jumpMovementFactor = this.speedInAir; + if (this.isSprinting()) { + this.jumpMovementFactor = (float) ((double) this.jumpMovementFactor + (double) this.speedInAir * 0.3D); + } + + this.setAIMoveSpeed((float) iattributeinstance.getAttributeValue()); + float f = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); + float f1 = (float) (Math.atan(-this.motionY * 0.20000000298023224D) * 15.0D); + if (f > 0.1F) { + f = 0.1F; + } + + if (!this.onGround || this.getHealth() <= 0.0F) { + f = 0.0F; + } + + if (this.onGround || this.getHealth() <= 0.0F) { + f1 = 0.0F; + } + + this.cameraYaw += (f - this.cameraYaw) * 0.4F; + this.cameraPitch += (f1 - this.cameraPitch) * 0.8F; + if (this.getHealth() > 0.0F && !this.isSpectator()) { + AxisAlignedBB axisalignedbb = null; + if (this.ridingEntity != null && !this.ridingEntity.isDead) { + axisalignedbb = this.getEntityBoundingBox().union(this.ridingEntity.getEntityBoundingBox()).expand(1.0D, + 0.0D, 1.0D); + } else { + axisalignedbb = this.getEntityBoundingBox().expand(1.0D, 0.5D, 1.0D); + } + + List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, axisalignedbb); + + for (int i = 0; i < list.size(); ++i) { + Entity entity = (Entity) list.get(i); + if (!entity.isDead) { + this.collideWithPlayer(entity); + } + } + } + + } + + /** + * + Called to update the entity's position/logic. + */ + public void onUpdate() { + this.noClip = this.isSpectator(); + if (this.isSpectator()) { + this.onGround = false; + } + + if (this.itemInUse != null) { + ItemStack itemstack = this.inventory.getCurrentItem(); + if (itemstack == this.itemInUse) { + if (this.itemInUseCount <= 25 && this.itemInUseCount % 4 == 0) { + this.updateItemUse(itemstack, 5); + } + + if (--this.itemInUseCount == 0 && !this.worldObj.isRemote) { + this.onItemUseFinish(); + } + } else { + this.clearItemInUse(); + } + } + + if (this.xpCooldown > 0) { + --this.xpCooldown; + } + + if (this.isPlayerSleeping()) { + ++this.sleepTimer; + if (this.sleepTimer > 100) { + this.sleepTimer = 100; + } + + if (!this.worldObj.isRemote) { + if (!this.isInBed()) { + this.wakeUpPlayer(true, true, false); + } else if (this.worldObj.isDaytime()) { + this.wakeUpPlayer(false, true, true); + } + } + } else if (this.sleepTimer > 0) { + ++this.sleepTimer; + if (this.sleepTimer >= 110) { + this.sleepTimer = 0; + } + } + + super.onUpdate(); + if (!this.worldObj.isRemote && this.openContainer != null && !this.openContainer.canInteractWith(this)) { + this.closeScreen(); + this.openContainer = this.inventoryContainer; + } + + if (this.isBurning() && this.capabilities.disableDamage) { + this.extinguish(); + } + + this.prevChasingPosX = this.chasingPosX; + this.prevChasingPosY = this.chasingPosY; + this.prevChasingPosZ = this.chasingPosZ; + double d5 = this.posX - this.chasingPosX; + double d0 = this.posY - this.chasingPosY; + double d1 = this.posZ - this.chasingPosZ; + double d2 = 10.0D; + if (d5 > d2) { + this.prevChasingPosX = this.chasingPosX = this.posX; + } + + if (d1 > d2) { + this.prevChasingPosZ = this.chasingPosZ = this.posZ; + } + + if (d0 > d2) { + this.prevChasingPosY = this.chasingPosY = this.posY; + } + + if (d5 < -d2) { + this.prevChasingPosX = this.chasingPosX = this.posX; + } + + if (d1 < -d2) { + this.prevChasingPosZ = this.chasingPosZ = this.posZ; + } + + if (d0 < -d2) { + this.prevChasingPosY = this.chasingPosY = this.posY; + } + + this.chasingPosX += d5 * 0.25D; + this.chasingPosZ += d1 * 0.25D; + this.chasingPosY += d0 * 0.25D; + if (this.ridingEntity == null) { + this.startMinecartRidingCoordinate = null; + } + + if (!this.worldObj.isRemote) { + this.foodStats.onUpdate(this); + this.triggerAchievement(StatList.minutesPlayedStat); + if (this.isEntityAlive()) { + this.triggerAchievement(StatList.timeSinceDeathStat); + } + } + + int i = 29999999; + double d3 = MathHelper.clamp_double(this.posX, -2.9999999E7D, 2.9999999E7D); + double d4 = MathHelper.clamp_double(this.posZ, -2.9999999E7D, 2.9999999E7D); + if (d3 != this.posX || d4 != this.posZ) { + this.setPosition(d3, this.posY, d4); + } + + } + + public void openEditCommandBlock(CommandBlockLogic var1) { + } + + public void openEditSign(TileEntitySign var1) { + } + + public void playSound(String s, float f, float f1) { + this.worldObj.playSoundToNearExcept(this, s, f, f1); + } + + /** + * + Keeps moving the entity up so it isn't colliding with blocks and other + * requirements for this entity to be spawned (only actually used on players + * though its also on Entity) + */ + public void preparePlayerToSpawn() { + this.setSize(0.6F, 1.8F); + super.preparePlayerToSpawn(); + this.setHealth(this.getMaxHealth()); + this.deathTime = 0; + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + this.entityUniqueID = getUUID(this.gameProfile); + NBTTagList nbttaglist = nbttagcompound.getTagList("Inventory", 10); + this.inventory.readFromNBT(nbttaglist); + this.inventory.currentItem = nbttagcompound.getInteger("SelectedItemSlot"); + this.sleeping = nbttagcompound.getBoolean("Sleeping"); + this.sleepTimer = nbttagcompound.getShort("SleepTimer"); + this.experience = nbttagcompound.getFloat("XpP"); + this.experienceLevel = nbttagcompound.getInteger("XpLevel"); + this.experienceTotal = nbttagcompound.getInteger("XpTotal"); + this.xpSeed = nbttagcompound.getInteger("XpSeed"); + if (this.xpSeed == 0) { + this.xpSeed = this.rand.nextInt(); + } + + this.setScore(nbttagcompound.getInteger("Score")); + if (this.sleeping) { + this.playerLocation = new BlockPos(this); + this.wakeUpPlayer(true, true, false); + } + + if (nbttagcompound.hasKey("SpawnX", 99) && nbttagcompound.hasKey("SpawnY", 99) + && nbttagcompound.hasKey("SpawnZ", 99)) { + this.spawnChunk = new BlockPos(nbttagcompound.getInteger("SpawnX"), nbttagcompound.getInteger("SpawnY"), + nbttagcompound.getInteger("SpawnZ")); + this.spawnForced = nbttagcompound.getBoolean("SpawnForced"); + } + + this.foodStats.readNBT(nbttagcompound); + this.capabilities.readCapabilitiesFromNBT(nbttagcompound); + if (nbttagcompound.hasKey("EnderItems", 9)) { + NBTTagList nbttaglist1 = nbttagcompound.getTagList("EnderItems", 10); + this.theInventoryEnderChest.loadInventoryFromNBT(nbttaglist1); + } + + } + + public void removeExperienceLevel(int i) { + this.experienceLevel -= i; + if (this.experienceLevel < 0) { + this.experienceLevel = 0; + this.experience = 0.0F; + this.experienceTotal = 0; + } + + this.xpSeed = this.rand.nextInt(); + } + + public boolean replaceItemInInventory(int i, ItemStack itemstack) { + if (i >= 0 && i < this.inventory.mainInventory.length) { + this.inventory.setInventorySlotContents(i, itemstack); + return true; + } else { + int j = i - 100; + if (j >= 0 && j < this.inventory.armorInventory.length) { + int l = j + 1; + if (itemstack != null && itemstack.getItem() != null) { + if (itemstack.getItem() instanceof ItemArmor) { + if (EntityLiving.getArmorPosition(itemstack) != l) { + return false; + } + } else if (l != 4 + || itemstack.getItem() != Items.skull && !(itemstack.getItem() instanceof ItemBlock)) { + return false; + } + } + + this.inventory.setInventorySlotContents(j + this.inventory.mainInventory.length, itemstack); + return true; + } else { + int k = i - 200; + if (k >= 0 && k < this.theInventoryEnderChest.getSizeInventory()) { + this.theInventoryEnderChest.setInventorySlotContents(k, itemstack); + return true; + } else { + return false; + } + } + } + } + + /** + * + sets the players height back to normal after doing things like sleeping and + * dieing + */ + protected void resetHeight() { + if (!this.isSpectator()) { + super.resetHeight(); + } + + } + public void respawnPlayer() { } - /**+ - * Will get destroyed next tick. + /** + * + Returns true if the command sender should be sent feedback about executed + * commands + */ + public boolean sendCommandFeedback() { + return MinecraftServer.getServer().worldServers[0].getGameRules().getBoolean("sendCommandFeedback"); + } + + /** + * + Sends the player's abilities to the server (if there is one). + */ + public void sendPlayerAbilities() { + } + + public void setAbsorptionAmount(float f) { + if (f < 0.0F) { + f = 0.0F; + } + + this.getDataWatcher().updateObject(17, Float.valueOf(f)); + } + + /** + * + Sets the held item, or an armor slot. Slot 0 is held item. Slot 1-4 is + * armor. Params: Item, slot + */ + public void setCurrentItemOrArmor(int i, ItemStack itemstack) { + this.inventory.armorInventory[i] = itemstack; + } + + /** + * + Will get destroyed next tick. */ public void setDead() { super.setDead(); @@ -1234,26 +1804,79 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS } - /**+ - * Checks if this entity is inside of an opaque block + /** + * + Sets the player's game mode and sends it to them. */ - public boolean isEntityInsideOpaqueBlock() { - return !this.sleeping && super.isEntityInsideOpaqueBlock(); + public void setGameType(WorldSettings.GameType var1) { } - /**+ - * returns true if this is an EntityPlayerSP, or the logged in - * player. + /** + * + Sets the Entity inside a web block. */ - public boolean isUser() { - return false; + public void setInWeb() { + if (!this.capabilities.isFlying) { + super.setInWeb(); + } + } - /**+ - * Returns the GameProfile for this player + /** + * + sets the itemInUse when the use item button is clicked. Args: itemstack, + * int maxItemUseDuration */ - public GameProfile getGameProfile() { - return this.gameProfile; + public void setItemInUse(ItemStack itemstack, int i) { + if (itemstack != this.itemInUse) { + this.itemInUse = itemstack; + this.itemInUseCount = i; + if (!this.worldObj.isRemote) { + this.setEating(true); + } + + } + } + + public void setReducedDebug(boolean reducedDebug) { + this.hasReducedDebug = reducedDebug; + } + + /** + * + Set player's score + */ + public void setScore(int parInt1) { + this.dataWatcher.updateObject(18, Integer.valueOf(parInt1)); + } + + public void setSpawnPoint(BlockPos pos, boolean forced) { + if (pos != null) { + this.spawnChunk = pos; + this.spawnForced = forced; + } else { + this.spawnChunk = null; + this.spawnForced = false; + } + + } + + /** + * + Checks if the player's health is not full and not zero. + */ + public boolean shouldHeal() { + return this.getHealth() > 0.0F && this.getHealth() < this.getMaxHealth(); + } + + public void stopUsingItem() { + if (this.itemInUse != null) { + this.itemInUse.onPlayerStoppedUsing(this.worldObj, this, this.itemInUseCount); + } + + this.clearItemInUse(); + } + + /** + * + Will trigger the specified trigger. + */ + public void triggerAchievement(StatBase achievementIn) { + this.addStat(achievementIn, 1); } public EntityPlayer.EnumStatus trySleep(BlockPos blockpos) { @@ -1330,27 +1953,75 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS return EntityPlayer.EnumStatus.OK; } - private void func_175139_a(EnumFacing parEnumFacing) { - this.renderOffsetX = 0.0F; - this.renderOffsetZ = 0.0F; - switch (parEnumFacing) { - case SOUTH: - this.renderOffsetZ = -1.8F; - break; - case NORTH: - this.renderOffsetZ = 1.8F; - break; - case WEST: - this.renderOffsetX = 1.8F; - break; - case EAST: - this.renderOffsetX = -1.8F; + protected void updateEntityActionState() { + super.updateEntityActionState(); + this.updateArmSwingProgress(); + this.rotationYawHead = this.rotationYaw; + } + + /** + * + Plays sounds and makes particles for item in use state + */ + protected void updateItemUse(ItemStack itemStackIn, int parInt1) { + if (itemStackIn.getItemUseAction() == EnumAction.DRINK) { + this.playSound("random.drink", 0.5F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F); + } + + if (itemStackIn.getItemUseAction() == EnumAction.EAT) { + for (int i = 0; i < parInt1; ++i) { + Vec3 vec3 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.1D, Math.random() * 0.1D + 0.1D, 0.0D); + vec3 = vec3.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); + vec3 = vec3.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); + double d0 = (double) (-this.rand.nextFloat()) * 0.6D - 0.3D; + Vec3 vec31 = new Vec3(((double) this.rand.nextFloat() - 0.5D) * 0.3D, d0, 0.6D); + vec31 = vec31.rotatePitch(-this.rotationPitch * 3.1415927F / 180.0F); + vec31 = vec31.rotateYaw(-this.rotationYaw * 3.1415927F / 180.0F); + vec31 = vec31.addVector(this.posX, this.posY + (double) this.getEyeHeight(), this.posZ); + if (itemStackIn.getHasSubtypes()) { + this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, + vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, + new int[] { Item.getIdFromItem(itemStackIn.getItem()), itemStackIn.getMetadata() }); + } else { + this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, vec31.xCoord, vec31.yCoord, vec31.zCoord, + vec3.xCoord, vec3.yCoord + 0.05D, vec3.zCoord, + new int[] { Item.getIdFromItem(itemStackIn.getItem()) }); + } + } + + this.playSound("random.eat", 0.5F + 0.5F * (float) this.rand.nextInt(2), + (this.rand.nextFloat() - this.rand.nextFloat()) * 0.2F + 1.0F); } } - /**+ - * Wake up the player if they're sleeping. + /** + * + Handles updating while being ridden by an entity + */ + public void updateRidden() { + if (!this.worldObj.isRemote && this.isSneaking()) { + this.mountEntity((Entity) null); + this.setSneaking(false); + } else { + double d0 = this.posX; + double d1 = this.posY; + double d2 = this.posZ; + float f = this.rotationYaw; + float f1 = this.rotationPitch; + super.updateRidden(); + this.prevCameraYaw = this.cameraYaw; + this.cameraYaw = 0.0F; + this.addMountedMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); + if (this.ridingEntity instanceof EntityPig) { + this.rotationPitch = f1; + this.rotationYaw = f; + this.renderYawOffset = ((EntityPig) this.ridingEntity).renderYawOffset; + } + + } + } + + /** + * + Wake up the player if they're sleeping. */ public void wakeUpPlayer(boolean flag, boolean flag1, boolean flag2) { this.setSize(0.6F, 1.8F); @@ -1379,722 +2050,44 @@ public abstract class EntityPlayer extends EntityLivingBase implements ICommandS } - private boolean isInBed() { - return this.worldObj.getBlockState(this.playerLocation).getBlock() == Blocks.bed; - } - - /**+ - * Return null if bed is invalid + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public static BlockPos getBedSpawnLocation(World worldIn, BlockPos bedLocation, boolean forceSpawn) { - Block block = worldIn.getBlockState(bedLocation).getBlock(); - if (block != Blocks.bed) { - if (!forceSpawn) { - return null; - } else { - boolean flag = block.func_181623_g(); - boolean flag1 = worldIn.getBlockState(bedLocation.up()).getBlock().func_181623_g(); - return flag && flag1 ? bedLocation : null; - } - } else { - return BlockBed.getSafeExitLocation(worldIn, bedLocation, 0); - } - } - - /**+ - * Returns the orientation of the bed in degrees. - */ - public float getBedOrientationInDegrees() { - if (this.playerLocation != null) { - EnumFacing enumfacing = (EnumFacing) this.worldObj.getBlockState(this.playerLocation) - .getValue(BlockDirectional.FACING); - switch (enumfacing) { - case SOUTH: - return 90.0F; - case NORTH: - return 270.0F; - case WEST: - return 0.0F; - case EAST: - return 180.0F; - } + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setTag("Inventory", this.inventory.writeToNBT(new NBTTagList())); + nbttagcompound.setInteger("SelectedItemSlot", this.inventory.currentItem); + nbttagcompound.setBoolean("Sleeping", this.sleeping); + nbttagcompound.setShort("SleepTimer", (short) this.sleepTimer); + nbttagcompound.setFloat("XpP", this.experience); + nbttagcompound.setInteger("XpLevel", this.experienceLevel); + nbttagcompound.setInteger("XpTotal", this.experienceTotal); + nbttagcompound.setInteger("XpSeed", this.xpSeed); + nbttagcompound.setInteger("Score", this.getScore()); + if (this.spawnChunk != null) { + nbttagcompound.setInteger("SpawnX", this.spawnChunk.getX()); + nbttagcompound.setInteger("SpawnY", this.spawnChunk.getY()); + nbttagcompound.setInteger("SpawnZ", this.spawnChunk.getZ()); + nbttagcompound.setBoolean("SpawnForced", this.spawnForced); } - return 0.0F; - } - - /**+ - * Returns whether player is sleeping or not - */ - public boolean isPlayerSleeping() { - return this.sleeping; - } - - /**+ - * Returns whether or not the player is asleep and the screen - * has fully faded. - */ - public boolean isPlayerFullyAsleep() { - return this.sleeping && this.sleepTimer >= 100; - } - - public int getSleepTimer() { - return this.sleepTimer; - } - - public void addChatComponentMessage(IChatComponent var1) { - } - - public BlockPos getBedLocation() { - return this.spawnChunk; - } - - public boolean isSpawnForced() { - return this.spawnForced; - } - - public void setSpawnPoint(BlockPos pos, boolean forced) { - if (pos != null) { - this.spawnChunk = pos; - this.spawnForced = forced; - } else { - this.spawnChunk = null; - this.spawnForced = false; + this.foodStats.writeNBT(nbttagcompound); + this.capabilities.writeCapabilitiesToNBT(nbttagcompound); + nbttagcompound.setTag("EnderItems", this.theInventoryEnderChest.saveInventoryToNBT()); + ItemStack itemstack = this.inventory.getCurrentItem(); + if (itemstack != null && itemstack.getItem() != null) { + nbttagcompound.setTag("SelectedItem", itemstack.writeToNBT(new NBTTagCompound())); } } - /**+ - * Will trigger the specified trigger. - */ - public void triggerAchievement(StatBase achievementIn) { - this.addStat(achievementIn, 1); - } - - /**+ - * Adds a value to a statistic field. - */ - public void addStat(StatBase var1, int var2) { - } - - public void func_175145_a(StatBase var1) { - } - - /**+ - * Causes this entity to do an upwards motion (jumping). - */ - public void jump() { - super.jump(); - this.triggerAchievement(StatList.jumpStat); - if (this.isSprinting()) { - this.addExhaustion(0.8F); - } else { - this.addExhaustion(0.2F); - } - - } - - /**+ - * Moves the entity based on the specified heading. Args: - * strafe, forward - */ - public void moveEntityWithHeading(float f, float f1) { - double d0 = this.posX; - double d1 = this.posY; - double d2 = this.posZ; - if (this.capabilities.isFlying && this.ridingEntity == null) { - double d3 = this.motionY; - float f2 = this.jumpMovementFactor; - this.jumpMovementFactor = this.capabilities.getFlySpeed() * (float) (this.isSprinting() ? 2 : 1); - super.moveEntityWithHeading(f, f1); - this.motionY = d3 * 0.6D; - this.jumpMovementFactor = f2; - } else { - super.moveEntityWithHeading(f, f1); - } - - this.addMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); - } - - /**+ - * the movespeed used for the new AI system - */ - public float getAIMoveSpeed() { - return (float) this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).getAttributeValue(); - } - - /**+ - * Adds a value to a movement statistic field - like run, walk, - * swin or climb. - */ - public void addMovementStat(double parDouble1, double parDouble2, double parDouble3) { - if (this.ridingEntity == null) { - if (this.isInsideOfMaterial(Material.water)) { - int i = Math.round(MathHelper.sqrt_double( - parDouble1 * parDouble1 + parDouble2 * parDouble2 + parDouble3 * parDouble3) * 100.0F); - if (i > 0) { - this.addStat(StatList.distanceDoveStat, i); - this.addExhaustion(0.015F * (float) i * 0.01F); - } - } else if (this.isInWater()) { - int j = Math.round(MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble3 * parDouble3) * 100.0F); - if (j > 0) { - this.addStat(StatList.distanceSwumStat, j); - this.addExhaustion(0.015F * (float) j * 0.01F); - } - } else if (this.isOnLadder()) { - if (parDouble2 > 0.0D) { - this.addStat(StatList.distanceClimbedStat, (int) Math.round(parDouble2 * 100.0D)); - } - } else if (this.onGround) { - int k = Math.round(MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble3 * parDouble3) * 100.0F); - if (k > 0) { - this.addStat(StatList.distanceWalkedStat, k); - if (this.isSprinting()) { - this.addStat(StatList.distanceSprintedStat, k); - this.addExhaustion(0.099999994F * (float) k * 0.01F); - } else { - if (this.isSneaking()) { - this.addStat(StatList.distanceCrouchedStat, k); - } - - this.addExhaustion(0.01F * (float) k * 0.01F); - } - } - } else { - int l = Math.round(MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble3 * parDouble3) * 100.0F); - if (l > 25) { - this.addStat(StatList.distanceFlownStat, l); - } - } - - } - } - - /**+ - * Adds a value to a mounted movement statistic field - by - * minecart, boat, or pig. - */ - private void addMountedMovementStat(double parDouble1, double parDouble2, double parDouble3) { - if (this.ridingEntity != null) { - int i = Math.round( - MathHelper.sqrt_double(parDouble1 * parDouble1 + parDouble2 * parDouble2 + parDouble3 * parDouble3) - * 100.0F); - if (i > 0) { - if (this.ridingEntity instanceof EntityMinecart) { - this.addStat(StatList.distanceByMinecartStat, i); - if (this.startMinecartRidingCoordinate == null) { - this.startMinecartRidingCoordinate = new BlockPos(this); - } else if (this.startMinecartRidingCoordinate.distanceSq( - (double) MathHelper.floor_double(this.posX), (double) MathHelper.floor_double(this.posY), - (double) MathHelper.floor_double(this.posZ)) >= 1000000.0D) { - this.triggerAchievement(AchievementList.onARail); - } - } else if (this.ridingEntity instanceof EntityBoat) { - this.addStat(StatList.distanceByBoatStat, i); - } else if (this.ridingEntity instanceof EntityPig) { - this.addStat(StatList.distanceByPigStat, i); - } else if (this.ridingEntity instanceof EntityHorse) { - this.addStat(StatList.distanceByHorseStat, i); - } - } - } - - } - - public void fall(float f, float f1) { - if (!this.capabilities.allowFlying) { - if (f >= 2.0F) { - this.addStat(StatList.distanceFallenStat, (int) Math.round((double) f * 100.0D)); - } - - super.fall(f, f1); - } - } - - /**+ - * sets the players height back to normal after doing things - * like sleeping and dieing - */ - protected void resetHeight() { - if (!this.isSpectator()) { - super.resetHeight(); - } - - } - - protected String getFallSoundString(int i) { - return i > 4 ? "game.player.hurt.fall.big" : "game.player.hurt.fall.small"; - } - - /**+ - * This method gets called when the entity kills another one. - */ - public void onKillEntity(EntityLivingBase entitylivingbase) { - if (entitylivingbase instanceof IMob) { - this.triggerAchievement(AchievementList.killEnemy); - } - - EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs - .get(Integer.valueOf(EntityList.getEntityID(entitylivingbase))); - if (entitylist$entityegginfo != null) { - this.triggerAchievement(entitylist$entityegginfo.field_151512_d); - } - - } - - /**+ - * Sets the Entity inside a web block. - */ - public void setInWeb() { - if (!this.capabilities.isFlying) { - super.setInWeb(); - } - - } - - public ItemStack getCurrentArmor(int i) { - return this.inventory.armorItemInSlot(i); - } - - /**+ - * Add experience points to player. - */ - public void addExperience(int amount) { - this.addScore(amount); - int i = Integer.MAX_VALUE - this.experienceTotal; - if (amount > i) { - amount = i; - } - - this.experience += (float) amount / (float) this.xpBarCap(); - - for (this.experienceTotal += amount; this.experience >= 1.0F; this.experience /= (float) this.xpBarCap()) { - this.experience = (this.experience - 1.0F) * (float) this.xpBarCap(); - this.addExperienceLevel(1); - } - - } - - public int getXPSeed() { - return this.xpSeed; - } - - public void removeExperienceLevel(int i) { - this.experienceLevel -= i; - if (this.experienceLevel < 0) { - this.experienceLevel = 0; - this.experience = 0.0F; - this.experienceTotal = 0; - } - - this.xpSeed = this.rand.nextInt(); - } - - /**+ - * Add experience levels to this player. - */ - public void addExperienceLevel(int i) { - this.experienceLevel += i; - if (this.experienceLevel < 0) { - this.experienceLevel = 0; - this.experience = 0.0F; - this.experienceTotal = 0; - } - - if (i > 0 && this.experienceLevel % 5 == 0 && (float) this.lastXPSound < (float) this.ticksExisted - 100.0F) { - float f = this.experienceLevel > 30 ? 1.0F : (float) this.experienceLevel / 30.0F; - this.worldObj.playSoundAtEntity(this, "random.levelup", f * 0.75F, 1.0F); - this.lastXPSound = this.ticksExisted; - } - - } - - /**+ - * This method returns the cap amount of experience that the - * experience bar can hold. With each level, the experience cap - * on the player's experience bar is raised by 10. + /** + * + This method returns the cap amount of experience that the experience bar + * can hold. With each level, the experience cap on the player's experience bar + * is raised by 10. */ public int xpBarCap() { return this.experienceLevel >= 30 ? 112 + (this.experienceLevel - 30) * 9 : (this.experienceLevel >= 15 ? 37 + (this.experienceLevel - 15) * 5 : 7 + this.experienceLevel * 2); } - - /**+ - * increases exhaustion level by supplied amount - */ - public void addExhaustion(float parFloat1) { - if (!this.capabilities.disableDamage) { - if (!this.worldObj.isRemote) { - this.foodStats.addExhaustion(parFloat1); - } - - } - } - - /**+ - * Returns the player's FoodStats object. - */ - public FoodStats getFoodStats() { - return this.foodStats; - } - - public boolean canEat(boolean ignoreHunger) { - return (ignoreHunger || this.foodStats.needFood()) && !this.capabilities.disableDamage; - } - - /**+ - * Checks if the player's health is not full and not zero. - */ - public boolean shouldHeal() { - return this.getHealth() > 0.0F && this.getHealth() < this.getMaxHealth(); - } - - /**+ - * sets the itemInUse when the use item button is clicked. Args: - * itemstack, int maxItemUseDuration - */ - public void setItemInUse(ItemStack itemstack, int i) { - if (itemstack != this.itemInUse) { - this.itemInUse = itemstack; - this.itemInUseCount = i; - if (!this.worldObj.isRemote) { - this.setEating(true); - } - - } - } - - public boolean isAllowEdit() { - return this.capabilities.allowEdit; - } - - public boolean canPlayerEdit(BlockPos parBlockPos, EnumFacing parEnumFacing, ItemStack parItemStack) { - if (this.capabilities.allowEdit) { - return true; - } else if (parItemStack == null) { - return false; - } else { - BlockPos blockpos = parBlockPos.offset(parEnumFacing.getOpposite()); - Block block = this.worldObj.getBlockState(blockpos).getBlock(); - return parItemStack.canPlaceOn(block) || parItemStack.canEditBlocks(); - } - } - - /**+ - * Get the experience points the entity currently has. - */ - protected int getExperiencePoints(EntityPlayer var1) { - if (this.worldObj.getGameRules().getBoolean("keepInventory")) { - return 0; - } else { - int i = this.experienceLevel * 7; - return i > 100 ? 100 : i; - } - } - - /**+ - * Only use is to identify if class is an instance of player for - * experience dropping - */ - protected boolean isPlayer() { - return true; - } - - public boolean getAlwaysRenderNameTagForRender() { - return true; - } - - /**+ - * Copies the values from the given player into this player if - * boolean par2 is true. Always clones Ender Chest Inventory. - */ - public void clonePlayer(EntityPlayer entityplayer, boolean flag) { - if (flag) { - this.inventory.copyInventory(entityplayer.inventory); - this.setHealth(entityplayer.getHealth()); - this.foodStats = entityplayer.foodStats; - this.experienceLevel = entityplayer.experienceLevel; - this.experienceTotal = entityplayer.experienceTotal; - this.experience = entityplayer.experience; - this.setScore(entityplayer.getScore()); - this.field_181016_an = entityplayer.field_181016_an; - this.field_181017_ao = entityplayer.field_181017_ao; - this.field_181018_ap = entityplayer.field_181018_ap; - } else if (this.worldObj.getGameRules().getBoolean("keepInventory")) { - this.inventory.copyInventory(entityplayer.inventory); - this.experienceLevel = entityplayer.experienceLevel; - this.experienceTotal = entityplayer.experienceTotal; - this.experience = entityplayer.experience; - this.setScore(entityplayer.getScore()); - } - - this.xpSeed = entityplayer.xpSeed; - this.theInventoryEnderChest = entityplayer.theInventoryEnderChest; - this.getDataWatcher().updateObject(10, Byte.valueOf(entityplayer.getDataWatcher().getWatchableObjectByte(10))); - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return !this.capabilities.isFlying; - } - - /**+ - * Sends the player's abilities to the server (if there is one). - */ - public void sendPlayerAbilities() { - } - - /**+ - * Sets the player's game mode and sends it to them. - */ - public void setGameType(WorldSettings.GameType var1) { - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.gameProfile.getName(); - } - - /**+ - * Returns the InventoryEnderChest of this player. - */ - public InventoryEnderChest getInventoryEnderChest() { - return this.theInventoryEnderChest; - } - - /**+ - * 0: Tool in Hand; 1-4: Armor - */ - public ItemStack getEquipmentInSlot(int i) { - return i == 0 ? this.inventory.getCurrentItem() : this.inventory.armorInventory[i - 1]; - } - - /**+ - * Returns the item that this EntityLiving is holding, if any. - */ - public ItemStack getHeldItem() { - return this.inventory.getCurrentItem(); - } - - /**+ - * Sets the held item, or an armor slot. Slot 0 is held item. - * Slot 1-4 is armor. Params: Item, slot - */ - public void setCurrentItemOrArmor(int i, ItemStack itemstack) { - this.inventory.armorInventory[i] = itemstack; - } - - /**+ - * Only used by renderer in EntityLivingBase - * subclasses.\nDetermines if an entity is visible or not to a - * specfic player, if the entity is normally invisible.\nFor - * EntityLivingBase subclasses, returning false when invisible - * will render the entity semitransparent. - */ - public boolean isInvisibleToPlayer(EntityPlayer entityplayer) { - if (!this.isInvisible()) { - return false; - } else if (entityplayer.isSpectator()) { - return false; - } else { - Team team = this.getTeam(); - return team == null || entityplayer == null || entityplayer.getTeam() != team - || !team.getSeeFriendlyInvisiblesEnabled(); - } - } - - public abstract boolean isSpectator(); - - /**+ - * returns the inventory of this entity (only used in - * EntityPlayerMP it seems) - */ - public ItemStack[] getInventory() { - return this.inventory.armorInventory; - } - - public boolean isPushedByWater() { - return !this.capabilities.isFlying; - } - - public Scoreboard getWorldScoreboard() { - return this.worldObj.getScoreboard(); - } - - public Team getTeam() { - return this.getWorldScoreboard().getPlayersTeam(this.getName()); - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - ChatComponentText chatcomponenttext = new ChatComponentText( - ScorePlayerTeam.formatPlayerName(this.getTeam(), this.getName())); - chatcomponenttext.getChatStyle() - .setChatClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, "/msg " + this.getName() + " ")); - chatcomponenttext.getChatStyle().setChatHoverEvent(this.getHoverEvent()); - chatcomponenttext.getChatStyle().setInsertion(this.getName()); - return chatcomponenttext; - } - - public float getEyeHeight() { - float f = 1.62F; - if (this.isPlayerSleeping()) { - f = 0.2F; - } - - if (this.isSneaking()) { - f -= 0.08F; - } - - return f; - } - - public void setAbsorptionAmount(float f) { - if (f < 0.0F) { - f = 0.0F; - } - - this.getDataWatcher().updateObject(17, Float.valueOf(f)); - } - - public float getAbsorptionAmount() { - return this.getDataWatcher().getWatchableObjectFloat(17); - } - - /**+ - * Gets a players UUID given their GameProfie - */ - public static EaglercraftUUID getUUID(GameProfile profile) { - EaglercraftUUID uuid = profile.getId(); - if (uuid == null) { - uuid = getOfflineUUID(profile.getName()); - } - - return uuid; - } - - public static EaglercraftUUID getOfflineUUID(String username) { - return EaglercraftUUID.nameUUIDFromBytes(("OfflinePlayer:" + username).getBytes(Charsets.UTF_8)); - } - - /**+ - * Check whether this player can open an inventory locked with - * the given LockCode. - */ - public boolean canOpen(LockCode code) { - if (code.isEmpty()) { - return true; - } else { - ItemStack itemstack = this.getCurrentEquippedItem(); - return itemstack != null && itemstack.hasDisplayName() ? itemstack.getDisplayName().equals(code.getLock()) - : false; - } - } - - public boolean isWearing(EnumPlayerModelParts parEnumPlayerModelParts) { - return (this.getDataWatcher().getWatchableObjectByte(10) - & parEnumPlayerModelParts.getPartMask()) == parEnumPlayerModelParts.getPartMask(); - } - - /**+ - * Returns true if the command sender should be sent feedback - * about executed commands - */ - public boolean sendCommandFeedback() { - return MinecraftServer.getServer().worldServers[0].getGameRules().getBoolean("sendCommandFeedback"); - } - - public boolean replaceItemInInventory(int i, ItemStack itemstack) { - if (i >= 0 && i < this.inventory.mainInventory.length) { - this.inventory.setInventorySlotContents(i, itemstack); - return true; - } else { - int j = i - 100; - if (j >= 0 && j < this.inventory.armorInventory.length) { - int l = j + 1; - if (itemstack != null && itemstack.getItem() != null) { - if (itemstack.getItem() instanceof ItemArmor) { - if (EntityLiving.getArmorPosition(itemstack) != l) { - return false; - } - } else if (l != 4 - || itemstack.getItem() != Items.skull && !(itemstack.getItem() instanceof ItemBlock)) { - return false; - } - } - - this.inventory.setInventorySlotContents(j + this.inventory.mainInventory.length, itemstack); - return true; - } else { - int k = i - 200; - if (k >= 0 && k < this.theInventoryEnderChest.getSizeInventory()) { - this.theInventoryEnderChest.setInventorySlotContents(k, itemstack); - return true; - } else { - return false; - } - } - } - } - - /**+ - * Whether the "reducedDebugInfo" option is active for this - * player. - */ - public boolean hasReducedDebug() { - return this.hasReducedDebug; - } - - public void setReducedDebug(boolean reducedDebug) { - this.hasReducedDebug = reducedDebug; - } - - public static enum EnumChatVisibility { - FULL(0, "options.chat.visibility.full"), SYSTEM(1, "options.chat.visibility.system"), - HIDDEN(2, "options.chat.visibility.hidden"); - - private static final EntityPlayer.EnumChatVisibility[] ID_LOOKUP = new EntityPlayer.EnumChatVisibility[3]; - private final int chatVisibility; - private final String resourceKey; - - private EnumChatVisibility(int id, String resourceKey) { - this.chatVisibility = id; - this.resourceKey = resourceKey; - } - - public int getChatVisibility() { - return this.chatVisibility; - } - - public static EntityPlayer.EnumChatVisibility getEnumChatVisibility(int id) { - return ID_LOOKUP[id % ID_LOOKUP.length]; - } - - public String getResourceKey() { - return this.resourceKey; - } - - static { - EntityPlayer.EnumChatVisibility[] lst = values(); - for (int i = 0; i < lst.length; ++i) { - ID_LOOKUP[lst[i].chatVisibility] = lst[i]; - } - - } - } - - public static enum EnumStatus { - OK, NOT_POSSIBLE_HERE, NOT_POSSIBLE_NOW, TOO_FAR_AWAY, OTHER_PROBLEM, NOT_SAFE; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/player/EntityPlayerMP.java b/src/game/java/net/minecraft/entity/player/EntityPlayerMP.java index 4a87e9df..a624ae92 100644 --- a/src/game/java/net/minecraft/entity/player/EntityPlayerMP.java +++ b/src/game/java/net/minecraft/entity/player/EntityPlayerMP.java @@ -1,14 +1,20 @@ package net.minecraft.entity.player; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.minecraft.block.Block; import net.minecraft.block.BlockFence; import net.minecraft.block.BlockFenceGate; @@ -94,27 +100,26 @@ import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; -import net.lax1dude.eaglercraft.v1_8.EagRuntime; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -128,42 +133,42 @@ public class EntityPlayerMP extends EntityPlayer implements ICrafting { public final ItemInWorldManager theItemInWorldManager; public double managedPosX; public double managedPosZ; - /**+ - * LinkedList that holds the loaded chunks. + /** + * + LinkedList that holds the loaded chunks. */ public final List loadedChunks = Lists.newLinkedList(); - /**+ - * entities added to this list will be packet29'd to the player + /** + * + entities added to this list will be packet29'd to the player */ private final List destroyedItemsNetCache = Lists.newLinkedList(); private final StatisticsFile statsFile; - /**+ - * the total health of the player, includes actual health and - * absorption health. Updated every tick. + /** + * + the total health of the player, includes actual health and absorption + * health. Updated every tick. */ private float combinedHealth = Float.MIN_VALUE; - /**+ - * amount of health the client was last set to + /** + * + amount of health the client was last set to */ private float lastHealth = -1.0E8F; - /**+ - * set to foodStats.GetFoodLevel + /** + * + set to foodStats.GetFoodLevel */ private int lastFoodLevel = -99999999; - /**+ - * set to foodStats.getSaturationLevel() == 0.0F each tick + /** + * + set to foodStats.getSaturationLevel() == 0.0F each tick */ private boolean wasHungry = true; - /**+ - * Amount of experience the client was last set to + /** + * + Amount of experience the client was last set to */ private int lastExperience = -99999999; private int respawnInvulnerabilityTicks = 60; private EntityPlayer.EnumChatVisibility chatVisibility; private boolean chatColours = true; private long playerLastActiveTime = EagRuntime.steadyTimeMillis(); - /**+ - * The entity the player is currently spectating through. + /** + * + The entity the player is currently spectating through. */ private Entity spectatingEntity = null; private int currentWindowId; @@ -207,69 +212,479 @@ public class EntityPlayerMP extends EntityPlayer implements ICrafting { } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound nbttagcompound) { - super.readEntityFromNBT(nbttagcompound); - if (nbttagcompound.hasKey("playerGameType", 99)) { - if (MinecraftServer.getServer().getForceGamemode()) { - this.theItemInWorldManager.setGameType(MinecraftServer.getServer().getGameType()); - } else { - this.theItemInWorldManager - .setGameType(WorldSettings.GameType.getByID(nbttagcompound.getInteger("playerGameType"))); - } - } - + public void addChatComponentMessage(IChatComponent ichatcomponent) { + this.playerNetServerHandler.sendPacket(new S02PacketChat(ichatcomponent)); } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Send a chat message to the CommandSender */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("playerGameType", this.theItemInWorldManager.getGameType().getID()); + public void addChatMessage(IChatComponent ichatcomponent) { + this.playerNetServerHandler.sendPacket(new S02PacketChat(ichatcomponent)); } - /**+ - * Add experience levels to this player. + /** + * + Add experience levels to this player. */ public void addExperienceLevel(int levels) { super.addExperienceLevel(levels); this.lastExperience = -1; } - public void removeExperienceLevel(int levels) { - super.removeExperienceLevel(levels); - this.lastExperience = -1; - } - public void addSelfToInternalCraftingInventory() { this.openContainer.onCraftGuiOpened(this); } - /**+ - * Sends an ENTER_COMBAT packet to the client + /** + * + Adds a value to a statistic field. */ - public void sendEnterCombat() { - super.sendEnterCombat(); - this.playerNetServerHandler - .sendPacket(new S42PacketCombatEvent(this.getCombatTracker(), S42PacketCombatEvent.Event.ENTER_COMBAT)); + public void addStat(StatBase statbase, int i) { + if (statbase != null) { + this.statsFile.increaseStat(this, statbase, i); + + for (ScoreObjective scoreobjective : this.getWorldScoreboard() + .getObjectivesFromCriteria(statbase.func_150952_k())) { + this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).increseScore(i); + } + + if (this.statsFile.func_150879_e()) { + this.statsFile.func_150876_a(this); + } + + } } - /**+ - * Sends an END_COMBAT packet to the client + /** + * + Called when the entity is attacked. */ - public void sendEndCombat() { - super.sendEndCombat(); - this.playerNetServerHandler - .sendPacket(new S42PacketCombatEvent(this.getCombatTracker(), S42PacketCombatEvent.Event.END_COMBAT)); + public boolean attackEntityFrom(DamageSource damagesource, float f) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + boolean flag = this.mcServer.isDedicatedServer() && this.canPlayersAttack() + && "fall".equals(damagesource.damageType); + if (!flag && this.respawnInvulnerabilityTicks > 0 && damagesource != DamageSource.outOfWorld) { + return false; + } else { + if (damagesource instanceof EntityDamageSource) { + Entity entity = damagesource.getEntity(); + if (entity instanceof EntityPlayer && !this.canAttackPlayer((EntityPlayer) entity)) { + return false; + } + + if (entity instanceof EntityArrow) { + EntityArrow entityarrow = (EntityArrow) entity; + if (entityarrow.shootingEntity instanceof EntityPlayer + && !this.canAttackPlayer((EntityPlayer) entityarrow.shootingEntity)) { + return false; + } + } + } + + return super.attackEntityFrom(damagesource, f); + } + } } - /**+ - * Called to update the entity's position/logic. + /** + * + Attacks for the player the targeted entity with the currently equipped + * item. The equipped item has hitEntity called on it. Args: targetEntity + */ + public void attackTargetEntityWithCurrentItem(Entity targetEntity) { + if (this.theItemInWorldManager.getGameType() == WorldSettings.GameType.SPECTATOR) { + this.setSpectatingEntity(targetEntity); + } else { + super.attackTargetEntityWithCurrentItem(targetEntity); + } + + } + + public boolean canAttackPlayer(EntityPlayer other) { + return !this.canPlayersAttack() ? false : super.canAttackPlayer(other); + } + + /** + * + Returns {@code true} if the CommandSender is allowed to execute the + * command, {@code false} if not + */ + public boolean canCommandSenderUseCommand(int i, String s) { + if ("seed".equals(s)) { + return true; + } else if (!"tell".equals(s) && !"help".equals(s) && !"me".equals(s) && !"trigger".equals(s)) { + return this.mcServer.getConfigurationManager().canSendCommands(this.getGameProfile()); + } else { + return true; + } + } + + /** + * + Returns if other players can attack this player + */ + private boolean canPlayersAttack() { + return this.mcServer.isPVPEnabled(); + } + + /** + * + Copies the values from the given player into this player if boolean par2 is + * true. Always clones Ender Chest Inventory. + */ + public void clonePlayer(EntityPlayer oldPlayer, boolean respawnFromEnd) { + super.clonePlayer(oldPlayer, respawnFromEnd); + this.lastExperience = -1; + this.lastHealth = -1.0F; + this.lastFoodLevel = -1; + this.destroyedItemsNetCache.addAll(((EntityPlayerMP) oldPlayer).destroyedItemsNetCache); + } + + /** + * + Closes the container the player currently has open. + */ + public void closeContainer() { + this.openContainer.onContainerClosed(this); + this.openContainer = this.inventoryContainer; + } + + /** + * + set current crafting inventory back to the 2x2 square + */ + public void closeScreen() { + this.playerNetServerHandler.sendPacket(new S2EPacketCloseWindow(this.openContainer.windowId)); + this.closeContainer(); + } + + public void displayGui(IInteractionObject iinteractionobject) { + this.getNextWindowId(); + this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, + iinteractionobject.getGuiID(), iinteractionobject.getDisplayName())); + this.openContainer = iinteractionobject.createContainer(this.inventory, this); + this.openContainer.windowId = this.currentWindowId; + this.openContainer.onCraftGuiOpened(this); + } + + /** + * + Displays the GUI for interacting with a book. + */ + public void displayGUIBook(ItemStack itemstack) { + Item item = itemstack.getItem(); + if (item == Items.written_book) { + this.playerNetServerHandler + .sendPacket(new S3FPacketCustomPayload("MC|BOpen", new PacketBuffer(Unpooled.buffer()))); + } + + } + + /** + * + Displays the GUI for interacting with a chest inventory. Args: + * chestInventory + */ + public void displayGUIChest(IInventory iinventory) { + if (this.openContainer != this.inventoryContainer) { + this.closeScreen(); + } + + if (iinventory instanceof ILockableContainer) { + ILockableContainer ilockablecontainer = (ILockableContainer) iinventory; + if (ilockablecontainer.isLocked() && !this.canOpen(ilockablecontainer.getLockCode()) + && !this.isSpectator()) { + this.playerNetServerHandler + .sendPacket(new S02PacketChat(new ChatComponentTranslation("container.isLocked", + new Object[] { iinventory.getDisplayName() }), (byte) 2)); + this.playerNetServerHandler.sendPacket( + new S29PacketSoundEffect("random.door_close", this.posX, this.posY, this.posZ, 1.0F, 1.0F)); + return; + } + } + + this.getNextWindowId(); + if (iinventory instanceof IInteractionObject) { + this.playerNetServerHandler.sendPacket( + new S2DPacketOpenWindow(this.currentWindowId, ((IInteractionObject) iinventory).getGuiID(), + iinventory.getDisplayName(), iinventory.getSizeInventory())); + this.openContainer = ((IInteractionObject) iinventory).createContainer(this.inventory, this); + } else { + this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "minecraft:container", + iinventory.getDisplayName(), iinventory.getSizeInventory())); + this.openContainer = new ContainerChest(this.inventory, iinventory, this); + } + + this.openContainer.windowId = this.currentWindowId; + this.openContainer.onCraftGuiOpened(this); + } + + public void displayGUIHorse(EntityHorse entityhorse, IInventory iinventory) { + if (this.openContainer != this.inventoryContainer) { + this.closeScreen(); + } + + this.getNextWindowId(); + this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "EntityHorse", + iinventory.getDisplayName(), iinventory.getSizeInventory(), entityhorse.getEntityId())); + this.openContainer = new ContainerHorseInventory(this.inventory, iinventory, entityhorse, this); + this.openContainer.windowId = this.currentWindowId; + this.openContainer.onCraftGuiOpened(this); + } + + public void displayVillagerTradeGui(IMerchant imerchant) { + this.getNextWindowId(); + this.openContainer = new ContainerMerchant(this.inventory, imerchant, this.worldObj); + this.openContainer.windowId = this.currentWindowId; + this.openContainer.onCraftGuiOpened(this); + InventoryMerchant inventorymerchant = ((ContainerMerchant) this.openContainer).getMerchantInventory(); + IChatComponent ichatcomponent = imerchant.getDisplayName(); + this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "minecraft:villager", + ichatcomponent, inventorymerchant.getSizeInventory())); + MerchantRecipeList merchantrecipelist = imerchant.getRecipes(this); + if (merchantrecipelist != null) { + PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); + packetbuffer.writeInt(this.currentWindowId); + merchantrecipelist.writeToBuf(packetbuffer); + this.playerNetServerHandler.sendPacket(new S3FPacketCustomPayload("MC|TrList", packetbuffer)); + } + + } + + public void func_175145_a(StatBase parStatBase) { + if (parStatBase != null) { + this.statsFile.unlockAchievement(this, parStatBase, 0); + + for (ScoreObjective scoreobjective : this.getWorldScoreboard() + .getObjectivesFromCriteria(parStatBase.func_150952_k())) { + this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).setScorePoints(0); + } + + if (this.statsFile.func_150879_e()) { + this.statsFile.func_150876_a(this); + } + + } + } + + public void func_175173_a(Container container, IInventory iinventory) { + for (int i = 0; i < iinventory.getFieldCount(); ++i) { + this.playerNetServerHandler + .sendPacket(new S31PacketWindowProperty(container.windowId, i, iinventory.getField(i))); + } + + } + + public EntityPlayer.EnumChatVisibility getChatVisibility() { + return this.chatVisibility; + } + + public long getLastActiveTime() { + return this.playerLastActiveTime; + } + + /** + * + get the next window id to use + */ + private void getNextWindowId() { + this.currentWindowId = this.currentWindowId % 100 + 1; + } + + /** + * + Gets the player's IP address. Used in /banip. + */ + public String getPlayerIP() { + return "channel:" + this.playerNetServerHandler.netManager.playerChannel; + } + + /** + * + Get the position in the world. {@code null} is not allowed! If you + * are not an entity in the world, return the coordinates 0, 0, 0 + */ + public BlockPos getPosition() { + return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); + } + + public WorldServer getServerForPlayer() { + return (WorldServer) this.worldObj; + } + + public Entity getSpectatingEntity() { + return (Entity) (this.spectatingEntity == null ? this : this.spectatingEntity); + } + + /** + * + Gets the stats file for reading achievements + */ + public StatisticsFile getStatFile() { + return this.statsFile; + } + + /** + * + Returns null which indicates the tab list should just display the player's + * name, return a different value to display the specified text instead of the + * player's name + */ + public IChatComponent getTabListDisplayName() { + return null; + } + + public void handleClientSettings(C15PacketClientSettings packetIn) { + this.translator = packetIn.getLang(); + this.chatVisibility = packetIn.getChatVisibility(); + this.chatColours = packetIn.isColorsEnabled(); + this.mcServer.getConfigurationManager().updatePlayerViewDistance(this, packetIn.getViewDistance()); + this.getDataWatcher().updateObject(10, Byte.valueOf((byte) packetIn.getModelPartFlags())); + } + + /** + * + process player falling based on movement packet + */ + public void handleFalling(double parDouble1, boolean parFlag) { + int i = MathHelper.floor_double(this.posX); + int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); + int k = MathHelper.floor_double(this.posZ); + BlockPos blockpos = new BlockPos(i, j, k); + Block block = this.worldObj.getBlockState(blockpos).getBlock(); + if (block.getMaterial() == Material.air) { + Block block1 = this.worldObj.getBlockState(blockpos.down()).getBlock(); + if (block1 instanceof BlockFence || block1 instanceof BlockWall || block1 instanceof BlockFenceGate) { + blockpos = blockpos.down(); + block = this.worldObj.getBlockState(blockpos).getBlock(); + } + } + + super.updateFallState(parDouble1, parFlag, block, blockpos); + } + + public boolean isSpectatedByPlayer(EntityPlayerMP player) { + return player.isSpectator() ? this.getSpectatingEntity() == this + : (this.isSpectator() ? false : super.isSpectatedByPlayer(player)); + } + + /** + * + Returns true if the player is in spectator mode. + */ + public boolean isSpectator() { + return this.theItemInWorldManager.getGameType() == WorldSettings.GameType.SPECTATOR; + } + + public void loadResourcePack(String url, String hash) { + this.playerNetServerHandler.sendPacket(new S48PacketResourcePackSend(url, hash)); + } + + public void markPlayerActive() { + this.playerLastActiveTime = MinecraftServer.getCurrentTimeMillis(); + } + + /** + * + Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. + */ + public void mountEntity(Entity entity) { + Entity entity1 = this.ridingEntity; + super.mountEntity(entity); + if (entity != entity1) { + this.playerNetServerHandler.sendPacket(new S1BPacketEntityAttach(0, this, this.ridingEntity)); + this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, + this.rotationPitch); + } + + } + + public void mountEntityAndWakeUp() { + if (this.riddenByEntity != null) { + this.riddenByEntity.mountEntity(this); + } + + if (this.sleeping) { + this.wakeUpPlayer(true, false, false); + } + + } + + protected void onChangedPotionEffect(PotionEffect id, boolean parFlag) { + super.onChangedPotionEffect(id, parFlag); + this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id)); + } + + /** + * + Called when the player performs a critical hit on the Entity. Args: entity + * that was hit critically + */ + public void onCriticalHit(Entity entity) { + this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(entity, 4)); + } + + /** + * + Called when the mob's health reaches 0. + */ + public void onDeath(DamageSource cause) { + if (this.worldObj.getGameRules().getBoolean("showDeathMessages")) { + Team team = this.getTeam(); + if (team != null && team.getDeathMessageVisibility() != Team.EnumVisible.ALWAYS) { + if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OTHER_TEAMS) { + this.mcServer.getConfigurationManager().sendMessageToAllTeamMembers(this, + this.getCombatTracker().getDeathMessage()); + } else if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OWN_TEAM) { + this.mcServer.getConfigurationManager().sendMessageToTeamOrEvryPlayer(this, + this.getCombatTracker().getDeathMessage()); + } + } else { + this.mcServer.getConfigurationManager().sendChatMsg(this.getCombatTracker().getDeathMessage()); + } + } + + if (!this.worldObj.getGameRules().getBoolean("keepInventory")) { + this.inventory.dropAllItems(); + } + + for (ScoreObjective scoreobjective : this.worldObj.getScoreboard() + .getObjectivesFromCriteria(IScoreObjectiveCriteria.deathCount)) { + Score score = this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective); + score.func_96648_a(); + } + + EntityLivingBase entitylivingbase = this.func_94060_bK(); + if (entitylivingbase != null) { + EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs + .get(Integer.valueOf(EntityList.getEntityID(entitylivingbase))); + if (entitylist$entityegginfo != null) { + this.triggerAchievement(entitylist$entityegginfo.field_151513_e); + } + + entitylivingbase.addToPlayerScore(this, this.scoreValue); + } + + this.triggerAchievement(StatList.deathsStat); + this.func_175145_a(StatList.timeSinceDeathStat); + this.getCombatTracker().reset(); + } + + public void onEnchantmentCritical(Entity entity) { + this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(entity, 5)); + } + + protected void onFinishedPotionEffect(PotionEffect parPotionEffect) { + super.onFinishedPotionEffect(parPotionEffect); + this.playerNetServerHandler.sendPacket(new S1EPacketRemoveEntityEffect(this.getEntityId(), parPotionEffect)); + } + + /** + * + Called whenever an item is picked up from walking over it. Args: + * pickedUpEntity, stackSize + */ + public void onItemPickup(Entity parEntity, int parInt1) { + super.onItemPickup(parEntity, parInt1); + this.openContainer.detectAndSendChanges(); + } + + /** + * + Used for when item use count runs out, ie: eating completed + */ + protected void onItemUseFinish() { + this.playerNetServerHandler.sendPacket(new S19PacketEntityStatus(this, (byte) 9)); + super.onItemUseFinish(); + } + + protected void onNewPotionEffect(PotionEffect id) { + super.onNewPotionEffect(id); + this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id)); + } + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.theItemInWorldManager.updateBlockRemoving(); @@ -410,9 +825,227 @@ public class EntityPlayerMP extends EntityPlayer implements ICrafting { } } - /**+ - * Updates all biomes that have been explored by this player and - * triggers Adventuring Time if player qualifies. + public void openEditSign(TileEntitySign tileentitysign) { + tileentitysign.setPlayer(this); + this.playerNetServerHandler.sendPacket(new S36PacketSignEditorOpen(tileentitysign.getPos())); + } + + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. + */ + public void readEntityFromNBT(NBTTagCompound nbttagcompound) { + super.readEntityFromNBT(nbttagcompound); + if (nbttagcompound.hasKey("playerGameType", 99)) { + if (MinecraftServer.getServer().getForceGamemode()) { + this.theItemInWorldManager.setGameType(MinecraftServer.getServer().getGameType()); + } else { + this.theItemInWorldManager + .setGameType(WorldSettings.GameType.getByID(nbttagcompound.getInteger("playerGameType"))); + } + } + + } + + /** + * + Sends a packet to the player to remove an entity. + */ + public void removeEntity(Entity parEntity) { + if (parEntity instanceof EntityPlayer) { + this.playerNetServerHandler.sendPacket(new S13PacketDestroyEntities(new int[] { parEntity.getEntityId() })); + } else { + this.destroyedItemsNetCache.add(Integer.valueOf(parEntity.getEntityId())); + } + + } + + public void removeExperienceLevel(int levels) { + super.removeExperienceLevel(levels); + this.lastExperience = -1; + } + + public void sendContainerToPlayer(Container parContainer) { + this.updateCraftingInventory(parContainer, parContainer.getInventory()); + } + + /** + * + Sends an END_COMBAT packet to the client + */ + public void sendEndCombat() { + super.sendEndCombat(); + this.playerNetServerHandler + .sendPacket(new S42PacketCombatEvent(this.getCombatTracker(), S42PacketCombatEvent.Event.END_COMBAT)); + } + + /** + * + Sends an ENTER_COMBAT packet to the client + */ + public void sendEnterCombat() { + super.sendEnterCombat(); + this.playerNetServerHandler + .sendPacket(new S42PacketCombatEvent(this.getCombatTracker(), S42PacketCombatEvent.Event.ENTER_COMBAT)); + } + + /** + * + Sends the player's abilities to the server (if there is one). + */ + public void sendPlayerAbilities() { + if (this.playerNetServerHandler != null) { + this.playerNetServerHandler.sendPacket(new S39PacketPlayerAbilities(this.capabilities)); + this.updatePotionMetadata(); + } + } + + /** + * + Sends two ints to the client-side Container. Used for furnace burning time, + * smelting progress, brewing progress, and enchanting level. Normally the first + * int identifies which variable to update, and the second contains the new + * value. Both are truncated to shorts in non-local SMP. + */ + public void sendProgressBarUpdate(Container container, int i, int j) { + this.playerNetServerHandler.sendPacket(new S31PacketWindowProperty(container.windowId, i, j)); + } + + /** + * + Sends the contents of an inventory slot to the client-side Container. This + * doesn't have to match the actual contents of that slot. Args: Container, slot + * number, slot contents + */ + public void sendSlotContents(Container container, int i, ItemStack itemstack) { + if (!(container.getSlot(i) instanceof SlotCrafting)) { + if (!this.isChangingQuantityOnly) { + this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(container.windowId, i, itemstack)); + } + } + } + + private void sendTileEntityUpdate(TileEntity parTileEntity) { + if (parTileEntity != null) { + Packet packet = parTileEntity.getDescriptionPacket(); + if (packet != null) { + this.playerNetServerHandler.sendPacket(packet); + } + } + + } + + public void setEntityActionState(float sneaking, float parFloat2, boolean parFlag, boolean parFlag2) { + if (this.ridingEntity != null) { + if (sneaking >= -1.0F && sneaking <= 1.0F) { + this.moveStrafing = sneaking; + } + + if (parFloat2 >= -1.0F && parFloat2 <= 1.0F) { + this.moveForward = parFloat2; + } + + this.isJumping = parFlag; + this.setSneaking(parFlag2); + } + + } + + /** + * + Sets the player's game mode and sends it to them. + */ + public void setGameType(WorldSettings.GameType gameType) { + this.theItemInWorldManager.setGameType(gameType); + this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(3, (float) gameType.getID())); + if (gameType == WorldSettings.GameType.SPECTATOR) { + this.mountEntity((Entity) null); + } else { + this.setSpectatingEntity(this); + } + + this.sendPlayerAbilities(); + this.markPotionsDirty(); + } + + /** + * + sets the itemInUse when the use item button is clicked. Args: itemstack, + * int maxItemUseDuration + */ + public void setItemInUse(ItemStack stack, int duration) { + super.setItemInUse(stack, duration); + if (stack != null && stack.getItem() != null && stack.getItem().getItemUseAction(stack) == EnumAction.EAT) { + this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(this, 3)); + } + + } + + /** + * + this function is called when a players inventory is sent to him, lastHealth + * is updated on any dimension transitions, then reset. + */ + public void setPlayerHealthUpdated() { + this.lastHealth = -1.0E8F; + } + + /** + * + Sets the position of the entity and updates the 'last' variables + */ + public void setPositionAndUpdate(double x, double y, double z) { + this.playerNetServerHandler.setPlayerLocation(x, y, z, this.rotationYaw, this.rotationPitch); + } + + public void setSpectatingEntity(Entity entityToSpectate) { + Entity entity = this.getSpectatingEntity(); + this.spectatingEntity = (Entity) (entityToSpectate == null ? this : entityToSpectate); + if (entity != this.spectatingEntity) { + this.playerNetServerHandler.sendPacket(new S43PacketCamera(this.spectatingEntity)); + this.setPositionAndUpdate(this.spectatingEntity.posX, this.spectatingEntity.posY, + this.spectatingEntity.posZ); + } + + } + + /** + * + Teleports the entity to another dimension. Params: Dimension number to + * teleport to + */ + public void travelToDimension(int dimensionId) { + if (this.dimension == 1 && dimensionId == 1) { + this.triggerAchievement(AchievementList.theEnd2); + this.worldObj.removeEntity(this); + this.playerConqueredTheEnd = true; + this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(4, 0.0F)); + } else { + if (this.dimension == 0 && dimensionId == 1) { + this.triggerAchievement(AchievementList.theEnd); + BlockPos blockpos = this.mcServer.worldServerForDimension(dimensionId).getSpawnCoordinate(); + if (blockpos != null) { + this.playerNetServerHandler.setPlayerLocation((double) blockpos.getX(), (double) blockpos.getY(), + (double) blockpos.getZ(), 0.0F, 0.0F); + } + + dimensionId = 1; + } else { + this.triggerAchievement(AchievementList.portal); + } + + this.mcServer.getConfigurationManager().transferPlayerToDimension(this, dimensionId); + this.lastExperience = -1; + this.lastHealth = -1.0F; + this.lastFoodLevel = -1; + } + + } + + public EntityPlayer.EnumStatus trySleep(BlockPos bedLocation) { + EntityPlayer.EnumStatus entityplayer$enumstatus = super.trySleep(bedLocation); + if (entityplayer$enumstatus == EntityPlayer.EnumStatus.OK) { + S0APacketUseBed s0apacketusebed = new S0APacketUseBed(this, bedLocation); + this.getServerForPlayer().getEntityTracker().sendToAllTrackingEntity(this, s0apacketusebed); + this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, + this.rotationPitch); + this.playerNetServerHandler.sendPacket(s0apacketusebed); + } + + return entityplayer$enumstatus; + } + + /** + * + Updates all biomes that have been explored by this player and triggers + * Adventuring Time if player qualifies. */ protected void updateBiomesExplored() { BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords( @@ -452,165 +1085,44 @@ public class EntityPlayerMP extends EntityPlayer implements ICrafting { } - /**+ - * Called when the mob's health reaches 0. + /** + * + update the crafting window inventory with the items in the list */ - public void onDeath(DamageSource cause) { - if (this.worldObj.getGameRules().getBoolean("showDeathMessages")) { - Team team = this.getTeam(); - if (team != null && team.getDeathMessageVisibility() != Team.EnumVisible.ALWAYS) { - if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OTHER_TEAMS) { - this.mcServer.getConfigurationManager().sendMessageToAllTeamMembers(this, - this.getCombatTracker().getDeathMessage()); - } else if (team.getDeathMessageVisibility() == Team.EnumVisible.HIDE_FOR_OWN_TEAM) { - this.mcServer.getConfigurationManager().sendMessageToTeamOrEvryPlayer(this, - this.getCombatTracker().getDeathMessage()); - } - } else { - this.mcServer.getConfigurationManager().sendChatMsg(this.getCombatTracker().getDeathMessage()); - } - } - - if (!this.worldObj.getGameRules().getBoolean("keepInventory")) { - this.inventory.dropAllItems(); - } - - for (ScoreObjective scoreobjective : this.worldObj.getScoreboard() - .getObjectivesFromCriteria(IScoreObjectiveCriteria.deathCount)) { - Score score = this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective); - score.func_96648_a(); - } - - EntityLivingBase entitylivingbase = this.func_94060_bK(); - if (entitylivingbase != null) { - EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs - .get(Integer.valueOf(EntityList.getEntityID(entitylivingbase))); - if (entitylist$entityegginfo != null) { - this.triggerAchievement(entitylist$entityegginfo.field_151513_e); - } - - entitylivingbase.addToPlayerScore(this, this.scoreValue); - } - - this.triggerAchievement(StatList.deathsStat); - this.func_175145_a(StatList.timeSinceDeathStat); - this.getCombatTracker().reset(); + public void updateCraftingInventory(Container container, List list) { + this.playerNetServerHandler.sendPacket(new S30PacketWindowItems(container.windowId, list)); + this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack())); } - /**+ - * Called when the entity is attacked. + protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos) { + } + + /** + * + updates item held by mouse */ - public boolean attackEntityFrom(DamageSource damagesource, float f) { - if (this.isEntityInvulnerable(damagesource)) { - return false; + public void updateHeldItem() { + if (!this.isChangingQuantityOnly) { + this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack())); + } + } + + /** + * + Clears potion metadata values if the entity has no potion effects. + * Otherwise, updates potion effect color, ambience, and invisibility metadata + * values + */ + protected void updatePotionMetadata() { + if (this.isSpectator()) { + this.resetPotionEffectMetadata(); + this.setInvisible(true); } else { - boolean flag = this.mcServer.isDedicatedServer() && this.canPlayersAttack() - && "fall".equals(damagesource.damageType); - if (!flag && this.respawnInvulnerabilityTicks > 0 && damagesource != DamageSource.outOfWorld) { - return false; - } else { - if (damagesource instanceof EntityDamageSource) { - Entity entity = damagesource.getEntity(); - if (entity instanceof EntityPlayer && !this.canAttackPlayer((EntityPlayer) entity)) { - return false; - } - - if (entity instanceof EntityArrow) { - EntityArrow entityarrow = (EntityArrow) entity; - if (entityarrow.shootingEntity instanceof EntityPlayer - && !this.canAttackPlayer((EntityPlayer) entityarrow.shootingEntity)) { - return false; - } - } - } - - return super.attackEntityFrom(damagesource, f); - } - } - } - - public boolean canAttackPlayer(EntityPlayer other) { - return !this.canPlayersAttack() ? false : super.canAttackPlayer(other); - } - - /**+ - * Returns if other players can attack this player - */ - private boolean canPlayersAttack() { - return this.mcServer.isPVPEnabled(); - } - - /**+ - * Teleports the entity to another dimension. Params: Dimension - * number to teleport to - */ - public void travelToDimension(int dimensionId) { - if (this.dimension == 1 && dimensionId == 1) { - this.triggerAchievement(AchievementList.theEnd2); - this.worldObj.removeEntity(this); - this.playerConqueredTheEnd = true; - this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(4, 0.0F)); - } else { - if (this.dimension == 0 && dimensionId == 1) { - this.triggerAchievement(AchievementList.theEnd); - BlockPos blockpos = this.mcServer.worldServerForDimension(dimensionId).getSpawnCoordinate(); - if (blockpos != null) { - this.playerNetServerHandler.setPlayerLocation((double) blockpos.getX(), (double) blockpos.getY(), - (double) blockpos.getZ(), 0.0F, 0.0F); - } - - dimensionId = 1; - } else { - this.triggerAchievement(AchievementList.portal); - } - - this.mcServer.getConfigurationManager().transferPlayerToDimension(this, dimensionId); - this.lastExperience = -1; - this.lastHealth = -1.0F; - this.lastFoodLevel = -1; + super.updatePotionMetadata(); } + this.getServerForPlayer().getEntityTracker().func_180245_a(this); } - public boolean isSpectatedByPlayer(EntityPlayerMP player) { - return player.isSpectator() ? this.getSpectatingEntity() == this - : (this.isSpectator() ? false : super.isSpectatedByPlayer(player)); - } - - private void sendTileEntityUpdate(TileEntity parTileEntity) { - if (parTileEntity != null) { - Packet packet = parTileEntity.getDescriptionPacket(); - if (packet != null) { - this.playerNetServerHandler.sendPacket(packet); - } - } - - } - - /**+ - * Called whenever an item is picked up from walking over it. - * Args: pickedUpEntity, stackSize - */ - public void onItemPickup(Entity parEntity, int parInt1) { - super.onItemPickup(parEntity, parInt1); - this.openContainer.detectAndSendChanges(); - } - - public EntityPlayer.EnumStatus trySleep(BlockPos bedLocation) { - EntityPlayer.EnumStatus entityplayer$enumstatus = super.trySleep(bedLocation); - if (entityplayer$enumstatus == EntityPlayer.EnumStatus.OK) { - S0APacketUseBed s0apacketusebed = new S0APacketUseBed(this, bedLocation); - this.getServerForPlayer().getEntityTracker().sendToAllTrackingEntity(this, s0apacketusebed); - this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, - this.rotationPitch); - this.playerNetServerHandler.sendPacket(s0apacketusebed); - } - - return entityplayer$enumstatus; - } - - /**+ - * Wake up the player if they're sleeping. + /** + * + Wake up the player if they're sleeping. */ public void wakeUpPlayer(boolean updateWorldFlag, boolean setSpawn, boolean parFlag3) { if (this.isPlayerSleeping()) { @@ -625,527 +1137,11 @@ public class EntityPlayerMP extends EntityPlayer implements ICrafting { } - /**+ - * Called when a player mounts an entity. e.g. mounts a pig, - * mounts a boat. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public void mountEntity(Entity entity) { - Entity entity1 = this.ridingEntity; - super.mountEntity(entity); - if (entity != entity1) { - this.playerNetServerHandler.sendPacket(new S1BPacketEntityAttach(0, this, this.ridingEntity)); - this.playerNetServerHandler.setPlayerLocation(this.posX, this.posY, this.posZ, this.rotationYaw, - this.rotationPitch); - } - - } - - protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos) { - } - - /**+ - * process player falling based on movement packet - */ - public void handleFalling(double parDouble1, boolean parFlag) { - int i = MathHelper.floor_double(this.posX); - int j = MathHelper.floor_double(this.posY - 0.20000000298023224D); - int k = MathHelper.floor_double(this.posZ); - BlockPos blockpos = new BlockPos(i, j, k); - Block block = this.worldObj.getBlockState(blockpos).getBlock(); - if (block.getMaterial() == Material.air) { - Block block1 = this.worldObj.getBlockState(blockpos.down()).getBlock(); - if (block1 instanceof BlockFence || block1 instanceof BlockWall || block1 instanceof BlockFenceGate) { - blockpos = blockpos.down(); - block = this.worldObj.getBlockState(blockpos).getBlock(); - } - } - - super.updateFallState(parDouble1, parFlag, block, blockpos); - } - - public void openEditSign(TileEntitySign tileentitysign) { - tileentitysign.setPlayer(this); - this.playerNetServerHandler.sendPacket(new S36PacketSignEditorOpen(tileentitysign.getPos())); - } - - /**+ - * get the next window id to use - */ - private void getNextWindowId() { - this.currentWindowId = this.currentWindowId % 100 + 1; - } - - public void displayGui(IInteractionObject iinteractionobject) { - this.getNextWindowId(); - this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, - iinteractionobject.getGuiID(), iinteractionobject.getDisplayName())); - this.openContainer = iinteractionobject.createContainer(this.inventory, this); - this.openContainer.windowId = this.currentWindowId; - this.openContainer.onCraftGuiOpened(this); - } - - /**+ - * Displays the GUI for interacting with a chest inventory. - * Args: chestInventory - */ - public void displayGUIChest(IInventory iinventory) { - if (this.openContainer != this.inventoryContainer) { - this.closeScreen(); - } - - if (iinventory instanceof ILockableContainer) { - ILockableContainer ilockablecontainer = (ILockableContainer) iinventory; - if (ilockablecontainer.isLocked() && !this.canOpen(ilockablecontainer.getLockCode()) - && !this.isSpectator()) { - this.playerNetServerHandler - .sendPacket(new S02PacketChat(new ChatComponentTranslation("container.isLocked", - new Object[] { iinventory.getDisplayName() }), (byte) 2)); - this.playerNetServerHandler.sendPacket( - new S29PacketSoundEffect("random.door_close", this.posX, this.posY, this.posZ, 1.0F, 1.0F)); - return; - } - } - - this.getNextWindowId(); - if (iinventory instanceof IInteractionObject) { - this.playerNetServerHandler.sendPacket( - new S2DPacketOpenWindow(this.currentWindowId, ((IInteractionObject) iinventory).getGuiID(), - iinventory.getDisplayName(), iinventory.getSizeInventory())); - this.openContainer = ((IInteractionObject) iinventory).createContainer(this.inventory, this); - } else { - this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "minecraft:container", - iinventory.getDisplayName(), iinventory.getSizeInventory())); - this.openContainer = new ContainerChest(this.inventory, iinventory, this); - } - - this.openContainer.windowId = this.currentWindowId; - this.openContainer.onCraftGuiOpened(this); - } - - public void displayVillagerTradeGui(IMerchant imerchant) { - this.getNextWindowId(); - this.openContainer = new ContainerMerchant(this.inventory, imerchant, this.worldObj); - this.openContainer.windowId = this.currentWindowId; - this.openContainer.onCraftGuiOpened(this); - InventoryMerchant inventorymerchant = ((ContainerMerchant) this.openContainer).getMerchantInventory(); - IChatComponent ichatcomponent = imerchant.getDisplayName(); - this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "minecraft:villager", - ichatcomponent, inventorymerchant.getSizeInventory())); - MerchantRecipeList merchantrecipelist = imerchant.getRecipes(this); - if (merchantrecipelist != null) { - PacketBuffer packetbuffer = new PacketBuffer(Unpooled.buffer()); - packetbuffer.writeInt(this.currentWindowId); - merchantrecipelist.writeToBuf(packetbuffer); - this.playerNetServerHandler.sendPacket(new S3FPacketCustomPayload("MC|TrList", packetbuffer)); - } - - } - - public void displayGUIHorse(EntityHorse entityhorse, IInventory iinventory) { - if (this.openContainer != this.inventoryContainer) { - this.closeScreen(); - } - - this.getNextWindowId(); - this.playerNetServerHandler.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "EntityHorse", - iinventory.getDisplayName(), iinventory.getSizeInventory(), entityhorse.getEntityId())); - this.openContainer = new ContainerHorseInventory(this.inventory, iinventory, entityhorse, this); - this.openContainer.windowId = this.currentWindowId; - this.openContainer.onCraftGuiOpened(this); - } - - /**+ - * Displays the GUI for interacting with a book. - */ - public void displayGUIBook(ItemStack itemstack) { - Item item = itemstack.getItem(); - if (item == Items.written_book) { - this.playerNetServerHandler - .sendPacket(new S3FPacketCustomPayload("MC|BOpen", new PacketBuffer(Unpooled.buffer()))); - } - - } - - /**+ - * Sends the contents of an inventory slot to the client-side - * Container. This doesn't have to match the actual contents of - * that slot. Args: Container, slot number, slot contents - */ - public void sendSlotContents(Container container, int i, ItemStack itemstack) { - if (!(container.getSlot(i) instanceof SlotCrafting)) { - if (!this.isChangingQuantityOnly) { - this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(container.windowId, i, itemstack)); - } - } - } - - public void sendContainerToPlayer(Container parContainer) { - this.updateCraftingInventory(parContainer, parContainer.getInventory()); - } - - /**+ - * update the crafting window inventory with the items in the - * list - */ - public void updateCraftingInventory(Container container, List list) { - this.playerNetServerHandler.sendPacket(new S30PacketWindowItems(container.windowId, list)); - this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack())); - } - - /**+ - * Sends two ints to the client-side Container. Used for furnace - * burning time, smelting progress, brewing progress, and - * enchanting level. Normally the first int identifies which - * variable to update, and the second contains the new value. - * Both are truncated to shorts in non-local SMP. - */ - public void sendProgressBarUpdate(Container container, int i, int j) { - this.playerNetServerHandler.sendPacket(new S31PacketWindowProperty(container.windowId, i, j)); - } - - public void func_175173_a(Container container, IInventory iinventory) { - for (int i = 0; i < iinventory.getFieldCount(); ++i) { - this.playerNetServerHandler - .sendPacket(new S31PacketWindowProperty(container.windowId, i, iinventory.getField(i))); - } - - } - - /**+ - * set current crafting inventory back to the 2x2 square - */ - public void closeScreen() { - this.playerNetServerHandler.sendPacket(new S2EPacketCloseWindow(this.openContainer.windowId)); - this.closeContainer(); - } - - /**+ - * updates item held by mouse - */ - public void updateHeldItem() { - if (!this.isChangingQuantityOnly) { - this.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(-1, -1, this.inventory.getItemStack())); - } - } - - /**+ - * Closes the container the player currently has open. - */ - public void closeContainer() { - this.openContainer.onContainerClosed(this); - this.openContainer = this.inventoryContainer; - } - - public void setEntityActionState(float sneaking, float parFloat2, boolean parFlag, boolean parFlag2) { - if (this.ridingEntity != null) { - if (sneaking >= -1.0F && sneaking <= 1.0F) { - this.moveStrafing = sneaking; - } - - if (parFloat2 >= -1.0F && parFloat2 <= 1.0F) { - this.moveForward = parFloat2; - } - - this.isJumping = parFlag; - this.setSneaking(parFlag2); - } - - } - - /**+ - * Adds a value to a statistic field. - */ - public void addStat(StatBase statbase, int i) { - if (statbase != null) { - this.statsFile.increaseStat(this, statbase, i); - - for (ScoreObjective scoreobjective : this.getWorldScoreboard() - .getObjectivesFromCriteria(statbase.func_150952_k())) { - this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).increseScore(i); - } - - if (this.statsFile.func_150879_e()) { - this.statsFile.func_150876_a(this); - } - - } - } - - public void func_175145_a(StatBase parStatBase) { - if (parStatBase != null) { - this.statsFile.unlockAchievement(this, parStatBase, 0); - - for (ScoreObjective scoreobjective : this.getWorldScoreboard() - .getObjectivesFromCriteria(parStatBase.func_150952_k())) { - this.getWorldScoreboard().getValueFromObjective(this.getName(), scoreobjective).setScorePoints(0); - } - - if (this.statsFile.func_150879_e()) { - this.statsFile.func_150876_a(this); - } - - } - } - - public void mountEntityAndWakeUp() { - if (this.riddenByEntity != null) { - this.riddenByEntity.mountEntity(this); - } - - if (this.sleeping) { - this.wakeUpPlayer(true, false, false); - } - - } - - /**+ - * this function is called when a players inventory is sent to - * him, lastHealth is updated on any dimension transitions, then - * reset. - */ - public void setPlayerHealthUpdated() { - this.lastHealth = -1.0E8F; - } - - public void addChatComponentMessage(IChatComponent ichatcomponent) { - this.playerNetServerHandler.sendPacket(new S02PacketChat(ichatcomponent)); - } - - /**+ - * Used for when item use count runs out, ie: eating completed - */ - protected void onItemUseFinish() { - this.playerNetServerHandler.sendPacket(new S19PacketEntityStatus(this, (byte) 9)); - super.onItemUseFinish(); - } - - /**+ - * sets the itemInUse when the use item button is clicked. Args: - * itemstack, int maxItemUseDuration - */ - public void setItemInUse(ItemStack stack, int duration) { - super.setItemInUse(stack, duration); - if (stack != null && stack.getItem() != null && stack.getItem().getItemUseAction(stack) == EnumAction.EAT) { - this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(this, 3)); - } - - } - - /**+ - * Copies the values from the given player into this player if - * boolean par2 is true. Always clones Ender Chest Inventory. - */ - public void clonePlayer(EntityPlayer oldPlayer, boolean respawnFromEnd) { - super.clonePlayer(oldPlayer, respawnFromEnd); - this.lastExperience = -1; - this.lastHealth = -1.0F; - this.lastFoodLevel = -1; - this.destroyedItemsNetCache.addAll(((EntityPlayerMP) oldPlayer).destroyedItemsNetCache); - } - - protected void onNewPotionEffect(PotionEffect id) { - super.onNewPotionEffect(id); - this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id)); - } - - protected void onChangedPotionEffect(PotionEffect id, boolean parFlag) { - super.onChangedPotionEffect(id, parFlag); - this.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(this.getEntityId(), id)); - } - - protected void onFinishedPotionEffect(PotionEffect parPotionEffect) { - super.onFinishedPotionEffect(parPotionEffect); - this.playerNetServerHandler.sendPacket(new S1EPacketRemoveEntityEffect(this.getEntityId(), parPotionEffect)); - } - - /**+ - * Sets the position of the entity and updates the 'last' - * variables - */ - public void setPositionAndUpdate(double x, double y, double z) { - this.playerNetServerHandler.setPlayerLocation(x, y, z, this.rotationYaw, this.rotationPitch); - } - - /**+ - * Called when the player performs a critical hit on the Entity. - * Args: entity that was hit critically - */ - public void onCriticalHit(Entity entity) { - this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(entity, 4)); - } - - public void onEnchantmentCritical(Entity entity) { - this.getServerForPlayer().getEntityTracker().func_151248_b(this, new S0BPacketAnimation(entity, 5)); - } - - /**+ - * Sends the player's abilities to the server (if there is one). - */ - public void sendPlayerAbilities() { - if (this.playerNetServerHandler != null) { - this.playerNetServerHandler.sendPacket(new S39PacketPlayerAbilities(this.capabilities)); - this.updatePotionMetadata(); - } - } - - public WorldServer getServerForPlayer() { - return (WorldServer) this.worldObj; - } - - /**+ - * Sets the player's game mode and sends it to them. - */ - public void setGameType(WorldSettings.GameType gameType) { - this.theItemInWorldManager.setGameType(gameType); - this.playerNetServerHandler.sendPacket(new S2BPacketChangeGameState(3, (float) gameType.getID())); - if (gameType == WorldSettings.GameType.SPECTATOR) { - this.mountEntity((Entity) null); - } else { - this.setSpectatingEntity(this); - } - - this.sendPlayerAbilities(); - this.markPotionsDirty(); - } - - /**+ - * Returns true if the player is in spectator mode. - */ - public boolean isSpectator() { - return this.theItemInWorldManager.getGameType() == WorldSettings.GameType.SPECTATOR; - } - - /**+ - * Send a chat message to the CommandSender - */ - public void addChatMessage(IChatComponent ichatcomponent) { - this.playerNetServerHandler.sendPacket(new S02PacketChat(ichatcomponent)); - } - - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not - */ - public boolean canCommandSenderUseCommand(int i, String s) { - if ("seed".equals(s)) { - return true; - } else if (!"tell".equals(s) && !"help".equals(s) && !"me".equals(s) && !"trigger".equals(s)) { - return this.mcServer.getConfigurationManager().canSendCommands(this.getGameProfile()); - } else { - return true; - } - } - - /**+ - * Gets the player's IP address. Used in /banip. - */ - public String getPlayerIP() { - return "channel:" + this.playerNetServerHandler.netManager.playerChannel; - } - - public void handleClientSettings(C15PacketClientSettings packetIn) { - this.translator = packetIn.getLang(); - this.chatVisibility = packetIn.getChatVisibility(); - this.chatColours = packetIn.isColorsEnabled(); - this.mcServer.getConfigurationManager().updatePlayerViewDistance(this, packetIn.getViewDistance()); - this.getDataWatcher().updateObject(10, Byte.valueOf((byte) packetIn.getModelPartFlags())); - } - - public EntityPlayer.EnumChatVisibility getChatVisibility() { - return this.chatVisibility; - } - - public void loadResourcePack(String url, String hash) { - this.playerNetServerHandler.sendPacket(new S48PacketResourcePackSend(url, hash)); - } - - /**+ - * Get the position in the world. {@code null} is not - * allowed! If you are not an entity in the world, return - * the coordinates 0, 0, 0 - */ - public BlockPos getPosition() { - return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); - } - - public void markPlayerActive() { - this.playerLastActiveTime = MinecraftServer.getCurrentTimeMillis(); - } - - /**+ - * Gets the stats file for reading achievements - */ - public StatisticsFile getStatFile() { - return this.statsFile; - } - - /**+ - * Sends a packet to the player to remove an entity. - */ - public void removeEntity(Entity parEntity) { - if (parEntity instanceof EntityPlayer) { - this.playerNetServerHandler.sendPacket(new S13PacketDestroyEntities(new int[] { parEntity.getEntityId() })); - } else { - this.destroyedItemsNetCache.add(Integer.valueOf(parEntity.getEntityId())); - } - - } - - /**+ - * Clears potion metadata values if the entity has no potion - * effects. Otherwise, updates potion effect color, ambience, - * and invisibility metadata values - */ - protected void updatePotionMetadata() { - if (this.isSpectator()) { - this.resetPotionEffectMetadata(); - this.setInvisible(true); - } else { - super.updatePotionMetadata(); - } - - this.getServerForPlayer().getEntityTracker().func_180245_a(this); - } - - public Entity getSpectatingEntity() { - return (Entity) (this.spectatingEntity == null ? this : this.spectatingEntity); - } - - public void setSpectatingEntity(Entity entityToSpectate) { - Entity entity = this.getSpectatingEntity(); - this.spectatingEntity = (Entity) (entityToSpectate == null ? this : entityToSpectate); - if (entity != this.spectatingEntity) { - this.playerNetServerHandler.sendPacket(new S43PacketCamera(this.spectatingEntity)); - this.setPositionAndUpdate(this.spectatingEntity.posX, this.spectatingEntity.posY, - this.spectatingEntity.posZ); - } - - } - - /**+ - * Attacks for the player the targeted entity with the currently - * equipped item. The equipped item has hitEntity called on it. - * Args: targetEntity - */ - public void attackTargetEntityWithCurrentItem(Entity targetEntity) { - if (this.theItemInWorldManager.getGameType() == WorldSettings.GameType.SPECTATOR) { - this.setSpectatingEntity(targetEntity); - } else { - super.attackTargetEntityWithCurrentItem(targetEntity); - } - - } - - public long getLastActiveTime() { - return this.playerLastActiveTime; - } - - /**+ - * Returns null which indicates the tab list should just display - * the player's name, return a different value to display the - * specified text instead of the player's name - */ - public IChatComponent getTabListDisplayName() { - return null; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("playerGameType", this.theItemInWorldManager.getGameType().getID()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/player/EnumPlayerModelParts.java b/src/game/java/net/minecraft/entity/player/EnumPlayerModelParts.java index 04abdbb2..31904df8 100644 --- a/src/game/java/net/minecraft/entity/player/EnumPlayerModelParts.java +++ b/src/game/java/net/minecraft/entity/player/EnumPlayerModelParts.java @@ -3,22 +3,25 @@ package net.minecraft.entity.player; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,19 +44,19 @@ public enum EnumPlayerModelParts { this.field_179339_k = new ChatComponentTranslation("options.modelPart." + partNameIn, new Object[0]); } - public int getPartMask() { - return this.partMask; + public IChatComponent func_179326_d() { + return this.field_179339_k; } public int getPartId() { return this.partId; } + public int getPartMask() { + return this.partMask; + } + public String getPartName() { return this.partName; } - - public IChatComponent func_179326_d() { - return this.field_179339_k; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/player/InventoryPlayer.java b/src/game/java/net/minecraft/entity/player/InventoryPlayer.java index 2bf546de..d3bee2bd 100644 --- a/src/game/java/net/minecraft/entity/player/InventoryPlayer.java +++ b/src/game/java/net/minecraft/entity/player/InventoryPlayer.java @@ -17,145 +17,129 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; import net.minecraft.util.ReportedException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class InventoryPlayer implements IInventory { - /**+ - * An array of 36 item stacks indicating the main player - * inventory (including the visible bar). + /** + * + Get the size of the player hotbar inventory + */ + public static int getHotbarSize() { + return 9; + } + + /** + * + An array of 36 item stacks indicating the main player inventory (including + * the visible bar). */ public ItemStack[] mainInventory = new ItemStack[36]; - /**+ - * An array of 4 item stacks containing the currently worn armor - * pieces. + /** + * + An array of 4 item stacks containing the currently worn armor pieces. */ public ItemStack[] armorInventory = new ItemStack[4]; public int currentItem; public EntityPlayer player; private ItemStack itemStack; + public boolean inventoryChanged; public InventoryPlayer(EntityPlayer playerIn) { this.player = playerIn; } - /**+ - * Returns the item stack currently held by the player. + /** + * + Adds the item stack to the inventory, returns false if it is impossible. */ - public ItemStack getCurrentItem() { - return this.currentItem < 9 && this.currentItem >= 0 ? this.mainInventory[this.currentItem] : null; - } - - /**+ - * Get the size of the player hotbar inventory - */ - public static int getHotbarSize() { - return 9; - } - - private int getInventorySlotContainItem(Item itemIn) { - for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemIn) { - return i; - } - } - - return -1; - } - - private int getInventorySlotContainItemAndDamage(Item itemIn, int parInt1) { - for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemIn - && this.mainInventory[i].getMetadata() == parInt1) { - return i; - } - } - - return -1; - } - - /**+ - * stores an itemstack in the users inventory - */ - private int storeItemStack(ItemStack itemStackIn) { - for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemStackIn.getItem() - && this.mainInventory[i].isStackable() - && this.mainInventory[i].stackSize < this.mainInventory[i].getMaxStackSize() - && this.mainInventory[i].stackSize < this.getInventoryStackLimit() - && (!this.mainInventory[i].getHasSubtypes() - || this.mainInventory[i].getMetadata() == itemStackIn.getMetadata()) - && ItemStack.areItemStackTagsEqual(this.mainInventory[i], itemStackIn)) { - return i; - } - } - - return -1; - } - - /**+ - * Returns the first item stack that is empty. - */ - public int getFirstEmptyStack() { - for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] == null) { - return i; - } - } - - return -1; - } - - public void setCurrentItem(Item itemIn, int parInt1, boolean parFlag, boolean parFlag2) { - ItemStack itemstack = this.getCurrentItem(); - int i = parFlag ? this.getInventorySlotContainItemAndDamage(itemIn, parInt1) - : this.getInventorySlotContainItem(itemIn); - if (i >= 0 && i < 9) { - this.currentItem = i; - } else if (parFlag2 && itemIn != null) { - int j = this.getFirstEmptyStack(); - if (j >= 0 && j < 9) { - this.currentItem = j; - } - - if (itemstack == null || !itemstack.isItemEnchantable() - || this.getInventorySlotContainItemAndDamage(itemstack.getItem(), - itemstack.getItemDamage()) != this.currentItem) { - int k = this.getInventorySlotContainItemAndDamage(itemIn, parInt1); - int l; - if (k >= 0) { - l = this.mainInventory[k].stackSize; - this.mainInventory[k] = this.mainInventory[this.currentItem]; + public boolean addItemStackToInventory(final ItemStack itemStackIn) { + if (itemStackIn != null && itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { + try { + if (itemStackIn.isItemDamaged()) { + int j = this.getFirstEmptyStack(); + if (j >= 0) { + this.mainInventory[j] = ItemStack.copyItemStack(itemStackIn); + this.mainInventory[j].animationsToGo = 5; + itemStackIn.stackSize = 0; + return true; + } else if (this.player.capabilities.isCreativeMode) { + itemStackIn.stackSize = 0; + return true; + } else { + return false; + } } else { - l = 1; + int i; + while (true) { + i = itemStackIn.stackSize; + itemStackIn.stackSize = this.storePartialItemStack(itemStackIn); + if (itemStackIn.stackSize <= 0 || itemStackIn.stackSize >= i) { + break; + } + } + + if (itemStackIn.stackSize == i && this.player.capabilities.isCreativeMode) { + itemStackIn.stackSize = 0; + return true; + } else { + return itemStackIn.stackSize < i; + } } - - this.mainInventory[this.currentItem] = new ItemStack(itemIn, l, parInt1); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Adding item to inventory"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Item being added"); + crashreportcategory.addCrashSection("Item ID", + Integer.valueOf(Item.getIdFromItem(itemStackIn.getItem()))); + crashreportcategory.addCrashSection("Item data", Integer.valueOf(itemStackIn.getMetadata())); + crashreportcategory.addCrashSectionCallable("Item name", new Callable() { + public String call() throws Exception { + return itemStackIn.getDisplayName(); + } + }); + throw new ReportedException(crashreport); } - + } else { + return false; } } - /**+ - * Switch the current item to the next one or the previous one + /** + * + returns a player armor item (as itemstack) contained in specified armor + * slot. + */ + public ItemStack armorItemInSlot(int parInt1) { + return this.armorInventory[parInt1]; + } + + public boolean canHeldItemHarvest(Block blockIn) { + if (blockIn.getMaterial().isToolNotRequired()) { + return true; + } else { + ItemStack itemstack = this.getStackInSlot(this.currentItem); + return itemstack != null ? itemstack.canHarvestBlock(blockIn) : false; + } + } + + /** + * + Switch the current item to the next one or the previous one */ public void changeCurrentItem(int parInt1) { if (parInt1 > 0) { @@ -176,14 +160,23 @@ public class InventoryPlayer implements IInventory { } - /**+ - * Removes matching items from the inventory.\n@param itemIn The - * item to match, null ignores.\n@param metadataIn The metadata - * to match, -1 ignores.\n@param removeCount The number of items - * to remove. If less than 1, removes all matching - * items.\n@param itemNBT The NBT data to match, null - * ignores.\n@return The number of items removed from the - * inventory. + public void clear() { + for (int i = 0; i < this.mainInventory.length; ++i) { + this.mainInventory[i] = null; + } + + for (int j = 0; j < this.armorInventory.length; ++j) { + this.armorInventory[j] = null; + } + + } + + /** + * + Removes matching items from the inventory.\n@param itemIn The item to + * match, null ignores.\n@param metadataIn The metadata to match, -1 + * ignores.\n@param removeCount The number of items to remove. If less than 1, + * removes all matching items.\n@param itemNBT The NBT data to match, null + * ignores.\n@return The number of items removed from the inventory. */ public int clearMatchingItems(Item itemIn, int metadataIn, int removeCount, NBTTagCompound itemNBT) { int i = 0; @@ -258,10 +251,431 @@ public class InventoryPlayer implements IInventory { return i; } - /**+ - * This function stores as many items of an ItemStack as - * possible in a matching slot and returns the quantity of left - * over items. + public void closeInventory(EntityPlayer var1) { + } + + /** + * + removed one item of specified Item from inventory (if it is in a stack, the + * stack size will reduce with 1) + */ + public boolean consumeInventoryItem(Item itemIn) { + int i = this.getInventorySlotContainItem(itemIn); + if (i < 0) { + return false; + } else { + if (--this.mainInventory[i].stackSize <= 0) { + this.mainInventory[i] = null; + } + + return true; + } + } + + /** + * + Copy the ItemStack contents from another InventoryPlayer instance + */ + public void copyInventory(InventoryPlayer playerInventory) { + for (int i = 0; i < this.mainInventory.length; ++i) { + this.mainInventory[i] = ItemStack.copyItemStack(playerInventory.mainInventory[i]); + } + + for (int j = 0; j < this.armorInventory.length; ++j) { + this.armorInventory[j] = ItemStack.copyItemStack(playerInventory.armorInventory[j]); + } + + this.currentItem = playerInventory.currentItem; + } + + /** + * + Damages armor in each slot by the specified amount. + */ + public void damageArmor(float damage) { + damage = damage / 4.0F; + if (damage < 1.0F) { + damage = 1.0F; + } + + for (int i = 0; i < this.armorInventory.length; ++i) { + if (this.armorInventory[i] != null && this.armorInventory[i].getItem() instanceof ItemArmor) { + this.armorInventory[i].damageItem((int) damage, this.player); + if (this.armorInventory[i].stackSize == 0) { + this.armorInventory[i] = null; + } + } + } + + } + + /** + * + Decrement the number of animations remaining. Only called on client side. + * This is used to handle the animation of receiving a block. + */ + public void decrementAnimations() { + for (int i = 0; i < this.mainInventory.length; ++i) { + if (this.mainInventory[i] != null) { + this.mainInventory[i].updateAnimation(this.player.worldObj, this.player, i, this.currentItem == i); + } + } + + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. + */ + public ItemStack decrStackSize(int i, int j) { + ItemStack[] aitemstack = this.mainInventory; + if (i >= this.mainInventory.length) { + aitemstack = this.armorInventory; + i -= this.mainInventory.length; + } + + if (aitemstack[i] != null) { + if (aitemstack[i].stackSize <= j) { + ItemStack itemstack1 = aitemstack[i]; + aitemstack[i] = null; + return itemstack1; + } else { + ItemStack itemstack = aitemstack[i].splitStack(j); + if (aitemstack[i].stackSize == 0) { + aitemstack[i] = null; + } + + return itemstack; + } + } else { + return null; + } + } + + /** + * + Drop all armor and main inventory items. + */ + public void dropAllItems() { + for (int i = 0; i < this.mainInventory.length; ++i) { + if (this.mainInventory[i] != null) { + this.player.dropItem(this.mainInventory[i], true, false); + this.mainInventory[i] = null; + } + } + + for (int j = 0; j < this.armorInventory.length; ++j) { + if (this.armorInventory[j] != null) { + this.player.dropItem(this.armorInventory[j], true, false); + this.armorInventory[j] = null; + } + } + + } + + /** + * + Returns the item stack currently held by the player. + */ + public ItemStack getCurrentItem() { + return this.currentItem < 9 && this.currentItem >= 0 ? this.mainInventory[this.currentItem] : null; + } + + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + /** + * + Returns the first item stack that is empty. + */ + public int getFirstEmptyStack() { + for (int i = 0; i < this.mainInventory.length; ++i) { + if (this.mainInventory[i] == null) { + return i; + } + } + + return -1; + } + + private int getInventorySlotContainItem(Item itemIn) { + for (int i = 0; i < this.mainInventory.length; ++i) { + if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemIn) { + return i; + } + } + + return -1; + } + + private int getInventorySlotContainItemAndDamage(Item itemIn, int parInt1) { + for (int i = 0; i < this.mainInventory.length; ++i) { + if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemIn + && this.mainInventory[i].getMetadata() == parInt1) { + return i; + } + } + + return -1; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Stack helds by mouse, used in GUI and Containers + */ + public ItemStack getItemStack() { + return this.itemStack; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return "container.inventory"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.mainInventory.length + 4; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + ItemStack[] aitemstack = this.mainInventory; + if (i >= aitemstack.length) { + i -= aitemstack.length; + aitemstack = this.armorInventory; + } + + return aitemstack[i]; + } + + public float getStrVsBlock(Block blockIn) { + float f = 1.0F; + if (this.mainInventory[this.currentItem] != null) { + f *= this.mainInventory[this.currentItem].getStrVsBlock(blockIn); + } + + return f; + } + + /** + * + Based on the damage values and maximum damage values of each armor item, + * returns the current armor value. + */ + public int getTotalArmorValue() { + int i = 0; + + for (int j = 0; j < this.armorInventory.length; ++j) { + if (this.armorInventory[j] != null && this.armorInventory[j].getItem() instanceof ItemArmor) { + int k = ((ItemArmor) this.armorInventory[j].getItem()).damageReduceAmount; + i += k; + } + } + + return i; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return false; + } + + /** + * + Checks if a specified Item is inside the inventory + */ + public boolean hasItem(Item itemIn) { + int i = this.getInventorySlotContainItem(itemIn); + return i >= 0; + } + + /** + * + Returns true if the specified ItemStack exists in the inventory. + */ + public boolean hasItemStack(ItemStack itemStackIn) { + for (int i = 0; i < this.armorInventory.length; ++i) { + if (this.armorInventory[i] != null && this.armorInventory[i].isItemEqual(itemStackIn)) { + return true; + } + } + + for (int j = 0; j < this.mainInventory.length; ++j) { + if (this.mainInventory[j] != null && this.mainInventory[j].isItemEqual(itemStackIn)) { + return true; + } + } + + return false; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.player.isDead ? false : entityplayer.getDistanceSqToEntity(this.player) <= 64.0D; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + this.inventoryChanged = true; + } + + public void openInventory(EntityPlayer var1) { + } + + /** + * + Reads from the given tag list and fills the slots in the inventory with the + * correct items. + */ + public void readFromNBT(NBTTagList parNBTTagList) { + this.mainInventory = new ItemStack[36]; + this.armorInventory = new ItemStack[4]; + + for (int i = 0; i < parNBTTagList.tagCount(); ++i) { + NBTTagCompound nbttagcompound = parNBTTagList.getCompoundTagAt(i); + int j = nbttagcompound.getByte("Slot") & 255; + ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); + if (itemstack != null) { + if (j >= 0 && j < this.mainInventory.length) { + this.mainInventory[j] = itemstack; + } + + if (j >= 100 && j < this.armorInventory.length + 100) { + this.armorInventory[j - 100] = itemstack; + } + } + } + + } + + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + ItemStack[] aitemstack = this.mainInventory; + if (i >= this.mainInventory.length) { + aitemstack = this.armorInventory; + i -= this.mainInventory.length; + } + + if (aitemstack[i] != null) { + ItemStack itemstack = aitemstack[i]; + aitemstack[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setCurrentItem(Item itemIn, int parInt1, boolean parFlag, boolean parFlag2) { + ItemStack itemstack = this.getCurrentItem(); + int i = parFlag ? this.getInventorySlotContainItemAndDamage(itemIn, parInt1) + : this.getInventorySlotContainItem(itemIn); + if (i >= 0 && i < 9) { + this.currentItem = i; + } else if (parFlag2 && itemIn != null) { + int j = this.getFirstEmptyStack(); + if (j >= 0 && j < 9) { + this.currentItem = j; + } + + if (itemstack == null || !itemstack.isItemEnchantable() + || this.getInventorySlotContainItemAndDamage(itemstack.getItem(), + itemstack.getItemDamage()) != this.currentItem) { + int k = this.getInventorySlotContainItemAndDamage(itemIn, parInt1); + int l; + if (k >= 0) { + l = this.mainInventory[k].stackSize; + this.mainInventory[k] = this.mainInventory[this.currentItem]; + } else { + l = 1; + } + + this.mainInventory[this.currentItem] = new ItemStack(itemIn, l, parInt1); + } + + } + } + + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + ItemStack[] aitemstack = this.mainInventory; + if (i >= aitemstack.length) { + i -= aitemstack.length; + aitemstack = this.armorInventory; + } + + aitemstack[i] = itemstack; + } + + /** + * + Set the stack helds by mouse, used in GUI/Container + */ + public void setItemStack(ItemStack itemStackIn) { + this.itemStack = itemStackIn; + } + + /** + * + stores an itemstack in the users inventory + */ + private int storeItemStack(ItemStack itemStackIn) { + for (int i = 0; i < this.mainInventory.length; ++i) { + if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemStackIn.getItem() + && this.mainInventory[i].isStackable() + && this.mainInventory[i].stackSize < this.mainInventory[i].getMaxStackSize() + && this.mainInventory[i].stackSize < this.getInventoryStackLimit() + && (!this.mainInventory[i].getHasSubtypes() + || this.mainInventory[i].getMetadata() == itemStackIn.getMetadata()) + && ItemStack.areItemStackTagsEqual(this.mainInventory[i], itemStackIn)) { + return i; + } + } + + return -1; + } + + /** + * + This function stores as many items of an ItemStack as possible in a + * matching slot and returns the quantity of left over items. */ private int storePartialItemStack(ItemStack itemStackIn) { Item item = itemStackIn.getItem(); @@ -301,175 +715,9 @@ public class InventoryPlayer implements IInventory { } } - /**+ - * Decrement the number of animations remaining. Only called on - * client side. This is used to handle the animation of - * receiving a block. - */ - public void decrementAnimations() { - for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null) { - this.mainInventory[i].updateAnimation(this.player.worldObj, this.player, i, this.currentItem == i); - } - } - - } - - /**+ - * removed one item of specified Item from inventory (if it is - * in a stack, the stack size will reduce with 1) - */ - public boolean consumeInventoryItem(Item itemIn) { - int i = this.getInventorySlotContainItem(itemIn); - if (i < 0) { - return false; - } else { - if (--this.mainInventory[i].stackSize <= 0) { - this.mainInventory[i] = null; - } - - return true; - } - } - - /**+ - * Checks if a specified Item is inside the inventory - */ - public boolean hasItem(Item itemIn) { - int i = this.getInventorySlotContainItem(itemIn); - return i >= 0; - } - - /**+ - * Adds the item stack to the inventory, returns false if it is - * impossible. - */ - public boolean addItemStackToInventory(final ItemStack itemStackIn) { - if (itemStackIn != null && itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) { - try { - if (itemStackIn.isItemDamaged()) { - int j = this.getFirstEmptyStack(); - if (j >= 0) { - this.mainInventory[j] = ItemStack.copyItemStack(itemStackIn); - this.mainInventory[j].animationsToGo = 5; - itemStackIn.stackSize = 0; - return true; - } else if (this.player.capabilities.isCreativeMode) { - itemStackIn.stackSize = 0; - return true; - } else { - return false; - } - } else { - int i; - while (true) { - i = itemStackIn.stackSize; - itemStackIn.stackSize = this.storePartialItemStack(itemStackIn); - if (itemStackIn.stackSize <= 0 || itemStackIn.stackSize >= i) { - break; - } - } - - if (itemStackIn.stackSize == i && this.player.capabilities.isCreativeMode) { - itemStackIn.stackSize = 0; - return true; - } else { - return itemStackIn.stackSize < i; - } - } - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Adding item to inventory"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Item being added"); - crashreportcategory.addCrashSection("Item ID", - Integer.valueOf(Item.getIdFromItem(itemStackIn.getItem()))); - crashreportcategory.addCrashSection("Item data", Integer.valueOf(itemStackIn.getMetadata())); - crashreportcategory.addCrashSectionCallable("Item name", new Callable() { - public String call() throws Exception { - return itemStackIn.getDisplayName(); - } - }); - throw new ReportedException(crashreport); - } - } else { - return false; - } - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. - */ - public ItemStack decrStackSize(int i, int j) { - ItemStack[] aitemstack = this.mainInventory; - if (i >= this.mainInventory.length) { - aitemstack = this.armorInventory; - i -= this.mainInventory.length; - } - - if (aitemstack[i] != null) { - if (aitemstack[i].stackSize <= j) { - ItemStack itemstack1 = aitemstack[i]; - aitemstack[i] = null; - return itemstack1; - } else { - ItemStack itemstack = aitemstack[i].splitStack(j); - if (aitemstack[i].stackSize == 0) { - aitemstack[i] = null; - } - - return itemstack; - } - } else { - return null; - } - } - - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - ItemStack[] aitemstack = this.mainInventory; - if (i >= this.mainInventory.length) { - aitemstack = this.armorInventory; - i -= this.mainInventory.length; - } - - if (aitemstack[i] != null) { - ItemStack itemstack = aitemstack[i]; - aitemstack[i] = null; - return itemstack; - } else { - return null; - } - } - - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - ItemStack[] aitemstack = this.mainInventory; - if (i >= aitemstack.length) { - i -= aitemstack.length; - aitemstack = this.armorInventory; - } - - aitemstack[i] = itemstack; - } - - public float getStrVsBlock(Block blockIn) { - float f = 1.0F; - if (this.mainInventory[this.currentItem] != null) { - f *= this.mainInventory[this.currentItem].getStrVsBlock(blockIn); - } - - return f; - } - - /**+ - * Writes the inventory out as a list of compound tags. This is - * where the slot indices are used (+100 for armor, +80 for - * crafting). + /** + * + Writes the inventory out as a list of compound tags. This is where the slot + * indices are used (+100 for armor, +80 for crafting). */ public NBTTagList writeToNBT(NBTTagList parNBTTagList) { for (int i = 0; i < this.mainInventory.length; ++i) { @@ -492,258 +740,4 @@ public class InventoryPlayer implements IInventory { return parNBTTagList; } - - /**+ - * Reads from the given tag list and fills the slots in the - * inventory with the correct items. - */ - public void readFromNBT(NBTTagList parNBTTagList) { - this.mainInventory = new ItemStack[36]; - this.armorInventory = new ItemStack[4]; - - for (int i = 0; i < parNBTTagList.tagCount(); ++i) { - NBTTagCompound nbttagcompound = parNBTTagList.getCompoundTagAt(i); - int j = nbttagcompound.getByte("Slot") & 255; - ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); - if (itemstack != null) { - if (j >= 0 && j < this.mainInventory.length) { - this.mainInventory[j] = itemstack; - } - - if (j >= 100 && j < this.armorInventory.length + 100) { - this.armorInventory[j - 100] = itemstack; - } - } - } - - } - - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return this.mainInventory.length + 4; - } - - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - ItemStack[] aitemstack = this.mainInventory; - if (i >= aitemstack.length) { - i -= aitemstack.length; - aitemstack = this.armorInventory; - } - - return aitemstack[i]; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return "container.inventory"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return false; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - public boolean canHeldItemHarvest(Block blockIn) { - if (blockIn.getMaterial().isToolNotRequired()) { - return true; - } else { - ItemStack itemstack = this.getStackInSlot(this.currentItem); - return itemstack != null ? itemstack.canHarvestBlock(blockIn) : false; - } - } - - /**+ - * returns a player armor item (as itemstack) contained in - * specified armor slot. - */ - public ItemStack armorItemInSlot(int parInt1) { - return this.armorInventory[parInt1]; - } - - /**+ - * Based on the damage values and maximum damage values of each - * armor item, returns the current armor value. - */ - public int getTotalArmorValue() { - int i = 0; - - for (int j = 0; j < this.armorInventory.length; ++j) { - if (this.armorInventory[j] != null && this.armorInventory[j].getItem() instanceof ItemArmor) { - int k = ((ItemArmor) this.armorInventory[j].getItem()).damageReduceAmount; - i += k; - } - } - - return i; - } - - /**+ - * Damages armor in each slot by the specified amount. - */ - public void damageArmor(float damage) { - damage = damage / 4.0F; - if (damage < 1.0F) { - damage = 1.0F; - } - - for (int i = 0; i < this.armorInventory.length; ++i) { - if (this.armorInventory[i] != null && this.armorInventory[i].getItem() instanceof ItemArmor) { - this.armorInventory[i].damageItem((int) damage, this.player); - if (this.armorInventory[i].stackSize == 0) { - this.armorInventory[i] = null; - } - } - } - - } - - /**+ - * Drop all armor and main inventory items. - */ - public void dropAllItems() { - for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null) { - this.player.dropItem(this.mainInventory[i], true, false); - this.mainInventory[i] = null; - } - } - - for (int j = 0; j < this.armorInventory.length; ++j) { - if (this.armorInventory[j] != null) { - this.player.dropItem(this.armorInventory[j], true, false); - this.armorInventory[j] = null; - } - } - - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - this.inventoryChanged = true; - } - - /**+ - * Set the stack helds by mouse, used in GUI/Container - */ - public void setItemStack(ItemStack itemStackIn) { - this.itemStack = itemStackIn; - } - - /**+ - * Stack helds by mouse, used in GUI and Containers - */ - public ItemStack getItemStack() { - return this.itemStack; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.player.isDead ? false : entityplayer.getDistanceSqToEntity(this.player) <= 64.0D; - } - - /**+ - * Returns true if the specified ItemStack exists in the - * inventory. - */ - public boolean hasItemStack(ItemStack itemStackIn) { - for (int i = 0; i < this.armorInventory.length; ++i) { - if (this.armorInventory[i] != null && this.armorInventory[i].isItemEqual(itemStackIn)) { - return true; - } - } - - for (int j = 0; j < this.mainInventory.length; ++j) { - if (this.mainInventory[j] != null && this.mainInventory[j].isItemEqual(itemStackIn)) { - return true; - } - } - - return false; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - /**+ - * Copy the ItemStack contents from another InventoryPlayer - * instance - */ - public void copyInventory(InventoryPlayer playerInventory) { - for (int i = 0; i < this.mainInventory.length; ++i) { - this.mainInventory[i] = ItemStack.copyItemStack(playerInventory.mainInventory[i]); - } - - for (int j = 0; j < this.armorInventory.length; ++j) { - this.armorInventory[j] = ItemStack.copyItemStack(playerInventory.armorInventory[j]); - } - - this.currentItem = playerInventory.currentItem; - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } - - public void clear() { - for (int i = 0; i < this.mainInventory.length; ++i) { - this.mainInventory[i] = null; - } - - for (int j = 0; j < this.armorInventory.length; ++j) { - this.armorInventory[j] = null; - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/player/PlayerCapabilities.java b/src/game/java/net/minecraft/entity/player/PlayerCapabilities.java index 0a3ab2f9..0c7dd064 100644 --- a/src/game/java/net/minecraft/entity/player/PlayerCapabilities.java +++ b/src/game/java/net/minecraft/entity/player/PlayerCapabilities.java @@ -2,22 +2,25 @@ package net.minecraft.entity.player; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,24 +30,19 @@ public class PlayerCapabilities { public boolean isFlying; public boolean allowFlying; public boolean isCreativeMode; - /**+ - * Indicates whether the player is allowed to modify the - * surroundings + /** + * + Indicates whether the player is allowed to modify the surroundings */ public boolean allowEdit = true; private float flySpeed = 0.05F; private float walkSpeed = 0.1F; - public void writeCapabilitiesToNBT(NBTTagCompound tagCompound) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setBoolean("invulnerable", this.disableDamage); - nbttagcompound.setBoolean("flying", this.isFlying); - nbttagcompound.setBoolean("mayfly", this.allowFlying); - nbttagcompound.setBoolean("instabuild", this.isCreativeMode); - nbttagcompound.setBoolean("mayBuild", this.allowEdit); - nbttagcompound.setFloat("flySpeed", this.flySpeed); - nbttagcompound.setFloat("walkSpeed", this.walkSpeed); - tagCompound.setTag("abilities", nbttagcompound); + public float getFlySpeed() { + return this.flySpeed; + } + + public float getWalkSpeed() { + return this.walkSpeed; } public void readCapabilitiesFromNBT(NBTTagCompound tagCompound) { @@ -66,19 +64,23 @@ public class PlayerCapabilities { } - public float getFlySpeed() { - return this.flySpeed; - } - public void setFlySpeed(float speed) { this.flySpeed = speed; } - public float getWalkSpeed() { - return this.walkSpeed; - } - public void setPlayerWalkSpeed(float speed) { this.walkSpeed = speed; } + + public void writeCapabilitiesToNBT(NBTTagCompound tagCompound) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setBoolean("invulnerable", this.disableDamage); + nbttagcompound.setBoolean("flying", this.isFlying); + nbttagcompound.setBoolean("mayfly", this.allowFlying); + nbttagcompound.setBoolean("instabuild", this.isCreativeMode); + nbttagcompound.setBoolean("mayBuild", this.allowEdit); + nbttagcompound.setFloat("flySpeed", this.flySpeed); + nbttagcompound.setFloat("walkSpeed", this.walkSpeed); + tagCompound.setTag("abilities", nbttagcompound); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntityArrow.java b/src/game/java/net/minecraft/entity/projectile/EntityArrow.java index 344701f5..155d3469 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityArrow.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityArrow.java @@ -1,6 +1,7 @@ package net.minecraft.entity.projectile; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -25,22 +26,25 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,6 +64,8 @@ public class EntityArrow extends Entity implements IProjectile { private double damage = 2.0D; private int knockbackStrength; + public boolean isChair = false; + public EntityArrow(World worldIn) { super(worldIn); this.renderDistanceWeight = 10.0D; @@ -122,69 +128,65 @@ public class EntityArrow extends Entity implements IProjectile { this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, velocity * 1.5F, 1.0F); } + /** + * + If returns false, the item will not inflict any damage against entities. + */ + public boolean canAttackWithItem() { + return false; + } + + /** + * + returns if this entity triggers Block.onEntityWalking on the blocks they + * walk on. used for spiders and wolves to prevent them from trampling crops + */ + protected boolean canTriggerWalking() { + return false; + } + protected void entityInit() { this.dataWatcher.addObject(16, Byte.valueOf((byte) 0)); } - /**+ - * Similar to setArrowHeading, it's point the throwable entity - * to a x, y, z direction. - */ - public void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy) { - float f = MathHelper.sqrt_double(x * x + y * y + z * z); - x = x / (double) f; - y = y / (double) f; - z = z / (double) f; - x = x + this.rand.nextGaussian() * (double) (this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D - * (double) inaccuracy; - y = y + this.rand.nextGaussian() * (double) (this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D - * (double) inaccuracy; - z = z + this.rand.nextGaussian() * (double) (this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D - * (double) inaccuracy; - x = x * (double) velocity; - y = y * (double) velocity; - z = z * (double) velocity; - this.motionX = x; - this.motionY = y; - this.motionZ = z; - float f1 = MathHelper.sqrt_double(x * x + z * z); - this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(x, z) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(y, (double) f1) * 180.0D - / 3.1415927410125732D); - this.ticksInGround = 0; + public double getDamage() { + return this.damage; } - public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int var9, boolean var10) { - this.setPosition(d0, d1, d2); - this.setRotation(f, f1); + public float getEyeHeight() { + return 0.0F; } - /**+ - * Sets the velocity to the args. Args: x, y, z + /** + * + Whether the arrow has a stream of critical hit particles flying behind it. */ - public void setVelocity(double d0, double d1, double d2) { - this.motionX = d0; - this.motionY = d1; - this.motionZ = d2; - if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { - float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); - this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch; - this.prevRotationYaw = this.rotationYaw; - this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); - this.ticksInGround = 0; + public boolean getIsCritical() { + byte b0 = this.dataWatcher.getWatchableObjectByte(16); + return (b0 & 1) != 0; + } + + /** + * + Called by a player entity when they collide with an entity + */ + public void onCollideWithPlayer(EntityPlayer entityplayer) { + if (!this.worldObj.isRemote && this.inGround && this.arrowShake <= 0) { + boolean flag = this.canBePickedUp == 1 + || this.canBePickedUp == 2 && entityplayer.capabilities.isCreativeMode; + if (this.canBePickedUp == 1 + && !entityplayer.inventory.addItemStackToInventory(new ItemStack(Items.arrow, 1))) { + flag = false; + } + + if (flag) { + this.playSound("random.pop", 0.2F, + ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); + entityplayer.onItemPickup(this, 1); + this.setDead(); + } + } - } - public boolean isChair = false; - - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -433,27 +435,8 @@ public class EntityArrow extends Entity implements IProjectile { } } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("xTile", (short) this.xTile); - nbttagcompound.setShort("yTile", (short) this.yTile); - nbttagcompound.setShort("zTile", (short) this.zTile); - nbttagcompound.setShort("life", (short) this.ticksInGround); - ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); - nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound.setByte("inData", (byte) this.inData); - nbttagcompound.setByte("shake", (byte) this.arrowShake); - nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); - nbttagcompound.setByte("pickup", (byte) this.canBePickedUp); - nbttagcompound.setDouble("damage", this.damage); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.xTile = nbttagcompound.getShort("xTile"); @@ -481,68 +464,12 @@ public class EntityArrow extends Entity implements IProjectile { } - /**+ - * Called by a player entity when they collide with an entity - */ - public void onCollideWithPlayer(EntityPlayer entityplayer) { - if (!this.worldObj.isRemote && this.inGround && this.arrowShake <= 0) { - boolean flag = this.canBePickedUp == 1 - || this.canBePickedUp == 2 && entityplayer.capabilities.isCreativeMode; - if (this.canBePickedUp == 1 - && !entityplayer.inventory.addItemStackToInventory(new ItemStack(Items.arrow, 1))) { - flag = false; - } - - if (flag) { - this.playSound("random.pop", 0.2F, - ((this.rand.nextFloat() - this.rand.nextFloat()) * 0.7F + 1.0F) * 2.0F); - entityplayer.onItemPickup(this, 1); - this.setDead(); - } - - } - } - - /**+ - * returns if this entity triggers Block.onEntityWalking on the - * blocks they walk on. used for spiders and wolves to prevent - * them from trampling crops - */ - protected boolean canTriggerWalking() { - return false; - } - public void setDamage(double damageIn) { this.damage = damageIn; } - public double getDamage() { - return this.damage; - } - - /**+ - * Sets the amount of knockback the arrow applies when it hits a - * mob. - */ - public void setKnockbackStrength(int knockbackStrengthIn) { - this.knockbackStrength = knockbackStrengthIn; - } - - /**+ - * If returns false, the item will not inflict any damage - * against entities. - */ - public boolean canAttackWithItem() { - return false; - } - - public float getEyeHeight() { - return 0.0F; - } - - /**+ - * Whether the arrow has a stream of critical hit particles - * flying behind it. + /** + * + Whether the arrow has a stream of critical hit particles flying behind it. */ public void setIsCritical(boolean critical) { byte b0 = this.dataWatcher.getWatchableObjectByte(16); @@ -554,12 +481,82 @@ public class EntityArrow extends Entity implements IProjectile { } - /**+ - * Whether the arrow has a stream of critical hit particles - * flying behind it. + /** + * + Sets the amount of knockback the arrow applies when it hits a mob. */ - public boolean getIsCritical() { - byte b0 = this.dataWatcher.getWatchableObjectByte(16); - return (b0 & 1) != 0; + public void setKnockbackStrength(int knockbackStrengthIn) { + this.knockbackStrength = knockbackStrengthIn; + } + + public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int var9, boolean var10) { + this.setPosition(d0, d1, d2); + this.setRotation(f, f1); + } + + /** + * + Similar to setArrowHeading, it's point the throwable entity to a x, y, z + * direction. + */ + public void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy) { + float f = MathHelper.sqrt_double(x * x + y * y + z * z); + x = x / (double) f; + y = y / (double) f; + z = z / (double) f; + x = x + this.rand.nextGaussian() * (double) (this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D + * (double) inaccuracy; + y = y + this.rand.nextGaussian() * (double) (this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D + * (double) inaccuracy; + z = z + this.rand.nextGaussian() * (double) (this.rand.nextBoolean() ? -1 : 1) * 0.007499999832361937D + * (double) inaccuracy; + x = x * (double) velocity; + y = y * (double) velocity; + z = z * (double) velocity; + this.motionX = x; + this.motionY = y; + this.motionZ = z; + float f1 = MathHelper.sqrt_double(x * x + z * z); + this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(x, z) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(y, (double) f1) * 180.0D + / 3.1415927410125732D); + this.ticksInGround = 0; + } + + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double d0, double d1, double d2) { + this.motionX = d0; + this.motionY = d1; + this.motionZ = d2; + if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { + float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); + this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch; + this.prevRotationYaw = this.rotationYaw; + this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, this.rotationPitch); + this.ticksInGround = 0; + } + + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.xTile); + nbttagcompound.setShort("yTile", (short) this.yTile); + nbttagcompound.setShort("zTile", (short) this.zTile); + nbttagcompound.setShort("life", (short) this.ticksInGround); + ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); + nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound.setByte("inData", (byte) this.inData); + nbttagcompound.setByte("shake", (byte) this.arrowShake); + nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); + nbttagcompound.setByte("pickup", (byte) this.canBePickedUp); + nbttagcompound.setDouble("damage", this.damage); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntityEgg.java b/src/game/java/net/minecraft/entity/projectile/EntityEgg.java index 8b554f21..66e3853c 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityEgg.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityEgg.java @@ -9,22 +9,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,16 +37,16 @@ public class EntityEgg extends EntityThrowable { super(worldIn); } - public EntityEgg(World worldIn, EntityLivingBase throwerIn) { - super(worldIn, throwerIn); - } - public EntityEgg(World worldIn, double x, double y, double z) { super(worldIn, x, y, z); } - /**+ - * Called when this EntityThrowable hits a block or entity. + public EntityEgg(World worldIn, EntityLivingBase throwerIn) { + super(worldIn, throwerIn); + } + + /** + * + Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { if (movingobjectposition.entityHit != null) { diff --git a/src/game/java/net/minecraft/entity/projectile/EntityFireball.java b/src/game/java/net/minecraft/entity/projectile/EntityFireball.java index 34ea7ffe..5af55a30 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityFireball.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityFireball.java @@ -17,22 +17,25 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,24 +58,6 @@ public abstract class EntityFireball extends Entity { this.setSize(1.0F, 1.0F); } - protected void entityInit() { - } - - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double d0) { - double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; - if (Double.isNaN(d1)) { - d1 = 4.0D; - } - - d1 = d1 * 64.0D; - return d0 < d1 * d1; - } - public EntityFireball(World worldIn, double x, double y, double z, double accelX, double accelY, double accelZ) { super(worldIn); this.setSize(1.0F, 1.0F); @@ -108,8 +93,93 @@ public abstract class EntityFireball extends Entity { this.accelerationZ = accelZ / d0 * 0.1D; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource damagesource, float var2) { + if (this.isEntityInvulnerable(damagesource)) { + return false; + } else { + this.setBeenAttacked(); + if (damagesource.getEntity() != null) { + Vec3 vec3 = damagesource.getEntity().getLookVec(); + if (vec3 != null) { + this.motionX = vec3.xCoord; + this.motionY = vec3.yCoord; + this.motionZ = vec3.zCoord; + this.accelerationX = this.motionX * 0.1D; + this.accelerationY = this.motionY * 0.1D; + this.accelerationZ = this.motionZ * 0.1D; + } + + if (damagesource.getEntity() instanceof EntityLivingBase) { + this.shootingEntity = (EntityLivingBase) damagesource.getEntity(); + } + + return true; + } else { + return false; + } + } + } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return true; + } + + protected void entityInit() { + } + + /** + * + Gets how bright this entity is. + */ + public float getBrightness(float var1) { + return 1.0F; + } + + public int getBrightnessForRender(float var1) { + return 15728880; + } + + public float getCollisionBorderSize() { + return 1.0F; + } + + protected float getEaglerDynamicLightsValueSimple(float partialTicks) { + return 1.0f; + } + + /** + * + Return the motion factor for this projectile. The factor is multiplied by + * the original motion. + */ + protected float getMotionFactor() { + return 0.95F; + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance + */ + public boolean isInRangeToRenderDist(double d0) { + double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; + if (Double.isNaN(d1)) { + d1 = 4.0D; + } + + d1 = d1 * 64.0D; + return d0 < d1 * d1; + } + + protected abstract void onImpact(MovingObjectPosition var1); + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { if (this.worldObj.isRemote || (this.shootingEntity == null || !this.shootingEntity.isDead) @@ -231,34 +301,8 @@ public abstract class EntityFireball extends Entity { } } - /**+ - * Return the motion factor for this projectile. The factor is - * multiplied by the original motion. - */ - protected float getMotionFactor() { - return 0.95F; - } - - protected abstract void onImpact(MovingObjectPosition var1); - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("xTile", (short) this.xTile); - nbttagcompound.setShort("yTile", (short) this.yTile); - nbttagcompound.setShort("zTile", (short) this.zTile); - ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); - nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); - nbttagcompound.setTag("direction", - this.newDoubleNBTList(new double[] { this.motionX, this.motionY, this.motionZ })); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.xTile = nbttagcompound.getShort("xTile"); @@ -282,60 +326,17 @@ public abstract class EntityFireball extends Entity { } - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ - public boolean canBeCollidedWith() { - return true; - } - - public float getCollisionBorderSize() { - return 1.0F; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource damagesource, float var2) { - if (this.isEntityInvulnerable(damagesource)) { - return false; - } else { - this.setBeenAttacked(); - if (damagesource.getEntity() != null) { - Vec3 vec3 = damagesource.getEntity().getLookVec(); - if (vec3 != null) { - this.motionX = vec3.xCoord; - this.motionY = vec3.yCoord; - this.motionZ = vec3.zCoord; - this.accelerationX = this.motionX * 0.1D; - this.accelerationY = this.motionY * 0.1D; - this.accelerationZ = this.motionZ * 0.1D; - } - - if (damagesource.getEntity() instanceof EntityLivingBase) { - this.shootingEntity = (EntityLivingBase) damagesource.getEntity(); - } - - return true; - } else { - return false; - } - } - } - - /**+ - * Gets how bright this entity is. - */ - public float getBrightness(float var1) { - return 1.0F; - } - - protected float getEaglerDynamicLightsValueSimple(float partialTicks) { - return 1.0f; - } - - public int getBrightnessForRender(float var1) { - return 15728880; + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.xTile); + nbttagcompound.setShort("yTile", (short) this.yTile); + nbttagcompound.setShort("zTile", (short) this.zTile); + ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); + nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); + nbttagcompound.setTag("direction", + this.newDoubleNBTList(new double[] { this.motionX, this.motionY, this.motionZ })); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntityFishHook.java b/src/game/java/net/minecraft/entity/projectile/EntityFishHook.java index 5aaf9590..e3fe984f 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityFishHook.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityFishHook.java @@ -2,6 +2,7 @@ package net.minecraft.entity.projectile; import java.util.Arrays; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.enchantment.EnchantmentHelper; @@ -29,22 +30,25 @@ import net.minecraft.util.WeightedRandomFishable; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -76,6 +80,11 @@ public class EntityFishHook extends Entity { new WeightedRandomFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.CLOWNFISH.getMetadata()), 2), new WeightedRandomFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.PUFFERFISH.getMetadata()), 13) }); + + public static List func_174855_j() { + return FISH; + } + private int xTile; private int yTile; private int zTile; @@ -98,11 +107,8 @@ public class EntityFishHook extends Entity { private double fishPitch; private double clientMotionX; private double clientMotionY; - private double clientMotionZ; - public static List func_174855_j() { - return FISH; - } + private double clientMotionZ; public EntityFishHook(World worldIn) { super(worldIn); @@ -148,19 +154,29 @@ public class EntityFishHook extends Entity { protected void entityInit() { } - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double d0) { - double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; - if (Double.isNaN(d1)) { - d1 = 4.0D; + private ItemStack getFishingResult() { + float f = this.worldObj.rand.nextFloat(); + int i = EnchantmentHelper.getLuckOfSeaModifier(this.angler); + int j = EnchantmentHelper.getLureModifier(this.angler); + float f1 = 0.1F - (float) i * 0.025F - (float) j * 0.01F; + float f2 = 0.05F + (float) i * 0.01F - (float) j * 0.01F; + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + f2 = MathHelper.clamp_float(f2, 0.0F, 1.0F); + if (f < f1) { + this.angler.triggerAchievement(StatList.junkFishedStat); + return ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, JUNK)).getItemStack(this.rand); + } else { + f = f - f1; + if (f < f2) { + this.angler.triggerAchievement(StatList.treasureFishedStat); + return ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, TREASURE)) + .getItemStack(this.rand); + } else { + float f3 = f - f2; + this.angler.triggerAchievement(StatList.fishCaughtStat); + return ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, FISH)).getItemStack(this.rand); + } } - - d1 = d1 * 64.0D; - return d0 < d1 * d1; } public void handleHookCasting(double parDouble1, double parDouble2, double parDouble3, float parFloat1, @@ -186,29 +202,65 @@ public class EntityFishHook extends Entity { this.ticksInGround = 0; } - public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean var10) { - this.fishX = d0; - this.fishY = d1; - this.fishZ = d2; - this.fishYaw = (double) f; - this.fishPitch = (double) f1; - this.fishPosRotationIncrements = i; - this.motionX = this.clientMotionX; - this.motionY = this.clientMotionY; - this.motionZ = this.clientMotionZ; + public int handleHookRetraction() { + if (this.worldObj.isRemote) { + return 0; + } else { + byte b0 = 0; + if (this.caughtEntity != null) { + double d0 = this.angler.posX - this.posX; + double d2 = this.angler.posY - this.posY; + double d4 = this.angler.posZ - this.posZ; + double d6 = (double) MathHelper.sqrt_double(d0 * d0 + d2 * d2 + d4 * d4); + double d8 = 0.1D; + this.caughtEntity.motionX += d0 * d8; + this.caughtEntity.motionY += d2 * d8 + (double) MathHelper.sqrt_double(d6) * 0.08D; + this.caughtEntity.motionZ += d4 * d8; + b0 = 3; + } else if (this.ticksCatchable > 0) { + EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY, this.posZ, + this.getFishingResult()); + double d1 = this.angler.posX - this.posX; + double d3 = this.angler.posY - this.posY; + double d5 = this.angler.posZ - this.posZ; + double d7 = (double) MathHelper.sqrt_double(d1 * d1 + d3 * d3 + d5 * d5); + double d9 = 0.1D; + entityitem.motionX = d1 * d9; + entityitem.motionY = d3 * d9 + (double) MathHelper.sqrt_double(d7) * 0.08D; + entityitem.motionZ = d5 * d9; + this.worldObj.spawnEntityInWorld(entityitem); + this.angler.worldObj.spawnEntityInWorld(new EntityXPOrb(this.angler.worldObj, this.angler.posX, + this.angler.posY + 0.5D, this.angler.posZ + 0.5D, this.rand.nextInt(6) + 1)); + b0 = 1; + } + + if (this.inGround) { + b0 = 2; + } + + this.setDead(); + this.angler.fishEntity = null; + return b0; + } } - /**+ - * Sets the velocity to the args. Args: x, y, z + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance */ - public void setVelocity(double d0, double d1, double d2) { - this.clientMotionX = this.motionX = d0; - this.clientMotionY = this.motionY = d1; - this.clientMotionZ = this.motionZ = d2; + public boolean isInRangeToRenderDist(double d0) { + double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; + if (Double.isNaN(d1)) { + d1 = 4.0D; + } + + d1 = d1 * 64.0D; + return d0 < d1 * d1; } - /**+ - * Called to update the entity's position/logic. + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); @@ -481,23 +533,8 @@ public class EntityFishHook extends Entity { } } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("xTile", (short) this.xTile); - nbttagcompound.setShort("yTile", (short) this.yTile); - nbttagcompound.setShort("zTile", (short) this.zTile); - ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); - nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound.setByte("shake", (byte) this.shake); - nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.xTile = nbttagcompound.getShort("xTile"); @@ -513,75 +550,8 @@ public class EntityFishHook extends Entity { this.inGround = nbttagcompound.getByte("inGround") == 1; } - public int handleHookRetraction() { - if (this.worldObj.isRemote) { - return 0; - } else { - byte b0 = 0; - if (this.caughtEntity != null) { - double d0 = this.angler.posX - this.posX; - double d2 = this.angler.posY - this.posY; - double d4 = this.angler.posZ - this.posZ; - double d6 = (double) MathHelper.sqrt_double(d0 * d0 + d2 * d2 + d4 * d4); - double d8 = 0.1D; - this.caughtEntity.motionX += d0 * d8; - this.caughtEntity.motionY += d2 * d8 + (double) MathHelper.sqrt_double(d6) * 0.08D; - this.caughtEntity.motionZ += d4 * d8; - b0 = 3; - } else if (this.ticksCatchable > 0) { - EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY, this.posZ, - this.getFishingResult()); - double d1 = this.angler.posX - this.posX; - double d3 = this.angler.posY - this.posY; - double d5 = this.angler.posZ - this.posZ; - double d7 = (double) MathHelper.sqrt_double(d1 * d1 + d3 * d3 + d5 * d5); - double d9 = 0.1D; - entityitem.motionX = d1 * d9; - entityitem.motionY = d3 * d9 + (double) MathHelper.sqrt_double(d7) * 0.08D; - entityitem.motionZ = d5 * d9; - this.worldObj.spawnEntityInWorld(entityitem); - this.angler.worldObj.spawnEntityInWorld(new EntityXPOrb(this.angler.worldObj, this.angler.posX, - this.angler.posY + 0.5D, this.angler.posZ + 0.5D, this.rand.nextInt(6) + 1)); - b0 = 1; - } - - if (this.inGround) { - b0 = 2; - } - - this.setDead(); - this.angler.fishEntity = null; - return b0; - } - } - - private ItemStack getFishingResult() { - float f = this.worldObj.rand.nextFloat(); - int i = EnchantmentHelper.getLuckOfSeaModifier(this.angler); - int j = EnchantmentHelper.getLureModifier(this.angler); - float f1 = 0.1F - (float) i * 0.025F - (float) j * 0.01F; - float f2 = 0.05F + (float) i * 0.01F - (float) j * 0.01F; - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - f2 = MathHelper.clamp_float(f2, 0.0F, 1.0F); - if (f < f1) { - this.angler.triggerAchievement(StatList.junkFishedStat); - return ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, JUNK)).getItemStack(this.rand); - } else { - f = f - f1; - if (f < f2) { - this.angler.triggerAchievement(StatList.treasureFishedStat); - return ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, TREASURE)) - .getItemStack(this.rand); - } else { - float f3 = f - f2; - this.angler.triggerAchievement(StatList.fishCaughtStat); - return ((WeightedRandomFishable) WeightedRandom.getRandomItem(this.rand, FISH)).getItemStack(this.rand); - } - } - } - - /**+ - * Will get destroyed next tick. + /** + * + Will get destroyed next tick. */ public void setDead() { super.setDead(); @@ -590,4 +560,38 @@ public class EntityFishHook extends Entity { } } + + public void setPositionAndRotation2(double d0, double d1, double d2, float f, float f1, int i, boolean var10) { + this.fishX = d0; + this.fishY = d1; + this.fishZ = d2; + this.fishYaw = (double) f; + this.fishPitch = (double) f1; + this.fishPosRotationIncrements = i; + this.motionX = this.clientMotionX; + this.motionY = this.clientMotionY; + this.motionZ = this.clientMotionZ; + } + + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double d0, double d1, double d2) { + this.clientMotionX = this.motionX = d0; + this.clientMotionY = this.motionY = d1; + this.clientMotionZ = this.motionZ = d2; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.xTile); + nbttagcompound.setShort("yTile", (short) this.yTile); + nbttagcompound.setShort("zTile", (short) this.zTile); + ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); + nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound.setByte("shake", (byte) this.shake); + nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntityLargeFireball.java b/src/game/java/net/minecraft/entity/projectile/EntityLargeFireball.java index 64662141..64aa2721 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityLargeFireball.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityLargeFireball.java @@ -7,22 +7,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,8 +46,8 @@ public class EntityLargeFireball extends EntityFireball { super(worldIn, shooter, accelX, accelY, accelZ); } - /**+ - * Called when this EntityFireball hits a block or entity. + /** + * + Called when this EntityFireball hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { if (!this.worldObj.isRemote) { @@ -62,18 +65,8 @@ public class EntityLargeFireball extends EntityFireball { } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - super.writeEntityToNBT(nbttagcompound); - nbttagcompound.setInteger("ExplosionPower", this.explosionPower); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -82,4 +75,12 @@ public class EntityLargeFireball extends EntityFireball { } } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + super.writeEntityToNBT(nbttagcompound); + nbttagcompound.setInteger("ExplosionPower", this.explosionPower); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntityPotion.java b/src/game/java/net/minecraft/entity/projectile/EntityPotion.java index d36b1663..f722def0 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityPotion.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityPotion.java @@ -1,6 +1,7 @@ package net.minecraft.entity.projectile; import java.util.List; + import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; @@ -12,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,15 +43,6 @@ public class EntityPotion extends EntityThrowable { super(worldIn); } - public EntityPotion(World worldIn, EntityLivingBase throwerIn, int meta) { - this(worldIn, throwerIn, new ItemStack(Items.potionitem, 1, meta)); - } - - public EntityPotion(World worldIn, EntityLivingBase throwerIn, ItemStack potionDamageIn) { - super(worldIn, throwerIn); - this.potionDamage = potionDamageIn; - } - public EntityPotion(World worldIn, double x, double y, double z, int parInt1) { this(worldIn, x, y, z, new ItemStack(Items.potionitem, 1, parInt1)); } @@ -57,36 +52,29 @@ public class EntityPotion extends EntityThrowable { this.potionDamage = potionDamageIn; } - /**+ - * Gets the amount of gravity to apply to the thrown entity with - * each tick. + public EntityPotion(World worldIn, EntityLivingBase throwerIn, int meta) { + this(worldIn, throwerIn, new ItemStack(Items.potionitem, 1, meta)); + } + + public EntityPotion(World worldIn, EntityLivingBase throwerIn, ItemStack potionDamageIn) { + super(worldIn, throwerIn); + this.potionDamage = potionDamageIn; + } + + /** + * + Gets the amount of gravity to apply to the thrown entity with each tick. */ protected float getGravityVelocity() { return 0.05F; } - protected float getVelocity() { - return 0.5F; - } - protected float getInaccuracy() { return -20.0F; } - /**+ - * Sets the PotionEffect by the given id of the potion effect. - */ - public void setPotionDamage(int potionId) { - if (this.potionDamage == null) { - this.potionDamage = new ItemStack(Items.potionitem, 1, 0); - } - - this.potionDamage.setItemDamage(potionId); - } - - /**+ - * Returns the damage value of the thrown potion that this - * EntityPotion represents. + /** + * + Returns the damage value of the thrown potion that this EntityPotion + * represents. */ public int getPotionDamage() { if (this.potionDamage == null) { @@ -96,8 +84,12 @@ public class EntityPotion extends EntityThrowable { return this.potionDamage.getMetadata(); } - /**+ - * Called when this EntityThrowable hits a block or entity. + protected float getVelocity() { + return 0.5F; + } + + /** + * + Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { if (!this.worldObj.isRemote) { @@ -140,9 +132,8 @@ public class EntityPotion extends EntityThrowable { } - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { super.readEntityFromNBT(nbttagcompound); @@ -158,9 +149,19 @@ public class EntityPotion extends EntityThrowable { } - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. + /** + * + Sets the PotionEffect by the given id of the potion effect. + */ + public void setPotionDamage(int potionId) { + if (this.potionDamage == null) { + this.potionDamage = new ItemStack(Items.potionitem, 1, 0); + } + + this.potionDamage.setItemDamage(potionId); + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound nbttagcompound) { super.writeEntityToNBT(nbttagcompound); diff --git a/src/game/java/net/minecraft/entity/projectile/EntitySmallFireball.java b/src/game/java/net/minecraft/entity/projectile/EntitySmallFireball.java index 2be754df..9498dd16 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntitySmallFireball.java +++ b/src/game/java/net/minecraft/entity/projectile/EntitySmallFireball.java @@ -8,22 +8,25 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,19 +37,34 @@ public class EntitySmallFireball extends EntityFireball { this.setSize(0.3125F, 0.3125F); } - public EntitySmallFireball(World worldIn, EntityLivingBase shooter, double accelX, double accelY, double accelZ) { - super(worldIn, shooter, accelX, accelY, accelZ); - this.setSize(0.3125F, 0.3125F); - } - public EntitySmallFireball(World worldIn, double x, double y, double z, double accelX, double accelY, double accelZ) { super(worldIn, x, y, z, accelX, accelY, accelZ); this.setSize(0.3125F, 0.3125F); } - /**+ - * Called when this EntityFireball hits a block or entity. + public EntitySmallFireball(World worldIn, EntityLivingBase shooter, double accelX, double accelY, double accelZ) { + super(worldIn, shooter, accelX, accelY, accelZ); + this.setSize(0.3125F, 0.3125F); + } + + /** + * + Called when the entity is attacked. + */ + public boolean attackEntityFrom(DamageSource var1, float var2) { + return false; + } + + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return false; + } + + /** + * + Called when this EntityFireball hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { if (!this.worldObj.isRemote) { @@ -77,19 +95,4 @@ public class EntitySmallFireball extends EntityFireball { } } - - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return false; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource var1, float var2) { - return false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntitySnowball.java b/src/game/java/net/minecraft/entity/projectile/EntitySnowball.java index 582ae8b3..202f8f36 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntitySnowball.java +++ b/src/game/java/net/minecraft/entity/projectile/EntitySnowball.java @@ -7,22 +7,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,16 +35,16 @@ public class EntitySnowball extends EntityThrowable { super(worldIn); } - public EntitySnowball(World worldIn, EntityLivingBase throwerIn) { - super(worldIn, throwerIn); - } - public EntitySnowball(World worldIn, double x, double y, double z) { super(worldIn, x, y, z); } - /**+ - * Called when this EntityThrowable hits a block or entity. + public EntitySnowball(World worldIn, EntityLivingBase throwerIn) { + super(worldIn, throwerIn); + } + + /** + * + Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition parMovingObjectPosition) { if (parMovingObjectPosition.entityHit != null) { diff --git a/src/game/java/net/minecraft/entity/projectile/EntityThrowable.java b/src/game/java/net/minecraft/entity/projectile/EntityThrowable.java index 47269fa7..3527cf0b 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityThrowable.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityThrowable.java @@ -1,6 +1,7 @@ package net.minecraft.entity.projectile; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.Block; import net.minecraft.entity.Entity; @@ -19,22 +20,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,22 +60,11 @@ public abstract class EntityThrowable extends Entity implements IProjectile { this.setSize(0.25F, 0.25F); } - protected void entityInit() { - } - - /**+ - * Checks if the entity is in range to render by using the past - * in distance and comparing it to its average edge length * 64 - * * renderDistanceWeight Args: distance - */ - public boolean isInRangeToRenderDist(double d0) { - double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; - if (Double.isNaN(d1)) { - d1 = 4.0D; - } - - d1 = d1 * 64.0D; - return d0 < d1 * d1; + public EntityThrowable(World worldIn, double x, double y, double z) { + super(worldIn); + this.ticksInGround = 0; + this.setSize(0.25F, 0.25F); + this.setPosition(x, y, z); } public EntityThrowable(World worldIn, EntityLivingBase throwerIn) { @@ -94,66 +87,62 @@ public abstract class EntityThrowable extends Entity implements IProjectile { this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, this.getVelocity(), 1.0F); } - public EntityThrowable(World worldIn, double x, double y, double z) { - super(worldIn); - this.ticksInGround = 0; - this.setSize(0.25F, 0.25F); - this.setPosition(x, y, z); + protected void entityInit() { } - protected float getVelocity() { - return 1.5F; + /** + * + Gets the amount of gravity to apply to the thrown entity with each tick. + */ + protected float getGravityVelocity() { + return 0.03F; } protected float getInaccuracy() { return 0.0F; } - /**+ - * Similar to setArrowHeading, it's point the throwable entity - * to a x, y, z direction. - */ - public void setThrowableHeading(double d0, double d1, double d2, float f, float f1) { - float f2 = MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); - d0 = d0 / (double) f2; - d1 = d1 / (double) f2; - d2 = d2 / (double) f2; - d0 = d0 + this.rand.nextGaussian() * 0.007499999832361937D * (double) f1; - d1 = d1 + this.rand.nextGaussian() * 0.007499999832361937D * (double) f1; - d2 = d2 + this.rand.nextGaussian() * 0.007499999832361937D * (double) f1; - d0 = d0 * (double) f; - d1 = d1 * (double) f; - d2 = d2 * (double) f; - this.motionX = d0; - this.motionY = d1; - this.motionZ = d2; - float f3 = MathHelper.sqrt_double(d0 * d0 + d2 * d2); - this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f3) * 180.0D - / 3.1415927410125732D); - this.ticksInGround = 0; - } - - /**+ - * Sets the velocity to the args. Args: x, y, z - */ - public void setVelocity(double d0, double d1, double d2) { - this.motionX = d0; - this.motionY = d1; - this.motionZ = d2; - if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { - float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); - this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D - / 3.1415927410125732D); - this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D - / 3.1415927410125732D); + public EntityLivingBase getThrower() { + if (this.thrower == null && this.throwerName != null && this.throwerName.length() > 0) { + this.thrower = this.worldObj.getPlayerEntityByName(this.throwerName); + if (this.thrower == null && this.worldObj instanceof WorldServer) { + try { + Entity entity = ((WorldServer) this.worldObj) + .getEntityFromUuid(EaglercraftUUID.fromString(this.throwerName)); + if (entity instanceof EntityLivingBase) { + this.thrower = (EntityLivingBase) entity; + } + } catch (Throwable var2) { + this.thrower = null; + } + } } + return this.thrower; } - /**+ - * Called to update the entity's position/logic. + protected float getVelocity() { + return 1.5F; + } + + /** + * + Checks if the entity is in range to render by using the past in distance + * and comparing it to its average edge length * 64 * renderDistanceWeight Args: + * distance + */ + public boolean isInRangeToRenderDist(double d0) { + double d1 = this.getEntityBoundingBox().getAverageEdgeLength() * 4.0D; + if (Double.isNaN(d1)) { + d1 = 4.0D; + } + + d1 = d1 * 64.0D; + return d0 < d1 * d1; + } + + protected abstract void onImpact(MovingObjectPosition var1); + + /** + * + Called to update the entity's position/logic. */ public void onUpdate() { this.lastTickPosX = this.posX; @@ -280,38 +269,8 @@ public abstract class EntityThrowable extends Entity implements IProjectile { this.setPosition(this.posX, this.posY, this.posZ); } - /**+ - * Gets the amount of gravity to apply to the thrown entity with - * each tick. - */ - protected float getGravityVelocity() { - return 0.03F; - } - - protected abstract void onImpact(MovingObjectPosition var1); - - /**+ - * (abstract) Protected helper method to write subclass entity - * data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setShort("xTile", (short) this.xTile); - nbttagcompound.setShort("yTile", (short) this.yTile); - nbttagcompound.setShort("zTile", (short) this.zTile); - ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); - nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound.setByte("shake", (byte) this.throwableShake); - nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); - if ((this.throwerName == null || this.throwerName.length() == 0) && this.thrower instanceof EntityPlayer) { - this.throwerName = this.thrower.getName(); - } - - nbttagcompound.setString("ownerName", this.throwerName == null ? "" : this.throwerName); - } - - /**+ - * (abstract) Protected helper method to read subclass entity - * data from NBT. + /** + * + (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound nbttagcompound) { this.xTile = nbttagcompound.getShort("xTile"); @@ -334,22 +293,64 @@ public abstract class EntityThrowable extends Entity implements IProjectile { this.thrower = this.getThrower(); } - public EntityLivingBase getThrower() { - if (this.thrower == null && this.throwerName != null && this.throwerName.length() > 0) { - this.thrower = this.worldObj.getPlayerEntityByName(this.throwerName); - if (this.thrower == null && this.worldObj instanceof WorldServer) { - try { - Entity entity = ((WorldServer) this.worldObj) - .getEntityFromUuid(EaglercraftUUID.fromString(this.throwerName)); - if (entity instanceof EntityLivingBase) { - this.thrower = (EntityLivingBase) entity; - } - } catch (Throwable var2) { - this.thrower = null; - } - } + /** + * + Similar to setArrowHeading, it's point the throwable entity to a x, y, z + * direction. + */ + public void setThrowableHeading(double d0, double d1, double d2, float f, float f1) { + float f2 = MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); + d0 = d0 / (double) f2; + d1 = d1 / (double) f2; + d2 = d2 / (double) f2; + d0 = d0 + this.rand.nextGaussian() * 0.007499999832361937D * (double) f1; + d1 = d1 + this.rand.nextGaussian() * 0.007499999832361937D * (double) f1; + d2 = d2 + this.rand.nextGaussian() * 0.007499999832361937D * (double) f1; + d0 = d0 * (double) f; + d1 = d1 * (double) f; + d2 = d2 * (double) f; + this.motionX = d0; + this.motionY = d1; + this.motionZ = d2; + float f3 = MathHelper.sqrt_double(d0 * d0 + d2 * d2); + this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f3) * 180.0D + / 3.1415927410125732D); + this.ticksInGround = 0; + } + + /** + * + Sets the velocity to the args. Args: x, y, z + */ + public void setVelocity(double d0, double d1, double d2) { + this.motionX = d0; + this.motionY = d1; + this.motionZ = d2; + if (this.prevRotationPitch == 0.0F && this.prevRotationYaw == 0.0F) { + float f = MathHelper.sqrt_double(d0 * d0 + d2 * d2); + this.prevRotationYaw = this.rotationYaw = (float) (MathHelper.func_181159_b(d0, d2) * 180.0D + / 3.1415927410125732D); + this.prevRotationPitch = this.rotationPitch = (float) (MathHelper.func_181159_b(d1, (double) f) * 180.0D + / 3.1415927410125732D); } - return this.thrower; + } + + /** + * + (abstract) Protected helper method to write subclass entity data to NBT. + */ + public void writeEntityToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setShort("xTile", (short) this.xTile); + nbttagcompound.setShort("yTile", (short) this.yTile); + nbttagcompound.setShort("zTile", (short) this.zTile); + ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry.getNameForObject(this.inTile); + nbttagcompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound.setByte("shake", (byte) this.throwableShake); + nbttagcompound.setByte("inGround", (byte) (this.inGround ? 1 : 0)); + if ((this.throwerName == null || this.throwerName.length() == 0) && this.thrower instanceof EntityPlayer) { + this.throwerName = this.thrower.getName(); + } + + nbttagcompound.setString("ownerName", this.throwerName == null ? "" : this.throwerName); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/entity/projectile/EntityWitherSkull.java b/src/game/java/net/minecraft/entity/projectile/EntityWitherSkull.java index 9aae1d3f..00b678bf 100644 --- a/src/game/java/net/minecraft/entity/projectile/EntityWitherSkull.java +++ b/src/game/java/net/minecraft/entity/projectile/EntityWitherSkull.java @@ -13,22 +13,25 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.Explosion; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,34 +42,37 @@ public class EntityWitherSkull extends EntityFireball { this.setSize(0.3125F, 0.3125F); } - public EntityWitherSkull(World worldIn, EntityLivingBase shooter, double accelX, double accelY, double accelZ) { - super(worldIn, shooter, accelX, accelY, accelZ); - this.setSize(0.3125F, 0.3125F); - } - - /**+ - * Return the motion factor for this projectile. The factor is - * multiplied by the original motion. - */ - protected float getMotionFactor() { - return this.isInvulnerable() ? 0.73F : super.getMotionFactor(); - } - public EntityWitherSkull(World worldIn, double x, double y, double z, double accelX, double accelY, double accelZ) { super(worldIn, x, y, z, accelX, accelY, accelZ); this.setSize(0.3125F, 0.3125F); } - /**+ - * Returns true if the entity is on fire. Used by render to add - * the fire effect on rendering. + public EntityWitherSkull(World worldIn, EntityLivingBase shooter, double accelX, double accelY, double accelZ) { + super(worldIn, shooter, accelX, accelY, accelZ); + this.setSize(0.3125F, 0.3125F); + } + + /** + * + Called when the entity is attacked. */ - public boolean isBurning() { + public boolean attackEntityFrom(DamageSource var1, float var2) { return false; } - /**+ - * Explosion resistance of a block relative to this entity + /** + * + Returns true if other Entities should be prevented from moving through this + * Entity. + */ + public boolean canBeCollidedWith() { + return false; + } + + protected void entityInit() { + this.dataWatcher.addObject(10, Byte.valueOf((byte) 0)); + } + + /** + * + Explosion resistance of a block relative to this entity */ public float getExplosionResistance(Explosion explosion, World world, BlockPos blockpos, IBlockState iblockstate) { float f = super.getExplosionResistance(explosion, world, blockpos, iblockstate); @@ -78,8 +84,31 @@ public class EntityWitherSkull extends EntityFireball { return f; } - /**+ - * Called when this EntityFireball hits a block or entity. + /** + * + Return the motion factor for this projectile. The factor is multiplied by + * the original motion. + */ + protected float getMotionFactor() { + return this.isInvulnerable() ? 0.73F : super.getMotionFactor(); + } + + /** + * + Returns true if the entity is on fire. Used by render to add the fire + * effect on rendering. + */ + public boolean isBurning() { + return false; + } + + /** + * + Return whether this skull comes from an invulnerable (aura) wither boss. + */ + public boolean isInvulnerable() { + return this.dataWatcher.getWatchableObjectByte(10) == 1; + } + + /** + * + Called when this EntityFireball hits a block or entity. */ protected void onImpact(MovingObjectPosition movingobjectposition) { if (!this.worldObj.isRemote) { @@ -119,36 +148,8 @@ public class EntityWitherSkull extends EntityFireball { } - /**+ - * Returns true if other Entities should be prevented from - * moving through this Entity. - */ - public boolean canBeCollidedWith() { - return false; - } - - /**+ - * Called when the entity is attacked. - */ - public boolean attackEntityFrom(DamageSource var1, float var2) { - return false; - } - - protected void entityInit() { - this.dataWatcher.addObject(10, Byte.valueOf((byte) 0)); - } - - /**+ - * Return whether this skull comes from an invulnerable (aura) - * wither boss. - */ - public boolean isInvulnerable() { - return this.dataWatcher.getWatchableObjectByte(10) == 1; - } - - /**+ - * Set whether this skull comes from an invulnerable (aura) - * wither boss. + /** + * + Set whether this skull comes from an invulnerable (aura) wither boss. */ public void setInvulnerable(boolean invulnerable) { this.dataWatcher.updateObject(10, Byte.valueOf((byte) (invulnerable ? 1 : 0))); diff --git a/src/game/java/net/minecraft/event/ClickEvent.java b/src/game/java/net/minecraft/event/ClickEvent.java index 094a85d5..b4ce76d7 100644 --- a/src/game/java/net/minecraft/event/ClickEvent.java +++ b/src/game/java/net/minecraft/event/ClickEvent.java @@ -4,28 +4,68 @@ import java.util.Map; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ClickEvent { + public static enum Action { + OPEN_URL("open_url", true), OPEN_FILE("open_file", false), RUN_COMMAND("run_command", true), + TWITCH_USER_INFO("twitch_user_info", false), SUGGEST_COMMAND("suggest_command", true), + CHANGE_PAGE("change_page", true), EAGLER_PLUGIN_DOWNLOAD("eagler_plugin_download", true); + + private static final Map nameMapping = Maps.newHashMap(); + static { + ClickEvent.Action[] types = values(); + for (int i = 0; i < types.length; ++i) { + nameMapping.put(types[i].getCanonicalName(), types[i]); + } + + } + + public static ClickEvent.Action getValueByCanonicalName(String canonicalNameIn) { + return (ClickEvent.Action) nameMapping.get(canonicalNameIn); + } + + private final boolean allowedInChat; + + private final String canonicalName; + + private Action(String canonicalNameIn, boolean allowedInChatIn) { + this.canonicalName = canonicalNameIn; + this.allowedInChat = allowedInChatIn; + } + + public String getCanonicalName() { + return this.canonicalName; + } + + public boolean shouldAllowInChat() { + return this.allowedInChat; + } + } + private final ClickEvent.Action action; + private final String value; public ClickEvent(ClickEvent.Action theAction, String theValue) { @@ -33,22 +73,6 @@ public class ClickEvent { this.value = theValue; } - /**+ - * Gets the action to perform when this event is raised. - */ - public ClickEvent.Action getAction() { - return this.action; - } - - /**+ - * Gets the value to perform the action on when this event is - * raised. For example, if the action is "open URL", this would - * be the URL to open. - */ - public String getValue() { - return this.value; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -72,8 +96,19 @@ public class ClickEvent { } } - public String toString() { - return "ClickEvent{action=" + this.action + ", value=\'" + this.value + '\'' + '}'; + /** + * + Gets the action to perform when this event is raised. + */ + public ClickEvent.Action getAction() { + return this.action; + } + + /** + * + Gets the value to perform the action on when this event is raised. For + * example, if the action is "open URL", this would be the URL to open. + */ + public String getValue() { + return this.value; } public int hashCode() { @@ -82,38 +117,7 @@ public class ClickEvent { return i; } - public static enum Action { - OPEN_URL("open_url", true), OPEN_FILE("open_file", false), RUN_COMMAND("run_command", true), - TWITCH_USER_INFO("twitch_user_info", false), SUGGEST_COMMAND("suggest_command", true), - CHANGE_PAGE("change_page", true), EAGLER_PLUGIN_DOWNLOAD("eagler_plugin_download", true); - - private static final Map nameMapping = Maps.newHashMap(); - private final boolean allowedInChat; - private final String canonicalName; - - private Action(String canonicalNameIn, boolean allowedInChatIn) { - this.canonicalName = canonicalNameIn; - this.allowedInChat = allowedInChatIn; - } - - public boolean shouldAllowInChat() { - return this.allowedInChat; - } - - public String getCanonicalName() { - return this.canonicalName; - } - - public static ClickEvent.Action getValueByCanonicalName(String canonicalNameIn) { - return (ClickEvent.Action) nameMapping.get(canonicalNameIn); - } - - static { - ClickEvent.Action[] types = values(); - for (int i = 0; i < types.length; ++i) { - nameMapping.put(types[i].getCanonicalName(), types[i]); - } - - } + public String toString() { + return "ClickEvent{action=" + this.action + ", value=\'" + this.value + '\'' + '}'; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/event/HoverEvent.java b/src/game/java/net/minecraft/event/HoverEvent.java index c5cca3f7..50547fdb 100644 --- a/src/game/java/net/minecraft/event/HoverEvent.java +++ b/src/game/java/net/minecraft/event/HoverEvent.java @@ -6,28 +6,67 @@ import com.google.common.collect.Maps; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class HoverEvent { + public static enum Action { + SHOW_TEXT("show_text", true), SHOW_ACHIEVEMENT("show_achievement", true), SHOW_ITEM("show_item", true), + SHOW_ENTITY("show_entity", true); + + private static final Map nameMapping = Maps.newHashMap(); + static { + HoverEvent.Action[] types = values(); + for (int i = 0; i < types.length; ++i) { + nameMapping.put(types[i].getCanonicalName(), types[i]); + } + + } + + public static HoverEvent.Action getValueByCanonicalName(String canonicalNameIn) { + return (HoverEvent.Action) nameMapping.get(canonicalNameIn); + } + + private final boolean allowedInChat; + + private final String canonicalName; + + private Action(String canonicalNameIn, boolean allowedInChatIn) { + this.canonicalName = canonicalNameIn; + this.allowedInChat = allowedInChatIn; + } + + public String getCanonicalName() { + return this.canonicalName; + } + + public boolean shouldAllowInChat() { + return this.allowedInChat; + } + } + private final HoverEvent.Action action; + private final IChatComponent value; public HoverEvent(HoverEvent.Action actionIn, IChatComponent valueIn) { @@ -35,22 +74,6 @@ public class HoverEvent { this.value = valueIn; } - /**+ - * Gets the action to perform when this event is raised. - */ - public HoverEvent.Action getAction() { - return this.action; - } - - /**+ - * Gets the value to perform the action on when this event is - * raised. For example, if the action is "show item", this would - * be the item to show. - */ - public IChatComponent getValue() { - return this.value; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -74,8 +97,19 @@ public class HoverEvent { } } - public String toString() { - return "HoverEvent{action=" + this.action + ", value=\'" + this.value + '\'' + '}'; + /** + * + Gets the action to perform when this event is raised. + */ + public HoverEvent.Action getAction() { + return this.action; + } + + /** + * + Gets the value to perform the action on when this event is raised. For + * example, if the action is "show item", this would be the item to show. + */ + public IChatComponent getValue() { + return this.value; } public int hashCode() { @@ -84,37 +118,7 @@ public class HoverEvent { return i; } - public static enum Action { - SHOW_TEXT("show_text", true), SHOW_ACHIEVEMENT("show_achievement", true), SHOW_ITEM("show_item", true), - SHOW_ENTITY("show_entity", true); - - private static final Map nameMapping = Maps.newHashMap(); - private final boolean allowedInChat; - private final String canonicalName; - - private Action(String canonicalNameIn, boolean allowedInChatIn) { - this.canonicalName = canonicalNameIn; - this.allowedInChat = allowedInChatIn; - } - - public boolean shouldAllowInChat() { - return this.allowedInChat; - } - - public String getCanonicalName() { - return this.canonicalName; - } - - public static HoverEvent.Action getValueByCanonicalName(String canonicalNameIn) { - return (HoverEvent.Action) nameMapping.get(canonicalNameIn); - } - - static { - HoverEvent.Action[] types = values(); - for (int i = 0; i < types.length; ++i) { - nameMapping.put(types[i].getCanonicalName(), types[i]); - } - - } + public String toString() { + return "HoverEvent{action=" + this.action + ", value=\'" + this.value + '\'' + '}'; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/init/Blocks.java b/src/game/java/net/minecraft/init/Blocks.java index 36f840c6..2987e2a1 100644 --- a/src/game/java/net/minecraft/init/Blocks.java +++ b/src/game/java/net/minecraft/init/Blocks.java @@ -10,6 +10,7 @@ import net.minecraft.block.BlockDaylightDetector; import net.minecraft.block.BlockDeadBush; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.BlockDynamicLiquid; +import net.minecraft.block.BlockFabricator; import net.minecraft.block.BlockFire; import net.minecraft.block.BlockFlower; import net.minecraft.block.BlockGrass; @@ -34,22 +35,25 @@ import net.minecraft.block.BlockTallGrass; import net.minecraft.block.BlockTripWireHook; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -253,18 +257,18 @@ public class Blocks { public static Block red_sandstone_stairs; public static BlockSlab double_stone_slab2; public static BlockSlab stone_slab2; - public static Block iron_grate; + public static Block deepstone; + public static Block cobbled_deepstone; + public static Block steel_block; + public static Block steel_grate; public static Block platinum_ore; public static Block platinum_block; + public static Block titanium_ore; + public static Block titanium_block; public static Block uranium_ore; - - /**+ - * Returns the Block in the blockRegistry with the specified - * name. - */ - private static Block getRegisteredBlock(String parString1) { - return (Block) Block.blockRegistry.getObject(new ResourceLocation(parString1)); - } + public static Block uranium_block; + public static Block mosaic; + public static Block fabricator; static void doBootstrap() { if (!Bootstrap.isRegistered()) { @@ -468,10 +472,27 @@ public class Blocks { red_sandstone_stairs = getRegisteredBlock("red_sandstone_stairs"); double_stone_slab2 = (BlockSlab) getRegisteredBlock("double_stone_slab2"); stone_slab2 = (BlockSlab) getRegisteredBlock("stone_slab2"); - iron_grate = getRegisteredBlock("starlike:iron_grate"); + + deepstone = getRegisteredBlock("starlike:deepstone"); + cobbled_deepstone = getRegisteredBlock("starlike:cobbled_deepstone"); + steel_block = getRegisteredBlock("starlike:steel_block"); + steel_grate = getRegisteredBlock("starlike:steel_grate"); platinum_ore = getRegisteredBlock("starlike:platinum_ore"); platinum_block = getRegisteredBlock("starlike:platinum_block"); + titanium_ore = getRegisteredBlock("starlike:titanium_ore"); + titanium_block = getRegisteredBlock("starlike:titanium_block"); uranium_ore = getRegisteredBlock("starlike:uranium_ore"); + uranium_block = getRegisteredBlock("starlike:uranium_block"); + mosaic = getRegisteredBlock("starlike:mosaic"); + fabricator = (BlockFabricator) getRegisteredBlock("starlike:fabricator"); + } } + + /** + * + Returns the Block in the blockRegistry with the specified name. + */ + private static Block getRegisteredBlock(String parString1) { + return (Block) Block.blockRegistry.getObject(new ResourceLocation(parString1)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/init/Bootstrap.java b/src/game/java/net/minecraft/init/Bootstrap.java index 10527a12..385da1ca 100644 --- a/src/game/java/net/minecraft/init/Bootstrap.java +++ b/src/game/java/net/minecraft/init/Bootstrap.java @@ -1,9 +1,12 @@ package net.minecraft.init; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import java.io.PrintStream; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.block.Block; import net.minecraft.block.BlockDispenser; import net.minecraft.block.BlockFire; @@ -45,54 +48,93 @@ import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; -import net.minecraft.util.LoggingPrintStream; import net.minecraft.stats.StatList; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityDispenser; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; +import net.minecraft.util.LoggingPrintStream; import net.minecraft.util.StringUtils; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Bootstrap { private static final PrintStream SYSOUT = System.out; - /**+ - * Whether the blocks, items, etc have already been registered + /** + * + Whether the blocks, items, etc have already been registered */ private static boolean alreadyRegistered = false; private static final Logger LOGGER = LogManager.getLogger(); - /**+ - * Is Bootstrap registration already done? + /** + * + Is Bootstrap registration already done? */ public static boolean isRegistered() { return alreadyRegistered; } + public static void printToSYSOUT(String parString1) { + SYSOUT.println(parString1); + } + + /** + * + redirect standard streams to logger + */ + private static void redirectOutputToLog() { + System.setErr(new LoggingPrintStream("STDERR", true, System.err)); + System.setOut(new LoggingPrintStream("STDOUT", false, SYSOUT)); + } + + /** + * + Registers blocks, items, stats, etc. + */ + public static void register() { + if (!alreadyRegistered) { + alreadyRegistered = true; + if (LOGGER.isDebugEnabled()) { + redirectOutputToLog(); + } + + Block.registerBlocks(); + Blocks.doBootstrap(); + BiomeGenBase.doBootstrap(); + BlockFire.init(); + EntityEnderman.bootstrap(); + ItemAxe.bootstrap(); + ItemPickaxe.bootstrap(); + ItemSpade.bootstrap(); + Item.registerItems(); + Items.doBootstrap(); + EntityVillager.bootstrap(); + StatList.init(); + registerDispenserBehaviors(); + } + } + static void registerDispenserBehaviors() { BlockDispenser.dispenseBehaviorRegistry.putObject(Items.arrow, new BehaviorProjectileDispense() { protected IProjectile getProjectileEntity(World world, IPosition iposition) { @@ -112,10 +154,6 @@ public class Bootstrap { } }); BlockDispenser.dispenseBehaviorRegistry.putObject(Items.experience_bottle, new BehaviorProjectileDispense() { - protected IProjectile getProjectileEntity(World world, IPosition iposition) { - return new EntityExpBottle(world, iposition.getX(), iposition.getY(), iposition.getZ()); - } - protected float func_82498_a() { return super.func_82498_a() * 0.5F; } @@ -123,17 +161,16 @@ public class Bootstrap { protected float func_82500_b() { return super.func_82500_b() * 1.25F; } + + protected IProjectile getProjectileEntity(World world, IPosition iposition) { + return new EntityExpBottle(world, iposition.getX(), iposition.getY(), iposition.getZ()); + } }); BlockDispenser.dispenseBehaviorRegistry.putObject(Items.potionitem, new IBehaviorDispenseItem() { private final BehaviorDefaultDispenseItem field_150843_b = new BehaviorDefaultDispenseItem(); public ItemStack dispense(IBlockSource iblocksource, final ItemStack itemstack) { return ItemPotion.isSplash(itemstack.getMetadata()) ? (new BehaviorProjectileDispense() { - protected IProjectile getProjectileEntity(World world, IPosition iposition) { - return new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ(), - itemstack.copy()); - } - protected float func_82498_a() { return super.func_82498_a() * 0.5F; } @@ -141,6 +178,11 @@ public class Bootstrap { protected float func_82500_b() { return super.func_82500_b() * 1.25F; } + + protected IProjectile getProjectileEntity(World world, IPosition iposition) { + return new EntityPotion(world, iposition.getX(), iposition.getY(), iposition.getZ(), + itemstack.copy()); + } }).dispense(iblocksource, itemstack) : this.field_150843_b.dispense(iblocksource, itemstack); } }); @@ -445,42 +487,4 @@ public class Bootstrap { } }); } - - /**+ - * Registers blocks, items, stats, etc. - */ - public static void register() { - if (!alreadyRegistered) { - alreadyRegistered = true; - if (LOGGER.isDebugEnabled()) { - redirectOutputToLog(); - } - - Block.registerBlocks(); - Blocks.doBootstrap(); - BiomeGenBase.doBootstrap(); - BlockFire.init(); - EntityEnderman.bootstrap(); - ItemAxe.bootstrap(); - ItemPickaxe.bootstrap(); - ItemSpade.bootstrap(); - Item.registerItems(); - Items.doBootstrap(); - EntityVillager.bootstrap(); - StatList.init(); - registerDispenserBehaviors(); - } - } - - /**+ - * redirect standard streams to logger - */ - private static void redirectOutputToLog() { - System.setErr(new LoggingPrintStream("STDERR", true, System.err)); - System.setOut(new LoggingPrintStream("STDOUT", false, SYSOUT)); - } - - public static void printToSYSOUT(String parString1) { - SYSOUT.println(parString1); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/init/Items.java b/src/game/java/net/minecraft/init/Items.java index 9255c0ec..8361e688 100644 --- a/src/game/java/net/minecraft/init/Items.java +++ b/src/game/java/net/minecraft/init/Items.java @@ -12,22 +12,25 @@ import net.minecraft.item.ItemPotion; import net.minecraft.item.ItemShears; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -220,14 +223,22 @@ public class Items { public static Item prismarine_shard; public static Item prismarine_crystals; public static Item banner; + public static Item steel; public static Item platinum_ingot; public static Item platinum_sword; public static Item platinum_pickaxe; - public static Item normal_drill; - - private static Item getRegisteredItem(String name) { - return (Item) Item.itemRegistry.getObject(new ResourceLocation(name)); - } + public static Item platinum_shovel; + public static Item platinum_axe; + public static Item platinum_hoe; + public static Item platinum_helmet; + public static Item platinum_chestplate; + public static Item platinum_leggings; + public static Item platinum_boots; + public static Item titanium_ingot; + public static Item uranium_crystal; + public static Item uranium_rod; + public static Item platinum_drill; + public static Item titanium_drill; static void doBootstrap() { if (!Bootstrap.isRegistered()) { @@ -420,10 +431,27 @@ public class Items { prismarine_shard = getRegisteredItem("prismarine_shard"); prismarine_crystals = getRegisteredItem("prismarine_crystals"); banner = getRegisteredItem("banner"); + + steel = getRegisteredItem("starlike:steel"); platinum_ingot = getRegisteredItem("starlike:platinum_ingot"); platinum_sword = getRegisteredItem("starlike:platinum_sword"); platinum_pickaxe = getRegisteredItem("starlike:platinum_pickaxe"); - normal_drill = getRegisteredItem("starlike:normal_drill"); + platinum_shovel = getRegisteredItem("starlike:platinum_shovel"); + platinum_axe = getRegisteredItem("starlike:platinum_axe"); + platinum_hoe = getRegisteredItem("starlike:platinum_hoe"); + platinum_helmet = getRegisteredItem("starlike:platinum_helmet"); + platinum_chestplate = getRegisteredItem("starlike:platinum_chestplate"); + platinum_leggings = getRegisteredItem("starlike:platinum_leggings"); + platinum_boots = getRegisteredItem("starlike:platinum_boots"); + titanium_ingot = getRegisteredItem("starlike:titanium_ingot"); + uranium_crystal = getRegisteredItem("starlike:uranium_crystal"); + uranium_rod = getRegisteredItem("starlike:uranium_rod"); + platinum_drill = getRegisteredItem("starlike:platinum_drill"); + titanium_drill = getRegisteredItem("starlike:titanium_drill"); } } + + private static Item getRegisteredItem(String name) { + return (Item) Item.itemRegistry.getObject(new ResourceLocation(name)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/AnimalChest.java b/src/game/java/net/minecraft/inventory/AnimalChest.java index 6c86254c..4410324b 100644 --- a/src/game/java/net/minecraft/inventory/AnimalChest.java +++ b/src/game/java/net/minecraft/inventory/AnimalChest.java @@ -2,32 +2,35 @@ package net.minecraft.inventory; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class AnimalChest extends InventoryBasic { - public AnimalChest(String inventoryName, int slotCount) { - super(inventoryName, false, slotCount); - } - public AnimalChest(IChatComponent invTitle, int slotCount) { super(invTitle, slotCount); } + + public AnimalChest(String inventoryName, int slotCount) { + super(inventoryName, false, slotCount); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/Container.java b/src/game/java/net/minecraft/inventory/Container.java index a231e30f..ece9793c 100644 --- a/src/game/java/net/minecraft/inventory/Container.java +++ b/src/game/java/net/minecraft/inventory/Container.java @@ -14,57 +14,152 @@ import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class Container { - /**+ - * the list of all items(stacks) for the corresponding slot + /** + * + Like the version that takes an inventory. If the given TileEntity is not an + * Inventory, 0 is returned instead. + */ + public static int calcRedstone(TileEntity te) { + return te instanceof IInventory ? calcRedstoneFromInventory((IInventory) te) : 0; + } + + public static int calcRedstoneFromInventory(IInventory inv) { + if (inv == null) { + return 0; + } else { + int i = 0; + float f = 0.0F; + + for (int j = 0; j < inv.getSizeInventory(); ++j) { + ItemStack itemstack = inv.getStackInSlot(j); + if (itemstack != null) { + f += (float) itemstack.stackSize + / (float) Math.min(inv.getInventoryStackLimit(), itemstack.getMaxStackSize()); + ++i; + } + } + + f = f / (float) inv.getSizeInventory(); + return MathHelper.floor_float(f * 14.0F) + (i > 0 ? 1 : 0); + } + } + + /** + * + Checks if it's possible to add the given itemstack to the given slot. + */ + public static boolean canAddItemToSlot(Slot slotIn, ItemStack stack, boolean stackSizeMatters) { + boolean flag = slotIn == null || !slotIn.getHasStack(); + if (slotIn != null && slotIn.getHasStack() && stack != null && stack.isItemEqual(slotIn.getStack()) + && ItemStack.areItemStackTagsEqual(slotIn.getStack(), stack)) { + flag |= slotIn.getStack().stackSize + (stackSizeMatters ? 0 : stack.stackSize) <= stack.getMaxStackSize(); + } + + return flag; + } + + /** + * + Compute the new stack size, Returns the stack with the new size. Args : + * dragSlots, dragMode, dragStack, slotStackSize + */ + public static void computeStackSize(Set parSet, int parInt1, ItemStack parItemStack, int parInt2) { + switch (parInt1) { + case 0: + parItemStack.stackSize = MathHelper.floor_float((float) parItemStack.stackSize / (float) parSet.size()); + break; + case 1: + parItemStack.stackSize = 1; + break; + case 2: + parItemStack.stackSize = parItemStack.getItem().getItemStackLimit(); + } + + parItemStack.stackSize += parInt2; + } + + /** + * + Extracts the drag mode. Args : eventButton. Return (0 : evenly split, 1 : + * one item by slot, 2 : not used ?) + */ + public static int extractDragMode(int parInt1) { + return parInt1 >> 2 & 3; + } + + public static int func_94534_d(int parInt1, int parInt2) { + return parInt1 & 3 | (parInt2 & 3) << 2; + } + + /** + * + Args : clickedButton, Returns (0 : start drag, 1 : add slot, 2 : end drag) + */ + public static int getDragEvent(int parInt1) { + return parInt1 & 3; + } + + public static boolean isValidDragMode(int dragModeIn, EntityPlayer player) { + return dragModeIn == 0 ? true + : (dragModeIn == 1 ? true : dragModeIn == 2 && player.capabilities.isCreativeMode); + } + + /** + * + the list of all items(stacks) for the corresponding slot */ public List inventoryItemStacks = Lists.newArrayList(); - /**+ - * the list of all slots in the inventory + + /** + * + the list of all slots in the inventory */ public List inventorySlots = Lists.newArrayList(); + public int windowId; + private short transactionID; - /**+ - * The current drag mode (0 : evenly split, 1 : one item by - * slot, 2 : not used ?) + + /** + * + The current drag mode (0 : evenly split, 1 : one item by slot, 2 : not used + * ?) */ private int dragMode = -1; + private int dragEvent; - /**+ - * The list of slots where the itemstack holds will be - * distributed + + /** + * + The list of slots where the itemstack holds will be distributed */ private final Set dragSlots = Sets.newHashSet(); - /**+ - * list of all people that need to be notified when this - * craftinventory changes + + /** + * + list of all people that need to be notified when this craftinventory + * changes */ protected List crafters = Lists.newArrayList(); + private Set playerList = Sets.newHashSet(); - /**+ - * Adds an item slot to this container + /** + * + Adds an item slot to this container */ protected Slot addSlotToContainer(Slot slotIn) { slotIn.slotNumber = this.inventorySlots.size(); @@ -73,39 +168,28 @@ public abstract class Container { return slotIn; } - public void onCraftGuiOpened(ICrafting listener) { - if (this.crafters.contains(listener)) { - throw new IllegalArgumentException("Listener already listening"); - } else { - this.crafters.add(listener); - listener.updateCraftingInventory(this, this.getInventory()); - this.detectAndSendChanges(); - } - } - - /**+ - * Remove the given Listener. Method name is for legacy. + /** + * + Returns true if the player can "drag-spilt" items into this slot,. returns + * true by default. Called to check if the slot can be added to a list of Slots + * to split the held ItemStack across. */ - public void removeCraftingFromCrafters(ICrafting listeners) { - this.crafters.remove(listeners); + public boolean canDragIntoSlot(Slot var1) { + return true; } - /**+ - * returns a list if itemStacks, for each slot. + public abstract boolean canInteractWith(EntityPlayer var1); + + /** + * + Called to determine if the current slot is valid for the stack merging + * (double-click) code. The stack passed in is null for the initial slot that + * was double-clicked. */ - public List getInventory() { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < this.inventorySlots.size(); ++i) { - arraylist.add(((Slot) this.inventorySlots.get(i)).getStack()); - } - - return arraylist; + public boolean canMergeSlot(ItemStack var1, Slot var2) { + return true; } - /**+ - * Looks for changes made in the container, sends them to every - * listener. + /** + * + Looks for changes made in the container, sends them to every listener. */ public void detectAndSendChanges() { for (int i = 0; i < this.inventorySlots.size(); ++i) { @@ -123,14 +207,46 @@ public abstract class Container { } - /**+ - * Handles the given Button-click on the server, currently only - * used by enchanting. Name is for legacy. + /** + * + Handles the given Button-click on the server, currently only used by + * enchanting. Name is for legacy. */ public boolean enchantItem(EntityPlayer playerIn, int id) { return false; } + /** + * + gets whether or not the player can craft in this inventory or not + */ + public boolean getCanCraft(EntityPlayer parEntityPlayer) { + return !this.playerList.contains(parEntityPlayer); + } + + /** + * + returns a list if itemStacks, for each slot. + */ + public List getInventory() { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < this.inventorySlots.size(); ++i) { + arraylist.add(((Slot) this.inventorySlots.get(i)).getStack()); + } + + return arraylist; + } + + /** + * + Gets a unique transaction ID. Parameter is unused. + */ + public short getNextTransactionID(InventoryPlayer parInventoryPlayer) { + ++this.transactionID; + return this.transactionID; + } + + public Slot getSlot(int slotId) { + return (Slot) this.inventorySlots.get(slotId); + } + public Slot getSlotFromInventory(IInventory inv, int slotIn) { for (int i = 0; i < this.inventorySlots.size(); ++i) { Slot slot = (Slot) this.inventorySlots.get(i); @@ -142,20 +258,159 @@ public abstract class Container { return null; } - public Slot getSlot(int slotId) { - return (Slot) this.inventorySlots.get(slotId); - } - - /**+ - * Take a stack from the specified inventory slot. + /** + * + Merges provided ItemStack with the first avaliable one in the + * container/player inventor between minIndex (included) and maxIndex + * (excluded). Args : stack, minIndex, maxIndex, negativDirection. /!\ the + * Container implementation do not check if the item is valid for the slot */ - public ItemStack transferStackInSlot(EntityPlayer var1, int i) { - Slot slot = (Slot) this.inventorySlots.get(i); - return slot != null ? slot.getStack() : null; + protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection) { + boolean flag = false; + int i = startIndex; + if (reverseDirection) { + i = endIndex - 1; + } + + if (stack.isStackable()) { + while (stack.stackSize > 0 && (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex)) { + Slot slot = (Slot) this.inventorySlots.get(i); + ItemStack itemstack = slot.getStack(); + if (itemstack != null && itemstack.getItem() == stack.getItem() + && (!stack.getHasSubtypes() || stack.getMetadata() == itemstack.getMetadata()) + && ItemStack.areItemStackTagsEqual(stack, itemstack)) { + int j = itemstack.stackSize + stack.stackSize; + if (j <= stack.getMaxStackSize()) { + stack.stackSize = 0; + itemstack.stackSize = j; + slot.onSlotChanged(); + flag = true; + } else if (itemstack.stackSize < stack.getMaxStackSize()) { + stack.stackSize -= stack.getMaxStackSize() - itemstack.stackSize; + itemstack.stackSize = stack.getMaxStackSize(); + slot.onSlotChanged(); + flag = true; + } + } + + if (reverseDirection) { + --i; + } else { + ++i; + } + } + } + + if (stack.stackSize > 0) { + if (reverseDirection) { + i = endIndex - 1; + } else { + i = startIndex; + } + + while (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex) { + Slot slot1 = (Slot) this.inventorySlots.get(i); + ItemStack itemstack1 = slot1.getStack(); + if (itemstack1 == null) { + slot1.putStack(stack.copy()); + slot1.onSlotChanged(); + stack.stackSize = 0; + flag = true; + break; + } + + if (reverseDirection) { + --i; + } else { + ++i; + } + } + } + + return flag; } - /**+ - * Handles slot click. + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer playerIn) { + InventoryPlayer inventoryplayer = playerIn.inventory; + if (inventoryplayer.getItemStack() != null) { + playerIn.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack(), false); + inventoryplayer.setItemStack((ItemStack) null); + } + + } + + public void onCraftGuiOpened(ICrafting listener) { + if (this.crafters.contains(listener)) { + throw new IllegalArgumentException("Listener already listening"); + } else { + this.crafters.add(listener); + listener.updateCraftingInventory(this, this.getInventory()); + this.detectAndSendChanges(); + } + } + + /** + * + Callback for when the crafting matrix is changed. + */ + public void onCraftMatrixChanged(IInventory inventoryIn) { + this.detectAndSendChanges(); + } + + /** + * + args: slotID, itemStack to put in slot + */ + public void putStackInSlot(int slotID, ItemStack stack) { + this.getSlot(slotID).putStack(stack); + } + + /** + * + places itemstacks in first x slots, x being aitemstack.lenght + */ + public void putStacksInSlots(ItemStack[] parArrayOfItemStack) { + for (int i = 0; i < parArrayOfItemStack.length; ++i) { + this.getSlot(i).putStack(parArrayOfItemStack[i]); + } + + } + + /** + * + Remove the given Listener. Method name is for legacy. + */ + public void removeCraftingFromCrafters(ICrafting listeners) { + this.crafters.remove(listeners); + } + + /** + * + Reset the drag fields + */ + protected void resetDrag() { + this.dragEvent = 0; + this.dragSlots.clear(); + } + + /** + * + Retries slotClick() in case of failure + */ + protected void retrySlotClick(int i, int j, boolean var3, EntityPlayer entityplayer) { + this.slotClick(i, j, 1, entityplayer); + } + + /** + * + sets whether the player can craft in this inventory or not + */ + public void setCanCraft(EntityPlayer parEntityPlayer, boolean parFlag) { + if (parFlag) { + this.playerList.remove(parEntityPlayer); + } else { + this.playerList.add(parEntityPlayer); + } + + } + + /** + * + Handles slot click. */ public ItemStack slotClick(int slotId, int clickedButton, int mode, EntityPlayer playerIn) { ItemStack itemstack = null; @@ -416,265 +671,14 @@ public abstract class Container { return itemstack; } - /**+ - * Called to determine if the current slot is valid for the - * stack merging (double-click) code. The stack passed in is - * null for the initial slot that was double-clicked. + /** + * + Take a stack from the specified inventory slot. */ - public boolean canMergeSlot(ItemStack var1, Slot var2) { - return true; - } - - /**+ - * Retries slotClick() in case of failure - */ - protected void retrySlotClick(int i, int j, boolean var3, EntityPlayer entityplayer) { - this.slotClick(i, j, 1, entityplayer); - } - - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer playerIn) { - InventoryPlayer inventoryplayer = playerIn.inventory; - if (inventoryplayer.getItemStack() != null) { - playerIn.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack(), false); - inventoryplayer.setItemStack((ItemStack) null); - } - - } - - /**+ - * Callback for when the crafting matrix is changed. - */ - public void onCraftMatrixChanged(IInventory inventoryIn) { - this.detectAndSendChanges(); - } - - /**+ - * args: slotID, itemStack to put in slot - */ - public void putStackInSlot(int slotID, ItemStack stack) { - this.getSlot(slotID).putStack(stack); - } - - /**+ - * places itemstacks in first x slots, x being aitemstack.lenght - */ - public void putStacksInSlots(ItemStack[] parArrayOfItemStack) { - for (int i = 0; i < parArrayOfItemStack.length; ++i) { - this.getSlot(i).putStack(parArrayOfItemStack[i]); - } - + public ItemStack transferStackInSlot(EntityPlayer var1, int i) { + Slot slot = (Slot) this.inventorySlots.get(i); + return slot != null ? slot.getStack() : null; } public void updateProgressBar(int id, int data) { } - - /**+ - * Gets a unique transaction ID. Parameter is unused. - */ - public short getNextTransactionID(InventoryPlayer parInventoryPlayer) { - ++this.transactionID; - return this.transactionID; - } - - /**+ - * gets whether or not the player can craft in this inventory or - * not - */ - public boolean getCanCraft(EntityPlayer parEntityPlayer) { - return !this.playerList.contains(parEntityPlayer); - } - - /**+ - * sets whether the player can craft in this inventory or not - */ - public void setCanCraft(EntityPlayer parEntityPlayer, boolean parFlag) { - if (parFlag) { - this.playerList.remove(parEntityPlayer); - } else { - this.playerList.add(parEntityPlayer); - } - - } - - public abstract boolean canInteractWith(EntityPlayer var1); - - /**+ - * Merges provided ItemStack with the first avaliable one in the - * container/player inventor between minIndex (included) and - * maxIndex (excluded). Args : stack, minIndex, maxIndex, - * negativDirection. /!\ the Container implementation do not - * check if the item is valid for the slot - */ - protected boolean mergeItemStack(ItemStack stack, int startIndex, int endIndex, boolean reverseDirection) { - boolean flag = false; - int i = startIndex; - if (reverseDirection) { - i = endIndex - 1; - } - - if (stack.isStackable()) { - while (stack.stackSize > 0 && (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex)) { - Slot slot = (Slot) this.inventorySlots.get(i); - ItemStack itemstack = slot.getStack(); - if (itemstack != null && itemstack.getItem() == stack.getItem() - && (!stack.getHasSubtypes() || stack.getMetadata() == itemstack.getMetadata()) - && ItemStack.areItemStackTagsEqual(stack, itemstack)) { - int j = itemstack.stackSize + stack.stackSize; - if (j <= stack.getMaxStackSize()) { - stack.stackSize = 0; - itemstack.stackSize = j; - slot.onSlotChanged(); - flag = true; - } else if (itemstack.stackSize < stack.getMaxStackSize()) { - stack.stackSize -= stack.getMaxStackSize() - itemstack.stackSize; - itemstack.stackSize = stack.getMaxStackSize(); - slot.onSlotChanged(); - flag = true; - } - } - - if (reverseDirection) { - --i; - } else { - ++i; - } - } - } - - if (stack.stackSize > 0) { - if (reverseDirection) { - i = endIndex - 1; - } else { - i = startIndex; - } - - while (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex) { - Slot slot1 = (Slot) this.inventorySlots.get(i); - ItemStack itemstack1 = slot1.getStack(); - if (itemstack1 == null) { - slot1.putStack(stack.copy()); - slot1.onSlotChanged(); - stack.stackSize = 0; - flag = true; - break; - } - - if (reverseDirection) { - --i; - } else { - ++i; - } - } - } - - return flag; - } - - /**+ - * Extracts the drag mode. Args : eventButton. Return (0 : - * evenly split, 1 : one item by slot, 2 : not used ?) - */ - public static int extractDragMode(int parInt1) { - return parInt1 >> 2 & 3; - } - - /**+ - * Args : clickedButton, Returns (0 : start drag, 1 : add slot, - * 2 : end drag) - */ - public static int getDragEvent(int parInt1) { - return parInt1 & 3; - } - - public static int func_94534_d(int parInt1, int parInt2) { - return parInt1 & 3 | (parInt2 & 3) << 2; - } - - public static boolean isValidDragMode(int dragModeIn, EntityPlayer player) { - return dragModeIn == 0 ? true - : (dragModeIn == 1 ? true : dragModeIn == 2 && player.capabilities.isCreativeMode); - } - - /**+ - * Reset the drag fields - */ - protected void resetDrag() { - this.dragEvent = 0; - this.dragSlots.clear(); - } - - /**+ - * Checks if it's possible to add the given itemstack to the - * given slot. - */ - public static boolean canAddItemToSlot(Slot slotIn, ItemStack stack, boolean stackSizeMatters) { - boolean flag = slotIn == null || !slotIn.getHasStack(); - if (slotIn != null && slotIn.getHasStack() && stack != null && stack.isItemEqual(slotIn.getStack()) - && ItemStack.areItemStackTagsEqual(slotIn.getStack(), stack)) { - flag |= slotIn.getStack().stackSize + (stackSizeMatters ? 0 : stack.stackSize) <= stack.getMaxStackSize(); - } - - return flag; - } - - /**+ - * Compute the new stack size, Returns the stack with the new - * size. Args : dragSlots, dragMode, dragStack, slotStackSize - */ - public static void computeStackSize(Set parSet, int parInt1, ItemStack parItemStack, int parInt2) { - switch (parInt1) { - case 0: - parItemStack.stackSize = MathHelper.floor_float((float) parItemStack.stackSize / (float) parSet.size()); - break; - case 1: - parItemStack.stackSize = 1; - break; - case 2: - parItemStack.stackSize = parItemStack.getItem().getItemStackLimit(); - } - - parItemStack.stackSize += parInt2; - } - - /**+ - * Returns true if the player can "drag-spilt" items into this - * slot,. returns true by default. Called to check if the slot - * can be added to a list of Slots to split the held ItemStack - * across. - */ - public boolean canDragIntoSlot(Slot var1) { - return true; - } - - /**+ - * Like the version that takes an inventory. If the given - * TileEntity is not an Inventory, 0 is returned instead. - */ - public static int calcRedstone(TileEntity te) { - return te instanceof IInventory ? calcRedstoneFromInventory((IInventory) te) : 0; - } - - public static int calcRedstoneFromInventory(IInventory inv) { - if (inv == null) { - return 0; - } else { - int i = 0; - float f = 0.0F; - - for (int j = 0; j < inv.getSizeInventory(); ++j) { - ItemStack itemstack = inv.getStackInSlot(j); - if (itemstack != null) { - f += (float) itemstack.stackSize - / (float) Math.min(inv.getInventoryStackLimit(), itemstack.getMaxStackSize()); - ++i; - } - } - - f = f / (float) inv.getSizeInventory(); - return MathHelper.floor_float(f * 14.0F) + (i > 0 ? 1 : 0); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerBeacon.java b/src/game/java/net/minecraft/inventory/ContainerBeacon.java index ec43a88e..6230ed1a 100644 --- a/src/game/java/net/minecraft/inventory/ContainerBeacon.java +++ b/src/game/java/net/minecraft/inventory/ContainerBeacon.java @@ -4,28 +4,48 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ContainerBeacon extends Container { + class BeaconSlot extends Slot { + public BeaconSlot(IInventory parIInventory, int parInt1, int parInt2, int parInt3) { + super(parIInventory, parInt1, parInt2, parInt3); + } + + public int getSlotStackLimit() { + return 1; + } + + public boolean isItemValid(ItemStack itemstack) { + return itemstack == null ? false + : itemstack.getItem() == Items.emerald || itemstack.getItem() == Items.diamond + || itemstack.getItem() == Items.gold_ingot || itemstack.getItem() == Items.iron_ingot; + } + } + private IInventory tileBeacon; + private final ContainerBeacon.BeaconSlot beaconSlot; public ContainerBeacon(IInventory playerInventory, IInventory tileBeaconIn) { @@ -46,21 +66,16 @@ public class ContainerBeacon extends Container { } - public void onCraftGuiOpened(ICrafting icrafting) { - super.onCraftGuiOpened(icrafting); - icrafting.func_175173_a(this, this.tileBeacon); - } - - public void updateProgressBar(int i, int j) { - this.tileBeacon.setField(i, j); + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.tileBeacon.isUseableByPlayer(entityplayer); } public IInventory func_180611_e() { return this.tileBeacon; } - /**+ - * Called when the container is closed. + /** + * + Called when the container is closed. */ public void onContainerClosed(EntityPlayer entityplayer) { super.onContainerClosed(entityplayer); @@ -73,12 +88,13 @@ public class ContainerBeacon extends Container { } } - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.tileBeacon.isUseableByPlayer(entityplayer); + public void onCraftGuiOpened(ICrafting icrafting) { + super.onCraftGuiOpened(icrafting); + icrafting.func_175173_a(this, this.tileBeacon); } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -125,19 +141,7 @@ public class ContainerBeacon extends Container { return itemstack; } - class BeaconSlot extends Slot { - public BeaconSlot(IInventory parIInventory, int parInt1, int parInt2, int parInt3) { - super(parIInventory, parInt1, parInt2, parInt3); - } - - public boolean isItemValid(ItemStack itemstack) { - return itemstack == null ? false - : itemstack.getItem() == Items.emerald || itemstack.getItem() == Items.diamond - || itemstack.getItem() == Items.gold_ingot || itemstack.getItem() == Items.iron_ingot; - } - - public int getSlotStackLimit() { - return 1; - } + public void updateProgressBar(int i, int j) { + this.tileBeacon.setField(i, j); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerBrewingStand.java b/src/game/java/net/minecraft/inventory/ContainerBrewingStand.java index 22e66399..add07c5e 100644 --- a/src/game/java/net/minecraft/inventory/ContainerBrewingStand.java +++ b/src/game/java/net/minecraft/inventory/ContainerBrewingStand.java @@ -6,29 +6,78 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.stats.AchievementList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ContainerBrewingStand extends Container { + class Ingredient extends Slot { + public Ingredient(IInventory inventoryIn, int index, int xPosition, int yPosition) { + super(inventoryIn, index, xPosition, yPosition); + } + + public int getSlotStackLimit() { + return 64; + } + + public boolean isItemValid(ItemStack itemstack) { + return itemstack != null ? itemstack.getItem().isPotionIngredient(itemstack) : false; + } + } + + static class Potion extends Slot { + public static boolean canHoldPotion(ItemStack parItemStack) { + return parItemStack != null + && (parItemStack.getItem() == Items.potionitem || parItemStack.getItem() == Items.glass_bottle); + } + + private EntityPlayer player; + + public Potion(EntityPlayer playerIn, IInventory inventoryIn, int index, int xPosition, int yPosition) { + super(inventoryIn, index, xPosition, yPosition); + this.player = playerIn; + } + + public int getSlotStackLimit() { + return 1; + } + + public boolean isItemValid(ItemStack itemstack) { + return canHoldPotion(itemstack); + } + + public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack itemstack) { + if (itemstack.getItem() == Items.potionitem && itemstack.getMetadata() > 0) { + this.player.triggerAchievement(AchievementList.potion); + } + + super.onPickupFromSlot(entityplayer, itemstack); + } + } + private IInventory tileBrewingStand; + private final Slot theSlot; + private int brewTime; public ContainerBrewingStand(InventoryPlayer playerInventory, IInventory tileBrewingStandIn) { @@ -53,14 +102,12 @@ public class ContainerBrewingStand extends Container { } - public void onCraftGuiOpened(ICrafting icrafting) { - super.onCraftGuiOpened(icrafting); - icrafting.func_175173_a(this, this.tileBrewingStand); + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.tileBrewingStand.isUseableByPlayer(entityplayer); } - /**+ - * Looks for changes made in the container, sends them to every - * listener. + /** + * + Looks for changes made in the container, sends them to every listener. */ public void detectAndSendChanges() { super.detectAndSendChanges(); @@ -75,16 +122,13 @@ public class ContainerBrewingStand extends Container { this.brewTime = this.tileBrewingStand.getField(0); } - public void updateProgressBar(int i, int j) { - this.tileBrewingStand.setField(i, j); + public void onCraftGuiOpened(ICrafting icrafting) { + super.onCraftGuiOpened(icrafting); + icrafting.func_175173_a(this, this.tileBrewingStand); } - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.tileBrewingStand.isUseableByPlayer(entityplayer); - } - - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -136,47 +180,7 @@ public class ContainerBrewingStand extends Container { return itemstack; } - class Ingredient extends Slot { - public Ingredient(IInventory inventoryIn, int index, int xPosition, int yPosition) { - super(inventoryIn, index, xPosition, yPosition); - } - - public boolean isItemValid(ItemStack itemstack) { - return itemstack != null ? itemstack.getItem().isPotionIngredient(itemstack) : false; - } - - public int getSlotStackLimit() { - return 64; - } - } - - static class Potion extends Slot { - private EntityPlayer player; - - public Potion(EntityPlayer playerIn, IInventory inventoryIn, int index, int xPosition, int yPosition) { - super(inventoryIn, index, xPosition, yPosition); - this.player = playerIn; - } - - public boolean isItemValid(ItemStack itemstack) { - return canHoldPotion(itemstack); - } - - public int getSlotStackLimit() { - return 1; - } - - public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack itemstack) { - if (itemstack.getItem() == Items.potionitem && itemstack.getMetadata() > 0) { - this.player.triggerAchievement(AchievementList.potion); - } - - super.onPickupFromSlot(entityplayer, itemstack); - } - - public static boolean canHoldPotion(ItemStack parItemStack) { - return parItemStack != null - && (parItemStack.getItem() == Items.potionitem || parItemStack.getItem() == Items.glass_bottle); - } + public void updateProgressBar(int i, int j) { + this.tileBrewingStand.setField(i, j); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerChest.java b/src/game/java/net/minecraft/inventory/ContainerChest.java index 89c662fb..efe43d48 100644 --- a/src/game/java/net/minecraft/inventory/ContainerChest.java +++ b/src/game/java/net/minecraft/inventory/ContainerChest.java @@ -3,22 +3,25 @@ package net.minecraft.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,8 +58,23 @@ public class ContainerChest extends Container { return this.lowerChestInventory.isUseableByPlayer(entityplayer); } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Return this chest container's lower chest inventory. + */ + public IInventory getLowerChestInventory() { + return this.lowerChestInventory; + } + + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + this.lowerChestInventory.closeInventory(entityplayer); + } + + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer var1, int i) { ItemStack itemstack = null; @@ -81,19 +99,4 @@ public class ContainerChest extends Container { return itemstack; } - - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - this.lowerChestInventory.closeInventory(entityplayer); - } - - /**+ - * Return this chest container's lower chest inventory. - */ - public IInventory getLowerChestInventory() { - return this.lowerChestInventory; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerDispenser.java b/src/game/java/net/minecraft/inventory/ContainerDispenser.java index 4ddeee70..55342f5c 100644 --- a/src/game/java/net/minecraft/inventory/ContainerDispenser.java +++ b/src/game/java/net/minecraft/inventory/ContainerDispenser.java @@ -3,22 +3,25 @@ package net.minecraft.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -51,8 +54,8 @@ public class ContainerDispenser extends Container { return this.dispenserInventory.isUseableByPlayer(entityplayer); } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; diff --git a/src/game/java/net/minecraft/inventory/ContainerEnchantment.java b/src/game/java/net/minecraft/inventory/ContainerEnchantment.java index c3d7a78e..e98f2353 100644 --- a/src/game/java/net/minecraft/inventory/ContainerEnchantment.java +++ b/src/game/java/net/minecraft/inventory/ContainerEnchantment.java @@ -1,6 +1,7 @@ package net.minecraft.inventory; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.enchantment.EnchantmentHelper; @@ -14,22 +15,25 @@ import net.minecraft.stats.StatList; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,13 +69,13 @@ public class ContainerEnchantment extends Container { this.position = pos; this.xpSeed = playerInv.player.getXPSeed(); this.addSlotToContainer(new Slot(this.tableInventory, 0, 15, 47) { - public boolean isItemValid(ItemStack var1) { - return true; - } - public int getSlotStackLimit() { return 1; } + + public boolean isItemValid(ItemStack var1) { + return true; + } }); this.addSlotToContainer(new Slot(this.tableInventory, 1, 35, 47) { public boolean isItemValid(ItemStack itemstack) { @@ -92,20 +96,14 @@ public class ContainerEnchantment extends Container { } - public void onCraftGuiOpened(ICrafting icrafting) { - super.onCraftGuiOpened(icrafting); - icrafting.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); - icrafting.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); - icrafting.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); - icrafting.sendProgressBarUpdate(this, 3, this.xpSeed & -16); - icrafting.sendProgressBarUpdate(this, 4, this.field_178151_h[0]); - icrafting.sendProgressBarUpdate(this, 5, this.field_178151_h[1]); - icrafting.sendProgressBarUpdate(this, 6, this.field_178151_h[2]); + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.worldPointer.getBlockState(this.position).getBlock() != Blocks.enchanting_table ? false + : entityplayer.getDistanceSq((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, + (double) this.position.getZ() + 0.5D) <= 64.0D; } - /**+ - * Looks for changes made in the container, sends them to every - * listener. + /** + * + Looks for changes made in the container, sends them to every listener. */ public void detectAndSendChanges() { super.detectAndSendChanges(); @@ -123,21 +121,101 @@ public class ContainerEnchantment extends Container { } - public void updateProgressBar(int i, int j) { - if (i >= 0 && i <= 2) { - this.enchantLevels[i] = j; - } else if (i == 3) { - this.xpSeed = j; - } else if (i >= 4 && i <= 6) { - this.field_178151_h[i - 4] = j; - } else { - super.updateProgressBar(i, j); - } + /** + * + Handles the given Button-click on the server, currently only used by + * enchanting. Name is for legacy. + */ + public boolean enchantItem(EntityPlayer entityplayer, int i) { + ItemStack itemstack = this.tableInventory.getStackInSlot(0); + ItemStack itemstack1 = this.tableInventory.getStackInSlot(1); + int j = i + 1; + if ((itemstack1 == null || itemstack1.stackSize < j) && !entityplayer.capabilities.isCreativeMode) { + return false; + } else if (this.enchantLevels[i] > 0 && itemstack != null + && (entityplayer.experienceLevel >= j && entityplayer.experienceLevel >= this.enchantLevels[i] + || entityplayer.capabilities.isCreativeMode)) { + if (!this.worldPointer.isRemote) { + List list = this.func_178148_a(itemstack, i, this.enchantLevels[i]); + boolean flag = itemstack.getItem() == Items.book; + if (list != null) { + entityplayer.removeExperienceLevel(j); + if (flag) { + itemstack.setItem(Items.enchanted_book); + } + for (int k = 0; k < list.size(); ++k) { + EnchantmentData enchantmentdata = (EnchantmentData) list.get(k); + if (flag) { + Items.enchanted_book.addEnchantment(itemstack, enchantmentdata); + } else { + itemstack.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); + } + } + + if (!entityplayer.capabilities.isCreativeMode) { + itemstack1.stackSize -= j; + if (itemstack1.stackSize <= 0) { + this.tableInventory.setInventorySlotContents(1, (ItemStack) null); + } + } + + entityplayer.triggerAchievement(StatList.field_181739_W); + this.tableInventory.markDirty(); + this.xpSeed = entityplayer.getXPSeed(); + this.onCraftMatrixChanged(this.tableInventory); + } + } + + return true; + } else { + return false; + } } - /**+ - * Callback for when the crafting matrix is changed. + private List func_178148_a(ItemStack stack, int parInt1, int parInt2) { + this.rand.setSeed((long) (this.xpSeed + parInt1)); + List list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, parInt2); + if (stack.getItem() == Items.book && list != null && list.size() > 1) { + list.remove(this.rand.nextInt(list.size())); + } + + return list; + } + + public int getLapisAmount() { + ItemStack itemstack = this.tableInventory.getStackInSlot(1); + return itemstack == null ? 0 : itemstack.stackSize; + } + + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + if (!this.worldPointer.isRemote) { + for (int i = 0; i < this.tableInventory.getSizeInventory(); ++i) { + ItemStack itemstack = this.tableInventory.removeStackFromSlot(i); + if (itemstack != null) { + entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + + } + } + + public void onCraftGuiOpened(ICrafting icrafting) { + super.onCraftGuiOpened(icrafting); + icrafting.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); + icrafting.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); + icrafting.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); + icrafting.sendProgressBarUpdate(this, 3, this.xpSeed & -16); + icrafting.sendProgressBarUpdate(this, 4, this.field_178151_h[0]); + icrafting.sendProgressBarUpdate(this, 5, this.field_178151_h[1]); + icrafting.sendProgressBarUpdate(this, 6, this.field_178151_h[2]); + } + + /** + * + Callback for when the crafting matrix is changed. */ public void onCraftMatrixChanged(IInventory iinventory) { if (iinventory == this.tableInventory) { @@ -220,96 +298,8 @@ public class ContainerEnchantment extends Container { } - /**+ - * Handles the given Button-click on the server, currently only - * used by enchanting. Name is for legacy. - */ - public boolean enchantItem(EntityPlayer entityplayer, int i) { - ItemStack itemstack = this.tableInventory.getStackInSlot(0); - ItemStack itemstack1 = this.tableInventory.getStackInSlot(1); - int j = i + 1; - if ((itemstack1 == null || itemstack1.stackSize < j) && !entityplayer.capabilities.isCreativeMode) { - return false; - } else if (this.enchantLevels[i] > 0 && itemstack != null - && (entityplayer.experienceLevel >= j && entityplayer.experienceLevel >= this.enchantLevels[i] - || entityplayer.capabilities.isCreativeMode)) { - if (!this.worldPointer.isRemote) { - List list = this.func_178148_a(itemstack, i, this.enchantLevels[i]); - boolean flag = itemstack.getItem() == Items.book; - if (list != null) { - entityplayer.removeExperienceLevel(j); - if (flag) { - itemstack.setItem(Items.enchanted_book); - } - - for (int k = 0; k < list.size(); ++k) { - EnchantmentData enchantmentdata = (EnchantmentData) list.get(k); - if (flag) { - Items.enchanted_book.addEnchantment(itemstack, enchantmentdata); - } else { - itemstack.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); - } - } - - if (!entityplayer.capabilities.isCreativeMode) { - itemstack1.stackSize -= j; - if (itemstack1.stackSize <= 0) { - this.tableInventory.setInventorySlotContents(1, (ItemStack) null); - } - } - - entityplayer.triggerAchievement(StatList.field_181739_W); - this.tableInventory.markDirty(); - this.xpSeed = entityplayer.getXPSeed(); - this.onCraftMatrixChanged(this.tableInventory); - } - } - - return true; - } else { - return false; - } - } - - private List func_178148_a(ItemStack stack, int parInt1, int parInt2) { - this.rand.setSeed((long) (this.xpSeed + parInt1)); - List list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, parInt2); - if (stack.getItem() == Items.book && list != null && list.size() > 1) { - list.remove(this.rand.nextInt(list.size())); - } - - return list; - } - - public int getLapisAmount() { - ItemStack itemstack = this.tableInventory.getStackInSlot(1); - return itemstack == null ? 0 : itemstack.stackSize; - } - - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - if (!this.worldPointer.isRemote) { - for (int i = 0; i < this.tableInventory.getSizeInventory(); ++i) { - ItemStack itemstack = this.tableInventory.removeStackFromSlot(i); - if (itemstack != null) { - entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); - } - } - - } - } - - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.worldPointer.getBlockState(this.position).getBlock() != Blocks.enchanting_table ? false - : entityplayer.getDistanceSq((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, - (double) this.position.getZ() + 0.5D) <= 64.0D; - } - - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -361,4 +351,17 @@ public class ContainerEnchantment extends Container { return itemstack; } + + public void updateProgressBar(int i, int j) { + if (i >= 0 && i <= 2) { + this.enchantLevels[i] = j; + } else if (i == 3) { + this.xpSeed = j; + } else if (i >= 4 && i <= 6) { + this.field_178151_h[i - 4] = j; + } else { + super.updateProgressBar(i, j); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerFabricator.java b/src/game/java/net/minecraft/inventory/ContainerFabricator.java new file mode 100644 index 00000000..062cd2b0 --- /dev/null +++ b/src/game/java/net/minecraft/inventory/ContainerFabricator.java @@ -0,0 +1,148 @@ +package net.minecraft.inventory; + +import net.minecraft.entity.player.EntityPlayer; +import net.minecraft.entity.player.InventoryPlayer; +import net.minecraft.init.Blocks; +import net.minecraft.item.ItemStack; +import net.minecraft.item.crafting.FabricatorManager; +import net.minecraft.util.BlockPos; +import net.minecraft.world.World; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class ContainerFabricator extends Container { + /** + * + The crafting matrix inventory (4x4). + */ + public InventoryCrafting craftMatrix = new InventoryCrafting(this, 3, 3); + public IInventory craftResult = new InventoryCraftResult(); + private World worldObj; + private BlockPos pos; + + public ContainerFabricator(InventoryPlayer playerInventory, World worldIn, BlockPos posIn) { + this.worldObj = worldIn; + this.pos = posIn; + this.addSlotToContainer( + new SlotCrafting(playerInventory.player, this.craftMatrix, this.craftResult, 0, 124, 35)); + + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) { + this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 3, 30 + j * 18, 17 + i * 18)); + } + } + + for (int k = 0; k < 3; ++k) { + for (int i1 = 0; i1 < 9; ++i1) { + this.addSlotToContainer(new Slot(playerInventory, i1 + k * 9 + 9, 8 + i1 * 18, 84 + k * 18)); + } + } + + for (int l = 0; l < 9; ++l) { + this.addSlotToContainer(new Slot(playerInventory, l, 8 + l * 18, 142)); + } + + this.onCraftMatrixChanged(this.craftMatrix); + } + + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.worldObj.getBlockState(this.pos).getBlock() != Blocks.fabricator ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + /** + * + Called to determine if the current slot is valid for the stack merging + * (double-click) code. The stack passed in is null for the initial slot that + * was double-clicked. + */ + public boolean canMergeSlot(ItemStack itemstack, Slot slot) { + return slot.inventory != this.craftResult && super.canMergeSlot(itemstack, slot); + } + + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + if (!this.worldObj.isRemote) { + for (int i = 0; i < 9; ++i) { + ItemStack itemstack = this.craftMatrix.removeStackFromSlot(i); + if (itemstack != null) { + entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + } + } + + /** + * + Callback for when the crafting matrix is changed. + */ + public void onCraftMatrixChanged(IInventory var1) { + this.craftResult.setInventorySlotContents(0, + FabricatorManager.getInstance().findMatchingRecipe(this.craftMatrix, this.worldObj)); + } + + /** + * + Take a stack from the specified inventory slot. + */ + public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(i); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (i == 0) { + if (!this.mergeItemStack(itemstack1, 10, 46, true)) { + return null; + } + + slot.onSlotChange(itemstack1, itemstack); + } else if (i >= 10 && i < 37) { + if (!this.mergeItemStack(itemstack1, 37, 46, false)) { + return null; + } + } else if (i >= 37 && i < 46) { + if (!this.mergeItemStack(itemstack1, 10, 37, false)) { + return null; + } + } else if (!this.mergeItemStack(itemstack1, 10, 46, false)) { + return null; + } + + if (itemstack1.stackSize == 0) { + slot.putStack((ItemStack) null); + } else { + slot.onSlotChanged(); + } + + if (itemstack1.stackSize == itemstack.stackSize) { + return null; + } + + slot.onPickupFromSlot(entityplayer, itemstack1); + } + + return itemstack; + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerFurnace.java b/src/game/java/net/minecraft/inventory/ContainerFurnace.java index ad910fd0..3b3ba130 100644 --- a/src/game/java/net/minecraft/inventory/ContainerFurnace.java +++ b/src/game/java/net/minecraft/inventory/ContainerFurnace.java @@ -6,22 +6,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.tileentity.TileEntityFurnace; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -51,14 +54,12 @@ public class ContainerFurnace extends Container { } - public void onCraftGuiOpened(ICrafting icrafting) { - super.onCraftGuiOpened(icrafting); - icrafting.func_175173_a(this, this.tileFurnace); + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.tileFurnace.isUseableByPlayer(entityplayer); } - /**+ - * Looks for changes made in the container, sends them to every - * listener. + /** + * + Looks for changes made in the container, sends them to every listener. */ public void detectAndSendChanges() { super.detectAndSendChanges(); @@ -88,16 +89,13 @@ public class ContainerFurnace extends Container { this.field_178153_g = this.tileFurnace.getField(3); } - public void updateProgressBar(int i, int j) { - this.tileFurnace.setField(i, j); + public void onCraftGuiOpened(ICrafting icrafting) { + super.onCraftGuiOpened(icrafting); + icrafting.func_175173_a(this, this.tileFurnace); } - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.tileFurnace.isUseableByPlayer(entityplayer); - } - - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -146,4 +144,8 @@ public class ContainerFurnace extends Container { return itemstack; } + + public void updateProgressBar(int i, int j) { + this.tileFurnace.setField(i, j); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerHopper.java b/src/game/java/net/minecraft/inventory/ContainerHopper.java index e45e7784..d39c5edf 100644 --- a/src/game/java/net/minecraft/inventory/ContainerHopper.java +++ b/src/game/java/net/minecraft/inventory/ContainerHopper.java @@ -4,22 +4,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,8 +55,16 @@ public class ContainerHopper extends Container { return this.hopperInventory.isUseableByPlayer(entityplayer); } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + this.hopperInventory.closeInventory(entityplayer); + } + + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer var1, int i) { ItemStack itemstack = null; @@ -79,12 +90,4 @@ public class ContainerHopper extends Container { return itemstack; } - - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - this.hopperInventory.closeInventory(entityplayer); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerHorseInventory.java b/src/game/java/net/minecraft/inventory/ContainerHorseInventory.java index 353df0d5..3e72285b 100644 --- a/src/game/java/net/minecraft/inventory/ContainerHorseInventory.java +++ b/src/game/java/net/minecraft/inventory/ContainerHorseInventory.java @@ -5,22 +5,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,14 +45,14 @@ public class ContainerHorseInventory extends Container { } }); this.addSlotToContainer(new Slot(horseInventoryIn, 1, 8, 36) { + public boolean canBeHovered() { + return horse.canWearArmor(); + } + public boolean isItemValid(ItemStack itemstack) { return super.isItemValid(itemstack) && horse.canWearArmor() && EntityHorse.isArmorItem(itemstack.getItem()); } - - public boolean canBeHovered() { - return horse.canWearArmor(); - } }); if (horse.isChested()) { for (int j = 0; j < b0; ++j) { @@ -76,8 +79,16 @@ public class ContainerHorseInventory extends Container { && this.theHorse.getDistanceToEntity(entityplayer) < 8.0F; } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + this.horseInventory.closeInventory(entityplayer); + } + + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer var1, int i) { ItemStack itemstack = null; @@ -112,12 +123,4 @@ public class ContainerHorseInventory extends Container { return itemstack; } - - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - this.horseInventory.closeInventory(entityplayer); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerMerchant.java b/src/game/java/net/minecraft/inventory/ContainerMerchant.java index 23f2ecff..ddb66a30 100644 --- a/src/game/java/net/minecraft/inventory/ContainerMerchant.java +++ b/src/game/java/net/minecraft/inventory/ContainerMerchant.java @@ -6,22 +6,25 @@ import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,24 +55,47 @@ public class ContainerMerchant extends Container { } + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.theMerchant.getCustomer() == entityplayer; + } + + /** + * + Looks for changes made in the container, sends them to every listener. + */ + public void detectAndSendChanges() { + super.detectAndSendChanges(); + } + public InventoryMerchant getMerchantInventory() { return this.merchantInventory; } + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + this.theMerchant.setCustomer((EntityPlayer) null); + super.onContainerClosed(entityplayer); + if (!this.theWorld.isRemote) { + ItemStack itemstack = this.merchantInventory.removeStackFromSlot(0); + if (itemstack != null) { + entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); + } + + itemstack = this.merchantInventory.removeStackFromSlot(1); + if (itemstack != null) { + entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + } + public void onCraftGuiOpened(ICrafting icrafting) { super.onCraftGuiOpened(icrafting); } - /**+ - * Looks for changes made in the container, sends them to every - * listener. - */ - public void detectAndSendChanges() { - super.detectAndSendChanges(); - } - - /**+ - * Callback for when the crafting matrix is changed. + /** + * + Callback for when the crafting matrix is changed. */ public void onCraftMatrixChanged(IInventory iinventory) { this.merchantInventory.resetRecipeAndSlots(); @@ -80,15 +106,8 @@ public class ContainerMerchant extends Container { this.merchantInventory.setCurrentRecipeIndex(currentRecipeIndex); } - public void updateProgressBar(int var1, int var2) { - } - - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.theMerchant.getCustomer() == entityplayer; - } - - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -130,23 +149,6 @@ public class ContainerMerchant extends Container { return itemstack; } - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - this.theMerchant.setCustomer((EntityPlayer) null); - super.onContainerClosed(entityplayer); - if (!this.theWorld.isRemote) { - ItemStack itemstack = this.merchantInventory.removeStackFromSlot(0); - if (itemstack != null) { - entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); - } - - itemstack = this.merchantInventory.removeStackFromSlot(1); - if (itemstack != null) { - entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); - } - } + public void updateProgressBar(int var1, int var2) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerPlayer.java b/src/game/java/net/minecraft/inventory/ContainerPlayer.java index 6ef5459b..eae4916f 100644 --- a/src/game/java/net/minecraft/inventory/ContainerPlayer.java +++ b/src/game/java/net/minecraft/inventory/ContainerPlayer.java @@ -9,29 +9,32 @@ import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ContainerPlayer extends Container { - /**+ - * The crafting matrix inventory. + /** + * + The crafting matrix inventory. */ public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2); public IInventory craftResult = new InventoryCraftResult(); @@ -58,6 +61,10 @@ public class ContainerPlayer extends Container { return 1; } + public String getSlotTexture() { + return ItemArmor.EMPTY_SLOT_NAMES[k2]; + } + public boolean isItemValid(ItemStack itemstack) { return itemstack == null ? false : (itemstack.getItem() instanceof ItemArmor @@ -65,10 +72,6 @@ public class ContainerPlayer extends Container { : (itemstack.getItem() != Item.getItemFromBlock(Blocks.pumpkin) && itemstack.getItem() != Items.skull ? false : k2 == 0)); } - - public String getSlotTexture() { - return ItemArmor.EMPTY_SLOT_NAMES[k2]; - } }); } @@ -85,16 +88,21 @@ public class ContainerPlayer extends Container { this.onCraftMatrixChanged(this.craftMatrix); } - /**+ - * Callback for when the crafting matrix is changed. - */ - public void onCraftMatrixChanged(IInventory var1) { - this.craftResult.setInventorySlotContents(0, - CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj)); + public boolean canInteractWith(EntityPlayer var1) { + return true; } - /**+ - * Called when the container is closed. + /** + * + Called to determine if the current slot is valid for the stack merging + * (double-click) code. The stack passed in is null for the initial slot that + * was double-clicked. + */ + public boolean canMergeSlot(ItemStack itemstack, Slot slot) { + return slot.inventory != this.craftResult && super.canMergeSlot(itemstack, slot); + } + + /** + * + Called when the container is closed. */ public void onContainerClosed(EntityPlayer entityplayer) { super.onContainerClosed(entityplayer); @@ -109,12 +117,16 @@ public class ContainerPlayer extends Container { this.craftResult.setInventorySlotContents(0, (ItemStack) null); } - public boolean canInteractWith(EntityPlayer var1) { - return true; + /** + * + Callback for when the crafting matrix is changed. + */ + public void onCraftMatrixChanged(IInventory var1) { + this.craftResult.setInventorySlotContents(0, + CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj)); } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -170,13 +182,4 @@ public class ContainerPlayer extends Container { return itemstack; } - - /**+ - * Called to determine if the current slot is valid for the - * stack merging (double-click) code. The stack passed in is - * null for the initial slot that was double-clicked. - */ - public boolean canMergeSlot(ItemStack itemstack, Slot slot) { - return slot.inventory != this.craftResult && super.canMergeSlot(itemstack, slot); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerRepair.java b/src/game/java/net/minecraft/inventory/ContainerRepair.java index 6ca923fb..a32b9405 100644 --- a/src/game/java/net/minecraft/inventory/ContainerRepair.java +++ b/src/game/java/net/minecraft/inventory/ContainerRepair.java @@ -2,6 +2,11 @@ package net.minecraft.inventory; import java.util.Iterator; import java.util.Map; + +import org.apache.commons.lang3.StringUtils; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.block.BlockAnvil; import net.minecraft.block.state.IBlockState; import net.minecraft.enchantment.Enchantment; @@ -13,26 +18,26 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -import org.apache.commons.lang3.StringUtils; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,10 +53,6 @@ public class ContainerRepair extends Container { private String repairedItemName; private final EntityPlayer thePlayer; - public ContainerRepair(InventoryPlayer playerInventory, World worldIn, EntityPlayer player) { - this(playerInventory, worldIn, BlockPos.ORIGIN, player); - } - public ContainerRepair(InventoryPlayer playerInventory, final World worldIn, final BlockPos blockPosIn, EntityPlayer player) { this.outputSlot = new InventoryCraftResult(); @@ -67,16 +68,16 @@ public class ContainerRepair extends Container { this.addSlotToContainer(new Slot(this.inputSlots, 0, 27, 47)); this.addSlotToContainer(new Slot(this.inputSlots, 1, 76, 47)); this.addSlotToContainer(new Slot(this.outputSlot, 2, 134, 47) { - public boolean isItemValid(ItemStack var1) { - return false; - } - public boolean canTakeStack(EntityPlayer playerIn) { return (playerIn.capabilities.isCreativeMode || playerIn.experienceLevel >= ContainerRepair.this.maximumCost) && ContainerRepair.this.maximumCost > 0 && this.getHasStack(); } + public boolean isItemValid(ItemStack var1) { + return false; + } + public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack var2) { if (!entityplayer.capabilities.isCreativeMode) { entityplayer.addExperienceLevel(-ContainerRepair.this.maximumCost); @@ -128,8 +129,39 @@ public class ContainerRepair extends Container { } - /**+ - * Callback for when the crafting matrix is changed. + public ContainerRepair(InventoryPlayer playerInventory, World worldIn, EntityPlayer player) { + this(playerInventory, worldIn, BlockPos.ORIGIN, player); + } + + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.theWorld.getBlockState(this.selfPosition).getBlock() != Blocks.anvil ? false + : entityplayer.getDistanceSq((double) this.selfPosition.getX() + 0.5D, + (double) this.selfPosition.getY() + 0.5D, (double) this.selfPosition.getZ() + 0.5D) <= 64.0D; + } + + /** + * + Called when the container is closed. + */ + public void onContainerClosed(EntityPlayer entityplayer) { + super.onContainerClosed(entityplayer); + if (!this.theWorld.isRemote) { + for (int i = 0; i < this.inputSlots.getSizeInventory(); ++i) { + ItemStack itemstack = this.inputSlots.removeStackFromSlot(i); + if (itemstack != null) { + entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + + } + } + + public void onCraftGuiOpened(ICrafting icrafting) { + super.onCraftGuiOpened(icrafting); + icrafting.sendProgressBarUpdate(this, 0, this.maximumCost); + } + + /** + * + Callback for when the crafting matrix is changed. */ public void onCraftMatrixChanged(IInventory iinventory) { super.onCraftMatrixChanged(iinventory); @@ -139,9 +171,72 @@ public class ContainerRepair extends Container { } - /**+ - * called when the Anvil Input Slot changes, calculates the new - * result and puts it in the output slot + /** + * + Take a stack from the specified inventory slot. + */ + public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { + ItemStack itemstack = null; + Slot slot = (Slot) this.inventorySlots.get(i); + if (slot != null && slot.getHasStack()) { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + if (i == 2) { + if (!this.mergeItemStack(itemstack1, 3, 39, true)) { + return null; + } + + slot.onSlotChange(itemstack1, itemstack); + } else if (i != 0 && i != 1) { + if (i >= 3 && i < 39 && !this.mergeItemStack(itemstack1, 0, 2, false)) { + return null; + } + } else if (!this.mergeItemStack(itemstack1, 3, 39, false)) { + return null; + } + + if (itemstack1.stackSize == 0) { + slot.putStack((ItemStack) null); + } else { + slot.onSlotChanged(); + } + + if (itemstack1.stackSize == itemstack.stackSize) { + return null; + } + + slot.onPickupFromSlot(entityplayer, itemstack1); + } + + return itemstack; + } + + /** + * + used by the Anvil GUI to update the Item Name being typed by the player + */ + public void updateItemName(String newName) { + this.repairedItemName = newName; + if (this.getSlot(2).getHasStack()) { + ItemStack itemstack = this.getSlot(2).getStack(); + if (StringUtils.isBlank(newName)) { + itemstack.clearCustomName(); + } else { + itemstack.setStackDisplayName(this.repairedItemName); + } + } + + this.updateRepairOutput(); + } + + public void updateProgressBar(int i, int j) { + if (i == 0) { + this.maximumCost = j; + } + + } + + /** + * + called when the Anvil Input Slot changes, calculates the new result and + * puts it in the output slot */ public void updateRepairOutput() { boolean flag = false; @@ -325,95 +420,4 @@ public class ContainerRepair extends Container { this.detectAndSendChanges(); } } - - public void onCraftGuiOpened(ICrafting icrafting) { - super.onCraftGuiOpened(icrafting); - icrafting.sendProgressBarUpdate(this, 0, this.maximumCost); - } - - public void updateProgressBar(int i, int j) { - if (i == 0) { - this.maximumCost = j; - } - - } - - /**+ - * Called when the container is closed. - */ - public void onContainerClosed(EntityPlayer entityplayer) { - super.onContainerClosed(entityplayer); - if (!this.theWorld.isRemote) { - for (int i = 0; i < this.inputSlots.getSizeInventory(); ++i) { - ItemStack itemstack = this.inputSlots.removeStackFromSlot(i); - if (itemstack != null) { - entityplayer.dropPlayerItemWithRandomChoice(itemstack, false); - } - } - - } - } - - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.theWorld.getBlockState(this.selfPosition).getBlock() != Blocks.anvil ? false - : entityplayer.getDistanceSq((double) this.selfPosition.getX() + 0.5D, - (double) this.selfPosition.getY() + 0.5D, (double) this.selfPosition.getZ() + 0.5D) <= 64.0D; - } - - /**+ - * Take a stack from the specified inventory slot. - */ - public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { - ItemStack itemstack = null; - Slot slot = (Slot) this.inventorySlots.get(i); - if (slot != null && slot.getHasStack()) { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - if (i == 2) { - if (!this.mergeItemStack(itemstack1, 3, 39, true)) { - return null; - } - - slot.onSlotChange(itemstack1, itemstack); - } else if (i != 0 && i != 1) { - if (i >= 3 && i < 39 && !this.mergeItemStack(itemstack1, 0, 2, false)) { - return null; - } - } else if (!this.mergeItemStack(itemstack1, 3, 39, false)) { - return null; - } - - if (itemstack1.stackSize == 0) { - slot.putStack((ItemStack) null); - } else { - slot.onSlotChanged(); - } - - if (itemstack1.stackSize == itemstack.stackSize) { - return null; - } - - slot.onPickupFromSlot(entityplayer, itemstack1); - } - - return itemstack; - } - - /**+ - * used by the Anvil GUI to update the Item Name being typed by - * the player - */ - public void updateItemName(String newName) { - this.repairedItemName = newName; - if (this.getSlot(2).getHasStack()) { - ItemStack itemstack = this.getSlot(2).getStack(); - if (StringUtils.isBlank(newName)) { - itemstack.clearCustomName(); - } else { - itemstack.setStackDisplayName(this.repairedItemName); - } - } - - this.updateRepairOutput(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ContainerWorkbench.java b/src/game/java/net/minecraft/inventory/ContainerWorkbench.java index 122d5519..7c48d75e 100644 --- a/src/game/java/net/minecraft/inventory/ContainerWorkbench.java +++ b/src/game/java/net/minecraft/inventory/ContainerWorkbench.java @@ -8,29 +8,32 @@ import net.minecraft.item.crafting.CraftingManager; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ContainerWorkbench extends Container { - /**+ - * The crafting matrix inventory (3x3). + /** + * + The crafting matrix inventory (3x3). */ public InventoryCrafting craftMatrix = new InventoryCrafting(this, 3, 3); public IInventory craftResult = new InventoryCraftResult(); @@ -62,16 +65,23 @@ public class ContainerWorkbench extends Container { this.onCraftMatrixChanged(this.craftMatrix); } - /**+ - * Callback for when the crafting matrix is changed. - */ - public void onCraftMatrixChanged(IInventory var1) { - this.craftResult.setInventorySlotContents(0, - CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.worldObj)); + public boolean canInteractWith(EntityPlayer entityplayer) { + return this.worldObj.getBlockState(this.pos).getBlock() != Blocks.crafting_table ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; } - /**+ - * Called when the container is closed. + /** + * + Called to determine if the current slot is valid for the stack merging + * (double-click) code. The stack passed in is null for the initial slot that + * was double-clicked. + */ + public boolean canMergeSlot(ItemStack itemstack, Slot slot) { + return slot.inventory != this.craftResult && super.canMergeSlot(itemstack, slot); + } + + /** + * + Called when the container is closed. */ public void onContainerClosed(EntityPlayer entityplayer) { super.onContainerClosed(entityplayer); @@ -85,14 +95,16 @@ public class ContainerWorkbench extends Container { } } - public boolean canInteractWith(EntityPlayer entityplayer) { - return this.worldObj.getBlockState(this.pos).getBlock() != Blocks.crafting_table ? false - : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; + /** + * + Callback for when the crafting matrix is changed. + */ + public void onCraftMatrixChanged(IInventory var1) { + this.craftResult.setInventorySlotContents(0, + CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.worldObj)); } - /**+ - * Take a stack from the specified inventory slot. + /** + * + Take a stack from the specified inventory slot. */ public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { ItemStack itemstack = null; @@ -133,13 +145,4 @@ public class ContainerWorkbench extends Container { return itemstack; } - - /**+ - * Called to determine if the current slot is valid for the - * stack merging (double-click) code. The stack passed in is - * null for the initial slot that was double-clicked. - */ - public boolean canMergeSlot(ItemStack itemstack, Slot slot) { - return slot.inventory != this.craftResult && super.canMergeSlot(itemstack, slot); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ICrafting.java b/src/game/java/net/minecraft/inventory/ICrafting.java index 5bee2a31..ec206154 100644 --- a/src/game/java/net/minecraft/inventory/ICrafting.java +++ b/src/game/java/net/minecraft/inventory/ICrafting.java @@ -4,48 +4,49 @@ import java.util.List; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ICrafting { - /**+ - * update the crafting window inventory with the items in the - * list - */ - void updateCraftingInventory(Container var1, List var2); + void func_175173_a(Container var1, IInventory var2); - /**+ - * Sends the contents of an inventory slot to the client-side - * Container. This doesn't have to match the actual contents of - * that slot. Args: Container, slot number, slot contents - */ - void sendSlotContents(Container var1, int var2, ItemStack var3); - - /**+ - * Sends two ints to the client-side Container. Used for furnace - * burning time, smelting progress, brewing progress, and - * enchanting level. Normally the first int identifies which - * variable to update, and the second contains the new value. - * Both are truncated to shorts in non-local SMP. + /** + * + Sends two ints to the client-side Container. Used for furnace burning time, + * smelting progress, brewing progress, and enchanting level. Normally the first + * int identifies which variable to update, and the second contains the new + * value. Both are truncated to shorts in non-local SMP. */ void sendProgressBarUpdate(Container var1, int var2, int var3); - void func_175173_a(Container var1, IInventory var2); + /** + * + Sends the contents of an inventory slot to the client-side Container. This + * doesn't have to match the actual contents of that slot. Args: Container, slot + * number, slot contents + */ + void sendSlotContents(Container var1, int var2, ItemStack var3); + + /** + * + update the crafting window inventory with the items in the list + */ + void updateCraftingInventory(Container var1, List var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/IInvBasic.java b/src/game/java/net/minecraft/inventory/IInvBasic.java index b413898e..16765735 100644 --- a/src/game/java/net/minecraft/inventory/IInvBasic.java +++ b/src/game/java/net/minecraft/inventory/IInvBasic.java @@ -1,29 +1,32 @@ package net.minecraft.inventory; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IInvBasic { - /**+ - * Called by InventoryBasic.onInventoryChanged() on a array that - * is never filled. + /** + * + Called by InventoryBasic.onInventoryChanged() on a array that is never + * filled. */ void onInventoryChanged(InventoryBasic var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/IInventory.java b/src/game/java/net/minecraft/inventory/IInventory.java index 27f26de1..0e0a14ba 100644 --- a/src/game/java/net/minecraft/inventory/IInventory.java +++ b/src/game/java/net/minecraft/inventory/IInventory.java @@ -4,88 +4,90 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.world.IWorldNameable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IInventory extends IWorldNameable { - /**+ - * Returns the number of slots in the inventory. - */ - int getSizeInventory(); - - /**+ - * Returns the stack in the given slot. - */ - ItemStack getStackInSlot(int var1); - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. - */ - ItemStack decrStackSize(int var1, int var2); - - /**+ - * Removes a stack from the given slot and returns it. - */ - ItemStack removeStackFromSlot(int var1); - - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - void setInventorySlotContents(int var1, ItemStack var2); - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - int getInventoryStackLimit(); - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - void markDirty(); - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - boolean isUseableByPlayer(EntityPlayer var1); - - void openInventory(EntityPlayer var1); + void clear(); void closeInventory(EntityPlayer var1); - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ - boolean isItemValidForSlot(int var1, ItemStack var2); + ItemStack decrStackSize(int var1, int var2); int getField(int var1); - void setField(int var1, int var2); - int getFieldCount(); - void clear(); + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + int getInventoryStackLimit(); + + /** + * + Returns the number of slots in the inventory. + */ + int getSizeInventory(); + + /** + * + Returns the stack in the given slot. + */ + ItemStack getStackInSlot(int var1); + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + boolean isItemValidForSlot(int var1, ItemStack var2); + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + boolean isUseableByPlayer(EntityPlayer var1); + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + void markDirty(); + + void openInventory(EntityPlayer var1); + + /** + * + Removes a stack from the given slot and returns it. + */ + ItemStack removeStackFromSlot(int var1); + + void setField(int var1, int var2); + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + void setInventorySlotContents(int var1, ItemStack var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/ISidedInventory.java b/src/game/java/net/minecraft/inventory/ISidedInventory.java index eedd3605..91f5318b 100644 --- a/src/game/java/net/minecraft/inventory/ISidedInventory.java +++ b/src/game/java/net/minecraft/inventory/ISidedInventory.java @@ -3,38 +3,41 @@ package net.minecraft.inventory; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ISidedInventory extends IInventory { - int[] getSlotsForFace(EnumFacing var1); + /** + * + Returns true if automation can extract the given item in the given slot + * from the given side. Args: slot, item, side + */ + boolean canExtractItem(int var1, ItemStack var2, EnumFacing var3); - /**+ - * Returns true if automation can insert the given item in the - * given slot from the given side. Args: slot, item, side + /** + * + Returns true if automation can insert the given item in the given slot from + * the given side. Args: slot, item, side */ boolean canInsertItem(int var1, ItemStack var2, EnumFacing var3); - /**+ - * Returns true if automation can extract the given item in the - * given slot from the given side. Args: slot, item, side - */ - boolean canExtractItem(int var1, ItemStack var2, EnumFacing var3); + int[] getSlotsForFace(EnumFacing var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/InventoryBasic.java b/src/game/java/net/minecraft/inventory/InventoryBasic.java index 2e35ead2..977bc95c 100644 --- a/src/game/java/net/minecraft/inventory/InventoryBasic.java +++ b/src/game/java/net/minecraft/inventory/InventoryBasic.java @@ -10,22 +10,25 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +40,10 @@ public class InventoryBasic implements IInventory { private List field_70480_d; private boolean hasCustomName; + public InventoryBasic(IChatComponent title, int slotCount) { + this(title.getUnformattedText(), true, slotCount); + } + public InventoryBasic(String title, boolean customName, int slotCount) { this.inventoryTitle = title; this.hasCustomName = customName; @@ -44,32 +51,19 @@ public class InventoryBasic implements IInventory { this.inventoryContents = new ItemStack[slotCount]; } - public InventoryBasic(IChatComponent title, int slotCount) { - this(title.getUnformattedText(), true, slotCount); - } - - public void func_110134_a(IInvBasic parIInvBasic) { - if (this.field_70480_d == null) { - this.field_70480_d = Lists.newArrayList(); + public void clear() { + for (int i = 0; i < this.inventoryContents.length; ++i) { + this.inventoryContents[i] = null; } - this.field_70480_d.add(parIInvBasic); } - public void func_110132_b(IInvBasic parIInvBasic) { - this.field_70480_d.remove(parIInvBasic); + public void closeInventory(EntityPlayer var1) { } - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return i >= 0 && i < this.inventoryContents.length ? this.inventoryContents[i] : null; - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.inventoryContents[i] != null) { @@ -92,6 +86,18 @@ public class InventoryBasic implements IInventory { } } + public void func_110132_b(IInvBasic parIInvBasic) { + this.field_70480_d.remove(parIInvBasic); + } + + public void func_110134_a(IInvBasic parIInvBasic) { + if (this.field_70480_d == null) { + this.field_70480_d = Lists.newArrayList(); + } + + this.field_70480_d.add(parIInvBasic); + } + public ItemStack func_174894_a(ItemStack stack) { ItemStack itemstack = stack.copy(); @@ -124,8 +130,94 @@ public class InventoryBasic implements IInventory { return itemstack; } - /**+ - * Removes a stack from the given slot and returns it. + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.inventoryTitle; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.slotsCount; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return i >= 0 && i < this.inventoryContents.length ? this.inventoryContents[i] : null; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.hasCustomName; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer var1) { + return true; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + if (this.field_70480_d != null) { + for (int i = 0; i < this.field_70480_d.size(); ++i) { + ((IInvBasic) this.field_70480_d.get(i)).onInventoryChanged(this); + } + } + + } + + public void openInventory(EntityPlayer var1) { + } + + /** + * + Removes a stack from the given slot and returns it. */ public ItemStack removeStackFromSlot(int i) { if (this.inventoryContents[i] != null) { @@ -137,9 +229,21 @@ public class InventoryBasic implements IInventory { } } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). + /** + * + Sets the name of this inventory. This is displayed to the client on + * opening. + */ + public void setCustomName(String inventoryTitleIn) { + this.hasCustomName = true; + this.inventoryTitle = inventoryTitleIn; + } + + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). */ public void setInventorySlotContents(int i, ItemStack itemstack) { this.inventoryContents[i] = itemstack; @@ -149,106 +253,4 @@ public class InventoryBasic implements IInventory { this.markDirty(); } - - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return this.slotsCount; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.inventoryTitle; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.hasCustomName; - } - - /**+ - * Sets the name of this inventory. This is displayed to the - * client on opening. - */ - public void setCustomName(String inventoryTitleIn) { - this.hasCustomName = true; - this.inventoryTitle = inventoryTitleIn; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - if (this.field_70480_d != null) { - for (int i = 0; i < this.field_70480_d.size(); ++i) { - ((IInvBasic) this.field_70480_d.get(i)).onInventoryChanged(this); - } - } - - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer var1) { - return true; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } - - public void clear() { - for (int i = 0; i < this.inventoryContents.length; ++i) { - this.inventoryContents[i] = null; - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/InventoryCraftResult.java b/src/game/java/net/minecraft/inventory/InventoryCraftResult.java index 13c85988..53143d6c 100644 --- a/src/game/java/net/minecraft/inventory/InventoryCraftResult.java +++ b/src/game/java/net/minecraft/inventory/InventoryCraftResult.java @@ -6,74 +6,48 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class InventoryCraftResult implements IInventory { - /**+ - * A list of one item containing the result of the crafting - * formula + /** + * + A list of one item containing the result of the crafting formula */ private ItemStack[] stackResult = new ItemStack[1]; - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return 1; + public void clear() { + for (int i = 0; i < this.stackResult.length; ++i) { + this.stackResult[i] = null; + } + } - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int var1) { - return this.stackResult[0]; + public void closeInventory(EntityPlayer var1) { } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return "Result"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return false; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int var1, int var2) { if (this.stackResult[0] != null) { @@ -85,8 +59,88 @@ public class InventoryCraftResult implements IInventory { } } - /**+ - * Removes a stack from the given slot and returns it. + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return "Result"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return 1; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int var1) { + return this.stackResult[0]; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return false; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer var1) { + return true; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + } + + public void openInventory(EntityPlayer var1) { + } + + /** + * + Removes a stack from the given slot and returns it. */ public ItemStack removeStackFromSlot(int var1) { if (this.stackResult[0] != null) { @@ -98,67 +152,14 @@ public class InventoryCraftResult implements IInventory { } } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). */ public void setInventorySlotContents(int var1, ItemStack itemstack) { this.stackResult[0] = itemstack; } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer var1) { - return true; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } - - public void clear() { - for (int i = 0; i < this.stackResult.length; ++i) { - this.stackResult[i] = null; - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/InventoryCrafting.java b/src/game/java/net/minecraft/inventory/InventoryCrafting.java index 0b652126..f31df8f0 100644 --- a/src/game/java/net/minecraft/inventory/InventoryCrafting.java +++ b/src/game/java/net/minecraft/inventory/InventoryCrafting.java @@ -6,22 +6,25 @@ import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,70 +43,19 @@ public class InventoryCrafting implements IInventory { this.inventoryHeight = height; } - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return this.stackList.length; - } - - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return i >= this.getSizeInventory() ? null : this.stackList[i]; - } - - /**+ - * Returns the itemstack in the slot specified (Top left is 0, - * 0). Args: row, column - */ - public ItemStack getStackInRowAndColumn(int row, int column) { - return row >= 0 && row < this.inventoryWidth && column >= 0 && column <= this.inventoryHeight - ? this.getStackInSlot(row + column * this.inventoryWidth) - : null; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return "container.crafting"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return false; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (this.stackList[i] != null) { - ItemStack itemstack = this.stackList[i]; + public void clear() { + for (int i = 0; i < this.stackList.length; ++i) { this.stackList[i] = null; - return itemstack; - } else { - return null; } + } - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + public void closeInventory(EntityPlayer var1) { + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.stackList[i] != null) { @@ -126,76 +78,126 @@ public class InventoryCrafting implements IInventory { } } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - this.stackList[i] = itemstack; - this.eventHandler.onCraftMatrixChanged(this); - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer var1) { - return true; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); } public int getField(int var1) { return 0; } - public void setField(int var1, int var2) { - } - public int getFieldCount() { return 0; } - public void clear() { - for (int i = 0; i < this.stackList.length; ++i) { - this.stackList[i] = null; - } - - } - public int getHeight() { return this.inventoryHeight; } + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return "container.crafting"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.stackList.length; + } + + /** + * + Returns the itemstack in the slot specified (Top left is 0, 0). Args: row, + * column + */ + public ItemStack getStackInRowAndColumn(int row, int column) { + return row >= 0 && row < this.inventoryWidth && column >= 0 && column <= this.inventoryHeight + ? this.getStackInSlot(row + column * this.inventoryWidth) + : null; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return i >= this.getSizeInventory() ? null : this.stackList[i]; + } + public int getWidth() { return this.inventoryWidth; } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return false; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer var1) { + return true; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + } + + public void openInventory(EntityPlayer var1) { + } + + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + if (this.stackList[i] != null) { + ItemStack itemstack = this.stackList[i]; + this.stackList[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + this.stackList[i] = itemstack; + this.eventHandler.onCraftMatrixChanged(this); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/InventoryEnderChest.java b/src/game/java/net/minecraft/inventory/InventoryEnderChest.java index 63b2f55d..2e3b001c 100644 --- a/src/game/java/net/minecraft/inventory/InventoryEnderChest.java +++ b/src/game/java/net/minecraft/inventory/InventoryEnderChest.java @@ -6,22 +6,25 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntityEnderChest; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +36,22 @@ public class InventoryEnderChest extends InventoryBasic { super("container.enderchest", false, 27); } - public void setChestTileEntity(TileEntityEnderChest chestTileEntity) { - this.associatedChest = chestTileEntity; + public void closeInventory(EntityPlayer entityplayer) { + if (this.associatedChest != null) { + this.associatedChest.closeChest(); + } + + super.closeInventory(entityplayer); + this.associatedChest = null; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.associatedChest != null && !this.associatedChest.canBeUsed(entityplayer) ? false + : super.isUseableByPlayer(entityplayer); } public void loadInventoryFromNBT(NBTTagList parNBTTagList) { @@ -52,6 +69,14 @@ public class InventoryEnderChest extends InventoryBasic { } + public void openInventory(EntityPlayer entityplayer) { + if (this.associatedChest != null) { + this.associatedChest.openChest(); + } + + super.openInventory(entityplayer); + } + public NBTTagList saveInventoryToNBT() { NBTTagList nbttaglist = new NBTTagList(); @@ -68,29 +93,7 @@ public class InventoryEnderChest extends InventoryBasic { return nbttaglist; } - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.associatedChest != null && !this.associatedChest.canBeUsed(entityplayer) ? false - : super.isUseableByPlayer(entityplayer); - } - - public void openInventory(EntityPlayer entityplayer) { - if (this.associatedChest != null) { - this.associatedChest.openChest(); - } - - super.openInventory(entityplayer); - } - - public void closeInventory(EntityPlayer entityplayer) { - if (this.associatedChest != null) { - this.associatedChest.closeChest(); - } - - super.closeInventory(entityplayer); - this.associatedChest = null; + public void setChestTileEntity(TileEntityEnderChest chestTileEntity) { + this.associatedChest = chestTileEntity; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/InventoryHelper.java b/src/game/java/net/minecraft/inventory/InventoryHelper.java index 079362be..48b905ca 100644 --- a/src/game/java/net/minecraft/inventory/InventoryHelper.java +++ b/src/game/java/net/minecraft/inventory/InventoryHelper.java @@ -1,7 +1,6 @@ package net.minecraft.inventory; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; @@ -9,22 +8,25 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,10 +38,6 @@ public class InventoryHelper { func_180174_a(worldIn, (double) pos.getX(), (double) pos.getY(), (double) pos.getZ(), parIInventory); } - public static void func_180176_a(World worldIn, Entity parEntity, IInventory parIInventory) { - func_180174_a(worldIn, parEntity.posX, parEntity.posY, parEntity.posZ, parIInventory); - } - private static void func_180174_a(World worldIn, double x, double y, double z, IInventory parIInventory) { for (int i = 0; i < parIInventory.getSizeInventory(); ++i) { ItemStack itemstack = parIInventory.getStackInSlot(i); @@ -50,6 +48,10 @@ public class InventoryHelper { } + public static void func_180176_a(World worldIn, Entity parEntity, IInventory parIInventory) { + func_180174_a(worldIn, parEntity.posX, parEntity.posY, parEntity.posZ, parIInventory); + } + private static void spawnItemStack(World worldIn, double x, double y, double z, ItemStack stack) { float f = RANDOM.nextFloat() * 0.8F + 0.1F; float f1 = RANDOM.nextFloat() * 0.8F + 0.1F; diff --git a/src/game/java/net/minecraft/inventory/InventoryLargeChest.java b/src/game/java/net/minecraft/inventory/InventoryLargeChest.java index 2127c691..e15aa5ab 100644 --- a/src/game/java/net/minecraft/inventory/InventoryLargeChest.java +++ b/src/game/java/net/minecraft/inventory/InventoryLargeChest.java @@ -9,22 +9,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,58 +57,23 @@ public class InventoryLargeChest implements ILockableContainer { } - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return this.upperChest.getSizeInventory() + this.lowerChest.getSizeInventory(); + public void clear() { + this.upperChest.clear(); + this.lowerChest.clear(); } - /**+ - * Return whether the given inventory is part of this large - * chest. - */ - public boolean isPartOfLargeChest(IInventory inventoryIn) { - return this.upperChest == inventoryIn || this.lowerChest == inventoryIn; + public void closeInventory(EntityPlayer entityplayer) { + this.upperChest.closeInventory(entityplayer); + this.lowerChest.closeInventory(entityplayer); } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.upperChest.hasCustomName() ? this.upperChest.getName() - : (this.lowerChest.hasCustomName() ? this.lowerChest.getName() : this.name); + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { + return new ContainerChest(inventoryplayer, this, entityplayer); } - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.upperChest.hasCustomName() || this.lowerChest.hasCustomName(); - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return i >= this.upperChest.getSizeInventory() - ? this.lowerChest.getStackInSlot(i - this.upperChest.getSizeInventory()) - : this.upperChest.getStackInSlot(i); - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { return i >= this.upperChest.getSizeInventory() @@ -113,8 +81,114 @@ public class InventoryLargeChest implements ILockableContainer { : this.upperChest.decrStackSize(i, j); } - /**+ - * Removes a stack from the given slot and returns it. + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + public String getGuiID() { + return this.upperChest.getGuiID(); + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return this.upperChest.getInventoryStackLimit(); + } + + public LockCode getLockCode() { + return this.upperChest.getLockCode(); + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.upperChest.hasCustomName() ? this.upperChest.getName() + : (this.lowerChest.hasCustomName() ? this.lowerChest.getName() : this.name); + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.upperChest.getSizeInventory() + this.lowerChest.getSizeInventory(); + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return i >= this.upperChest.getSizeInventory() + ? this.lowerChest.getStackInSlot(i - this.upperChest.getSizeInventory()) + : this.upperChest.getStackInSlot(i); + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.upperChest.hasCustomName() || this.lowerChest.hasCustomName(); + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + public boolean isLocked() { + return this.upperChest.isLocked() || this.lowerChest.isLocked(); + } + + /** + * + Return whether the given inventory is part of this large chest. + */ + public boolean isPartOfLargeChest(IInventory inventoryIn) { + return this.upperChest == inventoryIn || this.lowerChest == inventoryIn; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.upperChest.isUseableByPlayer(entityplayer) && this.lowerChest.isUseableByPlayer(entityplayer); + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + this.upperChest.markDirty(); + this.lowerChest.markDirty(); + } + + public void openInventory(EntityPlayer entityplayer) { + this.upperChest.openInventory(entityplayer); + this.lowerChest.openInventory(entityplayer); + } + + /** + * + Removes a stack from the given slot and returns it. */ public ItemStack removeStackFromSlot(int i) { return i >= this.upperChest.getSizeInventory() @@ -122,9 +196,12 @@ public class InventoryLargeChest implements ILockableContainer { : this.upperChest.removeStackFromSlot(i); } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). */ public void setInventorySlotContents(int i, ItemStack itemstack) { if (i >= this.upperChest.getSizeInventory()) { @@ -135,84 +212,8 @@ public class InventoryLargeChest implements ILockableContainer { } - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return this.upperChest.getInventoryStackLimit(); - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - this.upperChest.markDirty(); - this.lowerChest.markDirty(); - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.upperChest.isUseableByPlayer(entityplayer) && this.lowerChest.isUseableByPlayer(entityplayer); - } - - public void openInventory(EntityPlayer entityplayer) { - this.upperChest.openInventory(entityplayer); - this.lowerChest.openInventory(entityplayer); - } - - public void closeInventory(EntityPlayer entityplayer) { - this.upperChest.closeInventory(entityplayer); - this.lowerChest.closeInventory(entityplayer); - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } - - public boolean isLocked() { - return this.upperChest.isLocked() || this.lowerChest.isLocked(); - } - public void setLockCode(LockCode lockcode) { this.upperChest.setLockCode(lockcode); this.lowerChest.setLockCode(lockcode); } - - public LockCode getLockCode() { - return this.upperChest.getLockCode(); - } - - public String getGuiID() { - return this.upperChest.getGuiID(); - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { - return new ContainerChest(inventoryplayer, this, entityplayer); - } - - public void clear() { - this.upperChest.clear(); - this.lowerChest.clear(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/InventoryMerchant.java b/src/game/java/net/minecraft/inventory/InventoryMerchant.java index b0b7d86e..07465ba5 100644 --- a/src/game/java/net/minecraft/inventory/InventoryMerchant.java +++ b/src/game/java/net/minecraft/inventory/InventoryMerchant.java @@ -9,22 +9,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.village.MerchantRecipe; import net.minecraft.village.MerchantRecipeList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,23 +44,19 @@ public class InventoryMerchant implements IInventory { this.theMerchant = theMerchantIn; } - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return this.theInventory.length; + public void clear() { + for (int i = 0; i < this.theInventory.length; ++i) { + this.theInventory[i] = null; + } + } - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return this.theInventory[i]; + public void closeInventory(EntityPlayer var1) { } - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.theInventory[i] != null) { @@ -90,16 +89,100 @@ public class InventoryMerchant implements IInventory { } } - /**+ - * if par1 slot has changed, does resetRecipeAndSlots need to be - * called? + public MerchantRecipe getCurrentRecipe() { + return this.currentRecipe; + } + + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return "mob.villager"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.theInventory.length; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return this.theInventory[i]; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return false; + } + + /** + * + if par1 slot has changed, does resetRecipeAndSlots need to be called? */ private boolean inventoryResetNeededOnSlotChange(int parInt1) { return parInt1 == 0 || parInt1 == 1; } - /**+ - * Removes a stack from the given slot and returns it. + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.theMerchant.getCustomer() == entityplayer; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + this.resetRecipeAndSlots(); + } + + public void openInventory(EntityPlayer var1) { + } + + /** + * + Removes a stack from the given slot and returns it. */ public ItemStack removeStackFromSlot(int i) { if (this.theInventory[i] != null) { @@ -111,85 +194,6 @@ public class InventoryMerchant implements IInventory { } } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - this.theInventory[i] = itemstack; - if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { - itemstack.stackSize = this.getInventoryStackLimit(); - } - - if (this.inventoryResetNeededOnSlotChange(i)) { - this.resetRecipeAndSlots(); - } - - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return "mob.villager"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return false; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.theMerchant.getCustomer() == entityplayer; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - this.resetRecipeAndSlots(); - } - public void resetRecipeAndSlots() { this.currentRecipe = null; ItemStack itemstack = this.theInventory[0]; @@ -226,29 +230,26 @@ public class InventoryMerchant implements IInventory { this.theMerchant.verifySellingItem(this.getStackInSlot(2)); } - public MerchantRecipe getCurrentRecipe() { - return this.currentRecipe; - } - public void setCurrentRecipeIndex(int currentRecipeIndexIn) { this.currentRecipeIndex = currentRecipeIndexIn; this.resetRecipeAndSlots(); } - public int getField(int var1) { - return 0; - } - public void setField(int var1, int var2) { } - public int getFieldCount() { - return 0; - } + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + this.theInventory[i] = itemstack; + if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { + itemstack.stackSize = this.getInventoryStackLimit(); + } - public void clear() { - for (int i = 0; i < this.theInventory.length; ++i) { - this.theInventory[i] = null; + if (this.inventoryResetNeededOnSlotChange(i)) { + this.resetRecipeAndSlots(); } } diff --git a/src/game/java/net/minecraft/inventory/Slot.java b/src/game/java/net/minecraft/inventory/Slot.java index 3749b345..77c3e238 100644 --- a/src/game/java/net/minecraft/inventory/Slot.java +++ b/src/game/java/net/minecraft/inventory/Slot.java @@ -3,22 +3,25 @@ package net.minecraft.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,9 +40,97 @@ public class Slot { this.yDisplayPosition = yPosition; } - /**+ - * if par2 has more items than par1, - * onCrafting(item,countIncrease) is called + /** + * + Actualy only call when we want to render the white square effect over the + * slots. Return always True, except for the armor slot of the Donkey/Mule (we + * can't interact with the Undead and Skeleton horses) + */ + public boolean canBeHovered() { + return true; + } + + /** + * + Return whether this slot's stack can be taken from this slot. + */ + public boolean canTakeStack(EntityPlayer var1) { + return true; + } + + /** + * + Decrease the size of the stack in slot (first int arg) by the amount of the + * second int arg. Returns the new stack. + */ + public ItemStack decrStackSize(int i) { + return this.inventory.decrStackSize(this.slotIndex, i); + } + + /** + * + Returns if this slot contains a stack. + */ + public boolean getHasStack() { + return this.getStack() != null; + } + + public int getItemStackLimit(ItemStack var1) { + return this.getSlotStackLimit(); + } + + /** + * + Returns the maximum stack size for a given slot (usually the same as + * getInventoryStackLimit(), but 1 in the case of armor slots) + */ + public int getSlotStackLimit() { + return this.inventory.getInventoryStackLimit(); + } + + public String getSlotTexture() { + return null; + } + + /** + * + Helper fnct to get the stack in the slot. + */ + public ItemStack getStack() { + return this.inventory.getStackInSlot(this.slotIndex); + } + + /** + * + returns true if the slot exists in the given inventory and location + */ + public boolean isHere(IInventory iinventory, int i) { + return iinventory == this.inventory && i == this.slotIndex; + } + + /** + * + Check if the stack is a valid item for this slot. Always true beside for + * the armor slots. + */ + public boolean isItemValid(ItemStack var1) { + return true; + } + + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). + */ + protected void onCrafting(ItemStack var1) { + } + + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). + */ + protected void onCrafting(ItemStack var1, int var2) { + } + + public void onPickupFromSlot(EntityPlayer var1, ItemStack var2) { + this.onSlotChanged(); + } + + /** + * + if par2 has more items than par1, onCrafting(item,countIncrease) is called */ public void onSlotChange(ItemStack parItemStack, ItemStack parItemStack2) { if (parItemStack != null && parItemStack2 != null) { @@ -53,110 +144,18 @@ public class Slot { } } - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). - */ - protected void onCrafting(ItemStack var1, int var2) { - } - - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). - */ - protected void onCrafting(ItemStack var1) { - } - - public void onPickupFromSlot(EntityPlayer var1, ItemStack var2) { - this.onSlotChanged(); - } - - /**+ - * Check if the stack is a valid item for this slot. Always true - * beside for the armor slots. - */ - public boolean isItemValid(ItemStack var1) { - return true; - } - - /**+ - * Helper fnct to get the stack in the slot. - */ - public ItemStack getStack() { - return this.inventory.getStackInSlot(this.slotIndex); - } - - /**+ - * Returns if this slot contains a stack. - */ - public boolean getHasStack() { - return this.getStack() != null; - } - - /**+ - * Helper method to put a stack in the slot. - */ - public void putStack(ItemStack itemstack) { - this.inventory.setInventorySlotContents(this.slotIndex, itemstack); - this.onSlotChanged(); - } - - /**+ - * Called when the stack in a Slot changes + /** + * + Called when the stack in a Slot changes */ public void onSlotChanged() { this.inventory.markDirty(); } - /**+ - * Returns the maximum stack size for a given slot (usually the - * same as getInventoryStackLimit(), but 1 in the case of armor - * slots) + /** + * + Helper method to put a stack in the slot. */ - public int getSlotStackLimit() { - return this.inventory.getInventoryStackLimit(); - } - - public int getItemStackLimit(ItemStack var1) { - return this.getSlotStackLimit(); - } - - public String getSlotTexture() { - return null; - } - - /**+ - * Decrease the size of the stack in slot (first int arg) by the - * amount of the second int arg. Returns the new stack. - */ - public ItemStack decrStackSize(int i) { - return this.inventory.decrStackSize(this.slotIndex, i); - } - - /**+ - * returns true if the slot exists in the given inventory and - * location - */ - public boolean isHere(IInventory iinventory, int i) { - return iinventory == this.inventory && i == this.slotIndex; - } - - /**+ - * Return whether this slot's stack can be taken from this slot. - */ - public boolean canTakeStack(EntityPlayer var1) { - return true; - } - - /**+ - * Actualy only call when we want to render the white square - * effect over the slots. Return always True, except for the - * armor slot of the Donkey/Mule (we can't interact with the - * Undead and Skeleton horses) - */ - public boolean canBeHovered() { - return true; + public void putStack(ItemStack itemstack) { + this.inventory.setInventorySlotContents(this.slotIndex, itemstack); + this.onSlotChanged(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/SlotCrafting.java b/src/game/java/net/minecraft/inventory/SlotCrafting.java index 7e2c527c..9bb92279 100644 --- a/src/game/java/net/minecraft/inventory/SlotCrafting.java +++ b/src/game/java/net/minecraft/inventory/SlotCrafting.java @@ -11,22 +11,25 @@ import net.minecraft.item.ItemSword; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.stats.AchievementList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,17 +46,9 @@ public class SlotCrafting extends Slot { this.craftMatrix = craftingInventory; } - /**+ - * Check if the stack is a valid item for this slot. Always true - * beside for the armor slots. - */ - public boolean isItemValid(ItemStack var1) { - return false; - } - - /**+ - * Decrease the size of the stack in slot (first int arg) by the - * amount of the second int arg. Returns the new stack. + /** + * + Decrease the size of the stack in slot (first int arg) by the amount of the + * second int arg. Returns the new stack. */ public ItemStack decrStackSize(int i) { if (this.getHasStack()) { @@ -63,20 +58,18 @@ public class SlotCrafting extends Slot { return super.decrStackSize(i); } - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). + /** + * + Check if the stack is a valid item for this slot. Always true beside for + * the armor slots. */ - protected void onCrafting(ItemStack itemstack, int i) { - this.amountCrafted += i; - this.onCrafting(itemstack); + public boolean isItemValid(ItemStack var1) { + return false; } - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). */ protected void onCrafting(ItemStack itemstack) { if (this.amountCrafted > 0) { @@ -131,6 +124,16 @@ public class SlotCrafting extends Slot { } + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). + */ + protected void onCrafting(ItemStack itemstack, int i) { + this.amountCrafted += i; + this.onCrafting(itemstack); + } + public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack itemstack) { this.onCrafting(itemstack); ItemStack[] aitemstack = CraftingManager.getInstance().func_180303_b(this.craftMatrix, entityplayer.worldObj); diff --git a/src/game/java/net/minecraft/inventory/SlotFurnaceFuel.java b/src/game/java/net/minecraft/inventory/SlotFurnaceFuel.java index c800db77..2f442862 100644 --- a/src/game/java/net/minecraft/inventory/SlotFurnaceFuel.java +++ b/src/game/java/net/minecraft/inventory/SlotFurnaceFuel.java @@ -4,44 +4,47 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityFurnace; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SlotFurnaceFuel extends Slot { - public SlotFurnaceFuel(IInventory inventoryIn, int slotIndex, int xPosition, int yPosition) { - super(inventoryIn, slotIndex, xPosition, yPosition); + public static boolean isBucket(ItemStack parItemStack) { + return parItemStack != null && parItemStack.getItem() != null && parItemStack.getItem() == Items.bucket; } - /**+ - * Check if the stack is a valid item for this slot. Always true - * beside for the armor slots. - */ - public boolean isItemValid(ItemStack itemstack) { - return TileEntityFurnace.isItemFuel(itemstack) || isBucket(itemstack); + public SlotFurnaceFuel(IInventory inventoryIn, int slotIndex, int xPosition, int yPosition) { + super(inventoryIn, slotIndex, xPosition, yPosition); } public int getItemStackLimit(ItemStack itemstack) { return isBucket(itemstack) ? 1 : super.getItemStackLimit(itemstack); } - public static boolean isBucket(ItemStack parItemStack) { - return parItemStack != null && parItemStack.getItem() != null && parItemStack.getItem() == Items.bucket; + /** + * + Check if the stack is a valid item for this slot. Always true beside for + * the armor slots. + */ + public boolean isItemValid(ItemStack itemstack) { + return TileEntityFurnace.isItemFuel(itemstack) || isBucket(itemstack); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/SlotFurnaceOutput.java b/src/game/java/net/minecraft/inventory/SlotFurnaceOutput.java index d1093a9d..785510d7 100644 --- a/src/game/java/net/minecraft/inventory/SlotFurnaceOutput.java +++ b/src/game/java/net/minecraft/inventory/SlotFurnaceOutput.java @@ -8,22 +8,25 @@ import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.stats.AchievementList; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,17 +40,9 @@ public class SlotFurnaceOutput extends Slot { this.thePlayer = player; } - /**+ - * Check if the stack is a valid item for this slot. Always true - * beside for the armor slots. - */ - public boolean isItemValid(ItemStack var1) { - return false; - } - - /**+ - * Decrease the size of the stack in slot (first int arg) by the - * amount of the second int arg. Returns the new stack. + /** + * + Decrease the size of the stack in slot (first int arg) by the amount of the + * second int arg. Returns the new stack. */ public ItemStack decrStackSize(int i) { if (this.getHasStack()) { @@ -57,25 +52,18 @@ public class SlotFurnaceOutput extends Slot { return super.decrStackSize(i); } - public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack itemstack) { - this.onCrafting(itemstack); - super.onPickupFromSlot(entityplayer, itemstack); - } - - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). + /** + * + Check if the stack is a valid item for this slot. Always true beside for + * the armor slots. */ - protected void onCrafting(ItemStack stack, int amount) { - this.field_75228_b += amount; - this.onCrafting(stack); + public boolean isItemValid(ItemStack var1) { + return false; } - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). */ protected void onCrafting(ItemStack stack) { stack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.field_75228_b); @@ -112,4 +100,19 @@ public class SlotFurnaceOutput extends Slot { } } + + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). + */ + protected void onCrafting(ItemStack stack, int amount) { + this.field_75228_b += amount; + this.onCrafting(stack); + } + + public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack itemstack) { + this.onCrafting(itemstack); + super.onPickupFromSlot(entityplayer, itemstack); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/inventory/SlotMerchantResult.java b/src/game/java/net/minecraft/inventory/SlotMerchantResult.java index 9255f2a8..a956c705 100644 --- a/src/game/java/net/minecraft/inventory/SlotMerchantResult.java +++ b/src/game/java/net/minecraft/inventory/SlotMerchantResult.java @@ -6,22 +6,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.stats.StatList; import net.minecraft.village.MerchantRecipe; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,17 +43,9 @@ public class SlotMerchantResult extends Slot { this.theMerchantInventory = merchantInventory; } - /**+ - * Check if the stack is a valid item for this slot. Always true - * beside for the armor slots. - */ - public boolean isItemValid(ItemStack var1) { - return false; - } - - /**+ - * Decrease the size of the stack in slot (first int arg) by the - * amount of the second int arg. Returns the new stack. + /** + * + Decrease the size of the stack in slot (first int arg) by the amount of the + * second int arg. Returns the new stack. */ public ItemStack decrStackSize(int i) { if (this.getHasStack()) { @@ -60,26 +55,53 @@ public class SlotMerchantResult extends Slot { return super.decrStackSize(i); } - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). - */ - protected void onCrafting(ItemStack itemstack, int i) { - this.field_75231_g += i; - this.onCrafting(itemstack); + private boolean doTrade(MerchantRecipe trade, ItemStack firstItem, ItemStack secondItem) { + ItemStack itemstack = trade.getItemToBuy(); + ItemStack itemstack1 = trade.getSecondItemToBuy(); + if (firstItem != null && firstItem.getItem() == itemstack.getItem()) { + if (itemstack1 != null && secondItem != null && itemstack1.getItem() == secondItem.getItem()) { + firstItem.stackSize -= itemstack.stackSize; + secondItem.stackSize -= itemstack1.stackSize; + return true; + } + + if (itemstack1 == null && secondItem == null) { + firstItem.stackSize -= itemstack.stackSize; + return true; + } + } + + return false; } - /**+ - * the itemStack passed in is the output - ie, iron ingots, and - * pickaxes, not ore and wood. Typically increases an internal - * count then calls onCrafting(item). + /** + * + Check if the stack is a valid item for this slot. Always true beside for + * the armor slots. + */ + public boolean isItemValid(ItemStack var1) { + return false; + } + + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). */ protected void onCrafting(ItemStack itemstack) { itemstack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.field_75231_g); this.field_75231_g = 0; } + /** + * + the itemStack passed in is the output - ie, iron ingots, and pickaxes, not + * ore and wood. Typically increases an internal count then calls + * onCrafting(item). + */ + protected void onCrafting(ItemStack itemstack, int i) { + this.field_75231_g += i; + this.onCrafting(itemstack); + } + public void onPickupFromSlot(EntityPlayer entityplayer, ItemStack itemstack) { this.onCrafting(itemstack); MerchantRecipe merchantrecipe = this.theMerchantInventory.getCurrentRecipe(); @@ -104,23 +126,4 @@ public class SlotMerchantResult extends Slot { } } - - private boolean doTrade(MerchantRecipe trade, ItemStack firstItem, ItemStack secondItem) { - ItemStack itemstack = trade.getItemToBuy(); - ItemStack itemstack1 = trade.getSecondItemToBuy(); - if (firstItem != null && firstItem.getItem() == itemstack.getItem()) { - if (itemstack1 != null && secondItem != null && itemstack1.getItem() == secondItem.getItem()) { - firstItem.stackSize -= itemstack.stackSize; - secondItem.stackSize -= itemstack1.stackSize; - return true; - } - - if (itemstack1 == null && secondItem == null) { - firstItem.stackSize -= itemstack.stackSize; - return true; - } - } - - return false; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/EnumAction.java b/src/game/java/net/minecraft/item/EnumAction.java index 01758fc2..6abcaa58 100644 --- a/src/game/java/net/minecraft/item/EnumAction.java +++ b/src/game/java/net/minecraft/item/EnumAction.java @@ -1,21 +1,24 @@ package net.minecraft.item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/item/EnumDyeColor.java b/src/game/java/net/minecraft/item/EnumDyeColor.java index 41fbf603..8601d823 100644 --- a/src/game/java/net/minecraft/item/EnumDyeColor.java +++ b/src/game/java/net/minecraft/item/EnumDyeColor.java @@ -4,22 +4,25 @@ import net.minecraft.block.material.MapColor; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IStringSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,37 +47,14 @@ public enum EnumDyeColor implements IStringSerializable { public static final EnumDyeColor[] META_LOOKUP = new EnumDyeColor[16]; public static final EnumDyeColor[] DYE_DMG_LOOKUP = new EnumDyeColor[16]; - private final int meta; - private final int dyeDamage; - private final String name; - private final String unlocalizedName; - private final MapColor mapColor; - private final EnumChatFormatting chatColor; + static { + EnumDyeColor[] colors = values(); + for (int i = 0; i < colors.length; ++i) { + EnumDyeColor enumdyecolor = colors[i]; + META_LOOKUP[enumdyecolor.getMetadata()] = enumdyecolor; + DYE_DMG_LOOKUP[enumdyecolor.getDyeDamage()] = enumdyecolor; + } - private EnumDyeColor(int meta, int dyeDamage, String name, String unlocalizedName, MapColor mapColorIn, - EnumChatFormatting chatColor) { - this.meta = meta; - this.dyeDamage = dyeDamage; - this.name = name; - this.unlocalizedName = unlocalizedName; - this.mapColor = mapColorIn; - this.chatColor = chatColor; - } - - public int getMetadata() { - return this.meta; - } - - public int getDyeDamage() { - return this.dyeDamage; - } - - public String getUnlocalizedName() { - return this.unlocalizedName; - } - - public MapColor getMapColor() { - return this.mapColor; } public static EnumDyeColor byDyeDamage(int damage) { @@ -93,21 +73,47 @@ public enum EnumDyeColor implements IStringSerializable { return META_LOOKUP[meta]; } - public String toString() { - return this.unlocalizedName; + private final int meta; + private final int dyeDamage; + private final String name; + + private final String unlocalizedName; + + private final MapColor mapColor; + + private final EnumChatFormatting chatColor; + + private EnumDyeColor(int meta, int dyeDamage, String name, String unlocalizedName, MapColor mapColorIn, + EnumChatFormatting chatColor) { + this.meta = meta; + this.dyeDamage = dyeDamage; + this.name = name; + this.unlocalizedName = unlocalizedName; + this.mapColor = mapColorIn; + this.chatColor = chatColor; + } + + public int getDyeDamage() { + return this.dyeDamage; + } + + public MapColor getMapColor() { + return this.mapColor; + } + + public int getMetadata() { + return this.meta; } public String getName() { return this.name; } - static { - EnumDyeColor[] colors = values(); - for (int i = 0; i < colors.length; ++i) { - EnumDyeColor enumdyecolor = colors[i]; - META_LOOKUP[enumdyecolor.getMetadata()] = enumdyecolor; - DYE_DMG_LOOKUP[enumdyecolor.getDyeDamage()] = enumdyecolor; - } + public String getUnlocalizedName() { + return this.unlocalizedName; + } + public String toString() { + return this.unlocalizedName; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/EnumRarity.java b/src/game/java/net/minecraft/item/EnumRarity.java index e5fcac88..5470d626 100644 --- a/src/game/java/net/minecraft/item/EnumRarity.java +++ b/src/game/java/net/minecraft/item/EnumRarity.java @@ -2,22 +2,25 @@ package net.minecraft.item; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/item/Item.java b/src/game/java/net/minecraft/item/Item.java index 3cd80eae..f18235b5 100644 --- a/src/game/java/net/minecraft/item/Item.java +++ b/src/game/java/net/minecraft/item/Item.java @@ -2,18 +2,19 @@ package net.minecraft.item; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import com.google.common.base.Function; import com.google.common.collect.HashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.block.Block; import net.minecraft.block.BlockDirt; import net.minecraft.block.BlockDoublePlant; import net.minecraft.block.BlockFlower; +import net.minecraft.block.BlockMosaic; import net.minecraft.block.BlockPlanks; import net.minecraft.block.BlockPrismarine; import net.minecraft.block.BlockRedSandstone; @@ -46,63 +47,109 @@ import net.minecraft.util.StatCollector; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Item { + public static enum ToolMaterial { + // MATERIAL(HARVEST_LEVEL, DURABILITY, EFFICIENCY, DAMAGE, ENCHANTABILITY) + WOOD(0, 59, 2.0F, 0.0F, 15), STONE(1, 131, 4.0F, 1.0F, 5), IRON(2, 250, 6.0F, 2.0F, 14), + DIAMOND(3, 1561, 8.0F, 3.0F, 10), GOLD(0, 32, 12.0F, 0.0F, 22), PLATINUM(4, 2000, 10.0F, 4.0F, 12), + PLATINUM_DRILL(4, 2500, 50.0F, 4.0F, 14), TITANIUM_DRILL(5, 4750, 70.0F, 6.0F, 18), + SPEED_DRILL(5, 7500, 200.0F, 6.0F, 18), POWER_DRILL(6, 8500, 50.0F, 6.0F, 18), + LATE_GAME_DRILL(7, 8000, 300.0F, 7.0F, 24), OP_DRILL(8, 15000, 500.0F, 8.0F, 30); + + private final int harvestLevel; + private final int maxUses; + private final float efficiencyOnProperMaterial; + private final float damageVsEntity; + private final int enchantability; + + private ToolMaterial(int harvestLevel, int maxUses, float efficiency, float damageVsEntity, + int enchantability) { + this.harvestLevel = harvestLevel; + this.maxUses = maxUses; + this.efficiencyOnProperMaterial = efficiency; + this.damageVsEntity = damageVsEntity; + this.enchantability = enchantability; + } + + public float getDamageVsEntity() { + return this.damageVsEntity; + } + + public float getEfficiencyOnProperMaterial() { + return this.efficiencyOnProperMaterial; + } + + public int getEnchantability() { + return this.enchantability; + } + + public int getHarvestLevel() { + return this.harvestLevel; + } + + public int getMaxUses() { + return this.maxUses; + } + + public Item getRepairItem() { + return this == WOOD ? Item.getItemFromBlock(Blocks.planks) + : (this == STONE ? Item.getItemFromBlock(Blocks.cobblestone) + : (this == GOLD ? Items.gold_ingot + : (this == IRON ? Items.iron_ingot + : (this == DIAMOND ? Items.diamond + : (this == PLATINUM ? Items.platinum_ingot + : (this == PLATINUM_DRILL ? Items.uranium_rod + : (this == PLATINUM_DRILL ? Items.uranium_rod + : (this == TITANIUM_DRILL + ? Items.uranium_rod + : (this == SPEED_DRILL + ? Items.uranium_rod + : (this == POWER_DRILL + ? Items.uranium_rod + : (this == LATE_GAME_DRILL + ? Items.uranium_rod + : (this == OP_DRILL + ? Items.uranium_rod + : null)))))))))))); + + } + } + public static final RegistryNamespaced itemRegistry = new RegistryNamespaced(); private static final Map BLOCK_TO_ITEM = Maps.newHashMap(); protected static final EaglercraftUUID itemModifierUUID = EaglercraftUUID .fromString("CB3F55D3-645C-4F38-A497-9C13A33DB5CF"); - private CreativeTabs tabToDisplayOn; - /**+ - * The RNG used by the Item subclasses. + /** + * + The RNG used by the Item subclasses. */ protected static EaglercraftRandom itemRand = new EaglercraftRandom(); - /**+ - * Maximum size of the stack. - */ - protected int maxStackSize = 64; - private int maxDamage; - protected boolean bFull3D; - protected boolean hasSubtypes; - private Item containerItem; - private String potionEffect; - private String unlocalizedName; - public static int getIdFromItem(Item itemIn) { - return itemIn == null ? 0 : itemRegistry.getIDForObject(itemIn); - } - - public static Item getItemById(int id) { - return (Item) itemRegistry.getObjectById(id); - } - - public static Item getItemFromBlock(Block blockIn) { - return (Item) BLOCK_TO_ITEM.get(blockIn); - } - - /**+ - * Tries to get an Item by it's name (e.g. minecraft:apple) or a - * String representation of a numerical ID. If both fail, null - * is returned. + /** + * + Tries to get an Item by it's name (e.g. minecraft:apple) or a String + * representation of a numerical ID. If both fail, null is returned. */ public static Item getByNameOrId(String id) { Item item = (Item) itemRegistry.getObject(new ResourceLocation(id)); @@ -117,368 +164,40 @@ public class Item { return item; } - /**+ - * Called when an ItemStack with NBT data is read to potentially - * that ItemStack's NBT data + public static int getIdFromItem(Item itemIn) { + return itemIn == null ? 0 : itemRegistry.getIDForObject(itemIn); + } + + public static Item getItemById(int id) { + return (Item) itemRegistry.getObjectById(id); + } + + public static Item getItemFromBlock(Block blockIn) { + return (Item) BLOCK_TO_ITEM.get(blockIn); + } + + private static void registerItem(int id, ResourceLocation textualID, Item itemIn) { + itemRegistry.register(id, textualID, itemIn); + } + + private static void registerItem(int id, String textualID, Item itemIn) { + registerItem(id, new ResourceLocation(textualID), itemIn); + } + + /** + * + Register the given Item as the ItemBlock for the given Block. */ - public boolean updateItemStackNBT(NBTTagCompound var1) { - return false; + private static void registerItemBlock(Block blockIn) { + registerItemBlock(blockIn, new ItemBlock(blockIn)); } - public Item setMaxStackSize(int maxStackSize) { - this.maxStackSize = maxStackSize; - return this; - } - - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Register the given Item as the ItemBlock for the given Block. */ - public boolean onItemUse(ItemStack var1, EntityPlayer var2, World var3, BlockPos var4, EnumFacing var5, float var6, - float var7, float var8) { - return false; - } - - public float getStrVsBlock(ItemStack var1, Block var2) { - return 1.0F; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer var3) { - return itemstack; - } - - /**+ - * Called when the player finishes using this Item (E.g. - * finishes eating.). Not called when the player stops using the - * Item before the action is complete. - */ - public ItemStack onItemUseFinish(ItemStack itemstack, World var2, EntityPlayer var3) { - return itemstack; - } - - /**+ - * Returns the maximum size of the stack for a specific item. - * *Isn't this more a Set than a Get?* - */ - public int getItemStackLimit() { - return this.maxStackSize; - } - - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). - */ - public int getMetadata(int var1) { - return 0; - } - - public boolean getHasSubtypes() { - return this.hasSubtypes; - } - - protected Item setHasSubtypes(boolean hasSubtypes) { - this.hasSubtypes = hasSubtypes; - return this; - } - - /**+ - * Returns the maximum damage an item can take. - */ - public int getMaxDamage() { - return this.maxDamage; - } - - /**+ - * set max damage of an Item - */ - protected Item setMaxDamage(int maxDamageIn) { - this.maxDamage = maxDamageIn; - return this; - } - - public boolean isDamageable() { - return this.maxDamage > 0 && !this.hasSubtypes; - } - - /**+ - * Current implementations of this method in child classes do - * not use the entry argument beside ev. They just raise the - * damage on the stack. - */ - public boolean hitEntity(ItemStack var1, EntityLivingBase var2, EntityLivingBase var3) { - return false; - } - - /**+ - * Called when a Block is destroyed using this Item. Return true - * to trigger the "Use Item" statistic. - */ - public boolean onBlockDestroyed(ItemStack var1, World var2, Block var3, BlockPos var4, EntityLivingBase var5) { - return false; - } - - /**+ - * Check whether this Item can harvest the given Block - */ - public boolean canHarvestBlock(Block var1) { - return false; - } - - /**+ - * Returns true if the item can be used on the given entity, - * e.g. shears on sheep. - */ - public boolean itemInteractionForEntity(ItemStack var1, EntityPlayer var2, EntityLivingBase var3) { - return false; - } - - /**+ - * Sets bFull3D to True and return the object. - */ - public Item setFull3D() { - this.bFull3D = true; - return this; - } - - /**+ - * Returns True is the item is renderer in full 3D when hold. - */ - public boolean isFull3D() { - return this.bFull3D; - } - - /**+ - * Returns true if this item should be rotated by 180 degrees - * around the Y axis when being held in an entities hands. - */ - public boolean shouldRotateAroundWhenRendering() { - return false; - } - - /**+ - * Sets the unlocalized name of this item to the string passed - * as the parameter, prefixed by "item." - */ - public Item setUnlocalizedName(String s) { - this.unlocalizedName = s; - return this; - } - - /**+ - * Translates the unlocalized name of this item, but without the - * .name suffix, so the translation fails and the unlocalized - * name itself is returned. - */ - public String getUnlocalizedNameInefficiently(ItemStack stack) { - String s = this.getUnlocalizedName(stack); - return s == null ? "" : StatCollector.translateToLocal(s); - } - - /**+ - * Returns the unlocalized name of this item. - */ - public String getUnlocalizedName() { - return "item." + this.unlocalizedName; - } - - /**+ - * Returns the unlocalized name of this item. - */ - public String getUnlocalizedName(ItemStack var1) { - return "item." + this.unlocalizedName; - } - - public Item setContainerItem(Item containerItem) { - this.containerItem = containerItem; - return this; - } - - /**+ - * If this function returns true (or the item is damageable), - * the ItemStack's NBT tag will be sent to the client. - */ - public boolean getShareTag() { - return true; - } - - public Item getContainerItem() { - return this.containerItem; - } - - /**+ - * True if this Item has a container item (a.k.a. crafting - * result) - */ - public boolean hasContainerItem() { - return this.containerItem != null; - } - - public int getColorFromItemStack(ItemStack var1, int var2) { - return 16777215; - } - - /**+ - * Called each tick as long the item is on a player inventory. - * Uses by maps to check if is on a player hand and update it's - * contents. - */ - public void onUpdate(ItemStack var1, World var2, Entity var3, int var4, boolean var5) { - } - - /**+ - * Called when item is crafted/smelted. Used only by maps so - * far. - */ - public void onCreated(ItemStack var1, World var2, EntityPlayer var3) { - } - - /**+ - * false for all Items except sub-classes of ItemMapBase - */ - public boolean isMap() { - return false; - } - - /**+ - * returns the action that specifies what animation to play when - * the items is being used - */ - public EnumAction getItemUseAction(ItemStack var1) { - return EnumAction.NONE; - } - - /**+ - * How long it takes to use or consume an item - */ - public int getMaxItemUseDuration(ItemStack var1) { - return 0; - } - - /**+ - * Called when the player stops using an Item (stops holding the - * right mouse button). - */ - public void onPlayerStoppedUsing(ItemStack var1, World var2, EntityPlayer var3, int var4) { - } - - /**+ - * Sets the string representing this item's effect on a potion - * when used as an ingredient. - */ - protected Item setPotionEffect(String potionEffect) { - this.potionEffect = potionEffect; - return this; - } - - public String getPotionEffect(ItemStack var1) { - return this.potionEffect; - } - - public boolean isPotionIngredient(ItemStack stack) { - return this.getPotionEffect(stack) != null; - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description - */ - public void addInformation(ItemStack var1, EntityPlayer var2, List var3, boolean var4) { - } - - public String getItemStackDisplayName(ItemStack itemstack) { - return ("" + StatCollector.translateToLocal(this.getUnlocalizedNameInefficiently(itemstack) + ".name")).trim(); - } - - public boolean hasEffect(ItemStack itemstack) { - return itemstack.isItemEnchanted(); - } - - /**+ - * Return an item rarity from EnumRarity - */ - public EnumRarity getRarity(ItemStack itemstack) { - return itemstack.isItemEnchanted() ? EnumRarity.RARE : EnumRarity.COMMON; - } - - /**+ - * Checks isDamagable and if it cannot be stacked - */ - public boolean isItemTool(ItemStack var1) { - return this.getItemStackLimit() == 1 && this.isDamageable(); - } - - protected MovingObjectPosition getMovingObjectPositionFromPlayer(World worldIn, EntityPlayer playerIn, - boolean useLiquids) { - float f = playerIn.rotationPitch; - float f1 = playerIn.rotationYaw; - double d0 = playerIn.posX; - double d1 = playerIn.posY + (double) playerIn.getEyeHeight(); - double d2 = playerIn.posZ; - Vec3 vec3 = new Vec3(d0, d1, d2); - float f2 = MathHelper.cos(-f1 * 0.017453292F - 3.1415927F); - float f3 = MathHelper.sin(-f1 * 0.017453292F - 3.1415927F); - float f4 = -MathHelper.cos(-f * 0.017453292F); - float f5 = MathHelper.sin(-f * 0.017453292F); - float f6 = f3 * f4; - float f7 = f2 * f4; - double d3 = 5.0D; - Vec3 vec31 = vec3.addVector((double) f6 * d3, (double) f5 * d3, (double) f7 * d3); - return worldIn.rayTraceBlocks(vec3, vec31, useLiquids, !useLiquids, false); - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. - */ - public int getItemEnchantability() { - return 0; - } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, 0)); - } - - /**+ - * gets the CreativeTab this item is displayed on - */ - public CreativeTabs getCreativeTab() { - return this.tabToDisplayOn; - } - - /**+ - * returns this; - */ - public Item setCreativeTab(CreativeTabs tab) { - this.tabToDisplayOn = tab; - return this; - } - - /**+ - * Returns true if players can use this item to affect the world - * (e.g. placing blocks, placing ender eyes in portal) when not - * in creative - */ - public boolean canItemEditBlocks() { - return false; - } - - /**+ - * Return whether this item is repairable in an anvil. - */ - public boolean getIsRepairable(ItemStack var1, ItemStack var2) { - return false; - } - - public Multimap getItemAttributeModifiers() { - return HashMultimap.create(); + protected static void registerItemBlock(Block blockIn, Item itemIn) { + registerItem(Block.getIdFromBlock(blockIn), (ResourceLocation) Block.blockRegistry.getNameForObject(blockIn), + itemIn); + BLOCK_TO_ITEM.put(blockIn, itemIn); } public static void registerItems() { @@ -728,14 +447,10 @@ public class Item { } })).setUnlocalizedName("redSandStone")); registerItemBlock(Blocks.red_sandstone_stairs); - registerItemBlock(Blocks.iron_grate); registerItemBlock(Blocks.stone_slab2, (new ItemSlab(Blocks.stone_slab2, Blocks.stone_slab2, Blocks.double_stone_slab2)) .setUnlocalizedName("stoneSlab2")); - registerItemBlock(Blocks.platinum_ore); - registerItemBlock(Blocks.platinum_block); - registerItemBlock(Blocks.uranium_ore); registerItem(256, (String) "iron_shovel", (new ItemSpade(Item.ToolMaterial.IRON)).setUnlocalizedName("shovelIron")); @@ -773,13 +488,13 @@ public class Item { registerItem(275, (String) "stone_axe", (new ItemAxe(Item.ToolMaterial.STONE)).setUnlocalizedName("hatchetStone")); registerItem(276, (String) "diamond_sword", - (new ItemSword(Item.ToolMaterial.EMERALD)).setUnlocalizedName("swordDiamond")); + (new ItemSword(Item.ToolMaterial.DIAMOND)).setUnlocalizedName("swordDiamond")); registerItem(277, (String) "diamond_shovel", - (new ItemSpade(Item.ToolMaterial.EMERALD)).setUnlocalizedName("shovelDiamond")); + (new ItemSpade(Item.ToolMaterial.DIAMOND)).setUnlocalizedName("shovelDiamond")); registerItem(278, (String) "diamond_pickaxe", - (new ItemPickaxe(Item.ToolMaterial.EMERALD)).setUnlocalizedName("pickaxeDiamond")); + (new ItemPickaxe(Item.ToolMaterial.DIAMOND)).setUnlocalizedName("pickaxeDiamond")); registerItem(279, (String) "diamond_axe", - (new ItemAxe(Item.ToolMaterial.EMERALD)).setUnlocalizedName("hatchetDiamond")); + (new ItemAxe(Item.ToolMaterial.DIAMOND)).setUnlocalizedName("hatchetDiamond")); registerItem(280, (String) "stick", (new Item()).setFull3D().setUnlocalizedName("stick").setCreativeTab(CreativeTabs.tabMaterials)); registerItem(281, (String) "bowl", @@ -803,7 +518,7 @@ public class Item { registerItem(291, (String) "stone_hoe", (new ItemHoe(Item.ToolMaterial.STONE)).setUnlocalizedName("hoeStone")); registerItem(292, (String) "iron_hoe", (new ItemHoe(Item.ToolMaterial.IRON)).setUnlocalizedName("hoeIron")); registerItem(293, (String) "diamond_hoe", - (new ItemHoe(Item.ToolMaterial.EMERALD)).setUnlocalizedName("hoeDiamond")); + (new ItemHoe(Item.ToolMaterial.DIAMOND)).setUnlocalizedName("hoeDiamond")); registerItem(294, (String) "golden_hoe", (new ItemHoe(Item.ToolMaterial.GOLD)).setUnlocalizedName("hoeGold")); registerItem(295, (String) "wheat_seeds", (new ItemSeeds(Blocks.wheat, Blocks.farmland)).setUnlocalizedName("seeds")); @@ -1036,19 +751,6 @@ public class Item { registerItem(430, (String) "acacia_door", (new ItemDoor(Blocks.acacia_door)).setUnlocalizedName("doorAcacia")); registerItem(431, (String) "dark_oak_door", (new ItemDoor(Blocks.dark_oak_door)).setUnlocalizedName("doorDarkOak")); - registerItem(432, (String) "starlike:platinum_ingot", - (new Item()) - .setUnlocalizedName("platinum_ingot") - .setCreativeTab(CreativeTabs.tabMaterials)); - registerItem(433, (String) "starlike:platinum_sword", - (new ItemSword(Item.ToolMaterial.PLATINUM)) - .setUnlocalizedName("platinum_sword")); - registerItem(444, (String) "starlike:platinum_pickaxe", - (new ItemPickaxe(Item.ToolMaterial.PLATINUM)) - .setUnlocalizedName("platinum_pickaxe")); - registerItem(445, (String) "starlike:normal_drill", - (new ItemPickaxe(Item.ToolMaterial.NORMAL_DRILL)) - .setUnlocalizedName("normal_drill")); registerItem(2256, (String) "record_13", (new ItemRecord("13")).setUnlocalizedName("record")); registerItem(2257, (String) "record_cat", (new ItemRecord("cat")).setUnlocalizedName("record")); registerItem(2258, (String) "record_blocks", (new ItemRecord("blocks")).setUnlocalizedName("record")); @@ -1061,93 +763,445 @@ public class Item { registerItem(2265, (String) "record_ward", (new ItemRecord("ward")).setUnlocalizedName("record")); registerItem(2266, (String) "record_11", (new ItemRecord("11")).setUnlocalizedName("record")); registerItem(2267, (String) "record_wait", (new ItemRecord("wait")).setUnlocalizedName("record")); + + registerItemBlock(Blocks.deepstone); + registerItemBlock(Blocks.cobbled_deepstone); + registerItemBlock(Blocks.steel_block); + registerItemBlock(Blocks.steel_grate); + registerItemBlock(Blocks.platinum_ore); + registerItemBlock(Blocks.platinum_block); + registerItemBlock(Blocks.titanium_ore); + registerItemBlock(Blocks.titanium_block); + registerItemBlock(Blocks.uranium_ore); + registerItemBlock(Blocks.uranium_block); + registerItemBlock(Blocks.mosaic, + (new ItemMultiTexture(Blocks.mosaic, Blocks.mosaic, new Function() { + public String apply(ItemStack itemstack) { + return BlockMosaic.EnumType.byMetadata(itemstack.getMetadata()).getUnlocalizedName(); + } + })).setUnlocalizedName("mosaic")); + registerItemBlock(Blocks.fabricator); + + registerItem(1024, (String) "starlike:steel", + (new Item()).setUnlocalizedName("steel").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1025, (String) "starlike:platinum_ingot", + (new Item()).setUnlocalizedName("platinum_ingot").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1026, (String) "starlike:platinum_sword", (new ItemSword(Item.ToolMaterial.PLATINUM)) + .setUnlocalizedName("platinum_sword").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1027, (String) "starlike:platinum_pickaxe", (new ItemPickaxe(Item.ToolMaterial.PLATINUM)) + .setUnlocalizedName("platinum_pickaxe").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1028, (String) "starlike:platinum_shovel", (new ItemSpade(Item.ToolMaterial.PLATINUM)) + .setUnlocalizedName("platinum_shovel").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1029, (String) "starlike:platinum_axe", (new ItemAxe(Item.ToolMaterial.PLATINUM)) + .setUnlocalizedName("platinum_axe").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1030, (String) "starlike:platinum_hoe", (new ItemHoe(Item.ToolMaterial.PLATINUM)) + .setUnlocalizedName("platinum_hoe").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1031, (String) "starlike:platinum_helmet", + (new ItemArmor(ItemArmor.ArmorMaterial.PLATINUM, 5, 0)).setUnlocalizedName("platinum_helmet")); + registerItem(1032, (String) "starlike:platinum_chestplate", + (new ItemArmor(ItemArmor.ArmorMaterial.PLATINUM, 5, 1)).setUnlocalizedName("platinum_chestplate")); + registerItem(1033, (String) "starlike:platinum_leggings", + (new ItemArmor(ItemArmor.ArmorMaterial.PLATINUM, 5, 2)).setUnlocalizedName("platinum_leggings")); + registerItem(1034, (String) "starlike:platinum_boots", + (new ItemArmor(ItemArmor.ArmorMaterial.PLATINUM, 5, 3)).setUnlocalizedName("platinum_boots")); + registerItem(1035, (String) "starlike:titanium_ingot", + (new Item()).setUnlocalizedName("titanium_ingot").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1036, (String) "starlike:uranium_crystal", + (new Item()).setUnlocalizedName("uranium_crystal").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1037, (String) "starlike:uranium_rod", + (new Item()).setUnlocalizedName("uranium_rod").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1038, (String) "starlike:platinum_drill", (new ItemPickaxe(Item.ToolMaterial.PLATINUM_DRILL)) + .setUnlocalizedName("platinum_drill").setCreativeTab(CreativeTabs.tabStarlike)); + registerItem(1039, (String) "starlike:titanium_drill", (new ItemPickaxe(Item.ToolMaterial.TITANIUM_DRILL)) + .setUnlocalizedName("titanium_drill").setCreativeTab(CreativeTabs.tabStarlike)); } - /**+ - * Register the given Item as the ItemBlock for the given Block. + private CreativeTabs tabToDisplayOn; + + /** + * + Maximum size of the stack. */ - private static void registerItemBlock(Block blockIn) { - registerItemBlock(blockIn, new ItemBlock(blockIn)); - } + protected int maxStackSize = 64; - /**+ - * Register the given Item as the ItemBlock for the given Block. + private int maxDamage; + + protected boolean bFull3D; + + protected boolean hasSubtypes; + + private Item containerItem; + + private String potionEffect; + + private String unlocalizedName; + + /** + * + allows items to add custom lines of information to the mouseover + * description */ - protected static void registerItemBlock(Block blockIn, Item itemIn) { - registerItem(Block.getIdFromBlock(blockIn), (ResourceLocation) Block.blockRegistry.getNameForObject(blockIn), - itemIn); - BLOCK_TO_ITEM.put(blockIn, itemIn); + public void addInformation(ItemStack var1, EntityPlayer var2, List var3, boolean var4) { } - private static void registerItem(int id, String textualID, Item itemIn) { - registerItem(id, new ResourceLocation(textualID), itemIn); + /** + * + Check whether this Item can harvest the given Block + */ + public boolean canHarvestBlock(Block var1) { + return false; } - private static void registerItem(int id, ResourceLocation textualID, Item itemIn) { - itemRegistry.register(id, textualID, itemIn); + /** + * + Returns true if players can use this item to affect the world (e.g. placing + * blocks, placing ender eyes in portal) when not in creative + */ + public boolean canItemEditBlocks() { + return false; } - public static enum ToolMaterial { - WOOD(0, 59, 2.0F, 0.0F, 15), - STONE(1, 131, 4.0F, 1.0F, 5), - IRON(2, 250, 6.0F, 2.0F, 14), - EMERALD(3, 1561, 8.0F, 3.0F, 10), - GOLD(0, 32, 12.0F, 0.0F, 22), - PLATINUM(3, 3501, 10.0F, 4.0F, 12), - NORMAL_DRILL(3, 6000, 100.0F, 4.0F, 14); + public int getColorFromItemStack(ItemStack var1, int var2) { + return 16777215; + } - private final int harvestLevel; - private final int maxUses; - private final float efficiencyOnProperMaterial; - private final float damageVsEntity; - private final int enchantability; + public Item getContainerItem() { + return this.containerItem; + } - private ToolMaterial(int harvestLevel, int maxUses, float efficiency, float damageVsEntity, - int enchantability) { - this.harvestLevel = harvestLevel; - this.maxUses = maxUses; - this.efficiencyOnProperMaterial = efficiency; - this.damageVsEntity = damageVsEntity; - this.enchantability = enchantability; - } + /** + * + gets the CreativeTab this item is displayed on + */ + public CreativeTabs getCreativeTab() { + return this.tabToDisplayOn; + } - public int getMaxUses() { - return this.maxUses; - } - - public float getEfficiencyOnProperMaterial() { - return this.efficiencyOnProperMaterial; - } - - public float getDamageVsEntity() { - return this.damageVsEntity; - } - - public int getHarvestLevel() { - return this.harvestLevel; - } - - public int getEnchantability() { - return this.enchantability; - } - - public Item getRepairItem() { - return this == WOOD ? Item.getItemFromBlock(Blocks.planks) - : (this == STONE ? Item.getItemFromBlock(Blocks.cobblestone) - : (this == GOLD ? Items.gold_ingot - : (this == IRON ? Items.iron_ingot : (this == EMERALD ? Items.diamond : null)))); - } + public boolean getHasSubtypes() { + return this.hasSubtypes; } public float getHeldItemBrightnessEagler(ItemStack itemStack) { return 0.0f; } + /** + * + Return whether this item is repairable in an anvil. + */ + public boolean getIsRepairable(ItemStack var1, ItemStack var2) { + return false; + } + + public Multimap getItemAttributeModifiers() { + return HashMultimap.create(); + } + + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. + */ + public int getItemEnchantability() { + return 0; + } + + public String getItemStackDisplayName(ItemStack itemstack) { + return ("" + StatCollector.translateToLocal(this.getUnlocalizedNameInefficiently(itemstack) + ".name")).trim(); + } + + /** + * + Returns the maximum size of the stack for a specific item. *Isn't this more + * a Set than a Get?* + */ + public int getItemStackLimit() { + return this.maxStackSize; + } + + /** + * + returns the action that specifies what animation to play when the items is + * being used + */ + public EnumAction getItemUseAction(ItemStack var1) { + return EnumAction.NONE; + } + + /** + * + Returns the maximum damage an item can take. + */ + public int getMaxDamage() { + return this.maxDamage; + } + + /** + * + How long it takes to use or consume an item + */ + public int getMaxItemUseDuration(ItemStack var1) { + return 0; + } + + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). + */ + public int getMetadata(int var1) { + return 0; + } + + protected MovingObjectPosition getMovingObjectPositionFromPlayer(World worldIn, EntityPlayer playerIn, + boolean useLiquids) { + float f = playerIn.rotationPitch; + float f1 = playerIn.rotationYaw; + double d0 = playerIn.posX; + double d1 = playerIn.posY + (double) playerIn.getEyeHeight(); + double d2 = playerIn.posZ; + Vec3 vec3 = new Vec3(d0, d1, d2); + float f2 = MathHelper.cos(-f1 * 0.017453292F - 3.1415927F); + float f3 = MathHelper.sin(-f1 * 0.017453292F - 3.1415927F); + float f4 = -MathHelper.cos(-f * 0.017453292F); + float f5 = MathHelper.sin(-f * 0.017453292F); + float f6 = f3 * f4; + float f7 = f2 * f4; + double d3 = 5.0D; + Vec3 vec31 = vec3.addVector((double) f6 * d3, (double) f5 * d3, (double) f7 * d3); + return worldIn.rayTraceBlocks(vec3, vec31, useLiquids, !useLiquids, false); + } + + public String getPotionEffect(ItemStack var1) { + return this.potionEffect; + } + + /** + * + Return an item rarity from EnumRarity + */ + public EnumRarity getRarity(ItemStack itemstack) { + return itemstack.isItemEnchanted() ? EnumRarity.RARE : EnumRarity.COMMON; + } + + /** + * + If this function returns true (or the item is damageable), the ItemStack's + * NBT tag will be sent to the client. + */ + public boolean getShareTag() { + return true; + } + + public float getStrVsBlock(ItemStack var1, Block var2) { + return 1.0F; + } + + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, 0)); + } + + /** + * + Returns the unlocalized name of this item. + */ + public String getUnlocalizedName() { + return "item." + this.unlocalizedName; + } + + /** + * + Returns the unlocalized name of this item. + */ + public String getUnlocalizedName(ItemStack var1) { + return "item." + this.unlocalizedName; + } + + /** + * + Translates the unlocalized name of this item, but without the .name suffix, + * so the translation fails and the unlocalized name itself is returned. + */ + public String getUnlocalizedNameInefficiently(ItemStack stack) { + String s = this.getUnlocalizedName(stack); + return s == null ? "" : StatCollector.translateToLocal(s); + } + + /** + * + True if this Item has a container item (a.k.a. crafting result) + */ + public boolean hasContainerItem() { + return this.containerItem != null; + } + + public boolean hasEffect(ItemStack itemstack) { + return itemstack.isItemEnchanted(); + } + + /** + * + Current implementations of this method in child classes do not use the + * entry argument beside ev. They just raise the damage on the stack. + */ + public boolean hitEntity(ItemStack var1, EntityLivingBase var2, EntityLivingBase var3) { + return false; + } + + public boolean isDamageable() { + return this.maxDamage > 0 && !this.hasSubtypes; + } + + /** + * + Returns True is the item is renderer in full 3D when hold. + */ + public boolean isFull3D() { + return this.bFull3D; + } + + /** + * + Checks isDamagable and if it cannot be stacked + */ + public boolean isItemTool(ItemStack var1) { + return this.getItemStackLimit() == 1 && this.isDamageable(); + } + + /** + * + false for all Items except sub-classes of ItemMapBase + */ + public boolean isMap() { + return false; + } + + public boolean isPotionIngredient(ItemStack stack) { + return this.getPotionEffect(stack) != null; + } + + /** + * + Returns true if the item can be used on the given entity, e.g. shears on + * sheep. + */ + public boolean itemInteractionForEntity(ItemStack var1, EntityPlayer var2, EntityLivingBase var3) { + return false; + } + + /** + * + Called when a Block is destroyed using this Item. Return true to trigger + * the "Use Item" statistic. + */ + public boolean onBlockDestroyed(ItemStack var1, World var2, Block var3, BlockPos var4, EntityLivingBase var5) { + return false; + } + + /** + * + Called when item is crafted/smelted. Used only by maps so far. + */ + public void onCreated(ItemStack var1, World var2, EntityPlayer var3) { + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer var3) { + return itemstack; + } + + /** + * + Called when a Block is right-clicked with this Item + */ + public boolean onItemUse(ItemStack var1, EntityPlayer var2, World var3, BlockPos var4, EnumFacing var5, float var6, + float var7, float var8) { + return false; + } + + /** + * + Called when the player finishes using this Item (E.g. finishes eating.). + * Not called when the player stops using the Item before the action is + * complete. + */ + public ItemStack onItemUseFinish(ItemStack itemstack, World var2, EntityPlayer var3) { + return itemstack; + } + + /** + * + Called when the player stops using an Item (stops holding the right mouse + * button). + */ + public void onPlayerStoppedUsing(ItemStack var1, World var2, EntityPlayer var3, int var4) { + } + + /** + * + Called each tick as long the item is on a player inventory. Uses by maps to + * check if is on a player hand and update it's contents. + */ + public void onUpdate(ItemStack var1, World var2, Entity var3, int var4, boolean var5) { + } + + public Item setContainerItem(Item containerItem) { + this.containerItem = containerItem; + return this; + } + + /** + * + returns this; + */ + public Item setCreativeTab(CreativeTabs tab) { + this.tabToDisplayOn = tab; + return this; + } + + /** + * + Sets bFull3D to True and return the object. + */ + public Item setFull3D() { + this.bFull3D = true; + return this; + } + + protected Item setHasSubtypes(boolean hasSubtypes) { + this.hasSubtypes = hasSubtypes; + return this; + } + + /** + * + set max damage of an Item + */ + protected Item setMaxDamage(int maxDamageIn) { + this.maxDamage = maxDamageIn; + return this; + } + + public Item setMaxStackSize(int maxStackSize) { + this.maxStackSize = maxStackSize; + return this; + } + + /** + * + Sets the string representing this item's effect on a potion when used as an + * ingredient. + */ + protected Item setPotionEffect(String potionEffect) { + this.potionEffect = potionEffect; + return this; + } + + /** + * + Sets the unlocalized name of this item to the string passed as the + * parameter, prefixed by "item." + */ + public Item setUnlocalizedName(String s) { + this.unlocalizedName = s; + return this; + } + + /** + * + Returns true if this item should be rotated by 180 degrees around the Y + * axis when being held in an entities hands. + */ + public boolean shouldRotateAroundWhenRendering() { + return false; + } + public boolean shouldUseOnTouchEagler(ItemStack itemStack) { - /**+ - * returns the action that specifies what animation to play when - * the items is being used + /** + * + returns the action that specifies what animation to play when the items is + * being used */ return getItemUseAction(itemStack) != EnumAction.NONE; } + + /** + * + Called when an ItemStack with NBT data is read to potentially that + * ItemStack's NBT data + */ + public boolean updateItemStackNBT(NBTTagCompound var1) { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemAnvilBlock.java b/src/game/java/net/minecraft/item/ItemAnvilBlock.java index 02ce6ea0..1dac3986 100644 --- a/src/game/java/net/minecraft/item/ItemAnvilBlock.java +++ b/src/game/java/net/minecraft/item/ItemAnvilBlock.java @@ -2,22 +2,25 @@ package net.minecraft.item; import net.minecraft.block.Block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,10 +30,10 @@ public class ItemAnvilBlock extends ItemMultiTexture { super(block, block, new String[] { "intact", "slightlyDamaged", "veryDamaged" }); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int i) { return i << 2; diff --git a/src/game/java/net/minecraft/item/ItemAppleGold.java b/src/game/java/net/minecraft/item/ItemAppleGold.java index 25022a06..f7ca4c2c 100644 --- a/src/game/java/net/minecraft/item/ItemAppleGold.java +++ b/src/game/java/net/minecraft/item/ItemAppleGold.java @@ -1,28 +1,32 @@ package net.minecraft.item; import java.util.List; + import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,17 +37,26 @@ public class ItemAppleGold extends ItemFood { this.setHasSubtypes(true); } - public boolean hasEffect(ItemStack itemstack) { - return itemstack.getMetadata() > 0; - } - - /**+ - * Return an item rarity from EnumRarity + /** + * + Return an item rarity from EnumRarity */ public EnumRarity getRarity(ItemStack itemstack) { return itemstack.getMetadata() == 0 ? EnumRarity.RARE : EnumRarity.EPIC; } + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs var2, List list) { + list.add(new ItemStack(item, 1, 0)); + list.add(new ItemStack(item, 1, 1)); + } + + public boolean hasEffect(ItemStack itemstack) { + return itemstack.getMetadata() > 0; + } + protected void onFoodEaten(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (!world.isRemote) { entityplayer.addPotionEffect(new PotionEffect(Potion.absorption.id, 2400, 0)); @@ -60,13 +73,4 @@ public class ItemAppleGold extends ItemFood { } } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs var2, List list) { - list.add(new ItemStack(item, 1, 0)); - list.add(new ItemStack(item, 1, 1)); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemArmor.java b/src/game/java/net/minecraft/item/ItemArmor.java index 48e6f3d8..68cce969 100644 --- a/src/game/java/net/minecraft/item/ItemArmor.java +++ b/src/game/java/net/minecraft/item/ItemArmor.java @@ -19,29 +19,75 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EntitySelectors; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemArmor extends Item { - /**+ - * Holds the 'base' maxDamage that each armorType have. + public static enum ArmorMaterial { + LEATHER("leather", 5, new int[] { 1, 3, 2, 1 }, 15), CHAIN("chainmail", 15, new int[] { 2, 5, 4, 1 }, 12), + IRON("iron", 15, new int[] { 2, 6, 5, 2 }, 9), GOLD("gold", 7, new int[] { 2, 5, 3, 1 }, 25), + DIAMOND("diamond", 33, new int[] { 3, 8, 6, 3 }, 10), PLATINUM("platinum", 41, new int[] { 4, 10, 7, 3 }, 12); + + private final String name; + private final int maxDamageFactor; + private final int[] damageReductionAmountArray; + private final int enchantability; + + private ArmorMaterial(String name, int maxDamage, int[] reductionAmounts, int enchantability) { + this.name = name; + this.maxDamageFactor = maxDamage; + this.damageReductionAmountArray = reductionAmounts; + this.enchantability = enchantability; + } + + public int getDamageReductionAmount(int armorType) { + return this.damageReductionAmountArray[armorType]; + } + + public int getDurability(int armorType) { + return ItemArmor.maxDamageArray[armorType] * this.maxDamageFactor; + } + + public int getEnchantability() { + return this.enchantability; + } + + public String getName() { + return this.name; + } + + public Item getRepairItem() { + return this == LEATHER ? Items.leather + : (this == CHAIN ? Items.iron_ingot + : (this == GOLD ? Items.gold_ingot + : (this == IRON ? Items.iron_ingot + : (this == DIAMOND ? Items.diamond + : (this == PLATINUM ? Items.platinum_ingot : null))))); + } + } + + /** + * + Holds the 'base' maxDamage that each armorType have. */ private static final int[] maxDamageArray = new int[] { 11, 16, 15, 13 }; public static final String[] EMPTY_SLOT_NAMES = new String[] { "minecraft:items/empty_armor_slot_helmet", @@ -79,6 +125,7 @@ public class ItemArmor extends Item { public final int armorType; public final int damageReduceAmount; public final int renderIndex; + private final ItemArmor.ArmorMaterial material; public ItemArmor(ItemArmor.ArmorMaterial material, int renderIndex, int armorType) { @@ -92,46 +139,15 @@ public class ItemArmor extends Item { BlockDispenser.dispenseBehaviorRegistry.putObject(this, dispenserBehavior); } - public int getColorFromItemStack(ItemStack itemstack, int i) { - if (i > 0) { - return 16777215; - } else { - int j = this.getColor(itemstack); - if (j < 0) { - j = 16777215; - } - - return j; - } - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. - */ - public int getItemEnchantability() { - return this.material.getEnchantability(); - } - - /**+ - * Return the armor material for this armor item. + /** + * + Return the armor material for this armor item. */ public ItemArmor.ArmorMaterial getArmorMaterial() { return this.material; } - /**+ - * Return whether the specified armor ItemStack has a color. - */ - public boolean hasColor(ItemStack parItemStack) { - return this.material != ItemArmor.ArmorMaterial.LEATHER ? false - : (!parItemStack.hasTagCompound() ? false - : (!parItemStack.getTagCompound().hasKey("display", 10) ? false - : parItemStack.getTagCompound().getCompoundTag("display").hasKey("color", 3))); - } - - /**+ - * Return the color for the specified armor ItemStack. + /** + * + Return the color for the specified armor ItemStack. */ public int getColor(ItemStack stack) { if (this.material != ItemArmor.ArmorMaterial.LEATHER) { @@ -149,8 +165,62 @@ public class ItemArmor extends Item { } } - /**+ - * Remove the color from the specified armor ItemStack. + public int getColorFromItemStack(ItemStack itemstack, int i) { + if (i > 0) { + return 16777215; + } else { + int j = this.getColor(itemstack); + if (j < 0) { + j = 16777215; + } + + return j; + } + } + + /** + * + Return whether this item is repairable in an anvil. + */ + public boolean getIsRepairable(ItemStack itemstack, ItemStack itemstack1) { + return this.material.getRepairItem() == itemstack1.getItem() ? true + : super.getIsRepairable(itemstack, itemstack1); + } + + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. + */ + public int getItemEnchantability() { + return this.material.getEnchantability(); + } + + /** + * + Return whether the specified armor ItemStack has a color. + */ + public boolean hasColor(ItemStack parItemStack) { + return this.material != ItemArmor.ArmorMaterial.LEATHER ? false + : (!parItemStack.hasTagCompound() ? false + : (!parItemStack.getTagCompound().hasKey("display", 10) ? false + : parItemStack.getTagCompound().getCompoundTag("display").hasKey("color", 3))); + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { + int i = EntityLiving.getArmorPosition(itemstack) - 1; + ItemStack itemstack1 = entityplayer.getCurrentArmor(i); + if (itemstack1 == null) { + entityplayer.setCurrentItemOrArmor(i, itemstack.copy()); + itemstack.stackSize = 0; + } + + return itemstack; + } + + /** + * + Remove the color from the specified armor ItemStack. */ public void removeColor(ItemStack stack) { if (this.material == ItemArmor.ArmorMaterial.LEATHER) { @@ -165,8 +235,8 @@ public class ItemArmor extends Item { } } - /**+ - * Sets the color of the specified armor ItemStack + /** + * + Sets the color of the specified armor ItemStack */ public void setColor(ItemStack stack, int color) { if (this.material != ItemArmor.ArmorMaterial.LEATHER) { @@ -186,68 +256,4 @@ public class ItemArmor extends Item { nbttagcompound1.setInteger("color", color); } } - - /**+ - * Return whether this item is repairable in an anvil. - */ - public boolean getIsRepairable(ItemStack itemstack, ItemStack itemstack1) { - return this.material.getRepairItem() == itemstack1.getItem() ? true - : super.getIsRepairable(itemstack, itemstack1); - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { - int i = EntityLiving.getArmorPosition(itemstack) - 1; - ItemStack itemstack1 = entityplayer.getCurrentArmor(i); - if (itemstack1 == null) { - entityplayer.setCurrentItemOrArmor(i, itemstack.copy()); - itemstack.stackSize = 0; - } - - return itemstack; - } - - public static enum ArmorMaterial { - LEATHER("leather", 5, new int[] { 1, 3, 2, 1 }, 15), CHAIN("chainmail", 15, new int[] { 2, 5, 4, 1 }, 12), - IRON("iron", 15, new int[] { 2, 6, 5, 2 }, 9), GOLD("gold", 7, new int[] { 2, 5, 3, 1 }, 25), - DIAMOND("diamond", 33, new int[] { 3, 8, 6, 3 }, 10); - - private final String name; - private final int maxDamageFactor; - private final int[] damageReductionAmountArray; - private final int enchantability; - - private ArmorMaterial(String name, int maxDamage, int[] reductionAmounts, int enchantability) { - this.name = name; - this.maxDamageFactor = maxDamage; - this.damageReductionAmountArray = reductionAmounts; - this.enchantability = enchantability; - } - - public int getDurability(int armorType) { - return ItemArmor.maxDamageArray[armorType] * this.maxDamageFactor; - } - - public int getDamageReductionAmount(int armorType) { - return this.damageReductionAmountArray[armorType]; - } - - public int getEnchantability() { - return this.enchantability; - } - - public Item getRepairItem() { - return this == LEATHER ? Items.leather - : (this == CHAIN ? Items.iron_ingot - : (this == GOLD ? Items.gold_ingot - : (this == IRON ? Items.iron_ingot : (this == DIAMOND ? Items.diamond : null)))); - } - - public String getName() { - return this.name; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemArmorStand.java b/src/game/java/net/minecraft/item/ItemArmorStand.java index d19d578a..b4002786 100644 --- a/src/game/java/net/minecraft/item/ItemArmorStand.java +++ b/src/game/java/net/minecraft/item/ItemArmorStand.java @@ -1,6 +1,7 @@ package net.minecraft.item; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; @@ -14,22 +15,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.Rotations; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,8 +43,20 @@ public class ItemArmorStand extends Item { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Called when a Block is right-clicked with this Item + private void applyRandomRotations(EntityArmorStand armorStand, EaglercraftRandom rand) { + Rotations rotations = armorStand.getHeadRotation(); + float f = rand.nextFloat() * 5.0F; + float f1 = rand.nextFloat() * 20.0F - 10.0F; + Rotations rotations1 = new Rotations(rotations.getX() + f, rotations.getY() + f1, rotations.getZ()); + armorStand.setHeadRotation(rotations1); + rotations = armorStand.getBodyRotation(); + f = rand.nextFloat() * 10.0F - 5.0F; + rotations1 = new Rotations(rotations.getX(), rotations.getY() + f, rotations.getZ()); + armorStand.setBodyRotation(rotations1); + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -96,16 +112,4 @@ public class ItemArmorStand extends Item { } } } - - private void applyRandomRotations(EntityArmorStand armorStand, EaglercraftRandom rand) { - Rotations rotations = armorStand.getHeadRotation(); - float f = rand.nextFloat() * 5.0F; - float f1 = rand.nextFloat() * 20.0F - 10.0F; - Rotations rotations1 = new Rotations(rotations.getX() + f, rotations.getY() + f1, rotations.getZ()); - armorStand.setHeadRotation(rotations1); - rotations = armorStand.getBodyRotation(); - f = rand.nextFloat() * 10.0F - 5.0F; - rotations1 = new Rotations(rotations.getX(), rotations.getY() + f, rotations.getZ()); - armorStand.setBodyRotation(rotations1); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemAxe.java b/src/game/java/net/minecraft/item/ItemAxe.java index 24dc879f..2d49b19b 100644 --- a/src/game/java/net/minecraft/item/ItemAxe.java +++ b/src/game/java/net/minecraft/item/ItemAxe.java @@ -8,22 +8,25 @@ import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/item/ItemBanner.java b/src/game/java/net/minecraft/item/ItemBanner.java index 7b0c6e71..af43d3c8 100644 --- a/src/game/java/net/minecraft/item/ItemBanner.java +++ b/src/game/java/net/minecraft/item/ItemBanner.java @@ -1,6 +1,7 @@ package net.minecraft.item; import java.util.List; + import net.minecraft.block.BlockStandingSign; import net.minecraft.block.BlockWallSign; import net.minecraft.creativetab.CreativeTabs; @@ -16,22 +17,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,8 +49,86 @@ public class ItemBanner extends ItemBlock { this.setMaxDamage(0); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + allows items to add custom lines of information to the mouseover + * description + */ + public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { + NBTTagCompound nbttagcompound = itemstack.getSubCompound("BlockEntityTag", false); + if (nbttagcompound != null && nbttagcompound.hasKey("Patterns")) { + NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); + + for (int i = 0; i < nbttaglist.tagCount() && i < 6; ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(nbttagcompound1.getInteger("Color")); + TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = TileEntityBanner.EnumBannerPattern + .getPatternByID(nbttagcompound1.getString("Pattern")); + if (tileentitybanner$enumbannerpattern != null) { + list.add(StatCollector + .translateToLocal("item.banner." + tileentitybanner$enumbannerpattern.getPatternName() + "." + + enumdyecolor.getUnlocalizedName())); + } + } + + } + } + + private EnumDyeColor getBaseColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + EnumDyeColor enumdyecolor = null; + if (nbttagcompound != null && nbttagcompound.hasKey("Base")) { + enumdyecolor = EnumDyeColor.byDyeDamage(nbttagcompound.getInteger("Base")); + } else { + enumdyecolor = EnumDyeColor.byDyeDamage(stack.getMetadata()); + } + + return enumdyecolor; + } + + public int getColorFromItemStack(ItemStack itemstack, int i) { + if (i == 0) { + return 16777215; + } else { + EnumDyeColor enumdyecolor = this.getBaseColor(itemstack); + return enumdyecolor.getMapColor().colorValue; + } + } + + /** + * + gets the CreativeTab this item is displayed on + */ + public CreativeTabs getCreativeTab() { + return CreativeTabs.tabDecorations; + } + + public String getItemStackDisplayName(ItemStack itemstack) { + String s = "item.banner."; + EnumDyeColor enumdyecolor = this.getBaseColor(itemstack); + s = s + enumdyecolor.getUnlocalizedName() + ".name"; + return StatCollector.translateToLocal(s); + } + + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs var2, List list) { + EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP; + for (int i = 0; i < colors.length; ++i) { + EnumDyeColor enumdyecolor = colors[i]; + NBTTagCompound nbttagcompound = new NBTTagCompound(); + TileEntityBanner.func_181020_a(nbttagcompound, enumdyecolor.getDyeDamage(), (NBTTagList) null); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setTag("BlockEntityTag", nbttagcompound); + ItemStack itemstack = new ItemStack(item, 1, enumdyecolor.getDyeDamage()); + itemstack.setTagCompound(nbttagcompound1); + list.add(itemstack); + } + + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -83,82 +165,4 @@ public class ItemBanner extends ItemBlock { } } } - - public String getItemStackDisplayName(ItemStack itemstack) { - String s = "item.banner."; - EnumDyeColor enumdyecolor = this.getBaseColor(itemstack); - s = s + enumdyecolor.getUnlocalizedName() + ".name"; - return StatCollector.translateToLocal(s); - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description - */ - public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { - NBTTagCompound nbttagcompound = itemstack.getSubCompound("BlockEntityTag", false); - if (nbttagcompound != null && nbttagcompound.hasKey("Patterns")) { - NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); - - for (int i = 0; i < nbttaglist.tagCount() && i < 6; ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(nbttagcompound1.getInteger("Color")); - TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = TileEntityBanner.EnumBannerPattern - .getPatternByID(nbttagcompound1.getString("Pattern")); - if (tileentitybanner$enumbannerpattern != null) { - list.add(StatCollector - .translateToLocal("item.banner." + tileentitybanner$enumbannerpattern.getPatternName() + "." - + enumdyecolor.getUnlocalizedName())); - } - } - - } - } - - public int getColorFromItemStack(ItemStack itemstack, int i) { - if (i == 0) { - return 16777215; - } else { - EnumDyeColor enumdyecolor = this.getBaseColor(itemstack); - return enumdyecolor.getMapColor().colorValue; - } - } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs var2, List list) { - EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP; - for (int i = 0; i < colors.length; ++i) { - EnumDyeColor enumdyecolor = colors[i]; - NBTTagCompound nbttagcompound = new NBTTagCompound(); - TileEntityBanner.func_181020_a(nbttagcompound, enumdyecolor.getDyeDamage(), (NBTTagList) null); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setTag("BlockEntityTag", nbttagcompound); - ItemStack itemstack = new ItemStack(item, 1, enumdyecolor.getDyeDamage()); - itemstack.setTagCompound(nbttagcompound1); - list.add(itemstack); - } - - } - - /**+ - * gets the CreativeTab this item is displayed on - */ - public CreativeTabs getCreativeTab() { - return CreativeTabs.tabDecorations; - } - - private EnumDyeColor getBaseColor(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - EnumDyeColor enumdyecolor = null; - if (nbttagcompound != null && nbttagcompound.hasKey("Base")) { - enumdyecolor = EnumDyeColor.byDyeDamage(nbttagcompound.getInteger("Base")); - } else { - enumdyecolor = EnumDyeColor.byDyeDamage(stack.getMetadata()); - } - - return enumdyecolor; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemBed.java b/src/game/java/net/minecraft/item/ItemBed.java index 87697062..7c985d94 100644 --- a/src/game/java/net/minecraft/item/ItemBed.java +++ b/src/game/java/net/minecraft/item/ItemBed.java @@ -11,22 +11,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,8 @@ public class ItemBed extends Item { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemBlock.java b/src/game/java/net/minecraft/item/ItemBlock.java index 29f6393a..6734d0fa 100644 --- a/src/game/java/net/minecraft/item/ItemBlock.java +++ b/src/game/java/net/minecraft/item/ItemBlock.java @@ -1,6 +1,7 @@ package net.minecraft.item; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.creativetab.CreativeTabs; @@ -14,44 +15,121 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemBlock extends Item { + public static boolean setTileEntityNBT(World worldIn, EntityPlayer pos, BlockPos stack, ItemStack parItemStack) { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + if (minecraftserver == null) { + return false; + } else { + if (parItemStack.hasTagCompound() && parItemStack.getTagCompound().hasKey("BlockEntityTag", 10)) { + TileEntity tileentity = worldIn.getTileEntity(stack); + if (tileentity != null) { + if (!worldIn.isRemote && tileentity.func_183000_F() + && !minecraftserver.getConfigurationManager().canSendCommands(pos.getGameProfile())) { + return false; + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttagcompound.copy(); + tileentity.writeToNBT(nbttagcompound); + NBTTagCompound nbttagcompound2 = (NBTTagCompound) parItemStack.getTagCompound() + .getTag("BlockEntityTag"); + nbttagcompound.merge(nbttagcompound2); + nbttagcompound.setInteger("x", stack.getX()); + nbttagcompound.setInteger("y", stack.getY()); + nbttagcompound.setInteger("z", stack.getZ()); + if (!nbttagcompound.equals(nbttagcompound1)) { + tileentity.readFromNBT(nbttagcompound); + tileentity.markDirty(); + return true; + } + } + } + + return false; + } + } + protected final Block block; public ItemBlock(Block block) { this.block = block; } - /**+ - * Sets the unlocalized name of this item to the string passed - * as the parameter, prefixed by "item." - */ - public ItemBlock setUnlocalizedName(String unlocalizedName) { - super.setUnlocalizedName(unlocalizedName); - return this; + public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing, EntityPlayer var4, + ItemStack itemstack) { + Block blockx = world.getBlockState(blockpos).getBlock(); + if (blockx == Blocks.snow_layer) { + enumfacing = EnumFacing.UP; + } else if (!blockx.isReplaceable(world, blockpos)) { + blockpos = blockpos.offset(enumfacing); + } + + return world.canBlockBePlaced(this.block, blockpos, false, enumfacing, (Entity) null, itemstack); } - /**+ - * Called when a Block is right-clicked with this Item + public Block getBlock() { + return this.block; + } + + /** + * + gets the CreativeTab this item is displayed on + */ + public CreativeTabs getCreativeTab() { + return this.block.getCreativeTabToDisplayOn(); + } + + public float getHeldItemBrightnessEagler(ItemStack itemStack) { + return this.block.getLightValue() * 0.06667f; + } + + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs creativetabs, List list) { + this.block.getSubBlocks(item, creativetabs, list); + } + + /** + * + Returns the unlocalized name of this item. + */ + public String getUnlocalizedName() { + return this.block.getUnlocalizedName(); + } + + /** + * + Returns the unlocalized name of this item. + */ + public String getUnlocalizedName(ItemStack var1) { + return this.block.getUnlocalizedName(); + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { @@ -89,86 +167,12 @@ public class ItemBlock extends Item { } } - public static boolean setTileEntityNBT(World worldIn, EntityPlayer pos, BlockPos stack, ItemStack parItemStack) { - MinecraftServer minecraftserver = MinecraftServer.getServer(); - if (minecraftserver == null) { - return false; - } else { - if (parItemStack.hasTagCompound() && parItemStack.getTagCompound().hasKey("BlockEntityTag", 10)) { - TileEntity tileentity = worldIn.getTileEntity(stack); - if (tileentity != null) { - if (!worldIn.isRemote && tileentity.func_183000_F() - && !minecraftserver.getConfigurationManager().canSendCommands(pos.getGameProfile())) { - return false; - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbttagcompound.copy(); - tileentity.writeToNBT(nbttagcompound); - NBTTagCompound nbttagcompound2 = (NBTTagCompound) parItemStack.getTagCompound() - .getTag("BlockEntityTag"); - nbttagcompound.merge(nbttagcompound2); - nbttagcompound.setInteger("x", stack.getX()); - nbttagcompound.setInteger("y", stack.getY()); - nbttagcompound.setInteger("z", stack.getZ()); - if (!nbttagcompound.equals(nbttagcompound1)) { - tileentity.readFromNBT(nbttagcompound); - tileentity.markDirty(); - return true; - } - } - } - - return false; - } - } - - public boolean canPlaceBlockOnSide(World world, BlockPos blockpos, EnumFacing enumfacing, EntityPlayer var4, - ItemStack itemstack) { - Block blockx = world.getBlockState(blockpos).getBlock(); - if (blockx == Blocks.snow_layer) { - enumfacing = EnumFacing.UP; - } else if (!blockx.isReplaceable(world, blockpos)) { - blockpos = blockpos.offset(enumfacing); - } - - return world.canBlockBePlaced(this.block, blockpos, false, enumfacing, (Entity) null, itemstack); - } - - /**+ - * Returns the unlocalized name of this item. + /** + * + Sets the unlocalized name of this item to the string passed as the + * parameter, prefixed by "item." */ - public String getUnlocalizedName(ItemStack var1) { - return this.block.getUnlocalizedName(); - } - - /**+ - * Returns the unlocalized name of this item. - */ - public String getUnlocalizedName() { - return this.block.getUnlocalizedName(); - } - - /**+ - * gets the CreativeTab this item is displayed on - */ - public CreativeTabs getCreativeTab() { - return this.block.getCreativeTabToDisplayOn(); - } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs creativetabs, List list) { - this.block.getSubBlocks(item, creativetabs, list); - } - - public Block getBlock() { - return this.block; - } - - public float getHeldItemBrightnessEagler(ItemStack itemStack) { - return this.block.getLightValue() * 0.06667f; + public ItemBlock setUnlocalizedName(String unlocalizedName) { + super.setUnlocalizedName(unlocalizedName); + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemBoat.java b/src/game/java/net/minecraft/item/ItemBoat.java index 4c8dc569..ace262e8 100644 --- a/src/game/java/net/minecraft/item/ItemBoat.java +++ b/src/game/java/net/minecraft/item/ItemBoat.java @@ -15,22 +15,25 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,9 +44,9 @@ public class ItemBoat extends Item { this.setCreativeTab(CreativeTabs.tabTransport); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { float f = 1.0F; diff --git a/src/game/java/net/minecraft/item/ItemBook.java b/src/game/java/net/minecraft/item/ItemBook.java index f7b06e81..e049997a 100644 --- a/src/game/java/net/minecraft/item/ItemBook.java +++ b/src/game/java/net/minecraft/item/ItemBook.java @@ -1,38 +1,41 @@ package net.minecraft.item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemBook extends Item { - /**+ - * Checks isDamagable and if it cannot be stacked - */ - public boolean isItemTool(ItemStack stack) { - return stack.stackSize == 1; - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. */ public int getItemEnchantability() { return 1; } + + /** + * + Checks isDamagable and if it cannot be stacked + */ + public boolean isItemTool(ItemStack stack) { + return stack.stackSize == 1; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemBow.java b/src/game/java/net/minecraft/item/ItemBow.java index 90755cbb..335bc2e0 100644 --- a/src/game/java/net/minecraft/item/ItemBow.java +++ b/src/game/java/net/minecraft/item/ItemBow.java @@ -9,22 +9,25 @@ import net.minecraft.init.Items; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,9 +41,53 @@ public class ItemBow extends Item { this.setCreativeTab(CreativeTabs.tabCombat); } - /**+ - * Called when the player stops using an Item (stops holding the - * right mouse button). + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. + */ + public int getItemEnchantability() { + return 1; + } + + /** + * + returns the action that specifies what animation to play when the items is + * being used + */ + public EnumAction getItemUseAction(ItemStack var1) { + return EnumAction.BOW; + } + + /** + * + How long it takes to use or consume an item + */ + public int getMaxItemUseDuration(ItemStack var1) { + return 72000; + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { + if (entityplayer.capabilities.isCreativeMode || entityplayer.inventory.hasItem(Items.arrow)) { + entityplayer.setItemInUse(itemstack, this.getMaxItemUseDuration(itemstack)); + } + + return itemstack; + } + + /** + * + Called when the player finishes using this Item (E.g. finishes eating.). + * Not called when the player stops using the Item before the action is + * complete. + */ + public ItemStack onItemUseFinish(ItemStack itemstack, World var2, EntityPlayer var3) { + return itemstack; + } + + /** + * + Called when the player stops using an Item (stops holding the right mouse + * button). */ public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityPlayer playerIn, int timeLeft) { boolean flag = playerIn.capabilities.isCreativeMode @@ -92,48 +139,4 @@ public class ItemBow extends Item { } } - - /**+ - * Called when the player finishes using this Item (E.g. - * finishes eating.). Not called when the player stops using the - * Item before the action is complete. - */ - public ItemStack onItemUseFinish(ItemStack itemstack, World var2, EntityPlayer var3) { - return itemstack; - } - - /**+ - * How long it takes to use or consume an item - */ - public int getMaxItemUseDuration(ItemStack var1) { - return 72000; - } - - /**+ - * returns the action that specifies what animation to play when - * the items is being used - */ - public EnumAction getItemUseAction(ItemStack var1) { - return EnumAction.BOW; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { - if (entityplayer.capabilities.isCreativeMode || entityplayer.inventory.hasItem(Items.arrow)) { - entityplayer.setItemInUse(itemstack, this.getMaxItemUseDuration(itemstack)); - } - - return itemstack; - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. - */ - public int getItemEnchantability() { - return 1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemBucket.java b/src/game/java/net/minecraft/item/ItemBucket.java index 543f152c..ee0b6c8a 100644 --- a/src/game/java/net/minecraft/item/ItemBucket.java +++ b/src/game/java/net/minecraft/item/ItemBucket.java @@ -14,22 +14,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,9 +46,23 @@ public class ItemBucket extends Item { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + private ItemStack fillBucket(ItemStack emptyBuckets, EntityPlayer player, Item fullBucket) { + if (player.capabilities.isCreativeMode) { + return emptyBuckets; + } else if (--emptyBuckets.stackSize <= 0) { + return new ItemStack(fullBucket); + } else { + if (!player.inventory.addItemStackToInventory(new ItemStack(fullBucket))) { + player.dropPlayerItemWithRandomChoice(new ItemStack(fullBucket, 1, 0), false); + } + + return emptyBuckets; + } + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { boolean flag = this.isFull == Blocks.air; @@ -101,20 +118,6 @@ public class ItemBucket extends Item { } } - private ItemStack fillBucket(ItemStack emptyBuckets, EntityPlayer player, Item fullBucket) { - if (player.capabilities.isCreativeMode) { - return emptyBuckets; - } else if (--emptyBuckets.stackSize <= 0) { - return new ItemStack(fullBucket); - } else { - if (!player.inventory.addItemStackToInventory(new ItemStack(fullBucket))) { - player.dropPlayerItemWithRandomChoice(new ItemStack(fullBucket, 1, 0), false); - } - - return emptyBuckets; - } - } - public boolean tryPlaceContainedLiquid(World worldIn, BlockPos pos) { if (this.isFull == Blocks.air) { return false; diff --git a/src/game/java/net/minecraft/item/ItemBucketMilk.java b/src/game/java/net/minecraft/item/ItemBucketMilk.java index 3af48048..264da848 100644 --- a/src/game/java/net/minecraft/item/ItemBucketMilk.java +++ b/src/game/java/net/minecraft/item/ItemBucketMilk.java @@ -6,22 +6,25 @@ import net.minecraft.init.Items; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,10 +35,34 @@ public class ItemBucketMilk extends Item { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called when the player finishes using this Item (E.g. - * finishes eating.). Not called when the player stops using the - * Item before the action is complete. + /** + * + returns the action that specifies what animation to play when the items is + * being used + */ + public EnumAction getItemUseAction(ItemStack stack) { + return EnumAction.DRINK; + } + + /** + * + How long it takes to use or consume an item + */ + public int getMaxItemUseDuration(ItemStack stack) { + return 32; + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { + playerIn.setItemInUse(itemStackIn, this.getMaxItemUseDuration(itemStackIn)); + return itemStackIn; + } + + /** + * + Called when the player finishes using this Item (E.g. finishes eating.). + * Not called when the player stops using the Item before the action is + * complete. */ public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityPlayer playerIn) { if (!playerIn.capabilities.isCreativeMode) { @@ -49,28 +76,4 @@ public class ItemBucketMilk extends Item { playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return stack.stackSize <= 0 ? new ItemStack(Items.bucket) : stack; } - - /**+ - * How long it takes to use or consume an item - */ - public int getMaxItemUseDuration(ItemStack stack) { - return 32; - } - - /**+ - * returns the action that specifies what animation to play when - * the items is being used - */ - public EnumAction getItemUseAction(ItemStack stack) { - return EnumAction.DRINK; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn) { - playerIn.setItemInUse(itemStackIn, this.getMaxItemUseDuration(itemStackIn)); - return itemStackIn; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemCarrotOnAStick.java b/src/game/java/net/minecraft/item/ItemCarrotOnAStick.java index 299f985b..b9cca53b 100644 --- a/src/game/java/net/minecraft/item/ItemCarrotOnAStick.java +++ b/src/game/java/net/minecraft/item/ItemCarrotOnAStick.java @@ -7,22 +7,25 @@ import net.minecraft.init.Items; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,24 +37,16 @@ public class ItemCarrotOnAStick extends Item { this.setMaxDamage(25); } - /**+ - * Returns True is the item is renderer in full 3D when hold. + /** + * + Returns True is the item is renderer in full 3D when hold. */ public boolean isFull3D() { return true; } - /**+ - * Returns true if this item should be rotated by 180 degrees - * around the Y axis when being held in an entities hands. - */ - public boolean shouldRotateAroundWhenRendering() { - return true; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { if (entityplayer.isRiding() && entityplayer.ridingEntity instanceof EntityPig) { @@ -71,4 +66,12 @@ public class ItemCarrotOnAStick extends Item { entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); return itemstack; } + + /** + * + Returns true if this item should be rotated by 180 degrees around the Y + * axis when being held in an entities hands. + */ + public boolean shouldRotateAroundWhenRendering() { + return true; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemCloth.java b/src/game/java/net/minecraft/item/ItemCloth.java index 6d294f63..d189dad6 100644 --- a/src/game/java/net/minecraft/item/ItemCloth.java +++ b/src/game/java/net/minecraft/item/ItemCloth.java @@ -2,22 +2,25 @@ package net.minecraft.item; import net.minecraft.block.Block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,19 +32,19 @@ public class ItemCloth extends ItemBlock { this.setHasSubtypes(true); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int i) { return i; } - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack itemstack) { return super.getUnlocalizedName() + "." + EnumDyeColor.byMetadata(itemstack.getMetadata()).getUnlocalizedName(); diff --git a/src/game/java/net/minecraft/item/ItemCoal.java b/src/game/java/net/minecraft/item/ItemCoal.java index 3779b7df..2d420e57 100644 --- a/src/game/java/net/minecraft/item/ItemCoal.java +++ b/src/game/java/net/minecraft/item/ItemCoal.java @@ -4,22 +4,25 @@ import java.util.List; import net.minecraft.creativetab.CreativeTabs; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,21 +34,21 @@ public class ItemCoal extends Item { this.setCreativeTab(CreativeTabs.tabMaterials); } - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. - */ - public String getUnlocalizedName(ItemStack itemstack) { - return itemstack.getMetadata() == 1 ? "item.charcoal" : "item.coal"; - } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) */ public void getSubItems(Item item, CreativeTabs var2, List list) { list.add(new ItemStack(item, 1, 0)); list.add(new ItemStack(item, 1, 1)); } + + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. + */ + public String getUnlocalizedName(ItemStack itemstack) { + return itemstack.getMetadata() == 1 ? "item.charcoal" : "item.coal"; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemColored.java b/src/game/java/net/minecraft/item/ItemColored.java index f1da60cf..f6496799 100644 --- a/src/game/java/net/minecraft/item/ItemColored.java +++ b/src/game/java/net/minecraft/item/ItemColored.java @@ -2,22 +2,25 @@ package net.minecraft.item; import net.minecraft.block.Block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,24 +43,19 @@ public class ItemColored extends ItemBlock { return this.coloredBlock.getRenderColor(this.coloredBlock.getStateFromMeta(itemstack.getMetadata())); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int i) { return i; } - public ItemColored setSubtypeNames(String[] names) { - this.subtypeNames = names; - return this; - } - - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack itemstack) { if (this.subtypeNames == null) { @@ -69,4 +67,9 @@ public class ItemColored extends ItemBlock { : super.getUnlocalizedName(itemstack); } } + + public ItemColored setSubtypeNames(String[] names) { + this.subtypeNames = names; + return this; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemDoor.java b/src/game/java/net/minecraft/item/ItemDoor.java index 32908f90..17656f24 100644 --- a/src/game/java/net/minecraft/item/ItemDoor.java +++ b/src/game/java/net/minecraft/item/ItemDoor.java @@ -9,60 +9,30 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemDoor extends Item { - private Block block; - - public ItemDoor(Block block) { - this.block = block; - this.setCreativeTab(CreativeTabs.tabRedstone); - } - - /**+ - * Called when a Block is right-clicked with this Item - */ - public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, - EnumFacing enumfacing, float var6, float var7, float var8) { - if (enumfacing != EnumFacing.UP) { - return false; - } else { - IBlockState iblockstate = world.getBlockState(blockpos); - Block blockx = iblockstate.getBlock(); - if (!blockx.isReplaceable(world, blockpos)) { - blockpos = blockpos.offset(enumfacing); - } - - if (!entityplayer.canPlayerEdit(blockpos, enumfacing, itemstack)) { - return false; - } else if (!this.block.canPlaceBlockAt(world, blockpos)) { - return false; - } else { - placeDoor(world, blockpos, EnumFacing.fromAngle((double) entityplayer.rotationYaw), this.block); - --itemstack.stackSize; - return true; - } - } - } - public static void placeDoor(World worldIn, BlockPos pos, EnumFacing facing, Block door) { BlockPos blockpos = pos.offset(facing.rotateY()); BlockPos blockpos1 = pos.offset(facing.rotateYCCW()); @@ -87,4 +57,37 @@ public class ItemDoor extends Item { worldIn.notifyNeighborsOfStateChange(pos, door); worldIn.notifyNeighborsOfStateChange(blockpos2, door); } + + private Block block; + + public ItemDoor(Block block) { + this.block = block; + this.setCreativeTab(CreativeTabs.tabRedstone); + } + + /** + * + Called when a Block is right-clicked with this Item + */ + public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, + EnumFacing enumfacing, float var6, float var7, float var8) { + if (enumfacing != EnumFacing.UP) { + return false; + } else { + IBlockState iblockstate = world.getBlockState(blockpos); + Block blockx = iblockstate.getBlock(); + if (!blockx.isReplaceable(world, blockpos)) { + blockpos = blockpos.offset(enumfacing); + } + + if (!entityplayer.canPlayerEdit(blockpos, enumfacing, itemstack)) { + return false; + } else if (!this.block.canPlaceBlockAt(world, blockpos)) { + return false; + } else { + placeDoor(world, blockpos, EnumFacing.fromAngle((double) entityplayer.rotationYaw), this.block); + --itemstack.stackSize; + return true; + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemDoublePlant.java b/src/game/java/net/minecraft/item/ItemDoublePlant.java index 1e747891..5016e819 100644 --- a/src/game/java/net/minecraft/item/ItemDoublePlant.java +++ b/src/game/java/net/minecraft/item/ItemDoublePlant.java @@ -6,22 +6,25 @@ import net.minecraft.block.Block; import net.minecraft.block.BlockDoublePlant; import net.minecraft.world.ColorizerGrass; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/item/ItemDye.java b/src/game/java/net/minecraft/item/ItemDye.java index 9b1d1c62..8ce61402 100644 --- a/src/game/java/net/minecraft/item/ItemDye.java +++ b/src/game/java/net/minecraft/item/ItemDye.java @@ -17,22 +17,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,24 +44,96 @@ public class ItemDye extends Item { public static final int[] dyeColors = new int[] { 1973019, 11743532, 3887386, 5320730, 2437522, 8073150, 2651799, 11250603, 4408131, 14188952, 4312372, 14602026, 6719955, 12801229, 15435844, 15790320 }; + public static boolean applyBonemeal(ItemStack stack, World worldIn, BlockPos target) { + IBlockState iblockstate = worldIn.getBlockState(target); + if (iblockstate.getBlock() instanceof IGrowable) { + IGrowable igrowable = (IGrowable) iblockstate.getBlock(); + if (igrowable.canGrow(worldIn, target, iblockstate, worldIn.isRemote)) { + if (!worldIn.isRemote) { + if (igrowable.canUseBonemeal(worldIn, worldIn.rand, target, iblockstate)) { + igrowable.grow(worldIn, worldIn.rand, target, iblockstate); + } + + --stack.stackSize; + } + + return true; + } + } + + return false; + } + + public static void spawnBonemealParticles(World worldIn, BlockPos pos, int amount) { + if (amount == 0) { + amount = 15; + } + + Block block = worldIn.getBlockState(pos).getBlock(); + if (block.getMaterial() != Material.air) { + block.setBlockBoundsBasedOnState(worldIn, pos); + + for (int i = 0; i < amount; ++i) { + double d0 = itemRand.nextGaussian() * 0.02D; + double d1 = itemRand.nextGaussian() * 0.02D; + double d2 = itemRand.nextGaussian() * 0.02D; + worldIn.spawnParticle(EnumParticleTypes.VILLAGER_HAPPY, + (double) ((float) pos.getX() + itemRand.nextFloat()), + (double) pos.getY() + (double) itemRand.nextFloat() * block.getBlockBoundsMaxY(), + (double) ((float) pos.getZ() + itemRand.nextFloat()), d0, d1, d2, new int[0]); + } + + } + } + public ItemDye() { this.setHasSubtypes(true); this.setMaxDamage(0); this.setCreativeTab(CreativeTabs.tabMaterials); } - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs var2, List list) { + for (int i = 0; i < 16; ++i) { + list.add(new ItemStack(item, 1, i)); + } + + } + + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack itemstack) { int i = itemstack.getMetadata(); return super.getUnlocalizedName() + "." + EnumDyeColor.byDyeDamage(i).getUnlocalizedName(); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Returns true if the item can be used on the given entity, e.g. shears on + * sheep. + */ + public boolean itemInteractionForEntity(ItemStack itemstack, EntityPlayer var2, EntityLivingBase entitylivingbase) { + if (entitylivingbase instanceof EntitySheep) { + EntitySheep entitysheep = (EntitySheep) entitylivingbase; + EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(itemstack.getMetadata()); + if (!entitysheep.getSheared() && entitysheep.getFleeceColor() != enumdyecolor) { + entitysheep.setFleeceColor(enumdyecolor); + --itemstack.stackSize; + } + + return true; + } else { + return false; + } + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { @@ -103,76 +178,4 @@ public class ItemDye extends Item { return false; } } - - public static boolean applyBonemeal(ItemStack stack, World worldIn, BlockPos target) { - IBlockState iblockstate = worldIn.getBlockState(target); - if (iblockstate.getBlock() instanceof IGrowable) { - IGrowable igrowable = (IGrowable) iblockstate.getBlock(); - if (igrowable.canGrow(worldIn, target, iblockstate, worldIn.isRemote)) { - if (!worldIn.isRemote) { - if (igrowable.canUseBonemeal(worldIn, worldIn.rand, target, iblockstate)) { - igrowable.grow(worldIn, worldIn.rand, target, iblockstate); - } - - --stack.stackSize; - } - - return true; - } - } - - return false; - } - - public static void spawnBonemealParticles(World worldIn, BlockPos pos, int amount) { - if (amount == 0) { - amount = 15; - } - - Block block = worldIn.getBlockState(pos).getBlock(); - if (block.getMaterial() != Material.air) { - block.setBlockBoundsBasedOnState(worldIn, pos); - - for (int i = 0; i < amount; ++i) { - double d0 = itemRand.nextGaussian() * 0.02D; - double d1 = itemRand.nextGaussian() * 0.02D; - double d2 = itemRand.nextGaussian() * 0.02D; - worldIn.spawnParticle(EnumParticleTypes.VILLAGER_HAPPY, - (double) ((float) pos.getX() + itemRand.nextFloat()), - (double) pos.getY() + (double) itemRand.nextFloat() * block.getBlockBoundsMaxY(), - (double) ((float) pos.getZ() + itemRand.nextFloat()), d0, d1, d2, new int[0]); - } - - } - } - - /**+ - * Returns true if the item can be used on the given entity, - * e.g. shears on sheep. - */ - public boolean itemInteractionForEntity(ItemStack itemstack, EntityPlayer var2, EntityLivingBase entitylivingbase) { - if (entitylivingbase instanceof EntitySheep) { - EntitySheep entitysheep = (EntitySheep) entitylivingbase; - EnumDyeColor enumdyecolor = EnumDyeColor.byDyeDamage(itemstack.getMetadata()); - if (!entitysheep.getSheared() && entitysheep.getFleeceColor() != enumdyecolor) { - entitysheep.setFleeceColor(enumdyecolor); - --itemstack.stackSize; - } - - return true; - } else { - return false; - } - } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs var2, List list) { - for (int i = 0; i < 16; ++i) { - list.add(new ItemStack(item, 1, i)); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemEditableBook.java b/src/game/java/net/minecraft/item/ItemEditableBook.java index 86731c09..5c7d3830 100644 --- a/src/game/java/net/minecraft/item/ItemEditableBook.java +++ b/src/game/java/net/minecraft/item/ItemEditableBook.java @@ -18,29 +18,35 @@ import net.minecraft.util.StatCollector; import net.minecraft.util.StringUtils; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemEditableBook extends Item { - public ItemEditableBook() { - this.setMaxStackSize(1); + /** + * + Gets the generation of the book (how many times it has been cloned) + */ + public static int getGeneration(ItemStack book) { + return book.getTagCompound().getInteger("generation"); } public static boolean validBookTagContents(NBTTagCompound nbt) { @@ -54,29 +60,13 @@ public class ItemEditableBook extends Item { } } - /**+ - * Gets the generation of the book (how many times it has been - * cloned) - */ - public static int getGeneration(ItemStack book) { - return book.getTagCompound().getInteger("generation"); + public ItemEditableBook() { + this.setMaxStackSize(1); } - public String getItemStackDisplayName(ItemStack itemstack) { - if (itemstack.hasTagCompound()) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound(); - String s = nbttagcompound.getString("title"); - if (!StringUtils.isNullOrEmpty(s)) { - return s; - } - } - - return super.getItemStackDisplayName(itemstack); - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description + /** + * + allows items to add custom lines of information to the mouseover + * description */ public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { if (itemstack.hasTagCompound()) { @@ -93,9 +83,25 @@ public class ItemEditableBook extends Item { } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + public String getItemStackDisplayName(ItemStack itemstack) { + if (itemstack.hasTagCompound()) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound(); + String s = nbttagcompound.getString("title"); + if (!StringUtils.isNullOrEmpty(s)) { + return s; + } + } + + return super.getItemStackDisplayName(itemstack); + } + + public boolean hasEffect(ItemStack var1) { + return true; + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (!world.isRemote) { @@ -141,8 +147,4 @@ public class ItemEditableBook extends Item { } } } - - public boolean hasEffect(ItemStack var1) { - return true; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemEgg.java b/src/game/java/net/minecraft/item/ItemEgg.java index 7ea5127b..e4bb6190 100644 --- a/src/game/java/net/minecraft/item/ItemEgg.java +++ b/src/game/java/net/minecraft/item/ItemEgg.java @@ -6,22 +6,25 @@ import net.minecraft.entity.projectile.EntityEgg; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,9 +35,9 @@ public class ItemEgg extends Item { this.setCreativeTab(CreativeTabs.tabMaterials); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (!entityplayer.capabilities.isCreativeMode) { diff --git a/src/game/java/net/minecraft/item/ItemEmptyMap.java b/src/game/java/net/minecraft/item/ItemEmptyMap.java index ecc726b9..fb919402 100644 --- a/src/game/java/net/minecraft/item/ItemEmptyMap.java +++ b/src/game/java/net/minecraft/item/ItemEmptyMap.java @@ -7,22 +7,25 @@ import net.minecraft.stats.StatList; import net.minecraft.world.World; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,9 +35,9 @@ public class ItemEmptyMap extends ItemMapBase { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { ItemStack itemstack1 = new ItemStack(Items.filled_map, 1, world.getUniqueDataId("map")); diff --git a/src/game/java/net/minecraft/item/ItemEnchantedBook.java b/src/game/java/net/minecraft/item/ItemEnchantedBook.java index 8d58c412..5a7d9e3d 100644 --- a/src/game/java/net/minecraft/item/ItemEnchantedBook.java +++ b/src/game/java/net/minecraft/item/ItemEnchantedBook.java @@ -1,8 +1,8 @@ package net.minecraft.item; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.enchantment.EnchantmentHelper; @@ -12,73 +12,32 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.WeightedRandomChestContent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemEnchantedBook extends Item { - public boolean hasEffect(ItemStack var1) { - return true; - } - - /**+ - * Checks isDamagable and if it cannot be stacked - */ - public boolean isItemTool(ItemStack var1) { - return false; - } - - /**+ - * Return an item rarity from EnumRarity - */ - public EnumRarity getRarity(ItemStack itemstack) { - return this.getEnchantments(itemstack).tagCount() > 0 ? EnumRarity.UNCOMMON : super.getRarity(itemstack); - } - - public NBTTagList getEnchantments(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getTagCompound(); - return nbttagcompound != null && nbttagcompound.hasKey("StoredEnchantments", 9) - ? (NBTTagList) nbttagcompound.getTag("StoredEnchantments") - : new NBTTagList(); - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description - */ - public void addInformation(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { - super.addInformation(itemstack, entityplayer, list, flag); - NBTTagList nbttaglist = this.getEnchantments(itemstack); - if (nbttaglist != null) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); - short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - if (Enchantment.getEnchantmentById(short1) != null) { - list.add(Enchantment.getEnchantmentById(short1).getTranslatedName(short2)); - } - } - } - - } - - /**+ - * Adds an stored enchantment to an enchanted book ItemStack + /** + * + Adds an stored enchantment to an enchanted book ItemStack */ public void addEnchantment(ItemStack stack, EnchantmentData enchantment) { NBTTagList nbttaglist = this.getEnchantments(stack); @@ -110,13 +69,23 @@ public class ItemEnchantedBook extends Item { stack.getTagCompound().setTag("StoredEnchantments", nbttaglist); } - /**+ - * Returns the ItemStack of an enchanted version of this item. + /** + * + allows items to add custom lines of information to the mouseover + * description */ - public ItemStack getEnchantedItemStack(EnchantmentData data) { - ItemStack itemstack = new ItemStack(this); - this.addEnchantment(itemstack, data); - return itemstack; + public void addInformation(ItemStack itemstack, EntityPlayer entityplayer, List list, boolean flag) { + super.addInformation(itemstack, entityplayer, list, flag); + NBTTagList nbttaglist = this.getEnchantments(itemstack); + if (nbttaglist != null) { + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + short short1 = nbttaglist.getCompoundTagAt(i).getShort("id"); + short short2 = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + if (Enchantment.getEnchantmentById(short1) != null) { + list.add(Enchantment.getEnchantmentById(short1).getTranslatedName(short2)); + } + } + } + } public void getAll(Enchantment enchantment, List list) { @@ -126,6 +95,22 @@ public class ItemEnchantedBook extends Item { } + /** + * + Returns the ItemStack of an enchanted version of this item. + */ + public ItemStack getEnchantedItemStack(EnchantmentData data) { + ItemStack itemstack = new ItemStack(this); + this.addEnchantment(itemstack, data); + return itemstack; + } + + public NBTTagList getEnchantments(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getTagCompound(); + return nbttagcompound != null && nbttagcompound.hasKey("StoredEnchantments", 9) + ? (NBTTagList) nbttagcompound.getTag("StoredEnchantments") + : new NBTTagList(); + } + public WeightedRandomChestContent getRandom(EaglercraftRandom rand) { return this.getRandom(rand, 1, 1, 1); } @@ -135,4 +120,22 @@ public class ItemEnchantedBook extends Item { EnchantmentHelper.addRandomEnchantment(rand, itemstack, 30); return new WeightedRandomChestContent(itemstack, minChance, maxChance, weight); } + + /** + * + Return an item rarity from EnumRarity + */ + public EnumRarity getRarity(ItemStack itemstack) { + return this.getEnchantments(itemstack).tagCount() > 0 ? EnumRarity.UNCOMMON : super.getRarity(itemstack); + } + + public boolean hasEffect(ItemStack var1) { + return true; + } + + /** + * + Checks isDamagable and if it cannot be stacked + */ + public boolean isItemTool(ItemStack var1) { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemEnderEye.java b/src/game/java/net/minecraft/item/ItemEnderEye.java index 5fc74160..7fe58661 100644 --- a/src/game/java/net/minecraft/item/ItemEnderEye.java +++ b/src/game/java/net/minecraft/item/ItemEnderEye.java @@ -13,22 +13,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,8 +41,41 @@ public class ItemEnderEye extends Item { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, false); + if (movingobjectposition != null + && movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK + && world.getBlockState(movingobjectposition.getBlockPos()).getBlock() == Blocks.end_portal_frame) { + return itemstack; + } else { + if (!world.isRemote) { + BlockPos blockpos = world.getStrongholdPos("Stronghold", new BlockPos(entityplayer)); + if (blockpos != null) { + EntityEnderEye entityendereye = new EntityEnderEye(world, entityplayer.posX, entityplayer.posY, + entityplayer.posZ); + entityendereye.moveTowards(blockpos); + world.spawnEntityInWorld(entityendereye); + world.playSoundAtEntity(entityplayer, "random.bow", 0.5F, + 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); + world.playAuxSFXAtEntity((EntityPlayer) null, 1002, new BlockPos(entityplayer), 0); + if (!entityplayer.capabilities.isCreativeMode) { + --itemstack.stackSize; + } + + entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); + } + } + + return itemstack; + } + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -135,39 +171,6 @@ public class ItemEnderEye extends Item { } } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, false); - if (movingobjectposition != null - && movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK - && world.getBlockState(movingobjectposition.getBlockPos()).getBlock() == Blocks.end_portal_frame) { - return itemstack; - } else { - if (!world.isRemote) { - BlockPos blockpos = world.getStrongholdPos("Stronghold", new BlockPos(entityplayer)); - if (blockpos != null) { - EntityEnderEye entityendereye = new EntityEnderEye(world, entityplayer.posX, entityplayer.posY, - entityplayer.posZ); - entityendereye.moveTowards(blockpos); - world.spawnEntityInWorld(entityendereye); - world.playSoundAtEntity(entityplayer, "random.bow", 0.5F, - 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); - world.playAuxSFXAtEntity((EntityPlayer) null, 1002, new BlockPos(entityplayer), 0); - if (!entityplayer.capabilities.isCreativeMode) { - --itemstack.stackSize; - } - - entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); - } - } - - return itemstack; - } - } - public boolean shouldUseOnTouchEagler(ItemStack itemStack) { return true; } diff --git a/src/game/java/net/minecraft/item/ItemEnderPearl.java b/src/game/java/net/minecraft/item/ItemEnderPearl.java index b74d01b1..77485999 100644 --- a/src/game/java/net/minecraft/item/ItemEnderPearl.java +++ b/src/game/java/net/minecraft/item/ItemEnderPearl.java @@ -7,22 +7,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +36,9 @@ public class ItemEnderPearl extends Item { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (entityplayer.capabilities.isCreativeMode && world.isRemote diff --git a/src/game/java/net/minecraft/item/ItemExpBottle.java b/src/game/java/net/minecraft/item/ItemExpBottle.java index 585f0fa2..48df0628 100644 --- a/src/game/java/net/minecraft/item/ItemExpBottle.java +++ b/src/game/java/net/minecraft/item/ItemExpBottle.java @@ -6,22 +6,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,9 +38,9 @@ public class ItemExpBottle extends Item { return true; } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (!entityplayer.capabilities.isCreativeMode) { diff --git a/src/game/java/net/minecraft/item/ItemFireball.java b/src/game/java/net/minecraft/item/ItemFireball.java index 6fc102df..0a35d3b1 100644 --- a/src/game/java/net/minecraft/item/ItemFireball.java +++ b/src/game/java/net/minecraft/item/ItemFireball.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +36,8 @@ public class ItemFireball extends Item { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemFirework.java b/src/game/java/net/minecraft/item/ItemFirework.java index 59adab63..dd2f8ad4 100644 --- a/src/game/java/net/minecraft/item/ItemFirework.java +++ b/src/game/java/net/minecraft/item/ItemFirework.java @@ -1,8 +1,10 @@ package net.minecraft.item; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.entity.item.EntityFireworkRocket; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; @@ -12,51 +14,34 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemFirework extends Item { - /**+ - * Called when a Block is right-clicked with this Item - */ - public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, - EnumFacing var5, float f, float f1, float f2) { - if (!world.isRemote) { - EntityFireworkRocket entityfireworkrocket = new EntityFireworkRocket(world, - (double) ((float) blockpos.getX() + f), (double) ((float) blockpos.getY() + f1), - (double) ((float) blockpos.getZ() + f2), itemstack); - world.spawnEntityInWorld(entityfireworkrocket); - if (!entityplayer.capabilities.isCreativeMode) { - --itemstack.stackSize; - } - - return true; - } else { - return false; - } - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description + /** + * + allows items to add custom lines of information to the mouseover + * description */ public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { if (itemstack.hasTagCompound()) { @@ -87,6 +72,26 @@ public class ItemFirework extends Item { } } + /** + * + Called when a Block is right-clicked with this Item + */ + public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, + EnumFacing var5, float f, float f1, float f2) { + if (!world.isRemote) { + EntityFireworkRocket entityfireworkrocket = new EntityFireworkRocket(world, + (double) ((float) blockpos.getX() + f), (double) ((float) blockpos.getY() + f1), + (double) ((float) blockpos.getZ() + f2), itemstack); + world.spawnEntityInWorld(entityfireworkrocket); + if (!entityplayer.capabilities.isCreativeMode) { + --itemstack.stackSize; + } + + return true; + } else { + return false; + } + } + public boolean shouldUseOnTouchEagler(ItemStack itemStack) { return true; } diff --git a/src/game/java/net/minecraft/item/ItemFireworkCharge.java b/src/game/java/net/minecraft/item/ItemFireworkCharge.java index 9095c588..77a1d507 100644 --- a/src/game/java/net/minecraft/item/ItemFireworkCharge.java +++ b/src/game/java/net/minecraft/item/ItemFireworkCharge.java @@ -8,85 +8,30 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagIntArray; import net.minecraft.util.StatCollector; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemFireworkCharge extends Item { - public int getColorFromItemStack(ItemStack itemstack, int i) { - if (i != 1) { - return super.getColorFromItemStack(itemstack, i); - } else { - NBTBase nbtbase = getExplosionTag(itemstack, "Colors"); - if (!(nbtbase instanceof NBTTagIntArray)) { - return 9079434; - } else { - NBTTagIntArray nbttagintarray = (NBTTagIntArray) nbtbase; - int[] aint = nbttagintarray.getIntArray(); - if (aint.length == 1) { - return aint[0]; - } else { - int j = 0; - int k = 0; - int l = 0; - - for (int m = 0; m < aint.length; ++m) { - int i1 = aint[m]; - j += (i1 & 16711680) >> 16; - k += (i1 & '\uff00') >> 8; - l += (i1 & 255) >> 0; - } - - j = j / aint.length; - k = k / aint.length; - l = l / aint.length; - return j << 16 | k << 8 | l; - } - } - } - } - - public static NBTBase getExplosionTag(ItemStack stack, String key) { - if (stack.hasTagCompound()) { - NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Explosion"); - if (nbttagcompound != null) { - return nbttagcompound.getTag(key); - } - } - - return null; - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description - */ - public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { - if (itemstack.hasTagCompound()) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("Explosion"); - if (nbttagcompound != null) { - addExplosionInfo(nbttagcompound, list); - } - } - - } - public static void addExplosionInfo(NBTTagCompound nbt, List tooltip) { byte b0 = nbt.getByte("Type"); if (b0 >= 0 && b0 <= 4) { @@ -168,4 +113,62 @@ public class ItemFireworkCharge extends Item { } } + + public static NBTBase getExplosionTag(ItemStack stack, String key) { + if (stack.hasTagCompound()) { + NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Explosion"); + if (nbttagcompound != null) { + return nbttagcompound.getTag(key); + } + } + + return null; + } + + /** + * + allows items to add custom lines of information to the mouseover + * description + */ + public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { + if (itemstack.hasTagCompound()) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("Explosion"); + if (nbttagcompound != null) { + addExplosionInfo(nbttagcompound, list); + } + } + + } + + public int getColorFromItemStack(ItemStack itemstack, int i) { + if (i != 1) { + return super.getColorFromItemStack(itemstack, i); + } else { + NBTBase nbtbase = getExplosionTag(itemstack, "Colors"); + if (!(nbtbase instanceof NBTTagIntArray)) { + return 9079434; + } else { + NBTTagIntArray nbttagintarray = (NBTTagIntArray) nbtbase; + int[] aint = nbttagintarray.getIntArray(); + if (aint.length == 1) { + return aint[0]; + } else { + int j = 0; + int k = 0; + int l = 0; + + for (int m = 0; m < aint.length; ++m) { + int i1 = aint[m]; + j += (i1 & 16711680) >> 16; + k += (i1 & '\uff00') >> 8; + l += (i1 & 255) >> 0; + } + + j = j / aint.length; + k = k / aint.length; + l = l / aint.length; + return j << 16 | k << 8 | l; + } + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemFishFood.java b/src/game/java/net/minecraft/item/ItemFishFood.java index 4eb24e16..0ae57c54 100644 --- a/src/game/java/net/minecraft/item/ItemFishFood.java +++ b/src/game/java/net/minecraft/item/ItemFishFood.java @@ -12,27 +12,119 @@ import net.minecraft.potion.PotionEffect; import net.minecraft.potion.PotionHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemFishFood extends ItemFood { + public static enum FishType { + COD(0, "cod", 2, 0.1F, 5, 0.6F), SALMON(1, "salmon", 2, 0.1F, 6, 0.8F), CLOWNFISH(2, "clownfish", 1, 0.1F), + PUFFERFISH(3, "pufferfish", 1, 0.1F); + + private static final Map META_LOOKUP = Maps.newHashMap(); + static { + ItemFishFood.FishType[] types = values(); + for (int i = 0; i < types.length; ++i) { + META_LOOKUP.put(Integer.valueOf(types[i].getMetadata()), types[i]); + } + + } + + public static ItemFishFood.FishType byItemStack(ItemStack stack) { + return stack.getItem() instanceof ItemFishFood ? byMetadata(stack.getMetadata()) : COD; + } + + public static ItemFishFood.FishType byMetadata(int meta) { + ItemFishFood.FishType itemfishfood$fishtype = (ItemFishFood.FishType) META_LOOKUP + .get(Integer.valueOf(meta)); + return itemfishfood$fishtype == null ? COD : itemfishfood$fishtype; + } + + private final int meta; + private final String unlocalizedName; + private final int uncookedHealAmount; + private final float uncookedSaturationModifier; + + private final int cookedHealAmount; + + private final float cookedSaturationModifier; + + private boolean cookable = false; + + private FishType(int meta, String unlocalizedName, int uncookedHeal, float uncookedSaturation) { + this.meta = meta; + this.unlocalizedName = unlocalizedName; + this.uncookedHealAmount = uncookedHeal; + this.uncookedSaturationModifier = uncookedSaturation; + this.cookedHealAmount = 0; + this.cookedSaturationModifier = 0.0F; + this.cookable = false; + } + + private FishType(int meta, String unlocalizedName, int uncookedHeal, float uncookedSaturation, int cookedHeal, + float cookedSaturation) { + this.meta = meta; + this.unlocalizedName = unlocalizedName; + this.uncookedHealAmount = uncookedHeal; + this.uncookedSaturationModifier = uncookedSaturation; + this.cookedHealAmount = cookedHeal; + this.cookedSaturationModifier = cookedSaturation; + this.cookable = true; + } + + public boolean canCook() { + return this.cookable; + } + + public int getCookedHealAmount() { + return this.cookedHealAmount; + } + + public float getCookedSaturationModifier() { + return this.cookedSaturationModifier; + } + + public int getMetadata() { + return this.meta; + } + + public int getUncookedHealAmount() { + return this.uncookedHealAmount; + } + + public float getUncookedSaturationModifier() { + return this.uncookedSaturationModifier; + } + + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. + */ + public String getUnlocalizedName() { + return this.unlocalizedName; + } + } + private final boolean cooked; public ItemFishFood(boolean cooked) { @@ -46,32 +138,21 @@ public class ItemFishFood extends ItemFood { : itemfishfood$fishtype.getUncookedHealAmount(); } - public float getSaturationModifier(ItemStack stack) { - ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); - return this.cooked && itemfishfood$fishtype.canCook() ? itemfishfood$fishtype.getCookedSaturationModifier() - : itemfishfood$fishtype.getUncookedSaturationModifier(); - } - public String getPotionEffect(ItemStack stack) { return ItemFishFood.FishType.byItemStack(stack) == ItemFishFood.FishType.PUFFERFISH ? PotionHelper.pufferfishEffect : null; } - protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) { + public float getSaturationModifier(ItemStack stack) { ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); - if (itemfishfood$fishtype == ItemFishFood.FishType.PUFFERFISH) { - player.addPotionEffect(new PotionEffect(Potion.poison.id, 1200, 3)); - player.addPotionEffect(new PotionEffect(Potion.hunger.id, 300, 2)); - player.addPotionEffect(new PotionEffect(Potion.confusion.id, 300, 1)); - } - - super.onFoodEaten(stack, worldIn, player); + return this.cooked && itemfishfood$fishtype.canCook() ? itemfishfood$fishtype.getCookedSaturationModifier() + : itemfishfood$fishtype.getUncookedSaturationModifier(); } - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) */ public void getSubItems(Item var1, CreativeTabs var2, List list) { ItemFishFood.FishType[] types = ItemFishFood.FishType.values(); @@ -84,10 +165,10 @@ public class ItemFishFood extends ItemFood { } - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack itemstack) { ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(itemstack); @@ -95,89 +176,14 @@ public class ItemFishFood extends ItemFood { + (this.cooked && itemfishfood$fishtype.canCook() ? "cooked" : "raw"); } - public static enum FishType { - COD(0, "cod", 2, 0.1F, 5, 0.6F), SALMON(1, "salmon", 2, 0.1F, 6, 0.8F), CLOWNFISH(2, "clownfish", 1, 0.1F), - PUFFERFISH(3, "pufferfish", 1, 0.1F); - - private static final Map META_LOOKUP = Maps.newHashMap(); - private final int meta; - private final String unlocalizedName; - private final int uncookedHealAmount; - private final float uncookedSaturationModifier; - private final int cookedHealAmount; - private final float cookedSaturationModifier; - private boolean cookable = false; - - private FishType(int meta, String unlocalizedName, int uncookedHeal, float uncookedSaturation, int cookedHeal, - float cookedSaturation) { - this.meta = meta; - this.unlocalizedName = unlocalizedName; - this.uncookedHealAmount = uncookedHeal; - this.uncookedSaturationModifier = uncookedSaturation; - this.cookedHealAmount = cookedHeal; - this.cookedSaturationModifier = cookedSaturation; - this.cookable = true; + protected void onFoodEaten(ItemStack stack, World worldIn, EntityPlayer player) { + ItemFishFood.FishType itemfishfood$fishtype = ItemFishFood.FishType.byItemStack(stack); + if (itemfishfood$fishtype == ItemFishFood.FishType.PUFFERFISH) { + player.addPotionEffect(new PotionEffect(Potion.poison.id, 1200, 3)); + player.addPotionEffect(new PotionEffect(Potion.hunger.id, 300, 2)); + player.addPotionEffect(new PotionEffect(Potion.confusion.id, 300, 1)); } - private FishType(int meta, String unlocalizedName, int uncookedHeal, float uncookedSaturation) { - this.meta = meta; - this.unlocalizedName = unlocalizedName; - this.uncookedHealAmount = uncookedHeal; - this.uncookedSaturationModifier = uncookedSaturation; - this.cookedHealAmount = 0; - this.cookedSaturationModifier = 0.0F; - this.cookable = false; - } - - public int getMetadata() { - return this.meta; - } - - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. - */ - public String getUnlocalizedName() { - return this.unlocalizedName; - } - - public int getUncookedHealAmount() { - return this.uncookedHealAmount; - } - - public float getUncookedSaturationModifier() { - return this.uncookedSaturationModifier; - } - - public int getCookedHealAmount() { - return this.cookedHealAmount; - } - - public float getCookedSaturationModifier() { - return this.cookedSaturationModifier; - } - - public boolean canCook() { - return this.cookable; - } - - public static ItemFishFood.FishType byMetadata(int meta) { - ItemFishFood.FishType itemfishfood$fishtype = (ItemFishFood.FishType) META_LOOKUP - .get(Integer.valueOf(meta)); - return itemfishfood$fishtype == null ? COD : itemfishfood$fishtype; - } - - public static ItemFishFood.FishType byItemStack(ItemStack stack) { - return stack.getItem() instanceof ItemFishFood ? byMetadata(stack.getMetadata()) : COD; - } - - static { - ItemFishFood.FishType[] types = values(); - for (int i = 0; i < types.length; ++i) { - META_LOOKUP.put(Integer.valueOf(types[i].getMetadata()), types[i]); - } - - } + super.onFoodEaten(stack, worldIn, player); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemFishingRod.java b/src/game/java/net/minecraft/item/ItemFishingRod.java index 2782076c..066332fa 100644 --- a/src/game/java/net/minecraft/item/ItemFishingRod.java +++ b/src/game/java/net/minecraft/item/ItemFishingRod.java @@ -6,22 +6,25 @@ import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,24 +36,31 @@ public class ItemFishingRod extends Item { this.setCreativeTab(CreativeTabs.tabTools); } - /**+ - * Returns True is the item is renderer in full 3D when hold. + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. + */ + public int getItemEnchantability() { + return 1; + } + + /** + * + Returns True is the item is renderer in full 3D when hold. */ public boolean isFull3D() { return true; } - /**+ - * Returns true if this item should be rotated by 180 degrees - * around the Y axis when being held in an entities hands. + /** + * + Checks isDamagable and if it cannot be stacked */ - public boolean shouldRotateAroundWhenRendering() { - return true; + public boolean isItemTool(ItemStack itemstack) { + return super.isItemTool(itemstack); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (entityplayer.fishEntity != null) { @@ -70,18 +80,11 @@ public class ItemFishingRod extends Item { return itemstack; } - /**+ - * Checks isDamagable and if it cannot be stacked + /** + * + Returns true if this item should be rotated by 180 degrees around the Y + * axis when being held in an entities hands. */ - public boolean isItemTool(ItemStack itemstack) { - return super.isItemTool(itemstack); - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. - */ - public int getItemEnchantability() { - return 1; + public boolean shouldRotateAroundWhenRendering() { + return true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemFlintAndSteel.java b/src/game/java/net/minecraft/item/ItemFlintAndSteel.java index 17ed9d91..d35a3335 100644 --- a/src/game/java/net/minecraft/item/ItemFlintAndSteel.java +++ b/src/game/java/net/minecraft/item/ItemFlintAndSteel.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,8 +38,8 @@ public class ItemFlintAndSteel extends Item { this.setCreativeTab(CreativeTabs.tabTools); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemFood.java b/src/game/java/net/minecraft/item/ItemFood.java index a8952fd1..193d08c2 100644 --- a/src/game/java/net/minecraft/item/ItemFood.java +++ b/src/game/java/net/minecraft/item/ItemFood.java @@ -6,22 +6,25 @@ import net.minecraft.potion.PotionEffect; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +40,10 @@ public class ItemFood extends Item { private int potionAmplifier; private float potionEffectProbability; + public ItemFood(int amount, boolean isWolfFood) { + this(amount, 0.6F, isWolfFood); + } + public ItemFood(int amount, float saturation, boolean isWolfFood) { this.itemUseDuration = 32; this.healAmount = amount; @@ -45,22 +52,34 @@ public class ItemFood extends Item { this.setCreativeTab(CreativeTabs.tabFood); } - public ItemFood(int amount, boolean isWolfFood) { - this(amount, 0.6F, isWolfFood); + public int getHealAmount(ItemStack var1) { + return this.healAmount; } - /**+ - * Called when the player finishes using this Item (E.g. - * finishes eating.). Not called when the player stops using the - * Item before the action is complete. + /** + * + returns the action that specifies what animation to play when the items is + * being used */ - public ItemStack onItemUseFinish(ItemStack itemstack, World world, EntityPlayer entityplayer) { - --itemstack.stackSize; - entityplayer.getFoodStats().addStats(this, itemstack); - world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); - this.onFoodEaten(itemstack, world, entityplayer); - entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); - return itemstack; + public EnumAction getItemUseAction(ItemStack var1) { + return EnumAction.EAT; + } + + /** + * + How long it takes to use or consume an item + */ + public int getMaxItemUseDuration(ItemStack var1) { + return 32; + } + + public float getSaturationModifier(ItemStack var1) { + return this.saturationModifier; + } + + /** + * + Whether wolves like this food (true for raw and cooked porkchop). + */ + public boolean isWolfsFavoriteMeat() { + return this.isWolfsFavoriteMeat; } protected void onFoodEaten(ItemStack var1, World world, EntityPlayer entityplayer) { @@ -71,24 +90,9 @@ public class ItemFood extends Item { } - /**+ - * How long it takes to use or consume an item - */ - public int getMaxItemUseDuration(ItemStack var1) { - return 32; - } - - /**+ - * returns the action that specifies what animation to play when - * the items is being used - */ - public EnumAction getItemUseAction(ItemStack var1) { - return EnumAction.EAT; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { if (entityplayer.canEat(this.alwaysEdible)) { @@ -98,26 +102,32 @@ public class ItemFood extends Item { return itemstack; } - public int getHealAmount(ItemStack var1) { - return this.healAmount; - } - - public float getSaturationModifier(ItemStack var1) { - return this.saturationModifier; - } - - /**+ - * Whether wolves like this food (true for raw and cooked - * porkchop). + /** + * + Called when the player finishes using this Item (E.g. finishes eating.). + * Not called when the player stops using the Item before the action is + * complete. */ - public boolean isWolfsFavoriteMeat() { - return this.isWolfsFavoriteMeat; + public ItemStack onItemUseFinish(ItemStack itemstack, World world, EntityPlayer entityplayer) { + --itemstack.stackSize; + entityplayer.getFoodStats().addStats(this, itemstack); + world.playSoundAtEntity(entityplayer, "random.burp", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F); + this.onFoodEaten(itemstack, world, entityplayer); + entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); + return itemstack; } - /**+ - * sets a potion effect on the item. Args: int potionId, int - * duration (will be multiplied by 20), int amplifier, float - * probability of effect happening + /** + * + Set the field 'alwaysEdible' to true, and make the food edible even if the + * player don't need to eat. + */ + public ItemFood setAlwaysEdible() { + this.alwaysEdible = true; + return this; + } + + /** + * + sets a potion effect on the item. Args: int potionId, int duration (will be + * multiplied by 20), int amplifier, float probability of effect happening */ public ItemFood setPotionEffect(int id, int duration, int amplifier, float probability) { this.potionId = id; @@ -126,13 +136,4 @@ public class ItemFood extends Item { this.potionEffectProbability = probability; return this; } - - /**+ - * Set the field 'alwaysEdible' to true, and make the food - * edible even if the player don't need to eat. - */ - public ItemFood setAlwaysEdible() { - this.alwaysEdible = true; - return this; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemGlassBottle.java b/src/game/java/net/minecraft/item/ItemGlassBottle.java index ff8da312..4a1fb44d 100644 --- a/src/game/java/net/minecraft/item/ItemGlassBottle.java +++ b/src/game/java/net/minecraft/item/ItemGlassBottle.java @@ -9,22 +9,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,9 +37,9 @@ public class ItemGlassBottle extends Item { this.setCreativeTab(CreativeTabs.tabBrewing); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, true); diff --git a/src/game/java/net/minecraft/item/ItemHangingEntity.java b/src/game/java/net/minecraft/item/ItemHangingEntity.java index e39a9bf6..a0205c2d 100644 --- a/src/game/java/net/minecraft/item/ItemHangingEntity.java +++ b/src/game/java/net/minecraft/item/ItemHangingEntity.java @@ -9,22 +9,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,15 @@ public class ItemHangingEntity extends Item { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Called when a Block is right-clicked with this Item + private EntityHanging createEntity(World worldIn, BlockPos pos, EnumFacing clickedSide) { + return (EntityHanging) (this.hangingEntityClass == EntityPainting.class + ? new EntityPainting(worldIn, pos, clickedSide) + : (this.hangingEntityClass == EntityItemFrame.class ? new EntityItemFrame(worldIn, pos, clickedSide) + : null)); + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -63,11 +73,4 @@ public class ItemHangingEntity extends Item { } } } - - private EntityHanging createEntity(World worldIn, BlockPos pos, EnumFacing clickedSide) { - return (EntityHanging) (this.hangingEntityClass == EntityPainting.class - ? new EntityPainting(worldIn, pos, clickedSide) - : (this.hangingEntityClass == EntityItemFrame.class ? new EntityItemFrame(worldIn, pos, clickedSide) - : null)); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemHoe.java b/src/game/java/net/minecraft/item/ItemHoe.java index 145a5e2b..58026492 100644 --- a/src/game/java/net/minecraft/item/ItemHoe.java +++ b/src/game/java/net/minecraft/item/ItemHoe.java @@ -11,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,8 +44,23 @@ public class ItemHoe extends Item { this.setCreativeTab(CreativeTabs.tabTools); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Returns the name of the material this tool is made from as it is declared + * in EnumToolMaterial (meaning diamond would return "DIAMOND") + */ + public String getMaterialName() { + return this.theToolMaterial.toString(); + } + + /** + * + Returns True is the item is renderer in full 3D when hold. + */ + public boolean isFull3D() { + return true; + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -86,20 +104,4 @@ public class ItemHoe extends Item { return true; } } - - /**+ - * Returns True is the item is renderer in full 3D when hold. - */ - public boolean isFull3D() { - return true; - } - - /**+ - * Returns the name of the material this tool is made from as it - * is declared in EnumToolMaterial (meaning diamond would return - * "EMERALD") - */ - public String getMaterialName() { - return this.theToolMaterial.toString(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemLead.java b/src/game/java/net/minecraft/item/ItemLead.java index 8f10060f..32c04e45 100644 --- a/src/game/java/net/minecraft/item/ItemLead.java +++ b/src/game/java/net/minecraft/item/ItemLead.java @@ -13,49 +13,30 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemLead extends Item { - public ItemLead() { - this.setCreativeTab(CreativeTabs.tabTools); - } - - /**+ - * Called when a Block is right-clicked with this Item - */ - public boolean onItemUse(ItemStack var1, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing var5, - float var6, float var7, float var8) { - Block block = world.getBlockState(blockpos).getBlock(); - if (block instanceof BlockFence) { - if (world.isRemote) { - return true; - } else { - attachToFence(entityplayer, world, blockpos); - return true; - } - } else { - return false; - } - } - public static boolean attachToFence(EntityPlayer player, World worldIn, BlockPos fence) { EntityLeashKnot entityleashknot = EntityLeashKnot.getKnotForPosition(worldIn, fence); boolean flag = false; @@ -80,4 +61,26 @@ public class ItemLead extends Item { return flag; } + + public ItemLead() { + this.setCreativeTab(CreativeTabs.tabTools); + } + + /** + * + Called when a Block is right-clicked with this Item + */ + public boolean onItemUse(ItemStack var1, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing var5, + float var6, float var7, float var8) { + Block block = world.getBlockState(blockpos).getBlock(); + if (block instanceof BlockFence) { + if (world.isRemote) { + return true; + } else { + attachToFence(entityplayer, world, blockpos); + return true; + } + } else { + return false; + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemLeaves.java b/src/game/java/net/minecraft/item/ItemLeaves.java index 090113ed..5facbce5 100644 --- a/src/game/java/net/minecraft/item/ItemLeaves.java +++ b/src/game/java/net/minecraft/item/ItemLeaves.java @@ -2,22 +2,25 @@ package net.minecraft.item; import net.minecraft.block.BlockLeaves; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,23 +35,23 @@ public class ItemLeaves extends ItemBlock { this.setHasSubtypes(true); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + public int getColorFromItemStack(ItemStack stack, int renderPass) { + return this.leaves.getRenderColor(this.leaves.getStateFromMeta(stack.getMetadata())); + } + + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int damage) { return damage | 4; } - public int getColorFromItemStack(ItemStack stack, int renderPass) { - return this.leaves.getRenderColor(this.leaves.getStateFromMeta(stack.getMetadata())); - } - - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack stack) { return super.getUnlocalizedName() + "." + this.leaves.getWoodType(stack.getMetadata()).getUnlocalizedName(); diff --git a/src/game/java/net/minecraft/item/ItemLilyPad.java b/src/game/java/net/minecraft/item/ItemLilyPad.java index 3b8eb273..06bc1fd2 100644 --- a/src/game/java/net/minecraft/item/ItemLilyPad.java +++ b/src/game/java/net/minecraft/item/ItemLilyPad.java @@ -11,22 +11,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,9 +39,13 @@ public class ItemLilyPad extends ItemColored { super(block, false); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + public int getColorFromItemStack(ItemStack itemstack, int var2) { + return Blocks.waterlily.getRenderColor(Blocks.waterlily.getStateFromMeta(itemstack.getMetadata())); + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, true); @@ -73,8 +80,4 @@ public class ItemLilyPad extends ItemColored { return itemstack; } } - - public int getColorFromItemStack(ItemStack itemstack, int var2) { - return Blocks.waterlily.getRenderColor(Blocks.waterlily.getStateFromMeta(itemstack.getMetadata())); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemMap.java b/src/game/java/net/minecraft/item/ItemMap.java index 3549629f..a6f58941 100644 --- a/src/game/java/net/minecraft/item/ItemMap.java +++ b/src/game/java/net/minecraft/item/ItemMap.java @@ -22,31 +22,30 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemMap extends ItemMapBase { - protected ItemMap() { - this.setHasSubtypes(true); - } - public static MapData loadMapData(int mapId, World worldIn) { String s = "map_" + mapId; MapData mapdata = (MapData) worldIn.loadItemData(MapData.class, s); @@ -58,6 +57,31 @@ public class ItemMap extends ItemMapBase { return mapdata; } + protected ItemMap() { + this.setHasSubtypes(true); + } + + /** + * + allows items to add custom lines of information to the mouseover + * description + */ + public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) { + MapData mapdata = this.getMapData(stack, playerIn.worldObj); + if (advanced) { + if (mapdata == null) { + tooltip.add("Unknown map"); + } else { + tooltip.add("Scaling at 1:" + (1 << mapdata.scale)); + tooltip.add("(Level " + mapdata.scale + "/" + 4 + ")"); + } + } + + } + + public Packet createMapDataPacket(ItemStack stack, World worldIn, EntityPlayer player) { + return this.getMapData(stack, worldIn).getMapPacket(stack, worldIn, player); + } + public MapData getMapData(ItemStack stack, World worldIn) { String s = "map_" + stack.getMetadata(); MapData mapdata = (MapData) worldIn.loadItemData(MapData.class, s); @@ -76,6 +100,46 @@ public class ItemMap extends ItemMapBase { return mapdata; } + /** + * + Called when item is crafted/smelted. Used only by maps so far. + */ + public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) { + if (stack.hasTagCompound() && stack.getTagCompound().getBoolean("map_is_scaling")) { + MapData mapdata = Items.filled_map.getMapData(stack, worldIn); + stack.setItemDamage(worldIn.getUniqueDataId("map")); + MapData mapdata1 = new MapData("map_" + stack.getMetadata()); + mapdata1.scale = (byte) (mapdata.scale + 1); + if (mapdata1.scale > 4) { + mapdata1.scale = 4; + } + + mapdata1.calculateMapCenter((double) mapdata.xCenter, (double) mapdata.zCenter, mapdata1.scale); + mapdata1.dimension = mapdata.dimension; + mapdata1.markDirty(); + worldIn.setItemData("map_" + stack.getMetadata(), mapdata1); + } + + } + + /** + * + Called each tick as long the item is on a player inventory. Uses by maps to + * check if is on a player hand and update it's contents. + */ + public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) { + if (!worldIn.isRemote) { + MapData mapdata = this.getMapData(stack, worldIn); + if (entityIn instanceof EntityPlayer) { + EntityPlayer entityplayer = (EntityPlayer) entityIn; + mapdata.updateVisiblePlayers(entityplayer, stack); + } + + if (isSelected) { + this.updateMapData(worldIn, entityIn, mapdata); + } + + } + } + public void updateMapData(World worldIn, Entity viewer, MapData data) { if (worldIn.provider.getDimensionId() == data.dimension && viewer instanceof EntityPlayer) { int i = 1 << data.scale; @@ -209,67 +273,4 @@ public class ItemMap extends ItemMapBase { } } - - /**+ - * Called each tick as long the item is on a player inventory. - * Uses by maps to check if is on a player hand and update it's - * contents. - */ - public void onUpdate(ItemStack stack, World worldIn, Entity entityIn, int itemSlot, boolean isSelected) { - if (!worldIn.isRemote) { - MapData mapdata = this.getMapData(stack, worldIn); - if (entityIn instanceof EntityPlayer) { - EntityPlayer entityplayer = (EntityPlayer) entityIn; - mapdata.updateVisiblePlayers(entityplayer, stack); - } - - if (isSelected) { - this.updateMapData(worldIn, entityIn, mapdata); - } - - } - } - - public Packet createMapDataPacket(ItemStack stack, World worldIn, EntityPlayer player) { - return this.getMapData(stack, worldIn).getMapPacket(stack, worldIn, player); - } - - /**+ - * Called when item is crafted/smelted. Used only by maps so - * far. - */ - public void onCreated(ItemStack stack, World worldIn, EntityPlayer playerIn) { - if (stack.hasTagCompound() && stack.getTagCompound().getBoolean("map_is_scaling")) { - MapData mapdata = Items.filled_map.getMapData(stack, worldIn); - stack.setItemDamage(worldIn.getUniqueDataId("map")); - MapData mapdata1 = new MapData("map_" + stack.getMetadata()); - mapdata1.scale = (byte) (mapdata.scale + 1); - if (mapdata1.scale > 4) { - mapdata1.scale = 4; - } - - mapdata1.calculateMapCenter((double) mapdata.xCenter, (double) mapdata.zCenter, mapdata1.scale); - mapdata1.dimension = mapdata.dimension; - mapdata1.markDirty(); - worldIn.setItemData("map_" + stack.getMetadata(), mapdata1); - } - - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description - */ - public void addInformation(ItemStack stack, EntityPlayer playerIn, List tooltip, boolean advanced) { - MapData mapdata = this.getMapData(stack, playerIn.worldObj); - if (advanced) { - if (mapdata == null) { - tooltip.add("Unknown map"); - } else { - tooltip.add("Scaling at 1:" + (1 << mapdata.scale)); - tooltip.add("(Level " + mapdata.scale + "/" + 4 + ")"); - } - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemMapBase.java b/src/game/java/net/minecraft/item/ItemMapBase.java index 0c16dce8..690774dc 100644 --- a/src/game/java/net/minecraft/item/ItemMapBase.java +++ b/src/game/java/net/minecraft/item/ItemMapBase.java @@ -4,35 +4,38 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.Packet; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemMapBase extends Item { - /**+ - * false for all Items except sub-classes of ItemMapBase + public Packet createMapDataPacket(ItemStack var1, World var2, EntityPlayer var3) { + return null; + } + + /** + * + false for all Items except sub-classes of ItemMapBase */ public boolean isMap() { return true; } - - public Packet createMapDataPacket(ItemStack var1, World var2, EntityPlayer var3) { - return null; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemMinecart.java b/src/game/java/net/minecraft/item/ItemMinecart.java index bf534e68..10c3b805 100644 --- a/src/game/java/net/minecraft/item/ItemMinecart.java +++ b/src/game/java/net/minecraft/item/ItemMinecart.java @@ -14,22 +14,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -101,8 +104,8 @@ public class ItemMinecart extends Item { BlockDispenser.dispenseBehaviorRegistry.putObject(this, dispenserMinecartBehavior); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ) { diff --git a/src/game/java/net/minecraft/item/ItemMonsterPlacer.java b/src/game/java/net/minecraft/item/ItemMonsterPlacer.java index eb59bd77..5bd24e91 100644 --- a/src/game/java/net/minecraft/item/ItemMonsterPlacer.java +++ b/src/game/java/net/minecraft/item/ItemMonsterPlacer.java @@ -1,6 +1,7 @@ package net.minecraft.item; import java.util.List; + import net.minecraft.block.BlockFence; import net.minecraft.block.BlockLiquid; import net.minecraft.block.state.IBlockState; @@ -23,32 +24,72 @@ import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemMonsterPlacer extends Item { + /** + * + Spawns the creature specified by the egg's type in the location specified + * by the last three parameters. Parameters: world, entityID, x, y, z. + */ + public static Entity spawnCreature(World worldIn, int entityID, double x, double y, double z) { + if (!EntityList.entityEggs.containsKey(Integer.valueOf(entityID))) { + return null; + } else { + Entity entity = null; + + for (int i = 0; i < 1; ++i) { + entity = EntityList.createEntityByID(entityID, worldIn); + if (entity instanceof EntityLivingBase) { + EntityLiving entityliving = (EntityLiving) entity; + entity.setLocationAndAngles(x, y, z, + MathHelper.wrapAngleTo180_float(worldIn.rand.nextFloat() * 360.0F), 0.0F); + entityliving.rotationYawHead = entityliving.rotationYaw; + entityliving.renderYawOffset = entityliving.rotationYaw; + entityliving.onInitialSpawn(worldIn.getDifficultyForLocation(new BlockPos(entityliving)), + (IEntityLivingData) null); + worldIn.spawnEntityInWorld(entity); + entityliving.playLivingSound(); + } + } + + return entity; + } + } + public ItemMonsterPlacer() { this.setHasSubtypes(true); this.setCreativeTab(CreativeTabs.tabMisc); } + public int getColorFromItemStack(ItemStack itemstack, int i) { + EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs + .get(Integer.valueOf(itemstack.getMetadata())); + return entitylist$entityegginfo != null + ? (i == 0 ? entitylist$entityegginfo.primaryColor : entitylist$entityegginfo.secondaryColor) + : 16777215; + } + public String getItemStackDisplayName(ItemStack itemstack) { String s = ("" + StatCollector.translateToLocal(this.getUnlocalizedName() + ".name")).trim(); String s1 = EntityList.getStringFromID(itemstack.getMetadata()); @@ -59,16 +100,64 @@ public class ItemMonsterPlacer extends Item { return s; } - public int getColorFromItemStack(ItemStack itemstack, int i) { - EntityList.EntityEggInfo entitylist$entityegginfo = (EntityList.EntityEggInfo) EntityList.entityEggs - .get(Integer.valueOf(itemstack.getMetadata())); - return entitylist$entityegginfo != null - ? (i == 0 ? entitylist$entityegginfo.primaryColor : entitylist$entityegginfo.secondaryColor) - : 16777215; + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs var2, List list) { + for (EntityList.EntityEggInfo entitylist$entityegginfo : EntityList.entityEggs.values()) { + list.add(new ItemStack(item, 1, entitylist$entityegginfo.spawnedID)); + } + } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (world.isRemote) { + return itemstack; + } else { + MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, + true); + if (movingobjectposition == null) { + return itemstack; + } else { + if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { + BlockPos blockpos = movingobjectposition.getBlockPos(); + if (!world.isBlockModifiable(entityplayer, blockpos)) { + return itemstack; + } + + if (!entityplayer.canPlayerEdit(blockpos, movingobjectposition.sideHit, itemstack)) { + return itemstack; + } + + if (world.getBlockState(blockpos).getBlock() instanceof BlockLiquid) { + Entity entity = spawnCreature(world, itemstack.getMetadata(), (double) blockpos.getX() + 0.5D, + (double) blockpos.getY() + 0.5D, (double) blockpos.getZ() + 0.5D); + if (entity != null) { + if (entity instanceof EntityLivingBase && itemstack.hasDisplayName()) { + ((EntityLiving) entity).setCustomNameTag(itemstack.getDisplayName()); + } + + if (!entityplayer.capabilities.isCreativeMode) { + --itemstack.stackSize; + } + + entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); + } + } + } + + return itemstack; + } + } + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -114,90 +203,4 @@ public class ItemMonsterPlacer extends Item { return true; } } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (world.isRemote) { - return itemstack; - } else { - MovingObjectPosition movingobjectposition = this.getMovingObjectPositionFromPlayer(world, entityplayer, - true); - if (movingobjectposition == null) { - return itemstack; - } else { - if (movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { - BlockPos blockpos = movingobjectposition.getBlockPos(); - if (!world.isBlockModifiable(entityplayer, blockpos)) { - return itemstack; - } - - if (!entityplayer.canPlayerEdit(blockpos, movingobjectposition.sideHit, itemstack)) { - return itemstack; - } - - if (world.getBlockState(blockpos).getBlock() instanceof BlockLiquid) { - Entity entity = spawnCreature(world, itemstack.getMetadata(), (double) blockpos.getX() + 0.5D, - (double) blockpos.getY() + 0.5D, (double) blockpos.getZ() + 0.5D); - if (entity != null) { - if (entity instanceof EntityLivingBase && itemstack.hasDisplayName()) { - ((EntityLiving) entity).setCustomNameTag(itemstack.getDisplayName()); - } - - if (!entityplayer.capabilities.isCreativeMode) { - --itemstack.stackSize; - } - - entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); - } - } - } - - return itemstack; - } - } - } - - /**+ - * Spawns the creature specified by the egg's type in the - * location specified by the last three parameters. Parameters: - * world, entityID, x, y, z. - */ - public static Entity spawnCreature(World worldIn, int entityID, double x, double y, double z) { - if (!EntityList.entityEggs.containsKey(Integer.valueOf(entityID))) { - return null; - } else { - Entity entity = null; - - for (int i = 0; i < 1; ++i) { - entity = EntityList.createEntityByID(entityID, worldIn); - if (entity instanceof EntityLivingBase) { - EntityLiving entityliving = (EntityLiving) entity; - entity.setLocationAndAngles(x, y, z, - MathHelper.wrapAngleTo180_float(worldIn.rand.nextFloat() * 360.0F), 0.0F); - entityliving.rotationYawHead = entityliving.rotationYaw; - entityliving.renderYawOffset = entityliving.rotationYaw; - entityliving.onInitialSpawn(worldIn.getDifficultyForLocation(new BlockPos(entityliving)), - (IEntityLivingData) null); - worldIn.spawnEntityInWorld(entity); - entityliving.playLivingSound(); - } - } - - return entity; - } - } - - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs var2, List list) { - for (EntityList.EntityEggInfo entitylist$entityegginfo : EntityList.entityEggs.values()) { - list.add(new ItemStack(item, 1, entitylist$entityegginfo.spawnedID)); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemMultiTexture.java b/src/game/java/net/minecraft/item/ItemMultiTexture.java index f6e400e0..166ae03c 100644 --- a/src/game/java/net/minecraft/item/ItemMultiTexture.java +++ b/src/game/java/net/minecraft/item/ItemMultiTexture.java @@ -4,22 +4,25 @@ import com.google.common.base.Function; import net.minecraft.block.Block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,19 +52,19 @@ public class ItemMultiTexture extends ItemBlock { }); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int i) { return i; } - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack itemstack) { return super.getUnlocalizedName() + "." + (String) this.nameFunction.apply(itemstack); diff --git a/src/game/java/net/minecraft/item/ItemNameTag.java b/src/game/java/net/minecraft/item/ItemNameTag.java index 5dfe7079..4a8e00a3 100644 --- a/src/game/java/net/minecraft/item/ItemNameTag.java +++ b/src/game/java/net/minecraft/item/ItemNameTag.java @@ -5,22 +5,25 @@ import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,9 +33,9 @@ public class ItemNameTag extends Item { this.setCreativeTab(CreativeTabs.tabTools); } - /**+ - * Returns true if the item can be used on the given entity, - * e.g. shears on sheep. + /** + * + Returns true if the item can be used on the given entity, e.g. shears on + * sheep. */ public boolean itemInteractionForEntity(ItemStack stack, EntityPlayer playerIn, EntityLivingBase target) { if (!stack.hasDisplayName()) { diff --git a/src/game/java/net/minecraft/item/ItemPickaxe.java b/src/game/java/net/minecraft/item/ItemPickaxe.java index c8bc4480..b5c46ec6 100644 --- a/src/game/java/net/minecraft/item/ItemPickaxe.java +++ b/src/game/java/net/minecraft/item/ItemPickaxe.java @@ -8,22 +8,25 @@ import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,37 +40,39 @@ public class ItemPickaxe extends ItemTool { Blocks.golden_rail, Blocks.gold_block, Blocks.gold_ore, Blocks.ice, Blocks.iron_block, Blocks.iron_ore, Blocks.lapis_block, Blocks.lapis_ore, Blocks.lit_redstone_ore, Blocks.mossy_cobblestone, Blocks.netherrack, Blocks.packed_ice, Blocks.rail, Blocks.redstone_ore, Blocks.sandstone, - Blocks.red_sandstone, Blocks.stone, Blocks.stone_slab }); + Blocks.red_sandstone, Blocks.stone, Blocks.stone_slab, + + Blocks.titanium_ore, Blocks.titanium_block, Blocks.uranium_ore, Blocks.uranium_block, + Blocks.platinum_ore, Blocks.platinum_block, Blocks.steel_block, Blocks.steel_grate, Blocks.deepstone, + Blocks.cobbled_deepstone }); } protected ItemPickaxe(Item.ToolMaterial material) { super(2.0F, material, EFFECTIVE_ON); } - /**+ - * Check whether this Item can harvest the given Block + /** + * + Check whether this Item can harvest the given Block */ public boolean canHarvestBlock(Block blockIn) { - return blockIn == Blocks.obsidian ? this.toolMaterial.getHarvestLevel() == 3 - : (blockIn != Blocks.diamond_block && blockIn != Blocks.diamond_ore - ? (blockIn != Blocks.emerald_ore && blockIn != Blocks.emerald_block - ? (blockIn != Blocks.gold_block && blockIn != Blocks.gold_ore - ? (blockIn != Blocks.iron_block && blockIn != Blocks.iron_ore - ? (blockIn != Blocks.lapis_block && blockIn != Blocks.lapis_ore - ? (blockIn != Blocks.redstone_ore - && blockIn != Blocks.lit_redstone_ore - ? (blockIn.getMaterial() == Material.rock ? true - : (blockIn - .getMaterial() == Material.iron - ? true - : blockIn - .getMaterial() == Material.anvil)) - : this.toolMaterial.getHarvestLevel() >= 2) - : this.toolMaterial.getHarvestLevel() >= 1) - : this.toolMaterial.getHarvestLevel() >= 1) - : this.toolMaterial.getHarvestLevel() >= 2) - : this.toolMaterial.getHarvestLevel() >= 2) - : this.toolMaterial.getHarvestLevel() >= 2); + if (blockIn == Blocks.titanium_block || blockIn == Blocks.titanium_ore || blockIn == Blocks.uranium_block + || blockIn == Blocks.uranium_ore) { + return this.toolMaterial.getHarvestLevel() >= 4; + } else if (blockIn == Blocks.platinum_block || blockIn == Blocks.platinum_ore || blockIn == Blocks.obsidian) { + return this.toolMaterial.getHarvestLevel() >= 3; + } else if (blockIn == Blocks.diamond_block || blockIn == Blocks.diamond_ore || blockIn == Blocks.emerald_block + || blockIn == Blocks.emerald_ore || blockIn == Blocks.gold_block || blockIn == Blocks.gold_ore + || blockIn == Blocks.redstone_ore || blockIn == Blocks.lit_redstone_ore) { + return this.toolMaterial.getHarvestLevel() >= 2; + } else if (blockIn == Blocks.iron_block || blockIn == Blocks.iron_ore || blockIn == Blocks.lapis_block + || blockIn == Blocks.lapis_ore || blockIn == Blocks.steel_block || blockIn == Blocks.steel_grate) { + return this.toolMaterial.getHarvestLevel() >= 1; + } else if (blockIn.getMaterial() == Material.rock || blockIn.getMaterial() == Material.iron + || blockIn.getMaterial() == Material.anvil) { + return true; + } else { + return false; + } } public float getStrVsBlock(ItemStack stack, Block block) { diff --git a/src/game/java/net/minecraft/item/ItemPiston.java b/src/game/java/net/minecraft/item/ItemPiston.java index 557dab52..f834847d 100644 --- a/src/game/java/net/minecraft/item/ItemPiston.java +++ b/src/game/java/net/minecraft/item/ItemPiston.java @@ -2,22 +2,25 @@ package net.minecraft.item; import net.minecraft.block.Block; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,10 +30,10 @@ public class ItemPiston extends ItemBlock { super(block); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int var1) { return 7; diff --git a/src/game/java/net/minecraft/item/ItemPotion.java b/src/game/java/net/minecraft/item/ItemPotion.java index cc607e51..40159fa3 100644 --- a/src/game/java/net/minecraft/item/ItemPotion.java +++ b/src/game/java/net/minecraft/item/ItemPotion.java @@ -27,30 +27,42 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemPotion extends Item { - private Map> effectCache = Maps.newHashMap(); private static final Map, Integer> SUB_ITEMS_CACHE = Maps.newLinkedHashMap(); + /** + * + returns wether or not a potion is a throwable splash potion based on damage + * value + */ + public static boolean isSplash(int meta) { + return (meta & 16384) != 0; + } + + private Map> effectCache = Maps.newHashMap(); + public ItemPotion() { this.setMaxStackSize(1); this.setHasSubtypes(true); @@ -58,173 +70,9 @@ public class ItemPotion extends Item { this.setCreativeTab(CreativeTabs.tabBrewing); } - /**+ - * Returns a list of effects for the specified potion damage - * value. - */ - public List getEffects(ItemStack stack) { - if (stack.hasTagCompound() && stack.getTagCompound().hasKey("CustomPotionEffects", 9)) { - ArrayList arraylist = Lists.newArrayList(); - NBTTagList nbttaglist = stack.getTagCompound().getTagList("CustomPotionEffects", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound); - if (potioneffect != null) { - arraylist.add(potioneffect); - } - } - - return arraylist; - } else { - List list = (List) this.effectCache.get(Integer.valueOf(stack.getMetadata())); - if (list == null) { - list = PotionHelper.getPotionEffects(stack.getMetadata(), false); - this.effectCache.put(Integer.valueOf(stack.getMetadata()), list); - } - - return list; - } - } - - /**+ - * Returns a list of effects for the specified potion damage - * value. - */ - public List getEffects(int meta) { - List list = (List) this.effectCache.get(Integer.valueOf(meta)); - if (list == null) { - list = PotionHelper.getPotionEffects(meta, false); - this.effectCache.put(Integer.valueOf(meta), list); - } - - return list; - } - - /**+ - * Called when the player finishes using this Item (E.g. - * finishes eating.). Not called when the player stops using the - * Item before the action is complete. - */ - public ItemStack onItemUseFinish(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (!entityplayer.capabilities.isCreativeMode) { - --itemstack.stackSize; - } - - if (!world.isRemote) { - List list = this.getEffects(itemstack); - if (list != null) { - for (int i = 0, l = list.size(); i < l; ++i) { - entityplayer.addPotionEffect(new PotionEffect(list.get(i))); - } - } - } - - entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); - if (!entityplayer.capabilities.isCreativeMode) { - if (itemstack.stackSize <= 0) { - return new ItemStack(Items.glass_bottle); - } - - entityplayer.inventory.addItemStackToInventory(new ItemStack(Items.glass_bottle)); - } - - return itemstack; - } - - /**+ - * How long it takes to use or consume an item - */ - public int getMaxItemUseDuration(ItemStack var1) { - return 32; - } - - /**+ - * returns the action that specifies what animation to play when - * the items is being used - */ - public EnumAction getItemUseAction(ItemStack var1) { - return EnumAction.DRINK; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { - if (isSplash(itemstack.getMetadata())) { - if (!entityplayer.capabilities.isCreativeMode) { - --itemstack.stackSize; - } - - world.playSoundAtEntity(entityplayer, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); - if (!world.isRemote) { - world.spawnEntityInWorld(new EntityPotion(world, entityplayer, itemstack)); - } - - entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); - return itemstack; - } else { - entityplayer.setItemInUse(itemstack, this.getMaxItemUseDuration(itemstack)); - return itemstack; - } - } - - /**+ - * returns wether or not a potion is a throwable splash potion - * based on damage value - */ - public static boolean isSplash(int meta) { - return (meta & 16384) != 0; - } - - public int getColorFromDamage(int meta) { - return PotionHelper.getLiquidColor(meta, false); - } - - public int getColorFromItemStack(ItemStack itemstack, int i) { - return i > 0 ? 16777215 : this.getColorFromDamage(itemstack.getMetadata()); - } - - public boolean isEffectInstant(int meta) { - List list = this.getEffects(meta); - if (list != null && !list.isEmpty()) { - for (int i = 0, l = list.size(); i < l; ++i) { - if (Potion.potionTypes[list.get(i).getPotionID()].isInstant()) { - return true; - } - } - - return false; - } else { - return false; - } - } - - public String getItemStackDisplayName(ItemStack stack) { - if (stack.getMetadata() == 0) { - return StatCollector.translateToLocal("item.emptyPotion.name").trim(); - } else { - String s = ""; - if (isSplash(stack.getMetadata())) { - s = StatCollector.translateToLocal("potion.prefix.grenade").trim() + " "; - } - - List list = Items.potionitem.getEffects(stack); - if (list != null && !list.isEmpty()) { - String s2 = ((PotionEffect) list.get(0)).getEffectName(); - s2 = s2 + ".postfix"; - return s + StatCollector.translateToLocal(s2).trim(); - } else { - String s1 = PotionHelper.getPotionPrefix(stack.getMetadata()); - return StatCollector.translateToLocal(s1).trim() + " " + super.getItemStackDisplayName(stack); - } - } - } - - /**+ - * allows items to add custom lines of information to the - * mouseover description + /** + * + allows items to add custom lines of information to the mouseover + * description */ public void addInformation(ItemStack itemstack, EntityPlayer var2, List list, boolean var4) { if (itemstack.getMetadata() != 0) { @@ -299,14 +147,94 @@ public class ItemPotion extends Item { } } - public boolean hasEffect(ItemStack stack) { - List list = this.getEffects(stack); - return list != null && !list.isEmpty(); + public int getColorFromDamage(int meta) { + return PotionHelper.getLiquidColor(meta, false); } - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) + public int getColorFromItemStack(ItemStack itemstack, int i) { + return i > 0 ? 16777215 : this.getColorFromDamage(itemstack.getMetadata()); + } + + /** + * + Returns a list of effects for the specified potion damage value. + */ + public List getEffects(int meta) { + List list = (List) this.effectCache.get(Integer.valueOf(meta)); + if (list == null) { + list = PotionHelper.getPotionEffects(meta, false); + this.effectCache.put(Integer.valueOf(meta), list); + } + + return list; + } + + /** + * + Returns a list of effects for the specified potion damage value. + */ + public List getEffects(ItemStack stack) { + if (stack.hasTagCompound() && stack.getTagCompound().hasKey("CustomPotionEffects", 9)) { + ArrayList arraylist = Lists.newArrayList(); + NBTTagList nbttaglist = stack.getTagCompound().getTagList("CustomPotionEffects", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + PotionEffect potioneffect = PotionEffect.readCustomPotionEffectFromNBT(nbttagcompound); + if (potioneffect != null) { + arraylist.add(potioneffect); + } + } + + return arraylist; + } else { + List list = (List) this.effectCache.get(Integer.valueOf(stack.getMetadata())); + if (list == null) { + list = PotionHelper.getPotionEffects(stack.getMetadata(), false); + this.effectCache.put(Integer.valueOf(stack.getMetadata()), list); + } + + return list; + } + } + + public String getItemStackDisplayName(ItemStack stack) { + if (stack.getMetadata() == 0) { + return StatCollector.translateToLocal("item.emptyPotion.name").trim(); + } else { + String s = ""; + if (isSplash(stack.getMetadata())) { + s = StatCollector.translateToLocal("potion.prefix.grenade").trim() + " "; + } + + List list = Items.potionitem.getEffects(stack); + if (list != null && !list.isEmpty()) { + String s2 = ((PotionEffect) list.get(0)).getEffectName(); + s2 = s2 + ".postfix"; + return s + StatCollector.translateToLocal(s2).trim(); + } else { + String s1 = PotionHelper.getPotionPrefix(stack.getMetadata()); + return StatCollector.translateToLocal(s1).trim() + " " + super.getItemStackDisplayName(stack); + } + } + } + + /** + * + returns the action that specifies what animation to play when the items is + * being used + */ + public EnumAction getItemUseAction(ItemStack var1) { + return EnumAction.DRINK; + } + + /** + * + How long it takes to use or consume an item + */ + public int getMaxItemUseDuration(ItemStack var1) { + return 32; + } + + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) */ public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) { super.getSubItems(itemIn, tab, subItems); @@ -347,4 +275,78 @@ public class ItemPotion extends Item { } } + + public boolean hasEffect(ItemStack stack) { + List list = this.getEffects(stack); + return list != null && !list.isEmpty(); + } + + public boolean isEffectInstant(int meta) { + List list = this.getEffects(meta); + if (list != null && !list.isEmpty()) { + for (int i = 0, l = list.size(); i < l; ++i) { + if (Potion.potionTypes[list.get(i).getPotionID()].isInstant()) { + return true; + } + } + + return false; + } else { + return false; + } + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (isSplash(itemstack.getMetadata())) { + if (!entityplayer.capabilities.isCreativeMode) { + --itemstack.stackSize; + } + + world.playSoundAtEntity(entityplayer, "random.bow", 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); + if (!world.isRemote) { + world.spawnEntityInWorld(new EntityPotion(world, entityplayer, itemstack)); + } + + entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); + return itemstack; + } else { + entityplayer.setItemInUse(itemstack, this.getMaxItemUseDuration(itemstack)); + return itemstack; + } + } + + /** + * + Called when the player finishes using this Item (E.g. finishes eating.). + * Not called when the player stops using the Item before the action is + * complete. + */ + public ItemStack onItemUseFinish(ItemStack itemstack, World world, EntityPlayer entityplayer) { + if (!entityplayer.capabilities.isCreativeMode) { + --itemstack.stackSize; + } + + if (!world.isRemote) { + List list = this.getEffects(itemstack); + if (list != null) { + for (int i = 0, l = list.size(); i < l; ++i) { + entityplayer.addPotionEffect(new PotionEffect(list.get(i))); + } + } + } + + entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); + if (!entityplayer.capabilities.isCreativeMode) { + if (itemstack.stackSize <= 0) { + return new ItemStack(Items.glass_bottle); + } + + entityplayer.inventory.addItemStackToInventory(new ItemStack(Items.glass_bottle)); + } + + return itemstack; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemRecord.java b/src/game/java/net/minecraft/item/ItemRecord.java index 4e7c4eef..9e95fda4 100644 --- a/src/game/java/net/minecraft/item/ItemRecord.java +++ b/src/game/java/net/minecraft/item/ItemRecord.java @@ -16,28 +16,39 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemRecord extends Item { private static final Map RECORDS = Maps.newHashMap(); + + /** + * + Return the record item corresponding to the given name. + */ + public static ItemRecord getRecord(String name) { + return (ItemRecord) RECORDS.get(name); + } + public final String recordName; protected ItemRecord(String name) { @@ -47,8 +58,27 @@ public class ItemRecord extends Item { RECORDS.put("records." + name, this); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + allows items to add custom lines of information to the mouseover + * description + */ + public void addInformation(ItemStack var1, EntityPlayer var2, List list, boolean var4) { + list.add(this.getRecordNameLocal()); + } + + /** + * + Return an item rarity from EnumRarity + */ + public EnumRarity getRarity(ItemStack stack) { + return EnumRarity.RARE; + } + + public String getRecordNameLocal() { + return StatCollector.translateToLocal("item.record." + this.recordName + ".desc"); + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing var5, float var6, float var7, float var8) { @@ -68,30 +98,4 @@ public class ItemRecord extends Item { return false; } } - - /**+ - * allows items to add custom lines of information to the - * mouseover description - */ - public void addInformation(ItemStack var1, EntityPlayer var2, List list, boolean var4) { - list.add(this.getRecordNameLocal()); - } - - public String getRecordNameLocal() { - return StatCollector.translateToLocal("item.record." + this.recordName + ".desc"); - } - - /**+ - * Return an item rarity from EnumRarity - */ - public EnumRarity getRarity(ItemStack stack) { - return EnumRarity.RARE; - } - - /**+ - * Return the record item corresponding to the given name. - */ - public static ItemRecord getRecord(String name) { - return (ItemRecord) RECORDS.get(name); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemRedstone.java b/src/game/java/net/minecraft/item/ItemRedstone.java index 9073723a..9da39ed0 100644 --- a/src/game/java/net/minecraft/item/ItemRedstone.java +++ b/src/game/java/net/minecraft/item/ItemRedstone.java @@ -9,22 +9,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,8 +37,8 @@ public class ItemRedstone extends Item { this.setCreativeTab(CreativeTabs.tabRedstone); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemReed.java b/src/game/java/net/minecraft/item/ItemReed.java index 69176b9c..07f2029f 100644 --- a/src/game/java/net/minecraft/item/ItemReed.java +++ b/src/game/java/net/minecraft/item/ItemReed.java @@ -10,22 +10,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,8 @@ public class ItemReed extends Item { this.block = block; } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { diff --git a/src/game/java/net/minecraft/item/ItemSaddle.java b/src/game/java/net/minecraft/item/ItemSaddle.java index 0f87ff3a..edad2400 100644 --- a/src/game/java/net/minecraft/item/ItemSaddle.java +++ b/src/game/java/net/minecraft/item/ItemSaddle.java @@ -5,22 +5,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityPig; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,9 +34,18 @@ public class ItemSaddle extends Item { this.setCreativeTab(CreativeTabs.tabTransport); } - /**+ - * Returns true if the item can be used on the given entity, - * e.g. shears on sheep. + /** + * + Current implementations of this method in child classes do not use the + * entry argument beside ev. They just raise the damage on the stack. + */ + public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { + this.itemInteractionForEntity(stack, (EntityPlayer) null, target); + return true; + } + + /** + * + Returns true if the item can be used on the given entity, e.g. shears on + * sheep. */ public boolean itemInteractionForEntity(ItemStack itemstack, EntityPlayer var2, EntityLivingBase entitylivingbase) { if (entitylivingbase instanceof EntityPig) { @@ -49,14 +61,4 @@ public class ItemSaddle extends Item { return false; } } - - /**+ - * Current implementations of this method in child classes do - * not use the entry argument beside ev. They just raise the - * damage on the stack. - */ - public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { - this.itemInteractionForEntity(stack, (EntityPlayer) null, target); - return true; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemSeedFood.java b/src/game/java/net/minecraft/item/ItemSeedFood.java index 83b4d20b..8389ce1d 100644 --- a/src/game/java/net/minecraft/item/ItemSeedFood.java +++ b/src/game/java/net/minecraft/item/ItemSeedFood.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,8 @@ public class ItemSeedFood extends ItemFood { this.soilId = soil; } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemSeeds.java b/src/game/java/net/minecraft/item/ItemSeeds.java index 2072a448..b793416f 100644 --- a/src/game/java/net/minecraft/item/ItemSeeds.java +++ b/src/game/java/net/minecraft/item/ItemSeeds.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,8 @@ public class ItemSeeds extends Item { this.setCreativeTab(CreativeTabs.tabMaterials); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemShears.java b/src/game/java/net/minecraft/item/ItemShears.java index 74d87b5a..432b51f2 100644 --- a/src/game/java/net/minecraft/item/ItemShears.java +++ b/src/game/java/net/minecraft/item/ItemShears.java @@ -8,22 +8,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,9 +38,22 @@ public class ItemShears extends Item { this.setCreativeTab(CreativeTabs.tabTools); } - /**+ - * Called when a Block is destroyed using this Item. Return true - * to trigger the "Use Item" statistic. + /** + * + Check whether this Item can harvest the given Block + */ + public boolean canHarvestBlock(Block block) { + return block == Blocks.web || block == Blocks.redstone_wire || block == Blocks.tripwire; + } + + public float getStrVsBlock(ItemStack itemstack, Block block) { + return block != Blocks.web && block.getMaterial() != Material.leaves + ? (block == Blocks.wool ? 5.0F : super.getStrVsBlock(itemstack, block)) + : 15.0F; + } + + /** + * + Called when a Block is destroyed using this Item. Return true to trigger + * the "Use Item" statistic. */ public boolean onBlockDestroyed(ItemStack stack, World worldIn, Block blockIn, BlockPos pos, EntityLivingBase playerIn) { @@ -49,17 +65,4 @@ public class ItemShears extends Item { return true; } } - - /**+ - * Check whether this Item can harvest the given Block - */ - public boolean canHarvestBlock(Block block) { - return block == Blocks.web || block == Blocks.redstone_wire || block == Blocks.tripwire; - } - - public float getStrVsBlock(ItemStack itemstack, Block block) { - return block != Blocks.web && block.getMaterial() != Material.leaves - ? (block == Blocks.wool ? 5.0F : super.getStrVsBlock(itemstack, block)) - : 15.0F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemSign.java b/src/game/java/net/minecraft/item/ItemSign.java index a64e720e..8761713b 100644 --- a/src/game/java/net/minecraft/item/ItemSign.java +++ b/src/game/java/net/minecraft/item/ItemSign.java @@ -12,22 +12,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,8 +41,8 @@ public class ItemSign extends Item { this.setCreativeTab(CreativeTabs.tabDecorations); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { diff --git a/src/game/java/net/minecraft/item/ItemSimpleFoiled.java b/src/game/java/net/minecraft/item/ItemSimpleFoiled.java index 6200e0cd..e95a669e 100644 --- a/src/game/java/net/minecraft/item/ItemSimpleFoiled.java +++ b/src/game/java/net/minecraft/item/ItemSimpleFoiled.java @@ -1,21 +1,24 @@ package net.minecraft.item; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/item/ItemSkull.java b/src/game/java/net/minecraft/item/ItemSkull.java index 6e145831..091ba5c4 100644 --- a/src/game/java/net/minecraft/item/ItemSkull.java +++ b/src/game/java/net/minecraft/item/ItemSkull.java @@ -1,8 +1,9 @@ package net.minecraft.item; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.block.Block; import net.minecraft.block.BlockSkull; import net.minecraft.block.state.IBlockState; @@ -19,22 +20,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,8 +52,61 @@ public class ItemSkull extends Item { this.setHasSubtypes(true); } - /**+ - * Called when a Block is right-clicked with this Item + public String getItemStackDisplayName(ItemStack itemstack) { + if (itemstack.getMetadata() == 3 && itemstack.hasTagCompound()) { + if (itemstack.getTagCompound().hasKey("SkullOwner", 8)) { + return StatCollector.translateToLocalFormatted("item.skull.player.name", + new Object[] { itemstack.getTagCompound().getString("SkullOwner") }); + } + + if (itemstack.getTagCompound().hasKey("SkullOwner", 10)) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("SkullOwner"); + if (nbttagcompound.hasKey("Name", 8)) { + return StatCollector.translateToLocalFormatted("item.skull.player.name", + new Object[] { nbttagcompound.getString("Name") }); + } + } + } + + return super.getItemStackDisplayName(itemstack); + } + + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). + */ + public int getMetadata(int i) { + return i; + } + + /** + * + returns a list of items with the same ID, but different meta (eg: dye + * returns 16 items) + */ + public void getSubItems(Item item, CreativeTabs var2, List list) { + for (int i = 0; i < skullTypes.length; ++i) { + list.add(new ItemStack(item, 1, i)); + } + + } + + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. + */ + public String getUnlocalizedName(ItemStack itemstack) { + int i = itemstack.getMetadata(); + if (i < 0 || i >= skullTypes.length) { + i = 0; + } + + return super.getUnlocalizedName() + "." + skullTypes[i]; + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float var6, float var7, float var8) { @@ -114,62 +171,9 @@ public class ItemSkull extends Item { } } - /**+ - * returns a list of items with the same ID, but different meta - * (eg: dye returns 16 items) - */ - public void getSubItems(Item item, CreativeTabs var2, List list) { - for (int i = 0; i < skullTypes.length; ++i) { - list.add(new ItemStack(item, 1, i)); - } - - } - - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). - */ - public int getMetadata(int i) { - return i; - } - - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. - */ - public String getUnlocalizedName(ItemStack itemstack) { - int i = itemstack.getMetadata(); - if (i < 0 || i >= skullTypes.length) { - i = 0; - } - - return super.getUnlocalizedName() + "." + skullTypes[i]; - } - - public String getItemStackDisplayName(ItemStack itemstack) { - if (itemstack.getMetadata() == 3 && itemstack.hasTagCompound()) { - if (itemstack.getTagCompound().hasKey("SkullOwner", 8)) { - return StatCollector.translateToLocalFormatted("item.skull.player.name", - new Object[] { itemstack.getTagCompound().getString("SkullOwner") }); - } - - if (itemstack.getTagCompound().hasKey("SkullOwner", 10)) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("SkullOwner"); - if (nbttagcompound.hasKey("Name", 8)) { - return StatCollector.translateToLocalFormatted("item.skull.player.name", - new Object[] { nbttagcompound.getString("Name") }); - } - } - } - - return super.getItemStackDisplayName(itemstack); - } - - /**+ - * Called when an ItemStack with NBT data is read to potentially - * that ItemStack's NBT data + /** + * + Called when an ItemStack with NBT data is read to potentially that + * ItemStack's NBT data */ public boolean updateItemStackNBT(NBTTagCompound nbt) { super.updateItemStackNBT(nbt); diff --git a/src/game/java/net/minecraft/item/ItemSlab.java b/src/game/java/net/minecraft/item/ItemSlab.java index 90c86756..1bc37683 100644 --- a/src/game/java/net/minecraft/item/ItemSlab.java +++ b/src/game/java/net/minecraft/item/ItemSlab.java @@ -9,22 +9,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,26 +44,46 @@ public class ItemSlab extends ItemBlock { this.setHasSubtypes(true); } - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). + public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, EnumFacing side, EntityPlayer player, + ItemStack stack) { + BlockPos blockpos = pos; + IProperty iproperty = this.singleSlab.getVariantProperty(); + Object object = this.singleSlab.getVariant(stack); + IBlockState iblockstate = worldIn.getBlockState(pos); + if (iblockstate.getBlock() == this.singleSlab) { + boolean flag = iblockstate.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.TOP; + if ((side == EnumFacing.UP && !flag || side == EnumFacing.DOWN && flag) + && object == iblockstate.getValue(iproperty)) { + return true; + } + } + + pos = pos.offset(side); + IBlockState iblockstate1 = worldIn.getBlockState(pos); + return iblockstate1.getBlock() == this.singleSlab && object == iblockstate1.getValue(iproperty) ? true + : super.canPlaceBlockOnSide(worldIn, blockpos, side, player, stack); + } + + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). */ public int getMetadata(int i) { return i; } - /**+ - * Returns the unlocalized name of this item. This version - * accepts an ItemStack so different stacks can have different - * names based on their damage or NBT. + /** + * + Returns the unlocalized name of this item. This version accepts an + * ItemStack so different stacks can have different names based on their damage + * or NBT. */ public String getUnlocalizedName(ItemStack itemstack) { return this.singleSlab.getUnlocalizedName(itemstack.getMetadata()); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { @@ -100,26 +123,6 @@ public class ItemSlab extends ItemBlock { } } - public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, EnumFacing side, EntityPlayer player, - ItemStack stack) { - BlockPos blockpos = pos; - IProperty iproperty = this.singleSlab.getVariantProperty(); - Object object = this.singleSlab.getVariant(stack); - IBlockState iblockstate = worldIn.getBlockState(pos); - if (iblockstate.getBlock() == this.singleSlab) { - boolean flag = iblockstate.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.TOP; - if ((side == EnumFacing.UP && !flag || side == EnumFacing.DOWN && flag) - && object == iblockstate.getValue(iproperty)) { - return true; - } - } - - pos = pos.offset(side); - IBlockState iblockstate1 = worldIn.getBlockState(pos); - return iblockstate1.getBlock() == this.singleSlab && object == iblockstate1.getValue(iproperty) ? true - : super.canPlaceBlockOnSide(worldIn, blockpos, side, player, stack); - } - private boolean tryPlace(ItemStack stack, World worldIn, BlockPos pos, Object variantInStack) { IBlockState iblockstate = worldIn.getBlockState(pos); if (iblockstate.getBlock() == this.singleSlab) { diff --git a/src/game/java/net/minecraft/item/ItemSnow.java b/src/game/java/net/minecraft/item/ItemSnow.java index 5c2b37f8..d3c4a1d3 100644 --- a/src/game/java/net/minecraft/item/ItemSnow.java +++ b/src/game/java/net/minecraft/item/ItemSnow.java @@ -9,22 +9,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,17 @@ public class ItemSnow extends ItemBlock { this.setHasSubtypes(true); } - /**+ - * Called when a Block is right-clicked with this Item + /** + * + Converts the given ItemStack damage value into a metadata value to be + * placed in the world when this Item is placed as a Block (mostly used with + * ItemBlocks). + */ + public int getMetadata(int i) { + return i; + } + + /** + * + Called when a Block is right-clicked with this Item */ public boolean onItemUse(ItemStack itemstack, EntityPlayer entityplayer, World world, BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { @@ -75,13 +87,4 @@ public class ItemSnow extends ItemBlock { return super.onItemUse(itemstack, entityplayer, world, blockpos1, enumfacing, f, f1, f2); } } - - /**+ - * Converts the given ItemStack damage value into a metadata - * value to be placed in the world when this Item is placed as a - * Block (mostly used with ItemBlocks). - */ - public int getMetadata(int i) { - return i; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemSnowball.java b/src/game/java/net/minecraft/item/ItemSnowball.java index 0da39038..a3b0bb49 100644 --- a/src/game/java/net/minecraft/item/ItemSnowball.java +++ b/src/game/java/net/minecraft/item/ItemSnowball.java @@ -6,22 +6,25 @@ import net.minecraft.entity.projectile.EntitySnowball; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,9 +35,9 @@ public class ItemSnowball extends Item { this.setCreativeTab(CreativeTabs.tabMisc); } - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World world, EntityPlayer entityplayer) { if (!entityplayer.capabilities.isCreativeMode) { diff --git a/src/game/java/net/minecraft/item/ItemSoup.java b/src/game/java/net/minecraft/item/ItemSoup.java index 57431d21..669396d2 100644 --- a/src/game/java/net/minecraft/item/ItemSoup.java +++ b/src/game/java/net/minecraft/item/ItemSoup.java @@ -4,22 +4,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,10 +33,10 @@ public class ItemSoup extends ItemFood { this.setMaxStackSize(1); } - /**+ - * Called when the player finishes using this Item (E.g. - * finishes eating.). Not called when the player stops using the - * Item before the action is complete. + /** + * + Called when the player finishes using this Item (E.g. finishes eating.). + * Not called when the player stops using the Item before the action is + * complete. */ public ItemStack onItemUseFinish(ItemStack itemstack, World world, EntityPlayer entityplayer) { super.onItemUseFinish(itemstack, world, entityplayer); diff --git a/src/game/java/net/minecraft/item/ItemSpade.java b/src/game/java/net/minecraft/item/ItemSpade.java index ca8b4f62..ed0a1cd7 100644 --- a/src/game/java/net/minecraft/item/ItemSpade.java +++ b/src/game/java/net/minecraft/item/ItemSpade.java @@ -7,22 +7,25 @@ import com.google.common.collect.Sets; import net.minecraft.block.Block; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,8 +42,8 @@ public class ItemSpade extends ItemTool { super(1.0F, material, EFFECTIVE_ON); } - /**+ - * Check whether this Item can harvest the given Block + /** + * + Check whether this Item can harvest the given Block */ public boolean canHarvestBlock(Block block) { return block == Blocks.snow_layer ? true : block == Blocks.snow; diff --git a/src/game/java/net/minecraft/item/ItemStack.java b/src/game/java/net/minecraft/item/ItemStack.java index a469a648..388eb9e6 100644 --- a/src/game/java/net/minecraft/item/ItemStack.java +++ b/src/game/java/net/minecraft/item/ItemStack.java @@ -4,16 +4,15 @@ import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.HString; -import net.lax1dude.eaglercraft.v1_8.profanity_filter.ProfanityFilter; - import java.util.Set; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.profanity_filter.ProfanityFilter; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.enchantment.Enchantment; @@ -41,28 +40,73 @@ import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public final class ItemStack { public static final DecimalFormat DECIMALFORMAT = new DecimalFormat("#.###"); + + /** + * + Compares Item and damage value of the two stacks + */ + public static boolean areItemsEqual(ItemStack stackA, ItemStack stackB) { + return stackA == null && stackB == null ? true + : (stackA != null && stackB != null ? stackA.isItemEqual(stackB) : false); + } + + /** + * + compares ItemStack argument1 with ItemStack argument2; returns true if both + * ItemStacks are equal + */ + public static boolean areItemStacksEqual(ItemStack stackA, ItemStack stackB) { + return stackA == null && stackB == null ? true + : (stackA != null && stackB != null ? stackA.isItemStackEqual(stackB) : false); + } + + public static boolean areItemStackTagsEqual(ItemStack stackA, ItemStack stackB) { + return stackA == null + && stackB == null + ? true + : (stackA != null && stackB != null + ? (stackA.stackTagCompound == null && stackB.stackTagCompound != null ? false + : stackA.stackTagCompound == null + || stackA.stackTagCompound.equals(stackB.stackTagCompound)) + : false); + } + + /** + * + Creates a copy of a ItemStack, a null parameters will return a null. + */ + public static ItemStack copyItemStack(ItemStack stack) { + return stack == null ? null : stack.copy(); + } + + public static ItemStack loadItemStackFromNBT(NBTTagCompound nbt) { + ItemStack itemstack = new ItemStack(); + itemstack.readFromNBT(nbt); + return itemstack.getItem() != null ? itemstack : null; + } + public int stackSize; public int animationsToGo; private Item item; @@ -70,12 +114,24 @@ public final class ItemStack { private String profanityFilteredName; private String profanityFilteredNameFiltered; private int itemDamage; + private EntityItemFrame itemFrame; + private Block canDestroyCacheBlock; + private boolean canDestroyCacheResult; + private Block canPlaceOnCacheBlock; + private boolean canPlaceOnCacheResult; + private ItemStack() { + this.canDestroyCacheBlock = null; + this.canDestroyCacheResult = false; + this.canPlaceOnCacheBlock = null; + this.canPlaceOnCacheResult = false; + } + public ItemStack(Block blockIn) { this((Block) blockIn, 1); } @@ -110,182 +166,31 @@ public final class ItemStack { } - public static ItemStack loadItemStackFromNBT(NBTTagCompound nbt) { - ItemStack itemstack = new ItemStack(); - itemstack.readFromNBT(nbt); - return itemstack.getItem() != null ? itemstack : null; - } - - private ItemStack() { - this.canDestroyCacheBlock = null; - this.canDestroyCacheResult = false; - this.canPlaceOnCacheBlock = null; - this.canPlaceOnCacheResult = false; - } - - /**+ - * Splits off a stack of the given amount of this stack and - * reduces this stack by the amount. + /** + * + Adds an enchantment with a desired level on the ItemStack. */ - public ItemStack splitStack(int amount) { - ItemStack itemstack = new ItemStack(this.item, amount, this.itemDamage); - if (this.stackTagCompound != null) { - itemstack.stackTagCompound = (NBTTagCompound) this.stackTagCompound.copy(); + public void addEnchantment(Enchantment ench, int level) { + if (this.stackTagCompound == null) { + this.setTagCompound(new NBTTagCompound()); } - this.stackSize -= amount; - return itemstack; - } - - /**+ - * Returns the object corresponding to the stack. - */ - public Item getItem() { - return this.item; - } - - /**+ - * Called when the player uses this ItemStack on a Block - * (right-click). Places blocks, etc. (Legacy name: - * tryPlaceItemIntoWorld) - */ - public boolean onItemUse(EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, - float hitY, float hitZ) { - boolean flag = this.getItem().onItemUse(this, playerIn, worldIn, pos, side, hitX, hitY, hitZ); - if (flag) { - playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this.item)]); + if (!this.stackTagCompound.hasKey("ench", 9)) { + this.stackTagCompound.setTag("ench", new NBTTagList()); } - return flag; + NBTTagList nbttaglist = this.stackTagCompound.getTagList("ench", 10); + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setShort("id", (short) ench.effectId); + nbttagcompound.setShort("lvl", (short) ((byte) level)); + nbttaglist.appendTag(nbttagcompound); } - public float getStrVsBlock(Block blockIn) { - return this.getItem().getStrVsBlock(this, blockIn); - } - - /**+ - * Called whenever this item stack is equipped and right - * clicked. Returns the new item stack to put in the position - * where this item is. Args: world, player - */ - public ItemStack useItemRightClick(World worldIn, EntityPlayer playerIn) { - return this.getItem().onItemRightClick(this, worldIn, playerIn); - } - - /**+ - * Called when the item in use count reach 0, e.g. item food - * eaten. Return the new ItemStack. Args : world, entity - */ - public ItemStack onItemUseFinish(World worldIn, EntityPlayer playerIn) { - return this.getItem().onItemUseFinish(this, worldIn, playerIn); - } - - /**+ - * Write the stack fields to a NBT object. Return the new NBT - * object. - */ - public NBTTagCompound writeToNBT(NBTTagCompound nbt) { - ResourceLocation resourcelocation = (ResourceLocation) Item.itemRegistry.getNameForObject(this.item); - nbt.setString("id", resourcelocation == null ? "minecraft:air" : resourcelocation.toString()); - nbt.setByte("Count", (byte) this.stackSize); - nbt.setShort("Damage", (short) this.itemDamage); - if (this.stackTagCompound != null) { - nbt.setTag("tag", this.stackTagCompound); - } - - return nbt; - } - - /**+ - * Read the stack fields from a NBT object. - */ - public void readFromNBT(NBTTagCompound nbt) { - if (nbt.hasKey("id", 8)) { - this.item = Item.getByNameOrId(nbt.getString("id")); - } else { - this.item = Item.getItemById(nbt.getShort("id")); - } - - this.stackSize = nbt.getByte("Count"); - this.itemDamage = nbt.getShort("Damage"); - if (this.itemDamage < 0) { - this.itemDamage = 0; - } - - if (nbt.hasKey("tag", 10)) { - this.stackTagCompound = nbt.getCompoundTag("tag"); - if (this.item != null) { - this.item.updateItemStackNBT(this.stackTagCompound); - } - } - - } - - /**+ - * Returns maximum size of the stack. - */ - public int getMaxStackSize() { - return this.getItem().getItemStackLimit(); - } - - /**+ - * Returns true if the ItemStack can hold 2 or more units of the - * item. - */ - public boolean isStackable() { - return this.getMaxStackSize() > 1 && (!this.isItemStackDamageable() || !this.isItemDamaged()); - } - - /**+ - * true if this itemStack is damageable - */ - public boolean isItemStackDamageable() { - return this.item == null ? false - : (this.item.getMaxDamage() <= 0 ? false - : !this.hasTagCompound() || !this.getTagCompound().getBoolean("Unbreakable")); - } - - public boolean getHasSubtypes() { - return this.item.getHasSubtypes(); - } - - /**+ - * returns true when a damageable item is damaged - */ - public boolean isItemDamaged() { - return this.isItemStackDamageable() && this.itemDamage > 0; - } - - public int getItemDamage() { - return this.itemDamage; - } - - public int getMetadata() { - return this.itemDamage; - } - - public void setItemDamage(int meta) { - this.itemDamage = meta; - if (this.itemDamage < 0) { - this.itemDamage = 0; - } - - } - - /**+ - * Returns the max damage an item in the stack can take. - */ - public int getMaxDamage() { - return this.item.getMaxDamage(); - } - - /**+ - * Attempts to damage the ItemStack with par1 amount of damage, - * If the ItemStack has the Unbreaking enchantment there is a - * chance for each point of damage to be negated. Returns true - * if it takes more damage than getMaxDamage(). Returns false - * otherwise or if the ItemStack can't be damaged or if all - * points of damage are negated. + /** + * + Attempts to damage the ItemStack with par1 amount of damage, If the + * ItemStack has the Unbreaking enchantment there is a chance for each point of + * damage to be negated. Returns true if it takes more damage than + * getMaxDamage(). Returns false otherwise or if the ItemStack can't be damaged + * or if all points of damage are negated. */ public boolean attemptDamageItem(int amount, EaglercraftRandom rand) { if (!this.isItemStackDamageable()) { @@ -312,8 +217,94 @@ public final class ItemStack { } } - /**+ - * Damages the item in the ItemStack + public boolean canDestroy(Block blockIn) { + if (blockIn == this.canDestroyCacheBlock) { + return this.canDestroyCacheResult; + } else { + this.canDestroyCacheBlock = blockIn; + if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanDestroy", 9)) { + NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanDestroy", 8); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + Block block = Block.getBlockFromName(nbttaglist.getStringTagAt(i)); + if (block == blockIn) { + this.canDestroyCacheResult = true; + return true; + } + } + } + + this.canDestroyCacheResult = false; + return false; + } + } + + public boolean canEditBlocks() { + return this.getItem().canItemEditBlocks(); + } + + /** + * + Check whether the given Block can be harvested using this ItemStack. + */ + public boolean canHarvestBlock(Block blockIn) { + return this.item.canHarvestBlock(blockIn); + } + + public boolean canPlaceOn(Block blockIn) { + if (blockIn == this.canPlaceOnCacheBlock) { + return this.canPlaceOnCacheResult; + } else { + this.canPlaceOnCacheBlock = blockIn; + if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanPlaceOn", 9)) { + NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanPlaceOn", 8); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + Block block = Block.getBlockFromName(nbttaglist.getStringTagAt(i)); + if (block == blockIn) { + this.canPlaceOnCacheResult = true; + return true; + } + } + } + + this.canPlaceOnCacheResult = false; + return false; + } + } + + /** + * + Clear any custom name set for this ItemStack + */ + public void clearCustomName() { + if (this.stackTagCompound != null) { + if (this.stackTagCompound.hasKey("display", 10)) { + NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); + nbttagcompound.removeTag("Name"); + if (nbttagcompound.hasNoTags()) { + this.stackTagCompound.removeTag("display"); + if (this.stackTagCompound.hasNoTags()) { + this.setTagCompound((NBTTagCompound) null); + } + } + + } + } + } + + /** + * + Returns a new stack with the same properties. + */ + public ItemStack copy() { + ItemStack itemstack = new ItemStack(this.item, this.stackSize, this.itemDamage); + if (this.stackTagCompound != null) { + itemstack.stackTagCompound = (NBTTagCompound) this.stackTagCompound.copy(); + } + + return itemstack; + } + + /** + * + Damages the item in the ItemStack */ public void damageItem(int amount, EntityLivingBase entityIn) { if (!(entityIn instanceof EntityPlayer) || !((EntityPlayer) entityIn).capabilities.isCreativeMode) { @@ -340,200 +331,52 @@ public final class ItemStack { } } - /**+ - * Calls the corresponding fct in di - */ - public void hitEntity(EntityLivingBase entityIn, EntityPlayer playerIn) { - boolean flag = this.item.hitEntity(this, entityIn, playerIn); - if (flag) { - playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this.item)]); - } + public Multimap getAttributeModifiers() { + Object object; + if (this.hasTagCompound() && this.stackTagCompound.hasKey("AttributeModifiers", 9)) { + object = HashMultimap.create(); + NBTTagList nbttaglist = this.stackTagCompound.getTagList("AttributeModifiers", 10); - } - - /**+ - * Called when a Block is destroyed using this ItemStack - */ - public void onBlockDestroyed(World worldIn, Block blockIn, BlockPos pos, EntityPlayer playerIn) { - boolean flag = this.item.onBlockDestroyed(this, worldIn, blockIn, pos, playerIn); - if (flag) { - playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this.item)]); - } - - } - - /**+ - * Check whether the given Block can be harvested using this - * ItemStack. - */ - public boolean canHarvestBlock(Block blockIn) { - return this.item.canHarvestBlock(blockIn); - } - - public boolean interactWithEntity(EntityPlayer playerIn, EntityLivingBase entityIn) { - return this.item.itemInteractionForEntity(this, playerIn, entityIn); - } - - /**+ - * Returns a new stack with the same properties. - */ - public ItemStack copy() { - ItemStack itemstack = new ItemStack(this.item, this.stackSize, this.itemDamage); - if (this.stackTagCompound != null) { - itemstack.stackTagCompound = (NBTTagCompound) this.stackTagCompound.copy(); - } - - return itemstack; - } - - public static boolean areItemStackTagsEqual(ItemStack stackA, ItemStack stackB) { - return stackA == null - && stackB == null - ? true - : (stackA != null && stackB != null - ? (stackA.stackTagCompound == null && stackB.stackTagCompound != null ? false - : stackA.stackTagCompound == null - || stackA.stackTagCompound.equals(stackB.stackTagCompound)) - : false); - } - - /**+ - * compares ItemStack argument1 with ItemStack argument2; - * returns true if both ItemStacks are equal - */ - public static boolean areItemStacksEqual(ItemStack stackA, ItemStack stackB) { - return stackA == null && stackB == null ? true - : (stackA != null && stackB != null ? stackA.isItemStackEqual(stackB) : false); - } - - /**+ - * compares ItemStack argument to the instance ItemStack; - * returns true if both ItemStacks are equal - */ - private boolean isItemStackEqual(ItemStack other) { - return this.stackSize != other.stackSize ? false - : (this.item != other.item ? false - : (this.itemDamage != other.itemDamage ? false - : (this.stackTagCompound == null && other.stackTagCompound != null ? false - : this.stackTagCompound == null - || this.stackTagCompound.equals(other.stackTagCompound)))); - } - - /**+ - * Compares Item and damage value of the two stacks - */ - public static boolean areItemsEqual(ItemStack stackA, ItemStack stackB) { - return stackA == null && stackB == null ? true - : (stackA != null && stackB != null ? stackA.isItemEqual(stackB) : false); - } - - /**+ - * compares ItemStack argument to the instance ItemStack; - * returns true if the Items contained in both ItemStacks are - * equal - */ - public boolean isItemEqual(ItemStack other) { - return other != null && this.item == other.item && this.itemDamage == other.itemDamage; - } - - public String getUnlocalizedName() { - return this.item.getUnlocalizedName(this); - } - - /**+ - * Creates a copy of a ItemStack, a null parameters will return - * a null. - */ - public static ItemStack copyItemStack(ItemStack stack) { - return stack == null ? null : stack.copy(); - } - - public String toString() { - return this.stackSize + "x" + this.item.getUnlocalizedName() + "@" + this.itemDamage; - } - - /**+ - * Called each tick as long the ItemStack in on player - * inventory. Used to progress the pickup animation and update - * maps. - */ - public void updateAnimation(World worldIn, Entity entityIn, int inventorySlot, boolean isCurrentItem) { - if (this.animationsToGo > 0) { - --this.animationsToGo; - } - - this.item.onUpdate(this, worldIn, entityIn, inventorySlot, isCurrentItem); - } - - public void onCrafting(World worldIn, EntityPlayer playerIn, int amount) { - playerIn.addStat(StatList.objectCraftStats[Item.getIdFromItem(this.item)], amount); - this.item.onCreated(this, worldIn, playerIn); - } - - public boolean getIsItemStackEqual(ItemStack parItemStack) { - return this.isItemStackEqual(parItemStack); - } - - public int getMaxItemUseDuration() { - return this.getItem().getMaxItemUseDuration(this); - } - - public EnumAction getItemUseAction() { - return this.getItem().getItemUseAction(this); - } - - /**+ - * Called when the player releases the use item button. Args: - * world, entityplayer, itemInUseCount - */ - public void onPlayerStoppedUsing(World worldIn, EntityPlayer playerIn, int timeLeft) { - this.getItem().onPlayerStoppedUsing(this, worldIn, playerIn, timeLeft); - } - - /**+ - * Returns true if the ItemStack has an NBTTagCompound. - * Currently used to store enchantments. - */ - public boolean hasTagCompound() { - return this.stackTagCompound != null; - } - - /**+ - * Returns the NBTTagCompound of the ItemStack. - */ - public NBTTagCompound getTagCompound() { - return this.stackTagCompound; - } - - /**+ - * Get an NBTTagCompound from this stack's NBT data. - */ - public NBTTagCompound getSubCompound(String key, boolean create) { - if (this.stackTagCompound != null && this.stackTagCompound.hasKey(key, 10)) { - return this.stackTagCompound.getCompoundTag(key); - } else if (create) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.setTagInfo(key, nbttagcompound); - return nbttagcompound; + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + AttributeModifier attributemodifier = SharedMonsterAttributes + .readAttributeModifierFromNBT(nbttagcompound); + if (attributemodifier != null && attributemodifier.getID().getLeastSignificantBits() != 0L + && attributemodifier.getID().getMostSignificantBits() != 0L) { + ((Multimap) object).put(nbttagcompound.getString("AttributeName"), attributemodifier); + } + } } else { - return null; + object = this.getItem().getItemAttributeModifiers(); } + + return (Multimap) object; } - public NBTTagList getEnchantmentTagList() { - return this.stackTagCompound == null ? null : this.stackTagCompound.getTagList("ench", 10); - } - - /**+ - * Assigns a NBTTagCompound to the ItemStack, minecraft - * validates that only non-stackable items can have it. + /** + * + Get a ChatComponent for this Item's display name that shows this Item on + * hover */ - public void setTagCompound(NBTTagCompound nbt) { - this.stackTagCompound = nbt; + public IChatComponent getChatComponent() { + ChatComponentText chatcomponenttext = new ChatComponentText(this.getDisplayName()); + if (this.hasDisplayName()) { + chatcomponenttext.getChatStyle().setItalic(Boolean.valueOf(true)); + } + + IChatComponent ichatcomponent = (new ChatComponentText("[")).appendSibling(chatcomponenttext).appendText("]"); + if (this.item != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + ichatcomponent.getChatStyle().setChatHoverEvent( + new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ChatComponentText(nbttagcompound.toString()))); + ichatcomponent.getChatStyle().setColor(this.getRarity().rarityColor); + } + + return ichatcomponent; } - /**+ - * returns the display name of the itemstack + /** + * + returns the display name of the itemstack */ public String getDisplayName() { String s = this.getItem().getItemStackDisplayName(this); @@ -568,59 +411,109 @@ public final class ItemStack { return s; } - public ItemStack setStackDisplayName(String displayName) { - if (this.stackTagCompound == null) { - this.stackTagCompound = new NBTTagCompound(); - } - - if (!this.stackTagCompound.hasKey("display", 10)) { - this.stackTagCompound.setTag("display", new NBTTagCompound()); - } - - this.stackTagCompound.getCompoundTag("display").setString("Name", displayName); - return this; + public NBTTagList getEnchantmentTagList() { + return this.stackTagCompound == null ? null : this.stackTagCompound.getTagList("ench", 10); } - /**+ - * Clear any custom name set for this ItemStack + public boolean getHasSubtypes() { + return this.item.getHasSubtypes(); + } + + public boolean getIsItemStackEqual(ItemStack parItemStack) { + return this.isItemStackEqual(parItemStack); + } + + /** + * + Returns the object corresponding to the stack. */ - public void clearCustomName() { - if (this.stackTagCompound != null) { - if (this.stackTagCompound.hasKey("display", 10)) { - NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); - nbttagcompound.removeTag("Name"); - if (nbttagcompound.hasNoTags()) { - this.stackTagCompound.removeTag("display"); - if (this.stackTagCompound.hasNoTags()) { - this.setTagCompound((NBTTagCompound) null); - } - } + public Item getItem() { + return this.item; + } - } + public int getItemDamage() { + return this.itemDamage; + } + + /** + * + Return the item frame this stack is on. Returns null if not on an item + * frame. + */ + public EntityItemFrame getItemFrame() { + return this.itemFrame; + } + + public EnumAction getItemUseAction() { + return this.getItem().getItemUseAction(this); + } + + /** + * + Returns the max damage an item in the stack can take. + */ + public int getMaxDamage() { + return this.item.getMaxDamage(); + } + + public int getMaxItemUseDuration() { + return this.getItem().getMaxItemUseDuration(this); + } + + /** + * + Returns maximum size of the stack. + */ + public int getMaxStackSize() { + return this.getItem().getItemStackLimit(); + } + + public int getMetadata() { + return this.itemDamage; + } + + public EnumRarity getRarity() { + return this.getItem().getRarity(this); + } + + /** + * + Get this stack's repair cost, or 0 if no repair cost is defined. + */ + public int getRepairCost() { + return this.hasTagCompound() && this.stackTagCompound.hasKey("RepairCost", 3) + ? this.stackTagCompound.getInteger("RepairCost") + : 0; + } + + public float getStrVsBlock(Block blockIn) { + return this.getItem().getStrVsBlock(this, blockIn); + } + + /** + * + Get an NBTTagCompound from this stack's NBT data. + */ + public NBTTagCompound getSubCompound(String key, boolean create) { + if (this.stackTagCompound != null && this.stackTagCompound.hasKey(key, 10)) { + return this.stackTagCompound.getCompoundTag(key); + } else if (create) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.setTagInfo(key, nbttagcompound); + return nbttagcompound; + } else { + return null; } } - /**+ - * Returns true if the itemstack has a display name + /** + * + Returns the NBTTagCompound of the ItemStack. */ - public boolean hasDisplayName() { - return this.stackTagCompound == null ? false - : (!this.stackTagCompound.hasKey("display", 10) ? false - : this.stackTagCompound.getCompoundTag("display").hasKey("Name", 8)); + public NBTTagCompound getTagCompound() { + return this.stackTagCompound; } - /**+ - * Return a list of strings containing information about the - * item + /** + * + Return a list of strings containing information about the item */ public List getTooltip(EntityPlayer playerIn, boolean advanced) { return getTooltipImpl(playerIn, advanced, false); } - public List getTooltipProfanityFilter(EntityPlayer playerIn, boolean advanced) { - return getTooltipImpl(playerIn, advanced, true); - } - public List getTooltipImpl(EntityPlayer playerIn, boolean advanced, boolean profanityFilter) { ArrayList arraylist = Lists.newArrayList(); String s = profanityFilter ? this.getDisplayNameProfanityFilter() : this.getDisplayName(); @@ -782,47 +675,237 @@ public final class ItemStack { return arraylist; } + public List getTooltipProfanityFilter(EntityPlayer playerIn, boolean advanced) { + return getTooltipImpl(playerIn, advanced, true); + } + + public String getUnlocalizedName() { + return this.item.getUnlocalizedName(this); + } + + /** + * + Returns true if the itemstack has a display name + */ + public boolean hasDisplayName() { + return this.stackTagCompound == null ? false + : (!this.stackTagCompound.hasKey("display", 10) ? false + : this.stackTagCompound.getCompoundTag("display").hasKey("Name", 8)); + } + public boolean hasEffect() { return this.getItem().hasEffect(this); } - public EnumRarity getRarity() { - return this.getItem().getRarity(this); + /** + * + Returns true if the ItemStack has an NBTTagCompound. Currently used to + * store enchantments. + */ + public boolean hasTagCompound() { + return this.stackTagCompound != null; } - /**+ - * True if it is a tool and has no enchantments to begin with + /** + * + Calls the corresponding fct in di + */ + public void hitEntity(EntityLivingBase entityIn, EntityPlayer playerIn) { + boolean flag = this.item.hitEntity(this, entityIn, playerIn); + if (flag) { + playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this.item)]); + } + + } + + public boolean interactWithEntity(EntityPlayer playerIn, EntityLivingBase entityIn) { + return this.item.itemInteractionForEntity(this, playerIn, entityIn); + } + + /** + * + returns true when a damageable item is damaged + */ + public boolean isItemDamaged() { + return this.isItemStackDamageable() && this.itemDamage > 0; + } + + /** + * + True if it is a tool and has no enchantments to begin with */ public boolean isItemEnchantable() { return !this.getItem().isItemTool(this) ? false : !this.isItemEnchanted(); } - /**+ - * Adds an enchantment with a desired level on the ItemStack. - */ - public void addEnchantment(Enchantment ench, int level) { - if (this.stackTagCompound == null) { - this.setTagCompound(new NBTTagCompound()); - } - - if (!this.stackTagCompound.hasKey("ench", 9)) { - this.stackTagCompound.setTag("ench", new NBTTagList()); - } - - NBTTagList nbttaglist = this.stackTagCompound.getTagList("ench", 10); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setShort("id", (short) ench.effectId); - nbttagcompound.setShort("lvl", (short) ((byte) level)); - nbttaglist.appendTag(nbttagcompound); - } - - /**+ - * True if the item has enchantment data + /** + * + True if the item has enchantment data */ public boolean isItemEnchanted() { return this.stackTagCompound != null && this.stackTagCompound.hasKey("ench", 9); } + /** + * + compares ItemStack argument to the instance ItemStack; returns true if the + * Items contained in both ItemStacks are equal + */ + public boolean isItemEqual(ItemStack other) { + return other != null && this.item == other.item && this.itemDamage == other.itemDamage; + } + + /** + * + true if this itemStack is damageable + */ + public boolean isItemStackDamageable() { + return this.item == null ? false + : (this.item.getMaxDamage() <= 0 ? false + : !this.hasTagCompound() || !this.getTagCompound().getBoolean("Unbreakable")); + } + + /** + * + compares ItemStack argument to the instance ItemStack; returns true if both + * ItemStacks are equal + */ + private boolean isItemStackEqual(ItemStack other) { + return this.stackSize != other.stackSize ? false + : (this.item != other.item ? false + : (this.itemDamage != other.itemDamage ? false + : (this.stackTagCompound == null && other.stackTagCompound != null ? false + : this.stackTagCompound == null + || this.stackTagCompound.equals(other.stackTagCompound)))); + } + + /** + * + Return whether this stack is on an item frame. + */ + public boolean isOnItemFrame() { + return this.itemFrame != null; + } + + /** + * + Returns true if the ItemStack can hold 2 or more units of the item. + */ + public boolean isStackable() { + return this.getMaxStackSize() > 1 && (!this.isItemStackDamageable() || !this.isItemDamaged()); + } + + /** + * + Called when a Block is destroyed using this ItemStack + */ + public void onBlockDestroyed(World worldIn, Block blockIn, BlockPos pos, EntityPlayer playerIn) { + boolean flag = this.item.onBlockDestroyed(this, worldIn, blockIn, pos, playerIn); + if (flag) { + playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this.item)]); + } + + } + + public void onCrafting(World worldIn, EntityPlayer playerIn, int amount) { + playerIn.addStat(StatList.objectCraftStats[Item.getIdFromItem(this.item)], amount); + this.item.onCreated(this, worldIn, playerIn); + } + + /** + * + Called when the player uses this ItemStack on a Block (right-click). Places + * blocks, etc. (Legacy name: tryPlaceItemIntoWorld) + */ + public boolean onItemUse(EntityPlayer playerIn, World worldIn, BlockPos pos, EnumFacing side, float hitX, + float hitY, float hitZ) { + boolean flag = this.getItem().onItemUse(this, playerIn, worldIn, pos, side, hitX, hitY, hitZ); + if (flag) { + playerIn.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this.item)]); + } + + return flag; + } + + /** + * + Called when the item in use count reach 0, e.g. item food eaten. Return the + * new ItemStack. Args : world, entity + */ + public ItemStack onItemUseFinish(World worldIn, EntityPlayer playerIn) { + return this.getItem().onItemUseFinish(this, worldIn, playerIn); + } + + /** + * + Called when the player releases the use item button. Args: world, + * entityplayer, itemInUseCount + */ + public void onPlayerStoppedUsing(World worldIn, EntityPlayer playerIn, int timeLeft) { + this.getItem().onPlayerStoppedUsing(this, worldIn, playerIn, timeLeft); + } + + /** + * + Read the stack fields from a NBT object. + */ + public void readFromNBT(NBTTagCompound nbt) { + if (nbt.hasKey("id", 8)) { + this.item = Item.getByNameOrId(nbt.getString("id")); + } else { + this.item = Item.getItemById(nbt.getShort("id")); + } + + this.stackSize = nbt.getByte("Count"); + this.itemDamage = nbt.getShort("Damage"); + if (this.itemDamage < 0) { + this.itemDamage = 0; + } + + if (nbt.hasKey("tag", 10)) { + this.stackTagCompound = nbt.getCompoundTag("tag"); + if (this.item != null) { + this.item.updateItemStackNBT(this.stackTagCompound); + } + } + + } + + public void setItem(Item newItem) { + this.item = newItem; + } + + public void setItemDamage(int meta) { + this.itemDamage = meta; + if (this.itemDamage < 0) { + this.itemDamage = 0; + } + + } + + /** + * + Set the item frame this stack is on. + */ + public void setItemFrame(EntityItemFrame frame) { + this.itemFrame = frame; + } + + /** + * + Set this stack's repair cost. + */ + public void setRepairCost(int cost) { + if (!this.hasTagCompound()) { + this.stackTagCompound = new NBTTagCompound(); + } + + this.stackTagCompound.setInteger("RepairCost", cost); + } + + public ItemStack setStackDisplayName(String displayName) { + if (this.stackTagCompound == null) { + this.stackTagCompound = new NBTTagCompound(); + } + + if (!this.stackTagCompound.hasKey("display", 10)) { + this.stackTagCompound.setTag("display", new NBTTagCompound()); + } + + this.stackTagCompound.getCompoundTag("display").setString("Name", displayName); + return this; + } + + /** + * + Assigns a NBTTagCompound to the ItemStack, minecraft validates that only + * non-stackable items can have it. + */ + public void setTagCompound(NBTTagCompound nbt) { + this.stackTagCompound = nbt; + } + public void setTagInfo(String key, NBTBase value) { if (this.stackTagCompound == null) { this.setTagCompound(new NBTTagCompound()); @@ -831,142 +914,56 @@ public final class ItemStack { this.stackTagCompound.setTag(key, value); } - public boolean canEditBlocks() { - return this.getItem().canItemEditBlocks(); - } - - /**+ - * Return whether this stack is on an item frame. + /** + * + Splits off a stack of the given amount of this stack and reduces this stack + * by the amount. */ - public boolean isOnItemFrame() { - return this.itemFrame != null; - } - - /**+ - * Set the item frame this stack is on. - */ - public void setItemFrame(EntityItemFrame frame) { - this.itemFrame = frame; - } - - /**+ - * Return the item frame this stack is on. Returns null if not - * on an item frame. - */ - public EntityItemFrame getItemFrame() { - return this.itemFrame; - } - - /**+ - * Get this stack's repair cost, or 0 if no repair cost is - * defined. - */ - public int getRepairCost() { - return this.hasTagCompound() && this.stackTagCompound.hasKey("RepairCost", 3) - ? this.stackTagCompound.getInteger("RepairCost") - : 0; - } - - /**+ - * Set this stack's repair cost. - */ - public void setRepairCost(int cost) { - if (!this.hasTagCompound()) { - this.stackTagCompound = new NBTTagCompound(); + public ItemStack splitStack(int amount) { + ItemStack itemstack = new ItemStack(this.item, amount, this.itemDamage); + if (this.stackTagCompound != null) { + itemstack.stackTagCompound = (NBTTagCompound) this.stackTagCompound.copy(); } - this.stackTagCompound.setInteger("RepairCost", cost); + this.stackSize -= amount; + return itemstack; } - public Multimap getAttributeModifiers() { - Object object; - if (this.hasTagCompound() && this.stackTagCompound.hasKey("AttributeModifiers", 9)) { - object = HashMultimap.create(); - NBTTagList nbttaglist = this.stackTagCompound.getTagList("AttributeModifiers", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - AttributeModifier attributemodifier = SharedMonsterAttributes - .readAttributeModifierFromNBT(nbttagcompound); - if (attributemodifier != null && attributemodifier.getID().getLeastSignificantBits() != 0L - && attributemodifier.getID().getMostSignificantBits() != 0L) { - ((Multimap) object).put(nbttagcompound.getString("AttributeName"), attributemodifier); - } - } - } else { - object = this.getItem().getItemAttributeModifiers(); - } - - return (Multimap) object; + public String toString() { + return this.stackSize + "x" + this.item.getUnlocalizedName() + "@" + this.itemDamage; } - public void setItem(Item newItem) { - this.item = newItem; - } - - /**+ - * Get a ChatComponent for this Item's display name that shows - * this Item on hover + /** + * + Called each tick as long the ItemStack in on player inventory. Used to + * progress the pickup animation and update maps. */ - public IChatComponent getChatComponent() { - ChatComponentText chatcomponenttext = new ChatComponentText(this.getDisplayName()); - if (this.hasDisplayName()) { - chatcomponenttext.getChatStyle().setItalic(Boolean.valueOf(true)); + public void updateAnimation(World worldIn, Entity entityIn, int inventorySlot, boolean isCurrentItem) { + if (this.animationsToGo > 0) { + --this.animationsToGo; } - IChatComponent ichatcomponent = (new ChatComponentText("[")).appendSibling(chatcomponenttext).appendText("]"); - if (this.item != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - ichatcomponent.getChatStyle().setChatHoverEvent( - new HoverEvent(HoverEvent.Action.SHOW_ITEM, new ChatComponentText(nbttagcompound.toString()))); - ichatcomponent.getChatStyle().setColor(this.getRarity().rarityColor); - } - - return ichatcomponent; + this.item.onUpdate(this, worldIn, entityIn, inventorySlot, isCurrentItem); } - public boolean canDestroy(Block blockIn) { - if (blockIn == this.canDestroyCacheBlock) { - return this.canDestroyCacheResult; - } else { - this.canDestroyCacheBlock = blockIn; - if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanDestroy", 9)) { - NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanDestroy", 8); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - Block block = Block.getBlockFromName(nbttaglist.getStringTagAt(i)); - if (block == blockIn) { - this.canDestroyCacheResult = true; - return true; - } - } - } - - this.canDestroyCacheResult = false; - return false; - } + /** + * + Called whenever this item stack is equipped and right clicked. Returns the + * new item stack to put in the position where this item is. Args: world, player + */ + public ItemStack useItemRightClick(World worldIn, EntityPlayer playerIn) { + return this.getItem().onItemRightClick(this, worldIn, playerIn); } - public boolean canPlaceOn(Block blockIn) { - if (blockIn == this.canPlaceOnCacheBlock) { - return this.canPlaceOnCacheResult; - } else { - this.canPlaceOnCacheBlock = blockIn; - if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanPlaceOn", 9)) { - NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanPlaceOn", 8); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - Block block = Block.getBlockFromName(nbttaglist.getStringTagAt(i)); - if (block == blockIn) { - this.canPlaceOnCacheResult = true; - return true; - } - } - } - - this.canPlaceOnCacheResult = false; - return false; + /** + * + Write the stack fields to a NBT object. Return the new NBT object. + */ + public NBTTagCompound writeToNBT(NBTTagCompound nbt) { + ResourceLocation resourcelocation = (ResourceLocation) Item.itemRegistry.getNameForObject(this.item); + nbt.setString("id", resourcelocation == null ? "minecraft:air" : resourcelocation.toString()); + nbt.setByte("Count", (byte) this.stackSize); + nbt.setShort("Damage", (short) this.itemDamage); + if (this.stackTagCompound != null) { + nbt.setTag("tag", this.stackTagCompound); } + + return nbt; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemSword.java b/src/game/java/net/minecraft/item/ItemSword.java index 44366559..29e8cfd1 100644 --- a/src/game/java/net/minecraft/item/ItemSword.java +++ b/src/game/java/net/minecraft/item/ItemSword.java @@ -13,22 +13,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,14 +48,58 @@ public class ItemSword extends Item { this.attackDamage = 4.0F + material.getDamageVsEntity(); } - /**+ - * Returns the amount of damage this item will deal. One heart - * of damage is equal to 2 damage points. + /** + * + Check whether this Item can harvest the given Block + */ + public boolean canHarvestBlock(Block block) { + return block == Blocks.web; + } + + /** + * + Returns the amount of damage this item will deal. One heart of damage is + * equal to 2 damage points. */ public float getDamageVsEntity() { return this.material.getDamageVsEntity(); } + /** + * + Return whether this item is repairable in an anvil. + */ + public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) { + return this.material.getRepairItem() == repair.getItem() ? true : super.getIsRepairable(toRepair, repair); + } + + public Multimap getItemAttributeModifiers() { + Multimap multimap = super.getItemAttributeModifiers(); + multimap.put(SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(), + new AttributeModifier(itemModifierUUID, "Weapon modifier", (double) this.attackDamage, 0)); + return multimap; + } + + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. + */ + public int getItemEnchantability() { + return this.material.getEnchantability(); + } + + /** + * + returns the action that specifies what animation to play when the items is + * being used + */ + public EnumAction getItemUseAction(ItemStack var1) { + return EnumAction.BLOCK; + } + + /** + * + How long it takes to use or consume an item + */ + public int getMaxItemUseDuration(ItemStack var1) { + return 72000; + } + public float getStrVsBlock(ItemStack var1, Block block) { if (block == Blocks.web) { return 15.0F; @@ -63,19 +110,32 @@ public class ItemSword extends Item { } } - /**+ - * Current implementations of this method in child classes do - * not use the entry argument beside ev. They just raise the - * damage on the stack. + /** + * + Return the name for this tool's material. + */ + public String getToolMaterialName() { + return this.material.toString(); + } + + /** + * + Current implementations of this method in child classes do not use the + * entry argument beside ev. They just raise the damage on the stack. */ public boolean hitEntity(ItemStack itemstack, EntityLivingBase var2, EntityLivingBase entitylivingbase) { itemstack.damageItem(1, entitylivingbase); return true; } - /**+ - * Called when a Block is destroyed using this Item. Return true - * to trigger the "Use Item" statistic. + /** + * + Returns True is the item is renderer in full 3D when hold. + */ + public boolean isFull3D() { + return true; + } + + /** + * + Called when a Block is destroyed using this Item. Return true to trigger + * the "Use Item" statistic. */ public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, BlockPos blockpos, EntityLivingBase entitylivingbase) { @@ -86,70 +146,12 @@ public class ItemSword extends Item { return true; } - /**+ - * Returns True is the item is renderer in full 3D when hold. - */ - public boolean isFull3D() { - return true; - } - - /**+ - * returns the action that specifies what animation to play when - * the items is being used - */ - public EnumAction getItemUseAction(ItemStack var1) { - return EnumAction.BLOCK; - } - - /**+ - * How long it takes to use or consume an item - */ - public int getMaxItemUseDuration(ItemStack var1) { - return 72000; - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer */ public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { entityplayer.setItemInUse(itemstack, this.getMaxItemUseDuration(itemstack)); return itemstack; } - - /**+ - * Check whether this Item can harvest the given Block - */ - public boolean canHarvestBlock(Block block) { - return block == Blocks.web; - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. - */ - public int getItemEnchantability() { - return this.material.getEnchantability(); - } - - /**+ - * Return the name for this tool's material. - */ - public String getToolMaterialName() { - return this.material.toString(); - } - - /**+ - * Return whether this item is repairable in an anvil. - */ - public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) { - return this.material.getRepairItem() == repair.getItem() ? true : super.getIsRepairable(toRepair, repair); - } - - public Multimap getItemAttributeModifiers() { - Multimap multimap = super.getItemAttributeModifiers(); - multimap.put(SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(), - new AttributeModifier(itemModifierUUID, "Weapon modifier", (double) this.attackDamage, 0)); - return multimap; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemTool.java b/src/game/java/net/minecraft/item/ItemTool.java index 4edf6eaf..a4cfd699 100644 --- a/src/game/java/net/minecraft/item/ItemTool.java +++ b/src/game/java/net/minecraft/item/ItemTool.java @@ -12,22 +12,25 @@ import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,61 +51,8 @@ public class ItemTool extends Item { this.setCreativeTab(CreativeTabs.tabTools); } - public float getStrVsBlock(ItemStack var1, Block block) { - return this.effectiveBlocks.contains(block) ? this.efficiencyOnProperMaterial : 1.0F; - } - - /**+ - * Current implementations of this method in child classes do - * not use the entry argument beside ev. They just raise the - * damage on the stack. - */ - public boolean hitEntity(ItemStack itemstack, EntityLivingBase var2, EntityLivingBase entitylivingbase) { - itemstack.damageItem(2, entitylivingbase); - return true; - } - - /**+ - * Called when a Block is destroyed using this Item. Return true - * to trigger the "Use Item" statistic. - */ - public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, BlockPos blockpos, - EntityLivingBase entitylivingbase) { - if ((double) block.getBlockHardness(world, blockpos) != 0.0D) { - itemstack.damageItem(1, entitylivingbase); - } - - return true; - } - - /**+ - * Returns True is the item is renderer in full 3D when hold. - */ - public boolean isFull3D() { - return true; - } - - public Item.ToolMaterial getToolMaterial() { - return this.toolMaterial; - } - - /**+ - * Return the enchantability factor of the item, most of the - * time is based on material. - */ - public int getItemEnchantability() { - return this.toolMaterial.getEnchantability(); - } - - /**+ - * Return the name for this tool's material. - */ - public String getToolMaterialName() { - return this.toolMaterial.toString(); - } - - /**+ - * Return whether this item is repairable in an anvil. + /** + * + Return whether this item is repairable in an anvil. */ public boolean getIsRepairable(ItemStack itemstack, ItemStack itemstack1) { return this.toolMaterial.getRepairItem() == itemstack1.getItem() ? true @@ -115,4 +65,56 @@ public class ItemTool extends Item { new AttributeModifier(itemModifierUUID, "Tool modifier", (double) this.damageVsEntity, 0)); return multimap; } + + /** + * + Return the enchantability factor of the item, most of the time is based on + * material. + */ + public int getItemEnchantability() { + return this.toolMaterial.getEnchantability(); + } + + public float getStrVsBlock(ItemStack var1, Block block) { + return this.effectiveBlocks.contains(block) ? this.efficiencyOnProperMaterial : 1.0F; + } + + public Item.ToolMaterial getToolMaterial() { + return this.toolMaterial; + } + + /** + * + Return the name for this tool's material. + */ + public String getToolMaterialName() { + return this.toolMaterial.toString(); + } + + /** + * + Current implementations of this method in child classes do not use the + * entry argument beside ev. They just raise the damage on the stack. + */ + public boolean hitEntity(ItemStack itemstack, EntityLivingBase var2, EntityLivingBase entitylivingbase) { + itemstack.damageItem(2, entitylivingbase); + return true; + } + + /** + * + Returns True is the item is renderer in full 3D when hold. + */ + public boolean isFull3D() { + return true; + } + + /** + * + Called when a Block is destroyed using this Item. Return true to trigger + * the "Use Item" statistic. + */ + public boolean onBlockDestroyed(ItemStack itemstack, World world, Block block, BlockPos blockpos, + EntityLivingBase entitylivingbase) { + if ((double) block.getBlockHardness(world, blockpos) != 0.0D) { + itemstack.damageItem(1, entitylivingbase); + } + + return true; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/ItemWritableBook.java b/src/game/java/net/minecraft/item/ItemWritableBook.java index 94f1975a..a97d3350 100644 --- a/src/game/java/net/minecraft/item/ItemWritableBook.java +++ b/src/game/java/net/minecraft/item/ItemWritableBook.java @@ -6,44 +6,32 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.stats.StatList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ItemWritableBook extends Item { - public ItemWritableBook() { - this.setMaxStackSize(1); - } - - /**+ - * Called whenever this item is equipped and the right mouse - * button is pressed. Args: itemStack, world, entityPlayer - */ - public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { - entityplayer.displayGUIBook(itemstack); - entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); - return itemstack; - } - - /**+ - * this method returns true if the book's NBT Tag List "pages" - * is valid + /** + * + this method returns true if the book's NBT Tag List "pages" is valid */ public static boolean isNBTValid(NBTTagCompound nbt) { if (nbt == null) { @@ -67,4 +55,18 @@ public class ItemWritableBook extends Item { return true; } } + + public ItemWritableBook() { + this.setMaxStackSize(1); + } + + /** + * + Called whenever this item is equipped and the right mouse button is + * pressed. Args: itemStack, world, entityPlayer + */ + public ItemStack onItemRightClick(ItemStack itemstack, World var2, EntityPlayer entityplayer) { + entityplayer.displayGUIBook(itemstack); + entityplayer.triggerAchievement(StatList.objectUseStats[Item.getIdFromItem(this)]); + return itemstack; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/CraftingManager.java b/src/game/java/net/minecraft/item/crafting/CraftingManager.java index 650c9a42..65815148 100644 --- a/src/game/java/net/minecraft/item/crafting/CraftingManager.java +++ b/src/game/java/net/minecraft/item/crafting/CraftingManager.java @@ -10,8 +10,15 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import net.minecraft.block.Block; +import net.minecraft.block.BlockDirt; import net.minecraft.block.BlockPlanks; +import net.minecraft.block.BlockPrismarine; +import net.minecraft.block.BlockQuartz; +import net.minecraft.block.BlockRedSandstone; +import net.minecraft.block.BlockSand; +import net.minecraft.block.BlockSandStone; import net.minecraft.block.BlockStone; +import net.minecraft.block.BlockStoneBrick; import net.minecraft.block.BlockStoneSlab; import net.minecraft.block.BlockStoneSlabNew; import net.minecraft.block.BlockWall; @@ -23,35 +30,34 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CraftingManager { private static CraftingManager instance; - /**+ - * A list of all the recipes added - */ - private final List recipes = Lists.newArrayList(); - /**+ - * Returns the static instance of this class + /** + * + Returns the static instance of this class */ public static CraftingManager getInstance() { if (instance == null) { @@ -60,6 +66,11 @@ public class CraftingManager { return instance; } + /** + * + A list of all the recipes added + */ + private final List recipes = Lists.newArrayList(); + private CraftingManager() { (new RecipesTools()).addRecipes(this); (new RecipesWeapons()).addRecipes(this); @@ -75,6 +86,87 @@ public class CraftingManager { this.recipes.add(new RecipeFireworks()); this.recipes.add(new RecipeRepairItem()); (new RecipesBanners()).addRecipes(this); + this.addRecipe(new ItemStack(Blocks.chest), + new Object[] { "###", "# #", "###", Character.valueOf('#'), Blocks.planks }); + this.addRecipe(new ItemStack(Blocks.trapped_chest), new Object[] { "#-", Character.valueOf('#'), Blocks.chest, + Character.valueOf('-'), Blocks.tripwire_hook }); + this.addRecipe(new ItemStack(Blocks.ender_chest), new Object[] { "###", "#E#", "###", Character.valueOf('#'), + Blocks.obsidian, Character.valueOf('E'), Items.ender_eye }); + this.addRecipe(new ItemStack(Blocks.furnace), + new Object[] { "###", "# #", "###", Character.valueOf('#'), Blocks.cobblestone }); + this.addRecipe(new ItemStack(Blocks.crafting_table), + new Object[] { "##", "##", Character.valueOf('#'), Blocks.planks }); + this.addRecipe(new ItemStack(Blocks.sandstone), new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.sand, 1, BlockSand.EnumType.SAND.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.red_sandstone), new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.sand, 1, BlockSand.EnumType.RED_SAND.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.sandstone, 4, BlockSandStone.EnumType.SMOOTH.getMetadata()), + new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.DEFAULT.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.red_sandstone, 4, BlockRedSandstone.EnumType.SMOOTH.getMetadata()), + new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.DEFAULT.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.CHISELED.getMetadata()), + new Object[] { "#", "#", Character.valueOf('#'), + new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SAND.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.CHISELED.getMetadata()), + new Object[] { "#", "#", Character.valueOf('#'), + new ItemStack(Blocks.stone_slab2, 1, BlockStoneSlabNew.EnumType.RED_SANDSTONE.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.CHISELED.getMetadata()), + new Object[] { "#", "#", Character.valueOf('#'), + new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.QUARTZ.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.quartz_block, 2, BlockQuartz.EnumType.LINES_Y.getMetadata()), + new Object[] { "#", "#", Character.valueOf('#'), + new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.DEFAULT.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.stonebrick, 4), new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.stone, 1, BlockStone.EnumType.STONE.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.CHISELED_META), + new Object[] { "#", "#", Character.valueOf('#'), + new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SMOOTHBRICK.getMetadata()) }); + this.addShapelessRecipe(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.MOSSY_META), + new Object[] { Blocks.stonebrick, Blocks.vine }); + this.addShapelessRecipe(new ItemStack(Blocks.mossy_cobblestone, 1), + new Object[] { Blocks.cobblestone, Blocks.vine }); + this.addRecipe(new ItemStack(Blocks.iron_bars, 16), + new Object[] { "###", "###", Character.valueOf('#'), Items.iron_ingot }); + this.addRecipe(new ItemStack(Blocks.glass_pane, 16), + new Object[] { "###", "###", Character.valueOf('#'), Blocks.glass }); + this.addRecipe(new ItemStack(Blocks.redstone_lamp, 1), new Object[] { " R ", "RGR", " R ", + Character.valueOf('R'), Items.redstone, Character.valueOf('G'), Blocks.glowstone }); + this.addRecipe(new ItemStack(Blocks.beacon, 1), new Object[] { "GGG", "GSG", "OOO", Character.valueOf('G'), + Blocks.glass, Character.valueOf('S'), Items.nether_star, Character.valueOf('O'), Blocks.obsidian }); + this.addRecipe(new ItemStack(Blocks.nether_brick, 1), + new Object[] { "NN", "NN", Character.valueOf('N'), Items.netherbrick }); + this.addRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.DIORITE.getMetadata()), new Object[] { "CQ", + "QC", Character.valueOf('C'), Blocks.cobblestone, Character.valueOf('Q'), Items.quartz }); + this.addShapelessRecipe(new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata()), + new Object[] { new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), + Items.quartz }); + this.addShapelessRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.ANDESITE.getMetadata()), + new Object[] { new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), + Blocks.cobblestone }); + this.addRecipe(new ItemStack(Blocks.dirt, 4, BlockDirt.DirtType.COARSE_DIRT.getMetadata()), + new Object[] { "DG", "GD", Character.valueOf('D'), + new ItemStack(Blocks.dirt, 1, BlockDirt.DirtType.DIRT.getMetadata()), Character.valueOf('G'), + Blocks.gravel }); + this.addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.DIORITE_SMOOTH.getMetadata()), + new Object[] { "SS", "SS", Character.valueOf('S'), + new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.GRANITE_SMOOTH.getMetadata()), + new Object[] { "SS", "SS", Character.valueOf('S'), + new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.ANDESITE_SMOOTH.getMetadata()), + new Object[] { "SS", "SS", Character.valueOf('S'), + new ItemStack(Blocks.stone, 1, BlockStone.EnumType.ANDESITE.getMetadata()) }); + this.addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.ROUGH_META), + new Object[] { "SS", "SS", Character.valueOf('S'), Items.prismarine_shard }); + this.addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.BRICKS_META), + new Object[] { "SSS", "SSS", "SSS", Character.valueOf('S'), Items.prismarine_shard }); + this.addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.DARK_META), + new Object[] { "SSS", "SIS", "SSS", Character.valueOf('S'), Items.prismarine_shard, + Character.valueOf('I'), new ItemStack(Items.dye, 1, EnumDyeColor.BLACK.getDyeDamage()) }); + this.addRecipe(new ItemStack(Blocks.sea_lantern, 1, 0), new Object[] { "SCS", "CCC", "SCS", + Character.valueOf('S'), Items.prismarine_shard, Character.valueOf('C'), Items.prismarine_crystals }); this.addRecipe(new ItemStack(Items.paper, 3), new Object[] { "###", Character.valueOf('#'), Items.reeds }); this.addShapelessRecipe(new ItemStack(Items.book, 1), new Object[] { Items.paper, Items.paper, Items.paper, Items.leather }); @@ -382,8 +474,15 @@ public class CraftingManager { }); } - /**+ - * Adds an IRecipe to the list of crafting recipes. + /** + * + Adds an IRecipe to the list of crafting recipes. + */ + public void addRecipe(IRecipe recipe) { + this.recipes.add(recipe); + } + + /** + * + Adds an IRecipe to the list of crafting recipes. */ public ShapedRecipes addRecipe(ItemStack stack, Object... recipeComponents) { String s = ""; @@ -439,8 +538,8 @@ public class CraftingManager { return shapedrecipes; } - /**+ - * Adds a shapeless crafting recipe to the the game. + /** + * + Adds a shapeless crafting recipe to the the game. */ public void addShapelessRecipe(ItemStack stack, Object... recipeComponents) { ArrayList arraylist = Lists.newArrayList(); @@ -464,15 +563,8 @@ public class CraftingManager { this.recipes.add(new ShapelessRecipes(stack, arraylist)); } - /**+ - * Adds an IRecipe to the list of crafting recipes. - */ - public void addRecipe(IRecipe recipe) { - this.recipes.add(recipe); - } - - /**+ - * Retrieves an ItemStack that has multiple recipes for it. + /** + * + Retrieves an ItemStack that has multiple recipes for it. */ public ItemStack findMatchingRecipe(InventoryCrafting worldIn, World parWorld) { for (int i = 0, l = this.recipes.size(); i < l; ++i) { @@ -502,8 +594,8 @@ public class CraftingManager { return aitemstack; } - /**+ - * returns the List<> of all recipes + /** + * + returns the List<> of all recipes */ public List getRecipeList() { return this.recipes; diff --git a/src/game/java/net/minecraft/item/crafting/FabricatorManager.java b/src/game/java/net/minecraft/item/crafting/FabricatorManager.java new file mode 100644 index 00000000..67b9aaa1 --- /dev/null +++ b/src/game/java/net/minecraft/item/crafting/FabricatorManager.java @@ -0,0 +1,202 @@ +package net.minecraft.item.crafting; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import net.minecraft.block.Block; +import net.minecraft.block.BlockStoneSlab; +import net.minecraft.init.Blocks; +import net.minecraft.init.Items; +import net.minecraft.inventory.InventoryCrafting; +import net.minecraft.item.Item; +import net.minecraft.item.ItemStack; +import net.minecraft.world.World; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. + * + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class FabricatorManager { + private static FabricatorManager instance; + + /** + * + Returns the static instance of this class + */ + public static FabricatorManager getInstance() { + if (instance == null) { + instance = new FabricatorManager(); + } + return instance; + } + + /** + * + A list of all the recipes added + */ + private final List recipes = Lists.newArrayList(); + + private FabricatorManager() { + this.addRecipe(new ItemStack(Items.steel, 1), + new Object[] { "///", " / ", "/_/", Character.valueOf('/'), Items.stick, Character.valueOf('_'), + new ItemStack(Blocks.stone, 1, BlockStoneSlab.EnumType.STONE.getMetadata()) }); + Collections.sort(this.recipes, new Comparator() { + public int compare(IRecipe parIRecipe, IRecipe parIRecipe2) { + return parIRecipe instanceof ShapelessRecipes && parIRecipe2 instanceof ShapedRecipes ? 1 + : (parIRecipe2 instanceof ShapelessRecipes && parIRecipe instanceof ShapedRecipes ? -1 + : (parIRecipe2.getRecipeSize() < parIRecipe.getRecipeSize() ? -1 + : (parIRecipe2.getRecipeSize() > parIRecipe.getRecipeSize() ? 1 : 0))); + } + }); + } + + /** + * + Adds an IRecipe to the list of crafting recipes. + */ + public void addRecipe(IRecipe recipe) { + this.recipes.add(recipe); + } + + /** + * + Adds an IRecipe to the list of crafting recipes. + */ + public ShapedRecipes addRecipe(ItemStack stack, Object... recipeComponents) { + String s = ""; + int i = 0; + int j = 0; + int k = 0; + if (recipeComponents[i] instanceof String[]) { + String[] astring = (String[]) ((String[]) recipeComponents[i++]); + + for (int l = 0; l < astring.length; ++l) { + String s2 = astring[l]; + ++k; + j = s2.length(); + s = s + s2; + } + } else { + while (recipeComponents[i] instanceof String) { + String s1 = (String) recipeComponents[i++]; + ++k; + j = s1.length(); + s = s + s1; + } + } + + HashMap hashmap; + for (hashmap = Maps.newHashMap(); i < recipeComponents.length; i += 2) { + Character character = (Character) recipeComponents[i]; + ItemStack itemstack = null; + if (recipeComponents[i + 1] instanceof Item) { + itemstack = new ItemStack((Item) recipeComponents[i + 1]); + } else if (recipeComponents[i + 1] instanceof Block) { + itemstack = new ItemStack((Block) recipeComponents[i + 1], 1, 32767); + } else if (recipeComponents[i + 1] instanceof ItemStack) { + itemstack = (ItemStack) recipeComponents[i + 1]; + } + + hashmap.put(character, itemstack); + } + + ItemStack[] aitemstack = new ItemStack[j * k]; + + for (int i1 = 0; i1 < j * k; ++i1) { + char c0 = s.charAt(i1); + if (hashmap.containsKey(Character.valueOf(c0))) { + aitemstack[i1] = ((ItemStack) hashmap.get(Character.valueOf(c0))).copy(); + } else { + aitemstack[i1] = null; + } + } + + ShapedRecipes shapedrecipes = new ShapedRecipes(j, k, aitemstack, stack); + this.recipes.add(shapedrecipes); + return shapedrecipes; + } + + /** + * + Adds a shapeless crafting recipe to the the game. + */ + public void addShapelessRecipe(ItemStack stack, Object... recipeComponents) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < recipeComponents.length; ++i) { + Object object = recipeComponents[i]; + if (object instanceof ItemStack) { + arraylist.add(((ItemStack) object).copy()); + } else if (object instanceof Item) { + arraylist.add(new ItemStack((Item) object)); + } else { + if (!(object instanceof Block)) { + throw new IllegalArgumentException( + "Invalid shapeless recipe: unknown type " + object.getClass().getName() + "!"); + } + + arraylist.add(new ItemStack((Block) object)); + } + } + + this.recipes.add(new ShapelessRecipes(stack, arraylist)); + } + + /** + * + Retrieves an ItemStack that has multiple recipes for it. + */ + public ItemStack findMatchingRecipe(InventoryCrafting worldIn, World parWorld) { + for (int i = 0, l = this.recipes.size(); i < l; ++i) { + IRecipe irecipe = this.recipes.get(i); + if (irecipe.matches(worldIn, parWorld)) { + return irecipe.getCraftingResult(worldIn); + } + } + + return null; + } + + public ItemStack[] func_180303_b(InventoryCrafting worldIn, World parWorld) { + for (int i = 0, l = this.recipes.size(); i < l; ++i) { + IRecipe irecipe = this.recipes.get(i); + if (irecipe.matches(worldIn, parWorld)) { + return irecipe.getRemainingItems(worldIn); + } + } + + ItemStack[] aitemstack = new ItemStack[worldIn.getSizeInventory()]; + + for (int i = 0; i < aitemstack.length; ++i) { + aitemstack[i] = worldIn.getStackInSlot(i); + } + + return aitemstack; + } + + /** + * + returns the List<> of all recipes + */ + public List getRecipeList() { + return this.recipes; + } +} \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/FurnaceRecipes.java b/src/game/java/net/minecraft/item/crafting/FurnaceRecipes.java index 57b9a025..07127d6a 100644 --- a/src/game/java/net/minecraft/item/crafting/FurnaceRecipes.java +++ b/src/game/java/net/minecraft/item/crafting/FurnaceRecipes.java @@ -14,33 +14,34 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemFishFood; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FurnaceRecipes { private static FurnaceRecipes smeltingBase; - private Map smeltingList = Maps.newHashMap(); - private Map experienceList = Maps.newHashMap(); - /**+ - * Returns an instance of FurnaceRecipes. + /** + * + Returns an instance of FurnaceRecipes. */ public static FurnaceRecipes instance() { if (smeltingBase == null) { @@ -49,6 +50,10 @@ public class FurnaceRecipes { return smeltingBase; } + private Map smeltingList = Maps.newHashMap(); + + private Map experienceList = Maps.newHashMap(); + private FurnaceRecipes() { this.addSmeltingRecipeForBlock(Blocks.iron_ore, new ItemStack(Items.iron_ingot), 0.7F); this.addSmeltingRecipeForBlock(Blocks.gold_ore, new ItemStack(Items.gold_ingot), 1.0F); @@ -72,7 +77,6 @@ public class FurnaceRecipes { this.addSmelting(Items.potato, new ItemStack(Items.baked_potato), 0.35F); this.addSmeltingRecipeForBlock(Blocks.netherrack, new ItemStack(Items.netherbrick), 0.1F); this.addSmeltingRecipe(new ItemStack(Blocks.sponge, 1, 1), new ItemStack(Blocks.sponge, 1, 0), 0.15F); - this.addSmeltingRecipeForBlock(Blocks.platinum_ore, new ItemStack(Items.platinum_ingot), 0.7F); ItemFishFood.FishType[] types = ItemFishFood.FishType.values(); for (int i = 0; i < types.length; ++i) { @@ -88,58 +92,44 @@ public class FurnaceRecipes { this.addSmeltingRecipeForBlock(Blocks.lapis_ore, new ItemStack(Items.dye, 1, EnumDyeColor.BLUE.getDyeDamage()), 0.2F); this.addSmeltingRecipeForBlock(Blocks.quartz_ore, new ItemStack(Items.quartz), 0.2F); + + this.addSmeltingRecipeForBlock(Blocks.cobbled_deepstone, new ItemStack(Blocks.deepstone), 0.1F); + this.addSmeltingRecipeForBlock(Blocks.platinum_ore, new ItemStack(Items.platinum_ingot), 1.5F); + this.addSmeltingRecipeForBlock(Blocks.titanium_ore, new ItemStack(Items.titanium_ingot), 2.0F); + this.addSmeltingRecipeForBlock(Blocks.uranium_ore, new ItemStack(Items.uranium_crystal), 0.2F); } - /**+ - * Adds a smelting recipe, where the input item is an instance - * of Block. - */ - public void addSmeltingRecipeForBlock(Block input, ItemStack stack, float experience) { - this.addSmelting(Item.getItemFromBlock(input), stack, experience); - } - - /**+ - * Adds a smelting recipe using an Item as the input item. + /** + * + Adds a smelting recipe using an Item as the input item. */ public void addSmelting(Item input, ItemStack stack, float experience) { this.addSmeltingRecipe(new ItemStack(input, 1, 32767), stack, experience); } - /**+ - * Adds a smelting recipe using an ItemStack as the input for - * the recipe. + /** + * + Adds a smelting recipe using an ItemStack as the input for the recipe. */ public void addSmeltingRecipe(ItemStack input, ItemStack stack, float experience) { this.smeltingList.put(input, stack); this.experienceList.put(stack, Float.valueOf(experience)); } - /**+ - * Returns the smelting result of an item. + /** + * + Adds a smelting recipe, where the input item is an instance of Block. */ - public ItemStack getSmeltingResult(ItemStack stack) { - for (Entry entry : this.smeltingList.entrySet()) { - if (this.compareItemStacks(stack, (ItemStack) entry.getKey())) { - return (ItemStack) entry.getValue(); - } - } - - return null; + public void addSmeltingRecipeForBlock(Block input, ItemStack stack, float experience) { + this.addSmelting(Item.getItemFromBlock(input), stack, experience); } - /**+ - * Compares two itemstacks to ensure that they are the same. - * This checks both the item and the metadata of the item. + /** + * + Compares two itemstacks to ensure that they are the same. This checks both + * the item and the metadata of the item. */ private boolean compareItemStacks(ItemStack stack1, ItemStack stack2) { return stack2.getItem() == stack1.getItem() && (stack2.getMetadata() == 32767 || stack2.getMetadata() == stack1.getMetadata()); } - public Map getSmeltingList() { - return this.smeltingList; - } - public float getSmeltingExperience(ItemStack stack) { for (Entry entry : this.experienceList.entrySet()) { if (this.compareItemStacks(stack, (ItemStack) entry.getKey())) { @@ -149,4 +139,21 @@ public class FurnaceRecipes { return 0.0F; } + + public Map getSmeltingList() { + return this.smeltingList; + } + + /** + * + Returns the smelting result of an item. + */ + public ItemStack getSmeltingResult(ItemStack stack) { + for (Entry entry : this.smeltingList.entrySet()) { + if (this.compareItemStacks(stack, (ItemStack) entry.getKey())) { + return (ItemStack) entry.getValue(); + } + } + + return null; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/IRecipe.java b/src/game/java/net/minecraft/item/crafting/IRecipe.java index 08a0eb9e..7730404d 100644 --- a/src/game/java/net/minecraft/item/crafting/IRecipe.java +++ b/src/game/java/net/minecraft/item/crafting/IRecipe.java @@ -4,43 +4,46 @@ import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IRecipe { - /**+ - * Used to check if a recipe matches current crafting inventory - */ - boolean matches(InventoryCrafting var1, World var2); - - /**+ - * Returns an Item that is the result of this recipe + /** + * + Returns an Item that is the result of this recipe */ ItemStack getCraftingResult(InventoryCrafting var1); - /**+ - * Returns the size of the recipe area + ItemStack getRecipeOutput(); + + /** + * + Returns the size of the recipe area */ int getRecipeSize(); - ItemStack getRecipeOutput(); - ItemStack[] getRemainingItems(InventoryCrafting var1); + + /** + * + Used to check if a recipe matches current crafting inventory + */ + boolean matches(InventoryCrafting var1, World var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipeBookCloning.java b/src/game/java/net/minecraft/item/crafting/RecipeBookCloning.java index e45ec868..667f4134 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipeBookCloning.java +++ b/src/game/java/net/minecraft/item/crafting/RecipeBookCloning.java @@ -7,58 +7,32 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipeBookCloning implements IRecipe { - /**+ - * Used to check if a recipe matches current crafting inventory - */ - public boolean matches(InventoryCrafting inventorycrafting, World var2) { - int i = 0; - ItemStack itemstack = null; - - for (int j = 0; j < inventorycrafting.getSizeInventory(); ++j) { - ItemStack itemstack1 = inventorycrafting.getStackInSlot(j); - if (itemstack1 != null) { - if (itemstack1.getItem() == Items.written_book) { - if (itemstack != null) { - return false; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.writable_book) { - return false; - } - - ++i; - } - } - } - - return itemstack != null && i > 0; - } - - /**+ - * Returns an Item that is the result of this recipe + /** + * + Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { int i = 0; @@ -97,17 +71,17 @@ public class RecipeBookCloning implements IRecipe { } } - /**+ - * Returns the size of the recipe area + public ItemStack getRecipeOutput() { + return null; + } + + /** + * + Returns the size of the recipe area */ public int getRecipeSize() { return 9; } - public ItemStack getRecipeOutput() { - return null; - } - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; @@ -121,4 +95,33 @@ public class RecipeBookCloning implements IRecipe { return aitemstack; } + + /** + * + Used to check if a recipe matches current crafting inventory + */ + public boolean matches(InventoryCrafting inventorycrafting, World var2) { + int i = 0; + ItemStack itemstack = null; + + for (int j = 0; j < inventorycrafting.getSizeInventory(); ++j) { + ItemStack itemstack1 = inventorycrafting.getStackInSlot(j); + if (itemstack1 != null) { + if (itemstack1.getItem() == Items.written_book) { + if (itemstack != null) { + return false; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.writable_book) { + return false; + } + + ++i; + } + } + } + + return itemstack != null && i > 0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipeFireworks.java b/src/game/java/net/minecraft/item/crafting/RecipeFireworks.java index 3b4be4f5..e675255b 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipeFireworks.java +++ b/src/game/java/net/minecraft/item/crafting/RecipeFireworks.java @@ -12,22 +12,25 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,8 +38,39 @@ import net.minecraft.world.World; public class RecipeFireworks implements IRecipe { private ItemStack field_92102_a; - /**+ - * Used to check if a recipe matches current crafting inventory + /** + * + Returns an Item that is the result of this recipe + */ + public ItemStack getCraftingResult(InventoryCrafting var1) { + return this.field_92102_a.copy(); + } + + public ItemStack getRecipeOutput() { + return this.field_92102_a; + } + + /** + * + Returns the size of the recipe area + */ + public int getRecipeSize() { + return 10; + } + + public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null && itemstack.getItem().hasContainerItem()) { + aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); + } + } + + return aitemstack; + } + + /** + * + Used to check if a recipe matches current crafting inventory */ public boolean matches(InventoryCrafting inventorycrafting, World var2) { this.field_92102_a = null; @@ -180,35 +214,4 @@ public class RecipeFireworks implements IRecipe { return false; } } - - /**+ - * Returns an Item that is the result of this recipe - */ - public ItemStack getCraftingResult(InventoryCrafting var1) { - return this.field_92102_a.copy(); - } - - /**+ - * Returns the size of the recipe area - */ - public int getRecipeSize() { - return 10; - } - - public ItemStack getRecipeOutput() { - return this.field_92102_a; - } - - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { - ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; - - for (int i = 0; i < aitemstack.length; ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null && itemstack.getItem().hasContainerItem()) { - aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); - } - } - - return aitemstack; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipeRepairItem.java b/src/game/java/net/minecraft/item/crafting/RecipeRepairItem.java index fb6001b1..c4555093 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipeRepairItem.java +++ b/src/game/java/net/minecraft/item/crafting/RecipeRepairItem.java @@ -9,52 +9,32 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipeRepairItem implements IRecipe { - /**+ - * Used to check if a recipe matches current crafting inventory - */ - public boolean matches(InventoryCrafting inventorycrafting, World var2) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null) { - arraylist.add(itemstack); - if (arraylist.size() > 1) { - ItemStack itemstack1 = (ItemStack) arraylist.get(0); - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.stackSize != 1 - || itemstack.stackSize != 1 || !itemstack1.getItem().isDamageable()) { - return false; - } - } - } - } - - return arraylist.size() == 2; - } - - /**+ - * Returns an Item that is the result of this recipe + /** + * + Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { ArrayList arraylist = Lists.newArrayList(); @@ -94,17 +74,17 @@ public class RecipeRepairItem implements IRecipe { return null; } - /**+ - * Returns the size of the recipe area + public ItemStack getRecipeOutput() { + return null; + } + + /** + * + Returns the size of the recipe area */ public int getRecipeSize() { return 4; } - public ItemStack getRecipeOutput() { - return null; - } - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; @@ -117,4 +97,27 @@ public class RecipeRepairItem implements IRecipe { return aitemstack; } + + /** + * + Used to check if a recipe matches current crafting inventory + */ + public boolean matches(InventoryCrafting inventorycrafting, World var2) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null) { + arraylist.add(itemstack); + if (arraylist.size() > 1) { + ItemStack itemstack1 = (ItemStack) arraylist.get(0); + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.stackSize != 1 + || itemstack.stackSize != 1 || !itemstack1.getItem().isDamageable()) { + return false; + } + } + } + } + + return arraylist.size() == 2; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipesArmor.java b/src/game/java/net/minecraft/item/crafting/RecipesArmor.java index fb38f04b..46d5840e 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesArmor.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesArmor.java @@ -4,22 +4,25 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,8 +36,8 @@ public class RecipesArmor { { Items.leather_leggings, Items.iron_leggings, Items.diamond_leggings, Items.golden_leggings }, { Items.leather_boots, Items.iron_boots, Items.diamond_boots, Items.golden_boots } }; - /**+ - * Adds the armor recipes to the CraftingManager. + /** + * + Adds the armor recipes to the CraftingManager. */ public void addRecipes(CraftingManager craftManager) { for (int i = 0; i < this.recipeItems[0].length; ++i) { diff --git a/src/game/java/net/minecraft/item/crafting/RecipesArmorDyes.java b/src/game/java/net/minecraft/item/crafting/RecipesArmorDyes.java index 86ea33e9..20525c84 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesArmorDyes.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesArmorDyes.java @@ -12,59 +12,32 @@ import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipesArmorDyes implements IRecipe { - /**+ - * Used to check if a recipe matches current crafting inventory - */ - public boolean matches(InventoryCrafting inv, World worldIn) { - ItemStack itemstack = null; - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < inv.getSizeInventory(); ++i) { - ItemStack itemstack1 = inv.getStackInSlot(i); - if (itemstack1 != null) { - if (itemstack1.getItem() instanceof ItemArmor) { - ItemArmor itemarmor = (ItemArmor) itemstack1.getItem(); - if (itemarmor.getArmorMaterial() != ItemArmor.ArmorMaterial.LEATHER || itemstack != null) { - return false; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.dye) { - return false; - } - - arraylist.add(itemstack1); - } - } - } - - return itemstack != null && !arraylist.isEmpty(); - } - - /**+ - * Returns an Item that is the result of this recipe + /** + * + Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting inv) { ItemStack itemstack = null; @@ -131,17 +104,17 @@ public class RecipesArmorDyes implements IRecipe { } } - /**+ - * Returns the size of the recipe area + public ItemStack getRecipeOutput() { + return null; + } + + /** + * + Returns the size of the recipe area */ public int getRecipeSize() { return 10; } - public ItemStack getRecipeOutput() { - return null; - } - public ItemStack[] getRemainingItems(InventoryCrafting inv) { ItemStack[] aitemstack = new ItemStack[inv.getSizeInventory()]; @@ -154,4 +127,34 @@ public class RecipesArmorDyes implements IRecipe { return aitemstack; } + + /** + * + Used to check if a recipe matches current crafting inventory + */ + public boolean matches(InventoryCrafting inv, World worldIn) { + ItemStack itemstack = null; + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < inv.getSizeInventory(); ++i) { + ItemStack itemstack1 = inv.getStackInSlot(i); + if (itemstack1 != null) { + if (itemstack1.getItem() instanceof ItemArmor) { + ItemArmor itemarmor = (ItemArmor) itemstack1.getItem(); + if (itemarmor.getArmorMaterial() != ItemArmor.ArmorMaterial.LEATHER || itemstack != null) { + return false; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.dye) { + return false; + } + + arraylist.add(itemstack1); + } + } + } + + return itemstack != null && !arraylist.isEmpty(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipesBanners.java b/src/game/java/net/minecraft/item/crafting/RecipesBanners.java index 5d56085b..b9cbfca8 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesBanners.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesBanners.java @@ -10,137 +10,34 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntityBanner; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipesBanners { - /**+ - * Adds the banner recipes to the CraftingManager. - */ - void addRecipes(CraftingManager parCraftingManager) { - EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP; - for (int i = 0; i < colors.length; ++i) { - EnumDyeColor enumdyecolor = colors[i]; - parCraftingManager.addRecipe(new ItemStack(Items.banner, 1, enumdyecolor.getDyeDamage()), - new Object[] { "###", "###", " | ", Character.valueOf('#'), - new ItemStack(Blocks.wool, 1, enumdyecolor.getMetadata()), Character.valueOf('|'), - Items.stick }); - } - - parCraftingManager.addRecipe(new RecipesBanners.RecipeDuplicatePattern()); - parCraftingManager.addRecipe(new RecipesBanners.RecipeAddPattern()); - } - static class RecipeAddPattern implements IRecipe { private RecipeAddPattern() { } - public boolean matches(InventoryCrafting inventorycrafting, World var2) { - boolean flag = false; - - for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null && itemstack.getItem() == Items.banner) { - if (flag) { - return false; - } - - if (TileEntityBanner.getPatterns(itemstack) >= 6) { - return false; - } - - flag = true; - } - } - - if (!flag) { - return false; - } else { - return this.func_179533_c(inventorycrafting) != null; - } - } - - public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { - ItemStack itemstack = null; - - for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { - ItemStack itemstack1 = inventorycrafting.getStackInSlot(i); - if (itemstack1 != null && itemstack1.getItem() == Items.banner) { - itemstack = itemstack1.copy(); - itemstack.stackSize = 1; - break; - } - } - - TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = this - .func_179533_c(inventorycrafting); - if (tileentitybanner$enumbannerpattern != null) { - int k = 0; - - for (int j = 0; j < inventorycrafting.getSizeInventory(); ++j) { - ItemStack itemstack2 = inventorycrafting.getStackInSlot(j); - if (itemstack2 != null && itemstack2.getItem() == Items.dye) { - k = itemstack2.getMetadata(); - break; - } - } - - NBTTagCompound nbttagcompound1 = itemstack.getSubCompound("BlockEntityTag", true); - NBTTagList nbttaglist = null; - if (nbttagcompound1.hasKey("Patterns", 9)) { - nbttaglist = nbttagcompound1.getTagList("Patterns", 10); - } else { - nbttaglist = new NBTTagList(); - nbttagcompound1.setTag("Patterns", nbttaglist); - } - - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("Pattern", tileentitybanner$enumbannerpattern.getPatternID()); - nbttagcompound.setInteger("Color", k); - nbttaglist.appendTag(nbttagcompound); - } - - return itemstack; - } - - public int getRecipeSize() { - return 10; - } - - public ItemStack getRecipeOutput() { - return null; - } - - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { - ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; - - for (int i = 0; i < aitemstack.length; ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null && itemstack.getItem().hasContainerItem()) { - aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); - } - } - - return aitemstack; - } - private TileEntityBanner.EnumBannerPattern func_179533_c(InventoryCrafting parInventoryCrafting) { TileEntityBanner.EnumBannerPattern[] patterns = TileEntityBanner.EnumBannerPattern._VALUES; for (int m = 0; m < patterns.length; ++m) { @@ -219,12 +116,140 @@ public class RecipesBanners { return null; } + + public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { + ItemStack itemstack = null; + + for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { + ItemStack itemstack1 = inventorycrafting.getStackInSlot(i); + if (itemstack1 != null && itemstack1.getItem() == Items.banner) { + itemstack = itemstack1.copy(); + itemstack.stackSize = 1; + break; + } + } + + TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = this + .func_179533_c(inventorycrafting); + if (tileentitybanner$enumbannerpattern != null) { + int k = 0; + + for (int j = 0; j < inventorycrafting.getSizeInventory(); ++j) { + ItemStack itemstack2 = inventorycrafting.getStackInSlot(j); + if (itemstack2 != null && itemstack2.getItem() == Items.dye) { + k = itemstack2.getMetadata(); + break; + } + } + + NBTTagCompound nbttagcompound1 = itemstack.getSubCompound("BlockEntityTag", true); + NBTTagList nbttaglist = null; + if (nbttagcompound1.hasKey("Patterns", 9)) { + nbttaglist = nbttagcompound1.getTagList("Patterns", 10); + } else { + nbttaglist = new NBTTagList(); + nbttagcompound1.setTag("Patterns", nbttaglist); + } + + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("Pattern", tileentitybanner$enumbannerpattern.getPatternID()); + nbttagcompound.setInteger("Color", k); + nbttaglist.appendTag(nbttagcompound); + } + + return itemstack; + } + + public ItemStack getRecipeOutput() { + return null; + } + + public int getRecipeSize() { + return 10; + } + + public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null && itemstack.getItem().hasContainerItem()) { + aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); + } + } + + return aitemstack; + } + + public boolean matches(InventoryCrafting inventorycrafting, World var2) { + boolean flag = false; + + for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null && itemstack.getItem() == Items.banner) { + if (flag) { + return false; + } + + if (TileEntityBanner.getPatterns(itemstack) >= 6) { + return false; + } + + flag = true; + } + } + + if (!flag) { + return false; + } else { + return this.func_179533_c(inventorycrafting) != null; + } + } } static class RecipeDuplicatePattern implements IRecipe { private RecipeDuplicatePattern() { } + public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { + for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null && TileEntityBanner.getPatterns(itemstack) > 0) { + ItemStack itemstack1 = itemstack.copy(); + itemstack1.stackSize = 1; + return itemstack1; + } + } + + return null; + } + + public ItemStack getRecipeOutput() { + return null; + } + + public int getRecipeSize() { + return 2; + } + + public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null) { + if (itemstack.getItem().hasContainerItem()) { + aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); + } else if (itemstack.hasTagCompound() && TileEntityBanner.getPatterns(itemstack) > 0) { + aitemstack[i] = itemstack.copy(); + aitemstack[i].stackSize = 1; + } + } + } + + return aitemstack; + } + public boolean matches(InventoryCrafting inventorycrafting, World var2) { ItemStack itemstack = null; ItemStack itemstack1 = null; @@ -272,44 +297,22 @@ public class RecipesBanners { return itemstack != null && itemstack1 != null; } + } - public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { - for (int i = 0; i < inventorycrafting.getSizeInventory(); ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null && TileEntityBanner.getPatterns(itemstack) > 0) { - ItemStack itemstack1 = itemstack.copy(); - itemstack1.stackSize = 1; - return itemstack1; - } - } - - return null; + /** + * + Adds the banner recipes to the CraftingManager. + */ + void addRecipes(CraftingManager parCraftingManager) { + EnumDyeColor[] colors = EnumDyeColor.META_LOOKUP; + for (int i = 0; i < colors.length; ++i) { + EnumDyeColor enumdyecolor = colors[i]; + parCraftingManager.addRecipe(new ItemStack(Items.banner, 1, enumdyecolor.getDyeDamage()), + new Object[] { "###", "###", " | ", Character.valueOf('#'), + new ItemStack(Blocks.wool, 1, enumdyecolor.getMetadata()), Character.valueOf('|'), + Items.stick }); } - public int getRecipeSize() { - return 2; - } - - public ItemStack getRecipeOutput() { - return null; - } - - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { - ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; - - for (int i = 0; i < aitemstack.length; ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null) { - if (itemstack.getItem().hasContainerItem()) { - aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); - } else if (itemstack.hasTagCompound() && TileEntityBanner.getPatterns(itemstack) > 0) { - aitemstack[i] = itemstack.copy(); - aitemstack[i].stackSize = 1; - } - } - } - - return aitemstack; - } + parCraftingManager.addRecipe(new RecipesBanners.RecipeDuplicatePattern()); + parCraftingManager.addRecipe(new RecipesBanners.RecipeAddPattern()); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipesCrafting.java b/src/game/java/net/minecraft/item/crafting/RecipesCrafting.java index f2e81c63..4bd611c1 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesCrafting.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesCrafting.java @@ -1,150 +1,89 @@ package net.minecraft.item.crafting; -import net.minecraft.block.BlockDirt; -import net.minecraft.block.BlockPrismarine; -import net.minecraft.block.BlockQuartz; -import net.minecraft.block.BlockRedSandstone; -import net.minecraft.block.BlockSand; -import net.minecraft.block.BlockSandStone; -import net.minecraft.block.BlockStone; -import net.minecraft.block.BlockStoneBrick; -import net.minecraft.block.BlockStoneSlab; -import net.minecraft.block.BlockStoneSlabNew; +import net.minecraft.block.BlockMosaic; +import net.minecraft.block.BlockPlanks; import net.minecraft.init.Blocks; import net.minecraft.init.Items; -import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipesCrafting { - /**+ - * Adds the crafting recipes to the CraftingManager. + /** + * + Adds the crafting recipes to the CraftingManager. */ public void addRecipes(CraftingManager parCraftingManager) { - parCraftingManager.addRecipe(new ItemStack(Blocks.chest), - new Object[] { "###", "# #", "###", Character.valueOf('#'), Blocks.planks }); - parCraftingManager.addRecipe(new ItemStack(Blocks.trapped_chest), new Object[] { "#-", Character.valueOf('#'), - Blocks.chest, Character.valueOf('-'), Blocks.tripwire_hook }); - parCraftingManager.addRecipe(new ItemStack(Blocks.ender_chest), new Object[] { "###", "#E#", "###", - Character.valueOf('#'), Blocks.obsidian, Character.valueOf('E'), Items.ender_eye }); - parCraftingManager.addRecipe(new ItemStack(Blocks.furnace), - new Object[] { "###", "# #", "###", Character.valueOf('#'), Blocks.cobblestone }); - parCraftingManager.addRecipe(new ItemStack(Blocks.crafting_table), - new Object[] { "##", "##", Character.valueOf('#'), Blocks.planks }); - parCraftingManager.addRecipe(new ItemStack(Blocks.sandstone), new Object[] { "##", "##", Character.valueOf('#'), - new ItemStack(Blocks.sand, 1, BlockSand.EnumType.SAND.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.red_sandstone), new Object[] { "##", "##", - Character.valueOf('#'), new ItemStack(Blocks.sand, 1, BlockSand.EnumType.RED_SAND.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.sandstone, 4, BlockSandStone.EnumType.SMOOTH.getMetadata()), + parCraftingManager.addRecipe(new ItemStack(Items.steel, 1), new Object[] { "III", "ICI", "III", + Character.valueOf('I'), Items.iron_ingot, Character.valueOf('C'), Items.coal }); + parCraftingManager.addRecipe(new ItemStack(Blocks.steel_grate, 4), + new Object[] { "SSS", "S S", "SSS", Character.valueOf('S'), Items.steel }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_sword, 1), new Object[] { "P", "P", "B", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_pickaxe, 1), new Object[] { "PPP", " B ", " B ", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_shovel, 1), new Object[] { "P", "B", "B", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_axe, 1), new Object[] { "PP ", "PB ", " B ", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_axe, 1), new Object[] { " PP", " BP", " B ", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_hoe, 1), new Object[] { "PP ", " B ", " B ", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_hoe, 1), new Object[] { " PP", " B ", " B ", + Character.valueOf('P'), Items.platinum_ingot, Character.valueOf('B'), Items.blaze_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_helmet, 1), + new Object[] { "PPP", "P P", Character.valueOf('P'), Items.platinum_ingot }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_chestplate, 1), + new Object[] { "P P", "PPP", "PPP", Character.valueOf('P'), Items.platinum_ingot }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_leggings, 1), + new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), Items.platinum_ingot }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_boots, 1), + new Object[] { "P P", "P P", Character.valueOf('P'), Items.platinum_ingot }); + parCraftingManager.addRecipe(new ItemStack(Items.uranium_rod, 1), + new Object[] { "U", "U", "U", Character.valueOf('U'), Items.uranium_crystal, }); + parCraftingManager.addRecipe(new ItemStack(Items.platinum_drill, 1), + new Object[] { " PP", "SUP", "SS ", Character.valueOf('P'), Items.platinum_ingot, + Character.valueOf('S'), Items.steel, Character.valueOf('U'), Items.uranium_rod }); + parCraftingManager.addRecipe(new ItemStack(Items.titanium_drill, 1), new Object[] { "TTT", "TDT", "TTT", + Character.valueOf('T'), Items.titanium_ingot, Character.valueOf('D'), Items.platinum_drill }); + parCraftingManager.addRecipe(new ItemStack(Blocks.mosaic, 4, BlockMosaic.EnumType.OAK.getMetadata()), new Object[] { "##", "##", Character.valueOf('#'), - new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.DEFAULT.getMetadata()) }); - parCraftingManager.addRecipe( - new ItemStack(Blocks.red_sandstone, 4, BlockRedSandstone.EnumType.SMOOTH.getMetadata()), + new ItemStack(Blocks.planks, 1, BlockPlanks.EnumType.OAK.getMetadata()) }); + parCraftingManager.addRecipe(new ItemStack(Blocks.mosaic, 4, BlockMosaic.EnumType.SPRUCE.getMetadata()), new Object[] { "##", "##", Character.valueOf('#'), - new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.DEFAULT.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.CHISELED.getMetadata()), - new Object[] { "#", "#", Character.valueOf('#'), - new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SAND.getMetadata()) }); - parCraftingManager.addRecipe( - new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.CHISELED.getMetadata()), - new Object[] { "#", "#", Character.valueOf('#'), - new ItemStack(Blocks.stone_slab2, 1, BlockStoneSlabNew.EnumType.RED_SANDSTONE.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.CHISELED.getMetadata()), - new Object[] { "#", "#", Character.valueOf('#'), - new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.QUARTZ.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.quartz_block, 2, BlockQuartz.EnumType.LINES_Y.getMetadata()), - new Object[] { "#", "#", Character.valueOf('#'), - new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.DEFAULT.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.stonebrick, 4), new Object[] { "##", "##", - Character.valueOf('#'), new ItemStack(Blocks.stone, 1, BlockStone.EnumType.STONE.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.CHISELED_META), - new Object[] { "#", "#", Character.valueOf('#'), - new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SMOOTHBRICK.getMetadata()) }); - parCraftingManager.addShapelessRecipe(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.MOSSY_META), - new Object[] { Blocks.stonebrick, Blocks.vine }); - parCraftingManager.addShapelessRecipe(new ItemStack(Blocks.mossy_cobblestone, 1), - new Object[] { Blocks.cobblestone, Blocks.vine }); - parCraftingManager.addRecipe(new ItemStack(Blocks.iron_bars, 16), - new Object[] { "###", "###", Character.valueOf('#'), Items.iron_ingot }); - parCraftingManager.addRecipe(new ItemStack(Blocks.glass_pane, 16), - new Object[] { "###", "###", Character.valueOf('#'), Blocks.glass }); - parCraftingManager.addRecipe(new ItemStack(Blocks.redstone_lamp, 1), new Object[] { " R ", "RGR", " R ", - Character.valueOf('R'), Items.redstone, Character.valueOf('G'), Blocks.glowstone }); - parCraftingManager.addRecipe(new ItemStack(Blocks.beacon, 1), - new Object[] { "GGG", "GSG", "OOO", Character.valueOf('G'), Blocks.glass, Character.valueOf('S'), - Items.nether_star, Character.valueOf('O'), Blocks.obsidian }); - parCraftingManager.addRecipe(new ItemStack(Blocks.nether_brick, 1), - new Object[] { "NN", "NN", Character.valueOf('N'), Items.netherbrick }); - parCraftingManager.addRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.DIORITE.getMetadata()), - new Object[] { "CQ", "QC", Character.valueOf('C'), Blocks.cobblestone, Character.valueOf('Q'), - Items.quartz }); - parCraftingManager.addShapelessRecipe(new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata()), - new Object[] { new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), - Items.quartz }); - parCraftingManager.addShapelessRecipe( - new ItemStack(Blocks.stone, 2, BlockStone.EnumType.ANDESITE.getMetadata()), - new Object[] { new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), - Blocks.cobblestone }); - parCraftingManager.addRecipe(new ItemStack(Blocks.dirt, 4, BlockDirt.DirtType.COARSE_DIRT.getMetadata()), - new Object[] { "DG", "GD", Character.valueOf('D'), - new ItemStack(Blocks.dirt, 1, BlockDirt.DirtType.DIRT.getMetadata()), Character.valueOf('G'), - Blocks.gravel }); - parCraftingManager.addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.DIORITE_SMOOTH.getMetadata()), - new Object[] { "SS", "SS", Character.valueOf('S'), - new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.GRANITE_SMOOTH.getMetadata()), - new Object[] { "SS", "SS", Character.valueOf('S'), - new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.ANDESITE_SMOOTH.getMetadata()), - new Object[] { "SS", "SS", Character.valueOf('S'), - new ItemStack(Blocks.stone, 1, BlockStone.EnumType.ANDESITE.getMetadata()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.ROUGH_META), - new Object[] { "SS", "SS", Character.valueOf('S'), Items.prismarine_shard }); - parCraftingManager.addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.BRICKS_META), - new Object[] { "SSS", "SSS", "SSS", Character.valueOf('S'), Items.prismarine_shard }); - parCraftingManager.addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.DARK_META), - new Object[] { "SSS", "SIS", "SSS", Character.valueOf('S'), Items.prismarine_shard, - Character.valueOf('I'), new ItemStack(Items.dye, 1, EnumDyeColor.BLACK.getDyeDamage()) }); - parCraftingManager.addRecipe(new ItemStack(Blocks.sea_lantern, 1, 0), new Object[] { "SCS", "CCC", "SCS", - Character.valueOf('S'), Items.prismarine_shard, Character.valueOf('C'), Items.prismarine_crystals }); - parCraftingManager.addRecipe(new ItemStack(Blocks.iron_grate, 16, 0), new Object[] { - "SSS", - "S S", - "SSS", - Character.valueOf('S'), Items.iron_ingot - }); - parCraftingManager.addRecipe(new ItemStack(Items.platinum_sword, 1), new Object[] { - " P ", - " P ", - " B ", - Character.valueOf('P'), Items.platinum_ingot, - Character.valueOf('B'), Items.blaze_rod - }); - parCraftingManager.addRecipe(new ItemStack(Items.platinum_pickaxe, 1), new Object[] { - "PPP", - " B ", - " B ", - Character.valueOf('P'), Items.platinum_ingot, - Character.valueOf('B'), Items.blaze_rod - }); + new ItemStack(Blocks.planks, 1, BlockPlanks.EnumType.SPRUCE.getMetadata()) }); + parCraftingManager.addRecipe(new ItemStack(Blocks.mosaic, 4, BlockMosaic.EnumType.BIRCH.getMetadata()), + new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.planks, 1, BlockPlanks.EnumType.BIRCH.getMetadata()) }); + parCraftingManager.addRecipe(new ItemStack(Blocks.mosaic, 4, BlockMosaic.EnumType.JUNGLE.getMetadata()), + new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.planks, 1, BlockPlanks.EnumType.JUNGLE.getMetadata()) }); + parCraftingManager.addRecipe(new ItemStack(Blocks.mosaic, 4, BlockMosaic.EnumType.ACACIA.getMetadata()), + new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.planks, 1, BlockPlanks.EnumType.ACACIA.getMetadata()) }); + parCraftingManager.addRecipe(new ItemStack(Blocks.mosaic, 4, BlockMosaic.EnumType.DARK_OAK.getMetadata()), + new Object[] { "##", "##", Character.valueOf('#'), + new ItemStack(Blocks.planks, 1, BlockPlanks.EnumType.DARK_OAK.getMetadata()) }); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipesDyes.java b/src/game/java/net/minecraft/item/crafting/RecipesDyes.java index de6a670b..276817ed 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesDyes.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesDyes.java @@ -8,29 +8,32 @@ import net.minecraft.item.EnumDyeColor; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipesDyes { - /**+ - * Adds the dye recipes to the CraftingManager. + /** + * + Adds the dye recipes to the CraftingManager. */ public void addRecipes(CraftingManager parCraftingManager) { for (int i = 0; i < 16; ++i) { diff --git a/src/game/java/net/minecraft/item/crafting/RecipesFood.java b/src/game/java/net/minecraft/item/crafting/RecipesFood.java index ac3c90fd..9fe35e8d 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesFood.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesFood.java @@ -5,29 +5,32 @@ import net.minecraft.init.Items; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipesFood { - /**+ - * Adds the food recipes to the CraftingManager. + /** + * + Adds the food recipes to the CraftingManager. */ public void addRecipes(CraftingManager parCraftingManager) { parCraftingManager.addShapelessRecipe(new ItemStack(Items.mushroom_stew), diff --git a/src/game/java/net/minecraft/item/crafting/RecipesIngots.java b/src/game/java/net/minecraft/item/crafting/RecipesIngots.java index c8cbc712..98349b4c 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesIngots.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesIngots.java @@ -6,22 +6,25 @@ import net.minecraft.init.Items; import net.minecraft.item.EnumDyeColor; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,8 +32,8 @@ import net.minecraft.item.ItemStack; public class RecipesIngots { private Object[][] recipeItems; - /**+ - * Adds the ingot recipes to the CraftingManager. + /** + * + Adds the ingot recipes to the CraftingManager. */ public void addRecipes(CraftingManager parCraftingManager) { recipeItems = new Object[][] { { Blocks.gold_block, new ItemStack(Items.gold_ingot, 9) }, @@ -42,7 +45,10 @@ public class RecipesIngots { { Blocks.coal_block, new ItemStack(Items.coal, 9, 0) }, { Blocks.hay_block, new ItemStack(Items.wheat, 9) }, { Blocks.slime_block, new ItemStack(Items.slime_ball, 9) }, - { Blocks.platinum_block, new ItemStack(Items.platinum_ingot, 9) } }; + { Blocks.platinum_block, new ItemStack(Items.platinum_ingot, 9) }, + { Blocks.titanium_block, new ItemStack(Items.titanium_ingot, 9) }, + { Blocks.uranium_block, new ItemStack(Items.uranium_crystal, 9) }, + { Blocks.steel_block, new ItemStack(Items.steel, 9) } }; for (int i = 0; i < this.recipeItems.length; ++i) { Block block = (Block) this.recipeItems[i][0]; ItemStack itemstack = (ItemStack) this.recipeItems[i][1]; diff --git a/src/game/java/net/minecraft/item/crafting/RecipesMapCloning.java b/src/game/java/net/minecraft/item/crafting/RecipesMapCloning.java index e8790048..1aedf63b 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesMapCloning.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesMapCloning.java @@ -5,58 +5,32 @@ import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RecipesMapCloning implements IRecipe { - /**+ - * Used to check if a recipe matches current crafting inventory - */ - public boolean matches(InventoryCrafting inventorycrafting, World var2) { - int i = 0; - ItemStack itemstack = null; - - for (int j = 0; j < inventorycrafting.getSizeInventory(); ++j) { - ItemStack itemstack1 = inventorycrafting.getStackInSlot(j); - if (itemstack1 != null) { - if (itemstack1.getItem() == Items.filled_map) { - if (itemstack != null) { - return false; - } - - itemstack = itemstack1; - } else { - if (itemstack1.getItem() != Items.map) { - return false; - } - - ++i; - } - } - } - - return itemstack != null && i > 0; - } - - /**+ - * Returns an Item that is the result of this recipe + /** + * + Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { int i = 0; @@ -93,17 +67,17 @@ public class RecipesMapCloning implements IRecipe { } } - /**+ - * Returns the size of the recipe area + public ItemStack getRecipeOutput() { + return null; + } + + /** + * + Returns the size of the recipe area */ public int getRecipeSize() { return 9; } - public ItemStack getRecipeOutput() { - return null; - } - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; @@ -116,4 +90,33 @@ public class RecipesMapCloning implements IRecipe { return aitemstack; } + + /** + * + Used to check if a recipe matches current crafting inventory + */ + public boolean matches(InventoryCrafting inventorycrafting, World var2) { + int i = 0; + ItemStack itemstack = null; + + for (int j = 0; j < inventorycrafting.getSizeInventory(); ++j) { + ItemStack itemstack1 = inventorycrafting.getStackInSlot(j); + if (itemstack1 != null) { + if (itemstack1.getItem() == Items.filled_map) { + if (itemstack != null) { + return false; + } + + itemstack = itemstack1; + } else { + if (itemstack1.getItem() != Items.map) { + return false; + } + + ++i; + } + } + } + + return itemstack != null && i > 0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipesMapExtending.java b/src/game/java/net/minecraft/item/crafting/RecipesMapExtending.java index 9986fd46..1fc0fc18 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesMapExtending.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesMapExtending.java @@ -7,22 +7,25 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,8 +40,31 @@ public class RecipesMapExtending extends ShapedRecipes { new ItemStack(Items.map, 0, 0)); } - /**+ - * Used to check if a recipe matches current crafting inventory + /** + * + Returns an Item that is the result of this recipe + */ + public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { + ItemStack itemstack = null; + + for (int i = 0; i < inventorycrafting.getSizeInventory() && itemstack == null; ++i) { + ItemStack itemstack1 = inventorycrafting.getStackInSlot(i); + if (itemstack1 != null && itemstack1.getItem() == Items.filled_map) { + itemstack = itemstack1; + } + } + + itemstack = itemstack.copy(); + itemstack.stackSize = 1; + if (itemstack.getTagCompound() == null) { + itemstack.setTagCompound(new NBTTagCompound()); + } + + itemstack.getTagCompound().setBoolean("map_is_scaling", true); + return itemstack; + } + + /** + * + Used to check if a recipe matches current crafting inventory */ public boolean matches(InventoryCrafting inventorycrafting, World world) { if (!super.matches(inventorycrafting, world)) { @@ -61,27 +87,4 @@ public class RecipesMapExtending extends ShapedRecipes { } } } - - /**+ - * Returns an Item that is the result of this recipe - */ - public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { - ItemStack itemstack = null; - - for (int i = 0; i < inventorycrafting.getSizeInventory() && itemstack == null; ++i) { - ItemStack itemstack1 = inventorycrafting.getStackInSlot(i); - if (itemstack1 != null && itemstack1.getItem() == Items.filled_map) { - itemstack = itemstack1; - } - } - - itemstack = itemstack.copy(); - itemstack.stackSize = 1; - if (itemstack.getTagCompound() == null) { - itemstack.setTagCompound(new NBTTagCompound()); - } - - itemstack.getTagCompound().setBoolean("map_is_scaling", true); - return itemstack; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/RecipesTools.java b/src/game/java/net/minecraft/item/crafting/RecipesTools.java index b1cb2f3d..3a5c6a1e 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesTools.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesTools.java @@ -5,22 +5,25 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,8 +33,8 @@ public class RecipesTools { { "XX", "X#", " #" }, { "XX", " #", " #" } }; private Object[][] recipeItems; - /**+ - * Adds the tool recipes to the CraftingManager. + /** + * + Adds the tool recipes to the CraftingManager. */ public void addRecipes(CraftingManager parCraftingManager) { recipeItems = new Object[][] { diff --git a/src/game/java/net/minecraft/item/crafting/RecipesWeapons.java b/src/game/java/net/minecraft/item/crafting/RecipesWeapons.java index f2075e06..2938b32a 100644 --- a/src/game/java/net/minecraft/item/crafting/RecipesWeapons.java +++ b/src/game/java/net/minecraft/item/crafting/RecipesWeapons.java @@ -5,22 +5,25 @@ import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,8 +32,8 @@ public class RecipesWeapons { private String[][] recipePatterns = new String[][] { { "X", "X", "#" } }; private Object[][] recipeItems; - /**+ - * Adds the weapon recipes to the CraftingManager. + /** + * + Adds the weapon recipes to the CraftingManager. */ public void addRecipes(CraftingManager parCraftingManager) { recipeItems = new Object[][] { diff --git a/src/game/java/net/minecraft/item/crafting/ShapedRecipes.java b/src/game/java/net/minecraft/item/crafting/ShapedRecipes.java index 940ff9af..3f1bb570 100644 --- a/src/game/java/net/minecraft/item/crafting/ShapedRecipes.java +++ b/src/game/java/net/minecraft/item/crafting/ShapedRecipes.java @@ -5,22 +5,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,45 +42,8 @@ public class ShapedRecipes implements IRecipe { this.recipeOutput = output; } - public ItemStack getRecipeOutput() { - return this.recipeOutput; - } - - public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { - ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; - - for (int i = 0; i < aitemstack.length; ++i) { - ItemStack itemstack = inventorycrafting.getStackInSlot(i); - if (itemstack != null && itemstack.getItem().hasContainerItem()) { - aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); - } - } - - return aitemstack; - } - - /**+ - * Used to check if a recipe matches current crafting inventory - */ - public boolean matches(InventoryCrafting inventorycrafting, World var2) { - for (int i = 0; i <= 3 - this.recipeWidth; ++i) { - for (int j = 0; j <= 3 - this.recipeHeight; ++j) { - if (this.checkMatch(inventorycrafting, i, j, true)) { - return true; - } - - if (this.checkMatch(inventorycrafting, i, j, false)) { - return true; - } - } - } - - return false; - } - - /**+ - * Checks if the region of a crafting inventory is match for the - * recipe. + /** + * + Checks if the region of a crafting inventory is match for the recipe. */ private boolean checkMatch(InventoryCrafting parInventoryCrafting, int parInt1, int parInt2, boolean parFlag) { for (int i = 0; i < 3; ++i) { @@ -113,8 +79,8 @@ public class ShapedRecipes implements IRecipe { return true; } - /**+ - * Returns an Item that is the result of this recipe + /** + * + Returns an Item that is the result of this recipe */ public ItemStack getCraftingResult(InventoryCrafting inventorycrafting) { ItemStack itemstack = this.getRecipeOutput().copy(); @@ -130,10 +96,46 @@ public class ShapedRecipes implements IRecipe { return itemstack; } - /**+ - * Returns the size of the recipe area + public ItemStack getRecipeOutput() { + return this.recipeOutput; + } + + /** + * + Returns the size of the recipe area */ public int getRecipeSize() { return this.recipeWidth * this.recipeHeight; } + + public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { + ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; + + for (int i = 0; i < aitemstack.length; ++i) { + ItemStack itemstack = inventorycrafting.getStackInSlot(i); + if (itemstack != null && itemstack.getItem().hasContainerItem()) { + aitemstack[i] = new ItemStack(itemstack.getItem().getContainerItem()); + } + } + + return aitemstack; + } + + /** + * + Used to check if a recipe matches current crafting inventory + */ + public boolean matches(InventoryCrafting inventorycrafting, World var2) { + for (int i = 0; i <= 3 - this.recipeWidth; ++i) { + for (int j = 0; j <= 3 - this.recipeHeight; ++j) { + if (this.checkMatch(inventorycrafting, i, j, true)) { + return true; + } + + if (this.checkMatch(inventorycrafting, i, j, false)) { + return true; + } + } + } + + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/item/crafting/ShapelessRecipes.java b/src/game/java/net/minecraft/item/crafting/ShapelessRecipes.java index e2970d8b..c057ab95 100644 --- a/src/game/java/net/minecraft/item/crafting/ShapelessRecipes.java +++ b/src/game/java/net/minecraft/item/crafting/ShapelessRecipes.java @@ -9,22 +9,25 @@ import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.ItemStack; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,10 +41,24 @@ public class ShapelessRecipes implements IRecipe { this.recipeItems = inputList; } + /** + * + Returns an Item that is the result of this recipe + */ + public ItemStack getCraftingResult(InventoryCrafting var1) { + return this.recipeOutput.copy(); + } + public ItemStack getRecipeOutput() { return this.recipeOutput; } + /** + * + Returns the size of the recipe area + */ + public int getRecipeSize() { + return this.recipeItems.size(); + } + public ItemStack[] getRemainingItems(InventoryCrafting inventorycrafting) { ItemStack[] aitemstack = new ItemStack[inventorycrafting.getSizeInventory()]; @@ -55,8 +72,8 @@ public class ShapelessRecipes implements IRecipe { return aitemstack; } - /**+ - * Used to check if a recipe matches current crafting inventory + /** + * + Used to check if a recipe matches current crafting inventory */ public boolean matches(InventoryCrafting inventorycrafting, World var2) { ArrayList arraylist = Lists.newArrayList(this.recipeItems); @@ -86,18 +103,4 @@ public class ShapelessRecipes implements IRecipe { return arraylist.isEmpty(); } - - /**+ - * Returns an Item that is the result of this recipe - */ - public ItemStack getCraftingResult(InventoryCrafting var1) { - return this.recipeOutput.copy(); - } - - /**+ - * Returns the size of the recipe area - */ - public int getRecipeSize() { - return this.recipeItems.size(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/CompressedStreamTools.java b/src/game/java/net/minecraft/nbt/CompressedStreamTools.java index 834608d4..98bfdabd 100644 --- a/src/game/java/net/minecraft/nbt/CompressedStreamTools.java +++ b/src/game/java/net/minecraft/nbt/CompressedStreamTools.java @@ -15,96 +15,30 @@ import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CompressedStreamTools { - /**+ - * Load the gzipped compound from the inputstream. - */ - public static NBTTagCompound readCompressed(InputStream is) throws IOException { - DataInputStream datainputstream = new DataInputStream( - new BufferedInputStream(EaglerZLIB.newGZIPInputStream(is))); - - NBTTagCompound nbttagcompound; - try { - nbttagcompound = read(datainputstream, NBTSizeTracker.INFINITE); - } finally { - datainputstream.close(); - } - - return nbttagcompound; - } - - /**+ - * Write the compound, gzipped, to the outputstream. - */ - public static void writeCompressed(NBTTagCompound outputStream, OutputStream parOutputStream) throws IOException { - DataOutputStream dataoutputstream = new DataOutputStream( - new BufferedOutputStream(EaglerZLIB.newGZIPOutputStream(parOutputStream))); - - try { - write(outputStream, (DataOutput) dataoutputstream); - } finally { - dataoutputstream.close(); - } - - } - - /**+ - * Reads the given DataInput, constructs, and returns an - * NBTTagCompound with the data from the DataInput - */ - public static NBTTagCompound read(DataInputStream inputStream) throws IOException { - /**+ - * Reads the given DataInput, constructs, and returns an - * NBTTagCompound with the data from the DataInput - */ - return read(inputStream, NBTSizeTracker.INFINITE); - } - - /**+ - * Reads the given DataInput, constructs, and returns an - * NBTTagCompound with the data from the DataInput - */ - public static NBTTagCompound read(DataInput parDataInput, NBTSizeTracker parNBTSizeTracker) throws IOException { - NBTBase nbtbase = func_152455_a(parDataInput, 0, parNBTSizeTracker); - if (nbtbase instanceof NBTTagCompound) { - return (NBTTagCompound) nbtbase; - } else { - throw new IOException("Root tag must be a named compound tag"); - } - } - - public static void write(NBTTagCompound parNBTTagCompound, DataOutput parDataOutput) throws IOException { - writeTag(parNBTTagCompound, parDataOutput); - } - - private static void writeTag(NBTBase parNBTBase, DataOutput parDataOutput) throws IOException { - parDataOutput.writeByte(parNBTBase.getId()); - if (parNBTBase.getId() != 0) { - parDataOutput.writeUTF(""); - parNBTBase.write(parDataOutput); - } - } - private static NBTBase func_152455_a(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { byte b0 = parDataInput.readByte(); @@ -126,4 +60,73 @@ public class CompressedStreamTools { } } } + + /** + * + Reads the given DataInput, constructs, and returns an NBTTagCompound with + * the data from the DataInput + */ + public static NBTTagCompound read(DataInput parDataInput, NBTSizeTracker parNBTSizeTracker) throws IOException { + NBTBase nbtbase = func_152455_a(parDataInput, 0, parNBTSizeTracker); + if (nbtbase instanceof NBTTagCompound) { + return (NBTTagCompound) nbtbase; + } else { + throw new IOException("Root tag must be a named compound tag"); + } + } + + /** + * + Reads the given DataInput, constructs, and returns an NBTTagCompound with + * the data from the DataInput + */ + public static NBTTagCompound read(DataInputStream inputStream) throws IOException { + /** + * + Reads the given DataInput, constructs, and returns an NBTTagCompound with + * the data from the DataInput + */ + return read(inputStream, NBTSizeTracker.INFINITE); + } + + /** + * + Load the gzipped compound from the inputstream. + */ + public static NBTTagCompound readCompressed(InputStream is) throws IOException { + DataInputStream datainputstream = new DataInputStream( + new BufferedInputStream(EaglerZLIB.newGZIPInputStream(is))); + + NBTTagCompound nbttagcompound; + try { + nbttagcompound = read(datainputstream, NBTSizeTracker.INFINITE); + } finally { + datainputstream.close(); + } + + return nbttagcompound; + } + + public static void write(NBTTagCompound parNBTTagCompound, DataOutput parDataOutput) throws IOException { + writeTag(parNBTTagCompound, parDataOutput); + } + + /** + * + Write the compound, gzipped, to the outputstream. + */ + public static void writeCompressed(NBTTagCompound outputStream, OutputStream parOutputStream) throws IOException { + DataOutputStream dataoutputstream = new DataOutputStream( + new BufferedOutputStream(EaglerZLIB.newGZIPOutputStream(parOutputStream))); + + try { + write(outputStream, (DataOutput) dataoutputstream); + } finally { + dataoutputstream.close(); + } + + } + + private static void writeTag(NBTBase parNBTBase, DataOutput parDataOutput) throws IOException { + parDataOutput.writeByte(parNBTBase.getId()); + if (parNBTBase.getId() != 0) { + parDataOutput.writeUTF(""); + parNBTBase.write(parDataOutput); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/JsonToNBT.java b/src/game/java/net/minecraft/nbt/JsonToNBT.java index a77a99b5..a5115e5f 100644 --- a/src/game/java/net/minecraft/nbt/JsonToNBT.java +++ b/src/game/java/net/minecraft/nbt/JsonToNBT.java @@ -10,292 +10,30 @@ import com.google.common.collect.Lists; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JsonToNBT { - private static final Logger logger = LogManager.getLogger(); - private static final Pattern field_179273_b = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); - - public static NBTTagCompound getTagFromJson(String jsonString) throws NBTException { - jsonString = jsonString.trim(); - if (!jsonString.startsWith("{")) { - throw new NBTException("Invalid tag encountered, expected \'{\' as first char."); - } else if (func_150310_b(jsonString) != 1) { - throw new NBTException("Encountered multiple top tags, only one expected"); - } else { - return (NBTTagCompound) func_150316_a("tag", jsonString).parse(); - } - } - - static int func_150310_b(String parString1) throws NBTException { - int i = 0; - boolean flag = false; - Stack stack = new Stack(); - - for (int j = 0; j < parString1.length(); ++j) { - char c0 = parString1.charAt(j); - if (c0 == 34) { - if (func_179271_b(parString1, j)) { - if (!flag) { - throw new NBTException("Illegal use of \\\": " + parString1); - } - } else { - flag = !flag; - } - } else if (!flag) { - if (c0 != 123 && c0 != 91) { - if (c0 == 125 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 123)) { - throw new NBTException("Unbalanced curly brackets {}: " + parString1); - } - - if (c0 == 93 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 91)) { - throw new NBTException("Unbalanced square brackets []: " + parString1); - } - } else { - if (stack.isEmpty()) { - ++i; - } - - stack.push(Character.valueOf(c0)); - } - } - } - - if (flag) { - throw new NBTException("Unbalanced quotation: " + parString1); - } else if (!stack.isEmpty()) { - throw new NBTException("Unbalanced brackets: " + parString1); - } else { - if (i == 0 && !parString1.isEmpty()) { - i = 1; - } - - return i; - } - } - - static JsonToNBT.Any func_179272_a(String... parArrayOfString) throws NBTException { - return func_150316_a(parArrayOfString[0], parArrayOfString[1]); - } - - static JsonToNBT.Any func_150316_a(String parString1, String parString2) throws NBTException { - parString2 = parString2.trim(); - if (parString2.startsWith("{")) { - parString2 = parString2.substring(1, parString2.length() - 1); - - JsonToNBT.Compound jsontonbt$compound; - String s1; - for (jsontonbt$compound = new JsonToNBT.Compound(parString1); parString2 - .length() > 0; parString2 = parString2.substring(s1.length() + 1)) { - s1 = func_150314_a(parString2, true); - if (s1.length() > 0) { - boolean flag1 = false; - jsontonbt$compound.field_150491_b.add(func_179270_a(s1, flag1)); - } - - if (parString2.length() < s1.length() + 1) { - break; - } - - char c1 = parString2.charAt(s1.length()); - if (c1 != 44 && c1 != 123 && c1 != 125 && c1 != 91 && c1 != 93) { - throw new NBTException("Unexpected token \'" + c1 + "\' at: " + parString2.substring(s1.length())); - } - } - - return jsontonbt$compound; - } else if (parString2.startsWith("[") && !field_179273_b.matcher(parString2).matches()) { - parString2 = parString2.substring(1, parString2.length() - 1); - - JsonToNBT.List jsontonbt$list; - String s; - for (jsontonbt$list = new JsonToNBT.List(parString1); parString2.length() > 0; parString2 = parString2 - .substring(s.length() + 1)) { - s = func_150314_a(parString2, false); - if (s.length() > 0) { - boolean flag = true; - jsontonbt$list.field_150492_b.add(func_179270_a(s, flag)); - } - - if (parString2.length() < s.length() + 1) { - break; - } - - char c0 = parString2.charAt(s.length()); - if (c0 != 44 && c0 != 123 && c0 != 125 && c0 != 91 && c0 != 93) { - throw new NBTException("Unexpected token \'" + c0 + "\' at: " + parString2.substring(s.length())); - } - } - - return jsontonbt$list; - } else { - return new JsonToNBT.Primitive(parString1, parString2); - } - } - - private static JsonToNBT.Any func_179270_a(String parString1, boolean parFlag) throws NBTException { - String s = func_150313_b(parString1, parFlag); - String s1 = func_150311_c(parString1, parFlag); - return func_179272_a(new String[] { s, s1 }); - } - - private static String func_150314_a(String parString1, boolean parFlag) throws NBTException { - int i = func_150312_a(parString1, ':'); - int j = func_150312_a(parString1, ','); - if (parFlag) { - if (i == -1) { - throw new NBTException("Unable to locate name/value separator for string: " + parString1); - } - - if (j != -1 && j < i) { - throw new NBTException("Name error at: " + parString1); - } - } else if (i == -1 || i > j) { - i = -1; - } - - return func_179269_a(parString1, i); - } - - private static String func_179269_a(String parString1, int parInt1) throws NBTException { - Stack stack = new Stack(); - int i = parInt1 + 1; - boolean flag = false; - boolean flag1 = false; - boolean flag2 = false; - - for (int j = 0; i < parString1.length(); ++i) { - char c0 = parString1.charAt(i); - if (c0 == 34) { - if (func_179271_b(parString1, i)) { - if (!flag) { - throw new NBTException("Illegal use of \\\": " + parString1); - } - } else { - flag = !flag; - if (flag && !flag2) { - flag1 = true; - } - - if (!flag) { - j = i; - } - } - } else if (!flag) { - if (c0 != 123 && c0 != 91) { - if (c0 == 125 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 123)) { - throw new NBTException("Unbalanced curly brackets {}: " + parString1); - } - - if (c0 == 93 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 91)) { - throw new NBTException("Unbalanced square brackets []: " + parString1); - } - - if (c0 == 44 && stack.isEmpty()) { - return parString1.substring(0, i); - } - } else { - stack.push(Character.valueOf(c0)); - } - } - - if (!Character.isWhitespace(c0)) { - if (!flag && flag1 && j != i) { - return parString1.substring(0, j + 1); - } - - flag2 = true; - } - } - - return parString1.substring(0, i); - } - - private static String func_150313_b(String parString1, boolean parFlag) throws NBTException { - if (parFlag) { - parString1 = parString1.trim(); - if (parString1.startsWith("{") || parString1.startsWith("[")) { - return ""; - } - } - - int i = func_150312_a(parString1, ':'); - if (i == -1) { - if (parFlag) { - return ""; - } else { - throw new NBTException("Unable to locate name/value separator for string: " + parString1); - } - } else { - return parString1.substring(0, i).trim(); - } - } - - private static String func_150311_c(String parString1, boolean parFlag) throws NBTException { - if (parFlag) { - parString1 = parString1.trim(); - if (parString1.startsWith("{") || parString1.startsWith("[")) { - return parString1; - } - } - - int i = func_150312_a(parString1, ':'); - if (i == -1) { - if (parFlag) { - return parString1; - } else { - throw new NBTException("Unable to locate name/value separator for string: " + parString1); - } - } else { - return parString1.substring(i + 1).trim(); - } - } - - private static int func_150312_a(String parString1, char parChar1) { - int i = 0; - - for (boolean flag = true; i < parString1.length(); ++i) { - char c0 = parString1.charAt(i); - if (c0 == 34) { - if (!func_179271_b(parString1, i)) { - flag = !flag; - } - } else if (flag) { - if (c0 == parChar1) { - return i; - } - - if (c0 == 123 || c0 == 91) { - return -1; - } - } - } - - return -1; - } - - private static boolean func_179271_b(String parString1, int parInt1) { - return parInt1 > 0 && parString1.charAt(parInt1 - 1) == 92 && !func_179271_b(parString1, parInt1 - 1); - } - abstract static class Any { protected String json; @@ -431,4 +169,270 @@ public class JsonToNBT { } } } + + private static final Logger logger = LogManager.getLogger(); + + private static final Pattern field_179273_b = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); + + static int func_150310_b(String parString1) throws NBTException { + int i = 0; + boolean flag = false; + Stack stack = new Stack(); + + for (int j = 0; j < parString1.length(); ++j) { + char c0 = parString1.charAt(j); + if (c0 == 34) { + if (func_179271_b(parString1, j)) { + if (!flag) { + throw new NBTException("Illegal use of \\\": " + parString1); + } + } else { + flag = !flag; + } + } else if (!flag) { + if (c0 != 123 && c0 != 91) { + if (c0 == 125 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 123)) { + throw new NBTException("Unbalanced curly brackets {}: " + parString1); + } + + if (c0 == 93 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 91)) { + throw new NBTException("Unbalanced square brackets []: " + parString1); + } + } else { + if (stack.isEmpty()) { + ++i; + } + + stack.push(Character.valueOf(c0)); + } + } + } + + if (flag) { + throw new NBTException("Unbalanced quotation: " + parString1); + } else if (!stack.isEmpty()) { + throw new NBTException("Unbalanced brackets: " + parString1); + } else { + if (i == 0 && !parString1.isEmpty()) { + i = 1; + } + + return i; + } + } + + private static String func_150311_c(String parString1, boolean parFlag) throws NBTException { + if (parFlag) { + parString1 = parString1.trim(); + if (parString1.startsWith("{") || parString1.startsWith("[")) { + return parString1; + } + } + + int i = func_150312_a(parString1, ':'); + if (i == -1) { + if (parFlag) { + return parString1; + } else { + throw new NBTException("Unable to locate name/value separator for string: " + parString1); + } + } else { + return parString1.substring(i + 1).trim(); + } + } + + private static int func_150312_a(String parString1, char parChar1) { + int i = 0; + + for (boolean flag = true; i < parString1.length(); ++i) { + char c0 = parString1.charAt(i); + if (c0 == 34) { + if (!func_179271_b(parString1, i)) { + flag = !flag; + } + } else if (flag) { + if (c0 == parChar1) { + return i; + } + + if (c0 == 123 || c0 == 91) { + return -1; + } + } + } + + return -1; + } + + private static String func_150313_b(String parString1, boolean parFlag) throws NBTException { + if (parFlag) { + parString1 = parString1.trim(); + if (parString1.startsWith("{") || parString1.startsWith("[")) { + return ""; + } + } + + int i = func_150312_a(parString1, ':'); + if (i == -1) { + if (parFlag) { + return ""; + } else { + throw new NBTException("Unable to locate name/value separator for string: " + parString1); + } + } else { + return parString1.substring(0, i).trim(); + } + } + + private static String func_150314_a(String parString1, boolean parFlag) throws NBTException { + int i = func_150312_a(parString1, ':'); + int j = func_150312_a(parString1, ','); + if (parFlag) { + if (i == -1) { + throw new NBTException("Unable to locate name/value separator for string: " + parString1); + } + + if (j != -1 && j < i) { + throw new NBTException("Name error at: " + parString1); + } + } else if (i == -1 || i > j) { + i = -1; + } + + return func_179269_a(parString1, i); + } + + static JsonToNBT.Any func_150316_a(String parString1, String parString2) throws NBTException { + parString2 = parString2.trim(); + if (parString2.startsWith("{")) { + parString2 = parString2.substring(1, parString2.length() - 1); + + JsonToNBT.Compound jsontonbt$compound; + String s1; + for (jsontonbt$compound = new JsonToNBT.Compound(parString1); parString2 + .length() > 0; parString2 = parString2.substring(s1.length() + 1)) { + s1 = func_150314_a(parString2, true); + if (s1.length() > 0) { + boolean flag1 = false; + jsontonbt$compound.field_150491_b.add(func_179270_a(s1, flag1)); + } + + if (parString2.length() < s1.length() + 1) { + break; + } + + char c1 = parString2.charAt(s1.length()); + if (c1 != 44 && c1 != 123 && c1 != 125 && c1 != 91 && c1 != 93) { + throw new NBTException("Unexpected token \'" + c1 + "\' at: " + parString2.substring(s1.length())); + } + } + + return jsontonbt$compound; + } else if (parString2.startsWith("[") && !field_179273_b.matcher(parString2).matches()) { + parString2 = parString2.substring(1, parString2.length() - 1); + + JsonToNBT.List jsontonbt$list; + String s; + for (jsontonbt$list = new JsonToNBT.List(parString1); parString2.length() > 0; parString2 = parString2 + .substring(s.length() + 1)) { + s = func_150314_a(parString2, false); + if (s.length() > 0) { + boolean flag = true; + jsontonbt$list.field_150492_b.add(func_179270_a(s, flag)); + } + + if (parString2.length() < s.length() + 1) { + break; + } + + char c0 = parString2.charAt(s.length()); + if (c0 != 44 && c0 != 123 && c0 != 125 && c0 != 91 && c0 != 93) { + throw new NBTException("Unexpected token \'" + c0 + "\' at: " + parString2.substring(s.length())); + } + } + + return jsontonbt$list; + } else { + return new JsonToNBT.Primitive(parString1, parString2); + } + } + + private static String func_179269_a(String parString1, int parInt1) throws NBTException { + Stack stack = new Stack(); + int i = parInt1 + 1; + boolean flag = false; + boolean flag1 = false; + boolean flag2 = false; + + for (int j = 0; i < parString1.length(); ++i) { + char c0 = parString1.charAt(i); + if (c0 == 34) { + if (func_179271_b(parString1, i)) { + if (!flag) { + throw new NBTException("Illegal use of \\\": " + parString1); + } + } else { + flag = !flag; + if (flag && !flag2) { + flag1 = true; + } + + if (!flag) { + j = i; + } + } + } else if (!flag) { + if (c0 != 123 && c0 != 91) { + if (c0 == 125 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 123)) { + throw new NBTException("Unbalanced curly brackets {}: " + parString1); + } + + if (c0 == 93 && (stack.isEmpty() || ((Character) stack.pop()).charValue() != 91)) { + throw new NBTException("Unbalanced square brackets []: " + parString1); + } + + if (c0 == 44 && stack.isEmpty()) { + return parString1.substring(0, i); + } + } else { + stack.push(Character.valueOf(c0)); + } + } + + if (!Character.isWhitespace(c0)) { + if (!flag && flag1 && j != i) { + return parString1.substring(0, j + 1); + } + + flag2 = true; + } + } + + return parString1.substring(0, i); + } + + private static JsonToNBT.Any func_179270_a(String parString1, boolean parFlag) throws NBTException { + String s = func_150313_b(parString1, parFlag); + String s1 = func_150311_c(parString1, parFlag); + return func_179272_a(new String[] { s, s1 }); + } + + private static boolean func_179271_b(String parString1, int parInt1) { + return parInt1 > 0 && parString1.charAt(parInt1 - 1) == 92 && !func_179271_b(parString1, parInt1 - 1); + } + + static JsonToNBT.Any func_179272_a(String... parArrayOfString) throws NBTException { + return func_150316_a(parArrayOfString[0], parArrayOfString[1]); + } + + public static NBTTagCompound getTagFromJson(String jsonString) throws NBTException { + jsonString = jsonString.trim(); + if (!jsonString.startsWith("{")) { + throw new NBTException("Invalid tag encountered, expected \'{\' as first char."); + } else if (func_150310_b(jsonString) != 1) { + throw new NBTException("Encountered multiple top tags, only one expected"); + } else { + return (NBTTagCompound) func_150316_a("tag", jsonString).parse(); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTBase.java b/src/game/java/net/minecraft/nbt/NBTBase.java index 1b33e08b..b64a75bd 100644 --- a/src/game/java/net/minecraft/nbt/NBTBase.java +++ b/src/game/java/net/minecraft/nbt/NBTBase.java @@ -4,41 +4,49 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class NBTBase { + public abstract static class NBTPrimitive extends NBTBase { + public abstract byte getByte(); + + public abstract double getDouble(); + + public abstract float getFloat(); + + public abstract int getInt(); + + public abstract long getLong(); + + public abstract short getShort(); + } + public static final String[] NBT_TYPES = new String[] { "END", "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "BYTE[]", "STRING", "LIST", "COMPOUND", "INT[]" }; - abstract void write(DataOutput var1) throws IOException; - - abstract void read(DataInput var1, int var2, NBTSizeTracker var3) throws IOException; - - public abstract String toString(); - - public abstract byte getId(); - - /**+ - * Creates a new NBTBase object that corresponds with the passed - * in id. + /** + * + Creates a new NBTBase object that corresponds with the passed in id. */ protected static NBTBase createNewByType(byte id) { switch (id) { @@ -73,13 +81,6 @@ public abstract class NBTBase { public abstract NBTBase copy(); - /**+ - * Return whether this compound has no tags. - */ - public boolean hasNoTags() { - return false; - } - public boolean equals(Object object) { if (!(object instanceof NBTBase)) { return false; @@ -89,25 +90,26 @@ public abstract class NBTBase { } } - public int hashCode() { - return this.getId(); - } + public abstract byte getId(); protected String getString() { return this.toString(); } - public abstract static class NBTPrimitive extends NBTBase { - public abstract long getLong(); - - public abstract int getInt(); - - public abstract short getShort(); - - public abstract byte getByte(); - - public abstract double getDouble(); - - public abstract float getFloat(); + public int hashCode() { + return this.getId(); } + + /** + * + Return whether this compound has no tags. + */ + public boolean hasNoTags() { + return false; + } + + abstract void read(DataInput var1, int var2, NBTSizeTracker var3) throws IOException; + + public abstract String toString(); + + abstract void write(DataOutput var1) throws IOException; } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTException.java b/src/game/java/net/minecraft/nbt/NBTException.java index f5c381a8..4cda66ae 100644 --- a/src/game/java/net/minecraft/nbt/NBTException.java +++ b/src/game/java/net/minecraft/nbt/NBTException.java @@ -1,21 +1,24 @@ package net.minecraft.nbt; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/nbt/NBTSizeTracker.java b/src/game/java/net/minecraft/nbt/NBTSizeTracker.java index 5e3498cf..40511aab 100644 --- a/src/game/java/net/minecraft/nbt/NBTSizeTracker.java +++ b/src/game/java/net/minecraft/nbt/NBTSizeTracker.java @@ -1,29 +1,32 @@ package net.minecraft.nbt; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NBTSizeTracker { public static final NBTSizeTracker INFINITE = new NBTSizeTracker(0L) { - /**+ - * Tracks the reading of the given amount of bits(!) + /** + * + Tracks the reading of the given amount of bits(!) */ public void read(long bits) { } @@ -35,8 +38,8 @@ public class NBTSizeTracker { this.max = max; } - /**+ - * Tracks the reading of the given amount of bits(!) + /** + * + Tracks the reading of the given amount of bits(!) */ public void read(long i) { this.read += i / 8L; diff --git a/src/game/java/net/minecraft/nbt/NBTTagByte.java b/src/game/java/net/minecraft/nbt/NBTTagByte.java index 356e8cf3..96bfcc94 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagByte.java +++ b/src/game/java/net/minecraft/nbt/NBTTagByte.java @@ -4,22 +4,25 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,32 +37,8 @@ public class NBTTagByte extends NBTBase.NBTPrimitive { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeByte(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(72L); - this.data = parDataInput.readByte(); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 1; - } - - public String toString() { - return "" + this.data + "b"; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagByte(this.data); @@ -74,22 +53,6 @@ public class NBTTagByte extends NBTBase.NBTPrimitive { } } - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public long getLong() { - return (long) this.data; - } - - public int getInt() { - return this.data; - } - - public short getShort() { - return (short) this.data; - } - public byte getByte() { return this.data; } @@ -101,4 +64,44 @@ public class NBTTagByte extends NBTBase.NBTPrimitive { public float getFloat() { return (float) this.data; } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 1; + } + + public int getInt() { + return this.data; + } + + public long getLong() { + return (long) this.data; + } + + public short getShort() { + return (short) this.data; + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(72L); + this.data = parDataInput.readByte(); + } + + public String toString() { + return "" + this.data + "b"; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeByte(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagByteArray.java b/src/game/java/net/minecraft/nbt/NBTTagByteArray.java index bc9ff644..15aea213 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagByteArray.java +++ b/src/game/java/net/minecraft/nbt/NBTTagByteArray.java @@ -5,22 +5,25 @@ import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,36 +38,8 @@ public class NBTTagByteArray extends NBTBase { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput output) throws IOException { - output.writeInt(this.data.length); - output.write(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException { - sizeTracker.read(192L); - int i = input.readInt(); - sizeTracker.read((long) (8 * i)); - this.data = new byte[i]; - input.readFully(this.data); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 7; - } - - public String toString() { - return "[" + this.data.length + " bytes]"; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { byte[] abyte = new byte[this.data.length]; @@ -76,11 +51,39 @@ public class NBTTagByteArray extends NBTBase { return super.equals(object) ? Arrays.equals(this.data, ((NBTTagByteArray) object).data) : false; } + public byte[] getByteArray() { + return this.data; + } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 7; + } + public int hashCode() { return super.hashCode() ^ Arrays.hashCode(this.data); } - public byte[] getByteArray() { - return this.data; + void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException { + sizeTracker.read(192L); + int i = input.readInt(); + sizeTracker.read((long) (8 * i)); + this.data = new byte[i]; + input.readFully(this.data); + } + + public String toString() { + return "[" + this.data.length + " bytes]"; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput output) throws IOException { + output.writeInt(this.data.length); + output.write(this.data); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagCompound.java b/src/game/java/net/minecraft/nbt/NBTTagCompound.java index 7d114880..c6cf652c 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagCompound.java +++ b/src/game/java/net/minecraft/nbt/NBTTagCompound.java @@ -14,40 +14,337 @@ import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NBTTagCompound extends NBTBase { + private static String readKey(DataInput input, NBTSizeTracker sizeTracker) throws IOException { + return input.readUTF(); + } + + static NBTBase readNBT(byte id, String key, DataInput input, int depth, NBTSizeTracker sizeTracker) + throws IOException { + NBTBase nbtbase = NBTBase.createNewByType(id); + + try { + nbtbase.read(input, depth, sizeTracker); + return nbtbase; + } catch (IOException ioexception) { + CrashReport crashreport = CrashReport.makeCrashReport(ioexception, "Loading NBT data"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("NBT Tag"); + crashreportcategory.addCrashSection("Tag name", key); + crashreportcategory.addCrashSection("Tag type", Byte.valueOf(id)); + throw new ReportedException(crashreport); + } + } + + private static byte readType(DataInput input, NBTSizeTracker sizeTracker) throws IOException { + return input.readByte(); + } + + private static void writeEntry(String name, NBTBase data, DataOutput output) throws IOException { + output.writeByte(data.getId()); + if (data.getId() != 0) { + output.writeUTF(name); + data.write(output); + } + } + private Map tagMap = Maps.newHashMap(); - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes + /** + * + Creates a clone of the tag. */ - void write(DataOutput parDataOutput) throws IOException { + public NBTBase copy() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + for (String s : this.tagMap.keySet()) { - NBTBase nbtbase = (NBTBase) this.tagMap.get(s); - writeEntry(s, nbtbase, parDataOutput); + nbttagcompound.setTag(s, ((NBTBase) this.tagMap.get(s)).copy()); + } + + return nbttagcompound; + } + + /** + * + Create a crash report which indicates a NBT read error. + */ + private CrashReport createCrashReport(final String key, final int expectedType, ClassCastException ex) { + CrashReport crashreport = CrashReport.makeCrashReport(ex, "Reading NBT data"); + CrashReportCategory crashreportcategory = crashreport.makeCategoryDepth("Corrupt NBT tag", 1); + crashreportcategory.addCrashSectionCallable("Tag type found", new Callable() { + public String call() throws Exception { + return NBTBase.NBT_TYPES[((NBTBase) NBTTagCompound.this.tagMap.get(key)).getId()]; + } + }); + crashreportcategory.addCrashSectionCallable("Tag type expected", new Callable() { + public String call() throws Exception { + return NBTBase.NBT_TYPES[expectedType]; + } + }); + crashreportcategory.addCrashSection("Tag name", key); + return crashreport; + } + + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagCompound nbttagcompound = (NBTTagCompound) object; + return this.tagMap.entrySet().equals(nbttagcompound.tagMap.entrySet()); + } else { + return false; + } + } + + /** + * + Retrieves a boolean value using the specified key, or false if no such key + * was stored. This uses the getByte method. + */ + public boolean getBoolean(String key) { + return this.getByte(key) != 0; + } + + /** + * + Retrieves a byte value using the specified key, or 0 if no such key was + * stored. + */ + public byte getByte(String key) { + try { + return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getByte(); + } catch (ClassCastException var3) { + return (byte) 0; + } + } + + /** + * + Retrieves a byte array using the specified key, or a zero-length array if + * no such key was stored. + */ + public byte[] getByteArray(String key) { + try { + return !this.hasKey(key, 7) ? new byte[0] : ((NBTTagByteArray) this.tagMap.get(key)).getByteArray(); + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.createCrashReport(key, 7, classcastexception)); + } + } + + /** + * + Retrieves a NBTTagCompound subtag matching the specified key, or a new + * empty NBTTagCompound if no such key was stored. + */ + public NBTTagCompound getCompoundTag(String key) { + try { + return !this.hasKey(key, 10) ? new NBTTagCompound() : (NBTTagCompound) this.tagMap.get(key); + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.createCrashReport(key, 10, classcastexception)); + } + } + + /** + * + Retrieves a double value using the specified key, or 0 if no such key was + * stored. + */ + public double getDouble(String key) { + try { + return !this.hasKey(key, 99) ? 0.0D : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getDouble(); + } catch (ClassCastException var3) { + return 0.0D; + } + } + + /** + * + Retrieves a float value using the specified key, or 0 if no such key was + * stored. + */ + public float getFloat(String key) { + try { + return !this.hasKey(key, 99) ? 0.0F : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getFloat(); + } catch (ClassCastException var3) { + return 0.0F; + } + } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 10; + } + + /** + * + Retrieves an int array using the specified key, or a zero-length array if + * no such key was stored. + */ + public int[] getIntArray(String key) { + try { + return !this.hasKey(key, 11) ? new int[0] : ((NBTTagIntArray) this.tagMap.get(key)).getIntArray(); + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.createCrashReport(key, 11, classcastexception)); + } + } + + /** + * + Retrieves an integer value using the specified key, or 0 if no such key was + * stored. + */ + public int getInteger(String key) { + try { + return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getInt(); + } catch (ClassCastException var3) { + return 0; + } + } + + /** + * + Gets a set with the names of the keys in the tag compound. + */ + public Set getKeySet() { + return this.tagMap.keySet(); + } + + /** + * + Retrieves a long value using the specified key, or 0 if no such key was + * stored. + */ + public long getLong(String key) { + try { + return !this.hasKey(key, 99) ? 0L : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getLong(); + } catch (ClassCastException var3) { + return 0L; + } + } + + /** + * + Retrieves a short value using the specified key, or 0 if no such key was + * stored. + */ + public short getShort(String key) { + try { + return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getShort(); + } catch (ClassCastException var3) { + return (short) 0; + } + } + + /** + * + Retrieves a string value using the specified key, or an empty string if no + * such key was stored. + */ + public String getString(String key) { + try { + return !this.hasKey(key, 8) ? "" : ((NBTBase) this.tagMap.get(key)).getString(); + } catch (ClassCastException var3) { + return ""; + } + } + + /** + * + gets a generic tag with the specified name + */ + public NBTBase getTag(String key) { + return (NBTBase) this.tagMap.get(key); + } + + /** + * + Gets the ID byte for the given tag key + */ + public byte getTagId(String key) { + NBTBase nbtbase = (NBTBase) this.tagMap.get(key); + return nbtbase != null ? nbtbase.getId() : 0; + } + + /** + * + Gets the NBTTagList object with the given name. Args: name, NBTBase type + */ + public NBTTagList getTagList(String key, int type) { + try { + if (this.getTagId(key) != 9) { + return new NBTTagList(); + } else { + NBTTagList nbttaglist = (NBTTagList) this.tagMap.get(key); + return nbttaglist.tagCount() > 0 && nbttaglist.getTagType() != type ? new NBTTagList() : nbttaglist; + } + } catch (ClassCastException classcastexception) { + throw new ReportedException(this.createCrashReport(key, 9, classcastexception)); + } + } + + public int hashCode() { + return super.hashCode() ^ this.tagMap.hashCode(); + } + + /** + * + Returns whether the given string has been previously stored as a key in the + * map. + */ + public boolean hasKey(String key) { + return this.tagMap.containsKey(key); + } + + /** + * + Returns whether the given string has been previously stored as a key in the + * map. + */ + public boolean hasKey(String key, int type) { + byte b0 = this.getTagId(key); + if (b0 == type) { + return true; + } else if (type != 99) { + if (b0 > 0) { + ; + } + + return false; + } else { + return b0 == 1 || b0 == 2 || b0 == 3 || b0 == 4 || b0 == 5 || b0 == 6; + } + } + + /** + * + Return whether this compound has no tags. + */ + public boolean hasNoTags() { + return this.tagMap.isEmpty(); + } + + /** + * + Merges this NBTTagCompound with the given compound. Any sub-compounds are + * merged using the same methods, other types of tags are overwritten from the + * given compound. + */ + public void merge(NBTTagCompound other) { + for (String s : other.tagMap.keySet()) { + NBTBase nbtbase = (NBTBase) other.tagMap.get(s); + if (nbtbase.getId() == 10) { + if (this.hasKey(s, 10)) { + NBTTagCompound nbttagcompound = this.getCompoundTag(s); + nbttagcompound.merge((NBTTagCompound) nbtbase); + } else { + this.setTag(s, nbtbase.copy()); + } + } else { + this.setTag(s, nbtbase.copy()); + } } - parDataOutput.writeByte(0); } void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { @@ -70,300 +367,99 @@ public class NBTTagCompound extends NBTBase { } } - /**+ - * Gets a set with the names of the keys in the tag compound. + /** + * + Remove the specified tag. */ - public Set getKeySet() { - return this.tagMap.keySet(); + public void removeTag(String key) { + this.tagMap.remove(key); } - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 10; - } - - /**+ - * Stores the given tag into the map with the given string key. - * This is mostly used to store tag lists. - */ - public void setTag(String key, NBTBase value) { - this.tagMap.put(key, value); - } - - /**+ - * Stores a new NBTTagByte with the given byte value into the - * map with the given string key. - */ - public void setByte(String key, byte value) { - this.tagMap.put(key, new NBTTagByte(value)); - } - - /**+ - * Stores a new NBTTagShort with the given short value into the - * map with the given string key. - */ - public void setShort(String key, short value) { - this.tagMap.put(key, new NBTTagShort(value)); - } - - /**+ - * Stores a new NBTTagInt with the given integer value into the - * map with the given string key. - */ - public void setInteger(String key, int value) { - this.tagMap.put(key, new NBTTagInt(value)); - } - - /**+ - * Stores a new NBTTagLong with the given long value into the - * map with the given string key. - */ - public void setLong(String key, long value) { - this.tagMap.put(key, new NBTTagLong(value)); - } - - /**+ - * Stores a new NBTTagFloat with the given float value into the - * map with the given string key. - */ - public void setFloat(String key, float value) { - this.tagMap.put(key, new NBTTagFloat(value)); - } - - /**+ - * Stores a new NBTTagDouble with the given double value into - * the map with the given string key. - */ - public void setDouble(String key, double value) { - this.tagMap.put(key, new NBTTagDouble(value)); - } - - /**+ - * Stores a new NBTTagString with the given string value into - * the map with the given string key. - */ - public void setString(String key, String value) { - this.tagMap.put(key, new NBTTagString(value)); - } - - /**+ - * Stores a new NBTTagByteArray with the given array as data - * into the map with the given string key. - */ - public void setByteArray(String key, byte[] value) { - this.tagMap.put(key, new NBTTagByteArray(value)); - } - - /**+ - * Stores a new NBTTagIntArray with the given array as data into - * the map with the given string key. - */ - public void setIntArray(String key, int[] value) { - this.tagMap.put(key, new NBTTagIntArray(value)); - } - - /**+ - * Stores the given boolean value as a NBTTagByte, storing 1 for - * true and 0 for false, using the given string key. + /** + * + Stores the given boolean value as a NBTTagByte, storing 1 for true and 0 + * for false, using the given string key. */ public void setBoolean(String key, boolean value) { this.setByte(key, (byte) (value ? 1 : 0)); } - /**+ - * gets a generic tag with the specified name + /** + * + Stores a new NBTTagByte with the given byte value into the map with the + * given string key. */ - public NBTBase getTag(String key) { - return (NBTBase) this.tagMap.get(key); + public void setByte(String key, byte value) { + this.tagMap.put(key, new NBTTagByte(value)); } - /**+ - * Gets the ID byte for the given tag key + /** + * + Stores a new NBTTagByteArray with the given array as data into the map with + * the given string key. */ - public byte getTagId(String key) { - NBTBase nbtbase = (NBTBase) this.tagMap.get(key); - return nbtbase != null ? nbtbase.getId() : 0; + public void setByteArray(String key, byte[] value) { + this.tagMap.put(key, new NBTTagByteArray(value)); } - /**+ - * Returns whether the given string has been previously stored - * as a key in the map. + /** + * + Stores a new NBTTagDouble with the given double value into the map with the + * given string key. */ - public boolean hasKey(String key) { - return this.tagMap.containsKey(key); + public void setDouble(String key, double value) { + this.tagMap.put(key, new NBTTagDouble(value)); } - /**+ - * Returns whether the given string has been previously stored - * as a key in the map. + /** + * + Stores a new NBTTagFloat with the given float value into the map with the + * given string key. */ - public boolean hasKey(String key, int type) { - byte b0 = this.getTagId(key); - if (b0 == type) { - return true; - } else if (type != 99) { - if (b0 > 0) { - ; - } - - return false; - } else { - return b0 == 1 || b0 == 2 || b0 == 3 || b0 == 4 || b0 == 5 || b0 == 6; - } + public void setFloat(String key, float value) { + this.tagMap.put(key, new NBTTagFloat(value)); } - /**+ - * Retrieves a byte value using the specified key, or 0 if no - * such key was stored. + /** + * + Stores a new NBTTagIntArray with the given array as data into the map with + * the given string key. */ - public byte getByte(String key) { - try { - return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getByte(); - } catch (ClassCastException var3) { - return (byte) 0; - } + public void setIntArray(String key, int[] value) { + this.tagMap.put(key, new NBTTagIntArray(value)); } - /**+ - * Retrieves a short value using the specified key, or 0 if no - * such key was stored. + /** + * + Stores a new NBTTagInt with the given integer value into the map with the + * given string key. */ - public short getShort(String key) { - try { - return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getShort(); - } catch (ClassCastException var3) { - return (short) 0; - } + public void setInteger(String key, int value) { + this.tagMap.put(key, new NBTTagInt(value)); } - /**+ - * Retrieves an integer value using the specified key, or 0 if - * no such key was stored. + /** + * + Stores a new NBTTagLong with the given long value into the map with the + * given string key. */ - public int getInteger(String key) { - try { - return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getInt(); - } catch (ClassCastException var3) { - return 0; - } + public void setLong(String key, long value) { + this.tagMap.put(key, new NBTTagLong(value)); } - /**+ - * Retrieves a long value using the specified key, or 0 if no - * such key was stored. + /** + * + Stores a new NBTTagShort with the given short value into the map with the + * given string key. */ - public long getLong(String key) { - try { - return !this.hasKey(key, 99) ? 0L : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getLong(); - } catch (ClassCastException var3) { - return 0L; - } + public void setShort(String key, short value) { + this.tagMap.put(key, new NBTTagShort(value)); } - /**+ - * Retrieves a float value using the specified key, or 0 if no - * such key was stored. + /** + * + Stores a new NBTTagString with the given string value into the map with the + * given string key. */ - public float getFloat(String key) { - try { - return !this.hasKey(key, 99) ? 0.0F : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getFloat(); - } catch (ClassCastException var3) { - return 0.0F; - } + public void setString(String key, String value) { + this.tagMap.put(key, new NBTTagString(value)); } - /**+ - * Retrieves a double value using the specified key, or 0 if no - * such key was stored. + /** + * + Stores the given tag into the map with the given string key. This is mostly + * used to store tag lists. */ - public double getDouble(String key) { - try { - return !this.hasKey(key, 99) ? 0.0D : ((NBTBase.NBTPrimitive) this.tagMap.get(key)).getDouble(); - } catch (ClassCastException var3) { - return 0.0D; - } - } - - /**+ - * Retrieves a string value using the specified key, or an empty - * string if no such key was stored. - */ - public String getString(String key) { - try { - return !this.hasKey(key, 8) ? "" : ((NBTBase) this.tagMap.get(key)).getString(); - } catch (ClassCastException var3) { - return ""; - } - } - - /**+ - * Retrieves a byte array using the specified key, or a - * zero-length array if no such key was stored. - */ - public byte[] getByteArray(String key) { - try { - return !this.hasKey(key, 7) ? new byte[0] : ((NBTTagByteArray) this.tagMap.get(key)).getByteArray(); - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.createCrashReport(key, 7, classcastexception)); - } - } - - /**+ - * Retrieves an int array using the specified key, or a - * zero-length array if no such key was stored. - */ - public int[] getIntArray(String key) { - try { - return !this.hasKey(key, 11) ? new int[0] : ((NBTTagIntArray) this.tagMap.get(key)).getIntArray(); - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.createCrashReport(key, 11, classcastexception)); - } - } - - /**+ - * Retrieves a NBTTagCompound subtag matching the specified key, - * or a new empty NBTTagCompound if no such key was stored. - */ - public NBTTagCompound getCompoundTag(String key) { - try { - return !this.hasKey(key, 10) ? new NBTTagCompound() : (NBTTagCompound) this.tagMap.get(key); - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.createCrashReport(key, 10, classcastexception)); - } - } - - /**+ - * Gets the NBTTagList object with the given name. Args: name, - * NBTBase type - */ - public NBTTagList getTagList(String key, int type) { - try { - if (this.getTagId(key) != 9) { - return new NBTTagList(); - } else { - NBTTagList nbttaglist = (NBTTagList) this.tagMap.get(key); - return nbttaglist.tagCount() > 0 && nbttaglist.getTagType() != type ? new NBTTagList() : nbttaglist; - } - } catch (ClassCastException classcastexception) { - throw new ReportedException(this.createCrashReport(key, 9, classcastexception)); - } - } - - /**+ - * Retrieves a boolean value using the specified key, or false - * if no such key was stored. This uses the getByte method. - */ - public boolean getBoolean(String key) { - return this.getByte(key) != 0; - } - - /**+ - * Remove the specified tag. - */ - public void removeTag(String key) { - this.tagMap.remove(key); + public void setTag(String key, NBTBase value) { + this.tagMap.put(key, value); } public String toString() { @@ -380,110 +476,16 @@ public class NBTTagCompound extends NBTBase { return stringbuilder.append('}').toString(); } - /**+ - * Return whether this compound has no tags. + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes */ - public boolean hasNoTags() { - return this.tagMap.isEmpty(); - } - - /**+ - * Create a crash report which indicates a NBT read error. - */ - private CrashReport createCrashReport(final String key, final int expectedType, ClassCastException ex) { - CrashReport crashreport = CrashReport.makeCrashReport(ex, "Reading NBT data"); - CrashReportCategory crashreportcategory = crashreport.makeCategoryDepth("Corrupt NBT tag", 1); - crashreportcategory.addCrashSectionCallable("Tag type found", new Callable() { - public String call() throws Exception { - return NBTBase.NBT_TYPES[((NBTBase) NBTTagCompound.this.tagMap.get(key)).getId()]; - } - }); - crashreportcategory.addCrashSectionCallable("Tag type expected", new Callable() { - public String call() throws Exception { - return NBTBase.NBT_TYPES[expectedType]; - } - }); - crashreportcategory.addCrashSection("Tag name", key); - return crashreport; - } - - /**+ - * Creates a clone of the tag. - */ - public NBTBase copy() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - + void write(DataOutput parDataOutput) throws IOException { for (String s : this.tagMap.keySet()) { - nbttagcompound.setTag(s, ((NBTBase) this.tagMap.get(s)).copy()); - } - - return nbttagcompound; - } - - public boolean equals(Object object) { - if (super.equals(object)) { - NBTTagCompound nbttagcompound = (NBTTagCompound) object; - return this.tagMap.entrySet().equals(nbttagcompound.tagMap.entrySet()); - } else { - return false; - } - } - - public int hashCode() { - return super.hashCode() ^ this.tagMap.hashCode(); - } - - private static void writeEntry(String name, NBTBase data, DataOutput output) throws IOException { - output.writeByte(data.getId()); - if (data.getId() != 0) { - output.writeUTF(name); - data.write(output); - } - } - - private static byte readType(DataInput input, NBTSizeTracker sizeTracker) throws IOException { - return input.readByte(); - } - - private static String readKey(DataInput input, NBTSizeTracker sizeTracker) throws IOException { - return input.readUTF(); - } - - static NBTBase readNBT(byte id, String key, DataInput input, int depth, NBTSizeTracker sizeTracker) - throws IOException { - NBTBase nbtbase = NBTBase.createNewByType(id); - - try { - nbtbase.read(input, depth, sizeTracker); - return nbtbase; - } catch (IOException ioexception) { - CrashReport crashreport = CrashReport.makeCrashReport(ioexception, "Loading NBT data"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("NBT Tag"); - crashreportcategory.addCrashSection("Tag name", key); - crashreportcategory.addCrashSection("Tag type", Byte.valueOf(id)); - throw new ReportedException(crashreport); - } - } - - /**+ - * Merges this NBTTagCompound with the given compound. Any - * sub-compounds are merged using the same methods, other types - * of tags are overwritten from the given compound. - */ - public void merge(NBTTagCompound other) { - for (String s : other.tagMap.keySet()) { - NBTBase nbtbase = (NBTBase) other.tagMap.get(s); - if (nbtbase.getId() == 10) { - if (this.hasKey(s, 10)) { - NBTTagCompound nbttagcompound = this.getCompoundTag(s); - nbttagcompound.merge((NBTTagCompound) nbtbase); - } else { - this.setTag(s, nbtbase.copy()); - } - } else { - this.setTag(s, nbtbase.copy()); - } + NBTBase nbtbase = (NBTBase) this.tagMap.get(s); + writeEntry(s, nbtbase, parDataOutput); } + parDataOutput.writeByte(0); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagDouble.java b/src/game/java/net/minecraft/nbt/NBTTagDouble.java index 2b5463d3..81d0cc2e 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagDouble.java +++ b/src/game/java/net/minecraft/nbt/NBTTagDouble.java @@ -6,22 +6,25 @@ import java.io.IOException; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,32 +39,8 @@ public class NBTTagDouble extends NBTBase.NBTPrimitive { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeDouble(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(128L); - this.data = parDataInput.readDouble(); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 6; - } - - public String toString() { - return "" + this.data + "d"; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagDouble(this.data); @@ -76,23 +55,6 @@ public class NBTTagDouble extends NBTBase.NBTPrimitive { } } - public int hashCode() { - long i = Double.doubleToLongBits(this.data); - return super.hashCode() ^ (int) (i ^ i >>> 32); - } - - public long getLong() { - return (long) Math.floor(this.data); - } - - public int getInt() { - return MathHelper.floor_double(this.data); - } - - public short getShort() { - return (short) (MathHelper.floor_double(this.data) & '\uffff'); - } - public byte getByte() { return (byte) (MathHelper.floor_double(this.data) & 255); } @@ -104,4 +66,45 @@ public class NBTTagDouble extends NBTBase.NBTPrimitive { public float getFloat() { return (float) this.data; } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 6; + } + + public int getInt() { + return MathHelper.floor_double(this.data); + } + + public long getLong() { + return (long) Math.floor(this.data); + } + + public short getShort() { + return (short) (MathHelper.floor_double(this.data) & '\uffff'); + } + + public int hashCode() { + long i = Double.doubleToLongBits(this.data); + return super.hashCode() ^ (int) (i ^ i >>> 32); + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(128L); + this.data = parDataInput.readDouble(); + } + + public String toString() { + return "" + this.data + "d"; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeDouble(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagEnd.java b/src/game/java/net/minecraft/nbt/NBTTagEnd.java index 5f23292c..1a8b661c 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagEnd.java +++ b/src/game/java/net/minecraft/nbt/NBTTagEnd.java @@ -4,53 +4,56 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NBTTagEnd extends NBTBase { - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(64L); - } - - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes + /** + * + Creates a clone of the tag. */ - void write(DataOutput parDataOutput) throws IOException { + public NBTBase copy() { + return new NBTTagEnd(); } - /**+ - * Gets the type byte for the tag. + /** + * + Gets the type byte for the tag. */ public byte getId() { return (byte) 0; } + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(64L); + } + public String toString() { return "END"; } - /**+ - * Creates a clone of the tag. + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes */ - public NBTBase copy() { - return new NBTTagEnd(); + void write(DataOutput parDataOutput) throws IOException { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagFloat.java b/src/game/java/net/minecraft/nbt/NBTTagFloat.java index cf3a33f4..d241133c 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagFloat.java +++ b/src/game/java/net/minecraft/nbt/NBTTagFloat.java @@ -6,22 +6,25 @@ import java.io.IOException; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,32 +39,8 @@ public class NBTTagFloat extends NBTBase.NBTPrimitive { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeFloat(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(96L); - this.data = parDataInput.readFloat(); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 5; - } - - public String toString() { - return "" + this.data + "f"; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagFloat(this.data); @@ -76,22 +55,6 @@ public class NBTTagFloat extends NBTBase.NBTPrimitive { } } - public int hashCode() { - return super.hashCode() ^ Float.floatToIntBits(this.data); - } - - public long getLong() { - return (long) this.data; - } - - public int getInt() { - return MathHelper.floor_float(this.data); - } - - public short getShort() { - return (short) (MathHelper.floor_float(this.data) & '\uffff'); - } - public byte getByte() { return (byte) (MathHelper.floor_float(this.data) & 255); } @@ -103,4 +66,44 @@ public class NBTTagFloat extends NBTBase.NBTPrimitive { public float getFloat() { return this.data; } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 5; + } + + public int getInt() { + return MathHelper.floor_float(this.data); + } + + public long getLong() { + return (long) this.data; + } + + public short getShort() { + return (short) (MathHelper.floor_float(this.data) & '\uffff'); + } + + public int hashCode() { + return super.hashCode() ^ Float.floatToIntBits(this.data); + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(96L); + this.data = parDataInput.readFloat(); + } + + public String toString() { + return "" + this.data + "f"; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeFloat(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagInt.java b/src/game/java/net/minecraft/nbt/NBTTagInt.java index 6f5973da..8bc1fa02 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagInt.java +++ b/src/game/java/net/minecraft/nbt/NBTTagInt.java @@ -4,22 +4,25 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,32 +37,8 @@ public class NBTTagInt extends NBTBase.NBTPrimitive { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeInt(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(96L); - this.data = parDataInput.readInt(); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 3; - } - - public String toString() { - return "" + this.data; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagInt(this.data); @@ -74,22 +53,6 @@ public class NBTTagInt extends NBTBase.NBTPrimitive { } } - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public long getLong() { - return (long) this.data; - } - - public int getInt() { - return this.data; - } - - public short getShort() { - return (short) (this.data & '\uffff'); - } - public byte getByte() { return (byte) (this.data & 255); } @@ -101,4 +64,44 @@ public class NBTTagInt extends NBTBase.NBTPrimitive { public float getFloat() { return (float) this.data; } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 3; + } + + public int getInt() { + return this.data; + } + + public long getLong() { + return (long) this.data; + } + + public short getShort() { + return (short) (this.data & '\uffff'); + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(96L); + this.data = parDataInput.readInt(); + } + + public String toString() { + return "" + this.data; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeInt(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagIntArray.java b/src/game/java/net/minecraft/nbt/NBTTagIntArray.java index 0fed6dfe..8afe2808 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagIntArray.java +++ b/src/game/java/net/minecraft/nbt/NBTTagIntArray.java @@ -5,22 +5,25 @@ import java.io.DataOutput; import java.io.IOException; import java.util.Arrays; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,17 +38,32 @@ public class NBTTagIntArray extends NBTBase { this.intArray = parArrayOfInt; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes + /** + * + Creates a clone of the tag. */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeInt(this.intArray.length); + public NBTBase copy() { + int[] aint = new int[this.intArray.length]; + System.arraycopy(this.intArray, 0, aint, 0, this.intArray.length); + return new NBTTagIntArray(aint); + } - for (int i = 0; i < this.intArray.length; ++i) { - parDataOutput.writeInt(this.intArray[i]); - } + public boolean equals(Object object) { + return super.equals(object) ? Arrays.equals(this.intArray, ((NBTTagIntArray) object).intArray) : false; + } + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 11; + } + + public int[] getIntArray() { + return this.intArray; + } + + public int hashCode() { + return super.hashCode() ^ Arrays.hashCode(this.intArray); } void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { @@ -60,13 +78,6 @@ public class NBTTagIntArray extends NBTBase { } - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 11; - } - public String toString() { String s = "["; @@ -77,24 +88,16 @@ public class NBTTagIntArray extends NBTBase { return s + "]"; } - /**+ - * Creates a clone of the tag. + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes */ - public NBTBase copy() { - int[] aint = new int[this.intArray.length]; - System.arraycopy(this.intArray, 0, aint, 0, this.intArray.length); - return new NBTTagIntArray(aint); - } + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeInt(this.intArray.length); - public boolean equals(Object object) { - return super.equals(object) ? Arrays.equals(this.intArray, ((NBTTagIntArray) object).intArray) : false; - } + for (int i = 0; i < this.intArray.length; ++i) { + parDataOutput.writeInt(this.intArray[i]); + } - public int hashCode() { - return super.hashCode() ^ Arrays.hashCode(this.intArray); - } - - public int[] getIntArray() { - return this.intArray; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagList.java b/src/game/java/net/minecraft/nbt/NBTTagList.java index 82bfae39..8eab9738 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagList.java +++ b/src/game/java/net/minecraft/nbt/NBTTagList.java @@ -10,56 +10,163 @@ import com.google.common.collect.Lists; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NBTTagList extends NBTBase { private static final Logger LOGGER = LogManager.getLogger(); - /**+ - * The array list containing the tags encapsulated in this list. + /** + * + The array list containing the tags encapsulated in this list. */ private List tagList = Lists.newArrayList(); - /**+ - * The type byte for the tags in the list - they must all be of - * the same type. + /** + * + The type byte for the tags in the list - they must all be of the same type. */ private byte tagType = 0; - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes + /** + * + Adds the provided tag to the end of the list. There is no check to verify + * this tag is of the same type as any previous tag. */ - void write(DataOutput parDataOutput) throws IOException { - if (!this.tagList.isEmpty()) { - this.tagType = ((NBTBase) this.tagList.get(0)).getId(); + public void appendTag(NBTBase nbt) { + if (nbt.getId() == 0) { + LOGGER.warn("Invalid TagEnd added to ListTag"); } else { - this.tagType = 0; + if (this.tagType == 0) { + this.tagType = nbt.getId(); + } else if (this.tagType != nbt.getId()) { + LOGGER.warn("Adding mismatching tag types to tag list"); + return; + } + + this.tagList.add(nbt); + } + } + + /** + * + Creates a clone of the tag. + */ + public NBTBase copy() { + NBTTagList nbttaglist = new NBTTagList(); + nbttaglist.tagType = this.tagType; + + for (int i = 0, l = this.tagList.size(); i < l; ++i) { + NBTBase nbtbase1 = this.tagList.get(i).copy(); + nbttaglist.tagList.add(nbtbase1); } - parDataOutput.writeByte(this.tagType); - parDataOutput.writeInt(this.tagList.size()); + return nbttaglist; + } - for (int i = 0; i < this.tagList.size(); ++i) { - ((NBTBase) this.tagList.get(i)).write(parDataOutput); + public boolean equals(Object object) { + if (super.equals(object)) { + NBTTagList nbttaglist = (NBTTagList) object; + if (this.tagType == nbttaglist.tagType) { + return this.tagList.equals(nbttaglist.tagList); + } } + return false; + } + + /** + * + Get the tag at the given position + */ + public NBTBase get(int idx) { + return (NBTBase) (idx >= 0 && idx < this.tagList.size() ? (NBTBase) this.tagList.get(idx) : new NBTTagEnd()); + } + + /** + * + Retrieves the NBTTagCompound at the specified index in the list + */ + public NBTTagCompound getCompoundTagAt(int i) { + if (i >= 0 && i < this.tagList.size()) { + NBTBase nbtbase = (NBTBase) this.tagList.get(i); + return nbtbase.getId() == 10 ? (NBTTagCompound) nbtbase : new NBTTagCompound(); + } else { + return new NBTTagCompound(); + } + } + + public double getDoubleAt(int i) { + if (i >= 0 && i < this.tagList.size()) { + NBTBase nbtbase = (NBTBase) this.tagList.get(i); + return nbtbase.getId() == 6 ? ((NBTTagDouble) nbtbase).getDouble() : 0.0D; + } else { + return 0.0D; + } + } + + public float getFloatAt(int i) { + if (i >= 0 && i < this.tagList.size()) { + NBTBase nbtbase = (NBTBase) this.tagList.get(i); + return nbtbase.getId() == 5 ? ((NBTTagFloat) nbtbase).getFloat() : 0.0F; + } else { + return 0.0F; + } + } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 9; + } + + public int[] getIntArrayAt(int i) { + if (i >= 0 && i < this.tagList.size()) { + NBTBase nbtbase = (NBTBase) this.tagList.get(i); + return nbtbase.getId() == 11 ? ((NBTTagIntArray) nbtbase).getIntArray() : new int[0]; + } else { + return new int[0]; + } + } + + /** + * + Retrieves the tag String value at the specified index in the list + */ + public String getStringTagAt(int i) { + if (i >= 0 && i < this.tagList.size()) { + NBTBase nbtbase = (NBTBase) this.tagList.get(i); + return nbtbase.getId() == 8 ? nbtbase.getString() : nbtbase.toString(); + } else { + return ""; + } + } + + public int getTagType() { + return this.tagType; + } + + public int hashCode() { + return super.hashCode() ^ this.tagList.hashCode(); + } + + /** + * + Return whether this compound has no tags. + */ + public boolean hasNoTags() { + return this.tagList.isEmpty(); } void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { @@ -85,49 +192,15 @@ public class NBTTagList extends NBTBase { } } - /**+ - * Gets the type byte for the tag. + /** + * + Removes a tag at the given index. */ - public byte getId() { - return (byte) 9; + public NBTBase removeTag(int i) { + return (NBTBase) this.tagList.remove(i); } - public String toString() { - StringBuilder stringbuilder = new StringBuilder("["); - - for (int i = 0; i < this.tagList.size(); ++i) { - if (i != 0) { - stringbuilder.append(','); - } - - stringbuilder.append(i).append(':').append(this.tagList.get(i)); - } - - return stringbuilder.append(']').toString(); - } - - /**+ - * Adds the provided tag to the end of the list. There is no - * check to verify this tag is of the same type as any previous - * tag. - */ - public void appendTag(NBTBase nbt) { - if (nbt.getId() == 0) { - LOGGER.warn("Invalid TagEnd added to ListTag"); - } else { - if (this.tagType == 0) { - this.tagType = nbt.getId(); - } else if (this.tagType != nbt.getId()) { - LOGGER.warn("Adding mismatching tag types to tag list"); - return; - } - - this.tagList.add(nbt); - } - } - - /**+ - * Set the given index to the given tag + /** + * + Set the given index to the given tag */ public void set(int idx, NBTBase nbt) { if (nbt.getId() == 0) { @@ -146,118 +219,44 @@ public class NBTTagList extends NBTBase { } } - /**+ - * Removes a tag at the given index. - */ - public NBTBase removeTag(int i) { - return (NBTBase) this.tagList.remove(i); - } - - /**+ - * Return whether this compound has no tags. - */ - public boolean hasNoTags() { - return this.tagList.isEmpty(); - } - - /**+ - * Retrieves the NBTTagCompound at the specified index in the - * list - */ - public NBTTagCompound getCompoundTagAt(int i) { - if (i >= 0 && i < this.tagList.size()) { - NBTBase nbtbase = (NBTBase) this.tagList.get(i); - return nbtbase.getId() == 10 ? (NBTTagCompound) nbtbase : new NBTTagCompound(); - } else { - return new NBTTagCompound(); - } - } - - public int[] getIntArrayAt(int i) { - if (i >= 0 && i < this.tagList.size()) { - NBTBase nbtbase = (NBTBase) this.tagList.get(i); - return nbtbase.getId() == 11 ? ((NBTTagIntArray) nbtbase).getIntArray() : new int[0]; - } else { - return new int[0]; - } - } - - public double getDoubleAt(int i) { - if (i >= 0 && i < this.tagList.size()) { - NBTBase nbtbase = (NBTBase) this.tagList.get(i); - return nbtbase.getId() == 6 ? ((NBTTagDouble) nbtbase).getDouble() : 0.0D; - } else { - return 0.0D; - } - } - - public float getFloatAt(int i) { - if (i >= 0 && i < this.tagList.size()) { - NBTBase nbtbase = (NBTBase) this.tagList.get(i); - return nbtbase.getId() == 5 ? ((NBTTagFloat) nbtbase).getFloat() : 0.0F; - } else { - return 0.0F; - } - } - - /**+ - * Retrieves the tag String value at the specified index in the - * list - */ - public String getStringTagAt(int i) { - if (i >= 0 && i < this.tagList.size()) { - NBTBase nbtbase = (NBTBase) this.tagList.get(i); - return nbtbase.getId() == 8 ? nbtbase.getString() : nbtbase.toString(); - } else { - return ""; - } - } - - /**+ - * Get the tag at the given position - */ - public NBTBase get(int idx) { - return (NBTBase) (idx >= 0 && idx < this.tagList.size() ? (NBTBase) this.tagList.get(idx) : new NBTTagEnd()); - } - - /**+ - * Returns the number of tags in the list. + /** + * + Returns the number of tags in the list. */ public int tagCount() { return this.tagList.size(); } - /**+ - * Creates a clone of the tag. - */ - public NBTBase copy() { - NBTTagList nbttaglist = new NBTTagList(); - nbttaglist.tagType = this.tagType; + public String toString() { + StringBuilder stringbuilder = new StringBuilder("["); - for (int i = 0, l = this.tagList.size(); i < l; ++i) { - NBTBase nbtbase1 = this.tagList.get(i).copy(); - nbttaglist.tagList.add(nbtbase1); - } - - return nbttaglist; - } - - public boolean equals(Object object) { - if (super.equals(object)) { - NBTTagList nbttaglist = (NBTTagList) object; - if (this.tagType == nbttaglist.tagType) { - return this.tagList.equals(nbttaglist.tagList); + for (int i = 0; i < this.tagList.size(); ++i) { + if (i != 0) { + stringbuilder.append(','); } + + stringbuilder.append(i).append(':').append(this.tagList.get(i)); } - return false; + return stringbuilder.append(']').toString(); } - public int hashCode() { - return super.hashCode() ^ this.tagList.hashCode(); - } + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + if (!this.tagList.isEmpty()) { + this.tagType = ((NBTBase) this.tagList.get(0)).getId(); + } else { + this.tagType = 0; + } + + parDataOutput.writeByte(this.tagType); + parDataOutput.writeInt(this.tagList.size()); + + for (int i = 0; i < this.tagList.size(); ++i) { + ((NBTBase) this.tagList.get(i)).write(parDataOutput); + } - public int getTagType() { - return this.tagType; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagLong.java b/src/game/java/net/minecraft/nbt/NBTTagLong.java index 738ff07e..3f8f5aca 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagLong.java +++ b/src/game/java/net/minecraft/nbt/NBTTagLong.java @@ -4,22 +4,25 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,32 +37,8 @@ public class NBTTagLong extends NBTBase.NBTPrimitive { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeLong(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(128L); - this.data = parDataInput.readLong(); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 4; - } - - public String toString() { - return "" + this.data + "L"; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagLong(this.data); @@ -74,22 +53,6 @@ public class NBTTagLong extends NBTBase.NBTPrimitive { } } - public int hashCode() { - return super.hashCode() ^ (int) (this.data ^ this.data >>> 32); - } - - public long getLong() { - return this.data; - } - - public int getInt() { - return (int) (this.data & -1L); - } - - public short getShort() { - return (short) ((int) (this.data & 65535L)); - } - public byte getByte() { return (byte) ((int) (this.data & 255L)); } @@ -101,4 +64,44 @@ public class NBTTagLong extends NBTBase.NBTPrimitive { public float getFloat() { return (float) this.data; } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 4; + } + + public int getInt() { + return (int) (this.data & -1L); + } + + public long getLong() { + return this.data; + } + + public short getShort() { + return (short) ((int) (this.data & 65535L)); + } + + public int hashCode() { + return super.hashCode() ^ (int) (this.data ^ this.data >>> 32); + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(128L); + this.data = parDataInput.readLong(); + } + + public String toString() { + return "" + this.data + "L"; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeLong(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagShort.java b/src/game/java/net/minecraft/nbt/NBTTagShort.java index a92ac408..bccdec1c 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagShort.java +++ b/src/game/java/net/minecraft/nbt/NBTTagShort.java @@ -4,22 +4,25 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,32 +37,8 @@ public class NBTTagShort extends NBTBase.NBTPrimitive { this.data = data; } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeShort(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(80L); - this.data = parDataInput.readShort(); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 2; - } - - public String toString() { - return "" + this.data + "s"; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagShort(this.data); @@ -74,22 +53,6 @@ public class NBTTagShort extends NBTBase.NBTPrimitive { } } - public int hashCode() { - return super.hashCode() ^ this.data; - } - - public long getLong() { - return (long) this.data; - } - - public int getInt() { - return this.data; - } - - public short getShort() { - return this.data; - } - public byte getByte() { return (byte) (this.data & 255); } @@ -101,4 +64,44 @@ public class NBTTagShort extends NBTBase.NBTPrimitive { public float getFloat() { return (float) this.data; } + + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 2; + } + + public int getInt() { + return this.data; + } + + public long getLong() { + return (long) this.data; + } + + public short getShort() { + return this.data; + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(80L); + this.data = parDataInput.readShort(); + } + + public String toString() { + return "" + this.data + "s"; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeShort(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTTagString.java b/src/game/java/net/minecraft/nbt/NBTTagString.java index 47e376b1..9a39742e 100644 --- a/src/game/java/net/minecraft/nbt/NBTTagString.java +++ b/src/game/java/net/minecraft/nbt/NBTTagString.java @@ -4,22 +4,25 @@ import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,45 +41,13 @@ public class NBTTagString extends NBTBase { } } - /**+ - * Write the actual data contents of the tag, implemented in NBT - * extension classes - */ - void write(DataOutput parDataOutput) throws IOException { - parDataOutput.writeUTF(this.data); - } - - void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { - parNBTSizeTracker.read(288L); - this.data = parDataInput.readUTF(); - parNBTSizeTracker.read((long) (16 * this.data.length())); - } - - /**+ - * Gets the type byte for the tag. - */ - public byte getId() { - return (byte) 8; - } - - public String toString() { - return "\"" + this.data.replace("\"", "\\\"") + "\""; - } - - /**+ - * Creates a clone of the tag. + /** + * + Creates a clone of the tag. */ public NBTBase copy() { return new NBTTagString(this.data); } - /**+ - * Return whether this compound has no tags. - */ - public boolean hasNoTags() { - return this.data.isEmpty(); - } - public boolean equals(Object object) { if (!super.equals(object)) { return false; @@ -87,11 +58,43 @@ public class NBTTagString extends NBTBase { } } - public int hashCode() { - return super.hashCode() ^ this.data.hashCode(); + /** + * + Gets the type byte for the tag. + */ + public byte getId() { + return (byte) 8; } public String getString() { return this.data; } + + public int hashCode() { + return super.hashCode() ^ this.data.hashCode(); + } + + /** + * + Return whether this compound has no tags. + */ + public boolean hasNoTags() { + return this.data.isEmpty(); + } + + void read(DataInput parDataInput, int parInt1, NBTSizeTracker parNBTSizeTracker) throws IOException { + parNBTSizeTracker.read(288L); + this.data = parDataInput.readUTF(); + parNBTSizeTracker.read((long) (16 * this.data.length())); + } + + public String toString() { + return "\"" + this.data.replace("\"", "\\\"") + "\""; + } + + /** + * + Write the actual data contents of the tag, implemented in NBT extension + * classes + */ + void write(DataOutput parDataOutput) throws IOException { + parDataOutput.writeUTF(this.data); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/nbt/NBTUtil.java b/src/game/java/net/minecraft/nbt/NBTUtil.java index 211eeded..e5ca1414 100644 --- a/src/game/java/net/minecraft/nbt/NBTUtil.java +++ b/src/game/java/net/minecraft/nbt/NBTUtil.java @@ -4,117 +4,34 @@ import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.mojang.authlib.Property; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public final class NBTUtil { - /**+ - * Reads and returns a GameProfile that has been saved to the - * passed in NBTTagCompound - */ - public static GameProfile readGameProfileFromNBT(NBTTagCompound compound) { - String s = null; - String s1 = null; - if (compound.hasKey("Name", 8)) { - s = compound.getString("Name"); - } - - if (compound.hasKey("Id", 8)) { - s1 = compound.getString("Id"); - } - - if (StringUtils.isNullOrEmpty(s) && StringUtils.isNullOrEmpty(s1)) { - return null; - } else { - EaglercraftUUID uuid; - try { - uuid = EaglercraftUUID.fromString(s1); - } catch (Throwable var12) { - uuid = null; - } - - Multimap propertiesMap = MultimapBuilder.hashKeys().arrayListValues().build(); - if (compound.hasKey("Properties", 10)) { - NBTTagCompound nbttagcompound = compound.getCompoundTag("Properties"); - for (String s2 : nbttagcompound.getKeySet()) { - NBTTagList nbttaglist = nbttagcompound.getTagList(s2, 10); - for (int i = 0, l = nbttaglist.tagCount(); i < l; ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - String value = nbttagcompound1.getString("Value"); - if (!StringUtils.isNullOrEmpty(value)) { - String sig = nbttagcompound1.getString("Signature"); - if (!StringUtils.isNullOrEmpty(sig)) { - propertiesMap.put(s2, new Property(s2, value, sig)); - } else { - propertiesMap.put(s2, new Property(s2, value)); - } - } - } - } - } - - return new GameProfile(uuid, s, propertiesMap); - } - } - - /**+ - * Writes a GameProfile to an NBTTagCompound. - */ - public static NBTTagCompound writeGameProfile(NBTTagCompound tagCompound, GameProfile profile) { - if (!StringUtils.isNullOrEmpty(profile.getName())) { - tagCompound.setString("Name", profile.getName()); - } - - if (profile.getId() != null) { - tagCompound.setString("Id", profile.getId().toString()); - } - - Multimap propertiesMap = profile.getProperties(); - if (!propertiesMap.isEmpty()) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - for (String s : profile.getProperties().keySet()) { - NBTTagList nbttaglist = new NBTTagList(); - - for (Property property : profile.getProperties().get(s)) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setString("Value", property.getValue()); - if (property.hasSignature()) { - nbttagcompound1.setString("Signature", property.getSignature()); - } - - nbttaglist.appendTag(nbttagcompound1); - } - - nbttagcompound.setTag(s, nbttaglist); - } - tagCompound.setTag("Properties", nbttagcompound); - } - - return tagCompound; - } - public static boolean func_181123_a(NBTBase parNBTBase, NBTBase parNBTBase2, boolean parFlag) { if (parNBTBase == parNBTBase2) { return true; @@ -164,4 +81,89 @@ public final class NBTUtil { return parNBTBase.equals(parNBTBase2); } } + + /** + * + Reads and returns a GameProfile that has been saved to the passed in + * NBTTagCompound + */ + public static GameProfile readGameProfileFromNBT(NBTTagCompound compound) { + String s = null; + String s1 = null; + if (compound.hasKey("Name", 8)) { + s = compound.getString("Name"); + } + + if (compound.hasKey("Id", 8)) { + s1 = compound.getString("Id"); + } + + if (StringUtils.isNullOrEmpty(s) && StringUtils.isNullOrEmpty(s1)) { + return null; + } else { + EaglercraftUUID uuid; + try { + uuid = EaglercraftUUID.fromString(s1); + } catch (Throwable var12) { + uuid = null; + } + + Multimap propertiesMap = MultimapBuilder.hashKeys().arrayListValues().build(); + if (compound.hasKey("Properties", 10)) { + NBTTagCompound nbttagcompound = compound.getCompoundTag("Properties"); + for (String s2 : nbttagcompound.getKeySet()) { + NBTTagList nbttaglist = nbttagcompound.getTagList(s2, 10); + for (int i = 0, l = nbttaglist.tagCount(); i < l; ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + String value = nbttagcompound1.getString("Value"); + if (!StringUtils.isNullOrEmpty(value)) { + String sig = nbttagcompound1.getString("Signature"); + if (!StringUtils.isNullOrEmpty(sig)) { + propertiesMap.put(s2, new Property(s2, value, sig)); + } else { + propertiesMap.put(s2, new Property(s2, value)); + } + } + } + } + } + + return new GameProfile(uuid, s, propertiesMap); + } + } + + /** + * + Writes a GameProfile to an NBTTagCompound. + */ + public static NBTTagCompound writeGameProfile(NBTTagCompound tagCompound, GameProfile profile) { + if (!StringUtils.isNullOrEmpty(profile.getName())) { + tagCompound.setString("Name", profile.getName()); + } + + if (profile.getId() != null) { + tagCompound.setString("Id", profile.getId().toString()); + } + + Multimap propertiesMap = profile.getProperties(); + if (!propertiesMap.isEmpty()) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + for (String s : profile.getProperties().keySet()) { + NBTTagList nbttaglist = new NBTTagList(); + + for (Property property : profile.getProperties().get(s)) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setString("Value", property.getValue()); + if (property.hasSignature()) { + nbttagcompound1.setString("Signature", property.getSignature()); + } + + nbttaglist.appendTag(nbttagcompound1); + } + + nbttagcompound.setTag(s, nbttaglist); + } + tagCompound.setTag("Properties", nbttagcompound); + } + + return tagCompound; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/EnumConnectionState.java b/src/game/java/net/minecraft/network/EnumConnectionState.java index d117c287..3e6ef177 100644 --- a/src/game/java/net/minecraft/network/EnumConnectionState.java +++ b/src/game/java/net/minecraft/network/EnumConnectionState.java @@ -1,11 +1,13 @@ package net.minecraft.network; +import java.util.Collection; +import java.util.Map; + import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Maps; -import java.util.Collection; -import java.util.Map; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.minecraft.network.handshake.client.C00Handshake; import net.minecraft.network.login.client.C00PacketLoginStart; import net.minecraft.network.login.client.C01PacketEncryptionResponse; @@ -107,24 +109,26 @@ import net.minecraft.network.play.server.S46PacketSetCompressionLevel; import net.minecraft.network.play.server.S47PacketPlayerListHeaderFooter; import net.minecraft.network.play.server.S48PacketResourcePackSend; import net.minecraft.network.play.server.S49PacketUpdateEntityNBT; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -255,54 +259,6 @@ public enum EnumConnectionState { private static final EnumConnectionState[] STATES_BY_ID = new EnumConnectionState[field_181137_f - field_181136_e + 1]; private static final Map, EnumConnectionState> STATES_BY_CLASS = Maps.newHashMap(); - private final int id; - private final Map>> directionMaps; - - private EnumConnectionState(int protocolId) { - this.directionMaps = Maps.newEnumMap(EnumPacketDirection.class); - this.id = protocolId; - } - - protected EnumConnectionState registerPacket(EnumPacketDirection direction, Class packetClass) { - Object object = (BiMap) this.directionMaps.get(direction); - if (object == null) { - object = HashBiMap.create(); - this.directionMaps.put(direction, (BiMap>) object); - } - - if (((BiMap) object).containsValue(packetClass)) { - String s = direction + " packet " + packetClass + " is already known to ID " - + ((BiMap) object).inverse().get(packetClass); - LogManager.getLogger().fatal(s); - throw new IllegalArgumentException(s); - } else { - ((BiMap) object).put(Integer.valueOf(((BiMap) object).size()), packetClass); - return this; - } - } - - public Integer getPacketId(EnumPacketDirection direction, Packet packetIn) { - return (Integer) ((BiMap) this.directionMaps.get(direction)).inverse().get(packetIn.getClass()); - } - - public Packet getPacket(EnumPacketDirection direction, int packetId) - throws IllegalAccessException, InstantiationException { - Class oclass = (Class) ((BiMap) this.directionMaps.get(direction)).get(Integer.valueOf(packetId)); - return oclass == null ? null : (Packet) oclass.newInstance(); - } - - public int getId() { - return this.id; - } - - public static EnumConnectionState getById(int stateId) { - return stateId >= field_181136_e && stateId <= field_181137_f ? STATES_BY_ID[stateId - field_181136_e] : null; - } - - public static EnumConnectionState getFromPacket(Packet packetIn) { - return (EnumConnectionState) STATES_BY_CLASS.get(packetIn.getClass()); - } - static { EnumConnectionState[] states = values(); for (int j = 0; j < states.length; ++j) { @@ -334,4 +290,53 @@ public enum EnumConnectionState { } } + + public static EnumConnectionState getById(int stateId) { + return stateId >= field_181136_e && stateId <= field_181137_f ? STATES_BY_ID[stateId - field_181136_e] : null; + } + + public static EnumConnectionState getFromPacket(Packet packetIn) { + return (EnumConnectionState) STATES_BY_CLASS.get(packetIn.getClass()); + } + + private final int id; + + private final Map>> directionMaps; + + private EnumConnectionState(int protocolId) { + this.directionMaps = Maps.newEnumMap(EnumPacketDirection.class); + this.id = protocolId; + } + + public int getId() { + return this.id; + } + + public Packet getPacket(EnumPacketDirection direction, int packetId) + throws IllegalAccessException, InstantiationException { + Class oclass = (Class) ((BiMap) this.directionMaps.get(direction)).get(Integer.valueOf(packetId)); + return oclass == null ? null : (Packet) oclass.newInstance(); + } + + public Integer getPacketId(EnumPacketDirection direction, Packet packetIn) { + return (Integer) ((BiMap) this.directionMaps.get(direction)).inverse().get(packetIn.getClass()); + } + + protected EnumConnectionState registerPacket(EnumPacketDirection direction, Class packetClass) { + Object object = (BiMap) this.directionMaps.get(direction); + if (object == null) { + object = HashBiMap.create(); + this.directionMaps.put(direction, (BiMap>) object); + } + + if (((BiMap) object).containsValue(packetClass)) { + String s = direction + " packet " + packetClass + " is already known to ID " + + ((BiMap) object).inverse().get(packetClass); + LogManager.getLogger().fatal(s); + throw new IllegalArgumentException(s); + } else { + ((BiMap) object).put(Integer.valueOf(((BiMap) object).size()), packetClass); + return this; + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/EnumPacketDirection.java b/src/game/java/net/minecraft/network/EnumPacketDirection.java index fc17acb7..e1ce8aca 100644 --- a/src/game/java/net/minecraft/network/EnumPacketDirection.java +++ b/src/game/java/net/minecraft/network/EnumPacketDirection.java @@ -1,21 +1,24 @@ package net.minecraft.network; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/network/INetHandler.java b/src/game/java/net/minecraft/network/INetHandler.java index 2fdd5cdf..67578d4c 100644 --- a/src/game/java/net/minecraft/network/INetHandler.java +++ b/src/game/java/net/minecraft/network/INetHandler.java @@ -2,30 +2,33 @@ package net.minecraft.network; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface INetHandler { - /**+ - * Invoked when disconnecting, the parameter is a ChatComponent - * describing the reason for termination + /** + * + Invoked when disconnecting, the parameter is a ChatComponent describing the + * reason for termination */ void onDisconnect(IChatComponent var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/NetHandlerPlayServer.java b/src/game/java/net/minecraft/network/NetHandlerPlayServer.java index b6c8d26f..d2d6b673 100644 --- a/src/game/java/net/minecraft/network/NetHandlerPlayServer.java +++ b/src/game/java/net/minecraft/network/NetHandlerPlayServer.java @@ -1,13 +1,5 @@ package net.minecraft.network; -import com.google.common.collect.Lists; -import com.google.common.primitives.Doubles; -import com.google.common.primitives.Floats; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.client.GameProtocolMessageController; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; - import java.io.IOException; import java.util.ArrayList; import java.util.Collections; @@ -15,6 +7,20 @@ import java.util.List; import java.util.Set; import java.util.concurrent.Callable; +import org.apache.commons.lang3.StringUtils; + +import com.google.common.collect.Lists; +import com.google.common.primitives.Doubles; +import com.google.common.primitives.Floats; + +import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.client.GameProtocolMessageController; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; +import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; import net.minecraft.block.material.Material; import net.minecraft.command.server.CommandBlockLogic; import net.minecraft.crash.CrashReport; @@ -91,30 +97,26 @@ import net.minecraft.util.ITickable; import net.minecraft.util.IntHashMap; import net.minecraft.util.ReportedException; import net.minecraft.world.WorldServer; -import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; -import org.apache.commons.lang3.StringUtils; - -import net.lax1dude.eaglercraft.v1_8.EagRuntime; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -151,80 +153,8 @@ public class NetHandlerPlayServer implements INetHandlerPlayServer, ITickable { playerIn.playerNetServerHandler = this; } - public GameProtocolMessageController getEaglerMessageController() { - return eaglerMessageController; - } - - public void setEaglerMessageController(GameProtocolMessageController eaglerMessageController) { - this.eaglerMessageController = eaglerMessageController; - } - - public GamePluginMessageProtocol getEaglerMessageProtocol() { - return eaglerMessageController != null ? eaglerMessageController.protocol : null; - } - - public void sendEaglerMessage(GameMessagePacket packet) { - try { - eaglerMessageController.sendPacket(packet); - } catch (IOException e) { - logger.error("Failed to send eaglercraft plugin message packet: " + packet); - logger.error(e); - } - } - - /**+ - * Like the old updateEntity(), except more generic. - */ - public void update() { - this.field_147366_g = false; - ++this.networkTickCount; - if ((long) this.networkTickCount - this.lastSentPingPacket > 40L) { - this.lastSentPingPacket = (long) this.networkTickCount; - this.lastPingTime = this.currentTimeMillis(); - this.field_147378_h = (int) this.lastPingTime; - this.sendPacket(new S00PacketKeepAlive(this.field_147378_h)); - } - - if (this.chatSpamThresholdCount > 0) { - --this.chatSpamThresholdCount; - } - - if (this.itemDropThreshold > 0) { - --this.itemDropThreshold; - } - - if (this.playerEntity.getLastActiveTime() > 0L && this.serverController.getMaxPlayerIdleMinutes() > 0 - && MinecraftServer.getCurrentTimeMillis() - this.playerEntity - .getLastActiveTime() > (long) (this.serverController.getMaxPlayerIdleMinutes() * 1000 * 60)) { - this.kickPlayerFromServer("You have been idle for too long!"); - } - - if (this.eaglerMessageController != null) { - this.eaglerMessageController.flush(); - } - } - - public IntegratedServerPlayerNetworkManager getNetworkManager() { - return this.netManager; - } - - /**+ - * Kick a player from the server with a reason - */ - public void kickPlayerFromServer(String reason) { - final ChatComponentText chatcomponenttext = new ChatComponentText(reason); - this.netManager.sendPacket(new S40PacketDisconnect(chatcomponenttext)); - this.netManager.closeChannel(chatcomponenttext); - } - - /**+ - * Processes player movement input. Includes walking, strafing, - * jumping, sneaking; excludes riding and toggling - * flying/sprinting - */ - public void processInput(C0CPacketInput c0cpacketinput) { - this.playerEntity.setEntityActionState(c0cpacketinput.getStrafeSpeed(), c0cpacketinput.getForwardSpeed(), - c0cpacketinput.isJumping(), c0cpacketinput.isSneaking()); + private long currentTimeMillis() { + return EagRuntime.steadyTimeMillis(); } private boolean func_183006_b(C03PacketPlayer parC03PacketPlayer) { @@ -234,9 +164,415 @@ public class NetHandlerPlayServer implements INetHandlerPlayServer, ITickable { || !Floats.isFinite(parC03PacketPlayer.getPitch()) || !Floats.isFinite(parC03PacketPlayer.getYaw()); } - /**+ - * Processes clients perspective on player positioning and/or - * orientation + public GameProtocolMessageController getEaglerMessageController() { + return eaglerMessageController; + } + + public GamePluginMessageProtocol getEaglerMessageProtocol() { + return eaglerMessageController != null ? eaglerMessageController.protocol : null; + } + + public IntegratedServerPlayerNetworkManager getNetworkManager() { + return this.netManager; + } + + public void handleAnimation(C0APacketAnimation c0apacketanimation) { + this.playerEntity.markPlayerActive(); + this.playerEntity.swingItem(); + } + + public void handleResourcePackStatus(C19PacketResourcePackStatus var1) { + } + + /** + * + Handle commands that start with a / + */ + private void handleSlashCommand(String command) { + this.serverController.getCommandManager().executeCommand(this.playerEntity, command); + } + + public void handleSpectate(C18PacketSpectate c18packetspectate) { + if (this.playerEntity.isSpectator()) { + Entity entity = null; + + WorldServer[] srv = this.serverController.worldServers; + for (int i = 0; i < srv.length; ++i) { + WorldServer worldserver = srv[i]; + if (worldserver != null) { + entity = c18packetspectate.getEntity(worldserver); + if (entity != null) { + break; + } + } + } + + if (entity != null) { + this.playerEntity.setSpectatingEntity(this.playerEntity); + this.playerEntity.mountEntity((Entity) null); + if (entity.worldObj != this.playerEntity.worldObj) { + WorldServer worldserver1 = this.playerEntity.getServerForPlayer(); + WorldServer worldserver2 = (WorldServer) entity.worldObj; + this.playerEntity.dimension = entity.dimension; + this.sendPacket(new S07PacketRespawn(this.playerEntity.dimension, worldserver1.getDifficulty(), + worldserver1.getWorldInfo().getTerrainType(), + this.playerEntity.theItemInWorldManager.getGameType())); + worldserver1.removePlayerEntityDangerously(this.playerEntity); + this.playerEntity.isDead = false; + this.playerEntity.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, entity.rotationYaw, + entity.rotationPitch); + if (this.playerEntity.isEntityAlive()) { + worldserver1.updateEntityWithOptionalForce(this.playerEntity, false); + worldserver2.spawnEntityInWorld(this.playerEntity); + worldserver2.updateEntityWithOptionalForce(this.playerEntity, false); + } + + this.playerEntity.setWorld(worldserver2); + this.serverController.getConfigurationManager().preparePlayer(this.playerEntity, worldserver1); + this.playerEntity.setPositionAndUpdate(entity.posX, entity.posY, entity.posZ); + this.playerEntity.theItemInWorldManager.setWorld(worldserver2); + this.serverController.getConfigurationManager().updateTimeAndWeatherForPlayer(this.playerEntity, + worldserver2); + this.serverController.getConfigurationManager().syncPlayerInventory(this.playerEntity); + } else { + this.playerEntity.setPositionAndUpdate(entity.posX, entity.posY, entity.posZ); + } + } + } + + } + + /** + * + Kick a player from the server with a reason + */ + public void kickPlayerFromServer(String reason) { + final ChatComponentText chatcomponenttext = new ChatComponentText(reason); + this.netManager.sendPacket(new S40PacketDisconnect(chatcomponenttext)); + this.netManager.closeChannel(chatcomponenttext); + } + + /** + * + Invoked when disconnecting, the parameter is a ChatComponent describing the + * reason for termination + */ + public void onDisconnect(IChatComponent ichatcomponent) { + if (!hasDisconnected) { + hasDisconnected = true; + logger.info(this.playerEntity.getName() + " lost connection: " + ichatcomponent); + this.serverController.refreshStatusNextTick(); + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("multiplayer.player.left", + new Object[] { this.playerEntity.getDisplayName() }); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.YELLOW); + this.serverController.getConfigurationManager().sendChatMsg(chatcomponenttranslation); + this.playerEntity.mountEntityAndWakeUp(); + this.serverController.getConfigurationManager().playerLoggedOut(this.playerEntity); + if (this.playerEntity.getName().equals(this.serverController.getServerOwner())) { + logger.info("Stopping singleplayer server as player logged out"); + this.serverController.initiateShutdown(); + } + } + } + + /** + * + Process chat messages (broadcast back to clients) and commands (executes) + */ + public void processChatMessage(C01PacketChatMessage c01packetchatmessage) { + if (this.playerEntity.getChatVisibility() == EntityPlayer.EnumChatVisibility.HIDDEN) { + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("chat.cannotSend", + new Object[0]); + chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); + this.sendPacket(new S02PacketChat(chatcomponenttranslation)); + } else { + this.playerEntity.markPlayerActive(); + String s = c01packetchatmessage.getMessage(); + s = StringUtils.normalizeSpace(s); + + for (int i = 0; i < s.length(); ++i) { + if (!ChatAllowedCharacters.isAllowedCharacter(s.charAt(i))) { + this.kickPlayerFromServer("Illegal characters in chat"); + return; + } + } + + if (s.startsWith("/")) { + this.handleSlashCommand(s); + } else { + if (this.serverController.worldServers[0].getWorldInfo().getGameRulesInstance() + .getBoolean("colorCodes")) { + s = net.minecraft.util.StringUtils.translateControlCodesAlternate(s); + } + ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation("chat.type.text", + new Object[] { this.playerEntity.getDisplayName(), s }); + this.serverController.getConfigurationManager().sendChatMsgImpl(chatcomponenttranslation1, false); + } + + this.chatSpamThresholdCount += 20; + if (this.chatSpamThresholdCount > 200 && !this.serverController.getConfigurationManager() + .canSendCommands(this.playerEntity.getGameProfile())) { + this.kickPlayerFromServer("disconnect.spam"); + } + + } + } + + /** + * + Executes a container/inventory slot manipulation as indicated by the + * packet. Sends the serverside result if they didn't match the indicated result + * and prevents further manipulation by the player until he confirms that it has + * the same open container/inventory + */ + public void processClickWindow(C0EPacketClickWindow c0epacketclickwindow) { + this.playerEntity.markPlayerActive(); + if (this.playerEntity.openContainer.windowId == c0epacketclickwindow.getWindowId() + && this.playerEntity.openContainer.getCanCraft(this.playerEntity)) { + if (this.playerEntity.isSpectator()) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < this.playerEntity.openContainer.inventorySlots.size(); ++i) { + arraylist.add(((Slot) this.playerEntity.openContainer.inventorySlots.get(i)).getStack()); + } + + this.playerEntity.updateCraftingInventory(this.playerEntity.openContainer, arraylist); + } else { + ItemStack itemstack = this.playerEntity.openContainer.slotClick(c0epacketclickwindow.getSlotId(), + c0epacketclickwindow.getUsedButton(), c0epacketclickwindow.getMode(), this.playerEntity); + if (ItemStack.areItemStacksEqual(c0epacketclickwindow.getClickedItem(), itemstack)) { + this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction( + c0epacketclickwindow.getWindowId(), c0epacketclickwindow.getActionNumber(), true)); + this.playerEntity.isChangingQuantityOnly = true; + this.playerEntity.openContainer.detectAndSendChanges(); + this.playerEntity.updateHeldItem(); + this.playerEntity.isChangingQuantityOnly = false; + } else { + this.field_147372_n.addKey(this.playerEntity.openContainer.windowId, + Short.valueOf(c0epacketclickwindow.getActionNumber())); + this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction( + c0epacketclickwindow.getWindowId(), c0epacketclickwindow.getActionNumber(), false)); + this.playerEntity.openContainer.setCanCraft(this.playerEntity, false); + ArrayList arraylist1 = Lists.newArrayList(); + + for (int j = 0; j < this.playerEntity.openContainer.inventorySlots.size(); ++j) { + arraylist1.add(((Slot) this.playerEntity.openContainer.inventorySlots.get(j)).getStack()); + } + + this.playerEntity.updateCraftingInventory(this.playerEntity.openContainer, arraylist1); + } + } + } + + } + + /** + * + Updates serverside copy of client settings: language, render distance, chat + * visibility, chat colours, difficulty, and whether to show the cape + */ + public void processClientSettings(C15PacketClientSettings c15packetclientsettings) { + this.playerEntity.handleClientSettings(c15packetclientsettings); + } + + /** + * + Processes the client status updates: respawn attempt from player, opening + * statistics or achievements, or acquiring 'open inventory' achievement + */ + public void processClientStatus(C16PacketClientStatus c16packetclientstatus) { + this.playerEntity.markPlayerActive(); + C16PacketClientStatus.EnumState c16packetclientstatus$enumstate = c16packetclientstatus.getStatus(); + switch (c16packetclientstatus$enumstate) { + case PERFORM_RESPAWN: + if (this.playerEntity.playerConqueredTheEnd) { + this.playerEntity = this.serverController.getConfigurationManager() + .recreatePlayerEntity(this.playerEntity, 0, true); + } else if (this.playerEntity.getServerForPlayer().getWorldInfo().isHardcoreModeEnabled()) { + if (this.serverController.isSinglePlayer() + && this.playerEntity.getName().equals(this.serverController.getServerOwner())) { + this.playerEntity.playerNetServerHandler + .kickPlayerFromServer("You have died. Game over, man, it\'s game over!"); + this.serverController.deleteWorldAndStopServer(); + } else { + this.playerEntity.playerNetServerHandler + .kickPlayerFromServer("You have died. Game over, man, it\'s game over!"); + } + } else { + if (this.playerEntity.getHealth() > 0.0F) { + return; + } + + this.playerEntity = this.serverController.getConfigurationManager() + .recreatePlayerEntity(this.playerEntity, 0, false); + } + break; + case REQUEST_STATS: + this.playerEntity.getStatFile().func_150876_a(this.playerEntity); + break; + case OPEN_INVENTORY_ACHIEVEMENT: + this.playerEntity.triggerAchievement(AchievementList.openInventory); + } + + } + + /** + * + Processes the client closing windows (container) + */ + public void processCloseWindow(C0DPacketCloseWindow c0dpacketclosewindow) { + this.playerEntity.closeContainer(); + } + + /** + * + Received in response to the server requesting to confirm that the + * client-side open container matches the servers' after a mismatched + * container-slot manipulation. It will unlock the player's ability to + * manipulate the container contents + */ + public void processConfirmTransaction(C0FPacketConfirmTransaction c0fpacketconfirmtransaction) { + Short oshort = (Short) this.field_147372_n.lookup(this.playerEntity.openContainer.windowId); + if (oshort != null && c0fpacketconfirmtransaction.getUid() == oshort.shortValue() + && this.playerEntity.openContainer.windowId == c0fpacketconfirmtransaction.getWindowId() + && !this.playerEntity.openContainer.getCanCraft(this.playerEntity) + && !this.playerEntity.isSpectator()) { + this.playerEntity.openContainer.setCanCraft(this.playerEntity, true); + } + + } + + /** + * + Update the server with an ItemStack in a slot. + */ + public void processCreativeInventoryAction(C10PacketCreativeInventoryAction c10packetcreativeinventoryaction) { + if (this.playerEntity.theItemInWorldManager.isCreative()) { + boolean flag = c10packetcreativeinventoryaction.getSlotId() < 0; + ItemStack itemstack = c10packetcreativeinventoryaction.getStack(); + if (itemstack != null && itemstack.hasTagCompound() + && itemstack.getTagCompound().hasKey("BlockEntityTag", 10)) { + NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("BlockEntityTag"); + if (nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z")) { + BlockPos blockpos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), + nbttagcompound.getInteger("z")); + TileEntity tileentity = this.playerEntity.worldObj.getTileEntity(blockpos); + if (tileentity != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + tileentity.writeToNBT(nbttagcompound1); + nbttagcompound1.removeTag("x"); + nbttagcompound1.removeTag("y"); + nbttagcompound1.removeTag("z"); + itemstack.setTagInfo("BlockEntityTag", nbttagcompound1); + } + } + } + + boolean flag1 = c10packetcreativeinventoryaction.getSlotId() >= 1 + && c10packetcreativeinventoryaction.getSlotId() < 36 + InventoryPlayer.getHotbarSize(); + boolean flag2 = itemstack == null || itemstack.getItem() != null; + boolean flag3 = itemstack == null + || itemstack.getMetadata() >= 0 && itemstack.stackSize <= 64 && itemstack.stackSize > 0; + if (flag1 && flag2 && flag3) { + if (itemstack == null) { + this.playerEntity.inventoryContainer.putStackInSlot(c10packetcreativeinventoryaction.getSlotId(), + (ItemStack) null); + } else { + this.playerEntity.inventoryContainer.putStackInSlot(c10packetcreativeinventoryaction.getSlotId(), + itemstack); + } + + this.playerEntity.inventoryContainer.setCanCraft(this.playerEntity, true); + } else if (flag && flag2 && flag3 && this.itemDropThreshold < 200) { + this.itemDropThreshold += 20; + EntityItem entityitem = this.playerEntity.dropPlayerItemWithRandomChoice(itemstack, true); + if (entityitem != null) { + entityitem.setAgeToCreativeDespawnTime(); + } + } + } + + } + + /** + * + Enchants the item identified by the packet given some convoluted conditions + * (matching window, which should/shouldn't be in use?) + */ + public void processEnchantItem(C11PacketEnchantItem c11packetenchantitem) { + this.playerEntity.markPlayerActive(); + if (this.playerEntity.openContainer.windowId == c11packetenchantitem.getWindowId() + && this.playerEntity.openContainer.getCanCraft(this.playerEntity) && !this.playerEntity.isSpectator()) { + this.playerEntity.openContainer.enchantItem(this.playerEntity, c11packetenchantitem.getButton()); + this.playerEntity.openContainer.detectAndSendChanges(); + } + + } + + /** + * + Processes a range of action-types: sneaking, sprinting, waking from sleep, + * opening the inventory or setting jump height of the horse the player is + * riding + */ + public void processEntityAction(C0BPacketEntityAction c0bpacketentityaction) { + this.playerEntity.markPlayerActive(); + switch (c0bpacketentityaction.getAction()) { + case START_SNEAKING: + this.playerEntity.setSneaking(true); + break; + case STOP_SNEAKING: + this.playerEntity.setSneaking(false); + break; + case START_SPRINTING: + this.playerEntity.setSprinting(true); + break; + case STOP_SPRINTING: + this.playerEntity.setSprinting(false); + break; + case STOP_SLEEPING: + this.playerEntity.wakeUpPlayer(false, true, true); + this.hasMoved = false; + break; + case RIDING_JUMP: + if (this.playerEntity.ridingEntity instanceof EntityHorse) { + ((EntityHorse) this.playerEntity.ridingEntity).setJumpPower(c0bpacketentityaction.getAuxData()); + } + break; + case OPEN_INVENTORY: + if (this.playerEntity.ridingEntity instanceof EntityHorse) { + ((EntityHorse) this.playerEntity.ridingEntity).openGUI(this.playerEntity); + } + break; + default: + throw new IllegalArgumentException("Invalid client command!"); + } + + } + + /** + * + Updates which quickbar slot is selected + */ + public void processHeldItemChange(C09PacketHeldItemChange c09packethelditemchange) { + if (c09packethelditemchange.getSlotId() >= 0 + && c09packethelditemchange.getSlotId() < InventoryPlayer.getHotbarSize()) { + this.playerEntity.inventory.currentItem = c09packethelditemchange.getSlotId(); + this.playerEntity.markPlayerActive(); + } else { + logger.warn(this.playerEntity.getName() + " tried to set an invalid carried item"); + } + } + + /** + * + Processes player movement input. Includes walking, strafing, jumping, + * sneaking; excludes riding and toggling flying/sprinting + */ + public void processInput(C0CPacketInput c0cpacketinput) { + this.playerEntity.setEntityActionState(c0cpacketinput.getStrafeSpeed(), c0cpacketinput.getForwardSpeed(), + c0cpacketinput.isJumping(), c0cpacketinput.isSneaking()); + } + + /** + * + Updates a players' ping statistics + */ + public void processKeepAlive(C00PacketKeepAlive c00packetkeepalive) { + if (c00packetkeepalive.getKey() == this.field_147378_h) { + int i = (int) (this.currentTimeMillis() - this.lastPingTime); + this.playerEntity.ping = (this.playerEntity.ping * 3 + i) / 4; + } + + } + + /** + * + Processes clients perspective on player positioning and/or orientation */ public void processPlayer(C03PacketPlayer c03packetplayer) { if (this.func_183006_b(c03packetplayer)) { @@ -429,115 +765,16 @@ public class NetHandlerPlayServer implements INetHandlerPlayServer, ITickable { } } - public void setPlayerLocation(double x, double y, double z, float yaw, float pitch) { - this.setPlayerLocation(x, y, z, yaw, pitch, Collections.emptySet()); - } - - public void setPlayerLocation(double x, double y, double z, float yaw, float pitch, - Set relativeSet) { - this.hasMoved = false; - this.lastPosX = x; - this.lastPosY = y; - this.lastPosZ = z; - if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.X)) { - this.lastPosX += this.playerEntity.posX; - } - - if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.Y)) { - this.lastPosY += this.playerEntity.posY; - } - - if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.Z)) { - this.lastPosZ += this.playerEntity.posZ; - } - - float f = yaw; - float f1 = pitch; - if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.Y_ROT)) { - f = yaw + this.playerEntity.rotationYaw; - } - - if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.X_ROT)) { - f1 = pitch + this.playerEntity.rotationPitch; - } - - this.playerEntity.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, f, f1); - this.playerEntity.playerNetServerHandler - .sendPacket(new S08PacketPlayerPosLook(x, y, z, yaw, pitch, relativeSet)); - } - - /**+ - * Processes the player initiating/stopping digging on a - * particular spot, as well as a player dropping items?. (0: - * initiated, 1: reinitiated, 2? , 3-4 drop item (respectively - * without or with player control), 5: stopped; x,y,z, side - * clicked on;) + /** + * + Processes a player starting/stopping flying */ - public void processPlayerDigging(C07PacketPlayerDigging c07packetplayerdigging) { - WorldServer worldserver = this.serverController.worldServerForDimension(this.playerEntity.dimension); - BlockPos blockpos = c07packetplayerdigging.getPosition(); - this.playerEntity.markPlayerActive(); - switch (c07packetplayerdigging.getStatus()) { - case DROP_ITEM: - if (!this.playerEntity.isSpectator()) { - this.playerEntity.dropOneItem(false); - } - - return; - case DROP_ALL_ITEMS: - if (!this.playerEntity.isSpectator()) { - this.playerEntity.dropOneItem(true); - } - - return; - case RELEASE_USE_ITEM: - this.playerEntity.stopUsingItem(); - return; - case START_DESTROY_BLOCK: - case ABORT_DESTROY_BLOCK: - case STOP_DESTROY_BLOCK: - double d0 = this.playerEntity.posX - ((double) blockpos.getX() + 0.5D); - double d1 = this.playerEntity.posY - ((double) blockpos.getY() + 0.5D) + 1.5D; - double d2 = this.playerEntity.posZ - ((double) blockpos.getZ() + 0.5D); - double d3 = d0 * d0 + d1 * d1 + d2 * d2; - if (d3 > 36.0D) { - return; - } else if (blockpos.getY() >= this.serverController.getBuildLimit()) { - return; - } else { - if (c07packetplayerdigging.getStatus() == C07PacketPlayerDigging.Action.START_DESTROY_BLOCK) { - if (!this.serverController.isBlockProtected(worldserver, blockpos, this.playerEntity) - && worldserver.getWorldBorder().contains(blockpos)) { - this.playerEntity.theItemInWorldManager.onBlockClicked(blockpos, - c07packetplayerdigging.getFacing()); - } else { - this.playerEntity.playerNetServerHandler - .sendPacket(new S23PacketBlockChange(worldserver, blockpos)); - } - } else { - if (c07packetplayerdigging.getStatus() == C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK) { - this.playerEntity.theItemInWorldManager.blockRemoving(blockpos); - } else if (c07packetplayerdigging - .getStatus() == C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK) { - this.playerEntity.theItemInWorldManager.cancelDestroyingBlock(); - } - - if (worldserver.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { - this.playerEntity.playerNetServerHandler - .sendPacket(new S23PacketBlockChange(worldserver, blockpos)); - } - } - - return; - } - default: - throw new IllegalArgumentException("Invalid player action"); - } + public void processPlayerAbilities(C13PacketPlayerAbilities c13packetplayerabilities) { + this.playerEntity.capabilities.isFlying = c13packetplayerabilities.isFlying() + && this.playerEntity.capabilities.allowFlying; } - /**+ - * Processes block placement and block activation (anvil, - * furnace, etc.) + /** + * + Processes block placement and block activation (anvil, furnace, etc.) */ public void processPlayerBlockPlacement(C08PacketPlayerBlockPlacement c08packetplayerblockplacement) { WorldServer worldserver = this.serverController.worldServerForDimension(this.playerEntity.dimension); @@ -603,430 +840,87 @@ public class NetHandlerPlayServer implements INetHandlerPlayServer, ITickable { } - public void handleSpectate(C18PacketSpectate c18packetspectate) { - if (this.playerEntity.isSpectator()) { - Entity entity = null; - - WorldServer[] srv = this.serverController.worldServers; - for (int i = 0; i < srv.length; ++i) { - WorldServer worldserver = srv[i]; - if (worldserver != null) { - entity = c18packetspectate.getEntity(worldserver); - if (entity != null) { - break; - } - } - } - - if (entity != null) { - this.playerEntity.setSpectatingEntity(this.playerEntity); - this.playerEntity.mountEntity((Entity) null); - if (entity.worldObj != this.playerEntity.worldObj) { - WorldServer worldserver1 = this.playerEntity.getServerForPlayer(); - WorldServer worldserver2 = (WorldServer) entity.worldObj; - this.playerEntity.dimension = entity.dimension; - this.sendPacket(new S07PacketRespawn(this.playerEntity.dimension, worldserver1.getDifficulty(), - worldserver1.getWorldInfo().getTerrainType(), - this.playerEntity.theItemInWorldManager.getGameType())); - worldserver1.removePlayerEntityDangerously(this.playerEntity); - this.playerEntity.isDead = false; - this.playerEntity.setLocationAndAngles(entity.posX, entity.posY, entity.posZ, entity.rotationYaw, - entity.rotationPitch); - if (this.playerEntity.isEntityAlive()) { - worldserver1.updateEntityWithOptionalForce(this.playerEntity, false); - worldserver2.spawnEntityInWorld(this.playerEntity); - worldserver2.updateEntityWithOptionalForce(this.playerEntity, false); - } - - this.playerEntity.setWorld(worldserver2); - this.serverController.getConfigurationManager().preparePlayer(this.playerEntity, worldserver1); - this.playerEntity.setPositionAndUpdate(entity.posX, entity.posY, entity.posZ); - this.playerEntity.theItemInWorldManager.setWorld(worldserver2); - this.serverController.getConfigurationManager().updateTimeAndWeatherForPlayer(this.playerEntity, - worldserver2); - this.serverController.getConfigurationManager().syncPlayerInventory(this.playerEntity); - } else { - this.playerEntity.setPositionAndUpdate(entity.posX, entity.posY, entity.posZ); - } - } - } - - } - - public void handleResourcePackStatus(C19PacketResourcePackStatus var1) { - } - - /**+ - * Invoked when disconnecting, the parameter is a ChatComponent - * describing the reason for termination + /** + * + Processes the player initiating/stopping digging on a particular spot, as + * well as a player dropping items?. (0: initiated, 1: reinitiated, 2? , 3-4 + * drop item (respectively without or with player control), 5: stopped; x,y,z, + * side clicked on;) */ - public void onDisconnect(IChatComponent ichatcomponent) { - if (!hasDisconnected) { - hasDisconnected = true; - logger.info(this.playerEntity.getName() + " lost connection: " + ichatcomponent); - this.serverController.refreshStatusNextTick(); - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("multiplayer.player.left", - new Object[] { this.playerEntity.getDisplayName() }); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.YELLOW); - this.serverController.getConfigurationManager().sendChatMsg(chatcomponenttranslation); - this.playerEntity.mountEntityAndWakeUp(); - this.serverController.getConfigurationManager().playerLoggedOut(this.playerEntity); - if (this.playerEntity.getName().equals(this.serverController.getServerOwner())) { - logger.info("Stopping singleplayer server as player logged out"); - this.serverController.initiateShutdown(); - } - } - } - - public void sendPacket(final Packet packetIn) { - if (packetIn instanceof S02PacketChat) { - S02PacketChat s02packetchat = (S02PacketChat) packetIn; - EntityPlayer.EnumChatVisibility entityplayer$enumchatvisibility = this.playerEntity.getChatVisibility(); - if (entityplayer$enumchatvisibility == EntityPlayer.EnumChatVisibility.HIDDEN) { - return; - } - - if (entityplayer$enumchatvisibility == EntityPlayer.EnumChatVisibility.SYSTEM && !s02packetchat.isChat()) { - return; - } - } - - try { - this.netManager.sendPacket(packetIn); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Sending packet"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Packet being sent"); - crashreportcategory.addCrashSectionCallable("Packet class", new Callable() { - public String call() throws Exception { - return packetIn.getClass().getCanonicalName(); - } - }); - throw new ReportedException(crashreport); - } - } - - /**+ - * Updates which quickbar slot is selected - */ - public void processHeldItemChange(C09PacketHeldItemChange c09packethelditemchange) { - if (c09packethelditemchange.getSlotId() >= 0 - && c09packethelditemchange.getSlotId() < InventoryPlayer.getHotbarSize()) { - this.playerEntity.inventory.currentItem = c09packethelditemchange.getSlotId(); - this.playerEntity.markPlayerActive(); - } else { - logger.warn(this.playerEntity.getName() + " tried to set an invalid carried item"); - } - } - - /**+ - * Process chat messages (broadcast back to clients) and - * commands (executes) - */ - public void processChatMessage(C01PacketChatMessage c01packetchatmessage) { - if (this.playerEntity.getChatVisibility() == EntityPlayer.EnumChatVisibility.HIDDEN) { - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation("chat.cannotSend", - new Object[0]); - chatcomponenttranslation.getChatStyle().setColor(EnumChatFormatting.RED); - this.sendPacket(new S02PacketChat(chatcomponenttranslation)); - } else { - this.playerEntity.markPlayerActive(); - String s = c01packetchatmessage.getMessage(); - s = StringUtils.normalizeSpace(s); - - for (int i = 0; i < s.length(); ++i) { - if (!ChatAllowedCharacters.isAllowedCharacter(s.charAt(i))) { - this.kickPlayerFromServer("Illegal characters in chat"); - return; - } - } - - if (s.startsWith("/")) { - this.handleSlashCommand(s); - } else { - if (this.serverController.worldServers[0].getWorldInfo().getGameRulesInstance() - .getBoolean("colorCodes")) { - s = net.minecraft.util.StringUtils.translateControlCodesAlternate(s); - } - ChatComponentTranslation chatcomponenttranslation1 = new ChatComponentTranslation("chat.type.text", - new Object[] { this.playerEntity.getDisplayName(), s }); - this.serverController.getConfigurationManager().sendChatMsgImpl(chatcomponenttranslation1, false); - } - - this.chatSpamThresholdCount += 20; - if (this.chatSpamThresholdCount > 200 && !this.serverController.getConfigurationManager() - .canSendCommands(this.playerEntity.getGameProfile())) { - this.kickPlayerFromServer("disconnect.spam"); - } - - } - } - - /**+ - * Handle commands that start with a / - */ - private void handleSlashCommand(String command) { - this.serverController.getCommandManager().executeCommand(this.playerEntity, command); - } - - public void handleAnimation(C0APacketAnimation c0apacketanimation) { - this.playerEntity.markPlayerActive(); - this.playerEntity.swingItem(); - } - - /**+ - * Processes a range of action-types: sneaking, sprinting, - * waking from sleep, opening the inventory or setting jump - * height of the horse the player is riding - */ - public void processEntityAction(C0BPacketEntityAction c0bpacketentityaction) { - this.playerEntity.markPlayerActive(); - switch (c0bpacketentityaction.getAction()) { - case START_SNEAKING: - this.playerEntity.setSneaking(true); - break; - case STOP_SNEAKING: - this.playerEntity.setSneaking(false); - break; - case START_SPRINTING: - this.playerEntity.setSprinting(true); - break; - case STOP_SPRINTING: - this.playerEntity.setSprinting(false); - break; - case STOP_SLEEPING: - this.playerEntity.wakeUpPlayer(false, true, true); - this.hasMoved = false; - break; - case RIDING_JUMP: - if (this.playerEntity.ridingEntity instanceof EntityHorse) { - ((EntityHorse) this.playerEntity.ridingEntity).setJumpPower(c0bpacketentityaction.getAuxData()); - } - break; - case OPEN_INVENTORY: - if (this.playerEntity.ridingEntity instanceof EntityHorse) { - ((EntityHorse) this.playerEntity.ridingEntity).openGUI(this.playerEntity); - } - break; - default: - throw new IllegalArgumentException("Invalid client command!"); - } - - } - - /**+ - * Processes interactions ((un)leashing, opening command block - * GUI) and attacks on an entity with players currently equipped - * item - */ - public void processUseEntity(C02PacketUseEntity c02packetuseentity) { + public void processPlayerDigging(C07PacketPlayerDigging c07packetplayerdigging) { WorldServer worldserver = this.serverController.worldServerForDimension(this.playerEntity.dimension); - Entity entity = c02packetuseentity.getEntityFromWorld(worldserver); + BlockPos blockpos = c07packetplayerdigging.getPosition(); this.playerEntity.markPlayerActive(); - if (entity != null) { - boolean flag = this.playerEntity.canEntityBeSeen(entity); - double d0 = 36.0D; - if (!flag) { - d0 = 9.0D; + switch (c07packetplayerdigging.getStatus()) { + case DROP_ITEM: + if (!this.playerEntity.isSpectator()) { + this.playerEntity.dropOneItem(false); } - if (this.playerEntity.getDistanceSqToEntity(entity) < d0) { - if (c02packetuseentity.getAction() == C02PacketUseEntity.Action.INTERACT) { - this.playerEntity.interactWith(entity); - } else if (c02packetuseentity.getAction() == C02PacketUseEntity.Action.INTERACT_AT) { - entity.interactAt(this.playerEntity, c02packetuseentity.getHitVec()); - } else if (c02packetuseentity.getAction() == C02PacketUseEntity.Action.ATTACK) { - if (entity instanceof EntityItem || entity instanceof EntityXPOrb || entity instanceof EntityArrow - || entity == this.playerEntity) { - this.kickPlayerFromServer("Attempting to attack an invalid entity"); - this.serverController.logWarning( - "Player " + this.playerEntity.getName() + " tried to attack an invalid entity"); - return; - } - - this.playerEntity.attackTargetEntityWithCurrentItem(entity); - } + return; + case DROP_ALL_ITEMS: + if (!this.playerEntity.isSpectator()) { + this.playerEntity.dropOneItem(true); } - } - } - - /**+ - * Processes the client status updates: respawn attempt from - * player, opening statistics or achievements, or acquiring - * 'open inventory' achievement - */ - public void processClientStatus(C16PacketClientStatus c16packetclientstatus) { - this.playerEntity.markPlayerActive(); - C16PacketClientStatus.EnumState c16packetclientstatus$enumstate = c16packetclientstatus.getStatus(); - switch (c16packetclientstatus$enumstate) { - case PERFORM_RESPAWN: - if (this.playerEntity.playerConqueredTheEnd) { - this.playerEntity = this.serverController.getConfigurationManager() - .recreatePlayerEntity(this.playerEntity, 0, true); - } else if (this.playerEntity.getServerForPlayer().getWorldInfo().isHardcoreModeEnabled()) { - if (this.serverController.isSinglePlayer() - && this.playerEntity.getName().equals(this.serverController.getServerOwner())) { - this.playerEntity.playerNetServerHandler - .kickPlayerFromServer("You have died. Game over, man, it\'s game over!"); - this.serverController.deleteWorldAndStopServer(); - } else { - this.playerEntity.playerNetServerHandler - .kickPlayerFromServer("You have died. Game over, man, it\'s game over!"); - } + return; + case RELEASE_USE_ITEM: + this.playerEntity.stopUsingItem(); + return; + case START_DESTROY_BLOCK: + case ABORT_DESTROY_BLOCK: + case STOP_DESTROY_BLOCK: + double d0 = this.playerEntity.posX - ((double) blockpos.getX() + 0.5D); + double d1 = this.playerEntity.posY - ((double) blockpos.getY() + 0.5D) + 1.5D; + double d2 = this.playerEntity.posZ - ((double) blockpos.getZ() + 0.5D); + double d3 = d0 * d0 + d1 * d1 + d2 * d2; + if (d3 > 36.0D) { + return; + } else if (blockpos.getY() >= this.serverController.getBuildLimit()) { + return; } else { - if (this.playerEntity.getHealth() > 0.0F) { - return; - } - - this.playerEntity = this.serverController.getConfigurationManager() - .recreatePlayerEntity(this.playerEntity, 0, false); - } - break; - case REQUEST_STATS: - this.playerEntity.getStatFile().func_150876_a(this.playerEntity); - break; - case OPEN_INVENTORY_ACHIEVEMENT: - this.playerEntity.triggerAchievement(AchievementList.openInventory); - } - - } - - /**+ - * Processes the client closing windows (container) - */ - public void processCloseWindow(C0DPacketCloseWindow c0dpacketclosewindow) { - this.playerEntity.closeContainer(); - } - - /**+ - * Executes a container/inventory slot manipulation as indicated - * by the packet. Sends the serverside result if they didn't - * match the indicated result and prevents further manipulation - * by the player until he confirms that it has the same open - * container/inventory - */ - public void processClickWindow(C0EPacketClickWindow c0epacketclickwindow) { - this.playerEntity.markPlayerActive(); - if (this.playerEntity.openContainer.windowId == c0epacketclickwindow.getWindowId() - && this.playerEntity.openContainer.getCanCraft(this.playerEntity)) { - if (this.playerEntity.isSpectator()) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < this.playerEntity.openContainer.inventorySlots.size(); ++i) { - arraylist.add(((Slot) this.playerEntity.openContainer.inventorySlots.get(i)).getStack()); - } - - this.playerEntity.updateCraftingInventory(this.playerEntity.openContainer, arraylist); - } else { - ItemStack itemstack = this.playerEntity.openContainer.slotClick(c0epacketclickwindow.getSlotId(), - c0epacketclickwindow.getUsedButton(), c0epacketclickwindow.getMode(), this.playerEntity); - if (ItemStack.areItemStacksEqual(c0epacketclickwindow.getClickedItem(), itemstack)) { - this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction( - c0epacketclickwindow.getWindowId(), c0epacketclickwindow.getActionNumber(), true)); - this.playerEntity.isChangingQuantityOnly = true; - this.playerEntity.openContainer.detectAndSendChanges(); - this.playerEntity.updateHeldItem(); - this.playerEntity.isChangingQuantityOnly = false; + if (c07packetplayerdigging.getStatus() == C07PacketPlayerDigging.Action.START_DESTROY_BLOCK) { + if (!this.serverController.isBlockProtected(worldserver, blockpos, this.playerEntity) + && worldserver.getWorldBorder().contains(blockpos)) { + this.playerEntity.theItemInWorldManager.onBlockClicked(blockpos, + c07packetplayerdigging.getFacing()); + } else { + this.playerEntity.playerNetServerHandler + .sendPacket(new S23PacketBlockChange(worldserver, blockpos)); + } } else { - this.field_147372_n.addKey(this.playerEntity.openContainer.windowId, - Short.valueOf(c0epacketclickwindow.getActionNumber())); - this.playerEntity.playerNetServerHandler.sendPacket(new S32PacketConfirmTransaction( - c0epacketclickwindow.getWindowId(), c0epacketclickwindow.getActionNumber(), false)); - this.playerEntity.openContainer.setCanCraft(this.playerEntity, false); - ArrayList arraylist1 = Lists.newArrayList(); - - for (int j = 0; j < this.playerEntity.openContainer.inventorySlots.size(); ++j) { - arraylist1.add(((Slot) this.playerEntity.openContainer.inventorySlots.get(j)).getStack()); + if (c07packetplayerdigging.getStatus() == C07PacketPlayerDigging.Action.STOP_DESTROY_BLOCK) { + this.playerEntity.theItemInWorldManager.blockRemoving(blockpos); + } else if (c07packetplayerdigging + .getStatus() == C07PacketPlayerDigging.Action.ABORT_DESTROY_BLOCK) { + this.playerEntity.theItemInWorldManager.cancelDestroyingBlock(); } - this.playerEntity.updateCraftingInventory(this.playerEntity.openContainer, arraylist1); - } - } - } - - } - - /**+ - * Enchants the item identified by the packet given some - * convoluted conditions (matching window, which - * should/shouldn't be in use?) - */ - public void processEnchantItem(C11PacketEnchantItem c11packetenchantitem) { - this.playerEntity.markPlayerActive(); - if (this.playerEntity.openContainer.windowId == c11packetenchantitem.getWindowId() - && this.playerEntity.openContainer.getCanCraft(this.playerEntity) && !this.playerEntity.isSpectator()) { - this.playerEntity.openContainer.enchantItem(this.playerEntity, c11packetenchantitem.getButton()); - this.playerEntity.openContainer.detectAndSendChanges(); - } - - } - - /**+ - * Update the server with an ItemStack in a slot. - */ - public void processCreativeInventoryAction(C10PacketCreativeInventoryAction c10packetcreativeinventoryaction) { - if (this.playerEntity.theItemInWorldManager.isCreative()) { - boolean flag = c10packetcreativeinventoryaction.getSlotId() < 0; - ItemStack itemstack = c10packetcreativeinventoryaction.getStack(); - if (itemstack != null && itemstack.hasTagCompound() - && itemstack.getTagCompound().hasKey("BlockEntityTag", 10)) { - NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("BlockEntityTag"); - if (nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z")) { - BlockPos blockpos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), - nbttagcompound.getInteger("z")); - TileEntity tileentity = this.playerEntity.worldObj.getTileEntity(blockpos); - if (tileentity != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - tileentity.writeToNBT(nbttagcompound1); - nbttagcompound1.removeTag("x"); - nbttagcompound1.removeTag("y"); - nbttagcompound1.removeTag("z"); - itemstack.setTagInfo("BlockEntityTag", nbttagcompound1); + if (worldserver.getBlockState(blockpos).getBlock().getMaterial() != Material.air) { + this.playerEntity.playerNetServerHandler + .sendPacket(new S23PacketBlockChange(worldserver, blockpos)); } } - } - boolean flag1 = c10packetcreativeinventoryaction.getSlotId() >= 1 - && c10packetcreativeinventoryaction.getSlotId() < 36 + InventoryPlayer.getHotbarSize(); - boolean flag2 = itemstack == null || itemstack.getItem() != null; - boolean flag3 = itemstack == null - || itemstack.getMetadata() >= 0 && itemstack.stackSize <= 64 && itemstack.stackSize > 0; - if (flag1 && flag2 && flag3) { - if (itemstack == null) { - this.playerEntity.inventoryContainer.putStackInSlot(c10packetcreativeinventoryaction.getSlotId(), - (ItemStack) null); - } else { - this.playerEntity.inventoryContainer.putStackInSlot(c10packetcreativeinventoryaction.getSlotId(), - itemstack); - } - - this.playerEntity.inventoryContainer.setCanCraft(this.playerEntity, true); - } else if (flag && flag2 && flag3 && this.itemDropThreshold < 200) { - this.itemDropThreshold += 20; - EntityItem entityitem = this.playerEntity.dropPlayerItemWithRandomChoice(itemstack, true); - if (entityitem != null) { - entityitem.setAgeToCreativeDespawnTime(); - } + return; } + default: + throw new IllegalArgumentException("Invalid player action"); } - } - /**+ - * Received in response to the server requesting to confirm that - * the client-side open container matches the servers' after a - * mismatched container-slot manipulation. It will unlock the - * player's ability to manipulate the container contents + /** + * + Retrieves possible tab completions for the requested command string and + * sends them to the client */ - public void processConfirmTransaction(C0FPacketConfirmTransaction c0fpacketconfirmtransaction) { - Short oshort = (Short) this.field_147372_n.lookup(this.playerEntity.openContainer.windowId); - if (oshort != null && c0fpacketconfirmtransaction.getUid() == oshort.shortValue() - && this.playerEntity.openContainer.windowId == c0fpacketconfirmtransaction.getWindowId() - && !this.playerEntity.openContainer.getCanCraft(this.playerEntity) - && !this.playerEntity.isSpectator()) { - this.playerEntity.openContainer.setCanCraft(this.playerEntity, true); + public void processTabComplete(C14PacketTabComplete c14packettabcomplete) { + List lst = this.serverController.getTabCompletions(this.playerEntity, c14packettabcomplete.getMessage(), + c14packettabcomplete.getTargetBlock()); + String[] fuckOff = new String[lst.size()]; + for (int i = 0; i < fuckOff.length; ++i) { + fuckOff[i] = lst.get(i); } + this.playerEntity.playerNetServerHandler.sendPacket(new S3APacketTabComplete(fuckOff)); } public void processUpdateSign(C12PacketUpdateSign c12packetupdatesign) { @@ -1063,56 +957,44 @@ public class NetHandlerPlayServer implements INetHandlerPlayServer, ITickable { } - /**+ - * Updates a players' ping statistics + /** + * + Processes interactions ((un)leashing, opening command block GUI) and + * attacks on an entity with players currently equipped item */ - public void processKeepAlive(C00PacketKeepAlive c00packetkeepalive) { - if (c00packetkeepalive.getKey() == this.field_147378_h) { - int i = (int) (this.currentTimeMillis() - this.lastPingTime); - this.playerEntity.ping = (this.playerEntity.ping * 3 + i) / 4; + public void processUseEntity(C02PacketUseEntity c02packetuseentity) { + WorldServer worldserver = this.serverController.worldServerForDimension(this.playerEntity.dimension); + Entity entity = c02packetuseentity.getEntityFromWorld(worldserver); + this.playerEntity.markPlayerActive(); + if (entity != null) { + boolean flag = this.playerEntity.canEntityBeSeen(entity); + double d0 = 36.0D; + if (!flag) { + d0 = 9.0D; + } + + if (this.playerEntity.getDistanceSqToEntity(entity) < d0) { + if (c02packetuseentity.getAction() == C02PacketUseEntity.Action.INTERACT) { + this.playerEntity.interactWith(entity); + } else if (c02packetuseentity.getAction() == C02PacketUseEntity.Action.INTERACT_AT) { + entity.interactAt(this.playerEntity, c02packetuseentity.getHitVec()); + } else if (c02packetuseentity.getAction() == C02PacketUseEntity.Action.ATTACK) { + if (entity instanceof EntityItem || entity instanceof EntityXPOrb || entity instanceof EntityArrow + || entity == this.playerEntity) { + this.kickPlayerFromServer("Attempting to attack an invalid entity"); + this.serverController.logWarning( + "Player " + this.playerEntity.getName() + " tried to attack an invalid entity"); + return; + } + + this.playerEntity.attackTargetEntityWithCurrentItem(entity); + } + } } } - private long currentTimeMillis() { - return EagRuntime.steadyTimeMillis(); - } - - /**+ - * Processes a player starting/stopping flying - */ - public void processPlayerAbilities(C13PacketPlayerAbilities c13packetplayerabilities) { - this.playerEntity.capabilities.isFlying = c13packetplayerabilities.isFlying() - && this.playerEntity.capabilities.allowFlying; - } - - /**+ - * Retrieves possible tab completions for the requested command - * string and sends them to the client - */ - public void processTabComplete(C14PacketTabComplete c14packettabcomplete) { - List lst = this.serverController.getTabCompletions(this.playerEntity, c14packettabcomplete.getMessage(), - c14packettabcomplete.getTargetBlock()); - String[] fuckOff = new String[lst.size()]; - for (int i = 0; i < fuckOff.length; ++i) { - fuckOff[i] = lst.get(i); - } - - this.playerEntity.playerNetServerHandler.sendPacket(new S3APacketTabComplete(fuckOff)); - } - - /**+ - * Updates serverside copy of client settings: language, render - * distance, chat visibility, chat colours, difficulty, and - * whether to show the cape - */ - public void processClientSettings(C15PacketClientSettings c15packetclientsettings) { - this.playerEntity.handleClientSettings(c15packetclientsettings); - } - - /**+ - * Synchronizes serverside and clientside book contents and - * signing + /** + * + Synchronizes serverside and clientside book contents and signing */ public void processVanilla250Packet(C17PacketCustomPayload c17packetcustompayload) { if ("MC|BEdit".equals(c17packetcustompayload.getChannelName())) { @@ -1287,4 +1169,113 @@ public class NetHandlerPlayServer implements INetHandlerPlayServer, ITickable { } } } + + public void sendEaglerMessage(GameMessagePacket packet) { + try { + eaglerMessageController.sendPacket(packet); + } catch (IOException e) { + logger.error("Failed to send eaglercraft plugin message packet: " + packet); + logger.error(e); + } + } + + public void sendPacket(final Packet packetIn) { + if (packetIn instanceof S02PacketChat) { + S02PacketChat s02packetchat = (S02PacketChat) packetIn; + EntityPlayer.EnumChatVisibility entityplayer$enumchatvisibility = this.playerEntity.getChatVisibility(); + if (entityplayer$enumchatvisibility == EntityPlayer.EnumChatVisibility.HIDDEN) { + return; + } + + if (entityplayer$enumchatvisibility == EntityPlayer.EnumChatVisibility.SYSTEM && !s02packetchat.isChat()) { + return; + } + } + + try { + this.netManager.sendPacket(packetIn); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Sending packet"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Packet being sent"); + crashreportcategory.addCrashSectionCallable("Packet class", new Callable() { + public String call() throws Exception { + return packetIn.getClass().getCanonicalName(); + } + }); + throw new ReportedException(crashreport); + } + } + + public void setEaglerMessageController(GameProtocolMessageController eaglerMessageController) { + this.eaglerMessageController = eaglerMessageController; + } + + public void setPlayerLocation(double x, double y, double z, float yaw, float pitch) { + this.setPlayerLocation(x, y, z, yaw, pitch, Collections.emptySet()); + } + + public void setPlayerLocation(double x, double y, double z, float yaw, float pitch, + Set relativeSet) { + this.hasMoved = false; + this.lastPosX = x; + this.lastPosY = y; + this.lastPosZ = z; + if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.X)) { + this.lastPosX += this.playerEntity.posX; + } + + if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.Y)) { + this.lastPosY += this.playerEntity.posY; + } + + if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.Z)) { + this.lastPosZ += this.playerEntity.posZ; + } + + float f = yaw; + float f1 = pitch; + if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.Y_ROT)) { + f = yaw + this.playerEntity.rotationYaw; + } + + if (relativeSet.contains(S08PacketPlayerPosLook.EnumFlags.X_ROT)) { + f1 = pitch + this.playerEntity.rotationPitch; + } + + this.playerEntity.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, f, f1); + this.playerEntity.playerNetServerHandler + .sendPacket(new S08PacketPlayerPosLook(x, y, z, yaw, pitch, relativeSet)); + } + + /** + * + Like the old updateEntity(), except more generic. + */ + public void update() { + this.field_147366_g = false; + ++this.networkTickCount; + if ((long) this.networkTickCount - this.lastSentPingPacket > 40L) { + this.lastSentPingPacket = (long) this.networkTickCount; + this.lastPingTime = this.currentTimeMillis(); + this.field_147378_h = (int) this.lastPingTime; + this.sendPacket(new S00PacketKeepAlive(this.field_147378_h)); + } + + if (this.chatSpamThresholdCount > 0) { + --this.chatSpamThresholdCount; + } + + if (this.itemDropThreshold > 0) { + --this.itemDropThreshold; + } + + if (this.playerEntity.getLastActiveTime() > 0L && this.serverController.getMaxPlayerIdleMinutes() > 0 + && MinecraftServer.getCurrentTimeMillis() - this.playerEntity + .getLastActiveTime() > (long) (this.serverController.getMaxPlayerIdleMinutes() * 1000 * 60)) { + this.kickPlayerFromServer("You have been idle for too long!"); + } + + if (this.eaglerMessageController != null) { + this.eaglerMessageController.flush(); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/Packet.java b/src/game/java/net/minecraft/network/Packet.java index a9f59fc1..b26c0f26 100644 --- a/src/game/java/net/minecraft/network/Packet.java +++ b/src/game/java/net/minecraft/network/Packet.java @@ -2,39 +2,42 @@ package net.minecraft.network; import java.io.IOException; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface Packet { - /**+ - * Reads the raw packet data from the data stream. + /** + * + Passes this Packet on to the NetHandler for processing. + */ + void processPacket(T var1); + + /** + * + Reads the raw packet data from the data stream. */ void readPacketData(PacketBuffer var1) throws IOException; - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ void writePacketData(PacketBuffer var1) throws IOException; - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - void processPacket(T var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/PacketBuffer.java b/src/game/java/net/minecraft/network/PacketBuffer.java index ff7393d1..48aa0e0b 100644 --- a/src/game/java/net/minecraft/network/PacketBuffer.java +++ b/src/game/java/net/minecraft/network/PacketBuffer.java @@ -12,7 +12,6 @@ import java.nio.charset.StandardCharsets; import net.lax1dude.eaglercraft.v1_8.DecoderException; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.EncoderException; - import net.lax1dude.eaglercraft.v1_8.netty.ByteBuf; import net.lax1dude.eaglercraft.v1_8.netty.ByteBufInputStream; import net.lax1dude.eaglercraft.v1_8.netty.ByteBufOutputStream; @@ -24,37 +23,33 @@ import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PacketBuffer extends ByteBuf { - private final ByteBuf buf; - - public PacketBuffer(ByteBuf wrapped) { - this.buf = wrapped; - } - - /**+ - * Calculates the number of bytes required to fit the supplied - * int (0-5) if it were to be read/written using - * readVarIntFromBuffer or writeVarIntToBuffer + /** + * + Calculates the number of bytes required to fit the supplied int (0-5) if it + * were to be read/written using readVarIntFromBuffer or writeVarIntToBuffer */ public static int getVarIntSize(int input) { for (int i = 1; i < 5; ++i) { @@ -66,9 +61,274 @@ public class PacketBuffer extends ByteBuf { return 5; } - public void writeByteArray(byte[] array) { - this.writeVarIntToBuffer(array.length); - this.writeBytes(array); + private final ByteBuf buf; + + public PacketBuffer(ByteBuf wrapped) { + this.buf = wrapped; + } + + public byte[] array() { + return this.buf.array(); + } + + public int arrayOffset() { + return this.buf.arrayOffset(); + } + + public int bytesBefore(byte parByte1) { + return this.buf.bytesBefore(parByte1); + } + + public int bytesBefore(int i, byte b0) { + return this.buf.bytesBefore(i, b0); + } + + public int bytesBefore(int i, int j, byte b0) { + return this.buf.bytesBefore(i, j, b0); + } + + public int capacity() { + return this.buf.capacity(); + } + + public ByteBuf capacity(int i) { + return this.buf.capacity(i); + } + + public ByteBuf clear() { + return this.buf.clear(); + } + + public int compareTo(ByteBuf bytebuf) { + return this.buf.compareTo(bytebuf); + } + + public ByteBuf copy() { + return this.buf.copy(); + } + + public ByteBuf copy(int i, int j) { + return this.buf.copy(i, j); + } + + public ByteBuf discardReadBytes() { + return this.buf.discardReadBytes(); + } + + public ByteBuf discardSomeReadBytes() { + return this.buf.discardSomeReadBytes(); + } + + public ByteBuf duplicate() { + return this.buf.duplicate(); + } + + public ByteBuf ensureWritable(int parInt1) { + return this.buf.ensureWritable(parInt1); + } + + public int ensureWritable(int i, boolean flag) { + return this.buf.ensureWritable(i, flag); + } + + public boolean equals(Object object) { + return this.buf.equals(object); + } + + public boolean getBoolean(int parInt1) { + return this.buf.getBoolean(parInt1); + } + + public byte getByte(int parInt1) { + return this.buf.getByte(parInt1); + } + + public ByteBuf getBytes(int i, byte[] abyte) { + return this.buf.getBytes(i, abyte); + } + + public ByteBuf getBytes(int i, byte[] abyte, int j, int k) { + return this.buf.getBytes(i, abyte, j, k); + } + + public ByteBuf getBytes(int parInt1, ByteBuf parByteBuf) { + if (parByteBuf instanceof PacketBuffer) { + return this.buf.getBytes(parInt1, ((PacketBuffer) parByteBuf).buf); + } else { + return this.buf.getBytes(parInt1, parByteBuf); + } + } + + public ByteBuf getBytes(int i, ByteBuf bytebuf, int j) { + if (bytebuf instanceof PacketBuffer) { + return this.buf.getBytes(i, ((PacketBuffer) bytebuf).buf, j); + } else { + return this.buf.getBytes(i, bytebuf, j); + } + } + + public ByteBuf getBytes(int i, ByteBuf bytebuf, int j, int k) { + if (bytebuf instanceof PacketBuffer) { + return this.buf.getBytes(i, ((PacketBuffer) bytebuf).buf, j, k); + } else { + return this.buf.getBytes(i, bytebuf, j, k); + } + } + + public ByteBuf getBytes(int i, ByteBuffer bytebuffer) { + return this.buf.getBytes(i, bytebuffer); + } + + public ByteBuf getBytes(int parInt1, OutputStream parOutputStream, int parInt2) throws IOException { + return this.buf.getBytes(parInt1, parOutputStream, parInt2); + } + + public char getChar(int parInt1) { + return this.buf.getChar(parInt1); + } + + public double getDouble(int parInt1) { + return this.buf.getDouble(parInt1); + } + + public float getFloat(int parInt1) { + return this.buf.getFloat(parInt1); + } + + public int getInt(int parInt1) { + return this.buf.getInt(parInt1); + } + + public long getLong(int parInt1) { + return this.buf.getLong(parInt1); + } + + public int getMedium(int parInt1) { + return this.buf.getMedium(parInt1); + } + + public short getShort(int parInt1) { + return this.buf.getShort(parInt1); + } + + public short getUnsignedByte(int parInt1) { + return this.buf.getUnsignedByte(parInt1); + } + + public long getUnsignedInt(int parInt1) { + return this.buf.getUnsignedInt(parInt1); + } + + public int getUnsignedMedium(int parInt1) { + return this.buf.getUnsignedMedium(parInt1); + } + + public int getUnsignedShort(int parInt1) { + return this.buf.getUnsignedShort(parInt1); + } + + public boolean hasArray() { + return this.buf.hasArray(); + } + + public int hashCode() { + return this.buf.hashCode(); + } + + public boolean hasMemoryAddress() { + return this.buf.hasMemoryAddress(); + } + + public int indexOf(int parInt1, int parInt2, byte parByte1) { + return this.buf.indexOf(parInt1, parInt2, parByte1); + } + + public ByteBuffer internalNioBuffer(int parInt1, int parInt2) { + return this.buf.internalNioBuffer(parInt1, parInt2); + } + + public boolean isDirect() { + return this.buf.isDirect(); + } + + public boolean isReadable() { + return this.buf.isReadable(); + } + + public boolean isReadable(int i) { + return this.buf.isReadable(i); + } + + public boolean isWritable() { + return this.buf.isWritable(); + } + + public boolean isWritable(int i) { + return this.buf.isWritable(i); + } + + public ByteBuf markReaderIndex() { + return this.buf.markReaderIndex(); + } + + public ByteBuf markWriterIndex() { + return this.buf.markWriterIndex(); + } + + public int maxCapacity() { + return this.buf.maxCapacity(); + } + + public int maxWritableBytes() { + return this.buf.maxWritableBytes(); + } + + public long memoryAddress() { + return this.buf.memoryAddress(); + } + + public ByteBuffer nioBuffer() { + return this.buf.nioBuffer(); + } + + public ByteBuffer nioBuffer(int i, int j) { + return this.buf.nioBuffer(i, j); + } + + public int nioBufferCount() { + return this.buf.nioBufferCount(); + } + + public ByteBuffer[] nioBuffers() { + return this.buf.nioBuffers(); + } + + public ByteBuffer[] nioBuffers(int i, int j) { + return this.buf.nioBuffers(i, j); + } + + public ByteOrder order() { + return this.buf.order(); + } + + public ByteBuf order(ByteOrder byteorder) { + return this.buf.order(byteorder); + } + + public int readableBytes() { + return this.buf.readableBytes(); + } + + public BlockPos readBlockPos() { + return BlockPos.fromLong(this.readLong()); + } + + public boolean readBoolean() { + return this.buf.readBoolean(); + } + + public byte readByte() { + return this.buf.readByte(); } public byte[] readByteArray() { @@ -77,34 +337,174 @@ public class PacketBuffer extends ByteBuf { return abyte; } - public BlockPos readBlockPos() { - return BlockPos.fromLong(this.readLong()); + public ByteBuf readBytes(byte[] abyte) { + return this.buf.readBytes(abyte); } - public void writeBlockPos(BlockPos pos) { - this.writeLong(pos.toLong()); + public ByteBuf readBytes(byte[] abyte, int i, int j) { + return this.buf.readBytes(abyte, i, j); + } + + public ByteBuf readBytes(ByteBuf bytebuf) { + if (bytebuf instanceof PacketBuffer) { + return this.buf.readBytes(((PacketBuffer) bytebuf).buf); + } else { + return this.buf.readBytes(bytebuf); + } + } + + public ByteBuf readBytes(ByteBuf bytebuf, int i) { + if (bytebuf instanceof PacketBuffer) { + return this.buf.readBytes(((PacketBuffer) bytebuf).buf, i); + } else { + return this.buf.readBytes(bytebuf, i); + } + } + + public ByteBuf readBytes(ByteBuf bytebuf, int i, int j) { + if (bytebuf instanceof PacketBuffer) { + return this.buf.readBytes(((PacketBuffer) bytebuf).buf, i, j); + } else { + return this.buf.readBytes(bytebuf, i, j); + } + } + + public ByteBuf readBytes(ByteBuffer bytebuffer) { + return this.buf.readBytes(bytebuffer); + } + + public ByteBuf readBytes(int parInt1) { + return this.buf.readBytes(parInt1); + } + + public ByteBuf readBytes(OutputStream parOutputStream, int parInt1) throws IOException { + return this.buf.readBytes(parOutputStream, parInt1); + } + + public char readChar() { + return this.buf.readChar(); } public IChatComponent readChatComponent() throws IOException { return IChatComponent.Serializer.jsonToComponent(this.readStringFromBuffer(32767)); } - public void writeChatComponent(IChatComponent component) throws IOException { - this.writeString(IChatComponent.Serializer.componentToJson(component)); + public double readDouble() { + return this.buf.readDouble(); } public > T readEnumValue(Class enumClass) { return (T) ((Enum[]) enumClass.getEnumConstants())[this.readVarIntFromBuffer()]; } - public void writeEnumValue(Enum value) { - this.writeVarIntToBuffer(value.ordinal()); + public int readerIndex() { + return this.buf.readerIndex(); } - /**+ - * Reads a compressed int from the buffer. To do so it maximally - * reads 5 byte-sized chunks whose most significant bit dictates - * whether another byte should be read. + public ByteBuf readerIndex(int i) { + return this.buf.readerIndex(i); + } + + public float readFloat() { + return this.buf.readFloat(); + } + + public int readInt() { + return this.buf.readInt(); + } + + /** + * + Reads an ItemStack from this buffer + */ + public ItemStack readItemStackFromBuffer() throws IOException { + ItemStack itemstack = null; + short short1 = this.readShort(); + if (short1 >= 0) { + byte b0 = this.readByte(); + short short2 = this.readShort(); + itemstack = new ItemStack(Item.getItemById(short1), b0, short2); + itemstack.setTagCompound(this.readNBTTagCompoundFromBuffer()); + } + + return itemstack; + } + + public long readLong() { + return this.buf.readLong(); + } + + public int readMedium() { + return this.buf.readMedium(); + } + + /** + * + Reads a compressed NBTTagCompound from this buffer + */ + public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { + int i = this.readerIndex(); + byte b0 = this.readByte(); + if (b0 == 0) { + return null; + } else { + this.readerIndex(i); + return CompressedStreamTools.read(new ByteBufInputStream(this), new NBTSizeTracker(2097152L)); + } + } + + public short readShort() { + return this.buf.readShort(); + } + + public ByteBuf readSlice(int parInt1) { + return this.buf.readSlice(parInt1); + } + + /** + * + Reads a string from this buffer. Expected parameter is maximum allowed + * string length. Will throw IOException if string length exceeds this value! + */ + public String readStringFromBuffer(int maxLength) { + int i = this.readVarIntFromBuffer(); + if (i > maxLength * 4) { + throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + i + + " > " + maxLength * 4 + ")"); + } else if (i < 0) { + throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); + } else { + String s = new String(this.readBytes(i).array(), StandardCharsets.UTF_8); + if (s.length() > maxLength) { + throw new DecoderException( + "The received string length is longer than maximum allowed (" + i + " > " + maxLength + ")"); + } else { + return s; + } + } + } + + public short readUnsignedByte() { + return this.buf.readUnsignedByte(); + } + + public long readUnsignedInt() { + return this.buf.readUnsignedInt(); + } + + public int readUnsignedMedium() { + return this.buf.readUnsignedMedium(); + } + + public int readUnsignedShort() { + return this.buf.readUnsignedShort(); + } + + public EaglercraftUUID readUuid() { + return new EaglercraftUUID(this.readLong(), this.readLong()); + } + + /** + * + Reads a compressed int from the buffer. To do so it maximally reads 5 + * byte-sized chunks whose most significant bit dictates whether another byte + * should be read. */ public int readVarIntFromBuffer() { int i = 0; @@ -144,346 +544,14 @@ public class PacketBuffer extends ByteBuf { return i; } - public void writeUuid(EaglercraftUUID uuid) { - this.writeLong(uuid.getMostSignificantBits()); - this.writeLong(uuid.getLeastSignificantBits()); - } - - public EaglercraftUUID readUuid() { - return new EaglercraftUUID(this.readLong(), this.readLong()); - } - - /**+ - * Writes a compressed int to the buffer. The smallest number of - * bytes to fit the passed int will be written. Of each such - * byte only 7 bits will be used to describe the actual value - * since its most significant bit dictates whether the next byte - * is part of that same int. Micro-optimization for int values - * that are expected to have values below 128. - */ - public void writeVarIntToBuffer(int input) { - while ((input & -128) != 0) { - this.writeByte(input & 127 | 128); - input >>>= 7; - } - - this.writeByte(input); - } - - public void writeVarLong(long value) { - while ((value & -128L) != 0L) { - this.writeByte((int) (value & 127L) | 128); - value >>>= 7; - } - - this.writeByte((int) value); - } - - /**+ - * Writes a compressed NBTTagCompound to this buffer - */ - public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) { - if (nbt == null) { - this.writeByte(0); - } else { - try { - CompressedStreamTools.write(nbt, (DataOutput) (new ByteBufOutputStream(this))); - } catch (IOException ioexception) { - throw new EncoderException(ioexception); - } - } - - } - - /**+ - * Reads a compressed NBTTagCompound from this buffer - */ - public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException { - int i = this.readerIndex(); - byte b0 = this.readByte(); - if (b0 == 0) { - return null; - } else { - this.readerIndex(i); - return CompressedStreamTools.read(new ByteBufInputStream(this), new NBTSizeTracker(2097152L)); - } - } - - /**+ - * Writes the ItemStack's ID (short), then size (byte), then - * damage. (short) - */ - public void writeItemStackToBuffer(ItemStack stack) { - if (stack == null) { - this.writeShort(-1); - } else { - this.writeShort(Item.getIdFromItem(stack.getItem())); - this.writeByte(stack.stackSize); - this.writeShort(stack.getMetadata()); - NBTTagCompound nbttagcompound = null; - if (stack.getItem().isDamageable() || stack.getItem().getShareTag()) { - nbttagcompound = stack.getTagCompound(); - } - - this.writeNBTTagCompoundToBuffer(nbttagcompound); - } - - } - - /**+ - * Reads an ItemStack from this buffer - */ - public ItemStack readItemStackFromBuffer() throws IOException { - ItemStack itemstack = null; - short short1 = this.readShort(); - if (short1 >= 0) { - byte b0 = this.readByte(); - short short2 = this.readShort(); - itemstack = new ItemStack(Item.getItemById(short1), b0, short2); - itemstack.setTagCompound(this.readNBTTagCompoundFromBuffer()); - } - - return itemstack; - } - - /**+ - * Reads a string from this buffer. Expected parameter is - * maximum allowed string length. Will throw IOException if - * string length exceeds this value! - */ - public String readStringFromBuffer(int maxLength) { - int i = this.readVarIntFromBuffer(); - if (i > maxLength * 4) { - throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + i - + " > " + maxLength * 4 + ")"); - } else if (i < 0) { - throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); - } else { - String s = new String(this.readBytes(i).array(), StandardCharsets.UTF_8); - if (s.length() > maxLength) { - throw new DecoderException( - "The received string length is longer than maximum allowed (" + i + " > " + maxLength + ")"); - } else { - return s; - } - } - } - - public PacketBuffer writeString(String string) { - byte[] abyte = string.getBytes(StandardCharsets.UTF_8); - if (abyte.length > 32767) { - throw new EncoderException("String too big (was " + string.length() + " bytes encoded, max " + 32767 + ")"); - } else { - this.writeVarIntToBuffer(abyte.length); - this.writeBytes(abyte); - return this; - } - } - - public int capacity() { - return this.buf.capacity(); - } - - public ByteBuf capacity(int i) { - return this.buf.capacity(i); - } - - public int maxCapacity() { - return this.buf.maxCapacity(); - } - - public ByteOrder order() { - return this.buf.order(); - } - - public ByteBuf order(ByteOrder byteorder) { - return this.buf.order(byteorder); - } - - public ByteBuf unwrap() { - return this.buf.unwrap(); - } - - public boolean isDirect() { - return this.buf.isDirect(); - } - - public int readerIndex() { - return this.buf.readerIndex(); - } - - public ByteBuf readerIndex(int i) { - return this.buf.readerIndex(i); - } - - public int writerIndex() { - return this.buf.writerIndex(); - } - - public ByteBuf writerIndex(int i) { - return this.buf.writerIndex(i); - } - - public ByteBuf setIndex(int parInt1, int parInt2) { - return this.buf.setIndex(parInt1, parInt2); - } - - public int readableBytes() { - return this.buf.readableBytes(); - } - - public int writableBytes() { - return this.buf.writableBytes(); - } - - public int maxWritableBytes() { - return this.buf.maxWritableBytes(); - } - - public boolean isReadable() { - return this.buf.isReadable(); - } - - public boolean isReadable(int i) { - return this.buf.isReadable(i); - } - - public boolean isWritable() { - return this.buf.isWritable(); - } - - public boolean isWritable(int i) { - return this.buf.isWritable(i); - } - - public ByteBuf clear() { - return this.buf.clear(); - } - - public ByteBuf markReaderIndex() { - return this.buf.markReaderIndex(); - } - public ByteBuf resetReaderIndex() { return this.buf.resetReaderIndex(); } - public ByteBuf markWriterIndex() { - return this.buf.markWriterIndex(); - } - public ByteBuf resetWriterIndex() { return this.buf.resetWriterIndex(); } - public ByteBuf discardReadBytes() { - return this.buf.discardReadBytes(); - } - - public ByteBuf discardSomeReadBytes() { - return this.buf.discardSomeReadBytes(); - } - - public ByteBuf ensureWritable(int parInt1) { - return this.buf.ensureWritable(parInt1); - } - - public int ensureWritable(int i, boolean flag) { - return this.buf.ensureWritable(i, flag); - } - - public boolean getBoolean(int parInt1) { - return this.buf.getBoolean(parInt1); - } - - public byte getByte(int parInt1) { - return this.buf.getByte(parInt1); - } - - public short getUnsignedByte(int parInt1) { - return this.buf.getUnsignedByte(parInt1); - } - - public short getShort(int parInt1) { - return this.buf.getShort(parInt1); - } - - public int getUnsignedShort(int parInt1) { - return this.buf.getUnsignedShort(parInt1); - } - - public int getMedium(int parInt1) { - return this.buf.getMedium(parInt1); - } - - public int getUnsignedMedium(int parInt1) { - return this.buf.getUnsignedMedium(parInt1); - } - - public int getInt(int parInt1) { - return this.buf.getInt(parInt1); - } - - public long getUnsignedInt(int parInt1) { - return this.buf.getUnsignedInt(parInt1); - } - - public long getLong(int parInt1) { - return this.buf.getLong(parInt1); - } - - public char getChar(int parInt1) { - return this.buf.getChar(parInt1); - } - - public float getFloat(int parInt1) { - return this.buf.getFloat(parInt1); - } - - public double getDouble(int parInt1) { - return this.buf.getDouble(parInt1); - } - - public ByteBuf getBytes(int parInt1, ByteBuf parByteBuf) { - if (parByteBuf instanceof PacketBuffer) { - return this.buf.getBytes(parInt1, ((PacketBuffer) parByteBuf).buf); - } else { - return this.buf.getBytes(parInt1, parByteBuf); - } - } - - public ByteBuf getBytes(int i, ByteBuf bytebuf, int j) { - if (bytebuf instanceof PacketBuffer) { - return this.buf.getBytes(i, ((PacketBuffer) bytebuf).buf, j); - } else { - return this.buf.getBytes(i, bytebuf, j); - } - } - - public ByteBuf getBytes(int i, ByteBuf bytebuf, int j, int k) { - if (bytebuf instanceof PacketBuffer) { - return this.buf.getBytes(i, ((PacketBuffer) bytebuf).buf, j, k); - } else { - return this.buf.getBytes(i, bytebuf, j, k); - } - } - - public ByteBuf getBytes(int i, byte[] abyte) { - return this.buf.getBytes(i, abyte); - } - - public ByteBuf getBytes(int i, byte[] abyte, int j, int k) { - return this.buf.getBytes(i, abyte, j, k); - } - - public ByteBuf getBytes(int i, ByteBuffer bytebuffer) { - return this.buf.getBytes(i, bytebuffer); - } - - public ByteBuf getBytes(int parInt1, OutputStream parOutputStream, int parInt2) throws IOException { - return this.buf.getBytes(parInt1, parOutputStream, parInt2); - } - public ByteBuf setBoolean(int parInt1, boolean parFlag) { return this.buf.setBoolean(parInt1, parFlag); } @@ -492,32 +560,12 @@ public class PacketBuffer extends ByteBuf { return this.buf.setByte(parInt1, parInt2); } - public ByteBuf setShort(int parInt1, int parInt2) { - return this.buf.setShort(parInt1, parInt2); + public ByteBuf setBytes(int i, byte[] abyte) { + return this.buf.setBytes(i, abyte); } - public ByteBuf setMedium(int parInt1, int parInt2) { - return this.buf.setMedium(parInt1, parInt2); - } - - public ByteBuf setInt(int parInt1, int parInt2) { - return this.buf.setInt(parInt1, parInt2); - } - - public ByteBuf setLong(int parInt1, long parLong1) { - return this.buf.setLong(parInt1, parLong1); - } - - public ByteBuf setChar(int parInt1, int parInt2) { - return this.buf.setChar(parInt1, parInt2); - } - - public ByteBuf setFloat(int parInt1, float parFloat1) { - return this.buf.setFloat(parInt1, parFloat1); - } - - public ByteBuf setDouble(int parInt1, double parDouble1) { - return this.buf.setDouble(parInt1, parDouble1); + public ByteBuf setBytes(int i, byte[] abyte, int j, int k) { + return this.buf.setBytes(i, abyte, j, k); } public ByteBuf setBytes(int parInt1, ByteBuf parByteBuf) { @@ -540,14 +588,6 @@ public class PacketBuffer extends ByteBuf { } } - public ByteBuf setBytes(int i, byte[] abyte) { - return this.buf.setBytes(i, abyte); - } - - public ByteBuf setBytes(int i, byte[] abyte, int j, int k) { - return this.buf.setBytes(i, abyte, j, k); - } - public ByteBuf setBytes(int i, ByteBuffer bytebuffer) { return this.buf.setBytes(i, bytebuffer); } @@ -556,114 +596,78 @@ public class PacketBuffer extends ByteBuf { return this.buf.setBytes(parInt1, parInputStream, parInt2); } + public ByteBuf setChar(int parInt1, int parInt2) { + return this.buf.setChar(parInt1, parInt2); + } + + public ByteBuf setDouble(int parInt1, double parDouble1) { + return this.buf.setDouble(parInt1, parDouble1); + } + + public ByteBuf setFloat(int parInt1, float parFloat1) { + return this.buf.setFloat(parInt1, parFloat1); + } + + public ByteBuf setIndex(int parInt1, int parInt2) { + return this.buf.setIndex(parInt1, parInt2); + } + + public ByteBuf setInt(int parInt1, int parInt2) { + return this.buf.setInt(parInt1, parInt2); + } + + public ByteBuf setLong(int parInt1, long parLong1) { + return this.buf.setLong(parInt1, parLong1); + } + + public ByteBuf setMedium(int parInt1, int parInt2) { + return this.buf.setMedium(parInt1, parInt2); + } + + public ByteBuf setShort(int parInt1, int parInt2) { + return this.buf.setShort(parInt1, parInt2); + } + public ByteBuf setZero(int parInt1, int parInt2) { return this.buf.setZero(parInt1, parInt2); } - public boolean readBoolean() { - return this.buf.readBoolean(); - } - - public byte readByte() { - return this.buf.readByte(); - } - - public short readUnsignedByte() { - return this.buf.readUnsignedByte(); - } - - public short readShort() { - return this.buf.readShort(); - } - - public int readUnsignedShort() { - return this.buf.readUnsignedShort(); - } - - public int readMedium() { - return this.buf.readMedium(); - } - - public int readUnsignedMedium() { - return this.buf.readUnsignedMedium(); - } - - public int readInt() { - return this.buf.readInt(); - } - - public long readUnsignedInt() { - return this.buf.readUnsignedInt(); - } - - public long readLong() { - return this.buf.readLong(); - } - - public char readChar() { - return this.buf.readChar(); - } - - public float readFloat() { - return this.buf.readFloat(); - } - - public double readDouble() { - return this.buf.readDouble(); - } - - public ByteBuf readBytes(int parInt1) { - return this.buf.readBytes(parInt1); - } - - public ByteBuf readSlice(int parInt1) { - return this.buf.readSlice(parInt1); - } - - public ByteBuf readBytes(ByteBuf bytebuf) { - if (bytebuf instanceof PacketBuffer) { - return this.buf.readBytes(((PacketBuffer) bytebuf).buf); - } else { - return this.buf.readBytes(bytebuf); - } - } - - public ByteBuf readBytes(ByteBuf bytebuf, int i) { - if (bytebuf instanceof PacketBuffer) { - return this.buf.readBytes(((PacketBuffer) bytebuf).buf, i); - } else { - return this.buf.readBytes(bytebuf, i); - } - } - - public ByteBuf readBytes(ByteBuf bytebuf, int i, int j) { - if (bytebuf instanceof PacketBuffer) { - return this.buf.readBytes(((PacketBuffer) bytebuf).buf, i, j); - } else { - return this.buf.readBytes(bytebuf, i, j); - } - } - - public ByteBuf readBytes(byte[] abyte) { - return this.buf.readBytes(abyte); - } - - public ByteBuf readBytes(byte[] abyte, int i, int j) { - return this.buf.readBytes(abyte, i, j); - } - - public ByteBuf readBytes(ByteBuffer bytebuffer) { - return this.buf.readBytes(bytebuffer); - } - - public ByteBuf readBytes(OutputStream parOutputStream, int parInt1) throws IOException { - return this.buf.readBytes(parOutputStream, parInt1); - } - public ByteBuf skipBytes(int parInt1) { return this.buf.skipBytes(parInt1); } + public ByteBuf slice() { + return this.buf.slice(); + } + + public ByteBuf slice(int i, int j) { + return this.buf.slice(i, j); + } + + public String toString() { + return this.buf.toString(); + } + + public String toString(Charset charset) { + return this.buf.toString(charset); + } + + public String toString(int i, int j, Charset charset) { + return this.buf.toString(i, j, charset); + } + + public ByteBuf unwrap() { + return this.buf.unwrap(); + } + + public int writableBytes() { + return this.buf.writableBytes(); + } + + public void writeBlockPos(BlockPos pos) { + this.writeLong(pos.toLong()); + } + public ByteBuf writeBoolean(boolean parFlag) { return this.buf.writeBoolean(parFlag); } @@ -672,32 +676,17 @@ public class PacketBuffer extends ByteBuf { return this.buf.writeByte(parInt1); } - public ByteBuf writeShort(int parInt1) { - return this.buf.writeShort(parInt1); + public void writeByteArray(byte[] array) { + this.writeVarIntToBuffer(array.length); + this.writeBytes(array); } - public ByteBuf writeMedium(int parInt1) { - return this.buf.writeMedium(parInt1); + public ByteBuf writeBytes(byte[] abyte) { + return this.buf.writeBytes(abyte); } - public ByteBuf writeInt(int parInt1) { - return this.buf.writeInt(parInt1); - } - - public ByteBuf writeLong(long parLong1) { - return this.buf.writeLong(parLong1); - } - - public ByteBuf writeChar(int parInt1) { - return this.buf.writeChar(parInt1); - } - - public ByteBuf writeFloat(float parFloat1) { - return this.buf.writeFloat(parFloat1); - } - - public ByteBuf writeDouble(double parDouble1) { - return this.buf.writeDouble(parDouble1); + public ByteBuf writeBytes(byte[] abyte, int i, int j) { + return this.buf.writeBytes(abyte, i, j); } public ByteBuf writeBytes(ByteBuf parByteBuf) { @@ -724,14 +713,6 @@ public class PacketBuffer extends ByteBuf { } } - public ByteBuf writeBytes(byte[] abyte) { - return this.buf.writeBytes(abyte); - } - - public ByteBuf writeBytes(byte[] abyte, int i, int j) { - return this.buf.writeBytes(abyte, i, j); - } - public ByteBuf writeBytes(ByteBuffer bytebuffer) { return this.buf.writeBytes(bytebuffer); } @@ -740,112 +721,129 @@ public class PacketBuffer extends ByteBuf { return this.buf.writeBytes(parInputStream, parInt1); } + public ByteBuf writeChar(int parInt1) { + return this.buf.writeChar(parInt1); + } + + public void writeChatComponent(IChatComponent component) throws IOException { + this.writeString(IChatComponent.Serializer.componentToJson(component)); + } + + public ByteBuf writeDouble(double parDouble1) { + return this.buf.writeDouble(parDouble1); + } + + public void writeEnumValue(Enum value) { + this.writeVarIntToBuffer(value.ordinal()); + } + + public ByteBuf writeFloat(float parFloat1) { + return this.buf.writeFloat(parFloat1); + } + + public ByteBuf writeInt(int parInt1) { + return this.buf.writeInt(parInt1); + } + + /** + * + Writes the ItemStack's ID (short), then size (byte), then damage. (short) + */ + public void writeItemStackToBuffer(ItemStack stack) { + if (stack == null) { + this.writeShort(-1); + } else { + this.writeShort(Item.getIdFromItem(stack.getItem())); + this.writeByte(stack.stackSize); + this.writeShort(stack.getMetadata()); + NBTTagCompound nbttagcompound = null; + if (stack.getItem().isDamageable() || stack.getItem().getShareTag()) { + nbttagcompound = stack.getTagCompound(); + } + + this.writeNBTTagCompoundToBuffer(nbttagcompound); + } + + } + + public ByteBuf writeLong(long parLong1) { + return this.buf.writeLong(parLong1); + } + + public ByteBuf writeMedium(int parInt1) { + return this.buf.writeMedium(parInt1); + } + + /** + * + Writes a compressed NBTTagCompound to this buffer + */ + public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) { + if (nbt == null) { + this.writeByte(0); + } else { + try { + CompressedStreamTools.write(nbt, (DataOutput) (new ByteBufOutputStream(this))); + } catch (IOException ioexception) { + throw new EncoderException(ioexception); + } + } + + } + + public int writerIndex() { + return this.buf.writerIndex(); + } + + public ByteBuf writerIndex(int i) { + return this.buf.writerIndex(i); + } + + public ByteBuf writeShort(int parInt1) { + return this.buf.writeShort(parInt1); + } + + public PacketBuffer writeString(String string) { + byte[] abyte = string.getBytes(StandardCharsets.UTF_8); + if (abyte.length > 32767) { + throw new EncoderException("String too big (was " + string.length() + " bytes encoded, max " + 32767 + ")"); + } else { + this.writeVarIntToBuffer(abyte.length); + this.writeBytes(abyte); + return this; + } + } + + public void writeUuid(EaglercraftUUID uuid) { + this.writeLong(uuid.getMostSignificantBits()); + this.writeLong(uuid.getLeastSignificantBits()); + } + + /** + * + Writes a compressed int to the buffer. The smallest number of bytes to fit + * the passed int will be written. Of each such byte only 7 bits will be used to + * describe the actual value since its most significant bit dictates whether the + * next byte is part of that same int. Micro-optimization for int values that + * are expected to have values below 128. + */ + public void writeVarIntToBuffer(int input) { + while ((input & -128) != 0) { + this.writeByte(input & 127 | 128); + input >>>= 7; + } + + this.writeByte(input); + } + + public void writeVarLong(long value) { + while ((value & -128L) != 0L) { + this.writeByte((int) (value & 127L) | 128); + value >>>= 7; + } + + this.writeByte((int) value); + } + public ByteBuf writeZero(int parInt1) { return this.buf.writeZero(parInt1); } - public int indexOf(int parInt1, int parInt2, byte parByte1) { - return this.buf.indexOf(parInt1, parInt2, parByte1); - } - - public int bytesBefore(byte parByte1) { - return this.buf.bytesBefore(parByte1); - } - - public int bytesBefore(int i, byte b0) { - return this.buf.bytesBefore(i, b0); - } - - public int bytesBefore(int i, int j, byte b0) { - return this.buf.bytesBefore(i, j, b0); - } - - public ByteBuf copy() { - return this.buf.copy(); - } - - public ByteBuf copy(int i, int j) { - return this.buf.copy(i, j); - } - - public ByteBuf slice() { - return this.buf.slice(); - } - - public ByteBuf slice(int i, int j) { - return this.buf.slice(i, j); - } - - public ByteBuf duplicate() { - return this.buf.duplicate(); - } - - public int nioBufferCount() { - return this.buf.nioBufferCount(); - } - - public ByteBuffer nioBuffer() { - return this.buf.nioBuffer(); - } - - public ByteBuffer nioBuffer(int i, int j) { - return this.buf.nioBuffer(i, j); - } - - public ByteBuffer internalNioBuffer(int parInt1, int parInt2) { - return this.buf.internalNioBuffer(parInt1, parInt2); - } - - public ByteBuffer[] nioBuffers() { - return this.buf.nioBuffers(); - } - - public ByteBuffer[] nioBuffers(int i, int j) { - return this.buf.nioBuffers(i, j); - } - - public boolean hasArray() { - return this.buf.hasArray(); - } - - public byte[] array() { - return this.buf.array(); - } - - public int arrayOffset() { - return this.buf.arrayOffset(); - } - - public boolean hasMemoryAddress() { - return this.buf.hasMemoryAddress(); - } - - public long memoryAddress() { - return this.buf.memoryAddress(); - } - - public String toString(Charset charset) { - return this.buf.toString(charset); - } - - public String toString(int i, int j, Charset charset) { - return this.buf.toString(i, j, charset); - } - - public int hashCode() { - return this.buf.hashCode(); - } - - public boolean equals(Object object) { - return this.buf.equals(object); - } - - public int compareTo(ByteBuf bytebuf) { - return this.buf.compareTo(bytebuf); - } - - public String toString() { - return this.buf.toString(); - } - } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/ServerStatusResponse.java b/src/game/java/net/minecraft/network/ServerStatusResponse.java index d696b1e6..273f5096 100644 --- a/src/game/java/net/minecraft/network/ServerStatusResponse.java +++ b/src/game/java/net/minecraft/network/ServerStatusResponse.java @@ -10,81 +10,31 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerStatusResponse { - private IChatComponent serverMotd; - private ServerStatusResponse.PlayerCountData playerCount; - private ServerStatusResponse.MinecraftProtocolVersionIdentifier protocolVersion; - private String favicon; - - public IChatComponent getServerDescription() { - return this.serverMotd; - } - - public void setServerDescription(IChatComponent motd) { - this.serverMotd = motd; - } - - public ServerStatusResponse.PlayerCountData getPlayerCountData() { - return this.playerCount; - } - - public void setPlayerCountData(ServerStatusResponse.PlayerCountData countData) { - this.playerCount = countData; - } - - public ServerStatusResponse.MinecraftProtocolVersionIdentifier getProtocolVersionInfo() { - return this.protocolVersion; - } - - public void setProtocolVersionInfo(ServerStatusResponse.MinecraftProtocolVersionIdentifier protocolVersionData) { - this.protocolVersion = protocolVersionData; - } - - public void setFavicon(String faviconBlob) { - this.favicon = faviconBlob; - } - - public String getFavicon() { - return this.favicon; - } - public static class MinecraftProtocolVersionIdentifier { - private final String name; - private final int protocol; - - public MinecraftProtocolVersionIdentifier(String nameIn, int protocolIn) { - this.name = nameIn; - this.protocol = protocolIn; - } - - public String getName() { - return this.name; - } - - public int getProtocol() { - return this.protocol; - } - public static class Serializer implements JSONTypeCodec { public ServerStatusResponse.MinecraftProtocolVersionIdentifier deserialize(JSONObject jsonobject) @@ -102,34 +52,26 @@ public class ServerStatusResponse { return jsonobject; } } + + private final String name; + + private final int protocol; + + public MinecraftProtocolVersionIdentifier(String nameIn, int protocolIn) { + this.name = nameIn; + this.protocol = protocolIn; + } + + public String getName() { + return this.name; + } + + public int getProtocol() { + return this.protocol; + } } public static class PlayerCountData { - private final int maxPlayers; - private final int onlinePlayerCount; - private GameProfile[] players; - - public PlayerCountData(int maxOnlinePlayers, int onlinePlayers) { - this.maxPlayers = maxOnlinePlayers; - this.onlinePlayerCount = onlinePlayers; - } - - public int getMaxPlayers() { - return this.maxPlayers; - } - - public int getOnlinePlayerCount() { - return this.onlinePlayerCount; - } - - public GameProfile[] getPlayers() { - return this.players; - } - - public void setPlayers(GameProfile[] playersIn) { - this.players = playersIn; - } - public static class Serializer implements JSONTypeCodec { public ServerStatusResponse.PlayerCountData deserialize(JSONObject jsonobject) throws JSONException { ServerStatusResponse.PlayerCountData serverstatusresponse$playercountdata = new ServerStatusResponse.PlayerCountData( @@ -176,6 +118,32 @@ public class ServerStatusResponse { return jsonobject; } } + + private final int maxPlayers; + private final int onlinePlayerCount; + + private GameProfile[] players; + + public PlayerCountData(int maxOnlinePlayers, int onlinePlayers) { + this.maxPlayers = maxOnlinePlayers; + this.onlinePlayerCount = onlinePlayers; + } + + public int getMaxPlayers() { + return this.maxPlayers; + } + + public int getOnlinePlayerCount() { + return this.onlinePlayerCount; + } + + public GameProfile[] getPlayers() { + return this.players; + } + + public void setPlayers(GameProfile[] playersIn) { + this.players = playersIn; + } } public static class Serializer implements JSONTypeCodec { @@ -229,4 +197,44 @@ public class ServerStatusResponse { return jsonobject; } } + + private IChatComponent serverMotd; + + private ServerStatusResponse.PlayerCountData playerCount; + + private ServerStatusResponse.MinecraftProtocolVersionIdentifier protocolVersion; + + private String favicon; + + public String getFavicon() { + return this.favicon; + } + + public ServerStatusResponse.PlayerCountData getPlayerCountData() { + return this.playerCount; + } + + public ServerStatusResponse.MinecraftProtocolVersionIdentifier getProtocolVersionInfo() { + return this.protocolVersion; + } + + public IChatComponent getServerDescription() { + return this.serverMotd; + } + + public void setFavicon(String faviconBlob) { + this.favicon = faviconBlob; + } + + public void setPlayerCountData(ServerStatusResponse.PlayerCountData countData) { + this.playerCount = countData; + } + + public void setProtocolVersionInfo(ServerStatusResponse.MinecraftProtocolVersionIdentifier protocolVersionData) { + this.protocolVersion = protocolVersionData; + } + + public void setServerDescription(IChatComponent motd) { + this.serverMotd = motd; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/handshake/INetHandlerHandshakeServer.java b/src/game/java/net/minecraft/network/handshake/INetHandlerHandshakeServer.java index 8a8dbdf3..de13febd 100644 --- a/src/game/java/net/minecraft/network/handshake/INetHandlerHandshakeServer.java +++ b/src/game/java/net/minecraft/network/handshake/INetHandlerHandshakeServer.java @@ -3,33 +3,35 @@ package net.minecraft.network.handshake; import net.minecraft.network.INetHandler; import net.minecraft.network.handshake.client.C00Handshake; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface INetHandlerHandshakeServer extends INetHandler { - /**+ - * There are two recognized intentions for initiating a - * handshake: logging in and acquiring server status. The - * NetworkManager's protocol will be reconfigured according to - * the specified intention, although a login-intention must pass - * a versioncheck or receive a disconnect otherwise + /** + * + There are two recognized intentions for initiating a handshake: logging in + * and acquiring server status. The NetworkManager's protocol will be + * reconfigured according to the specified intention, although a login-intention + * must pass a versioncheck or receive a disconnect otherwise */ void processHandshake(C00Handshake var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/handshake/client/C00Handshake.java b/src/game/java/net/minecraft/network/handshake/client/C00Handshake.java index eea85953..7c02c0a9 100644 --- a/src/game/java/net/minecraft/network/handshake/client/C00Handshake.java +++ b/src/game/java/net/minecraft/network/handshake/client/C00Handshake.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.handshake.INetHandlerHandshakeServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,8 +46,23 @@ public class C00Handshake implements Packet { this.requestedState = requestedState; } - /**+ - * Reads the raw packet data from the data stream. + public int getProtocolVersion() { + return this.protocolVersion; + } + + public EnumConnectionState getRequestedState() { + return this.requestedState; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerHandshakeServer inethandlerhandshakeserver) { + inethandlerhandshakeserver.processHandshake(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.protocolVersion = parPacketBuffer.readVarIntFromBuffer(); @@ -53,8 +71,8 @@ public class C00Handshake implements Packet { this.requestedState = EnumConnectionState.getById(parPacketBuffer.readVarIntFromBuffer()); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.protocolVersion); @@ -62,19 +80,4 @@ public class C00Handshake implements Packet { parPacketBuffer.writeShort(this.port); parPacketBuffer.writeVarIntToBuffer(this.requestedState.getId()); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerHandshakeServer inethandlerhandshakeserver) { - inethandlerhandshakeserver.processHandshake(this); - } - - public EnumConnectionState getRequestedState() { - return this.requestedState; - } - - public int getProtocolVersion() { - return this.protocolVersion; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/login/INetHandlerLoginClient.java b/src/game/java/net/minecraft/network/login/INetHandlerLoginClient.java index 0b12529e..42593385 100644 --- a/src/game/java/net/minecraft/network/login/INetHandlerLoginClient.java +++ b/src/game/java/net/minecraft/network/login/INetHandlerLoginClient.java @@ -6,32 +6,35 @@ import net.minecraft.network.login.server.S01PacketEncryptionRequest; import net.minecraft.network.login.server.S02PacketLoginSuccess; import net.minecraft.network.login.server.S03PacketEnableCompression; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface INetHandlerLoginClient extends INetHandler { - void handleEncryptionRequest(S01PacketEncryptionRequest var1); - - void handleLoginSuccess(S02PacketLoginSuccess var1); - void handleDisconnect(S00PacketDisconnect var1); void handleEnableCompression(S03PacketEnableCompression var1); + + void handleEncryptionRequest(S01PacketEncryptionRequest var1); + + void handleLoginSuccess(S02PacketLoginSuccess var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/login/INetHandlerLoginServer.java b/src/game/java/net/minecraft/network/login/INetHandlerLoginServer.java index debb8655..3d48e50b 100644 --- a/src/game/java/net/minecraft/network/login/INetHandlerLoginServer.java +++ b/src/game/java/net/minecraft/network/login/INetHandlerLoginServer.java @@ -4,28 +4,31 @@ import net.minecraft.network.INetHandler; import net.minecraft.network.login.client.C00PacketLoginStart; import net.minecraft.network.login.client.C01PacketEncryptionResponse; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface INetHandlerLoginServer extends INetHandler { - void processLoginStart(C00PacketLoginStart var1); - void processEncryptionResponse(C01PacketEncryptionResponse var1); + + void processLoginStart(C00PacketLoginStart var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/login/client/C00PacketLoginStart.java b/src/game/java/net/minecraft/network/login/client/C00PacketLoginStart.java index 5d6f7b4b..f1c9cc48 100644 --- a/src/game/java/net/minecraft/network/login/client/C00PacketLoginStart.java +++ b/src/game/java/net/minecraft/network/login/client/C00PacketLoginStart.java @@ -1,28 +1,32 @@ package net.minecraft.network.login.client; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import java.io.IOException; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.login.INetHandlerLoginServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,8 +50,35 @@ public class C00PacketLoginStart implements Packet { this.brandUUID = brandUUID; } - /**+ - * Reads the raw packet data from the data stream. + public EaglercraftUUID getBrandUUID() { + return this.brandUUID; + } + + public byte[] getCape() { + return this.cape; + } + + public GameProfile getProfile() { + return this.profile; + } + + public byte[] getProtocols() { + return this.protocols; + } + + public byte[] getSkin() { + return this.skin; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerLoginServer inethandlerloginserver) { + inethandlerloginserver.processLoginStart(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.profile = new GameProfile((EaglercraftUUID) null, parPacketBuffer.readStringFromBuffer(16)); @@ -57,8 +88,8 @@ public class C00PacketLoginStart implements Packet { this.brandUUID = parPacketBuffer.readableBytes() > 0 ? parPacketBuffer.readUuid() : null; } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeString(this.profile.getName()); @@ -67,31 +98,4 @@ public class C00PacketLoginStart implements Packet { parPacketBuffer.writeByteArray(this.protocols); parPacketBuffer.writeUuid(brandUUID); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerLoginServer inethandlerloginserver) { - inethandlerloginserver.processLoginStart(this); - } - - public GameProfile getProfile() { - return this.profile; - } - - public byte[] getSkin() { - return this.skin; - } - - public byte[] getCape() { - return this.cape; - } - - public byte[] getProtocols() { - return this.protocols; - } - - public EaglercraftUUID getBrandUUID() { - return this.brandUUID; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/login/client/C01PacketEncryptionResponse.java b/src/game/java/net/minecraft/network/login/client/C01PacketEncryptionResponse.java index 4e994bdd..4ae24eda 100644 --- a/src/game/java/net/minecraft/network/login/client/C01PacketEncryptionResponse.java +++ b/src/game/java/net/minecraft/network/login/client/C01PacketEncryptionResponse.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.login.INetHandlerLoginServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,29 +41,29 @@ public class C01PacketEncryptionResponse implements Packet { this.reason = reasonIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.reason = parPacketBuffer.readChatComponent(); + public IChatComponent func_149603_c() { + return this.reason; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeChatComponent(this.reason); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerLoginClient inethandlerloginclient) { inethandlerloginclient.handleDisconnect(this); } - public IChatComponent func_149603_c() { - return this.reason; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.reason = parPacketBuffer.readChatComponent(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeChatComponent(this.reason); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/login/server/S01PacketEncryptionRequest.java b/src/game/java/net/minecraft/network/login/server/S01PacketEncryptionRequest.java index 0d2386b6..deba074c 100644 --- a/src/game/java/net/minecraft/network/login/server/S01PacketEncryptionRequest.java +++ b/src/game/java/net/minecraft/network/login/server/S01PacketEncryptionRequest.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.login.INetHandlerLoginClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,8 +43,23 @@ public class S01PacketEncryptionRequest implements Packet { this.selectedProtocol = selectedProtocol; } - /**+ - * Reads the raw packet data from the data stream. + public GameProfile getProfile() { + return this.profile; + } + + public int getSelectedProtocol() { + return selectedProtocol; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerLoginClient inethandlerloginclient) { + inethandlerloginclient.handleLoginSuccess(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { String s = parPacketBuffer.readStringFromBuffer(36); @@ -51,8 +69,8 @@ public class S02PacketLoginSuccess implements Packet { this.profile = new GameProfile(uuid, s1); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { EaglercraftUUID uuid = this.profile.getId(); @@ -62,19 +80,4 @@ public class S02PacketLoginSuccess implements Packet { parPacketBuffer.writeShort(selectedProtocol); } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerLoginClient inethandlerloginclient) { - inethandlerloginclient.handleLoginSuccess(this); - } - - public GameProfile getProfile() { - return this.profile; - } - - public int getSelectedProtocol() { - return selectedProtocol; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/login/server/S03PacketEnableCompression.java b/src/game/java/net/minecraft/network/login/server/S03PacketEnableCompression.java index 77d07573..a32b4cf2 100644 --- a/src/game/java/net/minecraft/network/login/server/S03PacketEnableCompression.java +++ b/src/game/java/net/minecraft/network/login/server/S03PacketEnableCompression.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.login.INetHandlerLoginClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,28 +39,28 @@ public class S03PacketEnableCompression implements Packet Registers any changes + * locally + */ + void handleEntityMetadata(S1CPacketEntityMetadata var1); + + /** + * + Updates the specified entity's position by the specified relative moment + * and absolute rotation. Note that subclassing of the packet allows for the + * specification of a subset of this data (e.g. only rel. position, abs. + * rotation or both). */ void handleEntityMovement(S14PacketEntity var1); - /**+ - * Handles changes in player positioning and rotation such as - * when travelling to a new dimension, (re)spawning, mounting - * horses etc. Seems to immediately reply to the server with the - * clients post-processing perspective on the player positioning - */ - void handlePlayerPosLook(S08PacketPlayerPosLook var1); + void handleEntityNBT(S49PacketUpdateEntityNBT var1); - /**+ - * Spawns a specified number of particles at the specified - * location with a randomized displacement according to - * specified bounds + /** + * + Updates en entity's attributes and their respective modifiers, which are + * used for speed bonusses (player sprinting, animals fleeing, baby speed), + * weapon/tool attackDamage, hostiles followRange randomization, zombie + * maxHealth and knockback resistance as well as reinforcement spawning chance. + */ + void handleEntityProperties(S20PacketEntityProperties var1); + + /** + * + Invokes the entities' handleUpdateHealth method which is implemented in + * LivingBase (hurt/death), MinecartMobSpawner (spawn delay), FireworkRocket & + * MinecartTNT (explosion), IronGolem (throwing,...), Witch (spawn particles), + * Zombie (villager transformation), Animal (breeding mode particles), Horse + * (breeding/smoke particles), Sheep (...), Tameable (...), Villager (particles + * for breeding mode, angry and happy), Wolf (...) + */ + void handleEntityStatus(S19PacketEntityStatus var1); + + /** + * + Updates an entity's position and rotation as specified by the packet + */ + void handleEntityTeleport(S18PacketEntityTeleport var1); + + /** + * + Sets the velocity of the specified entity to the specified value + */ + void handleEntityVelocity(S12PacketEntityVelocity var1); + + /** + * + Initiates a new explosion (sound, particles, drop spawn) for the affected + * blocks indicated by the packet. + */ + void handleExplosion(S27PacketExplosion var1); + + /** + * + Updates which hotbar slot of the player is currently selected + */ + void handleHeldItemChange(S09PacketHeldItemChange var1); + + /** + * + Registers some server properties + * (gametype,hardcore-mode,terraintype,difficulty,player limit), creates a new + * WorldClient and sets the player initial dimension + */ + void handleJoinGame(S01PacketJoinGame var1); + + void handleKeepAlive(S00PacketKeepAlive var1); + + void handleMapChunkBulk(S26PacketMapChunkBulk var1); + + /** + * + Updates the worlds MapStorage with the specified MapData for the specified + * map-identifier and invokes a MapItemRenderer for it + */ + void handleMaps(S34PacketMaps var1); + + /** + * + Received from the servers PlayerManager if between 1 and 64 blocks in a + * chunk are changed. If only one block requires an update, the server sends + * S23PacketBlockChange and if 64 or more blocks are changed, the server sends + * S21PacketChunkData + */ + void handleMultiBlockChange(S22PacketMultiBlockChange var1); + + /** + * + Displays a GUI by ID. In order starting from id 0: Chest, Workbench, + * Furnace, Dispenser, Enchanting table, Brewing stand, Villager merchant, + * Beacon, Anvil, Hopper, Dropper, Horse + */ + void handleOpenWindow(S2DPacketOpenWindow var1); + + /** + * + Spawns a specified number of particles at the specified location with a + * randomized displacement according to specified bounds */ void handleParticles(S2APacketParticles var1); void handlePlayerAbilities(S39PacketPlayerAbilities var1); + void handlePlayerListHeaderFooter(S47PacketPlayerListHeaderFooter var1); + void handlePlayerListItem(S38PacketPlayerListItem var1); - /**+ - * Locally eliminates the entities. Invoked by the server when - * the items are in fact destroyed, or the player is no longer - * registered as required to monitor them. The latter happens - * when distance between the player and item increases beyond a - * certain treshold (typically the viewing distance) + /** + * + Handles changes in player positioning and rotation such as when travelling + * to a new dimension, (re)spawning, mounting horses etc. Seems to immediately + * reply to the server with the clients post-processing perspective on the + * player positioning */ - void handleDestroyEntities(S13PacketDestroyEntities var1); + void handlePlayerPosLook(S08PacketPlayerPosLook var1); void handleRemoveEntityEffect(S1EPacketRemoveEntityEffect var1); + void handleResourcePack(S48PacketResourcePackSend var1); + void handleRespawn(S07PacketRespawn var1); - /**+ - * Updates the direction in which the specified entity is - * looking, normally this head rotation is independent of the - * rotation of the entity itself + /** + * + May create a scoreboard objective, remove an objective from the scoreboard + * or update an objectives' displayname */ - void handleEntityHeadLook(S19PacketEntityHeadLook var1); - - /**+ - * Updates which hotbar slot of the player is currently selected - */ - void handleHeldItemChange(S09PacketHeldItemChange var1); - - /**+ - * Removes or sets the ScoreObjective to be displayed at a - * particular scoreboard position (list, sidebar, below name) - */ - void handleDisplayScoreboard(S3DPacketDisplayScoreboard var1); - - /**+ - * Invoked when the server registers new proximate objects in - * your watchlist or when objects in your watchlist have changed - * -> Registers any changes locally - */ - void handleEntityMetadata(S1CPacketEntityMetadata var1); - - /**+ - * Sets the velocity of the specified entity to the specified - * value - */ - void handleEntityVelocity(S12PacketEntityVelocity var1); - - void handleEntityEquipment(S04PacketEntityEquipment var1); - - void handleSetExperience(S1FPacketSetExperience var1); - - void handleUpdateHealth(S06PacketUpdateHealth var1); - - /**+ - * Updates a team managed by the scoreboard: Create/Remove the - * team registration, Register/Remove the - * player-team-memberships, Set team displayname/prefix/suffix - * and/or whether friendly fire is enabled - */ - void handleTeams(S3EPacketTeams var1); - - /**+ - * Either updates the score with a specified value or removes - * the score for an objective - */ - void handleUpdateScore(S3CPacketUpdateScore var1); - - void handleSpawnPosition(S05PacketSpawnPosition var1); - - void handleTimeUpdate(S03PacketTimeUpdate var1); - - /**+ - * Updates a specified sign with the specified text lines - */ - void handleUpdateSign(S33PacketUpdateSign var1); - - void handleSoundEffect(S29PacketSoundEffect var1); - - void handleCollectItem(S0DPacketCollectItem var1); - - /**+ - * Updates an entity's position and rotation as specified by the - * packet - */ - void handleEntityTeleport(S18PacketEntityTeleport var1); - - /**+ - * Updates en entity's attributes and their respective - * modifiers, which are used for speed bonusses (player - * sprinting, animals fleeing, baby speed), weapon/tool - * attackDamage, hostiles followRange randomization, zombie - * maxHealth and knockback resistance as well as reinforcement - * spawning chance. - */ - void handleEntityProperties(S20PacketEntityProperties var1); - - void handleEntityEffect(S1DPacketEntityEffect var1); - - void handleCombatEvent(S42PacketCombatEvent var1); + void handleScoreboardObjective(S3BPacketScoreboardObjective var1); void handleServerDifficulty(S41PacketServerDifficulty var1); - void handleCamera(S43PacketCamera var1); + void handleSetCompressionLevel(S46PacketSetCompressionLevel var1); - void handleWorldBorder(S44PacketWorldBorder var1); + void handleSetExperience(S1FPacketSetExperience var1); + + /** + * + Handles pickin up an ItemStack or dropping one in your inventory or an open + * (non-creative) container + */ + void handleSetSlot(S2FPacketSetSlot var1); + + /** + * + Creates a sign in the specified location if it didn't exist and opens the + * GUI to edit its text + */ + void handleSignEditorOpen(S36PacketSignEditorOpen var1); + + void handleSoundEffect(S29PacketSoundEffect var1); + + /** + * + Spawns an experience orb and sets its value (amount of XP) + */ + void handleSpawnExperienceOrb(S11PacketSpawnExperienceOrb var1); + + /** + * + Handles globally visible entities. Used in vanilla for lightning bolts + */ + void handleSpawnGlobalEntity(S2CPacketSpawnGlobalEntity var1); + + /** + * + Spawns the mob entity at the specified location, with the specified + * rotation, momentum and type. Updates the entities Datawatchers with the + * entity metadata specified in the packet + */ + void handleSpawnMob(S0FPacketSpawnMob var1); + + /** + * + Spawns an instance of the objecttype indicated by the packet and sets its + * position and momentum + */ + void handleSpawnObject(S0EPacketSpawnObject var1); + + /** + * + Handles the spawning of a painting object + */ + void handleSpawnPainting(S10PacketSpawnPainting var1); + + /** + * + Handles the creation of a nearby player entity, sets the position and held + * item + */ + void handleSpawnPlayer(S0CPacketSpawnPlayer var1); + + void handleSpawnPosition(S05PacketSpawnPosition var1); + + /** + * + Updates the players statistics or achievements + */ + void handleStatistics(S37PacketStatistics var1); + + /** + * + Displays the available command-completion options the server knows of + */ + void handleTabComplete(S3APacketTabComplete var1); + + /** + * + Updates a team managed by the scoreboard: Create/Remove the team + * registration, Register/Remove the player-team-memberships, Set team + * displayname/prefix/suffix and/or whether friendly fire is enabled + */ + void handleTeams(S3EPacketTeams var1); + + void handleTimeUpdate(S03PacketTimeUpdate var1); void handleTitle(S45PacketTitle var1); - void handleSetCompressionLevel(S46PacketSetCompressionLevel var1); + void handleUpdateHealth(S06PacketUpdateHealth var1); - void handlePlayerListHeaderFooter(S47PacketPlayerListHeaderFooter var1); + /** + * + Either updates the score with a specified value or removes the score for an + * objective + */ + void handleUpdateScore(S3CPacketUpdateScore var1); - void handleResourcePack(S48PacketResourcePackSend var1); + /** + * + Updates a specified sign with the specified text lines + */ + void handleUpdateSign(S33PacketUpdateSign var1); - void handleEntityNBT(S49PacketUpdateEntityNBT var1); + /** + * + Updates the NBTTagCompound metadata of instances of the following + * entitytypes: Mob spawners, command blocks, beacons, skulls, flowerpot + */ + void handleUpdateTileEntity(S35PacketUpdateTileEntity var1); + + /** + * + Retrieves the player identified by the packet, puts him to sleep if + * possible (and flags whether all players are asleep) + */ + void handleUseBed(S0APacketUseBed var1); + + /** + * + Handles the placement of a specified ItemStack in a specified + * container/inventory slot + */ + void handleWindowItems(S30PacketWindowItems var1); + + /** + * + Sets the progressbar of the opened window to the specified value + */ + void handleWindowProperty(S31PacketWindowProperty var1); + + void handleWorldBorder(S44PacketWorldBorder var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/INetHandlerPlayServer.java b/src/game/java/net/minecraft/network/play/INetHandlerPlayServer.java index 2059778b..76b1e2aa 100644 --- a/src/game/java/net/minecraft/network/play/INetHandlerPlayServer.java +++ b/src/game/java/net/minecraft/network/play/INetHandlerPlayServer.java @@ -25,22 +25,25 @@ import net.minecraft.network.play.client.C17PacketCustomPayload; import net.minecraft.network.play.client.C18PacketSpectate; import net.minecraft.network.play.client.C19PacketResourcePackStatus; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,132 +51,121 @@ import net.minecraft.network.play.client.C19PacketResourcePackStatus; public interface INetHandlerPlayServer extends INetHandler { void handleAnimation(C0APacketAnimation var1); - /**+ - * Process chat messages (broadcast back to clients) and - * commands (executes) - */ - void processChatMessage(C01PacketChatMessage var1); - - /**+ - * Retrieves possible tab completions for the requested command - * string and sends them to the client - */ - void processTabComplete(C14PacketTabComplete var1); - - /**+ - * Processes the client status updates: respawn attempt from - * player, opening statistics or achievements, or acquiring - * 'open inventory' achievement - */ - void processClientStatus(C16PacketClientStatus var1); - - /**+ - * Updates serverside copy of client settings: language, render - * distance, chat visibility, chat colours, difficulty, and - * whether to show the cape - */ - void processClientSettings(C15PacketClientSettings var1); - - /**+ - * Received in response to the server requesting to confirm that - * the client-side open container matches the servers' after a - * mismatched container-slot manipulation. It will unlock the - * player's ability to manipulate the container contents - */ - void processConfirmTransaction(C0FPacketConfirmTransaction var1); - - /**+ - * Enchants the item identified by the packet given some - * convoluted conditions (matching window, which - * should/shouldn't be in use?) - */ - void processEnchantItem(C11PacketEnchantItem var1); - - /**+ - * Executes a container/inventory slot manipulation as indicated - * by the packet. Sends the serverside result if they didn't - * match the indicated result and prevents further manipulation - * by the player until he confirms that it has the same open - * container/inventory - */ - void processClickWindow(C0EPacketClickWindow var1); - - /**+ - * Processes the client closing windows (container) - */ - void processCloseWindow(C0DPacketCloseWindow var1); - - /**+ - * Synchronizes serverside and clientside book contents and - * signing - */ - void processVanilla250Packet(C17PacketCustomPayload var1); - - /**+ - * Processes interactions ((un)leashing, opening command block - * GUI) and attacks on an entity with players currently equipped - * item - */ - void processUseEntity(C02PacketUseEntity var1); - - /**+ - * Updates a players' ping statistics - */ - void processKeepAlive(C00PacketKeepAlive var1); - - /**+ - * Processes clients perspective on player positioning and/or - * orientation - */ - void processPlayer(C03PacketPlayer var1); - - /**+ - * Processes a player starting/stopping flying - */ - void processPlayerAbilities(C13PacketPlayerAbilities var1); - - /**+ - * Processes the player initiating/stopping digging on a - * particular spot, as well as a player dropping items?. (0: - * initiated, 1: reinitiated, 2? , 3-4 drop item (respectively - * without or with player control), 5: stopped; x,y,z, side - * clicked on;) - */ - void processPlayerDigging(C07PacketPlayerDigging var1); - - /**+ - * Processes a range of action-types: sneaking, sprinting, - * waking from sleep, opening the inventory or setting jump - * height of the horse the player is riding - */ - void processEntityAction(C0BPacketEntityAction var1); - - /**+ - * Processes player movement input. Includes walking, strafing, - * jumping, sneaking; excludes riding and toggling - * flying/sprinting - */ - void processInput(C0CPacketInput var1); - - /**+ - * Updates which quickbar slot is selected - */ - void processHeldItemChange(C09PacketHeldItemChange var1); - - /**+ - * Update the server with an ItemStack in a slot. - */ - void processCreativeInventoryAction(C10PacketCreativeInventoryAction var1); - - void processUpdateSign(C12PacketUpdateSign var1); - - /**+ - * Processes block placement and block activation (anvil, - * furnace, etc.) - */ - void processPlayerBlockPlacement(C08PacketPlayerBlockPlacement var1); + void handleResourcePackStatus(C19PacketResourcePackStatus var1); void handleSpectate(C18PacketSpectate var1); - void handleResourcePackStatus(C19PacketResourcePackStatus var1); + /** + * + Process chat messages (broadcast back to clients) and commands (executes) + */ + void processChatMessage(C01PacketChatMessage var1); + + /** + * + Executes a container/inventory slot manipulation as indicated by the + * packet. Sends the serverside result if they didn't match the indicated result + * and prevents further manipulation by the player until he confirms that it has + * the same open container/inventory + */ + void processClickWindow(C0EPacketClickWindow var1); + + /** + * + Updates serverside copy of client settings: language, render distance, chat + * visibility, chat colours, difficulty, and whether to show the cape + */ + void processClientSettings(C15PacketClientSettings var1); + + /** + * + Processes the client status updates: respawn attempt from player, opening + * statistics or achievements, or acquiring 'open inventory' achievement + */ + void processClientStatus(C16PacketClientStatus var1); + + /** + * + Processes the client closing windows (container) + */ + void processCloseWindow(C0DPacketCloseWindow var1); + + /** + * + Received in response to the server requesting to confirm that the + * client-side open container matches the servers' after a mismatched + * container-slot manipulation. It will unlock the player's ability to + * manipulate the container contents + */ + void processConfirmTransaction(C0FPacketConfirmTransaction var1); + + /** + * + Update the server with an ItemStack in a slot. + */ + void processCreativeInventoryAction(C10PacketCreativeInventoryAction var1); + + /** + * + Enchants the item identified by the packet given some convoluted conditions + * (matching window, which should/shouldn't be in use?) + */ + void processEnchantItem(C11PacketEnchantItem var1); + + /** + * + Processes a range of action-types: sneaking, sprinting, waking from sleep, + * opening the inventory or setting jump height of the horse the player is + * riding + */ + void processEntityAction(C0BPacketEntityAction var1); + + /** + * + Updates which quickbar slot is selected + */ + void processHeldItemChange(C09PacketHeldItemChange var1); + + /** + * + Processes player movement input. Includes walking, strafing, jumping, + * sneaking; excludes riding and toggling flying/sprinting + */ + void processInput(C0CPacketInput var1); + + /** + * + Updates a players' ping statistics + */ + void processKeepAlive(C00PacketKeepAlive var1); + + /** + * + Processes clients perspective on player positioning and/or orientation + */ + void processPlayer(C03PacketPlayer var1); + + /** + * + Processes a player starting/stopping flying + */ + void processPlayerAbilities(C13PacketPlayerAbilities var1); + + /** + * + Processes block placement and block activation (anvil, furnace, etc.) + */ + void processPlayerBlockPlacement(C08PacketPlayerBlockPlacement var1); + + /** + * + Processes the player initiating/stopping digging on a particular spot, as + * well as a player dropping items?. (0: initiated, 1: reinitiated, 2? , 3-4 + * drop item (respectively without or with player control), 5: stopped; x,y,z, + * side clicked on;) + */ + void processPlayerDigging(C07PacketPlayerDigging var1); + + /** + * + Retrieves possible tab completions for the requested command string and + * sends them to the client + */ + void processTabComplete(C14PacketTabComplete var1); + + void processUpdateSign(C12PacketUpdateSign var1); + + /** + * + Processes interactions ((un)leashing, opening command block GUI) and + * attacks on an entity with players currently equipped item + */ + void processUseEntity(C02PacketUseEntity var1); + + /** + * + Synchronizes serverside and clientside book contents and signing + */ + void processVanilla250Packet(C17PacketCustomPayload var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C00PacketKeepAlive.java b/src/game/java/net/minecraft/network/play/client/C00PacketKeepAlive.java index 1001434f..baef2f64 100644 --- a/src/game/java/net/minecraft/network/play/client/C00PacketKeepAlive.java +++ b/src/game/java/net/minecraft/network/play/client/C00PacketKeepAlive.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,28 +39,28 @@ public class C00PacketKeepAlive implements Packet { this.key = key; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public int getKey() { + return this.key; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer inethandlerplayserver) { inethandlerplayserver.processKeepAlive(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.key = parPacketBuffer.readVarIntFromBuffer(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.key); } - - public int getKey() { - return this.key; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C01PacketChatMessage.java b/src/game/java/net/minecraft/network/play/client/C01PacketChatMessage.java index eae02abe..7c6ee1ec 100644 --- a/src/game/java/net/minecraft/network/play/client/C01PacketChatMessage.java +++ b/src/game/java/net/minecraft/network/play/client/C01PacketChatMessage.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,28 +43,28 @@ public class C01PacketChatMessage implements Packet { this.message = messageIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.message = parPacketBuffer.readStringFromBuffer(100); + public String getMessage() { + return this.message; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeString(this.message); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer inethandlerplayserver) { inethandlerplayserver.processChatMessage(this); } - public String getMessage() { - return this.message; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.message = parPacketBuffer.readStringFromBuffer(100); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeString(this.message); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C02PacketUseEntity.java b/src/game/java/net/minecraft/network/play/client/C02PacketUseEntity.java index 8ceefc7a..ae2e610b 100644 --- a/src/game/java/net/minecraft/network/play/client/C02PacketUseEntity.java +++ b/src/game/java/net/minecraft/network/play/client/C02PacketUseEntity.java @@ -9,29 +9,37 @@ import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C02PacketUseEntity implements Packet { + public static enum Action { + INTERACT, ATTACK, INTERACT_AT; + } + private int entityId; private C02PacketUseEntity.Action action; + private Vec3 hitVec; public C02PacketUseEntity() { @@ -47,8 +55,27 @@ public class C02PacketUseEntity implements Packet { this.hitVec = hitVec; } - /**+ - * Reads the raw packet data from the data stream. + public C02PacketUseEntity.Action getAction() { + return this.action; + } + + public Entity getEntityFromWorld(World worldIn) { + return worldIn.getEntityByID(this.entityId); + } + + public Vec3 getHitVec() { + return this.hitVec; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processUseEntity(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readVarIntFromBuffer(); @@ -60,8 +87,8 @@ public class C02PacketUseEntity implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityId); @@ -73,27 +100,4 @@ public class C02PacketUseEntity implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processUseEntity(this); - } - - public Entity getEntityFromWorld(World worldIn) { - return worldIn.getEntityByID(this.entityId); - } - - public C02PacketUseEntity.Action getAction() { - return this.action; - } - - public Vec3 getHitVec() { - return this.hitVec; - } - - public static enum Action { - INTERACT, ATTACK, INTERACT_AT; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C03PacketPlayer.java b/src/game/java/net/minecraft/network/play/client/C03PacketPlayer.java index b620de63..9a2bd551 100644 --- a/src/game/java/net/minecraft/network/play/client/C03PacketPlayer.java +++ b/src/game/java/net/minecraft/network/play/client/C03PacketPlayer.java @@ -6,100 +6,30 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C03PacketPlayer implements Packet { - protected double x; - protected double y; - protected double z; - protected float yaw; - protected float pitch; - protected boolean onGround; - protected boolean moving; - protected boolean rotating; - - public C03PacketPlayer() { - } - - public C03PacketPlayer(boolean isOnGround) { - this.onGround = isOnGround; - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processPlayer(this); - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.onGround = parPacketBuffer.readUnsignedByte() != 0; - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.onGround ? 1 : 0); - } - - public double getPositionX() { - return this.x; - } - - public double getPositionY() { - return this.y; - } - - public double getPositionZ() { - return this.z; - } - - public float getYaw() { - return this.yaw; - } - - public float getPitch() { - return this.pitch; - } - - public boolean isOnGround() { - return this.onGround; - } - - public boolean isMoving() { - return this.moving; - } - - public boolean getRotating() { - return this.rotating; - } - - public void setMoving(boolean isMoving) { - this.moving = isMoving; - } - public static class C04PacketPlayerPosition extends C03PacketPlayer { public C04PacketPlayerPosition() { this.moving = true; @@ -113,8 +43,8 @@ public class C03PacketPlayer implements Packet { this.moving = true; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.x = parPacketBuffer.readDouble(); @@ -123,8 +53,8 @@ public class C03PacketPlayer implements Packet { super.readPacketData(parPacketBuffer); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeDouble(this.x); @@ -146,8 +76,8 @@ public class C03PacketPlayer implements Packet { this.rotating = true; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.yaw = parPacketBuffer.readFloat(); @@ -155,8 +85,8 @@ public class C03PacketPlayer implements Packet { super.readPacketData(parPacketBuffer); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeFloat(this.yaw); @@ -183,8 +113,8 @@ public class C03PacketPlayer implements Packet { this.moving = true; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.x = parPacketBuffer.readDouble(); @@ -195,8 +125,8 @@ public class C03PacketPlayer implements Packet { super.readPacketData(parPacketBuffer); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeDouble(this.x); @@ -207,4 +137,80 @@ public class C03PacketPlayer implements Packet { super.writePacketData(parPacketBuffer); } } + + protected double x; + protected double y; + protected double z; + protected float yaw; + protected float pitch; + + protected boolean onGround; + + protected boolean moving; + + protected boolean rotating; + + public C03PacketPlayer() { + } + + public C03PacketPlayer(boolean isOnGround) { + this.onGround = isOnGround; + } + + public float getPitch() { + return this.pitch; + } + + public double getPositionX() { + return this.x; + } + + public double getPositionY() { + return this.y; + } + + public double getPositionZ() { + return this.z; + } + + public boolean getRotating() { + return this.rotating; + } + + public float getYaw() { + return this.yaw; + } + + public boolean isMoving() { + return this.moving; + } + + public boolean isOnGround() { + return this.onGround; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processPlayer(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.onGround = parPacketBuffer.readUnsignedByte() != 0; + } + + public void setMoving(boolean isMoving) { + this.moving = isMoving; + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.onGround ? 1 : 0); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C07PacketPlayerDigging.java b/src/game/java/net/minecraft/network/play/client/C07PacketPlayerDigging.java index c3b85e8a..e59c73d7 100644 --- a/src/game/java/net/minecraft/network/play/client/C07PacketPlayerDigging.java +++ b/src/game/java/net/minecraft/network/play/client/C07PacketPlayerDigging.java @@ -8,29 +8,37 @@ import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C07PacketPlayerDigging implements Packet { + public static enum Action { + START_DESTROY_BLOCK, ABORT_DESTROY_BLOCK, STOP_DESTROY_BLOCK, DROP_ALL_ITEMS, DROP_ITEM, RELEASE_USE_ITEM; + } + private BlockPos position; private EnumFacing facing; + private C07PacketPlayerDigging.Action status; public C07PacketPlayerDigging() { @@ -42,8 +50,27 @@ public class C07PacketPlayerDigging implements Packet { this.facing = facingIn; } - /**+ - * Reads the raw packet data from the data stream. + public EnumFacing getFacing() { + return this.facing; + } + + public BlockPos getPosition() { + return this.position; + } + + public C07PacketPlayerDigging.Action getStatus() { + return this.status; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processPlayerDigging(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.status = (C07PacketPlayerDigging.Action) parPacketBuffer @@ -52,35 +79,12 @@ public class C07PacketPlayerDigging implements Packet { this.facing = EnumFacing.getFront(parPacketBuffer.readUnsignedByte()); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeEnumValue(this.status); parPacketBuffer.writeBlockPos(this.position); parPacketBuffer.writeByte(this.facing.getIndex()); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processPlayerDigging(this); - } - - public BlockPos getPosition() { - return this.position; - } - - public EnumFacing getFacing() { - return this.facing; - } - - public C07PacketPlayerDigging.Action getStatus() { - return this.status; - } - - public static enum Action { - START_DESTROY_BLOCK, ABORT_DESTROY_BLOCK, STOP_DESTROY_BLOCK, DROP_ALL_ITEMS, DROP_ITEM, RELEASE_USE_ITEM; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C08PacketPlayerBlockPlacement.java b/src/game/java/net/minecraft/network/play/client/C08PacketPlayerBlockPlacement.java index 01bd5bad..36a15aa5 100644 --- a/src/game/java/net/minecraft/network/play/client/C08PacketPlayerBlockPlacement.java +++ b/src/game/java/net/minecraft/network/play/client/C08PacketPlayerBlockPlacement.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,10 +43,6 @@ public class C08PacketPlayerBlockPlacement implements Packet { this.slotId = slotId; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.slotId = parPacketBuffer.readShort(); + public int getSlotId() { + return this.slotId; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeShort(this.slotId); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer inethandlerplayserver) { inethandlerplayserver.processHeldItemChange(this); } - public int getSlotId() { - return this.slotId; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.slotId = parPacketBuffer.readShort(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeShort(this.slotId); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C0APacketAnimation.java b/src/game/java/net/minecraft/network/play/client/C0APacketAnimation.java index 57172228..ac896f56 100644 --- a/src/game/java/net/minecraft/network/play/client/C0APacketAnimation.java +++ b/src/game/java/net/minecraft/network/play/client/C0APacketAnimation.java @@ -6,43 +6,46 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C0APacketAnimation implements Packet { - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer inethandlerplayserver) { inethandlerplayserver.handleAnimation(this); } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C0BPacketEntityAction.java b/src/game/java/net/minecraft/network/play/client/C0BPacketEntityAction.java index 2d502e5e..08a6ae7f 100644 --- a/src/game/java/net/minecraft/network/play/client/C0BPacketEntityAction.java +++ b/src/game/java/net/minecraft/network/play/client/C0BPacketEntityAction.java @@ -7,29 +7,37 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C0BPacketEntityAction implements Packet { + public static enum Action { + START_SNEAKING, STOP_SNEAKING, STOP_SLEEPING, START_SPRINTING, STOP_SPRINTING, RIDING_JUMP, OPEN_INVENTORY; + } + private int entityID; private C0BPacketEntityAction.Action action; + private int auxData; public C0BPacketEntityAction() { @@ -45,31 +53,6 @@ public class C0BPacketEntityAction implements Packet { this.auxData = auxData; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityID = parPacketBuffer.readVarIntFromBuffer(); - this.action = (C0BPacketEntityAction.Action) parPacketBuffer.readEnumValue(C0BPacketEntityAction.Action.class); - this.auxData = parPacketBuffer.readVarIntFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityID); - parPacketBuffer.writeEnumValue(this.action); - parPacketBuffer.writeVarIntToBuffer(this.auxData); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processEntityAction(this); - } - public C0BPacketEntityAction.Action getAction() { return this.action; } @@ -78,7 +61,28 @@ public class C0BPacketEntityAction implements Packet { return this.auxData; } - public static enum Action { - START_SNEAKING, STOP_SNEAKING, STOP_SLEEPING, START_SPRINTING, STOP_SPRINTING, RIDING_JUMP, OPEN_INVENTORY; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processEntityAction(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityID = parPacketBuffer.readVarIntFromBuffer(); + this.action = (C0BPacketEntityAction.Action) parPacketBuffer.readEnumValue(C0BPacketEntityAction.Action.class); + this.auxData = parPacketBuffer.readVarIntFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityID); + parPacketBuffer.writeEnumValue(this.action); + parPacketBuffer.writeVarIntToBuffer(this.auxData); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C0CPacketInput.java b/src/game/java/net/minecraft/network/play/client/C0CPacketInput.java index e1df5f09..f606dd6f 100644 --- a/src/game/java/net/minecraft/network/play/client/C0CPacketInput.java +++ b/src/game/java/net/minecraft/network/play/client/C0CPacketInput.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,8 +45,31 @@ public class C0CPacketInput implements Packet { this.sneaking = sneaking; } - /**+ - * Reads the raw packet data from the data stream. + public float getForwardSpeed() { + return this.forwardSpeed; + } + + public float getStrafeSpeed() { + return this.strafeSpeed; + } + + public boolean isJumping() { + return this.jumping; + } + + public boolean isSneaking() { + return this.sneaking; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processInput(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.strafeSpeed = parPacketBuffer.readFloat(); @@ -53,8 +79,8 @@ public class C0CPacketInput implements Packet { this.sneaking = (b0 & 2) > 0; } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeFloat(this.strafeSpeed); @@ -70,27 +96,4 @@ public class C0CPacketInput implements Packet { parPacketBuffer.writeByte(b0); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processInput(this); - } - - public float getStrafeSpeed() { - return this.strafeSpeed; - } - - public float getForwardSpeed() { - return this.forwardSpeed; - } - - public boolean isJumping() { - return this.jumping; - } - - public boolean isSneaking() { - return this.sneaking; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C0DPacketCloseWindow.java b/src/game/java/net/minecraft/network/play/client/C0DPacketCloseWindow.java index 9c1db611..49647190 100644 --- a/src/game/java/net/minecraft/network/play/client/C0DPacketCloseWindow.java +++ b/src/game/java/net/minecraft/network/play/client/C0DPacketCloseWindow.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,22 +39,22 @@ public class C0DPacketCloseWindow implements Packet { this.windowId = windowId; } - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer inethandlerplayserver) { inethandlerplayserver.processCloseWindow(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.windowId = parPacketBuffer.readByte(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeByte(this.windowId); diff --git a/src/game/java/net/minecraft/network/play/client/C0EPacketClickWindow.java b/src/game/java/net/minecraft/network/play/client/C0EPacketClickWindow.java index 10d39981..91b2ad78 100644 --- a/src/game/java/net/minecraft/network/play/client/C0EPacketClickWindow.java +++ b/src/game/java/net/minecraft/network/play/client/C0EPacketClickWindow.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,49 +51,6 @@ public class C0EPacketClickWindow implements Packet { this.mode = mode; } - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processClickWindow(this); - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.windowId = parPacketBuffer.readByte(); - this.slotId = parPacketBuffer.readShort(); - this.usedButton = parPacketBuffer.readByte(); - this.actionNumber = parPacketBuffer.readShort(); - this.mode = parPacketBuffer.readByte(); - this.clickedItem = parPacketBuffer.readItemStackFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.windowId); - parPacketBuffer.writeShort(this.slotId); - parPacketBuffer.writeByte(this.usedButton); - parPacketBuffer.writeShort(this.actionNumber); - parPacketBuffer.writeByte(this.mode); - parPacketBuffer.writeItemStackToBuffer(this.clickedItem); - } - - public int getWindowId() { - return this.windowId; - } - - public int getSlotId() { - return this.slotId; - } - - public int getUsedButton() { - return this.usedButton; - } - public short getActionNumber() { return this.actionNumber; } @@ -102,4 +62,47 @@ public class C0EPacketClickWindow implements Packet { public int getMode() { return this.mode; } + + public int getSlotId() { + return this.slotId; + } + + public int getUsedButton() { + return this.usedButton; + } + + public int getWindowId() { + return this.windowId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processClickWindow(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.windowId = parPacketBuffer.readByte(); + this.slotId = parPacketBuffer.readShort(); + this.usedButton = parPacketBuffer.readByte(); + this.actionNumber = parPacketBuffer.readShort(); + this.mode = parPacketBuffer.readByte(); + this.clickedItem = parPacketBuffer.readItemStackFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.windowId); + parPacketBuffer.writeShort(this.slotId); + parPacketBuffer.writeByte(this.usedButton); + parPacketBuffer.writeShort(this.actionNumber); + parPacketBuffer.writeByte(this.mode); + parPacketBuffer.writeItemStackToBuffer(this.clickedItem); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C0FPacketConfirmTransaction.java b/src/game/java/net/minecraft/network/play/client/C0FPacketConfirmTransaction.java index 7307b107..dc4d4c5d 100644 --- a/src/game/java/net/minecraft/network/play/client/C0FPacketConfirmTransaction.java +++ b/src/game/java/net/minecraft/network/play/client/C0FPacketConfirmTransaction.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,15 +43,23 @@ public class C0FPacketConfirmTransaction implements Packet { this.button = button; } - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processEnchantItem(this); - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.windowId = parPacketBuffer.readByte(); - this.button = parPacketBuffer.readByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.windowId); - parPacketBuffer.writeByte(this.button); + public int getButton() { + return this.button; } public int getWindowId() { return this.windowId; } - public int getButton() { - return this.button; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processEnchantItem(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.windowId = parPacketBuffer.readByte(); + this.button = parPacketBuffer.readByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.windowId); + parPacketBuffer.writeByte(this.button); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C12PacketUpdateSign.java b/src/game/java/net/minecraft/network/play/client/C12PacketUpdateSign.java index 6b70f2a7..5aa4ac6d 100644 --- a/src/game/java/net/minecraft/network/play/client/C12PacketUpdateSign.java +++ b/src/game/java/net/minecraft/network/play/client/C12PacketUpdateSign.java @@ -8,22 +8,25 @@ import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.util.BlockPos; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,8 +43,23 @@ public class C12PacketUpdateSign implements Packet { this.lines = new IChatComponent[] { lines[0], lines[1], lines[2], lines[3] }; } - /**+ - * Reads the raw packet data from the data stream. + public IChatComponent[] getLines() { + return this.lines; + } + + public BlockPos getPosition() { + return this.pos; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processUpdateSign(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.pos = parPacketBuffer.readBlockPos(); @@ -55,8 +73,8 @@ public class C12PacketUpdateSign implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeBlockPos(this.pos); @@ -68,19 +86,4 @@ public class C12PacketUpdateSign implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processUpdateSign(this); - } - - public BlockPos getPosition() { - return this.pos; - } - - public IChatComponent[] getLines() { - return this.lines; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C13PacketPlayerAbilities.java b/src/game/java/net/minecraft/network/play/client/C13PacketPlayerAbilities.java index 683c6c9c..9a2276e3 100644 --- a/src/game/java/net/minecraft/network/play/client/C13PacketPlayerAbilities.java +++ b/src/game/java/net/minecraft/network/play/client/C13PacketPlayerAbilities.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,8 +50,31 @@ public class C13PacketPlayerAbilities implements Packet { this.setWalkSpeed(capabilities.getWalkSpeed()); } - /**+ - * Reads the raw packet data from the data stream. + public boolean isAllowFlying() { + return this.allowFlying; + } + + public boolean isCreativeMode() { + return this.creativeMode; + } + + public boolean isFlying() { + return this.flying; + } + + public boolean isInvulnerable() { + return this.invulnerable; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processPlayerAbilities(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { byte b0 = parPacketBuffer.readByte(); @@ -60,8 +86,32 @@ public class C13PacketPlayerAbilities implements Packet { this.setWalkSpeed(parPacketBuffer.readFloat()); } - /**+ - * Writes the raw packet data to the data stream. + public void setAllowFlying(boolean isAllowFlying) { + this.allowFlying = isAllowFlying; + } + + public void setCreativeMode(boolean isCreativeMode) { + this.creativeMode = isCreativeMode; + } + + public void setFlying(boolean isFlying) { + this.flying = isFlying; + } + + public void setFlySpeed(float flySpeedIn) { + this.flySpeed = flySpeedIn; + } + + public void setInvulnerable(boolean isInvulnerable) { + this.invulnerable = isInvulnerable; + } + + public void setWalkSpeed(float walkSpeedIn) { + this.walkSpeed = walkSpeedIn; + } + + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { byte b0 = 0; @@ -85,51 +135,4 @@ public class C13PacketPlayerAbilities implements Packet { parPacketBuffer.writeFloat(this.flySpeed); parPacketBuffer.writeFloat(this.walkSpeed); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processPlayerAbilities(this); - } - - public boolean isInvulnerable() { - return this.invulnerable; - } - - public void setInvulnerable(boolean isInvulnerable) { - this.invulnerable = isInvulnerable; - } - - public boolean isFlying() { - return this.flying; - } - - public void setFlying(boolean isFlying) { - this.flying = isFlying; - } - - public boolean isAllowFlying() { - return this.allowFlying; - } - - public void setAllowFlying(boolean isAllowFlying) { - this.allowFlying = isAllowFlying; - } - - public boolean isCreativeMode() { - return this.creativeMode; - } - - public void setCreativeMode(boolean isCreativeMode) { - this.creativeMode = isCreativeMode; - } - - public void setFlySpeed(float flySpeedIn) { - this.flySpeed = flySpeedIn; - } - - public void setWalkSpeed(float walkSpeedIn) { - this.walkSpeed = walkSpeedIn; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C14PacketTabComplete.java b/src/game/java/net/minecraft/network/play/client/C14PacketTabComplete.java index bf6c2d2c..38104da3 100644 --- a/src/game/java/net/minecraft/network/play/client/C14PacketTabComplete.java +++ b/src/game/java/net/minecraft/network/play/client/C14PacketTabComplete.java @@ -9,22 +9,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,8 +48,23 @@ public class C14PacketTabComplete implements Packet { this.targetBlock = target; } - /**+ - * Reads the raw packet data from the data stream. + public String getMessage() { + return this.message; + } + + public BlockPos getTargetBlock() { + return this.targetBlock; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processTabComplete(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.message = parPacketBuffer.readStringFromBuffer(32767); @@ -57,8 +75,8 @@ public class C14PacketTabComplete implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeString(StringUtils.substring(this.message, 0, 32767)); @@ -69,19 +87,4 @@ public class C14PacketTabComplete implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processTabComplete(this); - } - - public String getMessage() { - return this.message; - } - - public BlockPos getTargetBlock() { - return this.targetBlock; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C15PacketClientSettings.java b/src/game/java/net/minecraft/network/play/client/C15PacketClientSettings.java index 13451fe9..c131b89c 100644 --- a/src/game/java/net/minecraft/network/play/client/C15PacketClientSettings.java +++ b/src/game/java/net/minecraft/network/play/client/C15PacketClientSettings.java @@ -1,27 +1,31 @@ package net.minecraft.network.play.client; import java.io.IOException; + import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,45 +49,12 @@ public class C15PacketClientSettings implements Packet { this.modelPartFlags = modelPartFlagsIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.lang = parPacketBuffer.readStringFromBuffer(7); - this.view = parPacketBuffer.readByte(); - this.chatVisibility = EntityPlayer.EnumChatVisibility.getEnumChatVisibility(parPacketBuffer.readByte()); - this.enableColors = parPacketBuffer.readBoolean(); - this.modelPartFlags = parPacketBuffer.readUnsignedByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeString(this.lang); - parPacketBuffer.writeByte(this.view); - parPacketBuffer.writeByte(this.chatVisibility.getChatVisibility()); - parPacketBuffer.writeBoolean(this.enableColors); - parPacketBuffer.writeByte(this.modelPartFlags); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processClientSettings(this); - } - - public String getLang() { - return this.lang; - } - public EntityPlayer.EnumChatVisibility getChatVisibility() { return this.chatVisibility; } - public boolean isColorsEnabled() { - return this.enableColors; + public String getLang() { + return this.lang; } public int getModelPartFlags() { @@ -93,4 +64,37 @@ public class C15PacketClientSettings implements Packet { public int getViewDistance() { return this.view; } + + public boolean isColorsEnabled() { + return this.enableColors; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processClientSettings(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.lang = parPacketBuffer.readStringFromBuffer(7); + this.view = parPacketBuffer.readByte(); + this.chatVisibility = EntityPlayer.EnumChatVisibility.getEnumChatVisibility(parPacketBuffer.readByte()); + this.enableColors = parPacketBuffer.readBoolean(); + this.modelPartFlags = parPacketBuffer.readUnsignedByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeString(this.lang); + parPacketBuffer.writeByte(this.view); + parPacketBuffer.writeByte(this.chatVisibility.getChatVisibility()); + parPacketBuffer.writeBoolean(this.enableColors); + parPacketBuffer.writeByte(this.modelPartFlags); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C16PacketClientStatus.java b/src/game/java/net/minecraft/network/play/client/C16PacketClientStatus.java index f91edab0..2c636d70 100644 --- a/src/game/java/net/minecraft/network/play/client/C16PacketClientStatus.java +++ b/src/game/java/net/minecraft/network/play/client/C16PacketClientStatus.java @@ -6,27 +6,34 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C16PacketClientStatus implements Packet { + public static enum EnumState { + PERFORM_RESPAWN, REQUEST_STATS, OPEN_INVENTORY_ACHIEVEMENT; + } + private C16PacketClientStatus.EnumState status; public C16PacketClientStatus() { @@ -36,33 +43,29 @@ public class C16PacketClientStatus implements Packet { this.status = statusIn; } - /**+ - * Reads the raw packet data from the data stream. + public C16PacketClientStatus.EnumState getStatus() { + return this.status; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processClientStatus(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.status = (C16PacketClientStatus.EnumState) parPacketBuffer .readEnumValue(C16PacketClientStatus.EnumState.class); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeEnumValue(this.status); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processClientStatus(this); - } - - public C16PacketClientStatus.EnumState getStatus() { - return this.status; - } - - public static enum EnumState { - PERFORM_RESPAWN, REQUEST_STATS, OPEN_INVENTORY_ACHIEVEMENT; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C17PacketCustomPayload.java b/src/game/java/net/minecraft/network/play/client/C17PacketCustomPayload.java index 1476efbd..ea3bd318 100644 --- a/src/game/java/net/minecraft/network/play/client/C17PacketCustomPayload.java +++ b/src/game/java/net/minecraft/network/play/client/C17PacketCustomPayload.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,8 +45,23 @@ public class C17PacketCustomPayload implements Packet { } } - /**+ - * Reads the raw packet data from the data stream. + public PacketBuffer getBufferData() { + return this.data; + } + + public String getChannelName() { + return this.channel; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayServer inethandlerplayserver) { + inethandlerplayserver.processVanilla250Packet(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.channel = parPacketBuffer.readStringFromBuffer(20); @@ -55,26 +73,11 @@ public class C17PacketCustomPayload implements Packet { } } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeString(this.channel); parPacketBuffer.writeBytes((ByteBuf) this.data); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayServer inethandlerplayserver) { - inethandlerplayserver.processVanilla250Packet(this); - } - - public String getChannelName() { - return this.channel; - } - - public PacketBuffer getBufferData() { - return this.data; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C18PacketSpectate.java b/src/game/java/net/minecraft/network/play/client/C18PacketSpectate.java index 075853dc..6a96dcee 100644 --- a/src/game/java/net/minecraft/network/play/client/C18PacketSpectate.java +++ b/src/game/java/net/minecraft/network/play/client/C18PacketSpectate.java @@ -1,6 +1,7 @@ package net.minecraft.network.play.client; import java.io.IOException; + import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.entity.Entity; import net.minecraft.network.Packet; @@ -8,22 +9,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; import net.minecraft.world.WorldServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,28 +42,28 @@ public class C18PacketSpectate implements Packet { this.id = id; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.id = parPacketBuffer.readUuid(); + public Entity getEntity(WorldServer worldIn) { + return worldIn.getEntityFromUuid(this.id); } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeUuid(this.id); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayServer inethandlerplayserver) { inethandlerplayserver.handleSpectate(this); } - public Entity getEntity(WorldServer worldIn) { - return worldIn.getEntityFromUuid(this.id); + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.id = parPacketBuffer.readUuid(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeUuid(this.id); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/client/C19PacketResourcePackStatus.java b/src/game/java/net/minecraft/network/play/client/C19PacketResourcePackStatus.java index 3a13f4f4..1c1a3b8e 100644 --- a/src/game/java/net/minecraft/network/play/client/C19PacketResourcePackStatus.java +++ b/src/game/java/net/minecraft/network/play/client/C19PacketResourcePackStatus.java @@ -6,28 +6,36 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class C19PacketResourcePackStatus implements Packet { + public static enum Action { + SUCCESSFULLY_LOADED, DECLINED, FAILED_DOWNLOAD, ACCEPTED; + } + private String hash; + private C19PacketResourcePackStatus.Action status; public C19PacketResourcePackStatus() { @@ -42,8 +50,15 @@ public class C19PacketResourcePackStatus implements Packet { this.id = idIn; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public int func_149134_c() { + return this.id; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleKeepAlive(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.id = parPacketBuffer.readVarIntFromBuffer(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.id); } - - public int func_149134_c() { - return this.id; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S01PacketJoinGame.java b/src/game/java/net/minecraft/network/play/server/S01PacketJoinGame.java index e5407ad5..64e51a2e 100644 --- a/src/game/java/net/minecraft/network/play/server/S01PacketJoinGame.java +++ b/src/game/java/net/minecraft/network/play/server/S01PacketJoinGame.java @@ -9,22 +9,25 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,8 +57,47 @@ public class S01PacketJoinGame implements Packet { this.reducedDebugInfo = reducedDebugInfoIn; } - /**+ - * Reads the raw packet data from the data stream. + public EnumDifficulty getDifficulty() { + return this.difficulty; + } + + public int getDimension() { + return this.dimension; + } + + public int getEntityId() { + return this.entityId; + } + + public WorldSettings.GameType getGameType() { + return this.gameType; + } + + public int getMaxPlayers() { + return this.maxPlayers; + } + + public WorldType getWorldType() { + return this.worldType; + } + + public boolean isHardcoreMode() { + return this.hardcoreMode; + } + + public boolean isReducedDebugInfo() { + return this.reducedDebugInfo; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleJoinGame(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readInt(); @@ -74,8 +116,8 @@ public class S01PacketJoinGame implements Packet { this.reducedDebugInfo = parPacketBuffer.readBoolean(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeInt(this.entityId); @@ -91,43 +133,4 @@ public class S01PacketJoinGame implements Packet { parPacketBuffer.writeString(this.worldType.getWorldTypeName()); parPacketBuffer.writeBoolean(this.reducedDebugInfo); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleJoinGame(this); - } - - public int getEntityId() { - return this.entityId; - } - - public boolean isHardcoreMode() { - return this.hardcoreMode; - } - - public WorldSettings.GameType getGameType() { - return this.gameType; - } - - public int getDimension() { - return this.dimension; - } - - public EnumDifficulty getDifficulty() { - return this.difficulty; - } - - public int getMaxPlayers() { - return this.maxPlayers; - } - - public WorldType getWorldType() { - return this.worldType; - } - - public boolean isReducedDebugInfo() { - return this.reducedDebugInfo; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S02PacketChat.java b/src/game/java/net/minecraft/network/play/server/S02PacketChat.java index 923c3ab2..a434c04b 100644 --- a/src/game/java/net/minecraft/network/play/server/S02PacketChat.java +++ b/src/game/java/net/minecraft/network/play/server/S02PacketChat.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,42 +46,42 @@ public class S02PacketChat implements Packet { this.type = typeIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.chatComponent = parPacketBuffer.readChatComponent(); - this.type = parPacketBuffer.readByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeChatComponent(this.chatComponent); - parPacketBuffer.writeByte(this.type); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleChat(this); - } - public IChatComponent getChatComponent() { return this.chatComponent; } + /** + * + Returns the id of the area to display the text, 2 for above the action bar, + * anything else currently for the chat window + */ + public byte getType() { + return this.type; + } + public boolean isChat() { return this.type == 1 || this.type == 2; } - /**+ - * Returns the id of the area to display the text, 2 for above - * the action bar, anything else currently for the chat window + /** + * + Passes this Packet on to the NetHandler for processing. */ - public byte getType() { - return this.type; + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleChat(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.chatComponent = parPacketBuffer.readChatComponent(); + this.type = parPacketBuffer.readByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeChatComponent(this.chatComponent); + parPacketBuffer.writeByte(this.type); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S03PacketTimeUpdate.java b/src/game/java/net/minecraft/network/play/server/S03PacketTimeUpdate.java index 19156e2c..6f48013a 100644 --- a/src/game/java/net/minecraft/network/play/server/S03PacketTimeUpdate.java +++ b/src/game/java/net/minecraft/network/play/server/S03PacketTimeUpdate.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,29 +48,6 @@ public class S03PacketTimeUpdate implements Packet { } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.totalWorldTime = parPacketBuffer.readLong(); - this.worldTime = parPacketBuffer.readLong(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeLong(this.totalWorldTime); - parPacketBuffer.writeLong(this.worldTime); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleTimeUpdate(this); - } - public long getTotalWorldTime() { return this.totalWorldTime; } @@ -75,4 +55,27 @@ public class S03PacketTimeUpdate implements Packet { public long getWorldTime() { return this.worldTime; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleTimeUpdate(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.totalWorldTime = parPacketBuffer.readLong(); + this.worldTime = parPacketBuffer.readLong(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeLong(this.totalWorldTime); + parPacketBuffer.writeLong(this.worldTime); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S04PacketEntityEquipment.java b/src/game/java/net/minecraft/network/play/server/S04PacketEntityEquipment.java index 1339609a..83d7a4b7 100644 --- a/src/game/java/net/minecraft/network/play/server/S04PacketEntityEquipment.java +++ b/src/game/java/net/minecraft/network/play/server/S04PacketEntityEquipment.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,35 +44,6 @@ public class S04PacketEntityEquipment implements Packet { this.itemStack = itemStackIn == null ? null : itemStackIn.copy(); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityID = parPacketBuffer.readVarIntFromBuffer(); - this.equipmentSlot = parPacketBuffer.readShort(); - this.itemStack = parPacketBuffer.readItemStackFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityID); - parPacketBuffer.writeShort(this.equipmentSlot); - parPacketBuffer.writeItemStackToBuffer(this.itemStack); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityEquipment(this); - } - - public ItemStack getItemStack() { - return this.itemStack; - } - public int getEntityID() { return this.entityID; } @@ -77,4 +51,33 @@ public class S04PacketEntityEquipment implements Packet { public int getEquipmentSlot() { return this.equipmentSlot; } + + public ItemStack getItemStack() { + return this.itemStack; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityEquipment(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityID = parPacketBuffer.readVarIntFromBuffer(); + this.equipmentSlot = parPacketBuffer.readShort(); + this.itemStack = parPacketBuffer.readItemStackFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityID); + parPacketBuffer.writeShort(this.equipmentSlot); + parPacketBuffer.writeItemStackToBuffer(this.itemStack); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S05PacketSpawnPosition.java b/src/game/java/net/minecraft/network/play/server/S05PacketSpawnPosition.java index fb43d730..f55c426c 100644 --- a/src/game/java/net/minecraft/network/play/server/S05PacketSpawnPosition.java +++ b/src/game/java/net/minecraft/network/play/server/S05PacketSpawnPosition.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,28 +40,28 @@ public class S05PacketSpawnPosition implements Packet { this.spawnBlockPos = spawnBlockPosIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.spawnBlockPos = parPacketBuffer.readBlockPos(); + public BlockPos getSpawnPos() { + return this.spawnBlockPos; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeBlockPos(this.spawnBlockPos); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleSpawnPosition(this); } - public BlockPos getSpawnPos() { - return this.spawnBlockPos; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.spawnBlockPos = parPacketBuffer.readBlockPos(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeBlockPos(this.spawnBlockPos); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S06PacketUpdateHealth.java b/src/game/java/net/minecraft/network/play/server/S06PacketUpdateHealth.java index 64412666..9daeef71 100644 --- a/src/game/java/net/minecraft/network/play/server/S06PacketUpdateHealth.java +++ b/src/game/java/net/minecraft/network/play/server/S06PacketUpdateHealth.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,8 +43,27 @@ public class S06PacketUpdateHealth implements Packet { this.saturationLevel = saturationIn; } - /**+ - * Reads the raw packet data from the data stream. + public int getFoodLevel() { + return this.foodLevel; + } + + public float getHealth() { + return this.health; + } + + public float getSaturationLevel() { + return this.saturationLevel; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleUpdateHealth(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.health = parPacketBuffer.readFloat(); @@ -49,31 +71,12 @@ public class S06PacketUpdateHealth implements Packet { this.saturationLevel = parPacketBuffer.readFloat(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeFloat(this.health); parPacketBuffer.writeVarIntToBuffer(this.foodLevel); parPacketBuffer.writeFloat(this.saturationLevel); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleUpdateHealth(this); - } - - public float getHealth() { - return this.health; - } - - public int getFoodLevel() { - return this.foodLevel; - } - - public float getSaturationLevel() { - return this.saturationLevel; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S07PacketRespawn.java b/src/game/java/net/minecraft/network/play/server/S07PacketRespawn.java index 5bdc483b..6b464838 100644 --- a/src/game/java/net/minecraft/network/play/server/S07PacketRespawn.java +++ b/src/game/java/net/minecraft/network/play/server/S07PacketRespawn.java @@ -9,22 +9,25 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,15 +49,31 @@ public class S07PacketRespawn implements Packet { this.worldType = worldTypeIn; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public EnumDifficulty getDifficulty() { + return this.difficulty; + } + + public int getDimensionID() { + return this.dimensionID; + } + + public WorldSettings.GameType getGameType() { + return this.gameType; + } + + public WorldType getWorldType() { + return this.worldType; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleRespawn(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.dimensionID = parPacketBuffer.readInt(); @@ -67,8 +86,8 @@ public class S07PacketRespawn implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeInt(this.dimensionID); @@ -76,20 +95,4 @@ public class S07PacketRespawn implements Packet { parPacketBuffer.writeByte(this.gameType.getID()); parPacketBuffer.writeString(this.worldType.getWorldTypeName()); } - - public int getDimensionID() { - return this.dimensionID; - } - - public EnumDifficulty getDifficulty() { - return this.difficulty; - } - - public WorldSettings.GameType getGameType() { - return this.gameType; - } - - public WorldType getWorldType() { - return this.worldType; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S08PacketPlayerPosLook.java b/src/game/java/net/minecraft/network/play/server/S08PacketPlayerPosLook.java index 68668c14..92b7d93e 100644 --- a/src/game/java/net/minecraft/network/play/server/S08PacketPlayerPosLook.java +++ b/src/game/java/net/minecraft/network/play/server/S08PacketPlayerPosLook.java @@ -8,119 +8,33 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S08PacketPlayerPosLook implements Packet { - private double x; - private double y; - private double z; - private float yaw; - private float pitch; - private Set field_179835_f; - - public S08PacketPlayerPosLook() { - } - - public S08PacketPlayerPosLook(double xIn, double yIn, double zIn, float yawIn, float pitchIn, - Set parSet) { - this.x = xIn; - this.y = yIn; - this.z = zIn; - this.yaw = yawIn; - this.pitch = pitchIn; - this.field_179835_f = parSet; - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.x = parPacketBuffer.readDouble(); - this.y = parPacketBuffer.readDouble(); - this.z = parPacketBuffer.readDouble(); - this.yaw = parPacketBuffer.readFloat(); - this.pitch = parPacketBuffer.readFloat(); - this.field_179835_f = S08PacketPlayerPosLook.EnumFlags.func_180053_a(parPacketBuffer.readUnsignedByte()); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeDouble(this.x); - parPacketBuffer.writeDouble(this.y); - parPacketBuffer.writeDouble(this.z); - parPacketBuffer.writeFloat(this.yaw); - parPacketBuffer.writeFloat(this.pitch); - parPacketBuffer.writeByte(S08PacketPlayerPosLook.EnumFlags.func_180056_a(this.field_179835_f)); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handlePlayerPosLook(this); - } - - public double getX() { - return this.x; - } - - public double getY() { - return this.y; - } - - public double getZ() { - return this.z; - } - - public float getYaw() { - return this.yaw; - } - - public float getPitch() { - return this.pitch; - } - - public Set func_179834_f() { - return this.field_179835_f; - } - public static enum EnumFlags { X(0), Y(1), Z(2), Y_ROT(3), X_ROT(4); - private int field_180058_f; - - private EnumFlags(int parInt2) { - this.field_180058_f = parInt2; - } - - private int func_180055_a() { - return 1 << this.field_180058_f; - } - - private boolean func_180054_b(int parInt1) { - return (parInt1 & this.func_180055_a()) == this.func_180055_a(); - } - public static Set func_180053_a(int parInt1) { EnumSet enumset = EnumSet.noneOf(S08PacketPlayerPosLook.EnumFlags.class); @@ -144,5 +58,95 @@ public class S08PacketPlayerPosLook implements Packet { return i; } + + private int field_180058_f; + + private EnumFlags(int parInt2) { + this.field_180058_f = parInt2; + } + + private boolean func_180054_b(int parInt1) { + return (parInt1 & this.func_180055_a()) == this.func_180055_a(); + } + + private int func_180055_a() { + return 1 << this.field_180058_f; + } + } + + private double x; + private double y; + private double z; + private float yaw; + private float pitch; + + private Set field_179835_f; + + public S08PacketPlayerPosLook() { + } + + public S08PacketPlayerPosLook(double xIn, double yIn, double zIn, float yawIn, float pitchIn, + Set parSet) { + this.x = xIn; + this.y = yIn; + this.z = zIn; + this.yaw = yawIn; + this.pitch = pitchIn; + this.field_179835_f = parSet; + } + + public Set func_179834_f() { + return this.field_179835_f; + } + + public float getPitch() { + return this.pitch; + } + + public double getX() { + return this.x; + } + + public double getY() { + return this.y; + } + + public float getYaw() { + return this.yaw; + } + + public double getZ() { + return this.z; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handlePlayerPosLook(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.x = parPacketBuffer.readDouble(); + this.y = parPacketBuffer.readDouble(); + this.z = parPacketBuffer.readDouble(); + this.yaw = parPacketBuffer.readFloat(); + this.pitch = parPacketBuffer.readFloat(); + this.field_179835_f = S08PacketPlayerPosLook.EnumFlags.func_180053_a(parPacketBuffer.readUnsignedByte()); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeDouble(this.x); + parPacketBuffer.writeDouble(this.y); + parPacketBuffer.writeDouble(this.z); + parPacketBuffer.writeFloat(this.yaw); + parPacketBuffer.writeFloat(this.pitch); + parPacketBuffer.writeByte(S08PacketPlayerPosLook.EnumFlags.func_180056_a(this.field_179835_f)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S09PacketHeldItemChange.java b/src/game/java/net/minecraft/network/play/server/S09PacketHeldItemChange.java index 64950718..fd4afe8c 100644 --- a/src/game/java/net/minecraft/network/play/server/S09PacketHeldItemChange.java +++ b/src/game/java/net/minecraft/network/play/server/S09PacketHeldItemChange.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,28 +39,28 @@ public class S09PacketHeldItemChange implements Packet { this.heldItemHotbarIndex = hotbarIndexIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.heldItemHotbarIndex = parPacketBuffer.readByte(); + public int getHeldItemHotbarIndex() { + return this.heldItemHotbarIndex; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.heldItemHotbarIndex); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleHeldItemChange(this); } - public int getHeldItemHotbarIndex() { - return this.heldItemHotbarIndex; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.heldItemHotbarIndex = parPacketBuffer.readByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.heldItemHotbarIndex); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S0APacketUseBed.java b/src/game/java/net/minecraft/network/play/server/S0APacketUseBed.java index ff65507c..b4ee2bf2 100644 --- a/src/game/java/net/minecraft/network/play/server/S0APacketUseBed.java +++ b/src/game/java/net/minecraft/network/play/server/S0APacketUseBed.java @@ -9,22 +9,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,34 +44,34 @@ public class S0APacketUseBed implements Packet { this.bedPos = bedPosIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.playerID = parPacketBuffer.readVarIntFromBuffer(); - this.bedPos = parPacketBuffer.readBlockPos(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.playerID); - parPacketBuffer.writeBlockPos(this.bedPos); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleUseBed(this); + public BlockPos getBedPosition() { + return this.bedPos; } public EntityPlayer getPlayer(World worldIn) { return (EntityPlayer) worldIn.getEntityByID(this.playerID); } - public BlockPos getBedPosition() { - return this.bedPos; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleUseBed(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.playerID = parPacketBuffer.readVarIntFromBuffer(); + this.bedPos = parPacketBuffer.readBlockPos(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.playerID); + parPacketBuffer.writeBlockPos(this.bedPos); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S0BPacketAnimation.java b/src/game/java/net/minecraft/network/play/server/S0BPacketAnimation.java index bd7463b6..0a39d6b9 100644 --- a/src/game/java/net/minecraft/network/play/server/S0BPacketAnimation.java +++ b/src/game/java/net/minecraft/network/play/server/S0BPacketAnimation.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,34 +42,34 @@ public class S0BPacketAnimation implements Packet { this.type = animationType; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.type = parPacketBuffer.readUnsignedByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - parPacketBuffer.writeByte(this.type); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleAnimation(this); + public int getAnimationType() { + return this.type; } public int getEntityID() { return this.entityId; } - public int getAnimationType() { - return this.type; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleAnimation(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.type = parPacketBuffer.readUnsignedByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + parPacketBuffer.writeByte(this.type); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S0CPacketSpawnPlayer.java b/src/game/java/net/minecraft/network/play/server/S0CPacketSpawnPlayer.java index c76d6273..5891dac2 100644 --- a/src/game/java/net/minecraft/network/play/server/S0CPacketSpawnPlayer.java +++ b/src/game/java/net/minecraft/network/play/server/S0CPacketSpawnPlayer.java @@ -2,8 +2,8 @@ package net.minecraft.network.play.server; import java.io.IOException; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.entity.DataWatcher; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; @@ -13,22 +13,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,43 +64,6 @@ public class S0CPacketSpawnPlayer implements Packet { this.watcher = player.getDataWatcher(); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.playerId = parPacketBuffer.readUuid(); - this.x = parPacketBuffer.readInt(); - this.y = parPacketBuffer.readInt(); - this.z = parPacketBuffer.readInt(); - this.yaw = parPacketBuffer.readByte(); - this.pitch = parPacketBuffer.readByte(); - this.currentItem = parPacketBuffer.readShort(); - this.field_148958_j = DataWatcher.readWatchedListFromPacketBuffer(parPacketBuffer); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - parPacketBuffer.writeUuid(this.playerId); - parPacketBuffer.writeInt(this.x); - parPacketBuffer.writeInt(this.y); - parPacketBuffer.writeInt(this.z); - parPacketBuffer.writeByte(this.yaw); - parPacketBuffer.writeByte(this.pitch); - parPacketBuffer.writeShort(this.currentItem); - this.watcher.writeTo(parPacketBuffer); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSpawnPlayer(this); - } - public List func_148944_c() { if (this.field_148958_j == null) { this.field_148958_j = this.watcher.getAllWatched(); @@ -106,10 +72,18 @@ public class S0CPacketSpawnPlayer implements Packet { return this.field_148958_j; } + public int getCurrentItemID() { + return this.currentItem; + } + public int getEntityID() { return this.entityId; } + public byte getPitch() { + return this.pitch; + } + public EaglercraftUUID getPlayer() { return this.playerId; } @@ -122,19 +96,48 @@ public class S0CPacketSpawnPlayer implements Packet { return this.y; } - public int getZ() { - return this.z; - } - public byte getYaw() { return this.yaw; } - public byte getPitch() { - return this.pitch; + public int getZ() { + return this.z; } - public int getCurrentItemID() { - return this.currentItem; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSpawnPlayer(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.playerId = parPacketBuffer.readUuid(); + this.x = parPacketBuffer.readInt(); + this.y = parPacketBuffer.readInt(); + this.z = parPacketBuffer.readInt(); + this.yaw = parPacketBuffer.readByte(); + this.pitch = parPacketBuffer.readByte(); + this.currentItem = parPacketBuffer.readShort(); + this.field_148958_j = DataWatcher.readWatchedListFromPacketBuffer(parPacketBuffer); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + parPacketBuffer.writeUuid(this.playerId); + parPacketBuffer.writeInt(this.x); + parPacketBuffer.writeInt(this.y); + parPacketBuffer.writeInt(this.z); + parPacketBuffer.writeByte(this.yaw); + parPacketBuffer.writeByte(this.pitch); + parPacketBuffer.writeShort(this.currentItem); + this.watcher.writeTo(parPacketBuffer); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S0DPacketCollectItem.java b/src/game/java/net/minecraft/network/play/server/S0DPacketCollectItem.java index bbeb5dd5..055e6496 100644 --- a/src/game/java/net/minecraft/network/play/server/S0DPacketCollectItem.java +++ b/src/game/java/net/minecraft/network/play/server/S0DPacketCollectItem.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,29 +41,6 @@ public class S0DPacketCollectItem implements Packet { this.entityId = entityIdIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.collectedItemEntityId = parPacketBuffer.readVarIntFromBuffer(); - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.collectedItemEntityId); - parPacketBuffer.writeVarIntToBuffer(this.entityId); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleCollectItem(this); - } - public int getCollectedItemEntityID() { return this.collectedItemEntityId; } @@ -68,4 +48,27 @@ public class S0DPacketCollectItem implements Packet { public int getEntityID() { return this.entityId; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleCollectItem(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.collectedItemEntityId = parPacketBuffer.readVarIntFromBuffer(); + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.collectedItemEntityId); + parPacketBuffer.writeVarIntToBuffer(this.entityId); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S0EPacketSpawnObject.java b/src/game/java/net/minecraft/network/play/server/S0EPacketSpawnObject.java index 7b04495f..a2105384 100644 --- a/src/game/java/net/minecraft/network/play/server/S0EPacketSpawnObject.java +++ b/src/game/java/net/minecraft/network/play/server/S0EPacketSpawnObject.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -93,8 +96,63 @@ public class S0EPacketSpawnObject implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + public void func_149002_g(int parInt1) { + this.field_149020_k = parInt1; + } + + public int func_149009_m() { + return this.field_149020_k; + } + + public int getEntityID() { + return this.entityId; + } + + public int getPitch() { + return this.pitch; + } + + public int getSpeedX() { + return this.speedX; + } + + public int getSpeedY() { + return this.speedY; + } + + public int getSpeedZ() { + return this.speedZ; + } + + public int getType() { + return this.type; + } + + public int getX() { + return this.x; + } + + public int getY() { + return this.y; + } + + public int getYaw() { + return this.yaw; + } + + public int getZ() { + return this.z; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSpawnObject(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readVarIntFromBuffer(); @@ -113,8 +171,32 @@ public class S0EPacketSpawnObject implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + public void setSpeedX(int newSpeedX) { + this.speedX = newSpeedX; + } + + public void setSpeedY(int newSpeedY) { + this.speedY = newSpeedY; + } + + public void setSpeedZ(int newSpeedZ) { + this.speedZ = newSpeedZ; + } + + public void setX(int newX) { + this.x = newX; + } + + public void setY(int newY) { + this.y = newY; + } + + public void setZ(int newZ) { + this.z = newZ; + } + + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityId); @@ -132,83 +214,4 @@ public class S0EPacketSpawnObject implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSpawnObject(this); - } - - public int getEntityID() { - return this.entityId; - } - - public int getX() { - return this.x; - } - - public int getY() { - return this.y; - } - - public int getZ() { - return this.z; - } - - public int getSpeedX() { - return this.speedX; - } - - public int getSpeedY() { - return this.speedY; - } - - public int getSpeedZ() { - return this.speedZ; - } - - public int getPitch() { - return this.pitch; - } - - public int getYaw() { - return this.yaw; - } - - public int getType() { - return this.type; - } - - public int func_149009_m() { - return this.field_149020_k; - } - - public void setX(int newX) { - this.x = newX; - } - - public void setY(int newY) { - this.y = newY; - } - - public void setZ(int newZ) { - this.z = newZ; - } - - public void setSpeedX(int newSpeedX) { - this.speedX = newSpeedX; - } - - public void setSpeedY(int newSpeedY) { - this.speedY = newSpeedY; - } - - public void setSpeedZ(int newSpeedZ) { - this.speedZ = newSpeedZ; - } - - public void func_149002_g(int parInt1) { - this.field_149020_k = parInt1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S0FPacketSpawnMob.java b/src/game/java/net/minecraft/network/play/server/S0FPacketSpawnMob.java index f2989af1..7b04c1c2 100644 --- a/src/game/java/net/minecraft/network/play/server/S0FPacketSpawnMob.java +++ b/src/game/java/net/minecraft/network/play/server/S0FPacketSpawnMob.java @@ -11,22 +11,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -92,49 +95,6 @@ public class S0FPacketSpawnMob implements Packet { this.field_149043_l = entityIn.getDataWatcher(); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.type = parPacketBuffer.readByte() & 255; - this.x = parPacketBuffer.readInt(); - this.y = parPacketBuffer.readInt(); - this.z = parPacketBuffer.readInt(); - this.yaw = parPacketBuffer.readByte(); - this.pitch = parPacketBuffer.readByte(); - this.headPitch = parPacketBuffer.readByte(); - this.velocityX = parPacketBuffer.readShort(); - this.velocityY = parPacketBuffer.readShort(); - this.velocityZ = parPacketBuffer.readShort(); - this.watcher = DataWatcher.readWatchedListFromPacketBuffer(parPacketBuffer); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - parPacketBuffer.writeByte(this.type & 255); - parPacketBuffer.writeInt(this.x); - parPacketBuffer.writeInt(this.y); - parPacketBuffer.writeInt(this.z); - parPacketBuffer.writeByte(this.yaw); - parPacketBuffer.writeByte(this.pitch); - parPacketBuffer.writeByte(this.headPitch); - parPacketBuffer.writeShort(this.velocityX); - parPacketBuffer.writeShort(this.velocityY); - parPacketBuffer.writeShort(this.velocityZ); - this.field_149043_l.writeTo(parPacketBuffer); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSpawnMob(this); - } - public List func_149027_c() { if (this.watcher == null) { this.watcher = this.field_149043_l.getAllWatched(); @@ -151,16 +111,12 @@ public class S0FPacketSpawnMob implements Packet { return this.type; } - public int getX() { - return this.x; + public byte getHeadPitch() { + return this.headPitch; } - public int getY() { - return this.y; - } - - public int getZ() { - return this.z; + public byte getPitch() { + return this.pitch; } public int getVelocityX() { @@ -175,15 +131,62 @@ public class S0FPacketSpawnMob implements Packet { return this.velocityZ; } + public int getX() { + return this.x; + } + + public int getY() { + return this.y; + } + public byte getYaw() { return this.yaw; } - public byte getPitch() { - return this.pitch; + public int getZ() { + return this.z; } - public byte getHeadPitch() { - return this.headPitch; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSpawnMob(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.type = parPacketBuffer.readByte() & 255; + this.x = parPacketBuffer.readInt(); + this.y = parPacketBuffer.readInt(); + this.z = parPacketBuffer.readInt(); + this.yaw = parPacketBuffer.readByte(); + this.pitch = parPacketBuffer.readByte(); + this.headPitch = parPacketBuffer.readByte(); + this.velocityX = parPacketBuffer.readShort(); + this.velocityY = parPacketBuffer.readShort(); + this.velocityZ = parPacketBuffer.readShort(); + this.watcher = DataWatcher.readWatchedListFromPacketBuffer(parPacketBuffer); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + parPacketBuffer.writeByte(this.type & 255); + parPacketBuffer.writeInt(this.x); + parPacketBuffer.writeInt(this.y); + parPacketBuffer.writeInt(this.z); + parPacketBuffer.writeByte(this.yaw); + parPacketBuffer.writeByte(this.pitch); + parPacketBuffer.writeByte(this.headPitch); + parPacketBuffer.writeShort(this.velocityX); + parPacketBuffer.writeShort(this.velocityY); + parPacketBuffer.writeShort(this.velocityZ); + this.field_149043_l.writeTo(parPacketBuffer); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S10PacketSpawnPainting.java b/src/game/java/net/minecraft/network/play/server/S10PacketSpawnPainting.java index e3c7d48e..a2d96026 100644 --- a/src/game/java/net/minecraft/network/play/server/S10PacketSpawnPainting.java +++ b/src/game/java/net/minecraft/network/play/server/S10PacketSpawnPainting.java @@ -9,22 +9,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,8 +48,31 @@ public class S10PacketSpawnPainting implements Packet { this.title = painting.art.title; } - /**+ - * Reads the raw packet data from the data stream. + public int getEntityID() { + return this.entityID; + } + + public EnumFacing getFacing() { + return this.facing; + } + + public BlockPos getPosition() { + return this.position; + } + + public String getTitle() { + return this.title; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSpawnPainting(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityID = parPacketBuffer.readVarIntFromBuffer(); @@ -55,8 +81,8 @@ public class S10PacketSpawnPainting implements Packet { this.facing = EnumFacing.getHorizontal(parPacketBuffer.readUnsignedByte()); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityID); @@ -64,27 +90,4 @@ public class S10PacketSpawnPainting implements Packet { parPacketBuffer.writeBlockPos(this.position); parPacketBuffer.writeByte(this.facing.getHorizontalIndex()); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSpawnPainting(this); - } - - public int getEntityID() { - return this.entityID; - } - - public BlockPos getPosition() { - return this.position; - } - - public EnumFacing getFacing() { - return this.facing; - } - - public String getTitle() { - return this.title; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S11PacketSpawnExperienceOrb.java b/src/game/java/net/minecraft/network/play/server/S11PacketSpawnExperienceOrb.java index c76453c6..4888cda1 100644 --- a/src/game/java/net/minecraft/network/play/server/S11PacketSpawnExperienceOrb.java +++ b/src/game/java/net/minecraft/network/play/server/S11PacketSpawnExperienceOrb.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,35 +49,6 @@ public class S11PacketSpawnExperienceOrb implements Packet { this.motionZ = (int) (motionZIn * 8000.0D); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityID = parPacketBuffer.readVarIntFromBuffer(); - this.motionX = parPacketBuffer.readShort(); - this.motionY = parPacketBuffer.readShort(); - this.motionZ = parPacketBuffer.readShort(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityID); - parPacketBuffer.writeShort(this.motionX); - parPacketBuffer.writeShort(this.motionY); - parPacketBuffer.writeShort(this.motionZ); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityVelocity(this); - } - public int getEntityID() { return this.entityID; } @@ -114,4 +90,31 @@ public class S12PacketEntityVelocity implements Packet { public int getMotionZ() { return this.motionZ; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityVelocity(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityID = parPacketBuffer.readVarIntFromBuffer(); + this.motionX = parPacketBuffer.readShort(); + this.motionY = parPacketBuffer.readShort(); + this.motionZ = parPacketBuffer.readShort(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityID); + parPacketBuffer.writeShort(this.motionX); + parPacketBuffer.writeShort(this.motionY); + parPacketBuffer.writeShort(this.motionZ); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S13PacketDestroyEntities.java b/src/game/java/net/minecraft/network/play/server/S13PacketDestroyEntities.java index 1ca15716..489b9f8d 100644 --- a/src/game/java/net/minecraft/network/play/server/S13PacketDestroyEntities.java +++ b/src/game/java/net/minecraft/network/play/server/S13PacketDestroyEntities.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,19 @@ public class S13PacketDestroyEntities implements Packet { this.entityIDs = entityIDsIn; } - /**+ - * Reads the raw packet data from the data stream. + public int[] getEntityIDs() { + return this.entityIDs; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleDestroyEntities(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityIDs = new int[parPacketBuffer.readVarIntFromBuffer()]; @@ -48,8 +62,8 @@ public class S13PacketDestroyEntities implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityIDs.length); @@ -59,15 +73,4 @@ public class S13PacketDestroyEntities implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleDestroyEntities(this); - } - - public int[] getEntityIDs() { - return this.entityIDs; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S14PacketEntity.java b/src/game/java/net/minecraft/network/play/server/S14PacketEntity.java index 882d08e1..46b8ea4d 100644 --- a/src/game/java/net/minecraft/network/play/server/S14PacketEntity.java +++ b/src/game/java/net/minecraft/network/play/server/S14PacketEntity.java @@ -8,100 +8,30 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S14PacketEntity implements Packet { - protected int entityId; - protected byte posX; - protected byte posY; - protected byte posZ; - protected byte yaw; - protected byte pitch; - protected boolean onGround; - protected boolean field_149069_g; - - public S14PacketEntity() { - } - - public S14PacketEntity(int entityIdIn) { - this.entityId = entityIdIn; - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityMovement(this); - } - - public String toString() { - return "Entity_" + super.toString(); - } - - public Entity getEntity(World worldIn) { - return worldIn.getEntityByID(this.entityId); - } - - public byte func_149062_c() { - return this.posX; - } - - public byte func_149061_d() { - return this.posY; - } - - public byte func_149064_e() { - return this.posZ; - } - - public byte func_149066_f() { - return this.yaw; - } - - public byte func_149063_g() { - return this.pitch; - } - - public boolean func_149060_h() { - return this.field_149069_g; - } - - public boolean getOnGround() { - return this.onGround; - } - public static class S15PacketEntityRelMove extends S14PacketEntity { public S15PacketEntityRelMove() { } @@ -114,8 +44,8 @@ public class S14PacketEntity implements Packet { this.onGround = onGroundIn; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { super.readPacketData(parPacketBuffer); @@ -125,8 +55,8 @@ public class S14PacketEntity implements Packet { this.onGround = parPacketBuffer.readBoolean(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { super.writePacketData(parPacketBuffer); @@ -150,8 +80,8 @@ public class S14PacketEntity implements Packet { this.onGround = onGroundIn; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { super.readPacketData(parPacketBuffer); @@ -160,8 +90,8 @@ public class S14PacketEntity implements Packet { this.onGround = parPacketBuffer.readBoolean(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { super.writePacketData(parPacketBuffer); @@ -188,8 +118,8 @@ public class S14PacketEntity implements Packet { this.field_149069_g = true; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { super.readPacketData(parPacketBuffer); @@ -201,8 +131,8 @@ public class S14PacketEntity implements Packet { this.onGround = parPacketBuffer.readBoolean(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { super.writePacketData(parPacketBuffer); @@ -214,4 +144,80 @@ public class S14PacketEntity implements Packet { parPacketBuffer.writeBoolean(this.onGround); } } + + protected int entityId; + protected byte posX; + protected byte posY; + protected byte posZ; + protected byte yaw; + + protected byte pitch; + + protected boolean onGround; + + protected boolean field_149069_g; + + public S14PacketEntity() { + } + + public S14PacketEntity(int entityIdIn) { + this.entityId = entityIdIn; + } + + public boolean func_149060_h() { + return this.field_149069_g; + } + + public byte func_149061_d() { + return this.posY; + } + + public byte func_149062_c() { + return this.posX; + } + + public byte func_149063_g() { + return this.pitch; + } + + public byte func_149064_e() { + return this.posZ; + } + + public byte func_149066_f() { + return this.yaw; + } + + public Entity getEntity(World worldIn) { + return worldIn.getEntityByID(this.entityId); + } + + public boolean getOnGround() { + return this.onGround; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityMovement(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + } + + public String toString() { + return "Entity_" + super.toString(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S18PacketEntityTeleport.java b/src/game/java/net/minecraft/network/play/server/S18PacketEntityTeleport.java index e28b65fb..0c1eb37b 100644 --- a/src/game/java/net/minecraft/network/play/server/S18PacketEntityTeleport.java +++ b/src/game/java/net/minecraft/network/play/server/S18PacketEntityTeleport.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,8 +64,43 @@ public class S18PacketEntityTeleport implements Packet { this.onGround = onGroundIn; } - /**+ - * Reads the raw packet data from the data stream. + public int getEntityId() { + return this.entityId; + } + + public boolean getOnGround() { + return this.onGround; + } + + public byte getPitch() { + return this.pitch; + } + + public int getX() { + return this.posX; + } + + public int getY() { + return this.posY; + } + + public byte getYaw() { + return this.yaw; + } + + public int getZ() { + return this.posZ; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityTeleport(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readVarIntFromBuffer(); @@ -74,8 +112,8 @@ public class S18PacketEntityTeleport implements Packet { this.onGround = parPacketBuffer.readBoolean(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityId); @@ -86,39 +124,4 @@ public class S18PacketEntityTeleport implements Packet { parPacketBuffer.writeByte(this.pitch); parPacketBuffer.writeBoolean(this.onGround); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityTeleport(this); - } - - public int getEntityId() { - return this.entityId; - } - - public int getX() { - return this.posX; - } - - public int getY() { - return this.posY; - } - - public int getZ() { - return this.posZ; - } - - public byte getYaw() { - return this.yaw; - } - - public byte getPitch() { - return this.pitch; - } - - public boolean getOnGround() { - return this.onGround; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S19PacketEntityHeadLook.java b/src/game/java/net/minecraft/network/play/server/S19PacketEntityHeadLook.java index f3853d2d..cbf41431 100644 --- a/src/game/java/net/minecraft/network/play/server/S19PacketEntityHeadLook.java +++ b/src/game/java/net/minecraft/network/play/server/S19PacketEntityHeadLook.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,29 +43,6 @@ public class S19PacketEntityHeadLook implements Packet { this.yaw = parByte1; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.yaw = parPacketBuffer.readByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - parPacketBuffer.writeByte(this.yaw); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityHeadLook(this); - } - public Entity getEntity(World worldIn) { return worldIn.getEntityByID(this.entityId); } @@ -70,4 +50,27 @@ public class S19PacketEntityHeadLook implements Packet { public byte getYaw() { return this.yaw; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityHeadLook(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.yaw = parPacketBuffer.readByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + parPacketBuffer.writeByte(this.yaw); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S19PacketEntityStatus.java b/src/game/java/net/minecraft/network/play/server/S19PacketEntityStatus.java index 05ef6a7f..dd25d128 100644 --- a/src/game/java/net/minecraft/network/play/server/S19PacketEntityStatus.java +++ b/src/game/java/net/minecraft/network/play/server/S19PacketEntityStatus.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,29 +43,6 @@ public class S19PacketEntityStatus implements Packet { this.logicOpcode = opCodeIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readInt(); - this.logicOpcode = parPacketBuffer.readByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeInt(this.entityId); - parPacketBuffer.writeByte(this.logicOpcode); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityStatus(this); - } - public Entity getEntity(World worldIn) { return worldIn.getEntityByID(this.entityId); } @@ -70,4 +50,27 @@ public class S19PacketEntityStatus implements Packet { public byte getOpCode() { return this.logicOpcode; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityStatus(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readInt(); + this.logicOpcode = parPacketBuffer.readByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeInt(this.entityId); + parPacketBuffer.writeByte(this.logicOpcode); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S1BPacketEntityAttach.java b/src/game/java/net/minecraft/network/play/server/S1BPacketEntityAttach.java index 97a5a13a..3709715b 100644 --- a/src/game/java/net/minecraft/network/play/server/S1BPacketEntityAttach.java +++ b/src/game/java/net/minecraft/network/play/server/S1BPacketEntityAttach.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,8 +44,27 @@ public class S1BPacketEntityAttach implements Packet { this.vehicleEntityId = vehicle != null ? vehicle.getEntityId() : -1; } - /**+ - * Reads the raw packet data from the data stream. + public int getEntityId() { + return this.entityId; + } + + public int getLeash() { + return this.leash; + } + + public int getVehicleEntityId() { + return this.vehicleEntityId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityAttach(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readInt(); @@ -50,31 +72,12 @@ public class S1BPacketEntityAttach implements Packet { this.leash = parPacketBuffer.readUnsignedByte(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeInt(this.entityId); parPacketBuffer.writeInt(this.vehicleEntityId); parPacketBuffer.writeByte(this.leash); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityAttach(this); - } - - public int getLeash() { - return this.leash; - } - - public int getEntityId() { - return this.entityId; - } - - public int getVehicleEntityId() { - return this.vehicleEntityId; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S1CPacketEntityMetadata.java b/src/game/java/net/minecraft/network/play/server/S1CPacketEntityMetadata.java index 68e522a8..68e5ab70 100644 --- a/src/game/java/net/minecraft/network/play/server/S1CPacketEntityMetadata.java +++ b/src/game/java/net/minecraft/network/play/server/S1CPacketEntityMetadata.java @@ -8,22 +8,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,29 +48,6 @@ public class S1CPacketEntityMetadata implements Packet { } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.field_149378_b = DataWatcher.readWatchedListFromPacketBuffer(parPacketBuffer); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - DataWatcher.writeWatchedListToPacketBuffer(this.field_149378_b, parPacketBuffer); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityMetadata(this); - } - public List func_149376_c() { return this.field_149378_b; } @@ -75,4 +55,27 @@ public class S1CPacketEntityMetadata implements Packet { public int getEntityId() { return this.entityId; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityMetadata(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.field_149378_b = DataWatcher.readWatchedListFromPacketBuffer(parPacketBuffer); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + DataWatcher.writeWatchedListToPacketBuffer(this.field_149378_b, parPacketBuffer); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S1DPacketEntityEffect.java b/src/game/java/net/minecraft/network/play/server/S1DPacketEntityEffect.java index a9d9a2be..496370ef 100644 --- a/src/game/java/net/minecraft/network/play/server/S1DPacketEntityEffect.java +++ b/src/game/java/net/minecraft/network/play/server/S1DPacketEntityEffect.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.potion.PotionEffect; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,45 +53,12 @@ public class S1DPacketEntityEffect implements Packet { this.hideParticles = (byte) (effect.getIsShowParticles() ? 1 : 0); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.effectId = parPacketBuffer.readByte(); - this.amplifier = parPacketBuffer.readByte(); - this.duration = parPacketBuffer.readVarIntFromBuffer(); - this.hideParticles = parPacketBuffer.readByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - parPacketBuffer.writeByte(this.effectId); - parPacketBuffer.writeByte(this.amplifier); - parPacketBuffer.writeVarIntToBuffer(this.duration); - parPacketBuffer.writeByte(this.hideParticles); - } - public boolean func_149429_c() { return this.duration == 32767; } - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityEffect(this); - } - - public int getEntityId() { - return this.entityId; - } - - public byte getEffectId() { - return this.effectId; + public boolean func_179707_f() { + return this.hideParticles != 0; } public byte getAmplifier() { @@ -99,7 +69,40 @@ public class S1DPacketEntityEffect implements Packet { return this.duration; } - public boolean func_179707_f() { - return this.hideParticles != 0; + public byte getEffectId() { + return this.effectId; + } + + public int getEntityId() { + return this.entityId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityEffect(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.effectId = parPacketBuffer.readByte(); + this.amplifier = parPacketBuffer.readByte(); + this.duration = parPacketBuffer.readVarIntFromBuffer(); + this.hideParticles = parPacketBuffer.readByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + parPacketBuffer.writeByte(this.effectId); + parPacketBuffer.writeByte(this.amplifier); + parPacketBuffer.writeVarIntToBuffer(this.duration); + parPacketBuffer.writeByte(this.hideParticles); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S1EPacketRemoveEntityEffect.java b/src/game/java/net/minecraft/network/play/server/S1EPacketRemoveEntityEffect.java index 0fb29b27..c11d8aeb 100644 --- a/src/game/java/net/minecraft/network/play/server/S1EPacketRemoveEntityEffect.java +++ b/src/game/java/net/minecraft/network/play/server/S1EPacketRemoveEntityEffect.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.potion.PotionEffect; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,34 +42,34 @@ public class S1EPacketRemoveEntityEffect implements Packet { this.level = levelIn; } - /**+ - * Reads the raw packet data from the data stream. + public float func_149397_c() { + return this.field_149401_a; + } + + public int getLevel() { + return this.level; + } + + public int getTotalExperience() { + return this.totalExperience; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSetExperience(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.field_149401_a = parPacketBuffer.readFloat(); @@ -49,31 +71,12 @@ public class S1FPacketSetExperience implements Packet { this.totalExperience = parPacketBuffer.readVarIntFromBuffer(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeFloat(this.field_149401_a); parPacketBuffer.writeVarIntToBuffer(this.level); parPacketBuffer.writeVarIntToBuffer(this.totalExperience); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSetExperience(this); - } - - public float func_149397_c() { - return this.field_149401_a; - } - - public int getTotalExperience() { - return this.totalExperience; - } - - public int getLevel() { - return this.level; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S20PacketEntityProperties.java b/src/game/java/net/minecraft/network/play/server/S20PacketEntityProperties.java index 197214a9..f3c25ed0 100644 --- a/src/game/java/net/minecraft/network/play/server/S20PacketEntityProperties.java +++ b/src/game/java/net/minecraft/network/play/server/S20PacketEntityProperties.java @@ -4,38 +4,66 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.ai.attributes.IAttributeInstance; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S20PacketEntityProperties implements Packet { + public class Snapshot { + private final String field_151412_b; + private final double field_151413_c; + private final Collection field_151411_d; + + public Snapshot(String parString1, double parDouble1, Collection parCollection) { + this.field_151412_b = parString1; + this.field_151413_c = parDouble1; + this.field_151411_d = parCollection; + } + + public Collection func_151408_c() { + return this.field_151411_d; + } + + public String func_151409_a() { + return this.field_151412_b; + } + + public double func_151410_b() { + return this.field_151413_c; + } + } + private int entityId; + private final List field_149444_b = Lists.newArrayList(); public S20PacketEntityProperties() { @@ -52,8 +80,23 @@ public class S20PacketEntityProperties implements Packet } - /**+ - * Reads the raw packet data from the data stream. + public List func_149441_d() { + return this.field_149444_b; + } + + public int getEntityId() { + return this.entityId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityProperties(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readVarIntFromBuffer(); @@ -76,8 +119,8 @@ public class S20PacketEntityProperties implements Packet } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityId); @@ -96,43 +139,4 @@ public class S20PacketEntityProperties implements Packet } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityProperties(this); - } - - public int getEntityId() { - return this.entityId; - } - - public List func_149441_d() { - return this.field_149444_b; - } - - public class Snapshot { - private final String field_151412_b; - private final double field_151413_c; - private final Collection field_151411_d; - - public Snapshot(String parString1, double parDouble1, Collection parCollection) { - this.field_151412_b = parString1; - this.field_151413_c = parDouble1; - this.field_151411_d = parCollection; - } - - public String func_151409_a() { - return this.field_151412_b; - } - - public double func_151410_b() { - return this.field_151413_c; - } - - public Collection func_151408_c() { - return this.field_151411_d; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S21PacketChunkData.java b/src/game/java/net/minecraft/network/play/server/S21PacketChunkData.java index 53463667..8d3e40d4 100644 --- a/src/game/java/net/minecraft/network/play/server/S21PacketChunkData.java +++ b/src/game/java/net/minecraft/network/play/server/S21PacketChunkData.java @@ -11,82 +11,33 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S21PacketChunkData implements Packet { - private int chunkX; - private int chunkZ; - private S21PacketChunkData.Extracted extractedData; - private boolean field_149279_g; - - public S21PacketChunkData() { - } - - public S21PacketChunkData(Chunk chunkIn, boolean parFlag, int parInt1) { - this.chunkX = chunkIn.xPosition; - this.chunkZ = chunkIn.zPosition; - this.field_149279_g = parFlag; - this.extractedData = func_179756_a(chunkIn, parFlag, !chunkIn.getWorld().provider.getHasNoSky(), parInt1); - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.chunkX = parPacketBuffer.readInt(); - this.chunkZ = parPacketBuffer.readInt(); - this.field_149279_g = parPacketBuffer.readBoolean(); - this.extractedData = new S21PacketChunkData.Extracted(); - this.extractedData.dataSize = parPacketBuffer.readShort(); - this.extractedData.data = parPacketBuffer.readByteArray(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeInt(this.chunkX); - parPacketBuffer.writeInt(this.chunkZ); - parPacketBuffer.writeBoolean(this.field_149279_g); - parPacketBuffer.writeShort((short) (this.extractedData.dataSize & '\uffff')); - parPacketBuffer.writeByteArray(this.extractedData.data); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleChunkData(this); - } - - public byte[] func_149272_d() { - return this.extractedData.data; - } - - protected static int func_180737_a(int parInt1, boolean parFlag, boolean parFlag2) { - int i = parInt1 * 2 * 16 * 16 * 16; - int j = parInt1 * 16 * 16 * 16 / 2; - int k = parFlag ? parInt1 * 16 * 16 * 16 / 2 : 0; - int l = parFlag2 ? 256 : 0; - return i + j + k + l; + public static class Extracted { + public byte[] data; + public int dataSize; } public static S21PacketChunkData.Extracted func_179756_a(Chunk parChunk, boolean parFlag, boolean parFlag2, @@ -140,6 +91,40 @@ public class S21PacketChunkData implements Packet { return parInt1 + parArrayOfByte.length; } + protected static int func_180737_a(int parInt1, boolean parFlag, boolean parFlag2) { + int i = parInt1 * 2 * 16 * 16 * 16; + int j = parInt1 * 16 * 16 * 16 / 2; + int k = parFlag ? parInt1 * 16 * 16 * 16 / 2 : 0; + int l = parFlag2 ? 256 : 0; + return i + j + k + l; + } + + private int chunkX; + + private int chunkZ; + + private S21PacketChunkData.Extracted extractedData; + + private boolean field_149279_g; + + public S21PacketChunkData() { + } + + public S21PacketChunkData(Chunk chunkIn, boolean parFlag, int parInt1) { + this.chunkX = chunkIn.xPosition; + this.chunkZ = chunkIn.zPosition; + this.field_149279_g = parFlag; + this.extractedData = func_179756_a(chunkIn, parFlag, !chunkIn.getWorld().provider.getHasNoSky(), parInt1); + } + + public byte[] func_149272_d() { + return this.extractedData.data; + } + + public boolean func_149274_i() { + return this.field_149279_g; + } + public int getChunkX() { return this.chunkX; } @@ -152,12 +137,33 @@ public class S21PacketChunkData implements Packet { return this.extractedData.dataSize; } - public boolean func_149274_i() { - return this.field_149279_g; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleChunkData(this); } - public static class Extracted { - public byte[] data; - public int dataSize; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.chunkX = parPacketBuffer.readInt(); + this.chunkZ = parPacketBuffer.readInt(); + this.field_149279_g = parPacketBuffer.readBoolean(); + this.extractedData = new S21PacketChunkData.Extracted(); + this.extractedData.dataSize = parPacketBuffer.readShort(); + this.extractedData.data = parPacketBuffer.readByteArray(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeInt(this.chunkX); + parPacketBuffer.writeInt(this.chunkZ); + parPacketBuffer.writeBoolean(this.field_149279_g); + parPacketBuffer.writeShort((short) (this.extractedData.dataSize & '\uffff')); + parPacketBuffer.writeByteArray(this.extractedData.data); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S22PacketMultiBlockChange.java b/src/game/java/net/minecraft/network/play/server/S22PacketMultiBlockChange.java index 55d078b8..37f4e48a 100644 --- a/src/game/java/net/minecraft/network/play/server/S22PacketMultiBlockChange.java +++ b/src/game/java/net/minecraft/network/play/server/S22PacketMultiBlockChange.java @@ -11,28 +11,60 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S22PacketMultiBlockChange implements Packet { + public class BlockUpdateData { + private final short chunkPosCrammed; + private final IBlockState blockState; + + public BlockUpdateData(short parShort1, Chunk chunkIn) { + this.chunkPosCrammed = parShort1; + this.blockState = chunkIn.getBlockState(this.getPos()); + } + + public BlockUpdateData(short parShort1, IBlockState state) { + this.chunkPosCrammed = parShort1; + this.blockState = state; + } + + public short func_180089_b() { + return this.chunkPosCrammed; + } + + public IBlockState getBlockState() { + return this.blockState; + } + + public BlockPos getPos() { + return new BlockPos(S22PacketMultiBlockChange.this.chunkPosCoord.getBlock(this.chunkPosCrammed >> 12 & 15, + this.chunkPosCrammed & 255, this.chunkPosCrammed >> 8 & 15)); + } + } + private ChunkCoordIntPair chunkPosCoord; + private S22PacketMultiBlockChange.BlockUpdateData[] changedBlocks; public S22PacketMultiBlockChange() { @@ -48,8 +80,19 @@ public class S22PacketMultiBlockChange implements Packet } - /**+ - * Reads the raw packet data from the data stream. + public S22PacketMultiBlockChange.BlockUpdateData[] getChangedBlocks() { + return this.changedBlocks; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleMultiBlockChange(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.chunkPosCoord = new ChunkCoordIntPair(parPacketBuffer.readInt(), parPacketBuffer.readInt()); @@ -62,8 +105,8 @@ public class S22PacketMultiBlockChange implements Packet } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeInt(this.chunkPosCoord.chunkXPos); @@ -78,43 +121,4 @@ public class S22PacketMultiBlockChange implements Packet } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleMultiBlockChange(this); - } - - public S22PacketMultiBlockChange.BlockUpdateData[] getChangedBlocks() { - return this.changedBlocks; - } - - public class BlockUpdateData { - private final short chunkPosCrammed; - private final IBlockState blockState; - - public BlockUpdateData(short parShort1, IBlockState state) { - this.chunkPosCrammed = parShort1; - this.blockState = state; - } - - public BlockUpdateData(short parShort1, Chunk chunkIn) { - this.chunkPosCrammed = parShort1; - this.blockState = chunkIn.getBlockState(this.getPos()); - } - - public BlockPos getPos() { - return new BlockPos(S22PacketMultiBlockChange.this.chunkPosCoord.getBlock(this.chunkPosCrammed >> 12 & 15, - this.chunkPosCrammed & 255, this.chunkPosCrammed >> 8 & 15)); - } - - public short func_180089_b() { - return this.chunkPosCrammed; - } - - public IBlockState getBlockState() { - return this.blockState; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S23PacketBlockChange.java b/src/game/java/net/minecraft/network/play/server/S23PacketBlockChange.java index 91875a6e..de25c44d 100644 --- a/src/game/java/net/minecraft/network/play/server/S23PacketBlockChange.java +++ b/src/game/java/net/minecraft/network/play/server/S23PacketBlockChange.java @@ -10,22 +10,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,34 +45,34 @@ public class S23PacketBlockChange implements Packet { this.blockState = worldIn.getBlockState(blockPositionIn); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.blockPosition = parPacketBuffer.readBlockPos(); - this.blockState = (IBlockState) Block.BLOCK_STATE_IDS.getByValue(parPacketBuffer.readVarIntFromBuffer()); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeBlockPos(this.blockPosition); - parPacketBuffer.writeVarIntToBuffer(Block.BLOCK_STATE_IDS.get(this.blockState)); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleBlockChange(this); + public BlockPos getBlockPosition() { + return this.blockPosition; } public IBlockState getBlockState() { return this.blockState; } - public BlockPos getBlockPosition() { - return this.blockPosition; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleBlockChange(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.blockPosition = parPacketBuffer.readBlockPos(); + this.blockState = (IBlockState) Block.BLOCK_STATE_IDS.getByValue(parPacketBuffer.readVarIntFromBuffer()); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeBlockPos(this.blockPosition); + parPacketBuffer.writeVarIntToBuffer(Block.BLOCK_STATE_IDS.get(this.blockState)); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S24PacketBlockAction.java b/src/game/java/net/minecraft/network/play/server/S24PacketBlockAction.java index ef87dd87..5e157ee2 100644 --- a/src/game/java/net/minecraft/network/play/server/S24PacketBlockAction.java +++ b/src/game/java/net/minecraft/network/play/server/S24PacketBlockAction.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,8 +47,37 @@ public class S24PacketBlockAction implements Packet { this.block = blockIn; } - /**+ - * Reads the raw packet data from the data stream. + public BlockPos getBlockPosition() { + return this.blockPosition; + } + + public Block getBlockType() { + return this.block; + } + + /** + * + instrument data for noteblocks + */ + public int getData1() { + return this.instrument; + } + + /** + * + pitch data for noteblocks + */ + public int getData2() { + return this.pitch; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleBlockAction(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.blockPosition = parPacketBuffer.readBlockPos(); @@ -54,8 +86,8 @@ public class S24PacketBlockAction implements Packet { this.block = Block.getBlockById(parPacketBuffer.readVarIntFromBuffer() & 4095); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeBlockPos(this.blockPosition); @@ -63,33 +95,4 @@ public class S24PacketBlockAction implements Packet { parPacketBuffer.writeByte(this.pitch); parPacketBuffer.writeVarIntToBuffer(Block.getIdFromBlock(this.block) & 4095); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleBlockAction(this); - } - - public BlockPos getBlockPosition() { - return this.blockPosition; - } - - /**+ - * instrument data for noteblocks - */ - public int getData1() { - return this.instrument; - } - - /**+ - * pitch data for noteblocks - */ - public int getData2() { - return this.pitch; - } - - public Block getBlockType() { - return this.block; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S25PacketBlockBreakAnim.java b/src/game/java/net/minecraft/network/play/server/S25PacketBlockBreakAnim.java index 037120ae..4c80b6c0 100644 --- a/src/game/java/net/minecraft/network/play/server/S25PacketBlockBreakAnim.java +++ b/src/game/java/net/minecraft/network/play/server/S25PacketBlockBreakAnim.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,31 +44,6 @@ public class S25PacketBlockBreakAnim implements Packet { this.progress = progress; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.breakerId = parPacketBuffer.readVarIntFromBuffer(); - this.position = parPacketBuffer.readBlockPos(); - this.progress = parPacketBuffer.readUnsignedByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.breakerId); - parPacketBuffer.writeBlockPos(this.position); - parPacketBuffer.writeByte(this.progress); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleBlockBreakAnim(this); - } - public int getBreakerId() { return this.breakerId; } @@ -77,4 +55,29 @@ public class S25PacketBlockBreakAnim implements Packet { public int getProgress() { return this.progress; } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleBlockBreakAnim(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.breakerId = parPacketBuffer.readVarIntFromBuffer(); + this.position = parPacketBuffer.readBlockPos(); + this.progress = parPacketBuffer.readUnsignedByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.breakerId); + parPacketBuffer.writeBlockPos(this.position); + parPacketBuffer.writeByte(this.progress); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S26PacketMapChunkBulk.java b/src/game/java/net/minecraft/network/play/server/S26PacketMapChunkBulk.java index 75da0102..beb8d8c2 100644 --- a/src/game/java/net/minecraft/network/play/server/S26PacketMapChunkBulk.java +++ b/src/game/java/net/minecraft/network/play/server/S26PacketMapChunkBulk.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,8 +58,35 @@ public class S26PacketMapChunkBulk implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + public byte[] getChunkBytes(int parInt1) { + return this.chunksData[parInt1].data; + } + + public int getChunkCount() { + return this.xPositions.length; + } + + public int getChunkSize(int parInt1) { + return this.chunksData[parInt1].dataSize; + } + + public int getChunkX(int parInt1) { + return this.xPositions[parInt1]; + } + + public int getChunkZ(int parInt1) { + return this.zPositions[parInt1]; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleMapChunkBulk(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.isOverworld = parPacketBuffer.readBoolean(); @@ -80,8 +110,8 @@ public class S26PacketMapChunkBulk implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeBoolean(this.isOverworld); @@ -98,31 +128,4 @@ public class S26PacketMapChunkBulk implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleMapChunkBulk(this); - } - - public int getChunkX(int parInt1) { - return this.xPositions[parInt1]; - } - - public int getChunkZ(int parInt1) { - return this.zPositions[parInt1]; - } - - public int getChunkCount() { - return this.xPositions.length; - } - - public byte[] getChunkBytes(int parInt1) { - return this.chunksData[parInt1].data; - } - - public int getChunkSize(int parInt1) { - return this.chunksData[parInt1].dataSize; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S27PacketExplosion.java b/src/game/java/net/minecraft/network/play/server/S27PacketExplosion.java index e7623c76..9245f725 100644 --- a/src/game/java/net/minecraft/network/play/server/S27PacketExplosion.java +++ b/src/game/java/net/minecraft/network/play/server/S27PacketExplosion.java @@ -11,22 +11,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -59,8 +62,47 @@ public class S27PacketExplosion implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + public float func_149144_d() { + return this.field_149153_g; + } + + public float func_149147_e() { + return this.field_149159_h; + } + + public float func_149149_c() { + return this.field_149152_f; + } + + public List getAffectedBlockPositions() { + return this.affectedBlockPositions; + } + + public float getStrength() { + return this.strength; + } + + public double getX() { + return this.posX; + } + + public double getY() { + return this.posY; + } + + public double getZ() { + return this.posZ; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleExplosion(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.posX = (double) parPacketBuffer.readFloat(); @@ -85,8 +127,8 @@ public class S27PacketExplosion implements Packet { this.field_149159_h = parPacketBuffer.readFloat(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeFloat((float) this.posX); @@ -112,43 +154,4 @@ public class S27PacketExplosion implements Packet { parPacketBuffer.writeFloat(this.field_149153_g); parPacketBuffer.writeFloat(this.field_149159_h); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleExplosion(this); - } - - public float func_149149_c() { - return this.field_149152_f; - } - - public float func_149144_d() { - return this.field_149153_g; - } - - public float func_149147_e() { - return this.field_149159_h; - } - - public double getX() { - return this.posX; - } - - public double getY() { - return this.posY; - } - - public double getZ() { - return this.posZ; - } - - public float getStrength() { - return this.strength; - } - - public List getAffectedBlockPositions() { - return this.affectedBlockPositions; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S28PacketEffect.java b/src/game/java/net/minecraft/network/play/server/S28PacketEffect.java index 71f1dba3..3575649c 100644 --- a/src/game/java/net/minecraft/network/play/server/S28PacketEffect.java +++ b/src/game/java/net/minecraft/network/play/server/S28PacketEffect.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,8 +46,31 @@ public class S28PacketEffect implements Packet { this.serverWide = serverWideIn; } - /**+ - * Reads the raw packet data from the data stream. + public int getSoundData() { + return this.soundData; + } + + public BlockPos getSoundPos() { + return this.soundPos; + } + + public int getSoundType() { + return this.soundType; + } + + public boolean isSoundServerwide() { + return this.serverWide; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEffect(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.soundType = parPacketBuffer.readInt(); @@ -53,8 +79,8 @@ public class S28PacketEffect implements Packet { this.serverWide = parPacketBuffer.readBoolean(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeInt(this.soundType); @@ -62,27 +88,4 @@ public class S28PacketEffect implements Packet { parPacketBuffer.writeInt(this.soundData); parPacketBuffer.writeBoolean(this.serverWide); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEffect(this); - } - - public boolean isSoundServerwide() { - return this.serverWide; - } - - public int getSoundType() { - return this.soundType; - } - - public int getSoundData() { - return this.soundData; - } - - public BlockPos getSoundPos() { - return this.soundPos; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S29PacketSoundEffect.java b/src/game/java/net/minecraft/network/play/server/S29PacketSoundEffect.java index 25d3ffee..75f0d945 100644 --- a/src/game/java/net/minecraft/network/play/server/S29PacketSoundEffect.java +++ b/src/game/java/net/minecraft/network/play/server/S29PacketSoundEffect.java @@ -9,22 +9,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,34 +55,18 @@ public class S29PacketSoundEffect implements Packet { pitch = MathHelper.clamp_float(pitch, 0.0F, 255.0F); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.soundName = parPacketBuffer.readStringFromBuffer(256); - this.posX = parPacketBuffer.readInt(); - this.posY = parPacketBuffer.readInt(); - this.posZ = parPacketBuffer.readInt(); - this.soundVolume = parPacketBuffer.readFloat(); - this.soundPitch = parPacketBuffer.readUnsignedByte(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeString(this.soundName); - parPacketBuffer.writeInt(this.posX); - parPacketBuffer.writeInt(this.posY); - parPacketBuffer.writeInt(this.posZ); - parPacketBuffer.writeFloat(this.soundVolume); - parPacketBuffer.writeByte(this.soundPitch); + public float getPitch() { + return (float) this.soundPitch / 63.0F; } public String getSoundName() { return this.soundName; } + public float getVolume() { + return this.soundVolume; + } + public double getX() { return (double) ((float) this.posX / 8.0F); } @@ -92,18 +79,34 @@ public class S29PacketSoundEffect implements Packet { return (double) ((float) this.posZ / 8.0F); } - public float getVolume() { - return this.soundVolume; - } - - public float getPitch() { - return (float) this.soundPitch / 63.0F; - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleSoundEffect(this); } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.soundName = parPacketBuffer.readStringFromBuffer(256); + this.posX = parPacketBuffer.readInt(); + this.posY = parPacketBuffer.readInt(); + this.posZ = parPacketBuffer.readInt(); + this.soundVolume = parPacketBuffer.readFloat(); + this.soundPitch = parPacketBuffer.readUnsignedByte(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeString(this.soundName); + parPacketBuffer.writeInt(this.posX); + parPacketBuffer.writeInt(this.posY); + parPacketBuffer.writeInt(this.posZ); + parPacketBuffer.writeFloat(this.soundVolume); + parPacketBuffer.writeByte(this.soundPitch); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S2APacketParticles.java b/src/game/java/net/minecraft/network/play/server/S2APacketParticles.java index b3e371f8..9ef070c9 100644 --- a/src/game/java/net/minecraft/network/play/server/S2APacketParticles.java +++ b/src/game/java/net/minecraft/network/play/server/S2APacketParticles.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.EnumParticleTypes; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -59,8 +62,90 @@ public class S2APacketParticles implements Packet { this.particleArguments = particleArgumentsIn; } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Gets the particle arguments. Some particles rely on block and/or item ids + * and sometimes metadata ids to color or texture the particle. + */ + public int[] getParticleArgs() { + return this.particleArguments; + } + + /** + * + Gets the amount of particles to spawn + */ + public int getParticleCount() { + return this.particleCount; + } + + /** + * + Gets the speed of the particle animation (used in client side rendering). + */ + public float getParticleSpeed() { + return this.particleSpeed; + } + + public EnumParticleTypes getParticleType() { + return this.particleType; + } + + /** + * + Gets the x coordinate to spawn the particle. + */ + public double getXCoordinate() { + return (double) this.xCoord; + } + + /** + * + Gets the x coordinate offset for the particle. The particle may use the + * offset for particle spread. + */ + public float getXOffset() { + return this.xOffset; + } + + /** + * + Gets the y coordinate to spawn the particle. + */ + public double getYCoordinate() { + return (double) this.yCoord; + } + + /** + * + Gets the y coordinate offset for the particle. The particle may use the + * offset for particle spread. + */ + public float getYOffset() { + return this.yOffset; + } + + /** + * + Gets the z coordinate to spawn the particle. + */ + public double getZCoordinate() { + return (double) this.zCoord; + } + + /** + * + Gets the z coordinate offset for the particle. The particle may use the + * offset for particle spread. + */ + public float getZOffset() { + return this.zOffset; + } + + public boolean isLongDistance() { + return this.longDistance; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleParticles(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.particleType = EnumParticleTypes.getParticleFromId(parPacketBuffer.readInt()); @@ -86,8 +171,8 @@ public class S2APacketParticles implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeInt(this.particleType.getParticleID()); @@ -107,88 +192,4 @@ public class S2APacketParticles implements Packet { } } - - public EnumParticleTypes getParticleType() { - return this.particleType; - } - - public boolean isLongDistance() { - return this.longDistance; - } - - /**+ - * Gets the x coordinate to spawn the particle. - */ - public double getXCoordinate() { - return (double) this.xCoord; - } - - /**+ - * Gets the y coordinate to spawn the particle. - */ - public double getYCoordinate() { - return (double) this.yCoord; - } - - /**+ - * Gets the z coordinate to spawn the particle. - */ - public double getZCoordinate() { - return (double) this.zCoord; - } - - /**+ - * Gets the x coordinate offset for the particle. The particle - * may use the offset for particle spread. - */ - public float getXOffset() { - return this.xOffset; - } - - /**+ - * Gets the y coordinate offset for the particle. The particle - * may use the offset for particle spread. - */ - public float getYOffset() { - return this.yOffset; - } - - /**+ - * Gets the z coordinate offset for the particle. The particle - * may use the offset for particle spread. - */ - public float getZOffset() { - return this.zOffset; - } - - /**+ - * Gets the speed of the particle animation (used in client side - * rendering). - */ - public float getParticleSpeed() { - return this.particleSpeed; - } - - /**+ - * Gets the amount of particles to spawn - */ - public int getParticleCount() { - return this.particleCount; - } - - /**+ - * Gets the particle arguments. Some particles rely on block - * and/or item ids and sometimes metadata ids to color or - * texture the particle. - */ - public int[] getParticleArgs() { - return this.particleArguments; - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleParticles(this); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S2BPacketChangeGameState.java b/src/game/java/net/minecraft/network/play/server/S2BPacketChangeGameState.java index 7636d384..276288cf 100644 --- a/src/game/java/net/minecraft/network/play/server/S2BPacketChangeGameState.java +++ b/src/game/java/net/minecraft/network/play/server/S2BPacketChangeGameState.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,34 +42,34 @@ public class S2BPacketChangeGameState implements Packet { this.field_149141_c = parFloat1; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.state = parPacketBuffer.readUnsignedByte(); - this.field_149141_c = parPacketBuffer.readFloat(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.state); - parPacketBuffer.writeFloat(this.field_149141_c); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleChangeGameState(this); + public float func_149137_d() { + return this.field_149141_c; } public int getGameState() { return this.state; } - public float func_149137_d() { - return this.field_149141_c; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleChangeGameState(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.state = parPacketBuffer.readUnsignedByte(); + this.field_149141_c = parPacketBuffer.readFloat(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.state); + parPacketBuffer.writeFloat(this.field_149141_c); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S2CPacketSpawnGlobalEntity.java b/src/game/java/net/minecraft/network/play/server/S2CPacketSpawnGlobalEntity.java index f9d369ab..a6b38c3f 100644 --- a/src/game/java/net/minecraft/network/play/server/S2CPacketSpawnGlobalEntity.java +++ b/src/game/java/net/minecraft/network/play/server/S2CPacketSpawnGlobalEntity.java @@ -9,22 +9,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,8 +53,35 @@ public class S2CPacketSpawnGlobalEntity implements Packet } - /**+ - * Reads the raw packet data from the data stream. + public int func_149049_f() { + return this.z; + } + + public int func_149050_e() { + return this.y; + } + + public int func_149051_d() { + return this.x; + } + + public int func_149052_c() { + return this.entityId; + } + + public int func_149053_g() { + return this.type; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSpawnGlobalEntity(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.entityId = parPacketBuffer.readVarIntFromBuffer(); @@ -61,8 +91,8 @@ public class S2CPacketSpawnGlobalEntity implements Packet this.z = parPacketBuffer.readInt(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.entityId); @@ -71,31 +101,4 @@ public class S2CPacketSpawnGlobalEntity implements Packet parPacketBuffer.writeInt(this.y); parPacketBuffer.writeInt(this.z); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSpawnGlobalEntity(this); - } - - public int func_149052_c() { - return this.entityId; - } - - public int func_149051_d() { - return this.x; - } - - public int func_149050_e() { - return this.y; - } - - public int func_149049_f() { - return this.z; - } - - public int func_149053_g() { - return this.type; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S2DPacketOpenWindow.java b/src/game/java/net/minecraft/network/play/server/S2DPacketOpenWindow.java index 8e19e670..5f265b3b 100644 --- a/src/game/java/net/minecraft/network/play/server/S2DPacketOpenWindow.java +++ b/src/game/java/net/minecraft/network/play/server/S2DPacketOpenWindow.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,15 +57,39 @@ public class S2DPacketOpenWindow implements Packet { this.entityId = incomingEntityId; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public int getEntityId() { + return this.entityId; + } + + public String getGuiId() { + return this.inventoryType; + } + + public int getSlotCount() { + return this.slotCount; + } + + public int getWindowId() { + return this.windowId; + } + + public IChatComponent getWindowTitle() { + return this.windowTitle; + } + + public boolean hasSlots() { + return this.slotCount > 0; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleOpenWindow(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.windowId = parPacketBuffer.readUnsignedByte(); @@ -75,8 +102,8 @@ public class S2DPacketOpenWindow implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeByte(this.windowId); @@ -88,28 +115,4 @@ public class S2DPacketOpenWindow implements Packet { } } - - public int getWindowId() { - return this.windowId; - } - - public String getGuiId() { - return this.inventoryType; - } - - public IChatComponent getWindowTitle() { - return this.windowTitle; - } - - public int getSlotCount() { - return this.slotCount; - } - - public int getEntityId() { - return this.entityId; - } - - public boolean hasSlots() { - return this.slotCount > 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S2EPacketCloseWindow.java b/src/game/java/net/minecraft/network/play/server/S2EPacketCloseWindow.java index 6b86a0f5..a58a5d56 100644 --- a/src/game/java/net/minecraft/network/play/server/S2EPacketCloseWindow.java +++ b/src/game/java/net/minecraft/network/play/server/S2EPacketCloseWindow.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,22 +39,22 @@ public class S2EPacketCloseWindow implements Packet { this.windowId = windowIdIn; } - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleCloseWindow(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.windowId = parPacketBuffer.readUnsignedByte(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeByte(this.windowId); diff --git a/src/game/java/net/minecraft/network/play/server/S2FPacketSetSlot.java b/src/game/java/net/minecraft/network/play/server/S2FPacketSetSlot.java index 2fb6fed2..6f9a9c50 100644 --- a/src/game/java/net/minecraft/network/play/server/S2FPacketSetSlot.java +++ b/src/game/java/net/minecraft/network/play/server/S2FPacketSetSlot.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,35 +44,6 @@ public class S2FPacketSetSlot implements Packet { this.item = itemIn == null ? null : itemIn.copy(); } - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleSetSlot(this); - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.windowId = parPacketBuffer.readByte(); - this.slot = parPacketBuffer.readShort(); - this.item = parPacketBuffer.readItemStackFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.windowId); - parPacketBuffer.writeShort(this.slot); - parPacketBuffer.writeItemStackToBuffer(this.item); - } - - public int func_149175_c() { - return this.windowId; - } - public int func_149173_d() { return this.slot; } @@ -77,4 +51,33 @@ public class S2FPacketSetSlot implements Packet { public ItemStack func_149174_e() { return this.item; } + + public int func_149175_c() { + return this.windowId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleSetSlot(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.windowId = parPacketBuffer.readByte(); + this.slot = parPacketBuffer.readShort(); + this.item = parPacketBuffer.readItemStackFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.windowId); + parPacketBuffer.writeShort(this.slot); + parPacketBuffer.writeItemStackToBuffer(this.item); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S30PacketWindowItems.java b/src/game/java/net/minecraft/network/play/server/S30PacketWindowItems.java index 1c745510..3e14d968 100644 --- a/src/game/java/net/minecraft/network/play/server/S30PacketWindowItems.java +++ b/src/game/java/net/minecraft/network/play/server/S30PacketWindowItems.java @@ -8,22 +8,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,8 +49,23 @@ public class S30PacketWindowItems implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + public int func_148911_c() { + return this.windowId; + } + + public ItemStack[] getItemStacks() { + return this.itemStacks; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleWindowItems(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.windowId = parPacketBuffer.readUnsignedByte(); @@ -60,8 +78,8 @@ public class S30PacketWindowItems implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeByte(this.windowId); @@ -72,19 +90,4 @@ public class S30PacketWindowItems implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleWindowItems(this); - } - - public int func_148911_c() { - return this.windowId; - } - - public ItemStack[] getItemStacks() { - return this.itemStacks; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S31PacketWindowProperty.java b/src/game/java/net/minecraft/network/play/server/S31PacketWindowProperty.java index f5498afc..1901107b 100644 --- a/src/game/java/net/minecraft/network/play/server/S31PacketWindowProperty.java +++ b/src/game/java/net/minecraft/network/play/server/S31PacketWindowProperty.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,35 +43,6 @@ public class S31PacketWindowProperty implements Packet { this.varValue = varValueIn; } - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleWindowProperty(this); - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.windowId = parPacketBuffer.readUnsignedByte(); - this.varIndex = parPacketBuffer.readShort(); - this.varValue = parPacketBuffer.readShort(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.windowId); - parPacketBuffer.writeShort(this.varIndex); - parPacketBuffer.writeShort(this.varValue); - } - - public int getWindowId() { - return this.windowId; - } - public int getVarIndex() { return this.varIndex; } @@ -76,4 +50,33 @@ public class S31PacketWindowProperty implements Packet { public int getVarValue() { return this.varValue; } + + public int getWindowId() { + return this.windowId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleWindowProperty(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.windowId = parPacketBuffer.readUnsignedByte(); + this.varIndex = parPacketBuffer.readShort(); + this.varValue = parPacketBuffer.readShort(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.windowId); + parPacketBuffer.writeShort(this.varIndex); + parPacketBuffer.writeShort(this.varValue); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S32PacketConfirmTransaction.java b/src/game/java/net/minecraft/network/play/server/S32PacketConfirmTransaction.java index ddc9e8cb..8da9f9b0 100644 --- a/src/game/java/net/minecraft/network/play/server/S32PacketConfirmTransaction.java +++ b/src/game/java/net/minecraft/network/play/server/S32PacketConfirmTransaction.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,15 +43,27 @@ public class S32PacketConfirmTransaction implements Packet { this.lines = new IChatComponent[] { linesIn[0], linesIn[1], linesIn[2], linesIn[3] }; } - /**+ - * Reads the raw packet data from the data stream. + public IChatComponent[] getLines() { + return this.lines; + } + + public BlockPos getPos() { + return this.blockPos; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleUpdateSign(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.blockPos = parPacketBuffer.readBlockPos(); @@ -56,8 +74,8 @@ public class S33PacketUpdateSign implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeBlockPos(this.blockPos); @@ -67,19 +85,4 @@ public class S33PacketUpdateSign implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleUpdateSign(this); - } - - public BlockPos getPos() { - return this.blockPos; - } - - public IChatComponent[] getLines() { - return this.lines; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S34PacketMaps.java b/src/game/java/net/minecraft/network/play/server/S34PacketMaps.java index 9c30a976..dc4d6afb 100644 --- a/src/game/java/net/minecraft/network/play/server/S34PacketMaps.java +++ b/src/game/java/net/minecraft/network/play/server/S34PacketMaps.java @@ -9,22 +9,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.Vec4b; import net.minecraft.world.storage.MapData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,8 +64,19 @@ public class S34PacketMaps implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + public int getMapId() { + return this.mapId; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleMaps(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.mapId = parPacketBuffer.readVarIntFromBuffer(); @@ -85,8 +99,28 @@ public class S34PacketMaps implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Sets new MapData from the packet to given MapData param + */ + public void setMapdataTo(MapData mapdataIn) { + mapdataIn.scale = this.mapScale; + mapdataIn.mapDecorations.clear(); + + for (int i = 0; i < this.mapVisiblePlayersVec4b.length; ++i) { + Vec4b vec4b = this.mapVisiblePlayersVec4b[i]; + mapdataIn.mapDecorations.put("icon-" + i, vec4b); + } + + for (int j = 0; j < this.mapMaxX; ++j) { + for (int k = 0; k < this.mapMaxY; ++k) { + mapdataIn.colors[this.mapMinX + j + (this.mapMinY + k) * 128] = this.mapDataBytes[j + k * this.mapMaxX]; + } + } + + } + + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.mapId); @@ -109,35 +143,4 @@ public class S34PacketMaps implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleMaps(this); - } - - public int getMapId() { - return this.mapId; - } - - /**+ - * Sets new MapData from the packet to given MapData param - */ - public void setMapdataTo(MapData mapdataIn) { - mapdataIn.scale = this.mapScale; - mapdataIn.mapDecorations.clear(); - - for (int i = 0; i < this.mapVisiblePlayersVec4b.length; ++i) { - Vec4b vec4b = this.mapVisiblePlayersVec4b[i]; - mapdataIn.mapDecorations.put("icon-" + i, vec4b); - } - - for (int j = 0; j < this.mapMaxX; ++j) { - for (int k = 0; k < this.mapMaxY; ++k) { - mapdataIn.colors[this.mapMinX + j + (this.mapMinY + k) * 128] = this.mapDataBytes[j + k * this.mapMaxX]; - } - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S35PacketUpdateTileEntity.java b/src/game/java/net/minecraft/network/play/server/S35PacketUpdateTileEntity.java index 80c84131..a3d66f9b 100644 --- a/src/game/java/net/minecraft/network/play/server/S35PacketUpdateTileEntity.java +++ b/src/game/java/net/minecraft/network/play/server/S35PacketUpdateTileEntity.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,29 +45,8 @@ public class S35PacketUpdateTileEntity implements Packet this.nbt = nbtIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.blockPos = parPacketBuffer.readBlockPos(); - this.metadata = parPacketBuffer.readUnsignedByte(); - this.nbt = parPacketBuffer.readNBTTagCompoundFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeBlockPos(this.blockPos); - parPacketBuffer.writeByte((byte) this.metadata); - parPacketBuffer.writeNBTTagCompoundToBuffer(this.nbt); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleUpdateTileEntity(this); + public NBTTagCompound getNbtCompound() { + return this.nbt; } public BlockPos getPos() { @@ -75,7 +57,28 @@ public class S35PacketUpdateTileEntity implements Packet return this.metadata; } - public NBTTagCompound getNbtCompound() { - return this.nbt; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleUpdateTileEntity(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.blockPos = parPacketBuffer.readBlockPos(); + this.metadata = parPacketBuffer.readUnsignedByte(); + this.nbt = parPacketBuffer.readNBTTagCompoundFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeBlockPos(this.blockPos); + parPacketBuffer.writeByte((byte) this.metadata); + parPacketBuffer.writeNBTTagCompoundToBuffer(this.nbt); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S36PacketSignEditorOpen.java b/src/game/java/net/minecraft/network/play/server/S36PacketSignEditorOpen.java index 1c4b1152..6fe87502 100644 --- a/src/game/java/net/minecraft/network/play/server/S36PacketSignEditorOpen.java +++ b/src/game/java/net/minecraft/network/play/server/S36PacketSignEditorOpen.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,28 +40,28 @@ public class S36PacketSignEditorOpen implements Packet { this.signPosition = signPositionIn; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public BlockPos getSignPosition() { + return this.signPosition; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleSignEditorOpen(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.signPosition = parPacketBuffer.readBlockPos(); } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeBlockPos(this.signPosition); } - - public BlockPos getSignPosition() { - return this.signPosition; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S37PacketStatistics.java b/src/game/java/net/minecraft/network/play/server/S37PacketStatistics.java index 213331c8..1dbe87ae 100644 --- a/src/game/java/net/minecraft/network/play/server/S37PacketStatistics.java +++ b/src/game/java/net/minecraft/network/play/server/S37PacketStatistics.java @@ -12,22 +12,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.stats.StatBase; import net.minecraft.stats.StatList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,15 +45,19 @@ public class S37PacketStatistics implements Packet { this.field_148976_a = parMap; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public Map func_148974_c() { + return this.field_148976_a; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleStatistics(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { int i = parPacketBuffer.readVarIntFromBuffer(); @@ -66,8 +73,8 @@ public class S37PacketStatistics implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.field_148976_a.size()); @@ -78,8 +85,4 @@ public class S37PacketStatistics implements Packet { } } - - public Map func_148974_c() { - return this.field_148976_a; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S38PacketPlayerListItem.java b/src/game/java/net/minecraft/network/play/server/S38PacketPlayerListItem.java index 9d7b4ec3..92099ce0 100644 --- a/src/game/java/net/minecraft/network/play/server/S38PacketPlayerListItem.java +++ b/src/game/java/net/minecraft/network/play/server/S38PacketPlayerListItem.java @@ -1,11 +1,13 @@ package net.minecraft.network.play.server; +import java.io.IOException; +import java.util.List; + import com.google.common.base.Objects; import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.mojang.authlib.Property; -import java.io.IOException; -import java.util.List; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; @@ -13,28 +15,74 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.IChatComponent; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S38PacketPlayerListItem implements Packet { + public static enum Action { + ADD_PLAYER, UPDATE_GAME_MODE, UPDATE_LATENCY, UPDATE_DISPLAY_NAME, REMOVE_PLAYER; + } + + public class AddPlayerData { + private final int ping; + private final WorldSettings.GameType gamemode; + private final GameProfile profile; + private final IChatComponent displayName; + + public AddPlayerData(GameProfile profile, int pingIn, WorldSettings.GameType gamemodeIn, + IChatComponent displayNameIn) { + this.profile = profile; + this.ping = pingIn; + this.gamemode = gamemodeIn; + this.displayName = displayNameIn; + } + + public IChatComponent getDisplayName() { + return this.displayName; + } + + public WorldSettings.GameType getGameMode() { + return this.gamemode; + } + + public int getPing() { + return this.ping; + } + + public GameProfile getProfile() { + return this.profile; + } + + public String toString() { + return Objects.toStringHelper(this).add("latency", this.ping).add("gameMode", this.gamemode) + .add("profile", this.profile).add("displayName", this.displayName == null ? null + : IChatComponent.Serializer.componentToJson(this.displayName)) + .toString(); + } + } + private S38PacketPlayerListItem.Action action; + private final List players = Lists.newArrayList(); public S38PacketPlayerListItem() { @@ -63,8 +111,23 @@ public class S38PacketPlayerListItem implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + public List func_179767_a() { + return this.players; + } + + public S38PacketPlayerListItem.Action func_179768_b() { + return this.action; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handlePlayerListItem(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.action = (S38PacketPlayerListItem.Action) parPacketBuffer @@ -123,8 +186,12 @@ public class S38PacketPlayerListItem implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + public String toString() { + return Objects.toStringHelper(this).add("action", this.action).add("entries", this.players).toString(); + } + + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeEnumValue(this.action); @@ -182,65 +249,4 @@ public class S38PacketPlayerListItem implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handlePlayerListItem(this); - } - - public List func_179767_a() { - return this.players; - } - - public S38PacketPlayerListItem.Action func_179768_b() { - return this.action; - } - - public String toString() { - return Objects.toStringHelper(this).add("action", this.action).add("entries", this.players).toString(); - } - - public static enum Action { - ADD_PLAYER, UPDATE_GAME_MODE, UPDATE_LATENCY, UPDATE_DISPLAY_NAME, REMOVE_PLAYER; - } - - public class AddPlayerData { - private final int ping; - private final WorldSettings.GameType gamemode; - private final GameProfile profile; - private final IChatComponent displayName; - - public AddPlayerData(GameProfile profile, int pingIn, WorldSettings.GameType gamemodeIn, - IChatComponent displayNameIn) { - this.profile = profile; - this.ping = pingIn; - this.gamemode = gamemodeIn; - this.displayName = displayNameIn; - } - - public GameProfile getProfile() { - return this.profile; - } - - public int getPing() { - return this.ping; - } - - public WorldSettings.GameType getGameMode() { - return this.gamemode; - } - - public IChatComponent getDisplayName() { - return this.displayName; - } - - public String toString() { - return Objects.toStringHelper(this).add("latency", this.ping).add("gameMode", this.gamemode) - .add("profile", this.profile).add("displayName", this.displayName == null ? null - : IChatComponent.Serializer.componentToJson(this.displayName)) - .toString(); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S39PacketPlayerAbilities.java b/src/game/java/net/minecraft/network/play/server/S39PacketPlayerAbilities.java index f556582d..94fb80a6 100644 --- a/src/game/java/net/minecraft/network/play/server/S39PacketPlayerAbilities.java +++ b/src/game/java/net/minecraft/network/play/server/S39PacketPlayerAbilities.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,8 +50,39 @@ public class S39PacketPlayerAbilities implements Packet { this.setWalkSpeed(capabilities.getWalkSpeed()); } - /**+ - * Reads the raw packet data from the data stream. + public float getFlySpeed() { + return this.flySpeed; + } + + public float getWalkSpeed() { + return this.walkSpeed; + } + + public boolean isAllowFlying() { + return this.allowFlying; + } + + public boolean isCreativeMode() { + return this.creativeMode; + } + + public boolean isFlying() { + return this.flying; + } + + public boolean isInvulnerable() { + return this.invulnerable; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handlePlayerAbilities(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { byte b0 = parPacketBuffer.readByte(); @@ -60,8 +94,32 @@ public class S39PacketPlayerAbilities implements Packet { this.setWalkSpeed(parPacketBuffer.readFloat()); } - /**+ - * Writes the raw packet data to the data stream. + public void setAllowFlying(boolean isAllowFlying) { + this.allowFlying = isAllowFlying; + } + + public void setCreativeMode(boolean isCreativeMode) { + this.creativeMode = isCreativeMode; + } + + public void setFlying(boolean isFlying) { + this.flying = isFlying; + } + + public void setFlySpeed(float flySpeedIn) { + this.flySpeed = flySpeedIn; + } + + public void setInvulnerable(boolean isInvulnerable) { + this.invulnerable = isInvulnerable; + } + + public void setWalkSpeed(float walkSpeedIn) { + this.walkSpeed = walkSpeedIn; + } + + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { byte b0 = 0; @@ -85,59 +143,4 @@ public class S39PacketPlayerAbilities implements Packet { parPacketBuffer.writeFloat(this.flySpeed); parPacketBuffer.writeFloat(this.walkSpeed); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handlePlayerAbilities(this); - } - - public boolean isInvulnerable() { - return this.invulnerable; - } - - public void setInvulnerable(boolean isInvulnerable) { - this.invulnerable = isInvulnerable; - } - - public boolean isFlying() { - return this.flying; - } - - public void setFlying(boolean isFlying) { - this.flying = isFlying; - } - - public boolean isAllowFlying() { - return this.allowFlying; - } - - public void setAllowFlying(boolean isAllowFlying) { - this.allowFlying = isAllowFlying; - } - - public boolean isCreativeMode() { - return this.creativeMode; - } - - public void setCreativeMode(boolean isCreativeMode) { - this.creativeMode = isCreativeMode; - } - - public float getFlySpeed() { - return this.flySpeed; - } - - public void setFlySpeed(float flySpeedIn) { - this.flySpeed = flySpeedIn; - } - - public float getWalkSpeed() { - return this.walkSpeed; - } - - public void setWalkSpeed(float walkSpeedIn) { - this.walkSpeed = walkSpeedIn; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S3APacketTabComplete.java b/src/game/java/net/minecraft/network/play/server/S3APacketTabComplete.java index c20d955e..9d05fbcf 100644 --- a/src/game/java/net/minecraft/network/play/server/S3APacketTabComplete.java +++ b/src/game/java/net/minecraft/network/play/server/S3APacketTabComplete.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,19 @@ public class S3APacketTabComplete implements Packet { this.matches = matchesIn; } - /**+ - * Reads the raw packet data from the data stream. + public String[] func_149630_c() { + return this.matches; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleTabComplete(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.matches = new String[parPacketBuffer.readVarIntFromBuffer()]; @@ -48,8 +62,8 @@ public class S3APacketTabComplete implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeVarIntToBuffer(this.matches.length); @@ -59,15 +73,4 @@ public class S3APacketTabComplete implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleTabComplete(this); - } - - public String[] func_149630_c() { - return this.matches; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S3BPacketScoreboardObjective.java b/src/game/java/net/minecraft/network/play/server/S3BPacketScoreboardObjective.java index e6b8203c..bd5db149 100644 --- a/src/game/java/net/minecraft/network/play/server/S3BPacketScoreboardObjective.java +++ b/src/game/java/net/minecraft/network/play/server/S3BPacketScoreboardObjective.java @@ -8,22 +8,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.scoreboard.IScoreObjectiveCriteria; import net.minecraft.scoreboard.ScoreObjective; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,8 +47,31 @@ public class S3BPacketScoreboardObjective implements Packet { + public static enum Action { + CHANGE, REMOVE; + } + private String name = ""; private String objective = ""; private int value; + private S3CPacketUpdateScore.Action action; public S3CPacketUpdateScore() { @@ -58,8 +66,31 @@ public class S3CPacketUpdateScore implements Packet { this.action = S3CPacketUpdateScore.Action.REMOVE; } - /**+ - * Reads the raw packet data from the data stream. + public String getObjectiveName() { + return this.objective; + } + + public String getPlayerName() { + return this.name; + } + + public S3CPacketUpdateScore.Action getScoreAction() { + return this.action; + } + + public int getScoreValue() { + return this.value; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleUpdateScore(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.name = parPacketBuffer.readStringFromBuffer(40); @@ -71,8 +102,8 @@ public class S3CPacketUpdateScore implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeString(this.name); @@ -83,31 +114,4 @@ public class S3CPacketUpdateScore implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleUpdateScore(this); - } - - public String getPlayerName() { - return this.name; - } - - public String getObjectiveName() { - return this.objective; - } - - public int getScoreValue() { - return this.value; - } - - public S3CPacketUpdateScore.Action getScoreAction() { - return this.action; - } - - public static enum Action { - CHANGE, REMOVE; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S3DPacketDisplayScoreboard.java b/src/game/java/net/minecraft/network/play/server/S3DPacketDisplayScoreboard.java index 1d276cac..0f851f55 100644 --- a/src/game/java/net/minecraft/network/play/server/S3DPacketDisplayScoreboard.java +++ b/src/game/java/net/minecraft/network/play/server/S3DPacketDisplayScoreboard.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.scoreboard.ScoreObjective; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,34 +47,34 @@ public class S3DPacketDisplayScoreboard implements Packet } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.position = parPacketBuffer.readByte(); - this.scoreName = parPacketBuffer.readStringFromBuffer(16); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeByte(this.position); - parPacketBuffer.writeString(this.scoreName); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleDisplayScoreboard(this); + public String func_149370_d() { + return this.scoreName; } public int func_149371_c() { return this.position; } - public String func_149370_d() { - return this.scoreName; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleDisplayScoreboard(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.position = parPacketBuffer.readByte(); + this.scoreName = parPacketBuffer.readStringFromBuffer(16); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeByte(this.position); + parPacketBuffer.writeString(this.scoreName); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S3EPacketTeams.java b/src/game/java/net/minecraft/network/play/server/S3EPacketTeams.java index 7b6030fa..3c4f29d1 100644 --- a/src/game/java/net/minecraft/network/play/server/S3EPacketTeams.java +++ b/src/game/java/net/minecraft/network/play/server/S3EPacketTeams.java @@ -11,22 +11,25 @@ import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.scoreboard.ScorePlayerTeam; import net.minecraft.scoreboard.Team; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,6 +51,21 @@ public class S3EPacketTeams implements Packet { this.field_149317_e = Lists.newArrayList(); } + public S3EPacketTeams(ScorePlayerTeam parScorePlayerTeam, Collection parCollection, int parInt1) { + this.field_179816_e = Team.EnumVisible.ALWAYS.field_178830_e; + this.field_179815_f = -1; + this.field_149317_e = Lists.newArrayList(); + if (parInt1 != 3 && parInt1 != 4) { + throw new IllegalArgumentException("Method must be join or leave for player constructor"); + } else if (parCollection != null && !parCollection.isEmpty()) { + this.field_149314_f = parInt1; + this.field_149320_a = parScorePlayerTeam.getRegisteredName(); + this.field_149317_e.addAll(parCollection); + } else { + throw new IllegalArgumentException("Players cannot be null/empty"); + } + } + public S3EPacketTeams(ScorePlayerTeam parScorePlayerTeam, int parInt1) { this.field_179816_e = Team.EnumVisible.ALWAYS.field_178830_e; this.field_179815_f = -1; @@ -69,23 +87,51 @@ public class S3EPacketTeams implements Packet { } - public S3EPacketTeams(ScorePlayerTeam parScorePlayerTeam, Collection parCollection, int parInt1) { - this.field_179816_e = Team.EnumVisible.ALWAYS.field_178830_e; - this.field_179815_f = -1; - this.field_149317_e = Lists.newArrayList(); - if (parInt1 != 3 && parInt1 != 4) { - throw new IllegalArgumentException("Method must be join or leave for player constructor"); - } else if (parCollection != null && !parCollection.isEmpty()) { - this.field_149314_f = parInt1; - this.field_149320_a = parScorePlayerTeam.getRegisteredName(); - this.field_149317_e.addAll(parCollection); - } else { - throw new IllegalArgumentException("Players cannot be null/empty"); - } + public String func_149306_d() { + return this.field_149318_b; } - /**+ - * Reads the raw packet data from the data stream. + public int func_149307_h() { + return this.field_149314_f; + } + + public int func_149308_i() { + return this.field_149315_g; + } + + public String func_149309_f() { + return this.field_149316_d; + } + + public Collection func_149310_g() { + return this.field_149317_e; + } + + public String func_149311_e() { + return this.field_149319_c; + } + + public String func_149312_c() { + return this.field_149320_a; + } + + public int func_179813_h() { + return this.field_179815_f; + } + + public String func_179814_i() { + return this.field_179816_e; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleTeams(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.field_149320_a = parPacketBuffer.readStringFromBuffer(16); @@ -109,8 +155,8 @@ public class S3EPacketTeams implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeString(this.field_149320_a); @@ -133,47 +179,4 @@ public class S3EPacketTeams implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleTeams(this); - } - - public String func_149312_c() { - return this.field_149320_a; - } - - public String func_149306_d() { - return this.field_149318_b; - } - - public String func_149311_e() { - return this.field_149319_c; - } - - public String func_149309_f() { - return this.field_149316_d; - } - - public Collection func_149310_g() { - return this.field_149317_e; - } - - public int func_149307_h() { - return this.field_149314_f; - } - - public int func_149308_i() { - return this.field_149315_g; - } - - public int func_179813_h() { - return this.field_179815_f; - } - - public String func_179814_i() { - return this.field_179816_e; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S3FPacketCustomPayload.java b/src/game/java/net/minecraft/network/play/server/S3FPacketCustomPayload.java index fcc56636..f58a5fe2 100644 --- a/src/game/java/net/minecraft/network/play/server/S3FPacketCustomPayload.java +++ b/src/game/java/net/minecraft/network/play/server/S3FPacketCustomPayload.java @@ -7,22 +7,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,8 +45,23 @@ public class S3FPacketCustomPayload implements Packet { } } - /**+ - * Reads the raw packet data from the data stream. + public PacketBuffer getBufferData() { + return this.data; + } + + public String getChannelName() { + return this.channel; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleCustomPayload(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.channel = parPacketBuffer.readStringFromBuffer(20); @@ -55,26 +73,11 @@ public class S3FPacketCustomPayload implements Packet { } } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeString(this.channel); parPacketBuffer.writeBytes((ByteBuf) this.data); } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleCustomPayload(this); - } - - public String getChannelName() { - return this.channel; - } - - public PacketBuffer getBufferData() { - return this.data; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S40PacketDisconnect.java b/src/game/java/net/minecraft/network/play/server/S40PacketDisconnect.java index 3a5b9c36..7bade5dd 100644 --- a/src/game/java/net/minecraft/network/play/server/S40PacketDisconnect.java +++ b/src/game/java/net/minecraft/network/play/server/S40PacketDisconnect.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,28 +40,28 @@ public class S40PacketDisconnect implements Packet { this.reason = reasonIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.reason = parPacketBuffer.readChatComponent(); + public IChatComponent getReason() { + return this.reason; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeChatComponent(this.reason); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleDisconnect(this); } - public IChatComponent getReason() { - return this.reason; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.reason = parPacketBuffer.readChatComponent(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeChatComponent(this.reason); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S41PacketServerDifficulty.java b/src/game/java/net/minecraft/network/play/server/S41PacketServerDifficulty.java index cfeaf08d..2b30ac49 100644 --- a/src/game/java/net/minecraft/network/play/server/S41PacketServerDifficulty.java +++ b/src/game/java/net/minecraft/network/play/server/S41PacketServerDifficulty.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.EnumDifficulty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,15 +42,23 @@ public class S41PacketServerDifficulty implements Packet this.difficultyLocked = lockedIn; } - /**+ - * Passes this Packet on to the NetHandler for processing. + public EnumDifficulty getDifficulty() { + return this.difficulty; + } + + public boolean isDifficultyLocked() { + return this.difficultyLocked; + } + + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleServerDifficulty(this); } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { int i = parPacketBuffer.readUnsignedByte(); @@ -55,18 +66,10 @@ public class S41PacketServerDifficulty implements Packet this.difficultyLocked = (i & 4) != 0; } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeByte(this.difficulty.getDifficultyId() | (this.difficultyLocked ? 4 : 0)); } - - public boolean isDifficultyLocked() { - return this.difficultyLocked; - } - - public EnumDifficulty getDifficulty() { - return this.difficulty; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S42PacketCombatEvent.java b/src/game/java/net/minecraft/network/play/server/S42PacketCombatEvent.java index e44f7d1c..34d6d863 100644 --- a/src/game/java/net/minecraft/network/play/server/S42PacketCombatEvent.java +++ b/src/game/java/net/minecraft/network/play/server/S42PacketCombatEvent.java @@ -8,31 +8,39 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.CombatTracker; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S42PacketCombatEvent implements Packet { + public static enum Event { + ENTER_COMBAT, END_COMBAT, ENTITY_DIED; + } + public S42PacketCombatEvent.Event eventType; public int field_179774_b; public int field_179775_c; public int field_179772_d; + public String deathMessage; public S42PacketCombatEvent() { @@ -54,8 +62,15 @@ public class S42PacketCombatEvent implements Packet { } - /**+ - * Reads the raw packet data from the data stream. + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleCombatEvent(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.eventType = (S42PacketCombatEvent.Event) parPacketBuffer.readEnumValue(S42PacketCombatEvent.Event.class); @@ -70,8 +85,8 @@ public class S42PacketCombatEvent implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeEnumValue(this.eventType); @@ -85,15 +100,4 @@ public class S42PacketCombatEvent implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleCombatEvent(this); - } - - public static enum Event { - ENTER_COMBAT, END_COMBAT, ENTITY_DIED; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S43PacketCamera.java b/src/game/java/net/minecraft/network/play/server/S43PacketCamera.java index b3c410ad..62542981 100644 --- a/src/game/java/net/minecraft/network/play/server/S43PacketCamera.java +++ b/src/game/java/net/minecraft/network/play/server/S43PacketCamera.java @@ -8,22 +8,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,28 +41,28 @@ public class S43PacketCamera implements Packet { this.entityId = entityIn.getEntityId(); } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); + public Entity getEntity(World worldIn) { + return worldIn.getEntityByID(this.entityId); } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleCamera(this); } - public Entity getEntity(World worldIn) { - return worldIn.getEntityByID(this.entityId); + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S44PacketWorldBorder.java b/src/game/java/net/minecraft/network/play/server/S44PacketWorldBorder.java index c0be7a8c..2ad8d896 100644 --- a/src/game/java/net/minecraft/network/play/server/S44PacketWorldBorder.java +++ b/src/game/java/net/minecraft/network/play/server/S44PacketWorldBorder.java @@ -7,27 +7,34 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.border.WorldBorder; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S44PacketWorldBorder implements Packet { + public static enum Action { + SET_SIZE, LERP_SIZE, SET_CENTER, INITIALIZE, SET_WARNING_TIME, SET_WARNING_BLOCKS; + } + private S44PacketWorldBorder.Action action; private int size; private double centerX; @@ -36,6 +43,7 @@ public class S44PacketWorldBorder implements Packet { private double diameter; private long timeUntilTarget; private int warningTime; + private int warningDistance; public S44PacketWorldBorder() { @@ -53,8 +61,47 @@ public class S44PacketWorldBorder implements Packet { this.warningTime = border.getWarningTime(); } - /**+ - * Reads the raw packet data from the data stream. + public void func_179788_a(WorldBorder border) { + switch (this.action) { + case SET_SIZE: + border.setTransition(this.targetSize); + break; + case LERP_SIZE: + border.setTransition(this.diameter, this.targetSize, this.timeUntilTarget); + break; + case SET_CENTER: + border.setCenter(this.centerX, this.centerZ); + break; + case SET_WARNING_BLOCKS: + border.setWarningDistance(this.warningDistance); + break; + case SET_WARNING_TIME: + border.setWarningTime(this.warningTime); + break; + case INITIALIZE: + border.setCenter(this.centerX, this.centerZ); + if (this.timeUntilTarget > 0L) { + border.setTransition(this.diameter, this.targetSize, this.timeUntilTarget); + } else { + border.setTransition(this.targetSize); + } + + border.setSize(this.size); + border.setWarningDistance(this.warningDistance); + border.setWarningTime(this.warningTime); + } + + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleWorldBorder(this); + } + + /** + * + Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { this.action = (S44PacketWorldBorder.Action) parPacketBuffer.readEnumValue(S44PacketWorldBorder.Action.class); @@ -90,8 +137,8 @@ public class S44PacketWorldBorder implements Packet { } - /**+ - * Writes the raw packet data to the data stream. + /** + * + Writes the raw packet data to the data stream. */ public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { parPacketBuffer.writeEnumValue(this.action); @@ -126,47 +173,4 @@ public class S44PacketWorldBorder implements Packet { } } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleWorldBorder(this); - } - - public void func_179788_a(WorldBorder border) { - switch (this.action) { - case SET_SIZE: - border.setTransition(this.targetSize); - break; - case LERP_SIZE: - border.setTransition(this.diameter, this.targetSize, this.timeUntilTarget); - break; - case SET_CENTER: - border.setCenter(this.centerX, this.centerZ); - break; - case SET_WARNING_BLOCKS: - border.setWarningDistance(this.warningDistance); - break; - case SET_WARNING_TIME: - border.setWarningTime(this.warningTime); - break; - case INITIALIZE: - border.setCenter(this.centerX, this.centerZ); - if (this.timeUntilTarget > 0L) { - border.setTransition(this.diameter, this.targetSize, this.timeUntilTarget); - } else { - border.setTransition(this.targetSize); - } - - border.setSize(this.size); - border.setWarningDistance(this.warningDistance); - border.setWarningTime(this.warningTime); - } - - } - - public static enum Action { - SET_SIZE, LERP_SIZE, SET_CENTER, INITIALIZE, SET_WARNING_TIME, SET_WARNING_BLOCKS; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S45PacketTitle.java b/src/game/java/net/minecraft/network/play/server/S45PacketTitle.java index 555a95d4..4cc38d1e 100644 --- a/src/game/java/net/minecraft/network/play/server/S45PacketTitle.java +++ b/src/game/java/net/minecraft/network/play/server/S45PacketTitle.java @@ -7,114 +7,30 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class S45PacketTitle implements Packet { - private S45PacketTitle.Type type; - private IChatComponent message; - private int fadeInTime; - private int displayTime; - private int fadeOutTime; - - public S45PacketTitle() { - } - - public S45PacketTitle(S45PacketTitle.Type type, IChatComponent message) { - this(type, message, -1, -1, -1); - } - - public S45PacketTitle(int fadeInTime, int displayTime, int fadeOutTime) { - this(S45PacketTitle.Type.TIMES, (IChatComponent) null, fadeInTime, displayTime, fadeOutTime); - } - - public S45PacketTitle(S45PacketTitle.Type type, IChatComponent message, int fadeInTime, int displayTime, - int fadeOutTime) { - this.type = type; - this.message = message; - this.fadeInTime = fadeInTime; - this.displayTime = displayTime; - this.fadeOutTime = fadeOutTime; - } - - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.type = (S45PacketTitle.Type) parPacketBuffer.readEnumValue(S45PacketTitle.Type.class); - if (this.type == S45PacketTitle.Type.TITLE || this.type == S45PacketTitle.Type.SUBTITLE) { - this.message = parPacketBuffer.readChatComponent(); - } - - if (this.type == S45PacketTitle.Type.TIMES) { - this.fadeInTime = parPacketBuffer.readInt(); - this.displayTime = parPacketBuffer.readInt(); - this.fadeOutTime = parPacketBuffer.readInt(); - } - - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeEnumValue(this.type); - if (this.type == S45PacketTitle.Type.TITLE || this.type == S45PacketTitle.Type.SUBTITLE) { - parPacketBuffer.writeChatComponent(this.message); - } - - if (this.type == S45PacketTitle.Type.TIMES) { - parPacketBuffer.writeInt(this.fadeInTime); - parPacketBuffer.writeInt(this.displayTime); - parPacketBuffer.writeInt(this.fadeOutTime); - } - - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleTitle(this); - } - - public S45PacketTitle.Type getType() { - return this.type; - } - - public IChatComponent getMessage() { - return this.message; - } - - public int getFadeInTime() { - return this.fadeInTime; - } - - public int getDisplayTime() { - return this.displayTime; - } - - public int getFadeOutTime() { - return this.fadeOutTime; - } - public static enum Type { TITLE, SUBTITLE, TIMES, CLEAR, RESET; @@ -141,4 +57,92 @@ public class S45PacketTitle implements Packet { return astring; } } + + private S45PacketTitle.Type type; + private IChatComponent message; + private int fadeInTime; + private int displayTime; + + private int fadeOutTime; + + public S45PacketTitle() { + } + + public S45PacketTitle(int fadeInTime, int displayTime, int fadeOutTime) { + this(S45PacketTitle.Type.TIMES, (IChatComponent) null, fadeInTime, displayTime, fadeOutTime); + } + + public S45PacketTitle(S45PacketTitle.Type type, IChatComponent message) { + this(type, message, -1, -1, -1); + } + + public S45PacketTitle(S45PacketTitle.Type type, IChatComponent message, int fadeInTime, int displayTime, + int fadeOutTime) { + this.type = type; + this.message = message; + this.fadeInTime = fadeInTime; + this.displayTime = displayTime; + this.fadeOutTime = fadeOutTime; + } + + public int getDisplayTime() { + return this.displayTime; + } + + public int getFadeInTime() { + return this.fadeInTime; + } + + public int getFadeOutTime() { + return this.fadeOutTime; + } + + public IChatComponent getMessage() { + return this.message; + } + + public S45PacketTitle.Type getType() { + return this.type; + } + + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleTitle(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.type = (S45PacketTitle.Type) parPacketBuffer.readEnumValue(S45PacketTitle.Type.class); + if (this.type == S45PacketTitle.Type.TITLE || this.type == S45PacketTitle.Type.SUBTITLE) { + this.message = parPacketBuffer.readChatComponent(); + } + + if (this.type == S45PacketTitle.Type.TIMES) { + this.fadeInTime = parPacketBuffer.readInt(); + this.displayTime = parPacketBuffer.readInt(); + this.fadeOutTime = parPacketBuffer.readInt(); + } + + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeEnumValue(this.type); + if (this.type == S45PacketTitle.Type.TITLE || this.type == S45PacketTitle.Type.SUBTITLE) { + parPacketBuffer.writeChatComponent(this.message); + } + + if (this.type == S45PacketTitle.Type.TIMES) { + parPacketBuffer.writeInt(this.fadeInTime); + parPacketBuffer.writeInt(this.displayTime); + parPacketBuffer.writeInt(this.fadeOutTime); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S46PacketSetCompressionLevel.java b/src/game/java/net/minecraft/network/play/server/S46PacketSetCompressionLevel.java index a3847287..3802d88d 100644 --- a/src/game/java/net/minecraft/network/play/server/S46PacketSetCompressionLevel.java +++ b/src/game/java/net/minecraft/network/play/server/S46PacketSetCompressionLevel.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,28 +32,28 @@ import net.minecraft.network.play.INetHandlerPlayClient; public class S46PacketSetCompressionLevel implements Packet { private int field_179761_a; - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.field_179761_a = parPacketBuffer.readVarIntFromBuffer(); + public int func_179760_a() { + return this.field_179761_a; } - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.field_179761_a); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. + /** + * + Passes this Packet on to the NetHandler for processing. */ public void processPacket(INetHandlerPlayClient inethandlerplayclient) { inethandlerplayclient.handleSetCompressionLevel(this); } - public int func_179760_a() { - return this.field_179761_a; + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.field_179761_a = parPacketBuffer.readVarIntFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.field_179761_a); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S47PacketPlayerListHeaderFooter.java b/src/game/java/net/minecraft/network/play/server/S47PacketPlayerListHeaderFooter.java index ba5e307b..b23bbdb5 100644 --- a/src/game/java/net/minecraft/network/play/server/S47PacketPlayerListHeaderFooter.java +++ b/src/game/java/net/minecraft/network/play/server/S47PacketPlayerListHeaderFooter.java @@ -7,22 +7,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,34 +41,34 @@ public class S47PacketPlayerListHeaderFooter implements Packet } } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.url = parPacketBuffer.readStringFromBuffer(32767); - this.hash = parPacketBuffer.readStringFromBuffer(40); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeString(this.url); - parPacketBuffer.writeString(this.hash); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleResourcePack(this); + public String getHash() { + return this.hash; } public String getURL() { return this.url; } - public String getHash() { - return this.hash; + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleResourcePack(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.url = parPacketBuffer.readStringFromBuffer(32767); + this.hash = parPacketBuffer.readStringFromBuffer(40); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeString(this.url); + parPacketBuffer.writeString(this.hash); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/network/play/server/S49PacketUpdateEntityNBT.java b/src/game/java/net/minecraft/network/play/server/S49PacketUpdateEntityNBT.java index 41790729..1deba491 100644 --- a/src/game/java/net/minecraft/network/play/server/S49PacketUpdateEntityNBT.java +++ b/src/game/java/net/minecraft/network/play/server/S49PacketUpdateEntityNBT.java @@ -9,22 +9,25 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,34 +44,34 @@ public class S49PacketUpdateEntityNBT implements Packet { this.tagCompound = tagCompoundIn; } - /**+ - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { - this.entityId = parPacketBuffer.readVarIntFromBuffer(); - this.tagCompound = parPacketBuffer.readNBTTagCompoundFromBuffer(); - } - - /**+ - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { - parPacketBuffer.writeVarIntToBuffer(this.entityId); - parPacketBuffer.writeNBTTagCompoundToBuffer(this.tagCompound); - } - - /**+ - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(INetHandlerPlayClient inethandlerplayclient) { - inethandlerplayclient.handleEntityNBT(this); + public Entity getEntity(World worldIn) { + return worldIn.getEntityByID(this.entityId); } public NBTTagCompound getTagCompound() { return this.tagCompound; } - public Entity getEntity(World worldIn) { - return worldIn.getEntityByID(this.entityId); + /** + * + Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(INetHandlerPlayClient inethandlerplayclient) { + inethandlerplayclient.handleEntityNBT(this); + } + + /** + * + Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer parPacketBuffer) throws IOException { + this.entityId = parPacketBuffer.readVarIntFromBuffer(); + this.tagCompound = parPacketBuffer.readNBTTagCompoundFromBuffer(); + } + + /** + * + Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer parPacketBuffer) throws IOException { + parPacketBuffer.writeVarIntToBuffer(this.entityId); + parPacketBuffer.writeNBTTagCompoundToBuffer(this.tagCompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/Path.java b/src/game/java/net/minecraft/pathfinding/Path.java index 4fd4578d..8ec75ed6 100644 --- a/src/game/java/net/minecraft/pathfinding/Path.java +++ b/src/game/java/net/minecraft/pathfinding/Path.java @@ -1,34 +1,37 @@ package net.minecraft.pathfinding; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Path { - /**+ - * Contains the points in this path + /** + * + Contains the points in this path */ private PathPoint[] pathPoints = new PathPoint[1024]; private int count; - /**+ - * Adds a point to the path + /** + * + Adds a point to the path */ public PathPoint addPoint(PathPoint point) { if (point.index >= 0) { @@ -47,15 +50,29 @@ public class Path { } } - /**+ - * Clears the path + /** + * + Changes the provided point's distance to target + */ + public void changeDistance(PathPoint parPathPoint, float parFloat1) { + float f = parPathPoint.distanceToTarget; + parPathPoint.distanceToTarget = parFloat1; + if (parFloat1 < f) { + this.sortBack(parPathPoint.index); + } else { + this.sortForward(parPathPoint.index); + } + + } + + /** + * + Clears the path */ public void clearPath() { this.count = 0; } - /**+ - * Returns and removes the first point in the path + /** + * + Returns and removes the first point in the path */ public PathPoint dequeue() { PathPoint pathpoint = this.pathPoints[0]; @@ -69,22 +86,15 @@ public class Path { return pathpoint; } - /**+ - * Changes the provided point's distance to target + /** + * + Returns true if this path contains no points */ - public void changeDistance(PathPoint parPathPoint, float parFloat1) { - float f = parPathPoint.distanceToTarget; - parPathPoint.distanceToTarget = parFloat1; - if (parFloat1 < f) { - this.sortBack(parPathPoint.index); - } else { - this.sortForward(parPathPoint.index); - } - + public boolean isPathEmpty() { + return this.count == 0; } - /**+ - * Sorts a point to the left + /** + * + Sorts a point to the left */ private void sortBack(int parInt1) { PathPoint pathpoint = this.pathPoints[parInt1]; @@ -105,8 +115,8 @@ public class Path { pathpoint.index = parInt1; } - /**+ - * Sorts a point to the right + /** + * + Sorts a point to the right */ private void sortForward(int parInt1) { PathPoint pathpoint = this.pathPoints[parInt1]; @@ -153,11 +163,4 @@ public class Path { this.pathPoints[parInt1] = pathpoint; pathpoint.index = parInt1; } - - /**+ - * Returns true if this path contains no points - */ - public boolean isPathEmpty() { - return this.count == 0; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathEntity.java b/src/game/java/net/minecraft/pathfinding/PathEntity.java index 8ec43602..d4e99e2d 100644 --- a/src/game/java/net/minecraft/pathfinding/PathEntity.java +++ b/src/game/java/net/minecraft/pathfinding/PathEntity.java @@ -3,22 +3,25 @@ package net.minecraft.pathfinding; import net.minecraft.entity.Entity; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,54 +36,38 @@ public class PathEntity { this.pathLength = pathpoints.length; } - /**+ - * Directs this path to the next point in its array - */ - public void incrementPathIndex() { - ++this.currentPathIndex; - } - - /**+ - * Returns true if this path has reached the end - */ - public boolean isFinished() { - return this.currentPathIndex >= this.pathLength; - } - - /**+ - * returns the last PathPoint of the Array - */ - public PathPoint getFinalPathPoint() { - return this.pathLength > 0 ? this.points[this.pathLength - 1] : null; - } - - /**+ - * return the PathPoint located at the specified PathIndex, - * usually the current one - */ - public PathPoint getPathPointFromIndex(int index) { - return this.points[index]; + public int getCurrentPathIndex() { + return this.currentPathIndex; } public int getCurrentPathLength() { return this.pathLength; } - public void setCurrentPathLength(int length) { - this.pathLength = length; + /** + * + returns the last PathPoint of the Array + */ + public PathPoint getFinalPathPoint() { + return this.pathLength > 0 ? this.points[this.pathLength - 1] : null; } - public int getCurrentPathIndex() { - return this.currentPathIndex; + /** + * + return the PathPoint located at the specified PathIndex, usually the + * current one + */ + public PathPoint getPathPointFromIndex(int index) { + return this.points[index]; } - public void setCurrentPathIndex(int currentPathIndexIn) { - this.currentPathIndex = currentPathIndexIn; + /** + * + returns the current PathEntity target node as Vec3D + */ + public Vec3 getPosition(Entity entityIn) { + return this.getVectorFromIndex(entityIn, this.currentPathIndex); } - /**+ - * Gets the vector of the PathPoint associated with the given - * index. + /** + * + Gets the vector of the PathPoint associated with the given index. */ public Vec3 getVectorFromIndex(Entity entityIn, int index) { double d0 = (double) this.points[index].xCoord + (double) ((int) (entityIn.width + 1.0F)) * 0.5D; @@ -89,16 +76,31 @@ public class PathEntity { return new Vec3(d0, d1, d2); } - /**+ - * returns the current PathEntity target node as Vec3D + /** + * + Directs this path to the next point in its array */ - public Vec3 getPosition(Entity entityIn) { - return this.getVectorFromIndex(entityIn, this.currentPathIndex); + public void incrementPathIndex() { + ++this.currentPathIndex; } - /**+ - * Returns true if the EntityPath are the same. Non instance - * related equals. + /** + * + Returns true if the final PathPoint in the PathEntity is equal to Vec3D + * coords. + */ + public boolean isDestinationSame(Vec3 vec) { + PathPoint pathpoint = this.getFinalPathPoint(); + return pathpoint == null ? false : pathpoint.xCoord == (int) vec.xCoord && pathpoint.zCoord == (int) vec.zCoord; + } + + /** + * + Returns true if this path has reached the end + */ + public boolean isFinished() { + return this.currentPathIndex >= this.pathLength; + } + + /** + * + Returns true if the EntityPath are the same. Non instance related equals. */ public boolean isSamePath(PathEntity pathentityIn) { if (pathentityIn == null) { @@ -118,12 +120,11 @@ public class PathEntity { } } - /**+ - * Returns true if the final PathPoint in the PathEntity is - * equal to Vec3D coords. - */ - public boolean isDestinationSame(Vec3 vec) { - PathPoint pathpoint = this.getFinalPathPoint(); - return pathpoint == null ? false : pathpoint.xCoord == (int) vec.xCoord && pathpoint.zCoord == (int) vec.zCoord; + public void setCurrentPathIndex(int currentPathIndexIn) { + this.currentPathIndex = currentPathIndexIn; + } + + public void setCurrentPathLength(int length) { + this.pathLength = length; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathFinder.java b/src/game/java/net/minecraft/pathfinding/PathFinder.java index 20d07b80..2cc7bc0d 100644 --- a/src/game/java/net/minecraft/pathfinding/PathFinder.java +++ b/src/game/java/net/minecraft/pathfinding/PathFinder.java @@ -5,33 +5,36 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.pathfinder.NodeProcessor; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PathFinder { - /**+ - * The path being generated + /** + * + The path being generated */ private Path path = new Path(); - /**+ - * Selection of path points to add to the path + /** + * + Selection of path points to add to the path */ private PathPoint[] pathOptions = new PathPoint[32]; private NodeProcessor nodeProcessor; @@ -40,41 +43,8 @@ public class PathFinder { this.nodeProcessor = nodeProcessorIn; } - /**+ - * Internal implementation of creating a path from an entity to - * a point - */ - public PathEntity createEntityPathTo(IBlockAccess blockaccess, Entity entityFrom, Entity entityTo, float dist) { - return this.createEntityPathTo(blockaccess, entityFrom, entityTo.posX, entityTo.getEntityBoundingBox().minY, - entityTo.posZ, dist); - } - - /**+ - * Internal implementation of creating a path from an entity to - * a point - */ - public PathEntity createEntityPathTo(IBlockAccess blockaccess, Entity entityIn, BlockPos targetPos, float dist) { - return this.createEntityPathTo(blockaccess, entityIn, (double) ((float) targetPos.getX() + 0.5F), - (double) ((float) targetPos.getY() + 0.5F), (double) ((float) targetPos.getZ() + 0.5F), dist); - } - - /**+ - * Internal implementation of creating a path from an entity to - * a point - */ - private PathEntity createEntityPathTo(IBlockAccess blockaccess, Entity entityIn, double x, double y, double z, - float distance) { - this.path.clearPath(); - this.nodeProcessor.initProcessor(blockaccess, entityIn); - PathPoint pathpoint = this.nodeProcessor.getPathPointTo(entityIn); - PathPoint pathpoint1 = this.nodeProcessor.getPathPointToCoords(entityIn, x, y, z); - PathEntity pathentity = this.addToPath(entityIn, pathpoint, pathpoint1, distance); - this.nodeProcessor.postProcess(); - return pathentity; - } - - /**+ - * Adds a path from start to end and returns the whole path + /** + * + Adds a path from start to end and returns the whole path */ private PathEntity addToPath(Entity entityIn, PathPoint pathpointStart, PathPoint pathpointEnd, float maxDistance) { pathpointStart.totalPathDistance = 0.0F; @@ -122,8 +92,8 @@ public class PathFinder { } } - /**+ - * Returns a new PathEntity for a given start and end point + /** + * + Returns a new PathEntity for a given start and end point */ private PathEntity createEntityPath(PathPoint start, PathPoint end) { int i = 1; @@ -143,4 +113,34 @@ public class PathFinder { return new PathEntity(apathpoint); } + + /** + * + Internal implementation of creating a path from an entity to a point + */ + public PathEntity createEntityPathTo(IBlockAccess blockaccess, Entity entityIn, BlockPos targetPos, float dist) { + return this.createEntityPathTo(blockaccess, entityIn, (double) ((float) targetPos.getX() + 0.5F), + (double) ((float) targetPos.getY() + 0.5F), (double) ((float) targetPos.getZ() + 0.5F), dist); + } + + /** + * + Internal implementation of creating a path from an entity to a point + */ + private PathEntity createEntityPathTo(IBlockAccess blockaccess, Entity entityIn, double x, double y, double z, + float distance) { + this.path.clearPath(); + this.nodeProcessor.initProcessor(blockaccess, entityIn); + PathPoint pathpoint = this.nodeProcessor.getPathPointTo(entityIn); + PathPoint pathpoint1 = this.nodeProcessor.getPathPointToCoords(entityIn, x, y, z); + PathEntity pathentity = this.addToPath(entityIn, pathpoint, pathpoint1, distance); + this.nodeProcessor.postProcess(); + return pathentity; + } + + /** + * + Internal implementation of creating a path from an entity to a point + */ + public PathEntity createEntityPathTo(IBlockAccess blockaccess, Entity entityFrom, Entity entityTo, float dist) { + return this.createEntityPathTo(blockaccess, entityFrom, entityTo.posX, entityTo.getEntityBoundingBox().minY, + entityTo.posZ, dist); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathNavigate.java b/src/game/java/net/minecraft/pathfinding/PathNavigate.java index 900a4f8b..6d15ed05 100644 --- a/src/game/java/net/minecraft/pathfinding/PathNavigate.java +++ b/src/game/java/net/minecraft/pathfinding/PathNavigate.java @@ -1,6 +1,7 @@ package net.minecraft.pathfinding; import java.util.List; + import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.SharedMonsterAttributes; @@ -12,22 +13,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.ChunkCache; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,9 +44,9 @@ public abstract class PathNavigate { private final IAttributeInstance pathSearchRange; private int totalTicks; private int ticksAtLastPos; - /**+ - * Coordinates of the entity's position last time a check was - * done (part of monitoring getting 'stuck') + /** + * + Coordinates of the entity's position last time a check was done (part of + * monitoring getting 'stuck') */ private Vec3 lastPosCheck = new Vec3(0.0D, 0.0D, 0.0D); private float heightRequirement = 1.0F; @@ -55,65 +59,51 @@ public abstract class PathNavigate { this.pathFinder = this.getPathFinder(); } - protected abstract PathFinder getPathFinder(); + protected abstract boolean canNavigate(); - /**+ - * Sets the speed + /** + * + Checks if entity haven't been moved when last checked and if so, clears + * current {@link net.minecraft.pathfinding.PathEntity} */ - public void setSpeed(double speedIn) { - this.speed = speedIn; + protected void checkForStuck(Vec3 positionVec3) { + if (this.totalTicks - this.ticksAtLastPos > 100) { + if (positionVec3.squareDistanceTo(this.lastPosCheck) < 2.25D) { + this.clearPathEntity(); + } + + this.ticksAtLastPos = this.totalTicks; + this.lastPosCheck = positionVec3; + } + } - /**+ - * Gets the maximum distance that the path finding will search - * in. + /** + * + sets active PathEntity to null + */ + public void clearPathEntity() { + this.currentPath = null; + } + + protected abstract Vec3 getEntityPosition(); + + /** + * + gets the actively used PathEntity + */ + public PathEntity getPath() { + return this.currentPath; + } + + protected abstract PathFinder getPathFinder(); + + /** + * + Gets the maximum distance that the path finding will search in. */ public float getPathSearchRange() { return (float) this.pathSearchRange.getAttributeValue(); } - /**+ - * Returns the path to the given coordinates. Args : x, y, z - */ - public final PathEntity getPathToXYZ(double x, double y, double z) { - return this.getPathToPos(new BlockPos(MathHelper.floor_double(x), (int) y, MathHelper.floor_double(z))); - } - - /**+ - * Returns path to given BlockPos - */ - public PathEntity getPathToPos(BlockPos pos) { - if (!this.canNavigate()) { - return null; - } else { - float f = this.getPathSearchRange(); - BlockPos blockpos = new BlockPos(this.theEntity); - int i = (int) (f + 8.0F); - ChunkCache chunkcache = new ChunkCache(this.worldObj, blockpos.add(-i, -i, -i), blockpos.add(i, i, i), 0); - PathEntity pathentity = this.pathFinder.createEntityPathTo(chunkcache, this.theEntity, (BlockPos) pos, f); - return pathentity; - } - } - - /**+ - * Try to find and set a path to XYZ. Returns true if - * successful. Args : x, y, z, speed - */ - public boolean tryMoveToXYZ(double x, double y, double z, double speedIn) { - PathEntity pathentity = this.getPathToXYZ((double) MathHelper.floor_double(x), (double) ((int) y), - (double) MathHelper.floor_double(z)); - return this.setPath(pathentity, speedIn); - } - - /**+ - * Sets vertical space requirement for path - */ - public void setHeightRequirement(float jumpHeight) { - this.heightRequirement = jumpHeight; - } - - /**+ - * Returns the path to the given EntityLiving. Args : entity + /** + * + Returns the path to the given EntityLiving. Args : entity */ public PathEntity getPathToEntityLiving(Entity entityIn) { if (!this.canNavigate()) { @@ -129,47 +119,43 @@ public abstract class PathNavigate { } } - /**+ - * Try to find and set a path to EntityLiving. Returns true if - * successful. Args : entity, speed + /** + * + Returns path to given BlockPos */ - public boolean tryMoveToEntityLiving(Entity entityIn, double speedIn) { - PathEntity pathentity = this.getPathToEntityLiving(entityIn); - return pathentity != null ? this.setPath(pathentity, speedIn) : false; - } - - /**+ - * Sets a new path. If it's diferent from the old path. Checks - * to adjust path for sun avoiding, and stores start coords. - * Args : path, speed - */ - public boolean setPath(PathEntity pathentityIn, double speedIn) { - if (pathentityIn == null) { - this.currentPath = null; - return false; + public PathEntity getPathToPos(BlockPos pos) { + if (!this.canNavigate()) { + return null; } else { - if (!pathentityIn.isSamePath(this.currentPath)) { - this.currentPath = pathentityIn; - } - - this.removeSunnyPath(); - if (this.currentPath.getCurrentPathLength() == 0) { - return false; - } else { - this.speed = speedIn; - Vec3 vec3 = this.getEntityPosition(); - this.ticksAtLastPos = this.totalTicks; - this.lastPosCheck = vec3; - return true; - } + float f = this.getPathSearchRange(); + BlockPos blockpos = new BlockPos(this.theEntity); + int i = (int) (f + 8.0F); + ChunkCache chunkcache = new ChunkCache(this.worldObj, blockpos.add(-i, -i, -i), blockpos.add(i, i, i), 0); + PathEntity pathentity = this.pathFinder.createEntityPathTo(chunkcache, this.theEntity, (BlockPos) pos, f); + return pathentity; } } - /**+ - * gets the actively used PathEntity + /** + * + Returns the path to the given coordinates. Args : x, y, z */ - public PathEntity getPath() { - return this.currentPath; + public final PathEntity getPathToXYZ(double x, double y, double z) { + return this.getPathToPos(new BlockPos(MathHelper.floor_double(x), (int) y, MathHelper.floor_double(z))); + } + + protected abstract boolean isDirectPathBetweenPoints(Vec3 var1, Vec3 var2, int var3, int var4, int var5); + + /** + * + Returns true if the entity is in water or lava, false otherwise + */ + protected boolean isInLiquid() { + return this.theEntity.isInWater() || this.theEntity.isInLava(); + } + + /** + * + If null path or reached the end + */ + public boolean noPath() { + return this.currentPath == null || this.currentPath.isFinished(); } public void onUpdateNavigation() { @@ -245,54 +231,68 @@ public abstract class PathNavigate { this.checkForStuck(vec3); } - /**+ - * Checks if entity haven't been moved when last checked and if - * so, clears current {@link - * net.minecraft.pathfinding.PathEntity} - */ - protected void checkForStuck(Vec3 positionVec3) { - if (this.totalTicks - this.ticksAtLastPos > 100) { - if (positionVec3.squareDistanceTo(this.lastPosCheck) < 2.25D) { - this.clearPathEntity(); - } - - this.ticksAtLastPos = this.totalTicks; - this.lastPosCheck = positionVec3; - } - - } - - /**+ - * If null path or reached the end - */ - public boolean noPath() { - return this.currentPath == null || this.currentPath.isFinished(); - } - - /**+ - * sets active PathEntity to null - */ - public void clearPathEntity() { - this.currentPath = null; - } - - protected abstract Vec3 getEntityPosition(); - - protected abstract boolean canNavigate(); - - /**+ - * Returns true if the entity is in water or lava, false - * otherwise - */ - protected boolean isInLiquid() { - return this.theEntity.isInWater() || this.theEntity.isInLava(); - } - - /**+ - * Trims path data from the end to the first sun covered block + /** + * + Trims path data from the end to the first sun covered block */ protected void removeSunnyPath() { } - protected abstract boolean isDirectPathBetweenPoints(Vec3 var1, Vec3 var2, int var3, int var4, int var5); + /** + * + Sets vertical space requirement for path + */ + public void setHeightRequirement(float jumpHeight) { + this.heightRequirement = jumpHeight; + } + + /** + * + Sets a new path. If it's diferent from the old path. Checks to adjust path + * for sun avoiding, and stores start coords. Args : path, speed + */ + public boolean setPath(PathEntity pathentityIn, double speedIn) { + if (pathentityIn == null) { + this.currentPath = null; + return false; + } else { + if (!pathentityIn.isSamePath(this.currentPath)) { + this.currentPath = pathentityIn; + } + + this.removeSunnyPath(); + if (this.currentPath.getCurrentPathLength() == 0) { + return false; + } else { + this.speed = speedIn; + Vec3 vec3 = this.getEntityPosition(); + this.ticksAtLastPos = this.totalTicks; + this.lastPosCheck = vec3; + return true; + } + } + } + + /** + * + Sets the speed + */ + public void setSpeed(double speedIn) { + this.speed = speedIn; + } + + /** + * + Try to find and set a path to EntityLiving. Returns true if successful. + * Args : entity, speed + */ + public boolean tryMoveToEntityLiving(Entity entityIn, double speedIn) { + PathEntity pathentity = this.getPathToEntityLiving(entityIn); + return pathentity != null ? this.setPath(pathentity, speedIn) : false; + } + + /** + * + Try to find and set a path to XYZ. Returns true if successful. Args : x, y, + * z, speed + */ + public boolean tryMoveToXYZ(double x, double y, double z, double speedIn) { + PathEntity pathentity = this.getPathToXYZ((double) MathHelper.floor_double(x), (double) ((int) y), + (double) MathHelper.floor_double(z)); + return this.setPath(pathentity, speedIn); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathNavigateClimber.java b/src/game/java/net/minecraft/pathfinding/PathNavigateClimber.java index 59dead7d..144d43cd 100644 --- a/src/game/java/net/minecraft/pathfinding/PathNavigateClimber.java +++ b/src/game/java/net/minecraft/pathfinding/PathNavigateClimber.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,35 +36,20 @@ public class PathNavigateClimber extends PathNavigateGround { super(entityLivingIn, worldIn); } - /**+ - * Returns path to given BlockPos - */ - public PathEntity getPathToPos(BlockPos blockpos) { - this.targetPosition = blockpos; - return super.getPathToPos(blockpos); - } - - /**+ - * Returns the path to the given EntityLiving. Args : entity + /** + * + Returns the path to the given EntityLiving. Args : entity */ public PathEntity getPathToEntityLiving(Entity entity) { this.targetPosition = new BlockPos(entity); return super.getPathToEntityLiving(entity); } - /**+ - * Try to find and set a path to EntityLiving. Returns true if - * successful. Args : entity, speed + /** + * + Returns path to given BlockPos */ - public boolean tryMoveToEntityLiving(Entity entity, double d0) { - PathEntity pathentity = this.getPathToEntityLiving(entity); - if (pathentity != null) { - return this.setPath(pathentity, d0); - } else { - this.targetPosition = new BlockPos(entity); - this.speed = d0; - return true; - } + public PathEntity getPathToPos(BlockPos blockpos) { + this.targetPosition = blockpos; + return super.getPathToPos(blockpos); } public void onUpdateNavigation() { @@ -84,4 +72,19 @@ public class PathNavigateClimber extends PathNavigateGround { } } + + /** + * + Try to find and set a path to EntityLiving. Returns true if successful. + * Args : entity, speed + */ + public boolean tryMoveToEntityLiving(Entity entity, double d0) { + PathEntity pathentity = this.getPathToEntityLiving(entity); + if (pathentity != null) { + return this.setPath(pathentity, d0); + } else { + this.targetPosition = new BlockPos(entity); + this.speed = d0; + return true; + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathNavigateGround.java b/src/game/java/net/minecraft/pathfinding/PathNavigateGround.java index 2805a5d7..3510765f 100644 --- a/src/game/java/net/minecraft/pathfinding/PathNavigateGround.java +++ b/src/game/java/net/minecraft/pathfinding/PathNavigateGround.java @@ -12,22 +12,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.pathfinder.WalkNodeProcessor; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,27 +43,33 @@ public class PathNavigateGround extends PathNavigate { super(entitylivingIn, worldIn); } - protected PathFinder getPathFinder() { - this.nodeProcessor = new WalkNodeProcessor(); - this.nodeProcessor.setEnterDoors(true); - return new PathFinder(this.nodeProcessor); - } - - /**+ - * If on ground or swimming and can swim + /** + * + If on ground or swimming and can swim */ protected boolean canNavigate() { return this.theEntity.onGround || this.getCanSwim() && this.isInLiquid() || this.theEntity.isRiding() && this.theEntity instanceof EntityZombie && this.theEntity.ridingEntity instanceof EntityChicken; } + public boolean getAvoidsWater() { + return this.nodeProcessor.getAvoidsWater(); + } + + public boolean getCanSwim() { + return this.nodeProcessor.getCanSwim(); + } + + public boolean getEnterDoors() { + return this.nodeProcessor.getEnterDoors(); + } + protected Vec3 getEntityPosition() { return new Vec3(this.theEntity.posX, (double) this.getPathablePosY(), this.theEntity.posZ); } - /**+ - * Gets the safe pathing Y position for the entity depending on - * if it can path swim or not + /** + * + Gets the safe pathing Y position for the entity depending on if it can path + * swim or not */ private int getPathablePosY() { if (this.theEntity.isInWater() && this.getCanSwim()) { @@ -85,33 +94,16 @@ public class PathNavigateGround extends PathNavigate { } } - /**+ - * Trims path data from the end to the first sun covered block - */ - protected void removeSunnyPath() { - super.removeSunnyPath(); - if (this.shouldAvoidSun) { - if (this.worldObj.canSeeSky(new BlockPos(MathHelper.floor_double(this.theEntity.posX), - (int) (this.theEntity.getEntityBoundingBox().minY + 0.5D), - MathHelper.floor_double(this.theEntity.posZ)))) { - return; - } - - for (int i = 0; i < this.currentPath.getCurrentPathLength(); ++i) { - PathPoint pathpoint = this.currentPath.getPathPointFromIndex(i); - if (this.worldObj.canSeeSky(new BlockPos(pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord))) { - this.currentPath.setCurrentPathLength(i - 1); - return; - } - } - } - + protected PathFinder getPathFinder() { + this.nodeProcessor = new WalkNodeProcessor(); + this.nodeProcessor.setEnterDoors(true); + return new PathFinder(this.nodeProcessor); } - /**+ - * Returns true when an entity of specified size could safely - * walk in a straight line between the two points. Args: pos1, - * pos2, entityXSize, entityYSize, entityZSize + /** + * + Returns true when an entity of specified size could safely walk in a + * straight line between the two points. Args: pos1, pos2, entityXSize, + * entityYSize, entityZSize */ protected boolean isDirectPathBetweenPoints(Vec3 posVec31, Vec3 posVec32, int sizeX, int sizeY, int sizeZ) { int i = MathHelper.floor_double(posVec31.xCoord); @@ -174,9 +166,30 @@ public class PathNavigateGround extends PathNavigate { } } - /**+ - * Returns true when an entity could stand at a position, - * including solid blocks under the entire entity. + /** + * + Returns true if an entity does not collide with any solid blocks at the + * position. + */ + private boolean isPositionClear(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, + Vec3 parVec3_1, double parDouble1, double parDouble2) { + for (BlockPos blockpos : BlockPos.getAllInBox(new BlockPos(parInt1, parInt2, parInt3), + new BlockPos(parInt1 + parInt4 - 1, parInt2 + parInt5 - 1, parInt3 + parInt6 - 1))) { + double d0 = (double) blockpos.getX() + 0.5D - parVec3_1.xCoord; + double d1 = (double) blockpos.getZ() + 0.5D - parVec3_1.zCoord; + if (d0 * parDouble1 + d1 * parDouble2 >= 0.0D) { + Block block = this.worldObj.getBlockState(blockpos).getBlock(); + if (!block.isPassable(this.worldObj, blockpos)) { + return false; + } + } + } + + return true; + } + + /** + * + Returns true when an entity could stand at a position, including solid + * blocks under the entire entity. */ private boolean isSafeToStandAt(int x, int y, int z, int sizeX, int sizeY, int sizeZ, Vec3 vec31, double parDouble1, double parDouble2) { @@ -211,56 +224,46 @@ public class PathNavigateGround extends PathNavigate { } } - /**+ - * Returns true if an entity does not collide with any solid - * blocks at the position. + /** + * + Trims path data from the end to the first sun covered block */ - private boolean isPositionClear(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, - Vec3 parVec3_1, double parDouble1, double parDouble2) { - for (BlockPos blockpos : BlockPos.getAllInBox(new BlockPos(parInt1, parInt2, parInt3), - new BlockPos(parInt1 + parInt4 - 1, parInt2 + parInt5 - 1, parInt3 + parInt6 - 1))) { - double d0 = (double) blockpos.getX() + 0.5D - parVec3_1.xCoord; - double d1 = (double) blockpos.getZ() + 0.5D - parVec3_1.zCoord; - if (d0 * parDouble1 + d1 * parDouble2 >= 0.0D) { - Block block = this.worldObj.getBlockState(blockpos).getBlock(); - if (!block.isPassable(this.worldObj, blockpos)) { - return false; + protected void removeSunnyPath() { + super.removeSunnyPath(); + if (this.shouldAvoidSun) { + if (this.worldObj.canSeeSky(new BlockPos(MathHelper.floor_double(this.theEntity.posX), + (int) (this.theEntity.getEntityBoundingBox().minY + 0.5D), + MathHelper.floor_double(this.theEntity.posZ)))) { + return; + } + + for (int i = 0; i < this.currentPath.getCurrentPathLength(); ++i) { + PathPoint pathpoint = this.currentPath.getPathPointFromIndex(i); + if (this.worldObj.canSeeSky(new BlockPos(pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord))) { + this.currentPath.setCurrentPathLength(i - 1); + return; } } } - return true; + } + + public void setAvoidSun(boolean par1) { + this.shouldAvoidSun = par1; } public void setAvoidsWater(boolean avoidsWater) { this.nodeProcessor.setAvoidsWater(avoidsWater); } - public boolean getAvoidsWater() { - return this.nodeProcessor.getAvoidsWater(); - } - public void setBreakDoors(boolean canBreakDoors) { this.nodeProcessor.setBreakDoors(canBreakDoors); } - public void setEnterDoors(boolean par1) { - this.nodeProcessor.setEnterDoors(par1); - } - - public boolean getEnterDoors() { - return this.nodeProcessor.getEnterDoors(); - } - public void setCanSwim(boolean canSwim) { this.nodeProcessor.setCanSwim(canSwim); } - public boolean getCanSwim() { - return this.nodeProcessor.getCanSwim(); - } - - public void setAvoidSun(boolean par1) { - this.shouldAvoidSun = par1; + public void setEnterDoors(boolean par1) { + this.nodeProcessor.setEnterDoors(par1); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathNavigateSwimmer.java b/src/game/java/net/minecraft/pathfinding/PathNavigateSwimmer.java index 7ac96980..535b62db 100644 --- a/src/game/java/net/minecraft/pathfinding/PathNavigateSwimmer.java +++ b/src/game/java/net/minecraft/pathfinding/PathNavigateSwimmer.java @@ -6,22 +6,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.World; import net.minecraft.world.pathfinder.SwimNodeProcessor; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,12 +34,8 @@ public class PathNavigateSwimmer extends PathNavigate { super(entitylivingIn, worldIn); } - protected PathFinder getPathFinder() { - return new PathFinder(new SwimNodeProcessor()); - } - - /**+ - * If on ground or swimming and can swim + /** + * + If on ground or swimming and can swim */ protected boolean canNavigate() { return this.isInLiquid(); @@ -47,6 +46,23 @@ public class PathNavigateSwimmer extends PathNavigate { this.theEntity.posZ); } + protected PathFinder getPathFinder() { + return new PathFinder(new SwimNodeProcessor()); + } + + /** + * + Returns true when an entity of specified size could safely walk in a + * straight line between the two points. Args: pos1, pos2, entityXSize, + * entityYSize, entityZSize + */ + protected boolean isDirectPathBetweenPoints(Vec3 vec3, Vec3 vec31, int var3, int var4, int var5) { + MovingObjectPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec3, + new Vec3(vec31.xCoord, vec31.yCoord + (double) this.theEntity.height * 0.5D, vec31.zCoord), false, true, + false); + return movingobjectposition == null + || movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.MISS; + } + protected void pathFollow() { Vec3 vec3 = this.getEntityPosition(); float f = this.theEntity.width * this.theEntity.width; @@ -68,23 +84,10 @@ public class PathNavigateSwimmer extends PathNavigate { this.checkForStuck(vec3); } - /**+ - * Trims path data from the end to the first sun covered block + /** + * + Trims path data from the end to the first sun covered block */ protected void removeSunnyPath() { super.removeSunnyPath(); } - - /**+ - * Returns true when an entity of specified size could safely - * walk in a straight line between the two points. Args: pos1, - * pos2, entityXSize, entityYSize, entityZSize - */ - protected boolean isDirectPathBetweenPoints(Vec3 vec3, Vec3 vec31, int var3, int var4, int var5) { - MovingObjectPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec3, - new Vec3(vec31.xCoord, vec31.yCoord + (double) this.theEntity.height * 0.5D, vec31.zCoord), false, true, - false); - return movingobjectposition == null - || movingobjectposition.typeOfHit == MovingObjectPosition.MovingObjectType.MISS; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/pathfinding/PathPoint.java b/src/game/java/net/minecraft/pathfinding/PathPoint.java index 14887633..9479cccc 100644 --- a/src/game/java/net/minecraft/pathfinding/PathPoint.java +++ b/src/game/java/net/minecraft/pathfinding/PathPoint.java @@ -2,27 +2,35 @@ package net.minecraft.pathfinding; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PathPoint { + public static int makeHash(int x, int y, int z) { + return y & 255 | (x & 32767) << 8 | (z & 32767) << 24 | (x < 0 ? Integer.MIN_VALUE : 0) + | (z < 0 ? '\u8000' : 0); + } + public final int xCoord; public final int yCoord; public final int zCoord; @@ -32,6 +40,7 @@ public class PathPoint { float distanceToNext; float distanceToTarget; PathPoint previous; + public boolean visited; public PathPoint(int x, int y, int z) { @@ -41,13 +50,8 @@ public class PathPoint { this.hash = makeHash(x, y, z); } - public static int makeHash(int x, int y, int z) { - return y & 255 | (x & 32767) << 8 | (z & 32767) << 24 | (x < 0 ? Integer.MIN_VALUE : 0) - | (z < 0 ? '\u8000' : 0); - } - - /**+ - * Returns the linear distance to another path point + /** + * + Returns the linear distance to another path point */ public float distanceTo(PathPoint pathpointIn) { float f = (float) (pathpointIn.xCoord - this.xCoord); @@ -56,8 +60,8 @@ public class PathPoint { return MathHelper.sqrt_float(f * f + f1 * f1 + f2 * f2); } - /**+ - * Returns the squared distance to another path point + /** + * + Returns the squared distance to another path point */ public float distanceToSquared(PathPoint pathpointIn) { float f = (float) (pathpointIn.xCoord - this.xCoord); @@ -80,9 +84,8 @@ public class PathPoint { return this.hash; } - /**+ - * Returns true if this point has already been assigned to a - * path + /** + * + Returns true if this point has already been assigned to a path */ public boolean isAssigned() { return this.index >= 0; diff --git a/src/game/java/net/minecraft/potion/Potion.java b/src/game/java/net/minecraft/potion/Potion.java index f714d754..b1d183c7 100644 --- a/src/game/java/net/minecraft/potion/Potion.java +++ b/src/game/java/net/minecraft/potion/Potion.java @@ -3,10 +3,10 @@ package net.minecraft.potion; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import com.google.common.collect.Maps; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; @@ -19,29 +19,32 @@ import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Potion { - /**+ - * The array of potion types. + /** + * + The array of potion types. */ public static final Potion[] potionTypes = new Potion[32]; private static final Map field_180150_I = Maps.newHashMap(); @@ -69,72 +72,72 @@ public class Potion { .setPotionName("potion.jump").setIconIndex(2, 1); public static final Potion confusion = (new Potion(9, new ResourceLocation("nausea"), true, 5578058)) .setPotionName("potion.confusion").setIconIndex(3, 1).setEffectiveness(0.25D); - /**+ - * The regeneration Potion object. + /** + * + The regeneration Potion object. */ public static final Potion regeneration = (new Potion(10, new ResourceLocation("regeneration"), false, 13458603)) .setPotionName("potion.regeneration").setIconIndex(7, 0).setEffectiveness(0.25D); public static final Potion resistance = (new Potion(11, new ResourceLocation("resistance"), false, 10044730)) .setPotionName("potion.resistance").setIconIndex(6, 1); - /**+ - * The fire resistance Potion object. + /** + * + The fire resistance Potion object. */ public static final Potion fireResistance = (new Potion(12, new ResourceLocation("fire_resistance"), false, 14981690)).setPotionName("potion.fireResistance").setIconIndex(7, 1); - /**+ - * The water breathing Potion object. + /** + * + The water breathing Potion object. */ public static final Potion waterBreathing = (new Potion(13, new ResourceLocation("water_breathing"), false, 3035801)).setPotionName("potion.waterBreathing").setIconIndex(0, 2); - /**+ - * The invisibility Potion object. + /** + * + The invisibility Potion object. */ public static final Potion invisibility = (new Potion(14, new ResourceLocation("invisibility"), false, 8356754)) .setPotionName("potion.invisibility").setIconIndex(0, 1); - /**+ - * The blindness Potion object. + /** + * + The blindness Potion object. */ public static final Potion blindness = (new Potion(15, new ResourceLocation("blindness"), true, 2039587)) .setPotionName("potion.blindness").setIconIndex(5, 1).setEffectiveness(0.25D); - /**+ - * The night vision Potion object. + /** + * + The night vision Potion object. */ public static final Potion nightVision = (new Potion(16, new ResourceLocation("night_vision"), false, 2039713)) .setPotionName("potion.nightVision").setIconIndex(4, 1); - /**+ - * The hunger Potion object. + /** + * + The hunger Potion object. */ public static final Potion hunger = (new Potion(17, new ResourceLocation("hunger"), true, 5797459)) .setPotionName("potion.hunger").setIconIndex(1, 1); - /**+ - * The weakness Potion object. + /** + * + The weakness Potion object. */ public static final Potion weakness = (new PotionAttackDamage(18, new ResourceLocation("weakness"), true, 4738376)) .setPotionName("potion.weakness").setIconIndex(5, 0).registerPotionAttributeModifier( SharedMonsterAttributes.attackDamage, "22653B89-116E-49DC-9B6B-9971489B5BE5", 2.0D, 0); - /**+ - * The poison Potion object. + /** + * + The poison Potion object. */ public static final Potion poison = (new Potion(19, new ResourceLocation("poison"), true, 5149489)) .setPotionName("potion.poison").setIconIndex(6, 0).setEffectiveness(0.25D); - /**+ - * The wither Potion object. + /** + * + The wither Potion object. */ public static final Potion wither = (new Potion(20, new ResourceLocation("wither"), true, 3484199)) .setPotionName("potion.wither").setIconIndex(1, 2).setEffectiveness(0.25D); - /**+ - * The health boost Potion object. + /** + * + The health boost Potion object. */ public static final Potion healthBoost = (new PotionHealthBoost(21, new ResourceLocation("health_boost"), false, 16284963)).setPotionName("potion.healthBoost").setIconIndex(2, 2).registerPotionAttributeModifier( SharedMonsterAttributes.maxHealth, "5D6F0BA2-1186-46AC-B896-C61C5CEE99CC", 4.0D, 0); - /**+ - * The absorption Potion object. + /** + * + The absorption Potion object. */ public static final Potion absorption = (new PotionAbsorption(22, new ResourceLocation("absorption"), false, 2445989)).setPotionName("potion.absorption").setIconIndex(2, 2); - /**+ - * The saturation Potion object. + /** + * + The saturation Potion object. */ public static final Potion saturation = (new PotionHealth(23, new ResourceLocation("saturation"), false, 16262179)) .setPotionName("potion.saturation"); @@ -146,20 +149,40 @@ public class Potion { public static final Potion field_180144_E = null; public static final Potion field_180145_F = null; public static final Potion field_180146_G = null; + + public static Set func_181168_c() { + return field_180150_I.keySet(); + } + + public static String getDurationString(PotionEffect effect) { + if (effect.getIsPotionDurationMax()) { + return "**:**"; + } else { + int i = effect.getDuration(); + return StringUtils.ticksToElapsedTime(i); + } + } + + public static Potion getPotionFromResourceLocation(String location) { + return (Potion) field_180150_I.get(new ResourceLocation(location)); + } + public final int id; private final Map attributeModifierMap = Maps.newHashMap(); private final boolean isBadEffect; private final int liquidColor; - /**+ - * The name of the Potion. + /** + * + The name of the Potion. */ private String name = ""; - /**+ - * The index for the icon displayed when the potion effect is - * active. + + /** + * + The index for the icon displayed when the potion effect is active. */ private int statusIconIndex = -1; + private double effectiveness; + private boolean usable; protected Potion(int potionID, ResourceLocation location, boolean badEffect, int potionColor) { @@ -176,30 +199,127 @@ public class Potion { this.liquidColor = potionColor; } - public static Potion getPotionFromResourceLocation(String location) { - return (Potion) field_180150_I.get(new ResourceLocation(location)); + public void affectEntity(Entity entityLivingBaseIn, Entity parEntity2, EntityLivingBase parEntityLivingBase, + int parInt1, double parDouble1) { + if ((this.id != heal.id || parEntityLivingBase.isEntityUndead()) + && (this.id != harm.id || !parEntityLivingBase.isEntityUndead())) { + if (this.id == harm.id && !parEntityLivingBase.isEntityUndead() + || this.id == heal.id && parEntityLivingBase.isEntityUndead()) { + int j = (int) (parDouble1 * (double) (6 << parInt1) + 0.5D); + if (entityLivingBaseIn == null) { + parEntityLivingBase.attackEntityFrom(DamageSource.magic, (float) j); + } else { + parEntityLivingBase.attackEntityFrom( + DamageSource.causeIndirectMagicDamage(entityLivingBaseIn, parEntity2), (float) j); + } + } + } else { + int i = (int) (parDouble1 * (double) (4 << parInt1) + 0.5D); + parEntityLivingBase.heal((float) i); + } + } - public static Set func_181168_c() { - return field_180150_I.keySet(); + public void applyAttributesModifiersToEntity(EntityLivingBase var1, BaseAttributeMap baseattributemap, int i) { + for (Entry entry : this.attributeModifierMap.entrySet()) { + IAttributeInstance iattributeinstance = baseattributemap.getAttributeInstance((IAttribute) entry.getKey()); + if (iattributeinstance != null) { + AttributeModifier attributemodifier = (AttributeModifier) entry.getValue(); + iattributeinstance.removeModifier(attributemodifier); + iattributeinstance.applyModifier(new AttributeModifier(attributemodifier.getID(), + this.getName() + " " + i, this.getAttributeModifierAmount(i, attributemodifier), + attributemodifier.getOperation())); + } + } + } - /**+ - * Sets the index for the icon displayed in the player's - * inventory when the status is active. - */ - protected Potion setIconIndex(int parInt1, int parInt2) { - this.statusIconIndex = parInt1 + parInt2 * 8; - return this; + public double getAttributeModifierAmount(int i, AttributeModifier attributemodifier) { + return attributemodifier.getAmount() * (double) (i + 1); } - /**+ - * returns the ID of the potion + public Map getAttributeModifierMap() { + return this.attributeModifierMap; + } + + public double getEffectiveness() { + return this.effectiveness; + } + + /** + * + returns the ID of the potion */ public int getId() { return this.id; } + /** + * + Returns the color of the potion liquid. + */ + public int getLiquidColor() { + return this.liquidColor; + } + + /** + * + returns the name of the potion + */ + public String getName() { + return this.name; + } + + /** + * + Returns the index for the icon to display when the potion is active. + */ + public int getStatusIconIndex() { + return this.statusIconIndex; + } + + /** + * + Returns true if the potion has a associated status icon to display in then + * inventory when active. + */ + public boolean hasStatusIcon() { + return this.statusIconIndex >= 0; + } + + /** + * + This method returns true if the potion effect is bad - negative - for the + * entity. + */ + public boolean isBadEffect() { + return this.isBadEffect; + } + + /** + * + Returns true if the potion has an instant effect instead of a continuous + * one (eg Harming) + */ + public boolean isInstant() { + return false; + } + + /** + * + checks if Potion effect is ready to be applied this tick. + */ + public boolean isReady(int i, int j) { + if (this.id == regeneration.id) { + int i1 = 50 >> j; + return i1 > 0 ? i % i1 == 0 : true; + } else if (this.id == poison.id) { + int l = 25 >> j; + return l > 0 ? i % l == 0 : true; + } else if (this.id == wither.id) { + int k = 40 >> j; + return k > 0 ? i % k == 0 : true; + } else { + return this.id == hunger.id; + } + } + + public boolean isUsable() { + return this.usable; + } + public void performEffect(EntityLivingBase entityLivingBaseIn, int parInt1) { if (this.id == regeneration.id) { if (entityLivingBaseIn.getHealth() < entityLivingBaseIn.getMaxHealth()) { @@ -229,123 +349,8 @@ public class Potion { } - public void affectEntity(Entity entityLivingBaseIn, Entity parEntity2, EntityLivingBase parEntityLivingBase, - int parInt1, double parDouble1) { - if ((this.id != heal.id || parEntityLivingBase.isEntityUndead()) - && (this.id != harm.id || !parEntityLivingBase.isEntityUndead())) { - if (this.id == harm.id && !parEntityLivingBase.isEntityUndead() - || this.id == heal.id && parEntityLivingBase.isEntityUndead()) { - int j = (int) (parDouble1 * (double) (6 << parInt1) + 0.5D); - if (entityLivingBaseIn == null) { - parEntityLivingBase.attackEntityFrom(DamageSource.magic, (float) j); - } else { - parEntityLivingBase.attackEntityFrom( - DamageSource.causeIndirectMagicDamage(entityLivingBaseIn, parEntity2), (float) j); - } - } - } else { - int i = (int) (parDouble1 * (double) (4 << parInt1) + 0.5D); - parEntityLivingBase.heal((float) i); - } - - } - - /**+ - * Returns true if the potion has an instant effect instead of a - * continuous one (eg Harming) - */ - public boolean isInstant() { - return false; - } - - /**+ - * checks if Potion effect is ready to be applied this tick. - */ - public boolean isReady(int i, int j) { - if (this.id == regeneration.id) { - int i1 = 50 >> j; - return i1 > 0 ? i % i1 == 0 : true; - } else if (this.id == poison.id) { - int l = 25 >> j; - return l > 0 ? i % l == 0 : true; - } else if (this.id == wither.id) { - int k = 40 >> j; - return k > 0 ? i % k == 0 : true; - } else { - return this.id == hunger.id; - } - } - - /**+ - * Set the potion name. - */ - public Potion setPotionName(String nameIn) { - this.name = nameIn; - return this; - } - - /**+ - * returns the name of the potion - */ - public String getName() { - return this.name; - } - - /**+ - * Returns true if the potion has a associated status icon to - * display in then inventory when active. - */ - public boolean hasStatusIcon() { - return this.statusIconIndex >= 0; - } - - /**+ - * Returns the index for the icon to display when the potion is - * active. - */ - public int getStatusIconIndex() { - return this.statusIconIndex; - } - - /**+ - * This method returns true if the potion effect is bad - - * negative - for the entity. - */ - public boolean isBadEffect() { - return this.isBadEffect; - } - - public static String getDurationString(PotionEffect effect) { - if (effect.getIsPotionDurationMax()) { - return "**:**"; - } else { - int i = effect.getDuration(); - return StringUtils.ticksToElapsedTime(i); - } - } - - protected Potion setEffectiveness(double effectivenessIn) { - this.effectiveness = effectivenessIn; - return this; - } - - public double getEffectiveness() { - return this.effectiveness; - } - - public boolean isUsable() { - return this.usable; - } - - /**+ - * Returns the color of the potion liquid. - */ - public int getLiquidColor() { - return this.liquidColor; - } - - /**+ - * Used by potions to register the attribute they modify. + /** + * + Used by potions to register the attribute they modify. */ public Potion registerPotionAttributeModifier(IAttribute parIAttribute, String parString1, double parDouble1, int parInt1) { @@ -355,10 +360,6 @@ public class Potion { return this; } - public Map getAttributeModifierMap() { - return this.attributeModifierMap; - } - public void removeAttributesModifiersFromEntity(EntityLivingBase var1, BaseAttributeMap baseattributemap, int var3) { for (Entry entry : this.attributeModifierMap.entrySet()) { @@ -370,21 +371,25 @@ public class Potion { } - public void applyAttributesModifiersToEntity(EntityLivingBase var1, BaseAttributeMap baseattributemap, int i) { - for (Entry entry : this.attributeModifierMap.entrySet()) { - IAttributeInstance iattributeinstance = baseattributemap.getAttributeInstance((IAttribute) entry.getKey()); - if (iattributeinstance != null) { - AttributeModifier attributemodifier = (AttributeModifier) entry.getValue(); - iattributeinstance.removeModifier(attributemodifier); - iattributeinstance.applyModifier(new AttributeModifier(attributemodifier.getID(), - this.getName() + " " + i, this.getAttributeModifierAmount(i, attributemodifier), - attributemodifier.getOperation())); - } - } - + protected Potion setEffectiveness(double effectivenessIn) { + this.effectiveness = effectivenessIn; + return this; } - public double getAttributeModifierAmount(int i, AttributeModifier attributemodifier) { - return attributemodifier.getAmount() * (double) (i + 1); + /** + * + Sets the index for the icon displayed in the player's inventory when the + * status is active. + */ + protected Potion setIconIndex(int parInt1, int parInt2) { + this.statusIconIndex = parInt1 + parInt2 * 8; + return this; + } + + /** + * + Set the potion name. + */ + public Potion setPotionName(String nameIn) { + this.name = nameIn; + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/potion/PotionAbsorption.java b/src/game/java/net/minecraft/potion/PotionAbsorption.java index 81060fe5..e393e577 100644 --- a/src/game/java/net/minecraft/potion/PotionAbsorption.java +++ b/src/game/java/net/minecraft/potion/PotionAbsorption.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.BaseAttributeMap; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,15 +32,15 @@ public class PotionAbsorption extends Potion { super(potionID, location, badEffect, potionColor); } - public void removeAttributesModifiersFromEntity(EntityLivingBase entityLivingBaseIn, BaseAttributeMap amplifier, - int parInt1) { - entityLivingBaseIn.setAbsorptionAmount(entityLivingBaseIn.getAbsorptionAmount() - (float) (4 * (parInt1 + 1))); - super.removeAttributesModifiersFromEntity(entityLivingBaseIn, amplifier, parInt1); - } - public void applyAttributesModifiersToEntity(EntityLivingBase entityLivingBaseIn, BaseAttributeMap amplifier, int parInt1) { entityLivingBaseIn.setAbsorptionAmount(entityLivingBaseIn.getAbsorptionAmount() + (float) (4 * (parInt1 + 1))); super.applyAttributesModifiersToEntity(entityLivingBaseIn, amplifier, parInt1); } + + public void removeAttributesModifiersFromEntity(EntityLivingBase entityLivingBaseIn, BaseAttributeMap amplifier, + int parInt1) { + entityLivingBaseIn.setAbsorptionAmount(entityLivingBaseIn.getAbsorptionAmount() - (float) (4 * (parInt1 + 1))); + super.removeAttributesModifiersFromEntity(entityLivingBaseIn, amplifier, parInt1); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/potion/PotionAttackDamage.java b/src/game/java/net/minecraft/potion/PotionAttackDamage.java index 2002c96d..491345e3 100644 --- a/src/game/java/net/minecraft/potion/PotionAttackDamage.java +++ b/src/game/java/net/minecraft/potion/PotionAttackDamage.java @@ -3,22 +3,25 @@ package net.minecraft.potion; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/potion/PotionEffect.java b/src/game/java/net/minecraft/potion/PotionEffect.java index 2fb6ad67..c2217670 100644 --- a/src/game/java/net/minecraft/potion/PotionEffect.java +++ b/src/game/java/net/minecraft/potion/PotionEffect.java @@ -5,34 +5,59 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.EntityLivingBase; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PotionEffect { private static final Logger LOGGER = LogManager.getLogger(); + + /** + * + Read a custom potion effect from a potion item's NBT data. + */ + public static PotionEffect readCustomPotionEffectFromNBT(NBTTagCompound nbt) { + byte b0 = nbt.getByte("Id"); + if (b0 >= 0 && b0 < Potion.potionTypes.length && Potion.potionTypes[b0] != null) { + byte b1 = nbt.getByte("Amplifier"); + int i = nbt.getInteger("Duration"); + boolean flag = nbt.getBoolean("Ambient"); + boolean flag1 = true; + if (nbt.hasKey("ShowParticles", 1)) { + flag1 = nbt.getBoolean("ShowParticles"); + } + + return new PotionEffect(b0, i, b1, flag, flag1); + } else { + return null; + } + } + private int potionID; private int duration; private int amplifier; private boolean isSplashPotion; private boolean isAmbient; private boolean isPotionDurationMax; + private boolean showParticles; public PotionEffect(int id, int effectDuration) { @@ -59,10 +84,10 @@ public class PotionEffect { this.showParticles = other.showParticles; } - /**+ - * merges the input PotionEffect into this one if this.amplifier - * <= tomerge.amplifier. The duration in the supplied potion - * effect is assumed to be greater. + /** + * + merges the input PotionEffect into this one if this.amplifier <= + * tomerge.amplifier. The duration in the supplied potion effect is assumed to + * be greater. */ public void combine(PotionEffect other) { if (this.potionID != other.potionID) { @@ -81,39 +106,59 @@ public class PotionEffect { this.showParticles = other.showParticles; } - /**+ - * Retrieve the ID of the potion this effect matches. - */ - public int getPotionID() { - return this.potionID; + private int deincrementDuration() { + return --this.duration; } - public int getDuration() { - return this.duration; + public boolean equals(Object object) { + if (!(object instanceof PotionEffect)) { + return false; + } else { + PotionEffect potioneffect = (PotionEffect) object; + return this.potionID == potioneffect.potionID && this.amplifier == potioneffect.amplifier + && this.duration == potioneffect.duration && this.isSplashPotion == potioneffect.isSplashPotion + && this.isAmbient == potioneffect.isAmbient; + } } public int getAmplifier() { return this.amplifier; } - /**+ - * Set whether this potion is a splash potion. - */ - public void setSplashPotion(boolean splashPotion) { - this.isSplashPotion = splashPotion; + public int getDuration() { + return this.duration; } - /**+ - * Gets whether this potion effect originated from a beacon + public String getEffectName() { + return Potion.potionTypes[this.potionID].getName(); + } + + /** + * + Gets whether this potion effect originated from a beacon */ public boolean getIsAmbient() { return this.isAmbient; } + public boolean getIsPotionDurationMax() { + return this.isPotionDurationMax; + } + public boolean getIsShowParticles() { return this.showParticles; } + /** + * + Retrieve the ID of the potion this effect matches. + */ + public int getPotionID() { + return this.potionID; + } + + public int hashCode() { + return this.potionID; + } + public boolean onUpdate(EntityLivingBase entityIn) { if (this.duration > 0) { if (Potion.potionTypes[this.potionID].isReady(this.duration, this.amplifier)) { @@ -126,10 +171,6 @@ public class PotionEffect { return this.duration > 0; } - private int deincrementDuration() { - return --this.duration; - } - public void performEffect(EntityLivingBase entityIn) { if (this.duration > 0) { Potion.potionTypes[this.potionID].performEffect(entityIn, this.amplifier); @@ -137,12 +178,18 @@ public class PotionEffect { } - public String getEffectName() { - return Potion.potionTypes[this.potionID].getName(); + /** + * + Toggle the isPotionDurationMax field. + */ + public void setPotionDurationMax(boolean maxDuration) { + this.isPotionDurationMax = maxDuration; } - public int hashCode() { - return this.potionID; + /** + * + Set whether this potion is a splash potion. + */ + public void setSplashPotion(boolean splashPotion) { + this.isSplashPotion = splashPotion; } public String toString() { @@ -164,19 +211,8 @@ public class PotionEffect { return Potion.potionTypes[this.potionID].isUsable() ? "(" + s + ")" : s; } - public boolean equals(Object object) { - if (!(object instanceof PotionEffect)) { - return false; - } else { - PotionEffect potioneffect = (PotionEffect) object; - return this.potionID == potioneffect.potionID && this.amplifier == potioneffect.amplifier - && this.duration == potioneffect.duration && this.isSplashPotion == potioneffect.isSplashPotion - && this.isAmbient == potioneffect.isAmbient; - } - } - - /**+ - * Write a custom potion effect to a potion item's NBT data. + /** + * + Write a custom potion effect to a potion item's NBT data. */ public NBTTagCompound writeCustomPotionEffectToNBT(NBTTagCompound nbt) { nbt.setByte("Id", (byte) this.getPotionID()); @@ -186,35 +222,4 @@ public class PotionEffect { nbt.setBoolean("ShowParticles", this.getIsShowParticles()); return nbt; } - - /**+ - * Read a custom potion effect from a potion item's NBT data. - */ - public static PotionEffect readCustomPotionEffectFromNBT(NBTTagCompound nbt) { - byte b0 = nbt.getByte("Id"); - if (b0 >= 0 && b0 < Potion.potionTypes.length && Potion.potionTypes[b0] != null) { - byte b1 = nbt.getByte("Amplifier"); - int i = nbt.getInteger("Duration"); - boolean flag = nbt.getBoolean("Ambient"); - boolean flag1 = true; - if (nbt.hasKey("ShowParticles", 1)) { - flag1 = nbt.getBoolean("ShowParticles"); - } - - return new PotionEffect(b0, i, b1, flag, flag1); - } else { - return null; - } - } - - /**+ - * Toggle the isPotionDurationMax field. - */ - public void setPotionDurationMax(boolean maxDuration) { - this.isPotionDurationMax = maxDuration; - } - - public boolean getIsPotionDurationMax() { - return this.isPotionDurationMax; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/potion/PotionHealth.java b/src/game/java/net/minecraft/potion/PotionHealth.java index 0201411f..0e6640c7 100644 --- a/src/game/java/net/minecraft/potion/PotionHealth.java +++ b/src/game/java/net/minecraft/potion/PotionHealth.java @@ -2,22 +2,25 @@ package net.minecraft.potion; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,16 +30,16 @@ public class PotionHealth extends Potion { super(potionID, location, badEffect, potionColor); } - /**+ - * Returns true if the potion has an instant effect instead of a - * continuous one (eg Harming) + /** + * + Returns true if the potion has an instant effect instead of a continuous + * one (eg Harming) */ public boolean isInstant() { return true; } - /**+ - * checks if Potion effect is ready to be applied this tick. + /** + * + checks if Potion effect is ready to be applied this tick. */ public boolean isReady(int parInt1, int parInt2) { return parInt1 >= 1; diff --git a/src/game/java/net/minecraft/potion/PotionHealthBoost.java b/src/game/java/net/minecraft/potion/PotionHealthBoost.java index 1778ee34..50bf1b40 100644 --- a/src/game/java/net/minecraft/potion/PotionHealthBoost.java +++ b/src/game/java/net/minecraft/potion/PotionHealthBoost.java @@ -4,22 +4,25 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.BaseAttributeMap; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/potion/PotionHelper.java b/src/game/java/net/minecraft/potion/PotionHelper.java index ef786030..84d59fd8 100644 --- a/src/game/java/net/minecraft/potion/PotionHelper.java +++ b/src/game/java/net/minecraft/potion/PotionHelper.java @@ -10,22 +10,25 @@ import com.google.common.collect.Maps; import net.minecraft.util.IntegerCache; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,8 +51,8 @@ public class PotionHelper { private static final Map potionRequirements = Maps.newHashMap(); private static final Map potionAmplifiers = Maps.newHashMap(); private static final Map DATAVALUE_COLORS = Maps.newHashMap(); - /**+ - * An array of possible potion prefix names, as translation IDs. + /** + * + An array of possible potion prefix names, as translation IDs. */ private static final String[] potionPrefixes = new String[] { "potion.prefix.mundane", "potion.prefix.uninteresting", "potion.prefix.bland", "potion.prefix.clear", "potion.prefix.milky", @@ -61,43 +64,130 @@ public class PotionHelper { "potion.prefix.foul", "potion.prefix.odorless", "potion.prefix.rank", "potion.prefix.harsh", "potion.prefix.acrid", "potion.prefix.gross", "potion.prefix.stinky" }; - /**+ - * Checks if the bit at 1 << j is on in i. - */ - public static boolean checkFlag(int parInt1, int parInt2) { - return (parInt1 & 1 << parInt2) != 0; + static { + potionRequirements.put(Integer.valueOf(Potion.regeneration.getId()), "0 & !1 & !2 & !3 & 0+6"); + potionRequirements.put(Integer.valueOf(Potion.moveSpeed.getId()), "!0 & 1 & !2 & !3 & 1+6"); + potionRequirements.put(Integer.valueOf(Potion.fireResistance.getId()), "0 & 1 & !2 & !3 & 0+6"); + potionRequirements.put(Integer.valueOf(Potion.heal.getId()), "0 & !1 & 2 & !3"); + potionRequirements.put(Integer.valueOf(Potion.poison.getId()), "!0 & !1 & 2 & !3 & 2+6"); + potionRequirements.put(Integer.valueOf(Potion.weakness.getId()), "!0 & !1 & !2 & 3 & 3+6"); + potionRequirements.put(Integer.valueOf(Potion.harm.getId()), "!0 & !1 & 2 & 3"); + potionRequirements.put(Integer.valueOf(Potion.moveSlowdown.getId()), "!0 & 1 & !2 & 3 & 3+6"); + potionRequirements.put(Integer.valueOf(Potion.damageBoost.getId()), "0 & !1 & !2 & 3 & 3+6"); + potionRequirements.put(Integer.valueOf(Potion.nightVision.getId()), "!0 & 1 & 2 & !3 & 2+6"); + potionRequirements.put(Integer.valueOf(Potion.invisibility.getId()), "!0 & 1 & 2 & 3 & 2+6"); + potionRequirements.put(Integer.valueOf(Potion.waterBreathing.getId()), "0 & !1 & 2 & 3 & 2+6"); + potionRequirements.put(Integer.valueOf(Potion.jump.getId()), "0 & 1 & !2 & 3 & 3+6"); + potionAmplifiers.put(Integer.valueOf(Potion.moveSpeed.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.digSpeed.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.damageBoost.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.regeneration.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.harm.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.heal.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.resistance.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.poison.getId()), "5"); + potionAmplifiers.put(Integer.valueOf(Potion.jump.getId()), "5"); } - /**+ - * Returns 1 if the flag is set, 0 if it is not set. + /** + * + Returns the new potion damage value after the specified ingredient info is + * applied to the specified potion. */ - private static int isFlagSet(int parInt1, int parInt2) { - /**+ - * Checks if the bit at 1 << j is on in i. - */ - return checkFlag(parInt1, parInt2) ? 1 : 0; + public static int applyIngredient(int parInt1, String parString1) { + byte b0 = 0; + int i = parString1.length(); + boolean flag = false; + boolean flag1 = false; + boolean flag2 = false; + boolean flag3 = false; + int j = 0; + + for (int k = b0; k < i; ++k) { + char c0 = parString1.charAt(k); + if (c0 >= 48 && c0 <= 57) { + j = j * 10; + j = j + (c0 - 48); + flag = true; + } else if (c0 == 33) { + if (flag) { + parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + j = 0; + } + + flag1 = true; + } else if (c0 == 45) { + if (flag) { + parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + j = 0; + } + + flag2 = true; + } else if (c0 == 43) { + if (flag) { + parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + j = 0; + } + } else if (c0 == 38) { + if (flag) { + parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); + flag3 = false; + flag1 = false; + flag2 = false; + flag = false; + j = 0; + } + + flag3 = true; + } + } + + if (flag) { + parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); + } + + return parInt1 & 32767; } - /**+ - * Returns 0 if the flag is set, 1 if it is not set. + /** + * + Manipulates the specified bit of the potion damage value according to the + * rules passed from applyIngredient. */ - private static int isFlagUnset(int parInt1, int parInt2) { - /**+ - * Checks if the bit at 1 << j is on in i. - */ - return checkFlag(parInt1, parInt2) ? 0 : 1; + private static int brewBitOperations(int parInt1, int parInt2, boolean parFlag, boolean parFlag2, + boolean parFlag3) { + if (parFlag3) { + if (!checkFlag(parInt1, parInt2)) { + return 0; + } + } else if (parFlag) { + parInt1 &= ~(1 << parInt2); + } else if (parFlag2) { + if ((parInt1 & 1 << parInt2) == 0) { + parInt1 |= 1 << parInt2; + } else { + parInt1 &= ~(1 << parInt2); + } + } else { + parInt1 |= 1 << parInt2; + } + + return parInt1; } - /**+ - * Given a potion data value, get its prefix index number. - */ - public static int getPotionPrefixIndex(int dataValue) { - return func_77908_a(dataValue, 5, 4, 3, 2, 1); - } - - /**+ - * Given a {@link Collection}<{@link PotionEffect}> will return - * an Integer color. + /** + * + Given a {@link Collection}<{@link PotionEffect}> will return an Integer + * color. */ public static int calcPotionLiquidColor(Collection parCollection) { int i = 3694022; @@ -133,50 +223,23 @@ public class PotionHelper { } } - /**+ - * Check whether a {@link Collection}<{@link PotionEffect}> are - * all ambient. + /** + * + Checks if the bit at 1 << j is on in i. */ - public static boolean getAreAmbient(Collection potionEffects) { - for (PotionEffect potioneffect : potionEffects) { - if (!potioneffect.getIsAmbient()) { - return false; - } - } - - return true; + public static boolean checkFlag(int parInt1, int parInt2) { + return (parInt1 & 1 << parInt2) != 0; } - /**+ - * Given a potion data value, get the associated liquid color - * (optionally bypassing the cache) + /** + * + Returns the number of 1 bits in the given integer. */ - public static int getLiquidColor(int dataValue, boolean bypassCache) { - Integer integer = IntegerCache.func_181756_a(dataValue); - if (!bypassCache) { - if (DATAVALUE_COLORS.containsKey(integer)) { - return ((Integer) DATAVALUE_COLORS.get(integer)).intValue(); - } else { - int i = calcPotionLiquidColor(getPotionEffects(integer.intValue(), false)); - DATAVALUE_COLORS.put(integer, Integer.valueOf(i)); - return i; - } - } else { - /**+ - * Given a {@link Collection}<{@link PotionEffect}> will return - * an Integer color. - */ - return calcPotionLiquidColor(getPotionEffects(integer.intValue(), true)); + private static int countSetFlags(int parInt1) { + int i; + for (i = 0; parInt1 > 0; ++i) { + parInt1 &= parInt1 - 1; } - } - /**+ - * Given a potion data value, get its prefix as a translation - * ID. - */ - public static String getPotionPrefix(int dataValue) { - int i = getPotionPrefixIndex(dataValue); - return potionPrefixes[i]; + return i; } private static int func_77904_a(boolean parFlag, boolean parFlag2, boolean parFlag3, int parInt1, int parInt2, @@ -207,16 +270,132 @@ public class PotionHelper { return i; } - /**+ - * Returns the number of 1 bits in the given integer. + public static int func_77908_a(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6) { + return (checkFlag(parInt1, parInt2) ? 16 : 0) | (checkFlag(parInt1, parInt3) ? 8 : 0) + | (checkFlag(parInt1, parInt4) ? 4 : 0) | (checkFlag(parInt1, parInt5) ? 2 : 0) + | (checkFlag(parInt1, parInt6) ? 1 : 0); + } + + /** + * + Check whether a {@link Collection}<{@link PotionEffect}> are all ambient. */ - private static int countSetFlags(int parInt1) { - int i; - for (i = 0; parInt1 > 0; ++i) { - parInt1 &= parInt1 - 1; + public static boolean getAreAmbient(Collection potionEffects) { + for (PotionEffect potioneffect : potionEffects) { + if (!potioneffect.getIsAmbient()) { + return false; + } } - return i; + return true; + } + + /** + * + Given a potion data value, get the associated liquid color (optionally + * bypassing the cache) + */ + public static int getLiquidColor(int dataValue, boolean bypassCache) { + Integer integer = IntegerCache.func_181756_a(dataValue); + if (!bypassCache) { + if (DATAVALUE_COLORS.containsKey(integer)) { + return ((Integer) DATAVALUE_COLORS.get(integer)).intValue(); + } else { + int i = calcPotionLiquidColor(getPotionEffects(integer.intValue(), false)); + DATAVALUE_COLORS.put(integer, Integer.valueOf(i)); + return i; + } + } else { + /** + * + Given a {@link Collection}<{@link PotionEffect}> will return an Integer + * color. + */ + return calcPotionLiquidColor(getPotionEffects(integer.intValue(), true)); + } + } + + /** + * + Returns a list of effects for the specified potion damage value. + */ + public static List getPotionEffects(int parInt1, boolean parFlag) { + ArrayList arraylist = null; + + for (int k = 0; k < Potion.potionTypes.length; ++k) { + Potion potion = Potion.potionTypes[k]; + if (potion != null && (!potion.isUsable() || parFlag)) { + String s = (String) potionRequirements.get(Integer.valueOf(potion.getId())); + if (s != null) { + int i = parsePotionEffects(s, 0, s.length(), parInt1); + if (i > 0) { + int j = 0; + String s1 = (String) potionAmplifiers.get(Integer.valueOf(potion.getId())); + if (s1 != null) { + j = parsePotionEffects(s1, 0, s1.length(), parInt1); + if (j < 0) { + j = 0; + } + } + + if (potion.isInstant()) { + i = 1; + } else { + i = 1200 * (i * 3 + (i - 1) * 2); + i = i >> j; + i = (int) Math.round((double) i * potion.getEffectiveness()); + if ((parInt1 & 16384) != 0) { + i = (int) Math.round((double) i * 0.75D + 0.5D); + } + } + + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } + + PotionEffect potioneffect = new PotionEffect(potion.getId(), i, j); + if ((parInt1 & 16384) != 0) { + potioneffect.setSplashPotion(true); + } + + arraylist.add(potioneffect); + } + } + } + } + + return arraylist; + } + + /** + * + Given a potion data value, get its prefix as a translation ID. + */ + public static String getPotionPrefix(int dataValue) { + int i = getPotionPrefixIndex(dataValue); + return potionPrefixes[i]; + } + + /** + * + Given a potion data value, get its prefix index number. + */ + public static int getPotionPrefixIndex(int dataValue) { + return func_77908_a(dataValue, 5, 4, 3, 2, 1); + } + + /** + * + Returns 1 if the flag is set, 0 if it is not set. + */ + private static int isFlagSet(int parInt1, int parInt2) { + /** + * + Checks if the bit at 1 << j is on in i. + */ + return checkFlag(parInt1, parInt2) ? 1 : 0; + } + + /** + * + Returns 0 if the flag is set, 1 if it is not set. + */ + private static int isFlagUnset(int parInt1, int parInt2) { + /** + * + Checks if the bit at 1 << j is on in i. + */ + return checkFlag(parInt1, parInt2) ? 0 : 1; } private static int parsePotionEffects(String parString1, int parInt1, int parInt2, int parInt3) { @@ -338,183 +517,4 @@ public class PotionHelper { return 0; } } - - /**+ - * Returns a list of effects for the specified potion damage - * value. - */ - public static List getPotionEffects(int parInt1, boolean parFlag) { - ArrayList arraylist = null; - - for (int k = 0; k < Potion.potionTypes.length; ++k) { - Potion potion = Potion.potionTypes[k]; - if (potion != null && (!potion.isUsable() || parFlag)) { - String s = (String) potionRequirements.get(Integer.valueOf(potion.getId())); - if (s != null) { - int i = parsePotionEffects(s, 0, s.length(), parInt1); - if (i > 0) { - int j = 0; - String s1 = (String) potionAmplifiers.get(Integer.valueOf(potion.getId())); - if (s1 != null) { - j = parsePotionEffects(s1, 0, s1.length(), parInt1); - if (j < 0) { - j = 0; - } - } - - if (potion.isInstant()) { - i = 1; - } else { - i = 1200 * (i * 3 + (i - 1) * 2); - i = i >> j; - i = (int) Math.round((double) i * potion.getEffectiveness()); - if ((parInt1 & 16384) != 0) { - i = (int) Math.round((double) i * 0.75D + 0.5D); - } - } - - if (arraylist == null) { - arraylist = Lists.newArrayList(); - } - - PotionEffect potioneffect = new PotionEffect(potion.getId(), i, j); - if ((parInt1 & 16384) != 0) { - potioneffect.setSplashPotion(true); - } - - arraylist.add(potioneffect); - } - } - } - } - - return arraylist; - } - - /**+ - * Manipulates the specified bit of the potion damage value - * according to the rules passed from applyIngredient. - */ - private static int brewBitOperations(int parInt1, int parInt2, boolean parFlag, boolean parFlag2, - boolean parFlag3) { - if (parFlag3) { - if (!checkFlag(parInt1, parInt2)) { - return 0; - } - } else if (parFlag) { - parInt1 &= ~(1 << parInt2); - } else if (parFlag2) { - if ((parInt1 & 1 << parInt2) == 0) { - parInt1 |= 1 << parInt2; - } else { - parInt1 &= ~(1 << parInt2); - } - } else { - parInt1 |= 1 << parInt2; - } - - return parInt1; - } - - /**+ - * Returns the new potion damage value after the specified - * ingredient info is applied to the specified potion. - */ - public static int applyIngredient(int parInt1, String parString1) { - byte b0 = 0; - int i = parString1.length(); - boolean flag = false; - boolean flag1 = false; - boolean flag2 = false; - boolean flag3 = false; - int j = 0; - - for (int k = b0; k < i; ++k) { - char c0 = parString1.charAt(k); - if (c0 >= 48 && c0 <= 57) { - j = j * 10; - j = j + (c0 - 48); - flag = true; - } else if (c0 == 33) { - if (flag) { - parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); - flag3 = false; - flag1 = false; - flag2 = false; - flag = false; - j = 0; - } - - flag1 = true; - } else if (c0 == 45) { - if (flag) { - parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); - flag3 = false; - flag1 = false; - flag2 = false; - flag = false; - j = 0; - } - - flag2 = true; - } else if (c0 == 43) { - if (flag) { - parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); - flag3 = false; - flag1 = false; - flag2 = false; - flag = false; - j = 0; - } - } else if (c0 == 38) { - if (flag) { - parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); - flag3 = false; - flag1 = false; - flag2 = false; - flag = false; - j = 0; - } - - flag3 = true; - } - } - - if (flag) { - parInt1 = brewBitOperations(parInt1, j, flag2, flag1, flag3); - } - - return parInt1 & 32767; - } - - public static int func_77908_a(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6) { - return (checkFlag(parInt1, parInt2) ? 16 : 0) | (checkFlag(parInt1, parInt3) ? 8 : 0) - | (checkFlag(parInt1, parInt4) ? 4 : 0) | (checkFlag(parInt1, parInt5) ? 2 : 0) - | (checkFlag(parInt1, parInt6) ? 1 : 0); - } - - static { - potionRequirements.put(Integer.valueOf(Potion.regeneration.getId()), "0 & !1 & !2 & !3 & 0+6"); - potionRequirements.put(Integer.valueOf(Potion.moveSpeed.getId()), "!0 & 1 & !2 & !3 & 1+6"); - potionRequirements.put(Integer.valueOf(Potion.fireResistance.getId()), "0 & 1 & !2 & !3 & 0+6"); - potionRequirements.put(Integer.valueOf(Potion.heal.getId()), "0 & !1 & 2 & !3"); - potionRequirements.put(Integer.valueOf(Potion.poison.getId()), "!0 & !1 & 2 & !3 & 2+6"); - potionRequirements.put(Integer.valueOf(Potion.weakness.getId()), "!0 & !1 & !2 & 3 & 3+6"); - potionRequirements.put(Integer.valueOf(Potion.harm.getId()), "!0 & !1 & 2 & 3"); - potionRequirements.put(Integer.valueOf(Potion.moveSlowdown.getId()), "!0 & 1 & !2 & 3 & 3+6"); - potionRequirements.put(Integer.valueOf(Potion.damageBoost.getId()), "0 & !1 & !2 & 3 & 3+6"); - potionRequirements.put(Integer.valueOf(Potion.nightVision.getId()), "!0 & 1 & 2 & !3 & 2+6"); - potionRequirements.put(Integer.valueOf(Potion.invisibility.getId()), "!0 & 1 & 2 & 3 & 2+6"); - potionRequirements.put(Integer.valueOf(Potion.waterBreathing.getId()), "0 & !1 & 2 & 3 & 2+6"); - potionRequirements.put(Integer.valueOf(Potion.jump.getId()), "0 & 1 & !2 & 3 & 3+6"); - potionAmplifiers.put(Integer.valueOf(Potion.moveSpeed.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.digSpeed.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.damageBoost.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.regeneration.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.harm.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.heal.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.resistance.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.poison.getId()), "5"); - potionAmplifiers.put(Integer.valueOf(Potion.jump.getId()), "5"); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/GoalColor.java b/src/game/java/net/minecraft/scoreboard/GoalColor.java index ace2c903..2d14f356 100644 --- a/src/game/java/net/minecraft/scoreboard/GoalColor.java +++ b/src/game/java/net/minecraft/scoreboard/GoalColor.java @@ -5,22 +5,25 @@ import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,19 +36,19 @@ public class GoalColor implements IScoreObjectiveCriteria { IScoreObjectiveCriteria.INSTANCES.put(this.goalName, this); } - public String getName() { - return this.goalName; - } - public int func_96635_a(List parList) { return 0; } - public boolean isReadOnly() { - return false; + public String getName() { + return this.goalName; } public IScoreObjectiveCriteria.EnumRenderType getRenderType() { return IScoreObjectiveCriteria.EnumRenderType.INTEGER; } + + public boolean isReadOnly() { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/IScoreObjectiveCriteria.java b/src/game/java/net/minecraft/scoreboard/IScoreObjectiveCriteria.java index 3f42a8d0..ca74b6a8 100644 --- a/src/game/java/net/minecraft/scoreboard/IScoreObjectiveCriteria.java +++ b/src/game/java/net/minecraft/scoreboard/IScoreObjectiveCriteria.java @@ -8,27 +8,59 @@ import com.google.common.collect.Maps; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IScoreObjectiveCriteria { + public static enum EnumRenderType { + INTEGER("integer"), HEARTS("hearts"); + + private static final Map field_178801_c = Maps.newHashMap(); + static { + IScoreObjectiveCriteria.EnumRenderType[] types = values(); + for (int i = 0; i < types.length; ++i) { + field_178801_c.put(types[i].func_178796_a(), types[i]); + } + + } + + public static IScoreObjectiveCriteria.EnumRenderType func_178795_a(String parString1) { + IScoreObjectiveCriteria.EnumRenderType iscoreobjectivecriteria$enumrendertype = (IScoreObjectiveCriteria.EnumRenderType) field_178801_c + .get(parString1); + return iscoreobjectivecriteria$enumrendertype == null ? INTEGER : iscoreobjectivecriteria$enumrendertype; + } + + private final String field_178798_d; + + private EnumRenderType(String parString2) { + this.field_178798_d = parString2; + } + + public String func_178796_a() { + return this.field_178798_d; + } + } + Map INSTANCES = Maps.newHashMap(); IScoreObjectiveCriteria DUMMY = new ScoreDummyCriteria("dummy"); IScoreObjectiveCriteria TRIGGER = new ScoreDummyCriteria("trigger"); @@ -50,6 +82,7 @@ public interface IScoreObjectiveCriteria { new GoalColor("teamkill.", EnumChatFormatting.LIGHT_PURPLE), new GoalColor("teamkill.", EnumChatFormatting.YELLOW), new GoalColor("teamkill.", EnumChatFormatting.WHITE) }; + IScoreObjectiveCriteria[] field_178793_i = new IScoreObjectiveCriteria[] { new GoalColor("killedByTeam.", EnumChatFormatting.BLACK), new GoalColor("killedByTeam.", EnumChatFormatting.DARK_BLUE), @@ -68,40 +101,11 @@ public interface IScoreObjectiveCriteria { new GoalColor("killedByTeam.", EnumChatFormatting.YELLOW), new GoalColor("killedByTeam.", EnumChatFormatting.WHITE) }; - String getName(); - int func_96635_a(List var1); - boolean isReadOnly(); + String getName(); IScoreObjectiveCriteria.EnumRenderType getRenderType(); - public static enum EnumRenderType { - INTEGER("integer"), HEARTS("hearts"); - - private static final Map field_178801_c = Maps.newHashMap(); - private final String field_178798_d; - - private EnumRenderType(String parString2) { - this.field_178798_d = parString2; - } - - public String func_178796_a() { - return this.field_178798_d; - } - - public static IScoreObjectiveCriteria.EnumRenderType func_178795_a(String parString1) { - IScoreObjectiveCriteria.EnumRenderType iscoreobjectivecriteria$enumrendertype = (IScoreObjectiveCriteria.EnumRenderType) field_178801_c - .get(parString1); - return iscoreobjectivecriteria$enumrendertype == null ? INTEGER : iscoreobjectivecriteria$enumrendertype; - } - - static { - IScoreObjectiveCriteria.EnumRenderType[] types = values(); - for (int i = 0; i < types.length; ++i) { - field_178801_c.put(types[i].func_178796_a(), types[i]); - } - - } - } + boolean isReadOnly(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/Score.java b/src/game/java/net/minecraft/scoreboard/Score.java index 7a440707..3529382f 100644 --- a/src/game/java/net/minecraft/scoreboard/Score.java +++ b/src/game/java/net/minecraft/scoreboard/Score.java @@ -5,29 +5,32 @@ import java.util.List; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Score { - /**+ - * Used for sorting score by points + /** + * + Used for sorting score by points */ public static final Comparator scoreComparator = new Comparator() { public int compare(Score score, Score score1) { @@ -50,14 +53,6 @@ public class Score { this.field_178818_g = true; } - public void increseScore(int amount) { - if (this.theScoreObjective.getCriteria().isReadOnly()) { - throw new IllegalStateException("Cannot modify read-only score"); - } else { - this.setScorePoints(this.getScorePoints() + amount); - } - } - public void decreaseScore(int amount) { if (this.theScoreObjective.getCriteria().isReadOnly()) { throw new IllegalStateException("Cannot modify read-only score"); @@ -74,10 +69,45 @@ public class Score { } } + public void func_96651_a(List parList) { + this.setScorePoints(this.theScoreObjective.getCriteria().func_96635_a(parList)); + } + + public ScoreObjective getObjective() { + return this.theScoreObjective; + } + + /** + * + Returns the name of the player this score belongs to + */ + public String getPlayerName() { + return this.scorePlayerName; + } + public int getScorePoints() { return this.scorePoints; } + public Scoreboard getScoreScoreboard() { + return this.theScoreboard; + } + + public void increseScore(int amount) { + if (this.theScoreObjective.getCriteria().isReadOnly()) { + throw new IllegalStateException("Cannot modify read-only score"); + } else { + this.setScorePoints(this.getScorePoints() + amount); + } + } + + public boolean isLocked() { + return this.locked; + } + + public void setLocked(boolean locked) { + this.locked = locked; + } + public void setScorePoints(int points) { int i = this.scorePoints; this.scorePoints = points; @@ -87,31 +117,4 @@ public class Score { } } - - public ScoreObjective getObjective() { - return this.theScoreObjective; - } - - /**+ - * Returns the name of the player this score belongs to - */ - public String getPlayerName() { - return this.scorePlayerName; - } - - public Scoreboard getScoreScoreboard() { - return this.theScoreboard; - } - - public boolean isLocked() { - return this.locked; - } - - public void setLocked(boolean locked) { - this.locked = locked; - } - - public void func_96651_a(List parList) { - this.setScorePoints(this.theScoreObjective.getCriteria().func_96635_a(parList)); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/ScoreDummyCriteria.java b/src/game/java/net/minecraft/scoreboard/ScoreDummyCriteria.java index a7f83502..494d606e 100644 --- a/src/game/java/net/minecraft/scoreboard/ScoreDummyCriteria.java +++ b/src/game/java/net/minecraft/scoreboard/ScoreDummyCriteria.java @@ -4,22 +4,25 @@ import java.util.List; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,19 +35,19 @@ public class ScoreDummyCriteria implements IScoreObjectiveCriteria { IScoreObjectiveCriteria.INSTANCES.put(name, this); } - public String getName() { - return this.dummyName; - } - public int func_96635_a(List var1) { return 0; } - public boolean isReadOnly() { - return false; + public String getName() { + return this.dummyName; } public IScoreObjectiveCriteria.EnumRenderType getRenderType() { return IScoreObjectiveCriteria.EnumRenderType.INTEGER; } + + public boolean isReadOnly() { + return false; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/ScoreHealthCriteria.java b/src/game/java/net/minecraft/scoreboard/ScoreHealthCriteria.java index 5105241a..5427dbff 100644 --- a/src/game/java/net/minecraft/scoreboard/ScoreHealthCriteria.java +++ b/src/game/java/net/minecraft/scoreboard/ScoreHealthCriteria.java @@ -5,22 +5,25 @@ import java.util.List; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,11 +48,11 @@ public class ScoreHealthCriteria extends ScoreDummyCriteria { return MathHelper.ceiling_float_int(f); } - public boolean isReadOnly() { - return true; - } - public IScoreObjectiveCriteria.EnumRenderType getRenderType() { return IScoreObjectiveCriteria.EnumRenderType.HEARTS; } + + public boolean isReadOnly() { + return true; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/ScoreObjective.java b/src/game/java/net/minecraft/scoreboard/ScoreObjective.java index 1bc4f550..51be0521 100644 --- a/src/game/java/net/minecraft/scoreboard/ScoreObjective.java +++ b/src/game/java/net/minecraft/scoreboard/ScoreObjective.java @@ -3,22 +3,25 @@ package net.minecraft.scoreboard; import net.lax1dude.eaglercraft.v1_8.profanity_filter.ProfanityFilter; import net.minecraft.client.Minecraft; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,14 +42,6 @@ public class ScoreObjective { this.renderType = objectiveCriteriaIn.getRenderType(); } - public Scoreboard getScoreboard() { - return this.theScoreboard; - } - - public String getName() { - return this.name; - } - public IScoreObjectiveCriteria getCriteria() { return this.objectiveCriteria; } @@ -66,15 +61,23 @@ public class ScoreObjective { } } - public void setDisplayName(String nameIn) { - this.displayName = nameIn; - this.theScoreboard.func_96532_b(this); + public String getName() { + return this.name; } public IScoreObjectiveCriteria.EnumRenderType getRenderType() { return this.renderType; } + public Scoreboard getScoreboard() { + return this.theScoreboard; + } + + public void setDisplayName(String nameIn) { + this.displayName = nameIn; + this.theScoreboard.func_96532_b(this); + } + public void setRenderType(IScoreObjectiveCriteria.EnumRenderType type) { this.renderType = type; this.theScoreboard.func_96532_b(this); diff --git a/src/game/java/net/minecraft/scoreboard/ScorePlayerTeam.java b/src/game/java/net/minecraft/scoreboard/ScorePlayerTeam.java index 74f502cb..e9a94e76 100644 --- a/src/game/java/net/minecraft/scoreboard/ScorePlayerTeam.java +++ b/src/game/java/net/minecraft/scoreboard/ScorePlayerTeam.java @@ -7,31 +7,41 @@ import com.google.common.collect.Sets; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ScorePlayerTeam extends Team { + /** + * + Returns the player name including the color prefixes and suffixes + */ + public static String formatPlayerName(Team parTeam, String parString1) { + return parTeam == null ? parString1 : parTeam.formatString(parString1); + } + private final Scoreboard theScoreboard; private final String registeredName; - /**+ - * A set of all team member usernames. + /** + * + A set of all team member usernames. */ private final Set membershipSet = Sets.newHashSet(); private String teamNameSPT; @@ -41,6 +51,7 @@ public class ScorePlayerTeam extends Team { private boolean canSeeFriendlyInvisibles = true; private Team.EnumVisible nameTagVisibility = Team.EnumVisible.ALWAYS; private Team.EnumVisible deathMessageVisibility = Team.EnumVisible.ALWAYS; + private EnumChatFormatting chatFormat = EnumChatFormatting.RESET; public ScorePlayerTeam(Scoreboard theScoreboardIn, String name) { @@ -49,105 +60,13 @@ public class ScorePlayerTeam extends Team { this.teamNameSPT = name; } - /**+ - * Retrieve the name by which this team is registered in the - * scoreboard - */ - public String getRegisteredName() { - return this.registeredName; - } - - public String getTeamName() { - return this.teamNameSPT; - } - - public void setTeamName(String name) { - if (name == null) { - throw new IllegalArgumentException("Name cannot be null"); - } else { - this.teamNameSPT = name; - this.theScoreboard.sendTeamUpdate(this); - } - } - - public Collection getMembershipCollection() { - return this.membershipSet; - } - - /**+ - * Returns the color prefix for the player's team name - */ - public String getColorPrefix() { - return this.namePrefixSPT; - } - - public void setNamePrefix(String prefix) { - if (prefix == null) { - throw new IllegalArgumentException("Prefix cannot be null"); - } else { - this.namePrefixSPT = prefix; - this.theScoreboard.sendTeamUpdate(this); - } - } - - /**+ - * Returns the color suffix for the player's team name - */ - public String getColorSuffix() { - return this.colorSuffix; - } - - public void setNameSuffix(String suffix) { - this.colorSuffix = suffix; - this.theScoreboard.sendTeamUpdate(this); - } - public String formatString(String input) { return this.getColorPrefix() + input + this.getColorSuffix(); } - /**+ - * Returns the player name including the color prefixes and - * suffixes - */ - public static String formatPlayerName(Team parTeam, String parString1) { - return parTeam == null ? parString1 : parTeam.formatString(parString1); - } - - public boolean getAllowFriendlyFire() { - return this.allowFriendlyFire; - } - - public void setAllowFriendlyFire(boolean friendlyFire) { - this.allowFriendlyFire = friendlyFire; - this.theScoreboard.sendTeamUpdate(this); - } - - public boolean getSeeFriendlyInvisiblesEnabled() { - return this.canSeeFriendlyInvisibles; - } - - public void setSeeFriendlyInvisiblesEnabled(boolean friendlyInvisibles) { - this.canSeeFriendlyInvisibles = friendlyInvisibles; - this.theScoreboard.sendTeamUpdate(this); - } - - public Team.EnumVisible getNameTagVisibility() { - return this.nameTagVisibility; - } - - public Team.EnumVisible getDeathMessageVisibility() { - return this.deathMessageVisibility; - } - - public void setNameTagVisibility(Team.EnumVisible parEnumVisible) { - this.nameTagVisibility = parEnumVisible; - this.theScoreboard.sendTeamUpdate(this); - } - - public void setDeathMessageVisibility(Team.EnumVisible parEnumVisible) { - this.deathMessageVisibility = parEnumVisible; - this.theScoreboard.sendTeamUpdate(this); + public void func_98298_a(int parInt1) { + this.setAllowFriendlyFire((parInt1 & 1) > 0); + this.setSeeFriendlyInvisiblesEnabled((parInt1 & 2) > 0); } public int func_98299_i() { @@ -163,16 +82,99 @@ public class ScorePlayerTeam extends Team { return i; } - public void func_98298_a(int parInt1) { - this.setAllowFriendlyFire((parInt1 & 1) > 0); - this.setSeeFriendlyInvisiblesEnabled((parInt1 & 2) > 0); + public boolean getAllowFriendlyFire() { + return this.allowFriendlyFire; + } + + public EnumChatFormatting getChatFormat() { + return this.chatFormat; + } + + /** + * + Returns the color prefix for the player's team name + */ + public String getColorPrefix() { + return this.namePrefixSPT; + } + + /** + * + Returns the color suffix for the player's team name + */ + public String getColorSuffix() { + return this.colorSuffix; + } + + public Team.EnumVisible getDeathMessageVisibility() { + return this.deathMessageVisibility; + } + + public Collection getMembershipCollection() { + return this.membershipSet; + } + + public Team.EnumVisible getNameTagVisibility() { + return this.nameTagVisibility; + } + + /** + * + Retrieve the name by which this team is registered in the scoreboard + */ + public String getRegisteredName() { + return this.registeredName; + } + + public boolean getSeeFriendlyInvisiblesEnabled() { + return this.canSeeFriendlyInvisibles; + } + + public String getTeamName() { + return this.teamNameSPT; + } + + public void setAllowFriendlyFire(boolean friendlyFire) { + this.allowFriendlyFire = friendlyFire; + this.theScoreboard.sendTeamUpdate(this); } public void setChatFormat(EnumChatFormatting parEnumChatFormatting) { this.chatFormat = parEnumChatFormatting; } - public EnumChatFormatting getChatFormat() { - return this.chatFormat; + public void setDeathMessageVisibility(Team.EnumVisible parEnumVisible) { + this.deathMessageVisibility = parEnumVisible; + this.theScoreboard.sendTeamUpdate(this); + } + + public void setNamePrefix(String prefix) { + if (prefix == null) { + throw new IllegalArgumentException("Prefix cannot be null"); + } else { + this.namePrefixSPT = prefix; + this.theScoreboard.sendTeamUpdate(this); + } + } + + public void setNameSuffix(String suffix) { + this.colorSuffix = suffix; + this.theScoreboard.sendTeamUpdate(this); + } + + public void setNameTagVisibility(Team.EnumVisible parEnumVisible) { + this.nameTagVisibility = parEnumVisible; + this.theScoreboard.sendTeamUpdate(this); + } + + public void setSeeFriendlyInvisiblesEnabled(boolean friendlyInvisibles) { + this.canSeeFriendlyInvisibles = friendlyInvisibles; + this.theScoreboard.sendTeamUpdate(this); + } + + public void setTeamName(String name) { + if (name == null) { + throw new IllegalArgumentException("Name cannot be null"); + } else { + this.teamNameSPT = name; + this.theScoreboard.sendTeamUpdate(this); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/Scoreboard.java b/src/game/java/net/minecraft/scoreboard/Scoreboard.java index 726f8145..2f372178 100644 --- a/src/game/java/net/minecraft/scoreboard/Scoreboard.java +++ b/src/game/java/net/minecraft/scoreboard/Scoreboard.java @@ -13,48 +13,126 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumChatFormatting; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Scoreboard { + private static String[] field_178823_g = null; + + public static String[] getDisplaySlotStrings() { + if (field_178823_g == null) { + field_178823_g = new String[19]; + + for (int i = 0; i < 19; ++i) { + field_178823_g[i] = getObjectiveDisplaySlot(i); + } + } + + return field_178823_g; + } + + /** + * + Returns 'list' for 0, 'sidebar' for 1, 'belowName for 2, otherwise null. + */ + public static String getObjectiveDisplaySlot(int parInt1) { + switch (parInt1) { + case 0: + return "list"; + case 1: + return "sidebar"; + case 2: + return "belowName"; + default: + if (parInt1 >= 3 && parInt1 <= 18) { + EnumChatFormatting enumchatformatting = EnumChatFormatting.func_175744_a(parInt1 - 3); + if (enumchatformatting != null && enumchatformatting != EnumChatFormatting.RESET) { + return "sidebar.team." + enumchatformatting.getFriendlyName(); + } + } + + return null; + } + } + + /** + * + Returns 0 for (case-insensitive) 'list', 1 for 'sidebar', 2 for + * 'belowName', otherwise -1. + */ + public static int getObjectiveDisplaySlotNumber(String parString1) { + if (parString1.equalsIgnoreCase("list")) { + return 0; + } else if (parString1.equalsIgnoreCase("sidebar")) { + return 1; + } else if (parString1.equalsIgnoreCase("belowName")) { + return 2; + } else { + if (parString1.startsWith("sidebar.team.")) { + String s = parString1.substring("sidebar.team.".length()); + EnumChatFormatting enumchatformatting = EnumChatFormatting.getValueByName(s); + if (enumchatformatting != null && enumchatformatting.getColorIndex() >= 0) { + return enumchatformatting.getColorIndex() + 3; + } + } + + return -1; + } + } + private final Map scoreObjectives = Maps.newHashMap(); private final Map> scoreObjectiveCriterias = Maps.newHashMap(); private final Map> entitiesScoreObjectives = Maps.newHashMap(); - /**+ - * Index 0 is tab menu, 1 is sidebar, and 2 is below name + + /** + * + Index 0 is tab menu, 1 is sidebar, and 2 is below name */ private final ScoreObjective[] objectiveDisplaySlots = new ScoreObjective[19]; - private final Map teams = Maps.newHashMap(); - private final Map teamMemberships = Maps.newHashMap(); - private static String[] field_178823_g = null; - /**+ - * Returns a ScoreObjective for the objective name + private final Map teams = Maps.newHashMap(); + + private final Map teamMemberships = Maps.newHashMap(); + + /** + * + Adds a player to the given team */ - public ScoreObjective getObjective(String name) { - return (ScoreObjective) this.scoreObjectives.get(name); + public boolean addPlayerToTeam(String player, String newTeam) { + if (player.length() > 40) { + throw new IllegalArgumentException("The player name \'" + player + "\' is too long!"); + } else if (!this.teams.containsKey(newTeam)) { + return false; + } else { + ScorePlayerTeam scoreplayerteam = this.getTeam(newTeam); + if (this.getPlayersTeam(player) != null) { + this.removePlayerFromTeams(player); + } + + this.teamMemberships.put(player, scoreplayerteam); + scoreplayerteam.getMembershipCollection().add(player); + return true; + } } - /**+ - * Create and returns the score objective for the given name and - * ScoreCriteria + /** + * + Create and returns the score objective for the given name and ScoreCriteria */ public ScoreObjective addScoreObjective(String name, IScoreObjectiveCriteria criteria) { if (name.length() > 16) { @@ -79,16 +157,31 @@ public class Scoreboard { } } - /**+ - * Returns all the objectives for the given criteria + /** + * + This packet will notify the players that this team is created, and that + * will register it on the client */ - public Collection getObjectivesFromCriteria(IScoreObjectiveCriteria criteria) { - Collection collection = (Collection) this.scoreObjectiveCriterias.get(criteria); - return collection == null ? Lists.newArrayList() : Lists.newArrayList(collection); + public void broadcastTeamCreated(ScorePlayerTeam playerTeam) { } - /**+ - * Returns if the entity has the given ScoreObjective + public ScorePlayerTeam createTeam(String parString1) { + if (parString1.length() > 16) { + throw new IllegalArgumentException("The team name \'" + parString1 + "\' is too long!"); + } else { + ScorePlayerTeam scoreplayerteam = this.getTeam(parString1); + if (scoreplayerteam != null) { + throw new IllegalArgumentException("A team with the name \'" + parString1 + "\' already exists!"); + } else { + scoreplayerteam = new ScorePlayerTeam(this, parString1); + this.teams.put(parString1, scoreplayerteam); + this.broadcastTeamCreated(scoreplayerteam); + return scoreplayerteam; + } + } + } + + /** + * + Returns if the entity has the given ScoreObjective */ public boolean entityHasObjective(String name, ScoreObjective parScoreObjective) { Map map = (Map) this.entitiesScoreObjectives.get(name); @@ -100,9 +193,129 @@ public class Scoreboard { } } - /**+ - * Returns the value of the given objective for the given entity - * name + public void func_178820_a(String parString1, ScoreObjective parScoreObjective) { + } + + public void func_181140_a(Entity parEntity) { + if (parEntity != null && !(parEntity instanceof EntityPlayer) && !parEntity.isEntityAlive()) { + String s = parEntity.getUniqueID().toString(); + this.removeObjectiveFromEntity(s, (ScoreObjective) null); + this.removePlayerFromTeams(s); + } + } + + public void func_96513_c(ScorePlayerTeam playerTeam) { + } + + public void func_96516_a(String parString1) { + } + + public void func_96532_b(ScoreObjective parScoreObjective) { + } + + public void func_96533_c(ScoreObjective parScoreObjective) { + } + + public void func_96536_a(Score parScore) { + } + + /** + * + Returns a ScoreObjective for the objective name + */ + public ScoreObjective getObjective(String name) { + return (ScoreObjective) this.scoreObjectives.get(name); + } + + /** + * + 0 is tab menu, 1 is sidebar, 2 is below name + */ + public ScoreObjective getObjectiveInDisplaySlot(int parInt1) { + return this.objectiveDisplaySlots[parInt1]; + } + + public Collection getObjectiveNames() { + return this.entitiesScoreObjectives.keySet(); + } + + public Map getObjectivesForEntity(String name) { + Object object = (Map) this.entitiesScoreObjectives.get(name); + if (object == null) { + object = Maps.newHashMap(); + } + + return (Map) object; + } + + /** + * + Returns all the objectives for the given criteria + */ + public Collection getObjectivesFromCriteria(IScoreObjectiveCriteria criteria) { + Collection collection = (Collection) this.scoreObjectiveCriterias.get(criteria); + return collection == null ? Lists.newArrayList() : Lists.newArrayList(collection); + } + + /** + * + Gets the ScorePlayerTeam object for the given username. + */ + public ScorePlayerTeam getPlayersTeam(String parString1) { + return (ScorePlayerTeam) this.teamMemberships.get(parString1); + } + + public Collection getScoreObjectives() { + return this.scoreObjectives.values(); + } + + public Collection getScores() { + Collection collection = this.entitiesScoreObjectives.values(); + ArrayList arraylist = Lists.newArrayList(); + + for (Map map : (Collection) collection) { + arraylist.addAll(map.values()); + } + + return arraylist; + } + + /** + * + Returns an array of Score objects, sorting by Score.getScorePoints() + */ + public Collection getSortedScores(ScoreObjective objective) { + ArrayList arraylist = Lists.newArrayList(); + + for (Map map : this.entitiesScoreObjectives.values()) { + Score score = (Score) map.get(objective); + if (score != null) { + arraylist.add(score); + } + } + + Collections.sort(arraylist, Score.scoreComparator); + return arraylist; + } + + /** + * + Retrieve the ScorePlayerTeam instance identified by the passed team name + */ + public ScorePlayerTeam getTeam(String parString1) { + return (ScorePlayerTeam) this.teams.get(parString1); + } + + /** + * + Retrieve all registered ScorePlayerTeam names + */ + public Collection getTeamNames() { + return this.teams.keySet(); + } + + /** + * + Retrieve all registered ScorePlayerTeam instances + */ + public Collection getTeams() { + return this.teams.values(); + } + + /** + * + Returns the value of the given objective for the given entity name */ public Score getValueFromObjective(String name, ScoreObjective objective) { if (name.length() > 40) { @@ -124,34 +337,35 @@ public class Scoreboard { } } - /**+ - * Returns an array of Score objects, sorting by - * Score.getScorePoints() + /** + * + Called when a score objective is added */ - public Collection getSortedScores(ScoreObjective objective) { - ArrayList arraylist = Lists.newArrayList(); + public void onScoreObjectiveAdded(ScoreObjective scoreObjectiveIn) { + } - for (Map map : this.entitiesScoreObjectives.values()) { - Score score = (Score) map.get(objective); - if (score != null) { - arraylist.add(score); + public void removeObjective(ScoreObjective parScoreObjective) { + this.scoreObjectives.remove(parScoreObjective.getName()); + + for (int i = 0; i < 19; ++i) { + if (this.getObjectiveInDisplaySlot(i) == parScoreObjective) { + this.setObjectiveInDisplaySlot(i, (ScoreObjective) null); } } - Collections.sort(arraylist, Score.scoreComparator); - return arraylist; + List list = (List) this.scoreObjectiveCriterias.get(parScoreObjective.getCriteria()); + if (list != null) { + list.remove(parScoreObjective); + } + + for (Map map : this.entitiesScoreObjectives.values()) { + map.remove(parScoreObjective); + } + + this.func_96533_c(parScoreObjective); } - public Collection getScoreObjectives() { - return this.scoreObjectives.values(); - } - - public Collection getObjectiveNames() { - return this.entitiesScoreObjectives.keySet(); - } - - /**+ - * Remove the given ScoreObjective for the given Entity name. + /** + * + Remove the given ScoreObjective for the given Entity name. */ public void removeObjectiveFromEntity(String name, ScoreObjective objective) { if (objective == null) { @@ -176,116 +390,18 @@ public class Scoreboard { } - public Collection getScores() { - Collection collection = this.entitiesScoreObjectives.values(); - ArrayList arraylist = Lists.newArrayList(); - - for (Map map : (Collection) collection) { - arraylist.addAll(map.values()); - } - - return arraylist; - } - - public Map getObjectivesForEntity(String name) { - Object object = (Map) this.entitiesScoreObjectives.get(name); - if (object == null) { - object = Maps.newHashMap(); - } - - return (Map) object; - } - - public void removeObjective(ScoreObjective parScoreObjective) { - this.scoreObjectives.remove(parScoreObjective.getName()); - - for (int i = 0; i < 19; ++i) { - if (this.getObjectiveInDisplaySlot(i) == parScoreObjective) { - this.setObjectiveInDisplaySlot(i, (ScoreObjective) null); - } - } - - List list = (List) this.scoreObjectiveCriterias.get(parScoreObjective.getCriteria()); - if (list != null) { - list.remove(parScoreObjective); - } - - for (Map map : this.entitiesScoreObjectives.values()) { - map.remove(parScoreObjective); - } - - this.func_96533_c(parScoreObjective); - } - - /**+ - * 0 is tab menu, 1 is sidebar, 2 is below name + /** + * + Removes the given username from the given ScorePlayerTeam. If the player is + * not on the team then an IllegalStateException is thrown. */ - public void setObjectiveInDisplaySlot(int parInt1, ScoreObjective parScoreObjective) { - this.objectiveDisplaySlots[parInt1] = parScoreObjective; - } - - /**+ - * 0 is tab menu, 1 is sidebar, 2 is below name - */ - public ScoreObjective getObjectiveInDisplaySlot(int parInt1) { - return this.objectiveDisplaySlots[parInt1]; - } - - /**+ - * Retrieve the ScorePlayerTeam instance identified by the - * passed team name - */ - public ScorePlayerTeam getTeam(String parString1) { - return (ScorePlayerTeam) this.teams.get(parString1); - } - - public ScorePlayerTeam createTeam(String parString1) { - if (parString1.length() > 16) { - throw new IllegalArgumentException("The team name \'" + parString1 + "\' is too long!"); + public void removePlayerFromTeam(String parString1, ScorePlayerTeam parScorePlayerTeam) { + if (this.getPlayersTeam(parString1) != parScorePlayerTeam) { + throw new IllegalStateException( + "Player is either on another team or not on any team. Cannot remove from team \'" + + parScorePlayerTeam.getRegisteredName() + "\'."); } else { - ScorePlayerTeam scoreplayerteam = this.getTeam(parString1); - if (scoreplayerteam != null) { - throw new IllegalArgumentException("A team with the name \'" + parString1 + "\' already exists!"); - } else { - scoreplayerteam = new ScorePlayerTeam(this, parString1); - this.teams.put(parString1, scoreplayerteam); - this.broadcastTeamCreated(scoreplayerteam); - return scoreplayerteam; - } - } - } - - /**+ - * Removes the team from the scoreboard, updates all player - * memberships and broadcasts the deletion to all players - */ - public void removeTeam(ScorePlayerTeam parScorePlayerTeam) { - this.teams.remove(parScorePlayerTeam.getRegisteredName()); - - for (String s : parScorePlayerTeam.getMembershipCollection()) { - this.teamMemberships.remove(s); - } - - this.func_96513_c(parScorePlayerTeam); - } - - /**+ - * Adds a player to the given team - */ - public boolean addPlayerToTeam(String player, String newTeam) { - if (player.length() > 40) { - throw new IllegalArgumentException("The player name \'" + player + "\' is too long!"); - } else if (!this.teams.containsKey(newTeam)) { - return false; - } else { - ScorePlayerTeam scoreplayerteam = this.getTeam(newTeam); - if (this.getPlayersTeam(player) != null) { - this.removePlayerFromTeams(player); - } - - this.teamMemberships.put(player, scoreplayerteam); - scoreplayerteam.getMembershipCollection().add(player); - return true; + this.teamMemberships.remove(parString1); + parScorePlayerTeam.getMembershipCollection().remove(parString1); } } @@ -299,145 +415,30 @@ public class Scoreboard { } } - /**+ - * Removes the given username from the given ScorePlayerTeam. If - * the player is not on the team then an IllegalStateException - * is thrown. + /** + * + Removes the team from the scoreboard, updates all player memberships and + * broadcasts the deletion to all players */ - public void removePlayerFromTeam(String parString1, ScorePlayerTeam parScorePlayerTeam) { - if (this.getPlayersTeam(parString1) != parScorePlayerTeam) { - throw new IllegalStateException( - "Player is either on another team or not on any team. Cannot remove from team \'" - + parScorePlayerTeam.getRegisteredName() + "\'."); - } else { - this.teamMemberships.remove(parString1); - parScorePlayerTeam.getMembershipCollection().remove(parString1); + public void removeTeam(ScorePlayerTeam parScorePlayerTeam) { + this.teams.remove(parScorePlayerTeam.getRegisteredName()); + + for (String s : parScorePlayerTeam.getMembershipCollection()) { + this.teamMemberships.remove(s); } + + this.func_96513_c(parScorePlayerTeam); } - /**+ - * Retrieve all registered ScorePlayerTeam names - */ - public Collection getTeamNames() { - return this.teams.keySet(); - } - - /**+ - * Retrieve all registered ScorePlayerTeam instances - */ - public Collection getTeams() { - return this.teams.values(); - } - - /**+ - * Gets the ScorePlayerTeam object for the given username. - */ - public ScorePlayerTeam getPlayersTeam(String parString1) { - return (ScorePlayerTeam) this.teamMemberships.get(parString1); - } - - /**+ - * Called when a score objective is added - */ - public void onScoreObjectiveAdded(ScoreObjective scoreObjectiveIn) { - } - - public void func_96532_b(ScoreObjective parScoreObjective) { - } - - public void func_96533_c(ScoreObjective parScoreObjective) { - } - - public void func_96536_a(Score parScore) { - } - - public void func_96516_a(String parString1) { - } - - public void func_178820_a(String parString1, ScoreObjective parScoreObjective) { - } - - /**+ - * This packet will notify the players that this team is - * created, and that will register it on the client - */ - public void broadcastTeamCreated(ScorePlayerTeam playerTeam) { - } - - /**+ - * This packet will notify the players that this team is updated + /** + * + This packet will notify the players that this team is updated */ public void sendTeamUpdate(ScorePlayerTeam playerTeam) { } - public void func_96513_c(ScorePlayerTeam playerTeam) { - } - - /**+ - * Returns 'list' for 0, 'sidebar' for 1, 'belowName for 2, - * otherwise null. + /** + * + 0 is tab menu, 1 is sidebar, 2 is below name */ - public static String getObjectiveDisplaySlot(int parInt1) { - switch (parInt1) { - case 0: - return "list"; - case 1: - return "sidebar"; - case 2: - return "belowName"; - default: - if (parInt1 >= 3 && parInt1 <= 18) { - EnumChatFormatting enumchatformatting = EnumChatFormatting.func_175744_a(parInt1 - 3); - if (enumchatformatting != null && enumchatformatting != EnumChatFormatting.RESET) { - return "sidebar.team." + enumchatformatting.getFriendlyName(); - } - } - - return null; - } - } - - /**+ - * Returns 0 for (case-insensitive) 'list', 1 for 'sidebar', 2 - * for 'belowName', otherwise -1. - */ - public static int getObjectiveDisplaySlotNumber(String parString1) { - if (parString1.equalsIgnoreCase("list")) { - return 0; - } else if (parString1.equalsIgnoreCase("sidebar")) { - return 1; - } else if (parString1.equalsIgnoreCase("belowName")) { - return 2; - } else { - if (parString1.startsWith("sidebar.team.")) { - String s = parString1.substring("sidebar.team.".length()); - EnumChatFormatting enumchatformatting = EnumChatFormatting.getValueByName(s); - if (enumchatformatting != null && enumchatformatting.getColorIndex() >= 0) { - return enumchatformatting.getColorIndex() + 3; - } - } - - return -1; - } - } - - public static String[] getDisplaySlotStrings() { - if (field_178823_g == null) { - field_178823_g = new String[19]; - - for (int i = 0; i < 19; ++i) { - field_178823_g[i] = getObjectiveDisplaySlot(i); - } - } - - return field_178823_g; - } - - public void func_181140_a(Entity parEntity) { - if (parEntity != null && !(parEntity instanceof EntityPlayer) && !parEntity.isEntityAlive()) { - String s = parEntity.getUniqueID().toString(); - this.removeObjectiveFromEntity(s, (ScoreObjective) null); - this.removePlayerFromTeams(s); - } + public void setObjectiveInDisplaySlot(int parInt1, ScoreObjective parScoreObjective) { + this.objectiveDisplaySlots[parInt1] = parScoreObjective; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/ScoreboardSaveData.java b/src/game/java/net/minecraft/scoreboard/ScoreboardSaveData.java index 0d923342..93e443ff 100644 --- a/src/game/java/net/minecraft/scoreboard/ScoreboardSaveData.java +++ b/src/game/java/net/minecraft/scoreboard/ScoreboardSaveData.java @@ -8,22 +8,25 @@ import net.minecraft.nbt.NBTTagString; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.WorldSavedData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,16 +44,92 @@ public class ScoreboardSaveData extends WorldSavedData { super(name); } - public void setScoreboard(Scoreboard scoreboardIn) { - this.theScoreboard = scoreboardIn; - if (this.delayedInitNbt != null) { - this.readFromNBT(this.delayedInitNbt); + protected NBTTagList func_96496_a() { + NBTTagList nbttaglist = new NBTTagList(); + + for (ScorePlayerTeam scoreplayerteam : this.theScoreboard.getTeams()) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("Name", scoreplayerteam.getRegisteredName()); + nbttagcompound.setString("DisplayName", scoreplayerteam.getTeamName()); + if (scoreplayerteam.getChatFormat().getColorIndex() >= 0) { + nbttagcompound.setString("TeamColor", scoreplayerteam.getChatFormat().getFriendlyName()); + } + + nbttagcompound.setString("Prefix", scoreplayerteam.getColorPrefix()); + nbttagcompound.setString("Suffix", scoreplayerteam.getColorSuffix()); + nbttagcompound.setBoolean("AllowFriendlyFire", scoreplayerteam.getAllowFriendlyFire()); + nbttagcompound.setBoolean("SeeFriendlyInvisibles", scoreplayerteam.getSeeFriendlyInvisiblesEnabled()); + nbttagcompound.setString("NameTagVisibility", scoreplayerteam.getNameTagVisibility().field_178830_e); + nbttagcompound.setString("DeathMessageVisibility", + scoreplayerteam.getDeathMessageVisibility().field_178830_e); + NBTTagList nbttaglist1 = new NBTTagList(); + + for (String s : scoreplayerteam.getMembershipCollection()) { + nbttaglist1.appendTag(new NBTTagString(s)); + } + + nbttagcompound.setTag("Players", nbttaglist1); + nbttaglist.appendTag(nbttagcompound); + } + + return nbttaglist; + } + + protected void func_96497_d(NBTTagCompound parNBTTagCompound) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + boolean flag = false; + + for (int i = 0; i < 19; ++i) { + ScoreObjective scoreobjective = this.theScoreboard.getObjectiveInDisplaySlot(i); + if (scoreobjective != null) { + nbttagcompound.setString("slot_" + i, scoreobjective.getName()); + flag = true; + } + } + + if (flag) { + parNBTTagCompound.setTag("DisplaySlots", nbttagcompound); } } - /**+ - * reads in data from the NBTTagCompound into this MapDataBase + protected void func_96502_a(ScorePlayerTeam parScorePlayerTeam, NBTTagList parNBTTagList) { + for (int i = 0; i < parNBTTagList.tagCount(); ++i) { + this.theScoreboard.addPlayerToTeam(parNBTTagList.getStringTagAt(i), parScorePlayerTeam.getRegisteredName()); + } + + } + + protected NBTTagList objectivesToNbt() { + NBTTagList nbttaglist = new NBTTagList(); + + for (ScoreObjective scoreobjective : this.theScoreboard.getScoreObjectives()) { + if (scoreobjective.getCriteria() != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("Name", scoreobjective.getName()); + nbttagcompound.setString("CriteriaName", scoreobjective.getCriteria().getName()); + nbttagcompound.setString("DisplayName", scoreobjective.getDisplayName()); + nbttagcompound.setString("RenderType", scoreobjective.getRenderType().func_178796_a()); + nbttaglist.appendTag(nbttagcompound); + } + } + + return nbttaglist; + } + + protected void readDisplayConfig(NBTTagCompound parNBTTagCompound) { + for (int i = 0; i < 19; ++i) { + if (parNBTTagCompound.hasKey("slot_" + i, 8)) { + String s = parNBTTagCompound.getString("slot_" + i); + ScoreObjective scoreobjective = this.theScoreboard.getObjective(s); + this.theScoreboard.setObjectiveInDisplaySlot(i, scoreobjective); + } + } + + } + + /** + * + reads in data from the NBTTagCompound into this MapDataBase */ public void readFromNBT(NBTTagCompound nbttagcompound) { if (this.theScoreboard == null) { @@ -69,6 +148,44 @@ public class ScoreboardSaveData extends WorldSavedData { } } + protected void readObjectives(NBTTagList nbt) { + for (int i = 0; i < nbt.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbt.getCompoundTagAt(i); + IScoreObjectiveCriteria iscoreobjectivecriteria = (IScoreObjectiveCriteria) IScoreObjectiveCriteria.INSTANCES + .get(nbttagcompound.getString("CriteriaName")); + if (iscoreobjectivecriteria != null) { + String s = nbttagcompound.getString("Name"); + if (s.length() > 16) { + s = s.substring(0, 16); + } + + ScoreObjective scoreobjective = this.theScoreboard.addScoreObjective(s, iscoreobjectivecriteria); + scoreobjective.setDisplayName(nbttagcompound.getString("DisplayName")); + scoreobjective.setRenderType( + IScoreObjectiveCriteria.EnumRenderType.func_178795_a(nbttagcompound.getString("RenderType"))); + } + } + + } + + protected void readScores(NBTTagList nbt) { + for (int i = 0; i < nbt.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbt.getCompoundTagAt(i); + ScoreObjective scoreobjective = this.theScoreboard.getObjective(nbttagcompound.getString("Objective")); + String s = nbttagcompound.getString("Name"); + if (s.length() > 40) { + s = s.substring(0, 40); + } + + Score score = this.theScoreboard.getValueFromObjective(s, scoreobjective); + score.setScorePoints(nbttagcompound.getInteger("Score")); + if (nbttagcompound.hasKey("Locked")) { + score.setLocked(nbttagcompound.getBoolean("Locked")); + } + } + + } + protected void readTeams(NBTTagList parNBTTagList) { for (int i = 0; i < parNBTTagList.tagCount(); ++i) { NBTTagCompound nbttagcompound = parNBTTagList.getCompoundTagAt(i); @@ -119,143 +236,6 @@ public class ScoreboardSaveData extends WorldSavedData { } - protected void func_96502_a(ScorePlayerTeam parScorePlayerTeam, NBTTagList parNBTTagList) { - for (int i = 0; i < parNBTTagList.tagCount(); ++i) { - this.theScoreboard.addPlayerToTeam(parNBTTagList.getStringTagAt(i), parScorePlayerTeam.getRegisteredName()); - } - - } - - protected void readDisplayConfig(NBTTagCompound parNBTTagCompound) { - for (int i = 0; i < 19; ++i) { - if (parNBTTagCompound.hasKey("slot_" + i, 8)) { - String s = parNBTTagCompound.getString("slot_" + i); - ScoreObjective scoreobjective = this.theScoreboard.getObjective(s); - this.theScoreboard.setObjectiveInDisplaySlot(i, scoreobjective); - } - } - - } - - protected void readObjectives(NBTTagList nbt) { - for (int i = 0; i < nbt.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbt.getCompoundTagAt(i); - IScoreObjectiveCriteria iscoreobjectivecriteria = (IScoreObjectiveCriteria) IScoreObjectiveCriteria.INSTANCES - .get(nbttagcompound.getString("CriteriaName")); - if (iscoreobjectivecriteria != null) { - String s = nbttagcompound.getString("Name"); - if (s.length() > 16) { - s = s.substring(0, 16); - } - - ScoreObjective scoreobjective = this.theScoreboard.addScoreObjective(s, iscoreobjectivecriteria); - scoreobjective.setDisplayName(nbttagcompound.getString("DisplayName")); - scoreobjective.setRenderType( - IScoreObjectiveCriteria.EnumRenderType.func_178795_a(nbttagcompound.getString("RenderType"))); - } - } - - } - - protected void readScores(NBTTagList nbt) { - for (int i = 0; i < nbt.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbt.getCompoundTagAt(i); - ScoreObjective scoreobjective = this.theScoreboard.getObjective(nbttagcompound.getString("Objective")); - String s = nbttagcompound.getString("Name"); - if (s.length() > 40) { - s = s.substring(0, 40); - } - - Score score = this.theScoreboard.getValueFromObjective(s, scoreobjective); - score.setScorePoints(nbttagcompound.getInteger("Score")); - if (nbttagcompound.hasKey("Locked")) { - score.setLocked(nbttagcompound.getBoolean("Locked")); - } - } - - } - - /**+ - * write data to NBTTagCompound from this MapDataBase, similar - * to Entities and TileEntities - */ - public void writeToNBT(NBTTagCompound nbttagcompound) { - if (this.theScoreboard == null) { - logger.warn("Tried to save scoreboard without having a scoreboard..."); - } else { - nbttagcompound.setTag("Objectives", this.objectivesToNbt()); - nbttagcompound.setTag("PlayerScores", this.scoresToNbt()); - nbttagcompound.setTag("Teams", this.func_96496_a()); - this.func_96497_d(nbttagcompound); - } - } - - protected NBTTagList func_96496_a() { - NBTTagList nbttaglist = new NBTTagList(); - - for (ScorePlayerTeam scoreplayerteam : this.theScoreboard.getTeams()) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("Name", scoreplayerteam.getRegisteredName()); - nbttagcompound.setString("DisplayName", scoreplayerteam.getTeamName()); - if (scoreplayerteam.getChatFormat().getColorIndex() >= 0) { - nbttagcompound.setString("TeamColor", scoreplayerteam.getChatFormat().getFriendlyName()); - } - - nbttagcompound.setString("Prefix", scoreplayerteam.getColorPrefix()); - nbttagcompound.setString("Suffix", scoreplayerteam.getColorSuffix()); - nbttagcompound.setBoolean("AllowFriendlyFire", scoreplayerteam.getAllowFriendlyFire()); - nbttagcompound.setBoolean("SeeFriendlyInvisibles", scoreplayerteam.getSeeFriendlyInvisiblesEnabled()); - nbttagcompound.setString("NameTagVisibility", scoreplayerteam.getNameTagVisibility().field_178830_e); - nbttagcompound.setString("DeathMessageVisibility", - scoreplayerteam.getDeathMessageVisibility().field_178830_e); - NBTTagList nbttaglist1 = new NBTTagList(); - - for (String s : scoreplayerteam.getMembershipCollection()) { - nbttaglist1.appendTag(new NBTTagString(s)); - } - - nbttagcompound.setTag("Players", nbttaglist1); - nbttaglist.appendTag(nbttagcompound); - } - - return nbttaglist; - } - - protected void func_96497_d(NBTTagCompound parNBTTagCompound) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - boolean flag = false; - - for (int i = 0; i < 19; ++i) { - ScoreObjective scoreobjective = this.theScoreboard.getObjectiveInDisplaySlot(i); - if (scoreobjective != null) { - nbttagcompound.setString("slot_" + i, scoreobjective.getName()); - flag = true; - } - } - - if (flag) { - parNBTTagCompound.setTag("DisplaySlots", nbttagcompound); - } - - } - - protected NBTTagList objectivesToNbt() { - NBTTagList nbttaglist = new NBTTagList(); - - for (ScoreObjective scoreobjective : this.theScoreboard.getScoreObjectives()) { - if (scoreobjective.getCriteria() != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("Name", scoreobjective.getName()); - nbttagcompound.setString("CriteriaName", scoreobjective.getCriteria().getName()); - nbttagcompound.setString("DisplayName", scoreobjective.getDisplayName()); - nbttagcompound.setString("RenderType", scoreobjective.getRenderType().func_178796_a()); - nbttaglist.appendTag(nbttagcompound); - } - } - - return nbttaglist; - } - protected NBTTagList scoresToNbt() { NBTTagList nbttaglist = new NBTTagList(); @@ -272,4 +252,27 @@ public class ScoreboardSaveData extends WorldSavedData { return nbttaglist; } + + public void setScoreboard(Scoreboard scoreboardIn) { + this.theScoreboard = scoreboardIn; + if (this.delayedInitNbt != null) { + this.readFromNBT(this.delayedInitNbt); + } + + } + + /** + * + write data to NBTTagCompound from this MapDataBase, similar to Entities and + * TileEntities + */ + public void writeToNBT(NBTTagCompound nbttagcompound) { + if (this.theScoreboard == null) { + logger.warn("Tried to save scoreboard without having a scoreboard..."); + } else { + nbttagcompound.setTag("Objectives", this.objectivesToNbt()); + nbttagcompound.setTag("PlayerScores", this.scoresToNbt()); + nbttagcompound.setTag("Teams", this.func_96496_a()); + this.func_96497_d(nbttagcompound); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/ServerScoreboard.java b/src/game/java/net/minecraft/scoreboard/ServerScoreboard.java index c3cf9075..0e309a9a 100644 --- a/src/game/java/net/minecraft/scoreboard/ServerScoreboard.java +++ b/src/game/java/net/minecraft/scoreboard/ServerScoreboard.java @@ -1,11 +1,13 @@ package net.minecraft.scoreboard; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S3BPacketScoreboardObjective; @@ -14,22 +16,25 @@ import net.minecraft.network.play.server.S3DPacketDisplayScoreboard; import net.minecraft.network.play.server.S3EPacketTeams; import net.minecraft.server.MinecraftServer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,18 +49,29 @@ public class ServerScoreboard extends Scoreboard { this.scoreboardMCServer = mcServer; } - public void func_96536_a(Score score) { - super.func_96536_a(score); - if (this.field_96553_b.contains(score.getObjective())) { - this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3CPacketUpdateScore(score)); + /** + * + Adds a player to the given team + */ + public boolean addPlayerToTeam(String s, String s1) { + if (super.addPlayerToTeam(s, s1)) { + ScorePlayerTeam scoreplayerteam = this.getTeam(s1); + this.scoreboardMCServer.getConfigurationManager() + .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, Arrays.asList(new String[] { s }), 3)); + this.func_96551_b(); + return true; + } else { + return false; } - - this.func_96551_b(); } - public void func_96516_a(String s) { - super.func_96516_a(s); - this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3CPacketUpdateScore(s)); + /** + * + This packet will notify the players that this team is created, and that + * will register it on the client + */ + public void broadcastTeamCreated(ScorePlayerTeam scoreplayerteam) { + super.broadcastTeamCreated(scoreplayerteam); + this.scoreboardMCServer.getConfigurationManager() + .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, 0)); this.func_96551_b(); } @@ -66,8 +82,159 @@ public class ServerScoreboard extends Scoreboard { this.func_96551_b(); } - /**+ - * 0 is tab menu, 1 is sidebar, 2 is below name + public void func_96513_c(ScorePlayerTeam scoreplayerteam) { + super.func_96513_c(scoreplayerteam); + this.scoreboardMCServer.getConfigurationManager() + .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, 1)); + this.func_96551_b(); + } + + public void func_96516_a(String s) { + super.func_96516_a(s); + this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3CPacketUpdateScore(s)); + this.func_96551_b(); + } + + public void func_96532_b(ScoreObjective scoreobjective) { + super.func_96532_b(scoreobjective); + if (this.field_96553_b.contains(scoreobjective)) { + this.scoreboardMCServer.getConfigurationManager() + .sendPacketToAllPlayers(new S3BPacketScoreboardObjective(scoreobjective, 2)); + } + + this.func_96551_b(); + } + + public void func_96533_c(ScoreObjective scoreobjective) { + super.func_96533_c(scoreobjective); + if (this.field_96553_b.contains(scoreobjective)) { + this.getPlayerIterator(scoreobjective); + } + + this.func_96551_b(); + } + + public void func_96536_a(Score score) { + super.func_96536_a(score); + if (this.field_96553_b.contains(score.getObjective())) { + this.scoreboardMCServer.getConfigurationManager().sendPacketToAllPlayers(new S3CPacketUpdateScore(score)); + } + + this.func_96551_b(); + } + + public void func_96547_a(ScoreboardSaveData parScoreboardSaveData) { + this.scoreboardSaveData = parScoreboardSaveData; + } + + public List func_96548_f(ScoreObjective parScoreObjective) { + ArrayList arraylist = Lists.newArrayList(); + arraylist.add(new S3BPacketScoreboardObjective(parScoreObjective, 1)); + + for (int i = 0; i < 19; ++i) { + if (this.getObjectiveInDisplaySlot(i) == parScoreObjective) { + arraylist.add(new S3DPacketDisplayScoreboard(i, parScoreObjective)); + } + } + + return arraylist; + } + + public void func_96549_e(ScoreObjective parScoreObjective) { + List list = this.func_96550_d(parScoreObjective); + + List players = this.scoreboardMCServer.getConfigurationManager().func_181057_v(); + for (int i = 0, l = players.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = players.get(i); + for (int j = 0, m = list.size(); j < m; ++j) { + entityplayermp.playerNetServerHandler.sendPacket(list.get(j)); + } + } + + this.field_96553_b.add(parScoreObjective); + } + + public List func_96550_d(ScoreObjective parScoreObjective) { + ArrayList arraylist = Lists.newArrayList(); + arraylist.add(new S3BPacketScoreboardObjective(parScoreObjective, 0)); + + for (int i = 0; i < 19; ++i) { + if (this.getObjectiveInDisplaySlot(i) == parScoreObjective) { + arraylist.add(new S3DPacketDisplayScoreboard(i, parScoreObjective)); + } + } + + for (Score score : this.getSortedScores(parScoreObjective)) { + arraylist.add(new S3CPacketUpdateScore(score)); + } + + return arraylist; + } + + protected void func_96551_b() { + if (this.scoreboardSaveData != null) { + this.scoreboardSaveData.markDirty(); + } + + } + + public int func_96552_h(ScoreObjective parScoreObjective) { + int i = 0; + + for (int j = 0; j < 19; ++j) { + if (this.getObjectiveInDisplaySlot(j) == parScoreObjective) { + ++i; + } + } + + return i; + } + + public void getPlayerIterator(ScoreObjective parScoreObjective) { + List list = this.func_96548_f(parScoreObjective); + + List players = this.scoreboardMCServer.getConfigurationManager().func_181057_v(); + for (int i = 0, l = players.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = players.get(i); + for (int j = 0, m = list.size(); j < m; ++j) { + entityplayermp.playerNetServerHandler.sendPacket(list.get(j)); + } + } + + this.field_96553_b.remove(parScoreObjective); + } + + /** + * + Called when a score objective is added + */ + public void onScoreObjectiveAdded(ScoreObjective scoreobjective) { + super.onScoreObjectiveAdded(scoreobjective); + this.func_96551_b(); + } + + /** + * + Removes the given username from the given ScorePlayerTeam. If the player is + * not on the team then an IllegalStateException is thrown. + */ + public void removePlayerFromTeam(String s, ScorePlayerTeam scoreplayerteam) { + super.removePlayerFromTeam(s, scoreplayerteam); + this.scoreboardMCServer.getConfigurationManager() + .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, Arrays.asList(new String[] { s }), 4)); + this.func_96551_b(); + } + + /** + * + This packet will notify the players that this team is updated + */ + public void sendTeamUpdate(ScorePlayerTeam scoreplayerteam) { + super.sendTeamUpdate(scoreplayerteam); + this.scoreboardMCServer.getConfigurationManager() + .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, 2)); + this.func_96551_b(); + } + + /** + * + 0 is tab menu, 1 is sidebar, 2 is below name */ public void setObjectiveInDisplaySlot(int i, ScoreObjective scoreobjective) { ScoreObjective scoreobjective1 = this.getObjectiveInDisplaySlot(i); @@ -92,167 +259,4 @@ public class ServerScoreboard extends Scoreboard { this.func_96551_b(); } - - /**+ - * Adds a player to the given team - */ - public boolean addPlayerToTeam(String s, String s1) { - if (super.addPlayerToTeam(s, s1)) { - ScorePlayerTeam scoreplayerteam = this.getTeam(s1); - this.scoreboardMCServer.getConfigurationManager() - .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, Arrays.asList(new String[] { s }), 3)); - this.func_96551_b(); - return true; - } else { - return false; - } - } - - /**+ - * Removes the given username from the given ScorePlayerTeam. If - * the player is not on the team then an IllegalStateException - * is thrown. - */ - public void removePlayerFromTeam(String s, ScorePlayerTeam scoreplayerteam) { - super.removePlayerFromTeam(s, scoreplayerteam); - this.scoreboardMCServer.getConfigurationManager() - .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, Arrays.asList(new String[] { s }), 4)); - this.func_96551_b(); - } - - /**+ - * Called when a score objective is added - */ - public void onScoreObjectiveAdded(ScoreObjective scoreobjective) { - super.onScoreObjectiveAdded(scoreobjective); - this.func_96551_b(); - } - - public void func_96532_b(ScoreObjective scoreobjective) { - super.func_96532_b(scoreobjective); - if (this.field_96553_b.contains(scoreobjective)) { - this.scoreboardMCServer.getConfigurationManager() - .sendPacketToAllPlayers(new S3BPacketScoreboardObjective(scoreobjective, 2)); - } - - this.func_96551_b(); - } - - public void func_96533_c(ScoreObjective scoreobjective) { - super.func_96533_c(scoreobjective); - if (this.field_96553_b.contains(scoreobjective)) { - this.getPlayerIterator(scoreobjective); - } - - this.func_96551_b(); - } - - /**+ - * This packet will notify the players that this team is - * created, and that will register it on the client - */ - public void broadcastTeamCreated(ScorePlayerTeam scoreplayerteam) { - super.broadcastTeamCreated(scoreplayerteam); - this.scoreboardMCServer.getConfigurationManager() - .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, 0)); - this.func_96551_b(); - } - - /**+ - * This packet will notify the players that this team is updated - */ - public void sendTeamUpdate(ScorePlayerTeam scoreplayerteam) { - super.sendTeamUpdate(scoreplayerteam); - this.scoreboardMCServer.getConfigurationManager() - .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, 2)); - this.func_96551_b(); - } - - public void func_96513_c(ScorePlayerTeam scoreplayerteam) { - super.func_96513_c(scoreplayerteam); - this.scoreboardMCServer.getConfigurationManager() - .sendPacketToAllPlayers(new S3EPacketTeams(scoreplayerteam, 1)); - this.func_96551_b(); - } - - public void func_96547_a(ScoreboardSaveData parScoreboardSaveData) { - this.scoreboardSaveData = parScoreboardSaveData; - } - - protected void func_96551_b() { - if (this.scoreboardSaveData != null) { - this.scoreboardSaveData.markDirty(); - } - - } - - public List func_96550_d(ScoreObjective parScoreObjective) { - ArrayList arraylist = Lists.newArrayList(); - arraylist.add(new S3BPacketScoreboardObjective(parScoreObjective, 0)); - - for (int i = 0; i < 19; ++i) { - if (this.getObjectiveInDisplaySlot(i) == parScoreObjective) { - arraylist.add(new S3DPacketDisplayScoreboard(i, parScoreObjective)); - } - } - - for (Score score : this.getSortedScores(parScoreObjective)) { - arraylist.add(new S3CPacketUpdateScore(score)); - } - - return arraylist; - } - - public void func_96549_e(ScoreObjective parScoreObjective) { - List list = this.func_96550_d(parScoreObjective); - - List players = this.scoreboardMCServer.getConfigurationManager().func_181057_v(); - for (int i = 0, l = players.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = players.get(i); - for (int j = 0, m = list.size(); j < m; ++j) { - entityplayermp.playerNetServerHandler.sendPacket(list.get(j)); - } - } - - this.field_96553_b.add(parScoreObjective); - } - - public List func_96548_f(ScoreObjective parScoreObjective) { - ArrayList arraylist = Lists.newArrayList(); - arraylist.add(new S3BPacketScoreboardObjective(parScoreObjective, 1)); - - for (int i = 0; i < 19; ++i) { - if (this.getObjectiveInDisplaySlot(i) == parScoreObjective) { - arraylist.add(new S3DPacketDisplayScoreboard(i, parScoreObjective)); - } - } - - return arraylist; - } - - public void getPlayerIterator(ScoreObjective parScoreObjective) { - List list = this.func_96548_f(parScoreObjective); - - List players = this.scoreboardMCServer.getConfigurationManager().func_181057_v(); - for (int i = 0, l = players.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = players.get(i); - for (int j = 0, m = list.size(); j < m; ++j) { - entityplayermp.playerNetServerHandler.sendPacket(list.get(j)); - } - } - - this.field_96553_b.remove(parScoreObjective); - } - - public int func_96552_h(ScoreObjective parScoreObjective) { - int i = 0; - - for (int j = 0; j < 19; ++j) { - if (this.getObjectiveInDisplaySlot(j) == parScoreObjective) { - ++i; - } - } - - return i; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/scoreboard/Team.java b/src/game/java/net/minecraft/scoreboard/Team.java index daea0e7e..908172b8 100644 --- a/src/game/java/net/minecraft/scoreboard/Team.java +++ b/src/game/java/net/minecraft/scoreboard/Team.java @@ -5,69 +5,35 @@ import java.util.Map; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class Team { - /**+ - * Same as == - */ - public boolean isSameTeam(Team other) { - return other == null ? false : this == other; - } - - public abstract String getRegisteredName(); - - public abstract String formatString(String var1); - - public abstract boolean getSeeFriendlyInvisiblesEnabled(); - - public abstract boolean getAllowFriendlyFire(); - - public abstract Team.EnumVisible getNameTagVisibility(); - - public abstract Collection getMembershipCollection(); - - public abstract Team.EnumVisible getDeathMessageVisibility(); - public static enum EnumVisible { ALWAYS("always", 0), NEVER("never", 1), HIDE_FOR_OTHER_TEAMS("hideForOtherTeams", 2), HIDE_FOR_OWN_TEAM("hideForOwnTeam", 3); private static Map field_178828_g = Maps.newHashMap(); - public final String field_178830_e; - public final int field_178827_f; - - public static String[] func_178825_a() { - return (String[]) field_178828_g.keySet().toArray(new String[field_178828_g.size()]); - } - - public static Team.EnumVisible func_178824_a(String parString1) { - return (Team.EnumVisible) field_178828_g.get(parString1); - } - - private EnumVisible(String parString2, int parInt2) { - this.field_178830_e = parString2; - this.field_178827_f = parInt2; - } - static { Team.EnumVisible[] types = values(); for (int i = 0; i < types.length; ++i) { @@ -75,5 +41,43 @@ public abstract class Team { } } + + public static Team.EnumVisible func_178824_a(String parString1) { + return (Team.EnumVisible) field_178828_g.get(parString1); + } + + public static String[] func_178825_a() { + return (String[]) field_178828_g.keySet().toArray(new String[field_178828_g.size()]); + } + + public final String field_178830_e; + + public final int field_178827_f; + + private EnumVisible(String parString2, int parInt2) { + this.field_178830_e = parString2; + this.field_178827_f = parInt2; + } + } + + public abstract String formatString(String var1); + + public abstract boolean getAllowFriendlyFire(); + + public abstract Team.EnumVisible getDeathMessageVisibility(); + + public abstract Collection getMembershipCollection(); + + public abstract Team.EnumVisible getNameTagVisibility(); + + public abstract String getRegisteredName(); + + public abstract boolean getSeeFriendlyInvisiblesEnabled(); + + /** + * + Same as == + */ + public boolean isSameTeam(Team other) { + return other == null ? false : this == other; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/server/MinecraftServer.java b/src/game/java/net/minecraft/server/MinecraftServer.java index 355aacf3..71d9aa07 100644 --- a/src/game/java/net/minecraft/server/MinecraftServer.java +++ b/src/game/java/net/minecraft/server/MinecraftServer.java @@ -1,8 +1,5 @@ package net.minecraft.server; -import com.google.common.collect.Lists; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; - import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; @@ -10,10 +7,15 @@ import java.util.List; import java.util.Queue; import java.util.concurrent.Callable; +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.futures.FutureTask; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerIntegratedServerWorker; import net.minecraft.command.CommandBase; import net.minecraft.command.CommandResultStats; @@ -46,25 +48,26 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.demo.DemoWorldServer; import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.WorldInfo; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -72,21 +75,33 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; public abstract class MinecraftServer implements Runnable, ICommandSender, IThreadListener { private static final Logger logger = LogManager.getLogger(); private static MinecraftServer mcServer; - /**+ - * List of names of players who are online. + + public static long getCurrentTimeMillis() { + return EagRuntime.steadyTimeMillis(); + } + + /** + * + Gets mcServer. + */ + public static MinecraftServer getServer() { + return mcServer; + } + + /** + * + List of names of players who are online. */ protected final List playersOnline = Lists.newArrayList(); protected final ICommandManager commandManager; private final EaglercraftRandom random = new EaglercraftRandom(); - /**+ - * The server's port. + /** + * + The server's port. */ private int serverPort = -1; public WorldServer[] worldServers; private ServerConfigurationManager serverConfigManager; - /**+ - * Indicates whether the server is running or not. Set to false - * to initiate a shutdown. + /** + * + Indicates whether the server is running or not. Set to false to initiate a + * shutdown. */ protected boolean serverRunning = false; private boolean serverStopped; @@ -108,8 +123,8 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre private boolean isDemo; private boolean enableBonusChest; private boolean worldIsBeingDeleted; - /**+ - * The texture pack for the server + /** + * + The texture pack for the server */ private String resourcePackUrl = ""; private String resourcePackHash = ""; @@ -122,7 +137,9 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre protected final Queue> futureTaskQueue = new LinkedList<>(); private Thread serverThread; protected long currentTime = getCurrentTimeMillis(); + private boolean paused = false; + private boolean isSpawnChunksLoaded = false; public MinecraftServer(String worldName) { @@ -131,28 +148,420 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre this.commandManager = new ServerCommandManager(); } - protected ServerCommandManager createNewCommandManager() { - return new ServerCommandManager(); + /** + * + Send a chat message to the CommandSender + */ + public void addChatMessage(IChatComponent ichatcomponent) { + logger.info(ichatcomponent.getUnformattedText()); } - protected abstract boolean startServer() throws IOException; + /** + * + Adds the server info, including from theWorldServer, to the crash report. + */ + public CrashReport addServerInfoToCrashReport(CrashReport crashreport) { + crashreport.getCategory().addCrashSectionCallable("Profiler Position", new Callable() { + public String call() throws Exception { + return "N/A (disabled)"; + } + }); + if (this.serverConfigManager != null) { + crashreport.getCategory().addCrashSectionCallable("Player Count", new Callable() { + public String call() { + return MinecraftServer.this.serverConfigManager.getCurrentPlayerCount() + " / " + + MinecraftServer.this.serverConfigManager.getMaxPlayers() + "; " + + MinecraftServer.this.serverConfigManager.func_181057_v(); + } + }); + } + + return crashreport; + } + + protected boolean allowSpawnMonsters() { + return true; + } + + /** + * + Returns {@code true} if the CommandSender is allowed to execute the + * command, {@code false} if not + */ + public boolean canCommandSenderUseCommand(int var1, String var2) { + return true; + } + + public void canCreateBonusChest(boolean enable) { + this.enableBonusChest = enable; + } + + public abstract boolean canStructuresSpawn(); + + /** + * + Set current task to null and set its percentage to 0. + */ + protected void clearCurrentTask() { + this.currentTask = null; + this.percentDone = 0; + } protected void convertMapIfNeeded(String worldNameIn) { } - /**+ - * Typically "menu.convertingLevel", "menu.loadingLevel" or - * others. + protected ServerCommandManager createNewCommandManager() { + return new ServerCommandManager(); + } + + /** + * + WARNING : directly calls + * getActiveAnvilConverter().deleteWorldDirectory(theWorldServer[0].getSaveHandler().getWorldDirectoryName()); */ - protected synchronized void setUserMessage(String message) { - this.userMessage = message; + public void deleteWorldAndStopServer() { + this.worldIsBeingDeleted = true; + this.initiateShutdown(); + } + + public void enableProfiling() { + this.startProfiling = true; + } + + /** + * + Called on exit from the main run() loop. + */ + protected void finalTick(CrashReport var1) { + } + + public abstract boolean func_181034_q(); + + public abstract boolean func_181035_ah(); + + public abstract boolean func_183002_r(); + + public boolean getAllowNether() { + return true; + } + + /** + * + Returns an array of the usernames of all the connected players. + */ + public String[] getAllUsernames() { + return this.serverConfigManager.getAllUsernames(); + } + + public int getBuildLimit() { + return this.buildLimit; + } + + public boolean getCanSpawnAnimals() { + return this.canSpawnAnimals; + } + + public boolean getCanSpawnNPCs() { + return this.canSpawnNPCs; + } + + public ICommandManager getCommandManager() { + return this.commandManager; + } + + /** + * + Returns the entity associated with the command sender. MAY BE NULL! + */ + public Entity getCommandSenderEntity() { + return null; + } + + public ServerConfigurationManager getConfigurationManager() { + return this.serverConfigManager; + } + + /** + * + Returns the number of players currently on the server. + */ + public int getCurrentPlayerCount() { + return this.serverConfigManager.getCurrentPlayerCount(); + } + + public abstract EnumDifficulty getDifficulty(); + + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return new ChatComponentText(this.getName()); + } + + public Entity getEntityFromUuid(EaglercraftUUID uuid) { + for (int i = 0; i < this.worldServers.length; ++i) { + WorldServer worldserver = this.worldServers[i]; + if (worldserver != null) { + Entity entity = worldserver.getEntityFromUuid(uuid); + if (entity != null) { + return entity; + } + } + } + + return null; + } + + /** + * + Get the world, if available. {@code null} is not allowed! If you are + * not an entity in the world, return the overworld + */ + public World getEntityWorld() { + return this.worldServers[0]; + } + + public String getFolderName() { + return this.worldName; + } + + public boolean getForceGamemode() { + return this.isGamemodeForced; + } + + /** + * + Returns an array of the GameProfiles of all the connected players + */ + public GameProfile[] getGameProfiles() { + return this.serverConfigManager.getAllProfiles(); + } + + public abstract WorldSettings.GameType getGameType(); + + public boolean getGuiEnabled() { + return false; + } + + public int getMaxPlayerIdleMinutes() { + return this.maxPlayerIdleMinutes; + } + + /** + * + Returns the maximum number of players allowed on the server. + */ + public int getMaxPlayers() { + return this.serverConfigManager.getMaxPlayers(); + } + + public int getMaxWorldSize() { + return 29999984; + } + + /** + * + Returns the server's Minecraft version as string. + */ + public String getMinecraftVersion() { + return "1.8.8"; + } + + public String getMOTD() { + return this.motd; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return "Server"; + } + + /** + * + The compression treshold. If the packet is larger than the specified amount + * of bytes, it will be compressed + */ + public int getNetworkCompressionTreshold() { + return 256; + } + + public abstract int getOpPermissionLevel(); + + public boolean getPaused() { + return paused; + } + + /** + * + Get the position in the world. {@code null} is not allowed! If you + * are not an entity in the world, return the coordinates 0, 0, 0 + */ + public BlockPos getPosition() { + return BlockPos.ORIGIN; + } + + /** + * + Get the position vector. {@code null} is not allowed! If you are not + * an entity in the world, return 0.0D, 0.0D, 0.0D + */ + public Vec3 getPositionVector() { + return new Vec3(0.0D, 0.0D, 0.0D); + } + + public String getResourcePackHash() { + return this.resourcePackHash; + } + + public String getResourcePackUrl() { + return this.resourcePackUrl; + } + + public String getServerModName() { + return "eagler"; + } + + /** + * + Returns the username of the server owner (for integrated servers) + */ + public String getServerOwner() { + return this.serverOwner; + } + + /** + * + Return the spawn protection area's size. + */ + public int getSpawnProtectionSize() { + return 16; + } + + public List getTabCompletions(ICommandSender sender, String input, BlockPos pos) { + ArrayList arraylist = Lists.newArrayList(); + if (input.startsWith("/")) { + input = input.substring(1); + boolean flag = !input.contains(" "); + List list = this.commandManager.getTabCompletionOptions(sender, input, pos); + if (list != null) { + for (int i = 0, l = list.size(); i < l; ++i) { + String s2 = list.get(i); + if (flag) { + arraylist.add("/" + s2); + } else { + arraylist.add(s2); + } + } + } + + return arraylist; + } else { + String[] astring = input.split(" ", -1); + String s = astring[astring.length - 1]; + String[] unames = this.serverConfigManager.getAllUsernames(); + for (int i = 0; i < unames.length; ++i) { + String s1 = unames[i]; + if (CommandBase.doesStringStartWith(s, s1)) { + arraylist.add(s1); + } + } + + return arraylist; + } + } + + public int getTickCounter() { + return this.tickCounter; } public synchronized String getUserMessage() { return this.userMessage; } + public String getWorldName() { + return this.worldName; + } + + protected void initialWorldChunkLoad() { + boolean flag = true; + boolean flag1 = true; + boolean flag2 = true; + boolean flag3 = true; + int i = 0; + this.setUserMessage("menu.generatingTerrain"); + byte b0 = 0; + logger.info("Preparing start region for level " + b0); + WorldServer worldserver = this.worldServers[b0]; + BlockPos blockpos = worldserver.getSpawnPoint(); + long j = getCurrentTimeMillis(); + + for (int k = -192; k <= 192; k += 16) { + for (int l = -192; l <= 192; l += 16) { + long i1 = getCurrentTimeMillis(); + if (i1 - j > 1000L) { + this.outputPercentRemaining("Preparing spawn area", i * 100 / 625); + j = i1; + } + + ++i; + worldserver.theChunkProviderServer.loadChunk(blockpos.getX() + k >> 4, blockpos.getZ() + l >> 4); + } + } + + this.clearCurrentTask(); + } + + /** + * + Sets the serverRunning variable to false, in order to get the server to + * shut down. + */ + public void initiateShutdown() { + this.serverRunning = false; + } + + public boolean isAnnouncingPlayerAchievements() { + return true; + } + + public boolean isBlockProtected(World var1, BlockPos var2, EntityPlayer var3) { + return false; + } + + public boolean isCallingFromMinecraftThread() { + return true; + } + + public abstract boolean isCommandBlockEnabled(); + + public abstract boolean isDedicatedServer(); + + /** + * + Gets whether this is a demo or not. + */ + public boolean isDemo() { + return this.isDemo; + } + + public boolean isFlightAllowed() { + return this.allowFlight; + } + + public abstract boolean isHardcore(); + + public boolean isPVPEnabled() { + return this.pvpEnabled; + } + + public boolean isServerInOnlineMode() { + return this.onlineMode; + } + + public boolean isServerRunning() { + return this.serverRunning; + } + + public boolean isServerStopped() { + return this.serverStopped; + } + + public boolean isSinglePlayer() { + return this.serverOwner != null; + } + + /** + * + Returns whether snooping is enabled or not. + */ + public boolean isSnooperEnabled() { + return true; + } + protected void loadAllWorlds(ISaveHandler isavehandler, String s1, WorldSettings worldsettings) { this.setUserMessage("menu.loadingLevel"); this.worldServers = new WorldServer[3]; @@ -211,72 +620,15 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre } } - protected void initialWorldChunkLoad() { - boolean flag = true; - boolean flag1 = true; - boolean flag2 = true; - boolean flag3 = true; - int i = 0; - this.setUserMessage("menu.generatingTerrain"); - byte b0 = 0; - logger.info("Preparing start region for level " + b0); - WorldServer worldserver = this.worldServers[b0]; - BlockPos blockpos = worldserver.getSpawnPoint(); - long j = getCurrentTimeMillis(); - - for (int k = -192; k <= 192; k += 16) { - for (int l = -192; l <= 192; l += 16) { - long i1 = getCurrentTimeMillis(); - if (i1 - j > 1000L) { - this.outputPercentRemaining("Preparing spawn area", i * 100 / 625); - j = i1; - } - - ++i; - worldserver.theChunkProviderServer.loadChunk(blockpos.getX() + k >> 4, blockpos.getZ() + l >> 4); - } - } - - this.clearCurrentTask(); + /** + * + Logs the message with a level of WARN. + */ + public void logWarning(String s) { + logger.warn(s); } - protected void unloadSpawnChunks() { - WorldServer worldserver = this.worldServers[0]; - BlockPos blockpos = worldserver.getSpawnPoint(); - int cnt = 0; - - for (int k = -192; k <= 192 && this.isServerRunning(); k += 16) { - for (int l = -192; l <= 192 && this.isServerRunning(); l += 16) { - Chunk chunk = worldserver.theChunkProviderServer.loadChunk(blockpos.getX() + k >> 4, - blockpos.getZ() + l >> 4); - if (chunk != null - && !worldserver.getPlayerManager().hasPlayerInstance(chunk.xPosition, chunk.zPosition)) { - worldserver.theChunkProviderServer.dropChunk(chunk.xPosition, chunk.zPosition); - ++cnt; - } - } - } - - logger.info("Dropped {} spawn chunks with no players in them", cnt); - } - - public abstract boolean canStructuresSpawn(); - - public abstract WorldSettings.GameType getGameType(); - - public abstract EnumDifficulty getDifficulty(); - - public abstract boolean isHardcore(); - - public abstract int getOpPermissionLevel(); - - public abstract boolean func_181034_q(); - - public abstract boolean func_183002_r(); - - /**+ - * Used to display a percent remaining given text and the - * percentage. + /** + * + Used to display a percent remaining given text and the percentage. */ protected void outputPercentRemaining(String parString1, int parInt1) { this.currentTask = parString1; @@ -285,93 +637,8 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.startingIntegratedServer", parInt1 * 0.01f); } - /**+ - * Set current task to null and set its percentage to 0. - */ - protected void clearCurrentTask() { - this.currentTask = null; - this.percentDone = 0; - } - - /**+ - * par1 indicates if a log message should be output. - */ - public void saveAllWorlds(boolean dontLog) { - if (!this.worldIsBeingDeleted) { - for (int i = 0; i < this.worldServers.length; ++i) { - WorldServer worldserver = this.worldServers[i]; - if (worldserver != null) { - if (!dontLog) { - logger.info("Saving chunks for level \'" + worldserver.getWorldInfo().getWorldName() + "\'/" - + worldserver.provider.getDimensionName()); - } - - try { - worldserver.saveAllChunks(true, (IProgressUpdate) null); - } catch (MinecraftException minecraftexception) { - logger.warn(minecraftexception.getMessage()); - } - } - } - - } - } - - /**+ - * Saves all necessary data as preparation for stopping the - * server. - */ - public void stopServer() { - if (!this.worldIsBeingDeleted) { - logger.info("Stopping server"); - - if (this.serverConfigManager != null) { - logger.info("Saving players"); - this.serverConfigManager.saveAllPlayerData(); - this.serverConfigManager.removeAllPlayers(); - } - - if (this.worldServers != null) { - logger.info("Saving worlds"); - this.saveAllWorlds(false); - - for (int i = 0; i < this.worldServers.length; ++i) { - WorldServer worldserver = this.worldServers[i]; - worldserver.flush(); - } - } - } else { - logger.info("Stopping server without saving"); - String str = getFolderName(); - logger.info("Deleting world \"{}\"...", str); - EaglerIntegratedServerWorker.saveFormat.deleteWorldDirectory(str); - logger.info("Deletion successful!"); - } - } - - /**+ - * WARNING : directly calls - * getActiveAnvilConverter().deleteWorldDirectory(theWorldServer[0].getSaveHandler().getWorldDirectoryName()); - */ - public void deleteWorldAndStopServer() { - this.worldIsBeingDeleted = true; - this.initiateShutdown(); - } - - public boolean isServerRunning() { - return this.serverRunning; - } - - /**+ - * Sets the serverRunning variable to false, in order to get the - * server to shut down. - */ - public void initiateShutdown() { - this.serverRunning = false; - } - - protected void setInstance() { - mcServer = this; + public void refreshStatusNextTick() { + this.nanoTimeSinceStatusRefresh = 0L; } public void run() { @@ -439,20 +706,207 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre } - /**+ - * Called on exit from the main run() loop. + /** + * + par1 indicates if a log message should be output. */ - protected void finalTick(CrashReport var1) { + public void saveAllWorlds(boolean dontLog) { + if (!this.worldIsBeingDeleted) { + for (int i = 0; i < this.worldServers.length; ++i) { + WorldServer worldserver = this.worldServers[i]; + if (worldserver != null) { + if (!dontLog) { + logger.info("Saving chunks for level \'" + worldserver.getWorldInfo().getWorldName() + "\'/" + + worldserver.provider.getDimensionName()); + } + + try { + worldserver.saveAllChunks(true, (IProgressUpdate) null); + } catch (MinecraftException minecraftexception) { + logger.warn(minecraftexception.getMessage()); + } + } + } + + } } - /**+ - * Directly calls System.exit(0), instantly killing the program. + /** + * + Returns true if the command sender should be sent feedback about executed + * commands + */ + public boolean sendCommandFeedback() { + /** + * + Gets mcServer. + */ + return getServer().worldServers[0].getGameRules().getBoolean("sendCommandFeedback"); + } + + public boolean serverIsInRunLoop() { + return this.serverIsRunning; + } + + public void setAllowFlight(boolean allow) { + this.allowFlight = allow; + } + + public void setAllowPvp(boolean allowPvp) { + this.pvpEnabled = allowPvp; + } + + public void setBuildLimit(int maxBuildHeight) { + this.buildLimit = maxBuildHeight; + } + + public void setCanSpawnAnimals(boolean spawnAnimals) { + this.canSpawnAnimals = spawnAnimals; + } + + public void setCanSpawnNPCs(boolean spawnNpcs) { + this.canSpawnNPCs = spawnNpcs; + } + + public void setCommandStat(CommandResultStats.Type var1, int var2) { + } + + public void setConfigManager(ServerConfigurationManager configManager) { + this.serverConfigManager = configManager; + } + + /** + * + Sets whether this is a demo or not. + */ + public void setDemo(boolean demo) { + this.isDemo = demo; + } + + public void setDifficultyForAllWorlds(EnumDifficulty enumdifficulty) { + for (int i = 0; i < this.worldServers.length; ++i) { + WorldServer worldserver = this.worldServers[i]; + if (worldserver != null) { + if (worldserver.getWorldInfo().isHardcoreModeEnabled()) { + worldserver.getWorldInfo().setDifficulty(EnumDifficulty.HARD); + worldserver.setAllowedSpawnTypes(true, true); + } else if (this.isSinglePlayer()) { + worldserver.getWorldInfo().setDifficulty(enumdifficulty); + worldserver.setAllowedSpawnTypes(worldserver.getDifficulty() != EnumDifficulty.PEACEFUL, true); + } else { + worldserver.getWorldInfo().setDifficulty(enumdifficulty); + worldserver.setAllowedSpawnTypes(this.allowSpawnMonsters(), this.canSpawnAnimals); + } + } + } + this.getConfigurationManager().sendPacketToAllPlayers(new S41PacketServerDifficulty( + this.worldServers[0].getDifficulty(), this.worldServers[0].getWorldInfo().isDifficultyLocked())); + } + + public void setDifficultyLockedForAllWorlds(boolean locked) { + for (int i = 0; i < this.worldServers.length; ++i) { + WorldServer worldserver = this.worldServers[i]; + if (worldserver != null) { + worldserver.getWorldInfo().setDifficultyLocked(locked); + } + } + + } + + /** + * + Sets the game type for all worlds. + */ + public void setGameType(WorldSettings.GameType worldsettings$gametype) { + for (int i = 0; i < this.worldServers.length; ++i) { + getServer().worldServers[i].getWorldInfo().setGameType(worldsettings$gametype); + } + + } + + protected void setInstance() { + mcServer = this; + } + + public void setMOTD(String motdIn) { + this.motd = motdIn; + } + + public void setOnlineMode(boolean online) { + this.onlineMode = online; + } + + public void setPaused(boolean pause) { + this.paused = pause; + } + + public void setPlayerIdleTimeout(int i) { + this.maxPlayerIdleMinutes = i; + } + + public void setResourcePack(String parString1, String parString2) { + this.resourcePackUrl = parString1; + this.resourcePackHash = parString2; + } + + /** + * + Sets the username of the owner of this server (in the case of an integrated + * server) + */ + public void setServerOwner(String owner) { + this.serverOwner = owner; + } + + /** + * + Typically "menu.convertingLevel", "menu.loadingLevel" or others. + */ + protected synchronized void setUserMessage(String message) { + this.userMessage = message; + } + + public abstract String shareToLAN(WorldSettings.GameType var1, boolean var2); + + protected abstract boolean startServer() throws IOException; + + public void startServerThread() { + this.serverThread = new Thread(this, "Server thread"); + this.serverThread.start(); + } + + /** + * + Saves all necessary data as preparation for stopping the server. + */ + public void stopServer() { + if (!this.worldIsBeingDeleted) { + logger.info("Stopping server"); + + if (this.serverConfigManager != null) { + logger.info("Saving players"); + this.serverConfigManager.saveAllPlayerData(); + this.serverConfigManager.removeAllPlayers(); + } + + if (this.worldServers != null) { + logger.info("Saving worlds"); + this.saveAllWorlds(false); + + for (int i = 0; i < this.worldServers.length; ++i) { + WorldServer worldserver = this.worldServers[i]; + worldserver.flush(); + } + } + } else { + logger.info("Stopping server without saving"); + String str = getFolderName(); + logger.info("Deleting world \"{}\"...", str); + EaglerIntegratedServerWorker.saveFormat.deleteWorldDirectory(str); + logger.info("Deletion successful!"); + } + } + + /** + * + Directly calls System.exit(0), instantly killing the program. */ protected void systemExitNow() { } - /**+ - * Main function called by run() every loop. + /** + * + Main function called by run() every loop. */ public void tick() { long i = EagRuntime.nanoTime(); @@ -482,6 +936,26 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre this.tickTimeArray[this.tickCounter % 100] = EagRuntime.nanoTime() - i; } + protected void unloadSpawnChunks() { + WorldServer worldserver = this.worldServers[0]; + BlockPos blockpos = worldserver.getSpawnPoint(); + int cnt = 0; + + for (int k = -192; k <= 192 && this.isServerRunning(); k += 16) { + for (int l = -192; l <= 192 && this.isServerRunning(); l += 16) { + Chunk chunk = worldserver.theChunkProviderServer.loadChunk(blockpos.getX() + k >> 4, + blockpos.getZ() + l >> 4); + if (chunk != null + && !worldserver.getPlayerManager().hasPlayerInstance(chunk.xPosition, chunk.zPosition)) { + worldserver.theChunkProviderServer.dropChunk(chunk.xPosition, chunk.zPosition); + ++cnt; + } + } + } + + logger.info("Dropped {} spawn chunks with no players in them", cnt); + } + public void updateTimeLightAndEntities() { synchronized (this.futureTaskQueue) { while (!this.futureTaskQueue.isEmpty()) { @@ -531,489 +1005,10 @@ public abstract class MinecraftServer implements Runnable, ICommandSender, IThre } } - public boolean getAllowNether() { - return true; - } - - public void startServerThread() { - this.serverThread = new Thread(this, "Server thread"); - this.serverThread.start(); - } - - /**+ - * Logs the message with a level of WARN. - */ - public void logWarning(String s) { - logger.warn(s); - } - - /**+ - * Gets the worldServer by the given dimension. + /** + * + Gets the worldServer by the given dimension. */ public WorldServer worldServerForDimension(int dimension) { return dimension == -1 ? this.worldServers[1] : (dimension == 1 ? this.worldServers[2] : this.worldServers[0]); } - - /**+ - * Returns the server's Minecraft version as string. - */ - public String getMinecraftVersion() { - return "1.8.8"; - } - - /**+ - * Returns the number of players currently on the server. - */ - public int getCurrentPlayerCount() { - return this.serverConfigManager.getCurrentPlayerCount(); - } - - /**+ - * Returns the maximum number of players allowed on the server. - */ - public int getMaxPlayers() { - return this.serverConfigManager.getMaxPlayers(); - } - - /**+ - * Returns an array of the usernames of all the connected - * players. - */ - public String[] getAllUsernames() { - return this.serverConfigManager.getAllUsernames(); - } - - /**+ - * Returns an array of the GameProfiles of all the connected - * players - */ - public GameProfile[] getGameProfiles() { - return this.serverConfigManager.getAllProfiles(); - } - - public String getServerModName() { - return "eagler"; - } - - /**+ - * Adds the server info, including from theWorldServer, to the - * crash report. - */ - public CrashReport addServerInfoToCrashReport(CrashReport crashreport) { - crashreport.getCategory().addCrashSectionCallable("Profiler Position", new Callable() { - public String call() throws Exception { - return "N/A (disabled)"; - } - }); - if (this.serverConfigManager != null) { - crashreport.getCategory().addCrashSectionCallable("Player Count", new Callable() { - public String call() { - return MinecraftServer.this.serverConfigManager.getCurrentPlayerCount() + " / " - + MinecraftServer.this.serverConfigManager.getMaxPlayers() + "; " - + MinecraftServer.this.serverConfigManager.func_181057_v(); - } - }); - } - - return crashreport; - } - - public List getTabCompletions(ICommandSender sender, String input, BlockPos pos) { - ArrayList arraylist = Lists.newArrayList(); - if (input.startsWith("/")) { - input = input.substring(1); - boolean flag = !input.contains(" "); - List list = this.commandManager.getTabCompletionOptions(sender, input, pos); - if (list != null) { - for (int i = 0, l = list.size(); i < l; ++i) { - String s2 = list.get(i); - if (flag) { - arraylist.add("/" + s2); - } else { - arraylist.add(s2); - } - } - } - - return arraylist; - } else { - String[] astring = input.split(" ", -1); - String s = astring[astring.length - 1]; - String[] unames = this.serverConfigManager.getAllUsernames(); - for (int i = 0; i < unames.length; ++i) { - String s1 = unames[i]; - if (CommandBase.doesStringStartWith(s, s1)) { - arraylist.add(s1); - } - } - - return arraylist; - } - } - - /**+ - * Gets mcServer. - */ - public static MinecraftServer getServer() { - return mcServer; - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return "Server"; - } - - /**+ - * Send a chat message to the CommandSender - */ - public void addChatMessage(IChatComponent ichatcomponent) { - logger.info(ichatcomponent.getUnformattedText()); - } - - /**+ - * Returns {@code true} if the CommandSender is allowed to - * execute the command, {@code false} if not - */ - public boolean canCommandSenderUseCommand(int var1, String var2) { - return true; - } - - public ICommandManager getCommandManager() { - return this.commandManager; - } - - /**+ - * Returns the username of the server owner (for integrated - * servers) - */ - public String getServerOwner() { - return this.serverOwner; - } - - /**+ - * Sets the username of the owner of this server (in the case of - * an integrated server) - */ - public void setServerOwner(String owner) { - this.serverOwner = owner; - } - - public boolean isSinglePlayer() { - return this.serverOwner != null; - } - - public String getFolderName() { - return this.worldName; - } - - public String getWorldName() { - return this.worldName; - } - - public void setDifficultyForAllWorlds(EnumDifficulty enumdifficulty) { - for (int i = 0; i < this.worldServers.length; ++i) { - WorldServer worldserver = this.worldServers[i]; - if (worldserver != null) { - if (worldserver.getWorldInfo().isHardcoreModeEnabled()) { - worldserver.getWorldInfo().setDifficulty(EnumDifficulty.HARD); - worldserver.setAllowedSpawnTypes(true, true); - } else if (this.isSinglePlayer()) { - worldserver.getWorldInfo().setDifficulty(enumdifficulty); - worldserver.setAllowedSpawnTypes(worldserver.getDifficulty() != EnumDifficulty.PEACEFUL, true); - } else { - worldserver.getWorldInfo().setDifficulty(enumdifficulty); - worldserver.setAllowedSpawnTypes(this.allowSpawnMonsters(), this.canSpawnAnimals); - } - } - } - this.getConfigurationManager().sendPacketToAllPlayers(new S41PacketServerDifficulty( - this.worldServers[0].getDifficulty(), this.worldServers[0].getWorldInfo().isDifficultyLocked())); - } - - public void setDifficultyLockedForAllWorlds(boolean locked) { - for (int i = 0; i < this.worldServers.length; ++i) { - WorldServer worldserver = this.worldServers[i]; - if (worldserver != null) { - worldserver.getWorldInfo().setDifficultyLocked(locked); - } - } - - } - - protected boolean allowSpawnMonsters() { - return true; - } - - /**+ - * Gets whether this is a demo or not. - */ - public boolean isDemo() { - return this.isDemo; - } - - /**+ - * Sets whether this is a demo or not. - */ - public void setDemo(boolean demo) { - this.isDemo = demo; - } - - public void canCreateBonusChest(boolean enable) { - this.enableBonusChest = enable; - } - - public String getResourcePackUrl() { - return this.resourcePackUrl; - } - - public String getResourcePackHash() { - return this.resourcePackHash; - } - - public void setResourcePack(String parString1, String parString2) { - this.resourcePackUrl = parString1; - this.resourcePackHash = parString2; - } - - /**+ - * Returns whether snooping is enabled or not. - */ - public boolean isSnooperEnabled() { - return true; - } - - public abstract boolean isDedicatedServer(); - - public boolean isServerInOnlineMode() { - return this.onlineMode; - } - - public void setOnlineMode(boolean online) { - this.onlineMode = online; - } - - public boolean getCanSpawnAnimals() { - return this.canSpawnAnimals; - } - - public void setCanSpawnAnimals(boolean spawnAnimals) { - this.canSpawnAnimals = spawnAnimals; - } - - public boolean getCanSpawnNPCs() { - return this.canSpawnNPCs; - } - - public abstract boolean func_181035_ah(); - - public void setCanSpawnNPCs(boolean spawnNpcs) { - this.canSpawnNPCs = spawnNpcs; - } - - public boolean isPVPEnabled() { - return this.pvpEnabled; - } - - public void setAllowPvp(boolean allowPvp) { - this.pvpEnabled = allowPvp; - } - - public boolean isFlightAllowed() { - return this.allowFlight; - } - - public void setAllowFlight(boolean allow) { - this.allowFlight = allow; - } - - public abstract boolean isCommandBlockEnabled(); - - public String getMOTD() { - return this.motd; - } - - public void setMOTD(String motdIn) { - this.motd = motdIn; - } - - public int getBuildLimit() { - return this.buildLimit; - } - - public void setBuildLimit(int maxBuildHeight) { - this.buildLimit = maxBuildHeight; - } - - public boolean isServerStopped() { - return this.serverStopped; - } - - public ServerConfigurationManager getConfigurationManager() { - return this.serverConfigManager; - } - - public void setConfigManager(ServerConfigurationManager configManager) { - this.serverConfigManager = configManager; - } - - /**+ - * Sets the game type for all worlds. - */ - public void setGameType(WorldSettings.GameType worldsettings$gametype) { - for (int i = 0; i < this.worldServers.length; ++i) { - getServer().worldServers[i].getWorldInfo().setGameType(worldsettings$gametype); - } - - } - - public boolean serverIsInRunLoop() { - return this.serverIsRunning; - } - - public boolean getGuiEnabled() { - return false; - } - - public abstract String shareToLAN(WorldSettings.GameType var1, boolean var2); - - public int getTickCounter() { - return this.tickCounter; - } - - public void enableProfiling() { - this.startProfiling = true; - } - - /**+ - * Get the position in the world. {@code null} is not - * allowed! If you are not an entity in the world, return - * the coordinates 0, 0, 0 - */ - public BlockPos getPosition() { - return BlockPos.ORIGIN; - } - - /**+ - * Get the position vector. {@code null} is not allowed! - * If you are not an entity in the world, return 0.0D, 0.0D, - * 0.0D - */ - public Vec3 getPositionVector() { - return new Vec3(0.0D, 0.0D, 0.0D); - } - - /**+ - * Get the world, if available. {@code null} is not - * allowed! If you are not an entity in the world, return - * the overworld - */ - public World getEntityWorld() { - return this.worldServers[0]; - } - - /**+ - * Returns the entity associated with the command sender. MAY BE - * NULL! - */ - public Entity getCommandSenderEntity() { - return null; - } - - /**+ - * Return the spawn protection area's size. - */ - public int getSpawnProtectionSize() { - return 16; - } - - public boolean isBlockProtected(World var1, BlockPos var2, EntityPlayer var3) { - return false; - } - - public boolean getForceGamemode() { - return this.isGamemodeForced; - } - - public static long getCurrentTimeMillis() { - return EagRuntime.steadyTimeMillis(); - } - - public int getMaxPlayerIdleMinutes() { - return this.maxPlayerIdleMinutes; - } - - public void setPlayerIdleTimeout(int i) { - this.maxPlayerIdleMinutes = i; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return new ChatComponentText(this.getName()); - } - - public boolean isAnnouncingPlayerAchievements() { - return true; - } - - public void refreshStatusNextTick() { - this.nanoTimeSinceStatusRefresh = 0L; - } - - public Entity getEntityFromUuid(EaglercraftUUID uuid) { - for (int i = 0; i < this.worldServers.length; ++i) { - WorldServer worldserver = this.worldServers[i]; - if (worldserver != null) { - Entity entity = worldserver.getEntityFromUuid(uuid); - if (entity != null) { - return entity; - } - } - } - - return null; - } - - /**+ - * Returns true if the command sender should be sent feedback - * about executed commands - */ - public boolean sendCommandFeedback() { - /**+ - * Gets mcServer. - */ - return getServer().worldServers[0].getGameRules().getBoolean("sendCommandFeedback"); - } - - public void setCommandStat(CommandResultStats.Type var1, int var2) { - } - - public int getMaxWorldSize() { - return 29999984; - } - - public boolean isCallingFromMinecraftThread() { - return true; - } - - /**+ - * The compression treshold. If the packet is larger than the - * specified amount of bytes, it will be compressed - */ - public int getNetworkCompressionTreshold() { - return 256; - } - - public void setPaused(boolean pause) { - this.paused = pause; - } - - public boolean getPaused() { - return paused; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/server/management/ItemInWorldManager.java b/src/game/java/net/minecraft/server/management/ItemInWorldManager.java index de6f2a5c..027ca1e5 100644 --- a/src/game/java/net/minecraft/server/management/ItemInWorldManager.java +++ b/src/game/java/net/minecraft/server/management/ItemInWorldManager.java @@ -20,22 +20,25 @@ import net.minecraft.world.World; import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -57,31 +60,90 @@ public class ItemInWorldManager { this.theWorld = worldIn; } - public void setGameType(WorldSettings.GameType type) { - this.gameType = type; - type.configurePlayerCapabilities(this.thisPlayerMP.capabilities); - this.thisPlayerMP.sendPlayerAbilities(); - this.thisPlayerMP.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S38PacketPlayerListItem( - S38PacketPlayerListItem.Action.UPDATE_GAME_MODE, new EntityPlayerMP[] { this.thisPlayerMP })); + /** + * + Activate the clicked on block, otherwise use the held item. + */ + public boolean activateBlockOrUseItem(EntityPlayer entityplayer, World world, ItemStack itemstack, + BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { + if (this.gameType == WorldSettings.GameType.SPECTATOR) { + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof ILockableContainer) { + Block block = world.getBlockState(blockpos).getBlock(); + ILockableContainer ilockablecontainer = (ILockableContainer) tileentity; + if (ilockablecontainer instanceof TileEntityChest && block instanceof BlockChest) { + ilockablecontainer = ((BlockChest) block).getLockableContainer(world, blockpos); + } + + if (ilockablecontainer != null) { + entityplayer.displayGUIChest(ilockablecontainer); + return true; + } + } else if (tileentity instanceof IInventory) { + entityplayer.displayGUIChest((IInventory) tileentity); + return true; + } + + return false; + } else { + if (!entityplayer.isSneaking() || entityplayer.getHeldItem() == null) { + IBlockState iblockstate = world.getBlockState(blockpos); + if (iblockstate.getBlock().onBlockActivated(world, blockpos, iblockstate, entityplayer, enumfacing, f, + f1, f2)) { + return true; + } + } + + if (itemstack == null) { + return false; + } else if (this.isCreative()) { + int j = itemstack.getMetadata(); + int i = itemstack.stackSize; + boolean flag = itemstack.onItemUse(entityplayer, world, blockpos, enumfacing, f, f1, f2); + itemstack.setItemDamage(j); + itemstack.stackSize = i; + return flag; + } else { + return itemstack.onItemUse(entityplayer, world, blockpos, enumfacing, f, f1, f2); + } + } + } + + public void blockRemoving(BlockPos blockpos) { + if (blockpos.equals(this.field_180240_f)) { + int i = this.curblockDamage - this.initialDamage; + Block block = this.theWorld.getBlockState(blockpos).getBlock(); + if (block.getMaterial() != Material.air) { + float f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, blockpos) + * (float) (i + 1); + if (f >= 0.7F) { + this.isDestroyingBlock = false; + this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), blockpos, -1); + this.tryHarvestBlock(blockpos); + } else if (!this.receivedFinishDiggingPacket) { + this.isDestroyingBlock = false; + this.receivedFinishDiggingPacket = true; + this.field_180241_i = blockpos; + this.initialBlockDamage = this.initialDamage; + } + } + } + + } + + /** + * + Stops the block breaking process + */ + public void cancelDestroyingBlock() { + this.isDestroyingBlock = false; + this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, -1); } public WorldSettings.GameType getGameType() { return this.gameType; } - public boolean survivalOrAdventure() { - return this.gameType.isSurvivalOrAdventure(); - } - - /**+ - * Get if we are in creative game mode. - */ - public boolean isCreative() { - return this.gameType.isCreative(); - } - - /**+ - * if the gameType is currently NOT_SET then change it to par1 + /** + * + if the gameType is currently NOT_SET then change it to par1 */ public void initializeGameType(WorldSettings.GameType type) { if (this.gameType == WorldSettings.GameType.NOT_SET) { @@ -91,51 +153,16 @@ public class ItemInWorldManager { this.setGameType(this.gameType); } - public void updateBlockRemoving() { - ++this.curblockDamage; - if (this.receivedFinishDiggingPacket) { - int i = this.curblockDamage - this.initialBlockDamage; - Block block = this.theWorld.getBlockState(this.field_180241_i).getBlock(); - if (block.getMaterial() == Material.air) { - this.receivedFinishDiggingPacket = false; - } else { - float f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, - this.field_180241_i) * (float) (i + 1); - int j = (int) (f * 10.0F); - if (j != this.durabilityRemainingOnBlock) { - this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180241_i, j); - this.durabilityRemainingOnBlock = j; - } - - if (f >= 1.0F) { - this.receivedFinishDiggingPacket = false; - this.tryHarvestBlock(this.field_180241_i); - } - } - } else if (this.isDestroyingBlock) { - Block block1 = this.theWorld.getBlockState(this.field_180240_f).getBlock(); - if (block1.getMaterial() == Material.air) { - this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, -1); - this.durabilityRemainingOnBlock = -1; - this.isDestroyingBlock = false; - } else { - int k = this.curblockDamage - this.initialDamage; - float f1 = block1.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, - this.field_180241_i) * (float) (k + 1); - int l = (int) (f1 * 10.0F); - if (l != this.durabilityRemainingOnBlock) { - this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, l); - this.durabilityRemainingOnBlock = l; - } - } - } - + /** + * + Get if we are in creative game mode. + */ + public boolean isCreative() { + return this.gameType.isCreative(); } - /**+ - * If not creative, it calls sendBlockBreakProgress until the - * block is broken first. tryHarvestBlock can also be the result - * of this call. + /** + * + If not creative, it calls sendBlockBreakProgress until the block is broken + * first. tryHarvestBlock can also be the result of this call. */ public void onBlockClicked(BlockPos blockpos, EnumFacing enumfacing) { if (this.isCreative()) { @@ -183,38 +210,8 @@ public class ItemInWorldManager { } } - public void blockRemoving(BlockPos blockpos) { - if (blockpos.equals(this.field_180240_f)) { - int i = this.curblockDamage - this.initialDamage; - Block block = this.theWorld.getBlockState(blockpos).getBlock(); - if (block.getMaterial() != Material.air) { - float f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, blockpos) - * (float) (i + 1); - if (f >= 0.7F) { - this.isDestroyingBlock = false; - this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), blockpos, -1); - this.tryHarvestBlock(blockpos); - } else if (!this.receivedFinishDiggingPacket) { - this.isDestroyingBlock = false; - this.receivedFinishDiggingPacket = true; - this.field_180241_i = blockpos; - this.initialBlockDamage = this.initialDamage; - } - } - } - - } - - /**+ - * Stops the block breaking process - */ - public void cancelDestroyingBlock() { - this.isDestroyingBlock = false; - this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, -1); - } - - /**+ - * Removes a block and triggers the appropriate events + /** + * + Removes a block and triggers the appropriate events */ private boolean removeBlock(BlockPos pos) { IBlockState iblockstate = this.theWorld.getBlockState(pos); @@ -227,8 +224,27 @@ public class ItemInWorldManager { return flag; } - /**+ - * Attempts to harvest a block + public void setGameType(WorldSettings.GameType type) { + this.gameType = type; + type.configurePlayerCapabilities(this.thisPlayerMP.capabilities); + this.thisPlayerMP.sendPlayerAbilities(); + this.thisPlayerMP.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S38PacketPlayerListItem( + S38PacketPlayerListItem.Action.UPDATE_GAME_MODE, new EntityPlayerMP[] { this.thisPlayerMP })); + } + + /** + * + Sets the world instance. + */ + public void setWorld(WorldServer serverWorld) { + this.theWorld = serverWorld; + } + + public boolean survivalOrAdventure() { + return this.gameType.isSurvivalOrAdventure(); + } + + /** + * + Attempts to harvest a block */ public boolean tryHarvestBlock(BlockPos blockpos) { if (this.gameType.isCreative() && this.thisPlayerMP.getHeldItem() != null @@ -278,9 +294,9 @@ public class ItemInWorldManager { } } - /**+ - * Attempts to right-click use an item by the given EntityPlayer - * in the given World + /** + * + Attempts to right-click use an item by the given EntityPlayer in the given + * World */ public boolean tryUseItem(EntityPlayer entityplayer, World world, ItemStack itemstack) { if (this.gameType == WorldSettings.GameType.SPECTATOR) { @@ -314,58 +330,44 @@ public class ItemInWorldManager { } } - /**+ - * Activate the clicked on block, otherwise use the held item. - */ - public boolean activateBlockOrUseItem(EntityPlayer entityplayer, World world, ItemStack itemstack, - BlockPos blockpos, EnumFacing enumfacing, float f, float f1, float f2) { - if (this.gameType == WorldSettings.GameType.SPECTATOR) { - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof ILockableContainer) { - Block block = world.getBlockState(blockpos).getBlock(); - ILockableContainer ilockablecontainer = (ILockableContainer) tileentity; - if (ilockablecontainer instanceof TileEntityChest && block instanceof BlockChest) { - ilockablecontainer = ((BlockChest) block).getLockableContainer(world, blockpos); - } - - if (ilockablecontainer != null) { - entityplayer.displayGUIChest(ilockablecontainer); - return true; - } - } else if (tileentity instanceof IInventory) { - entityplayer.displayGUIChest((IInventory) tileentity); - return true; - } - - return false; - } else { - if (!entityplayer.isSneaking() || entityplayer.getHeldItem() == null) { - IBlockState iblockstate = world.getBlockState(blockpos); - if (iblockstate.getBlock().onBlockActivated(world, blockpos, iblockstate, entityplayer, enumfacing, f, - f1, f2)) { - return true; - } - } - - if (itemstack == null) { - return false; - } else if (this.isCreative()) { - int j = itemstack.getMetadata(); - int i = itemstack.stackSize; - boolean flag = itemstack.onItemUse(entityplayer, world, blockpos, enumfacing, f, f1, f2); - itemstack.setItemDamage(j); - itemstack.stackSize = i; - return flag; + public void updateBlockRemoving() { + ++this.curblockDamage; + if (this.receivedFinishDiggingPacket) { + int i = this.curblockDamage - this.initialBlockDamage; + Block block = this.theWorld.getBlockState(this.field_180241_i).getBlock(); + if (block.getMaterial() == Material.air) { + this.receivedFinishDiggingPacket = false; } else { - return itemstack.onItemUse(entityplayer, world, blockpos, enumfacing, f, f1, f2); + float f = block.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, + this.field_180241_i) * (float) (i + 1); + int j = (int) (f * 10.0F); + if (j != this.durabilityRemainingOnBlock) { + this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180241_i, j); + this.durabilityRemainingOnBlock = j; + } + + if (f >= 1.0F) { + this.receivedFinishDiggingPacket = false; + this.tryHarvestBlock(this.field_180241_i); + } + } + } else if (this.isDestroyingBlock) { + Block block1 = this.theWorld.getBlockState(this.field_180240_f).getBlock(); + if (block1.getMaterial() == Material.air) { + this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, -1); + this.durabilityRemainingOnBlock = -1; + this.isDestroyingBlock = false; + } else { + int k = this.curblockDamage - this.initialDamage; + float f1 = block1.getPlayerRelativeBlockHardness(this.thisPlayerMP, this.thisPlayerMP.worldObj, + this.field_180241_i) * (float) (k + 1); + int l = (int) (f1 * 10.0F); + if (l != this.durabilityRemainingOnBlock) { + this.theWorld.sendBlockBreakProgress(this.thisPlayerMP.getEntityId(), this.field_180240_f, l); + this.durabilityRemainingOnBlock = l; + } } } - } - /**+ - * Sets the world instance. - */ - public void setWorld(WorldServer serverWorld) { - this.theWorld = serverWorld; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/server/management/LowerStringMap.java b/src/game/java/net/minecraft/server/management/LowerStringMap.java index f514483b..26962004 100644 --- a/src/game/java/net/minecraft/server/management/LowerStringMap.java +++ b/src/game/java/net/minecraft/server/management/LowerStringMap.java @@ -6,22 +6,25 @@ import java.util.Set; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,12 +32,8 @@ import com.google.common.collect.Maps; public class LowerStringMap implements Map { private final Map internalMap = Maps.newLinkedHashMap(); - public int size() { - return this.internalMap.size(); - } - - public boolean isEmpty() { - return this.internalMap.isEmpty(); + public void clear() { + this.internalMap.clear(); } public boolean containsKey(Object parObject) { @@ -45,16 +44,24 @@ public class LowerStringMap implements Map { return this.internalMap.containsKey(parObject); } + public Set> entrySet() { + return this.internalMap.entrySet(); + } + public V get(Object parObject) { return (V) this.internalMap.get(parObject.toString().toLowerCase()); } - public V put(String parString1, V parObject) { - return (V) this.internalMap.put(parString1.toLowerCase(), parObject); + public boolean isEmpty() { + return this.internalMap.isEmpty(); } - public V remove(Object object) { - return (V) this.internalMap.remove(object.toString().toLowerCase()); + public Set keySet() { + return this.internalMap.keySet(); + } + + public V put(String parString1, V parObject) { + return (V) this.internalMap.put(parString1.toLowerCase(), parObject); } public void putAll(Map parMap) { @@ -64,19 +71,15 @@ public class LowerStringMap implements Map { } - public void clear() { - this.internalMap.clear(); + public V remove(Object object) { + return (V) this.internalMap.remove(object.toString().toLowerCase()); } - public Set keySet() { - return this.internalMap.keySet(); + public int size() { + return this.internalMap.size(); } public Collection values() { return this.internalMap.values(); } - - public Set> entrySet() { - return this.internalMap.entrySet(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/server/management/PlayerManager.java b/src/game/java/net/minecraft/server/management/PlayerManager.java index 8f4fbf63..5d8e36c9 100644 --- a/src/game/java/net/minecraft/server/management/PlayerManager.java +++ b/src/game/java/net/minecraft/server/management/PlayerManager.java @@ -1,8 +1,12 @@ package net.minecraft.server.management; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; + +import com.google.common.collect.Lists; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S21PacketChunkData; @@ -16,317 +20,31 @@ import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldServer; import net.minecraft.world.chunk.Chunk; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlayerManager { - private static final Logger pmLogger = LogManager.getLogger(); - private final WorldServer theWorldServer; - /**+ - * players in the current instance - */ - private final List players = Lists.newArrayList(); - /**+ - * the hash of all playerInstances created - */ - private final LongHashMap playerInstances = new LongHashMap(); - /**+ - * the playerInstances(chunks) that need to be updated - */ - private final List playerInstancesToUpdate = Lists.newArrayList(); - /**+ - * This field is using when chunk should be processed (every - * 8000 ticks) - */ - private final List playerInstanceList = Lists.newArrayList(); - private int playerViewRadius; - private long previousTotalWorldTime; - /**+ - * x, z direction vectors: east, south, west, north - */ - private final int[][] xzDirectionsConst = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; - - public PlayerManager(WorldServer serverWorld) { - this.theWorldServer = serverWorld; - this.setPlayerViewRadius(serverWorld.getMinecraftServer().getConfigurationManager().getViewDistance()); - } - - /**+ - * Returns the WorldServer associated with this PlayerManager - */ - public WorldServer getWorldServer() { - return this.theWorldServer; - } - - /**+ - * updates all the player instances that need to be updated - */ - public void updatePlayerInstances() { - long i = this.theWorldServer.getTotalWorldTime(); - if (i - this.previousTotalWorldTime > 8000L) { - this.previousTotalWorldTime = i; - - for (int j = 0; j < this.playerInstanceList.size(); ++j) { - PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance) this.playerInstanceList - .get(j); - playermanager$playerinstance.onUpdate(); - playermanager$playerinstance.processChunk(); - } - } else { - for (int k = 0; k < this.playerInstancesToUpdate.size(); ++k) { - PlayerManager.PlayerInstance playermanager$playerinstance1 = (PlayerManager.PlayerInstance) this.playerInstancesToUpdate - .get(k); - playermanager$playerinstance1.onUpdate(); - } - } - - this.playerInstancesToUpdate.clear(); - if (this.players.isEmpty()) { - WorldProvider worldprovider = this.theWorldServer.provider; - if (!worldprovider.canRespawnHere()) { - this.theWorldServer.theChunkProviderServer.unloadAllChunks(); - } - } - - } - - public boolean hasPlayerInstance(int chunkX, int chunkZ) { - long i = (long) chunkX + 2147483647L | (long) chunkZ + 2147483647L << 32; - return this.playerInstances.getValueByKey(i) != null; - } - - /**+ - * passi n the chunk x and y and a flag as to whether or not the - * instance should be made if it doesnt exist - */ - private PlayerManager.PlayerInstance getPlayerInstance(int chunkX, int chunkZ, boolean createIfAbsent) { - long i = (long) chunkX + 2147483647L | (long) chunkZ + 2147483647L << 32; - PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance) this.playerInstances - .getValueByKey(i); - if (playermanager$playerinstance == null && createIfAbsent) { - playermanager$playerinstance = new PlayerManager.PlayerInstance(chunkX, chunkZ); - this.playerInstances.add(i, playermanager$playerinstance); - this.playerInstanceList.add(playermanager$playerinstance); - } - - return playermanager$playerinstance; - } - - public void markBlockForUpdate(BlockPos pos) { - int i = pos.getX() >> 4; - int j = pos.getZ() >> 4; - PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(i, j, false); - if (playermanager$playerinstance != null) { - playermanager$playerinstance.flagChunkForUpdate(pos.getX() & 15, pos.getY(), pos.getZ() & 15); - } - - } - - /**+ - * Adds an EntityPlayerMP to the PlayerManager and to all player - * instances within player visibility - */ - public void addPlayer(EntityPlayerMP player) { - int i = (int) player.posX >> 4; - int j = (int) player.posZ >> 4; - player.managedPosX = player.posX; - player.managedPosZ = player.posZ; - - for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k) { - for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l) { - this.getPlayerInstance(k, l, true).addPlayer(player); - } - } - - this.players.add(player); - this.filterChunkLoadQueue(player); - } - - /**+ - * Removes all chunks from the given player's chunk load queue - * that are not in viewing range of the player. - */ - public void filterChunkLoadQueue(EntityPlayerMP player) { - ArrayList arraylist = Lists.newArrayList(player.loadedChunks); - int i = 0; - int j = this.playerViewRadius; - int k = (int) player.posX >> 4; - int l = (int) player.posZ >> 4; - int i1 = 0; - int j1 = 0; - ChunkCoordIntPair chunkcoordintpair = this.getPlayerInstance(k, l, true).chunkCoords; - player.loadedChunks.clear(); - if (arraylist.contains(chunkcoordintpair)) { - player.loadedChunks.add(chunkcoordintpair); - } - - for (int k1 = 1; k1 <= j * 2; ++k1) { - for (int l1 = 0; l1 < 2; ++l1) { - int[] aint = this.xzDirectionsConst[i++ % 4]; - - for (int i2 = 0; i2 < k1; ++i2) { - i1 += aint[0]; - j1 += aint[1]; - chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords; - if (arraylist.contains(chunkcoordintpair)) { - player.loadedChunks.add(chunkcoordintpair); - } - } - } - } - - i = i % 4; - - for (int j2 = 0; j2 < j * 2; ++j2) { - i1 += this.xzDirectionsConst[i][0]; - j1 += this.xzDirectionsConst[i][1]; - chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords; - if (arraylist.contains(chunkcoordintpair)) { - player.loadedChunks.add(chunkcoordintpair); - } - } - - } - - /**+ - * Removes an EntityPlayerMP from the PlayerManager. - */ - public void removePlayer(EntityPlayerMP player) { - int i = (int) player.managedPosX >> 4; - int j = (int) player.managedPosZ >> 4; - - for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k) { - for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l) { - PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(k, l, false); - if (playermanager$playerinstance != null) { - playermanager$playerinstance.removePlayer(player); - } - } - } - - this.players.remove(player); - } - - /**+ - * Determine if two rectangles centered at the given points - * overlap for the provided radius. Arguments: x1, z1, x2, z2, - * radius. - */ - private boolean overlaps(int x1, int z1, int x2, int z2, int radius) { - int i = x1 - x2; - int j = z1 - z2; - return i >= -radius && i <= radius ? j >= -radius && j <= radius : false; - } - - /**+ - * update chunks around a player being moved by server logic - * (e.g. cart, boat) - */ - public void updateMountedMovingPlayer(EntityPlayerMP player) { - int i = (int) player.posX >> 4; - int j = (int) player.posZ >> 4; - double d0 = player.managedPosX - player.posX; - double d1 = player.managedPosZ - player.posZ; - double d2 = d0 * d0 + d1 * d1; - if (d2 >= 64.0D) { - int k = (int) player.managedPosX >> 4; - int l = (int) player.managedPosZ >> 4; - int i1 = this.playerViewRadius; - int j1 = i - k; - int k1 = j - l; - if (j1 != 0 || k1 != 0) { - for (int l1 = i - i1; l1 <= i + i1; ++l1) { - for (int i2 = j - i1; i2 <= j + i1; ++i2) { - if (!this.overlaps(l1, i2, k, l, i1)) { - this.getPlayerInstance(l1, i2, true).addPlayer(player); - } - - if (!this.overlaps(l1 - j1, i2 - k1, i, j, i1)) { - PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(l1 - j1, - i2 - k1, false); - if (playermanager$playerinstance != null) { - playermanager$playerinstance.removePlayer(player); - } - } - } - } - - this.filterChunkLoadQueue(player); - player.managedPosX = player.posX; - player.managedPosZ = player.posZ; - } - } - } - - public boolean isPlayerWatchingChunk(EntityPlayerMP player, int chunkX, int chunkZ) { - PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(chunkX, chunkZ, false); - return playermanager$playerinstance != null - && playermanager$playerinstance.playersWatchingChunk.contains(player) - && !player.loadedChunks.contains(playermanager$playerinstance.chunkCoords); - } - - public void setPlayerViewRadius(int radius) { - radius = MathHelper.clamp_int(radius, 3, 32); - if (radius != this.playerViewRadius) { - int i = radius - this.playerViewRadius; - - List playerz = Lists.newArrayList(this.players); - for (int m = 0, n = playerz.size(); m < n; ++m) { - EntityPlayerMP entityplayermp = playerz.get(m); - int j = (int) entityplayermp.posX >> 4; - int k = (int) entityplayermp.posZ >> 4; - if (i > 0) { - for (int j1 = j - radius; j1 <= j + radius; ++j1) { - for (int k1 = k - radius; k1 <= k + radius; ++k1) { - PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(j1, k1, - true); - if (!playermanager$playerinstance.playersWatchingChunk.contains(entityplayermp)) { - playermanager$playerinstance.addPlayer(entityplayermp); - } - } - } - } else { - for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l) { - for (int i1 = k - this.playerViewRadius; i1 <= k + this.playerViewRadius; ++i1) { - if (!this.overlaps(l, i1, j, k, radius)) { - this.getPlayerInstance(l, i1, true).removePlayer(entityplayermp); - } - } - } - } - } - - this.playerViewRadius = radius; - } - } - - /**+ - * Get the furthest viewable block given player's view distance - */ - public static int getFurthestViewableBlock(int distance) { - return distance * 16 - 16; - } - class PlayerInstance { private final List playersWatchingChunk = Lists.newArrayList(); private final ChunkCoordIntPair chunkCoords; @@ -340,9 +58,9 @@ public class PlayerManager { PlayerManager.this.getWorldServer().theChunkProviderServer.loadChunk(chunkX, chunkZ); } - /**+ - * Adds an EntityPlayerMP to the PlayerManager and to all player - * instances within player visibility + /** + * + Adds an EntityPlayerMP to the PlayerManager and to all player instances + * within player visibility */ public void addPlayer(EntityPlayerMP player) { if (this.playersWatchingChunk.contains(player)) { @@ -359,47 +77,6 @@ public class PlayerManager { } } - /**+ - * Removes an EntityPlayerMP from the PlayerManager. - */ - public void removePlayer(EntityPlayerMP player) { - if (this.playersWatchingChunk.contains(player)) { - Chunk chunk = PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, - this.chunkCoords.chunkZPos); - if (chunk.isPopulated()) { - player.playerNetServerHandler.sendPacket(new S21PacketChunkData(chunk, true, 0)); - } - - this.playersWatchingChunk.remove(player); - player.loadedChunks.remove(this.chunkCoords); - if (this.playersWatchingChunk.isEmpty()) { - long i = (long) this.chunkCoords.chunkXPos + 2147483647L - | (long) this.chunkCoords.chunkZPos + 2147483647L << 32; - this.increaseInhabitedTime(chunk); - PlayerManager.this.playerInstances.remove(i); - PlayerManager.this.playerInstanceList.remove(this); - if (this.numBlocksToUpdate > 0) { - PlayerManager.this.playerInstancesToUpdate.remove(this); - } - - PlayerManager.this.getWorldServer().theChunkProviderServer.dropChunk(this.chunkCoords.chunkXPos, - this.chunkCoords.chunkZPos); - } - - } - } - - public void processChunk() { - this.increaseInhabitedTime(PlayerManager.this.theWorldServer - .getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos)); - } - - private void increaseInhabitedTime(Chunk theChunk) { - theChunk.setInhabitedTime(theChunk.getInhabitedTime() - + PlayerManager.this.theWorldServer.getTotalWorldTime() - this.previousWorldTime); - this.previousWorldTime = PlayerManager.this.theWorldServer.getTotalWorldTime(); - } - public void flagChunkForUpdate(int x, int y, int z) { if (this.numBlocksToUpdate == 0) { PlayerManager.this.playerInstancesToUpdate.add(this); @@ -420,14 +97,10 @@ public class PlayerManager { } - public void sendToAllPlayersWatchingChunk(Packet thePacket) { - for (int i = 0; i < this.playersWatchingChunk.size(); ++i) { - EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playersWatchingChunk.get(i); - if (!entityplayermp.loadedChunks.contains(this.chunkCoords)) { - entityplayermp.playerNetServerHandler.sendPacket(thePacket); - } - } - + private void increaseInhabitedTime(Chunk theChunk) { + theChunk.setInhabitedTime(theChunk.getInhabitedTime() + + PlayerManager.this.theWorldServer.getTotalWorldTime() - this.previousWorldTime); + this.previousWorldTime = PlayerManager.this.theWorldServer.getTotalWorldTime(); } public void onUpdate() { @@ -485,6 +158,41 @@ public class PlayerManager { } } + public void processChunk() { + this.increaseInhabitedTime(PlayerManager.this.theWorldServer + .getChunkFromChunkCoords(this.chunkCoords.chunkXPos, this.chunkCoords.chunkZPos)); + } + + /** + * + Removes an EntityPlayerMP from the PlayerManager. + */ + public void removePlayer(EntityPlayerMP player) { + if (this.playersWatchingChunk.contains(player)) { + Chunk chunk = PlayerManager.this.theWorldServer.getChunkFromChunkCoords(this.chunkCoords.chunkXPos, + this.chunkCoords.chunkZPos); + if (chunk.isPopulated()) { + player.playerNetServerHandler.sendPacket(new S21PacketChunkData(chunk, true, 0)); + } + + this.playersWatchingChunk.remove(player); + player.loadedChunks.remove(this.chunkCoords); + if (this.playersWatchingChunk.isEmpty()) { + long i = (long) this.chunkCoords.chunkXPos + 2147483647L + | (long) this.chunkCoords.chunkZPos + 2147483647L << 32; + this.increaseInhabitedTime(chunk); + PlayerManager.this.playerInstances.remove(i); + PlayerManager.this.playerInstanceList.remove(this); + if (this.numBlocksToUpdate > 0) { + PlayerManager.this.playerInstancesToUpdate.remove(this); + } + + PlayerManager.this.getWorldServer().theChunkProviderServer.dropChunk(this.chunkCoords.chunkXPos, + this.chunkCoords.chunkZPos); + } + + } + } + private void sendTileToAllPlayersWatchingChunk(TileEntity theTileEntity) { if (theTileEntity != null) { Packet packet = theTileEntity.getDescriptionPacket(); @@ -494,5 +202,302 @@ public class PlayerManager { } } + + public void sendToAllPlayersWatchingChunk(Packet thePacket) { + for (int i = 0; i < this.playersWatchingChunk.size(); ++i) { + EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playersWatchingChunk.get(i); + if (!entityplayermp.loadedChunks.contains(this.chunkCoords)) { + entityplayermp.playerNetServerHandler.sendPacket(thePacket); + } + } + + } + } + + private static final Logger pmLogger = LogManager.getLogger(); + + /** + * + Get the furthest viewable block given player's view distance + */ + public static int getFurthestViewableBlock(int distance) { + return distance * 16 - 16; + } + + private final WorldServer theWorldServer; + /** + * + players in the current instance + */ + private final List players = Lists.newArrayList(); + /** + * + the hash of all playerInstances created + */ + private final LongHashMap playerInstances = new LongHashMap(); + /** + * + the playerInstances(chunks) that need to be updated + */ + private final List playerInstancesToUpdate = Lists.newArrayList(); + /** + * + This field is using when chunk should be processed (every 8000 ticks) + */ + private final List playerInstanceList = Lists.newArrayList(); + private int playerViewRadius; + + private long previousTotalWorldTime; + + /** + * + x, z direction vectors: east, south, west, north + */ + private final int[][] xzDirectionsConst = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } }; + + public PlayerManager(WorldServer serverWorld) { + this.theWorldServer = serverWorld; + this.setPlayerViewRadius(serverWorld.getMinecraftServer().getConfigurationManager().getViewDistance()); + } + + /** + * + Adds an EntityPlayerMP to the PlayerManager and to all player instances + * within player visibility + */ + public void addPlayer(EntityPlayerMP player) { + int i = (int) player.posX >> 4; + int j = (int) player.posZ >> 4; + player.managedPosX = player.posX; + player.managedPosZ = player.posZ; + + for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k) { + for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l) { + this.getPlayerInstance(k, l, true).addPlayer(player); + } + } + + this.players.add(player); + this.filterChunkLoadQueue(player); + } + + /** + * + Removes all chunks from the given player's chunk load queue that are not in + * viewing range of the player. + */ + public void filterChunkLoadQueue(EntityPlayerMP player) { + ArrayList arraylist = Lists.newArrayList(player.loadedChunks); + int i = 0; + int j = this.playerViewRadius; + int k = (int) player.posX >> 4; + int l = (int) player.posZ >> 4; + int i1 = 0; + int j1 = 0; + ChunkCoordIntPair chunkcoordintpair = this.getPlayerInstance(k, l, true).chunkCoords; + player.loadedChunks.clear(); + if (arraylist.contains(chunkcoordintpair)) { + player.loadedChunks.add(chunkcoordintpair); + } + + for (int k1 = 1; k1 <= j * 2; ++k1) { + for (int l1 = 0; l1 < 2; ++l1) { + int[] aint = this.xzDirectionsConst[i++ % 4]; + + for (int i2 = 0; i2 < k1; ++i2) { + i1 += aint[0]; + j1 += aint[1]; + chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords; + if (arraylist.contains(chunkcoordintpair)) { + player.loadedChunks.add(chunkcoordintpair); + } + } + } + } + + i = i % 4; + + for (int j2 = 0; j2 < j * 2; ++j2) { + i1 += this.xzDirectionsConst[i][0]; + j1 += this.xzDirectionsConst[i][1]; + chunkcoordintpair = this.getPlayerInstance(k + i1, l + j1, true).chunkCoords; + if (arraylist.contains(chunkcoordintpair)) { + player.loadedChunks.add(chunkcoordintpair); + } + } + + } + + /** + * + passi n the chunk x and y and a flag as to whether or not the instance + * should be made if it doesnt exist + */ + private PlayerManager.PlayerInstance getPlayerInstance(int chunkX, int chunkZ, boolean createIfAbsent) { + long i = (long) chunkX + 2147483647L | (long) chunkZ + 2147483647L << 32; + PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance) this.playerInstances + .getValueByKey(i); + if (playermanager$playerinstance == null && createIfAbsent) { + playermanager$playerinstance = new PlayerManager.PlayerInstance(chunkX, chunkZ); + this.playerInstances.add(i, playermanager$playerinstance); + this.playerInstanceList.add(playermanager$playerinstance); + } + + return playermanager$playerinstance; + } + + /** + * + Returns the WorldServer associated with this PlayerManager + */ + public WorldServer getWorldServer() { + return this.theWorldServer; + } + + public boolean hasPlayerInstance(int chunkX, int chunkZ) { + long i = (long) chunkX + 2147483647L | (long) chunkZ + 2147483647L << 32; + return this.playerInstances.getValueByKey(i) != null; + } + + public boolean isPlayerWatchingChunk(EntityPlayerMP player, int chunkX, int chunkZ) { + PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(chunkX, chunkZ, false); + return playermanager$playerinstance != null + && playermanager$playerinstance.playersWatchingChunk.contains(player) + && !player.loadedChunks.contains(playermanager$playerinstance.chunkCoords); + } + + public void markBlockForUpdate(BlockPos pos) { + int i = pos.getX() >> 4; + int j = pos.getZ() >> 4; + PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(i, j, false); + if (playermanager$playerinstance != null) { + playermanager$playerinstance.flagChunkForUpdate(pos.getX() & 15, pos.getY(), pos.getZ() & 15); + } + + } + + /** + * + Determine if two rectangles centered at the given points overlap for the + * provided radius. Arguments: x1, z1, x2, z2, radius. + */ + private boolean overlaps(int x1, int z1, int x2, int z2, int radius) { + int i = x1 - x2; + int j = z1 - z2; + return i >= -radius && i <= radius ? j >= -radius && j <= radius : false; + } + + /** + * + Removes an EntityPlayerMP from the PlayerManager. + */ + public void removePlayer(EntityPlayerMP player) { + int i = (int) player.managedPosX >> 4; + int j = (int) player.managedPosZ >> 4; + + for (int k = i - this.playerViewRadius; k <= i + this.playerViewRadius; ++k) { + for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l) { + PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(k, l, false); + if (playermanager$playerinstance != null) { + playermanager$playerinstance.removePlayer(player); + } + } + } + + this.players.remove(player); + } + + public void setPlayerViewRadius(int radius) { + radius = MathHelper.clamp_int(radius, 3, 32); + if (radius != this.playerViewRadius) { + int i = radius - this.playerViewRadius; + + List playerz = Lists.newArrayList(this.players); + for (int m = 0, n = playerz.size(); m < n; ++m) { + EntityPlayerMP entityplayermp = playerz.get(m); + int j = (int) entityplayermp.posX >> 4; + int k = (int) entityplayermp.posZ >> 4; + if (i > 0) { + for (int j1 = j - radius; j1 <= j + radius; ++j1) { + for (int k1 = k - radius; k1 <= k + radius; ++k1) { + PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(j1, k1, + true); + if (!playermanager$playerinstance.playersWatchingChunk.contains(entityplayermp)) { + playermanager$playerinstance.addPlayer(entityplayermp); + } + } + } + } else { + for (int l = j - this.playerViewRadius; l <= j + this.playerViewRadius; ++l) { + for (int i1 = k - this.playerViewRadius; i1 <= k + this.playerViewRadius; ++i1) { + if (!this.overlaps(l, i1, j, k, radius)) { + this.getPlayerInstance(l, i1, true).removePlayer(entityplayermp); + } + } + } + } + } + + this.playerViewRadius = radius; + } + } + + /** + * + update chunks around a player being moved by server logic (e.g. cart, boat) + */ + public void updateMountedMovingPlayer(EntityPlayerMP player) { + int i = (int) player.posX >> 4; + int j = (int) player.posZ >> 4; + double d0 = player.managedPosX - player.posX; + double d1 = player.managedPosZ - player.posZ; + double d2 = d0 * d0 + d1 * d1; + if (d2 >= 64.0D) { + int k = (int) player.managedPosX >> 4; + int l = (int) player.managedPosZ >> 4; + int i1 = this.playerViewRadius; + int j1 = i - k; + int k1 = j - l; + if (j1 != 0 || k1 != 0) { + for (int l1 = i - i1; l1 <= i + i1; ++l1) { + for (int i2 = j - i1; i2 <= j + i1; ++i2) { + if (!this.overlaps(l1, i2, k, l, i1)) { + this.getPlayerInstance(l1, i2, true).addPlayer(player); + } + + if (!this.overlaps(l1 - j1, i2 - k1, i, j, i1)) { + PlayerManager.PlayerInstance playermanager$playerinstance = this.getPlayerInstance(l1 - j1, + i2 - k1, false); + if (playermanager$playerinstance != null) { + playermanager$playerinstance.removePlayer(player); + } + } + } + } + + this.filterChunkLoadQueue(player); + player.managedPosX = player.posX; + player.managedPosZ = player.posZ; + } + } + } + + /** + * + updates all the player instances that need to be updated + */ + public void updatePlayerInstances() { + long i = this.theWorldServer.getTotalWorldTime(); + if (i - this.previousTotalWorldTime > 8000L) { + this.previousTotalWorldTime = i; + + for (int j = 0; j < this.playerInstanceList.size(); ++j) { + PlayerManager.PlayerInstance playermanager$playerinstance = (PlayerManager.PlayerInstance) this.playerInstanceList + .get(j); + playermanager$playerinstance.onUpdate(); + playermanager$playerinstance.processChunk(); + } + } else { + for (int k = 0; k < this.playerInstancesToUpdate.size(); ++k) { + PlayerManager.PlayerInstance playermanager$playerinstance1 = (PlayerManager.PlayerInstance) this.playerInstancesToUpdate + .get(k); + playermanager$playerinstance1.onUpdate(); + } + } + + this.playerInstancesToUpdate.clear(); + if (this.players.isEmpty()) { + WorldProvider worldprovider = this.theWorldServer.provider; + if (!worldprovider.canRespawnHere()) { + this.theWorldServer.theChunkProviderServer.unloadAllChunks(); + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/server/management/ServerConfigurationManager.java b/src/game/java/net/minecraft/server/management/ServerConfigurationManager.java index f96392e2..0e0574df 100644 --- a/src/game/java/net/minecraft/server/management/ServerConfigurationManager.java +++ b/src/game/java/net/minecraft/server/management/ServerConfigurationManager.java @@ -1,20 +1,30 @@ package net.minecraft.server.management; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; -import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; - import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; +import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.client.GameProtocolMessageController; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; +import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; +import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; +import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; +import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.player.EntityPlayer; @@ -60,33 +70,26 @@ import net.minecraft.world.border.WorldBorder; import net.minecraft.world.demo.DemoWorldManager; import net.minecraft.world.storage.IPlayerFileData; import net.minecraft.world.storage.WorldInfo; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.client.GameProtocolMessageController; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; -import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; -import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; -import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; -import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -95,8 +98,8 @@ public abstract class ServerConfigurationManager { private static final Logger logger = LogManager.getLogger(); private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd \'at\' HH:mm:ss z"); private final MinecraftServer mcServer; - /**+ - * A list of player entities that exist on this server. + /** + * + A list of player entities that exist on this server. */ private final List playerEntityList = Lists.newArrayList(); private final Map uuidToPlayerMap = Maps.newHashMap(); @@ -118,6 +121,216 @@ public abstract class ServerConfigurationManager { this.maxPlayers = 100; } + /** + * + checks ban-lists, then white-lists, then space for the server. Returns null + * on success, or an error message + */ + public String allowUserToConnect(GameProfile gameprofile) { + return doesPlayerAlreadyExist(gameprofile) + ? "\"" + gameprofile.getName() + "\" is already playing on this world!" + : null; + } + + public boolean canJoin(GameProfile gameprofile) { + return true; + } + + public boolean canSendCommands(GameProfile profile) { + return lanCheats + || this.mcServer.isSinglePlayer() && this.mcServer.worldServers[0].getWorldInfo().areCommandsAllowed() + && this.mcServer.getServerOwner().equalsIgnoreCase(profile.getName()) + || this.commandsAllowedForAll; + } + + public void configureLAN(int gamemode, boolean cheats) { + lanGamemode = WorldSettings.GameType.getByID(gamemode); + lanCheats = cheats; + } + + /** + * + also checks for multiple logins across servers + */ + public EntityPlayerMP createPlayerForUser(GameProfile profile) { + EaglercraftUUID uuid = EntityPlayer.getUUID(profile); + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); + if (entityplayermp.getUniqueID().equals(uuid) + || entityplayermp.getName().equalsIgnoreCase(profile.getName())) { + arraylist.add(entityplayermp); + } + } + + EntityPlayerMP entityplayermp2 = (EntityPlayerMP) this.uuidToPlayerMap.get(profile.getId()); + if (entityplayermp2 != null && !arraylist.contains(entityplayermp2)) { + arraylist.add(entityplayermp2); + } + + for (int i = 0, l = arraylist.size(); i < l; ++i) { + arraylist.get(i).playerNetServerHandler.kickPlayerFromServer("You logged in from another location"); + } + + Object object; + if (this.mcServer.isDemo()) { + object = new DemoWorldManager(this.mcServer.worldServerForDimension(0)); + } else { + object = new ItemInWorldManager(this.mcServer.worldServerForDimension(0)); + } + + return new EntityPlayerMP(this.mcServer, this.mcServer.worldServerForDimension(0), profile, + (ItemInWorldManager) object); + } + + private boolean doesPlayerAlreadyExist(GameProfile gameprofile) { + for (int i = 0, l = playerEntityList.size(); i < l; ++i) { + EntityPlayerMP player = playerEntityList.get(i); + if (player.getName().equalsIgnoreCase(gameprofile.getName()) + || player.getUniqueID().equals(gameprofile.getId())) { + return true; + } + } + return false; + } + + public List func_181057_v() { + return this.playerEntityList; + } + + public String func_181058_b(boolean parFlag) { + String s = ""; + ArrayList arraylist = Lists.newArrayList(this.playerEntityList); + + for (int i = 0; i < arraylist.size(); ++i) { + if (i > 0) { + s = s + ", "; + } + + s = s + ((EntityPlayerMP) arraylist.get(i)).getName(); + if (parFlag) { + s = s + " (" + ((EntityPlayerMP) arraylist.get(i)).getUniqueID().toString() + ")"; + } + } + + return s; + } + + public boolean func_183023_f(GameProfile var1) { + return false; + } + + public GameProfile[] getAllProfiles() { + GameProfile[] agameprofile = new GameProfile[this.playerEntityList.size()]; + + for (int i = 0; i < agameprofile.length; ++i) { + agameprofile[i] = ((EntityPlayerMP) this.playerEntityList.get(i)).getGameProfile(); + } + + return agameprofile; + } + + /** + * + Returns an array of the usernames of all the connected players. + */ + public String[] getAllUsernames() { + String[] astring = new String[this.playerEntityList.size()]; + + for (int i = 0; i < astring.length; ++i) { + astring[i] = ((EntityPlayerMP) this.playerEntityList.get(i)).getName(); + } + + return astring; + } + + /** + * + Returns an array of usernames for which player.dat exists for. + */ + public String[] getAvailablePlayerDat() { + return this.mcServer.worldServers[0].getSaveHandler().getPlayerNBTManager().getAvailablePlayerDat(); + } + + /** + * + Returns the number of players currently on the server. + */ + public int getCurrentPlayerCount() { + return this.playerEntityList.size(); + } + + public int getEntityViewDistance() { + return PlayerManager.getFurthestViewableBlock(this.getViewDistance()); + } + + /** + * + On integrated servers, returns the host's player data to be written to + * level.dat. + */ + public NBTTagCompound getHostPlayerData() { + return null; + } + + /** + * + Returns the maximum number of players allowed on the server. + */ + public int getMaxPlayers() { + return this.maxPlayers; + } + + public EntityPlayerMP getPlayerByUsername(String username) { + for (EntityPlayerMP entityplayermp : this.playerEntityList) { + if (entityplayermp.getName().equalsIgnoreCase(username)) { + return entityplayermp; + } + } + + return null; + } + + /** + * + Get's the EntityPlayerMP object representing the player with the UUID. + */ + public EntityPlayerMP getPlayerByUUID(EaglercraftUUID playerUUID) { + return (EntityPlayerMP) this.uuidToPlayerMap.get(playerUUID); + } + + public List getPlayersMatchingAddress(String address) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = playerEntityList.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = playerEntityList.get(i); + if (entityplayermp.getPlayerIP().equals(address)) { + arraylist.add(entityplayermp); + } + } + + return arraylist; + } + + public StatisticsFile getPlayerStatsFile(EntityPlayer playerIn) { + String name = playerIn.getName(); + StatisticsFile statisticsfile = (StatisticsFile) this.playerStatFiles.get(name); + if (statisticsfile == null) { + VFile2 file1 = WorldsDB + .newVFile(this.mcServer.worldServerForDimension(0).getSaveHandler().getWorldDirectory(), "stats"); + VFile2 file2 = WorldsDB.newVFile(file1, name + ".json"); + statisticsfile = new StatisticsFile(this.mcServer, file2); + statisticsfile.readStatFile(); + this.playerStatFiles.put(name, statisticsfile); + } + + return statisticsfile; + } + + public MinecraftServer getServerInstance() { + return this.mcServer; + } + + /** + * + Gets the View Distance. + */ + public int getViewDistance() { + return this.viewDistance; + } + public void initializeConnectionToPlayer(IntegratedServerPlayerNetworkManager netManager, EntityPlayerMP playerIn, int protocolVersion, EaglercraftUUID clientBrandUUID) { playerIn.clientBrandUUID = clientBrandUUID; @@ -200,113 +413,21 @@ public abstract class ServerConfigurationManager { } } - protected void sendScoreboard(ServerScoreboard scoreboardIn, EntityPlayerMP playerIn) { - HashSet hashset = Sets.newHashSet(); - - for (ScorePlayerTeam scoreplayerteam : scoreboardIn.getTeams()) { - playerIn.playerNetServerHandler.sendPacket(new S3EPacketTeams(scoreplayerteam, 0)); - } - - for (int i = 0; i < 19; ++i) { - ScoreObjective scoreobjective = scoreboardIn.getObjectiveInDisplaySlot(i); - if (scoreobjective != null && !hashset.contains(scoreobjective)) { - List lst = scoreboardIn.func_96550_d(scoreobjective); - for (int j = 0, l = lst.size(); j < l; ++j) { - playerIn.playerNetServerHandler.sendPacket(lst.get(j)); - } - - hashset.add(scoreobjective); - } - } - - } - - /**+ - * Sets the NBT manager to the one for the WorldServer given. + /** + * + self explanitory */ - public void setPlayerManager(WorldServer[] worldServers) { - this.playerNBTManagerObj = worldServers[0].getSaveHandler().getPlayerNBTManager(); - worldServers[0].getWorldBorder().addListener(new IBorderListener() { - public void onSizeChanged(WorldBorder worldborder, double var2) { - ServerConfigurationManager.this.sendPacketToAllPlayers( - new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_SIZE)); - } - - public void onTransitionStarted(WorldBorder worldborder, double var2, double var4, long var6) { - ServerConfigurationManager.this.sendPacketToAllPlayers( - new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.LERP_SIZE)); - } - - public void onCenterChanged(WorldBorder worldborder, double var2, double var4) { - ServerConfigurationManager.this.sendPacketToAllPlayers( - new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_CENTER)); - } - - public void onWarningTimeChanged(WorldBorder worldborder, int var2) { - ServerConfigurationManager.this.sendPacketToAllPlayers( - new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_WARNING_TIME)); - } - - public void onWarningDistanceChanged(WorldBorder worldborder, int var2) { - ServerConfigurationManager.this.sendPacketToAllPlayers( - new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_WARNING_BLOCKS)); - } - - public void onDamageAmountChanged(WorldBorder var1, double var2) { - } - - public void onDamageBufferChanged(WorldBorder var1, double var2) { - } - }); - } - - public void preparePlayer(EntityPlayerMP playerIn, WorldServer worldIn) { - WorldServer worldserver = playerIn.getServerForPlayer(); - if (worldIn != null) { - worldIn.getPlayerManager().removePlayer(playerIn); - } - - worldserver.getPlayerManager().addPlayer(playerIn); - worldserver.theChunkProviderServer.loadChunk((int) playerIn.posX >> 4, (int) playerIn.posZ >> 4); - } - - public int getEntityViewDistance() { - return PlayerManager.getFurthestViewableBlock(this.getViewDistance()); - } - - /**+ - * called during player login. reads the player information from - * disk. - */ - public NBTTagCompound readPlayerDataFromFile(EntityPlayerMP playerIn) { - NBTTagCompound nbttagcompound = this.mcServer.worldServers[0].getWorldInfo().getPlayerNBTTagCompound(); - NBTTagCompound nbttagcompound1; - if (playerIn.getName().equals(this.mcServer.getServerOwner()) && nbttagcompound != null) { - playerIn.readFromNBT(nbttagcompound); - nbttagcompound1 = nbttagcompound; - logger.debug("loading single player"); - } else { - nbttagcompound1 = this.playerNBTManagerObj.readPlayerData(playerIn); - } - - return nbttagcompound1; - } - - /**+ - * also stores the NBTTags if this is an intergratedPlayerList - */ - protected void writePlayerData(EntityPlayerMP entityplayermp) { - this.playerNBTManagerObj.writePlayerData(entityplayermp); - StatisticsFile statisticsfile = (StatisticsFile) this.playerStatFiles.get(entityplayermp.getName()); - if (statisticsfile != null) { - statisticsfile.saveStatFile(); + public void onTick() { + if (++this.playerPingIndex > 600) { + this.sendPacketToAllPlayers( + new S38PacketPlayerListItem(S38PacketPlayerListItem.Action.UPDATE_LATENCY, this.playerEntityList)); + this.playerPingIndex = 0; } } - /**+ - * Called when a player successfully logs in. Reads player data - * from disk and inserts the player into the world. + /** + * + Called when a player successfully logs in. Reads player data from disk and + * inserts the player into the world. */ public void playerLoggedIn(EntityPlayerMP playerIn) { this.playerEntityList.add(playerIn); @@ -325,17 +446,9 @@ public abstract class ServerConfigurationManager { } - /**+ - * using player's dimension, update their movement when in a - * vehicle (e.g. cart, boat) - */ - public void serverUpdateMountedMovingPlayer(EntityPlayerMP playerIn) { - playerIn.getServerForPlayer().getPlayerManager().updateMountedMovingPlayer(playerIn); - } - - /**+ - * Called when a player disconnects from the game. Writes player - * data to disk and removes them from the world. + /** + * + Called when a player disconnects from the game. Writes player data to disk + * and removes them from the world. */ public void playerLoggedOut(EntityPlayerMP playerIn) { playerIn.triggerAchievement(StatList.leaveGameStat); @@ -367,64 +480,35 @@ public abstract class ServerConfigurationManager { new EntityPlayerMP[] { playerIn })); } - /**+ - * checks ban-lists, then white-lists, then space for the - * server. Returns null on success, or an error message - */ - public String allowUserToConnect(GameProfile gameprofile) { - return doesPlayerAlreadyExist(gameprofile) - ? "\"" + gameprofile.getName() + "\" is already playing on this world!" - : null; + public void preparePlayer(EntityPlayerMP playerIn, WorldServer worldIn) { + WorldServer worldserver = playerIn.getServerForPlayer(); + if (worldIn != null) { + worldIn.getPlayerManager().removePlayer(playerIn); + } + + worldserver.getPlayerManager().addPlayer(playerIn); + worldserver.theChunkProviderServer.loadChunk((int) playerIn.posX >> 4, (int) playerIn.posZ >> 4); } - private boolean doesPlayerAlreadyExist(GameProfile gameprofile) { - for (int i = 0, l = playerEntityList.size(); i < l; ++i) { - EntityPlayerMP player = playerEntityList.get(i); - if (player.getName().equalsIgnoreCase(gameprofile.getName()) - || player.getUniqueID().equals(gameprofile.getId())) { - return true; - } - } - return false; - } - - /**+ - * also checks for multiple logins across servers + /** + * + called during player login. reads the player information from disk. */ - public EntityPlayerMP createPlayerForUser(GameProfile profile) { - EaglercraftUUID uuid = EntityPlayer.getUUID(profile); - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); - if (entityplayermp.getUniqueID().equals(uuid) - || entityplayermp.getName().equalsIgnoreCase(profile.getName())) { - arraylist.add(entityplayermp); - } - } - - EntityPlayerMP entityplayermp2 = (EntityPlayerMP) this.uuidToPlayerMap.get(profile.getId()); - if (entityplayermp2 != null && !arraylist.contains(entityplayermp2)) { - arraylist.add(entityplayermp2); - } - - for (int i = 0, l = arraylist.size(); i < l; ++i) { - arraylist.get(i).playerNetServerHandler.kickPlayerFromServer("You logged in from another location"); - } - - Object object; - if (this.mcServer.isDemo()) { - object = new DemoWorldManager(this.mcServer.worldServerForDimension(0)); + public NBTTagCompound readPlayerDataFromFile(EntityPlayerMP playerIn) { + NBTTagCompound nbttagcompound = this.mcServer.worldServers[0].getWorldInfo().getPlayerNBTTagCompound(); + NBTTagCompound nbttagcompound1; + if (playerIn.getName().equals(this.mcServer.getServerOwner()) && nbttagcompound != null) { + playerIn.readFromNBT(nbttagcompound); + nbttagcompound1 = nbttagcompound; + logger.debug("loading single player"); } else { - object = new ItemInWorldManager(this.mcServer.worldServerForDimension(0)); + nbttagcompound1 = this.playerNBTManagerObj.readPlayerData(playerIn); } - return new EntityPlayerMP(this.mcServer, this.mcServer.worldServerForDimension(0), profile, - (ItemInWorldManager) object); + return nbttagcompound1; } - /**+ - * Called on respawn + /** + * + Called on respawn */ public EntityPlayerMP recreatePlayerEntity(EntityPlayerMP playerIn, int dimension, boolean conqueredEnd) { playerIn.getServerForPlayer().getEntityTracker().removePlayerFromTrackers(playerIn); @@ -492,35 +576,236 @@ public abstract class ServerConfigurationManager { return entityplayermp; } - /**+ - * moves provided player from overworld to nether or vice versa + /** + * + Kicks everyone with "Server closed" as reason. */ - public void transferPlayerToDimension(EntityPlayerMP playerIn, int dimension) { - int i = playerIn.dimension; - WorldServer worldserver = this.mcServer.worldServerForDimension(playerIn.dimension); - playerIn.dimension = dimension; - WorldServer worldserver1 = this.mcServer.worldServerForDimension(playerIn.dimension); - playerIn.playerNetServerHandler.sendPacket(new S07PacketRespawn(playerIn.dimension, - playerIn.worldObj.getDifficulty(), playerIn.worldObj.getWorldInfo().getTerrainType(), - playerIn.theItemInWorldManager.getGameType())); - worldserver.removePlayerEntityDangerously(playerIn); - playerIn.isDead = false; - this.transferEntityToWorld(playerIn, i, worldserver, worldserver1); - this.preparePlayer(playerIn, worldserver); - playerIn.playerNetServerHandler.setPlayerLocation(playerIn.posX, playerIn.posY, playerIn.posZ, - playerIn.rotationYaw, playerIn.rotationPitch); - playerIn.theItemInWorldManager.setWorld(worldserver1); - this.updateTimeAndWeatherForPlayer(playerIn, worldserver1); - this.syncPlayerInventory(playerIn); - - for (PotionEffect potioneffect : playerIn.getActivePotionEffects()) { - playerIn.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(playerIn.getEntityId(), potioneffect)); + public void removeAllPlayers() { + for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { + ((EntityPlayerMP) this.playerEntityList.get(i)).playerNetServerHandler + .kickPlayerFromServer("Server closed"); } } - /**+ - * Transfers an entity from a world to another world. + /** + * + Saves all of the players' current states. + */ + public void saveAllPlayerData() { + for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { + this.writePlayerData((EntityPlayerMP) this.playerEntityList.get(i)); + } + + } + + /** + * + Sends the given string to every player as chat message. + */ + public void sendChatMsg(IChatComponent component) { + this.sendChatMsgImpl(component, true); + } + + public void sendChatMsgImpl(IChatComponent component, boolean isChat) { + this.mcServer.addChatMessage(component); + int i = isChat ? 1 : 0; + this.sendPacketToAllPlayers(new S02PacketChat(component, (byte) i)); + } + + public void sendMessageToAllTeamMembers(EntityPlayer player, IChatComponent message) { + Team team = player.getTeam(); + if (team != null) { + for (String s : team.getMembershipCollection()) { + EntityPlayerMP entityplayermp = this.getPlayerByUsername(s); + if (entityplayermp != null && entityplayermp != player) { + entityplayermp.addChatMessage(message); + } + } + + } + } + + public void sendMessageToTeamOrEvryPlayer(EntityPlayer player, IChatComponent message) { + Team team = player.getTeam(); + if (team == null) { + this.sendChatMsg(message); + } else { + for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); + if (entityplayermp.getTeam() != team) { + entityplayermp.addChatMessage(message); + } + } + + } + } + + public void sendPacketToAllPlayers(Packet packetIn) { + for (int i = 0; i < this.playerEntityList.size(); ++i) { + ((EntityPlayerMP) this.playerEntityList.get(i)).playerNetServerHandler.sendPacket(packetIn); + } + + } + + public void sendPacketToAllPlayersInDimension(Packet packetIn, int dimension) { + for (int i = 0; i < this.playerEntityList.size(); ++i) { + EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); + if (entityplayermp.dimension == dimension) { + entityplayermp.playerNetServerHandler.sendPacket(packetIn); + } + } + + } + + protected void sendScoreboard(ServerScoreboard scoreboardIn, EntityPlayerMP playerIn) { + HashSet hashset = Sets.newHashSet(); + + for (ScorePlayerTeam scoreplayerteam : scoreboardIn.getTeams()) { + playerIn.playerNetServerHandler.sendPacket(new S3EPacketTeams(scoreplayerteam, 0)); + } + + for (int i = 0; i < 19; ++i) { + ScoreObjective scoreobjective = scoreboardIn.getObjectiveInDisplaySlot(i); + if (scoreobjective != null && !hashset.contains(scoreobjective)) { + List lst = scoreboardIn.func_96550_d(scoreobjective); + for (int j = 0, l = lst.size(); j < l; ++j) { + playerIn.playerNetServerHandler.sendPacket(lst.get(j)); + } + + hashset.add(scoreobjective); + } + } + + } + + /** + * + params: x,y,z,r,dimension. The packet is sent to all players within r + * radius of x,y,z (r^2>x^2+y^2+z^2) + */ + public void sendToAllNear(double x, double y, double z, double radius, int dimension, Packet packetIn) { + this.sendToAllNearExcept((EntityPlayer) null, x, y, z, radius, dimension, packetIn); + } + + /** + * + params: srcPlayer,x,y,z,r,dimension. The packet is not sent to the + * srcPlayer, but all other players within the search radius + */ + public void sendToAllNearExcept(EntityPlayer x, double y, double z, double radius, double dimension, int parInt1, + Packet parPacket) { + for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { + EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); + if (entityplayermp != x && entityplayermp.dimension == parInt1) { + double d0 = y - entityplayermp.posX; + double d1 = z - entityplayermp.posY; + double d2 = radius - entityplayermp.posZ; + if (d0 * d0 + d1 * d1 + d2 * d2 < dimension * dimension) { + entityplayermp.playerNetServerHandler.sendPacket(parPacket); + } + } + } + + } + + /** + * + using player's dimension, update their movement when in a vehicle (e.g. + * cart, boat) + */ + public void serverUpdateMountedMovingPlayer(EntityPlayerMP playerIn) { + playerIn.getServerForPlayer().getPlayerManager().updateMountedMovingPlayer(playerIn); + } + + /** + * + Sets whether all players are allowed to use commands (cheats) on the + * server. + */ + public void setCommandsAllowedForAll(boolean parFlag) { + this.commandsAllowedForAll = parFlag; + } + + public void setGameType(WorldSettings.GameType parGameType) { + this.gameType = parGameType; + } + + private void setPlayerGameTypeBasedOnOther(EntityPlayerMP worldIn, EntityPlayerMP parEntityPlayerMP2, + World parWorld) { + if (parEntityPlayerMP2 == null || parEntityPlayerMP2.getName().equals(mcServer.getServerOwner())) { + if (parEntityPlayerMP2 != null) { + worldIn.theItemInWorldManager.setGameType(parEntityPlayerMP2.theItemInWorldManager.getGameType()); + } else if (this.gameType != null) { + worldIn.theItemInWorldManager.setGameType(this.gameType); + } + + worldIn.theItemInWorldManager.initializeGameType(parWorld.getWorldInfo().getGameType()); + } else { + worldIn.theItemInWorldManager.setGameType(lanGamemode); + } + } + + /** + * + Sets the NBT manager to the one for the WorldServer given. + */ + public void setPlayerManager(WorldServer[] worldServers) { + this.playerNBTManagerObj = worldServers[0].getSaveHandler().getPlayerNBTManager(); + worldServers[0].getWorldBorder().addListener(new IBorderListener() { + public void onCenterChanged(WorldBorder worldborder, double var2, double var4) { + ServerConfigurationManager.this.sendPacketToAllPlayers( + new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_CENTER)); + } + + public void onDamageAmountChanged(WorldBorder var1, double var2) { + } + + public void onDamageBufferChanged(WorldBorder var1, double var2) { + } + + public void onSizeChanged(WorldBorder worldborder, double var2) { + ServerConfigurationManager.this.sendPacketToAllPlayers( + new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_SIZE)); + } + + public void onTransitionStarted(WorldBorder worldborder, double var2, double var4, long var6) { + ServerConfigurationManager.this.sendPacketToAllPlayers( + new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.LERP_SIZE)); + } + + public void onWarningDistanceChanged(WorldBorder worldborder, int var2) { + ServerConfigurationManager.this.sendPacketToAllPlayers( + new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_WARNING_BLOCKS)); + } + + public void onWarningTimeChanged(WorldBorder worldborder, int var2) { + ServerConfigurationManager.this.sendPacketToAllPlayers( + new S44PacketWorldBorder(worldborder, S44PacketWorldBorder.Action.SET_WARNING_TIME)); + } + }); + } + + public void setViewDistance(int distance) { + this.viewDistance = distance; + if (this.mcServer.worldServers != null) { + WorldServer[] srv = this.mcServer.worldServers; + for (int i = 0; i < srv.length; ++i) { + WorldServer worldserver = srv[i]; + if (worldserver != null) { + worldserver.getPlayerManager().setPlayerViewRadius(distance); + } + } + } + } + + public void setWhiteListEnabled(boolean flag) { + this.whiteListEnforced = flag; + } + + /** + * + sends the players inventory to himself + */ + public void syncPlayerInventory(EntityPlayerMP playerIn) { + playerIn.sendContainerToPlayer(playerIn.inventoryContainer); + playerIn.setPlayerHealthUpdated(); + playerIn.playerNetServerHandler.sendPacket(new S09PacketHeldItemChange(playerIn.inventory.currentItem)); + } + + /** + * + Transfers an entity from a world to another world. */ public void transferEntityToWorld(Entity entityIn, int parInt1, WorldServer parWorldServer, WorldServer parWorldServer2) { @@ -577,168 +862,45 @@ public abstract class ServerConfigurationManager { entityIn.setWorld(parWorldServer2); } - /**+ - * self explanitory + /** + * + moves provided player from overworld to nether or vice versa */ - public void onTick() { - if (++this.playerPingIndex > 600) { - this.sendPacketToAllPlayers( - new S38PacketPlayerListItem(S38PacketPlayerListItem.Action.UPDATE_LATENCY, this.playerEntityList)); - this.playerPingIndex = 0; + public void transferPlayerToDimension(EntityPlayerMP playerIn, int dimension) { + int i = playerIn.dimension; + WorldServer worldserver = this.mcServer.worldServerForDimension(playerIn.dimension); + playerIn.dimension = dimension; + WorldServer worldserver1 = this.mcServer.worldServerForDimension(playerIn.dimension); + playerIn.playerNetServerHandler.sendPacket(new S07PacketRespawn(playerIn.dimension, + playerIn.worldObj.getDifficulty(), playerIn.worldObj.getWorldInfo().getTerrainType(), + playerIn.theItemInWorldManager.getGameType())); + worldserver.removePlayerEntityDangerously(playerIn); + playerIn.isDead = false; + this.transferEntityToWorld(playerIn, i, worldserver, worldserver1); + this.preparePlayer(playerIn, worldserver); + playerIn.playerNetServerHandler.setPlayerLocation(playerIn.posX, playerIn.posY, playerIn.posZ, + playerIn.rotationYaw, playerIn.rotationPitch); + playerIn.theItemInWorldManager.setWorld(worldserver1); + this.updateTimeAndWeatherForPlayer(playerIn, worldserver1); + this.syncPlayerInventory(playerIn); + + for (PotionEffect potioneffect : playerIn.getActivePotionEffects()) { + playerIn.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(playerIn.getEntityId(), potioneffect)); } } - public void sendPacketToAllPlayers(Packet packetIn) { - for (int i = 0; i < this.playerEntityList.size(); ++i) { - ((EntityPlayerMP) this.playerEntityList.get(i)).playerNetServerHandler.sendPacket(packetIn); - } - - } - - public void sendPacketToAllPlayersInDimension(Packet packetIn, int dimension) { - for (int i = 0; i < this.playerEntityList.size(); ++i) { - EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); - if (entityplayermp.dimension == dimension) { - entityplayermp.playerNetServerHandler.sendPacket(packetIn); + public void updatePlayerViewDistance(EntityPlayerMP entityPlayerMP, int viewDistance2) { + if (entityPlayerMP.getName().equals(mcServer.getServerOwner())) { + if (viewDistance != viewDistance2) { + logger.info("Owner is setting view distance: {}", viewDistance2); + setViewDistance(viewDistance2); } } - } - public void sendMessageToAllTeamMembers(EntityPlayer player, IChatComponent message) { - Team team = player.getTeam(); - if (team != null) { - for (String s : team.getMembershipCollection()) { - EntityPlayerMP entityplayermp = this.getPlayerByUsername(s); - if (entityplayermp != null && entityplayermp != player) { - entityplayermp.addChatMessage(message); - } - } - - } - } - - public void sendMessageToTeamOrEvryPlayer(EntityPlayer player, IChatComponent message) { - Team team = player.getTeam(); - if (team == null) { - this.sendChatMsg(message); - } else { - for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); - if (entityplayermp.getTeam() != team) { - entityplayermp.addChatMessage(message); - } - } - - } - } - - public String func_181058_b(boolean parFlag) { - String s = ""; - ArrayList arraylist = Lists.newArrayList(this.playerEntityList); - - for (int i = 0; i < arraylist.size(); ++i) { - if (i > 0) { - s = s + ", "; - } - - s = s + ((EntityPlayerMP) arraylist.get(i)).getName(); - if (parFlag) { - s = s + " (" + ((EntityPlayerMP) arraylist.get(i)).getUniqueID().toString() + ")"; - } - } - - return s; - } - - /**+ - * Returns an array of the usernames of all the connected - * players. - */ - public String[] getAllUsernames() { - String[] astring = new String[this.playerEntityList.size()]; - - for (int i = 0; i < astring.length; ++i) { - astring[i] = ((EntityPlayerMP) this.playerEntityList.get(i)).getName(); - } - - return astring; - } - - public GameProfile[] getAllProfiles() { - GameProfile[] agameprofile = new GameProfile[this.playerEntityList.size()]; - - for (int i = 0; i < agameprofile.length; ++i) { - agameprofile[i] = ((EntityPlayerMP) this.playerEntityList.get(i)).getGameProfile(); - } - - return agameprofile; - } - - public boolean canJoin(GameProfile gameprofile) { - return true; - } - - public boolean canSendCommands(GameProfile profile) { - return lanCheats - || this.mcServer.isSinglePlayer() && this.mcServer.worldServers[0].getWorldInfo().areCommandsAllowed() - && this.mcServer.getServerOwner().equalsIgnoreCase(profile.getName()) - || this.commandsAllowedForAll; - } - - public EntityPlayerMP getPlayerByUsername(String username) { - for (EntityPlayerMP entityplayermp : this.playerEntityList) { - if (entityplayermp.getName().equalsIgnoreCase(username)) { - return entityplayermp; - } - } - - return null; - } - - /**+ - * params: x,y,z,r,dimension. The packet is sent to all players - * within r radius of x,y,z (r^2>x^2+y^2+z^2) - */ - public void sendToAllNear(double x, double y, double z, double radius, int dimension, Packet packetIn) { - this.sendToAllNearExcept((EntityPlayer) null, x, y, z, radius, dimension, packetIn); - } - - /**+ - * params: srcPlayer,x,y,z,r,dimension. The packet is not sent - * to the srcPlayer, but all other players within the search - * radius - */ - public void sendToAllNearExcept(EntityPlayer x, double y, double z, double radius, double dimension, int parInt1, - Packet parPacket) { - for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntityList.get(i); - if (entityplayermp != x && entityplayermp.dimension == parInt1) { - double d0 = y - entityplayermp.posX; - double d1 = z - entityplayermp.posY; - double d2 = radius - entityplayermp.posZ; - if (d0 * d0 + d1 * d1 + d2 * d2 < dimension * dimension) { - entityplayermp.playerNetServerHandler.sendPacket(parPacket); - } - } - } - - } - - /**+ - * Saves all of the players' current states. - */ - public void saveAllPlayerData() { - for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { - this.writePlayerData((EntityPlayerMP) this.playerEntityList.get(i)); - } - - } - - /**+ - * Updates the time and weather for the given player to those of - * the given world + /** + * + Updates the time and weather for the given player to those of the given + * world */ public void updateTimeAndWeatherForPlayer(EntityPlayerMP playerIn, WorldServer worldIn) { WorldBorder worldborder = this.mcServer.worldServers[0].getWorldBorder(); @@ -755,179 +917,15 @@ public abstract class ServerConfigurationManager { } - /**+ - * sends the players inventory to himself + /** + * + also stores the NBTTags if this is an intergratedPlayerList */ - public void syncPlayerInventory(EntityPlayerMP playerIn) { - playerIn.sendContainerToPlayer(playerIn.inventoryContainer); - playerIn.setPlayerHealthUpdated(); - playerIn.playerNetServerHandler.sendPacket(new S09PacketHeldItemChange(playerIn.inventory.currentItem)); - } - - /**+ - * Returns the number of players currently on the server. - */ - public int getCurrentPlayerCount() { - return this.playerEntityList.size(); - } - - /**+ - * Returns the maximum number of players allowed on the server. - */ - public int getMaxPlayers() { - return this.maxPlayers; - } - - /**+ - * Returns an array of usernames for which player.dat exists - * for. - */ - public String[] getAvailablePlayerDat() { - return this.mcServer.worldServers[0].getSaveHandler().getPlayerNBTManager().getAvailablePlayerDat(); - } - - public void setWhiteListEnabled(boolean flag) { - this.whiteListEnforced = flag; - } - - public List getPlayersMatchingAddress(String address) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = playerEntityList.size(); i < l; ++i) { - EntityPlayerMP entityplayermp = playerEntityList.get(i); - if (entityplayermp.getPlayerIP().equals(address)) { - arraylist.add(entityplayermp); - } + protected void writePlayerData(EntityPlayerMP entityplayermp) { + this.playerNBTManagerObj.writePlayerData(entityplayermp); + StatisticsFile statisticsfile = (StatisticsFile) this.playerStatFiles.get(entityplayermp.getName()); + if (statisticsfile != null) { + statisticsfile.saveStatFile(); } - return arraylist; - } - - /**+ - * Gets the View Distance. - */ - public int getViewDistance() { - return this.viewDistance; - } - - public MinecraftServer getServerInstance() { - return this.mcServer; - } - - /**+ - * On integrated servers, returns the host's player data to be - * written to level.dat. - */ - public NBTTagCompound getHostPlayerData() { - return null; - } - - public void setGameType(WorldSettings.GameType parGameType) { - this.gameType = parGameType; - } - - private void setPlayerGameTypeBasedOnOther(EntityPlayerMP worldIn, EntityPlayerMP parEntityPlayerMP2, - World parWorld) { - if (parEntityPlayerMP2 == null || parEntityPlayerMP2.getName().equals(mcServer.getServerOwner())) { - if (parEntityPlayerMP2 != null) { - worldIn.theItemInWorldManager.setGameType(parEntityPlayerMP2.theItemInWorldManager.getGameType()); - } else if (this.gameType != null) { - worldIn.theItemInWorldManager.setGameType(this.gameType); - } - - worldIn.theItemInWorldManager.initializeGameType(parWorld.getWorldInfo().getGameType()); - } else { - worldIn.theItemInWorldManager.setGameType(lanGamemode); - } - } - - /**+ - * Sets whether all players are allowed to use commands (cheats) - * on the server. - */ - public void setCommandsAllowedForAll(boolean parFlag) { - this.commandsAllowedForAll = parFlag; - } - - /**+ - * Kicks everyone with "Server closed" as reason. - */ - public void removeAllPlayers() { - for (int i = 0, l = this.playerEntityList.size(); i < l; ++i) { - ((EntityPlayerMP) this.playerEntityList.get(i)).playerNetServerHandler - .kickPlayerFromServer("Server closed"); - } - - } - - public void sendChatMsgImpl(IChatComponent component, boolean isChat) { - this.mcServer.addChatMessage(component); - int i = isChat ? 1 : 0; - this.sendPacketToAllPlayers(new S02PacketChat(component, (byte) i)); - } - - /**+ - * Sends the given string to every player as chat message. - */ - public void sendChatMsg(IChatComponent component) { - this.sendChatMsgImpl(component, true); - } - - public StatisticsFile getPlayerStatsFile(EntityPlayer playerIn) { - String name = playerIn.getName(); - StatisticsFile statisticsfile = (StatisticsFile) this.playerStatFiles.get(name); - if (statisticsfile == null) { - VFile2 file1 = WorldsDB - .newVFile(this.mcServer.worldServerForDimension(0).getSaveHandler().getWorldDirectory(), "stats"); - VFile2 file2 = WorldsDB.newVFile(file1, name + ".json"); - statisticsfile = new StatisticsFile(this.mcServer, file2); - statisticsfile.readStatFile(); - this.playerStatFiles.put(name, statisticsfile); - } - - return statisticsfile; - } - - public void setViewDistance(int distance) { - this.viewDistance = distance; - if (this.mcServer.worldServers != null) { - WorldServer[] srv = this.mcServer.worldServers; - for (int i = 0; i < srv.length; ++i) { - WorldServer worldserver = srv[i]; - if (worldserver != null) { - worldserver.getPlayerManager().setPlayerViewRadius(distance); - } - } - } - } - - public List func_181057_v() { - return this.playerEntityList; - } - - /**+ - * Get's the EntityPlayerMP object representing the player with - * the UUID. - */ - public EntityPlayerMP getPlayerByUUID(EaglercraftUUID playerUUID) { - return (EntityPlayerMP) this.uuidToPlayerMap.get(playerUUID); - } - - public boolean func_183023_f(GameProfile var1) { - return false; - } - - public void updatePlayerViewDistance(EntityPlayerMP entityPlayerMP, int viewDistance2) { - if (entityPlayerMP.getName().equals(mcServer.getServerOwner())) { - if (viewDistance != viewDistance2) { - logger.info("Owner is setting view distance: {}", viewDistance2); - setViewDistance(viewDistance2); - } - } - } - - public void configureLAN(int gamemode, boolean cheats) { - lanGamemode = WorldSettings.GameType.getByID(gamemode); - lanCheats = cheats; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/server/network/NetHandlerLoginServer.java b/src/game/java/net/minecraft/server/network/NetHandlerLoginServer.java index 3b02a1c8..d8982a0c 100644 --- a/src/game/java/net/minecraft/server/network/NetHandlerLoginServer.java +++ b/src/game/java/net/minecraft/server/network/NetHandlerLoginServer.java @@ -1,12 +1,22 @@ package net.minecraft.server.network; +import java.io.DataInputStream; +import java.io.IOException; + +import org.apache.commons.lang3.Validate; + import com.google.common.base.Charsets; -import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; + import net.lax1dude.eaglercraft.v1_8.ClientUUIDLoadingCache; import net.lax1dude.eaglercraft.v1_8.EaglerInputStream; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; +import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; +import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.EnumConnectionState; import net.minecraft.network.login.INetHandlerLoginServer; @@ -18,37 +28,35 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; import net.minecraft.util.ITickable; -import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; -import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; -import java.io.DataInputStream; -import java.io.IOException; - -import org.apache.commons.lang3.Validate; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NetHandlerLoginServer implements INetHandlerLoginServer, ITickable { + static enum LoginState { + HELLO, KEY, AUTHENTICATING, READY_TO_ACCEPT, DELAY_ACCEPT, ACCEPTED; + } + private static final Logger logger = LogManager.getLogger(); private final MinecraftServer server; public final IntegratedServerPlayerNetworkManager networkManager; @@ -60,6 +68,7 @@ public class NetHandlerLoginServer implements INetHandlerLoginServer, ITickable private int selectedProtocol = 3; private EaglercraftUUID clientBrandUUID; private String serverId = ""; + private EntityPlayerMP field_181025_l; public NetHandlerLoginServer(MinecraftServer parMinecraftServer, @@ -68,40 +77,6 @@ public class NetHandlerLoginServer implements INetHandlerLoginServer, ITickable this.networkManager = parNetworkManager; } - /**+ - * Like the old updateEntity(), except more generic. - */ - public void update() { - if (this.currentLoginState == NetHandlerLoginServer.LoginState.READY_TO_ACCEPT) { - this.tryAcceptPlayer(); - } else if (this.currentLoginState == NetHandlerLoginServer.LoginState.DELAY_ACCEPT) { - EntityPlayerMP entityplayermp = this.server.getConfigurationManager() - .getPlayerByUUID(this.loginGameProfile.getId()); - if (entityplayermp == null) { - this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT; - this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, - this.field_181025_l, this.selectedProtocol, this.clientBrandUUID); - ((EaglerMinecraftServer) field_181025_l.mcServer).getSkinService() - .processLoginPacket(this.loginSkinPacket, field_181025_l, 3); // singleplayer always sends V3 - // skin in handshake - if (this.loginCapePacket != null) { - ((EaglerMinecraftServer) field_181025_l.mcServer).getCapeService() - .processLoginPacket(this.loginCapePacket, field_181025_l); - } - IntegratedVoiceService svc = ((EaglerMinecraftServer) field_181025_l.mcServer).getVoiceService(); - if (svc != null) { - svc.handlePlayerLoggedIn(entityplayermp); - } - this.field_181025_l = null; - } - } - - if (this.connectionTimer++ == 600) { - this.closeConnection("Took too long to log in"); - } - - } - public void closeConnection(String reason) { try { logger.info("Disconnecting " + this.getConnectionInfo() + ": " + reason); @@ -114,51 +89,28 @@ public class NetHandlerLoginServer implements INetHandlerLoginServer, ITickable } - public void tryAcceptPlayer() { - String s = this.server.getConfigurationManager().allowUserToConnect(this.loginGameProfile); - if (s != null) { - this.closeConnection(s); - } else { - this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED; - this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile, this.selectedProtocol)); - this.networkManager.setConnectionState(EnumConnectionState.PLAY); - EntityPlayerMP entityplayermp = this.server.getConfigurationManager() - .getPlayerByUUID(this.loginGameProfile.getId()); - if (entityplayermp != null) { - this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT; - this.field_181025_l = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile); - } else { - entityplayermp = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile); - this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, entityplayermp, - this.selectedProtocol, this.clientBrandUUID); - ((EaglerMinecraftServer) entityplayermp.mcServer).getSkinService() - .processLoginPacket(this.loginSkinPacket, entityplayermp, 3); // singleplayer always sends V3 - // skin in handshake - if (this.loginCapePacket != null) { - ((EaglerMinecraftServer) entityplayermp.mcServer).getCapeService() - .processLoginPacket(this.loginCapePacket, entityplayermp); - } - IntegratedVoiceService svc = ((EaglerMinecraftServer) entityplayermp.mcServer).getVoiceService(); - if (svc != null) { - svc.handlePlayerLoggedIn(entityplayermp); - } - } - } - + public String getConnectionInfo() { + return this.loginGameProfile != null + ? this.loginGameProfile.toString() + " (channel:" + this.networkManager.playerChannel + ")" + : ("channel:" + this.networkManager.playerChannel); } - /**+ - * Invoked when disconnecting, the parameter is a ChatComponent - * describing the reason for termination + protected GameProfile getOfflineProfile(GameProfile original) { + EaglercraftUUID uuid = EaglercraftUUID + .nameUUIDFromBytes(("OfflinePlayer:" + original.getName()).getBytes(Charsets.UTF_8)); + return new GameProfile(uuid, original.getName()); + } + + /** + * + Invoked when disconnecting, the parameter is a ChatComponent describing the + * reason for termination */ public void onDisconnect(IChatComponent ichatcomponent) { logger.info(this.getConnectionInfo() + " lost connection: " + ichatcomponent.getUnformattedText()); } - public String getConnectionInfo() { - return this.loginGameProfile != null - ? this.loginGameProfile.toString() + " (channel:" + this.networkManager.playerChannel + ")" - : ("channel:" + this.networkManager.playerChannel); + public void processEncryptionResponse(C01PacketEncryptionResponse c01packetencryptionresponse) { + } public void processLoginStart(C00PacketLoginStart c00packetloginstart) { @@ -199,17 +151,70 @@ public class NetHandlerLoginServer implements INetHandlerLoginServer, ITickable this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT; } - public void processEncryptionResponse(C01PacketEncryptionResponse c01packetencryptionresponse) { + public void tryAcceptPlayer() { + String s = this.server.getConfigurationManager().allowUserToConnect(this.loginGameProfile); + if (s != null) { + this.closeConnection(s); + } else { + this.currentLoginState = NetHandlerLoginServer.LoginState.ACCEPTED; + this.networkManager.sendPacket(new S02PacketLoginSuccess(this.loginGameProfile, this.selectedProtocol)); + this.networkManager.setConnectionState(EnumConnectionState.PLAY); + EntityPlayerMP entityplayermp = this.server.getConfigurationManager() + .getPlayerByUUID(this.loginGameProfile.getId()); + if (entityplayermp != null) { + this.currentLoginState = NetHandlerLoginServer.LoginState.DELAY_ACCEPT; + this.field_181025_l = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile); + } else { + entityplayermp = this.server.getConfigurationManager().createPlayerForUser(this.loginGameProfile); + this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, entityplayermp, + this.selectedProtocol, this.clientBrandUUID); + ((EaglerMinecraftServer) entityplayermp.mcServer).getSkinService() + .processLoginPacket(this.loginSkinPacket, entityplayermp, 3); // singleplayer always sends V3 + // skin in handshake + if (this.loginCapePacket != null) { + ((EaglerMinecraftServer) entityplayermp.mcServer).getCapeService() + .processLoginPacket(this.loginCapePacket, entityplayermp); + } + IntegratedVoiceService svc = ((EaglerMinecraftServer) entityplayermp.mcServer).getVoiceService(); + if (svc != null) { + svc.handlePlayerLoggedIn(entityplayermp); + } + } + } } - protected GameProfile getOfflineProfile(GameProfile original) { - EaglercraftUUID uuid = EaglercraftUUID - .nameUUIDFromBytes(("OfflinePlayer:" + original.getName()).getBytes(Charsets.UTF_8)); - return new GameProfile(uuid, original.getName()); - } + /** + * + Like the old updateEntity(), except more generic. + */ + public void update() { + if (this.currentLoginState == NetHandlerLoginServer.LoginState.READY_TO_ACCEPT) { + this.tryAcceptPlayer(); + } else if (this.currentLoginState == NetHandlerLoginServer.LoginState.DELAY_ACCEPT) { + EntityPlayerMP entityplayermp = this.server.getConfigurationManager() + .getPlayerByUUID(this.loginGameProfile.getId()); + if (entityplayermp == null) { + this.currentLoginState = NetHandlerLoginServer.LoginState.READY_TO_ACCEPT; + this.server.getConfigurationManager().initializeConnectionToPlayer(this.networkManager, + this.field_181025_l, this.selectedProtocol, this.clientBrandUUID); + ((EaglerMinecraftServer) field_181025_l.mcServer).getSkinService() + .processLoginPacket(this.loginSkinPacket, field_181025_l, 3); // singleplayer always sends V3 + // skin in handshake + if (this.loginCapePacket != null) { + ((EaglerMinecraftServer) field_181025_l.mcServer).getCapeService() + .processLoginPacket(this.loginCapePacket, field_181025_l); + } + IntegratedVoiceService svc = ((EaglerMinecraftServer) field_181025_l.mcServer).getVoiceService(); + if (svc != null) { + svc.handlePlayerLoggedIn(entityplayermp); + } + this.field_181025_l = null; + } + } + + if (this.connectionTimer++ == 600) { + this.closeConnection("Took too long to log in"); + } - static enum LoginState { - HELLO, KEY, AUTHENTICATING, READY_TO_ACCEPT, DELAY_ACCEPT, ACCEPTED; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/Achievement.java b/src/game/java/net/minecraft/stats/Achievement.java index 5d01e904..63888f37 100644 --- a/src/game/java/net/minecraft/stats/Achievement.java +++ b/src/game/java/net/minecraft/stats/Achievement.java @@ -9,22 +9,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.IJsonSerializable; import net.minecraft.util.StatCollector; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,14 +41,14 @@ public class Achievement extends StatBase { public final ItemStack theItemStack; private boolean isSpecial; - public Achievement(String parString1, String parString2, int column, int row, Item parItem, Achievement parent) { - this(parString1, parString2, column, row, new ItemStack(parItem), parent); - } - public Achievement(String parString1, String parString2, int column, int row, Block parBlock, Achievement parent) { this(parString1, parString2, column, row, new ItemStack(parBlock), parent); } + public Achievement(String parString1, String parString2, int column, int row, Item parItem, Achievement parent) { + this(parString1, parString2, column, row, new ItemStack(parItem), parent); + } + public Achievement(String parString1, String parString2, int column, int row, ItemStack parItemStack, Achievement parent) { super(parString1, new ChatComponentTranslation("achievement." + parString2, new Object[0])); @@ -72,40 +75,26 @@ public class Achievement extends StatBase { this.parentAchievement = parent; } - /**+ - * Initializes the current stat as independent (i.e., lacking - * prerequisites for being updated) and returns the current - * instance. - */ - public Achievement initIndependentStat() { - this.isIndependent = true; - return this; + public Achievement func_150953_b(Class parClass1) { + return (Achievement) super.func_150953_b(parClass1); } - /**+ - * Special achievements have a 'spiked' (on normal texture pack) - * frame, special achievements are the hardest ones to achieve. + /** + * + Returns the fully description of the achievement - ready to be displayed on + * screen. */ - public Achievement setSpecial() { - this.isSpecial = true; - return this; + public String getDescription() { + return this.statStringFormatter != null + ? this.statStringFormatter.formatString(StatCollector.translateToLocal(this.achievementDescription)) + : StatCollector.translateToLocal(this.achievementDescription); } - /**+ - * Register the stat into StatList. + /** + * + Special achievements have a 'spiked' (on normal texture pack) frame, + * special achievements are the hardest ones to achieve. */ - public Achievement registerStat() { - super.registerStat(); - AchievementList.achievementList.add(this); - return this; - } - - /**+ - * Returns whether or not the StatBase-derived class is a - * statistic (running counter) or an achievement (one-shot). - */ - public boolean isAchievement() { - return true; + public boolean getSpecial() { + return this.isSpecial; } public IChatComponent getStatName() { @@ -115,33 +104,46 @@ public class Achievement extends StatBase { return ichatcomponent; } - public Achievement func_150953_b(Class parClass1) { - return (Achievement) super.func_150953_b(parClass1); - } - - /**+ - * Returns the fully description of the achievement - ready to - * be displayed on screen. + /** + * + Initializes the current stat as independent (i.e., lacking prerequisites + * for being updated) and returns the current instance. */ - public String getDescription() { - return this.statStringFormatter != null - ? this.statStringFormatter.formatString(StatCollector.translateToLocal(this.achievementDescription)) - : StatCollector.translateToLocal(this.achievementDescription); + public Achievement initIndependentStat() { + this.isIndependent = true; + return this; } - /**+ - * Defines a string formatter for the achievement. + /** + * + Returns whether or not the StatBase-derived class is a statistic (running + * counter) or an achievement (one-shot). + */ + public boolean isAchievement() { + return true; + } + + /** + * + Register the stat into StatList. + */ + public Achievement registerStat() { + super.registerStat(); + AchievementList.achievementList.add(this); + return this; + } + + /** + * + Special achievements have a 'spiked' (on normal texture pack) frame, + * special achievements are the hardest ones to achieve. + */ + public Achievement setSpecial() { + this.isSpecial = true; + return this; + } + + /** + * + Defines a string formatter for the achievement. */ public Achievement setStatStringFormatter(IStatStringFormat parIStatStringFormat) { this.statStringFormatter = parIStatStringFormat; return this; } - - /**+ - * Special achievements have a 'spiked' (on normal texture pack) - * frame, special achievements are the hardest ones to achieve. - */ - public boolean getSpecial() { - return this.isSpecial; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/AchievementList.java b/src/game/java/net/minecraft/stats/AchievementList.java index 246dde3d..ae61c36a 100644 --- a/src/game/java/net/minecraft/stats/AchievementList.java +++ b/src/game/java/net/minecraft/stats/AchievementList.java @@ -9,22 +9,25 @@ import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.JsonSerializableSet; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -70,9 +73,8 @@ public class AchievementList { public static Achievement exploreAllBiomes; public static Achievement overpowered; - /**+ - * A stub functions called to make the static initializer for - * this class run. + /** + * + A stub functions called to make the static initializer for this class run. */ public static void init() { achievementList = Lists.newArrayList(); diff --git a/src/game/java/net/minecraft/stats/IStatStringFormat.java b/src/game/java/net/minecraft/stats/IStatStringFormat.java index c7395246..5392599f 100644 --- a/src/game/java/net/minecraft/stats/IStatStringFormat.java +++ b/src/game/java/net/minecraft/stats/IStatStringFormat.java @@ -1,28 +1,31 @@ package net.minecraft.stats; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IStatStringFormat { - /**+ - * Formats the strings based on 'IStatStringFormat' interface. + /** + * + Formats the strings based on 'IStatStringFormat' interface. */ String formatString(String var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/IStatType.java b/src/game/java/net/minecraft/stats/IStatType.java index bbe7149c..3a91d9f8 100644 --- a/src/game/java/net/minecraft/stats/IStatType.java +++ b/src/game/java/net/minecraft/stats/IStatType.java @@ -1,28 +1,31 @@ package net.minecraft.stats; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IStatType { - /**+ - * Formats a given stat for human consumption. + /** + * + Formats a given stat for human consumption. */ String format(int var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/ObjectiveStat.java b/src/game/java/net/minecraft/stats/ObjectiveStat.java index 189e1a52..7aba33d2 100644 --- a/src/game/java/net/minecraft/stats/ObjectiveStat.java +++ b/src/game/java/net/minecraft/stats/ObjectiveStat.java @@ -2,22 +2,25 @@ package net.minecraft.stats; import net.minecraft.scoreboard.ScoreDummyCriteria; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/stats/StatBase.java b/src/game/java/net/minecraft/stats/StatBase.java index 019fce97..7b44befc 100644 --- a/src/game/java/net/minecraft/stats/StatBase.java +++ b/src/game/java/net/minecraft/stats/StatBase.java @@ -11,33 +11,30 @@ import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IChatComponent; import net.minecraft.util.IJsonSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StatBase { - public final String statId; - private final IChatComponent statName; - public boolean isIndependent; - private final IStatType type; - private final IScoreObjectiveCriteria field_150957_c; - private Class field_150956_d; private static NumberFormat numberFormat = NumberFormat.getIntegerInstance(Locale.US); public static IStatType simpleStatType = new IStatType() { public String format(int parInt1) { @@ -71,6 +68,16 @@ public class StatBase { return StatBase.decimalFormat.format((double) i * 0.1D); } }; + public final String statId; + private final IChatComponent statName; + public boolean isIndependent; + private final IStatType type; + private final IScoreObjectiveCriteria field_150957_c; + private Class field_150956_d; + + public StatBase(String statIdIn, IChatComponent statNameIn) { + this(statIdIn, statNameIn, simpleStatType); + } public StatBase(String statIdIn, IChatComponent statNameIn, IStatType typeIn) { this.statId = statIdIn; @@ -80,62 +87,6 @@ public class StatBase { IScoreObjectiveCriteria.INSTANCES.put(this.field_150957_c.getName(), this.field_150957_c); } - public StatBase(String statIdIn, IChatComponent statNameIn) { - this(statIdIn, statNameIn, simpleStatType); - } - - /**+ - * Initializes the current stat as independent (i.e., lacking - * prerequisites for being updated) and returns the current - * instance. - */ - public StatBase initIndependentStat() { - this.isIndependent = true; - return this; - } - - /**+ - * Register the stat into StatList. - */ - public StatBase registerStat() { - if (StatList.oneShotStats.containsKey(this.statId)) { - throw new RuntimeException( - "Duplicate stat id: \"" + ((StatBase) StatList.oneShotStats.get(this.statId)).statName + "\" and \"" - + this.statName + "\" at id " + this.statId); - } else { - StatList.allStats.add(this); - StatList.oneShotStats.put(this.statId, this); - return this; - } - } - - /**+ - * Returns whether or not the StatBase-derived class is a - * statistic (running counter) or an achievement (one-shot). - */ - public boolean isAchievement() { - return false; - } - - public String format(int parInt1) { - return this.type.format(parInt1); - } - - public IChatComponent getStatName() { - IChatComponent ichatcomponent = this.statName.createCopy(); - ichatcomponent.getChatStyle().setColor(EnumChatFormatting.GRAY); - ichatcomponent.getChatStyle().setChatHoverEvent( - new HoverEvent(HoverEvent.Action.SHOW_ACHIEVEMENT, new ChatComponentText(this.statId))); - return ichatcomponent; - } - - public IChatComponent func_150955_j() { - IChatComponent ichatcomponent = this.getStatName(); - IChatComponent ichatcomponent1 = (new ChatComponentText("[")).appendSibling(ichatcomponent).appendText("]"); - ichatcomponent1.setChatStyle(ichatcomponent.getChatStyle()); - return ichatcomponent1; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -147,25 +98,76 @@ public class StatBase { } } - public int hashCode() { - return this.statId.hashCode(); - } - - public String toString() { - return "Stat{id=" + this.statId + ", nameId=" + this.statName + ", awardLocallyOnly=" + this.isIndependent - + ", formatter=" + this.type + ", objectiveCriteria=" + this.field_150957_c + '}'; + public String format(int parInt1) { + return this.type.format(parInt1); } public IScoreObjectiveCriteria func_150952_k() { return this.field_150957_c; } - public Class func_150954_l() { - return this.field_150956_d; - } - public StatBase func_150953_b(Class oclass) { this.field_150956_d = oclass; return this; } + + public Class func_150954_l() { + return this.field_150956_d; + } + + public IChatComponent func_150955_j() { + IChatComponent ichatcomponent = this.getStatName(); + IChatComponent ichatcomponent1 = (new ChatComponentText("[")).appendSibling(ichatcomponent).appendText("]"); + ichatcomponent1.setChatStyle(ichatcomponent.getChatStyle()); + return ichatcomponent1; + } + + public IChatComponent getStatName() { + IChatComponent ichatcomponent = this.statName.createCopy(); + ichatcomponent.getChatStyle().setColor(EnumChatFormatting.GRAY); + ichatcomponent.getChatStyle().setChatHoverEvent( + new HoverEvent(HoverEvent.Action.SHOW_ACHIEVEMENT, new ChatComponentText(this.statId))); + return ichatcomponent; + } + + public int hashCode() { + return this.statId.hashCode(); + } + + /** + * + Initializes the current stat as independent (i.e., lacking prerequisites + * for being updated) and returns the current instance. + */ + public StatBase initIndependentStat() { + this.isIndependent = true; + return this; + } + + /** + * + Returns whether or not the StatBase-derived class is a statistic (running + * counter) or an achievement (one-shot). + */ + public boolean isAchievement() { + return false; + } + + /** + * + Register the stat into StatList. + */ + public StatBase registerStat() { + if (StatList.oneShotStats.containsKey(this.statId)) { + throw new RuntimeException( + "Duplicate stat id: \"" + ((StatBase) StatList.oneShotStats.get(this.statId)).statName + "\" and \"" + + this.statName + "\" at id " + this.statId); + } else { + StatList.allStats.add(this); + StatList.oneShotStats.put(this.statId, this); + return this; + } + } + + public String toString() { + return "Stat{id=" + this.statId + ", nameId=" + this.statName + ", awardLocallyOnly=" + this.isIndependent + + ", formatter=" + this.type + ", objectiveCriteria=" + this.field_150957_c + '}'; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/StatBasic.java b/src/game/java/net/minecraft/stats/StatBasic.java index e5ae485b..faabf623 100644 --- a/src/game/java/net/minecraft/stats/StatBasic.java +++ b/src/game/java/net/minecraft/stats/StatBasic.java @@ -2,37 +2,40 @@ package net.minecraft.stats; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StatBasic extends StatBase { - public StatBasic(String statIdIn, IChatComponent statNameIn, IStatType typeIn) { - super(statIdIn, statNameIn, typeIn); - } - public StatBasic(String statIdIn, IChatComponent statNameIn) { super(statIdIn, statNameIn); } - /**+ - * Register the stat into StatList. + public StatBasic(String statIdIn, IChatComponent statNameIn, IStatType typeIn) { + super(statIdIn, statNameIn, typeIn); + } + + /** + * + Register the stat into StatList. */ public StatBase registerStat() { super.registerStat(); diff --git a/src/game/java/net/minecraft/stats/StatCrafting.java b/src/game/java/net/minecraft/stats/StatCrafting.java index 13d7f8b4..3902c35f 100644 --- a/src/game/java/net/minecraft/stats/StatCrafting.java +++ b/src/game/java/net/minecraft/stats/StatCrafting.java @@ -4,22 +4,25 @@ import net.minecraft.item.Item; import net.minecraft.scoreboard.IScoreObjectiveCriteria; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/stats/StatFileWriter.java b/src/game/java/net/minecraft/stats/StatFileWriter.java index 1d10b44b..80ac9f9f 100644 --- a/src/game/java/net/minecraft/stats/StatFileWriter.java +++ b/src/game/java/net/minecraft/stats/StatFileWriter.java @@ -8,22 +8,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.IJsonSerializable; import net.minecraft.util.TupleIntJsonSerializable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,64 +34,13 @@ import net.minecraft.util.TupleIntJsonSerializable; public class StatFileWriter { protected final Map statsData = Maps.newHashMap(); - /**+ - * Returns true if the achievement has been unlocked. - */ - public boolean hasAchievementUnlocked(Achievement achievementIn) { - return this.readStat(achievementIn) > 0; - } - - /**+ - * Returns true if the parent has been unlocked, or there is no - * parent + /** + * + Returns true if the parent has been unlocked, or there is no parent */ public boolean canUnlockAchievement(Achievement achievementIn) { return achievementIn.parentAchievement == null || this.hasAchievementUnlocked(achievementIn.parentAchievement); } - public int func_150874_c(Achievement parAchievement) { - if (this.hasAchievementUnlocked(parAchievement)) { - return 0; - } else { - int i = 0; - - for (Achievement achievement = parAchievement.parentAchievement; achievement != null - && !this.hasAchievementUnlocked(achievement); ++i) { - achievement = achievement.parentAchievement; - } - - return i; - } - } - - public void increaseStat(EntityPlayer player, StatBase stat, int amount) { - if (!stat.isAchievement() || this.canUnlockAchievement((Achievement) stat)) { - this.unlockAchievement(player, stat, this.readStat(stat) + amount); - } - } - - /**+ - * Triggers the logging of an achievement and attempts to - * announce to server - */ - public void unlockAchievement(EntityPlayer var1, StatBase statbase, int i) { - TupleIntJsonSerializable tupleintjsonserializable = (TupleIntJsonSerializable) this.statsData.get(statbase); - if (tupleintjsonserializable == null) { - tupleintjsonserializable = new TupleIntJsonSerializable(); - this.statsData.put(statbase, tupleintjsonserializable); - } - - tupleintjsonserializable.setIntegerValue(i); - } - - /**+ - * Reads the given stat and returns its value as an int. - */ - public int readStat(StatBase stat) { - TupleIntJsonSerializable tupleintjsonserializable = (TupleIntJsonSerializable) this.statsData.get(stat); - return tupleintjsonserializable == null ? 0 : tupleintjsonserializable.getIntegerValue(); - } - public T func_150870_b(StatBase parStatBase) { TupleIntJsonSerializable tupleintjsonserializable = (TupleIntJsonSerializable) this.statsData.get(parStatBase); return (T) (tupleintjsonserializable != null ? tupleintjsonserializable.getJsonSerializableValue() : null); @@ -104,4 +56,53 @@ public class StatFileWriter { tupleintjsonserializable.setJsonSerializableValue(parIJsonSerializable); return (T) parIJsonSerializable; } + + public int func_150874_c(Achievement parAchievement) { + if (this.hasAchievementUnlocked(parAchievement)) { + return 0; + } else { + int i = 0; + + for (Achievement achievement = parAchievement.parentAchievement; achievement != null + && !this.hasAchievementUnlocked(achievement); ++i) { + achievement = achievement.parentAchievement; + } + + return i; + } + } + + /** + * + Returns true if the achievement has been unlocked. + */ + public boolean hasAchievementUnlocked(Achievement achievementIn) { + return this.readStat(achievementIn) > 0; + } + + public void increaseStat(EntityPlayer player, StatBase stat, int amount) { + if (!stat.isAchievement() || this.canUnlockAchievement((Achievement) stat)) { + this.unlockAchievement(player, stat, this.readStat(stat) + amount); + } + } + + /** + * + Reads the given stat and returns its value as an int. + */ + public int readStat(StatBase stat) { + TupleIntJsonSerializable tupleintjsonserializable = (TupleIntJsonSerializable) this.statsData.get(stat); + return tupleintjsonserializable == null ? 0 : tupleintjsonserializable.getIntegerValue(); + } + + /** + * + Triggers the logging of an achievement and attempts to announce to server + */ + public void unlockAchievement(EntityPlayer var1, StatBase statbase, int i) { + TupleIntJsonSerializable tupleintjsonserializable = (TupleIntJsonSerializable) this.statsData.get(statbase); + if (tupleintjsonserializable == null) { + tupleintjsonserializable = new TupleIntJsonSerializable(); + this.statsData.put(statbase, tupleintjsonserializable); + } + + tupleintjsonserializable.setIntegerValue(i); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/StatList.java b/src/game/java/net/minecraft/stats/StatList.java index 1ac5fdd9..ff0ae3e3 100644 --- a/src/game/java/net/minecraft/stats/StatList.java +++ b/src/game/java/net/minecraft/stats/StatList.java @@ -20,22 +20,25 @@ import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,125 +48,124 @@ public class StatList { public static List allStats = Lists.newArrayList(); public static List generalStats = Lists.newArrayList(); public static List itemStats = Lists.newArrayList(); - /**+ - * Tracks the number of times a given block or item has been - * mined. + /** + * + Tracks the number of times a given block or item has been mined. */ public static List objectMineStats = Lists.newArrayList(); - /**+ - * number of times you've left a game + /** + * + number of times you've left a game */ public static StatBase leaveGameStat = (new StatBasic("stat.leaveGame", new ChatComponentTranslation("stat.leaveGame", new Object[0]))).initIndependentStat().registerStat(); - /**+ - * number of minutes you have played + /** + * + number of minutes you have played */ public static StatBase minutesPlayedStat = (new StatBasic("stat.playOneMinute", new ChatComponentTranslation("stat.playOneMinute", new Object[0]), StatBase.timeStatType)) - .initIndependentStat().registerStat(); + .initIndependentStat().registerStat(); public static StatBase timeSinceDeathStat = (new StatBasic("stat.timeSinceDeath", new ChatComponentTranslation("stat.timeSinceDeath", new Object[0]), StatBase.timeStatType)) - .initIndependentStat().registerStat(); - /**+ - * distance you've walked + .initIndependentStat().registerStat(); + /** + * + distance you've walked */ public static StatBase distanceWalkedStat = (new StatBasic("stat.walkOneCm", new ChatComponentTranslation("stat.walkOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); + .initIndependentStat().registerStat(); public static StatBase distanceCrouchedStat = (new StatBasic("stat.crouchOneCm", new ChatComponentTranslation("stat.crouchOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); + .initIndependentStat().registerStat(); public static StatBase distanceSprintedStat = (new StatBasic("stat.sprintOneCm", new ChatComponentTranslation("stat.sprintOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * distance you have swam + .initIndependentStat().registerStat(); + /** + * + distance you have swam */ public static StatBase distanceSwumStat = (new StatBasic("stat.swimOneCm", new ChatComponentTranslation("stat.swimOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you have fallen + .initIndependentStat().registerStat(); + /** + * + the distance you have fallen */ public static StatBase distanceFallenStat = (new StatBasic("stat.fallOneCm", new ChatComponentTranslation("stat.fallOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you've climbed + .initIndependentStat().registerStat(); + /** + * + the distance you've climbed */ public static StatBase distanceClimbedStat = (new StatBasic("stat.climbOneCm", new ChatComponentTranslation("stat.climbOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you've flown + .initIndependentStat().registerStat(); + /** + * + the distance you've flown */ public static StatBase distanceFlownStat = (new StatBasic("stat.flyOneCm", new ChatComponentTranslation("stat.flyOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you've dived + .initIndependentStat().registerStat(); + /** + * + the distance you've dived */ public static StatBase distanceDoveStat = (new StatBasic("stat.diveOneCm", new ChatComponentTranslation("stat.diveOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you've traveled by minecart + .initIndependentStat().registerStat(); + /** + * + the distance you've traveled by minecart */ public static StatBase distanceByMinecartStat = (new StatBasic("stat.minecartOneCm", new ChatComponentTranslation("stat.minecartOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you've traveled by boat + .initIndependentStat().registerStat(); + /** + * + the distance you've traveled by boat */ public static StatBase distanceByBoatStat = (new StatBasic("stat.boatOneCm", new ChatComponentTranslation("stat.boatOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the distance you've traveled by pig + .initIndependentStat().registerStat(); + /** + * + the distance you've traveled by pig */ public static StatBase distanceByPigStat = (new StatBasic("stat.pigOneCm", new ChatComponentTranslation("stat.pigOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); + .initIndependentStat().registerStat(); public static StatBase distanceByHorseStat = (new StatBasic("stat.horseOneCm", new ChatComponentTranslation("stat.horseOneCm", new Object[0]), StatBase.distanceStatType)) - .initIndependentStat().registerStat(); - /**+ - * the times you've jumped + .initIndependentStat().registerStat(); + /** + * + the times you've jumped */ public static StatBase jumpStat = (new StatBasic("stat.jump", new ChatComponentTranslation("stat.jump", new Object[0]))).initIndependentStat().registerStat(); - /**+ - * the distance you've dropped (or times you've fallen?) + /** + * + the distance you've dropped (or times you've fallen?) */ public static StatBase dropStat = (new StatBasic("stat.drop", new ChatComponentTranslation("stat.drop", new Object[0]))).initIndependentStat().registerStat(); - /**+ - * the amount of damage you've dealt + /** + * + the amount of damage you've dealt */ public static StatBase damageDealtStat = (new StatBasic("stat.damageDealt", new ChatComponentTranslation("stat.damageDealt", new Object[0]), StatBase.field_111202_k)).registerStat(); - /**+ - * the amount of damage you have taken + /** + * + the amount of damage you have taken */ public static StatBase damageTakenStat = (new StatBasic("stat.damageTaken", new ChatComponentTranslation("stat.damageTaken", new Object[0]), StatBase.field_111202_k)).registerStat(); - /**+ - * the number of times you have died + /** + * + the number of times you have died */ public static StatBase deathsStat = (new StatBasic("stat.deaths", new ChatComponentTranslation("stat.deaths", new Object[0]))).registerStat(); - /**+ - * the number of mobs you have killed + /** + * + the number of mobs you have killed */ public static StatBase mobKillsStat = (new StatBasic("stat.mobKills", new ChatComponentTranslation("stat.mobKills", new Object[0]))).registerStat(); - /**+ - * the number of animals you have bred + /** + * + the number of animals you have bred */ public static StatBase animalsBredStat = (new StatBasic("stat.animalsBred", new ChatComponentTranslation("stat.animalsBred", new Object[0]))).registerStat(); - /**+ - * counts the number of times you've killed a player + /** + * + counts the number of times you've killed a player */ public static StatBase playerKillsStat = (new StatBasic("stat.playerKills", new ChatComponentTranslation("stat.playerKills", new Object[0]))).registerStat(); @@ -218,22 +220,46 @@ public class StatList { public static StatBase field_181723_aa = (new StatBasic("stat.chestOpened", new ChatComponentTranslation("stat.chestOpened", new Object[0]))).registerStat(); public static final StatBase[] mineBlockStatArray = new StatBase[4096]; - /**+ - * Tracks the number of items a given block or item has been - * crafted. + /** + * + Tracks the number of items a given block or item has been crafted. */ public static final StatBase[] objectCraftStats = new StatBase[32000]; - /**+ - * Tracks the number of times a given block or item has been - * used. + /** + * + Tracks the number of times a given block or item has been used. */ public static final StatBase[] objectUseStats = new StatBase[32000]; - /**+ - * Tracks the number of times a given block or item has been - * broken. + /** + * + Tracks the number of times a given block or item has been broken. */ public static final StatBase[] objectBreakStats = new StatBase[32000]; + private static String func_180204_a(Item parItem) { + ResourceLocation resourcelocation = (ResourceLocation) Item.itemRegistry.getNameForObject(parItem); + return resourcelocation != null ? resourcelocation.toString().replace(':', '.') : null; + } + + public static StatBase getOneShotStat(String parString1) { + return (StatBase) oneShotStats.get(parString1); + } + + public static StatBase getStatEntityKilledBy(EntityList.EntityEggInfo eggInfo) { + String s = EntityList.getStringFromID(eggInfo.spawnedID); + return s == null ? null + : (new StatBase("stat.entityKilledBy." + s, + new ChatComponentTranslation("stat.entityKilledBy", + new Object[] { new ChatComponentTranslation("entity." + s + ".name", new Object[0]) }))) + .registerStat(); + } + + public static StatBase getStatKillEntity(EntityList.EntityEggInfo eggInfo) { + String s = EntityList.getStringFromID(eggInfo.spawnedID); + return s == null ? null + : (new StatBase("stat.killEntity." + s, + new ChatComponentTranslation("stat.entityKill", + new Object[] { new ChatComponentTranslation("entity." + s + ".name", new Object[0]) }))) + .registerStat(); + } + public static void init() { initMiningStats(); initStats(); @@ -243,9 +269,9 @@ public class StatList { EntityList.func_151514_a(); } - /**+ - * Initializes statistics related to craftable items. Is only - * called after both block and item stats have been initialized. + /** + * + Initializes statistics related to craftable items. Is only called after + * both block and item stats have been initialized. */ private static void initCraftableStats() { HashSet hashset = Sets.newHashSet(); @@ -267,7 +293,7 @@ public class StatList { if (s != null) { objectCraftStats[i] = (new StatCrafting("stat.craftItem.", s, new ChatComponentTranslation( "stat.craftItem", new Object[] { (new ItemStack(item)).getChatComponent() }), item)) - .registerStat(); + .registerStat(); } } } @@ -275,6 +301,22 @@ public class StatList { replaceAllSimilarBlocks(objectCraftStats); } + private static void initItemDepleteStats() { + for (Item item : Item.itemRegistry) { + if (item != null) { + int i = Item.getIdFromItem(item); + String s = func_180204_a(item); + if (s != null && item.isDamageable()) { + objectBreakStats[i] = (new StatCrafting("stat.breakItem.", s, new ChatComponentTranslation( + "stat.breakItem", new Object[] { (new ItemStack(item)).getChatComponent() }), item)) + .registerStat(); + } + } + } + + replaceAllSimilarBlocks(objectBreakStats); + } + private static void initMiningStats() { for (Block block : Block.blockRegistry) { Item item = Item.getItemFromBlock(block); @@ -284,7 +326,7 @@ public class StatList { if (s != null && block.getEnableStats()) { mineBlockStatArray[i] = (new StatCrafting("stat.mineBlock.", s, new ChatComponentTranslation( "stat.mineBlock", new Object[] { (new ItemStack(block)).getChatComponent() }), item)) - .registerStat(); + .registerStat(); objectMineStats.add((StatCrafting) mineBlockStatArray[i]); } } @@ -301,7 +343,7 @@ public class StatList { if (s != null) { objectUseStats[i] = (new StatCrafting("stat.useItem.", s, new ChatComponentTranslation( "stat.useItem", new Object[] { (new ItemStack(item)).getChatComponent() }), item)) - .registerStat(); + .registerStat(); if (!(item instanceof ItemBlock)) { itemStats.add((StatCrafting) objectUseStats[i]); } @@ -312,30 +354,24 @@ public class StatList { replaceAllSimilarBlocks(objectUseStats); } - private static void initItemDepleteStats() { - for (Item item : Item.itemRegistry) { - if (item != null) { - int i = Item.getIdFromItem(item); - String s = func_180204_a(item); - if (s != null && item.isDamageable()) { - objectBreakStats[i] = (new StatCrafting("stat.breakItem.", s, new ChatComponentTranslation( - "stat.breakItem", new Object[] { (new ItemStack(item)).getChatComponent() }), item)) - .registerStat(); - } - } + /** + * + Merge {@link StatBase} object references for similar blocks + */ + private static void mergeStatBases(StatBase[] statBaseIn, Block parBlock, Block parBlock2) { + int i = Block.getIdFromBlock(parBlock); + int j = Block.getIdFromBlock(parBlock2); + if (statBaseIn[i] != null && statBaseIn[j] == null) { + statBaseIn[j] = statBaseIn[i]; + } else { + allStats.remove(statBaseIn[i]); + objectMineStats.remove(statBaseIn[i]); + generalStats.remove(statBaseIn[i]); + statBaseIn[i] = statBaseIn[j]; } - - replaceAllSimilarBlocks(objectBreakStats); } - private static String func_180204_a(Item parItem) { - ResourceLocation resourcelocation = (ResourceLocation) Item.itemRegistry.getNameForObject(parItem); - return resourcelocation != null ? resourcelocation.toString().replace(':', '.') : null; - } - - /**+ - * Forces all dual blocks to count for each other on the stats - * list + /** + * + Forces all dual blocks to count for each other on the stats list */ private static void replaceAllSimilarBlocks(StatBase[] parArrayOfStatBase) { mergeStatBases(parArrayOfStatBase, Blocks.water, Blocks.flowing_water); @@ -353,42 +389,4 @@ public class StatList { mergeStatBases(parArrayOfStatBase, Blocks.grass, Blocks.dirt); mergeStatBases(parArrayOfStatBase, Blocks.farmland, Blocks.dirt); } - - /**+ - * Merge {@link StatBase} object references for similar blocks - */ - private static void mergeStatBases(StatBase[] statBaseIn, Block parBlock, Block parBlock2) { - int i = Block.getIdFromBlock(parBlock); - int j = Block.getIdFromBlock(parBlock2); - if (statBaseIn[i] != null && statBaseIn[j] == null) { - statBaseIn[j] = statBaseIn[i]; - } else { - allStats.remove(statBaseIn[i]); - objectMineStats.remove(statBaseIn[i]); - generalStats.remove(statBaseIn[i]); - statBaseIn[i] = statBaseIn[j]; - } - } - - public static StatBase getStatKillEntity(EntityList.EntityEggInfo eggInfo) { - String s = EntityList.getStringFromID(eggInfo.spawnedID); - return s == null ? null - : (new StatBase("stat.killEntity." + s, - new ChatComponentTranslation("stat.entityKill", - new Object[] { new ChatComponentTranslation("entity." + s + ".name", new Object[0]) }))) - .registerStat(); - } - - public static StatBase getStatEntityKilledBy(EntityList.EntityEggInfo eggInfo) { - String s = EntityList.getStringFromID(eggInfo.spawnedID); - return s == null ? null - : (new StatBase("stat.entityKilledBy." + s, - new ChatComponentTranslation("stat.entityKilledBy", - new Object[] { new ChatComponentTranslation("entity." + s + ".name", new Object[0]) }))) - .registerStat(); - } - - public static StatBase getOneShotStat(String parString1) { - return (StatBase) oneShotStats.get(parString1); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/stats/StatisticsFile.java b/src/game/java/net/minecraft/stats/StatisticsFile.java index b33e4aed..e97b86c0 100644 --- a/src/game/java/net/minecraft/stats/StatisticsFile.java +++ b/src/game/java/net/minecraft/stats/StatisticsFile.java @@ -1,13 +1,21 @@ package net.minecraft.stats; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import java.util.Set; import java.util.Map.Entry; +import java.util.Set; + +import org.json.JSONException; +import org.json.JSONObject; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S37PacketStatistics; @@ -15,39 +23,65 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IJsonSerializable; import net.minecraft.util.TupleIntJsonSerializable; -import org.json.JSONException; -import org.json.JSONObject; -import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StatisticsFile extends StatFileWriter { private static final Logger logger = LogManager.getLogger(); + + public static String dumpJson(Map parMap) { + JSONObject jsonobject = new JSONObject(); + + for (Entry entry : parMap.entrySet()) { + if (((TupleIntJsonSerializable) entry.getValue()).getJsonSerializableValue() != null) { + JSONObject jsonobject1 = new JSONObject(); + jsonobject1.put("value", + Integer.valueOf(((TupleIntJsonSerializable) entry.getValue()).getIntegerValue())); + + try { + jsonobject1.put("progress", ((TupleIntJsonSerializable) entry.getValue()).getJsonSerializableValue() + .getSerializableElement()); + } catch (Throwable throwable) { + logger.warn("Couldn\'t save statistic " + ((StatBase) entry.getKey()).getStatName() + + ": error serializing progress", throwable); + } + + jsonobject.put(((StatBase) entry.getKey()).statId, jsonobject1); + } else { + jsonobject.put(((StatBase) entry.getKey()).statId, + Integer.valueOf(((TupleIntJsonSerializable) entry.getValue()).getIntegerValue())); + } + } + + return jsonobject.toString(); + } + private final MinecraftServer mcServer; private final VFile2 statsFile; private final Set field_150888_e = Sets.newHashSet(); private int field_150885_f = -300; + private boolean field_150886_g = false; public StatisticsFile(MinecraftServer serverIn, VFile2 statsFileIn) { @@ -55,45 +89,23 @@ public class StatisticsFile extends StatFileWriter { this.statsFile = statsFileIn; } - public void readStatFile() { - if (this.statsFile.exists()) { - try { - this.statsData.clear(); - this.statsData.putAll(this.parseJson(this.statsFile.getAllChars())); - } catch (JSONException jsonparseexception) { - logger.error("Couldn\'t parse statistics file " + this.statsFile, jsonparseexception); + public void func_150876_a(EntityPlayerMP parEntityPlayerMP) { + int i = this.mcServer.getTickCounter(); + HashMap hashmap = Maps.newHashMap(); + if (this.field_150886_g || i - this.field_150885_f > 300) { + this.field_150885_f = i; + + for (StatBase statbase : this.func_150878_c()) { + hashmap.put(statbase, Integer.valueOf(this.readStat(statbase))); } } + parEntityPlayerMP.playerNetServerHandler.sendPacket(new S37PacketStatistics(hashmap)); } - public void saveStatFile() { - this.statsFile.setAllChars(dumpJson(this.statsData)); - } - - /**+ - * Triggers the logging of an achievement and attempts to - * announce to server - */ - public void unlockAchievement(EntityPlayer playerIn, StatBase statIn, int parInt1) { - int i = statIn.isAchievement() ? this.readStat(statIn) : 0; - super.unlockAchievement(playerIn, statIn, parInt1); - this.field_150888_e.add(statIn); - if (statIn.isAchievement() && i == 0 && parInt1 > 0) { - this.field_150886_g = true; - if (this.mcServer.isAnnouncingPlayerAchievements()) { - this.mcServer.getConfigurationManager().sendChatMsg(new ChatComponentTranslation( - "chat.type.achievement", new Object[] { playerIn.getDisplayName(), statIn.func_150955_j() })); - } - } - - if (statIn.isAchievement() && i > 0 && parInt1 == 0) { - this.field_150886_g = true; - if (this.mcServer.isAnnouncingPlayerAchievements()) { - this.mcServer.getConfigurationManager() - .sendChatMsg(new ChatComponentTranslation("chat.type.achievement.taken", - new Object[] { playerIn.getDisplayName(), statIn.func_150955_j() })); - } + public void func_150877_d() { + for (StatBase statbase : this.statsData.keySet()) { + this.field_150888_e.add(statbase); } } @@ -105,6 +117,10 @@ public class StatisticsFile extends StatFileWriter { return hashset; } + public boolean func_150879_e() { + return this.field_150886_g; + } + public Map parseJson(String parString1) { JSONObject jsonobject = null; try { @@ -153,52 +169,20 @@ public class StatisticsFile extends StatFileWriter { } } - public static String dumpJson(Map parMap) { - JSONObject jsonobject = new JSONObject(); - - for (Entry entry : parMap.entrySet()) { - if (((TupleIntJsonSerializable) entry.getValue()).getJsonSerializableValue() != null) { - JSONObject jsonobject1 = new JSONObject(); - jsonobject1.put("value", - Integer.valueOf(((TupleIntJsonSerializable) entry.getValue()).getIntegerValue())); - - try { - jsonobject1.put("progress", ((TupleIntJsonSerializable) entry.getValue()).getJsonSerializableValue() - .getSerializableElement()); - } catch (Throwable throwable) { - logger.warn("Couldn\'t save statistic " + ((StatBase) entry.getKey()).getStatName() - + ": error serializing progress", throwable); - } - - jsonobject.put(((StatBase) entry.getKey()).statId, jsonobject1); - } else { - jsonobject.put(((StatBase) entry.getKey()).statId, - Integer.valueOf(((TupleIntJsonSerializable) entry.getValue()).getIntegerValue())); + public void readStatFile() { + if (this.statsFile.exists()) { + try { + this.statsData.clear(); + this.statsData.putAll(this.parseJson(this.statsFile.getAllChars())); + } catch (JSONException jsonparseexception) { + logger.error("Couldn\'t parse statistics file " + this.statsFile, jsonparseexception); } } - return jsonobject.toString(); - } - - public void func_150877_d() { - for (StatBase statbase : this.statsData.keySet()) { - this.field_150888_e.add(statbase); - } - } - public void func_150876_a(EntityPlayerMP parEntityPlayerMP) { - int i = this.mcServer.getTickCounter(); - HashMap hashmap = Maps.newHashMap(); - if (this.field_150886_g || i - this.field_150885_f > 300) { - this.field_150885_f = i; - - for (StatBase statbase : this.func_150878_c()) { - hashmap.put(statbase, Integer.valueOf(this.readStat(statbase))); - } - } - - parEntityPlayerMP.playerNetServerHandler.sendPacket(new S37PacketStatistics(hashmap)); + public void saveStatFile() { + this.statsFile.setAllChars(dumpJson(this.statsData)); } public void sendAchievements(EntityPlayerMP player) { @@ -215,7 +199,29 @@ public class StatisticsFile extends StatFileWriter { player.playerNetServerHandler.sendPacket(new S37PacketStatistics(hashmap)); } - public boolean func_150879_e() { - return this.field_150886_g; + /** + * + Triggers the logging of an achievement and attempts to announce to server + */ + public void unlockAchievement(EntityPlayer playerIn, StatBase statIn, int parInt1) { + int i = statIn.isAchievement() ? this.readStat(statIn) : 0; + super.unlockAchievement(playerIn, statIn, parInt1); + this.field_150888_e.add(statIn); + if (statIn.isAchievement() && i == 0 && parInt1 > 0) { + this.field_150886_g = true; + if (this.mcServer.isAnnouncingPlayerAchievements()) { + this.mcServer.getConfigurationManager().sendChatMsg(new ChatComponentTranslation( + "chat.type.achievement", new Object[] { playerIn.getDisplayName(), statIn.func_150955_j() })); + } + } + + if (statIn.isAchievement() && i > 0 && parInt1 == 0) { + this.field_150886_g = true; + if (this.mcServer.isAnnouncingPlayerAchievements()) { + this.mcServer.getConfigurationManager() + .sendChatMsg(new ChatComponentTranslation("chat.type.achievement.taken", + new Object[] { playerIn.getDisplayName(), statIn.func_150955_j() })); + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/IHopper.java b/src/game/java/net/minecraft/tileentity/IHopper.java index 6b0c1aac..65b4897b 100644 --- a/src/game/java/net/minecraft/tileentity/IHopper.java +++ b/src/game/java/net/minecraft/tileentity/IHopper.java @@ -3,44 +3,47 @@ package net.minecraft.tileentity; import net.minecraft.inventory.IInventory; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IHopper extends IInventory { - /**+ - * Returns the worldObj for this tileEntity. + /** + * + Returns the worldObj for this tileEntity. */ World getWorld(); - /**+ - * Gets the world X position for this hopper entity. + /** + * + Gets the world X position for this hopper entity. */ double getXPos(); - /**+ - * Gets the world Y position for this hopper entity. + /** + * + Gets the world Y position for this hopper entity. */ double getYPos(); - /**+ - * Gets the world Z position for this hopper entity. + /** + * + Gets the world Z position for this hopper entity. */ double getZPos(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/MobSpawnerBaseLogic.java b/src/game/java/net/minecraft/tileentity/MobSpawnerBaseLogic.java index 350b5a07..a55a9aa6 100644 --- a/src/game/java/net/minecraft/tileentity/MobSpawnerBaseLogic.java +++ b/src/game/java/net/minecraft/tileentity/MobSpawnerBaseLogic.java @@ -20,34 +20,73 @@ import net.minecraft.util.StringUtils; import net.minecraft.util.WeightedRandom; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class MobSpawnerBaseLogic { - /**+ - * The delay to spawn. + public class WeightedRandomMinecart extends WeightedRandom.Item { + private final NBTTagCompound nbtData; + private final String entityType; + + public WeightedRandomMinecart(NBTTagCompound tagCompound) { + this(tagCompound.getCompoundTag("Properties"), tagCompound.getString("Type"), + tagCompound.getInteger("Weight")); + } + + public WeightedRandomMinecart(NBTTagCompound tagCompound, String type) { + this(tagCompound, type, 1); + } + + private WeightedRandomMinecart(NBTTagCompound tagCompound, String type, int weight) { + super(weight); + if (type.equals("Minecart")) { + if (tagCompound != null) { + type = EntityMinecart.EnumMinecartType.byNetworkID(tagCompound.getInteger("Type")).getName(); + } else { + type = "MinecartRideable"; + } + } + + this.nbtData = tagCompound; + this.entityType = type; + } + + public NBTTagCompound toNBT() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setTag("Properties", this.nbtData); + nbttagcompound.setString("Type", this.entityType); + nbttagcompound.setInteger("Weight", this.itemWeight); + return nbttagcompound; + } + } + + /** + * + The delay to spawn. */ private int spawnDelay = 20; private String mobID = "Pig"; - /**+ - * List of minecart to spawn. + /** + * + List of minecart to spawn. */ private final List minecartToSpawn = Lists.newArrayList(); private MobSpawnerBaseLogic.WeightedRandomMinecart randomEntity; @@ -58,17 +97,32 @@ public abstract class MobSpawnerBaseLogic { private int spawnCount = 4; private Entity cachedEntity; private int maxNearbyEntities = 6; - /**+ - * The distance from which a player activates the spawner. + /** + * + The distance from which a player activates the spawner. */ private int activatingRangeFromPlayer = 16; - /**+ - * The range coefficient for spawning entities around. + + /** + * + The range coefficient for spawning entities around. */ private int spawnRange = 4; - /**+ - * Gets the entity name that should be spawned. + public Entity func_180612_a(World worldIn) { + if (this.cachedEntity == null) { + Entity entity = EntityList.createEntityByName(this.getEntityNameToSpawn(), worldIn); + if (entity != null) { + entity = this.spawnNewEntity(entity, false); + this.cachedEntity = entity; + } + } + + return this.cachedEntity; + } + + public abstract void func_98267_a(int var1); + + /** + * + Gets the entity name that should be spawned. */ private String getEntityNameToSpawn() { if (this.getRandomEntity() == null) { @@ -82,13 +136,25 @@ public abstract class MobSpawnerBaseLogic { } } - public void setEntityName(String name) { - this.mobID = name; + public double getMobRotation() { + return this.mobRotation; } - /**+ - * Returns true if there's a player close enough to this mob - * spawner to activate it. + public double getPrevMobRotation() { + return this.prevMobRotation; + } + + private MobSpawnerBaseLogic.WeightedRandomMinecart getRandomEntity() { + return this.randomEntity; + } + + public abstract BlockPos getSpawnerPosition(); + + public abstract World getSpawnerWorld(); + + /** + * + Returns true if there's a player close enough to this mob spawner to + * activate it. */ private boolean isActivated() { BlockPos blockpos = this.getSpawnerPosition(); @@ -97,82 +163,81 @@ public abstract class MobSpawnerBaseLogic { (double) this.activatingRangeFromPlayer); } - public void updateSpawner() { - if (this.isActivated()) { - BlockPos blockpos = this.getSpawnerPosition(); - if (this.getSpawnerWorld().isRemote) { - double d3 = (double) ((float) blockpos.getX() + this.getSpawnerWorld().rand.nextFloat()); - double d4 = (double) ((float) blockpos.getY() + this.getSpawnerWorld().rand.nextFloat()); - double d5 = (double) ((float) blockpos.getZ() + this.getSpawnerWorld().rand.nextFloat()); - this.getSpawnerWorld().spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d3, d4, d5, 0.0D, 0.0D, 0.0D, - new int[0]); - this.getSpawnerWorld().spawnParticle(EnumParticleTypes.FLAME, d3, d4, d5, 0.0D, 0.0D, 0.0D, new int[0]); - if (this.spawnDelay > 0) { - --this.spawnDelay; - } + public void readFromNBT(NBTTagCompound nbt) { + this.mobID = nbt.getString("EntityId"); + this.spawnDelay = nbt.getShort("Delay"); + this.minecartToSpawn.clear(); + if (nbt.hasKey("SpawnPotentials", 9)) { + NBTTagList nbttaglist = nbt.getTagList("SpawnPotentials", 10); - this.prevMobRotation = this.mobRotation; - this.mobRotation = (this.mobRotation + (double) (1000.0F / ((float) this.spawnDelay + 200.0F))) - % 360.0D; - } else { - if (this.spawnDelay == -1) { - this.resetTimer(); - } - - if (this.spawnDelay > 0) { - --this.spawnDelay; - return; - } - - boolean flag = false; - - for (int i = 0; i < this.spawnCount; ++i) { - Entity entity = EntityList.createEntityByName(this.getEntityNameToSpawn(), this.getSpawnerWorld()); - if (entity == null) { - return; - } - - int j = this.getSpawnerWorld() - .getEntitiesWithinAABB(entity.getClass(), - (new AxisAlignedBB((double) blockpos.getX(), (double) blockpos.getY(), - (double) blockpos.getZ(), (double) (blockpos.getX() + 1), - (double) (blockpos.getY() + 1), (double) (blockpos.getZ() + 1))).expand( - (double) this.spawnRange, (double) this.spawnRange, - (double) this.spawnRange)) - .size(); - if (j >= this.maxNearbyEntities) { - this.resetTimer(); - return; - } - - double d0 = (double) blockpos.getX() - + (this.getSpawnerWorld().rand.nextDouble() - this.getSpawnerWorld().rand.nextDouble()) - * (double) this.spawnRange - + 0.5D; - double d1 = (double) (blockpos.getY() + this.getSpawnerWorld().rand.nextInt(3) - 1); - double d2 = (double) blockpos.getZ() - + (this.getSpawnerWorld().rand.nextDouble() - this.getSpawnerWorld().rand.nextDouble()) - * (double) this.spawnRange - + 0.5D; - EntityLiving entityliving = entity instanceof EntityLiving ? (EntityLiving) entity : null; - entity.setLocationAndAngles(d0, d1, d2, this.getSpawnerWorld().rand.nextFloat() * 360.0F, 0.0F); - if (entityliving == null || entityliving.getCanSpawnHere() && entityliving.isNotColliding()) { - this.spawnNewEntity(entity, true); - this.getSpawnerWorld().playAuxSFX(2004, blockpos, 0); - if (entityliving != null) { - entityliving.spawnExplosionParticle(); - } - - flag = true; - } - } - - if (flag) { - this.resetTimer(); - } + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + this.minecartToSpawn + .add(new MobSpawnerBaseLogic.WeightedRandomMinecart(nbttaglist.getCompoundTagAt(i))); } - } + + if (nbt.hasKey("SpawnData", 10)) { + this.setRandomEntity( + new MobSpawnerBaseLogic.WeightedRandomMinecart(nbt.getCompoundTag("SpawnData"), this.mobID)); + } else { + this.setRandomEntity((MobSpawnerBaseLogic.WeightedRandomMinecart) null); + } + + if (nbt.hasKey("MinSpawnDelay", 99)) { + this.minSpawnDelay = nbt.getShort("MinSpawnDelay"); + this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay"); + this.spawnCount = nbt.getShort("SpawnCount"); + } + + if (nbt.hasKey("MaxNearbyEntities", 99)) { + this.maxNearbyEntities = nbt.getShort("MaxNearbyEntities"); + this.activatingRangeFromPlayer = nbt.getShort("RequiredPlayerRange"); + } + + if (nbt.hasKey("SpawnRange", 99)) { + this.spawnRange = nbt.getShort("SpawnRange"); + } + + if (this.getSpawnerWorld() != null) { + this.cachedEntity = null; + } + + } + + private void resetTimer() { + if (this.maxSpawnDelay <= this.minSpawnDelay) { + this.spawnDelay = this.minSpawnDelay; + } else { + int i = this.maxSpawnDelay - this.minSpawnDelay; + this.spawnDelay = this.minSpawnDelay + this.getSpawnerWorld().rand.nextInt(i); + } + + if (this.minecartToSpawn.size() > 0) { + this.setRandomEntity((MobSpawnerBaseLogic.WeightedRandomMinecart) WeightedRandom + .getRandomItem(this.getSpawnerWorld().rand, this.minecartToSpawn)); + } + + this.func_98267_a(1); + } + + /** + * + Sets the delay to minDelay if parameter given is 1, else return false. + */ + public boolean setDelayToMin(int delay) { + if (delay == 1 && this.getSpawnerWorld().isRemote) { + this.spawnDelay = this.minSpawnDelay; + return true; + } else { + return false; + } + } + + public void setEntityName(String name) { + this.mobID = name; + } + + public void setRandomEntity(MobSpawnerBaseLogic.WeightedRandomMinecart parWeightedRandomMinecart) { + this.randomEntity = parWeightedRandomMinecart; } private Entity spawnNewEntity(Entity entityIn, boolean spawn) { @@ -227,61 +292,82 @@ public abstract class MobSpawnerBaseLogic { return entityIn; } - private void resetTimer() { - if (this.maxSpawnDelay <= this.minSpawnDelay) { - this.spawnDelay = this.minSpawnDelay; - } else { - int i = this.maxSpawnDelay - this.minSpawnDelay; - this.spawnDelay = this.minSpawnDelay + this.getSpawnerWorld().rand.nextInt(i); - } + public void updateSpawner() { + if (this.isActivated()) { + BlockPos blockpos = this.getSpawnerPosition(); + if (this.getSpawnerWorld().isRemote) { + double d3 = (double) ((float) blockpos.getX() + this.getSpawnerWorld().rand.nextFloat()); + double d4 = (double) ((float) blockpos.getY() + this.getSpawnerWorld().rand.nextFloat()); + double d5 = (double) ((float) blockpos.getZ() + this.getSpawnerWorld().rand.nextFloat()); + this.getSpawnerWorld().spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d3, d4, d5, 0.0D, 0.0D, 0.0D, + new int[0]); + this.getSpawnerWorld().spawnParticle(EnumParticleTypes.FLAME, d3, d4, d5, 0.0D, 0.0D, 0.0D, new int[0]); + if (this.spawnDelay > 0) { + --this.spawnDelay; + } - if (this.minecartToSpawn.size() > 0) { - this.setRandomEntity((MobSpawnerBaseLogic.WeightedRandomMinecart) WeightedRandom - .getRandomItem(this.getSpawnerWorld().rand, this.minecartToSpawn)); - } + this.prevMobRotation = this.mobRotation; + this.mobRotation = (this.mobRotation + (double) (1000.0F / ((float) this.spawnDelay + 200.0F))) + % 360.0D; + } else { + if (this.spawnDelay == -1) { + this.resetTimer(); + } - this.func_98267_a(1); - } + if (this.spawnDelay > 0) { + --this.spawnDelay; + return; + } - public void readFromNBT(NBTTagCompound nbt) { - this.mobID = nbt.getString("EntityId"); - this.spawnDelay = nbt.getShort("Delay"); - this.minecartToSpawn.clear(); - if (nbt.hasKey("SpawnPotentials", 9)) { - NBTTagList nbttaglist = nbt.getTagList("SpawnPotentials", 10); + boolean flag = false; - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - this.minecartToSpawn - .add(new MobSpawnerBaseLogic.WeightedRandomMinecart(nbttaglist.getCompoundTagAt(i))); + for (int i = 0; i < this.spawnCount; ++i) { + Entity entity = EntityList.createEntityByName(this.getEntityNameToSpawn(), this.getSpawnerWorld()); + if (entity == null) { + return; + } + + int j = this.getSpawnerWorld() + .getEntitiesWithinAABB(entity.getClass(), + (new AxisAlignedBB((double) blockpos.getX(), (double) blockpos.getY(), + (double) blockpos.getZ(), (double) (blockpos.getX() + 1), + (double) (blockpos.getY() + 1), (double) (blockpos.getZ() + 1))) + .expand((double) this.spawnRange, (double) this.spawnRange, + (double) this.spawnRange)) + .size(); + if (j >= this.maxNearbyEntities) { + this.resetTimer(); + return; + } + + double d0 = (double) blockpos.getX() + + (this.getSpawnerWorld().rand.nextDouble() - this.getSpawnerWorld().rand.nextDouble()) + * (double) this.spawnRange + + 0.5D; + double d1 = (double) (blockpos.getY() + this.getSpawnerWorld().rand.nextInt(3) - 1); + double d2 = (double) blockpos.getZ() + + (this.getSpawnerWorld().rand.nextDouble() - this.getSpawnerWorld().rand.nextDouble()) + * (double) this.spawnRange + + 0.5D; + EntityLiving entityliving = entity instanceof EntityLiving ? (EntityLiving) entity : null; + entity.setLocationAndAngles(d0, d1, d2, this.getSpawnerWorld().rand.nextFloat() * 360.0F, 0.0F); + if (entityliving == null || entityliving.getCanSpawnHere() && entityliving.isNotColliding()) { + this.spawnNewEntity(entity, true); + this.getSpawnerWorld().playAuxSFX(2004, blockpos, 0); + if (entityliving != null) { + entityliving.spawnExplosionParticle(); + } + + flag = true; + } + } + + if (flag) { + this.resetTimer(); + } } - } - if (nbt.hasKey("SpawnData", 10)) { - this.setRandomEntity( - new MobSpawnerBaseLogic.WeightedRandomMinecart(nbt.getCompoundTag("SpawnData"), this.mobID)); - } else { - this.setRandomEntity((MobSpawnerBaseLogic.WeightedRandomMinecart) null); } - - if (nbt.hasKey("MinSpawnDelay", 99)) { - this.minSpawnDelay = nbt.getShort("MinSpawnDelay"); - this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay"); - this.spawnCount = nbt.getShort("SpawnCount"); - } - - if (nbt.hasKey("MaxNearbyEntities", 99)) { - this.maxNearbyEntities = nbt.getShort("MaxNearbyEntities"); - this.activatingRangeFromPlayer = nbt.getShort("RequiredPlayerRange"); - } - - if (nbt.hasKey("SpawnRange", 99)) { - this.spawnRange = nbt.getShort("SpawnRange"); - } - - if (this.getSpawnerWorld() != null) { - this.cachedEntity = null; - } - } public void writeToNBT(NBTTagCompound nbt) { @@ -315,87 +401,4 @@ public abstract class MobSpawnerBaseLogic { } } - - public Entity func_180612_a(World worldIn) { - if (this.cachedEntity == null) { - Entity entity = EntityList.createEntityByName(this.getEntityNameToSpawn(), worldIn); - if (entity != null) { - entity = this.spawnNewEntity(entity, false); - this.cachedEntity = entity; - } - } - - return this.cachedEntity; - } - - /**+ - * Sets the delay to minDelay if parameter given is 1, else - * return false. - */ - public boolean setDelayToMin(int delay) { - if (delay == 1 && this.getSpawnerWorld().isRemote) { - this.spawnDelay = this.minSpawnDelay; - return true; - } else { - return false; - } - } - - private MobSpawnerBaseLogic.WeightedRandomMinecart getRandomEntity() { - return this.randomEntity; - } - - public void setRandomEntity(MobSpawnerBaseLogic.WeightedRandomMinecart parWeightedRandomMinecart) { - this.randomEntity = parWeightedRandomMinecart; - } - - public abstract void func_98267_a(int var1); - - public abstract World getSpawnerWorld(); - - public abstract BlockPos getSpawnerPosition(); - - public double getMobRotation() { - return this.mobRotation; - } - - public double getPrevMobRotation() { - return this.prevMobRotation; - } - - public class WeightedRandomMinecart extends WeightedRandom.Item { - private final NBTTagCompound nbtData; - private final String entityType; - - public WeightedRandomMinecart(NBTTagCompound tagCompound) { - this(tagCompound.getCompoundTag("Properties"), tagCompound.getString("Type"), - tagCompound.getInteger("Weight")); - } - - public WeightedRandomMinecart(NBTTagCompound tagCompound, String type) { - this(tagCompound, type, 1); - } - - private WeightedRandomMinecart(NBTTagCompound tagCompound, String type, int weight) { - super(weight); - if (type.equals("Minecart")) { - if (tagCompound != null) { - type = EntityMinecart.EnumMinecartType.byNetworkID(tagCompound.getInteger("Type")).getName(); - } else { - type = "MinecartRideable"; - } - } - - this.nbtData = tagCompound; - this.entityType = type; - } - - public NBTTagCompound toNBT() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setTag("Properties", this.nbtData); - nbttagcompound.setString("Type", this.entityType); - nbttagcompound.setInteger("Weight", this.itemWeight); - return nbttagcompound; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntity.java b/src/game/java/net/minecraft/tileentity/TileEntity.java index eddb2f38..2960652b 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntity.java +++ b/src/game/java/net/minecraft/tileentity/TileEntity.java @@ -18,22 +18,25 @@ import net.minecraft.network.Packet; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,15 +45,33 @@ public abstract class TileEntity { private static final Logger logger = LogManager.getLogger(); private static Map> nameToClassMap = Maps.newHashMap(); private static Map, String> classToNameMap = Maps.newHashMap(); - protected World worldObj; - protected BlockPos pos = BlockPos.ORIGIN; - protected boolean tileEntityInvalid; - private int blockMetadata = -1; - protected Block blockType; + static { + addMapping(TileEntityFurnace.class, "Furnace"); + addMapping(TileEntityChest.class, "Chest"); + addMapping(TileEntityEnderChest.class, "EnderChest"); + addMapping(BlockJukebox.TileEntityJukebox.class, "RecordPlayer"); + addMapping(TileEntityDispenser.class, "Trap"); + addMapping(TileEntityDropper.class, "Dropper"); + addMapping(TileEntitySign.class, "Sign"); + addMapping(TileEntityMobSpawner.class, "MobSpawner"); + addMapping(TileEntityNote.class, "Music"); + addMapping(TileEntityPiston.class, "Piston"); + addMapping(TileEntityBrewingStand.class, "Cauldron"); + addMapping(TileEntityEnchantmentTable.class, "EnchantTable"); + addMapping(TileEntityEndPortal.class, "Airportal"); + addMapping(TileEntityCommandBlock.class, "Control"); + addMapping(TileEntityBeacon.class, "Beacon"); + addMapping(TileEntitySkull.class, "Skull"); + addMapping(TileEntityDaylightDetector.class, "DLDetector"); + addMapping(TileEntityHopper.class, "Hopper"); + addMapping(TileEntityComparator.class, "Comparator"); + addMapping(TileEntityFlowerPot.class, "FlowerPot"); + addMapping(TileEntityBanner.class, "Banner"); + } - /**+ - * Adds a new two-way mapping between the class and its string - * name in both hashmaps. + /** + * + Adds a new two-way mapping between the class and its string name in both + * hashmaps. */ private static void addMapping(Class cl, String id) { if (nameToClassMap.containsKey(id)) { @@ -61,47 +82,8 @@ public abstract class TileEntity { } } - /**+ - * Returns the worldObj for this tileEntity. - */ - public World getWorld() { - return this.worldObj; - } - - /**+ - * Sets the worldObj for this tileEntity. - */ - public void setWorldObj(World worldIn) { - this.worldObj = worldIn; - } - - /**+ - * Returns true if the worldObj isn't null. - */ - public boolean hasWorldObj() { - return this.worldObj != null; - } - - public void readFromNBT(NBTTagCompound nbttagcompound) { - this.pos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), - nbttagcompound.getInteger("z")); - } - - public void writeToNBT(NBTTagCompound nbttagcompound) { - String s = (String) classToNameMap.get(this.getClass()); - if (s == null) { - throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!"); - } else { - nbttagcompound.setString("id", s); - nbttagcompound.setInteger("x", this.pos.getX()); - nbttagcompound.setInteger("y", this.pos.getY()); - nbttagcompound.setInteger("z", this.pos.getZ()); - } - } - - /**+ - * Creates a new entity and loads its data from the specified - * NBT. + /** + * + Creates a new entity and loads its data from the specified NBT. */ public static TileEntity createAndLoadEntity(NBTTagCompound nbt) { TileEntity tileentity = null; @@ -124,99 +106,14 @@ public abstract class TileEntity { return tileentity; } - public int getBlockMetadata() { - if (this.blockMetadata == -1) { - IBlockState iblockstate = this.worldObj.getBlockState(this.pos); - this.blockMetadata = iblockstate.getBlock().getMetaFromState(iblockstate); - } + protected World worldObj; + protected BlockPos pos = BlockPos.ORIGIN; - return this.blockMetadata; - } + protected boolean tileEntityInvalid; - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. - */ - public void markDirty() { - if (this.worldObj != null) { - IBlockState iblockstate = this.worldObj.getBlockState(this.pos); - this.blockMetadata = iblockstate.getBlock().getMetaFromState(iblockstate); - this.worldObj.markChunkDirty(this.pos, this); - if (this.getBlockType() != Blocks.air) { - this.worldObj.updateComparatorOutputLevel(this.pos, this.getBlockType()); - } - } + private int blockMetadata = -1; - } - - /**+ - * Returns the square of the distance between this entity and - * the passed in coordinates. - */ - public double getDistanceSq(double x, double y, double z) { - double d0 = (double) this.pos.getX() + 0.5D - x; - double d1 = (double) this.pos.getY() + 0.5D - y; - double d2 = (double) this.pos.getZ() + 0.5D - z; - return d0 * d0 + d1 * d1 + d2 * d2; - } - - public double getMaxRenderDistanceSquared() { - return 4096.0D; - } - - public BlockPos getPos() { - return this.pos; - } - - /**+ - * Gets the block type at the location of this entity - * (client-only). - */ - public Block getBlockType() { - if (this.blockType == null) { - this.blockType = this.worldObj.getBlockState(this.pos).getBlock(); - } - - return this.blockType; - } - - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - return null; - } - - public boolean isInvalid() { - return this.tileEntityInvalid; - } - - /**+ - * invalidates a tile entity - */ - public void invalidate() { - this.tileEntityInvalid = true; - } - - /**+ - * validates a tile entity - */ - public void validate() { - this.tileEntityInvalid = false; - } - - public boolean receiveClientEvent(int var1, int var2) { - return false; - } - - public void updateContainingBlockInfo() { - this.blockType = null; - this.blockMetadata = -1; - } + protected Block blockType; public void addInfoToCrashReport(CrashReportCategory reportCategory) { reportCategory.addCrashSectionCallable("Name", new Callable() { @@ -256,35 +153,140 @@ public abstract class TileEntity { } } - public void setPos(BlockPos posIn) { - this.pos = posIn; - } - public boolean func_183000_F() { return false; } - static { - addMapping(TileEntityFurnace.class, "Furnace"); - addMapping(TileEntityChest.class, "Chest"); - addMapping(TileEntityEnderChest.class, "EnderChest"); - addMapping(BlockJukebox.TileEntityJukebox.class, "RecordPlayer"); - addMapping(TileEntityDispenser.class, "Trap"); - addMapping(TileEntityDropper.class, "Dropper"); - addMapping(TileEntitySign.class, "Sign"); - addMapping(TileEntityMobSpawner.class, "MobSpawner"); - addMapping(TileEntityNote.class, "Music"); - addMapping(TileEntityPiston.class, "Piston"); - addMapping(TileEntityBrewingStand.class, "Cauldron"); - addMapping(TileEntityEnchantmentTable.class, "EnchantTable"); - addMapping(TileEntityEndPortal.class, "Airportal"); - addMapping(TileEntityCommandBlock.class, "Control"); - addMapping(TileEntityBeacon.class, "Beacon"); - addMapping(TileEntitySkull.class, "Skull"); - addMapping(TileEntityDaylightDetector.class, "DLDetector"); - addMapping(TileEntityHopper.class, "Hopper"); - addMapping(TileEntityComparator.class, "Comparator"); - addMapping(TileEntityFlowerPot.class, "FlowerPot"); - addMapping(TileEntityBanner.class, "Banner"); + public int getBlockMetadata() { + if (this.blockMetadata == -1) { + IBlockState iblockstate = this.worldObj.getBlockState(this.pos); + this.blockMetadata = iblockstate.getBlock().getMetaFromState(iblockstate); + } + + return this.blockMetadata; + } + + /** + * + Gets the block type at the location of this entity (client-only). + */ + public Block getBlockType() { + if (this.blockType == null) { + this.blockType = this.worldObj.getBlockState(this.pos).getBlock(); + } + + return this.blockType; + } + + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + return null; + } + + /** + * + Returns the square of the distance between this entity and the passed in + * coordinates. + */ + public double getDistanceSq(double x, double y, double z) { + double d0 = (double) this.pos.getX() + 0.5D - x; + double d1 = (double) this.pos.getY() + 0.5D - y; + double d2 = (double) this.pos.getZ() + 0.5D - z; + return d0 * d0 + d1 * d1 + d2 * d2; + } + + public double getMaxRenderDistanceSquared() { + return 4096.0D; + } + + public BlockPos getPos() { + return this.pos; + } + + /** + * + Returns the worldObj for this tileEntity. + */ + public World getWorld() { + return this.worldObj; + } + + /** + * + Returns true if the worldObj isn't null. + */ + public boolean hasWorldObj() { + return this.worldObj != null; + } + + /** + * + invalidates a tile entity + */ + public void invalidate() { + this.tileEntityInvalid = true; + } + + public boolean isInvalid() { + return this.tileEntityInvalid; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + if (this.worldObj != null) { + IBlockState iblockstate = this.worldObj.getBlockState(this.pos); + this.blockMetadata = iblockstate.getBlock().getMetaFromState(iblockstate); + this.worldObj.markChunkDirty(this.pos, this); + if (this.getBlockType() != Blocks.air) { + this.worldObj.updateComparatorOutputLevel(this.pos, this.getBlockType()); + } + } + + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + this.pos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), + nbttagcompound.getInteger("z")); + } + + public boolean receiveClientEvent(int var1, int var2) { + return false; + } + + public void setPos(BlockPos posIn) { + this.pos = posIn; + } + + /** + * + Sets the worldObj for this tileEntity. + */ + public void setWorldObj(World worldIn) { + this.worldObj = worldIn; + } + + public void updateContainingBlockInfo() { + this.blockType = null; + this.blockMetadata = -1; + } + + /** + * + validates a tile entity + */ + public void validate() { + this.tileEntityInvalid = false; + } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + String s = (String) classToNameMap.get(this.getClass()); + if (s == null) { + throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!"); + } else { + nbttagcompound.setString("id", s); + nbttagcompound.setInteger("x", this.pos.getX()); + nbttagcompound.setInteger("y", this.pos.getY()); + nbttagcompound.setInteger("z", this.pos.getZ()); + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityBanner.java b/src/game/java/net/minecraft/tileentity/TileEntityBanner.java index 944e6381..17f2b4d6 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityBanner.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityBanner.java @@ -15,196 +15,30 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityBanner extends TileEntity { - private int baseColor; - private NBTTagList patterns; - private boolean field_175119_g; - private List patternList; - private List colorList; - private String patternResourceLocation; - - public void setItemValues(ItemStack stack) { - this.patterns = null; - if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag", 10)) { - NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("BlockEntityTag"); - if (nbttagcompound.hasKey("Patterns")) { - this.patterns = (NBTTagList) nbttagcompound.getTagList("Patterns", 10).copy(); - } - - if (nbttagcompound.hasKey("Base", 99)) { - this.baseColor = nbttagcompound.getInteger("Base"); - } else { - this.baseColor = stack.getMetadata() & 15; - } - } else { - this.baseColor = stack.getMetadata() & 15; - } - - this.patternList = null; - this.colorList = null; - this.patternResourceLocation = ""; - this.field_175119_g = true; - } - - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - func_181020_a(nbttagcompound, this.baseColor, this.patterns); - } - - public static void func_181020_a(NBTTagCompound parNBTTagCompound, int parInt1, NBTTagList parNBTTagList) { - parNBTTagCompound.setInteger("Base", parInt1); - if (parNBTTagList != null) { - parNBTTagCompound.setTag("Patterns", parNBTTagList); - } - - } - - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - this.baseColor = nbttagcompound.getInteger("Base"); - this.patterns = nbttagcompound.getTagList("Patterns", 10); - this.patternList = null; - this.colorList = null; - this.patternResourceLocation = null; - this.field_175119_g = true; - } - - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new S35PacketUpdateTileEntity(this.pos, 6, nbttagcompound); - } - - public int getBaseColor() { - return this.baseColor; - } - - public static int getBaseColor(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - return nbttagcompound != null && nbttagcompound.hasKey("Base") ? nbttagcompound.getInteger("Base") - : stack.getMetadata(); - } - - /**+ - * Retrieves the amount of patterns stored on an ItemStack. If - * the tag does not exist this value will be 0. - */ - public static int getPatterns(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - return nbttagcompound != null && nbttagcompound.hasKey("Patterns") - ? nbttagcompound.getTagList("Patterns", 10).tagCount() - : 0; - } - - /**+ - * Retrieves the list of patterns for this tile entity. The - * banner data will be initialized/refreshed before this - * happens. - */ - public List getPatternList() { - this.initializeBannerData(); - return this.patternList; - } - - public NBTTagList func_181021_d() { - return this.patterns; - } - - /**+ - * Retrieves the list of colors for this tile entity. The banner - * data will be initialized/refreshed before this happens. - */ - public List getColorList() { - this.initializeBannerData(); - return this.colorList; - } - - public String func_175116_e() { - this.initializeBannerData(); - return this.patternResourceLocation; - } - - /**+ - * Establishes all of the basic properties for the banner. This - * will also apply the data from the tile entities nbt tag - * compounds. - */ - private void initializeBannerData() { - if (this.patternList == null || this.colorList == null || this.patternResourceLocation == null) { - if (!this.field_175119_g) { - this.patternResourceLocation = ""; - } else { - this.patternList = Lists.newArrayList(); - this.colorList = Lists.newArrayList(); - this.patternList.add(TileEntityBanner.EnumBannerPattern.BASE); - this.colorList.add(EnumDyeColor.byDyeDamage(this.baseColor)); - this.patternResourceLocation = "b" + this.baseColor; - if (this.patterns != null) { - for (int i = 0; i < this.patterns.tagCount(); ++i) { - NBTTagCompound nbttagcompound = this.patterns.getCompoundTagAt(i); - TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = TileEntityBanner.EnumBannerPattern - .getPatternByID(nbttagcompound.getString("Pattern")); - if (tileentitybanner$enumbannerpattern != null) { - this.patternList.add(tileentitybanner$enumbannerpattern); - int j = nbttagcompound.getInteger("Color"); - this.colorList.add(EnumDyeColor.byDyeDamage(j)); - this.patternResourceLocation = this.patternResourceLocation - + tileentitybanner$enumbannerpattern.getPatternID() + j; - } - } - } - - } - } - } - - /**+ - * Removes all the banner related data from a provided instance - * of ItemStack. - */ - public static void removeBannerData(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - if (nbttagcompound != null && nbttagcompound.hasKey("Patterns", 9)) { - NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); - if (nbttaglist.tagCount() > 0) { - nbttaglist.removeTag(nbttaglist.tagCount() - 1); - if (nbttaglist.hasNoTags()) { - stack.getTagCompound().removeTag("BlockEntityTag"); - if (stack.getTagCompound().hasNoTags()) { - stack.setTagCompound((NBTTagCompound) null); - } - } - - } - } - } - public static enum EnumBannerPattern { BASE("base", "b"), SQUARE_BOTTOM_LEFT("square_bottom_left", "bl", " ", " ", "# "), SQUARE_BOTTOM_RIGHT("square_bottom_right", "br", " ", " ", " #"), @@ -243,57 +77,6 @@ public class TileEntityBanner extends TileEntity { public static final EnumBannerPattern[] _VALUES = values(); - private String patternName; - private String patternID; - private String[] craftingLayers; - private Supplier patternCraftingStackSupplier; - private ItemStack patternCraftingStack; - - private EnumBannerPattern(String name, String id) { - this.craftingLayers = new String[3]; - this.patternName = name; - this.patternID = id; - } - - private EnumBannerPattern(String name, String id, Supplier craftingItem) { - this(name, id); - this.patternCraftingStackSupplier = craftingItem; - } - - private EnumBannerPattern(String name, String id, String craftingTop, String craftingMid, String craftingBot) { - this(name, id); - this.craftingLayers[0] = craftingTop; - this.craftingLayers[1] = craftingMid; - this.craftingLayers[2] = craftingBot; - } - - public String getPatternName() { - return this.patternName; - } - - public String getPatternID() { - return this.patternID; - } - - public String[] getCraftingLayers() { - return this.craftingLayers; - } - - public boolean hasValidCrafting() { - return this.patternCraftingStackSupplier != null || this.craftingLayers[0] != null; - } - - public boolean hasCraftingStack() { - return this.patternCraftingStackSupplier != null; - } - - public ItemStack getCraftingStack() { - if (patternCraftingStack == null) { - patternCraftingStack = patternCraftingStackSupplier.get(); - } - return this.patternCraftingStack; - } - public static TileEntityBanner.EnumBannerPattern getPatternByID(String id) { TileEntityBanner.EnumBannerPattern[] arr = _VALUES; for (int i = 0; i < arr.length; ++i) { @@ -305,5 +88,227 @@ public class TileEntityBanner extends TileEntity { return null; } + + private String patternName; + private String patternID; + private String[] craftingLayers; + private Supplier patternCraftingStackSupplier; + + private ItemStack patternCraftingStack; + + private EnumBannerPattern(String name, String id) { + this.craftingLayers = new String[3]; + this.patternName = name; + this.patternID = id; + } + + private EnumBannerPattern(String name, String id, String craftingTop, String craftingMid, String craftingBot) { + this(name, id); + this.craftingLayers[0] = craftingTop; + this.craftingLayers[1] = craftingMid; + this.craftingLayers[2] = craftingBot; + } + + private EnumBannerPattern(String name, String id, Supplier craftingItem) { + this(name, id); + this.patternCraftingStackSupplier = craftingItem; + } + + public String[] getCraftingLayers() { + return this.craftingLayers; + } + + public ItemStack getCraftingStack() { + if (patternCraftingStack == null) { + patternCraftingStack = patternCraftingStackSupplier.get(); + } + return this.patternCraftingStack; + } + + public String getPatternID() { + return this.patternID; + } + + public String getPatternName() { + return this.patternName; + } + + public boolean hasCraftingStack() { + return this.patternCraftingStackSupplier != null; + } + + public boolean hasValidCrafting() { + return this.patternCraftingStackSupplier != null || this.craftingLayers[0] != null; + } + } + + public static void func_181020_a(NBTTagCompound parNBTTagCompound, int parInt1, NBTTagList parNBTTagList) { + parNBTTagCompound.setInteger("Base", parInt1); + if (parNBTTagList != null) { + parNBTTagCompound.setTag("Patterns", parNBTTagList); + } + + } + + public static int getBaseColor(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + return nbttagcompound != null && nbttagcompound.hasKey("Base") ? nbttagcompound.getInteger("Base") + : stack.getMetadata(); + } + + /** + * + Retrieves the amount of patterns stored on an ItemStack. If the tag does + * not exist this value will be 0. + */ + public static int getPatterns(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + return nbttagcompound != null && nbttagcompound.hasKey("Patterns") + ? nbttagcompound.getTagList("Patterns", 10).tagCount() + : 0; + } + + /** + * + Removes all the banner related data from a provided instance of ItemStack. + */ + public static void removeBannerData(ItemStack stack) { + NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + if (nbttagcompound != null && nbttagcompound.hasKey("Patterns", 9)) { + NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); + if (nbttaglist.tagCount() > 0) { + nbttaglist.removeTag(nbttaglist.tagCount() - 1); + if (nbttaglist.hasNoTags()) { + stack.getTagCompound().removeTag("BlockEntityTag"); + if (stack.getTagCompound().hasNoTags()) { + stack.setTagCompound((NBTTagCompound) null); + } + } + + } + } + } + + private int baseColor; + + private NBTTagList patterns; + + private boolean field_175119_g; + + private List patternList; + + private List colorList; + + private String patternResourceLocation; + + public String func_175116_e() { + this.initializeBannerData(); + return this.patternResourceLocation; + } + + public NBTTagList func_181021_d() { + return this.patterns; + } + + public int getBaseColor() { + return this.baseColor; + } + + /** + * + Retrieves the list of colors for this tile entity. The banner data will be + * initialized/refreshed before this happens. + */ + public List getColorList() { + this.initializeBannerData(); + return this.colorList; + } + + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new S35PacketUpdateTileEntity(this.pos, 6, nbttagcompound); + } + + /** + * + Retrieves the list of patterns for this tile entity. The banner data will + * be initialized/refreshed before this happens. + */ + public List getPatternList() { + this.initializeBannerData(); + return this.patternList; + } + + /** + * + Establishes all of the basic properties for the banner. This will also + * apply the data from the tile entities nbt tag compounds. + */ + private void initializeBannerData() { + if (this.patternList == null || this.colorList == null || this.patternResourceLocation == null) { + if (!this.field_175119_g) { + this.patternResourceLocation = ""; + } else { + this.patternList = Lists.newArrayList(); + this.colorList = Lists.newArrayList(); + this.patternList.add(TileEntityBanner.EnumBannerPattern.BASE); + this.colorList.add(EnumDyeColor.byDyeDamage(this.baseColor)); + this.patternResourceLocation = "b" + this.baseColor; + if (this.patterns != null) { + for (int i = 0; i < this.patterns.tagCount(); ++i) { + NBTTagCompound nbttagcompound = this.patterns.getCompoundTagAt(i); + TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = TileEntityBanner.EnumBannerPattern + .getPatternByID(nbttagcompound.getString("Pattern")); + if (tileentitybanner$enumbannerpattern != null) { + this.patternList.add(tileentitybanner$enumbannerpattern); + int j = nbttagcompound.getInteger("Color"); + this.colorList.add(EnumDyeColor.byDyeDamage(j)); + this.patternResourceLocation = this.patternResourceLocation + + tileentitybanner$enumbannerpattern.getPatternID() + j; + } + } + } + + } + } + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + this.baseColor = nbttagcompound.getInteger("Base"); + this.patterns = nbttagcompound.getTagList("Patterns", 10); + this.patternList = null; + this.colorList = null; + this.patternResourceLocation = null; + this.field_175119_g = true; + } + + public void setItemValues(ItemStack stack) { + this.patterns = null; + if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag", 10)) { + NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("BlockEntityTag"); + if (nbttagcompound.hasKey("Patterns")) { + this.patterns = (NBTTagList) nbttagcompound.getTagList("Patterns", 10).copy(); + } + + if (nbttagcompound.hasKey("Base", 99)) { + this.baseColor = nbttagcompound.getInteger("Base"); + } else { + this.baseColor = stack.getMetadata() & 15; + } + } else { + this.baseColor = stack.getMetadata() & 15; + } + + this.patternList = null; + this.colorList = null; + this.patternResourceLocation = ""; + this.field_175119_g = true; + } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + func_181020_a(nbttagcompound, this.baseColor, this.patterns); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityBeacon.java b/src/game/java/net/minecraft/tileentity/TileEntityBeacon.java index deaad042..f2f7bd2b 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityBeacon.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityBeacon.java @@ -1,8 +1,10 @@ package net.minecraft.tileentity; -import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.BlockStainedGlass; import net.minecraft.block.BlockStainedGlassPane; @@ -27,63 +29,74 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityBeacon extends TileEntityLockable implements ITickable, IInventory { - /**+ - * List of effects that Beacon can apply + public static class BeamSegment { + private final float[] colors; + private int height; + + public BeamSegment(float[] parArrayOfFloat) { + this.colors = parArrayOfFloat; + this.height = 1; + } + + public float[] getColors() { + return this.colors; + } + + public int getHeight() { + return this.height; + } + + protected void incrementHeight() { + ++this.height; + } + } + + /** + * + List of effects that Beacon can apply */ public static final Potion[][] effectsList = new Potion[][] { { Potion.moveSpeed, Potion.digSpeed }, { Potion.resistance, Potion.jump }, { Potion.damageBoost }, { Potion.regeneration } }; - /**+ - * A list of beam segments for this beacon + /** + * + A list of beam segments for this beacon */ private final List beamSegments = Lists.newArrayList(); private long beamRenderCounter; private float field_146014_j; private boolean isComplete; - /**+ - * Level of this beacon's pyramid. + /** + * + Level of this beacon's pyramid. */ private int levels = -1; private int primaryEffect; private int secondaryEffect; private ItemStack payment; + private String customName; - /**+ - * Like the old updateEntity(), except more generic. - */ - public void update() { - if (this.worldObj.getTotalWorldTime() % 80L == 0L) { - this.updateBeacon(); - } - - } - - public void updateBeacon() { - this.updateSegmentColors(); - this.addEffectsToPlayers(); - } - private void addEffectsToPlayers() { if (this.isComplete && this.levels > 0 && !this.worldObj.isRemote && this.primaryEffect > 0) { double d0 = (double) (this.levels * 10 + 10); @@ -96,8 +109,8 @@ public class TileEntityBeacon extends TileEntityLockable implements ITickable, I int j = this.pos.getY(); int k = this.pos.getZ(); AxisAlignedBB axisalignedbb = (new AxisAlignedBB((double) i, (double) j, (double) k, (double) (i + 1), - (double) (j + 1), (double) (k + 1))).expand(d0, d0, d0).addCoord(0.0D, - (double) this.worldObj.getHeight(), 0.0D); + (double) (j + 1), (double) (k + 1))).expand(d0, d0, d0) + .addCoord(0.0D, (double) this.worldObj.getHeight(), 0.0D); List list = this.worldObj.getEntitiesWithinAABB(EntityPlayer.class, axisalignedbb); for (int m = 0, l = list.size(); m < l; ++m) { @@ -113,6 +126,241 @@ public class TileEntityBeacon extends TileEntityLockable implements ITickable, I } + public void clear() { + this.payment = null; + } + + public void closeInventory(EntityPlayer player) { + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerBeacon(inventoryplayer, this); + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. + */ + public ItemStack decrStackSize(int index, int count) { + if (index == 0 && this.payment != null) { + if (count >= this.payment.stackSize) { + ItemStack itemstack = this.payment; + this.payment = null; + return itemstack; + } else { + this.payment.stackSize -= count; + return new ItemStack(this.payment.getItem(), count, this.payment.getMetadata()); + } + } else { + return null; + } + } + + private int func_183001_h(int parInt1) { + if (parInt1 >= 0 && parInt1 < Potion.potionTypes.length && Potion.potionTypes[parInt1] != null) { + Potion potion = Potion.potionTypes[parInt1]; + return potion != Potion.moveSpeed && potion != Potion.digSpeed && potion != Potion.resistance + && potion != Potion.jump && potion != Potion.damageBoost && potion != Potion.regeneration ? 0 + : parInt1; + } else { + return 0; + } + } + + public List getBeamSegments() { + return this.beamSegments; + } + + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new S35PacketUpdateTileEntity(this.pos, 3, nbttagcompound); + } + + public int getField(int parInt1) { + switch (parInt1) { + case 0: + return this.levels; + case 1: + return this.primaryEffect; + case 2: + return this.secondaryEffect; + default: + return 0; + } + } + + public int getFieldCount() { + return 3; + } + + public String getGuiID() { + return "minecraft:beacon"; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 1; + } + + public double getMaxRenderDistanceSquared() { + return 65536.0D; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.hasCustomName() ? this.customName : "container.beacon"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return 1; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int index) { + return index == 0 ? this.payment : null; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.customName != null && this.customName.length() > 0; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int index, ItemStack stack) { + return stack.getItem() == Items.emerald || stack.getItem() == Items.diamond + || stack.getItem() == Items.gold_ingot || stack.getItem() == Items.iron_ingot; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer player) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : player.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + public void openInventory(EntityPlayer player) { + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + this.primaryEffect = this.func_183001_h(nbttagcompound.getInteger("Primary")); + this.secondaryEffect = this.func_183001_h(nbttagcompound.getInteger("Secondary")); + this.levels = nbttagcompound.getInteger("Levels"); + } + + public boolean receiveClientEvent(int id, int type) { + if (id == 1) { + this.updateBeacon(); + return true; + } else { + return super.receiveClientEvent(id, type); + } + } + + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int index) { + if (index == 0 && this.payment != null) { + ItemStack itemstack = this.payment; + this.payment = null; + return itemstack; + } else { + return null; + } + } + + public void setField(int id, int value) { + switch (id) { + case 0: + this.levels = value; + break; + case 1: + this.primaryEffect = this.func_183001_h(value); + break; + case 2: + this.secondaryEffect = this.func_183001_h(value); + } + + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int index, ItemStack stack) { + if (index == 0) { + this.payment = stack; + } + + } + + public void setName(String name) { + this.customName = name; + } + + public float shouldBeamRender() { + if (!this.isComplete) { + return 0.0F; + } else { + int i = (int) (this.worldObj.getTotalWorldTime() - this.beamRenderCounter); + this.beamRenderCounter = this.worldObj.getTotalWorldTime(); + if (i > 1) { + this.field_146014_j -= (float) i / 40.0F; + if (this.field_146014_j < 0.0F) { + this.field_146014_j = 0.0F; + } + } + + this.field_146014_j += 0.025F; + if (this.field_146014_j > 1.0F) { + this.field_146014_j = 1.0F; + } + + return this.field_146014_j; + } + } + + /** + * + Like the old updateEntity(), except more generic. + */ + public void update() { + if (this.worldObj.getTotalWorldTime() % 80L == 0L) { + this.updateBeacon(); + } + + } + + public void updateBeacon() { + this.updateSegmentColors(); + this.addEffectsToPlayers(); + } + private void updateSegmentColors() { int i = this.levels; int j = this.pos.getX(); @@ -204,253 +452,10 @@ public class TileEntityBeacon extends TileEntityLockable implements ITickable, I } - public List getBeamSegments() { - return this.beamSegments; - } - - public float shouldBeamRender() { - if (!this.isComplete) { - return 0.0F; - } else { - int i = (int) (this.worldObj.getTotalWorldTime() - this.beamRenderCounter); - this.beamRenderCounter = this.worldObj.getTotalWorldTime(); - if (i > 1) { - this.field_146014_j -= (float) i / 40.0F; - if (this.field_146014_j < 0.0F) { - this.field_146014_j = 0.0F; - } - } - - this.field_146014_j += 0.025F; - if (this.field_146014_j > 1.0F) { - this.field_146014_j = 1.0F; - } - - return this.field_146014_j; - } - } - - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new S35PacketUpdateTileEntity(this.pos, 3, nbttagcompound); - } - - public double getMaxRenderDistanceSquared() { - return 65536.0D; - } - - private int func_183001_h(int parInt1) { - if (parInt1 >= 0 && parInt1 < Potion.potionTypes.length && Potion.potionTypes[parInt1] != null) { - Potion potion = Potion.potionTypes[parInt1]; - return potion != Potion.moveSpeed && potion != Potion.digSpeed && potion != Potion.resistance - && potion != Potion.jump && potion != Potion.damageBoost && potion != Potion.regeneration ? 0 - : parInt1; - } else { - return 0; - } - } - - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - this.primaryEffect = this.func_183001_h(nbttagcompound.getInteger("Primary")); - this.secondaryEffect = this.func_183001_h(nbttagcompound.getInteger("Secondary")); - this.levels = nbttagcompound.getInteger("Levels"); - } - public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); nbttagcompound.setInteger("Primary", this.primaryEffect); nbttagcompound.setInteger("Secondary", this.secondaryEffect); nbttagcompound.setInteger("Levels", this.levels); } - - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return 1; - } - - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int index) { - return index == 0 ? this.payment : null; - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. - */ - public ItemStack decrStackSize(int index, int count) { - if (index == 0 && this.payment != null) { - if (count >= this.payment.stackSize) { - ItemStack itemstack = this.payment; - this.payment = null; - return itemstack; - } else { - this.payment.stackSize -= count; - return new ItemStack(this.payment.getItem(), count, this.payment.getMetadata()); - } - } else { - return null; - } - } - - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int index) { - if (index == 0 && this.payment != null) { - ItemStack itemstack = this.payment; - this.payment = null; - return itemstack; - } else { - return null; - } - } - - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int index, ItemStack stack) { - if (index == 0) { - this.payment = stack; - } - - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.hasCustomName() ? this.customName : "container.beacon"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.customName != null && this.customName.length() > 0; - } - - public void setName(String name) { - this.customName = name; - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 1; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer player) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : player.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } - - public void openInventory(EntityPlayer player) { - } - - public void closeInventory(EntityPlayer player) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int index, ItemStack stack) { - return stack.getItem() == Items.emerald || stack.getItem() == Items.diamond - || stack.getItem() == Items.gold_ingot || stack.getItem() == Items.iron_ingot; - } - - public String getGuiID() { - return "minecraft:beacon"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { - return new ContainerBeacon(inventoryplayer, this); - } - - public int getField(int parInt1) { - switch (parInt1) { - case 0: - return this.levels; - case 1: - return this.primaryEffect; - case 2: - return this.secondaryEffect; - default: - return 0; - } - } - - public void setField(int id, int value) { - switch (id) { - case 0: - this.levels = value; - break; - case 1: - this.primaryEffect = this.func_183001_h(value); - break; - case 2: - this.secondaryEffect = this.func_183001_h(value); - } - - } - - public int getFieldCount() { - return 3; - } - - public void clear() { - this.payment = null; - } - - public boolean receiveClientEvent(int id, int type) { - if (id == 1) { - this.updateBeacon(); - return true; - } else { - return super.receiveClientEvent(id, type); - } - } - - public static class BeamSegment { - private final float[] colors; - private int height; - - public BeamSegment(float[] parArrayOfFloat) { - this.colors = parArrayOfFloat; - this.height = 1; - } - - protected void incrementHeight() { - ++this.height; - } - - public float[] getColors() { - return this.colors; - } - - public int getHeight() { - return this.height; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityBrewingStand.java b/src/game/java/net/minecraft/tileentity/TileEntityBrewingStand.java index 9e020d04..7d5cdc45 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityBrewingStand.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityBrewingStand.java @@ -2,6 +2,7 @@ package net.minecraft.tileentity; import java.util.Arrays; import java.util.List; + import net.minecraft.block.BlockBrewingStand; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; @@ -19,38 +20,40 @@ import net.minecraft.potion.PotionHelper; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityBrewingStand extends TileEntityLockable implements ITickable, ISidedInventory { - /**+ - * an array of the input slot indices + /** + * + an array of the input slot indices */ private static final int[] inputSlots = new int[] { 3 }; - /**+ - * an array of the output slot indices + /** + * + an array of the output slot indices */ private static final int[] outputSlots = new int[] { 0, 1, 2 }; - /**+ - * The ItemStacks currently placed in the slots of the brewing - * stand + /** + * + The ItemStacks currently placed in the slots of the brewing stand */ private ItemStack[] brewingItemStacks = new ItemStack[4]; private int brewTime; @@ -58,34 +61,277 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka private Item ingredientID; private String customName; - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + private void brewPotions() { + if (this.canBrew()) { + ItemStack itemstack = this.brewingItemStacks[3]; + + for (int i = 0; i < 3; ++i) { + if (this.brewingItemStacks[i] != null && this.brewingItemStacks[i].getItem() == Items.potionitem) { + int j = this.brewingItemStacks[i].getMetadata(); + int k = this.getPotionResult(j, itemstack); + List list = Items.potionitem.getEffects(j); + List list1 = Items.potionitem.getEffects(k); + if (j > 0 && list == list1 || list != null && (list.equals(list1) || list1 == null)) { + if (!ItemPotion.isSplash(j) && ItemPotion.isSplash(k)) { + this.brewingItemStacks[i].setItemDamage(k); + } + } else if (j != k) { + this.brewingItemStacks[i].setItemDamage(k); + } + } + } + + if (itemstack.getItem().hasContainerItem()) { + this.brewingItemStacks[3] = new ItemStack(itemstack.getItem().getContainerItem()); + } else { + --this.brewingItemStacks[3].stackSize; + if (this.brewingItemStacks[3].stackSize <= 0) { + this.brewingItemStacks[3] = null; + } + } + + } + } + + private boolean canBrew() { + if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].stackSize > 0) { + ItemStack itemstack = this.brewingItemStacks[3]; + if (!itemstack.getItem().isPotionIngredient(itemstack)) { + return false; + } else { + boolean flag = false; + + for (int i = 0; i < 3; ++i) { + if (this.brewingItemStacks[i] != null && this.brewingItemStacks[i].getItem() == Items.potionitem) { + int j = this.brewingItemStacks[i].getMetadata(); + int k = this.getPotionResult(j, itemstack); + if (!ItemPotion.isSplash(j) && ItemPotion.isSplash(k)) { + flag = true; + break; + } + + List list = Items.potionitem.getEffects(j); + List list1 = Items.potionitem.getEffects(k); + if ((j <= 0 || list != list1) && (list == null || !list.equals(list1) && list1 != null) + && j != k) { + flag = true; + break; + } + } + } + + return flag; + } + } else { + return false; + } + } + + /** + * + Returns true if automation can extract the given item in the given slot + * from the given side. Args: slot, item, side + */ + public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) { + return true; + } + + /** + * + Returns true if automation can insert the given item in the given slot from + * the given side. Args: slot, item, side + */ + public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { + return this.isItemValidForSlot(index, itemStackIn); + } + + public void clear() { + for (int i = 0; i < this.brewingItemStacks.length; ++i) { + this.brewingItemStacks[i] = null; + } + + } + + public void closeInventory(EntityPlayer var1) { + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerBrewingStand(inventoryplayer, this); + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. + */ + public ItemStack decrStackSize(int i, int var2) { + if (i >= 0 && i < this.brewingItemStacks.length) { + ItemStack itemstack = this.brewingItemStacks[i]; + this.brewingItemStacks[i] = null; + return itemstack; + } else { + return null; + } + } + + public boolean[] func_174902_m() { + boolean[] aboolean = new boolean[3]; + + for (int i = 0; i < 3; ++i) { + if (this.brewingItemStacks[i] != null) { + aboolean[i] = true; + } + } + + return aboolean; + } + + public int getField(int i) { + switch (i) { + case 0: + return this.brewTime; + default: + return 0; + } + } + + public int getFieldCount() { + return 1; + } + + public String getGuiID() { + return "minecraft:brewing_stand"; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ public String getName() { return this.hasCustomName() ? this.customName : "container.brewing"; } - /**+ - * Returns true if this thing is named + /** + * + The result of brewing a potion of the specified damage value with an + * ingredient itemstack. + */ + private int getPotionResult(int meta, ItemStack stack) { + return stack == null ? meta + : (stack.getItem().isPotionIngredient(stack) + ? PotionHelper.applyIngredient(meta, stack.getItem().getPotionEffect(stack)) + : meta); + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.brewingItemStacks.length; + } + + public int[] getSlotsForFace(EnumFacing side) { + return side == EnumFacing.UP ? inputSlots : outputSlots; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return i >= 0 && i < this.brewingItemStacks.length ? this.brewingItemStacks[i] : null; + } + + /** + * + Returns true if this thing is named */ public boolean hasCustomName() { return this.customName != null && this.customName.length() > 0; } + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return i == 3 ? itemstack.getItem().isPotionIngredient(itemstack) + : itemstack.getItem() == Items.potionitem || itemstack.getItem() == Items.glass_bottle; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + public void openInventory(EntityPlayer var1) { + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); + this.brewingItemStacks = new ItemStack[this.getSizeInventory()]; + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + byte b0 = nbttagcompound1.getByte("Slot"); + if (b0 >= 0 && b0 < this.brewingItemStacks.length) { + this.brewingItemStacks[b0] = ItemStack.loadItemStackFromNBT(nbttagcompound1); + } + } + + this.brewTime = nbttagcompound.getShort("BrewTime"); + if (nbttagcompound.hasKey("CustomName", 8)) { + this.customName = nbttagcompound.getString("CustomName"); + } + + } + + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + if (i >= 0 && i < this.brewingItemStacks.length) { + ItemStack itemstack = this.brewingItemStacks[i]; + this.brewingItemStacks[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setField(int i, int j) { + switch (i) { + case 0: + this.brewTime = j; + default: + } + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + if (i >= 0 && i < this.brewingItemStacks.length) { + this.brewingItemStacks[i] = itemstack; + } + + } + public void setName(String name) { this.customName = name; } - /**+ - * Returns the number of slots in the inventory. - */ - public int getSizeInventory() { - return this.brewingItemStacks.length; - } - - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ public void update() { if (this.brewTime > 0) { @@ -125,103 +371,6 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka } - private boolean canBrew() { - if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].stackSize > 0) { - ItemStack itemstack = this.brewingItemStacks[3]; - if (!itemstack.getItem().isPotionIngredient(itemstack)) { - return false; - } else { - boolean flag = false; - - for (int i = 0; i < 3; ++i) { - if (this.brewingItemStacks[i] != null && this.brewingItemStacks[i].getItem() == Items.potionitem) { - int j = this.brewingItemStacks[i].getMetadata(); - int k = this.getPotionResult(j, itemstack); - if (!ItemPotion.isSplash(j) && ItemPotion.isSplash(k)) { - flag = true; - break; - } - - List list = Items.potionitem.getEffects(j); - List list1 = Items.potionitem.getEffects(k); - if ((j <= 0 || list != list1) && (list == null || !list.equals(list1) && list1 != null) - && j != k) { - flag = true; - break; - } - } - } - - return flag; - } - } else { - return false; - } - } - - private void brewPotions() { - if (this.canBrew()) { - ItemStack itemstack = this.brewingItemStacks[3]; - - for (int i = 0; i < 3; ++i) { - if (this.brewingItemStacks[i] != null && this.brewingItemStacks[i].getItem() == Items.potionitem) { - int j = this.brewingItemStacks[i].getMetadata(); - int k = this.getPotionResult(j, itemstack); - List list = Items.potionitem.getEffects(j); - List list1 = Items.potionitem.getEffects(k); - if (j > 0 && list == list1 || list != null && (list.equals(list1) || list1 == null)) { - if (!ItemPotion.isSplash(j) && ItemPotion.isSplash(k)) { - this.brewingItemStacks[i].setItemDamage(k); - } - } else if (j != k) { - this.brewingItemStacks[i].setItemDamage(k); - } - } - } - - if (itemstack.getItem().hasContainerItem()) { - this.brewingItemStacks[3] = new ItemStack(itemstack.getItem().getContainerItem()); - } else { - --this.brewingItemStacks[3].stackSize; - if (this.brewingItemStacks[3].stackSize <= 0) { - this.brewingItemStacks[3] = null; - } - } - - } - } - - /**+ - * The result of brewing a potion of the specified damage value - * with an ingredient itemstack. - */ - private int getPotionResult(int meta, ItemStack stack) { - return stack == null ? meta - : (stack.getItem().isPotionIngredient(stack) - ? PotionHelper.applyIngredient(meta, stack.getItem().getPotionEffect(stack)) - : meta); - } - - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); - this.brewingItemStacks = new ItemStack[this.getSizeInventory()]; - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - byte b0 = nbttagcompound1.getByte("Slot"); - if (b0 >= 0 && b0 < this.brewingItemStacks.length) { - this.brewingItemStacks[b0] = ItemStack.loadItemStackFromNBT(nbttagcompound1); - } - } - - this.brewTime = nbttagcompound.getShort("BrewTime"); - if (nbttagcompound.hasKey("CustomName", 8)) { - this.customName = nbttagcompound.getString("CustomName"); - } - - } - public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); nbttagcompound.setShort("BrewTime", (short) this.brewTime); @@ -242,150 +391,4 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka } } - - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return i >= 0 && i < this.brewingItemStacks.length ? this.brewingItemStacks[i] : null; - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. - */ - public ItemStack decrStackSize(int i, int var2) { - if (i >= 0 && i < this.brewingItemStacks.length) { - ItemStack itemstack = this.brewingItemStacks[i]; - this.brewingItemStacks[i] = null; - return itemstack; - } else { - return null; - } - } - - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (i >= 0 && i < this.brewingItemStacks.length) { - ItemStack itemstack = this.brewingItemStacks[i]; - this.brewingItemStacks[i] = null; - return itemstack; - } else { - return null; - } - } - - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - if (i >= 0 && i < this.brewingItemStacks.length) { - this.brewingItemStacks[i] = itemstack; - } - - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return i == 3 ? itemstack.getItem().isPotionIngredient(itemstack) - : itemstack.getItem() == Items.potionitem || itemstack.getItem() == Items.glass_bottle; - } - - public boolean[] func_174902_m() { - boolean[] aboolean = new boolean[3]; - - for (int i = 0; i < 3; ++i) { - if (this.brewingItemStacks[i] != null) { - aboolean[i] = true; - } - } - - return aboolean; - } - - public int[] getSlotsForFace(EnumFacing side) { - return side == EnumFacing.UP ? inputSlots : outputSlots; - } - - /**+ - * Returns true if automation can insert the given item in the - * given slot from the given side. Args: slot, item, side - */ - public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { - return this.isItemValidForSlot(index, itemStackIn); - } - - /**+ - * Returns true if automation can extract the given item in the - * given slot from the given side. Args: slot, item, side - */ - public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) { - return true; - } - - public String getGuiID() { - return "minecraft:brewing_stand"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { - return new ContainerBrewingStand(inventoryplayer, this); - } - - public int getField(int i) { - switch (i) { - case 0: - return this.brewTime; - default: - return 0; - } - } - - public void setField(int i, int j) { - switch (i) { - case 0: - this.brewTime = j; - default: - } - } - - public int getFieldCount() { - return 1; - } - - public void clear() { - for (int i = 0; i < this.brewingItemStacks.length; ++i) { - this.brewingItemStacks[i] = null; - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityChest.java b/src/game/java/net/minecraft/tileentity/TileEntityChest.java index c4d513bb..5dbf29f1 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityChest.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityChest.java @@ -18,22 +18,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,23 +63,44 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II this.cachedChestType = chestType; } - /**+ - * Returns the number of slots in the inventory. + /** + * + Performs the check for adjacent chests to determine if this chest is double + * or not. */ - public int getSizeInventory() { - return 27; + public void checkForAdjacentChests() { + if (!this.adjacentChestChecked) { + this.adjacentChestChecked = true; + this.adjacentChestXNeg = this.getAdjacentChest(EnumFacing.WEST); + this.adjacentChestXPos = this.getAdjacentChest(EnumFacing.EAST); + this.adjacentChestZNeg = this.getAdjacentChest(EnumFacing.NORTH); + this.adjacentChestZPos = this.getAdjacentChest(EnumFacing.SOUTH); + } } - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return this.chestContents[i]; + public void clear() { + for (int i = 0; i < this.chestContents.length; ++i) { + this.chestContents[i] = null; + } + } - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + public void closeInventory(EntityPlayer entityplayer) { + if (!entityplayer.isSpectator() && this.getBlockType() instanceof BlockChest) { + --this.numPlayersUsing; + this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayersUsing); + this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType()); + this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType()); + } + + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { + return new ContainerChest(inventoryplayer, this, entityplayer); + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.chestContents[i] != null) { @@ -99,112 +123,6 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II } } - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (this.chestContents[i] != null) { - ItemStack itemstack = this.chestContents[i]; - this.chestContents[i] = null; - return itemstack; - } else { - return null; - } - } - - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - this.chestContents[i] = itemstack; - if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { - itemstack.stackSize = this.getInventoryStackLimit(); - } - - this.markDirty(); - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.hasCustomName() ? this.customName : "container.chest"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.customName != null && this.customName.length() > 0; - } - - public void setCustomName(String name) { - this.customName = name; - } - - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); - this.chestContents = new ItemStack[this.getSizeInventory()]; - if (nbttagcompound.hasKey("CustomName", 8)) { - this.customName = nbttagcompound.getString("CustomName"); - } - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - int j = nbttagcompound1.getByte("Slot") & 255; - if (j >= 0 && j < this.chestContents.length) { - this.chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); - } - } - - } - - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.chestContents.length; ++i) { - if (this.chestContents[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - this.chestContents[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - - nbttagcompound.setTag("Items", nbttaglist); - if (this.hasCustomName()) { - nbttagcompound.setString("CustomName", this.customName); - } - - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } - - public void updateContainingBlockInfo() { - super.updateContainingBlockInfo(); - this.adjacentChestChecked = false; - } - private void func_174910_a(TileEntityChest chestTe, EnumFacing side) { if (chestTe.isInvalid()) { this.adjacentChestChecked = false; @@ -234,20 +152,6 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II } - /**+ - * Performs the check for adjacent chests to determine if this - * chest is double or not. - */ - public void checkForAdjacentChests() { - if (!this.adjacentChestChecked) { - this.adjacentChestChecked = true; - this.adjacentChestXNeg = this.getAdjacentChest(EnumFacing.WEST); - this.adjacentChestXPos = this.getAdjacentChest(EnumFacing.EAST); - this.adjacentChestZNeg = this.getAdjacentChest(EnumFacing.NORTH); - this.adjacentChestZPos = this.getAdjacentChest(EnumFacing.SOUTH); - } - } - protected TileEntityChest getAdjacentChest(EnumFacing side) { BlockPos blockpos = this.pos.offset(side); if (this.isChestAt(blockpos)) { @@ -262,6 +166,76 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II return null; } + public int getChestType() { + if (this.cachedChestType == -1) { + if (this.worldObj == null || !(this.getBlockType() instanceof BlockChest)) { + return 0; + } + + this.cachedChestType = ((BlockChest) this.getBlockType()).chestType; + } + + return this.cachedChestType; + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + public String getGuiID() { + return "minecraft:chest"; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.hasCustomName() ? this.customName : "container.chest"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return 27; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return this.chestContents[i]; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.customName != null && this.customName.length() > 0; + } + + /** + * + invalidates a tile entity + */ + public void invalidate() { + super.invalidate(); + this.updateContainingBlockInfo(); + this.checkForAdjacentChests(); + } + private boolean isChestAt(BlockPos posIn) { if (this.worldObj == null) { return false; @@ -271,8 +245,100 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II } } - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + public void openInventory(EntityPlayer entityplayer) { + if (!entityplayer.isSpectator()) { + if (this.numPlayersUsing < 0) { + this.numPlayersUsing = 0; + } + + ++this.numPlayersUsing; + this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayersUsing); + this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType()); + this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType()); + } + + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); + this.chestContents = new ItemStack[this.getSizeInventory()]; + if (nbttagcompound.hasKey("CustomName", 8)) { + this.customName = nbttagcompound.getString("CustomName"); + } + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + int j = nbttagcompound1.getByte("Slot") & 255; + if (j >= 0 && j < this.chestContents.length) { + this.chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound1); + } + } + + } + + public boolean receiveClientEvent(int i, int j) { + if (i == 1) { + this.numPlayersUsing = j; + return true; + } else { + return super.receiveClientEvent(i, j); + } + } + + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + if (this.chestContents[i] != null) { + ItemStack itemstack = this.chestContents[i]; + this.chestContents[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setCustomName(String name) { + this.customName = name; + } + + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + this.chestContents[i] = itemstack; + if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { + itemstack.stackSize = this.getInventoryStackLimit(); + } + + this.markDirty(); + } + + /** + * + Like the old updateEntity(), except more generic. */ public void update() { this.checkForAdjacentChests(); @@ -353,90 +419,27 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II } - public boolean receiveClientEvent(int i, int j) { - if (i == 1) { - this.numPlayersUsing = j; - return true; - } else { - return super.receiveClientEvent(i, j); - } + public void updateContainingBlockInfo() { + super.updateContainingBlockInfo(); + this.adjacentChestChecked = false; } - public void openInventory(EntityPlayer entityplayer) { - if (!entityplayer.isSpectator()) { - if (this.numPlayersUsing < 0) { - this.numPlayersUsing = 0; - } + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); - ++this.numPlayersUsing; - this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayersUsing); - this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType()); - this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType()); - } - - } - - public void closeInventory(EntityPlayer entityplayer) { - if (!entityplayer.isSpectator() && this.getBlockType() instanceof BlockChest) { - --this.numPlayersUsing; - this.worldObj.addBlockEvent(this.pos, this.getBlockType(), 1, this.numPlayersUsing); - this.worldObj.notifyNeighborsOfStateChange(this.pos, this.getBlockType()); - this.worldObj.notifyNeighborsOfStateChange(this.pos.down(), this.getBlockType()); - } - - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - /**+ - * invalidates a tile entity - */ - public void invalidate() { - super.invalidate(); - this.updateContainingBlockInfo(); - this.checkForAdjacentChests(); - } - - public int getChestType() { - if (this.cachedChestType == -1) { - if (this.worldObj == null || !(this.getBlockType() instanceof BlockChest)) { - return 0; - } - - this.cachedChestType = ((BlockChest) this.getBlockType()).chestType; - } - - return this.cachedChestType; - } - - public String getGuiID() { - return "minecraft:chest"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { - return new ContainerChest(inventoryplayer, this, entityplayer); - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } - - public void clear() { for (int i = 0; i < this.chestContents.length; ++i) { - this.chestContents[i] = null; + if (this.chestContents[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + this.chestContents[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + + nbttagcompound.setTag("Items", nbttaglist); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.customName); } } diff --git a/src/game/java/net/minecraft/tileentity/TileEntityCommandBlock.java b/src/game/java/net/minecraft/tileentity/TileEntityCommandBlock.java index 2c175f37..9b76848a 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityCommandBlock.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityCommandBlock.java @@ -11,51 +11,31 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityCommandBlock extends TileEntity { private final CommandBlockLogic commandBlockLogic = new CommandBlockLogic() { - public BlockPos getPosition() { - return TileEntityCommandBlock.this.pos; - } - - public Vec3 getPositionVector() { - return new Vec3((double) TileEntityCommandBlock.this.pos.getX() + 0.5D, - (double) TileEntityCommandBlock.this.pos.getY() + 0.5D, - (double) TileEntityCommandBlock.this.pos.getZ() + 0.5D); - } - - public World getEntityWorld() { - return TileEntityCommandBlock.this.getWorld(); - } - - public void setCommand(String s) { - super.setCommand(s); - TileEntityCommandBlock.this.markDirty(); - } - - public void updateCommand() { - TileEntityCommandBlock.this.getWorld().markBlockForUpdate(TileEntityCommandBlock.this.pos); - } - public int func_145751_f() { return 0; } @@ -69,30 +49,31 @@ public class TileEntityCommandBlock extends TileEntity { public Entity getCommandSenderEntity() { return null; } + + public World getEntityWorld() { + return TileEntityCommandBlock.this.getWorld(); + } + + public BlockPos getPosition() { + return TileEntityCommandBlock.this.pos; + } + + public Vec3 getPositionVector() { + return new Vec3((double) TileEntityCommandBlock.this.pos.getX() + 0.5D, + (double) TileEntityCommandBlock.this.pos.getY() + 0.5D, + (double) TileEntityCommandBlock.this.pos.getZ() + 0.5D); + } + + public void setCommand(String s) { + super.setCommand(s); + TileEntityCommandBlock.this.markDirty(); + } + + public void updateCommand() { + TileEntityCommandBlock.this.getWorld().markBlockForUpdate(TileEntityCommandBlock.this.pos); + } }; - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - this.commandBlockLogic.writeDataToNBT(nbttagcompound); - } - - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - this.commandBlockLogic.readDataFromNBT(nbttagcompound); - } - - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new S35PacketUpdateTileEntity(this.pos, 2, nbttagcompound); - } - public boolean func_183000_F() { return true; } @@ -104,4 +85,25 @@ public class TileEntityCommandBlock extends TileEntity { public CommandResultStats getCommandResultStats() { return this.commandBlockLogic.getCommandResultStats(); } + + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new S35PacketUpdateTileEntity(this.pos, 2, nbttagcompound); + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + this.commandBlockLogic.readDataFromNBT(nbttagcompound); + } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + this.commandBlockLogic.writeDataToNBT(nbttagcompound); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityComparator.java b/src/game/java/net/minecraft/tileentity/TileEntityComparator.java index bf1abe84..c1c814b9 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityComparator.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityComparator.java @@ -2,22 +2,25 @@ package net.minecraft.tileentity; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,9 +28,8 @@ import net.minecraft.nbt.NBTTagCompound; public class TileEntityComparator extends TileEntity { private int outputSignal; - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setInteger("OutputSignal", this.outputSignal); + public int getOutputSignal() { + return this.outputSignal; } public void readFromNBT(NBTTagCompound nbttagcompound) { @@ -35,11 +37,12 @@ public class TileEntityComparator extends TileEntity { this.outputSignal = nbttagcompound.getInteger("OutputSignal"); } - public int getOutputSignal() { - return this.outputSignal; - } - public void setOutputSignal(int parInt1) { this.outputSignal = parInt1; } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setInteger("OutputSignal", this.outputSignal); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityDaylightDetector.java b/src/game/java/net/minecraft/tileentity/TileEntityDaylightDetector.java index 059a93fe..9cd8bfc2 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityDaylightDetector.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityDaylightDetector.java @@ -3,29 +3,32 @@ package net.minecraft.tileentity; import net.minecraft.block.BlockDaylightDetector; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityDaylightDetector extends TileEntity implements ITickable { - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ public void update() { if (this.worldObj != null && !this.worldObj.isRemote && this.worldObj.getTotalWorldTime() % 20L == 0L) { diff --git a/src/game/java/net/minecraft/tileentity/TileEntityDispenser.java b/src/game/java/net/minecraft/tileentity/TileEntityDispenser.java index 786bf47a..5f0e89f9 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityDispenser.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityDispenser.java @@ -1,7 +1,6 @@ package net.minecraft.tileentity; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; @@ -11,22 +10,25 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,23 +38,38 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor private ItemStack[] stacks = new ItemStack[9]; protected String customName; - /**+ - * Returns the number of slots in the inventory. + /** + * + Add the given ItemStack to this Dispenser. Return the Slot the Item was + * placed in or -1 if no free slot is available. */ - public int getSizeInventory() { - return 9; + public int addItemStack(ItemStack stack) { + for (int i = 0; i < this.stacks.length; ++i) { + if (this.stacks[i] == null || this.stacks[i].getItem() == null) { + this.setInventorySlotContents(i, stack); + return i; + } + } + + return -1; } - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return this.stacks[i]; + public void clear() { + for (int i = 0; i < this.stacks.length; ++i) { + this.stacks[i] = null; + } + } - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + public void closeInventory(EntityPlayer var1) { + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerDispenser(inventoryplayer, this); + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.stacks[i] != null) { @@ -75,19 +92,6 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor } } - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (this.stacks[i] != null) { - ItemStack itemstack = this.stacks[i]; - this.stacks[i] = null; - return itemstack; - } else { - return null; - } - } - public int getDispenseSlot() { int i = -1; int j = 1; @@ -101,53 +105,76 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor return i; } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - this.stacks[i] = itemstack; - if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { - itemstack.stackSize = this.getInventoryStackLimit(); - } - - this.markDirty(); + public int getField(int var1) { + return 0; } - /**+ - * Add the given ItemStack to this Dispenser. Return the Slot - * the Item was placed in or -1 if no free slot is available. - */ - public int addItemStack(ItemStack stack) { - for (int i = 0; i < this.stacks.length; ++i) { - if (this.stacks[i] == null || this.stacks[i].getItem() == null) { - this.setInventorySlotContents(i, stack); - return i; - } - } - - return -1; + public int getFieldCount() { + return 0; } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + public String getGuiID() { + return "minecraft:dispenser"; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ public String getName() { return this.hasCustomName() ? this.customName : "container.dispenser"; } - public void setCustomName(String customName) { - this.customName = customName; + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return 9; } - /**+ - * Returns true if this thing is named + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return this.stacks[i]; + } + + /** + * + Returns true if this thing is named */ public boolean hasCustomName() { return this.customName != null; } + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + public void openInventory(EntityPlayer var1) { + } + public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); @@ -167,6 +194,39 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor } + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + if (this.stacks[i] != null) { + ItemStack itemstack = this.stacks[i]; + this.stacks[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setCustomName(String customName) { + this.customName = customName; + } + + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + this.stacks[i] = itemstack; + if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { + itemstack.stackSize = this.getInventoryStackLimit(); + } + + this.markDirty(); + } + public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); NBTTagList nbttaglist = new NBTTagList(); @@ -186,62 +246,4 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor } } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - public String getGuiID() { - return "minecraft:dispenser"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { - return new ContainerDispenser(inventoryplayer, this); - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } - - public void clear() { - for (int i = 0; i < this.stacks.length; ++i) { - this.stacks[i] = null; - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityDropper.java b/src/game/java/net/minecraft/tileentity/TileEntityDropper.java index f004c3d4..39ff7f1d 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityDropper.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityDropper.java @@ -1,35 +1,38 @@ package net.minecraft.tileentity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityDropper extends TileEntityDispenser { - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + public String getGuiID() { + return "minecraft:dropper"; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ public String getName() { return this.hasCustomName() ? this.customName : "container.dropper"; } - - public String getGuiID() { - return "minecraft:dropper"; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityEnchantmentTable.java b/src/game/java/net/minecraft/tileentity/TileEntityEnchantmentTable.java index d230112a..42621b84 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityEnchantmentTable.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityEnchantmentTable.java @@ -1,7 +1,6 @@ package net.minecraft.tileentity; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; @@ -14,27 +13,31 @@ import net.minecraft.util.ITickable; import net.minecraft.util.MathHelper; import net.minecraft.world.IInteractionObject; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, IInteractionObject { + private static EaglercraftRandom rand = new EaglercraftRandom(); public int tickCount; public float pageFlip; public float pageFlipPrev; @@ -45,15 +48,38 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, public float bookRotation; public float bookRotationPrev; public float field_145924_q; - private static EaglercraftRandom rand = new EaglercraftRandom(); private String customName; - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - if (this.hasCustomName()) { - nbttagcompound.setString("CustomName", this.customName); - } + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerEnchantment(inventoryplayer, this.worldObj, this.pos); + } + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public String getGuiID() { + return "minecraft:enchanting_table"; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.hasCustomName() ? this.customName : "container.enchant"; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.customName != null && this.customName.length() > 0; } public void readFromNBT(NBTTagCompound nbttagcompound) { @@ -64,8 +90,12 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, } - /**+ - * Like the old updateEntity(), except more generic. + public void setCustomName(String customNameIn) { + this.customName = customNameIn; + } + + /** + * + Like the old updateEntity(), except more generic. */ public void update() { this.bookSpreadPrev = this.bookSpread; @@ -128,39 +158,11 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, this.pageFlip += this.field_145929_l; } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.hasCustomName() ? this.customName : "container.enchant"; - } + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.customName); + } - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.customName != null && this.customName.length() > 0; - } - - public void setCustomName(String customNameIn) { - this.customName = customNameIn; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { - return new ContainerEnchantment(inventoryplayer, this.worldObj, this.pos); - } - - public String getGuiID() { - return "minecraft:enchanting_table"; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityEndPortal.java b/src/game/java/net/minecraft/tileentity/TileEntityEndPortal.java index 07cf8481..28a6aa6d 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityEndPortal.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityEndPortal.java @@ -1,21 +1,24 @@ package net.minecraft.tileentity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/tileentity/TileEntityEnderChest.java b/src/game/java/net/minecraft/tileentity/TileEntityEnderChest.java index 54742b4c..5ada98a1 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityEnderChest.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityEnderChest.java @@ -4,22 +4,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,8 +33,41 @@ public class TileEntityEnderChest extends TileEntity implements ITickable { public int numPlayersUsing; private int ticksSinceSync; - /**+ - * Like the old updateEntity(), except more generic. + public boolean canBeUsed(EntityPlayer parEntityPlayer) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : parEntityPlayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + public void closeChest() { + --this.numPlayersUsing; + this.worldObj.addBlockEvent(this.pos, Blocks.ender_chest, 1, this.numPlayersUsing); + } + + /** + * + invalidates a tile entity + */ + public void invalidate() { + this.updateContainingBlockInfo(); + super.invalidate(); + } + + public void openChest() { + ++this.numPlayersUsing; + this.worldObj.addBlockEvent(this.pos, Blocks.ender_chest, 1, this.numPlayersUsing); + } + + public boolean receiveClientEvent(int i, int j) { + if (i == 1) { + this.numPlayersUsing = j; + return true; + } else { + return super.receiveClientEvent(i, j); + } + } + + /** + * + Like the old updateEntity(), except more generic. */ public void update() { if (++this.ticksSinceSync % 20 * 4 == 0) { @@ -76,37 +112,4 @@ public class TileEntityEnderChest extends TileEntity implements ITickable { } } - - public boolean receiveClientEvent(int i, int j) { - if (i == 1) { - this.numPlayersUsing = j; - return true; - } else { - return super.receiveClientEvent(i, j); - } - } - - /**+ - * invalidates a tile entity - */ - public void invalidate() { - this.updateContainingBlockInfo(); - super.invalidate(); - } - - public void openChest() { - ++this.numPlayersUsing; - this.worldObj.addBlockEvent(this.pos, Blocks.ender_chest, 1, this.numPlayersUsing); - } - - public void closeChest() { - --this.numPlayersUsing; - this.worldObj.addBlockEvent(this.pos, Blocks.ender_chest, 1, this.numPlayersUsing); - } - - public boolean canBeUsed(EntityPlayer parEntityPlayer) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : parEntityPlayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityFlowerPot.java b/src/game/java/net/minecraft/tileentity/TileEntityFlowerPot.java index dbbafcec..a5cd5516 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityFlowerPot.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityFlowerPot.java @@ -6,22 +6,25 @@ import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,11 +41,25 @@ public class TileEntityFlowerPot extends TileEntity { this.flowerPotData = potData; } - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - ResourceLocation resourcelocation = (ResourceLocation) Item.itemRegistry.getNameForObject(this.flowerPotItem); - nbttagcompound.setString("Item", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound.setInteger("Data", this.flowerPotData); + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + nbttagcompound.removeTag("Item"); + nbttagcompound.setInteger("Item", Item.getIdFromItem(this.flowerPotItem)); + return new S35PacketUpdateTileEntity(this.pos, 5, nbttagcompound); + } + + public int getFlowerPotData() { + return this.flowerPotData; + } + + public Item getFlowerPotItem() { + return this.flowerPotItem; } public void readFromNBT(NBTTagCompound nbttagcompound) { @@ -56,30 +73,15 @@ public class TileEntityFlowerPot extends TileEntity { this.flowerPotData = nbttagcompound.getInteger("Data"); } - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - nbttagcompound.removeTag("Item"); - nbttagcompound.setInteger("Item", Item.getIdFromItem(this.flowerPotItem)); - return new S35PacketUpdateTileEntity(this.pos, 5, nbttagcompound); - } - public void setFlowerPotData(Item potItem, int potData) { this.flowerPotItem = potItem; this.flowerPotData = potData; } - public Item getFlowerPotItem() { - return this.flowerPotItem; - } - - public int getFlowerPotData() { - return this.flowerPotData; + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + ResourceLocation resourcelocation = (ResourceLocation) Item.itemRegistry.getNameForObject(this.flowerPotItem); + nbttagcompound.setString("Item", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound.setInteger("Data", this.flowerPotData); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityFurnace.java b/src/game/java/net/minecraft/tileentity/TileEntityFurnace.java index e57d62e9..b8148006 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityFurnace.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityFurnace.java @@ -25,22 +25,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,34 +52,130 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, private static final int[] slotsTop = new int[] { 0 }; private static final int[] slotsBottom = new int[] { 2, 1 }; private static final int[] slotsSides = new int[] { 1 }; - /**+ - * The ItemStacks that hold the items currently being used in - * the furnace + + /** + * + Returns the number of ticks that the supplied fuel item will keep the + * furnace burning, or 0 if the item isn't fuel + */ + public static int getItemBurnTime(ItemStack parItemStack) { + if (parItemStack == null) { + return 0; + } else { + Item item = parItemStack.getItem(); + if (item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.air) { + Block block = Block.getBlockFromItem(item); + if (block == Blocks.wooden_slab) { + return 150; + } + + if (block.getMaterial() == Material.wood) { + return 300; + } + + if (block == Blocks.coal_block) { + return 16000; + } + } + + return item instanceof ItemTool && ((ItemTool) item).getToolMaterialName().equals("WOOD") ? 200 + : (item instanceof ItemSword && ((ItemSword) item).getToolMaterialName().equals("WOOD") ? 200 + : (item instanceof ItemHoe && ((ItemHoe) item).getMaterialName().equals("WOOD") ? 200 + : (item == Items.stick ? 100 + : (item == Items.coal ? 1600 + : (item == Items.lava_bucket ? 20000 + : (item == Item.getItemFromBlock(Blocks.sapling) ? 100 + : (item == Items.blaze_rod ? 2400 : 0))))))); + } + } + + /** + * + Furnace isBurning + */ + public static boolean isBurning(IInventory parIInventory) { + return parIInventory.getField(0) > 0; + } + + public static boolean isItemFuel(ItemStack parItemStack) { + /** + * + Returns the number of ticks that the supplied fuel item will keep the + * furnace burning, or 0 if the item isn't fuel + */ + return getItemBurnTime(parItemStack) > 0; + } + + /** + * + The ItemStacks that hold the items currently being used in the furnace */ private ItemStack[] furnaceItemStacks = new ItemStack[3]; private int furnaceBurnTime; private int currentItemBurnTime; + private int cookTime; + private int totalCookTime; + private String furnaceCustomName; - /**+ - * Returns the number of slots in the inventory. + /** + * + Returns true if automation can extract the given item in the given slot + * from the given side. Args: slot, item, side */ - public int getSizeInventory() { - return this.furnaceItemStacks.length; + public boolean canExtractItem(int i, ItemStack itemstack, EnumFacing enumfacing) { + if (enumfacing == EnumFacing.DOWN && i == 1) { + Item item = itemstack.getItem(); + if (item != Items.water_bucket && item != Items.bucket) { + return false; + } + } + + return true; } - /**+ - * Returns the stack in the given slot. + /** + * + Returns true if automation can insert the given item in the given slot from + * the given side. Args: slot, item, side */ - public ItemStack getStackInSlot(int i) { - return this.furnaceItemStacks[i]; + public boolean canInsertItem(int i, ItemStack itemstack, EnumFacing var3) { + return this.isItemValidForSlot(i, itemstack); } - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. + /** + * + Returns true if the furnace can smelt an item, i.e. has a source item, + * destination stack isn't full, etc. + */ + private boolean canSmelt() { + if (this.furnaceItemStacks[0] == null) { + return false; + } else { + ItemStack itemstack = FurnaceRecipes.instance().getSmeltingResult(this.furnaceItemStacks[0]); + return itemstack == null ? false + : (this.furnaceItemStacks[2] == null ? true + : (!this.furnaceItemStacks[2].isItemEqual(itemstack) ? false + : (this.furnaceItemStacks[2].stackSize < this.getInventoryStackLimit() + && this.furnaceItemStacks[2].stackSize < this.furnaceItemStacks[2] + .getMaxStackSize() ? true + : this.furnaceItemStacks[2].stackSize < itemstack + .getMaxStackSize()))); + } + } + + public void clear() { + for (int i = 0; i < this.furnaceItemStacks.length; ++i) { + this.furnaceItemStacks[i] = null; + } + + } + + public void closeInventory(EntityPlayer var1) { + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { + return new ContainerFurnace(inventoryplayer, this); + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. */ public ItemStack decrStackSize(int i, int j) { if (this.furnaceItemStacks[i] != null) { @@ -97,56 +196,100 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, } } - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (this.furnaceItemStacks[i] != null) { - ItemStack itemstack = this.furnaceItemStacks[i]; - this.furnaceItemStacks[i] = null; - return itemstack; - } else { - return null; + public int getCookTime(ItemStack stack) { + return 200; + } + + public int getField(int i) { + switch (i) { + case 0: + return this.furnaceBurnTime; + case 1: + return this.currentItemBurnTime; + case 2: + return this.cookTime; + case 3: + return this.totalCookTime; + default: + return 0; } } - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - boolean flag = itemstack != null && itemstack.isItemEqual(this.furnaceItemStacks[i]) - && ItemStack.areItemStackTagsEqual(itemstack, this.furnaceItemStacks[i]); - this.furnaceItemStacks[i] = itemstack; - if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { - itemstack.stackSize = this.getInventoryStackLimit(); - } - - if (i == 0 && !flag) { - this.totalCookTime = this.getCookTime(itemstack); - this.cookTime = 0; - this.markDirty(); - } - + public int getFieldCount() { + return 4; } - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + public String getGuiID() { + return "minecraft:furnace"; + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ public String getName() { return this.hasCustomName() ? this.furnaceCustomName : "container.furnace"; } - /**+ - * Returns true if this thing is named + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.furnaceItemStacks.length; + } + + public int[] getSlotsForFace(EnumFacing enumfacing) { + return enumfacing == EnumFacing.DOWN ? slotsBottom : (enumfacing == EnumFacing.UP ? slotsTop : slotsSides); + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return this.furnaceItemStacks[i]; + } + + /** + * + Returns true if this thing is named */ public boolean hasCustomName() { return this.furnaceCustomName != null && this.furnaceCustomName.length() > 0; } - public void setCustomInventoryName(String parString1) { - this.furnaceCustomName = parString1; + /** + * + Furnace isBurning + */ + public boolean isBurning() { + return this.furnaceBurnTime > 0; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int i, ItemStack itemstack) { + return i == 2 ? false : (i != 1 ? true : isItemFuel(itemstack) || SlotFurnaceFuel.isBucket(itemstack)); + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + public void openInventory(EntityPlayer var1) { } public void readFromNBT(NBTTagCompound nbttagcompound) { @@ -172,53 +315,89 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, } - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setShort("BurnTime", (short) this.furnaceBurnTime); - nbttagcompound.setShort("CookTime", (short) this.cookTime); - nbttagcompound.setShort("CookTimeTotal", (short) this.totalCookTime); - NBTTagList nbttaglist = new NBTTagList(); + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + if (this.furnaceItemStacks[i] != null) { + ItemStack itemstack = this.furnaceItemStacks[i]; + this.furnaceItemStacks[i] = null; + return itemstack; + } else { + return null; + } + } - for (int i = 0; i < this.furnaceItemStacks.length; ++i) { - if (this.furnaceItemStacks[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - this.furnaceItemStacks[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); + public void setCustomInventoryName(String parString1) { + this.furnaceCustomName = parString1; + } + + public void setField(int i, int j) { + switch (i) { + case 0: + this.furnaceBurnTime = j; + break; + case 1: + this.currentItemBurnTime = j; + break; + case 2: + this.cookTime = j; + break; + case 3: + this.totalCookTime = j; + } + + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + boolean flag = itemstack != null && itemstack.isItemEqual(this.furnaceItemStacks[i]) + && ItemStack.areItemStackTagsEqual(itemstack, this.furnaceItemStacks[i]); + this.furnaceItemStacks[i] = itemstack; + if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { + itemstack.stackSize = this.getInventoryStackLimit(); + } + + if (i == 0 && !flag) { + this.totalCookTime = this.getCookTime(itemstack); + this.cookTime = 0; + this.markDirty(); + } + + } + + /** + * + Turn one item from the furnace source stack into the appropriate smelted + * item in the furnace result stack + */ + public void smeltItem() { + if (this.canSmelt()) { + ItemStack itemstack = FurnaceRecipes.instance().getSmeltingResult(this.furnaceItemStacks[0]); + if (this.furnaceItemStacks[2] == null) { + this.furnaceItemStacks[2] = itemstack.copy(); + } else if (this.furnaceItemStacks[2].getItem() == itemstack.getItem()) { + ++this.furnaceItemStacks[2].stackSize; } + + if (this.furnaceItemStacks[0].getItem() == Item.getItemFromBlock(Blocks.sponge) + && this.furnaceItemStacks[0].getMetadata() == 1 && this.furnaceItemStacks[1] != null + && this.furnaceItemStacks[1].getItem() == Items.bucket) { + this.furnaceItemStacks[1] = new ItemStack(Items.water_bucket); + } + + --this.furnaceItemStacks[0].stackSize; + if (this.furnaceItemStacks[0].stackSize <= 0) { + this.furnaceItemStacks[0] = null; + } + } - - nbttagcompound.setTag("Items", nbttaglist); - if (this.hasCustomName()) { - nbttagcompound.setString("CustomName", this.furnaceCustomName); - } - } - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * Furnace isBurning - */ - public boolean isBurning() { - return this.furnaceBurnTime > 0; - } - - /**+ - * Furnace isBurning - */ - public static boolean isBurning(IInventory parIInventory) { - return parIInventory.getField(0) > 0; - } - - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ public void update() { boolean flag = this.isBurning(); @@ -270,198 +449,25 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, } - public int getCookTime(ItemStack stack) { - return 200; - } + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setShort("BurnTime", (short) this.furnaceBurnTime); + nbttagcompound.setShort("CookTime", (short) this.cookTime); + nbttagcompound.setShort("CookTimeTotal", (short) this.totalCookTime); + NBTTagList nbttaglist = new NBTTagList(); - /**+ - * Returns true if the furnace can smelt an item, i.e. has a - * source item, destination stack isn't full, etc. - */ - private boolean canSmelt() { - if (this.furnaceItemStacks[0] == null) { - return false; - } else { - ItemStack itemstack = FurnaceRecipes.instance().getSmeltingResult(this.furnaceItemStacks[0]); - return itemstack == null ? false - : (this.furnaceItemStacks[2] == null ? true - : (!this.furnaceItemStacks[2].isItemEqual(itemstack) ? false - : (this.furnaceItemStacks[2].stackSize < this.getInventoryStackLimit() - && this.furnaceItemStacks[2].stackSize < this.furnaceItemStacks[2] - .getMaxStackSize() ? true - : this.furnaceItemStacks[2].stackSize < itemstack - .getMaxStackSize()))); - } - } - - /**+ - * Turn one item from the furnace source stack into the - * appropriate smelted item in the furnace result stack - */ - public void smeltItem() { - if (this.canSmelt()) { - ItemStack itemstack = FurnaceRecipes.instance().getSmeltingResult(this.furnaceItemStacks[0]); - if (this.furnaceItemStacks[2] == null) { - this.furnaceItemStacks[2] = itemstack.copy(); - } else if (this.furnaceItemStacks[2].getItem() == itemstack.getItem()) { - ++this.furnaceItemStacks[2].stackSize; - } - - if (this.furnaceItemStacks[0].getItem() == Item.getItemFromBlock(Blocks.sponge) - && this.furnaceItemStacks[0].getMetadata() == 1 && this.furnaceItemStacks[1] != null - && this.furnaceItemStacks[1].getItem() == Items.bucket) { - this.furnaceItemStacks[1] = new ItemStack(Items.water_bucket); - } - - --this.furnaceItemStacks[0].stackSize; - if (this.furnaceItemStacks[0].stackSize <= 0) { - this.furnaceItemStacks[0] = null; - } - - } - } - - /**+ - * Returns the number of ticks that the supplied fuel item will - * keep the furnace burning, or 0 if the item isn't fuel - */ - public static int getItemBurnTime(ItemStack parItemStack) { - if (parItemStack == null) { - return 0; - } else { - Item item = parItemStack.getItem(); - if (item instanceof ItemBlock && Block.getBlockFromItem(item) != Blocks.air) { - Block block = Block.getBlockFromItem(item); - if (block == Blocks.wooden_slab) { - return 150; - } - - if (block.getMaterial() == Material.wood) { - return 300; - } - - if (block == Blocks.coal_block) { - return 16000; - } - } - - return item instanceof ItemTool && ((ItemTool) item).getToolMaterialName().equals("WOOD") ? 200 - : (item instanceof ItemSword && ((ItemSword) item).getToolMaterialName().equals("WOOD") ? 200 - : (item instanceof ItemHoe && ((ItemHoe) item).getMaterialName().equals("WOOD") ? 200 - : (item == Items.stick ? 100 - : (item == Items.coal ? 1600 - : (item == Items.lava_bucket ? 20000 - : (item == Item.getItemFromBlock(Blocks.sapling) ? 100 - : (item == Items.blaze_rod ? 2400 : 0))))))); - } - } - - public static boolean isItemFuel(ItemStack parItemStack) { - /**+ - * Returns the number of ticks that the supplied fuel item will - * keep the furnace burning, or 0 if the item isn't fuel - */ - return getItemBurnTime(parItemStack) > 0; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int i, ItemStack itemstack) { - return i == 2 ? false : (i != 1 ? true : isItemFuel(itemstack) || SlotFurnaceFuel.isBucket(itemstack)); - } - - public int[] getSlotsForFace(EnumFacing enumfacing) { - return enumfacing == EnumFacing.DOWN ? slotsBottom : (enumfacing == EnumFacing.UP ? slotsTop : slotsSides); - } - - /**+ - * Returns true if automation can insert the given item in the - * given slot from the given side. Args: slot, item, side - */ - public boolean canInsertItem(int i, ItemStack itemstack, EnumFacing var3) { - return this.isItemValidForSlot(i, itemstack); - } - - /**+ - * Returns true if automation can extract the given item in the - * given slot from the given side. Args: slot, item, side - */ - public boolean canExtractItem(int i, ItemStack itemstack, EnumFacing enumfacing) { - if (enumfacing == EnumFacing.DOWN && i == 1) { - Item item = itemstack.getItem(); - if (item != Items.water_bucket && item != Items.bucket) { - return false; - } - } - - return true; - } - - public String getGuiID() { - return "minecraft:furnace"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer var2) { - return new ContainerFurnace(inventoryplayer, this); - } - - public int getField(int i) { - switch (i) { - case 0: - return this.furnaceBurnTime; - case 1: - return this.currentItemBurnTime; - case 2: - return this.cookTime; - case 3: - return this.totalCookTime; - default: - return 0; - } - } - - public void setField(int i, int j) { - switch (i) { - case 0: - this.furnaceBurnTime = j; - break; - case 1: - this.currentItemBurnTime = j; - break; - case 2: - this.cookTime = j; - break; - case 3: - this.totalCookTime = j; - } - - } - - public int getFieldCount() { - return 4; - } - - public void clear() { for (int i = 0; i < this.furnaceItemStacks.length; ++i) { - this.furnaceItemStacks[i] = null; + if (this.furnaceItemStacks[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + this.furnaceItemStacks[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + + nbttagcompound.setTag("Items", nbttaglist); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.furnaceCustomName); } } diff --git a/src/game/java/net/minecraft/tileentity/TileEntityHopper.java b/src/game/java/net/minecraft/tileentity/TileEntityHopper.java index 469fcdd8..e5f30b81 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityHopper.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityHopper.java @@ -1,6 +1,7 @@ package net.minecraft.tileentity; import java.util.List; + import net.minecraft.block.Block; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockHopper; @@ -23,334 +24,54 @@ import net.minecraft.util.ITickable; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITickable { - private ItemStack[] inventory = new ItemStack[5]; - private String customName; - private int transferCooldown = -1; - - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); - this.inventory = new ItemStack[this.getSizeInventory()]; - if (nbttagcompound.hasKey("CustomName", 8)) { - this.customName = nbttagcompound.getString("CustomName"); - } - - this.transferCooldown = nbttagcompound.getInteger("TransferCooldown"); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - byte b0 = nbttagcompound1.getByte("Slot"); - if (b0 >= 0 && b0 < this.inventory.length) { - this.inventory[b0] = ItemStack.loadItemStackFromNBT(nbttagcompound1); - } - } - + private static boolean canCombine(ItemStack stack1, ItemStack stack2) { + return stack1.getItem() != stack2.getItem() ? false + : (stack1.getMetadata() != stack2.getMetadata() ? false + : (stack1.stackSize > stack1.getMaxStackSize() ? false + : ItemStack.areItemStackTagsEqual(stack1, stack2))); } - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.inventory.length; ++i) { - if (this.inventory[i] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setByte("Slot", (byte) i); - this.inventory[i].writeToNBT(nbttagcompound1); - nbttaglist.appendTag(nbttagcompound1); - } - } - - nbttagcompound.setTag("Items", nbttaglist); - nbttagcompound.setInteger("TransferCooldown", this.transferCooldown); - if (this.hasCustomName()) { - nbttagcompound.setString("CustomName", this.customName); - } - - } - - /**+ - * For tile entities, ensures the chunk containing the tile - * entity is saved to disk later - the game won't think it - * hasn't changed and skip it. + /** + * + Can this hopper extract the specified item from the specified slot on the + * specified side? */ - public void markDirty() { - super.markDirty(); + private static boolean canExtractItemFromSlot(IInventory inventoryIn, ItemStack stack, int index, EnumFacing side) { + return !(inventoryIn instanceof ISidedInventory) + || ((ISidedInventory) inventoryIn).canExtractItem(index, stack, side); } - /**+ - * Returns the number of slots in the inventory. + /** + * + Can this hopper insert the specified item from the specified slot on the + * specified side? */ - public int getSizeInventory() { - return this.inventory.length; - } - - /**+ - * Returns the stack in the given slot. - */ - public ItemStack getStackInSlot(int i) { - return this.inventory[i]; - } - - /**+ - * Removes up to a specified number of items from an inventory - * slot and returns them in a new stack. - */ - public ItemStack decrStackSize(int i, int j) { - if (this.inventory[i] != null) { - if (this.inventory[i].stackSize <= j) { - ItemStack itemstack1 = this.inventory[i]; - this.inventory[i] = null; - return itemstack1; - } else { - ItemStack itemstack = this.inventory[i].splitStack(j); - if (this.inventory[i].stackSize == 0) { - this.inventory[i] = null; - } - - return itemstack; - } - } else { - return null; - } - } - - /**+ - * Removes a stack from the given slot and returns it. - */ - public ItemStack removeStackFromSlot(int i) { - if (this.inventory[i] != null) { - ItemStack itemstack = this.inventory[i]; - this.inventory[i] = null; - return itemstack; - } else { - return null; - } - } - - /**+ - * Sets the given item stack to the specified slot in the - * inventory (can be crafting or armor sections). - */ - public void setInventorySlotContents(int i, ItemStack itemstack) { - this.inventory[i] = itemstack; - if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { - itemstack.stackSize = this.getInventoryStackLimit(); - } - - } - - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") - */ - public String getName() { - return this.hasCustomName() ? this.customName : "container.hopper"; - } - - /**+ - * Returns true if this thing is named - */ - public boolean hasCustomName() { - return this.customName != null && this.customName.length() > 0; - } - - public void setCustomName(String customNameIn) { - this.customName = customNameIn; - } - - /**+ - * Returns the maximum stack size for a inventory slot. Seems to - * always be 64, possibly will be extended. - */ - public int getInventoryStackLimit() { - return 64; - } - - /**+ - * Do not make give this method the name canInteractWith because - * it clashes with Container - */ - public boolean isUseableByPlayer(EntityPlayer entityplayer) { - return this.worldObj.getTileEntity(this.pos) != this ? false - : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, - (double) this.pos.getZ() + 0.5D) <= 64.0D; - } - - public void openInventory(EntityPlayer var1) { - } - - public void closeInventory(EntityPlayer var1) { - } - - /**+ - * Returns true if automation is allowed to insert the given - * stack (ignoring stack size) into the given slot. - */ - public boolean isItemValidForSlot(int var1, ItemStack var2) { - return true; - } - - /**+ - * Like the old updateEntity(), except more generic. - */ - public void update() { - if (this.worldObj != null && !this.worldObj.isRemote) { - --this.transferCooldown; - if (!this.isOnTransferCooldown()) { - this.setTransferCooldown(0); - this.updateHopper(); - } - - } - } - - public boolean updateHopper() { - if (this.worldObj != null && !this.worldObj.isRemote) { - if (!this.isOnTransferCooldown() && BlockHopper.isEnabled(this.getBlockMetadata())) { - boolean flag = false; - if (!this.isEmpty()) { - flag = this.transferItemsOut(); - } - - if (!this.isFull()) { - flag = captureDroppedItems(this) || flag; - } - - if (flag) { - this.setTransferCooldown(8); - this.markDirty(); - return true; - } - } - - return false; - } else { - return false; - } - } - - private boolean isEmpty() { - for (int i = 0; i < this.inventory.length; ++i) { - if (this.inventory[i] != null) { - return false; - } - } - - return true; - } - - private boolean isFull() { - for (int i = 0; i < this.inventory.length; ++i) { - ItemStack itemstack = this.inventory[i]; - if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { - return false; - } - } - - return true; - } - - private boolean transferItemsOut() { - IInventory iinventory = this.getInventoryForHopperTransfer(); - if (iinventory == null) { - return false; - } else { - EnumFacing enumfacing = BlockHopper.getFacing(this.getBlockMetadata()).getOpposite(); - if (this.isInventoryFull(iinventory, enumfacing)) { - return false; - } else { - for (int i = 0; i < this.getSizeInventory(); ++i) { - if (this.getStackInSlot(i) != null) { - ItemStack itemstack = this.getStackInSlot(i).copy(); - ItemStack itemstack1 = putStackInInventoryAllSlots(iinventory, this.decrStackSize(i, 1), - enumfacing); - if (itemstack1 == null || itemstack1.stackSize == 0) { - iinventory.markDirty(); - return true; - } - - this.setInventorySlotContents(i, itemstack); - } - } - - return false; - } - } - } - - /**+ - * Returns false if the inventory has any room to place items in - */ - private boolean isInventoryFull(IInventory inventoryIn, EnumFacing side) { - if (inventoryIn instanceof ISidedInventory) { - ISidedInventory isidedinventory = (ISidedInventory) inventoryIn; - int[] aint = isidedinventory.getSlotsForFace(side); - - for (int k = 0; k < aint.length; ++k) { - ItemStack itemstack1 = isidedinventory.getStackInSlot(aint[k]); - if (itemstack1 == null || itemstack1.stackSize != itemstack1.getMaxStackSize()) { - return false; - } - } - } else { - int i = inventoryIn.getSizeInventory(); - - for (int j = 0; j < i; ++j) { - ItemStack itemstack = inventoryIn.getStackInSlot(j); - if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { - return false; - } - } - } - - return true; - } - - /**+ - * Returns false if the specified IInventory contains any items - */ - private static boolean isInventoryEmpty(IInventory inventoryIn, EnumFacing side) { - if (inventoryIn instanceof ISidedInventory) { - ISidedInventory isidedinventory = (ISidedInventory) inventoryIn; - int[] aint = isidedinventory.getSlotsForFace(side); - - for (int i = 0; i < aint.length; ++i) { - if (isidedinventory.getStackInSlot(aint[i]) != null) { - return false; - } - } - } else { - int j = inventoryIn.getSizeInventory(); - - for (int k = 0; k < j; ++k) { - if (inventoryIn.getStackInSlot(k) != null) { - return false; - } - } - } - - return true; + private static boolean canInsertItemInSlot(IInventory inventoryIn, ItemStack stack, int index, EnumFacing side) { + return !inventoryIn.isItemValidForSlot(index, stack) ? false + : !(inventoryIn instanceof ISidedInventory) + || ((ISidedInventory) inventoryIn).canInsertItem(index, stack, side); } public static boolean captureDroppedItems(IHopper parIHopper) { @@ -392,100 +113,62 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi return false; } - /**+ - * Pulls from the specified slot in the inventory and places in - * any available slot in the hopper. Returns true if the entire - * stack was moved - */ - private static boolean pullItemFromSlot(IHopper hopper, IInventory inventoryIn, int index, EnumFacing direction) { - ItemStack itemstack = inventoryIn.getStackInSlot(index); - if (itemstack != null && canExtractItemFromSlot(inventoryIn, itemstack, index, direction)) { - ItemStack itemstack1 = itemstack.copy(); - ItemStack itemstack2 = putStackInInventoryAllSlots(hopper, inventoryIn.decrStackSize(index, 1), - (EnumFacing) null); - if (itemstack2 == null || itemstack2.stackSize == 0) { - inventoryIn.markDirty(); - return true; - } - - inventoryIn.setInventorySlotContents(index, itemstack1); - } - - return false; + public static List func_181556_a(World parWorld, double parDouble1, double parDouble2, + double parDouble3) { + return parWorld + .getEntitiesWithinAABB( + EntityItem.class, new AxisAlignedBB(parDouble1 - 0.5D, parDouble2 - 0.5D, parDouble3 - 0.5D, + parDouble1 + 0.5D, parDouble2 + 0.5D, parDouble3 + 0.5D), + EntitySelectors.selectAnything); } - /**+ - * Attempts to place the passed EntityItem's stack into the - * inventory using as many slots as possible. Returns false if - * the stackSize of the drop was not depleted. + /** + * + Returns the IInventory for the specified hopper */ - public static boolean putDropInInventoryAllSlots(IInventory itemIn, EntityItem parEntityItem) { - boolean flag = false; - if (parEntityItem == null) { - return false; - } else { - ItemStack itemstack = parEntityItem.getEntityItem().copy(); - ItemStack itemstack1 = putStackInInventoryAllSlots(itemIn, itemstack, (EnumFacing) null); - if (itemstack1 != null && itemstack1.stackSize != 0) { - parEntityItem.setEntityItemStack(itemstack1); - } else { - flag = true; - parEntityItem.setDead(); - } - - return flag; - } + public static IInventory getHopperInventory(IHopper hopper) { + /** + * + Returns the IInventory (if applicable) of the TileEntity at the specified + * position + */ + return getInventoryAtPosition(hopper.getWorld(), hopper.getXPos(), hopper.getYPos() + 1.0D, hopper.getZPos()); } - /**+ - * Attempts to place the passed stack in the inventory, using as - * many slots as required. Returns leftover items + /** + * + Returns the IInventory (if applicable) of the TileEntity at the specified + * position */ - public static ItemStack putStackInInventoryAllSlots(IInventory inventoryIn, ItemStack stack, EnumFacing side) { - if (inventoryIn instanceof ISidedInventory && side != null) { - ISidedInventory isidedinventory = (ISidedInventory) inventoryIn; - int[] aint = isidedinventory.getSlotsForFace(side); - - for (int k = 0; k < aint.length && stack != null && stack.stackSize > 0; ++k) { - stack = insertStack(inventoryIn, stack, aint[k], side); - } - } else { - int i = inventoryIn.getSizeInventory(); - - for (int j = 0; j < i && stack != null && stack.stackSize > 0; ++j) { - stack = insertStack(inventoryIn, stack, j, side); + public static IInventory getInventoryAtPosition(World worldIn, double x, double y, double z) { + Object object = null; + int i = MathHelper.floor_double(x); + int j = MathHelper.floor_double(y); + int k = MathHelper.floor_double(z); + BlockPos blockpos = new BlockPos(i, j, k); + Block block = worldIn.getBlockState(blockpos).getBlock(); + if (block.hasTileEntity()) { + TileEntity tileentity = worldIn.getTileEntity(blockpos); + if (tileentity instanceof IInventory) { + object = (IInventory) tileentity; + if (object instanceof TileEntityChest && block instanceof BlockChest) { + object = ((BlockChest) block).getLockableContainer(worldIn, blockpos); + } } } - if (stack != null && stack.stackSize == 0) { - stack = null; + if (object == null) { + List list = worldIn.getEntitiesInAABBexcluding((Entity) null, + new AxisAlignedBB(x - 0.5D, y - 0.5D, z - 0.5D, x + 0.5D, y + 0.5D, z + 0.5D), + EntitySelectors.selectInventories); + if (list.size() > 0) { + object = (IInventory) list.get(worldIn.rand.nextInt(list.size())); + } } - return stack; + return (IInventory) object; } - /**+ - * Can this hopper insert the specified item from the specified - * slot on the specified side? - */ - private static boolean canInsertItemInSlot(IInventory inventoryIn, ItemStack stack, int index, EnumFacing side) { - return !inventoryIn.isItemValidForSlot(index, stack) ? false - : !(inventoryIn instanceof ISidedInventory) - || ((ISidedInventory) inventoryIn).canInsertItem(index, stack, side); - } - - /**+ - * Can this hopper extract the specified item from the specified - * slot on the specified side? - */ - private static boolean canExtractItemFromSlot(IInventory inventoryIn, ItemStack stack, int index, EnumFacing side) { - return !(inventoryIn instanceof ISidedInventory) - || ((ISidedInventory) inventoryIn).canExtractItem(index, stack, side); - } - - /**+ - * Insert the specified stack to the specified inventory and - * return any leftover items + /** + * + Insert the specified stack to the specified inventory and return any + * leftover items */ private static ItemStack insertStack(IInventory inventoryIn, ItemStack stack, int index, EnumFacing side) { ItemStack itemstack = inventoryIn.getStackInSlot(index); @@ -520,131 +203,108 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi return stack; } - /**+ - * Returns the IInventory that this hopper is pointing into + /** + * + Returns false if the specified IInventory contains any items */ - private IInventory getInventoryForHopperTransfer() { - EnumFacing enumfacing = BlockHopper.getFacing(this.getBlockMetadata()); - /**+ - * Returns the IInventory (if applicable) of the TileEntity at - * the specified position - */ - return getInventoryAtPosition(this.getWorld(), (double) (this.pos.getX() + enumfacing.getFrontOffsetX()), - (double) (this.pos.getY() + enumfacing.getFrontOffsetY()), - (double) (this.pos.getZ() + enumfacing.getFrontOffsetZ())); - } + private static boolean isInventoryEmpty(IInventory inventoryIn, EnumFacing side) { + if (inventoryIn instanceof ISidedInventory) { + ISidedInventory isidedinventory = (ISidedInventory) inventoryIn; + int[] aint = isidedinventory.getSlotsForFace(side); - /**+ - * Returns the IInventory for the specified hopper - */ - public static IInventory getHopperInventory(IHopper hopper) { - /**+ - * Returns the IInventory (if applicable) of the TileEntity at - * the specified position - */ - return getInventoryAtPosition(hopper.getWorld(), hopper.getXPos(), hopper.getYPos() + 1.0D, hopper.getZPos()); - } + for (int i = 0; i < aint.length; ++i) { + if (isidedinventory.getStackInSlot(aint[i]) != null) { + return false; + } + } + } else { + int j = inventoryIn.getSizeInventory(); - public static List func_181556_a(World parWorld, double parDouble1, double parDouble2, - double parDouble3) { - return parWorld - .getEntitiesWithinAABB( - EntityItem.class, new AxisAlignedBB(parDouble1 - 0.5D, parDouble2 - 0.5D, parDouble3 - 0.5D, - parDouble1 + 0.5D, parDouble2 + 0.5D, parDouble3 + 0.5D), - EntitySelectors.selectAnything); - } - - /**+ - * Returns the IInventory (if applicable) of the TileEntity at - * the specified position - */ - public static IInventory getInventoryAtPosition(World worldIn, double x, double y, double z) { - Object object = null; - int i = MathHelper.floor_double(x); - int j = MathHelper.floor_double(y); - int k = MathHelper.floor_double(z); - BlockPos blockpos = new BlockPos(i, j, k); - Block block = worldIn.getBlockState(blockpos).getBlock(); - if (block.hasTileEntity()) { - TileEntity tileentity = worldIn.getTileEntity(blockpos); - if (tileentity instanceof IInventory) { - object = (IInventory) tileentity; - if (object instanceof TileEntityChest && block instanceof BlockChest) { - object = ((BlockChest) block).getLockableContainer(worldIn, blockpos); + for (int k = 0; k < j; ++k) { + if (inventoryIn.getStackInSlot(k) != null) { + return false; } } } - if (object == null) { - List list = worldIn.getEntitiesInAABBexcluding((Entity) null, - new AxisAlignedBB(x - 0.5D, y - 0.5D, z - 0.5D, x + 0.5D, y + 0.5D, z + 0.5D), - EntitySelectors.selectInventories); - if (list.size() > 0) { - object = (IInventory) list.get(worldIn.rand.nextInt(list.size())); + return true; + } + + /** + * + Pulls from the specified slot in the inventory and places in any available + * slot in the hopper. Returns true if the entire stack was moved + */ + private static boolean pullItemFromSlot(IHopper hopper, IInventory inventoryIn, int index, EnumFacing direction) { + ItemStack itemstack = inventoryIn.getStackInSlot(index); + if (itemstack != null && canExtractItemFromSlot(inventoryIn, itemstack, index, direction)) { + ItemStack itemstack1 = itemstack.copy(); + ItemStack itemstack2 = putStackInInventoryAllSlots(hopper, inventoryIn.decrStackSize(index, 1), + (EnumFacing) null); + if (itemstack2 == null || itemstack2.stackSize == 0) { + inventoryIn.markDirty(); + return true; + } + + inventoryIn.setInventorySlotContents(index, itemstack1); + } + + return false; + } + + /** + * + Attempts to place the passed EntityItem's stack into the inventory using as + * many slots as possible. Returns false if the stackSize of the drop was not + * depleted. + */ + public static boolean putDropInInventoryAllSlots(IInventory itemIn, EntityItem parEntityItem) { + boolean flag = false; + if (parEntityItem == null) { + return false; + } else { + ItemStack itemstack = parEntityItem.getEntityItem().copy(); + ItemStack itemstack1 = putStackInInventoryAllSlots(itemIn, itemstack, (EnumFacing) null); + if (itemstack1 != null && itemstack1.stackSize != 0) { + parEntityItem.setEntityItemStack(itemstack1); + } else { + flag = true; + parEntityItem.setDead(); + } + + return flag; + } + } + + /** + * + Attempts to place the passed stack in the inventory, using as many slots as + * required. Returns leftover items + */ + public static ItemStack putStackInInventoryAllSlots(IInventory inventoryIn, ItemStack stack, EnumFacing side) { + if (inventoryIn instanceof ISidedInventory && side != null) { + ISidedInventory isidedinventory = (ISidedInventory) inventoryIn; + int[] aint = isidedinventory.getSlotsForFace(side); + + for (int k = 0; k < aint.length && stack != null && stack.stackSize > 0; ++k) { + stack = insertStack(inventoryIn, stack, aint[k], side); + } + } else { + int i = inventoryIn.getSizeInventory(); + + for (int j = 0; j < i && stack != null && stack.stackSize > 0; ++j) { + stack = insertStack(inventoryIn, stack, j, side); } } - return (IInventory) object; + if (stack != null && stack.stackSize == 0) { + stack = null; + } + + return stack; } - private static boolean canCombine(ItemStack stack1, ItemStack stack2) { - return stack1.getItem() != stack2.getItem() ? false - : (stack1.getMetadata() != stack2.getMetadata() ? false - : (stack1.stackSize > stack1.getMaxStackSize() ? false - : ItemStack.areItemStackTagsEqual(stack1, stack2))); - } + private ItemStack[] inventory = new ItemStack[5]; - /**+ - * Gets the world X position for this hopper entity. - */ - public double getXPos() { - return (double) this.pos.getX() + 0.5D; - } + private String customName; - /**+ - * Gets the world Y position for this hopper entity. - */ - public double getYPos() { - return (double) this.pos.getY() + 0.5D; - } - - /**+ - * Gets the world Z position for this hopper entity. - */ - public double getZPos() { - return (double) this.pos.getZ() + 0.5D; - } - - public void setTransferCooldown(int ticks) { - this.transferCooldown = ticks; - } - - public boolean isOnTransferCooldown() { - return this.transferCooldown > 0; - } - - public boolean mayTransfer() { - return this.transferCooldown <= 1; - } - - public String getGuiID() { - return "minecraft:hopper"; - } - - public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { - return new ContainerHopper(inventoryplayer, this, entityplayer); - } - - public int getField(int var1) { - return 0; - } - - public void setField(int var1, int var2) { - } - - public int getFieldCount() { - return 0; - } + private int transferCooldown = -1; public void clear() { for (int i = 0; i < this.inventory.length; ++i) { @@ -652,4 +312,348 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi } } + + public void closeInventory(EntityPlayer var1) { + } + + public Container createContainer(InventoryPlayer inventoryplayer, EntityPlayer entityplayer) { + return new ContainerHopper(inventoryplayer, this, entityplayer); + } + + /** + * + Removes up to a specified number of items from an inventory slot and + * returns them in a new stack. + */ + public ItemStack decrStackSize(int i, int j) { + if (this.inventory[i] != null) { + if (this.inventory[i].stackSize <= j) { + ItemStack itemstack1 = this.inventory[i]; + this.inventory[i] = null; + return itemstack1; + } else { + ItemStack itemstack = this.inventory[i].splitStack(j); + if (this.inventory[i].stackSize == 0) { + this.inventory[i] = null; + } + + return itemstack; + } + } else { + return null; + } + } + + public int getField(int var1) { + return 0; + } + + public int getFieldCount() { + return 0; + } + + public String getGuiID() { + return "minecraft:hopper"; + } + + /** + * + Returns the IInventory that this hopper is pointing into + */ + private IInventory getInventoryForHopperTransfer() { + EnumFacing enumfacing = BlockHopper.getFacing(this.getBlockMetadata()); + /** + * + Returns the IInventory (if applicable) of the TileEntity at the specified + * position + */ + return getInventoryAtPosition(this.getWorld(), (double) (this.pos.getX() + enumfacing.getFrontOffsetX()), + (double) (this.pos.getY() + enumfacing.getFrontOffsetY()), + (double) (this.pos.getZ() + enumfacing.getFrontOffsetZ())); + } + + /** + * + Returns the maximum stack size for a inventory slot. Seems to always be 64, + * possibly will be extended. + */ + public int getInventoryStackLimit() { + return 64; + } + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") + */ + public String getName() { + return this.hasCustomName() ? this.customName : "container.hopper"; + } + + /** + * + Returns the number of slots in the inventory. + */ + public int getSizeInventory() { + return this.inventory.length; + } + + /** + * + Returns the stack in the given slot. + */ + public ItemStack getStackInSlot(int i) { + return this.inventory[i]; + } + + /** + * + Gets the world X position for this hopper entity. + */ + public double getXPos() { + return (double) this.pos.getX() + 0.5D; + } + + /** + * + Gets the world Y position for this hopper entity. + */ + public double getYPos() { + return (double) this.pos.getY() + 0.5D; + } + + /** + * + Gets the world Z position for this hopper entity. + */ + public double getZPos() { + return (double) this.pos.getZ() + 0.5D; + } + + /** + * + Returns true if this thing is named + */ + public boolean hasCustomName() { + return this.customName != null && this.customName.length() > 0; + } + + private boolean isEmpty() { + for (int i = 0; i < this.inventory.length; ++i) { + if (this.inventory[i] != null) { + return false; + } + } + + return true; + } + + private boolean isFull() { + for (int i = 0; i < this.inventory.length; ++i) { + ItemStack itemstack = this.inventory[i]; + if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { + return false; + } + } + + return true; + } + + /** + * + Returns false if the inventory has any room to place items in + */ + private boolean isInventoryFull(IInventory inventoryIn, EnumFacing side) { + if (inventoryIn instanceof ISidedInventory) { + ISidedInventory isidedinventory = (ISidedInventory) inventoryIn; + int[] aint = isidedinventory.getSlotsForFace(side); + + for (int k = 0; k < aint.length; ++k) { + ItemStack itemstack1 = isidedinventory.getStackInSlot(aint[k]); + if (itemstack1 == null || itemstack1.stackSize != itemstack1.getMaxStackSize()) { + return false; + } + } + } else { + int i = inventoryIn.getSizeInventory(); + + for (int j = 0; j < i; ++j) { + ItemStack itemstack = inventoryIn.getStackInSlot(j); + if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { + return false; + } + } + } + + return true; + } + + /** + * + Returns true if automation is allowed to insert the given stack (ignoring + * stack size) into the given slot. + */ + public boolean isItemValidForSlot(int var1, ItemStack var2) { + return true; + } + + public boolean isOnTransferCooldown() { + return this.transferCooldown > 0; + } + + /** + * + Do not make give this method the name canInteractWith because it clashes + * with Container + */ + public boolean isUseableByPlayer(EntityPlayer entityplayer) { + return this.worldObj.getTileEntity(this.pos) != this ? false + : entityplayer.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, + (double) this.pos.getZ() + 0.5D) <= 64.0D; + } + + /** + * + For tile entities, ensures the chunk containing the tile entity is saved to + * disk later - the game won't think it hasn't changed and skip it. + */ + public void markDirty() { + super.markDirty(); + } + + public boolean mayTransfer() { + return this.transferCooldown <= 1; + } + + public void openInventory(EntityPlayer var1) { + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + NBTTagList nbttaglist = nbttagcompound.getTagList("Items", 10); + this.inventory = new ItemStack[this.getSizeInventory()]; + if (nbttagcompound.hasKey("CustomName", 8)) { + this.customName = nbttagcompound.getString("CustomName"); + } + + this.transferCooldown = nbttagcompound.getInteger("TransferCooldown"); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + byte b0 = nbttagcompound1.getByte("Slot"); + if (b0 >= 0 && b0 < this.inventory.length) { + this.inventory[b0] = ItemStack.loadItemStackFromNBT(nbttagcompound1); + } + } + + } + + /** + * + Removes a stack from the given slot and returns it. + */ + public ItemStack removeStackFromSlot(int i) { + if (this.inventory[i] != null) { + ItemStack itemstack = this.inventory[i]; + this.inventory[i] = null; + return itemstack; + } else { + return null; + } + } + + public void setCustomName(String customNameIn) { + this.customName = customNameIn; + } + + public void setField(int var1, int var2) { + } + + /** + * + Sets the given item stack to the specified slot in the inventory (can be + * crafting or armor sections). + */ + public void setInventorySlotContents(int i, ItemStack itemstack) { + this.inventory[i] = itemstack; + if (itemstack != null && itemstack.stackSize > this.getInventoryStackLimit()) { + itemstack.stackSize = this.getInventoryStackLimit(); + } + + } + + public void setTransferCooldown(int ticks) { + this.transferCooldown = ticks; + } + + private boolean transferItemsOut() { + IInventory iinventory = this.getInventoryForHopperTransfer(); + if (iinventory == null) { + return false; + } else { + EnumFacing enumfacing = BlockHopper.getFacing(this.getBlockMetadata()).getOpposite(); + if (this.isInventoryFull(iinventory, enumfacing)) { + return false; + } else { + for (int i = 0; i < this.getSizeInventory(); ++i) { + if (this.getStackInSlot(i) != null) { + ItemStack itemstack = this.getStackInSlot(i).copy(); + ItemStack itemstack1 = putStackInInventoryAllSlots(iinventory, this.decrStackSize(i, 1), + enumfacing); + if (itemstack1 == null || itemstack1.stackSize == 0) { + iinventory.markDirty(); + return true; + } + + this.setInventorySlotContents(i, itemstack); + } + } + + return false; + } + } + } + + /** + * + Like the old updateEntity(), except more generic. + */ + public void update() { + if (this.worldObj != null && !this.worldObj.isRemote) { + --this.transferCooldown; + if (!this.isOnTransferCooldown()) { + this.setTransferCooldown(0); + this.updateHopper(); + } + + } + } + + public boolean updateHopper() { + if (this.worldObj != null && !this.worldObj.isRemote) { + if (!this.isOnTransferCooldown() && BlockHopper.isEnabled(this.getBlockMetadata())) { + boolean flag = false; + if (!this.isEmpty()) { + flag = this.transferItemsOut(); + } + + if (!this.isFull()) { + flag = captureDroppedItems(this) || flag; + } + + if (flag) { + this.setTransferCooldown(8); + this.markDirty(); + return true; + } + } + + return false; + } else { + return false; + } + } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.inventory.length; ++i) { + if (this.inventory[i] != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setByte("Slot", (byte) i); + this.inventory[i].writeToNBT(nbttagcompound1); + nbttaglist.appendTag(nbttagcompound1); + } + } + + nbttagcompound.setTag("Items", nbttaglist); + nbttagcompound.setInteger("TransferCooldown", this.transferCooldown); + if (this.hasCustomName()) { + nbttagcompound.setString("CustomName", this.customName); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityLockable.java b/src/game/java/net/minecraft/tileentity/TileEntityLockable.java index c2ce3ed0..115c37a0 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityLockable.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityLockable.java @@ -8,22 +8,25 @@ import net.minecraft.world.IInteractionObject; import net.minecraft.world.ILockableContainer; import net.minecraft.world.LockCode; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,11 +34,32 @@ import net.minecraft.world.LockCode; public abstract class TileEntityLockable extends TileEntity implements IInteractionObject, ILockableContainer { private LockCode code = LockCode.EMPTY_CODE; + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + public IChatComponent getDisplayName() { + return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) + : new ChatComponentTranslation(this.getName(), new Object[0])); + } + + public LockCode getLockCode() { + return this.code; + } + + public boolean isLocked() { + return this.code != null && !this.code.isEmpty(); + } + public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); this.code = LockCode.fromNBT(nbttagcompound); } + public void setLockCode(LockCode code) { + this.code = code; + } + public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); if (this.code != null) { @@ -43,25 +67,4 @@ public abstract class TileEntityLockable extends TileEntity implements IInteract } } - - public boolean isLocked() { - return this.code != null && !this.code.isEmpty(); - } - - public LockCode getLockCode() { - return this.code; - } - - public void setLockCode(LockCode code) { - this.code = code; - } - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - public IChatComponent getDisplayName() { - return (IChatComponent) (this.hasCustomName() ? new ChatComponentText(this.getName()) - : new ChatComponentTranslation(this.getName(), new Object[0])); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityMobSpawner.java b/src/game/java/net/minecraft/tileentity/TileEntityMobSpawner.java index 189162af..0efa608a 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityMobSpawner.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityMobSpawner.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.ITickable; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,14 +37,14 @@ public class TileEntityMobSpawner extends TileEntity implements ITickable { TileEntityMobSpawner.this.worldObj.addBlockEvent(TileEntityMobSpawner.this.pos, Blocks.mob_spawner, i, 0); } - public World getSpawnerWorld() { - return TileEntityMobSpawner.this.worldObj; - } - public BlockPos getSpawnerPosition() { return TileEntityMobSpawner.this.pos; } + public World getSpawnerWorld() { + return TileEntityMobSpawner.this.worldObj; + } + public void setRandomEntity( MobSpawnerBaseLogic.WeightedRandomMinecart mobspawnerbaselogic$weightedrandomminecart) { super.setRandomEntity(mobspawnerbaselogic$weightedrandomminecart); @@ -52,28 +55,14 @@ public class TileEntityMobSpawner extends TileEntity implements ITickable { } }; - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - this.spawnerLogic.readFromNBT(nbttagcompound); + public boolean func_183000_F() { + return true; } - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - this.spawnerLogic.writeToNBT(nbttagcompound); - } - - /**+ - * Like the old updateEntity(), except more generic. - */ - public void update() { - this.spawnerLogic.updateSpawner(); - } - - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. */ public Packet getDescriptionPacket() { NBTTagCompound nbttagcompound = new NBTTagCompound(); @@ -82,15 +71,28 @@ public class TileEntityMobSpawner extends TileEntity implements ITickable { return new S35PacketUpdateTileEntity(this.pos, 1, nbttagcompound); } + public MobSpawnerBaseLogic getSpawnerBaseLogic() { + return this.spawnerLogic; + } + + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + this.spawnerLogic.readFromNBT(nbttagcompound); + } + public boolean receiveClientEvent(int i, int j) { return this.spawnerLogic.setDelayToMin(i) ? true : super.receiveClientEvent(i, j); } - public boolean func_183000_F() { - return true; + /** + * + Like the old updateEntity(), except more generic. + */ + public void update() { + this.spawnerLogic.updateSpawner(); } - public MobSpawnerBaseLogic getSpawnerBaseLogic() { - return this.spawnerLogic; + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + this.spawnerLogic.writeToNBT(nbttagcompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityNote.java b/src/game/java/net/minecraft/tileentity/TileEntityNote.java index 0e172970..84a303f5 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityNote.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityNote.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,9 +34,12 @@ public class TileEntityNote extends TileEntity { public byte note; public boolean previousRedstoneState; - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setByte("note", this.note); + /** + * + change pitch by -> (currentPitch + 1) % 25 + */ + public void changePitch() { + this.note = (byte) ((this.note + 1) % 25); + this.markDirty(); } public void readFromNBT(NBTTagCompound nbttagcompound) { @@ -42,14 +48,6 @@ public class TileEntityNote extends TileEntity { this.note = (byte) MathHelper.clamp_int(this.note, 0, 24); } - /**+ - * change pitch by -> (currentPitch + 1) % 25 - */ - public void changePitch() { - this.note = (byte) ((this.note + 1) % 25); - this.markDirty(); - } - public void triggerNote(World worldIn, BlockPos parBlockPos) { if (worldIn.getBlockState(parBlockPos.up()).getBlock().getMaterial() == Material.air) { Material material = worldIn.getBlockState(parBlockPos.down()).getBlock().getMaterial(); @@ -73,4 +71,9 @@ public class TileEntityNote extends TileEntity { worldIn.addBlockEvent(parBlockPos, Blocks.noteblock, b0, this.note); } } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setByte("note", this.note); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntityPiston.java b/src/game/java/net/minecraft/tileentity/TileEntityPiston.java index b09beb7e..83ee7681 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntityPiston.java +++ b/src/game/java/net/minecraft/tileentity/TileEntityPiston.java @@ -13,22 +13,25 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.EnumFacing; import net.minecraft.util.ITickable; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,42 +56,30 @@ public class TileEntityPiston extends TileEntity implements ITickable { this.shouldHeadBeRendered = shouldHeadBeRenderedIn; } - public IBlockState getPistonState() { - return this.pistonState; + /** + * + removes a piston's tile entity (and if the piston is moving, stops it) + */ + public void clearPistonTileEntity() { + if (this.lastProgress < 1.0F && this.worldObj != null) { + this.lastProgress = this.progress = 1.0F; + this.worldObj.removeTileEntity(this.pos); + this.invalidate(); + if (this.worldObj.getBlockState(this.pos).getBlock() == Blocks.piston_extension) { + this.worldObj.setBlockState(this.pos, this.pistonState, 3); + this.worldObj.notifyBlockOfStateChange(this.pos, this.pistonState.getBlock()); + } + } + } public int getBlockMetadata() { return 0; } - /**+ - * Returns true if a piston is extending - */ - public boolean isExtending() { - return this.extending; - } - public EnumFacing getFacing() { return this.pistonFacing; } - public boolean shouldPistonHeadBeRendered() { - return this.shouldHeadBeRendered; - } - - /**+ - * Get interpolated progress value (between lastProgress and - * progress) given the fractional time between ticks as an - * argument - */ - public float getProgress(float ticks) { - if (ticks > 1.0F) { - ticks = 1.0F; - } - - return this.lastProgress + (this.progress - this.lastProgress) * ticks; - } - public float getOffsetX(float ticks) { return this.extending ? (this.getProgress(ticks) - 1.0F) * (float) this.pistonFacing.getFrontOffsetX() : (1.0F - this.getProgress(ticks)) * (float) this.pistonFacing.getFrontOffsetX(); @@ -104,6 +95,29 @@ public class TileEntityPiston extends TileEntity implements ITickable { : (1.0F - this.getProgress(ticks)) * (float) this.pistonFacing.getFrontOffsetZ(); } + public IBlockState getPistonState() { + return this.pistonState; + } + + /** + * + Get interpolated progress value (between lastProgress and progress) given + * the fractional time between ticks as an argument + */ + public float getProgress(float ticks) { + if (ticks > 1.0F) { + ticks = 1.0F; + } + + return this.lastProgress + (this.progress - this.lastProgress) * ticks; + } + + /** + * + Returns true if a piston is extending + */ + public boolean isExtending() { + return this.extending; + } + private void launchWithSlimeBlock(float parFloat1, float parFloat2) { if (this.extending) { parFloat1 = 1.0F - parFloat1; @@ -144,25 +158,21 @@ public class TileEntityPiston extends TileEntity implements ITickable { } - /**+ - * removes a piston's tile entity (and if the piston is moving, - * stops it) - */ - public void clearPistonTileEntity() { - if (this.lastProgress < 1.0F && this.worldObj != null) { - this.lastProgress = this.progress = 1.0F; - this.worldObj.removeTileEntity(this.pos); - this.invalidate(); - if (this.worldObj.getBlockState(this.pos).getBlock() == Blocks.piston_extension) { - this.worldObj.setBlockState(this.pos, this.pistonState, 3); - this.worldObj.notifyBlockOfStateChange(this.pos, this.pistonState.getBlock()); - } - } - + public void readFromNBT(NBTTagCompound nbttagcompound) { + super.readFromNBT(nbttagcompound); + this.pistonState = Block.getBlockById(nbttagcompound.getInteger("blockId")) + .getStateFromMeta(nbttagcompound.getInteger("blockData")); + this.pistonFacing = EnumFacing.getFront(nbttagcompound.getInteger("facing")); + this.lastProgress = this.progress = nbttagcompound.getFloat("progress"); + this.extending = nbttagcompound.getBoolean("extending"); } - /**+ - * Like the old updateEntity(), except more generic. + public boolean shouldPistonHeadBeRendered() { + return this.shouldHeadBeRendered; + } + + /** + * + Like the old updateEntity(), except more generic. */ public void update() { this.lastProgress = this.progress; @@ -188,15 +198,6 @@ public class TileEntityPiston extends TileEntity implements ITickable { } } - public void readFromNBT(NBTTagCompound nbttagcompound) { - super.readFromNBT(nbttagcompound); - this.pistonState = Block.getBlockById(nbttagcompound.getInteger("blockId")) - .getStateFromMeta(nbttagcompound.getInteger("blockData")); - this.pistonFacing = EnumFacing.getFront(nbttagcompound.getInteger("facing")); - this.lastProgress = this.progress = nbttagcompound.getFloat("progress"); - this.extending = nbttagcompound.getBoolean("extending"); - } - public void writeToNBT(NBTTagCompound nbttagcompound) { super.writeToNBT(nbttagcompound); nbttagcompound.setInteger("blockId", Block.getIdFromBlock(this.pistonState.getBlock())); diff --git a/src/game/java/net/minecraft/tileentity/TileEntitySign.java b/src/game/java/net/minecraft/tileentity/TileEntitySign.java index b7bcc147..4d9fe38b 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntitySign.java +++ b/src/game/java/net/minecraft/tileentity/TileEntitySign.java @@ -1,5 +1,7 @@ package net.minecraft.tileentity; +import org.json.JSONException; + import net.lax1dude.eaglercraft.v1_8.profanity_filter.ProfanityFilter; import net.minecraft.client.Minecraft; import net.minecraft.command.CommandException; @@ -20,24 +22,25 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.Vec3; import net.minecraft.world.World; -import org.json.JSONException; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,25 +49,98 @@ public class TileEntitySign extends TileEntity { public final IChatComponent[] signText = new IChatComponent[] { new ChatComponentText(""), new ChatComponentText(""), new ChatComponentText(""), new ChatComponentText("") }; protected IChatComponent[] signTextProfanityFilter = null; - /**+ - * The index of the line currently being edited. Only used on - * client side, but defined on both. Note this is only really - * used when the > < are going to be visible. + /** + * + The index of the line currently being edited. Only used on client side, but + * defined on both. Note this is only really used when the > < are going to be + * visible. */ public int lineBeingEdited = -1; private boolean isEditable = true; private EntityPlayer player; private final CommandResultStats stats = new CommandResultStats(); - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); + public void clearProfanityFilterCache() { + signTextProfanityFilter = null; + } - for (int i = 0; i < 4; ++i) { - String s = IChatComponent.Serializer.componentToJson(this.signText[i]); - nbttagcompound.setString("Text" + (i + 1), s); + public boolean executeCommand(final EntityPlayer playerIn) { + ICommandSender icommandsender = new ICommandSender() { + public void addChatMessage(IChatComponent var1) { + } + + public boolean canCommandSenderUseCommand(int j, String var2) { + return j <= 2; + } + + public Entity getCommandSenderEntity() { + return playerIn; + } + + public IChatComponent getDisplayName() { + return playerIn.getDisplayName(); + } + + public World getEntityWorld() { + return playerIn.getEntityWorld(); + } + + public String getName() { + return playerIn.getName(); + } + + public BlockPos getPosition() { + return TileEntitySign.this.pos; + } + + public Vec3 getPositionVector() { + return new Vec3((double) TileEntitySign.this.pos.getX() + 0.5D, + (double) TileEntitySign.this.pos.getY() + 0.5D, (double) TileEntitySign.this.pos.getZ() + 0.5D); + } + + public boolean sendCommandFeedback() { + return false; + } + + public void setCommandStat(CommandResultStats.Type commandresultstats$type, int j) { + TileEntitySign.this.stats.func_179672_a(this, commandresultstats$type, j); + } + }; + + for (int i = 0; i < this.signText.length; ++i) { + ChatStyle chatstyle = this.signText[i] == null ? null : this.signText[i].getChatStyle(); + if (chatstyle != null && chatstyle.getChatClickEvent() != null) { + ClickEvent clickevent = chatstyle.getChatClickEvent(); + if (clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) { + MinecraftServer.getServer().getCommandManager().executeCommand(icommandsender, + clickevent.getValue()); + } + } } - this.stats.writeStatsToNBT(nbttagcompound); + return true; + } + + public boolean func_183000_F() { + return true; + } + + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + IChatComponent[] aichatcomponent = new IChatComponent[4]; + System.arraycopy(this.signText, 0, aichatcomponent, 0, 4); + return new S33PacketUpdateSign(this.worldObj, this.pos, aichatcomponent); + } + + public boolean getIsEditable() { + return this.isEditable; + } + + public EntityPlayer getPlayer() { + return this.player; } public IChatComponent[] getSignTextProfanityFilter() { @@ -82,27 +158,35 @@ public class TileEntitySign extends TileEntity { } } - public void clearProfanityFilterCache() { - signTextProfanityFilter = null; + public CommandResultStats getStats() { + return this.stats; } public void readFromNBT(NBTTagCompound nbttagcompound) { this.isEditable = false; super.readFromNBT(nbttagcompound); ICommandSender icommandsender = new ICommandSender() { - public String getName() { - return "Sign"; + public void addChatMessage(IChatComponent var1) { + } + + public boolean canCommandSenderUseCommand(int var1, String var2) { + return true; + } + + public Entity getCommandSenderEntity() { + return null; } public IChatComponent getDisplayName() { return new ChatComponentText(this.getName()); } - public void addChatMessage(IChatComponent var1) { + public World getEntityWorld() { + return TileEntitySign.this.worldObj; } - public boolean canCommandSenderUseCommand(int var1, String var2) { - return true; + public String getName() { + return "Sign"; } public BlockPos getPosition() { @@ -114,14 +198,6 @@ public class TileEntitySign extends TileEntity { (double) TileEntitySign.this.pos.getY() + 0.5D, (double) TileEntitySign.this.pos.getZ() + 0.5D); } - public World getEntityWorld() { - return TileEntitySign.this.worldObj; - } - - public Entity getCommandSenderEntity() { - return null; - } - public boolean sendCommandFeedback() { return false; } @@ -150,28 +226,8 @@ public class TileEntitySign extends TileEntity { this.stats.readStatsFromNBT(nbttagcompound); } - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - IChatComponent[] aichatcomponent = new IChatComponent[4]; - System.arraycopy(this.signText, 0, aichatcomponent, 0, 4); - return new S33PacketUpdateSign(this.worldObj, this.pos, aichatcomponent); - } - - public boolean func_183000_F() { - return true; - } - - public boolean getIsEditable() { - return this.isEditable; - } - - /**+ - * Sets the sign's isEditable flag to the specified parameter. + /** + * + Sets the sign's isEditable flag to the specified parameter. */ public void setEditable(boolean isEditableIn) { this.isEditable = isEditableIn; @@ -185,68 +241,14 @@ public class TileEntitySign extends TileEntity { this.player = playerIn; } - public EntityPlayer getPlayer() { - return this.player; - } + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); - public boolean executeCommand(final EntityPlayer playerIn) { - ICommandSender icommandsender = new ICommandSender() { - public String getName() { - return playerIn.getName(); - } - - public IChatComponent getDisplayName() { - return playerIn.getDisplayName(); - } - - public void addChatMessage(IChatComponent var1) { - } - - public boolean canCommandSenderUseCommand(int j, String var2) { - return j <= 2; - } - - public BlockPos getPosition() { - return TileEntitySign.this.pos; - } - - public Vec3 getPositionVector() { - return new Vec3((double) TileEntitySign.this.pos.getX() + 0.5D, - (double) TileEntitySign.this.pos.getY() + 0.5D, (double) TileEntitySign.this.pos.getZ() + 0.5D); - } - - public World getEntityWorld() { - return playerIn.getEntityWorld(); - } - - public Entity getCommandSenderEntity() { - return playerIn; - } - - public boolean sendCommandFeedback() { - return false; - } - - public void setCommandStat(CommandResultStats.Type commandresultstats$type, int j) { - TileEntitySign.this.stats.func_179672_a(this, commandresultstats$type, j); - } - }; - - for (int i = 0; i < this.signText.length; ++i) { - ChatStyle chatstyle = this.signText[i] == null ? null : this.signText[i].getChatStyle(); - if (chatstyle != null && chatstyle.getChatClickEvent() != null) { - ClickEvent clickevent = chatstyle.getChatClickEvent(); - if (clickevent.getAction() == ClickEvent.Action.RUN_COMMAND) { - MinecraftServer.getServer().getCommandManager().executeCommand(icommandsender, - clickevent.getValue()); - } - } + for (int i = 0; i < 4; ++i) { + String s = IChatComponent.Serializer.componentToJson(this.signText[i]); + nbttagcompound.setString("Text" + (i + 1), s); } - return true; - } - - public CommandResultStats getStats() { - return this.stats; + this.stats.writeStatsToNBT(nbttagcompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/tileentity/TileEntitySkull.java b/src/game/java/net/minecraft/tileentity/TileEntitySkull.java index 620d486a..9a1f3086 100644 --- a/src/game/java/net/minecraft/tileentity/TileEntitySkull.java +++ b/src/game/java/net/minecraft/tileentity/TileEntitySkull.java @@ -1,7 +1,6 @@ package net.minecraft.tileentity; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTUtil; @@ -9,41 +8,60 @@ import net.minecraft.network.Packet; import net.minecraft.network.play.server.S35PacketUpdateTileEntity; import net.minecraft.util.StringUtils; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TileEntitySkull extends TileEntity { + public static GameProfile updateGameprofile(GameProfile input) { + return input; + } + private int skullType; private int skullRotation; + private GameProfile playerProfile = null; - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setByte("SkullType", (byte) (this.skullType & 255)); - nbttagcompound.setByte("Rot", (byte) (this.skullRotation & 255)); - if (this.playerProfile != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - NBTUtil.writeGameProfile(nbttagcompound1, this.playerProfile); - nbttagcompound.setTag("Owner", nbttagcompound1); - } + /** + * + Allows for a specialized description packet to be created. This is often + * used to sync tile entity data from the server to the client easily. For + * example this is used by signs to synchronise the text to be displayed. + */ + public Packet getDescriptionPacket() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.writeToNBT(nbttagcompound); + return new S35PacketUpdateTileEntity(this.pos, 4, nbttagcompound); + } + public GameProfile getPlayerProfile() { + return this.playerProfile; + } + + public int getSkullRotation() { + return this.skullRotation; + } + + public int getSkullType() { + return this.skullType; } public void readFromNBT(NBTTagCompound nbttagcompound) { @@ -64,20 +82,14 @@ public class TileEntitySkull extends TileEntity { } - public GameProfile getPlayerProfile() { - return this.playerProfile; + public void setPlayerProfile(GameProfile playerProfile) { + this.skullType = 3; + this.playerProfile = playerProfile; + this.updatePlayerProfile(); } - /**+ - * Allows for a specialized description packet to be created. - * This is often used to sync tile entity data from the server - * to the client easily. For example this is used by signs to - * synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.writeToNBT(nbttagcompound); - return new S35PacketUpdateTileEntity(this.pos, 4, nbttagcompound); + public void setSkullRotation(int rotation) { + this.skullRotation = rotation; } public void setType(int type) { @@ -85,30 +97,20 @@ public class TileEntitySkull extends TileEntity { this.playerProfile = null; } - public void setPlayerProfile(GameProfile playerProfile) { - this.skullType = 3; - this.playerProfile = playerProfile; - this.updatePlayerProfile(); - } - private void updatePlayerProfile() { this.playerProfile = updateGameprofile(this.playerProfile); this.markDirty(); } - public static GameProfile updateGameprofile(GameProfile input) { - return input; - } + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setByte("SkullType", (byte) (this.skullType & 255)); + nbttagcompound.setByte("Rot", (byte) (this.skullRotation & 255)); + if (this.playerProfile != null) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + NBTUtil.writeGameProfile(nbttagcompound1, this.playerProfile); + nbttagcompound.setTag("Owner", nbttagcompound1); + } - public int getSkullType() { - return this.skullType; - } - - public int getSkullRotation() { - return this.skullRotation; - } - - public void setSkullRotation(int rotation) { - this.skullRotation = rotation; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/AxisAlignedBB.java b/src/game/java/net/minecraft/util/AxisAlignedBB.java index 66e902cf..51a05333 100644 --- a/src/game/java/net/minecraft/util/AxisAlignedBB.java +++ b/src/game/java/net/minecraft/util/AxisAlignedBB.java @@ -1,41 +1,49 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class AxisAlignedBB { + /** + * + returns an AABB with corners x1, y1, z1 and x2, y2, z2 + */ + public static AxisAlignedBB fromBounds(double x1, double y1, double z1, double x2, double y2, double z2) { + double d0 = Math.min(x1, x2); + double d1 = Math.min(y1, y2); + double d2 = Math.min(z1, z2); + double d3 = Math.max(x1, x2); + double d4 = Math.max(y1, y2); + double d5 = Math.max(z1, z2); + return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); + } + public final double minX; public final double minY; public final double minZ; public final double maxX; public final double maxY; - public final double maxZ; - public AxisAlignedBB(double x1, double y1, double z1, double x2, double y2, double z2) { - this.minX = Math.min(x1, x2); - this.minY = Math.min(y1, y2); - this.minZ = Math.min(z1, z2); - this.maxX = Math.max(x1, x2); - this.maxY = Math.max(y1, y2); - this.maxZ = Math.max(z1, z2); - } + public final double maxZ; public AxisAlignedBB(BlockPos pos1, BlockPos pos2) { this.minX = (double) pos1.getX(); @@ -46,9 +54,18 @@ public class AxisAlignedBB { this.maxZ = (double) pos2.getZ(); } - /**+ - * Adds the coordinates to the bounding box extending it if the - * point lies outside the current ranges. Args: x, y, z + public AxisAlignedBB(double x1, double y1, double z1, double x2, double y2, double z2) { + this.minX = Math.min(x1, x2); + this.minY = Math.min(y1, y2); + this.minZ = Math.min(z1, z2); + this.maxX = Math.max(x1, x2); + this.maxY = Math.max(y1, y2); + this.maxZ = Math.max(z1, z2); + } + + /** + * + Adds the coordinates to the bounding box extending it if the point lies + * outside the current ranges. Args: x, y, z */ public AxisAlignedBB addCoord(double x, double y, double z) { double d0 = this.minX; @@ -78,178 +95,6 @@ public class AxisAlignedBB { return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); } - /**+ - * Returns a bounding box expanded by the specified vector (if - * negative numbers are given it will shrink). Args: x, y, z - */ - public AxisAlignedBB expand(double x, double y, double z) { - double d0 = this.minX - x; - double d1 = this.minY - y; - double d2 = this.minZ - z; - double d3 = this.maxX + x; - double d4 = this.maxY + y; - double d5 = this.maxZ + z; - return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); - } - - public AxisAlignedBB union(AxisAlignedBB other) { - double d0 = Math.min(this.minX, other.minX); - double d1 = Math.min(this.minY, other.minY); - double d2 = Math.min(this.minZ, other.minZ); - double d3 = Math.max(this.maxX, other.maxX); - double d4 = Math.max(this.maxY, other.maxY); - double d5 = Math.max(this.maxZ, other.maxZ); - return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); - } - - /**+ - * returns an AABB with corners x1, y1, z1 and x2, y2, z2 - */ - public static AxisAlignedBB fromBounds(double x1, double y1, double z1, double x2, double y2, double z2) { - double d0 = Math.min(x1, x2); - double d1 = Math.min(y1, y2); - double d2 = Math.min(z1, z2); - double d3 = Math.max(x1, x2); - double d4 = Math.max(y1, y2); - double d5 = Math.max(z1, z2); - return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); - } - - /**+ - * Offsets the current bounding box by the specified - * coordinates. Args: x, y, z - */ - public AxisAlignedBB offset(double x, double y, double z) { - return new AxisAlignedBB(this.minX + x, this.minY + y, this.minZ + z, this.maxX + x, this.maxY + y, - this.maxZ + z); - } - - /**+ - * if instance and the argument bounding boxes overlap in the Y - * and Z dimensions, calculate the offset between them in the X - * dimension. return var2 if the bounding boxes do not overlap - * or if var2 is closer to 0 then the calculated offset. - * Otherwise return the calculated offset. - */ - public double calculateXOffset(AxisAlignedBB other, double offsetX) { - if (other.maxY > this.minY && other.minY < this.maxY && other.maxZ > this.minZ && other.minZ < this.maxZ) { - if (offsetX > 0.0D && other.maxX <= this.minX) { - double d1 = this.minX - other.maxX; - if (d1 < offsetX) { - offsetX = d1; - } - } else if (offsetX < 0.0D && other.minX >= this.maxX) { - double d0 = this.maxX - other.minX; - if (d0 > offsetX) { - offsetX = d0; - } - } - - return offsetX; - } else { - return offsetX; - } - } - - /**+ - * if instance and the argument bounding boxes overlap in the X - * and Z dimensions, calculate the offset between them in the Y - * dimension. return var2 if the bounding boxes do not overlap - * or if var2 is closer to 0 then the calculated offset. - * Otherwise return the calculated offset. - */ - public double calculateYOffset(AxisAlignedBB other, double offsetY) { - if (other.maxX > this.minX && other.minX < this.maxX && other.maxZ > this.minZ && other.minZ < this.maxZ) { - if (offsetY > 0.0D && other.maxY <= this.minY) { - double d1 = this.minY - other.maxY; - if (d1 < offsetY) { - offsetY = d1; - } - } else if (offsetY < 0.0D && other.minY >= this.maxY) { - double d0 = this.maxY - other.minY; - if (d0 > offsetY) { - offsetY = d0; - } - } - - return offsetY; - } else { - return offsetY; - } - } - - /**+ - * if instance and the argument bounding boxes overlap in the Y - * and X dimensions, calculate the offset between them in the Z - * dimension. return var2 if the bounding boxes do not overlap - * or if var2 is closer to 0 then the calculated offset. - * Otherwise return the calculated offset. - */ - public double calculateZOffset(AxisAlignedBB other, double offsetZ) { - if (other.maxX > this.minX && other.minX < this.maxX && other.maxY > this.minY && other.minY < this.maxY) { - if (offsetZ > 0.0D && other.maxZ <= this.minZ) { - double d1 = this.minZ - other.maxZ; - if (d1 < offsetZ) { - offsetZ = d1; - } - } else if (offsetZ < 0.0D && other.minZ >= this.maxZ) { - double d0 = this.maxZ - other.minZ; - if (d0 > offsetZ) { - offsetZ = d0; - } - } - - return offsetZ; - } else { - return offsetZ; - } - } - - /**+ - * Returns whether the given bounding box intersects with this - * one. Args: axisAlignedBB - */ - public boolean intersectsWith(AxisAlignedBB other) { - return other.maxX > this.minX && other.minX < this.maxX - ? (other.maxY > this.minY && other.minY < this.maxY ? other.maxZ > this.minZ && other.minZ < this.maxZ - : false) - : false; - } - - /**+ - * Returns if the supplied Vec3D is completely inside the - * bounding box - */ - public boolean isVecInside(Vec3 vec) { - return vec.xCoord > this.minX && vec.xCoord < this.maxX - ? (vec.yCoord > this.minY && vec.yCoord < this.maxY ? vec.zCoord > this.minZ && vec.zCoord < this.maxZ - : false) - : false; - } - - /**+ - * Returns the average length of the edges of the bounding box. - */ - public double getAverageEdgeLength() { - double d0 = this.maxX - this.minX; - double d1 = this.maxY - this.minY; - double d2 = this.maxZ - this.minZ; - return (d0 + d1 + d2) / 3.0D; - } - - /**+ - * Returns a bounding box that is inset by the specified amounts - */ - public AxisAlignedBB contract(double x, double y, double z) { - double d0 = this.minX + x; - double d1 = this.minY + y; - double d2 = this.minZ + z; - double d3 = this.maxX - x; - double d4 = this.maxY - y; - double d5 = this.maxZ - z; - return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); - } - public MovingObjectPosition calculateIntercept(Vec3 vecA, Vec3 vecB) { Vec3 vec3 = vecA.getIntermediateWithXValue(vecB, this.minX); Vec3 vec31 = vecA.getIntermediateWithXValue(vecB, this.maxX); @@ -328,29 +173,150 @@ public class AxisAlignedBB { } } - /**+ - * Checks if the specified vector is within the YZ dimensions of - * the bounding box. Args: Vec3D + /** + * + if instance and the argument bounding boxes overlap in the Y and Z + * dimensions, calculate the offset between them in the X dimension. return var2 + * if the bounding boxes do not overlap or if var2 is closer to 0 then the + * calculated offset. Otherwise return the calculated offset. */ - private boolean isVecInYZ(Vec3 vec) { - return vec == null ? false - : vec.yCoord >= this.minY && vec.yCoord <= this.maxY && vec.zCoord >= this.minZ - && vec.zCoord <= this.maxZ; + public double calculateXOffset(AxisAlignedBB other, double offsetX) { + if (other.maxY > this.minY && other.minY < this.maxY && other.maxZ > this.minZ && other.minZ < this.maxZ) { + if (offsetX > 0.0D && other.maxX <= this.minX) { + double d1 = this.minX - other.maxX; + if (d1 < offsetX) { + offsetX = d1; + } + } else if (offsetX < 0.0D && other.minX >= this.maxX) { + double d0 = this.maxX - other.minX; + if (d0 > offsetX) { + offsetX = d0; + } + } + + return offsetX; + } else { + return offsetX; + } } - /**+ - * Checks if the specified vector is within the XZ dimensions of - * the bounding box. Args: Vec3D + /** + * + if instance and the argument bounding boxes overlap in the X and Z + * dimensions, calculate the offset between them in the Y dimension. return var2 + * if the bounding boxes do not overlap or if var2 is closer to 0 then the + * calculated offset. Otherwise return the calculated offset. */ - private boolean isVecInXZ(Vec3 vec) { - return vec == null ? false - : vec.xCoord >= this.minX && vec.xCoord <= this.maxX && vec.zCoord >= this.minZ - && vec.zCoord <= this.maxZ; + public double calculateYOffset(AxisAlignedBB other, double offsetY) { + if (other.maxX > this.minX && other.minX < this.maxX && other.maxZ > this.minZ && other.minZ < this.maxZ) { + if (offsetY > 0.0D && other.maxY <= this.minY) { + double d1 = this.minY - other.maxY; + if (d1 < offsetY) { + offsetY = d1; + } + } else if (offsetY < 0.0D && other.minY >= this.maxY) { + double d0 = this.maxY - other.minY; + if (d0 > offsetY) { + offsetY = d0; + } + } + + return offsetY; + } else { + return offsetY; + } } - /**+ - * Checks if the specified vector is within the XY dimensions of - * the bounding box. Args: Vec3D + /** + * + if instance and the argument bounding boxes overlap in the Y and X + * dimensions, calculate the offset between them in the Z dimension. return var2 + * if the bounding boxes do not overlap or if var2 is closer to 0 then the + * calculated offset. Otherwise return the calculated offset. + */ + public double calculateZOffset(AxisAlignedBB other, double offsetZ) { + if (other.maxX > this.minX && other.minX < this.maxX && other.maxY > this.minY && other.minY < this.maxY) { + if (offsetZ > 0.0D && other.maxZ <= this.minZ) { + double d1 = this.minZ - other.maxZ; + if (d1 < offsetZ) { + offsetZ = d1; + } + } else if (offsetZ < 0.0D && other.minZ >= this.maxZ) { + double d0 = this.maxZ - other.minZ; + if (d0 > offsetZ) { + offsetZ = d0; + } + } + + return offsetZ; + } else { + return offsetZ; + } + } + + /** + * + Returns a bounding box that is inset by the specified amounts + */ + public AxisAlignedBB contract(double x, double y, double z) { + double d0 = this.minX + x; + double d1 = this.minY + y; + double d2 = this.minZ + z; + double d3 = this.maxX - x; + double d4 = this.maxY - y; + double d5 = this.maxZ - z; + return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); + } + + /** + * + Returns a bounding box expanded by the specified vector (if negative + * numbers are given it will shrink). Args: x, y, z + */ + public AxisAlignedBB expand(double x, double y, double z) { + double d0 = this.minX - x; + double d1 = this.minY - y; + double d2 = this.minZ - z; + double d3 = this.maxX + x; + double d4 = this.maxY + y; + double d5 = this.maxZ + z; + return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); + } + + public boolean func_181656_b() { + return Double.isNaN(this.minX) || Double.isNaN(this.minY) || Double.isNaN(this.minZ) || Double.isNaN(this.maxX) + || Double.isNaN(this.maxY) || Double.isNaN(this.maxZ); + } + + /** + * + Returns the average length of the edges of the bounding box. + */ + public double getAverageEdgeLength() { + double d0 = this.maxX - this.minX; + double d1 = this.maxY - this.minY; + double d2 = this.maxZ - this.minZ; + return (d0 + d1 + d2) / 3.0D; + } + + /** + * + Returns whether the given bounding box intersects with this one. Args: + * axisAlignedBB + */ + public boolean intersectsWith(AxisAlignedBB other) { + return other.maxX > this.minX && other.minX < this.maxX + ? (other.maxY > this.minY && other.minY < this.maxY ? other.maxZ > this.minZ && other.minZ < this.maxZ + : false) + : false; + } + + /** + * + Returns if the supplied Vec3D is completely inside the bounding box + */ + public boolean isVecInside(Vec3 vec) { + return vec.xCoord > this.minX && vec.xCoord < this.maxX + ? (vec.yCoord > this.minY && vec.yCoord < this.maxY ? vec.zCoord > this.minZ && vec.zCoord < this.maxZ + : false) + : false; + } + + /** + * + Checks if the specified vector is within the XY dimensions of the bounding + * box. Args: Vec3D */ private boolean isVecInXY(Vec3 vec) { return vec == null ? false @@ -358,13 +324,47 @@ public class AxisAlignedBB { && vec.yCoord <= this.maxY; } + /** + * + Checks if the specified vector is within the XZ dimensions of the bounding + * box. Args: Vec3D + */ + private boolean isVecInXZ(Vec3 vec) { + return vec == null ? false + : vec.xCoord >= this.minX && vec.xCoord <= this.maxX && vec.zCoord >= this.minZ + && vec.zCoord <= this.maxZ; + } + + /** + * + Checks if the specified vector is within the YZ dimensions of the bounding + * box. Args: Vec3D + */ + private boolean isVecInYZ(Vec3 vec) { + return vec == null ? false + : vec.yCoord >= this.minY && vec.yCoord <= this.maxY && vec.zCoord >= this.minZ + && vec.zCoord <= this.maxZ; + } + + /** + * + Offsets the current bounding box by the specified coordinates. Args: x, y, + * z + */ + public AxisAlignedBB offset(double x, double y, double z) { + return new AxisAlignedBB(this.minX + x, this.minY + y, this.minZ + z, this.maxX + x, this.maxY + y, + this.maxZ + z); + } + public String toString() { return "box[" + this.minX + ", " + this.minY + ", " + this.minZ + " -> " + this.maxX + ", " + this.maxY + ", " + this.maxZ + "]"; } - public boolean func_181656_b() { - return Double.isNaN(this.minX) || Double.isNaN(this.minY) || Double.isNaN(this.minZ) || Double.isNaN(this.maxX) - || Double.isNaN(this.maxY) || Double.isNaN(this.maxZ); + public AxisAlignedBB union(AxisAlignedBB other) { + double d0 = Math.min(this.minX, other.minX); + double d1 = Math.min(this.minY, other.minY); + double d2 = Math.min(this.minZ, other.minZ); + double d3 = Math.max(this.maxX, other.maxX); + double d4 = Math.max(this.maxY, other.maxY); + double d5 = Math.max(this.maxZ, other.maxZ); + return new AxisAlignedBB(d0, d1, d2, d3, d4, d5); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/BlockPos.java b/src/game/java/net/minecraft/util/BlockPos.java index 1aff9c15..943ba9cd 100644 --- a/src/game/java/net/minecraft/util/BlockPos.java +++ b/src/game/java/net/minecraft/util/BlockPos.java @@ -6,29 +6,62 @@ import com.google.common.collect.AbstractIterator; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BlockPos extends Vec3i { - /**+ - * The BlockPos with all coordinates 0 + public static final class MutableBlockPos extends BlockPos { + + public MutableBlockPos() { + this(0, 0, 0); + } + + public MutableBlockPos(int x_, int y_, int z_) { + super(x_, y_, z_); + } + + public BlockPos.MutableBlockPos func_181079_c(int parInt1, int parInt2, int parInt3) { + this.x = parInt1; + this.y = parInt2; + this.z = parInt3; + return this; + } + + public int getX() { + return this.x; + } + + public int getY() { + return this.y; + } + + public int getZ() { + return this.z; + } + } + + /** + * + The BlockPos with all coordinates 0 */ public static final BlockPos ORIGIN = new BlockPos(0, 0, 0); private static final int NUM_X_BITS = 1 + MathHelper.calculateLogBaseTwo(MathHelper.roundUpToPowerOfTwo(30000000)); @@ -38,274 +71,11 @@ public class BlockPos extends Vec3i { private static final int X_SHIFT = Y_SHIFT + NUM_Y_BITS; private static final long X_MASK = (1L << NUM_X_BITS) - 1L; private static final long Y_MASK = (1L << NUM_Y_BITS) - 1L; + private static final long Z_MASK = (1L << NUM_Z_BITS) - 1L; - public BlockPos(int x, int y, int z) { - super(x, y, z); - } - - public BlockPos(double x, double y, double z) { - super(x, y, z); - } - - public BlockPos(Entity source) { - this(source.posX, source.posY, source.posZ); - } - - public BlockPos(Vec3 source) { - this(source.xCoord, source.yCoord, source.zCoord); - } - - public BlockPos(Vec3i source) { - this(source.getX(), source.getY(), source.getZ()); - } - - /**+ - * Add the given coordinates to the coordinates of this BlockPos - */ - public BlockPos add(double x, double y, double z) { - return x == 0.0D && y == 0.0D && z == 0.0D ? this - : new BlockPos((double) this.getX() + x, (double) this.getY() + y, (double) this.getZ() + z); - } - - /**+ - * Add the given coordinates to the coordinates of this BlockPos - */ - public BlockPos add(int x, int y, int z) { - return x == 0 && y == 0 && z == 0 ? this : new BlockPos(this.getX() + x, this.getY() + y, this.getZ() + z); - } - - /**+ - * Add the given coordinates to the coordinates of this BlockPos - */ - public BlockPos add(Vec3i vec) { - return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0 ? this - : new BlockPos(this.getX() + vec.getX(), this.getY() + vec.getY(), this.getZ() + vec.getZ()); - } - - /**+ - * Subtract the given Vector from this BlockPos - */ - public BlockPos subtract(Vec3i vec) { - return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0 ? this - : new BlockPos(this.getX() - vec.getX(), this.getY() - vec.getY(), this.getZ() - vec.getZ()); - } - - /**+ - * Offset this BlockPos 1 block up - */ - public BlockPos up() { - return this.up(1); - } - /** - * eagler - */ - /**+ - * Offset this BlockPos 1 block up - */ - public BlockPos up(BlockPos dst) { - dst.x = x; - dst.y = y + 1; - dst.z = z; - return dst; - } - - /**+ - * Offset this BlockPos 1 block up - */ - public BlockPos up(int n) { - return this.offset(EnumFacing.UP, n); - } - - /**+ - * Offset this BlockPos 1 block down - */ - public BlockPos down() { - return this.down(1); - } - - /** - * eagler - */ - /**+ - * Offset this BlockPos 1 block down - */ - public BlockPos down(BlockPos dst) { - dst.x = x; - dst.y = y - 1; - dst.z = z; - return dst; - } - - /**+ - * Offset this BlockPos 1 block down - */ - public BlockPos down(int n) { - return this.offset(EnumFacing.DOWN, n); - } - - /**+ - * Offset this BlockPos 1 block in northern direction - */ - public BlockPos north() { - return this.north(1); - } - - /** - * eagler - */ - /**+ - * Offset this BlockPos 1 block in northern direction - */ - public BlockPos north(BlockPos dst) { - dst.x = x; - dst.y = y; - dst.z = z - 1; - return dst; - } - - /**+ - * Offset this BlockPos 1 block in northern direction - */ - public BlockPos north(int n) { - return this.offset(EnumFacing.NORTH, n); - } - - /**+ - * Offset this BlockPos 1 block in southern direction - */ - public BlockPos south() { - return this.south(1); - } - - /** - * eagler - */ - /**+ - * Offset this BlockPos 1 block in southern direction - */ - public BlockPos south(BlockPos dst) { - dst.x = x; - dst.y = y; - dst.z = z + 1; - return dst; - } - - /**+ - * Offset this BlockPos 1 block in southern direction - */ - public BlockPos south(int n) { - return this.offset(EnumFacing.SOUTH, n); - } - - /**+ - * Offset this BlockPos 1 block in western direction - */ - public BlockPos west() { - return this.west(1); - } - - /**+ - * Offset this BlockPos 1 block in western direction - */ - public BlockPos west(int n) { - return this.offset(EnumFacing.WEST, n); - } - - /** - * eagler - */ - /**+ - * Offset this BlockPos 1 block in western direction - */ - public BlockPos west(BlockPos dst) { - dst.x = x - 1; - dst.y = y; - dst.z = z; - return dst; - } - - /**+ - * Offset this BlockPos 1 block in eastern direction - */ - public BlockPos east() { - return this.east(1); - } - - /**+ - * Offset this BlockPos 1 block in eastern direction - */ - public BlockPos east(int n) { - return this.offset(EnumFacing.EAST, n); - } - - /** - * eagler - */ - /**+ - * Offset this BlockPos 1 block in eastern direction - */ - public BlockPos east(BlockPos dst) { - dst.x = x + 1; - dst.y = y; - dst.z = z; - return dst; - } - - /**+ - * Offset this BlockPos 1 block in the given direction - */ - public BlockPos offset(EnumFacing facing) { - return this.offset(facing, 1); - } - - public BlockPos offsetFaster(EnumFacing facing, BlockPos ret) { - ret.x = this.getX() + facing.getFrontOffsetX(); - ret.y = this.getY() + facing.getFrontOffsetY(); - ret.z = this.getZ() + facing.getFrontOffsetZ(); - return ret; - } - - /** - * only use with a regular "net.minecraft.util.BlockPos"! - */ - public BlockPos offsetEvenFaster(EnumFacing facing, BlockPos ret) { - ret.x = this.x + facing.getFrontOffsetX(); - ret.y = this.y + facing.getFrontOffsetY(); - ret.z = this.z + facing.getFrontOffsetZ(); - return ret; - } - - /**+ - * Offset this BlockPos 1 block in the given direction - */ - public BlockPos offset(EnumFacing facing, int n) { - return n == 0 ? this - : new BlockPos(this.x + facing.getFrontOffsetX() * n, this.y + facing.getFrontOffsetY() * n, - this.z + facing.getFrontOffsetZ() * n); - } - - /**+ - * Calculate the cross product of this and the given Vector - */ - public BlockPos crossProduct(Vec3i vec3i) { - return new BlockPos(this.getY() * vec3i.getZ() - this.getZ() * vec3i.getY(), - this.getZ() * vec3i.getX() - this.getX() * vec3i.getZ(), - this.getX() * vec3i.getY() - this.getY() * vec3i.getX()); - } - - /**+ - * Serialize this BlockPos into a long value - */ - public long toLong() { - return ((long) this.getX() & X_MASK) << X_SHIFT | ((long) this.getY() & Y_MASK) << Y_SHIFT - | ((long) this.getZ() & Z_MASK) << 0; - } - - /**+ - * Create a BlockPos from a serialized long value (created by - * toLong) + * + Create a BlockPos from a serialized long value (created by toLong) */ public static BlockPos fromLong(long serialized) { int i = (int) (serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS); @@ -314,9 +84,9 @@ public class BlockPos extends Vec3i { return new BlockPos(i, j, k); } - /**+ - * Create an Iterable that returns all positions in the box - * specified by the given corners + /** + * + Create an Iterable that returns all positions in the box specified by the + * given corners */ public static Iterable getAllInBox(BlockPos from, BlockPos to) { final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), @@ -358,10 +128,10 @@ public class BlockPos extends Vec3i { }; } - /**+ - * Like getAllInBox but reuses a single MutableBlockPos instead. - * If this method is used, the resulting BlockPos instances can - * only be used inside the iteration loop. + /** + * + Like getAllInBox but reuses a single MutableBlockPos instead. If this + * method is used, the resulting BlockPos instances can only be used inside the + * iteration loop. */ public static Iterable getAllInBoxMutable(BlockPos from, BlockPos to) { final BlockPos blockpos = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), @@ -406,33 +176,266 @@ public class BlockPos extends Vec3i { }; } - public static final class MutableBlockPos extends BlockPos { + public BlockPos(double x, double y, double z) { + super(x, y, z); + } - public MutableBlockPos() { - this(0, 0, 0); - } + public BlockPos(Entity source) { + this(source.posX, source.posY, source.posZ); + } - public MutableBlockPos(int x_, int y_, int z_) { - super(x_, y_, z_); - } + public BlockPos(int x, int y, int z) { + super(x, y, z); + } - public int getX() { - return this.x; - } + public BlockPos(Vec3 source) { + this(source.xCoord, source.yCoord, source.zCoord); + } - public int getY() { - return this.y; - } + public BlockPos(Vec3i source) { + this(source.getX(), source.getY(), source.getZ()); + } - public int getZ() { - return this.z; - } + /** + * + Add the given coordinates to the coordinates of this BlockPos + */ + public BlockPos add(double x, double y, double z) { + return x == 0.0D && y == 0.0D && z == 0.0D ? this + : new BlockPos((double) this.getX() + x, (double) this.getY() + y, (double) this.getZ() + z); + } - public BlockPos.MutableBlockPos func_181079_c(int parInt1, int parInt2, int parInt3) { - this.x = parInt1; - this.y = parInt2; - this.z = parInt3; - return this; - } + /** + * + Add the given coordinates to the coordinates of this BlockPos + */ + public BlockPos add(int x, int y, int z) { + return x == 0 && y == 0 && z == 0 ? this : new BlockPos(this.getX() + x, this.getY() + y, this.getZ() + z); + } + + /** + * + Add the given coordinates to the coordinates of this BlockPos + */ + public BlockPos add(Vec3i vec) { + return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0 ? this + : new BlockPos(this.getX() + vec.getX(), this.getY() + vec.getY(), this.getZ() + vec.getZ()); + } + + /** + * + Calculate the cross product of this and the given Vector + */ + public BlockPos crossProduct(Vec3i vec3i) { + return new BlockPos(this.getY() * vec3i.getZ() - this.getZ() * vec3i.getY(), + this.getZ() * vec3i.getX() - this.getX() * vec3i.getZ(), + this.getX() * vec3i.getY() - this.getY() * vec3i.getX()); + } + + /** + * + Offset this BlockPos 1 block down + */ + public BlockPos down() { + return this.down(1); + } + + /** + * eagler + */ + /** + * + Offset this BlockPos 1 block down + */ + public BlockPos down(BlockPos dst) { + dst.x = x; + dst.y = y - 1; + dst.z = z; + return dst; + } + + /** + * + Offset this BlockPos 1 block down + */ + public BlockPos down(int n) { + return this.offset(EnumFacing.DOWN, n); + } + + /** + * + Offset this BlockPos 1 block in eastern direction + */ + public BlockPos east() { + return this.east(1); + } + + /** + * eagler + */ + /** + * + Offset this BlockPos 1 block in eastern direction + */ + public BlockPos east(BlockPos dst) { + dst.x = x + 1; + dst.y = y; + dst.z = z; + return dst; + } + + /** + * + Offset this BlockPos 1 block in eastern direction + */ + public BlockPos east(int n) { + return this.offset(EnumFacing.EAST, n); + } + + /** + * + Offset this BlockPos 1 block in northern direction + */ + public BlockPos north() { + return this.north(1); + } + + /** + * eagler + */ + /** + * + Offset this BlockPos 1 block in northern direction + */ + public BlockPos north(BlockPos dst) { + dst.x = x; + dst.y = y; + dst.z = z - 1; + return dst; + } + + /** + * + Offset this BlockPos 1 block in northern direction + */ + public BlockPos north(int n) { + return this.offset(EnumFacing.NORTH, n); + } + + /** + * + Offset this BlockPos 1 block in the given direction + */ + public BlockPos offset(EnumFacing facing) { + return this.offset(facing, 1); + } + + /** + * + Offset this BlockPos 1 block in the given direction + */ + public BlockPos offset(EnumFacing facing, int n) { + return n == 0 ? this + : new BlockPos(this.x + facing.getFrontOffsetX() * n, this.y + facing.getFrontOffsetY() * n, + this.z + facing.getFrontOffsetZ() * n); + } + + /** + * only use with a regular "net.minecraft.util.BlockPos"! + */ + public BlockPos offsetEvenFaster(EnumFacing facing, BlockPos ret) { + ret.x = this.x + facing.getFrontOffsetX(); + ret.y = this.y + facing.getFrontOffsetY(); + ret.z = this.z + facing.getFrontOffsetZ(); + return ret; + } + + public BlockPos offsetFaster(EnumFacing facing, BlockPos ret) { + ret.x = this.getX() + facing.getFrontOffsetX(); + ret.y = this.getY() + facing.getFrontOffsetY(); + ret.z = this.getZ() + facing.getFrontOffsetZ(); + return ret; + } + + /** + * + Offset this BlockPos 1 block in southern direction + */ + public BlockPos south() { + return this.south(1); + } + + /** + * eagler + */ + /** + * + Offset this BlockPos 1 block in southern direction + */ + public BlockPos south(BlockPos dst) { + dst.x = x; + dst.y = y; + dst.z = z + 1; + return dst; + } + + /** + * + Offset this BlockPos 1 block in southern direction + */ + public BlockPos south(int n) { + return this.offset(EnumFacing.SOUTH, n); + } + + /** + * + Subtract the given Vector from this BlockPos + */ + public BlockPos subtract(Vec3i vec) { + return vec.getX() == 0 && vec.getY() == 0 && vec.getZ() == 0 ? this + : new BlockPos(this.getX() - vec.getX(), this.getY() - vec.getY(), this.getZ() - vec.getZ()); + } + + /** + * + Serialize this BlockPos into a long value + */ + public long toLong() { + return ((long) this.getX() & X_MASK) << X_SHIFT | ((long) this.getY() & Y_MASK) << Y_SHIFT + | ((long) this.getZ() & Z_MASK) << 0; + } + + /** + * + Offset this BlockPos 1 block up + */ + public BlockPos up() { + return this.up(1); + } + + /** + * eagler + */ + /** + * + Offset this BlockPos 1 block up + */ + public BlockPos up(BlockPos dst) { + dst.x = x; + dst.y = y + 1; + dst.z = z; + return dst; + } + + /** + * + Offset this BlockPos 1 block up + */ + public BlockPos up(int n) { + return this.offset(EnumFacing.UP, n); + } + + /** + * + Offset this BlockPos 1 block in western direction + */ + public BlockPos west() { + return this.west(1); + } + + /** + * eagler + */ + /** + * + Offset this BlockPos 1 block in western direction + */ + public BlockPos west(BlockPos dst) { + dst.x = x - 1; + dst.y = y; + dst.z = z; + return dst; + } + + /** + * + Offset this BlockPos 1 block in western direction + */ + public BlockPos west(int n) { + return this.offset(EnumFacing.WEST, n); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/Cartesian.java b/src/game/java/net/minecraft/util/Cartesian.java index 3059dfc8..5be7929a 100644 --- a/src/game/java/net/minecraft/util/Cartesian.java +++ b/src/game/java/net/minecraft/util/Cartesian.java @@ -13,57 +13,30 @@ import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.UnmodifiableIterator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Cartesian { - public static Iterable cartesianProduct(Class clazz, Iterable> sets) { - return new Cartesian.Product(clazz, (Iterable[]) toArray(Iterable.class, sets)); - } - - public static Iterable> cartesianProduct(Iterable> sets) { - /**+ - * Convert an Iterable of Arrays (Object[]) to an Iterable of - * Lists - */ - return arraysAsLists(cartesianProduct(Object.class, sets)); - } - - private static Iterable> arraysAsLists(Iterable arrays) { - return Iterables.transform(arrays, new Cartesian.GetList()); - } - - private static T[] toArray(Class clazz, Iterable it) { - ArrayList arraylist = Lists.newArrayList(); - - for (Object object : it) { - arraylist.add(object); - } - - return (T[]) ((Object[]) arraylist.toArray(createArray(clazz, arraylist.size()))); - } - - private static T[] createArray(Class parClass1, int parInt1) { - return (T[]) ((Object[]) ((Object[]) Array.newInstance(parClass1, parInt1))); - } - static class GetList implements Function> { private GetList() { } @@ -74,20 +47,6 @@ public class Cartesian { } static class Product implements Iterable { - private final Class clazz; - private final Iterable[] iterables; - - private Product(Class clazz, Iterable[] iterables) { - this.clazz = clazz; - this.iterables = iterables; - } - - public Iterator iterator() { - return (Iterator) (this.iterables.length <= 0 - ? Collections.singletonList((T[]) Cartesian.createArray(this.clazz, 0)).iterator() - : new Cartesian.Product.ProductIterator(this.clazz, this.iterables)); - } - static class ProductIterator extends UnmodifiableIterator { private int index; private final Iterable[] iterables; @@ -163,5 +122,49 @@ public class Cartesian { } } } + + private final Class clazz; + + private final Iterable[] iterables; + + private Product(Class clazz, Iterable[] iterables) { + this.clazz = clazz; + this.iterables = iterables; + } + + public Iterator iterator() { + return (Iterator) (this.iterables.length <= 0 + ? Collections.singletonList((T[]) Cartesian.createArray(this.clazz, 0)).iterator() + : new Cartesian.Product.ProductIterator(this.clazz, this.iterables)); + } + } + + private static Iterable> arraysAsLists(Iterable arrays) { + return Iterables.transform(arrays, new Cartesian.GetList()); + } + + public static Iterable cartesianProduct(Class clazz, Iterable> sets) { + return new Cartesian.Product(clazz, (Iterable[]) toArray(Iterable.class, sets)); + } + + public static Iterable> cartesianProduct(Iterable> sets) { + /** + * + Convert an Iterable of Arrays (Object[]) to an Iterable of Lists + */ + return arraysAsLists(cartesianProduct(Object.class, sets)); + } + + private static T[] createArray(Class parClass1, int parInt1) { + return (T[]) ((Object[]) ((Object[]) Array.newInstance(parClass1, parInt1))); + } + + private static T[] toArray(Class clazz, Iterable it) { + ArrayList arraylist = Lists.newArrayList(); + + for (Object object : it) { + arraylist.add(object); + } + + return (T[]) ((Object[]) arraylist.toArray(createArray(clazz, arraylist.size()))); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ChatAllowedCharacters.java b/src/game/java/net/minecraft/util/ChatAllowedCharacters.java index d8b7735a..778b52b5 100644 --- a/src/game/java/net/minecraft/util/ChatAllowedCharacters.java +++ b/src/game/java/net/minecraft/util/ChatAllowedCharacters.java @@ -1,39 +1,38 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChatAllowedCharacters { - /**+ - * Array of the special characters that are allowed in any text - * drawing of Minecraft. + /** + * + Array of the special characters that are allowed in any text drawing of + * Minecraft. */ public static final char[] allowedCharactersArray = new char[] { '/', '\n', '\r', '\t', '\u0000', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':' }; - public static boolean isAllowedCharacter(char character) { - return character != 167 && character >= 32 && character != 127; - } - - /**+ - * Filter string by only keeping those characters for which + /** + * + Filter string by only keeping those characters for which * isAllowedCharacter() returns true. */ public static String filterAllowedCharacters(String input) { @@ -49,4 +48,8 @@ public class ChatAllowedCharacters { return stringbuilder.toString(); } + + public static boolean isAllowedCharacter(char character) { + return character != 167 && character >= 32 && character != 127; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ChatComponentProcessor.java b/src/game/java/net/minecraft/util/ChatComponentProcessor.java index 89f665a0..5bf4ad6c 100644 --- a/src/game/java/net/minecraft/util/ChatComponentProcessor.java +++ b/src/game/java/net/minecraft/util/ChatComponentProcessor.java @@ -8,22 +8,25 @@ import net.minecraft.command.ICommandSender; import net.minecraft.command.PlayerSelector; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/ChatComponentScore.java b/src/game/java/net/minecraft/util/ChatComponentScore.java index d6fe7272..581bf935 100644 --- a/src/game/java/net/minecraft/util/ChatComponentScore.java +++ b/src/game/java/net/minecraft/util/ChatComponentScore.java @@ -1,30 +1,32 @@ package net.minecraft.util; +import java.util.List; + +import net.lax1dude.eaglercraft.v1_8.HString; import net.minecraft.scoreboard.Score; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.scoreboard.Scoreboard; import net.minecraft.server.MinecraftServer; -import java.util.List; - -import net.lax1dude.eaglercraft.v1_8.HString; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +34,8 @@ import net.lax1dude.eaglercraft.v1_8.HString; public class ChatComponentScore extends ChatComponentStyle { private final String name; private final String objective; - /**+ - * The value displayed instead of the real score (may be null) + /** + * + The value displayed instead of the real score (may be null) */ private String value = ""; @@ -42,45 +44,9 @@ public class ChatComponentScore extends ChatComponentStyle { this.objective = objectiveIn; } - public String getName() { - return this.name; - } - - public String getObjective() { - return this.objective; - } - - /**+ - * Sets the value displayed instead of the real score. - */ - public void setValue(String valueIn) { - this.value = valueIn; - } - - /**+ - * Gets the text of this component, without any special - * formatting codes added, for chat. TODO: why is this two - * different methods? - */ - public String getUnformattedTextForChat() { - MinecraftServer minecraftserver = MinecraftServer.getServer(); - if (minecraftserver != null && StringUtils.isNullOrEmpty(this.value)) { - Scoreboard scoreboard = minecraftserver.worldServerForDimension(0).getScoreboard(); - ScoreObjective scoreobjective = scoreboard.getObjective(this.objective); - if (scoreboard.entityHasObjective(this.name, scoreobjective)) { - Score score = scoreboard.getValueFromObjective(this.name, scoreobjective); - this.setValue(HString.format("%d", new Object[] { Integer.valueOf(score.getScorePoints()) })); - } else { - this.value = ""; - } - } - - return this.value; - } - - /**+ - * Creates a copy of this component. Almost a deep copy, except - * the style is shallow-copied. + /** + * + Creates a copy of this component. Almost a deep copy, except the style is + * shallow-copied. */ public ChatComponentScore createCopy() { ChatComponentScore chatcomponentscore = new ChatComponentScore(this.name, this.objective); @@ -107,6 +73,41 @@ public class ChatComponentScore extends ChatComponentStyle { } } + public String getName() { + return this.name; + } + + public String getObjective() { + return this.objective; + } + + /** + * + Gets the text of this component, without any special formatting codes + * added, for chat. TODO: why is this two different methods? + */ + public String getUnformattedTextForChat() { + MinecraftServer minecraftserver = MinecraftServer.getServer(); + if (minecraftserver != null && StringUtils.isNullOrEmpty(this.value)) { + Scoreboard scoreboard = minecraftserver.worldServerForDimension(0).getScoreboard(); + ScoreObjective scoreobjective = scoreboard.getObjective(this.objective); + if (scoreboard.entityHasObjective(this.name, scoreobjective)) { + Score score = scoreboard.getValueFromObjective(this.name, scoreobjective); + this.setValue(HString.format("%d", new Object[] { Integer.valueOf(score.getScorePoints()) })); + } else { + this.value = ""; + } + } + + return this.value; + } + + /** + * + Sets the value displayed instead of the real score. + */ + public void setValue(String valueIn) { + this.value = valueIn; + } + public String toString() { return "ScoreComponent{name=\'" + this.name + '\'' + "objective=\'" + this.objective + '\'' + ", siblings=" + this.siblings + ", style=" + this.getChatStyle() + '}'; diff --git a/src/game/java/net/minecraft/util/ChatComponentSelector.java b/src/game/java/net/minecraft/util/ChatComponentSelector.java index d703fe67..6def42b4 100644 --- a/src/game/java/net/minecraft/util/ChatComponentSelector.java +++ b/src/game/java/net/minecraft/util/ChatComponentSelector.java @@ -2,22 +2,25 @@ package net.minecraft.util; import java.util.List; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,25 +32,9 @@ public class ChatComponentSelector extends ChatComponentStyle { this.selector = selectorIn; } - /**+ - * Gets the selector of this component, in plain text. - */ - public String getSelector() { - return this.selector; - } - - /**+ - * Gets the text of this component, without any special - * formatting codes added, for chat. TODO: why is this two - * different methods? - */ - public String getUnformattedTextForChat() { - return this.selector; - } - - /**+ - * Creates a copy of this component. Almost a deep copy, except - * the style is shallow-copied. + /** + * + Creates a copy of this component. Almost a deep copy, except the style is + * shallow-copied. */ public ChatComponentSelector createCopy() { ChatComponentSelector chatcomponentselector = new ChatComponentSelector(this.selector); @@ -72,6 +59,21 @@ public class ChatComponentSelector extends ChatComponentStyle { } } + /** + * + Gets the selector of this component, in plain text. + */ + public String getSelector() { + return this.selector; + } + + /** + * + Gets the text of this component, without any special formatting codes + * added, for chat. TODO: why is this two different methods? + */ + public String getUnformattedTextForChat() { + return this.selector; + } + public String toString() { return "SelectorComponent{pattern=\'" + this.selector + '\'' + ", siblings=" + this.siblings + ", style=" + this.getChatStyle() + '}'; diff --git a/src/game/java/net/minecraft/util/ChatComponentStyle.java b/src/game/java/net/minecraft/util/ChatComponentStyle.java index d570e439..410ab27a 100644 --- a/src/game/java/net/minecraft/util/ChatComponentStyle.java +++ b/src/game/java/net/minecraft/util/ChatComponentStyle.java @@ -7,124 +7,34 @@ import com.google.common.base.Function; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class ChatComponentStyle implements IChatComponent { - /**+ - * The later siblings of this component. If this component turns - * the text bold, that will apply to all the siblings until a - * later sibling turns the text something else. - */ - protected List siblings = Lists.newArrayList(); - private ChatStyle style; - - /**+ - * Appends the given component to the end of this one. - */ - public IChatComponent appendSibling(IChatComponent component) { - component.getChatStyle().setParentStyle(this.getChatStyle()); - this.siblings.add(component); - return this; - } - - /**+ - * Gets the sibling components of this one. - */ - public List getSiblings() { - return this.siblings; - } - - /**+ - * Appends the given text to the end of this component. - */ - public IChatComponent appendText(String text) { - return this.appendSibling(new ChatComponentText(text)); - } - - public IChatComponent setChatStyle(ChatStyle style) { - this.style = style; - - for (int i = 0, l = this.siblings.size(); i < l; ++i) { - this.siblings.get(i).getChatStyle().setParentStyle(this.getChatStyle()); - } - - return this; - } - - public ChatStyle getChatStyle() { - if (this.style == null) { - this.style = new ChatStyle(); - - for (int i = 0, l = this.siblings.size(); i < l; ++i) { - this.siblings.get(i).getChatStyle().setParentStyle(this.style); - } - } - - return this.style; - } - - public ChatStyle getChatStyleIfPresent() { - return this.style; - } - - public Iterator iterator() { - return Iterators.concat(Iterators.forArray(new ChatComponentStyle[] { this }), - createDeepCopyIterator(this.siblings)); - } - - /**+ - * Get the text of this component, and all child - * components, with all special formatting codes removed. - */ - public final String getUnformattedText() { - StringBuilder stringbuilder = new StringBuilder(); - - for (IChatComponent ichatcomponent : this) { - stringbuilder.append(ichatcomponent.getUnformattedTextForChat()); - } - - return stringbuilder.toString(); - } - - /**+ - * Gets the text of this component, with formatting codes added - * for rendering. - */ - public final String getFormattedText() { - StringBuilder stringbuilder = new StringBuilder(); - - for (IChatComponent ichatcomponent : this) { - stringbuilder.append(ichatcomponent.getChatStyle().getFormattingCode()); - stringbuilder.append(ichatcomponent.getUnformattedTextForChat()); - stringbuilder.append(EnumChatFormatting.RESET); - } - - return stringbuilder.toString(); - } - - /**+ - * Creates an iterator that iterates over the given components, - * returning deep copies of each component in turn so that the - * properties of the returned objects will remain externally - * consistent after being returned. + /** + * + Creates an iterator that iterates over the given components, returning deep + * copies of each component in turn so that the properties of the returned + * objects will remain externally consistent after being returned. */ public static Iterator createDeepCopyIterator(Iterable components) { Iterator iterator = Iterators.concat( @@ -143,6 +53,31 @@ public abstract class ChatComponentStyle implements IChatComponent { return iterator; } + /** + * + The later siblings of this component. If this component turns the text + * bold, that will apply to all the siblings until a later sibling turns the + * text something else. + */ + protected List siblings = Lists.newArrayList(); + + private ChatStyle style; + + /** + * + Appends the given component to the end of this one. + */ + public IChatComponent appendSibling(IChatComponent component) { + component.getChatStyle().setParentStyle(this.getChatStyle()); + this.siblings.add(component); + return this; + } + + /** + * + Appends the given text to the end of this component. + */ + public IChatComponent appendText(String text) { + return this.appendSibling(new ChatComponentText(text)); + } + public boolean equals(Object object) { if (this == object) { return true; @@ -155,10 +90,77 @@ public abstract class ChatComponentStyle implements IChatComponent { } } + public ChatStyle getChatStyle() { + if (this.style == null) { + this.style = new ChatStyle(); + + for (int i = 0, l = this.siblings.size(); i < l; ++i) { + this.siblings.get(i).getChatStyle().setParentStyle(this.style); + } + } + + return this.style; + } + + public ChatStyle getChatStyleIfPresent() { + return this.style; + } + + /** + * + Gets the text of this component, with formatting codes added for rendering. + */ + public final String getFormattedText() { + StringBuilder stringbuilder = new StringBuilder(); + + for (IChatComponent ichatcomponent : this) { + stringbuilder.append(ichatcomponent.getChatStyle().getFormattingCode()); + stringbuilder.append(ichatcomponent.getUnformattedTextForChat()); + stringbuilder.append(EnumChatFormatting.RESET); + } + + return stringbuilder.toString(); + } + + /** + * + Gets the sibling components of this one. + */ + public List getSiblings() { + return this.siblings; + } + + /** + * + Get the text of this component, and all child components, with all + * special formatting codes removed. + */ + public final String getUnformattedText() { + StringBuilder stringbuilder = new StringBuilder(); + + for (IChatComponent ichatcomponent : this) { + stringbuilder.append(ichatcomponent.getUnformattedTextForChat()); + } + + return stringbuilder.toString(); + } + public int hashCode() { return 31 * this.style.hashCode() + this.siblings.hashCode(); } + public Iterator iterator() { + return Iterators.concat(Iterators.forArray(new ChatComponentStyle[] { this }), + createDeepCopyIterator(this.siblings)); + } + + public IChatComponent setChatStyle(ChatStyle style) { + this.style = style; + + for (int i = 0, l = this.siblings.size(); i < l; ++i) { + this.siblings.get(i).getChatStyle().setParentStyle(this.getChatStyle()); + } + + return this; + } + public String toString() { return "BaseComponent{style=" + this.style + ", siblings=" + this.siblings + '}'; } diff --git a/src/game/java/net/minecraft/util/ChatComponentText.java b/src/game/java/net/minecraft/util/ChatComponentText.java index 7dbc3376..29561c9d 100644 --- a/src/game/java/net/minecraft/util/ChatComponentText.java +++ b/src/game/java/net/minecraft/util/ChatComponentText.java @@ -2,22 +2,25 @@ package net.minecraft.util; import java.util.List; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,28 +32,9 @@ public class ChatComponentText extends ChatComponentStyle { this.text = msg; } - /**+ - * Gets the text value of this ChatComponentText. TODO: what are - * getUnformattedText and getUnformattedTextForChat missing that - * made someone decide to create a third equivalent method that - * only ChatComponentText can implement? - */ - public String getChatComponentText_TextValue() { - return this.text; - } - - /**+ - * Gets the text of this component, without any special - * formatting codes added, for chat. TODO: why is this two - * different methods? - */ - public String getUnformattedTextForChat() { - return this.text; - } - - /**+ - * Creates a copy of this component. Almost a deep copy, except - * the style is shallow-copied. + /** + * + Creates a copy of this component. Almost a deep copy, except the style is + * shallow-copied. */ public ChatComponentText createCopy() { ChatComponentText chatcomponenttext = new ChatComponentText(this.text); @@ -75,6 +59,24 @@ public class ChatComponentText extends ChatComponentStyle { } } + /** + * + Gets the text value of this ChatComponentText. TODO: what are + * getUnformattedText and getUnformattedTextForChat missing that made someone + * decide to create a third equivalent method that only ChatComponentText can + * implement? + */ + public String getChatComponentText_TextValue() { + return this.text; + } + + /** + * + Gets the text of this component, without any special formatting codes + * added, for chat. TODO: why is this two different methods? + */ + public String getUnformattedTextForChat() { + return this.text; + } + public String toString() { return "TextComponent{text=\'" + this.text + '\'' + ", siblings=" + this.siblings + ", style=" + this.getChatStyle() + '}'; diff --git a/src/game/java/net/minecraft/util/ChatComponentTranslation.java b/src/game/java/net/minecraft/util/ChatComponentTranslation.java index 4270f0ba..ac283515 100644 --- a/src/game/java/net/minecraft/util/ChatComponentTranslation.java +++ b/src/game/java/net/minecraft/util/ChatComponentTranslation.java @@ -12,33 +12,36 @@ import com.google.common.collect.Lists; import net.lax1dude.eaglercraft.v1_8.HString; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChatComponentTranslation extends ChatComponentStyle { + public static final Pattern stringVariablePattern = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); private final String key; private final Object[] formatArgs; private final Object syncLock = new Object(); private long lastTranslationUpdateTimeInMilliseconds = -1L; List children = Lists.newArrayList(); - public static final Pattern stringVariablePattern = Pattern.compile("%(?:(\\d+)\\$)?([A-Za-z%]|$)"); public ChatComponentTranslation(String translationKey, Object... args) { this.key = translationKey; @@ -53,9 +56,35 @@ public class ChatComponentTranslation extends ChatComponentStyle { } - /**+ - * ensures that our children are initialized from the most - * recent string translation mapping. + /** + * + Creates a copy of this component. Almost a deep copy, except the style is + * shallow-copied. + */ + public ChatComponentTranslation createCopy() { + Object[] aobject = new Object[this.formatArgs.length]; + + for (int i = 0; i < this.formatArgs.length; ++i) { + if (this.formatArgs[i] instanceof IChatComponent) { + aobject[i] = ((IChatComponent) this.formatArgs[i]).createCopy(); + } else { + aobject[i] = this.formatArgs[i]; + } + } + + ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(this.key, aobject); + chatcomponenttranslation.setChatStyle(this.getChatStyle().createShallowCopy()); + + List lst = this.getSiblings(); + for (int i = 0, l = lst.size(); i < l; ++i) { + chatcomponenttranslation.appendSibling(lst.get(i).createCopy()); + } + + return chatcomponenttranslation; + } + + /** + * + ensures that our children are initialized from the most recent string + * translation mapping. */ synchronized void ensureInitialized() { synchronized (this.syncLock) { @@ -82,9 +111,68 @@ public class ChatComponentTranslation extends ChatComponentStyle { } - /**+ - * initializes our children from a format string, using the - * format args to fill in the placeholder variables. + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatComponentTranslation)) { + return false; + } else { + ChatComponentTranslation chatcomponenttranslation = (ChatComponentTranslation) object; + return Arrays.equals(this.formatArgs, chatcomponenttranslation.formatArgs) + && this.key.equals(chatcomponenttranslation.key) && super.equals(object); + } + } + + public Object[] getFormatArgs() { + return this.formatArgs; + } + + private IChatComponent getFormatArgumentAsComponent(int index) { + if (index >= this.formatArgs.length) { + throw new ChatComponentTranslationFormatException(this, index); + } else { + Object object = this.formatArgs[index]; + Object object1; + if (object instanceof IChatComponent) { + object1 = (IChatComponent) object; + } else { + object1 = new ChatComponentText(object == null ? "null" : object.toString()); + ((IChatComponent) object1).getChatStyle().setParentStyle(this.getChatStyle()); + } + + return (IChatComponent) object1; + } + } + + public String getKey() { + return this.key; + } + + /** + * + Gets the text of this component, without any special formatting codes + * added, for chat. TODO: why is this two different methods? + */ + public String getUnformattedTextForChat() { + this.ensureInitialized(); + StringBuilder stringbuilder = new StringBuilder(); + + for (int i = 0, l = this.children.size(); i < l; ++i) { + stringbuilder.append(this.children.get(i).getUnformattedTextForChat()); + } + + return stringbuilder.toString(); + } + + public int hashCode() { + int i = super.hashCode(); + i = 31 * i + this.key.hashCode(); + i = 31 * i + Arrays.hashCode(this.formatArgs); + return i; + } + + /** + * + initializes our children from a format string, using the format args to + * fill in the placeholder variables. */ protected void initializeFromFormat(String format) { boolean flag = false; @@ -135,21 +223,9 @@ public class ChatComponentTranslation extends ChatComponentStyle { } } - private IChatComponent getFormatArgumentAsComponent(int index) { - if (index >= this.formatArgs.length) { - throw new ChatComponentTranslationFormatException(this, index); - } else { - Object object = this.formatArgs[index]; - Object object1; - if (object instanceof IChatComponent) { - object1 = (IChatComponent) object; - } else { - object1 = new ChatComponentText(object == null ? "null" : object.toString()); - ((IChatComponent) object1).getChatStyle().setParentStyle(this.getChatStyle()); - } - - return (IChatComponent) object1; - } + public Iterator iterator() { + this.ensureInitialized(); + return Iterators.concat(createDeepCopyIterator(this.children), createDeepCopyIterator(this.siblings)); } public IChatComponent setChatStyle(ChatStyle chatstyle) { @@ -171,82 +247,8 @@ public class ChatComponentTranslation extends ChatComponentStyle { return this; } - public Iterator iterator() { - this.ensureInitialized(); - return Iterators.concat(createDeepCopyIterator(this.children), createDeepCopyIterator(this.siblings)); - } - - /**+ - * Gets the text of this component, without any special - * formatting codes added, for chat. TODO: why is this two - * different methods? - */ - public String getUnformattedTextForChat() { - this.ensureInitialized(); - StringBuilder stringbuilder = new StringBuilder(); - - for (int i = 0, l = this.children.size(); i < l; ++i) { - stringbuilder.append(this.children.get(i).getUnformattedTextForChat()); - } - - return stringbuilder.toString(); - } - - /**+ - * Creates a copy of this component. Almost a deep copy, except - * the style is shallow-copied. - */ - public ChatComponentTranslation createCopy() { - Object[] aobject = new Object[this.formatArgs.length]; - - for (int i = 0; i < this.formatArgs.length; ++i) { - if (this.formatArgs[i] instanceof IChatComponent) { - aobject[i] = ((IChatComponent) this.formatArgs[i]).createCopy(); - } else { - aobject[i] = this.formatArgs[i]; - } - } - - ChatComponentTranslation chatcomponenttranslation = new ChatComponentTranslation(this.key, aobject); - chatcomponenttranslation.setChatStyle(this.getChatStyle().createShallowCopy()); - - List lst = this.getSiblings(); - for (int i = 0, l = lst.size(); i < l; ++i) { - chatcomponenttranslation.appendSibling(lst.get(i).createCopy()); - } - - return chatcomponenttranslation; - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof ChatComponentTranslation)) { - return false; - } else { - ChatComponentTranslation chatcomponenttranslation = (ChatComponentTranslation) object; - return Arrays.equals(this.formatArgs, chatcomponenttranslation.formatArgs) - && this.key.equals(chatcomponenttranslation.key) && super.equals(object); - } - } - - public int hashCode() { - int i = super.hashCode(); - i = 31 * i + this.key.hashCode(); - i = 31 * i + Arrays.hashCode(this.formatArgs); - return i; - } - public String toString() { return "TranslatableComponent{key=\'" + this.key + '\'' + ", args=" + Arrays.toString(this.formatArgs) + ", siblings=" + this.siblings + ", style=" + this.getChatStyle() + '}'; } - - public String getKey() { - return this.key; - } - - public Object[] getFormatArgs() { - return this.formatArgs; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ChatComponentTranslationFormatException.java b/src/game/java/net/minecraft/util/ChatComponentTranslationFormatException.java index 53771851..dfacbc20 100644 --- a/src/game/java/net/minecraft/util/ChatComponentTranslationFormatException.java +++ b/src/game/java/net/minecraft/util/ChatComponentTranslationFormatException.java @@ -2,35 +2,38 @@ package net.minecraft.util; import net.lax1dude.eaglercraft.v1_8.HString; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChatComponentTranslationFormatException extends IllegalArgumentException { - public ChatComponentTranslationFormatException(ChatComponentTranslation component, String message) { - super(HString.format("Error parsing: %s: %s", new Object[] { component, message })); - } - public ChatComponentTranslationFormatException(ChatComponentTranslation component, int index) { super(HString.format("Invalid index %d requested for %s", new Object[] { Integer.valueOf(index), component })); } + public ChatComponentTranslationFormatException(ChatComponentTranslation component, String message) { + super(HString.format("Error parsing: %s: %s", new Object[] { component, message })); + } + public ChatComponentTranslationFormatException(ChatComponentTranslation component, Throwable cause) { super(HString.format("Error while parsing: %s", new Object[] { component }), cause); } diff --git a/src/game/java/net/minecraft/util/ChatStyle.java b/src/game/java/net/minecraft/util/ChatStyle.java index 2cae84ed..b86e3b7b 100644 --- a/src/game/java/net/minecraft/util/ChatStyle.java +++ b/src/game/java/net/minecraft/util/ChatStyle.java @@ -8,544 +8,30 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.minecraft.event.ClickEvent; import net.minecraft.event.HoverEvent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChatStyle { - private ChatStyle parentStyle; - private EnumChatFormatting color; - private Boolean bold; - private Boolean italic; - private Boolean underlined; - private Boolean strikethrough; - private Boolean obfuscated; - private ClickEvent chatClickEvent; - private HoverEvent chatHoverEvent; - private String insertion; - /**+ - * The base of the ChatStyle hierarchy. All ChatStyle instances - * are implicitly children of this. - */ - private static final ChatStyle rootStyle = new ChatStyle() { - /**+ - * Gets the effective color of this ChatStyle. - */ - public EnumChatFormatting getColor() { - return null; - } - - /**+ - * Whether or not text of this ChatStyle should be in bold. - */ - public boolean getBold() { - return false; - } - - /**+ - * Whether or not text of this ChatStyle should be italicized. - */ - public boolean getItalic() { - return false; - } - - /**+ - * Whether or not to format text of this ChatStyle using - * strikethrough. - */ - public boolean getStrikethrough() { - return false; - } - - /**+ - * Whether or not text of this ChatStyle should be underlined. - */ - public boolean getUnderlined() { - return false; - } - - /**+ - * Whether or not text of this ChatStyle should be obfuscated. - */ - public boolean getObfuscated() { - return false; - } - - /**+ - * The effective chat click event. - */ - public ClickEvent getChatClickEvent() { - return null; - } - - /**+ - * The effective chat hover event. - */ - public HoverEvent getChatHoverEvent() { - return null; - } - - /**+ - * Get the text to be inserted into Chat when the component is - * shift-clicked - */ - public String getInsertion() { - return null; - } - - /**+ - * Sets the color for this ChatStyle to the given value. Only - * use color values for this; set other values using the - * specific methods. - */ - public ChatStyle setColor(EnumChatFormatting color) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets whether or not text of this ChatStyle should be in bold. - * Set to false if, e.g., the parent style is bold and you want - * text of this style to be unbolded. - */ - public ChatStyle setBold(Boolean boldIn) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets whether or not text of this ChatStyle should be - * italicized. Set to false if, e.g., the parent style is - * italicized and you want to override that for this style. - */ - public ChatStyle setItalic(Boolean italic) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets whether or not to format text of this ChatStyle using - * strikethrough. Set to false if, e.g., the parent style uses - * strikethrough and you want to override that for this style. - */ - public ChatStyle setStrikethrough(Boolean strikethrough) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets whether or not text of this ChatStyle should be - * underlined. Set to false if, e.g., the parent style is - * underlined and you want to override that for this style. - */ - public ChatStyle setUnderlined(Boolean underlined) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets whether or not text of this ChatStyle should be - * obfuscated. Set to false if, e.g., the parent style is - * obfuscated and you want to override that for this style. - */ - public ChatStyle setObfuscated(Boolean obfuscated) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets the event that should be run when text of this ChatStyle - * is clicked on. - */ - public ChatStyle setChatClickEvent(ClickEvent event) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets the event that should be run when text of this ChatStyle - * is hovered over. - */ - public ChatStyle setChatHoverEvent(HoverEvent event) { - throw new UnsupportedOperationException(); - } - - /**+ - * Sets the fallback ChatStyle to use if this ChatStyle does not - * override some value. Without a parent, obvious defaults are - * used (bold: false, underlined: false, etc). - */ - public ChatStyle setParentStyle(ChatStyle parent) { - throw new UnsupportedOperationException(); - } - - public String toString() { - return "Style.ROOT"; - } - - /**+ - * Creates a shallow copy of this style. Changes to this - * instance's values will not be reflected in the copy, but - * changes to the parent style's values WILL be reflected in - * both this instance and the copy, wherever either does not - * override a value. - */ - public ChatStyle createShallowCopy() { - return this; - } - - /**+ - * Creates a deep copy of this style. No changes to this - * instance or its parent style will be reflected in the copy. - */ - public ChatStyle createDeepCopy() { - return this; - } - - /**+ - * Gets the equivalent text formatting code for this style, - * without the initial section sign (U+00A7) character. - */ - public String getFormattingCode() { - return ""; - } - }; - - /**+ - * Gets the effective color of this ChatStyle. - */ - public EnumChatFormatting getColor() { - return this.color == null ? this.getParent().getColor() : this.color; - } - - /**+ - * Whether or not text of this ChatStyle should be in bold. - */ - public boolean getBold() { - return this.bold == null ? this.getParent().getBold() : this.bold.booleanValue(); - } - - /**+ - * Whether or not text of this ChatStyle should be italicized. - */ - public boolean getItalic() { - return this.italic == null ? this.getParent().getItalic() : this.italic.booleanValue(); - } - - /**+ - * Whether or not to format text of this ChatStyle using - * strikethrough. - */ - public boolean getStrikethrough() { - return this.strikethrough == null ? this.getParent().getStrikethrough() : this.strikethrough.booleanValue(); - } - - /**+ - * Whether or not text of this ChatStyle should be underlined. - */ - public boolean getUnderlined() { - return this.underlined == null ? this.getParent().getUnderlined() : this.underlined.booleanValue(); - } - - /**+ - * Whether or not text of this ChatStyle should be obfuscated. - */ - public boolean getObfuscated() { - return this.obfuscated == null ? this.getParent().getObfuscated() : this.obfuscated.booleanValue(); - } - - /**+ - * Whether or not this style is empty (inherits everything from - * the parent). - */ - public boolean isEmpty() { - return this.bold == null && this.italic == null && this.strikethrough == null && this.underlined == null - && this.obfuscated == null && this.color == null && this.chatClickEvent == null - && this.chatHoverEvent == null; - } - - /**+ - * The effective chat click event. - */ - public ClickEvent getChatClickEvent() { - return this.chatClickEvent == null ? this.getParent().getChatClickEvent() : this.chatClickEvent; - } - - /**+ - * The effective chat hover event. - */ - public HoverEvent getChatHoverEvent() { - return this.chatHoverEvent == null ? this.getParent().getChatHoverEvent() : this.chatHoverEvent; - } - - /**+ - * Get the text to be inserted into Chat when the component is - * shift-clicked - */ - public String getInsertion() { - return this.insertion == null ? this.getParent().getInsertion() : this.insertion; - } - - /**+ - * Sets the color for this ChatStyle to the given value. Only - * use color values for this; set other values using the - * specific methods. - */ - public ChatStyle setColor(EnumChatFormatting enumchatformatting) { - this.color = enumchatformatting; - return this; - } - - /**+ - * Sets whether or not text of this ChatStyle should be in bold. - * Set to false if, e.g., the parent style is bold and you want - * text of this style to be unbolded. - */ - public ChatStyle setBold(Boolean obool) { - this.bold = obool; - return this; - } - - /**+ - * Sets whether or not text of this ChatStyle should be - * italicized. Set to false if, e.g., the parent style is - * italicized and you want to override that for this style. - */ - public ChatStyle setItalic(Boolean obool) { - this.italic = obool; - return this; - } - - /**+ - * Sets whether or not to format text of this ChatStyle using - * strikethrough. Set to false if, e.g., the parent style uses - * strikethrough and you want to override that for this style. - */ - public ChatStyle setStrikethrough(Boolean obool) { - this.strikethrough = obool; - return this; - } - - /**+ - * Sets whether or not text of this ChatStyle should be - * underlined. Set to false if, e.g., the parent style is - * underlined and you want to override that for this style. - */ - public ChatStyle setUnderlined(Boolean obool) { - this.underlined = obool; - return this; - } - - /**+ - * Sets whether or not text of this ChatStyle should be - * obfuscated. Set to false if, e.g., the parent style is - * obfuscated and you want to override that for this style. - */ - public ChatStyle setObfuscated(Boolean obool) { - this.obfuscated = obool; - return this; - } - - /**+ - * Sets the event that should be run when text of this ChatStyle - * is clicked on. - */ - public ChatStyle setChatClickEvent(ClickEvent clickevent) { - this.chatClickEvent = clickevent; - return this; - } - - /**+ - * Sets the event that should be run when text of this ChatStyle - * is hovered over. - */ - public ChatStyle setChatHoverEvent(HoverEvent hoverevent) { - this.chatHoverEvent = hoverevent; - return this; - } - - /**+ - * Set a text to be inserted into Chat when the component is - * shift-clicked - */ - public ChatStyle setInsertion(String insertion) { - this.insertion = insertion; - return this; - } - - /**+ - * Sets the fallback ChatStyle to use if this ChatStyle does not - * override some value. Without a parent, obvious defaults are - * used (bold: false, underlined: false, etc). - */ - public ChatStyle setParentStyle(ChatStyle chatstyle) { - this.parentStyle = chatstyle; - return this; - } - - /**+ - * Gets the equivalent text formatting code for this style, - * without the initial section sign (U+00A7) character. - */ - public String getFormattingCode() { - if (this.isEmpty()) { - return this.parentStyle != null ? this.parentStyle.getFormattingCode() : ""; - } else { - StringBuilder stringbuilder = new StringBuilder(); - if (this.getColor() != null) { - stringbuilder.append(this.getColor()); - } - - if (this.getBold()) { - stringbuilder.append(EnumChatFormatting.BOLD); - } - - if (this.getItalic()) { - stringbuilder.append(EnumChatFormatting.ITALIC); - } - - if (this.getUnderlined()) { - stringbuilder.append(EnumChatFormatting.UNDERLINE); - } - - if (this.getObfuscated()) { - stringbuilder.append(EnumChatFormatting.OBFUSCATED); - } - - if (this.getStrikethrough()) { - stringbuilder.append(EnumChatFormatting.STRIKETHROUGH); - } - - return stringbuilder.toString(); - } - } - - /**+ - * Gets the immediate parent of this ChatStyle. - */ - private ChatStyle getParent() { - return this.parentStyle == null ? rootStyle : this.parentStyle; - } - - public String toString() { - return "Style{hasParent=" + (this.parentStyle != null) + ", color=" + this.color + ", bold=" + this.bold - + ", italic=" + this.italic + ", underlined=" + this.underlined + ", obfuscated=" + this.obfuscated - + ", clickEvent=" + this.getChatClickEvent() + ", hoverEvent=" + this.getChatHoverEvent() - + ", insertion=" + this.getInsertion() + '}'; - } - - public boolean equals(Object object) { - if (this == object) { - return true; - } else if (!(object instanceof ChatStyle)) { - return false; - } else { - boolean flag; - label0: { - ChatStyle chatstyle = (ChatStyle) object; - if (this.getBold() == chatstyle.getBold() && this.getColor() == chatstyle.getColor() - && this.getItalic() == chatstyle.getItalic() - && this.getObfuscated() == chatstyle.getObfuscated() - && this.getStrikethrough() == chatstyle.getStrikethrough() - && this.getUnderlined() == chatstyle.getUnderlined()) { - label85: { - if (this.getChatClickEvent() != null) { - if (!this.getChatClickEvent().equals(chatstyle.getChatClickEvent())) { - break label85; - } - } else if (chatstyle.getChatClickEvent() != null) { - break label85; - } - - if (this.getChatHoverEvent() != null) { - if (!this.getChatHoverEvent().equals(chatstyle.getChatHoverEvent())) { - break label85; - } - } else if (chatstyle.getChatHoverEvent() != null) { - break label85; - } - - if (this.getInsertion() != null) { - if (this.getInsertion().equals(chatstyle.getInsertion())) { - break label0; - } - } else if (chatstyle.getInsertion() == null) { - break label0; - } - } - } - - flag = false; - return flag; - } - - flag = true; - return flag; - } - } - - public int hashCode() { - int i = this.color.hashCode(); - i = 31 * i + this.bold.hashCode(); - i = 31 * i + this.italic.hashCode(); - i = 31 * i + this.underlined.hashCode(); - i = 31 * i + this.strikethrough.hashCode(); - i = 31 * i + this.obfuscated.hashCode(); - i = 31 * i + this.chatClickEvent.hashCode(); - i = 31 * i + this.chatHoverEvent.hashCode(); - i = 31 * i + this.insertion.hashCode(); - return i; - } - - /**+ - * Creates a shallow copy of this style. Changes to this - * instance's values will not be reflected in the copy, but - * changes to the parent style's values WILL be reflected in - * both this instance and the copy, wherever either does not - * override a value. - */ - public ChatStyle createShallowCopy() { - ChatStyle chatstyle = new ChatStyle(); - chatstyle.bold = this.bold; - chatstyle.italic = this.italic; - chatstyle.strikethrough = this.strikethrough; - chatstyle.underlined = this.underlined; - chatstyle.obfuscated = this.obfuscated; - chatstyle.color = this.color; - chatstyle.chatClickEvent = this.chatClickEvent; - chatstyle.chatHoverEvent = this.chatHoverEvent; - chatstyle.parentStyle = this.parentStyle; - chatstyle.insertion = this.insertion; - return chatstyle; - } - - /**+ - * Creates a deep copy of this style. No changes to this - * instance or its parent style will be reflected in the copy. - */ - public ChatStyle createDeepCopy() { - ChatStyle chatstyle = new ChatStyle(); - chatstyle.setBold(Boolean.valueOf(this.getBold())); - chatstyle.setItalic(Boolean.valueOf(this.getItalic())); - chatstyle.setStrikethrough(Boolean.valueOf(this.getStrikethrough())); - chatstyle.setUnderlined(Boolean.valueOf(this.getUnderlined())); - chatstyle.setObfuscated(Boolean.valueOf(this.getObfuscated())); - chatstyle.setColor(this.getColor()); - chatstyle.setChatClickEvent(this.getChatClickEvent()); - chatstyle.setChatHoverEvent(this.getChatHoverEvent()); - chatstyle.setInsertion(this.getInsertion()); - return chatstyle; - } - public static class Serializer implements JSONTypeCodec { public ChatStyle deserialize(JSONObject jsonobject) throws JSONException { ChatStyle chatstyle = new ChatStyle(); @@ -678,4 +164,512 @@ public class ChatStyle { } } } + + /** + * + The base of the ChatStyle hierarchy. All ChatStyle instances are implicitly + * children of this. + */ + private static final ChatStyle rootStyle = new ChatStyle() { + /** + * + Creates a deep copy of this style. No changes to this instance or its + * parent style will be reflected in the copy. + */ + public ChatStyle createDeepCopy() { + return this; + } + + /** + * + Creates a shallow copy of this style. Changes to this instance's values + * will not be reflected in the copy, but changes to the parent style's values + * WILL be reflected in both this instance and the copy, wherever either does + * not override a value. + */ + public ChatStyle createShallowCopy() { + return this; + } + + /** + * + Whether or not text of this ChatStyle should be in bold. + */ + public boolean getBold() { + return false; + } + + /** + * + The effective chat click event. + */ + public ClickEvent getChatClickEvent() { + return null; + } + + /** + * + The effective chat hover event. + */ + public HoverEvent getChatHoverEvent() { + return null; + } + + /** + * + Gets the effective color of this ChatStyle. + */ + public EnumChatFormatting getColor() { + return null; + } + + /** + * + Gets the equivalent text formatting code for this style, without the + * initial section sign (U+00A7) character. + */ + public String getFormattingCode() { + return ""; + } + + /** + * + Get the text to be inserted into Chat when the component is shift-clicked + */ + public String getInsertion() { + return null; + } + + /** + * + Whether or not text of this ChatStyle should be italicized. + */ + public boolean getItalic() { + return false; + } + + /** + * + Whether or not text of this ChatStyle should be obfuscated. + */ + public boolean getObfuscated() { + return false; + } + + /** + * + Whether or not to format text of this ChatStyle using strikethrough. + */ + public boolean getStrikethrough() { + return false; + } + + /** + * + Whether or not text of this ChatStyle should be underlined. + */ + public boolean getUnderlined() { + return false; + } + + /** + * + Sets whether or not text of this ChatStyle should be in bold. Set to false + * if, e.g., the parent style is bold and you want text of this style to be + * unbolded. + */ + public ChatStyle setBold(Boolean boldIn) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets the event that should be run when text of this ChatStyle is clicked + * on. + */ + public ChatStyle setChatClickEvent(ClickEvent event) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets the event that should be run when text of this ChatStyle is hovered + * over. + */ + public ChatStyle setChatHoverEvent(HoverEvent event) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets the color for this ChatStyle to the given value. Only use color values + * for this; set other values using the specific methods. + */ + public ChatStyle setColor(EnumChatFormatting color) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets whether or not text of this ChatStyle should be italicized. Set to + * false if, e.g., the parent style is italicized and you want to override that + * for this style. + */ + public ChatStyle setItalic(Boolean italic) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets whether or not text of this ChatStyle should be obfuscated. Set to + * false if, e.g., the parent style is obfuscated and you want to override that + * for this style. + */ + public ChatStyle setObfuscated(Boolean obfuscated) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets the fallback ChatStyle to use if this ChatStyle does not override some + * value. Without a parent, obvious defaults are used (bold: false, underlined: + * false, etc). + */ + public ChatStyle setParentStyle(ChatStyle parent) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets whether or not to format text of this ChatStyle using strikethrough. + * Set to false if, e.g., the parent style uses strikethrough and you want to + * override that for this style. + */ + public ChatStyle setStrikethrough(Boolean strikethrough) { + throw new UnsupportedOperationException(); + } + + /** + * + Sets whether or not text of this ChatStyle should be underlined. Set to + * false if, e.g., the parent style is underlined and you want to override that + * for this style. + */ + public ChatStyle setUnderlined(Boolean underlined) { + throw new UnsupportedOperationException(); + } + + public String toString() { + return "Style.ROOT"; + } + }; + private ChatStyle parentStyle; + private EnumChatFormatting color; + private Boolean bold; + private Boolean italic; + private Boolean underlined; + private Boolean strikethrough; + private Boolean obfuscated; + private ClickEvent chatClickEvent; + private HoverEvent chatHoverEvent; + + private String insertion; + + /** + * + Creates a deep copy of this style. No changes to this instance or its + * parent style will be reflected in the copy. + */ + public ChatStyle createDeepCopy() { + ChatStyle chatstyle = new ChatStyle(); + chatstyle.setBold(Boolean.valueOf(this.getBold())); + chatstyle.setItalic(Boolean.valueOf(this.getItalic())); + chatstyle.setStrikethrough(Boolean.valueOf(this.getStrikethrough())); + chatstyle.setUnderlined(Boolean.valueOf(this.getUnderlined())); + chatstyle.setObfuscated(Boolean.valueOf(this.getObfuscated())); + chatstyle.setColor(this.getColor()); + chatstyle.setChatClickEvent(this.getChatClickEvent()); + chatstyle.setChatHoverEvent(this.getChatHoverEvent()); + chatstyle.setInsertion(this.getInsertion()); + return chatstyle; + } + + /** + * + Creates a shallow copy of this style. Changes to this instance's values + * will not be reflected in the copy, but changes to the parent style's values + * WILL be reflected in both this instance and the copy, wherever either does + * not override a value. + */ + public ChatStyle createShallowCopy() { + ChatStyle chatstyle = new ChatStyle(); + chatstyle.bold = this.bold; + chatstyle.italic = this.italic; + chatstyle.strikethrough = this.strikethrough; + chatstyle.underlined = this.underlined; + chatstyle.obfuscated = this.obfuscated; + chatstyle.color = this.color; + chatstyle.chatClickEvent = this.chatClickEvent; + chatstyle.chatHoverEvent = this.chatHoverEvent; + chatstyle.parentStyle = this.parentStyle; + chatstyle.insertion = this.insertion; + return chatstyle; + } + + public boolean equals(Object object) { + if (this == object) { + return true; + } else if (!(object instanceof ChatStyle)) { + return false; + } else { + boolean flag; + label0: { + ChatStyle chatstyle = (ChatStyle) object; + if (this.getBold() == chatstyle.getBold() && this.getColor() == chatstyle.getColor() + && this.getItalic() == chatstyle.getItalic() + && this.getObfuscated() == chatstyle.getObfuscated() + && this.getStrikethrough() == chatstyle.getStrikethrough() + && this.getUnderlined() == chatstyle.getUnderlined()) { + label85: { + if (this.getChatClickEvent() != null) { + if (!this.getChatClickEvent().equals(chatstyle.getChatClickEvent())) { + break label85; + } + } else if (chatstyle.getChatClickEvent() != null) { + break label85; + } + + if (this.getChatHoverEvent() != null) { + if (!this.getChatHoverEvent().equals(chatstyle.getChatHoverEvent())) { + break label85; + } + } else if (chatstyle.getChatHoverEvent() != null) { + break label85; + } + + if (this.getInsertion() != null) { + if (this.getInsertion().equals(chatstyle.getInsertion())) { + break label0; + } + } else if (chatstyle.getInsertion() == null) { + break label0; + } + } + } + + flag = false; + return flag; + } + + flag = true; + return flag; + } + } + + /** + * + Whether or not text of this ChatStyle should be in bold. + */ + public boolean getBold() { + return this.bold == null ? this.getParent().getBold() : this.bold.booleanValue(); + } + + /** + * + The effective chat click event. + */ + public ClickEvent getChatClickEvent() { + return this.chatClickEvent == null ? this.getParent().getChatClickEvent() : this.chatClickEvent; + } + + /** + * + The effective chat hover event. + */ + public HoverEvent getChatHoverEvent() { + return this.chatHoverEvent == null ? this.getParent().getChatHoverEvent() : this.chatHoverEvent; + } + + /** + * + Gets the effective color of this ChatStyle. + */ + public EnumChatFormatting getColor() { + return this.color == null ? this.getParent().getColor() : this.color; + } + + /** + * + Gets the equivalent text formatting code for this style, without the + * initial section sign (U+00A7) character. + */ + public String getFormattingCode() { + if (this.isEmpty()) { + return this.parentStyle != null ? this.parentStyle.getFormattingCode() : ""; + } else { + StringBuilder stringbuilder = new StringBuilder(); + if (this.getColor() != null) { + stringbuilder.append(this.getColor()); + } + + if (this.getBold()) { + stringbuilder.append(EnumChatFormatting.BOLD); + } + + if (this.getItalic()) { + stringbuilder.append(EnumChatFormatting.ITALIC); + } + + if (this.getUnderlined()) { + stringbuilder.append(EnumChatFormatting.UNDERLINE); + } + + if (this.getObfuscated()) { + stringbuilder.append(EnumChatFormatting.OBFUSCATED); + } + + if (this.getStrikethrough()) { + stringbuilder.append(EnumChatFormatting.STRIKETHROUGH); + } + + return stringbuilder.toString(); + } + } + + /** + * + Get the text to be inserted into Chat when the component is shift-clicked + */ + public String getInsertion() { + return this.insertion == null ? this.getParent().getInsertion() : this.insertion; + } + + /** + * + Whether or not text of this ChatStyle should be italicized. + */ + public boolean getItalic() { + return this.italic == null ? this.getParent().getItalic() : this.italic.booleanValue(); + } + + /** + * + Whether or not text of this ChatStyle should be obfuscated. + */ + public boolean getObfuscated() { + return this.obfuscated == null ? this.getParent().getObfuscated() : this.obfuscated.booleanValue(); + } + + /** + * + Gets the immediate parent of this ChatStyle. + */ + private ChatStyle getParent() { + return this.parentStyle == null ? rootStyle : this.parentStyle; + } + + /** + * + Whether or not to format text of this ChatStyle using strikethrough. + */ + public boolean getStrikethrough() { + return this.strikethrough == null ? this.getParent().getStrikethrough() : this.strikethrough.booleanValue(); + } + + /** + * + Whether or not text of this ChatStyle should be underlined. + */ + public boolean getUnderlined() { + return this.underlined == null ? this.getParent().getUnderlined() : this.underlined.booleanValue(); + } + + public int hashCode() { + int i = this.color.hashCode(); + i = 31 * i + this.bold.hashCode(); + i = 31 * i + this.italic.hashCode(); + i = 31 * i + this.underlined.hashCode(); + i = 31 * i + this.strikethrough.hashCode(); + i = 31 * i + this.obfuscated.hashCode(); + i = 31 * i + this.chatClickEvent.hashCode(); + i = 31 * i + this.chatHoverEvent.hashCode(); + i = 31 * i + this.insertion.hashCode(); + return i; + } + + /** + * + Whether or not this style is empty (inherits everything from the parent). + */ + public boolean isEmpty() { + return this.bold == null && this.italic == null && this.strikethrough == null && this.underlined == null + && this.obfuscated == null && this.color == null && this.chatClickEvent == null + && this.chatHoverEvent == null; + } + + /** + * + Sets whether or not text of this ChatStyle should be in bold. Set to false + * if, e.g., the parent style is bold and you want text of this style to be + * unbolded. + */ + public ChatStyle setBold(Boolean obool) { + this.bold = obool; + return this; + } + + /** + * + Sets the event that should be run when text of this ChatStyle is clicked + * on. + */ + public ChatStyle setChatClickEvent(ClickEvent clickevent) { + this.chatClickEvent = clickevent; + return this; + } + + /** + * + Sets the event that should be run when text of this ChatStyle is hovered + * over. + */ + public ChatStyle setChatHoverEvent(HoverEvent hoverevent) { + this.chatHoverEvent = hoverevent; + return this; + } + + /** + * + Sets the color for this ChatStyle to the given value. Only use color values + * for this; set other values using the specific methods. + */ + public ChatStyle setColor(EnumChatFormatting enumchatformatting) { + this.color = enumchatformatting; + return this; + } + + /** + * + Set a text to be inserted into Chat when the component is shift-clicked + */ + public ChatStyle setInsertion(String insertion) { + this.insertion = insertion; + return this; + } + + /** + * + Sets whether or not text of this ChatStyle should be italicized. Set to + * false if, e.g., the parent style is italicized and you want to override that + * for this style. + */ + public ChatStyle setItalic(Boolean obool) { + this.italic = obool; + return this; + } + + /** + * + Sets whether or not text of this ChatStyle should be obfuscated. Set to + * false if, e.g., the parent style is obfuscated and you want to override that + * for this style. + */ + public ChatStyle setObfuscated(Boolean obool) { + this.obfuscated = obool; + return this; + } + + /** + * + Sets the fallback ChatStyle to use if this ChatStyle does not override some + * value. Without a parent, obvious defaults are used (bold: false, underlined: + * false, etc). + */ + public ChatStyle setParentStyle(ChatStyle chatstyle) { + this.parentStyle = chatstyle; + return this; + } + + /** + * + Sets whether or not to format text of this ChatStyle using strikethrough. + * Set to false if, e.g., the parent style uses strikethrough and you want to + * override that for this style. + */ + public ChatStyle setStrikethrough(Boolean obool) { + this.strikethrough = obool; + return this; + } + + /** + * + Sets whether or not text of this ChatStyle should be underlined. Set to + * false if, e.g., the parent style is underlined and you want to override that + * for this style. + */ + public ChatStyle setUnderlined(Boolean obool) { + this.underlined = obool; + return this; + } + + public String toString() { + return "Style{hasParent=" + (this.parentStyle != null) + ", color=" + this.color + ", bold=" + this.bold + + ", italic=" + this.italic + ", underlined=" + this.underlined + ", obfuscated=" + this.obfuscated + + ", clickEvent=" + this.getChatClickEvent() + ", hoverEvent=" + this.getChatHoverEvent() + + ", insertion=" + this.getInsertion() + '}'; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ClassInheritanceMultiMap.java b/src/game/java/net/minecraft/util/ClassInheritanceMultiMap.java index 79a433a3..60679005 100644 --- a/src/game/java/net/minecraft/util/ClassInheritanceMultiMap.java +++ b/src/game/java/net/minecraft/util/ClassInheritanceMultiMap.java @@ -11,22 +11,25 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,6 +52,20 @@ public class ClassInheritanceMultiMap extends AbstractSet { } + public boolean add(T parObject) { + for (Class oclass : this.knownKeys) { + if (oclass.isAssignableFrom(parObject.getClass())) { + this.func_181743_a(parObject, oclass); + } + } + + return true; + } + + public boolean contains(Object parObject) { + return Iterators.contains(this.getByClass(parObject.getClass()).iterator(), parObject); + } + protected void createLookup(Class clazz) { field_181158_a.add(clazz); @@ -74,16 +91,6 @@ public class ClassInheritanceMultiMap extends AbstractSet { } } - public boolean add(T parObject) { - for (Class oclass : this.knownKeys) { - if (oclass.isAssignableFrom(parObject.getClass())) { - this.func_181743_a(parObject, oclass); - } - } - - return true; - } - private void func_181743_a(T parObject, Class parClass1) { List list = (List) this.map.get(parClass1); if (list == null) { @@ -94,26 +101,6 @@ public class ClassInheritanceMultiMap extends AbstractSet { } - public boolean remove(Object parObject) { - Object object = parObject; - boolean flag = false; - - for (Class oclass : this.knownKeys) { - if (oclass.isAssignableFrom(object.getClass())) { - List list = (List) this.map.get(oclass); - if (list != null && list.remove(object)) { - flag = true; - } - } - } - - return flag; - } - - public boolean contains(Object parObject) { - return Iterators.contains(this.getByClass(parObject.getClass()).iterator(), parObject); - } - public Iterable getByClass(final Class clazz) { return new Iterable() { public Iterator iterator() { @@ -134,6 +121,22 @@ public class ClassInheritanceMultiMap extends AbstractSet { : Iterators.unmodifiableIterator(this.field_181745_e.iterator()); } + public boolean remove(Object parObject) { + Object object = parObject; + boolean flag = false; + + for (Class oclass : this.knownKeys) { + if (oclass.isAssignableFrom(object.getClass())) { + List list = (List) this.map.get(oclass); + if (list != null && list.remove(object)) { + flag = true; + } + } + } + + return flag; + } + public int size() { return this.field_181745_e.size(); } diff --git a/src/game/java/net/minecraft/util/CombatEntry.java b/src/game/java/net/minecraft/util/CombatEntry.java index 0d243cd7..93a532ae 100644 --- a/src/game/java/net/minecraft/util/CombatEntry.java +++ b/src/game/java/net/minecraft/util/CombatEntry.java @@ -2,22 +2,25 @@ package net.minecraft.util; import net.minecraft.entity.EntityLivingBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,35 +43,34 @@ public class CombatEntry { this.fallDistance = fallDistanceIn; } - /**+ - * Get the DamageSource of the CombatEntry instance. - */ - public DamageSource getDamageSrc() { - return this.damageSrc; + public String func_94562_g() { + return this.field_94566_e; } public float func_94563_c() { return this.damage; } - /**+ - * Returns true if {@link - * net.minecraft.util.DamageSource#getEntity() damage source} is - * a living entity - */ - public boolean isLivingDamageSrc() { - return this.damageSrc.getEntity() instanceof EntityLivingBase; + public float getDamageAmount() { + return this.damageSrc == DamageSource.outOfWorld ? Float.MAX_VALUE : this.fallDistance; } - public String func_94562_g() { - return this.field_94566_e; + /** + * + Get the DamageSource of the CombatEntry instance. + */ + public DamageSource getDamageSrc() { + return this.damageSrc; } public IChatComponent getDamageSrcDisplayName() { return this.getDamageSrc().getEntity() == null ? null : this.getDamageSrc().getEntity().getDisplayName(); } - public float getDamageAmount() { - return this.damageSrc == DamageSource.outOfWorld ? Float.MAX_VALUE : this.fallDistance; + /** + * + Returns true if {@link net.minecraft.util.DamageSource#getEntity() damage + * source} is a living entity + */ + public boolean isLivingDamageSrc() { + return this.damageSrc.getEntity() instanceof EntityLivingBase; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/CombatTracker.java b/src/game/java/net/minecraft/util/CombatTracker.java index 59cc4676..8efaa2dc 100644 --- a/src/game/java/net/minecraft/util/CombatTracker.java +++ b/src/game/java/net/minecraft/util/CombatTracker.java @@ -11,29 +11,32 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CombatTracker { - /**+ - * The CombatEntry objects that we've tracked so far. + /** + * + The CombatEntry objects that we've tracked so far. */ private final List combatEntries = Lists.newArrayList(); private final EntityLivingBase fighter; @@ -48,6 +51,51 @@ public class CombatTracker { this.fighter = fighterIn; } + public int func_180134_f() { + return this.field_94552_d ? this.fighter.ticksExisted - this.field_152775_d + : this.field_152776_e - this.field_152775_d; + } + + private void func_94542_g() { + this.field_94551_f = null; + } + + private CombatEntry func_94544_f() { + CombatEntry combatentry = null; + CombatEntry combatentry1 = null; + byte b0 = 0; + float f = 0.0F; + + for (int i = 0; i < this.combatEntries.size(); ++i) { + CombatEntry combatentry2 = (CombatEntry) this.combatEntries.get(i); + CombatEntry combatentry3 = i > 0 ? (CombatEntry) this.combatEntries.get(i - 1) : null; + if ((combatentry2.getDamageSrc() == DamageSource.fall + || combatentry2.getDamageSrc() == DamageSource.outOfWorld) && combatentry2.getDamageAmount() > 0.0F + && (combatentry == null || combatentry2.getDamageAmount() > f)) { + if (i > 0) { + combatentry = combatentry3; + } else { + combatentry = combatentry2; + } + + f = combatentry2.getDamageAmount(); + } + + if (combatentry2.func_94562_g() != null + && (combatentry1 == null || combatentry2.func_94563_c() > (float) b0)) { + combatentry1 = combatentry2; + } + } + + if (f > 5.0F && combatentry != null) { + return combatentry; + } else if (b0 > 5 && combatentry1 != null) { + return combatentry1; + } else { + return null; + } + } + public void func_94545_a() { this.func_94542_g(); if (this.fighter.isOnLadder()) { @@ -65,24 +113,36 @@ public class CombatTracker { } - /**+ - * Adds an entry for the combat tracker - */ - public void trackDamage(DamageSource damageSrc, float healthIn, float damageAmount) { - this.reset(); - this.func_94545_a(); - CombatEntry combatentry = new CombatEntry(damageSrc, this.fighter.ticksExisted, healthIn, damageAmount, - this.field_94551_f, this.fighter.fallDistance); - this.combatEntries.add(combatentry); - this.field_94555_c = this.fighter.ticksExisted; - this.field_94553_e = true; - if (combatentry.isLivingDamageSrc() && !this.field_94552_d && this.fighter.isEntityAlive()) { - this.field_94552_d = true; - this.field_152775_d = this.fighter.ticksExisted; - this.field_152776_e = this.field_152775_d; - this.fighter.sendEnterCombat(); + private String func_94548_b(CombatEntry parCombatEntry) { + return parCombatEntry.func_94562_g() == null ? "generic" : parCombatEntry.func_94562_g(); + } + + public EntityLivingBase func_94550_c() { + EntityLivingBase entitylivingbase = null; + EntityPlayer entityplayer = null; + float f = 0.0F; + float f1 = 0.0F; + + for (int i = 0, l = this.combatEntries.size(); i < l; ++i) { + CombatEntry combatentry = this.combatEntries.get(i); + if (combatentry.getDamageSrc().getEntity() instanceof EntityPlayer + && (entityplayer == null || combatentry.func_94563_c() > f1)) { + f1 = combatentry.func_94563_c(); + entityplayer = (EntityPlayer) combatentry.getDamageSrc().getEntity(); + } + + if (combatentry.getDamageSrc().getEntity() instanceof EntityLivingBase + && (entitylivingbase == null || combatentry.func_94563_c() > f)) { + f = combatentry.func_94563_c(); + entitylivingbase = (EntityLivingBase) combatentry.getDamageSrc().getEntity(); + } } + if (entityplayer != null && f1 >= f / 3.0F) { + return entityplayer; + } else { + return entitylivingbase; + } } public IChatComponent getDeathMessage() { @@ -138,85 +198,15 @@ public class CombatTracker { } } - public EntityLivingBase func_94550_c() { - EntityLivingBase entitylivingbase = null; - EntityPlayer entityplayer = null; - float f = 0.0F; - float f1 = 0.0F; - - for (int i = 0, l = this.combatEntries.size(); i < l; ++i) { - CombatEntry combatentry = this.combatEntries.get(i); - if (combatentry.getDamageSrc().getEntity() instanceof EntityPlayer - && (entityplayer == null || combatentry.func_94563_c() > f1)) { - f1 = combatentry.func_94563_c(); - entityplayer = (EntityPlayer) combatentry.getDamageSrc().getEntity(); - } - - if (combatentry.getDamageSrc().getEntity() instanceof EntityLivingBase - && (entitylivingbase == null || combatentry.func_94563_c() > f)) { - f = combatentry.func_94563_c(); - entitylivingbase = (EntityLivingBase) combatentry.getDamageSrc().getEntity(); - } - } - - if (entityplayer != null && f1 >= f / 3.0F) { - return entityplayer; - } else { - return entitylivingbase; - } + /** + * + Returns EntityLivingBase assigned for this CombatTracker + */ + public EntityLivingBase getFighter() { + return this.fighter; } - private CombatEntry func_94544_f() { - CombatEntry combatentry = null; - CombatEntry combatentry1 = null; - byte b0 = 0; - float f = 0.0F; - - for (int i = 0; i < this.combatEntries.size(); ++i) { - CombatEntry combatentry2 = (CombatEntry) this.combatEntries.get(i); - CombatEntry combatentry3 = i > 0 ? (CombatEntry) this.combatEntries.get(i - 1) : null; - if ((combatentry2.getDamageSrc() == DamageSource.fall - || combatentry2.getDamageSrc() == DamageSource.outOfWorld) && combatentry2.getDamageAmount() > 0.0F - && (combatentry == null || combatentry2.getDamageAmount() > f)) { - if (i > 0) { - combatentry = combatentry3; - } else { - combatentry = combatentry2; - } - - f = combatentry2.getDamageAmount(); - } - - if (combatentry2.func_94562_g() != null - && (combatentry1 == null || combatentry2.func_94563_c() > (float) b0)) { - combatentry1 = combatentry2; - } - } - - if (f > 5.0F && combatentry != null) { - return combatentry; - } else if (b0 > 5 && combatentry1 != null) { - return combatentry1; - } else { - return null; - } - } - - private String func_94548_b(CombatEntry parCombatEntry) { - return parCombatEntry.func_94562_g() == null ? "generic" : parCombatEntry.func_94562_g(); - } - - public int func_180134_f() { - return this.field_94552_d ? this.fighter.ticksExisted - this.field_152775_d - : this.field_152776_e - this.field_152775_d; - } - - private void func_94542_g() { - this.field_94551_f = null; - } - - /**+ - * Resets this trackers list of combat entries + /** + * + Resets this trackers list of combat entries */ public void reset() { int i = this.field_94552_d ? 300 : 100; @@ -235,10 +225,23 @@ public class CombatTracker { } - /**+ - * Returns EntityLivingBase assigned for this CombatTracker + /** + * + Adds an entry for the combat tracker */ - public EntityLivingBase getFighter() { - return this.fighter; + public void trackDamage(DamageSource damageSrc, float healthIn, float damageAmount) { + this.reset(); + this.func_94545_a(); + CombatEntry combatentry = new CombatEntry(damageSrc, this.fighter.ticksExisted, healthIn, damageAmount, + this.field_94551_f, this.fighter.fallDistance); + this.combatEntries.add(combatentry); + this.field_94555_c = this.fighter.ticksExisted; + this.field_94553_e = true; + if (combatentry.isLivingDamageSrc() && !this.field_94552_d && this.fighter.isEntityAlive()) { + this.field_94552_d = true; + this.field_152775_d = this.fighter.ticksExisted; + this.field_152776_e = this.field_152775_d; + this.fighter.sendEnterCombat(); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/DamageSource.java b/src/game/java/net/minecraft/util/DamageSource.java index b814df58..de137425 100644 --- a/src/game/java/net/minecraft/util/DamageSource.java +++ b/src/game/java/net/minecraft/util/DamageSource.java @@ -7,22 +7,25 @@ import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.entity.projectile.EntityFireball; import net.minecraft.world.Explosion; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,37 +47,16 @@ public class DamageSource { public static DamageSource wither = (new DamageSource("wither")).setDamageBypassesArmor(); public static DamageSource anvil = new DamageSource("anvil"); public static DamageSource fallingBlock = new DamageSource("fallingBlock"); - private boolean isUnblockable; - private boolean isDamageAllowedInCreativeMode; - private boolean damageIsAbsolute; - private float hungerDamage = 0.3F; - private boolean fireDamage; - private boolean projectile; - private boolean difficultyScaled; - private boolean magicDamage; - private boolean explosion; - public String damageType; - public static DamageSource causeMobDamage(EntityLivingBase mob) { - return new EntityDamageSource("mob", mob); - } - - /**+ - * returns an EntityDamageSource of type player - */ - public static DamageSource causePlayerDamage(EntityPlayer player) { - return new EntityDamageSource("player", player); - } - - /**+ - * returns EntityDamageSourceIndirect of an arrow + /** + * + returns EntityDamageSourceIndirect of an arrow */ public static DamageSource causeArrowDamage(EntityArrow arrow, Entity parEntity) { return (new EntityDamageSourceIndirect("arrow", arrow, parEntity)).setProjectile(); } - /**+ - * returns EntityDamageSourceIndirect of a fireball + /** + * + returns EntityDamageSourceIndirect of a fireball */ public static DamageSource causeFireballDamage(EntityFireball fireball, Entity parEntity) { return parEntity == null @@ -82,22 +64,33 @@ public class DamageSource { : (new EntityDamageSourceIndirect("fireball", fireball, parEntity)).setFireDamage().setProjectile(); } - public static DamageSource causeThrownDamage(Entity parEntity, Entity parEntity2) { - return (new EntityDamageSourceIndirect("thrown", parEntity, parEntity2)).setProjectile(); - } - public static DamageSource causeIndirectMagicDamage(Entity parEntity, Entity parEntity2) { return (new EntityDamageSourceIndirect("indirectMagic", parEntity, parEntity2)).setDamageBypassesArmor() .setMagicDamage(); } - /**+ - * Returns the EntityDamageSource of the Thorns enchantment + public static DamageSource causeMobDamage(EntityLivingBase mob) { + return new EntityDamageSource("mob", mob); + } + + /** + * + returns an EntityDamageSource of type player + */ + public static DamageSource causePlayerDamage(EntityPlayer player) { + return new EntityDamageSource("player", player); + } + + /** + * + Returns the EntityDamageSource of the Thorns enchantment */ public static DamageSource causeThornsDamage(Entity parEntity) { return (new EntityDamageSource("thorns", parEntity)).setIsThornsDamage().setMagicDamage(); } + public static DamageSource causeThrownDamage(Entity parEntity, Entity parEntity2) { + return (new EntityDamageSourceIndirect("thrown", parEntity, parEntity2)).setProjectile(); + } + public static DamageSource setExplosionSource(Explosion explosionIn) { return explosionIn != null && explosionIn.getExplosivePlacedBy() != null ? (new EntityDamageSource("explosion.player", explosionIn.getExplosivePlacedBy())).setDifficultyScaled() @@ -105,97 +98,42 @@ public class DamageSource { : (new DamageSource("explosion")).setDifficultyScaled().setExplosion(); } - /**+ - * Returns true if the damage is projectile based. - */ - public boolean isProjectile() { - return this.projectile; - } + private boolean isUnblockable; + private boolean isDamageAllowedInCreativeMode; - /**+ - * Define the damage type as projectile based. - */ - public DamageSource setProjectile() { - this.projectile = true; - return this; - } + private boolean damageIsAbsolute; - public boolean isExplosion() { - return this.explosion; - } + private float hungerDamage = 0.3F; - public DamageSource setExplosion() { - this.explosion = true; - return this; - } + private boolean fireDamage; - public boolean isUnblockable() { - return this.isUnblockable; - } + private boolean projectile; - /**+ - * How much satiate(food) is consumed by this DamageSource - */ - public float getHungerDamage() { - return this.hungerDamage; + private boolean difficultyScaled; + + private boolean magicDamage; + + private boolean explosion; + + public String damageType; + + protected DamageSource(String damageTypeIn) { + this.damageType = damageTypeIn; } public boolean canHarmInCreative() { return this.isDamageAllowedInCreativeMode; } - /**+ - * Whether or not the damage ignores modification by potion - * effects or enchantments. + /** + * + Return the name of damage type. */ - public boolean isDamageAbsolute() { - return this.damageIsAbsolute; + public String getDamageType() { + return this.damageType; } - protected DamageSource(String damageTypeIn) { - this.damageType = damageTypeIn; - } - - public Entity getSourceOfDamage() { - return this.getEntity(); - } - - public Entity getEntity() { - return null; - } - - protected DamageSource setDamageBypassesArmor() { - this.isUnblockable = true; - this.hungerDamage = 0.0F; - return this; - } - - protected DamageSource setDamageAllowedInCreativeMode() { - this.isDamageAllowedInCreativeMode = true; - return this; - } - - /**+ - * Sets a value indicating whether the damage is absolute - * (ignores modification by potion effects or enchantments), and - * also clears out hunger damage. - */ - protected DamageSource setDamageIsAbsolute() { - this.damageIsAbsolute = true; - this.hungerDamage = 0.0F; - return this; - } - - /**+ - * Define the damage type as fire based. - */ - protected DamageSource setFireDamage() { - this.fireDamage = true; - return this; - } - - /**+ - * Gets the death message that is displayed when the player dies + /** + * + Gets the death message that is displayed when the player dies */ public IChatComponent getDeathMessage(EntityLivingBase parEntityLivingBase) { EntityLivingBase entitylivingbase = parEntityLivingBase.func_94060_bK(); @@ -207,54 +145,128 @@ public class DamageSource { : new ChatComponentTranslation(s, new Object[] { parEntityLivingBase.getDisplayName() }); } - /**+ - * Returns true if the damage is fire based. - */ - public boolean isFireDamage() { - return this.fireDamage; + public Entity getEntity() { + return null; } - /**+ - * Return the name of damage type. + /** + * + How much satiate(food) is consumed by this DamageSource */ - public String getDamageType() { - return this.damageType; + public float getHungerDamage() { + return this.hungerDamage; } - /**+ - * Set whether this damage source will have its damage amount - * scaled based on the current difficulty. - */ - public DamageSource setDifficultyScaled() { - this.difficultyScaled = true; - return this; - } - - /**+ - * Return whether this damage source will have its damage amount - * scaled based on the current difficulty. - */ - public boolean isDifficultyScaled() { - return this.difficultyScaled; - } - - /**+ - * Returns true if the damage is magic based. - */ - public boolean isMagicDamage() { - return this.magicDamage; - } - - /**+ - * Define the damage type as magic based. - */ - public DamageSource setMagicDamage() { - this.magicDamage = true; - return this; + public Entity getSourceOfDamage() { + return this.getEntity(); } public boolean isCreativePlayer() { Entity entity = this.getEntity(); return entity instanceof EntityPlayer && ((EntityPlayer) entity).capabilities.isCreativeMode; } + + /** + * + Whether or not the damage ignores modification by potion effects or + * enchantments. + */ + public boolean isDamageAbsolute() { + return this.damageIsAbsolute; + } + + /** + * + Return whether this damage source will have its damage amount scaled based + * on the current difficulty. + */ + public boolean isDifficultyScaled() { + return this.difficultyScaled; + } + + public boolean isExplosion() { + return this.explosion; + } + + /** + * + Returns true if the damage is fire based. + */ + public boolean isFireDamage() { + return this.fireDamage; + } + + /** + * + Returns true if the damage is magic based. + */ + public boolean isMagicDamage() { + return this.magicDamage; + } + + /** + * + Returns true if the damage is projectile based. + */ + public boolean isProjectile() { + return this.projectile; + } + + public boolean isUnblockable() { + return this.isUnblockable; + } + + protected DamageSource setDamageAllowedInCreativeMode() { + this.isDamageAllowedInCreativeMode = true; + return this; + } + + protected DamageSource setDamageBypassesArmor() { + this.isUnblockable = true; + this.hungerDamage = 0.0F; + return this; + } + + /** + * + Sets a value indicating whether the damage is absolute (ignores + * modification by potion effects or enchantments), and also clears out hunger + * damage. + */ + protected DamageSource setDamageIsAbsolute() { + this.damageIsAbsolute = true; + this.hungerDamage = 0.0F; + return this; + } + + /** + * + Set whether this damage source will have its damage amount scaled based on + * the current difficulty. + */ + public DamageSource setDifficultyScaled() { + this.difficultyScaled = true; + return this; + } + + public DamageSource setExplosion() { + this.explosion = true; + return this; + } + + /** + * + Define the damage type as fire based. + */ + protected DamageSource setFireDamage() { + this.fireDamage = true; + return this; + } + + /** + * + Define the damage type as magic based. + */ + public DamageSource setMagicDamage() { + this.magicDamage = true; + return this; + } + + /** + * + Define the damage type as projectile based. + */ + public DamageSource setProjectile() { + this.projectile = true; + return this; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EnchantmentNameParts.java b/src/game/java/net/minecraft/util/EnchantmentNameParts.java index b71075d7..f52f8a16 100644 --- a/src/game/java/net/minecraft/util/EnchantmentNameParts.java +++ b/src/game/java/net/minecraft/util/EnchantmentNameParts.java @@ -2,39 +2,43 @@ package net.minecraft.util; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EnchantmentNameParts { private static final EnchantmentNameParts instance = new EnchantmentNameParts(); - private EaglercraftRandom rand = new EaglercraftRandom(); - private String[] namePartsArray = "the elder scrolls klaatu berata niktu xyzzy bless curse light darkness fire air earth water hot dry cold wet ignite snuff embiggen twist shorten stretch fiddle destroy imbue galvanize enchant free limited range of towards inside sphere cube self other ball mental physical grow shrink demon elemental spirit animal creature beast humanoid undead fresh stale " - .split(" "); public static EnchantmentNameParts getInstance() { return instance; } - /**+ - * Randomly generates a new name built up of 3 or 4 randomly - * selected words. + private EaglercraftRandom rand = new EaglercraftRandom(); + + private String[] namePartsArray = "the elder scrolls klaatu berata niktu xyzzy bless curse light darkness fire air earth water hot dry cold wet ignite snuff embiggen twist shorten stretch fiddle destroy imbue galvanize enchant free limited range of towards inside sphere cube self other ball mental physical grow shrink demon elemental spirit animal creature beast humanoid undead fresh stale " + .split(" "); + + /** + * + Randomly generates a new name built up of 3 or 4 randomly selected words. */ public String generateNewRandomName() { int i = this.rand.nextInt(2) + 3; @@ -51,9 +55,8 @@ public class EnchantmentNameParts { return s; } - /**+ - * Resets the underlying random number generator using a given - * seed. + /** + * + Resets the underlying random number generator using a given seed. */ public void reseedRandomGenerator(long seed) { this.rand.setSeed(seed); diff --git a/src/game/java/net/minecraft/util/EntityDamageSource.java b/src/game/java/net/minecraft/util/EntityDamageSource.java index ece9f5a2..a3abab46 100644 --- a/src/game/java/net/minecraft/util/EntityDamageSource.java +++ b/src/game/java/net/minecraft/util/EntityDamageSource.java @@ -5,31 +5,34 @@ import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EntityDamageSource extends DamageSource { protected Entity damageSourceEntity; - /**+ - * Whether this EntityDamageSource is from an entity wearing - * Thorns-enchanted armor. + /** + * + Whether this EntityDamageSource is from an entity wearing Thorns-enchanted + * armor. */ private boolean isThornsDamage = false; @@ -38,24 +41,8 @@ public class EntityDamageSource extends DamageSource { this.damageSourceEntity = damageSourceEntityIn; } - /**+ - * Sets this EntityDamageSource as originating from Thorns armor - */ - public EntityDamageSource setIsThornsDamage() { - this.isThornsDamage = true; - return this; - } - - public boolean getIsThornsDamage() { - return this.isThornsDamage; - } - - public Entity getEntity() { - return this.damageSourceEntity; - } - - /**+ - * Gets the death message that is displayed when the player dies + /** + * + Gets the death message that is displayed when the player dies */ public IChatComponent getDeathMessage(EntityLivingBase entitylivingbase) { ItemStack itemstack = this.damageSourceEntity instanceof EntityLivingBase @@ -71,12 +58,28 @@ public class EntityDamageSource extends DamageSource { new Object[] { entitylivingbase.getDisplayName(), this.damageSourceEntity.getDisplayName() }); } - /**+ - * Return whether this damage source will have its damage amount - * scaled based on the current difficulty. + public Entity getEntity() { + return this.damageSourceEntity; + } + + public boolean getIsThornsDamage() { + return this.isThornsDamage; + } + + /** + * + Return whether this damage source will have its damage amount scaled based + * on the current difficulty. */ public boolean isDifficultyScaled() { return this.damageSourceEntity != null && this.damageSourceEntity instanceof EntityLivingBase && !(this.damageSourceEntity instanceof EntityPlayer); } + + /** + * + Sets this EntityDamageSource as originating from Thorns armor + */ + public EntityDamageSource setIsThornsDamage() { + this.isThornsDamage = true; + return this; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EntityDamageSourceIndirect.java b/src/game/java/net/minecraft/util/EntityDamageSourceIndirect.java index 321f533a..1dec0e06 100644 --- a/src/game/java/net/minecraft/util/EntityDamageSourceIndirect.java +++ b/src/game/java/net/minecraft/util/EntityDamageSourceIndirect.java @@ -4,22 +4,25 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,16 +35,8 @@ public class EntityDamageSourceIndirect extends EntityDamageSource { this.indirectEntity = indirectEntityIn; } - public Entity getSourceOfDamage() { - return this.damageSourceEntity; - } - - public Entity getEntity() { - return this.indirectEntity; - } - - /**+ - * Gets the death message that is displayed when the player dies + /** + * + Gets the death message that is displayed when the player dies */ public IChatComponent getDeathMessage(EntityLivingBase entitylivingbase) { IChatComponent ichatcomponent = this.indirectEntity == null ? this.damageSourceEntity.getDisplayName() @@ -57,4 +52,12 @@ public class EntityDamageSourceIndirect extends EntityDamageSource { itemstack.getChatComponent() }) : new ChatComponentTranslation(s, new Object[] { entitylivingbase.getDisplayName(), ichatcomponent }); } + + public Entity getEntity() { + return this.indirectEntity; + } + + public Entity getSourceOfDamage() { + return this.damageSourceEntity; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EntitySelectors.java b/src/game/java/net/minecraft/util/EntitySelectors.java index 639e5c6e..245aa0b0 100644 --- a/src/game/java/net/minecraft/util/EntitySelectors.java +++ b/src/game/java/net/minecraft/util/EntitySelectors.java @@ -10,56 +10,30 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public final class EntitySelectors { - public static final Predicate selectAnything = new Predicate() { - public boolean apply(Entity entity) { - return entity.isEntityAlive(); - } - }; - /**+ - * Selects only entities which are neither ridden by anything - * nor ride on anything - */ - public static final Predicate IS_STANDALONE = new Predicate() { - public boolean apply(Entity entity) { - return entity.isEntityAlive() && entity.riddenByEntity == null && entity.ridingEntity == null; - } - }; - public static final Predicate selectInventories = new Predicate() { - public boolean apply(Entity entity) { - return entity instanceof IInventory && entity.isEntityAlive(); - } - }; - /**+ - * Selects entities which are either not players or players that - * are not spectating - */ - public static final Predicate NOT_SPECTATING = new Predicate() { - public boolean apply(Entity entity) { - return !(entity instanceof EntityPlayer) || !((EntityPlayer) entity).isSpectator(); - } - }; - public static class ArmoredMob implements Predicate { private final ItemStack armor; @@ -81,4 +55,34 @@ public final class EntitySelectors { } } } + + public static final Predicate selectAnything = new Predicate() { + public boolean apply(Entity entity) { + return entity.isEntityAlive(); + } + }; + /** + * + Selects only entities which are neither ridden by anything nor ride on + * anything + */ + public static final Predicate IS_STANDALONE = new Predicate() { + public boolean apply(Entity entity) { + return entity.isEntityAlive() && entity.riddenByEntity == null && entity.ridingEntity == null; + } + }; + public static final Predicate selectInventories = new Predicate() { + public boolean apply(Entity entity) { + return entity instanceof IInventory && entity.isEntityAlive(); + } + }; + + /** + * + Selects entities which are either not players or players that are not + * spectating + */ + public static final Predicate NOT_SPECTATING = new Predicate() { + public boolean apply(Entity entity) { + return !(entity instanceof EntityPlayer) || !((EntityPlayer) entity).isSpectator(); + } + }; } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EnumChatFormatting.java b/src/game/java/net/minecraft/util/EnumChatFormatting.java index 59328f80..a0cfca87 100644 --- a/src/game/java/net/minecraft/util/EnumChatFormatting.java +++ b/src/game/java/net/minecraft/util/EnumChatFormatting.java @@ -8,22 +8,25 @@ import java.util.regex.Pattern; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,86 +43,18 @@ public enum EnumChatFormatting { public static final EnumChatFormatting[] _VALUES = values(); private static final Map nameMapping = Maps.newHashMap(); - /**+ - * Matches formatting codes that indicate that the client should - * treat the following text as bold, recolored, obfuscated, etc. + /** + * + Matches formatting codes that indicate that the client should treat the + * following text as bold, recolored, obfuscated, etc. */ private static final Pattern formattingCodePattern = Pattern .compile("(?i)" + String.valueOf('\u00a7') + "[0-9A-FK-OR]"); - private final String name; - private final char formattingCode; - private final boolean fancyStyling; - private final String controlString; - private final int colorIndex; + static { + EnumChatFormatting[] types = _VALUES; + for (int i = 0; i < types.length; ++i) { + nameMapping.put(func_175745_c(types[i].name), types[i]); + } - private static String func_175745_c(String parString1) { - return parString1.toLowerCase().replaceAll("[^a-z]", ""); - } - - private EnumChatFormatting(String formattingName, char formattingCodeIn, int colorIndex) { - this(formattingName, formattingCodeIn, false, colorIndex); - } - - private EnumChatFormatting(String formattingName, char formattingCodeIn, boolean fancyStylingIn) { - this(formattingName, formattingCodeIn, fancyStylingIn, -1); - } - - private EnumChatFormatting(String formattingName, char formattingCodeIn, boolean fancyStylingIn, int colorIndex) { - this.name = formattingName; - this.formattingCode = formattingCodeIn; - this.fancyStyling = fancyStylingIn; - this.colorIndex = colorIndex; - this.controlString = "\u00a7" + formattingCodeIn; - } - - /**+ - * Returns the numerical color index that represents this - * formatting - */ - public int getColorIndex() { - return this.colorIndex; - } - - /**+ - * False if this is just changing the color or resetting; true - * otherwise. - */ - public boolean isFancyStyling() { - return this.fancyStyling; - } - - /**+ - * Checks if this is a color code. - */ - public boolean isColor() { - return !this.fancyStyling && this != RESET; - } - - /**+ - * Gets the friendly name of this value. - */ - public String getFriendlyName() { - return this.name().toLowerCase(); - } - - public String toString() { - return this.controlString; - } - - /**+ - * Returns a copy of the given string, with formatting codes - * stripped away. - */ - public static String getTextWithoutFormattingCodes(String text) { - return text == null ? null : formattingCodePattern.matcher(text).replaceAll(""); - } - - /**+ - * Gets a value by its friendly name; null if the given name - * does not map to a defined value. - */ - public static EnumChatFormatting getValueByName(String friendlyName) { - return friendlyName == null ? null : (EnumChatFormatting) nameMapping.get(func_175745_c(friendlyName)); } public static EnumChatFormatting func_175744_a(int parInt1) { @@ -138,11 +73,21 @@ public enum EnumChatFormatting { } } - /**+ - * Gets all the valid values. Args: @param par0: Whether or not - * to include color values. @param par1: Whether or not to - * include fancy-styling values (anything that isn't a color - * value or the "reset" value). + private static String func_175745_c(String parString1) { + return parString1.toLowerCase().replaceAll("[^a-z]", ""); + } + + /** + * + Returns a copy of the given string, with formatting codes stripped away. + */ + public static String getTextWithoutFormattingCodes(String text) { + return text == null ? null : formattingCodePattern.matcher(text).replaceAll(""); + } + + /** + * + Gets all the valid values. Args: @param par0: Whether or not to include + * color values. @param par1: Whether or not to include fancy-styling values + * (anything that isn't a color value or the "reset" value). */ public static Collection getValidValues(boolean parFlag, boolean parFlag2) { ArrayList arraylist = Lists.newArrayList(); @@ -158,11 +103,69 @@ public enum EnumChatFormatting { return arraylist; } - static { - EnumChatFormatting[] types = _VALUES; - for (int i = 0; i < types.length; ++i) { - nameMapping.put(func_175745_c(types[i].name), types[i]); - } + /** + * + Gets a value by its friendly name; null if the given name does not map to a + * defined value. + */ + public static EnumChatFormatting getValueByName(String friendlyName) { + return friendlyName == null ? null : (EnumChatFormatting) nameMapping.get(func_175745_c(friendlyName)); + } + private final String name; + + private final char formattingCode; + + private final boolean fancyStyling; + + private final String controlString; + + private final int colorIndex; + + private EnumChatFormatting(String formattingName, char formattingCodeIn, boolean fancyStylingIn) { + this(formattingName, formattingCodeIn, fancyStylingIn, -1); + } + + private EnumChatFormatting(String formattingName, char formattingCodeIn, boolean fancyStylingIn, int colorIndex) { + this.name = formattingName; + this.formattingCode = formattingCodeIn; + this.fancyStyling = fancyStylingIn; + this.colorIndex = colorIndex; + this.controlString = "\u00a7" + formattingCodeIn; + } + + private EnumChatFormatting(String formattingName, char formattingCodeIn, int colorIndex) { + this(formattingName, formattingCodeIn, false, colorIndex); + } + + /** + * + Returns the numerical color index that represents this formatting + */ + public int getColorIndex() { + return this.colorIndex; + } + + /** + * + Gets the friendly name of this value. + */ + public String getFriendlyName() { + return this.name().toLowerCase(); + } + + /** + * + Checks if this is a color code. + */ + public boolean isColor() { + return !this.fancyStyling && this != RESET; + } + + /** + * + False if this is just changing the color or resetting; true otherwise. + */ + public boolean isFancyStyling() { + return this.fancyStyling; + } + + public String toString() { + return this.controlString; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EnumFacing.java b/src/game/java/net/minecraft/util/EnumFacing.java index ed57a210..bb04e6bf 100644 --- a/src/game/java/net/minecraft/util/EnumFacing.java +++ b/src/game/java/net/minecraft/util/EnumFacing.java @@ -2,28 +2,32 @@ package net.minecraft.util; import java.util.Iterator; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,318 +40,27 @@ public enum EnumFacing implements IStringSerializable { WEST(4, 5, 1, "west", EnumFacing.AxisDirection.NEGATIVE, EnumFacing.Axis.X, new Vec3i(-1, 0, 0)), EAST(5, 4, 3, "east", EnumFacing.AxisDirection.POSITIVE, EnumFacing.Axis.X, new Vec3i(1, 0, 0)); - public static final EnumFacing[] _VALUES = values(); - - private final int index; - private final int opposite; - private final int horizontalIndex; - private final String name; - private final EnumFacing.Axis axis; - private final EnumFacing.AxisDirection axisDirection; - private final Vec3i directionVec; - /**+ - * All facings in D-U-N-S-W-E order - */ - private static final EnumFacing[] VALUES = new EnumFacing[6]; - /**+ - * All Facings with horizontal axis in order S-W-N-E - */ - private static final EnumFacing[] HORIZONTALS = new EnumFacing[4]; - private static final Map NAME_LOOKUP = Maps.newHashMap(); - - private EnumFacing(int indexIn, int oppositeIn, int horizontalIndexIn, String nameIn, - EnumFacing.AxisDirection axisDirectionIn, EnumFacing.Axis axisIn, Vec3i directionVecIn) { - this.index = indexIn; - this.horizontalIndex = horizontalIndexIn; - this.opposite = oppositeIn; - this.name = nameIn; - this.axis = axisIn; - this.axisDirection = axisDirectionIn; - this.directionVec = directionVecIn; - } - - /**+ - * Get the Index of this Facing (0-5). The order is D-U-N-S-W-E - */ - public int getIndex() { - return this.index; - } - - /**+ - * Get the index of this horizontal facing (0-3). The order is - * S-W-N-E - */ - public int getHorizontalIndex() { - return this.horizontalIndex; - } - - /**+ - * Get the AxisDirection of this Facing. - */ - public EnumFacing.AxisDirection getAxisDirection() { - return this.axisDirection; - } - - /**+ - * Get the opposite Facing (e.g. DOWN => UP) - */ - public EnumFacing getOpposite() { - /**+ - * Get a Facing by it's index (0-5). The order is D-U-N-S-W-E. - * Named getFront for legacy reasons. - */ - return getFront(this.opposite); - } - - /**+ - * Rotate this Facing around the given axis clockwise. If this - * facing cannot be rotated around the given axis, returns this - * facing without rotating. - */ - public EnumFacing rotateAround(EnumFacing.Axis axis) { - switch (axis) { - case X: - if (this != WEST && this != EAST) { - return this.rotateX(); - } - - return this; - case Y: - if (this != UP && this != DOWN) { - return this.rotateY(); - } - - return this; - case Z: - if (this != NORTH && this != SOUTH) { - return this.rotateZ(); - } - - return this; - default: - throw new IllegalStateException("Unable to get CW facing for axis " + axis); - } - } - - /**+ - * Rotate this Facing around the Y axis clockwise (NORTH => EAST - * => SOUTH => WEST => NORTH) - */ - public EnumFacing rotateY() { - switch (this) { - case NORTH: - return EAST; - case EAST: - return SOUTH; - case SOUTH: - return WEST; - case WEST: - return NORTH; - default: - throw new IllegalStateException("Unable to get Y-rotated facing of " + this); - } - } - - /**+ - * Rotate this Facing around the X axis (NORTH => DOWN => SOUTH - * => UP => NORTH) - */ - private EnumFacing rotateX() { - switch (this) { - case NORTH: - return DOWN; - case EAST: - case WEST: - default: - throw new IllegalStateException("Unable to get X-rotated facing of " + this); - case SOUTH: - return UP; - case UP: - return NORTH; - case DOWN: - return SOUTH; - } - } - - /**+ - * Rotate this Facing around the Z axis (EAST => DOWN => WEST => - * UP => EAST) - */ - private EnumFacing rotateZ() { - switch (this) { - case EAST: - return DOWN; - case SOUTH: - default: - throw new IllegalStateException("Unable to get Z-rotated facing of " + this); - case WEST: - return UP; - case UP: - return EAST; - case DOWN: - return WEST; - } - } - - /**+ - * Rotate this Facing around the Y axis counter-clockwise (NORTH - * => WEST => SOUTH => EAST => NORTH) - */ - public EnumFacing rotateYCCW() { - switch (this) { - case NORTH: - return WEST; - case EAST: - return NORTH; - case SOUTH: - return EAST; - case WEST: - return SOUTH; - default: - throw new IllegalStateException("Unable to get CCW facing of " + this); - } - } - - /**+ - * Returns a offset that addresses the block in front of this - * facing. - */ - public int getFrontOffsetX() { - return this.axis == EnumFacing.Axis.X ? this.axisDirection.getOffset() : 0; - } - - public int getFrontOffsetY() { - return this.axis == EnumFacing.Axis.Y ? this.axisDirection.getOffset() : 0; - } - - /**+ - * Returns a offset that addresses the block in front of this - * facing. - */ - public int getFrontOffsetZ() { - return this.axis == EnumFacing.Axis.Z ? this.axisDirection.getOffset() : 0; - } - - /**+ - * Same as getName, but does not override the method from Enum. - */ - public String getName2() { - return this.name; - } - - public EnumFacing.Axis getAxis() { - return this.axis; - } - - /**+ - * Get the facing specified by the given name - */ - public static EnumFacing byName(String name) { - return name == null ? null : (EnumFacing) NAME_LOOKUP.get(name.toLowerCase()); - } - - /**+ - * Get a Facing by it's index (0-5). The order is D-U-N-S-W-E. - * Named getFront for legacy reasons. - */ - public static EnumFacing getFront(int index) { - return VALUES[MathHelper.abs_int(index % VALUES.length)]; - } - - /**+ - * Get a Facing by it's horizontal index (0-3). The order is - * S-W-N-E. - */ - public static EnumFacing getHorizontal(int parInt1) { - return HORIZONTALS[MathHelper.abs_int(parInt1 % HORIZONTALS.length)]; - } - - /**+ - * Get the Facing corresponding to the given angle (0-360). An - * angle of 0 is SOUTH, an angle of 90 would be WEST. - */ - public static EnumFacing fromAngle(double angle) { - /**+ - * Get a Facing by it's horizontal index (0-3). The order is - * S-W-N-E. - */ - return getHorizontal(MathHelper.floor_double(angle / 90.0D + 0.5D) & 3); - } - - /**+ - * Choose a random Facing using the given Random - */ - public static EnumFacing random(EaglercraftRandom rand) { - return _VALUES[rand.nextInt(_VALUES.length)]; - } - - public static EnumFacing getFacingFromVector(float parFloat1, float parFloat2, float parFloat3) { - EnumFacing enumfacing = NORTH; - float f = Float.MIN_VALUE; - - EnumFacing[] facings = _VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing1 = facings[i]; - float f1 = parFloat1 * (float) enumfacing1.directionVec.getX() - + parFloat2 * (float) enumfacing1.directionVec.getY() - + parFloat3 * (float) enumfacing1.directionVec.getZ(); - if (f1 > f) { - f = f1; - enumfacing = enumfacing1; - } - } - - return enumfacing; - } - - public String toString() { - return this.name; - } - - public String getName() { - return this.name; - } - - public static EnumFacing func_181076_a(EnumFacing.AxisDirection parAxisDirection, EnumFacing.Axis parAxis) { - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - if (enumfacing.getAxisDirection() == parAxisDirection && enumfacing.getAxis() == parAxis) { - return enumfacing; - } - } - - throw new IllegalArgumentException("No such direction: " + parAxisDirection + " " + parAxis); - } - - /**+ - * Get a normalized Vector that points in the direction of this - * Facing. - */ - public Vec3i getDirectionVec() { - return this.directionVec; - } - - static { - Plane.bootstrap(); - EnumFacing[] facings = EnumFacing._VALUES; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - VALUES[enumfacing.index] = enumfacing; - if (enumfacing.getAxis().isHorizontal()) { - HORIZONTALS[enumfacing.horizontalIndex] = enumfacing; - } - - NAME_LOOKUP.put(enumfacing.getName2().toLowerCase(), enumfacing); - } - - } - public static enum Axis implements Predicate, IStringSerializable { X("x", EnumFacing.Plane.HORIZONTAL), Y("y", EnumFacing.Plane.VERTICAL), Z("z", EnumFacing.Plane.HORIZONTAL); private static final Map NAME_LOOKUP = Maps.newHashMap(); + static { + EnumFacing.Axis[] axis = values(); + for (int i = 0; i < axis.length; ++i) { + NAME_LOOKUP.put(axis[i].getName2().toLowerCase(), axis[i]); + } + + } + + /** + * + Get the facing specified by the given name + */ + public static EnumFacing.Axis byName(String name) { + return name == null ? null : (EnumFacing.Axis) NAME_LOOKUP.get(name.toLowerCase()); + } + private final String name; + private final EnumFacing.Plane plane; private Axis(String name, EnumFacing.Plane plane) { @@ -355,50 +68,35 @@ public enum EnumFacing implements IStringSerializable { this.plane = plane; } - /**+ - * Get the facing specified by the given name - */ - public static EnumFacing.Axis byName(String name) { - return name == null ? null : (EnumFacing.Axis) NAME_LOOKUP.get(name.toLowerCase()); - } - - /**+ - * Same as getName, but does not override the method from Enum. - */ - public String getName2() { - return this.name; - } - - public boolean isVertical() { - return this.plane == EnumFacing.Plane.VERTICAL; - } - - public boolean isHorizontal() { - return this.plane == EnumFacing.Plane.HORIZONTAL; - } - - public String toString() { - return this.name; - } - public boolean apply(EnumFacing enumfacing) { return enumfacing != null && enumfacing.getAxis() == this; } - public EnumFacing.Plane getPlane() { - return this.plane; - } - public String getName() { return this.name; } - static { - EnumFacing.Axis[] axis = values(); - for (int i = 0; i < axis.length; ++i) { - NAME_LOOKUP.put(axis[i].getName2().toLowerCase(), axis[i]); - } + /** + * + Same as getName, but does not override the method from Enum. + */ + public String getName2() { + return this.name; + } + public EnumFacing.Plane getPlane() { + return this.plane; + } + + public boolean isHorizontal() { + return this.plane == EnumFacing.Plane.HORIZONTAL; + } + + public boolean isVertical() { + return this.plane == EnumFacing.Plane.VERTICAL; + } + + public String toString() { + return this.name; } } @@ -427,32 +125,6 @@ public enum EnumFacing implements IStringSerializable { public static enum Plane implements Predicate, Iterable { HORIZONTAL(new EnumFacing[4]), VERTICAL(new EnumFacing[2]); - public final EnumFacing[] facingsArray; - - private Plane(EnumFacing[] facingsArray) { - this.facingsArray = facingsArray; - } - - public EnumFacing[] facings() { - return facingsArray; - } - - /**+ - * Choose a random Facing using the given Random - */ - public EnumFacing random(EaglercraftRandom rand) { - EnumFacing[] aenumfacing = this.facings(); - return aenumfacing[rand.nextInt(aenumfacing.length)]; - } - - public boolean apply(EnumFacing enumfacing) { - return enumfacing != null && enumfacing.getAxis().getPlane() == this; - } - - public Iterator iterator() { - return Iterators.forArray(facingsArray); - } - private static void bootstrap() { HORIZONTAL.facingsArray[0] = EnumFacing.NORTH; HORIZONTAL.facingsArray[1] = EnumFacing.EAST; @@ -461,5 +133,335 @@ public enum EnumFacing implements IStringSerializable { VERTICAL.facingsArray[0] = EnumFacing.UP; VERTICAL.facingsArray[1] = EnumFacing.DOWN; } + + public final EnumFacing[] facingsArray; + + private Plane(EnumFacing[] facingsArray) { + this.facingsArray = facingsArray; + } + + public boolean apply(EnumFacing enumfacing) { + return enumfacing != null && enumfacing.getAxis().getPlane() == this; + } + + public EnumFacing[] facings() { + return facingsArray; + } + + public Iterator iterator() { + return Iterators.forArray(facingsArray); + } + + /** + * + Choose a random Facing using the given Random + */ + public EnumFacing random(EaglercraftRandom rand) { + EnumFacing[] aenumfacing = this.facings(); + return aenumfacing[rand.nextInt(aenumfacing.length)]; + } + } + + public static final EnumFacing[] _VALUES = values(); + /** + * + All facings in D-U-N-S-W-E order + */ + private static final EnumFacing[] VALUES = new EnumFacing[6]; + /** + * + All Facings with horizontal axis in order S-W-N-E + */ + private static final EnumFacing[] HORIZONTALS = new EnumFacing[4]; + private static final Map NAME_LOOKUP = Maps.newHashMap(); + static { + Plane.bootstrap(); + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + VALUES[enumfacing.index] = enumfacing; + if (enumfacing.getAxis().isHorizontal()) { + HORIZONTALS[enumfacing.horizontalIndex] = enumfacing; + } + + NAME_LOOKUP.put(enumfacing.getName2().toLowerCase(), enumfacing); + } + + } + + /** + * + Get the facing specified by the given name + */ + public static EnumFacing byName(String name) { + return name == null ? null : (EnumFacing) NAME_LOOKUP.get(name.toLowerCase()); + } + + /** + * + Get the Facing corresponding to the given angle (0-360). An angle of 0 is + * SOUTH, an angle of 90 would be WEST. + */ + public static EnumFacing fromAngle(double angle) { + /** + * + Get a Facing by it's horizontal index (0-3). The order is S-W-N-E. + */ + return getHorizontal(MathHelper.floor_double(angle / 90.0D + 0.5D) & 3); + } + + public static EnumFacing func_181076_a(EnumFacing.AxisDirection parAxisDirection, EnumFacing.Axis parAxis) { + EnumFacing[] facings = EnumFacing._VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + if (enumfacing.getAxisDirection() == parAxisDirection && enumfacing.getAxis() == parAxis) { + return enumfacing; + } + } + + throw new IllegalArgumentException("No such direction: " + parAxisDirection + " " + parAxis); + } + + public static EnumFacing getFacingFromVector(float parFloat1, float parFloat2, float parFloat3) { + EnumFacing enumfacing = NORTH; + float f = Float.MIN_VALUE; + + EnumFacing[] facings = _VALUES; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing1 = facings[i]; + float f1 = parFloat1 * (float) enumfacing1.directionVec.getX() + + parFloat2 * (float) enumfacing1.directionVec.getY() + + parFloat3 * (float) enumfacing1.directionVec.getZ(); + if (f1 > f) { + f = f1; + enumfacing = enumfacing1; + } + } + + return enumfacing; + } + + /** + * + Get a Facing by it's index (0-5). The order is D-U-N-S-W-E. Named getFront + * for legacy reasons. + */ + public static EnumFacing getFront(int index) { + return VALUES[MathHelper.abs_int(index % VALUES.length)]; + } + + /** + * + Get a Facing by it's horizontal index (0-3). The order is S-W-N-E. + */ + public static EnumFacing getHorizontal(int parInt1) { + return HORIZONTALS[MathHelper.abs_int(parInt1 % HORIZONTALS.length)]; + } + + /** + * + Choose a random Facing using the given Random + */ + public static EnumFacing random(EaglercraftRandom rand) { + return _VALUES[rand.nextInt(_VALUES.length)]; + } + + private final int index; + + private final int opposite; + + private final int horizontalIndex; + + private final String name; + + private final EnumFacing.Axis axis; + + private final EnumFacing.AxisDirection axisDirection; + + private final Vec3i directionVec; + + private EnumFacing(int indexIn, int oppositeIn, int horizontalIndexIn, String nameIn, + EnumFacing.AxisDirection axisDirectionIn, EnumFacing.Axis axisIn, Vec3i directionVecIn) { + this.index = indexIn; + this.horizontalIndex = horizontalIndexIn; + this.opposite = oppositeIn; + this.name = nameIn; + this.axis = axisIn; + this.axisDirection = axisDirectionIn; + this.directionVec = directionVecIn; + } + + public EnumFacing.Axis getAxis() { + return this.axis; + } + + /** + * + Get the AxisDirection of this Facing. + */ + public EnumFacing.AxisDirection getAxisDirection() { + return this.axisDirection; + } + + /** + * + Get a normalized Vector that points in the direction of this Facing. + */ + public Vec3i getDirectionVec() { + return this.directionVec; + } + + /** + * + Returns a offset that addresses the block in front of this facing. + */ + public int getFrontOffsetX() { + return this.axis == EnumFacing.Axis.X ? this.axisDirection.getOffset() : 0; + } + + public int getFrontOffsetY() { + return this.axis == EnumFacing.Axis.Y ? this.axisDirection.getOffset() : 0; + } + + /** + * + Returns a offset that addresses the block in front of this facing. + */ + public int getFrontOffsetZ() { + return this.axis == EnumFacing.Axis.Z ? this.axisDirection.getOffset() : 0; + } + + /** + * + Get the index of this horizontal facing (0-3). The order is S-W-N-E + */ + public int getHorizontalIndex() { + return this.horizontalIndex; + } + + /** + * + Get the Index of this Facing (0-5). The order is D-U-N-S-W-E + */ + public int getIndex() { + return this.index; + } + + public String getName() { + return this.name; + } + + /** + * + Same as getName, but does not override the method from Enum. + */ + public String getName2() { + return this.name; + } + + /** + * + Get the opposite Facing (e.g. DOWN => UP) + */ + public EnumFacing getOpposite() { + /** + * + Get a Facing by it's index (0-5). The order is D-U-N-S-W-E. Named getFront + * for legacy reasons. + */ + return getFront(this.opposite); + } + + /** + * + Rotate this Facing around the given axis clockwise. If this facing cannot + * be rotated around the given axis, returns this facing without rotating. + */ + public EnumFacing rotateAround(EnumFacing.Axis axis) { + switch (axis) { + case X: + if (this != WEST && this != EAST) { + return this.rotateX(); + } + + return this; + case Y: + if (this != UP && this != DOWN) { + return this.rotateY(); + } + + return this; + case Z: + if (this != NORTH && this != SOUTH) { + return this.rotateZ(); + } + + return this; + default: + throw new IllegalStateException("Unable to get CW facing for axis " + axis); + } + } + + /** + * + Rotate this Facing around the X axis (NORTH => DOWN => SOUTH => UP => + * NORTH) + */ + private EnumFacing rotateX() { + switch (this) { + case NORTH: + return DOWN; + case EAST: + case WEST: + default: + throw new IllegalStateException("Unable to get X-rotated facing of " + this); + case SOUTH: + return UP; + case UP: + return NORTH; + case DOWN: + return SOUTH; + } + } + + /** + * + Rotate this Facing around the Y axis clockwise (NORTH => EAST => SOUTH => + * WEST => NORTH) + */ + public EnumFacing rotateY() { + switch (this) { + case NORTH: + return EAST; + case EAST: + return SOUTH; + case SOUTH: + return WEST; + case WEST: + return NORTH; + default: + throw new IllegalStateException("Unable to get Y-rotated facing of " + this); + } + } + + /** + * + Rotate this Facing around the Y axis counter-clockwise (NORTH => WEST => + * SOUTH => EAST => NORTH) + */ + public EnumFacing rotateYCCW() { + switch (this) { + case NORTH: + return WEST; + case EAST: + return NORTH; + case SOUTH: + return EAST; + case WEST: + return SOUTH; + default: + throw new IllegalStateException("Unable to get CCW facing of " + this); + } + } + + /** + * + Rotate this Facing around the Z axis (EAST => DOWN => WEST => UP => EAST) + */ + private EnumFacing rotateZ() { + switch (this) { + case EAST: + return DOWN; + case SOUTH: + default: + throw new IllegalStateException("Unable to get Z-rotated facing of " + this); + case WEST: + return UP; + case UP: + return EAST; + case DOWN: + return WEST; + } + } + + public String toString() { + return this.name; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EnumParticleTypes.java b/src/game/java/net/minecraft/util/EnumParticleTypes.java index a28a8aeb..77a1c0a7 100644 --- a/src/game/java/net/minecraft/util/EnumParticleTypes.java +++ b/src/game/java/net/minecraft/util/EnumParticleTypes.java @@ -6,22 +6,25 @@ import java.util.Map; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,55 +48,8 @@ public enum EnumParticleTypes { public static final EnumParticleTypes[] _VALUES = values(); - private final String particleName; - private final int particleID; - private final boolean shouldIgnoreRange; - private final int argumentCount; private static final Map PARTICLES = Maps.newHashMap(); private static final String[] PARTICLE_NAMES; - - private EnumParticleTypes(String particleNameIn, int particleIDIn, boolean parFlag, int argumentCountIn) { - this.particleName = particleNameIn; - this.particleID = particleIDIn; - this.shouldIgnoreRange = parFlag; - this.argumentCount = argumentCountIn; - } - - private EnumParticleTypes(String particleNameIn, int particleIDIn, boolean parFlag) { - this(particleNameIn, particleIDIn, parFlag, 0); - } - - public static String[] getParticleNames() { - return PARTICLE_NAMES; - } - - public String getParticleName() { - return this.particleName; - } - - public int getParticleID() { - return this.particleID; - } - - public int getArgumentCount() { - return this.argumentCount; - } - - public boolean getShouldIgnoreRange() { - return this.shouldIgnoreRange; - } - - public boolean hasArguments() { - return this.argumentCount > 0; - } - - /**+ - * Gets the relative EnumParticleTypes by id. - */ - public static EnumParticleTypes getParticleFromId(int particleId) { - return (EnumParticleTypes) PARTICLES.get(Integer.valueOf(particleId)); - } - static { ArrayList arraylist = Lists.newArrayList(); @@ -108,4 +64,54 @@ public enum EnumParticleTypes { PARTICLE_NAMES = (String[]) arraylist.toArray(new String[arraylist.size()]); } + + /** + * + Gets the relative EnumParticleTypes by id. + */ + public static EnumParticleTypes getParticleFromId(int particleId) { + return (EnumParticleTypes) PARTICLES.get(Integer.valueOf(particleId)); + } + + public static String[] getParticleNames() { + return PARTICLE_NAMES; + } + + private final String particleName; + + private final int particleID; + + private final boolean shouldIgnoreRange; + + private final int argumentCount; + + private EnumParticleTypes(String particleNameIn, int particleIDIn, boolean parFlag) { + this(particleNameIn, particleIDIn, parFlag, 0); + } + + private EnumParticleTypes(String particleNameIn, int particleIDIn, boolean parFlag, int argumentCountIn) { + this.particleName = particleNameIn; + this.particleID = particleIDIn; + this.shouldIgnoreRange = parFlag; + this.argumentCount = argumentCountIn; + } + + public int getArgumentCount() { + return this.argumentCount; + } + + public int getParticleID() { + return this.particleID; + } + + public String getParticleName() { + return this.particleName; + } + + public boolean getShouldIgnoreRange() { + return this.shouldIgnoreRange; + } + + public boolean hasArguments() { + return this.argumentCount > 0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/EnumWorldBlockLayer.java b/src/game/java/net/minecraft/util/EnumWorldBlockLayer.java index b69d97c0..a9c3694d 100644 --- a/src/game/java/net/minecraft/util/EnumWorldBlockLayer.java +++ b/src/game/java/net/minecraft/util/EnumWorldBlockLayer.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/FoodStats.java b/src/game/java/net/minecraft/util/FoodStats.java index 9590d208..9ea8c544 100644 --- a/src/game/java/net/minecraft/util/FoodStats.java +++ b/src/game/java/net/minecraft/util/FoodStats.java @@ -6,41 +6,51 @@ import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.EnumDifficulty; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FoodStats { - /**+ - * The player's food level. + /** + * + The player's food level. */ private int foodLevel = 20; - /**+ - * The player's food saturation. + /** + * + The player's food saturation. */ private float foodSaturationLevel = 5.0F; private float foodExhaustionLevel; private int foodTimer; private int prevFoodLevel = 20; - /**+ - * Add food stats. + /** + * + adds input to foodExhaustionLevel to a max of 40 + */ + public void addExhaustion(float parFloat1) { + this.foodExhaustionLevel = Math.min(this.foodExhaustionLevel + parFloat1, 40.0F); + } + + /** + * + Add food stats. */ public void addStats(int foodLevelIn, float foodSaturationModifier) { this.foodLevel = Math.min(foodLevelIn + this.foodLevel, 20); @@ -48,15 +58,40 @@ public class FoodStats { this.foodSaturationLevel + (float) foodLevelIn * foodSaturationModifier * 2.0F, (float) this.foodLevel); } - /**+ - * Add food stats. + /** + * + Add food stats. */ public void addStats(ItemFood foodItem, ItemStack parItemStack) { this.addStats(foodItem.getHealAmount(parItemStack), foodItem.getSaturationModifier(parItemStack)); } - /**+ - * Handles the food game logic. + /** + * + Get the player's food level. + */ + public int getFoodLevel() { + return this.foodLevel; + } + + public int getPrevFoodLevel() { + return this.prevFoodLevel; + } + + /** + * + Get the player's food saturation level. + */ + public float getSaturationLevel() { + return this.foodSaturationLevel; + } + + /** + * + Get whether the player must eat food. + */ + public boolean needFood() { + return this.foodLevel < 20; + } + + /** + * + Handles the food game logic. */ public void onUpdate(EntityPlayer player) { EnumDifficulty enumdifficulty = player.worldObj.getDifficulty(); @@ -94,8 +129,8 @@ public class FoodStats { } - /**+ - * Reads the food data for the player. + /** + * + Reads the food data for the player. */ public void readNBT(NBTTagCompound parNBTTagCompound) { if (parNBTTagCompound.hasKey("foodLevel", 99)) { @@ -107,48 +142,6 @@ public class FoodStats { } - /**+ - * Writes the food data for the player. - */ - public void writeNBT(NBTTagCompound parNBTTagCompound) { - parNBTTagCompound.setInteger("foodLevel", this.foodLevel); - parNBTTagCompound.setInteger("foodTickTimer", this.foodTimer); - parNBTTagCompound.setFloat("foodSaturationLevel", this.foodSaturationLevel); - parNBTTagCompound.setFloat("foodExhaustionLevel", this.foodExhaustionLevel); - } - - /**+ - * Get the player's food level. - */ - public int getFoodLevel() { - return this.foodLevel; - } - - public int getPrevFoodLevel() { - return this.prevFoodLevel; - } - - /**+ - * Get whether the player must eat food. - */ - public boolean needFood() { - return this.foodLevel < 20; - } - - /**+ - * adds input to foodExhaustionLevel to a max of 40 - */ - public void addExhaustion(float parFloat1) { - this.foodExhaustionLevel = Math.min(this.foodExhaustionLevel + parFloat1, 40.0F); - } - - /**+ - * Get the player's food saturation level. - */ - public float getSaturationLevel() { - return this.foodSaturationLevel; - } - public void setFoodLevel(int foodLevelIn) { this.foodLevel = foodLevelIn; } @@ -156,4 +149,14 @@ public class FoodStats { public void setFoodSaturationLevel(float foodSaturationLevelIn) { this.foodSaturationLevel = foodSaturationLevelIn; } + + /** + * + Writes the food data for the player. + */ + public void writeNBT(NBTTagCompound parNBTTagCompound) { + parNBTTagCompound.setInteger("foodLevel", this.foodLevel); + parNBTTagCompound.setInteger("foodTickTimer", this.foodTimer); + parNBTTagCompound.setFloat("foodSaturationLevel", this.foodSaturationLevel); + parNBTTagCompound.setFloat("foodExhaustionLevel", this.foodExhaustionLevel); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/FrameTimer.java b/src/game/java/net/minecraft/util/FrameTimer.java index a557b757..d5bd4f68 100644 --- a/src/game/java/net/minecraft/util/FrameTimer.java +++ b/src/game/java/net/minecraft/util/FrameTimer.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,6 +29,10 @@ public class FrameTimer { private int field_181754_c; private int field_181755_d; + public long[] func_181746_c() { + return this.field_181752_a; + } + public void func_181747_a(long parLong1) { this.field_181752_a[this.field_181755_d] = parLong1; ++this.field_181755_d; @@ -58,8 +65,4 @@ public class FrameTimer { public int func_181751_b(int parInt1) { return parInt1 % 240; } - - public long[] func_181746_c() { - return this.field_181752_a; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IChatComponent.java b/src/game/java/net/minecraft/util/IChatComponent.java index 35dc577e..f044601b 100644 --- a/src/game/java/net/minecraft/util/IChatComponent.java +++ b/src/game/java/net/minecraft/util/IChatComponent.java @@ -9,73 +9,52 @@ import org.json.JSONObject; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeCodec; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IChatComponent extends Iterable { - IChatComponent setChatStyle(ChatStyle var1); - - ChatStyle getChatStyle(); - - /**+ - * Appends the given text to the end of this component. - */ - IChatComponent appendText(String var1); - - /**+ - * Appends the given component to the end of this one. - */ - IChatComponent appendSibling(IChatComponent var1); - - /**+ - * Gets the text of this component, without any special - * formatting codes added, for chat. TODO: why is this two - * different methods? - */ - String getUnformattedTextForChat(); - - /**+ - * Get the text of this component, and all child - * components, with all special formatting codes removed. - */ - String getUnformattedText(); - - /**+ - * Gets the text of this component, with formatting codes added - * for rendering. - */ - String getFormattedText(); - - /**+ - * Gets the sibling components of this one. - */ - List getSiblings(); - - /**+ - * Creates a copy of this component. Almost a deep copy, except - * the style is shallow-copied. - */ - IChatComponent createCopy(); - public static class Serializer implements JSONTypeCodec { + /** + * So sorry for this implementation + */ + public static String componentToJson(IChatComponent component) { + if ((component instanceof ChatComponentText) && component.getChatStyle().isEmpty() + && component.getSiblings().isEmpty()) { + String escaped = new JSONObject().put("E", component.getUnformattedTextForChat()).toString(); + return escaped.substring(5, escaped.length() - 1); + } else { + return JSONTypeProvider.serialize(component).toString(); + } + } + + public static IChatComponent jsonToComponent(String json) { + if (json.equals("null")) { + return new ChatComponentText(""); + } + return (IChatComponent) JSONTypeProvider.deserialize(json, IChatComponent.class); + } + public IChatComponent deserialize(Object parJsonElement) throws JSONException { if (parJsonElement instanceof String) { return new ChatComponentText((String) parJsonElement); @@ -159,13 +138,6 @@ public interface IChatComponent extends Iterable { } } - private void serializeChatStyle(ChatStyle style, JSONObject object) { - JSONObject jsonelement = JSONTypeProvider.serialize(style); - for (String entry : jsonelement.keySet()) { - object.put(entry, jsonelement.get(entry)); - } - } - public Object serialize(IChatComponent ichatcomponent) { if (ichatcomponent instanceof ChatComponentText && ichatcomponent.getChatStyle().isEmpty() && ichatcomponent.getSiblings().isEmpty()) { @@ -229,25 +201,12 @@ public interface IChatComponent extends Iterable { } } - /** - * So sorry for this implementation - */ - public static String componentToJson(IChatComponent component) { - if ((component instanceof ChatComponentText) && component.getChatStyle().isEmpty() - && component.getSiblings().isEmpty()) { - String escaped = new JSONObject().put("E", component.getUnformattedTextForChat()).toString(); - return escaped.substring(5, escaped.length() - 1); - } else { - return JSONTypeProvider.serialize(component).toString(); + private void serializeChatStyle(ChatStyle style, JSONObject object) { + JSONObject jsonelement = JSONTypeProvider.serialize(style); + for (String entry : jsonelement.keySet()) { + object.put(entry, jsonelement.get(entry)); } } - - public static IChatComponent jsonToComponent(String json) { - if (json.equals("null")) { - return new ChatComponentText(""); - } - return (IChatComponent) JSONTypeProvider.deserialize(json, IChatComponent.class); - } } public static IChatComponent join(List components) { @@ -267,4 +226,46 @@ public interface IChatComponent extends Iterable { return chatcomponenttext; } + + /** + * + Appends the given component to the end of this one. + */ + IChatComponent appendSibling(IChatComponent var1); + + /** + * + Appends the given text to the end of this component. + */ + IChatComponent appendText(String var1); + + /** + * + Creates a copy of this component. Almost a deep copy, except the style is + * shallow-copied. + */ + IChatComponent createCopy(); + + ChatStyle getChatStyle(); + + /** + * + Gets the text of this component, with formatting codes added for rendering. + */ + String getFormattedText(); + + /** + * + Gets the sibling components of this one. + */ + List getSiblings(); + + /** + * + Get the text of this component, and all child components, with all + * special formatting codes removed. + */ + String getUnformattedText(); + + /** + * + Gets the text of this component, without any special formatting codes + * added, for chat. TODO: why is this two different methods? + */ + String getUnformattedTextForChat(); + + IChatComponent setChatStyle(ChatStyle var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IJsonSerializable.java b/src/game/java/net/minecraft/util/IJsonSerializable.java index 2c6fa5c5..dc751f75 100644 --- a/src/game/java/net/minecraft/util/IJsonSerializable.java +++ b/src/game/java/net/minecraft/util/IJsonSerializable.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,8 +26,8 @@ package net.minecraft.util; public interface IJsonSerializable { void fromJson(Object var1); - /**+ - * Gets the JsonElement that can be serialized. + /** + * + Gets the JsonElement that can be serialized. */ Object getSerializableElement(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IObjectIntIterable.java b/src/game/java/net/minecraft/util/IObjectIntIterable.java index 4fb1c313..3171aea9 100644 --- a/src/game/java/net/minecraft/util/IObjectIntIterable.java +++ b/src/game/java/net/minecraft/util/IObjectIntIterable.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/IProgressUpdate.java b/src/game/java/net/minecraft/util/IProgressUpdate.java index 1fe54f05..3e217048 100644 --- a/src/game/java/net/minecraft/util/IProgressUpdate.java +++ b/src/game/java/net/minecraft/util/IProgressUpdate.java @@ -1,49 +1,52 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IProgressUpdate { - /**+ - * Shows the 'Saving level' string. - */ - void displaySavingString(String var1); - - /**+ - * this string, followed by "working..." and then the "% - * complete" are the 3 lines shown. This resets progress to 0, - * and the WorkingString to "working...". - */ - void resetProgressAndMessage(String var1); - - /**+ - * Displays a string on the loading screen supposed to indicate - * what is being done currently. + /** + * + Displays a string on the loading screen supposed to indicate what is being + * done currently. */ void displayLoadingString(String var1); - /**+ - * Updates the progress bar on the loading screen to the - * specified amount. Args: loadProgress + /** + * + Shows the 'Saving level' string. */ - void setLoadingProgress(int var1); + void displaySavingString(String var1); + + /** + * + this string, followed by "working..." and then the "% complete" are the 3 + * lines shown. This resets progress to 0, and the WorkingString to + * "working...". + */ + void resetProgressAndMessage(String var1); void setDoneWorking(); + + /** + * + Updates the progress bar on the loading screen to the specified amount. + * Args: loadProgress + */ + void setLoadingProgress(int var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IRegistry.java b/src/game/java/net/minecraft/util/IRegistry.java index e05db288..ac7c5225 100644 --- a/src/game/java/net/minecraft/util/IRegistry.java +++ b/src/game/java/net/minecraft/util/IRegistry.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,8 +26,8 @@ package net.minecraft.util; public interface IRegistry extends Iterable { V getObject(K var1); - /**+ - * Register an object on this registry. + /** + * + Register an object on this registry. */ void putObject(K var1, V var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IStringSerializable.java b/src/game/java/net/minecraft/util/IStringSerializable.java index 1265f28f..8880deac 100644 --- a/src/game/java/net/minecraft/util/IStringSerializable.java +++ b/src/game/java/net/minecraft/util/IStringSerializable.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/IThreadListener.java b/src/game/java/net/minecraft/util/IThreadListener.java index b6797e57..b23f09da 100644 --- a/src/game/java/net/minecraft/util/IThreadListener.java +++ b/src/game/java/net/minecraft/util/IThreadListener.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/ITickable.java b/src/game/java/net/minecraft/util/ITickable.java index e63c7273..101c0c40 100644 --- a/src/game/java/net/minecraft/util/ITickable.java +++ b/src/game/java/net/minecraft/util/ITickable.java @@ -1,28 +1,31 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ITickable { - /**+ - * Like the old updateEntity(), except more generic. + /** + * + Like the old updateEntity(), except more generic. */ void update(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IntHashMap.java b/src/game/java/net/minecraft/util/IntHashMap.java index e4e9138b..cbd94c4f 100644 --- a/src/game/java/net/minecraft/util/IntHashMap.java +++ b/src/game/java/net/minecraft/util/IntHashMap.java @@ -1,99 +1,112 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IntHashMap { - /**+ - * An array of HashEntries representing the heads of hash slot - * lists - */ - private transient IntHashMap.Entry[] slots = new IntHashMap.Entry[16]; - private transient int count; - /**+ - * The grow threshold - */ - private int threshold = 12; - /**+ - * The scale factor used to determine when to grow the table - */ - private final float growFactor = 0.75F; + static class Entry { + final int hashEntry; + V valueEntry; + IntHashMap.Entry nextEntry; + final int slotHash; - /**+ - * Makes the passed in integer suitable for hashing by a number - * of shifts + Entry(int parInt1, int parInt2, V parObject, IntHashMap.Entry parEntry) { + this.valueEntry = parObject; + this.nextEntry = parEntry; + this.hashEntry = parInt2; + this.slotHash = parInt1; + } + + public final boolean equals(Object object) { + if (!(object instanceof IntHashMap.Entry)) { + return false; + } else { + IntHashMap.Entry inthashmap$entry = (IntHashMap.Entry) object; + Integer integer = Integer.valueOf(this.getHash()); + Integer integer1 = Integer.valueOf(inthashmap$entry.getHash()); + if (integer == integer1 || integer != null && integer.equals(integer1)) { + Object object1 = this.getValue(); + Object object2 = inthashmap$entry.getValue(); + if (object1 == object2 || object1 != null && object1.equals(object2)) { + return true; + } + } + + return false; + } + } + + public final int getHash() { + return this.hashEntry; + } + + public final V getValue() { + return this.valueEntry; + } + + public final int hashCode() { + return IntHashMap.computeHash(this.hashEntry); + } + + public final String toString() { + return this.getHash() + "=" + this.getValue(); + } + } + + /** + * + Makes the passed in integer suitable for hashing by a number of shifts */ private static int computeHash(int integer) { integer = integer ^ integer >>> 20 ^ integer >>> 12; return integer ^ integer >>> 7 ^ integer >>> 4; } - /**+ - * Computes the index of the slot for the hash and slot count - * passed in. + /** + * + Computes the index of the slot for the hash and slot count passed in. */ private static int getSlotIndex(int hash, int slotCount) { return hash & slotCount - 1; } - /**+ - * Returns the object associated to a key + /** + * + An array of HashEntries representing the heads of hash slot lists */ - public V lookup(int parInt1) { - int i = computeHash(parInt1); + private transient IntHashMap.Entry[] slots = new IntHashMap.Entry[16]; - for (IntHashMap.Entry inthashmap$entry = this.slots[getSlotIndex(i, - this.slots.length)]; inthashmap$entry != null; inthashmap$entry = inthashmap$entry.nextEntry) { - if (inthashmap$entry.hashEntry == parInt1) { - return (V) inthashmap$entry.valueEntry; - } - } + private transient int count; - return (V) null; - } - - /**+ - * Returns true if this hash table contains the specified item. + /** + * + The grow threshold */ - public boolean containsItem(int parInt1) { - return this.lookupEntry(parInt1) != null; - } + private int threshold = 12; - /**+ - * Returns the internal entry for a key + /** + * + The scale factor used to determine when to grow the table */ - final IntHashMap.Entry lookupEntry(int parInt1) { - int i = computeHash(parInt1); + private final float growFactor = 0.75F; - for (IntHashMap.Entry inthashmap$entry = this.slots[getSlotIndex(i, - this.slots.length)]; inthashmap$entry != null; inthashmap$entry = inthashmap$entry.nextEntry) { - if (inthashmap$entry.hashEntry == parInt1) { - return inthashmap$entry; - } - } - - return null; - } - - /**+ - * Adds a key and associated value to this map + /** + * + Adds a key and associated value to this map */ public void addKey(int parInt1, V parObject) { int i = computeHash(parInt1); @@ -109,24 +122,28 @@ public class IntHashMap { this.insert(i, parInt1, parObject, j); } - /**+ - * Increases the number of hash slots + /** + * + Removes all entries from the map */ - private void grow(int parInt1) { + public void clearMap() { IntHashMap.Entry[] ainthashmap$entry = this.slots; - int i = ainthashmap$entry.length; - if (i == 1073741824) { - this.threshold = Integer.MAX_VALUE; - } else { - IntHashMap.Entry[] ainthashmap$entry1 = new IntHashMap.Entry[parInt1]; - this.copyTo(ainthashmap$entry1); - this.slots = ainthashmap$entry1; - this.threshold = (int) ((float) parInt1 * this.growFactor); + + for (int i = 0; i < ainthashmap$entry.length; ++i) { + ainthashmap$entry[i] = null; } + + this.count = 0; } - /**+ - * Copies the hash slots to a new array + /** + * + Returns true if this hash table contains the specified item. + */ + public boolean containsItem(int parInt1) { + return this.lookupEntry(parInt1) != null; + } + + /** + * + Copies the hash slots to a new array */ private void copyTo(IntHashMap.Entry[] parArrayOfEntry) { IntHashMap.Entry[] ainthashmap$entry = this.slots; @@ -152,16 +169,68 @@ public class IntHashMap { } - /**+ - * Removes the specified object from the map and returns it + /** + * + Increases the number of hash slots */ - public V removeObject(int parInt1) { - IntHashMap.Entry inthashmap$entry = this.removeEntry(parInt1); - return (V) (inthashmap$entry == null ? null : inthashmap$entry.valueEntry); + private void grow(int parInt1) { + IntHashMap.Entry[] ainthashmap$entry = this.slots; + int i = ainthashmap$entry.length; + if (i == 1073741824) { + this.threshold = Integer.MAX_VALUE; + } else { + IntHashMap.Entry[] ainthashmap$entry1 = new IntHashMap.Entry[parInt1]; + this.copyTo(ainthashmap$entry1); + this.slots = ainthashmap$entry1; + this.threshold = (int) ((float) parInt1 * this.growFactor); + } } - /**+ - * Removes the specified entry from the map and returns it + /** + * + Adds an object to a slot + */ + private void insert(int parInt1, int parInt2, V parObject, int parInt3) { + IntHashMap.Entry inthashmap$entry = this.slots[parInt3]; + this.slots[parInt3] = new IntHashMap.Entry(parInt1, parInt2, parObject, inthashmap$entry); + if (this.count++ >= this.threshold) { + this.grow(2 * this.slots.length); + } + + } + + /** + * + Returns the object associated to a key + */ + public V lookup(int parInt1) { + int i = computeHash(parInt1); + + for (IntHashMap.Entry inthashmap$entry = this.slots[getSlotIndex(i, + this.slots.length)]; inthashmap$entry != null; inthashmap$entry = inthashmap$entry.nextEntry) { + if (inthashmap$entry.hashEntry == parInt1) { + return (V) inthashmap$entry.valueEntry; + } + } + + return (V) null; + } + + /** + * + Returns the internal entry for a key + */ + final IntHashMap.Entry lookupEntry(int parInt1) { + int i = computeHash(parInt1); + + for (IntHashMap.Entry inthashmap$entry = this.slots[getSlotIndex(i, + this.slots.length)]; inthashmap$entry != null; inthashmap$entry = inthashmap$entry.nextEntry) { + if (inthashmap$entry.hashEntry == parInt1) { + return inthashmap$entry; + } + } + + return null; + } + + /** + * + Removes the specified entry from the map and returns it */ final IntHashMap.Entry removeEntry(int parInt1) { int i = computeHash(parInt1); @@ -189,77 +258,11 @@ public class IntHashMap { return inthashmap$entry1; } - /**+ - * Removes all entries from the map + /** + * + Removes the specified object from the map and returns it */ - public void clearMap() { - IntHashMap.Entry[] ainthashmap$entry = this.slots; - - for (int i = 0; i < ainthashmap$entry.length; ++i) { - ainthashmap$entry[i] = null; - } - - this.count = 0; - } - - /**+ - * Adds an object to a slot - */ - private void insert(int parInt1, int parInt2, V parObject, int parInt3) { - IntHashMap.Entry inthashmap$entry = this.slots[parInt3]; - this.slots[parInt3] = new IntHashMap.Entry(parInt1, parInt2, parObject, inthashmap$entry); - if (this.count++ >= this.threshold) { - this.grow(2 * this.slots.length); - } - - } - - static class Entry { - final int hashEntry; - V valueEntry; - IntHashMap.Entry nextEntry; - final int slotHash; - - Entry(int parInt1, int parInt2, V parObject, IntHashMap.Entry parEntry) { - this.valueEntry = parObject; - this.nextEntry = parEntry; - this.hashEntry = parInt2; - this.slotHash = parInt1; - } - - public final int getHash() { - return this.hashEntry; - } - - public final V getValue() { - return this.valueEntry; - } - - public final boolean equals(Object object) { - if (!(object instanceof IntHashMap.Entry)) { - return false; - } else { - IntHashMap.Entry inthashmap$entry = (IntHashMap.Entry) object; - Integer integer = Integer.valueOf(this.getHash()); - Integer integer1 = Integer.valueOf(inthashmap$entry.getHash()); - if (integer == integer1 || integer != null && integer.equals(integer1)) { - Object object1 = this.getValue(); - Object object2 = inthashmap$entry.getValue(); - if (object1 == object2 || object1 != null && object1.equals(object2)) { - return true; - } - } - - return false; - } - } - - public final int hashCode() { - return IntHashMap.computeHash(this.hashEntry); - } - - public final String toString() { - return this.getHash() + "=" + this.getValue(); - } + public V removeObject(int parInt1) { + IntHashMap.Entry inthashmap$entry = this.removeEntry(parInt1); + return (V) (inthashmap$entry == null ? null : inthashmap$entry.valueEntry); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/IntegerCache.java b/src/game/java/net/minecraft/util/IntegerCache.java index 9083309f..7d860941 100644 --- a/src/game/java/net/minecraft/util/IntegerCache.java +++ b/src/game/java/net/minecraft/util/IntegerCache.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,10 +26,6 @@ package net.minecraft.util; public class IntegerCache { private static final Integer[] field_181757_a = new Integer['\uffff']; - public static Integer func_181756_a(int parInt1) { - return parInt1 > 0 && parInt1 < field_181757_a.length ? field_181757_a[parInt1] : Integer.valueOf(parInt1); - } - static { int i = 0; @@ -35,4 +34,8 @@ public class IntegerCache { } } + + public static Integer func_181756_a(int parInt1) { + return parInt1 > 0 && parInt1 < field_181757_a.length ? field_181757_a[parInt1] : Integer.valueOf(parInt1); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/JsonSerializableSet.java b/src/game/java/net/minecraft/util/JsonSerializableSet.java index 4ac4b282..bd75ff5a 100644 --- a/src/game/java/net/minecraft/util/JsonSerializableSet.java +++ b/src/game/java/net/minecraft/util/JsonSerializableSet.java @@ -7,32 +7,39 @@ import org.json.JSONArray; import com.google.common.collect.ForwardingSet; import com.google.common.collect.Sets; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JsonSerializableSet extends ForwardingSet implements IJsonSerializable { - /**+ - * The set for this ForwardingSet to forward methods to. + /** + * + The set for this ForwardingSet to forward methods to. */ private final Set underlyingSet = Sets.newHashSet(); + protected Set delegate() { + return this.underlyingSet; + } + public void fromJson(Object jsonelement) { if (jsonelement instanceof JSONArray) { JSONArray arr = (JSONArray) jsonelement; @@ -43,8 +50,8 @@ public class JsonSerializableSet extends ForwardingSet implements IJsonS } - /**+ - * Gets the JsonElement that can be serialized. + /** + * + Gets the JsonElement that can be serialized. */ public Object getSerializableElement() { JSONArray jsonarray = new JSONArray(); @@ -55,8 +62,4 @@ public class JsonSerializableSet extends ForwardingSet implements IJsonS return jsonarray; } - - protected Set delegate() { - return this.underlyingSet; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/LazyLoadBase.java b/src/game/java/net/minecraft/util/LazyLoadBase.java index 9ff2de51..87faec89 100644 --- a/src/game/java/net/minecraft/util/LazyLoadBase.java +++ b/src/game/java/net/minecraft/util/LazyLoadBase.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/LoggingPrintStream.java b/src/game/java/net/minecraft/util/LoggingPrintStream.java index 70fedb6e..d22e258a 100644 --- a/src/game/java/net/minecraft/util/LoggingPrintStream.java +++ b/src/game/java/net/minecraft/util/LoggingPrintStream.java @@ -7,22 +7,25 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,14 +42,6 @@ public class LoggingPrintStream extends PrintStream { this.err = err; } - public void println(String s) { - this.logString(s); - } - - public void println(Object parObject) { - this.logString(String.valueOf(parObject)); - } - private void logString(String string) { String callingClass = PlatformRuntime.getCallingClass(3); if (callingClass == null) { @@ -63,4 +58,12 @@ public class LoggingPrintStream extends PrintStream { } } } + + public void println(Object parObject) { + this.logString(String.valueOf(parObject)); + } + + public void println(String s) { + this.logString(s); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/LongHashMap.java b/src/game/java/net/minecraft/util/LongHashMap.java index 554f9521..a5910bc7 100644 --- a/src/game/java/net/minecraft/util/LongHashMap.java +++ b/src/game/java/net/minecraft/util/LongHashMap.java @@ -1,113 +1,130 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LongHashMap { - /**+ - * the array of all elements in the hash - */ - private transient LongHashMap.Entry[] hashArray = new LongHashMap.Entry[4096]; - private transient int numHashElements; - private int mask; - /**+ - * the maximum amount of elements in the hash (probably 3/4 the - * size due to meh hashing function) - */ - private int capacity = 3072; - /**+ - * percent of the hasharray that can be used without hash - * colliding probably - */ - private final float percentUseable = 0.75F; - private transient volatile int modCount; + static class Entry { + final long key; + V value; + LongHashMap.Entry nextEntry; + final int hash; - public LongHashMap() { - this.mask = this.hashArray.length - 1; + Entry(int parInt1, long parLong1, V parObject, LongHashMap.Entry parEntry) { + this.value = parObject; + this.nextEntry = parEntry; + this.key = parLong1; + this.hash = parInt1; + } + + public final boolean equals(Object object) { + if (!(object instanceof LongHashMap.Entry)) { + return false; + } else { + LongHashMap.Entry longhashmap$entry = (LongHashMap.Entry) object; + Long olong = Long.valueOf(this.getKey()); + Long olong1 = Long.valueOf(longhashmap$entry.getKey()); + if (olong == olong1 || olong != null && olong.equals(olong1)) { + Object object1 = this.getValue(); + Object object2 = longhashmap$entry.getValue(); + if (object1 == object2 || object1 != null && object1.equals(object2)) { + return true; + } + } + + return false; + } + } + + public final long getKey() { + return this.key; + } + + public final V getValue() { + return this.value; + } + + public final int hashCode() { + return LongHashMap.getHashedKey(this.key); + } + + public final String toString() { + return this.getKey() + "=" + this.getValue(); + } } - /**+ - * returns the hashed key given the original key + /** + * + returns the hashed key given the original key */ private static int getHashedKey(long originalKey) { - /**+ - * the hash function + /** + * + the hash function */ return hash((int) (originalKey ^ originalKey >>> 32)); } - /**+ - * the hash function + /** + * + gets the index in the hash given the array length and the hashed key + */ + private static int getHashIndex(int parInt1, int parInt2) { + return parInt1 & parInt2; + } + + /** + * + the hash function */ private static int hash(int integer) { integer = integer ^ integer >>> 20 ^ integer >>> 12; return integer ^ integer >>> 7 ^ integer >>> 4; } - /**+ - * gets the index in the hash given the array length and the - * hashed key + /** + * + the array of all elements in the hash */ - private static int getHashIndex(int parInt1, int parInt2) { - return parInt1 & parInt2; - } + private transient LongHashMap.Entry[] hashArray = new LongHashMap.Entry[4096]; + private transient int numHashElements; - public int getNumHashElements() { - return this.numHashElements; - } + private int mask; - /**+ - * get the value from the map given the key + /** + * + the maximum amount of elements in the hash (probably 3/4 the size due to + * meh hashing function) */ - public V getValueByKey(long parLong1) { - int i = getHashedKey(parLong1); + private int capacity = 3072; - for (LongHashMap.Entry longhashmap$entry = this.hashArray[getHashIndex(i, - this.mask)]; longhashmap$entry != null; longhashmap$entry = longhashmap$entry.nextEntry) { - if (longhashmap$entry.key == parLong1) { - return (V) longhashmap$entry.value; - } - } + /** + * + percent of the hasharray that can be used without hash colliding probably + */ + private final float percentUseable = 0.75F; - return (V) null; + private transient volatile int modCount; + + public LongHashMap() { + this.mask = this.hashArray.length - 1; } - public boolean containsItem(long parLong1) { - return this.getEntry(parLong1) != null; - } - - final LongHashMap.Entry getEntry(long parLong1) { - int i = getHashedKey(parLong1); - - for (LongHashMap.Entry longhashmap$entry = this.hashArray[getHashIndex(i, - this.mask)]; longhashmap$entry != null; longhashmap$entry = longhashmap$entry.nextEntry) { - if (longhashmap$entry.key == parLong1) { - return longhashmap$entry; - } - } - - return null; - } - - /**+ - * Add a key-value pair. + /** + * + Add a key-value pair. */ public void add(long parLong1, V parObject) { int i = getHashedKey(parLong1); @@ -124,25 +141,12 @@ public class LongHashMap { this.createKey(i, parLong1, parObject, j); } - /**+ - * resizes the table - */ - private void resizeTable(int parInt1) { - LongHashMap.Entry[] alonghashmap$entry = this.hashArray; - int i = alonghashmap$entry.length; - if (i == 1073741824) { - this.capacity = Integer.MAX_VALUE; - } else { - LongHashMap.Entry[] alonghashmap$entry1 = new LongHashMap.Entry[parInt1]; - this.copyHashTableTo(alonghashmap$entry1); - this.hashArray = alonghashmap$entry1; - this.mask = this.hashArray.length - 1; - this.capacity = (int) ((float) parInt1 * this.percentUseable); - } + public boolean containsItem(long parLong1) { + return this.getEntry(parLong1) != null; } - /**+ - * copies the hash table to the specified array + /** + * + copies the hash table to the specified array */ private void copyHashTableTo(LongHashMap.Entry[] parArrayOfEntry) { LongHashMap.Entry[] alonghashmap$entry = this.hashArray; @@ -168,16 +172,61 @@ public class LongHashMap { } - /**+ - * calls the removeKey method and returns removed object + /** + * + creates the key in the hash table + */ + private void createKey(int parInt1, long parLong1, V parObject, int parInt2) { + LongHashMap.Entry longhashmap$entry = this.hashArray[parInt2]; + this.hashArray[parInt2] = new LongHashMap.Entry(parInt1, parLong1, parObject, longhashmap$entry); + if (this.numHashElements++ >= this.capacity) { + this.resizeTable(2 * this.hashArray.length); + } + + } + + final LongHashMap.Entry getEntry(long parLong1) { + int i = getHashedKey(parLong1); + + for (LongHashMap.Entry longhashmap$entry = this.hashArray[getHashIndex(i, + this.mask)]; longhashmap$entry != null; longhashmap$entry = longhashmap$entry.nextEntry) { + if (longhashmap$entry.key == parLong1) { + return longhashmap$entry; + } + } + + return null; + } + + public int getNumHashElements() { + return this.numHashElements; + } + + /** + * + get the value from the map given the key + */ + public V getValueByKey(long parLong1) { + int i = getHashedKey(parLong1); + + for (LongHashMap.Entry longhashmap$entry = this.hashArray[getHashIndex(i, + this.mask)]; longhashmap$entry != null; longhashmap$entry = longhashmap$entry.nextEntry) { + if (longhashmap$entry.key == parLong1) { + return (V) longhashmap$entry.value; + } + } + + return (V) null; + } + + /** + * + calls the removeKey method and returns removed object */ public V remove(long parLong1) { LongHashMap.Entry longhashmap$entry = this.removeKey(parLong1); return (V) (longhashmap$entry == null ? null : longhashmap$entry.value); } - /**+ - * removes the key from the hash linked list + /** + * + removes the key from the hash linked list */ final LongHashMap.Entry removeKey(long parLong1) { int i = getHashedKey(parLong1); @@ -206,64 +255,20 @@ public class LongHashMap { return longhashmap$entry1; } - /**+ - * creates the key in the hash table + /** + * + resizes the table */ - private void createKey(int parInt1, long parLong1, V parObject, int parInt2) { - LongHashMap.Entry longhashmap$entry = this.hashArray[parInt2]; - this.hashArray[parInt2] = new LongHashMap.Entry(parInt1, parLong1, parObject, longhashmap$entry); - if (this.numHashElements++ >= this.capacity) { - this.resizeTable(2 * this.hashArray.length); - } - - } - - static class Entry { - final long key; - V value; - LongHashMap.Entry nextEntry; - final int hash; - - Entry(int parInt1, long parLong1, V parObject, LongHashMap.Entry parEntry) { - this.value = parObject; - this.nextEntry = parEntry; - this.key = parLong1; - this.hash = parInt1; - } - - public final long getKey() { - return this.key; - } - - public final V getValue() { - return this.value; - } - - public final boolean equals(Object object) { - if (!(object instanceof LongHashMap.Entry)) { - return false; - } else { - LongHashMap.Entry longhashmap$entry = (LongHashMap.Entry) object; - Long olong = Long.valueOf(this.getKey()); - Long olong1 = Long.valueOf(longhashmap$entry.getKey()); - if (olong == olong1 || olong != null && olong.equals(olong1)) { - Object object1 = this.getValue(); - Object object2 = longhashmap$entry.getValue(); - if (object1 == object2 || object1 != null && object1.equals(object2)) { - return true; - } - } - - return false; - } - } - - public final int hashCode() { - return LongHashMap.getHashedKey(this.key); - } - - public final String toString() { - return this.getKey() + "=" + this.getValue(); + private void resizeTable(int parInt1) { + LongHashMap.Entry[] alonghashmap$entry = this.hashArray; + int i = alonghashmap$entry.length; + if (i == 1073741824) { + this.capacity = Integer.MAX_VALUE; + } else { + LongHashMap.Entry[] alonghashmap$entry1 = new LongHashMap.Entry[parInt1]; + this.copyHashTableTo(alonghashmap$entry1); + this.hashArray = alonghashmap$entry1; + this.mask = this.hashArray.length - 1; + this.capacity = (int) ((float) parInt1 * this.percentUseable); } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/MapPopulator.java b/src/game/java/net/minecraft/util/MapPopulator.java index 3607637a..79f1de68 100644 --- a/src/game/java/net/minecraft/util/MapPopulator.java +++ b/src/game/java/net/minecraft/util/MapPopulator.java @@ -6,30 +6,33 @@ import java.util.NoSuchElementException; import com.google.common.collect.Maps; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapPopulator { public static Map createMap(Iterable keys, Iterable values) { - /**+ - * Populate the given Map with the given keys and values. + /** + * + Populate the given Map with the given keys and values. */ return populateMap(keys, values, Maps.newLinkedHashMap()); } diff --git a/src/game/java/net/minecraft/util/MathHelper.java b/src/game/java/net/minecraft/util/MathHelper.java index 3dd8d860..3c35d5e8 100644 --- a/src/game/java/net/minecraft/util/MathHelper.java +++ b/src/game/java/net/minecraft/util/MathHelper.java @@ -3,31 +3,34 @@ package net.minecraft.util; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MathHelper { public static final float SQRT_2 = sqrt_float(2.0F); - /**+ - * A table of sin values computed from 0 (inclusive) to 2*pi - * (exclusive), with steps of 2*PI / 65536. + /** + * + A table of sin values computed from 0 (inclusive) to 2*pi (exclusive), with + * steps of 2*PI / 65536. */ private static final float[] SIN_TABLE = new float[65536]; private static final int[] multiplyDeBruijnBitPosition; @@ -35,116 +38,39 @@ public class MathHelper { private static final double[] field_181164_e; private static final double[] field_181165_f; - /**+ - * sin looked up in a table - */ - public static float sin(float parFloat1) { - return SIN_TABLE[(int) (parFloat1 * 10430.378F) & '\uffff']; - } + static { + for (int i = 0; i < 65536; ++i) { + SIN_TABLE[i] = (float) Math.sin((double) i * 3.141592653589793D * 2.0D / 65536.0D); + } - /**+ - * cos looked up in the sin table with the appropriate offset - */ - public static float cos(float value) { - return SIN_TABLE[(int) (value * 10430.378F + 16384.0F) & '\uffff']; - } + multiplyDeBruijnBitPosition = new int[] { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, + 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; + field_181163_d = Double.longBitsToDouble(4805340802404319232L); + field_181164_e = new double[257]; + field_181165_f = new double[257]; - public static float sqrt_float(float value) { - return (float) Math.sqrt((double) value); - } + for (int j = 0; j < 257; ++j) { + double d0 = (double) j / 256.0D; + double d1 = Math.asin(d0); + field_181165_f[j] = Math.cos(d1); + field_181164_e[j] = d1; + } - public static float sqrt_double(double value) { - return (float) Math.sqrt(value); - } - - /**+ - * Returns the greatest integer less than or equal to the float - * argument - */ - public static int floor_float(float value) { - int i = (int) value; - return value < (float) i ? i - 1 : i; - } - - /**+ - * returns par0 cast as an int, and no greater than - * Integer.MAX_VALUE-1024 - */ - public static int truncateDoubleToInt(double value) { - return (int) (value + 1024.0D) - 1024; - } - - /**+ - * Returns the greatest integer less than or equal to the double - * argument - */ - public static int floor_double(double value) { - int i = (int) value; - return value < (double) i ? i - 1 : i; - } - - /**+ - * Long version of floor_double - */ - public static long floor_double_long(double value) { - long i = (long) value; - return value < (double) i ? i - 1L : i; - } - - public static int func_154353_e(double value) { - return (int) (value >= 0.0D ? value : -value + 1.0D); } public static float abs(float value) { return value >= 0.0F ? value : -value; } - /**+ - * Returns the unsigned value of an int. + /** + * + Returns the unsigned value of an int. */ public static int abs_int(int value) { return value >= 0 ? value : -value; } - public static int ceiling_float_int(float value) { - int i = (int) value; - return value > (float) i ? i + 1 : i; - } - - public static int ceiling_double_int(double value) { - int i = (int) value; - return value > (double) i ? i + 1 : i; - } - - /**+ - * Returns the value of the first parameter, clamped to be - * within the lower and upper limits given by the second and - * third parameters. - */ - public static int clamp_int(int num, int min, int max) { - return num < min ? min : (num > max ? max : num); - } - - /**+ - * Returns the value of the first parameter, clamped to be - * within the lower and upper limits given by the second and - * third parameters - */ - public static float clamp_float(float num, float min, float max) { - return num < min ? min : (num > max ? max : num); - } - - public static double clamp_double(double num, double min, double max) { - return num < min ? min : (num > max ? max : num); - } - - public static double denormalizeClamp(double parDouble1, double parDouble2, double parDouble3) { - return parDouble3 < 0.0D ? parDouble1 - : (parDouble3 > 1.0D ? parDouble2 : parDouble1 + (parDouble2 - parDouble1) * parDouble3); - } - - /**+ - * Maximum of the absolute value of two numbers. + /** + * + Maximum of the absolute value of two numbers. */ public static double abs_max(double parDouble1, double parDouble2) { if (parDouble1 < 0.0D) { @@ -158,26 +84,6 @@ public class MathHelper { return parDouble1 > parDouble2 ? parDouble1 : parDouble2; } - /**+ - * Buckets an integer with specifed bucket sizes. Args: i, - * bucketSize - */ - public static int bucketInt(int parInt1, int parInt2) { - return parInt1 < 0 ? -((-parInt1 - 1) / parInt2) - 1 : parInt1 / parInt2; - } - - public static int getRandomIntegerInRange(EaglercraftRandom parRandom, int parInt1, int parInt2) { - return parInt1 >= parInt2 ? parInt1 : parRandom.nextInt(parInt2 - parInt1 + 1) + parInt1; - } - - public static float randomFloatClamp(EaglercraftRandom parRandom, float parFloat1, float parFloat2) { - return parFloat1 >= parFloat2 ? parFloat1 : parRandom.nextFloat() * (parFloat2 - parFloat1) + parFloat1; - } - - public static double getRandomDoubleInRange(EaglercraftRandom parRandom, double parDouble1, double parDouble2) { - return parDouble1 >= parDouble2 ? parDouble1 : parRandom.nextDouble() * (parDouble2 - parDouble1) + parDouble1; - } - public static double average(long[] values) { long i = 0L; @@ -188,132 +94,111 @@ public class MathHelper { return (double) i / (double) values.length; } - public static boolean epsilonEquals(float parFloat1, float parFloat2) { - return abs(parFloat2 - parFloat1) < 1.0E-5F; - } - - public static int normalizeAngle(int parInt1, int parInt2) { - return (parInt1 % parInt2 + parInt2) % parInt2; - } - - /**+ - * the angle is reduced to an angle between -180 and +180 by - * mod, and a 360 check + /** + * + Buckets an integer with specifed bucket sizes. Args: i, bucketSize */ - public static float wrapAngleTo180_float(float value) { - value = value % 360.0F; - if (value >= 180.0F) { - value -= 360.0F; - } - - if (value < -180.0F) { - value += 360.0F; - } - - return value; + public static int bucketInt(int parInt1, int parInt2) { + return parInt1 < 0 ? -((-parInt1 - 1) / parInt2) - 1 : parInt1 / parInt2; } - /**+ - * the angle is reduced to an angle between -180 and +180 by - * mod, and a 360 check + /** + * + Efficiently calculates the floor of the base-2 log of an integer value. + * This is effectively the index of the highest bit that is set. For example, if + * the number in binary is 0...100101, this will return 5. */ - public static double wrapAngleTo180_double(double value) { - value = value % 360.0D; - if (value >= 180.0D) { - value -= 360.0D; - } - - if (value < -180.0D) { - value += 360.0D; - } - - return value; + public static int calculateLogBaseTwo(int value) { + /** + * + Uses a B(2, 5) De Bruijn sequence and a lookup table to efficiently + * calculate the log-base-two of the given value. Optimized for cases where the + * input value is a power-of-two. If the input value is not a power-of-two, then + * subtract 1 from the return value. + */ + return calculateLogBaseTwoDeBruijn(value) - (isPowerOfTwo(value) ? 0 : 1); } - /**+ - * parses the string as integer or returns the second parameter - * if it fails - */ - public static int parseIntWithDefault(String parString1, int parInt1) { - try { - return Integer.parseInt(parString1); - } catch (Throwable var3) { - return parInt1; - } - } - - /**+ - * parses the string as integer or returns the second parameter - * if it fails. this value is capped to par2 - */ - public static int parseIntWithDefaultAndMax(String parString1, int parInt1, int parInt2) { - return Math.max(parInt2, parseIntWithDefault(parString1, parInt1)); - } - - /**+ - * parses the string as double or returns the second parameter - * if it fails. - */ - public static double parseDoubleWithDefault(String parString1, double parDouble1) { - try { - return Double.parseDouble(parString1); - } catch (Throwable var4) { - return parDouble1; - } - } - - public static double parseDoubleWithDefaultAndMax(String parString1, double parDouble1, double parDouble2) { - return Math.max(parDouble2, parseDoubleWithDefault(parString1, parDouble1)); - } - - /**+ - * Returns the input value rounded up to the next highest power - * of two. - */ - public static int roundUpToPowerOfTwo(int value) { - int i = value - 1; - i = i | i >> 1; - i = i | i >> 2; - i = i | i >> 4; - i = i | i >> 8; - i = i | i >> 16; - return i + 1; - } - - /**+ - * Is the given value a power of two? (1, 2, 4, 8, 16, ...) - */ - private static boolean isPowerOfTwo(int value) { - return value != 0 && (value & value - 1) == 0; - } - - /**+ - * Uses a B(2, 5) De Bruijn sequence and a lookup table to - * efficiently calculate the log-base-two of the given value. - * Optimized for cases where the input value is a power-of-two. - * If the input value is not a power-of-two, then subtract 1 - * from the return value. + /** + * + Uses a B(2, 5) De Bruijn sequence and a lookup table to efficiently + * calculate the log-base-two of the given value. Optimized for cases where the + * input value is a power-of-two. If the input value is not a power-of-two, then + * subtract 1 from the return value. */ private static int calculateLogBaseTwoDeBruijn(int value) { value = isPowerOfTwo(value) ? value : roundUpToPowerOfTwo(value); return multiplyDeBruijnBitPosition[(int) ((long) value * 125613361L >> 27) & 31]; } - /**+ - * Efficiently calculates the floor of the base-2 log of an - * integer value. This is effectively the index of the highest - * bit that is set. For example, if the number in binary is - * 0...100101, this will return 5. + public static int ceiling_double_int(double value) { + int i = (int) value; + return value > (double) i ? i + 1 : i; + } + + public static int ceiling_float_int(float value) { + int i = (int) value; + return value > (float) i ? i + 1 : i; + } + + public static double clamp_double(double num, double min, double max) { + return num < min ? min : (num > max ? max : num); + } + + /** + * + Returns the value of the first parameter, clamped to be within the lower + * and upper limits given by the second and third parameters */ - public static int calculateLogBaseTwo(int value) { - /**+ - * Uses a B(2, 5) De Bruijn sequence and a lookup table to - * efficiently calculate the log-base-two of the given value. - * Optimized for cases where the input value is a power-of-two. - * If the input value is not a power-of-two, then subtract 1 - * from the return value. - */ - return calculateLogBaseTwoDeBruijn(value) - (isPowerOfTwo(value) ? 0 : 1); + public static float clamp_float(float num, float min, float max) { + return num < min ? min : (num > max ? max : num); + } + + /** + * + Returns the value of the first parameter, clamped to be within the lower + * and upper limits given by the second and third parameters. + */ + public static int clamp_int(int num, int min, int max) { + return num < min ? min : (num > max ? max : num); + } + + /** + * + cos looked up in the sin table with the appropriate offset + */ + public static float cos(float value) { + return SIN_TABLE[(int) (value * 10430.378F + 16384.0F) & '\uffff']; + } + + public static double denormalizeClamp(double parDouble1, double parDouble2, double parDouble3) { + return parDouble3 < 0.0D ? parDouble1 + : (parDouble3 > 1.0D ? parDouble2 : parDouble1 + (parDouble2 - parDouble1) * parDouble3); + } + + public static boolean epsilonEquals(float parFloat1, float parFloat2) { + return abs(parFloat2 - parFloat1) < 1.0E-5F; + } + + /** + * + Returns the greatest integer less than or equal to the double argument + */ + public static int floor_double(double value) { + int i = (int) value; + return value < (double) i ? i - 1 : i; + } + + /** + * + Long version of floor_double + */ + public static long floor_double_long(double value) { + long i = (long) value; + return value < (double) i ? i - 1L : i; + } + + /** + * + Returns the greatest integer less than or equal to the float argument + */ + public static int floor_float(float value) { + int i = (int) value; + return value < (float) i ? i - 1 : i; + } + + public static int func_154353_e(double value) { + return (int) (value >= 0.0D ? value : -value + 1.0D); } public static int func_154354_b(int parInt1, int parInt2) { @@ -331,17 +216,17 @@ public class MathHelper { } } - public static int func_180183_b(float parFloat1, float parFloat2, float parFloat3) { - return func_180181_b(floor_float(parFloat1 * 255.0F), floor_float(parFloat2 * 255.0F), - floor_float(parFloat3 * 255.0F)); - } - public static int func_180181_b(int parInt1, int parInt2, int parInt3) { int i = (parInt1 << 8) + parInt2; i = (i << 8) + parInt3; return i; } + public static int func_180183_b(float parFloat1, float parFloat2, float parFloat3) { + return func_180181_b(floor_float(parFloat1 * 255.0F), floor_float(parFloat2 * 255.0F), + floor_float(parFloat3 * 255.0F)); + } + public static int func_180188_d(int parInt1, int parInt2) { int i = (parInt1 & 16711680) >> 16; int j = (parInt2 & 16711680) >> 16; @@ -355,30 +240,6 @@ public class MathHelper { return parInt1 & -16777216 | k1 << 16 | l1 << 8 | i2; } - public static double func_181162_h(double parDouble1) { - return parDouble1 - Math.floor(parDouble1); - } - - public static long getPositionRandom(Vec3i pos) { - return getCoordinateRandom(pos.getX(), pos.getY(), pos.getZ()); - } - - public static long getCoordinateRandom(int x, int y, int z) { - long i = (long) (x * 3129871) ^ (long) z * 116129781L ^ (long) y; - i = i * i * 42317861L + i * 11L; - return i; - } - - public static EaglercraftUUID getRandomUuid(EaglercraftRandom rand) { - long i = rand.nextLong() & -61441L | 16384L; - long j = rand.nextLong() & 4611686018427387903L | Long.MIN_VALUE; - return new EaglercraftUUID(i, j); - } - - public static double func_181160_c(double parDouble1, double parDouble2, double parDouble3) { - return (parDouble1 - parDouble2) / (parDouble3 - parDouble2); - } - public static double func_181159_b(double parDouble1, double parDouble2) { double d0 = parDouble2 * parDouble2 + parDouble1 * parDouble1; if (Double.isNaN(d0)) { @@ -428,6 +289,10 @@ public class MathHelper { } } + public static double func_181160_c(double parDouble1, double parDouble2, double parDouble3) { + return (parDouble1 - parDouble2) / (parDouble3 - parDouble2); + } + public static double func_181161_i(double parDouble1) { double d0 = 0.5D * parDouble1; long i = Double.doubleToRawLongBits(parDouble1); @@ -437,6 +302,10 @@ public class MathHelper { return parDouble1; } + public static double func_181162_h(double parDouble1) { + return parDouble1 - Math.floor(parDouble1); + } + public static int func_181758_c(float parFloat1, float parFloat2, float parFloat3) { int i = (int) (parFloat1 * 6.0F) % 6; float f = parFloat1 * 6.0F - (float) i; @@ -488,23 +357,145 @@ public class MathHelper { return j << 16 | k << 8 | l; } - static { - for (int i = 0; i < 65536; ++i) { - SIN_TABLE[i] = (float) Math.sin((double) i * 3.141592653589793D * 2.0D / 65536.0D); + public static long getCoordinateRandom(int x, int y, int z) { + long i = (long) (x * 3129871) ^ (long) z * 116129781L ^ (long) y; + i = i * i * 42317861L + i * 11L; + return i; + } + + public static long getPositionRandom(Vec3i pos) { + return getCoordinateRandom(pos.getX(), pos.getY(), pos.getZ()); + } + + public static double getRandomDoubleInRange(EaglercraftRandom parRandom, double parDouble1, double parDouble2) { + return parDouble1 >= parDouble2 ? parDouble1 : parRandom.nextDouble() * (parDouble2 - parDouble1) + parDouble1; + } + + public static int getRandomIntegerInRange(EaglercraftRandom parRandom, int parInt1, int parInt2) { + return parInt1 >= parInt2 ? parInt1 : parRandom.nextInt(parInt2 - parInt1 + 1) + parInt1; + } + + public static EaglercraftUUID getRandomUuid(EaglercraftRandom rand) { + long i = rand.nextLong() & -61441L | 16384L; + long j = rand.nextLong() & 4611686018427387903L | Long.MIN_VALUE; + return new EaglercraftUUID(i, j); + } + + /** + * + Is the given value a power of two? (1, 2, 4, 8, 16, ...) + */ + private static boolean isPowerOfTwo(int value) { + return value != 0 && (value & value - 1) == 0; + } + + public static int normalizeAngle(int parInt1, int parInt2) { + return (parInt1 % parInt2 + parInt2) % parInt2; + } + + /** + * + parses the string as double or returns the second parameter if it fails. + */ + public static double parseDoubleWithDefault(String parString1, double parDouble1) { + try { + return Double.parseDouble(parString1); + } catch (Throwable var4) { + return parDouble1; + } + } + + public static double parseDoubleWithDefaultAndMax(String parString1, double parDouble1, double parDouble2) { + return Math.max(parDouble2, parseDoubleWithDefault(parString1, parDouble1)); + } + + /** + * + parses the string as integer or returns the second parameter if it fails + */ + public static int parseIntWithDefault(String parString1, int parInt1) { + try { + return Integer.parseInt(parString1); + } catch (Throwable var3) { + return parInt1; + } + } + + /** + * + parses the string as integer or returns the second parameter if it fails. + * this value is capped to par2 + */ + public static int parseIntWithDefaultAndMax(String parString1, int parInt1, int parInt2) { + return Math.max(parInt2, parseIntWithDefault(parString1, parInt1)); + } + + public static float randomFloatClamp(EaglercraftRandom parRandom, float parFloat1, float parFloat2) { + return parFloat1 >= parFloat2 ? parFloat1 : parRandom.nextFloat() * (parFloat2 - parFloat1) + parFloat1; + } + + /** + * + Returns the input value rounded up to the next highest power of two. + */ + public static int roundUpToPowerOfTwo(int value) { + int i = value - 1; + i = i | i >> 1; + i = i | i >> 2; + i = i | i >> 4; + i = i | i >> 8; + i = i | i >> 16; + return i + 1; + } + + /** + * + sin looked up in a table + */ + public static float sin(float parFloat1) { + return SIN_TABLE[(int) (parFloat1 * 10430.378F) & '\uffff']; + } + + public static float sqrt_double(double value) { + return (float) Math.sqrt(value); + } + + public static float sqrt_float(float value) { + return (float) Math.sqrt((double) value); + } + + /** + * + returns par0 cast as an int, and no greater than Integer.MAX_VALUE-1024 + */ + public static int truncateDoubleToInt(double value) { + return (int) (value + 1024.0D) - 1024; + } + + /** + * + the angle is reduced to an angle between -180 and +180 by mod, and a 360 + * check + */ + public static double wrapAngleTo180_double(double value) { + value = value % 360.0D; + if (value >= 180.0D) { + value -= 360.0D; } - multiplyDeBruijnBitPosition = new int[] { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, - 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; - field_181163_d = Double.longBitsToDouble(4805340802404319232L); - field_181164_e = new double[257]; - field_181165_f = new double[257]; - - for (int j = 0; j < 257; ++j) { - double d0 = (double) j / 256.0D; - double d1 = Math.asin(d0); - field_181165_f[j] = Math.cos(d1); - field_181164_e[j] = d1; + if (value < -180.0D) { + value += 360.0D; } + return value; + } + + /** + * + the angle is reduced to an angle between -180 and +180 by mod, and a 360 + * check + */ + public static float wrapAngleTo180_float(float value) { + value = value % 360.0F; + if (value >= 180.0F) { + value -= 360.0F; + } + + if (value < -180.0F) { + value += 360.0F; + } + + return value; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/Matrix4f.java b/src/game/java/net/minecraft/util/Matrix4f.java index f74f4238..38ce81ca 100644 --- a/src/game/java/net/minecraft/util/Matrix4f.java +++ b/src/game/java/net/minecraft/util/Matrix4f.java @@ -1,26 +1,33 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Matrix4f extends net.lax1dude.eaglercraft.v1_8.vector.Matrix4f { + public Matrix4f() { + this.m00 = this.m01 = this.m02 = this.m03 = this.m10 = this.m11 = this.m12 = this.m13 = this.m20 = this.m21 = this.m22 = this.m23 = this.m30 = this.m31 = this.m32 = this.m33 = 0.0F; + } + public Matrix4f(float[] parArrayOfFloat) { this.m00 = parArrayOfFloat[0]; this.m01 = parArrayOfFloat[1]; @@ -39,8 +46,4 @@ public class Matrix4f extends net.lax1dude.eaglercraft.v1_8.vector.Matrix4f { this.m32 = parArrayOfFloat[14]; this.m33 = parArrayOfFloat[15]; } - - public Matrix4f() { - this.m00 = this.m01 = this.m02 = this.m03 = this.m10 = this.m11 = this.m12 = this.m13 = this.m20 = this.m21 = this.m22 = this.m23 = this.m30 = this.m31 = this.m32 = this.m33 = 0.0F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/MinecraftError.java b/src/game/java/net/minecraft/util/MinecraftError.java index e0af5c35..d56560f1 100644 --- a/src/game/java/net/minecraft/util/MinecraftError.java +++ b/src/game/java/net/minecraft/util/MinecraftError.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/MouseFilter.java b/src/game/java/net/minecraft/util/MouseFilter.java index 7cb22903..99a75454 100644 --- a/src/game/java/net/minecraft/util/MouseFilter.java +++ b/src/game/java/net/minecraft/util/MouseFilter.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,8 +28,14 @@ public class MouseFilter { private float field_76334_b; private float field_76335_c; - /**+ - * Smooths mouse input + public void reset() { + this.field_76336_a = 0.0F; + this.field_76334_b = 0.0F; + this.field_76335_c = 0.0F; + } + + /** + * + Smooths mouse input */ public float smooth(float parFloat1, float parFloat2) { this.field_76336_a += parFloat1; @@ -39,10 +48,4 @@ public class MouseFilter { this.field_76334_b += parFloat1; return parFloat1; } - - public void reset() { - this.field_76336_a = 0.0F; - this.field_76334_b = 0.0F; - this.field_76335_c = 0.0F; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/MouseHelper.java b/src/game/java/net/minecraft/util/MouseHelper.java index 7471d92d..22e69bd3 100644 --- a/src/game/java/net/minecraft/util/MouseHelper.java +++ b/src/game/java/net/minecraft/util/MouseHelper.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.Display; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,8 +31,8 @@ public class MouseHelper { public int deltaX; public int deltaY; - /**+ - * Grabs the mouse cursor it doesn't move and isn't seen. + /** + * + Grabs the mouse cursor it doesn't move and isn't seen. */ public void grabMouseCursor() { Mouse.setGrabbed(true); @@ -37,17 +40,17 @@ public class MouseHelper { this.deltaY = 0; } - /**+ - * Ungrabs the mouse cursor so it can be moved and set it to the - * center of the screen + public void mouseXYChange() { + this.deltaX = PointerInputAbstraction.getVCursorDX(); + this.deltaY = PointerInputAbstraction.getVCursorDY(); + } + + /** + * + Ungrabs the mouse cursor so it can be moved and set it to the center of the + * screen */ public void ungrabMouseCursor() { Mouse.setCursorPosition(Display.getWidth() / 2, Display.getHeight() / 2); Mouse.setGrabbed(false); } - - public void mouseXYChange() { - this.deltaX = PointerInputAbstraction.getVCursorDX(); - this.deltaY = PointerInputAbstraction.getVCursorDY(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/MovementInput.java b/src/game/java/net/minecraft/util/MovementInput.java index ed5342a6..150b623b 100644 --- a/src/game/java/net/minecraft/util/MovementInput.java +++ b/src/game/java/net/minecraft/util/MovementInput.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/MovementInputFromOptions.java b/src/game/java/net/minecraft/util/MovementInputFromOptions.java index 7719b84e..7e7dc1e4 100644 --- a/src/game/java/net/minecraft/util/MovementInputFromOptions.java +++ b/src/game/java/net/minecraft/util/MovementInputFromOptions.java @@ -4,22 +4,25 @@ import net.lax1dude.eaglercraft.v1_8.touch_gui.EnumTouchControl; import net.lax1dude.eaglercraft.v1_8.touch_gui.TouchControls; import net.minecraft.client.settings.GameSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/MovingObjectPosition.java b/src/game/java/net/minecraft/util/MovingObjectPosition.java index d7e96cc2..9102ccc6 100644 --- a/src/game/java/net/minecraft/util/MovingObjectPosition.java +++ b/src/game/java/net/minecraft/util/MovingObjectPosition.java @@ -2,45 +2,51 @@ package net.minecraft.util; import net.minecraft.entity.Entity; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MovingObjectPosition { + public static enum MovingObjectType { + MISS, BLOCK, ENTITY; + } + private BlockPos blockPos; public MovingObjectPosition.MovingObjectType typeOfHit; public EnumFacing sideHit; public Vec3 hitVec; + public Entity entityHit; - public MovingObjectPosition(Vec3 hitVecIn, EnumFacing facing, BlockPos blockPosIn) { - this(MovingObjectPosition.MovingObjectType.BLOCK, hitVecIn, facing, blockPosIn); - } - - public MovingObjectPosition(Vec3 parVec3_1, EnumFacing facing) { - this(MovingObjectPosition.MovingObjectType.BLOCK, parVec3_1, facing, BlockPos.ORIGIN); - } - public MovingObjectPosition(Entity parEntity) { this(parEntity, new Vec3(parEntity.posX, parEntity.posY, parEntity.posZ)); } + public MovingObjectPosition(Entity entityHitIn, Vec3 hitVecIn) { + this.typeOfHit = MovingObjectPosition.MovingObjectType.ENTITY; + this.entityHit = entityHitIn; + this.hitVec = hitVecIn; + } + public MovingObjectPosition(MovingObjectPosition.MovingObjectType typeOfHitIn, Vec3 hitVecIn, EnumFacing sideHitIn, BlockPos blockPosIn) { this.typeOfHit = typeOfHitIn; @@ -49,10 +55,12 @@ public class MovingObjectPosition { this.hitVec = new Vec3(hitVecIn.xCoord, hitVecIn.yCoord, hitVecIn.zCoord); } - public MovingObjectPosition(Entity entityHitIn, Vec3 hitVecIn) { - this.typeOfHit = MovingObjectPosition.MovingObjectType.ENTITY; - this.entityHit = entityHitIn; - this.hitVec = hitVecIn; + public MovingObjectPosition(Vec3 parVec3_1, EnumFacing facing) { + this(MovingObjectPosition.MovingObjectType.BLOCK, parVec3_1, facing, BlockPos.ORIGIN); + } + + public MovingObjectPosition(Vec3 hitVecIn, EnumFacing facing, BlockPos blockPosIn) { + this(MovingObjectPosition.MovingObjectType.BLOCK, hitVecIn, facing, blockPosIn); } public BlockPos getBlockPos() { @@ -63,8 +71,4 @@ public class MovingObjectPosition { return "HitResult{type=" + this.typeOfHit + ", blockpos=" + this.blockPos + ", f=" + this.sideHit + ", pos=" + this.hitVec + ", entity=" + this.entityHit + '}'; } - - public static enum MovingObjectType { - MISS, BLOCK, ENTITY; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ObjectIntIdentityMap.java b/src/game/java/net/minecraft/util/ObjectIntIdentityMap.java index 357b6d2c..6464783a 100644 --- a/src/game/java/net/minecraft/util/ObjectIntIdentityMap.java +++ b/src/game/java/net/minecraft/util/ObjectIntIdentityMap.java @@ -8,22 +8,25 @@ import com.google.common.base.Predicates; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,16 +35,6 @@ public class ObjectIntIdentityMap implements IObjectIntIterable { private final IdentityHashMap identityMap = new IdentityHashMap(512); private final List objectList = Lists.newArrayList(); - public void put(T key, int value) { - this.identityMap.put(key, Integer.valueOf(value)); - - while (this.objectList.size() <= value) { - this.objectList.add((T) null); - } - - this.objectList.set(value, key); - } - public int get(T key) { Integer integer = (Integer) this.identityMap.get(key); return integer == null ? -1 : integer.intValue(); @@ -54,4 +47,14 @@ public class ObjectIntIdentityMap implements IObjectIntIterable { public Iterator iterator() { return Iterators.filter(this.objectList.iterator(), Predicates.notNull()); } + + public void put(T key, int value) { + this.identityMap.put(key, Integer.valueOf(value)); + + while (this.objectList.size() <= value) { + this.objectList.add((T) null); + } + + this.objectList.set(value, key); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/RegistryDefaulted.java b/src/game/java/net/minecraft/util/RegistryDefaulted.java index 8c15bc22..783b6bc0 100644 --- a/src/game/java/net/minecraft/util/RegistryDefaulted.java +++ b/src/game/java/net/minecraft/util/RegistryDefaulted.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/RegistryNamespaced.java b/src/game/java/net/minecraft/util/RegistryNamespaced.java index 0aad460f..7ee541de 100644 --- a/src/game/java/net/minecraft/util/RegistryNamespaced.java +++ b/src/game/java/net/minecraft/util/RegistryNamespaced.java @@ -6,29 +6,32 @@ import java.util.Map; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RegistryNamespaced extends RegistrySimple implements IObjectIntIterable { - /**+ - * The backing store that maps Integers to objects. + /** + * + The backing store that maps Integers to objects. */ protected final ObjectIntIdentityMap underlyingIntegerMap = new ObjectIntIdentityMap(); protected final Map inverseObjectRegistry; @@ -37,42 +40,37 @@ public class RegistryNamespaced extends RegistrySimple implements IO this.inverseObjectRegistry = ((BiMap) this.registryObjects).inverse(); } - public void register(int i, K object, V object1) { - this.underlyingIntegerMap.put(object1, i); - this.putObject(object, object1); + /** + * + Does this registry contain an entry for the given key? + */ + public boolean containsKey(K parObject) { + return super.containsKey(parObject); } protected Map createUnderlyingMap() { return HashBiMap.create(); } - public V getObject(K object) { - return super.getObject(object); - } - - /**+ - * Gets the name we use to identify the given object. - */ - public K getNameForObject(V parObject) { - return (K) this.inverseObjectRegistry.get(parObject); - } - - /**+ - * Does this registry contain an entry for the given key? - */ - public boolean containsKey(K parObject) { - return super.containsKey(parObject); - } - - /**+ - * Gets the integer ID we use to identify the given object. + /** + * + Gets the integer ID we use to identify the given object. */ public int getIDForObject(V parObject) { return this.underlyingIntegerMap.get(parObject); } - /**+ - * Gets the object identified by the given ID. + /** + * + Gets the name we use to identify the given object. + */ + public K getNameForObject(V parObject) { + return (K) this.inverseObjectRegistry.get(parObject); + } + + public V getObject(K object) { + return super.getObject(object); + } + + /** + * + Gets the object identified by the given ID. */ public V getObjectById(int i) { return (V) this.underlyingIntegerMap.getByValue(i); @@ -81,4 +79,9 @@ public class RegistryNamespaced extends RegistrySimple implements IO public Iterator iterator() { return this.underlyingIntegerMap.iterator(); } + + public void register(int i, K object, V object1) { + this.underlyingIntegerMap.put(object1, i); + this.putObject(object, object1); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/RegistryNamespacedDefaultedByKey.java b/src/game/java/net/minecraft/util/RegistryNamespacedDefaultedByKey.java index c7b280e1..7fc052a2 100644 --- a/src/game/java/net/minecraft/util/RegistryNamespacedDefaultedByKey.java +++ b/src/game/java/net/minecraft/util/RegistryNamespacedDefaultedByKey.java @@ -2,22 +2,25 @@ package net.minecraft.util; import org.apache.commons.lang3.Validate; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,6 +33,19 @@ public class RegistryNamespacedDefaultedByKey extends RegistryNamespaced extends RegistryNamespaced implements IRegistry { private static final Logger logger = LogManager.getLogger(); protected final Map registryObjects = this.createUnderlyingMap(); + /** + * + Does this registry contain an entry for the given key? + */ + public boolean containsKey(K object) { + return this.registryObjects.containsKey(object); + } + protected Map createUnderlyingMap() { return Maps.newHashMap(); } + /** + * + Gets all the keys recognized by this registry. + */ + public Set getKeys() { + return Collections.unmodifiableSet(this.registryObjects.keySet()); + } + public V getObject(K object) { return (V) this.registryObjects.get(object); } - /**+ - * Register an object on this registry. + public Iterator iterator() { + return this.registryObjects.values().iterator(); + } + + /** + * + Register an object on this registry. */ public void putObject(K object, V object1) { Validate.notNull(object); @@ -56,22 +77,4 @@ public class RegistrySimple implements IRegistry { this.registryObjects.put(object, object1); } - - /**+ - * Gets all the keys recognized by this registry. - */ - public Set getKeys() { - return Collections.unmodifiableSet(this.registryObjects.keySet()); - } - - /**+ - * Does this registry contain an entry for the given key? - */ - public boolean containsKey(K object) { - return this.registryObjects.containsKey(object); - } - - public Iterator iterator() { - return this.registryObjects.values().iterator(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ReportedException.java b/src/game/java/net/minecraft/util/ReportedException.java index 7dfea3e7..15c76ee6 100644 --- a/src/game/java/net/minecraft/util/ReportedException.java +++ b/src/game/java/net/minecraft/util/ReportedException.java @@ -2,22 +2,25 @@ package net.minecraft.util; import net.minecraft.crash.CrashReport; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,17 +32,17 @@ public class ReportedException extends RuntimeException { this.theReportedExceptionCrashReport = report; } - /**+ - * Gets the CrashReport wrapped by this exception. + public Throwable getCause() { + return this.theReportedExceptionCrashReport.getCrashCause(); + } + + /** + * + Gets the CrashReport wrapped by this exception. */ public CrashReport getCrashReport() { return this.theReportedExceptionCrashReport; } - public Throwable getCause() { - return this.theReportedExceptionCrashReport.getCrashCause(); - } - public String getMessage() { return this.theReportedExceptionCrashReport.getDescription(); } diff --git a/src/game/java/net/minecraft/util/ResourceLocation.java b/src/game/java/net/minecraft/util/ResourceLocation.java index 844f9b57..58b4fcb2 100644 --- a/src/game/java/net/minecraft/util/ResourceLocation.java +++ b/src/game/java/net/minecraft/util/ResourceLocation.java @@ -2,37 +2,59 @@ package net.minecraft.util; import org.apache.commons.lang3.Validate; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ResourceLocation { - protected final String resourceDomain; - protected final String resourcePath; - - public Object cachedPointer = null; - public int cachedPointerType = 0; - public static final int CACHED_POINTER_NONE = 0; public static final int CACHED_POINTER_TEXTURE = 1; + public static final int CACHED_POINTER_EAGLER_MESH = 2; + /** + * + Splits an object name (such as minecraft:apple) into the domain and path + * parts and returns these as an array of length 2. If no colon is present in + * the passed value the returned array will contain {null, toSplit}. + */ + protected static String[] splitObjectName(String toSplit) { + String[] astring = new String[] { null, toSplit }; + int i = toSplit.indexOf(58); + if (i >= 0) { + astring[1] = toSplit.substring(i + 1, toSplit.length()); + if (i > 1) { + astring[0] = toSplit.substring(0, i); + } + } + + return astring; + } + + protected final String resourceDomain; + protected final String resourcePath; + public Object cachedPointer = null; + + public int cachedPointerType = 0; + protected ResourceLocation(int parInt1, String... resourceName) { this.resourceDomain = org.apache.commons.lang3.StringUtils.isEmpty(resourceName[0]) ? "minecraft" : resourceName[0].toLowerCase(); @@ -48,37 +70,6 @@ public class ResourceLocation { this(0, new String[] { resourceDomainIn, resourcePathIn }); } - /**+ - * Splits an object name (such as minecraft:apple) into the - * domain and path parts and returns these as an array of length - * 2. If no colon is present in the passed value the returned - * array will contain {null, toSplit}. - */ - protected static String[] splitObjectName(String toSplit) { - String[] astring = new String[] { null, toSplit }; - int i = toSplit.indexOf(58); - if (i >= 0) { - astring[1] = toSplit.substring(i + 1, toSplit.length()); - if (i > 1) { - astring[0] = toSplit.substring(0, i); - } - } - - return astring; - } - - public String getResourcePath() { - return this.resourcePath; - } - - public String getResourceDomain() { - return this.resourceDomain; - } - - public String toString() { - return this.resourceDomain + ':' + this.resourcePath; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -91,7 +82,19 @@ public class ResourceLocation { } } + public String getResourceDomain() { + return this.resourceDomain; + } + + public String getResourcePath() { + return this.resourcePath; + } + public int hashCode() { return 31 * this.resourceDomain.hashCode() + this.resourcePath.hashCode(); } + + public String toString() { + return this.resourceDomain + ':' + this.resourcePath; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/Rotations.java b/src/game/java/net/minecraft/util/Rotations.java index b2f214b3..f0aa1435 100644 --- a/src/game/java/net/minecraft/util/Rotations.java +++ b/src/game/java/net/minecraft/util/Rotations.java @@ -3,22 +3,25 @@ package net.minecraft.util; import net.minecraft.nbt.NBTTagFloat; import net.minecraft.nbt.NBTTagList; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,14 +43,6 @@ public class Rotations { this.z = nbt.getFloatAt(2); } - public NBTTagList writeToNBT() { - NBTTagList nbttaglist = new NBTTagList(); - nbttaglist.appendTag(new NBTTagFloat(this.x)); - nbttaglist.appendTag(new NBTTagFloat(this.y)); - nbttaglist.appendTag(new NBTTagFloat(this.z)); - return nbttaglist; - } - public boolean equals(Object object) { if (!(object instanceof Rotations)) { return false; @@ -57,24 +52,32 @@ public class Rotations { } } - /**+ - * Gets the X axis rotation + /** + * + Gets the X axis rotation */ public float getX() { return this.x; } - /**+ - * Gets the Y axis rotation + /** + * + Gets the Y axis rotation */ public float getY() { return this.y; } - /**+ - * Gets the Z axis rotation + /** + * + Gets the Z axis rotation */ public float getZ() { return this.z; } + + public NBTTagList writeToNBT() { + NBTTagList nbttaglist = new NBTTagList(); + nbttaglist.appendTag(new NBTTagFloat(this.x)); + nbttaglist.appendTag(new NBTTagFloat(this.y)); + nbttaglist.appendTag(new NBTTagFloat(this.z)); + return nbttaglist; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/ScreenShotHelper.java b/src/game/java/net/minecraft/util/ScreenShotHelper.java index 891f9b9d..42c0b3d9 100644 --- a/src/game/java/net/minecraft/util/ScreenShotHelper.java +++ b/src/game/java/net/minecraft/util/ScreenShotHelper.java @@ -2,32 +2,35 @@ package net.minecraft.util; import net.lax1dude.eaglercraft.v1_8.internal.PlatformApplication; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ScreenShotHelper { - /**+ - * Saves a screenshot in the game directory with a time-stamped - * filename. Args: gameDirectory, requestedWidthInPixels, - * requestedHeightInPixels, frameBuffer + /** + * + Saves a screenshot in the game directory with a time-stamped filename. + * Args: gameDirectory, requestedWidthInPixels, requestedHeightInPixels, + * frameBuffer */ public static IChatComponent saveScreenshot() { return new ChatComponentText("Saved Screenshot As: " + PlatformApplication.saveScreenshot()); diff --git a/src/game/java/net/minecraft/util/Session.java b/src/game/java/net/minecraft/util/Session.java index b0c32865..0c1c7875 100644 --- a/src/game/java/net/minecraft/util/Session.java +++ b/src/game/java/net/minecraft/util/Session.java @@ -6,31 +6,40 @@ import net.lax1dude.eaglercraft.v1_8.mojang.authlib.GameProfile; import net.lax1dude.eaglercraft.v1_8.profile.EaglerProfile; import net.minecraft.entity.player.EntityPlayer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Session { - private GameProfile profile; - private static final EaglercraftUUID outOfGameUUID; + static { + byte[] bytes = new byte[16]; + (new EaglercraftRandom()).nextBytes(bytes); + outOfGameUUID = new EaglercraftUUID(bytes); + } + + private GameProfile profile; + public Session() { reset(); } @@ -39,10 +48,6 @@ public class Session { return profile; } - public void update(String serverUsername, EaglercraftUUID uuid) { - profile = new GameProfile(uuid, serverUsername); - } - public void reset() { update(EaglerProfile.getName(), outOfGameUUID); } @@ -51,10 +56,8 @@ public class Session { update(EaglerProfile.getName(), EntityPlayer.getOfflineUUID(EaglerProfile.getName())); } - static { - byte[] bytes = new byte[16]; - (new EaglercraftRandom()).nextBytes(bytes); - outOfGameUUID = new EaglercraftUUID(bytes); + public void update(String serverUsername, EaglercraftUUID uuid) { + profile = new GameProfile(uuid, serverUsername); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/StatCollector.java b/src/game/java/net/minecraft/util/StatCollector.java index 1988044c..ca9f1fc2 100644 --- a/src/game/java/net/minecraft/util/StatCollector.java +++ b/src/game/java/net/minecraft/util/StatCollector.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,43 +26,42 @@ package net.minecraft.util; public class StatCollector { private static StringTranslate localizedName = StringTranslate.getInstance(); - /**+ - * Translates a Stat name + /** + * + Determines whether or not translateToLocal will find a translation for the + * given key. */ - public static String translateToLocal(String key) { - return localizedName.translateKey(key); + public static boolean canTranslate(String key) { + return localizedName.isKeyTranslated(key); } - /**+ - * Translates a Stat name with format args + /** + * + Gets the time, in milliseconds since epoch, that the translation mapping + * was last updated */ - public static String translateToLocalFormatted(String key, Object... format) { - return localizedName.translateKeyFormat(key, format); + public static long getLastTranslationUpdateTimeInMilliseconds() { + return localizedName.getLastUpdateTimeInMilliseconds(); } - /**+ - * Translates a Stat name using the fallback (hardcoded en_US) - * locale. Looks like it's only intended to be used if - * translateToLocal fails. + /** + * + Translates a Stat name using the fallback (hardcoded en_US) locale. Looks + * like it's only intended to be used if translateToLocal fails. */ public static String translateToFallback(String key) { return StringTranslate.fallbackInstance != null ? StringTranslate.fallbackInstance.translateKey(key) : localizedName.translateKey(key); } - /**+ - * Determines whether or not translateToLocal will find a - * translation for the given key. + /** + * + Translates a Stat name */ - public static boolean canTranslate(String key) { - return localizedName.isKeyTranslated(key); + public static String translateToLocal(String key) { + return localizedName.translateKey(key); } - /**+ - * Gets the time, in milliseconds since epoch, that the - * translation mapping was last updated + /** + * + Translates a Stat name with format args */ - public static long getLastTranslationUpdateTimeInMilliseconds() { - return localizedName.getLastUpdateTimeInMilliseconds(); + public static String translateToLocalFormatted(String key, Object... format) { + return localizedName.translateKeyFormat(key, format); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/StringTranslate.java b/src/game/java/net/minecraft/util/StringTranslate.java index 3806b37f..08988a03 100644 --- a/src/game/java/net/minecraft/util/StringTranslate.java +++ b/src/game/java/net/minecraft/util/StringTranslate.java @@ -1,14 +1,5 @@ package net.minecraft.util; -import com.google.common.base.Splitter; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; - -import net.lax1dude.eaglercraft.v1_8.EagRuntime; -import net.lax1dude.eaglercraft.v1_8.HString; -import net.lax1dude.eaglercraft.v1_8.IOUtils; -import net.lax1dude.eaglercraft.v1_8.sp.SingleplayerServerController; - import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -19,46 +10,68 @@ import java.util.Map; import java.util.Map.Entry; import java.util.regex.Pattern; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; + +import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.IOUtils; +import net.lax1dude.eaglercraft.v1_8.sp.SingleplayerServerController; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StringTranslate { - /**+ - * Pattern that matches numeric variable placeholders in a - * resource string, such as "%d", "%3$d", "%.2f" + /** + * + Pattern that matches numeric variable placeholders in a resource string, + * such as "%d", "%3$d", "%.2f" */ private static final Pattern numericVariablePattern = Pattern.compile("%(\\d+\\$)?[\\d\\.]*[df]"); - /**+ - * A Splitter that splits a string on the first "=". For - * example, "a=b=c" would split into ["a", "b=c"]. + /** + * + A Splitter that splits a string on the first "=". For example, "a=b=c" + * would split into ["a", "b=c"]. */ private static final Splitter equalSignSplitter = Splitter.on('=').limit(2); - /**+ - * Is the private singleton instance of StringTranslate. + /** + * + Is the private singleton instance of StringTranslate. */ private static StringTranslate instance = new StringTranslate(); static StringTranslate fallbackInstance = null; - private final Map languageList = Maps.newHashMap(); - private long lastUpdateTimeInMilliseconds; - private StringTranslate() { + public static List dump() { + List ret = new ArrayList(instance.languageList.size()); + for (Entry etr : instance.languageList.entrySet()) { + ret.add(etr.getKey() + "=" + etr.getValue()); + } + return ret; + } + + /** + * + Return the StringTranslate singleton instance + */ + static StringTranslate getInstance() { + return instance; } public static void initClient() { @@ -92,16 +105,9 @@ public class StringTranslate { instance.lastUpdateTimeInMilliseconds = EagRuntime.steadyTimeMillis(); } - /**+ - * Return the StringTranslate singleton instance - */ - static StringTranslate getInstance() { - return instance; - } - - /**+ - * Replaces all the current instance's translations with the - * ones that are passed in. + /** + * + Replaces all the current instance's translations with the ones that are + * passed in. */ public static void replaceWith(Map parMap) { instance.languageList.clear(); @@ -109,15 +115,37 @@ public class StringTranslate { instance.lastUpdateTimeInMilliseconds = EagRuntime.steadyTimeMillis(); } - /**+ - * Translate a key to current language. + private final Map languageList = Maps.newHashMap(); + + private long lastUpdateTimeInMilliseconds; + + private StringTranslate() { + } + + /** + * + Gets the time, in milliseconds since epoch, that this instance was last + * updated + */ + public long getLastUpdateTimeInMilliseconds() { + return this.lastUpdateTimeInMilliseconds; + } + + /** + * + Returns true if the passed key is in the translation table. + */ + public boolean isKeyTranslated(String key) { + return this.languageList.containsKey(key); + } + + /** + * + Translate a key to current language. */ public String translateKey(String key) { return this.tryTranslateKey(key); } - /**+ - * Translate a key to current language applying String.format() + /** + * + Translate a key to current language applying String.format() */ public String translateKeyFormat(String key, Object... format) { String s = this.tryTranslateKey(key); @@ -129,35 +157,12 @@ public class StringTranslate { } } - /**+ - * Tries to look up a translation for the given key; spits back - * the key if no result was found. + /** + * + Tries to look up a translation for the given key; spits back the key if no + * result was found. */ private String tryTranslateKey(String key) { String s = (String) this.languageList.get(key); return s == null ? key : s; } - - /**+ - * Returns true if the passed key is in the translation table. - */ - public boolean isKeyTranslated(String key) { - return this.languageList.containsKey(key); - } - - /**+ - * Gets the time, in milliseconds since epoch, that this - * instance was last updated - */ - public long getLastUpdateTimeInMilliseconds() { - return this.lastUpdateTimeInMilliseconds; - } - - public static List dump() { - List ret = new ArrayList(instance.languageList.size()); - for (Entry etr : instance.languageList.entrySet()) { - ret.add(etr.getKey() + "=" + etr.getValue()); - } - return ret; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/StringUtils.java b/src/game/java/net/minecraft/util/StringUtils.java index 02cdfe13..728805d2 100644 --- a/src/game/java/net/minecraft/util/StringUtils.java +++ b/src/game/java/net/minecraft/util/StringUtils.java @@ -2,22 +2,25 @@ package net.minecraft.util; import java.util.regex.Pattern; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,9 +28,21 @@ import java.util.regex.Pattern; public class StringUtils { private static final Pattern patternControlCode = Pattern.compile("(?i)\\u00A7[0-9A-FK-OR]"); - /**+ - * Returns the time elapsed for the given number of ticks, in - * "mm:ss" format. + private static final Pattern patternControlCodeAlternate = Pattern.compile("(?i)&([0-9A-FK-OR])"); + + /** + * + Returns a value indicating whether the given string is null or empty. + */ + public static boolean isNullOrEmpty(String string) { + return org.apache.commons.lang3.StringUtils.isEmpty(string); + } + + public static String stripControlCodes(String parString1) { + return patternControlCode.matcher(parString1).replaceAll(""); + } + + /** + * + Returns the time elapsed for the given number of ticks, in "mm:ss" format. */ public static String ticksToElapsedTime(int ticks) { int i = ticks / 20; @@ -36,20 +51,6 @@ public class StringUtils { return i < 10 ? j + ":0" + i : j + ":" + i; } - public static String stripControlCodes(String parString1) { - return patternControlCode.matcher(parString1).replaceAll(""); - } - - /**+ - * Returns a value indicating whether the given string is null - * or empty. - */ - public static boolean isNullOrEmpty(String string) { - return org.apache.commons.lang3.StringUtils.isEmpty(string); - } - - private static final Pattern patternControlCodeAlternate = Pattern.compile("(?i)&([0-9A-FK-OR])"); - public static String translateControlCodesAlternate(String parString1) { return patternControlCodeAlternate.matcher(parString1).replaceAll(new String(new char[] { 0xA7, '$', '1' })); } diff --git a/src/game/java/net/minecraft/util/Timer.java b/src/game/java/net/minecraft/util/Timer.java index 59e745be..42c8c555 100644 --- a/src/game/java/net/minecraft/util/Timer.java +++ b/src/game/java/net/minecraft/util/Timer.java @@ -3,22 +3,25 @@ package net.minecraft.util; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.minecraft.client.Minecraft; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,18 +31,18 @@ public class Timer { private double lastHRTime; public int elapsedTicks; public float renderPartialTicks; - /**+ - * A multiplier to make the timer (and therefore the game) go - * faster or slower. 0.5 makes the game run at half-speed. + /** + * + A multiplier to make the timer (and therefore the game) go faster or + * slower. 0.5 makes the game run at half-speed. */ public float timerSpeed = 1.0F; public float elapsedPartialTicks; private long lastSyncSysClock; private long lastSyncHRClock; private long field_74285_i; - /**+ - * A ratio used to sync the high-resolution clock to the system - * clock, updated once per second + /** + * + A ratio used to sync the high-resolution clock to the system clock, updated + * once per second */ private double timeSyncAdjustment = 1.0D; @@ -49,8 +52,8 @@ public class Timer { this.lastSyncHRClock = EagRuntime.nanoTime() / 1000000L; } - /**+ - * Updates all fields of the Timer using the current time + /** + * + Updates all fields of the Timer using the current time */ public void updateTimer() { long i = Minecraft.getSystemTime(); diff --git a/src/game/java/net/minecraft/util/Tuple.java b/src/game/java/net/minecraft/util/Tuple.java index 87dca182..7a5e5b0c 100644 --- a/src/game/java/net/minecraft/util/Tuple.java +++ b/src/game/java/net/minecraft/util/Tuple.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,15 +32,15 @@ public class Tuple { this.b = bIn; } - /**+ - * Get the first Object in the Tuple + /** + * + Get the first Object in the Tuple */ public A getFirst() { return this.a; } - /**+ - * Get the second Object in the Tuple + /** + * + Get the second Object in the Tuple */ public B getSecond() { return this.b; diff --git a/src/game/java/net/minecraft/util/TupleIntJsonSerializable.java b/src/game/java/net/minecraft/util/TupleIntJsonSerializable.java index 976bb8aa..ca526034 100644 --- a/src/game/java/net/minecraft/util/TupleIntJsonSerializable.java +++ b/src/game/java/net/minecraft/util/TupleIntJsonSerializable.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,26 +27,26 @@ public class TupleIntJsonSerializable { private int integerValue; private IJsonSerializable jsonSerializableValue; - /**+ - * Gets the integer value stored in this tuple. + /** + * + Gets the integer value stored in this tuple. */ public int getIntegerValue() { return this.integerValue; } - /**+ - * Sets this tuple's integer value to the given value. - */ - public void setIntegerValue(int integerValueIn) { - this.integerValue = integerValueIn; - } - public T getJsonSerializableValue() { return (T) this.jsonSerializableValue; } - /**+ - * Sets this tuple's JsonSerializable value to the given value. + /** + * + Sets this tuple's integer value to the given value. + */ + public void setIntegerValue(int integerValueIn) { + this.integerValue = integerValueIn; + } + + /** + * + Sets this tuple's JsonSerializable value to the given value. */ public void setJsonSerializableValue(IJsonSerializable jsonSerializableValueIn) { this.jsonSerializableValue = jsonSerializableValueIn; diff --git a/src/game/java/net/minecraft/util/Util.java b/src/game/java/net/minecraft/util/Util.java index 495ea5e5..fae58b07 100644 --- a/src/game/java/net/minecraft/util/Util.java +++ b/src/game/java/net/minecraft/util/Util.java @@ -5,29 +5,32 @@ import net.lax1dude.eaglercraft.v1_8.futures.ExecutionException; import net.lax1dude.eaglercraft.v1_8.futures.FutureTask; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Util { - public static Util.EnumOS getOSType() { - return EagRuntime.getPlatformOS().getMinecraftEnum(); + public static enum EnumOS { + LINUX, SOLARIS, WINDOWS, OSX, UNKNOWN; } public static V func_181617_a(FutureTask parFutureTask, Logger parLogger) { @@ -43,7 +46,7 @@ public class Util { return (V) null; } - public static enum EnumOS { - LINUX, SOLARIS, WINDOWS, OSX, UNKNOWN; + public static Util.EnumOS getOSType() { + return EagRuntime.getPlatformOS().getMinecraftEnum(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/Vec3.java b/src/game/java/net/minecraft/util/Vec3.java index 4ec3d61e..6a6b9458 100644 --- a/src/game/java/net/minecraft/util/Vec3.java +++ b/src/game/java/net/minecraft/util/Vec3.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,32 +50,20 @@ public class Vec3 { this((double) parVec3i.getX(), (double) parVec3i.getY(), (double) parVec3i.getZ()); } - /**+ - * Returns a new vector with the result of the specified vector - * minus this. + public Vec3 add(Vec3 vec) { + return this.addVector(vec.xCoord, vec.yCoord, vec.zCoord); + } + + /** + * + Adds the specified x,y,z vector components to this vector and returns the + * resulting vector. Does not change this vector. */ - public Vec3 subtractReverse(Vec3 vec) { - return new Vec3(vec.xCoord - this.xCoord, vec.yCoord - this.yCoord, vec.zCoord - this.zCoord); + public Vec3 addVector(double x, double y, double z) { + return new Vec3(this.xCoord + x, this.yCoord + y, this.zCoord + z); } - /**+ - * Normalizes the vector to a length of 1 (except if it is the - * zero vector) - */ - public Vec3 normalize() { - double d0 = (double) MathHelper - .sqrt_double(this.xCoord * this.xCoord + this.yCoord * this.yCoord + this.zCoord * this.zCoord); - return d0 < 1.0E-4D ? new Vec3(0.0D, 0.0D, 0.0D) - : new Vec3(this.xCoord / d0, this.yCoord / d0, this.zCoord / d0); - } - - public double dotProduct(Vec3 vec) { - return this.xCoord * vec.xCoord + this.yCoord * vec.yCoord + this.zCoord * vec.zCoord; - } - - /**+ - * Returns a new vector with the result of this vector x the - * specified vector. + /** + * + Returns a new vector with the result of this vector x the specified vector. */ public Vec3 crossProduct(Vec3 vec) { return new Vec3(this.yCoord * vec.zCoord - this.zCoord * vec.yCoord, @@ -80,29 +71,9 @@ public class Vec3 { this.xCoord * vec.yCoord - this.yCoord * vec.xCoord); } - public Vec3 subtract(Vec3 vec) { - return this.subtract(vec.xCoord, vec.yCoord, vec.zCoord); - } - - public Vec3 subtract(double x, double y, double z) { - return this.addVector(-x, -y, -z); - } - - public Vec3 add(Vec3 vec) { - return this.addVector(vec.xCoord, vec.yCoord, vec.zCoord); - } - - /**+ - * Adds the specified x,y,z vector components to this vector and - * returns the resulting vector. Does not change this vector. - */ - public Vec3 addVector(double x, double y, double z) { - return new Vec3(this.xCoord + x, this.yCoord + y, this.zCoord + z); - } - - /**+ - * Euclidean distance between this and the specified vector, - * returned as double. + /** + * + Euclidean distance between this and the specified vector, returned as + * double. */ public double distanceTo(Vec3 vec) { double d0 = vec.xCoord - this.xCoord; @@ -111,29 +82,13 @@ public class Vec3 { return (double) MathHelper.sqrt_double(d0 * d0 + d1 * d1 + d2 * d2); } - /**+ - * The square of the Euclidean distance between this and the - * specified vector. - */ - public double squareDistanceTo(Vec3 vec) { - double d0 = vec.xCoord - this.xCoord; - double d1 = vec.yCoord - this.yCoord; - double d2 = vec.zCoord - this.zCoord; - return d0 * d0 + d1 * d1 + d2 * d2; + public double dotProduct(Vec3 vec) { + return this.xCoord * vec.xCoord + this.yCoord * vec.yCoord + this.zCoord * vec.zCoord; } - /**+ - * Returns the length of the vector. - */ - public double lengthVector() { - return (double) MathHelper - .sqrt_double(this.xCoord * this.xCoord + this.yCoord * this.yCoord + this.zCoord * this.zCoord); - } - - /**+ - * Returns a new vector with x value equal to the second - * parameter, along the line between this vector and the passed - * in vector, or null if not possible. + /** + * + Returns a new vector with x value equal to the second parameter, along the + * line between this vector and the passed in vector, or null if not possible. */ public Vec3 getIntermediateWithXValue(Vec3 vec, double x) { double d0 = vec.xCoord - this.xCoord; @@ -149,10 +104,9 @@ public class Vec3 { } } - /**+ - * Returns a new vector with y value equal to the second - * parameter, along the line between this vector and the passed - * in vector, or null if not possible. + /** + * + Returns a new vector with y value equal to the second parameter, along the + * line between this vector and the passed in vector, or null if not possible. */ public Vec3 getIntermediateWithYValue(Vec3 vec, double y) { double d0 = vec.xCoord - this.xCoord; @@ -168,10 +122,9 @@ public class Vec3 { } } - /**+ - * Returns a new vector with z value equal to the second - * parameter, along the line between this vector and the passed - * in vector, or null if not possible. + /** + * + Returns a new vector with z value equal to the second parameter, along the + * line between this vector and the passed in vector, or null if not possible. */ public Vec3 getIntermediateWithZValue(Vec3 vec, double z) { double d0 = vec.xCoord - this.xCoord; @@ -187,8 +140,22 @@ public class Vec3 { } } - public String toString() { - return "(" + this.xCoord + ", " + this.yCoord + ", " + this.zCoord + ")"; + /** + * + Returns the length of the vector. + */ + public double lengthVector() { + return (double) MathHelper + .sqrt_double(this.xCoord * this.xCoord + this.yCoord * this.yCoord + this.zCoord * this.zCoord); + } + + /** + * + Normalizes the vector to a length of 1 (except if it is the zero vector) + */ + public Vec3 normalize() { + double d0 = (double) MathHelper + .sqrt_double(this.xCoord * this.xCoord + this.yCoord * this.yCoord + this.zCoord * this.zCoord); + return d0 < 1.0E-4D ? new Vec3(0.0D, 0.0D, 0.0D) + : new Vec3(this.xCoord / d0, this.yCoord / d0, this.zCoord / d0); } public Vec3 rotatePitch(float pitch) { @@ -208,4 +175,33 @@ public class Vec3 { double d2 = this.zCoord * (double) f - this.xCoord * (double) f1; return new Vec3(d0, d1, d2); } + + /** + * + The square of the Euclidean distance between this and the specified vector. + */ + public double squareDistanceTo(Vec3 vec) { + double d0 = vec.xCoord - this.xCoord; + double d1 = vec.yCoord - this.yCoord; + double d2 = vec.zCoord - this.zCoord; + return d0 * d0 + d1 * d1 + d2 * d2; + } + + public Vec3 subtract(double x, double y, double z) { + return this.addVector(-x, -y, -z); + } + + public Vec3 subtract(Vec3 vec) { + return this.subtract(vec.xCoord, vec.yCoord, vec.zCoord); + } + + /** + * + Returns a new vector with the result of the specified vector minus this. + */ + public Vec3 subtractReverse(Vec3 vec) { + return new Vec3(vec.xCoord - this.xCoord, vec.yCoord - this.yCoord, vec.zCoord - this.zCoord); + } + + public String toString() { + return "(" + this.xCoord + ", " + this.yCoord + ", " + this.zCoord + ")"; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/Vec3i.java b/src/game/java/net/minecraft/util/Vec3i.java index c7aa2a56..845f9219 100644 --- a/src/game/java/net/minecraft/util/Vec3i.java +++ b/src/game/java/net/minecraft/util/Vec3i.java @@ -2,43 +2,88 @@ package net.minecraft.util; import com.google.common.base.Objects; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Vec3i implements Comparable { - /**+ - * The Null vector constant (0, 0, 0) + /** + * + The Null vector constant (0, 0, 0) */ public static final Vec3i NULL_VECTOR = new Vec3i(0, 0, 0); public int x; public int y; public int z; + public Vec3i(double xIn, double yIn, double zIn) { + this(MathHelper.floor_double(xIn), MathHelper.floor_double(yIn), MathHelper.floor_double(zIn)); + } + public Vec3i(int xIn, int yIn, int zIn) { this.x = xIn; this.y = yIn; this.z = zIn; } - public Vec3i(double xIn, double yIn, double zIn) { - this(MathHelper.floor_double(xIn), MathHelper.floor_double(yIn), MathHelper.floor_double(zIn)); + public int compareTo(Vec3i vec3i) { + return this.getY() == vec3i.getY() + ? (this.getZ() == vec3i.getZ() ? this.getX() - vec3i.getX() : this.getZ() - vec3i.getZ()) + : this.getY() - vec3i.getY(); + } + + /** + * + Calculate the cross product of this and the given Vector + */ + public Vec3i crossProduct(Vec3i vec3i) { + return new Vec3i(this.getY() * vec3i.getZ() - this.getZ() * vec3i.getY(), + this.getZ() * vec3i.getX() - this.getX() * vec3i.getZ(), + this.getX() * vec3i.getY() - this.getY() * vec3i.getX()); + } + + /** + * + Calculate squared distance to the given coordinates + */ + public double distanceSq(double toX, double toY, double toZ) { + double d0 = (double) this.getX() - toX; + double d1 = (double) this.getY() - toY; + double d2 = (double) this.getZ() - toZ; + return d0 * d0 + d1 * d1 + d2 * d2; + } + + /** + * + Calculate squared distance to the given coordinates + */ + public double distanceSq(Vec3i to) { + return this.distanceSq((double) to.getX(), (double) to.getY(), (double) to.getZ()); + } + + /** + * + Compute square of distance from point x, y, z to center of this Block + */ + public double distanceSqToCenter(double xIn, double yIn, double zIn) { + double d0 = (double) this.getX() + 0.5D - xIn; + double d1 = (double) this.getY() + 0.5D - yIn; + double d2 = (double) this.getZ() + 0.5D - zIn; + return d0 * d0 + d1 * d1 + d2 * d2; } public boolean equals(Object object) { @@ -53,72 +98,29 @@ public class Vec3i implements Comparable { } } - public int hashCode() { - return (this.getY() + this.getZ() * 31) * 31 + this.getX(); - } - - public int compareTo(Vec3i vec3i) { - return this.getY() == vec3i.getY() - ? (this.getZ() == vec3i.getZ() ? this.getX() - vec3i.getX() : this.getZ() - vec3i.getZ()) - : this.getY() - vec3i.getY(); - } - - /**+ - * Get the X coordinate + /** + * + Get the X coordinate */ public int getX() { return this.x; } - /**+ - * Get the Y coordinate + /** + * + Get the Y coordinate */ public int getY() { return this.y; } - /**+ - * Get the Z coordinate + /** + * + Get the Z coordinate */ public int getZ() { return this.z; } - /**+ - * Calculate the cross product of this and the given Vector - */ - public Vec3i crossProduct(Vec3i vec3i) { - return new Vec3i(this.getY() * vec3i.getZ() - this.getZ() * vec3i.getY(), - this.getZ() * vec3i.getX() - this.getX() * vec3i.getZ(), - this.getX() * vec3i.getY() - this.getY() * vec3i.getX()); - } - - /**+ - * Calculate squared distance to the given coordinates - */ - public double distanceSq(double toX, double toY, double toZ) { - double d0 = (double) this.getX() - toX; - double d1 = (double) this.getY() - toY; - double d2 = (double) this.getZ() - toZ; - return d0 * d0 + d1 * d1 + d2 * d2; - } - - /**+ - * Compute square of distance from point x, y, z to center of - * this Block - */ - public double distanceSqToCenter(double xIn, double yIn, double zIn) { - double d0 = (double) this.getX() + 0.5D - xIn; - double d1 = (double) this.getY() + 0.5D - yIn; - double d2 = (double) this.getZ() + 0.5D - zIn; - return d0 * d0 + d1 * d1 + d2 * d2; - } - - /**+ - * Calculate squared distance to the given coordinates - */ - public double distanceSq(Vec3i to) { - return this.distanceSq((double) to.getX(), (double) to.getY(), (double) to.getZ()); + public int hashCode() { + return (this.getY() + this.getZ() * 31) * 31 + this.getX(); } public String toString() { diff --git a/src/game/java/net/minecraft/util/Vec4b.java b/src/game/java/net/minecraft/util/Vec4b.java index 85cde28a..09674ae7 100644 --- a/src/game/java/net/minecraft/util/Vec4b.java +++ b/src/game/java/net/minecraft/util/Vec4b.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,22 +43,6 @@ public class Vec4b { this.field_176114_d = parVec4b.field_176114_d; } - public byte func_176110_a() { - return this.field_176117_a; - } - - public byte func_176112_b() { - return this.field_176115_b; - } - - public byte func_176113_c() { - return this.field_176116_c; - } - - public byte func_176111_d() { - return this.field_176114_d; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -70,6 +57,22 @@ public class Vec4b { } } + public byte func_176110_a() { + return this.field_176117_a; + } + + public byte func_176111_d() { + return this.field_176114_d; + } + + public byte func_176112_b() { + return this.field_176115_b; + } + + public byte func_176113_c() { + return this.field_176116_c; + } + public int hashCode() { int i = this.field_176117_a; i = 31 * i + this.field_176115_b; diff --git a/src/game/java/net/minecraft/util/Vector3d.java b/src/game/java/net/minecraft/util/Vector3d.java index ad16e651..684730eb 100644 --- a/src/game/java/net/minecraft/util/Vector3d.java +++ b/src/game/java/net/minecraft/util/Vector3d.java @@ -1,21 +1,24 @@ package net.minecraft.util; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/util/WeightedRandom.java b/src/game/java/net/minecraft/util/WeightedRandom.java index 8a4c5814..93d229e8 100644 --- a/src/game/java/net/minecraft/util/WeightedRandom.java +++ b/src/game/java/net/minecraft/util/WeightedRandom.java @@ -1,52 +1,38 @@ package net.minecraft.util; import java.util.Collection; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WeightedRandom { - /**+ - * Returns the total weight of all items in a collection. - */ - public static int getTotalWeight(Collection collection) { - int i = 0; + public static class Item { + protected int itemWeight; - for (WeightedRandom.Item weightedrandom$item : collection) { - i += weightedrandom$item.itemWeight; - } - - return i; - } - - public static T getRandomItem(EaglercraftRandom random, Collection collection, - int totalWeight) { - if (totalWeight <= 0) { - throw new IllegalArgumentException(); - } else { - int i = random.nextInt(totalWeight); - /**+ - * Returns a random choice from the input items. - */ - return getRandomItem(collection, i); + public Item(int itemWeightIn) { + this.itemWeight = itemWeightIn; } } @@ -62,17 +48,35 @@ public class WeightedRandom { } public static T getRandomItem(EaglercraftRandom random, Collection collection) { - /**+ - * Returns a random choice from the input items. + /** + * + Returns a random choice from the input items. */ return getRandomItem(random, collection, getTotalWeight(collection)); } - public static class Item { - protected int itemWeight; - - public Item(int itemWeightIn) { - this.itemWeight = itemWeightIn; + public static T getRandomItem(EaglercraftRandom random, Collection collection, + int totalWeight) { + if (totalWeight <= 0) { + throw new IllegalArgumentException(); + } else { + int i = random.nextInt(totalWeight); + /** + * + Returns a random choice from the input items. + */ + return getRandomItem(collection, i); } } + + /** + * + Returns the total weight of all items in a collection. + */ + public static int getTotalWeight(Collection collection) { + int i = 0; + + for (WeightedRandom.Item weightedrandom$item : collection) { + i += weightedrandom$item.itemWeight; + } + + return i; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/WeightedRandomChestContent.java b/src/game/java/net/minecraft/util/WeightedRandomChestContent.java index 8251ee68..3a8de761 100644 --- a/src/game/java/net/minecraft/util/WeightedRandomChestContent.java +++ b/src/game/java/net/minecraft/util/WeightedRandomChestContent.java @@ -3,53 +3,44 @@ package net.minecraft.util; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.inventory.IInventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntityDispenser; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WeightedRandomChestContent extends WeightedRandom.Item { - private ItemStack theItemId; - private int minStackSize; - private int maxStackSize; - - public WeightedRandomChestContent(Item parItem, int parInt1, int minimumChance, int maximumChance, - int itemWeightIn) { - super(itemWeightIn); - this.theItemId = new ItemStack(parItem, 1, parInt1); - this.minStackSize = minimumChance; - this.maxStackSize = maximumChance; - } - - public WeightedRandomChestContent(ItemStack stack, int minimumChance, int maximumChance, int itemWeightIn) { - super(itemWeightIn); - this.theItemId = stack; - this.minStackSize = minimumChance; - this.maxStackSize = maximumChance; + public static List func_177629_a(List parList, + WeightedRandomChestContent... parArrayOfWeightedRandomChestContent) { + ArrayList arraylist = Lists.newArrayList(parList); + Collections.addAll(arraylist, parArrayOfWeightedRandomChestContent); + return arraylist; } public static void generateChestContents(EaglercraftRandom random, List listIn, @@ -96,10 +87,24 @@ public class WeightedRandomChestContent extends WeightedRandom.Item { } - public static List func_177629_a(List parList, - WeightedRandomChestContent... parArrayOfWeightedRandomChestContent) { - ArrayList arraylist = Lists.newArrayList(parList); - Collections.addAll(arraylist, parArrayOfWeightedRandomChestContent); - return arraylist; + private ItemStack theItemId; + + private int minStackSize; + + private int maxStackSize; + + public WeightedRandomChestContent(Item parItem, int parInt1, int minimumChance, int maximumChance, + int itemWeightIn) { + super(itemWeightIn); + this.theItemId = new ItemStack(parItem, 1, parInt1); + this.minStackSize = minimumChance; + this.maxStackSize = maximumChance; + } + + public WeightedRandomChestContent(ItemStack stack, int minimumChance, int maximumChance, int itemWeightIn) { + super(itemWeightIn); + this.theItemId = stack; + this.minStackSize = minimumChance; + this.maxStackSize = maximumChance; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/util/WeightedRandomFishable.java b/src/game/java/net/minecraft/util/WeightedRandomFishable.java index 43416f1d..01f78900 100644 --- a/src/game/java/net/minecraft/util/WeightedRandomFishable.java +++ b/src/game/java/net/minecraft/util/WeightedRandomFishable.java @@ -1,26 +1,28 @@ package net.minecraft.util; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.item.ItemStack; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -58,13 +60,13 @@ public class WeightedRandomFishable extends WeightedRandom.Item { return itemstack; } - public WeightedRandomFishable setMaxDamagePercent(float maxDamagePercentIn) { - this.maxDamagePercent = maxDamagePercentIn; - return this; - } - public WeightedRandomFishable setEnchantable() { this.enchantable = true; return this; } + + public WeightedRandomFishable setMaxDamagePercent(float maxDamagePercentIn) { + this.maxDamagePercent = maxDamagePercentIn; + return this; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/village/MerchantRecipe.java b/src/game/java/net/minecraft/village/MerchantRecipe.java index 7caa01b4..d3d2496a 100644 --- a/src/game/java/net/minecraft/village/MerchantRecipe.java +++ b/src/game/java/net/minecraft/village/MerchantRecipe.java @@ -4,22 +4,25 @@ import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +35,12 @@ public class MerchantRecipe { private int maxTradeUses; private boolean rewardsExp; - public MerchantRecipe(NBTTagCompound tagCompound) { - this.readFromTags(tagCompound); + public MerchantRecipe(ItemStack buy1, Item sellItem) { + this(buy1, new ItemStack(sellItem)); + } + + public MerchantRecipe(ItemStack buy1, ItemStack sell) { + this(buy1, (ItemStack) null, sell); } public MerchantRecipe(ItemStack buy1, ItemStack buy2, ItemStack sell) { @@ -49,76 +56,70 @@ public class MerchantRecipe { this.rewardsExp = true; } - public MerchantRecipe(ItemStack buy1, ItemStack sell) { - this(buy1, (ItemStack) null, sell); + public MerchantRecipe(NBTTagCompound tagCompound) { + this.readFromTags(tagCompound); } - public MerchantRecipe(ItemStack buy1, Item sellItem) { - this(buy1, new ItemStack(sellItem)); + /** + * + Compensates {@link net.minecraft.village.MerchantRecipe#toolUses toolUses} + * with {@link net.minecraft.village.MerchantRecipe#maxTradeUses maxTradeUses} + */ + public void compensateToolUses() { + this.toolUses = this.maxTradeUses; } - /**+ - * Gets the itemToBuy. + /** + * + Gets the itemToBuy. */ public ItemStack getItemToBuy() { return this.itemToBuy; } - /**+ - * Gets secondItemToBuy. - */ - public ItemStack getSecondItemToBuy() { - return this.secondItemToBuy; - } - - /**+ - * Gets if Villager has secondItemToBuy. - */ - public boolean hasSecondItemToBuy() { - return this.secondItemToBuy != null; - } - - /**+ - * Gets itemToSell. + /** + * + Gets itemToSell. */ public ItemStack getItemToSell() { return this.itemToSell; } - public int getToolUses() { - return this.toolUses; - } - public int getMaxTradeUses() { return this.maxTradeUses; } - public void incrementToolUses() { - ++this.toolUses; + public boolean getRewardsExp() { + return this.rewardsExp; + } + + /** + * + Gets secondItemToBuy. + */ + public ItemStack getSecondItemToBuy() { + return this.secondItemToBuy; + } + + public int getToolUses() { + return this.toolUses; + } + + /** + * + Gets if Villager has secondItemToBuy. + */ + public boolean hasSecondItemToBuy() { + return this.secondItemToBuy != null; } public void increaseMaxTradeUses(int increment) { this.maxTradeUses += increment; } + public void incrementToolUses() { + ++this.toolUses; + } + public boolean isRecipeDisabled() { return this.toolUses >= this.maxTradeUses; } - /**+ - * Compensates {@link - * net.minecraft.village.MerchantRecipe#toolUses toolUses} with - * {@link net.minecraft.village.MerchantRecipe#maxTradeUses - * maxTradeUses} - */ - public void compensateToolUses() { - this.toolUses = this.maxTradeUses; - } - - public boolean getRewardsExp() { - return this.rewardsExp; - } - public void readFromTags(NBTTagCompound tagCompound) { NBTTagCompound nbttagcompound = tagCompound.getCompoundTag("buy"); this.itemToBuy = ItemStack.loadItemStackFromNBT(nbttagcompound); diff --git a/src/game/java/net/minecraft/village/MerchantRecipeList.java b/src/game/java/net/minecraft/village/MerchantRecipeList.java index 43d59c8e..de920cd4 100644 --- a/src/game/java/net/minecraft/village/MerchantRecipeList.java +++ b/src/game/java/net/minecraft/village/MerchantRecipeList.java @@ -9,27 +9,56 @@ import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTUtil; import net.minecraft.network.PacketBuffer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MerchantRecipeList extends ArrayList { + public static MerchantRecipeList readFromBuf(PacketBuffer buffer) throws IOException { + MerchantRecipeList merchantrecipelist = new MerchantRecipeList(); + int i = buffer.readByte() & 255; + + for (int j = 0; j < i; ++j) { + ItemStack itemstack = buffer.readItemStackFromBuffer(); + ItemStack itemstack1 = buffer.readItemStackFromBuffer(); + ItemStack itemstack2 = null; + if (buffer.readBoolean()) { + itemstack2 = buffer.readItemStackFromBuffer(); + } + + boolean flag = buffer.readBoolean(); + int k = buffer.readInt(); + int l = buffer.readInt(); + MerchantRecipe merchantrecipe = new MerchantRecipe(itemstack, itemstack2, itemstack1, k, l); + if (flag) { + merchantrecipe.compensateToolUses(); + } + + merchantrecipelist.add(merchantrecipe); + } + + return merchantrecipelist; + } + public MerchantRecipeList() { } @@ -37,8 +66,8 @@ public class MerchantRecipeList extends ArrayList { this.readRecipiesFromTags(compound); } - /**+ - * can par1,par2 be used to in crafting recipe par3 + /** + * + can par1,par2 be used to in crafting recipe par3 */ public MerchantRecipe canRecipeBeUsed(ItemStack parItemStack, ItemStack parItemStack2, int parInt1) { if (parInt1 > 0 && parInt1 < this.size()) { @@ -74,6 +103,29 @@ public class MerchantRecipeList extends ArrayList { && NBTUtil.func_181123_a(parItemStack2.getTagCompound(), parItemStack.getTagCompound(), false)); } + public NBTTagCompound getRecipiesAsTags() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + NBTTagList nbttaglist = new NBTTagList(); + + for (int i = 0; i < this.size(); ++i) { + MerchantRecipe merchantrecipe = (MerchantRecipe) this.get(i); + nbttaglist.appendTag(merchantrecipe.writeToTags()); + } + + nbttagcompound.setTag("Recipes", nbttaglist); + return nbttagcompound; + } + + public void readRecipiesFromTags(NBTTagCompound compound) { + NBTTagList nbttaglist = compound.getTagList("Recipes", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + this.add(new MerchantRecipe(nbttagcompound)); + } + + } + public void writeToBuf(PacketBuffer buffer) { buffer.writeByte((byte) (this.size() & 255)); @@ -93,53 +145,4 @@ public class MerchantRecipeList extends ArrayList { } } - - public static MerchantRecipeList readFromBuf(PacketBuffer buffer) throws IOException { - MerchantRecipeList merchantrecipelist = new MerchantRecipeList(); - int i = buffer.readByte() & 255; - - for (int j = 0; j < i; ++j) { - ItemStack itemstack = buffer.readItemStackFromBuffer(); - ItemStack itemstack1 = buffer.readItemStackFromBuffer(); - ItemStack itemstack2 = null; - if (buffer.readBoolean()) { - itemstack2 = buffer.readItemStackFromBuffer(); - } - - boolean flag = buffer.readBoolean(); - int k = buffer.readInt(); - int l = buffer.readInt(); - MerchantRecipe merchantrecipe = new MerchantRecipe(itemstack, itemstack2, itemstack1, k, l); - if (flag) { - merchantrecipe.compensateToolUses(); - } - - merchantrecipelist.add(merchantrecipe); - } - - return merchantrecipelist; - } - - public void readRecipiesFromTags(NBTTagCompound compound) { - NBTTagList nbttaglist = compound.getTagList("Recipes", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - this.add(new MerchantRecipe(nbttagcompound)); - } - - } - - public NBTTagCompound getRecipiesAsTags() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.size(); ++i) { - MerchantRecipe merchantrecipe = (MerchantRecipe) this.get(i); - nbttaglist.appendTag(merchantrecipe.writeToTags()); - } - - nbttagcompound.setTag("Recipes", nbttaglist); - return nbttagcompound; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/village/Village.java b/src/game/java/net/minecraft/village/Village.java index d815c7d9..790e3a1e 100644 --- a/src/game/java/net/minecraft/village/Village.java +++ b/src/game/java/net/minecraft/village/Village.java @@ -1,9 +1,11 @@ package net.minecraft.village; -import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; import java.util.TreeMap; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.BlockDoor; import net.minecraft.block.material.Material; @@ -19,39 +21,52 @@ import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Village { + class VillageAggressor { + public EntityLivingBase agressor; + public int agressionTime; + + VillageAggressor(EntityLivingBase parEntityLivingBase, int parInt1) { + this.agressor = parEntityLivingBase; + this.agressionTime = parInt1; + } + } + private World worldObj; - /**+ - * list of VillageDoorInfo objects + /** + * + list of VillageDoorInfo objects */ private final List villageDoorInfoList = Lists.newArrayList(); - /**+ - * This is the sum of all door coordinates and used to calculate - * the actual village center by dividing by the number of doors. + /** + * + This is the sum of all door coordinates and used to calculate the actual + * village center by dividing by the number of doors. */ private BlockPos centerHelper = BlockPos.ORIGIN; - /**+ - * This is the actual village center. + /** + * + This is the actual village center. */ private BlockPos center = BlockPos.ORIGIN; private int villageRadius; @@ -61,6 +76,7 @@ public class Village { private int noBreedTicks; private TreeMap playerReputation = new TreeMap(); private List villageAgressors = Lists.newArrayList(); + private int numIronGolems; public Village() { @@ -70,48 +86,47 @@ public class Village { this.worldObj = worldIn; } - public void setWorld(World worldIn) { - this.worldObj = worldIn; + public void addOrRenewAgressor(EntityLivingBase entitylivingbaseIn) { + for (int i = 0, l = this.villageAgressors.size(); i < l; ++i) { + Village.VillageAggressor village$villageaggressor = this.villageAgressors.get(i); + if (village$villageaggressor.agressor == entitylivingbaseIn) { + village$villageaggressor.agressionTime = this.tickCounter; + return; + } + } + + this.villageAgressors.add(new Village.VillageAggressor(entitylivingbaseIn, this.tickCounter)); } - /**+ - * Called periodically by VillageCollection + public void addVillageDoorInfo(VillageDoorInfo doorInfo) { + this.villageDoorInfoList.add(doorInfo); + this.centerHelper = this.centerHelper.add(doorInfo.getDoorBlockPos()); + this.updateVillageRadiusAndCenter(); + this.lastAddDoorTimestamp = doorInfo.getInsidePosY(); + } + + /** + * + Prevent villager breeding for a fixed interval of time */ - public void tick(int parInt1) { - this.tickCounter = parInt1; - this.removeDeadAndOutOfRangeDoors(); - this.removeDeadAndOldAgressors(); - if (parInt1 % 20 == 0) { - this.updateNumVillagers(); - } - - if (parInt1 % 30 == 0) { - this.updateNumIronGolems(); - } - - int i = this.numVillagers / 10; - if (this.numIronGolems < i && this.villageDoorInfoList.size() > 20 && this.worldObj.rand.nextInt(7000) == 0) { - Vec3 vec3 = this.func_179862_a(this.center, 2, 4, 2); - if (vec3 != null) { - EntityIronGolem entityirongolem = new EntityIronGolem(this.worldObj); - entityirongolem.setPosition(vec3.xCoord, vec3.yCoord, vec3.zCoord); - this.worldObj.spawnEntityInWorld(entityirongolem); - ++this.numIronGolems; - } - } - + public void endMatingSeason() { + this.noBreedTicks = this.tickCounter; } - private Vec3 func_179862_a(BlockPos parBlockPos, int parInt1, int parInt2, int parInt3) { - for (int i = 0; i < 10; ++i) { - BlockPos blockpos = parBlockPos.add(this.worldObj.rand.nextInt(16) - 8, this.worldObj.rand.nextInt(6) - 3, - this.worldObj.rand.nextInt(16) - 8); - if (this.func_179866_a(blockpos) && this.func_179861_a(new BlockPos(parInt1, parInt2, parInt3), blockpos)) { - return new Vec3((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); + public EntityLivingBase findNearestVillageAggressor(EntityLivingBase entitylivingbaseIn) { + double d0 = Double.MAX_VALUE; + Village.VillageAggressor village$villageaggressor = null; + + for (int i = 0; i < this.villageAgressors.size(); ++i) { + Village.VillageAggressor village$villageaggressor1 = (Village.VillageAggressor) this.villageAgressors + .get(i); + double d1 = village$villageaggressor1.agressor.getDistanceSqToEntity(entitylivingbaseIn); + if (d1 <= d0) { + village$villageaggressor = village$villageaggressor1; + d0 = d1; } } - return null; + return village$villageaggressor != null ? village$villageaggressor.agressor : null; } private boolean func_179861_a(BlockPos parBlockPos, BlockPos parBlockPos2) { @@ -135,83 +150,29 @@ public class Village { } } - private void updateNumIronGolems() { - List list = this.worldObj.getEntitiesWithinAABB(EntityIronGolem.class, - new AxisAlignedBB((double) (this.center.getX() - this.villageRadius), (double) (this.center.getY() - 4), - (double) (this.center.getZ() - this.villageRadius), - (double) (this.center.getX() + this.villageRadius), (double) (this.center.getY() + 4), - (double) (this.center.getZ() + this.villageRadius))); - this.numIronGolems = list.size(); - } - - private void updateNumVillagers() { - List list = this.worldObj.getEntitiesWithinAABB(EntityVillager.class, - new AxisAlignedBB((double) (this.center.getX() - this.villageRadius), (double) (this.center.getY() - 4), - (double) (this.center.getZ() - this.villageRadius), - (double) (this.center.getX() + this.villageRadius), (double) (this.center.getY() + 4), - (double) (this.center.getZ() + this.villageRadius))); - this.numVillagers = list.size(); - if (this.numVillagers == 0) { - this.playerReputation.clear(); + private Vec3 func_179862_a(BlockPos parBlockPos, int parInt1, int parInt2, int parInt3) { + for (int i = 0; i < 10; ++i) { + BlockPos blockpos = parBlockPos.add(this.worldObj.rand.nextInt(16) - 8, this.worldObj.rand.nextInt(6) - 3, + this.worldObj.rand.nextInt(16) - 8); + if (this.func_179866_a(blockpos) && this.func_179861_a(new BlockPos(parInt1, parInt2, parInt3), blockpos)) { + return new Vec3((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); + } } - } - - public BlockPos getCenter() { - return this.center; - } - - public int getVillageRadius() { - return this.villageRadius; - } - - /**+ - * Actually get num village door info entries, but that boils - * down to number of doors. Called by EntityAIVillagerMate and - * VillageSiege - */ - public int getNumVillageDoors() { - return this.villageDoorInfoList.size(); - } - - public int getTicksSinceLastDoorAdding() { - return this.tickCounter - this.lastAddDoorTimestamp; - } - - public int getNumVillagers() { - return this.numVillagers; + return null; } public boolean func_179866_a(BlockPos pos) { return this.center.distanceSq(pos) < (double) (this.villageRadius * this.villageRadius); } - /**+ - * called only by class EntityAIMoveThroughVillage - */ - public List getVillageDoorInfoList() { - return this.villageDoorInfoList; + public BlockPos getCenter() { + return this.center; } - public VillageDoorInfo getNearestDoor(BlockPos pos) { - VillageDoorInfo villagedoorinfo = null; - int i = Integer.MAX_VALUE; - - for (int m = 0, n = this.villageDoorInfoList.size(); m < n; ++m) { - VillageDoorInfo villagedoorinfo1 = this.villageDoorInfoList.get(m); - int j = villagedoorinfo1.getDistanceToDoorBlockSq(pos); - if (j < i) { - villagedoorinfo = villagedoorinfo1; - i = j; - } - } - - return villagedoorinfo; - } - - /**+ - * Returns {@link net.minecraft.village.VillageDoorInfo - * VillageDoorInfo} from given block position + /** + * + Returns {@link net.minecraft.village.VillageDoorInfo VillageDoorInfo} from + * given block position */ public VillageDoorInfo getDoorInfo(BlockPos pos) { VillageDoorInfo villagedoorinfo = null; @@ -235,8 +196,8 @@ public class Village { return villagedoorinfo; } - /**+ - * if door not existed in this village, null will be returned + /** + * + if door not existed in this village, null will be returned */ public VillageDoorInfo getExistedDoor(BlockPos doorBlock) { if (this.center.distanceSq(doorBlock) > (double) (this.villageRadius * this.villageRadius)) { @@ -255,48 +216,20 @@ public class Village { } } - public void addVillageDoorInfo(VillageDoorInfo doorInfo) { - this.villageDoorInfoList.add(doorInfo); - this.centerHelper = this.centerHelper.add(doorInfo.getDoorBlockPos()); - this.updateVillageRadiusAndCenter(); - this.lastAddDoorTimestamp = doorInfo.getInsidePosY(); - } + public VillageDoorInfo getNearestDoor(BlockPos pos) { + VillageDoorInfo villagedoorinfo = null; + int i = Integer.MAX_VALUE; - /**+ - * Returns true, if there is not a single village door left. - * Called by VillageCollection - */ - public boolean isAnnihilated() { - return this.villageDoorInfoList.isEmpty(); - } - - public void addOrRenewAgressor(EntityLivingBase entitylivingbaseIn) { - for (int i = 0, l = this.villageAgressors.size(); i < l; ++i) { - Village.VillageAggressor village$villageaggressor = this.villageAgressors.get(i); - if (village$villageaggressor.agressor == entitylivingbaseIn) { - village$villageaggressor.agressionTime = this.tickCounter; - return; + for (int m = 0, n = this.villageDoorInfoList.size(); m < n; ++m) { + VillageDoorInfo villagedoorinfo1 = this.villageDoorInfoList.get(m); + int j = villagedoorinfo1.getDistanceToDoorBlockSq(pos); + if (j < i) { + villagedoorinfo = villagedoorinfo1; + i = j; } } - this.villageAgressors.add(new Village.VillageAggressor(entitylivingbaseIn, this.tickCounter)); - } - - public EntityLivingBase findNearestVillageAggressor(EntityLivingBase entitylivingbaseIn) { - double d0 = Double.MAX_VALUE; - Village.VillageAggressor village$villageaggressor = null; - - for (int i = 0; i < this.villageAgressors.size(); ++i) { - Village.VillageAggressor village$villageaggressor1 = (Village.VillageAggressor) this.villageAgressors - .get(i); - double d1 = village$villageaggressor1.agressor.getDistanceSqToEntity(entitylivingbaseIn); - if (d1 <= d0) { - village$villageaggressor = village$villageaggressor1; - d0 = d1; - } - } - - return village$villageaggressor != null ? village$villageaggressor.agressor : null; + return villagedoorinfo; } public EntityPlayer getNearestTargetPlayer(EntityLivingBase villageDefender) { @@ -319,6 +252,106 @@ public class Village { return entityplayer; } + /** + * + Actually get num village door info entries, but that boils down to number + * of doors. Called by EntityAIVillagerMate and VillageSiege + */ + public int getNumVillageDoors() { + return this.villageDoorInfoList.size(); + } + + public int getNumVillagers() { + return this.numVillagers; + } + + /** + * + Return the village reputation for a player + */ + public int getReputationForPlayer(String parString1) { + Integer integer = (Integer) this.playerReputation.get(parString1); + return integer != null ? integer.intValue() : 0; + } + + public int getTicksSinceLastDoorAdding() { + return this.tickCounter - this.lastAddDoorTimestamp; + } + + /** + * + called only by class EntityAIMoveThroughVillage + */ + public List getVillageDoorInfoList() { + return this.villageDoorInfoList; + } + + public int getVillageRadius() { + return this.villageRadius; + } + + /** + * + Returns true, if there is not a single village door left. Called by + * VillageCollection + */ + public boolean isAnnihilated() { + return this.villageDoorInfoList.isEmpty(); + } + + /** + * + Return whether villagers mating refractory period has passed + */ + public boolean isMatingSeason() { + return this.noBreedTicks == 0 || this.tickCounter - this.noBreedTicks >= 3600; + } + + /** + * + Return whether this player has a too low reputation with this village. + */ + public boolean isPlayerReputationTooLow(String parString1) { + return this.getReputationForPlayer(parString1) <= -15; + } + + private boolean isWoodDoor(BlockPos pos) { + Block block = this.worldObj.getBlockState(pos).getBlock(); + return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; + } + + /** + * + Read this village's data from NBT. + */ + public void readVillageDataFromNBT(NBTTagCompound parNBTTagCompound) { + this.numVillagers = parNBTTagCompound.getInteger("PopSize"); + this.villageRadius = parNBTTagCompound.getInteger("Radius"); + this.numIronGolems = parNBTTagCompound.getInteger("Golems"); + this.lastAddDoorTimestamp = parNBTTagCompound.getInteger("Stable"); + this.tickCounter = parNBTTagCompound.getInteger("Tick"); + this.noBreedTicks = parNBTTagCompound.getInteger("MTick"); + this.center = new BlockPos(parNBTTagCompound.getInteger("CX"), parNBTTagCompound.getInteger("CY"), + parNBTTagCompound.getInteger("CZ")); + this.centerHelper = new BlockPos(parNBTTagCompound.getInteger("ACX"), parNBTTagCompound.getInteger("ACY"), + parNBTTagCompound.getInteger("ACZ")); + NBTTagList nbttaglist = parNBTTagCompound.getTagList("Doors", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + VillageDoorInfo villagedoorinfo = new VillageDoorInfo( + new BlockPos(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Y"), + nbttagcompound.getInteger("Z")), + nbttagcompound.getInteger("IDX"), nbttagcompound.getInteger("IDZ"), + nbttagcompound.getInteger("TS")); + this.villageDoorInfoList.add(villagedoorinfo); + } + + NBTTagList nbttaglist1 = parNBTTagCompound.getTagList("Players", 10); + + for (int j = 0; j < nbttaglist1.tagCount(); ++j) { + NBTTagCompound nbttagcompound1 = nbttaglist1.getCompoundTagAt(j); + if (nbttagcompound1.hasKey("Name")) { + this.playerReputation.put(nbttagcompound1.getString("Name"), + Integer.valueOf(nbttagcompound1.getInteger("S"))); + } + } + + } + private void removeDeadAndOldAgressors() { Iterator iterator = this.villageAgressors.iterator(); @@ -358,9 +391,75 @@ public class Village { } - private boolean isWoodDoor(BlockPos pos) { - Block block = this.worldObj.getBlockState(pos).getBlock(); - return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; + public void setDefaultPlayerReputation(int parInt1) { + for (String s : this.playerReputation.keySet()) { + this.setReputationForPlayer(s, parInt1); + } + + } + + /** + * + Set the village reputation for a player. + */ + public int setReputationForPlayer(String parString1, int parInt1) { + int i = this.getReputationForPlayer(parString1); + int j = MathHelper.clamp_int(i + parInt1, -30, 10); + this.playerReputation.put(parString1, Integer.valueOf(j)); + return j; + } + + public void setWorld(World worldIn) { + this.worldObj = worldIn; + } + + /** + * + Called periodically by VillageCollection + */ + public void tick(int parInt1) { + this.tickCounter = parInt1; + this.removeDeadAndOutOfRangeDoors(); + this.removeDeadAndOldAgressors(); + if (parInt1 % 20 == 0) { + this.updateNumVillagers(); + } + + if (parInt1 % 30 == 0) { + this.updateNumIronGolems(); + } + + int i = this.numVillagers / 10; + if (this.numIronGolems < i && this.villageDoorInfoList.size() > 20 && this.worldObj.rand.nextInt(7000) == 0) { + Vec3 vec3 = this.func_179862_a(this.center, 2, 4, 2); + if (vec3 != null) { + EntityIronGolem entityirongolem = new EntityIronGolem(this.worldObj); + entityirongolem.setPosition(vec3.xCoord, vec3.yCoord, vec3.zCoord); + this.worldObj.spawnEntityInWorld(entityirongolem); + ++this.numIronGolems; + } + } + + } + + private void updateNumIronGolems() { + List list = this.worldObj.getEntitiesWithinAABB(EntityIronGolem.class, + new AxisAlignedBB((double) (this.center.getX() - this.villageRadius), (double) (this.center.getY() - 4), + (double) (this.center.getZ() - this.villageRadius), + (double) (this.center.getX() + this.villageRadius), (double) (this.center.getY() + 4), + (double) (this.center.getZ() + this.villageRadius))); + this.numIronGolems = list.size(); + } + + private void updateNumVillagers() { + List list = this.worldObj.getEntitiesWithinAABB(EntityVillager.class, + new AxisAlignedBB((double) (this.center.getX() - this.villageRadius), (double) (this.center.getY() - 4), + (double) (this.center.getZ() - this.villageRadius), + (double) (this.center.getX() + this.villageRadius), (double) (this.center.getY() + 4), + (double) (this.center.getZ() + this.villageRadius))); + this.numVillagers = list.size(); + if (this.numVillagers == 0) { + this.playerReputation.clear(); + } + } private void updateVillageRadiusAndCenter() { @@ -381,72 +480,8 @@ public class Village { } } - /**+ - * Return the village reputation for a player - */ - public int getReputationForPlayer(String parString1) { - Integer integer = (Integer) this.playerReputation.get(parString1); - return integer != null ? integer.intValue() : 0; - } - - /**+ - * Set the village reputation for a player. - */ - public int setReputationForPlayer(String parString1, int parInt1) { - int i = this.getReputationForPlayer(parString1); - int j = MathHelper.clamp_int(i + parInt1, -30, 10); - this.playerReputation.put(parString1, Integer.valueOf(j)); - return j; - } - - /**+ - * Return whether this player has a too low reputation with this - * village. - */ - public boolean isPlayerReputationTooLow(String parString1) { - return this.getReputationForPlayer(parString1) <= -15; - } - - /**+ - * Read this village's data from NBT. - */ - public void readVillageDataFromNBT(NBTTagCompound parNBTTagCompound) { - this.numVillagers = parNBTTagCompound.getInteger("PopSize"); - this.villageRadius = parNBTTagCompound.getInteger("Radius"); - this.numIronGolems = parNBTTagCompound.getInteger("Golems"); - this.lastAddDoorTimestamp = parNBTTagCompound.getInteger("Stable"); - this.tickCounter = parNBTTagCompound.getInteger("Tick"); - this.noBreedTicks = parNBTTagCompound.getInteger("MTick"); - this.center = new BlockPos(parNBTTagCompound.getInteger("CX"), parNBTTagCompound.getInteger("CY"), - parNBTTagCompound.getInteger("CZ")); - this.centerHelper = new BlockPos(parNBTTagCompound.getInteger("ACX"), parNBTTagCompound.getInteger("ACY"), - parNBTTagCompound.getInteger("ACZ")); - NBTTagList nbttaglist = parNBTTagCompound.getTagList("Doors", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - VillageDoorInfo villagedoorinfo = new VillageDoorInfo( - new BlockPos(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Y"), - nbttagcompound.getInteger("Z")), - nbttagcompound.getInteger("IDX"), nbttagcompound.getInteger("IDZ"), - nbttagcompound.getInteger("TS")); - this.villageDoorInfoList.add(villagedoorinfo); - } - - NBTTagList nbttaglist1 = parNBTTagCompound.getTagList("Players", 10); - - for (int j = 0; j < nbttaglist1.tagCount(); ++j) { - NBTTagCompound nbttagcompound1 = nbttaglist1.getCompoundTagAt(j); - if (nbttagcompound1.hasKey("Name")) { - this.playerReputation.put(nbttagcompound1.getString("Name"), - Integer.valueOf(nbttagcompound1.getInteger("S"))); - } - } - - } - - /**+ - * Write this village's data to NBT. + /** + * + Write this village's data to NBT. */ public void writeVillageDataToNBT(NBTTagCompound parNBTTagCompound) { parNBTTagCompound.setInteger("PopSize", this.numVillagers); @@ -487,35 +522,4 @@ public class Village { parNBTTagCompound.setTag("Players", nbttaglist1); } - - /**+ - * Prevent villager breeding for a fixed interval of time - */ - public void endMatingSeason() { - this.noBreedTicks = this.tickCounter; - } - - /**+ - * Return whether villagers mating refractory period has passed - */ - public boolean isMatingSeason() { - return this.noBreedTicks == 0 || this.tickCounter - this.noBreedTicks >= 3600; - } - - public void setDefaultPlayerReputation(int parInt1) { - for (String s : this.playerReputation.keySet()) { - this.setReputationForPlayer(s, parInt1); - } - - } - - class VillageAggressor { - public EntityLivingBase agressor; - public int agressionTime; - - VillageAggressor(EntityLivingBase parEntityLivingBase, int parInt1) { - this.agressor = parEntityLivingBase; - this.agressionTime = parInt1; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/village/VillageCollection.java b/src/game/java/net/minecraft/village/VillageCollection.java index 10edb10e..ce0470dd 100644 --- a/src/game/java/net/minecraft/village/VillageCollection.java +++ b/src/game/java/net/minecraft/village/VillageCollection.java @@ -1,8 +1,10 @@ package net.minecraft.village; -import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.BlockDoor; import net.minecraft.block.material.Material; @@ -14,36 +16,44 @@ import net.minecraft.world.World; import net.minecraft.world.WorldProvider; import net.minecraft.world.WorldSavedData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class VillageCollection extends WorldSavedData { + public static String fileNameForProvider(WorldProvider provider) { + return "villages" + provider.getInternalNameSuffix(); + } + private World worldObj; - /**+ - * This is a black hole. You can add data to this list through a - * public interface, but you can't query that information in any - * way and it's not used internally either. + /** + * + This is a black hole. You can add data to this list through a public + * interface, but you can't query that information in any way and it's not used + * internally either. */ private final List villagerPositionsList = Lists.newArrayList(); private final List newDoors = Lists.newArrayList(); private final List villageList = Lists.newArrayList(); + private int tickCounter; public VillageCollection(String name) { @@ -56,104 +66,6 @@ public class VillageCollection extends WorldSavedData { this.markDirty(); } - public void setWorldsForAll(World worldIn) { - this.worldObj = worldIn; - - for (int i = 0, l = this.villageList.size(); i < l; ++i) { - this.villageList.get(i).setWorld(worldIn); - } - - } - - public void addToVillagerPositionList(BlockPos pos) { - if (this.villagerPositionsList.size() <= 64) { - if (!this.positionInList(pos)) { - this.villagerPositionsList.add(pos); - } - - } - } - - /**+ - * Runs a single tick for the village collection - */ - public void tick() { - ++this.tickCounter; - - for (int i = 0, l = this.villageList.size(); i < l; ++i) { - this.villageList.get(i).tick(this.tickCounter); - } - - this.removeAnnihilatedVillages(); - this.dropOldestVillagerPosition(); - this.addNewDoorsToVillageOrCreateVillage(); - if (this.tickCounter % 400 == 0) { - this.markDirty(); - } - - } - - private void removeAnnihilatedVillages() { - Iterator iterator = this.villageList.iterator(); - - while (iterator.hasNext()) { - Village village = (Village) iterator.next(); - if (village.isAnnihilated()) { - iterator.remove(); - this.markDirty(); - } - } - - } - - /**+ - * Get a list of villages. - */ - public List getVillageList() { - return this.villageList; - } - - public Village getNearestVillage(BlockPos doorBlock, int radius) { - Village village = null; - double d0 = 3.4028234663852886E38D; - - for (int i = 0, l = this.villageList.size(); i < l; ++i) { - Village village1 = this.villageList.get(i); - double d1 = village1.getCenter().distanceSq(doorBlock); - if (d1 < d0) { - float f = (float) (radius + village1.getVillageRadius()); - if (d1 <= (double) (f * f)) { - village = village1; - d0 = d1; - } - } - } - - return village; - } - - private void dropOldestVillagerPosition() { - if (!this.villagerPositionsList.isEmpty()) { - this.addDoorsAround((BlockPos) this.villagerPositionsList.remove(0)); - } - } - - private void addNewDoorsToVillageOrCreateVillage() { - for (int i = 0; i < this.newDoors.size(); ++i) { - VillageDoorInfo villagedoorinfo = (VillageDoorInfo) this.newDoors.get(i); - Village village = this.getNearestVillage(villagedoorinfo.getDoorBlockPos(), 32); - if (village == null) { - village = new Village(this.worldObj); - this.villageList.add(village); - this.markDirty(); - } - - village.addVillageDoorInfo(villagedoorinfo); - } - - this.newDoors.clear(); - } - private void addDoorsAround(BlockPos central) { byte b0 = 16; byte b1 = 4; @@ -177,9 +89,45 @@ public class VillageCollection extends WorldSavedData { } - /**+ - * returns the VillageDoorInfo if it exists in any village or in - * the newDoor list, otherwise returns null + private void addNewDoorsToVillageOrCreateVillage() { + for (int i = 0; i < this.newDoors.size(); ++i) { + VillageDoorInfo villagedoorinfo = (VillageDoorInfo) this.newDoors.get(i); + Village village = this.getNearestVillage(villagedoorinfo.getDoorBlockPos(), 32); + if (village == null) { + village = new Village(this.worldObj); + this.villageList.add(village); + this.markDirty(); + } + + village.addVillageDoorInfo(villagedoorinfo); + } + + this.newDoors.clear(); + } + + private void addToNewDoorsList(BlockPos doorBlock) { + EnumFacing enumfacing = BlockDoor.getFacing(this.worldObj, doorBlock); + EnumFacing enumfacing1 = enumfacing.getOpposite(); + int i = this.countBlocksCanSeeSky(doorBlock, enumfacing, 5); + int j = this.countBlocksCanSeeSky(doorBlock, enumfacing1, i + 1); + if (i != j) { + this.newDoors.add(new VillageDoorInfo(doorBlock, i < j ? enumfacing : enumfacing1, this.tickCounter)); + } + + } + + public void addToVillagerPositionList(BlockPos pos) { + if (this.villagerPositionsList.size() <= 64) { + if (!this.positionInList(pos)) { + this.villagerPositionsList.add(pos); + } + + } + } + + /** + * + returns the VillageDoorInfo if it exists in any village or in the newDoor + * list, otherwise returns null */ private VillageDoorInfo checkDoorExistence(BlockPos doorBlock) { for (int i = 0, l = this.newDoors.size(); i < l; ++i) { @@ -201,20 +149,8 @@ public class VillageCollection extends WorldSavedData { return null; } - private void addToNewDoorsList(BlockPos doorBlock) { - EnumFacing enumfacing = BlockDoor.getFacing(this.worldObj, doorBlock); - EnumFacing enumfacing1 = enumfacing.getOpposite(); - int i = this.countBlocksCanSeeSky(doorBlock, enumfacing, 5); - int j = this.countBlocksCanSeeSky(doorBlock, enumfacing1, i + 1); - if (i != j) { - this.newDoors.add(new VillageDoorInfo(doorBlock, i < j ? enumfacing : enumfacing1, this.tickCounter)); - } - - } - - /**+ - * Check five blocks in the direction. The centerPos will not be - * checked. + /** + * + Check five blocks in the direction. The centerPos will not be checked. */ private int countBlocksCanSeeSky(BlockPos centerPos, EnumFacing direction, int limitation) { int i = 0; @@ -231,6 +167,43 @@ public class VillageCollection extends WorldSavedData { return i; } + private void dropOldestVillagerPosition() { + if (!this.villagerPositionsList.isEmpty()) { + this.addDoorsAround((BlockPos) this.villagerPositionsList.remove(0)); + } + } + + public Village getNearestVillage(BlockPos doorBlock, int radius) { + Village village = null; + double d0 = 3.4028234663852886E38D; + + for (int i = 0, l = this.villageList.size(); i < l; ++i) { + Village village1 = this.villageList.get(i); + double d1 = village1.getCenter().distanceSq(doorBlock); + if (d1 < d0) { + float f = (float) (radius + village1.getVillageRadius()); + if (d1 <= (double) (f * f)) { + village = village1; + d0 = d1; + } + } + } + + return village; + } + + /** + * + Get a list of villages. + */ + public List getVillageList() { + return this.villageList; + } + + private boolean isWoodDoor(BlockPos doorPos) { + Block block = this.worldObj.getBlockState(doorPos).getBlock(); + return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; + } + private boolean positionInList(BlockPos pos) { for (int i = 0, l = this.villagerPositionsList.size(); i < l; ++i) { if (this.villagerPositionsList.get(i).equals(pos)) { @@ -241,13 +214,8 @@ public class VillageCollection extends WorldSavedData { return false; } - private boolean isWoodDoor(BlockPos doorPos) { - Block block = this.worldObj.getBlockState(doorPos).getBlock(); - return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; - } - - /**+ - * reads in data from the NBTTagCompound into this MapDataBase + /** + * + reads in data from the NBTTagCompound into this MapDataBase */ public void readFromNBT(NBTTagCompound nbttagcompound) { this.tickCounter = nbttagcompound.getInteger("Tick"); @@ -262,9 +230,50 @@ public class VillageCollection extends WorldSavedData { } - /**+ - * write data to NBTTagCompound from this MapDataBase, similar - * to Entities and TileEntities + private void removeAnnihilatedVillages() { + Iterator iterator = this.villageList.iterator(); + + while (iterator.hasNext()) { + Village village = (Village) iterator.next(); + if (village.isAnnihilated()) { + iterator.remove(); + this.markDirty(); + } + } + + } + + public void setWorldsForAll(World worldIn) { + this.worldObj = worldIn; + + for (int i = 0, l = this.villageList.size(); i < l; ++i) { + this.villageList.get(i).setWorld(worldIn); + } + + } + + /** + * + Runs a single tick for the village collection + */ + public void tick() { + ++this.tickCounter; + + for (int i = 0, l = this.villageList.size(); i < l; ++i) { + this.villageList.get(i).tick(this.tickCounter); + } + + this.removeAnnihilatedVillages(); + this.dropOldestVillagerPosition(); + this.addNewDoorsToVillageOrCreateVillage(); + if (this.tickCounter % 400 == 0) { + this.markDirty(); + } + + } + + /** + * + write data to NBTTagCompound from this MapDataBase, similar to Entities and + * TileEntities */ public void writeToNBT(NBTTagCompound nbttagcompound) { nbttagcompound.setInteger("Tick", this.tickCounter); @@ -278,8 +287,4 @@ public class VillageCollection extends WorldSavedData { nbttagcompound.setTag("Villages", nbttaglist); } - - public static String fileNameForProvider(WorldProvider provider) { - return "villages" + provider.getInternalNameSuffix(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/village/VillageDoorInfo.java b/src/game/java/net/minecraft/village/VillageDoorInfo.java index 867f9124..cef75249 100644 --- a/src/game/java/net/minecraft/village/VillageDoorInfo.java +++ b/src/game/java/net/minecraft/village/VillageDoorInfo.java @@ -3,43 +3,43 @@ package net.minecraft.village; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class VillageDoorInfo { + private static EnumFacing getFaceDirection(int deltaX, int deltaZ) { + return deltaX < 0 ? EnumFacing.WEST + : (deltaX > 0 ? EnumFacing.EAST : (deltaZ < 0 ? EnumFacing.NORTH : EnumFacing.SOUTH)); + } + private final BlockPos doorBlockPos; private final BlockPos insideBlock; private final EnumFacing insideDirection; private int lastActivityTimestamp; private boolean isDetachedFromVillageFlag; + private int doorOpeningRestrictionCounter; - public VillageDoorInfo(BlockPos parBlockPos, int parInt1, int parInt2, int parInt3) { - this(parBlockPos, getFaceDirection(parInt1, parInt2), parInt3); - } - - private static EnumFacing getFaceDirection(int deltaX, int deltaZ) { - return deltaX < 0 ? EnumFacing.WEST - : (deltaX > 0 ? EnumFacing.EAST : (deltaZ < 0 ? EnumFacing.NORTH : EnumFacing.SOUTH)); - } - public VillageDoorInfo(BlockPos parBlockPos, EnumFacing parEnumFacing, int parInt1) { this.doorBlockPos = parBlockPos; this.insideDirection = parEnumFacing; @@ -47,9 +47,22 @@ public class VillageDoorInfo { this.lastActivityTimestamp = parInt1; } - /**+ - * Returns the squared distance between this door and the given - * coordinate. + public VillageDoorInfo(BlockPos parBlockPos, int parInt1, int parInt2, int parInt3) { + this(parBlockPos, getFaceDirection(parInt1, parInt2), parInt3); + } + + public void func_179849_a(int parInt1) { + this.lastActivityTimestamp = parInt1; + } + + public boolean func_179850_c(BlockPos parBlockPos) { + int i = parBlockPos.getX() - this.doorBlockPos.getX(); + int j = parBlockPos.getZ() - this.doorBlockPos.getY(); + return i * this.insideDirection.getFrontOffsetX() + j * this.insideDirection.getFrontOffsetZ() >= 0; + } + + /** + * + Returns the squared distance between this door and the given coordinate. */ public int getDistanceSquared(int parInt1, int parInt2, int parInt3) { return (int) this.doorBlockPos.distanceSq((double) parInt1, (double) parInt2, (double) parInt3); @@ -63,28 +76,14 @@ public class VillageDoorInfo { return (int) this.insideBlock.distanceSq(parBlockPos); } - public boolean func_179850_c(BlockPos parBlockPos) { - int i = parBlockPos.getX() - this.doorBlockPos.getX(); - int j = parBlockPos.getZ() - this.doorBlockPos.getY(); - return i * this.insideDirection.getFrontOffsetX() + j * this.insideDirection.getFrontOffsetZ() >= 0; - } - - public void resetDoorOpeningRestrictionCounter() { - this.doorOpeningRestrictionCounter = 0; - } - - public void incrementDoorOpeningRestrictionCounter() { - ++this.doorOpeningRestrictionCounter; + public BlockPos getDoorBlockPos() { + return this.doorBlockPos; } public int getDoorOpeningRestrictionCounter() { return this.doorOpeningRestrictionCounter; } - public BlockPos getDoorBlockPos() { - return this.doorBlockPos; - } - public BlockPos getInsideBlockPos() { return this.insideBlock; } @@ -101,14 +100,18 @@ public class VillageDoorInfo { return this.lastActivityTimestamp; } - public void func_179849_a(int parInt1) { - this.lastActivityTimestamp = parInt1; - } - public boolean getIsDetachedFromVillageFlag() { return this.isDetachedFromVillageFlag; } + public void incrementDoorOpeningRestrictionCounter() { + ++this.doorOpeningRestrictionCounter; + } + + public void resetDoorOpeningRestrictionCounter() { + this.doorOpeningRestrictionCounter = 0; + } + public void setIsDetachedFromVillageFlag(boolean parFlag) { this.isDetachedFromVillageFlag = parFlag; } diff --git a/src/game/java/net/minecraft/village/VillageSiege.java b/src/game/java/net/minecraft/village/VillageSiege.java index 2648b90a..e4a8f0ca 100644 --- a/src/game/java/net/minecraft/village/VillageSiege.java +++ b/src/game/java/net/minecraft/village/VillageSiege.java @@ -14,22 +14,25 @@ import net.minecraft.util.Vec3; import net.minecraft.world.SpawnerAnimals; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,49 +52,17 @@ public class VillageSiege { this.worldObj = worldIn; } - /**+ - * Runs a single tick for the village siege - */ - public void tick() { - if (this.worldObj.isDaytime()) { - this.field_75536_c = 0; - } else if (this.field_75536_c != 2) { - if (this.field_75536_c == 0) { - float f = this.worldObj.getCelestialAngle(0.0F); - if ((double) f < 0.5D || (double) f > 0.501D) { - return; - } - - this.field_75536_c = this.worldObj.rand.nextInt(10) == 0 ? 1 : 2; - this.field_75535_b = false; - if (this.field_75536_c == 2) { - return; - } - } - - if (this.field_75536_c != -1) { - if (!this.field_75535_b) { - if (!this.func_75529_b()) { - return; - } - - this.field_75535_b = true; - } - - if (this.field_75534_e > 0) { - --this.field_75534_e; - } else { - this.field_75534_e = 2; - if (this.field_75533_d > 0) { - this.spawnZombie(); - --this.field_75533_d; - } else { - this.field_75536_c = 2; - } - - } + private Vec3 func_179867_a(BlockPos parBlockPos) { + for (int i = 0; i < 10; ++i) { + BlockPos blockpos = parBlockPos.add(this.worldObj.rand.nextInt(16) - 8, this.worldObj.rand.nextInt(6) - 3, + this.worldObj.rand.nextInt(16) - 8); + if (this.theVillage.func_179866_a(blockpos) && SpawnerAnimals.canCreatureTypeSpawnAtLocation( + EntityLiving.SpawnPlacementType.ON_GROUND, this.worldObj, blockpos)) { + return new Vec3((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); } } + + return null; } private boolean func_75529_b() { @@ -178,16 +149,48 @@ public class VillageSiege { } } - private Vec3 func_179867_a(BlockPos parBlockPos) { - for (int i = 0; i < 10; ++i) { - BlockPos blockpos = parBlockPos.add(this.worldObj.rand.nextInt(16) - 8, this.worldObj.rand.nextInt(6) - 3, - this.worldObj.rand.nextInt(16) - 8); - if (this.theVillage.func_179866_a(blockpos) && SpawnerAnimals.canCreatureTypeSpawnAtLocation( - EntityLiving.SpawnPlacementType.ON_GROUND, this.worldObj, blockpos)) { - return new Vec3((double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ()); + /** + * + Runs a single tick for the village siege + */ + public void tick() { + if (this.worldObj.isDaytime()) { + this.field_75536_c = 0; + } else if (this.field_75536_c != 2) { + if (this.field_75536_c == 0) { + float f = this.worldObj.getCelestialAngle(0.0F); + if ((double) f < 0.5D || (double) f > 0.501D) { + return; + } + + this.field_75536_c = this.worldObj.rand.nextInt(10) == 0 ? 1 : 2; + this.field_75535_b = false; + if (this.field_75536_c == 2) { + return; + } + } + + if (this.field_75536_c != -1) { + if (!this.field_75535_b) { + if (!this.func_75529_b()) { + return; + } + + this.field_75535_b = true; + } + + if (this.field_75534_e > 0) { + --this.field_75534_e; + } else { + this.field_75534_e = 2; + if (this.field_75533_d > 0) { + this.spawnZombie(); + --this.field_75533_d; + } else { + this.field_75536_c = 2; + } + + } } } - - return null; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/ChunkCache.java b/src/game/java/net/minecraft/world/ChunkCache.java index 3ab56a4c..8ae01327 100644 --- a/src/game/java/net/minecraft/world/ChunkCache.java +++ b/src/game/java/net/minecraft/world/ChunkCache.java @@ -9,22 +9,25 @@ import net.minecraft.util.EnumFacing; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,27 +65,15 @@ public class ChunkCache implements IBlockAccess { } - /**+ - * set by !chunk.getAreLevelsEmpty + /** + * + set by !chunk.getAreLevelsEmpty */ public boolean extendedLevelsInChunkCache() { return this.hasExtendedLevels; } - public TileEntity getTileEntity(BlockPos blockpos) { - int i = (blockpos.getX() >> 4) - this.chunkX; - int j = (blockpos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getTileEntity(blockpos, Chunk.EnumCreateEntityType.IMMEDIATE); - } - - public int getCombinedLight(BlockPos blockpos, int i) { - int j = this.getLightForExt(EnumSkyBlock.SKY, blockpos); - int k = this.getLightForExt(EnumSkyBlock.BLOCK, blockpos); - if (k < i) { - k = i; - } - - return j << 20 | k << 4; + public BiomeGenBase getBiomeGenForCoords(BlockPos blockpos) { + return this.worldObj.getBiomeGenForCoords(blockpos); } public IBlockState getBlockState(BlockPos blockpos) { @@ -100,8 +91,24 @@ public class ChunkCache implements IBlockAccess { return Blocks.air.getDefaultState(); } - public BiomeGenBase getBiomeGenForCoords(BlockPos blockpos) { - return this.worldObj.getBiomeGenForCoords(blockpos); + public int getCombinedLight(BlockPos blockpos, int i) { + int j = this.getLightForExt(EnumSkyBlock.SKY, blockpos); + int k = this.getLightForExt(EnumSkyBlock.BLOCK, blockpos); + if (k < i) { + k = i; + } + + return j << 20 | k << 4; + } + + public int getLightFor(EnumSkyBlock pos, BlockPos parBlockPos) { + if (parBlockPos.getY() >= 0 && parBlockPos.getY() < 256) { + int i = (parBlockPos.getX() >> 4) - this.chunkX; + int j = (parBlockPos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getLightFor(pos, parBlockPos); + } else { + return pos.defaultLightValue; + } } private int getLightForExt(EnumSkyBlock pos, BlockPos parBlockPos) { @@ -135,32 +142,27 @@ public class ChunkCache implements IBlockAccess { } } - /**+ - * Checks to see if an air block exists at the provided - * location. Note that this only checks to see if the blocks - * material is set to air, meaning it is possible for - * non-vanilla blocks to still pass this check. - */ - public boolean isAirBlock(BlockPos blockpos) { - return this.getBlockState(blockpos).getBlock().getMaterial() == Material.air; - } - - public int getLightFor(EnumSkyBlock pos, BlockPos parBlockPos) { - if (parBlockPos.getY() >= 0 && parBlockPos.getY() < 256) { - int i = (parBlockPos.getX() >> 4) - this.chunkX; - int j = (parBlockPos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getLightFor(pos, parBlockPos); - } else { - return pos.defaultLightValue; - } - } - public int getStrongPower(BlockPos blockpos, EnumFacing enumfacing) { IBlockState iblockstate = this.getBlockState(blockpos); return iblockstate.getBlock().getStrongPower(this, blockpos, iblockstate, enumfacing); } + public TileEntity getTileEntity(BlockPos blockpos) { + int i = (blockpos.getX() >> 4) - this.chunkX; + int j = (blockpos.getZ() >> 4) - this.chunkZ; + return this.chunkArray[i][j].getTileEntity(blockpos, Chunk.EnumCreateEntityType.IMMEDIATE); + } + public WorldType getWorldType() { return this.worldObj.getWorldType(); } + + /** + * + Checks to see if an air block exists at the provided location. Note that + * this only checks to see if the blocks material is set to air, meaning it is + * possible for non-vanilla blocks to still pass this check. + */ + public boolean isAirBlock(BlockPos blockpos) { + return this.getBlockState(blockpos).getBlock().getMaterial() == Material.air; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/ChunkCoordIntPair.java b/src/game/java/net/minecraft/world/ChunkCoordIntPair.java index 3dc6240f..e61e8787 100644 --- a/src/game/java/net/minecraft/world/ChunkCoordIntPair.java +++ b/src/game/java/net/minecraft/world/ChunkCoordIntPair.java @@ -2,47 +2,44 @@ package net.minecraft.world; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChunkCoordIntPair { - public final int chunkXPos; - public final int chunkZPos; - - public ChunkCoordIntPair(int x, int z) { - this.chunkXPos = x; - this.chunkZPos = z; - } - - /**+ - * converts a chunk coordinate pair to an integer (suitable for - * hashing) + /** + * + converts a chunk coordinate pair to an integer (suitable for hashing) */ public static long chunkXZ2Int(int x, int z) { return (long) x & 4294967295L | ((long) z & 4294967295L) << 32; } - public int hashCode() { - int i = 1664525 * this.chunkXPos + 1013904223; - int j = 1664525 * (this.chunkZPos ^ -559038737) + 1013904223; - return i ^ j; + public final int chunkXPos; + + public final int chunkZPos; + + public ChunkCoordIntPair(int x, int z) { + this.chunkXPos = x; + this.chunkZPos = z; } public boolean equals(Object object) { @@ -56,6 +53,22 @@ public class ChunkCoordIntPair { } } + /** + * + Get the World coordinates of the Block with the given Chunk coordinates + * relative to this chunk + */ + public BlockPos getBlock(int x, int y, int z) { + return new BlockPos((this.chunkXPos << 4) + x, y, (this.chunkZPos << 4) + z); + } + + /** + * + Get the coordinates of the Block in the center of this chunk with the given + * Y coordinate + */ + public BlockPos getCenterBlock(int y) { + return new BlockPos(this.getCenterXPos(), y, this.getCenterZPosition()); + } + public int getCenterXPos() { return (this.chunkXPos << 4) + 8; } @@ -64,48 +77,38 @@ public class ChunkCoordIntPair { return (this.chunkZPos << 4) + 8; } - /**+ - * Get the first world X coordinate that belongs to this Chunk - */ - public int getXStart() { - return this.chunkXPos << 4; - } - - /**+ - * Get the first world Z coordinate that belongs to this Chunk - */ - public int getZStart() { - return this.chunkZPos << 4; - } - - /**+ - * Get the last world X coordinate that belongs to this Chunk + /** + * + Get the last world X coordinate that belongs to this Chunk */ public int getXEnd() { return (this.chunkXPos << 4) + 15; } - /**+ - * Get the last world Z coordinate that belongs to this Chunk + /** + * + Get the first world X coordinate that belongs to this Chunk + */ + public int getXStart() { + return this.chunkXPos << 4; + } + + /** + * + Get the last world Z coordinate that belongs to this Chunk */ public int getZEnd() { return (this.chunkZPos << 4) + 15; } - /**+ - * Get the World coordinates of the Block with the given Chunk - * coordinates relative to this chunk + /** + * + Get the first world Z coordinate that belongs to this Chunk */ - public BlockPos getBlock(int x, int y, int z) { - return new BlockPos((this.chunkXPos << 4) + x, y, (this.chunkZPos << 4) + z); + public int getZStart() { + return this.chunkZPos << 4; } - /**+ - * Get the coordinates of the Block in the center of this chunk - * with the given Y coordinate - */ - public BlockPos getCenterBlock(int y) { - return new BlockPos(this.getCenterXPos(), y, this.getCenterZPosition()); + public int hashCode() { + int i = 1664525 * this.chunkXPos + 1013904223; + int j = 1664525 * (this.chunkZPos ^ -559038737) + 1013904223; + return i ^ j; } public String toString() { diff --git a/src/game/java/net/minecraft/world/ColorizerFoliage.java b/src/game/java/net/minecraft/world/ColorizerFoliage.java index fc6215cf..699bf51b 100644 --- a/src/game/java/net/minecraft/world/ColorizerFoliage.java +++ b/src/game/java/net/minecraft/world/ColorizerFoliage.java @@ -1,38 +1,37 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ColorizerFoliage { - /**+ - * Color buffer for foliage + /** + * + Color buffer for foliage */ private static int[] foliageBuffer = new int[65536]; - public static void setFoliageBiomeColorizer(int[] parArrayOfInt) { - foliageBuffer = parArrayOfInt; - } - - /**+ - * Gets foliage color from temperature and humidity. Args: - * temperature, humidity + /** + * + Gets foliage color from temperature and humidity. Args: temperature, + * humidity */ public static int getFoliageColor(double parDouble1, double parDouble2) { parDouble2 = parDouble2 * parDouble1; @@ -41,21 +40,25 @@ public class ColorizerFoliage { return foliageBuffer[j << 8 | i]; } - /**+ - * Gets the foliage color for pine type (metadata 1) trees - */ - public static int getFoliageColorPine() { - return 6396257; + public static int getFoliageColorBasic() { + return 4764952; } - /**+ - * Gets the foliage color for birch type (metadata 2) trees + /** + * + Gets the foliage color for birch type (metadata 2) trees */ public static int getFoliageColorBirch() { return 8431445; } - public static int getFoliageColorBasic() { - return 4764952; + /** + * + Gets the foliage color for pine type (metadata 1) trees + */ + public static int getFoliageColorPine() { + return 6396257; + } + + public static void setFoliageBiomeColorizer(int[] parArrayOfInt) { + foliageBuffer = parArrayOfInt; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/ColorizerGrass.java b/src/game/java/net/minecraft/world/ColorizerGrass.java index 434f3010..aa317f8e 100644 --- a/src/game/java/net/minecraft/world/ColorizerGrass.java +++ b/src/game/java/net/minecraft/world/ColorizerGrass.java @@ -1,38 +1,36 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ColorizerGrass { - /**+ - * Color buffer for grass + /** + * + Color buffer for grass */ private static int[] grassBuffer = new int[65536]; - public static void setGrassBiomeColorizer(int[] parArrayOfInt) { - grassBuffer = parArrayOfInt; - } - - /**+ - * Gets grass color from temperature and humidity. Args: - * temperature, humidity + /** + * + Gets grass color from temperature and humidity. Args: temperature, humidity */ public static int getGrassColor(double parDouble1, double parDouble2) { parDouble2 = parDouble2 * parDouble1; @@ -41,4 +39,8 @@ public class ColorizerGrass { int k = j << 8 | i; return k > grassBuffer.length ? -65281 : grassBuffer[k]; } + + public static void setGrassBiomeColorizer(int[] parArrayOfInt) { + grassBuffer = parArrayOfInt; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/DifficultyInstance.java b/src/game/java/net/minecraft/world/DifficultyInstance.java index 2d0c899c..fffd8b5a 100644 --- a/src/game/java/net/minecraft/world/DifficultyInstance.java +++ b/src/game/java/net/minecraft/world/DifficultyInstance.java @@ -2,22 +2,25 @@ package net.minecraft.world; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,15 +36,6 @@ public class DifficultyInstance { moonPhaseFactor); } - public float getAdditionalDifficulty() { - return this.additionalDifficulty; - } - - public float getClampedAdditionalDifficulty() { - return this.additionalDifficulty < 2.0F ? 0.0F - : (this.additionalDifficulty > 4.0F ? 1.0F : (this.additionalDifficulty - 2.0F) / 2.0F); - } - private float calculateAdditionalDifficulty(EnumDifficulty difficulty, long worldTime, long chunkInhabitedTime, float moonPhaseFactor) { if (difficulty == EnumDifficulty.PEACEFUL) { @@ -63,4 +57,13 @@ public class DifficultyInstance { return (float) difficulty.getDifficultyId() * f; } } + + public float getAdditionalDifficulty() { + return this.additionalDifficulty; + } + + public float getClampedAdditionalDifficulty() { + return this.additionalDifficulty < 2.0F ? 0.0F + : (this.additionalDifficulty > 4.0F ? 1.0F : (this.additionalDifficulty - 2.0F) / 2.0F); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/EnumDifficulty.java b/src/game/java/net/minecraft/world/EnumDifficulty.java index 862bdaac..50f96f44 100644 --- a/src/game/java/net/minecraft/world/EnumDifficulty.java +++ b/src/game/java/net/minecraft/world/EnumDifficulty.java @@ -1,21 +1,24 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,7 +28,20 @@ public enum EnumDifficulty { NORMAL(2, "options.difficulty.normal"), HARD(3, "options.difficulty.hard"); private static final EnumDifficulty[] difficultyEnums = new EnumDifficulty[4]; + static { + EnumDifficulty[] types = values(); + for (int i = 0; i < types.length; ++i) { + difficultyEnums[types[i].difficultyId] = types[i]; + } + + } + + public static EnumDifficulty getDifficultyEnum(int parInt1) { + return difficultyEnums[parInt1 % difficultyEnums.length]; + } + private final int difficultyId; + private final String difficultyResourceKey; private EnumDifficulty(int difficultyIdIn, String difficultyResourceKeyIn) { @@ -37,19 +53,7 @@ public enum EnumDifficulty { return this.difficultyId; } - public static EnumDifficulty getDifficultyEnum(int parInt1) { - return difficultyEnums[parInt1 % difficultyEnums.length]; - } - public String getDifficultyResourceKey() { return this.difficultyResourceKey; } - - static { - EnumDifficulty[] types = values(); - for (int i = 0; i < types.length; ++i) { - difficultyEnums[types[i].difficultyId] = types[i]; - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/EnumSkyBlock.java b/src/game/java/net/minecraft/world/EnumSkyBlock.java index 2bcc0214..4bb03ee9 100644 --- a/src/game/java/net/minecraft/world/EnumSkyBlock.java +++ b/src/game/java/net/minecraft/world/EnumSkyBlock.java @@ -1,21 +1,24 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/Explosion.java b/src/game/java/net/minecraft/world/Explosion.java index 59b91301..685c2638 100644 --- a/src/game/java/net/minecraft/world/Explosion.java +++ b/src/game/java/net/minecraft/world/Explosion.java @@ -3,12 +3,12 @@ package net.minecraft.world; import java.util.HashSet; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -26,22 +26,25 @@ import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -59,17 +62,6 @@ public class Explosion { private final List affectedBlockPositions; private final Map playerKnockbackMap; - public Explosion(World worldIn, Entity parEntity, double parDouble1, double parDouble2, double parDouble3, - float parFloat1, List parList) { - this(worldIn, parEntity, parDouble1, parDouble2, parDouble3, parFloat1, false, true, parList); - } - - public Explosion(World worldIn, Entity parEntity, double parDouble1, double parDouble2, double parDouble3, - float parFloat1, boolean parFlag, boolean parFlag2, List parList) { - this(worldIn, parEntity, parDouble1, parDouble2, parDouble3, parFloat1, parFlag, parFlag2); - this.affectedBlockPositions.addAll(parList); - } - public Explosion(World worldIn, Entity parEntity, double parDouble1, double parDouble2, double parDouble3, float size, boolean parFlag, boolean parFlag2) { this.explosionRNG = new EaglercraftRandom(); @@ -85,8 +77,19 @@ public class Explosion { this.isSmoking = parFlag2; } - /**+ - * Does the first part of the explosion (destroy blocks) + public Explosion(World worldIn, Entity parEntity, double parDouble1, double parDouble2, double parDouble3, + float parFloat1, boolean parFlag, boolean parFlag2, List parList) { + this(worldIn, parEntity, parDouble1, parDouble2, parDouble3, parFloat1, parFlag, parFlag2); + this.affectedBlockPositions.addAll(parList); + } + + public Explosion(World worldIn, Entity parEntity, double parDouble1, double parDouble2, double parDouble3, + float parFloat1, List parList) { + this(worldIn, parEntity, parDouble1, parDouble2, parDouble3, parFloat1, false, true, parList); + } + + /** + * + Does the first part of the explosion (destroy blocks) */ public void doExplosionA() { HashSet hashset = Sets.newHashSet(); @@ -176,9 +179,8 @@ public class Explosion { } - /**+ - * Does the second part of the explosion (sound, particles, drop - * spawn) + /** + * + Does the second part of the explosion (sound, particles, drop spawn) */ public void doExplosionB(boolean spawnParticles) { this.worldObj.playSoundEffect(this.explosionX, this.explosionY, this.explosionZ, "random.explode", 4.0F, @@ -243,20 +245,6 @@ public class Explosion { } - public Map getPlayerKnockbackMap() { - return this.playerKnockbackMap; - } - - /**+ - * Returns either the entity that placed the explosive block, - * the entity that caused the explosion or null. - */ - public EntityLivingBase getExplosivePlacedBy() { - return this.exploder == null ? null - : (this.exploder instanceof EntityTNTPrimed ? ((EntityTNTPrimed) this.exploder).getTntPlacedBy() - : (this.exploder instanceof EntityLivingBase ? (EntityLivingBase) this.exploder : null)); - } - public void func_180342_d() { this.affectedBlockPositions.clear(); } @@ -264,4 +252,18 @@ public class Explosion { public List getAffectedBlockPositions() { return this.affectedBlockPositions; } + + /** + * + Returns either the entity that placed the explosive block, the entity that + * caused the explosion or null. + */ + public EntityLivingBase getExplosivePlacedBy() { + return this.exploder == null ? null + : (this.exploder instanceof EntityTNTPrimed ? ((EntityTNTPrimed) this.exploder).getTntPlacedBy() + : (this.exploder instanceof EntityLivingBase ? (EntityLivingBase) this.exploder : null)); + } + + public Map getPlayerKnockbackMap() { + return this.playerKnockbackMap; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/GameRules.java b/src/game/java/net/minecraft/world/GameRules.java index a4449408..1275713c 100644 --- a/src/game/java/net/minecraft/world/GameRules.java +++ b/src/game/java/net/minecraft/world/GameRules.java @@ -5,27 +5,88 @@ import java.util.TreeMap; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GameRules { + static class Value { + private String valueString; + private boolean valueBoolean; + private int valueInteger; + private double valueDouble; + private final GameRules.ValueType type; + + public Value(String value, GameRules.ValueType type) { + this.type = type; + this.setValue(value); + } + + /** + * + Gets the boolean Game Rule value. + */ + public boolean getBoolean() { + return this.valueBoolean; + } + + public int getInt() { + return this.valueInteger; + } + + /** + * + Gets the string Game Rule value. + */ + public String getString() { + return this.valueString; + } + + public GameRules.ValueType getType() { + return this.type; + } + + public void setValue(String value) { + this.valueString = value; + this.valueBoolean = Boolean.parseBoolean(value); + this.valueInteger = this.valueBoolean ? 1 : 0; + + try { + this.valueInteger = Integer.parseInt(value); + } catch (NumberFormatException var4) { + ; + } + + try { + this.valueDouble = Double.parseDouble(value); + } catch (NumberFormatException var3) { + ; + } + + } + } + + public static enum ValueType { + ANY_VALUE, BOOLEAN_VALUE, NUMERICAL_VALUE; + } + private TreeMap theGameRules = new TreeMap(); public GameRules() { @@ -57,26 +118,14 @@ public class GameRules { this.theGameRules.put(key, new GameRules.Value(value, type)); } - public void setOrCreateGameRule(String key, String ruleValue) { + public boolean areSameType(String key, GameRules.ValueType otherValue) { GameRules.Value gamerules$value = (GameRules.Value) this.theGameRules.get(key); - if (gamerules$value != null) { - gamerules$value.setValue(ruleValue); - } else { - this.addGameRule(key, ruleValue, GameRules.ValueType.ANY_VALUE); - } - + return gamerules$value != null + && (gamerules$value.getType() == otherValue || otherValue == GameRules.ValueType.ANY_VALUE); } - /**+ - * Gets the string Game Rule value. - */ - public String getString(String name) { - GameRules.Value gamerules$value = (GameRules.Value) this.theGameRules.get(name); - return gamerules$value != null ? gamerules$value.getString() : ""; - } - - /**+ - * Gets the boolean Game Rule value. + /** + * + Gets the boolean Game Rule value. */ public boolean getBoolean(String name) { GameRules.Value gamerules$value = (GameRules.Value) this.theGameRules.get(name); @@ -88,8 +137,52 @@ public class GameRules { return gamerules$value != null ? gamerules$value.getInt() : 0; } - /**+ - * Return the defined game rules as NBT. + /** + * + Return the defined game rules. + */ + public String[] getRules() { + Set set = this.theGameRules.keySet(); + return (String[]) set.toArray(new String[set.size()]); + } + + /** + * + Gets the string Game Rule value. + */ + public String getString(String name) { + GameRules.Value gamerules$value = (GameRules.Value) this.theGameRules.get(name); + return gamerules$value != null ? gamerules$value.getString() : ""; + } + + /** + * + Return whether the specified game rule is defined. + */ + public boolean hasRule(String name) { + return this.theGameRules.containsKey(name); + } + + /** + * + Set defined game rules from NBT. + */ + public void readFromNBT(NBTTagCompound nbt) { + for (String s : nbt.getKeySet()) { + String s1 = nbt.getString(s); + this.setOrCreateGameRule(s, s1); + } + + } + + public void setOrCreateGameRule(String key, String ruleValue) { + GameRules.Value gamerules$value = (GameRules.Value) this.theGameRules.get(key); + if (gamerules$value != null) { + gamerules$value.setValue(ruleValue); + } else { + this.addGameRule(key, ruleValue, GameRules.ValueType.ANY_VALUE); + } + + } + + /** + * + Return the defined game rules as NBT. */ public NBTTagCompound writeToNBT() { NBTTagCompound nbttagcompound = new NBTTagCompound(); @@ -101,94 +194,4 @@ public class GameRules { return nbttagcompound; } - - /**+ - * Set defined game rules from NBT. - */ - public void readFromNBT(NBTTagCompound nbt) { - for (String s : nbt.getKeySet()) { - String s1 = nbt.getString(s); - this.setOrCreateGameRule(s, s1); - } - - } - - /**+ - * Return the defined game rules. - */ - public String[] getRules() { - Set set = this.theGameRules.keySet(); - return (String[]) set.toArray(new String[set.size()]); - } - - /**+ - * Return whether the specified game rule is defined. - */ - public boolean hasRule(String name) { - return this.theGameRules.containsKey(name); - } - - public boolean areSameType(String key, GameRules.ValueType otherValue) { - GameRules.Value gamerules$value = (GameRules.Value) this.theGameRules.get(key); - return gamerules$value != null - && (gamerules$value.getType() == otherValue || otherValue == GameRules.ValueType.ANY_VALUE); - } - - static class Value { - private String valueString; - private boolean valueBoolean; - private int valueInteger; - private double valueDouble; - private final GameRules.ValueType type; - - public Value(String value, GameRules.ValueType type) { - this.type = type; - this.setValue(value); - } - - public void setValue(String value) { - this.valueString = value; - this.valueBoolean = Boolean.parseBoolean(value); - this.valueInteger = this.valueBoolean ? 1 : 0; - - try { - this.valueInteger = Integer.parseInt(value); - } catch (NumberFormatException var4) { - ; - } - - try { - this.valueDouble = Double.parseDouble(value); - } catch (NumberFormatException var3) { - ; - } - - } - - /**+ - * Gets the string Game Rule value. - */ - public String getString() { - return this.valueString; - } - - /**+ - * Gets the boolean Game Rule value. - */ - public boolean getBoolean() { - return this.valueBoolean; - } - - public int getInt() { - return this.valueInteger; - } - - public GameRules.ValueType getType() { - return this.type; - } - } - - public static enum ValueType { - ANY_VALUE, BOOLEAN_VALUE, NUMERICAL_VALUE; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/IBlockAccess.java b/src/game/java/net/minecraft/world/IBlockAccess.java index d8538c53..43aaa2e8 100644 --- a/src/game/java/net/minecraft/world/IBlockAccess.java +++ b/src/game/java/net/minecraft/world/IBlockAccess.java @@ -6,49 +6,51 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IBlockAccess { - TileEntity getTileEntity(BlockPos var1); - - int getCombinedLight(BlockPos var1, int var2); - - IBlockState getBlockState(BlockPos var1); - - /**+ - * Checks to see if an air block exists at the provided - * location. Note that this only checks to see if the blocks - * material is set to air, meaning it is possible for - * non-vanilla blocks to still pass this check. - */ - boolean isAirBlock(BlockPos var1); - - BiomeGenBase getBiomeGenForCoords(BlockPos var1); - - /**+ - * set by !chunk.getAreLevelsEmpty + /** + * + set by !chunk.getAreLevelsEmpty */ boolean extendedLevelsInChunkCache(); + BiomeGenBase getBiomeGenForCoords(BlockPos var1); + + IBlockState getBlockState(BlockPos var1); + + int getCombinedLight(BlockPos var1, int var2); + int getStrongPower(BlockPos var1, EnumFacing var2); + TileEntity getTileEntity(BlockPos var1); + WorldType getWorldType(); + + /** + * + Checks to see if an air block exists at the provided location. Note that + * this only checks to see if the blocks material is set to air, meaning it is + * possible for non-vanilla blocks to still pass this check. + */ + boolean isAirBlock(BlockPos var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/IInteractionObject.java b/src/game/java/net/minecraft/world/IInteractionObject.java index cee350a6..655efaac 100644 --- a/src/game/java/net/minecraft/world/IInteractionObject.java +++ b/src/game/java/net/minecraft/world/IInteractionObject.java @@ -4,22 +4,25 @@ import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Container; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/ILockableContainer.java b/src/game/java/net/minecraft/world/ILockableContainer.java index 112a4c4a..9d37fa93 100644 --- a/src/game/java/net/minecraft/world/ILockableContainer.java +++ b/src/game/java/net/minecraft/world/ILockableContainer.java @@ -2,30 +2,33 @@ package net.minecraft.world; import net.minecraft.inventory.IInventory; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ILockableContainer extends IInventory, IInteractionObject { + LockCode getLockCode(); + boolean isLocked(); void setLockCode(LockCode var1); - - LockCode getLockCode(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/IWorldAccess.java b/src/game/java/net/minecraft/world/IWorldAccess.java index c42db99d..46cfcfbc 100644 --- a/src/game/java/net/minecraft/world/IWorldAccess.java +++ b/src/game/java/net/minecraft/world/IWorldAccess.java @@ -4,75 +4,73 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IWorldAccess { + void broadcastSound(int var1, BlockPos var2, int var3); + void markBlockForUpdate(BlockPos var1); - void notifyLightSet(BlockPos var1); - - /**+ - * On the client, re-renders all blocks in this range, - * inclusive. On the server, does nothing. Args: min x, min y, - * min z, max x, max y, max z + /** + * + On the client, re-renders all blocks in this range, inclusive. On the + * server, does nothing. Args: min x, min y, min z, max x, max y, max z */ void markBlockRangeForRenderUpdate(int var1, int var2, int var3, int var4, int var5, int var6); - /**+ - * Plays the specified sound. Arg: soundName, x, y, z, volume, - * pitch + void notifyLightSet(BlockPos var1); + + /** + * + Called on all IWorldAccesses when an entity is created or loaded. On client + * worlds, starts downloading any necessary textures. On server worlds, adds the + * entity to the entity tracker. + */ + void onEntityAdded(Entity var1); + + /** + * + Called on all IWorldAccesses when an entity is unloaded or destroyed. On + * client worlds, releases any downloaded textures. On server worlds, removes + * the entity from the entity tracker. + */ + void onEntityRemoved(Entity var1); + + void playAuxSFX(EntityPlayer var1, int var2, BlockPos var3, int var4); + + void playRecord(String var1, BlockPos var2); + + /** + * + Plays the specified sound. Arg: soundName, x, y, z, volume, pitch */ void playSound(String var1, double var2, double var4, double var6, float var8, float var9); - /**+ - * Plays sound to all near players except the player reference - * given + /** + * + Plays sound to all near players except the player reference given */ void playSoundToNearExcept(EntityPlayer var1, String var2, double var3, double var5, double var7, float var9, float var10); + void sendBlockBreakProgress(int var1, BlockPos var2, int var3); + void spawnParticle(int var1, boolean var2, double var3, double var5, double var7, double var9, double var11, double var13, int... var15); - - /**+ - * Called on all IWorldAccesses when an entity is created or - * loaded. On client worlds, starts downloading any necessary - * textures. On server worlds, adds the entity to the entity - * tracker. - */ - void onEntityAdded(Entity var1); - - /**+ - * Called on all IWorldAccesses when an entity is unloaded or - * destroyed. On client worlds, releases any downloaded - * textures. On server worlds, removes the entity from the - * entity tracker. - */ - void onEntityRemoved(Entity var1); - - void playRecord(String var1, BlockPos var2); - - void broadcastSound(int var1, BlockPos var2, int var3); - - void playAuxSFX(EntityPlayer var1, int var2, BlockPos var3, int var4); - - void sendBlockBreakProgress(int var1, BlockPos var2, int var3); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/IWorldNameable.java b/src/game/java/net/minecraft/world/IWorldNameable.java index b4f46d5b..3a17dbcd 100644 --- a/src/game/java/net/minecraft/world/IWorldNameable.java +++ b/src/game/java/net/minecraft/world/IWorldNameable.java @@ -2,41 +2,44 @@ package net.minecraft.world; import net.minecraft.util.IChatComponent; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IWorldNameable { - /**+ - * Gets the name of this command sender (usually username, but - * possibly "Rcon") + /** + * + Get the formatted ChatComponent that will be used for the sender's username + * in chat + */ + IChatComponent getDisplayName(); + + /** + * + Gets the name of this command sender (usually username, but possibly + * "Rcon") */ String getName(); - /**+ - * Returns true if this thing is named + /** + * + Returns true if this thing is named */ boolean hasCustomName(); - - /**+ - * Get the formatted ChatComponent that will be used for the - * sender's username in chat - */ - IChatComponent getDisplayName(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/LockCode.java b/src/game/java/net/minecraft/world/LockCode.java index 9d72940e..ab50ded4 100644 --- a/src/game/java/net/minecraft/world/LockCode.java +++ b/src/game/java/net/minecraft/world/LockCode.java @@ -2,45 +2,31 @@ package net.minecraft.world; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LockCode { public static final LockCode EMPTY_CODE = new LockCode(""); - private final String lock; - - public LockCode(String code) { - this.lock = code; - } - - public boolean isEmpty() { - return this.lock == null || this.lock.isEmpty(); - } - - public String getLock() { - return this.lock; - } - - public void toNBT(NBTTagCompound nbt) { - nbt.setString("Lock", this.lock); - } public static LockCode fromNBT(NBTTagCompound nbt) { if (nbt.hasKey("Lock", 8)) { @@ -50,4 +36,22 @@ public class LockCode { return EMPTY_CODE; } } + + private final String lock; + + public LockCode(String code) { + this.lock = code; + } + + public String getLock() { + return this.lock; + } + + public boolean isEmpty() { + return this.lock == null || this.lock.isEmpty(); + } + + public void toNBT(NBTTagCompound nbt) { + nbt.setString("Lock", this.lock); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/MinecraftException.java b/src/game/java/net/minecraft/world/MinecraftException.java index 3c328445..5e5f1bee 100644 --- a/src/game/java/net/minecraft/world/MinecraftException.java +++ b/src/game/java/net/minecraft/world/MinecraftException.java @@ -1,21 +1,24 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/NextTickListEntry.java b/src/game/java/net/minecraft/world/NextTickListEntry.java index bead7b8e..23fc074d 100644 --- a/src/game/java/net/minecraft/world/NextTickListEntry.java +++ b/src/game/java/net/minecraft/world/NextTickListEntry.java @@ -3,22 +3,25 @@ package net.minecraft.world; import net.minecraft.block.Block; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +40,15 @@ public class NextTickListEntry implements Comparable { this.block = parBlock; } + public int compareTo(NextTickListEntry parNextTickListEntry) { + return this.scheduledTime < parNextTickListEntry.scheduledTime ? -1 + : (this.scheduledTime > parNextTickListEntry.scheduledTime ? 1 + : (this.priority != parNextTickListEntry.priority + ? this.priority - parNextTickListEntry.priority + : (this.tickEntryID < parNextTickListEntry.tickEntryID ? -1 + : (this.tickEntryID > parNextTickListEntry.tickEntryID ? 1 : 0)))); + } + public boolean equals(Object object) { if (!(object instanceof NextTickListEntry)) { return false; @@ -47,37 +59,28 @@ public class NextTickListEntry implements Comparable { } } - public int hashCode() { - return this.position.hashCode(); + public Block getBlock() { + return this.block; } - /**+ - * Sets the scheduled time for this tick entry - */ - public NextTickListEntry setScheduledTime(long parLong1) { - this.scheduledTime = parLong1; - return this; + public int hashCode() { + return this.position.hashCode(); } public void setPriority(int parInt1) { this.priority = parInt1; } - public int compareTo(NextTickListEntry parNextTickListEntry) { - return this.scheduledTime < parNextTickListEntry.scheduledTime ? -1 - : (this.scheduledTime > parNextTickListEntry.scheduledTime ? 1 - : (this.priority != parNextTickListEntry.priority - ? this.priority - parNextTickListEntry.priority - : (this.tickEntryID < parNextTickListEntry.tickEntryID ? -1 - : (this.tickEntryID > parNextTickListEntry.tickEntryID ? 1 : 0)))); + /** + * + Sets the scheduled time for this tick entry + */ + public NextTickListEntry setScheduledTime(long parLong1) { + this.scheduledTime = parLong1; + return this; } public String toString() { return Block.getIdFromBlock(this.block) + ": " + this.position + ", " + this.scheduledTime + ", " + this.priority + ", " + this.tickEntryID; } - - public Block getBlock() { - return this.block; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/SpawnerAnimals.java b/src/game/java/net/minecraft/world/SpawnerAnimals.java index 398df466..5865686b 100644 --- a/src/game/java/net/minecraft/world/SpawnerAnimals.java +++ b/src/game/java/net/minecraft/world/SpawnerAnimals.java @@ -1,12 +1,12 @@ package net.minecraft.world; +import java.util.List; +import java.util.Set; + import com.google.common.collect.Sets; -import java.util.List; - import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import java.util.Set; import net.minecraft.block.Block; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; @@ -21,35 +21,128 @@ import net.minecraft.util.WeightedRandom; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public final class SpawnerAnimals { private static final int MOB_COUNT_DIV = (int) Math.pow(17.0D, 2.0D); - /**+ - * The 17x17 area around the player where mobs can spawn + + public static boolean canCreatureTypeSpawnAtLocation(EntityLiving.SpawnPlacementType worldIn, World pos, + BlockPos parBlockPos) { + if (!pos.getWorldBorder().contains(parBlockPos)) { + return false; + } else { + Block block = pos.getBlockState(parBlockPos).getBlock(); + if (worldIn == EntityLiving.SpawnPlacementType.IN_WATER) { + return block.getMaterial().isLiquid() + && pos.getBlockState(parBlockPos.down()).getBlock().getMaterial().isLiquid() + && !pos.getBlockState(parBlockPos.up()).getBlock().isNormalCube(); + } else { + BlockPos blockpos = parBlockPos.down(); + if (!World.doesBlockHaveSolidTopSurface(pos, blockpos)) { + return false; + } else { + Block block1 = pos.getBlockState(blockpos).getBlock(); + boolean flag = block1 != Blocks.bedrock && block1 != Blocks.barrier; + return flag && !block.isNormalCube() && !block.getMaterial().isLiquid() + && !pos.getBlockState(parBlockPos.up()).getBlock().isNormalCube(); + } + } + } + } + + protected static BlockPos getRandomChunkPosition(World worldIn, int x, int z) { + Chunk chunk = worldIn.getChunkFromChunkCoords(x, z); + int i = x * 16 + worldIn.rand.nextInt(16); + int j = z * 16 + worldIn.rand.nextInt(16); + int k = MathHelper.func_154354_b(chunk.getHeight(new BlockPos(i, 0, j)) + 1, 16); + int l = worldIn.rand.nextInt(k > 0 ? k : chunk.getTopFilledSegment() + 16 - 1); + return new BlockPos(i, l, j); + } + + /** + * + Called during chunk generation to spawn initial creatures. + */ + public static void performWorldGenSpawning(World worldIn, BiomeGenBase parBiomeGenBase, int parInt1, int parInt2, + int parInt3, int parInt4, EaglercraftRandom parRandom) { + List list = parBiomeGenBase.getSpawnableList(EnumCreatureType.CREATURE); + if (!list.isEmpty()) { + while (parRandom.nextFloat() < parBiomeGenBase.getSpawningChance()) { + BiomeGenBase.SpawnListEntry biomegenbase$spawnlistentry = (BiomeGenBase.SpawnListEntry) WeightedRandom + .getRandomItem(worldIn.rand, list); + int i = biomegenbase$spawnlistentry.minGroupCount + parRandom.nextInt( + 1 + biomegenbase$spawnlistentry.maxGroupCount - biomegenbase$spawnlistentry.minGroupCount); + IEntityLivingData ientitylivingdata = null; + int j = parInt1 + parRandom.nextInt(parInt3); + int k = parInt2 + parRandom.nextInt(parInt4); + int l = j; + int i1 = k; + + for (int j1 = 0; j1 < i; ++j1) { + boolean flag = false; + + for (int k1 = 0; !flag && k1 < 4; ++k1) { + BlockPos blockpos = worldIn.getTopSolidOrLiquidBlock(new BlockPos(j, 0, k)); + if (canCreatureTypeSpawnAtLocation(EntityLiving.SpawnPlacementType.ON_GROUND, worldIn, + blockpos)) { + EntityLiving entityliving; + try { + entityliving = (EntityLiving) EntityList + .createEntityByClass(biomegenbase$spawnlistentry.entityClass, worldIn); + } catch (Exception exception) { + EagRuntime.debugPrintStackTrace(exception); + continue; + } + + entityliving.setLocationAndAngles((double) ((float) j + 0.5F), (double) blockpos.getY(), + (double) ((float) k + 0.5F), parRandom.nextFloat() * 360.0F, 0.0F); + worldIn.spawnEntityInWorld(entityliving); + ientitylivingdata = entityliving.onInitialSpawn( + worldIn.getDifficultyForLocation(new BlockPos(entityliving)), ientitylivingdata); + flag = true; + } + + j += parRandom.nextInt(5) - parRandom.nextInt(5); + + for (k += parRandom.nextInt(5) - parRandom.nextInt(5); j < parInt1 || j >= parInt1 + parInt3 + || k < parInt2 + || k >= parInt2 + parInt3; k = i1 + parRandom.nextInt(5) - parRandom.nextInt(5)) { + j = l + parRandom.nextInt(5) - parRandom.nextInt(5); + } + } + } + } + + } + } + + /** + * + The 17x17 area around the player where mobs can spawn */ private final Set eligibleChunksForSpawning = Sets.newHashSet(); - /**+ - * adds all chunks within the spawn radius of the players to + /** + * + adds all chunks within the spawn radius of the players to * eligibleChunksForSpawning. pars: the world, hostileCreatures, * passiveCreatures. returns number of eligible chunks. */ @@ -182,93 +275,4 @@ public final class SpawnerAnimals { return k3; } } - - protected static BlockPos getRandomChunkPosition(World worldIn, int x, int z) { - Chunk chunk = worldIn.getChunkFromChunkCoords(x, z); - int i = x * 16 + worldIn.rand.nextInt(16); - int j = z * 16 + worldIn.rand.nextInt(16); - int k = MathHelper.func_154354_b(chunk.getHeight(new BlockPos(i, 0, j)) + 1, 16); - int l = worldIn.rand.nextInt(k > 0 ? k : chunk.getTopFilledSegment() + 16 - 1); - return new BlockPos(i, l, j); - } - - public static boolean canCreatureTypeSpawnAtLocation(EntityLiving.SpawnPlacementType worldIn, World pos, - BlockPos parBlockPos) { - if (!pos.getWorldBorder().contains(parBlockPos)) { - return false; - } else { - Block block = pos.getBlockState(parBlockPos).getBlock(); - if (worldIn == EntityLiving.SpawnPlacementType.IN_WATER) { - return block.getMaterial().isLiquid() - && pos.getBlockState(parBlockPos.down()).getBlock().getMaterial().isLiquid() - && !pos.getBlockState(parBlockPos.up()).getBlock().isNormalCube(); - } else { - BlockPos blockpos = parBlockPos.down(); - if (!World.doesBlockHaveSolidTopSurface(pos, blockpos)) { - return false; - } else { - Block block1 = pos.getBlockState(blockpos).getBlock(); - boolean flag = block1 != Blocks.bedrock && block1 != Blocks.barrier; - return flag && !block.isNormalCube() && !block.getMaterial().isLiquid() - && !pos.getBlockState(parBlockPos.up()).getBlock().isNormalCube(); - } - } - } - } - - /**+ - * Called during chunk generation to spawn initial creatures. - */ - public static void performWorldGenSpawning(World worldIn, BiomeGenBase parBiomeGenBase, int parInt1, int parInt2, - int parInt3, int parInt4, EaglercraftRandom parRandom) { - List list = parBiomeGenBase.getSpawnableList(EnumCreatureType.CREATURE); - if (!list.isEmpty()) { - while (parRandom.nextFloat() < parBiomeGenBase.getSpawningChance()) { - BiomeGenBase.SpawnListEntry biomegenbase$spawnlistentry = (BiomeGenBase.SpawnListEntry) WeightedRandom - .getRandomItem(worldIn.rand, list); - int i = biomegenbase$spawnlistentry.minGroupCount + parRandom.nextInt( - 1 + biomegenbase$spawnlistentry.maxGroupCount - biomegenbase$spawnlistentry.minGroupCount); - IEntityLivingData ientitylivingdata = null; - int j = parInt1 + parRandom.nextInt(parInt3); - int k = parInt2 + parRandom.nextInt(parInt4); - int l = j; - int i1 = k; - - for (int j1 = 0; j1 < i; ++j1) { - boolean flag = false; - - for (int k1 = 0; !flag && k1 < 4; ++k1) { - BlockPos blockpos = worldIn.getTopSolidOrLiquidBlock(new BlockPos(j, 0, k)); - if (canCreatureTypeSpawnAtLocation(EntityLiving.SpawnPlacementType.ON_GROUND, worldIn, - blockpos)) { - EntityLiving entityliving; - try { - entityliving = (EntityLiving) EntityList - .createEntityByClass(biomegenbase$spawnlistentry.entityClass, worldIn); - } catch (Exception exception) { - EagRuntime.debugPrintStackTrace(exception); - continue; - } - - entityliving.setLocationAndAngles((double) ((float) j + 0.5F), (double) blockpos.getY(), - (double) ((float) k + 0.5F), parRandom.nextFloat() * 360.0F, 0.0F); - worldIn.spawnEntityInWorld(entityliving); - ientitylivingdata = entityliving.onInitialSpawn( - worldIn.getDifficultyForLocation(new BlockPos(entityliving)), ientitylivingdata); - flag = true; - } - - j += parRandom.nextInt(5) - parRandom.nextInt(5); - - for (k += parRandom.nextInt(5) - parRandom.nextInt(5); j < parInt1 || j >= parInt1 + parInt3 - || k < parInt2 - || k >= parInt2 + parInt3; k = i1 + parRandom.nextInt(5) - parRandom.nextInt(5)) { - j = l + parRandom.nextInt(5) - parRandom.nextInt(5); - } - } - } - } - - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/Teleporter.java b/src/game/java/net/minecraft/world/Teleporter.java index 0849fe98..53a9c037 100644 --- a/src/game/java/net/minecraft/world/Teleporter.java +++ b/src/game/java/net/minecraft/world/Teleporter.java @@ -1,8 +1,10 @@ package net.minecraft.world; -import com.google.common.collect.Lists; import java.util.Iterator; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockPortal; import net.minecraft.block.state.IBlockState; @@ -14,37 +16,49 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.LongHashMap; import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Teleporter { + public class PortalPosition extends BlockPos { + public long lastUpdateTime; + + public PortalPosition(BlockPos pos, long lastUpdate) { + super(pos.getX(), pos.getY(), pos.getZ()); + this.lastUpdateTime = lastUpdate; + } + } + private final WorldServer worldServerInstance; private final EaglercraftRandom random; - /**+ - * Stores successful portal placement locations for rapid - * lookup. + /** + * + Stores successful portal placement locations for rapid lookup. */ private final LongHashMap destinationCoordinateCache = new LongHashMap(); - /**+ - * A list of valid keys for the destinationCoordainteCache. - * These are based on the X & Z of the players initial location. + + /** + * + A list of valid keys for the destinationCoordainteCache. These are based on + * the X & Z of the players initial location. */ private final List destinationCoordinateKeys = Lists.newArrayList(); @@ -53,145 +67,6 @@ public class Teleporter { this.random = new EaglercraftRandom(worldIn.getSeed(), !worldIn.getWorldInfo().isOldEaglercraftRandom()); } - public void placeInPortal(Entity entityIn, float rotationYaw) { - if (this.worldServerInstance.provider.getDimensionId() != 1) { - if (!this.placeInExistingPortal(entityIn, rotationYaw)) { - this.makePortal(entityIn); - this.placeInExistingPortal(entityIn, rotationYaw); - } - } else { - int i = MathHelper.floor_double(entityIn.posX); - int j = MathHelper.floor_double(entityIn.posY) - 1; - int k = MathHelper.floor_double(entityIn.posZ); - byte b0 = 1; - byte b1 = 0; - - for (int l = -2; l <= 2; ++l) { - for (int i1 = -2; i1 <= 2; ++i1) { - for (int j1 = -1; j1 < 3; ++j1) { - int k1 = i + i1 * b0 + l * b1; - int l1 = j + j1; - int i2 = k + i1 * b1 - l * b0; - boolean flag = j1 < 0; - this.worldServerInstance.setBlockState(new BlockPos(k1, l1, i2), - flag ? Blocks.obsidian.getDefaultState() : Blocks.air.getDefaultState()); - } - } - } - - entityIn.setLocationAndAngles((double) i, (double) j, (double) k, entityIn.rotationYaw, 0.0F); - entityIn.motionX = entityIn.motionY = entityIn.motionZ = 0.0D; - } - } - - public boolean placeInExistingPortal(Entity entityIn, float rotationYaw) { - boolean flag = true; - double d0 = -1.0D; - int i = MathHelper.floor_double(entityIn.posX); - int j = MathHelper.floor_double(entityIn.posZ); - boolean flag1 = true; - Object object = BlockPos.ORIGIN; - long k = ChunkCoordIntPair.chunkXZ2Int(i, j); - if (this.destinationCoordinateCache.containsItem(k)) { - Teleporter.PortalPosition teleporter$portalposition = (Teleporter.PortalPosition) this.destinationCoordinateCache - .getValueByKey(k); - d0 = 0.0D; - object = teleporter$portalposition; - teleporter$portalposition.lastUpdateTime = this.worldServerInstance.getTotalWorldTime(); - flag1 = false; - } else { - BlockPos blockpos2 = new BlockPos(entityIn); - - for (int l = -128; l <= 128; ++l) { - BlockPos blockpos1; - for (int i1 = -128; i1 <= 128; ++i1) { - for (BlockPos blockpos = blockpos2.add(l, - this.worldServerInstance.getActualHeight() - 1 - blockpos2.getY(), i1); blockpos - .getY() >= 0; blockpos = blockpos1) { - blockpos1 = blockpos.down(); - if (this.worldServerInstance.getBlockState(blockpos).getBlock() == Blocks.portal) { - while (this.worldServerInstance.getBlockState(blockpos1 = blockpos.down()) - .getBlock() == Blocks.portal) { - blockpos = blockpos1; - } - - double d1 = blockpos.distanceSq(blockpos2); - if (d0 < 0.0D || d1 < d0) { - d0 = d1; - object = blockpos; - } - } - } - } - } - } - - if (d0 >= 0.0D) { - if (flag1) { - this.destinationCoordinateCache.add(k, - new Teleporter.PortalPosition((BlockPos) object, this.worldServerInstance.getTotalWorldTime())); - this.destinationCoordinateKeys.add(Long.valueOf(k)); - } - - double d5 = (double) ((BlockPos) object).getX() + 0.5D; - double d6 = (double) ((BlockPos) object).getY() + 0.5D; - double d7 = (double) ((BlockPos) object).getZ() + 0.5D; - BlockPattern.PatternHelper blockpattern$patternhelper = Blocks.portal - .func_181089_f(this.worldServerInstance, (BlockPos) object); - boolean flag2 = blockpattern$patternhelper.getFinger().rotateY() - .getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE; - double d2 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X - ? (double) blockpattern$patternhelper.func_181117_a().getZ() - : (double) blockpattern$patternhelper.func_181117_a().getX(); - d6 = (double) (blockpattern$patternhelper.func_181117_a().getY() + 1) - - entityIn.func_181014_aG().yCoord * (double) blockpattern$patternhelper.func_181119_e(); - if (flag2) { - ++d2; - } - - if (blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X) { - d7 = d2 + (1.0D - entityIn.func_181014_aG().xCoord) - * (double) blockpattern$patternhelper.func_181118_d() - * (double) blockpattern$patternhelper.getFinger().rotateY().getAxisDirection().getOffset(); - } else { - d5 = d2 + (1.0D - entityIn.func_181014_aG().xCoord) - * (double) blockpattern$patternhelper.func_181118_d() - * (double) blockpattern$patternhelper.getFinger().rotateY().getAxisDirection().getOffset(); - } - - float f = 0.0F; - float f1 = 0.0F; - float f2 = 0.0F; - float f3 = 0.0F; - if (blockpattern$patternhelper.getFinger().getOpposite() == entityIn.func_181012_aH()) { - f = 1.0F; - f1 = 1.0F; - } else if (blockpattern$patternhelper.getFinger().getOpposite() == entityIn.func_181012_aH() - .getOpposite()) { - f = -1.0F; - f1 = -1.0F; - } else if (blockpattern$patternhelper.getFinger().getOpposite() == entityIn.func_181012_aH().rotateY()) { - f2 = 1.0F; - f3 = -1.0F; - } else { - f2 = -1.0F; - f3 = 1.0F; - } - - double d3 = entityIn.motionX; - double d4 = entityIn.motionZ; - entityIn.motionX = d3 * (double) f + d4 * (double) f3; - entityIn.motionZ = d3 * (double) f2 + d4 * (double) f1; - entityIn.rotationYaw = rotationYaw - - (float) (entityIn.func_181012_aH().getOpposite().getHorizontalIndex() * 90) - + (float) (blockpattern$patternhelper.getFinger().getHorizontalIndex() * 90); - entityIn.setLocationAndAngles(d5, d6, d7, entityIn.rotationYaw, entityIn.rotationPitch); - return true; - } else { - return false; - } - } - public boolean makePortal(Entity parEntity) { byte b0 = 16; double d0 = -1.0D; @@ -367,10 +242,148 @@ public class Teleporter { return true; } - /**+ - * called periodically to remove out-of-date portal locations - * from the cache list. Argument par1 is a - * WorldServer.getTotalWorldTime() value. + public boolean placeInExistingPortal(Entity entityIn, float rotationYaw) { + boolean flag = true; + double d0 = -1.0D; + int i = MathHelper.floor_double(entityIn.posX); + int j = MathHelper.floor_double(entityIn.posZ); + boolean flag1 = true; + Object object = BlockPos.ORIGIN; + long k = ChunkCoordIntPair.chunkXZ2Int(i, j); + if (this.destinationCoordinateCache.containsItem(k)) { + Teleporter.PortalPosition teleporter$portalposition = (Teleporter.PortalPosition) this.destinationCoordinateCache + .getValueByKey(k); + d0 = 0.0D; + object = teleporter$portalposition; + teleporter$portalposition.lastUpdateTime = this.worldServerInstance.getTotalWorldTime(); + flag1 = false; + } else { + BlockPos blockpos2 = new BlockPos(entityIn); + + for (int l = -128; l <= 128; ++l) { + BlockPos blockpos1; + for (int i1 = -128; i1 <= 128; ++i1) { + for (BlockPos blockpos = blockpos2.add(l, + this.worldServerInstance.getActualHeight() - 1 - blockpos2.getY(), i1); blockpos + .getY() >= 0; blockpos = blockpos1) { + blockpos1 = blockpos.down(); + if (this.worldServerInstance.getBlockState(blockpos).getBlock() == Blocks.portal) { + while (this.worldServerInstance.getBlockState(blockpos1 = blockpos.down()) + .getBlock() == Blocks.portal) { + blockpos = blockpos1; + } + + double d1 = blockpos.distanceSq(blockpos2); + if (d0 < 0.0D || d1 < d0) { + d0 = d1; + object = blockpos; + } + } + } + } + } + } + + if (d0 >= 0.0D) { + if (flag1) { + this.destinationCoordinateCache.add(k, + new Teleporter.PortalPosition((BlockPos) object, this.worldServerInstance.getTotalWorldTime())); + this.destinationCoordinateKeys.add(Long.valueOf(k)); + } + + double d5 = (double) ((BlockPos) object).getX() + 0.5D; + double d6 = (double) ((BlockPos) object).getY() + 0.5D; + double d7 = (double) ((BlockPos) object).getZ() + 0.5D; + BlockPattern.PatternHelper blockpattern$patternhelper = Blocks.portal + .func_181089_f(this.worldServerInstance, (BlockPos) object); + boolean flag2 = blockpattern$patternhelper.getFinger().rotateY() + .getAxisDirection() == EnumFacing.AxisDirection.NEGATIVE; + double d2 = blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X + ? (double) blockpattern$patternhelper.func_181117_a().getZ() + : (double) blockpattern$patternhelper.func_181117_a().getX(); + d6 = (double) (blockpattern$patternhelper.func_181117_a().getY() + 1) + - entityIn.func_181014_aG().yCoord * (double) blockpattern$patternhelper.func_181119_e(); + if (flag2) { + ++d2; + } + + if (blockpattern$patternhelper.getFinger().getAxis() == EnumFacing.Axis.X) { + d7 = d2 + (1.0D - entityIn.func_181014_aG().xCoord) + * (double) blockpattern$patternhelper.func_181118_d() + * (double) blockpattern$patternhelper.getFinger().rotateY().getAxisDirection().getOffset(); + } else { + d5 = d2 + (1.0D - entityIn.func_181014_aG().xCoord) + * (double) blockpattern$patternhelper.func_181118_d() + * (double) blockpattern$patternhelper.getFinger().rotateY().getAxisDirection().getOffset(); + } + + float f = 0.0F; + float f1 = 0.0F; + float f2 = 0.0F; + float f3 = 0.0F; + if (blockpattern$patternhelper.getFinger().getOpposite() == entityIn.func_181012_aH()) { + f = 1.0F; + f1 = 1.0F; + } else if (blockpattern$patternhelper.getFinger().getOpposite() == entityIn.func_181012_aH() + .getOpposite()) { + f = -1.0F; + f1 = -1.0F; + } else if (blockpattern$patternhelper.getFinger().getOpposite() == entityIn.func_181012_aH().rotateY()) { + f2 = 1.0F; + f3 = -1.0F; + } else { + f2 = -1.0F; + f3 = 1.0F; + } + + double d3 = entityIn.motionX; + double d4 = entityIn.motionZ; + entityIn.motionX = d3 * (double) f + d4 * (double) f3; + entityIn.motionZ = d3 * (double) f2 + d4 * (double) f1; + entityIn.rotationYaw = rotationYaw + - (float) (entityIn.func_181012_aH().getOpposite().getHorizontalIndex() * 90) + + (float) (blockpattern$patternhelper.getFinger().getHorizontalIndex() * 90); + entityIn.setLocationAndAngles(d5, d6, d7, entityIn.rotationYaw, entityIn.rotationPitch); + return true; + } else { + return false; + } + } + + public void placeInPortal(Entity entityIn, float rotationYaw) { + if (this.worldServerInstance.provider.getDimensionId() != 1) { + if (!this.placeInExistingPortal(entityIn, rotationYaw)) { + this.makePortal(entityIn); + this.placeInExistingPortal(entityIn, rotationYaw); + } + } else { + int i = MathHelper.floor_double(entityIn.posX); + int j = MathHelper.floor_double(entityIn.posY) - 1; + int k = MathHelper.floor_double(entityIn.posZ); + byte b0 = 1; + byte b1 = 0; + + for (int l = -2; l <= 2; ++l) { + for (int i1 = -2; i1 <= 2; ++i1) { + for (int j1 = -1; j1 < 3; ++j1) { + int k1 = i + i1 * b0 + l * b1; + int l1 = j + j1; + int i2 = k + i1 * b1 - l * b0; + boolean flag = j1 < 0; + this.worldServerInstance.setBlockState(new BlockPos(k1, l1, i2), + flag ? Blocks.obsidian.getDefaultState() : Blocks.air.getDefaultState()); + } + } + } + + entityIn.setLocationAndAngles((double) i, (double) j, (double) k, entityIn.rotationYaw, 0.0F); + entityIn.motionX = entityIn.motionY = entityIn.motionZ = 0.0D; + } + } + + /** + * + called periodically to remove out-of-date portal locations from the cache + * list. Argument par1 is a WorldServer.getTotalWorldTime() value. */ public void removeStalePortalLocations(long worldTime) { if (worldTime % 100L == 0L) { @@ -389,13 +402,4 @@ public class Teleporter { } } - - public class PortalPosition extends BlockPos { - public long lastUpdateTime; - - public PortalPosition(BlockPos pos, long lastUpdate) { - super(pos.getX(), pos.getY(), pos.getZ()); - this.lastUpdateTime = lastUpdate; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/World.java b/src/game/java/net/minecraft/world/World.java index e5024e2d..e7b9fea1 100644 --- a/src/game/java/net/minecraft/world/World.java +++ b/src/game/java/net/minecraft/world/World.java @@ -1,22 +1,20 @@ package net.minecraft.world; -import com.google.common.base.Predicate; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Iterator; import java.util.List; - -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; -import net.lax1dude.eaglercraft.v1_8.HString; - import java.util.concurrent.Callable; +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.HString; import net.minecraft.block.Block; import net.minecraft.block.BlockHopper; import net.minecraft.block.BlockLiquid; @@ -58,62 +56,78 @@ import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.MapStorage; import net.minecraft.world.storage.WorldInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class World implements IBlockAccess { + public static boolean doesBlockHaveSolidTopSurface(IBlockAccess blockAccess, BlockPos pos) { + IBlockState iblockstate = blockAccess.getBlockState(pos); + Block block = iblockstate.getBlock(); + return block.getMaterial().isOpaque() && block.isFullCube() ? true + : (block instanceof BlockStairs ? iblockstate.getValue(BlockStairs.HALF) == BlockStairs.EnumHalf.TOP + : (block instanceof BlockSlab + ? iblockstate.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.TOP + : (block instanceof BlockHopper ? true + : (block instanceof BlockSnow + ? ((Integer) iblockstate.getValue(BlockSnow.LAYERS)).intValue() == 7 + : false)))); + } + private int field_181546_a = 63; protected boolean scheduledUpdatesAreImmediate; - /**+ - * A list of all Entities in all currently-loaded chunks + /** + * + A list of all Entities in all currently-loaded chunks */ public final List loadedEntityList = Lists.newArrayList(); protected final List unloadedEntityList = Lists.newArrayList(); - /**+ - * A list of the loaded tile entities in the world + /** + * + A list of the loaded tile entities in the world */ public final List loadedTileEntityList = Lists.newArrayList(); public final List tickableTileEntities = Lists.newArrayList(); private final List addedTileEntityList = Lists.newArrayList(); private final List tileEntitiesToBeRemoved = Lists.newArrayList(); - /**+ - * Array list of players in the world. + /** + * + Array list of players in the world. */ public final List playerEntities = Lists.newArrayList(); - /**+ - * a list of all the lightning entities + /** + * + a list of all the lightning entities */ public final List weatherEffects = Lists.newArrayList(); protected final IntHashMap entitiesById = new IntHashMap(); private long cloudColour = 16777215L; private int skylightSubtracted; - /**+ - * Contains the current Linear Congruential Generator seed for - * block updates. Used with an A value of 3 and a C value of - * 0x3c6ef35f, producing a highly planar series of values - * ill-suited for choosing random blocks in a 16x128x16 field. + /** + * + Contains the current Linear Congruential Generator seed for block updates. + * Used with an A value of 3 and a C value of 0x3c6ef35f, producing a highly + * planar series of values ill-suited for choosing random blocks in a 16x128x16 + * field. */ protected int updateLCG = (new EaglercraftRandom()).nextInt(); - /**+ - * magic number used to generate fast random numbers for 3d - * distribution within a chunk + /** + * + magic number used to generate fast random numbers for 3d distribution + * within a chunk */ protected final int DIST_HASH_MAGIC = 1013904223; protected float prevRainingStrength; @@ -121,8 +135,8 @@ public abstract class World implements IBlockAccess { protected float prevThunderingStrength; protected float thunderingStrength; private int lastLightningBolt; - /**+ - * RNG for World. + /** + * + RNG for World. */ public final EaglercraftRandom rand = new EaglercraftRandom(); public final WorldProvider provider; @@ -135,8 +149,8 @@ public abstract class World implements IBlockAccess { protected VillageCollection villageCollectionObj; private final Calendar theCalendar = Calendar.getInstance(); protected Scoreboard worldScoreboard = new Scoreboard(); - /**+ - * populated by chunks that are within 9 chunks of any player + /** + * + populated by chunks that are within 9 chunks of any player */ protected Set activeChunkSet = Sets.newHashSet(); private int ambientTickCountdown; @@ -145,6 +159,7 @@ public abstract class World implements IBlockAccess { private boolean processingLoadedTiles; private final WorldBorder worldBorder; int[] lightUpdateBlockList; + public final boolean isRemote; protected World(ISaveHandler saveHandlerIn, WorldInfo info, WorldProvider providerIn, boolean client) { @@ -159,8 +174,544 @@ public abstract class World implements IBlockAccess { this.isRemote = client; } - public World init() { - return this; + public void addBlockEvent(BlockPos pos, Block blockIn, int eventID, int eventParam) { + blockIn.onBlockEventReceived(this, pos, this.getBlockState(pos), eventID, eventParam); + } + + public void addTileEntities(Collection tileEntityCollection) { + if (this.processingLoadedTiles) { + this.addedTileEntityList.addAll(tileEntityCollection); + } else { + for (TileEntity tileentity : tileEntityCollection) { + this.loadedTileEntityList.add(tileentity); + if (tileentity instanceof ITickable) { + this.tickableTileEntities.add(tileentity); + } + } + } + + } + + public boolean addTileEntity(TileEntity tile) { + boolean flag = this.loadedTileEntityList.add(tile); + if (flag && tile instanceof ITickable) { + this.tickableTileEntities.add(tile); + } + + return flag; + } + + /** + * + adds a lightning bolt to the list of lightning bolts in this world. + */ + public boolean addWeatherEffect(Entity entityIn) { + this.weatherEffects.add(entityIn); + return true; + } + + /** + * + Adds a IWorldAccess to the list of worldAccesses + */ + public void addWorldAccess(IWorldAccess worldAccess) { + this.worldAccesses.add(worldAccess); + } + + /** + * + Adds some basic stats of the world to the given crash report. + */ + public CrashReportCategory addWorldInfoToCrashReport(CrashReport report) { + CrashReportCategory crashreportcategory = report.makeCategoryDepth("Affected level", 1); + crashreportcategory.addCrashSection("Level name", + this.worldInfo == null ? "????" : this.worldInfo.getWorldName()); + crashreportcategory.addCrashSectionCallable("All players", new Callable() { + public String call() { + return World.this.playerEntities.size() + " total; " + World.this.playerEntities.toString(); + } + }); + crashreportcategory.addCrashSectionCallable("Chunk stats", new Callable() { + public String call() { + return World.this.chunkProvider.makeString(); + } + }); + + try { + this.worldInfo.addToCrashReport(crashreportcategory); + } catch (Throwable throwable) { + crashreportcategory.addCrashSectionThrowable("Level Data Unobtainable", throwable); + } + + return crashreportcategory; + } + + /** + * + Called on construction of the World class to setup the initial skylight + * values + */ + public void calculateInitialSkylight() { + int i = this.calculateSkylightSubtracted(1.0F); + if (i != this.skylightSubtracted) { + this.skylightSubtracted = i; + } + + } + + /** + * + Called from World constructor to set rainingStrength and thunderingStrength + */ + protected void calculateInitialWeather() { + if (this.worldInfo.isRaining()) { + this.rainingStrength = 1.0F; + if (this.worldInfo.isThundering()) { + this.thunderingStrength = 1.0F; + } + } + + } + + /** + * + Returns the amount of skylight subtracted for the current time + */ + public int calculateSkylightSubtracted(float parFloat1) { + float f = this.getCelestialAngle(parFloat1); + float f1 = 1.0F - (MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.5F); + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + f1 = 1.0F - f1; + f1 = (float) ((double) f1 * (1.0D - (double) (this.getRainStrength(parFloat1) * 5.0F) / 16.0D)); + f1 = (float) ((double) f1 * (1.0D - (double) (this.getThunderStrength(parFloat1) * 5.0F) / 16.0D)); + f1 = 1.0F - f1; + return (int) (f1 * 11.0F); + } + + public boolean canBlockBePlaced(Block blockIn, BlockPos pos, boolean side, EnumFacing entityIn, Entity itemStackIn, + ItemStack parItemStack) { + Block block = this.getBlockState(pos).getBlock(); + AxisAlignedBB axisalignedbb = side ? null + : blockIn.getCollisionBoundingBox(this, pos, blockIn.getDefaultState()); + return axisalignedbb != null && !this.checkNoEntityCollision(axisalignedbb, itemStackIn) ? false + : (block.getMaterial() == Material.circuits && blockIn == Blocks.anvil ? true + : block.getMaterial().isReplaceable() && blockIn.canReplace(this, pos, entityIn, parItemStack)); + } + + /** + * + Checks to see if a given block is both water and cold enough to freeze. + */ + public boolean canBlockFreeze(BlockPos pos, boolean noWaterAdj) { + BiomeGenBase biomegenbase = this.getBiomeGenForCoords(pos); + float f = biomegenbase.getFloatTemperature(pos); + if (f > 0.15F) { + return false; + } else { + if (pos.getY() >= 0 && pos.getY() < 256 && this.getLightFor(EnumSkyBlock.BLOCK, pos) < 10) { + IBlockState iblockstate = this.getBlockState(pos); + Block block = iblockstate.getBlock(); + if ((block == Blocks.water || block == Blocks.flowing_water) + && ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) { + if (!noWaterAdj) { + return true; + } + + boolean flag = this.isWater(pos.west()) && this.isWater(pos.east()) && this.isWater(pos.north()) + && this.isWater(pos.south()); + if (!flag) { + return true; + } + } + } + + return false; + } + } + + public boolean canBlockFreezeNoWater(BlockPos pos) { + return this.canBlockFreeze(pos, true); + } + + public boolean canBlockFreezeWater(BlockPos pos) { + return this.canBlockFreeze(pos, false); + } + + public boolean canBlockSeeSky(BlockPos pos) { + if (pos.getY() >= this.func_181545_F()) { + return this.canSeeSky(pos); + } else { + BlockPos blockpos = new BlockPos(pos.getX(), this.func_181545_F(), pos.getZ()); + if (!this.canSeeSky(blockpos)) { + return false; + } else { + for (blockpos = blockpos.down(); blockpos.getY() > pos.getY(); blockpos = blockpos.down()) { + Block block = this.getBlockState(blockpos).getBlock(); + if (block.getLightOpacity() > 0 && !block.getMaterial().isLiquid()) { + return false; + } + } + + return true; + } + } + } + + public boolean canLightningStrike(BlockPos strikePosition) { + if (!this.isRaining()) { + return false; + } else if (!this.canSeeSky(strikePosition)) { + return false; + } else if (this.getPrecipitationHeight(strikePosition).getY() > strikePosition.getY()) { + return false; + } else { + BiomeGenBase biomegenbase = this.getBiomeGenForCoords(strikePosition); + return biomegenbase.getEnableSnow() ? false + : (this.canSnowAt(strikePosition, false) ? false : biomegenbase.canSpawnLightningBolt()); + } + } + + public boolean canSeeSky(BlockPos pos) { + return this.getChunkFromBlockCoords(pos).canSeeSky(pos); + } + + /** + * + Checks to see if a given block can accumulate snow from it snowing + */ + public boolean canSnowAt(BlockPos pos, boolean checkLight) { + BiomeGenBase biomegenbase = this.getBiomeGenForCoords(pos); + float f = biomegenbase.getFloatTemperature(pos); + if (f > 0.15F) { + return false; + } else if (!checkLight) { + return true; + } else { + if (pos.getY() >= 0 && pos.getY() < 256 && this.getLightFor(EnumSkyBlock.BLOCK, pos) < 10) { + Block block = this.getBlockState(pos).getBlock(); + if (block.getMaterial() == Material.air && Blocks.snow_layer.canPlaceBlockAt(this, pos)) { + return true; + } + } + + return false; + } + } + + /** + * + Returns true if there are any blocks in the region constrained by an + * AxisAlignedBB + */ + public boolean checkBlockCollision(AxisAlignedBB bb) { + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 <= j; ++k1) { + for (int l1 = k; l1 <= l; ++l1) { + for (int i2 = i1; i2 <= j1; ++i2) { + Block block = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock(); + if (block.getMaterial() != Material.air) { + return true; + } + } + } + } + + return false; + } + + public boolean checkLight(BlockPos pos) { + boolean flag = false; + if (!this.provider.getHasNoSky()) { + flag |= this.checkLightFor(EnumSkyBlock.SKY, pos); + } + + flag = flag | this.checkLightFor(EnumSkyBlock.BLOCK, pos); + return flag; + } + + public boolean checkLightFor(EnumSkyBlock lightType, BlockPos pos) { + if (!this.isAreaLoaded(pos, 17, false)) { + return false; + } else { + int i = 0; + int j = 0; + int k = this.getLightFor(lightType, pos); + int l = this.getRawLight(pos, lightType); + int i1 = pos.getX(); + int j1 = pos.getY(); + int k1 = pos.getZ(); + if (l > k) { + this.lightUpdateBlockList[j++] = 133152; + } else if (l < k) { + this.lightUpdateBlockList[j++] = 133152 | k << 18; + + while (i < j) { + int l1 = this.lightUpdateBlockList[i++]; + int i2 = (l1 & 63) - 32 + i1; + int j2 = (l1 >> 6 & 63) - 32 + j1; + int k2 = (l1 >> 12 & 63) - 32 + k1; + int l2 = l1 >> 18 & 15; + BlockPos blockpos = new BlockPos(i2, j2, k2); + int i3 = this.getLightFor(lightType, blockpos); + if (i3 == l2) { + this.setLightFor(lightType, blockpos, 0); + if (l2 > 0) { + int j3 = MathHelper.abs_int(i2 - i1); + int k3 = MathHelper.abs_int(j2 - j1); + int l3 = MathHelper.abs_int(k2 - k1); + if (j3 + k3 + l3 < 17) { + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + EnumFacing[] facings = EnumFacing._VALUES; + for (int m = 0; m < facings.length; ++m) { + EnumFacing enumfacing = facings[m]; + int i4 = i2 + enumfacing.getFrontOffsetX(); + int j4 = j2 + enumfacing.getFrontOffsetY(); + int k4 = k2 + enumfacing.getFrontOffsetZ(); + blockpos$mutableblockpos.func_181079_c(i4, j4, k4); + int l4 = Math.max(1, + this.getBlockState(blockpos$mutableblockpos).getBlock().getLightOpacity()); + i3 = this.getLightFor(lightType, blockpos$mutableblockpos); + if (i3 == l2 - l4 && j < this.lightUpdateBlockList.length) { + this.lightUpdateBlockList[j++] = i4 - i1 + 32 | j4 - j1 + 32 << 6 + | k4 - k1 + 32 << 12 | l2 - l4 << 18; + } + } + } + } + } + } + + i = 0; + } + + while (i < j) { + int i5 = this.lightUpdateBlockList[i++]; + int j5 = (i5 & 63) - 32 + i1; + int k5 = (i5 >> 6 & 63) - 32 + j1; + int l5 = (i5 >> 12 & 63) - 32 + k1; + BlockPos blockpos1 = new BlockPos(j5, k5, l5); + int i6 = this.getLightFor(lightType, blockpos1); + int j6 = this.getRawLight(blockpos1, lightType); + if (j6 != i6) { + this.setLightFor(lightType, blockpos1, j6); + if (j6 > i6) { + int k6 = Math.abs(j5 - i1); + int l6 = Math.abs(k5 - j1); + int i7 = Math.abs(l5 - k1); + boolean flag = j < this.lightUpdateBlockList.length - 6; + if (k6 + l6 + i7 < 17 && flag) { + if (this.getLightFor(lightType, blockpos1.west()) < j6) { + this.lightUpdateBlockList[j++] = j5 - 1 - i1 + 32 + (k5 - j1 + 32 << 6) + + (l5 - k1 + 32 << 12); + } + + if (this.getLightFor(lightType, blockpos1.east()) < j6) { + this.lightUpdateBlockList[j++] = j5 + 1 - i1 + 32 + (k5 - j1 + 32 << 6) + + (l5 - k1 + 32 << 12); + } + + if (this.getLightFor(lightType, blockpos1.down()) < j6) { + this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 - 1 - j1 + 32 << 6) + + (l5 - k1 + 32 << 12); + } + + if (this.getLightFor(lightType, blockpos1.up()) < j6) { + this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 + 1 - j1 + 32 << 6) + + (l5 - k1 + 32 << 12); + } + + if (this.getLightFor(lightType, blockpos1.north()) < j6) { + this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 - j1 + 32 << 6) + + (l5 - 1 - k1 + 32 << 12); + } + + if (this.getLightFor(lightType, blockpos1.south()) < j6) { + this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 - j1 + 32 << 6) + + (l5 + 1 - k1 + 32 << 12); + } + } + } + } + } + + return true; + } + } + + /** + * + Returns true if there are no solid, live entities in the specified + * AxisAlignedBB, excluding the given entity + */ + public boolean checkNoEntityCollision(AxisAlignedBB bb) { + return this.checkNoEntityCollision(bb, (Entity) null); + } + + /** + * + Returns true if there are no solid, live entities in the specified + * AxisAlignedBB, excluding the given entity + */ + public boolean checkNoEntityCollision(AxisAlignedBB bb, Entity entityIn) { + List list = this.getEntitiesWithinAABBExcludingEntity((Entity) null, bb); + + for (int i = 0; i < list.size(); ++i) { + Entity entity = (Entity) list.get(i); + if (!entity.isDead && entity.preventEntitySpawning && entity != entityIn + && (entityIn == null || entityIn.ridingEntity != entity && entityIn.riddenByEntity != entity)) { + return false; + } + } + + return true; + } + + /** + * + Checks whether the session lock file was modified by another process + */ + public void checkSessionLock() throws MinecraftException { + this.saveHandler.checkSessionLock(); + } + + /** + * + Counts how many entities of an entity class exist in the world. Args: + * entityClass + */ + public int countEntities(Class entityType) { + int i = 0; + + for (int j = 0, l = this.loadedEntityList.size(); j < l; ++j) { + Entity entity = this.loadedEntityList.get(j); + if ((!(entity instanceof EntityLiving) || !((EntityLiving) entity).isNoDespawnRequired()) + && entityType.isAssignableFrom(entity.getClass())) { + ++i; + } + } + + return i; + } + + protected abstract IChunkProvider createChunkProvider(); + + /** + * + Creates an explosion. Args: entity, x, y, z, strength + */ + public Explosion createExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isSmoking) { + return this.newExplosion(entityIn, x, y, z, strength, false, isSmoking); + } + + /** + * + Sets a block to air, but also plays the sound and particles and can spawn + * drops + */ + public boolean destroyBlock(BlockPos pos, boolean dropBlock) { + IBlockState iblockstate = this.getBlockState(pos); + Block block = iblockstate.getBlock(); + if (block.getMaterial() == Material.air) { + return false; + } else { + this.playAuxSFX(2001, pos, Block.getStateId(iblockstate)); + if (dropBlock) { + block.dropBlockAsItem(this, pos, iblockstate, 0); + } + + return this.setBlockState(pos, Blocks.air.getDefaultState(), 3); + } + } + + /** + * + set by !chunk.getAreLevelsEmpty + */ + public boolean extendedLevelsInChunkCache() { + return false; + } + + /** + * + Attempts to extinguish a fire + */ + public boolean extinguishFire(EntityPlayer player, BlockPos pos, EnumFacing side) { + pos = pos.offset(side); + if (this.getBlockState(pos).getBlock() == Blocks.fire) { + this.playAuxSFXAtEntity(player, 1004, pos, 0); + this.setBlockToAir(pos); + return true; + } else { + return false; + } + } + + public T findNearestEntityWithinAABB(Class entityType, AxisAlignedBB aabb, + T closestTo) { + List list = this.getEntitiesWithinAABB(entityType, aabb); + Entity entity = null; + double d0 = Double.MAX_VALUE; + + for (int i = 0; i < list.size(); ++i) { + Entity entity1 = (Entity) list.get(i); + if (entity1 != closestTo && EntitySelectors.NOT_SPECTATING.apply(entity1)) { + double d1 = closestTo.getDistanceSqToEntity(entity1); + if (d1 <= d0) { + entity = entity1; + d0 = d1; + } + } + } + + return (T) entity; + } + + public void forceBlockUpdateTick(Block blockType, BlockPos pos, EaglercraftRandom random) { + this.scheduledUpdatesAreImmediate = true; + blockType.updateTick(this, pos, this.getBlockState(pos), random); + this.scheduledUpdatesAreImmediate = false; + } + + public List func_147461_a(AxisAlignedBB bb) { + ArrayList arraylist = Lists.newArrayList(); + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX + 1.0D); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY + 1.0D); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = i1; l1 < j1; ++l1) { + if (this.isBlockLoaded(blockpos$mutableblockpos.func_181079_c(k1, 64, l1))) { + for (int i2 = k - 1; i2 < l; ++i2) { + blockpos$mutableblockpos.func_181079_c(k1, i2, l1); + IBlockState iblockstate; + if (k1 >= -30000000 && k1 < 30000000 && l1 >= -30000000 && l1 < 30000000) { + iblockstate = this.getBlockState(blockpos$mutableblockpos); + } else { + iblockstate = Blocks.bedrock.getDefaultState(); + } + + iblockstate.getBlock().addCollisionBoxesToList(this, blockpos$mutableblockpos, iblockstate, bb, + arraylist, (Entity) null); + } + } + } + } + + return arraylist; + } + + public List func_175712_a(StructureBoundingBox structureBB, boolean parFlag) { + return null; + } + + public void func_181544_b(int parInt1) { + this.field_181546_a = parInt1; + } + + public int func_181545_F() { + return this.field_181546_a; + } + + /** + * + Returns current world height. + */ + public int getActualHeight() { + return this.provider.getHasNoSky() ? 128 : 256; } public BiomeGenBase getBiomeGenForCoords(final BlockPos pos) { @@ -185,22 +736,367 @@ public abstract class World implements IBlockAccess { } } - public WorldChunkManager getWorldChunkManager() { - return this.provider.getWorldChunkManager(); - } - - protected abstract IChunkProvider createChunkProvider(); - - public void initialize(WorldSettings settings) { - this.worldInfo.setServerInitialized(true); - } - - /**+ - * Sets a new spawn location by finding an uncovered block at a - * random (x,z) location in the chunk. + /** + * + Gets the percentage of real blocks within within a bounding box, along a + * specified vector. */ - public void setInitialSpawnLocation() { - this.setSpawnPoint(new BlockPos(8, 64, 8)); + public float getBlockDensity(Vec3 vec, AxisAlignedBB bb) { + double d0 = 1.0D / ((bb.maxX - bb.minX) * 2.0D + 1.0D); + double d1 = 1.0D / ((bb.maxY - bb.minY) * 2.0D + 1.0D); + double d2 = 1.0D / ((bb.maxZ - bb.minZ) * 2.0D + 1.0D); + double d3 = (1.0D - Math.floor(1.0D / d0) * d0) / 2.0D; + double d4 = (1.0D - Math.floor(1.0D / d2) * d2) / 2.0D; + if (d0 >= 0.0D && d1 >= 0.0D && d2 >= 0.0D) { + int i = 0; + int j = 0; + + for (float f = 0.0F; f <= 1.0F; f = (float) ((double) f + d0)) { + for (float f1 = 0.0F; f1 <= 1.0F; f1 = (float) ((double) f1 + d1)) { + for (float f2 = 0.0F; f2 <= 1.0F; f2 = (float) ((double) f2 + d2)) { + double d5 = bb.minX + (bb.maxX - bb.minX) * (double) f; + double d6 = bb.minY + (bb.maxY - bb.minY) * (double) f1; + double d7 = bb.minZ + (bb.maxZ - bb.minZ) * (double) f2; + if (this.rayTraceBlocks(new Vec3(d5 + d3, d6, d7 + d4), vec) == null) { + ++i; + } + + ++j; + } + } + } + + return (float) i / (float) j; + } else { + return 0.0F; + } + } + + public IBlockState getBlockState(BlockPos pos) { + if (!this.isValid(pos)) { + return Blocks.air.getDefaultState(); + } else { + Chunk chunk = this.getChunkFromBlockCoords(pos); + return chunk.getBlockState(pos); + } + } + + /** + * + calls calculateCelestialAngle + */ + public float getCelestialAngle(float partialTicks) { + return this.provider.calculateCelestialAngle(this.worldInfo.getWorldTime(), partialTicks); + } + + /** + * + Return getCelestialAngle()*2*PI + */ + public float getCelestialAngleRadians(float partialTicks) { + float f = this.getCelestialAngle(partialTicks); + return f * 3.1415927F * 2.0F; + } + + public Chunk getChunkFromBlockCoords(BlockPos pos) { + return this.getChunkFromChunkCoords(pos.getX() >> 4, pos.getZ() >> 4); + } + + /** + * + Returns back a chunk looked up by chunk coordinates Args: x, y + */ + public Chunk getChunkFromChunkCoords(int chunkX, int chunkZ) { + return this.chunkProvider.provideChunk(chunkX, chunkZ); + } + + /** + * + gets the world's chunk provider + */ + public IChunkProvider getChunkProvider() { + return this.chunkProvider; + } + + /** + * + Gets the lowest height of the chunk where sunlight directly reaches + */ + public int getChunksLowestHorizon(int x, int z) { + if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { + if (!this.isChunkLoaded(x >> 4, z >> 4, true)) { + return 0; + } else { + Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4); + return chunk.getLowestHeight(); + } + } else { + return this.func_181545_F() + 1; + } + } + + /** + * + Gets the closest player to the point within the specified distance + * (distance can be set to less than 0 to not limit the distance). Args: x, y, + * z, dist + */ + public EntityPlayer getClosestPlayer(double x, double y, double z, double distance) { + double d0 = -1.0D; + EntityPlayer entityplayer = null; + + for (int i = 0; i < this.playerEntities.size(); ++i) { + EntityPlayer entityplayer1 = (EntityPlayer) this.playerEntities.get(i); + if (EntitySelectors.NOT_SPECTATING.apply(entityplayer1)) { + double d1 = entityplayer1.getDistanceSq(x, y, z); + if ((distance < 0.0D || d1 < distance * distance) && (d0 == -1.0D || d1 < d0)) { + d0 = d1; + entityplayer = entityplayer1; + } + } + } + + return entityplayer; + } + + /** + * + Gets the closest player to the entity within the specified distance (if + * distance is less than 0 then ignored). Args: entity, dist + */ + public EntityPlayer getClosestPlayerToEntity(Entity entityIn, double distance) { + return this.getClosestPlayer(entityIn.posX, entityIn.posY, entityIn.posZ, distance); + } + + public Vec3 getCloudColour(float partialTicks) { + float f = this.getCelestialAngle(partialTicks); + float f1 = MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.5F; + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + float f2 = (float) (this.cloudColour >> 16 & 255L) / 255.0F; + float f3 = (float) (this.cloudColour >> 8 & 255L) / 255.0F; + float f4 = (float) (this.cloudColour & 255L) / 255.0F; + float f5 = this.getRainStrength(partialTicks); + if (f5 > 0.0F) { + float f6 = (f2 * 0.3F + f3 * 0.59F + f4 * 0.11F) * 0.6F; + float f7 = 1.0F - f5 * 0.95F; + f2 = f2 * f7 + f6 * (1.0F - f7); + f3 = f3 * f7 + f6 * (1.0F - f7); + f4 = f4 * f7 + f6 * (1.0F - f7); + } + + f2 = f2 * (f1 * 0.9F + 0.1F); + f3 = f3 * (f1 * 0.9F + 0.1F); + f4 = f4 * (f1 * 0.85F + 0.15F); + float f9 = this.getThunderStrength(partialTicks); + if (f9 > 0.0F) { + float f10 = (f2 * 0.3F + f3 * 0.59F + f4 * 0.11F) * 0.2F; + float f8 = 1.0F - f9 * 0.95F; + f2 = f2 * f8 + f10 * (1.0F - f8); + f3 = f3 * f8 + f10 * (1.0F - f8); + f4 = f4 * f8 + f10 * (1.0F - f8); + } + + return new Vec3((double) f2, (double) f3, (double) f4); + } + + /** + * + Returns a list of bounding boxes that collide with aabb excluding the + * passed in entity's collision. Args: entity, aabb + */ + public List getCollidingBoundingBoxes(Entity entityIn, AxisAlignedBB bb) { + ArrayList arraylist = Lists.newArrayList(); + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX + 1.0D); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY + 1.0D); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); + WorldBorder worldborder = this.getWorldBorder(); + boolean flag = entityIn.isOutsideBorder(); + boolean flag1 = this.isInsideBorder(worldborder, entityIn); + IBlockState iblockstate = Blocks.stone.getDefaultState(); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = i1; l1 < j1; ++l1) { + if (this.isBlockLoaded(blockpos$mutableblockpos.func_181079_c(k1, 64, l1))) { + for (int i2 = k - 1; i2 < l; ++i2) { + blockpos$mutableblockpos.func_181079_c(k1, i2, l1); + if (flag && flag1) { + entityIn.setOutsideBorder(false); + } else if (!flag && !flag1) { + entityIn.setOutsideBorder(true); + } + + IBlockState iblockstate1 = iblockstate; + if (worldborder.contains((BlockPos) blockpos$mutableblockpos) || !flag1) { + iblockstate1 = this.getBlockState(blockpos$mutableblockpos); + } + + iblockstate1.getBlock().addCollisionBoxesToList(this, blockpos$mutableblockpos, iblockstate1, + bb, arraylist, entityIn); + } + } + } + } + + double d0 = 0.25D; + List list = this.getEntitiesWithinAABBExcludingEntity(entityIn, bb.expand(d0, d0, d0)); + + for (int j2 = 0; j2 < list.size(); ++j2) { + if (entityIn.riddenByEntity != list && entityIn.ridingEntity != list) { + AxisAlignedBB axisalignedbb = ((Entity) list.get(j2)).getCollisionBoundingBox(); + if (axisalignedbb != null && axisalignedbb.intersectsWith(bb)) { + arraylist.add(axisalignedbb); + } + + axisalignedbb = entityIn.getCollisionBox((Entity) list.get(j2)); + if (axisalignedbb != null && axisalignedbb.intersectsWith(bb)) { + arraylist.add(axisalignedbb); + } + } + } + + return arraylist; + } + + public int getCombinedLight(BlockPos pos, int lightValue) { + int i = this.getLightFromNeighborsFor(EnumSkyBlock.SKY, pos); + int j = this.getLightFromNeighborsFor(EnumSkyBlock.BLOCK, pos); + if (lightValue < 0) { + j += -lightValue; + if (j > 15) { + j = 15; + } + } else if (j < lightValue) { + j = lightValue; + } + + return i << 20 | j << 4; + } + + /** + * + returns a calendar object containing the current date + */ + public Calendar getCurrentDate() { + if (this.getTotalWorldTime() % 600L == 0L) { + this.theCalendar.setTimeInMillis(MinecraftServer.getCurrentTimeMillis()); + } + + return this.theCalendar; + } + + /** + * + gets the current fullness of the moon expressed as a float between 1.0 and + * 0.0, in steps of .25 + */ + public float getCurrentMoonPhaseFactor() { + return WorldProvider.moonPhaseFactors[this.provider.getMoonPhase(this.worldInfo.getWorldTime())]; + } + + /** + * + This string is 'All: (number of loaded entities)' Viewable by press ing F3 + */ + public String getDebugLoadedEntities() { + return "All: " + this.loadedEntityList.size(); + } + + public EnumDifficulty getDifficulty() { + return this.getWorldInfo().getDifficulty(); + } + + public DifficultyInstance getDifficultyForLocation(BlockPos pos) { + long i = 0L; + float f = 0.0F; + if (this.isBlockLoaded(pos)) { + f = this.getCurrentMoonPhaseFactor(); + i = this.getChunkFromBlockCoords(pos).getInhabitedTime(); + } + + return new DifficultyInstance(this.getDifficulty(), this.getWorldTime(), i, f); + } + + public List getEntities(Class entityType, Predicate filter) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = this.loadedEntityList.size(); i < l; ++i) { + Entity entity = this.loadedEntityList.get(i); + if (entityType.isAssignableFrom(entity.getClass()) && filter.apply((T) entity)) { + arraylist.add(entity); + } + } + + return arraylist; + } + + /** + * + Gets all entities within the specified AABB excluding the one passed into + * it. Args: entityToExclude, aabb, predicate + */ + public List getEntitiesInAABBexcluding(Entity entityIn, AxisAlignedBB boundingBox, + Predicate predicate) { + ArrayList arraylist = Lists.newArrayList(); + int i = MathHelper.floor_double((boundingBox.minX - 2.0D) / 16.0D); + int j = MathHelper.floor_double((boundingBox.maxX + 2.0D) / 16.0D); + int k = MathHelper.floor_double((boundingBox.minZ - 2.0D) / 16.0D); + int l = MathHelper.floor_double((boundingBox.maxZ + 2.0D) / 16.0D); + + for (int i1 = i; i1 <= j; ++i1) { + for (int j1 = k; j1 <= l; ++j1) { + if (this.isChunkLoaded(i1, j1, true)) { + this.getChunkFromChunkCoords(i1, j1).getEntitiesWithinAABBForEntity(entityIn, boundingBox, + arraylist, predicate); + } + } + } + + return arraylist; + } + + public List getEntitiesWithinAABB(Class classEntity, AxisAlignedBB bb) { + return this.getEntitiesWithinAABB(classEntity, bb, EntitySelectors.NOT_SPECTATING); + } + + public List getEntitiesWithinAABB(Class clazz, AxisAlignedBB aabb, + Predicate filter) { + int i = MathHelper.floor_double((aabb.minX - 2.0D) / 16.0D); + int j = MathHelper.floor_double((aabb.maxX + 2.0D) / 16.0D); + int k = MathHelper.floor_double((aabb.minZ - 2.0D) / 16.0D); + int l = MathHelper.floor_double((aabb.maxZ + 2.0D) / 16.0D); + ArrayList arraylist = Lists.newArrayList(); + + for (int i1 = i; i1 <= j; ++i1) { + for (int j1 = k; j1 <= l; ++j1) { + if (this.isChunkLoaded(i1, j1, true)) { + this.getChunkFromChunkCoords(i1, j1).getEntitiesOfTypeWithinAAAB(clazz, aabb, arraylist, filter); + } + } + } + + return arraylist; + } + + /** + * + Will get all entities within the specified AABB excluding the one passed + * into it. Args: entityToExclude, aabb + */ + public List getEntitiesWithinAABBExcludingEntity(Entity entityIn, AxisAlignedBB bb) { + return this.getEntitiesInAABBexcluding(entityIn, bb, EntitySelectors.NOT_SPECTATING); + } + + /** + * + Returns the Entity with the given ID, or null if it doesn't exist in this + * World. + */ + public Entity getEntityByID(int id) { + return (Entity) this.entitiesById.lookup(id); + } + + /** + * + Returns vector(ish) with R/G/B for fog + */ + public Vec3 getFogColor(float partialTicks) { + float f = this.getCelestialAngle(partialTicks); + return this.provider.getFogColor(f, partialTicks); + } + + /** + * + Gets the GameRules instance. + */ + public GameRules getGameRules() { + return this.worldInfo.getGameRulesInstance(); } public Block getGroundAboveSeaLevel(BlockPos pos) { @@ -213,296 +1109,41 @@ public abstract class World implements IBlockAccess { return this.getBlockState(blockpos).getBlock(); } - /**+ - * Check if the given BlockPos has valid coordinates + /** + * + Returns maximum world height. */ - private boolean isValid(BlockPos pos) { - return pos.getX() >= -30000000 && pos.getZ() >= -30000000 && pos.getX() < 30000000 && pos.getZ() < 30000000 - && pos.getY() >= 0 && pos.getY() < 256; + public int getHeight() { + return 256; } - /**+ - * Checks to see if an air block exists at the provided - * location. Note that this only checks to see if the blocks - * material is set to air, meaning it is possible for - * non-vanilla blocks to still pass this check. + /** + * + Returns maximum world height. */ - public boolean isAirBlock(BlockPos pos) { - return this.getBlockState(pos).getBlock().getMaterial() == Material.air; - } - - public boolean isBlockLoaded(BlockPos pos) { - return this.isBlockLoaded(pos, true); - } - - public boolean isBlockLoaded(BlockPos pos, boolean allowEmpty) { - return !this.isValid(pos) ? false : this.isChunkLoaded(pos.getX() >> 4, pos.getZ() >> 4, allowEmpty); - } - - public boolean isAreaLoaded(BlockPos center, int radius) { - return this.isAreaLoaded(center, radius, true); - } - - public boolean isAreaLoaded(BlockPos center, int radius, boolean allowEmpty) { - return this.isAreaLoaded(center.getX() - radius, center.getY() - radius, center.getZ() - radius, - center.getX() + radius, center.getY() + radius, center.getZ() + radius, allowEmpty); - } - - public boolean isAreaLoaded(BlockPos from, BlockPos to) { - return this.isAreaLoaded(from, to, true); - } - - public boolean isAreaLoaded(BlockPos from, BlockPos to, boolean allowEmpty) { - return this.isAreaLoaded(from.getX(), from.getY(), from.getZ(), to.getX(), to.getY(), to.getZ(), allowEmpty); - } - - public boolean isAreaLoaded(StructureBoundingBox box) { - return this.isAreaLoaded(box, true); - } - - public boolean isAreaLoaded(StructureBoundingBox box, boolean allowEmpty) { - return this.isAreaLoaded(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ, allowEmpty); - } - - private boolean isAreaLoaded(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty) { - if (yEnd >= 0 && yStart < 256) { - xStart = xStart >> 4; - zStart = zStart >> 4; - xEnd = xEnd >> 4; - zEnd = zEnd >> 4; - - for (int i = xStart; i <= xEnd; ++i) { - for (int j = zStart; j <= zEnd; ++j) { - if (!this.isChunkLoaded(i, j, allowEmpty)) { - return false; - } - } - } - - return true; - } else { - return false; - } - } - - protected boolean isChunkLoaded(int x, int z, boolean allowEmpty) { - return this.chunkProvider.chunkExists(x, z) && (allowEmpty || !this.chunkProvider.provideChunk(x, z).isEmpty()); - } - - public Chunk getChunkFromBlockCoords(BlockPos pos) { - return this.getChunkFromChunkCoords(pos.getX() >> 4, pos.getZ() >> 4); - } - - /**+ - * Returns back a chunk looked up by chunk coordinates Args: x, - * y - */ - public Chunk getChunkFromChunkCoords(int chunkX, int chunkZ) { - return this.chunkProvider.provideChunk(chunkX, chunkZ); - } - - /**+ - * Convenience method to update the block on both the client and - * server - */ - public boolean setBlockState(BlockPos pos, IBlockState newState, int flags) { - if (!this.isValid(pos)) { - return false; - } else if (!this.isRemote && this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { - return false; - } else { - Chunk chunk = this.getChunkFromBlockCoords(pos); - Block block = newState.getBlock(); - IBlockState iblockstate = chunk.setBlockState(pos, newState); - if (iblockstate == null) { - return false; + public BlockPos getHeight(BlockPos pos) { + int i; + if (pos.getX() >= -30000000 && pos.getZ() >= -30000000 && pos.getX() < 30000000 && pos.getZ() < 30000000) { + if (this.isChunkLoaded(pos.getX() >> 4, pos.getZ() >> 4, true)) { + i = this.getChunkFromChunkCoords(pos.getX() >> 4, pos.getZ() >> 4).getHeightValue(pos.getX() & 15, + pos.getZ() & 15); } else { - Block block1 = iblockstate.getBlock(); - if (block.getLightOpacity() != block1.getLightOpacity() - || block.getLightValue() != block1.getLightValue()) { - this.checkLight(pos); - } - - if ((flags & 2) != 0 && (!this.isRemote || (flags & 4) == 0) && chunk.isPopulated()) { - this.markBlockForUpdate(pos); - } - - if (!this.isRemote && (flags & 1) != 0) { - this.notifyNeighborsRespectDebug(pos, iblockstate.getBlock()); - if (block.hasComparatorInputOverride()) { - this.updateComparatorOutputLevel(pos, block); - } - } - - return true; + i = 0; } - } - } - - public boolean setBlockToAir(BlockPos pos) { - return this.setBlockState(pos, Blocks.air.getDefaultState(), 3); - } - - /**+ - * Sets a block to air, but also plays the sound and particles - * and can spawn drops - */ - public boolean destroyBlock(BlockPos pos, boolean dropBlock) { - IBlockState iblockstate = this.getBlockState(pos); - Block block = iblockstate.getBlock(); - if (block.getMaterial() == Material.air) { - return false; } else { - this.playAuxSFX(2001, pos, Block.getStateId(iblockstate)); - if (dropBlock) { - block.dropBlockAsItem(this, pos, iblockstate, 0); - } - - return this.setBlockState(pos, Blocks.air.getDefaultState(), 3); + i = this.func_181545_F() + 1; } + + return new BlockPos(pos.getX(), i, pos.getZ()); } - /**+ - * Convenience method to update the block on both the client and - * server + /** + * + Returns horizon height for use in rendering the sky. */ - public boolean setBlockState(BlockPos pos, IBlockState state) { - return this.setBlockState(pos, state, 3); + public double getHorizon() { + return this.worldInfo.getTerrainType() == WorldType.FLAT ? 0.0D : 63.0D; } - public void markBlockForUpdate(BlockPos pos) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).markBlockForUpdate(pos); - } - - } - - public void notifyNeighborsRespectDebug(BlockPos pos, Block blockType) { - if (this.worldInfo.getTerrainType() != WorldType.DEBUG_WORLD) { - this.notifyNeighborsOfStateChange(pos, blockType); - } - - } - - /**+ - * marks a vertical line of blocks as dirty - */ - public void markBlocksDirtyVertical(int x1, int z1, int x2, int z2) { - if (x2 > z2) { - int i = z2; - z2 = x2; - x2 = i; - } - - if (!this.provider.getHasNoSky()) { - for (int j = x2; j <= z2; ++j) { - this.checkLightFor(EnumSkyBlock.SKY, new BlockPos(x1, j, z1)); - } - } - - this.markBlockRangeForRenderUpdate(x1, x2, z1, x1, z2, z1); - } - - public void markBlockRangeForRenderUpdate(BlockPos rangeMin, BlockPos rangeMax) { - this.markBlockRangeForRenderUpdate(rangeMin.getX(), rangeMin.getY(), rangeMin.getZ(), rangeMax.getX(), - rangeMax.getY(), rangeMax.getZ()); - } - - public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).markBlockRangeForRenderUpdate(x1, y1, z1, x2, y2, z2); - } - - } - - public void notifyNeighborsOfStateChange(BlockPos pos, Block blockType) { - this.notifyBlockOfStateChange(pos.west(), blockType); - this.notifyBlockOfStateChange(pos.east(), blockType); - this.notifyBlockOfStateChange(pos.down(), blockType); - this.notifyBlockOfStateChange(pos.up(), blockType); - this.notifyBlockOfStateChange(pos.north(), blockType); - this.notifyBlockOfStateChange(pos.south(), blockType); - } - - public void notifyNeighborsOfStateExcept(BlockPos pos, Block blockType, EnumFacing skipSide) { - if (skipSide != EnumFacing.WEST) { - this.notifyBlockOfStateChange(pos.west(), blockType); - } - - if (skipSide != EnumFacing.EAST) { - this.notifyBlockOfStateChange(pos.east(), blockType); - } - - if (skipSide != EnumFacing.DOWN) { - this.notifyBlockOfStateChange(pos.down(), blockType); - } - - if (skipSide != EnumFacing.UP) { - this.notifyBlockOfStateChange(pos.up(), blockType); - } - - if (skipSide != EnumFacing.NORTH) { - this.notifyBlockOfStateChange(pos.north(), blockType); - } - - if (skipSide != EnumFacing.SOUTH) { - this.notifyBlockOfStateChange(pos.south(), blockType); - } - - } - - public void notifyBlockOfStateChange(BlockPos pos, final Block blockIn) { - if (!this.isRemote) { - IBlockState iblockstate = this.getBlockState(pos); - - try { - iblockstate.getBlock().onNeighborBlockChange(this, pos, iblockstate, blockIn); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while updating neighbours"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated"); - crashreportcategory.addCrashSectionCallable("Source block type", new Callable() { - public String call() throws Exception { - try { - return HString.format("ID #%d (%s // %s)", - new Object[] { Integer.valueOf(Block.getIdFromBlock(blockIn)), - blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName() }); - } catch (Throwable var2) { - return "ID #" + Block.getIdFromBlock(blockIn); - } - } - }); - CrashReportCategory.addBlockInfo(crashreportcategory, pos, iblockstate); - throw new ReportedException(crashreport); - } - } - } - - public boolean isBlockTickPending(BlockPos pos, Block blockType) { - return false; - } - - public boolean canSeeSky(BlockPos pos) { - return this.getChunkFromBlockCoords(pos).canSeeSky(pos); - } - - public boolean canBlockSeeSky(BlockPos pos) { - if (pos.getY() >= this.func_181545_F()) { - return this.canSeeSky(pos); - } else { - BlockPos blockpos = new BlockPos(pos.getX(), this.func_181545_F(), pos.getZ()); - if (!this.canSeeSky(blockpos)) { - return false; - } else { - for (blockpos = blockpos.down(); blockpos.getY() > pos.getY(); blockpos = blockpos.down()) { - Block block = this.getBlockState(blockpos).getBlock(); - if (block.getLightOpacity() > 0 && !block.getMaterial().isLiquid()) { - return false; - } - } - - return true; - } - } + public int getLastLightningBolt() { + return this.lastLightningBolt; } public int getLight(BlockPos pos) { @@ -517,10 +1158,6 @@ public abstract class World implements IBlockAccess { } } - public int getLightFromNeighbors(BlockPos pos) { - return this.getLight(pos, true); - } - public int getLight(BlockPos pos, boolean checkNeighbors) { if (pos.getX() >= -30000000 && pos.getZ() >= -30000000 && pos.getX() < 30000000 && pos.getZ() < 30000000) { if (checkNeighbors && this.getBlockState(pos).getBlock().getUseNeighborBrightness()) { @@ -561,40 +1198,27 @@ public abstract class World implements IBlockAccess { } } - /**+ - * Returns maximum world height. - */ - public BlockPos getHeight(BlockPos pos) { - int i; - if (pos.getX() >= -30000000 && pos.getZ() >= -30000000 && pos.getX() < 30000000 && pos.getZ() < 30000000) { - if (this.isChunkLoaded(pos.getX() >> 4, pos.getZ() >> 4, true)) { - i = this.getChunkFromChunkCoords(pos.getX() >> 4, pos.getZ() >> 4).getHeightValue(pos.getX() & 15, - pos.getZ() & 15); - } else { - i = 0; - } - } else { - i = this.func_181545_F() + 1; - } - - return new BlockPos(pos.getX(), i, pos.getZ()); + public float getLightBrightness(BlockPos pos) { + return this.provider.getLightBrightnessTable()[this.getLightFromNeighbors(pos)]; } - /**+ - * Gets the lowest height of the chunk where sunlight directly - * reaches - */ - public int getChunksLowestHorizon(int x, int z) { - if (x >= -30000000 && z >= -30000000 && x < 30000000 && z < 30000000) { - if (!this.isChunkLoaded(x >> 4, z >> 4, true)) { - return 0; - } else { - Chunk chunk = this.getChunkFromChunkCoords(x >> 4, z >> 4); - return chunk.getLowestHeight(); - } - } else { - return this.func_181545_F() + 1; + public int getLightFor(EnumSkyBlock type, BlockPos pos) { + if (pos.getY() < 0) { + pos = new BlockPos(pos.getX(), 0, pos.getZ()); } + + if (!this.isValid(pos)) { + return type.defaultLightValue; + } else if (!this.isBlockLoaded(pos)) { + return type.defaultLightValue; + } else { + Chunk chunk = this.getChunkFromBlockCoords(pos); + return chunk.getLightFor(type, pos); + } + } + + public int getLightFromNeighbors(BlockPos pos) { + return this.getLight(pos, true); } public int getLightFromNeighborsFor(EnumSkyBlock type, BlockPos pos) { @@ -639,27 +1263,913 @@ public abstract class World implements IBlockAccess { } } - public int getLightFor(EnumSkyBlock type, BlockPos pos) { - if (pos.getY() < 0) { - pos = new BlockPos(pos.getX(), 0, pos.getZ()); + /** + * + Accessor for world Loaded Entity List + */ + public List getLoadedEntityList() { + return this.loadedEntityList; + } + + public MapStorage getMapStorage() { + return this.mapStorage; + } + + public int getMoonPhase() { + return this.provider.getMoonPhase(this.worldInfo.getWorldTime()); + } + + public List getPendingBlockUpdates(Chunk chunkIn, boolean parFlag) { + return null; + } + + /** + * + Find a player by name in this world. + */ + public EntityPlayer getPlayerEntityByName(String name) { + for (int i = 0; i < this.playerEntities.size(); ++i) { + EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); + if (name.equals(entityplayer.getName())) { + return entityplayer; + } } - if (!this.isValid(pos)) { - return type.defaultLightValue; - } else if (!this.isBlockLoaded(pos)) { - return type.defaultLightValue; + return null; + } + + public EntityPlayer getPlayerEntityByUUID(EaglercraftUUID uuid) { + for (int i = 0; i < this.playerEntities.size(); ++i) { + EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); + if (uuid.equals(entityplayer.getUniqueID())) { + return entityplayer; + } + } + + return null; + } + + public List getPlayers(Class playerType, Predicate filter) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0, l = this.playerEntities.size(); i < l; ++i) { + Entity entity = this.playerEntities.get(i); + if (playerType.isAssignableFrom(entity.getClass()) && filter.apply((T) entity)) { + arraylist.add(entity); + } + } + + return arraylist; + } + + public BlockPos getPrecipitationHeight(BlockPos pos) { + return this.getChunkFromBlockCoords(pos).getPrecipitationHeight(pos); + } + + /** + * + Returns the name of the current chunk provider, by calling + * chunkprovider.makeString() + */ + public String getProviderName() { + return this.chunkProvider.makeString(); + } + + /** + * + Returns rain strength. + */ + public float getRainStrength(float delta) { + return this.prevRainingStrength + (this.rainingStrength - this.prevRainingStrength) * delta; + } + + /** + * + gets the light level at the supplied position + */ + private int getRawLight(BlockPos pos, EnumSkyBlock lightType) { + if (lightType == EnumSkyBlock.SKY && this.canSeeSky(pos)) { + return 15; } else { - Chunk chunk = this.getChunkFromBlockCoords(pos); - return chunk.getLightFor(type, pos); + Block block = this.getBlockState(pos).getBlock(); + int i = lightType == EnumSkyBlock.SKY ? 0 : block.getLightValue(); + int j = block.getLightOpacity(); + if (j >= 15 && block.getLightValue() > 0) { + j = 1; + } + + if (j < 1) { + j = 1; + } + + if (j >= 15) { + return 0; + } else if (i >= 14) { + return i; + } else { + EnumFacing[] facings = EnumFacing._VALUES; + for (int m = 0; m < facings.length; ++m) { + EnumFacing enumfacing = facings[m]; + BlockPos blockpos = pos.offset(enumfacing); + int k = this.getLightFor(lightType, blockpos) - j; + if (k > i) { + i = k; + } + + if (i >= 14) { + return i; + } + } + + return i; + } } } - public void setLightFor(EnumSkyBlock type, BlockPos pos, int lightValue) { - if (this.isValid(pos)) { - if (this.isBlockLoaded(pos)) { - Chunk chunk = this.getChunkFromBlockCoords(pos); - chunk.setLightFor(type, pos, lightValue); - this.notifyLightSet(pos); + public int getRedstonePower(BlockPos pos, EnumFacing facing) { + IBlockState iblockstate = this.getBlockState(pos); + Block block = iblockstate.getBlock(); + return block.isNormalCube() ? this.getStrongPower(pos) : block.getWeakPower(this, pos, iblockstate, facing); + } + + protected abstract int getRenderDistanceChunks(); + + /** + * + Returns this world's current save handler + */ + public ISaveHandler getSaveHandler() { + return this.saveHandler; + } + + public Scoreboard getScoreboard() { + return this.worldScoreboard; + } + + /** + * + gets the random world seed + */ + public long getSeed() { + return this.worldInfo.getSeed(); + } + + /** + * + Calculates the color for the skybox + */ + public Vec3 getSkyColor(Entity entityIn, float partialTicks) { + float f = this.getCelestialAngle(partialTicks); + float f1 = MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.5F; + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + int i = MathHelper.floor_double(entityIn.posX); + int j = MathHelper.floor_double(entityIn.posY); + int k = MathHelper.floor_double(entityIn.posZ); + BlockPos blockpos = new BlockPos(i, j, k); + BiomeGenBase biomegenbase = this.getBiomeGenForCoords(blockpos); + float f2 = biomegenbase.getFloatTemperature(blockpos); + int l = biomegenbase.getSkyColorByTemp(f2); + float f3 = (float) (l >> 16 & 255) / 255.0F; + float f4 = (float) (l >> 8 & 255) / 255.0F; + float f5 = (float) (l & 255) / 255.0F; + f3 = f3 * f1; + f4 = f4 * f1; + f5 = f5 * f1; + float f6 = this.getRainStrength(partialTicks); + if (f6 > 0.0F) { + float f7 = (f3 * 0.3F + f4 * 0.59F + f5 * 0.11F) * 0.6F; + float f8 = 1.0F - f6 * 0.75F; + f3 = f3 * f8 + f7 * (1.0F - f8); + f4 = f4 * f8 + f7 * (1.0F - f8); + f5 = f5 * f8 + f7 * (1.0F - f8); + } + + float f10 = this.getThunderStrength(partialTicks); + if (f10 > 0.0F) { + float f11 = (f3 * 0.3F + f4 * 0.59F + f5 * 0.11F) * 0.2F; + float f9 = 1.0F - f10 * 0.75F; + f3 = f3 * f9 + f11 * (1.0F - f9); + f4 = f4 * f9 + f11 * (1.0F - f9); + f5 = f5 * f9 + f11 * (1.0F - f9); + } + + if (this.lastLightningBolt > 0) { + float f12 = (float) this.lastLightningBolt - partialTicks; + if (f12 > 1.0F) { + f12 = 1.0F; + } + + f12 = f12 * 0.45F; + f3 = f3 * (1.0F - f12) + 0.8F * f12; + f4 = f4 * (1.0F - f12) + 0.8F * f12; + f5 = f5 * (1.0F - f12) + 1.0F * f12; + } + + return new Vec3((double) f3, (double) f4, (double) f5); + } + + public int getSkylightSubtracted() { + return this.skylightSubtracted; + } + + /** + * + Gets the spawn point in the world + */ + public BlockPos getSpawnPoint() { + BlockPos blockpos = new BlockPos(this.worldInfo.getSpawnX(), this.worldInfo.getSpawnY(), + this.worldInfo.getSpawnZ()); + if (!this.getWorldBorder().contains(blockpos)) { + blockpos = this.getHeight( + new BlockPos(this.getWorldBorder().getCenterX(), 0.0D, this.getWorldBorder().getCenterZ())); + } + + return blockpos; + } + + /** + * + How bright are stars in the sky + */ + public float getStarBrightness(float partialTicks) { + float f = this.getCelestialAngle(partialTicks); + float f1 = 1.0F - (MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.25F); + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + return f1 * f1 * 0.5F; + } + + public BlockPos getStrongholdPos(String name, BlockPos pos) { + return this.getChunkProvider().getStrongholdGen(this, name, pos); + } + + /** + * + Returns the single highest strong power out of all directions using + * getStrongPower(BlockPos, EnumFacing) + */ + public int getStrongPower(BlockPos pos) { + int i = 0; + i = Math.max(i, this.getStrongPower(pos.down(), EnumFacing.DOWN)); + if (i >= 15) { + return i; + } else { + i = Math.max(i, this.getStrongPower(pos.up(), EnumFacing.UP)); + if (i >= 15) { + return i; + } else { + i = Math.max(i, this.getStrongPower(pos.north(), EnumFacing.NORTH)); + if (i >= 15) { + return i; + } else { + i = Math.max(i, this.getStrongPower(pos.south(), EnumFacing.SOUTH)); + if (i >= 15) { + return i; + } else { + i = Math.max(i, this.getStrongPower(pos.west(), EnumFacing.WEST)); + if (i >= 15) { + return i; + } else { + i = Math.max(i, this.getStrongPower(pos.east(), EnumFacing.EAST)); + return i >= 15 ? i : i; + } + } + } + } + } + } + + /** + * + Returns the single highest strong power out of all directions using + * getStrongPower(BlockPos, EnumFacing) + */ + public int getStrongPower(BlockPos pos, EnumFacing direction) { + IBlockState iblockstate = this.getBlockState(pos); + return iblockstate.getBlock().getStrongPower(this, pos, iblockstate, direction); + } + + /** + * + Returns the sun brightness - checks time of day, rain and thunder + */ + public float getSunBrightness(float parFloat1) { + float f = this.getCelestialAngle(parFloat1); + float f1 = 1.0F - (MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.2F); + f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); + f1 = 1.0F - f1; + f1 = (float) ((double) f1 * (1.0D - (double) (this.getRainStrength(parFloat1) * 5.0F) / 16.0D)); + f1 = (float) ((double) f1 * (1.0D - (double) (this.getThunderStrength(parFloat1) * 5.0F) / 16.0D)); + return f1 * 0.8F + 0.2F; + } + + public float getThunderStrength(float delta) { + return (this.prevThunderingStrength + (this.thunderingStrength - this.prevThunderingStrength) * delta) + * this.getRainStrength(delta); + } + + public TileEntity getTileEntity(BlockPos pos) { + if (!this.isValid(pos)) { + return null; + } else { + TileEntity tileentity = null; + if (this.processingLoadedTiles) { + for (int i = 0; i < this.addedTileEntityList.size(); ++i) { + TileEntity tileentity1 = (TileEntity) this.addedTileEntityList.get(i); + if (!tileentity1.isInvalid() && tileentity1.getPos().equals(pos)) { + tileentity = tileentity1; + break; + } + } + } + + if (tileentity == null) { + tileentity = this.getChunkFromBlockCoords(pos).getTileEntity(pos, Chunk.EnumCreateEntityType.IMMEDIATE); + } + + if (tileentity == null) { + for (int j = 0; j < this.addedTileEntityList.size(); ++j) { + TileEntity tileentity2 = (TileEntity) this.addedTileEntityList.get(j); + if (!tileentity2.isInvalid() && tileentity2.getPos().equals(pos)) { + tileentity = tileentity2; + break; + } + } + } + + return tileentity; + } + } + + /** + * + Finds the highest block on the x and z coordinate that is solid or liquid, + * and returns its y coord. + */ + public BlockPos getTopSolidOrLiquidBlock(BlockPos pos) { + Chunk chunk = this.getChunkFromBlockCoords(pos); + + BlockPos blockpos; + BlockPos blockpos1; + for (blockpos = new BlockPos(pos.getX(), chunk.getTopFilledSegment() + 16, pos.getZ()); blockpos + .getY() >= 0; blockpos = blockpos1) { + blockpos1 = blockpos.down(); + Material material = chunk.getBlock(blockpos1).getMaterial(); + if (material.blocksMovement() && material != Material.leaves) { + break; + } + } + + return blockpos; + } + + public long getTotalWorldTime() { + return this.worldInfo.getWorldTotalTime(); + } + + /** + * + Returns an unique new data id from the MapStorage for the given prefix and + * saves the idCounts map to the 'idcounts' file. + */ + public int getUniqueDataId(String key) { + return this.mapStorage.getUniqueDataId(key); + } + + public VillageCollection getVillageCollection() { + return this.villageCollectionObj; + } + + public WorldBorder getWorldBorder() { + return this.worldBorder; + } + + public WorldChunkManager getWorldChunkManager() { + return this.provider.getWorldChunkManager(); + } + + /** + * + Returns the world's WorldInfo object + */ + public WorldInfo getWorldInfo() { + return this.worldInfo; + } + + public long getWorldTime() { + return this.worldInfo.getWorldTime(); + } + + public WorldType getWorldType() { + return this.worldInfo.getTerrainType(); + } + + /** + * + handles the acceleration of an object whilst in water. Not sure if it is + * used elsewhere. + */ + public boolean handleMaterialAcceleration(AxisAlignedBB bb, Material materialIn, Entity entityIn) { + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX + 1.0D); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY + 1.0D); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); + if (!this.isAreaLoaded(i, k, i1, j, l, j1, true)) { + return false; + } else { + boolean flag = false; + Vec3 vec3 = new Vec3(0.0D, 0.0D, 0.0D); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + blockpos$mutableblockpos.func_181079_c(k1, l1, i2); + IBlockState iblockstate = this.getBlockState(blockpos$mutableblockpos); + Block block = iblockstate.getBlock(); + if (block.getMaterial() == materialIn) { + double d0 = (double) ((float) (l1 + 1) - BlockLiquid.getLiquidHeightPercent( + ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue())); + if ((double) l >= d0) { + flag = true; + vec3 = block.modifyAcceleration(this, blockpos$mutableblockpos, entityIn, vec3); + } + } + } + } + } + + if (vec3.lengthVector() > 0.0D && entityIn.isPushedByWater()) { + vec3 = vec3.normalize(); + double d1 = 0.014D; + entityIn.motionX += vec3.xCoord * d1; + entityIn.motionY += vec3.yCoord * d1; + entityIn.motionZ += vec3.zCoord * d1; + } + + return flag; + } + } + + public World init() { + return this; + } + + public void initialize(WorldSettings settings) { + this.worldInfo.setServerInitialized(true); + } + + /** + * + checks if the given AABB is in the material given. Used while swimming. + */ + public boolean isAABBInMaterial(AxisAlignedBB bb, Material materialIn) { + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX + 1.0D); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY + 1.0D); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + IBlockState iblockstate = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)); + Block block = iblockstate.getBlock(); + if (block.getMaterial() == materialIn) { + int j2 = ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue(); + double d0 = (double) (l1 + 1); + if (j2 < 8) { + d0 = (double) (l1 + 1) - (double) j2 / 8.0D; + } + + if (d0 >= bb.minY) { + return true; + } + } + } + } + } + + return false; + } + + /** + * + Checks to see if an air block exists at the provided location. Note that + * this only checks to see if the blocks material is set to air, meaning it is + * possible for non-vanilla blocks to still pass this check. + */ + public boolean isAirBlock(BlockPos pos) { + return this.getBlockState(pos).getBlock().getMaterial() == Material.air; + } + + /** + * + Returns if any of the blocks within the aabb are liquids. Args: aabb + */ + public boolean isAnyLiquid(AxisAlignedBB bb) { + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 <= j; ++k1) { + for (int l1 = k; l1 <= l; ++l1) { + for (int i2 = i1; i2 <= j1; ++i2) { + Block block = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock(); + if (block.getMaterial().isLiquid()) { + return true; + } + } + } + } + + return false; + } + + public boolean isAnyPlayerWithinRangeAt(double x, double y, double z, double range) { + for (int i = 0; i < this.playerEntities.size(); ++i) { + EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); + if (EntitySelectors.NOT_SPECTATING.apply(entityplayer)) { + double d0 = entityplayer.getDistanceSq(x, y, z); + if (range < 0.0D || d0 < range * range) { + return true; + } + } + } + + return false; + } + + public boolean isAreaLoaded(BlockPos from, BlockPos to) { + return this.isAreaLoaded(from, to, true); + } + + public boolean isAreaLoaded(BlockPos from, BlockPos to, boolean allowEmpty) { + return this.isAreaLoaded(from.getX(), from.getY(), from.getZ(), to.getX(), to.getY(), to.getZ(), allowEmpty); + } + + public boolean isAreaLoaded(BlockPos center, int radius) { + return this.isAreaLoaded(center, radius, true); + } + + public boolean isAreaLoaded(BlockPos center, int radius, boolean allowEmpty) { + return this.isAreaLoaded(center.getX() - radius, center.getY() - radius, center.getZ() - radius, + center.getX() + radius, center.getY() + radius, center.getZ() + radius, allowEmpty); + } + + private boolean isAreaLoaded(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty) { + if (yEnd >= 0 && yStart < 256) { + xStart = xStart >> 4; + zStart = zStart >> 4; + xEnd = xEnd >> 4; + zEnd = zEnd >> 4; + + for (int i = xStart; i <= xEnd; ++i) { + for (int j = zStart; j <= zEnd; ++j) { + if (!this.isChunkLoaded(i, j, allowEmpty)) { + return false; + } + } + } + + return true; + } else { + return false; + } + } + + public boolean isAreaLoaded(StructureBoundingBox box) { + return this.isAreaLoaded(box, true); + } + + public boolean isAreaLoaded(StructureBoundingBox box, boolean allowEmpty) { + return this.isAreaLoaded(box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ, allowEmpty); + } + + public boolean isBlockFullCube(BlockPos pos) { + IBlockState iblockstate = this.getBlockState(pos); + AxisAlignedBB axisalignedbb = iblockstate.getBlock().getCollisionBoundingBox(this, pos, iblockstate); + return axisalignedbb != null && axisalignedbb.getAverageEdgeLength() >= 1.0D; + } + + /** + * + Checks if the specified block or its neighbors are powered by a neighboring + * block. Used by blocks like TNT and Doors. + */ + public int isBlockIndirectlyGettingPowered(BlockPos pos) { + int i = 0; + + EnumFacing[] facings = EnumFacing._VALUES; + BlockPos tmp = new BlockPos(0, 0, 0); + for (int k = 0; k < facings.length; ++k) { + EnumFacing enumfacing = facings[k]; + int j = this.getRedstonePower(pos.offsetEvenFaster(enumfacing, tmp), enumfacing); + if (j >= 15) { + return 15; + } + + if (j > i) { + i = j; + } + } + + return i; + } + + public boolean isBlockinHighHumidity(BlockPos pos) { + BiomeGenBase biomegenbase = this.getBiomeGenForCoords(pos); + return biomegenbase.isHighHumidity(); + } + + public boolean isBlockLoaded(BlockPos pos) { + return this.isBlockLoaded(pos, true); + } + + public boolean isBlockLoaded(BlockPos pos, boolean allowEmpty) { + return !this.isValid(pos) ? false : this.isChunkLoaded(pos.getX() >> 4, pos.getZ() >> 4, allowEmpty); + } + + public boolean isBlockModifiable(EntityPlayer player, BlockPos pos) { + return true; + } + + /** + * + Checks if a block's material is opaque, and that it takes up a full cube + */ + public boolean isBlockNormalCube(BlockPos pos, boolean _default) { + if (!this.isValid(pos)) { + return _default; + } else { + Chunk chunk = this.chunkProvider.provideChunk(pos); + if (chunk.isEmpty()) { + return _default; + } else { + Block block = this.getBlockState(pos).getBlock(); + return block.getMaterial().isOpaque() && block.isFullCube(); + } + } + } + + public boolean isBlockPowered(BlockPos pos) { + return this.getRedstonePower(pos.down(), EnumFacing.DOWN) > 0 ? true + : (this.getRedstonePower(pos.up(), EnumFacing.UP) > 0 ? true + : (this.getRedstonePower(pos.north(), EnumFacing.NORTH) > 0 ? true + : (this.getRedstonePower(pos.south(), EnumFacing.SOUTH) > 0 ? true + : (this.getRedstonePower(pos.west(), EnumFacing.WEST) > 0 ? true + : this.getRedstonePower(pos.east(), EnumFacing.EAST) > 0)))); + } + + public boolean isBlockTickPending(BlockPos pos, Block blockType) { + return false; + } + + protected boolean isChunkLoaded(int x, int z, boolean allowEmpty) { + return this.chunkProvider.chunkExists(x, z) && (allowEmpty || !this.chunkProvider.provideChunk(x, z).isEmpty()); + } + + /** + * + Checks whether its daytime by seeing if the light subtracted from the + * skylight is less than 4 + */ + public boolean isDaytime() { + return this.skylightSubtracted < 4; + } + + public boolean isFindingSpawnPoint() { + return this.findingSpawnPoint; + } + + public boolean isFlammableWithin(AxisAlignedBB bb) { + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX + 1.0D); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY + 1.0D); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); + if (this.isAreaLoaded(i, k, i1, j, l, j1, true)) { + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + Block block = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock(); + if (block == Blocks.fire || block == Blocks.flowing_lava || block == Blocks.lava) { + return true; + } + } + } + } + } + + return false; + } + + public boolean isInsideBorder(WorldBorder worldBorderIn, Entity entityIn) { + double d0 = worldBorderIn.minX(); + double d1 = worldBorderIn.minZ(); + double d2 = worldBorderIn.maxX(); + double d3 = worldBorderIn.maxZ(); + if (entityIn.isOutsideBorder()) { + ++d0; + ++d1; + --d2; + --d3; + } else { + --d0; + --d1; + ++d2; + ++d3; + } + + return entityIn.posX > d0 && entityIn.posX < d2 && entityIn.posZ > d1 && entityIn.posZ < d3; + } + + /** + * + Returns true if the given bounding box contains the given material + */ + public boolean isMaterialInBB(AxisAlignedBB bb, Material materialIn) { + int i = MathHelper.floor_double(bb.minX); + int j = MathHelper.floor_double(bb.maxX + 1.0D); + int k = MathHelper.floor_double(bb.minY); + int l = MathHelper.floor_double(bb.maxY + 1.0D); + int i1 = MathHelper.floor_double(bb.minZ); + int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 < j; ++k1) { + for (int l1 = k; l1 < l; ++l1) { + for (int i2 = i1; i2 < j1; ++i2) { + if (this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock() + .getMaterial() == materialIn) { + return true; + } + } + } + } + + return false; + } + + /** + * + Returns true if the current rain strength is greater than 0.2 + */ + public boolean isRaining() { + return (double) this.getRainStrength(1.0F) > 0.2D; + } + + public boolean isSidePowered(BlockPos pos, EnumFacing side) { + return this.getRedstonePower(pos, side) > 0; + } + + /** + * + Returns true if the chunk is located near the spawn point + */ + public boolean isSpawnChunk(int x, int z) { + if (!MinecraftServer.getServer().worldServers[0].getWorldInfo().getGameRulesInstance() + .getBoolean("loadSpawnChunks")) + return false; + BlockPos blockpos = this.getSpawnPoint(); + int i = x * 16 + 8 - blockpos.getX(); + int j = z * 16 + 8 - blockpos.getZ(); + short short1 = 128; + return i >= -short1 && i <= short1 && j >= -short1 && j <= short1; + } + + /** + * + Returns true if the current thunder strength (weighted with the rain + * strength) is greater than 0.9 + */ + public boolean isThundering() { + return (double) this.getThunderStrength(1.0F) > 0.9D; + } + + /** + * + Check if the given BlockPos has valid coordinates + */ + private boolean isValid(BlockPos pos) { + return pos.getX() >= -30000000 && pos.getZ() >= -30000000 && pos.getX() < 30000000 && pos.getZ() < 30000000 + && pos.getY() >= 0 && pos.getY() < 256; + } + + private boolean isWater(BlockPos pos) { + return this.getBlockState(pos).getBlock().getMaterial() == Material.water; + } + + /** + * + spwans an entity and loads surrounding chunks + */ + public void joinEntityInSurroundings(Entity entityIn) { + int i = MathHelper.floor_double(entityIn.posX / 16.0D); + int j = MathHelper.floor_double(entityIn.posZ / 16.0D); + byte b0 = 2; + + for (int k = i - b0; k <= i + b0; ++k) { + for (int l = j - b0; l <= j + b0; ++l) { + this.getChunkFromChunkCoords(k, l); + } + } + + if (!this.loadedEntityList.contains(entityIn)) { + this.loadedEntityList.add(entityIn); + } + + } + + public void loadEntities(Collection entityCollection) { + this.loadedEntityList.addAll(entityCollection); + + for (Entity entity : entityCollection) { + this.onEntityAdded(entity); + } + + } + + /** + * + Loads an existing MapDataBase corresponding to the given String id from + * disk using the MapStorage, instantiating the given Class, or returns null if + * none such file exists. args: Class to instantiate, String dataid + */ + public WorldSavedData loadItemData(Class clazz, String dataID) { + return this.mapStorage.loadData(clazz, dataID); + } + + public void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, + NBTTagCompound compund) { + } + + public void markBlockForUpdate(BlockPos pos) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).markBlockForUpdate(pos); + } + + } + + public void markBlockRangeForRenderUpdate(BlockPos rangeMin, BlockPos rangeMax) { + this.markBlockRangeForRenderUpdate(rangeMin.getX(), rangeMin.getY(), rangeMin.getZ(), rangeMax.getX(), + rangeMax.getY(), rangeMax.getZ()); + } + + public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).markBlockRangeForRenderUpdate(x1, y1, z1, x2, y2, z2); + } + + } + + /** + * + marks a vertical line of blocks as dirty + */ + public void markBlocksDirtyVertical(int x1, int z1, int x2, int z2) { + if (x2 > z2) { + int i = z2; + z2 = x2; + x2 = i; + } + + if (!this.provider.getHasNoSky()) { + for (int j = x2; j <= z2; ++j) { + this.checkLightFor(EnumSkyBlock.SKY, new BlockPos(x1, j, z1)); + } + } + + this.markBlockRangeForRenderUpdate(x1, x2, z1, x1, z2, z1); + } + + public void markChunkDirty(BlockPos pos, TileEntity unusedTileEntity) { + if (this.isBlockLoaded(pos)) { + this.getChunkFromBlockCoords(pos).setChunkModified(); + } + + } + + /** + * + Adds the specified TileEntity to the pending removal list. + */ + public void markTileEntityForRemoval(TileEntity tileEntityIn) { + this.tileEntitiesToBeRemoved.add(tileEntityIn); + } + + /** + * + returns a new explosion. Does initiation (at time of writing Explosion is + * not finished) + */ + public Explosion newExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, + boolean isSmoking) { + Explosion explosion = new Explosion(this, entityIn, x, y, z, strength, isFlaming, isSmoking); + explosion.doExplosionA(); + explosion.doExplosionB(true); + return explosion; + } + + public void notifyBlockOfStateChange(BlockPos pos, final Block blockIn) { + if (!this.isRemote) { + IBlockState iblockstate = this.getBlockState(pos); + + try { + iblockstate.getBlock().onNeighborBlockChange(this, pos, iblockstate, blockIn); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception while updating neighbours"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being updated"); + crashreportcategory.addCrashSectionCallable("Source block type", new Callable() { + public String call() throws Exception { + try { + return HString.format("ID #%d (%s // %s)", + new Object[] { Integer.valueOf(Block.getIdFromBlock(blockIn)), + blockIn.getUnlocalizedName(), blockIn.getClass().getCanonicalName() }); + } catch (Throwable var2) { + return "ID #" + Block.getIdFromBlock(blockIn); + } + } + }); + CrashReportCategory.addBlockInfo(crashreportcategory, pos, iblockstate); + throw new ReportedException(crashreport); } } } @@ -671,58 +2181,184 @@ public abstract class World implements IBlockAccess { } - public int getCombinedLight(BlockPos pos, int lightValue) { - int i = this.getLightFromNeighborsFor(EnumSkyBlock.SKY, pos); - int j = this.getLightFromNeighborsFor(EnumSkyBlock.BLOCK, pos); - if (lightValue < 0) { - j += -lightValue; - if (j > 15) { - j = 15; + public void notifyNeighborsOfStateChange(BlockPos pos, Block blockType) { + this.notifyBlockOfStateChange(pos.west(), blockType); + this.notifyBlockOfStateChange(pos.east(), blockType); + this.notifyBlockOfStateChange(pos.down(), blockType); + this.notifyBlockOfStateChange(pos.up(), blockType); + this.notifyBlockOfStateChange(pos.north(), blockType); + this.notifyBlockOfStateChange(pos.south(), blockType); + } + + public void notifyNeighborsOfStateExcept(BlockPos pos, Block blockType, EnumFacing skipSide) { + if (skipSide != EnumFacing.WEST) { + this.notifyBlockOfStateChange(pos.west(), blockType); + } + + if (skipSide != EnumFacing.EAST) { + this.notifyBlockOfStateChange(pos.east(), blockType); + } + + if (skipSide != EnumFacing.DOWN) { + this.notifyBlockOfStateChange(pos.down(), blockType); + } + + if (skipSide != EnumFacing.UP) { + this.notifyBlockOfStateChange(pos.up(), blockType); + } + + if (skipSide != EnumFacing.NORTH) { + this.notifyBlockOfStateChange(pos.north(), blockType); + } + + if (skipSide != EnumFacing.SOUTH) { + this.notifyBlockOfStateChange(pos.south(), blockType); + } + + } + + public void notifyNeighborsRespectDebug(BlockPos pos, Block blockType) { + if (this.worldInfo.getTerrainType() != WorldType.DEBUG_WORLD) { + this.notifyNeighborsOfStateChange(pos, blockType); + } + + } + + protected void onEntityAdded(Entity entityIn) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).onEntityAdded(entityIn); + } + + } + + protected void onEntityRemoved(Entity entityIn) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).onEntityRemoved(entityIn); + } + + } + + public void playAuxSFX(int pos, BlockPos parBlockPos, int parInt2) { + this.playAuxSFXAtEntity((EntityPlayer) null, pos, parBlockPos, parInt2); + } + + public void playAuxSFXAtEntity(EntityPlayer player, int sfxType, BlockPos pos, int parInt2) { + try { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).playAuxSFX(player, sfxType, pos, parInt2); } - } else if (j < lightValue) { - j = lightValue; - } - return i << 20 | j << 4; - } - - public float getLightBrightness(BlockPos pos) { - return this.provider.getLightBrightnessTable()[this.getLightFromNeighbors(pos)]; - } - - public IBlockState getBlockState(BlockPos pos) { - if (!this.isValid(pos)) { - return Blocks.air.getDefaultState(); - } else { - Chunk chunk = this.getChunkFromBlockCoords(pos); - return chunk.getBlockState(pos); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Playing level event"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Level event being played"); + crashreportcategory.addCrashSection("Block coordinates", CrashReportCategory.getCoordinateInfo(pos)); + crashreportcategory.addCrashSection("Event source", player); + crashreportcategory.addCrashSection("Event type", Integer.valueOf(sfxType)); + crashreportcategory.addCrashSection("Event data", Integer.valueOf(parInt2)); + throw new ReportedException(crashreport); } } - /**+ - * Checks whether its daytime by seeing if the light subtracted - * from the skylight is less than 4 + public void playBroadcastSound(int pos, BlockPos parBlockPos, int parInt2) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).broadcastSound(pos, parBlockPos, parInt2); + } + + } + + protected void playMoodSoundAndCheckLight(int chunkIn, int parInt2, Chunk parChunk) { + if (this.ambientTickCountdown == 0 && !this.isRemote) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int i = this.updateLCG >> 2; + int j = i & 15; + int k = i >> 8 & 15; + int l = i >> 16 & 255; + BlockPos blockpos = new BlockPos(j, l, k); + Block block = parChunk.getBlock(blockpos); + j = j + chunkIn; + k = k + parInt2; + if (block.getMaterial() == Material.air && this.getLight(blockpos) <= this.rand.nextInt(8) + && this.getLightFor(EnumSkyBlock.SKY, blockpos) <= 0) { + EntityPlayer entityplayer = this.getClosestPlayer((double) j + 0.5D, (double) l + 0.5D, + (double) k + 0.5D, 8.0D); + if (entityplayer != null + && entityplayer.getDistanceSq((double) j + 0.5D, (double) l + 0.5D, (double) k + 0.5D) > 4.0D) { + this.playSoundEffect((double) j + 0.5D, (double) l + 0.5D, (double) k + 0.5D, "ambient.cave.cave", + 0.7F, 0.8F + this.rand.nextFloat() * 0.2F); + this.ambientTickCountdown = this.rand.nextInt(12000) + 6000; + } + } + } + + parChunk.enqueueRelightChecks(); + } + + public void playRecord(BlockPos pos, String name) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).playRecord(name, pos); + } + + } + + /** + * + par8 is loudness, all pars passed to minecraftInstance.sndManager.playSound */ - public boolean isDaytime() { - return this.skylightSubtracted < 4; + public void playSound(double x, double y, double z, String soundName, float volume, float pitch, + boolean distanceDelay) { } - /**+ - * ray traces all blocks, including non-collideable ones + /** + * + Plays a sound at the entity's position. Args: entity, sound, volume + * (relative to 1.0), and frequency (or pitch, also relative to 1.0). + */ + public void playSoundAtEntity(Entity entityIn, String name, float volume, float pitch) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).playSound(name, entityIn.posX, entityIn.posY, entityIn.posZ, + volume, pitch); + } + + } + + /** + * + Play a sound effect. Many many parameters for this function. Not sure what + * they do, but a classic call is : (double)i + 0.5D, (double)j + 0.5D, + * (double)k + 0.5D, 'random.door_open', 1.0F, world.rand.nextFloat() * 0.1F + + * 0.9F with i,j,k position of the block. + */ + public void playSoundEffect(double x, double y, double z, String soundName, float volume, float pitch) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).playSound(soundName, x, y, z, volume, pitch); + } + + } + + /** + * + Plays sound to all near players except the player reference given + */ + public void playSoundToNearExcept(EntityPlayer player, String name, float volume, float pitch) { + for (int i = 0; i < this.worldAccesses.size(); ++i) { + ((IWorldAccess) this.worldAccesses.get(i)).playSoundToNearExcept(player, name, player.posX, player.posY, + player.posZ, volume, pitch); + } + + } + + /** + * + ray traces all blocks, including non-collideable ones */ public MovingObjectPosition rayTraceBlocks(Vec3 parVec3_1, Vec3 parVec3_2) { return this.rayTraceBlocks(parVec3_1, parVec3_2, false, false, false); } - /**+ - * ray traces all blocks, including non-collideable ones + /** + * + ray traces all blocks, including non-collideable ones */ public MovingObjectPosition rayTraceBlocks(Vec3 start, Vec3 end, boolean stopOnLiquid) { return this.rayTraceBlocks(start, end, stopOnLiquid, false, false); } - /**+ - * ray traces all blocks, including non-collideable ones + /** + * + ray traces all blocks, including non-collideable ones */ public MovingObjectPosition rayTraceBlocks(Vec3 vec31, Vec3 vec32, boolean stopOnLiquid, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) { @@ -860,93 +2496,285 @@ public abstract class World implements IBlockAccess { } } - /**+ - * Plays a sound at the entity's position. Args: entity, sound, - * volume (relative to 1.0), and frequency (or pitch, also - * relative to 1.0). + /** + * + Schedule the entity for removal during the next tick. Marks the entity dead + * in anticipation. */ - public void playSoundAtEntity(Entity entityIn, String name, float volume, float pitch) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).playSound(name, entityIn.posX, entityIn.posY, entityIn.posZ, - volume, pitch); + public void removeEntity(Entity entityIn) { + if (entityIn.riddenByEntity != null) { + entityIn.riddenByEntity.mountEntity((Entity) null); + } + + if (entityIn.ridingEntity != null) { + entityIn.mountEntity((Entity) null); + } + + entityIn.setDead(); + if (entityIn instanceof EntityPlayer) { + this.playerEntities.remove(entityIn); + this.updateAllPlayersSleepingFlag(); + this.onEntityRemoved(entityIn); } } - /**+ - * Plays sound to all near players except the player reference - * given + /** + * + Do NOT use this method to remove normal entities- use normal removeEntity */ - public void playSoundToNearExcept(EntityPlayer player, String name, float volume, float pitch) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).playSoundToNearExcept(player, name, player.posX, player.posY, - player.posZ, volume, pitch); + public void removePlayerEntityDangerously(Entity entityIn) { + entityIn.setDead(); + if (entityIn instanceof EntityPlayer) { + this.playerEntities.remove(entityIn); + this.updateAllPlayersSleepingFlag(); + } + + int i = entityIn.chunkCoordX; + int j = entityIn.chunkCoordZ; + if (entityIn.addedToChunk && this.isChunkLoaded(i, j, true)) { + this.getChunkFromChunkCoords(i, j).removeEntity(entityIn); + } + + this.loadedEntityList.remove(entityIn); + this.onEntityRemoved(entityIn); + } + + public void removeTileEntity(BlockPos pos) { + TileEntity tileentity = this.getTileEntity(pos); + if (tileentity != null && this.processingLoadedTiles) { + tileentity.invalidate(); + this.addedTileEntityList.remove(tileentity); + } else { + if (tileentity != null) { + this.addedTileEntityList.remove(tileentity); + this.loadedTileEntityList.remove(tileentity); + this.tickableTileEntities.remove(tileentity); + } + + this.getChunkFromBlockCoords(pos).removeTileEntity(pos); } } - /**+ - * Play a sound effect. Many many parameters for this function. - * Not sure what they do, but a classic call is : (double)i + - * 0.5D, (double)j + 0.5D, (double)k + 0.5D, 'random.door_open', - * 1.0F, world.rand.nextFloat() * 0.1F + 0.9F with i,j,k - * position of the block. + /** + * + Removes a worldAccess from the worldAccesses object */ - public void playSoundEffect(double x, double y, double z, String soundName, float volume, float pitch) { + public void removeWorldAccess(IWorldAccess worldAccess) { + this.worldAccesses.remove(worldAccess); + } + + public void scheduleBlockUpdate(BlockPos pos, Block blockIn, int delay, int priority) { + } + + public void scheduleUpdate(BlockPos pos, Block blockIn, int delay) { + } + + public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).playSound(soundName, x, y, z, volume, pitch); + IWorldAccess iworldaccess = (IWorldAccess) this.worldAccesses.get(i); + iworldaccess.sendBlockBreakProgress(breakerId, pos, progress); } } - /**+ - * par8 is loudness, all pars passed to - * minecraftInstance.sndManager.playSound + /** + * + If on MP, sends a quitting packet. */ - public void playSound(double x, double y, double z, String soundName, float volume, float pitch, - boolean distanceDelay) { + public void sendQuittingDisconnectingPacket() { } - public void playRecord(BlockPos pos, String name) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).playRecord(name, pos); + protected void setActivePlayerChunksAndCheckLight() { + this.activeChunkSet.clear(); + + for (int i = 0; i < this.playerEntities.size(); ++i) { + EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); + int j = MathHelper.floor_double(entityplayer.posX / 16.0D); + int k = MathHelper.floor_double(entityplayer.posZ / 16.0D); + int l = this.getRenderDistanceChunks(); + + for (int i1 = -l; i1 <= l; ++i1) { + for (int j1 = -l; j1 <= l; ++j1) { + this.activeChunkSet.add(new ChunkCoordIntPair(i1 + j, j1 + k)); + } + } + } + + if (this.ambientTickCountdown > 0) { + --this.ambientTickCountdown; + } + + if (!this.playerEntities.isEmpty()) { + int k1 = this.rand.nextInt(this.playerEntities.size()); + EntityPlayer entityplayer1 = (EntityPlayer) this.playerEntities.get(k1); + int l1 = MathHelper.floor_double(entityplayer1.posX) + this.rand.nextInt(11) - 5; + int i2 = MathHelper.floor_double(entityplayer1.posY) + this.rand.nextInt(11) - 5; + int j2 = MathHelper.floor_double(entityplayer1.posZ) + this.rand.nextInt(11) - 5; + this.checkLight(new BlockPos(l1, i2, j2)); } } - public void spawnParticle(EnumParticleTypes particleType, double xCoord, double yCoord, double zCoord, - double xOffset, double yOffset, double zOffset, int... parArrayOfInt) { - this.spawnParticle(particleType.getParticleID(), particleType.getShouldIgnoreRange(), xCoord, yCoord, zCoord, - xOffset, yOffset, zOffset, parArrayOfInt); + /** + * + first boolean for hostile mobs and second for peaceful mobs + */ + public void setAllowedSpawnTypes(boolean hostile, boolean peaceful) { + this.spawnHostileMobs = hostile; + this.spawnPeacefulMobs = peaceful; } - public void spawnParticle(EnumParticleTypes particleType, boolean xCoord, double yCoord, double zCoord, - double xOffset, double yOffset, double zOffset, double parDouble6, int... parArrayOfInt) { - this.spawnParticle(particleType.getParticleID(), particleType.getShouldIgnoreRange() | xCoord, yCoord, zCoord, - xOffset, yOffset, zOffset, parDouble6, parArrayOfInt); + /** + * + Convenience method to update the block on both the client and server + */ + public boolean setBlockState(BlockPos pos, IBlockState state) { + return this.setBlockState(pos, state, 3); } - private void spawnParticle(int particleID, boolean xCood, double yCoord, double zCoord, double xOffset, - double yOffset, double zOffset, double parDouble6, int... parArrayOfInt) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).spawnParticle(particleID, xCood, yCoord, zCoord, xOffset, - yOffset, zOffset, parDouble6, parArrayOfInt); + /** + * + Convenience method to update the block on both the client and server + */ + public boolean setBlockState(BlockPos pos, IBlockState newState, int flags) { + if (!this.isValid(pos)) { + return false; + } else if (!this.isRemote && this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { + return false; + } else { + Chunk chunk = this.getChunkFromBlockCoords(pos); + Block block = newState.getBlock(); + IBlockState iblockstate = chunk.setBlockState(pos, newState); + if (iblockstate == null) { + return false; + } else { + Block block1 = iblockstate.getBlock(); + if (block.getLightOpacity() != block1.getLightOpacity() + || block.getLightValue() != block1.getLightValue()) { + this.checkLight(pos); + } + + if ((flags & 2) != 0 && (!this.isRemote || (flags & 4) == 0) && chunk.isPopulated()) { + this.markBlockForUpdate(pos); + } + + if (!this.isRemote && (flags & 1) != 0) { + this.notifyNeighborsRespectDebug(pos, iblockstate.getBlock()); + if (block.hasComparatorInputOverride()) { + this.updateComparatorOutputLevel(pos, block); + } + } + + return true; + } + } + } + + public boolean setBlockToAir(BlockPos pos) { + return this.setBlockState(pos, Blocks.air.getDefaultState(), 3); + } + + /** + * + sends a Packet 38 (Entity Status) to all tracked players of that entity + */ + public void setEntityState(Entity entityIn, byte state) { + } + + /** + * + Sets a new spawn location by finding an uncovered block at a random (x,z) + * location in the chunk. + */ + public void setInitialSpawnLocation() { + this.setSpawnPoint(new BlockPos(8, 64, 8)); + } + + /** + * + Assigns the given String id to the given MapDataBase using the MapStorage, + * removing any existing ones of the same id. + */ + public void setItemData(String dataID, WorldSavedData worldSavedDataIn) { + this.mapStorage.setData(dataID, worldSavedDataIn); + } + + public void setLastLightningBolt(int lastLightningBoltIn) { + this.lastLightningBolt = lastLightningBoltIn; + } + + public void setLightFor(EnumSkyBlock type, BlockPos pos, int lightValue) { + if (this.isValid(pos)) { + if (this.isBlockLoaded(pos)) { + Chunk chunk = this.getChunkFromBlockCoords(pos); + chunk.setLightFor(type, pos, lightValue); + this.notifyLightSet(pos); + } + } + } + + /** + * + Sets the strength of the rain. + */ + public void setRainStrength(float strength) { + this.prevRainingStrength = strength; + this.rainingStrength = strength; + } + + /** + * + puts the World Random seed to a specific state dependant on the inputs + */ + public EaglercraftRandom setRandomSeed(int parInt1, int parInt2, int parInt3) { + long i = (long) parInt1 * 341873128712L + (long) parInt2 * 132897987541L + this.getWorldInfo().getSeed() + + (long) parInt3; + this.rand.setSeed(i); + return this.rand; + } + + public void setSkylightSubtracted(int newSkylightSubtracted) { + this.skylightSubtracted = newSkylightSubtracted; + } + + public void setSpawnPoint(BlockPos pos) { + this.worldInfo.setSpawn(pos); + } + + /** + * + Sets the strength of the thunder. + */ + public void setThunderStrength(float strength) { + this.prevThunderingStrength = strength; + this.thunderingStrength = strength; + } + + public void setTileEntity(BlockPos pos, TileEntity tileEntityIn) { + if (tileEntityIn != null && !tileEntityIn.isInvalid()) { + if (this.processingLoadedTiles) { + tileEntityIn.setPos(pos); + Iterator iterator = this.addedTileEntityList.iterator(); + + while (iterator.hasNext()) { + TileEntity tileentity = (TileEntity) iterator.next(); + if (tileentity.getPos().equals(pos)) { + tileentity.invalidate(); + iterator.remove(); + } + } + + this.addedTileEntityList.add(tileEntityIn); + } else { + this.addTileEntity(tileEntityIn); + this.getChunkFromBlockCoords(pos).addTileEntity(pos, tileEntityIn); + } } } - /**+ - * adds a lightning bolt to the list of lightning bolts in this - * world. - */ - public boolean addWeatherEffect(Entity entityIn) { - this.weatherEffects.add(entityIn); - return true; + public void setTotalWorldTime(long worldTime) { + this.worldInfo.setWorldTotalTime(worldTime); } - /**+ - * Called when an entity is spawned in the world. This includes - * players. + /** + * + Sets the world time. + */ + public void setWorldTime(long time) { + this.worldInfo.setWorldTime(time); + } + + /** + * + Called when an entity is spawned in the world. This includes players. */ public boolean spawnEntityInWorld(Entity entityIn) { int i = MathHelper.floor_double(entityIn.posX / 16.0D); @@ -972,385 +2800,82 @@ public abstract class World implements IBlockAccess { } } - protected void onEntityAdded(Entity entityIn) { + public void spawnParticle(EnumParticleTypes particleType, boolean xCoord, double yCoord, double zCoord, + double xOffset, double yOffset, double zOffset, double parDouble6, int... parArrayOfInt) { + this.spawnParticle(particleType.getParticleID(), particleType.getShouldIgnoreRange() | xCoord, yCoord, zCoord, + xOffset, yOffset, zOffset, parDouble6, parArrayOfInt); + } + + public void spawnParticle(EnumParticleTypes particleType, double xCoord, double yCoord, double zCoord, + double xOffset, double yOffset, double zOffset, int... parArrayOfInt) { + this.spawnParticle(particleType.getParticleID(), particleType.getShouldIgnoreRange(), xCoord, yCoord, zCoord, + xOffset, yOffset, zOffset, parArrayOfInt); + } + + private void spawnParticle(int particleID, boolean xCood, double yCoord, double zCoord, double xOffset, + double yOffset, double zOffset, double parDouble6, int... parArrayOfInt) { for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).onEntityAdded(entityIn); + ((IWorldAccess) this.worldAccesses.get(i)).spawnParticle(particleID, xCood, yCoord, zCoord, xOffset, + yOffset, zOffset, parDouble6, parArrayOfInt); } } - protected void onEntityRemoved(Entity entityIn) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).onEntityRemoved(entityIn); - } - - } - - /**+ - * Schedule the entity for removal during the next tick. Marks - * the entity dead in anticipation. + /** + * + Runs a single tick for the world */ - public void removeEntity(Entity entityIn) { - if (entityIn.riddenByEntity != null) { - entityIn.riddenByEntity.mountEntity((Entity) null); - } - - if (entityIn.ridingEntity != null) { - entityIn.mountEntity((Entity) null); - } - - entityIn.setDead(); - if (entityIn instanceof EntityPlayer) { - this.playerEntities.remove(entityIn); - this.updateAllPlayersSleepingFlag(); - this.onEntityRemoved(entityIn); - } - + public void tick() { + this.updateWeather(); } - /**+ - * Do NOT use this method to remove normal entities- use normal - * removeEntity + /** + * + Runs through the list of updates to run and ticks them */ - public void removePlayerEntityDangerously(Entity entityIn) { - entityIn.setDead(); - if (entityIn instanceof EntityPlayer) { - this.playerEntities.remove(entityIn); - this.updateAllPlayersSleepingFlag(); - } - - int i = entityIn.chunkCoordX; - int j = entityIn.chunkCoordZ; - if (entityIn.addedToChunk && this.isChunkLoaded(i, j, true)) { - this.getChunkFromChunkCoords(i, j).removeEntity(entityIn); - } - - this.loadedEntityList.remove(entityIn); - this.onEntityRemoved(entityIn); + public boolean tickUpdates(boolean parFlag) { + return false; } - /**+ - * Adds a IWorldAccess to the list of worldAccesses + public void unloadEntities(Collection entityCollection) { + this.unloadedEntityList.addAll(entityCollection); + } + + /** + * + Updates the flag that indicates whether or not all players in the world are + * sleeping. */ - public void addWorldAccess(IWorldAccess worldAccess) { - this.worldAccesses.add(worldAccess); + public void updateAllPlayersSleepingFlag() { } - /**+ - * Removes a worldAccess from the worldAccesses object - */ - public void removeWorldAccess(IWorldAccess worldAccess) { - this.worldAccesses.remove(worldAccess); - } - - /**+ - * Returns a list of bounding boxes that collide with aabb - * excluding the passed in entity's collision. Args: entity, - * aabb - */ - public List getCollidingBoundingBoxes(Entity entityIn, AxisAlignedBB bb) { - ArrayList arraylist = Lists.newArrayList(); - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX + 1.0D); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY + 1.0D); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); - WorldBorder worldborder = this.getWorldBorder(); - boolean flag = entityIn.isOutsideBorder(); - boolean flag1 = this.isInsideBorder(worldborder, entityIn); - IBlockState iblockstate = Blocks.stone.getDefaultState(); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = i1; l1 < j1; ++l1) { - if (this.isBlockLoaded(blockpos$mutableblockpos.func_181079_c(k1, 64, l1))) { - for (int i2 = k - 1; i2 < l; ++i2) { - blockpos$mutableblockpos.func_181079_c(k1, i2, l1); - if (flag && flag1) { - entityIn.setOutsideBorder(false); - } else if (!flag && !flag1) { - entityIn.setOutsideBorder(true); - } - - IBlockState iblockstate1 = iblockstate; - if (worldborder.contains((BlockPos) blockpos$mutableblockpos) || !flag1) { - iblockstate1 = this.getBlockState(blockpos$mutableblockpos); - } - - iblockstate1.getBlock().addCollisionBoxesToList(this, blockpos$mutableblockpos, iblockstate1, - bb, arraylist, entityIn); - } - } - } - } - - double d0 = 0.25D; - List list = this.getEntitiesWithinAABBExcludingEntity(entityIn, bb.expand(d0, d0, d0)); - - for (int j2 = 0; j2 < list.size(); ++j2) { - if (entityIn.riddenByEntity != list && entityIn.ridingEntity != list) { - AxisAlignedBB axisalignedbb = ((Entity) list.get(j2)).getCollisionBoundingBox(); - if (axisalignedbb != null && axisalignedbb.intersectsWith(bb)) { - arraylist.add(axisalignedbb); - } - - axisalignedbb = entityIn.getCollisionBox((Entity) list.get(j2)); - if (axisalignedbb != null && axisalignedbb.intersectsWith(bb)) { - arraylist.add(axisalignedbb); - } - } - } - - return arraylist; - } - - public boolean isInsideBorder(WorldBorder worldBorderIn, Entity entityIn) { - double d0 = worldBorderIn.minX(); - double d1 = worldBorderIn.minZ(); - double d2 = worldBorderIn.maxX(); - double d3 = worldBorderIn.maxZ(); - if (entityIn.isOutsideBorder()) { - ++d0; - ++d1; - --d2; - --d3; - } else { - --d0; - --d1; - ++d2; - ++d3; - } - - return entityIn.posX > d0 && entityIn.posX < d2 && entityIn.posZ > d1 && entityIn.posZ < d3; - } - - public List func_147461_a(AxisAlignedBB bb) { - ArrayList arraylist = Lists.newArrayList(); - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX + 1.0D); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY + 1.0D); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = i1; l1 < j1; ++l1) { - if (this.isBlockLoaded(blockpos$mutableblockpos.func_181079_c(k1, 64, l1))) { - for (int i2 = k - 1; i2 < l; ++i2) { - blockpos$mutableblockpos.func_181079_c(k1, i2, l1); - IBlockState iblockstate; - if (k1 >= -30000000 && k1 < 30000000 && l1 >= -30000000 && l1 < 30000000) { - iblockstate = this.getBlockState(blockpos$mutableblockpos); - } else { - iblockstate = Blocks.bedrock.getDefaultState(); - } - - iblockstate.getBlock().addCollisionBoxesToList(this, blockpos$mutableblockpos, iblockstate, bb, - arraylist, (Entity) null); - } - } - } - } - - return arraylist; - } - - /**+ - * Returns the amount of skylight subtracted for the current - * time - */ - public int calculateSkylightSubtracted(float parFloat1) { - float f = this.getCelestialAngle(parFloat1); - float f1 = 1.0F - (MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.5F); - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - f1 = 1.0F - f1; - f1 = (float) ((double) f1 * (1.0D - (double) (this.getRainStrength(parFloat1) * 5.0F) / 16.0D)); - f1 = (float) ((double) f1 * (1.0D - (double) (this.getThunderStrength(parFloat1) * 5.0F) / 16.0D)); - f1 = 1.0F - f1; - return (int) (f1 * 11.0F); - } - - /**+ - * Returns the sun brightness - checks time of day, rain and - * thunder - */ - public float getSunBrightness(float parFloat1) { - float f = this.getCelestialAngle(parFloat1); - float f1 = 1.0F - (MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.2F); - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - f1 = 1.0F - f1; - f1 = (float) ((double) f1 * (1.0D - (double) (this.getRainStrength(parFloat1) * 5.0F) / 16.0D)); - f1 = (float) ((double) f1 * (1.0D - (double) (this.getThunderStrength(parFloat1) * 5.0F) / 16.0D)); - return f1 * 0.8F + 0.2F; - } - - /**+ - * Calculates the color for the skybox - */ - public Vec3 getSkyColor(Entity entityIn, float partialTicks) { - float f = this.getCelestialAngle(partialTicks); - float f1 = MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.5F; - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - int i = MathHelper.floor_double(entityIn.posX); - int j = MathHelper.floor_double(entityIn.posY); - int k = MathHelper.floor_double(entityIn.posZ); - BlockPos blockpos = new BlockPos(i, j, k); - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(blockpos); - float f2 = biomegenbase.getFloatTemperature(blockpos); - int l = biomegenbase.getSkyColorByTemp(f2); - float f3 = (float) (l >> 16 & 255) / 255.0F; - float f4 = (float) (l >> 8 & 255) / 255.0F; - float f5 = (float) (l & 255) / 255.0F; - f3 = f3 * f1; - f4 = f4 * f1; - f5 = f5 * f1; - float f6 = this.getRainStrength(partialTicks); - if (f6 > 0.0F) { - float f7 = (f3 * 0.3F + f4 * 0.59F + f5 * 0.11F) * 0.6F; - float f8 = 1.0F - f6 * 0.75F; - f3 = f3 * f8 + f7 * (1.0F - f8); - f4 = f4 * f8 + f7 * (1.0F - f8); - f5 = f5 * f8 + f7 * (1.0F - f8); - } - - float f10 = this.getThunderStrength(partialTicks); - if (f10 > 0.0F) { - float f11 = (f3 * 0.3F + f4 * 0.59F + f5 * 0.11F) * 0.2F; - float f9 = 1.0F - f10 * 0.75F; - f3 = f3 * f9 + f11 * (1.0F - f9); - f4 = f4 * f9 + f11 * (1.0F - f9); - f5 = f5 * f9 + f11 * (1.0F - f9); - } - - if (this.lastLightningBolt > 0) { - float f12 = (float) this.lastLightningBolt - partialTicks; - if (f12 > 1.0F) { - f12 = 1.0F; - } - - f12 = f12 * 0.45F; - f3 = f3 * (1.0F - f12) + 0.8F * f12; - f4 = f4 * (1.0F - f12) + 0.8F * f12; - f5 = f5 * (1.0F - f12) + 1.0F * f12; - } - - return new Vec3((double) f3, (double) f4, (double) f5); - } - - /**+ - * calls calculateCelestialAngle - */ - public float getCelestialAngle(float partialTicks) { - return this.provider.calculateCelestialAngle(this.worldInfo.getWorldTime(), partialTicks); - } - - public int getMoonPhase() { - return this.provider.getMoonPhase(this.worldInfo.getWorldTime()); - } - - /**+ - * gets the current fullness of the moon expressed as a float - * between 1.0 and 0.0, in steps of .25 - */ - public float getCurrentMoonPhaseFactor() { - return WorldProvider.moonPhaseFactors[this.provider.getMoonPhase(this.worldInfo.getWorldTime())]; - } - - /**+ - * Return getCelestialAngle()*2*PI - */ - public float getCelestialAngleRadians(float partialTicks) { - float f = this.getCelestialAngle(partialTicks); - return f * 3.1415927F * 2.0F; - } - - public Vec3 getCloudColour(float partialTicks) { - float f = this.getCelestialAngle(partialTicks); - float f1 = MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.5F; - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - float f2 = (float) (this.cloudColour >> 16 & 255L) / 255.0F; - float f3 = (float) (this.cloudColour >> 8 & 255L) / 255.0F; - float f4 = (float) (this.cloudColour & 255L) / 255.0F; - float f5 = this.getRainStrength(partialTicks); - if (f5 > 0.0F) { - float f6 = (f2 * 0.3F + f3 * 0.59F + f4 * 0.11F) * 0.6F; - float f7 = 1.0F - f5 * 0.95F; - f2 = f2 * f7 + f6 * (1.0F - f7); - f3 = f3 * f7 + f6 * (1.0F - f7); - f4 = f4 * f7 + f6 * (1.0F - f7); - } - - f2 = f2 * (f1 * 0.9F + 0.1F); - f3 = f3 * (f1 * 0.9F + 0.1F); - f4 = f4 * (f1 * 0.85F + 0.15F); - float f9 = this.getThunderStrength(partialTicks); - if (f9 > 0.0F) { - float f10 = (f2 * 0.3F + f3 * 0.59F + f4 * 0.11F) * 0.2F; - float f8 = 1.0F - f9 * 0.95F; - f2 = f2 * f8 + f10 * (1.0F - f8); - f3 = f3 * f8 + f10 * (1.0F - f8); - f4 = f4 * f8 + f10 * (1.0F - f8); - } - - return new Vec3((double) f2, (double) f3, (double) f4); - } - - /**+ - * Returns vector(ish) with R/G/B for fog - */ - public Vec3 getFogColor(float partialTicks) { - float f = this.getCelestialAngle(partialTicks); - return this.provider.getFogColor(f, partialTicks); - } - - public BlockPos getPrecipitationHeight(BlockPos pos) { - return this.getChunkFromBlockCoords(pos).getPrecipitationHeight(pos); - } - - /**+ - * Finds the highest block on the x and z coordinate that is - * solid or liquid, and returns its y coord. - */ - public BlockPos getTopSolidOrLiquidBlock(BlockPos pos) { - Chunk chunk = this.getChunkFromBlockCoords(pos); - - BlockPos blockpos; - BlockPos blockpos1; - for (blockpos = new BlockPos(pos.getX(), chunk.getTopFilledSegment() + 16, pos.getZ()); blockpos - .getY() >= 0; blockpos = blockpos1) { - blockpos1 = blockpos.down(); - Material material = chunk.getBlock(blockpos1).getMaterial(); - if (material.blocksMovement() && material != Material.leaves) { - break; - } - } - - return blockpos; - } - - /**+ - * How bright are stars in the sky - */ - public float getStarBrightness(float partialTicks) { - float f = this.getCelestialAngle(partialTicks); - float f1 = 1.0F - (MathHelper.cos(f * 3.1415927F * 2.0F) * 2.0F + 0.25F); - f1 = MathHelper.clamp_float(f1, 0.0F, 1.0F); - return f1 * f1 * 0.5F; - } - - public void scheduleUpdate(BlockPos pos, Block blockIn, int delay) { + protected void updateBlocks() { + this.setActivePlayerChunksAndCheckLight(); } public void updateBlockTick(BlockPos pos, Block blockIn, int delay, int priority) { } - public void scheduleBlockUpdate(BlockPos pos, Block blockIn, int delay, int priority) { + public void updateComparatorOutputLevel(BlockPos pos, Block blockIn) { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + BlockPos blockpos = pos.offset(enumfacing); + if (this.isBlockLoaded(blockpos)) { + IBlockState iblockstate = this.getBlockState(blockpos); + if (Blocks.unpowered_comparator.isAssociated(iblockstate.getBlock())) { + iblockstate.getBlock().onNeighborBlockChange(this, blockpos, iblockstate, blockIn); + } else if (iblockstate.getBlock().isNormalCube()) { + blockpos = blockpos.offset(enumfacing); + iblockstate = this.getBlockState(blockpos); + if (Blocks.unpowered_comparator.isAssociated(iblockstate.getBlock())) { + iblockstate.getBlock().onNeighborBlockChange(this, blockpos, iblockstate, blockIn); + } + } + } + } + } - /**+ - * Updates (and cleans up) entities and tile entities + /** + * + Updates (and cleans up) entities and tile entities */ public void updateEntities() { for (int i = 0; i < this.weatherEffects.size(); ++i) { @@ -1486,41 +3011,17 @@ public abstract class World implements IBlockAccess { } - public boolean addTileEntity(TileEntity tile) { - boolean flag = this.loadedTileEntityList.add(tile); - if (flag && tile instanceof ITickable) { - this.tickableTileEntities.add(tile); - } - - return flag; - } - - public void addTileEntities(Collection tileEntityCollection) { - if (this.processingLoadedTiles) { - this.addedTileEntityList.addAll(tileEntityCollection); - } else { - for (TileEntity tileentity : tileEntityCollection) { - this.loadedTileEntityList.add(tileentity); - if (tileentity instanceof ITickable) { - this.tickableTileEntities.add(tileentity); - } - } - } - - } - - /**+ - * Will update the entity in the world if the chunk the entity - * is in is currently loaded. Args: entity + /** + * + Will update the entity in the world if the chunk the entity is in is + * currently loaded. Args: entity */ public void updateEntity(Entity ent) { this.updateEntityWithOptionalForce(ent, true); } - /**+ - * Will update the entity in the world if the chunk the entity - * is in is currently loaded or its forced to update. Args: - * entity, forceUpdate + /** + * + Will update the entity in the world if the chunk the entity is in is + * currently loaded or its forced to update. Args: entity, forceUpdate */ public void updateEntityWithOptionalForce(Entity entityIn, boolean forceUpdate) { int i = MathHelper.floor_double(entityIn.posX); @@ -1591,466 +3092,8 @@ public abstract class World implements IBlockAccess { } } - /**+ - * Returns true if there are no solid, live entities in the - * specified AxisAlignedBB, excluding the given entity - */ - public boolean checkNoEntityCollision(AxisAlignedBB bb) { - return this.checkNoEntityCollision(bb, (Entity) null); - } - - /**+ - * Returns true if there are no solid, live entities in the - * specified AxisAlignedBB, excluding the given entity - */ - public boolean checkNoEntityCollision(AxisAlignedBB bb, Entity entityIn) { - List list = this.getEntitiesWithinAABBExcludingEntity((Entity) null, bb); - - for (int i = 0; i < list.size(); ++i) { - Entity entity = (Entity) list.get(i); - if (!entity.isDead && entity.preventEntitySpawning && entity != entityIn - && (entityIn == null || entityIn.ridingEntity != entity && entityIn.riddenByEntity != entity)) { - return false; - } - } - - return true; - } - - /**+ - * Returns true if there are any blocks in the region - * constrained by an AxisAlignedBB - */ - public boolean checkBlockCollision(AxisAlignedBB bb) { - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 <= j; ++k1) { - for (int l1 = k; l1 <= l; ++l1) { - for (int i2 = i1; i2 <= j1; ++i2) { - Block block = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock(); - if (block.getMaterial() != Material.air) { - return true; - } - } - } - } - - return false; - } - - /**+ - * Returns if any of the blocks within the aabb are liquids. - * Args: aabb - */ - public boolean isAnyLiquid(AxisAlignedBB bb) { - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 <= j; ++k1) { - for (int l1 = k; l1 <= l; ++l1) { - for (int i2 = i1; i2 <= j1; ++i2) { - Block block = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock(); - if (block.getMaterial().isLiquid()) { - return true; - } - } - } - } - - return false; - } - - public boolean isFlammableWithin(AxisAlignedBB bb) { - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX + 1.0D); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY + 1.0D); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); - if (this.isAreaLoaded(i, k, i1, j, l, j1, true)) { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = k; l1 < l; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - Block block = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock(); - if (block == Blocks.fire || block == Blocks.flowing_lava || block == Blocks.lava) { - return true; - } - } - } - } - } - - return false; - } - - /**+ - * handles the acceleration of an object whilst in water. Not - * sure if it is used elsewhere. - */ - public boolean handleMaterialAcceleration(AxisAlignedBB bb, Material materialIn, Entity entityIn) { - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX + 1.0D); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY + 1.0D); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); - if (!this.isAreaLoaded(i, k, i1, j, l, j1, true)) { - return false; - } else { - boolean flag = false; - Vec3 vec3 = new Vec3(0.0D, 0.0D, 0.0D); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = k; l1 < l; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - blockpos$mutableblockpos.func_181079_c(k1, l1, i2); - IBlockState iblockstate = this.getBlockState(blockpos$mutableblockpos); - Block block = iblockstate.getBlock(); - if (block.getMaterial() == materialIn) { - double d0 = (double) ((float) (l1 + 1) - BlockLiquid.getLiquidHeightPercent( - ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue())); - if ((double) l >= d0) { - flag = true; - vec3 = block.modifyAcceleration(this, blockpos$mutableblockpos, entityIn, vec3); - } - } - } - } - } - - if (vec3.lengthVector() > 0.0D && entityIn.isPushedByWater()) { - vec3 = vec3.normalize(); - double d1 = 0.014D; - entityIn.motionX += vec3.xCoord * d1; - entityIn.motionY += vec3.yCoord * d1; - entityIn.motionZ += vec3.zCoord * d1; - } - - return flag; - } - } - - /**+ - * Returns true if the given bounding box contains the given - * material - */ - public boolean isMaterialInBB(AxisAlignedBB bb, Material materialIn) { - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX + 1.0D); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY + 1.0D); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = k; l1 < l; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - if (this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)).getBlock() - .getMaterial() == materialIn) { - return true; - } - } - } - } - - return false; - } - - /**+ - * checks if the given AABB is in the material given. Used while - * swimming. - */ - public boolean isAABBInMaterial(AxisAlignedBB bb, Material materialIn) { - int i = MathHelper.floor_double(bb.minX); - int j = MathHelper.floor_double(bb.maxX + 1.0D); - int k = MathHelper.floor_double(bb.minY); - int l = MathHelper.floor_double(bb.maxY + 1.0D); - int i1 = MathHelper.floor_double(bb.minZ); - int j1 = MathHelper.floor_double(bb.maxZ + 1.0D); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 < j; ++k1) { - for (int l1 = k; l1 < l; ++l1) { - for (int i2 = i1; i2 < j1; ++i2) { - IBlockState iblockstate = this.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, l1, i2)); - Block block = iblockstate.getBlock(); - if (block.getMaterial() == materialIn) { - int j2 = ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue(); - double d0 = (double) (l1 + 1); - if (j2 < 8) { - d0 = (double) (l1 + 1) - (double) j2 / 8.0D; - } - - if (d0 >= bb.minY) { - return true; - } - } - } - } - } - - return false; - } - - /**+ - * Creates an explosion. Args: entity, x, y, z, strength - */ - public Explosion createExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isSmoking) { - return this.newExplosion(entityIn, x, y, z, strength, false, isSmoking); - } - - /**+ - * returns a new explosion. Does initiation (at time of writing - * Explosion is not finished) - */ - public Explosion newExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, - boolean isSmoking) { - Explosion explosion = new Explosion(this, entityIn, x, y, z, strength, isFlaming, isSmoking); - explosion.doExplosionA(); - explosion.doExplosionB(true); - return explosion; - } - - /**+ - * Gets the percentage of real blocks within within a bounding - * box, along a specified vector. - */ - public float getBlockDensity(Vec3 vec, AxisAlignedBB bb) { - double d0 = 1.0D / ((bb.maxX - bb.minX) * 2.0D + 1.0D); - double d1 = 1.0D / ((bb.maxY - bb.minY) * 2.0D + 1.0D); - double d2 = 1.0D / ((bb.maxZ - bb.minZ) * 2.0D + 1.0D); - double d3 = (1.0D - Math.floor(1.0D / d0) * d0) / 2.0D; - double d4 = (1.0D - Math.floor(1.0D / d2) * d2) / 2.0D; - if (d0 >= 0.0D && d1 >= 0.0D && d2 >= 0.0D) { - int i = 0; - int j = 0; - - for (float f = 0.0F; f <= 1.0F; f = (float) ((double) f + d0)) { - for (float f1 = 0.0F; f1 <= 1.0F; f1 = (float) ((double) f1 + d1)) { - for (float f2 = 0.0F; f2 <= 1.0F; f2 = (float) ((double) f2 + d2)) { - double d5 = bb.minX + (bb.maxX - bb.minX) * (double) f; - double d6 = bb.minY + (bb.maxY - bb.minY) * (double) f1; - double d7 = bb.minZ + (bb.maxZ - bb.minZ) * (double) f2; - if (this.rayTraceBlocks(new Vec3(d5 + d3, d6, d7 + d4), vec) == null) { - ++i; - } - - ++j; - } - } - } - - return (float) i / (float) j; - } else { - return 0.0F; - } - } - - /**+ - * Attempts to extinguish a fire - */ - public boolean extinguishFire(EntityPlayer player, BlockPos pos, EnumFacing side) { - pos = pos.offset(side); - if (this.getBlockState(pos).getBlock() == Blocks.fire) { - this.playAuxSFXAtEntity(player, 1004, pos, 0); - this.setBlockToAir(pos); - return true; - } else { - return false; - } - } - - /**+ - * This string is 'All: (number of loaded entities)' Viewable by - * press ing F3 - */ - public String getDebugLoadedEntities() { - return "All: " + this.loadedEntityList.size(); - } - - /**+ - * Returns the name of the current chunk provider, by calling - * chunkprovider.makeString() - */ - public String getProviderName() { - return this.chunkProvider.makeString(); - } - - public TileEntity getTileEntity(BlockPos pos) { - if (!this.isValid(pos)) { - return null; - } else { - TileEntity tileentity = null; - if (this.processingLoadedTiles) { - for (int i = 0; i < this.addedTileEntityList.size(); ++i) { - TileEntity tileentity1 = (TileEntity) this.addedTileEntityList.get(i); - if (!tileentity1.isInvalid() && tileentity1.getPos().equals(pos)) { - tileentity = tileentity1; - break; - } - } - } - - if (tileentity == null) { - tileentity = this.getChunkFromBlockCoords(pos).getTileEntity(pos, Chunk.EnumCreateEntityType.IMMEDIATE); - } - - if (tileentity == null) { - for (int j = 0; j < this.addedTileEntityList.size(); ++j) { - TileEntity tileentity2 = (TileEntity) this.addedTileEntityList.get(j); - if (!tileentity2.isInvalid() && tileentity2.getPos().equals(pos)) { - tileentity = tileentity2; - break; - } - } - } - - return tileentity; - } - } - - public void setTileEntity(BlockPos pos, TileEntity tileEntityIn) { - if (tileEntityIn != null && !tileEntityIn.isInvalid()) { - if (this.processingLoadedTiles) { - tileEntityIn.setPos(pos); - Iterator iterator = this.addedTileEntityList.iterator(); - - while (iterator.hasNext()) { - TileEntity tileentity = (TileEntity) iterator.next(); - if (tileentity.getPos().equals(pos)) { - tileentity.invalidate(); - iterator.remove(); - } - } - - this.addedTileEntityList.add(tileEntityIn); - } else { - this.addTileEntity(tileEntityIn); - this.getChunkFromBlockCoords(pos).addTileEntity(pos, tileEntityIn); - } - } - - } - - public void removeTileEntity(BlockPos pos) { - TileEntity tileentity = this.getTileEntity(pos); - if (tileentity != null && this.processingLoadedTiles) { - tileentity.invalidate(); - this.addedTileEntityList.remove(tileentity); - } else { - if (tileentity != null) { - this.addedTileEntityList.remove(tileentity); - this.loadedTileEntityList.remove(tileentity); - this.tickableTileEntities.remove(tileentity); - } - - this.getChunkFromBlockCoords(pos).removeTileEntity(pos); - } - - } - - /**+ - * Adds the specified TileEntity to the pending removal list. - */ - public void markTileEntityForRemoval(TileEntity tileEntityIn) { - this.tileEntitiesToBeRemoved.add(tileEntityIn); - } - - public boolean isBlockFullCube(BlockPos pos) { - IBlockState iblockstate = this.getBlockState(pos); - AxisAlignedBB axisalignedbb = iblockstate.getBlock().getCollisionBoundingBox(this, pos, iblockstate); - return axisalignedbb != null && axisalignedbb.getAverageEdgeLength() >= 1.0D; - } - - public static boolean doesBlockHaveSolidTopSurface(IBlockAccess blockAccess, BlockPos pos) { - IBlockState iblockstate = blockAccess.getBlockState(pos); - Block block = iblockstate.getBlock(); - return block.getMaterial().isOpaque() && block.isFullCube() ? true - : (block instanceof BlockStairs ? iblockstate.getValue(BlockStairs.HALF) == BlockStairs.EnumHalf.TOP - : (block instanceof BlockSlab - ? iblockstate.getValue(BlockSlab.HALF) == BlockSlab.EnumBlockHalf.TOP - : (block instanceof BlockHopper ? true - : (block instanceof BlockSnow - ? ((Integer) iblockstate.getValue(BlockSnow.LAYERS)).intValue() == 7 - : false)))); - } - - /**+ - * Checks if a block's material is opaque, and that it takes up - * a full cube - */ - public boolean isBlockNormalCube(BlockPos pos, boolean _default) { - if (!this.isValid(pos)) { - return _default; - } else { - Chunk chunk = this.chunkProvider.provideChunk(pos); - if (chunk.isEmpty()) { - return _default; - } else { - Block block = this.getBlockState(pos).getBlock(); - return block.getMaterial().isOpaque() && block.isFullCube(); - } - } - } - - /**+ - * Called on construction of the World class to setup the - * initial skylight values - */ - public void calculateInitialSkylight() { - int i = this.calculateSkylightSubtracted(1.0F); - if (i != this.skylightSubtracted) { - this.skylightSubtracted = i; - } - - } - - /**+ - * first boolean for hostile mobs and second for peaceful mobs - */ - public void setAllowedSpawnTypes(boolean hostile, boolean peaceful) { - this.spawnHostileMobs = hostile; - this.spawnPeacefulMobs = peaceful; - } - - /**+ - * Runs a single tick for the world - */ - public void tick() { - this.updateWeather(); - } - - /**+ - * Called from World constructor to set rainingStrength and - * thunderingStrength - */ - protected void calculateInitialWeather() { - if (this.worldInfo.isRaining()) { - this.rainingStrength = 1.0F; - if (this.worldInfo.isThundering()) { - this.thunderingStrength = 1.0F; - } - } - - } - - /**+ - * Updates all weather states. + /** + * + Updates all weather states. */ protected void updateWeather() { if (!this.provider.getHasNoSky() && this.getGameRules().getBoolean("doWeatherCycle")) { @@ -2112,1075 +3155,4 @@ public abstract class World implements IBlockAccess { } } } - - protected void setActivePlayerChunksAndCheckLight() { - this.activeChunkSet.clear(); - - for (int i = 0; i < this.playerEntities.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); - int j = MathHelper.floor_double(entityplayer.posX / 16.0D); - int k = MathHelper.floor_double(entityplayer.posZ / 16.0D); - int l = this.getRenderDistanceChunks(); - - for (int i1 = -l; i1 <= l; ++i1) { - for (int j1 = -l; j1 <= l; ++j1) { - this.activeChunkSet.add(new ChunkCoordIntPair(i1 + j, j1 + k)); - } - } - } - - if (this.ambientTickCountdown > 0) { - --this.ambientTickCountdown; - } - - if (!this.playerEntities.isEmpty()) { - int k1 = this.rand.nextInt(this.playerEntities.size()); - EntityPlayer entityplayer1 = (EntityPlayer) this.playerEntities.get(k1); - int l1 = MathHelper.floor_double(entityplayer1.posX) + this.rand.nextInt(11) - 5; - int i2 = MathHelper.floor_double(entityplayer1.posY) + this.rand.nextInt(11) - 5; - int j2 = MathHelper.floor_double(entityplayer1.posZ) + this.rand.nextInt(11) - 5; - this.checkLight(new BlockPos(l1, i2, j2)); - } - - } - - protected abstract int getRenderDistanceChunks(); - - protected void playMoodSoundAndCheckLight(int chunkIn, int parInt2, Chunk parChunk) { - if (this.ambientTickCountdown == 0 && !this.isRemote) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int i = this.updateLCG >> 2; - int j = i & 15; - int k = i >> 8 & 15; - int l = i >> 16 & 255; - BlockPos blockpos = new BlockPos(j, l, k); - Block block = parChunk.getBlock(blockpos); - j = j + chunkIn; - k = k + parInt2; - if (block.getMaterial() == Material.air && this.getLight(blockpos) <= this.rand.nextInt(8) - && this.getLightFor(EnumSkyBlock.SKY, blockpos) <= 0) { - EntityPlayer entityplayer = this.getClosestPlayer((double) j + 0.5D, (double) l + 0.5D, - (double) k + 0.5D, 8.0D); - if (entityplayer != null - && entityplayer.getDistanceSq((double) j + 0.5D, (double) l + 0.5D, (double) k + 0.5D) > 4.0D) { - this.playSoundEffect((double) j + 0.5D, (double) l + 0.5D, (double) k + 0.5D, "ambient.cave.cave", - 0.7F, 0.8F + this.rand.nextFloat() * 0.2F); - this.ambientTickCountdown = this.rand.nextInt(12000) + 6000; - } - } - } - - parChunk.enqueueRelightChecks(); - } - - protected void updateBlocks() { - this.setActivePlayerChunksAndCheckLight(); - } - - public void forceBlockUpdateTick(Block blockType, BlockPos pos, EaglercraftRandom random) { - this.scheduledUpdatesAreImmediate = true; - blockType.updateTick(this, pos, this.getBlockState(pos), random); - this.scheduledUpdatesAreImmediate = false; - } - - public boolean canBlockFreezeWater(BlockPos pos) { - return this.canBlockFreeze(pos, false); - } - - public boolean canBlockFreezeNoWater(BlockPos pos) { - return this.canBlockFreeze(pos, true); - } - - /**+ - * Checks to see if a given block is both water and cold enough - * to freeze. - */ - public boolean canBlockFreeze(BlockPos pos, boolean noWaterAdj) { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(pos); - float f = biomegenbase.getFloatTemperature(pos); - if (f > 0.15F) { - return false; - } else { - if (pos.getY() >= 0 && pos.getY() < 256 && this.getLightFor(EnumSkyBlock.BLOCK, pos) < 10) { - IBlockState iblockstate = this.getBlockState(pos); - Block block = iblockstate.getBlock(); - if ((block == Blocks.water || block == Blocks.flowing_water) - && ((Integer) iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) { - if (!noWaterAdj) { - return true; - } - - boolean flag = this.isWater(pos.west()) && this.isWater(pos.east()) && this.isWater(pos.north()) - && this.isWater(pos.south()); - if (!flag) { - return true; - } - } - } - - return false; - } - } - - private boolean isWater(BlockPos pos) { - return this.getBlockState(pos).getBlock().getMaterial() == Material.water; - } - - /**+ - * Checks to see if a given block can accumulate snow from it - * snowing - */ - public boolean canSnowAt(BlockPos pos, boolean checkLight) { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(pos); - float f = biomegenbase.getFloatTemperature(pos); - if (f > 0.15F) { - return false; - } else if (!checkLight) { - return true; - } else { - if (pos.getY() >= 0 && pos.getY() < 256 && this.getLightFor(EnumSkyBlock.BLOCK, pos) < 10) { - Block block = this.getBlockState(pos).getBlock(); - if (block.getMaterial() == Material.air && Blocks.snow_layer.canPlaceBlockAt(this, pos)) { - return true; - } - } - - return false; - } - } - - public boolean checkLight(BlockPos pos) { - boolean flag = false; - if (!this.provider.getHasNoSky()) { - flag |= this.checkLightFor(EnumSkyBlock.SKY, pos); - } - - flag = flag | this.checkLightFor(EnumSkyBlock.BLOCK, pos); - return flag; - } - - /**+ - * gets the light level at the supplied position - */ - private int getRawLight(BlockPos pos, EnumSkyBlock lightType) { - if (lightType == EnumSkyBlock.SKY && this.canSeeSky(pos)) { - return 15; - } else { - Block block = this.getBlockState(pos).getBlock(); - int i = lightType == EnumSkyBlock.SKY ? 0 : block.getLightValue(); - int j = block.getLightOpacity(); - if (j >= 15 && block.getLightValue() > 0) { - j = 1; - } - - if (j < 1) { - j = 1; - } - - if (j >= 15) { - return 0; - } else if (i >= 14) { - return i; - } else { - EnumFacing[] facings = EnumFacing._VALUES; - for (int m = 0; m < facings.length; ++m) { - EnumFacing enumfacing = facings[m]; - BlockPos blockpos = pos.offset(enumfacing); - int k = this.getLightFor(lightType, blockpos) - j; - if (k > i) { - i = k; - } - - if (i >= 14) { - return i; - } - } - - return i; - } - } - } - - public boolean checkLightFor(EnumSkyBlock lightType, BlockPos pos) { - if (!this.isAreaLoaded(pos, 17, false)) { - return false; - } else { - int i = 0; - int j = 0; - int k = this.getLightFor(lightType, pos); - int l = this.getRawLight(pos, lightType); - int i1 = pos.getX(); - int j1 = pos.getY(); - int k1 = pos.getZ(); - if (l > k) { - this.lightUpdateBlockList[j++] = 133152; - } else if (l < k) { - this.lightUpdateBlockList[j++] = 133152 | k << 18; - - while (i < j) { - int l1 = this.lightUpdateBlockList[i++]; - int i2 = (l1 & 63) - 32 + i1; - int j2 = (l1 >> 6 & 63) - 32 + j1; - int k2 = (l1 >> 12 & 63) - 32 + k1; - int l2 = l1 >> 18 & 15; - BlockPos blockpos = new BlockPos(i2, j2, k2); - int i3 = this.getLightFor(lightType, blockpos); - if (i3 == l2) { - this.setLightFor(lightType, blockpos, 0); - if (l2 > 0) { - int j3 = MathHelper.abs_int(i2 - i1); - int k3 = MathHelper.abs_int(j2 - j1); - int l3 = MathHelper.abs_int(k2 - k1); - if (j3 + k3 + l3 < 17) { - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - EnumFacing[] facings = EnumFacing._VALUES; - for (int m = 0; m < facings.length; ++m) { - EnumFacing enumfacing = facings[m]; - int i4 = i2 + enumfacing.getFrontOffsetX(); - int j4 = j2 + enumfacing.getFrontOffsetY(); - int k4 = k2 + enumfacing.getFrontOffsetZ(); - blockpos$mutableblockpos.func_181079_c(i4, j4, k4); - int l4 = Math.max(1, - this.getBlockState(blockpos$mutableblockpos).getBlock().getLightOpacity()); - i3 = this.getLightFor(lightType, blockpos$mutableblockpos); - if (i3 == l2 - l4 && j < this.lightUpdateBlockList.length) { - this.lightUpdateBlockList[j++] = i4 - i1 + 32 | j4 - j1 + 32 << 6 - | k4 - k1 + 32 << 12 | l2 - l4 << 18; - } - } - } - } - } - } - - i = 0; - } - - while (i < j) { - int i5 = this.lightUpdateBlockList[i++]; - int j5 = (i5 & 63) - 32 + i1; - int k5 = (i5 >> 6 & 63) - 32 + j1; - int l5 = (i5 >> 12 & 63) - 32 + k1; - BlockPos blockpos1 = new BlockPos(j5, k5, l5); - int i6 = this.getLightFor(lightType, blockpos1); - int j6 = this.getRawLight(blockpos1, lightType); - if (j6 != i6) { - this.setLightFor(lightType, blockpos1, j6); - if (j6 > i6) { - int k6 = Math.abs(j5 - i1); - int l6 = Math.abs(k5 - j1); - int i7 = Math.abs(l5 - k1); - boolean flag = j < this.lightUpdateBlockList.length - 6; - if (k6 + l6 + i7 < 17 && flag) { - if (this.getLightFor(lightType, blockpos1.west()) < j6) { - this.lightUpdateBlockList[j++] = j5 - 1 - i1 + 32 + (k5 - j1 + 32 << 6) - + (l5 - k1 + 32 << 12); - } - - if (this.getLightFor(lightType, blockpos1.east()) < j6) { - this.lightUpdateBlockList[j++] = j5 + 1 - i1 + 32 + (k5 - j1 + 32 << 6) - + (l5 - k1 + 32 << 12); - } - - if (this.getLightFor(lightType, blockpos1.down()) < j6) { - this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 - 1 - j1 + 32 << 6) - + (l5 - k1 + 32 << 12); - } - - if (this.getLightFor(lightType, blockpos1.up()) < j6) { - this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 + 1 - j1 + 32 << 6) - + (l5 - k1 + 32 << 12); - } - - if (this.getLightFor(lightType, blockpos1.north()) < j6) { - this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 - j1 + 32 << 6) - + (l5 - 1 - k1 + 32 << 12); - } - - if (this.getLightFor(lightType, blockpos1.south()) < j6) { - this.lightUpdateBlockList[j++] = j5 - i1 + 32 + (k5 - j1 + 32 << 6) - + (l5 + 1 - k1 + 32 << 12); - } - } - } - } - } - - return true; - } - } - - /**+ - * Runs through the list of updates to run and ticks them - */ - public boolean tickUpdates(boolean parFlag) { - return false; - } - - public List getPendingBlockUpdates(Chunk chunkIn, boolean parFlag) { - return null; - } - - public List func_175712_a(StructureBoundingBox structureBB, boolean parFlag) { - return null; - } - - /**+ - * Will get all entities within the specified AABB excluding the - * one passed into it. Args: entityToExclude, aabb - */ - public List getEntitiesWithinAABBExcludingEntity(Entity entityIn, AxisAlignedBB bb) { - return this.getEntitiesInAABBexcluding(entityIn, bb, EntitySelectors.NOT_SPECTATING); - } - - /**+ - * Gets all entities within the specified AABB excluding the one - * passed into it. Args: entityToExclude, aabb, predicate - */ - public List getEntitiesInAABBexcluding(Entity entityIn, AxisAlignedBB boundingBox, - Predicate predicate) { - ArrayList arraylist = Lists.newArrayList(); - int i = MathHelper.floor_double((boundingBox.minX - 2.0D) / 16.0D); - int j = MathHelper.floor_double((boundingBox.maxX + 2.0D) / 16.0D); - int k = MathHelper.floor_double((boundingBox.minZ - 2.0D) / 16.0D); - int l = MathHelper.floor_double((boundingBox.maxZ + 2.0D) / 16.0D); - - for (int i1 = i; i1 <= j; ++i1) { - for (int j1 = k; j1 <= l; ++j1) { - if (this.isChunkLoaded(i1, j1, true)) { - this.getChunkFromChunkCoords(i1, j1).getEntitiesWithinAABBForEntity(entityIn, boundingBox, - arraylist, predicate); - } - } - } - - return arraylist; - } - - public List getEntities(Class entityType, Predicate filter) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = this.loadedEntityList.size(); i < l; ++i) { - Entity entity = this.loadedEntityList.get(i); - if (entityType.isAssignableFrom(entity.getClass()) && filter.apply((T) entity)) { - arraylist.add(entity); - } - } - - return arraylist; - } - - public List getPlayers(Class playerType, Predicate filter) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0, l = this.playerEntities.size(); i < l; ++i) { - Entity entity = this.playerEntities.get(i); - if (playerType.isAssignableFrom(entity.getClass()) && filter.apply((T) entity)) { - arraylist.add(entity); - } - } - - return arraylist; - } - - public List getEntitiesWithinAABB(Class classEntity, AxisAlignedBB bb) { - return this.getEntitiesWithinAABB(classEntity, bb, EntitySelectors.NOT_SPECTATING); - } - - public List getEntitiesWithinAABB(Class clazz, AxisAlignedBB aabb, - Predicate filter) { - int i = MathHelper.floor_double((aabb.minX - 2.0D) / 16.0D); - int j = MathHelper.floor_double((aabb.maxX + 2.0D) / 16.0D); - int k = MathHelper.floor_double((aabb.minZ - 2.0D) / 16.0D); - int l = MathHelper.floor_double((aabb.maxZ + 2.0D) / 16.0D); - ArrayList arraylist = Lists.newArrayList(); - - for (int i1 = i; i1 <= j; ++i1) { - for (int j1 = k; j1 <= l; ++j1) { - if (this.isChunkLoaded(i1, j1, true)) { - this.getChunkFromChunkCoords(i1, j1).getEntitiesOfTypeWithinAAAB(clazz, aabb, arraylist, filter); - } - } - } - - return arraylist; - } - - public T findNearestEntityWithinAABB(Class entityType, AxisAlignedBB aabb, - T closestTo) { - List list = this.getEntitiesWithinAABB(entityType, aabb); - Entity entity = null; - double d0 = Double.MAX_VALUE; - - for (int i = 0; i < list.size(); ++i) { - Entity entity1 = (Entity) list.get(i); - if (entity1 != closestTo && EntitySelectors.NOT_SPECTATING.apply(entity1)) { - double d1 = closestTo.getDistanceSqToEntity(entity1); - if (d1 <= d0) { - entity = entity1; - d0 = d1; - } - } - } - - return (T) entity; - } - - /**+ - * Returns the Entity with the given ID, or null if it doesn't - * exist in this World. - */ - public Entity getEntityByID(int id) { - return (Entity) this.entitiesById.lookup(id); - } - - /**+ - * Accessor for world Loaded Entity List - */ - public List getLoadedEntityList() { - return this.loadedEntityList; - } - - public void markChunkDirty(BlockPos pos, TileEntity unusedTileEntity) { - if (this.isBlockLoaded(pos)) { - this.getChunkFromBlockCoords(pos).setChunkModified(); - } - - } - - /**+ - * Counts how many entities of an entity class exist in the - * world. Args: entityClass - */ - public int countEntities(Class entityType) { - int i = 0; - - for (int j = 0, l = this.loadedEntityList.size(); j < l; ++j) { - Entity entity = this.loadedEntityList.get(j); - if ((!(entity instanceof EntityLiving) || !((EntityLiving) entity).isNoDespawnRequired()) - && entityType.isAssignableFrom(entity.getClass())) { - ++i; - } - } - - return i; - } - - public void loadEntities(Collection entityCollection) { - this.loadedEntityList.addAll(entityCollection); - - for (Entity entity : entityCollection) { - this.onEntityAdded(entity); - } - - } - - public void unloadEntities(Collection entityCollection) { - this.unloadedEntityList.addAll(entityCollection); - } - - public boolean canBlockBePlaced(Block blockIn, BlockPos pos, boolean side, EnumFacing entityIn, Entity itemStackIn, - ItemStack parItemStack) { - Block block = this.getBlockState(pos).getBlock(); - AxisAlignedBB axisalignedbb = side ? null - : blockIn.getCollisionBoundingBox(this, pos, blockIn.getDefaultState()); - return axisalignedbb != null && !this.checkNoEntityCollision(axisalignedbb, itemStackIn) ? false - : (block.getMaterial() == Material.circuits && blockIn == Blocks.anvil ? true - : block.getMaterial().isReplaceable() && blockIn.canReplace(this, pos, entityIn, parItemStack)); - } - - public int func_181545_F() { - return this.field_181546_a; - } - - public void func_181544_b(int parInt1) { - this.field_181546_a = parInt1; - } - - /**+ - * Returns the single highest strong power out of all directions - * using getStrongPower(BlockPos, EnumFacing) - */ - public int getStrongPower(BlockPos pos, EnumFacing direction) { - IBlockState iblockstate = this.getBlockState(pos); - return iblockstate.getBlock().getStrongPower(this, pos, iblockstate, direction); - } - - public WorldType getWorldType() { - return this.worldInfo.getTerrainType(); - } - - /**+ - * Returns the single highest strong power out of all directions - * using getStrongPower(BlockPos, EnumFacing) - */ - public int getStrongPower(BlockPos pos) { - int i = 0; - i = Math.max(i, this.getStrongPower(pos.down(), EnumFacing.DOWN)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.getStrongPower(pos.up(), EnumFacing.UP)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.getStrongPower(pos.north(), EnumFacing.NORTH)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.getStrongPower(pos.south(), EnumFacing.SOUTH)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.getStrongPower(pos.west(), EnumFacing.WEST)); - if (i >= 15) { - return i; - } else { - i = Math.max(i, this.getStrongPower(pos.east(), EnumFacing.EAST)); - return i >= 15 ? i : i; - } - } - } - } - } - } - - public boolean isSidePowered(BlockPos pos, EnumFacing side) { - return this.getRedstonePower(pos, side) > 0; - } - - public int getRedstonePower(BlockPos pos, EnumFacing facing) { - IBlockState iblockstate = this.getBlockState(pos); - Block block = iblockstate.getBlock(); - return block.isNormalCube() ? this.getStrongPower(pos) : block.getWeakPower(this, pos, iblockstate, facing); - } - - public boolean isBlockPowered(BlockPos pos) { - return this.getRedstonePower(pos.down(), EnumFacing.DOWN) > 0 ? true - : (this.getRedstonePower(pos.up(), EnumFacing.UP) > 0 ? true - : (this.getRedstonePower(pos.north(), EnumFacing.NORTH) > 0 ? true - : (this.getRedstonePower(pos.south(), EnumFacing.SOUTH) > 0 ? true - : (this.getRedstonePower(pos.west(), EnumFacing.WEST) > 0 ? true - : this.getRedstonePower(pos.east(), EnumFacing.EAST) > 0)))); - } - - /**+ - * Checks if the specified block or its neighbors are powered by - * a neighboring block. Used by blocks like TNT and Doors. - */ - public int isBlockIndirectlyGettingPowered(BlockPos pos) { - int i = 0; - - EnumFacing[] facings = EnumFacing._VALUES; - BlockPos tmp = new BlockPos(0, 0, 0); - for (int k = 0; k < facings.length; ++k) { - EnumFacing enumfacing = facings[k]; - int j = this.getRedstonePower(pos.offsetEvenFaster(enumfacing, tmp), enumfacing); - if (j >= 15) { - return 15; - } - - if (j > i) { - i = j; - } - } - - return i; - } - - /**+ - * Gets the closest player to the entity within the specified - * distance (if distance is less than 0 then ignored). Args: - * entity, dist - */ - public EntityPlayer getClosestPlayerToEntity(Entity entityIn, double distance) { - return this.getClosestPlayer(entityIn.posX, entityIn.posY, entityIn.posZ, distance); - } - - /**+ - * Gets the closest player to the point within the specified - * distance (distance can be set to less than 0 to not limit the - * distance). Args: x, y, z, dist - */ - public EntityPlayer getClosestPlayer(double x, double y, double z, double distance) { - double d0 = -1.0D; - EntityPlayer entityplayer = null; - - for (int i = 0; i < this.playerEntities.size(); ++i) { - EntityPlayer entityplayer1 = (EntityPlayer) this.playerEntities.get(i); - if (EntitySelectors.NOT_SPECTATING.apply(entityplayer1)) { - double d1 = entityplayer1.getDistanceSq(x, y, z); - if ((distance < 0.0D || d1 < distance * distance) && (d0 == -1.0D || d1 < d0)) { - d0 = d1; - entityplayer = entityplayer1; - } - } - } - - return entityplayer; - } - - public boolean isAnyPlayerWithinRangeAt(double x, double y, double z, double range) { - for (int i = 0; i < this.playerEntities.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); - if (EntitySelectors.NOT_SPECTATING.apply(entityplayer)) { - double d0 = entityplayer.getDistanceSq(x, y, z); - if (range < 0.0D || d0 < range * range) { - return true; - } - } - } - - return false; - } - - /**+ - * Find a player by name in this world. - */ - public EntityPlayer getPlayerEntityByName(String name) { - for (int i = 0; i < this.playerEntities.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); - if (name.equals(entityplayer.getName())) { - return entityplayer; - } - } - - return null; - } - - public EntityPlayer getPlayerEntityByUUID(EaglercraftUUID uuid) { - for (int i = 0; i < this.playerEntities.size(); ++i) { - EntityPlayer entityplayer = (EntityPlayer) this.playerEntities.get(i); - if (uuid.equals(entityplayer.getUniqueID())) { - return entityplayer; - } - } - - return null; - } - - /**+ - * If on MP, sends a quitting packet. - */ - public void sendQuittingDisconnectingPacket() { - } - - /**+ - * Checks whether the session lock file was modified by another - * process - */ - public void checkSessionLock() throws MinecraftException { - this.saveHandler.checkSessionLock(); - } - - public void setTotalWorldTime(long worldTime) { - this.worldInfo.setWorldTotalTime(worldTime); - } - - /**+ - * gets the random world seed - */ - public long getSeed() { - return this.worldInfo.getSeed(); - } - - public long getTotalWorldTime() { - return this.worldInfo.getWorldTotalTime(); - } - - public long getWorldTime() { - return this.worldInfo.getWorldTime(); - } - - /**+ - * Sets the world time. - */ - public void setWorldTime(long time) { - this.worldInfo.setWorldTime(time); - } - - /**+ - * Gets the spawn point in the world - */ - public BlockPos getSpawnPoint() { - BlockPos blockpos = new BlockPos(this.worldInfo.getSpawnX(), this.worldInfo.getSpawnY(), - this.worldInfo.getSpawnZ()); - if (!this.getWorldBorder().contains(blockpos)) { - blockpos = this.getHeight( - new BlockPos(this.getWorldBorder().getCenterX(), 0.0D, this.getWorldBorder().getCenterZ())); - } - - return blockpos; - } - - public void setSpawnPoint(BlockPos pos) { - this.worldInfo.setSpawn(pos); - } - - /**+ - * spwans an entity and loads surrounding chunks - */ - public void joinEntityInSurroundings(Entity entityIn) { - int i = MathHelper.floor_double(entityIn.posX / 16.0D); - int j = MathHelper.floor_double(entityIn.posZ / 16.0D); - byte b0 = 2; - - for (int k = i - b0; k <= i + b0; ++k) { - for (int l = j - b0; l <= j + b0; ++l) { - this.getChunkFromChunkCoords(k, l); - } - } - - if (!this.loadedEntityList.contains(entityIn)) { - this.loadedEntityList.add(entityIn); - } - - } - - public boolean isBlockModifiable(EntityPlayer player, BlockPos pos) { - return true; - } - - /**+ - * sends a Packet 38 (Entity Status) to all tracked players of - * that entity - */ - public void setEntityState(Entity entityIn, byte state) { - } - - /**+ - * gets the world's chunk provider - */ - public IChunkProvider getChunkProvider() { - return this.chunkProvider; - } - - public void addBlockEvent(BlockPos pos, Block blockIn, int eventID, int eventParam) { - blockIn.onBlockEventReceived(this, pos, this.getBlockState(pos), eventID, eventParam); - } - - /**+ - * Returns this world's current save handler - */ - public ISaveHandler getSaveHandler() { - return this.saveHandler; - } - - /**+ - * Returns the world's WorldInfo object - */ - public WorldInfo getWorldInfo() { - return this.worldInfo; - } - - /**+ - * Gets the GameRules instance. - */ - public GameRules getGameRules() { - return this.worldInfo.getGameRulesInstance(); - } - - /**+ - * Updates the flag that indicates whether or not all players in - * the world are sleeping. - */ - public void updateAllPlayersSleepingFlag() { - } - - public float getThunderStrength(float delta) { - return (this.prevThunderingStrength + (this.thunderingStrength - this.prevThunderingStrength) * delta) - * this.getRainStrength(delta); - } - - /**+ - * Sets the strength of the thunder. - */ - public void setThunderStrength(float strength) { - this.prevThunderingStrength = strength; - this.thunderingStrength = strength; - } - - /**+ - * Returns rain strength. - */ - public float getRainStrength(float delta) { - return this.prevRainingStrength + (this.rainingStrength - this.prevRainingStrength) * delta; - } - - /**+ - * Sets the strength of the rain. - */ - public void setRainStrength(float strength) { - this.prevRainingStrength = strength; - this.rainingStrength = strength; - } - - /**+ - * Returns true if the current thunder strength (weighted with - * the rain strength) is greater than 0.9 - */ - public boolean isThundering() { - return (double) this.getThunderStrength(1.0F) > 0.9D; - } - - /**+ - * Returns true if the current rain strength is greater than 0.2 - */ - public boolean isRaining() { - return (double) this.getRainStrength(1.0F) > 0.2D; - } - - public boolean canLightningStrike(BlockPos strikePosition) { - if (!this.isRaining()) { - return false; - } else if (!this.canSeeSky(strikePosition)) { - return false; - } else if (this.getPrecipitationHeight(strikePosition).getY() > strikePosition.getY()) { - return false; - } else { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(strikePosition); - return biomegenbase.getEnableSnow() ? false - : (this.canSnowAt(strikePosition, false) ? false : biomegenbase.canSpawnLightningBolt()); - } - } - - public boolean isBlockinHighHumidity(BlockPos pos) { - BiomeGenBase biomegenbase = this.getBiomeGenForCoords(pos); - return biomegenbase.isHighHumidity(); - } - - public MapStorage getMapStorage() { - return this.mapStorage; - } - - /**+ - * Assigns the given String id to the given MapDataBase using - * the MapStorage, removing any existing ones of the same id. - */ - public void setItemData(String dataID, WorldSavedData worldSavedDataIn) { - this.mapStorage.setData(dataID, worldSavedDataIn); - } - - /**+ - * Loads an existing MapDataBase corresponding to the given - * String id from disk using the MapStorage, instantiating the - * given Class, or returns null if none such file exists. args: - * Class to instantiate, String dataid - */ - public WorldSavedData loadItemData(Class clazz, String dataID) { - return this.mapStorage.loadData(clazz, dataID); - } - - /**+ - * Returns an unique new data id from the MapStorage for the - * given prefix and saves the idCounts map to the 'idcounts' - * file. - */ - public int getUniqueDataId(String key) { - return this.mapStorage.getUniqueDataId(key); - } - - public void playBroadcastSound(int pos, BlockPos parBlockPos, int parInt2) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).broadcastSound(pos, parBlockPos, parInt2); - } - - } - - public void playAuxSFX(int pos, BlockPos parBlockPos, int parInt2) { - this.playAuxSFXAtEntity((EntityPlayer) null, pos, parBlockPos, parInt2); - } - - public void playAuxSFXAtEntity(EntityPlayer player, int sfxType, BlockPos pos, int parInt2) { - try { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - ((IWorldAccess) this.worldAccesses.get(i)).playAuxSFX(player, sfxType, pos, parInt2); - } - - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Playing level event"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Level event being played"); - crashreportcategory.addCrashSection("Block coordinates", CrashReportCategory.getCoordinateInfo(pos)); - crashreportcategory.addCrashSection("Event source", player); - crashreportcategory.addCrashSection("Event type", Integer.valueOf(sfxType)); - crashreportcategory.addCrashSection("Event data", Integer.valueOf(parInt2)); - throw new ReportedException(crashreport); - } - } - - /**+ - * Returns maximum world height. - */ - public int getHeight() { - return 256; - } - - /**+ - * Returns current world height. - */ - public int getActualHeight() { - return this.provider.getHasNoSky() ? 128 : 256; - } - - /**+ - * puts the World Random seed to a specific state dependant on - * the inputs - */ - public EaglercraftRandom setRandomSeed(int parInt1, int parInt2, int parInt3) { - long i = (long) parInt1 * 341873128712L + (long) parInt2 * 132897987541L + this.getWorldInfo().getSeed() - + (long) parInt3; - this.rand.setSeed(i); - return this.rand; - } - - public BlockPos getStrongholdPos(String name, BlockPos pos) { - return this.getChunkProvider().getStrongholdGen(this, name, pos); - } - - /**+ - * set by !chunk.getAreLevelsEmpty - */ - public boolean extendedLevelsInChunkCache() { - return false; - } - - /**+ - * Returns horizon height for use in rendering the sky. - */ - public double getHorizon() { - return this.worldInfo.getTerrainType() == WorldType.FLAT ? 0.0D : 63.0D; - } - - /**+ - * Adds some basic stats of the world to the given crash report. - */ - public CrashReportCategory addWorldInfoToCrashReport(CrashReport report) { - CrashReportCategory crashreportcategory = report.makeCategoryDepth("Affected level", 1); - crashreportcategory.addCrashSection("Level name", - this.worldInfo == null ? "????" : this.worldInfo.getWorldName()); - crashreportcategory.addCrashSectionCallable("All players", new Callable() { - public String call() { - return World.this.playerEntities.size() + " total; " + World.this.playerEntities.toString(); - } - }); - crashreportcategory.addCrashSectionCallable("Chunk stats", new Callable() { - public String call() { - return World.this.chunkProvider.makeString(); - } - }); - - try { - this.worldInfo.addToCrashReport(crashreportcategory); - } catch (Throwable throwable) { - crashreportcategory.addCrashSectionThrowable("Level Data Unobtainable", throwable); - } - - return crashreportcategory; - } - - public void sendBlockBreakProgress(int breakerId, BlockPos pos, int progress) { - for (int i = 0; i < this.worldAccesses.size(); ++i) { - IWorldAccess iworldaccess = (IWorldAccess) this.worldAccesses.get(i); - iworldaccess.sendBlockBreakProgress(breakerId, pos, progress); - } - - } - - /**+ - * returns a calendar object containing the current date - */ - public Calendar getCurrentDate() { - if (this.getTotalWorldTime() % 600L == 0L) { - this.theCalendar.setTimeInMillis(MinecraftServer.getCurrentTimeMillis()); - } - - return this.theCalendar; - } - - public void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, - NBTTagCompound compund) { - } - - public Scoreboard getScoreboard() { - return this.worldScoreboard; - } - - public void updateComparatorOutputLevel(BlockPos pos, Block blockIn) { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - BlockPos blockpos = pos.offset(enumfacing); - if (this.isBlockLoaded(blockpos)) { - IBlockState iblockstate = this.getBlockState(blockpos); - if (Blocks.unpowered_comparator.isAssociated(iblockstate.getBlock())) { - iblockstate.getBlock().onNeighborBlockChange(this, blockpos, iblockstate, blockIn); - } else if (iblockstate.getBlock().isNormalCube()) { - blockpos = blockpos.offset(enumfacing); - iblockstate = this.getBlockState(blockpos); - if (Blocks.unpowered_comparator.isAssociated(iblockstate.getBlock())) { - iblockstate.getBlock().onNeighborBlockChange(this, blockpos, iblockstate, blockIn); - } - } - } - } - - } - - public DifficultyInstance getDifficultyForLocation(BlockPos pos) { - long i = 0L; - float f = 0.0F; - if (this.isBlockLoaded(pos)) { - f = this.getCurrentMoonPhaseFactor(); - i = this.getChunkFromBlockCoords(pos).getInhabitedTime(); - } - - return new DifficultyInstance(this.getDifficulty(), this.getWorldTime(), i, f); - } - - public EnumDifficulty getDifficulty() { - return this.getWorldInfo().getDifficulty(); - } - - public int getSkylightSubtracted() { - return this.skylightSubtracted; - } - - public void setSkylightSubtracted(int newSkylightSubtracted) { - this.skylightSubtracted = newSkylightSubtracted; - } - - public int getLastLightningBolt() { - return this.lastLightningBolt; - } - - public void setLastLightningBolt(int lastLightningBoltIn) { - this.lastLightningBolt = lastLightningBoltIn; - } - - public boolean isFindingSpawnPoint() { - return this.findingSpawnPoint; - } - - public VillageCollection getVillageCollection() { - return this.villageCollectionObj; - } - - public WorldBorder getWorldBorder() { - return this.worldBorder; - } - - /**+ - * Returns true if the chunk is located near the spawn point - */ - public boolean isSpawnChunk(int x, int z) { - if (!MinecraftServer.getServer().worldServers[0].getWorldInfo().getGameRulesInstance() - .getBoolean("loadSpawnChunks")) - return false; - BlockPos blockpos = this.getSpawnPoint(); - int i = x * 16 + 8 - blockpos.getX(); - int j = z * 16 + 8 - blockpos.getZ(); - short short1 = 128; - return i >= -short1 && i <= short1 && j >= -short1 && j <= short1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldManager.java b/src/game/java/net/minecraft/world/WorldManager.java index 1e0502a0..e9c8bfa3 100644 --- a/src/game/java/net/minecraft/world/WorldManager.java +++ b/src/game/java/net/minecraft/world/WorldManager.java @@ -9,22 +9,25 @@ import net.minecraft.network.play.server.S29PacketSoundEffect; import net.minecraft.server.MinecraftServer; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,67 +41,41 @@ public class WorldManager implements IWorldAccess { this.theWorldServer = parWorldServer; } - public void spawnParticle(int var1, boolean var2, double var3, double var5, double var7, double var9, double var11, - double var13, int... var15) { - } - - /**+ - * Called on all IWorldAccesses when an entity is created or - * loaded. On client worlds, starts downloading any necessary - * textures. On server worlds, adds the entity to the entity - * tracker. - */ - public void onEntityAdded(Entity entity) { - this.theWorldServer.getEntityTracker().trackEntity(entity); - } - - /**+ - * Called on all IWorldAccesses when an entity is unloaded or - * destroyed. On client worlds, releases any downloaded - * textures. On server worlds, removes the entity from the - * entity tracker. - */ - public void onEntityRemoved(Entity entity) { - this.theWorldServer.getEntityTracker().untrackEntity(entity); - this.theWorldServer.getScoreboard().func_181140_a(entity); - } - - /**+ - * Plays the specified sound. Arg: soundName, x, y, z, volume, - * pitch - */ - public void playSound(String s, double d0, double d1, double d2, float f, float f1) { - this.mcServer.getConfigurationManager().sendToAllNear(d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, - this.theWorldServer.provider.getDimensionId(), new S29PacketSoundEffect(s, d0, d1, d2, f, f1)); - } - - /**+ - * Plays sound to all near players except the player reference - * given - */ - public void playSoundToNearExcept(EntityPlayer entityplayer, String s, double d0, double d1, double d2, float f, - float f1) { - this.mcServer.getConfigurationManager().sendToAllNearExcept(entityplayer, d0, d1, d2, - f > 1.0F ? (double) (16.0F * f) : 16.0D, this.theWorldServer.provider.getDimensionId(), - new S29PacketSoundEffect(s, d0, d1, d2, f, f1)); - } - - /**+ - * On the client, re-renders all blocks in this range, - * inclusive. On the server, does nothing. Args: min x, min y, - * min z, max x, max y, max z - */ - public void markBlockRangeForRenderUpdate(int var1, int var2, int var3, int var4, int var5, int var6) { + public void broadcastSound(int i, BlockPos blockpos, int j) { + this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S28PacketEffect(i, blockpos, j, true)); } public void markBlockForUpdate(BlockPos blockpos) { this.theWorldServer.getPlayerManager().markBlockForUpdate(blockpos); } + /** + * + On the client, re-renders all blocks in this range, inclusive. On the + * server, does nothing. Args: min x, min y, min z, max x, max y, max z + */ + public void markBlockRangeForRenderUpdate(int var1, int var2, int var3, int var4, int var5, int var6) { + } + public void notifyLightSet(BlockPos var1) { } - public void playRecord(String var1, BlockPos var2) { + /** + * + Called on all IWorldAccesses when an entity is created or loaded. On client + * worlds, starts downloading any necessary textures. On server worlds, adds the + * entity to the entity tracker. + */ + public void onEntityAdded(Entity entity) { + this.theWorldServer.getEntityTracker().trackEntity(entity); + } + + /** + * + Called on all IWorldAccesses when an entity is unloaded or destroyed. On + * client worlds, releases any downloaded textures. On server worlds, removes + * the entity from the entity tracker. + */ + public void onEntityRemoved(Entity entity) { + this.theWorldServer.getEntityTracker().untrackEntity(entity); + this.theWorldServer.getScoreboard().func_181140_a(entity); } public void playAuxSFX(EntityPlayer entityplayer, int i, BlockPos blockpos, int j) { @@ -107,8 +84,25 @@ public class WorldManager implements IWorldAccess { this.theWorldServer.provider.getDimensionId(), new S28PacketEffect(i, blockpos, j, false)); } - public void broadcastSound(int i, BlockPos blockpos, int j) { - this.mcServer.getConfigurationManager().sendPacketToAllPlayers(new S28PacketEffect(i, blockpos, j, true)); + public void playRecord(String var1, BlockPos var2) { + } + + /** + * + Plays the specified sound. Arg: soundName, x, y, z, volume, pitch + */ + public void playSound(String s, double d0, double d1, double d2, float f, float f1) { + this.mcServer.getConfigurationManager().sendToAllNear(d0, d1, d2, f > 1.0F ? (double) (16.0F * f) : 16.0D, + this.theWorldServer.provider.getDimensionId(), new S29PacketSoundEffect(s, d0, d1, d2, f, f1)); + } + + /** + * + Plays sound to all near players except the player reference given + */ + public void playSoundToNearExcept(EntityPlayer entityplayer, String s, double d0, double d1, double d2, float f, + float f1) { + this.mcServer.getConfigurationManager().sendToAllNearExcept(entityplayer, d0, d1, d2, + f > 1.0F ? (double) (16.0F * f) : 16.0D, this.theWorldServer.provider.getDimensionId(), + new S29PacketSoundEffect(s, d0, d1, d2, f, f1)); } public void sendBlockBreakProgress(int i, BlockPos blockpos, int j) { @@ -125,4 +119,8 @@ public class WorldManager implements IWorldAccess { } } + + public void spawnParticle(int var1, boolean var2, double var3, double var5, double var7, double var9, double var11, + double var13, int... var15) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldProvider.java b/src/game/java/net/minecraft/world/WorldProvider.java index 89909fc7..6a5c30a8 100644 --- a/src/game/java/net/minecraft/world/WorldProvider.java +++ b/src/game/java/net/minecraft/world/WorldProvider.java @@ -14,147 +14,56 @@ import net.minecraft.world.gen.ChunkProviderFlat; import net.minecraft.world.gen.ChunkProviderGenerate; import net.minecraft.world.gen.FlatGeneratorInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class WorldProvider { public static final float[] moonPhaseFactors = new float[] { 1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F }; + + public static WorldProvider getProviderForDimension(int dimension) { + return (WorldProvider) (dimension == -1 ? new WorldProviderHell() + : (dimension == 0 ? new WorldProviderSurface() : (dimension == 1 ? new WorldProviderEnd() : null))); + } + protected World worldObj; private WorldType terrainType; private String generatorSettings; protected WorldChunkManager worldChunkMgr; protected boolean isHellWorld; protected boolean hasNoSky; - /**+ - * Light to brightness conversion table + /** + * + Light to brightness conversion table */ protected final float[] lightBrightnessTable = new float[16]; protected int dimensionId; - /**+ - * Array for sunrise/sunset colors (RGBA) + + /** + * + Array for sunrise/sunset colors (RGBA) */ private final float[] colorsSunriseSunset = new float[4]; - /**+ - * associate an existing world with a World provider, and setup - * its lightbrightness table - */ - public final void registerWorld(World worldIn) { - this.worldObj = worldIn; - this.terrainType = worldIn.getWorldInfo().getTerrainType(); - this.generatorSettings = worldIn.getWorldInfo().getGeneratorOptions(); - this.registerWorldChunkManager(); - this.generateLightBrightnessTable(); - } - - /**+ - * Creates the light to brightness table - */ - protected void generateLightBrightnessTable() { - float f = 0.0F; - - for (int i = 0; i <= 15; ++i) { - float f1 = 1.0F - (float) i / 15.0F; - this.lightBrightnessTable[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * (1.0F - f) + f; - } - - } - - /**+ - * creates a new world chunk manager for WorldProvider - */ - protected void registerWorldChunkManager() { - WorldType worldtype = this.worldObj.getWorldInfo().getTerrainType(); - if (worldtype == WorldType.FLAT) { - FlatGeneratorInfo flatgeneratorinfo = FlatGeneratorInfo - .createFlatGeneratorFromString(this.worldObj.getWorldInfo().getGeneratorOptions()); - this.worldChunkMgr = new WorldChunkManagerHell( - BiomeGenBase.getBiomeFromBiomeList(flatgeneratorinfo.getBiome(), BiomeGenBase.field_180279_ad), - 0.5F); - } else if (worldtype == WorldType.DEBUG_WORLD) { - this.worldChunkMgr = new WorldChunkManagerHell(BiomeGenBase.plains, 0.0F); - } else { - this.worldChunkMgr = new WorldChunkManager(this.worldObj); - } - - } - - /**+ - * Returns a new chunk provider which generates chunks for this - * world - */ - public IChunkProvider createChunkGenerator() { - return (IChunkProvider) (this.terrainType == WorldType.FLAT - ? new ChunkProviderFlat(this.worldObj, this.worldObj.getSeed(), - this.worldObj.getWorldInfo().isMapFeaturesEnabled(), this.generatorSettings) - : (this.terrainType == WorldType.DEBUG_WORLD ? new ChunkProviderDebug(this.worldObj) - : (this.terrainType == WorldType.CUSTOMIZED - ? new ChunkProviderGenerate(this.worldObj, this.worldObj.getSeed(), - this.worldObj.getWorldInfo().isMapFeaturesEnabled(), this.generatorSettings) - : new ChunkProviderGenerate(this.worldObj, this.worldObj.getSeed(), - this.worldObj.getWorldInfo().isMapFeaturesEnabled(), this.generatorSettings)))); - } - - /**+ - * Will check if the x, z position specified is alright to be - * set as the map spawn point - */ - public boolean canCoordinateBeSpawn(int x, int z) { - return this.worldObj.getGroundAboveSeaLevel(new BlockPos(x, 0, z)) == Blocks.grass; - } - - /**+ - * Calculates the angle of sun and moon in the sky relative to a - * specified time (usually worldTime) - */ - public float calculateCelestialAngle(long parLong1, float parFloat1) { - int i = (int) (parLong1 % 24000L); - float f = ((float) i + parFloat1) / 24000.0F - 0.25F; - if (f < 0.0F) { - ++f; - } - - if (f > 1.0F) { - --f; - } - - float f2 = f; - f = 1.0F - (float) ((Math.cos((double) f * 3.141592653589793D) + 1.0D) / 2.0D); - f = f2 + (f - f2) / 3.0F; - return f; - } - - public int getMoonPhase(long parLong1) { - return (int) (parLong1 / 24000L % 8L + 8L) % 8; - } - - /**+ - * Returns 'true' if in the "main surface world", but 'false' if - * in the Nether or End dimensions. - */ - public boolean isSurfaceWorld() { - return true; - } - - /**+ - * Returns array with sunrise/sunset colors + /** + * + Returns array with sunrise/sunset colors */ public float[] calcSunriseSunsetColors(float celestialAngle, float partialTicks) { float f = 0.4F; @@ -174,8 +83,104 @@ public abstract class WorldProvider { } } - /**+ - * Return Vec3D with biome specific fog color + /** + * + Calculates the angle of sun and moon in the sky relative to a specified + * time (usually worldTime) + */ + public float calculateCelestialAngle(long parLong1, float parFloat1) { + int i = (int) (parLong1 % 24000L); + float f = ((float) i + parFloat1) / 24000.0F - 0.25F; + if (f < 0.0F) { + ++f; + } + + if (f > 1.0F) { + --f; + } + + float f2 = f; + f = 1.0F - (float) ((Math.cos((double) f * 3.141592653589793D) + 1.0D) / 2.0D); + f = f2 + (f - f2) / 3.0F; + return f; + } + + /** + * + Will check if the x, z position specified is alright to be set as the map + * spawn point + */ + public boolean canCoordinateBeSpawn(int x, int z) { + return this.worldObj.getGroundAboveSeaLevel(new BlockPos(x, 0, z)) == Blocks.grass; + } + + /** + * + True if the player can respawn in this dimension (true = overworld, false = + * nether). + */ + public boolean canRespawnHere() { + return true; + } + + /** + * + Returns a new chunk provider which generates chunks for this world + */ + public IChunkProvider createChunkGenerator() { + return (IChunkProvider) (this.terrainType == WorldType.FLAT + ? new ChunkProviderFlat(this.worldObj, this.worldObj.getSeed(), + this.worldObj.getWorldInfo().isMapFeaturesEnabled(), this.generatorSettings) + : (this.terrainType == WorldType.DEBUG_WORLD ? new ChunkProviderDebug(this.worldObj) + : (this.terrainType == WorldType.CUSTOMIZED + ? new ChunkProviderGenerate(this.worldObj, this.worldObj.getSeed(), + this.worldObj.getWorldInfo().isMapFeaturesEnabled(), this.generatorSettings) + : new ChunkProviderGenerate(this.worldObj, this.worldObj.getSeed(), + this.worldObj.getWorldInfo().isMapFeaturesEnabled(), this.generatorSettings)))); + } + + public boolean doesWaterVaporize() { + return this.isHellWorld; + } + + /** + * + Returns true if the given X,Z coordinate should show environmental fog. + */ + public boolean doesXZShowFog(int x, int z) { + return false; + } + + /** + * + Creates the light to brightness table + */ + protected void generateLightBrightnessTable() { + float f = 0.0F; + + for (int i = 0; i <= 15; ++i) { + float f1 = 1.0F - (float) i / 15.0F; + this.lightBrightnessTable[i] = (1.0F - f1) / (f1 * 3.0F + 1.0F) * (1.0F - f) + f; + } + + } + + public int getAverageGroundLevel() { + return this.terrainType == WorldType.FLAT ? 4 : this.worldObj.func_181545_F() + 1; + } + + /** + * + the y level at which clouds are rendered. + */ + public float getCloudHeight() { + return 128.0F; + } + + /** + * + Gets the dimension of the provider + */ + public int getDimensionId() { + return this.dimensionId; + } + + public abstract String getDimensionName(); + + /** + * + Return Vec3D with biome specific fog color */ public Vec3 getFogColor(float parFloat1, float parFloat2) { float f = MathHelper.cos(parFloat1 * 3.1415927F * 2.0F) * 2.0F + 0.5F; @@ -189,84 +194,82 @@ public abstract class WorldProvider { return new Vec3((double) f1, (double) f2, (double) f3); } - /**+ - * True if the player can respawn in this dimension (true = - * overworld, false = nether). - */ - public boolean canRespawnHere() { - return true; + public boolean getHasNoSky() { + return this.hasNoSky; } - public static WorldProvider getProviderForDimension(int dimension) { - return (WorldProvider) (dimension == -1 ? new WorldProviderHell() - : (dimension == 0 ? new WorldProviderSurface() : (dimension == 1 ? new WorldProviderEnd() : null))); + public abstract String getInternalNameSuffix(); + + public float[] getLightBrightnessTable() { + return this.lightBrightnessTable; } - /**+ - * the y level at which clouds are rendered. - */ - public float getCloudHeight() { - return 128.0F; - } - - public boolean isSkyColored() { - return true; + public int getMoonPhase(long parLong1) { + return (int) (parLong1 / 24000L % 8L + 8L) % 8; } public BlockPos getSpawnCoordinate() { return null; } - public int getAverageGroundLevel() { - return this.terrainType == WorldType.FLAT ? 4 : this.worldObj.func_181545_F() + 1; - } - - /**+ - * Returns a double value representing the Y value relative to - * the top of the map at which void fog is at its maximum. The - * default factor of 0.03125 relative to 256, for example, means - * the void fog will be at its maximum at (256*0.03125), or 8. + /** + * + Returns a double value representing the Y value relative to the top of the + * map at which void fog is at its maximum. The default factor of 0.03125 + * relative to 256, for example, means the void fog will be at its maximum at + * (256*0.03125), or 8. */ public double getVoidFogYFactor() { return this.terrainType == WorldType.FLAT ? 1.0D : 0.03125D; } - /**+ - * Returns true if the given X,Z coordinate should show - * environmental fog. - */ - public boolean doesXZShowFog(int x, int z) { - return false; + public WorldBorder getWorldBorder() { + return new WorldBorder(); } - public abstract String getDimensionName(); - - public abstract String getInternalNameSuffix(); - public WorldChunkManager getWorldChunkManager() { return this.worldChunkMgr; } - public boolean doesWaterVaporize() { - return this.isHellWorld; + public boolean isSkyColored() { + return true; } - public boolean getHasNoSky() { - return this.hasNoSky; - } - - public float[] getLightBrightnessTable() { - return this.lightBrightnessTable; - } - - /**+ - * Gets the dimension of the provider + /** + * + Returns 'true' if in the "main surface world", but 'false' if in the Nether + * or End dimensions. */ - public int getDimensionId() { - return this.dimensionId; + public boolean isSurfaceWorld() { + return true; } - public WorldBorder getWorldBorder() { - return new WorldBorder(); + /** + * + associate an existing world with a World provider, and setup its + * lightbrightness table + */ + public final void registerWorld(World worldIn) { + this.worldObj = worldIn; + this.terrainType = worldIn.getWorldInfo().getTerrainType(); + this.generatorSettings = worldIn.getWorldInfo().getGeneratorOptions(); + this.registerWorldChunkManager(); + this.generateLightBrightnessTable(); + } + + /** + * + creates a new world chunk manager for WorldProvider + */ + protected void registerWorldChunkManager() { + WorldType worldtype = this.worldObj.getWorldInfo().getTerrainType(); + if (worldtype == WorldType.FLAT) { + FlatGeneratorInfo flatgeneratorinfo = FlatGeneratorInfo + .createFlatGeneratorFromString(this.worldObj.getWorldInfo().getGeneratorOptions()); + this.worldChunkMgr = new WorldChunkManagerHell( + BiomeGenBase.getBiomeFromBiomeList(flatgeneratorinfo.getBiome(), BiomeGenBase.field_180279_ad), + 0.5F); + } else if (worldtype == WorldType.DEBUG_WORLD) { + this.worldChunkMgr = new WorldChunkManagerHell(BiomeGenBase.plains, 0.0F); + } else { + this.worldChunkMgr = new WorldChunkManager(this.worldObj); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldProviderEnd.java b/src/game/java/net/minecraft/world/WorldProviderEnd.java index 6e7a84e4..4f1dbeee 100644 --- a/src/game/java/net/minecraft/world/WorldProviderEnd.java +++ b/src/game/java/net/minecraft/world/WorldProviderEnd.java @@ -8,61 +8,95 @@ import net.minecraft.world.biome.WorldChunkManagerHell; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderEnd; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldProviderEnd extends WorldProvider { - /**+ - * creates a new world chunk manager for WorldProvider - */ - public void registerWorldChunkManager() { - this.worldChunkMgr = new WorldChunkManagerHell(BiomeGenBase.sky, 0.0F); - this.dimensionId = 1; - this.hasNoSky = true; - } - - /**+ - * Returns a new chunk provider which generates chunks for this - * world - */ - public IChunkProvider createChunkGenerator() { - return new ChunkProviderEnd(this.worldObj, this.worldObj.getSeed()); - } - - /**+ - * Calculates the angle of sun and moon in the sky relative to a - * specified time (usually worldTime) - */ - public float calculateCelestialAngle(long var1, float var3) { - return 0.0F; - } - - /**+ - * Returns array with sunrise/sunset colors + /** + * + Returns array with sunrise/sunset colors */ public float[] calcSunriseSunsetColors(float var1, float var2) { return null; } - /**+ - * Return Vec3D with biome specific fog color + /** + * + Calculates the angle of sun and moon in the sky relative to a specified + * time (usually worldTime) + */ + public float calculateCelestialAngle(long var1, float var3) { + return 0.0F; + } + + /** + * + Will check if the x, z position specified is alright to be set as the map + * spawn point + */ + public boolean canCoordinateBeSpawn(int i, int j) { + return this.worldObj.getGroundAboveSeaLevel(new BlockPos(i, 0, j)).getMaterial().blocksMovement(); + } + + /** + * + True if the player can respawn in this dimension (true = overworld, false = + * nether). + */ + public boolean canRespawnHere() { + return false; + } + + /** + * + Returns a new chunk provider which generates chunks for this world + */ + public IChunkProvider createChunkGenerator() { + return new ChunkProviderEnd(this.worldObj, this.worldObj.getSeed()); + } + + /** + * + Returns true if the given X,Z coordinate should show environmental fog. + */ + public boolean doesXZShowFog(int var1, int var2) { + return true; + } + + public int getAverageGroundLevel() { + return 50; + } + + /** + * + the y level at which clouds are rendered. + */ + public float getCloudHeight() { + return 8.0F; + } + + /** + * + Returns the dimension's name, e.g. "The End", "Nether", or "Overworld". + */ + public String getDimensionName() { + return "The End"; + } + + /** + * + Return Vec3D with biome specific fog color */ public Vec3 getFogColor(float f, float var2) { int i = 10518688; @@ -77,66 +111,32 @@ public class WorldProviderEnd extends WorldProvider { return new Vec3((double) f2, (double) f3, (double) f4); } - public boolean isSkyColored() { - return false; - } - - /**+ - * True if the player can respawn in this dimension (true = - * overworld, false = nether). - */ - public boolean canRespawnHere() { - return false; - } - - /**+ - * Returns 'true' if in the "main surface world", but 'false' if - * in the Nether or End dimensions. - */ - public boolean isSurfaceWorld() { - return false; - } - - /**+ - * the y level at which clouds are rendered. - */ - public float getCloudHeight() { - return 8.0F; - } - - /**+ - * Will check if the x, z position specified is alright to be - * set as the map spawn point - */ - public boolean canCoordinateBeSpawn(int i, int j) { - return this.worldObj.getGroundAboveSeaLevel(new BlockPos(i, 0, j)).getMaterial().blocksMovement(); + public String getInternalNameSuffix() { + return "_end"; } public BlockPos getSpawnCoordinate() { return new BlockPos(100, 50, 0); } - public int getAverageGroundLevel() { - return 50; + public boolean isSkyColored() { + return false; } - /**+ - * Returns true if the given X,Z coordinate should show - * environmental fog. + /** + * + Returns 'true' if in the "main surface world", but 'false' if in the Nether + * or End dimensions. */ - public boolean doesXZShowFog(int var1, int var2) { - return true; + public boolean isSurfaceWorld() { + return false; } - /**+ - * Returns the dimension's name, e.g. "The End", "Nether", or - * "Overworld". + /** + * + creates a new world chunk manager for WorldProvider */ - public String getDimensionName() { - return "The End"; - } - - public String getInternalNameSuffix() { - return "_end"; + public void registerWorldChunkManager() { + this.worldChunkMgr = new WorldChunkManagerHell(BiomeGenBase.sky, 0.0F); + this.dimensionId = 1; + this.hasNoSky = true; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldProviderHell.java b/src/game/java/net/minecraft/world/WorldProviderHell.java index 4e20ba16..aa2091ec 100644 --- a/src/game/java/net/minecraft/world/WorldProviderHell.java +++ b/src/game/java/net/minecraft/world/WorldProviderHell.java @@ -7,46 +7,71 @@ import net.minecraft.world.border.WorldBorder; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.gen.ChunkProviderHell; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldProviderHell extends WorldProvider { - /**+ - * creates a new world chunk manager for WorldProvider + /** + * + Calculates the angle of sun and moon in the sky relative to a specified + * time (usually worldTime) */ - public void registerWorldChunkManager() { - this.worldChunkMgr = new WorldChunkManagerHell(BiomeGenBase.hell, 0.0F); - this.isHellWorld = true; - this.hasNoSky = true; - this.dimensionId = -1; + public float calculateCelestialAngle(long var1, float var3) { + return 0.5F; } - /**+ - * Return Vec3D with biome specific fog color + /** + * + Will check if the x, z position specified is alright to be set as the map + * spawn point */ - public Vec3 getFogColor(float var1, float var2) { - return new Vec3(0.20000000298023224D, 0.029999999329447746D, 0.029999999329447746D); + public boolean canCoordinateBeSpawn(int var1, int var2) { + return false; } - /**+ - * Creates the light to brightness table + /** + * + True if the player can respawn in this dimension (true = overworld, false = + * nether). + */ + public boolean canRespawnHere() { + return false; + } + + /** + * + Returns a new chunk provider which generates chunks for this world + */ + public IChunkProvider createChunkGenerator() { + return new ChunkProviderHell(this.worldObj, this.worldObj.getWorldInfo().isMapFeaturesEnabled(), + this.worldObj.getSeed()); + } + + /** + * + Returns true if the given X,Z coordinate should show environmental fog. + */ + public boolean doesXZShowFog(int var1, int var2) { + return true; + } + + /** + * + Creates the light to brightness table */ protected void generateLightBrightnessTable() { float f = 0.1F; @@ -58,63 +83,20 @@ public class WorldProviderHell extends WorldProvider { } - /**+ - * Returns a new chunk provider which generates chunks for this - * world - */ - public IChunkProvider createChunkGenerator() { - return new ChunkProviderHell(this.worldObj, this.worldObj.getWorldInfo().isMapFeaturesEnabled(), - this.worldObj.getSeed()); - } - - /**+ - * Returns 'true' if in the "main surface world", but 'false' if - * in the Nether or End dimensions. - */ - public boolean isSurfaceWorld() { - return false; - } - - /**+ - * Will check if the x, z position specified is alright to be - * set as the map spawn point - */ - public boolean canCoordinateBeSpawn(int var1, int var2) { - return false; - } - - /**+ - * Calculates the angle of sun and moon in the sky relative to a - * specified time (usually worldTime) - */ - public float calculateCelestialAngle(long var1, float var3) { - return 0.5F; - } - - /**+ - * True if the player can respawn in this dimension (true = - * overworld, false = nether). - */ - public boolean canRespawnHere() { - return false; - } - - /**+ - * Returns true if the given X,Z coordinate should show - * environmental fog. - */ - public boolean doesXZShowFog(int var1, int var2) { - return true; - } - - /**+ - * Returns the dimension's name, e.g. "The End", "Nether", or - * "Overworld". + /** + * + Returns the dimension's name, e.g. "The End", "Nether", or "Overworld". */ public String getDimensionName() { return "Nether"; } + /** + * + Return Vec3D with biome specific fog color + */ + public Vec3 getFogColor(float var1, float var2) { + return new Vec3(0.20000000298023224D, 0.029999999329447746D, 0.029999999329447746D); + } + public String getInternalNameSuffix() { return "_nether"; } @@ -130,4 +112,22 @@ public class WorldProviderHell extends WorldProvider { } }; } + + /** + * + Returns 'true' if in the "main surface world", but 'false' if in the Nether + * or End dimensions. + */ + public boolean isSurfaceWorld() { + return false; + } + + /** + * + creates a new world chunk manager for WorldProvider + */ + public void registerWorldChunkManager() { + this.worldChunkMgr = new WorldChunkManagerHell(BiomeGenBase.hell, 0.0F); + this.isHellWorld = true; + this.hasNoSky = true; + this.dimensionId = -1; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldProviderSurface.java b/src/game/java/net/minecraft/world/WorldProviderSurface.java index eb55a11c..58486cda 100644 --- a/src/game/java/net/minecraft/world/WorldProviderSurface.java +++ b/src/game/java/net/minecraft/world/WorldProviderSurface.java @@ -1,29 +1,31 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldProviderSurface extends WorldProvider { - /**+ - * Returns the dimension's name, e.g. "The End", "Nether", or - * "Overworld". + /** + * + Returns the dimension's name, e.g. "The End", "Nether", or "Overworld". */ public String getDimensionName() { return "Overworld"; diff --git a/src/game/java/net/minecraft/world/WorldSavedData.java b/src/game/java/net/minecraft/world/WorldSavedData.java index 1212c851..a8209e5b 100644 --- a/src/game/java/net/minecraft/world/WorldSavedData.java +++ b/src/game/java/net/minecraft/world/WorldSavedData.java @@ -2,22 +2,25 @@ package net.minecraft.world; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,30 +33,29 @@ public abstract class WorldSavedData { this.mapName = name; } - public abstract void readFromNBT(NBTTagCompound var1); + /** + * + Whether this MapDataBase needs saving to disk. + */ + public boolean isDirty() { + return this.dirty; + } - public abstract void writeToNBT(NBTTagCompound var1); - - /**+ - * Marks this MapDataBase dirty, to be saved to disk when the - * level next saves. + /** + * + Marks this MapDataBase dirty, to be saved to disk when the level next + * saves. */ public void markDirty() { this.setDirty(true); } - /**+ - * Sets the dirty state of this MapDataBase, whether it needs - * saving to disk. + public abstract void readFromNBT(NBTTagCompound var1); + + /** + * + Sets the dirty state of this MapDataBase, whether it needs saving to disk. */ public void setDirty(boolean isDirty) { this.dirty = isDirty; } - /**+ - * Whether this MapDataBase needs saving to disk. - */ - public boolean isDirty() { - return this.dirty; - } + public abstract void writeToNBT(NBTTagCompound var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldServer.java b/src/game/java/net/minecraft/world/WorldServer.java index bcecccc2..4d4f0d3c 100644 --- a/src/game/java/net/minecraft/world/WorldServer.java +++ b/src/game/java/net/minecraft/world/WorldServer.java @@ -1,17 +1,21 @@ package net.minecraft.world; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + import com.google.common.base.Predicate; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import java.util.Set; -import java.util.TreeSet; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; import net.minecraft.block.Block; import net.minecraft.block.BlockEventData; @@ -66,37 +70,54 @@ import net.minecraft.world.gen.structure.StructureBoundingBox; import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.MapStorage; import net.minecraft.world.storage.WorldInfo; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldServer extends World implements IThreadListener { + static class ServerBlockEventList extends ArrayList { + private ServerBlockEventList() { + } + } + private static final Logger logger = LogManager.getLogger(); + private static final List bonusChestContent = Lists + .newArrayList(new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.stick, 0, 1, 3, 10), + new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.planks), 0, 1, 3, 10), + new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.log), 0, 1, 3, 10), + new WeightedRandomChestContent(Items.stone_axe, 0, 1, 1, 3), + new WeightedRandomChestContent(Items.wooden_axe, 0, 1, 1, 5), + new WeightedRandomChestContent(Items.stone_pickaxe, 0, 1, 1, 3), + new WeightedRandomChestContent(Items.wooden_pickaxe, 0, 1, 1, 5), + new WeightedRandomChestContent(Items.apple, 0, 2, 3, 5), + new WeightedRandomChestContent(Items.bread, 0, 2, 3, 3), + new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.log2), 0, 1, 3, 10) }); private final MinecraftServer mcServer; private final EntityTracker theEntityTracker; private final PlayerManager thePlayerManager; private final Set pendingTickListEntriesHashSet = Sets.newHashSet(); - /**+ - * All work to do in future ticks. + /** + * + All work to do in future ticks. */ private final TreeSet pendingTickListEntriesTreeSet = new TreeSet(); private final Map entitiesByUuid = Maps.newHashMap(); @@ -110,17 +131,7 @@ public class WorldServer extends World implements IThreadListener { private WorldServer.ServerBlockEventList[] field_147490_S = new WorldServer.ServerBlockEventList[] { new WorldServer.ServerBlockEventList(), new WorldServer.ServerBlockEventList() }; private int blockEventCacheIndex; - private static final List bonusChestContent = Lists - .newArrayList(new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.stick, 0, 1, 3, 10), - new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.planks), 0, 1, 3, 10), - new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.log), 0, 1, 3, 10), - new WeightedRandomChestContent(Items.stone_axe, 0, 1, 1, 3), - new WeightedRandomChestContent(Items.wooden_axe, 0, 1, 1, 5), - new WeightedRandomChestContent(Items.stone_pickaxe, 0, 1, 1, 3), - new WeightedRandomChestContent(Items.wooden_pickaxe, 0, 1, 1, 5), - new WeightedRandomChestContent(Items.apple, 0, 2, 3, 5), - new WeightedRandomChestContent(Items.bread, 0, 2, 3, 3), - new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.log2), 0, 1, 3, 10) }); + private List pendingTickListEntriesThisTick = Lists.newArrayList(); public WorldServer(MinecraftServer server, ISaveHandler saveHandlerIn, WorldInfo info, int dimensionId) { @@ -136,6 +147,265 @@ public class WorldServer extends World implements IThreadListener { this.getWorldBorder().setSize(server.getMaxWorldSize()); } + public void addBlockEvent(BlockPos blockpos, Block block, int i, int j) { + BlockEventData blockeventdata = new BlockEventData(blockpos, block, i, j); + + ServerBlockEventList lst = this.field_147490_S[this.blockEventCacheIndex]; + for (int k = 0, l = lst.size(); k < l; ++k) { + if (lst.get(k).equals(blockeventdata)) { + return; + } + } + + this.field_147490_S[this.blockEventCacheIndex].add(blockeventdata); + } + + public void addScheduledTask(Runnable runnable) { + this.mcServer.addScheduledTask(runnable); + } + + /** + * + adds a lightning bolt to the list of lightning bolts in this world. + */ + public boolean addWeatherEffect(Entity entity) { + if (super.addWeatherEffect(entity)) { + this.mcServer.getConfigurationManager().sendToAllNear(entity.posX, entity.posY, entity.posZ, 512.0D, + this.provider.getDimensionId(), new S2CPacketSpawnGlobalEntity(entity)); + return true; + } else { + return false; + } + } + + protected BlockPos adjustPosToNearbyEntity(BlockPos pos) { + BlockPos blockpos = this.getPrecipitationHeight(pos); + AxisAlignedBB axisalignedbb = (new AxisAlignedBB(blockpos, + new BlockPos(blockpos.getX(), this.getHeight(), blockpos.getZ()))).expand(3.0D, 3.0D, 3.0D); + List list = this.getEntitiesWithinAABB(EntityLivingBase.class, axisalignedbb, + new Predicate() { + public boolean apply(EntityLivingBase entitylivingbase) { + return entitylivingbase != null && entitylivingbase.isEntityAlive() + && WorldServer.this.canSeeSky(entitylivingbase.getPosition()); + } + }); + return !list.isEmpty() ? ((EntityLivingBase) list.get(this.rand.nextInt(list.size()))).getPosition() : blockpos; + } + + public boolean areAllPlayersAsleep() { + if (this.allPlayersSleeping) { + for (int k = 0, l = this.playerEntities.size(); k < l; ++k) { + EntityPlayer entityplayer = this.playerEntities.get(k); + if (entityplayer.isSpectator() || !entityplayer.isPlayerFullyAsleep()) { + return false; + } + } + + return true; + } else { + return false; + } + } + + public boolean canCreatureTypeSpawnHere(EnumCreatureType creatureType, BiomeGenBase.SpawnListEntry spawnListEntry, + BlockPos pos) { + List list = this.getChunkProvider().getPossibleCreatures(creatureType, pos); + return list != null && !list.isEmpty() ? list.contains(spawnListEntry) : false; + } + + private boolean canSpawnAnimals() { + return this.mcServer.getCanSpawnAnimals(); + } + + private boolean canSpawnNPCs() { + return this.mcServer.getCanSpawnNPCs(); + } + + /** + * + Creates the bonus chest in the world. + */ + protected void createBonusChest() { + WorldGeneratorBonusChest worldgeneratorbonuschest = new WorldGeneratorBonusChest(bonusChestContent, 10); + + for (int i = 0; i < 10; ++i) { + int j = this.worldInfo.getSpawnX() + this.rand.nextInt(6) - this.rand.nextInt(6); + int k = this.worldInfo.getSpawnZ() + this.rand.nextInt(6) - this.rand.nextInt(6); + BlockPos blockpos = this.getTopSolidOrLiquidBlock(new BlockPos(j, 0, k)).up(); + if (worldgeneratorbonuschest.generate(this, this.rand, blockpos)) { + break; + } + } + + } + + /** + * + Creates the chunk provider for this world. Called in the constructor. + * Retrieves provider from worldProvider? + */ + protected IChunkProvider createChunkProvider() { + IChunkLoader ichunkloader = this.saveHandler.getChunkLoader(this.provider); + this.theChunkProviderServer = new ChunkProviderServer(this, ichunkloader, this.provider.createChunkGenerator()); + return this.theChunkProviderServer; + } + + /** + * + creates a spawn position at random within 256 blocks of 0,0 + */ + private void createSpawnPosition(WorldSettings parWorldSettings) { + if (!this.provider.canRespawnHere()) { + this.worldInfo.setSpawn(BlockPos.ORIGIN.up(this.provider.getAverageGroundLevel())); + } else if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { + this.worldInfo.setSpawn(BlockPos.ORIGIN.up()); + } else { + this.findingSpawnPoint = true; + WorldChunkManager worldchunkmanager = this.provider.getWorldChunkManager(); + List list = worldchunkmanager.getBiomesToSpawnIn(); + EaglercraftRandom random = new EaglercraftRandom(this.getSeed()); + BlockPos blockpos = worldchunkmanager.findBiomePosition(0, 0, 256, list, random); + int i = 0; + int j = this.provider.getAverageGroundLevel(); + int k = 0; + if (blockpos != null) { + i = blockpos.getX(); + k = blockpos.getZ(); + } else { + logger.warn("Unable to find spawn biome"); + } + + int l = 0; + + while (!this.provider.canCoordinateBeSpawn(i, k)) { + i += random.nextInt(64) - random.nextInt(64); + k += random.nextInt(64) - random.nextInt(64); + ++l; + if (l == 1000) { + break; + } + } + + this.worldInfo.setSpawn(new BlockPos(i, j, k)); + this.findingSpawnPoint = false; + if (parWorldSettings.isBonusChestEnabled()) { + this.createBonusChest(); + } + + } + } + + private boolean fireBlockEvent(BlockEventData event) { + IBlockState iblockstate = this.getBlockState(event.getPosition()); + return iblockstate.getBlock() == event.getBlock() ? iblockstate.getBlock().onBlockEventReceived(this, + event.getPosition(), iblockstate, event.getEventID(), event.getEventParameter()) : false; + } + + /** + * + Syncs all changes to disk and wait for completion. + */ + public void flush() { + this.saveHandler.flush(); + } + + public List func_175712_a(StructureBoundingBox structureboundingbox, boolean flag) { + ArrayList arraylist = null; + + for (int i = 0; i < 2; ++i) { + Iterator iterator; + if (i == 0) { + iterator = this.pendingTickListEntriesTreeSet.iterator(); + } else { + iterator = this.pendingTickListEntriesThisTick.iterator(); + } + + while (iterator.hasNext()) { + NextTickListEntry nextticklistentry = (NextTickListEntry) iterator.next(); + BlockPos blockpos = nextticklistentry.position; + if (blockpos.getX() >= structureboundingbox.minX && blockpos.getX() < structureboundingbox.maxX + && blockpos.getZ() >= structureboundingbox.minZ + && blockpos.getZ() < structureboundingbox.maxZ) { + if (flag) { + this.pendingTickListEntriesHashSet.remove(nextticklistentry); + iterator.remove(); + } + + if (arraylist == null) { + arraylist = Lists.newArrayList(); + } + + arraylist.add(nextticklistentry); + } + } + } + + return arraylist; + } + + public Teleporter getDefaultTeleporter() { + return this.worldTeleporter; + } + + public Entity getEntityFromUuid(EaglercraftUUID uuid) { + return (Entity) this.entitiesByUuid.get(uuid); + } + + /** + * + Gets the EntityTracker + */ + public EntityTracker getEntityTracker() { + return this.theEntityTracker; + } + + public MinecraftServer getMinecraftServer() { + return this.mcServer; + } + + public List getPendingBlockUpdates(Chunk chunk, boolean flag) { + ChunkCoordIntPair chunkcoordintpair = chunk.getChunkCoordIntPair(); + int i = (chunkcoordintpair.chunkXPos << 4) - 2; + int j = i + 16 + 2; + int k = (chunkcoordintpair.chunkZPos << 4) - 2; + int l = k + 16 + 2; + return this.func_175712_a(new StructureBoundingBox(i, 0, k, j, 256, l), flag); + } + + public PlayerManager getPlayerManager() { + return this.thePlayerManager; + } + + protected int getRenderDistanceChunks() { + return this.mcServer.getConfigurationManager().getViewDistance(); + } + + /** + * + Returns null for anything other than the End + */ + public BlockPos getSpawnCoordinate() { + return this.provider.getSpawnCoordinate(); + } + + public BiomeGenBase.SpawnListEntry getSpawnListEntryForTypeAt(EnumCreatureType creatureType, BlockPos pos) { + List list = this.getChunkProvider().getPossibleCreatures(creatureType, pos); + return list != null && !list.isEmpty() + ? (BiomeGenBase.SpawnListEntry) WeightedRandom.getRandomItem(this.rand, list) + : null; + } + + /** + * + Returns all the tile entities located between the given coordinates + */ + public List getTileEntitiesIn(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { + ArrayList arraylist = Lists.newArrayList(); + + for (int i = 0; i < this.loadedTileEntityList.size(); ++i) { + TileEntity tileentity = (TileEntity) this.loadedTileEntityList.get(i); + BlockPos blockpos = tileentity.getPos(); + if (blockpos.getX() >= minX && blockpos.getY() >= minY && blockpos.getZ() >= minZ && blockpos.getX() < maxX + && blockpos.getY() < maxY && blockpos.getZ() < maxZ) { + arraylist.add(tileentity); + } + } + + return arraylist; + } + public World init() { this.mapStorage = new MapStorage(this.saveHandler); String s = VillageCollection.fileNameForProvider(this.provider); @@ -173,8 +443,286 @@ public class WorldServer extends World implements IThreadListener { return this; } - /**+ - * Runs a single tick for the world + public void initialize(WorldSettings worldsettings) { + if (!this.worldInfo.isInitialized()) { + try { + this.createSpawnPosition(worldsettings); + if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { + this.setDebugWorldSettings(); + } + + super.initialize(worldsettings); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception initializing level"); + + try { + this.addWorldInfoToCrashReport(crashreport); + } catch (Throwable var5) { + ; + } + + throw new ReportedException(crashreport); + } + + this.worldInfo.setServerInitialized(true); + } + + } + + public boolean isBlockModifiable(EntityPlayer entityplayer, BlockPos blockpos) { + return !this.mcServer.isBlockProtected(this, blockpos, entityplayer) + && this.getWorldBorder().contains(blockpos); + } + + public boolean isBlockTickPending(BlockPos blockpos, Block block) { + NextTickListEntry nextticklistentry = new NextTickListEntry(blockpos, block); + return this.pendingTickListEntriesThisTick.contains(nextticklistentry); + } + + /** + * + returns a new explosion. Does initiation (at time of writing Explosion is + * not finished) + */ + public Explosion newExplosion(Entity entity, double d0, double d1, double d2, float f, boolean flag, + boolean flag1) { + Explosion explosion = new Explosion(this, entity, d0, d1, d2, f, flag, flag1); + explosion.doExplosionA(); + explosion.doExplosionB(false); + if (!flag1) { + explosion.func_180342_d(); + } + + List lst = this.playerEntities; + for (int i = 0, l = lst.size(); i < l; ++i) { + EntityPlayer entityplayer = lst.get(i); + if (entityplayer.getDistanceSq(d0, d1, d2) < 4096.0D) { + ((EntityPlayerMP) entityplayer).playerNetServerHandler + .sendPacket(new S27PacketExplosion(d0, d1, d2, f, explosion.getAffectedBlockPositions(), + (Vec3) explosion.getPlayerKnockbackMap().get(entityplayer))); + } + } + + return explosion; + } + + protected void onEntityAdded(Entity entity) { + super.onEntityAdded(entity); + this.entitiesById.addKey(entity.getEntityId(), entity); + this.entitiesByUuid.put(entity.getUniqueID(), entity); + Entity[] aentity = entity.getParts(); + if (aentity != null) { + for (int i = 0; i < aentity.length; ++i) { + this.entitiesById.addKey(aentity[i].getEntityId(), aentity[i]); + } + } + + } + + protected void onEntityRemoved(Entity entity) { + super.onEntityRemoved(entity); + this.entitiesById.removeObject(entity.getEntityId()); + this.entitiesByUuid.remove(entity.getUniqueID()); + Entity[] aentity = entity.getParts(); + if (aentity != null) { + for (int i = 0; i < aentity.length; ++i) { + this.entitiesById.removeObject(aentity[i].getEntityId()); + } + } + + } + + private void resetRainAndThunder() { + this.worldInfo.setRainTime(0); + this.worldInfo.setRaining(false); + this.worldInfo.setThunderTime(0); + this.worldInfo.setThundering(false); + } + + /** + * + Resets the updateEntityTick field to 0 + */ + public void resetUpdateEntityTick() { + this.updateEntityTick = 0; + } + + /** + * + Saves all chunks to disk while updating progress bar. + */ + public void saveAllChunks(boolean progressCallback, IProgressUpdate parIProgressUpdate) throws MinecraftException { + if (this.chunkProvider.canSave()) { + if (parIProgressUpdate != null) { + parIProgressUpdate.displaySavingString("Saving level"); + } + + this.saveLevel(); + if (parIProgressUpdate != null) { + parIProgressUpdate.displayLoadingString("Saving chunks"); + } + + this.chunkProvider.saveChunks(progressCallback, parIProgressUpdate); + + List lst = Lists.newArrayList(this.theChunkProviderServer.func_152380_a()); + for (int i = 0, l = lst.size(); i < l; ++i) { + Chunk chunk = lst.get(i); + if (chunk != null && !this.thePlayerManager.hasPlayerInstance(chunk.xPosition, chunk.zPosition)) { + this.theChunkProviderServer.dropChunk(chunk.xPosition, chunk.zPosition); + } + } + + } + } + + /** + * + saves chunk data - currently only called during execution of the Save All + * command + */ + public void saveChunkData() { + if (this.chunkProvider.canSave()) { + this.chunkProvider.saveExtraData(); + } + } + + /** + * + Saves the chunks to disk. + */ + protected void saveLevel() throws MinecraftException { + this.checkSessionLock(); + this.worldInfo.setBorderSize(this.getWorldBorder().getDiameter()); + this.worldInfo.getBorderCenterX(this.getWorldBorder().getCenterX()); + this.worldInfo.getBorderCenterZ(this.getWorldBorder().getCenterZ()); + this.worldInfo.setBorderSafeZone(this.getWorldBorder().getDamageBuffer()); + this.worldInfo.setBorderDamagePerBlock(this.getWorldBorder().getDamageAmount()); + this.worldInfo.setBorderWarningDistance(this.getWorldBorder().getWarningDistance()); + this.worldInfo.setBorderWarningTime(this.getWorldBorder().getWarningTime()); + this.worldInfo.setBorderLerpTarget(this.getWorldBorder().getTargetSize()); + this.worldInfo.setBorderLerpTime(this.getWorldBorder().getTimeUntilTarget()); + this.saveHandler.saveWorldInfoWithPlayer(this.worldInfo, + this.mcServer.getConfigurationManager().getHostPlayerData()); + this.mapStorage.saveAllData(); + } + + public void scheduleBlockUpdate(BlockPos blockpos, Block block, int i, int j) { + NextTickListEntry nextticklistentry = new NextTickListEntry(blockpos, block); + nextticklistentry.setPriority(j); + if (block.getMaterial() != Material.air) { + nextticklistentry.setScheduledTime((long) i + this.worldInfo.getWorldTotalTime()); + } + + if (!this.pendingTickListEntriesHashSet.contains(nextticklistentry)) { + this.pendingTickListEntriesHashSet.add(nextticklistentry); + this.pendingTickListEntriesTreeSet.add(nextticklistentry); + } + + } + + public void scheduleUpdate(BlockPos blockpos, Block block, int i) { + this.updateBlockTick(blockpos, block, i, 0); + } + + private void sendQueuedBlockEvents() { + while (!this.field_147490_S[this.blockEventCacheIndex].isEmpty()) { + int i = this.blockEventCacheIndex; + this.blockEventCacheIndex ^= 1; + + ServerBlockEventList lst = this.field_147490_S[i]; + for (int k = 0, l = lst.size(); k < l; ++k) { + BlockEventData blockeventdata = lst.get(k); + if (this.fireBlockEvent(blockeventdata)) { + this.mcServer.getConfigurationManager().sendToAllNear((double) blockeventdata.getPosition().getX(), + (double) blockeventdata.getPosition().getY(), (double) blockeventdata.getPosition().getZ(), + 64.0D, this.provider.getDimensionId(), + new S24PacketBlockAction(blockeventdata.getPosition(), blockeventdata.getBlock(), + blockeventdata.getEventID(), blockeventdata.getEventParameter())); + } + } + + this.field_147490_S[i].clear(); + } + + } + + private void setDebugWorldSettings() { + this.worldInfo.setMapFeaturesEnabled(false); + this.worldInfo.setAllowCommands(true); + this.worldInfo.setRaining(false); + this.worldInfo.setThundering(false); + this.worldInfo.setCleanWeatherTime(1000000000); + this.worldInfo.setWorldTime(6000L); + this.worldInfo.setGameType(WorldSettings.GameType.SPECTATOR); + this.worldInfo.setHardcore(false); + this.worldInfo.setDifficulty(EnumDifficulty.PEACEFUL); + this.worldInfo.setDifficultyLocked(true); + this.getGameRules().setOrCreateGameRule("doDaylightCycle", "false"); + } + + /** + * + sends a Packet 38 (Entity Status) to all tracked players of that entity + */ + public void setEntityState(Entity entity, byte b0) { + this.getEntityTracker().func_151248_b(entity, new S19PacketEntityStatus(entity, b0)); + } + + /** + * + Sets a new spawn location by finding an uncovered block at a random (x,z) + * location in the chunk. + */ + public void setInitialSpawnLocation() { + if (this.worldInfo.getSpawnY() <= 0) { + this.worldInfo.setSpawnY(this.func_181545_F() + 1); + } + + int i = this.worldInfo.getSpawnX(); + int j = this.worldInfo.getSpawnZ(); + int k = 0; + + while (this.getGroundAboveSeaLevel(new BlockPos(i, 0, j)).getMaterial() == Material.air) { + i += this.rand.nextInt(8) - this.rand.nextInt(8); + j += this.rand.nextInt(8) - this.rand.nextInt(8); + ++k; + if (k == 10000) { + break; + } + } + + this.worldInfo.setSpawnX(i); + this.worldInfo.setSpawnZ(j); + } + + /** + * + Spawns the desired particle and sends the necessary packets to the relevant + * connected players. + */ + public void spawnParticle(EnumParticleTypes particleType, boolean longDistance, double xCoord, double yCoord, + double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, + int... parArrayOfInt) { + S2APacketParticles s2apacketparticles = new S2APacketParticles(particleType, longDistance, (float) xCoord, + (float) yCoord, (float) zCoord, (float) xOffset, (float) yOffset, (float) zOffset, + (float) particleSpeed, numberOfParticles, parArrayOfInt); + + for (int i = 0; i < this.playerEntities.size(); ++i) { + EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntities.get(i); + BlockPos blockpos = entityplayermp.getPosition(); + double d0 = blockpos.distanceSq(xCoord, yCoord, zCoord); + if (d0 <= 256.0D || longDistance && d0 <= 65536.0D) { + entityplayermp.playerNetServerHandler.sendPacket(s2apacketparticles); + } + } + + } + + /** + * + Spawns the desired particle and sends the necessary packets to the relevant + * connected players. + */ + public void spawnParticle(EnumParticleTypes particleType, double xCoord, double yCoord, double zCoord, + int numberOfParticles, double parDouble4, double parDouble5, double parDouble6, double parDouble7, + int... parArrayOfInt) { + this.spawnParticle(particleType, false, xCoord, yCoord, zCoord, numberOfParticles, parDouble4, parDouble5, + parDouble6, parDouble7, parArrayOfInt); + } + + /** + * + Runs a single tick for the world */ public void tick() { super.tick(); @@ -218,22 +766,72 @@ public class WorldServer extends World implements IThreadListener { this.sendQueuedBlockEvents(); } - public BiomeGenBase.SpawnListEntry getSpawnListEntryForTypeAt(EnumCreatureType creatureType, BlockPos pos) { - List list = this.getChunkProvider().getPossibleCreatures(creatureType, pos); - return list != null && !list.isEmpty() - ? (BiomeGenBase.SpawnListEntry) WeightedRandom.getRandomItem(this.rand, list) - : null; + /** + * + Runs through the list of updates to run and ticks them + */ + public boolean tickUpdates(boolean flag) { + if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { + return false; + } else { + int i = this.pendingTickListEntriesTreeSet.size(); + if (i != this.pendingTickListEntriesHashSet.size()) { + throw new IllegalStateException("TickNextTick list out of synch"); + } else { + if (i > 1000) { + i = 1000; + } + + for (int j = 0; j < i; ++j) { + NextTickListEntry nextticklistentry = (NextTickListEntry) this.pendingTickListEntriesTreeSet + .first(); + if (!flag && nextticklistentry.scheduledTime > this.worldInfo.getWorldTotalTime()) { + break; + } + + this.pendingTickListEntriesTreeSet.remove(nextticklistentry); + this.pendingTickListEntriesHashSet.remove(nextticklistentry); + this.pendingTickListEntriesThisTick.add(nextticklistentry); + } + + Iterator iterator = this.pendingTickListEntriesThisTick.iterator(); + + while (iterator.hasNext()) { + NextTickListEntry nextticklistentry1 = (NextTickListEntry) iterator.next(); + iterator.remove(); + byte b0 = 0; + if (this.isAreaLoaded(nextticklistentry1.position.add(-b0, -b0, -b0), + nextticklistentry1.position.add(b0, b0, b0))) { + IBlockState iblockstate = this.getBlockState(nextticklistentry1.position); + if (iblockstate.getBlock().getMaterial() != Material.air + && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { + try { + iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, + this.rand); + ++EaglerMinecraftServer.counterTileUpdate; + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, + "Exception while ticking a block"); + CrashReportCategory crashreportcategory = crashreport + .makeCategory("Block being ticked"); + CrashReportCategory.addBlockInfo(crashreportcategory, nextticklistentry1.position, + iblockstate); + throw new ReportedException(crashreport); + } + } + } else { + this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); + } + } + + this.pendingTickListEntriesThisTick.clear(); + return !this.pendingTickListEntriesTreeSet.isEmpty(); + } + } } - public boolean canCreatureTypeSpawnHere(EnumCreatureType creatureType, BiomeGenBase.SpawnListEntry spawnListEntry, - BlockPos pos) { - List list = this.getChunkProvider().getPossibleCreatures(creatureType, pos); - return list != null && !list.isEmpty() ? list.contains(spawnListEntry) : false; - } - - /**+ - * Updates the flag that indicates whether or not all players in - * the world are sleeping. + /** + * + Updates the flag that indicates whether or not all players in the world are + * sleeping. */ public void updateAllPlayersSleepingFlag() { this.allPlayersSleeping = false; @@ -255,67 +853,6 @@ public class WorldServer extends World implements IThreadListener { } - protected void wakeAllPlayers() { - this.allPlayersSleeping = false; - - for (int k = 0, l = this.playerEntities.size(); k < l; ++k) { - EntityPlayer entityplayer = this.playerEntities.get(k); - if (entityplayer.isPlayerSleeping()) { - entityplayer.wakeUpPlayer(false, false, true); - } - } - - this.resetRainAndThunder(); - } - - private void resetRainAndThunder() { - this.worldInfo.setRainTime(0); - this.worldInfo.setRaining(false); - this.worldInfo.setThunderTime(0); - this.worldInfo.setThundering(false); - } - - public boolean areAllPlayersAsleep() { - if (this.allPlayersSleeping) { - for (int k = 0, l = this.playerEntities.size(); k < l; ++k) { - EntityPlayer entityplayer = this.playerEntities.get(k); - if (entityplayer.isSpectator() || !entityplayer.isPlayerFullyAsleep()) { - return false; - } - } - - return true; - } else { - return false; - } - } - - /**+ - * Sets a new spawn location by finding an uncovered block at a - * random (x,z) location in the chunk. - */ - public void setInitialSpawnLocation() { - if (this.worldInfo.getSpawnY() <= 0) { - this.worldInfo.setSpawnY(this.func_181545_F() + 1); - } - - int i = this.worldInfo.getSpawnX(); - int j = this.worldInfo.getSpawnZ(); - int k = 0; - - while (this.getGroundAboveSeaLevel(new BlockPos(i, 0, j)).getMaterial() == Material.air) { - i += this.rand.nextInt(8) - this.rand.nextInt(8); - j += this.rand.nextInt(8) - this.rand.nextInt(8); - ++k; - if (k == 10000) { - break; - } - } - - this.worldInfo.setSpawnX(i); - this.worldInfo.setSpawnZ(j); - } - protected void updateBlocks() { super.updateBlocks(); if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { @@ -394,29 +931,6 @@ public class WorldServer extends World implements IThreadListener { } } - protected BlockPos adjustPosToNearbyEntity(BlockPos pos) { - BlockPos blockpos = this.getPrecipitationHeight(pos); - AxisAlignedBB axisalignedbb = (new AxisAlignedBB(blockpos, - new BlockPos(blockpos.getX(), this.getHeight(), blockpos.getZ()))).expand(3.0D, 3.0D, 3.0D); - List list = this.getEntitiesWithinAABB(EntityLivingBase.class, axisalignedbb, - new Predicate() { - public boolean apply(EntityLivingBase entitylivingbase) { - return entitylivingbase != null && entitylivingbase.isEntityAlive() - && WorldServer.this.canSeeSky(entitylivingbase.getPosition()); - } - }); - return !list.isEmpty() ? ((EntityLivingBase) list.get(this.rand.nextInt(list.size()))).getPosition() : blockpos; - } - - public boolean isBlockTickPending(BlockPos blockpos, Block block) { - NextTickListEntry nextticklistentry = new NextTickListEntry(blockpos, block); - return this.pendingTickListEntriesThisTick.contains(nextticklistentry); - } - - public void scheduleUpdate(BlockPos blockpos, Block block, int i) { - this.updateBlockTick(blockpos, block, i, 0); - } - public void updateBlockTick(BlockPos blockpos, Block block, int i, int j) { NextTickListEntry nextticklistentry = new NextTickListEntry(blockpos, block); byte b0 = 0; @@ -453,22 +967,8 @@ public class WorldServer extends World implements IThreadListener { } - public void scheduleBlockUpdate(BlockPos blockpos, Block block, int i, int j) { - NextTickListEntry nextticklistentry = new NextTickListEntry(blockpos, block); - nextticklistentry.setPriority(j); - if (block.getMaterial() != Material.air) { - nextticklistentry.setScheduledTime((long) i + this.worldInfo.getWorldTotalTime()); - } - - if (!this.pendingTickListEntriesHashSet.contains(nextticklistentry)) { - this.pendingTickListEntriesHashSet.add(nextticklistentry); - this.pendingTickListEntriesTreeSet.add(nextticklistentry); - } - - } - - /**+ - * Updates (and cleans up) entities and tile entities + /** + * + Updates (and cleans up) entities and tile entities */ public void updateEntities() { if (this.playerEntities.isEmpty()) { @@ -482,123 +982,9 @@ public class WorldServer extends World implements IThreadListener { super.updateEntities(); } - /**+ - * Resets the updateEntityTick field to 0 - */ - public void resetUpdateEntityTick() { - this.updateEntityTick = 0; - } - - /**+ - * Runs through the list of updates to run and ticks them - */ - public boolean tickUpdates(boolean flag) { - if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { - return false; - } else { - int i = this.pendingTickListEntriesTreeSet.size(); - if (i != this.pendingTickListEntriesHashSet.size()) { - throw new IllegalStateException("TickNextTick list out of synch"); - } else { - if (i > 1000) { - i = 1000; - } - - for (int j = 0; j < i; ++j) { - NextTickListEntry nextticklistentry = (NextTickListEntry) this.pendingTickListEntriesTreeSet - .first(); - if (!flag && nextticklistentry.scheduledTime > this.worldInfo.getWorldTotalTime()) { - break; - } - - this.pendingTickListEntriesTreeSet.remove(nextticklistentry); - this.pendingTickListEntriesHashSet.remove(nextticklistentry); - this.pendingTickListEntriesThisTick.add(nextticklistentry); - } - - Iterator iterator = this.pendingTickListEntriesThisTick.iterator(); - - while (iterator.hasNext()) { - NextTickListEntry nextticklistentry1 = (NextTickListEntry) iterator.next(); - iterator.remove(); - byte b0 = 0; - if (this.isAreaLoaded(nextticklistentry1.position.add(-b0, -b0, -b0), - nextticklistentry1.position.add(b0, b0, b0))) { - IBlockState iblockstate = this.getBlockState(nextticklistentry1.position); - if (iblockstate.getBlock().getMaterial() != Material.air - && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { - try { - iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, - this.rand); - ++EaglerMinecraftServer.counterTileUpdate; - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, - "Exception while ticking a block"); - CrashReportCategory crashreportcategory = crashreport - .makeCategory("Block being ticked"); - CrashReportCategory.addBlockInfo(crashreportcategory, nextticklistentry1.position, - iblockstate); - throw new ReportedException(crashreport); - } - } - } else { - this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); - } - } - - this.pendingTickListEntriesThisTick.clear(); - return !this.pendingTickListEntriesTreeSet.isEmpty(); - } - } - } - - public List getPendingBlockUpdates(Chunk chunk, boolean flag) { - ChunkCoordIntPair chunkcoordintpair = chunk.getChunkCoordIntPair(); - int i = (chunkcoordintpair.chunkXPos << 4) - 2; - int j = i + 16 + 2; - int k = (chunkcoordintpair.chunkZPos << 4) - 2; - int l = k + 16 + 2; - return this.func_175712_a(new StructureBoundingBox(i, 0, k, j, 256, l), flag); - } - - public List func_175712_a(StructureBoundingBox structureboundingbox, boolean flag) { - ArrayList arraylist = null; - - for (int i = 0; i < 2; ++i) { - Iterator iterator; - if (i == 0) { - iterator = this.pendingTickListEntriesTreeSet.iterator(); - } else { - iterator = this.pendingTickListEntriesThisTick.iterator(); - } - - while (iterator.hasNext()) { - NextTickListEntry nextticklistentry = (NextTickListEntry) iterator.next(); - BlockPos blockpos = nextticklistentry.position; - if (blockpos.getX() >= structureboundingbox.minX && blockpos.getX() < structureboundingbox.maxX - && blockpos.getZ() >= structureboundingbox.minZ - && blockpos.getZ() < structureboundingbox.maxZ) { - if (flag) { - this.pendingTickListEntriesHashSet.remove(nextticklistentry); - iterator.remove(); - } - - if (arraylist == null) { - arraylist = Lists.newArrayList(); - } - - arraylist.add(nextticklistentry); - } - } - } - - return arraylist; - } - - /**+ - * Will update the entity in the world if the chunk the entity - * is in is currently loaded or its forced to update. Args: - * entity, forceUpdate + /** + * + Will update the entity in the world if the chunk the entity is in is + * currently loaded or its forced to update. Args: entity, forceUpdate */ public void updateEntityWithOptionalForce(Entity entity, boolean flag) { if (!this.canSpawnAnimals() && (entity instanceof EntityAnimal || entity instanceof EntityWaterMob)) { @@ -612,336 +998,8 @@ public class WorldServer extends World implements IThreadListener { super.updateEntityWithOptionalForce(entity, flag); } - private boolean canSpawnNPCs() { - return this.mcServer.getCanSpawnNPCs(); - } - - private boolean canSpawnAnimals() { - return this.mcServer.getCanSpawnAnimals(); - } - - /**+ - * Creates the chunk provider for this world. Called in the - * constructor. Retrieves provider from worldProvider? - */ - protected IChunkProvider createChunkProvider() { - IChunkLoader ichunkloader = this.saveHandler.getChunkLoader(this.provider); - this.theChunkProviderServer = new ChunkProviderServer(this, ichunkloader, this.provider.createChunkGenerator()); - return this.theChunkProviderServer; - } - - /**+ - * Returns all the tile entities located between the given - * coordinates - */ - public List getTileEntitiesIn(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - ArrayList arraylist = Lists.newArrayList(); - - for (int i = 0; i < this.loadedTileEntityList.size(); ++i) { - TileEntity tileentity = (TileEntity) this.loadedTileEntityList.get(i); - BlockPos blockpos = tileentity.getPos(); - if (blockpos.getX() >= minX && blockpos.getY() >= minY && blockpos.getZ() >= minZ && blockpos.getX() < maxX - && blockpos.getY() < maxY && blockpos.getZ() < maxZ) { - arraylist.add(tileentity); - } - } - - return arraylist; - } - - public boolean isBlockModifiable(EntityPlayer entityplayer, BlockPos blockpos) { - return !this.mcServer.isBlockProtected(this, blockpos, entityplayer) - && this.getWorldBorder().contains(blockpos); - } - - public void initialize(WorldSettings worldsettings) { - if (!this.worldInfo.isInitialized()) { - try { - this.createSpawnPosition(worldsettings); - if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { - this.setDebugWorldSettings(); - } - - super.initialize(worldsettings); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Exception initializing level"); - - try { - this.addWorldInfoToCrashReport(crashreport); - } catch (Throwable var5) { - ; - } - - throw new ReportedException(crashreport); - } - - this.worldInfo.setServerInitialized(true); - } - - } - - private void setDebugWorldSettings() { - this.worldInfo.setMapFeaturesEnabled(false); - this.worldInfo.setAllowCommands(true); - this.worldInfo.setRaining(false); - this.worldInfo.setThundering(false); - this.worldInfo.setCleanWeatherTime(1000000000); - this.worldInfo.setWorldTime(6000L); - this.worldInfo.setGameType(WorldSettings.GameType.SPECTATOR); - this.worldInfo.setHardcore(false); - this.worldInfo.setDifficulty(EnumDifficulty.PEACEFUL); - this.worldInfo.setDifficultyLocked(true); - this.getGameRules().setOrCreateGameRule("doDaylightCycle", "false"); - } - - /**+ - * creates a spawn position at random within 256 blocks of 0,0 - */ - private void createSpawnPosition(WorldSettings parWorldSettings) { - if (!this.provider.canRespawnHere()) { - this.worldInfo.setSpawn(BlockPos.ORIGIN.up(this.provider.getAverageGroundLevel())); - } else if (this.worldInfo.getTerrainType() == WorldType.DEBUG_WORLD) { - this.worldInfo.setSpawn(BlockPos.ORIGIN.up()); - } else { - this.findingSpawnPoint = true; - WorldChunkManager worldchunkmanager = this.provider.getWorldChunkManager(); - List list = worldchunkmanager.getBiomesToSpawnIn(); - EaglercraftRandom random = new EaglercraftRandom(this.getSeed()); - BlockPos blockpos = worldchunkmanager.findBiomePosition(0, 0, 256, list, random); - int i = 0; - int j = this.provider.getAverageGroundLevel(); - int k = 0; - if (blockpos != null) { - i = blockpos.getX(); - k = blockpos.getZ(); - } else { - logger.warn("Unable to find spawn biome"); - } - - int l = 0; - - while (!this.provider.canCoordinateBeSpawn(i, k)) { - i += random.nextInt(64) - random.nextInt(64); - k += random.nextInt(64) - random.nextInt(64); - ++l; - if (l == 1000) { - break; - } - } - - this.worldInfo.setSpawn(new BlockPos(i, j, k)); - this.findingSpawnPoint = false; - if (parWorldSettings.isBonusChestEnabled()) { - this.createBonusChest(); - } - - } - } - - /**+ - * Creates the bonus chest in the world. - */ - protected void createBonusChest() { - WorldGeneratorBonusChest worldgeneratorbonuschest = new WorldGeneratorBonusChest(bonusChestContent, 10); - - for (int i = 0; i < 10; ++i) { - int j = this.worldInfo.getSpawnX() + this.rand.nextInt(6) - this.rand.nextInt(6); - int k = this.worldInfo.getSpawnZ() + this.rand.nextInt(6) - this.rand.nextInt(6); - BlockPos blockpos = this.getTopSolidOrLiquidBlock(new BlockPos(j, 0, k)).up(); - if (worldgeneratorbonuschest.generate(this, this.rand, blockpos)) { - break; - } - } - - } - - /**+ - * Returns null for anything other than the End - */ - public BlockPos getSpawnCoordinate() { - return this.provider.getSpawnCoordinate(); - } - - /**+ - * Saves all chunks to disk while updating progress bar. - */ - public void saveAllChunks(boolean progressCallback, IProgressUpdate parIProgressUpdate) throws MinecraftException { - if (this.chunkProvider.canSave()) { - if (parIProgressUpdate != null) { - parIProgressUpdate.displaySavingString("Saving level"); - } - - this.saveLevel(); - if (parIProgressUpdate != null) { - parIProgressUpdate.displayLoadingString("Saving chunks"); - } - - this.chunkProvider.saveChunks(progressCallback, parIProgressUpdate); - - List lst = Lists.newArrayList(this.theChunkProviderServer.func_152380_a()); - for (int i = 0, l = lst.size(); i < l; ++i) { - Chunk chunk = lst.get(i); - if (chunk != null && !this.thePlayerManager.hasPlayerInstance(chunk.xPosition, chunk.zPosition)) { - this.theChunkProviderServer.dropChunk(chunk.xPosition, chunk.zPosition); - } - } - - } - } - - /**+ - * saves chunk data - currently only called during execution of - * the Save All command - */ - public void saveChunkData() { - if (this.chunkProvider.canSave()) { - this.chunkProvider.saveExtraData(); - } - } - - /**+ - * Saves the chunks to disk. - */ - protected void saveLevel() throws MinecraftException { - this.checkSessionLock(); - this.worldInfo.setBorderSize(this.getWorldBorder().getDiameter()); - this.worldInfo.getBorderCenterX(this.getWorldBorder().getCenterX()); - this.worldInfo.getBorderCenterZ(this.getWorldBorder().getCenterZ()); - this.worldInfo.setBorderSafeZone(this.getWorldBorder().getDamageBuffer()); - this.worldInfo.setBorderDamagePerBlock(this.getWorldBorder().getDamageAmount()); - this.worldInfo.setBorderWarningDistance(this.getWorldBorder().getWarningDistance()); - this.worldInfo.setBorderWarningTime(this.getWorldBorder().getWarningTime()); - this.worldInfo.setBorderLerpTarget(this.getWorldBorder().getTargetSize()); - this.worldInfo.setBorderLerpTime(this.getWorldBorder().getTimeUntilTarget()); - this.saveHandler.saveWorldInfoWithPlayer(this.worldInfo, - this.mcServer.getConfigurationManager().getHostPlayerData()); - this.mapStorage.saveAllData(); - } - - protected void onEntityAdded(Entity entity) { - super.onEntityAdded(entity); - this.entitiesById.addKey(entity.getEntityId(), entity); - this.entitiesByUuid.put(entity.getUniqueID(), entity); - Entity[] aentity = entity.getParts(); - if (aentity != null) { - for (int i = 0; i < aentity.length; ++i) { - this.entitiesById.addKey(aentity[i].getEntityId(), aentity[i]); - } - } - - } - - protected void onEntityRemoved(Entity entity) { - super.onEntityRemoved(entity); - this.entitiesById.removeObject(entity.getEntityId()); - this.entitiesByUuid.remove(entity.getUniqueID()); - Entity[] aentity = entity.getParts(); - if (aentity != null) { - for (int i = 0; i < aentity.length; ++i) { - this.entitiesById.removeObject(aentity[i].getEntityId()); - } - } - - } - - /**+ - * adds a lightning bolt to the list of lightning bolts in this - * world. - */ - public boolean addWeatherEffect(Entity entity) { - if (super.addWeatherEffect(entity)) { - this.mcServer.getConfigurationManager().sendToAllNear(entity.posX, entity.posY, entity.posZ, 512.0D, - this.provider.getDimensionId(), new S2CPacketSpawnGlobalEntity(entity)); - return true; - } else { - return false; - } - } - - /**+ - * sends a Packet 38 (Entity Status) to all tracked players of - * that entity - */ - public void setEntityState(Entity entity, byte b0) { - this.getEntityTracker().func_151248_b(entity, new S19PacketEntityStatus(entity, b0)); - } - - /**+ - * returns a new explosion. Does initiation (at time of writing - * Explosion is not finished) - */ - public Explosion newExplosion(Entity entity, double d0, double d1, double d2, float f, boolean flag, - boolean flag1) { - Explosion explosion = new Explosion(this, entity, d0, d1, d2, f, flag, flag1); - explosion.doExplosionA(); - explosion.doExplosionB(false); - if (!flag1) { - explosion.func_180342_d(); - } - - List lst = this.playerEntities; - for (int i = 0, l = lst.size(); i < l; ++i) { - EntityPlayer entityplayer = lst.get(i); - if (entityplayer.getDistanceSq(d0, d1, d2) < 4096.0D) { - ((EntityPlayerMP) entityplayer).playerNetServerHandler - .sendPacket(new S27PacketExplosion(d0, d1, d2, f, explosion.getAffectedBlockPositions(), - (Vec3) explosion.getPlayerKnockbackMap().get(entityplayer))); - } - } - - return explosion; - } - - public void addBlockEvent(BlockPos blockpos, Block block, int i, int j) { - BlockEventData blockeventdata = new BlockEventData(blockpos, block, i, j); - - ServerBlockEventList lst = this.field_147490_S[this.blockEventCacheIndex]; - for (int k = 0, l = lst.size(); k < l; ++k) { - if (lst.get(k).equals(blockeventdata)) { - return; - } - } - - this.field_147490_S[this.blockEventCacheIndex].add(blockeventdata); - } - - private void sendQueuedBlockEvents() { - while (!this.field_147490_S[this.blockEventCacheIndex].isEmpty()) { - int i = this.blockEventCacheIndex; - this.blockEventCacheIndex ^= 1; - - ServerBlockEventList lst = this.field_147490_S[i]; - for (int k = 0, l = lst.size(); k < l; ++k) { - BlockEventData blockeventdata = lst.get(k); - if (this.fireBlockEvent(blockeventdata)) { - this.mcServer.getConfigurationManager().sendToAllNear((double) blockeventdata.getPosition().getX(), - (double) blockeventdata.getPosition().getY(), (double) blockeventdata.getPosition().getZ(), - 64.0D, this.provider.getDimensionId(), - new S24PacketBlockAction(blockeventdata.getPosition(), blockeventdata.getBlock(), - blockeventdata.getEventID(), blockeventdata.getEventParameter())); - } - } - - this.field_147490_S[i].clear(); - } - - } - - private boolean fireBlockEvent(BlockEventData event) { - IBlockState iblockstate = this.getBlockState(event.getPosition()); - return iblockstate.getBlock() == event.getBlock() ? iblockstate.getBlock().onBlockEventReceived(this, - event.getPosition(), iblockstate, event.getEventID(), event.getEventParameter()) : false; - } - - /**+ - * Syncs all changes to disk and wait for completion. - */ - public void flush() { - this.saveHandler.flush(); - } - - /**+ - * Updates all weather states. + /** + * + Updates all weather states. */ protected void updateWeather() { boolean flag = this.isRaining(); @@ -971,72 +1029,17 @@ public class WorldServer extends World implements IThreadListener { } - protected int getRenderDistanceChunks() { - return this.mcServer.getConfigurationManager().getViewDistance(); - } - - public MinecraftServer getMinecraftServer() { - return this.mcServer; - } - - /**+ - * Gets the EntityTracker - */ - public EntityTracker getEntityTracker() { - return this.theEntityTracker; - } - - public PlayerManager getPlayerManager() { - return this.thePlayerManager; - } - - public Teleporter getDefaultTeleporter() { - return this.worldTeleporter; - } - - /**+ - * Spawns the desired particle and sends the necessary packets - * to the relevant connected players. - */ - public void spawnParticle(EnumParticleTypes particleType, double xCoord, double yCoord, double zCoord, - int numberOfParticles, double parDouble4, double parDouble5, double parDouble6, double parDouble7, - int... parArrayOfInt) { - this.spawnParticle(particleType, false, xCoord, yCoord, zCoord, numberOfParticles, parDouble4, parDouble5, - parDouble6, parDouble7, parArrayOfInt); - } - - /**+ - * Spawns the desired particle and sends the necessary packets - * to the relevant connected players. - */ - public void spawnParticle(EnumParticleTypes particleType, boolean longDistance, double xCoord, double yCoord, - double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, - int... parArrayOfInt) { - S2APacketParticles s2apacketparticles = new S2APacketParticles(particleType, longDistance, (float) xCoord, - (float) yCoord, (float) zCoord, (float) xOffset, (float) yOffset, (float) zOffset, - (float) particleSpeed, numberOfParticles, parArrayOfInt); - - for (int i = 0; i < this.playerEntities.size(); ++i) { - EntityPlayerMP entityplayermp = (EntityPlayerMP) this.playerEntities.get(i); - BlockPos blockpos = entityplayermp.getPosition(); - double d0 = blockpos.distanceSq(xCoord, yCoord, zCoord); - if (d0 <= 256.0D || longDistance && d0 <= 65536.0D) { - entityplayermp.playerNetServerHandler.sendPacket(s2apacketparticles); + protected void wakeAllPlayers() { + this.allPlayersSleeping = false; + double playerCountSize = (this.playerEntities.size() / 2); + double playerCountSizeRounded = Math.ceil(playerCountSize); + for (int k = 0, l = (int) playerCountSizeRounded; k < l; ++k) { + EntityPlayer entityplayer = this.playerEntities.get(k); + if (entityplayer.isPlayerSleeping()) { + entityplayer.wakeUpPlayer(false, false, true); } } - } - - public Entity getEntityFromUuid(EaglercraftUUID uuid) { - return (Entity) this.entitiesByUuid.get(uuid); - } - - public void addScheduledTask(Runnable runnable) { - this.mcServer.addScheduledTask(runnable); - } - - static class ServerBlockEventList extends ArrayList { - private ServerBlockEventList() { - } + this.resetRainAndThunder(); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldServerMulti.java b/src/game/java/net/minecraft/world/WorldServerMulti.java index 9627514e..2321bd76 100644 --- a/src/game/java/net/minecraft/world/WorldServerMulti.java +++ b/src/game/java/net/minecraft/world/WorldServerMulti.java @@ -7,22 +7,25 @@ import net.minecraft.world.border.WorldBorder; import net.minecraft.world.storage.DerivedWorldInfo; import net.minecraft.world.storage.ISaveHandler; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,26 +37,10 @@ public class WorldServerMulti extends WorldServer { super(server, saveHandlerIn, new DerivedWorldInfo(delegate.getWorldInfo()), dimensionId); this.delegate = delegate; delegate.getWorldBorder().addListener(new IBorderListener() { - public void onSizeChanged(WorldBorder var1, double d0) { - WorldServerMulti.this.getWorldBorder().setTransition(d0); - } - - public void onTransitionStarted(WorldBorder var1, double d0, double d1, long i) { - WorldServerMulti.this.getWorldBorder().setTransition(d0, d1, i); - } - public void onCenterChanged(WorldBorder var1, double d0, double d1) { WorldServerMulti.this.getWorldBorder().setCenter(d0, d1); } - public void onWarningTimeChanged(WorldBorder var1, int i) { - WorldServerMulti.this.getWorldBorder().setWarningTime(i); - } - - public void onWarningDistanceChanged(WorldBorder var1, int i) { - WorldServerMulti.this.getWorldBorder().setWarningDistance(i); - } - public void onDamageAmountChanged(WorldBorder var1, double d0) { WorldServerMulti.this.getWorldBorder().setDamageAmount(d0); } @@ -61,13 +48,23 @@ public class WorldServerMulti extends WorldServer { public void onDamageBufferChanged(WorldBorder var1, double d0) { WorldServerMulti.this.getWorldBorder().setDamageBuffer(d0); } - }); - } - /**+ - * Saves the chunks to disk. - */ - protected void saveLevel() throws MinecraftException { + public void onSizeChanged(WorldBorder var1, double d0) { + WorldServerMulti.this.getWorldBorder().setTransition(d0); + } + + public void onTransitionStarted(WorldBorder var1, double d0, double d1, long i) { + WorldServerMulti.this.getWorldBorder().setTransition(d0, d1, i); + } + + public void onWarningDistanceChanged(WorldBorder var1, int i) { + WorldServerMulti.this.getWorldBorder().setWarningDistance(i); + } + + public void onWarningTimeChanged(WorldBorder var1, int i) { + WorldServerMulti.this.getWorldBorder().setWarningTime(i); + } + }); } public World init() { @@ -85,4 +82,10 @@ public class WorldServerMulti extends WorldServer { return this; } + + /** + * + Saves the chunks to disk. + */ + protected void saveLevel() throws MinecraftException { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldSettings.java b/src/game/java/net/minecraft/world/WorldSettings.java index 46ee5b36..e511673b 100644 --- a/src/game/java/net/minecraft/world/WorldSettings.java +++ b/src/game/java/net/minecraft/world/WorldSettings.java @@ -3,184 +3,36 @@ package net.minecraft.world; import net.minecraft.entity.player.PlayerCapabilities; import net.minecraft.world.storage.WorldInfo; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public final class WorldSettings { - private final long seed; - private final WorldSettings.GameType theGameType; - private final boolean mapFeaturesEnabled; - private final boolean hardcoreEnabled; - private final WorldType terrainType; - private boolean commandsAllowed; - private boolean bonusChestEnabled; - private String worldName; - - public WorldSettings(long seedIn, WorldSettings.GameType gameType, boolean enableMapFeatures, boolean hardcoreMode, - WorldType worldTypeIn) { - this.worldName = ""; - this.seed = seedIn; - this.theGameType = gameType; - this.mapFeaturesEnabled = enableMapFeatures; - this.hardcoreEnabled = hardcoreMode; - this.terrainType = worldTypeIn; - } - - public WorldSettings(WorldInfo info) { - this(info.getSeed(), info.getGameType(), info.isMapFeaturesEnabled(), info.isHardcoreModeEnabled(), - info.getTerrainType()); - } - - /**+ - * Enables the bonus chest. - */ - public WorldSettings enableBonusChest() { - this.bonusChestEnabled = true; - return this; - } - - /**+ - * Enables Commands (cheats). - */ - public WorldSettings enableCommands() { - this.commandsAllowed = true; - return this; - } - - public WorldSettings setWorldName(String name) { - this.worldName = name; - return this; - } - - /**+ - * Returns true if the Bonus Chest is enabled. - */ - public boolean isBonusChestEnabled() { - return this.bonusChestEnabled; - } - - /**+ - * Returns the seed for the world. - */ - public long getSeed() { - return this.seed; - } - - /**+ - * Gets the game type. - */ - public WorldSettings.GameType getGameType() { - return this.theGameType; - } - - /**+ - * Returns true if hardcore mode is enabled, otherwise false - */ - public boolean getHardcoreEnabled() { - return this.hardcoreEnabled; - } - - /**+ - * Get whether the map features (e.g. strongholds) generation is - * enabled or disabled. - */ - public boolean isMapFeaturesEnabled() { - return this.mapFeaturesEnabled; - } - - public WorldType getTerrainType() { - return this.terrainType; - } - - /**+ - * Returns true if Commands (cheats) are allowed. - */ - public boolean areCommandsAllowed() { - return this.commandsAllowed; - } - - /**+ - * Gets the GameType by ID - */ - public static WorldSettings.GameType getGameTypeById(int id) { - return WorldSettings.GameType.getByID(id); - } - - public String getWorldName() { - return this.worldName; - } - public static enum GameType { NOT_SET(-1, ""), SURVIVAL(0, "survival"), CREATIVE(1, "creative"), ADVENTURE(2, "adventure"), SPECTATOR(3, "spectator"); public static final GameType[] _VALUES = values(); - int id; - String name; - - private GameType(int typeId, String nameIn) { - this.id = typeId; - this.name = nameIn; - } - - public int getID() { - return this.id; - } - - public String getName() { - return this.name; - } - - public void configurePlayerCapabilities(PlayerCapabilities capabilities) { - if (this == CREATIVE) { - capabilities.allowFlying = true; - capabilities.isCreativeMode = true; - capabilities.disableDamage = true; - } else if (this == SPECTATOR) { - capabilities.allowFlying = true; - capabilities.isCreativeMode = false; - capabilities.disableDamage = true; - capabilities.isFlying = true; - } else { - capabilities.allowFlying = false; - capabilities.isCreativeMode = false; - capabilities.disableDamage = false; - capabilities.isFlying = false; - } - - capabilities.allowEdit = !this.isAdventure(); - } - - public boolean isAdventure() { - return this == ADVENTURE || this == SPECTATOR; - } - - public boolean isCreative() { - return this == CREATIVE; - } - - public boolean isSurvivalOrAdventure() { - return this == SURVIVAL || this == ADVENTURE; - } - public static WorldSettings.GameType getByID(int idIn) { WorldSettings.GameType[] types = _VALUES; for (int i = 0; i < types.length; ++i) { @@ -204,5 +56,159 @@ public final class WorldSettings { return SURVIVAL; } + + int id; + + String name; + + private GameType(int typeId, String nameIn) { + this.id = typeId; + this.name = nameIn; + } + + public void configurePlayerCapabilities(PlayerCapabilities capabilities) { + if (this == CREATIVE) { + capabilities.allowFlying = true; + capabilities.isCreativeMode = true; + capabilities.disableDamage = true; + } else if (this == SPECTATOR) { + capabilities.allowFlying = true; + capabilities.isCreativeMode = false; + capabilities.disableDamage = true; + capabilities.isFlying = true; + } else { + capabilities.allowFlying = false; + capabilities.isCreativeMode = false; + capabilities.disableDamage = false; + capabilities.isFlying = false; + } + + capabilities.allowEdit = !this.isAdventure(); + } + + public int getID() { + return this.id; + } + + public String getName() { + return this.name; + } + + public boolean isAdventure() { + return this == ADVENTURE || this == SPECTATOR; + } + + public boolean isCreative() { + return this == CREATIVE; + } + + public boolean isSurvivalOrAdventure() { + return this == SURVIVAL || this == ADVENTURE; + } + } + + /** + * + Gets the GameType by ID + */ + public static WorldSettings.GameType getGameTypeById(int id) { + return WorldSettings.GameType.getByID(id); + } + + private final long seed; + private final WorldSettings.GameType theGameType; + private final boolean mapFeaturesEnabled; + private final boolean hardcoreEnabled; + private final WorldType terrainType; + private boolean commandsAllowed; + + private boolean bonusChestEnabled; + + private String worldName; + + public WorldSettings(long seedIn, WorldSettings.GameType gameType, boolean enableMapFeatures, boolean hardcoreMode, + WorldType worldTypeIn) { + this.worldName = ""; + this.seed = seedIn; + this.theGameType = gameType; + this.mapFeaturesEnabled = enableMapFeatures; + this.hardcoreEnabled = hardcoreMode; + this.terrainType = worldTypeIn; + } + + public WorldSettings(WorldInfo info) { + this(info.getSeed(), info.getGameType(), info.isMapFeaturesEnabled(), info.isHardcoreModeEnabled(), + info.getTerrainType()); + } + + /** + * + Returns true if Commands (cheats) are allowed. + */ + public boolean areCommandsAllowed() { + return this.commandsAllowed; + } + + /** + * + Enables the bonus chest. + */ + public WorldSettings enableBonusChest() { + this.bonusChestEnabled = true; + return this; + } + + /** + * + Enables Commands (cheats). + */ + public WorldSettings enableCommands() { + this.commandsAllowed = true; + return this; + } + + /** + * + Gets the game type. + */ + public WorldSettings.GameType getGameType() { + return this.theGameType; + } + + /** + * + Returns true if hardcore mode is enabled, otherwise false + */ + public boolean getHardcoreEnabled() { + return this.hardcoreEnabled; + } + + /** + * + Returns the seed for the world. + */ + public long getSeed() { + return this.seed; + } + + public WorldType getTerrainType() { + return this.terrainType; + } + + public String getWorldName() { + return this.worldName; + } + + /** + * + Returns true if the Bonus Chest is enabled. + */ + public boolean isBonusChestEnabled() { + return this.bonusChestEnabled; + } + + /** + * + Get whether the map features (e.g. strongholds) generation is enabled or + * disabled. + */ + public boolean isMapFeaturesEnabled() { + return this.mapFeaturesEnabled; + } + + public WorldSettings setWorldName(String name) { + this.worldName = name; + return this; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/WorldType.java b/src/game/java/net/minecraft/world/WorldType.java index 590daacf..d7a0f2ba 100644 --- a/src/game/java/net/minecraft/world/WorldType.java +++ b/src/game/java/net/minecraft/world/WorldType.java @@ -1,57 +1,72 @@ package net.minecraft.world; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldType { - /**+ - * List of world types. + /** + * + List of world types. */ public static final WorldType[] worldTypes = new WorldType[16]; - /**+ - * Default world type. + /** + * + Default world type. */ public static final WorldType DEFAULT = (new WorldType(0, "default", 1)).setVersioned(); - /**+ - * Flat world type. + /** + * + Flat world type. */ public static final WorldType FLAT = new WorldType(1, "flat"); - /**+ - * Large Biome world Type. + /** + * + Large Biome world Type. */ public static final WorldType LARGE_BIOMES = new WorldType(2, "largeBiomes"); - /**+ - * amplified world type + /** + * + amplified world type */ public static final WorldType AMPLIFIED = (new WorldType(3, "amplified")).setNotificationData(); public static final WorldType CUSTOMIZED = new WorldType(4, "customized"); public static final WorldType DEBUG_WORLD = new WorldType(5, "debug_all_block_states"); - /**+ - * Default (1.1) world type. + /** + * + Default (1.1) world type. */ public static final WorldType DEFAULT_1_1 = (new WorldType(8, "default_1_1", 0)).setCanBeCreated(false); + + public static WorldType parseWorldType(String type) { + for (int i = 0; i < worldTypes.length; ++i) { + if (worldTypes[i] != null && worldTypes[i].worldType.equalsIgnoreCase(type)) { + return worldTypes[i]; + } + } + + return null; + } + private final int worldTypeId; private final String worldType; private final int generatorVersion; private boolean canBeCreated; private boolean isWorldTypeVersioned; + private boolean hasNotificationData; private WorldType(int id, String name) { @@ -66,92 +81,80 @@ public class WorldType { worldTypes[id] = this; } - public String getWorldTypeName() { - return this.worldType; - } - - /**+ - * Gets the translation key for the name of this world type. - */ - public String getTranslateName() { - return "generator." + this.worldType; - } - public String func_151359_c() { return this.getTranslateName() + ".info"; } - /**+ - * Returns generatorVersion. + /** + * + Gets whether this WorldType can be used to generate a new world. + */ + public boolean getCanBeCreated() { + return this.canBeCreated; + } + + /** + * + Returns generatorVersion. */ public int getGeneratorVersion() { return this.generatorVersion; } + /** + * + Gets the translation key for the name of this world type. + */ + public String getTranslateName() { + return "generator." + this.worldType; + } + public WorldType getWorldTypeForGeneratorVersion(int version) { return this == DEFAULT && version == 0 ? DEFAULT_1_1 : this; } - /**+ - * Sets canBeCreated to the provided value, and returns this. + public int getWorldTypeID() { + return this.worldTypeId; + } + + public String getWorldTypeName() { + return this.worldType; + } + + /** + * + Returns true if this world Type has a version associated with it. + */ + public boolean isVersioned() { + return this.isWorldTypeVersioned; + } + + /** + * + Sets canBeCreated to the provided value, and returns this. */ private WorldType setCanBeCreated(boolean enable) { this.canBeCreated = enable; return this; } - /**+ - * Gets whether this WorldType can be used to generate a new - * world. + /** + * + enables the display of generator.[worldtype].info message on the customize + * world menu */ - public boolean getCanBeCreated() { - return this.canBeCreated; + private WorldType setNotificationData() { + this.hasNotificationData = true; + return this; } - /**+ - * Flags this world type as having an associated version. + /** + * + Flags this world type as having an associated version. */ private WorldType setVersioned() { this.isWorldTypeVersioned = true; return this; } - /**+ - * Returns true if this world Type has a version associated with - * it. - */ - public boolean isVersioned() { - return this.isWorldTypeVersioned; - } - - public static WorldType parseWorldType(String type) { - for (int i = 0; i < worldTypes.length; ++i) { - if (worldTypes[i] != null && worldTypes[i].worldType.equalsIgnoreCase(type)) { - return worldTypes[i]; - } - } - - return null; - } - - public int getWorldTypeID() { - return this.worldTypeId; - } - - /**+ - * returns true if selecting this worldtype from the customize - * menu should display the generator.[worldtype].info message + /** + * + returns true if selecting this worldtype from the customize menu should + * display the generator.[worldtype].info message */ public boolean showWorldInfoNotice() { return this.hasNotificationData; } - - /**+ - * enables the display of generator.[worldtype].info message on - * the customize world menu - */ - private WorldType setNotificationData() { - this.hasNotificationData = true; - return this; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeCache.java b/src/game/java/net/minecraft/world/biome/BiomeCache.java index f5d13202..249d7cba 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeCache.java +++ b/src/game/java/net/minecraft/world/biome/BiomeCache.java @@ -1,40 +1,65 @@ package net.minecraft.world.biome; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.server.MinecraftServer; import net.minecraft.util.LongHashMap; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BiomeCache { + public class Block { + public float[] rainfallValues = new float[256]; + public BiomeGenBase[] biomes = new BiomeGenBase[256]; + public int xPosition; + public int zPosition; + public long lastAccessTime; + + public Block(int x, int z) { + this.xPosition = x; + this.zPosition = z; + BiomeCache.this.chunkManager.getRainfall(this.rainfallValues, x << 4, z << 4, 16, 16); + BiomeCache.this.chunkManager.getBiomeGenAt(this.biomes, x << 4, z << 4, 16, 16, false); + } + + public BiomeGenBase getBiomeGenAt(int x, int z) { + return this.biomes[x & 15 | (z & 15) << 4]; + } + } + private final WorldChunkManager chunkManager; private long lastCleanupTime; - /**+ - * The map of keys to BiomeCacheBlocks. Keys are based on the - * chunk x, z coordinates as (x | z << 32). + /** + * + The map of keys to BiomeCacheBlocks. Keys are based on the chunk x, z + * coordinates as (x | z << 32). */ private LongHashMap cacheMap = new LongHashMap(); - /**+ - * The list of cached BiomeCacheBlocks + + /** + * + The list of cached BiomeCacheBlocks */ private List cache = Lists.newArrayList(); @@ -42,32 +67,9 @@ public class BiomeCache { this.chunkManager = chunkManagerIn; } - /**+ - * Returns a biome cache block at location specified. - */ - public BiomeCache.Block getBiomeCacheBlock(int x, int z) { - x = x >> 4; - z = z >> 4; - long i = (long) x & 4294967295L | ((long) z & 4294967295L) << 32; - BiomeCache.Block biomecache$block = (BiomeCache.Block) this.cacheMap.getValueByKey(i); - if (biomecache$block == null) { - biomecache$block = new BiomeCache.Block(x, z); - this.cacheMap.add(i, biomecache$block); - this.cache.add(biomecache$block); - } - - biomecache$block.lastAccessTime = MinecraftServer.getCurrentTimeMillis(); - return biomecache$block; - } - - public BiomeGenBase func_180284_a(int x, int z, BiomeGenBase parBiomeGenBase) { - BiomeGenBase biomegenbase = this.getBiomeCacheBlock(x, z).getBiomeGenAt(x, z); - return biomegenbase == null ? parBiomeGenBase : biomegenbase; - } - - /**+ - * Removes BiomeCacheBlocks from this cache that haven't been - * accessed in at least 30 seconds. + /** + * + Removes BiomeCacheBlocks from this cache that haven't been accessed in at + * least 30 seconds. */ public void cleanupCache() { long i = MinecraftServer.getCurrentTimeMillis(); @@ -89,30 +91,34 @@ public class BiomeCache { } - /**+ - * Returns the array of cached biome types in the - * BiomeCacheBlock at the given location. + public BiomeGenBase func_180284_a(int x, int z, BiomeGenBase parBiomeGenBase) { + BiomeGenBase biomegenbase = this.getBiomeCacheBlock(x, z).getBiomeGenAt(x, z); + return biomegenbase == null ? parBiomeGenBase : biomegenbase; + } + + /** + * + Returns a biome cache block at location specified. + */ + public BiomeCache.Block getBiomeCacheBlock(int x, int z) { + x = x >> 4; + z = z >> 4; + long i = (long) x & 4294967295L | ((long) z & 4294967295L) << 32; + BiomeCache.Block biomecache$block = (BiomeCache.Block) this.cacheMap.getValueByKey(i); + if (biomecache$block == null) { + biomecache$block = new BiomeCache.Block(x, z); + this.cacheMap.add(i, biomecache$block); + this.cache.add(biomecache$block); + } + + biomecache$block.lastAccessTime = MinecraftServer.getCurrentTimeMillis(); + return biomecache$block; + } + + /** + * + Returns the array of cached biome types in the BiomeCacheBlock at the given + * location. */ public BiomeGenBase[] getCachedBiomes(int x, int z) { return this.getBiomeCacheBlock(x, z).biomes; } - - public class Block { - public float[] rainfallValues = new float[256]; - public BiomeGenBase[] biomes = new BiomeGenBase[256]; - public int xPosition; - public int zPosition; - public long lastAccessTime; - - public Block(int x, int z) { - this.xPosition = x; - this.zPosition = z; - BiomeCache.this.chunkManager.getRainfall(this.rainfallValues, x << 4, z << 4, 16, 16); - BiomeCache.this.chunkManager.getBiomeGenAt(this.biomes, x << 4, z << 4, 16, 16, false); - } - - public BiomeGenBase getBiomeGenAt(int x, int z) { - return this.biomes[x & 15 | (z & 15) << 4]; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeColorHelper.java b/src/game/java/net/minecraft/world/biome/BiomeColorHelper.java index 04c2eee4..af04f69b 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeColorHelper.java +++ b/src/game/java/net/minecraft/world/biome/BiomeColorHelper.java @@ -3,27 +3,34 @@ package net.minecraft.world.biome; import net.minecraft.util.BlockPos; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BiomeColorHelper { + interface ColorResolver { + int getColorAtPos(BiomeGenBase var1, BlockPos var2); + } + private static final BiomeColorHelper.ColorResolver field_180291_a = new BiomeColorHelper.ColorResolver() { public int getColorAtPos(BiomeGenBase blockPosition, BlockPos parBlockPos) { return blockPosition.getGrassColorAtPos(parBlockPos); @@ -34,6 +41,7 @@ public class BiomeColorHelper { return biomegenbase.getFoliageColorAtPos(blockpos); } }; + private static final BiomeColorHelper.ColorResolver field_180290_c = new BiomeColorHelper.ColorResolver() { public int getColorAtPos(BiomeGenBase biomegenbase, BlockPos var2) { return biomegenbase.waterColorMultiplier; @@ -58,19 +66,15 @@ public class BiomeColorHelper { return (i / 9 & 255) << 16 | (j / 9 & 255) << 8 | k / 9 & 255; } - public static int getGrassColorAtPos(IBlockAccess parIBlockAccess, BlockPos parBlockPos) { - return func_180285_a(parIBlockAccess, parBlockPos, field_180291_a); - } - public static int getFoliageColorAtPos(IBlockAccess parIBlockAccess, BlockPos parBlockPos) { return func_180285_a(parIBlockAccess, parBlockPos, field_180289_b); } + public static int getGrassColorAtPos(IBlockAccess parIBlockAccess, BlockPos parBlockPos) { + return func_180285_a(parIBlockAccess, parBlockPos, field_180291_a); + } + public static int getWaterColorAtPos(IBlockAccess parIBlockAccess, BlockPos parBlockPos) { return func_180285_a(parIBlockAccess, parBlockPos, field_180290_c); } - - interface ColorResolver { - int getColorAtPos(BiomeGenBase var1, BlockPos var2); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeDecorator.java b/src/game/java/net/minecraft/world/biome/BiomeDecorator.java index 95487b54..75aab893 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeDecorator.java +++ b/src/game/java/net/minecraft/world/biome/BiomeDecorator.java @@ -23,22 +23,25 @@ import net.minecraft.world.gen.feature.WorldGenSand; import net.minecraft.world.gen.feature.WorldGenWaterlily; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,16 +52,16 @@ public class BiomeDecorator { protected EaglercraftRandom randomGenerator; protected BlockPos field_180294_c; protected ChunkProviderSettings chunkProviderSettings; - /**+ - * The clay generator. + /** + * + The clay generator. */ protected WorldGenerator clayGen = new WorldGenClay(4); - /**+ - * The sand generator. + /** + * + The sand generator. */ protected WorldGenerator sandGen = new WorldGenSand(Blocks.sand, 7); - /**+ - * The gravel generator. + /** + * + The gravel generator. */ protected WorldGenerator gravelAsSandGen = new WorldGenSand(Blocks.gravel, 6); protected WorldGenerator dirtGen; @@ -73,68 +76,69 @@ public class BiomeDecorator { protected WorldGenerator diamondGen; protected WorldGenerator lapisGen; protected WorldGenerator platinumGen; + protected WorldGenerator titaniumGen; protected WorldGenFlowers yellowFlowerGen = new WorldGenFlowers(Blocks.yellow_flower, BlockFlower.EnumFlowerType.DANDELION); - /**+ - * Field that holds mushroomBrown WorldGenFlowers + /** + * + Field that holds mushroomBrown WorldGenFlowers */ protected WorldGenerator mushroomBrownGen = new GeneratorBushFeature(Blocks.brown_mushroom); - /**+ - * Field that holds mushroomRed WorldGenFlowers + /** + * + Field that holds mushroomRed WorldGenFlowers */ protected WorldGenerator mushroomRedGen = new GeneratorBushFeature(Blocks.red_mushroom); - /**+ - * Field that holds big mushroom generator + /** + * + Field that holds big mushroom generator */ protected WorldGenerator bigMushroomGen = new WorldGenBigMushroom(); - /**+ - * Field that holds WorldGenReed + /** + * + Field that holds WorldGenReed */ protected WorldGenerator reedGen = new WorldGenReed(); - /**+ - * Field that holds WorldGenCactus + /** + * + Field that holds WorldGenCactus */ protected WorldGenerator cactusGen = new WorldGenCactus(); - /**+ - * The water lily generation! + /** + * + The water lily generation! */ protected WorldGenerator waterlilyGen = new WorldGenWaterlily(); protected int waterlilyPerChunk; protected int treesPerChunk; - /**+ - * The number of yellow flower patches to generate per chunk. - * The game generates much less than this number, since it - * attempts to generate them at a random altitude. + /** + * + The number of yellow flower patches to generate per chunk. The game + * generates much less than this number, since it attempts to generate them at a + * random altitude. */ protected int flowersPerChunk = 2; - /**+ - * The amount of tall grass to generate per chunk. + /** + * + The amount of tall grass to generate per chunk. */ protected int grassPerChunk = 1; protected int deadBushPerChunk; protected int mushroomsPerChunk; protected int reedsPerChunk; protected int cactiPerChunk; - /**+ - * The number of sand patches to generate per chunk. Sand - * patches only generate when part of it is underwater. + /** + * + The number of sand patches to generate per chunk. Sand patches only + * generate when part of it is underwater. */ protected int sandPerChunk = 1; - /**+ - * The number of sand patches to generate per chunk. Sand - * patches only generate when part of it is underwater. There - * appear to be two separate fields for this. + /** + * + The number of sand patches to generate per chunk. Sand patches only + * generate when part of it is underwater. There appear to be two separate + * fields for this. */ protected int sandPerChunk2 = 3; - /**+ - * The number of clay patches to generate per chunk. Only - * generates when part of it is underwater. + /** + * + The number of clay patches to generate per chunk. Only generates when part + * of it is underwater. */ protected int clayPerChunk = 1; protected int bigMushroomsPerChunk; - /**+ - * True if decorator should generate surface lava & water + /** + * + True if decorator should generate surface lava & water */ public boolean generateLakes = true; @@ -175,6 +179,8 @@ public class BiomeDecorator { this.chunkProviderSettings.lapisSize); this.platinumGen = new WorldGenMinable(Blocks.platinum_ore.getDefaultState(), this.chunkProviderSettings.platinumSize); + this.titaniumGen = new WorldGenMinable(Blocks.titanium_ore.getDefaultState(), + this.chunkProviderSettings.titaniumSize); this.genDecorations(parBiomeGenBase); this.currentWorld = null; this.randomGenerator = null; @@ -395,49 +401,10 @@ public class BiomeDecorator { } - /**+ - * Standard ore generation helper. Generates most ores. - */ - protected void genStandardOre1(int blockCount, WorldGenerator generator, int minHeight, int maxHeight) { - if (maxHeight < minHeight) { - int i = minHeight; - minHeight = maxHeight; - maxHeight = i; - } else if (maxHeight == minHeight) { - if (minHeight < 255) { - ++maxHeight; - } else { - --minHeight; - } - } - - for (int j = 0; j < blockCount; ++j) { - BlockPos blockpos = this.field_180294_c.add(this.randomGenerator.nextInt(16), - this.randomGenerator.nextInt(maxHeight - minHeight) + minHeight, this.randomGenerator.nextInt(16)); - generator.generate(this.currentWorld, this.randomGenerator, blockpos); - } - - } - - /**+ - * Standard ore generation helper. Generates Lapis Lazuli. - */ - protected void genStandardOre2(int blockCount, WorldGenerator generator, int centerHeight, int spread) { - for (int i = 0; i < blockCount; ++i) { - BlockPos blockpos = this.field_180294_c.add(this.randomGenerator.nextInt(16), - this.randomGenerator.nextInt(spread) + this.randomGenerator.nextInt(spread) + centerHeight - spread, - this.randomGenerator.nextInt(16)); - generator.generate(this.currentWorld, this.randomGenerator, blockpos); - } - - } - - /**+ - * Generates ores in the current chunk + /** + * + Generates ores in the current chunk */ protected void generateOres() { - this.genStandardOre1(this.chunkProviderSettings.dirtCount, this.dirtGen, - this.chunkProviderSettings.dirtMinHeight, this.chunkProviderSettings.dirtMaxHeight); this.genStandardOre1(this.chunkProviderSettings.gravelCount, this.gravelGen, this.chunkProviderSettings.gravelMinHeight, this.chunkProviderSettings.gravelMaxHeight); this.genStandardOre1(this.chunkProviderSettings.dioriteCount, this.dioriteGen, @@ -460,5 +427,44 @@ public class BiomeDecorator { this.chunkProviderSettings.lapisCenterHeight, this.chunkProviderSettings.lapisSpread); this.genStandardOre1(this.chunkProviderSettings.platinumCount, this.platinumGen, this.chunkProviderSettings.platinumMinHeight, this.chunkProviderSettings.platinumMaxHeight); + this.genStandardOre1(this.chunkProviderSettings.titaniumCount, this.titaniumGen, + this.chunkProviderSettings.titaniumMinHeight, this.chunkProviderSettings.titaniumMaxHeight); + } + + /** + * + Standard ore generation helper. Generates most ores. + */ + protected void genStandardOre1(int blockCount, WorldGenerator generator, int minHeight, int maxHeight) { + if (maxHeight < minHeight) { + int i = minHeight; + minHeight = maxHeight; + maxHeight = i; + } else if (maxHeight == minHeight) { + if (minHeight < 255) { + ++maxHeight; + } else { + --minHeight; + } + } + + for (int j = 0; j < blockCount; ++j) { + BlockPos blockpos = this.field_180294_c.add(this.randomGenerator.nextInt(16), + this.randomGenerator.nextInt(maxHeight - minHeight) + minHeight, this.randomGenerator.nextInt(16)); + generator.generate(this.currentWorld, this.randomGenerator, blockpos); + } + + } + + /** + * + Standard ore generation helper. Generates Lapis Lazuli. + */ + protected void genStandardOre2(int blockCount, WorldGenerator generator, int centerHeight, int spread) { + for (int i = 0; i < blockCount; ++i) { + BlockPos blockpos = this.field_180294_c.add(this.randomGenerator.nextInt(16), + this.randomGenerator.nextInt(spread) + this.randomGenerator.nextInt(spread) + centerHeight - spread, + this.randomGenerator.nextInt(16)); + generator.generate(this.currentWorld, this.randomGenerator, blockpos); + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeEndDecorator.java b/src/game/java/net/minecraft/world/biome/BiomeEndDecorator.java index be7dcd57..dc3713aa 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeEndDecorator.java +++ b/src/game/java/net/minecraft/world/biome/BiomeEndDecorator.java @@ -5,22 +5,25 @@ import net.minecraft.init.Blocks; import net.minecraft.world.gen.feature.WorldGenSpikes; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenBase.java b/src/game/java/net/minecraft/world/biome/BiomeGenBase.java index 7600a037..7187b26b 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenBase.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenBase.java @@ -1,14 +1,17 @@ package net.minecraft.world.biome; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import java.util.Collections; -import java.util.List; -import java.util.Map; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import java.util.Set; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.block.BlockFlower; import net.minecraft.block.BlockSand; import net.minecraft.block.BlockTallGrass; @@ -46,46 +49,86 @@ import net.minecraft.world.gen.feature.WorldGenSwamp; import net.minecraft.world.gen.feature.WorldGenTallGrass; import net.minecraft.world.gen.feature.WorldGenTrees; import net.minecraft.world.gen.feature.WorldGenerator; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class BiomeGenBase { + public static class Height { + public float rootHeight; + public float variation; + + public Height(float rootHeightIn, float variationIn) { + this.rootHeight = rootHeightIn; + this.variation = variationIn; + } + + public BiomeGenBase.Height attenuate() { + return new BiomeGenBase.Height(this.rootHeight * 0.8F, this.variation * 0.6F); + } + } + + public static class SpawnListEntry extends WeightedRandom.Item { + public Class entityClass; + public int minGroupCount; + public int maxGroupCount; + + public SpawnListEntry(Class entityclassIn, int weight, int groupCountMin, + int groupCountMax) { + super(weight); + this.entityClass = entityclassIn; + this.minGroupCount = groupCountMin; + this.maxGroupCount = groupCountMax; + } + + public String toString() { + return this.entityClass.getSimpleName() + "*(" + this.minGroupCount + "-" + this.maxGroupCount + "):" + + this.itemWeight; + } + } + + public static enum TempCategory { + OCEAN, COLD, MEDIUM, WARM; + } + private static final Logger logger = LogManager.getLogger(); - protected static final BiomeGenBase.Height height_Default = new BiomeGenBase.Height(0.1F, 0.2F); - protected static final BiomeGenBase.Height height_ShallowWaters = new BiomeGenBase.Height(-0.5F, 0.0F); + // height modify + protected static final BiomeGenBase.Height height_Default = new BiomeGenBase.Height(0.4F, 0.5F); + protected static final BiomeGenBase.Height height_ShallowWaters = new BiomeGenBase.Height(-0.3F, 0.1F); protected static final BiomeGenBase.Height height_Oceans = new BiomeGenBase.Height(-1.0F, 0.1F); - protected static final BiomeGenBase.Height height_DeepOceans = new BiomeGenBase.Height(-1.8F, 0.1F); - protected static final BiomeGenBase.Height height_LowPlains = new BiomeGenBase.Height(0.125F, 0.05F); - protected static final BiomeGenBase.Height height_MidPlains = new BiomeGenBase.Height(0.2F, 0.2F); - protected static final BiomeGenBase.Height height_LowHills = new BiomeGenBase.Height(0.45F, 0.3F); - protected static final BiomeGenBase.Height height_HighPlateaus = new BiomeGenBase.Height(1.5F, 0.025F); - protected static final BiomeGenBase.Height height_MidHills = new BiomeGenBase.Height(1.0F, 0.5F); - protected static final BiomeGenBase.Height height_Shores = new BiomeGenBase.Height(0.0F, 0.025F); - protected static final BiomeGenBase.Height height_RockyWaters = new BiomeGenBase.Height(0.1F, 0.8F); - protected static final BiomeGenBase.Height height_LowIslands = new BiomeGenBase.Height(0.2F, 0.3F); - protected static final BiomeGenBase.Height height_PartiallySubmerged = new BiomeGenBase.Height(-0.2F, 0.1F); - /**+ - * An array of all the biomes, indexed by biome id. + protected static final BiomeGenBase.Height height_DeepOceans = new BiomeGenBase.Height(-1.6F, 0.1F); + protected static final BiomeGenBase.Height height_LowPlains = new BiomeGenBase.Height(0.1F, 0.3F); + protected static final BiomeGenBase.Height height_MidPlains = new BiomeGenBase.Height(0.2F, 0.4F); + protected static final BiomeGenBase.Height height_LowHills = new BiomeGenBase.Height(0.6F, 0.7F); + protected static final BiomeGenBase.Height height_HighPlateaus = new BiomeGenBase.Height(1.3F, 0.5F); + protected static final BiomeGenBase.Height height_MidHills = new BiomeGenBase.Height(1.8F, 1.0F); + protected static final BiomeGenBase.Height height_Shores = new BiomeGenBase.Height(0.0F, 0.02F); + + protected static final BiomeGenBase.Height height_RockyWaters = new BiomeGenBase.Height(0.3F, 0.5F); + protected static final BiomeGenBase.Height height_LowIslands = new BiomeGenBase.Height(1.0F, 0.6F); + protected static final BiomeGenBase.Height height_PartiallySubmerged = new BiomeGenBase.Height(-0.4F, 0.4F); + /** + * + An array of all the biomes, indexed by biome id. */ private static final BiomeGenBase[] biomeList = new BiomeGenBase[256]; public static final Set explorationBiomesList = Sets.newHashSet(); @@ -134,382 +177,6 @@ public abstract class BiomeGenBase { protected static NoiseGeneratorPerlin temperatureNoise; protected static NoiseGeneratorPerlin GRASS_COLOR_NOISE; protected static WorldGenDoublePlant DOUBLE_PLANT_GENERATOR; - public String biomeName; - public int color; - public int field_150609_ah; - /**+ - * The block expected to be on the top of this biome - */ - public IBlockState topBlock = Blocks.grass.getDefaultState(); - /**+ - * The block to fill spots in when not on the top - */ - public IBlockState fillerBlock = Blocks.dirt.getDefaultState(); - public int fillerBlockMetadata = 5169201; - public float minHeight; - public float maxHeight; - public float temperature; - public float rainfall; - public int waterColorMultiplier; - public BiomeDecorator theBiomeDecorator; - protected List spawnableMonsterList; - protected List spawnableCreatureList; - protected List spawnableWaterCreatureList; - protected List spawnableCaveCreatureList; - protected boolean enableSnow; - protected boolean enableRain; - public final int biomeID; - protected WorldGenTrees worldGeneratorTrees; - protected WorldGenBigTree worldGeneratorBigTree; - protected WorldGenSwamp worldGeneratorSwamp; - - protected BiomeGenBase(int id) { - this.minHeight = height_Default.rootHeight; - this.maxHeight = height_Default.variation; - this.temperature = 0.5F; - this.rainfall = 0.5F; - this.waterColorMultiplier = 16777215; - this.spawnableMonsterList = Lists.newArrayList(); - this.spawnableCreatureList = Lists.newArrayList(); - this.spawnableWaterCreatureList = Lists.newArrayList(); - this.spawnableCaveCreatureList = Lists.newArrayList(); - this.enableRain = true; - this.worldGeneratorTrees = new WorldGenTrees(false); - this.worldGeneratorBigTree = new WorldGenBigTree(false); - this.worldGeneratorSwamp = new WorldGenSwamp(); - this.biomeID = id; - biomeList[id] = this; - this.theBiomeDecorator = this.createBiomeDecorator(); - this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntitySheep.class, 12, 4, 4)); - this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityRabbit.class, 10, 3, 3)); - this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityPig.class, 10, 4, 4)); - this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityChicken.class, 10, 4, 4)); - this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityCow.class, 8, 4, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySpider.class, 100, 4, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityZombie.class, 100, 4, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySkeleton.class, 100, 4, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityCreeper.class, 100, 4, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySlime.class, 100, 4, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityEnderman.class, 10, 1, 4)); - this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityWitch.class, 5, 1, 1)); - this.spawnableWaterCreatureList.add(new BiomeGenBase.SpawnListEntry(EntitySquid.class, 10, 4, 4)); - this.spawnableCaveCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityBat.class, 10, 8, 8)); - } - - /**+ - * Allocate a new BiomeDecorator for this BiomeGenBase - */ - protected BiomeDecorator createBiomeDecorator() { - return new BiomeDecorator(); - } - - /**+ - * Sets the temperature and rainfall of this biome. - */ - protected BiomeGenBase setTemperatureRainfall(float temperatureIn, float rainfallIn) { - if (temperatureIn > 0.1F && temperatureIn < 0.2F) { - throw new IllegalArgumentException("Please avoid temperatures in the range 0.1 - 0.2 because of snow"); - } else { - this.temperature = temperatureIn; - this.rainfall = rainfallIn; - return this; - } - } - - protected final BiomeGenBase setHeight(BiomeGenBase.Height heights) { - this.minHeight = heights.rootHeight; - this.maxHeight = heights.variation; - return this; - } - - /**+ - * Disable the rain for the biome. - */ - protected BiomeGenBase setDisableRain() { - this.enableRain = false; - return this; - } - - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom rand) { - return (WorldGenAbstractTree) (rand.nextInt(10) == 0 ? this.worldGeneratorBigTree : this.worldGeneratorTrees); - } - - /**+ - * Gets a WorldGen appropriate for this biome. - */ - public WorldGenerator getRandomWorldGenForGrass(EaglercraftRandom rand) { - return new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); - } - - public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom rand, BlockPos pos) { - return rand.nextInt(3) > 0 ? BlockFlower.EnumFlowerType.DANDELION : BlockFlower.EnumFlowerType.POPPY; - } - - /**+ - * sets enableSnow to true during biome initialization. returns - * BiomeGenBase. - */ - protected BiomeGenBase setEnableSnow() { - this.enableSnow = true; - return this; - } - - protected BiomeGenBase setBiomeName(String name) { - this.biomeName = name; - return this; - } - - protected BiomeGenBase setFillerBlockMetadata(int meta) { - this.fillerBlockMetadata = meta; - return this; - } - - protected BiomeGenBase setColor(int colorIn) { - this.func_150557_a(colorIn, false); - return this; - } - - protected BiomeGenBase func_150563_c(int parInt1) { - this.field_150609_ah = parInt1; - return this; - } - - protected BiomeGenBase func_150557_a(int parInt1, boolean parFlag) { - this.color = parInt1; - if (parFlag) { - this.field_150609_ah = (parInt1 & 16711422) >> 1; - } else { - this.field_150609_ah = parInt1; - } - - return this; - } - - /**+ - * takes temperature, returns color - */ - public int getSkyColorByTemp(float parFloat1) { - parFloat1 = parFloat1 / 3.0F; - parFloat1 = MathHelper.clamp_float(parFloat1, -1.0F, 1.0F); - return MathHelper.func_181758_c(0.62222224F - parFloat1 * 0.05F, 0.5F + parFloat1 * 0.1F, 1.0F); - } - - /**+ - * Returns the correspondent list of the EnumCreatureType - * informed. - */ - public List getSpawnableList(EnumCreatureType creatureType) { - switch (creatureType) { - case MONSTER: - return this.spawnableMonsterList; - case CREATURE: - return this.spawnableCreatureList; - case WATER_CREATURE: - return this.spawnableWaterCreatureList; - case AMBIENT: - return this.spawnableCaveCreatureList; - default: - return Collections.emptyList(); - } - } - - /**+ - * Returns true if the biome have snowfall instead a normal - * rain. - */ - public boolean getEnableSnow() { - return this.isSnowyBiome(); - } - - /**+ - * Return true if the biome supports lightning bolt spawn, - * either by have the bolts enabled and have rain enabled. - */ - public boolean canSpawnLightningBolt() { - return this.isSnowyBiome() ? false : this.enableRain; - } - - /**+ - * Checks to see if the rainfall level of the biome is extremely - * high - */ - public boolean isHighHumidity() { - return this.rainfall > 0.85F; - } - - /**+ - * returns the chance a creature has to spawn. - */ - public float getSpawningChance() { - return 0.1F; - } - - /**+ - * Gets an integer representation of this biome's rainfall - */ - public final int getIntRainfall() { - return (int) (this.rainfall * 65536.0F); - } - - /**+ - * Gets a floating point representation of this biome's rainfall - */ - public final float getFloatRainfall() { - return this.rainfall; - } - - /**+ - * Gets a floating point representation of this biome's - * temperature - */ - public final float getFloatTemperature(BlockPos pos) { - if (pos.getY() > 64) { - float f = (float) (temperatureNoise.func_151601_a((double) pos.getX() * 1.0D / 8.0D, - (double) pos.getZ() * 1.0D / 8.0D) * 4.0D); - return this.temperature - (f + (float) pos.getY() - 64.0F) * 0.05F / 30.0F; - } else { - return this.temperature; - } - } - - public void decorate(World worldIn, EaglercraftRandom rand, BlockPos pos) { - this.theBiomeDecorator.decorate(worldIn, rand, this, pos); - } - - public int getGrassColorAtPos(BlockPos pos) { - double d0 = (double) MathHelper.clamp_float(this.getFloatTemperature(pos), 0.0F, 1.0F); - double d1 = (double) MathHelper.clamp_float(this.getFloatRainfall(), 0.0F, 1.0F); - return ColorizerGrass.getGrassColor(d0, d1); - } - - public int getFoliageColorAtPos(BlockPos pos) { - double d0 = (double) MathHelper.clamp_float(this.getFloatTemperature(pos), 0.0F, 1.0F); - double d1 = (double) MathHelper.clamp_float(this.getFloatRainfall(), 0.0F, 1.0F); - return ColorizerFoliage.getFoliageColor(d0, d1); - } - - public boolean isSnowyBiome() { - return this.enableSnow; - } - - public void genTerrainBlocks(World worldIn, EaglercraftRandom rand, ChunkPrimer chunkPrimerIn, int parInt1, - int parInt2, double parDouble1) { - this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, parInt1, parInt2, parDouble1); - } - - public final void generateBiomeTerrain(World worldIn, EaglercraftRandom rand, ChunkPrimer chunkPrimerIn, - int parInt1, int parInt2, double parDouble1) { - int i = worldIn.func_181545_F(); - IBlockState iblockstate = this.topBlock; - IBlockState iblockstate1 = this.fillerBlock; - int j = -1; - int k = (int) (parDouble1 / 3.0D + 3.0D + rand.nextDouble() * 0.25D); - int l = parInt1 & 15; - int i1 = parInt2 & 15; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int j1 = 255; j1 >= 0; --j1) { - if (j1 <= rand.nextInt(5)) { - chunkPrimerIn.setBlockState(i1, j1, l, Blocks.bedrock.getDefaultState()); - } else { - IBlockState iblockstate2 = chunkPrimerIn.getBlockState(i1, j1, l); - if (iblockstate2.getBlock().getMaterial() == Material.air) { - j = -1; - } else if (iblockstate2.getBlock() == Blocks.stone) { - if (j == -1) { - if (k <= 0) { - iblockstate = null; - iblockstate1 = Blocks.stone.getDefaultState(); - } else if (j1 >= i - 4 && j1 <= i + 1) { - iblockstate = this.topBlock; - iblockstate1 = this.fillerBlock; - } - - if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) { - if (this.getFloatTemperature( - blockpos$mutableblockpos.func_181079_c(parInt1, j1, parInt2)) < 0.15F) { - iblockstate = Blocks.ice.getDefaultState(); - } else { - iblockstate = Blocks.water.getDefaultState(); - } - } - - j = k; - if (j1 >= i - 1) { - chunkPrimerIn.setBlockState(i1, j1, l, iblockstate); - } else if (j1 < i - 7 - k) { - iblockstate = null; - iblockstate1 = Blocks.stone.getDefaultState(); - chunkPrimerIn.setBlockState(i1, j1, l, Blocks.gravel.getDefaultState()); - } else { - chunkPrimerIn.setBlockState(i1, j1, l, iblockstate1); - } - } else if (j > 0) { - --j; - chunkPrimerIn.setBlockState(i1, j1, l, iblockstate1); - if (j == 0 && iblockstate1.getBlock() == Blocks.sand) { - j = rand.nextInt(4) + Math.max(0, j1 - 63); - iblockstate1 = iblockstate1.getValue(BlockSand.VARIANT) == BlockSand.EnumType.RED_SAND - ? Blocks.red_sandstone.getDefaultState() - : Blocks.sandstone.getDefaultState(); - } - } - } - } - } - - } - - /**+ - * Creates a mutated version of the biome and places it into the - * biomeList with an index equal to the original plus 128 - */ - protected BiomeGenBase createMutation() { - return this.createMutatedBiome(this.biomeID + 128); - } - - protected BiomeGenBase createMutatedBiome(int parInt1) { - return new BiomeGenMutated(parInt1, this); - } - - public Class getBiomeClass() { - return this.getClass(); - } - - /**+ - * returns true if the biome specified is equal to this biome - */ - public boolean isEqualTo(BiomeGenBase biome) { - return biome == this ? true : (biome == null ? false : this.getBiomeClass() == biome.getBiomeClass()); - } - - public BiomeGenBase.TempCategory getTempCategory() { - return (double) this.temperature < 0.2D ? BiomeGenBase.TempCategory.COLD - : ((double) this.temperature < 1.0D ? BiomeGenBase.TempCategory.MEDIUM - : BiomeGenBase.TempCategory.WARM); - } - - public static BiomeGenBase[] getBiomeGenArray() { - return biomeList; - } - - /**+ - * return the biome specified by biomeID, or 0 (ocean) if out of - * bounds - */ - public static BiomeGenBase getBiome(int id) { - return getBiomeFromBiomeList(id, (BiomeGenBase) null); - } - - public static BiomeGenBase getBiomeFromBiomeList(int biomeId, BiomeGenBase biome) { - if (biomeId >= 0 && biomeId <= biomeList.length) { - BiomeGenBase biomegenbase = biomeList[biomeId]; - return biomegenbase == null ? biome : biomegenbase; - } else { - logger.warn("Biome ID is out of bounds: " + biomeId + ", defaulting to 0 (Ocean)"); - return ocean; - } - } public static void doBootstrap() { ocean = (new BiomeGenOcean(0)).setColor(112).setBiomeName("Ocean").setHeight(height_Oceans); @@ -636,40 +303,381 @@ public abstract class BiomeGenBase { DOUBLE_PLANT_GENERATOR = new WorldGenDoublePlant(); } - public static class Height { - public float rootHeight; - public float variation; + /** + * + return the biome specified by biomeID, or 0 (ocean) if out of bounds + */ + public static BiomeGenBase getBiome(int id) { + return getBiomeFromBiomeList(id, (BiomeGenBase) null); + } - public Height(float rootHeightIn, float variationIn) { - this.rootHeight = rootHeightIn; - this.variation = variationIn; - } - - public BiomeGenBase.Height attenuate() { - return new BiomeGenBase.Height(this.rootHeight * 0.8F, this.variation * 0.6F); + public static BiomeGenBase getBiomeFromBiomeList(int biomeId, BiomeGenBase biome) { + if (biomeId >= 0 && biomeId <= biomeList.length) { + BiomeGenBase biomegenbase = biomeList[biomeId]; + return biomegenbase == null ? biome : biomegenbase; + } else { + logger.warn("Biome ID is out of bounds: " + biomeId + ", defaulting to 0 (Ocean)"); + return ocean; } } - public static class SpawnListEntry extends WeightedRandom.Item { - public Class entityClass; - public int minGroupCount; - public int maxGroupCount; + public static BiomeGenBase[] getBiomeGenArray() { + return biomeList; + } - public SpawnListEntry(Class entityclassIn, int weight, int groupCountMin, - int groupCountMax) { - super(weight); - this.entityClass = entityclassIn; - this.minGroupCount = groupCountMin; - this.maxGroupCount = groupCountMax; + public String biomeName; + public int color; + public int field_150609_ah; + /** + * + The block expected to be on the top of this biome + */ + public IBlockState topBlock = Blocks.grass.getDefaultState(); + /** + * + The block to fill spots in when not on the top + */ + public IBlockState fillerBlock = Blocks.dirt.getDefaultState(); + public int fillerBlockMetadata = 5169201; + public float minHeight; + public float maxHeight; + public float temperature; + public float rainfall; + public int waterColorMultiplier; + public BiomeDecorator theBiomeDecorator; + protected List spawnableMonsterList; + protected List spawnableCreatureList; + protected List spawnableWaterCreatureList; + + protected List spawnableCaveCreatureList; + + protected boolean enableSnow; + + protected boolean enableRain; + + public final int biomeID; + + protected WorldGenTrees worldGeneratorTrees; + + protected WorldGenBigTree worldGeneratorBigTree; + + protected WorldGenSwamp worldGeneratorSwamp; + + protected BiomeGenBase(int id) { + this.minHeight = height_Default.rootHeight; + this.maxHeight = height_Default.variation; + this.temperature = 0.5F; + this.rainfall = 0.5F; + this.waterColorMultiplier = 16777215; + this.spawnableMonsterList = Lists.newArrayList(); + this.spawnableCreatureList = Lists.newArrayList(); + this.spawnableWaterCreatureList = Lists.newArrayList(); + this.spawnableCaveCreatureList = Lists.newArrayList(); + this.enableRain = true; + this.worldGeneratorTrees = new WorldGenTrees(false); + this.worldGeneratorBigTree = new WorldGenBigTree(false); + this.worldGeneratorSwamp = new WorldGenSwamp(); + this.biomeID = id; + biomeList[id] = this; + this.theBiomeDecorator = this.createBiomeDecorator(); + this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntitySheep.class, 12, 4, 4)); + this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityRabbit.class, 10, 3, 3)); + this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityPig.class, 10, 4, 4)); + this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityChicken.class, 10, 4, 4)); + this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityCow.class, 8, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySpider.class, 100, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityZombie.class, 100, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySkeleton.class, 100, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityCreeper.class, 100, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntitySlime.class, 100, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityEnderman.class, 10, 1, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityWitch.class, 5, 1, 1)); + this.spawnableWaterCreatureList.add(new BiomeGenBase.SpawnListEntry(EntitySquid.class, 10, 4, 4)); + this.spawnableCaveCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityBat.class, 10, 8, 8)); + } + + /** + * + Return true if the biome supports lightning bolt spawn, either by have the + * bolts enabled and have rain enabled. + */ + public boolean canSpawnLightningBolt() { + return this.isSnowyBiome() ? false : this.enableRain; + } + + /** + * + Allocate a new BiomeDecorator for this BiomeGenBase + */ + protected BiomeDecorator createBiomeDecorator() { + return new BiomeDecorator(); + } + + protected BiomeGenBase createMutatedBiome(int parInt1) { + return new BiomeGenMutated(parInt1, this); + } + + /** + * + Creates a mutated version of the biome and places it into the biomeList + * with an index equal to the original plus 128 + */ + protected BiomeGenBase createMutation() { + return this.createMutatedBiome(this.biomeID + 128); + } + + public void decorate(World worldIn, EaglercraftRandom rand, BlockPos pos) { + this.theBiomeDecorator.decorate(worldIn, rand, this, pos); + } + + protected BiomeGenBase func_150557_a(int parInt1, boolean parFlag) { + this.color = parInt1; + if (parFlag) { + this.field_150609_ah = (parInt1 & 16711422) >> 1; + } else { + this.field_150609_ah = parInt1; } - public String toString() { - return this.entityClass.getSimpleName() + "*(" + this.minGroupCount + "-" + this.maxGroupCount + "):" - + this.itemWeight; + return this; + } + + protected BiomeGenBase func_150563_c(int parInt1) { + this.field_150609_ah = parInt1; + return this; + } + + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom rand) { + return (WorldGenAbstractTree) (rand.nextInt(10) == 0 ? this.worldGeneratorBigTree : this.worldGeneratorTrees); + } + + public final void generateBiomeTerrain(World worldIn, EaglercraftRandom rand, ChunkPrimer chunkPrimerIn, + int parInt1, int parInt2, double parDouble1) { + int i = worldIn.func_181545_F(); + IBlockState iblockstate = this.topBlock; + IBlockState iblockstate1 = this.fillerBlock; + int j = -1; + int k = (int) (parDouble1 / 3.0D + 3.0D + rand.nextDouble() * 0.25D); + int l = parInt1 & 15; + int i1 = parInt2 & 15; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int j1 = 255; j1 >= 0; --j1) { + if (j1 <= rand.nextInt(5)) { + chunkPrimerIn.setBlockState(i1, j1, l, Blocks.bedrock.getDefaultState()); + } else { + IBlockState iblockstate2 = chunkPrimerIn.getBlockState(i1, j1, l); + if (iblockstate2.getBlock().getMaterial() == Material.air) { + j = -1; + } else if (iblockstate2.getBlock() == Blocks.stone) { + if (j == -1) { + if (k <= 0) { + iblockstate = null; + iblockstate1 = Blocks.stone.getDefaultState(); + } else if (j1 >= i - 4 && j1 <= i + 1) { + iblockstate = this.topBlock; + iblockstate1 = this.fillerBlock; + } + + if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) { + if (this.getFloatTemperature( + blockpos$mutableblockpos.func_181079_c(parInt1, j1, parInt2)) < 0.15F) { + iblockstate = Blocks.ice.getDefaultState(); + } else { + iblockstate = Blocks.water.getDefaultState(); + } + } + + j = k; + if (j1 >= i - 1) { + chunkPrimerIn.setBlockState(i1, j1, l, iblockstate); + } else if (j1 < i - 7 - k) { + iblockstate = null; + iblockstate1 = Blocks.stone.getDefaultState(); + chunkPrimerIn.setBlockState(i1, j1, l, Blocks.gravel.getDefaultState()); + } else { + chunkPrimerIn.setBlockState(i1, j1, l, iblockstate1); + } + } else if (j > 0) { + --j; + chunkPrimerIn.setBlockState(i1, j1, l, iblockstate1); + if (j == 0 && iblockstate1.getBlock() == Blocks.sand) { + j = rand.nextInt(4) + Math.max(0, j1 - 63); + iblockstate1 = iblockstate1.getValue(BlockSand.VARIANT) == BlockSand.EnumType.RED_SAND + ? Blocks.red_sandstone.getDefaultState() + : Blocks.sandstone.getDefaultState(); + } + } + } + } + } + + } + + public void genTerrainBlocks(World worldIn, EaglercraftRandom rand, ChunkPrimer chunkPrimerIn, int parInt1, + int parInt2, double parDouble1) { + this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, parInt1, parInt2, parDouble1); + } + + public Class getBiomeClass() { + return this.getClass(); + } + + /** + * + Returns true if the biome have snowfall instead a normal rain. + */ + public boolean getEnableSnow() { + return this.isSnowyBiome(); + } + + /** + * + Gets a floating point representation of this biome's rainfall + */ + public final float getFloatRainfall() { + return this.rainfall; + } + + /** + * + Gets a floating point representation of this biome's temperature + */ + public final float getFloatTemperature(BlockPos pos) { + if (pos.getY() > 64) { + float f = (float) (temperatureNoise.func_151601_a((double) pos.getX() * 1.0D / 8.0D, + (double) pos.getZ() * 1.0D / 8.0D) * 4.0D); + return this.temperature - (f + (float) pos.getY() - 64.0F) * 0.05F / 30.0F; + } else { + return this.temperature; } } - public static enum TempCategory { - OCEAN, COLD, MEDIUM, WARM; + public int getFoliageColorAtPos(BlockPos pos) { + double d0 = (double) MathHelper.clamp_float(this.getFloatTemperature(pos), 0.0F, 1.0F); + double d1 = (double) MathHelper.clamp_float(this.getFloatRainfall(), 0.0F, 1.0F); + return ColorizerFoliage.getFoliageColor(d0, d1); + } + + public int getGrassColorAtPos(BlockPos pos) { + double d0 = (double) MathHelper.clamp_float(this.getFloatTemperature(pos), 0.0F, 1.0F); + double d1 = (double) MathHelper.clamp_float(this.getFloatRainfall(), 0.0F, 1.0F); + return ColorizerGrass.getGrassColor(d0, d1); + } + + /** + * + Gets an integer representation of this biome's rainfall + */ + public final int getIntRainfall() { + return (int) (this.rainfall * 65536.0F); + } + + /** + * + Gets a WorldGen appropriate for this biome. + */ + public WorldGenerator getRandomWorldGenForGrass(EaglercraftRandom rand) { + return new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); + } + + /** + * + takes temperature, returns color + */ + public int getSkyColorByTemp(float parFloat1) { + parFloat1 = parFloat1 / 3.0F; + parFloat1 = MathHelper.clamp_float(parFloat1, -1.0F, 1.0F); + return MathHelper.func_181758_c(0.62222224F - parFloat1 * 0.05F, 0.5F + parFloat1 * 0.1F, 1.0F); + } + + /** + * + Returns the correspondent list of the EnumCreatureType informed. + */ + public List getSpawnableList(EnumCreatureType creatureType) { + switch (creatureType) { + case MONSTER: + return this.spawnableMonsterList; + case CREATURE: + return this.spawnableCreatureList; + case WATER_CREATURE: + return this.spawnableWaterCreatureList; + case AMBIENT: + return this.spawnableCaveCreatureList; + default: + return Collections.emptyList(); + } + } + + /** + * + returns the chance a creature has to spawn. + */ + public float getSpawningChance() { + return 0.1F; + } + + public BiomeGenBase.TempCategory getTempCategory() { + return (double) this.temperature < 0.2D ? BiomeGenBase.TempCategory.COLD + : ((double) this.temperature < 1.0D ? BiomeGenBase.TempCategory.MEDIUM + : BiomeGenBase.TempCategory.WARM); + } + + /** + * + returns true if the biome specified is equal to this biome + */ + public boolean isEqualTo(BiomeGenBase biome) { + return biome == this ? true : (biome == null ? false : this.getBiomeClass() == biome.getBiomeClass()); + } + + /** + * + Checks to see if the rainfall level of the biome is extremely high + */ + public boolean isHighHumidity() { + return this.rainfall > 0.85F; + } + + public boolean isSnowyBiome() { + return this.enableSnow; + } + + public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom rand, BlockPos pos) { + return rand.nextInt(3) > 0 ? BlockFlower.EnumFlowerType.DANDELION : BlockFlower.EnumFlowerType.POPPY; + } + + protected BiomeGenBase setBiomeName(String name) { + this.biomeName = name; + return this; + } + + protected BiomeGenBase setColor(int colorIn) { + this.func_150557_a(colorIn, false); + return this; + } + + /** + * + Disable the rain for the biome. + */ + protected BiomeGenBase setDisableRain() { + this.enableRain = false; + return this; + } + + /** + * + sets enableSnow to true during biome initialization. returns BiomeGenBase. + */ + protected BiomeGenBase setEnableSnow() { + this.enableSnow = true; + return this; + } + + protected BiomeGenBase setFillerBlockMetadata(int meta) { + this.fillerBlockMetadata = meta; + return this; + } + + protected final BiomeGenBase setHeight(BiomeGenBase.Height heights) { + this.minHeight = heights.rootHeight; + this.maxHeight = heights.variation; + return this; + } + + /** + * + Sets the temperature and rainfall of this biome. + */ + protected BiomeGenBase setTemperatureRainfall(float temperatureIn, float rainfallIn) { + if (temperatureIn > 0.1F && temperatureIn < 0.2F) { + throw new IllegalArgumentException("Please avoid temperatures in the range 0.1 - 0.2 because of snow"); + } else { + this.temperature = temperatureIn; + this.rainfall = rainfallIn; + return this; + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenBeach.java b/src/game/java/net/minecraft/world/biome/BiomeGenBeach.java index 9b5469c2..26d3bd83 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenBeach.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenBeach.java @@ -2,22 +2,25 @@ package net.minecraft.world.biome; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenDesert.java b/src/game/java/net/minecraft/world/biome/BiomeGenDesert.java index 9d69d1c4..264acbcb 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenDesert.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenDesert.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenDesertWells; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenEnd.java b/src/game/java/net/minecraft/world/biome/BiomeGenEnd.java index 4036882a..88933697 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenEnd.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenEnd.java @@ -3,22 +3,25 @@ package net.minecraft.world.biome; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,8 +39,8 @@ public class BiomeGenEnd extends BiomeGenBase { this.theBiomeDecorator = new BiomeEndDecorator(); } - /**+ - * takes temperature, returns color + /** + * + takes temperature, returns color */ public int getSkyColorByTemp(float var1) { return 0; diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenForest.java b/src/game/java/net/minecraft/world/biome/BiomeGenForest.java index ebb7413a..cdcada93 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenForest.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenForest.java @@ -12,31 +12,34 @@ import net.minecraft.world.gen.feature.WorldGenBigMushroom; import net.minecraft.world.gen.feature.WorldGenCanopyTree; import net.minecraft.world.gen.feature.WorldGenForest; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BiomeGenForest extends BiomeGenBase { - private int field_150632_aF; protected static final WorldGenForest field_150629_aC = new WorldGenForest(false, true); protected static final WorldGenForest field_150630_aD = new WorldGenForest(false, false); protected static final WorldGenCanopyTree field_150631_aE = new WorldGenCanopyTree(false); + private int field_150632_aF; public BiomeGenForest(int parInt1, int parInt2) { super(parInt1); @@ -67,37 +70,26 @@ public class BiomeGenForest extends BiomeGenBase { } - protected BiomeGenBase func_150557_a(int i, boolean flag) { - if (this.field_150632_aF == 2) { - this.field_150609_ah = 353825; - this.color = i; - if (flag) { - this.field_150609_ah = (this.field_150609_ah & 16711422) >> 1; - } - - return this; + protected BiomeGenBase createMutatedBiome(final int i) { + if (this.biomeID == BiomeGenBase.forest.biomeID) { + BiomeGenForest biomegenforest = new BiomeGenForest(i, 1); + biomegenforest.setHeight(new BiomeGenBase.Height(this.minHeight, this.maxHeight + 0.2F)); + biomegenforest.setBiomeName("Flower Forest"); + biomegenforest.func_150557_a(6976549, true); + biomegenforest.setFillerBlockMetadata(8233509); + return biomegenforest; } else { - return super.func_150557_a(i, flag); - } - } - - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return (WorldGenAbstractTree) (this.field_150632_aF == 3 && random.nextInt(3) > 0 ? field_150631_aE - : (this.field_150632_aF != 2 && random.nextInt(5) != 0 ? this.worldGeneratorTrees : field_150630_aD)); - } - - public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom random, BlockPos blockpos) { - if (this.field_150632_aF == 1) { - double d0 = MathHelper.clamp_double((1.0D + GRASS_COLOR_NOISE - .func_151601_a((double) blockpos.getX() / 48.0D, (double) blockpos.getZ() / 48.0D)) / 2.0D, 0.0D, - 0.9999D); - BlockFlower.EnumFlowerType blockflower$enumflowertype = BlockFlower.EnumFlowerType._VALUES[(int) (d0 - * (double) BlockFlower.EnumFlowerType._VALUES.length)]; - return blockflower$enumflowertype == BlockFlower.EnumFlowerType.BLUE_ORCHID - ? BlockFlower.EnumFlowerType.POPPY - : blockflower$enumflowertype; - } else { - return super.pickRandomFlower(random, blockpos); + return this.biomeID != BiomeGenBase.birchForest.biomeID + && this.biomeID != BiomeGenBase.birchForestHills.biomeID ? new BiomeGenMutated(i, this) { + public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { + this.baseBiome.decorate(world, random, blockpos); + } + } : new BiomeGenMutated(i, this) { + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return random.nextBoolean() ? BiomeGenForest.field_150629_aC + : BiomeGenForest.field_150630_aD; + } + }; } } @@ -151,31 +143,42 @@ public class BiomeGenForest extends BiomeGenBase { super.decorate(world, random, blockpos); } + protected BiomeGenBase func_150557_a(int i, boolean flag) { + if (this.field_150632_aF == 2) { + this.field_150609_ah = 353825; + this.color = i; + if (flag) { + this.field_150609_ah = (this.field_150609_ah & 16711422) >> 1; + } + + return this; + } else { + return super.func_150557_a(i, flag); + } + } + + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return (WorldGenAbstractTree) (this.field_150632_aF == 3 && random.nextInt(3) > 0 ? field_150631_aE + : (this.field_150632_aF != 2 && random.nextInt(5) != 0 ? this.worldGeneratorTrees : field_150630_aD)); + } + public int getGrassColorAtPos(BlockPos blockpos) { int i = super.getGrassColorAtPos(blockpos); return this.field_150632_aF == 3 ? (i & 16711422) + 2634762 >> 1 : i; } - protected BiomeGenBase createMutatedBiome(final int i) { - if (this.biomeID == BiomeGenBase.forest.biomeID) { - BiomeGenForest biomegenforest = new BiomeGenForest(i, 1); - biomegenforest.setHeight(new BiomeGenBase.Height(this.minHeight, this.maxHeight + 0.2F)); - biomegenforest.setBiomeName("Flower Forest"); - biomegenforest.func_150557_a(6976549, true); - biomegenforest.setFillerBlockMetadata(8233509); - return biomegenforest; + public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom random, BlockPos blockpos) { + if (this.field_150632_aF == 1) { + double d0 = MathHelper.clamp_double((1.0D + GRASS_COLOR_NOISE + .func_151601_a((double) blockpos.getX() / 48.0D, (double) blockpos.getZ() / 48.0D)) / 2.0D, 0.0D, + 0.9999D); + BlockFlower.EnumFlowerType blockflower$enumflowertype = BlockFlower.EnumFlowerType._VALUES[(int) (d0 + * (double) BlockFlower.EnumFlowerType._VALUES.length)]; + return blockflower$enumflowertype == BlockFlower.EnumFlowerType.BLUE_ORCHID + ? BlockFlower.EnumFlowerType.POPPY + : blockflower$enumflowertype; } else { - return this.biomeID != BiomeGenBase.birchForest.biomeID - && this.biomeID != BiomeGenBase.birchForestHills.biomeID ? new BiomeGenMutated(i, this) { - public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { - this.baseBiome.decorate(world, random, blockpos); - } - } : new BiomeGenMutated(i, this) { - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return random.nextBoolean() ? BiomeGenForest.field_150629_aC - : BiomeGenForest.field_150630_aD; - } - }; + return super.pickRandomFlower(random, blockpos); } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenHell.java b/src/game/java/net/minecraft/world/biome/BiomeGenHell.java index 0c20fdf8..d9358f31 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenHell.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenHell.java @@ -2,24 +2,28 @@ package net.minecraft.world.biome; import net.minecraft.entity.monster.EntityGhast; import net.minecraft.entity.monster.EntityMagmaCube; +import net.minecraft.entity.monster.EntityNetherCreeper; import net.minecraft.entity.monster.EntityPigZombie; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,5 +38,7 @@ public class BiomeGenHell extends BiomeGenBase { this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityGhast.class, 50, 4, 4)); this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityPigZombie.class, 100, 4, 4)); this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityMagmaCube.class, 1, 4, 4)); + this.spawnableMonsterList.add(new BiomeGenBase.SpawnListEntry(EntityNetherCreeper.class, 100, 4, 1)); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenHills.java b/src/game/java/net/minecraft/world/biome/BiomeGenHills.java index e44958f6..f237ffe2 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenHills.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenHills.java @@ -11,22 +11,25 @@ import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraft.world.gen.feature.WorldGenTaiga2; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,8 +55,8 @@ public class BiomeGenHills extends BiomeGenBase { } - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return (WorldGenAbstractTree) (random.nextInt(3) > 0 ? this.field_150634_aD : super.genBigTreeChance(random)); + protected BiomeGenBase createMutatedBiome(int i) { + return (new BiomeGenHills(i, false)).mutateHills(this); } public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { @@ -79,6 +82,10 @@ public class BiomeGenHills extends BiomeGenBase { } + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return (WorldGenAbstractTree) (random.nextInt(3) > 0 ? this.field_150634_aD : super.genBigTreeChance(random)); + } + public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, double d0) { this.topBlock = Blocks.grass.getDefaultState(); @@ -94,8 +101,8 @@ public class BiomeGenHills extends BiomeGenBase { this.generateBiomeTerrain(world, random, chunkprimer, i, j, d0); } - /**+ - * this creates a mutation specific to Hills biomes + /** + * + this creates a mutation specific to Hills biomes */ private BiomeGenHills mutateHills(BiomeGenBase parBiomeGenBase) { this.field_150638_aH = this.field_150637_aG; @@ -105,8 +112,4 @@ public class BiomeGenHills extends BiomeGenBase { this.setTemperatureRainfall(parBiomeGenBase.temperature, parBiomeGenBase.rainfall); return this; } - - protected BiomeGenBase createMutatedBiome(int i) { - return (new BiomeGenHills(i, false)).mutateHills(this); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenJungle.java b/src/game/java/net/minecraft/world/biome/BiomeGenJungle.java index c6769714..c752b347 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenJungle.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenJungle.java @@ -21,22 +21,25 @@ import net.minecraft.world.gen.feature.WorldGenTrees; import net.minecraft.world.gen.feature.WorldGenVines; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -71,23 +74,6 @@ public class BiomeGenJungle extends BiomeGenBase { this.spawnableCreatureList.add(new BiomeGenBase.SpawnListEntry(EntityChicken.class, 10, 4, 4)); } - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return (WorldGenAbstractTree) (random.nextInt(10) == 0 ? this.worldGeneratorBigTree - : (random.nextInt(2) == 0 ? new WorldGenShrub(field_181620_aE, field_181622_aG) - : (!this.field_150614_aC && random.nextInt(3) == 0 - ? new WorldGenMegaJungle(false, 10, 20, field_181620_aE, field_181621_aF) - : new WorldGenTrees(false, 4 + random.nextInt(7), field_181620_aE, field_181621_aF, - true)))); - } - - /**+ - * Gets a WorldGen appropriate for this biome. - */ - public WorldGenerator getRandomWorldGenForGrass(EaglercraftRandom random) { - return random.nextInt(4) == 0 ? new WorldGenTallGrass(BlockTallGrass.EnumType.FERN) - : new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); - } - public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { super.decorate(world, random, blockpos); int i = random.nextInt(16) + 8; @@ -104,4 +90,21 @@ public class BiomeGenJungle extends BiomeGenBase { } } + + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return (WorldGenAbstractTree) (random.nextInt(10) == 0 ? this.worldGeneratorBigTree + : (random.nextInt(2) == 0 ? new WorldGenShrub(field_181620_aE, field_181622_aG) + : (!this.field_150614_aC && random.nextInt(3) == 0 + ? new WorldGenMegaJungle(false, 10, 20, field_181620_aE, field_181621_aF) + : new WorldGenTrees(false, 4 + random.nextInt(7), field_181620_aE, field_181621_aF, + true)))); + } + + /** + * + Gets a WorldGen appropriate for this biome. + */ + public WorldGenerator getRandomWorldGenForGrass(EaglercraftRandom random) { + return random.nextInt(4) == 0 ? new WorldGenTallGrass(BlockTallGrass.EnumType.FERN) + : new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenMesa.java b/src/game/java/net/minecraft/world/biome/BiomeGenMesa.java index 264923d0..1da52e98 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenMesa.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenMesa.java @@ -1,6 +1,7 @@ package net.minecraft.world.biome; import java.util.Arrays; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockColored; import net.minecraft.block.BlockDirt; @@ -15,22 +16,25 @@ import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.NoiseGeneratorPerlin; import net.minecraft.world.gen.feature.WorldGenAbstractTree; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,22 +69,109 @@ public class BiomeGenMesa extends BiomeGenBase { } - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom var1) { - return this.worldGeneratorTrees; - } + protected BiomeGenBase createMutatedBiome(int i) { + boolean flag = this.biomeID == BiomeGenBase.mesa.biomeID; + BiomeGenMesa biomegenmesa = new BiomeGenMesa(i, flag, this.field_150620_aI); + if (!flag) { + biomegenmesa.setHeight(height_LowHills); + biomegenmesa.setBiomeName(this.biomeName + " M"); + } else { + biomegenmesa.setBiomeName(this.biomeName + " (Bryce)"); + } - public int getFoliageColorAtPos(BlockPos var1) { - return 10387789; - } - - public int getGrassColorAtPos(BlockPos var1) { - return 9470285; + biomegenmesa.func_150557_a(this.color, true); + return biomegenmesa; } public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { super.decorate(world, random, blockpos); } + private void func_150619_a(long parLong1, boolean scrambleRNG) { + this.field_150621_aC = new IBlockState[64]; + Arrays.fill(this.field_150621_aC, Blocks.hardened_clay.getDefaultState()); + EaglercraftRandom random = new EaglercraftRandom(parLong1, scrambleRNG); + this.field_150625_aG = new NoiseGeneratorPerlin(random, 1); + + for (int l1 = 0; l1 < 64; ++l1) { + l1 += random.nextInt(5) + 1; + if (l1 < 64) { + this.field_150621_aC[l1] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.ORANGE); + } + } + + int i2 = random.nextInt(4) + 2; + + for (int i = 0; i < i2; ++i) { + int j = random.nextInt(3) + 1; + int k = random.nextInt(64); + + for (int l = 0; k + l < 64 && l < j; ++l) { + this.field_150621_aC[k + l] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.YELLOW); + } + } + + int j2 = random.nextInt(4) + 2; + + for (int k2 = 0; k2 < j2; ++k2) { + int i3 = random.nextInt(3) + 2; + int l3 = random.nextInt(64); + + for (int i1 = 0; l3 + i1 < 64 && i1 < i3; ++i1) { + this.field_150621_aC[l3 + i1] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.BROWN); + } + } + + int l2 = random.nextInt(4) + 2; + + for (int j3 = 0; j3 < l2; ++j3) { + int i4 = random.nextInt(3) + 1; + int k4 = random.nextInt(64); + + for (int j1 = 0; k4 + j1 < 64 && j1 < i4; ++j1) { + this.field_150621_aC[k4 + j1] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.RED); + } + } + + int k3 = random.nextInt(3) + 3; + int j4 = 0; + + for (int l4 = 0; l4 < k3; ++l4) { + byte b0 = 1; + j4 += random.nextInt(16) + 4; + + for (int k1 = 0; j4 + k1 < 64 && k1 < b0; ++k1) { + this.field_150621_aC[j4 + k1] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.WHITE); + if (j4 + k1 > 1 && random.nextBoolean()) { + this.field_150621_aC[j4 + k1 - 1] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.SILVER); + } + + if (j4 + k1 < 63 && random.nextBoolean()) { + this.field_150621_aC[j4 + k1 + 1] = Blocks.stained_hardened_clay.getDefaultState() + .withProperty(BlockColored.COLOR, EnumDyeColor.SILVER); + } + } + } + + } + + private IBlockState func_180629_a(int parInt1, int parInt2, int parInt3) { + int i = (int) Math.round( + this.field_150625_aG.func_151601_a((double) parInt1 * 1.0D / 512.0D, (double) parInt1 * 1.0D / 512.0D) + * 2.0D); + return this.field_150621_aC[(parInt2 + i + 64) % 64]; + } + + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom var1) { + return this.worldGeneratorTrees; + } + public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, double d0) { if (this.field_150621_aC == null || this.field_150622_aD != world.getSeed()) { @@ -198,98 +289,11 @@ public class BiomeGenMesa extends BiomeGenBase { } - private void func_150619_a(long parLong1, boolean scrambleRNG) { - this.field_150621_aC = new IBlockState[64]; - Arrays.fill(this.field_150621_aC, Blocks.hardened_clay.getDefaultState()); - EaglercraftRandom random = new EaglercraftRandom(parLong1, scrambleRNG); - this.field_150625_aG = new NoiseGeneratorPerlin(random, 1); - - for (int l1 = 0; l1 < 64; ++l1) { - l1 += random.nextInt(5) + 1; - if (l1 < 64) { - this.field_150621_aC[l1] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.ORANGE); - } - } - - int i2 = random.nextInt(4) + 2; - - for (int i = 0; i < i2; ++i) { - int j = random.nextInt(3) + 1; - int k = random.nextInt(64); - - for (int l = 0; k + l < 64 && l < j; ++l) { - this.field_150621_aC[k + l] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.YELLOW); - } - } - - int j2 = random.nextInt(4) + 2; - - for (int k2 = 0; k2 < j2; ++k2) { - int i3 = random.nextInt(3) + 2; - int l3 = random.nextInt(64); - - for (int i1 = 0; l3 + i1 < 64 && i1 < i3; ++i1) { - this.field_150621_aC[l3 + i1] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.BROWN); - } - } - - int l2 = random.nextInt(4) + 2; - - for (int j3 = 0; j3 < l2; ++j3) { - int i4 = random.nextInt(3) + 1; - int k4 = random.nextInt(64); - - for (int j1 = 0; k4 + j1 < 64 && j1 < i4; ++j1) { - this.field_150621_aC[k4 + j1] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.RED); - } - } - - int k3 = random.nextInt(3) + 3; - int j4 = 0; - - for (int l4 = 0; l4 < k3; ++l4) { - byte b0 = 1; - j4 += random.nextInt(16) + 4; - - for (int k1 = 0; j4 + k1 < 64 && k1 < b0; ++k1) { - this.field_150621_aC[j4 + k1] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.WHITE); - if (j4 + k1 > 1 && random.nextBoolean()) { - this.field_150621_aC[j4 + k1 - 1] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.SILVER); - } - - if (j4 + k1 < 63 && random.nextBoolean()) { - this.field_150621_aC[j4 + k1 + 1] = Blocks.stained_hardened_clay.getDefaultState() - .withProperty(BlockColored.COLOR, EnumDyeColor.SILVER); - } - } - } - + public int getFoliageColorAtPos(BlockPos var1) { + return 10387789; } - private IBlockState func_180629_a(int parInt1, int parInt2, int parInt3) { - int i = (int) Math.round( - this.field_150625_aG.func_151601_a((double) parInt1 * 1.0D / 512.0D, (double) parInt1 * 1.0D / 512.0D) - * 2.0D); - return this.field_150621_aC[(parInt2 + i + 64) % 64]; - } - - protected BiomeGenBase createMutatedBiome(int i) { - boolean flag = this.biomeID == BiomeGenBase.mesa.biomeID; - BiomeGenMesa biomegenmesa = new BiomeGenMesa(i, flag, this.field_150620_aI); - if (!flag) { - biomegenmesa.setHeight(height_LowHills); - biomegenmesa.setBiomeName(this.biomeName + " M"); - } else { - biomegenmesa.setBiomeName(this.biomeName + " (Bryce)"); - } - - biomegenmesa.func_150557_a(this.color, true); - return biomegenmesa; + public int getGrassColorAtPos(BlockPos var1) { + return 9470285; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenMushroomIsland.java b/src/game/java/net/minecraft/world/biome/BiomeGenMushroomIsland.java index 1141f859..9d5b7931 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenMushroomIsland.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenMushroomIsland.java @@ -3,22 +3,25 @@ package net.minecraft.world.biome; import net.minecraft.entity.passive.EntityMooshroom; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenMutated.java b/src/game/java/net/minecraft/world/biome/BiomeGenMutated.java index 8ce98d94..2b58a810 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenMutated.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenMutated.java @@ -1,30 +1,32 @@ package net.minecraft.world.biome; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import com.google.common.collect.Lists; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.feature.WorldGenAbstractTree; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,20 +63,17 @@ public class BiomeGenMutated extends BiomeGenBase { this.baseBiome.theBiomeDecorator.decorate(world, random, this, blockpos); } + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return this.baseBiome.genBigTreeChance(random); + } + public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, double d0) { this.baseBiome.genTerrainBlocks(world, random, chunkprimer, i, j, d0); } - /**+ - * returns the chance a creature has to spawn. - */ - public float getSpawningChance() { - return this.baseBiome.getSpawningChance(); - } - - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return this.baseBiome.genBigTreeChance(random); + public Class getBiomeClass() { + return this.baseBiome.getBiomeClass(); } public int getFoliageColorAtPos(BlockPos blockpos) { @@ -85,18 +84,21 @@ public class BiomeGenMutated extends BiomeGenBase { return this.baseBiome.getGrassColorAtPos(blockpos); } - public Class getBiomeClass() { - return this.baseBiome.getBiomeClass(); - } - - /**+ - * returns true if the biome specified is equal to this biome + /** + * + returns the chance a creature has to spawn. */ - public boolean isEqualTo(BiomeGenBase biomegenbase) { - return this.baseBiome.isEqualTo(biomegenbase); + public float getSpawningChance() { + return this.baseBiome.getSpawningChance(); } public BiomeGenBase.TempCategory getTempCategory() { return this.baseBiome.getTempCategory(); } + + /** + * + returns true if the biome specified is equal to this biome + */ + public boolean isEqualTo(BiomeGenBase biomegenbase) { + return this.baseBiome.isEqualTo(biomegenbase); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenOcean.java b/src/game/java/net/minecraft/world/biome/BiomeGenOcean.java index 852fccfc..a8963c53 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenOcean.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenOcean.java @@ -1,26 +1,28 @@ package net.minecraft.world.biome; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,12 +33,12 @@ public class BiomeGenOcean extends BiomeGenBase { this.spawnableCreatureList.clear(); } - public BiomeGenBase.TempCategory getTempCategory() { - return BiomeGenBase.TempCategory.OCEAN; - } - public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, double d0) { super.genTerrainBlocks(world, random, chunkprimer, i, j, d0); } + + public BiomeGenBase.TempCategory getTempCategory() { + return BiomeGenBase.TempCategory.OCEAN; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenPlains.java b/src/game/java/net/minecraft/world/biome/BiomeGenPlains.java index 4ae0ae43..b5be2416 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenPlains.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenPlains.java @@ -7,22 +7,25 @@ import net.minecraft.entity.passive.EntityHorse; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,29 +43,13 @@ public class BiomeGenPlains extends BiomeGenBase { this.theBiomeDecorator.grassPerChunk = 10; } - public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom random, BlockPos blockpos) { - double d0 = GRASS_COLOR_NOISE.func_151601_a((double) blockpos.getX() / 200.0D, - (double) blockpos.getZ() / 200.0D); - if (d0 < -0.8D) { - int j = random.nextInt(4); - switch (j) { - case 0: - return BlockFlower.EnumFlowerType.ORANGE_TULIP; - case 1: - return BlockFlower.EnumFlowerType.RED_TULIP; - case 2: - return BlockFlower.EnumFlowerType.PINK_TULIP; - case 3: - default: - return BlockFlower.EnumFlowerType.WHITE_TULIP; - } - } else if (random.nextInt(3) > 0) { - int i = random.nextInt(3); - return i == 0 ? BlockFlower.EnumFlowerType.POPPY - : (i == 1 ? BlockFlower.EnumFlowerType.HOUSTONIA : BlockFlower.EnumFlowerType.OXEYE_DAISY); - } else { - return BlockFlower.EnumFlowerType.DANDELION; - } + protected BiomeGenBase createMutatedBiome(int i) { + BiomeGenPlains biomegenplains = new BiomeGenPlains(i); + biomegenplains.setBiomeName("Sunflower Plains"); + biomegenplains.field_150628_aC = true; + biomegenplains.setColor(9286496); + biomegenplains.field_150609_ah = 14273354; + return biomegenplains; } public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { @@ -98,12 +85,28 @@ public class BiomeGenPlains extends BiomeGenBase { super.decorate(world, random, blockpos); } - protected BiomeGenBase createMutatedBiome(int i) { - BiomeGenPlains biomegenplains = new BiomeGenPlains(i); - biomegenplains.setBiomeName("Sunflower Plains"); - biomegenplains.field_150628_aC = true; - biomegenplains.setColor(9286496); - biomegenplains.field_150609_ah = 14273354; - return biomegenplains; + public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom random, BlockPos blockpos) { + double d0 = GRASS_COLOR_NOISE.func_151601_a((double) blockpos.getX() / 200.0D, + (double) blockpos.getZ() / 200.0D); + if (d0 < -0.8D) { + int j = random.nextInt(4); + switch (j) { + case 0: + return BlockFlower.EnumFlowerType.ORANGE_TULIP; + case 1: + return BlockFlower.EnumFlowerType.RED_TULIP; + case 2: + return BlockFlower.EnumFlowerType.PINK_TULIP; + case 3: + default: + return BlockFlower.EnumFlowerType.WHITE_TULIP; + } + } else if (random.nextInt(3) > 0) { + int i = random.nextInt(3); + return i == 0 ? BlockFlower.EnumFlowerType.POPPY + : (i == 1 ? BlockFlower.EnumFlowerType.HOUSTONIA : BlockFlower.EnumFlowerType.OXEYE_DAISY); + } else { + return BlockFlower.EnumFlowerType.DANDELION; + } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenRiver.java b/src/game/java/net/minecraft/world/biome/BiomeGenRiver.java index e8f1c403..9e323714 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenRiver.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenRiver.java @@ -1,21 +1,24 @@ package net.minecraft.world.biome; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenSavanna.java b/src/game/java/net/minecraft/world/biome/BiomeGenSavanna.java index 9a064839..ee643591 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenSavanna.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenSavanna.java @@ -11,28 +11,59 @@ import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.feature.WorldGenAbstractTree; import net.minecraft.world.gen.feature.WorldGenSavannaTree; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class BiomeGenSavanna extends BiomeGenBase { + public static class Mutated extends BiomeGenMutated { + public Mutated(int parInt1, BiomeGenBase parBiomeGenBase) { + super(parInt1, parBiomeGenBase); + this.theBiomeDecorator.treesPerChunk = 2; + this.theBiomeDecorator.flowersPerChunk = 2; + this.theBiomeDecorator.grassPerChunk = 5; + } + + public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { + this.theBiomeDecorator.decorate(world, random, this, blockpos); + } + + public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, + double d0) { + this.topBlock = Blocks.grass.getDefaultState(); + this.fillerBlock = Blocks.dirt.getDefaultState(); + if (d0 > 1.75D) { + this.topBlock = Blocks.stone.getDefaultState(); + this.fillerBlock = Blocks.stone.getDefaultState(); + } else if (d0 > -0.5D) { + this.topBlock = Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, + BlockDirt.DirtType.COARSE_DIRT); + } + + this.generateBiomeTerrain(world, random, chunkprimer, i, j, d0); + } + } + private static final WorldGenSavannaTree field_150627_aC = new WorldGenSavannaTree(false); protected BiomeGenSavanna(int parInt1) { @@ -43,10 +74,6 @@ public class BiomeGenSavanna extends BiomeGenBase { this.theBiomeDecorator.grassPerChunk = 20; } - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return (WorldGenAbstractTree) (random.nextInt(5) > 0 ? field_150627_aC : this.worldGeneratorTrees); - } - protected BiomeGenBase createMutatedBiome(int i) { BiomeGenSavanna.Mutated biomegensavanna$mutated = new BiomeGenSavanna.Mutated(i, this); biomegensavanna$mutated.temperature = (this.temperature + 1.0F) * 0.5F; @@ -68,31 +95,7 @@ public class BiomeGenSavanna extends BiomeGenBase { super.decorate(world, random, blockpos); } - public static class Mutated extends BiomeGenMutated { - public Mutated(int parInt1, BiomeGenBase parBiomeGenBase) { - super(parInt1, parBiomeGenBase); - this.theBiomeDecorator.treesPerChunk = 2; - this.theBiomeDecorator.flowersPerChunk = 2; - this.theBiomeDecorator.grassPerChunk = 5; - } - - public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, - double d0) { - this.topBlock = Blocks.grass.getDefaultState(); - this.fillerBlock = Blocks.dirt.getDefaultState(); - if (d0 > 1.75D) { - this.topBlock = Blocks.stone.getDefaultState(); - this.fillerBlock = Blocks.stone.getDefaultState(); - } else if (d0 > -0.5D) { - this.topBlock = Blocks.dirt.getDefaultState().withProperty(BlockDirt.VARIANT, - BlockDirt.DirtType.COARSE_DIRT); - } - - this.generateBiomeTerrain(world, random, chunkprimer, i, j, d0); - } - - public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { - this.theBiomeDecorator.decorate(world, random, this, blockpos); - } + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return (WorldGenAbstractTree) (random.nextInt(5) > 0 ? field_150627_aC : this.worldGeneratorTrees); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenSnow.java b/src/game/java/net/minecraft/world/biome/BiomeGenSnow.java index fa7b1f5d..7585ed05 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenSnow.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenSnow.java @@ -9,22 +9,25 @@ import net.minecraft.world.gen.feature.WorldGenIcePath; import net.minecraft.world.gen.feature.WorldGenIceSpike; import net.minecraft.world.gen.feature.WorldGenTaiga2; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +47,15 @@ public class BiomeGenSnow extends BiomeGenBase { this.spawnableCreatureList.clear(); } + protected BiomeGenBase createMutatedBiome(int i) { + BiomeGenBase biomegenbase = (new BiomeGenSnow(i, true)).func_150557_a(13828095, true) + .setBiomeName(this.biomeName + " Spikes").setEnableSnow().setTemperatureRainfall(0.0F, 0.5F) + .setHeight(new BiomeGenBase.Height(this.minHeight + 0.1F, this.maxHeight + 0.1F)); + biomegenbase.minHeight = this.minHeight + 0.3F; + biomegenbase.maxHeight = this.maxHeight + 0.4F; + return biomegenbase; + } + public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { if (this.field_150615_aC) { for (int i = 0; i < 3; ++i) { @@ -65,13 +77,4 @@ public class BiomeGenSnow extends BiomeGenBase { public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom var1) { return new WorldGenTaiga2(false); } - - protected BiomeGenBase createMutatedBiome(int i) { - BiomeGenBase biomegenbase = (new BiomeGenSnow(i, true)).func_150557_a(13828095, true) - .setBiomeName(this.biomeName + " Spikes").setEnableSnow().setTemperatureRainfall(0.0F, 0.5F) - .setHeight(new BiomeGenBase.Height(this.minHeight + 0.1F, this.maxHeight + 0.1F)); - biomegenbase.minHeight = this.minHeight + 0.3F; - biomegenbase.maxHeight = this.maxHeight + 0.4F; - return biomegenbase; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenStoneBeach.java b/src/game/java/net/minecraft/world/biome/BiomeGenStoneBeach.java index 8bb35378..5f3ac917 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenStoneBeach.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenStoneBeach.java @@ -2,22 +2,25 @@ package net.minecraft.world.biome; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenSwamp.java b/src/game/java/net/minecraft/world/biome/BiomeGenSwamp.java index 144356dc..e906dc13 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenSwamp.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenSwamp.java @@ -10,22 +10,25 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.feature.WorldGenAbstractTree; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -51,20 +54,6 @@ public class BiomeGenSwamp extends BiomeGenBase { return this.worldGeneratorSwamp; } - public int getGrassColorAtPos(BlockPos blockpos) { - double d0 = GRASS_COLOR_NOISE.func_151601_a((double) blockpos.getX() * 0.0225D, - (double) blockpos.getZ() * 0.0225D); - return d0 < -0.1D ? 5011004 : 6975545; - } - - public int getFoliageColorAtPos(BlockPos var1) { - return 6975545; - } - - public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom var1, BlockPos var2) { - return BlockFlower.EnumFlowerType.BLUE_ORCHID; - } - public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, double d0) { double d1 = GRASS_COLOR_NOISE.func_151601_a((double) i * 0.25D, (double) j * 0.25D); @@ -87,4 +76,18 @@ public class BiomeGenSwamp extends BiomeGenBase { this.generateBiomeTerrain(world, random, chunkprimer, i, j, d0); } + + public int getFoliageColorAtPos(BlockPos var1) { + return 6975545; + } + + public int getGrassColorAtPos(BlockPos blockpos) { + double d0 = GRASS_COLOR_NOISE.func_151601_a((double) blockpos.getX() * 0.0225D, + (double) blockpos.getZ() * 0.0225D); + return d0 < -0.1D ? 5011004 : 6975545; + } + + public BlockFlower.EnumFlowerType pickRandomFlower(EaglercraftRandom var1, BlockPos var2) { + return BlockFlower.EnumFlowerType.BLUE_ORCHID; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/BiomeGenTaiga.java b/src/game/java/net/minecraft/world/biome/BiomeGenTaiga.java index a9e7bcc3..9ef90a87 100644 --- a/src/game/java/net/minecraft/world/biome/BiomeGenTaiga.java +++ b/src/game/java/net/minecraft/world/biome/BiomeGenTaiga.java @@ -17,22 +17,25 @@ import net.minecraft.world.gen.feature.WorldGenTaiga2; import net.minecraft.world.gen.feature.WorldGenTallGrass; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,19 +65,10 @@ public class BiomeGenTaiga extends BiomeGenBase { } - public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { - return (WorldGenAbstractTree) ((this.field_150644_aH == 1 || this.field_150644_aH == 2) - && random.nextInt(3) == 0 - ? (this.field_150644_aH != 2 && random.nextInt(13) != 0 ? field_150641_aE : field_150642_aF) - : (random.nextInt(3) == 0 ? field_150639_aC : field_150640_aD)); - } - - /**+ - * Gets a WorldGen appropriate for this biome. - */ - public WorldGenerator getRandomWorldGenForGrass(EaglercraftRandom random) { - return random.nextInt(5) > 0 ? new WorldGenTallGrass(BlockTallGrass.EnumType.FERN) - : new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); + protected BiomeGenBase createMutatedBiome(int i) { + return this.biomeID == BiomeGenBase.megaTaiga.biomeID ? (new BiomeGenTaiga(i, 2)).func_150557_a(5858897, true) + .setBiomeName("Mega Spruce Taiga").setFillerBlockMetadata(5159473).setTemperatureRainfall(0.25F, 0.8F) + .setHeight(new BiomeGenBase.Height(this.minHeight, this.maxHeight)) : super.createMutatedBiome(i); } public void decorate(World world, EaglercraftRandom random, BlockPos blockpos) { @@ -101,6 +95,13 @@ public class BiomeGenTaiga extends BiomeGenBase { super.decorate(world, random, blockpos); } + public WorldGenAbstractTree genBigTreeChance(EaglercraftRandom random) { + return (WorldGenAbstractTree) ((this.field_150644_aH == 1 || this.field_150644_aH == 2) + && random.nextInt(3) == 0 + ? (this.field_150644_aH != 2 && random.nextInt(13) != 0 ? field_150641_aE : field_150642_aF) + : (random.nextInt(3) == 0 ? field_150639_aC : field_150640_aD)); + } + public void genTerrainBlocks(World world, EaglercraftRandom random, ChunkPrimer chunkprimer, int i, int j, double d0) { if (this.field_150644_aH == 1 || this.field_150644_aH == 2) { @@ -118,9 +119,11 @@ public class BiomeGenTaiga extends BiomeGenBase { this.generateBiomeTerrain(world, random, chunkprimer, i, j, d0); } - protected BiomeGenBase createMutatedBiome(int i) { - return this.biomeID == BiomeGenBase.megaTaiga.biomeID ? (new BiomeGenTaiga(i, 2)).func_150557_a(5858897, true) - .setBiomeName("Mega Spruce Taiga").setFillerBlockMetadata(5159473).setTemperatureRainfall(0.25F, 0.8F) - .setHeight(new BiomeGenBase.Height(this.minHeight, this.maxHeight)) : super.createMutatedBiome(i); + /** + * + Gets a WorldGen appropriate for this biome. + */ + public WorldGenerator getRandomWorldGenForGrass(EaglercraftRandom random) { + return random.nextInt(5) > 0 ? new WorldGenTallGrass(BlockTallGrass.EnumType.FERN) + : new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/WorldChunkManager.java b/src/game/java/net/minecraft/world/biome/WorldChunkManager.java index fd0bdfd3..6f0c4a38 100644 --- a/src/game/java/net/minecraft/world/biome/WorldChunkManager.java +++ b/src/game/java/net/minecraft/world/biome/WorldChunkManager.java @@ -1,7 +1,9 @@ package net.minecraft.world.biome; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; @@ -12,22 +14,25 @@ import net.minecraft.world.WorldType; import net.minecraft.world.gen.layer.GenLayer; import net.minecraft.world.gen.layer.IntCache; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -64,30 +69,152 @@ public class WorldChunkManager { this(worldIn.getSeed(), worldIn.getWorldInfo().getTerrainType(), worldIn.getWorldInfo().getGeneratorOptions()); } - /**+ - * Gets the list of valid biomes for the player to spawn in. + /** + * + checks given Chunk's Biomes against List of allowed ones */ - public List getBiomesToSpawnIn() { - return this.biomesToSpawnIn; + public boolean areBiomesViable(int parInt1, int parInt2, int parInt3, List parList) { + IntCache.resetIntCache(); + int i = parInt1 - parInt3 >> 2; + int j = parInt2 - parInt3 >> 2; + int k = parInt1 + parInt3 >> 2; + int l = parInt2 + parInt3 >> 2; + int i1 = k - i + 1; + int j1 = l - j + 1; + int[] aint = this.genBiomes.getInts(i, j, i1, j1); + + try { + for (int k1 = 0; k1 < i1 * j1; ++k1) { + BiomeGenBase biomegenbase = BiomeGenBase.getBiome(aint[k1]); + if (!parList.contains(biomegenbase)) { + return false; + } + } + + return true; + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Invalid Biome id"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Layer"); + crashreportcategory.addCrashSection("Layer", this.genBiomes.toString()); + crashreportcategory.addCrashSection("x", Integer.valueOf(parInt1)); + crashreportcategory.addCrashSection("z", Integer.valueOf(parInt2)); + crashreportcategory.addCrashSection("radius", Integer.valueOf(parInt3)); + crashreportcategory.addCrashSection("allowed", parList); + throw new ReportedException(crashreport); + } } - /**+ - * Returns the biome generator + /** + * + Calls the WorldChunkManager's biomeCache.cleanupCache() + */ + public void cleanupCache() { + this.biomeCache.cleanupCache(); + } + + public BlockPos findBiomePosition(int x, int z, int range, List biomes, EaglercraftRandom random) { + IntCache.resetIntCache(); + int i = x - range >> 2; + int j = z - range >> 2; + int k = x + range >> 2; + int l = z + range >> 2; + int i1 = k - i + 1; + int j1 = l - j + 1; + int[] aint = this.genBiomes.getInts(i, j, i1, j1); + BlockPos blockpos = null; + int k1 = 0; + + for (int l1 = 0; l1 < i1 * j1; ++l1) { + int i2 = i + l1 % i1 << 2; + int j2 = j + l1 / i1 << 2; + BiomeGenBase biomegenbase = BiomeGenBase.getBiome(aint[l1]); + if (biomes.contains(biomegenbase) && (blockpos == null || random.nextInt(k1 + 1) == 0)) { + blockpos = new BlockPos(i2, 0, j2); + ++k1; + } + } + + return blockpos; + } + + /** + * + Return a list of biomes for the specified blocks. Args: listToReuse, x, y, + * width, length, cacheFlag (if false, don't check biomeCache to avoid infinite + * loop in BiomeCacheBlock) + */ + public BiomeGenBase[] getBiomeGenAt(BiomeGenBase[] listToReuse, int x, int z, int width, int length, + boolean cacheFlag) { + IntCache.resetIntCache(); + if (listToReuse == null || listToReuse.length < width * length) { + listToReuse = new BiomeGenBase[width * length]; + } + + if (cacheFlag && width == 16 && length == 16 && (x & 15) == 0 && (z & 15) == 0) { + BiomeGenBase[] abiomegenbase = this.biomeCache.getCachedBiomes(x, z); + System.arraycopy(abiomegenbase, 0, listToReuse, 0, width * length); + return listToReuse; + } else { + int[] aint = this.biomeIndexLayer.getInts(x, z, width, length); + + for (int i = 0; i < width * length; ++i) { + listToReuse[i] = BiomeGenBase.getBiomeFromBiomeList(aint[i], BiomeGenBase.field_180279_ad); + } + + return listToReuse; + } + } + + /** + * + Returns the biome generator */ public BiomeGenBase getBiomeGenerator(BlockPos pos) { return this.getBiomeGenerator(pos, (BiomeGenBase) null); } - /**+ - * Returns the biome generator + /** + * + Returns the biome generator */ public BiomeGenBase getBiomeGenerator(BlockPos pos, BiomeGenBase biomeGenBaseIn) { return this.biomeCache.func_180284_a(pos.getX(), pos.getZ(), biomeGenBaseIn); } - /**+ - * Returns a list of rainfall values for the specified blocks. - * Args: listToReuse, x, z, width, length. + /** + * + Returns an array of biomes for the location input. + */ + public BiomeGenBase[] getBiomesForGeneration(BiomeGenBase[] biomes, int x, int z, int width, int height) { + IntCache.resetIntCache(); + if (biomes == null || biomes.length < width * height) { + biomes = new BiomeGenBase[width * height]; + } + + int[] aint = this.genBiomes.getInts(x, z, width, height); + + try { + for (int i = 0; i < width * height; ++i) { + biomes[i] = BiomeGenBase.getBiomeFromBiomeList(aint[i], BiomeGenBase.field_180279_ad); + } + + return biomes; + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Invalid Biome id"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("RawBiomeBlock"); + crashreportcategory.addCrashSection("biomes[] size", Integer.valueOf(biomes.length)); + crashreportcategory.addCrashSection("x", Integer.valueOf(x)); + crashreportcategory.addCrashSection("z", Integer.valueOf(z)); + crashreportcategory.addCrashSection("w", Integer.valueOf(width)); + crashreportcategory.addCrashSection("h", Integer.valueOf(height)); + throw new ReportedException(crashreport); + } + } + + /** + * + Gets the list of valid biomes for the player to spawn in. + */ + public List getBiomesToSpawnIn() { + return this.biomesToSpawnIn; + } + + /** + * + Returns a list of rainfall values for the specified blocks. Args: + * listToReuse, x, z, width, length. */ public float[] getRainfall(float[] listToReuse, int x, int z, int width, int length) { IntCache.resetIntCache(); @@ -122,142 +249,19 @@ public class WorldChunkManager { return listToReuse; } - /**+ - * Return an adjusted version of a given temperature based on - * the y height + /** + * + Return an adjusted version of a given temperature based on the y height */ public float getTemperatureAtHeight(float parFloat1, int parInt1) { return parFloat1; } - /**+ - * Returns an array of biomes for the location input. - */ - public BiomeGenBase[] getBiomesForGeneration(BiomeGenBase[] biomes, int x, int z, int width, int height) { - IntCache.resetIntCache(); - if (biomes == null || biomes.length < width * height) { - biomes = new BiomeGenBase[width * height]; - } - - int[] aint = this.genBiomes.getInts(x, z, width, height); - - try { - for (int i = 0; i < width * height; ++i) { - biomes[i] = BiomeGenBase.getBiomeFromBiomeList(aint[i], BiomeGenBase.field_180279_ad); - } - - return biomes; - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Invalid Biome id"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("RawBiomeBlock"); - crashreportcategory.addCrashSection("biomes[] size", Integer.valueOf(biomes.length)); - crashreportcategory.addCrashSection("x", Integer.valueOf(x)); - crashreportcategory.addCrashSection("z", Integer.valueOf(z)); - crashreportcategory.addCrashSection("w", Integer.valueOf(width)); - crashreportcategory.addCrashSection("h", Integer.valueOf(height)); - throw new ReportedException(crashreport); - } - } - - /**+ - * Returns biomes to use for the blocks and loads the other data - * like temperature and humidity onto the WorldChunkManager - * Args: oldBiomeList, x, z, width, depth + /** + * + Returns biomes to use for the blocks and loads the other data like + * temperature and humidity onto the WorldChunkManager Args: oldBiomeList, x, z, + * width, depth */ public BiomeGenBase[] loadBlockGeneratorData(BiomeGenBase[] oldBiomeList, int x, int z, int width, int depth) { return this.getBiomeGenAt(oldBiomeList, x, z, width, depth, true); } - - /**+ - * Return a list of biomes for the specified blocks. Args: - * listToReuse, x, y, width, length, cacheFlag (if false, don't - * check biomeCache to avoid infinite loop in BiomeCacheBlock) - */ - public BiomeGenBase[] getBiomeGenAt(BiomeGenBase[] listToReuse, int x, int z, int width, int length, - boolean cacheFlag) { - IntCache.resetIntCache(); - if (listToReuse == null || listToReuse.length < width * length) { - listToReuse = new BiomeGenBase[width * length]; - } - - if (cacheFlag && width == 16 && length == 16 && (x & 15) == 0 && (z & 15) == 0) { - BiomeGenBase[] abiomegenbase = this.biomeCache.getCachedBiomes(x, z); - System.arraycopy(abiomegenbase, 0, listToReuse, 0, width * length); - return listToReuse; - } else { - int[] aint = this.biomeIndexLayer.getInts(x, z, width, length); - - for (int i = 0; i < width * length; ++i) { - listToReuse[i] = BiomeGenBase.getBiomeFromBiomeList(aint[i], BiomeGenBase.field_180279_ad); - } - - return listToReuse; - } - } - - /**+ - * checks given Chunk's Biomes against List of allowed ones - */ - public boolean areBiomesViable(int parInt1, int parInt2, int parInt3, List parList) { - IntCache.resetIntCache(); - int i = parInt1 - parInt3 >> 2; - int j = parInt2 - parInt3 >> 2; - int k = parInt1 + parInt3 >> 2; - int l = parInt2 + parInt3 >> 2; - int i1 = k - i + 1; - int j1 = l - j + 1; - int[] aint = this.genBiomes.getInts(i, j, i1, j1); - - try { - for (int k1 = 0; k1 < i1 * j1; ++k1) { - BiomeGenBase biomegenbase = BiomeGenBase.getBiome(aint[k1]); - if (!parList.contains(biomegenbase)) { - return false; - } - } - - return true; - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Invalid Biome id"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Layer"); - crashreportcategory.addCrashSection("Layer", this.genBiomes.toString()); - crashreportcategory.addCrashSection("x", Integer.valueOf(parInt1)); - crashreportcategory.addCrashSection("z", Integer.valueOf(parInt2)); - crashreportcategory.addCrashSection("radius", Integer.valueOf(parInt3)); - crashreportcategory.addCrashSection("allowed", parList); - throw new ReportedException(crashreport); - } - } - - public BlockPos findBiomePosition(int x, int z, int range, List biomes, EaglercraftRandom random) { - IntCache.resetIntCache(); - int i = x - range >> 2; - int j = z - range >> 2; - int k = x + range >> 2; - int l = z + range >> 2; - int i1 = k - i + 1; - int j1 = l - j + 1; - int[] aint = this.genBiomes.getInts(i, j, i1, j1); - BlockPos blockpos = null; - int k1 = 0; - - for (int l1 = 0; l1 < i1 * j1; ++l1) { - int i2 = i + l1 % i1 << 2; - int j2 = j + l1 / i1 << 2; - BiomeGenBase biomegenbase = BiomeGenBase.getBiome(aint[l1]); - if (biomes.contains(biomegenbase) && (blockpos == null || random.nextInt(k1 + 1) == 0)) { - blockpos = new BlockPos(i2, 0, j2); - ++k1; - } - } - - return blockpos; - } - - /**+ - * Calls the WorldChunkManager's biomeCache.cleanupCache() - */ - public void cleanupCache() { - this.biomeCache.cleanupCache(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/biome/WorldChunkManagerHell.java b/src/game/java/net/minecraft/world/biome/WorldChunkManagerHell.java index e58c45c5..344eddb1 100644 --- a/src/game/java/net/minecraft/world/biome/WorldChunkManagerHell.java +++ b/src/game/java/net/minecraft/world/biome/WorldChunkManagerHell.java @@ -2,25 +2,29 @@ package net.minecraft.world.biome; import java.util.Arrays; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.util.BlockPos; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,15 +38,37 @@ public class WorldChunkManagerHell extends WorldChunkManager { this.rainfall = parFloat1; } - /**+ - * Returns the biome generator + /** + * + checks given Chunk's Biomes against List of allowed ones + */ + public boolean areBiomesViable(int var1, int var2, int var3, List list) { + return list.contains(this.biomeGenerator); + } + + public BlockPos findBiomePosition(int i, int j, int k, List list, EaglercraftRandom random) { + return list.contains(this.biomeGenerator) + ? new BlockPos(i - k + random.nextInt(k * 2 + 1), 0, j - k + random.nextInt(k * 2 + 1)) + : null; + } + + /** + * + Return a list of biomes for the specified blocks. Args: listToReuse, x, y, + * width, length, cacheFlag (if false, don't check biomeCache to avoid infinite + * loop in BiomeCacheBlock) + */ + public BiomeGenBase[] getBiomeGenAt(BiomeGenBase[] abiomegenbase, int i, int j, int k, int l, boolean var6) { + return this.loadBlockGeneratorData(abiomegenbase, i, j, k, l); + } + + /** + * + Returns the biome generator */ public BiomeGenBase getBiomeGenerator(BlockPos var1) { return this.biomeGenerator; } - /**+ - * Returns an array of biomes for the location input. + /** + * + Returns an array of biomes for the location input. */ public BiomeGenBase[] getBiomesForGeneration(BiomeGenBase[] abiomegenbase, int var2, int var3, int i, int j) { if (abiomegenbase == null || abiomegenbase.length < i * j) { @@ -53,9 +79,9 @@ public class WorldChunkManagerHell extends WorldChunkManager { return abiomegenbase; } - /**+ - * Returns a list of rainfall values for the specified blocks. - * Args: listToReuse, x, z, width, length. + /** + * + Returns a list of rainfall values for the specified blocks. Args: + * listToReuse, x, z, width, length. */ public float[] getRainfall(float[] afloat, int var2, int var3, int i, int j) { if (afloat == null || afloat.length < i * j) { @@ -66,10 +92,10 @@ public class WorldChunkManagerHell extends WorldChunkManager { return afloat; } - /**+ - * Returns biomes to use for the blocks and loads the other data - * like temperature and humidity onto the WorldChunkManager - * Args: oldBiomeList, x, z, width, depth + /** + * + Returns biomes to use for the blocks and loads the other data like + * temperature and humidity onto the WorldChunkManager Args: oldBiomeList, x, z, + * width, depth */ public BiomeGenBase[] loadBlockGeneratorData(BiomeGenBase[] abiomegenbase, int var2, int var3, int i, int j) { if (abiomegenbase == null || abiomegenbase.length < i * j) { @@ -79,26 +105,4 @@ public class WorldChunkManagerHell extends WorldChunkManager { Arrays.fill(abiomegenbase, 0, i * j, this.biomeGenerator); return abiomegenbase; } - - /**+ - * Return a list of biomes for the specified blocks. Args: - * listToReuse, x, y, width, length, cacheFlag (if false, don't - * check biomeCache to avoid infinite loop in BiomeCacheBlock) - */ - public BiomeGenBase[] getBiomeGenAt(BiomeGenBase[] abiomegenbase, int i, int j, int k, int l, boolean var6) { - return this.loadBlockGeneratorData(abiomegenbase, i, j, k, l); - } - - public BlockPos findBiomePosition(int i, int j, int k, List list, EaglercraftRandom random) { - return list.contains(this.biomeGenerator) - ? new BlockPos(i - k + random.nextInt(k * 2 + 1), 0, j - k + random.nextInt(k * 2 + 1)) - : null; - } - - /**+ - * checks given Chunk's Biomes against List of allowed ones - */ - public boolean areBiomesViable(int var1, int var2, int var3, List list) { - return list.contains(this.biomeGenerator); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/border/EnumBorderStatus.java b/src/game/java/net/minecraft/world/border/EnumBorderStatus.java index e4079402..25bd10a5 100644 --- a/src/game/java/net/minecraft/world/border/EnumBorderStatus.java +++ b/src/game/java/net/minecraft/world/border/EnumBorderStatus.java @@ -1,21 +1,24 @@ package net.minecraft.world.border; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,10 +32,9 @@ public enum EnumBorderStatus { this.id = id; } - /**+ - * Returns an integer that represents the state of the world - * border. Growing, Shrinking and Stationary all have unique - * values. + /** + * + Returns an integer that represents the state of the world border. Growing, + * Shrinking and Stationary all have unique values. */ public int getID() { return this.id; diff --git a/src/game/java/net/minecraft/world/border/IBorderListener.java b/src/game/java/net/minecraft/world/border/IBorderListener.java index 6a735a8f..d0feb086 100644 --- a/src/game/java/net/minecraft/world/border/IBorderListener.java +++ b/src/game/java/net/minecraft/world/border/IBorderListener.java @@ -1,37 +1,40 @@ package net.minecraft.world.border; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IBorderListener { - void onSizeChanged(WorldBorder var1, double var2); - - void onTransitionStarted(WorldBorder var1, double var2, double var4, long var6); - void onCenterChanged(WorldBorder var1, double var2, double var4); - void onWarningTimeChanged(WorldBorder var1, int var2); - - void onWarningDistanceChanged(WorldBorder var1, int var2); - void onDamageAmountChanged(WorldBorder var1, double var2); void onDamageBufferChanged(WorldBorder var1, double var2); + + void onSizeChanged(WorldBorder var1, double var2); + + void onTransitionStarted(WorldBorder var1, double var2, double var4, long var6); + + void onWarningDistanceChanged(WorldBorder var1, int var2); + + void onWarningTimeChanged(WorldBorder var1, int var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/border/WorldBorder.java b/src/game/java/net/minecraft/world/border/WorldBorder.java index 7115be20..6a4046f6 100644 --- a/src/game/java/net/minecraft/world/border/WorldBorder.java +++ b/src/game/java/net/minecraft/world/border/WorldBorder.java @@ -10,22 +10,25 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.world.ChunkCoordIntPair; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,6 +56,14 @@ public class WorldBorder { this.warningDistance = 5; } + public void addListener(IBorderListener listener) { + this.listeners.add(listener); + } + + public boolean contains(AxisAlignedBB bb) { + return bb.maxX > this.minX() && bb.minX < this.maxX() && bb.maxZ > this.minZ() && bb.minZ < this.maxZ(); + } + public boolean contains(BlockPos pos) { return (double) (pos.getX() + 1) > this.minX() && (double) pos.getX() < this.maxX() && (double) (pos.getZ() + 1) > this.minZ() && (double) pos.getZ() < this.maxZ(); @@ -63,12 +74,12 @@ public class WorldBorder { && (double) range.getZEnd() > this.minZ() && (double) range.getZStart() < this.maxZ(); } - public boolean contains(AxisAlignedBB bb) { - return bb.maxX > this.minX() && bb.minX < this.maxX() && bb.maxZ > this.minZ() && bb.minZ < this.maxZ(); + public double getCenterX() { + return this.centerX; } - public double getClosestDistance(Entity entityIn) { - return this.getClosestDistance(entityIn.posX, entityIn.posZ); + public double getCenterZ() { + return this.centerZ; } public double getClosestDistance(double x, double z) { @@ -81,27 +92,64 @@ public class WorldBorder { return Math.min(d4, d1); } + public double getClosestDistance(Entity entityIn) { + return this.getClosestDistance(entityIn.posX, entityIn.posZ); + } + + public double getDamageAmount() { + return this.damageAmount; + } + + public double getDamageBuffer() { + return this.damageBuffer; + } + + public double getDiameter() { + if (this.getStatus() != EnumBorderStatus.STATIONARY) { + double d0 = (double) ((float) (EagRuntime.steadyTimeMillis() - this.startTime) + / (float) (this.endTime - this.startTime)); + if (d0 < 1.0D) { + return this.startDiameter + (this.endDiameter - this.startDiameter) * d0; + } + + this.setTransition(this.endDiameter); + } + + return this.startDiameter; + } + + protected List getListeners() { + return Lists.newArrayList(this.listeners); + } + + public double getResizeSpeed() { + return this.endTime == this.startTime ? 0.0D + : Math.abs(this.startDiameter - this.endDiameter) / (double) (this.endTime - this.startTime); + } + + public int getSize() { + return this.worldSize; + } + public EnumBorderStatus getStatus() { return this.endDiameter < this.startDiameter ? EnumBorderStatus.SHRINKING : (this.endDiameter > this.startDiameter ? EnumBorderStatus.GROWING : EnumBorderStatus.STATIONARY); } - public double minX() { - double d0 = this.getCenterX() - this.getDiameter() / 2.0D; - if (d0 < (double) (-this.worldSize)) { - d0 = (double) (-this.worldSize); - } - - return d0; + public double getTargetSize() { + return this.endDiameter; } - public double minZ() { - double d0 = this.getCenterZ() - this.getDiameter() / 2.0D; - if (d0 < (double) (-this.worldSize)) { - d0 = (double) (-this.worldSize); - } + public long getTimeUntilTarget() { + return this.getStatus() != EnumBorderStatus.STATIONARY ? this.endTime - EagRuntime.steadyTimeMillis() : 0L; + } - return d0; + public int getWarningDistance() { + return this.warningDistance; + } + + public int getWarningTime() { + return this.warningTime; } public double maxX() { @@ -122,12 +170,22 @@ public class WorldBorder { return d0; } - public double getCenterX() { - return this.centerX; + public double minX() { + double d0 = this.getCenterX() - this.getDiameter() / 2.0D; + if (d0 < (double) (-this.worldSize)) { + d0 = (double) (-this.worldSize); + } + + return d0; } - public double getCenterZ() { - return this.centerZ; + public double minZ() { + double d0 = this.getCenterZ() - this.getDiameter() / 2.0D; + if (d0 < (double) (-this.worldSize)) { + d0 = (double) (-this.worldSize); + } + + return d0; } public void setCenter(double x, double z) { @@ -141,26 +199,28 @@ public class WorldBorder { } - public double getDiameter() { - if (this.getStatus() != EnumBorderStatus.STATIONARY) { - double d0 = (double) ((float) (EagRuntime.steadyTimeMillis() - this.startTime) - / (float) (this.endTime - this.startTime)); - if (d0 < 1.0D) { - return this.startDiameter + (this.endDiameter - this.startDiameter) * d0; - } + public void setDamageAmount(double newAmount) { + this.damageAmount = newAmount; - this.setTransition(this.endDiameter); + List lst = this.getListeners(); + for (int i = 0, l = lst.size(); i < l; ++i) { + lst.get(i).onDamageAmountChanged(this, newAmount); } - return this.startDiameter; } - public long getTimeUntilTarget() { - return this.getStatus() != EnumBorderStatus.STATIONARY ? this.endTime - EagRuntime.steadyTimeMillis() : 0L; + public void setDamageBuffer(double bufferSize) { + this.damageBuffer = bufferSize; + + List lst = this.getListeners(); + for (int i = 0, l = lst.size(); i < l; ++i) { + lst.get(i).onDamageBufferChanged(this, bufferSize); + } + } - public double getTargetSize() { - return this.endDiameter; + public void setSize(int size) { + this.worldSize = size; } public void setTransition(double newSize) { @@ -189,59 +249,16 @@ public class WorldBorder { } - protected List getListeners() { - return Lists.newArrayList(this.listeners); - } - - public void addListener(IBorderListener listener) { - this.listeners.add(listener); - } - - public void setSize(int size) { - this.worldSize = size; - } - - public int getSize() { - return this.worldSize; - } - - public double getDamageBuffer() { - return this.damageBuffer; - } - - public void setDamageBuffer(double bufferSize) { - this.damageBuffer = bufferSize; + public void setWarningDistance(int warningDistance) { + this.warningDistance = warningDistance; List lst = this.getListeners(); for (int i = 0, l = lst.size(); i < l; ++i) { - lst.get(i).onDamageBufferChanged(this, bufferSize); + lst.get(i).onWarningDistanceChanged(this, warningDistance); } } - public double getDamageAmount() { - return this.damageAmount; - } - - public void setDamageAmount(double newAmount) { - this.damageAmount = newAmount; - - List lst = this.getListeners(); - for (int i = 0, l = lst.size(); i < l; ++i) { - lst.get(i).onDamageAmountChanged(this, newAmount); - } - - } - - public double getResizeSpeed() { - return this.endTime == this.startTime ? 0.0D - : Math.abs(this.startDiameter - this.endDiameter) / (double) (this.endTime - this.startTime); - } - - public int getWarningTime() { - return this.warningTime; - } - public void setWarningTime(int warningTime) { this.warningTime = warningTime; @@ -251,18 +268,4 @@ public class WorldBorder { } } - - public int getWarningDistance() { - return this.warningDistance; - } - - public void setWarningDistance(int warningDistance) { - this.warningDistance = warningDistance; - - List lst = this.getListeners(); - for (int i = 0, l = lst.size(); i < l; ++i) { - lst.get(i).onWarningDistanceChanged(this, warningDistance); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/Chunk.java b/src/game/java/net/minecraft/world/chunk/Chunk.java index 31c624cb..2b9e71e9 100644 --- a/src/game/java/net/minecraft/world/chunk/Chunk.java +++ b/src/game/java/net/minecraft/world/chunk/Chunk.java @@ -1,15 +1,18 @@ package net.minecraft.world.chunk; -import com.google.common.base.Predicate; -import com.google.common.collect.Maps; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import java.util.concurrent.Callable; +import com.google.common.base.Predicate; +import com.google.common.collect.Maps; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; @@ -32,32 +35,41 @@ import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.WorldChunkManager; import net.minecraft.world.chunk.storage.ExtendedBlockStorage; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.DeferredStateManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Chunk { + public static enum EnumCreateEntityType { + IMMEDIATE, QUEUED, CHECK; + } + private static final Logger logger = LogManager.getLogger(); + + public static int getNoSkyLightValue() { + return DeferredStateManager.isDeferredRenderer() ? 5 : 0; + } + private final ExtendedBlockStorage[] storageArrays; private final byte[] blockBiomeArray; private final int[] precipitationHeightMap; @@ -78,31 +90,11 @@ public class Chunk { private long lastSaveTime; private int heightMapMinimum; private long inhabitedTime; + private int queuedLightChecks; + private List tileEntityPosQueue; - public Chunk(World worldIn, int x, int z) { - this.storageArrays = new ExtendedBlockStorage[16]; - this.blockBiomeArray = new byte[256]; - this.precipitationHeightMap = new int[256]; - this.updateSkylightColumns = new boolean[256]; - this.chunkTileEntityMap = Maps.newHashMap(); - this.queuedLightChecks = 4096; - this.tileEntityPosQueue = new LinkedList(); - this.entityLists = (ClassInheritanceMultiMap[]) (new ClassInheritanceMultiMap[16]); - this.worldObj = worldIn; - this.xPosition = x; - this.zPosition = z; - this.heightMap = new int[256]; - - for (int i = 0; i < this.entityLists.length; ++i) { - this.entityLists[i] = new ClassInheritanceMultiMap(Entity.class); - } - - Arrays.fill(this.precipitationHeightMap, -999); - Arrays.fill(this.blockBiomeArray, (byte) -1); - } - public Chunk(World worldIn, ChunkPrimer primer, int x, int z) { this(worldIn, x, z); short short1 = 256; @@ -127,48 +119,328 @@ public class Chunk { } - /**+ - * Checks whether the chunk is at the X/Z location specified - */ - public boolean isAtLocation(int i, int j) { - return i == this.xPosition && j == this.zPosition; + public Chunk(World worldIn, int x, int z) { + this.storageArrays = new ExtendedBlockStorage[16]; + this.blockBiomeArray = new byte[256]; + this.precipitationHeightMap = new int[256]; + this.updateSkylightColumns = new boolean[256]; + this.chunkTileEntityMap = Maps.newHashMap(); + this.queuedLightChecks = 4096; + this.tileEntityPosQueue = new LinkedList(); + this.entityLists = (ClassInheritanceMultiMap[]) (new ClassInheritanceMultiMap[16]); + this.worldObj = worldIn; + this.xPosition = x; + this.zPosition = z; + this.heightMap = new int[256]; + + for (int i = 0; i < this.entityLists.length; ++i) { + this.entityLists[i] = new ClassInheritanceMultiMap(Entity.class); + } + + Arrays.fill(this.precipitationHeightMap, -999); + Arrays.fill(this.blockBiomeArray, (byte) -1); } - public int getHeight(BlockPos pos) { - return this.getHeightValue(pos.getX() & 15, pos.getZ() & 15); + /** + * + Adds an entity to the chunk. Args: entity + */ + public void addEntity(Entity entity) { + this.hasEntities = true; + int i = MathHelper.floor_double(entity.posX / 16.0D); + int j = MathHelper.floor_double(entity.posZ / 16.0D); + if (i != this.xPosition || j != this.zPosition) { + logger.warn("Wrong location! (" + i + ", " + j + ") should be (" + this.xPosition + ", " + this.zPosition + + "), " + entity, new Object[] { entity }); + entity.setDead(); + } + + int k = MathHelper.floor_double(entity.posY / 16.0D); + if (k < 0) { + k = 0; + } + + if (k >= this.entityLists.length) { + k = this.entityLists.length - 1; + } + + entity.addedToChunk = true; + entity.chunkCoordX = this.xPosition; + entity.chunkCoordY = k; + entity.chunkCoordZ = this.zPosition; + this.entityLists[k].add(entity); } - /**+ - * Returns the value in the height map at this x, z coordinate - * in the chunk - */ - public int getHeightValue(int i, int j) { - return this.heightMap[j << 4 | i]; + public void addTileEntity(BlockPos blockpos, TileEntity tileentity) { + tileentity.setWorldObj(this.worldObj); + tileentity.setPos(blockpos); + if (this.getBlock(blockpos) instanceof ITileEntityProvider) { + if (this.chunkTileEntityMap.containsKey(blockpos)) { + ((TileEntity) this.chunkTileEntityMap.get(blockpos)).invalidate(); + } + + tileentity.validate(); + this.chunkTileEntityMap.put(blockpos, tileentity); + } } - /**+ - * Returns the topmost ExtendedBlockStorage instance for this - * Chunk that actually contains a block. + public void addTileEntity(TileEntity tileentity) { + this.addTileEntity(tileentity.getPos(), tileentity); + if (this.isChunkLoaded) { + this.worldObj.addTileEntity(tileentity); + } + + } + + public boolean canSeeSky(BlockPos blockpos) { + int i = blockpos.getX() & 15; + int j = blockpos.getY(); + int k = blockpos.getZ() & 15; + return j >= this.heightMap[k << 4 | i]; + } + + /** + * + Checks the height of a block next to a sky-visible block and schedules a + * lighting update as necessary. */ - public int getTopFilledSegment() { - for (int i = this.storageArrays.length - 1; i >= 0; --i) { - if (this.storageArrays[i] != null) { - return this.storageArrays[i].getYLocation(); + private void checkSkylightNeighborHeight(int x, int z, int maxValue) { + int i = this.worldObj.getHeight(new BlockPos(x, 0, z)).getY(); + if (i > maxValue) { + this.updateSkylightNeighborHeight(x, z, maxValue, i + 1); + } else if (i < maxValue) { + this.updateSkylightNeighborHeight(x, z, i, maxValue + 1); + } + + } + + private TileEntity createNewTileEntity(BlockPos pos) { + Block block = this.getBlock(pos); + return !block.hasTileEntity() ? null + : ((ITileEntityProvider) block).createNewTileEntity(this.worldObj, this.getBlockMetadata(pos)); + } + + /** + * + Called once-per-chunk-per-tick, and advances the round-robin relight check + * index by up to 8 blocks at a time. In a worst-case scenario, can potentially + * take up to 25.6 seconds, calculated via (4096/8)/20, to re-check all blocks + * in a chunk, which may explain lagging light updates on initial world + * generation. + */ + public void enqueueRelightChecks() { + BlockPos blockpos = new BlockPos(this.xPosition << 4, 0, this.zPosition << 4); + + for (int i = 0; i < 8; ++i) { + if (this.queuedLightChecks >= 4096) { + return; + } + + int j = this.queuedLightChecks % 16; + int k = this.queuedLightChecks / 16 % 16; + int l = this.queuedLightChecks / 256; + ++this.queuedLightChecks; + + EnumFacing[] facings = EnumFacing._VALUES; + for (int i1 = 0; i1 < 16; ++i1) { + BlockPos blockpos1 = blockpos.add(k, (j << 4) + i1, l); + boolean flag = i1 == 0 || i1 == 15 || k == 0 || k == 15 || l == 0 || l == 15; + if (this.storageArrays[j] == null && flag || this.storageArrays[j] != null + && this.storageArrays[j].getBlockByExtId(k, i1, l).getMaterial() == Material.air) { + for (int m = 0; m < facings.length; ++m) { + BlockPos blockpos2 = blockpos1.offset(facings[m]); + if (this.worldObj.getBlockState(blockpos2).getBlock().getLightValue() > 0) { + this.worldObj.checkLight(blockpos2); + } + } + + this.worldObj.checkLight(blockpos1); + } } } - return 0; } - /**+ - * Returns the ExtendedBlockStorage array for this Chunk. + /** + * + Initialize this chunk with new binary data. */ - public ExtendedBlockStorage[] getBlockStorageArray() { - return this.storageArrays; + public void fillChunk(byte[] parArrayOfByte, int parInt1, boolean parFlag) { + int i = 0; + boolean flag = !this.worldObj.provider.getHasNoSky(); + + for (int j = 0; j < this.storageArrays.length; ++j) { + if ((parInt1 & 1 << j) != 0) { + if (this.storageArrays[j] == null) { + this.storageArrays[j] = new ExtendedBlockStorage(j << 4, flag); + } + + char[] achar = this.storageArrays[j].getData(); + + for (int k = 0; k < achar.length; ++k) { + achar[k] = (char) ((parArrayOfByte[i + 1] & 255) << 8 | parArrayOfByte[i] & 255); + i += 2; + } + } else if (parFlag && this.storageArrays[j] != null) { + this.storageArrays[j] = null; + } + } + + for (int l = 0; l < this.storageArrays.length; ++l) { + if ((parInt1 & 1 << l) != 0 && this.storageArrays[l] != null) { + NibbleArray nibblearray = this.storageArrays[l].getBlocklightArray(); + System.arraycopy(parArrayOfByte, i, nibblearray.getData(), 0, nibblearray.getData().length); + i += nibblearray.getData().length; + } + } + + if (flag) { + for (int i1 = 0; i1 < this.storageArrays.length; ++i1) { + if ((parInt1 & 1 << i1) != 0 && this.storageArrays[i1] != null) { + NibbleArray nibblearray1 = this.storageArrays[i1].getSkylightArray(); + System.arraycopy(parArrayOfByte, i, nibblearray1.getData(), 0, nibblearray1.getData().length); + i += nibblearray1.getData().length; + } + } + } + + if (parFlag) { + System.arraycopy(parArrayOfByte, i, this.blockBiomeArray, 0, this.blockBiomeArray.length); + int k1 = i + this.blockBiomeArray.length; + } + + for (int j1 = 0; j1 < this.storageArrays.length; ++j1) { + if (this.storageArrays[j1] != null && (parInt1 & 1 << j1) != 0) { + this.storageArrays[j1].removeInvalidBlocks(); + } + } + + this.isLightPopulated = true; + this.isTerrainPopulated = true; + this.generateHeightMap(); + + for (TileEntity tileentity : this.chunkTileEntityMap.values()) { + tileentity.updateContainingBlockInfo(); + } + } - /**+ - * Generates the height map for a chunk from scratch + public void func_150804_b(boolean parFlag) { + if (this.isGapLightingUpdated && !this.worldObj.provider.getHasNoSky() && !parFlag) { + this.recheckGaps(this.worldObj.isRemote); + } + + this.field_150815_m = true; + if (!this.isLightPopulated && this.isTerrainPopulated) { + this.func_150809_p(); + } + + while (!this.tileEntityPosQueue.isEmpty()) { + BlockPos blockpos = (BlockPos) this.tileEntityPosQueue.remove(0); + if (this.getTileEntity(blockpos, Chunk.EnumCreateEntityType.CHECK) == null + && this.getBlock(blockpos).hasTileEntity()) { + TileEntity tileentity = this.createNewTileEntity(blockpos); + this.worldObj.setTileEntity(blockpos, tileentity); + this.worldObj.markBlockRangeForRenderUpdate(blockpos, blockpos); + } + } + + } + + public void func_150809_p() { + this.isTerrainPopulated = true; + this.isLightPopulated = true; + BlockPos blockpos = new BlockPos(this.xPosition << 4, 0, this.zPosition << 4); + if (!this.worldObj.provider.getHasNoSky()) { + if (this.worldObj.isAreaLoaded(blockpos.add(-1, 0, -1), + blockpos.add(16, this.worldObj.func_181545_F(), 16))) { + label92: for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + if (!this.func_150811_f(i, j)) { + this.isLightPopulated = false; + break label92; + } + } + } + + if (this.isLightPopulated) { + EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; + for (int i = 0; i < facings.length; ++i) { + EnumFacing enumfacing = facings[i]; + int k = enumfacing.getAxisDirection() == EnumFacing.AxisDirection.POSITIVE ? 16 : 1; + this.worldObj.getChunkFromBlockCoords(blockpos.offset(enumfacing, k)) + .func_180700_a(enumfacing.getOpposite()); + } + + this.func_177441_y(); + } + } else { + this.isLightPopulated = false; + } + } + + } + + private boolean func_150811_f(int x, int z) { + int i = this.getTopFilledSegment(); + boolean flag = false; + boolean flag1 = false; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos((this.xPosition << 4) + x, 0, + (this.zPosition << 4) + z); + + for (int j = i + 16 - 1; j > this.worldObj.func_181545_F() || j > 0 && !flag1; --j) { + blockpos$mutableblockpos.func_181079_c(blockpos$mutableblockpos.getX(), j, blockpos$mutableblockpos.getZ()); + int k = this.getBlockLightOpacity(blockpos$mutableblockpos); + if (k == 255 && blockpos$mutableblockpos.getY() < this.worldObj.func_181545_F()) { + flag1 = true; + } + + if (!flag && k > 0) { + flag = true; + } else if (flag && k == 0 && !this.worldObj.checkLight(blockpos$mutableblockpos)) { + return false; + } + } + + for (int l = blockpos$mutableblockpos.getY(); l > 0; --l) { + blockpos$mutableblockpos.func_181079_c(blockpos$mutableblockpos.getX(), l, blockpos$mutableblockpos.getZ()); + if (this.getBlock(blockpos$mutableblockpos).getLightValue() > 0) { + this.worldObj.checkLight(blockpos$mutableblockpos); + } + } + + return true; + } + + private void func_177441_y() { + for (int i = 0; i < this.updateSkylightColumns.length; ++i) { + this.updateSkylightColumns[i] = true; + } + + this.recheckGaps(false); + } + + private void func_180700_a(EnumFacing parEnumFacing) { + if (this.isTerrainPopulated) { + if (parEnumFacing == EnumFacing.EAST) { + for (int i = 0; i < 16; ++i) { + this.func_150811_f(15, i); + } + } else if (parEnumFacing == EnumFacing.WEST) { + for (int j = 0; j < 16; ++j) { + this.func_150811_f(0, j); + } + } else if (parEnumFacing == EnumFacing.SOUTH) { + for (int k = 0; k < 16; ++k) { + this.func_150811_f(k, 15); + } + } else if (parEnumFacing == EnumFacing.NORTH) { + for (int l = 0; l < 16; ++l) { + this.func_150811_f(l, 0); + } + } + + } + } + + /** + * + Generates the height map for a chunk from scratch */ protected void generateHeightMap() { int i = this.getTopFilledSegment(); @@ -194,9 +466,8 @@ public class Chunk { this.isModified = true; } - /**+ - * Generates the initial skylight map for the chunk upon - * generation or load. + /** + * + Generates the initial skylight map for the chunk upon generation or load. */ public void generateSkylightMap() { int i = this.getTopFilledSegment(); @@ -251,9 +522,509 @@ public class Chunk { this.isModified = true; } - /**+ - * Propagates a given sky-visible block's light value downward - * and upward to neighboring blocks as necessary. + /** + * + Returns whether the ExtendedBlockStorages containing levels (in blocks) + * from arg 1 to arg 2 are fully empty (true) or not (false). + */ + public boolean getAreLevelsEmpty(int i, int j) { + if (i < 0) { + i = 0; + } + + if (j >= 256) { + j = 255; + } + + for (int k = i; k <= j; k += 16) { + ExtendedBlockStorage extendedblockstorage = this.storageArrays[k >> 4]; + if (extendedblockstorage != null && !extendedblockstorage.isEmpty()) { + return false; + } + } + + return true; + } + + public BiomeGenBase getBiome(BlockPos pos, WorldChunkManager chunkManager) { + int i = pos.getX() & 15; + int j = pos.getZ() & 15; + int k = this.blockBiomeArray[j << 4 | i] & 255; + if (chunkManager != null && k == 255) { + BiomeGenBase biomegenbase = chunkManager.getBiomeGenerator(pos, BiomeGenBase.plains); + k = biomegenbase.biomeID; + this.blockBiomeArray[j << 4 | i] = (byte) (k & 255); + } + + BiomeGenBase biomegenbase1 = BiomeGenBase.getBiome(k); + return biomegenbase1 == null ? BiomeGenBase.plains : biomegenbase1; + } + + /** + * + Returns an array containing a 16x16 mapping on the X/Z of block positions + * in this Chunk to biome IDs. + */ + public byte[] getBiomeArray() { + return this.blockBiomeArray; + } + + public Block getBlock(final BlockPos blockpos) { + try { + return this.getBlock0(blockpos.getX() & 15, blockpos.getY(), blockpos.getZ() & 15); + } catch (ReportedException reportedexception) { + CrashReportCategory crashreportcategory = reportedexception.getCrashReport() + .makeCategory("Block being got"); + crashreportcategory.addCrashSectionCallable("Location", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo(blockpos); + } + }); + throw reportedexception; + } + } + + public Block getBlock(final int x, final int y, final int z) { + try { + return this.getBlock0(x & 15, y, z & 15); + } catch (ReportedException reportedexception) { + CrashReportCategory crashreportcategory = reportedexception.getCrashReport() + .makeCategory("Block being got"); + crashreportcategory.addCrashSectionCallable("Location", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo( + new BlockPos(Chunk.this.xPosition * 16 + x, y, Chunk.this.zPosition * 16 + z)); + } + }); + throw reportedexception; + } + } + + /** + * + Returns the block corresponding to the given coordinates inside a chunk. + */ + private Block getBlock0(int x, int y, int z) { + Block block = Blocks.air; + if (y >= 0 && y >> 4 < this.storageArrays.length) { + ExtendedBlockStorage extendedblockstorage = this.storageArrays[y >> 4]; + if (extendedblockstorage != null) { + try { + block = extendedblockstorage.getBlockByExtId(x, y & 15, z); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block"); + throw new ReportedException(crashreport); + } + } + } + + return block; + } + + public int getBlockLightOpacity(BlockPos blockpos) { + return this.getBlock(blockpos).getLightOpacity(); + } + + private int getBlockLightOpacity(int x, int y, int z) { + return this.getBlock0(x, y, z).getLightOpacity(); + } + + /** + * + Return the metadata corresponding to the given coordinates inside a chunk. + */ + public int getBlockMetadata(BlockPos blockpos) { + return this.getBlockMetadata(blockpos.getX() & 15, blockpos.getY(), blockpos.getZ() & 15); + } + + /** + * + Return the metadata corresponding to the given coordinates inside a chunk. + */ + private int getBlockMetadata(int x, int y, int z) { + if (y >> 4 >= this.storageArrays.length) { + return 0; + } else { + ExtendedBlockStorage extendedblockstorage = this.storageArrays[y >> 4]; + return extendedblockstorage != null ? extendedblockstorage.getExtBlockMetadata(x, y & 15, z) : 0; + } + } + + public IBlockState getBlockState(final BlockPos pos) { + try { + if (pos.getY() >= 0 && pos.getY() >> 4 < this.storageArrays.length) { + ExtendedBlockStorage extendedblockstorage = this.storageArrays[pos.getY() >> 4]; + if (extendedblockstorage != null) { + int j = pos.getX() & 15; + int k = pos.getY() & 15; + int i = pos.getZ() & 15; + return extendedblockstorage.get(j, k, i); + } + } + + return Blocks.air.getDefaultState(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block state"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being got"); + crashreportcategory.addCrashSectionCallable("Location", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo(pos); + } + }); + throw new ReportedException(crashreport); + } + } + + /** + * only use with a regular "net.minecraft.util.BlockPos"! + */ + public IBlockState getBlockStateFaster(final BlockPos pos) { + try { + if (pos.y >= 0 && pos.y >> 4 < this.storageArrays.length) { + ExtendedBlockStorage extendedblockstorage = this.storageArrays[pos.getY() >> 4]; + if (extendedblockstorage != null) { + int j = pos.x & 15; + int k = pos.y & 15; + int i = pos.z & 15; + return extendedblockstorage.get(j, k, i); + } + } + + return Blocks.air.getDefaultState(); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block state"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being got"); + crashreportcategory.addCrashSectionCallable("Location", new Callable() { + public String call() throws Exception { + return CrashReportCategory.getCoordinateInfo(pos); + } + }); + throw new ReportedException(crashreport); + } + } + + /** + * + Returns the ExtendedBlockStorage array for this Chunk. + */ + public ExtendedBlockStorage[] getBlockStorageArray() { + return this.storageArrays; + } + + /** + * + Gets a ChunkCoordIntPair representing the Chunk's position. + */ + public ChunkCoordIntPair getChunkCoordIntPair() { + return new ChunkCoordIntPair(this.xPosition, this.zPosition); + } + + public void getEntitiesOfTypeWithinAAAB(Class oclass, AxisAlignedBB axisalignedbb, + List list, Predicate predicate) { + int i = MathHelper.floor_double((axisalignedbb.minY - 2.0D) / 16.0D); + int j = MathHelper.floor_double((axisalignedbb.maxY + 2.0D) / 16.0D); + i = MathHelper.clamp_int(i, 0, this.entityLists.length - 1); + j = MathHelper.clamp_int(j, 0, this.entityLists.length - 1); + + for (int k = i; k <= j; ++k) { + for (Entity entity : this.entityLists[k].getByClass(oclass)) { + if (entity.getEntityBoundingBox().intersectsWith(axisalignedbb) + && (predicate == null || predicate.apply((T) entity))) { + list.add((T) entity); + } + } + } + + } + + /** + * + Fills the given list of all entities that intersect within the given + * bounding box that aren't the passed entity. + */ + public void getEntitiesWithinAABBForEntity(Entity entity, AxisAlignedBB axisalignedbb, List list, + Predicate predicate) { + int i = MathHelper.floor_double((axisalignedbb.minY - 2.0D) / 16.0D); + int j = MathHelper.floor_double((axisalignedbb.maxY + 2.0D) / 16.0D); + i = MathHelper.clamp_int(i, 0, this.entityLists.length - 1); + j = MathHelper.clamp_int(j, 0, this.entityLists.length - 1); + + for (int k = i; k <= j; ++k) { + if (!this.entityLists[k].isEmpty()) { + for (Entity entity1 : this.entityLists[k]) { + if (entity1.getEntityBoundingBox().intersectsWith(axisalignedbb) && entity1 != entity) { + if (predicate == null || predicate.apply(entity1)) { + list.add(entity1); + } + + Entity[] aentity = entity1.getParts(); + if (aentity != null) { + for (int l = 0; l < aentity.length; ++l) { + entity1 = aentity[l]; + if (entity1 != entity && entity1.getEntityBoundingBox().intersectsWith(axisalignedbb) + && (predicate == null || predicate.apply(entity1))) { + list.add(entity1); + } + } + } + } + } + } + } + + } + + public ClassInheritanceMultiMap[] getEntityLists() { + return this.entityLists; + } + + public int getHeight(BlockPos pos) { + return this.getHeightValue(pos.getX() & 15, pos.getZ() & 15); + } + + public int[] getHeightMap() { + return this.heightMap; + } + + /** + * + Returns the value in the height map at this x, z coordinate in the chunk + */ + public int getHeightValue(int i, int j) { + return this.heightMap[j << 4 | i]; + } + + public long getInhabitedTime() { + return this.inhabitedTime; + } + + public int getLightFor(EnumSkyBlock enumskyblock, BlockPos blockpos) { + int i = blockpos.getX() & 15; + int j = blockpos.getY(); + int k = blockpos.getZ() & 15; + ExtendedBlockStorage extendedblockstorage = this.storageArrays[j >> 4]; + return extendedblockstorage == null + ? (this.canSeeSky(blockpos) ? enumskyblock.defaultLightValue : getNoSkyLightValue()) + : (enumskyblock == EnumSkyBlock.SKY + ? (this.worldObj.provider.getHasNoSky() ? getNoSkyLightValue() + : extendedblockstorage.getExtSkylightValue(i, j & 15, k)) + : (enumskyblock == EnumSkyBlock.BLOCK ? extendedblockstorage.getExtBlocklightValue(i, j & 15, k) + : enumskyblock.defaultLightValue)); + } + + public int getLightSubtracted(BlockPos blockpos, int i) { + int j = blockpos.getX() & 15; + int k = blockpos.getY(); + int l = blockpos.getZ() & 15; + ExtendedBlockStorage extendedblockstorage = this.storageArrays[k >> 4]; + if (extendedblockstorage == null) { + return !this.worldObj.provider.getHasNoSky() && i < EnumSkyBlock.SKY.defaultLightValue + ? EnumSkyBlock.SKY.defaultLightValue - i + : getNoSkyLightValue(); + } else { + int i1 = this.worldObj.provider.getHasNoSky() ? getNoSkyLightValue() + : extendedblockstorage.getExtSkylightValue(j, k & 15, l); + i1 = i1 - i; + int j1 = extendedblockstorage.getExtBlocklightValue(j, k & 15, l); + if (j1 > i1) { + i1 = j1; + } + + return i1; + } + } + + public int getLowestHeight() { + return this.heightMapMinimum; + } + + public BlockPos getPrecipitationHeight(BlockPos pos) { + int i = pos.getX() & 15; + int j = pos.getZ() & 15; + int k = i | j << 4; + BlockPos blockpos = new BlockPos(pos.getX(), this.precipitationHeightMap[k], pos.getZ()); + if (blockpos.getY() == -999) { + int l = this.getTopFilledSegment() + 15; + blockpos = new BlockPos(pos.getX(), l, pos.getZ()); + int i1 = -1; + + while (blockpos.getY() > 0 && i1 == -1) { + Block block = this.getBlock(blockpos); + Material material = block.getMaterial(); + if (!material.blocksMovement() && !material.isLiquid()) { + blockpos = blockpos.down(); + } else { + i1 = blockpos.getY() + 1; + } + } + + this.precipitationHeightMap[k] = i1; + } + + return new BlockPos(pos.getX(), this.precipitationHeightMap[k], pos.getZ()); + } + + public EaglercraftRandom getRandomWithSeed(long i) { + return new EaglercraftRandom(this.worldObj.getSeed() + (long) (this.xPosition * this.xPosition * 4987142) + + (long) (this.xPosition * 5947611) + (long) (this.zPosition * this.zPosition) * 4392871L + + (long) (this.zPosition * 389711) ^ i, !this.worldObj.getWorldInfo().isOldEaglercraftRandom()); + } + + public TileEntity getTileEntity(BlockPos blockpos, Chunk.EnumCreateEntityType chunk$enumcreateentitytype) { + TileEntity tileentity = (TileEntity) this.chunkTileEntityMap.get(blockpos); + if (tileentity == null) { + if (chunk$enumcreateentitytype == Chunk.EnumCreateEntityType.IMMEDIATE) { + tileentity = this.createNewTileEntity(blockpos); + this.worldObj.setTileEntity(blockpos, tileentity); + } else if (chunk$enumcreateentitytype == Chunk.EnumCreateEntityType.QUEUED) { + this.tileEntityPosQueue.add(blockpos); + } + } else if (tileentity.isInvalid()) { + this.chunkTileEntityMap.remove(blockpos); + return null; + } + + return tileentity; + } + + public Map getTileEntityMap() { + return this.chunkTileEntityMap; + } + + /** + * + Returns the topmost ExtendedBlockStorage instance for this Chunk that + * actually contains a block. + */ + public int getTopFilledSegment() { + for (int i = this.storageArrays.length - 1; i >= 0; --i) { + if (this.storageArrays[i] != null) { + return this.storageArrays[i].getYLocation(); + } + } + + return 0; + } + + public World getWorld() { + return this.worldObj; + } + + /** + * + Checks whether the chunk is at the X/Z location specified + */ + public boolean isAtLocation(int i, int j) { + return i == this.xPosition && j == this.zPosition; + } + + public boolean isEmpty() { + return false; + } + + public boolean isLightPopulated() { + return this.isLightPopulated; + } + + public boolean isLoaded() { + return this.isChunkLoaded; + } + + public boolean isPopulated() { + return this.field_150815_m && this.isTerrainPopulated && this.isLightPopulated; + } + + public boolean isTerrainPopulated() { + return this.isTerrainPopulated; + } + + /** + * + Returns true if this Chunk needs to be saved + */ + public boolean needsSaving(boolean flag) { + if (flag) { + if (this.hasEntities && this.worldObj.getTotalWorldTime() != this.lastSaveTime || this.isModified) { + return true; + } + } else if (this.hasEntities && this.worldObj.getTotalWorldTime() >= this.lastSaveTime + 600L) { + return true; + } + + return this.isModified; + } + + /** + * + Called when this Chunk is loaded by the ChunkProvider + */ + public void onChunkLoad() { + this.isChunkLoaded = true; + this.worldObj.addTileEntities(this.chunkTileEntityMap.values()); + + for (int i = 0; i < this.entityLists.length; ++i) { + for (Entity entity : this.entityLists[i]) { + entity.onChunkLoad(); + } + + this.worldObj.loadEntities(this.entityLists[i]); + } + + } + + /** + * + Called when this Chunk is unloaded by the ChunkProvider + */ + public void onChunkUnload() { + this.isChunkLoaded = false; + + for (TileEntity tileentity : this.chunkTileEntityMap.values()) { + this.worldObj.markTileEntityForRemoval(tileentity); + } + + for (int i = 0; i < this.entityLists.length; ++i) { + this.worldObj.unloadEntities(this.entityLists[i]); + } + + } + + public void populateChunk(IChunkProvider parIChunkProvider, IChunkProvider parIChunkProvider2, int parInt1, + int parInt2) { + boolean flag = parIChunkProvider.chunkExists(parInt1, parInt2 - 1); + boolean flag1 = parIChunkProvider.chunkExists(parInt1 + 1, parInt2); + boolean flag2 = parIChunkProvider.chunkExists(parInt1, parInt2 + 1); + boolean flag3 = parIChunkProvider.chunkExists(parInt1 - 1, parInt2); + boolean flag4 = parIChunkProvider.chunkExists(parInt1 - 1, parInt2 - 1); + boolean flag5 = parIChunkProvider.chunkExists(parInt1 + 1, parInt2 + 1); + boolean flag6 = parIChunkProvider.chunkExists(parInt1 - 1, parInt2 + 1); + boolean flag7 = parIChunkProvider.chunkExists(parInt1 + 1, parInt2 - 1); + if (flag1 && flag2 && flag5) { + if (!this.isTerrainPopulated) { + parIChunkProvider.populate(parIChunkProvider2, parInt1, parInt2); + } else { + parIChunkProvider.func_177460_a(parIChunkProvider2, this, parInt1, parInt2); + } + } + + if (flag3 && flag2 && flag6) { + Chunk chunk = parIChunkProvider.provideChunk(parInt1 - 1, parInt2); + if (!chunk.isTerrainPopulated) { + parIChunkProvider.populate(parIChunkProvider2, parInt1 - 1, parInt2); + } else { + parIChunkProvider.func_177460_a(parIChunkProvider2, chunk, parInt1 - 1, parInt2); + } + } + + if (flag && flag1 && flag7) { + Chunk chunk1 = parIChunkProvider.provideChunk(parInt1, parInt2 - 1); + if (!chunk1.isTerrainPopulated) { + parIChunkProvider.populate(parIChunkProvider2, parInt1, parInt2 - 1); + } else { + parIChunkProvider.func_177460_a(parIChunkProvider2, chunk1, parInt1, parInt2 - 1); + } + } + + if (flag4 && flag && flag3) { + Chunk chunk2 = parIChunkProvider.provideChunk(parInt1 - 1, parInt2 - 1); + if (!chunk2.isTerrainPopulated) { + parIChunkProvider.populate(parIChunkProvider2, parInt1 - 1, parInt2 - 1); + } else { + parIChunkProvider.func_177460_a(parIChunkProvider2, chunk2, parInt1 - 1, parInt2 - 1); + } + } + + } + + /** + * + Propagates a given sky-visible block's light value downward and upward to + * neighboring blocks as necessary. */ private void propagateSkylightOcclusion(int x, int z) { this.updateSkylightColumns[x + z * 16] = true; @@ -297,34 +1068,9 @@ public class Chunk { } } - /**+ - * Checks the height of a block next to a sky-visible block and - * schedules a lighting update as necessary. - */ - private void checkSkylightNeighborHeight(int x, int z, int maxValue) { - int i = this.worldObj.getHeight(new BlockPos(x, 0, z)).getY(); - if (i > maxValue) { - this.updateSkylightNeighborHeight(x, z, maxValue, i + 1); - } else if (i < maxValue) { - this.updateSkylightNeighborHeight(x, z, i, maxValue + 1); - } - - } - - private void updateSkylightNeighborHeight(int x, int z, int startY, int endY) { - if (endY > startY && this.worldObj.isAreaLoaded(new BlockPos(x, 0, z), 16)) { - for (int i = startY; i < endY; ++i) { - this.worldObj.checkLightFor(EnumSkyBlock.SKY, new BlockPos(x, i, z)); - } - - this.isModified = true; - } - - } - - /**+ - * Initiates the recalculation of both the block-light and - * sky-light for a given block inside a chunk. + /** + * + Initiates the recalculation of both the block-light and sky-light for a + * given block inside a chunk. */ private void relightBlock(int x, int y, int z) { int i = this.heightMap[z << 4 | x] & 255; @@ -414,140 +1160,61 @@ public class Chunk { } } - public int getBlockLightOpacity(BlockPos blockpos) { - return this.getBlock(blockpos).getLightOpacity(); - } - - private int getBlockLightOpacity(int x, int y, int z) { - return this.getBlock0(x, y, z).getLightOpacity(); - } - - /**+ - * Returns the block corresponding to the given coordinates - * inside a chunk. + /** + * + removes entity using its y chunk coordinate as its index */ - private Block getBlock0(int x, int y, int z) { - Block block = Blocks.air; - if (y >= 0 && y >> 4 < this.storageArrays.length) { - ExtendedBlockStorage extendedblockstorage = this.storageArrays[y >> 4]; - if (extendedblockstorage != null) { - try { - block = extendedblockstorage.getBlockByExtId(x, y & 15, z); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block"); - throw new ReportedException(crashreport); - } - } - } - - return block; - } - - public Block getBlock(final int x, final int y, final int z) { - try { - return this.getBlock0(x & 15, y, z & 15); - } catch (ReportedException reportedexception) { - CrashReportCategory crashreportcategory = reportedexception.getCrashReport() - .makeCategory("Block being got"); - crashreportcategory.addCrashSectionCallable("Location", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo( - new BlockPos(Chunk.this.xPosition * 16 + x, y, Chunk.this.zPosition * 16 + z)); - } - }); - throw reportedexception; - } - } - - public Block getBlock(final BlockPos blockpos) { - try { - return this.getBlock0(blockpos.getX() & 15, blockpos.getY(), blockpos.getZ() & 15); - } catch (ReportedException reportedexception) { - CrashReportCategory crashreportcategory = reportedexception.getCrashReport() - .makeCategory("Block being got"); - crashreportcategory.addCrashSectionCallable("Location", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo(blockpos); - } - }); - throw reportedexception; - } - } - - public IBlockState getBlockState(final BlockPos pos) { - try { - if (pos.getY() >= 0 && pos.getY() >> 4 < this.storageArrays.length) { - ExtendedBlockStorage extendedblockstorage = this.storageArrays[pos.getY() >> 4]; - if (extendedblockstorage != null) { - int j = pos.getX() & 15; - int k = pos.getY() & 15; - int i = pos.getZ() & 15; - return extendedblockstorage.get(j, k, i); - } - } - - return Blocks.air.getDefaultState(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block state"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being got"); - crashreportcategory.addCrashSectionCallable("Location", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo(pos); - } - }); - throw new ReportedException(crashreport); - } + public void removeEntity(Entity entity) { + this.removeEntityAtIndex(entity, entity.chunkCoordY); } /** - * only use with a regular "net.minecraft.util.BlockPos"! + * + Removes entity at the specified index from the entity array. */ - public IBlockState getBlockStateFaster(final BlockPos pos) { - try { - if (pos.y >= 0 && pos.y >> 4 < this.storageArrays.length) { - ExtendedBlockStorage extendedblockstorage = this.storageArrays[pos.getY() >> 4]; - if (extendedblockstorage != null) { - int j = pos.x & 15; - int k = pos.y & 15; - int i = pos.z & 15; - return extendedblockstorage.get(j, k, i); - } + public void removeEntityAtIndex(Entity entity, int i) { + if (i < 0) { + i = 0; + } + + if (i >= this.entityLists.length) { + i = this.entityLists.length - 1; + } + + this.entityLists[i].remove(entity); + } + + public void removeTileEntity(BlockPos blockpos) { + if (this.isChunkLoaded) { + TileEntity tileentity = (TileEntity) this.chunkTileEntityMap.remove(blockpos); + if (tileentity != null) { + tileentity.invalidate(); + } + } + + } + + /** + * + Resets the relight check index to 0 for this Chunk. + */ + public void resetRelightChecks() { + this.queuedLightChecks = 0; + } + + /** + * + Accepts a 256-entry array that contains a 16x16 mapping on the X/Z plane of + * block positions in this Chunk to biome IDs. + */ + public void setBiomeArray(byte[] biomeArray) { + if (this.blockBiomeArray.length != biomeArray.length) { + logger.warn("Could not set level chunk biomes, array length is " + biomeArray.length + " instead of " + + this.blockBiomeArray.length); + } else { + for (int i = 0; i < this.blockBiomeArray.length; ++i) { + this.blockBiomeArray[i] = biomeArray[i]; } - return Blocks.air.getDefaultState(); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Getting block state"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Block being got"); - crashreportcategory.addCrashSectionCallable("Location", new Callable() { - public String call() throws Exception { - return CrashReportCategory.getCoordinateInfo(pos); - } - }); - throw new ReportedException(crashreport); } } - /**+ - * Return the metadata corresponding to the given coordinates - * inside a chunk. - */ - private int getBlockMetadata(int x, int y, int z) { - if (y >> 4 >= this.storageArrays.length) { - return 0; - } else { - ExtendedBlockStorage extendedblockstorage = this.storageArrays[y >> 4]; - return extendedblockstorage != null ? extendedblockstorage.getExtBlockMetadata(x, y & 15, z) : 0; - } - } - - /**+ - * Return the metadata corresponding to the given coordinates - * inside a chunk. - */ - public int getBlockMetadata(BlockPos blockpos) { - return this.getBlockMetadata(blockpos.getX() & 15, blockpos.getY(), blockpos.getZ() & 15); - } - public IBlockState setBlockState(BlockPos pos, IBlockState state) { int i = pos.getX() & 15; int j = pos.getY(); @@ -637,18 +1304,39 @@ public class Chunk { } } - public int getLightFor(EnumSkyBlock enumskyblock, BlockPos blockpos) { - int i = blockpos.getX() & 15; - int j = blockpos.getY(); - int k = blockpos.getZ() & 15; - ExtendedBlockStorage extendedblockstorage = this.storageArrays[j >> 4]; - return extendedblockstorage == null - ? (this.canSeeSky(blockpos) ? enumskyblock.defaultLightValue : getNoSkyLightValue()) - : (enumskyblock == EnumSkyBlock.SKY - ? (this.worldObj.provider.getHasNoSky() ? getNoSkyLightValue() - : extendedblockstorage.getExtSkylightValue(i, j & 15, k)) - : (enumskyblock == EnumSkyBlock.BLOCK ? extendedblockstorage.getExtBlocklightValue(i, j & 15, k) - : enumskyblock.defaultLightValue)); + public void setChunkLoaded(boolean loaded) { + this.isChunkLoaded = loaded; + } + + /** + * + Sets the isModified flag for this Chunk + */ + public void setChunkModified() { + this.isModified = true; + } + + public void setHasEntities(boolean hasEntitiesIn) { + this.hasEntities = hasEntitiesIn; + } + + public void setHeightMap(int[] newHeightMap) { + if (this.heightMap.length != newHeightMap.length) { + logger.warn("Could not set level chunk heightmap, array length is " + newHeightMap.length + " instead of " + + this.heightMap.length); + } else { + for (int i = 0; i < this.heightMap.length; ++i) { + this.heightMap[i] = newHeightMap[i]; + } + + } + } + + public void setInhabitedTime(long newInhabitedTime) { + this.inhabitedTime = newInhabitedTime; + } + + public void setLastSaveTime(long saveTime) { + this.lastSaveTime = saveTime; } public void setLightFor(EnumSkyBlock enumskyblock, BlockPos blockpos, int i) { @@ -673,391 +1361,12 @@ public class Chunk { } - public int getLightSubtracted(BlockPos blockpos, int i) { - int j = blockpos.getX() & 15; - int k = blockpos.getY(); - int l = blockpos.getZ() & 15; - ExtendedBlockStorage extendedblockstorage = this.storageArrays[k >> 4]; - if (extendedblockstorage == null) { - return !this.worldObj.provider.getHasNoSky() && i < EnumSkyBlock.SKY.defaultLightValue - ? EnumSkyBlock.SKY.defaultLightValue - i - : getNoSkyLightValue(); - } else { - int i1 = this.worldObj.provider.getHasNoSky() ? getNoSkyLightValue() - : extendedblockstorage.getExtSkylightValue(j, k & 15, l); - i1 = i1 - i; - int j1 = extendedblockstorage.getExtBlocklightValue(j, k & 15, l); - if (j1 > i1) { - i1 = j1; - } - - return i1; - } + public void setLightPopulated(boolean lightPopulated) { + this.isLightPopulated = lightPopulated; } - public static int getNoSkyLightValue() { - return DeferredStateManager.isDeferredRenderer() ? 5 : 0; - } - - /**+ - * Adds an entity to the chunk. Args: entity - */ - public void addEntity(Entity entity) { - this.hasEntities = true; - int i = MathHelper.floor_double(entity.posX / 16.0D); - int j = MathHelper.floor_double(entity.posZ / 16.0D); - if (i != this.xPosition || j != this.zPosition) { - logger.warn("Wrong location! (" + i + ", " + j + ") should be (" + this.xPosition + ", " + this.zPosition - + "), " + entity, new Object[] { entity }); - entity.setDead(); - } - - int k = MathHelper.floor_double(entity.posY / 16.0D); - if (k < 0) { - k = 0; - } - - if (k >= this.entityLists.length) { - k = this.entityLists.length - 1; - } - - entity.addedToChunk = true; - entity.chunkCoordX = this.xPosition; - entity.chunkCoordY = k; - entity.chunkCoordZ = this.zPosition; - this.entityLists[k].add(entity); - } - - /**+ - * removes entity using its y chunk coordinate as its index - */ - public void removeEntity(Entity entity) { - this.removeEntityAtIndex(entity, entity.chunkCoordY); - } - - /**+ - * Removes entity at the specified index from the entity array. - */ - public void removeEntityAtIndex(Entity entity, int i) { - if (i < 0) { - i = 0; - } - - if (i >= this.entityLists.length) { - i = this.entityLists.length - 1; - } - - this.entityLists[i].remove(entity); - } - - public boolean canSeeSky(BlockPos blockpos) { - int i = blockpos.getX() & 15; - int j = blockpos.getY(); - int k = blockpos.getZ() & 15; - return j >= this.heightMap[k << 4 | i]; - } - - private TileEntity createNewTileEntity(BlockPos pos) { - Block block = this.getBlock(pos); - return !block.hasTileEntity() ? null - : ((ITileEntityProvider) block).createNewTileEntity(this.worldObj, this.getBlockMetadata(pos)); - } - - public TileEntity getTileEntity(BlockPos blockpos, Chunk.EnumCreateEntityType chunk$enumcreateentitytype) { - TileEntity tileentity = (TileEntity) this.chunkTileEntityMap.get(blockpos); - if (tileentity == null) { - if (chunk$enumcreateentitytype == Chunk.EnumCreateEntityType.IMMEDIATE) { - tileentity = this.createNewTileEntity(blockpos); - this.worldObj.setTileEntity(blockpos, tileentity); - } else if (chunk$enumcreateentitytype == Chunk.EnumCreateEntityType.QUEUED) { - this.tileEntityPosQueue.add(blockpos); - } - } else if (tileentity.isInvalid()) { - this.chunkTileEntityMap.remove(blockpos); - return null; - } - - return tileentity; - } - - public void addTileEntity(TileEntity tileentity) { - this.addTileEntity(tileentity.getPos(), tileentity); - if (this.isChunkLoaded) { - this.worldObj.addTileEntity(tileentity); - } - - } - - public void addTileEntity(BlockPos blockpos, TileEntity tileentity) { - tileentity.setWorldObj(this.worldObj); - tileentity.setPos(blockpos); - if (this.getBlock(blockpos) instanceof ITileEntityProvider) { - if (this.chunkTileEntityMap.containsKey(blockpos)) { - ((TileEntity) this.chunkTileEntityMap.get(blockpos)).invalidate(); - } - - tileentity.validate(); - this.chunkTileEntityMap.put(blockpos, tileentity); - } - } - - public void removeTileEntity(BlockPos blockpos) { - if (this.isChunkLoaded) { - TileEntity tileentity = (TileEntity) this.chunkTileEntityMap.remove(blockpos); - if (tileentity != null) { - tileentity.invalidate(); - } - } - - } - - /**+ - * Called when this Chunk is loaded by the ChunkProvider - */ - public void onChunkLoad() { - this.isChunkLoaded = true; - this.worldObj.addTileEntities(this.chunkTileEntityMap.values()); - - for (int i = 0; i < this.entityLists.length; ++i) { - for (Entity entity : this.entityLists[i]) { - entity.onChunkLoad(); - } - - this.worldObj.loadEntities(this.entityLists[i]); - } - - } - - /**+ - * Called when this Chunk is unloaded by the ChunkProvider - */ - public void onChunkUnload() { - this.isChunkLoaded = false; - - for (TileEntity tileentity : this.chunkTileEntityMap.values()) { - this.worldObj.markTileEntityForRemoval(tileentity); - } - - for (int i = 0; i < this.entityLists.length; ++i) { - this.worldObj.unloadEntities(this.entityLists[i]); - } - - } - - /**+ - * Sets the isModified flag for this Chunk - */ - public void setChunkModified() { - this.isModified = true; - } - - /**+ - * Fills the given list of all entities that intersect within - * the given bounding box that aren't the passed entity. - */ - public void getEntitiesWithinAABBForEntity(Entity entity, AxisAlignedBB axisalignedbb, List list, - Predicate predicate) { - int i = MathHelper.floor_double((axisalignedbb.minY - 2.0D) / 16.0D); - int j = MathHelper.floor_double((axisalignedbb.maxY + 2.0D) / 16.0D); - i = MathHelper.clamp_int(i, 0, this.entityLists.length - 1); - j = MathHelper.clamp_int(j, 0, this.entityLists.length - 1); - - for (int k = i; k <= j; ++k) { - if (!this.entityLists[k].isEmpty()) { - for (Entity entity1 : this.entityLists[k]) { - if (entity1.getEntityBoundingBox().intersectsWith(axisalignedbb) && entity1 != entity) { - if (predicate == null || predicate.apply(entity1)) { - list.add(entity1); - } - - Entity[] aentity = entity1.getParts(); - if (aentity != null) { - for (int l = 0; l < aentity.length; ++l) { - entity1 = aentity[l]; - if (entity1 != entity && entity1.getEntityBoundingBox().intersectsWith(axisalignedbb) - && (predicate == null || predicate.apply(entity1))) { - list.add(entity1); - } - } - } - } - } - } - } - - } - - public void getEntitiesOfTypeWithinAAAB(Class oclass, AxisAlignedBB axisalignedbb, - List list, Predicate predicate) { - int i = MathHelper.floor_double((axisalignedbb.minY - 2.0D) / 16.0D); - int j = MathHelper.floor_double((axisalignedbb.maxY + 2.0D) / 16.0D); - i = MathHelper.clamp_int(i, 0, this.entityLists.length - 1); - j = MathHelper.clamp_int(j, 0, this.entityLists.length - 1); - - for (int k = i; k <= j; ++k) { - for (Entity entity : this.entityLists[k].getByClass(oclass)) { - if (entity.getEntityBoundingBox().intersectsWith(axisalignedbb) - && (predicate == null || predicate.apply((T) entity))) { - list.add((T) entity); - } - } - } - - } - - /**+ - * Returns true if this Chunk needs to be saved - */ - public boolean needsSaving(boolean flag) { - if (flag) { - if (this.hasEntities && this.worldObj.getTotalWorldTime() != this.lastSaveTime || this.isModified) { - return true; - } - } else if (this.hasEntities && this.worldObj.getTotalWorldTime() >= this.lastSaveTime + 600L) { - return true; - } - - return this.isModified; - } - - public EaglercraftRandom getRandomWithSeed(long i) { - return new EaglercraftRandom(this.worldObj.getSeed() + (long) (this.xPosition * this.xPosition * 4987142) - + (long) (this.xPosition * 5947611) + (long) (this.zPosition * this.zPosition) * 4392871L - + (long) (this.zPosition * 389711) ^ i, !this.worldObj.getWorldInfo().isOldEaglercraftRandom()); - } - - public boolean isEmpty() { - return false; - } - - public void populateChunk(IChunkProvider parIChunkProvider, IChunkProvider parIChunkProvider2, int parInt1, - int parInt2) { - boolean flag = parIChunkProvider.chunkExists(parInt1, parInt2 - 1); - boolean flag1 = parIChunkProvider.chunkExists(parInt1 + 1, parInt2); - boolean flag2 = parIChunkProvider.chunkExists(parInt1, parInt2 + 1); - boolean flag3 = parIChunkProvider.chunkExists(parInt1 - 1, parInt2); - boolean flag4 = parIChunkProvider.chunkExists(parInt1 - 1, parInt2 - 1); - boolean flag5 = parIChunkProvider.chunkExists(parInt1 + 1, parInt2 + 1); - boolean flag6 = parIChunkProvider.chunkExists(parInt1 - 1, parInt2 + 1); - boolean flag7 = parIChunkProvider.chunkExists(parInt1 + 1, parInt2 - 1); - if (flag1 && flag2 && flag5) { - if (!this.isTerrainPopulated) { - parIChunkProvider.populate(parIChunkProvider2, parInt1, parInt2); - } else { - parIChunkProvider.func_177460_a(parIChunkProvider2, this, parInt1, parInt2); - } - } - - if (flag3 && flag2 && flag6) { - Chunk chunk = parIChunkProvider.provideChunk(parInt1 - 1, parInt2); - if (!chunk.isTerrainPopulated) { - parIChunkProvider.populate(parIChunkProvider2, parInt1 - 1, parInt2); - } else { - parIChunkProvider.func_177460_a(parIChunkProvider2, chunk, parInt1 - 1, parInt2); - } - } - - if (flag && flag1 && flag7) { - Chunk chunk1 = parIChunkProvider.provideChunk(parInt1, parInt2 - 1); - if (!chunk1.isTerrainPopulated) { - parIChunkProvider.populate(parIChunkProvider2, parInt1, parInt2 - 1); - } else { - parIChunkProvider.func_177460_a(parIChunkProvider2, chunk1, parInt1, parInt2 - 1); - } - } - - if (flag4 && flag && flag3) { - Chunk chunk2 = parIChunkProvider.provideChunk(parInt1 - 1, parInt2 - 1); - if (!chunk2.isTerrainPopulated) { - parIChunkProvider.populate(parIChunkProvider2, parInt1 - 1, parInt2 - 1); - } else { - parIChunkProvider.func_177460_a(parIChunkProvider2, chunk2, parInt1 - 1, parInt2 - 1); - } - } - - } - - public BlockPos getPrecipitationHeight(BlockPos pos) { - int i = pos.getX() & 15; - int j = pos.getZ() & 15; - int k = i | j << 4; - BlockPos blockpos = new BlockPos(pos.getX(), this.precipitationHeightMap[k], pos.getZ()); - if (blockpos.getY() == -999) { - int l = this.getTopFilledSegment() + 15; - blockpos = new BlockPos(pos.getX(), l, pos.getZ()); - int i1 = -1; - - while (blockpos.getY() > 0 && i1 == -1) { - Block block = this.getBlock(blockpos); - Material material = block.getMaterial(); - if (!material.blocksMovement() && !material.isLiquid()) { - blockpos = blockpos.down(); - } else { - i1 = blockpos.getY() + 1; - } - } - - this.precipitationHeightMap[k] = i1; - } - - return new BlockPos(pos.getX(), this.precipitationHeightMap[k], pos.getZ()); - } - - public void func_150804_b(boolean parFlag) { - if (this.isGapLightingUpdated && !this.worldObj.provider.getHasNoSky() && !parFlag) { - this.recheckGaps(this.worldObj.isRemote); - } - - this.field_150815_m = true; - if (!this.isLightPopulated && this.isTerrainPopulated) { - this.func_150809_p(); - } - - while (!this.tileEntityPosQueue.isEmpty()) { - BlockPos blockpos = (BlockPos) this.tileEntityPosQueue.remove(0); - if (this.getTileEntity(blockpos, Chunk.EnumCreateEntityType.CHECK) == null - && this.getBlock(blockpos).hasTileEntity()) { - TileEntity tileentity = this.createNewTileEntity(blockpos); - this.worldObj.setTileEntity(blockpos, tileentity); - this.worldObj.markBlockRangeForRenderUpdate(blockpos, blockpos); - } - } - - } - - public boolean isPopulated() { - return this.field_150815_m && this.isTerrainPopulated && this.isLightPopulated; - } - - /**+ - * Gets a ChunkCoordIntPair representing the Chunk's position. - */ - public ChunkCoordIntPair getChunkCoordIntPair() { - return new ChunkCoordIntPair(this.xPosition, this.zPosition); - } - - /**+ - * Returns whether the ExtendedBlockStorages containing levels - * (in blocks) from arg 1 to arg 2 are fully empty (true) or not - * (false). - */ - public boolean getAreLevelsEmpty(int i, int j) { - if (i < 0) { - i = 0; - } - - if (j >= 256) { - j = 255; - } - - for (int k = i; k <= j; k += 16) { - ExtendedBlockStorage extendedblockstorage = this.storageArrays[k >> 4]; - if (extendedblockstorage != null && !extendedblockstorage.isEmpty()) { - return false; - } - } - - return true; + public void setModified(boolean modified) { + this.isModified = modified; } public void setStorageArrays(ExtendedBlockStorage[] newStorageArrays) { @@ -1072,328 +1381,18 @@ public class Chunk { } } - /**+ - * Initialize this chunk with new binary data. - */ - public void fillChunk(byte[] parArrayOfByte, int parInt1, boolean parFlag) { - int i = 0; - boolean flag = !this.worldObj.provider.getHasNoSky(); - - for (int j = 0; j < this.storageArrays.length; ++j) { - if ((parInt1 & 1 << j) != 0) { - if (this.storageArrays[j] == null) { - this.storageArrays[j] = new ExtendedBlockStorage(j << 4, flag); - } - - char[] achar = this.storageArrays[j].getData(); - - for (int k = 0; k < achar.length; ++k) { - achar[k] = (char) ((parArrayOfByte[i + 1] & 255) << 8 | parArrayOfByte[i] & 255); - i += 2; - } - } else if (parFlag && this.storageArrays[j] != null) { - this.storageArrays[j] = null; - } - } - - for (int l = 0; l < this.storageArrays.length; ++l) { - if ((parInt1 & 1 << l) != 0 && this.storageArrays[l] != null) { - NibbleArray nibblearray = this.storageArrays[l].getBlocklightArray(); - System.arraycopy(parArrayOfByte, i, nibblearray.getData(), 0, nibblearray.getData().length); - i += nibblearray.getData().length; - } - } - - if (flag) { - for (int i1 = 0; i1 < this.storageArrays.length; ++i1) { - if ((parInt1 & 1 << i1) != 0 && this.storageArrays[i1] != null) { - NibbleArray nibblearray1 = this.storageArrays[i1].getSkylightArray(); - System.arraycopy(parArrayOfByte, i, nibblearray1.getData(), 0, nibblearray1.getData().length); - i += nibblearray1.getData().length; - } - } - } - - if (parFlag) { - System.arraycopy(parArrayOfByte, i, this.blockBiomeArray, 0, this.blockBiomeArray.length); - int k1 = i + this.blockBiomeArray.length; - } - - for (int j1 = 0; j1 < this.storageArrays.length; ++j1) { - if (this.storageArrays[j1] != null && (parInt1 & 1 << j1) != 0) { - this.storageArrays[j1].removeInvalidBlocks(); - } - } - - this.isLightPopulated = true; - this.isTerrainPopulated = true; - this.generateHeightMap(); - - for (TileEntity tileentity : this.chunkTileEntityMap.values()) { - tileentity.updateContainingBlockInfo(); - } - - } - - public BiomeGenBase getBiome(BlockPos pos, WorldChunkManager chunkManager) { - int i = pos.getX() & 15; - int j = pos.getZ() & 15; - int k = this.blockBiomeArray[j << 4 | i] & 255; - if (chunkManager != null && k == 255) { - BiomeGenBase biomegenbase = chunkManager.getBiomeGenerator(pos, BiomeGenBase.plains); - k = biomegenbase.biomeID; - this.blockBiomeArray[j << 4 | i] = (byte) (k & 255); - } - - BiomeGenBase biomegenbase1 = BiomeGenBase.getBiome(k); - return biomegenbase1 == null ? BiomeGenBase.plains : biomegenbase1; - } - - /**+ - * Returns an array containing a 16x16 mapping on the X/Z of - * block positions in this Chunk to biome IDs. - */ - public byte[] getBiomeArray() { - return this.blockBiomeArray; - } - - /**+ - * Accepts a 256-entry array that contains a 16x16 mapping on - * the X/Z plane of block positions in this Chunk to biome IDs. - */ - public void setBiomeArray(byte[] biomeArray) { - if (this.blockBiomeArray.length != biomeArray.length) { - logger.warn("Could not set level chunk biomes, array length is " + biomeArray.length + " instead of " - + this.blockBiomeArray.length); - } else { - for (int i = 0; i < this.blockBiomeArray.length; ++i) { - this.blockBiomeArray[i] = biomeArray[i]; - } - - } - } - - /**+ - * Resets the relight check index to 0 for this Chunk. - */ - public void resetRelightChecks() { - this.queuedLightChecks = 0; - } - - /**+ - * Called once-per-chunk-per-tick, and advances the round-robin - * relight check index by up to 8 blocks at a time. In a - * worst-case scenario, can potentially take up to 25.6 seconds, - * calculated via (4096/8)/20, to re-check all blocks in a - * chunk, which may explain lagging light updates on initial - * world generation. - */ - public void enqueueRelightChecks() { - BlockPos blockpos = new BlockPos(this.xPosition << 4, 0, this.zPosition << 4); - - for (int i = 0; i < 8; ++i) { - if (this.queuedLightChecks >= 4096) { - return; - } - - int j = this.queuedLightChecks % 16; - int k = this.queuedLightChecks / 16 % 16; - int l = this.queuedLightChecks / 256; - ++this.queuedLightChecks; - - EnumFacing[] facings = EnumFacing._VALUES; - for (int i1 = 0; i1 < 16; ++i1) { - BlockPos blockpos1 = blockpos.add(k, (j << 4) + i1, l); - boolean flag = i1 == 0 || i1 == 15 || k == 0 || k == 15 || l == 0 || l == 15; - if (this.storageArrays[j] == null && flag || this.storageArrays[j] != null - && this.storageArrays[j].getBlockByExtId(k, i1, l).getMaterial() == Material.air) { - for (int m = 0; m < facings.length; ++m) { - BlockPos blockpos2 = blockpos1.offset(facings[m]); - if (this.worldObj.getBlockState(blockpos2).getBlock().getLightValue() > 0) { - this.worldObj.checkLight(blockpos2); - } - } - - this.worldObj.checkLight(blockpos1); - } - } - } - - } - - public void func_150809_p() { - this.isTerrainPopulated = true; - this.isLightPopulated = true; - BlockPos blockpos = new BlockPos(this.xPosition << 4, 0, this.zPosition << 4); - if (!this.worldObj.provider.getHasNoSky()) { - if (this.worldObj.isAreaLoaded(blockpos.add(-1, 0, -1), - blockpos.add(16, this.worldObj.func_181545_F(), 16))) { - label92: for (int i = 0; i < 16; ++i) { - for (int j = 0; j < 16; ++j) { - if (!this.func_150811_f(i, j)) { - this.isLightPopulated = false; - break label92; - } - } - } - - if (this.isLightPopulated) { - EnumFacing[] facings = EnumFacing.Plane.HORIZONTAL.facingsArray; - for (int i = 0; i < facings.length; ++i) { - EnumFacing enumfacing = facings[i]; - int k = enumfacing.getAxisDirection() == EnumFacing.AxisDirection.POSITIVE ? 16 : 1; - this.worldObj.getChunkFromBlockCoords(blockpos.offset(enumfacing, k)) - .func_180700_a(enumfacing.getOpposite()); - } - - this.func_177441_y(); - } - } else { - this.isLightPopulated = false; - } - } - - } - - private void func_177441_y() { - for (int i = 0; i < this.updateSkylightColumns.length; ++i) { - this.updateSkylightColumns[i] = true; - } - - this.recheckGaps(false); - } - - private void func_180700_a(EnumFacing parEnumFacing) { - if (this.isTerrainPopulated) { - if (parEnumFacing == EnumFacing.EAST) { - for (int i = 0; i < 16; ++i) { - this.func_150811_f(15, i); - } - } else if (parEnumFacing == EnumFacing.WEST) { - for (int j = 0; j < 16; ++j) { - this.func_150811_f(0, j); - } - } else if (parEnumFacing == EnumFacing.SOUTH) { - for (int k = 0; k < 16; ++k) { - this.func_150811_f(k, 15); - } - } else if (parEnumFacing == EnumFacing.NORTH) { - for (int l = 0; l < 16; ++l) { - this.func_150811_f(l, 0); - } - } - - } - } - - private boolean func_150811_f(int x, int z) { - int i = this.getTopFilledSegment(); - boolean flag = false; - boolean flag1 = false; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos((this.xPosition << 4) + x, 0, - (this.zPosition << 4) + z); - - for (int j = i + 16 - 1; j > this.worldObj.func_181545_F() || j > 0 && !flag1; --j) { - blockpos$mutableblockpos.func_181079_c(blockpos$mutableblockpos.getX(), j, blockpos$mutableblockpos.getZ()); - int k = this.getBlockLightOpacity(blockpos$mutableblockpos); - if (k == 255 && blockpos$mutableblockpos.getY() < this.worldObj.func_181545_F()) { - flag1 = true; - } - - if (!flag && k > 0) { - flag = true; - } else if (flag && k == 0 && !this.worldObj.checkLight(blockpos$mutableblockpos)) { - return false; - } - } - - for (int l = blockpos$mutableblockpos.getY(); l > 0; --l) { - blockpos$mutableblockpos.func_181079_c(blockpos$mutableblockpos.getX(), l, blockpos$mutableblockpos.getZ()); - if (this.getBlock(blockpos$mutableblockpos).getLightValue() > 0) { - this.worldObj.checkLight(blockpos$mutableblockpos); - } - } - - return true; - } - - public boolean isLoaded() { - return this.isChunkLoaded; - } - - public void setChunkLoaded(boolean loaded) { - this.isChunkLoaded = loaded; - } - - public World getWorld() { - return this.worldObj; - } - - public int[] getHeightMap() { - return this.heightMap; - } - - public void setHeightMap(int[] newHeightMap) { - if (this.heightMap.length != newHeightMap.length) { - logger.warn("Could not set level chunk heightmap, array length is " + newHeightMap.length + " instead of " - + this.heightMap.length); - } else { - for (int i = 0; i < this.heightMap.length; ++i) { - this.heightMap[i] = newHeightMap[i]; - } - - } - } - - public Map getTileEntityMap() { - return this.chunkTileEntityMap; - } - - public ClassInheritanceMultiMap[] getEntityLists() { - return this.entityLists; - } - - public boolean isTerrainPopulated() { - return this.isTerrainPopulated; - } - public void setTerrainPopulated(boolean terrainPopulated) { this.isTerrainPopulated = terrainPopulated; } - public boolean isLightPopulated() { - return this.isLightPopulated; - } + private void updateSkylightNeighborHeight(int x, int z, int startY, int endY) { + if (endY > startY && this.worldObj.isAreaLoaded(new BlockPos(x, 0, z), 16)) { + for (int i = startY; i < endY; ++i) { + this.worldObj.checkLightFor(EnumSkyBlock.SKY, new BlockPos(x, i, z)); + } - public void setLightPopulated(boolean lightPopulated) { - this.isLightPopulated = lightPopulated; - } + this.isModified = true; + } - public void setModified(boolean modified) { - this.isModified = modified; - } - - public void setHasEntities(boolean hasEntitiesIn) { - this.hasEntities = hasEntitiesIn; - } - - public void setLastSaveTime(long saveTime) { - this.lastSaveTime = saveTime; - } - - public int getLowestHeight() { - return this.heightMapMinimum; - } - - public long getInhabitedTime() { - return this.inhabitedTime; - } - - public void setInhabitedTime(long newInhabitedTime) { - this.inhabitedTime = newInhabitedTime; - } - - public static enum EnumCreateEntityType { - IMMEDIATE, QUEUED, CHECK; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/ChunkPrimer.java b/src/game/java/net/minecraft/world/chunk/ChunkPrimer.java index 9aa3cd72..6d1ec1f8 100644 --- a/src/game/java/net/minecraft/world/chunk/ChunkPrimer.java +++ b/src/game/java/net/minecraft/world/chunk/ChunkPrimer.java @@ -4,22 +4,25 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,6 @@ public class ChunkPrimer { private final short[] data = new short[65536]; private final IBlockState defaultState = Blocks.air.getDefaultState(); - public IBlockState getBlockState(int x, int y, int z) { - int i = x << 12 | z << 8 | y; - return this.getBlockState(i); - } - public IBlockState getBlockState(int index) { if (index >= 0 && index < this.data.length) { IBlockState iblockstate = (IBlockState) Block.BLOCK_STATE_IDS.getByValue(this.data[index]); @@ -42,9 +40,9 @@ public class ChunkPrimer { } } - public void setBlockState(int x, int y, int z, IBlockState state) { + public IBlockState getBlockState(int x, int y, int z) { int i = x << 12 | z << 8 | y; - this.setBlockState(i, state); + return this.getBlockState(i); } public void setBlockState(int index, IBlockState state) { @@ -54,4 +52,9 @@ public class ChunkPrimer { throw new IndexOutOfBoundsException("The coordinate is out of range"); } } + + public void setBlockState(int x, int y, int z, IBlockState state) { + int i = x << 12 | z << 8 | y; + this.setBlockState(i, state); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/EmptyChunk.java b/src/game/java/net/minecraft/world/chunk/EmptyChunk.java index 3702b881..4051c161 100644 --- a/src/game/java/net/minecraft/world/chunk/EmptyChunk.java +++ b/src/game/java/net/minecraft/world/chunk/EmptyChunk.java @@ -1,10 +1,10 @@ package net.minecraft.world.chunk; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import com.google.common.base.Predicate; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.init.Blocks; @@ -14,22 +14,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,34 +42,42 @@ public class EmptyChunk extends Chunk { super(worldIn, x, z); } - /**+ - * Checks whether the chunk is at the X/Z location specified + /** + * + Adds an entity to the chunk. Args: entity */ - public boolean isAtLocation(int x, int z) { - return x == this.xPosition && z == this.zPosition; + public void addEntity(Entity entityIn) { } - /**+ - * Returns the value in the height map at this x, z coordinate - * in the chunk - */ - public int getHeightValue(int x, int z) { - return 0; + public void addTileEntity(BlockPos pos, TileEntity tileEntityIn) { } - /**+ - * Generates the height map for a chunk from scratch + public void addTileEntity(TileEntity tileEntityIn) { + } + + public boolean canSeeSky(BlockPos pos) { + return false; + } + + /** + * + Generates the height map for a chunk from scratch */ public void generateHeightMap() { } - /**+ - * Generates the initial skylight map for the chunk upon - * generation or load. + /** + * + Generates the initial skylight map for the chunk upon generation or load. */ public void generateSkylightMap() { } + /** + * + Returns whether the ExtendedBlockStorages containing levels (in blocks) + * from arg 1 to arg 2 are fully empty (true) or not (false). + */ + public boolean getAreLevelsEmpty(int startY, int endY) { + return true; + } + public Block getBlock(BlockPos pos) { return Blocks.air; } @@ -79,87 +90,31 @@ public class EmptyChunk extends Chunk { return 0; } - public int getLightFor(EnumSkyBlock pos, BlockPos parBlockPos) { - return pos.defaultLightValue; + public void getEntitiesOfTypeWithinAAAB(Class entityClass, AxisAlignedBB aabb, + List listToFill, Predicate parPredicate) { } - public void setLightFor(EnumSkyBlock pos, BlockPos value, int parInt1) { - } - - public int getLightSubtracted(BlockPos pos, int amount) { - return 0; - } - - /**+ - * Adds an entity to the chunk. Args: entity - */ - public void addEntity(Entity entityIn) { - } - - /**+ - * removes entity using its y chunk coordinate as its index - */ - public void removeEntity(Entity entityIn) { - } - - /**+ - * Removes entity at the specified index from the entity array. - */ - public void removeEntityAtIndex(Entity entityIn, int parInt1) { - } - - public boolean canSeeSky(BlockPos pos) { - return false; - } - - public TileEntity getTileEntity(BlockPos pos, Chunk.EnumCreateEntityType parEnumCreateEntityType) { - return null; - } - - public void addTileEntity(TileEntity tileEntityIn) { - } - - public void addTileEntity(BlockPos pos, TileEntity tileEntityIn) { - } - - public void removeTileEntity(BlockPos pos) { - } - - /**+ - * Called when this Chunk is loaded by the ChunkProvider - */ - public void onChunkLoad() { - } - - /**+ - * Called when this Chunk is unloaded by the ChunkProvider - */ - public void onChunkUnload() { - } - - /**+ - * Sets the isModified flag for this Chunk - */ - public void setChunkModified() { - } - - /**+ - * Fills the given list of all entities that intersect within - * the given bounding box that aren't the passed entity. + /** + * + Fills the given list of all entities that intersect within the given + * bounding box that aren't the passed entity. */ public void getEntitiesWithinAABBForEntity(Entity entityIn, AxisAlignedBB aabb, List listToFill, Predicate parPredicate) { } - public void getEntitiesOfTypeWithinAAAB(Class entityClass, AxisAlignedBB aabb, - List listToFill, Predicate parPredicate) { + /** + * + Returns the value in the height map at this x, z coordinate in the chunk + */ + public int getHeightValue(int x, int z) { + return 0; } - /**+ - * Returns true if this Chunk needs to be saved - */ - public boolean needsSaving(boolean parFlag) { - return false; + public int getLightFor(EnumSkyBlock pos, BlockPos parBlockPos) { + return pos.defaultLightValue; + } + + public int getLightSubtracted(BlockPos pos, int amount) { + return 0; } public EaglercraftRandom getRandomWithSeed(long seed) { @@ -170,16 +125,61 @@ public class EmptyChunk extends Chunk { !this.getWorld().getWorldInfo().isOldEaglercraftRandom()); } + public TileEntity getTileEntity(BlockPos pos, Chunk.EnumCreateEntityType parEnumCreateEntityType) { + return null; + } + + /** + * + Checks whether the chunk is at the X/Z location specified + */ + public boolean isAtLocation(int x, int z) { + return x == this.xPosition && z == this.zPosition; + } + public boolean isEmpty() { return true; } - /**+ - * Returns whether the ExtendedBlockStorages containing levels - * (in blocks) from arg 1 to arg 2 are fully empty (true) or not - * (false). + /** + * + Returns true if this Chunk needs to be saved */ - public boolean getAreLevelsEmpty(int startY, int endY) { - return true; + public boolean needsSaving(boolean parFlag) { + return false; + } + + /** + * + Called when this Chunk is loaded by the ChunkProvider + */ + public void onChunkLoad() { + } + + /** + * + Called when this Chunk is unloaded by the ChunkProvider + */ + public void onChunkUnload() { + } + + /** + * + removes entity using its y chunk coordinate as its index + */ + public void removeEntity(Entity entityIn) { + } + + /** + * + Removes entity at the specified index from the entity array. + */ + public void removeEntityAtIndex(Entity entityIn, int parInt1) { + } + + public void removeTileEntity(BlockPos pos) { + } + + /** + * + Sets the isModified flag for this Chunk + */ + public void setChunkModified() { + } + + public void setLightFor(EnumSkyBlock pos, BlockPos value, int parInt1) { } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/IChunkProvider.java b/src/game/java/net/minecraft/world/chunk/IChunkProvider.java index 3fa0f006..a7e203ed 100644 --- a/src/game/java/net/minecraft/world/chunk/IChunkProvider.java +++ b/src/game/java/net/minecraft/world/chunk/IChunkProvider.java @@ -8,88 +8,90 @@ import net.minecraft.util.IProgressUpdate; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IChunkProvider { - /**+ - * Checks to see if a chunk exists at x, z - */ - boolean chunkExists(int var1, int var2); - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - Chunk provideChunk(int var1, int var2); - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - Chunk provideChunk(BlockPos var1); - - /**+ - * Populates chunk with ores etc etc - */ - void populate(IChunkProvider var1, int var2, int var3); - - boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4); - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. - */ - boolean saveChunks(boolean var1, IProgressUpdate var2); - - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. - */ - boolean unloadQueuedChunks(); - - /**+ - * Returns if the IChunkProvider supports saving. + /** + * + Returns if the IChunkProvider supports saving. */ boolean canSave(); - /**+ - * Converts the instance data to a readable string. + /** + * + Checks to see if a chunk exists at x, z */ - String makeString(); + boolean chunkExists(int var1, int var2); + + boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4); + + int getLoadedChunkCount(); List getPossibleCreatures(EnumCreatureType var1, BlockPos var2); BlockPos getStrongholdGen(World var1, String var2, BlockPos var3); - int getLoadedChunkCount(); + /** + * + Converts the instance data to a readable string. + */ + String makeString(); + + /** + * + Populates chunk with ores etc etc + */ + void populate(IChunkProvider var1, int var2, int var3); + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + Chunk provideChunk(BlockPos var1); + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + Chunk provideChunk(int var1, int var2); void recreateStructures(Chunk var1, int var2, int var3); - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. + */ + boolean saveChunks(boolean var1, IProgressUpdate var2); + + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. */ void saveExtraData(); + + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. + */ + boolean unloadQueuedChunks(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/NibbleArray.java b/src/game/java/net/minecraft/world/chunk/NibbleArray.java index 73456f9f..1f6b3714 100644 --- a/src/game/java/net/minecraft/world/chunk/NibbleArray.java +++ b/src/game/java/net/minecraft/world/chunk/NibbleArray.java @@ -1,21 +1,24 @@ package net.minecraft.world.chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,31 +37,43 @@ public class NibbleArray { } } - /**+ - * Returns the nibble of data corresponding to the passed in x, - * y, z. y is at most 6 bits, z is at most 4. + /** + * + Returns the nibble of data corresponding to the passed in x, y, z. y is at + * most 6 bits, z is at most 4. */ public int get(int x, int y, int z) { return this.getFromIndex(this.getCoordinateIndex(x, y, z)); } - /**+ - * Arguments are x, y, z, val. Sets the nibble of data at x << - * 11 | z << 7 | y to val. - */ - public void set(int x, int y, int z, int value) { - this.setIndex(this.getCoordinateIndex(x, y, z), value); - } - private int getCoordinateIndex(int x, int y, int z) { return y << 8 | z << 4 | x; } + public byte[] getData() { + return this.data; + } + public int getFromIndex(int index) { int i = this.getNibbleIndex(index); return this.isLowerNibble(index) ? this.data[i] & 15 : this.data[i] >> 4 & 15; } + private int getNibbleIndex(int index) { + return index >> 1; + } + + private boolean isLowerNibble(int index) { + return (index & 1) == 0; + } + + /** + * + Arguments are x, y, z, val. Sets the nibble of data at x << 11 | z << 7 | y + * to val. + */ + public void set(int x, int y, int z, int value) { + this.setIndex(this.getCoordinateIndex(x, y, z), value); + } + public void setIndex(int index, int value) { int i = this.getNibbleIndex(index); if (this.isLowerNibble(index)) { @@ -68,16 +83,4 @@ public class NibbleArray { } } - - private boolean isLowerNibble(int index) { - return (index & 1) == 0; - } - - private int getNibbleIndex(int index) { - return index >> 1; - } - - public byte[] getData() { - return this.data; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/storage/AnvilChunkLoader.java b/src/game/java/net/minecraft/world/chunk/storage/AnvilChunkLoader.java index 209b7d1b..79603ff9 100644 --- a/src/game/java/net/minecraft/world/chunk/storage/AnvilChunkLoader.java +++ b/src/game/java/net/minecraft/world/chunk/storage/AnvilChunkLoader.java @@ -1,6 +1,9 @@ package net.minecraft.world.chunk.storage; import java.util.List; + +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.block.Block; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; @@ -13,25 +16,26 @@ import net.minecraft.world.NextTickListEntry; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.NibbleArray; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,9 +43,8 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; public abstract class AnvilChunkLoader implements IChunkLoader { private static final Logger logger = LogManager.getLogger("AnvilChunkLoader"); - /**+ - * Wraps readChunkFromNBT. Checks the coordinates and several - * NBT tags. + /** + * + Wraps readChunkFromNBT. Checks the coordinates and several NBT tags. */ protected Chunk checkedReadChunkFromNBT(World worldIn, int x, int z, NBTTagCompound parNBTTagCompound) { if (!parNBTTagCompound.hasKey("Level", 10)) { @@ -67,120 +70,9 @@ public abstract class AnvilChunkLoader implements IChunkLoader { } } - /**+ - * Writes the Chunk passed as an argument to the NBTTagCompound - * also passed, using the World argument to retrieve the Chunk's - * last update time. - */ - protected void writeChunkToNBT(Chunk chunkIn, World worldIn, NBTTagCompound parNBTTagCompound) { - parNBTTagCompound.setByte("V", (byte) 1); - parNBTTagCompound.setInteger("xPos", chunkIn.xPosition); - parNBTTagCompound.setInteger("zPos", chunkIn.zPosition); - parNBTTagCompound.setLong("LastUpdate", worldIn.getTotalWorldTime()); - parNBTTagCompound.setIntArray("HeightMap", chunkIn.getHeightMap()); - parNBTTagCompound.setBoolean("TerrainPopulated", chunkIn.isTerrainPopulated()); - parNBTTagCompound.setBoolean("LightPopulated", chunkIn.isLightPopulated()); - parNBTTagCompound.setLong("InhabitedTime", chunkIn.getInhabitedTime()); - ExtendedBlockStorage[] aextendedblockstorage = chunkIn.getBlockStorageArray(); - NBTTagList nbttaglist = new NBTTagList(); - boolean flag = !worldIn.provider.getHasNoSky(); - - for (ExtendedBlockStorage extendedblockstorage : aextendedblockstorage) { - if (extendedblockstorage != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setByte("Y", (byte) (extendedblockstorage.getYLocation() >> 4 & 255)); - byte[] abyte = new byte[extendedblockstorage.getData().length]; - NibbleArray nibblearray = new NibbleArray(); - NibbleArray nibblearray1 = null; - - for (int i = 0; i < extendedblockstorage.getData().length; ++i) { - char c0 = extendedblockstorage.getData()[i]; - int j = i & 15; - int k = i >> 8 & 15; - int l = i >> 4 & 15; - if (c0 >> 12 != 0) { - if (nibblearray1 == null) { - nibblearray1 = new NibbleArray(); - } - - nibblearray1.set(j, k, l, c0 >> 12); - } - - abyte[i] = (byte) (c0 >> 4 & 255); - nibblearray.set(j, k, l, c0 & 15); - } - - nbttagcompound.setByteArray("Blocks", abyte); - nbttagcompound.setByteArray("Data", nibblearray.getData()); - if (nibblearray1 != null) { - nbttagcompound.setByteArray("Add", nibblearray1.getData()); - } - - nbttagcompound.setByteArray("BlockLight", extendedblockstorage.getBlocklightArray().getData()); - if (flag) { - nbttagcompound.setByteArray("SkyLight", extendedblockstorage.getSkylightArray().getData()); - } else { - nbttagcompound.setByteArray("SkyLight", - new byte[extendedblockstorage.getBlocklightArray().getData().length]); - } - - nbttaglist.appendTag(nbttagcompound); - } - } - - parNBTTagCompound.setTag("Sections", nbttaglist); - parNBTTagCompound.setByteArray("Biomes", chunkIn.getBiomeArray()); - chunkIn.setHasEntities(false); - NBTTagList nbttaglist1 = new NBTTagList(); - - for (int i1 = 0; i1 < chunkIn.getEntityLists().length; ++i1) { - for (Entity entity : chunkIn.getEntityLists()[i1]) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - if (entity.writeToNBTOptional(nbttagcompound1)) { - chunkIn.setHasEntities(true); - nbttaglist1.appendTag(nbttagcompound1); - } - } - } - - parNBTTagCompound.setTag("Entities", nbttaglist1); - NBTTagList nbttaglist2 = new NBTTagList(); - - for (TileEntity tileentity : chunkIn.getTileEntityMap().values()) { - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - tileentity.writeToNBT(nbttagcompound2); - nbttaglist2.appendTag(nbttagcompound2); - } - - parNBTTagCompound.setTag("TileEntities", nbttaglist2); - List list = worldIn.getPendingBlockUpdates(chunkIn, false); - if (list != null) { - long j1 = worldIn.getTotalWorldTime(); - NBTTagList nbttaglist3 = new NBTTagList(); - - for (int k = 0, l = list.size(); k < l; ++k) { - NextTickListEntry nextticklistentry = list.get(k); - NBTTagCompound nbttagcompound3 = new NBTTagCompound(); - ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry - .getNameForObject(nextticklistentry.getBlock()); - nbttagcompound3.setString("i", resourcelocation == null ? "" : resourcelocation.toString()); - nbttagcompound3.setInteger("x", nextticklistentry.position.getX()); - nbttagcompound3.setInteger("y", nextticklistentry.position.getY()); - nbttagcompound3.setInteger("z", nextticklistentry.position.getZ()); - nbttagcompound3.setInteger("t", (int) (nextticklistentry.scheduledTime - j1)); - nbttagcompound3.setInteger("p", nextticklistentry.priority); - nbttaglist3.appendTag(nbttagcompound3); - } - - parNBTTagCompound.setTag("TileTicks", nbttaglist3); - } - - } - - /**+ - * Reads the data stored in the passed NBTTagCompound and - * creates a Chunk with that data in the passed World. Returns - * the created Chunk. + /** + * + Reads the data stored in the passed NBTTagCompound and creates a Chunk with + * that data in the passed World. Returns the created Chunk. */ protected Chunk readChunkFromNBT(World worldIn, NBTTagCompound parNBTTagCompound) { int i = parNBTTagCompound.getInteger("xPos"); @@ -287,4 +179,113 @@ public abstract class AnvilChunkLoader implements IChunkLoader { return chunk; } + + /** + * + Writes the Chunk passed as an argument to the NBTTagCompound also passed, + * using the World argument to retrieve the Chunk's last update time. + */ + protected void writeChunkToNBT(Chunk chunkIn, World worldIn, NBTTagCompound parNBTTagCompound) { + parNBTTagCompound.setByte("V", (byte) 1); + parNBTTagCompound.setInteger("xPos", chunkIn.xPosition); + parNBTTagCompound.setInteger("zPos", chunkIn.zPosition); + parNBTTagCompound.setLong("LastUpdate", worldIn.getTotalWorldTime()); + parNBTTagCompound.setIntArray("HeightMap", chunkIn.getHeightMap()); + parNBTTagCompound.setBoolean("TerrainPopulated", chunkIn.isTerrainPopulated()); + parNBTTagCompound.setBoolean("LightPopulated", chunkIn.isLightPopulated()); + parNBTTagCompound.setLong("InhabitedTime", chunkIn.getInhabitedTime()); + ExtendedBlockStorage[] aextendedblockstorage = chunkIn.getBlockStorageArray(); + NBTTagList nbttaglist = new NBTTagList(); + boolean flag = !worldIn.provider.getHasNoSky(); + + for (ExtendedBlockStorage extendedblockstorage : aextendedblockstorage) { + if (extendedblockstorage != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setByte("Y", (byte) (extendedblockstorage.getYLocation() >> 4 & 255)); + byte[] abyte = new byte[extendedblockstorage.getData().length]; + NibbleArray nibblearray = new NibbleArray(); + NibbleArray nibblearray1 = null; + + for (int i = 0; i < extendedblockstorage.getData().length; ++i) { + char c0 = extendedblockstorage.getData()[i]; + int j = i & 15; + int k = i >> 8 & 15; + int l = i >> 4 & 15; + if (c0 >> 12 != 0) { + if (nibblearray1 == null) { + nibblearray1 = new NibbleArray(); + } + + nibblearray1.set(j, k, l, c0 >> 12); + } + + abyte[i] = (byte) (c0 >> 4 & 255); + nibblearray.set(j, k, l, c0 & 15); + } + + nbttagcompound.setByteArray("Blocks", abyte); + nbttagcompound.setByteArray("Data", nibblearray.getData()); + if (nibblearray1 != null) { + nbttagcompound.setByteArray("Add", nibblearray1.getData()); + } + + nbttagcompound.setByteArray("BlockLight", extendedblockstorage.getBlocklightArray().getData()); + if (flag) { + nbttagcompound.setByteArray("SkyLight", extendedblockstorage.getSkylightArray().getData()); + } else { + nbttagcompound.setByteArray("SkyLight", + new byte[extendedblockstorage.getBlocklightArray().getData().length]); + } + + nbttaglist.appendTag(nbttagcompound); + } + } + + parNBTTagCompound.setTag("Sections", nbttaglist); + parNBTTagCompound.setByteArray("Biomes", chunkIn.getBiomeArray()); + chunkIn.setHasEntities(false); + NBTTagList nbttaglist1 = new NBTTagList(); + + for (int i1 = 0; i1 < chunkIn.getEntityLists().length; ++i1) { + for (Entity entity : chunkIn.getEntityLists()[i1]) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + if (entity.writeToNBTOptional(nbttagcompound1)) { + chunkIn.setHasEntities(true); + nbttaglist1.appendTag(nbttagcompound1); + } + } + } + + parNBTTagCompound.setTag("Entities", nbttaglist1); + NBTTagList nbttaglist2 = new NBTTagList(); + + for (TileEntity tileentity : chunkIn.getTileEntityMap().values()) { + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + tileentity.writeToNBT(nbttagcompound2); + nbttaglist2.appendTag(nbttagcompound2); + } + + parNBTTagCompound.setTag("TileEntities", nbttaglist2); + List list = worldIn.getPendingBlockUpdates(chunkIn, false); + if (list != null) { + long j1 = worldIn.getTotalWorldTime(); + NBTTagList nbttaglist3 = new NBTTagList(); + + for (int k = 0, l = list.size(); k < l; ++k) { + NextTickListEntry nextticklistentry = list.get(k); + NBTTagCompound nbttagcompound3 = new NBTTagCompound(); + ResourceLocation resourcelocation = (ResourceLocation) Block.blockRegistry + .getNameForObject(nextticklistentry.getBlock()); + nbttagcompound3.setString("i", resourcelocation == null ? "" : resourcelocation.toString()); + nbttagcompound3.setInteger("x", nextticklistentry.position.getX()); + nbttagcompound3.setInteger("y", nextticklistentry.position.getY()); + nbttagcompound3.setInteger("z", nextticklistentry.position.getZ()); + nbttagcompound3.setInteger("t", (int) (nextticklistentry.scheduledTime - j1)); + nbttagcompound3.setInteger("p", nextticklistentry.priority); + nbttaglist3.appendTag(nbttagcompound3); + } + + parNBTTagCompound.setTag("TileTicks", nbttaglist3); + } + + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/storage/ChunkLoader.java b/src/game/java/net/minecraft/world/chunk/storage/ChunkLoader.java index c0d07d15..d2f4849d 100644 --- a/src/game/java/net/minecraft/world/chunk/storage/ChunkLoader.java +++ b/src/game/java/net/minecraft/world/chunk/storage/ChunkLoader.java @@ -7,48 +7,48 @@ import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.WorldChunkManager; import net.minecraft.world.chunk.NibbleArray; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChunkLoader { - public static ChunkLoader.AnvilConverterData load(NBTTagCompound nbt) { - int i = nbt.getInteger("xPos"); - int j = nbt.getInteger("zPos"); - ChunkLoader.AnvilConverterData chunkloader$anvilconverterdata = new ChunkLoader.AnvilConverterData(i, j); - chunkloader$anvilconverterdata.blocks = nbt.getByteArray("Blocks"); - chunkloader$anvilconverterdata.data = new NibbleArrayReader(nbt.getByteArray("Data"), 7); - chunkloader$anvilconverterdata.skyLight = new NibbleArrayReader(nbt.getByteArray("SkyLight"), 7); - chunkloader$anvilconverterdata.blockLight = new NibbleArrayReader(nbt.getByteArray("BlockLight"), 7); - chunkloader$anvilconverterdata.heightmap = nbt.getByteArray("HeightMap"); - chunkloader$anvilconverterdata.terrainPopulated = nbt.getBoolean("TerrainPopulated"); - chunkloader$anvilconverterdata.entities = nbt.getTagList("Entities", 10); - chunkloader$anvilconverterdata.tileEntities = nbt.getTagList("TileEntities", 10); - chunkloader$anvilconverterdata.tileTicks = nbt.getTagList("TileTicks", 10); + public static class AnvilConverterData { + public long lastUpdated; + public boolean terrainPopulated; + public byte[] heightmap; + public NibbleArrayReader blockLight; + public NibbleArrayReader skyLight; + public NibbleArrayReader data; + public byte[] blocks; + public NBTTagList entities; + public NBTTagList tileEntities; + public NBTTagList tileTicks; + public final int x; + public final int z; - try { - chunkloader$anvilconverterdata.lastUpdated = nbt.getLong("LastUpdate"); - } catch (ClassCastException var5) { - chunkloader$anvilconverterdata.lastUpdated = (long) nbt.getInteger("LastUpdate"); + public AnvilConverterData(int parInt1, int parInt2) { + this.x = parInt1; + this.z = parInt2; } - - return chunkloader$anvilconverterdata; } public static void convertToAnvilFormat(ChunkLoader.AnvilConverterData parAnvilConverterData, @@ -133,23 +133,26 @@ public class ChunkLoader { } - public static class AnvilConverterData { - public long lastUpdated; - public boolean terrainPopulated; - public byte[] heightmap; - public NibbleArrayReader blockLight; - public NibbleArrayReader skyLight; - public NibbleArrayReader data; - public byte[] blocks; - public NBTTagList entities; - public NBTTagList tileEntities; - public NBTTagList tileTicks; - public final int x; - public final int z; + public static ChunkLoader.AnvilConverterData load(NBTTagCompound nbt) { + int i = nbt.getInteger("xPos"); + int j = nbt.getInteger("zPos"); + ChunkLoader.AnvilConverterData chunkloader$anvilconverterdata = new ChunkLoader.AnvilConverterData(i, j); + chunkloader$anvilconverterdata.blocks = nbt.getByteArray("Blocks"); + chunkloader$anvilconverterdata.data = new NibbleArrayReader(nbt.getByteArray("Data"), 7); + chunkloader$anvilconverterdata.skyLight = new NibbleArrayReader(nbt.getByteArray("SkyLight"), 7); + chunkloader$anvilconverterdata.blockLight = new NibbleArrayReader(nbt.getByteArray("BlockLight"), 7); + chunkloader$anvilconverterdata.heightmap = nbt.getByteArray("HeightMap"); + chunkloader$anvilconverterdata.terrainPopulated = nbt.getBoolean("TerrainPopulated"); + chunkloader$anvilconverterdata.entities = nbt.getTagList("Entities", 10); + chunkloader$anvilconverterdata.tileEntities = nbt.getTagList("TileEntities", 10); + chunkloader$anvilconverterdata.tileTicks = nbt.getTagList("TileTicks", 10); - public AnvilConverterData(int parInt1, int parInt2) { - this.x = parInt1; - this.z = parInt2; + try { + chunkloader$anvilconverterdata.lastUpdated = nbt.getLong("LastUpdate"); + } catch (ClassCastException var5) { + chunkloader$anvilconverterdata.lastUpdated = (long) nbt.getInteger("LastUpdate"); } + + return chunkloader$anvilconverterdata; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java b/src/game/java/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java index 98481991..72a6bf78 100644 --- a/src/game/java/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java +++ b/src/game/java/net/minecraft/world/chunk/storage/ExtendedBlockStorage.java @@ -5,22 +5,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.chunk.NibbleArray; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,100 +51,77 @@ public class ExtendedBlockStorage { return iblockstate != null ? iblockstate : Blocks.air.getDefaultState(); } - public void set(int x, int y, int z, IBlockState state) { - IBlockState iblockstate = this.get(x, y, z); - Block block = iblockstate.getBlock(); - Block block1 = state.getBlock(); - if (block != Blocks.air) { - --this.blockRefCount; - if (block.getTickRandomly()) { - --this.tickRefCount; - } - } - - if (block1 != Blocks.air) { - ++this.blockRefCount; - if (block1.getTickRandomly()) { - ++this.tickRefCount; - } - } - - this.data[y << 8 | z << 4 | x] = (char) Block.BLOCK_STATE_IDS.get(state); - } - - /**+ - * Returns the block for a location in a chunk, with the - * extended ID merged from a byte array and a NibbleArray to - * form a full 12-bit block ID. + /** + * + Returns the block for a location in a chunk, with the extended ID merged + * from a byte array and a NibbleArray to form a full 12-bit block ID. */ public Block getBlockByExtId(int x, int y, int z) { return this.get(x, y, z).getBlock(); } - /**+ - * Returns the metadata associated with the block at the given - * coordinates in this ExtendedBlockStorage. + /** + * + Returns the NibbleArray instance containing Block-light data. + */ + public NibbleArray getBlocklightArray() { + return this.blocklightArray; + } + + public char[] getData() { + return this.data; + } + + /** + * + Gets the saved Block-light value in the extended block storage structure. + */ + public int getExtBlocklightValue(int x, int y, int z) { + return this.blocklightArray.get(x, y, z); + } + + /** + * + Returns the metadata associated with the block at the given coordinates in + * this ExtendedBlockStorage. */ public int getExtBlockMetadata(int x, int y, int z) { IBlockState iblockstate = this.get(x, y, z); return iblockstate.getBlock().getMetaFromState(iblockstate); } - /**+ - * Returns whether or not this block storage's Chunk is fully - * empty, based on its internal reference count. - */ - public boolean isEmpty() { - return this.blockRefCount == 0; - } - - /**+ - * Returns whether or not this block storage's Chunk will - * require random ticking, used to avoid looping through random - * block ticks when there are no blocks that would randomly - * tick. - */ - public boolean getNeedsRandomTick() { - return this.tickRefCount > 0; - } - - /**+ - * Returns the Y location of this ExtendedBlockStorage. - */ - public int getYLocation() { - return this.yBase; - } - - /**+ - * Sets the saved Sky-light value in the extended block storage - * structure. - */ - public void setExtSkylightValue(int x, int y, int z, int value) { - this.skylightArray.set(x, y, z, value); - } - - /**+ - * Gets the saved Sky-light value in the extended block storage - * structure. + /** + * + Gets the saved Sky-light value in the extended block storage structure. */ public int getExtSkylightValue(int x, int y, int z) { return this.skylightArray.get(x, y, z); } - /**+ - * Sets the saved Block-light value in the extended block - * storage structure. + /** + * + Returns whether or not this block storage's Chunk will require random + * ticking, used to avoid looping through random block ticks when there are no + * blocks that would randomly tick. */ - public void setExtBlocklightValue(int x, int y, int z, int value) { - this.blocklightArray.set(x, y, z, value); + public boolean getNeedsRandomTick() { + return this.tickRefCount > 0; } - /**+ - * Gets the saved Block-light value in the extended block - * storage structure. + /** + * + Returns the NibbleArray instance containing Sky-light data. */ - public int getExtBlocklightValue(int x, int y, int z) { - return this.blocklightArray.get(x, y, z); + public NibbleArray getSkylightArray() { + return this.skylightArray; + } + + /** + * + Returns the Y location of this ExtendedBlockStorage. + */ + public int getYLocation() { + return this.yBase; + } + + /** + * + Returns whether or not this block storage's Chunk is fully empty, based on + * its internal reference count. + */ + public boolean isEmpty() { + return this.blockRefCount == 0; } public void removeInvalidBlocks() { @@ -164,39 +144,56 @@ public class ExtendedBlockStorage { } - public char[] getData() { - return this.data; + public void set(int x, int y, int z, IBlockState state) { + IBlockState iblockstate = this.get(x, y, z); + Block block = iblockstate.getBlock(); + Block block1 = state.getBlock(); + if (block != Blocks.air) { + --this.blockRefCount; + if (block.getTickRandomly()) { + --this.tickRefCount; + } + } + + if (block1 != Blocks.air) { + ++this.blockRefCount; + if (block1.getTickRandomly()) { + ++this.tickRefCount; + } + } + + this.data[y << 8 | z << 4 | x] = (char) Block.BLOCK_STATE_IDS.get(state); + } + + /** + * + Sets the NibbleArray instance used for Block-light values in this + * particular storage block. + */ + public void setBlocklightArray(NibbleArray newBlocklightArray) { + this.blocklightArray = newBlocklightArray; } public void setData(char[] dataArray) { this.data = dataArray; } - /**+ - * Returns the NibbleArray instance containing Block-light data. + /** + * + Sets the saved Block-light value in the extended block storage structure. */ - public NibbleArray getBlocklightArray() { - return this.blocklightArray; + public void setExtBlocklightValue(int x, int y, int z, int value) { + this.blocklightArray.set(x, y, z, value); } - /**+ - * Returns the NibbleArray instance containing Sky-light data. + /** + * + Sets the saved Sky-light value in the extended block storage structure. */ - public NibbleArray getSkylightArray() { - return this.skylightArray; + public void setExtSkylightValue(int x, int y, int z, int value) { + this.skylightArray.set(x, y, z, value); } - /**+ - * Sets the NibbleArray instance used for Block-light values in - * this particular storage block. - */ - public void setBlocklightArray(NibbleArray newBlocklightArray) { - this.blocklightArray = newBlocklightArray; - } - - /**+ - * Sets the NibbleArray instance used for Sky-light values in - * this particular storage block. + /** + * + Sets the NibbleArray instance used for Sky-light values in this particular + * storage block. */ public void setSkylightArray(NibbleArray newSkylightArray) { this.skylightArray = newSkylightArray; diff --git a/src/game/java/net/minecraft/world/chunk/storage/IChunkLoader.java b/src/game/java/net/minecraft/world/chunk/storage/IChunkLoader.java index 2d90f910..df8972c3 100644 --- a/src/game/java/net/minecraft/world/chunk/storage/IChunkLoader.java +++ b/src/game/java/net/minecraft/world/chunk/storage/IChunkLoader.java @@ -1,52 +1,56 @@ package net.minecraft.world.chunk.storage; import java.io.IOException; + import net.minecraft.world.MinecraftException; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IChunkLoader { - /**+ - * Loads the specified(XZ) chunk into the specified world. + /** + * + Called every World.tick() + */ + void chunkTick(); + + /** + * + Loads the specified(XZ) chunk into the specified world. */ Chunk loadChunk(World var1, int var2, int var3) throws IOException; void saveChunk(World var1, Chunk var2) throws IOException, MinecraftException; - /**+ - * Save extra data associated with this Chunk not normally saved - * during autosave, only during chunk unload. Currently unused. + /** + * + Save extra data associated with this Chunk not normally saved during + * autosave, only during chunk unload. Currently unused. */ void saveExtraChunkData(World var1, Chunk var2) throws IOException; - /**+ - * Called every World.tick() - */ - void chunkTick(); - - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently unused. + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unused. */ void saveExtraData(); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/chunk/storage/NibbleArrayReader.java b/src/game/java/net/minecraft/world/chunk/storage/NibbleArrayReader.java index 70b978e1..b14ccf6f 100644 --- a/src/game/java/net/minecraft/world/chunk/storage/NibbleArrayReader.java +++ b/src/game/java/net/minecraft/world/chunk/storage/NibbleArrayReader.java @@ -1,21 +1,24 @@ package net.minecraft.world.chunk.storage; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/chunk/storage/RegionFile.java b/src/game/java/net/minecraft/world/chunk/storage/RegionFile.java index c7e0d867..87206cad 100644 --- a/src/game/java/net/minecraft/world/chunk/storage/RegionFile.java +++ b/src/game/java/net/minecraft/world/chunk/storage/RegionFile.java @@ -13,32 +13,54 @@ import net.lax1dude.eaglercraft.v1_8.EaglerOutputStream; import net.lax1dude.eaglercraft.v1_8.EaglerZLIB; import net.lax1dude.eaglercraft.v1_8.sp.server.export.RandomAccessMemoryFile; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RegionFile { + class ChunkBuffer extends EaglerOutputStream { + private int chunkX; + private int chunkZ; + + public ChunkBuffer(int x, int z) { + super(8096); + this.chunkX = x; + this.chunkZ = z; + } + + /** + * + close this RegionFile and prevent further writes + */ + public void close() throws IOException { + RegionFile.this.write(this.chunkX, this.chunkZ, this.buf, this.count); + } + } + private static final byte[] emptySector = new byte[4096]; private RandomAccessMemoryFile dataFile; private final int[] offsets = new int[1024]; private final int[] chunkTimestamps = new int[1024]; private List sectorFree; + private int sizeDelta; public RegionFile(RandomAccessMemoryFile dataFile) { @@ -95,8 +117,8 @@ public class RegionFile { } - /**+ - * Returns an uncompressed chunk stream from the region file. + /** + * + Returns an uncompressed chunk stream from the region file. */ public synchronized DataInputStream getChunkDataInputStream(int x, int z) { if (this.outOfBounds(x, z)) { @@ -142,17 +164,70 @@ public class RegionFile { } } - /**+ - * Returns an output stream used to write chunk data. Data is on - * disk when the returned stream is closed. + /** + * + Returns an output stream used to write chunk data. Data is on disk when the + * returned stream is closed. */ public DataOutputStream getChunkDataOutputStream(int x, int z) throws IOException { return this.outOfBounds(x, z) ? null : new DataOutputStream(EaglerZLIB.newDeflaterOutputStream(new RegionFile.ChunkBuffer(x, z))); } - /**+ - * args: x, z, data, length - write chunk data at (x, z) to disk + public RandomAccessMemoryFile getFile() { + return dataFile; + } + + /** + * + args: x, z - get chunk's offset in region file + */ + private int getOffset(int x, int z) { + return this.offsets[x + z * 32]; + } + + /** + * + args: x, z, - true if chunk has been saved / converted + */ + public boolean isChunkSaved(int x, int z) { + return this.getOffset(x, z) != 0; + } + + /** + * + args: x, z - check region bounds + */ + private boolean outOfBounds(int x, int z) { + return x < 0 || x >= 32 || z < 0 || z >= 32; + } + + /** + * + args: x, z, timestamp - sets the chunk's write timestamp + */ + private void setChunkTimestamp(int x, int z, int timestamp) throws IOException { + this.chunkTimestamps[x + z * 32] = timestamp; + this.dataFile.seek(4096 + (x + z * 32) * 4); + this.dataFile.writeInt(timestamp); + } + + /** + * + args: x, z, offset - sets the chunk's offset in the region file + */ + private void setOffset(int x, int z, int offset) throws IOException { + this.offsets[x + z * 32] = offset; + this.dataFile.seek((x + z * 32) * 4); + this.dataFile.writeInt(offset); + } + + /** + * + args: x, z, data, length - write chunk data at (x, z) to disk + */ + private void write(int sectorNumber, byte[] data, int length) throws IOException { + this.dataFile.seek(sectorNumber * 4096); + this.dataFile.writeInt(length + 1); + this.dataFile.writeByte(2); + this.dataFile.write(data, 0, length); + } + + /** + * + args: x, z, data, length - write chunk data at (x, z) to disk */ protected synchronized void write(int x, int z, byte[] data, int length) { try { @@ -222,76 +297,4 @@ public class RegionFile { } } - - /**+ - * args: x, z, data, length - write chunk data at (x, z) to disk - */ - private void write(int sectorNumber, byte[] data, int length) throws IOException { - this.dataFile.seek(sectorNumber * 4096); - this.dataFile.writeInt(length + 1); - this.dataFile.writeByte(2); - this.dataFile.write(data, 0, length); - } - - /**+ - * args: x, z - check region bounds - */ - private boolean outOfBounds(int x, int z) { - return x < 0 || x >= 32 || z < 0 || z >= 32; - } - - /**+ - * args: x, z - get chunk's offset in region file - */ - private int getOffset(int x, int z) { - return this.offsets[x + z * 32]; - } - - /**+ - * args: x, z, - true if chunk has been saved / converted - */ - public boolean isChunkSaved(int x, int z) { - return this.getOffset(x, z) != 0; - } - - /**+ - * args: x, z, offset - sets the chunk's offset in the region - * file - */ - private void setOffset(int x, int z, int offset) throws IOException { - this.offsets[x + z * 32] = offset; - this.dataFile.seek((x + z * 32) * 4); - this.dataFile.writeInt(offset); - } - - /**+ - * args: x, z, timestamp - sets the chunk's write timestamp - */ - private void setChunkTimestamp(int x, int z, int timestamp) throws IOException { - this.chunkTimestamps[x + z * 32] = timestamp; - this.dataFile.seek(4096 + (x + z * 32) * 4); - this.dataFile.writeInt(timestamp); - } - - public RandomAccessMemoryFile getFile() { - return dataFile; - } - - class ChunkBuffer extends EaglerOutputStream { - private int chunkX; - private int chunkZ; - - public ChunkBuffer(int x, int z) { - super(8096); - this.chunkX = x; - this.chunkZ = z; - } - - /**+ - * close this RegionFile and prevent further writes - */ - public void close() throws IOException { - RegionFile.this.write(this.chunkX, this.chunkZ, this.buf, this.count); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/demo/DemoWorldManager.java b/src/game/java/net/minecraft/world/demo/DemoWorldManager.java index d6b0b5e8..869a21a3 100644 --- a/src/game/java/net/minecraft/world/demo/DemoWorldManager.java +++ b/src/game/java/net/minecraft/world/demo/DemoWorldManager.java @@ -9,22 +9,25 @@ import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,6 +42,68 @@ public class DemoWorldManager extends ItemInWorldManager { super(worldIn); } + /** + * + Activate the clicked on block, otherwise use the held item. + */ + public boolean activateBlockOrUseItem(EntityPlayer player, World worldIn, ItemStack stack, BlockPos pos, + EnumFacing side, float offsetX, float offsetY, float offsetZ) { + if (this.demoTimeExpired) { + this.sendDemoReminder(); + return false; + } else { + return super.activateBlockOrUseItem(player, worldIn, stack, pos, side, offsetX, offsetY, offsetZ); + } + } + + public void blockRemoving(BlockPos pos) { + if (!this.demoTimeExpired) { + super.blockRemoving(pos); + } + } + + /** + * + If not creative, it calls sendBlockBreakProgress until the block is broken + * first. tryHarvestBlock can also be the result of this call. + */ + public void onBlockClicked(BlockPos pos, EnumFacing side) { + if (this.demoTimeExpired) { + this.sendDemoReminder(); + } else { + super.onBlockClicked(pos, side); + } + } + + /** + * + Sends a message to the player reminding them that this is the demo version + */ + private void sendDemoReminder() { + if (this.field_73104_e > 100) { + this.thisPlayerMP.addChatMessage(new ChatComponentTranslation("demo.reminder", new Object[0])); + this.field_73104_e = 0; + } + + } + + /** + * + Attempts to harvest a block + */ + public boolean tryHarvestBlock(BlockPos pos) { + return this.demoTimeExpired ? false : super.tryHarvestBlock(pos); + } + + /** + * + Attempts to right-click use an item by the given EntityPlayer in the given + * World + */ + public boolean tryUseItem(EntityPlayer player, World worldIn, ItemStack stack) { + if (this.demoTimeExpired) { + this.sendDemoReminder(); + return false; + } else { + return super.tryUseItem(player, worldIn, stack); + } + } + public void updateBlockRemoving() { super.updateBlockRemoving(); ++this.field_73102_f; @@ -71,68 +136,4 @@ public class DemoWorldManager extends ItemInWorldManager { } } - - /**+ - * Sends a message to the player reminding them that this is the - * demo version - */ - private void sendDemoReminder() { - if (this.field_73104_e > 100) { - this.thisPlayerMP.addChatMessage(new ChatComponentTranslation("demo.reminder", new Object[0])); - this.field_73104_e = 0; - } - - } - - /**+ - * If not creative, it calls sendBlockBreakProgress until the - * block is broken first. tryHarvestBlock can also be the result - * of this call. - */ - public void onBlockClicked(BlockPos pos, EnumFacing side) { - if (this.demoTimeExpired) { - this.sendDemoReminder(); - } else { - super.onBlockClicked(pos, side); - } - } - - public void blockRemoving(BlockPos pos) { - if (!this.demoTimeExpired) { - super.blockRemoving(pos); - } - } - - /**+ - * Attempts to harvest a block - */ - public boolean tryHarvestBlock(BlockPos pos) { - return this.demoTimeExpired ? false : super.tryHarvestBlock(pos); - } - - /**+ - * Attempts to right-click use an item by the given EntityPlayer - * in the given World - */ - public boolean tryUseItem(EntityPlayer player, World worldIn, ItemStack stack) { - if (this.demoTimeExpired) { - this.sendDemoReminder(); - return false; - } else { - return super.tryUseItem(player, worldIn, stack); - } - } - - /**+ - * Activate the clicked on block, otherwise use the held item. - */ - public boolean activateBlockOrUseItem(EntityPlayer player, World worldIn, ItemStack stack, BlockPos pos, - EnumFacing side, float offsetX, float offsetY, float offsetZ) { - if (this.demoTimeExpired) { - this.sendDemoReminder(); - return false; - } else { - return super.activateBlockOrUseItem(player, worldIn, stack, pos, side, offsetX, offsetY, offsetZ); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/demo/DemoWorldServer.java b/src/game/java/net/minecraft/world/demo/DemoWorldServer.java index 5ed87813..9329ed54 100644 --- a/src/game/java/net/minecraft/world/demo/DemoWorldServer.java +++ b/src/game/java/net/minecraft/world/demo/DemoWorldServer.java @@ -1,5 +1,6 @@ package net.minecraft.world.demo; +import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; import net.minecraft.server.MinecraftServer; import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings; @@ -7,24 +8,25 @@ import net.minecraft.world.WorldType; import net.minecraft.world.storage.ISaveHandler; import net.minecraft.world.storage.WorldInfo; -import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderDebug.java b/src/game/java/net/minecraft/world/gen/ChunkProviderDebug.java index 18b93de7..ae470e32 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderDebug.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderDebug.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; @@ -15,22 +17,25 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.chunk.IChunkProvider; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,16 +44,95 @@ public class ChunkProviderDebug implements IChunkProvider { private static final List field_177464_a = Lists.newArrayList(); private static final int field_177462_b; private static final int field_181039_c; + static { + for (Block block : Block.blockRegistry) { + field_177464_a.addAll(block.getBlockState().getValidStates()); + } + + field_177462_b = MathHelper.ceiling_float_int(MathHelper.sqrt_float((float) field_177464_a.size())); + field_181039_c = MathHelper.ceiling_float_int((float) field_177464_a.size() / (float) field_177462_b); + } + + public static IBlockState func_177461_b(int parInt1, int parInt2) { + IBlockState iblockstate = null; + if (parInt1 > 0 && parInt2 > 0 && parInt1 % 2 != 0 && parInt2 % 2 != 0) { + parInt1 = parInt1 / 2; + parInt2 = parInt2 / 2; + if (parInt1 <= field_177462_b && parInt2 <= field_181039_c) { + int i = MathHelper.abs_int(parInt1 * field_177462_b + parInt2); + if (i < field_177464_a.size()) { + iblockstate = (IBlockState) field_177464_a.get(i); + } + } + } + + return iblockstate; + } + private final World world; public ChunkProviderDebug(World worldIn) { this.world = worldIn; } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + /** + * + Returns if the IChunkProvider supports saving. + */ + public boolean canSave() { + return true; + } + + /** + * + Checks to see if a chunk exists at x, z + */ + public boolean chunkExists(int var1, int var2) { + return true; + } + + public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { + return false; + } + + public int getLoadedChunkCount() { + return 0; + } + + public List getPossibleCreatures(EnumCreatureType enumcreaturetype, + BlockPos blockpos) { + BiomeGenBase biomegenbase = this.world.getBiomeGenForCoords(blockpos); + return biomegenbase.getSpawnableList(enumcreaturetype); + } + + public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { + return null; + } + + /** + * + Converts the instance data to a readable string. + */ + public String makeString() { + return "DebugLevelSource"; + } + + /** + * + Populates chunk with ores etc etc + */ + public void populate(IChunkProvider var1, int var2, int var3) { + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ public Chunk provideChunk(int i, int j) { ChunkPrimer chunkprimer = new ChunkPrimer(); @@ -79,110 +163,30 @@ public class ChunkProviderDebug implements IChunkProvider { return chunk; } - public static IBlockState func_177461_b(int parInt1, int parInt2) { - IBlockState iblockstate = null; - if (parInt1 > 0 && parInt2 > 0 && parInt1 % 2 != 0 && parInt2 % 2 != 0) { - parInt1 = parInt1 / 2; - parInt2 = parInt2 / 2; - if (parInt1 <= field_177462_b && parInt2 <= field_181039_c) { - int i = MathHelper.abs_int(parInt1 * field_177462_b + parInt2); - if (i < field_177464_a.size()) { - iblockstate = (IBlockState) field_177464_a.get(i); - } - } - } - - return iblockstate; + public void recreateStructures(Chunk var1, int var2, int var3) { } - /**+ - * Checks to see if a chunk exists at x, z - */ - public boolean chunkExists(int var1, int var2) { - return true; - } - - /**+ - * Populates chunk with ores etc etc - */ - public void populate(IChunkProvider var1, int var2, int var3) { - } - - public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { - return false; - } - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. */ public boolean saveChunks(boolean var1, IProgressUpdate var2) { return true; } - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. */ public void saveExtraData() { } - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. */ public boolean unloadQueuedChunks() { return false; } - - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return true; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "DebugLevelSource"; - } - - public List getPossibleCreatures(EnumCreatureType enumcreaturetype, - BlockPos blockpos) { - BiomeGenBase biomegenbase = this.world.getBiomeGenForCoords(blockpos); - return biomegenbase.getSpawnableList(enumcreaturetype); - } - - public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { - return null; - } - - public int getLoadedChunkCount() { - return 0; - } - - public void recreateStructures(Chunk var1, int var2, int var3) { - } - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); - } - - static { - for (Block block : Block.blockRegistry) { - field_177464_a.addAll(block.getBlockState().getValidStates()); - } - - field_177462_b = MathHelper.ceiling_float_int(MathHelper.sqrt_float((float) field_177464_a.size())); - field_181039_c = MathHelper.ceiling_float_int((float) field_177464_a.size() / (float) field_177462_b); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderEnd.java b/src/game/java/net/minecraft/world/gen/ChunkProviderEnd.java index 6a478597..9dc47605 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderEnd.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderEnd.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockFalling; import net.minecraft.block.material.Material; @@ -16,22 +17,25 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.chunk.IChunkProvider; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,6 +66,60 @@ public class ChunkProviderEnd implements IChunkProvider { this.noiseGen5 = new NoiseGeneratorOctaves(this.endRNG, 16); } + /** + * + Returns if the IChunkProvider supports saving. + */ + public boolean canSave() { + return true; + } + + /** + * + Checks to see if a chunk exists at x, z + */ + public boolean chunkExists(int var1, int var2) { + return true; + } + + public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { + return false; + } + + public void func_180519_a(ChunkPrimer parChunkPrimer) { + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + byte b0 = 1; + int k = -1; + IBlockState iblockstate = Blocks.end_stone.getDefaultState(); + IBlockState iblockstate1 = Blocks.end_stone.getDefaultState(); + + for (int l = 127; l >= 0; --l) { + IBlockState iblockstate2 = parChunkPrimer.getBlockState(i, l, j); + if (iblockstate2.getBlock().getMaterial() == Material.air) { + k = -1; + } else if (iblockstate2.getBlock() == Blocks.stone) { + if (k == -1) { + if (b0 <= 0) { + iblockstate = Blocks.air.getDefaultState(); + iblockstate1 = Blocks.end_stone.getDefaultState(); + } + + k = b0; + if (l >= 0) { + parChunkPrimer.setBlockState(i, l, j, iblockstate); + } else { + parChunkPrimer.setBlockState(i, l, j, iblockstate1); + } + } else if (k > 0) { + --k; + parChunkPrimer.setBlockState(i, l, j, iblockstate1); + } + } + } + } + } + + } + public void func_180520_a(int parInt1, int parInt2, ChunkPrimer parChunkPrimer) { byte b0 = 2; int i = b0 + 1; @@ -122,69 +180,22 @@ public class ChunkProviderEnd implements IChunkProvider { } - public void func_180519_a(ChunkPrimer parChunkPrimer) { - for (int i = 0; i < 16; ++i) { - for (int j = 0; j < 16; ++j) { - byte b0 = 1; - int k = -1; - IBlockState iblockstate = Blocks.end_stone.getDefaultState(); - IBlockState iblockstate1 = Blocks.end_stone.getDefaultState(); - - for (int l = 127; l >= 0; --l) { - IBlockState iblockstate2 = parChunkPrimer.getBlockState(i, l, j); - if (iblockstate2.getBlock().getMaterial() == Material.air) { - k = -1; - } else if (iblockstate2.getBlock() == Blocks.stone) { - if (k == -1) { - if (b0 <= 0) { - iblockstate = Blocks.air.getDefaultState(); - iblockstate1 = Blocks.end_stone.getDefaultState(); - } - - k = b0; - if (l >= 0) { - parChunkPrimer.setBlockState(i, l, j, iblockstate); - } else { - parChunkPrimer.setBlockState(i, l, j, iblockstate1); - } - } else if (k > 0) { - --k; - parChunkPrimer.setBlockState(i, l, j, iblockstate1); - } - } - } - } - } - + public int getLoadedChunkCount() { + return 0; } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(int i, int j) { - this.endRNG.setSeed((long) i * 341873128712L + (long) j * 132897987541L); - ChunkPrimer chunkprimer = new ChunkPrimer(); - this.biomesForGeneration = this.endWorld.getWorldChunkManager().loadBlockGeneratorData(this.biomesForGeneration, - i * 16, j * 16, 16, 16); - this.func_180520_a(i, j, chunkprimer); - this.func_180519_a(chunkprimer); - Chunk chunk = new Chunk(this.endWorld, chunkprimer, i, j); - byte[] abyte = chunk.getBiomeArray(); - - for (int k = 0; k < abyte.length; ++k) { - abyte[k] = (byte) this.biomesForGeneration[k].biomeID; - } - - chunk.generateSkylightMap(); - return chunk; + public List getPossibleCreatures(EnumCreatureType enumcreaturetype, + BlockPos blockpos) { + return this.endWorld.getBiomeGenForCoords(blockpos).getSpawnableList(enumcreaturetype); } - /**+ - * generates a subset of the level's terrain data. Takes 7 - * arguments: the [empty] noise array, the position, and the - * size. + public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { + return null; + } + + /** + * + generates a subset of the level's terrain data. Takes 7 arguments: the + * [empty] noise array, the position, and the size. */ private double[] initializeNoiseField(double[] parArrayOfDouble, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6) { @@ -257,15 +268,15 @@ public class ChunkProviderEnd implements IChunkProvider { return parArrayOfDouble; } - /**+ - * Checks to see if a chunk exists at x, z + /** + * + Converts the instance data to a readable string. */ - public boolean chunkExists(int var1, int var2) { - return true; + public String makeString() { + return "RandomLevelSource"; } - /**+ - * Populates chunk with ores etc etc + /** + * + Populates chunk with ores etc etc */ public void populate(IChunkProvider var1, int i, int j) { BlockFalling.fallInstantly = true; @@ -275,71 +286,62 @@ public class ChunkProviderEnd implements IChunkProvider { BlockFalling.fallInstantly = false; } - public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { - return false; - } - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ - public boolean saveChunks(boolean var1, IProgressUpdate var2) { - return true; + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); } - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ - public void saveExtraData() { - } + public Chunk provideChunk(int i, int j) { + this.endRNG.setSeed((long) i * 341873128712L + (long) j * 132897987541L); + ChunkPrimer chunkprimer = new ChunkPrimer(); + this.biomesForGeneration = this.endWorld.getWorldChunkManager().loadBlockGeneratorData(this.biomesForGeneration, + i * 16, j * 16, 16, 16); + this.func_180520_a(i, j, chunkprimer); + this.func_180519_a(chunkprimer); + Chunk chunk = new Chunk(this.endWorld, chunkprimer, i, j); + byte[] abyte = chunk.getBiomeArray(); - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. - */ - public boolean unloadQueuedChunks() { - return false; - } + for (int k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) this.biomesForGeneration[k].biomeID; + } - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return true; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "RandomLevelSource"; - } - - public List getPossibleCreatures(EnumCreatureType enumcreaturetype, - BlockPos blockpos) { - return this.endWorld.getBiomeGenForCoords(blockpos).getSpawnableList(enumcreaturetype); - } - - public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { - return null; - } - - public int getLoadedChunkCount() { - return 0; + chunk.generateSkylightMap(); + return chunk; } public void recreateStructures(Chunk var1, int var2, int var3) { } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + public boolean saveChunks(boolean var1, IProgressUpdate var2) { + return true; + } + + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. + */ + public void saveExtraData() { + } + + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. + */ + public boolean unloadQueuedChunks() { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderFlat.java b/src/game/java/net/minecraft/world/gen/ChunkProviderFlat.java index 9f40a60b..36ed7a20 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderFlat.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderFlat.java @@ -1,8 +1,10 @@ package net.minecraft.world.gen; -import com.google.common.collect.Lists; import java.util.List; import java.util.Map; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; @@ -24,22 +26,25 @@ import net.minecraft.world.gen.structure.MapGenStructure; import net.minecraft.world.gen.structure.MapGenVillage; import net.minecraft.world.gen.structure.StructureOceanMonument; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -122,51 +127,56 @@ public class ChunkProviderFlat implements IChunkProvider { this.hasDecoration = flag ? false : this.flatWorldGenInfo.getWorldFeatures().containsKey("decoration"); } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + /** + * + Returns if the IChunkProvider supports saving. */ - public Chunk provideChunk(int i, int j) { - ChunkPrimer chunkprimer = new ChunkPrimer(); - - for (int k = 0; k < this.cachedBlockIDs.length; ++k) { - IBlockState iblockstate = this.cachedBlockIDs[k]; - if (iblockstate != null) { - for (int l = 0; l < 16; ++l) { - for (int i1 = 0; i1 < 16; ++i1) { - chunkprimer.setBlockState(l, k, i1, iblockstate); - } - } - } - } - - for (MapGenBase mapgenbase : this.structureGenerators) { - mapgenbase.generate(this, this.worldObj, i, j, chunkprimer); - } - - Chunk chunk = new Chunk(this.worldObj, chunkprimer, i, j); - BiomeGenBase[] abiomegenbase = this.worldObj.getWorldChunkManager() - .loadBlockGeneratorData((BiomeGenBase[]) null, i * 16, j * 16, 16, 16); - byte[] abyte = chunk.getBiomeArray(); - - for (int j1 = 0; j1 < abyte.length; ++j1) { - abyte[j1] = (byte) abiomegenbase[j1].biomeID; - } - - chunk.generateSkylightMap(); - return chunk; + public boolean canSave() { + return true; } - /**+ - * Checks to see if a chunk exists at x, z + /** + * + Checks to see if a chunk exists at x, z */ public boolean chunkExists(int var1, int var2) { return true; } - /**+ - * Populates chunk with ores etc etc + public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { + return false; + } + + public int getLoadedChunkCount() { + return 0; + } + + public List getPossibleCreatures(EnumCreatureType enumcreaturetype, + BlockPos blockpos) { + BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); + return biomegenbase.getSpawnableList(enumcreaturetype); + } + + public BlockPos getStrongholdGen(World world, String s, BlockPos blockpos) { + if ("Stronghold".equals(s)) { + for (int m = 0, n = this.structureGenerators.size(); m < n; ++m) { + MapGenStructure mapgenstructure = this.structureGenerators.get(m); + if (mapgenstructure instanceof MapGenStronghold) { + return mapgenstructure.getClosestStrongholdPos(world, blockpos); + } + } + } + + return null; + } + + /** + * + Converts the instance data to a readable string. + */ + public String makeString() { + return "FlatLevelSource"; + } + + /** + * + Populates chunk with ores etc etc */ public void populate(IChunkProvider var1, int i, int j) { int k = i * 16; @@ -214,70 +224,49 @@ public class ChunkProviderFlat implements IChunkProvider { } - public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { - return false; - } - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ - public boolean saveChunks(boolean var1, IProgressUpdate var2) { - return true; + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); } - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ - public void saveExtraData() { - } + public Chunk provideChunk(int i, int j) { + ChunkPrimer chunkprimer = new ChunkPrimer(); - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. - */ - public boolean unloadQueuedChunks() { - return false; - } - - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return true; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "FlatLevelSource"; - } - - public List getPossibleCreatures(EnumCreatureType enumcreaturetype, - BlockPos blockpos) { - BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); - return biomegenbase.getSpawnableList(enumcreaturetype); - } - - public BlockPos getStrongholdGen(World world, String s, BlockPos blockpos) { - if ("Stronghold".equals(s)) { - for (int m = 0, n = this.structureGenerators.size(); m < n; ++m) { - MapGenStructure mapgenstructure = this.structureGenerators.get(m); - if (mapgenstructure instanceof MapGenStronghold) { - return mapgenstructure.getClosestStrongholdPos(world, blockpos); + for (int k = 0; k < this.cachedBlockIDs.length; ++k) { + IBlockState iblockstate = this.cachedBlockIDs[k]; + if (iblockstate != null) { + for (int l = 0; l < 16; ++l) { + for (int i1 = 0; i1 < 16; ++i1) { + chunkprimer.setBlockState(l, k, i1, iblockstate); + } } } } - return null; - } + for (MapGenBase mapgenbase : this.structureGenerators) { + mapgenbase.generate(this, this.worldObj, i, j, chunkprimer); + } - public int getLoadedChunkCount() { - return 0; + Chunk chunk = new Chunk(this.worldObj, chunkprimer, i, j); + BiomeGenBase[] abiomegenbase = this.worldObj.getWorldChunkManager() + .loadBlockGeneratorData((BiomeGenBase[]) null, i * 16, j * 16, 16, 16); + byte[] abyte = chunk.getBiomeArray(); + + for (int j1 = 0; j1 < abyte.length; ++j1) { + abyte[j1] = (byte) abiomegenbase[j1].biomeID; + } + + chunk.generateSkylightMap(); + return chunk; } public void recreateStructures(Chunk var1, int i, int j) { @@ -287,12 +276,27 @@ public class ChunkProviderFlat implements IChunkProvider { } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + public boolean saveChunks(boolean var1, IProgressUpdate var2) { + return true; + } + + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. + */ + public void saveExtraData() { + } + + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. + */ + public boolean unloadQueuedChunks() { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderGenerate.java b/src/game/java/net/minecraft/world/gen/ChunkProviderGenerate.java index d0d00769..2db0c7ee 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderGenerate.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderGenerate.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.BlockFalling; @@ -25,22 +26,25 @@ import net.minecraft.world.gen.structure.MapGenStronghold; import net.minecraft.world.gen.structure.MapGenVillage; import net.minecraft.world.gen.structure.StructureOceanMonument; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -113,137 +117,22 @@ public class ChunkProviderGenerate implements IChunkProvider { } - public void setBlocksInChunk(int parInt1, int parInt2, ChunkPrimer parChunkPrimer) { - this.biomesForGeneration = this.worldObj.getWorldChunkManager().getBiomesForGeneration(this.biomesForGeneration, - parInt1 * 4 - 2, parInt2 * 4 - 2, 10, 10); - this.func_147423_a(parInt1 * 4, 0, parInt2 * 4); - - for (int i = 0; i < 4; ++i) { - int j = i * 5; - int k = (i + 1) * 5; - - for (int l = 0; l < 4; ++l) { - int i1 = (j + l) * 33; - int j1 = (j + l + 1) * 33; - int k1 = (k + l) * 33; - int l1 = (k + l + 1) * 33; - - for (int i2 = 0; i2 < 32; ++i2) { - double d0 = 0.125D; - double d1 = this.field_147434_q[i1 + i2]; - double d2 = this.field_147434_q[j1 + i2]; - double d3 = this.field_147434_q[k1 + i2]; - double d4 = this.field_147434_q[l1 + i2]; - double d5 = (this.field_147434_q[i1 + i2 + 1] - d1) * d0; - double d6 = (this.field_147434_q[j1 + i2 + 1] - d2) * d0; - double d7 = (this.field_147434_q[k1 + i2 + 1] - d3) * d0; - double d8 = (this.field_147434_q[l1 + i2 + 1] - d4) * d0; - - for (int j2 = 0; j2 < 8; ++j2) { - double d9 = 0.25D; - double d10 = d1; - double d11 = d2; - double d12 = (d3 - d1) * d9; - double d13 = (d4 - d2) * d9; - - for (int k2 = 0; k2 < 4; ++k2) { - double d14 = 0.25D; - double d16 = (d11 - d10) * d14; - double d15 = d10 - d16; - - for (int l2 = 0; l2 < 4; ++l2) { - if ((d15 += d16) > 0.0D) { - parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, - Blocks.stone.getDefaultState()); - } else if (i2 * 8 + j2 < this.settings.seaLevel) { - parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, - this.field_177476_s.getDefaultState()); - } - } - - d10 += d12; - d11 += d13; - } - - d1 += d5; - d2 += d6; - d3 += d7; - d4 += d8; - } - } - } - } - - } - - public void replaceBlocksForBiome(int parInt1, int parInt2, ChunkPrimer parChunkPrimer, - BiomeGenBase[] parArrayOfBiomeGenBase) { - double d0 = 0.03125D; - this.stoneNoise = this.field_147430_m.func_151599_a(this.stoneNoise, (double) (parInt1 * 16), - (double) (parInt2 * 16), 16, 16, d0 * 2.0D, d0 * 2.0D, 1.0D); - - for (int i = 0; i < 16; ++i) { - for (int j = 0; j < 16; ++j) { - BiomeGenBase biomegenbase = parArrayOfBiomeGenBase[j + i * 16]; - biomegenbase.genTerrainBlocks(this.worldObj, this.rand, parChunkPrimer, parInt1 * 16 + i, - parInt2 * 16 + j, this.stoneNoise[j + i * 16]); - } - } - - } - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + /** + * + Returns if the IChunkProvider supports saving. */ - public Chunk provideChunk(int i, int j) { - this.rand.setSeed((long) i * 341873128712L + (long) j * 132897987541L); - ChunkPrimer chunkprimer = new ChunkPrimer(); - this.setBlocksInChunk(i, j, chunkprimer); - this.biomesForGeneration = this.worldObj.getWorldChunkManager().loadBlockGeneratorData(this.biomesForGeneration, - i * 16, j * 16, 16, 16); - this.replaceBlocksForBiome(i, j, chunkprimer, this.biomesForGeneration); - if (this.settings.useCaves) { - this.caveGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } + public boolean canSave() { + return true; + } - if (this.settings.useRavines) { - this.ravineGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } - - if (this.settings.useMineShafts && this.mapFeaturesEnabled) { - this.mineshaftGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } - - if (this.settings.useVillages && this.mapFeaturesEnabled) { - this.villageGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } - - if (this.settings.useStrongholds && this.mapFeaturesEnabled) { - this.strongholdGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } - - if (this.settings.useTemples && this.mapFeaturesEnabled) { - this.scatteredFeatureGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } - - if (this.settings.useMonuments && this.mapFeaturesEnabled) { - this.oceanMonumentGenerator.generate(this, this.worldObj, i, j, chunkprimer); - } - - Chunk chunk = new Chunk(this.worldObj, chunkprimer, i, j); - byte[] abyte = chunk.getBiomeArray(); - - for (int k = 0; k < abyte.length; ++k) { - abyte[k] = (byte) this.biomesForGeneration[k].biomeID; - } - - chunk.generateSkylightMap(); - return chunk; + /** + * + Checks to see if a chunk exists at x, z + */ + public boolean chunkExists(int var1, int var2) { + return true; } private void func_147423_a(int parInt1, int parInt2, int parInt3) { + this.field_147426_g = this.noiseGen6.generateNoiseOctaves(this.field_147426_g, parInt1, parInt3, 5, 5, (double) this.settings.depthNoiseScaleX, (double) this.settings.depthNoiseScaleZ, (double) this.settings.depthNoiseScaleExponent); @@ -343,20 +232,60 @@ public class ChunkProviderGenerate implements IChunkProvider { this.field_147434_q[i] = d5; ++i; } + } + } } - /**+ - * Checks to see if a chunk exists at x, z - */ - public boolean chunkExists(int var1, int var2) { - return true; + public boolean func_177460_a(IChunkProvider var1, Chunk chunk, int i, int j) { + boolean flag = false; + if (this.settings.useMonuments && this.mapFeaturesEnabled && chunk.getInhabitedTime() < 3600L) { + flag |= this.oceanMonumentGenerator.generateStructure(this.worldObj, this.rand, + new ChunkCoordIntPair(i, j)); + } + + return flag; } - /**+ - * Populates chunk with ores etc etc + public int getLoadedChunkCount() { + return 0; + } + + public List getPossibleCreatures(EnumCreatureType enumcreaturetype, + BlockPos blockpos) { + BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); + if (this.mapFeaturesEnabled) { + if (enumcreaturetype == EnumCreatureType.MONSTER + && this.scatteredFeatureGenerator.func_175798_a(blockpos)) { + return this.scatteredFeatureGenerator.getScatteredFeatureSpawnList(); + } + + if (enumcreaturetype == EnumCreatureType.MONSTER && this.settings.useMonuments + && this.oceanMonumentGenerator.func_175796_a(this.worldObj, blockpos)) { + return this.oceanMonumentGenerator.func_175799_b(); + } + } + + return biomegenbase.getSpawnableList(enumcreaturetype); + } + + public BlockPos getStrongholdGen(World world, String s, BlockPos blockpos) { + return "Stronghold".equals(s) && this.strongholdGenerator != null + ? this.strongholdGenerator.getClosestStrongholdPos(world, blockpos) + : null; + } + + /** + * + Converts the instance data to a readable string. + */ + public String makeString() { + return "RandomLevelSource"; + } + + /** + * + Populates chunk with ores etc etc */ public void populate(IChunkProvider var1, int i, int j) { BlockFalling.fallInstantly = true; @@ -437,81 +366,64 @@ public class ChunkProviderGenerate implements IChunkProvider { BlockFalling.fallInstantly = false; } - public boolean func_177460_a(IChunkProvider var1, Chunk chunk, int i, int j) { - boolean flag = false; - if (this.settings.useMonuments && this.mapFeaturesEnabled && chunk.getInhabitedTime() < 3600L) { - flag |= this.oceanMonumentGenerator.generateStructure(this.worldObj, this.rand, - new ChunkCoordIntPair(i, j)); + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(int i, int j) { + this.rand.setSeed((long) i * 341873128712L + (long) j * 132897987541L); + ChunkPrimer chunkprimer = new ChunkPrimer(); + this.setBlocksInChunk(i, j, chunkprimer); + this.biomesForGeneration = this.worldObj.getWorldChunkManager().loadBlockGeneratorData(this.biomesForGeneration, + i * 16, j * 16, 16, 16); + this.replaceBlocksForBiome(i, j, chunkprimer, this.biomesForGeneration); + if (this.settings.useCaves) { + this.caveGenerator.generate(this, this.worldObj, i, j, chunkprimer); } - return flag; - } - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. - */ - public boolean saveChunks(boolean var1, IProgressUpdate var2) { - return true; - } - - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. - */ - public void saveExtraData() { - } - - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. - */ - public boolean unloadQueuedChunks() { - return false; - } - - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return true; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "RandomLevelSource"; - } - - public List getPossibleCreatures(EnumCreatureType enumcreaturetype, - BlockPos blockpos) { - BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); - if (this.mapFeaturesEnabled) { - if (enumcreaturetype == EnumCreatureType.MONSTER - && this.scatteredFeatureGenerator.func_175798_a(blockpos)) { - return this.scatteredFeatureGenerator.getScatteredFeatureSpawnList(); - } - - if (enumcreaturetype == EnumCreatureType.MONSTER && this.settings.useMonuments - && this.oceanMonumentGenerator.func_175796_a(this.worldObj, blockpos)) { - return this.oceanMonumentGenerator.func_175799_b(); - } + if (this.settings.useRavines) { + this.ravineGenerator.generate(this, this.worldObj, i, j, chunkprimer); } - return biomegenbase.getSpawnableList(enumcreaturetype); - } + if (this.settings.useMineShafts && this.mapFeaturesEnabled) { + this.mineshaftGenerator.generate(this, this.worldObj, i, j, chunkprimer); + } - public BlockPos getStrongholdGen(World world, String s, BlockPos blockpos) { - return "Stronghold".equals(s) && this.strongholdGenerator != null - ? this.strongholdGenerator.getClosestStrongholdPos(world, blockpos) - : null; - } + if (this.settings.useVillages && this.mapFeaturesEnabled) { + this.villageGenerator.generate(this, this.worldObj, i, j, chunkprimer); + } - public int getLoadedChunkCount() { - return 0; + if (this.settings.useStrongholds && this.mapFeaturesEnabled) { + this.strongholdGenerator.generate(this, this.worldObj, i, j, chunkprimer); + } + + if (this.settings.useTemples && this.mapFeaturesEnabled) { + this.scatteredFeatureGenerator.generate(this, this.worldObj, i, j, chunkprimer); + } + + if (this.settings.useMonuments && this.mapFeaturesEnabled) { + this.oceanMonumentGenerator.generate(this, this.worldObj, i, j, chunkprimer); + } + + Chunk chunk = new Chunk(this.worldObj, chunkprimer, i, j); + byte[] abyte = chunk.getBiomeArray(); + + for (int k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) this.biomesForGeneration[k].biomeID; + } + + chunk.generateSkylightMap(); + return chunk; } public void recreateStructures(Chunk var1, int i, int j) { @@ -537,12 +449,124 @@ public class ChunkProviderGenerate implements IChunkProvider { } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + public void replaceBlocksForBiome(int parInt1, int parInt2, ChunkPrimer parChunkPrimer, + BiomeGenBase[] parArrayOfBiomeGenBase) { + double d0 = 0.03125D; + this.stoneNoise = this.field_147430_m.func_151599_a(this.stoneNoise, (double) (parInt1 * 16), + (double) (parInt2 * 16), 16, 16, d0 * 2.0D, d0 * 2.0D, 1.0D); + + for (int i = 0; i < 16; ++i) { + for (int j = 0; j < 16; ++j) { + BiomeGenBase biomegenbase = parArrayOfBiomeGenBase[j + i * 16]; + biomegenbase.genTerrainBlocks(this.worldObj, this.rand, parChunkPrimer, parInt1 * 16 + i, + parInt2 * 16 + j, this.stoneNoise[j + i * 16]); + } + } + + } + + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + public boolean saveChunks(boolean var1, IProgressUpdate var2) { + return true; + } + + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. + */ + public void saveExtraData() { + } + + public void setBlocksInChunk(int parInt1, int parInt2, ChunkPrimer parChunkPrimer) { + this.biomesForGeneration = this.worldObj.getWorldChunkManager().getBiomesForGeneration(this.biomesForGeneration, + parInt1 * 4 - 2, parInt2 * 4 - 2, 10, 10); + this.func_147423_a(parInt1 * 4, 0, parInt2 * 4); + + for (int i = 0; i < 4; ++i) { + int j = i * 5; + int k = (i + 1) * 5; + + for (int l = 0; l < 4; ++l) { + int i1 = (j + l) * 33; + int j1 = (j + l + 1) * 33; + int k1 = (k + l) * 33; + int l1 = (k + l + 1) * 33; + + for (int i2 = 0; i2 < 32; ++i2) { + double d0 = 0.125D; + double d1 = this.field_147434_q[i1 + i2]; + double d2 = this.field_147434_q[j1 + i2]; + double d3 = this.field_147434_q[k1 + i2]; + double d4 = this.field_147434_q[l1 + i2]; + double d5 = (this.field_147434_q[i1 + i2 + 1] - d1) * d0; + double d6 = (this.field_147434_q[j1 + i2 + 1] - d2) * d0; + double d7 = (this.field_147434_q[k1 + i2 + 1] - d3) * d0; + double d8 = (this.field_147434_q[l1 + i2 + 1] - d4) * d0; + + for (int j2 = 0; j2 < 8; ++j2) { + double d9 = 0.25D; + double d10 = d1; + double d11 = d2; + double d12 = (d3 - d1) * d9; + double d13 = (d4 - d2) * d9; + + for (int k2 = 0; k2 < 4; ++k2) { + double d14 = 0.25D; + double d16 = (d11 - d10) * d14; + double d15 = d10 - d16; + + for (int l2 = 0; l2 < 4; ++l2) { + if ((d15 += d16) > 0.0D) { + if (i2 * 8 + j2 < 25) { + if (i2 * 8 + j2 > 22) { + EaglercraftRandom blend = new EaglercraftRandom(); + int blendAmount = blend.nextInt(4); + + if (blendAmount == 3) { + parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, + Blocks.stone.getDefaultState()); + } else { + parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, + Blocks.deepstone.getDefaultState()); + } + } else { + parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, + Blocks.deepstone.getDefaultState()); + } + } else { + parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, + Blocks.stone.getDefaultState()); + } + } else if (i2 * 8 + j2 < this.settings.seaLevel) { + parChunkPrimer.setBlockState(i * 4 + k2, i2 * 8 + j2, l * 4 + l2, + this.field_177476_s.getDefaultState()); + } + } + + d10 += d12; + d11 += d13; + } + + d1 += d5; + d2 += d6; + d3 += d7; + d4 += d8; + } + } + } + } + + } + + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. + */ + public boolean unloadQueuedChunks() { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderHell.java b/src/game/java/net/minecraft/world/gen/ChunkProviderHell.java index 693b53c7..be39462f 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderHell.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderHell.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockFalling; import net.minecraft.block.material.Material; @@ -25,22 +26,25 @@ import net.minecraft.world.gen.feature.WorldGenMinable; import net.minecraft.world.gen.feature.WorldGenerator; import net.minecraft.world.gen.structure.MapGenNetherBridge; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,15 +53,15 @@ public class ChunkProviderHell implements IChunkProvider { private final World worldObj; private final boolean field_177466_i; private final EaglercraftRandom hellRNG; - /**+ - * Holds the noise used to determine whether slowsand can be - * generated at a location + /** + * + Holds the noise used to determine whether slowsand can be generated at a + * location */ private double[] slowsandNoise = new double[256]; private double[] gravelNoise = new double[256]; - /**+ - * Holds the noise used to determine whether something other - * than netherrack can be generated at a location + /** + * + Holds the noise used to determine whether something other than netherrack + * can be generated at a location */ private double[] netherrackExclusivityNoise = new double[256]; private double[] noiseField; @@ -105,6 +109,24 @@ public class ChunkProviderHell implements IChunkProvider { worldIn.func_181544_b(63); } + /** + * + Returns if the IChunkProvider supports saving. + */ + public boolean canSave() { + return true; + } + + /** + * + Checks to see if a chunk exists at x, z + */ + public boolean chunkExists(int var1, int var2) { + return true; + } + + public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { + return false; + } + public void func_180515_a(int parInt1, int parInt2, ChunkPrimer parChunkPrimer) { byte b0 = 4; int i = this.worldObj.func_181545_F() / 2 + 1; @@ -242,38 +264,34 @@ public class ChunkProviderHell implements IChunkProvider { } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(int i, int j) { - this.hellRNG.setSeed((long) i * 341873128712L + (long) j * 132897987541L); - ChunkPrimer chunkprimer = new ChunkPrimer(); - this.func_180515_a(i, j, chunkprimer); - this.func_180516_b(i, j, chunkprimer); - this.netherCaveGenerator.generate(this, this.worldObj, i, j, chunkprimer); - if (this.field_177466_i) { - this.genNetherBridge.generate(this, this.worldObj, i, j, chunkprimer); - } - - Chunk chunk = new Chunk(this.worldObj, chunkprimer, i, j); - BiomeGenBase[] abiomegenbase = this.worldObj.getWorldChunkManager() - .loadBlockGeneratorData((BiomeGenBase[]) null, i * 16, j * 16, 16, 16); - byte[] abyte = chunk.getBiomeArray(); - - for (int k = 0; k < abyte.length; ++k) { - abyte[k] = (byte) abiomegenbase[k].biomeID; - } - - chunk.resetRelightChecks(); - return chunk; + public int getLoadedChunkCount() { + return 0; } - /**+ - * generates a subset of the level's terrain data. Takes 7 - * arguments: the [empty] noise array, the position, and the - * size. + public List getPossibleCreatures(EnumCreatureType enumcreaturetype, + BlockPos blockpos) { + if (enumcreaturetype == EnumCreatureType.MONSTER) { + if (this.genNetherBridge.func_175795_b(blockpos)) { + return this.genNetherBridge.getSpawnList(); + } + + if (this.genNetherBridge.func_175796_a(this.worldObj, blockpos) + && this.worldObj.getBlockState(blockpos.down()).getBlock() == Blocks.nether_brick) { + return this.genNetherBridge.getSpawnList(); + } + } + + BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); + return biomegenbase.getSpawnableList(enumcreaturetype); + } + + public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { + return null; + } + + /** + * + generates a subset of the level's terrain data. Takes 7 arguments: the + * [empty] noise array, the position, and the size. */ private double[] initializeNoiseField(double[] parArrayOfDouble, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6) { @@ -348,15 +366,15 @@ public class ChunkProviderHell implements IChunkProvider { return parArrayOfDouble; } - /**+ - * Checks to see if a chunk exists at x, z + /** + * + Converts the instance data to a readable string. */ - public boolean chunkExists(int var1, int var2) { - return true; + public String makeString() { + return "HellRandomLevelSource"; } - /**+ - * Populates chunk with ores etc etc + /** + * + Populates chunk with ores etc etc */ public void populate(IChunkProvider var1, int i, int j) { BlockFalling.fallInstantly = true; @@ -394,10 +412,10 @@ public class ChunkProviderHell implements IChunkProvider { this.hellRNG.nextInt(128), this.hellRNG.nextInt(16) + 8)); } - for (int k1 = 0; k1 < 8; ++k1) { - this.uraniumOreGen.generate(this.worldObj, this.hellRNG, blockpos.add(this.hellRNG.nextInt(16), - this.hellRNG.nextInt(108) + 10, this.hellRNG.nextInt(16))); - } + for (int k1 = 0; k1 < 8; ++k1) { + this.uraniumOreGen.generate(this.worldObj, this.hellRNG, + blockpos.add(this.hellRNG.nextInt(16), this.hellRNG.nextInt(108) + 10, this.hellRNG.nextInt(16))); + } for (int k1 = 0; k1 < 16; ++k1) { this.field_177467_w.generate(this.worldObj, this.hellRNG, @@ -412,84 +430,68 @@ public class ChunkProviderHell implements IChunkProvider { BlockFalling.fallInstantly = false; } - public boolean func_177460_a(IChunkProvider var1, Chunk var2, int var3, int var4) { - return false; - } - - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ - public boolean saveChunks(boolean var1, IProgressUpdate var2) { - return true; + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); } - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed */ - public void saveExtraData() { - } - - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. - */ - public boolean unloadQueuedChunks() { - return false; - } - - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return true; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "HellRandomLevelSource"; - } - - public List getPossibleCreatures(EnumCreatureType enumcreaturetype, - BlockPos blockpos) { - if (enumcreaturetype == EnumCreatureType.MONSTER) { - if (this.genNetherBridge.func_175795_b(blockpos)) { - return this.genNetherBridge.getSpawnList(); - } - - if (this.genNetherBridge.func_175796_a(this.worldObj, blockpos) - && this.worldObj.getBlockState(blockpos.down()).getBlock() == Blocks.nether_brick) { - return this.genNetherBridge.getSpawnList(); - } + public Chunk provideChunk(int i, int j) { + this.hellRNG.setSeed((long) i * 341873128712L + (long) j * 132897987541L); + ChunkPrimer chunkprimer = new ChunkPrimer(); + this.func_180515_a(i, j, chunkprimer); + this.func_180516_b(i, j, chunkprimer); + this.netherCaveGenerator.generate(this, this.worldObj, i, j, chunkprimer); + if (this.field_177466_i) { + this.genNetherBridge.generate(this, this.worldObj, i, j, chunkprimer); } - BiomeGenBase biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); - return biomegenbase.getSpawnableList(enumcreaturetype); - } + Chunk chunk = new Chunk(this.worldObj, chunkprimer, i, j); + BiomeGenBase[] abiomegenbase = this.worldObj.getWorldChunkManager() + .loadBlockGeneratorData((BiomeGenBase[]) null, i * 16, j * 16, 16, 16); + byte[] abyte = chunk.getBiomeArray(); - public BlockPos getStrongholdGen(World var1, String var2, BlockPos var3) { - return null; - } + for (int k = 0; k < abyte.length; ++k) { + abyte[k] = (byte) abiomegenbase[k].biomeID; + } - public int getLoadedChunkCount() { - return 0; + chunk.resetRelightChecks(); + return chunk; } public void recreateStructures(Chunk var1, int i, int j) { this.genNetherBridge.generate(this, this.worldObj, i, j, (ChunkPrimer) null); } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + public boolean saveChunks(boolean var1, IProgressUpdate var2) { + return true; + } + + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. + */ + public void saveExtraData() { + } + + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. + */ + public boolean unloadQueuedChunks() { + return false; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderServer.java b/src/game/java/net/minecraft/world/gen/ChunkProviderServer.java index cea4041e..5132b7e9 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderServer.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderServer.java @@ -1,15 +1,20 @@ package net.minecraft.world.gen; -import com.google.common.collect.Lists; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; + +import com.google.common.collect.Lists; + +import net.lax1dude.eaglercraft.v1_8.HString; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; -import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; import net.minecraft.entity.EnumCreatureType; import net.minecraft.util.BlockPos; import net.minecraft.util.IProgressUpdate; @@ -24,26 +29,26 @@ import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.EmptyChunk; import net.minecraft.world.chunk.IChunkProvider; import net.minecraft.world.chunk.storage.IChunkLoader; -import net.lax1dude.eaglercraft.v1_8.HString; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,13 +59,13 @@ public class ChunkProviderServer implements IChunkProvider { private Chunk dummyChunk; private IChunkProvider serverChunkGenerator; private IChunkLoader chunkLoader; - /**+ - * if set, this flag forces a request to load a chunk to load - * the chunk rather than defaulting to the dummy if possible + /** + * + if set, this flag forces a request to load a chunk to load the chunk rather + * than defaulting to the dummy if possible */ public boolean chunkLoadOverride = true; - /**+ - * map of chunk Id's to Chunk instances + /** + * + map of chunk Id's to Chunk instances */ private LongHashMap id2ChunkMap = new LongHashMap(); private List loadedChunks = Lists.newLinkedList(); @@ -74,17 +79,20 @@ public class ChunkProviderServer implements IChunkProvider { this.serverChunkGenerator = parIChunkProvider; } - /**+ - * Checks to see if a chunk exists at x, z + /** + * + Returns if the IChunkProvider supports saving. + */ + public boolean canSave() { + return !this.worldObj.disableLevelSaving; + } + + /** + * + Checks to see if a chunk exists at x, z */ public boolean chunkExists(int i, int j) { return this.id2ChunkMap.containsItem(ChunkCoordIntPair.chunkXZ2Int(i, j)); } - public List func_152380_a() { - return this.loadedChunks; - } - public void dropChunk(int parInt1, int parInt2) { if (this.worldObj.provider.canRespawnHere()) { if (!this.worldObj.isSpawnChunk(parInt1, parInt2)) { @@ -96,18 +104,35 @@ public class ChunkProviderServer implements IChunkProvider { } - /**+ - * marks all chunks for unload, ignoring those near the spawn - */ - public void unloadAllChunks() { - for (Chunk chunk : this.loadedChunks) { - this.dropChunk(chunk.xPosition, chunk.zPosition); - } - + public List func_152380_a() { + return this.loadedChunks; } - /**+ - * loads or generates the chunk at the chunk location specified + public boolean func_177460_a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { + if (this.serverChunkGenerator != null && this.serverChunkGenerator.func_177460_a(ichunkprovider, chunk, i, j)) { + Chunk chunk1 = this.provideChunk(i, j); + chunk1.setChunkModified(); + return true; + } else { + return false; + } + } + + public int getLoadedChunkCount() { + return this.id2ChunkMap.getNumHashElements(); + } + + public List getPossibleCreatures(EnumCreatureType enumcreaturetype, + BlockPos blockpos) { + return this.serverChunkGenerator.getPossibleCreatures(enumcreaturetype, blockpos); + } + + public BlockPos getStrongholdGen(World world, String s, BlockPos blockpos) { + return this.serverChunkGenerator.getStrongholdGen(world, s, blockpos); + } + + /** + * + loads or generates the chunk at the chunk location specified */ public Chunk loadChunk(int i, int j) { long k = ChunkCoordIntPair.chunkXZ2Int(i, j); @@ -146,17 +171,6 @@ public class ChunkProviderServer implements IChunkProvider { return chunk; } - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(int i, int j) { - Chunk chunk = (Chunk) this.id2ChunkMap.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(i, j)); - return chunk == null ? (!this.worldObj.isFindingSpawnPoint() && !this.chunkLoadOverride ? this.dummyChunk - : this.loadChunk(i, j)) : chunk; - } - private Chunk loadChunkFromFile(int x, int z) { if (this.chunkLoader == null) { return null; @@ -179,16 +193,49 @@ public class ChunkProviderServer implements IChunkProvider { } } - private void saveChunkExtraData(Chunk parChunk) { - if (this.chunkLoader != null) { - try { - this.chunkLoader.saveExtraChunkData(this.worldObj, parChunk); - } catch (Exception exception) { - logger.error("Couldn\'t save entities"); - logger.error(exception); - } + /** + * + Converts the instance data to a readable string. + */ + public String makeString() { + return "ServerChunkCache: " + this.id2ChunkMap.getNumHashElements() + " Drop: " + this.droppedChunksSet.size(); + } + /** + * + Populates chunk with ores etc etc + */ + public void populate(IChunkProvider ichunkprovider, int i, int j) { + Chunk chunk = this.provideChunk(i, j); + if (!chunk.isTerrainPopulated()) { + chunk.func_150809_p(); + if (this.serverChunkGenerator != null) { + this.serverChunkGenerator.populate(ichunkprovider, i, j); + chunk.setChunkModified(); + } } + + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(BlockPos blockpos) { + return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); + } + + /** + * + Will return back a chunk, if it doesn't exist and its not a MP client it + * will generates all the blocks for the specified chunk from the map seed and + * chunk seed + */ + public Chunk provideChunk(int i, int j) { + Chunk chunk = (Chunk) this.id2ChunkMap.getValueByKey(ChunkCoordIntPair.chunkXZ2Int(i, j)); + return chunk == null ? (!this.worldObj.isFindingSpawnPoint() && !this.chunkLoadOverride ? this.dummyChunk + : this.loadChunk(i, j)) : chunk; + } + + public void recreateStructures(Chunk var1, int var2, int var3) { } private void saveChunkData(Chunk parChunk) { @@ -208,35 +255,22 @@ public class ChunkProviderServer implements IChunkProvider { } } - /**+ - * Populates chunk with ores etc etc - */ - public void populate(IChunkProvider ichunkprovider, int i, int j) { - Chunk chunk = this.provideChunk(i, j); - if (!chunk.isTerrainPopulated()) { - chunk.func_150809_p(); - if (this.serverChunkGenerator != null) { - this.serverChunkGenerator.populate(ichunkprovider, i, j); - chunk.setChunkModified(); + private void saveChunkExtraData(Chunk parChunk) { + if (this.chunkLoader != null) { + try { + this.chunkLoader.saveExtraChunkData(this.worldObj, parChunk); + } catch (Exception exception) { + logger.error("Couldn\'t save entities"); + logger.error(exception); } - } - } - - public boolean func_177460_a(IChunkProvider ichunkprovider, Chunk chunk, int i, int j) { - if (this.serverChunkGenerator != null && this.serverChunkGenerator.func_177460_a(ichunkprovider, chunk, i, j)) { - Chunk chunk1 = this.provideChunk(i, j); - chunk1.setChunkModified(); - return true; - } else { - return false; } } - /**+ - * Two modes of operation: if passed true, save all Chunks in - * one go. If passed false, save up to two chunks. Return true - * if all chunks have been saved. + /** + * + Two modes of operation: if passed true, save all Chunks in one go. If + * passed false, save up to two chunks. Return true if all chunks have been + * saved. */ public boolean saveChunks(boolean flag, IProgressUpdate var2) { int i = 0; @@ -261,10 +295,9 @@ public class ChunkProviderServer implements IChunkProvider { return true; } - /**+ - * Save extra data not associated with any Chunk. Not saved - * during autosave, only during world unload. Currently - * unimplemented. + /** + * + Save extra data not associated with any Chunk. Not saved during autosave, + * only during world unload. Currently unimplemented. */ public void saveExtraData() { if (this.chunkLoader != null) { @@ -273,9 +306,19 @@ public class ChunkProviderServer implements IChunkProvider { } - /**+ - * Unloads chunks that are marked to be unloaded. This is not - * guaranteed to unload every such chunk. + /** + * + marks all chunks for unload, ignoring those near the spawn + */ + public void unloadAllChunks() { + for (Chunk chunk : this.loadedChunks) { + this.dropChunk(chunk.xPosition, chunk.zPosition); + } + + } + + /** + * + Unloads chunks that are marked to be unloaded. This is not guaranteed to + * unload every such chunk. */ public boolean unloadQueuedChunks() { if (!this.worldObj.disableLevelSaving) { @@ -302,43 +345,4 @@ public class ChunkProviderServer implements IChunkProvider { return this.serverChunkGenerator.unloadQueuedChunks(); } - - /**+ - * Returns if the IChunkProvider supports saving. - */ - public boolean canSave() { - return !this.worldObj.disableLevelSaving; - } - - /**+ - * Converts the instance data to a readable string. - */ - public String makeString() { - return "ServerChunkCache: " + this.id2ChunkMap.getNumHashElements() + " Drop: " + this.droppedChunksSet.size(); - } - - public List getPossibleCreatures(EnumCreatureType enumcreaturetype, - BlockPos blockpos) { - return this.serverChunkGenerator.getPossibleCreatures(enumcreaturetype, blockpos); - } - - public BlockPos getStrongholdGen(World world, String s, BlockPos blockpos) { - return this.serverChunkGenerator.getStrongholdGen(world, s, blockpos); - } - - public int getLoadedChunkCount() { - return this.id2ChunkMap.getNumHashElements(); - } - - public void recreateStructures(Chunk var1, int var2, int var3) { - } - - /**+ - * Will return back a chunk, if it doesn't exist and its not a - * MP client it will generates all the blocks for the specified - * chunk from the map seed and chunk seed - */ - public Chunk provideChunk(BlockPos blockpos) { - return this.provideChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/ChunkProviderSettings.java b/src/game/java/net/minecraft/world/gen/ChunkProviderSettings.java index f7898551..211a9a96 100644 --- a/src/game/java/net/minecraft/world/gen/ChunkProviderSettings.java +++ b/src/game/java/net/minecraft/world/gen/ChunkProviderSettings.java @@ -7,195 +7,43 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeCodec; import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ChunkProviderSettings { - public final float coordinateScale; - public final float heightScale; - public final float upperLimitScale; - public final float lowerLimitScale; - public final float depthNoiseScaleX; - public final float depthNoiseScaleZ; - public final float depthNoiseScaleExponent; - public final float mainNoiseScaleX; - public final float mainNoiseScaleY; - public final float mainNoiseScaleZ; - public final float baseSize; - public final float stretchY; - public final float biomeDepthWeight; - public final float biomeDepthOffSet; - public final float biomeScaleWeight; - public final float biomeScaleOffset; - public final int seaLevel; - public final boolean useCaves; - public final boolean useDungeons; - public final int dungeonChance; - public final boolean useStrongholds; - public final boolean useVillages; - public final boolean useMineShafts; - public final boolean useTemples; - public final boolean useMonuments; - public final boolean useRavines; - public final boolean useWaterLakes; - public final int waterLakeChance; - public final boolean useLavaLakes; - public final int lavaLakeChance; - public final boolean useLavaOceans; - public final int fixedBiome; - public final int biomeSize; - public final int riverSize; - public final int dirtSize; - public final int dirtCount; - public final int dirtMinHeight; - public final int dirtMaxHeight; - public final int gravelSize; - public final int gravelCount; - public final int gravelMinHeight; - public final int gravelMaxHeight; - public final int graniteSize; - public final int graniteCount; - public final int graniteMinHeight; - public final int graniteMaxHeight; - public final int dioriteSize; - public final int dioriteCount; - public final int dioriteMinHeight; - public final int dioriteMaxHeight; - public final int andesiteSize; - public final int andesiteCount; - public final int andesiteMinHeight; - public final int andesiteMaxHeight; - public final int coalSize; - public final int coalCount; - public final int coalMinHeight; - public final int coalMaxHeight; - public final int ironSize; - public final int ironCount; - public final int ironMinHeight; - public final int ironMaxHeight; - public final int goldSize; - public final int goldCount; - public final int goldMinHeight; - public final int goldMaxHeight; - public final int redstoneSize; - public final int redstoneCount; - public final int redstoneMinHeight; - public final int redstoneMaxHeight; - public final int diamondSize; - public final int diamondCount; - public final int diamondMinHeight; - public final int diamondMaxHeight; - public final int lapisSize; - public final int lapisCount; - public final int lapisCenterHeight; - public final int lapisSpread; - public final int platinumSize; - public final int platinumCount; - public final int platinumMinHeight; - public final int platinumMaxHeight; - private ChunkProviderSettings(ChunkProviderSettings.Factory settingsFactory) { - this.coordinateScale = settingsFactory.coordinateScale; - this.heightScale = settingsFactory.heightScale; - this.upperLimitScale = settingsFactory.upperLimitScale; - this.lowerLimitScale = settingsFactory.lowerLimitScale; - this.depthNoiseScaleX = settingsFactory.depthNoiseScaleX; - this.depthNoiseScaleZ = settingsFactory.depthNoiseScaleZ; - this.depthNoiseScaleExponent = settingsFactory.depthNoiseScaleExponent; - this.mainNoiseScaleX = settingsFactory.mainNoiseScaleX; - this.mainNoiseScaleY = settingsFactory.mainNoiseScaleY; - this.mainNoiseScaleZ = settingsFactory.mainNoiseScaleZ; - this.baseSize = settingsFactory.baseSize; - this.stretchY = settingsFactory.stretchY; - this.biomeDepthWeight = settingsFactory.biomeDepthWeight; - this.biomeDepthOffSet = settingsFactory.biomeDepthOffset; - this.biomeScaleWeight = settingsFactory.biomeScaleWeight; - this.biomeScaleOffset = settingsFactory.biomeScaleOffset; - this.seaLevel = settingsFactory.seaLevel; - this.useCaves = settingsFactory.useCaves; - this.useDungeons = settingsFactory.useDungeons; - this.dungeonChance = settingsFactory.dungeonChance; - this.useStrongholds = settingsFactory.useStrongholds; - this.useVillages = settingsFactory.useVillages; - this.useMineShafts = settingsFactory.useMineShafts; - this.useTemples = settingsFactory.useTemples; - this.useMonuments = settingsFactory.useMonuments; - this.useRavines = settingsFactory.useRavines; - this.useWaterLakes = settingsFactory.useWaterLakes; - this.waterLakeChance = settingsFactory.waterLakeChance; - this.useLavaLakes = settingsFactory.useLavaLakes; - this.lavaLakeChance = settingsFactory.lavaLakeChance; - this.useLavaOceans = settingsFactory.useLavaOceans; - this.fixedBiome = settingsFactory.fixedBiome; - this.biomeSize = settingsFactory.biomeSize; - this.riverSize = settingsFactory.riverSize; - this.dirtSize = settingsFactory.dirtSize; - this.dirtCount = settingsFactory.dirtCount; - this.dirtMinHeight = settingsFactory.dirtMinHeight; - this.dirtMaxHeight = settingsFactory.dirtMaxHeight; - this.gravelSize = settingsFactory.gravelSize; - this.gravelCount = settingsFactory.gravelCount; - this.gravelMinHeight = settingsFactory.gravelMinHeight; - this.gravelMaxHeight = settingsFactory.gravelMaxHeight; - this.graniteSize = settingsFactory.graniteSize; - this.graniteCount = settingsFactory.graniteCount; - this.graniteMinHeight = settingsFactory.graniteMinHeight; - this.graniteMaxHeight = settingsFactory.graniteMaxHeight; - this.dioriteSize = settingsFactory.dioriteSize; - this.dioriteCount = settingsFactory.dioriteCount; - this.dioriteMinHeight = settingsFactory.dioriteMinHeight; - this.dioriteMaxHeight = settingsFactory.dioriteMaxHeight; - this.andesiteSize = settingsFactory.andesiteSize; - this.andesiteCount = settingsFactory.andesiteCount; - this.andesiteMinHeight = settingsFactory.andesiteMinHeight; - this.andesiteMaxHeight = settingsFactory.andesiteMaxHeight; - this.coalSize = settingsFactory.coalSize; - this.coalCount = settingsFactory.coalCount; - this.coalMinHeight = settingsFactory.coalMinHeight; - this.coalMaxHeight = settingsFactory.coalMaxHeight; - this.ironSize = settingsFactory.ironSize; - this.ironCount = settingsFactory.ironCount; - this.ironMinHeight = settingsFactory.ironMinHeight; - this.ironMaxHeight = settingsFactory.ironMaxHeight; - this.goldSize = settingsFactory.goldSize; - this.goldCount = settingsFactory.goldCount; - this.goldMinHeight = settingsFactory.goldMinHeight; - this.goldMaxHeight = settingsFactory.goldMaxHeight; - this.redstoneSize = settingsFactory.redstoneSize; - this.redstoneCount = settingsFactory.redstoneCount; - this.redstoneMinHeight = settingsFactory.redstoneMinHeight; - this.redstoneMaxHeight = settingsFactory.redstoneMaxHeight; - this.diamondSize = settingsFactory.diamondSize; - this.diamondCount = settingsFactory.diamondCount; - this.diamondMinHeight = settingsFactory.diamondMinHeight; - this.diamondMaxHeight = settingsFactory.diamondMaxHeight; - this.lapisSize = settingsFactory.lapisSize; - this.lapisCount = settingsFactory.lapisCount; - this.lapisCenterHeight = settingsFactory.lapisCenterHeight; - this.lapisSpread = settingsFactory.lapisSpread; - this.platinumSize = settingsFactory.platinumSize; - this.platinumCount = settingsFactory.platinumCount; - this.platinumMinHeight = settingsFactory.platinumMinHeight; - this.platinumMaxHeight = settingsFactory.platinumMaxHeight; - } - public static class Factory { + public static ChunkProviderSettings.Factory jsonToFactory(String parString1) { + if (parString1.length() == 0) { + return new ChunkProviderSettings.Factory(); + } else { + try { + return JSONTypeProvider.deserialize(parString1, ChunkProviderSettings.Factory.class); + } catch (Exception var2) { + return new ChunkProviderSettings.Factory(); + } + } + } + public float coordinateScale = 684.412F; public float heightScale = 684.412F; public float upperLimitScale = 512.0F; @@ -256,8 +104,8 @@ public class ChunkProviderSettings { public int coalMaxHeight = 128; public int ironSize = 9; public int ironCount = 20; - public int ironMinHeight = 0; - public int ironMaxHeight = 64; + public int ironMinHeight = 30; + public int ironMaxHeight = 128; public int goldSize = 9; public int goldCount = 2; public int goldMinHeight = 0; @@ -265,7 +113,7 @@ public class ChunkProviderSettings { public int redstoneSize = 8; public int redstoneCount = 8; public int redstoneMinHeight = 0; - public int redstoneMaxHeight = 16; + public int redstoneMaxHeight = 32; public int diamondSize = 8; public int diamondCount = 1; public int diamondMinHeight = 0; @@ -274,115 +122,19 @@ public class ChunkProviderSettings { public int lapisCount = 1; public int lapisCenterHeight = 16; public int lapisSpread = 16; - public int platinumSize = 3; - public int platinumCount = 1; + public int platinumSize = 4; + public int platinumCount = 3; public int platinumMinHeight = 0; - public int platinumMaxHeight = 10; - public static ChunkProviderSettings.Factory jsonToFactory(String parString1) { - if (parString1.length() == 0) { - return new ChunkProviderSettings.Factory(); - } else { - try { - return JSONTypeProvider.deserialize(parString1, ChunkProviderSettings.Factory.class); - } catch (Exception var2) { - return new ChunkProviderSettings.Factory(); - } - } - } - - public String toString() { - return JSONTypeProvider.serialize(this).toString(); - } + public int platinumMaxHeight = 17; + public int titaniumSize = 2; + public int titaniumCount = 1; + public int titaniumMinHeight = 0; + public int titaniumMaxHeight = 10; public Factory() { this.func_177863_a(); } - public void func_177863_a() { - this.coordinateScale = 684.412F; - this.heightScale = 684.412F; - this.upperLimitScale = 512.0F; - this.lowerLimitScale = 512.0F; - this.depthNoiseScaleX = 200.0F; - this.depthNoiseScaleZ = 200.0F; - this.depthNoiseScaleExponent = 0.5F; - this.mainNoiseScaleX = 80.0F; - this.mainNoiseScaleY = 160.0F; - this.mainNoiseScaleZ = 80.0F; - this.baseSize = 8.5F; - this.stretchY = 12.0F; - this.biomeDepthWeight = 1.0F; - this.biomeDepthOffset = 0.0F; - this.biomeScaleWeight = 1.0F; - this.biomeScaleOffset = 0.0F; - this.seaLevel = 63; - this.useCaves = true; - this.useDungeons = true; - this.dungeonChance = 8; - this.useStrongholds = true; - this.useVillages = true; - this.useMineShafts = true; - this.useTemples = true; - this.useMonuments = true; - this.useRavines = true; - this.useWaterLakes = true; - this.waterLakeChance = 4; - this.useLavaLakes = true; - this.lavaLakeChance = 80; - this.useLavaOceans = false; - this.fixedBiome = -1; - this.biomeSize = 4; - this.riverSize = 4; - this.dirtSize = 33; - this.dirtCount = 10; - this.dirtMinHeight = 0; - this.dirtMaxHeight = 256; - this.gravelSize = 33; - this.gravelCount = 8; - this.gravelMinHeight = 0; - this.gravelMaxHeight = 256; - this.graniteSize = 33; - this.graniteCount = 10; - this.graniteMinHeight = 0; - this.graniteMaxHeight = 80; - this.dioriteSize = 33; - this.dioriteCount = 10; - this.dioriteMinHeight = 0; - this.dioriteMaxHeight = 80; - this.andesiteSize = 33; - this.andesiteCount = 10; - this.andesiteMinHeight = 0; - this.andesiteMaxHeight = 80; - this.coalSize = 17; - this.coalCount = 20; - this.coalMinHeight = 0; - this.coalMaxHeight = 128; - this.ironSize = 9; - this.ironCount = 20; - this.ironMinHeight = 0; - this.ironMaxHeight = 64; - this.goldSize = 9; - this.goldCount = 2; - this.goldMinHeight = 0; - this.goldMaxHeight = 32; - this.redstoneSize = 8; - this.redstoneCount = 8; - this.redstoneMinHeight = 0; - this.redstoneMaxHeight = 16; - this.diamondSize = 8; - this.diamondCount = 1; - this.diamondMinHeight = 0; - this.diamondMaxHeight = 16; - this.lapisSize = 7; - this.lapisCount = 1; - this.lapisCenterHeight = 16; - this.lapisSpread = 16; - this.platinumSize = 3; - this.platinumCount = 1; - this.platinumMinHeight = 0; - this.platinumMaxHeight = 10; - } - public boolean equals(Object object) { if (this == object) { return true; @@ -573,6 +325,99 @@ public class ChunkProviderSettings { } } + public void func_177863_a() { + this.coordinateScale = 684.412F; + this.heightScale = 684.412F; + this.upperLimitScale = 512.0F; + this.lowerLimitScale = 512.0F; + this.depthNoiseScaleX = 200.0F; + this.depthNoiseScaleZ = 200.0F; + this.depthNoiseScaleExponent = 0.5F; + this.mainNoiseScaleX = 80.0F; + this.mainNoiseScaleY = 160.0F; + this.mainNoiseScaleZ = 80.0F; + this.baseSize = 8.5F; + this.stretchY = 12.0F; + this.biomeDepthWeight = 1.0F; + this.biomeDepthOffset = 0.0F; + this.biomeScaleWeight = 1.0F; + this.biomeScaleOffset = 0.0F; + this.seaLevel = 63; + this.useCaves = true; + this.useDungeons = true; + this.dungeonChance = 8; + this.useStrongholds = true; + this.useVillages = true; + this.useMineShafts = true; + this.useTemples = true; + this.useMonuments = true; + this.useRavines = true; + this.useWaterLakes = true; + this.waterLakeChance = 4; + this.useLavaLakes = true; + this.lavaLakeChance = 80; + this.useLavaOceans = false; + this.fixedBiome = -1; + this.biomeSize = 4; + this.riverSize = 4; + this.dirtSize = 33; + this.dirtCount = 10; + this.dirtMinHeight = 0; + this.dirtMaxHeight = 256; + this.gravelSize = 33; + this.gravelCount = 8; + this.gravelMinHeight = 0; + this.gravelMaxHeight = 256; + this.graniteSize = 33; + this.graniteCount = 10; + this.graniteMinHeight = 0; + this.graniteMaxHeight = 80; + this.dioriteSize = 33; + this.dioriteCount = 10; + this.dioriteMinHeight = 0; + this.dioriteMaxHeight = 80; + this.andesiteSize = 33; + this.andesiteCount = 10; + this.andesiteMinHeight = 0; + this.andesiteMaxHeight = 80; + this.coalSize = 17; + this.coalCount = 20; + this.coalMinHeight = 0; + this.coalMaxHeight = 128; + this.ironSize = 9; + this.ironCount = 20; + this.ironMinHeight = 30; + this.ironMaxHeight = 128; + this.goldSize = 9; + this.goldCount = 2; + this.goldMinHeight = 0; + this.goldMaxHeight = 32; + this.redstoneSize = 8; + this.redstoneCount = 8; + this.redstoneMinHeight = 0; + this.redstoneMaxHeight = 32; + this.diamondSize = 8; + this.diamondCount = 1; + this.diamondMinHeight = 0; + this.diamondMaxHeight = 16; + this.lapisSize = 7; + this.lapisCount = 1; + this.lapisCenterHeight = 16; + this.lapisSpread = 16; + this.platinumSize = 4; + this.platinumCount = 8; + this.platinumMinHeight = 0; + this.platinumMaxHeight = 17; + this.titaniumSize = 2; + this.titaniumCount = 4; + this.titaniumMinHeight = 0; + this.titaniumMaxHeight = 10; + } + + public ChunkProviderSettings func_177864_b() { + return new ChunkProviderSettings(this); + } + public int hashCode() { int i = this.coordinateScale != 0.0F ? Float.floatToIntBits(this.coordinateScale) : 0; i = 31 * i + (this.heightScale != 0.0F ? Float.floatToIntBits(this.heightScale) : 0); @@ -656,8 +501,8 @@ public class ChunkProviderSettings { return i; } - public ChunkProviderSettings func_177864_b() { - return new ChunkProviderSettings(this); + public String toString() { + return JSONTypeProvider.serialize(this).toString(); } } @@ -917,11 +762,191 @@ public class ChunkProviderSettings { jsonobject.put("lapisCount", Integer.valueOf(parFactory.lapisCount)); jsonobject.put("lapisCenterHeight", Integer.valueOf(parFactory.lapisCenterHeight)); jsonobject.put("lapisSpread", Integer.valueOf(parFactory.lapisSpread)); - jsonobject.put("diamondSize", Integer.valueOf(parFactory.platinumSize)); + jsonobject.put("platinumSize", Integer.valueOf(parFactory.platinumSize)); jsonobject.put("platinumCount", Integer.valueOf(parFactory.platinumCount)); jsonobject.put("platinumMinHeight", Integer.valueOf(parFactory.platinumMinHeight)); jsonobject.put("platinumMaxHeight", Integer.valueOf(parFactory.platinumMaxHeight)); + jsonobject.put("titaniumSize", Integer.valueOf(parFactory.titaniumSize)); + jsonobject.put("titaniumCount", Integer.valueOf(parFactory.titaniumCount)); + jsonobject.put("titaniumMinHeight", Integer.valueOf(parFactory.titaniumMinHeight)); + jsonobject.put("titaniumMaxHeight", Integer.valueOf(parFactory.titaniumMaxHeight)); return jsonobject; } } + + public final float coordinateScale; + public final float heightScale; + public final float upperLimitScale; + public final float lowerLimitScale; + public final float depthNoiseScaleX; + public final float depthNoiseScaleZ; + public final float depthNoiseScaleExponent; + public final float mainNoiseScaleX; + public final float mainNoiseScaleY; + public final float mainNoiseScaleZ; + public final float baseSize; + public final float stretchY; + public final float biomeDepthWeight; + public final float biomeDepthOffSet; + public final float biomeScaleWeight; + public final float biomeScaleOffset; + public final int seaLevel; + public final boolean useCaves; + public final boolean useDungeons; + public final int dungeonChance; + public final boolean useStrongholds; + public final boolean useVillages; + public final boolean useMineShafts; + public final boolean useTemples; + public final boolean useMonuments; + public final boolean useRavines; + public final boolean useWaterLakes; + public final int waterLakeChance; + public final boolean useLavaLakes; + public final int lavaLakeChance; + public final boolean useLavaOceans; + public final int fixedBiome; + public final int biomeSize; + public final int riverSize; + public final int dirtSize; + public final int dirtCount; + public final int dirtMinHeight; + public final int dirtMaxHeight; + public final int gravelSize; + public final int gravelCount; + public final int gravelMinHeight; + public final int gravelMaxHeight; + public final int graniteSize; + public final int graniteCount; + public final int graniteMinHeight; + public final int graniteMaxHeight; + public final int dioriteSize; + public final int dioriteCount; + public final int dioriteMinHeight; + public final int dioriteMaxHeight; + public final int andesiteSize; + public final int andesiteCount; + public final int andesiteMinHeight; + public final int andesiteMaxHeight; + public final int coalSize; + public final int coalCount; + public final int coalMinHeight; + public final int coalMaxHeight; + public final int ironSize; + public final int ironCount; + public final int ironMinHeight; + public final int ironMaxHeight; + public final int goldSize; + public final int goldCount; + public final int goldMinHeight; + public final int goldMaxHeight; + public final int redstoneSize; + public final int redstoneCount; + public final int redstoneMinHeight; + public final int redstoneMaxHeight; + public final int diamondSize; + public final int diamondCount; + public final int diamondMinHeight; + public final int diamondMaxHeight; + public final int lapisSize; + public final int lapisCount; + public final int lapisCenterHeight; + public final int lapisSpread; + public final int platinumSize; + public final int platinumCount; + public final int platinumMinHeight; + public final int platinumMaxHeight; + public final int titaniumSize; + public final int titaniumCount; + public final int titaniumMinHeight; + public final int titaniumMaxHeight; + + private ChunkProviderSettings(ChunkProviderSettings.Factory settingsFactory) { + this.coordinateScale = settingsFactory.coordinateScale; + this.heightScale = settingsFactory.heightScale; + this.upperLimitScale = settingsFactory.upperLimitScale; + this.lowerLimitScale = settingsFactory.lowerLimitScale; + this.depthNoiseScaleX = settingsFactory.depthNoiseScaleX; + this.depthNoiseScaleZ = settingsFactory.depthNoiseScaleZ; + this.depthNoiseScaleExponent = settingsFactory.depthNoiseScaleExponent; + this.mainNoiseScaleX = settingsFactory.mainNoiseScaleX; + this.mainNoiseScaleY = settingsFactory.mainNoiseScaleY; + this.mainNoiseScaleZ = settingsFactory.mainNoiseScaleZ; + this.baseSize = settingsFactory.baseSize; + this.stretchY = settingsFactory.stretchY; + this.biomeDepthWeight = settingsFactory.biomeDepthWeight; + this.biomeDepthOffSet = settingsFactory.biomeDepthOffset; + this.biomeScaleWeight = settingsFactory.biomeScaleWeight; + this.biomeScaleOffset = settingsFactory.biomeScaleOffset; + this.seaLevel = settingsFactory.seaLevel; + this.useCaves = settingsFactory.useCaves; + this.useDungeons = settingsFactory.useDungeons; + this.dungeonChance = settingsFactory.dungeonChance; + this.useStrongholds = settingsFactory.useStrongholds; + this.useVillages = settingsFactory.useVillages; + this.useMineShafts = settingsFactory.useMineShafts; + this.useTemples = settingsFactory.useTemples; + this.useMonuments = settingsFactory.useMonuments; + this.useRavines = settingsFactory.useRavines; + this.useWaterLakes = settingsFactory.useWaterLakes; + this.waterLakeChance = settingsFactory.waterLakeChance; + this.useLavaLakes = settingsFactory.useLavaLakes; + this.lavaLakeChance = settingsFactory.lavaLakeChance; + this.useLavaOceans = settingsFactory.useLavaOceans; + this.fixedBiome = settingsFactory.fixedBiome; + this.biomeSize = settingsFactory.biomeSize; + this.riverSize = settingsFactory.riverSize; + this.dirtSize = settingsFactory.dirtSize; + this.dirtCount = settingsFactory.dirtCount; + this.dirtMinHeight = settingsFactory.dirtMinHeight; + this.dirtMaxHeight = settingsFactory.dirtMaxHeight; + this.gravelSize = settingsFactory.gravelSize; + this.gravelCount = settingsFactory.gravelCount; + this.gravelMinHeight = settingsFactory.gravelMinHeight; + this.gravelMaxHeight = settingsFactory.gravelMaxHeight; + this.graniteSize = settingsFactory.graniteSize; + this.graniteCount = settingsFactory.graniteCount; + this.graniteMinHeight = settingsFactory.graniteMinHeight; + this.graniteMaxHeight = settingsFactory.graniteMaxHeight; + this.dioriteSize = settingsFactory.dioriteSize; + this.dioriteCount = settingsFactory.dioriteCount; + this.dioriteMinHeight = settingsFactory.dioriteMinHeight; + this.dioriteMaxHeight = settingsFactory.dioriteMaxHeight; + this.andesiteSize = settingsFactory.andesiteSize; + this.andesiteCount = settingsFactory.andesiteCount; + this.andesiteMinHeight = settingsFactory.andesiteMinHeight; + this.andesiteMaxHeight = settingsFactory.andesiteMaxHeight; + this.coalSize = settingsFactory.coalSize; + this.coalCount = settingsFactory.coalCount; + this.coalMinHeight = settingsFactory.coalMinHeight; + this.coalMaxHeight = settingsFactory.coalMaxHeight; + this.ironSize = settingsFactory.ironSize; + this.ironCount = settingsFactory.ironCount; + this.ironMinHeight = settingsFactory.ironMinHeight; + this.ironMaxHeight = settingsFactory.ironMaxHeight; + this.goldSize = settingsFactory.goldSize; + this.goldCount = settingsFactory.goldCount; + this.goldMinHeight = settingsFactory.goldMinHeight; + this.goldMaxHeight = settingsFactory.goldMaxHeight; + this.redstoneSize = settingsFactory.redstoneSize; + this.redstoneCount = settingsFactory.redstoneCount; + this.redstoneMinHeight = settingsFactory.redstoneMinHeight; + this.redstoneMaxHeight = settingsFactory.redstoneMaxHeight; + this.diamondSize = settingsFactory.diamondSize; + this.diamondCount = settingsFactory.diamondCount; + this.diamondMinHeight = settingsFactory.diamondMinHeight; + this.diamondMaxHeight = settingsFactory.diamondMaxHeight; + this.lapisSize = settingsFactory.lapisSize; + this.lapisCount = settingsFactory.lapisCount; + this.lapisCenterHeight = settingsFactory.lapisCenterHeight; + this.lapisSpread = settingsFactory.lapisSpread; + this.platinumSize = settingsFactory.platinumSize; + this.platinumCount = settingsFactory.platinumCount; + this.platinumMinHeight = settingsFactory.platinumMinHeight; + this.platinumMaxHeight = settingsFactory.platinumMaxHeight; + this.titaniumSize = settingsFactory.titaniumSize; + this.titaniumCount = settingsFactory.titaniumCount; + this.titaniumMinHeight = settingsFactory.titaniumMinHeight; + this.titaniumMaxHeight = settingsFactory.titaniumMaxHeight; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/FlatGeneratorInfo.java b/src/game/java/net/minecraft/world/gen/FlatGeneratorInfo.java index 6b473983..90a4570f 100644 --- a/src/game/java/net/minecraft/world/gen/FlatGeneratorInfo.java +++ b/src/game/java/net/minecraft/world/gen/FlatGeneratorInfo.java @@ -15,118 +15,81 @@ import net.minecraft.init.Blocks; import net.minecraft.util.MathHelper; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FlatGeneratorInfo { - /**+ - * List of layers on this preset. - */ - private final List flatLayers = Lists.newArrayList(); - private final Map> worldFeatures = Maps.newHashMap(); - private int biomeToUse; - - /**+ - * Return the biome used on this preset. - */ - public int getBiome() { - return this.biomeToUse; - } - - /**+ - * Set the biome used on this preset. - */ - public void setBiome(int parInt1) { - this.biomeToUse = parInt1; - } - - public Map> getWorldFeatures() { - return this.worldFeatures; - } - - /**+ - * Return the list of layers on this preset. - */ - public List getFlatLayers() { - return this.flatLayers; - } - - public void func_82645_d() { - int i = 0; - - for (int j = 0, l = this.flatLayers.size(); j < l; ++j) { - FlatLayerInfo flatlayerinfo = this.flatLayers.get(j); - flatlayerinfo.setMinY(i); - i += flatlayerinfo.getLayerCount(); - } - - } - - public String toString() { - StringBuilder stringbuilder = new StringBuilder(); - stringbuilder.append(3); - stringbuilder.append(";"); - - for (int i = 0; i < this.flatLayers.size(); ++i) { - if (i > 0) { - stringbuilder.append(","); - } - - stringbuilder.append(((FlatLayerInfo) this.flatLayers.get(i)).toString()); - } - - stringbuilder.append(";"); - stringbuilder.append(this.biomeToUse); - if (!this.worldFeatures.isEmpty()) { - stringbuilder.append(";"); - int k = 0; - - for (Entry entry : this.worldFeatures.entrySet()) { - if (k++ > 0) { - stringbuilder.append(","); - } - - stringbuilder.append(((String) entry.getKey()).toLowerCase()); - Map map = (Map) entry.getValue(); - if (!map.isEmpty()) { - stringbuilder.append("("); - int j = 0; - - for (Entry entry1 : (Set) map.entrySet()) { - if (j++ > 0) { - stringbuilder.append(" "); - } - - stringbuilder.append((String) entry1.getKey()); - stringbuilder.append("="); - stringbuilder.append((String) entry1.getValue()); + public static FlatGeneratorInfo createFlatGeneratorFromString(String parString1) { + if (parString1 == null) { + return getDefaultFlatGenerator(); + } else { + String[] astring = parString1.split(";", -1); + int i = astring.length == 1 ? 0 : MathHelper.parseIntWithDefault(astring[0], 0); + if (i >= 0 && i <= 3) { + FlatGeneratorInfo flatgeneratorinfo = new FlatGeneratorInfo(); + int j = astring.length == 1 ? 0 : 1; + List list = func_180716_a(i, astring[j++]); + if (list != null && !list.isEmpty()) { + flatgeneratorinfo.getFlatLayers().addAll(list); + flatgeneratorinfo.func_82645_d(); + int k = BiomeGenBase.plains.biomeID; + if (i > 0 && astring.length > j) { + k = MathHelper.parseIntWithDefault(astring[j++], k); } - stringbuilder.append(")"); - } - } - } else { - stringbuilder.append(";"); - } + flatgeneratorinfo.setBiome(k); + if (i > 0 && astring.length > j) { + String[] astring1 = astring[j++].toLowerCase().split(","); - return stringbuilder.toString(); + for (int m = 0; m < astring1.length; ++m) { + String[] astring2 = astring1[m].split("\\(", 2); + HashMap hashmap = Maps.newHashMap(); + if (astring2[0].length() > 0) { + flatgeneratorinfo.getWorldFeatures().put(astring2[0], hashmap); + if (astring2.length > 1 && astring2[1].endsWith(")") && astring2[1].length() > 1) { + String[] astring3 = astring2[1].substring(0, astring2[1].length() - 1).split(" "); + + for (int l = 0; l < astring3.length; ++l) { + String[] astring4 = astring3[l].split("=", 2); + if (astring4.length == 2) { + hashmap.put(astring4[0], astring4[1]); + } + } + } + } + } + } else { + flatgeneratorinfo.getWorldFeatures().put("village", Maps.newHashMap()); + } + + return flatgeneratorinfo; + } else { + return getDefaultFlatGenerator(); + } + } else { + return getDefaultFlatGenerator(); + } + } } private static FlatLayerInfo func_180715_a(int parInt1, String parString1, int parInt2) { @@ -214,59 +177,6 @@ public class FlatGeneratorInfo { } } - public static FlatGeneratorInfo createFlatGeneratorFromString(String parString1) { - if (parString1 == null) { - return getDefaultFlatGenerator(); - } else { - String[] astring = parString1.split(";", -1); - int i = astring.length == 1 ? 0 : MathHelper.parseIntWithDefault(astring[0], 0); - if (i >= 0 && i <= 3) { - FlatGeneratorInfo flatgeneratorinfo = new FlatGeneratorInfo(); - int j = astring.length == 1 ? 0 : 1; - List list = func_180716_a(i, astring[j++]); - if (list != null && !list.isEmpty()) { - flatgeneratorinfo.getFlatLayers().addAll(list); - flatgeneratorinfo.func_82645_d(); - int k = BiomeGenBase.plains.biomeID; - if (i > 0 && astring.length > j) { - k = MathHelper.parseIntWithDefault(astring[j++], k); - } - - flatgeneratorinfo.setBiome(k); - if (i > 0 && astring.length > j) { - String[] astring1 = astring[j++].toLowerCase().split(","); - - for (int m = 0; m < astring1.length; ++m) { - String[] astring2 = astring1[m].split("\\(", 2); - HashMap hashmap = Maps.newHashMap(); - if (astring2[0].length() > 0) { - flatgeneratorinfo.getWorldFeatures().put(astring2[0], hashmap); - if (astring2.length > 1 && astring2[1].endsWith(")") && astring2[1].length() > 1) { - String[] astring3 = astring2[1].substring(0, astring2[1].length() - 1).split(" "); - - for (int l = 0; l < astring3.length; ++l) { - String[] astring4 = astring3[l].split("=", 2); - if (astring4.length == 2) { - hashmap.put(astring4[0], astring4[1]); - } - } - } - } - } - } else { - flatgeneratorinfo.getWorldFeatures().put("village", Maps.newHashMap()); - } - - return flatgeneratorinfo; - } else { - return getDefaultFlatGenerator(); - } - } else { - return getDefaultFlatGenerator(); - } - } - } - public static FlatGeneratorInfo getDefaultFlatGenerator() { FlatGeneratorInfo flatgeneratorinfo = new FlatGeneratorInfo(); flatgeneratorinfo.setBiome(BiomeGenBase.plains.biomeID); @@ -277,4 +187,99 @@ public class FlatGeneratorInfo { flatgeneratorinfo.getWorldFeatures().put("village", Maps.newHashMap()); return flatgeneratorinfo; } + + /** + * + List of layers on this preset. + */ + private final List flatLayers = Lists.newArrayList(); + + private final Map> worldFeatures = Maps.newHashMap(); + + private int biomeToUse; + + public void func_82645_d() { + int i = 0; + + for (int j = 0, l = this.flatLayers.size(); j < l; ++j) { + FlatLayerInfo flatlayerinfo = this.flatLayers.get(j); + flatlayerinfo.setMinY(i); + i += flatlayerinfo.getLayerCount(); + } + + } + + /** + * + Return the biome used on this preset. + */ + public int getBiome() { + return this.biomeToUse; + } + + /** + * + Return the list of layers on this preset. + */ + public List getFlatLayers() { + return this.flatLayers; + } + + public Map> getWorldFeatures() { + return this.worldFeatures; + } + + /** + * + Set the biome used on this preset. + */ + public void setBiome(int parInt1) { + this.biomeToUse = parInt1; + } + + public String toString() { + StringBuilder stringbuilder = new StringBuilder(); + stringbuilder.append(3); + stringbuilder.append(";"); + + for (int i = 0; i < this.flatLayers.size(); ++i) { + if (i > 0) { + stringbuilder.append(","); + } + + stringbuilder.append(((FlatLayerInfo) this.flatLayers.get(i)).toString()); + } + + stringbuilder.append(";"); + stringbuilder.append(this.biomeToUse); + if (!this.worldFeatures.isEmpty()) { + stringbuilder.append(";"); + int k = 0; + + for (Entry entry : this.worldFeatures.entrySet()) { + if (k++ > 0) { + stringbuilder.append(","); + } + + stringbuilder.append(((String) entry.getKey()).toLowerCase()); + Map map = (Map) entry.getValue(); + if (!map.isEmpty()) { + stringbuilder.append("("); + int j = 0; + + for (Entry entry1 : (Set) map.entrySet()) { + if (j++ > 0) { + stringbuilder.append(" "); + } + + stringbuilder.append((String) entry1.getKey()); + stringbuilder.append("="); + stringbuilder.append((String) entry1.getValue()); + } + + stringbuilder.append(")"); + } + } + } else { + stringbuilder.append(";"); + } + + return stringbuilder.toString(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/FlatLayerInfo.java b/src/game/java/net/minecraft/world/gen/FlatLayerInfo.java index fc812845..0023a3b1 100644 --- a/src/game/java/net/minecraft/world/gen/FlatLayerInfo.java +++ b/src/game/java/net/minecraft/world/gen/FlatLayerInfo.java @@ -4,22 +4,25 @@ import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.ResourceLocation; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,38 +49,37 @@ public class FlatLayerInfo { this.field_175901_b = parBlock.getStateFromMeta(parInt3); } - /**+ - * Return the amount of layers for this set of layers. - */ - public int getLayerCount() { - return this.layerCount; + private Block func_151536_b() { + return this.field_175901_b.getBlock(); } public IBlockState func_175900_c() { return this.field_175901_b; } - private Block func_151536_b() { - return this.field_175901_b.getBlock(); - } - - /**+ - * Return the block metadata used on this set of layers. + /** + * + Return the block metadata used on this set of layers. */ private int getFillBlockMeta() { return this.field_175901_b.getBlock().getMetaFromState(this.field_175901_b); } - /**+ - * Return the minimum Y coordinate for this layer, set during - * generation. + /** + * + Return the amount of layers for this set of layers. + */ + public int getLayerCount() { + return this.layerCount; + } + + /** + * + Return the minimum Y coordinate for this layer, set during generation. */ public int getMinY() { return this.layerMinimumY; } - /**+ - * Set the minimum Y coordinate for this layer. + /** + * + Set the minimum Y coordinate for this layer. */ public void setMinY(int parInt1) { this.layerMinimumY = parInt1; diff --git a/src/game/java/net/minecraft/world/gen/GeneratorBushFeature.java b/src/game/java/net/minecraft/world/gen/GeneratorBushFeature.java index d35b4900..b2447782 100644 --- a/src/game/java/net/minecraft/world/gen/GeneratorBushFeature.java +++ b/src/game/java/net/minecraft/world/gen/GeneratorBushFeature.java @@ -6,22 +6,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/MapGenBase.java b/src/game/java/net/minecraft/world/gen/MapGenBase.java index 1488da7a..a9dfef32 100644 --- a/src/game/java/net/minecraft/world/gen/MapGenBase.java +++ b/src/game/java/net/minecraft/world/gen/MapGenBase.java @@ -5,29 +5,32 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.chunk.IChunkProvider; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapGenBase { - /**+ - * The number of Chunks to gen-check in any given direction. + /** + * + The number of Chunks to gen-check in any given direction. */ protected int range = 8; protected EaglercraftRandom rand; @@ -59,8 +62,8 @@ public class MapGenBase { } - /**+ - * Recursively called by generate() + /** + * + Recursively called by generate() */ protected void recursiveGenerate(World var1, int var2, int var3, int var4, int var5, ChunkPrimer var6) { } diff --git a/src/game/java/net/minecraft/world/gen/MapGenCaves.java b/src/game/java/net/minecraft/world/gen/MapGenCaves.java index 9f14f5e0..d52931b8 100644 --- a/src/game/java/net/minecraft/world/gen/MapGenCaves.java +++ b/src/game/java/net/minecraft/world/gen/MapGenCaves.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen; import com.google.common.base.Objects; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockSand; import net.minecraft.block.material.Material; @@ -11,22 +12,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,10 +41,28 @@ public class MapGenCaves extends MapGenBase { super(scramble); } - protected void func_180703_a(long parLong1, int parInt1, int parInt2, ChunkPrimer parChunkPrimer, double parDouble1, - double parDouble2, double parDouble3) { - this.func_180702_a(parLong1, parInt1, parInt2, parChunkPrimer, parDouble1, parDouble2, parDouble3, - 1.0F + this.rand.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); + protected boolean func_175793_a(IBlockState parIBlockState, IBlockState parIBlockState2) { + return parIBlockState.getBlock() == Blocks.stone ? true + : (parIBlockState.getBlock() == Blocks.dirt ? true + : (parIBlockState.getBlock() == Blocks.deepstone ? true + : (parIBlockState.getBlock() == Blocks.grass ? true + : (parIBlockState.getBlock() == Blocks.hardened_clay ? true + : (parIBlockState.getBlock() == Blocks.stained_hardened_clay ? true + : (parIBlockState.getBlock() == Blocks.sandstone ? true + : (parIBlockState.getBlock() == Blocks.red_sandstone + ? true + : (parIBlockState.getBlock() == Blocks.mycelium + ? true + : (parIBlockState + .getBlock() == Blocks.snow_layer + ? true + : (parIBlockState + .getBlock() == Blocks.sand + || parIBlockState + .getBlock() == Blocks.gravel) + && parIBlockState2 + .getBlock() + .getMaterial() != Material.water))))))))); } protected void func_180702_a(long parLong1, int parInt1, int parInt2, ChunkPrimer parChunkPrimer, double parDouble1, @@ -65,11 +87,35 @@ public class MapGenCaves extends MapGenBase { int j = random.nextInt(parInt4 / 2) + parInt4 / 4; for (boolean flag = random.nextInt(6) == 0; parInt3 < parInt4; ++parInt3) { - double d2 = 1.5D - + (double) (MathHelper.sin((float) parInt3 * 3.1415927F / (float) parInt4) * parFloat1 * 1.0F); - double d3 = d2 * parDouble4; - float f2 = MathHelper.cos(parFloat3); - float f3 = MathHelper.sin(parFloat3); + EaglercraftRandom eaglerRand = new EaglercraftRandom(); + int rangeSelector = eaglerRand.nextInt(100); + double baseSize; + if (rangeSelector == 0) { + baseSize = 1.1D + (1.5D - 1.1D) * eaglerRand.nextDouble(); + } else if (rangeSelector == 1) { + baseSize = 1.1D + (1.3D - 1.1D) * eaglerRand.nextDouble(); + } else if (rangeSelector == 2) { + baseSize = 1.4D + (2.1D - 1.4D) * eaglerRand.nextDouble(); + + } else if (rangeSelector == 3) { + baseSize = 1.15D + (1.3D - 1.15D) * eaglerRand.nextDouble(); + } else { + baseSize = 0.3D + (1.3D - 0.3D) * eaglerRand.nextDouble(); + + } + + double d2 = baseSize + + MathHelper.sin(parInt3 * 3.1415927F / parInt4) * (parFloat1 + eaglerRand.nextFloat() * 2.0F); + double d3 = d2 * (parDouble4 * 2.0); + + float f2 = MathHelper.cos(parFloat3 * 0.3F); + + float f3 = MathHelper.sin(parFloat3 * 0.3F); + + if (parDouble2 > 50.0D) { + d2 = d2 * 1.5D; + } + parDouble1 += (double) (MathHelper.cos(parFloat2) * f2); parDouble2 += (double) f3; parDouble3 += (double) (MathHelper.sin(parFloat2) * f2); @@ -200,7 +246,7 @@ public class MapGenCaves extends MapGenBase { parChunkPrimer.setBlockState(j3, j2 - 1, i2, this.worldObj.getBiomeGenForCoords( blockpos$mutableblockpos).topBlock.getBlock() - .getDefaultState()); + .getDefaultState()); } } } @@ -220,29 +266,15 @@ public class MapGenCaves extends MapGenBase { } - protected boolean func_175793_a(IBlockState parIBlockState, IBlockState parIBlockState2) { - return parIBlockState.getBlock() == Blocks.stone ? true - : (parIBlockState.getBlock() == Blocks.dirt ? true - : (parIBlockState.getBlock() == Blocks.grass ? true - : (parIBlockState.getBlock() == Blocks.hardened_clay ? true - : (parIBlockState.getBlock() == Blocks.stained_hardened_clay ? true - : (parIBlockState.getBlock() == Blocks.sandstone ? true - : (parIBlockState.getBlock() == Blocks.red_sandstone ? true - : (parIBlockState.getBlock() == Blocks.mycelium ? true - : (parIBlockState - .getBlock() == Blocks.snow_layer - ? true - : (parIBlockState - .getBlock() == Blocks.sand - || parIBlockState - .getBlock() == Blocks.gravel) - && parIBlockState2 - .getBlock() - .getMaterial() != Material.water)))))))); + protected void func_180703_a(long parLong1, int parInt1, int parInt2, ChunkPrimer parChunkPrimer, double parDouble1, + double parDouble2, double parDouble3) { + + this.func_180702_a(parLong1, parInt1, parInt2, parChunkPrimer, parDouble1, parDouble2, parDouble3, + 2.0F + this.rand.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); } - /**+ - * Recursively called by generate() + /** + * + Recursively called by generate() */ protected void recursiveGenerate(World var1, int i, int j, int k, int l, ChunkPrimer chunkprimer) { int i1 = this.rand.nextInt(this.rand.nextInt(this.rand.nextInt(15) + 1) + 1); diff --git a/src/game/java/net/minecraft/world/gen/MapGenCavesHell.java b/src/game/java/net/minecraft/world/gen/MapGenCavesHell.java index 8bbe65b2..2e7c14cc 100644 --- a/src/game/java/net/minecraft/world/gen/MapGenCavesHell.java +++ b/src/game/java/net/minecraft/world/gen/MapGenCavesHell.java @@ -7,22 +7,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,12 +36,6 @@ public class MapGenCavesHell extends MapGenBase { super(scramble); } - protected void func_180705_a(long parLong1, int parInt1, int parInt2, ChunkPrimer parChunkPrimer, double parDouble1, - double parDouble2, double parDouble3) { - this.func_180704_a(parLong1, parInt1, parInt2, parChunkPrimer, parDouble1, parDouble2, parDouble3, - 1.0F + this.rand.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); - } - protected void func_180704_a(long parLong1, int parInt1, int parInt2, ChunkPrimer parChunkPrimer, double parDouble1, double parDouble2, double parDouble3, float parFloat1, float parFloat2, float parFloat3, int parInt3, int parInt4, double parDouble4) { @@ -183,8 +180,14 @@ public class MapGenCavesHell extends MapGenBase { } - /**+ - * Recursively called by generate() + protected void func_180705_a(long parLong1, int parInt1, int parInt2, ChunkPrimer parChunkPrimer, double parDouble1, + double parDouble2, double parDouble3) { + this.func_180704_a(parLong1, parInt1, parInt2, parChunkPrimer, parDouble1, parDouble2, parDouble3, + 1.0F + this.rand.nextFloat() * 6.0F, 0.0F, 0.0F, -1, -1, 0.5D); + } + + /** + * + Recursively called by generate() */ protected void recursiveGenerate(World var1, int i, int j, int k, int l, ChunkPrimer chunkprimer) { int i1 = this.rand.nextInt(this.rand.nextInt(this.rand.nextInt(10) + 1) + 1); diff --git a/src/game/java/net/minecraft/world/gen/MapGenRavine.java b/src/game/java/net/minecraft/world/gen/MapGenRavine.java index 9175e8e0..39fe64b3 100644 --- a/src/game/java/net/minecraft/world/gen/MapGenRavine.java +++ b/src/game/java/net/minecraft/world/gen/MapGenRavine.java @@ -8,22 +8,25 @@ import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -197,8 +200,8 @@ public class MapGenRavine extends MapGenBase { } - /**+ - * Recursively called by generate() + /** + * + Recursively called by generate() */ protected void recursiveGenerate(World worldIn, int chunkX, int chunkZ, int chunkPrimerIn, int parInt4, ChunkPrimer parChunkPrimer) { diff --git a/src/game/java/net/minecraft/world/gen/NoiseGenerator.java b/src/game/java/net/minecraft/world/gen/NoiseGenerator.java index 1fb7a2e5..b8359ad3 100644 --- a/src/game/java/net/minecraft/world/gen/NoiseGenerator.java +++ b/src/game/java/net/minecraft/world/gen/NoiseGenerator.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/NoiseGeneratorImproved.java b/src/game/java/net/minecraft/world/gen/NoiseGeneratorImproved.java index b274f561..d40d11d5 100644 --- a/src/game/java/net/minecraft/world/gen/NoiseGeneratorImproved.java +++ b/src/game/java/net/minecraft/world/gen/NoiseGeneratorImproved.java @@ -2,31 +2,30 @@ package net.minecraft.world.gen; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NoiseGeneratorImproved extends NoiseGenerator { - private int[] permutations; - public double xCoord; - public double yCoord; - public double zCoord; private static final double[] field_152381_e = new double[] { 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, -1.0D, 0.0D }; private static final double[] field_152382_f = new double[] { 1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, @@ -37,6 +36,10 @@ public class NoiseGeneratorImproved extends NoiseGenerator { 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, -1.0D, 0.0D }; private static final double[] field_152385_i = new double[] { 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 1.0D, -1.0D, -1.0D, 1.0D, 1.0D, -1.0D, -1.0D, 0.0D, 1.0D, 0.0D, -1.0D }; + private int[] permutations; + public double xCoord; + public double yCoord; + public double zCoord; public NoiseGeneratorImproved() { this(new EaglercraftRandom()); @@ -62,10 +65,6 @@ public class NoiseGeneratorImproved extends NoiseGenerator { } - public final double lerp(double parDouble1, double parDouble2, double parDouble3) { - return parDouble2 + parDouble1 * (parDouble3 - parDouble2); - } - public final double func_76309_a(int parInt1, double parDouble1, double parDouble2) { int i = parInt1 & 15; return field_152384_h[i] * parDouble1 + field_152385_i[i] * parDouble2; @@ -76,10 +75,14 @@ public class NoiseGeneratorImproved extends NoiseGenerator { return field_152381_e[i] * parDouble1 + field_152382_f[i] * parDouble2 + field_152383_g[i] * parDouble3; } - /**+ - * pars: noiseArray , xOffset , yOffset , zOffset , xSize , - * ySize , zSize , xScale, yScale , zScale , noiseScale. - * noiseArray should be xSize*ySize*zSize in size + public final double lerp(double parDouble1, double parDouble2, double parDouble3) { + return parDouble2 + parDouble1 * (parDouble3 - parDouble2); + } + + /** + * + pars: noiseArray , xOffset , yOffset , zOffset , xSize , ySize , zSize , + * xScale, yScale , zScale , noiseScale. noiseArray should be xSize*ySize*zSize + * in size */ public void populateNoiseArray(double[] parArrayOfDouble, double parDouble1, double parDouble2, double parDouble3, int parInt1, int parInt2, int parInt3, double parDouble4, double parDouble5, double parDouble6, diff --git a/src/game/java/net/minecraft/world/gen/NoiseGeneratorOctaves.java b/src/game/java/net/minecraft/world/gen/NoiseGeneratorOctaves.java index d710b3b0..e4a45054 100644 --- a/src/game/java/net/minecraft/world/gen/NoiseGeneratorOctaves.java +++ b/src/game/java/net/minecraft/world/gen/NoiseGeneratorOctaves.java @@ -1,25 +1,27 @@ package net.minecraft.world.gen; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; - import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,8 +40,17 @@ public class NoiseGeneratorOctaves extends NoiseGenerator { } - /**+ - * Bouncer function to the main one with some default arguments. + /** + * + Bouncer function to the main one with some default arguments. + */ + public double[] generateNoiseOctaves(double[] parArrayOfDouble, int parInt1, int parInt2, int parInt3, int parInt4, + double parDouble1, double parDouble2, double parDouble3) { + return this.generateNoiseOctaves(parArrayOfDouble, parInt1, 10, parInt2, parInt3, 1, parInt4, parDouble1, 1.0D, + parDouble2); + } + + /** + * + Bouncer function to the main one with some default arguments. */ public double[] generateNoiseOctaves(double[] parArrayOfDouble, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, double parDouble1, double parDouble2, double parDouble3) { @@ -72,13 +83,4 @@ public class NoiseGeneratorOctaves extends NoiseGenerator { return parArrayOfDouble; } - - /**+ - * Bouncer function to the main one with some default arguments. - */ - public double[] generateNoiseOctaves(double[] parArrayOfDouble, int parInt1, int parInt2, int parInt3, int parInt4, - double parDouble1, double parDouble2, double parDouble3) { - return this.generateNoiseOctaves(parArrayOfDouble, parInt1, 10, parInt2, parInt3, 1, parInt4, parDouble1, 1.0D, - parDouble2); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/NoiseGeneratorPerlin.java b/src/game/java/net/minecraft/world/gen/NoiseGeneratorPerlin.java index aeba9ea7..0f368615 100644 --- a/src/game/java/net/minecraft/world/gen/NoiseGeneratorPerlin.java +++ b/src/game/java/net/minecraft/world/gen/NoiseGeneratorPerlin.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,18 +39,6 @@ public class NoiseGeneratorPerlin extends NoiseGenerator { } - public double func_151601_a(double parDouble1, double parDouble2) { - double d0 = 0.0D; - double d1 = 1.0D; - - for (int i = 0; i < this.field_151602_b; ++i) { - d0 += this.field_151603_a[i].func_151605_a(parDouble1 * d1, parDouble2 * d1) / d1; - d1 /= 2.0D; - } - - return d0; - } - public double[] func_151599_a(double[] parArrayOfDouble, double parDouble1, double parDouble2, int parInt1, int parInt2, double parDouble3, double parDouble4, double parDouble5) { return this.func_151600_a(parArrayOfDouble, parDouble1, parDouble2, parInt1, parInt2, parDouble3, parDouble4, @@ -76,4 +67,16 @@ public class NoiseGeneratorPerlin extends NoiseGenerator { return parArrayOfDouble; } + + public double func_151601_a(double parDouble1, double parDouble2) { + double d0 = 0.0D; + double d1 = 1.0D; + + for (int i = 0; i < this.field_151602_b; ++i) { + d0 += this.field_151603_a[i].func_151605_a(parDouble1 * d1, parDouble2 * d1) / d1; + d1 /= 2.0D; + } + + return d0; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/NoiseGeneratorSimplex.java b/src/game/java/net/minecraft/world/gen/NoiseGeneratorSimplex.java index 764b8170..6d2ce6b8 100644 --- a/src/game/java/net/minecraft/world/gen/NoiseGeneratorSimplex.java +++ b/src/game/java/net/minecraft/world/gen/NoiseGeneratorSimplex.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,13 +30,24 @@ public class NoiseGeneratorSimplex { { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, { -1, 0, -1 }, { 0, 1, 1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, -1, -1 } }; public static final double field_151614_a = Math.sqrt(3.0D); - private int[] field_151608_f; - public double field_151612_b; - public double field_151613_c; - public double field_151610_d; private static final double field_151609_g = 0.5D * (field_151614_a - 1.0D); private static final double field_151615_h = (3.0D - field_151614_a) / 6.0D; + private static double func_151604_a(int[] parArrayOfInt, double parDouble1, double parDouble2) { + return (double) parArrayOfInt[0] * parDouble1 + (double) parArrayOfInt[1] * parDouble2; + } + + private static int func_151607_a(double parDouble1) { + return parDouble1 > 0.0D ? (int) parDouble1 : (int) parDouble1 - 1; + } + + private int[] field_151608_f; + public double field_151612_b; + + public double field_151613_c; + + public double field_151610_d; + public NoiseGeneratorSimplex() { this(new EaglercraftRandom()); } @@ -58,14 +72,6 @@ public class NoiseGeneratorSimplex { } - private static int func_151607_a(double parDouble1) { - return parDouble1 > 0.0D ? (int) parDouble1 : (int) parDouble1 - 1; - } - - private static double func_151604_a(int[] parArrayOfInt, double parDouble1, double parDouble2) { - return (double) parArrayOfInt[0] * parDouble1 + (double) parArrayOfInt[1] * parDouble2; - } - public double func_151605_a(double parDouble1, double parDouble2) { double d3 = 0.5D * (field_151614_a - 1.0D); double d4 = (parDouble1 + parDouble2) * d3; diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenAbstractTree.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenAbstractTree.java index 2583980d..34ce5ca6 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenAbstractTree.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenAbstractTree.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,13 +42,13 @@ public abstract class WorldGenAbstractTree extends WorldGenerator { || parBlock == Blocks.sapling || parBlock == Blocks.vine; } - public void func_180711_a(World worldIn, EaglercraftRandom parRandom, BlockPos parBlockPos) { - } - protected void func_175921_a(World worldIn, BlockPos parBlockPos) { if (worldIn.getBlockState(parBlockPos).getBlock() != Blocks.dirt) { this.setBlockAndNotifyAdequately(worldIn, parBlockPos, Blocks.dirt.getDefaultState()); } } + + public void func_180711_a(World worldIn, EaglercraftRandom parRandom, BlockPos parBlockPos) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenBigMushroom.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenBigMushroom.java index 78220921..b50d94ea 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenBigMushroom.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenBigMushroom.java @@ -8,22 +8,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,15 +34,15 @@ import net.minecraft.world.World; public class WorldGenBigMushroom extends WorldGenerator { private Block mushroomType; + public WorldGenBigMushroom() { + super(false); + } + public WorldGenBigMushroom(Block parBlock) { super(true); this.mushroomType = parBlock; } - public WorldGenBigMushroom() { - super(false); - } - public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { if (this.mushroomType == null) { this.mushroomType = random.nextBoolean() ? Blocks.brown_mushroom_block : Blocks.red_mushroom_block; diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenBigTree.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenBigTree.java index 6c7e6b29..ec60a018 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenBigTree.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenBigTree.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen.feature; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.BlockLeaves; @@ -13,27 +15,43 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldGenBigTree extends WorldGenAbstractTree { + static class FoliageCoordinates extends BlockPos { + private final int field_178000_b; + + public FoliageCoordinates(BlockPos parBlockPos, int parInt1) { + super(parBlockPos.getX(), parBlockPos.getY(), parBlockPos.getZ()); + this.field_178000_b = parInt1; + } + + public int func_177999_q() { + return this.field_178000_b; + } + } + private EaglercraftRandom rand; private World world; private BlockPos basePos = BlockPos.ORIGIN; @@ -46,15 +64,144 @@ public class WorldGenBigTree extends WorldGenAbstractTree { int trunkSize = 1; int heightLimitLimit = 12; int leafDistanceLimit = 4; + List field_175948_j; public WorldGenBigTree(boolean parFlag) { super(parFlag); } - /**+ - * Generates a list of leaf nodes for the tree, to be populated - * by generateLeaves. + /** + * + Checks a line of blocks in the world from the first coordinate to triplet + * to the second, returning the distance (in blocks) before a non-air, non-leaf + * block is encountered and/or the end is encountered. + */ + int checkBlockLine(BlockPos posOne, BlockPos posTwo) { + BlockPos blockpos = posTwo.add(-posOne.getX(), -posOne.getY(), -posOne.getZ()); + int i = this.getGreatestDistance(blockpos); + float f = (float) blockpos.getX() / (float) i; + float f1 = (float) blockpos.getY() / (float) i; + float f2 = (float) blockpos.getZ() / (float) i; + if (i == 0) { + return -1; + } else { + for (int j = 0; j <= i; ++j) { + BlockPos blockpos1 = posOne.add((double) (0.5F + (float) j * f), (double) (0.5F + (float) j * f1), + (double) (0.5F + (float) j * f2)); + if (!this.func_150523_a(this.world.getBlockState(blockpos1).getBlock())) { + return j; + } + } + + return -1; + } + } + + public void func_175904_e() { + this.leafDistanceLimit = 5; + } + + void func_175937_a(BlockPos parBlockPos, BlockPos parBlockPos2, Block parBlock) { + BlockPos blockpos = parBlockPos2.add(-parBlockPos.getX(), -parBlockPos.getY(), -parBlockPos.getZ()); + int i = this.getGreatestDistance(blockpos); + float f = (float) blockpos.getX() / (float) i; + float f1 = (float) blockpos.getY() / (float) i; + float f2 = (float) blockpos.getZ() / (float) i; + + for (int j = 0; j <= i; ++j) { + BlockPos blockpos1 = parBlockPos.add((double) (0.5F + (float) j * f), (double) (0.5F + (float) j * f1), + (double) (0.5F + (float) j * f2)); + BlockLog.EnumAxis blocklog$enumaxis = this.func_175938_b(parBlockPos, blockpos1); + this.setBlockAndNotifyAdequately(this.world, blockpos1, + parBlock.getDefaultState().withProperty(BlockLog.LOG_AXIS, blocklog$enumaxis)); + } + + } + + private BlockLog.EnumAxis func_175938_b(BlockPos parBlockPos, BlockPos parBlockPos2) { + BlockLog.EnumAxis blocklog$enumaxis = BlockLog.EnumAxis.Y; + int i = Math.abs(parBlockPos2.getX() - parBlockPos.getX()); + int j = Math.abs(parBlockPos2.getZ() - parBlockPos.getZ()); + int k = Math.max(i, j); + if (k > 0) { + if (i == k) { + blocklog$enumaxis = BlockLog.EnumAxis.X; + } else if (j == k) { + blocklog$enumaxis = BlockLog.EnumAxis.Z; + } + } + + return blocklog$enumaxis; + } + + void func_181631_a(BlockPos parBlockPos, float parFloat1, IBlockState parIBlockState) { + int i = (int) ((double) parFloat1 + 0.618D); + + for (int j = -i; j <= i; ++j) { + for (int k = -i; k <= i; ++k) { + if (Math.pow((double) Math.abs(j) + 0.5D, 2.0D) + + Math.pow((double) Math.abs(k) + 0.5D, 2.0D) <= (double) (parFloat1 * parFloat1)) { + BlockPos blockpos = parBlockPos.add(j, 0, k); + Material material = this.world.getBlockState(blockpos).getBlock().getMaterial(); + if (material == Material.air || material == Material.leaves) { + this.setBlockAndNotifyAdequately(this.world, blockpos, parIBlockState); + } + } + } + } + + } + + public boolean generate(World worldIn, EaglercraftRandom rand, BlockPos position) { + this.world = worldIn; + this.basePos = position; + this.rand = new EaglercraftRandom(rand.nextLong(), !worldIn.getWorldInfo().isOldEaglercraftRandom()); + if (this.heightLimit == 0) { + this.heightLimit = 5 + this.rand.nextInt(this.heightLimitLimit); + } + + if (!this.validTreeLocation()) { + return false; + } else { + this.generateLeafNodeList(); + this.generateLeaves(); + this.generateTrunk(); + this.generateLeafNodeBases(); + return true; + } + } + + /** + * + Generates the leaves surrounding an individual entry in the leafNodes list. + */ + void generateLeafNode(BlockPos pos) { + for (int i = 0; i < this.leafDistanceLimit; ++i) { + this.func_181631_a(pos.up(i), this.leafSize(i), + Blocks.leaves.getDefaultState().withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false))); + } + + } + + /** + * + Generates additional wood blocks to fill out the bases of different leaf + * nodes that would otherwise degrade. + */ + void generateLeafNodeBases() { + for (int j = 0, l = this.field_175948_j.size(); j < l; ++j) { + WorldGenBigTree.FoliageCoordinates worldgenbigtree$foliagecoordinates = this.field_175948_j.get(j); + int i = worldgenbigtree$foliagecoordinates.func_177999_q(); + BlockPos blockpos = new BlockPos(this.basePos.getX(), i, this.basePos.getZ()); + if (!blockpos.equals(worldgenbigtree$foliagecoordinates) + && this.leafNodeNeedsBase(i - this.basePos.getY())) { + this.func_175937_a(blockpos, worldgenbigtree$foliagecoordinates, Blocks.log); + } + } + + } + + /** + * + Generates a list of leaf nodes for the tree, to be populated by + * generateLeaves. */ void generateLeafNodeList() { this.height = (int) ((double) this.heightLimit * this.heightAttenuation); @@ -99,26 +246,45 @@ public class WorldGenBigTree extends WorldGenAbstractTree { } - void func_181631_a(BlockPos parBlockPos, float parFloat1, IBlockState parIBlockState) { - int i = (int) ((double) parFloat1 + 0.618D); - - for (int j = -i; j <= i; ++j) { - for (int k = -i; k <= i; ++k) { - if (Math.pow((double) Math.abs(j) + 0.5D, 2.0D) - + Math.pow((double) Math.abs(k) + 0.5D, 2.0D) <= (double) (parFloat1 * parFloat1)) { - BlockPos blockpos = parBlockPos.add(j, 0, k); - Material material = this.world.getBlockState(blockpos).getBlock().getMaterial(); - if (material == Material.air || material == Material.leaves) { - this.setBlockAndNotifyAdequately(this.world, blockpos, parIBlockState); - } - } - } + /** + * + Generates the leaf portion of the tree as specified by the leafNodes list. + */ + void generateLeaves() { + for (int i = 0, l = this.field_175948_j.size(); i < l; ++i) { + this.generateLeafNode(this.field_175948_j.get(i)); } } - /**+ - * Gets the rough size of a layer of the tree. + /** + * + Places the trunk for the big tree that is being generated. Able to generate + * double-sized trunks by changing a field that is always 1 to 2. + */ + void generateTrunk() { + BlockPos blockpos = this.basePos; + BlockPos blockpos1 = this.basePos.up(this.height); + Block block = Blocks.log; + this.func_175937_a(blockpos, blockpos1, block); + if (this.trunkSize == 2) { + this.func_175937_a(blockpos.east(), blockpos1.east(), block); + this.func_175937_a(blockpos.east().south(), blockpos1.east().south(), block); + this.func_175937_a(blockpos.south(), blockpos1.south(), block); + } + + } + + /** + * + Returns the absolute greatest distance in the BlockPos object. + */ + private int getGreatestDistance(BlockPos posIn) { + int i = MathHelper.abs_int(posIn.getX()); + int j = MathHelper.abs_int(posIn.getY()); + int k = MathHelper.abs_int(posIn.getZ()); + return k > i && k > j ? k : (j > i ? j : i); + } + + /** + * + Gets the rough size of a layer of the tree. */ float layerSize(int parInt1) { if ((float) parInt1 < (float) this.heightLimit * 0.3F) { @@ -137,176 +303,23 @@ public class WorldGenBigTree extends WorldGenAbstractTree { } } + /** + * + Indicates whether or not a leaf node requires additional wood to be added + * to preserve integrity. + */ + boolean leafNodeNeedsBase(int parInt1) { + return (double) parInt1 >= (double) this.heightLimit * 0.2D; + } + float leafSize(int parInt1) { return parInt1 >= 0 && parInt1 < this.leafDistanceLimit ? (parInt1 != 0 && parInt1 != this.leafDistanceLimit - 1 ? 3.0F : 2.0F) : -1.0F; } - /**+ - * Generates the leaves surrounding an individual entry in the - * leafNodes list. - */ - void generateLeafNode(BlockPos pos) { - for (int i = 0; i < this.leafDistanceLimit; ++i) { - this.func_181631_a(pos.up(i), this.leafSize(i), - Blocks.leaves.getDefaultState().withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false))); - } - - } - - void func_175937_a(BlockPos parBlockPos, BlockPos parBlockPos2, Block parBlock) { - BlockPos blockpos = parBlockPos2.add(-parBlockPos.getX(), -parBlockPos.getY(), -parBlockPos.getZ()); - int i = this.getGreatestDistance(blockpos); - float f = (float) blockpos.getX() / (float) i; - float f1 = (float) blockpos.getY() / (float) i; - float f2 = (float) blockpos.getZ() / (float) i; - - for (int j = 0; j <= i; ++j) { - BlockPos blockpos1 = parBlockPos.add((double) (0.5F + (float) j * f), (double) (0.5F + (float) j * f1), - (double) (0.5F + (float) j * f2)); - BlockLog.EnumAxis blocklog$enumaxis = this.func_175938_b(parBlockPos, blockpos1); - this.setBlockAndNotifyAdequately(this.world, blockpos1, - parBlock.getDefaultState().withProperty(BlockLog.LOG_AXIS, blocklog$enumaxis)); - } - - } - - /**+ - * Returns the absolute greatest distance in the BlockPos - * object. - */ - private int getGreatestDistance(BlockPos posIn) { - int i = MathHelper.abs_int(posIn.getX()); - int j = MathHelper.abs_int(posIn.getY()); - int k = MathHelper.abs_int(posIn.getZ()); - return k > i && k > j ? k : (j > i ? j : i); - } - - private BlockLog.EnumAxis func_175938_b(BlockPos parBlockPos, BlockPos parBlockPos2) { - BlockLog.EnumAxis blocklog$enumaxis = BlockLog.EnumAxis.Y; - int i = Math.abs(parBlockPos2.getX() - parBlockPos.getX()); - int j = Math.abs(parBlockPos2.getZ() - parBlockPos.getZ()); - int k = Math.max(i, j); - if (k > 0) { - if (i == k) { - blocklog$enumaxis = BlockLog.EnumAxis.X; - } else if (j == k) { - blocklog$enumaxis = BlockLog.EnumAxis.Z; - } - } - - return blocklog$enumaxis; - } - - /**+ - * Generates the leaf portion of the tree as specified by the - * leafNodes list. - */ - void generateLeaves() { - for (int i = 0, l = this.field_175948_j.size(); i < l; ++i) { - this.generateLeafNode(this.field_175948_j.get(i)); - } - - } - - /**+ - * Indicates whether or not a leaf node requires additional wood - * to be added to preserve integrity. - */ - boolean leafNodeNeedsBase(int parInt1) { - return (double) parInt1 >= (double) this.heightLimit * 0.2D; - } - - /**+ - * Places the trunk for the big tree that is being generated. - * Able to generate double-sized trunks by changing a field that - * is always 1 to 2. - */ - void generateTrunk() { - BlockPos blockpos = this.basePos; - BlockPos blockpos1 = this.basePos.up(this.height); - Block block = Blocks.log; - this.func_175937_a(blockpos, blockpos1, block); - if (this.trunkSize == 2) { - this.func_175937_a(blockpos.east(), blockpos1.east(), block); - this.func_175937_a(blockpos.east().south(), blockpos1.east().south(), block); - this.func_175937_a(blockpos.south(), blockpos1.south(), block); - } - - } - - /**+ - * Generates additional wood blocks to fill out the bases of - * different leaf nodes that would otherwise degrade. - */ - void generateLeafNodeBases() { - for (int j = 0, l = this.field_175948_j.size(); j < l; ++j) { - WorldGenBigTree.FoliageCoordinates worldgenbigtree$foliagecoordinates = this.field_175948_j.get(j); - int i = worldgenbigtree$foliagecoordinates.func_177999_q(); - BlockPos blockpos = new BlockPos(this.basePos.getX(), i, this.basePos.getZ()); - if (!blockpos.equals(worldgenbigtree$foliagecoordinates) - && this.leafNodeNeedsBase(i - this.basePos.getY())) { - this.func_175937_a(blockpos, worldgenbigtree$foliagecoordinates, Blocks.log); - } - } - - } - - /**+ - * Checks a line of blocks in the world from the first - * coordinate to triplet to the second, returning the distance - * (in blocks) before a non-air, non-leaf block is encountered - * and/or the end is encountered. - */ - int checkBlockLine(BlockPos posOne, BlockPos posTwo) { - BlockPos blockpos = posTwo.add(-posOne.getX(), -posOne.getY(), -posOne.getZ()); - int i = this.getGreatestDistance(blockpos); - float f = (float) blockpos.getX() / (float) i; - float f1 = (float) blockpos.getY() / (float) i; - float f2 = (float) blockpos.getZ() / (float) i; - if (i == 0) { - return -1; - } else { - for (int j = 0; j <= i; ++j) { - BlockPos blockpos1 = posOne.add((double) (0.5F + (float) j * f), (double) (0.5F + (float) j * f1), - (double) (0.5F + (float) j * f2)); - if (!this.func_150523_a(this.world.getBlockState(blockpos1).getBlock())) { - return j; - } - } - - return -1; - } - } - - public void func_175904_e() { - this.leafDistanceLimit = 5; - } - - public boolean generate(World worldIn, EaglercraftRandom rand, BlockPos position) { - this.world = worldIn; - this.basePos = position; - this.rand = new EaglercraftRandom(rand.nextLong(), !worldIn.getWorldInfo().isOldEaglercraftRandom()); - if (this.heightLimit == 0) { - this.heightLimit = 5 + this.rand.nextInt(this.heightLimitLimit); - } - - if (!this.validTreeLocation()) { - return false; - } else { - this.generateLeafNodeList(); - this.generateLeaves(); - this.generateTrunk(); - this.generateLeafNodeBases(); - return true; - } - } - - /**+ - * Returns a boolean indicating whether or not the current - * location for the tree, spanning basePos to to the height - * limit, is valid. + /** + * + Returns a boolean indicating whether or not the current location for the + * tree, spanning basePos to to the height limit, is valid. */ private boolean validTreeLocation() { Block block = this.world.getBlockState(this.basePos.down()).getBlock(); @@ -324,17 +337,4 @@ public class WorldGenBigTree extends WorldGenAbstractTree { } } } - - static class FoliageCoordinates extends BlockPos { - private final int field_178000_b; - - public FoliageCoordinates(BlockPos parBlockPos, int parInt1) { - super(parBlockPos.getX(), parBlockPos.getY(), parBlockPos.getZ()); - this.field_178000_b = parInt1; - } - - public int func_177999_q() { - return this.field_178000_b; - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenBlockBlob.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenBlockBlob.java index 98064d6d..03d12406 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenBlockBlob.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenBlockBlob.java @@ -6,22 +6,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenCactus.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenCactus.java index 0d373c61..4bfdf0c6 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenCactus.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenCactus.java @@ -5,22 +5,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenCanopyTree.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenCanopyTree.java index f5991fcf..81d0140c 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenCanopyTree.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenCanopyTree.java @@ -13,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +47,51 @@ public class WorldGenCanopyTree extends WorldGenAbstractTree { super(parFlag); } + private void func_150526_a(World worldIn, int parInt1, int parInt2, int parInt3) { + BlockPos blockpos = new BlockPos(parInt1, parInt2, parInt3); + Block block = worldIn.getBlockState(blockpos).getBlock(); + if (block.getMaterial() == Material.air) { + this.setBlockAndNotifyAdequately(worldIn, blockpos, field_181641_b); + } + + } + + private boolean func_181638_a(World parWorld, BlockPos parBlockPos, int parInt1) { + int i = parBlockPos.getX(); + int j = parBlockPos.getY(); + int k = parBlockPos.getZ(); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int l = 0; l <= parInt1 + 1; ++l) { + byte b0 = 1; + if (l == 0) { + b0 = 0; + } + + if (l >= parInt1 - 1) { + b0 = 2; + } + + for (int i1 = -b0; i1 <= b0; ++i1) { + for (int j1 = -b0; j1 <= b0; ++j1) { + if (!this.func_150523_a(parWorld + .getBlockState(blockpos$mutableblockpos.func_181079_c(i + i1, j + l, k + j1)).getBlock())) { + return false; + } + } + } + } + + return true; + } + + private void func_181639_b(World parWorld, BlockPos parBlockPos) { + if (this.func_150523_a(parWorld.getBlockState(parBlockPos).getBlock())) { + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, field_181640_a); + } + + } + public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { int i = random.nextInt(3) + random.nextInt(2) + 6; int j = blockpos.getX(); @@ -151,49 +199,4 @@ public class WorldGenCanopyTree extends WorldGenAbstractTree { return false; } } - - private boolean func_181638_a(World parWorld, BlockPos parBlockPos, int parInt1) { - int i = parBlockPos.getX(); - int j = parBlockPos.getY(); - int k = parBlockPos.getZ(); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int l = 0; l <= parInt1 + 1; ++l) { - byte b0 = 1; - if (l == 0) { - b0 = 0; - } - - if (l >= parInt1 - 1) { - b0 = 2; - } - - for (int i1 = -b0; i1 <= b0; ++i1) { - for (int j1 = -b0; j1 <= b0; ++j1) { - if (!this.func_150523_a(parWorld - .getBlockState(blockpos$mutableblockpos.func_181079_c(i + i1, j + l, k + j1)).getBlock())) { - return false; - } - } - } - } - - return true; - } - - private void func_181639_b(World parWorld, BlockPos parBlockPos) { - if (this.func_150523_a(parWorld.getBlockState(parBlockPos).getBlock())) { - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, field_181640_a); - } - - } - - private void func_150526_a(World worldIn, int parInt1, int parInt2, int parInt3) { - BlockPos blockpos = new BlockPos(parInt1, parInt2, parInt3); - Block block = worldIn.getBlockState(blockpos).getBlock(); - if (block.getMaterial() == Material.air) { - this.setBlockAndNotifyAdequately(worldIn, blockpos, field_181641_b); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenClay.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenClay.java index 82b3d92c..53402564 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenClay.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenClay.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenDeadBush.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenDeadBush.java index 8ce19ed9..b7b036fd 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenDeadBush.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenDeadBush.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenDesertWells.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenDesertWells.java index 18d43469..76cbeeef 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenDesertWells.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenDesertWells.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen.feature; import com.google.common.base.Predicates; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockSand; import net.minecraft.block.BlockSlab; @@ -12,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenDoublePlant.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenDoublePlant.java index 473965c6..399b588d 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenDoublePlant.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenDoublePlant.java @@ -6,22 +6,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,10 +32,6 @@ import net.minecraft.world.World; public class WorldGenDoublePlant extends WorldGenerator { private BlockDoublePlant.EnumPlantType field_150549_a; - public void setPlantType(BlockDoublePlant.EnumPlantType parEnumPlantType) { - this.field_150549_a = parEnumPlantType; - } - public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { boolean flag = false; @@ -48,4 +47,8 @@ public class WorldGenDoublePlant extends WorldGenerator { return flag; } + + public void setPlantType(BlockDoublePlant.EnumPlantType parEnumPlantType) { + this.field_150549_a = parEnumPlantType; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenDungeons.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenDungeons.java index c89f6cbb..1fc036b8 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenDungeons.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenDungeons.java @@ -1,8 +1,12 @@ package net.minecraft.world.gen.feature; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -13,25 +17,26 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -161,8 +166,8 @@ public class WorldGenDungeons extends WorldGenerator { } } - /**+ - * Randomly decides which spawner to use in a dungeon + /** + * + Randomly decides which spawner to use in a dungeon */ private String pickMobSpawner(EaglercraftRandom parRandom) { return SPAWNERTYPES[parRandom.nextInt(SPAWNERTYPES.length)]; diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenFire.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenFire.java index cccc5505..619a4cb5 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenFire.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenFire.java @@ -5,22 +5,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenFlowers.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenFlowers.java index 1709dd42..4f055b4a 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenFlowers.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenFlowers.java @@ -6,22 +6,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,12 +37,6 @@ public class WorldGenFlowers extends WorldGenerator { this.setGeneratedBlock(parBlockFlower, parEnumFlowerType); } - public void setGeneratedBlock(BlockFlower parBlockFlower, BlockFlower.EnumFlowerType parEnumFlowerType) { - this.flower = parBlockFlower; - this.field_175915_b = parBlockFlower.getDefaultState().withProperty(parBlockFlower.getTypeProperty(), - parEnumFlowerType); - } - public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { for (int i = 0; i < 64; ++i) { BlockPos blockpos1 = blockpos.add(random.nextInt(8) - random.nextInt(8), @@ -52,4 +49,10 @@ public class WorldGenFlowers extends WorldGenerator { return true; } + + public void setGeneratedBlock(BlockFlower parBlockFlower, BlockFlower.EnumFlowerType parEnumFlowerType) { + this.flower = parBlockFlower; + this.field_175915_b = parBlockFlower.getDefaultState().withProperty(parBlockFlower.getTypeProperty(), + parEnumFlowerType); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenForest.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenForest.java index 13e802ca..1e75f53e 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenForest.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenForest.java @@ -11,22 +11,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone1.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone1.java index e20bd45b..7b73d7dd 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone1.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone1.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone2.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone2.java index ce4ba41b..1814b8fa 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone2.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenGlowStone2.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenHellLava.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenHellLava.java index 03bee9c8..3a8a8b76 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenHellLava.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenHellLava.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenHugeTrees.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenHugeTrees.java index 3cb3a012..2696fb3c 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenHugeTrees.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenHugeTrees.java @@ -8,22 +8,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,6 +55,25 @@ public abstract class WorldGenHugeTrees extends WorldGenAbstractTree { return i; } + protected void func_175925_a(World worldIn, BlockPos parBlockPos, int parInt1) { + int i = parInt1 * parInt1; + + for (int j = -parInt1; j <= parInt1 + 1; ++j) { + for (int k = -parInt1; k <= parInt1 + 1; ++k) { + int l = j - 1; + int i1 = k - 1; + if (j * j + k * k <= i || l * l + i1 * i1 <= i || j * j + i1 * i1 <= i || l * l + k * k <= i) { + BlockPos blockpos = parBlockPos.add(j, 0, k); + Material material = worldIn.getBlockState(blockpos).getBlock().getMaterial(); + if (material == Material.air || material == Material.leaves) { + this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata); + } + } + } + } + + } + private boolean func_175926_c(World worldIn, BlockPos parBlockPos, int parInt1) { boolean flag = true; if (parBlockPos.getY() >= 1 && parBlockPos.getY() + parInt1 + 1 <= 256) { @@ -93,29 +115,6 @@ public abstract class WorldGenHugeTrees extends WorldGenAbstractTree { } } - protected boolean func_175929_a(World worldIn, EaglercraftRandom parRandom, BlockPos parBlockPos, int parInt1) { - return this.func_175926_c(worldIn, parBlockPos, parInt1) && this.func_175927_a(parBlockPos, worldIn); - } - - protected void func_175925_a(World worldIn, BlockPos parBlockPos, int parInt1) { - int i = parInt1 * parInt1; - - for (int j = -parInt1; j <= parInt1 + 1; ++j) { - for (int k = -parInt1; k <= parInt1 + 1; ++k) { - int l = j - 1; - int i1 = k - 1; - if (j * j + k * k <= i || l * l + i1 * i1 <= i || j * j + i1 * i1 <= i || l * l + k * k <= i) { - BlockPos blockpos = parBlockPos.add(j, 0, k); - Material material = worldIn.getBlockState(blockpos).getBlock().getMaterial(); - if (material == Material.air || material == Material.leaves) { - this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata); - } - } - } - } - - } - protected void func_175928_b(World worldIn, BlockPos parBlockPos, int parInt1) { int i = parInt1 * parInt1; @@ -132,4 +131,8 @@ public abstract class WorldGenHugeTrees extends WorldGenAbstractTree { } } + + protected boolean func_175929_a(World worldIn, EaglercraftRandom parRandom, BlockPos parBlockPos, int parInt1) { + return this.func_175926_c(worldIn, parBlockPos, parInt1) && this.func_175927_a(parBlockPos, worldIn); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenIcePath.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenIcePath.java index 0b79e7b1..46b78b5a 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenIcePath.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenIcePath.java @@ -6,22 +6,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenIceSpike.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenIceSpike.java index b42179dd..462e48b3 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenIceSpike.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenIceSpike.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenLakes.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenLakes.java index aa18b514..dae74481 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenLakes.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenLakes.java @@ -9,22 +9,25 @@ import net.minecraft.world.EnumSkyBlock; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenLiquids.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenLiquids.java index 15e30f55..e6c909d5 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenLiquids.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenLiquids.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaJungle.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaJungle.java index e1b6f407..93670ee6 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaJungle.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaJungle.java @@ -9,22 +9,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +38,24 @@ public class WorldGenMegaJungle extends WorldGenHugeTrees { super(parFlag, parInt1, parInt2, parIBlockState, parIBlockState2); } + private void func_175930_c(World worldIn, BlockPos parBlockPos, int parInt1) { + byte b0 = 2; + + for (int i = -b0; i <= 0; ++i) { + this.func_175925_a(worldIn, parBlockPos.up(i), parInt1 + 1 - i); + } + + } + + private void func_181632_a(World parWorld, EaglercraftRandom parRandom, BlockPos parBlockPos, + PropertyBool parPropertyBool) { + if (parRandom.nextInt(3) > 0 && parWorld.isAirBlock(parBlockPos)) { + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, + Blocks.vine.getDefaultState().withProperty(parPropertyBool, Boolean.valueOf(true))); + } + + } + public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { int i = this.func_150533_a(random); if (!this.func_175929_a(world, random, blockpos, i)) { @@ -106,22 +127,4 @@ public class WorldGenMegaJungle extends WorldGenHugeTrees { return true; } } - - private void func_181632_a(World parWorld, EaglercraftRandom parRandom, BlockPos parBlockPos, - PropertyBool parPropertyBool) { - if (parRandom.nextInt(3) > 0 && parWorld.isAirBlock(parBlockPos)) { - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, - Blocks.vine.getDefaultState().withProperty(parPropertyBool, Boolean.valueOf(true))); - } - - } - - private void func_175930_c(World worldIn, BlockPos parBlockPos, int parInt1) { - byte b0 = 2; - - for (int i = -b0; i <= 0; ++i) { - this.func_175925_a(worldIn, parBlockPos.up(i), parInt1 + 1 - i); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaPineTree.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaPineTree.java index c7868cc9..264ed41b 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaPineTree.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenMegaPineTree.java @@ -14,22 +14,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,6 +52,65 @@ public class WorldGenMegaPineTree extends WorldGenHugeTrees { this.useBaseHeight = parFlag2; } + private void func_150541_c(World worldIn, int parInt1, int parInt2, int parInt3, int parInt4, + EaglercraftRandom parRandom) { + int i = parRandom.nextInt(5) + (this.useBaseHeight ? this.baseHeight : 3); + int j = 0; + + for (int k = parInt3 - i; k <= parInt3; ++k) { + int l = parInt3 - k; + int i1 = parInt4 + MathHelper.floor_float((float) l / (float) i * 3.5F); + this.func_175925_a(worldIn, new BlockPos(parInt1, k, parInt2), + i1 + (l > 0 && i1 == j && (k & 1) == 0 ? 1 : 0)); + j = i1; + } + + } + + private void func_175933_b(World worldIn, BlockPos parBlockPos) { + for (int i = -2; i <= 2; ++i) { + for (int j = -2; j <= 2; ++j) { + if (Math.abs(i) != 2 || Math.abs(j) != 2) { + this.func_175934_c(worldIn, parBlockPos.add(i, 0, j)); + } + } + } + + } + + private void func_175934_c(World worldIn, BlockPos parBlockPos) { + for (int i = 2; i >= -3; --i) { + BlockPos blockpos = parBlockPos.up(i); + Block block = worldIn.getBlockState(blockpos).getBlock(); + if (block == Blocks.grass || block == Blocks.dirt) { + this.setBlockAndNotifyAdequately(worldIn, blockpos, field_181635_g); + break; + } + + if (block.getMaterial() != Material.air && i < 0) { + break; + } + } + + } + + public void func_180711_a(World world, EaglercraftRandom random, BlockPos blockpos) { + this.func_175933_b(world, blockpos.west().north()); + this.func_175933_b(world, blockpos.east(2).north()); + this.func_175933_b(world, blockpos.west().south(2)); + this.func_175933_b(world, blockpos.east(2).south(2)); + + for (int i = 0; i < 5; ++i) { + int j = random.nextInt(64); + int k = j % 8; + int l = j / 8; + if (k == 0 || k == 7 || l == 0 || l == 7) { + this.func_175933_b(world, blockpos.add(-3 + k, 0, -3 + l)); + } + } + + } + public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { int i = this.func_150533_a(random); if (!this.func_175929_a(world, random, blockpos, i)) { @@ -83,63 +145,4 @@ public class WorldGenMegaPineTree extends WorldGenHugeTrees { return true; } } - - private void func_150541_c(World worldIn, int parInt1, int parInt2, int parInt3, int parInt4, - EaglercraftRandom parRandom) { - int i = parRandom.nextInt(5) + (this.useBaseHeight ? this.baseHeight : 3); - int j = 0; - - for (int k = parInt3 - i; k <= parInt3; ++k) { - int l = parInt3 - k; - int i1 = parInt4 + MathHelper.floor_float((float) l / (float) i * 3.5F); - this.func_175925_a(worldIn, new BlockPos(parInt1, k, parInt2), - i1 + (l > 0 && i1 == j && (k & 1) == 0 ? 1 : 0)); - j = i1; - } - - } - - public void func_180711_a(World world, EaglercraftRandom random, BlockPos blockpos) { - this.func_175933_b(world, blockpos.west().north()); - this.func_175933_b(world, blockpos.east(2).north()); - this.func_175933_b(world, blockpos.west().south(2)); - this.func_175933_b(world, blockpos.east(2).south(2)); - - for (int i = 0; i < 5; ++i) { - int j = random.nextInt(64); - int k = j % 8; - int l = j / 8; - if (k == 0 || k == 7 || l == 0 || l == 7) { - this.func_175933_b(world, blockpos.add(-3 + k, 0, -3 + l)); - } - } - - } - - private void func_175933_b(World worldIn, BlockPos parBlockPos) { - for (int i = -2; i <= 2; ++i) { - for (int j = -2; j <= 2; ++j) { - if (Math.abs(i) != 2 || Math.abs(j) != 2) { - this.func_175934_c(worldIn, parBlockPos.add(i, 0, j)); - } - } - } - - } - - private void func_175934_c(World worldIn, BlockPos parBlockPos) { - for (int i = 2; i >= -3; --i) { - BlockPos blockpos = parBlockPos.up(i); - Block block = worldIn.getBlockState(blockpos).getBlock(); - if (block == Blocks.grass || block == Blocks.dirt) { - this.setBlockAndNotifyAdequately(worldIn, blockpos, field_181635_g); - break; - } - - if (block.getMaterial() != Material.air && i < 0) { - break; - } - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenMelon.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenMelon.java index d3b22438..5b55fea1 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenMelon.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenMelon.java @@ -5,22 +5,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenMinable.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenMinable.java index 92d09c85..ba7f38c1 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenMinable.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenMinable.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen.feature; import com.google.common.base.Predicate; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.pattern.BlockHelper; @@ -9,22 +10,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,6 +40,7 @@ public class WorldGenMinable extends WorldGenerator { public WorldGenMinable(IBlockState state, int blockCount) { this(state, blockCount, BlockHelper.forBlock(Blocks.stone)); + } public WorldGenMinable(IBlockState state, int blockCount, Predicate parPredicate) { @@ -78,7 +83,12 @@ public class WorldGenMinable extends WorldGenerator { double d14 = ((double) j2 + 0.5D - d8) / (d10 / 2.0D); if (d12 * d12 + d13 * d13 + d14 * d14 < 1.0D) { BlockPos blockpos1 = new BlockPos(l1, i2, j2); - if (this.predicate.apply(world.getBlockState(blockpos1))) { + IBlockState currentState = world.getBlockState(blockpos1); + + if (blockpos1.getY() < 20 && (currentState.getBlock() == Blocks.stone + || currentState.getBlock() == Blocks.deepstone)) { + world.setBlockState(blockpos1, this.oreBlock, 2); + } else if (this.predicate.apply(currentState)) { world.setBlockState(blockpos1, this.oreBlock, 2); } } @@ -91,4 +101,5 @@ public class WorldGenMinable extends WorldGenerator { return true; } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenPumpkin.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenPumpkin.java index bad8bda6..3f582e96 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenPumpkin.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenPumpkin.java @@ -7,22 +7,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenReed.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenReed.java index ceed1e4c..53b66787 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenReed.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenReed.java @@ -6,22 +6,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenSand.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenSand.java index 17df6453..e28f5b12 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenSand.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenSand.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenSavannaTree.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenSavannaTree.java index c5cb7df9..02870518 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenSavannaTree.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenSavannaTree.java @@ -13,22 +13,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +47,18 @@ public class WorldGenSavannaTree extends WorldGenAbstractTree { super(parFlag); } + private void func_175924_b(World worldIn, BlockPos parBlockPos) { + Material material = worldIn.getBlockState(parBlockPos).getBlock().getMaterial(); + if (material == Material.air || material == Material.leaves) { + this.setBlockAndNotifyAdequately(worldIn, parBlockPos, field_181644_b); + } + + } + + private void func_181642_b(World parWorld, BlockPos parBlockPos) { + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, field_181643_a); + } + public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { int i = random.nextInt(3) + random.nextInt(3) + 5; boolean flag = true; @@ -179,16 +194,4 @@ public class WorldGenSavannaTree extends WorldGenAbstractTree { return false; } } - - private void func_181642_b(World parWorld, BlockPos parBlockPos) { - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, field_181643_a); - } - - private void func_175924_b(World worldIn, BlockPos parBlockPos) { - Material material = worldIn.getBlockState(parBlockPos).getBlock().getMaterial(); - if (material == Material.air || material == Material.leaves) { - this.setBlockAndNotifyAdequately(worldIn, parBlockPos, field_181644_b); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenShrub.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenShrub.java index 2678d2ec..92426123 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenShrub.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenShrub.java @@ -8,22 +8,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenSpikes.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenSpikes.java index 8f8f702a..56cbd945 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenSpikes.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenSpikes.java @@ -7,22 +7,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenSwamp.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenSwamp.java index 90238b65..ffb9778a 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenSwamp.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenSwamp.java @@ -13,22 +13,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,6 +47,19 @@ public class WorldGenSwamp extends WorldGenAbstractTree { super(false); } + private void func_181647_a(World parWorld, BlockPos parBlockPos, PropertyBool parPropertyBool) { + IBlockState iblockstate = Blocks.vine.getDefaultState().withProperty(parPropertyBool, Boolean.valueOf(true)); + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, iblockstate); + int i = 4; + + for (parBlockPos = parBlockPos + .down(); parWorld.getBlockState(parBlockPos).getBlock().getMaterial() == Material.air && i > 0; --i) { + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, iblockstate); + parBlockPos = parBlockPos.down(); + } + + } + public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { int i; for (i = random.nextInt(4) + 5; world.getBlockState(blockpos.down()).getBlock() @@ -165,17 +181,4 @@ public class WorldGenSwamp extends WorldGenAbstractTree { return false; } } - - private void func_181647_a(World parWorld, BlockPos parBlockPos, PropertyBool parPropertyBool) { - IBlockState iblockstate = Blocks.vine.getDefaultState().withProperty(parPropertyBool, Boolean.valueOf(true)); - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, iblockstate); - int i = 4; - - for (parBlockPos = parBlockPos - .down(); parWorld.getBlockState(parBlockPos).getBlock().getMaterial() == Material.air && i > 0; --i) { - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, iblockstate); - parBlockPos = parBlockPos.down(); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga1.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga1.java index 93d8a0eb..b08e6078 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga1.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga1.java @@ -12,22 +12,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga2.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga2.java index f0f5ddab..ffa99059 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga2.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenTaiga2.java @@ -12,22 +12,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenTallGrass.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenTallGrass.java index af7c074a..5d2d43f7 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenTallGrass.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenTallGrass.java @@ -9,22 +9,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenTrees.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenTrees.java index 246f9243..402271c9 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenTrees.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenTrees.java @@ -16,22 +16,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,6 +63,28 @@ public class WorldGenTrees extends WorldGenAbstractTree { this.vinesGrow = parFlag2; } + private void func_181650_b(World parWorld, BlockPos parBlockPos, PropertyBool parPropertyBool) { + this.func_181651_a(parWorld, parBlockPos, parPropertyBool); + int i = 4; + + for (parBlockPos = parBlockPos + .down(); parWorld.getBlockState(parBlockPos).getBlock().getMaterial() == Material.air && i > 0; --i) { + this.func_181651_a(parWorld, parBlockPos, parPropertyBool); + parBlockPos = parBlockPos.down(); + } + + } + + private void func_181651_a(World parWorld, BlockPos parBlockPos, PropertyBool parPropertyBool) { + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, + Blocks.vine.getDefaultState().withProperty(parPropertyBool, Boolean.valueOf(true))); + } + + private void func_181652_a(World parWorld, int parInt1, BlockPos parBlockPos, EnumFacing parEnumFacing) { + this.setBlockAndNotifyAdequately(parWorld, parBlockPos, Blocks.cocoa.getDefaultState() + .withProperty(BlockCocoa.AGE, Integer.valueOf(parInt1)).withProperty(BlockCocoa.FACING, parEnumFacing)); + } + public boolean generate(World world, EaglercraftRandom random, BlockPos blockpos) { int i = random.nextInt(3) + this.minTreeHeight; boolean flag = true; @@ -211,26 +236,4 @@ public class WorldGenTrees extends WorldGenAbstractTree { return false; } } - - private void func_181652_a(World parWorld, int parInt1, BlockPos parBlockPos, EnumFacing parEnumFacing) { - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, Blocks.cocoa.getDefaultState() - .withProperty(BlockCocoa.AGE, Integer.valueOf(parInt1)).withProperty(BlockCocoa.FACING, parEnumFacing)); - } - - private void func_181651_a(World parWorld, BlockPos parBlockPos, PropertyBool parPropertyBool) { - this.setBlockAndNotifyAdequately(parWorld, parBlockPos, - Blocks.vine.getDefaultState().withProperty(parPropertyBool, Boolean.valueOf(true))); - } - - private void func_181650_b(World parWorld, BlockPos parBlockPos, PropertyBool parPropertyBool) { - this.func_181651_a(parWorld, parBlockPos, parPropertyBool); - int i = 4; - - for (parBlockPos = parBlockPos - .down(); parWorld.getBlockState(parBlockPos).getBlock().getMaterial() == Material.air && i > 0; --i) { - this.func_181651_a(parWorld, parBlockPos, parPropertyBool); - parBlockPos = parBlockPos.down(); - } - - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenVines.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenVines.java index 43c80d70..9ba98ca6 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenVines.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenVines.java @@ -8,22 +8,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenWaterlily.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenWaterlily.java index e6728112..7b2bf579 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenWaterlily.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenWaterlily.java @@ -5,22 +5,25 @@ import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGenerator.java b/src/game/java/net/minecraft/world/gen/feature/WorldGenerator.java index 4717ec17..8461c1d3 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGenerator.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGenerator.java @@ -5,22 +5,25 @@ import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,11 +39,11 @@ public abstract class WorldGenerator { this.doBlockNotify = notify; } - public abstract boolean generate(World var1, EaglercraftRandom var2, BlockPos var3); - public void func_175904_e() { } + public abstract boolean generate(World var1, EaglercraftRandom var2, BlockPos var3); + protected void setBlockAndNotifyAdequately(World worldIn, BlockPos pos, IBlockState state) { if (this.doBlockNotify) { worldIn.setBlockState(pos, state, 3); diff --git a/src/game/java/net/minecraft/world/gen/feature/WorldGeneratorBonusChest.java b/src/game/java/net/minecraft/world/gen/feature/WorldGeneratorBonusChest.java index 03adf5ae..4ae70615 100644 --- a/src/game/java/net/minecraft/world/gen/feature/WorldGeneratorBonusChest.java +++ b/src/game/java/net/minecraft/world/gen/feature/WorldGeneratorBonusChest.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen.feature; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.material.Material; @@ -11,22 +12,25 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayer.java b/src/game/java/net/minecraft/world/gen/layer/GenLayer.java index 8a3f3160..8737209d 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayer.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayer.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen.layer; import java.util.concurrent.Callable; + import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.util.ReportedException; @@ -8,31 +9,60 @@ import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.gen.ChunkProviderSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class GenLayer { - private long worldGenSeed; - protected GenLayer parent; - private long chunkSeed; - protected long baseSeed; + protected static boolean biomesEqualOrMesaPlateau(int biomeIDA, int biomeIDB) { + if (biomeIDA == biomeIDB) { + return true; + } else if (biomeIDA != BiomeGenBase.mesaPlateau_F.biomeID && biomeIDA != BiomeGenBase.mesaPlateau.biomeID) { + final BiomeGenBase biomegenbase = BiomeGenBase.getBiome(biomeIDA); + final BiomeGenBase biomegenbase1 = BiomeGenBase.getBiome(biomeIDB); + + try { + return biomegenbase != null && biomegenbase1 != null ? biomegenbase.isEqualTo(biomegenbase1) : false; + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Comparing biomes"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Biomes being compared"); + crashreportcategory.addCrashSection("Biome A ID", Integer.valueOf(biomeIDA)); + crashreportcategory.addCrashSection("Biome B ID", Integer.valueOf(biomeIDB)); + crashreportcategory.addCrashSectionCallable("Biome A", new Callable() { + public String call() throws Exception { + return String.valueOf(biomegenbase); + } + }); + crashreportcategory.addCrashSectionCallable("Biome B", new Callable() { + public String call() throws Exception { + return String.valueOf(biomegenbase1); + } + }); + throw new ReportedException(crashreport); + } + } else { + return biomeIDB == BiomeGenBase.mesaPlateau_F.biomeID || biomeIDB == BiomeGenBase.mesaPlateau.biomeID; + } + } public static GenLayer[] initializeAllBiomeGenerators(long seed, WorldType parWorldType, String parString1) { GenLayerIsland genlayerisland = new GenLayerIsland(1L); @@ -99,6 +129,22 @@ public abstract class GenLayer { return new GenLayer[] { genlayerrivermix, genlayervoronoizoom, genlayerrivermix }; } + /** + * + returns true if the biomeId is one of the various ocean biomes. + */ + protected static boolean isBiomeOceanic(int parInt1) { + return parInt1 == BiomeGenBase.ocean.biomeID || parInt1 == BiomeGenBase.deepOcean.biomeID + || parInt1 == BiomeGenBase.frozenOcean.biomeID; + } + + private long worldGenSeed; + + protected GenLayer parent; + + private long chunkSeed; + + protected long baseSeed; + public GenLayer(long parLong1) { this.baseSeed = parLong1; this.baseSeed *= this.baseSeed * 6364136223846793005L + 1442695040888963407L; @@ -109,10 +155,27 @@ public abstract class GenLayer { this.baseSeed += parLong1; } - /**+ - * Initialize layer's local worldGenSeed based on its own - * baseSeed and the world's global seed (passed in as an - * argument). + public abstract int[] getInts(int var1, int var2, int var3, int var4); + + /** + * + Initialize layer's current chunkSeed based on the local worldGenSeed and + * the (x,z) chunk coordinates. + */ + public void initChunkSeed(long parLong1, long parLong2) { + this.chunkSeed = this.worldGenSeed; + this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; + this.chunkSeed += parLong1; + this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; + this.chunkSeed += parLong2; + this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; + this.chunkSeed += parLong1; + this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; + this.chunkSeed += parLong2; + } + + /** + * + Initialize layer's local worldGenSeed based on its own baseSeed and the + * world's global seed (passed in as an argument). */ public void initWorldGenSeed(long seed) { this.worldGenSeed = seed; @@ -128,24 +191,8 @@ public abstract class GenLayer { this.worldGenSeed += this.baseSeed; } - /**+ - * Initialize layer's current chunkSeed based on the local - * worldGenSeed and the (x,z) chunk coordinates. - */ - public void initChunkSeed(long parLong1, long parLong2) { - this.chunkSeed = this.worldGenSeed; - this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; - this.chunkSeed += parLong1; - this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; - this.chunkSeed += parLong2; - this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; - this.chunkSeed += parLong1; - this.chunkSeed *= this.chunkSeed * 6364136223846793005L + 1442695040888963407L; - this.chunkSeed += parLong2; - } - - /**+ - * returns a LCG pseudo random number from [0, x). Args: int x + /** + * + returns a LCG pseudo random number from [0, x). Args: int x */ protected int nextInt(int parInt1) { int i = (int) ((this.chunkSeed >> 24) % (long) parInt1); @@ -158,58 +205,9 @@ public abstract class GenLayer { return i; } - public abstract int[] getInts(int var1, int var2, int var3, int var4); - - protected static boolean biomesEqualOrMesaPlateau(int biomeIDA, int biomeIDB) { - if (biomeIDA == biomeIDB) { - return true; - } else if (biomeIDA != BiomeGenBase.mesaPlateau_F.biomeID && biomeIDA != BiomeGenBase.mesaPlateau.biomeID) { - final BiomeGenBase biomegenbase = BiomeGenBase.getBiome(biomeIDA); - final BiomeGenBase biomegenbase1 = BiomeGenBase.getBiome(biomeIDB); - - try { - return biomegenbase != null && biomegenbase1 != null ? biomegenbase.isEqualTo(biomegenbase1) : false; - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Comparing biomes"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Biomes being compared"); - crashreportcategory.addCrashSection("Biome A ID", Integer.valueOf(biomeIDA)); - crashreportcategory.addCrashSection("Biome B ID", Integer.valueOf(biomeIDB)); - crashreportcategory.addCrashSectionCallable("Biome A", new Callable() { - public String call() throws Exception { - return String.valueOf(biomegenbase); - } - }); - crashreportcategory.addCrashSectionCallable("Biome B", new Callable() { - public String call() throws Exception { - return String.valueOf(biomegenbase1); - } - }); - throw new ReportedException(crashreport); - } - } else { - return biomeIDB == BiomeGenBase.mesaPlateau_F.biomeID || biomeIDB == BiomeGenBase.mesaPlateau.biomeID; - } - } - - /**+ - * returns true if the biomeId is one of the various ocean - * biomes. - */ - protected static boolean isBiomeOceanic(int parInt1) { - return parInt1 == BiomeGenBase.ocean.biomeID || parInt1 == BiomeGenBase.deepOcean.biomeID - || parInt1 == BiomeGenBase.frozenOcean.biomeID; - } - - /**+ - * selects a random integer from a set of provided integers - */ - protected int selectRandom(int... parArrayOfInt) { - return parArrayOfInt[this.nextInt(parArrayOfInt.length)]; - } - - /**+ - * returns the most frequently occurring number of the set, or a - * random number from those provided + /** + * + returns the most frequently occurring number of the set, or a random number + * from those provided */ protected int selectModeOrRandom(int i, int j, int k, int l) { return j == k && k == l ? j @@ -225,4 +223,11 @@ public abstract class GenLayer { : this.selectRandom(new int[] { i, j, k, l })))))))))); } + + /** + * + selects a random integer from a set of provided integers + */ + protected int selectRandom(int... parArrayOfInt) { + return parArrayOfInt[this.nextInt(parArrayOfInt.length)]; + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerAddIsland.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerAddIsland.java index 6138094a..fce0d1ed 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerAddIsland.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerAddIsland.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,11 +29,10 @@ public class GenLayerAddIsland extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i - 1; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerAddMushroomIsland.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerAddMushroomIsland.java index ba339521..49724467 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerAddMushroomIsland.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerAddMushroomIsland.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,10 @@ public class GenLayerAddMushroomIsland extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i - 1; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerAddSnow.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerAddSnow.java index 1b4f78bc..6b43ac76 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerAddSnow.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerAddSnow.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,11 +29,10 @@ public class GenLayerAddSnow extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i - 1; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerBiome.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerBiome.java index 00f890ce..a1ef9dbe 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerBiome.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerBiome.java @@ -4,22 +4,25 @@ import net.minecraft.world.WorldType; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.gen.ChunkProviderSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,11 +53,10 @@ public class GenLayerBiome extends GenLayer { } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.parent.getInts(i, j, k, l); diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerBiomeEdge.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerBiomeEdge.java index a9c1d9f8..66cdc4bf 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerBiomeEdge.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerBiomeEdge.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,32 @@ public class GenLayerBiomeEdge extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns if two biomes can logically be neighbors. If one is hot and the + * other cold, for example, it returns false. + */ + private boolean canBiomesBeNeighbors(int parInt1, int parInt2) { + if (biomesEqualOrMesaPlateau(parInt1, parInt2)) { + return true; + } else { + BiomeGenBase biomegenbase = BiomeGenBase.getBiome(parInt1); + BiomeGenBase biomegenbase1 = BiomeGenBase.getBiome(parInt2); + if (biomegenbase != null && biomegenbase1 != null) { + BiomeGenBase.TempCategory biomegenbase$tempcategory = biomegenbase.getTempCategory(); + BiomeGenBase.TempCategory biomegenbase$tempcategory1 = biomegenbase1.getTempCategory(); + return biomegenbase$tempcategory == biomegenbase$tempcategory1 + || biomegenbase$tempcategory == BiomeGenBase.TempCategory.MEDIUM + || biomegenbase$tempcategory1 == BiomeGenBase.TempCategory.MEDIUM; + } else { + return false; + } + } + } + + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.parent.getInts(i - 1, j - 1, k + 2, l + 2); @@ -91,32 +115,8 @@ public class GenLayerBiomeEdge extends GenLayer { return aint1; } - /**+ - * Creates a border around a biome if necessary, e.g. A - * transition from hot to cold climates would otherwise occur. - */ - private boolean replaceBiomeEdgeIfNecessary(int[] parArrayOfInt, int[] parArrayOfInt2, int parInt1, int parInt2, - int parInt3, int parInt4, int parInt5, int parInt6) { - if (!biomesEqualOrMesaPlateau(parInt4, parInt5)) { - return false; - } else { - int i = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 - 1) * (parInt3 + 2)]; - int j = parArrayOfInt[parInt1 + 1 + 1 + (parInt2 + 1) * (parInt3 + 2)]; - int k = parArrayOfInt[parInt1 + 1 - 1 + (parInt2 + 1) * (parInt3 + 2)]; - int l = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 + 1) * (parInt3 + 2)]; - if (this.canBiomesBeNeighbors(i, parInt5) && this.canBiomesBeNeighbors(j, parInt5) - && this.canBiomesBeNeighbors(k, parInt5) && this.canBiomesBeNeighbors(l, parInt5)) { - parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt4; - } else { - parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt6; - } - - return true; - } - } - - /**+ - * Creates a border around a biome. + /** + * + Creates a border around a biome. */ private boolean replaceBiomeEdge(int[] parArrayOfInt, int[] parArrayOfInt2, int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6) { @@ -138,25 +138,27 @@ public class GenLayerBiomeEdge extends GenLayer { } } - /**+ - * Returns if two biomes can logically be neighbors. If one is - * hot and the other cold, for example, it returns false. + /** + * + Creates a border around a biome if necessary, e.g. A transition from hot to + * cold climates would otherwise occur. */ - private boolean canBiomesBeNeighbors(int parInt1, int parInt2) { - if (biomesEqualOrMesaPlateau(parInt1, parInt2)) { - return true; + private boolean replaceBiomeEdgeIfNecessary(int[] parArrayOfInt, int[] parArrayOfInt2, int parInt1, int parInt2, + int parInt3, int parInt4, int parInt5, int parInt6) { + if (!biomesEqualOrMesaPlateau(parInt4, parInt5)) { + return false; } else { - BiomeGenBase biomegenbase = BiomeGenBase.getBiome(parInt1); - BiomeGenBase biomegenbase1 = BiomeGenBase.getBiome(parInt2); - if (biomegenbase != null && biomegenbase1 != null) { - BiomeGenBase.TempCategory biomegenbase$tempcategory = biomegenbase.getTempCategory(); - BiomeGenBase.TempCategory biomegenbase$tempcategory1 = biomegenbase1.getTempCategory(); - return biomegenbase$tempcategory == biomegenbase$tempcategory1 - || biomegenbase$tempcategory == BiomeGenBase.TempCategory.MEDIUM - || biomegenbase$tempcategory1 == BiomeGenBase.TempCategory.MEDIUM; + int i = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 - 1) * (parInt3 + 2)]; + int j = parArrayOfInt[parInt1 + 1 + 1 + (parInt2 + 1) * (parInt3 + 2)]; + int k = parArrayOfInt[parInt1 + 1 - 1 + (parInt2 + 1) * (parInt3 + 2)]; + int l = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 + 1) * (parInt3 + 2)]; + if (this.canBiomesBeNeighbors(i, parInt5) && this.canBiomesBeNeighbors(j, parInt5) + && this.canBiomesBeNeighbors(k, parInt5) && this.canBiomesBeNeighbors(l, parInt5)) { + parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt4; } else { - return false; + parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt6; } + + return true; } } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerDeepOcean.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerDeepOcean.java index 2a5173b9..76607658 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerDeepOcean.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerDeepOcean.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,10 @@ public class GenLayerDeepOcean extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int areaX, int areaY, int areaWidth, int areaHeight) { int i = areaX - 1; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerEdge.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerEdge.java index 895d7293..902b8387 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerEdge.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerEdge.java @@ -1,26 +1,33 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GenLayerEdge extends GenLayer { + public static enum Mode { + COOL_WARM, HEAT_ICE, SPECIAL; + } + private final GenLayerEdge.Mode field_151627_c; public GenLayerEdge(long parLong1, GenLayer parGenLayer, GenLayerEdge.Mode parMode) { @@ -29,11 +36,10 @@ public class GenLayerEdge extends GenLayer { this.field_151627_c = parMode; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { switch (this.field_151627_c) { @@ -126,8 +132,4 @@ public class GenLayerEdge extends GenLayer { return aint1; } - - public static enum Mode { - COOL_WARM, HEAT_ICE, SPECIAL; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerFuzzyZoom.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerFuzzyZoom.java index 8728d06d..66e3cd87 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerFuzzyZoom.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerFuzzyZoom.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,9 +28,9 @@ public class GenLayerFuzzyZoom extends GenLayerZoom { super(parLong1, parGenLayer); } - /**+ - * returns the most frequently occurring number of the set, or a - * random number from those provided + /** + * + returns the most frequently occurring number of the set, or a random number + * from those provided */ protected int selectModeOrRandom(int parInt1, int parInt2, int parInt3, int parInt4) { return this.selectRandom(new int[] { parInt1, parInt2, parInt3, parInt4 }); diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerHills.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerHills.java index c58de914..171b62d0 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerHills.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerHills.java @@ -1,25 +1,28 @@ package net.minecraft.world.gen.layer; -import net.minecraft.world.biome.BiomeGenBase; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,11 +37,10 @@ public class GenLayerHills extends GenLayer { this.field_151628_d = parGenLayer2; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.parent.getInts(i - 1, j - 1, k + 2, l + 2); diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerIsland.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerIsland.java index 680eb3ef..9ad09be0 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerIsland.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerIsland.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,11 +28,10 @@ public class GenLayerIsland extends GenLayer { super(parLong1); } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = IntCache.getIntCache(k * l); diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerRareBiome.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerRareBiome.java index 3cb5b016..7e05f6da 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerRareBiome.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerRareBiome.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,10 @@ public class GenLayerRareBiome extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.parent.getInts(i - 1, j - 1, k + 2, l + 2); diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerRemoveTooMuchOcean.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerRemoveTooMuchOcean.java index ebf3f86f..fa5f282b 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerRemoveTooMuchOcean.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerRemoveTooMuchOcean.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,11 +29,10 @@ public class GenLayerRemoveTooMuchOcean extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i - 1; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerRiver.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerRiver.java index 0762b658..050f92f3 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerRiver.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerRiver.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,11 +31,14 @@ public class GenLayerRiver extends GenLayer { super.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + private int func_151630_c(int parInt1) { + return parInt1 >= 2 ? 2 + (parInt1 & 1) : parInt1; + } + + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i - 1; @@ -59,8 +65,4 @@ public class GenLayerRiver extends GenLayer { return aint1; } - - private int func_151630_c(int parInt1) { - return parInt1 >= 2 ? 2 + (parInt1 & 1) : parInt1; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverInit.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverInit.java index f95bf1a8..1731936b 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverInit.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverInit.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,11 +29,10 @@ public class GenLayerRiverInit extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.parent.getInts(i, j, k, l); diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverMix.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverMix.java index 05691944..aa63df44 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverMix.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerRiverMix.java @@ -2,22 +2,25 @@ package net.minecraft.world.gen.layer; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,22 +35,10 @@ public class GenLayerRiverMix extends GenLayer { this.riverPatternGeneratorChain = parGenLayer2; } - /**+ - * Initialize layer's local worldGenSeed based on its own - * baseSeed and the world's global seed (passed in as an - * argument). - */ - public void initWorldGenSeed(long i) { - this.biomePatternGeneratorChain.initWorldGenSeed(i); - this.riverPatternGeneratorChain.initWorldGenSeed(i); - super.initWorldGenSeed(i); - } - - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.biomePatternGeneratorChain.getInts(i, j, k, l); @@ -75,4 +66,14 @@ public class GenLayerRiverMix extends GenLayer { return aint2; } + + /** + * + Initialize layer's local worldGenSeed based on its own baseSeed and the + * world's global seed (passed in as an argument). + */ + public void initWorldGenSeed(long i) { + this.biomePatternGeneratorChain.initWorldGenSeed(i); + this.riverPatternGeneratorChain.initWorldGenSeed(i); + super.initWorldGenSeed(i); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerShore.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerShore.java index ee77c8ca..c5f985c9 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerShore.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerShore.java @@ -4,22 +4,25 @@ import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.BiomeGenJungle; import net.minecraft.world.biome.BiomeGenMesa; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,11 +33,41 @@ public class GenLayerShore extends GenLayer { this.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + private boolean func_151631_c(int parInt1) { + return BiomeGenBase.getBiome(parInt1) != null + && BiomeGenBase.getBiome(parInt1).getBiomeClass() == BiomeGenJungle.class + ? true + : parInt1 == BiomeGenBase.jungleEdge.biomeID || parInt1 == BiomeGenBase.jungle.biomeID + || parInt1 == BiomeGenBase.jungleHills.biomeID || parInt1 == BiomeGenBase.forest.biomeID + || parInt1 == BiomeGenBase.taiga.biomeID || isBiomeOceanic(parInt1); + } + + private void func_151632_a(int[] parArrayOfInt, int[] parArrayOfInt2, int parInt1, int parInt2, int parInt3, + int parInt4, int parInt5) { + if (isBiomeOceanic(parInt4)) { + parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt4; + } else { + int i = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 - 1) * (parInt3 + 2)]; + int j = parArrayOfInt[parInt1 + 1 + 1 + (parInt2 + 1) * (parInt3 + 2)]; + int k = parArrayOfInt[parInt1 + 1 - 1 + (parInt2 + 1) * (parInt3 + 2)]; + int l = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 + 1) * (parInt3 + 2)]; + if (!isBiomeOceanic(i) && !isBiomeOceanic(j) && !isBiomeOceanic(k) && !isBiomeOceanic(l)) { + parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt4; + } else { + parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt5; + } + + } + } + + private boolean func_151633_d(int parInt1) { + return BiomeGenBase.getBiome(parInt1) instanceof BiomeGenMesa; + } + + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int[] aint = this.parent.getInts(i - 1, j - 1, k + 2, l + 2); @@ -115,35 +148,4 @@ public class GenLayerShore extends GenLayer { return aint1; } - - private void func_151632_a(int[] parArrayOfInt, int[] parArrayOfInt2, int parInt1, int parInt2, int parInt3, - int parInt4, int parInt5) { - if (isBiomeOceanic(parInt4)) { - parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt4; - } else { - int i = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 - 1) * (parInt3 + 2)]; - int j = parArrayOfInt[parInt1 + 1 + 1 + (parInt2 + 1) * (parInt3 + 2)]; - int k = parArrayOfInt[parInt1 + 1 - 1 + (parInt2 + 1) * (parInt3 + 2)]; - int l = parArrayOfInt[parInt1 + 1 + (parInt2 + 1 + 1) * (parInt3 + 2)]; - if (!isBiomeOceanic(i) && !isBiomeOceanic(j) && !isBiomeOceanic(k) && !isBiomeOceanic(l)) { - parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt4; - } else { - parArrayOfInt2[parInt1 + parInt2 * parInt3] = parInt5; - } - - } - } - - private boolean func_151631_c(int parInt1) { - return BiomeGenBase.getBiome(parInt1) != null - && BiomeGenBase.getBiome(parInt1).getBiomeClass() == BiomeGenJungle.class - ? true - : parInt1 == BiomeGenBase.jungleEdge.biomeID || parInt1 == BiomeGenBase.jungle.biomeID - || parInt1 == BiomeGenBase.jungleHills.biomeID || parInt1 == BiomeGenBase.forest.biomeID - || parInt1 == BiomeGenBase.taiga.biomeID || isBiomeOceanic(parInt1); - } - - private boolean func_151633_d(int parInt1) { - return BiomeGenBase.getBiome(parInt1) instanceof BiomeGenMesa; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerSmooth.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerSmooth.java index e372cd02..abe69e9f 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerSmooth.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerSmooth.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,11 +29,10 @@ public class GenLayerSmooth extends GenLayer { super.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i - 1; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerVoronoiZoom.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerVoronoiZoom.java index f0f28278..28434fb8 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerVoronoiZoom.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerVoronoiZoom.java @@ -1,21 +1,24 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,11 +29,10 @@ public class GenLayerVoronoiZoom extends GenLayer { super.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { i = i - 2; diff --git a/src/game/java/net/minecraft/world/gen/layer/GenLayerZoom.java b/src/game/java/net/minecraft/world/gen/layer/GenLayerZoom.java index 68b0c294..08cccf9f 100644 --- a/src/game/java/net/minecraft/world/gen/layer/GenLayerZoom.java +++ b/src/game/java/net/minecraft/world/gen/layer/GenLayerZoom.java @@ -1,36 +1,52 @@ package net.minecraft.world.gen.layer; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GenLayerZoom extends GenLayer { + /** + * + Magnify a layer. Parms are seed adjustment, layer, number of times to + * magnify + */ + public static GenLayer magnify(long parLong1, GenLayer parGenLayer, int parInt1) { + Object object = parGenLayer; + + for (int i = 0; i < parInt1; ++i) { + object = new GenLayerZoom(parLong1 + (long) i, (GenLayer) object); + } + + return (GenLayer) object; + } + public GenLayerZoom(long parLong1, GenLayer parGenLayer) { super(parLong1); super.parent = parGenLayer; } - /**+ - * Returns a list of integer values generated by this layer. - * These may be interpreted as temperatures, rainfall amounts, - * or biomeList[] indices based on the particular GenLayer - * subclass. + /** + * + Returns a list of integer values generated by this layer. These may be + * interpreted as temperatures, rainfall amounts, or biomeList[] indices based + * on the particular GenLayer subclass. */ public int[] getInts(int i, int j, int k, int l) { int i1 = i >> 1; @@ -68,18 +84,4 @@ public class GenLayerZoom extends GenLayer { return aint2; } - - /**+ - * Magnify a layer. Parms are seed adjustment, layer, number of - * times to magnify - */ - public static GenLayer magnify(long parLong1, GenLayer parGenLayer, int parInt1) { - Object object = parGenLayer; - - for (int i = 0; i < parInt1; ++i) { - object = new GenLayerZoom(parLong1 + (long) i, (GenLayer) object); - } - - return (GenLayer) object; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/layer/IntCache.java b/src/game/java/net/minecraft/world/gen/layer/IntCache.java index e2cd18e0..e9e375f5 100644 --- a/src/game/java/net/minecraft/world/gen/layer/IntCache.java +++ b/src/game/java/net/minecraft/world/gen/layer/IntCache.java @@ -1,53 +1,66 @@ package net.minecraft.world.gen.layer; -import com.google.common.collect.Lists; import java.util.List; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +import com.google.common.collect.Lists; + +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IntCache { private static int intCacheSize = 256; - /**+ - * A list of pre-allocated int[256] arrays that are currently - * unused and can be returned by getIntCache() + /** + * + A list of pre-allocated int[256] arrays that are currently unused and can + * be returned by getIntCache() */ private static List freeSmallArrays = Lists.newArrayList(); - /**+ - * A list of pre-allocated int[256] arrays that were previously - * returned by getIntCache() and which will not be re-used again - * until resetIntCache() is called. + /** + * + A list of pre-allocated int[256] arrays that were previously returned by + * getIntCache() and which will not be re-used again until resetIntCache() is + * called. */ private static List inUseSmallArrays = Lists.newArrayList(); - /**+ - * A list of pre-allocated int[cacheSize] arrays that are - * currently unused and can be returned by getIntCache() + /** + * + A list of pre-allocated int[cacheSize] arrays that are currently unused and + * can be returned by getIntCache() */ private static List freeLargeArrays = Lists.newArrayList(); - /**+ - * A list of pre-allocated int[cacheSize] arrays that were - * previously returned by getIntCache() and which will not be - * re-used again until resetIntCache() is called. + /** + * + A list of pre-allocated int[cacheSize] arrays that were previously returned + * by getIntCache() and which will not be re-used again until resetIntCache() is + * called. */ private static List inUseLargeArrays = Lists.newArrayList(); + /** + * + Gets a human-readable string that indicates the sizes of all the cache + * fields. Basically a synchronized static toString. + */ + public static synchronized String getCacheSizes() { + return "cache: " + freeLargeArrays.size() + ", tcache: " + freeSmallArrays.size() + ", allocated: " + + inUseLargeArrays.size() + ", tallocated: " + inUseSmallArrays.size(); + } + public static synchronized int[] getIntCache(int parInt1) { if (parInt1 <= 256) { if (freeSmallArrays.isEmpty()) { @@ -77,9 +90,9 @@ public class IntCache { } } - /**+ - * Mark all pre-allocated arrays as available for re-use by - * moving them to the appropriate free lists. + /** + * + Mark all pre-allocated arrays as available for re-use by moving them to the + * appropriate free lists. */ public static synchronized void resetIntCache() { if (!freeLargeArrays.isEmpty()) { @@ -95,13 +108,4 @@ public class IntCache { inUseLargeArrays.clear(); inUseSmallArrays.clear(); } - - /**+ - * Gets a human-readable string that indicates the sizes of all - * the cache fields. Basically a synchronized static toString. - */ - public static synchronized String getCacheSizes() { - return "cache: " + freeLargeArrays.size() + ", tcache: " + freeSmallArrays.size() + ", allocated: " - + inUseLargeArrays.size() + ", tallocated: " + inUseSmallArrays.size(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/ComponentScatteredFeaturePieces.java b/src/game/java/net/minecraft/world/gen/structure/ComponentScatteredFeaturePieces.java index de1aa759..96d7a52b 100644 --- a/src/game/java/net/minecraft/world/gen/structure/ComponentScatteredFeaturePieces.java +++ b/src/game/java/net/minecraft/world/gen/structure/ComponentScatteredFeaturePieces.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockFlowerPot; import net.minecraft.block.BlockLever; @@ -22,35 +24,31 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ComponentScatteredFeaturePieces { - public static void registerScatteredFeaturePieces() { - MapGenStructureIO.registerStructureComponent(ComponentScatteredFeaturePieces.DesertPyramid.class, "TeDP"); - MapGenStructureIO.registerStructureComponent(ComponentScatteredFeaturePieces.JunglePyramid.class, "TeJP"); - MapGenStructureIO.registerStructureComponent(ComponentScatteredFeaturePieces.SwampHut.class, "TeSH"); - } - public static class DesertPyramid extends ComponentScatteredFeaturePieces.Feature { - private boolean[] field_74940_h = new boolean[4]; private static final List itemsToGenerateInTemple = Lists.newArrayList( new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.diamond, 0, 1, 3, 3), new WeightedRandomChestContent(Items.iron_ingot, 0, 1, 5, 10), @@ -62,6 +60,7 @@ public class ComponentScatteredFeaturePieces { new WeightedRandomChestContent(Items.iron_horse_armor, 0, 1, 1, 1), new WeightedRandomChestContent(Items.golden_horse_armor, 0, 1, 1, 1), new WeightedRandomChestContent(Items.diamond_horse_armor, 0, 1, 1, 1) }); + private boolean[] field_74940_h = new boolean[4]; public DesertPyramid() { } @@ -70,22 +69,6 @@ public class ComponentScatteredFeaturePieces { super(parRandom, parInt1, 64, parInt2, 21, 15, 21); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("hasPlacedChest0", this.field_74940_h[0]); - nbttagcompound.setBoolean("hasPlacedChest1", this.field_74940_h[1]); - nbttagcompound.setBoolean("hasPlacedChest2", this.field_74940_h[2]); - nbttagcompound.setBoolean("hasPlacedChest3", this.field_74940_h[3]); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.field_74940_h[0] = nbttagcompound.getBoolean("hasPlacedChest0"); - this.field_74940_h[1] = nbttagcompound.getBoolean("hasPlacedChest1"); - this.field_74940_h[2] = nbttagcompound.getBoolean("hasPlacedChest2"); - this.field_74940_h[3] = nbttagcompound.getBoolean("hasPlacedChest3"); - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, -4, 0, this.scatteredFeatureSizeX - 1, 0, @@ -456,6 +439,22 @@ public class ComponentScatteredFeaturePieces { return true; } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_74940_h[0] = nbttagcompound.getBoolean("hasPlacedChest0"); + this.field_74940_h[1] = nbttagcompound.getBoolean("hasPlacedChest1"); + this.field_74940_h[2] = nbttagcompound.getBoolean("hasPlacedChest2"); + this.field_74940_h[3] = nbttagcompound.getBoolean("hasPlacedChest3"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("hasPlacedChest0", this.field_74940_h[0]); + nbttagcompound.setBoolean("hasPlacedChest1", this.field_74940_h[1]); + nbttagcompound.setBoolean("hasPlacedChest2", this.field_74940_h[2]); + nbttagcompound.setBoolean("hasPlacedChest3", this.field_74940_h[3]); + } } abstract static class Feature extends StructureComponent { @@ -487,20 +486,6 @@ public class ComponentScatteredFeaturePieces { } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("Width", this.scatteredFeatureSizeX); - nbttagcompound.setInteger("Height", this.scatteredFeatureSizeY); - nbttagcompound.setInteger("Depth", this.scatteredFeatureSizeZ); - nbttagcompound.setInteger("HPos", this.field_74936_d); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - this.scatteredFeatureSizeX = nbttagcompound.getInteger("Width"); - this.scatteredFeatureSizeY = nbttagcompound.getInteger("Height"); - this.scatteredFeatureSizeZ = nbttagcompound.getInteger("Depth"); - this.field_74936_d = nbttagcompound.getInteger("HPos"); - } - protected boolean func_74935_a(World worldIn, StructureBoundingBox parStructureBoundingBox, int parInt1) { if (this.field_74936_d >= 0) { return true; @@ -529,13 +514,37 @@ public class ComponentScatteredFeaturePieces { } } } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + this.scatteredFeatureSizeX = nbttagcompound.getInteger("Width"); + this.scatteredFeatureSizeY = nbttagcompound.getInteger("Height"); + this.scatteredFeatureSizeZ = nbttagcompound.getInteger("Depth"); + this.field_74936_d = nbttagcompound.getInteger("HPos"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("Width", this.scatteredFeatureSizeX); + nbttagcompound.setInteger("Height", this.scatteredFeatureSizeY); + nbttagcompound.setInteger("Depth", this.scatteredFeatureSizeZ); + nbttagcompound.setInteger("HPos", this.field_74936_d); + } } public static class JunglePyramid extends ComponentScatteredFeaturePieces.Feature { - private boolean field_74947_h; - private boolean field_74948_i; - private boolean field_74945_j; - private boolean field_74946_k; + static class Stones extends StructureComponent.BlockSelector { + private Stones() { + } + + public void selectBlocks(EaglercraftRandom rand, int x, int y, int z, boolean parFlag) { + if (rand.nextFloat() < 0.4F) { + this.blockstate = Blocks.cobblestone.getDefaultState(); + } else { + this.blockstate = Blocks.mossy_cobblestone.getDefaultState(); + } + + } + } + private static final List field_175816_i = Lists.newArrayList( new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.diamond, 0, 1, 3, 3), new WeightedRandomChestContent(Items.iron_ingot, 0, 1, 5, 10), @@ -550,6 +559,11 @@ public class ComponentScatteredFeaturePieces { private static final List field_175815_j = Lists.newArrayList( new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.arrow, 0, 2, 7, 30) }); private static ComponentScatteredFeaturePieces.JunglePyramid.Stones junglePyramidsRandomScatteredStones = new ComponentScatteredFeaturePieces.JunglePyramid.Stones(); + private boolean field_74947_h; + private boolean field_74948_i; + private boolean field_74945_j; + + private boolean field_74946_k; public JunglePyramid() { } @@ -558,22 +572,6 @@ public class ComponentScatteredFeaturePieces { super(parRandom, parInt1, 64, parInt2, 12, 10, 15); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("placedMainChest", this.field_74947_h); - nbttagcompound.setBoolean("placedHiddenChest", this.field_74948_i); - nbttagcompound.setBoolean("placedTrap1", this.field_74945_j); - nbttagcompound.setBoolean("placedTrap2", this.field_74946_k); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.field_74947_h = nbttagcompound.getBoolean("placedMainChest"); - this.field_74948_i = nbttagcompound.getBoolean("placedHiddenChest"); - this.field_74945_j = nbttagcompound.getBoolean("placedTrap1"); - this.field_74946_k = nbttagcompound.getBoolean("placedTrap2"); - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (!this.func_74935_a(world, structureboundingbox, 0)) { @@ -853,18 +851,20 @@ public class ComponentScatteredFeaturePieces { } } - static class Stones extends StructureComponent.BlockSelector { - private Stones() { - } + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_74947_h = nbttagcompound.getBoolean("placedMainChest"); + this.field_74948_i = nbttagcompound.getBoolean("placedHiddenChest"); + this.field_74945_j = nbttagcompound.getBoolean("placedTrap1"); + this.field_74946_k = nbttagcompound.getBoolean("placedTrap2"); + } - public void selectBlocks(EaglercraftRandom rand, int x, int y, int z, boolean parFlag) { - if (rand.nextFloat() < 0.4F) { - this.blockstate = Blocks.cobblestone.getDefaultState(); - } else { - this.blockstate = Blocks.mossy_cobblestone.getDefaultState(); - } - - } + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("placedMainChest", this.field_74947_h); + nbttagcompound.setBoolean("placedHiddenChest", this.field_74948_i); + nbttagcompound.setBoolean("placedTrap1", this.field_74945_j); + nbttagcompound.setBoolean("placedTrap2", this.field_74946_k); } } @@ -878,16 +878,6 @@ public class ComponentScatteredFeaturePieces { super(parRandom, parInt1, 64, parInt2, 7, 7, 9); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Witch", this.hasWitch); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.hasWitch = nbttagcompound.getBoolean("Witch"); - } - public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { if (!this.func_74935_a(world, structureboundingbox, 0)) { @@ -971,5 +961,21 @@ public class ComponentScatteredFeaturePieces { return true; } } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.hasWitch = nbttagcompound.getBoolean("Witch"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Witch", this.hasWitch); + } + } + + public static void registerScatteredFeaturePieces() { + MapGenStructureIO.registerStructureComponent(ComponentScatteredFeaturePieces.DesertPyramid.class, "TeDP"); + MapGenStructureIO.registerStructureComponent(ComponentScatteredFeaturePieces.JunglePyramid.class, "TeJP"); + MapGenStructureIO.registerStructureComponent(ComponentScatteredFeaturePieces.SwampHut.class, "TeSH"); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenMineshaft.java b/src/game/java/net/minecraft/world/gen/structure/MapGenMineshaft.java index 65ffb955..85798c0d 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenMineshaft.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenMineshaft.java @@ -2,24 +2,28 @@ package net.minecraft.world.gen.structure; import java.util.Map; import java.util.Map.Entry; + import net.minecraft.util.MathHelper; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,10 +35,6 @@ public class MapGenMineshaft extends MapGenStructure { super(scramble); } - public String getStructureName() { - return "Mineshaft"; - } - public MapGenMineshaft(Map parMap, boolean scramble) { super(scramble); for (Entry entry : parMap.entrySet()) { @@ -50,6 +50,10 @@ public class MapGenMineshaft extends MapGenStructure { && this.rand.nextInt(80) < Math.max(Math.abs(chunkX), Math.abs(chunkZ)); } + public String getStructureName() { + return "Mineshaft"; + } + protected StructureStart getStructureStart(int chunkX, int chunkZ) { return new StructureMineshaftStart(this.worldObj, this.rand, chunkX, chunkZ); } diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenNetherBridge.java b/src/game/java/net/minecraft/world/gen/structure/MapGenNetherBridge.java index d6fa67d2..608b7e2f 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenNetherBridge.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenNetherBridge.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.entity.monster.EntityBlaze; import net.minecraft.entity.monster.EntityMagmaCube; @@ -10,58 +12,30 @@ import net.minecraft.entity.monster.EntitySkeleton; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapGenNetherBridge extends MapGenStructure { - private List spawnList = Lists.newArrayList(); - - public MapGenNetherBridge(boolean scramble) { - super(scramble); - this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntityBlaze.class, 10, 2, 3)); - this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntityPigZombie.class, 5, 4, 4)); - this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntitySkeleton.class, 10, 4, 4)); - this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntityMagmaCube.class, 3, 4, 4)); - } - - public String getStructureName() { - return "Fortress"; - } - - public List getSpawnList() { - return this.spawnList; - } - - protected boolean canSpawnStructureAtCoords(int i, int j) { - int k = i >> 4; - int l = j >> 4; - this.rand.setSeed((long) (k ^ l << 4) ^ this.worldObj.getSeed()); - this.rand.nextInt(); - return this.rand.nextInt(3) != 0 ? false - : (i != (k << 4) + 4 + this.rand.nextInt(8) ? false : j == (l << 4) + 4 + this.rand.nextInt(8)); - } - - protected StructureStart getStructureStart(int i, int j) { - return new MapGenNetherBridge.Start(this.worldObj, this.rand, i, j); - } - public static class Start extends StructureStart { public Start() { } @@ -85,4 +59,35 @@ public class MapGenNetherBridge extends MapGenStructure { this.setRandomHeight(worldIn, parRandom, 48, 70); } } + + private List spawnList = Lists.newArrayList(); + + public MapGenNetherBridge(boolean scramble) { + super(scramble); + this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntityBlaze.class, 10, 2, 3)); + this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntityPigZombie.class, 5, 4, 4)); + this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntitySkeleton.class, 10, 4, 4)); + this.spawnList.add(new BiomeGenBase.SpawnListEntry(EntityMagmaCube.class, 3, 4, 4)); + } + + protected boolean canSpawnStructureAtCoords(int i, int j) { + int k = i >> 4; + int l = j >> 4; + this.rand.setSeed((long) (k ^ l << 4) ^ this.worldObj.getSeed()); + this.rand.nextInt(); + return this.rand.nextInt(3) != 0 ? false + : (i != (k << 4) + 4 + this.rand.nextInt(8) ? false : j == (l << 4) + 4 + this.rand.nextInt(8)); + } + + public List getSpawnList() { + return this.spawnList; + } + + public String getStructureName() { + return "Fortress"; + } + + protected StructureStart getStructureStart(int i, int j) { + return new MapGenNetherBridge.Start(this.worldObj, this.rand, i, j); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenScatteredFeature.java b/src/game/java/net/minecraft/world/gen/structure/MapGenScatteredFeature.java index 3fbe5217..f7dde44e 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenScatteredFeature.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenScatteredFeature.java @@ -1,42 +1,76 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Map.Entry; + +import com.google.common.collect.Lists; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.entity.monster.EntityWitch; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapGenScatteredFeature extends MapGenStructure { + public static class Start extends StructureStart { + public Start() { + } + + public Start(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { + super(parInt1, parInt2); + BiomeGenBase biomegenbase = worldIn + .getBiomeGenForCoords(new BlockPos(parInt1 * 16 + 8, 0, parInt2 * 16 + 8)); + if (biomegenbase != BiomeGenBase.jungle && biomegenbase != BiomeGenBase.jungleHills) { + if (biomegenbase == BiomeGenBase.swampland) { + ComponentScatteredFeaturePieces.SwampHut componentscatteredfeaturepieces$swamphut = new ComponentScatteredFeaturePieces.SwampHut( + parRandom, parInt1 * 16, parInt2 * 16); + this.components.add(componentscatteredfeaturepieces$swamphut); + } else if (biomegenbase == BiomeGenBase.desert || biomegenbase == BiomeGenBase.desertHills) { + ComponentScatteredFeaturePieces.DesertPyramid componentscatteredfeaturepieces$desertpyramid = new ComponentScatteredFeaturePieces.DesertPyramid( + parRandom, parInt1 * 16, parInt2 * 16); + this.components.add(componentscatteredfeaturepieces$desertpyramid); + } + } else { + ComponentScatteredFeaturePieces.JunglePyramid componentscatteredfeaturepieces$junglepyramid = new ComponentScatteredFeaturePieces.JunglePyramid( + parRandom, parInt1 * 16, parInt2 * 16); + this.components.add(componentscatteredfeaturepieces$junglepyramid); + } + + this.updateBoundingBox(); + } + } + private static final List biomelist = Arrays.asList(new BiomeGenBase[] { BiomeGenBase.desert, BiomeGenBase.desertHills, BiomeGenBase.jungle, BiomeGenBase.jungleHills, BiomeGenBase.swampland }); private List scatteredFeatureSpawnList; private int maxDistanceBetweenScatteredFeatures; + private int minDistanceBetweenScatteredFeatures; public MapGenScatteredFeature(boolean scramble) { @@ -60,10 +94,6 @@ public class MapGenScatteredFeature extends MapGenStructure { } - public String getStructureName() { - return "Temple"; - } - protected boolean canSpawnStructureAtCoords(int i, int j) { int k = i; int l = j; @@ -99,10 +129,6 @@ public class MapGenScatteredFeature extends MapGenStructure { return false; } - protected StructureStart getStructureStart(int i, int j) { - return new MapGenScatteredFeature.Start(this.worldObj, this.rand, i, j); - } - public boolean func_175798_a(BlockPos parBlockPos) { StructureStart structurestart = this.func_175797_c(parBlockPos); if (structurestart != null && structurestart instanceof MapGenScatteredFeature.Start @@ -114,38 +140,18 @@ public class MapGenScatteredFeature extends MapGenStructure { } } - /**+ - * returns possible spawns for scattered features + /** + * + returns possible spawns for scattered features */ public List getScatteredFeatureSpawnList() { return this.scatteredFeatureSpawnList; } - public static class Start extends StructureStart { - public Start() { - } + public String getStructureName() { + return "Temple"; + } - public Start(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { - super(parInt1, parInt2); - BiomeGenBase biomegenbase = worldIn - .getBiomeGenForCoords(new BlockPos(parInt1 * 16 + 8, 0, parInt2 * 16 + 8)); - if (biomegenbase != BiomeGenBase.jungle && biomegenbase != BiomeGenBase.jungleHills) { - if (biomegenbase == BiomeGenBase.swampland) { - ComponentScatteredFeaturePieces.SwampHut componentscatteredfeaturepieces$swamphut = new ComponentScatteredFeaturePieces.SwampHut( - parRandom, parInt1 * 16, parInt2 * 16); - this.components.add(componentscatteredfeaturepieces$swamphut); - } else if (biomegenbase == BiomeGenBase.desert || biomegenbase == BiomeGenBase.desertHills) { - ComponentScatteredFeaturePieces.DesertPyramid componentscatteredfeaturepieces$desertpyramid = new ComponentScatteredFeaturePieces.DesertPyramid( - parRandom, parInt1 * 16, parInt2 * 16); - this.components.add(componentscatteredfeaturepieces$desertpyramid); - } - } else { - ComponentScatteredFeaturePieces.JunglePyramid componentscatteredfeaturepieces$junglepyramid = new ComponentScatteredFeaturePieces.JunglePyramid( - parRandom, parInt1 * 16, parInt2 * 16); - this.components.add(componentscatteredfeaturepieces$junglepyramid); - } - - this.updateBoundingBox(); - } + protected StructureStart getStructureStart(int i, int j) { + return new MapGenScatteredFeature.Start(this.worldObj, this.rand, i, j); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenStronghold.java b/src/game/java/net/minecraft/world/gen/structure/MapGenStronghold.java index e75ce5a0..bec68185 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenStronghold.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenStronghold.java @@ -1,42 +1,73 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Map.Entry; + +import com.google.common.collect.Lists; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapGenStronghold extends MapGenStructure { + public static class Start extends StructureStart { + public Start() { + } + + public Start(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { + super(parInt1, parInt2); + StructureStrongholdPieces.prepareStructurePieces(); + StructureStrongholdPieces.Stairs2 structurestrongholdpieces$stairs2 = new StructureStrongholdPieces.Stairs2( + 0, parRandom, (parInt1 << 4) + 2, (parInt2 << 4) + 2); + this.components.add(structurestrongholdpieces$stairs2); + structurestrongholdpieces$stairs2.buildComponent(structurestrongholdpieces$stairs2, this.components, + parRandom); + List list = structurestrongholdpieces$stairs2.field_75026_c; + + while (!list.isEmpty()) { + int i = parRandom.nextInt(list.size()); + StructureComponent structurecomponent = (StructureComponent) list.remove(i); + structurecomponent.buildComponent(structurestrongholdpieces$stairs2, this.components, parRandom); + } + + this.updateBoundingBox(); + this.markAvailableHeight(worldIn, parRandom, 10); + } + } + private List field_151546_e; private boolean ranBiomeCheck; private ChunkCoordIntPair[] structureCoords; private double field_82671_h; + private int field_82672_i; public MapGenStronghold(boolean scramble) { @@ -74,10 +105,6 @@ public class MapGenStronghold extends MapGenStructure { } - public String getStructureName() { - return "Stronghold"; - } - protected boolean canSpawnStructureAtCoords(int i, int j) { if (!this.ranBiomeCheck) { EaglercraftRandom random = new EaglercraftRandom(!this.worldObj.getWorldInfo().isOldEaglercraftRandom()); @@ -117,10 +144,9 @@ public class MapGenStronghold extends MapGenStructure { return false; } - /**+ - * Returns a list of other locations at which the structure - * generation has been run, or null if not relevant to this - * structure generator. + /** + * + Returns a list of other locations at which the structure generation has + * been run, or null if not relevant to this structure generator. */ protected List getCoordList() { ArrayList arraylist = Lists.newArrayList(); @@ -135,6 +161,10 @@ public class MapGenStronghold extends MapGenStructure { return arraylist; } + public String getStructureName() { + return "Stronghold"; + } + protected StructureStart getStructureStart(int i, int j) { MapGenStronghold.Start mapgenstronghold$start; for (mapgenstronghold$start = new MapGenStronghold.Start(this.worldObj, this.rand, i, j); mapgenstronghold$start @@ -147,29 +177,4 @@ public class MapGenStronghold extends MapGenStructure { return mapgenstronghold$start; } - - public static class Start extends StructureStart { - public Start() { - } - - public Start(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { - super(parInt1, parInt2); - StructureStrongholdPieces.prepareStructurePieces(); - StructureStrongholdPieces.Stairs2 structurestrongholdpieces$stairs2 = new StructureStrongholdPieces.Stairs2( - 0, parRandom, (parInt1 << 4) + 2, (parInt2 << 4) + 2); - this.components.add(structurestrongholdpieces$stairs2); - structurestrongholdpieces$stairs2.buildComponent(structurestrongholdpieces$stairs2, this.components, - parRandom); - List list = structurestrongholdpieces$stairs2.field_75026_c; - - while (!list.isEmpty()) { - int i = parRandom.nextInt(list.size()); - StructureComponent structurecomponent = (StructureComponent) list.remove(i); - structurecomponent.buildComponent(structurestrongholdpieces$stairs2, this.components, parRandom); - } - - this.updateBoundingBox(); - this.markAvailableHeight(worldIn, parRandom, 10); - } - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenStructure.java b/src/game/java/net/minecraft/world/gen/structure/MapGenStructure.java index ce6eb43b..1640d39f 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenStructure.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenStructure.java @@ -1,14 +1,14 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Maps; - import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.concurrent.Callable; + +import com.google.common.collect.Maps; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.HString; - -import java.util.concurrent.Callable; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.nbt.NBTBase; @@ -20,22 +20,25 @@ import net.minecraft.world.World; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.MapGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,8 +47,6 @@ public abstract class MapGenStructure extends MapGenBase { private MapGenStructureData structureData; protected Map structureMap = Maps.newHashMap(); - public abstract String getStructureName(); - public MapGenStructure() { super(); } @@ -54,65 +55,43 @@ public abstract class MapGenStructure extends MapGenBase { super(scramble); } - /**+ - * Recursively called by generate() - */ - protected final void recursiveGenerate(World world, final int i, final int j, int var4, int var5, - ChunkPrimer var6) { - this.func_143027_a(world); - if (!this.structureMap.containsKey(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)))) { - this.rand.nextInt(); + protected abstract boolean canSpawnStructureAtCoords(int var1, int var2); - try { - if (this.canSpawnStructureAtCoords(i, j)) { - StructureStart structurestart = this.getStructureStart(i, j); - this.structureMap.put(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)), structurestart); - this.func_143026_a(i, j, structurestart); - } - - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, - "Exception preparing structure feature"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Feature being prepared"); - crashreportcategory.addCrashSectionCallable("Is feature chunk", new Callable() { - public String call() throws Exception { - return MapGenStructure.this.canSpawnStructureAtCoords(i, j) ? "True" : "False"; - } - }); - crashreportcategory.addCrashSection("Chunk location", - HString.format("%d,%d", new Object[] { Integer.valueOf(i), Integer.valueOf(j) })); - crashreportcategory.addCrashSectionCallable("Chunk pos hash", new Callable() { - public String call() throws Exception { - return String.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)); - } - }); - crashreportcategory.addCrashSectionCallable("Structure type", new Callable() { - public String call() throws Exception { - return MapGenStructure.this.getClass().getCanonicalName(); - } - }); - throw new ReportedException(crashreport); - } - } + private void func_143026_a(int start, int parInt2, StructureStart parStructureStart) { + this.structureData.writeInstance(parStructureStart.writeStructureComponentsToNBT(start, parInt2), start, + parInt2); + this.structureData.markDirty(); } - public boolean generateStructure(World worldIn, EaglercraftRandom randomIn, ChunkCoordIntPair chunkCoord) { - this.func_143027_a(worldIn); - int i = (chunkCoord.chunkXPos << 4) + 8; - int j = (chunkCoord.chunkZPos << 4) + 8; - boolean flag = false; + private void func_143027_a(World worldIn) { + if (this.structureData == null) { + this.structureData = (MapGenStructureData) worldIn.loadItemData(MapGenStructureData.class, + this.getStructureName()); + if (this.structureData == null) { + this.structureData = new MapGenStructureData(this.getStructureName()); + worldIn.setItemData(this.getStructureName(), this.structureData); + } else { + NBTTagCompound nbttagcompound = this.structureData.getTagCompound(); - for (StructureStart structurestart : this.structureMap.values()) { - if (structurestart.isSizeableStructure() && structurestart.func_175788_a(chunkCoord) - && structurestart.getBoundingBox().intersectsWith(i, j, i + 15, j + 15)) { - structurestart.generateStructure(worldIn, randomIn, new StructureBoundingBox(i, j, i + 15, j + 15)); - structurestart.func_175787_b(chunkCoord); - flag = true; - this.func_143026_a(structurestart.getChunkPosX(), structurestart.getChunkPosZ(), structurestart); + for (String s : nbttagcompound.getKeySet()) { + NBTBase nbtbase = nbttagcompound.getTag(s); + if (nbtbase.getId() == 10) { + NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbtbase; + if (nbttagcompound1.hasKey("ChunkX") && nbttagcompound1.hasKey("ChunkZ")) { + int i = nbttagcompound1.getInteger("ChunkX"); + int j = nbttagcompound1.getInteger("ChunkZ"); + StructureStart structurestart = MapGenStructureIO.getStructureStart(nbttagcompound1, + worldIn); + if (structurestart != null) { + this.structureMap.put(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)), + structurestart); + } + } + } + } } } - return flag; } public boolean func_175795_b(BlockPos pos) { @@ -120,6 +99,18 @@ public abstract class MapGenStructure extends MapGenBase { return this.func_175797_c(pos) != null; } + public boolean func_175796_a(World worldIn, BlockPos pos) { + this.func_143027_a(worldIn); + + for (StructureStart structurestart : this.structureMap.values()) { + if (structurestart.isSizeableStructure() && structurestart.getBoundingBox().isVecInside(pos)) { + return true; + } + } + + return false; + } + protected StructureStart func_175797_c(BlockPos pos) { label24: for (StructureStart structurestart : this.structureMap.values()) { if (structurestart.isSizeableStructure() && structurestart.getBoundingBox().isVecInside(pos)) { @@ -143,16 +134,23 @@ public abstract class MapGenStructure extends MapGenBase { return null; } - public boolean func_175796_a(World worldIn, BlockPos pos) { + public boolean generateStructure(World worldIn, EaglercraftRandom randomIn, ChunkCoordIntPair chunkCoord) { this.func_143027_a(worldIn); + int i = (chunkCoord.chunkXPos << 4) + 8; + int j = (chunkCoord.chunkZPos << 4) + 8; + boolean flag = false; for (StructureStart structurestart : this.structureMap.values()) { - if (structurestart.isSizeableStructure() && structurestart.getBoundingBox().isVecInside(pos)) { - return true; + if (structurestart.isSizeableStructure() && structurestart.func_175788_a(chunkCoord) + && structurestart.getBoundingBox().intersectsWith(i, j, i + 15, j + 15)) { + structurestart.generateStructure(worldIn, randomIn, new StructureBoundingBox(i, j, i + 15, j + 15)); + structurestart.func_175787_b(chunkCoord); + flag = true; + this.func_143026_a(structurestart.getChunkPosX(), structurestart.getChunkPosZ(), structurestart); } } - return false; + return flag; } public BlockPos getClosestStrongholdPos(World worldIn, BlockPos pos) { @@ -203,53 +201,57 @@ public abstract class MapGenStructure extends MapGenBase { } } - /**+ - * Returns a list of other locations at which the structure - * generation has been run, or null if not relevant to this - * structure generator. + /** + * + Returns a list of other locations at which the structure generation has + * been run, or null if not relevant to this structure generator. */ protected List getCoordList() { return null; } - private void func_143027_a(World worldIn) { - if (this.structureData == null) { - this.structureData = (MapGenStructureData) worldIn.loadItemData(MapGenStructureData.class, - this.getStructureName()); - if (this.structureData == null) { - this.structureData = new MapGenStructureData(this.getStructureName()); - worldIn.setItemData(this.getStructureName(), this.structureData); - } else { - NBTTagCompound nbttagcompound = this.structureData.getTagCompound(); - - for (String s : nbttagcompound.getKeySet()) { - NBTBase nbtbase = nbttagcompound.getTag(s); - if (nbtbase.getId() == 10) { - NBTTagCompound nbttagcompound1 = (NBTTagCompound) nbtbase; - if (nbttagcompound1.hasKey("ChunkX") && nbttagcompound1.hasKey("ChunkZ")) { - int i = nbttagcompound1.getInteger("ChunkX"); - int j = nbttagcompound1.getInteger("ChunkZ"); - StructureStart structurestart = MapGenStructureIO.getStructureStart(nbttagcompound1, - worldIn); - if (structurestart != null) { - this.structureMap.put(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)), - structurestart); - } - } - } - } - } - } - - } - - private void func_143026_a(int start, int parInt2, StructureStart parStructureStart) { - this.structureData.writeInstance(parStructureStart.writeStructureComponentsToNBT(start, parInt2), start, - parInt2); - this.structureData.markDirty(); - } - - protected abstract boolean canSpawnStructureAtCoords(int var1, int var2); + public abstract String getStructureName(); protected abstract StructureStart getStructureStart(int var1, int var2); + + /** + * + Recursively called by generate() + */ + protected final void recursiveGenerate(World world, final int i, final int j, int var4, int var5, + ChunkPrimer var6) { + this.func_143027_a(world); + if (!this.structureMap.containsKey(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)))) { + this.rand.nextInt(); + + try { + if (this.canSpawnStructureAtCoords(i, j)) { + StructureStart structurestart = this.getStructureStart(i, j); + this.structureMap.put(Long.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)), structurestart); + this.func_143026_a(i, j, structurestart); + } + + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, + "Exception preparing structure feature"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Feature being prepared"); + crashreportcategory.addCrashSectionCallable("Is feature chunk", new Callable() { + public String call() throws Exception { + return MapGenStructure.this.canSpawnStructureAtCoords(i, j) ? "True" : "False"; + } + }); + crashreportcategory.addCrashSection("Chunk location", + HString.format("%d,%d", new Object[] { Integer.valueOf(i), Integer.valueOf(j) })); + crashreportcategory.addCrashSectionCallable("Chunk pos hash", new Callable() { + public String call() throws Exception { + return String.valueOf(ChunkCoordIntPair.chunkXZ2Int(i, j)); + } + }); + crashreportcategory.addCrashSectionCallable("Structure type", new Callable() { + public String call() throws Exception { + return MapGenStructure.this.getClass().getCanonicalName(); + } + }); + throw new ReportedException(crashreport); + } + } + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenStructureData.java b/src/game/java/net/minecraft/world/gen/structure/MapGenStructureData.java index 6949978f..f3c3d059 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenStructureData.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenStructureData.java @@ -3,61 +3,64 @@ package net.minecraft.world.gen.structure; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSavedData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapGenStructureData extends WorldSavedData { + public static String formatChunkCoords(int chunkX, int chunkZ) { + return "[" + chunkX + "," + chunkZ + "]"; + } + private NBTTagCompound tagCompound = new NBTTagCompound(); public MapGenStructureData(String name) { super(name); } - /**+ - * reads in data from the NBTTagCompound into this MapDataBase + public NBTTagCompound getTagCompound() { + return this.tagCompound; + } + + /** + * + reads in data from the NBTTagCompound into this MapDataBase */ public void readFromNBT(NBTTagCompound nbt) { this.tagCompound = nbt.getCompoundTag("Features"); } - /**+ - * write data to NBTTagCompound from this MapDataBase, similar - * to Entities and TileEntities - */ - public void writeToNBT(NBTTagCompound nbt) { - nbt.setTag("Features", this.tagCompound); - } - - /**+ - * Writes the NBT tag of an instance of this structure type to - * the internal NBT tag, using the chunkcoordinates as the key + /** + * + Writes the NBT tag of an instance of this structure type to the internal + * NBT tag, using the chunkcoordinates as the key */ public void writeInstance(NBTTagCompound tagCompoundIn, int chunkX, int chunkZ) { this.tagCompound.setTag(formatChunkCoords(chunkX, chunkZ), tagCompoundIn); } - public static String formatChunkCoords(int chunkX, int chunkZ) { - return "[" + chunkX + "," + chunkZ + "]"; - } - - public NBTTagCompound getTagCompound() { - return this.tagCompound; + /** + * + write data to NBTTagCompound from this MapDataBase, similar to Entities and + * TileEntities + */ + public void writeToNBT(NBTTagCompound nbt) { + nbt.setTag("Features", this.tagCompound); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenStructureIO.java b/src/game/java/net/minecraft/world/gen/structure/MapGenStructureIO.java index e603be8d..87d7e3a6 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenStructureIO.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenStructureIO.java @@ -1,28 +1,33 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Maps; import java.util.Map; -import net.minecraft.nbt.NBTTagCompound; -import net.minecraft.world.World; + +import com.google.common.collect.Maps; + import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,18 +39,41 @@ public class MapGenStructureIO { private static Map> componentNameToClassMap = Maps.newHashMap(); private static Map, String> componentClassToNameMap = Maps.newHashMap(); - private static void registerStructure(Class startClass, String structureName) { - startNameToClassMap.put(structureName, startClass); - startClassToNameMap.put(startClass, structureName); + static { + registerStructure(StructureMineshaftStart.class, "Mineshaft"); + registerStructure(MapGenVillage.Start.class, "Village"); + registerStructure(MapGenNetherBridge.Start.class, "Fortress"); + registerStructure(MapGenStronghold.Start.class, "Stronghold"); + registerStructure(MapGenScatteredFeature.Start.class, "Temple"); + registerStructure(StructureOceanMonument.StartMonument.class, "Monument"); + StructureMineshaftPieces.registerStructurePieces(); + StructureVillagePieces.registerVillagePieces(); + StructureNetherBridgePieces.registerNetherFortressPieces(); + StructureStrongholdPieces.registerStrongholdPieces(); + ComponentScatteredFeaturePieces.registerScatteredFeaturePieces(); + StructureOceanMonumentPieces.registerOceanMonumentPieces(); } - static void registerStructureComponent(Class componentClass, String componentName) { - componentNameToClassMap.put(componentName, componentClass); - componentClassToNameMap.put(componentClass, componentName); - } + public static StructureComponent getStructureComponent(NBTTagCompound tagCompound, World worldIn) { + StructureComponent structurecomponent = null; - public static String getStructureStartName(StructureStart start) { - return (String) startClassToNameMap.get(start.getClass()); + try { + Class oclass = (Class) componentNameToClassMap.get(tagCompound.getString("id")); + if (oclass != null) { + structurecomponent = (StructureComponent) oclass.newInstance(); + } + } catch (Exception exception) { + logger.warn("Failed Piece with id " + tagCompound.getString("id")); + logger.warn(exception); + } + + if (structurecomponent != null) { + structurecomponent.readStructureBaseNBT(worldIn, tagCompound); + } else { + logger.warn("Skipping Piece with id " + tagCompound.getString("id")); + } + + return structurecomponent; } public static String getStructureComponentName(StructureComponent component) { @@ -74,40 +102,17 @@ public class MapGenStructureIO { return structurestart; } - public static StructureComponent getStructureComponent(NBTTagCompound tagCompound, World worldIn) { - StructureComponent structurecomponent = null; - - try { - Class oclass = (Class) componentNameToClassMap.get(tagCompound.getString("id")); - if (oclass != null) { - structurecomponent = (StructureComponent) oclass.newInstance(); - } - } catch (Exception exception) { - logger.warn("Failed Piece with id " + tagCompound.getString("id")); - logger.warn(exception); - } - - if (structurecomponent != null) { - structurecomponent.readStructureBaseNBT(worldIn, tagCompound); - } else { - logger.warn("Skipping Piece with id " + tagCompound.getString("id")); - } - - return structurecomponent; + public static String getStructureStartName(StructureStart start) { + return (String) startClassToNameMap.get(start.getClass()); } - static { - registerStructure(StructureMineshaftStart.class, "Mineshaft"); - registerStructure(MapGenVillage.Start.class, "Village"); - registerStructure(MapGenNetherBridge.Start.class, "Fortress"); - registerStructure(MapGenStronghold.Start.class, "Stronghold"); - registerStructure(MapGenScatteredFeature.Start.class, "Temple"); - registerStructure(StructureOceanMonument.StartMonument.class, "Monument"); - StructureMineshaftPieces.registerStructurePieces(); - StructureVillagePieces.registerVillagePieces(); - StructureNetherBridgePieces.registerNetherFortressPieces(); - StructureStrongholdPieces.registerStrongholdPieces(); - ComponentScatteredFeaturePieces.registerScatteredFeaturePieces(); - StructureOceanMonumentPieces.registerOceanMonumentPieces(); + private static void registerStructure(Class startClass, String structureName) { + startNameToClassMap.put(structureName, startClass); + startClassToNameMap.put(startClass, structureName); + } + + static void registerStructureComponent(Class componentClass, String componentName) { + componentNameToClassMap.put(componentName, componentClass); + componentClassToNameMap.put(componentClass, componentName); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/MapGenVillage.java b/src/game/java/net/minecraft/world/gen/structure/MapGenVillage.java index f42f898d..808c5bf6 100644 --- a/src/game/java/net/minecraft/world/gen/structure/MapGenVillage.java +++ b/src/game/java/net/minecraft/world/gen/structure/MapGenVillage.java @@ -3,100 +3,38 @@ package net.minecraft.world.gen.structure; import java.util.Arrays; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import java.util.Map.Entry; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapGenVillage extends MapGenStructure { - /**+ - * A list of all the biomes villages can spawn in. - */ - public static final List villageSpawnBiomes = Arrays - .asList(new BiomeGenBase[] { BiomeGenBase.plains, BiomeGenBase.desert, BiomeGenBase.savanna }); - private int terrainType; - private int field_82665_g; - private int field_82666_h; - - public MapGenVillage(boolean scramble) { - super(scramble); - this.field_82665_g = 32; - this.field_82666_h = 8; - } - - public MapGenVillage(Map parMap, boolean scramble) { - this(scramble); - - for (Entry entry : parMap.entrySet()) { - if (((String) entry.getKey()).equals("size")) { - this.terrainType = MathHelper.parseIntWithDefaultAndMax((String) entry.getValue(), this.terrainType, 0); - } else if (((String) entry.getKey()).equals("distance")) { - this.field_82665_g = MathHelper.parseIntWithDefaultAndMax((String) entry.getValue(), this.field_82665_g, - this.field_82666_h + 1); - } - } - - } - - public String getStructureName() { - return "Village"; - } - - protected boolean canSpawnStructureAtCoords(int i, int j) { - int k = i; - int l = j; - if (i < 0) { - i -= this.field_82665_g - 1; - } - - if (j < 0) { - j -= this.field_82665_g - 1; - } - - int i1 = i / this.field_82665_g; - int j1 = j / this.field_82665_g; - EaglercraftRandom random = this.worldObj.setRandomSeed(i1, j1, 10387312); - i1 = i1 * this.field_82665_g; - j1 = j1 * this.field_82665_g; - i1 = i1 + random.nextInt(this.field_82665_g - this.field_82666_h); - j1 = j1 + random.nextInt(this.field_82665_g - this.field_82666_h); - if (k == i1 && l == j1) { - boolean flag = this.worldObj.getWorldChunkManager().areBiomesViable(k * 16 + 8, l * 16 + 8, 0, - villageSpawnBiomes); - if (flag) { - return true; - } - } - - return false; - } - - protected StructureStart getStructureStart(int i, int j) { - return new MapGenVillage.Start(this.worldObj, this.rand, i, j, this.terrainType); - } - public static class Start extends StructureStart { private boolean hasMoreThanTwoComponents; @@ -141,14 +79,81 @@ public class MapGenVillage extends MapGenStructure { return this.hasMoreThanTwoComponents; } - public void writeToNBT(NBTTagCompound nbttagcompound) { - super.writeToNBT(nbttagcompound); - nbttagcompound.setBoolean("Valid", this.hasMoreThanTwoComponents); - } - public void readFromNBT(NBTTagCompound nbttagcompound) { super.readFromNBT(nbttagcompound); this.hasMoreThanTwoComponents = nbttagcompound.getBoolean("Valid"); } + + public void writeToNBT(NBTTagCompound nbttagcompound) { + super.writeToNBT(nbttagcompound); + nbttagcompound.setBoolean("Valid", this.hasMoreThanTwoComponents); + } + } + + /** + * + A list of all the biomes villages can spawn in. + */ + public static final List villageSpawnBiomes = Arrays + .asList(new BiomeGenBase[] { BiomeGenBase.plains, BiomeGenBase.desert, BiomeGenBase.savanna }); + private int terrainType; + private int field_82665_g; + + private int field_82666_h; + + public MapGenVillage(boolean scramble) { + super(scramble); + this.field_82665_g = 32; + this.field_82666_h = 8; + } + + public MapGenVillage(Map parMap, boolean scramble) { + this(scramble); + + for (Entry entry : parMap.entrySet()) { + if (((String) entry.getKey()).equals("size")) { + this.terrainType = MathHelper.parseIntWithDefaultAndMax((String) entry.getValue(), this.terrainType, 0); + } else if (((String) entry.getKey()).equals("distance")) { + this.field_82665_g = MathHelper.parseIntWithDefaultAndMax((String) entry.getValue(), this.field_82665_g, + this.field_82666_h + 1); + } + } + + } + + protected boolean canSpawnStructureAtCoords(int i, int j) { + int k = i; + int l = j; + if (i < 0) { + i -= this.field_82665_g - 1; + } + + if (j < 0) { + j -= this.field_82665_g - 1; + } + + int i1 = i / this.field_82665_g; + int j1 = j / this.field_82665_g; + EaglercraftRandom random = this.worldObj.setRandomSeed(i1, j1, 10387312); + i1 = i1 * this.field_82665_g; + j1 = j1 * this.field_82665_g; + i1 = i1 + random.nextInt(this.field_82665_g - this.field_82666_h); + j1 = j1 + random.nextInt(this.field_82665_g - this.field_82666_h); + if (k == i1 && l == j1) { + boolean flag = this.worldObj.getWorldChunkManager().areBiomesViable(k * 16 + 8, l * 16 + 8, 0, + villageSpawnBiomes); + if (flag) { + return true; + } + } + + return false; + } + + public String getStructureName() { + return "Village"; + } + + protected StructureStart getStructureStart(int i, int j) { + return new MapGenVillage.Start(this.worldObj, this.rand, i, j, this.terrainType); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureBoundingBox.java b/src/game/java/net/minecraft/world/gen/structure/StructureBoundingBox.java index b7979e70..de6d734e 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureBoundingBox.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureBoundingBox.java @@ -1,66 +1,47 @@ package net.minecraft.world.gen.structure; import com.google.common.base.Objects; + import net.minecraft.nbt.NBTTagIntArray; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.Vec3i; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureBoundingBox { - public int minX; - public int minY; - public int minZ; - public int maxX; - public int maxY; - public int maxZ; - - public StructureBoundingBox() { + public static StructureBoundingBox func_175899_a(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, + int parInt6) { + return new StructureBoundingBox(Math.min(parInt1, parInt4), Math.min(parInt2, parInt5), + Math.min(parInt3, parInt6), Math.max(parInt1, parInt4), Math.max(parInt2, parInt5), + Math.max(parInt3, parInt6)); } - public StructureBoundingBox(int[] coords) { - if (coords.length == 6) { - this.minX = coords[0]; - this.minY = coords[1]; - this.minZ = coords[2]; - this.maxX = coords[3]; - this.maxY = coords[4]; - this.maxZ = coords[5]; - } - - } - - /**+ - * returns a new StructureBoundingBox with MAX values - */ - public static StructureBoundingBox getNewBoundingBox() { - return new StructureBoundingBox(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, - Integer.MIN_VALUE, Integer.MIN_VALUE); - } - - /**+ - * Create a bounding box with the specified dimensions and - * rotate it. Used to project a possible new component Bounding - * Box - to check if it would cut anything already spawned + /** + * + Create a bounding box with the specified dimensions and rotate it. Used to + * project a possible new component Bounding Box - to check if it would cut + * anything already spawned */ public static StructureBoundingBox getComponentToAddBoundingBox(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, int parInt7, int parInt8, int parInt9, EnumFacing parEnumFacing) { @@ -83,38 +64,25 @@ public class StructureBoundingBox { } } - public static StructureBoundingBox func_175899_a(int parInt1, int parInt2, int parInt3, int parInt4, int parInt5, - int parInt6) { - return new StructureBoundingBox(Math.min(parInt1, parInt4), Math.min(parInt2, parInt5), - Math.min(parInt3, parInt6), Math.max(parInt1, parInt4), Math.max(parInt2, parInt5), - Math.max(parInt3, parInt6)); + /** + * + returns a new StructureBoundingBox with MAX values + */ + public static StructureBoundingBox getNewBoundingBox() { + return new StructureBoundingBox(Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, + Integer.MIN_VALUE, Integer.MIN_VALUE); } - public StructureBoundingBox(StructureBoundingBox structurebb) { - this.minX = structurebb.minX; - this.minY = structurebb.minY; - this.minZ = structurebb.minZ; - this.maxX = structurebb.maxX; - this.maxY = structurebb.maxY; - this.maxZ = structurebb.maxZ; - } + public int minX; + public int minY; + public int minZ; - public StructureBoundingBox(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax) { - this.minX = xMin; - this.minY = yMin; - this.minZ = zMin; - this.maxX = xMax; - this.maxY = yMax; - this.maxZ = zMax; - } + public int maxX; - public StructureBoundingBox(Vec3i vec1, Vec3i vec2) { - this.minX = Math.min(vec1.getX(), vec2.getX()); - this.minY = Math.min(vec1.getY(), vec2.getY()); - this.minZ = Math.min(vec1.getZ(), vec2.getZ()); - this.maxX = Math.max(vec1.getX(), vec2.getX()); - this.maxY = Math.max(vec1.getY(), vec2.getY()); - this.maxZ = Math.max(vec1.getZ(), vec2.getZ()); + public int maxY; + + public int maxZ; + + public StructureBoundingBox() { } public StructureBoundingBox(int xMin, int zMin, int xMax, int zMax) { @@ -126,24 +94,47 @@ public class StructureBoundingBox { this.maxY = 512; } - /**+ - * Discover if a coordinate is inside the bounding box area. - */ - public boolean intersectsWith(StructureBoundingBox structurebb) { - return this.maxX >= structurebb.minX && this.minX <= structurebb.maxX && this.maxZ >= structurebb.minZ - && this.minZ <= structurebb.maxZ && this.maxY >= structurebb.minY && this.minY <= structurebb.maxY; + public StructureBoundingBox(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax) { + this.minX = xMin; + this.minY = yMin; + this.minZ = zMin; + this.maxX = xMax; + this.maxY = yMax; + this.maxZ = zMax; } - /**+ - * Discover if a coordinate is inside the bounding box area. - */ - public boolean intersectsWith(int minXIn, int minZIn, int maxXIn, int maxZIn) { - return this.maxX >= minXIn && this.minX <= maxXIn && this.maxZ >= minZIn && this.minZ <= maxZIn; + public StructureBoundingBox(int[] coords) { + if (coords.length == 6) { + this.minX = coords[0]; + this.minY = coords[1]; + this.minZ = coords[2]; + this.maxX = coords[3]; + this.maxY = coords[4]; + this.maxZ = coords[5]; + } + } - /**+ - * Expands a bounding box's dimensions to include the supplied - * bounding box. + public StructureBoundingBox(StructureBoundingBox structurebb) { + this.minX = structurebb.minX; + this.minY = structurebb.minY; + this.minZ = structurebb.minZ; + this.maxX = structurebb.maxX; + this.maxY = structurebb.maxY; + this.maxZ = structurebb.maxZ; + } + + public StructureBoundingBox(Vec3i vec1, Vec3i vec2) { + this.minX = Math.min(vec1.getX(), vec2.getX()); + this.minY = Math.min(vec1.getY(), vec2.getY()); + this.minZ = Math.min(vec1.getZ(), vec2.getZ()); + this.maxX = Math.max(vec1.getX(), vec2.getX()); + this.maxY = Math.max(vec1.getY(), vec2.getY()); + this.maxZ = Math.max(vec1.getZ(), vec2.getZ()); + } + + /** + * + Expands a bounding box's dimensions to include the supplied bounding box. */ public void expandTo(StructureBoundingBox sbb) { this.minX = Math.min(this.minX, sbb.minX); @@ -154,9 +145,62 @@ public class StructureBoundingBox { this.maxZ = Math.max(this.maxZ, sbb.maxZ); } - /**+ - * Offsets the current bounding box by the specified - * coordinates. Args: x, y, z + public Vec3i func_175896_b() { + return new Vec3i(this.maxX - this.minX, this.maxY - this.minY, this.maxZ - this.minZ); + } + + public Vec3i getCenter() { + return new BlockPos(this.minX + (this.maxX - this.minX + 1) / 2, this.minY + (this.maxY - this.minY + 1) / 2, + this.minZ + (this.maxZ - this.minZ + 1) / 2); + } + + /** + * + Get dimension of the bounding box in the x direction. + */ + public int getXSize() { + return this.maxX - this.minX + 1; + } + + /** + * + Get dimension of the bounding box in the y direction. + */ + public int getYSize() { + return this.maxY - this.minY + 1; + } + + /** + * + Get dimension of the bounding box in the z direction. + */ + public int getZSize() { + return this.maxZ - this.minZ + 1; + } + + /** + * + Discover if a coordinate is inside the bounding box area. + */ + public boolean intersectsWith(int minXIn, int minZIn, int maxXIn, int maxZIn) { + return this.maxX >= minXIn && this.minX <= maxXIn && this.maxZ >= minZIn && this.minZ <= maxZIn; + } + + /** + * + Discover if a coordinate is inside the bounding box area. + */ + public boolean intersectsWith(StructureBoundingBox structurebb) { + return this.maxX >= structurebb.minX && this.minX <= structurebb.maxX && this.maxZ >= structurebb.minZ + && this.minZ <= structurebb.maxZ && this.maxY >= structurebb.minY && this.minY <= structurebb.maxY; + } + + /** + * + Checks if given Vec3i is inside of StructureBoundingBox + */ + public boolean isVecInside(Vec3i vec) { + return vec.getX() >= this.minX && vec.getX() <= this.maxX && vec.getZ() >= this.minZ && vec.getZ() <= this.maxZ + && vec.getY() >= this.minY && vec.getY() <= this.maxY; + } + + /** + * + Offsets the current bounding box by the specified coordinates. Args: x, y, + * z */ public void offset(int x, int y, int z) { this.minX += x; @@ -167,50 +211,12 @@ public class StructureBoundingBox { this.maxZ += z; } - /**+ - * Checks if given Vec3i is inside of StructureBoundingBox - */ - public boolean isVecInside(Vec3i vec) { - return vec.getX() >= this.minX && vec.getX() <= this.maxX && vec.getZ() >= this.minZ && vec.getZ() <= this.maxZ - && vec.getY() >= this.minY && vec.getY() <= this.maxY; - } - - public Vec3i func_175896_b() { - return new Vec3i(this.maxX - this.minX, this.maxY - this.minY, this.maxZ - this.minZ); - } - - /**+ - * Get dimension of the bounding box in the x direction. - */ - public int getXSize() { - return this.maxX - this.minX + 1; - } - - /**+ - * Get dimension of the bounding box in the y direction. - */ - public int getYSize() { - return this.maxY - this.minY + 1; - } - - /**+ - * Get dimension of the bounding box in the z direction. - */ - public int getZSize() { - return this.maxZ - this.minZ + 1; - } - - public Vec3i getCenter() { - return new BlockPos(this.minX + (this.maxX - this.minX + 1) / 2, this.minY + (this.maxY - this.minY + 1) / 2, - this.minZ + (this.maxZ - this.minZ + 1) / 2); + public NBTTagIntArray toNBTTagIntArray() { + return new NBTTagIntArray(new int[] { this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ }); } public String toString() { return Objects.toStringHelper(this).add("x0", this.minX).add("y0", this.minY).add("z0", this.minZ) .add("x1", this.maxX).add("y1", this.maxY).add("z1", this.maxZ).toString(); } - - public NBTTagIntArray toNBTTagIntArray() { - return new NBTTagIntArray(new int[] { this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ }); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureComponent.java b/src/game/java/net/minecraft/world/gen/structure/StructureComponent.java index 17bdba73..75595ca3 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureComponent.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureComponent.java @@ -1,6 +1,7 @@ package net.minecraft.world.gen.structure; import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.BlockDirectional; @@ -18,100 +19,42 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class StructureComponent { - protected StructureBoundingBox boundingBox; - protected EnumFacing coordBaseMode; - protected int componentType; + public abstract static class BlockSelector { + protected IBlockState blockstate = Blocks.air.getDefaultState(); - public StructureComponent() { - } - - protected StructureComponent(int type) { - this.componentType = type; - } - - /**+ - * Writes structure base data (id, boundingbox, {@link - * net.minecraft.world.gen.structure.StructureComponent#coordBaseMode - * coordBase} and {@link - * net.minecraft.world.gen.structure.StructureComponent#componentType - * componentType}) to new NBTTagCompound and returns it. - */ - public NBTTagCompound createStructureBaseNBT() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("id", MapGenStructureIO.getStructureComponentName(this)); - nbttagcompound.setTag("BB", this.boundingBox.toNBTTagIntArray()); - nbttagcompound.setInteger("O", this.coordBaseMode == null ? -1 : this.coordBaseMode.getHorizontalIndex()); - nbttagcompound.setInteger("GD", this.componentType); - this.writeStructureToNBT(nbttagcompound); - return nbttagcompound; - } - - protected abstract void writeStructureToNBT(NBTTagCompound var1); - - /**+ - * Reads and sets structure base data (boundingbox, {@link - * net.minecraft.world.gen.structure.StructureComponent#coordBaseMode - * coordBase} and {@link - * net.minecraft.world.gen.structure.StructureComponent#componentType - * componentType}) - */ - public void readStructureBaseNBT(World worldIn, NBTTagCompound tagCompound) { - if (tagCompound.hasKey("BB")) { - this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); + public IBlockState getBlockState() { + return this.blockstate; } - int i = tagCompound.getInteger("O"); - this.coordBaseMode = i == -1 ? null : EnumFacing.getHorizontal(i); - this.componentType = tagCompound.getInteger("GD"); - this.readStructureFromNBT(tagCompound); + public abstract void selectBlocks(EaglercraftRandom var1, int var2, int var3, int var4, boolean var5); } - protected abstract void readStructureFromNBT(NBTTagCompound var1); - - /**+ - * Initiates construction of the Structure Component picked, at - * the current Location of StructGen - */ - public void buildComponent(StructureComponent var1, List var2, EaglercraftRandom var3) { - } - - public abstract boolean addComponentParts(World var1, EaglercraftRandom var2, StructureBoundingBox var3); - - public StructureBoundingBox getBoundingBox() { - return this.boundingBox; - } - - /**+ - * Returns the component type ID of this component. - */ - public int getComponentType() { - return this.componentType; - } - - /**+ - * Discover if bounding box can fit within the current bounding - * box object. + /** + * + Discover if bounding box can fit within the current bounding box object. */ public static StructureComponent findIntersecting(List listIn, StructureBoundingBox boundingboxIn) { @@ -125,110 +68,209 @@ public abstract class StructureComponent { return null; } + protected StructureBoundingBox boundingBox; + + protected EnumFacing coordBaseMode; + + protected int componentType; + + public StructureComponent() { + } + + protected StructureComponent(int type) { + this.componentType = type; + } + + public abstract boolean addComponentParts(World var1, EaglercraftRandom var2, StructureBoundingBox var3); + + /** + * + Initiates construction of the Structure Component picked, at the current + * Location of StructGen + */ + public void buildComponent(StructureComponent var1, List var2, EaglercraftRandom var3) { + } + + /** + * + Deletes all continuous blocks from selected position upwards. Stops at + * hitting air. + */ + protected void clearCurrentPositionBlocksUpwards(World worldIn, int x, int y, int z, + StructureBoundingBox structurebb) { + BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); + if (structurebb.isVecInside(blockpos)) { + while (!worldIn.isAirBlock(blockpos) && blockpos.getY() < 255) { + worldIn.setBlockState(blockpos, Blocks.air.getDefaultState(), 2); + blockpos = blockpos.up(); + } + + } + } + + /** + * + Writes structure base data (id, boundingbox, + * {@link net.minecraft.world.gen.structure.StructureComponent#coordBaseMode + * coordBase} and + * {@link net.minecraft.world.gen.structure.StructureComponent#componentType + * componentType}) to new NBTTagCompound and returns it. + */ + public NBTTagCompound createStructureBaseNBT() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setString("id", MapGenStructureIO.getStructureComponentName(this)); + nbttagcompound.setTag("BB", this.boundingBox.toNBTTagIntArray()); + nbttagcompound.setInteger("O", this.coordBaseMode == null ? -1 : this.coordBaseMode.getHorizontalIndex()); + nbttagcompound.setInteger("GD", this.componentType); + this.writeStructureToNBT(nbttagcompound); + return nbttagcompound; + } + + /** + * + arguments: (World worldObj, StructureBoundingBox structBB, int minX, int + * minY, int minZ, int maxX, int maxY, int maxZ) + */ + protected void fillWithAir(World worldIn, StructureBoundingBox structurebb, int minX, int minY, int minZ, int maxX, + int maxY, int maxZ) { + for (int i = minY; i <= maxY; ++i) { + for (int j = minX; j <= maxX; ++j) { + for (int k = minZ; k <= maxZ; ++k) { + this.setBlockState(worldIn, Blocks.air.getDefaultState(), j, i, k, structurebb); + } + } + } + + } + + /** + * + Fill the given area with the selected blocks + */ + protected void fillWithBlocks(World worldIn, StructureBoundingBox boundingboxIn, int xMin, int yMin, int zMin, + int xMax, int yMax, int zMax, IBlockState boundaryBlockState, IBlockState insideBlockState, + boolean existingOnly) { + for (int i = yMin; i <= yMax; ++i) { + for (int j = xMin; j <= xMax; ++j) { + for (int k = zMin; k <= zMax; ++k) { + if (!existingOnly || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() + .getMaterial() != Material.air) { + if (i != yMin && i != yMax && j != xMin && j != xMax && k != zMin && k != zMax) { + this.setBlockState(worldIn, insideBlockState, j, i, k, boundingboxIn); + } else { + this.setBlockState(worldIn, boundaryBlockState, j, i, k, boundingboxIn); + } + } + } + } + } + + } + + /** + * + arguments: World worldObj, StructureBoundingBox structBB, int minX, int + * minY, int minZ, int maxX, int maxY, int maxZ, boolean alwaysreplace, Random + * rand, StructurePieceBlockSelector blockselector + */ + protected void fillWithRandomizedBlocks(World worldIn, StructureBoundingBox boundingboxIn, int minX, int minY, + int minZ, int maxX, int maxY, int maxZ, boolean alwaysReplace, EaglercraftRandom rand, + StructureComponent.BlockSelector blockselector) { + for (int i = minY; i <= maxY; ++i) { + for (int j = minX; j <= maxX; ++j) { + for (int k = minZ; k <= maxZ; ++k) { + if (!alwaysReplace || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() + .getMaterial() != Material.air) { + blockselector.selectBlocks(rand, j, i, k, + i == minY || i == maxY || j == minX || j == maxX || k == minZ || k == maxZ); + this.setBlockState(worldIn, blockselector.getBlockState(), j, i, k, boundingboxIn); + } + } + } + } + + } + + protected void func_175805_a(World worldIn, StructureBoundingBox boundingboxIn, EaglercraftRandom rand, + float chance, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, IBlockState blockstate1, + IBlockState blockstate2, boolean parFlag) { + for (int i = minY; i <= maxY; ++i) { + for (int j = minX; j <= maxX; ++j) { + for (int k = minZ; k <= maxZ; ++k) { + if (rand.nextFloat() <= chance + && (!parFlag || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() + .getMaterial() != Material.air)) { + if (i != minY && i != maxY && j != minX && j != maxX && k != minZ && k != maxZ) { + this.setBlockState(worldIn, blockstate2, j, i, k, boundingboxIn); + } else { + this.setBlockState(worldIn, blockstate1, j, i, k, boundingboxIn); + } + } + } + } + } + + } + + public void func_181138_a(int i, int j, int k) { + this.boundingBox.offset(i, j, k); + } + + protected boolean generateChestContents(World world, StructureBoundingBox structureboundingbox, + EaglercraftRandom random, int i, int j, int k, List list, int l) { + BlockPos blockpos = new BlockPos(this.getXWithOffset(i, k), this.getYWithOffset(j), this.getZWithOffset(i, k)); + if (structureboundingbox.isVecInside(blockpos) && world.getBlockState(blockpos).getBlock() != Blocks.chest) { + IBlockState iblockstate = Blocks.chest.getDefaultState(); + world.setBlockState(blockpos, Blocks.chest.correctFacing(world, blockpos, iblockstate), 2); + TileEntity tileentity = world.getTileEntity(blockpos); + if (tileentity instanceof TileEntityChest) { + WeightedRandomChestContent.generateChestContents(random, list, (TileEntityChest) tileentity, l); + } + + return true; + } else { + return false; + } + } + + protected boolean generateDispenserContents(World worldIn, StructureBoundingBox boundingBoxIn, + EaglercraftRandom rand, int x, int y, int z, int meta, List listIn, int max) { + BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); + if (boundingBoxIn.isVecInside(blockpos) && worldIn.getBlockState(blockpos).getBlock() != Blocks.dispenser) { + worldIn.setBlockState(blockpos, + Blocks.dispenser.getStateFromMeta(this.getMetadataWithOffset(Blocks.dispenser, meta)), 2); + TileEntity tileentity = worldIn.getTileEntity(blockpos); + if (tileentity instanceof TileEntityDispenser) { + WeightedRandomChestContent.generateDispenserContents(rand, listIn, (TileEntityDispenser) tileentity, + max); + } + + return true; + } else { + return false; + } + } + + protected IBlockState getBlockStateFromPos(World worldIn, int x, int y, int z, StructureBoundingBox boundingboxIn) { + int i = this.getXWithOffset(x, z); + int j = this.getYWithOffset(y); + int k = this.getZWithOffset(x, z); + BlockPos blockpos = new BlockPos(i, j, k); + return !boundingboxIn.isVecInside(blockpos) ? Blocks.air.getDefaultState() : worldIn.getBlockState(blockpos); + } + + public StructureBoundingBox getBoundingBox() { + return this.boundingBox; + } + public BlockPos getBoundingBoxCenter() { return new BlockPos(this.boundingBox.getCenter()); } - /**+ - * checks the entire StructureBoundingBox for Liquids + /** + * + Returns the component type ID of this component. */ - protected boolean isLiquidInStructureBoundingBox(World worldIn, StructureBoundingBox boundingboxIn) { - int i = Math.max(this.boundingBox.minX - 1, boundingboxIn.minX); - int j = Math.max(this.boundingBox.minY - 1, boundingboxIn.minY); - int k = Math.max(this.boundingBox.minZ - 1, boundingboxIn.minZ); - int l = Math.min(this.boundingBox.maxX + 1, boundingboxIn.maxX); - int i1 = Math.min(this.boundingBox.maxY + 1, boundingboxIn.maxY); - int j1 = Math.min(this.boundingBox.maxZ + 1, boundingboxIn.maxZ); - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k1 = i; k1 <= l; ++k1) { - for (int l1 = k; l1 <= j1; ++l1) { - if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, j, l1)).getBlock().getMaterial() - .isLiquid()) { - return true; - } - - if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, i1, l1)).getBlock().getMaterial() - .isLiquid()) { - return true; - } - } - } - - for (int i2 = i; i2 <= l; ++i2) { - for (int k2 = j; k2 <= i1; ++k2) { - if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(i2, k2, k)).getBlock().getMaterial() - .isLiquid()) { - return true; - } - - if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(i2, k2, j1)).getBlock().getMaterial() - .isLiquid()) { - return true; - } - } - } - - for (int j2 = k; j2 <= j1; ++j2) { - for (int l2 = j; l2 <= i1; ++l2) { - if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(i, l2, j2)).getBlock().getMaterial() - .isLiquid()) { - return true; - } - - if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(l, l2, j2)).getBlock().getMaterial() - .isLiquid()) { - return true; - } - } - } - - return false; + public int getComponentType() { + return this.componentType; } - protected int getXWithOffset(int x, int z) { - if (this.coordBaseMode == null) { - return x; - } else { - switch (this.coordBaseMode) { - case NORTH: - case SOUTH: - return this.boundingBox.minX + x; - case WEST: - return this.boundingBox.maxX - z; - case EAST: - return this.boundingBox.minX + z; - default: - return x; - } - } - } - - protected int getYWithOffset(int y) { - return this.coordBaseMode == null ? y : y + this.boundingBox.minY; - } - - protected int getZWithOffset(int x, int z) { - if (this.coordBaseMode == null) { - return z; - } else { - switch (this.coordBaseMode) { - case NORTH: - return this.boundingBox.maxZ - z; - case SOUTH: - return this.boundingBox.minZ + z; - case WEST: - case EAST: - return this.boundingBox.minZ + x; - default: - return z; - } - } - } - - /**+ - * Returns the direction-shifted metadata for blocks that - * require orientation, e.g. doors, stairs, ladders. + /** + * + Returns the direction-shifted metadata for blocks that require orientation, + * e.g. doors, stairs, ladders. */ protected int getMetadataWithOffset(Block blockIn, int meta) { if (blockIn == Blocks.rail) { @@ -470,102 +512,111 @@ public abstract class StructureComponent { return meta; } - protected void setBlockState(World worldIn, IBlockState blockstateIn, int x, int y, int z, - StructureBoundingBox boundingboxIn) { + protected int getXWithOffset(int x, int z) { + if (this.coordBaseMode == null) { + return x; + } else { + switch (this.coordBaseMode) { + case NORTH: + case SOUTH: + return this.boundingBox.minX + x; + case WEST: + return this.boundingBox.maxX - z; + case EAST: + return this.boundingBox.minX + z; + default: + return x; + } + } + } + + protected int getYWithOffset(int y) { + return this.coordBaseMode == null ? y : y + this.boundingBox.minY; + } + + protected int getZWithOffset(int x, int z) { + if (this.coordBaseMode == null) { + return z; + } else { + switch (this.coordBaseMode) { + case NORTH: + return this.boundingBox.maxZ - z; + case SOUTH: + return this.boundingBox.minZ + z; + case WEST: + case EAST: + return this.boundingBox.minZ + x; + default: + return z; + } + } + } + + /** + * + checks the entire StructureBoundingBox for Liquids + */ + protected boolean isLiquidInStructureBoundingBox(World worldIn, StructureBoundingBox boundingboxIn) { + int i = Math.max(this.boundingBox.minX - 1, boundingboxIn.minX); + int j = Math.max(this.boundingBox.minY - 1, boundingboxIn.minY); + int k = Math.max(this.boundingBox.minZ - 1, boundingboxIn.minZ); + int l = Math.min(this.boundingBox.maxX + 1, boundingboxIn.maxX); + int i1 = Math.min(this.boundingBox.maxY + 1, boundingboxIn.maxY); + int j1 = Math.min(this.boundingBox.maxZ + 1, boundingboxIn.maxZ); + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k1 = i; k1 <= l; ++k1) { + for (int l1 = k; l1 <= j1; ++l1) { + if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, j, l1)).getBlock().getMaterial() + .isLiquid()) { + return true; + } + + if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(k1, i1, l1)).getBlock().getMaterial() + .isLiquid()) { + return true; + } + } + } + + for (int i2 = i; i2 <= l; ++i2) { + for (int k2 = j; k2 <= i1; ++k2) { + if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(i2, k2, k)).getBlock().getMaterial() + .isLiquid()) { + return true; + } + + if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(i2, k2, j1)).getBlock().getMaterial() + .isLiquid()) { + return true; + } + } + } + + for (int j2 = k; j2 <= j1; ++j2) { + for (int l2 = j; l2 <= i1; ++l2) { + if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(i, l2, j2)).getBlock().getMaterial() + .isLiquid()) { + return true; + } + + if (worldIn.getBlockState(blockpos$mutableblockpos.func_181079_c(l, l2, j2)).getBlock().getMaterial() + .isLiquid()) { + return true; + } + } + } + + return false; + } + + /** + * + Places door on given position + */ + protected void placeDoorCurrentPosition(World worldIn, StructureBoundingBox boundingBoxIn, EaglercraftRandom rand, + int x, int y, int z, EnumFacing facing) { BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); - if (boundingboxIn.isVecInside(blockpos)) { - worldIn.setBlockState(blockpos, blockstateIn, 2); - } - } - - protected IBlockState getBlockStateFromPos(World worldIn, int x, int y, int z, StructureBoundingBox boundingboxIn) { - int i = this.getXWithOffset(x, z); - int j = this.getYWithOffset(y); - int k = this.getZWithOffset(x, z); - BlockPos blockpos = new BlockPos(i, j, k); - return !boundingboxIn.isVecInside(blockpos) ? Blocks.air.getDefaultState() : worldIn.getBlockState(blockpos); - } - - /**+ - * arguments: (World worldObj, StructureBoundingBox structBB, - * int minX, int minY, int minZ, int maxX, int maxY, int maxZ) - */ - protected void fillWithAir(World worldIn, StructureBoundingBox structurebb, int minX, int minY, int minZ, int maxX, - int maxY, int maxZ) { - for (int i = minY; i <= maxY; ++i) { - for (int j = minX; j <= maxX; ++j) { - for (int k = minZ; k <= maxZ; ++k) { - this.setBlockState(worldIn, Blocks.air.getDefaultState(), j, i, k, structurebb); - } - } - } - - } - - /**+ - * Fill the given area with the selected blocks - */ - protected void fillWithBlocks(World worldIn, StructureBoundingBox boundingboxIn, int xMin, int yMin, int zMin, - int xMax, int yMax, int zMax, IBlockState boundaryBlockState, IBlockState insideBlockState, - boolean existingOnly) { - for (int i = yMin; i <= yMax; ++i) { - for (int j = xMin; j <= xMax; ++j) { - for (int k = zMin; k <= zMax; ++k) { - if (!existingOnly || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() - .getMaterial() != Material.air) { - if (i != yMin && i != yMax && j != xMin && j != xMax && k != zMin && k != zMax) { - this.setBlockState(worldIn, insideBlockState, j, i, k, boundingboxIn); - } else { - this.setBlockState(worldIn, boundaryBlockState, j, i, k, boundingboxIn); - } - } - } - } - } - - } - - /**+ - * arguments: World worldObj, StructureBoundingBox structBB, int - * minX, int minY, int minZ, int maxX, int maxY, int maxZ, - * boolean alwaysreplace, Random rand, - * StructurePieceBlockSelector blockselector - */ - protected void fillWithRandomizedBlocks(World worldIn, StructureBoundingBox boundingboxIn, int minX, int minY, - int minZ, int maxX, int maxY, int maxZ, boolean alwaysReplace, EaglercraftRandom rand, - StructureComponent.BlockSelector blockselector) { - for (int i = minY; i <= maxY; ++i) { - for (int j = minX; j <= maxX; ++j) { - for (int k = minZ; k <= maxZ; ++k) { - if (!alwaysReplace || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() - .getMaterial() != Material.air) { - blockselector.selectBlocks(rand, j, i, k, - i == minY || i == maxY || j == minX || j == maxX || k == minZ || k == maxZ); - this.setBlockState(worldIn, blockselector.getBlockState(), j, i, k, boundingboxIn); - } - } - } - } - - } - - protected void func_175805_a(World worldIn, StructureBoundingBox boundingboxIn, EaglercraftRandom rand, - float chance, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, IBlockState blockstate1, - IBlockState blockstate2, boolean parFlag) { - for (int i = minY; i <= maxY; ++i) { - for (int j = minX; j <= maxX; ++j) { - for (int k = minZ; k <= maxZ; ++k) { - if (rand.nextFloat() <= chance - && (!parFlag || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() - .getMaterial() != Material.air)) { - if (i != minY && i != maxY && j != minX && j != maxX && k != minZ && k != maxZ) { - this.setBlockState(worldIn, blockstate2, j, i, k, boundingboxIn); - } else { - this.setBlockState(worldIn, blockstate1, j, i, k, boundingboxIn); - } - } - } - } + if (boundingBoxIn.isVecInside(blockpos)) { + ItemDoor.placeDoor(worldIn, blockpos, facing.rotateYCCW(), Blocks.oak_door); } } @@ -607,25 +658,29 @@ public abstract class StructureComponent { } - /**+ - * Deletes all continuous blocks from selected position upwards. - * Stops at hitting air. + /** + * + Reads and sets structure base data (boundingbox, + * {@link net.minecraft.world.gen.structure.StructureComponent#coordBaseMode + * coordBase} and + * {@link net.minecraft.world.gen.structure.StructureComponent#componentType + * componentType}) */ - protected void clearCurrentPositionBlocksUpwards(World worldIn, int x, int y, int z, - StructureBoundingBox structurebb) { - BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); - if (structurebb.isVecInside(blockpos)) { - while (!worldIn.isAirBlock(blockpos) && blockpos.getY() < 255) { - worldIn.setBlockState(blockpos, Blocks.air.getDefaultState(), 2); - blockpos = blockpos.up(); - } - + public void readStructureBaseNBT(World worldIn, NBTTagCompound tagCompound) { + if (tagCompound.hasKey("BB")) { + this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); } + + int i = tagCompound.getInteger("O"); + this.coordBaseMode = i == -1 ? null : EnumFacing.getHorizontal(i); + this.componentType = tagCompound.getInteger("GD"); + this.readStructureFromNBT(tagCompound); } - /**+ - * Replaces air and liquid from given position downwards. Stops - * when hitting anything else than air or liquid + protected abstract void readStructureFromNBT(NBTTagCompound var1); + + /** + * + Replaces air and liquid from given position downwards. Stops when hitting + * anything else than air or liquid */ protected void replaceAirAndLiquidDownwards(World worldIn, IBlockState blockstateIn, int x, int y, int z, StructureBoundingBox boundingboxIn) { @@ -642,64 +697,13 @@ public abstract class StructureComponent { } } - protected boolean generateChestContents(World world, StructureBoundingBox structureboundingbox, - EaglercraftRandom random, int i, int j, int k, List list, int l) { - BlockPos blockpos = new BlockPos(this.getXWithOffset(i, k), this.getYWithOffset(j), this.getZWithOffset(i, k)); - if (structureboundingbox.isVecInside(blockpos) && world.getBlockState(blockpos).getBlock() != Blocks.chest) { - IBlockState iblockstate = Blocks.chest.getDefaultState(); - world.setBlockState(blockpos, Blocks.chest.correctFacing(world, blockpos, iblockstate), 2); - TileEntity tileentity = world.getTileEntity(blockpos); - if (tileentity instanceof TileEntityChest) { - WeightedRandomChestContent.generateChestContents(random, list, (TileEntityChest) tileentity, l); - } - - return true; - } else { - return false; - } - } - - protected boolean generateDispenserContents(World worldIn, StructureBoundingBox boundingBoxIn, - EaglercraftRandom rand, int x, int y, int z, int meta, List listIn, int max) { + protected void setBlockState(World worldIn, IBlockState blockstateIn, int x, int y, int z, + StructureBoundingBox boundingboxIn) { BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); - if (boundingBoxIn.isVecInside(blockpos) && worldIn.getBlockState(blockpos).getBlock() != Blocks.dispenser) { - worldIn.setBlockState(blockpos, - Blocks.dispenser.getStateFromMeta(this.getMetadataWithOffset(Blocks.dispenser, meta)), 2); - TileEntity tileentity = worldIn.getTileEntity(blockpos); - if (tileentity instanceof TileEntityDispenser) { - WeightedRandomChestContent.generateDispenserContents(rand, listIn, (TileEntityDispenser) tileentity, - max); - } - - return true; - } else { - return false; + if (boundingboxIn.isVecInside(blockpos)) { + worldIn.setBlockState(blockpos, blockstateIn, 2); } } - /**+ - * Places door on given position - */ - protected void placeDoorCurrentPosition(World worldIn, StructureBoundingBox boundingBoxIn, EaglercraftRandom rand, - int x, int y, int z, EnumFacing facing) { - BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); - if (boundingBoxIn.isVecInside(blockpos)) { - ItemDoor.placeDoor(worldIn, blockpos, facing.rotateYCCW(), Blocks.oak_door); - } - - } - - public void func_181138_a(int i, int j, int k) { - this.boundingBox.offset(i, j, k); - } - - public abstract static class BlockSelector { - protected IBlockState blockstate = Blocks.air.getDefaultState(); - - public abstract void selectBlocks(EaglercraftRandom var1, int var2, int var3, int var4, boolean var5); - - public IBlockState getBlockState() { - return this.blockstate; - } - } + protected abstract void writeStructureToNBT(NBTTagCompound var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftPieces.java b/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftPieces.java index 0bf6c513..0d5b8563 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftPieces.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftPieces.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; @@ -19,130 +21,31 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureMineshaftPieces { - private static final List CHEST_CONTENT_WEIGHT_LIST = Lists.newArrayList( - new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.iron_ingot, 0, 1, 5, 10), - new WeightedRandomChestContent(Items.gold_ingot, 0, 1, 3, 5), - new WeightedRandomChestContent(Items.redstone, 0, 4, 9, 5), - new WeightedRandomChestContent(Items.dye, EnumDyeColor.BLUE.getDyeDamage(), 4, 9, 5), - new WeightedRandomChestContent(Items.diamond, 0, 1, 2, 3), - new WeightedRandomChestContent(Items.coal, 0, 3, 8, 10), - new WeightedRandomChestContent(Items.bread, 0, 1, 3, 15), - new WeightedRandomChestContent(Items.iron_pickaxe, 0, 1, 1, 1), - new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.rail), 0, 4, 8, 1), - new WeightedRandomChestContent(Items.melon_seeds, 0, 2, 4, 10), - new WeightedRandomChestContent(Items.pumpkin_seeds, 0, 2, 4, 10), - new WeightedRandomChestContent(Items.saddle, 0, 1, 1, 3), - new WeightedRandomChestContent(Items.iron_horse_armor, 0, 1, 1, 1) }); - - public static void registerStructurePieces() { - MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Corridor.class, "MSCorridor"); - MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Cross.class, "MSCrossing"); - MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Room.class, "MSRoom"); - MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Stairs.class, "MSStairs"); - } - - private static StructureComponent func_175892_a(List listIn, EaglercraftRandom rand, int x, - int y, int z, EnumFacing facing, int type) { - int i = rand.nextInt(100); - if (i >= 80) { - StructureBoundingBox structureboundingbox = StructureMineshaftPieces.Cross.func_175813_a(listIn, rand, x, y, - z, facing); - if (structureboundingbox != null) { - return new StructureMineshaftPieces.Cross(type, rand, structureboundingbox, facing); - } - } else if (i >= 70) { - StructureBoundingBox structureboundingbox1 = StructureMineshaftPieces.Stairs.func_175812_a(listIn, rand, x, - y, z, facing); - if (structureboundingbox1 != null) { - return new StructureMineshaftPieces.Stairs(type, rand, structureboundingbox1, facing); - } - } else { - StructureBoundingBox structureboundingbox2 = StructureMineshaftPieces.Corridor.func_175814_a(listIn, rand, - x, y, z, facing); - if (structureboundingbox2 != null) { - return new StructureMineshaftPieces.Corridor(type, rand, structureboundingbox2, facing); - } - } - - return null; - } - - private static StructureComponent func_175890_b(StructureComponent componentIn, List listIn, - EaglercraftRandom rand, int x, int y, int z, EnumFacing facing, int type) { - if (type > 8) { - return null; - } else if (Math.abs(x - componentIn.getBoundingBox().minX) <= 80 - && Math.abs(z - componentIn.getBoundingBox().minZ) <= 80) { - StructureComponent structurecomponent = func_175892_a(listIn, rand, x, y, z, facing, type + 1); - if (structurecomponent != null) { - listIn.add(structurecomponent); - structurecomponent.buildComponent(componentIn, listIn, rand); - } - - return structurecomponent; - } else { - return null; - } - } - public static class Corridor extends StructureComponent { - private boolean hasRails; - private boolean hasSpiders; - private boolean spawnerPlaced; - private int sectionCount; - - public Corridor() { - } - - protected void writeStructureToNBT(NBTTagCompound tagCompound) { - tagCompound.setBoolean("hr", this.hasRails); - tagCompound.setBoolean("sc", this.hasSpiders); - tagCompound.setBoolean("hps", this.spawnerPlaced); - tagCompound.setInteger("Num", this.sectionCount); - } - - protected void readStructureFromNBT(NBTTagCompound tagCompound) { - this.hasRails = tagCompound.getBoolean("hr"); - this.hasSpiders = tagCompound.getBoolean("sc"); - this.spawnerPlaced = tagCompound.getBoolean("hps"); - this.sectionCount = tagCompound.getInteger("Num"); - } - - public Corridor(int type, EaglercraftRandom rand, StructureBoundingBox structurebb, EnumFacing facing) { - super(type); - this.coordBaseMode = facing; - this.boundingBox = structurebb; - this.hasRails = rand.nextInt(3) == 0; - this.hasSpiders = !this.hasRails && rand.nextInt(23) == 0; - if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.SOUTH) { - this.sectionCount = structurebb.getXSize() / 5; - } else { - this.sectionCount = structurebb.getZSize() / 5; - } - - } - public static StructureBoundingBox func_175814_a(List rand, EaglercraftRandom x, int y, int z, int facing, EnumFacing parEnumFacing) { StructureBoundingBox structureboundingbox = new StructureBoundingBox(y, z, facing, y, z + 2, facing); @@ -176,118 +79,27 @@ public class StructureMineshaftPieces { return i > 0 ? structureboundingbox : null; } - public void buildComponent(StructureComponent componentIn, List listIn, - EaglercraftRandom rand) { - int i = this.getComponentType(); - int j = rand.nextInt(4); - if (this.coordBaseMode != null) { - switch (this.coordBaseMode) { - case NORTH: - if (j <= 1) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ - 1, - this.coordBaseMode, i); - } else if (j == 2) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, EnumFacing.WEST, i); - } else { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, EnumFacing.EAST, i); - } - break; - case SOUTH: - if (j <= 1) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ + 1, - this.coordBaseMode, i); - } else if (j == 2) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ - 3, EnumFacing.WEST, - i); - } else { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ - 3, EnumFacing.EAST, - i); - } - break; - case WEST: - if (j <= 1) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, this.coordBaseMode, - i); - } else if (j == 2) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ - 1, - EnumFacing.NORTH, i); - } else { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ + 1, - EnumFacing.SOUTH, i); - } - break; - case EAST: - if (j <= 1) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, this.coordBaseMode, - i); - } else if (j == 2) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX - 3, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ - 1, - EnumFacing.NORTH, i); - } else { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX - 3, - this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ + 1, - EnumFacing.SOUTH, i); - } - } - } + private boolean hasRails; + private boolean hasSpiders; + private boolean spawnerPlaced; - if (i < 8) { - if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.SOUTH) { - for (int i1 = this.boundingBox.minX + 3; i1 + 3 <= this.boundingBox.maxX; i1 += 5) { - int j1 = rand.nextInt(5); - if (j1 == 0) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, i1, this.boundingBox.minY, - this.boundingBox.minZ - 1, EnumFacing.NORTH, i + 1); - } else if (j1 == 1) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, i1, this.boundingBox.minY, - this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i + 1); - } - } - } else { - for (int k = this.boundingBox.minZ + 3; k + 3 <= this.boundingBox.maxZ; k += 5) { - int l = rand.nextInt(5); - if (l == 0) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, - this.boundingBox.minY, k, EnumFacing.WEST, i + 1); - } else if (l == 1) { - StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, - this.boundingBox.minY, k, EnumFacing.EAST, i + 1); - } - } - } - } + private int sectionCount; + public Corridor() { } - protected boolean generateChestContents(World worldIn, StructureBoundingBox boundingBoxIn, - EaglercraftRandom rand, int x, int y, int z, List listIn, int max) { - BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), - this.getZWithOffset(x, z)); - if (boundingBoxIn.isVecInside(blockpos) - && worldIn.getBlockState(blockpos).getBlock().getMaterial() == Material.air) { - int i = rand.nextBoolean() ? 1 : 0; - worldIn.setBlockState(blockpos, - Blocks.rail.getStateFromMeta(this.getMetadataWithOffset(Blocks.rail, i)), 2); - EntityMinecartChest entityminecartchest = new EntityMinecartChest(worldIn, - (double) ((float) blockpos.getX() + 0.5F), (double) ((float) blockpos.getY() + 0.5F), - (double) ((float) blockpos.getZ() + 0.5F)); - WeightedRandomChestContent.generateChestContents(rand, listIn, entityminecartchest, max); - worldIn.spawnEntityInWorld(entityminecartchest); - return true; + public Corridor(int type, EaglercraftRandom rand, StructureBoundingBox structurebb, EnumFacing facing) { + super(type); + this.coordBaseMode = facing; + this.boundingBox = structurebb; + this.hasRails = rand.nextInt(3) == 0; + this.hasSpiders = !this.hasRails && rand.nextInt(23) == 0; + if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.SOUTH) { + this.sectionCount = structurebb.getXSize() / 5; } else { - return false; + this.sectionCount = structurebb.getZSize() / 5; } + } public boolean addComponentParts(World worldIn, EaglercraftRandom randomIn, @@ -405,32 +217,137 @@ public class StructureMineshaftPieces { return true; } } + + public void buildComponent(StructureComponent componentIn, List listIn, + EaglercraftRandom rand) { + int i = this.getComponentType(); + int j = rand.nextInt(4); + if (this.coordBaseMode != null) { + switch (this.coordBaseMode) { + case NORTH: + if (j <= 1) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ - 1, + this.coordBaseMode, i); + } else if (j == 2) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, EnumFacing.WEST, i); + } else { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, EnumFacing.EAST, i); + } + break; + case SOUTH: + if (j <= 1) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ + 1, + this.coordBaseMode, i); + } else if (j == 2) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ - 3, EnumFacing.WEST, + i); + } else { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ - 3, EnumFacing.EAST, + i); + } + break; + case WEST: + if (j <= 1) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, this.coordBaseMode, + i); + } else if (j == 2) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ - 1, + EnumFacing.NORTH, i); + } else { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ + 1, + EnumFacing.SOUTH, i); + } + break; + case EAST: + if (j <= 1) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ, this.coordBaseMode, + i); + } else if (j == 2) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX - 3, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.minZ - 1, + EnumFacing.NORTH, i); + } else { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX - 3, + this.boundingBox.minY - 1 + rand.nextInt(3), this.boundingBox.maxZ + 1, + EnumFacing.SOUTH, i); + } + } + } + + if (i < 8) { + if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.SOUTH) { + for (int i1 = this.boundingBox.minX + 3; i1 + 3 <= this.boundingBox.maxX; i1 += 5) { + int j1 = rand.nextInt(5); + if (j1 == 0) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, i1, this.boundingBox.minY, + this.boundingBox.minZ - 1, EnumFacing.NORTH, i + 1); + } else if (j1 == 1) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, i1, this.boundingBox.minY, + this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i + 1); + } + } + } else { + for (int k = this.boundingBox.minZ + 3; k + 3 <= this.boundingBox.maxZ; k += 5) { + int l = rand.nextInt(5); + if (l == 0) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.minX - 1, + this.boundingBox.minY, k, EnumFacing.WEST, i + 1); + } else if (l == 1) { + StructureMineshaftPieces.func_175890_b(componentIn, listIn, rand, this.boundingBox.maxX + 1, + this.boundingBox.minY, k, EnumFacing.EAST, i + 1); + } + } + } + } + + } + + protected boolean generateChestContents(World worldIn, StructureBoundingBox boundingBoxIn, + EaglercraftRandom rand, int x, int y, int z, List listIn, int max) { + BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), + this.getZWithOffset(x, z)); + if (boundingBoxIn.isVecInside(blockpos) + && worldIn.getBlockState(blockpos).getBlock().getMaterial() == Material.air) { + int i = rand.nextBoolean() ? 1 : 0; + worldIn.setBlockState(blockpos, + Blocks.rail.getStateFromMeta(this.getMetadataWithOffset(Blocks.rail, i)), 2); + EntityMinecartChest entityminecartchest = new EntityMinecartChest(worldIn, + (double) ((float) blockpos.getX() + 0.5F), (double) ((float) blockpos.getY() + 0.5F), + (double) ((float) blockpos.getZ() + 0.5F)); + WeightedRandomChestContent.generateChestContents(rand, listIn, entityminecartchest, max); + worldIn.spawnEntityInWorld(entityminecartchest); + return true; + } else { + return false; + } + } + + protected void readStructureFromNBT(NBTTagCompound tagCompound) { + this.hasRails = tagCompound.getBoolean("hr"); + this.hasSpiders = tagCompound.getBoolean("sc"); + this.spawnerPlaced = tagCompound.getBoolean("hps"); + this.sectionCount = tagCompound.getInteger("Num"); + } + + protected void writeStructureToNBT(NBTTagCompound tagCompound) { + tagCompound.setBoolean("hr", this.hasRails); + tagCompound.setBoolean("sc", this.hasSpiders); + tagCompound.setBoolean("hps", this.spawnerPlaced); + tagCompound.setInteger("Num", this.sectionCount); + } } public static class Cross extends StructureComponent { - private EnumFacing corridorDirection; - private boolean isMultipleFloors; - - public Cross() { - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setBoolean("tf", this.isMultipleFloors); - nbttagcompound.setInteger("D", this.corridorDirection.getHorizontalIndex()); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - this.isMultipleFloors = nbttagcompound.getBoolean("tf"); - this.corridorDirection = EnumFacing.getHorizontal(nbttagcompound.getInteger("D")); - } - - public Cross(int type, EaglercraftRandom rand, StructureBoundingBox structurebb, EnumFacing facing) { - super(type); - this.corridorDirection = facing; - this.boundingBox = structurebb; - this.isMultipleFloors = structurebb.getYSize() > 3; - } - public static StructureBoundingBox func_175813_a(List listIn, EaglercraftRandom rand, int x, int y, int z, EnumFacing facing) { StructureBoundingBox structureboundingbox = new StructureBoundingBox(x, y, z, x, y + 2, z); @@ -464,65 +381,18 @@ public class StructureMineshaftPieces { : structureboundingbox; } - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - int i = this.getComponentType(); - switch (this.corridorDirection) { - case NORTH: - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, - this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.WEST, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, - this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.EAST, i); - break; - case SOUTH: - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, - this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.WEST, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, - this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.EAST, i); - break; - case WEST: - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, - this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.WEST, i); - break; - case EAST: - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, - this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.EAST, i); - } + private EnumFacing corridorDirection; - if (this.isMultipleFloors) { - if (random.nextBoolean()) { - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY + 3 + 1, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); - } + private boolean isMultipleFloors; - if (random.nextBoolean()) { - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, - this.boundingBox.minY + 3 + 1, this.boundingBox.minZ + 1, EnumFacing.WEST, i); - } - - if (random.nextBoolean()) { - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, - this.boundingBox.minY + 3 + 1, this.boundingBox.minZ + 1, EnumFacing.EAST, i); - } - - if (random.nextBoolean()) { - StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, - this.boundingBox.minY + 3 + 1, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); - } - } + public Cross() { + } + public Cross(int type, EaglercraftRandom rand, StructureBoundingBox structurebb, EnumFacing facing) { + super(type); + this.corridorDirection = facing; + this.boundingBox = structurebb; + this.isMultipleFloors = structurebb.getYSize() > 3; } public boolean addComponentParts(World world, EaglercraftRandom var2, @@ -590,6 +460,77 @@ public class StructureMineshaftPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + int i = this.getComponentType(); + switch (this.corridorDirection) { + case NORTH: + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, + this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.WEST, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, + this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.EAST, i); + break; + case SOUTH: + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, + this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.WEST, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, + this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.EAST, i); + break; + case WEST: + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, + this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.WEST, i); + break; + case EAST: + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, + this.boundingBox.minY, this.boundingBox.minZ + 1, EnumFacing.EAST, i); + } + + if (this.isMultipleFloors) { + if (random.nextBoolean()) { + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY + 3 + 1, this.boundingBox.minZ - 1, EnumFacing.NORTH, i); + } + + if (random.nextBoolean()) { + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX - 1, + this.boundingBox.minY + 3 + 1, this.boundingBox.minZ + 1, EnumFacing.WEST, i); + } + + if (random.nextBoolean()) { + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.maxX + 1, + this.boundingBox.minY + 3 + 1, this.boundingBox.minZ + 1, EnumFacing.EAST, i); + } + + if (random.nextBoolean()) { + StructureMineshaftPieces.func_175890_b(structurecomponent, list, random, this.boundingBox.minX + 1, + this.boundingBox.minY + 3 + 1, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, i); + } + } + + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + this.isMultipleFloors = nbttagcompound.getBoolean("tf"); + this.corridorDirection = EnumFacing.getHorizontal(nbttagcompound.getInteger("D")); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setBoolean("tf", this.isMultipleFloors); + nbttagcompound.setInteger("D", this.corridorDirection.getHorizontalIndex()); + } } public static class Room extends StructureComponent { @@ -604,6 +545,33 @@ public class StructureMineshaftPieces { z + 7 + rand.nextInt(6)); } + public boolean addComponentParts(World world, EaglercraftRandom var2, + StructureBoundingBox structureboundingbox) { + if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { + return false; + } else { + this.fillWithBlocks(world, structureboundingbox, this.boundingBox.minX, this.boundingBox.minY, + this.boundingBox.minZ, this.boundingBox.maxX, this.boundingBox.minY, this.boundingBox.maxZ, + Blocks.dirt.getDefaultState(), Blocks.air.getDefaultState(), true); + this.fillWithBlocks(world, structureboundingbox, this.boundingBox.minX, this.boundingBox.minY + 1, + this.boundingBox.minZ, this.boundingBox.maxX, + Math.min(this.boundingBox.minY + 3, this.boundingBox.maxY), this.boundingBox.maxZ, + Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false); + + for (StructureBoundingBox structureboundingbox1 : this.roomsLinkedToTheRoom) { + this.fillWithBlocks(world, structureboundingbox, structureboundingbox1.minX, + structureboundingbox1.maxY - 2, structureboundingbox1.minZ, structureboundingbox1.maxX, + structureboundingbox1.maxY, structureboundingbox1.maxZ, Blocks.air.getDefaultState(), + Blocks.air.getDefaultState(), false); + } + + this.randomlyRareFillWithBlocks(world, structureboundingbox, this.boundingBox.minX, + this.boundingBox.minY + 4, this.boundingBox.minZ, this.boundingBox.maxX, this.boundingBox.maxY, + this.boundingBox.maxZ, Blocks.air.getDefaultState(), false); + return true; + } + } + public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { int i = this.getComponentType(); @@ -683,33 +651,6 @@ public class StructureMineshaftPieces { } - public boolean addComponentParts(World world, EaglercraftRandom var2, - StructureBoundingBox structureboundingbox) { - if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { - return false; - } else { - this.fillWithBlocks(world, structureboundingbox, this.boundingBox.minX, this.boundingBox.minY, - this.boundingBox.minZ, this.boundingBox.maxX, this.boundingBox.minY, this.boundingBox.maxZ, - Blocks.dirt.getDefaultState(), Blocks.air.getDefaultState(), true); - this.fillWithBlocks(world, structureboundingbox, this.boundingBox.minX, this.boundingBox.minY + 1, - this.boundingBox.minZ, this.boundingBox.maxX, - Math.min(this.boundingBox.minY + 3, this.boundingBox.maxY), this.boundingBox.maxZ, - Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false); - - for (StructureBoundingBox structureboundingbox1 : this.roomsLinkedToTheRoom) { - this.fillWithBlocks(world, structureboundingbox, structureboundingbox1.minX, - structureboundingbox1.maxY - 2, structureboundingbox1.minZ, structureboundingbox1.maxX, - structureboundingbox1.maxY, structureboundingbox1.maxZ, Blocks.air.getDefaultState(), - Blocks.air.getDefaultState(), false); - } - - this.randomlyRareFillWithBlocks(world, structureboundingbox, this.boundingBox.minX, - this.boundingBox.minY + 4, this.boundingBox.minZ, this.boundingBox.maxX, this.boundingBox.maxY, - this.boundingBox.maxZ, Blocks.air.getDefaultState(), false); - return true; - } - } - public void func_181138_a(int parInt1, int parInt2, int parInt3) { super.func_181138_a(parInt1, parInt2, parInt3); @@ -719,6 +660,15 @@ public class StructureMineshaftPieces { } + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + NBTTagList nbttaglist = nbttagcompound.getTagList("Entrances", 11); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + this.roomsLinkedToTheRoom.add(new StructureBoundingBox(nbttaglist.getIntArrayAt(i))); + } + + } + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { NBTTagList nbttaglist = new NBTTagList(); @@ -728,33 +678,9 @@ public class StructureMineshaftPieces { nbttagcompound.setTag("Entrances", nbttaglist); } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - NBTTagList nbttaglist = nbttagcompound.getTagList("Entrances", 11); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - this.roomsLinkedToTheRoom.add(new StructureBoundingBox(nbttaglist.getIntArrayAt(i))); - } - - } } public static class Stairs extends StructureComponent { - public Stairs() { - } - - public Stairs(int type, EaglercraftRandom rand, StructureBoundingBox structurebb, EnumFacing facing) { - super(type); - this.coordBaseMode = facing; - this.boundingBox = structurebb; - } - - protected void writeStructureToNBT(NBTTagCompound var1) { - } - - protected void readStructureFromNBT(NBTTagCompound var1) { - } - public static StructureBoundingBox func_175812_a(List listIn, EaglercraftRandom rand, int x, int y, int z, EnumFacing facing) { StructureBoundingBox structureboundingbox = new StructureBoundingBox(x, y - 5, z, x, y + 2, z); @@ -780,6 +706,34 @@ public class StructureMineshaftPieces { : structureboundingbox; } + public Stairs() { + } + + public Stairs(int type, EaglercraftRandom rand, StructureBoundingBox structurebb, EnumFacing facing) { + super(type); + this.coordBaseMode = facing; + this.boundingBox = structurebb; + } + + public boolean addComponentParts(World world, EaglercraftRandom var2, + StructureBoundingBox structureboundingbox) { + if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { + return false; + } else { + this.fillWithBlocks(world, structureboundingbox, 0, 5, 0, 2, 7, 1, Blocks.air.getDefaultState(), + Blocks.air.getDefaultState(), false); + this.fillWithBlocks(world, structureboundingbox, 0, 0, 7, 2, 2, 8, Blocks.air.getDefaultState(), + Blocks.air.getDefaultState(), false); + + for (int i = 0; i < 5; ++i) { + this.fillWithBlocks(world, structureboundingbox, 0, 5 - i - (i < 4 ? 1 : 0), 2 + i, 2, 7 - i, 2 + i, + Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false); + } + + return true; + } + } + public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { int i = this.getComponentType(); @@ -805,23 +759,76 @@ public class StructureMineshaftPieces { } - public boolean addComponentParts(World world, EaglercraftRandom var2, - StructureBoundingBox structureboundingbox) { - if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { - return false; - } else { - this.fillWithBlocks(world, structureboundingbox, 0, 5, 0, 2, 7, 1, Blocks.air.getDefaultState(), - Blocks.air.getDefaultState(), false); - this.fillWithBlocks(world, structureboundingbox, 0, 0, 7, 2, 2, 8, Blocks.air.getDefaultState(), - Blocks.air.getDefaultState(), false); + protected void readStructureFromNBT(NBTTagCompound var1) { + } - for (int i = 0; i < 5; ++i) { - this.fillWithBlocks(world, structureboundingbox, 0, 5 - i - (i < 4 ? 1 : 0), 2 + i, 2, 7 - i, 2 + i, - Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false); - } - - return true; - } + protected void writeStructureToNBT(NBTTagCompound var1) { } } + + private static final List CHEST_CONTENT_WEIGHT_LIST = Lists.newArrayList( + new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.iron_ingot, 0, 1, 5, 10), + new WeightedRandomChestContent(Items.gold_ingot, 0, 1, 3, 5), + new WeightedRandomChestContent(Items.redstone, 0, 4, 9, 5), + new WeightedRandomChestContent(Items.dye, EnumDyeColor.BLUE.getDyeDamage(), 4, 9, 5), + new WeightedRandomChestContent(Items.diamond, 0, 1, 2, 3), + new WeightedRandomChestContent(Items.coal, 0, 3, 8, 10), + new WeightedRandomChestContent(Items.bread, 0, 1, 3, 15), + new WeightedRandomChestContent(Items.iron_pickaxe, 0, 1, 1, 1), + new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.rail), 0, 4, 8, 1), + new WeightedRandomChestContent(Items.melon_seeds, 0, 2, 4, 10), + new WeightedRandomChestContent(Items.pumpkin_seeds, 0, 2, 4, 10), + new WeightedRandomChestContent(Items.saddle, 0, 1, 1, 3), + new WeightedRandomChestContent(Items.iron_horse_armor, 0, 1, 1, 1) }); + + private static StructureComponent func_175890_b(StructureComponent componentIn, List listIn, + EaglercraftRandom rand, int x, int y, int z, EnumFacing facing, int type) { + if (type > 8) { + return null; + } else if (Math.abs(x - componentIn.getBoundingBox().minX) <= 80 + && Math.abs(z - componentIn.getBoundingBox().minZ) <= 80) { + StructureComponent structurecomponent = func_175892_a(listIn, rand, x, y, z, facing, type + 1); + if (structurecomponent != null) { + listIn.add(structurecomponent); + structurecomponent.buildComponent(componentIn, listIn, rand); + } + + return structurecomponent; + } else { + return null; + } + } + + private static StructureComponent func_175892_a(List listIn, EaglercraftRandom rand, int x, + int y, int z, EnumFacing facing, int type) { + int i = rand.nextInt(100); + if (i >= 80) { + StructureBoundingBox structureboundingbox = StructureMineshaftPieces.Cross.func_175813_a(listIn, rand, x, y, + z, facing); + if (structureboundingbox != null) { + return new StructureMineshaftPieces.Cross(type, rand, structureboundingbox, facing); + } + } else if (i >= 70) { + StructureBoundingBox structureboundingbox1 = StructureMineshaftPieces.Stairs.func_175812_a(listIn, rand, x, + y, z, facing); + if (structureboundingbox1 != null) { + return new StructureMineshaftPieces.Stairs(type, rand, structureboundingbox1, facing); + } + } else { + StructureBoundingBox structureboundingbox2 = StructureMineshaftPieces.Corridor.func_175814_a(listIn, rand, + x, y, z, facing); + if (structureboundingbox2 != null) { + return new StructureMineshaftPieces.Corridor(type, rand, structureboundingbox2, facing); + } + } + + return null; + } + + public static void registerStructurePieces() { + MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Corridor.class, "MSCorridor"); + MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Cross.class, "MSCrossing"); + MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Room.class, "MSRoom"); + MapGenStructureIO.registerStructureComponent(StructureMineshaftPieces.Stairs.class, "MSStairs"); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftStart.java b/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftStart.java index cbfc1d63..74043e1e 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftStart.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureMineshaftStart.java @@ -3,22 +3,25 @@ package net.minecraft.world.gen.structure; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureNetherBridgePieces.java b/src/game/java/net/minecraft/world/gen/structure/StructureNetherBridgePieces.java index 06a647c5..22aee858 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureNetherBridgePieces.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureNetherBridgePieces.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.init.Blocks; import net.minecraft.init.Items; @@ -14,111 +16,43 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureNetherBridgePieces { - private static final StructureNetherBridgePieces.PieceWeight[] primaryComponents = new StructureNetherBridgePieces.PieceWeight[] { - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Straight.class, 30, 0, true), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Crossing3.class, 10, 4), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Crossing.class, 10, 4), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Stairs.class, 10, 3), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Throne.class, 5, 2), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Entrance.class, 5, 1) }; - private static final StructureNetherBridgePieces.PieceWeight[] secondaryComponents = new StructureNetherBridgePieces.PieceWeight[] { - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor5.class, 25, 0, true), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Crossing2.class, 15, 5), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor2.class, 5, 10), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor.class, 5, 10), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor3.class, 10, 3, true), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor4.class, 7, 2), - new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.NetherStalkRoom.class, 5, 2) }; - - public static void registerNetherFortressPieces() { - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Crossing3.class, "NeBCr"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.End.class, "NeBEF"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Straight.class, "NeBS"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor3.class, "NeCCS"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor4.class, "NeCTB"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Entrance.class, "NeCE"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Crossing2.class, "NeSCSC"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor.class, "NeSCLT"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor5.class, "NeSC"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor2.class, "NeSCRT"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.NetherStalkRoom.class, "NeCSR"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Throne.class, "NeMT"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Crossing.class, "NeRC"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Stairs.class, "NeSR"); - MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Start.class, "NeStart"); - } - - private static StructureNetherBridgePieces.Piece func_175887_b( - StructureNetherBridgePieces.PieceWeight parPieceWeight, List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { - Class oclass = parPieceWeight.weightClass; - Object object = null; - if (oclass == StructureNetherBridgePieces.Straight.class) { - object = StructureNetherBridgePieces.Straight.func_175882_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Crossing3.class) { - object = StructureNetherBridgePieces.Crossing3.func_175885_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Crossing.class) { - object = StructureNetherBridgePieces.Crossing.func_175873_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Stairs.class) { - object = StructureNetherBridgePieces.Stairs.func_175872_a(parList, parRandom, parInt1, parInt2, parInt3, - parInt4, parEnumFacing); - } else if (oclass == StructureNetherBridgePieces.Throne.class) { - object = StructureNetherBridgePieces.Throne.func_175874_a(parList, parRandom, parInt1, parInt2, parInt3, - parInt4, parEnumFacing); - } else if (oclass == StructureNetherBridgePieces.Entrance.class) { - object = StructureNetherBridgePieces.Entrance.func_175881_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Corridor5.class) { - object = StructureNetherBridgePieces.Corridor5.func_175877_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Corridor2.class) { - object = StructureNetherBridgePieces.Corridor2.func_175876_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Corridor.class) { - object = StructureNetherBridgePieces.Corridor.func_175879_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Corridor3.class) { - object = StructureNetherBridgePieces.Corridor3.func_175883_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Corridor4.class) { - object = StructureNetherBridgePieces.Corridor4.func_175880_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.Crossing2.class) { - object = StructureNetherBridgePieces.Crossing2.func_175878_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureNetherBridgePieces.NetherStalkRoom.class) { - object = StructureNetherBridgePieces.NetherStalkRoom.func_175875_a(parList, parRandom, parInt1, parInt2, - parInt3, parEnumFacing, parInt4); + public static class Corridor extends StructureNetherBridgePieces.Piece { + public static StructureNetherBridgePieces.Corridor func_175879_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -1, 0, 0, 5, 7, 5, parEnumFacing); + return isAboveGround(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureNetherBridgePieces.Corridor(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; } - return (StructureNetherBridgePieces.Piece) object; - } - - public static class Corridor extends StructureNetherBridgePieces.Piece { private boolean field_111021_b; public Corridor() { @@ -132,33 +66,6 @@ public class StructureNetherBridgePieces { this.field_111021_b = parRandom.nextInt(3) == 0; } - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.field_111021_b = nbttagcompound.getBoolean("Chest"); - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Chest", this.field_111021_b); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); - } - - public static StructureNetherBridgePieces.Corridor func_175879_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -1, 0, 0, 5, 7, 5, parEnumFacing); - return isAboveGround(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureNetherBridgePieces.Corridor(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.nether_brick.getDefaultState(), @@ -198,9 +105,36 @@ public class StructureNetherBridgePieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_111021_b = nbttagcompound.getBoolean("Chest"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.field_111021_b); + } } public static class Corridor2 extends StructureNetherBridgePieces.Piece { + public static StructureNetherBridgePieces.Corridor2 func_175876_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -1, 0, 0, 5, 7, 5, parEnumFacing); + return isAboveGround(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureNetherBridgePieces.Corridor2(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; + } + private boolean field_111020_b; public Corridor2() { @@ -214,33 +148,6 @@ public class StructureNetherBridgePieces { this.field_111020_b = parRandom.nextInt(3) == 0; } - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.field_111020_b = nbttagcompound.getBoolean("Chest"); - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Chest", this.field_111020_b); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); - } - - public static StructureNetherBridgePieces.Corridor2 func_175876_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -1, 0, 0, 5, 7, 5, parEnumFacing); - return isAboveGround(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureNetherBridgePieces.Corridor2(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.nether_brick.getDefaultState(), @@ -280,25 +187,24 @@ public class StructureNetherBridgePieces { return true; } - } - - public static class Corridor3 extends StructureNetherBridgePieces.Piece { - public Corridor3() { - } - - public Corridor3(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 0, - true); + this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); } + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_111020_b = nbttagcompound.getBoolean("Chest"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.field_111020_b); + } + } + + public static class Corridor3 extends StructureNetherBridgePieces.Piece { public static StructureNetherBridgePieces.Corridor3 func_175883_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -311,6 +217,16 @@ public class StructureNetherBridgePieces { : null; } + public Corridor3() { + } + + public Corridor3(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { int i = this.getMetadataWithOffset(Blocks.nether_brick_stairs, 2); @@ -355,32 +271,15 @@ public class StructureNetherBridgePieces { return true; } - } - - public static class Corridor4 extends StructureNetherBridgePieces.Piece { - public Corridor4() { - } - - public Corridor4(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { - byte b0 = 1; - if (this.coordBaseMode == EnumFacing.WEST || this.coordBaseMode == EnumFacing.NORTH) { - b0 = 5; - } - - this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, b0, - random.nextInt(8) > 0); - this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, b0, - random.nextInt(8) > 0); + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 0, + true); } + } + public static class Corridor4 extends StructureNetherBridgePieces.Piece { public static StructureNetherBridgePieces.Corridor4 func_175880_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -393,6 +292,16 @@ public class StructureNetherBridgePieces { : null; } + public Corridor4() { + } + + public Corridor4(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 8, 1, 8, Blocks.nether_brick.getDefaultState(), @@ -443,25 +352,22 @@ public class StructureNetherBridgePieces { return true; } - } - - public static class Corridor5 extends StructureNetherBridgePieces.Piece { - public Corridor5() { - } - - public Corridor5(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 0, - true); - } + byte b0 = 1; + if (this.coordBaseMode == EnumFacing.WEST || this.coordBaseMode == EnumFacing.NORTH) { + b0 = 5; + } + this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, b0, + random.nextInt(8) > 0); + this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, b0, + random.nextInt(8) > 0); + } + } + + public static class Corridor5 extends StructureNetherBridgePieces.Piece { public static StructureNetherBridgePieces.Corridor5 func_175877_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -474,6 +380,16 @@ public class StructureNetherBridgePieces { : null; } + public Corridor5() { + } + + public Corridor5(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.nether_brick.getDefaultState(), @@ -504,27 +420,15 @@ public class StructureNetherBridgePieces { return true; } - } - - public static class Crossing extends StructureNetherBridgePieces.Piece { - public Crossing() { - } - - public Crossing(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 2, 0, - false); - this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 2, false); - this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 2, false); + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 0, + true); } + } + public static class Crossing extends StructureNetherBridgePieces.Piece { public static StructureNetherBridgePieces.Crossing func_175873_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -537,6 +441,16 @@ public class StructureNetherBridgePieces { : null; } + public Crossing() { + } + + public Crossing(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 6, 1, 6, Blocks.nether_brick.getDefaultState(), @@ -585,27 +499,17 @@ public class StructureNetherBridgePieces { return true; } - } - - public static class Crossing2 extends StructureNetherBridgePieces.Piece { - public Crossing2() { - } - - public Crossing2(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 0, - true); - this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); - this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 2, 0, + false); + this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 2, false); + this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 2, false); } + } + public static class Crossing2 extends StructureNetherBridgePieces.Piece { public static StructureNetherBridgePieces.Crossing2 func_175878_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -618,6 +522,16 @@ public class StructureNetherBridgePieces { : null; } + public Crossing2() { + } + + public Crossing2(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 4, 1, 4, Blocks.nether_brick.getDefaultState(), @@ -644,17 +558,30 @@ public class StructureNetherBridgePieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 0, + true); + this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); + this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 0, 1, true); + } } public static class Crossing3 extends StructureNetherBridgePieces.Piece { - public Crossing3() { + public static StructureNetherBridgePieces.Crossing3 func_175885_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -8, -3, 0, 19, 10, 19, parEnumFacing); + return isAboveGround(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureNetherBridgePieces.Crossing3(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; } - public Crossing3(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; + public Crossing3() { } protected Crossing3(EaglercraftRandom parRandom, int parInt1, int parInt2) { @@ -673,24 +600,11 @@ public class StructureNetherBridgePieces { } - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 8, 3, - false); - this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 3, 8, false); - this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 3, 8, false); - } - - public static StructureNetherBridgePieces.Crossing3 func_175885_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -8, -3, 0, 19, 10, 19, parEnumFacing); - return isAboveGround(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureNetherBridgePieces.Crossing3(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; + public Crossing3(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; } public boolean addComponentParts(World world, EaglercraftRandom var2, @@ -757,22 +671,17 @@ public class StructureNetherBridgePieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 8, 3, + false); + this.getNextComponentX((StructureNetherBridgePieces.Start) structurecomponent, list, random, 3, 8, false); + this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 3, 8, false); + } } public static class End extends StructureNetherBridgePieces.Piece { - private int fillSeed; - - public End() { - } - - public End(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - this.fillSeed = parRandom.nextInt(); - } - public static StructureNetherBridgePieces.End func_175884_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -785,14 +694,17 @@ public class StructureNetherBridgePieces { : null; } - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.fillSeed = nbttagcompound.getInteger("Seed"); + private int fillSeed; + + public End() { } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("Seed", this.fillSeed); + public End(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + this.fillSeed = parRandom.nextInt(); } public boolean addComponentParts(World world, EaglercraftRandom var2, @@ -830,25 +742,19 @@ public class StructureNetherBridgePieces { return true; } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.fillSeed = nbttagcompound.getInteger("Seed"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("Seed", this.fillSeed); + } } public static class Entrance extends StructureNetherBridgePieces.Piece { - public Entrance() { - } - - public Entrance(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 5, 3, - true); - } - public static StructureNetherBridgePieces.Entrance func_175881_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -861,6 +767,16 @@ public class StructureNetherBridgePieces { : null; } + public Entrance() { + } + + public Entrance(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 3, 0, 12, 4, 12, Blocks.nether_brick.getDefaultState(), @@ -974,27 +890,15 @@ public class StructureNetherBridgePieces { return true; } - } - - public static class NetherStalkRoom extends StructureNetherBridgePieces.Piece { - public NetherStalkRoom() { - } - - public NetherStalkRoom(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 5, 3, true); - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 5, 11, - true); } + } + public static class NetherStalkRoom extends StructureNetherBridgePieces.Piece { public static StructureNetherBridgePieces.NetherStalkRoom func_175875_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -1007,6 +911,16 @@ public class StructureNetherBridgePieces { : null; } + public NetherStalkRoom() { + } + + public NetherStalkRoom(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 3, 0, 12, 4, 12, Blocks.nether_brick.getDefaultState(), @@ -1171,6 +1085,14 @@ public class StructureNetherBridgePieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 5, 3, + true); + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 5, 11, + true); + } } abstract static class Piece extends StructureComponent { @@ -1188,6 +1110,10 @@ public class StructureNetherBridgePieces { new WeightedRandomChestContent(Items.diamond_horse_armor, 0, 1, 1, 3), new WeightedRandomChestContent(Item.getItemFromBlock(Blocks.obsidian), 0, 2, 4, 2) }); + protected static boolean isAboveGround(StructureBoundingBox parStructureBoundingBox) { + return parStructureBoundingBox != null && parStructureBoundingBox.minY > 10; + } + public Piece() { } @@ -1195,26 +1121,28 @@ public class StructureNetherBridgePieces { super(parInt1); } - protected void readStructureFromNBT(NBTTagCompound var1) { - } - - protected void writeStructureToNBT(NBTTagCompound var1) { - } - - private int getTotalWeight(List parList) { - boolean flag = false; - int i = 0; - - for (StructureNetherBridgePieces.PieceWeight structurenetherbridgepieces$pieceweight : parList) { - if (structurenetherbridgepieces$pieceweight.field_78824_d > 0 - && structurenetherbridgepieces$pieceweight.field_78827_c < structurenetherbridgepieces$pieceweight.field_78824_d) { - flag = true; + private StructureComponent func_175870_a(StructureNetherBridgePieces.Start parStart, + List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4, boolean parFlag) { + if (Math.abs(parInt1 - parStart.getBoundingBox().minX) <= 112 + && Math.abs(parInt3 - parStart.getBoundingBox().minZ) <= 112) { + List list = parStart.primaryWeights; + if (parFlag) { + list = parStart.secondaryWeights; } - i += structurenetherbridgepieces$pieceweight.field_78826_b; - } + StructureNetherBridgePieces.Piece structurenetherbridgepieces$piece = this.func_175871_a(parStart, list, + parList, parRandom, parInt1, parInt2, parInt3, parEnumFacing, parInt4 + 1); + if (structurenetherbridgepieces$piece != null) { + parList.add(structurenetherbridgepieces$piece); + parStart.field_74967_d.add(structurenetherbridgepieces$piece); + } - return flag ? i : -1; + return structurenetherbridgepieces$piece; + } else { + return StructureNetherBridgePieces.End.func_175884_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } } private StructureNetherBridgePieces.Piece func_175871_a(StructureNetherBridgePieces.Start parStart, @@ -1258,30 +1186,6 @@ public class StructureNetherBridgePieces { parEnumFacing, parInt4); } - private StructureComponent func_175870_a(StructureNetherBridgePieces.Start parStart, - List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4, boolean parFlag) { - if (Math.abs(parInt1 - parStart.getBoundingBox().minX) <= 112 - && Math.abs(parInt3 - parStart.getBoundingBox().minZ) <= 112) { - List list = parStart.primaryWeights; - if (parFlag) { - list = parStart.secondaryWeights; - } - - StructureNetherBridgePieces.Piece structurenetherbridgepieces$piece = this.func_175871_a(parStart, list, - parList, parRandom, parInt1, parInt2, parInt3, parEnumFacing, parInt4 + 1); - if (structurenetherbridgepieces$piece != null) { - parList.add(structurenetherbridgepieces$piece); - parStart.field_74967_d.add(structurenetherbridgepieces$piece); - } - - return structurenetherbridgepieces$piece; - } else { - return StructureNetherBridgePieces.End.func_175884_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } - } - protected StructureComponent getNextComponentNormal(StructureNetherBridgePieces.Start parStart, List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, boolean parFlag) { @@ -1363,8 +1267,26 @@ public class StructureNetherBridgePieces { return null; } - protected static boolean isAboveGround(StructureBoundingBox parStructureBoundingBox) { - return parStructureBoundingBox != null && parStructureBoundingBox.minY > 10; + private int getTotalWeight(List parList) { + boolean flag = false; + int i = 0; + + for (StructureNetherBridgePieces.PieceWeight structurenetherbridgepieces$pieceweight : parList) { + if (structurenetherbridgepieces$pieceweight.field_78824_d > 0 + && structurenetherbridgepieces$pieceweight.field_78827_c < structurenetherbridgepieces$pieceweight.field_78824_d) { + flag = true; + } + + i += structurenetherbridgepieces$pieceweight.field_78826_b; + } + + return flag ? i : -1; + } + + protected void readStructureFromNBT(NBTTagCompound var1) { + } + + protected void writeStructureToNBT(NBTTagCompound var1) { } } @@ -1375,6 +1297,10 @@ public class StructureNetherBridgePieces { public int field_78824_d; public boolean field_78825_e; + public PieceWeight(Class parClass1, int parInt1, int parInt2) { + this(parClass1, parInt1, parInt2, false); + } + public PieceWeight(Class parClass1, int parInt1, int parInt2, boolean parFlag) { this.weightClass = parClass1; @@ -1383,10 +1309,6 @@ public class StructureNetherBridgePieces { this.field_78825_e = parFlag; } - public PieceWeight(Class parClass1, int parInt1, int parInt2) { - this(parClass1, parInt1, parInt2, false); - } - public boolean func_78822_a(int parInt1) { return this.field_78824_d == 0 || this.field_78827_c < this.field_78824_d; } @@ -1397,21 +1319,6 @@ public class StructureNetherBridgePieces { } public static class Stairs extends StructureNetherBridgePieces.Piece { - public Stairs() { - } - - public Stairs(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 6, 2, false); - } - public static StructureNetherBridgePieces.Stairs func_175872_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, int parInt4, EnumFacing parEnumFacing) { @@ -1424,6 +1331,16 @@ public class StructureNetherBridgePieces { : null; } + public Stairs() { + } + + public Stairs(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 0, 0, 6, 1, 6, Blocks.nether_brick.getDefaultState(), @@ -1473,6 +1390,11 @@ public class StructureNetherBridgePieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentZ((StructureNetherBridgePieces.Start) structurecomponent, list, random, 6, 2, false); + } } public static class Start extends StructureNetherBridgePieces.Crossing3 { @@ -1512,22 +1434,6 @@ public class StructureNetherBridgePieces { } public static class Straight extends StructureNetherBridgePieces.Piece { - public Straight() { - } - - public Straight(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 3, - false); - } - public static StructureNetherBridgePieces.Straight func_175882_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -1540,6 +1446,16 @@ public class StructureNetherBridgePieces { : null; } + public Straight() { + } + + public Straight(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 3, 0, 4, 4, 18, Blocks.nether_brick.getDefaultState(), @@ -1586,31 +1502,15 @@ public class StructureNetherBridgePieces { Blocks.nether_brick_fence.getDefaultState(), Blocks.nether_brick_fence.getDefaultState(), false); return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureNetherBridgePieces.Start) structurecomponent, list, random, 1, 3, + false); + } } public static class Throne extends StructureNetherBridgePieces.Piece { - private boolean hasSpawner; - - public Throne() { - } - - public Throne(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.hasSpawner = nbttagcompound.getBoolean("Mob"); - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Mob", this.hasSpawner); - } - public static StructureNetherBridgePieces.Throne func_175874_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, int parInt4, EnumFacing parEnumFacing) { @@ -1623,6 +1523,18 @@ public class StructureNetherBridgePieces { : null; } + private boolean hasSpawner; + + public Throne() { + } + + public Throne(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { this.fillWithBlocks(world, structureboundingbox, 0, 2, 0, 6, 7, 7, Blocks.air.getDefaultState(), @@ -1681,5 +1593,99 @@ public class StructureNetherBridgePieces { return true; } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.hasSpawner = nbttagcompound.getBoolean("Mob"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Mob", this.hasSpawner); + } + } + + private static final StructureNetherBridgePieces.PieceWeight[] primaryComponents = new StructureNetherBridgePieces.PieceWeight[] { + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Straight.class, 30, 0, true), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Crossing3.class, 10, 4), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Crossing.class, 10, 4), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Stairs.class, 10, 3), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Throne.class, 5, 2), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Entrance.class, 5, 1) }; + + private static final StructureNetherBridgePieces.PieceWeight[] secondaryComponents = new StructureNetherBridgePieces.PieceWeight[] { + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor5.class, 25, 0, true), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Crossing2.class, 15, 5), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor2.class, 5, 10), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor.class, 5, 10), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor3.class, 10, 3, true), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.Corridor4.class, 7, 2), + new StructureNetherBridgePieces.PieceWeight(StructureNetherBridgePieces.NetherStalkRoom.class, 5, 2) }; + + private static StructureNetherBridgePieces.Piece func_175887_b( + StructureNetherBridgePieces.PieceWeight parPieceWeight, List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { + Class oclass = parPieceWeight.weightClass; + Object object = null; + if (oclass == StructureNetherBridgePieces.Straight.class) { + object = StructureNetherBridgePieces.Straight.func_175882_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Crossing3.class) { + object = StructureNetherBridgePieces.Crossing3.func_175885_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Crossing.class) { + object = StructureNetherBridgePieces.Crossing.func_175873_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Stairs.class) { + object = StructureNetherBridgePieces.Stairs.func_175872_a(parList, parRandom, parInt1, parInt2, parInt3, + parInt4, parEnumFacing); + } else if (oclass == StructureNetherBridgePieces.Throne.class) { + object = StructureNetherBridgePieces.Throne.func_175874_a(parList, parRandom, parInt1, parInt2, parInt3, + parInt4, parEnumFacing); + } else if (oclass == StructureNetherBridgePieces.Entrance.class) { + object = StructureNetherBridgePieces.Entrance.func_175881_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Corridor5.class) { + object = StructureNetherBridgePieces.Corridor5.func_175877_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Corridor2.class) { + object = StructureNetherBridgePieces.Corridor2.func_175876_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Corridor.class) { + object = StructureNetherBridgePieces.Corridor.func_175879_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Corridor3.class) { + object = StructureNetherBridgePieces.Corridor3.func_175883_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Corridor4.class) { + object = StructureNetherBridgePieces.Corridor4.func_175880_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.Crossing2.class) { + object = StructureNetherBridgePieces.Crossing2.func_175878_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureNetherBridgePieces.NetherStalkRoom.class) { + object = StructureNetherBridgePieces.NetherStalkRoom.func_175875_a(parList, parRandom, parInt1, parInt2, + parInt3, parEnumFacing, parInt4); + } + + return (StructureNetherBridgePieces.Piece) object; + } + + public static void registerNetherFortressPieces() { + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Crossing3.class, "NeBCr"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.End.class, "NeBEF"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Straight.class, "NeBS"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor3.class, "NeCCS"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor4.class, "NeCTB"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Entrance.class, "NeCE"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Crossing2.class, "NeSCSC"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor.class, "NeSCLT"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor5.class, "NeSC"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Corridor2.class, "NeSCRT"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.NetherStalkRoom.class, "NeCSR"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Throne.class, "NeMT"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Crossing.class, "NeRC"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Stairs.class, "NeSR"); + MapGenStructureIO.registerStructureComponent(StructureNetherBridgePieces.Start.class, "NeStart"); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonument.java b/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonument.java index 3e67fb91..1de8d641 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonument.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonument.java @@ -1,13 +1,15 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; import java.util.Arrays; import java.util.List; import java.util.Map; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import java.util.Set; import java.util.Map.Entry; +import java.util.Set; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.entity.monster.EntityGuardian; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; @@ -18,32 +20,114 @@ import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureOceanMonument extends MapGenStructure { - private int field_175800_f; - private int field_175801_g; + public static class StartMonument extends StructureStart { + private Set field_175791_c = Sets.newHashSet(); + private boolean field_175790_d; + + public StartMonument() { + } + + public StartMonument(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { + super(parInt1, parInt2); + this.func_175789_b(worldIn, parRandom, parInt1, parInt2); + } + + public void func_175787_b(ChunkCoordIntPair pair) { + super.func_175787_b(pair); + this.field_175791_c.add(pair); + } + + public boolean func_175788_a(ChunkCoordIntPair pair) { + return this.field_175791_c.contains(pair) ? false : super.func_175788_a(pair); + } + + private void func_175789_b(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { + parRandom.setSeed(worldIn.getSeed()); + long i = parRandom.nextLong(); + long j = parRandom.nextLong(); + long k = (long) parInt1 * i; + long l = (long) parInt2 * j; + parRandom.setSeed(k ^ l ^ worldIn.getSeed()); + int i1 = parInt1 * 16 + 8 - 29; + int j1 = parInt2 * 16 + 8 - 29; + EnumFacing enumfacing = EnumFacing.Plane.HORIZONTAL.random(parRandom); + this.components.add(new StructureOceanMonumentPieces.MonumentBuilding(parRandom, i1, j1, enumfacing)); + this.updateBoundingBox(); + this.field_175790_d = true; + } + + public void generateStructure(World worldIn, EaglercraftRandom rand, StructureBoundingBox structurebb) { + if (!this.field_175790_d) { + this.components.clear(); + this.func_175789_b(worldIn, rand, this.getChunkPosX(), this.getChunkPosZ()); + } + + super.generateStructure(worldIn, rand, structurebb); + } + + public void readFromNBT(NBTTagCompound tagCompound) { + super.readFromNBT(tagCompound); + if (tagCompound.hasKey("Processed", 9)) { + NBTTagList nbttaglist = tagCompound.getTagList("Processed", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + this.field_175791_c + .add(new ChunkCoordIntPair(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Z"))); + } + } + + } + + public void writeToNBT(NBTTagCompound tagCompound) { + super.writeToNBT(tagCompound); + NBTTagList nbttaglist = new NBTTagList(); + + for (ChunkCoordIntPair chunkcoordintpair : this.field_175791_c) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + nbttagcompound.setInteger("X", chunkcoordintpair.chunkXPos); + nbttagcompound.setInteger("Z", chunkcoordintpair.chunkZPos); + nbttaglist.appendTag(nbttagcompound); + } + + tagCompound.setTag("Processed", nbttaglist); + } + } + public static final List field_175802_d = Arrays.asList(new BiomeGenBase[] { BiomeGenBase.ocean, BiomeGenBase.deepOcean, BiomeGenBase.river, BiomeGenBase.frozenOcean, BiomeGenBase.frozenRiver }); private static final List field_175803_h = Lists.newArrayList(); + static { + field_175803_h.add(new BiomeGenBase.SpawnListEntry(EntityGuardian.class, 1, 2, 4)); + } + + private int field_175800_f; + + private int field_175801_g; public StructureOceanMonument(boolean scramble) { super(scramble); @@ -66,10 +150,6 @@ public class StructureOceanMonument extends MapGenStructure { } - public String getStructureName() { - return "Monument"; - } - protected boolean canSpawnStructureAtCoords(int i, int j) { int k = i; int l = j; @@ -106,89 +186,15 @@ public class StructureOceanMonument extends MapGenStructure { return false; } - protected StructureStart getStructureStart(int i, int j) { - return new StructureOceanMonument.StartMonument(this.worldObj, this.rand, i, j); - } - public List func_175799_b() { return field_175803_h; } - static { - field_175803_h.add(new BiomeGenBase.SpawnListEntry(EntityGuardian.class, 1, 2, 4)); + public String getStructureName() { + return "Monument"; } - public static class StartMonument extends StructureStart { - private Set field_175791_c = Sets.newHashSet(); - private boolean field_175790_d; - - public StartMonument() { - } - - public StartMonument(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { - super(parInt1, parInt2); - this.func_175789_b(worldIn, parRandom, parInt1, parInt2); - } - - private void func_175789_b(World worldIn, EaglercraftRandom parRandom, int parInt1, int parInt2) { - parRandom.setSeed(worldIn.getSeed()); - long i = parRandom.nextLong(); - long j = parRandom.nextLong(); - long k = (long) parInt1 * i; - long l = (long) parInt2 * j; - parRandom.setSeed(k ^ l ^ worldIn.getSeed()); - int i1 = parInt1 * 16 + 8 - 29; - int j1 = parInt2 * 16 + 8 - 29; - EnumFacing enumfacing = EnumFacing.Plane.HORIZONTAL.random(parRandom); - this.components.add(new StructureOceanMonumentPieces.MonumentBuilding(parRandom, i1, j1, enumfacing)); - this.updateBoundingBox(); - this.field_175790_d = true; - } - - public void generateStructure(World worldIn, EaglercraftRandom rand, StructureBoundingBox structurebb) { - if (!this.field_175790_d) { - this.components.clear(); - this.func_175789_b(worldIn, rand, this.getChunkPosX(), this.getChunkPosZ()); - } - - super.generateStructure(worldIn, rand, structurebb); - } - - public boolean func_175788_a(ChunkCoordIntPair pair) { - return this.field_175791_c.contains(pair) ? false : super.func_175788_a(pair); - } - - public void func_175787_b(ChunkCoordIntPair pair) { - super.func_175787_b(pair); - this.field_175791_c.add(pair); - } - - public void writeToNBT(NBTTagCompound tagCompound) { - super.writeToNBT(tagCompound); - NBTTagList nbttaglist = new NBTTagList(); - - for (ChunkCoordIntPair chunkcoordintpair : this.field_175791_c) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setInteger("X", chunkcoordintpair.chunkXPos); - nbttagcompound.setInteger("Z", chunkcoordintpair.chunkZPos); - nbttaglist.appendTag(nbttagcompound); - } - - tagCompound.setTag("Processed", nbttaglist); - } - - public void readFromNBT(NBTTagCompound tagCompound) { - super.readFromNBT(tagCompound); - if (tagCompound.hasKey("Processed", 9)) { - NBTTagList nbttaglist = tagCompound.getTagList("Processed", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - this.field_175791_c - .add(new ChunkCoordIntPair(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Z"))); - } - } - - } + protected StructureStart getStructureStart(int i, int j) { + return new StructureOceanMonument.StartMonument(this.worldObj, this.rand, i, j); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonumentPieces.java b/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonumentPieces.java index dda62587..e756fdc7 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonumentPieces.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureOceanMonumentPieces.java @@ -1,10 +1,11 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.ArrayUtils; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockPrismarine; @@ -18,41 +19,30 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureOceanMonumentPieces { - public static void registerOceanMonumentPieces() { - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.MonumentBuilding.class, "OMB"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.MonumentCoreRoom.class, "OMCR"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleXRoom.class, "OMDXR"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleXYRoom.class, "OMDXYR"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleYRoom.class, "OMDYR"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleYZRoom.class, "OMDYZR"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleZRoom.class, "OMDZR"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.EntryRoom.class, "OMEntry"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.Penthouse.class, "OMPenthouse"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.SimpleRoom.class, "OMSimple"); - MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.SimpleTopRoom.class, "OMSimpleT"); - } - public static class DoubleXRoom extends StructureOceanMonumentPieces.Piece { public DoubleXRoom() { } @@ -613,10 +603,6 @@ public class StructureOceanMonumentPieces { private FitSimpleRoomHelper() { } - public boolean func_175969_a(StructureOceanMonumentPieces.RoomDefinition var1) { - return true; - } - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, EaglercraftRandom random) { @@ -624,12 +610,24 @@ public class StructureOceanMonumentPieces { return new StructureOceanMonumentPieces.SimpleRoom(enumfacing, structureoceanmonumentpieces$roomdefinition, random); } + + public boolean func_175969_a(StructureOceanMonumentPieces.RoomDefinition var1) { + return true; + } } static class FitSimpleRoomTopHelper implements StructureOceanMonumentPieces.MonumentRoomFitHelper { private FitSimpleRoomTopHelper() { } + public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, + StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, + EaglercraftRandom random) { + structureoceanmonumentpieces$roomdefinition.field_175963_d = true; + return new StructureOceanMonumentPieces.SimpleTopRoom(enumfacing, + structureoceanmonumentpieces$roomdefinition, random); + } + public boolean func_175969_a( StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { return !structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.WEST.getIndex()] @@ -638,14 +636,6 @@ public class StructureOceanMonumentPieces { && !structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.SOUTH.getIndex()] && !structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.UP.getIndex()]; } - - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, - StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, - EaglercraftRandom random) { - structureoceanmonumentpieces$roomdefinition.field_175963_d = true; - return new StructureOceanMonumentPieces.SimpleTopRoom(enumfacing, - structureoceanmonumentpieces$roomdefinition, random); - } } public static class MonumentBuilding extends StructureOceanMonumentPieces.Piece { @@ -735,6 +725,133 @@ public class StructureOceanMonumentPieces { .add(new StructureOceanMonumentPieces.Penthouse(this.coordBaseMode, structureboundingbox)); } + public boolean addComponentParts(World world, EaglercraftRandom random, + StructureBoundingBox structureboundingbox) { + int i = Math.max(world.func_181545_F(), 64) - this.boundingBox.minY; + this.func_181655_a(world, structureboundingbox, 0, 0, 0, 58, i, 58, false); + this.func_175840_a(false, 0, world, random, structureboundingbox); + this.func_175840_a(true, 33, world, random, structureboundingbox); + this.func_175839_b(world, random, structureboundingbox); + this.func_175837_c(world, random, structureboundingbox); + this.func_175841_d(world, random, structureboundingbox); + this.func_175835_e(world, random, structureboundingbox); + this.func_175842_f(world, random, structureboundingbox); + this.func_175838_g(world, random, structureboundingbox); + + for (int j = 0; j < 7; ++j) { + int k = 0; + + while (k < 7) { + if (k == 0 && j == 3) { + k = 6; + } + + int l = j * 9; + int i1 = k * 9; + + for (int j1 = 0; j1 < 4; ++j1) { + for (int k1 = 0; k1 < 4; ++k1) { + this.setBlockState(world, field_175826_b, l + j1, 0, i1 + k1, structureboundingbox); + this.replaceAirAndLiquidDownwards(world, field_175826_b, l + j1, -1, i1 + k1, + structureboundingbox); + } + } + + if (j != 0 && j != 6) { + k += 6; + } else { + ++k; + } + } + } + + for (int l1 = 0; l1 < 5; ++l1) { + this.func_181655_a(world, structureboundingbox, -1 - l1, 0 + l1 * 2, -1 - l1, -1 - l1, 23, 58 + l1, + false); + this.func_181655_a(world, structureboundingbox, 58 + l1, 0 + l1 * 2, -1 - l1, 58 + l1, 23, 58 + l1, + false); + this.func_181655_a(world, structureboundingbox, 0 - l1, 0 + l1 * 2, -1 - l1, 57 + l1, 23, -1 - l1, + false); + this.func_181655_a(world, structureboundingbox, 0 - l1, 0 + l1 * 2, 58 + l1, 57 + l1, 23, 58 + l1, + false); + } + + for (StructureOceanMonumentPieces.Piece structureoceanmonumentpieces$piece : this.field_175843_q) { + if (structureoceanmonumentpieces$piece.getBoundingBox().intersectsWith(structureboundingbox)) { + structureoceanmonumentpieces$piece.addComponentParts(world, random, structureboundingbox); + } + } + + return true; + } + + private void func_175835_e(World worldIn, EaglercraftRandom parRandom, + StructureBoundingBox parStructureBoundingBox) { + if (this.func_175818_a(parStructureBoundingBox, 0, 21, 6, 58)) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 0, 0, 21, 6, 0, 57, field_175828_a, + field_175828_a, false); + this.func_181655_a(worldIn, parStructureBoundingBox, 0, 1, 21, 6, 7, 57, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 4, 4, 21, 6, 4, 53, field_175828_a, + field_175828_a, false); + + for (int i = 0; i < 4; ++i) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, i, i + 1, 21, i, i + 1, 57 - i, + field_175826_b, field_175826_b, false); + } + + for (int j = 23; j < 53; j += 3) { + this.setBlockState(worldIn, field_175824_d, 5, 5, j, parStructureBoundingBox); + } + + this.setBlockState(worldIn, field_175824_d, 5, 5, 52, parStructureBoundingBox); + + for (int k = 0; k < 4; ++k) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, k, k + 1, 21, k, k + 1, 57 - k, + field_175826_b, field_175826_b, false); + } + + this.fillWithBlocks(worldIn, parStructureBoundingBox, 4, 1, 52, 6, 3, 52, field_175828_a, + field_175828_a, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 5, 1, 51, 5, 3, 53, field_175828_a, + field_175828_a, false); + } + + if (this.func_175818_a(parStructureBoundingBox, 51, 21, 58, 58)) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 51, 0, 21, 57, 0, 57, field_175828_a, + field_175828_a, false); + this.func_181655_a(worldIn, parStructureBoundingBox, 51, 1, 21, 57, 7, 57, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 51, 4, 21, 53, 4, 53, field_175828_a, + field_175828_a, false); + + for (int l = 0; l < 4; ++l) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 57 - l, l + 1, 21, 57 - l, l + 1, 57 - l, + field_175826_b, field_175826_b, false); + } + + for (int i1 = 23; i1 < 53; i1 += 3) { + this.setBlockState(worldIn, field_175824_d, 52, 5, i1, parStructureBoundingBox); + } + + this.setBlockState(worldIn, field_175824_d, 52, 5, 52, parStructureBoundingBox); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 51, 1, 52, 53, 3, 52, field_175828_a, + field_175828_a, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 52, 1, 51, 52, 3, 53, field_175828_a, + field_175828_a, false); + } + + if (this.func_175818_a(parStructureBoundingBox, 0, 51, 57, 57)) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 7, 0, 51, 50, 0, 57, field_175828_a, + field_175828_a, false); + this.func_181655_a(worldIn, parStructureBoundingBox, 7, 1, 51, 50, 10, 57, false); + + for (int j1 = 0; j1 < 4; ++j1) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, j1 + 1, j1 + 1, 57 - j1, 56 - j1, j1 + 1, + 57 - j1, field_175826_b, field_175826_b, false); + } + } + + } + private List func_175836_a(EaglercraftRandom parRandom) { StructureOceanMonumentPieces.RoomDefinition[] astructureoceanmonumentpieces$roomdefinition = new StructureOceanMonumentPieces.RoomDefinition[75]; @@ -867,152 +984,6 @@ public class StructureOceanMonumentPieces { return arraylist; } - public boolean addComponentParts(World world, EaglercraftRandom random, - StructureBoundingBox structureboundingbox) { - int i = Math.max(world.func_181545_F(), 64) - this.boundingBox.minY; - this.func_181655_a(world, structureboundingbox, 0, 0, 0, 58, i, 58, false); - this.func_175840_a(false, 0, world, random, structureboundingbox); - this.func_175840_a(true, 33, world, random, structureboundingbox); - this.func_175839_b(world, random, structureboundingbox); - this.func_175837_c(world, random, structureboundingbox); - this.func_175841_d(world, random, structureboundingbox); - this.func_175835_e(world, random, structureboundingbox); - this.func_175842_f(world, random, structureboundingbox); - this.func_175838_g(world, random, structureboundingbox); - - for (int j = 0; j < 7; ++j) { - int k = 0; - - while (k < 7) { - if (k == 0 && j == 3) { - k = 6; - } - - int l = j * 9; - int i1 = k * 9; - - for (int j1 = 0; j1 < 4; ++j1) { - for (int k1 = 0; k1 < 4; ++k1) { - this.setBlockState(world, field_175826_b, l + j1, 0, i1 + k1, structureboundingbox); - this.replaceAirAndLiquidDownwards(world, field_175826_b, l + j1, -1, i1 + k1, - structureboundingbox); - } - } - - if (j != 0 && j != 6) { - k += 6; - } else { - ++k; - } - } - } - - for (int l1 = 0; l1 < 5; ++l1) { - this.func_181655_a(world, structureboundingbox, -1 - l1, 0 + l1 * 2, -1 - l1, -1 - l1, 23, 58 + l1, - false); - this.func_181655_a(world, structureboundingbox, 58 + l1, 0 + l1 * 2, -1 - l1, 58 + l1, 23, 58 + l1, - false); - this.func_181655_a(world, structureboundingbox, 0 - l1, 0 + l1 * 2, -1 - l1, 57 + l1, 23, -1 - l1, - false); - this.func_181655_a(world, structureboundingbox, 0 - l1, 0 + l1 * 2, 58 + l1, 57 + l1, 23, 58 + l1, - false); - } - - for (StructureOceanMonumentPieces.Piece structureoceanmonumentpieces$piece : this.field_175843_q) { - if (structureoceanmonumentpieces$piece.getBoundingBox().intersectsWith(structureboundingbox)) { - structureoceanmonumentpieces$piece.addComponentParts(world, random, structureboundingbox); - } - } - - return true; - } - - private void func_175840_a(boolean worldIn, int parInt1, World parWorld, EaglercraftRandom parRandom, - StructureBoundingBox parStructureBoundingBox) { - boolean flag = true; - if (this.func_175818_a(parStructureBoundingBox, parInt1, 0, parInt1 + 23, 20)) { - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 0, 0, 0, parInt1 + 24, 0, 20, - field_175828_a, field_175828_a, false); - this.func_181655_a(parWorld, parStructureBoundingBox, parInt1 + 0, 1, 0, parInt1 + 24, 10, 20, false); - - for (int i = 0; i < 4; ++i) { - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i, i + 1, i, parInt1 + i, i + 1, - 20, field_175826_b, field_175826_b, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i + 7, i + 5, i + 7, - parInt1 + i + 7, i + 5, 20, field_175826_b, field_175826_b, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 17 - i, i + 5, i + 7, - parInt1 + 17 - i, i + 5, 20, field_175826_b, field_175826_b, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 24 - i, i + 1, i, parInt1 + 24 - i, - i + 1, 20, field_175826_b, field_175826_b, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i + 1, i + 1, i, parInt1 + 23 - i, - i + 1, i, field_175826_b, field_175826_b, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i + 8, i + 5, i + 7, - parInt1 + 16 - i, i + 5, i + 7, field_175826_b, field_175826_b, false); - } - - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 4, 4, 4, parInt1 + 6, 4, 20, - field_175828_a, field_175828_a, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 7, 4, 4, parInt1 + 17, 4, 6, - field_175828_a, field_175828_a, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 18, 4, 4, parInt1 + 20, 4, 20, - field_175828_a, field_175828_a, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 11, 8, 11, parInt1 + 13, 8, 20, - field_175828_a, field_175828_a, false); - this.setBlockState(parWorld, field_175824_d, parInt1 + 12, 9, 12, parStructureBoundingBox); - this.setBlockState(parWorld, field_175824_d, parInt1 + 12, 9, 15, parStructureBoundingBox); - this.setBlockState(parWorld, field_175824_d, parInt1 + 12, 9, 18, parStructureBoundingBox); - int i1 = worldIn ? parInt1 + 19 : parInt1 + 5; - int j = worldIn ? parInt1 + 5 : parInt1 + 19; - - for (int k = 20; k >= 5; k -= 3) { - this.setBlockState(parWorld, field_175824_d, i1, 5, k, parStructureBoundingBox); - } - - for (int j1 = 19; j1 >= 7; j1 -= 3) { - this.setBlockState(parWorld, field_175824_d, j, 5, j1, parStructureBoundingBox); - } - - for (int k1 = 0; k1 < 4; ++k1) { - int l = worldIn ? parInt1 + (24 - (17 - k1 * 3)) : parInt1 + 17 - k1 * 3; - this.setBlockState(parWorld, field_175824_d, l, 5, 5, parStructureBoundingBox); - } - - this.setBlockState(parWorld, field_175824_d, j, 5, 5, parStructureBoundingBox); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 11, 1, 12, parInt1 + 13, 7, 12, - field_175828_a, field_175828_a, false); - this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 12, 1, 11, parInt1 + 12, 7, 13, - field_175828_a, field_175828_a, false); - } - - } - - private void func_175839_b(World worldIn, EaglercraftRandom parRandom, - StructureBoundingBox parStructureBoundingBox) { - if (this.func_175818_a(parStructureBoundingBox, 22, 5, 35, 17)) { - this.func_181655_a(worldIn, parStructureBoundingBox, 25, 0, 0, 32, 8, 20, false); - - for (int i = 0; i < 4; ++i) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 24, 2, 5 + i * 4, 24, 4, 5 + i * 4, - field_175826_b, field_175826_b, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 22, 4, 5 + i * 4, 23, 4, 5 + i * 4, - field_175826_b, field_175826_b, false); - this.setBlockState(worldIn, field_175826_b, 25, 5, 5 + i * 4, parStructureBoundingBox); - this.setBlockState(worldIn, field_175826_b, 26, 6, 5 + i * 4, parStructureBoundingBox); - this.setBlockState(worldIn, field_175825_e, 26, 5, 5 + i * 4, parStructureBoundingBox); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 33, 2, 5 + i * 4, 33, 4, 5 + i * 4, - field_175826_b, field_175826_b, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 34, 4, 5 + i * 4, 35, 4, 5 + i * 4, - field_175826_b, field_175826_b, false); - this.setBlockState(worldIn, field_175826_b, 32, 5, 5 + i * 4, parStructureBoundingBox); - this.setBlockState(worldIn, field_175826_b, 31, 6, 5 + i * 4, parStructureBoundingBox); - this.setBlockState(worldIn, field_175825_e, 31, 5, 5 + i * 4, parStructureBoundingBox); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 27, 6, 5 + i * 4, 30, 6, 5 + i * 4, - field_175828_a, field_175828_a, false); - } - } - - } - private void func_175837_c(World worldIn, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox) { if (this.func_175818_a(parStructureBoundingBox, 15, 20, 42, 21)) { @@ -1087,6 +1058,151 @@ public class StructureOceanMonumentPieces { } + private void func_175838_g(World worldIn, EaglercraftRandom parRandom, + StructureBoundingBox parStructureBoundingBox) { + if (this.func_175818_a(parStructureBoundingBox, 14, 21, 20, 43)) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 14, 0, 21, 20, 0, 43, field_175828_a, + field_175828_a, false); + this.func_181655_a(worldIn, parStructureBoundingBox, 14, 1, 22, 20, 14, 43, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 18, 12, 22, 20, 12, 39, field_175828_a, + field_175828_a, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 18, 12, 21, 20, 12, 21, field_175826_b, + field_175826_b, false); + + for (int i = 0; i < 4; ++i) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, i + 14, i + 9, 21, i + 14, i + 9, 43 - i, + field_175826_b, field_175826_b, false); + } + + for (int j = 23; j <= 39; j += 3) { + this.setBlockState(worldIn, field_175824_d, 19, 13, j, parStructureBoundingBox); + } + } + + if (this.func_175818_a(parStructureBoundingBox, 37, 21, 43, 43)) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 37, 0, 21, 43, 0, 43, field_175828_a, + field_175828_a, false); + this.func_181655_a(worldIn, parStructureBoundingBox, 37, 1, 22, 43, 14, 43, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 37, 12, 22, 39, 12, 39, field_175828_a, + field_175828_a, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 37, 12, 21, 39, 12, 21, field_175826_b, + field_175826_b, false); + + for (int k = 0; k < 4; ++k) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 43 - k, k + 9, 21, 43 - k, k + 9, 43 - k, + field_175826_b, field_175826_b, false); + } + + for (int l = 23; l <= 39; l += 3) { + this.setBlockState(worldIn, field_175824_d, 38, 13, l, parStructureBoundingBox); + } + } + + if (this.func_175818_a(parStructureBoundingBox, 15, 37, 42, 43)) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 21, 0, 37, 36, 0, 43, field_175828_a, + field_175828_a, false); + this.func_181655_a(worldIn, parStructureBoundingBox, 21, 1, 37, 36, 14, 43, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 21, 12, 37, 36, 12, 39, field_175828_a, + field_175828_a, false); + + for (int i1 = 0; i1 < 4; ++i1) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 15 + i1, i1 + 9, 43 - i1, 42 - i1, i1 + 9, + 43 - i1, field_175826_b, field_175826_b, false); + } + + for (int j1 = 21; j1 <= 36; j1 += 3) { + this.setBlockState(worldIn, field_175824_d, j1, 13, 38, parStructureBoundingBox); + } + } + + } + + private void func_175839_b(World worldIn, EaglercraftRandom parRandom, + StructureBoundingBox parStructureBoundingBox) { + if (this.func_175818_a(parStructureBoundingBox, 22, 5, 35, 17)) { + this.func_181655_a(worldIn, parStructureBoundingBox, 25, 0, 0, 32, 8, 20, false); + + for (int i = 0; i < 4; ++i) { + this.fillWithBlocks(worldIn, parStructureBoundingBox, 24, 2, 5 + i * 4, 24, 4, 5 + i * 4, + field_175826_b, field_175826_b, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 22, 4, 5 + i * 4, 23, 4, 5 + i * 4, + field_175826_b, field_175826_b, false); + this.setBlockState(worldIn, field_175826_b, 25, 5, 5 + i * 4, parStructureBoundingBox); + this.setBlockState(worldIn, field_175826_b, 26, 6, 5 + i * 4, parStructureBoundingBox); + this.setBlockState(worldIn, field_175825_e, 26, 5, 5 + i * 4, parStructureBoundingBox); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 33, 2, 5 + i * 4, 33, 4, 5 + i * 4, + field_175826_b, field_175826_b, false); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 34, 4, 5 + i * 4, 35, 4, 5 + i * 4, + field_175826_b, field_175826_b, false); + this.setBlockState(worldIn, field_175826_b, 32, 5, 5 + i * 4, parStructureBoundingBox); + this.setBlockState(worldIn, field_175826_b, 31, 6, 5 + i * 4, parStructureBoundingBox); + this.setBlockState(worldIn, field_175825_e, 31, 5, 5 + i * 4, parStructureBoundingBox); + this.fillWithBlocks(worldIn, parStructureBoundingBox, 27, 6, 5 + i * 4, 30, 6, 5 + i * 4, + field_175828_a, field_175828_a, false); + } + } + + } + + private void func_175840_a(boolean worldIn, int parInt1, World parWorld, EaglercraftRandom parRandom, + StructureBoundingBox parStructureBoundingBox) { + boolean flag = true; + if (this.func_175818_a(parStructureBoundingBox, parInt1, 0, parInt1 + 23, 20)) { + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 0, 0, 0, parInt1 + 24, 0, 20, + field_175828_a, field_175828_a, false); + this.func_181655_a(parWorld, parStructureBoundingBox, parInt1 + 0, 1, 0, parInt1 + 24, 10, 20, false); + + for (int i = 0; i < 4; ++i) { + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i, i + 1, i, parInt1 + i, i + 1, + 20, field_175826_b, field_175826_b, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i + 7, i + 5, i + 7, + parInt1 + i + 7, i + 5, 20, field_175826_b, field_175826_b, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 17 - i, i + 5, i + 7, + parInt1 + 17 - i, i + 5, 20, field_175826_b, field_175826_b, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 24 - i, i + 1, i, parInt1 + 24 - i, + i + 1, 20, field_175826_b, field_175826_b, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i + 1, i + 1, i, parInt1 + 23 - i, + i + 1, i, field_175826_b, field_175826_b, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + i + 8, i + 5, i + 7, + parInt1 + 16 - i, i + 5, i + 7, field_175826_b, field_175826_b, false); + } + + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 4, 4, 4, parInt1 + 6, 4, 20, + field_175828_a, field_175828_a, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 7, 4, 4, parInt1 + 17, 4, 6, + field_175828_a, field_175828_a, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 18, 4, 4, parInt1 + 20, 4, 20, + field_175828_a, field_175828_a, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 11, 8, 11, parInt1 + 13, 8, 20, + field_175828_a, field_175828_a, false); + this.setBlockState(parWorld, field_175824_d, parInt1 + 12, 9, 12, parStructureBoundingBox); + this.setBlockState(parWorld, field_175824_d, parInt1 + 12, 9, 15, parStructureBoundingBox); + this.setBlockState(parWorld, field_175824_d, parInt1 + 12, 9, 18, parStructureBoundingBox); + int i1 = worldIn ? parInt1 + 19 : parInt1 + 5; + int j = worldIn ? parInt1 + 5 : parInt1 + 19; + + for (int k = 20; k >= 5; k -= 3) { + this.setBlockState(parWorld, field_175824_d, i1, 5, k, parStructureBoundingBox); + } + + for (int j1 = 19; j1 >= 7; j1 -= 3) { + this.setBlockState(parWorld, field_175824_d, j, 5, j1, parStructureBoundingBox); + } + + for (int k1 = 0; k1 < 4; ++k1) { + int l = worldIn ? parInt1 + (24 - (17 - k1 * 3)) : parInt1 + 17 - k1 * 3; + this.setBlockState(parWorld, field_175824_d, l, 5, 5, parStructureBoundingBox); + } + + this.setBlockState(parWorld, field_175824_d, j, 5, 5, parStructureBoundingBox); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 11, 1, 12, parInt1 + 13, 7, 12, + field_175828_a, field_175828_a, false); + this.fillWithBlocks(parWorld, parStructureBoundingBox, parInt1 + 12, 1, 11, parInt1 + 12, 7, 13, + field_175828_a, field_175828_a, false); + } + + } + private void func_175841_d(World worldIn, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox) { if (this.func_175818_a(parStructureBoundingBox, 21, 21, 36, 36)) { @@ -1139,73 +1255,6 @@ public class StructureOceanMonumentPieces { } - private void func_175835_e(World worldIn, EaglercraftRandom parRandom, - StructureBoundingBox parStructureBoundingBox) { - if (this.func_175818_a(parStructureBoundingBox, 0, 21, 6, 58)) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 0, 0, 21, 6, 0, 57, field_175828_a, - field_175828_a, false); - this.func_181655_a(worldIn, parStructureBoundingBox, 0, 1, 21, 6, 7, 57, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 4, 4, 21, 6, 4, 53, field_175828_a, - field_175828_a, false); - - for (int i = 0; i < 4; ++i) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, i, i + 1, 21, i, i + 1, 57 - i, - field_175826_b, field_175826_b, false); - } - - for (int j = 23; j < 53; j += 3) { - this.setBlockState(worldIn, field_175824_d, 5, 5, j, parStructureBoundingBox); - } - - this.setBlockState(worldIn, field_175824_d, 5, 5, 52, parStructureBoundingBox); - - for (int k = 0; k < 4; ++k) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, k, k + 1, 21, k, k + 1, 57 - k, - field_175826_b, field_175826_b, false); - } - - this.fillWithBlocks(worldIn, parStructureBoundingBox, 4, 1, 52, 6, 3, 52, field_175828_a, - field_175828_a, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 5, 1, 51, 5, 3, 53, field_175828_a, - field_175828_a, false); - } - - if (this.func_175818_a(parStructureBoundingBox, 51, 21, 58, 58)) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 51, 0, 21, 57, 0, 57, field_175828_a, - field_175828_a, false); - this.func_181655_a(worldIn, parStructureBoundingBox, 51, 1, 21, 57, 7, 57, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 51, 4, 21, 53, 4, 53, field_175828_a, - field_175828_a, false); - - for (int l = 0; l < 4; ++l) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 57 - l, l + 1, 21, 57 - l, l + 1, 57 - l, - field_175826_b, field_175826_b, false); - } - - for (int i1 = 23; i1 < 53; i1 += 3) { - this.setBlockState(worldIn, field_175824_d, 52, 5, i1, parStructureBoundingBox); - } - - this.setBlockState(worldIn, field_175824_d, 52, 5, 52, parStructureBoundingBox); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 51, 1, 52, 53, 3, 52, field_175828_a, - field_175828_a, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 52, 1, 51, 52, 3, 53, field_175828_a, - field_175828_a, false); - } - - if (this.func_175818_a(parStructureBoundingBox, 0, 51, 57, 57)) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 7, 0, 51, 50, 0, 57, field_175828_a, - field_175828_a, false); - this.func_181655_a(worldIn, parStructureBoundingBox, 7, 1, 51, 50, 10, 57, false); - - for (int j1 = 0; j1 < 4; ++j1) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, j1 + 1, j1 + 1, 57 - j1, 56 - j1, j1 + 1, - 57 - j1, field_175826_b, field_175826_b, false); - } - } - - } - private void func_175842_f(World worldIn, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox) { if (this.func_175818_a(parStructureBoundingBox, 7, 21, 13, 50)) { @@ -1276,65 +1325,6 @@ public class StructureOceanMonumentPieces { } } - - private void func_175838_g(World worldIn, EaglercraftRandom parRandom, - StructureBoundingBox parStructureBoundingBox) { - if (this.func_175818_a(parStructureBoundingBox, 14, 21, 20, 43)) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 14, 0, 21, 20, 0, 43, field_175828_a, - field_175828_a, false); - this.func_181655_a(worldIn, parStructureBoundingBox, 14, 1, 22, 20, 14, 43, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 18, 12, 22, 20, 12, 39, field_175828_a, - field_175828_a, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 18, 12, 21, 20, 12, 21, field_175826_b, - field_175826_b, false); - - for (int i = 0; i < 4; ++i) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, i + 14, i + 9, 21, i + 14, i + 9, 43 - i, - field_175826_b, field_175826_b, false); - } - - for (int j = 23; j <= 39; j += 3) { - this.setBlockState(worldIn, field_175824_d, 19, 13, j, parStructureBoundingBox); - } - } - - if (this.func_175818_a(parStructureBoundingBox, 37, 21, 43, 43)) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 37, 0, 21, 43, 0, 43, field_175828_a, - field_175828_a, false); - this.func_181655_a(worldIn, parStructureBoundingBox, 37, 1, 22, 43, 14, 43, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 37, 12, 22, 39, 12, 39, field_175828_a, - field_175828_a, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 37, 12, 21, 39, 12, 21, field_175826_b, - field_175826_b, false); - - for (int k = 0; k < 4; ++k) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 43 - k, k + 9, 21, 43 - k, k + 9, 43 - k, - field_175826_b, field_175826_b, false); - } - - for (int l = 23; l <= 39; l += 3) { - this.setBlockState(worldIn, field_175824_d, 38, 13, l, parStructureBoundingBox); - } - } - - if (this.func_175818_a(parStructureBoundingBox, 15, 37, 42, 43)) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 21, 0, 37, 36, 0, 43, field_175828_a, - field_175828_a, false); - this.func_181655_a(worldIn, parStructureBoundingBox, 21, 1, 37, 36, 14, 43, false); - this.fillWithBlocks(worldIn, parStructureBoundingBox, 21, 12, 37, 36, 12, 39, field_175828_a, - field_175828_a, false); - - for (int i1 = 0; i1 < 4; ++i1) { - this.fillWithBlocks(worldIn, parStructureBoundingBox, 15 + i1, i1 + 9, 43 - i1, 42 - i1, i1 + 9, - 43 - i1, field_175826_b, field_175826_b, false); - } - - for (int j1 = 21; j1 <= 36; j1 += 3) { - this.setBlockState(worldIn, field_175824_d, j1, 13, 38, parStructureBoundingBox); - } - } - - } } public static class MonumentCoreRoom extends StructureOceanMonumentPieces.Piece { @@ -1424,10 +1414,10 @@ public class StructureOceanMonumentPieces { } interface MonumentRoomFitHelper { - boolean func_175969_a(StructureOceanMonumentPieces.RoomDefinition var1); - StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing var1, StructureOceanMonumentPieces.RoomDefinition var2, EaglercraftRandom var3); + + boolean func_175969_a(StructureOceanMonumentPieces.RoomDefinition var1); } public static class Penthouse extends StructureOceanMonumentPieces.Piece { @@ -1507,26 +1497,27 @@ public class StructureOceanMonumentPieces { protected static final int field_175831_h = func_175820_a(2, 2, 0); protected static final int field_175832_i = func_175820_a(0, 1, 0); protected static final int field_175829_j = func_175820_a(4, 1, 0); - protected StructureOceanMonumentPieces.RoomDefinition field_175830_k; protected static final int func_175820_a(int parInt1, int parInt2, int parInt3) { return parInt2 * 25 + parInt3 * 5 + parInt1; } + protected StructureOceanMonumentPieces.RoomDefinition field_175830_k; + public Piece() { super(0); } - public Piece(int parInt1) { - super(parInt1); - } - public Piece(EnumFacing parEnumFacing, StructureBoundingBox parStructureBoundingBox) { super(1); this.coordBaseMode = parEnumFacing; this.boundingBox = parStructureBoundingBox; } + public Piece(int parInt1) { + super(parInt1); + } + protected Piece(int parInt1, EnumFacing parEnumFacing, StructureOceanMonumentPieces.RoomDefinition parRoomDefinition, int parInt2, int parInt3, int parInt4) { super(parInt1); @@ -1558,25 +1549,42 @@ public class StructureOceanMonumentPieces { } - protected void writeStructureToNBT(NBTTagCompound var1) { + protected boolean func_175817_a(World worldIn, StructureBoundingBox parStructureBoundingBox, int parInt1, + int parInt2, int parInt3) { + int i = this.getXWithOffset(parInt1, parInt3); + int j = this.getYWithOffset(parInt2); + int k = this.getZWithOffset(parInt1, parInt3); + if (parStructureBoundingBox.isVecInside(new BlockPos(i, j, k))) { + EntityGuardian entityguardian = new EntityGuardian(worldIn); + entityguardian.setElder(true); + entityguardian.heal(entityguardian.getMaxHealth()); + entityguardian.setLocationAndAngles((double) i + 0.5D, (double) j, (double) k + 0.5D, 0.0F, 0.0F); + entityguardian.onInitialSpawn(worldIn.getDifficultyForLocation(new BlockPos(entityguardian)), + (IEntityLivingData) null); + worldIn.spawnEntityInWorld(entityguardian); + return true; + } else { + return false; + } } - protected void readStructureFromNBT(NBTTagCompound var1) { + protected boolean func_175818_a(StructureBoundingBox parStructureBoundingBox, int parInt1, int parInt2, + int parInt3, int parInt4) { + int i = this.getXWithOffset(parInt1, parInt2); + int j = this.getZWithOffset(parInt1, parInt2); + int k = this.getXWithOffset(parInt3, parInt4); + int l = this.getZWithOffset(parInt3, parInt4); + return parStructureBoundingBox.intersectsWith(Math.min(i, k), Math.min(j, l), Math.max(i, k), + Math.max(j, l)); } - protected void func_181655_a(World parWorld, StructureBoundingBox parStructureBoundingBox, int parInt1, - int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, boolean parFlag) { + protected void func_175819_a(World worldIn, StructureBoundingBox parStructureBoundingBox, int parInt1, + int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, IBlockState parIBlockState) { for (int i = parInt2; i <= parInt5; ++i) { for (int j = parInt1; j <= parInt4; ++j) { for (int k = parInt3; k <= parInt6; ++k) { - if (!parFlag || this.getBlockStateFromPos(parWorld, j, i, k, parStructureBoundingBox).getBlock() - .getMaterial() != Material.air) { - if (this.getYWithOffset(i) >= parWorld.func_181545_F()) { - this.setBlockState(parWorld, Blocks.air.getDefaultState(), j, i, k, - parStructureBoundingBox); - } else { - this.setBlockState(parWorld, field_175822_f, j, i, k, parStructureBoundingBox); - } + if (this.getBlockStateFromPos(worldIn, j, i, k, parStructureBoundingBox) == field_175822_f) { + this.setBlockState(worldIn, parIBlockState, j, i, k, parStructureBoundingBox); } } } @@ -1610,13 +1618,19 @@ public class StructureOceanMonumentPieces { } - protected void func_175819_a(World worldIn, StructureBoundingBox parStructureBoundingBox, int parInt1, - int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, IBlockState parIBlockState) { + protected void func_181655_a(World parWorld, StructureBoundingBox parStructureBoundingBox, int parInt1, + int parInt2, int parInt3, int parInt4, int parInt5, int parInt6, boolean parFlag) { for (int i = parInt2; i <= parInt5; ++i) { for (int j = parInt1; j <= parInt4; ++j) { for (int k = parInt3; k <= parInt6; ++k) { - if (this.getBlockStateFromPos(worldIn, j, i, k, parStructureBoundingBox) == field_175822_f) { - this.setBlockState(worldIn, parIBlockState, j, i, k, parStructureBoundingBox); + if (!parFlag || this.getBlockStateFromPos(parWorld, j, i, k, parStructureBoundingBox).getBlock() + .getMaterial() != Material.air) { + if (this.getYWithOffset(i) >= parWorld.func_181545_F()) { + this.setBlockState(parWorld, Blocks.air.getDefaultState(), j, i, k, + parStructureBoundingBox); + } else { + this.setBlockState(parWorld, field_175822_f, j, i, k, parStructureBoundingBox); + } } } } @@ -1624,33 +1638,10 @@ public class StructureOceanMonumentPieces { } - protected boolean func_175818_a(StructureBoundingBox parStructureBoundingBox, int parInt1, int parInt2, - int parInt3, int parInt4) { - int i = this.getXWithOffset(parInt1, parInt2); - int j = this.getZWithOffset(parInt1, parInt2); - int k = this.getXWithOffset(parInt3, parInt4); - int l = this.getZWithOffset(parInt3, parInt4); - return parStructureBoundingBox.intersectsWith(Math.min(i, k), Math.min(j, l), Math.max(i, k), - Math.max(j, l)); + protected void readStructureFromNBT(NBTTagCompound var1) { } - protected boolean func_175817_a(World worldIn, StructureBoundingBox parStructureBoundingBox, int parInt1, - int parInt2, int parInt3) { - int i = this.getXWithOffset(parInt1, parInt3); - int j = this.getYWithOffset(parInt2); - int k = this.getZWithOffset(parInt1, parInt3); - if (parStructureBoundingBox.isVecInside(new BlockPos(i, j, k))) { - EntityGuardian entityguardian = new EntityGuardian(worldIn); - entityguardian.setElder(true); - entityguardian.heal(entityguardian.getMaxHealth()); - entityguardian.setLocationAndAngles((double) i + 0.5D, (double) j, (double) k + 0.5D, 0.0F, 0.0F); - entityguardian.onInitialSpawn(worldIn.getDifficultyForLocation(new BlockPos(entityguardian)), - (IEntityLivingData) null); - worldIn.spawnEntityInWorld(entityguardian); - return true; - } else { - return false; - } + protected void writeStructureToNBT(NBTTagCompound var1) { } } @@ -1697,10 +1688,6 @@ public class StructureOceanMonumentPieces { } } - public boolean func_175961_b() { - return this.field_175967_a >= 75; - } - public int func_175960_c() { int i = 0; @@ -1712,6 +1699,10 @@ public class StructureOceanMonumentPieces { return i; } + + public boolean func_175961_b() { + return this.field_175967_a >= 75; + } } public static class SimpleRoom extends StructureOceanMonumentPieces.Piece { @@ -2149,23 +2140,36 @@ public class StructureOceanMonumentPieces { private XDoubleRoomFitHelper() { } - public boolean func_175969_a(StructureOceanMonumentPieces.RoomDefinition parRoomDefinition) { - return parRoomDefinition.field_175966_c[EnumFacing.EAST.getIndex()] - && !parRoomDefinition.field_175965_b[EnumFacing.EAST.getIndex()].field_175963_d; - } - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing parEnumFacing, StructureOceanMonumentPieces.RoomDefinition parRoomDefinition, EaglercraftRandom parRandom) { parRoomDefinition.field_175963_d = true; parRoomDefinition.field_175965_b[EnumFacing.EAST.getIndex()].field_175963_d = true; return new StructureOceanMonumentPieces.DoubleXRoom(parEnumFacing, parRoomDefinition, parRandom); } + + public boolean func_175969_a(StructureOceanMonumentPieces.RoomDefinition parRoomDefinition) { + return parRoomDefinition.field_175966_c[EnumFacing.EAST.getIndex()] + && !parRoomDefinition.field_175965_b[EnumFacing.EAST.getIndex()].field_175963_d; + } } static class XYDoubleRoomFitHelper implements StructureOceanMonumentPieces.MonumentRoomFitHelper { private XYDoubleRoomFitHelper() { } + public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, + StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, + EaglercraftRandom random) { + structureoceanmonumentpieces$roomdefinition.field_175963_d = true; + structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.EAST + .getIndex()].field_175963_d = true; + structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; + structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.EAST + .getIndex()].field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; + return new StructureOceanMonumentPieces.DoubleXYRoom(enumfacing, + structureoceanmonumentpieces$roomdefinition, random); + } + public boolean func_175969_a( StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { if (structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.EAST.getIndex()] @@ -2183,32 +2187,12 @@ public class StructureOceanMonumentPieces { return false; } } - - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, - StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, - EaglercraftRandom random) { - structureoceanmonumentpieces$roomdefinition.field_175963_d = true; - structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.EAST - .getIndex()].field_175963_d = true; - structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; - structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.EAST - .getIndex()].field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; - return new StructureOceanMonumentPieces.DoubleXYRoom(enumfacing, - structureoceanmonumentpieces$roomdefinition, random); - } } static class YDoubleRoomFitHelper implements StructureOceanMonumentPieces.MonumentRoomFitHelper { private YDoubleRoomFitHelper() { } - public boolean func_175969_a( - StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { - return structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.UP.getIndex()] - && !structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.UP - .getIndex()].field_175963_d; - } - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, EaglercraftRandom random) { @@ -2217,12 +2201,32 @@ public class StructureOceanMonumentPieces { return new StructureOceanMonumentPieces.DoubleYRoom(enumfacing, structureoceanmonumentpieces$roomdefinition, random); } + + public boolean func_175969_a( + StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { + return structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.UP.getIndex()] + && !structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.UP + .getIndex()].field_175963_d; + } } static class YZDoubleRoomFitHelper implements StructureOceanMonumentPieces.MonumentRoomFitHelper { private YZDoubleRoomFitHelper() { } + public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, + StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, + EaglercraftRandom random) { + structureoceanmonumentpieces$roomdefinition.field_175963_d = true; + structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.NORTH + .getIndex()].field_175963_d = true; + structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; + structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.NORTH + .getIndex()].field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; + return new StructureOceanMonumentPieces.DoubleYZRoom(enumfacing, + structureoceanmonumentpieces$roomdefinition, random); + } + public boolean func_175969_a( StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { if (structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.NORTH.getIndex()] @@ -2240,32 +2244,12 @@ public class StructureOceanMonumentPieces { return false; } } - - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, - StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, - EaglercraftRandom random) { - structureoceanmonumentpieces$roomdefinition.field_175963_d = true; - structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.NORTH - .getIndex()].field_175963_d = true; - structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; - structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.NORTH - .getIndex()].field_175965_b[EnumFacing.UP.getIndex()].field_175963_d = true; - return new StructureOceanMonumentPieces.DoubleYZRoom(enumfacing, - structureoceanmonumentpieces$roomdefinition, random); - } } static class ZDoubleRoomFitHelper implements StructureOceanMonumentPieces.MonumentRoomFitHelper { private ZDoubleRoomFitHelper() { } - public boolean func_175969_a( - StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { - return structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.NORTH.getIndex()] - && !structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.NORTH - .getIndex()].field_175963_d; - } - public StructureOceanMonumentPieces.Piece func_175968_a(EnumFacing enumfacing, StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition, EaglercraftRandom random) { @@ -2283,5 +2267,26 @@ public class StructureOceanMonumentPieces { return new StructureOceanMonumentPieces.DoubleZRoom(enumfacing, structureoceanmonumentpieces$roomdefinition1, random); } + + public boolean func_175969_a( + StructureOceanMonumentPieces.RoomDefinition structureoceanmonumentpieces$roomdefinition) { + return structureoceanmonumentpieces$roomdefinition.field_175966_c[EnumFacing.NORTH.getIndex()] + && !structureoceanmonumentpieces$roomdefinition.field_175965_b[EnumFacing.NORTH + .getIndex()].field_175963_d; + } + } + + public static void registerOceanMonumentPieces() { + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.MonumentBuilding.class, "OMB"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.MonumentCoreRoom.class, "OMCR"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleXRoom.class, "OMDXR"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleXYRoom.class, "OMDXYR"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleYRoom.class, "OMDYR"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleYZRoom.class, "OMDYZR"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.DoubleZRoom.class, "OMDZR"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.EntryRoom.class, "OMEntry"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.Penthouse.class, "OMPenthouse"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.SimpleRoom.class, "OMSimple"); + MapGenStructureIO.registerStructureComponent(StructureOceanMonumentPieces.SimpleTopRoom.class, "OMSimpleT"); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureStart.java b/src/game/java/net/minecraft/world/gen/structure/StructureStart.java index 0814b2e9..4532db62 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureStart.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureStart.java @@ -2,36 +2,39 @@ package net.minecraft.world.gen.structure; import java.util.Iterator; import java.util.LinkedList; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class StructureStart { - /**+ - * List of all StructureComponents that are part of this - * structure + /** + * + List of all StructureComponents that are part of this structure */ protected LinkedList components = new LinkedList(); protected StructureBoundingBox boundingBox; @@ -46,17 +49,16 @@ public abstract class StructureStart { this.chunkPosZ = chunkZ; } - public StructureBoundingBox getBoundingBox() { - return this.boundingBox; + public void func_175787_b(ChunkCoordIntPair var1) { } - public LinkedList getComponents() { - return this.components; + public boolean func_175788_a(ChunkCoordIntPair var1) { + return true; } - /**+ - * Keeps iterating Structure Pieces and spawning them until the - * checks tell it to stop + /** + * + Keeps iterating Structure Pieces and spawning them until the checks tell it + * to stop */ public void generateStructure(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { Iterator iterator = this.components.iterator(); @@ -71,9 +73,90 @@ public abstract class StructureStart { } - /**+ - * Calculates total bounding box based on components' bounding - * boxes and saves it to boundingBox + public StructureBoundingBox getBoundingBox() { + return this.boundingBox; + } + + public int getChunkPosX() { + return this.chunkPosX; + } + + public int getChunkPosZ() { + return this.chunkPosZ; + } + + public LinkedList getComponents() { + return this.components; + } + + /** + * + currently only defined for Villages, returns true if Village has more than + * 2 non-road components + */ + public boolean isSizeableStructure() { + return true; + } + + /** + * + offsets the structure Bounding Boxes up to a certain height, typically 63 - + * 10 + */ + protected void markAvailableHeight(World worldIn, EaglercraftRandom rand, int parInt1) { + int i = worldIn.func_181545_F() - parInt1; + int j = this.boundingBox.getYSize() + 1; + if (j < i) { + j += rand.nextInt(i - j); + } + + int k = j - this.boundingBox.maxY; + this.boundingBox.offset(0, k, 0); + + for (StructureComponent structurecomponent : this.components) { + structurecomponent.func_181138_a(0, k, 0); + } + + } + + public void readFromNBT(NBTTagCompound var1) { + } + + public void readStructureComponentsFromNBT(World worldIn, NBTTagCompound tagCompound) { + this.chunkPosX = tagCompound.getInteger("ChunkX"); + this.chunkPosZ = tagCompound.getInteger("ChunkZ"); + if (tagCompound.hasKey("BB")) { + this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); + } + + NBTTagList nbttaglist = tagCompound.getTagList("Children", 10); + + for (int i = 0; i < nbttaglist.tagCount(); ++i) { + this.components.add(MapGenStructureIO.getStructureComponent(nbttaglist.getCompoundTagAt(i), worldIn)); + } + + this.readFromNBT(tagCompound); + } + + protected void setRandomHeight(World worldIn, EaglercraftRandom rand, int parInt1, int parInt2) { + int i = parInt2 - parInt1 + 1 - this.boundingBox.getYSize(); + int j = 1; + if (i > 1) { + j = parInt1 + rand.nextInt(i); + } else { + j = parInt1; + } + + int k = j - this.boundingBox.minY; + this.boundingBox.offset(0, k, 0); + + for (StructureComponent structurecomponent : this.components) { + structurecomponent.func_181138_a(0, k, 0); + } + + } + + /** + * + Calculates total bounding box based on components' bounding boxes and saves + * it to boundingBox */ protected void updateBoundingBox() { this.boundingBox = StructureBoundingBox.getNewBoundingBox(); @@ -103,84 +186,4 @@ public abstract class StructureStart { public void writeToNBT(NBTTagCompound var1) { } - - public void readStructureComponentsFromNBT(World worldIn, NBTTagCompound tagCompound) { - this.chunkPosX = tagCompound.getInteger("ChunkX"); - this.chunkPosZ = tagCompound.getInteger("ChunkZ"); - if (tagCompound.hasKey("BB")) { - this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); - } - - NBTTagList nbttaglist = tagCompound.getTagList("Children", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) { - this.components.add(MapGenStructureIO.getStructureComponent(nbttaglist.getCompoundTagAt(i), worldIn)); - } - - this.readFromNBT(tagCompound); - } - - public void readFromNBT(NBTTagCompound var1) { - } - - /**+ - * offsets the structure Bounding Boxes up to a certain height, - * typically 63 - 10 - */ - protected void markAvailableHeight(World worldIn, EaglercraftRandom rand, int parInt1) { - int i = worldIn.func_181545_F() - parInt1; - int j = this.boundingBox.getYSize() + 1; - if (j < i) { - j += rand.nextInt(i - j); - } - - int k = j - this.boundingBox.maxY; - this.boundingBox.offset(0, k, 0); - - for (StructureComponent structurecomponent : this.components) { - structurecomponent.func_181138_a(0, k, 0); - } - - } - - protected void setRandomHeight(World worldIn, EaglercraftRandom rand, int parInt1, int parInt2) { - int i = parInt2 - parInt1 + 1 - this.boundingBox.getYSize(); - int j = 1; - if (i > 1) { - j = parInt1 + rand.nextInt(i); - } else { - j = parInt1; - } - - int k = j - this.boundingBox.minY; - this.boundingBox.offset(0, k, 0); - - for (StructureComponent structurecomponent : this.components) { - structurecomponent.func_181138_a(0, k, 0); - } - - } - - /**+ - * currently only defined for Villages, returns true if Village - * has more than 2 non-road components - */ - public boolean isSizeableStructure() { - return true; - } - - public boolean func_175788_a(ChunkCoordIntPair var1) { - return true; - } - - public void func_175787_b(ChunkCoordIntPair var1) { - } - - public int getChunkPosX() { - return this.chunkPosX; - } - - public int getChunkPosZ() { - return this.chunkPosZ; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureStrongholdPieces.java b/src/game/java/net/minecraft/world/gen/structure/StructureStrongholdPieces.java index 922c505b..2542cb41 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureStrongholdPieces.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureStrongholdPieces.java @@ -1,7 +1,9 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.BlockEndPortalFrame; import net.minecraft.block.BlockSilverfish; @@ -17,214 +19,30 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.WeightedRandomChestContent; import net.minecraft.world.World; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureStrongholdPieces { - private static final StructureStrongholdPieces.PieceWeight[] pieceWeightArray = new StructureStrongholdPieces.PieceWeight[] { - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Straight.class, 40, 0), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Prison.class, 5, 5), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.LeftTurn.class, 20, 0), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.RightTurn.class, 20, 0), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.RoomCrossing.class, 10, 6), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.StairsStraight.class, 5, 5), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Stairs.class, 5, 5), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Crossing.class, 5, 4), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.ChestCorridor.class, 5, 4), - new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Library.class, 10, 2) { - public boolean canSpawnMoreStructuresOfType(int parInt1) { - return super.canSpawnMoreStructuresOfType(parInt1) && parInt1 > 4; - } - }, new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.PortalRoom.class, 20, 1) { - public boolean canSpawnMoreStructuresOfType(int i) { - return super.canSpawnMoreStructuresOfType(i) && i > 5; - } - } }; - private static List structurePieceList; - private static Class strongComponentType; - static int totalWeight; - private static final StructureStrongholdPieces.Stones strongholdStones = new StructureStrongholdPieces.Stones(); - - public static void registerStrongholdPieces() { - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.ChestCorridor.class, "SHCC"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Corridor.class, "SHFC"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Crossing.class, "SH5C"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.LeftTurn.class, "SHLT"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Library.class, "SHLi"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.PortalRoom.class, "SHPR"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Prison.class, "SHPH"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.RightTurn.class, "SHRT"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.RoomCrossing.class, "SHRC"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Stairs.class, "SHSD"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Stairs2.class, "SHStart"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Straight.class, "SHS"); - MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.StairsStraight.class, "SHSSD"); - } - - /**+ - * sets up Arrays with the Structure pieces and their weights - */ - public static void prepareStructurePieces() { - structurePieceList = Lists.newArrayList(); - - for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : pieceWeightArray) { - structurestrongholdpieces$pieceweight.instancesSpawned = 0; - structurePieceList.add(structurestrongholdpieces$pieceweight); - } - - strongComponentType = null; - } - - private static boolean canAddStructurePieces() { - boolean flag = false; - totalWeight = 0; - - for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : structurePieceList) { - if (structurestrongholdpieces$pieceweight.instancesLimit > 0 - && structurestrongholdpieces$pieceweight.instancesSpawned < structurestrongholdpieces$pieceweight.instancesLimit) { - flag = true; - } - - totalWeight += structurestrongholdpieces$pieceweight.pieceWeight; - } - - return flag; - } - - private static StructureStrongholdPieces.Stronghold func_175954_a( - Class parClass1, List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { - Object object = null; - if (parClass1 == StructureStrongholdPieces.Straight.class) { - object = StructureStrongholdPieces.Straight.func_175862_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.Prison.class) { - object = StructureStrongholdPieces.Prison.func_175860_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.LeftTurn.class) { - object = StructureStrongholdPieces.LeftTurn.func_175867_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.RightTurn.class) { - object = StructureStrongholdPieces.RightTurn.func_175867_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.RoomCrossing.class) { - object = StructureStrongholdPieces.RoomCrossing.func_175859_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.StairsStraight.class) { - object = StructureStrongholdPieces.StairsStraight.func_175861_a(parList, parRandom, parInt1, parInt2, - parInt3, parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.Stairs.class) { - object = StructureStrongholdPieces.Stairs.func_175863_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.Crossing.class) { - object = StructureStrongholdPieces.Crossing.func_175866_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.ChestCorridor.class) { - object = StructureStrongholdPieces.ChestCorridor.func_175868_a(parList, parRandom, parInt1, parInt2, - parInt3, parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.Library.class) { - object = StructureStrongholdPieces.Library.func_175864_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (parClass1 == StructureStrongholdPieces.PortalRoom.class) { - object = StructureStrongholdPieces.PortalRoom.func_175865_a(parList, parRandom, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } - - return (StructureStrongholdPieces.Stronghold) object; - } - - private static StructureStrongholdPieces.Stronghold func_175955_b(StructureStrongholdPieces.Stairs2 parStairs2_1, - List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - if (!canAddStructurePieces()) { - return null; - } else { - if (strongComponentType != null) { - StructureStrongholdPieces.Stronghold structurestrongholdpieces$stronghold = func_175954_a( - strongComponentType, parList, parRandom, parInt1, parInt2, parInt3, parEnumFacing, parInt4); - strongComponentType = null; - if (structurestrongholdpieces$stronghold != null) { - return structurestrongholdpieces$stronghold; - } - } - - int j = 0; - - while (j < 5) { - ++j; - int i = parRandom.nextInt(totalWeight); - - for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : structurePieceList) { - i -= structurestrongholdpieces$pieceweight.pieceWeight; - if (i < 0) { - if (!structurestrongholdpieces$pieceweight.canSpawnMoreStructuresOfType(parInt4) - || structurestrongholdpieces$pieceweight == parStairs2_1.strongholdPieceWeight) { - break; - } - - StructureStrongholdPieces.Stronghold structurestrongholdpieces$stronghold1 = func_175954_a( - structurestrongholdpieces$pieceweight.pieceClass, parList, parRandom, parInt1, parInt2, - parInt3, parEnumFacing, parInt4); - if (structurestrongholdpieces$stronghold1 != null) { - ++structurestrongholdpieces$pieceweight.instancesSpawned; - parStairs2_1.strongholdPieceWeight = structurestrongholdpieces$pieceweight; - if (!structurestrongholdpieces$pieceweight.canSpawnMoreStructures()) { - structurePieceList.remove(structurestrongholdpieces$pieceweight); - } - - return structurestrongholdpieces$stronghold1; - } - } - } - } - - StructureBoundingBox structureboundingbox = StructureStrongholdPieces.Corridor.func_175869_a(parList, - parRandom, parInt1, parInt2, parInt3, parEnumFacing); - if (structureboundingbox != null && structureboundingbox.minY > 1) { - return new StructureStrongholdPieces.Corridor(parInt4, parRandom, structureboundingbox, parEnumFacing); - } else { - return null; - } - } - } - - private static StructureComponent func_175953_c(StructureStrongholdPieces.Stairs2 parStairs2_1, - List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - if (parInt4 > 50) { - return null; - } else if (Math.abs(parInt1 - parStairs2_1.getBoundingBox().minX) <= 112 - && Math.abs(parInt3 - parStairs2_1.getBoundingBox().minZ) <= 112) { - StructureStrongholdPieces.Stronghold structurestrongholdpieces$stronghold = func_175955_b(parStairs2_1, - parList, parRandom, parInt1, parInt2, parInt3, parEnumFacing, parInt4 + 1); - if (structurestrongholdpieces$stronghold != null) { - parList.add(structurestrongholdpieces$stronghold); - parStairs2_1.field_75026_c.add(structurestrongholdpieces$stronghold); - } - - return structurestrongholdpieces$stronghold; - } else { - return null; - } - } - public static class ChestCorridor extends StructureStrongholdPieces.Stronghold { private static final List strongholdChestContents = Lists.newArrayList( new WeightedRandomChestContent[] { new WeightedRandomChestContent(Items.ender_pearl, 0, 1, 1, 10), @@ -245,33 +63,6 @@ public class StructureStrongholdPieces { new WeightedRandomChestContent(Items.iron_horse_armor, 0, 1, 1, 1), new WeightedRandomChestContent(Items.golden_horse_armor, 0, 1, 1, 1), new WeightedRandomChestContent(Items.diamond_horse_armor, 0, 1, 1, 1) }); - private boolean hasMadeChest; - - public ChestCorridor() { - } - - public ChestCorridor(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.field_143013_d = this.getRandomDoor(parRandom); - this.boundingBox = parStructureBoundingBox; - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Chest", this.hasMadeChest); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.hasMadeChest = nbttagcompound.getBoolean("Chest"); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } public static StructureStrongholdPieces.ChestCorridor func_175868_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, @@ -285,6 +76,19 @@ public class StructureStrongholdPieces { : null; } + private boolean hasMadeChest; + + public ChestCorridor() { + } + + public ChestCorridor(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.field_143013_d = this.getRandomDoor(parRandom); + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -328,34 +132,24 @@ public class StructureStrongholdPieces { return true; } } - } - public static class Corridor extends StructureStrongholdPieces.Stronghold { - private int field_74993_a; - - public Corridor() { - } - - public Corridor(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - this.field_74993_a = parEnumFacing != EnumFacing.NORTH && parEnumFacing != EnumFacing.SOUTH - ? parStructureBoundingBox.getXSize() - : parStructureBoundingBox.getZSize(); - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("Steps", this.field_74993_a); + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); } protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { super.readStructureFromNBT(nbttagcompound); - this.field_74993_a = nbttagcompound.getInteger("Steps"); + this.hasMadeChest = nbttagcompound.getBoolean("Chest"); } + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.hasMadeChest); + } + } + + public static class Corridor extends StructureStrongholdPieces.Stronghold { public static StructureBoundingBox func_175869_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing) { boolean flag = true; @@ -380,6 +174,21 @@ public class StructureStrongholdPieces { } } + private int field_74993_a; + + public Corridor() { + } + + public Corridor(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + this.field_74993_a = parEnumFacing != EnumFacing.NORTH && parEnumFacing != EnumFacing.SOUTH + ? parStructureBoundingBox.getXSize() + : parStructureBoundingBox.getZSize(); + } + public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -410,12 +219,35 @@ public class StructureStrongholdPieces { return true; } } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_74993_a = nbttagcompound.getInteger("Steps"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("Steps", this.field_74993_a); + } } public static class Crossing extends StructureStrongholdPieces.Stronghold { + public static StructureStrongholdPieces.Crossing func_175866_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -4, -3, 0, 10, 9, 11, parEnumFacing); + return canStrongholdGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureStrongholdPieces.Crossing(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; + } + private boolean field_74996_b; private boolean field_74997_c; private boolean field_74995_d; + private boolean field_74999_h; public Crossing() { @@ -433,62 +265,6 @@ public class StructureStrongholdPieces { this.field_74999_h = parRandom.nextInt(3) > 0; } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("leftLow", this.field_74996_b); - nbttagcompound.setBoolean("leftHigh", this.field_74997_c); - nbttagcompound.setBoolean("rightLow", this.field_74995_d); - nbttagcompound.setBoolean("rightHigh", this.field_74999_h); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.field_74996_b = nbttagcompound.getBoolean("leftLow"); - this.field_74997_c = nbttagcompound.getBoolean("leftHigh"); - this.field_74995_d = nbttagcompound.getBoolean("rightLow"); - this.field_74999_h = nbttagcompound.getBoolean("rightHigh"); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - int i = 3; - int j = 5; - if (this.coordBaseMode == EnumFacing.WEST || this.coordBaseMode == EnumFacing.NORTH) { - i = 8 - i; - j = 8 - j; - } - - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 5, 1); - if (this.field_74996_b) { - this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, i, 1); - } - - if (this.field_74997_c) { - this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, j, 7); - } - - if (this.field_74995_d) { - this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, i, 1); - } - - if (this.field_74999_h) { - this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, j, 7); - } - - } - - public static StructureStrongholdPieces.Crossing func_175866_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -4, -3, 0, 10, 9, 11, parEnumFacing); - return canStrongholdGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureStrongholdPieces.Crossing(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -549,30 +325,53 @@ public class StructureStrongholdPieces { return true; } } - } - - public static class LeftTurn extends StructureStrongholdPieces.Stronghold { - public LeftTurn() { - } - - public LeftTurn(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.field_143013_d = this.getRandomDoor(parRandom); - this.boundingBox = parStructureBoundingBox; - } public void buildComponent(StructureComponent structurecomponent, List list, EaglercraftRandom random) { - if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.EAST) { - this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } else { - this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + int i = 3; + int j = 5; + if (this.coordBaseMode == EnumFacing.WEST || this.coordBaseMode == EnumFacing.NORTH) { + i = 8 - i; + j = 8 - j; + } + + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 5, 1); + if (this.field_74996_b) { + this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, i, 1); + } + + if (this.field_74997_c) { + this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, j, 7); + } + + if (this.field_74995_d) { + this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, i, 1); + } + + if (this.field_74999_h) { + this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, j, 7); } } + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_74996_b = nbttagcompound.getBoolean("leftLow"); + this.field_74997_c = nbttagcompound.getBoolean("leftHigh"); + this.field_74995_d = nbttagcompound.getBoolean("rightLow"); + this.field_74999_h = nbttagcompound.getBoolean("rightHigh"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("leftLow", this.field_74996_b); + nbttagcompound.setBoolean("leftHigh", this.field_74997_c); + nbttagcompound.setBoolean("rightLow", this.field_74995_d); + nbttagcompound.setBoolean("rightHigh", this.field_74999_h); + } + } + + public static class LeftTurn extends StructureStrongholdPieces.Stronghold { public static StructureStrongholdPieces.LeftTurn func_175867_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -585,6 +384,17 @@ public class StructureStrongholdPieces { : null; } + public LeftTurn() { + } + + public LeftTurn(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.field_143013_d = this.getRandomDoor(parRandom); + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -604,6 +414,16 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.EAST) { + this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } else { + this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } + + } } public static class Library extends StructureStrongholdPieces.Stronghold { @@ -612,29 +432,6 @@ public class StructureStrongholdPieces { new WeightedRandomChestContent(Items.paper, 0, 2, 7, 20), new WeightedRandomChestContent(Items.map, 0, 1, 1, 1), new WeightedRandomChestContent(Items.compass, 0, 1, 1, 1) }); - private boolean isLargeRoom; - - public Library() { - } - - public Library(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.field_143013_d = this.getRandomDoor(parRandom); - this.boundingBox = parStructureBoundingBox; - this.isLargeRoom = parStructureBoundingBox.getYSize() > 6; - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Tall", this.isLargeRoom); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.isLargeRoom = nbttagcompound.getBoolean("Tall"); - } public static StructureStrongholdPieces.Library func_175864_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, @@ -654,6 +451,20 @@ public class StructureStrongholdPieces { return new StructureStrongholdPieces.Library(parInt4, parRandom, structureboundingbox, parEnumFacing); } + private boolean isLargeRoom; + + public Library() { + } + + public Library(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.field_143013_d = this.getRandomDoor(parRandom); + this.boundingBox = parStructureBoundingBox; + this.isLargeRoom = parStructureBoundingBox.getYSize() > 6; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -781,6 +592,16 @@ public class StructureStrongholdPieces { return true; } } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.isLargeRoom = nbttagcompound.getBoolean("Tall"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Tall", this.isLargeRoom); + } } static class PieceWeight { @@ -795,46 +616,16 @@ public class StructureStrongholdPieces { this.instancesLimit = parInt2; } - public boolean canSpawnMoreStructuresOfType(int var1) { + public boolean canSpawnMoreStructures() { return this.instancesLimit == 0 || this.instancesSpawned < this.instancesLimit; } - public boolean canSpawnMoreStructures() { + public boolean canSpawnMoreStructuresOfType(int var1) { return this.instancesLimit == 0 || this.instancesSpawned < this.instancesLimit; } } public static class PortalRoom extends StructureStrongholdPieces.Stronghold { - private boolean hasSpawner; - - public PortalRoom() { - } - - public PortalRoom(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.boundingBox = parStructureBoundingBox; - } - - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Mob", this.hasSpawner); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.hasSpawner = nbttagcompound.getBoolean("Mob"); - } - - public void buildComponent(StructureComponent structurecomponent, List var2, - EaglercraftRandom var3) { - if (structurecomponent != null) { - ((StructureStrongholdPieces.Stairs2) structurecomponent).strongholdPortalRoom = this; - } - - } - public static StructureStrongholdPieces.PortalRoom func_175865_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -847,6 +638,18 @@ public class StructureStrongholdPieces { : null; } + private boolean hasSpawner; + + public PortalRoom() { + } + + public PortalRoom(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { this.fillWithRandomizedBlocks(world, structureboundingbox, 0, 0, 0, 10, 7, 15, false, random, @@ -967,25 +770,27 @@ public class StructureStrongholdPieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List var2, + EaglercraftRandom var3) { + if (structurecomponent != null) { + ((StructureStrongholdPieces.Stairs2) structurecomponent).strongholdPortalRoom = this; + } + + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.hasSpawner = nbttagcompound.getBoolean("Mob"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Mob", this.hasSpawner); + } } public static class Prison extends StructureStrongholdPieces.Stronghold { - public Prison() { - } - - public Prison(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.field_143013_d = this.getRandomDoor(parRandom); - this.boundingBox = parStructureBoundingBox; - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } - public static StructureStrongholdPieces.Prison func_175860_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -998,6 +803,17 @@ public class StructureStrongholdPieces { : null; } + public Prison() { + } + + public Prison(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.field_143013_d = this.getRandomDoor(parRandom); + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -1037,19 +853,14 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } } public static class RightTurn extends StructureStrongholdPieces.LeftTurn { - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.EAST) { - this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } else { - this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } - - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -1069,6 +880,16 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + if (this.coordBaseMode != EnumFacing.NORTH && this.coordBaseMode != EnumFacing.EAST) { + this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } else { + this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } + + } } public static class RoomCrossing extends StructureStrongholdPieces.Stronghold { @@ -1080,6 +901,19 @@ public class StructureStrongholdPieces { new WeightedRandomChestContent(Items.bread, 0, 1, 3, 15), new WeightedRandomChestContent(Items.apple, 0, 1, 3, 15), new WeightedRandomChestContent(Items.iron_pickaxe, 0, 1, 1, 1) }); + + public static StructureStrongholdPieces.RoomCrossing func_175859_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -4, -1, 0, 11, 7, 11, parEnumFacing); + return canStrongholdGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureStrongholdPieces.RoomCrossing(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; + } + protected int roomType; public RoomCrossing() { @@ -1094,35 +928,6 @@ public class StructureStrongholdPieces { this.roomType = parRandom.nextInt(5); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("Type", this.roomType); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.roomType = nbttagcompound.getInteger("Type"); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 4, 1); - this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 4); - this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 4); - } - - public static StructureStrongholdPieces.RoomCrossing func_175859_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -4, -1, 0, 11, 7, 11, parEnumFacing); - return canStrongholdGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureStrongholdPieces.RoomCrossing(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -1235,9 +1040,38 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 4, 1); + this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 4); + this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 4); + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.roomType = nbttagcompound.getInteger("Type"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("Type", this.roomType); + } } public static class Stairs extends StructureStrongholdPieces.Stronghold { + public static StructureStrongholdPieces.Stairs func_175863_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -1, -7, 0, 5, 11, 5, parEnumFacing); + return canStrongholdGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureStrongholdPieces.Stairs(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; + } + private boolean field_75024_a; public Stairs() { @@ -1268,37 +1102,6 @@ public class StructureStrongholdPieces { this.boundingBox = parStructureBoundingBox; } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Source", this.field_75024_a); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.field_75024_a = nbttagcompound.getBoolean("Source"); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - if (this.field_75024_a) { - StructureStrongholdPieces.strongComponentType = StructureStrongholdPieces.Crossing.class; - } - - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } - - public static StructureStrongholdPieces.Stairs func_175863_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -1, -7, 0, 5, 11, 5, parEnumFacing); - return canStrongholdGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureStrongholdPieces.Stairs(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -1341,6 +1144,25 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + if (this.field_75024_a) { + StructureStrongholdPieces.strongComponentType = StructureStrongholdPieces.Crossing.class; + } + + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.field_75024_a = nbttagcompound.getBoolean("Source"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Source", this.field_75024_a); + } } public static class Stairs2 extends StructureStrongholdPieces.Stairs { @@ -1362,22 +1184,6 @@ public class StructureStrongholdPieces { } public static class StairsStraight extends StructureStrongholdPieces.Stronghold { - public StairsStraight() { - } - - public StairsStraight(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, - EnumFacing parEnumFacing) { - super(parInt1); - this.coordBaseMode = parEnumFacing; - this.field_143013_d = this.getRandomDoor(parRandom); - this.boundingBox = parStructureBoundingBox; - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - } - public static StructureStrongholdPieces.StairsStraight func_175861_a(List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -1390,6 +1196,17 @@ public class StructureStrongholdPieces { : null; } + public StairsStraight() { + } + + public StairsStraight(int parInt1, EaglercraftRandom parRandom, StructureBoundingBox parStructureBoundingBox, + EnumFacing parEnumFacing) { + super(parInt1); + this.coordBaseMode = parEnumFacing; + this.field_143013_d = this.getRandomDoor(parRandom); + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -1422,6 +1239,11 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + } } static class Stones extends StructureComponent.BlockSelector { @@ -1449,7 +1271,20 @@ public class StructureStrongholdPieces { } public static class Straight extends StructureStrongholdPieces.Stronghold { + public static StructureStrongholdPieces.Straight func_175862_a(List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, + int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, -1, -1, 0, 5, 5, 7, parEnumFacing); + return canStrongholdGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(parList, structureboundingbox) == null + ? new StructureStrongholdPieces.Straight(parInt4, parRandom, structureboundingbox, + parEnumFacing) + : null; + } + private boolean expandsX; + private boolean expandsZ; public Straight() { @@ -1465,43 +1300,6 @@ public class StructureStrongholdPieces { this.expandsZ = parRandom.nextInt(2) == 0; } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Left", this.expandsX); - nbttagcompound.setBoolean("Right", this.expandsZ); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.expandsX = nbttagcompound.getBoolean("Left"); - this.expandsZ = nbttagcompound.getBoolean("Right"); - } - - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); - if (this.expandsX) { - this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 2); - } - - if (this.expandsZ) { - this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 2); - } - - } - - public static StructureStrongholdPieces.Straight func_175862_a(List parList, - EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, - int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, -1, -1, 0, 5, 5, 7, parEnumFacing); - return canStrongholdGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(parList, structureboundingbox) == null - ? new StructureStrongholdPieces.Straight(parInt4, parRandom, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.isLiquidInStructureBoundingBox(world, structureboundingbox)) { @@ -1533,9 +1331,42 @@ public class StructureStrongholdPieces { return true; } } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + this.getNextComponentNormal((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 1); + if (this.expandsX) { + this.getNextComponentX((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 2); + } + + if (this.expandsZ) { + this.getNextComponentZ((StructureStrongholdPieces.Stairs2) structurecomponent, list, random, 1, 2); + } + + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.expandsX = nbttagcompound.getBoolean("Left"); + this.expandsZ = nbttagcompound.getBoolean("Right"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Left", this.expandsX); + nbttagcompound.setBoolean("Right", this.expandsZ); + } } abstract static class Stronghold extends StructureComponent { + public static enum Door { + OPENING, WOOD_DOOR, GRATES, IRON_DOOR; + } + + protected static boolean canStrongholdGoDeeper(StructureBoundingBox parStructureBoundingBox) { + return parStructureBoundingBox != null && parStructureBoundingBox.minY > 10; + } + protected StructureStrongholdPieces.Stronghold.Door field_143013_d = StructureStrongholdPieces.Stronghold.Door.OPENING; public Stronghold() { @@ -1545,109 +1376,6 @@ public class StructureStrongholdPieces { super(parInt1); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setString("EntryDoor", this.field_143013_d.name()); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - this.field_143013_d = StructureStrongholdPieces.Stronghold.Door - .valueOf(nbttagcompound.getString("EntryDoor")); - } - - protected void placeDoor(World worldIn, EaglercraftRandom parRandom, - StructureBoundingBox parStructureBoundingBox, StructureStrongholdPieces.Stronghold.Door parDoor, - int parInt1, int parInt2, int parInt3) { - switch (parDoor) { - case OPENING: - default: - this.fillWithBlocks(worldIn, parStructureBoundingBox, parInt1, parInt2, parInt3, parInt1 + 3 - 1, - parInt2 + 3 - 1, parInt3, Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false); - break; - case WOOD_DOOR: - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 1, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.oak_door.getDefaultState(), parInt1 + 1, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.oak_door.getStateFromMeta(8), parInt1 + 1, parInt2 + 1, parInt3, - parStructureBoundingBox); - break; - case GRATES: - this.setBlockState(worldIn, Blocks.air.getDefaultState(), parInt1 + 1, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.air.getDefaultState(), parInt1 + 1, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 1, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 2, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 2, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 2, parInt2, parInt3, - parStructureBoundingBox); - break; - case IRON_DOOR: - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 1, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_door.getDefaultState(), parInt1 + 1, parInt2, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, Blocks.iron_door.getStateFromMeta(8), parInt1 + 1, parInt2 + 1, parInt3, - parStructureBoundingBox); - this.setBlockState(worldIn, - Blocks.stone_button.getStateFromMeta(this.getMetadataWithOffset(Blocks.stone_button, 4)), - parInt1 + 2, parInt2 + 1, parInt3 + 1, parStructureBoundingBox); - this.setBlockState(worldIn, - Blocks.stone_button.getStateFromMeta(this.getMetadataWithOffset(Blocks.stone_button, 3)), - parInt1 + 2, parInt2 + 1, parInt3 - 1, parStructureBoundingBox); - } - - } - - protected StructureStrongholdPieces.Stronghold.Door getRandomDoor(EaglercraftRandom parRandom) { - int i = parRandom.nextInt(5); - switch (i) { - case 0: - case 1: - default: - return StructureStrongholdPieces.Stronghold.Door.OPENING; - case 2: - return StructureStrongholdPieces.Stronghold.Door.WOOD_DOOR; - case 3: - return StructureStrongholdPieces.Stronghold.Door.GRATES; - case 4: - return StructureStrongholdPieces.Stronghold.Door.IRON_DOOR; - } - } - protected StructureComponent getNextComponentNormal(StructureStrongholdPieces.Stairs2 parStairs2_1, List parList, EaglercraftRandom parRandom, int parInt1, int parInt2) { if (this.coordBaseMode != null) { @@ -1726,12 +1454,298 @@ public class StructureStrongholdPieces { return null; } - protected static boolean canStrongholdGoDeeper(StructureBoundingBox parStructureBoundingBox) { - return parStructureBoundingBox != null && parStructureBoundingBox.minY > 10; + protected StructureStrongholdPieces.Stronghold.Door getRandomDoor(EaglercraftRandom parRandom) { + int i = parRandom.nextInt(5); + switch (i) { + case 0: + case 1: + default: + return StructureStrongholdPieces.Stronghold.Door.OPENING; + case 2: + return StructureStrongholdPieces.Stronghold.Door.WOOD_DOOR; + case 3: + return StructureStrongholdPieces.Stronghold.Door.GRATES; + case 4: + return StructureStrongholdPieces.Stronghold.Door.IRON_DOOR; + } } - public static enum Door { - OPENING, WOOD_DOOR, GRATES, IRON_DOOR; + protected void placeDoor(World worldIn, EaglercraftRandom parRandom, + StructureBoundingBox parStructureBoundingBox, StructureStrongholdPieces.Stronghold.Door parDoor, + int parInt1, int parInt2, int parInt3) { + switch (parDoor) { + case OPENING: + default: + this.fillWithBlocks(worldIn, parStructureBoundingBox, parInt1, parInt2, parInt3, parInt1 + 3 - 1, + parInt2 + 3 - 1, parInt3, Blocks.air.getDefaultState(), Blocks.air.getDefaultState(), false); + break; + case WOOD_DOOR: + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 1, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.oak_door.getDefaultState(), parInt1 + 1, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.oak_door.getStateFromMeta(8), parInt1 + 1, parInt2 + 1, parInt3, + parStructureBoundingBox); + break; + case GRATES: + this.setBlockState(worldIn, Blocks.air.getDefaultState(), parInt1 + 1, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.air.getDefaultState(), parInt1 + 1, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 1, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 2, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 2, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_bars.getDefaultState(), parInt1 + 2, parInt2, parInt3, + parStructureBoundingBox); + break; + case IRON_DOOR: + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 1, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.stonebrick.getDefaultState(), parInt1 + 2, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_door.getDefaultState(), parInt1 + 1, parInt2, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, Blocks.iron_door.getStateFromMeta(8), parInt1 + 1, parInt2 + 1, parInt3, + parStructureBoundingBox); + this.setBlockState(worldIn, + Blocks.stone_button.getStateFromMeta(this.getMetadataWithOffset(Blocks.stone_button, 4)), + parInt1 + 2, parInt2 + 1, parInt3 + 1, parStructureBoundingBox); + this.setBlockState(worldIn, + Blocks.stone_button.getStateFromMeta(this.getMetadataWithOffset(Blocks.stone_button, 3)), + parInt1 + 2, parInt2 + 1, parInt3 - 1, parStructureBoundingBox); + } + + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + this.field_143013_d = StructureStrongholdPieces.Stronghold.Door + .valueOf(nbttagcompound.getString("EntryDoor")); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setString("EntryDoor", this.field_143013_d.name()); } } + + private static final StructureStrongholdPieces.PieceWeight[] pieceWeightArray = new StructureStrongholdPieces.PieceWeight[] { + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Straight.class, 40, 0), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Prison.class, 5, 5), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.LeftTurn.class, 20, 0), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.RightTurn.class, 20, 0), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.RoomCrossing.class, 10, 6), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.StairsStraight.class, 5, 5), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Stairs.class, 5, 5), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Crossing.class, 5, 4), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.ChestCorridor.class, 5, 4), + new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.Library.class, 10, 2) { + public boolean canSpawnMoreStructuresOfType(int parInt1) { + return super.canSpawnMoreStructuresOfType(parInt1) && parInt1 > 4; + } + }, new StructureStrongholdPieces.PieceWeight(StructureStrongholdPieces.PortalRoom.class, 20, 1) { + public boolean canSpawnMoreStructuresOfType(int i) { + return super.canSpawnMoreStructuresOfType(i) && i > 5; + } + } }; + + private static List structurePieceList; + + private static Class strongComponentType; + + static int totalWeight; + + private static final StructureStrongholdPieces.Stones strongholdStones = new StructureStrongholdPieces.Stones(); + + private static boolean canAddStructurePieces() { + boolean flag = false; + totalWeight = 0; + + for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : structurePieceList) { + if (structurestrongholdpieces$pieceweight.instancesLimit > 0 + && structurestrongholdpieces$pieceweight.instancesSpawned < structurestrongholdpieces$pieceweight.instancesLimit) { + flag = true; + } + + totalWeight += structurestrongholdpieces$pieceweight.pieceWeight; + } + + return flag; + } + + private static StructureComponent func_175953_c(StructureStrongholdPieces.Stairs2 parStairs2_1, + List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + if (parInt4 > 50) { + return null; + } else if (Math.abs(parInt1 - parStairs2_1.getBoundingBox().minX) <= 112 + && Math.abs(parInt3 - parStairs2_1.getBoundingBox().minZ) <= 112) { + StructureStrongholdPieces.Stronghold structurestrongholdpieces$stronghold = func_175955_b(parStairs2_1, + parList, parRandom, parInt1, parInt2, parInt3, parEnumFacing, parInt4 + 1); + if (structurestrongholdpieces$stronghold != null) { + parList.add(structurestrongholdpieces$stronghold); + parStairs2_1.field_75026_c.add(structurestrongholdpieces$stronghold); + } + + return structurestrongholdpieces$stronghold; + } else { + return null; + } + } + + private static StructureStrongholdPieces.Stronghold func_175954_a( + Class parClass1, List parList, + EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { + Object object = null; + if (parClass1 == StructureStrongholdPieces.Straight.class) { + object = StructureStrongholdPieces.Straight.func_175862_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.Prison.class) { + object = StructureStrongholdPieces.Prison.func_175860_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.LeftTurn.class) { + object = StructureStrongholdPieces.LeftTurn.func_175867_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.RightTurn.class) { + object = StructureStrongholdPieces.RightTurn.func_175867_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.RoomCrossing.class) { + object = StructureStrongholdPieces.RoomCrossing.func_175859_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.StairsStraight.class) { + object = StructureStrongholdPieces.StairsStraight.func_175861_a(parList, parRandom, parInt1, parInt2, + parInt3, parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.Stairs.class) { + object = StructureStrongholdPieces.Stairs.func_175863_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.Crossing.class) { + object = StructureStrongholdPieces.Crossing.func_175866_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.ChestCorridor.class) { + object = StructureStrongholdPieces.ChestCorridor.func_175868_a(parList, parRandom, parInt1, parInt2, + parInt3, parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.Library.class) { + object = StructureStrongholdPieces.Library.func_175864_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (parClass1 == StructureStrongholdPieces.PortalRoom.class) { + object = StructureStrongholdPieces.PortalRoom.func_175865_a(parList, parRandom, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } + + return (StructureStrongholdPieces.Stronghold) object; + } + + private static StructureStrongholdPieces.Stronghold func_175955_b(StructureStrongholdPieces.Stairs2 parStairs2_1, + List parList, EaglercraftRandom parRandom, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + if (!canAddStructurePieces()) { + return null; + } else { + if (strongComponentType != null) { + StructureStrongholdPieces.Stronghold structurestrongholdpieces$stronghold = func_175954_a( + strongComponentType, parList, parRandom, parInt1, parInt2, parInt3, parEnumFacing, parInt4); + strongComponentType = null; + if (structurestrongholdpieces$stronghold != null) { + return structurestrongholdpieces$stronghold; + } + } + + int j = 0; + + while (j < 5) { + ++j; + int i = parRandom.nextInt(totalWeight); + + for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : structurePieceList) { + i -= structurestrongholdpieces$pieceweight.pieceWeight; + if (i < 0) { + if (!structurestrongholdpieces$pieceweight.canSpawnMoreStructuresOfType(parInt4) + || structurestrongholdpieces$pieceweight == parStairs2_1.strongholdPieceWeight) { + break; + } + + StructureStrongholdPieces.Stronghold structurestrongholdpieces$stronghold1 = func_175954_a( + structurestrongholdpieces$pieceweight.pieceClass, parList, parRandom, parInt1, parInt2, + parInt3, parEnumFacing, parInt4); + if (structurestrongholdpieces$stronghold1 != null) { + ++structurestrongholdpieces$pieceweight.instancesSpawned; + parStairs2_1.strongholdPieceWeight = structurestrongholdpieces$pieceweight; + if (!structurestrongholdpieces$pieceweight.canSpawnMoreStructures()) { + structurePieceList.remove(structurestrongholdpieces$pieceweight); + } + + return structurestrongholdpieces$stronghold1; + } + } + } + } + + StructureBoundingBox structureboundingbox = StructureStrongholdPieces.Corridor.func_175869_a(parList, + parRandom, parInt1, parInt2, parInt3, parEnumFacing); + if (structureboundingbox != null && structureboundingbox.minY > 1) { + return new StructureStrongholdPieces.Corridor(parInt4, parRandom, structureboundingbox, parEnumFacing); + } else { + return null; + } + } + } + + /** + * + sets up Arrays with the Structure pieces and their weights + */ + public static void prepareStructurePieces() { + structurePieceList = Lists.newArrayList(); + + for (StructureStrongholdPieces.PieceWeight structurestrongholdpieces$pieceweight : pieceWeightArray) { + structurestrongholdpieces$pieceweight.instancesSpawned = 0; + structurePieceList.add(structurestrongholdpieces$pieceweight); + } + + strongComponentType = null; + } + + public static void registerStrongholdPieces() { + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.ChestCorridor.class, "SHCC"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Corridor.class, "SHFC"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Crossing.class, "SH5C"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.LeftTurn.class, "SHLT"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Library.class, "SHLi"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.PortalRoom.class, "SHPR"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Prison.class, "SHPH"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.RightTurn.class, "SHRT"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.RoomCrossing.class, "SHRC"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Stairs.class, "SHSD"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Stairs2.class, "SHStart"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.Straight.class, "SHS"); + MapGenStructureIO.registerStructureComponent(StructureStrongholdPieces.StairsStraight.class, "SHSSD"); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/gen/structure/StructureVillagePieces.java b/src/game/java/net/minecraft/world/gen/structure/StructureVillagePieces.java index 7abbd5c8..6f856a16 100644 --- a/src/game/java/net/minecraft/world/gen/structure/StructureVillagePieces.java +++ b/src/game/java/net/minecraft/world/gen/structure/StructureVillagePieces.java @@ -1,9 +1,11 @@ package net.minecraft.world.gen.structure; -import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.Iterator; import java.util.List; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.minecraft.block.Block; import net.minecraft.block.BlockSandStone; @@ -26,249 +28,31 @@ import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; import net.minecraft.world.biome.WorldChunkManager; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StructureVillagePieces { - public static void registerVillagePieces() { - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House1.class, "ViBH"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Field1.class, "ViDF"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Field2.class, "ViF"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Torch.class, "ViL"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Hall.class, "ViPH"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House4Garden.class, "ViSH"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.WoodHut.class, "ViSmH"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Church.class, "ViST"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House2.class, "ViS"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Start.class, "ViStart"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Path.class, "ViSR"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House3.class, "ViTRH"); - MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Well.class, "ViW"); - } - - public static List getStructureVillageWeightedPieceList( - EaglercraftRandom random, int parInt1) { - ArrayList arraylist = Lists.newArrayList(); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House4Garden.class, 4, - MathHelper.getRandomIntegerInRange(random, 2 + parInt1, 4 + parInt1 * 2))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Church.class, 20, - MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 1 + parInt1))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House1.class, 20, - MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 2 + parInt1))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.WoodHut.class, 3, - MathHelper.getRandomIntegerInRange(random, 2 + parInt1, 5 + parInt1 * 3))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Hall.class, 15, - MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 2 + parInt1))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Field1.class, 3, - MathHelper.getRandomIntegerInRange(random, 1 + parInt1, 4 + parInt1))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Field2.class, 3, - MathHelper.getRandomIntegerInRange(random, 2 + parInt1, 4 + parInt1 * 2))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House2.class, 15, - MathHelper.getRandomIntegerInRange(random, 0, 1 + parInt1))); - arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House3.class, 8, - MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 3 + parInt1 * 2))); - Iterator iterator = arraylist.iterator(); - - while (iterator.hasNext()) { - if (((StructureVillagePieces.PieceWeight) iterator.next()).villagePiecesLimit == 0) { - iterator.remove(); - } - } - - return arraylist; - } - - private static int func_75079_a(List parList) { - boolean flag = false; - int i = 0; - - for (StructureVillagePieces.PieceWeight structurevillagepieces$pieceweight : parList) { - if (structurevillagepieces$pieceweight.villagePiecesLimit > 0 - && structurevillagepieces$pieceweight.villagePiecesSpawned < structurevillagepieces$pieceweight.villagePiecesLimit) { - flag = true; - } - - i += structurevillagepieces$pieceweight.villagePieceWeight; - } - - return flag ? i : -1; - } - - private static StructureVillagePieces.Village func_176065_a(StructureVillagePieces.Start start, - StructureVillagePieces.PieceWeight weight, List rand, EaglercraftRandom facing, - int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { - Class oclass = weight.villagePieceClass; - Object object = null; - if (oclass == StructureVillagePieces.House4Garden.class) { - object = StructureVillagePieces.House4Garden.func_175858_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.Church.class) { - object = StructureVillagePieces.Church.func_175854_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.House1.class) { - object = StructureVillagePieces.House1.func_175850_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.WoodHut.class) { - object = StructureVillagePieces.WoodHut.func_175853_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.Hall.class) { - object = StructureVillagePieces.Hall.func_175857_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.Field1.class) { - object = StructureVillagePieces.Field1.func_175851_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.Field2.class) { - object = StructureVillagePieces.Field2.func_175852_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.House2.class) { - object = StructureVillagePieces.House2.func_175855_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } else if (oclass == StructureVillagePieces.House3.class) { - object = StructureVillagePieces.House3.func_175849_a(start, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - } - - return (StructureVillagePieces.Village) object; - } - - private static StructureVillagePieces.Village func_176067_c(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - int i = func_75079_a(start.structureVillageWeightedPieceList); - if (i <= 0) { - return null; - } else { - int j = 0; - - while (j < 5) { - ++j; - int k = facing.nextInt(i); - - for (StructureVillagePieces.PieceWeight structurevillagepieces$pieceweight : start.structureVillageWeightedPieceList) { - k -= structurevillagepieces$pieceweight.villagePieceWeight; - if (k < 0) { - if (!structurevillagepieces$pieceweight.canSpawnMoreVillagePiecesOfType(parInt4) - || structurevillagepieces$pieceweight == start.structVillagePieceWeight - && start.structureVillageWeightedPieceList.size() > 1) { - break; - } - - StructureVillagePieces.Village structurevillagepieces$village = func_176065_a(start, - structurevillagepieces$pieceweight, rand, facing, parInt1, parInt2, parInt3, - parEnumFacing, parInt4); - if (structurevillagepieces$village != null) { - ++structurevillagepieces$pieceweight.villagePiecesSpawned; - start.structVillagePieceWeight = structurevillagepieces$pieceweight; - if (!structurevillagepieces$pieceweight.canSpawnMoreVillagePieces()) { - start.structureVillageWeightedPieceList.remove(structurevillagepieces$pieceweight); - } - - return structurevillagepieces$village; - } - } - } - } - - StructureBoundingBox structureboundingbox = StructureVillagePieces.Torch.func_175856_a(start, rand, facing, - parInt1, parInt2, parInt3, parEnumFacing); - if (structureboundingbox != null) { - return new StructureVillagePieces.Torch(start, parInt4, facing, structureboundingbox, parEnumFacing); - } else { - return null; - } - } - } - - private static StructureComponent func_176066_d(StructureVillagePieces.Start start, List rand, - EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { - if (parInt4 > 50) { - return null; - } else if (Math.abs(parInt1 - start.getBoundingBox().minX) <= 112 - && Math.abs(parInt3 - start.getBoundingBox().minZ) <= 112) { - StructureVillagePieces.Village structurevillagepieces$village = func_176067_c(start, rand, facing, parInt1, - parInt2, parInt3, parEnumFacing, parInt4 + 1); - if (structurevillagepieces$village != null) { - int i = (structurevillagepieces$village.boundingBox.minX - + structurevillagepieces$village.boundingBox.maxX) / 2; - int j = (structurevillagepieces$village.boundingBox.minZ - + structurevillagepieces$village.boundingBox.maxZ) / 2; - int k = structurevillagepieces$village.boundingBox.maxX - - structurevillagepieces$village.boundingBox.minX; - int l = structurevillagepieces$village.boundingBox.maxZ - - structurevillagepieces$village.boundingBox.minZ; - int i1 = k > l ? k : l; - if (start.getWorldChunkManager().areBiomesViable(i, j, i1 / 2 + 4, MapGenVillage.villageSpawnBiomes)) { - rand.add(structurevillagepieces$village); - start.field_74932_i.add(structurevillagepieces$village); - return structurevillagepieces$village; - } - } - - return null; - } else { - return null; - } - } - - private static StructureComponent func_176069_e(StructureVillagePieces.Start start, List rand, - EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { - if (parInt4 > 3 + start.terrainType) { - return null; - } else if (Math.abs(parInt1 - start.getBoundingBox().minX) <= 112 - && Math.abs(parInt3 - start.getBoundingBox().minZ) <= 112) { - StructureBoundingBox structureboundingbox = StructureVillagePieces.Path.func_175848_a(start, rand, facing, - parInt1, parInt2, parInt3, parEnumFacing); - if (structureboundingbox != null && structureboundingbox.minY > 10) { - StructureVillagePieces.Path structurevillagepieces$path = new StructureVillagePieces.Path(start, - parInt4, facing, structureboundingbox, parEnumFacing); - int i = (structurevillagepieces$path.boundingBox.minX + structurevillagepieces$path.boundingBox.maxX) - / 2; - int j = (structurevillagepieces$path.boundingBox.minZ + structurevillagepieces$path.boundingBox.maxZ) - / 2; - int k = structurevillagepieces$path.boundingBox.maxX - structurevillagepieces$path.boundingBox.minX; - int l = structurevillagepieces$path.boundingBox.maxZ - structurevillagepieces$path.boundingBox.minZ; - int i1 = k > l ? k : l; - if (start.getWorldChunkManager().areBiomesViable(i, j, i1 / 2 + 4, MapGenVillage.villageSpawnBiomes)) { - rand.add(structurevillagepieces$path); - start.field_74930_j.add(structurevillagepieces$path); - return structurevillagepieces$path; - } - } - - return null; - } else { - return null; - } - } - public static class Church extends StructureVillagePieces.Village { - public Church() { - } - - public Church(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, - StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { - super(start, parInt1); - this.coordBaseMode = facing; - this.boundingBox = parStructureBoundingBox; - } - public static StructureVillagePieces.Church func_175854_a(StructureVillagePieces.Start start, List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -281,6 +65,16 @@ public class StructureVillagePieces { : null; } + public Church() { + } + + public Church(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, + StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { + super(start, parInt1); + this.coordBaseMode = facing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -406,9 +200,22 @@ public class StructureVillagePieces { } public static class Field1 extends StructureVillagePieces.Village { + public static StructureVillagePieces.Field1 func_175851_a(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, 0, 0, 0, 13, 4, 9, parEnumFacing); + return canVillageGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(rand, structureboundingbox) == null + ? new StructureVillagePieces.Field1(start, parInt4, facing, structureboundingbox, + parEnumFacing) + : null; + } + private Block cropTypeA; private Block cropTypeB; private Block cropTypeC; + private Block cropTypeD; public Field1() { @@ -425,45 +232,6 @@ public class StructureVillagePieces { this.cropTypeD = this.func_151559_a(rand); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("CA", Block.blockRegistry.getIDForObject(this.cropTypeA)); - nbttagcompound.setInteger("CB", Block.blockRegistry.getIDForObject(this.cropTypeB)); - nbttagcompound.setInteger("CC", Block.blockRegistry.getIDForObject(this.cropTypeC)); - nbttagcompound.setInteger("CD", Block.blockRegistry.getIDForObject(this.cropTypeD)); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.cropTypeA = Block.getBlockById(nbttagcompound.getInteger("CA")); - this.cropTypeB = Block.getBlockById(nbttagcompound.getInteger("CB")); - this.cropTypeC = Block.getBlockById(nbttagcompound.getInteger("CC")); - this.cropTypeD = Block.getBlockById(nbttagcompound.getInteger("CD")); - } - - private Block func_151559_a(EaglercraftRandom rand) { - switch (rand.nextInt(5)) { - case 0: - return Blocks.carrots; - case 1: - return Blocks.potatoes; - default: - return Blocks.wheat; - } - } - - public static StructureVillagePieces.Field1 func_175851_a(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, 0, 0, 0, 13, 4, 9, parEnumFacing); - return canVillageGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(rand, structureboundingbox) == null - ? new StructureVillagePieces.Field1(start, parInt4, facing, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -537,10 +305,50 @@ public class StructureVillagePieces { return true; } + + private Block func_151559_a(EaglercraftRandom rand) { + switch (rand.nextInt(5)) { + case 0: + return Blocks.carrots; + case 1: + return Blocks.potatoes; + default: + return Blocks.wheat; + } + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.cropTypeA = Block.getBlockById(nbttagcompound.getInteger("CA")); + this.cropTypeB = Block.getBlockById(nbttagcompound.getInteger("CB")); + this.cropTypeC = Block.getBlockById(nbttagcompound.getInteger("CC")); + this.cropTypeD = Block.getBlockById(nbttagcompound.getInteger("CD")); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("CA", Block.blockRegistry.getIDForObject(this.cropTypeA)); + nbttagcompound.setInteger("CB", Block.blockRegistry.getIDForObject(this.cropTypeB)); + nbttagcompound.setInteger("CC", Block.blockRegistry.getIDForObject(this.cropTypeC)); + nbttagcompound.setInteger("CD", Block.blockRegistry.getIDForObject(this.cropTypeD)); + } } public static class Field2 extends StructureVillagePieces.Village { + public static StructureVillagePieces.Field2 func_175852_a(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, 0, 0, 0, 7, 4, 9, parEnumFacing); + return canVillageGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(rand, structureboundingbox) == null + ? new StructureVillagePieces.Field2(start, parInt4, facing, structureboundingbox, + parEnumFacing) + : null; + } + private Block cropTypeA; + private Block cropTypeB; public Field2() { @@ -555,41 +363,6 @@ public class StructureVillagePieces { this.cropTypeB = this.func_151560_a(rand); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("CA", Block.blockRegistry.getIDForObject(this.cropTypeA)); - nbttagcompound.setInteger("CB", Block.blockRegistry.getIDForObject(this.cropTypeB)); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.cropTypeA = Block.getBlockById(nbttagcompound.getInteger("CA")); - this.cropTypeB = Block.getBlockById(nbttagcompound.getInteger("CB")); - } - - private Block func_151560_a(EaglercraftRandom rand) { - switch (rand.nextInt(5)) { - case 0: - return Blocks.carrots; - case 1: - return Blocks.potatoes; - default: - return Blocks.wheat; - } - } - - public static StructureVillagePieces.Field2 func_175852_a(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, 0, 0, 0, 7, 4, 9, parEnumFacing); - return canVillageGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(rand, structureboundingbox) == null - ? new StructureVillagePieces.Field2(start, parInt4, facing, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -643,19 +416,32 @@ public class StructureVillagePieces { return true; } + + private Block func_151560_a(EaglercraftRandom rand) { + switch (rand.nextInt(5)) { + case 0: + return Blocks.carrots; + case 1: + return Blocks.potatoes; + default: + return Blocks.wheat; + } + } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.cropTypeA = Block.getBlockById(nbttagcompound.getInteger("CA")); + this.cropTypeB = Block.getBlockById(nbttagcompound.getInteger("CB")); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("CA", Block.blockRegistry.getIDForObject(this.cropTypeA)); + nbttagcompound.setInteger("CB", Block.blockRegistry.getIDForObject(this.cropTypeB)); + } } public static class Hall extends StructureVillagePieces.Village { - public Hall() { - } - - public Hall(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, - StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { - super(start, parInt1); - this.coordBaseMode = facing; - this.boundingBox = parStructureBoundingBox; - } - public static StructureVillagePieces.Hall func_175857_a(StructureVillagePieces.Start start, List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -668,6 +454,16 @@ public class StructureVillagePieces { : null; } + public Hall() { + } + + public Hall(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, + StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { + super(start, parInt1); + this.coordBaseMode = facing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -794,16 +590,6 @@ public class StructureVillagePieces { } public static class House1 extends StructureVillagePieces.Village { - public House1() { - } - - public House1(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, - StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { - super(start, parInt1); - this.coordBaseMode = facing; - this.boundingBox = parStructureBoundingBox; - } - public static StructureVillagePieces.House1 func_175850_a(StructureVillagePieces.Start start, List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -816,6 +602,16 @@ public class StructureVillagePieces { : null; } + public House1() { + } + + public House1(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, + StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { + super(start, parInt1); + this.coordBaseMode = facing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -959,17 +755,6 @@ public class StructureVillagePieces { new WeightedRandomChestContent(Items.iron_horse_armor, 0, 1, 1, 1), new WeightedRandomChestContent(Items.golden_horse_armor, 0, 1, 1, 1), new WeightedRandomChestContent(Items.diamond_horse_armor, 0, 1, 1, 1) }); - private boolean hasMadeChest; - - public House2() { - } - - public House2(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, - StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { - super(start, parInt1); - this.coordBaseMode = facing; - this.boundingBox = parStructureBoundingBox; - } public static StructureVillagePieces.House2 func_175855_a(StructureVillagePieces.Start start, List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, @@ -983,14 +768,16 @@ public class StructureVillagePieces { : null; } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Chest", this.hasMadeChest); + private boolean hasMadeChest; + + public House2() { } - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.hasMadeChest = nbttagcompound.getBoolean("Chest"); + public House2(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, + StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { + super(start, parInt1); + this.coordBaseMode = facing; + this.boundingBox = parStructureBoundingBox; } public boolean addComponentParts(World world, EaglercraftRandom random, @@ -1093,19 +880,19 @@ public class StructureVillagePieces { protected int func_180779_c(int var1, int var2) { return 3; } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.hasMadeChest = nbttagcompound.getBoolean("Chest"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Chest", this.hasMadeChest); + } } public static class House3 extends StructureVillagePieces.Village { - public House3() { - } - - public House3(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, - StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { - super(start, parInt1); - this.coordBaseMode = facing; - this.boundingBox = parStructureBoundingBox; - } - public static StructureVillagePieces.House3 func_175849_a(StructureVillagePieces.Start start, List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { @@ -1118,6 +905,16 @@ public class StructureVillagePieces { : null; } + public House3() { + } + + public House3(StructureVillagePieces.Start start, int parInt1, EaglercraftRandom rand, + StructureBoundingBox parStructureBoundingBox, EnumFacing facing) { + super(start, parInt1); + this.coordBaseMode = facing; + this.boundingBox = parStructureBoundingBox; + } + public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -1274,6 +1071,16 @@ public class StructureVillagePieces { } public static class House4Garden extends StructureVillagePieces.Village { + public static StructureVillagePieces.House4Garden func_175858_a(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, 0, 0, 0, 5, 6, 5, parEnumFacing); + return StructureComponent.findIntersecting(rand, structureboundingbox) != null ? null + : new StructureVillagePieces.House4Garden(start, parInt4, facing, structureboundingbox, + parEnumFacing); + } + private boolean isRoofAccessible; public House4Garden() { @@ -1287,26 +1094,6 @@ public class StructureVillagePieces { this.isRoofAccessible = rand.nextBoolean(); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setBoolean("Terrace", this.isRoofAccessible); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.isRoofAccessible = nbttagcompound.getBoolean("Terrace"); - } - - public static StructureVillagePieces.House4Garden func_175858_a(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, 0, 0, 0, 5, 6, 5, parEnumFacing); - return StructureComponent.findIntersecting(rand, structureboundingbox) != null ? null - : new StructureVillagePieces.House4Garden(start, parInt4, facing, structureboundingbox, - parEnumFacing); - } - public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -1405,9 +1192,33 @@ public class StructureVillagePieces { this.spawnVillagers(world, structureboundingbox, 1, 1, 2, 1); return true; } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.isRoofAccessible = nbttagcompound.getBoolean("Terrace"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setBoolean("Terrace", this.isRoofAccessible); + } } public static class Path extends StructureVillagePieces.Road { + public static StructureBoundingBox func_175848_a(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing) { + for (int i = 7 * MathHelper.getRandomIntegerInRange(facing, 3, 5); i >= 7; i -= 7) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, 0, 0, 0, 3, 3, i, parEnumFacing); + if (StructureComponent.findIntersecting(rand, structureboundingbox) == null) { + return structureboundingbox; + } + } + + return null; + } + private int length; public Path() { @@ -1421,14 +1232,23 @@ public class StructureVillagePieces { this.length = Math.max(parStructureBoundingBox.getXSize(), parStructureBoundingBox.getZSize()); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("Length", this.length); - } + public boolean addComponentParts(World world, EaglercraftRandom var2, + StructureBoundingBox structureboundingbox) { + IBlockState iblockstate = this.func_175847_a(Blocks.gravel.getDefaultState()); + IBlockState iblockstate1 = this.func_175847_a(Blocks.cobblestone.getDefaultState()); - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.length = nbttagcompound.getInteger("Length"); + for (int i = this.boundingBox.minX; i <= this.boundingBox.maxX; ++i) { + for (int j = this.boundingBox.minZ; j <= this.boundingBox.maxZ; ++j) { + BlockPos blockpos = new BlockPos(i, 64, j); + if (structureboundingbox.isVecInside(blockpos)) { + blockpos = world.getTopSolidOrLiquidBlock(blockpos).down(); + world.setBlockState(blockpos, iblockstate, 2); + world.setBlockState(blockpos.down(), iblockstate1, 2); + } + } + } + + return true; } public void buildComponent(StructureComponent structurecomponent, List list, @@ -1505,37 +1325,14 @@ public class StructureVillagePieces { } - public static StructureBoundingBox func_175848_a(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing) { - for (int i = 7 * MathHelper.getRandomIntegerInRange(facing, 3, 5); i >= 7; i -= 7) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, 0, 0, 0, 3, 3, i, parEnumFacing); - if (StructureComponent.findIntersecting(rand, structureboundingbox) == null) { - return structureboundingbox; - } - } - - return null; + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.length = nbttagcompound.getInteger("Length"); } - public boolean addComponentParts(World world, EaglercraftRandom var2, - StructureBoundingBox structureboundingbox) { - IBlockState iblockstate = this.func_175847_a(Blocks.gravel.getDefaultState()); - IBlockState iblockstate1 = this.func_175847_a(Blocks.cobblestone.getDefaultState()); - - for (int i = this.boundingBox.minX; i <= this.boundingBox.maxX; ++i) { - for (int j = this.boundingBox.minZ; j <= this.boundingBox.maxZ; ++j) { - BlockPos blockpos = new BlockPos(i, 64, j); - if (structureboundingbox.isVecInside(blockpos)) { - blockpos = world.getTopSolidOrLiquidBlock(blockpos).down(); - world.setBlockState(blockpos, iblockstate, 2); - world.setBlockState(blockpos.down(), iblockstate1, 2); - } - } - } - - return true; + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("Length", this.length); } } @@ -1551,11 +1348,11 @@ public class StructureVillagePieces { this.villagePiecesLimit = parInt2; } - public boolean canSpawnMoreVillagePiecesOfType(int parInt1) { + public boolean canSpawnMoreVillagePieces() { return this.villagePiecesLimit == 0 || this.villagePiecesSpawned < this.villagePiecesLimit; } - public boolean canSpawnMoreVillagePieces() { + public boolean canSpawnMoreVillagePiecesOfType(int parInt1) { return this.villagePiecesLimit == 0 || this.villagePiecesSpawned < this.villagePiecesLimit; } } @@ -1599,6 +1396,15 @@ public class StructureVillagePieces { } public static class Torch extends StructureVillagePieces.Village { + public static StructureBoundingBox func_175856_a(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, 0, 0, 0, 3, 4, 2, parEnumFacing); + return StructureComponent.findIntersecting(rand, structureboundingbox) != null ? null + : structureboundingbox; + } + public Torch() { } @@ -1609,15 +1415,6 @@ public class StructureVillagePieces { this.boundingBox = parStructureBoundingBox; } - public static StructureBoundingBox func_175856_a(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, 0, 0, 0, 3, 4, 2, parEnumFacing); - return StructureComponent.findIntersecting(rand, structureboundingbox) != null ? null - : structureboundingbox; - } - public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -1654,8 +1451,13 @@ public class StructureVillagePieces { } abstract static class Village extends StructureComponent { + protected static boolean canVillageGoDeeper(StructureBoundingBox parStructureBoundingBox) { + return parStructureBoundingBox != null && parStructureBoundingBox.minY > 10; + } + protected int field_143015_k = -1; private int villagersSpawned; + private boolean isDesertVillage; public Village() { @@ -1669,16 +1471,74 @@ public class StructureVillagePieces { } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setInteger("HPos", this.field_143015_k); - nbttagcompound.setInteger("VCount", this.villagersSpawned); - nbttagcompound.setBoolean("Desert", this.isDesertVillage); + protected void fillWithBlocks(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, + int l, int i1, int j1, IBlockState iblockstate, IBlockState iblockstate1, boolean flag) { + IBlockState iblockstate2 = this.func_175847_a(iblockstate); + IBlockState iblockstate3 = this.func_175847_a(iblockstate1); + super.fillWithBlocks(world, structureboundingbox, i, j, k, l, i1, j1, iblockstate2, iblockstate3, flag); } - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - this.field_143015_k = nbttagcompound.getInteger("HPos"); - this.villagersSpawned = nbttagcompound.getInteger("VCount"); - this.isDesertVillage = nbttagcompound.getBoolean("Desert"); + protected void func_175846_a(boolean parFlag) { + this.isDesertVillage = parFlag; + } + + protected IBlockState func_175847_a(IBlockState parIBlockState) { + if (this.isDesertVillage) { + if (parIBlockState.getBlock() == Blocks.log || parIBlockState.getBlock() == Blocks.log2) { + return Blocks.sandstone.getDefaultState(); + } + + if (parIBlockState.getBlock() == Blocks.cobblestone) { + return Blocks.sandstone.getStateFromMeta(BlockSandStone.EnumType.DEFAULT.getMetadata()); + } + + if (parIBlockState.getBlock() == Blocks.planks) { + return Blocks.sandstone.getStateFromMeta(BlockSandStone.EnumType.SMOOTH.getMetadata()); + } + + if (parIBlockState.getBlock() == Blocks.oak_stairs) { + return Blocks.sandstone_stairs.getDefaultState().withProperty(BlockStairs.FACING, + parIBlockState.getValue(BlockStairs.FACING)); + } + + if (parIBlockState.getBlock() == Blocks.stone_stairs) { + return Blocks.sandstone_stairs.getDefaultState().withProperty(BlockStairs.FACING, + parIBlockState.getValue(BlockStairs.FACING)); + } + + if (parIBlockState.getBlock() == Blocks.gravel) { + return Blocks.sandstone.getDefaultState(); + } + } + + return parIBlockState; + } + + protected int func_180779_c(int var1, int i) { + return i; + } + + protected int getAverageGroundLevel(World worldIn, StructureBoundingBox parStructureBoundingBox) { + int i = 0; + int j = 0; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int k = this.boundingBox.minZ; k <= this.boundingBox.maxZ; ++k) { + for (int l = this.boundingBox.minX; l <= this.boundingBox.maxX; ++l) { + blockpos$mutableblockpos.func_181079_c(l, 64, k); + if (parStructureBoundingBox.isVecInside(blockpos$mutableblockpos)) { + i += Math.max(worldIn.getTopSolidOrLiquidBlock(blockpos$mutableblockpos).getY(), + worldIn.provider.getAverageGroundLevel()); + ++j; + } + } + } + + if (j == 0) { + return -1; + } else { + return i / j; + } } protected StructureComponent getNextComponentNN(StructureVillagePieces.Start start, @@ -1733,31 +1593,22 @@ public class StructureVillagePieces { return null; } - protected int getAverageGroundLevel(World worldIn, StructureBoundingBox parStructureBoundingBox) { - int i = 0; - int j = 0; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int k = this.boundingBox.minZ; k <= this.boundingBox.maxZ; ++k) { - for (int l = this.boundingBox.minX; l <= this.boundingBox.maxX; ++l) { - blockpos$mutableblockpos.func_181079_c(l, 64, k); - if (parStructureBoundingBox.isVecInside(blockpos$mutableblockpos)) { - i += Math.max(worldIn.getTopSolidOrLiquidBlock(blockpos$mutableblockpos).getY(), - worldIn.provider.getAverageGroundLevel()); - ++j; - } - } - } - - if (j == 0) { - return -1; - } else { - return i / j; - } + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + this.field_143015_k = nbttagcompound.getInteger("HPos"); + this.villagersSpawned = nbttagcompound.getInteger("VCount"); + this.isDesertVillage = nbttagcompound.getBoolean("Desert"); } - protected static boolean canVillageGoDeeper(StructureBoundingBox parStructureBoundingBox) { - return parStructureBoundingBox != null && parStructureBoundingBox.minY > 10; + protected void replaceAirAndLiquidDownwards(World world, IBlockState iblockstate, int i, int j, int k, + StructureBoundingBox structureboundingbox) { + IBlockState iblockstate1 = this.func_175847_a(iblockstate); + super.replaceAirAndLiquidDownwards(world, iblockstate1, i, j, k, structureboundingbox); + } + + protected void setBlockState(World world, IBlockState iblockstate, int i, int j, int k, + StructureBoundingBox structureboundingbox) { + IBlockState iblockstate1 = this.func_175847_a(iblockstate); + super.setBlockState(world, iblockstate1, i, j, k, structureboundingbox); } protected void spawnVillagers(World worldIn, StructureBoundingBox parStructureBoundingBox, int parInt1, @@ -1783,63 +1634,10 @@ public class StructureVillagePieces { } } - protected int func_180779_c(int var1, int i) { - return i; - } - - protected IBlockState func_175847_a(IBlockState parIBlockState) { - if (this.isDesertVillage) { - if (parIBlockState.getBlock() == Blocks.log || parIBlockState.getBlock() == Blocks.log2) { - return Blocks.sandstone.getDefaultState(); - } - - if (parIBlockState.getBlock() == Blocks.cobblestone) { - return Blocks.sandstone.getStateFromMeta(BlockSandStone.EnumType.DEFAULT.getMetadata()); - } - - if (parIBlockState.getBlock() == Blocks.planks) { - return Blocks.sandstone.getStateFromMeta(BlockSandStone.EnumType.SMOOTH.getMetadata()); - } - - if (parIBlockState.getBlock() == Blocks.oak_stairs) { - return Blocks.sandstone_stairs.getDefaultState().withProperty(BlockStairs.FACING, - parIBlockState.getValue(BlockStairs.FACING)); - } - - if (parIBlockState.getBlock() == Blocks.stone_stairs) { - return Blocks.sandstone_stairs.getDefaultState().withProperty(BlockStairs.FACING, - parIBlockState.getValue(BlockStairs.FACING)); - } - - if (parIBlockState.getBlock() == Blocks.gravel) { - return Blocks.sandstone.getDefaultState(); - } - } - - return parIBlockState; - } - - protected void setBlockState(World world, IBlockState iblockstate, int i, int j, int k, - StructureBoundingBox structureboundingbox) { - IBlockState iblockstate1 = this.func_175847_a(iblockstate); - super.setBlockState(world, iblockstate1, i, j, k, structureboundingbox); - } - - protected void fillWithBlocks(World world, StructureBoundingBox structureboundingbox, int i, int j, int k, - int l, int i1, int j1, IBlockState iblockstate, IBlockState iblockstate1, boolean flag) { - IBlockState iblockstate2 = this.func_175847_a(iblockstate); - IBlockState iblockstate3 = this.func_175847_a(iblockstate1); - super.fillWithBlocks(world, structureboundingbox, i, j, k, l, i1, j1, iblockstate2, iblockstate3, flag); - } - - protected void replaceAirAndLiquidDownwards(World world, IBlockState iblockstate, int i, int j, int k, - StructureBoundingBox structureboundingbox) { - IBlockState iblockstate1 = this.func_175847_a(iblockstate); - super.replaceAirAndLiquidDownwards(world, iblockstate1, i, j, k, structureboundingbox); - } - - protected void func_175846_a(boolean parFlag) { - this.isDesertVillage = parFlag; + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setInteger("HPos", this.field_143015_k); + nbttagcompound.setInteger("VCount", this.villagersSpawned); + nbttagcompound.setBoolean("Desert", this.isDesertVillage); } } @@ -1861,22 +1659,6 @@ public class StructureVillagePieces { } - public void buildComponent(StructureComponent structurecomponent, List list, - EaglercraftRandom random) { - StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, - this.boundingBox.minX - 1, this.boundingBox.maxY - 4, this.boundingBox.minZ + 1, EnumFacing.WEST, - this.getComponentType()); - StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, - this.boundingBox.maxX + 1, this.boundingBox.maxY - 4, this.boundingBox.minZ + 1, EnumFacing.EAST, - this.getComponentType()); - StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, - this.boundingBox.minX + 1, this.boundingBox.maxY - 4, this.boundingBox.minZ - 1, EnumFacing.NORTH, - this.getComponentType()); - StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, - this.boundingBox.minX + 1, this.boundingBox.maxY - 4, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, - this.getComponentType()); - } - public boolean addComponentParts(World world, EaglercraftRandom var2, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -1916,10 +1698,39 @@ public class StructureVillagePieces { return true; } + + public void buildComponent(StructureComponent structurecomponent, List list, + EaglercraftRandom random) { + StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, + this.boundingBox.minX - 1, this.boundingBox.maxY - 4, this.boundingBox.minZ + 1, EnumFacing.WEST, + this.getComponentType()); + StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, + this.boundingBox.maxX + 1, this.boundingBox.maxY - 4, this.boundingBox.minZ + 1, EnumFacing.EAST, + this.getComponentType()); + StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, + this.boundingBox.minX + 1, this.boundingBox.maxY - 4, this.boundingBox.minZ - 1, EnumFacing.NORTH, + this.getComponentType()); + StructureVillagePieces.func_176069_e((StructureVillagePieces.Start) structurecomponent, list, random, + this.boundingBox.minX + 1, this.boundingBox.maxY - 4, this.boundingBox.maxZ + 1, EnumFacing.SOUTH, + this.getComponentType()); + } } public static class WoodHut extends StructureVillagePieces.Village { + public static StructureVillagePieces.WoodHut func_175853_a(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, + parInt2, parInt3, 0, 0, 0, 4, 6, 5, parEnumFacing); + return canVillageGoDeeper(structureboundingbox) + && StructureComponent.findIntersecting(rand, structureboundingbox) == null + ? new StructureVillagePieces.WoodHut(start, parInt4, facing, structureboundingbox, + parEnumFacing) + : null; + } + private boolean isTallHouse; + private int tablePosition; public WoodHut() { @@ -1934,30 +1745,6 @@ public class StructureVillagePieces { this.tablePosition = rand.nextInt(3); } - protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { - super.writeStructureToNBT(nbttagcompound); - nbttagcompound.setInteger("T", this.tablePosition); - nbttagcompound.setBoolean("C", this.isTallHouse); - } - - protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { - super.readStructureFromNBT(nbttagcompound); - this.tablePosition = nbttagcompound.getInteger("T"); - this.isTallHouse = nbttagcompound.getBoolean("C"); - } - - public static StructureVillagePieces.WoodHut func_175853_a(StructureVillagePieces.Start start, - List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, - EnumFacing parEnumFacing, int parInt4) { - StructureBoundingBox structureboundingbox = StructureBoundingBox.getComponentToAddBoundingBox(parInt1, - parInt2, parInt3, 0, 0, 0, 4, 6, 5, parEnumFacing); - return canVillageGoDeeper(structureboundingbox) - && StructureComponent.findIntersecting(rand, structureboundingbox) == null - ? new StructureVillagePieces.WoodHut(start, parInt4, facing, structureboundingbox, - parEnumFacing) - : null; - } - public boolean addComponentParts(World world, EaglercraftRandom random, StructureBoundingBox structureboundingbox) { if (this.field_143015_k < 0) { @@ -2042,5 +1829,228 @@ public class StructureVillagePieces { this.spawnVillagers(world, structureboundingbox, 1, 1, 2, 1); return true; } + + protected void readStructureFromNBT(NBTTagCompound nbttagcompound) { + super.readStructureFromNBT(nbttagcompound); + this.tablePosition = nbttagcompound.getInteger("T"); + this.isTallHouse = nbttagcompound.getBoolean("C"); + } + + protected void writeStructureToNBT(NBTTagCompound nbttagcompound) { + super.writeStructureToNBT(nbttagcompound); + nbttagcompound.setInteger("T", this.tablePosition); + nbttagcompound.setBoolean("C", this.isTallHouse); + } + } + + private static StructureVillagePieces.Village func_176065_a(StructureVillagePieces.Start start, + StructureVillagePieces.PieceWeight weight, List rand, EaglercraftRandom facing, + int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { + Class oclass = weight.villagePieceClass; + Object object = null; + if (oclass == StructureVillagePieces.House4Garden.class) { + object = StructureVillagePieces.House4Garden.func_175858_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.Church.class) { + object = StructureVillagePieces.Church.func_175854_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.House1.class) { + object = StructureVillagePieces.House1.func_175850_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.WoodHut.class) { + object = StructureVillagePieces.WoodHut.func_175853_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.Hall.class) { + object = StructureVillagePieces.Hall.func_175857_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.Field1.class) { + object = StructureVillagePieces.Field1.func_175851_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.Field2.class) { + object = StructureVillagePieces.Field2.func_175852_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.House2.class) { + object = StructureVillagePieces.House2.func_175855_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } else if (oclass == StructureVillagePieces.House3.class) { + object = StructureVillagePieces.House3.func_175849_a(start, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + } + + return (StructureVillagePieces.Village) object; + } + + private static StructureComponent func_176066_d(StructureVillagePieces.Start start, List rand, + EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { + if (parInt4 > 50) { + return null; + } else if (Math.abs(parInt1 - start.getBoundingBox().minX) <= 112 + && Math.abs(parInt3 - start.getBoundingBox().minZ) <= 112) { + StructureVillagePieces.Village structurevillagepieces$village = func_176067_c(start, rand, facing, parInt1, + parInt2, parInt3, parEnumFacing, parInt4 + 1); + if (structurevillagepieces$village != null) { + int i = (structurevillagepieces$village.boundingBox.minX + + structurevillagepieces$village.boundingBox.maxX) / 2; + int j = (structurevillagepieces$village.boundingBox.minZ + + structurevillagepieces$village.boundingBox.maxZ) / 2; + int k = structurevillagepieces$village.boundingBox.maxX + - structurevillagepieces$village.boundingBox.minX; + int l = structurevillagepieces$village.boundingBox.maxZ + - structurevillagepieces$village.boundingBox.minZ; + int i1 = k > l ? k : l; + if (start.getWorldChunkManager().areBiomesViable(i, j, i1 / 2 + 4, MapGenVillage.villageSpawnBiomes)) { + rand.add(structurevillagepieces$village); + start.field_74932_i.add(structurevillagepieces$village); + return structurevillagepieces$village; + } + } + + return null; + } else { + return null; + } + } + + private static StructureVillagePieces.Village func_176067_c(StructureVillagePieces.Start start, + List rand, EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, + EnumFacing parEnumFacing, int parInt4) { + int i = func_75079_a(start.structureVillageWeightedPieceList); + if (i <= 0) { + return null; + } else { + int j = 0; + + while (j < 5) { + ++j; + int k = facing.nextInt(i); + + for (StructureVillagePieces.PieceWeight structurevillagepieces$pieceweight : start.structureVillageWeightedPieceList) { + k -= structurevillagepieces$pieceweight.villagePieceWeight; + if (k < 0) { + if (!structurevillagepieces$pieceweight.canSpawnMoreVillagePiecesOfType(parInt4) + || structurevillagepieces$pieceweight == start.structVillagePieceWeight + && start.structureVillageWeightedPieceList.size() > 1) { + break; + } + + StructureVillagePieces.Village structurevillagepieces$village = func_176065_a(start, + structurevillagepieces$pieceweight, rand, facing, parInt1, parInt2, parInt3, + parEnumFacing, parInt4); + if (structurevillagepieces$village != null) { + ++structurevillagepieces$pieceweight.villagePiecesSpawned; + start.structVillagePieceWeight = structurevillagepieces$pieceweight; + if (!structurevillagepieces$pieceweight.canSpawnMoreVillagePieces()) { + start.structureVillageWeightedPieceList.remove(structurevillagepieces$pieceweight); + } + + return structurevillagepieces$village; + } + } + } + } + + StructureBoundingBox structureboundingbox = StructureVillagePieces.Torch.func_175856_a(start, rand, facing, + parInt1, parInt2, parInt3, parEnumFacing); + if (structureboundingbox != null) { + return new StructureVillagePieces.Torch(start, parInt4, facing, structureboundingbox, parEnumFacing); + } else { + return null; + } + } + } + + private static StructureComponent func_176069_e(StructureVillagePieces.Start start, List rand, + EaglercraftRandom facing, int parInt1, int parInt2, int parInt3, EnumFacing parEnumFacing, int parInt4) { + if (parInt4 > 3 + start.terrainType) { + return null; + } else if (Math.abs(parInt1 - start.getBoundingBox().minX) <= 112 + && Math.abs(parInt3 - start.getBoundingBox().minZ) <= 112) { + StructureBoundingBox structureboundingbox = StructureVillagePieces.Path.func_175848_a(start, rand, facing, + parInt1, parInt2, parInt3, parEnumFacing); + if (structureboundingbox != null && structureboundingbox.minY > 10) { + StructureVillagePieces.Path structurevillagepieces$path = new StructureVillagePieces.Path(start, + parInt4, facing, structureboundingbox, parEnumFacing); + int i = (structurevillagepieces$path.boundingBox.minX + structurevillagepieces$path.boundingBox.maxX) + / 2; + int j = (structurevillagepieces$path.boundingBox.minZ + structurevillagepieces$path.boundingBox.maxZ) + / 2; + int k = structurevillagepieces$path.boundingBox.maxX - structurevillagepieces$path.boundingBox.minX; + int l = structurevillagepieces$path.boundingBox.maxZ - structurevillagepieces$path.boundingBox.minZ; + int i1 = k > l ? k : l; + if (start.getWorldChunkManager().areBiomesViable(i, j, i1 / 2 + 4, MapGenVillage.villageSpawnBiomes)) { + rand.add(structurevillagepieces$path); + start.field_74930_j.add(structurevillagepieces$path); + return structurevillagepieces$path; + } + } + + return null; + } else { + return null; + } + } + + private static int func_75079_a(List parList) { + boolean flag = false; + int i = 0; + + for (StructureVillagePieces.PieceWeight structurevillagepieces$pieceweight : parList) { + if (structurevillagepieces$pieceweight.villagePiecesLimit > 0 + && structurevillagepieces$pieceweight.villagePiecesSpawned < structurevillagepieces$pieceweight.villagePiecesLimit) { + flag = true; + } + + i += structurevillagepieces$pieceweight.villagePieceWeight; + } + + return flag ? i : -1; + } + + public static List getStructureVillageWeightedPieceList( + EaglercraftRandom random, int parInt1) { + ArrayList arraylist = Lists.newArrayList(); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House4Garden.class, 4, + MathHelper.getRandomIntegerInRange(random, 2 + parInt1, 4 + parInt1 * 2))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Church.class, 20, + MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 1 + parInt1))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House1.class, 20, + MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 2 + parInt1))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.WoodHut.class, 3, + MathHelper.getRandomIntegerInRange(random, 2 + parInt1, 5 + parInt1 * 3))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Hall.class, 15, + MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 2 + parInt1))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Field1.class, 3, + MathHelper.getRandomIntegerInRange(random, 1 + parInt1, 4 + parInt1))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.Field2.class, 3, + MathHelper.getRandomIntegerInRange(random, 2 + parInt1, 4 + parInt1 * 2))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House2.class, 15, + MathHelper.getRandomIntegerInRange(random, 0, 1 + parInt1))); + arraylist.add(new StructureVillagePieces.PieceWeight(StructureVillagePieces.House3.class, 8, + MathHelper.getRandomIntegerInRange(random, 0 + parInt1, 3 + parInt1 * 2))); + Iterator iterator = arraylist.iterator(); + + while (iterator.hasNext()) { + if (((StructureVillagePieces.PieceWeight) iterator.next()).villagePiecesLimit == 0) { + iterator.remove(); + } + } + + return arraylist; + } + + public static void registerVillagePieces() { + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House1.class, "ViBH"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Field1.class, "ViDF"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Field2.class, "ViF"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Torch.class, "ViL"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Hall.class, "ViPH"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House4Garden.class, "ViSH"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.WoodHut.class, "ViSmH"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Church.class, "ViST"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House2.class, "ViS"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Start.class, "ViStart"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Path.class, "ViSR"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.House3.class, "ViTRH"); + MapGenStructureIO.registerStructureComponent(StructureVillagePieces.Well.class, "ViW"); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/pathfinder/NodeProcessor.java b/src/game/java/net/minecraft/world/pathfinder/NodeProcessor.java index 9756e6b5..d0775f8f 100644 --- a/src/game/java/net/minecraft/world/pathfinder/NodeProcessor.java +++ b/src/game/java/net/minecraft/world/pathfinder/NodeProcessor.java @@ -6,22 +6,25 @@ import net.minecraft.util.IntHashMap; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,6 +36,12 @@ public abstract class NodeProcessor { protected int entitySizeY; protected int entitySizeZ; + public abstract int findPathOptions(PathPoint[] var1, Entity var2, PathPoint var3, PathPoint var4, float var5); + + public abstract PathPoint getPathPointTo(Entity var1); + + public abstract PathPoint getPathPointToCoords(Entity var1, double var2, double var4, double var6); + public void initProcessor(IBlockAccess iblockaccessIn, Entity entityIn) { this.blockaccess = iblockaccessIn; this.pointMap.clearMap(); @@ -41,19 +50,8 @@ public abstract class NodeProcessor { this.entitySizeZ = MathHelper.floor_float(entityIn.width + 1.0F); } - /**+ - * This method is called when all nodes have been processed and - * PathEntity is created.\n {@link - * net.minecraft.world.pathfinder.WalkNodeProcessor - * WalkNodeProcessor} uses this to change its field {@link - * net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater - * avoidsWater} - */ - public void postProcess() { - } - - /**+ - * Returns a mapped point or creates and adds one + /** + * + Returns a mapped point or creates and adds one */ protected PathPoint openPoint(int x, int y, int z) { int i = PathPoint.makeHash(x, y, z); @@ -66,9 +64,13 @@ public abstract class NodeProcessor { return pathpoint; } - public abstract PathPoint getPathPointTo(Entity var1); - - public abstract PathPoint getPathPointToCoords(Entity var1, double var2, double var4, double var6); - - public abstract int findPathOptions(PathPoint[] var1, Entity var2, PathPoint var3, PathPoint var4, float var5); + /** + * + This method is called when all nodes have been processed and PathEntity is + * created.\n {@link net.minecraft.world.pathfinder.WalkNodeProcessor + * WalkNodeProcessor} uses this to change its field + * {@link net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater + * avoidsWater} + */ + public void postProcess() { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/pathfinder/SwimNodeProcessor.java b/src/game/java/net/minecraft/world/pathfinder/SwimNodeProcessor.java index a639b444..9703c89f 100644 --- a/src/game/java/net/minecraft/world/pathfinder/SwimNodeProcessor.java +++ b/src/game/java/net/minecraft/world/pathfinder/SwimNodeProcessor.java @@ -9,60 +9,30 @@ import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SwimNodeProcessor extends NodeProcessor { - public void initProcessor(IBlockAccess iblockaccess, Entity entity) { - super.initProcessor(iblockaccess, entity); - } - - /**+ - * This method is called when all nodes have been processed and - * PathEntity is created.\n {@link - * net.minecraft.world.pathfinder.WalkNodeProcessor - * WalkNodeProcessor} uses this to change its field {@link - * net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater - * avoidsWater} - */ - public void postProcess() { - super.postProcess(); - } - - /**+ - * Returns given entity's position as PathPoint - */ - public PathPoint getPathPointTo(Entity entity) { - return this.openPoint(MathHelper.floor_double(entity.getEntityBoundingBox().minX), - MathHelper.floor_double(entity.getEntityBoundingBox().minY + 0.5D), - MathHelper.floor_double(entity.getEntityBoundingBox().minZ)); - } - - /**+ - * Returns PathPoint for given coordinates - */ - public PathPoint getPathPointToCoords(Entity entity, double d0, double d1, double d2) { - return this.openPoint(MathHelper.floor_double(d0 - (double) (entity.width / 2.0F)), - MathHelper.floor_double(d1 + 0.5D), MathHelper.floor_double(d2 - (double) (entity.width / 2.0F))); - } - public int findPathOptions(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, float f) { int i = 0; @@ -80,14 +50,6 @@ public class SwimNodeProcessor extends NodeProcessor { return i; } - /**+ - * Returns a point that the entity can safely move to - */ - private PathPoint getSafePoint(Entity entityIn, int x, int y, int z) { - int i = this.func_176186_b(entityIn, x, y, z); - return i == -1 ? this.openPoint(x, y, z) : null; - } - private int func_176186_b(Entity entityIn, int x, int y, int z) { BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); @@ -105,4 +67,44 @@ public class SwimNodeProcessor extends NodeProcessor { return -1; } + + /** + * + Returns given entity's position as PathPoint + */ + public PathPoint getPathPointTo(Entity entity) { + return this.openPoint(MathHelper.floor_double(entity.getEntityBoundingBox().minX), + MathHelper.floor_double(entity.getEntityBoundingBox().minY + 0.5D), + MathHelper.floor_double(entity.getEntityBoundingBox().minZ)); + } + + /** + * + Returns PathPoint for given coordinates + */ + public PathPoint getPathPointToCoords(Entity entity, double d0, double d1, double d2) { + return this.openPoint(MathHelper.floor_double(d0 - (double) (entity.width / 2.0F)), + MathHelper.floor_double(d1 + 0.5D), MathHelper.floor_double(d2 - (double) (entity.width / 2.0F))); + } + + /** + * + Returns a point that the entity can safely move to + */ + private PathPoint getSafePoint(Entity entityIn, int x, int y, int z) { + int i = this.func_176186_b(entityIn, x, y, z); + return i == -1 ? this.openPoint(x, y, z) : null; + } + + public void initProcessor(IBlockAccess iblockaccess, Entity entity) { + super.initProcessor(iblockaccess, entity); + } + + /** + * + This method is called when all nodes have been processed and PathEntity is + * created.\n {@link net.minecraft.world.pathfinder.WalkNodeProcessor + * WalkNodeProcessor} uses this to change its field + * {@link net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater + * avoidsWater} + */ + public void postProcess() { + super.postProcess(); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/pathfinder/WalkNodeProcessor.java b/src/game/java/net/minecraft/world/pathfinder/WalkNodeProcessor.java index e8849cf1..a4c960d4 100644 --- a/src/game/java/net/minecraft/world/pathfinder/WalkNodeProcessor.java +++ b/src/game/java/net/minecraft/world/pathfinder/WalkNodeProcessor.java @@ -14,182 +14,30 @@ import net.minecraft.util.BlockPos; import net.minecraft.util.MathHelper; import net.minecraft.world.IBlockAccess; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WalkNodeProcessor extends NodeProcessor { - private boolean canEnterDoors; - private boolean canBreakDoors; - private boolean avoidsWater; - private boolean canSwim; - private boolean shouldAvoidWater; - - public void initProcessor(IBlockAccess iblockaccess, Entity entity) { - super.initProcessor(iblockaccess, entity); - this.shouldAvoidWater = this.avoidsWater; - } - - /**+ - * This method is called when all nodes have been processed and - * PathEntity is created.\n {@link - * net.minecraft.world.pathfinder.WalkNodeProcessor - * WalkNodeProcessor} uses this to change its field {@link - * net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater - * avoidsWater} - */ - public void postProcess() { - super.postProcess(); - this.avoidsWater = this.shouldAvoidWater; - } - - /**+ - * Returns given entity's position as PathPoint - */ - public PathPoint getPathPointTo(Entity entity) { - int i; - if (this.canSwim && entity.isInWater()) { - i = (int) entity.getEntityBoundingBox().minY; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos( - MathHelper.floor_double(entity.posX), i, MathHelper.floor_double(entity.posZ)); - - for (Block block = this.blockaccess.getBlockState(blockpos$mutableblockpos) - .getBlock(); block == Blocks.flowing_water - || block == Blocks.water; block = this.blockaccess.getBlockState(blockpos$mutableblockpos) - .getBlock()) { - ++i; - blockpos$mutableblockpos.func_181079_c(MathHelper.floor_double(entity.posX), i, - MathHelper.floor_double(entity.posZ)); - } - - this.avoidsWater = false; - } else { - i = MathHelper.floor_double(entity.getEntityBoundingBox().minY + 0.5D); - } - - return this.openPoint(MathHelper.floor_double(entity.getEntityBoundingBox().minX), i, - MathHelper.floor_double(entity.getEntityBoundingBox().minZ)); - } - - /**+ - * Returns PathPoint for given coordinates - */ - public PathPoint getPathPointToCoords(Entity entity, double d0, double d1, double d2) { - return this.openPoint(MathHelper.floor_double(d0 - (double) (entity.width / 2.0F)), MathHelper.floor_double(d1), - MathHelper.floor_double(d2 - (double) (entity.width / 2.0F))); - } - - public int findPathOptions(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, - float f) { - int i = 0; - byte b0 = 0; - if (this.getVerticalOffset(entity, pathpoint.xCoord, pathpoint.yCoord + 1, pathpoint.zCoord) == 1) { - b0 = 1; - } - - PathPoint pathpoint2 = this.getSafePoint(entity, pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord + 1, b0); - PathPoint pathpoint3 = this.getSafePoint(entity, pathpoint.xCoord - 1, pathpoint.yCoord, pathpoint.zCoord, b0); - PathPoint pathpoint4 = this.getSafePoint(entity, pathpoint.xCoord + 1, pathpoint.yCoord, pathpoint.zCoord, b0); - PathPoint pathpoint5 = this.getSafePoint(entity, pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord - 1, b0); - if (pathpoint2 != null && !pathpoint2.visited && pathpoint2.distanceTo(pathpoint1) < f) { - apathpoint[i++] = pathpoint2; - } - - if (pathpoint3 != null && !pathpoint3.visited && pathpoint3.distanceTo(pathpoint1) < f) { - apathpoint[i++] = pathpoint3; - } - - if (pathpoint4 != null && !pathpoint4.visited && pathpoint4.distanceTo(pathpoint1) < f) { - apathpoint[i++] = pathpoint4; - } - - if (pathpoint5 != null && !pathpoint5.visited && pathpoint5.distanceTo(pathpoint1) < f) { - apathpoint[i++] = pathpoint5; - } - - return i; - } - - /**+ - * Returns a point that the entity can safely move to - */ - private PathPoint getSafePoint(Entity entityIn, int x, int y, int z, int parInt4) { - PathPoint pathpoint = null; - int i = this.getVerticalOffset(entityIn, x, y, z); - if (i == 2) { - return this.openPoint(x, y, z); - } else { - if (i == 1) { - pathpoint = this.openPoint(x, y, z); - } - - if (pathpoint == null && parInt4 > 0 && i != -3 && i != -4 - && this.getVerticalOffset(entityIn, x, y + parInt4, z) == 1) { - pathpoint = this.openPoint(x, y + parInt4, z); - y += parInt4; - } - - if (pathpoint != null) { - int j = 0; - - int k; - for (k = 0; y > 0; pathpoint = this.openPoint(x, y, z)) { - k = this.getVerticalOffset(entityIn, x, y - 1, z); - if (this.avoidsWater && k == -1) { - return null; - } - - if (k != 1) { - break; - } - - if (j++ >= entityIn.getMaxFallHeight()) { - return null; - } - - --y; - if (y <= 0) { - return null; - } - } - - if (k == -2) { - return null; - } - } - - return pathpoint; - } - } - - /**+ - * Checks if an entity collides with blocks at a - * position.\nReturns 1 if clear, 0 for colliding with any solid - * block, -1 for water(if avoids water),\n-2 for lava, -3 for - * fence and wall, -4 for closed trapdoor, 2 if otherwise clear - * except for open trapdoor or water(if not avoiding) - */ - private int getVerticalOffset(Entity entityIn, int x, int y, int z) { - return func_176170_a(this.blockaccess, entityIn, x, y, z, this.entitySizeX, this.entitySizeY, this.entitySizeZ, - this.avoidsWater, this.canBreakDoors, this.canEnterDoors); - } - public static int func_176170_a(IBlockAccess blockaccessIn, Entity entityIn, int x, int y, int z, int sizeX, int sizeY, int sizeZ, boolean avoidWater, boolean breakDoors, boolean enterDoors) { boolean flag = false; @@ -253,31 +101,185 @@ public class WalkNodeProcessor extends NodeProcessor { return flag ? 2 : 1; } - public void setEnterDoors(boolean canEnterDoorsIn) { - this.canEnterDoors = canEnterDoorsIn; + private boolean canEnterDoors; + private boolean canBreakDoors; + private boolean avoidsWater; + private boolean canSwim; + + private boolean shouldAvoidWater; + + public int findPathOptions(PathPoint[] apathpoint, Entity entity, PathPoint pathpoint, PathPoint pathpoint1, + float f) { + int i = 0; + byte b0 = 0; + if (this.getVerticalOffset(entity, pathpoint.xCoord, pathpoint.yCoord + 1, pathpoint.zCoord) == 1) { + b0 = 1; + } + + PathPoint pathpoint2 = this.getSafePoint(entity, pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord + 1, b0); + PathPoint pathpoint3 = this.getSafePoint(entity, pathpoint.xCoord - 1, pathpoint.yCoord, pathpoint.zCoord, b0); + PathPoint pathpoint4 = this.getSafePoint(entity, pathpoint.xCoord + 1, pathpoint.yCoord, pathpoint.zCoord, b0); + PathPoint pathpoint5 = this.getSafePoint(entity, pathpoint.xCoord, pathpoint.yCoord, pathpoint.zCoord - 1, b0); + if (pathpoint2 != null && !pathpoint2.visited && pathpoint2.distanceTo(pathpoint1) < f) { + apathpoint[i++] = pathpoint2; + } + + if (pathpoint3 != null && !pathpoint3.visited && pathpoint3.distanceTo(pathpoint1) < f) { + apathpoint[i++] = pathpoint3; + } + + if (pathpoint4 != null && !pathpoint4.visited && pathpoint4.distanceTo(pathpoint1) < f) { + apathpoint[i++] = pathpoint4; + } + + if (pathpoint5 != null && !pathpoint5.visited && pathpoint5.distanceTo(pathpoint1) < f) { + apathpoint[i++] = pathpoint5; + } + + return i; } - public void setBreakDoors(boolean canBreakDoorsIn) { - this.canBreakDoors = canBreakDoorsIn; - } - - public void setAvoidsWater(boolean avoidsWaterIn) { - this.avoidsWater = avoidsWaterIn; - } - - public void setCanSwim(boolean canSwimIn) { - this.canSwim = canSwimIn; - } - - public boolean getEnterDoors() { - return this.canEnterDoors; + public boolean getAvoidsWater() { + return this.avoidsWater; } public boolean getCanSwim() { return this.canSwim; } - public boolean getAvoidsWater() { - return this.avoidsWater; + public boolean getEnterDoors() { + return this.canEnterDoors; + } + + /** + * + Returns given entity's position as PathPoint + */ + public PathPoint getPathPointTo(Entity entity) { + int i; + if (this.canSwim && entity.isInWater()) { + i = (int) entity.getEntityBoundingBox().minY; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos( + MathHelper.floor_double(entity.posX), i, MathHelper.floor_double(entity.posZ)); + + for (Block block = this.blockaccess.getBlockState(blockpos$mutableblockpos) + .getBlock(); block == Blocks.flowing_water + || block == Blocks.water; block = this.blockaccess.getBlockState(blockpos$mutableblockpos) + .getBlock()) { + ++i; + blockpos$mutableblockpos.func_181079_c(MathHelper.floor_double(entity.posX), i, + MathHelper.floor_double(entity.posZ)); + } + + this.avoidsWater = false; + } else { + i = MathHelper.floor_double(entity.getEntityBoundingBox().minY + 0.5D); + } + + return this.openPoint(MathHelper.floor_double(entity.getEntityBoundingBox().minX), i, + MathHelper.floor_double(entity.getEntityBoundingBox().minZ)); + } + + /** + * + Returns PathPoint for given coordinates + */ + public PathPoint getPathPointToCoords(Entity entity, double d0, double d1, double d2) { + return this.openPoint(MathHelper.floor_double(d0 - (double) (entity.width / 2.0F)), MathHelper.floor_double(d1), + MathHelper.floor_double(d2 - (double) (entity.width / 2.0F))); + } + + /** + * + Returns a point that the entity can safely move to + */ + private PathPoint getSafePoint(Entity entityIn, int x, int y, int z, int parInt4) { + PathPoint pathpoint = null; + int i = this.getVerticalOffset(entityIn, x, y, z); + if (i == 2) { + return this.openPoint(x, y, z); + } else { + if (i == 1) { + pathpoint = this.openPoint(x, y, z); + } + + if (pathpoint == null && parInt4 > 0 && i != -3 && i != -4 + && this.getVerticalOffset(entityIn, x, y + parInt4, z) == 1) { + pathpoint = this.openPoint(x, y + parInt4, z); + y += parInt4; + } + + if (pathpoint != null) { + int j = 0; + + int k; + for (k = 0; y > 0; pathpoint = this.openPoint(x, y, z)) { + k = this.getVerticalOffset(entityIn, x, y - 1, z); + if (this.avoidsWater && k == -1) { + return null; + } + + if (k != 1) { + break; + } + + if (j++ >= entityIn.getMaxFallHeight()) { + return null; + } + + --y; + if (y <= 0) { + return null; + } + } + + if (k == -2) { + return null; + } + } + + return pathpoint; + } + } + + /** + * + Checks if an entity collides with blocks at a position.\nReturns 1 if + * clear, 0 for colliding with any solid block, -1 for water(if avoids + * water),\n-2 for lava, -3 for fence and wall, -4 for closed trapdoor, 2 if + * otherwise clear except for open trapdoor or water(if not avoiding) + */ + private int getVerticalOffset(Entity entityIn, int x, int y, int z) { + return func_176170_a(this.blockaccess, entityIn, x, y, z, this.entitySizeX, this.entitySizeY, this.entitySizeZ, + this.avoidsWater, this.canBreakDoors, this.canEnterDoors); + } + + public void initProcessor(IBlockAccess iblockaccess, Entity entity) { + super.initProcessor(iblockaccess, entity); + this.shouldAvoidWater = this.avoidsWater; + } + + /** + * + This method is called when all nodes have been processed and PathEntity is + * created.\n {@link net.minecraft.world.pathfinder.WalkNodeProcessor + * WalkNodeProcessor} uses this to change its field + * {@link net.minecraft.world.pathfinder.WalkNodeProcessor#avoidsWater + * avoidsWater} + */ + public void postProcess() { + super.postProcess(); + this.avoidsWater = this.shouldAvoidWater; + } + + public void setAvoidsWater(boolean avoidsWaterIn) { + this.avoidsWater = avoidsWaterIn; + } + + public void setBreakDoors(boolean canBreakDoorsIn) { + this.canBreakDoors = canBreakDoorsIn; + } + + public void setCanSwim(boolean canSwimIn) { + this.canSwim = canSwimIn; + } + + public void setEnterDoors(boolean canEnterDoorsIn) { + this.canEnterDoors = canEnterDoorsIn; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/DerivedWorldInfo.java b/src/game/java/net/minecraft/world/storage/DerivedWorldInfo.java index 669c3e6c..70b3faf5 100644 --- a/src/game/java/net/minecraft/world/storage/DerivedWorldInfo.java +++ b/src/game/java/net/minecraft/world/storage/DerivedWorldInfo.java @@ -7,22 +7,25 @@ import net.minecraft.world.GameRules; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,253 +37,253 @@ public class DerivedWorldInfo extends WorldInfo { this.theWorldInfo = parWorldInfo; } - /**+ - * Gets the NBTTagCompound for the worldInfo - */ - public NBTTagCompound getNBTTagCompound() { - return this.theWorldInfo.getNBTTagCompound(); - } - - /**+ - * Creates a new NBTTagCompound for the world, with the given - * NBTTag as the "Player" - */ - public NBTTagCompound cloneNBTCompound(NBTTagCompound nbt) { - return this.theWorldInfo.cloneNBTCompound(nbt); - } - - /**+ - * Returns the seed of current world. - */ - public long getSeed() { - return this.theWorldInfo.getSeed(); - } - - /**+ - * Returns the x spawn position - */ - public int getSpawnX() { - return this.theWorldInfo.getSpawnX(); - } - - /**+ - * Return the Y axis spawning point of the player. - */ - public int getSpawnY() { - return this.theWorldInfo.getSpawnY(); - } - - /**+ - * Returns the z spawn position - */ - public int getSpawnZ() { - return this.theWorldInfo.getSpawnZ(); - } - - public long getWorldTotalTime() { - return this.theWorldInfo.getWorldTotalTime(); - } - - /**+ - * Get current world time - */ - public long getWorldTime() { - return this.theWorldInfo.getWorldTime(); - } - - public long getSizeOnDisk() { - return this.theWorldInfo.getSizeOnDisk(); - } - - /**+ - * Returns the player's NBTTagCompound to be loaded - */ - public NBTTagCompound getPlayerNBTTagCompound() { - return this.theWorldInfo.getPlayerNBTTagCompound(); - } - - /**+ - * Get current world name - */ - public String getWorldName() { - return this.theWorldInfo.getWorldName(); - } - - /**+ - * Returns the save version of this world - */ - public int getSaveVersion() { - return this.theWorldInfo.getSaveVersion(); - } - - /**+ - * Return the last time the player was in this world. - */ - public long getLastTimePlayed() { - return this.theWorldInfo.getLastTimePlayed(); - } - - /**+ - * Returns true if it is thundering, false otherwise. - */ - public boolean isThundering() { - return this.theWorldInfo.isThundering(); - } - - /**+ - * Returns the number of ticks until next thunderbolt. - */ - public int getThunderTime() { - return this.theWorldInfo.getThunderTime(); - } - - /**+ - * Returns true if it is raining, false otherwise. - */ - public boolean isRaining() { - return this.theWorldInfo.isRaining(); - } - - /**+ - * Return the number of ticks until rain. - */ - public int getRainTime() { - return this.theWorldInfo.getRainTime(); - } - - /**+ - * Gets the GameType. - */ - public WorldSettings.GameType getGameType() { - return this.theWorldInfo.getGameType(); - } - - /**+ - * Set the x spawn position to the passed in value - */ - public void setSpawnX(int x) { - } - - /**+ - * Sets the y spawn position - */ - public void setSpawnY(int y) { - } - - /**+ - * Set the z spawn position to the passed in value - */ - public void setSpawnZ(int z) { - } - - public void setWorldTotalTime(long time) { - } - - /**+ - * Set current world time - */ - public void setWorldTime(long time) { - } - - public void setSpawn(BlockPos spawnPoint) { - } - - public void setWorldName(String worldName) { - } - - /**+ - * Sets the save version of the world - */ - public void setSaveVersion(int version) { - } - - /**+ - * Sets whether it is thundering or not. - */ - public void setThundering(boolean thunderingIn) { - } - - /**+ - * Defines the number of ticks until next thunderbolt. - */ - public void setThunderTime(int time) { - } - - /**+ - * Sets whether it is raining or not. - */ - public void setRaining(boolean isRaining) { - } - - /**+ - * Sets the number of ticks until rain. - */ - public void setRainTime(int time) { - } - - /**+ - * Get whether the map features (e.g. strongholds) generation is - * enabled or disabled. - */ - public boolean isMapFeaturesEnabled() { - return this.theWorldInfo.isMapFeaturesEnabled(); - } - - /**+ - * Returns true if hardcore mode is enabled, otherwise false - */ - public boolean isHardcoreModeEnabled() { - return this.theWorldInfo.isHardcoreModeEnabled(); - } - - public WorldType getTerrainType() { - return this.theWorldInfo.getTerrainType(); - } - - public void setTerrainType(WorldType type) { - } - - /**+ - * Returns true if commands are allowed on this World. + /** + * + Returns true if commands are allowed on this World. */ public boolean areCommandsAllowed() { return this.theWorldInfo.areCommandsAllowed(); } - public void setAllowCommands(boolean allow) { - } - - /**+ - * Returns true if the World is initialized. + /** + * + Creates a new NBTTagCompound for the world, with the given NBTTag as the + * "Player" */ - public boolean isInitialized() { - return this.theWorldInfo.isInitialized(); - } - - /**+ - * Sets the initialization status of the World. - */ - public void setServerInitialized(boolean initializedIn) { - } - - /**+ - * Gets the GameRules class Instance. - */ - public GameRules getGameRulesInstance() { - return this.theWorldInfo.getGameRulesInstance(); + public NBTTagCompound cloneNBTCompound(NBTTagCompound nbt) { + return this.theWorldInfo.cloneNBTCompound(nbt); } public EnumDifficulty getDifficulty() { return this.theWorldInfo.getDifficulty(); } - public void setDifficulty(EnumDifficulty newDifficulty) { + /** + * + Gets the GameRules class Instance. + */ + public GameRules getGameRulesInstance() { + return this.theWorldInfo.getGameRulesInstance(); + } + + /** + * + Gets the GameType. + */ + public WorldSettings.GameType getGameType() { + return this.theWorldInfo.getGameType(); + } + + /** + * + Return the last time the player was in this world. + */ + public long getLastTimePlayed() { + return this.theWorldInfo.getLastTimePlayed(); + } + + /** + * + Gets the NBTTagCompound for the worldInfo + */ + public NBTTagCompound getNBTTagCompound() { + return this.theWorldInfo.getNBTTagCompound(); + } + + /** + * + Returns the player's NBTTagCompound to be loaded + */ + public NBTTagCompound getPlayerNBTTagCompound() { + return this.theWorldInfo.getPlayerNBTTagCompound(); + } + + /** + * + Return the number of ticks until rain. + */ + public int getRainTime() { + return this.theWorldInfo.getRainTime(); + } + + /** + * + Returns the save version of this world + */ + public int getSaveVersion() { + return this.theWorldInfo.getSaveVersion(); + } + + /** + * + Returns the seed of current world. + */ + public long getSeed() { + return this.theWorldInfo.getSeed(); + } + + public long getSizeOnDisk() { + return this.theWorldInfo.getSizeOnDisk(); + } + + /** + * + Returns the x spawn position + */ + public int getSpawnX() { + return this.theWorldInfo.getSpawnX(); + } + + /** + * + Return the Y axis spawning point of the player. + */ + public int getSpawnY() { + return this.theWorldInfo.getSpawnY(); + } + + /** + * + Returns the z spawn position + */ + public int getSpawnZ() { + return this.theWorldInfo.getSpawnZ(); + } + + public WorldType getTerrainType() { + return this.theWorldInfo.getTerrainType(); + } + + /** + * + Returns the number of ticks until next thunderbolt. + */ + public int getThunderTime() { + return this.theWorldInfo.getThunderTime(); + } + + /** + * + Get current world name + */ + public String getWorldName() { + return this.theWorldInfo.getWorldName(); + } + + /** + * + Get current world time + */ + public long getWorldTime() { + return this.theWorldInfo.getWorldTime(); + } + + public long getWorldTotalTime() { + return this.theWorldInfo.getWorldTotalTime(); } public boolean isDifficultyLocked() { return this.theWorldInfo.isDifficultyLocked(); } + /** + * + Returns true if hardcore mode is enabled, otherwise false + */ + public boolean isHardcoreModeEnabled() { + return this.theWorldInfo.isHardcoreModeEnabled(); + } + + /** + * + Returns true if the World is initialized. + */ + public boolean isInitialized() { + return this.theWorldInfo.isInitialized(); + } + + /** + * + Get whether the map features (e.g. strongholds) generation is enabled or + * disabled. + */ + public boolean isMapFeaturesEnabled() { + return this.theWorldInfo.isMapFeaturesEnabled(); + } + + /** + * + Returns true if it is raining, false otherwise. + */ + public boolean isRaining() { + return this.theWorldInfo.isRaining(); + } + + /** + * + Returns true if it is thundering, false otherwise. + */ + public boolean isThundering() { + return this.theWorldInfo.isThundering(); + } + + public void setAllowCommands(boolean allow) { + } + + public void setDifficulty(EnumDifficulty newDifficulty) { + } + public void setDifficultyLocked(boolean locked) { } + + /** + * + Sets whether it is raining or not. + */ + public void setRaining(boolean isRaining) { + } + + /** + * + Sets the number of ticks until rain. + */ + public void setRainTime(int time) { + } + + /** + * + Sets the save version of the world + */ + public void setSaveVersion(int version) { + } + + /** + * + Sets the initialization status of the World. + */ + public void setServerInitialized(boolean initializedIn) { + } + + public void setSpawn(BlockPos spawnPoint) { + } + + /** + * + Set the x spawn position to the passed in value + */ + public void setSpawnX(int x) { + } + + /** + * + Sets the y spawn position + */ + public void setSpawnY(int y) { + } + + /** + * + Set the z spawn position to the passed in value + */ + public void setSpawnZ(int z) { + } + + public void setTerrainType(WorldType type) { + } + + /** + * + Sets whether it is thundering or not. + */ + public void setThundering(boolean thunderingIn) { + } + + /** + * + Defines the number of ticks until next thunderbolt. + */ + public void setThunderTime(int time) { + } + + public void setWorldName(String worldName) { + } + + /** + * + Set current world time + */ + public void setWorldTime(long time) { + } + + public void setWorldTotalTime(long time) { + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/IPlayerFileData.java b/src/game/java/net/minecraft/world/storage/IPlayerFileData.java index 0e2c7511..b769b169 100644 --- a/src/game/java/net/minecraft/world/storage/IPlayerFileData.java +++ b/src/game/java/net/minecraft/world/storage/IPlayerFileData.java @@ -3,42 +3,42 @@ package net.minecraft.world.storage; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IPlayerFileData { - /**+ - * Writes the player data to disk from the specified - * PlayerEntityMP. + /** + * + Returns an array of usernames for which player.dat exists for. */ - void writePlayerData(EntityPlayer var1); + String[] getAvailablePlayerDat(); - /**+ - * Reads the player data from disk into the specified - * PlayerEntityMP. + /** + * + Reads the player data from disk into the specified PlayerEntityMP. */ NBTTagCompound readPlayerData(EntityPlayer var1); - /**+ - * Returns an array of usernames for which player.dat exists - * for. + /** + * + Writes the player data to disk from the specified PlayerEntityMP. */ - String[] getAvailablePlayerDat(); + void writePlayerData(EntityPlayer var1); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/ISaveFormat.java b/src/game/java/net/minecraft/world/storage/ISaveFormat.java index 8ce92229..09a12db3 100644 --- a/src/game/java/net/minecraft/world/storage/ISaveFormat.java +++ b/src/game/java/net/minecraft/world/storage/ISaveFormat.java @@ -1,78 +1,83 @@ package net.minecraft.world.storage; import java.util.List; + import net.minecraft.util.IProgressUpdate; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ISaveFormat { - /**+ - * Returns the name of the save format. + /** + * + Return whether the given world can be loaded. */ - String getName(); + boolean canLoadWorld(String var1); - /**+ - * Returns back a loader for the specified save directory - */ - ISaveHandler getSaveLoader(String var1, boolean var2); - - List getSaveList(); - - void flushCache(); - - /**+ - * Returns the world's WorldInfo object - */ - WorldInfo getWorldInfo(String var1); - - boolean func_154335_d(String var1); - - /**+ - * @args: Takes one argument - the name of the directory of the - * world to delete. @desc: Delete the world by deleting the - * associated directory recursively. - */ - boolean deleteWorldDirectory(String var1); - - /**+ - * Renames the world by storing the new name in level.dat. It - * does *not* rename the directory containing the world data. - */ - boolean renameWorld(String var1, String var2); - - boolean func_154334_a(String var1); - - /**+ - * gets if the map is old chunk saving (true) or McRegion - * (false) - */ - boolean isOldMapFormat(String var1); - - /**+ - * converts the map to mcRegion + /** + * + converts the map to mcRegion */ boolean convertMapFormat(String var1, IProgressUpdate var2); - /**+ - * Return whether the given world can be loaded. + /** + * + + * + * @args: Takes one argument - the name of the directory of the world to + * delete. @desc: Delete the world by deleting the associated directory + * recursively. */ - boolean canLoadWorld(String var1); + boolean deleteWorldDirectory(String var1); + + void flushCache(); + + boolean func_154334_a(String var1); + + boolean func_154335_d(String var1); + + /** + * + Returns the name of the save format. + */ + String getName(); + + List getSaveList(); + + /** + * + Returns back a loader for the specified save directory + */ + ISaveHandler getSaveLoader(String var1, boolean var2); + + /** + * + Returns the world's WorldInfo object + */ + WorldInfo getWorldInfo(String var1); + + /** + * + gets if the map is old chunk saving (true) or McRegion (false) + */ + boolean isOldMapFormat(String var1); + + /** + * + Renames the world by storing the new name in level.dat. It does *not* + * rename the directory containing the world data. + */ + boolean renameWorld(String var1, String var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/ISaveHandler.java b/src/game/java/net/minecraft/world/storage/ISaveHandler.java index b54304bd..8f438829 100644 --- a/src/game/java/net/minecraft/world/storage/ISaveHandler.java +++ b/src/game/java/net/minecraft/world/storage/ISaveHandler.java @@ -1,81 +1,79 @@ package net.minecraft.world.storage; -import net.minecraft.nbt.NBTTagCompound; import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.MinecraftException; import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ISaveHandler { - /**+ - * Loads and returns the world info - */ - WorldInfo loadWorldInfo(); - - /**+ - * Checks the session lock to prevent save collisions + /** + * + Checks the session lock to prevent save collisions */ void checkSessionLock() throws MinecraftException; - /**+ - * initializes and returns the chunk loader for the specified - * world provider - */ - IChunkLoader getChunkLoader(WorldProvider var1); - - /**+ - * Saves the given World Info with the given NBTTagCompound as - * the Player. - */ - void saveWorldInfoWithPlayer(WorldInfo var1, NBTTagCompound var2); - - /**+ - * used to update level.dat from old format to MCRegion format - */ - void saveWorldInfo(WorldInfo var1); - - IPlayerFileData getPlayerNBTManager(); - - /**+ - * Called to flush all changes to disk, waiting for them to - * complete. + /** + * + Called to flush all changes to disk, waiting for them to complete. */ void flush(); - /**+ - * Gets the File object corresponding to the base directory of - * this world. + /** + * + initializes and returns the chunk loader for the specified world provider */ - VFile2 getWorldDirectory(); + IChunkLoader getChunkLoader(WorldProvider var1); - /**+ - * Gets the file location of the given map + /** + * + Gets the file location of the given map */ VFile2 getMapFileFromName(String var1); - /**+ - * Returns the name of the directory where world information is - * saved. + IPlayerFileData getPlayerNBTManager(); + + /** + * + Gets the File object corresponding to the base directory of this world. + */ + VFile2 getWorldDirectory(); + + /** + * + Returns the name of the directory where world information is saved. */ String getWorldDirectoryName(); + + /** + * + Loads and returns the world info + */ + WorldInfo loadWorldInfo(); + + /** + * + used to update level.dat from old format to MCRegion format + */ + void saveWorldInfo(WorldInfo var1); + + /** + * + Saves the given World Info with the given NBTTagCompound as the Player. + */ + void saveWorldInfoWithPlayer(WorldInfo var1, NBTTagCompound var2); } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/MapData.java b/src/game/java/net/minecraft/world/storage/MapData.java index c79d8604..c523b894 100644 --- a/src/game/java/net/minecraft/world/storage/MapData.java +++ b/src/game/java/net/minecraft/world/storage/MapData.java @@ -19,41 +19,87 @@ import net.minecraft.util.Vec4b; import net.minecraft.world.World; import net.minecraft.world.WorldSavedData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapData extends WorldSavedData { + public class MapInfo { + public final EntityPlayer entityplayerObj; + private boolean field_176105_d = true; + private int minX = 0; + private int minY = 0; + private int maxX = 127; + private int maxY = 127; + private int field_176109_i; + public int field_82569_d; + + public MapInfo(EntityPlayer player) { + this.entityplayerObj = player; + } + + public Packet getPacket(ItemStack stack) { + if (this.field_176105_d) { + this.field_176105_d = false; + return new S34PacketMaps(stack.getMetadata(), MapData.this.scale, MapData.this.mapDecorations.values(), + MapData.this.colors, this.minX, this.minY, this.maxX + 1 - this.minX, + this.maxY + 1 - this.minY); + } else { + return this.field_176109_i++ % 5 == 0 ? new S34PacketMaps(stack.getMetadata(), MapData.this.scale, + MapData.this.mapDecorations.values(), MapData.this.colors, 0, 0, 0, 0) : null; + } + } + + public void update(int x, int y) { + if (this.field_176105_d) { + this.minX = Math.min(this.minX, x); + this.minY = Math.min(this.minY, y); + this.maxX = Math.max(this.maxX, x); + this.maxY = Math.max(this.maxY, y); + } else { + this.field_176105_d = true; + this.minX = x; + this.minY = y; + this.maxX = x; + this.maxY = y; + } + + } + } + public int xCenter; public int zCenter; public byte dimension; public byte scale; - /**+ - * colours + /** + * + colours */ public byte[] colors = new byte[16384]; - /**+ - * Holds a reference to the MapInfo of the players who own a - * copy of the map + /** + * + Holds a reference to the MapInfo of the players who own a copy of the map */ public List playersArrayList = Lists.newArrayList(); private Map playersHashMap = Maps.newHashMap(); + public Map mapDecorations = Maps.newLinkedHashMap(); public MapData(String mapname) { @@ -68,8 +114,24 @@ public class MapData extends WorldSavedData { this.zCenter = k * i + i / 2 - 64; } - /**+ - * reads in data from the NBTTagCompound into this MapDataBase + public MapData.MapInfo getMapInfo(EntityPlayer player) { + MapData.MapInfo mapdata$mapinfo = (MapData.MapInfo) this.playersHashMap.get(player); + if (mapdata$mapinfo == null) { + mapdata$mapinfo = new MapData.MapInfo(player); + this.playersHashMap.put(player, mapdata$mapinfo); + this.playersArrayList.add(mapdata$mapinfo); + } + + return mapdata$mapinfo; + } + + public Packet getMapPacket(ItemStack mapStack, World worldIn, EntityPlayer player) { + MapData.MapInfo mapdata$mapinfo = (MapData.MapInfo) this.playersHashMap.get(player); + return mapdata$mapinfo == null ? null : mapdata$mapinfo.getPacket(mapStack); + } + + /** + * + reads in data from the NBTTagCompound into this MapDataBase */ public void readFromNBT(NBTTagCompound nbttagcompound) { this.dimension = nbttagcompound.getByte("dimension"); @@ -102,23 +164,62 @@ public class MapData extends WorldSavedData { } - /**+ - * write data to NBTTagCompound from this MapDataBase, similar - * to Entities and TileEntities - */ - public void writeToNBT(NBTTagCompound nbttagcompound) { - nbttagcompound.setByte("dimension", this.dimension); - nbttagcompound.setInteger("xCenter", this.xCenter); - nbttagcompound.setInteger("zCenter", this.zCenter); - nbttagcompound.setByte("scale", this.scale); - nbttagcompound.setShort("width", (short) 128); - nbttagcompound.setShort("height", (short) 128); - nbttagcompound.setByteArray("colors", this.colors); + private void updateDecorations(int type, World worldIn, String entityIdentifier, double worldX, double worldZ, + double rotation) { + int i = 1 << this.scale; + float f = (float) (worldX - (double) this.xCenter) / (float) i; + float f1 = (float) (worldZ - (double) this.zCenter) / (float) i; + byte b0 = (byte) ((int) ((double) (f * 2.0F) + 0.5D)); + byte b1 = (byte) ((int) ((double) (f1 * 2.0F) + 0.5D)); + byte b3 = 63; + byte b2; + if (f >= (float) (-b3) && f1 >= (float) (-b3) && f <= (float) b3 && f1 <= (float) b3) { + rotation = rotation + (rotation < 0.0D ? -8.0D : 8.0D); + b2 = (byte) ((int) (rotation * 16.0D / 360.0D)); + if (this.dimension < 0) { + int j = (int) (worldIn.getWorldInfo().getWorldTime() / 10L); + b2 = (byte) (j * j * 34187121 + j * 121 >> 15 & 15); + } + } else { + if (Math.abs(f) >= 320.0F || Math.abs(f1) >= 320.0F) { + this.mapDecorations.remove(entityIdentifier); + return; + } + + type = 6; + b2 = 0; + if (f <= (float) (-b3)) { + b0 = (byte) ((int) ((double) (b3 * 2) + 2.5D)); + } + + if (f1 <= (float) (-b3)) { + b1 = (byte) ((int) ((double) (b3 * 2) + 2.5D)); + } + + if (f >= (float) b3) { + b0 = (byte) (b3 * 2 + 1); + } + + if (f1 >= (float) b3) { + b1 = (byte) (b3 * 2 + 1); + } + } + + this.mapDecorations.put(entityIdentifier, new Vec4b((byte) type, b0, b1, b2)); } - /**+ - * Adds the player passed to the list of visible players and - * checks to see which players are visible + public void updateMapData(int x, int y) { + super.markDirty(); + + for (int i = 0, l = this.playersArrayList.size(); i < l; ++i) { + this.playersArrayList.get(i).update(x, y); + } + + } + + /** + * + Adds the player passed to the list of visible players and checks to see + * which players are visible */ public void updateVisiblePlayers(EntityPlayer player, ItemStack mapStack) { if (!this.playersHashMap.containsKey(player)) { @@ -171,115 +272,17 @@ public class MapData extends WorldSavedData { } - private void updateDecorations(int type, World worldIn, String entityIdentifier, double worldX, double worldZ, - double rotation) { - int i = 1 << this.scale; - float f = (float) (worldX - (double) this.xCenter) / (float) i; - float f1 = (float) (worldZ - (double) this.zCenter) / (float) i; - byte b0 = (byte) ((int) ((double) (f * 2.0F) + 0.5D)); - byte b1 = (byte) ((int) ((double) (f1 * 2.0F) + 0.5D)); - byte b3 = 63; - byte b2; - if (f >= (float) (-b3) && f1 >= (float) (-b3) && f <= (float) b3 && f1 <= (float) b3) { - rotation = rotation + (rotation < 0.0D ? -8.0D : 8.0D); - b2 = (byte) ((int) (rotation * 16.0D / 360.0D)); - if (this.dimension < 0) { - int j = (int) (worldIn.getWorldInfo().getWorldTime() / 10L); - b2 = (byte) (j * j * 34187121 + j * 121 >> 15 & 15); - } - } else { - if (Math.abs(f) >= 320.0F || Math.abs(f1) >= 320.0F) { - this.mapDecorations.remove(entityIdentifier); - return; - } - - type = 6; - b2 = 0; - if (f <= (float) (-b3)) { - b0 = (byte) ((int) ((double) (b3 * 2) + 2.5D)); - } - - if (f1 <= (float) (-b3)) { - b1 = (byte) ((int) ((double) (b3 * 2) + 2.5D)); - } - - if (f >= (float) b3) { - b0 = (byte) (b3 * 2 + 1); - } - - if (f1 >= (float) b3) { - b1 = (byte) (b3 * 2 + 1); - } - } - - this.mapDecorations.put(entityIdentifier, new Vec4b((byte) type, b0, b1, b2)); - } - - public Packet getMapPacket(ItemStack mapStack, World worldIn, EntityPlayer player) { - MapData.MapInfo mapdata$mapinfo = (MapData.MapInfo) this.playersHashMap.get(player); - return mapdata$mapinfo == null ? null : mapdata$mapinfo.getPacket(mapStack); - } - - public void updateMapData(int x, int y) { - super.markDirty(); - - for (int i = 0, l = this.playersArrayList.size(); i < l; ++i) { - this.playersArrayList.get(i).update(x, y); - } - - } - - public MapData.MapInfo getMapInfo(EntityPlayer player) { - MapData.MapInfo mapdata$mapinfo = (MapData.MapInfo) this.playersHashMap.get(player); - if (mapdata$mapinfo == null) { - mapdata$mapinfo = new MapData.MapInfo(player); - this.playersHashMap.put(player, mapdata$mapinfo); - this.playersArrayList.add(mapdata$mapinfo); - } - - return mapdata$mapinfo; - } - - public class MapInfo { - public final EntityPlayer entityplayerObj; - private boolean field_176105_d = true; - private int minX = 0; - private int minY = 0; - private int maxX = 127; - private int maxY = 127; - private int field_176109_i; - public int field_82569_d; - - public MapInfo(EntityPlayer player) { - this.entityplayerObj = player; - } - - public Packet getPacket(ItemStack stack) { - if (this.field_176105_d) { - this.field_176105_d = false; - return new S34PacketMaps(stack.getMetadata(), MapData.this.scale, MapData.this.mapDecorations.values(), - MapData.this.colors, this.minX, this.minY, this.maxX + 1 - this.minX, - this.maxY + 1 - this.minY); - } else { - return this.field_176109_i++ % 5 == 0 ? new S34PacketMaps(stack.getMetadata(), MapData.this.scale, - MapData.this.mapDecorations.values(), MapData.this.colors, 0, 0, 0, 0) : null; - } - } - - public void update(int x, int y) { - if (this.field_176105_d) { - this.minX = Math.min(this.minX, x); - this.minY = Math.min(this.minY, y); - this.maxX = Math.max(this.maxX, x); - this.maxY = Math.max(this.maxY, y); - } else { - this.field_176105_d = true; - this.minX = x; - this.minY = y; - this.maxX = x; - this.maxY = y; - } - - } + /** + * + write data to NBTTagCompound from this MapDataBase, similar to Entities and + * TileEntities + */ + public void writeToNBT(NBTTagCompound nbttagcompound) { + nbttagcompound.setByte("dimension", this.dimension); + nbttagcompound.setInteger("xCenter", this.xCenter); + nbttagcompound.setInteger("zCenter", this.zCenter); + nbttagcompound.setByte("scale", this.scale); + nbttagcompound.setShort("width", (short) 128); + nbttagcompound.setShort("height", (short) 128); + nbttagcompound.setByteArray("colors", this.colors); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/MapStorage.java b/src/game/java/net/minecraft/world/storage/MapStorage.java index 19cddb2b..a324389b 100644 --- a/src/game/java/net/minecraft/world/storage/MapStorage.java +++ b/src/game/java/net/minecraft/world/storage/MapStorage.java @@ -1,7 +1,5 @@ package net.minecraft.world.storage; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; @@ -10,189 +8,75 @@ import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagShort; -import net.lax1dude.eaglercraft.v1_8.EagRuntime; -import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; import net.minecraft.scoreboard.ScoreboardSaveData; import net.minecraft.village.VillageCollection; import net.minecraft.world.WorldSavedData; import net.minecraft.world.gen.structure.MapGenStructureData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class MapStorage { - private ISaveHandler saveHandler; - protected Map loadedDataMap = Maps.newHashMap(); - /**+ - * List of loaded MapDataBases. - */ - private List loadedDataList = Lists.newArrayList(); - private Map idCounts = Maps.newHashMap(); - public static interface MapStorageProvider { WorldSavedData createInstance(String mapFileName); } public static final Map, MapStorageProvider> storageProviders = new HashMap<>(); - static { storageProviders.put(MapData.class, MapData::new); storageProviders.put(MapGenStructureData.class, MapGenStructureData::new); storageProviders.put(ScoreboardSaveData.class, ScoreboardSaveData::new); storageProviders.put(VillageCollection.class, VillageCollection::new); } + private ISaveHandler saveHandler; + + protected Map loadedDataMap = Maps.newHashMap(); + + /** + * + List of loaded MapDataBases. + */ + private List loadedDataList = Lists.newArrayList(); + + private Map idCounts = Maps.newHashMap(); public MapStorage(ISaveHandler saveHandlerIn) { this.saveHandler = saveHandlerIn; this.loadIdCounts(); } - /**+ - * Loads an existing MapDataBase corresponding to the given - * String id from disk, instantiating the given Class, or - * returns null if none such file exists. args: Class to - * instantiate, String dataid - */ - public WorldSavedData loadData(Class oclass, String s) { - WorldSavedData worldsaveddata = (WorldSavedData) this.loadedDataMap.get(s); - if (worldsaveddata != null) { - return worldsaveddata; - } else { - if (this.saveHandler != null) { - try { - VFile2 file1 = this.saveHandler.getMapFileFromName(s); - if (file1 != null && file1.exists()) { - try { - worldsaveddata = (WorldSavedData) storageProviders.get(oclass).createInstance(s); - } catch (Exception exception) { - throw new RuntimeException("Failed to instantiate " + oclass.toString(), exception); - } - try (InputStream is = file1.getInputStream()) { - NBTTagCompound nbttagcompound = CompressedStreamTools.readCompressed(is); - worldsaveddata.readFromNBT(nbttagcompound.getCompoundTag("data")); - } - } - } catch (Exception exception1) { - EagRuntime.debugPrintStackTrace(exception1); - } - } - - if (worldsaveddata != null) { - this.loadedDataMap.put(s, worldsaveddata); - this.loadedDataList.add(worldsaveddata); - } - - return worldsaveddata; - } - } - - /**+ - * Assigns the given String id to the given MapDataBase, - * removing any existing ones of the same id. - */ - public void setData(String s, WorldSavedData worldsaveddata) { - if (this.loadedDataMap.containsKey(s)) { - this.loadedDataList.remove(this.loadedDataMap.remove(s)); - } - - this.loadedDataMap.put(s, worldsaveddata); - this.loadedDataList.add(worldsaveddata); - } - - /**+ - * Saves all dirty loaded MapDataBases to disk. - */ - public void saveAllData() { - for (int i = 0; i < this.loadedDataList.size(); ++i) { - WorldSavedData worldsaveddata = (WorldSavedData) this.loadedDataList.get(i); - if (worldsaveddata.isDirty()) { - this.saveData(worldsaveddata); - worldsaveddata.setDirty(false); - } - } - - } - - /**+ - * Saves the given MapDataBase to disk. - */ - private void saveData(WorldSavedData parWorldSavedData) { - if (this.saveHandler != null) { - try { - VFile2 file1 = this.saveHandler.getMapFileFromName(parWorldSavedData.mapName); - if (file1 != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - parWorldSavedData.writeToNBT(nbttagcompound); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setTag("data", nbttagcompound); - - try (OutputStream fileoutputstream = file1.getOutputStream()) { - CompressedStreamTools.writeCompressed(nbttagcompound1, fileoutputstream); - } - } - } catch (Exception exception) { - EagRuntime.debugPrintStackTrace(exception); - } - - } - } - - /**+ - * Loads the idCounts Map from the 'idcounts' file. - */ - private void loadIdCounts() { - try { - this.idCounts.clear(); - if (this.saveHandler == null) { - return; - } - - VFile2 file1 = this.saveHandler.getMapFileFromName("idcounts"); - if (file1 != null && file1.exists()) { - NBTTagCompound nbttagcompound; - try (DataInputStream datainputstream = new DataInputStream(file1.getInputStream())) { - nbttagcompound = CompressedStreamTools.read(datainputstream); - } - - for (String s : nbttagcompound.getKeySet()) { - NBTBase nbtbase = nbttagcompound.getTag(s); - if (nbtbase instanceof NBTTagShort) { - NBTTagShort nbttagshort = (NBTTagShort) nbtbase; - short short1 = nbttagshort.getShort(); - this.idCounts.put(s, Short.valueOf(short1)); - } - } - } - } catch (Exception exception) { - EagRuntime.debugPrintStackTrace(exception); - } - - } - - /**+ - * Returns an unique new data id for the given prefix and saves - * the idCounts map to the 'idcounts' file. + /** + * + Returns an unique new data id for the given prefix and saves the idCounts + * map to the 'idcounts' file. */ public int getUniqueDataId(String s) { Short oshort = (Short) this.idCounts.get(s); @@ -227,4 +111,125 @@ public class MapStorage { return oshort.shortValue(); } } + + /** + * + Loads an existing MapDataBase corresponding to the given String id from + * disk, instantiating the given Class, or returns null if none such file + * exists. args: Class to instantiate, String dataid + */ + public WorldSavedData loadData(Class oclass, String s) { + WorldSavedData worldsaveddata = (WorldSavedData) this.loadedDataMap.get(s); + if (worldsaveddata != null) { + return worldsaveddata; + } else { + if (this.saveHandler != null) { + try { + VFile2 file1 = this.saveHandler.getMapFileFromName(s); + if (file1 != null && file1.exists()) { + try { + worldsaveddata = (WorldSavedData) storageProviders.get(oclass).createInstance(s); + } catch (Exception exception) { + throw new RuntimeException("Failed to instantiate " + oclass.toString(), exception); + } + try (InputStream is = file1.getInputStream()) { + NBTTagCompound nbttagcompound = CompressedStreamTools.readCompressed(is); + worldsaveddata.readFromNBT(nbttagcompound.getCompoundTag("data")); + } + } + } catch (Exception exception1) { + EagRuntime.debugPrintStackTrace(exception1); + } + } + + if (worldsaveddata != null) { + this.loadedDataMap.put(s, worldsaveddata); + this.loadedDataList.add(worldsaveddata); + } + + return worldsaveddata; + } + } + + /** + * + Loads the idCounts Map from the 'idcounts' file. + */ + private void loadIdCounts() { + try { + this.idCounts.clear(); + if (this.saveHandler == null) { + return; + } + + VFile2 file1 = this.saveHandler.getMapFileFromName("idcounts"); + if (file1 != null && file1.exists()) { + NBTTagCompound nbttagcompound; + try (DataInputStream datainputstream = new DataInputStream(file1.getInputStream())) { + nbttagcompound = CompressedStreamTools.read(datainputstream); + } + + for (String s : nbttagcompound.getKeySet()) { + NBTBase nbtbase = nbttagcompound.getTag(s); + if (nbtbase instanceof NBTTagShort) { + NBTTagShort nbttagshort = (NBTTagShort) nbtbase; + short short1 = nbttagshort.getShort(); + this.idCounts.put(s, Short.valueOf(short1)); + } + } + } + } catch (Exception exception) { + EagRuntime.debugPrintStackTrace(exception); + } + + } + + /** + * + Saves all dirty loaded MapDataBases to disk. + */ + public void saveAllData() { + for (int i = 0; i < this.loadedDataList.size(); ++i) { + WorldSavedData worldsaveddata = (WorldSavedData) this.loadedDataList.get(i); + if (worldsaveddata.isDirty()) { + this.saveData(worldsaveddata); + worldsaveddata.setDirty(false); + } + } + + } + + /** + * + Saves the given MapDataBase to disk. + */ + private void saveData(WorldSavedData parWorldSavedData) { + if (this.saveHandler != null) { + try { + VFile2 file1 = this.saveHandler.getMapFileFromName(parWorldSavedData.mapName); + if (file1 != null) { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + parWorldSavedData.writeToNBT(nbttagcompound); + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + nbttagcompound1.setTag("data", nbttagcompound); + + try (OutputStream fileoutputstream = file1.getOutputStream()) { + CompressedStreamTools.writeCompressed(nbttagcompound1, fileoutputstream); + } + } + } catch (Exception exception) { + EagRuntime.debugPrintStackTrace(exception); + } + + } + } + + /** + * + Assigns the given String id to the given MapDataBase, removing any existing + * ones of the same id. + */ + public void setData(String s, WorldSavedData worldsaveddata) { + if (this.loadedDataMap.containsKey(s)) { + this.loadedDataList.remove(this.loadedDataMap.remove(s)); + } + + this.loadedDataMap.put(s, worldsaveddata); + this.loadedDataList.add(worldsaveddata); + } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/SaveDataMemoryStorage.java b/src/game/java/net/minecraft/world/storage/SaveDataMemoryStorage.java index a48758f5..0bc5b7a3 100644 --- a/src/game/java/net/minecraft/world/storage/SaveDataMemoryStorage.java +++ b/src/game/java/net/minecraft/world/storage/SaveDataMemoryStorage.java @@ -2,22 +2,25 @@ package net.minecraft.world.storage; import net.minecraft.world.WorldSavedData; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,35 +30,34 @@ public class SaveDataMemoryStorage extends MapStorage { super((ISaveHandler) null); } - /**+ - * Loads an existing MapDataBase corresponding to the given - * String id from disk, instantiating the given Class, or - * returns null if none such file exists. args: Class to - * instantiate, String dataid + /** + * + Returns an unique new data id for the given prefix and saves the idCounts + * map to the 'idcounts' file. + */ + public int getUniqueDataId(String key) { + return 0; + } + + /** + * + Loads an existing MapDataBase corresponding to the given String id from + * disk, instantiating the given Class, or returns null if none such file + * exists. args: Class to instantiate, String dataid */ public WorldSavedData loadData(Class clazz, String dataIdentifier) { return (WorldSavedData) this.loadedDataMap.get(dataIdentifier); } - /**+ - * Assigns the given String id to the given MapDataBase, - * removing any existing ones of the same id. - */ - public void setData(String dataIdentifier, WorldSavedData data) { - this.loadedDataMap.put(dataIdentifier, data); - } - - /**+ - * Saves all dirty loaded MapDataBases to disk. + /** + * + Saves all dirty loaded MapDataBases to disk. */ public void saveAllData() { } - /**+ - * Returns an unique new data id for the given prefix and saves - * the idCounts map to the 'idcounts' file. + /** + * + Assigns the given String id to the given MapDataBase, removing any existing + * ones of the same id. */ - public int getUniqueDataId(String key) { - return 0; + public void setData(String dataIdentifier, WorldSavedData data) { + this.loadedDataMap.put(dataIdentifier, data); } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/SaveFormatComparator.java b/src/game/java/net/minecraft/world/storage/SaveFormatComparator.java index 58822c2b..e7635b49 100644 --- a/src/game/java/net/minecraft/world/storage/SaveFormatComparator.java +++ b/src/game/java/net/minecraft/world/storage/SaveFormatComparator.java @@ -3,22 +3,25 @@ package net.minecraft.world.storage; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSettings; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,53 +51,55 @@ public class SaveFormatComparator implements Comparable { this.levelDat = levelDat; } - /**+ - * return the file name - */ - public String getFileName() { - return this.fileName; - } - - /**+ - * return the display name of the save - */ - public String getDisplayName() { - return this.displayName; - } - - public long getSizeOnDisk() { - return this.sizeOnDisk; - } - - public boolean requiresConversion() { - return this.requiresConversion; - } - - public long getLastTimePlayed() { - return this.lastTimePlayed; - } - public int compareTo(SaveFormatComparator saveformatcomparator) { return this.lastTimePlayed < saveformatcomparator.lastTimePlayed ? 1 : (this.lastTimePlayed > saveformatcomparator.lastTimePlayed ? -1 : this.fileName.compareTo(saveformatcomparator.fileName)); } - /**+ - * Gets the EnumGameType. + /** + * + + * + * @return {@code true} if cheats are enabled for this world + */ + public boolean getCheatsEnabled() { + return this.cheatsEnabled; + } + + /** + * + return the display name of the save + */ + public String getDisplayName() { + return this.displayName; + } + + /** + * + Gets the EnumGameType. */ public WorldSettings.GameType getEnumGameType() { return this.theEnumGameType; } + /** + * + return the file name + */ + public String getFileName() { + return this.fileName; + } + + public long getLastTimePlayed() { + return this.lastTimePlayed; + } + + public long getSizeOnDisk() { + return this.sizeOnDisk; + } + public boolean isHardcoreModeEnabled() { return this.hardcore; } - /**+ - * @return {@code true} if cheats are enabled for this world - */ - public boolean getCheatsEnabled() { - return this.cheatsEnabled; + public boolean requiresConversion() { + return this.requiresConversion; } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/SaveFormatOld.java b/src/game/java/net/minecraft/world/storage/SaveFormatOld.java index b4514569..8fb9130b 100644 --- a/src/game/java/net/minecraft/world/storage/SaveFormatOld.java +++ b/src/game/java/net/minecraft/world/storage/SaveFormatOld.java @@ -1,50 +1,139 @@ package net.minecraft.world.storage; -import com.google.common.collect.Lists; - import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; -import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerIntegratedServerWorker; -import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; -import net.minecraft.util.IProgressUpdate; + +import com.google.common.collect.Lists; + import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerIntegratedServerWorker; +import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.util.IProgressUpdate; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SaveFormatOld implements ISaveFormat { private static final Logger logger = LogManager.getLogger(); + + /** + * + + * + * @args: Takes one argument - the list of files and directories to + * delete. @desc: Deletes the files and directory listed in the list + * recursively. + */ + protected static boolean deleteFiles(List files, String progressString) { + long totalSize = 0l; + long lastUpdate = 0; + for (int i = 0, l = files.size(); i < l; ++i) { + VFile2 file1 = files.get(i); + if (progressString != null) { + totalSize += file1.length(); + if (totalSize - lastUpdate > 10000) { + lastUpdate = totalSize; + EaglerIntegratedServerWorker.sendProgress(progressString, totalSize); + } + } + if (!file1.delete()) { + logger.warn("Couldn\'t delete file " + file1); + return false; + } + } + + return true; + } + protected final VFile2 savesDirectory; public SaveFormatOld(VFile2 parFile) { this.savesDirectory = parFile; } - /**+ - * Returns the name of the save format. + /** + * + Return whether the given world can be loaded. + */ + public boolean canLoadWorld(String parString1) { + return (WorldsDB.newVFile(this.savesDirectory, parString1, "level.dat")).exists() + || (WorldsDB.newVFile(this.savesDirectory, parString1, "level.dat_old")).exists(); + } + + /** + * + converts the map to mcRegion + */ + public boolean convertMapFormat(String var1, IProgressUpdate var2) { + return false; + } + + /** + * + + * + * @args: Takes one argument - the name of the directory of the world to + * delete. @desc: Delete the world by deleting the associated directory + * recursively. + */ + public boolean deleteWorldDirectory(String parString1) { + VFile2 file1 = WorldsDB.newVFile(this.savesDirectory, parString1); + logger.info("Deleting level " + parString1); + + for (int i = 1; i <= 5; ++i) { + logger.info("Attempt " + i + "..."); + if (deleteFiles(file1.listFiles(true), "singleplayer.busy.deleting")) { + return true; + } + + logger.warn("Unsuccessful in deleting contents."); + if (i < 5) { + try { + Thread.sleep(500L); + } catch (InterruptedException var5) { + ; + } + } + } + + return false; + } + + public void flushCache() { + } + + public boolean func_154334_a(String var1) { + return false; + } + + public boolean func_154335_d(String parString1) { + return !canLoadWorld(parString1); + } + + /** + * + Returns the name of the save format. */ public String getName() { return "Old Format"; @@ -66,11 +155,15 @@ public class SaveFormatOld implements ISaveFormat { return arraylist; } - public void flushCache() { + /** + * + Returns back a loader for the specified save directory + */ + public ISaveHandler getSaveLoader(String s, boolean flag) { + return new SaveHandler(this.savesDirectory, s); } - /**+ - * Returns the world's WorldInfo object + /** + * + Returns the world's WorldInfo object */ public WorldInfo getWorldInfo(String saveName) { VFile2 file1 = WorldsDB.newVFile(this.savesDirectory, saveName); @@ -109,9 +202,16 @@ public class SaveFormatOld implements ISaveFormat { } } - /**+ - * Renames the world by storing the new name in level.dat. It - * does *not* rename the directory containing the world data. + /** + * + gets if the map is old chunk saving (true) or McRegion (false) + */ + public boolean isOldMapFormat(String var1) { + return false; + } + + /** + * + Renames the world by storing the new name in level.dat. It does *not* + * rename the directory containing the world data. */ public boolean renameWorld(String dirName, String newName) { VFile2 file1 = WorldsDB.newVFile(this.savesDirectory, dirName); @@ -138,96 +238,4 @@ public class SaveFormatOld implements ISaveFormat { } return false; } - - public boolean func_154335_d(String parString1) { - return !canLoadWorld(parString1); - } - - /**+ - * @args: Takes one argument - the name of the directory of the - * world to delete. @desc: Delete the world by deleting the - * associated directory recursively. - */ - public boolean deleteWorldDirectory(String parString1) { - VFile2 file1 = WorldsDB.newVFile(this.savesDirectory, parString1); - logger.info("Deleting level " + parString1); - - for (int i = 1; i <= 5; ++i) { - logger.info("Attempt " + i + "..."); - if (deleteFiles(file1.listFiles(true), "singleplayer.busy.deleting")) { - return true; - } - - logger.warn("Unsuccessful in deleting contents."); - if (i < 5) { - try { - Thread.sleep(500L); - } catch (InterruptedException var5) { - ; - } - } - } - - return false; - } - - /**+ - * @args: Takes one argument - the list of files and directories - * to delete. @desc: Deletes the files and directory listed in - * the list recursively. - */ - protected static boolean deleteFiles(List files, String progressString) { - long totalSize = 0l; - long lastUpdate = 0; - for (int i = 0, l = files.size(); i < l; ++i) { - VFile2 file1 = files.get(i); - if (progressString != null) { - totalSize += file1.length(); - if (totalSize - lastUpdate > 10000) { - lastUpdate = totalSize; - EaglerIntegratedServerWorker.sendProgress(progressString, totalSize); - } - } - if (!file1.delete()) { - logger.warn("Couldn\'t delete file " + file1); - return false; - } - } - - return true; - } - - /**+ - * Returns back a loader for the specified save directory - */ - public ISaveHandler getSaveLoader(String s, boolean flag) { - return new SaveHandler(this.savesDirectory, s); - } - - public boolean func_154334_a(String var1) { - return false; - } - - /**+ - * gets if the map is old chunk saving (true) or McRegion - * (false) - */ - public boolean isOldMapFormat(String var1) { - return false; - } - - /**+ - * converts the map to mcRegion - */ - public boolean convertMapFormat(String var1, IProgressUpdate var2) { - return false; - } - - /**+ - * Return whether the given world can be loaded. - */ - public boolean canLoadWorld(String parString1) { - return (WorldsDB.newVFile(this.savesDirectory, parString1, "level.dat")).exists() - || (WorldsDB.newVFile(this.savesDirectory, parString1, "level.dat_old")).exists(); - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/SaveHandler.java b/src/game/java/net/minecraft/world/storage/SaveHandler.java index c8657cf9..ba522f76 100644 --- a/src/game/java/net/minecraft/world/storage/SaveHandler.java +++ b/src/game/java/net/minecraft/world/storage/SaveHandler.java @@ -4,6 +4,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.List; +import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; @@ -11,27 +15,26 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.MinecraftException; import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; -import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,9 +44,9 @@ public class SaveHandler implements ISaveHandler, IPlayerFileData { private final VFile2 worldDirectory; private final VFile2 playersDirectory; private final VFile2 mapDataDir; - /**+ - * The time in milliseconds when this field was initialized. - * Stored in the session lock file. + /** + * + The time in milliseconds when this field was initialized. Stored in the + * session lock file. */ private final long initializationTime = MinecraftServer.getCurrentTimeMillis(); private final String saveDirectoryName; @@ -56,30 +59,68 @@ public class SaveHandler implements ISaveHandler, IPlayerFileData { } - /**+ - * Gets the File object corresponding to the base directory of - * this world. - */ - public VFile2 getWorldDirectory() { - return this.worldDirectory; - } - - /**+ - * Checks the session lock to prevent save collisions + /** + * + Checks the session lock to prevent save collisions */ public void checkSessionLock() throws MinecraftException { } - /**+ - * initializes and returns the chunk loader for the specified - * world provider + /** + * + Called to flush all changes to disk, waiting for them to complete. + */ + public void flush() { + } + + /** + * + Returns an array of usernames for which player.dat exists for. + */ + public String[] getAvailablePlayerDat() { + List astring = this.playersDirectory.listFilenames(false); + + for (int i = 0, l = astring.size(); i < l; ++i) { + String str = astring.get(i); + if (str.endsWith(".dat")) { + astring.set(i, str.substring(0, str.length() - 4)); + } + } + + return astring.toArray(new String[astring.size()]); + } + + /** + * + initializes and returns the chunk loader for the specified world provider */ public IChunkLoader getChunkLoader(WorldProvider var1) { throw new RuntimeException("eagler"); } - /**+ - * Loads and returns the world info + /** + * + Gets the file location of the given map + */ + public VFile2 getMapFileFromName(String mapName) { + return WorldsDB.newVFile(this.mapDataDir, mapName + ".dat"); + } + + public IPlayerFileData getPlayerNBTManager() { + return this; + } + + /** + * + Gets the File object corresponding to the base directory of this world. + */ + public VFile2 getWorldDirectory() { + return this.worldDirectory; + } + + /** + * + Returns the name of the directory where world information is saved. + */ + public String getWorldDirectoryName() { + return this.saveDirectoryName; + } + + /** + * + Loads and returns the world info */ public WorldInfo loadWorldInfo() { VFile2 file1 = WorldsDB.newVFile(this.worldDirectory, "level.dat"); @@ -109,44 +150,33 @@ public class SaveHandler implements ISaveHandler, IPlayerFileData { return null; } - /**+ - * Saves the given World Info with the given NBTTagCompound as - * the Player. + /** + * + Reads the player data from disk into the specified PlayerEntityMP. */ - public void saveWorldInfoWithPlayer(WorldInfo worldinfo, NBTTagCompound nbttagcompound) { - NBTTagCompound nbttagcompound1 = worldinfo.cloneNBTCompound(nbttagcompound); - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); - nbttagcompound2.setTag("Data", nbttagcompound1); + public NBTTagCompound readPlayerData(EntityPlayer player) { + NBTTagCompound nbttagcompound = null; try { - VFile2 file1 = WorldsDB.newVFile(this.worldDirectory, "level.dat_new"); - VFile2 file2 = WorldsDB.newVFile(this.worldDirectory, "level.dat_old"); - VFile2 file3 = WorldsDB.newVFile(this.worldDirectory, "level.dat"); - try (OutputStream os = file1.getOutputStream()) { - CompressedStreamTools.writeCompressed(nbttagcompound2, os); - } - if (file2.exists()) { - file2.delete(); - } - - file3.renameTo(file2); - if (file3.exists()) { - file3.delete(); - } - - file1.renameTo(file3); + VFile2 file1 = WorldsDB.newVFile(this.playersDirectory, player.getName().toLowerCase() + ".dat"); if (file1.exists()) { - file1.delete(); + try (InputStream is = file1.getInputStream()) { + nbttagcompound = CompressedStreamTools.readCompressed(is); + } } - } catch (Exception exception) { - logger.error("Failed to write level.dat!"); - logger.error(exception); + } catch (Exception var4) { + logger.error("Failed to load player data for {}", player.getName()); + logger.error(var4); } + if (nbttagcompound != null) { + player.readFromNBT(nbttagcompound); + } + + return nbttagcompound; } - /**+ - * used to update level.dat from old format to MCRegion format + /** + * + used to update level.dat from old format to MCRegion format */ public void saveWorldInfo(WorldInfo worldInformation) { NBTTagCompound nbttagcompound = worldInformation.getNBTTagCompound(); @@ -180,9 +210,43 @@ public class SaveHandler implements ISaveHandler, IPlayerFileData { } - /**+ - * Writes the player data to disk from the specified - * PlayerEntityMP. + /** + * + Saves the given World Info with the given NBTTagCompound as the Player. + */ + public void saveWorldInfoWithPlayer(WorldInfo worldinfo, NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = worldinfo.cloneNBTCompound(nbttagcompound); + NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + nbttagcompound2.setTag("Data", nbttagcompound1); + + try { + VFile2 file1 = WorldsDB.newVFile(this.worldDirectory, "level.dat_new"); + VFile2 file2 = WorldsDB.newVFile(this.worldDirectory, "level.dat_old"); + VFile2 file3 = WorldsDB.newVFile(this.worldDirectory, "level.dat"); + try (OutputStream os = file1.getOutputStream()) { + CompressedStreamTools.writeCompressed(nbttagcompound2, os); + } + if (file2.exists()) { + file2.delete(); + } + + file3.renameTo(file2); + if (file3.exists()) { + file3.delete(); + } + + file1.renameTo(file3); + if (file1.exists()) { + file1.delete(); + } + } catch (Exception exception) { + logger.error("Failed to write level.dat!"); + logger.error(exception); + } + + } + + /** + * + Writes the player data to disk from the specified PlayerEntityMP. */ public void writePlayerData(EntityPlayer player) { try { @@ -205,73 +269,4 @@ public class SaveHandler implements ISaveHandler, IPlayerFileData { } } - - /**+ - * Reads the player data from disk into the specified - * PlayerEntityMP. - */ - public NBTTagCompound readPlayerData(EntityPlayer player) { - NBTTagCompound nbttagcompound = null; - - try { - VFile2 file1 = WorldsDB.newVFile(this.playersDirectory, player.getName().toLowerCase() + ".dat"); - if (file1.exists()) { - try (InputStream is = file1.getInputStream()) { - nbttagcompound = CompressedStreamTools.readCompressed(is); - } - } - } catch (Exception var4) { - logger.error("Failed to load player data for {}", player.getName()); - logger.error(var4); - } - - if (nbttagcompound != null) { - player.readFromNBT(nbttagcompound); - } - - return nbttagcompound; - } - - public IPlayerFileData getPlayerNBTManager() { - return this; - } - - /**+ - * Returns an array of usernames for which player.dat exists - * for. - */ - public String[] getAvailablePlayerDat() { - List astring = this.playersDirectory.listFilenames(false); - - for (int i = 0, l = astring.size(); i < l; ++i) { - String str = astring.get(i); - if (str.endsWith(".dat")) { - astring.set(i, str.substring(0, str.length() - 4)); - } - } - - return astring.toArray(new String[astring.size()]); - } - - /**+ - * Called to flush all changes to disk, waiting for them to - * complete. - */ - public void flush() { - } - - /**+ - * Gets the file location of the given map - */ - public VFile2 getMapFileFromName(String mapName) { - return WorldsDB.newVFile(this.mapDataDir, mapName + ".dat"); - } - - /**+ - * Returns the name of the directory where world information is - * saved. - */ - public String getWorldDirectoryName() { - return this.saveDirectoryName; - } } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/SaveHandlerMP.java b/src/game/java/net/minecraft/world/storage/SaveHandlerMP.java index 959c2da6..bd787a7a 100644 --- a/src/game/java/net/minecraft/world/storage/SaveHandlerMP.java +++ b/src/game/java/net/minecraft/world/storage/SaveHandlerMP.java @@ -6,96 +6,94 @@ import net.minecraft.world.MinecraftException; import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SaveHandlerMP implements ISaveHandler { - /**+ - * Loads and returns the world info - */ - public WorldInfo loadWorldInfo() { - return null; - } - - /**+ - * Checks the session lock to prevent save collisions + /** + * + Checks the session lock to prevent save collisions */ public void checkSessionLock() throws MinecraftException { } - /**+ - * Saves the given World Info with the given NBTTagCompound as - * the Player. - */ - public void saveWorldInfoWithPlayer(WorldInfo var1, NBTTagCompound var2) { - } - - /**+ - * used to update level.dat from old format to MCRegion format - */ - public void saveWorldInfo(WorldInfo var1) { - } - - public IPlayerFileData getPlayerNBTManager() { - return null; - } - - /**+ - * Called to flush all changes to disk, waiting for them to - * complete. + /** + * + Called to flush all changes to disk, waiting for them to complete. */ public void flush() { } - /**+ - * Returns the name of the directory where world information is - * saved. - */ - public String getWorldDirectoryName() { - return "none"; - } - @Override - /**+ - * initializes and returns the chunk loader for the specified - * world provider + /** + * + initializes and returns the chunk loader for the specified world provider */ public IChunkLoader getChunkLoader(WorldProvider var1) { return null; } @Override - /**+ - * Gets the File object corresponding to the base directory of - * this world. - */ - public VFile2 getWorldDirectory() { - return null; - } - - @Override - /**+ - * Gets the file location of the given map + /** + * + Gets the file location of the given map */ public VFile2 getMapFileFromName(String var1) { return null; } + public IPlayerFileData getPlayerNBTManager() { + return null; + } + + @Override + /** + * + Gets the File object corresponding to the base directory of this world. + */ + public VFile2 getWorldDirectory() { + return null; + } + + /** + * + Returns the name of the directory where world information is saved. + */ + public String getWorldDirectoryName() { + return "none"; + } + + /** + * + Loads and returns the world info + */ + public WorldInfo loadWorldInfo() { + return null; + } + + /** + * + used to update level.dat from old format to MCRegion format + */ + public void saveWorldInfo(WorldInfo var1) { + } + + /** + * + Saves the given World Info with the given NBTTagCompound as the Player. + */ + public void saveWorldInfoWithPlayer(WorldInfo var1, NBTTagCompound var2) { + } + } \ No newline at end of file diff --git a/src/game/java/net/minecraft/world/storage/WorldInfo.java b/src/game/java/net/minecraft/world/storage/WorldInfo.java index 5a02117b..e1549207 100644 --- a/src/game/java/net/minecraft/world/storage/WorldInfo.java +++ b/src/game/java/net/minecraft/world/storage/WorldInfo.java @@ -1,6 +1,8 @@ package net.minecraft.world.storage; import java.util.concurrent.Callable; + +import net.lax1dude.eaglercraft.v1_8.HString; import net.minecraft.crash.CrashReportCategory; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.BlockPos; @@ -9,30 +11,39 @@ import net.minecraft.world.GameRules; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; -import net.lax1dude.eaglercraft.v1_8.HString; - -/**+ - * This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source code. +/** + * + This portion of EaglercraftX contains deobfuscated Minecraft 1.8 source + * code. * - * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" - * Mod Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team + * Minecraft 1.8.8 bytecode is (c) 2015 Mojang AB. "Do not distribute!" Mod + * Coder Pack v9.18 deobfuscation configs are (c) Copyright by the MCP Team * - * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. + * EaglercraftX 1.8 patch files (c) 2022-2024 lax1dude, ayunami2000. All Rights + * Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldInfo { public static final EnumDifficulty DEFAULT_DIFFICULTY = EnumDifficulty.NORMAL; + public static final int eaglerVersionCurrent = 1; + + public static void initEaglerVersion(NBTTagCompound compound) { + if (!compound.hasKey("eaglerVersionSerial", 99)) { + compound.setInteger("eaglerVersionSerial", eaglerVersionCurrent); + } + } + private long randomSeed; private WorldType terrainType = WorldType.DEFAULT; private String generatorOptions = ""; @@ -67,10 +78,10 @@ public class WorldInfo { private double borderSafeZone = 5.0D; private double borderDamagePerBlock = 0.2D; private int borderWarningDistance = 5; + private int borderWarningTime = 15; private GameRules theGameRules = new GameRules(); - public static final int eaglerVersionCurrent = 1; private int eaglerVersion = eaglerVersionCurrent; protected WorldInfo() { @@ -192,23 +203,6 @@ public class WorldInfo { this.eaglerVersion = nbt.getInteger("eaglerVersionSerial"); } - public WorldInfo(WorldSettings settings, String name) { - this.populateFromWorldSettings(settings); - this.levelName = name; - this.difficulty = DEFAULT_DIFFICULTY; - this.initialized = false; - } - - public void populateFromWorldSettings(WorldSettings settings) { - this.randomSeed = settings.getSeed(); - this.theGameType = settings.getGameType(); - this.mapFeaturesEnabled = settings.isMapFeaturesEnabled(); - this.hardcore = settings.getHardcoreEnabled(); - this.terrainType = settings.getTerrainType(); - this.generatorOptions = settings.getWorldName(); - this.allowCommands = settings.areCommandsAllowed(); - } - public WorldInfo(WorldInfo worldInformation) { this.randomSeed = worldInformation.randomSeed; this.terrainType = worldInformation.terrainType; @@ -247,491 +241,15 @@ public class WorldInfo { this.borderWarningDistance = worldInformation.borderWarningDistance; } - /**+ - * Gets the NBTTagCompound for the worldInfo - */ - public NBTTagCompound getNBTTagCompound() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - this.updateTagCompound(nbttagcompound, this.playerTag); - return nbttagcompound; + public WorldInfo(WorldSettings settings, String name) { + this.populateFromWorldSettings(settings); + this.levelName = name; + this.difficulty = DEFAULT_DIFFICULTY; + this.initialized = false; } - /**+ - * Creates a new NBTTagCompound for the world, with the given - * NBTTag as the "Player" - */ - public NBTTagCompound cloneNBTCompound(NBTTagCompound nbttagcompound) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - this.updateTagCompound(nbttagcompound1, nbttagcompound); - return nbttagcompound1; - } - - private void updateTagCompound(NBTTagCompound nbt, NBTTagCompound playerNbt) { - nbt.setLong("RandomSeed", this.randomSeed); - nbt.setString("generatorName", this.terrainType.getWorldTypeName()); - nbt.setInteger("generatorVersion", this.terrainType.getGeneratorVersion()); - nbt.setString("generatorOptions", this.generatorOptions); - nbt.setInteger("GameType", this.theGameType.getID()); - nbt.setBoolean("MapFeatures", this.mapFeaturesEnabled); - nbt.setInteger("SpawnX", this.spawnX); - nbt.setInteger("SpawnY", this.spawnY); - nbt.setInteger("SpawnZ", this.spawnZ); - nbt.setLong("Time", this.totalTime); - nbt.setLong("DayTime", this.worldTime); - nbt.setLong("SizeOnDisk", this.sizeOnDisk); - nbt.setLong("LastPlayed", System.currentTimeMillis()); - nbt.setString("LevelName", this.levelName); - nbt.setInteger("version", this.saveVersion); - nbt.setInteger("clearWeatherTime", this.cleanWeatherTime); - nbt.setInteger("rainTime", this.rainTime); - nbt.setBoolean("raining", this.raining); - nbt.setInteger("thunderTime", this.thunderTime); - nbt.setBoolean("thundering", this.thundering); - nbt.setBoolean("hardcore", this.hardcore); - nbt.setBoolean("allowCommands", this.allowCommands); - nbt.setBoolean("initialized", this.initialized); - nbt.setDouble("BorderCenterX", this.borderCenterX); - nbt.setDouble("BorderCenterZ", this.borderCenterZ); - nbt.setDouble("BorderSize", this.borderSize); - nbt.setLong("BorderSizeLerpTime", this.borderSizeLerpTime); - nbt.setDouble("BorderSafeZone", this.borderSafeZone); - nbt.setDouble("BorderDamagePerBlock", this.borderDamagePerBlock); - nbt.setDouble("BorderSizeLerpTarget", this.borderSizeLerpTarget); - nbt.setDouble("BorderWarningBlocks", (double) this.borderWarningDistance); - nbt.setDouble("BorderWarningTime", (double) this.borderWarningTime); - nbt.setInteger("eaglerVersionSerial", this.eaglerVersion); - if (this.difficulty != null) { - nbt.setByte("Difficulty", (byte) this.difficulty.getDifficultyId()); - } - - nbt.setBoolean("DifficultyLocked", this.difficultyLocked); - nbt.setTag("GameRules", this.theGameRules.writeToNBT()); - if (playerNbt != null) { - nbt.setTag("Player", playerNbt); - } - - } - - /**+ - * Returns the seed of current world. - */ - public long getSeed() { - return this.randomSeed; - } - - /**+ - * Returns the x spawn position - */ - public int getSpawnX() { - return this.spawnX; - } - - /**+ - * Return the Y axis spawning point of the player. - */ - public int getSpawnY() { - return this.spawnY; - } - - /**+ - * Returns the z spawn position - */ - public int getSpawnZ() { - return this.spawnZ; - } - - public long getWorldTotalTime() { - return this.totalTime; - } - - /**+ - * Get current world time - */ - public long getWorldTime() { - return this.worldTime; - } - - public long getSizeOnDisk() { - return this.sizeOnDisk; - } - - /**+ - * Returns the player's NBTTagCompound to be loaded - */ - public NBTTagCompound getPlayerNBTTagCompound() { - return this.playerTag; - } - - /**+ - * Set the x spawn position to the passed in value - */ - public void setSpawnX(int i) { - this.spawnX = i; - } - - /**+ - * Sets the y spawn position - */ - public void setSpawnY(int i) { - this.spawnY = i; - } - - /**+ - * Set the z spawn position to the passed in value - */ - public void setSpawnZ(int i) { - this.spawnZ = i; - } - - public void setWorldTotalTime(long i) { - this.totalTime = i; - } - - /**+ - * Set current world time - */ - public void setWorldTime(long i) { - this.worldTime = i; - } - - public void setSpawn(BlockPos blockpos) { - this.spawnX = blockpos.getX(); - this.spawnY = blockpos.getY(); - this.spawnZ = blockpos.getZ(); - } - - /**+ - * Get current world name - */ - public String getWorldName() { - return this.levelName; - } - - public void setWorldName(String s) { - this.levelName = s; - } - - /**+ - * Returns the save version of this world - */ - public int getSaveVersion() { - return this.saveVersion; - } - - /**+ - * Sets the save version of the world - */ - public void setSaveVersion(int i) { - this.saveVersion = i; - } - - /**+ - * Return the last time the player was in this world. - */ - public long getLastTimePlayed() { - return this.lastTimePlayed; - } - - public int getCleanWeatherTime() { - return this.cleanWeatherTime; - } - - public void setCleanWeatherTime(int cleanWeatherTimeIn) { - this.cleanWeatherTime = cleanWeatherTimeIn; - } - - /**+ - * Returns true if it is thundering, false otherwise. - */ - public boolean isThundering() { - return this.thundering; - } - - /**+ - * Sets whether it is thundering or not. - */ - public void setThundering(boolean flag) { - this.thundering = flag; - } - - /**+ - * Returns the number of ticks until next thunderbolt. - */ - public int getThunderTime() { - return this.thunderTime; - } - - /**+ - * Defines the number of ticks until next thunderbolt. - */ - public void setThunderTime(int i) { - this.thunderTime = i; - } - - /**+ - * Returns true if it is raining, false otherwise. - */ - public boolean isRaining() { - return this.raining; - } - - /**+ - * Sets whether it is raining or not. - */ - public void setRaining(boolean flag) { - this.raining = flag; - } - - /**+ - * Return the number of ticks until rain. - */ - public int getRainTime() { - return this.rainTime; - } - - /**+ - * Sets the number of ticks until rain. - */ - public void setRainTime(int i) { - this.rainTime = i; - } - - /**+ - * Gets the GameType. - */ - public WorldSettings.GameType getGameType() { - return this.theGameType; - } - - /**+ - * Get whether the map features (e.g. strongholds) generation is - * enabled or disabled. - */ - public boolean isMapFeaturesEnabled() { - return this.mapFeaturesEnabled; - } - - public void setMapFeaturesEnabled(boolean enabled) { - this.mapFeaturesEnabled = enabled; - } - - /**+ - * Sets the GameType. - */ - public void setGameType(WorldSettings.GameType type) { - this.theGameType = type; - } - - /**+ - * Returns true if hardcore mode is enabled, otherwise false - */ - public boolean isHardcoreModeEnabled() { - return this.hardcore; - } - - public void setHardcore(boolean hardcoreIn) { - this.hardcore = hardcoreIn; - } - - public WorldType getTerrainType() { - return this.terrainType; - } - - public void setTerrainType(WorldType worldtype) { - this.terrainType = worldtype; - } - - public String getGeneratorOptions() { - return this.generatorOptions; - } - - /**+ - * Returns true if commands are allowed on this World. - */ - public boolean areCommandsAllowed() { - return this.allowCommands; - } - - public void setAllowCommands(boolean flag) { - this.allowCommands = flag; - } - - /**+ - * Returns true if the World is initialized. - */ - public boolean isInitialized() { - return this.initialized; - } - - /**+ - * Sets the initialization status of the World. - */ - public void setServerInitialized(boolean flag) { - this.initialized = flag; - } - - /**+ - * Gets the GameRules class Instance. - */ - public GameRules getGameRulesInstance() { - return this.theGameRules; - } - - /**+ - * Returns the border center X position - */ - public double getBorderCenterX() { - return this.borderCenterX; - } - - /**+ - * Returns the border center Z position - */ - public double getBorderCenterZ() { - return this.borderCenterZ; - } - - public double getBorderSize() { - return this.borderSize; - } - - /**+ - * Sets the border size - */ - public void setBorderSize(double size) { - this.borderSize = size; - } - - /**+ - * Returns the border lerp time - */ - public long getBorderLerpTime() { - return this.borderSizeLerpTime; - } - - /**+ - * Sets the border lerp time - */ - public void setBorderLerpTime(long time) { - this.borderSizeLerpTime = time; - } - - /**+ - * Returns the border lerp target - */ - public double getBorderLerpTarget() { - return this.borderSizeLerpTarget; - } - - /**+ - * Sets the border lerp target - */ - public void setBorderLerpTarget(double lerpSize) { - this.borderSizeLerpTarget = lerpSize; - } - - /**+ - * Returns the border center Z position - */ - public void getBorderCenterZ(double posZ) { - this.borderCenterZ = posZ; - } - - /**+ - * Returns the border center X position - */ - public void getBorderCenterX(double posX) { - this.borderCenterX = posX; - } - - /**+ - * Returns the border safe zone - */ - public double getBorderSafeZone() { - return this.borderSafeZone; - } - - /**+ - * Sets the border safe zone - */ - public void setBorderSafeZone(double amount) { - this.borderSafeZone = amount; - } - - /**+ - * Returns the border damage per block - */ - public double getBorderDamagePerBlock() { - return this.borderDamagePerBlock; - } - - /**+ - * Sets the border damage per block - */ - public void setBorderDamagePerBlock(double damage) { - this.borderDamagePerBlock = damage; - } - - /**+ - * Returns the border warning distance - */ - public int getBorderWarningDistance() { - return this.borderWarningDistance; - } - - /**+ - * Returns the border warning time - */ - public int getBorderWarningTime() { - return this.borderWarningTime; - } - - /**+ - * Sets the border warning distance - */ - public void setBorderWarningDistance(int amountOfBlocks) { - this.borderWarningDistance = amountOfBlocks; - } - - /**+ - * Sets the border warning time - */ - public void setBorderWarningTime(int ticks) { - this.borderWarningTime = ticks; - } - - public EnumDifficulty getDifficulty() { - return this.difficulty; - } - - public void setDifficulty(EnumDifficulty enumdifficulty) { - this.difficulty = enumdifficulty; - } - - public boolean isDifficultyLocked() { - return this.difficultyLocked; - } - - public void setDifficultyLocked(boolean flag) { - this.difficultyLocked = flag; - } - - public int getEaglerVersion() { - return this.eaglerVersion; - } - - public boolean isOldEaglercraftRandom() { - return this.eaglerVersion == 0; - } - - public static void initEaglerVersion(NBTTagCompound compound) { - if (!compound.hasKey("eaglerVersionSerial", 99)) { - compound.setInteger("eaglerVersionSerial", eaglerVersionCurrent); - } - } - - /**+ - * Adds this WorldInfo instance to the crash report. + /** + * + Adds this WorldInfo instance to the crash report. */ public void addToCrashReport(CrashReportCategory category) { category.addCrashSectionCallable("Level seed", new Callable() { @@ -805,4 +323,491 @@ public class WorldInfo { } }); } + + /** + * + Returns true if commands are allowed on this World. + */ + public boolean areCommandsAllowed() { + return this.allowCommands; + } + + /** + * + Creates a new NBTTagCompound for the world, with the given NBTTag as the + * "Player" + */ + public NBTTagCompound cloneNBTCompound(NBTTagCompound nbttagcompound) { + NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + this.updateTagCompound(nbttagcompound1, nbttagcompound); + return nbttagcompound1; + } + + /** + * + Returns the border center X position + */ + public double getBorderCenterX() { + return this.borderCenterX; + } + + /** + * + Returns the border center X position + */ + public void getBorderCenterX(double posX) { + this.borderCenterX = posX; + } + + /** + * + Returns the border center Z position + */ + public double getBorderCenterZ() { + return this.borderCenterZ; + } + + /** + * + Returns the border center Z position + */ + public void getBorderCenterZ(double posZ) { + this.borderCenterZ = posZ; + } + + /** + * + Returns the border damage per block + */ + public double getBorderDamagePerBlock() { + return this.borderDamagePerBlock; + } + + /** + * + Returns the border lerp target + */ + public double getBorderLerpTarget() { + return this.borderSizeLerpTarget; + } + + /** + * + Returns the border lerp time + */ + public long getBorderLerpTime() { + return this.borderSizeLerpTime; + } + + /** + * + Returns the border safe zone + */ + public double getBorderSafeZone() { + return this.borderSafeZone; + } + + public double getBorderSize() { + return this.borderSize; + } + + /** + * + Returns the border warning distance + */ + public int getBorderWarningDistance() { + return this.borderWarningDistance; + } + + /** + * + Returns the border warning time + */ + public int getBorderWarningTime() { + return this.borderWarningTime; + } + + public int getCleanWeatherTime() { + return this.cleanWeatherTime; + } + + public EnumDifficulty getDifficulty() { + return this.difficulty; + } + + public int getEaglerVersion() { + return this.eaglerVersion; + } + + /** + * + Gets the GameRules class Instance. + */ + public GameRules getGameRulesInstance() { + return this.theGameRules; + } + + /** + * + Gets the GameType. + */ + public WorldSettings.GameType getGameType() { + return this.theGameType; + } + + public String getGeneratorOptions() { + return this.generatorOptions; + } + + /** + * + Return the last time the player was in this world. + */ + public long getLastTimePlayed() { + return this.lastTimePlayed; + } + + /** + * + Gets the NBTTagCompound for the worldInfo + */ + public NBTTagCompound getNBTTagCompound() { + NBTTagCompound nbttagcompound = new NBTTagCompound(); + this.updateTagCompound(nbttagcompound, this.playerTag); + return nbttagcompound; + } + + /** + * + Returns the player's NBTTagCompound to be loaded + */ + public NBTTagCompound getPlayerNBTTagCompound() { + return this.playerTag; + } + + /** + * + Return the number of ticks until rain. + */ + public int getRainTime() { + return this.rainTime; + } + + /** + * + Returns the save version of this world + */ + public int getSaveVersion() { + return this.saveVersion; + } + + /** + * + Returns the seed of current world. + */ + public long getSeed() { + return this.randomSeed; + } + + public long getSizeOnDisk() { + return this.sizeOnDisk; + } + + /** + * + Returns the x spawn position + */ + public int getSpawnX() { + return this.spawnX; + } + + /** + * + Return the Y axis spawning point of the player. + */ + public int getSpawnY() { + return this.spawnY; + } + + /** + * + Returns the z spawn position + */ + public int getSpawnZ() { + return this.spawnZ; + } + + public WorldType getTerrainType() { + return this.terrainType; + } + + /** + * + Returns the number of ticks until next thunderbolt. + */ + public int getThunderTime() { + return this.thunderTime; + } + + /** + * + Get current world name + */ + public String getWorldName() { + return this.levelName; + } + + /** + * + Get current world time + */ + public long getWorldTime() { + return this.worldTime; + } + + public long getWorldTotalTime() { + return this.totalTime; + } + + public boolean isDifficultyLocked() { + return this.difficultyLocked; + } + + /** + * + Returns true if hardcore mode is enabled, otherwise false + */ + public boolean isHardcoreModeEnabled() { + return this.hardcore; + } + + /** + * + Returns true if the World is initialized. + */ + public boolean isInitialized() { + return this.initialized; + } + + /** + * + Get whether the map features (e.g. strongholds) generation is enabled or + * disabled. + */ + public boolean isMapFeaturesEnabled() { + return this.mapFeaturesEnabled; + } + + public boolean isOldEaglercraftRandom() { + return this.eaglerVersion == 0; + } + + /** + * + Returns true if it is raining, false otherwise. + */ + public boolean isRaining() { + return this.raining; + } + + /** + * + Returns true if it is thundering, false otherwise. + */ + public boolean isThundering() { + return this.thundering; + } + + public void populateFromWorldSettings(WorldSettings settings) { + this.randomSeed = settings.getSeed(); + this.theGameType = settings.getGameType(); + this.mapFeaturesEnabled = settings.isMapFeaturesEnabled(); + this.hardcore = settings.getHardcoreEnabled(); + this.terrainType = settings.getTerrainType(); + this.generatorOptions = settings.getWorldName(); + this.allowCommands = settings.areCommandsAllowed(); + } + + public void setAllowCommands(boolean flag) { + this.allowCommands = flag; + } + + /** + * + Sets the border damage per block + */ + public void setBorderDamagePerBlock(double damage) { + this.borderDamagePerBlock = damage; + } + + /** + * + Sets the border lerp target + */ + public void setBorderLerpTarget(double lerpSize) { + this.borderSizeLerpTarget = lerpSize; + } + + /** + * + Sets the border lerp time + */ + public void setBorderLerpTime(long time) { + this.borderSizeLerpTime = time; + } + + /** + * + Sets the border safe zone + */ + public void setBorderSafeZone(double amount) { + this.borderSafeZone = amount; + } + + /** + * + Sets the border size + */ + public void setBorderSize(double size) { + this.borderSize = size; + } + + /** + * + Sets the border warning distance + */ + public void setBorderWarningDistance(int amountOfBlocks) { + this.borderWarningDistance = amountOfBlocks; + } + + /** + * + Sets the border warning time + */ + public void setBorderWarningTime(int ticks) { + this.borderWarningTime = ticks; + } + + public void setCleanWeatherTime(int cleanWeatherTimeIn) { + this.cleanWeatherTime = cleanWeatherTimeIn; + } + + public void setDifficulty(EnumDifficulty enumdifficulty) { + this.difficulty = enumdifficulty; + } + + public void setDifficultyLocked(boolean flag) { + this.difficultyLocked = flag; + } + + /** + * + Sets the GameType. + */ + public void setGameType(WorldSettings.GameType type) { + this.theGameType = type; + } + + public void setHardcore(boolean hardcoreIn) { + this.hardcore = hardcoreIn; + } + + public void setMapFeaturesEnabled(boolean enabled) { + this.mapFeaturesEnabled = enabled; + } + + /** + * + Sets whether it is raining or not. + */ + public void setRaining(boolean flag) { + this.raining = flag; + } + + /** + * + Sets the number of ticks until rain. + */ + public void setRainTime(int i) { + this.rainTime = i; + } + + /** + * + Sets the save version of the world + */ + public void setSaveVersion(int i) { + this.saveVersion = i; + } + + /** + * + Sets the initialization status of the World. + */ + public void setServerInitialized(boolean flag) { + this.initialized = flag; + } + + public void setSpawn(BlockPos blockpos) { + this.spawnX = blockpos.getX(); + this.spawnY = blockpos.getY(); + this.spawnZ = blockpos.getZ(); + } + + /** + * + Set the x spawn position to the passed in value + */ + public void setSpawnX(int i) { + this.spawnX = i; + } + + /** + * + Sets the y spawn position + */ + public void setSpawnY(int i) { + this.spawnY = i; + } + + /** + * + Set the z spawn position to the passed in value + */ + public void setSpawnZ(int i) { + this.spawnZ = i; + } + + public void setTerrainType(WorldType worldtype) { + this.terrainType = worldtype; + } + + /** + * + Sets whether it is thundering or not. + */ + public void setThundering(boolean flag) { + this.thundering = flag; + } + + /** + * + Defines the number of ticks until next thunderbolt. + */ + public void setThunderTime(int i) { + this.thunderTime = i; + } + + public void setWorldName(String s) { + this.levelName = s; + } + + /** + * + Set current world time + */ + public void setWorldTime(long i) { + this.worldTime = i; + } + + public void setWorldTotalTime(long i) { + this.totalTime = i; + } + + private void updateTagCompound(NBTTagCompound nbt, NBTTagCompound playerNbt) { + nbt.setLong("RandomSeed", this.randomSeed); + nbt.setString("generatorName", this.terrainType.getWorldTypeName()); + nbt.setInteger("generatorVersion", this.terrainType.getGeneratorVersion()); + nbt.setString("generatorOptions", this.generatorOptions); + nbt.setInteger("GameType", this.theGameType.getID()); + nbt.setBoolean("MapFeatures", this.mapFeaturesEnabled); + nbt.setInteger("SpawnX", this.spawnX); + nbt.setInteger("SpawnY", this.spawnY); + nbt.setInteger("SpawnZ", this.spawnZ); + nbt.setLong("Time", this.totalTime); + nbt.setLong("DayTime", this.worldTime); + nbt.setLong("SizeOnDisk", this.sizeOnDisk); + nbt.setLong("LastPlayed", System.currentTimeMillis()); + nbt.setString("LevelName", this.levelName); + nbt.setInteger("version", this.saveVersion); + nbt.setInteger("clearWeatherTime", this.cleanWeatherTime); + nbt.setInteger("rainTime", this.rainTime); + nbt.setBoolean("raining", this.raining); + nbt.setInteger("thunderTime", this.thunderTime); + nbt.setBoolean("thundering", this.thundering); + nbt.setBoolean("hardcore", this.hardcore); + nbt.setBoolean("allowCommands", this.allowCommands); + nbt.setBoolean("initialized", this.initialized); + nbt.setDouble("BorderCenterX", this.borderCenterX); + nbt.setDouble("BorderCenterZ", this.borderCenterZ); + nbt.setDouble("BorderSize", this.borderSize); + nbt.setLong("BorderSizeLerpTime", this.borderSizeLerpTime); + nbt.setDouble("BorderSafeZone", this.borderSafeZone); + nbt.setDouble("BorderDamagePerBlock", this.borderDamagePerBlock); + nbt.setDouble("BorderSizeLerpTarget", this.borderSizeLerpTarget); + nbt.setDouble("BorderWarningBlocks", (double) this.borderWarningDistance); + nbt.setDouble("BorderWarningTime", (double) this.borderWarningTime); + nbt.setInteger("eaglerVersionSerial", this.eaglerVersion); + if (this.difficulty != null) { + nbt.setByte("Difficulty", (byte) this.difficulty.getDifficultyId()); + } + + nbt.setBoolean("DifficultyLocked", this.difficultyLocked); + nbt.setTag("GameRules", this.theGameRules.writeToNBT()); + if (playerNbt != null) { + nbt.setTag("Player", playerNbt); + } + + } } \ No newline at end of file diff --git a/src/lwjgl/java/fi/iki/elonen/NanoHTTPD.java b/src/lwjgl/java/fi/iki/elonen/NanoHTTPD.java index 3cc7199a..0200211f 100644 --- a/src/lwjgl/java/fi/iki/elonen/NanoHTTPD.java +++ b/src/lwjgl/java/fi/iki/elonen/NanoHTTPD.java @@ -215,6 +215,82 @@ public abstract class NanoHTTPD { } } + protected static class ContentType { + + private static final String ASCII_ENCODING = "US-ASCII"; + + private static final String MULTIPART_FORM_DATA_HEADER = "multipart/form-data"; + + private static final String CONTENT_REGEX = "[ |\t]*([^/^ ^;^,]+/[^ ^;^,]+)"; + + private static final Pattern MIME_PATTERN = Pattern.compile(CONTENT_REGEX, Pattern.CASE_INSENSITIVE); + + private static final String CHARSET_REGEX = "[ |\t]*(charset)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?"; + + private static final Pattern CHARSET_PATTERN = Pattern.compile(CHARSET_REGEX, Pattern.CASE_INSENSITIVE); + + private static final String BOUNDARY_REGEX = "[ |\t]*(boundary)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?"; + + private static final Pattern BOUNDARY_PATTERN = Pattern.compile(BOUNDARY_REGEX, Pattern.CASE_INSENSITIVE); + + private final String contentTypeHeader; + + private final String contentType; + + private final String encoding; + + private final String boundary; + + public ContentType(String contentTypeHeader) { + this.contentTypeHeader = contentTypeHeader; + if (contentTypeHeader != null) { + contentType = getDetailFromContentHeader(contentTypeHeader, MIME_PATTERN, "", 1); + encoding = getDetailFromContentHeader(contentTypeHeader, CHARSET_PATTERN, null, 2); + } else { + contentType = ""; + encoding = "UTF-8"; + } + if (MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType)) { + boundary = getDetailFromContentHeader(contentTypeHeader, BOUNDARY_PATTERN, null, 2); + } else { + boundary = null; + } + } + + public String getBoundary() { + return boundary; + } + + public String getContentType() { + return contentType; + } + + public String getContentTypeHeader() { + return contentTypeHeader; + } + + private String getDetailFromContentHeader(String contentTypeHeader, Pattern pattern, String defaultValue, + int group) { + Matcher matcher = pattern.matcher(contentTypeHeader); + return matcher.find() ? matcher.group(group) : defaultValue; + } + + public String getEncoding() { + return encoding == null ? ASCII_ENCODING : encoding; + } + + public boolean isMultipart() { + return MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType); + } + + public ContentType tryUTF8() { + if (encoding == null) { + return new ContentType(this.contentTypeHeader + "; charset=UTF-8"); + } + return this; + } + } + public static class Cookie { public static String getHTTPTime(int days) { @@ -344,13 +420,6 @@ public abstract class NanoHTTPD { private final List running = Collections .synchronizedList(new ArrayList()); - /** - * @return a list with currently running clients. - */ - public List getRunning() { - return running; - } - @Override public void closeAll() { // copy of the list for concurrency @@ -373,6 +442,25 @@ public abstract class NanoHTTPD { this.running.add(clientHandler); t.start(); } + + /** + * @return a list with currently running clients. + */ + public List getRunning() { + return running; + } + } + + /** + * Creates a normal ServerSocket for TCP connections + */ + public static class DefaultServerSocketFactory implements ServerSocketFactory { + + @Override + public ServerSocket create() throws IOException { + return new ServerSocket(); + } + } /** @@ -468,139 +556,6 @@ public abstract class NanoHTTPD { } } - /** - * Creates a normal ServerSocket for TCP connections - */ - public static class DefaultServerSocketFactory implements ServerSocketFactory { - - @Override - public ServerSocket create() throws IOException { - return new ServerSocket(); - } - - } - - /** - * Creates a new SSLServerSocket - */ - public static class SecureServerSocketFactory implements ServerSocketFactory { - - private SSLServerSocketFactory sslServerSocketFactory; - - private String[] sslProtocols; - - public SecureServerSocketFactory(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) { - this.sslServerSocketFactory = sslServerSocketFactory; - this.sslProtocols = sslProtocols; - } - - @Override - public ServerSocket create() throws IOException { - SSLServerSocket ss = null; - ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket(); - if (this.sslProtocols != null) { - ss.setEnabledProtocols(this.sslProtocols); - } else { - ss.setEnabledProtocols(ss.getSupportedProtocols()); - } - ss.setUseClientMode(false); - ss.setWantClientAuth(false); - ss.setNeedClientAuth(false); - return ss; - } - - } - - private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)"; - - private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, - Pattern.CASE_INSENSITIVE); - - private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)"; - - private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE); - - private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]"; - - private static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern - .compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX); - - protected static class ContentType { - - private static final String ASCII_ENCODING = "US-ASCII"; - - private static final String MULTIPART_FORM_DATA_HEADER = "multipart/form-data"; - - private static final String CONTENT_REGEX = "[ |\t]*([^/^ ^;^,]+/[^ ^;^,]+)"; - - private static final Pattern MIME_PATTERN = Pattern.compile(CONTENT_REGEX, Pattern.CASE_INSENSITIVE); - - private static final String CHARSET_REGEX = "[ |\t]*(charset)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?"; - - private static final Pattern CHARSET_PATTERN = Pattern.compile(CHARSET_REGEX, Pattern.CASE_INSENSITIVE); - - private static final String BOUNDARY_REGEX = "[ |\t]*(boundary)[ |\t]*=[ |\t]*['|\"]?([^\"^'^;^,]*)['|\"]?"; - - private static final Pattern BOUNDARY_PATTERN = Pattern.compile(BOUNDARY_REGEX, Pattern.CASE_INSENSITIVE); - - private final String contentTypeHeader; - - private final String contentType; - - private final String encoding; - - private final String boundary; - - public ContentType(String contentTypeHeader) { - this.contentTypeHeader = contentTypeHeader; - if (contentTypeHeader != null) { - contentType = getDetailFromContentHeader(contentTypeHeader, MIME_PATTERN, "", 1); - encoding = getDetailFromContentHeader(contentTypeHeader, CHARSET_PATTERN, null, 2); - } else { - contentType = ""; - encoding = "UTF-8"; - } - if (MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType)) { - boundary = getDetailFromContentHeader(contentTypeHeader, BOUNDARY_PATTERN, null, 2); - } else { - boundary = null; - } - } - - private String getDetailFromContentHeader(String contentTypeHeader, Pattern pattern, String defaultValue, - int group) { - Matcher matcher = pattern.matcher(contentTypeHeader); - return matcher.find() ? matcher.group(group) : defaultValue; - } - - public String getContentTypeHeader() { - return contentTypeHeader; - } - - public String getContentType() { - return contentType; - } - - public String getEncoding() { - return encoding == null ? ASCII_ENCODING : encoding; - } - - public String getBoundary() { - return boundary; - } - - public boolean isMultipart() { - return MULTIPART_FORM_DATA_HEADER.equalsIgnoreCase(contentType); - } - - public ContentType tryUTF8() { - if (encoding == null) { - return new ContentType(this.contentTypeHeader + "; charset=UTF-8"); - } - return this; - } - } - protected class HTTPSession implements IHTTPSession { private static final int REQUEST_BUFFER_LEN = 512; @@ -832,13 +787,6 @@ public abstract class NanoHTTPD { } } - private int scipOverNewLine(byte[] partHeaderBuff, int index) { - while (partHeaderBuff[index] != '\n') { - index++; - } - return ++index; - } - /** * Decodes parameters in percent-encoded URI-format ( e.g. * "name=Jack%20Daniels&pass=Single%20Malt" ) and adds them to given Map. @@ -1028,6 +976,19 @@ public abstract class NanoHTTPD { return 0; } + /** + * Deduce body length in bytes. Either from "content-length" header or read + * bytes. + */ + public long getBodySize() { + if (this.headers.containsKey("content-length")) { + return Long.parseLong(this.headers.get("content-length")); + } else if (this.splitbyte < this.rlen) { + return this.rlen - this.splitbyte; + } + return 0; + } + /** * Find the byte positions where multipart boundaries start. This reads a large * block at a time and uses a temporary buffer to optimize (memory mapped) file @@ -1095,6 +1056,11 @@ public abstract class NanoHTTPD { return this.method; } + @Override + public final Map> getParameters() { + return this.parms; + } + /** * @deprecated use {@link #getParameters()} instead. */ @@ -1110,13 +1076,18 @@ public abstract class NanoHTTPD { } @Override - public final Map> getParameters() { - return this.parms; + public String getQueryParameterString() { + return this.queryParameterString; } @Override - public String getQueryParameterString() { - return this.queryParameterString; + public String getRemoteHostName() { + return this.remoteHostname; + } + + @Override + public String getRemoteIpAddress() { + return this.remoteIp; } private RandomAccessFile getTmpBucket() { @@ -1133,19 +1104,6 @@ public abstract class NanoHTTPD { return this.uri; } - /** - * Deduce body length in bytes. Either from "content-length" header or read - * bytes. - */ - public long getBodySize() { - if (this.headers.containsKey("content-length")) { - return Long.parseLong(this.headers.get("content-length")); - } else if (this.splitbyte < this.rlen) { - return this.rlen - this.splitbyte; - } - return 0; - } - @Override public void parseBody(Map files) throws IOException, ResponseException { RandomAccessFile randomAccessFile = null; @@ -1240,14 +1198,11 @@ public abstract class NanoHTTPD { return path; } - @Override - public String getRemoteIpAddress() { - return this.remoteIp; - } - - @Override - public String getRemoteHostName() { - return this.remoteHostname; + private int scipOverNewLine(byte[] partHeaderBuff, int index) { + while (partHeaderBuff[index] != '\n') { + index++; + } + return ++index; } } @@ -1266,6 +1221,8 @@ public abstract class NanoHTTPD { Method getMethod(); + Map> getParameters(); + /** * This method will only return the first value for a given parameter. You will * want to use getParameters if you expect multiple values for a given key. @@ -1275,10 +1232,22 @@ public abstract class NanoHTTPD { @Deprecated Map getParms(); - Map> getParameters(); - String getQueryParameterString(); + /** + * Get the remote hostname of the requester. + * + * @return the hostname. + */ + String getRemoteHostName(); + + /** + * Get the remote ip address of the requester. + * + * @return the IP address. + */ + String getRemoteIpAddress(); + /** * @return the path part of the URL. */ @@ -1290,20 +1259,6 @@ public abstract class NanoHTTPD { * @param files map to modify */ void parseBody(Map files) throws IOException, ResponseException; - - /** - * Get the remote ip address of the requester. - * - * @return the IP address. - */ - String getRemoteIpAddress(); - - /** - * Get the remote hostname of the requester. - * - * @return the hostname. - */ - String getRemoteHostName(); } /** @@ -1332,6 +1287,43 @@ public abstract class NanoHTTPD { */ public static class Response implements Closeable { + /** + * Output stream that will automatically send every write to the wrapped + * OutputStream according to chunked transfer: + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 + */ + private static class ChunkedOutputStream extends FilterOutputStream { + + public ChunkedOutputStream(OutputStream out) { + super(out); + } + + public void finish() throws IOException { + out.write("0\r\n\r\n".getBytes()); + } + + @Override + public void write(byte[] b) throws IOException { + write(b, 0, b.length); + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (len == 0) + return; + out.write(String.format("%x\r\n", len).getBytes()); + out.write(b, off, len); + out.write("\r\n".getBytes()); + } + + @Override + public void write(int b) throws IOException { + byte[] data = { (byte) b }; + write(data, 0, 1); + } + + } + public interface IStatus { String getDescription(); @@ -1371,15 +1363,6 @@ public abstract class NanoHTTPD { SERVICE_UNAVAILABLE(503, "Service Unavailable"), UNSUPPORTED_HTTP_VERSION(505, "HTTP Version Not Supported"); - private final int requestStatus; - - private final String description; - - Status(int requestStatus, String description) { - this.requestStatus = requestStatus; - this.description = description; - } - public static Status lookup(int requestStatus) { for (Status status : Status.values()) { if (status.getRequestStatus() == requestStatus) { @@ -1389,6 +1372,15 @@ public abstract class NanoHTTPD { return null; } + private final int requestStatus; + + private final String description; + + Status(int requestStatus, String description) { + this.requestStatus = requestStatus; + this.description = description; + } + @Override public String getDescription() { return "" + this.requestStatus + " " + this.description; @@ -1401,43 +1393,6 @@ public abstract class NanoHTTPD { } - /** - * Output stream that will automatically send every write to the wrapped - * OutputStream according to chunked transfer: - * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 - */ - private static class ChunkedOutputStream extends FilterOutputStream { - - public ChunkedOutputStream(OutputStream out) { - super(out); - } - - @Override - public void write(int b) throws IOException { - byte[] data = { (byte) b }; - write(data, 0, 1); - } - - @Override - public void write(byte[] b) throws IOException { - write(b, 0, b.length); - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - if (len == 0) - return; - out.write(String.format("%x\r\n", len).getBytes()); - out.write(b, off, len); - out.write("\r\n".getBytes()); - } - - public void finish() throws IOException { - out.write("0\r\n\r\n".getBytes()); - } - - } - /** * HTTP status code after processing, e.g. "200 OK", Status.OK */ @@ -1504,13 +1459,6 @@ public abstract class NanoHTTPD { keepAlive = true; } - @Override - public void close() throws IOException { - if (this.data != null) { - this.data.close(); - } - } - /** * Adds given line to the header. */ @@ -1518,6 +1466,13 @@ public abstract class NanoHTTPD { this.header.put(name, value); } + @Override + public void close() throws IOException { + if (this.data != null) { + this.data.close(); + } + } + /** * Indicate to close the connection after the Response has been sent. * @@ -1531,14 +1486,6 @@ public abstract class NanoHTTPD { this.header.remove("connection"); } - /** - * @return {@code true} if connection is to be closed after this Response has - * been sent. - */ - public boolean isCloseConnection() { - return "close".equals(getHeader("connection")); - } - public InputStream getData() { return this.data; } @@ -1559,12 +1506,17 @@ public abstract class NanoHTTPD { return this.status; } - public void setGzipEncoding(boolean encodeAsGzip) { - this.encodeAsGzip = encodeAsGzip; + /** + * @return {@code true} if connection is to be closed after this Response has + * been sent. + */ + public boolean isCloseConnection() { + return "close".equals(getHeader("connection")); } - public void setKeepAlive(boolean useKeepAlive) { - this.keepAlive = useKeepAlive; + @SuppressWarnings("static-method") + protected void printHeader(PrintWriter pw, String key, String value) { + pw.append(key).append(": ").append(value).append("\r\n"); } /** @@ -1618,46 +1570,6 @@ public abstract class NanoHTTPD { } } - @SuppressWarnings("static-method") - protected void printHeader(PrintWriter pw, String key, String value) { - pw.append(key).append(": ").append(value).append("\r\n"); - } - - protected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) { - String contentLengthString = getHeader("content-length"); - long size = defaultSize; - if (contentLengthString != null) { - try { - size = Long.parseLong(contentLengthString); - } catch (NumberFormatException ex) { - LOG.severe("content-length was no number " + contentLengthString); - } - } - pw.print("Content-Length: " + size + "\r\n"); - return size; - } - - private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) - throws IOException { - if (this.requestMethod != Method.HEAD && this.chunkedTransfer) { - ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream); - sendBodyWithCorrectEncoding(chunkedOutputStream, -1); - chunkedOutputStream.finish(); - } else { - sendBodyWithCorrectEncoding(outputStream, pending); - } - } - - private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException { - if (encodeAsGzip) { - GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream); - sendBody(gzipOutputStream, -1); - gzipOutputStream.finish(); - } else { - sendBody(outputStream, pending); - } - } - /** * Sends the body to the specified OutputStream. The pending parameter limits * the maximum amounts of bytes sent unless it is -1, in which case everything @@ -1685,6 +1597,41 @@ public abstract class NanoHTTPD { } } + private void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException { + if (encodeAsGzip) { + GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream); + sendBody(gzipOutputStream, -1); + gzipOutputStream.finish(); + } else { + sendBody(outputStream, pending); + } + } + + private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) + throws IOException { + if (this.requestMethod != Method.HEAD && this.chunkedTransfer) { + ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream); + sendBodyWithCorrectEncoding(chunkedOutputStream, -1); + chunkedOutputStream.finish(); + } else { + sendBodyWithCorrectEncoding(outputStream, pending); + } + } + + protected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) { + String contentLengthString = getHeader("content-length"); + long size = defaultSize; + if (contentLengthString != null) { + try { + size = Long.parseLong(contentLengthString); + } catch (NumberFormatException ex) { + LOG.severe("content-length was no number " + contentLengthString); + } + } + pw.print("Content-Length: " + size + "\r\n"); + return size; + } + public void setChunkedTransfer(boolean chunkedTransfer) { this.chunkedTransfer = chunkedTransfer; } @@ -1693,6 +1640,14 @@ public abstract class NanoHTTPD { this.data = data; } + public void setGzipEncoding(boolean encodeAsGzip) { + this.encodeAsGzip = encodeAsGzip; + } + + public void setKeepAlive(boolean useKeepAlive) { + this.keepAlive = useKeepAlive; + } + public void setMimeType(String mimeType) { this.mimeType = mimeType; } @@ -1727,6 +1682,37 @@ public abstract class NanoHTTPD { } } + /** + * Creates a new SSLServerSocket + */ + public static class SecureServerSocketFactory implements ServerSocketFactory { + + private SSLServerSocketFactory sslServerSocketFactory; + + private String[] sslProtocols; + + public SecureServerSocketFactory(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) { + this.sslServerSocketFactory = sslServerSocketFactory; + this.sslProtocols = sslProtocols; + } + + @Override + public ServerSocket create() throws IOException { + SSLServerSocket ss = null; + ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket(); + if (this.sslProtocols != null) { + ss.setEnabledProtocols(this.sslProtocols); + } else { + ss.setEnabledProtocols(ss.getSupportedProtocols()); + } + ss.setUseClientMode(false); + ss.setWantClientAuth(false); + ss.setNeedClientAuth(false); + return ss; + } + + } + /** * The runnable that will be used for the main listening thread. */ @@ -1767,6 +1753,15 @@ public abstract class NanoHTTPD { } } + /** + * Factory to create ServerSocketFactories. + */ + public interface ServerSocketFactory { + + public ServerSocket create() throws IOException; + + } + /** * A temp file. *

@@ -1807,14 +1802,19 @@ public abstract class NanoHTTPD { public TempFileManager create(); } - /** - * Factory to create ServerSocketFactories. - */ - public interface ServerSocketFactory { + private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)"; - public ServerSocket create() throws IOException; + private static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile(CONTENT_DISPOSITION_REGEX, + Pattern.CASE_INSENSITIVE); - } + private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)"; + + private static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile(CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE); + + private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]"; + + private static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern + .compile(CONTENT_DISPOSITION_ATTRIBUTE_REGEX); /** * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) This @@ -1849,16 +1849,78 @@ public abstract class NanoHTTPD { */ protected static Map MIME_TYPES; - public static Map mimeTypes() { - if (MIME_TYPES == null) { - MIME_TYPES = new HashMap(); - loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/default-mimetypes.properties"); - loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/mimetypes.properties"); - if (MIME_TYPES.isEmpty()) { - LOG.log(Level.WARNING, "no mime types found in the classpath! please provide mimetypes.properties"); + /** + * Decode parameters from a URL, handing the case where a single parameter name + * might have been supplied several times, by return lists of values. In general + * these lists will contain a single element. + * + * @param parms original NanoHTTPD parameters values, as passed to the + * serve() method. + * @return a map of String (parameter name) to + * List<String> (a list of the values supplied). + */ + protected static Map> decodeParameters(Map parms) { + return decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER)); + } + + /** + * Decode parameters from a URL, handing the case where a single parameter name + * might have been supplied several times, by return lists of values. In general + * these lists will contain a single element. + * + * @param queryString a query string pulled from the URL. + * @return a map of String (parameter name) to + * List<String> (a list of the values supplied). + */ + protected static Map> decodeParameters(String queryString) { + Map> parms = new HashMap>(); + if (queryString != null) { + StringTokenizer st = new StringTokenizer(queryString, "&"); + while (st.hasMoreTokens()) { + String e = st.nextToken(); + int sep = e.indexOf('='); + String propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); + if (!parms.containsKey(propertyName)) { + parms.put(propertyName, new ArrayList()); + } + String propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null; + if (propertyValue != null) { + parms.get(propertyName).add(propertyValue); + } } } - return MIME_TYPES; + return parms; + }; + + /** + * Decode percent encoded String values. + * + * @param str the percent encoded String + * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" + */ + protected static String decodePercent(String str) { + String decoded = null; + try { + decoded = URLDecoder.decode(str, "UTF8"); + } catch (UnsupportedEncodingException ignored) { + NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored); + } + return decoded; + } + + /** + * Get MIME type from file name extension, if possible + * + * @param uri the string representing a file + * @return the connected mime/type + */ + public static String getMimeTypeForFile(String uri) { + int dot = uri.lastIndexOf('.'); + String mime = null; + if (dot >= 0) { + mime = mimeTypes().get(uri.substring(dot + 1).toLowerCase()); + } + return mime == null ? "application/octet-stream" : mime; } @SuppressWarnings({ "unchecked", "rawtypes" }) @@ -1882,7 +1944,7 @@ public abstract class NanoHTTPD { } catch (IOException e) { LOG.log(Level.INFO, "no mime types available at " + resourceName); } - }; + } /** * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an array of @@ -1943,216 +2005,16 @@ public abstract class NanoHTTPD { } } - /** - * Get MIME type from file name extension, if possible - * - * @param uri the string representing a file - * @return the connected mime/type - */ - public static String getMimeTypeForFile(String uri) { - int dot = uri.lastIndexOf('.'); - String mime = null; - if (dot >= 0) { - mime = mimeTypes().get(uri.substring(dot + 1).toLowerCase()); - } - return mime == null ? "application/octet-stream" : mime; - } - - private static final void safeClose(Object closeable) { - try { - if (closeable != null) { - if (closeable instanceof Closeable) { - ((Closeable) closeable).close(); - } else if (closeable instanceof Socket) { - ((Socket) closeable).close(); - } else if (closeable instanceof ServerSocket) { - ((ServerSocket) closeable).close(); - } else { - throw new IllegalArgumentException("Unknown object to close"); - } - } - } catch (IOException e) { - NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e); - } - } - - private final String hostname; - - private final int myPort; - - private volatile ServerSocket myServerSocket; - - private ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory(); - - private Thread myThread; - - /** - * Pluggable strategy for asynchronously executing requests. - */ - protected AsyncRunner asyncRunner; - - /** - * Pluggable strategy for creating and cleaning up temporary files. - */ - private TempFileManagerFactory tempFileManagerFactory; - - /** - * Constructs an HTTP server on given port. - */ - public NanoHTTPD(int port) { - this(null, port); - } - - // ------------------------------------------------------------------------------- - // // - // - // Threading Strategy. - // - // ------------------------------------------------------------------------------- - // // - - /** - * Constructs an HTTP server on given hostname and port. - */ - public NanoHTTPD(String hostname, int port) { - this.hostname = hostname; - this.myPort = port; - setTempFileManagerFactory(new DefaultTempFileManagerFactory()); - setAsyncRunner(new DefaultAsyncRunner()); - } - - /** - * Forcibly closes all connections that are open. - */ - public synchronized void closeAllConnections() { - stop(); - } - - /** - * create a instance of the client handler, subclasses can return a subclass of - * the ClientHandler. - * - * @param finalAccept the socket the cleint is connected to - * @param inputStream the input stream - * @return the client handler - */ - protected ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) { - return new ClientHandler(inputStream, finalAccept); - } - - /** - * Instantiate the server runnable, can be overwritten by subclasses to provide - * a subclass of the ServerRunnable. - * - * @param timeout the socet timeout to use. - * @return the server runnable. - */ - protected ServerRunnable createServerRunnable(final int timeout) { - return new ServerRunnable(timeout); - } - - /** - * Decode parameters from a URL, handing the case where a single parameter name - * might have been supplied several times, by return lists of values. In general - * these lists will contain a single element. - * - * @param parms original NanoHTTPD parameters values, as passed to the - * serve() method. - * @return a map of String (parameter name) to - * List<String> (a list of the values supplied). - */ - protected static Map> decodeParameters(Map parms) { - return decodeParameters(parms.get(NanoHTTPD.QUERY_STRING_PARAMETER)); - } - - // ------------------------------------------------------------------------------- - // // - - /** - * Decode parameters from a URL, handing the case where a single parameter name - * might have been supplied several times, by return lists of values. In general - * these lists will contain a single element. - * - * @param queryString a query string pulled from the URL. - * @return a map of String (parameter name) to - * List<String> (a list of the values supplied). - */ - protected static Map> decodeParameters(String queryString) { - Map> parms = new HashMap>(); - if (queryString != null) { - StringTokenizer st = new StringTokenizer(queryString, "&"); - while (st.hasMoreTokens()) { - String e = st.nextToken(); - int sep = e.indexOf('='); - String propertyName = sep >= 0 ? decodePercent(e.substring(0, sep)).trim() : decodePercent(e).trim(); - if (!parms.containsKey(propertyName)) { - parms.put(propertyName, new ArrayList()); - } - String propertyValue = sep >= 0 ? decodePercent(e.substring(sep + 1)) : null; - if (propertyValue != null) { - parms.get(propertyName).add(propertyValue); - } + public static Map mimeTypes() { + if (MIME_TYPES == null) { + MIME_TYPES = new HashMap(); + loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/default-mimetypes.properties"); + loadMimeTypes(MIME_TYPES, "META-INF/nanohttpd/mimetypes.properties"); + if (MIME_TYPES.isEmpty()) { + LOG.log(Level.WARNING, "no mime types found in the classpath! please provide mimetypes.properties"); } } - return parms; - } - - /** - * Decode percent encoded String values. - * - * @param str the percent encoded String - * @return expanded form of the input, for example "foo%20bar" becomes "foo bar" - */ - protected static String decodePercent(String str) { - String decoded = null; - try { - decoded = URLDecoder.decode(str, "UTF8"); - } catch (UnsupportedEncodingException ignored) { - NanoHTTPD.LOG.log(Level.WARNING, "Encoding not supported, ignored", ignored); - } - return decoded; - } - - /** - * @return true if the gzip compression should be used if the client accespts - * it. Default this option is on for text content and off for - * everything. Override this for custom semantics. - */ - @SuppressWarnings("static-method") - protected boolean useGzipWhenAccepted(Response r) { - return r.getMimeType() != null - && (r.getMimeType().toLowerCase().contains("text/") || r.getMimeType().toLowerCase().contains("/json")); - } - - public final int getListeningPort() { - return this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort(); - } - - public final boolean isAlive() { - return wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive(); - } - - public ServerSocketFactory getServerSocketFactory() { - return serverSocketFactory; - } - - public void setServerSocketFactory(ServerSocketFactory serverSocketFactory) { - this.serverSocketFactory = serverSocketFactory; - } - - public String getHostname() { - return hostname; - } - - public TempFileManagerFactory getTempFileManagerFactory() { - return tempFileManagerFactory; - } - - /** - * Call before start() to serve over HTTPS instead of HTTP - */ - public void makeSecure(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) { - this.serverSocketFactory = new SecureServerSocketFactory(sslServerSocketFactory, sslProtocols); + return MIME_TYPES; } /** @@ -2200,6 +2062,129 @@ public abstract class NanoHTTPD { return newFixedLengthResponse(Status.OK, NanoHTTPD.MIME_HTML, msg); } + private static final void safeClose(Object closeable) { + try { + if (closeable != null) { + if (closeable instanceof Closeable) { + ((Closeable) closeable).close(); + } else if (closeable instanceof Socket) { + ((Socket) closeable).close(); + } else if (closeable instanceof ServerSocket) { + ((ServerSocket) closeable).close(); + } else { + throw new IllegalArgumentException("Unknown object to close"); + } + } + } catch (IOException e) { + NanoHTTPD.LOG.log(Level.SEVERE, "Could not close", e); + } + } + + private final String hostname; + + // ------------------------------------------------------------------------------- + // // + // + // Threading Strategy. + // + // ------------------------------------------------------------------------------- + // // + + private final int myPort; + + private volatile ServerSocket myServerSocket; + + private ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory(); + + private Thread myThread; + + /** + * Pluggable strategy for asynchronously executing requests. + */ + protected AsyncRunner asyncRunner; + + // ------------------------------------------------------------------------------- + // // + + /** + * Pluggable strategy for creating and cleaning up temporary files. + */ + private TempFileManagerFactory tempFileManagerFactory; + + /** + * Constructs an HTTP server on given port. + */ + public NanoHTTPD(int port) { + this(null, port); + } + + /** + * Constructs an HTTP server on given hostname and port. + */ + public NanoHTTPD(String hostname, int port) { + this.hostname = hostname; + this.myPort = port; + setTempFileManagerFactory(new DefaultTempFileManagerFactory()); + setAsyncRunner(new DefaultAsyncRunner()); + } + + /** + * Forcibly closes all connections that are open. + */ + public synchronized void closeAllConnections() { + stop(); + } + + /** + * create a instance of the client handler, subclasses can return a subclass of + * the ClientHandler. + * + * @param finalAccept the socket the cleint is connected to + * @param inputStream the input stream + * @return the client handler + */ + protected ClientHandler createClientHandler(final Socket finalAccept, final InputStream inputStream) { + return new ClientHandler(inputStream, finalAccept); + } + + /** + * Instantiate the server runnable, can be overwritten by subclasses to provide + * a subclass of the ServerRunnable. + * + * @param timeout the socet timeout to use. + * @return the server runnable. + */ + protected ServerRunnable createServerRunnable(final int timeout) { + return new ServerRunnable(timeout); + } + + public String getHostname() { + return hostname; + } + + public final int getListeningPort() { + return this.myServerSocket == null ? -1 : this.myServerSocket.getLocalPort(); + } + + public ServerSocketFactory getServerSocketFactory() { + return serverSocketFactory; + } + + public TempFileManagerFactory getTempFileManagerFactory() { + return tempFileManagerFactory; + } + + public final boolean isAlive() { + return wasStarted() && !this.myServerSocket.isClosed() && this.myThread.isAlive(); + } + + /** + * Call before start() to serve over HTTPS instead of HTTP + */ + public void makeSecure(SSLServerSocketFactory sslServerSocketFactory, String[] sslProtocols) { + this.serverSocketFactory = new SecureServerSocketFactory(sslServerSocketFactory, sslProtocols); + } + /** * Override this to customize the server. *

@@ -2257,6 +2242,10 @@ public abstract class NanoHTTPD { this.asyncRunner = asyncRunner; } + public void setServerSocketFactory(ServerSocketFactory serverSocketFactory) { + this.serverSocketFactory = serverSocketFactory; + } + /** * Pluggable strategy for creating and cleaning up temporary files. * @@ -2327,6 +2316,17 @@ public abstract class NanoHTTPD { } } + /** + * @return true if the gzip compression should be used if the client accespts + * it. Default this option is on for text content and off for + * everything. Override this for custom semantics. + */ + @SuppressWarnings("static-method") + protected boolean useGzipWhenAccepted(Response r) { + return r.getMimeType() != null + && (r.getMimeType().toLowerCase().contains("text/") || r.getMimeType().toLowerCase().contains("/json")); + } + public final boolean wasStarted() { return this.myServerSocket != null && this.myThread != null; } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/OpenGLObjects.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/OpenGLObjects.java index 693cbbe6..94ee424d 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/OpenGLObjects.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/OpenGLObjects.java @@ -3,188 +3,189 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class OpenGLObjects { - static class BufferGL implements IBufferGL { - - final int ptr; - - BufferGL(int ptr) { - this.ptr = ptr; - } - - public int hashCode() { - return ptr; - } - - @Override - public void free() { - PlatformOpenGL._wglDeleteBuffers(this); - } - - } - static class BufferArrayGL implements IBufferArrayGL { - + final int ptr; - + BufferArrayGL(int ptr) { this.ptr = ptr; } - public int hashCode() { - return ptr; - } - @Override public void free() { PlatformOpenGL._wglDeleteVertexArrays(this); } - + + public int hashCode() { + return ptr; + } + } - static class TextureGL implements ITextureGL { - + static class BufferGL implements IBufferGL { + final int ptr; - - TextureGL(int ptr) { + + BufferGL(int ptr) { this.ptr = ptr; } + @Override + public void free() { + PlatformOpenGL._wglDeleteBuffers(this); + } + public int hashCode() { return ptr; } - @Override - public void free() { - PlatformOpenGL._wglDeleteTextures(this); - } - - } - - static class ProgramGL implements IProgramGL { - - final int ptr; - - ProgramGL(int ptr) { - this.ptr = ptr; - } - - public int hashCode() { - return ptr; - } - - @Override - public void free() { - PlatformOpenGL._wglDeleteProgram(this); - } - - } - - static class UniformGL implements IUniformGL { - - final int ptr; - - UniformGL(int ptr) { - this.ptr = ptr; - } - - public int hashCode() { - return ptr; - } - - @Override - public void free() { - } - - } - - static class ShaderGL implements IShaderGL { - - final int ptr; - - ShaderGL(int ptr) { - this.ptr = ptr; - } - - public int hashCode() { - return ptr; - } - - @Override - public void free() { - PlatformOpenGL._wglDeleteShader(this); - } - } static class FramebufferGL implements IFramebufferGL { - + final int ptr; - + FramebufferGL(int ptr) { this.ptr = ptr; } - public int hashCode() { - return ptr; - } - @Override public void free() { PlatformOpenGL._wglDeleteFramebuffer(this); } - - } - - static class RenderbufferGL implements IRenderbufferGL { - - final int ptr; - - RenderbufferGL(int ptr) { - this.ptr = ptr; - } public int hashCode() { return ptr; } + } + + static class ProgramGL implements IProgramGL { + + final int ptr; + + ProgramGL(int ptr) { + this.ptr = ptr; + } + @Override public void free() { - PlatformOpenGL._wglDeleteRenderbuffer(this); - } - - } - - static class QueryGL implements IQueryGL { - - final int ptr; - - QueryGL(int ptr) { - this.ptr = ptr; + PlatformOpenGL._wglDeleteProgram(this); } public int hashCode() { return ptr; } + } + + static class QueryGL implements IQueryGL { + + final int ptr; + + QueryGL(int ptr) { + this.ptr = ptr; + } + @Override public void free() { PlatformOpenGL._wglDeleteQueries(this); } - + + public int hashCode() { + return ptr; + } + } - + + static class RenderbufferGL implements IRenderbufferGL { + + final int ptr; + + RenderbufferGL(int ptr) { + this.ptr = ptr; + } + + @Override + public void free() { + PlatformOpenGL._wglDeleteRenderbuffer(this); + } + + public int hashCode() { + return ptr; + } + + } + + static class ShaderGL implements IShaderGL { + + final int ptr; + + ShaderGL(int ptr) { + this.ptr = ptr; + } + + @Override + public void free() { + PlatformOpenGL._wglDeleteShader(this); + } + + public int hashCode() { + return ptr; + } + + } + + static class TextureGL implements ITextureGL { + + final int ptr; + + TextureGL(int ptr) { + this.ptr = ptr; + } + + @Override + public void free() { + PlatformOpenGL._wglDeleteTextures(this); + } + + public int hashCode() { + return ptr; + } + + } + + static class UniformGL implements IUniformGL { + + final int ptr; + + UniformGL(int ptr) { + this.ptr = ptr; + } + + @Override + public void free() { + } + + public int hashCode() { + return ptr; + } + + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformApplication.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformApplication.java index d4985bf2..ff676e86 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformApplication.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformApplication.java @@ -1,15 +1,16 @@ package net.lax1dude.eaglercraft.v1_8.internal; -import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.glfw.GLFW.glfwGetClipboardString; +import static org.lwjgl.glfw.GLFW.glfwSetClipboardString; import java.awt.Component; import java.awt.Desktop; +import java.awt.Dialog.ModalExclusionType; +import java.awt.Dialog.ModalityType; import java.awt.EventQueue; import java.awt.HeadlessException; import java.awt.Toolkit; import java.awt.image.BufferedImage; -import java.awt.Dialog.ModalExclusionType; -import java.awt.Dialog.ModalityType; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; @@ -36,198 +37,33 @@ import net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformApplication { - - private static long win = 0l; - - static void initHooks(long glfwWindow) { - win = glfwWindow; - } - - public static void openLink(String url) { - URI safeURL; - try { - safeURL = new URI(url); - String proto = safeURL.getScheme(); - if(!proto.equalsIgnoreCase("http") && !proto.equalsIgnoreCase("https")) { - throw new IllegalArgumentException("Suspicious protocol: " + proto); - } - }catch(URISyntaxException | IllegalArgumentException ex) { - PlatformRuntime.logger.error("Refusing to open invalid URL: {}", url); - PlatformRuntime.logger.error(ex); - return; - } - try { - Desktop.getDesktop().browse(safeURL); - } catch (Throwable var5) { - PlatformRuntime.logger.error("Failed to browse to URL: {}", safeURL.toString()); - PlatformRuntime.logger.error(var5); - } - } - - public static void setClipboard(String text) { - glfwSetClipboardString(win, text); - } - - public static String getClipboard() { - String str = glfwGetClipboardString(win); - return str == null ? "" : str; - } - - public static void setLocalStorage(String name, byte[] data) { - setLocalStorage(name, data, true); - } - - public static void setLocalStorage(String name, byte[] data, boolean hooks) { - if(data == null) { - (new File("_eagstorage."+name+".dat")).delete(); - }else { - try(FileOutputStream f = new FileOutputStream(new File("_eagstorage."+name+".dat"))) { - f.write(data); - } catch (IOException e) { - EagRuntime.debugPrintStackTrace(e); - } - } - } - - public static byte[] getLocalStorage(String data) { - return getLocalStorage(data, true); - } - - public static byte[] getLocalStorage(String data, boolean hooks) { - File f = new File("_eagstorage."+data+".dat"); - if(!f.isFile()) { - return null; - } - byte[] b = new byte[(int)f.length()]; - try(FileInputStream s = new FileInputStream(f)) { - s.read(b); - return b; - } catch (IOException e) { - return null; - } - } - - private static final DateFormat dateFormatSS = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); - private static final File screeshotsDir = new File("screenshots"); - - public static String saveScreenshot() { - if(!screeshotsDir.isDirectory() && !screeshotsDir.mkdirs()) { - PlatformRuntime.logger.error("Failed to create screenshots directory: {}", screeshotsDir.getAbsolutePath()); - return "nothing"; - } - String name = "screenshot_" + dateFormatSS.format(new Date()).toString() + ".png"; - int w = PlatformInput.getWindowWidth(); - int h = PlatformInput.getWindowHeight(); - ByteBuffer screenshotBuffer = PlatformRuntime.allocateByteBuffer(w * h * 4); - PlatformOpenGL._wglReadPixels(0, 0, w, h, RealOpenGLEnums.GL_RGBA, RealOpenGLEnums.GL_UNSIGNED_BYTE, screenshotBuffer); - BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - int i; - for(int y = 0; y < h; ++y) { - for(int x = 0; x < w; ++x) { - i = (x + (h - y - 1) * w) << 2; - bufferedImage.setRGB(x, y, - ((screenshotBuffer.get(i) & 0xFF) << 16) | ((screenshotBuffer.get(i + 1) & 0xFF) << 8) - | (screenshotBuffer.get(i + 2) & 0xFF) | 0xFF000000); - } - } - PlatformRuntime.freeByteBuffer(screenshotBuffer); - File screenshotFile = new File(screeshotsDir, name); - try { - ImageIO.write(bufferedImage, "PNG", screenshotFile); - }catch(IOException ex) { - PlatformRuntime.logger.error("Failed to write screenshot: {}", screenshotFile.getAbsolutePath()); - return "nothing"; - } - PlatformRuntime.logger.info("Saved screenshot to: {}", screenshotFile.getAbsolutePath()); - return name; - } - - public static void showPopup(String msg) { - JOptionPane pane = new JOptionPane(msg, JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null, - new Object[] { "OK" }, "OK"); - pane.setInitialValue("OK"); - JDialog dialog = pane.createDialog("EaglercraftX Runtime"); - pane.selectInitialValue(); - dialog.setIconImage(Toolkit.getDefaultToolkit().getImage("icon32.png")); - dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - dialog.setAlwaysOnTop(true); - dialog.setModal(true); - dialog.setLocationByPlatform(true); - dialog.setModalExclusionType(ModalExclusionType.TOOLKIT_EXCLUDE); - dialog.setModalityType(ModalityType.TOOLKIT_MODAL); - dialog.setLocationRelativeTo(null); - dialog.setVisible(true); - } - - private static volatile boolean fileChooserOpen = false; - private static volatile boolean fileChooserHasResult = false; - private static volatile FileChooserResult fileChooserResultObject = null; - - public static void displayFileChooser(final String mime, final String ext) { - if(!fileChooserOpen) { - fileChooserOpen = true; - clearFileChooserResult(); - EventQueue.invokeLater(new Runnable() { - @Override - public void run() { - runDisplayFileChooser(mime, ext); - } - }); - } - } - - private static void runDisplayFileChooser(String mime, String ext) { - try { - JFileChooser fc = new FileChooserAlwaysOnTop((new File(".")).getAbsoluteFile()); - fc.setDialogTitle("select a file"); - fc.setFileSelectionMode(JFileChooser.FILES_ONLY); - fc.setMultiSelectionEnabled(false); - fc.setFileFilter(new FileFilterExt(ext)); - if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { - File f = fc.getSelectedFile(); - if(f != null) { - String name = f.getName(); - byte[] bytes = new byte[(int)f.length()]; - try(FileInputStream is = new FileInputStream(f)) { - is.read(bytes); - } - fileChooserResultObject = new FileChooserResult(name, bytes); - }else { - fileChooserResultObject = null; - } - } - }catch(Throwable t) { - fileChooserResultObject = null; - } - fileChooserOpen = false; - fileChooserHasResult = true; - } private static class FileChooserAlwaysOnTop extends JFileChooser { - + private FileChooserAlwaysOnTop(File file) { super(file); } - + protected JDialog createDialog(Component parent) throws HeadlessException { JDialog dialog = super.createDialog(parent); dialog.setAlwaysOnTop(true); return dialog; } - + } private static class FileFilterExt extends FileFilter { @@ -250,10 +86,89 @@ public class PlatformApplication { } + private static long win = 0l; + + private static final DateFormat dateFormatSS = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss"); + + private static final File screeshotsDir = new File("screenshots"); + + private static volatile boolean fileChooserOpen = false; + + private static volatile boolean fileChooserHasResult = false; + + private static volatile FileChooserResult fileChooserResultObject = null; + + private static MainMenuCreditsDialog creditsDialog = null; + + private static final File downloadsDirectory = new File("downloads"); + private static final Logger downloadsLogger = LogManager.getLogger("DownloadsFolder"); + + public static void addLogMessage(String logMessage, boolean isError) { + + } + + public static void clearFileChooserResult() { + fileChooserHasResult = false; + fileChooserResultObject = null; + } + + public static void displayFileChooser(final String mime, final String ext) { + if (!fileChooserOpen) { + fileChooserOpen = true; + clearFileChooserResult(); + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + runDisplayFileChooser(mime, ext); + } + }); + } + } + + public static void downloadFileWithName(String fileName, byte[] fileContents) { + if (!downloadsDirectory.isDirectory() && !downloadsDirectory.mkdirs()) { + throw new RuntimeException("Could not create directory: " + downloadsDirectory.getAbsolutePath()); + } + + File f = new File(downloadsDirectory, fileName); + if (f.exists()) { + String name = fileName; + String ext = ""; + int i = fileName.lastIndexOf('.'); + if (i != -1) { + name = fileName.substring(0, i); + ext = fileName.substring(i); + } + + i = 0; + do { + f = new File(downloadsDirectory, name + " (" + (++i) + ")" + ext); + } while (f.exists()); + } + + try (FileOutputStream fos = new FileOutputStream(f)) { + fos.write(fileContents); + } catch (IOException ex) { + throw new RuntimeException("Could not save file: " + f.getAbsolutePath()); + } + + downloadsLogger.info("Saved {} byte file to: {}", fileContents.length, f.getAbsolutePath()); + + try { + Desktop.getDesktop().open(downloadsDirectory); + } catch (Throwable t) { + } + } + public static boolean fileChooserHasResult() { return fileChooserHasResult; } + public static String getClipboard() { + String str = glfwGetClipboardString(win); + return str == null ? "" : str; + } + public static FileChooserResult getFileChooserResult() { fileChooserHasResult = false; FileChooserResult res = fileChooserResultObject; @@ -261,15 +176,34 @@ public class PlatformApplication { return res; } - public static void clearFileChooserResult() { - fileChooserHasResult = false; - fileChooserResultObject = null; + public static byte[] getLocalStorage(String data) { + return getLocalStorage(data, true); } - private static MainMenuCreditsDialog creditsDialog = null; + public static byte[] getLocalStorage(String data, boolean hooks) { + File f = new File("_eagstorage." + data + ".dat"); + if (!f.isFile()) { + return null; + } + byte[] b = new byte[(int) f.length()]; + try (FileInputStream s = new FileInputStream(f)) { + s.read(b); + return b; + } catch (IOException e) { + return null; + } + } + + static void initHooks(long glfwWindow) { + win = glfwWindow; + } + + public static boolean isShowingDebugConsole() { + return false; + } public static void openCreditsPopup(String text) { - if(creditsDialog == null) { + if (creditsDialog == null) { creditsDialog = new MainMenuCreditsDialog(); } creditsDialog.setCreditsText(text); @@ -277,58 +211,130 @@ public class PlatformApplication { creditsDialog.setVisible(true); } - private static final File downloadsDirectory = new File("downloads"); - private static final Logger downloadsLogger = LogManager.getLogger("DownloadsFolder"); - - public static void downloadFileWithName(String fileName, byte[] fileContents) { - if(!downloadsDirectory.isDirectory() && !downloadsDirectory.mkdirs()) { - throw new RuntimeException("Could not create directory: " + downloadsDirectory.getAbsolutePath()); - } - - File f = new File(downloadsDirectory, fileName); - if(f.exists()) { - String name = fileName; - String ext = ""; - int i = fileName.lastIndexOf('.'); - if(i != -1) { - name = fileName.substring(0, i); - ext = fileName.substring(i); - } - - i = 0; - do { - f = new File(downloadsDirectory, name + " (" + (++i) + ")" + ext); - }while(f.exists()); - } - - try(FileOutputStream fos = new FileOutputStream(f)) { - fos.write(fileContents); - }catch(IOException ex) { - throw new RuntimeException("Could not save file: " + f.getAbsolutePath()); - } - - downloadsLogger.info("Saved {} byte file to: {}", fileContents.length, f.getAbsolutePath()); - + public static void openLink(String url) { + URI safeURL; try { - Desktop.getDesktop().open(downloadsDirectory); - }catch(Throwable t) { + safeURL = new URI(url); + String proto = safeURL.getScheme(); + if (!proto.equalsIgnoreCase("http") && !proto.equalsIgnoreCase("https")) { + throw new IllegalArgumentException("Suspicious protocol: " + proto); + } + } catch (URISyntaxException | IllegalArgumentException ex) { + PlatformRuntime.logger.error("Refusing to open invalid URL: {}", url); + PlatformRuntime.logger.error(ex); + return; + } + try { + Desktop.getDesktop().browse(safeURL); + } catch (Throwable var5) { + PlatformRuntime.logger.error("Failed to browse to URL: {}", safeURL.toString()); + PlatformRuntime.logger.error(var5); } } - public static void addLogMessage(String logMessage, boolean isError) { - + private static void runDisplayFileChooser(String mime, String ext) { + try { + JFileChooser fc = new FileChooserAlwaysOnTop((new File(".")).getAbsoluteFile()); + fc.setDialogTitle("select a file"); + fc.setFileSelectionMode(JFileChooser.FILES_ONLY); + fc.setMultiSelectionEnabled(false); + fc.setFileFilter(new FileFilterExt(ext)); + if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { + File f = fc.getSelectedFile(); + if (f != null) { + String name = f.getName(); + byte[] bytes = new byte[(int) f.length()]; + try (FileInputStream is = new FileInputStream(f)) { + is.read(bytes); + } + fileChooserResultObject = new FileChooserResult(name, bytes); + } else { + fileChooserResultObject = null; + } + } + } catch (Throwable t) { + fileChooserResultObject = null; + } + fileChooserOpen = false; + fileChooserHasResult = true; } - public static boolean isShowingDebugConsole() { - return false; + public static String saveScreenshot() { + if (!screeshotsDir.isDirectory() && !screeshotsDir.mkdirs()) { + PlatformRuntime.logger.error("Failed to create screenshots directory: {}", screeshotsDir.getAbsolutePath()); + return "nothing"; + } + String name = "screenshot_" + dateFormatSS.format(new Date()).toString() + ".png"; + int w = PlatformInput.getWindowWidth(); + int h = PlatformInput.getWindowHeight(); + ByteBuffer screenshotBuffer = PlatformRuntime.allocateByteBuffer(w * h * 4); + PlatformOpenGL._wglReadPixels(0, 0, w, h, RealOpenGLEnums.GL_RGBA, RealOpenGLEnums.GL_UNSIGNED_BYTE, + screenshotBuffer); + BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); + int i; + for (int y = 0; y < h; ++y) { + for (int x = 0; x < w; ++x) { + i = (x + (h - y - 1) * w) << 2; + bufferedImage.setRGB(x, y, + ((screenshotBuffer.get(i) & 0xFF) << 16) | ((screenshotBuffer.get(i + 1) & 0xFF) << 8) + | (screenshotBuffer.get(i + 2) & 0xFF) | 0xFF000000); + } + } + PlatformRuntime.freeByteBuffer(screenshotBuffer); + File screenshotFile = new File(screeshotsDir, name); + try { + ImageIO.write(bufferedImage, "PNG", screenshotFile); + } catch (IOException ex) { + PlatformRuntime.logger.error("Failed to write screenshot: {}", screenshotFile.getAbsolutePath()); + return "nothing"; + } + PlatformRuntime.logger.info("Saved screenshot to: {}", screenshotFile.getAbsolutePath()); + return name; } - public static void showDebugConsole() { - + public static void setClipboard(String text) { + glfwSetClipboardString(win, text); + } + + public static void setLocalStorage(String name, byte[] data) { + setLocalStorage(name, data, true); + } + + public static void setLocalStorage(String name, byte[] data, boolean hooks) { + if (data == null) { + (new File("_eagstorage." + name + ".dat")).delete(); + } else { + try (FileOutputStream f = new FileOutputStream(new File("_eagstorage." + name + ".dat"))) { + f.write(data); + } catch (IOException e) { + EagRuntime.debugPrintStackTrace(e); + } + } } public static void setMCServerWindowGlobal(String str) { - + + } + + public static void showDebugConsole() { + + } + + public static void showPopup(String msg) { + JOptionPane pane = new JOptionPane(msg, JOptionPane.WARNING_MESSAGE, JOptionPane.DEFAULT_OPTION, null, + new Object[] { "OK" }, "OK"); + pane.setInitialValue("OK"); + JDialog dialog = pane.createDialog("EaglercraftX Runtime"); + pane.selectInitialValue(); + dialog.setIconImage(Toolkit.getDefaultToolkit().getImage("icon32.png")); + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + dialog.setAlwaysOnTop(true); + dialog.setModal(true); + dialog.setLocationByPlatform(true); + dialog.setModalExclusionType(ModalExclusionType.TOOLKIT_EXCLUDE); + dialog.setModalityType(ModalityType.TOOLKIT_MODAL); + dialog.setLocationRelativeTo(null); + dialog.setVisible(true); } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAssets.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAssets.java index 54eb330d..02d1fd21 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAssets.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAssets.java @@ -16,78 +16,50 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformAssets { - + static URL getDesktopResourceURL(String path) { File f = new File("resources", path); - if(f.isFile()) { + if (f.isFile()) { try { return f.toURI().toURL(); } catch (MalformedURLException e) { return null; } - }else { + } else { return null; } } - - public static boolean getResourceExists(String path) { - return (new File("resources", path)).isFile(); - } - + public static byte[] getResourceBytes(String path) { File loadFile = new File("resources", path); byte[] ret = new byte[(int) loadFile.length()]; - try(FileInputStream is = new FileInputStream(loadFile)) { + try (FileInputStream is = new FileInputStream(loadFile)) { int i, j = 0; - while(j < ret.length && (i = is.read(ret, j, ret.length - j)) != -1) { + while (j < ret.length && (i = is.read(ret, j, ret.length - j)) != -1) { j += i; } return ret; - }catch(IOException ex) { + } catch (IOException ex) { return null; } } - public static ImageData loadImageFile(InputStream data) { - return loadImageFile(data, "image/png"); - } - - public static ImageData loadImageFile(InputStream data, String mime) { - try { - BufferedImage img = ImageIO.read(data); - if(img == null) { - throw new IOException("Data is not a supported image format!"); - } - int w = img.getWidth(); - int h = img.getHeight(); - boolean a = img.getColorModel().hasAlpha(); - int[] pixels = new int[w * h]; - img.getRGB(0, 0, w, h, pixels, 0, w); - for(int i = 0; i < pixels.length; ++i) { - int j = pixels[i]; - if(!a) { - j = j | 0xFF000000; - } - pixels[i] = (j & 0xFF00FF00) | ((j & 0x00FF0000) >>> 16) | - ((j & 0x000000FF) << 16); - } - return new ImageData(w, h, pixels, a); - }catch(IOException ex) { - return null; - } + public static boolean getResourceExists(String path) { + return (new File("resources", path)).isFile(); } public static ImageData loadImageFile(byte[] data) { @@ -98,4 +70,32 @@ public class PlatformAssets { return loadImageFile(new EaglerInputStream(data), mime); } + public static ImageData loadImageFile(InputStream data) { + return loadImageFile(data, "image/png"); + } + + public static ImageData loadImageFile(InputStream data, String mime) { + try { + BufferedImage img = ImageIO.read(data); + if (img == null) { + throw new IOException("Data is not a supported image format!"); + } + int w = img.getWidth(); + int h = img.getHeight(); + boolean a = img.getColorModel().hasAlpha(); + int[] pixels = new int[w * h]; + img.getRGB(0, 0, w, h, pixels, 0, w); + for (int i = 0; i < pixels.length; ++i) { + int j = pixels[i]; + if (!a) { + j = j | 0xFF000000; + } + pixels[i] = (j & 0xFF00FF00) | ((j & 0x00FF0000) >>> 16) | ((j & 0x000000FF) << 16); + } + return new ImageData(w, h, pixels, a); + } catch (IOException ex) { + return null; + } + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAudio.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAudio.java index 0656d64f..41e36c91 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAudio.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformAudio.java @@ -15,53 +15,68 @@ import paulscode.sound.codecs.CodecWav; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformAudio { - - protected static class PaulscodeAudioResource implements IAudioResource { - - protected final URL resourceLoc; - - protected PaulscodeAudioResource(URL resourceLoc) { - this.resourceLoc = resourceLoc; - } - + + public static interface IAudioCacheLoader { + byte[] loadFile(String filename); } - + protected static class PaulscodeAudioHandle implements IAudioHandle { - + protected final String sourceName; protected long stall; - + protected PaulscodeAudioHandle(String sourceName) { this.sourceName = sourceName; this.stall = PlatformRuntime.steadyTimeMillis(); } + @Override + public void end() { + sndSystem.stop(sourceName); + } + + @Override + public void gain(float f) { + sndSystem.setVolume(sourceName, f); + } + + @Override + public void move(float x, float y, float z) { + sndSystem.setPosition(sourceName, x, y, z); + } + @Override public void pause(boolean setPaused) { - if(setPaused) { - if(sndSystem.playing(sourceName)) { + if (setPaused) { + if (sndSystem.playing(sourceName)) { sndSystem.pause(sourceName); } - }else { - if(!sndSystem.playing(sourceName)) { + } else { + if (!sndSystem.playing(sourceName)) { sndSystem.play(sourceName); } } } + @Override + public void pitch(float f) { + sndSystem.setPitch(sourceName, f); + } + @Override public void restart() { this.stall = PlatformRuntime.steadyTimeMillis(); @@ -69,61 +84,95 @@ public class PlatformAudio { sndSystem.play(sourceName); } - @Override - public void move(float x, float y, float z) { - sndSystem.setPosition(sourceName, x, y, z); - } - - @Override - public void pitch(float f) { - sndSystem.setPitch(sourceName, f); - } - - @Override - public void gain(float f) { - sndSystem.setVolume(sourceName, f); - } - - @Override - public void end() { - sndSystem.stop(sourceName); - } - @Override public boolean shouldFree() { - return !sndSystem.playing(sourceName) && PlatformRuntime.steadyTimeMillis() - this.stall > 250l; //TODO: I hate this hack + return !sndSystem.playing(sourceName) && PlatformRuntime.steadyTimeMillis() - this.stall > 250l; // TODO: I + // hate + // this + // hack } - + } - - public static IAudioResource loadAudioData(String filename, boolean holdInCache) { - URL ret = PlatformAssets.getDesktopResourceURL(filename); - if(ret != null) { - return new PaulscodeAudioResource(ret); - }else { + + protected static class PaulscodeAudioResource implements IAudioResource { + + protected final URL resourceLoc; + + protected PaulscodeAudioResource(URL resourceLoc) { + this.resourceLoc = resourceLoc; + } + + } + + private static final Logger logger = LogManager.getLogger("EaglercraftPlatformAudio"); + + private static SoundSystem sndSystem = null; + + private static int sourceCounter = 0; + + public static boolean available() { + return sndSystem != null; + } + + public static IAudioHandle beginPlayback(IAudioResource track, float x, float y, float z, float volume, + float pitch) { + if (sndSystem == null) { return null; } + + float f1 = 16.0F; + if (volume > 1.0F) { + f1 *= volume; + } + + String srcName = "src" + ++sourceCounter; + sndSystem.newSource(false, srcName, ((PaulscodeAudioResource) track).resourceLoc, + ((PaulscodeAudioResource) track).resourceLoc.getPath(), false, x, y, z, 2, f1); + sndSystem.setTemporary(srcName, true); + sndSystem.setPitch(srcName, pitch); + sndSystem.setVolume(srcName, volume); + sndSystem.play(srcName); + + return new PaulscodeAudioHandle(srcName); } - + + public static IAudioHandle beginPlaybackStatic(IAudioResource track, float volume, float pitch) { + if (sndSystem == null) { + return null; + } + + String srcName = "src" + ++sourceCounter; + sndSystem.newSource(false, srcName, ((PaulscodeAudioResource) track).resourceLoc, + ((PaulscodeAudioResource) track).resourceLoc.getPath(), false, 0.0f, 0.0f, 0.0f, 0, 0.0f); + sndSystem.setTemporary(srcName, true); + sndSystem.setPitch(srcName, pitch); + sndSystem.setVolume(srcName, volume); + sndSystem.play(srcName); + + return new PaulscodeAudioHandle(srcName); + } + public static void clearAudioCache() { // browser only } public static void flushAudioCache() { - + } - public static interface IAudioCacheLoader { - byte[] loadFile(String filename); + public static IAudioResource loadAudioData(String filename, boolean holdInCache) { + URL ret = PlatformAssets.getDesktopResourceURL(filename); + if (ret != null) { + return new PaulscodeAudioResource(ret); + } else { + return null; + } } public static IAudioResource loadAudioDataNew(String filename, boolean holdInCache, IAudioCacheLoader loader) { throw new UnsupportedOperationException("Browser only!"); } - - private static final Logger logger = LogManager.getLogger("EaglercraftPlatformAudio"); - private static SoundSystem sndSystem = null; - + static void platformInitialize() { logger.info("Eaglercraft uses Paul Lamb's SoundSystem (with LWJGL3)"); logger.info(" \"Author: Paul Lamb, www.paulscode.com\""); @@ -132,84 +181,42 @@ public class PlatformAudio { SoundSystemConfig.setCodec("ogg", CodecJOrbis.class); SoundSystemConfig.setCodec("wav", CodecWav.class); SoundSystemConfig.setLogger(new SoundSystemLogger() { - public void message(String parString1, int parInt1) { - if (!parString1.isEmpty()) { - logger.info(parString1); - } - } - public void importantMessage(String parString1, int parInt1) { - if (!parString1.isEmpty()) { - logger.warn(parString1); - } - } public void errorMessage(String parString1, String parString2, int parInt1) { if (!parString2.isEmpty()) { logger.error("Error in class \"{}\"!", parString1); logger.error(parString2); } } + + public void importantMessage(String parString1, int parInt1) { + if (!parString1.isEmpty()) { + logger.warn(parString1); + } + } + + public void message(String parString1, int parInt1) { + if (!parString1.isEmpty()) { + logger.info(parString1); + } + } }); sndSystem = new SoundSystem(); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Could not initialize Paulscode SoundSystem! Is this system's OpenAL installed correctly?"); logger.error(t); sndSystem = null; } } - + static void platformShutdown() { - if(sndSystem != null) { + if (sndSystem != null) { sndSystem.cleanup(); sndSystem = null; } } - - public static boolean available() { - return sndSystem != null; - } - - private static int sourceCounter = 0; - - public static IAudioHandle beginPlayback(IAudioResource track, float x, float y, float z, - float volume, float pitch) { - if(sndSystem == null) { - return null; - } - - float f1 = 16.0F; - if (volume > 1.0F) { - f1 *= volume; - } - - String srcName = "src" + ++sourceCounter; - sndSystem.newSource(false, srcName, ((PaulscodeAudioResource)track).resourceLoc, - ((PaulscodeAudioResource)track).resourceLoc.getPath(), false, x, y, z, 2, f1); - sndSystem.setTemporary(srcName, true); - sndSystem.setPitch(srcName, pitch); - sndSystem.setVolume(srcName, volume); - sndSystem.play(srcName); - - return new PaulscodeAudioHandle(srcName); - } - - public static IAudioHandle beginPlaybackStatic(IAudioResource track, float volume, float pitch) { - if(sndSystem == null) { - return null; - } - - String srcName = "src" + ++sourceCounter; - sndSystem.newSource(false, srcName, ((PaulscodeAudioResource)track).resourceLoc, - ((PaulscodeAudioResource)track).resourceLoc.getPath(), false, 0.0f, 0.0f, 0.0f, 0, 0.0f); - sndSystem.setTemporary(srcName, true); - sndSystem.setPitch(srcName, pitch); - sndSystem.setVolume(srcName, volume); - sndSystem.play(srcName); - - return new PaulscodeAudioHandle(srcName); - } - + public static void setListener(float x, float y, float z, float pitchDegrees, float yawDegrees) { - if(sndSystem == null) { + if (sndSystem == null) { return; } float f2 = MathHelper.cos((yawDegrees + 90.0F) * 0.017453292F); diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformFilesystem.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformFilesystem.java index c8562c58..33058896 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformFilesystem.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformFilesystem.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,7 +36,8 @@ public class PlatformFilesystem { private static final boolean isLegacyFolder = checkLegacy(); private static boolean checkLegacy() { - if(!debugFilesystemRoot.isDirectory()) return false; + if (!debugFilesystemRoot.isDirectory()) + return false; String[] str = debugFilesystemRoot.list(); return str != null && str.length > 0; } @@ -43,29 +45,33 @@ public class PlatformFilesystem { public static IEaglerFilesystem initializePersist(String dbName) { String jdbcUri = System.getProperty("eagler.jdbc." + dbName + ".uri"); String jdbcDriver = System.getProperty("eagler.jdbc." + dbName + ".driver"); - if(jdbcUri != null && jdbcDriver != null) { + if (jdbcUri != null && jdbcDriver != null) { try { IEaglerFilesystem provider = JDBCFilesystem.initialize(dbName, jdbcUri, jdbcDriver); - if(((JDBCFilesystem)provider).isNewFilesystem() && debugFilesystemRoot.isDirectory() && debugFilesystemRoot.list().length > 0) { - JDBCFilesystemConverter.convertFilesystem("Converting filesystem, please wait...", debugFilesystemRoot, provider, true); + if (((JDBCFilesystem) provider).isNewFilesystem() && debugFilesystemRoot.isDirectory() + && debugFilesystemRoot.list().length > 0) { + JDBCFilesystemConverter.convertFilesystem("Converting filesystem, please wait...", + debugFilesystemRoot, provider, true); } return provider; - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Could not open jdbc-based filesystem: {}", dbName); logger.error(t); return null; } - }else { + } else { File f; - if(isLegacyFolder && (dbName.equals("worlds") || dbName.equals("resourcePacks"))) { + if (isLegacyFolder && (dbName.equals("worlds") || dbName.equals("resourcePacks"))) { f = debugFilesystemRoot; - logger.info("Note: filesystem \"{}\" will be stored in the legacy \"sp\" folder because it exists and is not empty", dbName); - }else { + logger.info( + "Note: filesystem \"{}\" will be stored in the legacy \"sp\" folder because it exists and is not empty", + dbName); + } else { f = new File(filesystemsRoot, dbName); } try { return DebugFilesystem.initialize(dbName, f); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Could not open folder-based filesystem: {}", dbName); logger.error(t); return null; diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java index d8d15cd5..5bc7e413 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java @@ -1,6 +1,62 @@ package net.lax1dude.eaglercraft.v1_8.internal; -import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.glfw.GLFW.GLFW_ARROW_CURSOR; +import static org.lwjgl.glfw.GLFW.GLFW_CURSOR; +import static org.lwjgl.glfw.GLFW.GLFW_CURSOR_DISABLED; +import static org.lwjgl.glfw.GLFW.GLFW_CURSOR_NORMAL; +import static org.lwjgl.glfw.GLFW.GLFW_DISCONNECTED; +import static org.lwjgl.glfw.GLFW.GLFW_FALSE; +import static org.lwjgl.glfw.GLFW.GLFW_HAND_CURSOR; +import static org.lwjgl.glfw.GLFW.GLFW_IBEAM_CURSOR; +import static org.lwjgl.glfw.GLFW.GLFW_ICONIFIED; +import static org.lwjgl.glfw.GLFW.GLFW_JOYSTICK_1; +import static org.lwjgl.glfw.GLFW.GLFW_JOYSTICK_16; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_1; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_9; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_F; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_F1; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_F11; +import static org.lwjgl.glfw.GLFW.GLFW_KEY_F9; +import static org.lwjgl.glfw.GLFW.GLFW_PRESS; +import static org.lwjgl.glfw.GLFW.GLFW_RAW_MOUSE_MOTION; +import static org.lwjgl.glfw.GLFW.GLFW_RELEASE; +import static org.lwjgl.glfw.GLFW.GLFW_REPEAT; +import static org.lwjgl.glfw.GLFW.GLFW_TRUE; +import static org.lwjgl.glfw.GLFW.glfwCreateStandardCursor; +import static org.lwjgl.glfw.GLFW.glfwGetFramebufferSize; +import static org.lwjgl.glfw.GLFW.glfwGetGamepadName; +import static org.lwjgl.glfw.GLFW.glfwGetGamepadState; +import static org.lwjgl.glfw.GLFW.glfwGetJoystickGUID; +import static org.lwjgl.glfw.GLFW.glfwGetJoystickName; +import static org.lwjgl.glfw.GLFW.glfwGetKey; +import static org.lwjgl.glfw.GLFW.glfwGetMonitorPos; +import static org.lwjgl.glfw.GLFW.glfwGetMonitors; +import static org.lwjgl.glfw.GLFW.glfwGetMouseButton; +import static org.lwjgl.glfw.GLFW.glfwGetVideoMode; +import static org.lwjgl.glfw.GLFW.glfwGetWindowAttrib; +import static org.lwjgl.glfw.GLFW.glfwGetWindowContentScale; +import static org.lwjgl.glfw.GLFW.glfwGetWindowPos; +import static org.lwjgl.glfw.GLFW.glfwGetWindowSize; +import static org.lwjgl.glfw.GLFW.glfwJoystickIsGamepad; +import static org.lwjgl.glfw.GLFW.glfwPollEvents; +import static org.lwjgl.glfw.GLFW.glfwRawMouseMotionSupported; +import static org.lwjgl.glfw.GLFW.glfwSetCharCallback; +import static org.lwjgl.glfw.GLFW.glfwSetCursor; +import static org.lwjgl.glfw.GLFW.glfwSetCursorEnterCallback; +import static org.lwjgl.glfw.GLFW.glfwSetCursorPos; +import static org.lwjgl.glfw.GLFW.glfwSetCursorPosCallback; +import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback; +import static org.lwjgl.glfw.GLFW.glfwSetFramebufferSizeCallback; +import static org.lwjgl.glfw.GLFW.glfwSetInputMode; +import static org.lwjgl.glfw.GLFW.glfwSetJoystickCallback; +import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback; +import static org.lwjgl.glfw.GLFW.glfwSetMouseButtonCallback; +import static org.lwjgl.glfw.GLFW.glfwSetScrollCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowFocusCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowMonitor; +import static org.lwjgl.glfw.GLFW.glfwSwapBuffers; +import static org.lwjgl.glfw.GLFW.glfwSwapInterval; +import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose; import java.util.ArrayList; import java.util.HashSet; @@ -17,116 +73,33 @@ import org.lwjgl.system.MemoryStack; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformInput { - - private static long win = 0l; - private static long cursorDefault = 0l; - private static long cursorHand = 0l; - private static long cursorText = 0l; - - private static boolean windowFocused = true; - private static boolean windowResized = true; - private static boolean windowResized2 = true; - - private static boolean windowCursorEntered = true; - private static boolean windowMouseGrabbed = false; - private static int cursorX = 0; - private static int cursorY = 0; - private static int cursorDX = 0; - private static int cursorDY = 0; - private static int DWheel = 0; - - private static int windowWidth = 640; - private static int windowHeight = 480; - - private static final List keyboardEventList = new LinkedList<>(); - private static KeyboardEvent currentKeyboardEvent = null; - - private static final char[] keyboardReleaseEventChars = new char[256]; - - private static boolean enableRepeatEvents = false; - private static int functionKeyModifier = GLFW_KEY_F; - - public static boolean lockKeys = false; - - private static final List keyboardCharList = new LinkedList<>(); - - private static boolean vsync = true; - private static boolean glfwVSyncState = false; - - private static class KeyboardEvent { - - protected final int key; - protected final boolean pressed; - protected final boolean repeating; - protected char resolvedCharacter = '\0'; - - protected KeyboardEvent(int key, boolean pressed, boolean repeating) { - this.key = key; - this.pressed = pressed; - this.repeating = repeating; - } - - } - - private static final List mouseEventList = new LinkedList<>(); - private static MouseEvent currentMouseEvent = null; - - private static class MouseEvent { - - protected final int button; - protected final boolean pressed; - protected final int posX; - protected final int posY; - protected final float wheel; - - protected MouseEvent(int button, boolean pressed, int posX, int posY, float wheel) { - this.button = button; - this.pressed = pressed; - this.posX = posX; - this.posY = posY; - this.wheel = wheel; - } - - } - - private static final List gamepadList = new ArrayList<>(); - private static int selectedGamepad = -1; - private static String selectedGamepadName = null; - private static String selectedGamepadUUID = null; - private static final boolean[] gamepadButtonStates = new boolean[24]; - private static final float[] gamepadAxisStates = new float[4]; - private static class Gamepad { - + protected final int gamepadId; protected final String gamepadName; protected final String gamepadUUID; - + protected Gamepad(int gamepadId, String gamepadName, String gamepadUUID) { this.gamepadId = gamepadId; this.gamepadName = gamepadName; this.gamepadUUID = gamepadUUID; } - @Override - public int hashCode() { - return Objects.hash(gamepadId, gamepadName, gamepadUUID); - } - @Override public boolean equals(Object obj) { if (this == obj) @@ -139,451 +112,250 @@ public class PlatformInput { return gamepadId == other.gamepadId && Objects.equals(gamepadName, other.gamepadName) && Objects.equals(gamepadUUID, other.gamepadUUID); } - } - static void initHooks(long glfwWindow) { - win = glfwWindow; - - glfwSetErrorCallback((arg0, arg1) -> { - String errorString = ""; - if(arg1 != 0l) { - try(MemoryStack stack = MemoryStack.stackPush()) { - PointerBuffer pbuffer = stack.mallocPointer(1); - pbuffer.put(0, arg1); - errorString = pbuffer.getStringUTF8(0); - } - } - PlatformRuntime.logger.error("GLFW Error #{}: {}", arg0, errorString); - }); - - if(!glfwRawMouseMotionSupported()) { - throw new UnsupportedOperationException("Raw mouse movement (cursor lock) is not supported!"); - } - - int[] v1 = new int[1], v2 = new int[1]; - glfwGetFramebufferSize(glfwWindow, v1, v2); - - windowWidth = v1[0]; - windowHeight = v2[0]; - windowResized = true; - windowResized2 = true; - - glfwSetFramebufferSizeCallback(glfwWindow, (window, width, height) -> { - if(windowWidth != width || windowHeight != height) { - windowWidth = width; - windowHeight = height; - windowResized = true; - windowResized2 = true; - } - }); - - windowFocused = true; - - glfwSetWindowFocusCallback(glfwWindow, (window, focused) -> { - windowFocused = focused; - }); - - glfwSetKeyCallback(glfwWindow, (window, key, scancode, action, mods) -> { - if (key == GLFW_KEY_F11 && action == GLFW_PRESS) { - toggleFullscreen(); - } - if(glfwGetKey(glfwWindow, functionKeyModifier) == GLFW_PRESS) { - if(key >= GLFW_KEY_1 && key <= GLFW_KEY_9) { - key = key - GLFW_KEY_1 + GLFW_KEY_F1; - } - } - key = KeyboardConstants.getEaglerKeyFromGLFW(key); - keyboardEventList.add(new KeyboardEvent(key, action != GLFW_RELEASE, action == GLFW_REPEAT)); - if(keyboardEventList.size() > 64) { - keyboardEventList.remove(0); - } - }); - - glfwSetCharCallback(glfwWindow, (window, character) -> { - keyboardCharList.add(Character.valueOf((char)character)); - if(keyboardCharList.size() > 64) { - keyboardCharList.remove(0); - } - }); - - glfwSetCursorPosCallback(glfwWindow, (window, posX, posY) -> { - posY = windowHeight - posY; - if(windowMouseGrabbed) { - cursorDX -= (cursorX - (int)posX); - cursorDY -= (cursorY - (int)posY); - cursorX = (int)posX; - cursorY = (int)posY; - }else { - cursorX = (int)posX; - cursorY = (int)posY; - mouseEventList.add(new MouseEvent(-1, false, cursorX, cursorY, 0.0f)); - if(mouseEventList.size() > 64) { - mouseEventList.remove(0); - } - } - }); - - glfwSetMouseButtonCallback(glfwWindow, (window, button, action, mods) -> { - mouseEventList.add(new MouseEvent(button, action != GLFW_RELEASE, cursorX, cursorY, 0.0f)); - if(mouseEventList.size() > 64) { - mouseEventList.remove(0); - } - }); - - glfwSetCursorEnterCallback(glfwWindow, (window, enter) -> { - windowCursorEntered = enter; - }); - - glfwSetScrollCallback(glfwWindow, (window, scrollX, scrollY) -> { - DWheel += (int)scrollY; - mouseEventList.add(new MouseEvent(-1, false, cursorX, cursorY, (float)scrollY)); - if(mouseEventList.size() > 64) { - mouseEventList.remove(0); - } - }); - - cursorDefault = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); - cursorHand = glfwCreateStandardCursor(GLFW_HAND_CURSOR); - cursorText = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); - glfwSetCursor(glfwWindow, cursorDefault); - - if(!fullscreen && startupFullscreen) { - toggleFullscreen(); - } - - gamepadEnumerateDevices(); - - glfwSetJoystickCallback((jid, event) -> { - if(event == GLFW_DISCONNECTED && jid == selectedGamepad) { - selectedGamepad = -1; - } - gamepadEnumerateDevices(); - }); - } - - public static int getWindowWidth() { - return windowWidth; - } - - public static int getWindowHeight() { - return windowHeight; - } - - public static int getVisualViewportX() { - return 0; - } - - public static int getVisualViewportY() { - return 0; - } - - public static int getVisualViewportW() { - return windowWidth; - } - - public static int getVisualViewportH() { - return windowHeight; - } - - public static boolean getWindowFocused() { - return windowFocused; - } - - public static boolean isCloseRequested() { - return glfwWindowShouldClose(win); - } - - public static void setVSync(boolean enable) { - vsync = enable; - } - - public static void update() { - glfwPollEvents(); - if(vsync != glfwVSyncState) { - glfwSwapInterval(vsync ? 1 : 0); - glfwVSyncState = vsync; - } - glfwSwapBuffers(win); - } - - public static boolean isVSyncSupported() { - return true; - } - - public static boolean wasResized() { - boolean b = windowResized; - windowResized = false; - return b; - } - - public static boolean wasVisualViewportResized() { - boolean b = windowResized2; - windowResized2 = false; - return b; - } - - public static boolean keyboardNext() { - if(keyboardEventList.size() > 0) { - currentKeyboardEvent = keyboardEventList.remove(0); - if(currentKeyboardEvent.resolvedCharacter == '\0' && KeyboardConstants - .getKeyCharFromEagler(currentKeyboardEvent.key) != '\0') { - if(currentKeyboardEvent.pressed && keyboardCharList.size() > 0) { - currentKeyboardEvent.resolvedCharacter = keyboardCharList.remove(0); - keyboardReleaseEventChars[currentKeyboardEvent.key] = - currentKeyboardEvent.resolvedCharacter; - }else if(!currentKeyboardEvent.pressed) { - currentKeyboardEvent.resolvedCharacter = - keyboardReleaseEventChars[currentKeyboardEvent.key]; - keyboardReleaseEventChars[currentKeyboardEvent.key] = '\0'; - } - } - if(currentKeyboardEvent.repeating && !enableRepeatEvents) { - return keyboardNext(); - }else { - return true; - } - }else { - if(keyboardCharList.size() > 0) { - currentKeyboardEvent = new KeyboardEvent(KeyboardConstants.KEY_SPACE, true, false); - currentKeyboardEvent.resolvedCharacter = keyboardCharList.remove(0); - KeyboardEvent releaseEvent = new KeyboardEvent(KeyboardConstants.KEY_SPACE, false, false); - releaseEvent.resolvedCharacter = currentKeyboardEvent.resolvedCharacter; - keyboardEventList.add(releaseEvent); - return true; - }else { - return false; - } + @Override + public int hashCode() { + return Objects.hash(gamepadId, gamepadName, gamepadUUID); } } - public static void keyboardFireEvent(EnumFireKeyboardEvent eventType, int eagKey, char keyChar) { - switch(eventType) { - case KEY_DOWN: - keyboardCharList.add(keyChar); - keyboardEventList.add(new KeyboardEvent(eagKey, true, false)); - break; - case KEY_UP: - if(eagKey >= 0 && eagKey < keyboardReleaseEventChars.length) { - keyboardReleaseEventChars[eagKey] = keyChar; - } - keyboardEventList.add(new KeyboardEvent(eagKey, false, false)); - break; - case KEY_REPEAT: - keyboardCharList.add(keyChar); - keyboardEventList.add(new KeyboardEvent(eagKey, true, true)); - break; - default: - throw new UnsupportedOperationException(); + private static class KeyboardEvent { + + protected final int key; + protected final boolean pressed; + protected final boolean repeating; + protected char resolvedCharacter = '\0'; + + protected KeyboardEvent(int key, boolean pressed, boolean repeating) { + this.key = key; + this.pressed = pressed; + this.repeating = repeating; } - if(keyboardEventList.size() > 64) { - keyboardEventList.remove(0); - } - if(keyboardCharList.size() > 64) { - keyboardCharList.remove(0); + + } + + private static class MouseEvent { + + protected final int button; + protected final boolean pressed; + protected final int posX; + protected final int posY; + protected final float wheel; + + protected MouseEvent(int button, boolean pressed, int posX, int posY, float wheel) { + this.button = button; + this.pressed = pressed; + this.posX = posX; + this.posY = posY; + this.wheel = wheel; } + } - public static boolean keyboardGetEventKeyState() { - return currentKeyboardEvent.pressed; - } + private static long win = 0l; - public static int keyboardGetEventKey() { - return currentKeyboardEvent.key; - } + private static long cursorDefault = 0l; + private static long cursorHand = 0l; + private static long cursorText = 0l; - public static char keyboardGetEventCharacter() { - return currentKeyboardEvent.resolvedCharacter; - } + private static boolean windowFocused = true; + private static boolean windowResized = true; + private static boolean windowResized2 = true; + private static boolean windowCursorEntered = true; + private static boolean windowMouseGrabbed = false; + private static int cursorX = 0; + private static int cursorY = 0; - public static boolean keyboardIsKeyDown(int key) { - if(glfwGetKey(win, functionKeyModifier) == GLFW_PRESS) { - if(key >= GLFW_KEY_1 && key <= GLFW_KEY_9) { - return false; - } - if(key >= GLFW_KEY_F1 && key <= GLFW_KEY_F9) { - key = key - GLFW_KEY_F1 + GLFW_KEY_1; - } - } - return glfwGetKey(win, KeyboardConstants.getGLFWKeyFromEagler(key)) == GLFW_PRESS; - } + private static int cursorDX = 0; + private static int cursorDY = 0; - public static boolean keyboardIsRepeatEvent() { - return currentKeyboardEvent.repeating; - } + private static int DWheel = 0; + private static int windowWidth = 640; - public static void keyboardEnableRepeatEvents(boolean b) { - enableRepeatEvents = b; - } + private static int windowHeight = 480; - public static boolean mouseNext() { - if(mouseEventList.size() > 0) { - currentMouseEvent = mouseEventList.remove(0); - return true; - }else { - return false; - } - } + private static final List keyboardEventList = new LinkedList<>(); + private static KeyboardEvent currentKeyboardEvent = null; - public static void mouseFireMoveEvent(EnumFireMouseEvent eventType, int posX, int posY) { - if(eventType == EnumFireMouseEvent.MOUSE_MOVE) { - mouseEventList.add(new MouseEvent(-1, false, posX, posY, 0.0f)); - if(mouseEventList.size() > 64) { - mouseEventList.remove(0); - } - }else { - throw new UnsupportedOperationException(); - } - } + private static final char[] keyboardReleaseEventChars = new char[256]; - public static void mouseFireButtonEvent(EnumFireMouseEvent eventType, int posX, int posY, int button) { - switch(eventType) { - case MOUSE_DOWN: - mouseEventList.add(new MouseEvent(button, true, posX, posY, 0.0f)); - break; - case MOUSE_UP: - mouseEventList.add(new MouseEvent(button, false, posX, posY, 0.0f)); - break; - default: - throw new UnsupportedOperationException(); - } - if(mouseEventList.size() > 64) { - mouseEventList.remove(0); - } - } + private static boolean enableRepeatEvents = false; - public static void mouseFireWheelEvent(EnumFireMouseEvent eventType, int posX, int posY, float wheel) { - if(eventType == EnumFireMouseEvent.MOUSE_WHEEL) { - mouseEventList.add(new MouseEvent(-1, false, posX, posY, wheel)); - if(mouseEventList.size() > 64) { - mouseEventList.remove(0); - } - }else { - throw new UnsupportedOperationException(); - } - } + private static int functionKeyModifier = GLFW_KEY_F; + public static boolean lockKeys = false; - public static boolean mouseGetEventButtonState() { - return currentMouseEvent.pressed; - } + private static final List keyboardCharList = new LinkedList<>(); - public static int mouseGetEventButton() { - return currentMouseEvent.button; - } + private static boolean vsync = true; + private static boolean glfwVSyncState = false; - public static int mouseGetEventX() { - return currentMouseEvent.posX; - } + private static final List mouseEventList = new LinkedList<>(); - public static int mouseGetEventY() { - return currentMouseEvent.posY; - } + private static MouseEvent currentMouseEvent = null; + private static final List gamepadList = new ArrayList<>(); + private static int selectedGamepad = -1; + private static String selectedGamepadName = null; + private static String selectedGamepadUUID = null; + private static final boolean[] gamepadButtonStates = new boolean[24]; - public static int mouseGetEventDWheel() { - return (int)currentMouseEvent.wheel; - } + private static final float[] gamepadAxisStates = new float[4]; - public static int mouseGetX() { - return cursorX; - } + private static boolean fullscreen = false; - public static int mouseGetY() { - return cursorY; - } + private static boolean startupFullscreen = false; - public static boolean mouseIsButtonDown(int i) { - return glfwGetMouseButton(win, i) == GLFW_PRESS; - } + private static int[] lastPos = new int[4]; - public static int mouseGetDWheel() { - int i = DWheel; - DWheel = 0; - return i; - } - - public static void mouseSetGrabbed(boolean grab) { - if(grab != windowMouseGrabbed) { - cursorX = windowWidth / 2; - cursorY = windowHeight / 2; - glfwSetCursorPos(win, cursorX, cursorY); - windowMouseGrabbed = grab; - cursorDX = 0; - cursorDY = 0; - glfwSetInputMode(win, GLFW_CURSOR, grab ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); - glfwSetInputMode(win, GLFW_RAW_MOUSE_MOTION, grab ? GLFW_TRUE : GLFW_FALSE); - } - } - - public static boolean mouseGrabSupported() { - return true; - } - - public static boolean isPointerLocked() { - return windowMouseGrabbed; - } - - public static boolean isMouseGrabbed() { - return windowMouseGrabbed; - } - - public static int mouseGetDX() { - int i = cursorDX; - cursorDX = 0; - return i; - } - - public static int mouseGetDY() { - int i = cursorDY; - cursorDY = 0; - return i; - } - - public static void mouseSetCursorPosition(int x, int y) { - cursorX = x; - cursorY = y; - glfwSetCursorPos(win, x, y); - } - - public static boolean mouseIsInsideWindow() { - return windowCursorEntered; - } - public static boolean contextLost() { return glfwGetWindowAttrib(win, GLFW_ICONIFIED) == GLFW_TRUE; } - public static void setFunctionKeyModifier(int key) { - functionKeyModifier = KeyboardConstants.getGLFWKeyFromEagler(key); + private static int fixWheel(float val) { + return (val > 0.0f ? 1 : (val < 0.0f ? -1 : 0)); } - public static boolean supportsFullscreen() { - return true; - } - - private static boolean fullscreen = false; - private static boolean startupFullscreen = false; - private static int[] lastPos = new int[4]; - - public static void toggleFullscreen() { - long win = PlatformRuntime.getWindowHandle(); - long mon = getCurrentMonitor(win); - GLFWVidMode mode = glfwGetVideoMode(mon); - if (fullscreen) { - glfwSetWindowMonitor(win, 0, lastPos[0], lastPos[1], lastPos[2], lastPos[3], mode.refreshRate()); - } else { - int[] x = new int[1], y = new int[1]; - glfwGetWindowPos(win, x, y); - lastPos[0] = x[0]; - lastPos[1] = y[0]; - glfwGetWindowSize(win, x, y); - lastPos[2] = x[0]; - lastPos[3] = y[0]; - glfwSetWindowMonitor(win, mon, 0, 0, mode.width(), mode.height(), mode.refreshRate()); + private static void gamepadEnumerateDevices() { + if (selectedGamepad != -1 && !glfwJoystickIsGamepad(selectedGamepad)) { + selectedGamepad = -1; } - fullscreen = !fullscreen; + List oldList = null; + if (!gamepadList.isEmpty()) { + oldList = new ArrayList<>(gamepadList); + gamepadList.clear(); + } + for (int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_16; ++i) { + if (glfwJoystickIsGamepad(i)) { + gamepadList.add(new Gamepad(i, gamepadMakeName(i), glfwGetJoystickGUID(i))); + } + } + vigg: if (selectedGamepad != -1) { + for (int i = 0, l = gamepadList.size(); i < l; ++i) { + Gamepad gp = gamepadList.get(i); + if (gp.gamepadId == selectedGamepad && gp.gamepadUUID.equals(selectedGamepadUUID)) { + break vigg; + } + } + selectedGamepad = -1; + } + if (oldList == null) { + if (!gamepadList.isEmpty()) { + for (int i = 0, l = gamepadList.size(); i < l; ++i) { + PlatformRuntime.logger.info("Found controller: {}", gamepadList.get(i).gamepadName); + } + } + } else { + if (gamepadList.isEmpty()) { + for (int i = 0, l = oldList.size(); i < l; ++i) { + PlatformRuntime.logger.info("Lost controller: {}", oldList.get(i).gamepadName); + } + } else { + Set oldGamepadUUIDs = new HashSet<>(); + for (int i = 0, l = oldList.size(); i < l; ++i) { + oldGamepadUUIDs.add(oldList.get(i).gamepadUUID); + } + Set newGamepadUUIDs = new HashSet<>(); + for (int i = 0, l = gamepadList.size(); i < l; ++i) { + newGamepadUUIDs.add(gamepadList.get(i).gamepadUUID); + } + for (int i = 0, l = oldList.size(); i < l; ++i) { + Gamepad g = oldList.get(i); + if (!newGamepadUUIDs.contains(g.gamepadUUID)) { + PlatformRuntime.logger.info("Lost controller: {}", g.gamepadName); + } + } + for (int i = 0, l = gamepadList.size(); i < l; ++i) { + Gamepad g = gamepadList.get(i); + if (!oldGamepadUUIDs.contains(g.gamepadUUID)) { + PlatformRuntime.logger.info("Found controller: {}", g.gamepadName); + } + } + } + } + } - public static void setStartupFullscreen(boolean bool) { - startupFullscreen = bool; + public static float gamepadGetAxis(int axis) { + return selectedGamepad != -1 && axis >= 0 && axis < gamepadAxisStates.length ? gamepadAxisStates[axis] : 0.0f; + } + + public static boolean gamepadGetButtonState(int button) { + return selectedGamepad != -1 && button >= 0 && button < gamepadButtonStates.length ? gamepadButtonStates[button] + : false; + } + + public static String gamepadGetDeviceName(int deviceId) { + if (deviceId >= 0 && deviceId < gamepadList.size()) { + return gamepadList.get(deviceId).gamepadName; + } else { + return "Unknown"; + } + } + + public static String gamepadGetName() { + return selectedGamepad != -1 ? selectedGamepadName : "Unknown"; + } + + public static int gamepadGetValidDeviceCount() { + return gamepadList.size(); + } + + public static boolean gamepadIsValid() { + return selectedGamepad != -1; + } + + private static String gamepadMakeName(int glfwId) { + String s = glfwGetGamepadName(glfwId); + if (s.endsWith(" (GLFW)")) { + s = s.substring(0, s.length() - 7); + } + return glfwGetJoystickName(glfwId) + " (" + s + ")"; + } + + private static void gamepadReset() { + for (int i = 0; i < gamepadButtonStates.length; ++i) { + gamepadButtonStates[i] = false; + } + for (int i = 0; i < gamepadAxisStates.length; ++i) { + gamepadAxisStates[i] = 0.0f; + } + } + + public static void gamepadSetSelectedDevice(int deviceId) { + gamepadReset(); + if (deviceId >= 0 && deviceId < gamepadList.size()) { + selectedGamepad = gamepadList.get(deviceId).gamepadId; + if (!glfwJoystickIsGamepad(selectedGamepad)) { + selectedGamepad = -1; + } + } else { + selectedGamepad = -1; + } + } + + public static void gamepadUpdate() { + gamepadReset(); + if (selectedGamepad != -1) { + if (!glfwJoystickIsGamepad(selectedGamepad)) { + selectedGamepad = -1; + return; + } + try (MemoryStack ms = MemoryStack.stackPush()) { + GLFWGamepadState state = GLFWGamepadState.calloc(ms); + glfwGetGamepadState(selectedGamepad, state); + java.nio.FloatBuffer axes = state.axes(); + axes.get(gamepadAxisStates); + java.nio.ByteBuffer buttons = state.buttons(); + for (int i = 0, l = buttons.remaining(); i < l && i < gamepadButtonStates.length; ++i) { + boolean v = buttons.get() != (byte) 0; + int j = GamepadConstants.getEaglerButtonFromGLFW(i); + if (j != -1) { + gamepadButtonStates[j] = v; + } + } + gamepadButtonStates[GamepadConstants.GAMEPAD_LEFT_TRIGGER] = axes.get() > 0.4f; + gamepadButtonStates[GamepadConstants.GAMEPAD_RIGHT_TRIGGER] = axes.get() > 0.4f; + } + } } // https://stackoverflow.com/a/31526753 @@ -607,9 +379,8 @@ public class PlatformInput { mw[0] = mode.width(); mh[0] = mode.height(); - overlap = - Math.max(0, Math.min(wx[0] + ww[0], mx[0] + mw[0]) - Math.max(wx[0], mx[0])) * - Math.max(0, Math.min(wy[0] + wh[0], my[0] + mh[0]) - Math.max(wy[0], my[0])); + overlap = Math.max(0, Math.min(wx[0] + ww[0], mx[0] + mw[0]) - Math.max(wx[0], mx[0])) + * Math.max(0, Math.min(wy[0] + wh[0], my[0] + mh[0]) - Math.max(wy[0], my[0])); if (bestoverlap < overlap) { bestoverlap = overlap; @@ -620,12 +391,414 @@ public class PlatformInput { return bestmonitor; } + public static float getDPI() { + float[] dpiX = new float[1]; + float[] dpiY = new float[1]; + glfwGetWindowContentScale(win, dpiX, dpiY); + float ret = dpiX[0] * 0.5f + dpiY[0] * 0.5f; + if (ret <= 0.0f) { + ret = 1.0f; + } + return ret; + } + + public static int getVisualViewportH() { + return windowHeight; + } + + public static int getVisualViewportW() { + return windowWidth; + } + + public static int getVisualViewportX() { + return 0; + } + + public static int getVisualViewportY() { + return 0; + } + + public static boolean getWindowFocused() { + return windowFocused; + } + + public static int getWindowHeight() { + return windowHeight; + } + + public static int getWindowWidth() { + return windowWidth; + } + + static void initHooks(long glfwWindow) { + win = glfwWindow; + + glfwSetErrorCallback((arg0, arg1) -> { + String errorString = ""; + if (arg1 != 0l) { + try (MemoryStack stack = MemoryStack.stackPush()) { + PointerBuffer pbuffer = stack.mallocPointer(1); + pbuffer.put(0, arg1); + errorString = pbuffer.getStringUTF8(0); + } + } + PlatformRuntime.logger.error("GLFW Error #{}: {}", arg0, errorString); + }); + + if (!glfwRawMouseMotionSupported()) { + throw new UnsupportedOperationException("Raw mouse movement (cursor lock) is not supported!"); + } + + int[] v1 = new int[1], v2 = new int[1]; + glfwGetFramebufferSize(glfwWindow, v1, v2); + + windowWidth = v1[0]; + windowHeight = v2[0]; + windowResized = true; + windowResized2 = true; + + glfwSetFramebufferSizeCallback(glfwWindow, (window, width, height) -> { + if (windowWidth != width || windowHeight != height) { + windowWidth = width; + windowHeight = height; + windowResized = true; + windowResized2 = true; + } + }); + + windowFocused = true; + + glfwSetWindowFocusCallback(glfwWindow, (window, focused) -> { + windowFocused = focused; + }); + + glfwSetKeyCallback(glfwWindow, (window, key, scancode, action, mods) -> { + if (key == GLFW_KEY_F11 && action == GLFW_PRESS) { + toggleFullscreen(); + } + if (glfwGetKey(glfwWindow, functionKeyModifier) == GLFW_PRESS) { + if (key >= GLFW_KEY_1 && key <= GLFW_KEY_9) { + key = key - GLFW_KEY_1 + GLFW_KEY_F1; + } + } + key = KeyboardConstants.getEaglerKeyFromGLFW(key); + keyboardEventList.add(new KeyboardEvent(key, action != GLFW_RELEASE, action == GLFW_REPEAT)); + if (keyboardEventList.size() > 64) { + keyboardEventList.remove(0); + } + }); + + glfwSetCharCallback(glfwWindow, (window, character) -> { + keyboardCharList.add(Character.valueOf((char) character)); + if (keyboardCharList.size() > 64) { + keyboardCharList.remove(0); + } + }); + + glfwSetCursorPosCallback(glfwWindow, (window, posX, posY) -> { + posY = windowHeight - posY; + if (windowMouseGrabbed) { + cursorDX -= (cursorX - (int) posX); + cursorDY -= (cursorY - (int) posY); + cursorX = (int) posX; + cursorY = (int) posY; + } else { + cursorX = (int) posX; + cursorY = (int) posY; + mouseEventList.add(new MouseEvent(-1, false, cursorX, cursorY, 0.0f)); + if (mouseEventList.size() > 64) { + mouseEventList.remove(0); + } + } + }); + + glfwSetMouseButtonCallback(glfwWindow, (window, button, action, mods) -> { + mouseEventList.add(new MouseEvent(button, action != GLFW_RELEASE, cursorX, cursorY, 0.0f)); + if (mouseEventList.size() > 64) { + mouseEventList.remove(0); + } + }); + + glfwSetCursorEnterCallback(glfwWindow, (window, enter) -> { + windowCursorEntered = enter; + }); + + glfwSetScrollCallback(glfwWindow, (window, scrollX, scrollY) -> { + DWheel += (int) scrollY; + mouseEventList.add(new MouseEvent(-1, false, cursorX, cursorY, (float) scrollY)); + if (mouseEventList.size() > 64) { + mouseEventList.remove(0); + } + }); + + cursorDefault = glfwCreateStandardCursor(GLFW_ARROW_CURSOR); + cursorHand = glfwCreateStandardCursor(GLFW_HAND_CURSOR); + cursorText = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR); + glfwSetCursor(glfwWindow, cursorDefault); + + if (!fullscreen && startupFullscreen) { + toggleFullscreen(); + } + + gamepadEnumerateDevices(); + + glfwSetJoystickCallback((jid, event) -> { + if (event == GLFW_DISCONNECTED && jid == selectedGamepad) { + selectedGamepad = -1; + } + gamepadEnumerateDevices(); + }); + } + + public static boolean isCloseRequested() { + return glfwWindowShouldClose(win); + } + public static boolean isFullscreen() { return fullscreen; } + public static boolean isMouseGrabbed() { + return windowMouseGrabbed; + } + + public static boolean isPointerLocked() { + return windowMouseGrabbed; + } + + public static boolean isVSyncSupported() { + return true; + } + + public static void keyboardEnableRepeatEvents(boolean b) { + enableRepeatEvents = b; + } + + public static void keyboardFireEvent(EnumFireKeyboardEvent eventType, int eagKey, char keyChar) { + switch (eventType) { + case KEY_DOWN: + keyboardCharList.add(keyChar); + keyboardEventList.add(new KeyboardEvent(eagKey, true, false)); + break; + case KEY_UP: + if (eagKey >= 0 && eagKey < keyboardReleaseEventChars.length) { + keyboardReleaseEventChars[eagKey] = keyChar; + } + keyboardEventList.add(new KeyboardEvent(eagKey, false, false)); + break; + case KEY_REPEAT: + keyboardCharList.add(keyChar); + keyboardEventList.add(new KeyboardEvent(eagKey, true, true)); + break; + default: + throw new UnsupportedOperationException(); + } + if (keyboardEventList.size() > 64) { + keyboardEventList.remove(0); + } + if (keyboardCharList.size() > 64) { + keyboardCharList.remove(0); + } + } + + public static char keyboardGetEventCharacter() { + return currentKeyboardEvent.resolvedCharacter; + } + + public static int keyboardGetEventKey() { + return currentKeyboardEvent.key; + } + + public static boolean keyboardGetEventKeyState() { + return currentKeyboardEvent.pressed; + } + + public static boolean keyboardIsKeyDown(int key) { + if (glfwGetKey(win, functionKeyModifier) == GLFW_PRESS) { + if (key >= GLFW_KEY_1 && key <= GLFW_KEY_9) { + return false; + } + if (key >= GLFW_KEY_F1 && key <= GLFW_KEY_F9) { + key = key - GLFW_KEY_F1 + GLFW_KEY_1; + } + } + return glfwGetKey(win, KeyboardConstants.getGLFWKeyFromEagler(key)) == GLFW_PRESS; + } + + public static boolean keyboardIsRepeatEvent() { + return currentKeyboardEvent.repeating; + } + + public static boolean keyboardNext() { + if (keyboardEventList.size() > 0) { + currentKeyboardEvent = keyboardEventList.remove(0); + if (currentKeyboardEvent.resolvedCharacter == '\0' + && KeyboardConstants.getKeyCharFromEagler(currentKeyboardEvent.key) != '\0') { + if (currentKeyboardEvent.pressed && keyboardCharList.size() > 0) { + currentKeyboardEvent.resolvedCharacter = keyboardCharList.remove(0); + keyboardReleaseEventChars[currentKeyboardEvent.key] = currentKeyboardEvent.resolvedCharacter; + } else if (!currentKeyboardEvent.pressed) { + currentKeyboardEvent.resolvedCharacter = keyboardReleaseEventChars[currentKeyboardEvent.key]; + keyboardReleaseEventChars[currentKeyboardEvent.key] = '\0'; + } + } + if (currentKeyboardEvent.repeating && !enableRepeatEvents) { + return keyboardNext(); + } else { + return true; + } + } else { + if (keyboardCharList.size() > 0) { + currentKeyboardEvent = new KeyboardEvent(KeyboardConstants.KEY_SPACE, true, false); + currentKeyboardEvent.resolvedCharacter = keyboardCharList.remove(0); + KeyboardEvent releaseEvent = new KeyboardEvent(KeyboardConstants.KEY_SPACE, false, false); + releaseEvent.resolvedCharacter = currentKeyboardEvent.resolvedCharacter; + keyboardEventList.add(releaseEvent); + return true; + } else { + return false; + } + } + } + + public static void mouseFireButtonEvent(EnumFireMouseEvent eventType, int posX, int posY, int button) { + switch (eventType) { + case MOUSE_DOWN: + mouseEventList.add(new MouseEvent(button, true, posX, posY, 0.0f)); + break; + case MOUSE_UP: + mouseEventList.add(new MouseEvent(button, false, posX, posY, 0.0f)); + break; + default: + throw new UnsupportedOperationException(); + } + if (mouseEventList.size() > 64) { + mouseEventList.remove(0); + } + } + + public static void mouseFireMoveEvent(EnumFireMouseEvent eventType, int posX, int posY) { + if (eventType == EnumFireMouseEvent.MOUSE_MOVE) { + mouseEventList.add(new MouseEvent(-1, false, posX, posY, 0.0f)); + if (mouseEventList.size() > 64) { + mouseEventList.remove(0); + } + } else { + throw new UnsupportedOperationException(); + } + } + + public static void mouseFireWheelEvent(EnumFireMouseEvent eventType, int posX, int posY, float wheel) { + if (eventType == EnumFireMouseEvent.MOUSE_WHEEL) { + mouseEventList.add(new MouseEvent(-1, false, posX, posY, wheel)); + if (mouseEventList.size() > 64) { + mouseEventList.remove(0); + } + } else { + throw new UnsupportedOperationException(); + } + } + + public static int mouseGetDWheel() { + int i = DWheel; + DWheel = 0; + return i; + } + + public static int mouseGetDX() { + int i = cursorDX; + cursorDX = 0; + return i; + } + + public static int mouseGetDY() { + int i = cursorDY; + cursorDY = 0; + return i; + } + + public static int mouseGetEventButton() { + return currentMouseEvent.button; + } + + public static boolean mouseGetEventButtonState() { + return currentMouseEvent.pressed; + } + + public static int mouseGetEventDWheel() { + return fixWheel(currentMouseEvent.wheel); + } + + public static int mouseGetEventX() { + return currentMouseEvent.posX; + } + + public static int mouseGetEventY() { + return currentMouseEvent.posY; + } + + public static int mouseGetX() { + return cursorX; + } + + public static int mouseGetY() { + return cursorY; + } + + public static boolean mouseGrabSupported() { + return true; + } + + public static boolean mouseIsButtonDown(int i) { + return glfwGetMouseButton(win, i) == GLFW_PRESS; + } + + public static boolean mouseIsInsideWindow() { + return windowCursorEntered; + } + + public static boolean mouseNext() { + if (mouseEventList.size() > 0) { + currentMouseEvent = mouseEventList.remove(0); + return true; + } else { + return false; + } + } + + public static void mouseSetCursorPosition(int x, int y) { + cursorX = x; + cursorY = y; + glfwSetCursorPos(win, x, y); + } + + public static void mouseSetGrabbed(boolean grab) { + if (grab != windowMouseGrabbed) { + cursorX = windowWidth / 2; + cursorY = windowHeight / 2; + glfwSetCursorPos(win, cursorX, cursorY); + windowMouseGrabbed = grab; + cursorDX = 0; + cursorDY = 0; + glfwSetInputMode(win, GLFW_CURSOR, grab ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); + glfwSetInputMode(win, GLFW_RAW_MOUSE_MOTION, grab ? GLFW_TRUE : GLFW_FALSE); + } + } + + public static void setFunctionKeyModifier(int key) { + functionKeyModifier = KeyboardConstants.getGLFWKeyFromEagler(key); + } + + public static void setStartupFullscreen(boolean bool) { + startupFullscreen = bool; + } + + public static void setVSync(boolean enable) { + vsync = enable; + } + public static void showCursor(EnumCursorType cursor) { - switch(cursor) { + switch (cursor) { case DEFAULT: default: glfwSetCursor(win, cursorDefault); @@ -639,24 +812,51 @@ public class PlatformInput { } } - public static boolean touchNext() { - return false; + public static boolean supportsFullscreen() { + return true; } - public static EnumTouchEvent touchGetEventType() { - return null; + public static void toggleFullscreen() { + long win = PlatformRuntime.getWindowHandle(); + long mon = getCurrentMonitor(win); + GLFWVidMode mode = glfwGetVideoMode(mon); + if (fullscreen) { + glfwSetWindowMonitor(win, 0, lastPos[0], lastPos[1], lastPos[2], lastPos[3], mode.refreshRate()); + } else { + int[] x = new int[1], y = new int[1]; + glfwGetWindowPos(win, x, y); + lastPos[0] = x[0]; + lastPos[1] = y[0]; + glfwGetWindowSize(win, x, y); + lastPos[2] = x[0]; + lastPos[3] = y[0]; + glfwSetWindowMonitor(win, mon, 0, 0, mode.width(), mode.height(), mode.refreshRate()); + } + fullscreen = !fullscreen; + } + + public static void touchCloseDeviceKeyboard() { + + } + + public static float touchForce(int pointId) { + return 0.0f; + } + + public static float touchGetEventTouchForce(int pointId) { + return 0.0f; } public static int touchGetEventTouchPointCount() { return 0; } - public static int touchGetEventTouchX(int pointId) { + public static int touchGetEventTouchPointUID(int pointId) { return 0; } - public static int touchGetEventTouchY(int pointId) { - return 0; + public static float touchGetEventTouchRadiusMixed(int pointId) { + return touchGetEventTouchRadiusX(pointId) * 0.5f + touchGetEventTouchRadiusY(pointId) * 0.5f; } public static float touchGetEventTouchRadiusX(int pointId) { @@ -667,22 +867,38 @@ public class PlatformInput { return 0.0f; } - public static float touchGetEventTouchRadiusMixed(int pointId) { - return touchGetEventTouchRadiusX(pointId) * 0.5f + touchGetEventTouchRadiusY(pointId) * 0.5f; - } - - public static float touchGetEventTouchForce(int pointId) { - return 0.0f; - } - - public static int touchGetEventTouchPointUID(int pointId) { + public static int touchGetEventTouchX(int pointId) { return 0; } + public static int touchGetEventTouchY(int pointId) { + return 0; + } + + public static EnumTouchEvent touchGetEventType() { + return null; + } + + public static String touchGetPastedString() { + return null; + } + + public static boolean touchIsDeviceKeyboardOpenMAYBE() { + return false; + } + + public static boolean touchNext() { + return false; + } + public static int touchPointCount() { return 0; } + public static int touchPointUID(int pointId) { + return 0; + } + public static int touchPointX(int pointId) { return 0; } @@ -691,6 +907,10 @@ public class PlatformInput { return 0; } + public static float touchRadiusMixed(int pointId) { + return touchRadiusX(pointId) * 0.5f + touchRadiusY(pointId) * 0.5f; + } + public static float touchRadiusX(int pointId) { return 0.0f; } @@ -699,186 +919,29 @@ public class PlatformInput { return 0.0f; } - public static float touchRadiusMixed(int pointId) { - return touchRadiusX(pointId) * 0.5f + touchRadiusY(pointId) * 0.5f; - } - - public static float touchForce(int pointId) { - return 0.0f; - } - - public static int touchPointUID(int pointId) { - return 0; - } - public static void touchSetOpenKeyboardZone(int x, int y, int w, int h) { - + } - public static void touchCloseDeviceKeyboard() { - - } - - public static boolean touchIsDeviceKeyboardOpenMAYBE() { - return false; - } - - public static String touchGetPastedString() { - return null; - } - - private static void gamepadEnumerateDevices() { - if(selectedGamepad != -1 && !glfwJoystickIsGamepad(selectedGamepad)) { - selectedGamepad = -1; + public static void update() { + glfwPollEvents(); + if (vsync != glfwVSyncState) { + glfwSwapInterval(vsync ? 1 : 0); + glfwVSyncState = vsync; } - List oldList = null; - if(!gamepadList.isEmpty()) { - oldList = new ArrayList<>(gamepadList); - gamepadList.clear(); - } - for(int i = GLFW_JOYSTICK_1; i <= GLFW_JOYSTICK_16; ++i) { - if(glfwJoystickIsGamepad(i)) { - gamepadList.add(new Gamepad(i, gamepadMakeName(i), glfwGetJoystickGUID(i))); - } - } - vigg: if(selectedGamepad != -1) { - for(int i = 0, l = gamepadList.size(); i < l; ++i) { - Gamepad gp = gamepadList.get(i); - if(gp.gamepadId == selectedGamepad && gp.gamepadUUID.equals(selectedGamepadUUID)) { - break vigg; - } - } - selectedGamepad = -1; - } - if(oldList == null) { - if(!gamepadList.isEmpty()) { - for(int i = 0, l = gamepadList.size(); i < l; ++i) { - PlatformRuntime.logger.info("Found controller: {}", gamepadList.get(i).gamepadName); - } - } - }else { - if(gamepadList.isEmpty()) { - for(int i = 0, l = oldList.size(); i < l; ++i) { - PlatformRuntime.logger.info("Lost controller: {}", oldList.get(i).gamepadName); - } - }else { - Set oldGamepadUUIDs = new HashSet<>(); - for(int i = 0, l = oldList.size(); i < l; ++i) { - oldGamepadUUIDs.add(oldList.get(i).gamepadUUID); - } - Set newGamepadUUIDs = new HashSet<>(); - for(int i = 0, l = gamepadList.size(); i < l; ++i) { - newGamepadUUIDs.add(gamepadList.get(i).gamepadUUID); - } - for(int i = 0, l = oldList.size(); i < l; ++i) { - Gamepad g = oldList.get(i); - if(!newGamepadUUIDs.contains(g.gamepadUUID)) { - PlatformRuntime.logger.info("Lost controller: {}", g.gamepadName); - } - } - for(int i = 0, l = gamepadList.size(); i < l; ++i) { - Gamepad g = gamepadList.get(i); - if(!oldGamepadUUIDs.contains(g.gamepadUUID)) { - PlatformRuntime.logger.info("Found controller: {}", g.gamepadName); - } - } - } - } - + glfwSwapBuffers(win); } - private static String gamepadMakeName(int glfwId) { - String s = glfwGetGamepadName(glfwId); - if(s.endsWith(" (GLFW)")) { - s = s.substring(0, s.length() - 7); - } - return glfwGetJoystickName(glfwId) + " (" + s + ")"; + public static boolean wasResized() { + boolean b = windowResized; + windowResized = false; + return b; } - public static int gamepadGetValidDeviceCount() { - return gamepadList.size(); - } - - public static String gamepadGetDeviceName(int deviceId) { - if(deviceId >= 0 && deviceId < gamepadList.size()) { - return gamepadList.get(deviceId).gamepadName; - }else { - return "Unknown"; - } - } - - public static void gamepadSetSelectedDevice(int deviceId) { - gamepadReset(); - if(deviceId >= 0 && deviceId < gamepadList.size()) { - selectedGamepad = gamepadList.get(deviceId).gamepadId; - if(!glfwJoystickIsGamepad(selectedGamepad)) { - selectedGamepad = -1; - } - }else { - selectedGamepad = -1; - } - } - - private static void gamepadReset() { - for(int i = 0; i < gamepadButtonStates.length; ++i) { - gamepadButtonStates[i] = false; - } - for(int i = 0; i < gamepadAxisStates.length; ++i) { - gamepadAxisStates[i] = 0.0f; - } - } - - public static void gamepadUpdate() { - gamepadReset(); - if(selectedGamepad != -1) { - if(!glfwJoystickIsGamepad(selectedGamepad)) { - selectedGamepad = -1; - return; - } - try(MemoryStack ms = MemoryStack.stackPush()) { - GLFWGamepadState state = GLFWGamepadState.calloc(ms); - glfwGetGamepadState(selectedGamepad, state); - java.nio.FloatBuffer axes = state.axes(); - axes.get(gamepadAxisStates); - java.nio.ByteBuffer buttons = state.buttons(); - for(int i = 0, l = buttons.remaining(); i < l && i < gamepadButtonStates.length; ++i) { - boolean v = buttons.get() != (byte)0; - int j = GamepadConstants.getEaglerButtonFromGLFW(i); - if(j != -1) { - gamepadButtonStates[j] = v; - } - } - gamepadButtonStates[GamepadConstants.GAMEPAD_LEFT_TRIGGER] = axes.get() > 0.4f; - gamepadButtonStates[GamepadConstants.GAMEPAD_RIGHT_TRIGGER] = axes.get() > 0.4f; - } - } - } - - public static boolean gamepadIsValid() { - return selectedGamepad != -1; - } - - public static String gamepadGetName() { - return selectedGamepad != -1 ? selectedGamepadName : "Unknown"; - } - - public static boolean gamepadGetButtonState(int button) { - return selectedGamepad != -1 && button >= 0 && button < gamepadButtonStates.length ? gamepadButtonStates[button] : false; - } - - public static float gamepadGetAxis(int axis) { - return selectedGamepad != -1 && axis >= 0 && axis < gamepadAxisStates.length ? gamepadAxisStates[axis] : 0.0f; - } - - public static float getDPI() { - float[] dpiX = new float[1]; - float[] dpiY = new float[1]; - glfwGetWindowContentScale(win, dpiX, dpiY); - float ret = dpiX[0] * 0.5f + dpiY[0] * 0.5f; - if(ret <= 0.0f) { - ret = 1.0f; - } - return ret; + public static boolean wasVisualViewportResized() { + boolean b = windowResized2; + windowResized2 = false; + return b; } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformNetworking.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformNetworking.java index 3b81f5d0..e2d3290f 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformNetworking.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformNetworking.java @@ -10,36 +10,37 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformNetworking { - + private static final Logger logger = LogManager.getLogger("PlatformNetworking"); - + public static IWebSocketClient openWebSocket(String socketURI) { try { URI uri = new URI(socketURI); return new DesktopWebSocketClient(uri); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Could not open WebSocket to \"{}\"!", socketURI); logger.error(t); return null; } } - + public static IWebSocketClient openWebSocketUnsafe(String socketURI) throws URISyntaxException { URI uri = new URI(socketURI); return new DesktopWebSocketClient(uri); } - + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformOpenGL.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformOpenGL.java index 768dbb91..d7aae702 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformOpenGL.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformOpenGL.java @@ -1,32 +1,139 @@ package net.lax1dude.eaglercraft.v1_8.internal; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.EaglerLWJGLAllocator; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; - -import static org.lwjgl.opengles.GLES30.*; -import static org.lwjgl.opengles.ANGLEInstancedArrays.*; -import static org.lwjgl.opengles.EXTInstancedArrays.*; -import static org.lwjgl.opengles.EXTTextureStorage.*; -import static org.lwjgl.opengles.OESVertexArrayObject.*; +import static org.lwjgl.opengles.ANGLEInstancedArrays.glDrawArraysInstancedANGLE; +import static org.lwjgl.opengles.ANGLEInstancedArrays.glDrawElementsInstancedANGLE; +import static org.lwjgl.opengles.ANGLEInstancedArrays.glVertexAttribDivisorANGLE; +import static org.lwjgl.opengles.EXTInstancedArrays.glDrawArraysInstancedEXT; +import static org.lwjgl.opengles.EXTInstancedArrays.glDrawElementsInstancedEXT; +import static org.lwjgl.opengles.EXTInstancedArrays.glVertexAttribDivisorEXT; +import static org.lwjgl.opengles.EXTTextureStorage.glTexStorage2DEXT; +import static org.lwjgl.opengles.GLES20.GL_EXTENSIONS; +import static org.lwjgl.opengles.GLES20.glActiveTexture; +import static org.lwjgl.opengles.GLES20.glAttachShader; +import static org.lwjgl.opengles.GLES20.glBindAttribLocation; +import static org.lwjgl.opengles.GLES20.glBindBuffer; +import static org.lwjgl.opengles.GLES20.glBindFramebuffer; +import static org.lwjgl.opengles.GLES20.glBindRenderbuffer; +import static org.lwjgl.opengles.GLES20.glBindTexture; +import static org.lwjgl.opengles.GLES20.glBlendColor; +import static org.lwjgl.opengles.GLES20.glBlendEquation; +import static org.lwjgl.opengles.GLES20.glBlendFunc; +import static org.lwjgl.opengles.GLES20.glBlendFuncSeparate; +import static org.lwjgl.opengles.GLES20.glBufferData; +import static org.lwjgl.opengles.GLES20.glCheckFramebufferStatus; +import static org.lwjgl.opengles.GLES20.glClear; +import static org.lwjgl.opengles.GLES20.glClearColor; +import static org.lwjgl.opengles.GLES20.glClearDepthf; +import static org.lwjgl.opengles.GLES20.glColorMask; +import static org.lwjgl.opengles.GLES20.glCompileShader; +import static org.lwjgl.opengles.GLES20.glCopyTexSubImage2D; +import static org.lwjgl.opengles.GLES20.glCreateProgram; +import static org.lwjgl.opengles.GLES20.glCreateShader; +import static org.lwjgl.opengles.GLES20.glCullFace; +import static org.lwjgl.opengles.GLES20.glDeleteBuffers; +import static org.lwjgl.opengles.GLES20.glDeleteFramebuffers; +import static org.lwjgl.opengles.GLES20.glDeleteProgram; +import static org.lwjgl.opengles.GLES20.glDeleteRenderbuffers; +import static org.lwjgl.opengles.GLES20.glDeleteShader; +import static org.lwjgl.opengles.GLES20.glDeleteTextures; +import static org.lwjgl.opengles.GLES20.glDepthFunc; +import static org.lwjgl.opengles.GLES20.glDepthMask; +import static org.lwjgl.opengles.GLES20.glDetachShader; +import static org.lwjgl.opengles.GLES20.glDisable; +import static org.lwjgl.opengles.GLES20.glDisableVertexAttribArray; +import static org.lwjgl.opengles.GLES20.glDrawArrays; +import static org.lwjgl.opengles.GLES20.glDrawElements; +import static org.lwjgl.opengles.GLES20.glEnable; +import static org.lwjgl.opengles.GLES20.glEnableVertexAttribArray; +import static org.lwjgl.opengles.GLES20.glFramebufferRenderbuffer; +import static org.lwjgl.opengles.GLES20.glFramebufferTexture2D; +import static org.lwjgl.opengles.GLES20.glGenBuffers; +import static org.lwjgl.opengles.GLES20.glGenFramebuffers; +import static org.lwjgl.opengles.GLES20.glGenRenderbuffers; +import static org.lwjgl.opengles.GLES20.glGenTextures; +import static org.lwjgl.opengles.GLES20.glGenerateMipmap; +import static org.lwjgl.opengles.GLES20.glGetAttribLocation; +import static org.lwjgl.opengles.GLES20.glGetError; +import static org.lwjgl.opengles.GLES20.glGetInteger; +import static org.lwjgl.opengles.GLES20.glGetProgramInfoLog; +import static org.lwjgl.opengles.GLES20.glGetProgrami; +import static org.lwjgl.opengles.GLES20.glGetShaderInfoLog; +import static org.lwjgl.opengles.GLES20.glGetShaderi; +import static org.lwjgl.opengles.GLES20.glGetString; +import static org.lwjgl.opengles.GLES20.glGetUniformLocation; +import static org.lwjgl.opengles.GLES20.glLineWidth; +import static org.lwjgl.opengles.GLES20.glLinkProgram; +import static org.lwjgl.opengles.GLES20.glPixelStorei; +import static org.lwjgl.opengles.GLES20.glPolygonOffset; +import static org.lwjgl.opengles.GLES20.glRenderbufferStorage; +import static org.lwjgl.opengles.GLES20.glShaderSource; +import static org.lwjgl.opengles.GLES20.glTexParameterf; +import static org.lwjgl.opengles.GLES20.glTexParameteri; +import static org.lwjgl.opengles.GLES20.glUniform1f; +import static org.lwjgl.opengles.GLES20.glUniform1i; +import static org.lwjgl.opengles.GLES20.glUniform2f; +import static org.lwjgl.opengles.GLES20.glUniform2i; +import static org.lwjgl.opengles.GLES20.glUniform3f; +import static org.lwjgl.opengles.GLES20.glUniform3i; +import static org.lwjgl.opengles.GLES20.glUniform4f; +import static org.lwjgl.opengles.GLES20.glUniform4i; +import static org.lwjgl.opengles.GLES20.glUseProgram; +import static org.lwjgl.opengles.GLES20.glVertexAttribPointer; +import static org.lwjgl.opengles.GLES20.glViewport; +import static org.lwjgl.opengles.GLES20.nglBufferData; +import static org.lwjgl.opengles.GLES20.nglBufferSubData; +import static org.lwjgl.opengles.GLES20.nglReadPixels; +import static org.lwjgl.opengles.GLES20.nglTexImage2D; +import static org.lwjgl.opengles.GLES20.nglTexSubImage2D; +import static org.lwjgl.opengles.GLES20.nglUniformMatrix2fv; +import static org.lwjgl.opengles.GLES20.nglUniformMatrix3fv; +import static org.lwjgl.opengles.GLES20.nglUniformMatrix4fv; +import static org.lwjgl.opengles.GLES30.glBindBufferRange; +import static org.lwjgl.opengles.GLES30.glBindVertexArray; +import static org.lwjgl.opengles.GLES30.glBlitFramebuffer; +import static org.lwjgl.opengles.GLES30.glDeleteQueries; +import static org.lwjgl.opengles.GLES30.glDeleteVertexArrays; +import static org.lwjgl.opengles.GLES30.glDrawArraysInstanced; +import static org.lwjgl.opengles.GLES30.glDrawBuffers; +import static org.lwjgl.opengles.GLES30.glDrawElementsInstanced; +import static org.lwjgl.opengles.GLES30.glFramebufferTextureLayer; +import static org.lwjgl.opengles.GLES30.glGenQueries; +import static org.lwjgl.opengles.GLES30.glGenVertexArrays; +import static org.lwjgl.opengles.GLES30.glGetUniformBlockIndex; +import static org.lwjgl.opengles.GLES30.glReadBuffer; +import static org.lwjgl.opengles.GLES30.glTexStorage2D; +import static org.lwjgl.opengles.GLES30.glUniformBlockBinding; +import static org.lwjgl.opengles.GLES30.glVertexAttribDivisor; +import static org.lwjgl.opengles.GLES30.nglTexImage3D; +import static org.lwjgl.opengles.GLES30.nglUniformMatrix3x2fv; +import static org.lwjgl.opengles.GLES30.nglUniformMatrix4x2fv; +import static org.lwjgl.opengles.GLES30.nglUniformMatrix4x3fv; +import static org.lwjgl.opengles.OESVertexArrayObject.glBindVertexArrayOES; +import static org.lwjgl.opengles.OESVertexArrayObject.glDeleteVertexArraysOES; +import static org.lwjgl.opengles.OESVertexArrayObject.glGenVertexArraysOES; import java.util.ArrayList; import java.util.List; import org.lwjgl.opengles.GLESCapabilities; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.EaglerLWJGLAllocator; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; + /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -72,100 +179,62 @@ public class PlatformOpenGL { private static final int TEX_STORAGE_IMPL_EXT = 1; private static int texStorageImpl = TEX_STORAGE_IMPL_NONE; - static void setCurrentContext(int glesVersIn, GLESCapabilities caps) { - glesVers = glesVersIn; + public static final void _wglActiveTexture(int texture) { + glActiveTexture(texture); + } - hasANGLEInstancedArrays = glesVersIn == 200 && caps.GL_ANGLE_instanced_arrays; - hasOESTextureFloat = glesVersIn == 200 && caps.GL_OES_texture_float; - hasOESTextureFloatLinear = glesVersIn >= 300 && caps.GL_OES_texture_float_linear; - hasOESTextureHalfFloat = glesVersIn == 200 && caps.GL_OES_texture_half_float; - hasOESTextureHalfFloatLinear = glesVersIn == 200 && caps.GL_OES_texture_half_float_linear; - hasEXTColorBufferFloat = (glesVersIn == 310 || glesVersIn == 300) && caps.GL_EXT_color_buffer_float; - hasEXTColorBufferHalfFloat = !hasEXTColorBufferFloat - && (glesVersIn == 310 || glesVersIn == 300 || glesVersIn == 200) && caps.GL_EXT_color_buffer_half_float; - hasEXTInstancedArrays = !hasANGLEInstancedArrays && glesVersIn == 200 && caps.GL_EXT_instanced_arrays; - hasEXTShaderTextureLOD = glesVersIn == 200 && caps.GL_EXT_shader_texture_lod; - hasEXTTextureStorage = glesVersIn == 200 && caps.GL_EXT_texture_storage; - hasOESGPUShader5 = glesVersIn == 310 && caps.GL_OES_gpu_shader5; - hasEXTGPUShader5 = !hasOESGPUShader5 && glesVersIn == 310 && caps.GL_EXT_gpu_shader5; - hasOESFBORenderMipmap = glesVersIn == 200 && caps.GL_OES_fbo_render_mipmap; - hasOESVertexArrayObject = glesVersIn == 200 && caps.GL_OES_vertex_array_object; - hasLinearHDR32FSupport = caps.GL_OES_texture_float_linear; - hasEXTTextureFilterAnisotropic = caps.GL_EXT_texture_filter_anisotropic; - - hasFBO16FSupport = glesVersIn >= 320 || ((glesVersIn >= 300 || hasOESTextureFloat) && (hasEXTColorBufferFloat || hasEXTColorBufferHalfFloat)); - hasFBO32FSupport = glesVersIn >= 320 || ((glesVersIn >= 300 || hasOESTextureHalfFloat) && hasEXTColorBufferFloat); - hasLinearHDR16FSupport = glesVersIn >= 300 || hasOESTextureHalfFloatLinear; - hasLinearHDR32FSupport = glesVersIn >= 300 && hasOESTextureFloatLinear; - - if(glesVersIn >= 300) { - vertexArrayImpl = VAO_IMPL_CORE; - instancingImpl = INSTANCE_IMPL_CORE; - texStorageImpl = TEX_STORAGE_IMPL_CORE; - }else if(glesVersIn == 200) { - vertexArrayImpl = hasOESVertexArrayObject ? VAO_IMPL_OES : VAO_IMPL_NONE; - instancingImpl = hasANGLEInstancedArrays ? INSTANCE_IMPL_ANGLE : (hasEXTInstancedArrays ? INSTANCE_IMPL_EXT : INSTANCE_IMPL_NONE); - texStorageImpl = hasEXTTextureStorage ? TEX_STORAGE_IMPL_EXT : TEX_STORAGE_IMPL_NONE; - }else { - vertexArrayImpl = VAO_IMPL_NONE; - instancingImpl = INSTANCE_IMPL_NONE; - texStorageImpl = TEX_STORAGE_IMPL_NONE; + public static final void _wglAttachShader(IProgramGL obj, IShaderGL shader) { + glAttachShader(((OpenGLObjects.ProgramGL) obj).ptr, ((OpenGLObjects.ShaderGL) shader).ptr); + } + + public static final void _wglBindAttribLocation(IProgramGL obj, int index, String name) { + glBindAttribLocation(((OpenGLObjects.ProgramGL) obj).ptr, index, name); + } + + public static final void _wglBindBuffer(int target, IBufferGL obj) { + glBindBuffer(target, obj == null ? 0 : ((OpenGLObjects.BufferGL) obj).ptr); + } + + public static final void _wglBindBufferRange(int target, int index, IBufferGL buffer, int offset, int size) { + glBindBufferRange(target, index, ((OpenGLObjects.BufferGL) buffer).ptr, offset, size); + } + + public static final void _wglBindFramebuffer(int target, IFramebufferGL framebuffer) { + if (framebuffer == null) { + glBindFramebuffer(target, 0); + } else { + glBindFramebuffer(target, ((OpenGLObjects.FramebufferGL) framebuffer).ptr); } } - public static final List dumpActiveExtensions() { - List exts = new ArrayList<>(); - if(hasANGLEInstancedArrays) exts.add("ANGLE_instanced_arrays"); - if(hasEXTColorBufferFloat) exts.add("EXT_color_buffer_float"); - if(hasEXTColorBufferHalfFloat) exts.add("EXT_color_buffer_half_float"); - if(hasEXTGPUShader5) exts.add("EXT_gpu_shader5"); - if(hasEXTInstancedArrays) exts.add("EXT_instanced_arrays"); - if(hasEXTTextureStorage) exts.add("EXT_texture_storage"); - if(hasOESFBORenderMipmap) exts.add("OES_fbo_render_mipmap"); - if(hasOESGPUShader5) exts.add("OES_gpu_shader5"); - if(hasOESVertexArrayObject) exts.add("OES_vertex_array_object"); - if(hasOESTextureFloat) exts.add("OES_texture_float"); - if(hasOESTextureFloatLinear) exts.add("OES_texture_float_linear"); - if(hasOESTextureHalfFloat) exts.add("OES_texture_half_float"); - if(hasOESTextureHalfFloatLinear) exts.add("OES_texture_half_float_linear"); - if(hasEXTTextureFilterAnisotropic) exts.add("EXT_texture_filter_anisotropic"); - return exts; + public static final void _wglBindRenderbuffer(int target, IRenderbufferGL renderbuffer) { + glBindRenderbuffer(target, renderbuffer == null ? 0 : ((OpenGLObjects.RenderbufferGL) renderbuffer).ptr); } - public static final void _wglEnable(int glEnum) { - glEnable(glEnum); + public static final void _wglBindTexture(int target, ITextureGL obj) { + glBindTexture(target, obj == null ? 0 : ((OpenGLObjects.TextureGL) obj).ptr); } - public static final void _wglDisable(int glEnum) { - glDisable(glEnum); + public static final void _wglBindVertexArray(IBufferArrayGL obj) { + int ptr = obj == null ? 0 : ((OpenGLObjects.BufferArrayGL) obj).ptr; + switch (vertexArrayImpl) { + case VAO_IMPL_CORE: + glBindVertexArray(ptr); + break; + case VAO_IMPL_OES: + glBindVertexArrayOES(ptr); + break; + default: + throw new UnsupportedOperationException(); + } } - public static final void _wglClearColor(float r, float g, float b, float a) { - glClearColor(r, g, b, a); + public static final void _wglBlendColor(float r, float g, float b, float a) { + glBlendColor(r, g, b, a); } - public static final void _wglClearDepth(float f) { - glClearDepthf(f); - } - - public static final void _wglClear(int bits) { - glClear(bits); - } - - public static final void _wglDepthFunc(int glEnum) { - glDepthFunc(glEnum); - } - - public static final void _wglDepthMask(boolean mask) { - glDepthMask(mask); - } - - public static final void _wglCullFace(int glEnum) { - glCullFace(glEnum); - } - - public static final void _wglViewport(int x, int y, int w, int h) { - glViewport(x, y, w, h); + public static final void _wglBlendEquation(int glEnum) { + glBlendEquation(glEnum); } public static final void _wglBlendFunc(int src, int dst) { @@ -176,149 +245,9 @@ public class PlatformOpenGL { glBlendFuncSeparate(srcColor, dstColor, srcAlpha, dstAlpha); } - public static final void _wglBlendEquation(int glEnum) { - glBlendEquation(glEnum); - } - - public static final void _wglBlendColor(float r, float g, float b, float a) { - glBlendColor(r, g, b, a); - } - - public static final void _wglColorMask(boolean r, boolean g, boolean b, boolean a) { - glColorMask(r, g, b, a); - } - - public static final void _wglDrawBuffers(int buffer) { - if(glesVers == 200) { - if(buffer != 0x8CE0) { // GL_COLOR_ATTACHMENT0 - throw new UnsupportedOperationException(); - } - }else { - glDrawBuffers(buffer); - } - } - - public static final void _wglDrawBuffers(int[] buffers) { - if(glesVers == 200) { - if(buffers.length != 1 || buffers[0] != 0x8CE0) { // GL_COLOR_ATTACHMENT0 - throw new UnsupportedOperationException(); - } - }else { - glDrawBuffers(buffers); - } - } - - public static final void _wglReadBuffer(int buffer) { - glReadBuffer(buffer); - } - - public static final void _wglReadPixels(int x, int y, int width, int height, int format, int type, ByteBuffer data) { - nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglReadPixels_u16(int x, int y, int width, int height, int format, int type, ByteBuffer data) { - nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglReadPixels(int x, int y, int width, int height, int format, int type, IntBuffer data) { - nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglReadPixels(int x, int y, int width, int height, int format, int type, FloatBuffer data) { - nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglPolygonOffset(float f1, float f2) { - glPolygonOffset(f1, f2); - } - - public static final void _wglLineWidth(float width) { - glLineWidth(width); - } - - public static final IBufferGL _wglGenBuffers() { - return new OpenGLObjects.BufferGL(glGenBuffers()); - } - - public static final ITextureGL _wglGenTextures() { - return new OpenGLObjects.TextureGL(glGenTextures()); - } - - public static final IBufferArrayGL _wglGenVertexArrays() { - switch(vertexArrayImpl) { - case VAO_IMPL_CORE: - return new OpenGLObjects.BufferArrayGL(glGenVertexArrays()); - case VAO_IMPL_OES: - return new OpenGLObjects.BufferArrayGL(glGenVertexArraysOES()); - default: - throw new UnsupportedOperationException(); - } - } - - public static final IProgramGL _wglCreateProgram() { - return new OpenGLObjects.ProgramGL(glCreateProgram()); - } - - public static final IShaderGL _wglCreateShader(int type) { - return new OpenGLObjects.ShaderGL(glCreateShader(type)); - } - - public static final IFramebufferGL _wglCreateFramebuffer() { - return new OpenGLObjects.FramebufferGL(glGenFramebuffers()); - } - - public static final IRenderbufferGL _wglCreateRenderbuffer() { - return new OpenGLObjects.RenderbufferGL(glGenRenderbuffers()); - } - - public static final IQueryGL _wglGenQueries() { - return new OpenGLObjects.QueryGL(glGenQueries()); - } - - public static final void _wglDeleteBuffers(IBufferGL obj) { - glDeleteBuffers(((OpenGLObjects.BufferGL) obj).ptr); - } - - public static final void _wglDeleteTextures(ITextureGL obj) { - glDeleteTextures(((OpenGLObjects.TextureGL) obj).ptr); - } - - public static final void _wglDeleteVertexArrays(IBufferArrayGL obj) { - int ptr = ((OpenGLObjects.BufferArrayGL) obj).ptr; - switch(vertexArrayImpl) { - case VAO_IMPL_CORE: - glDeleteVertexArrays(ptr); - break; - case VAO_IMPL_OES: - glDeleteVertexArraysOES(ptr); - break; - default: - throw new UnsupportedOperationException(); - } - } - - public static final void _wglDeleteProgram(IProgramGL obj) { - glDeleteProgram(((OpenGLObjects.ProgramGL) obj).ptr); - } - - public static final void _wglDeleteShader(IShaderGL obj) { - glDeleteShader(((OpenGLObjects.ShaderGL) obj).ptr); - } - - public static final void _wglDeleteFramebuffer(IFramebufferGL obj) { - glDeleteFramebuffers(((OpenGLObjects.FramebufferGL) obj).ptr); - } - - public static final void _wglDeleteRenderbuffer(IRenderbufferGL obj) { - glDeleteRenderbuffers(((OpenGLObjects.RenderbufferGL) obj).ptr); - } - - public static final void _wglDeleteQueries(IQueryGL obj) { - glDeleteQueries(((OpenGLObjects.QueryGL) obj).ptr); - } - - public static final void _wglBindBuffer(int target, IBufferGL obj) { - glBindBuffer(target, obj == null ? 0 : ((OpenGLObjects.BufferGL) obj).ptr); + public static final void _wglBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, + int dstX1, int dstY1, int bits, int filter) { + glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, bits, filter); } public static final void _wglBufferData(int target, ByteBuffer data, int usage) { @@ -326,11 +255,6 @@ public class PlatformOpenGL { data == null ? 0l : EaglerLWJGLAllocator.getAddress(data), usage); } - public static final void _wglBufferData(int target, IntBuffer data, int usage) { - nglBufferData(target, data == null ? 0 : (data.remaining() << 2), - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data), usage); - } - public static final void _wglBufferData(int target, FloatBuffer data, int usage) { nglBufferData(target, data == null ? 0 : (data.remaining() << 2), data == null ? 0l : EaglerLWJGLAllocator.getAddress(data), usage); @@ -340,13 +264,13 @@ public class PlatformOpenGL { glBufferData(target, size, usage); } - public static final void _wglBufferSubData(int target, int offset, ByteBuffer data) { - nglBufferSubData(target, offset, data == null ? 0 : data.remaining(), - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final void _wglBufferData(int target, IntBuffer data, int usage) { + nglBufferData(target, data == null ? 0 : (data.remaining() << 2), + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data), usage); } - public static final void _wglBufferSubData(int target, int offset, IntBuffer data) { - nglBufferSubData(target, offset, data == null ? 0 : (data.remaining() << 2), + public static final void _wglBufferSubData(int target, int offset, ByteBuffer data) { + nglBufferSubData(target, offset, data == null ? 0 : data.remaining(), data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); } @@ -355,123 +279,33 @@ public class PlatformOpenGL { data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); } - public static final void _wglBindVertexArray(IBufferArrayGL obj) { - int ptr = obj == null ? 0 : ((OpenGLObjects.BufferArrayGL) obj).ptr; - switch(vertexArrayImpl) { - case VAO_IMPL_CORE: - glBindVertexArray(ptr); - break; - case VAO_IMPL_OES: - glBindVertexArrayOES(ptr); - break; - default: - throw new UnsupportedOperationException(); - } - } - - public static final void _wglEnableVertexAttribArray(int index) { - glEnableVertexAttribArray(index); - } - - public static final void _wglDisableVertexAttribArray(int index) { - glDisableVertexAttribArray(index); - } - - public static final void _wglVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, - int offset) { - glVertexAttribPointer(index, size, type, normalized, stride, offset); - } - - public static final void _wglVertexAttribDivisor(int index, int divisor) { - switch(instancingImpl) { - case INSTANCE_IMPL_CORE: - glVertexAttribDivisor(index, divisor); - break; - case INSTANCE_IMPL_ANGLE: - glVertexAttribDivisorANGLE(index, divisor); - break; - case INSTANCE_IMPL_EXT: - glVertexAttribDivisorEXT(index, divisor); - break; - default: - throw new UnsupportedOperationException(); - } - } - - public static final void _wglActiveTexture(int texture) { - glActiveTexture(texture); - } - - public static final void _wglBindTexture(int target, ITextureGL obj) { - glBindTexture(target, obj == null ? 0 : ((OpenGLObjects.TextureGL) obj).ptr); - } - - public static final void _wglTexParameterf(int target, int param, float value) { - glTexParameterf(target, param, value); - } - - public static final void _wglTexParameteri(int target, int param, int value) { - glTexParameteri(target, param, value); - } - - public static final void _wglTexImage3D(int target, int level, int internalFormat, int width, int height, int depth, - int border, int format, int type, ByteBuffer data) { - nglTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, + public static final void _wglBufferSubData(int target, int offset, IntBuffer data) { + nglBufferSubData(target, offset, data == null ? 0 : (data.remaining() << 2), data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); } - public static final void _wglTexImage2D(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, ByteBuffer data) { - nglTexImage2D(target, level, internalFormat, width, height, border, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final int _wglCheckFramebufferStatus(int target) { + return glCheckFramebufferStatus(target); } - public static final void _wglTexImage2D(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, IntBuffer data) { - nglTexImage2D(target, level, internalFormat, width, height, border, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final void _wglClear(int bits) { + glClear(bits); } - public static final void _wglTexImage2D(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, FloatBuffer data) { - nglTexImage2D(target, level, internalFormat, width, height, border, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final void _wglClearColor(float r, float g, float b, float a) { + glClearColor(r, g, b, a); } - public static final void _wglTexImage2Du16(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, ByteBuffer data) { - nglTexImage2D(target, level, internalFormat, width, height, border, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final void _wglClearDepth(float f) { + glClearDepthf(f); } - public static final void _wglTexImage2Df32(int target, int level, int internalFormat, int width, int height, - int border, int format, int type, ByteBuffer data) { - nglTexImage2D(target, level, internalFormat, width, height, border, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final void _wglColorMask(boolean r, boolean g, boolean b, boolean a) { + glColorMask(r, g, b, a); } - public static final void _wglTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, - int format, int type, ByteBuffer data) { - nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, - int format, int type, IntBuffer data) { - nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, - int format, int type, FloatBuffer data) { - nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); - } - - public static final void _wglTexSubImage2Du16(int target, int level, int xoffset, int yoffset, int width, int height, - int format, int type, ByteBuffer data) { - nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, - data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + public static final void _wglCompileShader(IShaderGL obj) { + glCompileShader(((OpenGLObjects.ShaderGL) obj).ptr); } public static final void _wglCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, @@ -479,73 +313,86 @@ public class PlatformOpenGL { glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } - public static final void _wglTexStorage2D(int target, int levels, int internalFormat, int w, int h) { - switch(texStorageImpl) { - case TEX_STORAGE_IMPL_CORE: - glTexStorage2D(target, levels, internalFormat, w, h); + public static final IFramebufferGL _wglCreateFramebuffer() { + return new OpenGLObjects.FramebufferGL(glGenFramebuffers()); + } + + public static final IProgramGL _wglCreateProgram() { + return new OpenGLObjects.ProgramGL(glCreateProgram()); + } + + public static final IRenderbufferGL _wglCreateRenderbuffer() { + return new OpenGLObjects.RenderbufferGL(glGenRenderbuffers()); + } + + public static final IShaderGL _wglCreateShader(int type) { + return new OpenGLObjects.ShaderGL(glCreateShader(type)); + } + + public static final void _wglCullFace(int glEnum) { + glCullFace(glEnum); + } + + public static final void _wglDeleteBuffers(IBufferGL obj) { + glDeleteBuffers(((OpenGLObjects.BufferGL) obj).ptr); + } + + public static final void _wglDeleteFramebuffer(IFramebufferGL obj) { + glDeleteFramebuffers(((OpenGLObjects.FramebufferGL) obj).ptr); + } + + public static final void _wglDeleteProgram(IProgramGL obj) { + glDeleteProgram(((OpenGLObjects.ProgramGL) obj).ptr); + } + + public static final void _wglDeleteQueries(IQueryGL obj) { + glDeleteQueries(((OpenGLObjects.QueryGL) obj).ptr); + } + + public static final void _wglDeleteRenderbuffer(IRenderbufferGL obj) { + glDeleteRenderbuffers(((OpenGLObjects.RenderbufferGL) obj).ptr); + } + + public static final void _wglDeleteShader(IShaderGL obj) { + glDeleteShader(((OpenGLObjects.ShaderGL) obj).ptr); + } + + public static final void _wglDeleteTextures(ITextureGL obj) { + glDeleteTextures(((OpenGLObjects.TextureGL) obj).ptr); + } + + public static final void _wglDeleteVertexArrays(IBufferArrayGL obj) { + int ptr = ((OpenGLObjects.BufferArrayGL) obj).ptr; + switch (vertexArrayImpl) { + case VAO_IMPL_CORE: + glDeleteVertexArrays(ptr); break; - case TEX_STORAGE_IMPL_EXT: - glTexStorage2DEXT(target, levels, internalFormat, w, h); + case VAO_IMPL_OES: + glDeleteVertexArraysOES(ptr); break; default: throw new UnsupportedOperationException(); } } - public static final void _wglPixelStorei(int pname, int value) { - glPixelStorei(pname, value); + public static final void _wglDepthFunc(int glEnum) { + glDepthFunc(glEnum); } - public static final void _wglGenerateMipmap(int target) { - glGenerateMipmap(target); - } - - public static final void _wglShaderSource(IShaderGL obj, String source) { - glShaderSource(((OpenGLObjects.ShaderGL) obj).ptr, source); - } - - public static final void _wglCompileShader(IShaderGL obj) { - glCompileShader(((OpenGLObjects.ShaderGL) obj).ptr); - } - - public static final int _wglGetShaderi(IShaderGL obj, int param) { - return glGetShaderi(((OpenGLObjects.ShaderGL) obj).ptr, param); - } - - public static final String _wglGetShaderInfoLog(IShaderGL obj) { - return glGetShaderInfoLog(((OpenGLObjects.ShaderGL) obj).ptr); - } - - public static final void _wglUseProgram(IProgramGL obj) { - glUseProgram(obj == null ? 0 : ((OpenGLObjects.ProgramGL) obj).ptr); - } - - public static final void _wglAttachShader(IProgramGL obj, IShaderGL shader) { - glAttachShader(((OpenGLObjects.ProgramGL) obj).ptr, ((OpenGLObjects.ShaderGL) shader).ptr); + public static final void _wglDepthMask(boolean mask) { + glDepthMask(mask); } public static final void _wglDetachShader(IProgramGL obj, IShaderGL shader) { glDetachShader(((OpenGLObjects.ProgramGL) obj).ptr, ((OpenGLObjects.ShaderGL) shader).ptr); } - public static final void _wglLinkProgram(IProgramGL obj) { - glLinkProgram(((OpenGLObjects.ProgramGL) obj).ptr); + public static final void _wglDisable(int glEnum) { + glDisable(glEnum); } - public static final int _wglGetProgrami(IProgramGL obj, int param) { - return glGetProgrami(((OpenGLObjects.ProgramGL) obj).ptr, param); - } - - public static final String _wglGetProgramInfoLog(IProgramGL obj) { - return glGetProgramInfoLog(((OpenGLObjects.ProgramGL) obj).ptr); - } - - public static final void _wglBindAttribLocation(IProgramGL obj, int index, String name) { - glBindAttribLocation(((OpenGLObjects.ProgramGL) obj).ptr, index, name); - } - - public static final int _wglGetAttribLocation(IProgramGL obj, String name) { - return glGetAttribLocation(((OpenGLObjects.ProgramGL) obj).ptr, name); + public static final void _wglDisableVertexAttribArray(int index) { + glDisableVertexAttribArray(index); } public static final void _wglDrawArrays(int mode, int first, int count) { @@ -553,7 +400,7 @@ public class PlatformOpenGL { } public static final void _wglDrawArraysInstanced(int mode, int first, int count, int instanced) { - switch(instancingImpl) { + switch (instancingImpl) { case INSTANCE_IMPL_CORE: glDrawArraysInstanced(mode, first, count, instanced); break; @@ -568,12 +415,32 @@ public class PlatformOpenGL { } } + public static final void _wglDrawBuffers(int buffer) { + if (glesVers == 200) { + if (buffer != 0x8CE0) { // GL_COLOR_ATTACHMENT0 + throw new UnsupportedOperationException(); + } + } else { + glDrawBuffers(buffer); + } + } + + public static final void _wglDrawBuffers(int[] buffers) { + if (glesVers == 200) { + if (buffers.length != 1 || buffers[0] != 0x8CE0) { // GL_COLOR_ATTACHMENT0 + throw new UnsupportedOperationException(); + } + } else { + glDrawBuffers(buffers); + } + } + public static final void _wglDrawElements(int mode, int count, int type, int offset) { glDrawElements(mode, count, type, offset); } public static final void _wglDrawElementsInstanced(int mode, int count, int type, int offset, int instanced) { - switch(instancingImpl) { + switch (instancingImpl) { case INSTANCE_IMPL_CORE: glDrawElementsInstanced(mode, count, type, offset, instanced); break; @@ -588,21 +455,224 @@ public class PlatformOpenGL { } } - public static final IUniformGL _wglGetUniformLocation(IProgramGL obj, String name) { - int loc = glGetUniformLocation(((OpenGLObjects.ProgramGL) obj).ptr, name); - return loc < 0 ? null : new OpenGLObjects.UniformGL(loc); + public static final void _wglEnable(int glEnum) { + glEnable(glEnum); + } + + public static final void _wglEnableVertexAttribArray(int index) { + glEnableVertexAttribArray(index); + } + + public static final void _wglFramebufferRenderbuffer(int target, int attachment, int renderbufferTarget, + IRenderbufferGL renderbuffer) { + glFramebufferRenderbuffer(target, attachment, renderbufferTarget, + ((OpenGLObjects.RenderbufferGL) renderbuffer).ptr); + } + + public static final void _wglFramebufferTexture2D(int target, int attachment, int texTarget, ITextureGL texture, + int level) { + glFramebufferTexture2D(target, attachment, texTarget, ((OpenGLObjects.TextureGL) texture).ptr, level); + } + + public static final void _wglFramebufferTextureLayer(int target, int attachment, ITextureGL texture, int level, + int layer) { + glFramebufferTextureLayer(target, attachment, ((OpenGLObjects.TextureGL) texture).ptr, level, layer); + } + + public static final IBufferGL _wglGenBuffers() { + return new OpenGLObjects.BufferGL(glGenBuffers()); + } + + public static final void _wglGenerateMipmap(int target) { + glGenerateMipmap(target); + } + + public static final IQueryGL _wglGenQueries() { + return new OpenGLObjects.QueryGL(glGenQueries()); + } + + public static final ITextureGL _wglGenTextures() { + return new OpenGLObjects.TextureGL(glGenTextures()); + } + + public static final IBufferArrayGL _wglGenVertexArrays() { + switch (vertexArrayImpl) { + case VAO_IMPL_CORE: + return new OpenGLObjects.BufferArrayGL(glGenVertexArrays()); + case VAO_IMPL_OES: + return new OpenGLObjects.BufferArrayGL(glGenVertexArraysOES()); + default: + throw new UnsupportedOperationException(); + } + } + + public static final int _wglGetAttribLocation(IProgramGL obj, String name) { + return glGetAttribLocation(((OpenGLObjects.ProgramGL) obj).ptr, name); + } + + public static final int _wglGetError() { + return glGetError(); + } + + public static final int _wglGetInteger(int param) { + return glGetInteger(param); + } + + public static final int _wglGetProgrami(IProgramGL obj, int param) { + return glGetProgrami(((OpenGLObjects.ProgramGL) obj).ptr, param); + } + + public static final String _wglGetProgramInfoLog(IProgramGL obj) { + return glGetProgramInfoLog(((OpenGLObjects.ProgramGL) obj).ptr); + } + + public static final int _wglGetShaderi(IShaderGL obj, int param) { + return glGetShaderi(((OpenGLObjects.ShaderGL) obj).ptr, param); + } + + public static final String _wglGetShaderInfoLog(IShaderGL obj) { + return glGetShaderInfoLog(((OpenGLObjects.ShaderGL) obj).ptr); + } + + public static final String _wglGetString(int param) { + return glGetString(param); } public static final int _wglGetUniformBlockIndex(IProgramGL obj, String name) { return glGetUniformBlockIndex(((OpenGLObjects.ProgramGL) obj).ptr, name); } - public static final void _wglBindBufferRange(int target, int index, IBufferGL buffer, int offset, int size) { - glBindBufferRange(target, index, ((OpenGLObjects.BufferGL) buffer).ptr, offset, size); + public static final IUniformGL _wglGetUniformLocation(IProgramGL obj, String name) { + int loc = glGetUniformLocation(((OpenGLObjects.ProgramGL) obj).ptr, name); + return loc < 0 ? null : new OpenGLObjects.UniformGL(loc); } - public static final void _wglUniformBlockBinding(IProgramGL obj, int blockIndex, int bufferIndex) { - glUniformBlockBinding(((OpenGLObjects.ProgramGL) obj).ptr, blockIndex, bufferIndex); + public static final void _wglLineWidth(float width) { + glLineWidth(width); + } + + public static final void _wglLinkProgram(IProgramGL obj) { + glLinkProgram(((OpenGLObjects.ProgramGL) obj).ptr); + } + + public static final void _wglPixelStorei(int pname, int value) { + glPixelStorei(pname, value); + } + + public static final void _wglPolygonOffset(float f1, float f2) { + glPolygonOffset(f1, f2); + } + + public static final void _wglReadBuffer(int buffer) { + glReadBuffer(buffer); + } + + public static final void _wglReadPixels(int x, int y, int width, int height, int format, int type, + ByteBuffer data) { + nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglReadPixels(int x, int y, int width, int height, int format, int type, + FloatBuffer data) { + nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglReadPixels(int x, int y, int width, int height, int format, int type, IntBuffer data) { + nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglReadPixels_u16(int x, int y, int width, int height, int format, int type, + ByteBuffer data) { + nglReadPixels(x, y, width, height, format, type, EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglRenderbufferStorage(int target, int internalformat, int width, int height) { + glRenderbufferStorage(target, internalformat, width, height); + } + + public static final void _wglShaderSource(IShaderGL obj, String source) { + glShaderSource(((OpenGLObjects.ShaderGL) obj).ptr, source); + } + + public static final void _wglTexImage2D(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, ByteBuffer data) { + nglTexImage2D(target, level, internalFormat, width, height, border, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexImage2D(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, FloatBuffer data) { + nglTexImage2D(target, level, internalFormat, width, height, border, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexImage2D(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, IntBuffer data) { + nglTexImage2D(target, level, internalFormat, width, height, border, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexImage2Df32(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, ByteBuffer data) { + nglTexImage2D(target, level, internalFormat, width, height, border, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexImage2Du16(int target, int level, int internalFormat, int width, int height, + int border, int format, int type, ByteBuffer data) { + nglTexImage2D(target, level, internalFormat, width, height, border, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexImage3D(int target, int level, int internalFormat, int width, int height, int depth, + int border, int format, int type, ByteBuffer data) { + nglTexImage3D(target, level, internalFormat, width, height, depth, border, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexParameterf(int target, int param, float value) { + glTexParameterf(target, param, value); + } + + public static final void _wglTexParameteri(int target, int param, int value) { + glTexParameteri(target, param, value); + } + + public static final void _wglTexStorage2D(int target, int levels, int internalFormat, int w, int h) { + switch (texStorageImpl) { + case TEX_STORAGE_IMPL_CORE: + glTexStorage2D(target, levels, internalFormat, w, h); + break; + case TEX_STORAGE_IMPL_EXT: + glTexStorage2DEXT(target, levels, internalFormat, w, h); + break; + default: + throw new UnsupportedOperationException(); + } + } + + public static final void _wglTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, + int format, int type, ByteBuffer data) { + nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, + int format, int type, FloatBuffer data) { + nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, + int format, int type, IntBuffer data) { + nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); + } + + public static final void _wglTexSubImage2Du16(int target, int level, int xoffset, int yoffset, int width, + int height, int format, int type, ByteBuffer data) { + nglTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, + data == null ? 0l : EaglerLWJGLAllocator.getAddress(data)); } public static final void _wglUniform1f(IUniformGL obj, float x) { @@ -610,41 +680,45 @@ public class PlatformOpenGL { glUniform1f(((OpenGLObjects.UniformGL) obj).ptr, x); } - public static final void _wglUniform2f(IUniformGL obj, float x, float y) { - if (obj != null) - glUniform2f(((OpenGLObjects.UniformGL) obj).ptr, x, y); - } - - public static final void _wglUniform3f(IUniformGL obj, float x, float y, float z) { - if (obj != null) - glUniform3f(((OpenGLObjects.UniformGL) obj).ptr, x, y, z); - } - - public static final void _wglUniform4f(IUniformGL obj, float x, float y, float z, float w) { - if (obj != null) - glUniform4f(((OpenGLObjects.UniformGL) obj).ptr, x, y, z, w); - } - public static final void _wglUniform1i(IUniformGL obj, int x) { if (obj != null) glUniform1i(((OpenGLObjects.UniformGL) obj).ptr, x); } + public static final void _wglUniform2f(IUniformGL obj, float x, float y) { + if (obj != null) + glUniform2f(((OpenGLObjects.UniformGL) obj).ptr, x, y); + } + public static final void _wglUniform2i(IUniformGL obj, int x, int y) { if (obj != null) glUniform2i(((OpenGLObjects.UniformGL) obj).ptr, x, y); } + public static final void _wglUniform3f(IUniformGL obj, float x, float y, float z) { + if (obj != null) + glUniform3f(((OpenGLObjects.UniformGL) obj).ptr, x, y, z); + } + public static final void _wglUniform3i(IUniformGL obj, int x, int y, int z) { if (obj != null) glUniform3i(((OpenGLObjects.UniformGL) obj).ptr, x, y, z); } + public static final void _wglUniform4f(IUniformGL obj, float x, float y, float z, float w) { + if (obj != null) + glUniform4f(((OpenGLObjects.UniformGL) obj).ptr, x, y, z, w); + } + public static final void _wglUniform4i(IUniformGL obj, int x, int y, int z, int w) { if (obj != null) glUniform4i(((OpenGLObjects.UniformGL) obj).ptr, x, y, z, w); } + public static final void _wglUniformBlockBinding(IProgramGL obj, int blockIndex, int bufferIndex) { + glUniformBlockBinding(((OpenGLObjects.ProgramGL) obj).ptr, blockIndex, bufferIndex); + } + public static final void _wglUniformMatrix2fv(IUniformGL obj, boolean transpose, FloatBuffer mat) { if (obj != null) nglUniformMatrix2fv(((OpenGLObjects.UniformGL) obj).ptr, mat.remaining() >> 2, transpose, @@ -681,82 +755,90 @@ public class PlatformOpenGL { EaglerLWJGLAllocator.getAddress(mat)); } - public static final void _wglBindFramebuffer(int target, IFramebufferGL framebuffer) { - if(framebuffer == null) { - glBindFramebuffer(target, 0); - }else { - glBindFramebuffer(target, ((OpenGLObjects.FramebufferGL) framebuffer).ptr); + public static final void _wglUseProgram(IProgramGL obj) { + glUseProgram(obj == null ? 0 : ((OpenGLObjects.ProgramGL) obj).ptr); + } + + public static final void _wglVertexAttribDivisor(int index, int divisor) { + switch (instancingImpl) { + case INSTANCE_IMPL_CORE: + glVertexAttribDivisor(index, divisor); + break; + case INSTANCE_IMPL_ANGLE: + glVertexAttribDivisorANGLE(index, divisor); + break; + case INSTANCE_IMPL_EXT: + glVertexAttribDivisorEXT(index, divisor); + break; + default: + throw new UnsupportedOperationException(); } } - public static final int _wglCheckFramebufferStatus(int target) { - return glCheckFramebufferStatus(target); + public static final void _wglVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, + int offset) { + glVertexAttribPointer(index, size, type, normalized, stride, offset); } - public static final void _wglFramebufferTexture2D(int target, int attachment, int texTarget, ITextureGL texture, - int level) { - glFramebufferTexture2D(target, attachment, texTarget, ((OpenGLObjects.TextureGL) texture).ptr, level); + public static final void _wglViewport(int x, int y, int w, int h) { + glViewport(x, y, w, h); } - public static final void _wglFramebufferTextureLayer(int target, int attachment, ITextureGL texture, int level, int layer) { - glFramebufferTextureLayer(target, attachment, ((OpenGLObjects.TextureGL) texture).ptr, level, layer); - } - - public static final void _wglBlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, - int dstX1, int dstY1, int bits, int filter) { - glBlitFramebuffer(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, bits, filter); - } - - public static final void _wglBindRenderbuffer(int target, IRenderbufferGL renderbuffer) { - glBindRenderbuffer(target, renderbuffer == null ? 0 : ((OpenGLObjects.RenderbufferGL) renderbuffer).ptr); - } - - public static final void _wglRenderbufferStorage(int target, int internalformat, int width, int height) { - glRenderbufferStorage(target, internalformat, width, height); - } - - public static final void _wglFramebufferRenderbuffer(int target, int attachment, int renderbufferTarget, - IRenderbufferGL renderbuffer) { - glFramebufferRenderbuffer(target, attachment, renderbufferTarget, - ((OpenGLObjects.RenderbufferGL) renderbuffer).ptr); - } - - public static final String _wglGetString(int param) { - return glGetString(param); - } - - public static final int _wglGetInteger(int param) { - return glGetInteger(param); - } - - public static final int _wglGetError() { - return glGetError(); - } - - public static final int checkOpenGLESVersion() { - return glesVers; + public static final boolean checkAnisotropicFilteringSupport() { + return hasEXTTextureFilterAnisotropic; } public static final boolean checkEXTGPUShader5Capable() { return hasEXTGPUShader5; } - public static final boolean checkOESGPUShader5Capable() { - return hasOESGPUShader5; - } - public static final boolean checkFBORenderMipmapCapable() { return hasOESFBORenderMipmap; } - public static final boolean checkVAOCapable() { - return vertexArrayImpl != VAO_IMPL_NONE; + public static final boolean checkHDRFramebufferSupport(int bits) { + switch (bits) { + case 16: + return hasFBO16FSupport; + case 32: + return hasFBO32FSupport; + default: + return false; + } } public static final boolean checkInstancingCapable() { return instancingImpl != INSTANCE_IMPL_NONE; } + // legacy + public static final boolean checkLinearHDR32FSupport() { + return hasLinearHDR32FSupport; + } + + public static final boolean checkLinearHDRFilteringSupport(int bits) { + switch (bits) { + case 16: + return hasLinearHDR16FSupport; + case 32: + return hasLinearHDR32FSupport; + default: + return false; + } + } + + public static final boolean checkNPOTCapable() { + return glesVers >= 300; + } + + public static final boolean checkOESGPUShader5Capable() { + return hasOESGPUShader5; + } + + public static final int checkOpenGLESVersion() { + return glesVers; + } + public static final boolean checkTexStorageCapable() { return texStorageImpl != TEX_STORAGE_IMPL_NONE; } @@ -765,47 +847,93 @@ public class PlatformOpenGL { return glesVers >= 300 || hasEXTShaderTextureLOD; } - public static final boolean checkNPOTCapable() { - return glesVers >= 300; + public static final boolean checkVAOCapable() { + return vertexArrayImpl != VAO_IMPL_NONE; } - public static final boolean checkHDRFramebufferSupport(int bits) { - switch(bits) { - case 16: - return hasFBO16FSupport; - case 32: - return hasFBO32FSupport; - default: - return false; - } + public static final List dumpActiveExtensions() { + List exts = new ArrayList<>(); + if (hasANGLEInstancedArrays) + exts.add("ANGLE_instanced_arrays"); + if (hasEXTColorBufferFloat) + exts.add("EXT_color_buffer_float"); + if (hasEXTColorBufferHalfFloat) + exts.add("EXT_color_buffer_half_float"); + if (hasEXTGPUShader5) + exts.add("EXT_gpu_shader5"); + if (hasEXTInstancedArrays) + exts.add("EXT_instanced_arrays"); + if (hasEXTTextureStorage) + exts.add("EXT_texture_storage"); + if (hasOESFBORenderMipmap) + exts.add("OES_fbo_render_mipmap"); + if (hasOESGPUShader5) + exts.add("OES_gpu_shader5"); + if (hasOESVertexArrayObject) + exts.add("OES_vertex_array_object"); + if (hasOESTextureFloat) + exts.add("OES_texture_float"); + if (hasOESTextureFloatLinear) + exts.add("OES_texture_float_linear"); + if (hasOESTextureHalfFloat) + exts.add("OES_texture_half_float"); + if (hasOESTextureHalfFloatLinear) + exts.add("OES_texture_half_float_linear"); + if (hasEXTTextureFilterAnisotropic) + exts.add("EXT_texture_filter_anisotropic"); + return exts; } - public static final boolean checkLinearHDRFilteringSupport(int bits) { - switch(bits) { - case 16: - return hasLinearHDR16FSupport; - case 32: - return hasLinearHDR32FSupport; - default: - return false; - } - } + public static final void enterVAOEmulationHook() { - // legacy - public static final boolean checkLinearHDR32FSupport() { - return hasLinearHDR32FSupport; - } - - public static final boolean checkAnisotropicFilteringSupport() { - return hasEXTTextureFilterAnisotropic; } public static final String[] getAllExtensions() { return glGetString(GL_EXTENSIONS).split(" "); } - public static final void enterVAOEmulationHook() { - + static void setCurrentContext(int glesVersIn, GLESCapabilities caps) { + glesVers = glesVersIn; + + hasANGLEInstancedArrays = glesVersIn == 200 && caps.GL_ANGLE_instanced_arrays; + hasOESTextureFloat = glesVersIn == 200 && caps.GL_OES_texture_float; + hasOESTextureFloatLinear = glesVersIn >= 300 && caps.GL_OES_texture_float_linear; + hasOESTextureHalfFloat = glesVersIn == 200 && caps.GL_OES_texture_half_float; + hasOESTextureHalfFloatLinear = glesVersIn == 200 && caps.GL_OES_texture_half_float_linear; + hasEXTColorBufferFloat = (glesVersIn == 310 || glesVersIn == 300) && caps.GL_EXT_color_buffer_float; + hasEXTColorBufferHalfFloat = !hasEXTColorBufferFloat + && (glesVersIn == 310 || glesVersIn == 300 || glesVersIn == 200) && caps.GL_EXT_color_buffer_half_float; + hasEXTInstancedArrays = !hasANGLEInstancedArrays && glesVersIn == 200 && caps.GL_EXT_instanced_arrays; + hasEXTShaderTextureLOD = glesVersIn == 200 && caps.GL_EXT_shader_texture_lod; + hasEXTTextureStorage = glesVersIn == 200 && caps.GL_EXT_texture_storage; + hasOESGPUShader5 = glesVersIn == 310 && caps.GL_OES_gpu_shader5; + hasEXTGPUShader5 = !hasOESGPUShader5 && glesVersIn == 310 && caps.GL_EXT_gpu_shader5; + hasOESFBORenderMipmap = glesVersIn == 200 && caps.GL_OES_fbo_render_mipmap; + hasOESVertexArrayObject = glesVersIn == 200 && caps.GL_OES_vertex_array_object; + hasLinearHDR32FSupport = caps.GL_OES_texture_float_linear; + hasEXTTextureFilterAnisotropic = caps.GL_EXT_texture_filter_anisotropic; + + hasFBO16FSupport = glesVersIn >= 320 || ((glesVersIn >= 300 || hasOESTextureFloat) + && (hasEXTColorBufferFloat || hasEXTColorBufferHalfFloat)); + hasFBO32FSupport = glesVersIn >= 320 + || ((glesVersIn >= 300 || hasOESTextureHalfFloat) && hasEXTColorBufferFloat); + hasLinearHDR16FSupport = glesVersIn >= 300 || hasOESTextureHalfFloatLinear; + hasLinearHDR32FSupport = glesVersIn >= 300 && hasOESTextureFloatLinear; + + if (glesVersIn >= 300) { + vertexArrayImpl = VAO_IMPL_CORE; + instancingImpl = INSTANCE_IMPL_CORE; + texStorageImpl = TEX_STORAGE_IMPL_CORE; + } else if (glesVersIn == 200) { + vertexArrayImpl = hasOESVertexArrayObject ? VAO_IMPL_OES : VAO_IMPL_NONE; + instancingImpl = hasANGLEInstancedArrays ? INSTANCE_IMPL_ANGLE + : (hasEXTInstancedArrays ? INSTANCE_IMPL_EXT : INSTANCE_IMPL_NONE); + texStorageImpl = hasEXTTextureStorage ? TEX_STORAGE_IMPL_EXT : TEX_STORAGE_IMPL_NONE; + } else { + vertexArrayImpl = VAO_IMPL_NONE; + instancingImpl = INSTANCE_IMPL_NONE; + texStorageImpl = TEX_STORAGE_IMPL_NONE; + } } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java index 28b9bcb5..e9e12ea4 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java @@ -1,8 +1,38 @@ package net.lax1dude.eaglercraft.v1_8.internal; -import static org.lwjgl.egl.EGL10.*; -import static org.lwjgl.glfw.GLFW.*; -import static org.lwjgl.glfw.GLFWNativeEGL.*; +import static org.lwjgl.egl.EGL10.EGL_VERSION; +import static org.lwjgl.egl.EGL10.eglInitialize; +import static org.lwjgl.egl.EGL10.eglQueryString; +import static org.lwjgl.glfw.GLFW.GLFW_ANGLE_PLATFORM_TYPE; +import static org.lwjgl.glfw.GLFW.GLFW_CENTER_CURSOR; +import static org.lwjgl.glfw.GLFW.GLFW_CLIENT_API; +import static org.lwjgl.glfw.GLFW.GLFW_CONTEXT_CREATION_API; +import static org.lwjgl.glfw.GLFW.GLFW_CONTEXT_VERSION_MAJOR; +import static org.lwjgl.glfw.GLFW.GLFW_CONTEXT_VERSION_MINOR; +import static org.lwjgl.glfw.GLFW.GLFW_EGL_CONTEXT_API; +import static org.lwjgl.glfw.GLFW.GLFW_OPENGL_DEBUG_CONTEXT; +import static org.lwjgl.glfw.GLFW.GLFW_OPENGL_ES_API; +import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE; +import static org.lwjgl.glfw.GLFW.GLFW_TRUE; +import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE; +import static org.lwjgl.glfw.GLFW.glfwCreateWindow; +import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints; +import static org.lwjgl.glfw.GLFW.glfwDestroyWindow; +import static org.lwjgl.glfw.GLFW.glfwGetMonitors; +import static org.lwjgl.glfw.GLFW.glfwGetVersionString; +import static org.lwjgl.glfw.GLFW.glfwGetVideoMode; +import static org.lwjgl.glfw.GLFW.glfwGetWindowFrameSize; +import static org.lwjgl.glfw.GLFW.glfwGetWindowPos; +import static org.lwjgl.glfw.GLFW.glfwInit; +import static org.lwjgl.glfw.GLFW.glfwInitHint; +import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent; +import static org.lwjgl.glfw.GLFW.glfwSetWindowIcon; +import static org.lwjgl.glfw.GLFW.glfwSetWindowPos; +import static org.lwjgl.glfw.GLFW.glfwSetWindowSize; +import static org.lwjgl.glfw.GLFW.glfwSwapInterval; +import static org.lwjgl.glfw.GLFW.glfwTerminate; +import static org.lwjgl.glfw.GLFW.glfwWindowHint; +import static org.lwjgl.glfw.GLFWNativeEGL.glfwGetEGLDisplay; import java.awt.image.BufferedImage; import java.io.File; @@ -39,10 +69,10 @@ import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.system.jemalloc.JEmalloc; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.EaglerLWJGLAllocator; import net.lax1dude.eaglercraft.v1_8.EaglerOutputStream; import net.lax1dude.eaglercraft.v1_8.Filesystem; import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.EaglerLWJGLAllocator; import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.DesktopClientConfigAdapter; @@ -55,57 +85,160 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplay /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformRuntime { - + + public static class NativeNIO { + + public static java.nio.ByteBuffer allocateByteBuffer(int length) { + long ret = JEmalloc.nje_malloc(length); + if (ret == 0l) { + throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); + } + return MemoryUtil.memByteBuffer(ret, length); + } + + public static java.nio.FloatBuffer allocateFloatBuffer(int length) { + long ret = JEmalloc.nje_malloc(length << 2); + if (ret == 0l) { + throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); + } + return MemoryUtil.memFloatBuffer(ret, length); + } + + public static java.nio.IntBuffer allocateIntBuffer(int length) { + long ret = JEmalloc.nje_malloc(length << 2); + if (ret == 0l) { + throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); + } + return MemoryUtil.memIntBuffer(ret, length); + } + + public static void freeByteBuffer(java.nio.ByteBuffer byteBuffer) { + JEmalloc.nje_free(MemoryUtil.memAddress(byteBuffer)); + } + + public static void freeFloatBuffer(java.nio.FloatBuffer floatBuffer) { + JEmalloc.nje_free(MemoryUtil.memAddress(floatBuffer)); + } + + public static void freeIntBuffer(java.nio.IntBuffer intBuffer) { + JEmalloc.nje_free(MemoryUtil.memAddress(intBuffer)); + } + + public static java.nio.ByteBuffer getAsByteBuffer(java.nio.FloatBuffer floatBuffer) { + return MemoryUtil.memByteBuffer(MemoryUtil.memAddress(floatBuffer), floatBuffer.capacity() << 2); + } + + public static java.nio.ByteBuffer getAsByteBuffer(java.nio.IntBuffer intBuffer) { + return MemoryUtil.memByteBuffer(MemoryUtil.memAddress(intBuffer), intBuffer.capacity() << 2); + } + + public static java.nio.FloatBuffer getFloatBuffer(java.nio.ByteBuffer byteBuffer) { + return MemoryUtil.memFloatBuffer(MemoryUtil.memAddress(byteBuffer), byteBuffer.capacity() >> 2); + } + + public static java.nio.IntBuffer getIntBuffer(java.nio.ByteBuffer byteBuffer) { + return MemoryUtil.memIntBuffer(MemoryUtil.memAddress(byteBuffer), byteBuffer.capacity() >> 2); + } + + } + static final Logger logger = LogManager.getLogger("RuntimeLWJGL3"); - private static String glVersion = "unknown"; + private static String glRenderer = "unknown"; private static EnumPlatformANGLE rendererANGLEPlatform = null; - + private static long windowHandle = 0l; + private static EnumPlatformOS currentPlatformOS = null; + + private static EnumPlatformANGLE requestedANGLEPlatform = EnumPlatformANGLE.DEFAULT; + + private static int requestedGLVersion = 300; + + private static final Random seedProvider = new Random(); + + public static ByteBuffer allocateByteBuffer(int length) { + return EaglerLWJGLAllocator.allocByteBuffer(length); + } + + public static FloatBuffer allocateFloatBuffer(int length) { + return EaglerLWJGLAllocator.allocFloatBuffer(length); + } + + public static IntBuffer allocateIntBuffer(int length) { + return EaglerLWJGLAllocator.allocIntBuffer(length); + } + + public static byte[] castNativeByteBuffer(ByteBuffer buffer) { + return null; + } + + public static float[] castNativeFloatBuffer(FloatBuffer buffer) { + return null; + } + + public static int[] castNativeIntBuffer(IntBuffer buffer) { + return null; + } + + public static ByteBuffer castPrimitiveByteArray(byte[] array) { + return null; + } + + public static FloatBuffer castPrimitiveFloatArray(float[] array) { + return null; + } + + public static IntBuffer castPrimitiveIntArray(int[] array) { + return null; + } + public static void create() { logger.info("Starting Desktop Runtime..."); - + ByteBuffer endiannessTestBytes = allocateByteBuffer(4); try { endiannessTestBytes.asIntBuffer().put(0x6969420); if (((endiannessTestBytes.get(0) & 0xFF) | ((endiannessTestBytes.get(1) & 0xFF) << 8) - | ((endiannessTestBytes.get(2) & 0xFF) << 16) | ((endiannessTestBytes.get(3) & 0xFF) << 24)) != 0x6969420) { - throw new UnsupportedOperationException("Big endian CPU detected! (somehow)"); - }else { + | ((endiannessTestBytes.get(2) & 0xFF) << 16) + | ((endiannessTestBytes.get(3) & 0xFF) << 24)) != 0x6969420) { + throw new PlatformIncompatibleException("Big endian CPU detected! (somehow)"); + } else { logger.info("Endianness: this CPU is little endian"); } - }finally { + } finally { freeByteBuffer(endiannessTestBytes); } - - IEaglerFilesystem resourcePackFilesystem = Filesystem.getHandleFor(getClientConfigAdapter().getResourcePacksDB()); + + IEaglerFilesystem resourcePackFilesystem = Filesystem + .getHandleFor(getClientConfigAdapter().getResourcePacksDB()); VFile2.setPrimaryFilesystem(resourcePackFilesystem); EaglerFolderResourcePack.setSupported(true); - - if(requestedANGLEPlatform != EnumPlatformANGLE.DEFAULT) { + + if (requestedANGLEPlatform != EnumPlatformANGLE.DEFAULT) { logger.info("Setting ANGLE Platform: {}", requestedANGLEPlatform.name); glfwInitHint(GLFW_ANGLE_PLATFORM_TYPE, requestedANGLEPlatform.eglEnum); } - + glfwInit(); logger.info("GLFW Version: {}", glfwGetVersionString()); - + glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, GLFW_TRUE); glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); @@ -125,187 +258,215 @@ public class PlatformRuntime { int winX = (mon.width() - windowWidth) / 2; int winY = (mon.height() - windowHeight - 20) / 2; - + int myGLVersion = -1; - if(requestedGLVersion >= 310 && windowHandle == 0) { + if (requestedGLVersion >= 310 && windowHandle == 0) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); windowHandle = glfwCreateWindow(windowWidth, windowHeight, title, 0l, 0l); - if(windowHandle == 0l) { + if (windowHandle == 0l) { logger.error("Failed to create OpenGL ES 3.1 context!"); - }else { + } else { myGLVersion = 310; } } - if(requestedGLVersion >= 300 && windowHandle == 0) { + if (requestedGLVersion >= 300 && windowHandle == 0) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); windowHandle = glfwCreateWindow(windowWidth, windowHeight, title, 0l, 0l); - if(windowHandle == 0l) { + if (windowHandle == 0l) { logger.error("Failed to create OpenGL ES 3.0 context!"); - }else { + } else { myGLVersion = 300; } } - if(requestedGLVersion >= 200 && windowHandle == 0) { + if (requestedGLVersion >= 200 && windowHandle == 0) { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); windowHandle = glfwCreateWindow(windowWidth, windowHeight, title, 0l, 0l); - if(windowHandle == 0l) { + if (windowHandle == 0l) { logger.error("Failed to create OpenGL ES 2.0 context!"); - }else { + } else { myGLVersion = 200; } } - if(myGLVersion == -1) { - throw new RuntimeException("Could not create a supported OpenGL ES context!"); + if (myGLVersion == -1) { + throw new PlatformIncompatibleException("Could not create a supported OpenGL ES context!"); } - + glfwSetWindowPos(windowHandle, winX, winY); - + int[] x2 = new int[1]; int[] y2 = new int[1]; int[] w2 = new int[1]; int[] h2 = new int[1]; glfwGetWindowFrameSize(windowHandle, x2, y2, w2, h2); glfwSetWindowSize(windowHandle, windowWidth - x2[0] - w2[0], windowHeight - y2[0] - h2[0]); - + ImageIO.setUseCache(false); BufferedImage[] windowIcons = null; - + try { - windowIcons = new BufferedImage[] { - ImageIO.read(new File("icon16.png")), - ImageIO.read(new File("icon32.png")) - }; - }catch(IOException t) { + windowIcons = new BufferedImage[] { ImageIO.read(new File("icon16.png")), + ImageIO.read(new File("icon32.png")) }; + } catch (IOException t) { logger.error("Could not load default window icons!"); logger.error(t); } - - if(windowIcons != null) { - try(MemoryStack st = MemoryStack.stackPush()) { + + if (windowIcons != null) { + try (MemoryStack st = MemoryStack.stackPush()) { GLFWImage.Buffer windowIconsBuffer = GLFWImage.malloc(windowIcons.length, st); - - for(int i = 0; i < windowIcons.length; ++i) { + + for (int i = 0; i < windowIcons.length; ++i) { int w = windowIcons[i].getWidth(); int h = windowIcons[i].getHeight(); - + int[] px = new int[w * h]; windowIcons[i].getRGB(0, 0, w, h, px, 0, w); - - for(int j = 0; j < px.length; ++j) { + + for (int j = 0; j < px.length; ++j) { px[j] = (px[j] & 0xFF00FF00) | ((px[j] >>> 16) & 0xFF) | ((px[j] & 0xFF) << 16); // swap R/B } - + java.nio.ByteBuffer iconBuffer = st.malloc(w * h * 4); iconBuffer.asIntBuffer().put(px); iconBuffer.flip(); - + windowIconsBuffer.position(i); windowIconsBuffer.width(w); windowIconsBuffer.height(h); windowIconsBuffer.pixels(iconBuffer); } - + glfwSetWindowIcon(windowHandle, windowIconsBuffer); } } - + long glfw_eglHandle = glfwGetEGLDisplay(); logger.info("EGL Version: {}", eglQueryString(glfw_eglHandle, EGL_VERSION)); - + int[] major = new int[] { 1 }; int[] minor = new int[] { 4 }; - if(!eglInitialize(glfw_eglHandle, major, minor)) { - throw new RuntimeException("Could not initialize EGL"); + if (!eglInitialize(glfw_eglHandle, major, minor)) { + throw new RuntimeInitializationFailureException("Could not initialize EGL"); } - + EGL.createDisplayCapabilities(glfw_eglHandle, major[0], minor[0]); glfwMakeContextCurrent(windowHandle); GLESCapabilities caps = GLES.createCapabilities(); PlatformOpenGL.setCurrentContext(myGLVersion, caps); - + logger.info("OpenGL Version: {}", (glVersion = GLES30.glGetString(GLES30.GL_VERSION))); logger.info("OpenGL Renderer: {}", (glRenderer = GLES30.glGetString(GLES30.GL_RENDERER))); rendererANGLEPlatform = EnumPlatformANGLE.fromGLRendererString(glRenderer); - + int realGLVersion = (glVersion != null && probablyGLES2(glVersion)) ? 200 : (GLES30.glGetInteger(GLES30.GL_MAJOR_VERSION) * 100 + GLES30.glGetInteger(GLES30.GL_MINOR_VERSION) * 10); - if(realGLVersion != myGLVersion) { + if (realGLVersion != myGLVersion) { logger.warn("Unexpected GLES verison resolved for requested {} context: {}", myGLVersion, realGLVersion); - if(myGLVersion == 200) { + if (myGLVersion == 200) { logger.warn("Note: try adding the \"d3d9\" option if you are on windows trying to get GLES 2.0"); } - if(realGLVersion != 320 && realGLVersion != 310 && realGLVersion != 300 && realGLVersion != 200) { - throw new RuntimeException("Unsupported OpenGL ES version detected: " + realGLVersion); + if (realGLVersion != 320 && realGLVersion != 310 && realGLVersion != 300 && realGLVersion != 200) { + throw new PlatformIncompatibleException("Unsupported OpenGL ES version detected: " + realGLVersion); } myGLVersion = realGLVersion; PlatformOpenGL.setCurrentContext(myGLVersion, caps); } - - if(requestedANGLEPlatform != EnumPlatformANGLE.DEFAULT - && rendererANGLEPlatform != requestedANGLEPlatform) { + + if (requestedANGLEPlatform != EnumPlatformANGLE.DEFAULT && rendererANGLEPlatform != requestedANGLEPlatform) { logger.warn("Incorrect ANGLE Platform: {}", rendererANGLEPlatform.name); } - - if(requestedANGLEPlatform == EnumPlatformANGLE.DEFAULT) { + + if (requestedANGLEPlatform == EnumPlatformANGLE.DEFAULT) { logger.info("ANGLE Platform: {}", rendererANGLEPlatform.name); } - + List exts = PlatformOpenGL.dumpActiveExtensions(); - if(exts.isEmpty()) { + if (exts.isEmpty()) { logger.info("Unlocked the following OpenGL ES extensions: (NONE)"); - }else { + } else { Collections.sort(exts); logger.info("Unlocked the following OpenGL ES extensions:"); - for(int i = 0, l = exts.size(); i < l; ++i) { + for (int i = 0, l = exts.size(); i < l; ++i) { logger.info(" - " + exts.get(i)); } } - - + glfwSwapInterval(0); - + KHRDebug.glDebugMessageCallbackKHR(new GLDebugMessageKHRCallbackI() { @Override public void invoke(int source, int type, int id, int severity, int length, long message, long userParam) { StringBuilder b = new StringBuilder(); - b.append("[KHR DEBUG #"); b.append(id); b.append("] "); + b.append("[KHR DEBUG #"); + b.append(id); + b.append("] "); - switch(source) { - case KHRDebug.GL_DEBUG_SOURCE_API_KHR: b.append("[API - "); break; - case KHRDebug.GL_DEBUG_SOURCE_APPLICATION_KHR: b.append("[APPLICATION - "); break; - case KHRDebug.GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: b.append("[SHADER COMPILER - "); break; - case KHRDebug.GL_DEBUG_SOURCE_THIRD_PARTY_KHR: b.append("[THIRD PARTY - "); break; - case KHRDebug.GL_DEBUG_SOURCE_OTHER_KHR: default: b.append("[OTHER - "); break; - } - - switch(type) { - case KHRDebug.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: b.append("DEPRECATED BEHAVIOR] "); break; - case KHRDebug.GL_DEBUG_TYPE_ERROR_KHR: b.append("ERROR] "); break; + switch (source) { + case KHRDebug.GL_DEBUG_SOURCE_API_KHR: + b.append("[API - "); + break; + case KHRDebug.GL_DEBUG_SOURCE_APPLICATION_KHR: + b.append("[APPLICATION - "); + break; + case KHRDebug.GL_DEBUG_SOURCE_SHADER_COMPILER_KHR: + b.append("[SHADER COMPILER - "); + break; + case KHRDebug.GL_DEBUG_SOURCE_THIRD_PARTY_KHR: + b.append("[THIRD PARTY - "); + break; + case KHRDebug.GL_DEBUG_SOURCE_OTHER_KHR: default: - case KHRDebug.GL_DEBUG_TYPE_OTHER_KHR: b.append("OTHER] "); break; - case KHRDebug.GL_DEBUG_TYPE_PERFORMANCE_KHR: b.append("PERFORMANCE] "); break; - case KHRDebug.GL_DEBUG_TYPE_PORTABILITY_KHR: b.append("PORTABILITY] "); break; - case KHRDebug.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: b.append("UNDEFINED BEHAVIOR] "); break; + b.append("[OTHER - "); + break; } - switch(severity) { + switch (type) { + case KHRDebug.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR: + b.append("DEPRECATED BEHAVIOR] "); + break; + case KHRDebug.GL_DEBUG_TYPE_ERROR_KHR: + b.append("ERROR] "); + break; default: - case KHRDebug.GL_DEBUG_SEVERITY_LOW_KHR: b.append("[LOW Severity] "); break; - case KHRDebug.GL_DEBUG_SEVERITY_MEDIUM_KHR: b.append("[MEDIUM Severity] "); break; - case KHRDebug.GL_DEBUG_SEVERITY_HIGH_KHR: b.append("[SEVERE] "); break; + case KHRDebug.GL_DEBUG_TYPE_OTHER_KHR: + b.append("OTHER] "); + break; + case KHRDebug.GL_DEBUG_TYPE_PERFORMANCE_KHR: + b.append("PERFORMANCE] "); + break; + case KHRDebug.GL_DEBUG_TYPE_PORTABILITY_KHR: + b.append("PORTABILITY] "); + break; + case KHRDebug.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR: + b.append("UNDEFINED BEHAVIOR] "); + break; } - + + switch (severity) { + default: + case KHRDebug.GL_DEBUG_SEVERITY_LOW_KHR: + b.append("[LOW Severity] "); + break; + case KHRDebug.GL_DEBUG_SEVERITY_MEDIUM_KHR: + b.append("[MEDIUM Severity] "); + break; + case KHRDebug.GL_DEBUG_SEVERITY_HIGH_KHR: + b.append("[SEVERE] "); + break; + } + String message2 = GLDebugMessageKHRCallback.getMessage(length, message); - if(message2.contains("GPU stall due to ReadPixels")) return; + if (message2.contains("GPU stall due to ReadPixels")) + return; b.append(message2); logger.error(b.toString()); StackTraceElement[] ex = new RuntimeException().getStackTrace(); - for(int i = 0; i < ex.length; ++i) { + for (int i = 0; i < ex.length; ++i) { logger.error(" at {}", ex[i]); } } @@ -313,7 +474,7 @@ public class PlatformRuntime { GLES30.glEnable(KHRDebug.GL_DEBUG_OUTPUT_KHR); GLES30.glEnable(KHRDebug.GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR); - + logger.info("Initializing Audio..."); PlatformAudio.platformInitialize(); @@ -321,7 +482,11 @@ public class PlatformRuntime { PlatformInput.initHooks(windowHandle); PlatformApplication.initHooks(windowHandle); } - + + public static String currentThreadName() { + return Thread.currentThread().getName(); + } + public static void destroy() { PlatformAudio.platformShutdown(); Filesystem.closeAllHandles(); @@ -332,36 +497,155 @@ public class PlatformRuntime { glfwTerminate(); } - private static boolean probablyGLES2(String glVersion) { - if(glVersion == null) return false; - glVersion = glVersion.toLowerCase(); - return glVersion.contains("opengl es 2.0") || glVersion.contains("ES 2.0"); + public static void downloadRemoteURIByteArray(String assetPackageURI, final Consumer cb) { + logger.info("Downloading: {}"); + try (InputStream is = (new URL(assetPackageURI)).openStream()) { + EaglerOutputStream bao = new EaglerOutputStream(); + byte[] copyBuffer = new byte[16384]; + int i; + while ((i = is.read(copyBuffer, 0, copyBuffer.length)) != -1) { + bao.write(copyBuffer, 0, i); + } + cb.accept(bao.toByteArray()); + } catch (IOException ex) { + logger.error("Failed to download file!"); + logger.error(ex); + } + } + + public static void exit() { + System.exit(0); + } + + public static void freeByteBuffer(ByteBuffer byteBuffer) { + EaglerLWJGLAllocator.freeByteBuffer(byteBuffer); + } + + public static void freeFloatBuffer(FloatBuffer floatBuffer) { + EaglerLWJGLAllocator.freeFloatBuffer(floatBuffer); + } + + public static void freeIntBuffer(IntBuffer intBuffer) { + EaglerLWJGLAllocator.freeIntBuffer(intBuffer); + } + + public static long freeMemory() { + return Runtime.getRuntime().freeMemory(); + } + + public static String getCallingClass(int backTrace) { + StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); + StackTraceElement stacktraceelement = astacktraceelement[Math.min(backTrace + 1, astacktraceelement.length)]; + return "" + stacktraceelement.getFileName() + ":" + stacktraceelement.getLineNumber(); + } + + public static IClientConfigAdapter getClientConfigAdapter() { + return DesktopClientConfigAdapter.instance; + } + + public static String getGLRenderer() { + return glRenderer; + } + + public static String getGLVersion() { + return glVersion; + } + + public static EnumPlatformAgent getPlatformAgent() { + return EnumPlatformAgent.DESKTOP; + } + + public static EnumPlatformANGLE getPlatformANGLE() { + return rendererANGLEPlatform; + } + + public static EnumPlatformOS getPlatformOS() { + if (currentPlatformOS == null) { + currentPlatformOS = EnumPlatformOS.getFromJVM(System.getProperty("os.name")); + } + return currentPlatformOS; } public static EnumPlatformType getPlatformType() { return EnumPlatformType.DESKTOP; } - public static EnumPlatformAgent getPlatformAgent() { - return EnumPlatformAgent.DESKTOP; + public static void getStackTrace(Throwable t, Consumer ret) { + StackTraceElement[] stackTrace = t.getStackTrace(); + for (int i = 0; i < stackTrace.length; ++i) { + ret.accept(stackTrace[i].toString()); + } } - + public static String getUserAgentString() { return "Desktop/" + System.getProperty("os.name"); } - private static EnumPlatformOS currentPlatformOS = null; - - public static EnumPlatformOS getPlatformOS() { - if(currentPlatformOS == null) { - currentPlatformOS = EnumPlatformOS.getFromJVM(System.getProperty("os.name")); - } - return currentPlatformOS; + public static long getWindowHandle() { + return windowHandle; } - - private static EnumPlatformANGLE requestedANGLEPlatform = EnumPlatformANGLE.DEFAULT; - private static int requestedGLVersion = 300; - + + public static void getWindowXY(int[] x, int[] y) { + glfwGetWindowPos(windowHandle, x, y); + } + + public static void immediateContinue() { + // nope + } + + public static boolean isDebugRuntime() { + return true; + } + + public static boolean isOfflineDownloadURL() { + return false; + } + + public static long maxMemory() { + return Runtime.getRuntime().maxMemory(); + } + + public static long nanoTime() { + return System.nanoTime(); + } + + public static OutputStream newDeflaterOutputStream(OutputStream os) throws IOException { + return new DeflaterOutputStream(os); + } + + public static InputStream newGZIPInputStream(InputStream is) throws IOException { + return new GZIPInputStream(is); + } + + public static OutputStream newGZIPOutputStream(OutputStream os) throws IOException { + return new GZIPOutputStream(os); + } + + public static InputStream newInflaterInputStream(InputStream is) throws IOException { + return new InflaterInputStream(is); + } + + public static void postCreate() { + + } + + public static boolean printJSExceptionIfBrowser(Throwable t) { + return false; + } + + private static boolean probablyGLES2(String glVersion) { + if (glVersion == null) + return false; + glVersion = glVersion.toLowerCase(); + return glVersion.contains("opengl es 2.0") || glVersion.contains("ES 2.0"); + } + + public static long randomSeed() { + synchronized (seedProvider) { + return seedProvider.nextLong(); + } + } + public static void requestANGLE(EnumPlatformANGLE plaf) { requestedANGLEPlatform = plaf; } @@ -370,264 +654,44 @@ public class PlatformRuntime { requestedGLVersion = i; } - public static EnumPlatformANGLE getPlatformANGLE() { - return rendererANGLEPlatform; - } - - public static String getGLVersion() { - return glVersion; - } - - public static String getGLRenderer() { - return glRenderer; - } - public static ByteBuffer allocateByteBuffer(int length) { - return EaglerLWJGLAllocator.allocByteBuffer(length); - } - - public static IntBuffer allocateIntBuffer(int length) { - return EaglerLWJGLAllocator.allocIntBuffer(length); - } - - public static FloatBuffer allocateFloatBuffer(int length) { - return EaglerLWJGLAllocator.allocFloatBuffer(length); - } - - public static ByteBuffer castPrimitiveByteArray(byte[] array) { - return null; - } - - public static IntBuffer castPrimitiveIntArray(int[] array) { - return null; - } - - public static FloatBuffer castPrimitiveFloatArray(float[] array) { - return null; - } - - public static byte[] castNativeByteBuffer(ByteBuffer buffer) { - return null; - } - - public static int[] castNativeIntBuffer(IntBuffer buffer) { - return null; - } - - public static float[] castNativeFloatBuffer(FloatBuffer buffer) { - return null; - } - - public static void freeByteBuffer(ByteBuffer byteBuffer) { - EaglerLWJGLAllocator.freeByteBuffer(byteBuffer); - } - - public static void freeIntBuffer(IntBuffer intBuffer) { - EaglerLWJGLAllocator.freeIntBuffer(intBuffer); - } - - public static void freeFloatBuffer(FloatBuffer floatBuffer) { - EaglerLWJGLAllocator.freeFloatBuffer(floatBuffer); - } - - public static class NativeNIO { - - public static java.nio.ByteBuffer allocateByteBuffer(int length) { - long ret = JEmalloc.nje_malloc(length); - if(ret == 0l) { - throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); - } - return MemoryUtil.memByteBuffer(ret, length); - } - - public static java.nio.IntBuffer allocateIntBuffer(int length) { - long ret = JEmalloc.nje_malloc(length << 2); - if(ret == 0l) { - throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); - } - return MemoryUtil.memIntBuffer(ret, length); - } - - public static java.nio.FloatBuffer allocateFloatBuffer(int length) { - long ret = JEmalloc.nje_malloc(length << 2); - if(ret == 0l) { - throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); - } - return MemoryUtil.memFloatBuffer(ret, length); - } - - public static java.nio.IntBuffer getIntBuffer(java.nio.ByteBuffer byteBuffer) { - return MemoryUtil.memIntBuffer(MemoryUtil.memAddress(byteBuffer), byteBuffer.capacity() >> 2); - } - - public static java.nio.FloatBuffer getFloatBuffer(java.nio.ByteBuffer byteBuffer) { - return MemoryUtil.memFloatBuffer(MemoryUtil.memAddress(byteBuffer), byteBuffer.capacity() >> 2); - } - - public static java.nio.ByteBuffer getAsByteBuffer(java.nio.IntBuffer intBuffer) { - return MemoryUtil.memByteBuffer(MemoryUtil.memAddress(intBuffer), intBuffer.capacity() << 2); - } - - public static java.nio.ByteBuffer getAsByteBuffer(java.nio.FloatBuffer floatBuffer) { - return MemoryUtil.memByteBuffer(MemoryUtil.memAddress(floatBuffer), floatBuffer.capacity() << 2); - } - - public static void freeByteBuffer(java.nio.ByteBuffer byteBuffer) { - JEmalloc.nje_free(MemoryUtil.memAddress(byteBuffer)); - } - - public static void freeIntBuffer(java.nio.IntBuffer intBuffer) { - JEmalloc.nje_free(MemoryUtil.memAddress(intBuffer)); - } - - public static void freeFloatBuffer(java.nio.FloatBuffer floatBuffer) { - JEmalloc.nje_free(MemoryUtil.memAddress(floatBuffer)); - } - - } - - public static boolean isDebugRuntime() { - return true; - } - - public static void writeCrashReport(String crashDump) { - File file1 = new File("./crash-reports"); - if(!file1.exists()) { - if(!file1.mkdirs()) { - PlatformRuntime.logger.fatal("Could not create crash report directory: {}", file1.getAbsolutePath()); - return; - } - } - File file2 = new File(file1, - "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-client.txt"); - try(FileOutputStream os = new FileOutputStream(file2)) { - os.write(crashDump.getBytes(StandardCharsets.UTF_8)); - }catch(IOException ex) { - PlatformRuntime.logger.fatal("Could not write crash report: {}", file2.getAbsolutePath()); - PlatformRuntime.logger.fatal(ex); - return; - } - PlatformRuntime.logger.fatal("Crash report was written to: {}", file2.getAbsolutePath()); - } - - public static void getStackTrace(Throwable t, Consumer ret) { - StackTraceElement[] stackTrace = t.getStackTrace(); - for(int i = 0; i < stackTrace.length; ++i) { - ret.accept(stackTrace[i].toString()); - } - } - - public static boolean printJSExceptionIfBrowser(Throwable t) { - return false; - } - - public static void exit() { - System.exit(0); - } - - public static void setThreadName(String string) { - Thread.currentThread().setName(string); - } - - public static long maxMemory() { - return Runtime.getRuntime().maxMemory(); - } - - public static long totalMemory() { - return Runtime.getRuntime().totalMemory(); - } - - public static long freeMemory() { - return Runtime.getRuntime().freeMemory(); - } - - public static String getCallingClass(int backTrace) { - StackTraceElement[] astacktraceelement = Thread.currentThread().getStackTrace(); - StackTraceElement stacktraceelement = astacktraceelement[Math.min(backTrace + 1, astacktraceelement.length)]; - return "" + stacktraceelement.getFileName() + ":" + stacktraceelement.getLineNumber(); - } - - public static OutputStream newDeflaterOutputStream(OutputStream os) throws IOException { - return new DeflaterOutputStream(os); - } - - public static OutputStream newGZIPOutputStream(OutputStream os) throws IOException { - return new GZIPOutputStream(os); - } - - public static InputStream newInflaterInputStream(InputStream is) throws IOException { - return new InflaterInputStream(is); - } - - public static InputStream newGZIPInputStream(InputStream is) throws IOException { - return new GZIPInputStream(is); - } - - public static void downloadRemoteURIByteArray(String assetPackageURI, final Consumer cb) { - logger.info("Downloading: {}"); - try(InputStream is = (new URL(assetPackageURI)).openStream()) { - EaglerOutputStream bao = new EaglerOutputStream(); - byte[] copyBuffer = new byte[16384]; - int i; - while((i = is.read(copyBuffer, 0, copyBuffer.length)) != -1) { - bao.write(copyBuffer, 0, i); - } - cb.accept(bao.toByteArray()); - }catch(IOException ex) { - logger.error("Failed to download file!"); - logger.error(ex); - } - } - public static boolean requireSSL() { return false; } - - public static boolean isOfflineDownloadURL() { - return false; - } - - public static IClientConfigAdapter getClientConfigAdapter() { - return DesktopClientConfigAdapter.instance; + + public static void setDisplayBootMenuNextRefresh(boolean en) { + } - private static final Random seedProvider = new Random(); - - public static long randomSeed() { - synchronized(seedProvider) { - return seedProvider.nextLong(); - } - } - - public static void getWindowXY(int[] x, int[] y) { - glfwGetWindowPos(windowHandle, x, y); - } - - public static String currentThreadName() { - return Thread.currentThread().getName(); - } - - public static long getWindowHandle() { - return windowHandle; + public static void setThreadName(String string) { + Thread.currentThread().setName(string); } public static long steadyTimeMillis() { return System.nanoTime() / 1000000l; } - public static long nanoTime() { - return System.nanoTime(); + public static long totalMemory() { + return Runtime.getRuntime().totalMemory(); } - public static void postCreate() { - - } - - public static void setDisplayBootMenuNextRefresh(boolean en) { - - } - - public static void immediateContinue() { - // nope + public static void writeCrashReport(String crashDump) { + File file1 = new File("./crash-reports"); + if (!file1.exists()) { + if (!file1.mkdirs()) { + PlatformRuntime.logger.fatal("Could not create crash report directory: {}", file1.getAbsolutePath()); + return; + } + } + File file2 = new File(file1, + "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-client.txt"); + try (FileOutputStream os = new FileOutputStream(file2)) { + os.write(crashDump.getBytes(StandardCharsets.UTF_8)); + } catch (IOException ex) { + PlatformRuntime.logger.fatal("Could not write crash report: {}", file2.getAbsolutePath()); + PlatformRuntime.logger.fatal(ex); + return; + } + PlatformRuntime.logger.fatal("Crash report was written to: {}", file2.getAbsolutePath()); } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformScreenRecord.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformScreenRecord.java index 1568d60c..47de5efc 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformScreenRecord.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformScreenRecord.java @@ -5,55 +5,55 @@ import net.lax1dude.eaglercraft.v1_8.recording.EnumScreenRecordingCodec; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformScreenRecord { - public static boolean isSupported() { - return false; + public static void endRecording() { + } public static boolean isCodecSupported(EnumScreenRecordingCodec codec) { return false; } - public static void setGameVolume(float volume) { - - } - - public static void setMicrophoneVolume(float volume) { - - } - - public static void startRecording(ScreenRecordParameters params) { - - } - - public static void endRecording() { - - } - - public static boolean isRecording() { - return false; - } - public static boolean isMicVolumeLocked() { return false; } + public static boolean isRecording() { + return false; + } + + public static boolean isSupported() { + return false; + } + public static boolean isVSyncLocked() { return false; } + public static void setGameVolume(float volume) { + + } + + public static void setMicrophoneVolume(float volume) { + + } + + public static void startRecording(ScreenRecordParameters params) { + + } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformUpdateSvc.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformUpdateSvc.java index ae4529f6..4128a9a3 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformUpdateSvc.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformUpdateSvc.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.update.UpdateResultObj; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,32 +24,24 @@ public class PlatformUpdateSvc { private static final UpdateProgressStruct dummyStruct = new UpdateProgressStruct(); - public static boolean supported() { - return false; - } - - public static void initialize() { - + public static byte[] getClientBundleData() { + return null; } public static byte[] getClientSignatureData() { return null; } - public static byte[] getClientBundleData() { + public static UpdateResultObj getUpdateResult() { return null; } - public static void startClientUpdateFrom(UpdateCertificate clientUpdate) { - - } - public static UpdateProgressStruct getUpdatingStatus() { return dummyStruct; } - public static UpdateResultObj getUpdateResult() { - return null; + public static void initialize() { + } public static void installSignedClient(UpdateCertificate clientCert, byte[] clientPayload, boolean setDefault, @@ -57,10 +50,18 @@ public class PlatformUpdateSvc { } public static void quine(String filename, byte[] cert, byte[] data, String date) { - + } public static void quine(UpdateCertificate clientUpdate, byte[] data) { - + + } + + public static void startClientUpdateFrom(UpdateCertificate clientUpdate) { + + } + + public static boolean supported() { + return false; } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformVoiceClient.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformVoiceClient.java index 5020d8f0..ef2e6503 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformVoiceClient.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformVoiceClient.java @@ -7,104 +7,33 @@ import net.lax1dude.eaglercraft.v1_8.voice.EnumVoiceChannelReadyState; /** * Copyright (c) 2022-2024 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformVoiceClient { - public static void initialize() { - - } - - public static void initializeDevices() { - - } - - public static boolean isSupported() { - return false; - } - - public static void setVoiceListenVolume(float f) { - - } - - public static void setVoiceSpeakVolume(float f) { - - } - public static void activateVoice(boolean talk) { - - } - public static void setICEServers(String[] servs) { - - } - - public static void signalConnect(EaglercraftUUID user, boolean offer) { - - } - - public static void signalDisconnect(EaglercraftUUID user, boolean b) { - - } - - public static void signalICECandidate(EaglercraftUUID user, String ice) { - - } - - public static void signalDescription(EaglercraftUUID user, String desc) { - - } - - public static void tickVoiceClient() { - - } - - public static void updateVoicePosition(EaglercraftUUID uuid, double x, double y, double z) { - - } - - public static void resetPeerStates() { - - } - - public static void setVoiceProximity(int prox) { - - } - - public static void setMicVolume(float f) { - - } - - public static void mutePeer(EaglercraftUUID uuid, boolean mute) { - } public static EnumVoiceChannelPeerState getPeerState() { return EnumVoiceChannelPeerState.LOADING; } - public static EnumVoiceChannelReadyState getReadyState() { - return EnumVoiceChannelReadyState.NONE; - } - public static EnumVoiceChannelPeerState getPeerStateConnect() { return EnumVoiceChannelPeerState.LOADING; } - public static EnumVoiceChannelPeerState getPeerStateInitial() { - return EnumVoiceChannelPeerState.LOADING; - } - public static EnumVoiceChannelPeerState getPeerStateDesc() { return EnumVoiceChannelPeerState.LOADING; } @@ -113,4 +42,76 @@ public class PlatformVoiceClient { return EnumVoiceChannelPeerState.LOADING; } + public static EnumVoiceChannelPeerState getPeerStateInitial() { + return EnumVoiceChannelPeerState.LOADING; + } + + public static EnumVoiceChannelReadyState getReadyState() { + return EnumVoiceChannelReadyState.NONE; + } + + public static void initialize() { + + } + + public static void initializeDevices() { + + } + + public static boolean isSupported() { + return false; + } + + public static void mutePeer(EaglercraftUUID uuid, boolean mute) { + + } + + public static void resetPeerStates() { + + } + + public static void setICEServers(String[] servs) { + + } + + public static void setMicVolume(float f) { + + } + + public static void setVoiceListenVolume(float f) { + + } + + public static void setVoiceProximity(int prox) { + + } + + public static void setVoiceSpeakVolume(float f) { + + } + + public static void signalConnect(EaglercraftUUID user, boolean offer) { + + } + + public static void signalDescription(EaglercraftUUID user, String desc) { + + } + + public static void signalDisconnect(EaglercraftUUID user, boolean b) { + + } + + public static void signalICECandidate(EaglercraftUUID user, String ice) { + + } + + public static void tickVoiceClient() { + + } + + public static void updateVoicePosition(EaglercraftUUID uuid, double x, double y, double z) { + + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebRTC.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebRTC.java index cfea7c39..183fe615 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebRTC.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebRTC.java @@ -1,6 +1,45 @@ package net.lax1dude.eaglercraft.v1_8.internal; -import dev.onvoid.webrtc.*; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang3.SystemUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.json.JSONWriter; + +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.ListMultimap; + +import dev.onvoid.webrtc.CreateSessionDescriptionObserver; +import dev.onvoid.webrtc.PeerConnectionFactory; +import dev.onvoid.webrtc.PeerConnectionObserver; +import dev.onvoid.webrtc.RTCAnswerOptions; +import dev.onvoid.webrtc.RTCConfiguration; +import dev.onvoid.webrtc.RTCDataChannel; +import dev.onvoid.webrtc.RTCDataChannelBuffer; +import dev.onvoid.webrtc.RTCDataChannelInit; +import dev.onvoid.webrtc.RTCDataChannelObserver; +import dev.onvoid.webrtc.RTCDataChannelState; +import dev.onvoid.webrtc.RTCIceCandidate; +import dev.onvoid.webrtc.RTCIceServer; +import dev.onvoid.webrtc.RTCOfferOptions; +import dev.onvoid.webrtc.RTCPeerConnection; +import dev.onvoid.webrtc.RTCPeerConnectionState; +import dev.onvoid.webrtc.RTCSdpType; +import dev.onvoid.webrtc.RTCSessionDescription; +import dev.onvoid.webrtc.SetSessionDescriptionObserver; import dev.onvoid.webrtc.internal.NativeLoader; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EagUtils; @@ -19,123 +58,24 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayWorldsQuery; import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayWorldsQueryImpl; import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayWorldsQueryRateLimitDummy; -import org.apache.commons.lang3.SystemUtils; -import org.json.JSONArray; -import org.json.JSONObject; -import org.json.JSONWriter; - -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.ListMultimap; - -import java.lang.reflect.Field; -import java.nio.ByteBuffer; -import java.nio.file.Paths; -import java.util.*; - /** * Copyright (c) 2022-2024 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PlatformWebRTC { - private static final Logger logger = LogManager.getLogger("PlatformWebRTC"); - - private static final RelayLoggerImpl loggerImpl = new RelayLoggerImpl(LogManager.getLogger("RelayPacket")); - - private static final Object lock1 = new Object(); - private static final Object lock2 = new Object(); - private static final Object lock3 = new Object(); - - private static final List scheduledRunnables = new LinkedList<>(); - - private static class ScheduledRunnable { - - private final long runAt; - private final Runnable runnable; - - private ScheduledRunnable(long runAt, Runnable runnable) { - this.runAt = runAt; - this.runnable = runnable; - } - - } - - public static PeerConnectionFactory pcFactory; - - private static boolean supported = true; - - public static boolean supported() { - if (supported && pcFactory == null) { - try { - System.load(Paths.get(SystemUtils.IS_OS_WINDOWS ? "webrtc-java.dll" : "libwebrtc-java.so").toAbsolutePath().toString()); - Field f = NativeLoader.class.getDeclaredField("LOADED_LIB_SET"); - f.setAccessible(true); - ((Set) f.get(null)).add("webrtc-java"); - pcFactory = new PeerConnectionFactory(); - Runtime.getRuntime().addShutdownHook(new Thread(() -> pcFactory.dispose())); - supported = true; - } catch (Exception e) { - logger.error("Failed to load WebRTC native library!"); - logger.error(e); - supported = false; - } - } - return supported; - } - - private static final Map fuckTeaVM = new HashMap<>(); - - private static final Comparator sortTasks = (r1, r2) -> { - return (int)(r1.runAt - r2.runAt); - }; - - public static void runScheduledTasks() { - List toRun = null; - synchronized(scheduledRunnables) { - if(scheduledRunnables.isEmpty()) return; - long millis = PlatformRuntime.steadyTimeMillis(); - Iterator itr = scheduledRunnables.iterator(); - while(itr.hasNext()) { - ScheduledRunnable r = itr.next(); - if(r.runAt < millis) { - itr.remove(); - if(toRun == null) { - toRun = new ArrayList<>(1); - } - toRun.add(r); - } - } - } - if(toRun != null) { - Collections.sort(toRun, sortTasks); - for(int i = 0, l = toRun.size(); i < l; ++i) { - try { - toRun.get(i).runnable.run(); - }catch(Throwable t) { - logger.error("Caught exception running scheduled WebRTC task!"); - logger.error(t); - } - } - } - } - - static void scheduleTask(long runAfter, Runnable runnable) { - synchronized(scheduledRunnables) { - scheduledRunnables.add(new ScheduledRunnable(PlatformRuntime.steadyTimeMillis() + runAfter, runnable)); - } - } - public static class LANClient { public static final byte READYSTATE_INIT_FAILED = -2; public static final byte READYSTATE_FAILED = -1; @@ -173,6 +113,18 @@ public class PlatformWebRTC { } synchronized (lock1) { this.peerConnection = pcFactory.createPeerConnection(rtcConfig, new PeerConnectionObserver() { + @Override + public void onConnectionChange(RTCPeerConnectionState connectionState) { + if (connectionState == RTCPeerConnectionState.DISCONNECTED) { + signalRemoteDisconnect(false); + } else if (connectionState == RTCPeerConnectionState.CONNECTED) { + readyState = READYSTATE_CONNECTED; + } else if (connectionState == RTCPeerConnectionState.FAILED) { + readyState = READYSTATE_FAILED; + signalRemoteDisconnect(false); + } + } + @Override public void onIceCandidate(RTCIceCandidate iceCandidate) { synchronized (lock1) { @@ -180,7 +132,8 @@ public class PlatformWebRTC { if (iceCandidates.isEmpty()) { scheduleTask(3000l, () -> { synchronized (lock1) { - if (peerConnection != null && peerConnection.getConnectionState() != RTCPeerConnectionState.DISCONNECTED) { + if (peerConnection != null && peerConnection + .getConnectionState() != RTCPeerConnectionState.DISCONNECTED) { clientICECandidate = JSONWriter.valueToString(iceCandidates); iceCandidates.clear(); } @@ -194,18 +147,6 @@ public class PlatformWebRTC { } } } - - @Override - public void onConnectionChange(RTCPeerConnectionState connectionState) { - if (connectionState == RTCPeerConnectionState.DISCONNECTED) { - signalRemoteDisconnect(false); - } else if (connectionState == RTCPeerConnectionState.CONNECTED) { - readyState = READYSTATE_CONNECTED; - } else if (connectionState == RTCPeerConnectionState.FAILED) { - readyState = READYSTATE_FAILED; - signalRemoteDisconnect(false); - } - } }); } this.readyState = READYSTATE_CONNECTING; @@ -214,6 +155,18 @@ public class PlatformWebRTC { } } + public void sendPacketToServer(RTCDataChannelBuffer buffer) { + if (dataChannel != null && dataChannel.getState() == RTCDataChannelState.OPEN) { + try { + dataChannel.send(buffer); + } catch (Throwable e) { + signalRemoteDisconnect(false); + } + } else { + signalRemoteDisconnect(false); + } + } + public void setIceServers(String[] urls) { iceServers.clear(); for (int i = 0; i < urls.length; ++i) { @@ -233,18 +186,6 @@ public class PlatformWebRTC { } } - public void sendPacketToServer(RTCDataChannelBuffer buffer) { - if (dataChannel != null && dataChannel.getState() == RTCDataChannelState.OPEN) { - try { - dataChannel.send(buffer); - } catch (Throwable e) { - signalRemoteDisconnect(false); - } - } else { - signalRemoteDisconnect(false); - } - } - public void signalRemoteConnect() { dataChannel = peerConnection.createDataChannel("lan", new RTCDataChannelInit()); @@ -254,6 +195,17 @@ public class PlatformWebRTC { // } + @Override + public void onMessage(RTCDataChannelBuffer buffer) { + if (!buffer.binary) + return; + byte[] data = new byte[buffer.data.remaining()]; + buffer.data.get(data); + synchronized (clientLANPacketBuffer) { + clientLANPacketBuffer.add(data); + } + } + @Override public void onStateChange() { if (dataChannel != null && dataChannel.getState() == RTCDataChannelState.OPEN) { @@ -273,22 +225,26 @@ public class PlatformWebRTC { }); } } - - @Override - public void onMessage(RTCDataChannelBuffer buffer) { - if (!buffer.binary) return; - byte[] data = new byte[buffer.data.remaining()]; - buffer.data.get(data); - synchronized (clientLANPacketBuffer) { - clientLANPacketBuffer.add(data); - } - } }); peerConnection.createOffer(new RTCOfferOptions(), new CreateSessionDescriptionObserver() { + @Override + public void onFailure(String s) { + logger.error("Failed to set create offer! {}", s); + readyState = READYSTATE_FAILED; + signalRemoteDisconnect(false); + } + @Override public void onSuccess(RTCSessionDescription desc) { peerConnection.setLocalDescription(desc, new SetSessionDescriptionObserver() { + @Override + public void onFailure(String s) { + logger.error("Failed to set local description! {}", s); + readyState = READYSTATE_FAILED; + signalRemoteDisconnect(false); + } + @Override public void onSuccess() { JSONObject descJson = new JSONObject(); @@ -296,55 +252,30 @@ public class PlatformWebRTC { descJson.put("sdp", desc.sdp); clientDescription = descJson.toString(); } - - @Override - public void onFailure(String s) { - logger.error("Failed to set local description! {}", s); - readyState = READYSTATE_FAILED; - signalRemoteDisconnect(false); - } }); } - - @Override - public void onFailure(String s) { - logger.error("Failed to set create offer! {}", s); - readyState = READYSTATE_FAILED; - signalRemoteDisconnect(false); - } }); } public void signalRemoteDescription(String json) { try { JSONObject jsonObject = new JSONObject(json); - peerConnection.setRemoteDescription(new RTCSessionDescription(RTCSdpType.valueOf(jsonObject.getString("type").toUpperCase()), jsonObject.getString("sdp")), new SetSessionDescriptionObserver() { - @Override - public void onSuccess() { - // - } + peerConnection.setRemoteDescription( + new RTCSessionDescription(RTCSdpType.valueOf(jsonObject.getString("type").toUpperCase()), + jsonObject.getString("sdp")), + new SetSessionDescriptionObserver() { + @Override + public void onFailure(String s) { + logger.error(s); + readyState = READYSTATE_FAILED; + signalRemoteDisconnect(false); + } - @Override - public void onFailure(String s) { - logger.error(s); - readyState = READYSTATE_FAILED; - signalRemoteDisconnect(false); - } - }); - } catch (Throwable t) { - EagRuntime.debugPrintStackTrace(t); - readyState = READYSTATE_FAILED; - signalRemoteDisconnect(false); - } - } - - public void signalRemoteICECandidate(String candidates) { - try { - JSONArray jsonArray = new JSONArray(candidates); - for (int i = 0, l = jsonArray.length(); i < l; ++i) { - JSONObject candidate = jsonArray.getJSONObject(i); - peerConnection.addIceCandidate(new RTCIceCandidate(null, candidate.getInt("sdpMLineIndex"), candidate.getString("candidate"))); - } + @Override + public void onSuccess() { + // + } + }); } catch (Throwable t) { EagRuntime.debugPrintStackTrace(t); readyState = READYSTATE_FAILED; @@ -364,15 +295,27 @@ public class PlatformWebRTC { } } synchronized (lock2) { - if (!quiet) clientDataChannelClosed = true; + if (!quiet) + clientDataChannelClosed = true; } readyState = READYSTATE_DISCONNECTED; } - } - public static final byte PEERSTATE_FAILED = 0; - public static final byte PEERSTATE_SUCCESS = 1; - public static final byte PEERSTATE_LOADING = 2; + public void signalRemoteICECandidate(String candidates) { + try { + JSONArray jsonArray = new JSONArray(candidates); + for (int i = 0, l = jsonArray.length(); i < l; ++i) { + JSONObject candidate = jsonArray.getJSONObject(i); + peerConnection.addIceCandidate(new RTCIceCandidate(null, candidate.getInt("sdpMLineIndex"), + candidate.getString("candidate"))); + } + } catch (Throwable t) { + EagRuntime.debugPrintStackTrace(t); + readyState = READYSTATE_FAILED; + signalRemoteDisconnect(false); + } + } + } public static class LANPeer { public LANServer client; @@ -385,6 +328,24 @@ public class PlatformWebRTC { this.peerConnection = peerConnection; } + public void addICECandidate(String candidates) { + try { + JSONArray jsonArray = new JSONArray(candidates); + for (int i = 0, l = jsonArray.length(); i < l; ++i) { + JSONObject candidate = jsonArray.getJSONObject(i); + peerConnection.addIceCandidate(new RTCIceCandidate(null, candidate.getInt("sdpMLineIndex"), + candidate.getString("candidate"))); + } + if (client.peerStateIce != PEERSTATE_SUCCESS) + client.peerStateIce = PEERSTATE_SUCCESS; + } catch (Throwable err) { + logger.error("Failed to parse ice candidate for \"{}\"! {}", peerId, err.getMessage()); + if (client.peerStateIce == PEERSTATE_LOADING) + client.peerStateIce = PEERSTATE_FAILED; + client.signalRemoteDisconnect(peerId); + } + } + public void disconnect() { synchronized (fuckTeaVM) { if (fuckTeaVM.get(peerId) != null) { @@ -398,73 +359,69 @@ public class PlatformWebRTC { public void setRemoteDescription(String descJSON) { try { JSONObject remoteDesc = new JSONObject(descJSON); - peerConnection.setRemoteDescription(new RTCSessionDescription(RTCSdpType.valueOf(remoteDesc.getString("type").toUpperCase()), remoteDesc.getString("sdp")), new SetSessionDescriptionObserver() { - @Override - public void onSuccess() { - if (remoteDesc.has("type") && "offer".equals(remoteDesc.getString("type"))) { - peerConnection.createAnswer(new RTCAnswerOptions(), new CreateSessionDescriptionObserver() { - @Override - public void onSuccess(RTCSessionDescription desc) { - peerConnection.setLocalDescription(desc, new SetSessionDescriptionObserver() { - @Override - public void onSuccess() { - JSONObject descJson = new JSONObject(); - descJson.put("type", desc.sdpType.name().toLowerCase()); - descJson.put("sdp", desc.sdp); - LANPeerEvent.LANPeerDescriptionEvent e = new LANPeerEvent.LANPeerDescriptionEvent(peerId, descJson.toString()); - synchronized (serverLANEventBuffer) { - serverLANEventBuffer.put(peerId, e); - } - if (client.peerStateDesc != PEERSTATE_SUCCESS) - client.peerStateDesc = PEERSTATE_SUCCESS; - } + peerConnection.setRemoteDescription( + new RTCSessionDescription(RTCSdpType.valueOf(remoteDesc.getString("type").toUpperCase()), + remoteDesc.getString("sdp")), + new SetSessionDescriptionObserver() { + @Override + public void onFailure(String s) { + logger.error("Failed to set remote description for \"{}\"! {}", peerId, s); + if (client.peerStateDesc == PEERSTATE_LOADING) + client.peerStateDesc = PEERSTATE_FAILED; + client.signalRemoteDisconnect(peerId); + } - @Override - public void onFailure(String s) { - logger.error("Failed to set local description for \"{}\"! {}", peerId, s); - if (client.peerStateDesc == PEERSTATE_LOADING) - client.peerStateDesc = PEERSTATE_FAILED; - client.signalRemoteDisconnect(peerId); - } - }); + @Override + public void onSuccess() { + if (remoteDesc.has("type") && "offer".equals(remoteDesc.getString("type"))) { + peerConnection.createAnswer(new RTCAnswerOptions(), + new CreateSessionDescriptionObserver() { + @Override + public void onFailure(String s) { + logger.error("Failed to create answer for \"{}\"! {}", peerId, s); + if (client.peerStateDesc == PEERSTATE_LOADING) + client.peerStateDesc = PEERSTATE_FAILED; + client.signalRemoteDisconnect(peerId); + } + + @Override + public void onSuccess(RTCSessionDescription desc) { + peerConnection.setLocalDescription(desc, + new SetSessionDescriptionObserver() { + @Override + public void onFailure(String s) { + logger.error( + "Failed to set local description for \"{}\"! {}", + peerId, s); + if (client.peerStateDesc == PEERSTATE_LOADING) + client.peerStateDesc = PEERSTATE_FAILED; + client.signalRemoteDisconnect(peerId); + } + + @Override + public void onSuccess() { + JSONObject descJson = new JSONObject(); + descJson.put("type", + desc.sdpType.name().toLowerCase()); + descJson.put("sdp", desc.sdp); + LANPeerEvent.LANPeerDescriptionEvent e = new LANPeerEvent.LANPeerDescriptionEvent( + peerId, descJson.toString()); + synchronized (serverLANEventBuffer) { + serverLANEventBuffer.put(peerId, e); + } + if (client.peerStateDesc != PEERSTATE_SUCCESS) + client.peerStateDesc = PEERSTATE_SUCCESS; + } + }); + } + }); } - - @Override - public void onFailure(String s) { - logger.error("Failed to create answer for \"{}\"! {}", peerId, s); - if (client.peerStateDesc == PEERSTATE_LOADING) - client.peerStateDesc = PEERSTATE_FAILED; - client.signalRemoteDisconnect(peerId); - } - }); - } - } - - @Override - public void onFailure(String s) { - logger.error("Failed to set remote description for \"{}\"! {}", peerId, s); - if (client.peerStateDesc == PEERSTATE_LOADING) client.peerStateDesc = PEERSTATE_FAILED; - client.signalRemoteDisconnect(peerId); - } - }); + } + }); } catch (Throwable err) { logger.error("Failed to parse remote description for \"{}\"! {}", peerId, err.getMessage()); - if (client.peerStateDesc == PEERSTATE_LOADING) client.peerStateDesc = PEERSTATE_FAILED; - client.signalRemoteDisconnect(peerId); - } - } - - public void addICECandidate(String candidates) { - try { - JSONArray jsonArray = new JSONArray(candidates); - for (int i = 0, l = jsonArray.length(); i < l; ++i) { - JSONObject candidate = jsonArray.getJSONObject(i); - peerConnection.addIceCandidate(new RTCIceCandidate(null, candidate.getInt("sdpMLineIndex"), candidate.getString("candidate"))); - } - if (client.peerStateIce != PEERSTATE_SUCCESS) client.peerStateIce = PEERSTATE_SUCCESS; - } catch (Throwable err) { - logger.error("Failed to parse ice candidate for \"{}\"! {}", peerId, err.getMessage()); - if (client.peerStateIce == PEERSTATE_LOADING) client.peerStateIce = PEERSTATE_FAILED; + if (client.peerStateDesc == PEERSTATE_LOADING) + client.peerStateDesc = PEERSTATE_FAILED; client.signalRemoteDisconnect(peerId); } } @@ -479,6 +436,36 @@ public class PlatformWebRTC { public byte peerStateDesc = PEERSTATE_LOADING; public byte peerStateIce = PEERSTATE_LOADING; + public int countPeers() { + return peerList.size(); + } + + public void resetPeerStates() { + peerState = peerStateConnect = peerStateInitial = peerStateDesc = peerStateIce = PEERSTATE_LOADING; + } + + public void sendPacketToRemoteClient(String peerId, RTCDataChannelBuffer buffer) { + LANPeer thePeer = this.peerList.get(peerId); + if (thePeer != null) { + boolean b = false; + synchronized (fuckTeaVM) { + if (fuckTeaVM.get(thePeer.peerId) != null + && fuckTeaVM.get(thePeer.peerId).getState() == RTCDataChannelState.OPEN) { + try { + fuckTeaVM.get(thePeer.peerId).send(buffer); + } catch (Throwable e) { + b = true; + } + } else { + b = true; + } + } + if (b) { + signalRemoteDisconnect(peerId); + } + } + } + public void setIceServers(String[] urls) { iceServers.clear(); for (int i = 0; i < urls.length; ++i) { @@ -497,31 +484,6 @@ public class PlatformWebRTC { } } - public void sendPacketToRemoteClient(String peerId, RTCDataChannelBuffer buffer) { - LANPeer thePeer = this.peerList.get(peerId); - if (thePeer != null) { - boolean b = false; - synchronized (fuckTeaVM) { - if (fuckTeaVM.get(thePeer.peerId) != null && fuckTeaVM.get(thePeer.peerId).getState() == RTCDataChannelState.OPEN) { - try { - fuckTeaVM.get(thePeer.peerId).send(buffer); - } catch (Throwable e) { - b = true; - } - } else { - b = true; - } - } - if (b) { - signalRemoteDisconnect(peerId); - } - } - } - - public void resetPeerStates() { - peerState = peerStateConnect = peerStateInitial = peerStateDesc = peerStateIce = PEERSTATE_LOADING; - } - public void signalRemoteConnect(String peerId) { try { List> iceCandidates = new ArrayList<>(); @@ -535,6 +497,66 @@ public class PlatformWebRTC { } RTCPeerConnection[] peerConnection = new RTCPeerConnection[1]; peerConnection[0] = pcFactory.createPeerConnection(rtcConfig, new PeerConnectionObserver() { + @Override + public void onConnectionChange(RTCPeerConnectionState connectionState) { + if (connectionState == RTCPeerConnectionState.DISCONNECTED) { + LANServer.this.signalRemoteDisconnect(peerId); + } else if (connectionState == RTCPeerConnectionState.CONNECTED) { + if (LANServer.this.peerState != PEERSTATE_SUCCESS) + LANServer.this.peerState = PEERSTATE_SUCCESS; + } else if (connectionState == RTCPeerConnectionState.FAILED) { + if (LANServer.this.peerState == PEERSTATE_LOADING) + LANServer.this.peerState = PEERSTATE_FAILED; + LANServer.this.signalRemoteDisconnect(peerId); + } + } + + @Override + public void onDataChannel(RTCDataChannel dataChannel) { + scheduleTask(-1l, () -> { + while (true) { + synchronized (lock3) { + if (iceCandidates.isEmpty()) { + break; + } + } + EagUtils.sleep(1); + } + if (dataChannel == null) + return; + synchronized (fuckTeaVM) { + fuckTeaVM.put(peerId, dataChannel); + } + synchronized (serverLANEventBuffer) { + serverLANEventBuffer.put(peerId, new LANPeerEvent.LANPeerDataChannelEvent(peerId)); + } + dataChannel.registerObserver(new RTCDataChannelObserver() { + @Override + public void onBufferedAmountChange(long l) { + // + } + + @Override + public void onMessage(RTCDataChannelBuffer buffer) { + if (!buffer.binary) + return; + byte[] data = new byte[buffer.data.remaining()]; + buffer.data.get(data); + LANPeerEvent.LANPeerPacketEvent e = new LANPeerEvent.LANPeerPacketEvent(peerId, + data); + synchronized (serverLANEventBuffer) { + serverLANEventBuffer.put(peerId, e); + } + } + + @Override + public void onStateChange() { + // + } + }); + }); + } + @Override public void onIceCandidate(RTCIceCandidate iceCandidate) { synchronized (lock3) { @@ -542,8 +564,10 @@ public class PlatformWebRTC { if (iceCandidates.isEmpty()) { scheduleTask(3000l, () -> { synchronized (lock3) { - if (peerConnection[0] != null && peerConnection[0].getConnectionState() != RTCPeerConnectionState.DISCONNECTED) { - LANPeerEvent.LANPeerICECandidateEvent e = new LANPeerEvent.LANPeerICECandidateEvent(peerId, JSONWriter.valueToString(iceCandidates)); + if (peerConnection[0] != null && peerConnection[0] + .getConnectionState() != RTCPeerConnectionState.DISCONNECTED) { + LANPeerEvent.LANPeerICECandidateEvent e = new LANPeerEvent.LANPeerICECandidateEvent( + peerId, JSONWriter.valueToString(iceCandidates)); synchronized (serverLANEventBuffer) { serverLANEventBuffer.put(peerId, e); } @@ -559,69 +583,14 @@ public class PlatformWebRTC { } } } - - @Override - public void onDataChannel(RTCDataChannel dataChannel) { - scheduleTask(-1l, () -> { - while (true) { - synchronized (lock3) { - if (iceCandidates.isEmpty()) { - break; - } - } - EagUtils.sleep(1); - } - if (dataChannel == null) return; - synchronized (fuckTeaVM) { - fuckTeaVM.put(peerId, dataChannel); - } - synchronized (serverLANEventBuffer) { - serverLANEventBuffer.put(peerId, new LANPeerEvent.LANPeerDataChannelEvent(peerId)); - } - dataChannel.registerObserver(new RTCDataChannelObserver() { - @Override - public void onBufferedAmountChange(long l) { - // - } - - @Override - public void onStateChange() { - // - } - - @Override - public void onMessage(RTCDataChannelBuffer buffer) { - if (!buffer.binary) return; - byte[] data = new byte[buffer.data.remaining()]; - buffer.data.get(data); - LANPeerEvent.LANPeerPacketEvent e = new LANPeerEvent.LANPeerPacketEvent(peerId, data); - synchronized (serverLANEventBuffer) { - serverLANEventBuffer.put(peerId, e); - } - } - }); - }); - } - - @Override - public void onConnectionChange(RTCPeerConnectionState connectionState) { - if (connectionState == RTCPeerConnectionState.DISCONNECTED) { - LANServer.this.signalRemoteDisconnect(peerId); - } else if (connectionState == RTCPeerConnectionState.CONNECTED) { - if (LANServer.this.peerState != PEERSTATE_SUCCESS) - LANServer.this.peerState = PEERSTATE_SUCCESS; - } else if (connectionState == RTCPeerConnectionState.FAILED) { - if (LANServer.this.peerState == PEERSTATE_LOADING) - LANServer.this.peerState = PEERSTATE_FAILED; - LANServer.this.signalRemoteDisconnect(peerId); - } - } }); LANPeer peerInstance = new LANPeer(this, peerId, peerConnection[0]); peerList.put(peerId, peerInstance); - if (peerStateConnect != PEERSTATE_SUCCESS) peerStateConnect = PEERSTATE_SUCCESS; + if (peerStateConnect != PEERSTATE_SUCCESS) + peerStateConnect = PEERSTATE_SUCCESS; } catch (Throwable e) { - if (peerStateConnect == PEERSTATE_LOADING) peerStateConnect = PEERSTATE_FAILED; + if (peerStateConnect == PEERSTATE_LOADING) + peerStateConnect = PEERSTATE_FAILED; } } @@ -632,13 +601,6 @@ public class PlatformWebRTC { } } - public void signalRemoteICECandidate(String peerId, String candidate) { - LANPeer thePeer = peerList.get(peerId); - if (thePeer != null) { - thePeer.addICECandidate(candidate); - } - } - public void signalRemoteDisconnect(String peerId) { if (peerId == null || peerId.isEmpty()) { for (LANPeer thePeer : peerList.values()) { @@ -648,7 +610,8 @@ public class PlatformWebRTC { } catch (Throwable ignored) { } synchronized (serverLANEventBuffer) { - serverLANEventBuffer.put(thePeer.peerId, new LANPeerEvent.LANPeerDisconnectEvent(thePeer.peerId)); + serverLANEventBuffer.put(thePeer.peerId, + new LANPeerEvent.LANPeerDisconnectEvent(thePeer.peerId)); } } } @@ -674,88 +637,68 @@ public class PlatformWebRTC { } } - public int countPeers() { - return peerList.size(); - } - } - public static RelayQuery openRelayQuery(String addr) { - RelayQuery.RateLimit limit = RelayServerRateLimitTracker.isLimited(addr); - if(limit == RelayQuery.RateLimit.LOCKED || limit == RelayQuery.RateLimit.BLOCKED) { - return new RelayQueryRateLimitDummy(limit); - } - return new RelayQueryImpl(addr); - } - - public static RelayWorldsQuery openRelayWorldsQuery(String addr) { - RelayQuery.RateLimit limit = RelayServerRateLimitTracker.isLimited(addr); - if(limit == RelayQuery.RateLimit.LOCKED || limit == RelayQuery.RateLimit.BLOCKED) { - return new RelayWorldsQueryRateLimitDummy(limit); - } - return new RelayWorldsQueryImpl(addr); - } - - public static RelayServerSocket openRelayConnection(String addr, int timeout) { - RelayQuery.RateLimit limit = RelayServerRateLimitTracker.isLimited(addr); - if(limit == RelayQuery.RateLimit.LOCKED || limit == RelayQuery.RateLimit.BLOCKED) { - return new RelayServerSocketRateLimitDummy(limit); - } - return new RelayServerSocketImpl(addr, timeout); - } - - private static LANClient rtcLANClient = null; - - public static void startRTCLANClient() { - if (rtcLANClient == null) { - rtcLANClient = new LANClient(); - } - } - - private static final List clientLANPacketBuffer = new ArrayList<>(); - - private static String clientICECandidate = null; - private static String clientDescription = null; - private static boolean clientDataChannelOpen = false; - private static boolean clientDataChannelClosed = true; - - public static int clientLANReadyState() { - return rtcLANClient.readyState; - } - - public static void clientLANCloseConnection() { - rtcLANClient.signalRemoteDisconnect(false); - } - - public static void clientLANSendPacket(byte[] pkt) { - rtcLANClient.sendPacketToServer(new RTCDataChannelBuffer(ByteBuffer.wrap(pkt), true)); - } - - public static byte[] clientLANReadPacket() { - synchronized(clientLANPacketBuffer) { - return !clientLANPacketBuffer.isEmpty() ? clientLANPacketBuffer.remove(0) : null; - } - } - - public static List clientLANReadAllPacket() { - synchronized(clientLANPacketBuffer) { - if(!clientLANPacketBuffer.isEmpty()) { - List ret = new ArrayList<>(clientLANPacketBuffer); - clientLANPacketBuffer.clear(); - return ret; - }else { - return null; + public void signalRemoteICECandidate(String peerId, String candidate) { + LANPeer thePeer = peerList.get(peerId); + if (thePeer != null) { + thePeer.addICECandidate(candidate); } } } - public static void clientLANSetICEServersAndConnect(String[] servers) { - rtcLANClient.setIceServers(servers); - if(clientLANReadyState() == LANClient.READYSTATE_CONNECTED || clientLANReadyState() == LANClient.READYSTATE_CONNECTING) { - rtcLANClient.signalRemoteDisconnect(true); + private static class ScheduledRunnable { + + private final long runAt; + private final Runnable runnable; + + private ScheduledRunnable(long runAt, Runnable runnable) { + this.runAt = runAt; + this.runnable = runnable; } - rtcLANClient.initialize(); - rtcLANClient.signalRemoteConnect(); + } + private static final Logger logger = LogManager.getLogger("PlatformWebRTC"); + + private static final RelayLoggerImpl loggerImpl = new RelayLoggerImpl(LogManager.getLogger("RelayPacket")); + + private static final Object lock1 = new Object(); + + private static final Object lock2 = new Object(); + + private static final Object lock3 = new Object(); + + private static final List scheduledRunnables = new LinkedList<>(); + + public static PeerConnectionFactory pcFactory; + + private static boolean supported = true; + + private static final Map fuckTeaVM = new HashMap<>(); + + private static final Comparator sortTasks = (r1, r2) -> { + return (int) (r1.runAt - r2.runAt); + }; + + public static final byte PEERSTATE_FAILED = 0; + + public static final byte PEERSTATE_SUCCESS = 1; + public static final byte PEERSTATE_LOADING = 2; + private static LANClient rtcLANClient = null; + + private static final List clientLANPacketBuffer = new ArrayList<>(); + + private static String clientICECandidate = null; + + private static String clientDescription = null; + + private static boolean clientDataChannelOpen = false; + + private static boolean clientDataChannelClosed = true; + + private static LANServer rtcLANServer = null; + + private static final ListMultimap serverLANEventBuffer = LinkedListMultimap.create(); + public static void clearLANClientState() { clientICECandidate = null; clientDescription = null; @@ -765,26 +708,6 @@ public class PlatformWebRTC { } } - public static String clientLANAwaitICECandidate() { - if(clientICECandidate != null) { - String ret = clientICECandidate; - clientICECandidate = null; - return ret; - }else { - return null; - } - } - - public static String clientLANAwaitDescription() { - if(clientDescription != null) { - String ret = clientDescription; - clientDescription = null; - return ret; - }else { - return null; - } - } - public static boolean clientLANAwaitChannel() { synchronized (lock2) { if (clientDataChannelOpen) { @@ -796,85 +719,78 @@ public class PlatformWebRTC { } } + public static String clientLANAwaitDescription() { + if (clientDescription != null) { + String ret = clientDescription; + clientDescription = null; + return ret; + } else { + return null; + } + } + + public static String clientLANAwaitICECandidate() { + if (clientICECandidate != null) { + String ret = clientICECandidate; + clientICECandidate = null; + return ret; + } else { + return null; + } + } + + public static void clientLANCloseConnection() { + rtcLANClient.signalRemoteDisconnect(false); + } + public static boolean clientLANClosed() { synchronized (lock2) { return clientDataChannelClosed; } } - public static void clientLANSetICECandidate(String candidate) { - rtcLANClient.signalRemoteICECandidate(candidate); + public static List clientLANReadAllPacket() { + synchronized (clientLANPacketBuffer) { + if (!clientLANPacketBuffer.isEmpty()) { + List ret = new ArrayList<>(clientLANPacketBuffer); + clientLANPacketBuffer.clear(); + return ret; + } else { + return null; + } + } + } + + public static byte[] clientLANReadPacket() { + synchronized (clientLANPacketBuffer) { + return !clientLANPacketBuffer.isEmpty() ? clientLANPacketBuffer.remove(0) : null; + } + } + + public static int clientLANReadyState() { + return rtcLANClient.readyState; + } + + public static void clientLANSendPacket(byte[] pkt) { + rtcLANClient.sendPacketToServer(new RTCDataChannelBuffer(ByteBuffer.wrap(pkt), true)); } public static void clientLANSetDescription(String description) { rtcLANClient.signalRemoteDescription(description); } - private static LANServer rtcLANServer = null; + public static void clientLANSetICECandidate(String candidate) { + rtcLANClient.signalRemoteICECandidate(candidate); + } - public static void startRTCLANServer() { - if (rtcLANServer == null) { - rtcLANServer = new LANServer(); + public static void clientLANSetICEServersAndConnect(String[] servers) { + rtcLANClient.setIceServers(servers); + if (clientLANReadyState() == LANClient.READYSTATE_CONNECTED + || clientLANReadyState() == LANClient.READYSTATE_CONNECTING) { + rtcLANClient.signalRemoteDisconnect(true); } - } - - private static final ListMultimap serverLANEventBuffer = LinkedListMultimap.create(); - - public static void serverLANInitializeServer(String[] servers) { - synchronized(serverLANEventBuffer) { - serverLANEventBuffer.clear(); - } - rtcLANServer.resetPeerStates(); - rtcLANServer.setIceServers(servers); - } - - public static void serverLANCloseServer() { - rtcLANServer.signalRemoteDisconnect(""); - } - - public static LANPeerEvent serverLANGetEvent(String clientId) { - synchronized(serverLANEventBuffer) { - if(!serverLANEventBuffer.isEmpty()) { - List l = serverLANEventBuffer.get(clientId); - if(!l.isEmpty()) { - return l.remove(0); - } - } - return null; - } - } - - public static List serverLANGetAllEvent(String clientId) { - synchronized(serverLANEventBuffer) { - if(!serverLANEventBuffer.isEmpty()) { - List l = serverLANEventBuffer.removeAll(clientId); - if(l.isEmpty()) { - return null; - } - return l; - } - return null; - } - } - - public static void serverLANWritePacket(String peer, byte[] data) { - rtcLANServer.sendPacketToRemoteClient(peer, new RTCDataChannelBuffer(ByteBuffer.wrap(data), true)); - } - - public static void serverLANCreatePeer(String peer) { - rtcLANServer.signalRemoteConnect(peer); - } - - public static void serverLANPeerICECandidates(String peer, String iceCandidates) { - rtcLANServer.signalRemoteICECandidate(peer, iceCandidates); - } - - public static void serverLANPeerDescription(String peer, String description) { - rtcLANServer.signalRemoteDescription(peer, description); - } - - public static void serverLANDisconnectPeer(String peer) { - rtcLANServer.signalRemoteDisconnect(peer); + rtcLANClient.initialize(); + rtcLANClient.signalRemoteConnect(); } public static int countPeers() { @@ -883,4 +799,154 @@ public class PlatformWebRTC { } return rtcLANServer.countPeers(); } + + public static RelayServerSocket openRelayConnection(String addr, int timeout) { + RelayQuery.RateLimit limit = RelayServerRateLimitTracker.isLimited(addr); + if (limit == RelayQuery.RateLimit.LOCKED || limit == RelayQuery.RateLimit.BLOCKED) { + return new RelayServerSocketRateLimitDummy(limit); + } + return new RelayServerSocketImpl(addr, timeout); + } + + public static RelayQuery openRelayQuery(String addr) { + RelayQuery.RateLimit limit = RelayServerRateLimitTracker.isLimited(addr); + if (limit == RelayQuery.RateLimit.LOCKED || limit == RelayQuery.RateLimit.BLOCKED) { + return new RelayQueryRateLimitDummy(limit); + } + return new RelayQueryImpl(addr); + } + + public static RelayWorldsQuery openRelayWorldsQuery(String addr) { + RelayQuery.RateLimit limit = RelayServerRateLimitTracker.isLimited(addr); + if (limit == RelayQuery.RateLimit.LOCKED || limit == RelayQuery.RateLimit.BLOCKED) { + return new RelayWorldsQueryRateLimitDummy(limit); + } + return new RelayWorldsQueryImpl(addr); + } + + public static void runScheduledTasks() { + List toRun = null; + synchronized (scheduledRunnables) { + if (scheduledRunnables.isEmpty()) + return; + long millis = PlatformRuntime.steadyTimeMillis(); + Iterator itr = scheduledRunnables.iterator(); + while (itr.hasNext()) { + ScheduledRunnable r = itr.next(); + if (r.runAt < millis) { + itr.remove(); + if (toRun == null) { + toRun = new ArrayList<>(1); + } + toRun.add(r); + } + } + } + if (toRun != null) { + Collections.sort(toRun, sortTasks); + for (int i = 0, l = toRun.size(); i < l; ++i) { + try { + toRun.get(i).runnable.run(); + } catch (Throwable t) { + logger.error("Caught exception running scheduled WebRTC task!"); + logger.error(t); + } + } + } + } + + static void scheduleTask(long runAfter, Runnable runnable) { + synchronized (scheduledRunnables) { + scheduledRunnables.add(new ScheduledRunnable(PlatformRuntime.steadyTimeMillis() + runAfter, runnable)); + } + } + + public static void serverLANCloseServer() { + rtcLANServer.signalRemoteDisconnect(""); + } + + public static void serverLANCreatePeer(String peer) { + rtcLANServer.signalRemoteConnect(peer); + } + + public static void serverLANDisconnectPeer(String peer) { + rtcLANServer.signalRemoteDisconnect(peer); + } + + public static List serverLANGetAllEvent(String clientId) { + synchronized (serverLANEventBuffer) { + if (!serverLANEventBuffer.isEmpty()) { + List l = serverLANEventBuffer.removeAll(clientId); + if (l.isEmpty()) { + return null; + } + return l; + } + return null; + } + } + + public static LANPeerEvent serverLANGetEvent(String clientId) { + synchronized (serverLANEventBuffer) { + if (!serverLANEventBuffer.isEmpty()) { + List l = serverLANEventBuffer.get(clientId); + if (!l.isEmpty()) { + return l.remove(0); + } + } + return null; + } + } + + public static void serverLANInitializeServer(String[] servers) { + synchronized (serverLANEventBuffer) { + serverLANEventBuffer.clear(); + } + rtcLANServer.resetPeerStates(); + rtcLANServer.setIceServers(servers); + } + + public static void serverLANPeerDescription(String peer, String description) { + rtcLANServer.signalRemoteDescription(peer, description); + } + + public static void serverLANPeerICECandidates(String peer, String iceCandidates) { + rtcLANServer.signalRemoteICECandidate(peer, iceCandidates); + } + + public static void serverLANWritePacket(String peer, byte[] data) { + rtcLANServer.sendPacketToRemoteClient(peer, new RTCDataChannelBuffer(ByteBuffer.wrap(data), true)); + } + + public static void startRTCLANClient() { + if (rtcLANClient == null) { + rtcLANClient = new LANClient(); + } + } + + public static void startRTCLANServer() { + if (rtcLANServer == null) { + rtcLANServer = new LANServer(); + } + } + + public static boolean supported() { + if (supported && pcFactory == null) { + try { + System.load(Paths.get(SystemUtils.IS_OS_WINDOWS ? "webrtc-java.dll" : "libwebrtc-java.so") + .toAbsolutePath().toString()); + Field f = NativeLoader.class.getDeclaredField("LOADED_LIB_SET"); + f.setAccessible(true); + ((Set) f.get(null)).add("webrtc-java"); + pcFactory = new PeerConnectionFactory(); + Runtime.getRuntime().addShutdownHook(new Thread(() -> pcFactory.dispose())); + supported = true; + } catch (Exception e) { + logger.error("Failed to load WebRTC native library!"); + logger.error(e); + supported = false; + } + } + return supported; + } } \ No newline at end of file diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebView.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebView.java index 650c9451..ecb6162b 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebView.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformWebView.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.webview.WebViewOverlayController.IPacketSen /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,70 +25,70 @@ public class PlatformWebView { private static FallbackWebViewServer fallbackServer = null; private static IPacketSendCallback packetCallback = null; - public static boolean supported() { - return false; - } - - public static boolean isShowing() { - return false; - } - public static void beginShowing(WebViewOptions options, int x, int y, int w, int h) { - + } - public static void resize(int x, int y, int w, int h) { - + public static void endFallbackServer() { + if (fallbackServer != null && !fallbackServer.isDead()) { + fallbackServer.killServer(); + } } public static void endShowing() { - + + } + + public static boolean fallbackRunning() { + return fallbackServer != null && !fallbackServer.isDead(); } public static boolean fallbackSupported() { return true; } + public static String getFallbackURL() { + return fallbackServer != null ? fallbackServer.getURL() : null; + } + + public static void handleMessageFromServer(SPacketWebViewMessageV4EAG packet) { + if (fallbackServer != null && !fallbackServer.isDead()) { + fallbackServer.handleMessageFromServer(packet); + } + } + + public static boolean isShowing() { + return false; + } + public static void launchFallback(WebViewOptions options) { fallbackServer = new FallbackWebViewServer(options); fallbackServer.setPacketSendCallback(packetCallback); fallbackServer.start(); } - public static boolean fallbackRunning() { - return fallbackServer != null && !fallbackServer.isDead(); - } + public static void resize(int x, int y, int w, int h) { - public static String getFallbackURL() { - return fallbackServer != null ? fallbackServer.getURL() : null; - } - - public static void endFallbackServer() { - if(fallbackServer != null && !fallbackServer.isDead()) { - fallbackServer.killServer(); - } - } - - public static void handleMessageFromServer(SPacketWebViewMessageV4EAG packet) { - if(fallbackServer != null && !fallbackServer.isDead()) { - fallbackServer.handleMessageFromServer(packet); - } - } - - public static void setPacketSendCallback(IPacketSendCallback callback) { - packetCallback = callback; - if(fallbackServer != null) { - fallbackServer.setPacketSendCallback(callback); - } } public static void runTick() { - if(fallbackServer != null) { + if (fallbackServer != null) { fallbackServer.runTick(); - if(fallbackServer.isDead()) { + if (fallbackServer.isDead()) { fallbackServer = null; } } } + public static void setPacketSendCallback(IPacketSendCallback callback) { + packetCallback = callback; + if (fallbackServer != null) { + fallbackServer.setPacketSendCallback(callback); + } + } + + public static boolean supported() { + return false; + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLAllocator.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLAllocator.java index e531404c..3a3ccd51 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLAllocator.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLAllocator.java @@ -5,20 +5,21 @@ import org.lwjgl.system.jemalloc.JEmalloc; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerLWJGLAllocator { - + public static class WrongBufferClassType extends RuntimeException { public WrongBufferClassType(String msg) { super(msg); @@ -27,138 +28,140 @@ public class EaglerLWJGLAllocator { public static ByteBuffer allocByteBuffer(int len) { long ret = JEmalloc.nje_malloc(len); - if(ret == 0l) { + if (ret == 0l) { throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); } return new EaglerLWJGLByteBuffer(ret, len, true); } - public static ShortBuffer allocShortBuffer(int len) { - long ret = JEmalloc.nje_malloc(len << 1); - if(ret == 0l) { - throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); - } - return new EaglerLWJGLShortBuffer(ret, len, true); - } - - public static IntBuffer allocIntBuffer(int len) { - long ret = JEmalloc.nje_malloc(len << 2); - if(ret == 0l) { - throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); - } - return new EaglerLWJGLIntBuffer(ret, len, true); - } - public static FloatBuffer allocFloatBuffer(int len) { long ret = JEmalloc.nje_malloc(len << 2); - if(ret == 0l) { + if (ret == 0l) { throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); } return new EaglerLWJGLFloatBuffer(ret, len, true); } + public static IntBuffer allocIntBuffer(int len) { + long ret = JEmalloc.nje_malloc(len << 2); + if (ret == 0l) { + throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); + } + return new EaglerLWJGLIntBuffer(ret, len, true); + } + + public static ShortBuffer allocShortBuffer(int len) { + long ret = JEmalloc.nje_malloc(len << 1); + if (ret == 0l) { + throw new OutOfMemoryError("Native je_malloc call returned null pointer!"); + } + return new EaglerLWJGLShortBuffer(ret, len, true); + } + public static void freeByteBuffer(ByteBuffer buffer) { - if(buffer instanceof EaglerLWJGLByteBuffer) { - EaglerLWJGLByteBuffer buf = (EaglerLWJGLByteBuffer)buffer; - if(buf.original) { + if (buffer instanceof EaglerLWJGLByteBuffer) { + EaglerLWJGLByteBuffer buf = (EaglerLWJGLByteBuffer) buffer; + if (buf.original) { JEmalloc.nje_free(buf.address); - }else { + } else { throwNotOriginal(buffer); } - }else { + } else { + throwNotEagler(buffer); + } + } + + public static void freeFloatBuffer(FloatBuffer buffer) { + if (buffer instanceof EaglerLWJGLFloatBuffer) { + EaglerLWJGLFloatBuffer buf = (EaglerLWJGLFloatBuffer) buffer; + if (buf.original) { + JEmalloc.nje_free(buf.address); + } else { + throwNotOriginal(buffer); + } + } else { + throwNotEagler(buffer); + } + } + + public static void freeIntBuffer(IntBuffer buffer) { + if (buffer instanceof EaglerLWJGLIntBuffer) { + EaglerLWJGLIntBuffer buf = (EaglerLWJGLIntBuffer) buffer; + if (buf.original) { + JEmalloc.nje_free(buf.address); + } else { + throwNotOriginal(buffer); + } + } else { + throwNotEagler(buffer); + } + } + + public static void freeShortBuffer(ShortBuffer buffer) { + if (buffer instanceof EaglerLWJGLShortBuffer) { + EaglerLWJGLShortBuffer buf = (EaglerLWJGLShortBuffer) buffer; + if (buf.original) { + JEmalloc.nje_free(buf.address); + } else { + throwNotOriginal(buffer); + } + } else { throwNotEagler(buffer); } } public static long getAddress(ByteBuffer buffer) { - if(buffer instanceof EaglerLWJGLByteBuffer) { - EaglerLWJGLByteBuffer b = (EaglerLWJGLByteBuffer)buffer; + if (buffer instanceof EaglerLWJGLByteBuffer) { + EaglerLWJGLByteBuffer b = (EaglerLWJGLByteBuffer) buffer; return b.address + b.position(); - }else { + } else { throw notEagler(buffer); } } - public static void freeShortBuffer(ShortBuffer buffer) { - if(buffer instanceof EaglerLWJGLShortBuffer) { - EaglerLWJGLShortBuffer buf = (EaglerLWJGLShortBuffer)buffer; - if(buf.original) { - JEmalloc.nje_free(buf.address); - }else { - throwNotOriginal(buffer); - } - }else { - throwNotEagler(buffer); - } - } - - public static long getAddress(ShortBuffer buffer) { - if(buffer instanceof EaglerLWJGLShortBuffer) { - EaglerLWJGLShortBuffer b = (EaglerLWJGLShortBuffer)buffer; - return b.address + (b.position() << 1); - }else { - throw notEagler(buffer); - } - } - - public static void freeIntBuffer(IntBuffer buffer) { - if(buffer instanceof EaglerLWJGLIntBuffer) { - EaglerLWJGLIntBuffer buf = (EaglerLWJGLIntBuffer)buffer; - if(buf.original) { - JEmalloc.nje_free(buf.address); - }else { - throwNotOriginal(buffer); - } - }else { - throwNotEagler(buffer); - } - } - - public static long getAddress(IntBuffer buffer) { - if(buffer instanceof EaglerLWJGLIntBuffer) { - EaglerLWJGLIntBuffer b = (EaglerLWJGLIntBuffer)buffer; - return b.address + (b.position() << 2); - }else { - throw notEagler(buffer); - } - } - - public static void freeFloatBuffer(FloatBuffer buffer) { - if(buffer instanceof EaglerLWJGLFloatBuffer) { - EaglerLWJGLFloatBuffer buf = (EaglerLWJGLFloatBuffer)buffer; - if(buf.original) { - JEmalloc.nje_free(buf.address); - }else { - throwNotOriginal(buffer); - } - }else { - throwNotEagler(buffer); - } - } - public static long getAddress(FloatBuffer buffer) { - if(buffer instanceof EaglerLWJGLFloatBuffer) { - EaglerLWJGLFloatBuffer b = (EaglerLWJGLFloatBuffer)buffer; + if (buffer instanceof EaglerLWJGLFloatBuffer) { + EaglerLWJGLFloatBuffer b = (EaglerLWJGLFloatBuffer) buffer; return b.address + (b.position() << 2); - }else { + } else { throw notEagler(buffer); } } - - private static void throwNotOriginal(Object clazz) { - throw notOriginal(clazz); + + public static long getAddress(IntBuffer buffer) { + if (buffer instanceof EaglerLWJGLIntBuffer) { + EaglerLWJGLIntBuffer b = (EaglerLWJGLIntBuffer) buffer; + return b.address + (b.position() << 2); + } else { + throw notEagler(buffer); + } } - + + public static long getAddress(ShortBuffer buffer) { + if (buffer instanceof EaglerLWJGLShortBuffer) { + EaglerLWJGLShortBuffer b = (EaglerLWJGLShortBuffer) buffer; + return b.address + (b.position() << 1); + } else { + throw notEagler(buffer); + } + } + + private static WrongBufferClassType notEagler(Object clazz) { + return new WrongBufferClassType( + "Tried to pass a " + clazz.getClass().getSimpleName() + " which is not a native eagler buffer"); + } + private static WrongBufferClassType notOriginal(Object clazz) { - return new WrongBufferClassType("Tried to pass a " + clazz.getClass().getSimpleName() + " which was not the original buffer"); + return new WrongBufferClassType( + "Tried to pass a " + clazz.getClass().getSimpleName() + " which was not the original buffer"); } - + private static void throwNotEagler(Object clazz) { throw notEagler(clazz); } - - private static WrongBufferClassType notEagler(Object clazz) { - return new WrongBufferClassType("Tried to pass a " + clazz.getClass().getSimpleName() + " which is not a native eagler buffer"); + + private static void throwNotOriginal(Object clazz) { + throw notOriginal(clazz); } - + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLByteBuffer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLByteBuffer.java index 74902975..38ebb856 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLByteBuffer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLByteBuffer.java @@ -6,14 +6,15 @@ import net.lax1dude.unsafememcpy.UnsafeUtils; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,301 +42,29 @@ public class EaglerLWJGLByteBuffer implements ByteBuffer { this.original = original; } - @Override - public int capacity() { - return capacity; - } - - @Override - public int position() { - return position; - } - - @Override - public int limit() { - return limit; - } - - @Override - public int remaining() { - return limit - position; - } - - @Override - public boolean hasRemaining() { - return position < limit; - } - - @Override - public boolean hasArray() { - return false; - } - @Override public byte[] array() { throw new UnsupportedOperationException(); } - @Override - public boolean isDirect() { - return true; - } - - @Override - public ByteBuffer duplicate() { - return new EaglerLWJGLByteBuffer(address, capacity, position, limit, mark, false); - } - - @Override - public byte get() { - if(position >= limit) throw Buffer.makeIOOBE(position); - return UnsafeUtils.getMemByte(address + position++); - } - - @Override - public ByteBuffer put(byte b) { - if(position >= limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemByte(address + position++, b); - return this; - } - - @Override - public byte get(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemByte(address + index); - } - - @Override - public ByteBuffer put(int index, byte b) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemByte(address + index, b); - return this; - } - - @Override - public ByteBuffer get(byte[] dst, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpy(dst, offset, address + position, length); - position += length; - return this; - } - - @Override - public ByteBuffer get(byte[] dst) { - if(position + dst.length > limit) throw Buffer.makeIOOBE(position + dst.length - 1); - UnsafeMemcpy.memcpy(dst, 0, address + position, dst.length); - position += dst.length; - return this; - } - - @Override - public ByteBuffer put(ByteBuffer src) { - if(src instanceof EaglerLWJGLByteBuffer) { - EaglerLWJGLByteBuffer c = (EaglerLWJGLByteBuffer)src; - int l = c.limit - c.position; - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - UnsafeMemcpy.memcpy(address + position, c.address + c.position, l); - position += l; - c.position += l; - }else { - int l = src.remaining(); - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - for(int i = 0; i < l; ++i) { - UnsafeUtils.setMemByte(address + position + l, src.get()); - } - position += l; - } - return this; - } - - @Override - public ByteBuffer put(byte[] src, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpy(address + position, src, offset, length); - position += length; - return this; - } - - @Override - public ByteBuffer put(byte[] src) { - if(position + src.length > limit) throw Buffer.makeIOOBE(position + src.length - 1); - UnsafeMemcpy.memcpy(address + position, src, 0, src.length); - position += src.length; - return this; - } - - @Override - public char getChar() { - if(position + 2 > limit) throw Buffer.makeIOOBE(position); - char c = UnsafeUtils.getMemChar(address + position); - position += 2; - return c; - } - - @Override - public ByteBuffer putChar(char value) { - if(position + 2 > limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemChar(address + position, value); - position += 2; - return this; - } - - @Override - public char getChar(int index) { - if(index < 0 || index + 2 > limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemChar(address + index); - } - - @Override - public ByteBuffer putChar(int index, char value) { - if(index < 0 || index + 2 > limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemChar(address + index, value); - return this; - } - - @Override - public short getShort() { - if(position + 2 > limit) throw Buffer.makeIOOBE(position); - short s = UnsafeUtils.getMemShort(address + position); - position += 2; - return s; - } - - @Override - public ByteBuffer putShort(short value) { - if(position + 2 > limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemShort(address + position, value); - position += 2; - return this; - } - - @Override - public short getShort(int index) { - if(index < 0 || index + 2 > limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemShort(address + index); - } - - @Override - public ByteBuffer putShort(int index, short value) { - if(index < 0 || index + 2 > limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemShort(address + index, value); - return this; - } - - @Override - public ShortBuffer asShortBuffer() { - return new EaglerLWJGLShortBuffer(address, capacity >> 1, false); - } - - @Override - public int getInt() { - if(position + 4 > limit) throw Buffer.makeIOOBE(position); - int i = UnsafeUtils.getMemInt(address + position); - position += 4; - return i; - } - - @Override - public ByteBuffer putInt(int value) { - if(position + 4 > limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemInt(address + position, value); - position += 4; - return this; - } - - @Override - public int getInt(int index) { - if(index < 0 || index + 4 > limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemInt(address + index); - } - - @Override - public ByteBuffer putInt(int index, int value) { - if(index < 0 || index + 4 > limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemInt(address + index, value); - return this; - } - - @Override - public IntBuffer asIntBuffer() { - return new EaglerLWJGLIntBuffer(address, capacity >> 2, false); - } - - @Override - public long getLong() { - if(position + 8 > limit) throw Buffer.makeIOOBE(position); - long l = UnsafeUtils.getMemLong(address + position); - position += 8; - return l; - } - - @Override - public ByteBuffer putLong(long value) { - if(position + 8 > limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemLong(address + position, value); - position += 8; - return this; - } - - @Override - public long getLong(int index) { - if(index < 0 || index + 8 > limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemLong(address + index); - } - - @Override - public ByteBuffer putLong(int index, long value) { - if(index < 0 || index + 8 > limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemLong(address + index, value); - return this; - } - - @Override - public float getFloat() { - if(position + 4 > limit) throw Buffer.makeIOOBE(position); - float f = UnsafeUtils.getMemFloat(address + position); - position += 4; - return f; - } - - @Override - public ByteBuffer putFloat(float value) { - if(position + 4 > limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemFloat(address + position, value); - position += 4; - return this; - } - - @Override - public float getFloat(int index) { - if(index < 0 || index + 4 > limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemFloat(address + index); - } - - @Override - public ByteBuffer putFloat(int index, float value) { - if(index < 0 || index + 4 > limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemFloat(address + index, value); - return this; - } - @Override public FloatBuffer asFloatBuffer() { return new EaglerLWJGLFloatBuffer(address, capacity >> 2, false); } @Override - public ByteBuffer mark() { - mark = position; - return this; + public IntBuffer asIntBuffer() { + return new EaglerLWJGLIntBuffer(address, capacity >> 2, false); } @Override - public ByteBuffer reset() { - int m = mark; - if(m < 0) throw new IndexOutOfBoundsException("Invalid mark: " + m); - position = m; - return this; + public ShortBuffer asShortBuffer() { + return new EaglerLWJGLShortBuffer(address, capacity >> 1, false); + } + + @Override + public int capacity() { + return capacity; } @Override @@ -346,6 +75,11 @@ public class EaglerLWJGLByteBuffer implements ByteBuffer { return this; } + @Override + public ByteBuffer duplicate() { + return new EaglerLWJGLByteBuffer(address, capacity, position, limit, mark, false); + } + @Override public ByteBuffer flip() { limit = position; @@ -354,6 +88,320 @@ public class EaglerLWJGLByteBuffer implements ByteBuffer { return this; } + @Override + public byte get() { + if (position >= limit) + throw Buffer.makeIOOBE(position); + return UnsafeUtils.getMemByte(address + position++); + } + + @Override + public ByteBuffer get(byte[] dst) { + if (position + dst.length > limit) + throw Buffer.makeIOOBE(position + dst.length - 1); + UnsafeMemcpy.memcpy(dst, 0, address + position, dst.length); + position += dst.length; + return this; + } + + @Override + public ByteBuffer get(byte[] dst, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpy(dst, offset, address + position, length); + position += length; + return this; + } + + @Override + public byte get(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemByte(address + index); + } + + @Override + public char getChar() { + if (position + 2 > limit) + throw Buffer.makeIOOBE(position); + char c = UnsafeUtils.getMemChar(address + position); + position += 2; + return c; + } + + @Override + public char getChar(int index) { + if (index < 0 || index + 2 > limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemChar(address + index); + } + + @Override + public float getFloat() { + if (position + 4 > limit) + throw Buffer.makeIOOBE(position); + float f = UnsafeUtils.getMemFloat(address + position); + position += 4; + return f; + } + + @Override + public float getFloat(int index) { + if (index < 0 || index + 4 > limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemFloat(address + index); + } + + @Override + public int getInt() { + if (position + 4 > limit) + throw Buffer.makeIOOBE(position); + int i = UnsafeUtils.getMemInt(address + position); + position += 4; + return i; + } + + @Override + public int getInt(int index) { + if (index < 0 || index + 4 > limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemInt(address + index); + } + + @Override + public long getLong() { + if (position + 8 > limit) + throw Buffer.makeIOOBE(position); + long l = UnsafeUtils.getMemLong(address + position); + position += 8; + return l; + } + + @Override + public long getLong(int index) { + if (index < 0 || index + 8 > limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemLong(address + index); + } + + @Override + public short getShort() { + if (position + 2 > limit) + throw Buffer.makeIOOBE(position); + short s = UnsafeUtils.getMemShort(address + position); + position += 2; + return s; + } + + @Override + public short getShort(int index) { + if (index < 0 || index + 2 > limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemShort(address + index); + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public boolean hasRemaining() { + return position < limit; + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public int limit() { + return limit; + } + + @Override + public ByteBuffer limit(int newLimit) { + if (newLimit < 0 || newLimit > capacity) + throw Buffer.makeIOOBE(newLimit); + limit = newLimit; + return this; + } + + @Override + public ByteBuffer mark() { + mark = position; + return this; + } + + @Override + public int position() { + return position; + } + + @Override + public ByteBuffer position(int newPosition) { + if (newPosition < 0 || newPosition > limit) + throw Buffer.makeIOOBE(newPosition); + position = newPosition; + return this; + } + + @Override + public ByteBuffer put(byte b) { + if (position >= limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemByte(address + position++, b); + return this; + } + + @Override + public ByteBuffer put(byte[] src) { + if (position + src.length > limit) + throw Buffer.makeIOOBE(position + src.length - 1); + UnsafeMemcpy.memcpy(address + position, src, 0, src.length); + position += src.length; + return this; + } + + @Override + public ByteBuffer put(byte[] src, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpy(address + position, src, offset, length); + position += length; + return this; + } + + @Override + public ByteBuffer put(ByteBuffer src) { + if (src instanceof EaglerLWJGLByteBuffer) { + EaglerLWJGLByteBuffer c = (EaglerLWJGLByteBuffer) src; + int l = c.limit - c.position; + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + UnsafeMemcpy.memcpy(address + position, c.address + c.position, l); + position += l; + c.position += l; + } else { + int l = src.remaining(); + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + for (int i = 0; i < l; ++i) { + UnsafeUtils.setMemByte(address + position + l, src.get()); + } + position += l; + } + return this; + } + + @Override + public ByteBuffer put(int index, byte b) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemByte(address + index, b); + return this; + } + + @Override + public ByteBuffer putChar(char value) { + if (position + 2 > limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemChar(address + position, value); + position += 2; + return this; + } + + @Override + public ByteBuffer putChar(int index, char value) { + if (index < 0 || index + 2 > limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemChar(address + index, value); + return this; + } + + @Override + public ByteBuffer putFloat(float value) { + if (position + 4 > limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemFloat(address + position, value); + position += 4; + return this; + } + + @Override + public ByteBuffer putFloat(int index, float value) { + if (index < 0 || index + 4 > limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemFloat(address + index, value); + return this; + } + + @Override + public ByteBuffer putInt(int value) { + if (position + 4 > limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemInt(address + position, value); + position += 4; + return this; + } + + @Override + public ByteBuffer putInt(int index, int value) { + if (index < 0 || index + 4 > limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemInt(address + index, value); + return this; + } + + @Override + public ByteBuffer putLong(int index, long value) { + if (index < 0 || index + 8 > limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemLong(address + index, value); + return this; + } + + @Override + public ByteBuffer putLong(long value) { + if (position + 8 > limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemLong(address + position, value); + position += 8; + return this; + } + + @Override + public ByteBuffer putShort(int index, short value) { + if (index < 0 || index + 2 > limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemShort(address + index, value); + return this; + } + + @Override + public ByteBuffer putShort(short value) { + if (position + 2 > limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemShort(address + position, value); + position += 2; + return this; + } + + @Override + public int remaining() { + return limit - position; + } + + @Override + public ByteBuffer reset() { + int m = mark; + if (m < 0) + throw new IndexOutOfBoundsException("Invalid mark: " + m); + position = m; + return this; + } + @Override public ByteBuffer rewind() { position = 0; @@ -361,18 +409,4 @@ public class EaglerLWJGLByteBuffer implements ByteBuffer { return this; } - @Override - public ByteBuffer limit(int newLimit) { - if(newLimit < 0 || newLimit > capacity) throw Buffer.makeIOOBE(newLimit); - limit = newLimit; - return this; - } - - @Override - public ByteBuffer position(int newPosition) { - if(newPosition < 0 || newPosition > limit) throw Buffer.makeIOOBE(newPosition); - position = newPosition; - return this; - } - } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLFloatBuffer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLFloatBuffer.java index aa862fda..ee51c038 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLFloatBuffer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLFloatBuffer.java @@ -6,29 +6,30 @@ import net.lax1dude.unsafememcpy.UnsafeUtils; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerLWJGLFloatBuffer implements FloatBuffer { + private static final int SHIFT = 2; final long address; - final boolean original; + final boolean original; private final int capacity; private int position; private int limit; - private int mark; - private static final int SHIFT = 2; + private int mark; EaglerLWJGLFloatBuffer(long address, int capacity, boolean original) { this(address, capacity, 0, capacity, -1, original); @@ -42,36 +43,6 @@ public class EaglerLWJGLFloatBuffer implements FloatBuffer { this.mark = mark; this.original = original; } - - @Override - public int capacity() { - return capacity; - } - - @Override - public int position() { - return position; - } - - @Override - public int limit() { - return limit; - } - - @Override - public int remaining() { - return limit - position; - } - - @Override - public boolean hasRemaining() { - return position < limit; - } - - @Override - public boolean hasArray() { - return false; - } @Override public float[] array() { @@ -79,117 +50,8 @@ public class EaglerLWJGLFloatBuffer implements FloatBuffer { } @Override - public FloatBuffer duplicate() { - return new EaglerLWJGLFloatBuffer(address, capacity, position, limit, mark, false); - } - - @Override - public float get() { - if(position >= limit) throw Buffer.makeIOOBE(position); - return UnsafeUtils.getMemFloat(address + ((position++) << SHIFT)); - } - - @Override - public FloatBuffer put(float b) { - if(position >= limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemFloat(address + ((position++) << SHIFT), b); - return this; - } - - @Override - public float get(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemFloat(address + (index << SHIFT)); - } - - @Override - public FloatBuffer put(int index, float b) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemFloat(address + (index << SHIFT), b); - return this; - } - - @Override - public float getElement(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemFloat(address + (index << SHIFT)); - } - - @Override - public void putElement(int index, float value) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemFloat(address + (index << SHIFT), value); - } - - @Override - public FloatBuffer get(float[] dst, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpyAlignDst(dst, offset << SHIFT, address + (position << SHIFT), length); - position += length; - return this; - } - - @Override - public FloatBuffer get(float[] dst) { - if(position + dst.length > limit) throw Buffer.makeIOOBE(position + dst.length - 1); - UnsafeMemcpy.memcpyAlignDst(dst, 0, address + (position << SHIFT), dst.length); - position += dst.length; - return this; - } - - @Override - public FloatBuffer put(FloatBuffer src) { - if(src instanceof EaglerLWJGLFloatBuffer) { - EaglerLWJGLFloatBuffer c = (EaglerLWJGLFloatBuffer)src; - int l = c.limit - c.position; - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - UnsafeMemcpy.memcpy(address + (position << SHIFT), c.address + (c.position << SHIFT), l << SHIFT); - position += l; - c.position += l; - }else { - int l = src.remaining(); - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - for(int i = 0; i < l; ++i) { - UnsafeUtils.setMemFloat(address + ((position + l) << SHIFT), src.get()); - } - position += l; - } - return this; - } - - @Override - public FloatBuffer put(float[] src, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, offset << SHIFT, length); - position += length; - return this; - } - - @Override - public FloatBuffer put(float[] src) { - if(position + src.length > limit) throw Buffer.makeIOOBE(position + src.length - 1); - UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, 0, src.length); - position += src.length; - return this; - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public FloatBuffer mark() { - mark = position; - return this; - } - - @Override - public FloatBuffer reset() { - int m = mark; - if(m < 0) throw new IndexOutOfBoundsException("Invalid mark: " + m); - position = m; - return this; + public int capacity() { + return capacity; } @Override @@ -200,6 +62,11 @@ public class EaglerLWJGLFloatBuffer implements FloatBuffer { return this; } + @Override + public FloatBuffer duplicate() { + return new EaglerLWJGLFloatBuffer(address, capacity, position, limit, mark, false); + } + @Override public FloatBuffer flip() { limit = position; @@ -208,6 +75,169 @@ public class EaglerLWJGLFloatBuffer implements FloatBuffer { return this; } + @Override + public float get() { + if (position >= limit) + throw Buffer.makeIOOBE(position); + return UnsafeUtils.getMemFloat(address + ((position++) << SHIFT)); + } + + @Override + public FloatBuffer get(float[] dst) { + if (position + dst.length > limit) + throw Buffer.makeIOOBE(position + dst.length - 1); + UnsafeMemcpy.memcpyAlignDst(dst, 0, address + (position << SHIFT), dst.length); + position += dst.length; + return this; + } + + @Override + public FloatBuffer get(float[] dst, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpyAlignDst(dst, offset << SHIFT, address + (position << SHIFT), length); + position += length; + return this; + } + + @Override + public float get(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemFloat(address + (index << SHIFT)); + } + + @Override + public float getElement(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemFloat(address + (index << SHIFT)); + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public boolean hasRemaining() { + return position < limit; + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public int limit() { + return limit; + } + + @Override + public FloatBuffer limit(int newLimit) { + if (newLimit < 0 || newLimit > capacity) + throw Buffer.makeIOOBE(newLimit); + limit = newLimit; + return this; + } + + @Override + public FloatBuffer mark() { + mark = position; + return this; + } + + @Override + public int position() { + return position; + } + + @Override + public FloatBuffer position(int newPosition) { + if (newPosition < 0 || newPosition > limit) + throw Buffer.makeIOOBE(newPosition); + position = newPosition; + return this; + } + + @Override + public FloatBuffer put(float b) { + if (position >= limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemFloat(address + ((position++) << SHIFT), b); + return this; + } + + @Override + public FloatBuffer put(float[] src) { + if (position + src.length > limit) + throw Buffer.makeIOOBE(position + src.length - 1); + UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, 0, src.length); + position += src.length; + return this; + } + + @Override + public FloatBuffer put(float[] src, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, offset << SHIFT, length); + position += length; + return this; + } + + @Override + public FloatBuffer put(FloatBuffer src) { + if (src instanceof EaglerLWJGLFloatBuffer) { + EaglerLWJGLFloatBuffer c = (EaglerLWJGLFloatBuffer) src; + int l = c.limit - c.position; + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + UnsafeMemcpy.memcpy(address + (position << SHIFT), c.address + (c.position << SHIFT), l << SHIFT); + position += l; + c.position += l; + } else { + int l = src.remaining(); + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + for (int i = 0; i < l; ++i) { + UnsafeUtils.setMemFloat(address + ((position + l) << SHIFT), src.get()); + } + position += l; + } + return this; + } + + @Override + public FloatBuffer put(int index, float b) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemFloat(address + (index << SHIFT), b); + return this; + } + + @Override + public void putElement(int index, float value) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemFloat(address + (index << SHIFT), value); + } + + @Override + public int remaining() { + return limit - position; + } + + @Override + public FloatBuffer reset() { + int m = mark; + if (m < 0) + throw new IndexOutOfBoundsException("Invalid mark: " + m); + position = m; + return this; + } + @Override public FloatBuffer rewind() { position = 0; @@ -215,18 +245,4 @@ public class EaglerLWJGLFloatBuffer implements FloatBuffer { return this; } - @Override - public FloatBuffer limit(int newLimit) { - if(newLimit < 0 || newLimit > capacity) throw Buffer.makeIOOBE(newLimit); - limit = newLimit; - return this; - } - - @Override - public FloatBuffer position(int newPosition) { - if(newPosition < 0 || newPosition > limit) throw Buffer.makeIOOBE(newPosition); - position = newPosition; - return this; - } - } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLIntBuffer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLIntBuffer.java index 030c3a7b..e0fd5785 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLIntBuffer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLIntBuffer.java @@ -6,29 +6,30 @@ import net.lax1dude.unsafememcpy.UnsafeUtils; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerLWJGLIntBuffer implements IntBuffer { + private static final int SHIFT = 2; final long address; - final boolean original; + final boolean original; private final int capacity; private int position; private int limit; - private int mark; - private static final int SHIFT = 2; + private int mark; EaglerLWJGLIntBuffer(long address, int capacity, boolean original) { this(address, capacity, 0, capacity, -1, original); @@ -43,153 +44,14 @@ public class EaglerLWJGLIntBuffer implements IntBuffer { this.original = original; } - @Override - public int capacity() { - return capacity; - } - - @Override - public int position() { - return position; - } - - @Override - public int limit() { - return limit; - } - - @Override - public int remaining() { - return limit - position; - } - - @Override - public boolean hasRemaining() { - return position < limit; - } - - @Override - public boolean hasArray() { - return false; - } - @Override public int[] array() { throw new UnsupportedOperationException(); } @Override - public IntBuffer duplicate() { - return new EaglerLWJGLIntBuffer(address, capacity, position, limit, mark, false); - } - - @Override - public int get() { - if(position >= limit) throw Buffer.makeIOOBE(position); - return UnsafeUtils.getMemInt(address + ((position++) << SHIFT)); - } - - @Override - public IntBuffer put(int b) { - if(position >= limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemInt(address + ((position++) << SHIFT), b); - return this; - } - - @Override - public int get(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemInt(address + (index << SHIFT)); - } - - @Override - public IntBuffer put(int index, int b) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemInt(address + (index << SHIFT), b); - return this; - } - - @Override - public int getElement(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemInt(address + (index << SHIFT)); - } - - @Override - public void putElement(int index, int value) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemInt(address + (index << SHIFT), value); - } - - @Override - public IntBuffer get(int[] dst, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpyAlignDst(dst, offset << SHIFT, address + (position << SHIFT), length); - position += length; - return this; - } - - @Override - public IntBuffer get(int[] dst) { - if(position + dst.length > limit) throw Buffer.makeIOOBE(position + dst.length - 1); - UnsafeMemcpy.memcpyAlignDst(dst, 0, address + (position << SHIFT), dst.length); - position += dst.length; - return this; - } - - @Override - public IntBuffer put(IntBuffer src) { - if(src instanceof EaglerLWJGLIntBuffer) { - EaglerLWJGLIntBuffer c = (EaglerLWJGLIntBuffer)src; - int l = c.limit - c.position; - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - UnsafeMemcpy.memcpy(address + (position << SHIFT), c.address + (c.position << SHIFT), l << SHIFT); - position += l; - c.position += l; - }else { - int l = src.remaining(); - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - for(int i = 0; i < l; ++i) { - UnsafeUtils.setMemInt(address + ((position + l) << SHIFT), src.get()); - } - position += l; - } - return this; - } - - @Override - public IntBuffer put(int[] src, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, offset << SHIFT, length); - position += length; - return this; - } - - @Override - public IntBuffer put(int[] src) { - if(position + src.length > limit) throw Buffer.makeIOOBE(position + src.length - 1); - UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, 0, src.length); - position += src.length; - return this; - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public IntBuffer mark() { - mark = position; - return this; - } - - @Override - public IntBuffer reset() { - int m = mark; - if(m < 0) throw new IndexOutOfBoundsException("Invalid mark: " + m); - position = m; - return this; + public int capacity() { + return capacity; } @Override @@ -200,6 +62,11 @@ public class EaglerLWJGLIntBuffer implements IntBuffer { return this; } + @Override + public IntBuffer duplicate() { + return new EaglerLWJGLIntBuffer(address, capacity, position, limit, mark, false); + } + @Override public IntBuffer flip() { limit = position; @@ -208,6 +75,169 @@ public class EaglerLWJGLIntBuffer implements IntBuffer { return this; } + @Override + public int get() { + if (position >= limit) + throw Buffer.makeIOOBE(position); + return UnsafeUtils.getMemInt(address + ((position++) << SHIFT)); + } + + @Override + public int get(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemInt(address + (index << SHIFT)); + } + + @Override + public IntBuffer get(int[] dst) { + if (position + dst.length > limit) + throw Buffer.makeIOOBE(position + dst.length - 1); + UnsafeMemcpy.memcpyAlignDst(dst, 0, address + (position << SHIFT), dst.length); + position += dst.length; + return this; + } + + @Override + public IntBuffer get(int[] dst, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpyAlignDst(dst, offset << SHIFT, address + (position << SHIFT), length); + position += length; + return this; + } + + @Override + public int getElement(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemInt(address + (index << SHIFT)); + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public boolean hasRemaining() { + return position < limit; + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public int limit() { + return limit; + } + + @Override + public IntBuffer limit(int newLimit) { + if (newLimit < 0 || newLimit > capacity) + throw Buffer.makeIOOBE(newLimit); + limit = newLimit; + return this; + } + + @Override + public IntBuffer mark() { + mark = position; + return this; + } + + @Override + public int position() { + return position; + } + + @Override + public IntBuffer position(int newPosition) { + if (newPosition < 0 || newPosition > limit) + throw Buffer.makeIOOBE(newPosition); + position = newPosition; + return this; + } + + @Override + public IntBuffer put(int b) { + if (position >= limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemInt(address + ((position++) << SHIFT), b); + return this; + } + + @Override + public IntBuffer put(int index, int b) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemInt(address + (index << SHIFT), b); + return this; + } + + @Override + public IntBuffer put(int[] src) { + if (position + src.length > limit) + throw Buffer.makeIOOBE(position + src.length - 1); + UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, 0, src.length); + position += src.length; + return this; + } + + @Override + public IntBuffer put(int[] src, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, offset << SHIFT, length); + position += length; + return this; + } + + @Override + public IntBuffer put(IntBuffer src) { + if (src instanceof EaglerLWJGLIntBuffer) { + EaglerLWJGLIntBuffer c = (EaglerLWJGLIntBuffer) src; + int l = c.limit - c.position; + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + UnsafeMemcpy.memcpy(address + (position << SHIFT), c.address + (c.position << SHIFT), l << SHIFT); + position += l; + c.position += l; + } else { + int l = src.remaining(); + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + for (int i = 0; i < l; ++i) { + UnsafeUtils.setMemInt(address + ((position + l) << SHIFT), src.get()); + } + position += l; + } + return this; + } + + @Override + public void putElement(int index, int value) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemInt(address + (index << SHIFT), value); + } + + @Override + public int remaining() { + return limit - position; + } + + @Override + public IntBuffer reset() { + int m = mark; + if (m < 0) + throw new IndexOutOfBoundsException("Invalid mark: " + m); + position = m; + return this; + } + @Override public IntBuffer rewind() { position = 0; @@ -215,18 +245,4 @@ public class EaglerLWJGLIntBuffer implements IntBuffer { return this; } - @Override - public IntBuffer limit(int newLimit) { - if(newLimit < 0 || newLimit > capacity) throw Buffer.makeIOOBE(newLimit); - limit = newLimit; - return this; - } - - @Override - public IntBuffer position(int newPosition) { - if(newPosition < 0 || newPosition > limit) throw Buffer.makeIOOBE(newPosition); - position = newPosition; - return this; - } - } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLShortBuffer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLShortBuffer.java index 41d45f61..12bf3d35 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLShortBuffer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerLWJGLShortBuffer.java @@ -6,29 +6,30 @@ import net.lax1dude.unsafememcpy.UnsafeUtils; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerLWJGLShortBuffer implements ShortBuffer { + private static final int SHIFT = 1; final long address; - final boolean original; + final boolean original; private final int capacity; private int position; private int limit; - private int mark; - private static final int SHIFT = 1; + private int mark; EaglerLWJGLShortBuffer(long address, int capacity, boolean original) { this(address, capacity, 0, capacity, -1, original); @@ -43,153 +44,14 @@ public class EaglerLWJGLShortBuffer implements ShortBuffer { this.original = original; } - @Override - public int capacity() { - return capacity; - } - - @Override - public int position() { - return position; - } - - @Override - public int limit() { - return limit; - } - - @Override - public int remaining() { - return limit - position; - } - - @Override - public boolean hasRemaining() { - return position < limit; - } - - @Override - public boolean hasArray() { - return false; - } - @Override public short[] array() { throw new UnsupportedOperationException(); } @Override - public ShortBuffer duplicate() { - return new EaglerLWJGLShortBuffer(address, capacity, position, limit, mark, false); - } - - @Override - public short get() { - if(position >= limit) throw Buffer.makeIOOBE(position); - return UnsafeUtils.getMemShort(address + ((position++) << SHIFT)); - } - - @Override - public ShortBuffer put(short b) { - if(position >= limit) throw Buffer.makeIOOBE(position); - UnsafeUtils.setMemShort(address + ((position++) << SHIFT), b); - return this; - } - - @Override - public short get(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemShort(address + (index << SHIFT)); - } - - @Override - public ShortBuffer put(int index, short b) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemShort(address + (index << SHIFT), b); - return this; - } - - @Override - public short getElement(int index) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - return UnsafeUtils.getMemShort(address + (index << SHIFT)); - } - - @Override - public void putElement(int index, short value) { - if(index < 0 || index >= limit) throw Buffer.makeIOOBE(index); - UnsafeUtils.setMemShort(address + (index << SHIFT), value); - } - - @Override - public ShortBuffer get(short[] dst, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpyAlignDst(dst, offset << SHIFT, address + (position << SHIFT), length); - position += length; - return this; - } - - @Override - public ShortBuffer get(short[] dst) { - if(position + dst.length > limit) throw Buffer.makeIOOBE(position + dst.length - 1); - UnsafeMemcpy.memcpyAlignDst(dst, 0, address + (position << SHIFT), dst.length); - position += dst.length; - return this; - } - - @Override - public ShortBuffer put(ShortBuffer src) { - if(src instanceof EaglerLWJGLShortBuffer) { - EaglerLWJGLShortBuffer c = (EaglerLWJGLShortBuffer)src; - int l = c.limit - c.position; - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - UnsafeMemcpy.memcpy(address + (position << SHIFT), c.address + (c.position << SHIFT), l << SHIFT); - position += l; - c.position += l; - }else { - int l = src.remaining(); - if(position + l > limit) throw Buffer.makeIOOBE(position + l - 1); - for(int i = 0; i < l; ++i) { - UnsafeUtils.setMemInt(address + ((position + l) << SHIFT), src.get()); - } - position += l; - } - return this; - } - - @Override - public ShortBuffer put(short[] src, int offset, int length) { - if(position + length > limit) throw Buffer.makeIOOBE(position + length - 1); - UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, offset << SHIFT, length); - position += length; - return this; - } - - @Override - public ShortBuffer put(short[] src) { - if(position + src.length > limit) throw Buffer.makeIOOBE(position + src.length - 1); - UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, 0, src.length); - position += src.length; - return this; - } - - @Override - public boolean isDirect() { - return true; - } - - @Override - public ShortBuffer mark() { - mark = position; - return this; - } - - @Override - public ShortBuffer reset() { - int m = mark; - if(m < 0) throw new IndexOutOfBoundsException("Invalid mark: " + m); - position = m; - return this; + public int capacity() { + return capacity; } @Override @@ -200,6 +62,11 @@ public class EaglerLWJGLShortBuffer implements ShortBuffer { return this; } + @Override + public ShortBuffer duplicate() { + return new EaglerLWJGLShortBuffer(address, capacity, position, limit, mark, false); + } + @Override public ShortBuffer flip() { limit = position; @@ -208,6 +75,169 @@ public class EaglerLWJGLShortBuffer implements ShortBuffer { return this; } + @Override + public short get() { + if (position >= limit) + throw Buffer.makeIOOBE(position); + return UnsafeUtils.getMemShort(address + ((position++) << SHIFT)); + } + + @Override + public short get(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemShort(address + (index << SHIFT)); + } + + @Override + public ShortBuffer get(short[] dst) { + if (position + dst.length > limit) + throw Buffer.makeIOOBE(position + dst.length - 1); + UnsafeMemcpy.memcpyAlignDst(dst, 0, address + (position << SHIFT), dst.length); + position += dst.length; + return this; + } + + @Override + public ShortBuffer get(short[] dst, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpyAlignDst(dst, offset << SHIFT, address + (position << SHIFT), length); + position += length; + return this; + } + + @Override + public short getElement(int index) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + return UnsafeUtils.getMemShort(address + (index << SHIFT)); + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public boolean hasRemaining() { + return position < limit; + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public int limit() { + return limit; + } + + @Override + public ShortBuffer limit(int newLimit) { + if (newLimit < 0 || newLimit > capacity) + throw Buffer.makeIOOBE(newLimit); + limit = newLimit; + return this; + } + + @Override + public ShortBuffer mark() { + mark = position; + return this; + } + + @Override + public int position() { + return position; + } + + @Override + public ShortBuffer position(int newPosition) { + if (newPosition < 0 || newPosition > limit) + throw Buffer.makeIOOBE(newPosition); + position = newPosition; + return this; + } + + @Override + public ShortBuffer put(int index, short b) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemShort(address + (index << SHIFT), b); + return this; + } + + @Override + public ShortBuffer put(short b) { + if (position >= limit) + throw Buffer.makeIOOBE(position); + UnsafeUtils.setMemShort(address + ((position++) << SHIFT), b); + return this; + } + + @Override + public ShortBuffer put(short[] src) { + if (position + src.length > limit) + throw Buffer.makeIOOBE(position + src.length - 1); + UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, 0, src.length); + position += src.length; + return this; + } + + @Override + public ShortBuffer put(short[] src, int offset, int length) { + if (position + length > limit) + throw Buffer.makeIOOBE(position + length - 1); + UnsafeMemcpy.memcpyAlignSrc(address + (position << SHIFT), src, offset << SHIFT, length); + position += length; + return this; + } + + @Override + public ShortBuffer put(ShortBuffer src) { + if (src instanceof EaglerLWJGLShortBuffer) { + EaglerLWJGLShortBuffer c = (EaglerLWJGLShortBuffer) src; + int l = c.limit - c.position; + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + UnsafeMemcpy.memcpy(address + (position << SHIFT), c.address + (c.position << SHIFT), l << SHIFT); + position += l; + c.position += l; + } else { + int l = src.remaining(); + if (position + l > limit) + throw Buffer.makeIOOBE(position + l - 1); + for (int i = 0; i < l; ++i) { + UnsafeUtils.setMemInt(address + ((position + l) << SHIFT), src.get()); + } + position += l; + } + return this; + } + + @Override + public void putElement(int index, short value) { + if (index < 0 || index >= limit) + throw Buffer.makeIOOBE(index); + UnsafeUtils.setMemShort(address + (index << SHIFT), value); + } + + @Override + public int remaining() { + return limit - position; + } + + @Override + public ShortBuffer reset() { + int m = mark; + if (m < 0) + throw new IndexOutOfBoundsException("Invalid mark: " + m); + position = m; + return this; + } + @Override public ShortBuffer rewind() { position = 0; @@ -215,18 +245,4 @@ public class EaglerLWJGLShortBuffer implements ShortBuffer { return this; } - @Override - public ShortBuffer limit(int newLimit) { - if(newLimit < 0 || newLimit > capacity) throw Buffer.makeIOOBE(newLimit); - limit = newLimit; - return this; - } - - @Override - public ShortBuffer position(int newPosition) { - if(newPosition < 0 || newPosition > limit) throw Buffer.makeIOOBE(newPosition); - position = newPosition; - return this; - } - } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DebugFilesystem.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DebugFilesystem.java index eb5cbcd8..0638250f 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DebugFilesystem.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DebugFilesystem.java @@ -16,14 +16,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFSIterator2.BreakLoop; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,8 +32,9 @@ import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFSIterator2.BreakLoop; public class DebugFilesystem implements IEaglerFilesystem { public static DebugFilesystem initialize(String fsName, File filesystemRoot) { - if(!filesystemRoot.isDirectory() && !filesystemRoot.mkdirs()) { - throw new EaglerFileSystemException("Could not create directory for virtual filesystem: " + filesystemRoot.getAbsolutePath()); + if (!filesystemRoot.isDirectory() && !filesystemRoot.mkdirs()) { + throw new EaglerFileSystemException( + "Could not create directory for virtual filesystem: " + filesystemRoot.getAbsolutePath()); } return new DebugFilesystem(fsName, filesystemRoot); } @@ -45,6 +47,171 @@ public class DebugFilesystem implements IEaglerFilesystem { this.filesystemRoot = root; } + @Override + public void closeHandle() { + + } + + private void deleteParentIfEmpty(File f) { + String[] s; + while ((f = f.getParentFile()) != null && (s = f.list()) != null && s.length == 0) { + f.delete(); + } + } + + @Override + public int eaglerCopy(String pathNameOld, String pathNameNew) { + File f1 = getJREFile(pathNameOld); + File f2 = getJREFile(pathNameNew); + if (!f1.isFile()) { + return -1; + } + if (f2.isDirectory()) { + throw new EaglerFileSystemException("Destination file is a directory: " + f2.getAbsolutePath()); + } + File p = f2.getParentFile(); + if (!p.isDirectory()) { + if (!p.mkdirs()) { + throw new EaglerFileSystemException("Could not create parent directory: " + p.getAbsolutePath()); + } + } + int sz = 0; + try (FileInputStream is = new FileInputStream(f1)) { + try (FileOutputStream os = new FileOutputStream(f2)) { + byte[] copyBuffer = new byte[4096]; + int i; + while ((i = is.read(copyBuffer, 0, copyBuffer.length)) != -1) { + os.write(copyBuffer, 0, i); + sz += i; + } + } + } catch (IOException e) { + throw new EaglerFileSystemException( + "Failed to copy \"" + f1.getAbsolutePath() + "\" to file \"" + f2.getAbsolutePath() + "\"", e); + } + return sz; + } + + @Override + public boolean eaglerDelete(String pathName) { + File f = getJREFile(pathName); + if (!f.exists()) { + PlatformFilesystem.logger.warn("Tried to delete file that doesn't exist: \"{}\"", pathName); + return false; + } + if (f.delete()) { + deleteParentIfEmpty(f); + return true; + } + return false; + } + + @Override + public boolean eaglerExists(String pathName) { + return getJREFile(pathName).isFile(); + } + + @Override + public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { + try { + iterateFile(pathName, getJREFile(pathName), itr, recursive); + } catch (BreakLoop ex) { + } + } + + @Override + public boolean eaglerMove(String pathNameOld, String pathNameNew) { + File f1 = getJREFile(pathNameOld); + File f2 = getJREFile(pathNameNew); + if (f2.exists()) { + PlatformFilesystem.logger + .warn("Tried to rename file \"{}\" to \"{}\" which already exists! File will be replaced"); + if (!f2.delete()) { + return false; + } + } + if (f1.renameTo(f2)) { + deleteParentIfEmpty(f1); + return true; + } + return false; + } + + @Override + public ByteBuffer eaglerRead(String pathName) { + File f = getJREFile(pathName); + if (f.isFile()) { + long fileSize = f.length(); + if (fileSize > 2147483647L) + throw new EaglerFileSystemException("Too large: " + fileSize + " @ " + f.getAbsolutePath()); + ByteBuffer buf = PlatformRuntime.allocateByteBuffer((int) fileSize); + try (FileInputStream is = new FileInputStream(f)) { + byte[] copyBuffer = new byte[4096]; + int i; + while ((i = is.read(copyBuffer, 0, copyBuffer.length)) != -1) { + buf.put(copyBuffer, 0, i); + } + if (buf.remaining() > 0) { + throw new EaglerFileSystemException( + "ERROR: " + buf.remaining() + " bytes are remaining after reading: " + f.getAbsolutePath()); + } + buf.flip(); + ByteBuffer tmp = buf; + buf = null; + return tmp; + } catch (IOException e) { + throw new EaglerFileSystemException("Failed to read: " + f.getAbsolutePath(), e); + } catch (IndexOutOfBoundsException ex) { + throw new EaglerFileSystemException( + "ERROR: Expected " + fileSize + " bytes, buffer overflow reading: " + f.getAbsolutePath(), ex); + } finally { + if (buf != null) { + PlatformRuntime.freeByteBuffer(buf); + } + } + } else { + PlatformFilesystem.logger.warn("Tried to read file that doesn't exist: \"{}\"", f.getAbsolutePath()); + return null; + } + } + + @Override + public int eaglerSize(String pathName) { + File f = getJREFile(pathName); + if (f.isFile()) { + long fileSize = f.length(); + if (fileSize > 2147483647L) + throw new EaglerFileSystemException("Too large: " + fileSize + " @ " + f.getAbsolutePath()); + return (int) fileSize; + } else { + return -1; + } + } + + @Override + public void eaglerWrite(String pathName, ByteBuffer data) { + File f = getJREFile(pathName); + File p = f.getParentFile(); + if (!p.isDirectory()) { + if (!p.mkdirs()) { + throw new EaglerFileSystemException("Could not create parent directory: " + p.getAbsolutePath()); + } + } + try (FileOutputStream fos = new FileOutputStream(f)) { + byte[] copyBuffer = new byte[Math.min(4096, data.remaining())]; + int i; + while ((i = data.remaining()) > 0) { + if (i > copyBuffer.length) { + i = copyBuffer.length; + } + data.get(copyBuffer, 0, i); + fos.write(copyBuffer, 0, i); + } + } catch (IOException e) { + throw new EaglerFileSystemException("Failed to write: " + f.getAbsolutePath(), e); + } + } + @Override public String getFilesystemName() { return fsName; @@ -55,194 +222,35 @@ public class DebugFilesystem implements IEaglerFilesystem { return "desktopruntime:" + filesystemRoot.getAbsolutePath(); } - @Override - public boolean eaglerDelete(String pathName) { - File f = getJREFile(pathName); - if(!f.exists()) { - PlatformFilesystem.logger.warn("Tried to delete file that doesn't exist: \"{}\"", pathName); - return false; - } - if(f.delete()) { - deleteParentIfEmpty(f); - return true; - } - return false; - } - - @Override - public ByteBuffer eaglerRead(String pathName) { - File f = getJREFile(pathName); - if(f.isFile()) { - long fileSize = f.length(); - if(fileSize > 2147483647L) throw new EaglerFileSystemException("Too large: " + fileSize + " @ " + f.getAbsolutePath()); - ByteBuffer buf = PlatformRuntime.allocateByteBuffer((int)fileSize); - try(FileInputStream is = new FileInputStream(f)) { - byte[] copyBuffer = new byte[4096]; - int i; - while((i = is.read(copyBuffer, 0, copyBuffer.length)) != -1) { - buf.put(copyBuffer, 0, i); - } - if(buf.remaining() > 0) { - throw new EaglerFileSystemException("ERROR: " + buf.remaining() + " bytes are remaining after reading: " + f.getAbsolutePath()); - } - buf.flip(); - ByteBuffer tmp = buf; - buf = null; - return tmp; - }catch (IOException e) { - throw new EaglerFileSystemException("Failed to read: " + f.getAbsolutePath(), e); - }catch(IndexOutOfBoundsException ex) { - throw new EaglerFileSystemException("ERROR: Expected " + fileSize + " bytes, buffer overflow reading: " + f.getAbsolutePath(), ex); - }finally { - if(buf != null) { - PlatformRuntime.freeByteBuffer(buf); - } - } - }else { - PlatformFilesystem.logger.warn("Tried to read file that doesn't exist: \"{}\"", f.getAbsolutePath()); - return null; - } - } - - @Override - public void eaglerWrite(String pathName, ByteBuffer data) { - File f = getJREFile(pathName); - File p = f.getParentFile(); - if(!p.isDirectory()) { - if(!p.mkdirs()) { - throw new EaglerFileSystemException("Could not create parent directory: " + p.getAbsolutePath()); - } - } - try(FileOutputStream fos = new FileOutputStream(f)) { - byte[] copyBuffer = new byte[Math.min(4096, data.remaining())]; - int i; - while((i = data.remaining()) > 0) { - if(i > copyBuffer.length) { - i = copyBuffer.length; - } - data.get(copyBuffer, 0, i); - fos.write(copyBuffer, 0, i); - } - }catch (IOException e) { - throw new EaglerFileSystemException("Failed to write: " + f.getAbsolutePath(), e); - } - } - - @Override - public boolean eaglerExists(String pathName) { - return getJREFile(pathName).isFile(); - } - - @Override - public boolean eaglerMove(String pathNameOld, String pathNameNew) { - File f1 = getJREFile(pathNameOld); - File f2 = getJREFile(pathNameNew); - if(f2.exists()) { - PlatformFilesystem.logger.warn("Tried to rename file \"{}\" to \"{}\" which already exists! File will be replaced"); - if(!f2.delete()) { - return false; - } - } - if(f1.renameTo(f2)) { - deleteParentIfEmpty(f1); - return true; - } - return false; - } - - @Override - public int eaglerCopy(String pathNameOld, String pathNameNew) { - File f1 = getJREFile(pathNameOld); - File f2 = getJREFile(pathNameNew); - if(!f1.isFile()) { - return -1; - } - if(f2.isDirectory()) { - throw new EaglerFileSystemException("Destination file is a directory: " + f2.getAbsolutePath()); - } - File p = f2.getParentFile(); - if(!p.isDirectory()) { - if(!p.mkdirs()) { - throw new EaglerFileSystemException("Could not create parent directory: " + p.getAbsolutePath()); - } - } - int sz = 0; - try(FileInputStream is = new FileInputStream(f1)) { - try(FileOutputStream os = new FileOutputStream(f2)) { - byte[] copyBuffer = new byte[4096]; - int i; - while((i = is.read(copyBuffer, 0, copyBuffer.length)) != -1) { - os.write(copyBuffer, 0, i); - sz += i; - } - } - }catch (IOException e) { - throw new EaglerFileSystemException("Failed to copy \"" + f1.getAbsolutePath() + "\" to file \"" + f2.getAbsolutePath() + "\"", e); - } - return sz; - } - - @Override - public int eaglerSize(String pathName) { - File f = getJREFile(pathName); - if(f.isFile()) { - long fileSize = f.length(); - if(fileSize > 2147483647L) throw new EaglerFileSystemException("Too large: " + fileSize + " @ " + f.getAbsolutePath()); - return (int)fileSize; - }else { - return -1; - } - } - - @Override - public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { - try { - iterateFile(pathName, getJREFile(pathName), itr, recursive); - }catch(BreakLoop ex) { - } - } - - private void iterateFile(String pathName, File f, VFSFilenameIterator itr, boolean recursive) { - if(!f.exists()) { - return; - } - if(!f.isDirectory()) { - itr.next(pathName); - return; - } - File[] fa = f.listFiles(); - for(int i = 0; i < fa.length; ++i) { - File ff = fa[i]; - String fn = pathName + "/" + ff.getName(); - if(ff.isDirectory()) { - if(recursive) { - iterateFile(fn, ff, itr, true); - } - }else { - itr.next(fn); - } - } - } - private File getJREFile(String path) { return new File(filesystemRoot, path); } - private void deleteParentIfEmpty(File f) { - String[] s; - while((f = f.getParentFile()) != null && (s = f.list()) != null && s.length == 0) { - f.delete(); - } - } - @Override public boolean isRamdisk() { return false; } - @Override - public void closeHandle() { - + private void iterateFile(String pathName, File f, VFSFilenameIterator itr, boolean recursive) { + if (!f.exists()) { + return; + } + if (!f.isDirectory()) { + itr.next(pathName); + return; + } + File[] fa = f.listFiles(); + for (int i = 0; i < fa.length; ++i) { + File ff = fa[i]; + String fn = pathName + "/" + ff.getName(); + if (ff.isDirectory()) { + if (recursive) { + iterateFile(fn, ff, itr, true); + } + } else { + itr.next(fn); + } + } } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopClientConfigAdapter.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopClientConfigAdapter.java index 5de69dc5..56bee96e 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopClientConfigAdapter.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopClientConfigAdapter.java @@ -15,26 +15,64 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayEntry; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DesktopClientConfigAdapter implements IClientConfigAdapter { + private static class DesktopClientConfigAdapterHooks implements IClientConfigAdapterHooks { + + @Override + public void callCrashReportHook(String crashReport, Consumer customMessageCB) { + + } + + @Override + public String callLocalStorageLoadHook(String key) { + return null; + } + + @Override + public void callLocalStorageSavedHook(String key, String base64) { + + } + + @Override + public void callScreenChangedHook(String screenName, int scaledWidth, int scaledHeight, int realWidth, + int realHeight, int scaleFactor) { + + } + + } + public static final IClientConfigAdapter instance = new DesktopClientConfigAdapter(); public final List defaultServers = new ArrayList<>(); private final DesktopClientConfigAdapterHooks hooks = new DesktopClientConfigAdapterHooks(); + private final List relays = new ArrayList<>(); + + @Override + public boolean allowUpdateDL() { + return false; + } + + @Override + public boolean allowUpdateSvc() { + return false; + } + @Override public String getDefaultLocale() { return "en_US"; @@ -46,18 +84,13 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { } @Override - public String getServerToJoin() { + public String getDownloadOfflineButtonLink() { return null; } @Override - public String getWorldsDB() { - return "worlds"; - } - - @Override - public String getResourcePacksDB() { - return "resourcePacks"; + public IClientConfigAdapterHooks getHooks() { + return hooks; } @Override @@ -65,7 +98,10 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { return new JSONObject("{\"container\":null,\"worldsDB\":\"worlds\"}"); } - private final List relays = new ArrayList<>(); + @Override + public String getLocalStorageNamespace() { + return EaglercraftVersion.localStorageNamespace; + } @Override public List getRelays() { @@ -78,6 +114,46 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { return relays; } + @Override + public String getResourcePacksDB() { + return "resourcePacks"; + } + + @Override + public String getServerToJoin() { + return null; + } + + @Override + public String getWorldsDB() { + return "worlds"; + } + + @Override + public boolean isAllowBootMenu() { + return false; + } + + @Override + public boolean isAllowFNAWSkins() { + return true; + } + + @Override + public boolean isAllowServerRedirects() { + return true; + } + + @Override + public boolean isAllowVoiceClient() { + return false; + } + + @Override + public boolean isCheckRelaysForUpdates() { + return false; + } + @Override public boolean isCheckShaderGLErrors() { return true; @@ -89,12 +165,7 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { } @Override - public boolean allowUpdateSvc() { - return false; - } - - @Override - public boolean allowUpdateDL() { + public boolean isEaglerNoDelay() { return false; } @@ -103,46 +174,6 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { return false; } - @Override - public String getDownloadOfflineButtonLink() { - return null; - } - - @Override - public boolean useSpecialCursors() { - return false; - } - - @Override - public boolean isLogInvalidCerts() { - return false; - } - - @Override - public boolean isCheckRelaysForUpdates() { - return false; - } - - @Override - public boolean isEnableSignatureBadge() { - return false; - } - - @Override - public boolean isAllowVoiceClient() { - return false; - } - - @Override - public boolean isAllowFNAWSkins() { - return true; - } - - @Override - public String getLocalStorageNamespace() { - return EaglercraftVersion.localStorageNamespace; - } - @Override public boolean isEnableMinceraft() { return true; @@ -154,17 +185,7 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { } @Override - public boolean isAllowServerRedirects() { - return true; - } - - @Override - public boolean isOpenDebugConsoleOnLaunch() { - return false; - } - - @Override - public boolean isForceWebViewSupport() { + public boolean isEnableSignatureBadge() { return false; } @@ -173,18 +194,23 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { return true; } - @Override - public boolean isAllowBootMenu() { - return false; - } - @Override public boolean isForceProfanityFilter() { return false; } @Override - public boolean isEaglerNoDelay() { + public boolean isForceWebViewSupport() { + return false; + } + + @Override + public boolean isLogInvalidCerts() { + return false; + } + + @Override + public boolean isOpenDebugConsoleOnLaunch() { return false; } @@ -194,33 +220,8 @@ public class DesktopClientConfigAdapter implements IClientConfigAdapter { } @Override - public IClientConfigAdapterHooks getHooks() { - return hooks; - } - - private static class DesktopClientConfigAdapterHooks implements IClientConfigAdapterHooks { - - @Override - public void callLocalStorageSavedHook(String key, String base64) { - - } - - @Override - public String callLocalStorageLoadHook(String key) { - return null; - } - - @Override - public void callCrashReportHook(String crashReport, Consumer customMessageCB) { - - } - - @Override - public void callScreenChangedHook(String screenName, int scaledWidth, int scaledHeight, int realWidth, - int realHeight, int scaleFactor) { - - } - + public boolean useSpecialCursors() { + return false; } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketClient.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketClient.java index a3b72a89..be295f94 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketClient.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketClient.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,7 +27,7 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; public class DesktopWebSocketClient extends AbstractWebSocketClient { static final Logger logger = LogManager.getLogger("DesktopWebSocketClient"); - + volatile EnumEaglerConnectionState playConnectState = EnumEaglerConnectionState.CONNECTING; final Object connectOpenMutex = new Object(); final WebSocketClientImpl clientImpl; @@ -38,18 +39,25 @@ public class DesktopWebSocketClient extends AbstractWebSocketClient { this.currentURI = currentURI; currentURIStr = currentURI.toString(); clientImpl = new WebSocketClientImpl(this, currentURI); - clientImpl.addHeader("Origin", "EAG_LWJGL_" + (EaglercraftVersion.projectForkName + "_" - + EaglercraftVersion.projectOriginVersion).replaceAll("[^a-zA-Z0-9\\-_\\.]", "_")); + clientImpl.addHeader("Origin", + "EAG_LWJGL_" + (EaglercraftVersion.projectForkName + "_" + EaglercraftVersion.projectOriginVersion) + .replaceAll("[^a-zA-Z0-9\\-_\\.]", "_")); } @Override - public EnumEaglerConnectionState getState() { - return playConnectState; + public void close() { + if (!playConnectState.isClosed()) { + try { + clientImpl.closeBlocking(); + } catch (InterruptedException e) { + } + playConnectState = EnumEaglerConnectionState.CLOSED; + } } @Override public boolean connectBlocking(int timeoutMS) { - synchronized(connectOpenMutex) { + synchronized (connectOpenMutex) { try { connectOpenMutex.wait(timeoutMS); } catch (InterruptedException e) { @@ -60,8 +68,16 @@ public class DesktopWebSocketClient extends AbstractWebSocketClient { } @Override - public boolean isOpen() { - return playConnectState.isOpen(); + public EnumEaglerConnectionState getState() { + return playConnectState; + } + + public void handleBytes(byte[] array) { + addRecievedFrame(new DesktopWebSocketFrameBinary(array)); + } + + public void handleString(String str) { + addRecievedFrame(new DesktopWebSocketFrameString(str)); } @Override @@ -70,40 +86,28 @@ public class DesktopWebSocketClient extends AbstractWebSocketClient { } @Override - public void close() { - if(!playConnectState.isClosed()) { - try { - clientImpl.closeBlocking(); - } catch (InterruptedException e) { - } - playConnectState = EnumEaglerConnectionState.CLOSED; + public boolean isOpen() { + return playConnectState.isOpen(); + } + + @Override + public void send(byte[] bytes) { + if (clientImpl.isClosed()) { + logger.error("[{}]: Client tried to send {} byte packet while the socket was closed!", currentURIStr, + bytes.length); + } else { + clientImpl.send(bytes); } } @Override public void send(String str) { - if(clientImpl.isClosed()) { - logger.error("[{}]: Client tried to send {} char packet while the socket was closed!", currentURIStr, str.length()); - }else { + if (clientImpl.isClosed()) { + logger.error("[{}]: Client tried to send {} char packet while the socket was closed!", currentURIStr, + str.length()); + } else { clientImpl.send(str); } } - @Override - public void send(byte[] bytes) { - if(clientImpl.isClosed()) { - logger.error("[{}]: Client tried to send {} byte packet while the socket was closed!", currentURIStr, bytes.length); - }else { - clientImpl.send(bytes); - } - } - - public void handleString(String str) { - addRecievedFrame(new DesktopWebSocketFrameString(str)); - } - - public void handleBytes(byte[] array) { - addRecievedFrame(new DesktopWebSocketFrameBinary(array)); - } - } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameBinary.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameBinary.java index c8919714..a2370767 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameBinary.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameBinary.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,16 +32,6 @@ public class DesktopWebSocketFrameBinary implements IWebSocketFrame { this.timestamp = PlatformRuntime.steadyTimeMillis(); } - @Override - public boolean isString() { - return false; - } - - @Override - public String getString() { - return null; - } - @Override public byte[] getByteArray() { return byteArray; @@ -56,9 +47,19 @@ public class DesktopWebSocketFrameBinary implements IWebSocketFrame { return byteArray.length; } + @Override + public String getString() { + return null; + } + @Override public long getTimestamp() { return timestamp; } + @Override + public boolean isString() { + return false; + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameString.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameString.java index 3be7a6b2..d8d67cc6 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameString.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/DesktopWebSocketFrameString.java @@ -8,14 +8,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,16 +31,6 @@ public class DesktopWebSocketFrameString implements IWebSocketFrame { this.timestamp = PlatformRuntime.steadyTimeMillis(); } - @Override - public boolean isString() { - return true; - } - - @Override - public String getString() { - return string; - } - @Override public byte[] getByteArray() { return null; @@ -55,9 +46,19 @@ public class DesktopWebSocketFrameString implements IWebSocketFrame { return string.length(); } + @Override + public String getString() { + return string; + } + @Override public long getTimestamp() { return timestamp; } + @Override + public boolean isString() { + return true; + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewHTTPD.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewHTTPD.java index f2eabebf..ea39fd2c 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewHTTPD.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewHTTPD.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,11 +32,12 @@ class FallbackWebViewHTTPD extends NanoHTTPD { } @Override - public Response serve(IHTTPSession session) { - if("/RTWebViewClient".equals(session.getUri())) { + public Response serve(IHTTPSession session) { + if ("/RTWebViewClient".equals(session.getUri())) { return newFixedLengthResponse(Status.OK, MIME_HTML, index); - }else { - return newFixedLengthResponse(Status.NOT_FOUND, MIME_HTML, "Eaglercraft Desktop Runtime

404 Not Found

"); + } else { + return newFixedLengthResponse(Status.NOT_FOUND, MIME_HTML, + "Eaglercraft Desktop Runtime

404 Not Found

"); } } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewProtocol.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewProtocol.java index 8516510e..a4f8cb71 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewProtocol.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewProtocol.java @@ -14,93 +14,21 @@ import net.lax1dude.eaglercraft.v1_8.webview.PermissionsCache; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class FallbackWebViewProtocol { - static final Logger logger = FallbackWebViewServer.logger; - - private static final Map> packetIDToClass = new HashMap<>(); - private static final Map,Integer> packetClassToID = new HashMap<>(); - - private static final int CLIENT_TO_SERVER = 0; - private static final int SERVER_TO_CLIENT = 1; - - static { - register(0x00, CLIENT_TO_SERVER, CPacketClientHandshake.class); - register(0x01, SERVER_TO_CLIENT, SPacketServerHandshake.class); - register(0x02, SERVER_TO_CLIENT, SPacketServerError.class); - register(0x03, CLIENT_TO_SERVER, CPacketWebViewChannelOpen.class); - register(0x04, CLIENT_TO_SERVER, CPacketWebViewChannelClose.class); - register(0x05, CLIENT_TO_SERVER, CPacketWebViewMessage.class); - register(0x06, SERVER_TO_CLIENT, SPacketWebViewMessage.class); - register(0x07, CLIENT_TO_SERVER, CPacketWebViewJSPermission.class); - } - - private static void register(int id, int dir, Class packet) { - if(dir == CLIENT_TO_SERVER) { - packetIDToClass.put(id, packet); - }else if(dir == SERVER_TO_CLIENT) { - packetClassToID.put(packet, id); - }else { - throw new IllegalArgumentException(); - } - } - - static String writePacket(FallbackWebViewPacket packet) { - Class cls = packet.getClass(); - Integer id = packetClassToID.get(cls); - if(id == null) { - throw new RuntimeException("Tried to send unknown packet to client: " + cls.getSimpleName()); - } - JSONObject json = new JSONObject(); - json.put("$", id); - packet.writePacket(json); - return json.toString(); - } - - static FallbackWebViewPacket readPacket(String data) { - try { - JSONObject json = new JSONObject(data); - int id = json.getInt("$"); - Class cls = packetIDToClass.get(id); - if(cls == null) { - logger.error("Unknown packet ID {} recieved from webview controller", id); - return null; - } - FallbackWebViewPacket ret; - try { - ret = cls.newInstance(); - }catch(Throwable t) { - throw new RuntimeException("Failed to call packet constructor for \"" + cls.getSimpleName() + "\"! (is it defined?)"); - } - ret.readPacket(json); - return ret; - }catch(Throwable ex) { - logger.error("Failed to parse message from webview controller: \"{}\"", data); - logger.error(ex); - return null; - } - } - - static interface FallbackWebViewPacket { - - void readPacket(JSONObject json); - - void writePacket(JSONObject json); - - } - static class CPacketClientHandshake implements FallbackWebViewPacket { public boolean cspSupport; @@ -120,6 +48,23 @@ class FallbackWebViewProtocol { } + static class CPacketWebViewChannelClose implements FallbackWebViewPacket { + + public CPacketWebViewChannelClose() { + } + + @Override + public void readPacket(JSONObject json) { + + } + + @Override + public void writePacket(JSONObject json) { + throw new UnsupportedOperationException("Client only!"); + } + + } + static class CPacketWebViewChannelOpen implements FallbackWebViewPacket { public String messageChannel; @@ -134,7 +79,7 @@ class FallbackWebViewProtocol { @Override public void readPacket(JSONObject json) { messageChannel = json.getString("channel"); - if(messageChannel.length() > 255) { + if (messageChannel.length() > 255) { throw new JSONException("Channel name too long!"); } } @@ -146,14 +91,16 @@ class FallbackWebViewProtocol { } - static class CPacketWebViewChannelClose implements FallbackWebViewPacket { + static class CPacketWebViewJSPermission implements FallbackWebViewPacket { - public CPacketWebViewChannelClose() { + public EnumWebViewJSPermission permission; + + public CPacketWebViewJSPermission() { } @Override public void readPacket(JSONObject json) { - + permission = EnumWebViewJSPermission.valueOf(json.getString("perm")); } @Override @@ -187,6 +134,49 @@ class FallbackWebViewProtocol { } + static enum EnumWebViewJSPermission { + NOT_SET, ALLOW, BLOCK; + + static EnumWebViewJSPermission fromPermission(PermissionsCache.Permission perm) { + if (perm != null) { + return perm.choice ? ALLOW : BLOCK; + } else { + return NOT_SET; + } + } + } + + static interface FallbackWebViewPacket { + + void readPacket(JSONObject json); + + void writePacket(JSONObject json); + + } + + static class SPacketServerError implements FallbackWebViewPacket { + + public String errorMessage; + + public SPacketServerError() { + } + + public SPacketServerError(String errorMessage) { + this.errorMessage = errorMessage; + } + + @Override + public void readPacket(JSONObject json) { + throw new UnsupportedOperationException("Server only!"); + } + + @Override + public void writePacket(JSONObject json) { + json.put("msg", errorMessage); + } + + } + static class SPacketServerHandshake implements FallbackWebViewPacket { public WebViewOptions options; @@ -219,29 +209,6 @@ class FallbackWebViewProtocol { } - static class SPacketServerError implements FallbackWebViewPacket { - - public String errorMessage; - - public SPacketServerError() { - } - - public SPacketServerError(String errorMessage) { - this.errorMessage = errorMessage; - } - - @Override - public void readPacket(JSONObject json) { - throw new UnsupportedOperationException("Server only!"); - } - - @Override - public void writePacket(JSONObject json) { - json.put("msg", errorMessage); - } - - } - static class SPacketWebViewMessage implements FallbackWebViewPacket { public String message; @@ -265,35 +232,72 @@ class FallbackWebViewProtocol { } - static enum EnumWebViewJSPermission { - NOT_SET, ALLOW, BLOCK; + static final Logger logger = FallbackWebViewServer.logger; - static EnumWebViewJSPermission fromPermission(PermissionsCache.Permission perm) { - if(perm != null) { - return perm.choice ? ALLOW : BLOCK; - }else { - return NOT_SET; + private static final Map> packetIDToClass = new HashMap<>(); + + private static final Map, Integer> packetClassToID = new HashMap<>(); + + private static final int CLIENT_TO_SERVER = 0; + + private static final int SERVER_TO_CLIENT = 1; + + static { + register(0x00, CLIENT_TO_SERVER, CPacketClientHandshake.class); + register(0x01, SERVER_TO_CLIENT, SPacketServerHandshake.class); + register(0x02, SERVER_TO_CLIENT, SPacketServerError.class); + register(0x03, CLIENT_TO_SERVER, CPacketWebViewChannelOpen.class); + register(0x04, CLIENT_TO_SERVER, CPacketWebViewChannelClose.class); + register(0x05, CLIENT_TO_SERVER, CPacketWebViewMessage.class); + register(0x06, SERVER_TO_CLIENT, SPacketWebViewMessage.class); + register(0x07, CLIENT_TO_SERVER, CPacketWebViewJSPermission.class); + } + + static FallbackWebViewPacket readPacket(String data) { + try { + JSONObject json = new JSONObject(data); + int id = json.getInt("$"); + Class cls = packetIDToClass.get(id); + if (cls == null) { + logger.error("Unknown packet ID {} recieved from webview controller", id); + return null; } + FallbackWebViewPacket ret; + try { + ret = cls.newInstance(); + } catch (Throwable t) { + throw new RuntimeException( + "Failed to call packet constructor for \"" + cls.getSimpleName() + "\"! (is it defined?)"); + } + ret.readPacket(json); + return ret; + } catch (Throwable ex) { + logger.error("Failed to parse message from webview controller: \"{}\"", data); + logger.error(ex); + return null; } } - static class CPacketWebViewJSPermission implements FallbackWebViewPacket { - - public EnumWebViewJSPermission permission; - - public CPacketWebViewJSPermission() { + private static void register(int id, int dir, Class packet) { + if (dir == CLIENT_TO_SERVER) { + packetIDToClass.put(id, packet); + } else if (dir == SERVER_TO_CLIENT) { + packetClassToID.put(packet, id); + } else { + throw new IllegalArgumentException(); } + } - @Override - public void readPacket(JSONObject json) { - permission = EnumWebViewJSPermission.valueOf(json.getString("perm")); + static String writePacket(FallbackWebViewPacket packet) { + Class cls = packet.getClass(); + Integer id = packetClassToID.get(cls); + if (id == null) { + throw new RuntimeException("Tried to send unknown packet to client: " + cls.getSimpleName()); } - - @Override - public void writePacket(JSONObject json) { - throw new UnsupportedOperationException("Client only!"); - } - + JSONObject json = new JSONObject(); + json.put("$", id); + packet.writePacket(json); + return json.toString(); } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewServer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewServer.java index 79da7b11..50a1922b 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewServer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewServer.java @@ -22,14 +22,15 @@ import net.lax1dude.eaglercraft.v1_8.webview.WebViewOverlayController.IPacketSen /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,73 +57,25 @@ public class FallbackWebViewServer { this.options = options; } - public void start() throws RuntimeException { - dead = false; - StringBuilder vigg = new StringBuilder(); - try(BufferedReader reader = new BufferedReader( - new InputStreamReader(new FileInputStream(webViewClientHTML), StandardCharsets.UTF_8))) { - String line; - while((line = reader.readLine()) != null) { - vigg.append(line).append('\n'); - } - }catch(IOException ex) { - logger.error("Failed to read \"{}\"!"); - } - String indexHTML = vigg.toString(); - - Object mutex = new Object(); - websocketServer = new FallbackWebViewWSD(LISTEN_ADDR, randomPort(), options); - websocketServer.setEaglerPacketSendCallback(callback); - synchronized(mutex) { - websocketServer.doStartup(mutex); - try { - mutex.wait(5000l); - } catch (InterruptedException e) { - } - } - if(!websocketServer.hasStarted) { - logger.error("Failed to start WebSocket in time!"); - try { - websocketServer.stop(5000); - }catch(Throwable t) { - } - websocketServer = null; - throw new RuntimeException("Failed to start WebSocket server!"); - } - InetSocketAddress addr = websocketServer.getAddress(); - String wsAddr = "ws://" + addr.getHostString() + ":" + addr.getPort() + "/"; - logger.info("Listening for WebSocket on {}", wsAddr); - indexHTML = indexHTML.replace("${client_websocket_uri}", wsAddr); - - JSONObject optsExport = new JSONObject(); - IClientConfigAdapter cfgAdapter = PlatformRuntime.getClientConfigAdapter(); - optsExport.put("forceWebViewSupport", cfgAdapter.isForceWebViewSupport()); - optsExport.put("enableWebViewCSP", cfgAdapter.isEnableWebViewCSP()); - indexHTML = indexHTML.replace("{eaglercraftXOpts}", optsExport.toString()); - - httpServer = new FallbackWebViewHTTPD(LISTEN_ADDR, 0, indexHTML); - try { - httpServer.start(5000, true); - } catch (IOException e) { - logger.error("Failed to start NanoHTTPD!"); - try { - websocketServer.stop(5000); - }catch(Throwable t) { - } - websocketServer = null; - httpServer = null; - throw new RuntimeException("Failed to start NanoHTTPD!", e); - } - int httpPort = httpServer.getListeningPort(); - currentURL = "http://" + LISTEN_ADDR + ":" + httpPort + "/RTWebViewClient"; - logger.info("Listening for HTTP on {}", currentURL); + public String getURL() { + return !dead ? currentURL : null; } - private int randomPort() { - try(ServerSocket sockler = new ServerSocket(0)) { - return sockler.getLocalPort(); - }catch(IOException ex) { - throw new RuntimeException("Failed to find random port to bind to!", ex); + public void handleMessageFromServer(SPacketWebViewMessageV4EAG packet) { + if (packet.type == SPacketWebViewMessageV4EAG.TYPE_STRING) { + if (websocketServer != null) { + websocketServer.handleServerMessageStr(new String(packet.data, StandardCharsets.UTF_8)); + } else { + logger.error("Recieved string message, but the webview server is not running!"); + } + } else if (packet.type == SPacketWebViewMessageV4EAG.TYPE_BINARY) { + if (websocketServer != null) { + websocketServer.handleServerMessageBytes(packet.data); + } else { + logger.error("Recieved string message, but the webview server is not running!"); + } + } else { + logger.error("Unknown server webview message type {}", packet.type); } } @@ -130,43 +83,10 @@ public class FallbackWebViewServer { return dead; } - public String getURL() { - return !dead ? currentURL : null; - } - - public void handleMessageFromServer(SPacketWebViewMessageV4EAG packet) { - if(packet.type == SPacketWebViewMessageV4EAG.TYPE_STRING) { - if(websocketServer != null) { - websocketServer.handleServerMessageStr(new String(packet.data, StandardCharsets.UTF_8)); - }else { - logger.error("Recieved string message, but the webview server is not running!"); - } - }else if(packet.type == SPacketWebViewMessageV4EAG.TYPE_BINARY) { - if(websocketServer != null) { - websocketServer.handleServerMessageBytes(packet.data); - }else { - logger.error("Recieved string message, but the webview server is not running!"); - } - }else { - logger.error("Unknown server webview message type {}", packet.type); - } - } - - public void setPacketSendCallback(IPacketSendCallback callback) { - this.callback = callback; - if(websocketServer != null) { - websocketServer.setEaglerPacketSendCallback(callback); - } - } - - public void runTick() { - - } - public void killServer() { - if(!dead) { + if (!dead) { dead = true; - if(websocketServer != null) { + if (websocketServer != null) { try { websocketServer.stop(10000); } catch (Throwable th) { @@ -175,7 +95,7 @@ public class FallbackWebViewServer { } websocketServer = null; } - if(httpServer != null) { + if (httpServer != null) { try { httpServer.stop(); } catch (Throwable th) { @@ -187,4 +107,85 @@ public class FallbackWebViewServer { } } + private int randomPort() { + try (ServerSocket sockler = new ServerSocket(0)) { + return sockler.getLocalPort(); + } catch (IOException ex) { + throw new RuntimeException("Failed to find random port to bind to!", ex); + } + } + + public void runTick() { + + } + + public void setPacketSendCallback(IPacketSendCallback callback) { + this.callback = callback; + if (websocketServer != null) { + websocketServer.setEaglerPacketSendCallback(callback); + } + } + + public void start() throws RuntimeException { + dead = false; + StringBuilder vigg = new StringBuilder(); + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(new FileInputStream(webViewClientHTML), StandardCharsets.UTF_8))) { + String line; + while ((line = reader.readLine()) != null) { + vigg.append(line).append('\n'); + } + } catch (IOException ex) { + logger.error("Failed to read \"{}\"!"); + } + String indexHTML = vigg.toString(); + + Object mutex = new Object(); + websocketServer = new FallbackWebViewWSD(LISTEN_ADDR, randomPort(), options); + websocketServer.setEaglerPacketSendCallback(callback); + synchronized (mutex) { + websocketServer.doStartup(mutex); + try { + mutex.wait(5000l); + } catch (InterruptedException e) { + } + } + if (!websocketServer.hasStarted) { + logger.error("Failed to start WebSocket in time!"); + try { + websocketServer.stop(5000); + } catch (Throwable t) { + } + websocketServer = null; + throw new RuntimeException("Failed to start WebSocket server!"); + } + InetSocketAddress addr = websocketServer.getAddress(); + String wsAddr = "ws://" + addr.getHostString() + ":" + addr.getPort() + "/"; + logger.info("Listening for WebSocket on {}", wsAddr); + indexHTML = indexHTML.replace("${client_websocket_uri}", wsAddr); + + JSONObject optsExport = new JSONObject(); + IClientConfigAdapter cfgAdapter = PlatformRuntime.getClientConfigAdapter(); + optsExport.put("forceWebViewSupport", cfgAdapter.isForceWebViewSupport()); + optsExport.put("enableWebViewCSP", cfgAdapter.isEnableWebViewCSP()); + indexHTML = indexHTML.replace("{eaglercraftXOpts}", optsExport.toString()); + + httpServer = new FallbackWebViewHTTPD(LISTEN_ADDR, 0, indexHTML); + try { + httpServer.start(5000, true); + } catch (IOException e) { + logger.error("Failed to start NanoHTTPD!"); + try { + websocketServer.stop(5000); + } catch (Throwable t) { + } + websocketServer = null; + httpServer = null; + throw new RuntimeException("Failed to start NanoHTTPD!", e); + } + int httpPort = httpServer.getListeningPort(); + currentURL = "http://" + LISTEN_ADDR + ":" + httpPort + "/RTWebViewClient"; + logger.info("Listening for HTTP on {}", currentURL); + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewWSD.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewWSD.java index bb941103..ef326579 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewWSD.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FallbackWebViewWSD.java @@ -1,5 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.internal.lwjgl; +import static net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.readPacket; +import static net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.writePacket; + import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -9,6 +12,16 @@ import org.java_websocket.server.WebSocketServer; import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; import net.lax1dude.eaglercraft.v1_8.internal.WebViewOptions; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.CPacketClientHandshake; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.CPacketWebViewChannelClose; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.CPacketWebViewChannelOpen; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.CPacketWebViewJSPermission; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.CPacketWebViewMessage; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.EnumWebViewJSPermission; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.FallbackWebViewPacket; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.SPacketServerError; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.SPacketServerHandshake; +import net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.SPacketWebViewMessage; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketWebViewMessageEnV4EAG; @@ -17,19 +30,18 @@ import net.lax1dude.eaglercraft.v1_8.webview.PermissionsCache; import net.lax1dude.eaglercraft.v1_8.webview.PermissionsCache.Permission; import net.lax1dude.eaglercraft.v1_8.webview.WebViewOverlayController.IPacketSendCallback; -import static net.lax1dude.eaglercraft.v1_8.internal.lwjgl.FallbackWebViewProtocol.*; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -69,16 +81,115 @@ class FallbackWebViewWSD extends WebSocketServer { this.start(); } + private void handleClose() { + if (currentChannelName != null && callback != null) { + callback.sendPacket(new CPacketWebViewMessageEnV4EAG(false, null)); + } + currentChannelName = null; + } + + private void handleMessage(ByteBuffer buffer) { + if (currentChannelName != null) { + safeCallbackSend(new CPacketWebViewMessageV4EAG(buffer.array())); + } else { + terminate("Sent binary webview message while channel was closed"); + } + } + + private void handleMessage(String str) { + WebSocket ws = webSocket; + FallbackWebViewPacket _packet = readPacket(str); + if (_packet != null) { + if (!hasHandshake) { + if (_packet instanceof CPacketClientHandshake) { + hasHandshake = true; + Permission perm = PermissionsCache.getJavaScriptAllowed(options.permissionsOriginUUID, + hashPermissionFlags()); + ws.send(writePacket( + new SPacketServerHandshake(options, EnumWebViewJSPermission.fromPermission(perm)))); + } else { + terminate("Unknown or unexpected packet: " + _packet.getClass().getSimpleName()); + } + } else { + if (_packet instanceof CPacketWebViewChannelOpen) { + CPacketWebViewChannelOpen packet = (CPacketWebViewChannelOpen) _packet; + if (currentChannelName == null) { + currentChannelName = packet.messageChannel; + logger.info("[{}]: opened WebView channel \"{}\"", ws.getRemoteSocketAddress(), + packet.messageChannel); + safeCallbackSend(new CPacketWebViewMessageEnV4EAG(true, packet.messageChannel)); + } else { + terminate("Tried to open multiple channels"); + } + } else if (_packet instanceof CPacketWebViewMessage) { + CPacketWebViewMessage packet = (CPacketWebViewMessage) _packet; + if (currentChannelName != null) { + safeCallbackSend(new CPacketWebViewMessageV4EAG(packet.messageContent)); + } else { + terminate("Tried to send message without opening channel"); + } + } else if (_packet instanceof CPacketWebViewChannelClose) { + if (currentChannelName != null) { + currentChannelName = null; + safeCallbackSend(new CPacketWebViewMessageEnV4EAG(false, null)); + } else { + terminate("Tried to close missing channel"); + } + } else if (_packet instanceof CPacketWebViewJSPermission) { + CPacketWebViewJSPermission packet = (CPacketWebViewJSPermission) _packet; + switch (packet.permission) { + case NOT_SET: + PermissionsCache.clearJavaScriptAllowed(options.permissionsOriginUUID); + break; + case ALLOW: + PermissionsCache.setJavaScriptAllowed(options.permissionsOriginUUID, hashPermissionFlags(), + true); + break; + case BLOCK: + PermissionsCache.setJavaScriptAllowed(options.permissionsOriginUUID, hashPermissionFlags(), + false); + break; + default: + terminate("Unknown permission state selected!"); + break; + } + + } else { + terminate("Unknown or unexpected packet: " + _packet.getClass().getSimpleName()); + } + } + } else { + terminate("Invalid packet recieved"); + } + } + private void handleOpen() { hasHandshake = false; currentChannelName = null; } - private void handleClose() { - if(currentChannelName != null && callback != null) { - callback.sendPacket(new CPacketWebViewMessageEnV4EAG(false, null)); + void handleServerMessageBytes(byte[] msg) { + if (webSocket != null) { + if (currentChannelName != null) { + webSocket.send(msg); + } else { + logger.error("Recieved binary message from server, but the channel is not open!"); + } + } else { + logger.error("Recieved binary message from server, but there is no active websocket!"); + } + } + + void handleServerMessageStr(String msg) { + if (webSocket != null) { + if (currentChannelName != null) { + webSocket.send(writePacket(new SPacketWebViewMessage(msg))); + } else { + logger.error("Recieved string message from server, but the channel is not open!"); + } + } else { + logger.error("Recieved string message from server, but there is no active websocket!"); } - currentChannelName = null; } private int hashPermissionFlags() { @@ -88,172 +199,14 @@ class FallbackWebViewWSD extends WebSocketServer { return i; } - private void handleMessage(String str) { - WebSocket ws = webSocket; - FallbackWebViewPacket _packet = readPacket(str); - if(_packet != null) { - if(!hasHandshake) { - if(_packet instanceof CPacketClientHandshake) { - hasHandshake = true; - Permission perm = PermissionsCache.getJavaScriptAllowed(options.permissionsOriginUUID, hashPermissionFlags()); - ws.send(writePacket(new SPacketServerHandshake(options, EnumWebViewJSPermission.fromPermission(perm)))); - }else { - terminate("Unknown or unexpected packet: " + _packet.getClass().getSimpleName()); - } - }else { - if(_packet instanceof CPacketWebViewChannelOpen) { - CPacketWebViewChannelOpen packet = (CPacketWebViewChannelOpen)_packet; - if(currentChannelName == null) { - currentChannelName = packet.messageChannel; - logger.info("[{}]: opened WebView channel \"{}\"", ws.getRemoteSocketAddress(), packet.messageChannel); - safeCallbackSend(new CPacketWebViewMessageEnV4EAG(true, packet.messageChannel)); - }else { - terminate("Tried to open multiple channels"); - } - }else if(_packet instanceof CPacketWebViewMessage) { - CPacketWebViewMessage packet = (CPacketWebViewMessage)_packet; - if(currentChannelName != null) { - safeCallbackSend(new CPacketWebViewMessageV4EAG(packet.messageContent)); - }else { - terminate("Tried to send message without opening channel"); - } - }else if(_packet instanceof CPacketWebViewChannelClose) { - if(currentChannelName != null) { - currentChannelName = null; - safeCallbackSend(new CPacketWebViewMessageEnV4EAG(false, null)); - }else { - terminate("Tried to close missing channel"); - } - }else if(_packet instanceof CPacketWebViewJSPermission) { - CPacketWebViewJSPermission packet = (CPacketWebViewJSPermission)_packet; - switch(packet.permission) { - case NOT_SET: - PermissionsCache.clearJavaScriptAllowed(options.permissionsOriginUUID); - break; - case ALLOW: - PermissionsCache.setJavaScriptAllowed(options.permissionsOriginUUID, hashPermissionFlags(), true); - break; - case BLOCK: - PermissionsCache.setJavaScriptAllowed(options.permissionsOriginUUID, hashPermissionFlags(), false); - break; - default: - terminate("Unknown permission state selected!"); - break; - } - - }else { - terminate("Unknown or unexpected packet: " + _packet.getClass().getSimpleName()); - } - } - }else { - terminate("Invalid packet recieved"); - } - } - - private void handleMessage(ByteBuffer buffer) { - if(currentChannelName != null) { - safeCallbackSend(new CPacketWebViewMessageV4EAG(buffer.array())); - }else { - terminate("Sent binary webview message while channel was closed"); - } - } - - private void terminate(String msg) { - if(webSocket != null) { - logger.error("[{}]: Terminating connection, reason: \"{}\"", webSocket.getRemoteSocketAddress(), msg); - webSocket.send(writePacket(new SPacketServerError(msg))); - webSocket.close(); - } - } - - private void safeCallbackSend(GameMessagePacket packet) { - if(callback != null) { - callback.sendPacket(packet); - }else { - logger.error("webview sent packet to server, but there's no callback registered to send packets!"); - } - } - - void handleServerMessageStr(String msg) { - if(webSocket != null) { - if(currentChannelName != null) { - webSocket.send(writePacket(new SPacketWebViewMessage(msg))); - }else { - logger.error("Recieved string message from server, but the channel is not open!"); - } - }else { - logger.error("Recieved string message from server, but there is no active websocket!"); - } - } - - void handleServerMessageBytes(byte[] msg) { - if(webSocket != null) { - if(currentChannelName != null) { - webSocket.send(msg); - }else { - logger.error("Recieved binary message from server, but the channel is not open!"); - } - }else { - logger.error("Recieved binary message from server, but there is no active websocket!"); - } - } - - @Override - public void onStart() { - hasStarted = true; - if(onStartNotify != null) { - synchronized(onStartNotify) { - onStartNotify.notifyAll(); - } - onStartNotify = null; - }else { - logger.warn("No mutex to notify!"); - } - } - - @Override - public void onOpen(WebSocket arg0, ClientHandshake arg1) { - boolean result; - synchronized(webSockMutex) { - if(webSocket == null) { - webSocket = arg0; - result = true; - }else { - result = false; - } - } - if(result) { - logger.info("[{}]: WebSocket connection opened", arg0.getRemoteSocketAddress()); - handleOpen(); - }else { - logger.error("[{}]: Rejecting duplicate connection", arg0.getRemoteSocketAddress()); - arg0.send(writePacket(new SPacketServerError("You already have a tab open!"))); - arg0.close(); - } - } - - @Override - public void onMessage(WebSocket arg0, String arg1) { - if(arg0 == webSocket) { - handleMessage(arg1); - } - } - - @Override - public void onMessage(WebSocket arg0, ByteBuffer arg1) { - if(arg0 == webSocket) { - handleMessage(arg1); - } - } - @Override public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) { - synchronized(webSockMutex) { - if(arg0 == webSocket) { + synchronized (webSockMutex) { + if (arg0 == webSocket) { logger.info("[{}]: WebSocket connection closed", arg0.getRemoteSocketAddress()); try { handleClose(); - }finally { + } finally { webSocket = null; } } @@ -266,8 +219,72 @@ class FallbackWebViewWSD extends WebSocketServer { logger.error(arg1); } + @Override + public void onMessage(WebSocket arg0, ByteBuffer arg1) { + if (arg0 == webSocket) { + handleMessage(arg1); + } + } + + @Override + public void onMessage(WebSocket arg0, String arg1) { + if (arg0 == webSocket) { + handleMessage(arg1); + } + } + + @Override + public void onOpen(WebSocket arg0, ClientHandshake arg1) { + boolean result; + synchronized (webSockMutex) { + if (webSocket == null) { + webSocket = arg0; + result = true; + } else { + result = false; + } + } + if (result) { + logger.info("[{}]: WebSocket connection opened", arg0.getRemoteSocketAddress()); + handleOpen(); + } else { + logger.error("[{}]: Rejecting duplicate connection", arg0.getRemoteSocketAddress()); + arg0.send(writePacket(new SPacketServerError("You already have a tab open!"))); + arg0.close(); + } + } + + @Override + public void onStart() { + hasStarted = true; + if (onStartNotify != null) { + synchronized (onStartNotify) { + onStartNotify.notifyAll(); + } + onStartNotify = null; + } else { + logger.warn("No mutex to notify!"); + } + } + + private void safeCallbackSend(GameMessagePacket packet) { + if (callback != null) { + callback.sendPacket(packet); + } else { + logger.error("webview sent packet to server, but there's no callback registered to send packets!"); + } + } + public void setEaglerPacketSendCallback(IPacketSendCallback callback) { this.callback = callback; } + private void terminate(String msg) { + if (webSocket != null) { + logger.error("[{}]: Terminating connection, reason: \"{}\"", webSocket.getRemoteSocketAddress(), msg); + webSocket.send(writePacket(new SPacketServerError(msg))); + webSocket.close(); + } + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FilesystemConvertingDialog.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FilesystemConvertingDialog.java index 4b237278..a7dc6739 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FilesystemConvertingDialog.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/FilesystemConvertingDialog.java @@ -1,29 +1,30 @@ package net.lax1dude.eaglercraft.v1_8.internal.lwjgl; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; -import java.awt.Color; import java.awt.BorderLayout; -import javax.swing.JProgressBar; +import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; +import javax.swing.JFrame; import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JProgressBar; import javax.swing.SwingConstants; import javax.swing.UIManager; +import javax.swing.border.EmptyBorder; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,20 +48,20 @@ public class FilesystemConvertingDialog extends JFrame { setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); - + JPanel panel = new JPanel(); panel.setBorder(new EmptyBorder(10, 10, 10, 10)); panel.setBackground(new Color(255, 255, 255)); contentPane.add(panel, BorderLayout.SOUTH); panel.setLayout(new BorderLayout(0, 0)); - + progressBar = new JProgressBar(); progressBar.setIndeterminate(true); progressBar.setPreferredSize(new Dimension(146, 20)); progressBar.setMinimum(0); progressBar.setMaximum(512); panel.add(progressBar, BorderLayout.CENTER); - + JLabel lblNewLabel = new JLabel(title); lblNewLabel.setFont(UIManager.getFont("PopupMenu.font")); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystem.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystem.java index 34d5c71a..bf186d8d 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystem.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystem.java @@ -13,9 +13,9 @@ import java.util.LinkedList; import java.util.Map.Entry; import java.util.Properties; -import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IEaglerFilesystem; import net.lax1dude.eaglercraft.v1_8.internal.PlatformFilesystem; +import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; import net.lax1dude.eaglercraft.v1_8.internal.VFSFilenameIterator; import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; import net.lax1dude.eaglercraft.v1_8.internal.vfs2.EaglerFileSystemException; @@ -26,14 +26,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,29 +43,10 @@ public class JDBCFilesystem implements IEaglerFilesystem { public static final Logger logger = LogManager.getLogger("JDBCFilesystem"); - private boolean newFilesystem = true; - private static volatile boolean cleanupThreadStarted = false; + private static final Collection jdbcFilesystems = new LinkedList<>(); - private final String dbName; - private final String jdbcUri; - private final String jdbcDriver; - - private final Connection conn; - private final PreparedStatement createStatement; - private final PreparedStatement updateStatement; - private final PreparedStatement readStatement; - private final PreparedStatement existsStatement; - private final PreparedStatement sizeStatement; - private final PreparedStatement deleteStatement; - private final PreparedStatement renameStatement; - private final PreparedStatement iterateNonRecursive; - private final PreparedStatement iterateRecursive; - private boolean hasClosed = false; - - private final Object mutex = new Object(); - public static IEaglerFilesystem initialize(String dbName, String jdbcUri, String jdbcDriver) { Class driver; try { @@ -73,22 +55,24 @@ public class JDBCFilesystem implements IEaglerFilesystem { throw new EaglerFileSystemException("JDBC driver class not found in JRE: " + jdbcDriver, e); } Driver driverObj = null; - Enumeration registeredDriversItr = DriverManager.getDrivers(); - while(registeredDriversItr.hasMoreElements()) { + Enumeration registeredDriversItr = DriverManager.getDrivers(); + while (registeredDriversItr.hasMoreElements()) { Driver drv = registeredDriversItr.nextElement(); - if(drv.getClass().equals(driver)) { + if (drv.getClass().equals(driver)) { driverObj = drv; break; } } - if(driverObj == null) { - logger.warn("The class \"{}\" is not a registered JDBC driver, eaglercraft will try all registered drivers...", jdbcDriver); + if (driverObj == null) { + logger.warn( + "The class \"{}\" is not a registered JDBC driver, eaglercraft will try all registered drivers...", + jdbcDriver); } Properties props = new Properties(); - for(Entry etr : System.getProperties().entrySet()) { - if(etr.getKey() instanceof String) { - String str = (String)etr.getKey(); - if(str.startsWith("eagler.jdbc." + dbName + ".opts.")) { + for (Entry etr : System.getProperties().entrySet()) { + if (etr.getKey() instanceof String) { + String str = (String) etr.getKey(); + if (str.startsWith("eagler.jdbc." + dbName + ".opts.")) { props.put(str.substring(18 + dbName.length()), etr.getValue()); } } @@ -96,12 +80,12 @@ public class JDBCFilesystem implements IEaglerFilesystem { logger.info("Connecting to database: \"{}\"", jdbcUri); Connection conn; try { - if(driverObj != null) { + if (driverObj != null) { conn = driverObj.connect(jdbcUri, props); - }else { + } else { conn = DriverManager.getConnection(jdbcUri, props); } - }catch(SQLException ex) { + } catch (SQLException ex) { throw new EaglerFileSystemException("Failed to connect to database: \"" + jdbcUri + "\"", ex); } try { @@ -109,51 +93,334 @@ public class JDBCFilesystem implements IEaglerFilesystem { } catch (SQLException ex) { try { conn.close(); - }catch(SQLException ex2) { + } catch (SQLException ex2) { } throw new EaglerFileSystemException("Failed to initialize database: \"" + jdbcUri + "\"", ex); } } + private static void quietClose(Statement stmt) { + try { + stmt.close(); + } catch (Throwable t) { + } + } + + private static void startCleanupThread() { + if (!cleanupThreadStarted) { + cleanupThreadStarted = true; + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + synchronized (jdbcFilesystems) { + if (!jdbcFilesystems.isEmpty()) { + for (JDBCFilesystem fs : jdbcFilesystems) { + fs.shutdown0(); + } + jdbcFilesystems.clear(); + } + } + }, "JDBCFilesystemCleanup")); + } + } + + private boolean newFilesystem = true; + + private final String dbName; + private final String jdbcUri; + private final String jdbcDriver; + private final Connection conn; + private final PreparedStatement createStatement; + private final PreparedStatement updateStatement; + private final PreparedStatement readStatement; + private final PreparedStatement existsStatement; + private final PreparedStatement sizeStatement; + private final PreparedStatement deleteStatement; + private final PreparedStatement renameStatement; + + private final PreparedStatement iterateNonRecursive; + + private final PreparedStatement iterateRecursive; + + private boolean hasClosed = false; + + private final Object mutex = new Object(); + private JDBCFilesystem(String dbName, Connection conn, String jdbcUri, String jdbcDriver) throws SQLException { this.dbName = dbName; this.conn = conn; this.jdbcUri = jdbcUri; this.jdbcDriver = jdbcDriver; - try(Statement stmt = conn.createStatement()) { - stmt.execute("CREATE TABLE IF NOT EXISTS " - + "\"eaglercraft_desktop_runtime_filesystem\" (" - + "\"FileName\" VARCHAR(1024) NOT NULL," - + "\"FileSize\" INT NOT NULL," - + "\"FileData\" BLOB NOT NULL," - + "PRIMARY KEY(\"FileName\"))"); - + try (Statement stmt = conn.createStatement()) { + stmt.execute("CREATE TABLE IF NOT EXISTS " + "\"eaglercraft_desktop_runtime_filesystem\" (" + + "\"FileName\" VARCHAR(1024) NOT NULL," + "\"FileSize\" INT NOT NULL," + + "\"FileData\" BLOB NOT NULL," + "PRIMARY KEY(\"FileName\"))"); + int totalFiles = 0; - try(ResultSet resultSet = stmt.executeQuery("SELECT COUNT(*) AS total_files FROM eaglercraft_desktop_runtime_filesystem")) { - if(resultSet.next()) { + try (ResultSet resultSet = stmt + .executeQuery("SELECT COUNT(*) AS total_files FROM eaglercraft_desktop_runtime_filesystem")) { + if (resultSet.next()) { totalFiles = resultSet.getInt(1); } } logger.info("Loaded JDBC filesystem with {} files: \"{}\"", totalFiles, jdbcUri); - if(totalFiles > 0) { + if (totalFiles > 0) { newFilesystem = false; } } - this.createStatement = conn.prepareStatement("INSERT INTO eaglercraft_desktop_runtime_filesystem (FileName, FileSize, FileData) VALUES(?,?,?)"); - this.updateStatement = conn.prepareStatement("UPDATE eaglercraft_desktop_runtime_filesystem SET FileSize = ?, FileData = ? WHERE FileName = ?"); - this.readStatement = conn.prepareStatement("SELECT FileData FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ? LIMIT 1"); - this.existsStatement = conn.prepareStatement("SELECT COUNT(FileName) AS has_object FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ? LIMIT 1"); - this.sizeStatement = conn.prepareStatement("SELECT FileSize FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ? LIMIT 1"); - this.deleteStatement = conn.prepareStatement("DELETE FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ?"); - this.renameStatement = conn.prepareStatement("UPDATE eaglercraft_desktop_runtime_filesystem SET FileName = ? WHERE FileName = ?"); - this.iterateNonRecursive = conn.prepareStatement("SELECT FileName FROM eaglercraft_desktop_runtime_filesystem WHERE FileName LIKE ? AND NOT FileName LIKE ?"); - this.iterateRecursive = conn.prepareStatement("SELECT FileName FROM eaglercraft_desktop_runtime_filesystem WHERE FileName LIKE ?"); + this.createStatement = conn.prepareStatement( + "INSERT INTO eaglercraft_desktop_runtime_filesystem (FileName, FileSize, FileData) VALUES(?,?,?)"); + this.updateStatement = conn.prepareStatement( + "UPDATE eaglercraft_desktop_runtime_filesystem SET FileSize = ?, FileData = ? WHERE FileName = ?"); + this.readStatement = conn.prepareStatement( + "SELECT FileData FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ? LIMIT 1"); + this.existsStatement = conn.prepareStatement( + "SELECT COUNT(FileName) AS has_object FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ? LIMIT 1"); + this.sizeStatement = conn.prepareStatement( + "SELECT FileSize FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ? LIMIT 1"); + this.deleteStatement = conn + .prepareStatement("DELETE FROM eaglercraft_desktop_runtime_filesystem WHERE FileName = ?"); + this.renameStatement = conn + .prepareStatement("UPDATE eaglercraft_desktop_runtime_filesystem SET FileName = ? WHERE FileName = ?"); + this.iterateNonRecursive = conn.prepareStatement( + "SELECT FileName FROM eaglercraft_desktop_runtime_filesystem WHERE FileName LIKE ? AND NOT FileName LIKE ?"); + this.iterateRecursive = conn + .prepareStatement("SELECT FileName FROM eaglercraft_desktop_runtime_filesystem WHERE FileName LIKE ?"); startCleanupThread(); - synchronized(jdbcFilesystems) { + synchronized (jdbcFilesystems) { jdbcFilesystems.add(this); } } + @Override + public void closeHandle() { + shutdown0(); + synchronized (jdbcFilesystems) { + jdbcFilesystems.remove(this); + } + } + + @Override + public int eaglerCopy(String pathNameOld, String pathNameNew) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + readStatement.setString(1, pathNameOld); + try (ResultSet resultSet = readStatement.executeQuery()) { + byte[] has = null; + if (resultSet.next()) { + has = resultSet.getBytes(1); + } + if (has == null) { + return -1; + } + existsStatement.setString(1, pathNameNew); + boolean exists; + try (ResultSet resultSet2 = existsStatement.executeQuery()) { + if (resultSet2.next()) { + exists = resultSet2.getInt(1) > 0; + } else { + exists = false; + } + } + if (exists) { + updateStatement.setInt(1, has.length); + updateStatement.setBytes(2, has); + updateStatement.setString(3, pathNameNew); + if (updateStatement.executeUpdate() == 0) { + throw new EaglerFileSystemException("SQL file update query did not update any rows!"); + } + } else { + createStatement.setString(1, pathNameNew); + createStatement.setInt(2, has.length); + createStatement.setBytes(3, has); + createStatement.executeUpdate(); + } + return has.length; + } + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing copy!", ex); + } + } + + @Override + public boolean eaglerDelete(String pathName) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + deleteStatement.setString(1, pathName); + int ret = deleteStatement.executeUpdate(); + if (ret == 0) { + PlatformFilesystem.logger.warn("Tried to delete file that doesn't exist: \"{}\"", pathName); + } + return ret > 0; + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing delete!", ex); + } + } + + @Override + public boolean eaglerExists(String pathName) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + existsStatement.setString(1, pathName); + try (ResultSet resultSet = existsStatement.executeQuery()) { + if (resultSet.next()) { + return resultSet.getInt(1) > 0; + } else { + return false; + } + } + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing exists!", ex); + } + } + + @Override + public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + PreparedStatement stmt; + if (recursive) { + stmt = iterateRecursive; + stmt.setString(1, pathName + (!pathName.endsWith("/") ? "/%" : "%")); + ; + } else { + stmt = iterateNonRecursive; + if (!pathName.endsWith("/")) { + pathName += "/"; + } + stmt.setString(1, pathName + "%"); + stmt.setString(2, pathName + "%/%"); + } + try (ResultSet resultSet = stmt.executeQuery()) { + while (resultSet.next()) { + try { + itr.next(resultSet.getString(1)); + } catch (VFSIterator2.BreakLoop exx) { + break; + } + } + } + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing iterate!", ex); + } + } + + @Override + public boolean eaglerMove(String pathNameOld, String pathNameNew) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + renameStatement.setString(1, pathNameNew); + renameStatement.setString(2, pathNameOld); + return renameStatement.executeUpdate() > 0; + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing move!", ex); + } + } + + @Override + public ByteBuffer eaglerRead(String pathName) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + readStatement.setString(1, pathName); + byte[] has = null; + try (ResultSet resultSet = readStatement.executeQuery()) { + if (resultSet.next()) { + has = resultSet.getBytes(1); + } + } + if (has == null) { + PlatformFilesystem.logger.warn("Tried to read file that doesn't exist: \"{}\"", pathName); + return null; + } + ByteBuffer byteBuf = PlatformRuntime.allocateByteBuffer(has.length); + byteBuf.put(has); + byteBuf.flip(); + return byteBuf; + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing read!", ex); + } + } + + @Override + public int eaglerSize(String pathName) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + sizeStatement.setString(1, pathName); + try (ResultSet resultSet = sizeStatement.executeQuery()) { + if (resultSet.next()) { + return resultSet.getInt(1); + } else { + return -1; + } + } + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing size!", ex); + } + } + + @Override + public void eaglerWrite(String pathName, ByteBuffer data) { + try { + synchronized (mutex) { + if (hasClosed || conn.isClosed()) { + throw new SQLException("Filesystem database connection is closed!"); + } + existsStatement.setString(1, pathName); + boolean exists; + try (ResultSet resultSet = existsStatement.executeQuery()) { + if (resultSet.next()) { + exists = resultSet.getInt(1) > 0; + } else { + exists = false; + } + } + byte[] cp = new byte[data.remaining()]; + data.get(cp); + if (exists) { + updateStatement.setInt(1, cp.length); + updateStatement.setBytes(2, cp); + updateStatement.setString(3, pathName); + if (updateStatement.executeUpdate() == 0) { + throw new EaglerFileSystemException("SQL file update query did not update any rows!"); + } + } else { + createStatement.setString(1, pathName); + createStatement.setInt(2, cp.length); + createStatement.setBytes(3, cp); + createStatement.executeUpdate(); + } + } + } catch (SQLException ex) { + throw new EaglerFileSystemException("JDBC exception thrown while executing write!", ex); + } + } + @Override public String getFilesystemName() { return dbName; @@ -168,38 +435,19 @@ public class JDBCFilesystem implements IEaglerFilesystem { return newFilesystem; } - private static void startCleanupThread() { - if(!cleanupThreadStarted) { - cleanupThreadStarted = true; - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - synchronized(jdbcFilesystems) { - if(!jdbcFilesystems.isEmpty()) { - for(JDBCFilesystem fs : jdbcFilesystems) { - fs.shutdown0(); - } - jdbcFilesystems.clear(); - } - } - }, "JDBCFilesystemCleanup")); - } - } - @Override - public void closeHandle() { - shutdown0(); - synchronized(jdbcFilesystems) { - jdbcFilesystems.remove(this); - } + public boolean isRamdisk() { + return false; } private void shutdown0() { - synchronized(mutex) { - if(!hasClosed) { + synchronized (mutex) { + if (!hasClosed) { hasClosed = true; logger.info("Disconnecting from database: \"{}\"", jdbcUri); try { shutdown1(); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Failed to disconnect from database: \"{}\""); logger.error(t); } @@ -208,7 +456,7 @@ public class JDBCFilesystem implements IEaglerFilesystem { } private void shutdown1() throws SQLException { - if(!conn.isClosed()) { + if (!conn.isClosed()) { quietClose(createStatement); quietClose(updateStatement); quietClose(readStatement); @@ -222,238 +470,4 @@ public class JDBCFilesystem implements IEaglerFilesystem { } } - private static void quietClose(Statement stmt) { - try { - stmt.close(); - }catch(Throwable t) { - } - } - - @Override - public boolean eaglerDelete(String pathName) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - deleteStatement.setString(1, pathName); - int ret = deleteStatement.executeUpdate(); - if(ret == 0) { - PlatformFilesystem.logger.warn("Tried to delete file that doesn't exist: \"{}\"", pathName); - } - return ret > 0; - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing delete!", ex); - } - } - - @Override - public ByteBuffer eaglerRead(String pathName) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - readStatement.setString(1, pathName); - byte[] has = null; - try(ResultSet resultSet = readStatement.executeQuery()) { - if(resultSet.next()) { - has = resultSet.getBytes(1); - } - } - if(has == null) { - PlatformFilesystem.logger.warn("Tried to read file that doesn't exist: \"{}\"", pathName); - return null; - } - ByteBuffer byteBuf = PlatformRuntime.allocateByteBuffer(has.length); - byteBuf.put(has); - byteBuf.flip(); - return byteBuf; - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing read!", ex); - } - } - - @Override - public void eaglerWrite(String pathName, ByteBuffer data) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - existsStatement.setString(1, pathName); - boolean exists; - try(ResultSet resultSet = existsStatement.executeQuery()) { - if(resultSet.next()) { - exists = resultSet.getInt(1) > 0; - }else { - exists = false; - } - } - byte[] cp = new byte[data.remaining()]; - data.get(cp); - if(exists) { - updateStatement.setInt(1, cp.length); - updateStatement.setBytes(2, cp); - updateStatement.setString(3, pathName); - if(updateStatement.executeUpdate() == 0) { - throw new EaglerFileSystemException("SQL file update query did not update any rows!"); - } - }else { - createStatement.setString(1, pathName); - createStatement.setInt(2, cp.length); - createStatement.setBytes(3, cp); - createStatement.executeUpdate(); - } - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing write!", ex); - } - } - - @Override - public boolean eaglerExists(String pathName) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - existsStatement.setString(1, pathName); - try(ResultSet resultSet = existsStatement.executeQuery()) { - if(resultSet.next()) { - return resultSet.getInt(1) > 0; - }else { - return false; - } - } - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing exists!", ex); - } - } - - @Override - public boolean eaglerMove(String pathNameOld, String pathNameNew) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - renameStatement.setString(1, pathNameNew); - renameStatement.setString(2, pathNameOld); - return renameStatement.executeUpdate() > 0; - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing move!", ex); - } - } - - @Override - public int eaglerCopy(String pathNameOld, String pathNameNew) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - readStatement.setString(1, pathNameOld); - try(ResultSet resultSet = readStatement.executeQuery()) { - byte[] has = null; - if(resultSet.next()) { - has = resultSet.getBytes(1); - } - if(has == null) { - return -1; - } - existsStatement.setString(1, pathNameNew); - boolean exists; - try(ResultSet resultSet2 = existsStatement.executeQuery()) { - if(resultSet2.next()) { - exists = resultSet2.getInt(1) > 0; - }else { - exists = false; - } - } - if(exists) { - updateStatement.setInt(1, has.length); - updateStatement.setBytes(2, has); - updateStatement.setString(3, pathNameNew); - if(updateStatement.executeUpdate() == 0) { - throw new EaglerFileSystemException("SQL file update query did not update any rows!"); - } - }else { - createStatement.setString(1, pathNameNew); - createStatement.setInt(2, has.length); - createStatement.setBytes(3, has); - createStatement.executeUpdate(); - } - return has.length; - } - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing copy!", ex); - } - } - - @Override - public int eaglerSize(String pathName) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - sizeStatement.setString(1, pathName); - try(ResultSet resultSet = sizeStatement.executeQuery()) { - if(resultSet.next()) { - return resultSet.getInt(1); - }else { - return -1; - } - } - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing size!", ex); - } - } - - @Override - public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { - try { - synchronized(mutex) { - if(hasClosed || conn.isClosed()) { - throw new SQLException("Filesystem database connection is closed!"); - } - PreparedStatement stmt; - if(recursive) { - stmt = iterateRecursive; - stmt.setString(1, pathName + (!pathName.endsWith("/") ? "/%" : "%"));; - }else { - stmt = iterateNonRecursive; - if(!pathName.endsWith("/")) { - pathName += "/"; - } - stmt.setString(1, pathName + "%"); - stmt.setString(2, pathName + "%/%"); - } - try(ResultSet resultSet = stmt.executeQuery()) { - while(resultSet.next()) { - try { - itr.next(resultSet.getString(1)); - }catch(VFSIterator2.BreakLoop exx) { - break; - } - } - } - } - }catch(SQLException ex) { - throw new EaglerFileSystemException("JDBC exception thrown while executing iterate!", ex); - } - } - - @Override - public boolean isRamdisk() { - return false; - } - } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystemConverter.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystemConverter.java index eef8d922..e27a49a1 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystemConverter.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/JDBCFilesystemConverter.java @@ -17,14 +17,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,42 +40,42 @@ public class JDBCFilesystemConverter { progressDialog.setProgressIndeterminate(true); progressDialog.setLocationRelativeTo(null); progressDialog.setVisible(true); - + String slug = oldFS.getAbsolutePath(); List filesToCopy = new ArrayList<>(); logger.info("Discovering files to convert..."); iterateFolder(slug.length(), oldFS, filesToCopy); logger.info("Found {} files in the old directory", filesToCopy.size()); - + progressDialog.setProgressIndeterminate(false); progressDialog.setProgressValue(0); - + int progCounter = 0; int lastProgUpdate = 0; byte[] copyArray = new byte[4096]; - + int l = filesToCopy.size(); - for(int i = 0; i < l; ++i) { + for (int i = 0; i < l; ++i) { String str = filesToCopy.get(i); File f = new File(oldFS, str); - try(InputStream is = new FileInputStream(f)) { - ByteBuffer copyBuffer = PlatformRuntime.allocateByteBuffer((int)f.length()); + try (InputStream is = new FileInputStream(f)) { + ByteBuffer copyBuffer = PlatformRuntime.allocateByteBuffer((int) f.length()); try { int j; - while(copyBuffer.hasRemaining() && (j = is.read(copyArray, 0, copyArray.length)) != -1) { + while (copyBuffer.hasRemaining() && (j = is.read(copyArray, 0, copyArray.length)) != -1) { copyBuffer.put(copyArray, 0, j); } copyBuffer.flip(); progCounter += copyBuffer.remaining(); newFS.eaglerWrite(str, copyBuffer); - }finally { + } finally { PlatformRuntime.freeByteBuffer(copyBuffer); } - if(progCounter - lastProgUpdate > 25000) { + if (progCounter - lastProgUpdate > 25000) { lastProgUpdate = progCounter; logger.info("Converted {}/{} files, {} bytes to JDBC format...", (i + 1), l, progCounter); } - }catch(IOException ex) { + } catch (IOException ex) { throw new EaglerFileSystemException("Failed to convert file: \"" + f.getAbsolutePath() + "\"", ex); } progressDialog.setProgressValue(i * 512 / (l - 1)); @@ -82,32 +83,44 @@ public class JDBCFilesystemConverter { logger.info("Converted {}/{} files successfully!", l, l); - if(deleteOld) { + if (deleteOld) { logger.info("Deleting old filesystem..."); progressDialog.setProgressIndeterminate(true); deleteOldFolder(oldFS); logger.info("Delete complete!"); } - }finally { + } finally { progressDialog.setVisible(false); progressDialog.dispose(); } } + private static void deleteOldFolder(File file) { + File[] f = file.listFiles(); + for (int i = 0; i < f.length; ++i) { + if (f[i].isDirectory()) { + deleteOldFolder(f[i]); + } else { + f[i].delete(); + } + } + file.delete(); + } + private static void iterateFolder(int slug, File file, List ret) { File[] f = file.listFiles(); - if(f == null) { + if (f == null) { return; } - for(int i = 0; i < f.length; ++i) { + for (int i = 0; i < f.length; ++i) { File ff = f[i]; - if(ff.isDirectory()) { + if (ff.isDirectory()) { iterateFolder(slug, ff, ret); - }else { + } else { String str = ff.getAbsolutePath(); - if(str.length() > slug) { + if (str.length() > slug) { str = str.substring(slug).replace('\\', '/'); - if(str.startsWith("/")) { + if (str.startsWith("/")) { str = str.substring(1); } ret.add(str); @@ -115,16 +128,4 @@ public class JDBCFilesystemConverter { } } } - - private static void deleteOldFolder(File file) { - File[] f = file.listFiles(); - for(int i = 0; i < f.length; ++i) { - if(f[i].isDirectory()) { - deleteOldFolder(f[i]); - }else { - f[i].delete(); - } - } - file.delete(); - } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LWJGLEntryPoint.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LWJGLEntryPoint.java index 23b13589..ddc68042 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LWJGLEntryPoint.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LWJGLEntryPoint.java @@ -15,14 +15,15 @@ import net.minecraft.client.main.Main; /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,69 +32,69 @@ public class LWJGLEntryPoint { public static Thread mainThread = null; - public static void main_(String[] args) { - mainThread = Thread.currentThread(); - - try { - UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException - | UnsupportedLookAndFeelException e) { - System.err.println("Could not set system look and feel: " + e.toString()); - } - - boolean hideRenderDocDialog = false; - for(int i = 0; i < args.length; ++i) { - if(args[i].equalsIgnoreCase("hide-renderdoc")) { - hideRenderDocDialog = true; - } - } - - if(!hideRenderDocDialog) { - LaunchRenderDocDialog lr = new LaunchRenderDocDialog(); - lr.setLocationRelativeTo(null); - lr.setVisible(true); - - while(lr.isVisible()) { - EagUtils.sleep(100l); - } - - lr.dispose(); - } - - getPlatformOptionsFromArgs(args); - - RelayManager.relayManager.load(EagRuntime.getStorage("r")); - - if (RelayManager.relayManager.count() <= 0) { - RelayManager.relayManager.loadDefaults(); - RelayManager.relayManager.save(); - } - - EagRuntime.create(); - - Main.appMain(new String[0]); - - } - private static void getPlatformOptionsFromArgs(String[] args) { - for(int i = 0; i < args.length; ++i) { - if(args[i].equalsIgnoreCase("fullscreen")) { + for (int i = 0; i < args.length; ++i) { + if (args[i].equalsIgnoreCase("fullscreen")) { PlatformInput.setStartupFullscreen(true); - }else if(args[i].equalsIgnoreCase("highp")) { + } else if (args[i].equalsIgnoreCase("highp")) { ShaderSource.setHighP(true); - }else if(args[i].equalsIgnoreCase("gles=200")) { + } else if (args[i].equalsIgnoreCase("gles=200")) { PlatformRuntime.requestGL(200); - }else if(args[i].equalsIgnoreCase("gles=300")) { + } else if (args[i].equalsIgnoreCase("gles=300")) { PlatformRuntime.requestGL(300); - }else if(args[i].equalsIgnoreCase("gles=310")) { + } else if (args[i].equalsIgnoreCase("gles=310")) { PlatformRuntime.requestGL(310); - }else { + } else { EnumPlatformANGLE angle = EnumPlatformANGLE.fromId(args[i]); - if(angle != EnumPlatformANGLE.DEFAULT) { + if (angle != EnumPlatformANGLE.DEFAULT) { PlatformRuntime.requestANGLE(angle); } } } } + public static void main_(String[] args) { + mainThread = Thread.currentThread(); + + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException + | UnsupportedLookAndFeelException e) { + System.err.println("Could not set system look and feel: " + e.toString()); + } + + boolean hideRenderDocDialog = false; + for (int i = 0; i < args.length; ++i) { + if (args[i].equalsIgnoreCase("hide-renderdoc")) { + hideRenderDocDialog = true; + } + } + + if (!hideRenderDocDialog) { + LaunchRenderDocDialog lr = new LaunchRenderDocDialog(); + lr.setLocationRelativeTo(null); + lr.setVisible(true); + + while (lr.isVisible()) { + EagUtils.sleep(100l); + } + + lr.dispose(); + } + + getPlatformOptionsFromArgs(args); + + RelayManager.relayManager.load(EagRuntime.getStorage("r")); + + if (RelayManager.relayManager.count() <= 0) { + RelayManager.relayManager.loadDefaults(); + RelayManager.relayManager.save(); + } + + EagRuntime.create(); + + Main.appMain(new String[0]); + + } + } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LaunchRenderDocDialog.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LaunchRenderDocDialog.java index 65540b36..7d9f6427 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LaunchRenderDocDialog.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/LaunchRenderDocDialog.java @@ -2,44 +2,44 @@ package net.lax1dude.eaglercraft.v1_8.internal.lwjgl; import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.Toolkit; - -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; -import javax.swing.JLabel; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.lang.management.ManagementFactory; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; -import java.awt.Color; -import java.awt.Dimension; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; import javax.swing.JSeparator; +import javax.swing.border.EmptyBorder; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LaunchRenderDocDialog extends JDialog { - + private static final long serialVersionUID = 8312760039213612790L; - + private final JPanel contentPanel = new JPanel(); /** @@ -106,7 +106,7 @@ public class LaunchRenderDocDialog extends JDialog { buttonPane.add(cancelButton); } } - + JSeparator separator = new JSeparator(); getContentPane().add(separator, BorderLayout.NORTH); } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/MainMenuCreditsDialog.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/MainMenuCreditsDialog.java index 7c961902..29c6a95f 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/MainMenuCreditsDialog.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/MainMenuCreditsDialog.java @@ -1,26 +1,28 @@ package net.lax1dude.eaglercraft.v1_8.internal.lwjgl; -import javax.swing.JFrame; -import javax.swing.JPanel; import java.awt.BorderLayout; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.Toolkit; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,24 +47,24 @@ public class MainMenuCreditsDialog extends JFrame { setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); - + JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); contentPane.add(scrollPane, BorderLayout.CENTER); - + textArea = new JTextArea(); textArea.setEditable(false); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); Font daFont = null; - for(int i = 0; i < fonts.length; ++i) { - if(fonts[i].equalsIgnoreCase("consolas")) { + for (int i = 0; i < fonts.length; ++i) { + if (fonts[i].equalsIgnoreCase("consolas")) { daFont = new Font(fonts[i], Font.PLAIN, 15); break; } } - if(daFont == null) { + if (daFont == null) { daFont = new Font(Font.MONOSPACED, Font.PLAIN, 15); } textArea.setFont(daFont); diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/WebSocketClientImpl.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/WebSocketClientImpl.java index feed7751..3893706b 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/WebSocketClientImpl.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/lwjgl/WebSocketClientImpl.java @@ -14,14 +14,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.EnumEaglerConnectionState; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,7 +30,7 @@ import net.lax1dude.eaglercraft.v1_8.internal.EnumEaglerConnectionState; class WebSocketClientImpl extends WebSocketClient { private static final Draft perMessageDeflateDraft = new Draft_6455(new PerMessageDeflateExtension()); - + protected final DesktopWebSocketClient clientObj; WebSocketClientImpl(DesktopWebSocketClient clientObj, URI serverUri) { @@ -40,19 +41,10 @@ class WebSocketClientImpl extends WebSocketClient { this.connect(); } - @Override - public void onOpen(ServerHandshake arg0) { - clientObj.playConnectState = EnumEaglerConnectionState.CONNECTED; - DesktopWebSocketClient.logger.info("Connection opened: {}", this.uri.toString()); - synchronized(clientObj.connectOpenMutex) { - clientObj.connectOpenMutex.notifyAll(); - } - } - @Override public void onClose(int arg0, String arg1, boolean arg2) { DesktopWebSocketClient.logger.info("Connection closed: {}", this.uri.toString()); - if(clientObj.playConnectState != EnumEaglerConnectionState.FAILED) { + if (clientObj.playConnectState != EnumEaglerConnectionState.FAILED) { clientObj.playConnectState = EnumEaglerConnectionState.CLOSED; } } @@ -61,19 +53,28 @@ class WebSocketClientImpl extends WebSocketClient { public void onError(Exception arg0) { DesktopWebSocketClient.logger.error("Exception thrown by websocket \"" + this.getURI().toString() + "\"!"); DesktopWebSocketClient.logger.error(arg0); - if(clientObj.playConnectState == EnumEaglerConnectionState.CONNECTING) { + if (clientObj.playConnectState == EnumEaglerConnectionState.CONNECTING) { clientObj.playConnectState = EnumEaglerConnectionState.FAILED; } } + @Override + public void onMessage(ByteBuffer arg0) { + clientObj.handleBytes(arg0.array()); + } + @Override public void onMessage(String arg0) { clientObj.handleString(arg0); } @Override - public void onMessage(ByteBuffer arg0) { - clientObj.handleBytes(arg0.array()); + public void onOpen(ServerHandshake arg0) { + clientObj.playConnectState = EnumEaglerConnectionState.CONNECTED; + DesktopWebSocketClient.logger.info("Connection opened: {}", this.uri.toString()); + synchronized (clientObj.connectOpenMutex) { + clientObj.connectOpenMutex.notifyAll(); + } } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/ChannelLWJGLOpenAL.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/ChannelLWJGLOpenAL.java index 601b4e0b..96f8da9c 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/ChannelLWJGLOpenAL.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/ChannelLWJGLOpenAL.java @@ -3,6 +3,7 @@ package net.lax1dude.eaglercraft.v1_8.internal.paulscode.lwjgl3; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.LinkedList; + import javax.sound.sampled.AudioFormat; // From the lwjgl library, http://www.lwjgl.org @@ -109,6 +110,83 @@ public class ChannelLWJGLOpenAL extends Channel { ALSource = src; } + /** + * Attaches an OpenAL sound-buffer identifier for the sound data to be played + * back for a normal source. + * + * @param buf Intbuffer identifier for the sound data to play. + * @return False if an error occurred. + */ + public boolean attachBuffer(IntBuffer buf) { + // A sound buffer can only be attached to a normal source: + if (errorCheck(channelType != SoundSystemConfig.TYPE_NORMAL, + "Sound buffers may only be attached to normal " + "sources.")) + return false; + + // send the sound buffer to the channel: + AL10.alSourcei(ALSource.get(0), AL10.AL_BUFFER, buf.get(0)); + + // save the format for later, for determining milliseconds played + if (attachedSource != null && attachedSource.soundBuffer != null + && attachedSource.soundBuffer.audioFormat != null) + setAudioFormat(attachedSource.soundBuffer.audioFormat); + + // Check for errors and return: + return checkALError(); + } + + /** + * Returns the number of queued byte[] buffers that have finished playing. + * + * @return Number of buffers processed. + */ + @Override + public int buffersProcessed() { + // Only streaming sources process buffers: + if (channelType != SoundSystemConfig.TYPE_STREAMING) + return 0; + + // determine how many have been processed: + int processed = AL10.alGetSourcei(ALSource.get(0), AL10.AL_BUFFERS_PROCESSED); + + // Check for errors: + if (checkALError()) + return 0; + + // Return how many were processed: + return processed; + } + + /** + * Checks for OpenAL errors, and prints a message if there is an error. + * + * @return True if there was an error, False if not. + */ + private boolean checkALError() { + switch (AL10.alGetError()) { + case AL10.AL_NO_ERROR: + return false; + case AL10.AL_INVALID_NAME: + errorMessage("Invalid name parameter."); + return true; + case AL10.AL_INVALID_ENUM: + errorMessage("Invalid parameter."); + return true; + case AL10.AL_INVALID_VALUE: + errorMessage("Invalid enumerated parameter value."); + return true; + case AL10.AL_INVALID_OPERATION: + errorMessage("Illegal call."); + return true; + case AL10.AL_OUT_OF_MEMORY: + errorMessage("Unable to allocate memory."); + return true; + default: + errorMessage("An unrecognized error occurred."); + return true; + } + } + /** * Empties the streamBuffers list, stops and deletes the ALSource, shuts the * channel down, and removes references to all instantiated objects. @@ -136,74 +214,196 @@ public class ChannelLWJGLOpenAL extends Channel { } /** - * Attaches an OpenAL sound-buffer identifier for the sound data to be played - * back for a normal source. - * - * @param buf Intbuffer identifier for the sound data to play. - * @return False if an error occurred. - */ - public boolean attachBuffer(IntBuffer buf) { - // A sound buffer can only be attached to a normal source: - if (errorCheck(channelType != SoundSystemConfig.TYPE_NORMAL, - "Sound buffers may only be attached to normal " + "sources.")) - return false; - - // send the sound buffer to the channel: - AL10.alSourcei(ALSource.get(0), AL10.AL_BUFFER, buf.get(0)); - - // save the format for later, for determining milliseconds played - if (attachedSource != null && attachedSource.soundBuffer != null - && attachedSource.soundBuffer.audioFormat != null) - setAudioFormat(attachedSource.soundBuffer.audioFormat); - - // Check for errors and return: - return checkALError(); - } - - /** - * Sets the channel up to receive the specified audio format. - * - * @param audioFormat Format to use when playing the stream data. + * Stops the channel, dequeues any queued data, and closes the channel. */ @Override - public void setAudioFormat(AudioFormat audioFormat) { - int soundFormat = 0; - if (audioFormat.getChannels() == 1) { - if (audioFormat.getSampleSizeInBits() == 8) { - soundFormat = AL10.AL_FORMAT_MONO8; - } else if (audioFormat.getSampleSizeInBits() == 16) { - soundFormat = AL10.AL_FORMAT_MONO16; - } else { - errorMessage("Illegal sample size in method " + "'setAudioFormat'"); - return; - } - } else if (audioFormat.getChannels() == 2) { - if (audioFormat.getSampleSizeInBits() == 8) { - soundFormat = AL10.AL_FORMAT_STEREO8; - } else if (audioFormat.getSampleSizeInBits() == 16) { - soundFormat = AL10.AL_FORMAT_STEREO16; - } else { - errorMessage("Illegal sample size in method " + "'setAudioFormat'"); - return; - } - } else { - errorMessage("Audio data neither mono nor stereo in " + "method 'setAudioFormat'"); - return; + public void close() { + try { + AL10.alSourceStop(ALSource.get(0)); + AL10.alGetError(); + } catch (Exception e) { } - ALformat = soundFormat; - sampleRate = (int) audioFormat.getSampleRate(); + + if (channelType == SoundSystemConfig.TYPE_STREAMING) + flush(); } /** - * Sets the channel up to receive the specified OpenAL audio format and sample - * rate. + * Feeds raw data to the stream. * - * @param format Format to use. - * @param rate Sample rate (speed) to use. + * @param buffer Buffer containing raw audio data to stream. + * @return Number of prior buffers that have been processed., or -1 if error. */ - public void setFormat(int format, int rate) { - ALformat = format; - sampleRate = rate; + @Override + public int feedRawAudioData(byte[] buffer) { + // Stream buffers can only be queued for streaming sources: + if (errorCheck(channelType != SoundSystemConfig.TYPE_STREAMING, + "Raw audio data can only be fed to streaming sources.")) + return -1; + + // ByteBuffer byteBuffer = ByteBuffer.wrap( buffer, 0, buffer.length ); + ByteBuffer byteBuffer = (ByteBuffer) BufferUtils.createByteBuffer(buffer.length).put(buffer).flip(); + + IntBuffer intBuffer; + + // Clear out any previously queued buffers: + int processed = AL10.alGetSourcei(ALSource.get(0), AL10.AL_BUFFERS_PROCESSED); + if (processed > 0) { + intBuffer = BufferUtils.createIntBuffer(processed); + AL10.alGenBuffers(intBuffer); + if (errorCheck(checkALError(), "Error clearing stream buffers in method 'feedRawAudioData'")) + return -1; + AL10.alSourceUnqueueBuffers(ALSource.get(0), intBuffer); + if (errorCheck(checkALError(), "Error unqueuing stream buffers in method 'feedRawAudioData'")) + return -1; + int i; + intBuffer.rewind(); + while (intBuffer.hasRemaining()) { + i = intBuffer.get(); + if (AL10.alIsBuffer(i)) { + millisPreviouslyPlayed += millisInBuffer(i); + } + checkALError(); + } + AL10.alDeleteBuffers(intBuffer); + checkALError(); + } + intBuffer = BufferUtils.createIntBuffer(1); + AL10.alGenBuffers(intBuffer); + if (errorCheck(checkALError(), "Error generating stream buffers in method 'preLoadBuffers'")) + return -1; + + AL10.alBufferData(intBuffer.get(0), ALformat, byteBuffer, sampleRate); + if (checkALError()) + return -1; + + AL10.alSourceQueueBuffers(ALSource.get(0), intBuffer); + if (checkALError()) + return -1; + + if (attachedSource != null && attachedSource.channel == this && attachedSource.active()) { + // restart the channel if it was previously playing: + if (!playing()) { + AL10.alSourcePlay(ALSource.get(0)); + checkALError(); + } + } + + return processed; + } + + /** + * Dequeues all previously queued data. + */ + @Override + public void flush() { + // Only a streaming source can be flushed, because only streaming + // sources have queued buffers: + if (channelType != SoundSystemConfig.TYPE_STREAMING) + return; + + // determine how many buffers have been queued: + int queued = AL10.alGetSourcei(ALSource.get(0), AL10.AL_BUFFERS_QUEUED); + // Check for errors: + if (checkALError()) + return; + + IntBuffer intBuffer = BufferUtils.createIntBuffer(1); + while (queued > 0) { + try { + AL10.alSourceUnqueueBuffers(ALSource.get(0), intBuffer); + } catch (Exception e) { + return; + } + if (checkALError()) + return; + queued--; + } + millisPreviouslyPlayed = 0; + } + + /** + * Calculates the number of milliseconds since the channel began playing. + * + * @return Milliseconds, or -1 if unable to calculate. + */ + @Override + public float millisecondsPlayed() { + // get number of samples played in current buffer + float offset = (float) AL10.alGetSourcei(ALSource.get(0), AL11.AL_BYTE_OFFSET); + + float bytesPerFrame = 1f; + switch (ALformat) { + case AL10.AL_FORMAT_MONO8: + bytesPerFrame = 1f; + break; + case AL10.AL_FORMAT_MONO16: + bytesPerFrame = 2f; + break; + case AL10.AL_FORMAT_STEREO8: + bytesPerFrame = 2f; + break; + case AL10.AL_FORMAT_STEREO16: + bytesPerFrame = 4f; + break; + default: + break; + } + + offset = (((float) offset / bytesPerFrame) / (float) sampleRate) * 1000; + + // add the milliseconds from stream-buffers that played previously + if (channelType == SoundSystemConfig.TYPE_STREAMING) + offset += millisPreviouslyPlayed; + + // Return millis played: + return (offset); + } + + /** + * Returns the number of milliseconds of audio contained in specified buffer. + * + * @return milliseconds, or 0 if unable to calculate. + */ + public float millisInBuffer(int alBufferi) { + return (((float) AL10.alGetBufferi(alBufferi, AL10.AL_SIZE) + / (float) AL10.alGetBufferi(alBufferi, AL10.AL_CHANNELS) + / ((float) AL10.alGetBufferi(alBufferi, AL10.AL_BITS) / 8.0f) / (float) sampleRate) * 1000); + } + + /** + * Temporarily stops playback for this channel. + */ + @Override + public void pause() { + AL10.alSourcePause(ALSource.get(0)); + checkALError(); + } + + /** + * Plays the currently attached normal source, opens this channel up for + * streaming, or resumes playback if this channel was paused. + */ + @Override + public void play() { + AL10.alSourcePlay(ALSource.get(0)); + checkALError(); + } + + /** + * Used to determine if a channel is actively playing a source. This method will + * return false if the channel is paused or stopped and when no data is queued + * to be streamed. + * + * @return True if this channel is playing a source. + */ + @Override + public boolean playing() { + int state = AL10.alGetSourcei(ALSource.get(0), AL10.AL_SOURCE_STATE); + if (checkALError()) + return false; + + return (state == AL10.AL_PLAYING); } /** @@ -329,216 +529,6 @@ public class ChannelLWJGLOpenAL extends Channel { return true; } - /** - * Feeds raw data to the stream. - * - * @param buffer Buffer containing raw audio data to stream. - * @return Number of prior buffers that have been processed., or -1 if error. - */ - @Override - public int feedRawAudioData(byte[] buffer) { - // Stream buffers can only be queued for streaming sources: - if (errorCheck(channelType != SoundSystemConfig.TYPE_STREAMING, - "Raw audio data can only be fed to streaming sources.")) - return -1; - - // ByteBuffer byteBuffer = ByteBuffer.wrap( buffer, 0, buffer.length ); - ByteBuffer byteBuffer = (ByteBuffer) BufferUtils.createByteBuffer(buffer.length).put(buffer).flip(); - - IntBuffer intBuffer; - - // Clear out any previously queued buffers: - int processed = AL10.alGetSourcei(ALSource.get(0), AL10.AL_BUFFERS_PROCESSED); - if (processed > 0) { - intBuffer = BufferUtils.createIntBuffer(processed); - AL10.alGenBuffers(intBuffer); - if (errorCheck(checkALError(), "Error clearing stream buffers in method 'feedRawAudioData'")) - return -1; - AL10.alSourceUnqueueBuffers(ALSource.get(0), intBuffer); - if (errorCheck(checkALError(), "Error unqueuing stream buffers in method 'feedRawAudioData'")) - return -1; - int i; - intBuffer.rewind(); - while (intBuffer.hasRemaining()) { - i = intBuffer.get(); - if (AL10.alIsBuffer(i)) { - millisPreviouslyPlayed += millisInBuffer(i); - } - checkALError(); - } - AL10.alDeleteBuffers(intBuffer); - checkALError(); - } - intBuffer = BufferUtils.createIntBuffer(1); - AL10.alGenBuffers(intBuffer); - if (errorCheck(checkALError(), "Error generating stream buffers in method 'preLoadBuffers'")) - return -1; - - AL10.alBufferData(intBuffer.get(0), ALformat, byteBuffer, sampleRate); - if (checkALError()) - return -1; - - AL10.alSourceQueueBuffers(ALSource.get(0), intBuffer); - if (checkALError()) - return -1; - - if (attachedSource != null && attachedSource.channel == this && attachedSource.active()) { - // restart the channel if it was previously playing: - if (!playing()) { - AL10.alSourcePlay(ALSource.get(0)); - checkALError(); - } - } - - return processed; - } - - /** - * Returns the number of milliseconds of audio contained in specified buffer. - * - * @return milliseconds, or 0 if unable to calculate. - */ - public float millisInBuffer(int alBufferi) { - return (((float) AL10.alGetBufferi(alBufferi, AL10.AL_SIZE) - / (float) AL10.alGetBufferi(alBufferi, AL10.AL_CHANNELS) - / ((float) AL10.alGetBufferi(alBufferi, AL10.AL_BITS) / 8.0f) / (float) sampleRate) * 1000); - } - - /** - * Calculates the number of milliseconds since the channel began playing. - * - * @return Milliseconds, or -1 if unable to calculate. - */ - @Override - public float millisecondsPlayed() { - // get number of samples played in current buffer - float offset = (float) AL10.alGetSourcei(ALSource.get(0), AL11.AL_BYTE_OFFSET); - - float bytesPerFrame = 1f; - switch (ALformat) { - case AL10.AL_FORMAT_MONO8: - bytesPerFrame = 1f; - break; - case AL10.AL_FORMAT_MONO16: - bytesPerFrame = 2f; - break; - case AL10.AL_FORMAT_STEREO8: - bytesPerFrame = 2f; - break; - case AL10.AL_FORMAT_STEREO16: - bytesPerFrame = 4f; - break; - default: - break; - } - - offset = (((float) offset / bytesPerFrame) / (float) sampleRate) * 1000; - - // add the milliseconds from stream-buffers that played previously - if (channelType == SoundSystemConfig.TYPE_STREAMING) - offset += millisPreviouslyPlayed; - - // Return millis played: - return (offset); - } - - /** - * Returns the number of queued byte[] buffers that have finished playing. - * - * @return Number of buffers processed. - */ - @Override - public int buffersProcessed() { - // Only streaming sources process buffers: - if (channelType != SoundSystemConfig.TYPE_STREAMING) - return 0; - - // determine how many have been processed: - int processed = AL10.alGetSourcei(ALSource.get(0), AL10.AL_BUFFERS_PROCESSED); - - // Check for errors: - if (checkALError()) - return 0; - - // Return how many were processed: - return processed; - } - - /** - * Dequeues all previously queued data. - */ - @Override - public void flush() { - // Only a streaming source can be flushed, because only streaming - // sources have queued buffers: - if (channelType != SoundSystemConfig.TYPE_STREAMING) - return; - - // determine how many buffers have been queued: - int queued = AL10.alGetSourcei(ALSource.get(0), AL10.AL_BUFFERS_QUEUED); - // Check for errors: - if (checkALError()) - return; - - IntBuffer intBuffer = BufferUtils.createIntBuffer(1); - while (queued > 0) { - try { - AL10.alSourceUnqueueBuffers(ALSource.get(0), intBuffer); - } catch (Exception e) { - return; - } - if (checkALError()) - return; - queued--; - } - millisPreviouslyPlayed = 0; - } - - /** - * Stops the channel, dequeues any queued data, and closes the channel. - */ - @Override - public void close() { - try { - AL10.alSourceStop(ALSource.get(0)); - AL10.alGetError(); - } catch (Exception e) { - } - - if (channelType == SoundSystemConfig.TYPE_STREAMING) - flush(); - } - - /** - * Plays the currently attached normal source, opens this channel up for - * streaming, or resumes playback if this channel was paused. - */ - @Override - public void play() { - AL10.alSourcePlay(ALSource.get(0)); - checkALError(); - } - - /** - * Temporarily stops playback for this channel. - */ - @Override - public void pause() { - AL10.alSourcePause(ALSource.get(0)); - checkALError(); - } - - /** - * Stops playback for this channel and rewinds the attached source to the - * beginning. - */ - @Override - public void stop() { - AL10.alSourceStop(ALSource.get(0)); - if (!checkALError()) - millisPreviouslyPlayed = 0; - } - /** * Rewinds the attached source to the beginning. Stops the source if it was * paused. @@ -555,48 +545,59 @@ public class ChannelLWJGLOpenAL extends Channel { } /** - * Used to determine if a channel is actively playing a source. This method will - * return false if the channel is paused or stopped and when no data is queued - * to be streamed. + * Sets the channel up to receive the specified audio format. * - * @return True if this channel is playing a source. + * @param audioFormat Format to use when playing the stream data. */ @Override - public boolean playing() { - int state = AL10.alGetSourcei(ALSource.get(0), AL10.AL_SOURCE_STATE); - if (checkALError()) - return false; - - return (state == AL10.AL_PLAYING); + public void setAudioFormat(AudioFormat audioFormat) { + int soundFormat = 0; + if (audioFormat.getChannels() == 1) { + if (audioFormat.getSampleSizeInBits() == 8) { + soundFormat = AL10.AL_FORMAT_MONO8; + } else if (audioFormat.getSampleSizeInBits() == 16) { + soundFormat = AL10.AL_FORMAT_MONO16; + } else { + errorMessage("Illegal sample size in method " + "'setAudioFormat'"); + return; + } + } else if (audioFormat.getChannels() == 2) { + if (audioFormat.getSampleSizeInBits() == 8) { + soundFormat = AL10.AL_FORMAT_STEREO8; + } else if (audioFormat.getSampleSizeInBits() == 16) { + soundFormat = AL10.AL_FORMAT_STEREO16; + } else { + errorMessage("Illegal sample size in method " + "'setAudioFormat'"); + return; + } + } else { + errorMessage("Audio data neither mono nor stereo in " + "method 'setAudioFormat'"); + return; + } + ALformat = soundFormat; + sampleRate = (int) audioFormat.getSampleRate(); } /** - * Checks for OpenAL errors, and prints a message if there is an error. + * Sets the channel up to receive the specified OpenAL audio format and sample + * rate. * - * @return True if there was an error, False if not. + * @param format Format to use. + * @param rate Sample rate (speed) to use. */ - private boolean checkALError() { - switch (AL10.alGetError()) { - case AL10.AL_NO_ERROR: - return false; - case AL10.AL_INVALID_NAME: - errorMessage("Invalid name parameter."); - return true; - case AL10.AL_INVALID_ENUM: - errorMessage("Invalid parameter."); - return true; - case AL10.AL_INVALID_VALUE: - errorMessage("Invalid enumerated parameter value."); - return true; - case AL10.AL_INVALID_OPERATION: - errorMessage("Illegal call."); - return true; - case AL10.AL_OUT_OF_MEMORY: - errorMessage("Unable to allocate memory."); - return true; - default: - errorMessage("An unrecognized error occurred."); - return true; - } + public void setFormat(int format, int rate) { + ALformat = format; + sampleRate = rate; + } + + /** + * Stops playback for this channel and rewinds the attached source to the + * beginning. + */ + @Override + public void stop() { + AL10.alSourceStop(ALSource.get(0)); + if (!checkALError()) + millisPreviouslyPlayed = 0; } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/LibraryLWJGLOpenAL.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/LibraryLWJGLOpenAL.java index 42a58b2a..48a5b86a 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/LibraryLWJGLOpenAL.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/LibraryLWJGLOpenAL.java @@ -1,12 +1,13 @@ package net.lax1dude.eaglercraft.v1_8.internal.paulscode.lwjgl3; -import java.nio.ByteBuffer; -import java.nio.IntBuffer; -import java.nio.FloatBuffer; import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.FloatBuffer; +import java.nio.IntBuffer; import java.util.HashMap; import java.util.Iterator; import java.util.Set; + import javax.sound.sampled.AudioFormat; import org.lwjgl.BufferUtils; @@ -88,6 +89,68 @@ import paulscode.sound.Source; * http://www.paulscode.com */ public class LibraryLWJGLOpenAL extends Library { + /** + * The LibraryLWJGLOpenAL.Exception class provides library-specific error + * information. + */ + public static class Exception extends SoundSystemException { + private static final long serialVersionUID = -7502452059037798035L; + /** + * Global identifier for an exception during AL.create(). Probably means that + * OpenAL is not supported. + */ + public static final int CREATE = 101; + /** + * Global identifier for an invalid name parameter in OpenAL. + */ + public static final int INVALID_NAME = 102; + /** + * Global identifier for an invalid parameter in OpenAL. + */ + public static final int INVALID_ENUM = 103; + /** + * Global identifier for an invalid enumerated parameter value in OpenAL. + */ + public static final int INVALID_VALUE = 104; + /** + * Global identifier for an illegal call in OpenAL. + */ + public static final int INVALID_OPERATION = 105; + /** + * Global identifier for OpenAL out of memory. + */ + public static final int OUT_OF_MEMORY = 106; + /** + * Global identifier for an exception while creating the OpenAL Listener. + */ + public static final int LISTENER = 107; + /** + * Global identifier for OpenAL AL_PITCH not supported. + */ + public static final int NO_AL_PITCH = 108; + + /** + * Constructor: Generates a standard "unknown error" exception with the + * specified message. + * + * @param message A brief description of the problem that occurred. + */ + public Exception(String message) { + super(message); + } + + /** + * Constructor: Generates an exception of the specified type, with the specified + * message. + * + * @param message A brief description of the problem that occurred. + * @param type Identifier indicating they type of error. + */ + public Exception(String message, int type) { + super(message, type); + } + } + /** * Used to return a current value from one of the synchronized boolean-interface * methods. @@ -97,33 +160,90 @@ public class LibraryLWJGLOpenAL extends Library { * Used to set the value in one of the synchronized boolean-interface methods. */ private static final boolean SET = true; + /** * Used when a parameter for one of the synchronized boolean-interface methods * is not aplicable. */ private static final boolean XXX = false; + /** + * Whether or not the AL_PITCH control is supported. + */ + private static boolean alPitchSupported = true; + private static final Logger logger = LogManager.getLogger("SoundSystem"); + + /** + * Whether or not the AL_PITCH control is supported. + * + * @return True if AL_PITCH is supported. + */ + public static boolean alPitchSupported() { + return alPitchSupported(GET, XXX); + } + + /** + * Sets or returns the value of boolean 'alPitchSupported'. + * + * @param action Action to perform (GET or SET). + * @param value New value if action is SET, otherwise XXX. + * @return value of boolean 'alPitchSupported'. + */ + private static synchronized boolean alPitchSupported(boolean action, boolean value) { + if (action == SET) + alPitchSupported = value; + return alPitchSupported; + } + + /** + * Returns a longer description of this library type. + * + * @return A longer description. + */ + public static String getDescription() { + return "The Eaglercraft LWJGL3 binding of OpenAL"; + } + + /** + * Returns the short title of this library type. + * + * @return A short title. + */ + public static String getTitle() { + return "LWJGL OpenAL (Eaglercraft)"; + } + + /** + * Checks if the OpenAL library type is compatible. + * + * @return True or false. + */ + public static boolean libraryCompatible() { + return true; + } /** * Position of the listener in 3D space. */ private FloatBuffer listenerPositionAL = null; + /** * Information about the listener's orientation. */ private FloatBuffer listenerOrientation = null; + /** * Velocity of the listener. */ private FloatBuffer listenerVelocity = null; + /** * Map containing OpenAL identifiers for sound buffers. */ private HashMap ALBufferMap = null; - /** - * Whether or not the AL_PITCH control is supported. - */ - private static boolean alPitchSupported = true; + private long openALDevice = 0l; + + private long openALContext = 0l; /** * Constructor: Instantiates the source map, buffer map and listener @@ -135,10 +255,168 @@ public class LibraryLWJGLOpenAL extends Library { reverseByteOrder = true; } - private long openALDevice = 0l; - private long openALContext = 0l; - - private static final Logger logger = LogManager.getLogger("SoundSystem"); + /** + * Checks for OpenAL errors, and prints a message if there is an error. + * + * @return True if there was an error, False if not. + */ + private boolean checkALError() { + switch (AL10.alGetError()) { + case AL10.AL_NO_ERROR: + return false; + case AL10.AL_INVALID_NAME: + errorMessage("Invalid name parameter."); + return true; + case AL10.AL_INVALID_ENUM: + errorMessage("Invalid parameter."); + return true; + case AL10.AL_INVALID_VALUE: + errorMessage("Invalid enumerated parameter value."); + return true; + case AL10.AL_INVALID_OPERATION: + errorMessage("Illegal call."); + return true; + case AL10.AL_OUT_OF_MEMORY: + errorMessage("Unable to allocate memory."); + return true; + default: + errorMessage("An unrecognized error occurred."); + return true; + } + } + + /** + * Stops all sources, shuts down OpenAL, and removes references to all + * instantiated objects. + */ + @Override + public void cleanup() { + super.cleanup(); + + Set keys = bufferMap.keySet(); + Iterator iter = keys.iterator(); + String filename; + IntBuffer buffer; + + // loop through and clear all sound buffers: + while (iter.hasNext()) { + filename = iter.next(); + buffer = ALBufferMap.get(filename); + if (buffer != null) { + AL10.alDeleteBuffers(buffer); + checkALError(); + buffer.clear(); + } + } + + bufferMap.clear(); + + ALC11.alcMakeContextCurrent(0l); + ALC11.alcDestroyContext(openALContext); + ALC11.alcCloseDevice(openALDevice); + ALC.destroy(); + + bufferMap = null; + listenerPositionAL = null; + listenerOrientation = null; + listenerVelocity = null; + } + + /** + * Creates sources based on the source map provided. + * + * @param srcMap Sources to copy. + */ + @Override + public void copySources(HashMap srcMap) { + if (srcMap == null) + return; + Set keys = srcMap.keySet(); + Iterator iter = keys.iterator(); + String sourcename; + Source source; + + // Make sure the buffer map exists: + if (bufferMap == null) { + bufferMap = new HashMap(); + importantMessage("Buffer Map was null in method 'copySources'"); + } + // Make sure the OpenAL buffer map exists: + if (ALBufferMap == null) { + ALBufferMap = new HashMap(); + importantMessage("Open AL Buffer Map was null in method" + "'copySources'"); + } + + // remove any existing sources before starting: + sourceMap.clear(); + + SoundBuffer buffer; + // loop through and copy all the sources: + while (iter.hasNext()) { + sourcename = iter.next(); + source = srcMap.get(sourcename); + if (source != null) { + buffer = null; + if (!source.toStream) { + loadSound(source.filenameURL); + buffer = bufferMap.get(source.filenameURL.getFilename()); + } + if (source.toStream || buffer != null) + sourceMap.put(sourcename, new SourceLWJGLOpenAL(listenerPositionAL, + ALBufferMap.get(source.filenameURL.getFilename()), source, buffer)); + } + } + } + + /** + * Creates a new channel of the specified type (normal or streaming). Possible + * values for channel type can be found in the + * {@link paulscode.sound.SoundSystemConfig SoundSystemConfig} class. + * + * @param type Type of channel. + */ + @Override + protected Channel createChannel(int type) { + ChannelLWJGLOpenAL channel; + IntBuffer ALSource; + + ALSource = BufferUtils.createIntBuffer(1); + try { + AL10.alGenSources(ALSource); + } catch (java.lang.Exception e) { + AL10.alGetError(); + return null; // no more voices left + } + + if (AL10.alGetError() != AL10.AL_NO_ERROR) + return null; + + channel = new ChannelLWJGLOpenAL(type, ALSource); + return channel; + } + + /** + * The Doppler parameters have changed. + */ + @Override + public void dopplerChanged() { + super.dopplerChanged(); + + AL10.alDopplerFactor(SoundSystemConfig.getDopplerFactor()); + checkALError(); + AL10.alDopplerVelocity(SoundSystemConfig.getDopplerVelocity()); + checkALError(); + } + + /** + * Returns the name of the class. + * + * @return "Library" + library title. + */ + @Override + public String getClassName() { + return "LibraryLWJGLOpenAL"; + } /** * Initializes OpenAL, creates the listener, and grabs up audio channels. @@ -147,28 +425,28 @@ public class LibraryLWJGLOpenAL extends Library { public void init() throws SoundSystemException { boolean errors = false; // set to 'true' if error(s) occur: - //TODO: eaglercraft - - openALDevice = ALC11.alcOpenDevice((String)null); - + // TODO: eaglercraft + + openALDevice = ALC11.alcOpenDevice((String) null); + ALCCapabilities caps; if (openALDevice == 0l) { logger.error("Unable to initialize OpenAL!"); throw new LibraryLWJGLOpenAL.Exception("Unable to initialize OpenAL", LibraryLWJGLOpenAL.Exception.CREATE); - }else { + } else { caps = ALC.createCapabilities(openALDevice); logger.info("Device opened: {}", openALDevice); } openALContext = ALC11.alcCreateContext(openALDevice, new int[] { SOFTHRTF.ALC_HRTF_SOFT, 1, 0 }); - if(!ALC11.alcMakeContextCurrent(openALContext)) { + if (!ALC11.alcMakeContextCurrent(openALContext)) { ALC11.alcCloseDevice(openALDevice); logger.error("Unable to initialize AL context!"); throw new LibraryLWJGLOpenAL.Exception("Unable to initialize OpenAL", LibraryLWJGLOpenAL.Exception.CREATE); } - + AL.createCapabilities(caps); - + // Let user know if the library loaded properly if (errors) importantMessage("OpenAL did not initialize properly!"); @@ -229,79 +507,6 @@ public class LibraryLWJGLOpenAL extends Library { } } - /** - * Checks if the OpenAL library type is compatible. - * - * @return True or false. - */ - public static boolean libraryCompatible() { - return true; - } - - /** - * Creates a new channel of the specified type (normal or streaming). Possible - * values for channel type can be found in the - * {@link paulscode.sound.SoundSystemConfig SoundSystemConfig} class. - * - * @param type Type of channel. - */ - @Override - protected Channel createChannel(int type) { - ChannelLWJGLOpenAL channel; - IntBuffer ALSource; - - ALSource = BufferUtils.createIntBuffer(1); - try { - AL10.alGenSources(ALSource); - } catch (java.lang.Exception e) { - AL10.alGetError(); - return null; // no more voices left - } - - if (AL10.alGetError() != AL10.AL_NO_ERROR) - return null; - - channel = new ChannelLWJGLOpenAL(type, ALSource); - return channel; - } - - /** - * Stops all sources, shuts down OpenAL, and removes references to all - * instantiated objects. - */ - @Override - public void cleanup() { - super.cleanup(); - - Set keys = bufferMap.keySet(); - Iterator iter = keys.iterator(); - String filename; - IntBuffer buffer; - - // loop through and clear all sound buffers: - while (iter.hasNext()) { - filename = iter.next(); - buffer = ALBufferMap.get(filename); - if (buffer != null) { - AL10.alDeleteBuffers(buffer); - checkALError(); - buffer.clear(); - } - } - - bufferMap.clear(); - - ALC11.alcMakeContextCurrent(0l); - ALC11.alcDestroyContext(openALContext); - ALC11.alcCloseDevice(openALDevice); - ALC.destroy(); - - bufferMap = null; - listenerPositionAL = null; - listenerOrientation = null; - listenerVelocity = null; - } - /** * Pre-loads a sound into memory. * @@ -479,33 +684,6 @@ public class LibraryLWJGLOpenAL extends Library { return true; } - /** - * Removes a pre-loaded sound from memory. This is a good method to use for - * freeing up memory after a large sound file is no longer needed. NOTE: the - * source will remain in memory after this method has been called, for as long - * as the sound is attached to an existing source. - * - * @param filename Filename/identifier of the sound file to unload. - */ - @Override - public void unloadSound(String filename) { - ALBufferMap.remove(filename); - super.unloadSound(filename); - } - - /** - * Sets the overall volume to the specified value, affecting all sources. - * - * @param value New volume, float value ( 0.0f - 1.0f ). - */ - @Override - public void setMasterVolume(float value) { - super.setMasterVolume(value); - - AL10.alListenerf(AL10.AL_GAIN, value); - checkALError(); - } - /** * Creates a new source and places it into the source map. * @@ -577,28 +755,6 @@ public class LibraryLWJGLOpenAL extends Library { sourcename, filenameURL, buffer, x, y, z, attModel, distOrRoll, false)); } - /** - * Opens a direct line for streaming audio data. - * - * @param audioFormat Format that the data will be in. - * @param priority Setting this to true will prevent other sounds from - * overriding this one. - * @param sourcename A unique identifier for this source. Two sources may not - * use the same sourcename. - * @param x X position for this source. - * @param y Y position for this source. - * @param z Z position for this source. - * @param attModel Attenuation model to use. - * @param distOrRoll Either the fading distance or rolloff factor, depending on - * the value of "attmodel". - */ - @Override - public void rawDataStream(AudioFormat audioFormat, boolean priority, String sourcename, float x, float y, float z, - int attModel, float distOrRoll) { - sourceMap.put(sourcename, new SourceLWJGLOpenAL(listenerPositionAL, audioFormat, priority, sourcename, x, y, z, - attModel, distOrRoll)); - } - /** * Creates and immediately plays a new source. * @@ -670,70 +826,25 @@ public class LibraryLWJGLOpenAL extends Library { } /** - * Creates sources based on the source map provided. + * Opens a direct line for streaming audio data. * - * @param srcMap Sources to copy. + * @param audioFormat Format that the data will be in. + * @param priority Setting this to true will prevent other sounds from + * overriding this one. + * @param sourcename A unique identifier for this source. Two sources may not + * use the same sourcename. + * @param x X position for this source. + * @param y Y position for this source. + * @param z Z position for this source. + * @param attModel Attenuation model to use. + * @param distOrRoll Either the fading distance or rolloff factor, depending on + * the value of "attmodel". */ @Override - public void copySources(HashMap srcMap) { - if (srcMap == null) - return; - Set keys = srcMap.keySet(); - Iterator iter = keys.iterator(); - String sourcename; - Source source; - - // Make sure the buffer map exists: - if (bufferMap == null) { - bufferMap = new HashMap(); - importantMessage("Buffer Map was null in method 'copySources'"); - } - // Make sure the OpenAL buffer map exists: - if (ALBufferMap == null) { - ALBufferMap = new HashMap(); - importantMessage("Open AL Buffer Map was null in method" + "'copySources'"); - } - - // remove any existing sources before starting: - sourceMap.clear(); - - SoundBuffer buffer; - // loop through and copy all the sources: - while (iter.hasNext()) { - sourcename = iter.next(); - source = srcMap.get(sourcename); - if (source != null) { - buffer = null; - if (!source.toStream) { - loadSound(source.filenameURL); - buffer = bufferMap.get(source.filenameURL.getFilename()); - } - if (source.toStream || buffer != null) - sourceMap.put(sourcename, new SourceLWJGLOpenAL(listenerPositionAL, - ALBufferMap.get(source.filenameURL.getFilename()), source, buffer)); - } - } - } - - /** - * Changes the listener's position. - * - * @param x Destination X coordinate. - * @param y Destination Y coordinate. - * @param z Destination Z coordinate. - */ - @Override - public void setListenerPosition(float x, float y, float z) { - super.setListenerPosition(x, y, z); - - listenerPositionAL.put(0, x); - listenerPositionAL.put(1, y); - listenerPositionAL.put(2, z); - - // Update OpenAL listener position: - AL10.alListenerfv(AL10.AL_POSITION, listenerPositionAL); - // Check for errors: - checkALError(); + public void rawDataStream(AudioFormat audioFormat, boolean priority, String sourcename, float x, float y, float z, + int attModel, float distOrRoll) { + sourceMap.put(sourcename, new SourceLWJGLOpenAL(listenerPositionAL, audioFormat, priority, sourcename, x, y, z, + attModel, distOrRoll)); } /** @@ -755,29 +866,6 @@ public class LibraryLWJGLOpenAL extends Library { checkALError(); } - /** - * Changes the listeners orientation using the specified coordinates. - * - * @param lookX X element of the look-at direction. - * @param lookY Y element of the look-at direction. - * @param lookZ Z element of the look-at direction. - * @param upX X element of the up direction. - * @param upY Y element of the up direction. - * @param upZ Z element of the up direction. - */ - @Override - public void setListenerOrientation(float lookX, float lookY, float lookZ, float upX, float upY, float upZ) { - super.setListenerOrientation(lookX, lookY, lookZ, upX, upY, upZ); - listenerOrientation.put(0, lookX); - listenerOrientation.put(1, lookY); - listenerOrientation.put(2, lookZ); - listenerOrientation.put(3, upX); - listenerOrientation.put(4, upY); - listenerOrientation.put(5, upZ); - AL10.alListenerfv(AL10.AL_ORIENTATION, listenerOrientation); - checkALError(); - } - /** * Changes the listeners position and orientation using the specified listener * data. @@ -810,6 +898,50 @@ public class LibraryLWJGLOpenAL extends Library { checkALError(); } + /** + * Changes the listeners orientation using the specified coordinates. + * + * @param lookX X element of the look-at direction. + * @param lookY Y element of the look-at direction. + * @param lookZ Z element of the look-at direction. + * @param upX X element of the up direction. + * @param upY Y element of the up direction. + * @param upZ Z element of the up direction. + */ + @Override + public void setListenerOrientation(float lookX, float lookY, float lookZ, float upX, float upY, float upZ) { + super.setListenerOrientation(lookX, lookY, lookZ, upX, upY, upZ); + listenerOrientation.put(0, lookX); + listenerOrientation.put(1, lookY); + listenerOrientation.put(2, lookZ); + listenerOrientation.put(3, upX); + listenerOrientation.put(4, upY); + listenerOrientation.put(5, upZ); + AL10.alListenerfv(AL10.AL_ORIENTATION, listenerOrientation); + checkALError(); + } + + /** + * Changes the listener's position. + * + * @param x Destination X coordinate. + * @param y Destination Y coordinate. + * @param z Destination Z coordinate. + */ + @Override + public void setListenerPosition(float x, float y, float z) { + super.setListenerPosition(x, y, z); + + listenerPositionAL.put(0, x); + listenerPositionAL.put(1, y); + listenerPositionAL.put(2, z); + + // Update OpenAL listener position: + AL10.alListenerfv(AL10.AL_POSITION, listenerPositionAL); + // Check for errors: + checkALError(); + } + /** * Sets the listener's velocity, for use in Doppler effect. * @@ -828,157 +960,29 @@ public class LibraryLWJGLOpenAL extends Library { } /** - * The Doppler parameters have changed. + * Sets the overall volume to the specified value, affecting all sources. + * + * @param value New volume, float value ( 0.0f - 1.0f ). */ @Override - public void dopplerChanged() { - super.dopplerChanged(); + public void setMasterVolume(float value) { + super.setMasterVolume(value); - AL10.alDopplerFactor(SoundSystemConfig.getDopplerFactor()); - checkALError(); - AL10.alDopplerVelocity(SoundSystemConfig.getDopplerVelocity()); + AL10.alListenerf(AL10.AL_GAIN, value); checkALError(); } /** - * Checks for OpenAL errors, and prints a message if there is an error. + * Removes a pre-loaded sound from memory. This is a good method to use for + * freeing up memory after a large sound file is no longer needed. NOTE: the + * source will remain in memory after this method has been called, for as long + * as the sound is attached to an existing source. * - * @return True if there was an error, False if not. - */ - private boolean checkALError() { - switch (AL10.alGetError()) { - case AL10.AL_NO_ERROR: - return false; - case AL10.AL_INVALID_NAME: - errorMessage("Invalid name parameter."); - return true; - case AL10.AL_INVALID_ENUM: - errorMessage("Invalid parameter."); - return true; - case AL10.AL_INVALID_VALUE: - errorMessage("Invalid enumerated parameter value."); - return true; - case AL10.AL_INVALID_OPERATION: - errorMessage("Illegal call."); - return true; - case AL10.AL_OUT_OF_MEMORY: - errorMessage("Unable to allocate memory."); - return true; - default: - errorMessage("An unrecognized error occurred."); - return true; - } - } - - /** - * Whether or not the AL_PITCH control is supported. - * - * @return True if AL_PITCH is supported. - */ - public static boolean alPitchSupported() { - return alPitchSupported(GET, XXX); - } - - /** - * Sets or returns the value of boolean 'alPitchSupported'. - * - * @param action Action to perform (GET or SET). - * @param value New value if action is SET, otherwise XXX. - * @return value of boolean 'alPitchSupported'. - */ - private static synchronized boolean alPitchSupported(boolean action, boolean value) { - if (action == SET) - alPitchSupported = value; - return alPitchSupported; - } - - /** - * Returns the short title of this library type. - * - * @return A short title. - */ - public static String getTitle() { - return "LWJGL OpenAL (Eaglercraft)"; - } - - /** - * Returns a longer description of this library type. - * - * @return A longer description. - */ - public static String getDescription() { - return "The Eaglercraft LWJGL3 binding of OpenAL"; - } - - /** - * Returns the name of the class. - * - * @return "Library" + library title. + * @param filename Filename/identifier of the sound file to unload. */ @Override - public String getClassName() { - return "LibraryLWJGLOpenAL"; - } - - /** - * The LibraryLWJGLOpenAL.Exception class provides library-specific error - * information. - */ - public static class Exception extends SoundSystemException { - private static final long serialVersionUID = -7502452059037798035L; - /** - * Global identifier for an exception during AL.create(). Probably means that - * OpenAL is not supported. - */ - public static final int CREATE = 101; - /** - * Global identifier for an invalid name parameter in OpenAL. - */ - public static final int INVALID_NAME = 102; - /** - * Global identifier for an invalid parameter in OpenAL. - */ - public static final int INVALID_ENUM = 103; - /** - * Global identifier for an invalid enumerated parameter value in OpenAL. - */ - public static final int INVALID_VALUE = 104; - /** - * Global identifier for an illegal call in OpenAL. - */ - public static final int INVALID_OPERATION = 105; - /** - * Global identifier for OpenAL out of memory. - */ - public static final int OUT_OF_MEMORY = 106; - /** - * Global identifier for an exception while creating the OpenAL Listener. - */ - public static final int LISTENER = 107; - /** - * Global identifier for OpenAL AL_PITCH not supported. - */ - public static final int NO_AL_PITCH = 108; - - /** - * Constructor: Generates a standard "unknown error" exception with the - * specified message. - * - * @param message A brief description of the problem that occurred. - */ - public Exception(String message) { - super(message); - } - - /** - * Constructor: Generates an exception of the specified type, with the specified - * message. - * - * @param message A brief description of the problem that occurred. - * @param type Identifier indicating they type of error. - */ - public Exception(String message, int type) { - super(message, type); - } + public void unloadSound(String filename) { + ALBufferMap.remove(filename); + super.unloadSound(filename); } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/SourceLWJGLOpenAL.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/SourceLWJGLOpenAL.java index 62b03329..f03067aa 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/SourceLWJGLOpenAL.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/internal/paulscode/lwjgl3/SourceLWJGLOpenAL.java @@ -1,8 +1,9 @@ package net.lax1dude.eaglercraft.v1_8.internal.paulscode.lwjgl3; -import java.nio.IntBuffer; import java.nio.FloatBuffer; +import java.nio.IntBuffer; import java.util.LinkedList; + import javax.sound.sampled.AudioFormat; // From the lwjgl library, http://www.lwjgl.org @@ -11,9 +12,9 @@ import org.lwjgl.openal.AL10; import paulscode.sound.Channel; import paulscode.sound.FilenameURL; -import paulscode.sound.Source; import paulscode.sound.SoundBuffer; import paulscode.sound.SoundSystemConfig; +import paulscode.sound.Source; /** * The SourceLWJGLOpenAL class provides an interface to the lwjgl binding of @@ -101,6 +102,32 @@ public class SourceLWJGLOpenAL extends Source { */ private FloatBuffer sourceVelocity; + /** + * Constructor: Creates a new streaming source that will be directly fed with + * raw audio data. + * + * @param listenerPosition FloatBuffer containing the listener's 3D coordinates. + * @param audioFormat Format that the data will be in. + * @param priority Setting this to true will prevent other sounds from + * overriding this one. + * @param sourcename A unique identifier for this source. Two sources may + * not use the same sourcename. + * @param x X position for this source. + * @param y Y position for this source. + * @param z Z position for this source. + * @param attModel Attenuation model to use. + * @param distOrRoll Either the fading distance or rolloff factor, + * depending on the value of 'att'. + */ + public SourceLWJGLOpenAL(FloatBuffer listenerPosition, AudioFormat audioFormat, boolean priority, String sourcename, + float x, float y, float z, int attModel, float distOrRoll) { + super(audioFormat, priority, sourcename, x, y, z, attModel, distOrRoll); + this.listenerPosition = listenerPosition; + libraryType = LibraryLWJGLOpenAL.class; + pitch = 1.0f; + resetALInformation(); + } + /** * Constructor: Creates a new source using the specified parameters. * @@ -162,38 +189,39 @@ public class SourceLWJGLOpenAL extends Source { } /** - * Constructor: Creates a new streaming source that will be directly fed with - * raw audio data. - * - * @param listenerPosition FloatBuffer containing the listener's 3D coordinates. - * @param audioFormat Format that the data will be in. - * @param priority Setting this to true will prevent other sounds from - * overriding this one. - * @param sourcename A unique identifier for this source. Two sources may - * not use the same sourcename. - * @param x X position for this source. - * @param y Y position for this source. - * @param z Z position for this source. - * @param attModel Attenuation model to use. - * @param distOrRoll Either the fading distance or rolloff factor, - * depending on the value of 'att'. + * Calculates this source's distance from the listener. */ - public SourceLWJGLOpenAL(FloatBuffer listenerPosition, AudioFormat audioFormat, boolean priority, String sourcename, - float x, float y, float z, int attModel, float distOrRoll) { - super(audioFormat, priority, sourcename, x, y, z, attModel, distOrRoll); - this.listenerPosition = listenerPosition; - libraryType = LibraryLWJGLOpenAL.class; - pitch = 1.0f; - resetALInformation(); + private void calculateDistance() { + if (listenerPosition != null) { + // Calculate the source's distance from the listener: + double dX = position.x - listenerPosition.get(0); + double dY = position.y - listenerPosition.get(1); + double dZ = position.z - listenerPosition.get(2); + distanceFromListener = (float) Math.sqrt(dX * dX + dY * dY + dZ * dZ); + } } /** - * Shuts the source down and removes references to all instantiated objects. + * If using linear attenuation, calculates the gain for this source based on its + * distance from the listener. */ - @Override - public void cleanup() { - - super.cleanup(); + private void calculateGain() { + // If using linear attenuation, calculate the source's gain: + if (attModel == SoundSystemConfig.ATTENUATION_LINEAR) { + if (distanceFromListener <= 0) { + gain = 1.0f; + } else if (distanceFromListener >= distOrRoll) { + gain = 0.0f; + } else { + gain = 1.0f - (distanceFromListener / distOrRoll); + } + if (gain > 1.0f) + gain = 1.0f; + if (gain < 0.0f) + gain = 0.0f; + } else { + gain = 1.0f; + } } /** @@ -233,6 +261,56 @@ public class SourceLWJGLOpenAL extends Source { resetALInformation(); } + /** + * Checks for OpenAL errors, and prints a message if there is an error. + * + * @return True if there was an error, False if not. + */ + private boolean checkALError() { + switch (AL10.alGetError()) { + case AL10.AL_NO_ERROR: + return false; + case AL10.AL_INVALID_NAME: + errorMessage("Invalid name parameter."); + return true; + case AL10.AL_INVALID_ENUM: + errorMessage("Invalid parameter."); + return true; + case AL10.AL_INVALID_VALUE: + errorMessage("Invalid enumerated parameter value."); + return true; + case AL10.AL_INVALID_OPERATION: + errorMessage("Illegal call."); + return true; + case AL10.AL_OUT_OF_MEMORY: + errorMessage("Unable to allocate memory."); + return true; + default: + errorMessage("An unrecognized error occurred."); + return true; + } + } + + /** + * Checks the source's pitch. + */ + private void checkPitch() { + if (channel != null && channel.attachedSource == this && LibraryLWJGLOpenAL.alPitchSupported() + && channelOpenAL != null && channelOpenAL.ALSource != null) { + AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_PITCH, pitch); + checkALError(); + } + } + + /** + * Shuts the source down and removes references to all instantiated objects. + */ + @Override + public void cleanup() { + + super.cleanup(); + } + /** * Removes the next filename from the sound sequence queue and assigns it to * this source. This method has no effect on non-streaming sources. This method @@ -307,163 +385,6 @@ public class SourceLWJGLOpenAL extends Source { positionChanged(); } - /** - * Moves the source to the specified position. - * - * @param x X coordinate to move to. - * @param y Y coordinate to move to. - * @param z Z coordinate to move to. - */ - @Override - public void setPosition(float x, float y, float z) { - super.setPosition(x, y, z); - - // Make sure OpenAL information has been created - if (sourcePosition == null) - resetALInformation(); - else - positionChanged(); - - // put the new position information into the buffer: - sourcePosition.put(0, x); - sourcePosition.put(1, y); - sourcePosition.put(2, z); - - // make sure we are assigned to a channel: - if (channel != null && channel.attachedSource == this && channelOpenAL != null - && channelOpenAL.ALSource != null) { - // move the source: - AL10.alSourcefv(channelOpenAL.ALSource.get(0), AL10.AL_POSITION, sourcePosition); - checkALError(); - } - } - - /** - * Recalculates the distance from the listner and the gain. - */ - @Override - public void positionChanged() { - calculateDistance(); - calculateGain(); - - if (channel != null && channel.attachedSource == this && channelOpenAL != null - && channelOpenAL.ALSource != null) { - AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_GAIN, - (gain * sourceVolume * (float) Math.abs(fadeOutGain) * fadeInGain)); - checkALError(); - } - checkPitch(); - } - - /** - * Checks the source's pitch. - */ - private void checkPitch() { - if (channel != null && channel.attachedSource == this && LibraryLWJGLOpenAL.alPitchSupported() - && channelOpenAL != null && channelOpenAL.ALSource != null) { - AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_PITCH, pitch); - checkALError(); - } - } - - /** - * Sets whether this source should loop or only play once. - * - * @param lp True or false. - */ - @Override - public void setLooping(boolean lp) { - super.setLooping(lp); - - // make sure we are assigned to a channel: - if (channel != null && channel.attachedSource == this && channelOpenAL != null - && channelOpenAL.ALSource != null) { - if (lp) - AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_LOOPING, AL10.AL_TRUE); - else - AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_LOOPING, AL10.AL_FALSE); - checkALError(); - } - } - - /** - * Sets this source's attenuation model. - * - * @param model Attenuation model to use. - */ - @Override - public void setAttenuation(int model) { - super.setAttenuation(model); - // make sure we are assigned to a channel: - if (channel != null && channel.attachedSource == this && channelOpenAL != null - && channelOpenAL.ALSource != null) { - // attenuation changed, so update the rolloff factor accordingly - if (model == SoundSystemConfig.ATTENUATION_ROLLOFF) - AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, distOrRoll); - else - AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, 0.0f); - checkALError(); - if (model == SoundSystemConfig.ATTENUATION_NONE) - AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_SOURCE_RELATIVE, 1); - else - AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_SOURCE_RELATIVE, 0); - checkALError(); - } - } - - /** - * Sets this source's fade distance or rolloff factor, depending on the - * attenuation model. - * - * @param dr New value for fade distance or rolloff factor. - */ - @Override - public void setDistOrRoll(float dr) { - super.setDistOrRoll(dr); - // make sure we are assigned to a channel: - if (channel != null && channel.attachedSource == this && channelOpenAL != null - && channelOpenAL.ALSource != null) { - // if we are using rolloff attenuation, then dr is a rolloff factor: - if (attModel == SoundSystemConfig.ATTENUATION_ROLLOFF) - AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, dr); - else - AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, 0.0f); - checkALError(); - } - } - - /** - * Sets this source's velocity, for use in Doppler effect. - * - * @param x Velocity along world x-axis. - * @param y Velocity along world y-axis. - * @param z Velocity along world z-axis. - */ - @Override - public void setVelocity(float x, float y, float z) { - super.setVelocity(x, y, z); - - sourceVelocity = BufferUtils.createFloatBuffer(3).put(new float[] { x, y, z }); - sourceVelocity.flip(); - // make sure we are assigned to a channel: - if (channel != null && channel.attachedSource == this && channelOpenAL != null - && channelOpenAL.ALSource != null) { - AL10.alSourcefv(channelOpenAL.ALSource.get(0), AL10.AL_VELOCITY, sourceVelocity); - checkALError(); - } - } - - /** - * Manually sets this source's pitch. - * - * @param value A float value ( 0.5f - 2.0f ). - */ - @Override - public void setPitch(float value) { - super.setPitch(value); - checkPitch(); - } - /** * Plays the source on the specified channel. * @@ -516,7 +437,7 @@ public class SourceLWJGLOpenAL extends Source { else AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, 0.0f); checkALError(); - + if (attModel == SoundSystemConfig.ATTENUATION_NONE) AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_SOURCE_RELATIVE, 1); else @@ -592,6 +513,23 @@ public class SourceLWJGLOpenAL extends Source { } } + /** + * Recalculates the distance from the listner and the gain. + */ + @Override + public void positionChanged() { + calculateDistance(); + calculateGain(); + + if (channel != null && channel.attachedSource == this && channelOpenAL != null + && channelOpenAL.ALSource != null) { + AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_GAIN, + (gain * sourceVolume * (float) Math.abs(fadeOutGain) * fadeInGain)); + checkALError(); + } + checkPitch(); + } + /** * Queues up the initial stream-buffers for the stream. * @@ -636,68 +574,131 @@ public class SourceLWJGLOpenAL extends Source { } /** - * Calculates this source's distance from the listener. - */ - private void calculateDistance() { - if (listenerPosition != null) { - // Calculate the source's distance from the listener: - double dX = position.x - listenerPosition.get(0); - double dY = position.y - listenerPosition.get(1); - double dZ = position.z - listenerPosition.get(2); - distanceFromListener = (float) Math.sqrt(dX * dX + dY * dY + dZ * dZ); - } - } - - /** - * If using linear attenuation, calculates the gain for this source based on its - * distance from the listener. - */ - private void calculateGain() { - // If using linear attenuation, calculate the source's gain: - if (attModel == SoundSystemConfig.ATTENUATION_LINEAR) { - if (distanceFromListener <= 0) { - gain = 1.0f; - } else if (distanceFromListener >= distOrRoll) { - gain = 0.0f; - } else { - gain = 1.0f - (distanceFromListener / distOrRoll); - } - if (gain > 1.0f) - gain = 1.0f; - if (gain < 0.0f) - gain = 0.0f; - } else { - gain = 1.0f; - } - } - - /** - * Checks for OpenAL errors, and prints a message if there is an error. + * Sets this source's attenuation model. * - * @return True if there was an error, False if not. + * @param model Attenuation model to use. */ - private boolean checkALError() { - switch (AL10.alGetError()) { - case AL10.AL_NO_ERROR: - return false; - case AL10.AL_INVALID_NAME: - errorMessage("Invalid name parameter."); - return true; - case AL10.AL_INVALID_ENUM: - errorMessage("Invalid parameter."); - return true; - case AL10.AL_INVALID_VALUE: - errorMessage("Invalid enumerated parameter value."); - return true; - case AL10.AL_INVALID_OPERATION: - errorMessage("Illegal call."); - return true; - case AL10.AL_OUT_OF_MEMORY: - errorMessage("Unable to allocate memory."); - return true; - default: - errorMessage("An unrecognized error occurred."); - return true; + @Override + public void setAttenuation(int model) { + super.setAttenuation(model); + // make sure we are assigned to a channel: + if (channel != null && channel.attachedSource == this && channelOpenAL != null + && channelOpenAL.ALSource != null) { + // attenuation changed, so update the rolloff factor accordingly + if (model == SoundSystemConfig.ATTENUATION_ROLLOFF) + AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, distOrRoll); + else + AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, 0.0f); + checkALError(); + if (model == SoundSystemConfig.ATTENUATION_NONE) + AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_SOURCE_RELATIVE, 1); + else + AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_SOURCE_RELATIVE, 0); + checkALError(); + } + } + + /** + * Sets this source's fade distance or rolloff factor, depending on the + * attenuation model. + * + * @param dr New value for fade distance or rolloff factor. + */ + @Override + public void setDistOrRoll(float dr) { + super.setDistOrRoll(dr); + // make sure we are assigned to a channel: + if (channel != null && channel.attachedSource == this && channelOpenAL != null + && channelOpenAL.ALSource != null) { + // if we are using rolloff attenuation, then dr is a rolloff factor: + if (attModel == SoundSystemConfig.ATTENUATION_ROLLOFF) + AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, dr); + else + AL10.alSourcef(channelOpenAL.ALSource.get(0), AL10.AL_ROLLOFF_FACTOR, 0.0f); + checkALError(); + } + } + + /** + * Sets whether this source should loop or only play once. + * + * @param lp True or false. + */ + @Override + public void setLooping(boolean lp) { + super.setLooping(lp); + + // make sure we are assigned to a channel: + if (channel != null && channel.attachedSource == this && channelOpenAL != null + && channelOpenAL.ALSource != null) { + if (lp) + AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_LOOPING, AL10.AL_TRUE); + else + AL10.alSourcei(channelOpenAL.ALSource.get(0), AL10.AL_LOOPING, AL10.AL_FALSE); + checkALError(); + } + } + + /** + * Manually sets this source's pitch. + * + * @param value A float value ( 0.5f - 2.0f ). + */ + @Override + public void setPitch(float value) { + super.setPitch(value); + checkPitch(); + } + + /** + * Moves the source to the specified position. + * + * @param x X coordinate to move to. + * @param y Y coordinate to move to. + * @param z Z coordinate to move to. + */ + @Override + public void setPosition(float x, float y, float z) { + super.setPosition(x, y, z); + + // Make sure OpenAL information has been created + if (sourcePosition == null) + resetALInformation(); + else + positionChanged(); + + // put the new position information into the buffer: + sourcePosition.put(0, x); + sourcePosition.put(1, y); + sourcePosition.put(2, z); + + // make sure we are assigned to a channel: + if (channel != null && channel.attachedSource == this && channelOpenAL != null + && channelOpenAL.ALSource != null) { + // move the source: + AL10.alSourcefv(channelOpenAL.ALSource.get(0), AL10.AL_POSITION, sourcePosition); + checkALError(); + } + } + + /** + * Sets this source's velocity, for use in Doppler effect. + * + * @param x Velocity along world x-axis. + * @param y Velocity along world y-axis. + * @param z Velocity along world z-axis. + */ + @Override + public void setVelocity(float x, float y, float z) { + super.setVelocity(x, y, z); + + sourceVelocity = BufferUtils.createFloatBuffer(3).put(new float[] { x, y, z }); + sourceVelocity.flip(); + // make sure we are assigned to a channel: + if (channel != null && channel.attachedSource == this && channelOpenAL != null + && channelOpenAL.ALSource != null) { + AL10.alSourcefv(channelOpenAL.ALSource.get(0), AL10.AL_VELOCITY, sourceVelocity); + checkALError(); } } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/internal/ClientPlatformSingleplayer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/internal/ClientPlatformSingleplayer.java index 8981e803..88cd7b47 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/internal/ClientPlatformSingleplayer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/internal/ClientPlatformSingleplayer.java @@ -12,14 +12,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.internal.lwjgl.MemoryConnection; /** * Copyright (c) 2023-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,43 +29,12 @@ public class ClientPlatformSingleplayer { private static CrashScreenPopup crashOverlay = null; - public static void startIntegratedServer(boolean forceSingleThread) { - DesktopIntegratedServer.startIntegratedServer(); - } - - public static void sendPacket(IPCPacketData packet) { - synchronized(MemoryConnection.clientToServerQueue) { - MemoryConnection.clientToServerQueue.add(packet); - } - } - - public static IPCPacketData recievePacket() { - synchronized(MemoryConnection.serverToClientQueue) { - if(MemoryConnection.serverToClientQueue.size() > 0) { - return MemoryConnection.serverToClientQueue.remove(0); - } - } - return null; - } - - public static List recieveAllPacket() { - synchronized(MemoryConnection.serverToClientQueue) { - if(MemoryConnection.serverToClientQueue.size() == 0) { - return null; - }else { - List ret = new ArrayList<>(MemoryConnection.serverToClientQueue); - MemoryConnection.serverToClientQueue.clear(); - return ret; - } - } - } - public static boolean canKillWorker() { return false; } - public static void killWorker() { - throw new IllegalStateException("Cannot kill worker thread on desktop! (memleak)"); + public static void hideCrashReportOverlay() { + crashOverlay.setVisible(false); } public static boolean isRunningSingleThreadMode() { @@ -75,12 +45,39 @@ public class ClientPlatformSingleplayer { return false; } - public static void updateSingleThreadMode() { - + public static void killWorker() { + throw new IllegalStateException("Cannot kill worker thread on desktop! (memleak)"); + } + + public static List recieveAllPacket() { + synchronized (MemoryConnection.serverToClientQueue) { + if (MemoryConnection.serverToClientQueue.size() == 0) { + return null; + } else { + List ret = new ArrayList<>(MemoryConnection.serverToClientQueue); + MemoryConnection.serverToClientQueue.clear(); + return ret; + } + } + } + + public static IPCPacketData recievePacket() { + synchronized (MemoryConnection.serverToClientQueue) { + if (MemoryConnection.serverToClientQueue.size() > 0) { + return MemoryConnection.serverToClientQueue.remove(0); + } + } + return null; + } + + public static void sendPacket(IPCPacketData packet) { + synchronized (MemoryConnection.clientToServerQueue) { + MemoryConnection.clientToServerQueue.add(packet); + } } public static void showCrashReportOverlay(String report, int x, int y, int w, int h) { - if(crashOverlay == null) { + if (crashOverlay == null) { crashOverlay = new CrashScreenPopup(); } int[] wx = new int[1]; @@ -92,8 +89,12 @@ public class ClientPlatformSingleplayer { crashOverlay.requestFocus(); } - public static void hideCrashReportOverlay() { - crashOverlay.setVisible(false); + public static void startIntegratedServer(boolean forceSingleThread) { + DesktopIntegratedServer.startIntegratedServer(); + } + + public static void updateSingleThreadMode() { + } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/ServerPlatformSingleplayer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/ServerPlatformSingleplayer.java index f1a54681..dcc807fc 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/ServerPlatformSingleplayer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/ServerPlatformSingleplayer.java @@ -14,14 +14,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.internal.lwjgl.MemoryConnection; /** * Copyright (c) 2023-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,8 +31,20 @@ public class ServerPlatformSingleplayer { private static IEaglerFilesystem filesystem = null; + public static IClientConfigAdapter getClientConfigAdapter() { + return DesktopClientConfigAdapter.instance; + } + + public static IEaglerFilesystem getWorldsDatabase() { + return filesystem; + } + + public static void immediateContinue() { + + } + public static void initializeContext() { - if(filesystem == null) { + if (filesystem == null) { filesystem = Filesystem.getHandleFor(getClientConfigAdapter().getWorldsDB()); } } @@ -40,30 +53,19 @@ public class ServerPlatformSingleplayer { throw new UnsupportedOperationException(); } - public static IEaglerFilesystem getWorldsDatabase() { - return filesystem; + public static boolean isSingleThreadMode() { + return false; } - public static void sendPacket(IPCPacketData packet) { - synchronized(MemoryConnection.serverToClientQueue) { - MemoryConnection.serverToClientQueue.add(packet); - } - } - - public static IPCPacketData recievePacket() { - synchronized(MemoryConnection.clientToServerQueue) { - if(MemoryConnection.clientToServerQueue.size() > 0) { - return MemoryConnection.clientToServerQueue.remove(0); - } - } - return null; + public static void platformShutdown() { + filesystem = null; } public static List recieveAllPacket() { - synchronized(MemoryConnection.clientToServerQueue) { - if(MemoryConnection.clientToServerQueue.size() == 0) { + synchronized (MemoryConnection.clientToServerQueue) { + if (MemoryConnection.clientToServerQueue.size() == 0) { return null; - }else { + } else { List ret = new ArrayList<>(MemoryConnection.clientToServerQueue); MemoryConnection.clientToServerQueue.clear(); return ret; @@ -71,20 +73,19 @@ public class ServerPlatformSingleplayer { } } - public static IClientConfigAdapter getClientConfigAdapter() { - return DesktopClientConfigAdapter.instance; + public static IPCPacketData recievePacket() { + synchronized (MemoryConnection.clientToServerQueue) { + if (MemoryConnection.clientToServerQueue.size() > 0) { + return MemoryConnection.clientToServerQueue.remove(0); + } + } + return null; } - public static void immediateContinue() { - - } - - public static void platformShutdown() { - filesystem = null; - } - - public static boolean isSingleThreadMode() { - return false; + public static void sendPacket(IPCPacketData packet) { + synchronized (MemoryConnection.serverToClientQueue) { + MemoryConnection.serverToClientQueue.add(packet); + } } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/CrashScreenPopup.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/CrashScreenPopup.java index 21c00186..efe27d75 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/CrashScreenPopup.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/CrashScreenPopup.java @@ -1,26 +1,28 @@ package net.lax1dude.eaglercraft.v1_8.sp.server.internal.lwjgl; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import java.awt.Toolkit; + import javax.swing.JFrame; import javax.swing.JPanel; -import java.awt.BorderLayout; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.ScrollPaneConstants; -import java.awt.Font; -import java.awt.Toolkit; -import java.awt.Color; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,12 +50,12 @@ public class CrashScreenPopup extends JFrame { setContentPane(contentPane); contentPane.setLayout(new BorderLayout(0, 0)); - + JScrollPane scrollPane = new JScrollPane(); scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); contentPane.add(scrollPane, BorderLayout.CENTER); - + txtrTest = new JTextArea(); txtrTest.setBackground(new Color(0, 0, 0)); txtrTest.setForeground(new Color(255, 255, 255)); diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/DesktopIntegratedServer.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/DesktopIntegratedServer.java index c6f213e8..56f8b136 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/DesktopIntegratedServer.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/DesktopIntegratedServer.java @@ -6,14 +6,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplay /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,7 +24,7 @@ public class DesktopIntegratedServer implements Runnable { public static Thread serverThread = null; public static void startIntegratedServer() { - if(serverThread == null) { + if (serverThread == null) { serverThread = new Thread(new DesktopIntegratedServer(), "IntegratedServer"); serverThread.setDaemon(true); serverThread.start(); @@ -35,7 +36,7 @@ public class DesktopIntegratedServer implements Runnable { try { ServerPlatformSingleplayer.initializeContext(); EaglerIntegratedServerWorker.serverMain(); - }finally { + } finally { serverThread = null; } } diff --git a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/MemoryConnection.java b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/MemoryConnection.java index e77091c9..c9293b0f 100644 --- a/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/MemoryConnection.java +++ b/src/lwjgl/java/net/lax1dude/eaglercraft/v1_8/sp/server/internal/lwjgl/MemoryConnection.java @@ -8,14 +8,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.IPCPacketData; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/com/google/common/annotations/GwtCompatible.java b/src/main/java/com/google/common/annotations/GwtCompatible.java index 4b144260..4a9bcd57 100644 --- a/src/main/java/com/google/common/annotations/GwtCompatible.java +++ b/src/main/java/com/google/common/annotations/GwtCompatible.java @@ -69,16 +69,6 @@ import java.lang.annotation.Target; @GwtCompatible public @interface GwtCompatible { - /** - * When {@code true}, the annotated type or the type of the method return value - * is GWT serializable. - * - * @see - * Documentation about GWT serialization - */ - boolean serializable() default false; - /** * When {@code true}, the annotated type is emulated in GWT. The emulated source * (also known as super-source) is different from the implementation used by the @@ -89,4 +79,14 @@ public @interface GwtCompatible { * Documentation about GWT emulated source */ boolean emulated() default false; + + /** + * When {@code true}, the annotated type or the type of the method return value + * is GWT serializable. + * + * @see + * Documentation about GWT serialization + */ + boolean serializable() default false; } diff --git a/src/main/java/com/google/common/base/Absent.java b/src/main/java/com/google/common/base/Absent.java index 1814d060..64ecaf2f 100644 --- a/src/main/java/com/google/common/base/Absent.java +++ b/src/main/java/com/google/common/base/Absent.java @@ -32,6 +32,8 @@ import com.google.common.annotations.GwtCompatible; final class Absent extends Optional { static final Absent INSTANCE = new Absent(); + private static final long serialVersionUID = 0; + @SuppressWarnings("unchecked") // implementation is "fully variant" static Optional withType() { return (Optional) INSTANCE; @@ -41,8 +43,13 @@ final class Absent extends Optional { } @Override - public boolean isPresent() { - return false; + public Set asSet() { + return Collections.emptySet(); + } + + @Override + public boolean equals(@Nullable Object object) { + return object == this; } @Override @@ -51,8 +58,13 @@ final class Absent extends Optional { } @Override - public T or(T defaultValue) { - return checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)"); + public int hashCode() { + return 0x598df91c; + } + + @Override + public boolean isPresent() { + return false; } @SuppressWarnings("unchecked") // safe covariant cast @@ -66,31 +78,19 @@ final class Absent extends Optional { return checkNotNull(supplier.get(), "use Optional.orNull() instead of a Supplier that returns null"); } + @Override + public T or(T defaultValue) { + return checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)"); + } + @Override @Nullable public T orNull() { return null; } - @Override - public Set asSet() { - return Collections.emptySet(); - } - - @Override - public Optional transform(Function function) { - checkNotNull(function); - return Optional.absent(); - } - - @Override - public boolean equals(@Nullable Object object) { - return object == this; - } - - @Override - public int hashCode() { - return 0x598df91c; + private Object readResolve() { + return INSTANCE; } @Override @@ -98,9 +98,9 @@ final class Absent extends Optional { return "Optional.absent()"; } - private Object readResolve() { - return INSTANCE; + @Override + public Optional transform(Function function) { + checkNotNull(function); + return Optional.absent(); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/base/AbstractIterator.java b/src/main/java/com/google/common/base/AbstractIterator.java index 91dad3c3..919f860e 100644 --- a/src/main/java/com/google/common/base/AbstractIterator.java +++ b/src/main/java/com/google/common/base/AbstractIterator.java @@ -29,17 +29,17 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible abstract class AbstractIterator implements Iterator { - private State state = State.NOT_READY; - - protected AbstractIterator() { - } - private enum State { READY, NOT_READY, DONE, FAILED, } + private State state = State.NOT_READY; + private T next; + protected AbstractIterator() { + } + protected abstract T computeNext(); protected final T endOfData() { @@ -60,16 +60,6 @@ abstract class AbstractIterator implements Iterator { return tryToComputeNext(); } - private boolean tryToComputeNext() { - state = State.FAILED; // temporary pessimism - next = computeNext(); - if (state != State.DONE) { - state = State.READY; - return true; - } - return false; - } - @Override public final T next() { if (!hasNext()) { @@ -85,4 +75,14 @@ abstract class AbstractIterator implements Iterator { public final void remove() { throw new UnsupportedOperationException(); } + + private boolean tryToComputeNext() { + state = State.FAILED; // temporary pessimism + next = computeNext(); + if (state != State.DONE) { + state = State.READY; + return true; + } + return false; + } } diff --git a/src/main/java/com/google/common/base/Ascii.java b/src/main/java/com/google/common/base/Ascii.java index e9d85b02..501697f7 100644 --- a/src/main/java/com/google/common/base/Ascii.java +++ b/src/main/java/com/google/common/base/Ascii.java @@ -47,9 +47,6 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible public final class Ascii { - private Ascii() { - } - /* The ASCII control characters, per RFC 20. */ /** * Null ('\0'): The all-zeros character which may serve to accomplish time fill @@ -415,191 +412,6 @@ public final class Ascii { */ public static final char MAX = 127; - /** - * Returns a copy of the input string in which all - * {@linkplain #isUpperCase(char) uppercase ASCII characters} have been - * converted to lowercase. All other characters are copied without modification. - */ - public static String toLowerCase(String string) { - int length = string.length(); - for (int i = 0; i < length; i++) { - if (isUpperCase(string.charAt(i))) { - char[] chars = string.toCharArray(); - for (; i < length; i++) { - char c = chars[i]; - if (isUpperCase(c)) { - chars[i] = (char) (c ^ 0x20); - } - } - return String.valueOf(chars); - } - } - return string; - } - - /** - * Returns a copy of the input character sequence in which all - * {@linkplain #isUpperCase(char) uppercase ASCII characters} have been - * converted to lowercase. All other characters are copied without modification. - * - * @since 14.0 - */ - public static String toLowerCase(CharSequence chars) { - if (chars instanceof String) { - return toLowerCase((String) chars); - } - int length = chars.length(); - StringBuilder builder = new StringBuilder(length); - for (int i = 0; i < length; i++) { - builder.append(toLowerCase(chars.charAt(i))); - } - return builder.toString(); - } - - /** - * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII - * character} returns the lowercase equivalent. Otherwise returns the argument. - */ - public static char toLowerCase(char c) { - return isUpperCase(c) ? (char) (c ^ 0x20) : c; - } - - /** - * Returns a copy of the input string in which all - * {@linkplain #isLowerCase(char) lowercase ASCII characters} have been - * converted to uppercase. All other characters are copied without modification. - */ - public static String toUpperCase(String string) { - int length = string.length(); - for (int i = 0; i < length; i++) { - if (isLowerCase(string.charAt(i))) { - char[] chars = string.toCharArray(); - for (; i < length; i++) { - char c = chars[i]; - if (isLowerCase(c)) { - chars[i] = (char) (c & 0x5f); - } - } - return String.valueOf(chars); - } - } - return string; - } - - /** - * Returns a copy of the input character sequence in which all - * {@linkplain #isLowerCase(char) lowercase ASCII characters} have been - * converted to uppercase. All other characters are copied without modification. - * - * @since 14.0 - */ - public static String toUpperCase(CharSequence chars) { - if (chars instanceof String) { - return toUpperCase((String) chars); - } - int length = chars.length(); - StringBuilder builder = new StringBuilder(length); - for (int i = 0; i < length; i++) { - builder.append(toUpperCase(chars.charAt(i))); - } - return builder.toString(); - } - - /** - * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII - * character} returns the uppercase equivalent. Otherwise returns the argument. - */ - public static char toUpperCase(char c) { - return isLowerCase(c) ? (char) (c & 0x5f) : c; - } - - /** - * Indicates whether {@code c} is one of the twenty-six lowercase ASCII - * alphabetic characters between {@code 'a'} and {@code 'z'} inclusive. All - * others (including non-ASCII characters) return {@code false}. - */ - public static boolean isLowerCase(char c) { - // Note: This was benchmarked against the alternate expression "(char)(c - 'a') - // < 26" (Nov '13) - // and found to perform at least as well, or better. - return (c >= 'a') && (c <= 'z'); - } - - /** - * Indicates whether {@code c} is one of the twenty-six uppercase ASCII - * alphabetic characters between {@code 'A'} and {@code 'Z'} inclusive. All - * others (including non-ASCII characters) return {@code false}. - */ - public static boolean isUpperCase(char c) { - return (c >= 'A') && (c <= 'Z'); - } - - /** - * Truncates the given character sequence to the given maximum length. If the - * length of the sequence is greater than {@code maxLength}, the returned string - * will be exactly {@code maxLength} chars in length and will end with the given - * {@code truncationIndicator}. Otherwise, the sequence will be returned as a - * string with no changes to the content. - * - *

- * Examples: - * - *

-	 *    {@code
-	 *   Ascii.truncate("foobar", 7, "..."); // returns "foobar"
-	 *   Ascii.truncate("foobar", 5, "..."); // returns "fo..." }
-	 * 
- * - *

- * Note: This method may work with certain non-ASCII text but is - * not safe for use with arbitrary Unicode text. It is mostly intended for use - * with text that is known to be safe for use with it (such as all-ASCII text) - * and for simple debugging text. When using this method, consider the - * following: - * - *

    - *
  • it may split surrogate pairs
  • - *
  • it may split characters and combining characters
  • - *
  • it does not consider word boundaries
  • - *
  • if truncating for display to users, there are other considerations that - * must be taken into account
  • - *
  • the appropriate truncation indicator may be locale-dependent
  • - *
  • it is safe to use non-ASCII characters in the truncation indicator
  • - *
- * - * - * @throws IllegalArgumentException if {@code maxLength} is less than the length - * of {@code truncationIndicator} - * @since 16.0 - */ - @Beta - @CheckReturnValue - public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) { - checkNotNull(seq); - - // length to truncate the sequence to, not including the truncation indicator - int truncationLength = maxLength - truncationIndicator.length(); - - // in this worst case, this allows a maxLength equal to the length of the - // truncationIndicator, - // meaning that a string will be truncated to just the truncation indicator - // itself - checkArgument(truncationLength >= 0, "maxLength (%s) must be >= length of the truncation indicator (%s)", - maxLength, truncationIndicator.length()); - - if (seq.length() <= maxLength) { - String string = seq.toString(); - if (string.length() <= maxLength) { - return string; - } - // if the length of the toString() result was > maxLength for some reason, - // truncate that - seq = string; - } - - return new StringBuilder(maxLength).append(seq, 0, truncationLength).append(truncationIndicator).toString(); - } - /** * Indicates whether the contents of the given character sequences {@code s1} * and {@code s2} are equal, ignoring the case of any ASCII alphabetic @@ -666,4 +478,193 @@ public final class Ascii { // casting to char). return (char) ((c | 0x20) - 'a'); } + + /** + * Indicates whether {@code c} is one of the twenty-six lowercase ASCII + * alphabetic characters between {@code 'a'} and {@code 'z'} inclusive. All + * others (including non-ASCII characters) return {@code false}. + */ + public static boolean isLowerCase(char c) { + // Note: This was benchmarked against the alternate expression "(char)(c - 'a') + // < 26" (Nov '13) + // and found to perform at least as well, or better. + return (c >= 'a') && (c <= 'z'); + } + + /** + * Indicates whether {@code c} is one of the twenty-six uppercase ASCII + * alphabetic characters between {@code 'A'} and {@code 'Z'} inclusive. All + * others (including non-ASCII characters) return {@code false}. + */ + public static boolean isUpperCase(char c) { + return (c >= 'A') && (c <= 'Z'); + } + + /** + * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII + * character} returns the lowercase equivalent. Otherwise returns the argument. + */ + public static char toLowerCase(char c) { + return isUpperCase(c) ? (char) (c ^ 0x20) : c; + } + + /** + * Returns a copy of the input character sequence in which all + * {@linkplain #isUpperCase(char) uppercase ASCII characters} have been + * converted to lowercase. All other characters are copied without modification. + * + * @since 14.0 + */ + public static String toLowerCase(CharSequence chars) { + if (chars instanceof String) { + return toLowerCase((String) chars); + } + int length = chars.length(); + StringBuilder builder = new StringBuilder(length); + for (int i = 0; i < length; i++) { + builder.append(toLowerCase(chars.charAt(i))); + } + return builder.toString(); + } + + /** + * Returns a copy of the input string in which all + * {@linkplain #isUpperCase(char) uppercase ASCII characters} have been + * converted to lowercase. All other characters are copied without modification. + */ + public static String toLowerCase(String string) { + int length = string.length(); + for (int i = 0; i < length; i++) { + if (isUpperCase(string.charAt(i))) { + char[] chars = string.toCharArray(); + for (; i < length; i++) { + char c = chars[i]; + if (isUpperCase(c)) { + chars[i] = (char) (c ^ 0x20); + } + } + return String.valueOf(chars); + } + } + return string; + } + + /** + * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII + * character} returns the uppercase equivalent. Otherwise returns the argument. + */ + public static char toUpperCase(char c) { + return isLowerCase(c) ? (char) (c & 0x5f) : c; + } + + /** + * Returns a copy of the input character sequence in which all + * {@linkplain #isLowerCase(char) lowercase ASCII characters} have been + * converted to uppercase. All other characters are copied without modification. + * + * @since 14.0 + */ + public static String toUpperCase(CharSequence chars) { + if (chars instanceof String) { + return toUpperCase((String) chars); + } + int length = chars.length(); + StringBuilder builder = new StringBuilder(length); + for (int i = 0; i < length; i++) { + builder.append(toUpperCase(chars.charAt(i))); + } + return builder.toString(); + } + + /** + * Returns a copy of the input string in which all + * {@linkplain #isLowerCase(char) lowercase ASCII characters} have been + * converted to uppercase. All other characters are copied without modification. + */ + public static String toUpperCase(String string) { + int length = string.length(); + for (int i = 0; i < length; i++) { + if (isLowerCase(string.charAt(i))) { + char[] chars = string.toCharArray(); + for (; i < length; i++) { + char c = chars[i]; + if (isLowerCase(c)) { + chars[i] = (char) (c & 0x5f); + } + } + return String.valueOf(chars); + } + } + return string; + } + + /** + * Truncates the given character sequence to the given maximum length. If the + * length of the sequence is greater than {@code maxLength}, the returned string + * will be exactly {@code maxLength} chars in length and will end with the given + * {@code truncationIndicator}. Otherwise, the sequence will be returned as a + * string with no changes to the content. + * + *

+ * Examples: + * + *

+	 *    {@code
+	 * Ascii.truncate("foobar", 7, "..."); // returns "foobar"
+	 * Ascii.truncate("foobar", 5, "..."); // returns "fo..."
+	 * }
+	 * 
+ * + *

+ * Note: This method may work with certain non-ASCII text but is + * not safe for use with arbitrary Unicode text. It is mostly intended for use + * with text that is known to be safe for use with it (such as all-ASCII text) + * and for simple debugging text. When using this method, consider the + * following: + * + *

    + *
  • it may split surrogate pairs
  • + *
  • it may split characters and combining characters
  • + *
  • it does not consider word boundaries
  • + *
  • if truncating for display to users, there are other considerations that + * must be taken into account
  • + *
  • the appropriate truncation indicator may be locale-dependent
  • + *
  • it is safe to use non-ASCII characters in the truncation indicator
  • + *
+ * + * + * @throws IllegalArgumentException if {@code maxLength} is less than the length + * of {@code truncationIndicator} + * @since 16.0 + */ + @Beta + @CheckReturnValue + public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) { + checkNotNull(seq); + + // length to truncate the sequence to, not including the truncation indicator + int truncationLength = maxLength - truncationIndicator.length(); + + // in this worst case, this allows a maxLength equal to the length of the + // truncationIndicator, + // meaning that a string will be truncated to just the truncation indicator + // itself + checkArgument(truncationLength >= 0, "maxLength (%s) must be >= length of the truncation indicator (%s)", + maxLength, truncationIndicator.length()); + + if (seq.length() <= maxLength) { + String string = seq.toString(); + if (string.length() <= maxLength) { + return string; + } + // if the length of the toString() result was > maxLength for some reason, + // truncate that + seq = string; + } + + return new StringBuilder(maxLength).append(seq, 0, truncationLength).append(truncationIndicator).toString(); + } + + private Ascii() { + } } diff --git a/src/main/java/com/google/common/base/CaseFormat.java b/src/main/java/com/google/common/base/CaseFormat.java index 8f7eeb78..6ace8a57 100644 --- a/src/main/java/com/google/common/base/CaseFormat.java +++ b/src/main/java/com/google/common/base/CaseFormat.java @@ -38,11 +38,6 @@ public enum CaseFormat { * Hyphenated variable naming convention, e.g., "lower-hyphen". */ LOWER_HYPHEN(CharMatcher.is('-'), "-") { - @Override - String normalizeWord(String word) { - return Ascii.toLowerCase(word); - } - @Override String convert(CaseFormat format, String s) { if (format == LOWER_UNDERSCORE) { @@ -53,17 +48,17 @@ public enum CaseFormat { } return super.convert(format, s); } + + @Override + String normalizeWord(String word) { + return Ascii.toLowerCase(word); + } }, /** * C++ variable naming convention, e.g., "lower_underscore". */ LOWER_UNDERSCORE(CharMatcher.is('_'), "_") { - @Override - String normalizeWord(String word) { - return Ascii.toLowerCase(word); - } - @Override String convert(CaseFormat format, String s) { if (format == LOWER_HYPHEN) { @@ -74,6 +69,11 @@ public enum CaseFormat { } return super.convert(format, s); } + + @Override + String normalizeWord(String word) { + return Ascii.toLowerCase(word); + } }, /** @@ -100,11 +100,6 @@ public enum CaseFormat { * Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE". */ UPPER_UNDERSCORE(CharMatcher.is('_'), "_") { - @Override - String normalizeWord(String word) { - return Ascii.toUpperCase(word); - } - @Override String convert(CaseFormat format, String s) { if (format == LOWER_HYPHEN) { @@ -115,9 +110,65 @@ public enum CaseFormat { } return super.convert(format, s); } + + @Override + String normalizeWord(String word) { + return Ascii.toUpperCase(word); + } }; + private static final class StringConverter extends Converter implements Serializable { + + private static final long serialVersionUID = 0L; + private final CaseFormat sourceFormat; + + private final CaseFormat targetFormat; + + StringConverter(CaseFormat sourceFormat, CaseFormat targetFormat) { + this.sourceFormat = checkNotNull(sourceFormat); + this.targetFormat = checkNotNull(targetFormat); + } + + @Override + protected String doBackward(String s) { + // TODO(kevinb): remove null boilerplate (convert() will do it automatically) + return s == null ? null : targetFormat.to(sourceFormat, s); + } + + @Override + protected String doForward(String s) { + // TODO(kevinb): remove null boilerplate (convert() will do it automatically) + return s == null ? null : sourceFormat.to(targetFormat, s); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof StringConverter) { + StringConverter that = (StringConverter) object; + return sourceFormat.equals(that.sourceFormat) && targetFormat.equals(that.targetFormat); + } + return false; + } + + @Override + public int hashCode() { + return sourceFormat.hashCode() ^ targetFormat.hashCode(); + } + + @Override + public String toString() { + return sourceFormat + ".converterTo(" + targetFormat + ")"; + } + } + + private static String firstCharOnlyToUpper(String word) { + return (word.isEmpty()) ? word + : new StringBuilder(word.length()).append(Ascii.toUpperCase(word.charAt(0))) + .append(Ascii.toLowerCase(word.substring(1))).toString(); + } + private final CharMatcher wordBoundary; + private final String wordSeparator; CaseFormat(CharMatcher wordBoundary, String wordSeparator) { @@ -125,18 +176,6 @@ public enum CaseFormat { this.wordSeparator = wordSeparator; } - /** - * Converts the specified {@code String str} from this format to the specified - * {@code format}. A "best effort" approach is taken; if {@code str} does not - * conform to the assumed format, then the behavior of this method is undefined - * but we make a reasonable effort at converting anyway. - */ - public final String to(CaseFormat format, String str) { - checkNotNull(format); - checkNotNull(str); - return (format == this) ? str : convert(format, str); - } - /** * Enum values can override for performance reasons. */ @@ -170,59 +209,21 @@ public enum CaseFormat { return new StringConverter(this, targetFormat); } - private static final class StringConverter extends Converter implements Serializable { - - private final CaseFormat sourceFormat; - private final CaseFormat targetFormat; - - StringConverter(CaseFormat sourceFormat, CaseFormat targetFormat) { - this.sourceFormat = checkNotNull(sourceFormat); - this.targetFormat = checkNotNull(targetFormat); - } - - @Override - protected String doForward(String s) { - // TODO(kevinb): remove null boilerplate (convert() will do it automatically) - return s == null ? null : sourceFormat.to(targetFormat, s); - } - - @Override - protected String doBackward(String s) { - // TODO(kevinb): remove null boilerplate (convert() will do it automatically) - return s == null ? null : targetFormat.to(sourceFormat, s); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof StringConverter) { - StringConverter that = (StringConverter) object; - return sourceFormat.equals(that.sourceFormat) && targetFormat.equals(that.targetFormat); - } - return false; - } - - @Override - public int hashCode() { - return sourceFormat.hashCode() ^ targetFormat.hashCode(); - } - - @Override - public String toString() { - return sourceFormat + ".converterTo(" + targetFormat + ")"; - } - - private static final long serialVersionUID = 0L; - } - - abstract String normalizeWord(String word); - private String normalizeFirstWord(String word) { return (this == LOWER_CAMEL) ? Ascii.toLowerCase(word) : normalizeWord(word); } - private static String firstCharOnlyToUpper(String word) { - return (word.isEmpty()) ? word - : new StringBuilder(word.length()).append(Ascii.toUpperCase(word.charAt(0))) - .append(Ascii.toLowerCase(word.substring(1))).toString(); + abstract String normalizeWord(String word); + + /** + * Converts the specified {@code String str} from this format to the specified + * {@code format}. A "best effort" approach is taken; if {@code str} does not + * conform to the assumed format, then the behavior of this method is undefined + * but we make a reasonable effort at converting anyway. + */ + public final String to(CaseFormat format, String str) { + checkNotNull(format); + checkNotNull(str); + return (format == this) ? str : convert(format, str); } } diff --git a/src/main/java/com/google/common/base/CharMatcher.java b/src/main/java/com/google/common/base/CharMatcher.java index 97f9b3a4..9ddceb2a 100644 --- a/src/main/java/com/google/common/base/CharMatcher.java +++ b/src/main/java/com/google/common/base/CharMatcher.java @@ -66,6 +66,222 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(emulated = true) public abstract class CharMatcher implements Predicate { + private static class And extends CharMatcher { + final CharMatcher first; + final CharMatcher second; + + And(CharMatcher a, CharMatcher b) { + this(a, b, "CharMatcher.and(" + a + ", " + b + ")"); + } + + And(CharMatcher a, CharMatcher b, String description) { + super(description); + first = checkNotNull(a); + second = checkNotNull(b); + } + + @Override + public boolean matches(char c) { + return first.matches(c) && second.matches(c); + } + + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + BitSet tmp1 = new BitSet(); + first.setBits(tmp1); + BitSet tmp2 = new BitSet(); + second.setBits(tmp2); + tmp1.and(tmp2); + table.or(tmp1); + } + + @Override + CharMatcher withToString(String description) { + return new And(first, second, description); + } + } + + @GwtIncompatible("java.util.BitSet") + private static class BitSetMatcher extends FastMatcher { + private final BitSet table; + + private BitSetMatcher(BitSet table, String description) { + super(description); + if (table.length() + Long.SIZE < table.size()) { + table = (BitSet) table.clone(); + // If only we could actually call BitSet.trimToSize() ourselves... + } + this.table = table; + } + + @Override + public boolean matches(char c) { + return table.get(c); + } + + @Override + void setBits(BitSet bitSet) { + bitSet.or(table); + } + } + + /** + * A matcher for which precomputation will not yield any significant benefit. + */ + abstract static class FastMatcher extends CharMatcher { + FastMatcher() { + super(); + } + + FastMatcher(String description) { + super(description); + } + + @Override + public CharMatcher negate() { + return new NegatedFastMatcher(this); + } + + @Override + public final CharMatcher precomputed() { + return this; + } + } + + static final class NegatedFastMatcher extends NegatedMatcher { + NegatedFastMatcher(CharMatcher original) { + super(original); + } + + NegatedFastMatcher(String toString, CharMatcher original) { + super(toString, original); + } + + @Override + public final CharMatcher precomputed() { + return this; + } + + @Override + CharMatcher withToString(String description) { + return new NegatedFastMatcher(description, original); + } + } + + private static class NegatedMatcher extends CharMatcher { + final CharMatcher original; + + NegatedMatcher(CharMatcher original) { + this(original + ".negate()", original); + } + + NegatedMatcher(String toString, CharMatcher original) { + super(toString); + this.original = original; + } + + @Override + public int countIn(CharSequence sequence) { + return sequence.length() - original.countIn(sequence); + } + + @Override + public boolean matches(char c) { + return !original.matches(c); + } + + @Override + public boolean matchesAllOf(CharSequence sequence) { + return original.matchesNoneOf(sequence); + } + + @Override + public boolean matchesNoneOf(CharSequence sequence) { + return original.matchesAllOf(sequence); + } + + @Override + public CharMatcher negate() { + return original; + } + + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + BitSet tmp = new BitSet(); + original.setBits(tmp); + tmp.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); + table.or(tmp); + } + + @Override + CharMatcher withToString(String description) { + return new NegatedMatcher(description, original); + } + } + + private static class Or extends CharMatcher { + final CharMatcher first; + final CharMatcher second; + + Or(CharMatcher a, CharMatcher b) { + this(a, b, "CharMatcher.or(" + a + ", " + b + ")"); + } + + Or(CharMatcher a, CharMatcher b, String description) { + super(description); + first = checkNotNull(a); + second = checkNotNull(b); + } + + @Override + public boolean matches(char c) { + return first.matches(c) || second.matches(c); + } + + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + first.setBits(table); + second.setBits(table); + } + + @Override + CharMatcher withToString(String description) { + return new Or(first, second, description); + } + } + + private static class RangesMatcher extends CharMatcher { + private final char[] rangeStarts; + private final char[] rangeEnds; + + RangesMatcher(String description, char[] rangeStarts, char[] rangeEnds) { + super(description); + this.rangeStarts = rangeStarts; + this.rangeEnds = rangeEnds; + checkArgument(rangeStarts.length == rangeEnds.length); + for (int i = 0; i < rangeStarts.length; i++) { + checkArgument(rangeStarts[i] <= rangeEnds[i]); + if (i + 1 < rangeStarts.length) { + checkArgument(rangeEnds[i] < rangeStarts[i + 1]); + } + } + } + + @Override + public boolean matches(char c) { + int index = Arrays.binarySearch(rangeStarts, c); + if (index >= 0) { + return true; + } else { + index = ~index - 1; + return index >= 0 && c <= rangeEnds[index]; + } + } + } + // Constants /** * Determines whether a character is a breaking whitespace (that is, a @@ -110,41 +326,13 @@ public abstract class CharMatcher implements Predicate { */ public static final CharMatcher ASCII = inRange('\0', '\u007f', "CharMatcher.ASCII"); - private static class RangesMatcher extends CharMatcher { - private final char[] rangeStarts; - private final char[] rangeEnds; - - RangesMatcher(String description, char[] rangeStarts, char[] rangeEnds) { - super(description); - this.rangeStarts = rangeStarts; - this.rangeEnds = rangeEnds; - checkArgument(rangeStarts.length == rangeEnds.length); - for (int i = 0; i < rangeStarts.length; i++) { - checkArgument(rangeStarts[i] <= rangeEnds[i]); - if (i + 1 < rangeStarts.length) { - checkArgument(rangeEnds[i] < rangeStarts[i + 1]); - } - } - } - - @Override - public boolean matches(char c) { - int index = Arrays.binarySearch(rangeStarts, c); - if (index >= 0) { - return true; - } else { - index = ~index - 1; - return index >= 0 && c <= rangeEnds[index]; - } - } - } - // Must be in ascending order. private static final String ZEROES = new String(new char[] { '0', 0x0660, 0x06f0, 0x07c0, 0x0966, 0x09e6, 0x0a66, 0x0ae6, 0x0b66, 0x0be6, 0x0c66, 0x0ce6, 0x0d66, 0x0e50, 0x0ed0, 0x0f20, 0x1040, 0x1090, 0x17e0, 0x1810, 0x1946, 0x19d0, 0x1b50, 0x1bb0, 0x1c40, 0x1c50, 0xa620, 0xa8d0, 0xa900, 0xaa50, 0xff10 }); private static final String NINES; + static { StringBuilder builder = new StringBuilder(ZEROES.length()); for (int i = 0; i < ZEROES.length(); i++) { @@ -221,6 +409,8 @@ public abstract class CharMatcher implements Predicate { } }; + // Static factories + /** * Determines whether a character is an ISO control character as specified by * {@link Character#isISOControl(char)}. @@ -239,17 +429,6 @@ public abstract class CharMatcher implements Predicate { new char[] { 0x0020, 0x00a0, 0x00ad, 0x0604, 0x061c, 0x06dd, 0x070f, 0x1680, 0x180e, 0x200f, 0x202f, 0x2064, 0x2066, 0x2067, 0x2068, 0x2069, 0x206f, 0x3000, 0xf8ff, 0xfeff, 0xfff9, 0xfffb }); - private static String showCharacter(char c) { - String hex = "0123456789ABCDEF"; - char[] tmp = { '\\', 'u', '\0', '\0', '\0', '\0' }; - for (int i = 0; i < 4; i++) { - tmp[5 - i] = hex.charAt(c & 0xF); - c >>= 4; - } - return String.copyValueOf(tmp); - - } - /** * Determines whether a character is single-width (not double-width). When in * doubt, this matcher errs on the side of returning {@code false} (that is, it @@ -260,14 +439,26 @@ public abstract class CharMatcher implements Predicate { * keep it up to date. */ public static final CharMatcher SINGLE_WIDTH = new RangesMatcher("CharMatcher.SINGLE_WIDTH", - new char[] { 0x0000, 0x05be, 0x05d0, 0x05f3, 0x0600, 0x0750, 0x0e00, 0x1e00, 0x2100, 0xfb50, 0xfe70, 0xff61 }, - new char[] { 0x04f9, 0x05be, 0x05ea, 0x05f4, 0x06ff, 0x077f, 0x0e7f, 0x20af, 0x213a, 0xfdff, 0xfeff, 0xffdc }); + new char[] { 0x0000, 0x05be, 0x05d0, 0x05f3, 0x0600, 0x0750, 0x0e00, 0x1e00, 0x2100, 0xfb50, 0xfe70, + 0xff61 }, + new char[] { 0x04f9, 0x05be, 0x05ea, 0x05f4, 0x06ff, 0x077f, 0x0e7f, 0x20af, 0x213a, 0xfdff, 0xfeff, + 0xffdc }); /** Matches any character. */ public static final CharMatcher ANY = new FastMatcher("CharMatcher.ANY") { @Override - public boolean matches(char c) { - return true; + public CharMatcher and(CharMatcher other) { + return checkNotNull(other); + } + + @Override + public String collapseFrom(CharSequence sequence, char replacement) { + return (sequence.length() == 0) ? "" : String.valueOf(replacement); + } + + @Override + public int countIn(CharSequence sequence) { + return sequence.length(); } @Override @@ -287,6 +478,11 @@ public abstract class CharMatcher implements Predicate { return sequence.length() - 1; } + @Override + public boolean matches(char c) { + return true; + } + @Override public boolean matchesAllOf(CharSequence sequence) { checkNotNull(sequence); @@ -298,6 +494,17 @@ public abstract class CharMatcher implements Predicate { return sequence.length() == 0; } + @Override + public CharMatcher negate() { + return NONE; + } + + @Override + public CharMatcher or(CharMatcher other) { + checkNotNull(other); + return this; + } + @Override public String removeFrom(CharSequence sequence) { checkNotNull(sequence); @@ -320,44 +527,30 @@ public abstract class CharMatcher implements Predicate { return retval.toString(); } - @Override - public String collapseFrom(CharSequence sequence, char replacement) { - return (sequence.length() == 0) ? "" : String.valueOf(replacement); - } - @Override public String trimFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } - - @Override - public int countIn(CharSequence sequence) { - return sequence.length(); - } - - @Override - public CharMatcher and(CharMatcher other) { - return checkNotNull(other); - } - - @Override - public CharMatcher or(CharMatcher other) { - checkNotNull(other); - return this; - } - - @Override - public CharMatcher negate() { - return NONE; - } }; /** Matches no characters. */ public static final CharMatcher NONE = new FastMatcher("CharMatcher.NONE") { @Override - public boolean matches(char c) { - return false; + public CharMatcher and(CharMatcher other) { + checkNotNull(other); + return this; + } + + @Override + public String collapseFrom(CharSequence sequence, char replacement) { + return sequence.toString(); + } + + @Override + public int countIn(CharSequence sequence) { + checkNotNull(sequence); + return 0; } @Override @@ -379,6 +572,11 @@ public abstract class CharMatcher implements Predicate { return -1; } + @Override + public boolean matches(char c) { + return false; + } + @Override public boolean matchesAllOf(CharSequence sequence) { return sequence.length() == 0; @@ -390,6 +588,16 @@ public abstract class CharMatcher implements Predicate { return true; } + @Override + public CharMatcher negate() { + return ANY; + } + + @Override + public CharMatcher or(CharMatcher other) { + return checkNotNull(other); + } + @Override public String removeFrom(CharSequence sequence) { return sequence.toString(); @@ -406,11 +614,6 @@ public abstract class CharMatcher implements Predicate { return sequence.toString(); } - @Override - public String collapseFrom(CharSequence sequence, char replacement) { - return sequence.toString(); - } - @Override public String trimFrom(CharSequence sequence) { return sequence.toString(); @@ -425,109 +628,46 @@ public abstract class CharMatcher implements Predicate { public String trimTrailingFrom(CharSequence sequence) { return sequence.toString(); } - - @Override - public int countIn(CharSequence sequence) { - checkNotNull(sequence); - return 0; - } - - @Override - public CharMatcher and(CharMatcher other) { - checkNotNull(other); - return this; - } - - @Override - public CharMatcher or(CharMatcher other) { - return checkNotNull(other); - } - - @Override - public CharMatcher negate() { - return ANY; - } }; - // Static factories + private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1; + + static final String WHITESPACE_TABLE = new String(new char[] { 0x2002, 0x3000, '\r', 0x0085, 0x200A, 0x2005, 0x2000, + 0x3000, 0x2029, 0x000B, 0x3000, 0x2008, 0x2003, 0x205F, 0x3000, 0x1680, 0x0009, 0x0020, 0x2006, 0x2001, + 0x202F, 0x00A0, 0x000C, 0x2009, 0x3000, 0x2004, 0x3000, 0x3000, 0x2028, '\n', 0x2007, 0x3000 }); + + static final int WHITESPACE_MULTIPLIER = 1682554634; + + static final int WHITESPACE_SHIFT = Integer.numberOfLeadingZeros(WHITESPACE_TABLE.length() - 1); + + // Constructors /** - * Returns a {@code char} matcher that matches only one specified character. - */ - public static CharMatcher is(final char match) { - String description = "CharMatcher.is('" + showCharacter(match) + "')"; - return new FastMatcher(description) { - @Override - public boolean matches(char c) { - return c == match; - } - - @Override - public String replaceFrom(CharSequence sequence, char replacement) { - return sequence.toString().replace(match, replacement); - } - - @Override - public CharMatcher and(CharMatcher other) { - return other.matches(match) ? this : NONE; - } - - @Override - public CharMatcher or(CharMatcher other) { - return other.matches(match) ? other : super.or(other); - } - - @Override - public CharMatcher negate() { - return isNot(match); - } - - @GwtIncompatible("java.util.BitSet") - @Override - void setBits(BitSet table) { - table.set(match); - } - }; - } - - /** - * Returns a {@code char} matcher that matches any character except the one - * specified. + * Determines whether a character is whitespace according to the latest Unicode + * standard, as illustrated here. + * This is not the same definition used by other Java APIs. (See a comparison + * of several definitions of "whitespace".) * *

- * To negate another {@code CharMatcher}, use {@link #negate()}. + * Note: as the Unicode definition evolves, we will modify this constant + * to keep it up to date. */ - public static CharMatcher isNot(final char match) { - String description = "CharMatcher.isNot('" + showCharacter(match) + "')"; - return new FastMatcher(description) { - @Override - public boolean matches(char c) { - return c != match; - } + public static final CharMatcher WHITESPACE = new FastMatcher("WHITESPACE") { + @Override + public boolean matches(char c) { + return WHITESPACE_TABLE.charAt((WHITESPACE_MULTIPLIER * c) >>> WHITESPACE_SHIFT) == c; + } - @Override - public CharMatcher and(CharMatcher other) { - return other.matches(match) ? super.and(other) : other; + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + for (int i = 0; i < WHITESPACE_TABLE.length(); i++) { + table.set(WHITESPACE_TABLE.charAt(i)); } - - @Override - public CharMatcher or(CharMatcher other) { - return other.matches(match) ? ANY : this; - } - - @GwtIncompatible("java.util.BitSet") - @Override - void setBits(BitSet table) { - table.set(0, match); - table.set(match + 1, Character.MAX_VALUE + 1); - } - - @Override - public CharMatcher negate() { - return is(match); - } - }; - } + } + }; /** * Returns a {@code char} matcher that matches any character present in the @@ -569,30 +709,33 @@ public abstract class CharMatcher implements Predicate { }; } - private static CharMatcher isEither(final char match1, final char match2) { - String description = "CharMatcher.anyOf(\"" + showCharacter(match1) + showCharacter(match2) + "\")"; - return new FastMatcher(description) { + // Abstract methods + + /** + * Returns a matcher with identical behavior to the given + * {@link Character}-based predicate, but which operates on primitive + * {@code char} instances instead. + */ + public static CharMatcher forPredicate(final Predicate predicate) { + checkNotNull(predicate); + if (predicate instanceof CharMatcher) { + return (CharMatcher) predicate; + } + String description = "CharMatcher.forPredicate(" + predicate + ")"; + return new CharMatcher(description) { @Override - public boolean matches(char c) { - return c == match1 || c == match2; + public boolean apply(Character character) { + return predicate.apply(checkNotNull(character)); } - @GwtIncompatible("java.util.BitSet") @Override - void setBits(BitSet table) { - table.set(match1); - table.set(match2); + public boolean matches(char c) { + return predicate.apply(c); } }; } - /** - * Returns a {@code char} matcher that matches any character not present in the - * given character sequence. - */ - public static CharMatcher noneOf(CharSequence sequence) { - return anyOf(sequence).negate(); - } + // Non-static factories /** * Returns a {@code char} matcher that matches any character in a given range @@ -625,303 +768,112 @@ public abstract class CharMatcher implements Predicate { } /** - * Returns a matcher with identical behavior to the given - * {@link Character}-based predicate, but which operates on primitive - * {@code char} instances instead. + * Returns a {@code char} matcher that matches only one specified character. */ - public static CharMatcher forPredicate(final Predicate predicate) { - checkNotNull(predicate); - if (predicate instanceof CharMatcher) { - return (CharMatcher) predicate; - } - String description = "CharMatcher.forPredicate(" + predicate + ")"; - return new CharMatcher(description) { + public static CharMatcher is(final char match) { + String description = "CharMatcher.is('" + showCharacter(match) + "')"; + return new FastMatcher(description) { @Override - public boolean matches(char c) { - return predicate.apply(c); + public CharMatcher and(CharMatcher other) { + return other.matches(match) ? this : NONE; } @Override - public boolean apply(Character character) { - return predicate.apply(checkNotNull(character)); + public boolean matches(char c) { + return c == match; + } + + @Override + public CharMatcher negate() { + return isNot(match); + } + + @Override + public CharMatcher or(CharMatcher other) { + return other.matches(match) ? other : super.or(other); + } + + @Override + public String replaceFrom(CharSequence sequence, char replacement) { + return sequence.toString().replace(match, replacement); + } + + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + table.set(match); } }; } - // State - final String description; + private static CharMatcher isEither(final char match1, final char match2) { + String description = "CharMatcher.anyOf(\"" + showCharacter(match1) + showCharacter(match2) + "\")"; + return new FastMatcher(description) { + @Override + public boolean matches(char c) { + return c == match1 || c == match2; + } - // Constructors - - /** - * Sets the {@code toString()} from the given description. - */ - CharMatcher(String description) { - this.description = description; + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + table.set(match1); + table.set(match2); + } + }; } /** - * Constructor for use by subclasses. When subclassing, you may want to override - * {@code toString()} to provide a useful description. - */ - protected CharMatcher() { - description = super.toString(); - } - - // Abstract methods - - /** Determines a true or false value for the given character. */ - public abstract boolean matches(char c); - - // Non-static factories - - /** - * Returns a matcher that matches any character not matched by this matcher. - */ - public CharMatcher negate() { - return new NegatedMatcher(this); - } - - private static class NegatedMatcher extends CharMatcher { - final CharMatcher original; - - NegatedMatcher(String toString, CharMatcher original) { - super(toString); - this.original = original; - } - - NegatedMatcher(CharMatcher original) { - this(original + ".negate()", original); - } - - @Override - public boolean matches(char c) { - return !original.matches(c); - } - - @Override - public boolean matchesAllOf(CharSequence sequence) { - return original.matchesNoneOf(sequence); - } - - @Override - public boolean matchesNoneOf(CharSequence sequence) { - return original.matchesAllOf(sequence); - } - - @Override - public int countIn(CharSequence sequence) { - return sequence.length() - original.countIn(sequence); - } - - @GwtIncompatible("java.util.BitSet") - @Override - void setBits(BitSet table) { - BitSet tmp = new BitSet(); - original.setBits(tmp); - tmp.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); - table.or(tmp); - } - - @Override - public CharMatcher negate() { - return original; - } - - @Override - CharMatcher withToString(String description) { - return new NegatedMatcher(description, original); - } - } - - /** - * Returns a matcher that matches any character matched by both this matcher and - * {@code other}. - */ - public CharMatcher and(CharMatcher other) { - return new And(this, checkNotNull(other)); - } - - private static class And extends CharMatcher { - final CharMatcher first; - final CharMatcher second; - - And(CharMatcher a, CharMatcher b) { - this(a, b, "CharMatcher.and(" + a + ", " + b + ")"); - } - - And(CharMatcher a, CharMatcher b, String description) { - super(description); - first = checkNotNull(a); - second = checkNotNull(b); - } - - @Override - public boolean matches(char c) { - return first.matches(c) && second.matches(c); - } - - @GwtIncompatible("java.util.BitSet") - @Override - void setBits(BitSet table) { - BitSet tmp1 = new BitSet(); - first.setBits(tmp1); - BitSet tmp2 = new BitSet(); - second.setBits(tmp2); - tmp1.and(tmp2); - table.or(tmp1); - } - - @Override - CharMatcher withToString(String description) { - return new And(first, second, description); - } - } - - /** - * Returns a matcher that matches any character matched by either this matcher - * or {@code other}. - */ - public CharMatcher or(CharMatcher other) { - return new Or(this, checkNotNull(other)); - } - - private static class Or extends CharMatcher { - final CharMatcher first; - final CharMatcher second; - - Or(CharMatcher a, CharMatcher b, String description) { - super(description); - first = checkNotNull(a); - second = checkNotNull(b); - } - - Or(CharMatcher a, CharMatcher b) { - this(a, b, "CharMatcher.or(" + a + ", " + b + ")"); - } - - @GwtIncompatible("java.util.BitSet") - @Override - void setBits(BitSet table) { - first.setBits(table); - second.setBits(table); - } - - @Override - public boolean matches(char c) { - return first.matches(c) || second.matches(c); - } - - @Override - CharMatcher withToString(String description) { - return new Or(first, second, description); - } - } - - /** - * Returns a {@code char} matcher functionally equivalent to this one, but which - * may be faster to query than the original; your mileage may vary. - * Precomputation takes time and is likely to be worthwhile only if the - * precomputed matcher is queried many thousands of times. + * Returns a {@code char} matcher that matches any character except the one + * specified. * *

- * This method has no effect (returns {@code this}) when called in GWT: it's - * unclear whether a precomputed matcher is faster, but it certainly consumes - * more memory, which doesn't seem like a worthwhile tradeoff in a browser. + * To negate another {@code CharMatcher}, use {@link #negate()}. */ - public CharMatcher precomputed() { - return Platform.precomputeCharMatcher(this); + public static CharMatcher isNot(final char match) { + String description = "CharMatcher.isNot('" + showCharacter(match) + "')"; + return new FastMatcher(description) { + @Override + public CharMatcher and(CharMatcher other) { + return other.matches(match) ? super.and(other) : other; + } + + @Override + public boolean matches(char c) { + return c != match; + } + + @Override + public CharMatcher negate() { + return is(match); + } + + @Override + public CharMatcher or(CharMatcher other) { + return other.matches(match) ? ANY : this; + } + + @GwtIncompatible("java.util.BitSet") + @Override + void setBits(BitSet table) { + table.set(0, match); + table.set(match + 1, Character.MAX_VALUE + 1); + } + }; + } + + @GwtIncompatible("SmallCharMatcher") + private static boolean isSmall(int totalCharacters, int tableLength) { + return totalCharacters <= SmallCharMatcher.MAX_SIZE && tableLength > (totalCharacters * 4 * Character.SIZE); + // err on the side of BitSetMatcher } /** - * Subclasses should provide a new CharMatcher with the same characteristics as - * {@code this}, but with their {@code toString} method overridden with the new - * description. - * - *

- * This is unsupported by default. + * Returns a {@code char} matcher that matches any character not present in the + * given character sequence. */ - CharMatcher withToString(String description) { - throw new UnsupportedOperationException(); - } - - private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1; - - /** - * This is the actual implementation of {@link #precomputed}, but we bounce - * calls through a method on {@link Platform} so that we can have different - * behavior in GWT. - * - *

- * This implementation tries to be smart in a number of ways. It recognizes - * cases where the negation is cheaper to precompute than the matcher itself; it - * tries to build small hash tables for matchers that only match a few - * characters, and so on. In the worst-case scenario, it constructs an - * eight-kilobyte bit array and queries that. In many situations this produces a - * matcher which is faster to query than the original. - */ - @GwtIncompatible("java.util.BitSet") - CharMatcher precomputedInternal() { - final BitSet table = new BitSet(); - setBits(table); - int totalCharacters = table.cardinality(); - if (totalCharacters * 2 <= DISTINCT_CHARS) { - return precomputedPositive(totalCharacters, table, description); - } else { - // TODO(user): is it worth it to worry about the last character of large - // matchers? - table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); - int negatedCharacters = DISTINCT_CHARS - totalCharacters; - String suffix = ".negate()"; - String negatedDescription = description.endsWith(suffix) - ? description.substring(0, description.length() - suffix.length()) - : description + suffix; - return new NegatedFastMatcher(toString(), - precomputedPositive(negatedCharacters, table, negatedDescription)); - } - } - - /** - * A matcher for which precomputation will not yield any significant benefit. - */ - abstract static class FastMatcher extends CharMatcher { - FastMatcher() { - super(); - } - - FastMatcher(String description) { - super(description); - } - - @Override - public final CharMatcher precomputed() { - return this; - } - - @Override - public CharMatcher negate() { - return new NegatedFastMatcher(this); - } - } - - static final class NegatedFastMatcher extends NegatedMatcher { - NegatedFastMatcher(CharMatcher original) { - super(original); - } - - NegatedFastMatcher(String toString, CharMatcher original) { - super(toString, original); - } - - @Override - public final CharMatcher precomputed() { - return this; - } - - @Override - CharMatcher withToString(String description) { - return new NegatedFastMatcher(description, original); - } + public static CharMatcher noneOf(CharSequence sequence) { + return anyOf(sequence).negate(); } /** @@ -945,105 +897,129 @@ public abstract class CharMatcher implements Predicate { } } - @GwtIncompatible("SmallCharMatcher") - private static boolean isSmall(int totalCharacters, int tableLength) { - return totalCharacters <= SmallCharMatcher.MAX_SIZE && tableLength > (totalCharacters * 4 * Character.SIZE); - // err on the side of BitSetMatcher + private static String showCharacter(char c) { + String hex = "0123456789ABCDEF"; + char[] tmp = { '\\', 'u', '\0', '\0', '\0', '\0' }; + for (int i = 0; i < 4; i++) { + tmp[5 - i] = hex.charAt(c & 0xF); + c >>= 4; + } + return String.copyValueOf(tmp); + } - @GwtIncompatible("java.util.BitSet") - private static class BitSetMatcher extends FastMatcher { - private final BitSet table; + // State + final String description; - private BitSetMatcher(BitSet table, String description) { - super(description); - if (table.length() + Long.SIZE < table.size()) { - table = (BitSet) table.clone(); - // If only we could actually call BitSet.trimToSize() ourselves... - } - this.table = table; - } - - @Override - public boolean matches(char c) { - return table.get(c); - } - - @Override - void setBits(BitSet bitSet) { - bitSet.or(table); - } + /** + * Constructor for use by subclasses. When subclassing, you may want to override + * {@code toString()} to provide a useful description. + */ + protected CharMatcher() { + description = super.toString(); } /** - * Sets bits in {@code table} matched by this matcher. + * Sets the {@code toString()} from the given description. */ - @GwtIncompatible("java.util.BitSet") - void setBits(BitSet table) { - for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) { - if (matches((char) c)) { - table.set(c); + CharMatcher(String description) { + this.description = description; + } + + /** + * Returns a matcher that matches any character matched by both this matcher and + * {@code other}. + */ + public CharMatcher and(CharMatcher other) { + return new And(this, checkNotNull(other)); + } + + /** + * @deprecated Provided only to satisfy the {@link Predicate} interface; use + * {@link #matches} instead. + */ + @Deprecated + @Override + public boolean apply(Character character) { + return matches(character); + } + + /** + * Returns a string copy of the input character sequence, with each group of + * consecutive characters that match this matcher replaced by a single + * replacement character. For example: + * + *

+	 *    {@code
+	 *
+	 * CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')
+	 * }
+	 * 
+ * + * ... returns {@code "b-p-r"}. + * + *

+ * The default implementation uses {@link #indexIn(CharSequence)} to find the + * first matching character, then iterates the remainder of the sequence calling + * {@link #matches(char)} for each character. + * + * @param sequence the character sequence to replace matching groups of + * characters in + * @param replacement the character to append to the result string in place of + * each group of matching characters in {@code sequence} + * @return the new string + */ + @CheckReturnValue + public String collapseFrom(CharSequence sequence, char replacement) { + // This implementation avoids unnecessary allocation. + int len = sequence.length(); + for (int i = 0; i < len; i++) { + char c = sequence.charAt(i); + if (matches(c)) { + if (c == replacement && (i == len - 1 || !matches(sequence.charAt(i + 1)))) { + // a no-op replacement + i++; + } else { + StringBuilder builder = new StringBuilder(len).append(sequence.subSequence(0, i)) + .append(replacement); + return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true); + } } } + // no replacement needed + return sequence.toString(); + } + + /** + * Returns the number of matching characters found in a character sequence. + */ + public int countIn(CharSequence sequence) { + int count = 0; + for (int i = 0; i < sequence.length(); i++) { + if (matches(sequence.charAt(i))) { + count++; + } + } + return count; } // Text processing routines - /** - * Returns {@code true} if a character sequence contains at least one matching - * character. Equivalent to {@code !matchesNoneOf(sequence)}. - * - *

- * The default implementation iterates over the sequence, invoking - * {@link #matches} for each character, until this returns {@code true} or the - * end is reached. - * - * @param sequence the character sequence to examine, possibly empty - * @return {@code true} if this matcher matches at least one character in the - * sequence - * @since 8.0 - */ - public boolean matchesAnyOf(CharSequence sequence) { - return !matchesNoneOf(sequence); - } - - /** - * Returns {@code true} if a character sequence contains only matching - * characters. - * - *

- * The default implementation iterates over the sequence, invoking - * {@link #matches} for each character, until this returns {@code false} or the - * end is reached. - * - * @param sequence the character sequence to examine, possibly empty - * @return {@code true} if this matcher matches every character in the sequence, - * including when the sequence is empty - */ - public boolean matchesAllOf(CharSequence sequence) { - for (int i = sequence.length() - 1; i >= 0; i--) { - if (!matches(sequence.charAt(i))) { - return false; + private String finishCollapseFrom(CharSequence sequence, int start, int end, char replacement, + StringBuilder builder, boolean inMatchingGroup) { + for (int i = start; i < end; i++) { + char c = sequence.charAt(i); + if (matches(c)) { + if (!inMatchingGroup) { + builder.append(replacement); + inMatchingGroup = true; + } + } else { + builder.append(c); + inMatchingGroup = false; } } - return true; - } - - /** - * Returns {@code true} if a character sequence contains no matching characters. - * Equivalent to {@code !matchesAnyOf(sequence)}. - * - *

- * The default implementation iterates over the sequence, invoking - * {@link #matches} for each character, until this returns {@code false} or the - * end is reached. - * - * @param sequence the character sequence to examine, possibly empty - * @return {@code true} if this matcher matches every character in the sequence, - * including when the sequence is empty - */ - public boolean matchesNoneOf(CharSequence sequence) { - return indexIn(sequence) == -1; + return builder.toString(); } /** @@ -1117,17 +1093,128 @@ public abstract class CharMatcher implements Predicate { return -1; } + /** Determines a true or false value for the given character. */ + public abstract boolean matches(char c); + /** - * Returns the number of matching characters found in a character sequence. + * Returns {@code true} if a character sequence contains only matching + * characters. + * + *

+ * The default implementation iterates over the sequence, invoking + * {@link #matches} for each character, until this returns {@code false} or the + * end is reached. + * + * @param sequence the character sequence to examine, possibly empty + * @return {@code true} if this matcher matches every character in the sequence, + * including when the sequence is empty */ - public int countIn(CharSequence sequence) { - int count = 0; - for (int i = 0; i < sequence.length(); i++) { - if (matches(sequence.charAt(i))) { - count++; + public boolean matchesAllOf(CharSequence sequence) { + for (int i = sequence.length() - 1; i >= 0; i--) { + if (!matches(sequence.charAt(i))) { + return false; } } - return count; + return true; + } + + /** + * Returns {@code true} if a character sequence contains at least one matching + * character. Equivalent to {@code !matchesNoneOf(sequence)}. + * + *

+ * The default implementation iterates over the sequence, invoking + * {@link #matches} for each character, until this returns {@code true} or the + * end is reached. + * + * @param sequence the character sequence to examine, possibly empty + * @return {@code true} if this matcher matches at least one character in the + * sequence + * @since 8.0 + */ + public boolean matchesAnyOf(CharSequence sequence) { + return !matchesNoneOf(sequence); + } + + /** + * Returns {@code true} if a character sequence contains no matching characters. + * Equivalent to {@code !matchesAnyOf(sequence)}. + * + *

+ * The default implementation iterates over the sequence, invoking + * {@link #matches} for each character, until this returns {@code false} or the + * end is reached. + * + * @param sequence the character sequence to examine, possibly empty + * @return {@code true} if this matcher matches every character in the sequence, + * including when the sequence is empty + */ + public boolean matchesNoneOf(CharSequence sequence) { + return indexIn(sequence) == -1; + } + + /** + * Returns a matcher that matches any character not matched by this matcher. + */ + public CharMatcher negate() { + return new NegatedMatcher(this); + } + + /** + * Returns a matcher that matches any character matched by either this matcher + * or {@code other}. + */ + public CharMatcher or(CharMatcher other) { + return new Or(this, checkNotNull(other)); + } + + /** + * Returns a {@code char} matcher functionally equivalent to this one, but which + * may be faster to query than the original; your mileage may vary. + * Precomputation takes time and is likely to be worthwhile only if the + * precomputed matcher is queried many thousands of times. + * + *

+ * This method has no effect (returns {@code this}) when called in GWT: it's + * unclear whether a precomputed matcher is faster, but it certainly consumes + * more memory, which doesn't seem like a worthwhile tradeoff in a browser. + */ + public CharMatcher precomputed() { + return Platform.precomputeCharMatcher(this); + } + + /** + * This is the actual implementation of {@link #precomputed}, but we bounce + * calls through a method on {@link Platform} so that we can have different + * behavior in GWT. + * + *

+ * This implementation tries to be smart in a number of ways. It recognizes + * cases where the negation is cheaper to precompute than the matcher itself; it + * tries to build small hash tables for matchers that only match a few + * characters, and so on. In the worst-case scenario, it constructs an + * eight-kilobyte bit array and queries that. In many situations this produces a + * matcher which is faster to query than the original. + */ + @GwtIncompatible("java.util.BitSet") + CharMatcher precomputedInternal() { + final BitSet table = new BitSet(); + setBits(table); + int totalCharacters = table.cardinality(); + if (totalCharacters * 2 <= DISTINCT_CHARS) { + return precomputedPositive(totalCharacters, table, description); + } else { + // TODO(user): is it worth it to worry about the last character of large + // matchers? + table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); + int negatedCharacters = DISTINCT_CHARS - totalCharacters; + String suffix = ".negate()"; + String negatedDescription = description.endsWith(suffix) + ? description.substring(0, description.length() - suffix.length()) + : description + suffix; + return new NegatedFastMatcher(toString(), + precomputedPositive(negatedCharacters, table, negatedDescription)); + } } /** @@ -1137,7 +1224,8 @@ public abstract class CharMatcher implements Predicate { *

 	 *    {@code
 	 *
-	 *   CharMatcher.is('a').removeFrom("bazaar")}
+	 * CharMatcher.is('a').removeFrom("bazaar")
+	 * }
 	 * 
* * ... returns {@code "bzr"}. @@ -1171,23 +1259,6 @@ public abstract class CharMatcher implements Predicate { return new String(chars, 0, pos - spread); } - /** - * Returns a string containing all matching characters of a character sequence, - * in order. For example: - * - *
-	 *    {@code
-	 *
-	 *   CharMatcher.is('a').retainFrom("bazaar")}
-	 * 
- * - * ... returns {@code "aaa"}. - */ - @CheckReturnValue - public String retainFrom(CharSequence sequence) { - return negate().removeFrom(sequence); - } - /** * Returns a string copy of the input character sequence, with each character * that matches this matcher replaced by a given replacement character. For @@ -1196,7 +1267,8 @@ public abstract class CharMatcher implements Predicate { *
 	 *    {@code
 	 *
-	 *   CharMatcher.is('a').replaceFrom("radar", 'o')}
+	 * CharMatcher.is('a').replaceFrom("radar", 'o')
+	 * }
 	 * 
* * ... returns {@code "rodor"}. @@ -1236,7 +1308,8 @@ public abstract class CharMatcher implements Predicate { *
 	 *    {@code
 	 *
-	 *   CharMatcher.is('a').replaceFrom("yaha", "oo")}
+	 * CharMatcher.is('a').replaceFrom("yaha", "oo")
+	 * }
 	 * 
* * ... returns {@code "yoohoo"}. @@ -1281,6 +1354,67 @@ public abstract class CharMatcher implements Predicate { return buf.toString(); } + /** + * Returns a string containing all matching characters of a character sequence, + * in order. For example: + * + *
+	 *    {@code
+	 *
+	 * CharMatcher.is('a').retainFrom("bazaar")
+	 * }
+	 * 
+ * + * ... returns {@code "aaa"}. + */ + @CheckReturnValue + public String retainFrom(CharSequence sequence) { + return negate().removeFrom(sequence); + } + + /** + * Sets bits in {@code table} matched by this matcher. + */ + @GwtIncompatible("java.util.BitSet") + void setBits(BitSet table) { + for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) { + if (matches((char) c)) { + table.set(c); + } + } + } + + /** + * Returns a string representation of this {@code CharMatcher}, such as + * {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}. + */ + @Override + public String toString() { + return description; + } + + /** + * Collapses groups of matching characters exactly as {@link #collapseFrom} + * does, except that groups of matching characters at the start or end of the + * sequence are removed without replacement. + */ + @CheckReturnValue + public String trimAndCollapseFrom(CharSequence sequence, char replacement) { + // This implementation avoids unnecessary allocation. + int len = sequence.length(); + int first; + int last; + + for (first = 0; first < len && matches(sequence.charAt(first)); first++) { + } + for (last = len - 1; last > first && matches(sequence.charAt(last)); last--) { + } + + return (first == 0 && last == len - 1) ? collapseFrom(sequence, replacement) + : finishCollapseFrom(sequence, first, last + 1, replacement, new StringBuilder(last + 1 - first), + false); + } + /** * Returns a substring of the input character sequence that omits all characters * this matcher matches from the beginning and from the end of the string. For @@ -1289,7 +1423,8 @@ public abstract class CharMatcher implements Predicate { *
 	 *    {@code
 	 *
-	 *   CharMatcher.anyOf("ab").trimFrom("abacatbab")}
+	 * CharMatcher.anyOf("ab").trimFrom("abacatbab")
+	 * }
 	 * 
* * ... returns {@code "cat"}. @@ -1300,7 +1435,8 @@ public abstract class CharMatcher implements Predicate { *
 	 *    {@code
 	 *
-	 *   CharMatcher.inRange('\0', ' ').trimFrom(str)}
+	 * CharMatcher.inRange('\0', ' ').trimFrom(str)
+	 * }
 	 * 
* * ... is equivalent to {@link String#trim()}. @@ -1332,7 +1468,8 @@ public abstract class CharMatcher implements Predicate { *
 	 *  {@code
 	 *
-	 *   CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")}
+	 * CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")
+	 * }
 	 * 
* * ... returns {@code "catbab"}. @@ -1355,7 +1492,8 @@ public abstract class CharMatcher implements Predicate { *
 	 *  {@code
 	 *
-	 *   CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")}
+	 * CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")
+	 * }
 	 * 
* * ... returns {@code "abacat"}. @@ -1372,138 +1510,14 @@ public abstract class CharMatcher implements Predicate { } /** - * Returns a string copy of the input character sequence, with each group of - * consecutive characters that match this matcher replaced by a single - * replacement character. For example: - * - *
-	 *    {@code
-	 *
-	 *   CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')}
-	 * 
- * - * ... returns {@code "b-p-r"}. + * Subclasses should provide a new CharMatcher with the same characteristics as + * {@code this}, but with their {@code toString} method overridden with the new + * description. * *

- * The default implementation uses {@link #indexIn(CharSequence)} to find the - * first matching character, then iterates the remainder of the sequence calling - * {@link #matches(char)} for each character. - * - * @param sequence the character sequence to replace matching groups of - * characters in - * @param replacement the character to append to the result string in place of - * each group of matching characters in {@code sequence} - * @return the new string + * This is unsupported by default. */ - @CheckReturnValue - public String collapseFrom(CharSequence sequence, char replacement) { - // This implementation avoids unnecessary allocation. - int len = sequence.length(); - for (int i = 0; i < len; i++) { - char c = sequence.charAt(i); - if (matches(c)) { - if (c == replacement && (i == len - 1 || !matches(sequence.charAt(i + 1)))) { - // a no-op replacement - i++; - } else { - StringBuilder builder = new StringBuilder(len).append(sequence.subSequence(0, i)) - .append(replacement); - return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true); - } - } - } - // no replacement needed - return sequence.toString(); + CharMatcher withToString(String description) { + throw new UnsupportedOperationException(); } - - /** - * Collapses groups of matching characters exactly as {@link #collapseFrom} - * does, except that groups of matching characters at the start or end of the - * sequence are removed without replacement. - */ - @CheckReturnValue - public String trimAndCollapseFrom(CharSequence sequence, char replacement) { - // This implementation avoids unnecessary allocation. - int len = sequence.length(); - int first; - int last; - - for (first = 0; first < len && matches(sequence.charAt(first)); first++) { - } - for (last = len - 1; last > first && matches(sequence.charAt(last)); last--) { - } - - return (first == 0 && last == len - 1) ? collapseFrom(sequence, replacement) - : finishCollapseFrom(sequence, first, last + 1, replacement, new StringBuilder(last + 1 - first), - false); - } - - private String finishCollapseFrom(CharSequence sequence, int start, int end, char replacement, - StringBuilder builder, boolean inMatchingGroup) { - for (int i = start; i < end; i++) { - char c = sequence.charAt(i); - if (matches(c)) { - if (!inMatchingGroup) { - builder.append(replacement); - inMatchingGroup = true; - } - } else { - builder.append(c); - inMatchingGroup = false; - } - } - return builder.toString(); - } - - /** - * @deprecated Provided only to satisfy the {@link Predicate} interface; use - * {@link #matches} instead. - */ - @Deprecated - @Override - public boolean apply(Character character) { - return matches(character); - } - - /** - * Returns a string representation of this {@code CharMatcher}, such as - * {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}. - */ - @Override - public String toString() { - return description; - } - - static final String WHITESPACE_TABLE = new String(new char[] { 0x2002, 0x3000, '\r', 0x0085, 0x200A, 0x2005, 0x2000, - 0x3000, 0x2029, 0x000B, 0x3000, 0x2008, 0x2003, 0x205F, 0x3000, 0x1680, 0x0009, 0x0020, 0x2006, 0x2001, - 0x202F, 0x00A0, 0x000C, 0x2009, 0x3000, 0x2004, 0x3000, 0x3000, 0x2028, '\n', 0x2007, 0x3000 }); - static final int WHITESPACE_MULTIPLIER = 1682554634; - static final int WHITESPACE_SHIFT = Integer.numberOfLeadingZeros(WHITESPACE_TABLE.length() - 1); - - /** - * Determines whether a character is whitespace according to the latest Unicode - * standard, as illustrated here. - * This is not the same definition used by other Java APIs. (See a comparison - * of several definitions of "whitespace".) - * - *

- * Note: as the Unicode definition evolves, we will modify this constant - * to keep it up to date. - */ - public static final CharMatcher WHITESPACE = new FastMatcher("WHITESPACE") { - @Override - public boolean matches(char c) { - return WHITESPACE_TABLE.charAt((WHITESPACE_MULTIPLIER * c) >>> WHITESPACE_SHIFT) == c; - } - - @GwtIncompatible("java.util.BitSet") - @Override - void setBits(BitSet table) { - for (int i = 0; i < WHITESPACE_TABLE.length(); i++) { - table.set(WHITESPACE_TABLE.charAt(i)); - } - } - }; } diff --git a/src/main/java/com/google/common/base/Charsets.java b/src/main/java/com/google/common/base/Charsets.java index 1d06b8d1..fb81d011 100644 --- a/src/main/java/com/google/common/base/Charsets.java +++ b/src/main/java/com/google/common/base/Charsets.java @@ -38,15 +38,15 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(emulated = true) public final class Charsets { - private Charsets() { - } - /** * UTF-8: eight-bit UCS Transformation Format. * */ public static final Charset UTF_8 = Charset.forName("UTF-8"); + private Charsets() { + } + /* * Please do not add new Charset references to this class, unless those * character encodings are part of the set required to be supported by all Java diff --git a/src/main/java/com/google/common/base/Converter.java b/src/main/java/com/google/common/base/Converter.java index 481a998a..baa90238 100644 --- a/src/main/java/com/google/common/base/Converter.java +++ b/src/main/java/com/google/common/base/Converter.java @@ -109,6 +109,251 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible public abstract class Converter implements Function { + private static final class ConverterComposition extends Converter implements Serializable { + private static final long serialVersionUID = 0L; + final Converter first; + + final Converter second; + + /* + * These gymnastics are a little confusing. Basically this class has neither + * legacy nor non-legacy behavior; it just needs to let the behaviors of the + * backing converters shine through (which might even differ from each other!). + * So, we override the correctedDo* methods, after which the do* methods should + * never be reached. + */ + + ConverterComposition(Converter first, Converter second) { + this.first = first; + this.second = second; + } + + @Override + @Nullable + A correctedDoBackward(@Nullable C c) { + return first.correctedDoBackward(second.correctedDoBackward(c)); + } + + @Override + @Nullable + C correctedDoForward(@Nullable A a) { + return second.correctedDoForward(first.correctedDoForward(a)); + } + + @Override + protected A doBackward(C c) { + throw new AssertionError(); + } + + @Override + protected C doForward(A a) { + throw new AssertionError(); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof ConverterComposition) { + ConverterComposition that = (ConverterComposition) object; + return this.first.equals(that.first) && this.second.equals(that.second); + } + return false; + } + + @Override + public int hashCode() { + return 31 * first.hashCode() + second.hashCode(); + } + + @Override + public String toString() { + return first + ".andThen(" + second + ")"; + } + } + + private static final class FunctionBasedConverter extends Converter implements Serializable { + private final Function forwardFunction; + private final Function backwardFunction; + + private FunctionBasedConverter(Function forwardFunction, + Function backwardFunction) { + this.forwardFunction = checkNotNull(forwardFunction); + this.backwardFunction = checkNotNull(backwardFunction); + } + + @Override + protected A doBackward(B b) { + return backwardFunction.apply(b); + } + + @Override + protected B doForward(A a) { + return forwardFunction.apply(a); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof FunctionBasedConverter) { + FunctionBasedConverter that = (FunctionBasedConverter) object; + return this.forwardFunction.equals(that.forwardFunction) + && this.backwardFunction.equals(that.backwardFunction); + } + return false; + } + + @Override + public int hashCode() { + return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); + } + + @Override + public String toString() { + return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; + } + } + + /** + * A converter that always converts or reverses an object to itself. Note that T + * is now a "pass-through type". + */ + private static final class IdentityConverter extends Converter implements Serializable { + static final IdentityConverter INSTANCE = new IdentityConverter(); + + private static final long serialVersionUID = 0L; + + @Override + public Converter andThen(Converter otherConverter) { + return checkNotNull(otherConverter, "otherConverter"); + } + + @Override + protected T doBackward(T t) { + return t; + } + + @Override + protected T doForward(T t) { + return t; + } + + /* + * We *could* override convertAll() to return its input, but it's a rather + * pointless optimization and opened up a weird type-safety problem. + */ + + private Object readResolve() { + return INSTANCE; + } + + @Override + public IdentityConverter reverse() { + return this; + } + + @Override + public String toString() { + return "Converter.identity()"; + } + } + + private static final class ReverseConverter extends Converter implements Serializable { + private static final long serialVersionUID = 0L; + + final Converter original; + + /* + * These gymnastics are a little confusing. Basically this class has neither + * legacy nor non-legacy behavior; it just needs to let the behavior of the + * backing converter shine through. So, we override the correctedDo* methods, + * after which the do* methods should never be reached. + */ + + ReverseConverter(Converter original) { + this.original = original; + } + + @Override + @Nullable + B correctedDoBackward(@Nullable A a) { + return original.correctedDoForward(a); + } + + @Override + @Nullable + A correctedDoForward(@Nullable B b) { + return original.correctedDoBackward(b); + } + + @Override + protected B doBackward(A a) { + throw new AssertionError(); + } + + @Override + protected A doForward(B b) { + throw new AssertionError(); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof ReverseConverter) { + ReverseConverter that = (ReverseConverter) object; + return this.original.equals(that.original); + } + return false; + } + + @Override + public int hashCode() { + return ~original.hashCode(); + } + + @Override + public Converter reverse() { + return original; + } + + @Override + public String toString() { + return original + ".reverse()"; + } + } + + // SPI methods (what subclasses must implement) + + /** + * Returns a converter based on existing forward and backward functions. + * Note that it is unnecessary to create new classes implementing + * {@code Function} just to pass them in here. Instead, simply subclass + * {@code Converter} and implement its {@link #doForward} and + * {@link #doBackward} methods directly. + * + *

+ * These functions will never be passed {@code null} and must not under any + * circumstances return {@code null}. If a value cannot be converted, the + * function should throw an unchecked exception (typically, but not necessarily, + * {@link IllegalArgumentException}). + * + *

+ * The returned converter is serializable if both provided functions are. + * + * @since 17.0 + */ + public static Converter from(Function forwardFunction, + Function backwardFunction) { + return new FunctionBasedConverter(forwardFunction, backwardFunction); + } + + /** + * Returns a serializable converter that always converts or reverses an object + * to itself. + */ + @SuppressWarnings("unchecked") // implementation is "fully variant" + public static Converter identity() { + return (IdentityConverter) IdentityConverter.INSTANCE; + } + + // API (consumer-side) methods + private final boolean handleNullAutomatically; // We lazily cache the reverse view to avoid allocating on every call to @@ -128,39 +373,29 @@ public abstract class Converter implements Function { this.handleNullAutomatically = handleNullAutomatically; } - // SPI methods (what subclasses must implement) + /** + * Returns a converter whose {@code convert} method applies + * {@code secondConverter} to the result of this converter. Its {@code reverse} + * method applies the converters in reverse order. + * + *

+ * The returned converter is serializable if {@code this} converter and + * {@code secondConverter} are. + */ + public Converter andThen(Converter secondConverter) { + return new ConverterComposition(this, checkNotNull(secondConverter)); + } /** - * Returns a representation of {@code a} as an instance of type {@code B}. If - * {@code a} cannot be converted, an unchecked exception (such as - * {@link IllegalArgumentException}) should be thrown. - * - * @param a the instance to convert; will never be null - * @return the converted instance; must not be null + * @deprecated Provided to satisfy the {@code Function} interface; use + * {@link #convert} instead. */ - protected abstract B doForward(A a); - - /** - * Returns a representation of {@code b} as an instance of type {@code A}. If - * {@code b} cannot be converted, an unchecked exception (such as - * {@link IllegalArgumentException}) should be thrown. - * - * @param b the instance to convert; will never be null - * @return the converted instance; must not be null - * @throws UnsupportedOperationException if backward conversion is not - * implemented; this should be very rare. - * Note that if backward conversion is not - * only unimplemented but - * unimplementable (for example, - * consider a - * {@code Converter}), - * then this is not logically a - * {@code Converter} at all, and should - * just implement {@link Function}. - */ - protected abstract A doBackward(B b); - - // API (consumer-side) methods + @Deprecated + @Override + @Nullable + public final B apply(@Nullable A a) { + return convert(a); + } /** * Returns a representation of {@code a} as an instance of type {@code B}. @@ -172,26 +407,6 @@ public abstract class Converter implements Function { return correctedDoForward(a); } - @Nullable - B correctedDoForward(@Nullable A a) { - if (handleNullAutomatically) { - // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? - return a == null ? null : checkNotNull(doForward(a)); - } else { - return doForward(a); - } - } - - @Nullable - A correctedDoBackward(@Nullable B b) { - if (handleNullAutomatically) { - // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? - return b == null ? null : checkNotNull(doBackward(b)); - } else { - return doBackward(b); - } - } - /** * Returns an iterable that applies {@code convert} to each element of * {@code fromIterable}. The conversion is done lazily. @@ -228,167 +443,58 @@ public abstract class Converter implements Function { }; } - /** - * Returns the reversed view of this converter, which converts - * {@code this.convert(a)} back to a value roughly equivalent to {@code a}. - * - *

- * The returned converter is serializable if {@code this} converter is. - */ - // TODO(user): Make this method final - public Converter reverse() { - Converter result = reverse; - return (result == null) ? reverse = new ReverseConverter(this) : result; - } - - private static final class ReverseConverter extends Converter implements Serializable { - final Converter original; - - ReverseConverter(Converter original) { - this.original = original; - } - - /* - * These gymnastics are a little confusing. Basically this class has neither - * legacy nor non-legacy behavior; it just needs to let the behavior of the - * backing converter shine through. So, we override the correctedDo* methods, - * after which the do* methods should never be reached. - */ - - @Override - protected A doForward(B b) { - throw new AssertionError(); - } - - @Override - protected B doBackward(A a) { - throw new AssertionError(); - } - - @Override - @Nullable - A correctedDoForward(@Nullable B b) { - return original.correctedDoBackward(b); - } - - @Override - @Nullable - B correctedDoBackward(@Nullable A a) { - return original.correctedDoForward(a); - } - - @Override - public Converter reverse() { - return original; - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof ReverseConverter) { - ReverseConverter that = (ReverseConverter) object; - return this.original.equals(that.original); - } - return false; - } - - @Override - public int hashCode() { - return ~original.hashCode(); - } - - @Override - public String toString() { - return original + ".reverse()"; - } - - private static final long serialVersionUID = 0L; - } - - /** - * Returns a converter whose {@code convert} method applies - * {@code secondConverter} to the result of this converter. Its {@code reverse} - * method applies the converters in reverse order. - * - *

- * The returned converter is serializable if {@code this} converter and - * {@code secondConverter} are. - */ - public Converter andThen(Converter secondConverter) { - return new ConverterComposition(this, checkNotNull(secondConverter)); - } - - private static final class ConverterComposition extends Converter implements Serializable { - final Converter first; - final Converter second; - - ConverterComposition(Converter first, Converter second) { - this.first = first; - this.second = second; - } - - /* - * These gymnastics are a little confusing. Basically this class has neither - * legacy nor non-legacy behavior; it just needs to let the behaviors of the - * backing converters shine through (which might even differ from each other!). - * So, we override the correctedDo* methods, after which the do* methods should - * never be reached. - */ - - @Override - protected C doForward(A a) { - throw new AssertionError(); - } - - @Override - protected A doBackward(C c) { - throw new AssertionError(); - } - - @Override - @Nullable - C correctedDoForward(@Nullable A a) { - return second.correctedDoForward(first.correctedDoForward(a)); - } - - @Override - @Nullable - A correctedDoBackward(@Nullable C c) { - return first.correctedDoBackward(second.correctedDoBackward(c)); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof ConverterComposition) { - ConverterComposition that = (ConverterComposition) object; - return this.first.equals(that.first) && this.second.equals(that.second); - } - return false; - } - - @Override - public int hashCode() { - return 31 * first.hashCode() + second.hashCode(); - } - - @Override - public String toString() { - return first + ".andThen(" + second + ")"; - } - - private static final long serialVersionUID = 0L; - } - - /** - * @deprecated Provided to satisfy the {@code Function} interface; use - * {@link #convert} instead. - */ - @Deprecated - @Override @Nullable - public final B apply(@Nullable A a) { - return convert(a); + A correctedDoBackward(@Nullable B b) { + if (handleNullAutomatically) { + // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? + return b == null ? null : checkNotNull(doBackward(b)); + } else { + return doBackward(b); + } } + @Nullable + B correctedDoForward(@Nullable A a) { + if (handleNullAutomatically) { + // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? + return a == null ? null : checkNotNull(doForward(a)); + } else { + return doForward(a); + } + } + + // Static converters + + /** + * Returns a representation of {@code b} as an instance of type {@code A}. If + * {@code b} cannot be converted, an unchecked exception (such as + * {@link IllegalArgumentException}) should be thrown. + * + * @param b the instance to convert; will never be null + * @return the converted instance; must not be null + * @throws UnsupportedOperationException if backward conversion is not + * implemented; this should be very rare. + * Note that if backward conversion is not + * only unimplemented but + * unimplementable (for example, + * consider a + * {@code Converter}), + * then this is not logically a + * {@code Converter} at all, and should + * just implement {@link Function}. + */ + protected abstract A doBackward(B b); + + /** + * Returns a representation of {@code a} as an instance of type {@code B}. If + * {@code a} cannot be converted, an unchecked exception (such as + * {@link IllegalArgumentException}) should be thrown. + * + * @param a the instance to convert; will never be null + * @return the converted instance; must not be null + */ + protected abstract B doForward(A a); + /** * Indicates whether another object is equal to this converter. * @@ -407,122 +513,16 @@ public abstract class Converter implements Function { return super.equals(object); } - // Static converters - /** - * Returns a converter based on existing forward and backward functions. - * Note that it is unnecessary to create new classes implementing - * {@code Function} just to pass them in here. Instead, simply subclass - * {@code Converter} and implement its {@link #doForward} and - * {@link #doBackward} methods directly. + * Returns the reversed view of this converter, which converts + * {@code this.convert(a)} back to a value roughly equivalent to {@code a}. * *

- * These functions will never be passed {@code null} and must not under any - * circumstances return {@code null}. If a value cannot be converted, the - * function should throw an unchecked exception (typically, but not necessarily, - * {@link IllegalArgumentException}). - * - *

- * The returned converter is serializable if both provided functions are. - * - * @since 17.0 + * The returned converter is serializable if {@code this} converter is. */ - public static Converter from(Function forwardFunction, - Function backwardFunction) { - return new FunctionBasedConverter(forwardFunction, backwardFunction); - } - - private static final class FunctionBasedConverter extends Converter implements Serializable { - private final Function forwardFunction; - private final Function backwardFunction; - - private FunctionBasedConverter(Function forwardFunction, - Function backwardFunction) { - this.forwardFunction = checkNotNull(forwardFunction); - this.backwardFunction = checkNotNull(backwardFunction); - } - - @Override - protected B doForward(A a) { - return forwardFunction.apply(a); - } - - @Override - protected A doBackward(B b) { - return backwardFunction.apply(b); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof FunctionBasedConverter) { - FunctionBasedConverter that = (FunctionBasedConverter) object; - return this.forwardFunction.equals(that.forwardFunction) - && this.backwardFunction.equals(that.backwardFunction); - } - return false; - } - - @Override - public int hashCode() { - return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); - } - - @Override - public String toString() { - return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; - } - } - - /** - * Returns a serializable converter that always converts or reverses an object - * to itself. - */ - @SuppressWarnings("unchecked") // implementation is "fully variant" - public static Converter identity() { - return (IdentityConverter) IdentityConverter.INSTANCE; - } - - /** - * A converter that always converts or reverses an object to itself. Note that T - * is now a "pass-through type". - */ - private static final class IdentityConverter extends Converter implements Serializable { - static final IdentityConverter INSTANCE = new IdentityConverter(); - - @Override - protected T doForward(T t) { - return t; - } - - @Override - protected T doBackward(T t) { - return t; - } - - @Override - public IdentityConverter reverse() { - return this; - } - - @Override - public Converter andThen(Converter otherConverter) { - return checkNotNull(otherConverter, "otherConverter"); - } - - /* - * We *could* override convertAll() to return its input, but it's a rather - * pointless optimization and opened up a weird type-safety problem. - */ - - @Override - public String toString() { - return "Converter.identity()"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 0L; + // TODO(user): Make this method final + public Converter reverse() { + Converter result = reverse; + return (result == null) ? reverse = new ReverseConverter(this) : result; } } diff --git a/src/main/java/com/google/common/base/Defaults.java b/src/main/java/com/google/common/base/Defaults.java index 1eda021a..6580774f 100644 --- a/src/main/java/com/google/common/base/Defaults.java +++ b/src/main/java/com/google/common/base/Defaults.java @@ -29,9 +29,6 @@ import java.util.Map; * @since 1.0 */ public final class Defaults { - private Defaults() { - } - private static final Map, Object> DEFAULTS; static { @@ -48,10 +45,6 @@ public final class Defaults { DEFAULTS = Collections.unmodifiableMap(map); } - private static void put(Map, Object> map, Class type, T value) { - map.put(type, value); - } - /** * Returns the default value of {@code type} as defined by JLS --- {@code 0} for * numbers, {@code @@ -65,4 +58,11 @@ public final class Defaults { T t = (T) DEFAULTS.get(checkNotNull(type)); return t; } + + private static void put(Map, Object> map, Class type, T value) { + map.put(type, value); + } + + private Defaults() { + } } diff --git a/src/main/java/com/google/common/base/Enums.java b/src/main/java/com/google/common/base/Enums.java index 952f0772..48aabf68 100644 --- a/src/main/java/com/google/common/base/Enums.java +++ b/src/main/java/com/google/common/base/Enums.java @@ -41,27 +41,44 @@ import com.google.common.annotations.GwtIncompatible; @Beta public final class Enums { - private Enums() { - } + private static final class StringConverter> extends Converter implements Serializable { - /** - * Returns a {@link Function} that maps an {@link Enum} name to the associated - * {@code Enum} constant. The {@code Function} will return {@code null} if the - * {@code Enum} constant does not exist. - * - * @param enumClass the {@link Class} of the {@code Enum} declaring the constant - * values - * @deprecated Use {@link Enums#stringConverter} instead. Note that the string - * converter has slightly different behavior: it throws - * {@link IllegalArgumentException} if the enum constant does not - * exist rather than returning {@code null}. It also converts - * {@code null} to {@code null} rather than throwing - * {@link NullPointerException}. This method is scheduled for - * removal in Guava 18.0. - */ - @Deprecated - public static > Function valueOfFunction(Class enumClass) { - return new ValueOfFunction(enumClass); + private static final long serialVersionUID = 0L; + + private final Class enumClass; + + StringConverter(Class enumClass) { + this.enumClass = checkNotNull(enumClass); + } + + @Override + protected String doBackward(T enumValue) { + return enumValue.name(); + } + + @Override + protected T doForward(String value) { + return Enum.valueOf(enumClass, value); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof StringConverter) { + StringConverter that = (StringConverter) object; + return this.enumClass.equals(that.enumClass); + } + return false; + } + + @Override + public int hashCode() { + return enumClass.hashCode(); + } + + @Override + public String toString() { + return "Enums.stringConverter(" + enumClass.getName() + ".class)"; + } } /** @@ -70,6 +87,8 @@ public final class Enums { */ private static final class ValueOfFunction> implements Function, Serializable { + private static final long serialVersionUID = 0; + private final Class enumClass; private ValueOfFunction(Class enumClass) { @@ -99,8 +118,20 @@ public final class Enums { public String toString() { return "Enums.valueOf(" + enumClass + ")"; } + } - private static final long serialVersionUID = 0; + @GwtIncompatible("java.lang.ref.WeakReference") + private static final Map>, Map>>> enumConstantCache = new HashMap>, Map>>>(); + + @GwtIncompatible("java.lang.ref.WeakReference") + static > Map>> getEnumConstants(Class enumClass) { + synchronized (enumConstantCache) { + Map>> constants = enumConstantCache.get(enumClass); + if (constants == null) { + constants = populateCache(enumClass); + } + return constants; + } } /** @@ -118,9 +149,6 @@ public final class Enums { return Platform.getEnumIfPresent(enumClass, value); } - @GwtIncompatible("java.lang.ref.WeakReference") - private static final Map>, Map>>> enumConstantCache = new HashMap>, Map>>>(); - @GwtIncompatible("java.lang.ref.WeakReference") private static > Map>> populateCache(Class enumClass) { Map>> result = new HashMap>>(); @@ -131,17 +159,6 @@ public final class Enums { return result; } - @GwtIncompatible("java.lang.ref.WeakReference") - static > Map>> getEnumConstants(Class enumClass) { - synchronized (enumConstantCache) { - Map>> constants = enumConstantCache.get(enumClass); - if (constants == null) { - constants = populateCache(enumClass); - } - return constants; - } - } - /** * Returns a converter that converts between strings and {@code enum} values of * type {@code enumClass} using {@link Enum#valueOf(Class, String)} and @@ -155,43 +172,26 @@ public final class Enums { return new StringConverter(enumClass); } - private static final class StringConverter> extends Converter implements Serializable { + /** + * Returns a {@link Function} that maps an {@link Enum} name to the associated + * {@code Enum} constant. The {@code Function} will return {@code null} if the + * {@code Enum} constant does not exist. + * + * @param enumClass the {@link Class} of the {@code Enum} declaring the constant + * values + * @deprecated Use {@link Enums#stringConverter} instead. Note that the string + * converter has slightly different behavior: it throws + * {@link IllegalArgumentException} if the enum constant does not + * exist rather than returning {@code null}. It also converts + * {@code null} to {@code null} rather than throwing + * {@link NullPointerException}. This method is scheduled for + * removal in Guava 18.0. + */ + @Deprecated + public static > Function valueOfFunction(Class enumClass) { + return new ValueOfFunction(enumClass); + } - private final Class enumClass; - - StringConverter(Class enumClass) { - this.enumClass = checkNotNull(enumClass); - } - - @Override - protected T doForward(String value) { - return Enum.valueOf(enumClass, value); - } - - @Override - protected String doBackward(T enumValue) { - return enumValue.name(); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof StringConverter) { - StringConverter that = (StringConverter) object; - return this.enumClass.equals(that.enumClass); - } - return false; - } - - @Override - public int hashCode() { - return enumClass.hashCode(); - } - - @Override - public String toString() { - return "Enums.stringConverter(" + enumClass.getName() + ".class)"; - } - - private static final long serialVersionUID = 0L; + private Enums() { } } diff --git a/src/main/java/com/google/common/base/Equivalence.java b/src/main/java/com/google/common/base/Equivalence.java index 77d943bd..ea368b0a 100644 --- a/src/main/java/com/google/common/base/Equivalence.java +++ b/src/main/java/com/google/common/base/Equivalence.java @@ -39,12 +39,234 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public abstract class Equivalence { + static final class Equals extends Equivalence implements Serializable { + + static final Equals INSTANCE = new Equals(); + + private static final long serialVersionUID = 1; + + @Override + protected boolean doEquivalent(Object a, Object b) { + return a.equals(b); + } + + @Override + public int doHash(Object o) { + return o.hashCode(); + } + + private Object readResolve() { + return INSTANCE; + } + } + + private static final class EquivalentToPredicate implements Predicate, Serializable { + + private static final long serialVersionUID = 0; + private final Equivalence equivalence; + + @Nullable + private final T target; + + EquivalentToPredicate(Equivalence equivalence, @Nullable T target) { + this.equivalence = checkNotNull(equivalence); + this.target = target; + } + + @Override + public boolean apply(@Nullable T input) { + return equivalence.equivalent(input, target); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof EquivalentToPredicate) { + EquivalentToPredicate that = (EquivalentToPredicate) obj; + return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hashCode(equivalence, target); + } + + @Override + public String toString() { + return equivalence + ".equivalentTo(" + target + ")"; + } + } + + static final class Identity extends Equivalence implements Serializable { + + static final Identity INSTANCE = new Identity(); + + private static final long serialVersionUID = 1; + + @Override + protected boolean doEquivalent(Object a, Object b) { + return false; + } + + @Override + protected int doHash(Object o) { + return System.identityHashCode(o); + } + + private Object readResolve() { + return INSTANCE; + } + } + + /** + * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} + * delegate to an {@link Equivalence}. + * + *

+ * For example, given an {@link Equivalence} for {@link String strings} named + * {@code equiv} that tests equivalence using their lengths: + * + *

+	 *    {@code
+	 *   equiv.wrap("a").equals(equiv.wrap("b")) // true
+	 *   equiv.wrap("a").equals(equiv.wrap("hello")) // false}
+	 * 
+ * + *

+ * Note in particular that an equivalence wrapper is never equal to the object + * it wraps. + * + *

+	 *    {@code
+	 * equiv.wrap(obj).equals(obj) // always false
+	 * }
+	 * 
+ * + * @since 10.0 + */ + public static final class Wrapper implements Serializable { + private static final long serialVersionUID = 0; + private final Equivalence equivalence; + + @Nullable + private final T reference; + + private Wrapper(Equivalence equivalence, @Nullable T reference) { + this.equivalence = checkNotNull(equivalence); + this.reference = reference; + } + + /** + * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} + * applied to the wrapped references is {@code true} and both wrappers use the + * {@link Object#equals(Object) same} equivalence. + */ + @Override + public boolean equals(@Nullable Object obj) { + if (obj == this) { + return true; + } + if (obj instanceof Wrapper) { + Wrapper that = (Wrapper) obj; // note: not necessarily a Wrapper + + if (this.equivalence.equals(that.equivalence)) { + /* + * We'll accept that as sufficient "proof" that either equivalence should be + * able to handle either reference, so it's safe to circumvent compile-time type + * checking. + */ + @SuppressWarnings("unchecked") + Equivalence equivalence = (Equivalence) this.equivalence; + return equivalence.equivalent(this.reference, that.reference); + } + } + return false; + } + + /** Returns the (possibly null) reference wrapped by this instance. */ + @Nullable + public T get() { + return reference; + } + + /** + * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped + * reference. + */ + @Override + public int hashCode() { + return equivalence.hash(reference); + } + + /** + * Returns a string representation for this equivalence wrapper. The form of + * this string representation is not specified. + */ + @Override + public String toString() { + return equivalence + ".wrap(" + reference + ")"; + } + } + + /** + * Returns an equivalence that delegates to {@link Object#equals} and + * {@link Object#hashCode}. {@link Equivalence#equivalent} returns {@code true} + * if both values are null, or if neither value is null and + * {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns + * {@code 0} if passed a null value. + * + * @since 13.0 + * @since 8.0 (in Equivalences with null-friendly behavior) + * @since 4.0 (in Equivalences) + */ + public static Equivalence equals() { + return Equals.INSTANCE; + } + + /** + * Returns an equivalence that uses {@code ==} to compare values and + * {@link System#identityHashCode(Object)} to compute the hash code. + * {@link Equivalence#equivalent} returns {@code true} if {@code a == b}, + * including in the case that a and b are both null. + * + * @since 13.0 + * @since 4.0 (in Equivalences) + */ + public static Equivalence identity() { + return Identity.INSTANCE; + } + /** * Constructor for use by subclasses. */ protected Equivalence() { } + /** + * Returns {@code true} if {@code a} and {@code b} are considered equivalent. + * + *

+ * Called by {@link #equivalent}. {@code a} and {@code b} are not the same + * object and are not nulls. + * + * @since 10.0 (previously, subclasses would override equivalent()) + */ + protected abstract boolean doEquivalent(T a, T b); + + /** + * Returns a hash code for non-null object {@code t}. + * + *

+ * Called by {@link #hash}. + * + * @since 10.0 (previously, subclasses would override hash()) + */ + protected abstract int doHash(T t); + /** * Returns {@code true} if the given objects are considered equivalent. * @@ -80,15 +302,15 @@ public abstract class Equivalence { } /** - * Returns {@code true} if {@code a} and {@code b} are considered equivalent. - * - *

- * Called by {@link #equivalent}. {@code a} and {@code b} are not the same - * object and are not nulls. - * - * @since 10.0 (previously, subclasses would override equivalent()) + * Returns a predicate that evaluates to true if and only if the input is + * equivalent to {@code target} according to this equivalence relation. + * + * @since 10.0 */ - protected abstract boolean doEquivalent(T a, T b); + @Beta + public final Predicate equivalentTo(@Nullable T target) { + return new EquivalentToPredicate(this, target); + } /** * Returns a hash code for {@code t}. @@ -116,16 +338,6 @@ public abstract class Equivalence { return doHash(t); } - /** - * Returns a hash code for non-null object {@code t}. - * - *

- * Called by {@link #hash}. - * - * @since 10.0 (previously, subclasses would override hash()) - */ - protected abstract int doHash(T t); - /** * Returns a new equivalence relation for {@code F} which evaluates equivalence * by first applying {@code function} to the argument, then evaluating using @@ -162,106 +374,6 @@ public abstract class Equivalence { return new FunctionalEquivalence(function, this); } - /** - * Returns a wrapper of {@code reference} that implements - * {@link Wrapper#equals(Object) Object.equals()} such that - * {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, b)}. - * - * @since 10.0 - */ - public final Wrapper wrap(@Nullable S reference) { - return new Wrapper(this, reference); - } - - /** - * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} - * delegate to an {@link Equivalence}. - * - *

- * For example, given an {@link Equivalence} for {@link String strings} named - * {@code equiv} that tests equivalence using their lengths: - * - *

-	 *    {@code
-	 *   equiv.wrap("a").equals(equiv.wrap("b")) // true
-	 *   equiv.wrap("a").equals(equiv.wrap("hello")) // false}
-	 * 
- * - *

- * Note in particular that an equivalence wrapper is never equal to the object - * it wraps. - * - *

-	 *    {@code
-	 *   equiv.wrap(obj).equals(obj) // always false}
-	 * 
- * - * @since 10.0 - */ - public static final class Wrapper implements Serializable { - private final Equivalence equivalence; - @Nullable - private final T reference; - - private Wrapper(Equivalence equivalence, @Nullable T reference) { - this.equivalence = checkNotNull(equivalence); - this.reference = reference; - } - - /** Returns the (possibly null) reference wrapped by this instance. */ - @Nullable - public T get() { - return reference; - } - - /** - * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} - * applied to the wrapped references is {@code true} and both wrappers use the - * {@link Object#equals(Object) same} equivalence. - */ - @Override - public boolean equals(@Nullable Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof Wrapper) { - Wrapper that = (Wrapper) obj; // note: not necessarily a Wrapper - - if (this.equivalence.equals(that.equivalence)) { - /* - * We'll accept that as sufficient "proof" that either equivalence should be - * able to handle either reference, so it's safe to circumvent compile-time type - * checking. - */ - @SuppressWarnings("unchecked") - Equivalence equivalence = (Equivalence) this.equivalence; - return equivalence.equivalent(this.reference, that.reference); - } - } - return false; - } - - /** - * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped - * reference. - */ - @Override - public int hashCode() { - return equivalence.hash(reference); - } - - /** - * Returns a string representation for this equivalence wrapper. The form of - * this string representation is not specified. - */ - @Override - public String toString() { - return equivalence + ".wrap(" + reference + ")"; - } - - private static final long serialVersionUID = 0; - } - /** * Returns an equivalence over iterables based on the equivalence of their * elements. More specifically, two iterables are considered equivalent if they @@ -286,124 +398,13 @@ public abstract class Equivalence { } /** - * Returns a predicate that evaluates to true if and only if the input is - * equivalent to {@code target} according to this equivalence relation. + * Returns a wrapper of {@code reference} that implements + * {@link Wrapper#equals(Object) Object.equals()} such that + * {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, b)}. * * @since 10.0 */ - @Beta - public final Predicate equivalentTo(@Nullable T target) { - return new EquivalentToPredicate(this, target); - } - - private static final class EquivalentToPredicate implements Predicate, Serializable { - - private final Equivalence equivalence; - @Nullable - private final T target; - - EquivalentToPredicate(Equivalence equivalence, @Nullable T target) { - this.equivalence = checkNotNull(equivalence); - this.target = target; - } - - @Override - public boolean apply(@Nullable T input) { - return equivalence.equivalent(input, target); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof EquivalentToPredicate) { - EquivalentToPredicate that = (EquivalentToPredicate) obj; - return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hashCode(equivalence, target); - } - - @Override - public String toString() { - return equivalence + ".equivalentTo(" + target + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns an equivalence that delegates to {@link Object#equals} and - * {@link Object#hashCode}. {@link Equivalence#equivalent} returns {@code true} - * if both values are null, or if neither value is null and - * {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns - * {@code 0} if passed a null value. - * - * @since 13.0 - * @since 8.0 (in Equivalences with null-friendly behavior) - * @since 4.0 (in Equivalences) - */ - public static Equivalence equals() { - return Equals.INSTANCE; - } - - /** - * Returns an equivalence that uses {@code ==} to compare values and - * {@link System#identityHashCode(Object)} to compute the hash code. - * {@link Equivalence#equivalent} returns {@code true} if {@code a == b}, - * including in the case that a and b are both null. - * - * @since 13.0 - * @since 4.0 (in Equivalences) - */ - public static Equivalence identity() { - return Identity.INSTANCE; - } - - static final class Equals extends Equivalence implements Serializable { - - static final Equals INSTANCE = new Equals(); - - @Override - protected boolean doEquivalent(Object a, Object b) { - return a.equals(b); - } - - @Override - public int doHash(Object o) { - return o.hashCode(); - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; - } - - static final class Identity extends Equivalence implements Serializable { - - static final Identity INSTANCE = new Identity(); - - @Override - protected boolean doEquivalent(Object a, Object b) { - return false; - } - - @Override - protected int doHash(Object o) { - return System.identityHashCode(o); - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; + public final Wrapper wrap(@Nullable S reference) { + return new Wrapper(this, reference); } } diff --git a/src/main/java/com/google/common/base/FinalizableReferenceQueue.java b/src/main/java/com/google/common/base/FinalizableReferenceQueue.java index ff01f898..381769c5 100644 --- a/src/main/java/com/google/common/base/FinalizableReferenceQueue.java +++ b/src/main/java/com/google/common/base/FinalizableReferenceQueue.java @@ -137,97 +137,83 @@ public class FinalizableReferenceQueue implements Closeable { * directly in the application class loader. */ - private static final Logger logger = Logger.getLogger(FinalizableReferenceQueue.class.getName()); - - private static final String FINALIZER_CLASS_NAME = "com.google.common.base.internal.Finalizer"; - - /** Reference to Finalizer.startFinalizer(). */ - private static final Method startFinalizer; - static { - Class finalizer = loadFinalizer(new SystemLoader(), new DecoupledLoader(), new DirectLoader()); - startFinalizer = getStartFinalizer(finalizer); - } - /** - * The actual reference queue that our background thread will poll. + * Try to load Finalizer in its own class loader. If Finalizer's thread had a + * direct reference to our class loader (which could be that of a dynamically + * loaded web application or OSGi bundle), it would prevent our class loader + * from getting garbage collected. */ - final ReferenceQueue queue; + static class DecoupledLoader implements FinalizerLoader { + private static final String LOADING_ERROR = "Could not load Finalizer in its own class loader." + + "Loading Finalizer in the current class loader instead. As a result, you will not be able" + + "to garbage collect this class loader. To support reclaiming this class loader, either" + + "resolve the underlying issue, or move Google Collections to your system class path."; - final PhantomReference frqRef; + /** + * Gets URL for base of path containing Finalizer.class. + */ + URL getBaseUrl() throws IOException { + // Find URL pointing to Finalizer.class file. + String finalizerPath = FINALIZER_CLASS_NAME.replace('.', '/') + ".class"; + URL finalizerUrl = getClass().getClassLoader().getResource(finalizerPath); + if (finalizerUrl == null) { + throw new FileNotFoundException(finalizerPath); + } - /** - * Whether or not the background thread started successfully. - */ - final boolean threadStarted; - - /** - * Constructs a new queue. - */ - public FinalizableReferenceQueue() { - // We could start the finalizer lazily, but I'd rather it blow up early. - queue = new ReferenceQueue(); - frqRef = new PhantomReference(this, queue); - boolean threadStarted = false; - try { - startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); - threadStarted = true; - } catch (IllegalAccessException impossible) { - throw new AssertionError(impossible); // startFinalizer() is public - } catch (Throwable t) { - logger.log(Level.INFO, "Failed to start reference finalizer thread." - + " Reference cleanup will only occur when new references are created.", t); + // Find URL pointing to base of class path. + String urlString = finalizerUrl.toString(); + if (!urlString.endsWith(finalizerPath)) { + throw new IOException("Unsupported path style: " + urlString); + } + urlString = urlString.substring(0, urlString.length() - finalizerPath.length()); + return new URL(finalizerUrl, urlString); } - this.threadStarted = threadStarted; - } - - @Override - public void close() { - frqRef.enqueue(); - cleanUp(); - } - - /** - * Repeatedly dequeues references from the queue and invokes - * {@link FinalizableReference#finalizeReferent()} on them until the queue is - * empty. This method is a no-op if the background thread was created - * successfully. - */ - void cleanUp() { - if (threadStarted) { - return; - } - - Reference reference; - while ((reference = queue.poll()) != null) { - /* - * This is for the benefit of phantom references. Weak and soft references will - * have already been cleared by this point. - */ - reference.clear(); + @Override + public Class loadFinalizer() { try { - ((FinalizableReference) reference).finalizeReferent(); - } catch (Throwable t) { - logger.log(Level.SEVERE, "Error cleaning up after reference.", t); + /* + * We use URLClassLoader because it's the only concrete class loader + * implementation in the JDK. If we used our own ClassLoader subclass, Finalizer + * would indirectly reference this class loader: + * + * Finalizer.class -> CustomClassLoader -> CustomClassLoader.class -> This class + * loader + * + * System class loader will (and must) be the parent. + */ + ClassLoader finalizerLoader = newLoader(getBaseUrl()); + return finalizerLoader.loadClass(FINALIZER_CLASS_NAME); + } catch (Exception e) { + logger.log(Level.WARNING, LOADING_ERROR, e); + return null; } } + + /** Creates a class loader with the given base URL as its classpath. */ + URLClassLoader newLoader(URL base) { + // We use the bootstrap class loader as the parent because Finalizer by design + // uses + // only standard Java classes. That also means that + // FinalizableReferenceQueueTest + // doesn't pick up the wrong version of the Finalizer class. + return new URLClassLoader(new URL[] { base }, null); + } } /** - * Iterates through the given loaders until it finds one that can load - * Finalizer. - * - * @return Finalizer.class + * Loads Finalizer directly using the current class loader. We won't be able to + * garbage collect this class loader, but at least the world doesn't end. */ - private static Class loadFinalizer(FinalizerLoader... loaders) { - for (FinalizerLoader loader : loaders) { - Class finalizer = loader.loadFinalizer(); - if (finalizer != null) { - return finalizer; + static class DirectLoader implements FinalizerLoader { + @Override + public Class loadFinalizer() { + try { + return Class.forName(FINALIZER_CLASS_NAME); + } catch (ClassNotFoundException e) { + throw new AssertionError(e); } } - - throw new AssertionError(); } /** @@ -279,83 +265,16 @@ public class FinalizableReferenceQueue implements Closeable { } } - /** - * Try to load Finalizer in its own class loader. If Finalizer's thread had a - * direct reference to our class loader (which could be that of a dynamically - * loaded web application or OSGi bundle), it would prevent our class loader - * from getting garbage collected. - */ - static class DecoupledLoader implements FinalizerLoader { - private static final String LOADING_ERROR = "Could not load Finalizer in its own class loader." - + "Loading Finalizer in the current class loader instead. As a result, you will not be able" - + "to garbage collect this class loader. To support reclaiming this class loader, either" - + "resolve the underlying issue, or move Google Collections to your system class path."; + private static final Logger logger = Logger.getLogger(FinalizableReferenceQueue.class.getName()); - @Override - public Class loadFinalizer() { - try { - /* - * We use URLClassLoader because it's the only concrete class loader - * implementation in the JDK. If we used our own ClassLoader subclass, Finalizer - * would indirectly reference this class loader: - * - * Finalizer.class -> CustomClassLoader -> CustomClassLoader.class -> This class - * loader - * - * System class loader will (and must) be the parent. - */ - ClassLoader finalizerLoader = newLoader(getBaseUrl()); - return finalizerLoader.loadClass(FINALIZER_CLASS_NAME); - } catch (Exception e) { - logger.log(Level.WARNING, LOADING_ERROR, e); - return null; - } - } + private static final String FINALIZER_CLASS_NAME = "com.google.common.base.internal.Finalizer"; - /** - * Gets URL for base of path containing Finalizer.class. - */ - URL getBaseUrl() throws IOException { - // Find URL pointing to Finalizer.class file. - String finalizerPath = FINALIZER_CLASS_NAME.replace('.', '/') + ".class"; - URL finalizerUrl = getClass().getClassLoader().getResource(finalizerPath); - if (finalizerUrl == null) { - throw new FileNotFoundException(finalizerPath); - } + /** Reference to Finalizer.startFinalizer(). */ + private static final Method startFinalizer; - // Find URL pointing to base of class path. - String urlString = finalizerUrl.toString(); - if (!urlString.endsWith(finalizerPath)) { - throw new IOException("Unsupported path style: " + urlString); - } - urlString = urlString.substring(0, urlString.length() - finalizerPath.length()); - return new URL(finalizerUrl, urlString); - } - - /** Creates a class loader with the given base URL as its classpath. */ - URLClassLoader newLoader(URL base) { - // We use the bootstrap class loader as the parent because Finalizer by design - // uses - // only standard Java classes. That also means that - // FinalizableReferenceQueueTest - // doesn't pick up the wrong version of the Finalizer class. - return new URLClassLoader(new URL[] { base }, null); - } - } - - /** - * Loads Finalizer directly using the current class loader. We won't be able to - * garbage collect this class loader, but at least the world doesn't end. - */ - static class DirectLoader implements FinalizerLoader { - @Override - public Class loadFinalizer() { - try { - return Class.forName(FINALIZER_CLASS_NAME); - } catch (ClassNotFoundException e) { - throw new AssertionError(e); - } - } + static { + Class finalizer = loadFinalizer(new SystemLoader(), new DecoupledLoader(), new DirectLoader()); + startFinalizer = getStartFinalizer(finalizer); } /** @@ -368,4 +287,86 @@ public class FinalizableReferenceQueue implements Closeable { throw new AssertionError(e); } } + + /** + * Iterates through the given loaders until it finds one that can load + * Finalizer. + * + * @return Finalizer.class + */ + private static Class loadFinalizer(FinalizerLoader... loaders) { + for (FinalizerLoader loader : loaders) { + Class finalizer = loader.loadFinalizer(); + if (finalizer != null) { + return finalizer; + } + } + + throw new AssertionError(); + } + + /** + * The actual reference queue that our background thread will poll. + */ + final ReferenceQueue queue; + + final PhantomReference frqRef; + + /** + * Whether or not the background thread started successfully. + */ + final boolean threadStarted; + + /** + * Constructs a new queue. + */ + public FinalizableReferenceQueue() { + // We could start the finalizer lazily, but I'd rather it blow up early. + queue = new ReferenceQueue(); + frqRef = new PhantomReference(this, queue); + boolean threadStarted = false; + try { + startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); + threadStarted = true; + } catch (IllegalAccessException impossible) { + throw new AssertionError(impossible); // startFinalizer() is public + } catch (Throwable t) { + logger.log(Level.INFO, "Failed to start reference finalizer thread." + + " Reference cleanup will only occur when new references are created.", t); + } + + this.threadStarted = threadStarted; + } + + /** + * Repeatedly dequeues references from the queue and invokes + * {@link FinalizableReference#finalizeReferent()} on them until the queue is + * empty. This method is a no-op if the background thread was created + * successfully. + */ + void cleanUp() { + if (threadStarted) { + return; + } + + Reference reference; + while ((reference = queue.poll()) != null) { + /* + * This is for the benefit of phantom references. Weak and soft references will + * have already been cleared by this point. + */ + reference.clear(); + try { + ((FinalizableReference) reference).finalizeReferent(); + } catch (Throwable t) { + logger.log(Level.SEVERE, "Error cleaning up after reference.", t); + } + } + } + + @Override + public void close() { + frqRef.enqueue(); + cleanUp(); + } } diff --git a/src/main/java/com/google/common/base/Functions.java b/src/main/java/com/google/common/base/Functions.java index 28c41baf..6ac96a89 100644 --- a/src/main/java/com/google/common/base/Functions.java +++ b/src/main/java/com/google/common/base/Functions.java @@ -46,135 +46,44 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public final class Functions { - private Functions() { - } + private static class ConstantFunction implements Function, Serializable { + private static final long serialVersionUID = 0; - /** - * Returns a function that calls {@code toString()} on its argument. The - * function does not accept nulls; it will throw a {@link NullPointerException} - * when applied to {@code null}. - * - *

- * Warning: The returned function may not be consistent with - * equals (as documented at {@link Function#apply}). For example, this - * function yields different results for the two equal instances - * {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}. - */ - public static Function toStringFunction() { - return ToStringFunction.INSTANCE; - } + private final E value; - // enum singleton pattern - private enum ToStringFunction implements Function { - INSTANCE; - - @Override - public String apply(Object o) { - checkNotNull(o); // eager for GWT. - return o.toString(); + public ConstantFunction(@Nullable E value) { + this.value = value; } @Override - public String toString() { - return "toString"; - } - } - - /** - * Returns the identity function. - */ - // implementation is "fully variant"; E has become a "pass-through" type - @SuppressWarnings("unchecked") - public static Function identity() { - return (Function) IdentityFunction.INSTANCE; - } - - // enum singleton pattern - private enum IdentityFunction implements Function { - INSTANCE; - - @Override - @Nullable - public Object apply(@Nullable Object o) { - return o; + public E apply(@Nullable Object from) { + return value; } @Override - public String toString() { - return "identity"; - } - } - - /** - * Returns a function which performs a map lookup. The returned function throws - * an {@link IllegalArgumentException} if given a key that does not exist in the - * map. See also {@link #forMap(Map, Object)}, which returns a default value in - * this case. - * - *

- * Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or - * can be one), you can use {@link com.google.common.collect.Maps#asConverter - * Maps.asConverter} instead to get a function that also supports reverse - * conversion. - */ - public static Function forMap(Map map) { - return new FunctionForMapNoDefault(map); - } - - private static class FunctionForMapNoDefault implements Function, Serializable { - final Map map; - - FunctionForMapNoDefault(Map map) { - this.map = checkNotNull(map); - } - - @Override - public V apply(@Nullable K key) { - V result = map.get(key); - checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key); - return result; - } - - @Override - public boolean equals(@Nullable Object o) { - if (o instanceof FunctionForMapNoDefault) { - FunctionForMapNoDefault that = (FunctionForMapNoDefault) o; - return map.equals(that.map); + public boolean equals(@Nullable Object obj) { + if (obj instanceof ConstantFunction) { + ConstantFunction that = (ConstantFunction) obj; + return Objects.equal(value, that.value); } return false; } @Override public int hashCode() { - return map.hashCode(); + return (value == null) ? 0 : value.hashCode(); } @Override public String toString() { - return "forMap(" + map + ")"; + return "constant(" + value + ")"; } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a function which performs a map lookup with a default value. The - * function created by this method returns {@code defaultValue} for all inputs - * that do not belong to the map's key set. See also {@link #forMap(Map)}, which - * throws an exception in this case. - * - * @param map source map that determines the function behavior - * @param defaultValue the value to return for inputs that aren't map keys - * @return function that returns {@code map.get(a)} when {@code a} is a key, or - * {@code - * defaultValue} otherwise - */ - public static Function forMap(Map map, @Nullable V defaultValue) { - return new ForMapWithDefault(map, defaultValue); } private static class ForMapWithDefault implements Function, Serializable { + private static final long serialVersionUID = 0; final Map map; + final V defaultValue; ForMapWithDefault(Map map, @Nullable V defaultValue) { @@ -206,27 +115,12 @@ public final class Functions { public String toString() { return "forMap(" + map + ", defaultValue=" + defaultValue + ")"; } - - private static final long serialVersionUID = 0; - } - - /** - * Returns the composition of two functions. For {@code f: A->B} and - * {@code g: B->C}, composition is defined as the function h such that - * {@code h(a) == g(f(a))} for each {@code a}. - * - * @param g the second function to apply - * @param f the first function to apply - * @return the composition of {@code f} and {@code g} - * @see function - * composition - */ - public static Function compose(Function g, Function f) { - return new FunctionComposition(g, f); } private static class FunctionComposition implements Function, Serializable { + private static final long serialVersionUID = 0; private final Function g; + private final Function f; public FunctionComposition(Function g, Function f) { @@ -257,25 +151,64 @@ public final class Functions { public String toString() { return g + "(" + f + ")"; } - - private static final long serialVersionUID = 0; } - /** - * Creates a function that returns the same boolean output as the given - * predicate for all inputs. - * - *

- * The returned function is consistent with equals (as documented at - * {@link Function#apply}) if and only if {@code predicate} is itself consistent - * with equals. - */ - public static Function forPredicate(Predicate predicate) { - return new PredicateFunction(predicate); + private static class FunctionForMapNoDefault implements Function, Serializable { + private static final long serialVersionUID = 0; + + final Map map; + + FunctionForMapNoDefault(Map map) { + this.map = checkNotNull(map); + } + + @Override + public V apply(@Nullable K key) { + V result = map.get(key); + checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key); + return result; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o instanceof FunctionForMapNoDefault) { + FunctionForMapNoDefault that = (FunctionForMapNoDefault) o; + return map.equals(that.map); + } + return false; + } + + @Override + public int hashCode() { + return map.hashCode(); + } + + @Override + public String toString() { + return "forMap(" + map + ")"; + } + } + + // enum singleton pattern + private enum IdentityFunction implements Function { + INSTANCE; + + @Override + @Nullable + public Object apply(@Nullable Object o) { + return o; + } + + @Override + public String toString() { + return "identity"; + } } /** @see Functions#forPredicate */ private static class PredicateFunction implements Function, Serializable { + private static final long serialVersionUID = 0; + private final Predicate predicate; private PredicateFunction(Predicate predicate) { @@ -305,69 +238,13 @@ public final class Functions { public String toString() { return "forPredicate(" + predicate + ")"; } - - private static final long serialVersionUID = 0; - } - - /** - * Creates a function that returns {@code value} for any input. - * - * @param value the constant value for the function to return - * @return a function that always returns {@code value} - */ - public static Function constant(@Nullable E value) { - return new ConstantFunction(value); - } - - private static class ConstantFunction implements Function, Serializable { - private final E value; - - public ConstantFunction(@Nullable E value) { - this.value = value; - } - - @Override - public E apply(@Nullable Object from) { - return value; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof ConstantFunction) { - ConstantFunction that = (ConstantFunction) obj; - return Objects.equal(value, that.value); - } - return false; - } - - @Override - public int hashCode() { - return (value == null) ? 0 : value.hashCode(); - } - - @Override - public String toString() { - return "constant(" + value + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a function that always returns the result of invoking - * {@link Supplier#get} on {@code - * supplier}, regardless of its input. - * - * @since 10.0 - */ - @Beta - public static Function forSupplier(Supplier supplier) { - return new SupplierFunction(supplier); } /** @see Functions#forSupplier */ private static class SupplierFunction implements Function, Serializable { + private static final long serialVersionUID = 0; + private final Supplier supplier; private SupplierFunction(Supplier supplier) { @@ -397,7 +274,130 @@ public final class Functions { public String toString() { return "forSupplier(" + supplier + ")"; } + } - private static final long serialVersionUID = 0; + // enum singleton pattern + private enum ToStringFunction implements Function { + INSTANCE; + + @Override + public String apply(Object o) { + checkNotNull(o); // eager for GWT. + return o.toString(); + } + + @Override + public String toString() { + return "toString"; + } + } + + /** + * Returns the composition of two functions. For {@code f: A->B} and + * {@code g: B->C}, composition is defined as the function h such that + * {@code h(a) == g(f(a))} for each {@code a}. + * + * @param g the second function to apply + * @param f the first function to apply + * @return the composition of {@code f} and {@code g} + * @see function + * composition + */ + public static Function compose(Function g, Function f) { + return new FunctionComposition(g, f); + } + + /** + * Creates a function that returns {@code value} for any input. + * + * @param value the constant value for the function to return + * @return a function that always returns {@code value} + */ + public static Function constant(@Nullable E value) { + return new ConstantFunction(value); + } + + /** + * Returns a function which performs a map lookup with a default value. The + * function created by this method returns {@code defaultValue} for all inputs + * that do not belong to the map's key set. See also {@link #forMap(Map)}, which + * throws an exception in this case. + * + * @param map source map that determines the function behavior + * @param defaultValue the value to return for inputs that aren't map keys + * @return function that returns {@code map.get(a)} when {@code a} is a key, or + * {@code + * defaultValue} otherwise + */ + public static Function forMap(Map map, @Nullable V defaultValue) { + return new ForMapWithDefault(map, defaultValue); + } + + /** + * Returns a function which performs a map lookup. The returned function throws + * an {@link IllegalArgumentException} if given a key that does not exist in the + * map. See also {@link #forMap(Map, Object)}, which returns a default value in + * this case. + * + *

+ * Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or + * can be one), you can use {@link com.google.common.collect.Maps#asConverter + * Maps.asConverter} instead to get a function that also supports reverse + * conversion. + */ + public static Function forMap(Map map) { + return new FunctionForMapNoDefault(map); + } + + /** + * Creates a function that returns the same boolean output as the given + * predicate for all inputs. + * + *

+ * The returned function is consistent with equals (as documented at + * {@link Function#apply}) if and only if {@code predicate} is itself consistent + * with equals. + */ + public static Function forPredicate(Predicate predicate) { + return new PredicateFunction(predicate); + } + + /** + * Returns a function that always returns the result of invoking + * {@link Supplier#get} on {@code + * supplier}, regardless of its input. + * + * @since 10.0 + */ + @Beta + public static Function forSupplier(Supplier supplier) { + return new SupplierFunction(supplier); + } + + /** + * Returns the identity function. + */ + // implementation is "fully variant"; E has become a "pass-through" type + @SuppressWarnings("unchecked") + public static Function identity() { + return (Function) IdentityFunction.INSTANCE; + } + + /** + * Returns a function that calls {@code toString()} on its argument. The + * function does not accept nulls; it will throw a {@link NullPointerException} + * when applied to {@code null}. + * + *

+ * Warning: The returned function may not be consistent with + * equals (as documented at {@link Function#apply}). For example, this + * function yields different results for the two equal instances + * {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}. + */ + public static Function toStringFunction() { + return ToStringFunction.INSTANCE; + } + + private Functions() { } } diff --git a/src/main/java/com/google/common/base/Joiner.java b/src/main/java/com/google/common/base/Joiner.java index 7ac6e321..e55cf581 100644 --- a/src/main/java/com/google/common/base/Joiner.java +++ b/src/main/java/com/google/common/base/Joiner.java @@ -83,232 +83,6 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public class Joiner { - /** - * Returns a joiner which automatically places {@code separator} between - * consecutive elements. - */ - public static Joiner on(String separator) { - return new Joiner(separator); - } - - /** - * Returns a joiner which automatically places {@code separator} between - * consecutive elements. - */ - public static Joiner on(char separator) { - return new Joiner(String.valueOf(separator)); - } - - private final String separator; - - private Joiner(String separator) { - this.separator = checkNotNull(separator); - } - - private Joiner(Joiner prototype) { - this.separator = prototype.separator; - } - - /** - * Appends the string representation of each of {@code parts}, using the - * previously configured separator between each, to {@code appendable}. - */ - public A appendTo(A appendable, Iterable parts) throws IOException { - return appendTo(appendable, parts.iterator()); - } - - /** - * Appends the string representation of each of {@code parts}, using the - * previously configured separator between each, to {@code appendable}. - * - * @since 11.0 - */ - public A appendTo(A appendable, Iterator parts) throws IOException { - checkNotNull(appendable); - if (parts.hasNext()) { - appendable.append(toString(parts.next())); - while (parts.hasNext()) { - appendable.append(separator); - appendable.append(toString(parts.next())); - } - } - return appendable; - } - - /** - * Appends the string representation of each of {@code parts}, using the - * previously configured separator between each, to {@code appendable}. - */ - public final A appendTo(A appendable, Object[] parts) throws IOException { - return appendTo(appendable, Arrays.asList(parts)); - } - - /** - * Appends to {@code appendable} the string representation of each of the - * remaining arguments. - */ - public final A appendTo(A appendable, @Nullable Object first, @Nullable Object second, - Object... rest) throws IOException { - return appendTo(appendable, iterable(first, second, rest)); - } - - /** - * Appends the string representation of each of {@code parts}, using the - * previously configured separator between each, to {@code builder}. Identical - * to {@link #appendTo(Appendable, Iterable)}, except that it does not throw - * {@link IOException}. - */ - public final StringBuilder appendTo(StringBuilder builder, Iterable parts) { - return appendTo(builder, parts.iterator()); - } - - /** - * Appends the string representation of each of {@code parts}, using the - * previously configured separator between each, to {@code builder}. Identical - * to {@link #appendTo(Appendable, Iterable)}, except that it does not throw - * {@link IOException}. - * - * @since 11.0 - */ - public final StringBuilder appendTo(StringBuilder builder, Iterator parts) { - try { - appendTo((Appendable) builder, parts); - } catch (IOException impossible) { - throw new AssertionError(impossible); - } - return builder; - } - - /** - * Appends the string representation of each of {@code parts}, using the - * previously configured separator between each, to {@code builder}. Identical - * to {@link #appendTo(Appendable, Iterable)}, except that it does not throw - * {@link IOException}. - */ - public final StringBuilder appendTo(StringBuilder builder, Object[] parts) { - return appendTo(builder, Arrays.asList(parts)); - } - - /** - * Appends to {@code builder} the string representation of each of the remaining - * arguments. Identical to - * {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does - * not throw {@link IOException}. - */ - public final StringBuilder appendTo(StringBuilder builder, @Nullable Object first, @Nullable Object second, - Object... rest) { - return appendTo(builder, iterable(first, second, rest)); - } - - /** - * Returns a string containing the string representation of each of - * {@code parts}, using the previously configured separator between each. - */ - public final String join(Iterable parts) { - return join(parts.iterator()); - } - - /** - * Returns a string containing the string representation of each of - * {@code parts}, using the previously configured separator between each. - * - * @since 11.0 - */ - public final String join(Iterator parts) { - return appendTo(new StringBuilder(), parts).toString(); - } - - /** - * Returns a string containing the string representation of each of - * {@code parts}, using the previously configured separator between each. - */ - public final String join(Object[] parts) { - return join(Arrays.asList(parts)); - } - - /** - * Returns a string containing the string representation of each argument, using - * the previously configured separator between each. - */ - public final String join(@Nullable Object first, @Nullable Object second, Object... rest) { - return join(iterable(first, second, rest)); - } - - /** - * Returns a joiner with the same behavior as this one, except automatically - * substituting {@code - * nullText} for any provided null elements. - */ - @CheckReturnValue - public Joiner useForNull(final String nullText) { - checkNotNull(nullText); - return new Joiner(this) { - @Override - CharSequence toString(@Nullable Object part) { - return (part == null) ? nullText : Joiner.this.toString(part); - } - - @Override - public Joiner useForNull(String nullText) { - throw new UnsupportedOperationException("already specified useForNull"); - } - - @Override - public Joiner skipNulls() { - throw new UnsupportedOperationException("already specified useForNull"); - } - }; - } - - /** - * Returns a joiner with the same behavior as this joiner, except automatically - * skipping over any provided null elements. - */ - @CheckReturnValue - public Joiner skipNulls() { - return new Joiner(this) { - @Override - public A appendTo(A appendable, Iterator parts) throws IOException { - checkNotNull(appendable, "appendable"); - checkNotNull(parts, "parts"); - while (parts.hasNext()) { - Object part = parts.next(); - if (part != null) { - appendable.append(Joiner.this.toString(part)); - break; - } - } - while (parts.hasNext()) { - Object part = parts.next(); - if (part != null) { - appendable.append(separator); - appendable.append(Joiner.this.toString(part)); - } - } - return appendable; - } - - @Override - public Joiner useForNull(String nullText) { - throw new UnsupportedOperationException("already specified skipNulls"); - } - - @Override - public MapJoiner withKeyValueSeparator(String kvs) { - throw new UnsupportedOperationException("can't use .skipNulls() with maps"); - } - }; - } - - /** - * Returns a {@code MapJoiner} using the given key-value separator, and the same - * configuration as this {@code Joiner} otherwise. - */ - @CheckReturnValue - public MapJoiner withKeyValueSeparator(String keyValueSeparator) { - return new MapJoiner(this, keyValueSeparator); - } - /** * An object that joins map entries in the same manner as {@code Joiner} joins * iterables and arrays. Like {@code Joiner}, it is thread-safe and immutable. @@ -339,34 +113,6 @@ public class Joiner { this.keyValueSeparator = checkNotNull(keyValueSeparator); } - /** - * Appends the string representation of each entry of {@code map}, using the - * previously configured separator and key-value separator, to - * {@code appendable}. - */ - public A appendTo(A appendable, Map map) throws IOException { - return appendTo(appendable, map.entrySet()); - } - - /** - * Appends the string representation of each entry of {@code map}, using the - * previously configured separator and key-value separator, to {@code builder}. - * Identical to {@link #appendTo(Appendable, Map)}, except that it does not - * throw {@link IOException}. - */ - public StringBuilder appendTo(StringBuilder builder, Map map) { - return appendTo(builder, map.entrySet()); - } - - /** - * Returns a string containing the string representation of each entry of - * {@code map}, using the previously configured separator and key-value - * separator. - */ - public String join(Map map) { - return join(map.entrySet()); - } - /** * Appends the string representation of each entry in {@code entries}, using the * previously configured separator and key-value separator, to @@ -407,6 +153,15 @@ public class Joiner { return appendable; } + /** + * Appends the string representation of each entry of {@code map}, using the + * previously configured separator and key-value separator, to + * {@code appendable}. + */ + public A appendTo(A appendable, Map map) throws IOException { + return appendTo(appendable, map.entrySet()); + } + /** * Appends the string representation of each entry in {@code entries}, using the * previously configured separator and key-value separator, to {@code builder}. @@ -438,6 +193,16 @@ public class Joiner { return builder; } + /** + * Appends the string representation of each entry of {@code map}, using the + * previously configured separator and key-value separator, to {@code builder}. + * Identical to {@link #appendTo(Appendable, Map)}, except that it does not + * throw {@link IOException}. + */ + public StringBuilder appendTo(StringBuilder builder, Map map) { + return appendTo(builder, map.entrySet()); + } + /** * Returns a string containing the string representation of each entry in * {@code entries}, using the previously configured separator and key-value @@ -462,6 +227,15 @@ public class Joiner { return appendTo(new StringBuilder(), entries).toString(); } + /** + * Returns a string containing the string representation of each entry of + * {@code map}, using the previously configured separator and key-value + * separator. + */ + public String join(Map map) { + return join(map.entrySet()); + } + /** * Returns a map joiner with the same behavior as this one, except automatically * substituting {@code nullText} for any provided null keys or values. @@ -472,19 +246,9 @@ public class Joiner { } } - CharSequence toString(Object part) { - checkNotNull(part); // checkNotNull for GWT (do not optimize). - return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); - } - private static Iterable iterable(final Object first, final Object second, final Object[] rest) { checkNotNull(rest); return new AbstractList() { - @Override - public int size() { - return rest.length + 2; - } - @Override public Object get(int index) { switch (index) { @@ -496,6 +260,242 @@ public class Joiner { return rest[index - 2]; } } + + @Override + public int size() { + return rest.length + 2; + } }; } + + /** + * Returns a joiner which automatically places {@code separator} between + * consecutive elements. + */ + public static Joiner on(char separator) { + return new Joiner(String.valueOf(separator)); + } + + /** + * Returns a joiner which automatically places {@code separator} between + * consecutive elements. + */ + public static Joiner on(String separator) { + return new Joiner(separator); + } + + private final String separator; + + private Joiner(Joiner prototype) { + this.separator = prototype.separator; + } + + private Joiner(String separator) { + this.separator = checkNotNull(separator); + } + + /** + * Appends the string representation of each of {@code parts}, using the + * previously configured separator between each, to {@code appendable}. + */ + public A appendTo(A appendable, Iterable parts) throws IOException { + return appendTo(appendable, parts.iterator()); + } + + /** + * Appends the string representation of each of {@code parts}, using the + * previously configured separator between each, to {@code appendable}. + * + * @since 11.0 + */ + public A appendTo(A appendable, Iterator parts) throws IOException { + checkNotNull(appendable); + if (parts.hasNext()) { + appendable.append(toString(parts.next())); + while (parts.hasNext()) { + appendable.append(separator); + appendable.append(toString(parts.next())); + } + } + return appendable; + } + + /** + * Appends to {@code appendable} the string representation of each of the + * remaining arguments. + */ + public final A appendTo(A appendable, @Nullable Object first, @Nullable Object second, + Object... rest) throws IOException { + return appendTo(appendable, iterable(first, second, rest)); + } + + /** + * Appends the string representation of each of {@code parts}, using the + * previously configured separator between each, to {@code appendable}. + */ + public final A appendTo(A appendable, Object[] parts) throws IOException { + return appendTo(appendable, Arrays.asList(parts)); + } + + /** + * Appends the string representation of each of {@code parts}, using the + * previously configured separator between each, to {@code builder}. Identical + * to {@link #appendTo(Appendable, Iterable)}, except that it does not throw + * {@link IOException}. + */ + public final StringBuilder appendTo(StringBuilder builder, Iterable parts) { + return appendTo(builder, parts.iterator()); + } + + /** + * Appends the string representation of each of {@code parts}, using the + * previously configured separator between each, to {@code builder}. Identical + * to {@link #appendTo(Appendable, Iterable)}, except that it does not throw + * {@link IOException}. + * + * @since 11.0 + */ + public final StringBuilder appendTo(StringBuilder builder, Iterator parts) { + try { + appendTo((Appendable) builder, parts); + } catch (IOException impossible) { + throw new AssertionError(impossible); + } + return builder; + } + + /** + * Appends to {@code builder} the string representation of each of the remaining + * arguments. Identical to + * {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does + * not throw {@link IOException}. + */ + public final StringBuilder appendTo(StringBuilder builder, @Nullable Object first, @Nullable Object second, + Object... rest) { + return appendTo(builder, iterable(first, second, rest)); + } + + /** + * Appends the string representation of each of {@code parts}, using the + * previously configured separator between each, to {@code builder}. Identical + * to {@link #appendTo(Appendable, Iterable)}, except that it does not throw + * {@link IOException}. + */ + public final StringBuilder appendTo(StringBuilder builder, Object[] parts) { + return appendTo(builder, Arrays.asList(parts)); + } + + /** + * Returns a string containing the string representation of each of + * {@code parts}, using the previously configured separator between each. + */ + public final String join(Iterable parts) { + return join(parts.iterator()); + } + + /** + * Returns a string containing the string representation of each of + * {@code parts}, using the previously configured separator between each. + * + * @since 11.0 + */ + public final String join(Iterator parts) { + return appendTo(new StringBuilder(), parts).toString(); + } + + /** + * Returns a string containing the string representation of each argument, using + * the previously configured separator between each. + */ + public final String join(@Nullable Object first, @Nullable Object second, Object... rest) { + return join(iterable(first, second, rest)); + } + + /** + * Returns a string containing the string representation of each of + * {@code parts}, using the previously configured separator between each. + */ + public final String join(Object[] parts) { + return join(Arrays.asList(parts)); + } + + /** + * Returns a joiner with the same behavior as this joiner, except automatically + * skipping over any provided null elements. + */ + @CheckReturnValue + public Joiner skipNulls() { + return new Joiner(this) { + @Override + public A appendTo(A appendable, Iterator parts) throws IOException { + checkNotNull(appendable, "appendable"); + checkNotNull(parts, "parts"); + while (parts.hasNext()) { + Object part = parts.next(); + if (part != null) { + appendable.append(Joiner.this.toString(part)); + break; + } + } + while (parts.hasNext()) { + Object part = parts.next(); + if (part != null) { + appendable.append(separator); + appendable.append(Joiner.this.toString(part)); + } + } + return appendable; + } + + @Override + public Joiner useForNull(String nullText) { + throw new UnsupportedOperationException("already specified skipNulls"); + } + + @Override + public MapJoiner withKeyValueSeparator(String kvs) { + throw new UnsupportedOperationException("can't use .skipNulls() with maps"); + } + }; + } + + CharSequence toString(Object part) { + checkNotNull(part); // checkNotNull for GWT (do not optimize). + return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); + } + + /** + * Returns a joiner with the same behavior as this one, except automatically + * substituting {@code + * nullText} for any provided null elements. + */ + @CheckReturnValue + public Joiner useForNull(final String nullText) { + checkNotNull(nullText); + return new Joiner(this) { + @Override + public Joiner skipNulls() { + throw new UnsupportedOperationException("already specified useForNull"); + } + + @Override + CharSequence toString(@Nullable Object part) { + return (part == null) ? nullText : Joiner.this.toString(part); + } + + @Override + public Joiner useForNull(String nullText) { + throw new UnsupportedOperationException("already specified useForNull"); + } + }; + } + + /** + * Returns a {@code MapJoiner} using the given key-value separator, and the same + * configuration as this {@code Joiner} otherwise. + */ + @CheckReturnValue + public MapJoiner withKeyValueSeparator(String keyValueSeparator) { + return new MapJoiner(this, keyValueSeparator); + } } diff --git a/src/main/java/com/google/common/base/Objects.java b/src/main/java/com/google/common/base/Objects.java index def8ea00..9915a3a7 100644 --- a/src/main/java/com/google/common/base/Objects.java +++ b/src/main/java/com/google/common/base/Objects.java @@ -38,173 +38,6 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public final class Objects { - private Objects() { - } - - /** - * Determines whether two possibly-null objects are equal. Returns: - * - *
    - *
  • {@code true} if {@code a} and {@code b} are both null. - *
  • {@code true} if {@code a} and {@code b} are both non-null and they are - * equal according to {@link Object#equals(Object)}. - *
  • {@code false} in all other situations. - *
- * - *

- * This assumes that any non-null objects passed to this function conform to the - * {@code equals()} contract. - */ - @CheckReturnValue - public static boolean equal(@Nullable Object a, @Nullable Object b) { - return a == b || (a != null && a.equals(b)); - } - - /** - * Generates a hash code for multiple values. The hash code is generated by - * calling {@link Arrays#hashCode(Object[])}. Note that array arguments to this - * method, with the exception of a single Object array, do not get any special - * handling; their hash codes are based on identity and not contents. - * - *

- * This is useful for implementing {@link Object#hashCode()}. For example, in an - * object that has three properties, {@code x}, {@code y}, and {@code z}, one - * could write: - * - *

-	 *    {@code
-	 *   public int hashCode() {
-	 *     return Objects.hashCode(getX(), getY(), getZ());
-	 *   }}
-	 * 
- * - *

- * Warning: When a single object is supplied, the returned hash code does - * not equal the hash code of that object. - */ - public static int hashCode(@Nullable Object... objects) { - return Arrays.hashCode(objects); - } - - /** - * Creates an instance of {@link ToStringHelper}. - * - *

- * This is helpful for implementing {@link Object#toString()}. Specification by - * example: - * - *

-	 *    {@code
-	 *   // Returns "ClassName{}"
-	 *   Objects.toStringHelper(this)
-	 *       .toString();
-	 *
-	 *   // Returns "ClassName{x=1}"
-	 *   Objects.toStringHelper(this)
-	 *       .add("x", 1)
-	 *       .toString();
-	 *
-	 *   // Returns "MyObject{x=1}"
-	 *   Objects.toStringHelper("MyObject")
-	 *       .add("x", 1)
-	 *       .toString();
-	 *
-	 *   // Returns "ClassName{x=1, y=foo}"
-	 *   Objects.toStringHelper(this)
-	 *       .add("x", 1)
-	 *       .add("y", "foo")
-	 *       .toString();
-	 *
-	 *   // Returns "ClassName{x=1}"
-	 *   Objects.toStringHelper(this)
-	 *       .omitNullValues()
-	 *       .add("x", 1)
-	 *       .add("y", null)
-	 *       .toString();
-	 *   }}
-	 * 
- * - *

- * Note that in GWT, class names are often obfuscated. - * - * @param self the object to generate the string for (typically {@code this}), - * used only for its class name - * @since 2.0 - */ - public static ToStringHelper toStringHelper(Object self) { - return new ToStringHelper(simpleName(self.getClass())); - } - - /** - * Creates an instance of {@link ToStringHelper} in the same manner as - * {@link Objects#toStringHelper(Object)}, but using the name of {@code clazz} - * instead of using an instance's {@link Object#getClass()}. - * - *

- * Note that in GWT, class names are often obfuscated. - * - * @param clazz the {@link Class} of the instance - * @since 7.0 (source-compatible since 2.0) - */ - public static ToStringHelper toStringHelper(Class clazz) { - return new ToStringHelper(simpleName(clazz)); - } - - /** - * Creates an instance of {@link ToStringHelper} in the same manner as - * {@link Objects#toStringHelper(Object)}, but using {@code className} instead - * of using an instance's {@link Object#getClass()}. - * - * @param className the name of the instance type - * @since 7.0 (source-compatible since 2.0) - */ - public static ToStringHelper toStringHelper(String className) { - return new ToStringHelper(className); - } - - /** - * {@link Class#getSimpleName()} is not GWT compatible yet, so we provide our - * own implementation. - */ - private static String simpleName(Class clazz) { - String name = clazz.getName(); - - // the nth anonymous class has a class name ending in "Outer$n" - // and local inner classes have names ending in "Outer.$1Inner" - name = name.replaceAll("\\$[0-9]+", "\\$"); - - // we want the name of the inner class all by its lonesome - int start = name.lastIndexOf('$'); - - // if this isn't an inner class, just find the start of the - // top level class name. - if (start == -1) { - start = name.lastIndexOf('.'); - } - return name.substring(start + 1); - } - - /** - * Returns the first of two given parameters that is not {@code null}, if either - * is, or otherwise throws a {@link NullPointerException}. - * - *

- * Note: if {@code first} is represented as an {@link Optional}, this can - * be accomplished with {@linkplain Optional#or(Object) first.or(second)}. That - * approach also allows for lazy evaluation of the fallback instance, using - * {@linkplain Optional#or(Supplier) first.or(Supplier)}. - * - * @return {@code first} if {@code first} is not {@code null}, or {@code second} - * if {@code first} is {@code null} and {@code second} is not - * {@code null} - * @throws NullPointerException if both {@code first} and {@code second} were - * {@code null} - * @since 3.0 - */ - public static T firstNonNull(@Nullable T first, @Nullable T second) { - return first != null ? first : checkNotNull(second); - } - /** * Support class for {@link Objects#toStringHelper}. * @@ -212,9 +45,16 @@ public final class Objects { * @since 2.0 */ public static final class ToStringHelper { + private static final class ValueHolder { + String name; + Object value; + ValueHolder next; + } + private final String className; private ValueHolder holderHead = new ValueHolder(); private ValueHolder holderTail = holderHead; + private boolean omitNullValues = false; /** @@ -224,28 +64,6 @@ public final class Objects { this.className = checkNotNull(className); } - /** - * Configures the {@link ToStringHelper} so {@link #toString()} will ignore - * properties with null value. The order of calling this method, relative to the - * {@code add()}/{@code addValue()} methods, is not significant. - * - * @since 12.0 - */ - public ToStringHelper omitNullValues() { - omitNullValues = true; - return this; - } - - /** - * Adds a name/value pair to the formatted output in {@code name=value} format. - * If {@code value} is {@code null}, the string {@code "null"} is used, unless - * {@link #omitNullValues()} is called, in which case this name/value pair will - * not be added. - */ - public ToStringHelper add(String name, @Nullable Object value) { - return addHolder(name, value); - } - /** * Adds a name/value pair to the formatted output in {@code name=value} format. * @@ -301,14 +119,32 @@ public final class Objects { } /** - * Adds an unnamed value to the formatted output. - * - *

- * It is strongly encouraged to use {@link #add(String, Object)} instead and - * give value a readable name. + * Adds a name/value pair to the formatted output in {@code name=value} format. + * If {@code value} is {@code null}, the string {@code "null"} is used, unless + * {@link #omitNullValues()} is called, in which case this name/value pair will + * not be added. */ - public ToStringHelper addValue(@Nullable Object value) { - return addHolder(value); + public ToStringHelper add(String name, @Nullable Object value) { + return addHolder(name, value); + } + + private ValueHolder addHolder() { + ValueHolder valueHolder = new ValueHolder(); + holderTail = holderTail.next = valueHolder; + return valueHolder; + } + + private ToStringHelper addHolder(@Nullable Object value) { + ValueHolder valueHolder = addHolder(); + valueHolder.value = value; + return this; + } + + private ToStringHelper addHolder(String name, @Nullable Object value) { + ValueHolder valueHolder = addHolder(); + valueHolder.value = value; + valueHolder.name = checkNotNull(name); + return this; } /** @@ -389,6 +225,29 @@ public final class Objects { return addHolder(String.valueOf(value)); } + /** + * Adds an unnamed value to the formatted output. + * + *

+ * It is strongly encouraged to use {@link #add(String, Object)} instead and + * give value a readable name. + */ + public ToStringHelper addValue(@Nullable Object value) { + return addHolder(value); + } + + /** + * Configures the {@link ToStringHelper} so {@link #toString()} will ignore + * properties with null value. The order of calling this method, relative to the + * {@code add()}/{@code addValue()} methods, is not significant. + * + * @since 12.0 + */ + public ToStringHelper omitNullValues() { + omitNullValues = true; + return this; + } + /** * Returns a string in the format specified by * {@link Objects#toStringHelper(Object)}. @@ -419,30 +278,161 @@ public final class Objects { } return builder.append('}').toString(); } + } - private ValueHolder addHolder() { - ValueHolder valueHolder = new ValueHolder(); - holderTail = holderTail.next = valueHolder; - return valueHolder; - } + /** + * Determines whether two possibly-null objects are equal. Returns: + * + *

    + *
  • {@code true} if {@code a} and {@code b} are both null. + *
  • {@code true} if {@code a} and {@code b} are both non-null and they are + * equal according to {@link Object#equals(Object)}. + *
  • {@code false} in all other situations. + *
+ * + *

+ * This assumes that any non-null objects passed to this function conform to the + * {@code equals()} contract. + */ + @CheckReturnValue + public static boolean equal(@Nullable Object a, @Nullable Object b) { + return a == b || (a != null && a.equals(b)); + } - private ToStringHelper addHolder(@Nullable Object value) { - ValueHolder valueHolder = addHolder(); - valueHolder.value = value; - return this; - } + /** + * Returns the first of two given parameters that is not {@code null}, if either + * is, or otherwise throws a {@link NullPointerException}. + * + *

+ * Note: if {@code first} is represented as an {@link Optional}, this can + * be accomplished with {@linkplain Optional#or(Object) first.or(second)}. That + * approach also allows for lazy evaluation of the fallback instance, using + * {@linkplain Optional#or(Supplier) first.or(Supplier)}. + * + * @return {@code first} if {@code first} is not {@code null}, or {@code second} + * if {@code first} is {@code null} and {@code second} is not + * {@code null} + * @throws NullPointerException if both {@code first} and {@code second} were + * {@code null} + * @since 3.0 + */ + public static T firstNonNull(@Nullable T first, @Nullable T second) { + return first != null ? first : checkNotNull(second); + } - private ToStringHelper addHolder(String name, @Nullable Object value) { - ValueHolder valueHolder = addHolder(); - valueHolder.value = value; - valueHolder.name = checkNotNull(name); - return this; - } + /** + * Generates a hash code for multiple values. The hash code is generated by + * calling {@link Arrays#hashCode(Object[])}. Note that array arguments to this + * method, with the exception of a single Object array, do not get any special + * handling; their hash codes are based on identity and not contents. + * + *

+ * This is useful for implementing {@link Object#hashCode()}. For example, in an + * object that has three properties, {@code x}, {@code y}, and {@code z}, one + * could write: + * + *

+	 *    {@code
+	 * public int hashCode() {
+	 * 	return Objects.hashCode(getX(), getY(), getZ());
+	 * }
+	 * }
+	 * 
+ * + *

+ * Warning: When a single object is supplied, the returned hash code does + * not equal the hash code of that object. + */ + public static int hashCode(@Nullable Object... objects) { + return Arrays.hashCode(objects); + } - private static final class ValueHolder { - String name; - Object value; - ValueHolder next; + /** + * {@link Class#getSimpleName()} is not GWT compatible yet, so we provide our + * own implementation. + */ + private static String simpleName(Class clazz) { + String name = clazz.getName(); + + // the nth anonymous class has a class name ending in "Outer$n" + // and local inner classes have names ending in "Outer.$1Inner" + name = name.replaceAll("\\$[0-9]+", "\\$"); + + // we want the name of the inner class all by its lonesome + int start = name.lastIndexOf('$'); + + // if this isn't an inner class, just find the start of the + // top level class name. + if (start == -1) { + start = name.lastIndexOf('.'); } + return name.substring(start + 1); + } + + /** + * Creates an instance of {@link ToStringHelper} in the same manner as + * {@link Objects#toStringHelper(Object)}, but using the name of {@code clazz} + * instead of using an instance's {@link Object#getClass()}. + * + *

+ * Note that in GWT, class names are often obfuscated. + * + * @param clazz the {@link Class} of the instance + * @since 7.0 (source-compatible since 2.0) + */ + public static ToStringHelper toStringHelper(Class clazz) { + return new ToStringHelper(simpleName(clazz)); + } + + /** + * Creates an instance of {@link ToStringHelper}. + * + *

+ * This is helpful for implementing {@link Object#toString()}. Specification by + * example: + * + *

+	 *    {@code
+	 * // Returns "ClassName{}"
+	 * Objects.toStringHelper(this).toString();
+	 *
+	 * // Returns "ClassName{x=1}"
+	 * Objects.toStringHelper(this).add("x", 1).toString();
+	 *
+	 * // Returns "MyObject{x=1}"
+	 * Objects.toStringHelper("MyObject").add("x", 1).toString();
+	 *
+	 * // Returns "ClassName{x=1, y=foo}"
+	 * Objects.toStringHelper(this).add("x", 1).add("y", "foo").toString();
+	 *
+	 * // Returns "ClassName{x=1}"
+	 * Objects.toStringHelper(this).omitNullValues().add("x", 1).add("y", null).toString();
+	 * }}
+	 * 
+ * + *

+ * Note that in GWT, class names are often obfuscated. + * + * @param self the object to generate the string for (typically {@code this}), + * used only for its class name + * @since 2.0 + */ + public static ToStringHelper toStringHelper(Object self) { + return new ToStringHelper(simpleName(self.getClass())); + } + + /** + * Creates an instance of {@link ToStringHelper} in the same manner as + * {@link Objects#toStringHelper(Object)}, but using {@code className} instead + * of using an instance's {@link Object#getClass()}. + * + * @param className the name of the instance type + * @since 7.0 (source-compatible since 2.0) + */ + public static ToStringHelper toStringHelper(String className) { + return new ToStringHelper(className); + } + + private Objects() { } } diff --git a/src/main/java/com/google/common/base/Optional.java b/src/main/java/com/google/common/base/Optional.java index 43b8eb2d..1c29e6c8 100644 --- a/src/main/java/com/google/common/base/Optional.java +++ b/src/main/java/com/google/common/base/Optional.java @@ -80,6 +80,8 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(serializable = true) public abstract class Optional implements Serializable { + private static final long serialVersionUID = 0; + /** * Returns an {@code Optional} instance with no contained reference. */ @@ -87,13 +89,6 @@ public abstract class Optional implements Serializable { return Absent.withType(); } - /** - * Returns an {@code Optional} instance containing the given non-null reference. - */ - public static Optional of(T reference) { - return new Present(checkNotNull(reference)); - } - /** * If {@code nullableReference} is non-null, returns an {@code Optional} * instance containing that reference; otherwise returns @@ -103,132 +98,13 @@ public abstract class Optional implements Serializable { return (nullableReference == null) ? Optional.absent() : new Present(nullableReference); } - Optional() { + /** + * Returns an {@code Optional} instance containing the given non-null reference. + */ + public static Optional of(T reference) { + return new Present(checkNotNull(reference)); } - /** - * Returns {@code true} if this holder contains a (non-null) instance. - */ - public abstract boolean isPresent(); - - /** - * Returns the contained instance, which must be present. If the instance might - * be absent, use {@link #or(Object)} or {@link #orNull} instead. - * - * @throws IllegalStateException if the instance is absent ({@link #isPresent} - * returns {@code false}) - */ - public abstract T get(); - - /** - * Returns the contained instance if it is present; {@code defaultValue} - * otherwise. If no default value should be required because the instance is - * known to be present, use {@link #get()} instead. For a default value of - * {@code null}, use {@link #orNull}. - * - *

- * Note about generics: The signature {@code public T or(T defaultValue)} is - * overly restrictive. However, the ideal signature, - * {@code public S or(S)}, is not legal Java. As a result, some - * sensible operations involving subtypes are compile errors: - * - *

-	 *    {@code
-	 *
-	 *   Optional optionalInt = getSomeOptionalInt();
-	 *   Number value = optionalInt.or(0.5); // error
-	 *
-	 *   FluentIterable numbers = getSomeNumbers();
-	 *   Optional first = numbers.first();
-	 *   Number value = first.or(0.5); // error}
-	 * 
- * - *

- * As a workaround, it is always safe to cast an {@code Optional} - * to {@code - * Optional}. Casting either of the above example {@code Optional} instances - * to {@code - * Optional} (where {@code Number} is the desired output type) solves - * the problem: - * - *

-	 *    {@code
-	 *
-	 *   Optional optionalInt = (Optional) getSomeOptionalInt();
-	 *   Number value = optionalInt.or(0.5); // fine
-	 *
-	 *   FluentIterable numbers = getSomeNumbers();
-	 *   Optional first = (Optional) numbers.first();
-	 *   Number value = first.or(0.5); // fine}
-	 * 
- */ - public abstract T or(T defaultValue); - - /** - * Returns this {@code Optional} if it has a value present; {@code secondChoice} - * otherwise. - */ - public abstract Optional or(Optional secondChoice); - - /** - * Returns the contained instance if it is present; {@code supplier.get()} - * otherwise. If the supplier returns {@code null}, a - * {@link NullPointerException} is thrown. - * - * @throws NullPointerException if the supplier returns {@code null} - */ - @Beta - public abstract T or(Supplier supplier); - - /** - * Returns the contained instance if it is present; {@code null} otherwise. If - * the instance is known to be present, use {@link #get()} instead. - */ - @Nullable - public abstract T orNull(); - - /** - * Returns an immutable singleton {@link Set} whose only element is the - * contained instance if it is present; an empty immutable {@link Set} - * otherwise. - * - * @since 11.0 - */ - public abstract Set asSet(); - - /** - * If the instance is present, it is transformed with the given - * {@link Function}; otherwise, {@link Optional#absent} is returned. If the - * function returns {@code null}, a {@link NullPointerException} is thrown. - * - * @throws NullPointerException if the function returns {@code null} - * - * @since 12.0 - */ - public abstract Optional transform(Function function); - - /** - * Returns {@code true} if {@code object} is an {@code Optional} instance, and - * either the contained references are {@linkplain Object#equals equal} to each - * other or both are absent. Note that {@code Optional} instances of differing - * parameterized types can be equal. - */ - @Override - public abstract boolean equals(@Nullable Object object); - - /** - * Returns a hash code for this instance. - */ - @Override - public abstract int hashCode(); - - /** - * Returns a string representation for this instance. The form of this string - * representation is unspecified. - */ - @Override - public abstract String toString(); - /** * Returns the value of each present instance from the supplied * {@code optionals}, in order, skipping over occurrences of @@ -261,5 +137,131 @@ public abstract class Optional implements Serializable { }; } - private static final long serialVersionUID = 0; + Optional() { + } + + /** + * Returns an immutable singleton {@link Set} whose only element is the + * contained instance if it is present; an empty immutable {@link Set} + * otherwise. + * + * @since 11.0 + */ + public abstract Set asSet(); + + /** + * Returns {@code true} if {@code object} is an {@code Optional} instance, and + * either the contained references are {@linkplain Object#equals equal} to each + * other or both are absent. Note that {@code Optional} instances of differing + * parameterized types can be equal. + */ + @Override + public abstract boolean equals(@Nullable Object object); + + /** + * Returns the contained instance, which must be present. If the instance might + * be absent, use {@link #or(Object)} or {@link #orNull} instead. + * + * @throws IllegalStateException if the instance is absent ({@link #isPresent} + * returns {@code false}) + */ + public abstract T get(); + + /** + * Returns a hash code for this instance. + */ + @Override + public abstract int hashCode(); + + /** + * Returns {@code true} if this holder contains a (non-null) instance. + */ + public abstract boolean isPresent(); + + /** + * Returns this {@code Optional} if it has a value present; {@code secondChoice} + * otherwise. + */ + public abstract Optional or(Optional secondChoice); + + /** + * Returns the contained instance if it is present; {@code supplier.get()} + * otherwise. If the supplier returns {@code null}, a + * {@link NullPointerException} is thrown. + * + * @throws NullPointerException if the supplier returns {@code null} + */ + @Beta + public abstract T or(Supplier supplier); + + /** + * Returns the contained instance if it is present; {@code defaultValue} + * otherwise. If no default value should be required because the instance is + * known to be present, use {@link #get()} instead. For a default value of + * {@code null}, use {@link #orNull}. + * + *

+ * Note about generics: The signature {@code public T or(T defaultValue)} is + * overly restrictive. However, the ideal signature, + * {@code public S or(S)}, is not legal Java. As a result, some + * sensible operations involving subtypes are compile errors: + * + *

+	 *    {@code
+	 *
+	 * Optional optionalInt = getSomeOptionalInt();
+	 * Number value = optionalInt.or(0.5); // error
+	 *
+	 * FluentIterable numbers = getSomeNumbers();
+	 * Optional first = numbers.first();
+	 * Number value = first.or(0.5); // error
+	 * }
+	 * 
+ * + *

+ * As a workaround, it is always safe to cast an {@code Optional} + * to {@code + * Optional}. Casting either of the above example {@code Optional} instances + * to {@code + * Optional} (where {@code Number} is the desired output type) solves + * the problem: + * + *

+	 *    {@code
+	 *
+	 * Optional optionalInt = (Optional) getSomeOptionalInt();
+	 * Number value = optionalInt.or(0.5); // fine
+	 *
+	 * FluentIterable numbers = getSomeNumbers();
+	 * Optional first = (Optional) numbers.first();
+	 * Number value = first.or(0.5); // fine
+	 * }
+	 * 
+ */ + public abstract T or(T defaultValue); + + /** + * Returns the contained instance if it is present; {@code null} otherwise. If + * the instance is known to be present, use {@link #get()} instead. + */ + @Nullable + public abstract T orNull(); + + /** + * Returns a string representation for this instance. The form of this string + * representation is unspecified. + */ + @Override + public abstract String toString(); + + /** + * If the instance is present, it is transformed with the given + * {@link Function}; otherwise, {@link Optional#absent} is returned. If the + * function returns {@code null}, a {@link NullPointerException} is thrown. + * + * @throws NullPointerException if the function returns {@code null} + * + * @since 12.0 + */ + public abstract Optional transform(Function function); } diff --git a/src/main/java/com/google/common/base/PairwiseEquivalence.java b/src/main/java/com/google/common/base/PairwiseEquivalence.java index f3528d4f..177906c8 100644 --- a/src/main/java/com/google/common/base/PairwiseEquivalence.java +++ b/src/main/java/com/google/common/base/PairwiseEquivalence.java @@ -26,6 +26,8 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible(serializable = true) final class PairwiseEquivalence extends Equivalence> implements Serializable { + private static final long serialVersionUID = 1; + final Equivalence elementEquivalence; PairwiseEquivalence(Equivalence elementEquivalence) { @@ -74,6 +76,4 @@ final class PairwiseEquivalence extends Equivalence> implements S public String toString() { return elementEquivalence + ".pairwise()"; } - - private static final long serialVersionUID = 1; } diff --git a/src/main/java/com/google/common/base/Platform.java b/src/main/java/com/google/common/base/Platform.java index 04b2fdd6..d13c3dd9 100644 --- a/src/main/java/com/google/common/base/Platform.java +++ b/src/main/java/com/google/common/base/Platform.java @@ -27,7 +27,13 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(emulated = true) final class Platform { - private Platform() { + static > Optional getEnumIfPresent(Class enumClass, String value) { + WeakReference> ref = Enums.getEnumConstants(enumClass).get(value); + return ref == null ? Optional.absent() : Optional.of(enumClass.cast(ref.get())); + } + + static CharMatcher precomputeCharMatcher(CharMatcher matcher) { + return matcher.precomputedInternal(); } /** Calls {@link System#nanoTime()}. */ @@ -35,12 +41,6 @@ final class Platform { return System.nanoTime(); } - static CharMatcher precomputeCharMatcher(CharMatcher matcher) { - return matcher.precomputedInternal(); - } - - static > Optional getEnumIfPresent(Class enumClass, String value) { - WeakReference> ref = Enums.getEnumConstants(enumClass).get(value); - return ref == null ? Optional.absent() : Optional.of(enumClass.cast(ref.get())); + private Platform() { } } diff --git a/src/main/java/com/google/common/base/Preconditions.java b/src/main/java/com/google/common/base/Preconditions.java index 3ff8b69d..e414864f 100644 --- a/src/main/java/com/google/common/base/Preconditions.java +++ b/src/main/java/com/google/common/base/Preconditions.java @@ -66,9 +66,10 @@ import com.google.common.annotations.GwtCompatible; *
  *    {@code
  *
- *   if (value < 0.0) {
- *     throw new IllegalArgumentException("negative value: " + value);
- *   }}
+ * if (value < 0.0) {
+ * 	throw new IllegalArgumentException("negative value: " + value);
+ * }
+ * }
  * 
* *

Other types of preconditions

@@ -123,7 +124,35 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public final class Preconditions { - private Preconditions() { + private static String badElementIndex(int index, int size, String desc) { + if (index < 0) { + return format("%s (%s) must not be negative", desc, index); + } else if (size < 0) { + throw new IllegalArgumentException("negative size: " + size); + } else { // index >= size + return format("%s (%s) must be less than size (%s)", desc, index, size); + } + } + + private static String badPositionIndex(int index, int size, String desc) { + if (index < 0) { + return format("%s (%s) must not be negative", desc, index); + } else if (size < 0) { + throw new IllegalArgumentException("negative size: " + size); + } else { // index > size + return format("%s (%s) must not be greater than size (%s)", desc, index, size); + } + } + + private static String badPositionIndexes(int start, int end, int size) { + if (start < 0 || start > size) { + return badPositionIndex(start, size, "start index"); + } + if (end < 0 || end > size) { + return badPositionIndex(end, size, "end index"); + } + // end < start + return format("end index (%s) must not be less than start index (%s)", end, start); } /** @@ -184,6 +213,191 @@ public final class Preconditions { } } + /** + * Ensures that {@code index} specifies a valid element in an array, list + * or string of size {@code size}. An element index may range from zero, + * inclusive, to {@code size}, exclusive. + * + * @param index a user-supplied index identifying an element of an array, list + * or string + * @param size the size of that array, list or string + * @return the value of {@code index} + * @throws IndexOutOfBoundsException if {@code index} is negative or is not less + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative + */ + public static int checkElementIndex(int index, int size) { + return checkElementIndex(index, size, "index"); + } + + /** + * Ensures that {@code index} specifies a valid element in an array, list + * or string of size {@code size}. An element index may range from zero, + * inclusive, to {@code size}, exclusive. + * + * @param index a user-supplied index identifying an element of an array, list + * or string + * @param size the size of that array, list or string + * @param desc the text to use to describe this index in an error message + * @return the value of {@code index} + * @throws IndexOutOfBoundsException if {@code index} is negative or is not less + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative + */ + public static int checkElementIndex(int index, int size, @Nullable String desc) { + // Carefully optimized for execution by hotspot (explanatory comment above) + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); + } + return index; + } + + /** + * Ensures that an object reference passed as a parameter to the calling method + * is not null. + * + * @param reference an object reference + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference) { + if (reference == null) { + throw new NullPointerException(); + } + return reference; + } + + /** + * Ensures that an object reference passed as a parameter to the calling method + * is not null. + * + * @param reference an object reference + * @param errorMessage the exception message to use if the check fails; will be + * converted to a string using + * {@link String#valueOf(Object)} + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference, @Nullable Object errorMessage) { + if (reference == null) { + throw new NullPointerException(String.valueOf(errorMessage)); + } + return reference; + } + + /* + * All recent hotspots (as of 2009) *really* like to have the natural code + * + * if (guardExpression) { throw new BadException(messageExpression); } + * + * refactored so that messageExpression is moved to a separate String-returning + * method. + * + * if (guardExpression) { throw new BadException(badMsg(...)); } + * + * The alternative natural refactorings into void or Exception-returning methods + * are much slower. This is a big deal - we're talking factors of 2-8 in + * microbenchmarks, not just 10-20%. (This is a hotspot optimizer bug, which + * should be fixed, but that's a separate, big project). + * + * The coding pattern above is heavily used in java.util, e.g. in ArrayList. + * There is a RangeCheckMicroBenchmark in the JDK that was used to test this. + * + * But the methods in this class want to throw different exceptions, depending + * on the args, so it appears that this pattern is not directly applicable. But + * we can use the ridiculous, devious trick of throwing an exception in the + * middle of the construction of another exception. Hotspot is fine with that. + */ + + /** + * Ensures that an object reference passed as a parameter to the calling method + * is not null. + * + * @param reference an object reference + * @param errorMessageTemplate a template for the exception message should the + * check fail. The message is formed by replacing + * each {@code %s} placeholder in the template with + * an argument. These are matched by position - the + * first {@code %s} gets {@code + * errorMessageArgs[0]} , etc. Unmatched arguments will be appended to + * the formatted message in square braces. Unmatched + * placeholders will be left as-is. + * @param errorMessageArgs the arguments to be substituted into the message + * template. Arguments are converted to strings + * using {@link String#valueOf(Object)}. + * @return the non-null reference that was validated + * @throws NullPointerException if {@code reference} is null + */ + public static T checkNotNull(T reference, @Nullable String errorMessageTemplate, + @Nullable Object... errorMessageArgs) { + if (reference == null) { + // If either of these parameters is null, the right thing happens anyway + throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); + } + return reference; + } + + /** + * Ensures that {@code index} specifies a valid position in an array, + * list or string of size {@code size}. A position index may range from zero to + * {@code size}, inclusive. + * + * @param index a user-supplied index identifying a position in an array, list + * or string + * @param size the size of that array, list or string + * @return the value of {@code index} + * @throws IndexOutOfBoundsException if {@code index} is negative or is greater + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative + */ + public static int checkPositionIndex(int index, int size) { + return checkPositionIndex(index, size, "index"); + } + + /** + * Ensures that {@code index} specifies a valid position in an array, + * list or string of size {@code size}. A position index may range from zero to + * {@code size}, inclusive. + * + * @param index a user-supplied index identifying a position in an array, list + * or string + * @param size the size of that array, list or string + * @param desc the text to use to describe this index in an error message + * @return the value of {@code index} + * @throws IndexOutOfBoundsException if {@code index} is negative or is greater + * than {@code size} + * @throws IllegalArgumentException if {@code size} is negative + */ + public static int checkPositionIndex(int index, int size, @Nullable String desc) { + // Carefully optimized for execution by hotspot (explanatory comment above) + if (index < 0 || index > size) { + throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); + } + return index; + } + + /** + * Ensures that {@code start} and {@code end} specify a valid positions + * in an array, list or string of size {@code size}, and are in order. A + * position index may range from zero to {@code size}, inclusive. + * + * @param start a user-supplied index identifying a starting position in an + * array, list or string + * @param end a user-supplied index identifying a ending position in an array, + * list or string + * @param size the size of that array, list or string + * @throws IndexOutOfBoundsException if either index is negative or is greater + * than {@code size}, or if {@code end} is + * less than {@code start} + * @throws IllegalArgumentException if {@code size} is negative + */ + public static void checkPositionIndexes(int start, int end, int size) { + // Carefully optimized for execution by hotspot (explanatory comment above) + if (start < 0 || end < start || end > size) { + throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); + } + } + /** * Ensures the truth of an expression involving the state of the calling * instance, but not involving any parameters to the calling method. @@ -242,222 +456,6 @@ public final class Preconditions { } } - /** - * Ensures that an object reference passed as a parameter to the calling method - * is not null. - * - * @param reference an object reference - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference) { - if (reference == null) { - throw new NullPointerException(); - } - return reference; - } - - /** - * Ensures that an object reference passed as a parameter to the calling method - * is not null. - * - * @param reference an object reference - * @param errorMessage the exception message to use if the check fails; will be - * converted to a string using - * {@link String#valueOf(Object)} - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference, @Nullable Object errorMessage) { - if (reference == null) { - throw new NullPointerException(String.valueOf(errorMessage)); - } - return reference; - } - - /** - * Ensures that an object reference passed as a parameter to the calling method - * is not null. - * - * @param reference an object reference - * @param errorMessageTemplate a template for the exception message should the - * check fail. The message is formed by replacing - * each {@code %s} placeholder in the template with - * an argument. These are matched by position - the - * first {@code %s} gets {@code - * errorMessageArgs[0]} , etc. Unmatched arguments will be appended to - * the formatted message in square braces. Unmatched - * placeholders will be left as-is. - * @param errorMessageArgs the arguments to be substituted into the message - * template. Arguments are converted to strings - * using {@link String#valueOf(Object)}. - * @return the non-null reference that was validated - * @throws NullPointerException if {@code reference} is null - */ - public static T checkNotNull(T reference, @Nullable String errorMessageTemplate, - @Nullable Object... errorMessageArgs) { - if (reference == null) { - // If either of these parameters is null, the right thing happens anyway - throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); - } - return reference; - } - - /* - * All recent hotspots (as of 2009) *really* like to have the natural code - * - * if (guardExpression) { throw new BadException(messageExpression); } - * - * refactored so that messageExpression is moved to a separate String-returning - * method. - * - * if (guardExpression) { throw new BadException(badMsg(...)); } - * - * The alternative natural refactorings into void or Exception-returning methods - * are much slower. This is a big deal - we're talking factors of 2-8 in - * microbenchmarks, not just 10-20%. (This is a hotspot optimizer bug, which - * should be fixed, but that's a separate, big project). - * - * The coding pattern above is heavily used in java.util, e.g. in ArrayList. - * There is a RangeCheckMicroBenchmark in the JDK that was used to test this. - * - * But the methods in this class want to throw different exceptions, depending - * on the args, so it appears that this pattern is not directly applicable. But - * we can use the ridiculous, devious trick of throwing an exception in the - * middle of the construction of another exception. Hotspot is fine with that. - */ - - /** - * Ensures that {@code index} specifies a valid element in an array, list - * or string of size {@code size}. An element index may range from zero, - * inclusive, to {@code size}, exclusive. - * - * @param index a user-supplied index identifying an element of an array, list - * or string - * @param size the size of that array, list or string - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is not less - * than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkElementIndex(int index, int size) { - return checkElementIndex(index, size, "index"); - } - - /** - * Ensures that {@code index} specifies a valid element in an array, list - * or string of size {@code size}. An element index may range from zero, - * inclusive, to {@code size}, exclusive. - * - * @param index a user-supplied index identifying an element of an array, list - * or string - * @param size the size of that array, list or string - * @param desc the text to use to describe this index in an error message - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is not less - * than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkElementIndex(int index, int size, @Nullable String desc) { - // Carefully optimized for execution by hotspot (explanatory comment above) - if (index < 0 || index >= size) { - throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); - } - return index; - } - - private static String badElementIndex(int index, int size, String desc) { - if (index < 0) { - return format("%s (%s) must not be negative", desc, index); - } else if (size < 0) { - throw new IllegalArgumentException("negative size: " + size); - } else { // index >= size - return format("%s (%s) must be less than size (%s)", desc, index, size); - } - } - - /** - * Ensures that {@code index} specifies a valid position in an array, - * list or string of size {@code size}. A position index may range from zero to - * {@code size}, inclusive. - * - * @param index a user-supplied index identifying a position in an array, list - * or string - * @param size the size of that array, list or string - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is greater - * than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkPositionIndex(int index, int size) { - return checkPositionIndex(index, size, "index"); - } - - /** - * Ensures that {@code index} specifies a valid position in an array, - * list or string of size {@code size}. A position index may range from zero to - * {@code size}, inclusive. - * - * @param index a user-supplied index identifying a position in an array, list - * or string - * @param size the size of that array, list or string - * @param desc the text to use to describe this index in an error message - * @return the value of {@code index} - * @throws IndexOutOfBoundsException if {@code index} is negative or is greater - * than {@code size} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static int checkPositionIndex(int index, int size, @Nullable String desc) { - // Carefully optimized for execution by hotspot (explanatory comment above) - if (index < 0 || index > size) { - throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); - } - return index; - } - - private static String badPositionIndex(int index, int size, String desc) { - if (index < 0) { - return format("%s (%s) must not be negative", desc, index); - } else if (size < 0) { - throw new IllegalArgumentException("negative size: " + size); - } else { // index > size - return format("%s (%s) must not be greater than size (%s)", desc, index, size); - } - } - - /** - * Ensures that {@code start} and {@code end} specify a valid positions - * in an array, list or string of size {@code size}, and are in order. A - * position index may range from zero to {@code size}, inclusive. - * - * @param start a user-supplied index identifying a starting position in an - * array, list or string - * @param end a user-supplied index identifying a ending position in an array, - * list or string - * @param size the size of that array, list or string - * @throws IndexOutOfBoundsException if either index is negative or is greater - * than {@code size}, or if {@code end} is - * less than {@code start} - * @throws IllegalArgumentException if {@code size} is negative - */ - public static void checkPositionIndexes(int start, int end, int size) { - // Carefully optimized for execution by hotspot (explanatory comment above) - if (start < 0 || end < start || end > size) { - throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); - } - } - - private static String badPositionIndexes(int start, int end, int size) { - if (start < 0 || start > size) { - return badPositionIndex(start, size, "start index"); - } - if (end < 0 || end > size) { - return badPositionIndex(end, size, "end index"); - } - // end < start - return format("end index (%s) must not be less than start index (%s)", end, start); - } - /** * Substitutes each {@code %s} in {@code template} with an argument. These are * matched by position: the first {@code %s} gets {@code args[0]}, etc. If there @@ -502,4 +500,7 @@ public final class Preconditions { return builder.toString(); } + + private Preconditions() { + } } diff --git a/src/main/java/com/google/common/base/Predicates.java b/src/main/java/com/google/common/base/Predicates.java index 4aa9b7c0..dca9099b 100644 --- a/src/main/java/com/google/common/base/Predicates.java +++ b/src/main/java/com/google/common/base/Predicates.java @@ -48,224 +48,331 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) public final class Predicates { - private Predicates() { + /** @see Predicates#and(Iterable) */ + private static class AndPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + + private final List> components; + + private AndPredicate(List> components) { + this.components = components; + } + + @Override + public boolean apply(@Nullable T t) { + // Avoid using the Iterator to avoid generating garbage (issue 820). + for (int i = 0; i < components.size(); i++) { + if (!components.get(i).apply(t)) { + return false; + } + } + return true; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof AndPredicate) { + AndPredicate that = (AndPredicate) obj; + return components.equals(that.components); + } + return false; + } + + @Override + public int hashCode() { + // add a random number to avoid collisions with OrPredicate + return components.hashCode() + 0x12472c2c; + } + + @Override + public String toString() { + return "Predicates.and(" + COMMA_JOINER.join(components) + ")"; + } } // TODO(kevinb): considering having these implement a VisitablePredicate // interface which specifies an accept(PredicateVisitor) method. - /** - * Returns a predicate that always evaluates to {@code true}. - */ - @GwtCompatible(serializable = true) - public static Predicate alwaysTrue() { - return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); - } - - /** - * Returns a predicate that always evaluates to {@code false}. - */ - @GwtCompatible(serializable = true) - public static Predicate alwaysFalse() { - return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); - } - - /** - * Returns a predicate that evaluates to {@code true} if the object reference - * being tested is null. - */ - @GwtCompatible(serializable = true) - public static Predicate isNull() { - return ObjectPredicate.IS_NULL.withNarrowedType(); - } - - /** - * Returns a predicate that evaluates to {@code true} if the object reference - * being tested is not null. - */ - @GwtCompatible(serializable = true) - public static Predicate notNull() { - return ObjectPredicate.NOT_NULL.withNarrowedType(); - } - - /** - * Returns a predicate that evaluates to {@code true} if the given predicate - * evaluates to {@code false}. - */ - public static Predicate not(Predicate predicate) { - return new NotPredicate(predicate); - } - - /** - * Returns a predicate that evaluates to {@code true} if each of its components - * evaluates to {@code true}. The components are evaluated in order, and - * evaluation will be "short-circuited" as soon as a false predicate is found. - * It defensively copies the iterable passed in, so future changes to it won't - * alter the behavior of this predicate. If {@code - * components} is empty, the returned predicate will always evaluate to {@code - * true}. - */ - public static Predicate and(Iterable> components) { - return new AndPredicate(defensiveCopy(components)); - } - - /** - * Returns a predicate that evaluates to {@code true} if each of its components - * evaluates to {@code true}. The components are evaluated in order, and - * evaluation will be "short-circuited" as soon as a false predicate is found. - * It defensively copies the array passed in, so future changes to it won't - * alter the behavior of this predicate. If {@code - * components} is empty, the returned predicate will always evaluate to {@code - * true}. - */ - public static Predicate and(Predicate... components) { - return new AndPredicate(defensiveCopy(components)); - } - - /** - * Returns a predicate that evaluates to {@code true} if both of its components - * evaluate to {@code true}. The components are evaluated in order, and - * evaluation will be "short-circuited" as soon as a false predicate is found. - */ - public static Predicate and(Predicate first, Predicate second) { - return new AndPredicate(Predicates.asList(checkNotNull(first), checkNotNull(second))); - } - - /** - * Returns a predicate that evaluates to {@code true} if any one of its - * components evaluates to {@code true}. The components are evaluated in order, - * and evaluation will be "short-circuited" as soon as a true predicate is - * found. It defensively copies the iterable passed in, so future changes to it - * won't alter the behavior of this predicate. If {@code - * components} is empty, the returned predicate will always evaluate to {@code - * false}. - */ - public static Predicate or(Iterable> components) { - return new OrPredicate(defensiveCopy(components)); - } - - /** - * Returns a predicate that evaluates to {@code true} if any one of its - * components evaluates to {@code true}. The components are evaluated in order, - * and evaluation will be "short-circuited" as soon as a true predicate is - * found. It defensively copies the array passed in, so future changes to it - * won't alter the behavior of this predicate. If {@code - * components} is empty, the returned predicate will always evaluate to {@code - * false}. - */ - public static Predicate or(Predicate... components) { - return new OrPredicate(defensiveCopy(components)); - } - - /** - * Returns a predicate that evaluates to {@code true} if either of its - * components evaluates to {@code true}. The components are evaluated in order, - * and evaluation will be "short-circuited" as soon as a true predicate is - * found. - */ - public static Predicate or(Predicate first, Predicate second) { - return new OrPredicate(Predicates.asList(checkNotNull(first), checkNotNull(second))); - } - - /** - * Returns a predicate that evaluates to {@code true} if the object being tested - * {@code equals()} the given target or both are null. - */ - public static Predicate equalTo(@Nullable T target) { - return (target == null) ? Predicates.isNull() : new IsEqualToPredicate(target); - } - - /** - * Returns a predicate that evaluates to {@code true} if the object being tested - * is an instance of the given class. If the object being tested is {@code null} - * this predicate evaluates to {@code false}. - * - *

- * If you want to filter an {@code Iterable} to narrow its type, consider using - * {@link com.google.common.collect.Iterables#filter(Iterable, Class)} in - * preference. - * - *

- * Warning: contrary to the typical assumptions about predicates (as - * documented at {@link Predicate#apply}), the returned predicate may not be - * consistent with equals. For example, {@code - * instanceOf(ArrayList.class)} will yield different results for the two equal - * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. - */ - @GwtIncompatible("Class.isInstance") - public static Predicate instanceOf(Class clazz) { - return new InstanceOfPredicate(clazz); - } - - /** - * Returns a predicate that evaluates to {@code true} if the class being tested - * is assignable from the given class. The returned predicate does not allow - * null inputs. - * - * @since 10.0 - */ + /** @see Predicates#assignableFrom(Class) */ @GwtIncompatible("Class.isAssignableFrom") - @Beta - public static Predicate> assignableFrom(Class clazz) { - return new AssignableFromPredicate(clazz); + private static class AssignableFromPredicate implements Predicate>, Serializable { + private static final long serialVersionUID = 0; + + private final Class clazz; + + private AssignableFromPredicate(Class clazz) { + this.clazz = checkNotNull(clazz); + } + + @Override + public boolean apply(Class input) { + return clazz.isAssignableFrom(input); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof AssignableFromPredicate) { + AssignableFromPredicate that = (AssignableFromPredicate) obj; + return clazz == that.clazz; + } + return false; + } + + @Override + public int hashCode() { + return clazz.hashCode(); + } + + @Override + public String toString() { + return "Predicates.assignableFrom(" + clazz.getName() + ")"; + } } - /** - * Returns a predicate that evaluates to {@code true} if the object reference - * being tested is a member of the given collection. It does not defensively - * copy the collection passed in, so future changes to it will alter the - * behavior of the predicate. - * - *

- * This method can technically accept any {@code Collection}, but using a - * typed collection helps prevent bugs. This approach doesn't block any - * potential users since it is always possible to use {@code - * Predicates.in()}. - * - * @param target the collection that may contain the function input - */ - public static Predicate in(Collection target) { - return new InPredicate(target); + /** @see Predicates#compose(Predicate, Function) */ + private static class CompositionPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + final Predicate p; + + final Function f; + + private CompositionPredicate(Predicate p, Function f) { + this.p = checkNotNull(p); + this.f = checkNotNull(f); + } + + @Override + public boolean apply(@Nullable A a) { + return p.apply(f.apply(a)); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof CompositionPredicate) { + CompositionPredicate that = (CompositionPredicate) obj; + return f.equals(that.f) && p.equals(that.p); + } + return false; + } + + @Override + public int hashCode() { + return f.hashCode() ^ p.hashCode(); + } + + @Override + public String toString() { + return p.toString() + "(" + f.toString() + ")"; + } } - /** - * Returns the composition of a function and a predicate. For every {@code x}, - * the generated predicate returns {@code predicate(function(x))}. - * - * @return the composition of the provided function and predicate - */ - public static Predicate compose(Predicate predicate, Function function) { - return new CompositionPredicate(predicate, function); + /** @see Predicates#containsPattern(String) */ + @GwtIncompatible("Only used by other GWT-incompatible code.") + private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { + + private static final long serialVersionUID = 0; + + ContainsPatternFromStringPredicate(String string) { + super(Pattern.compile(string)); + } + + @Override + public String toString() { + return "Predicates.containsPattern(" + pattern.pattern() + ")"; + } } - /** - * Returns a predicate that evaluates to {@code true} if the - * {@code CharSequence} being tested contains any match for the given regular - * expression pattern. The test used is equivalent to - * {@code Pattern.compile(pattern).matcher(arg).find()} - * - * @throws java.util.regex.PatternSyntaxException if the pattern is invalid - * @since 3.0 - */ - @GwtIncompatible(value = "java.util.regex.Pattern") - public static Predicate containsPattern(String pattern) { - return new ContainsPatternFromStringPredicate(pattern); + /** @see Predicates#contains(Pattern) */ + @GwtIncompatible("Only used by other GWT-incompatible code.") + private static class ContainsPatternPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + + final Pattern pattern; + + ContainsPatternPredicate(Pattern pattern) { + this.pattern = checkNotNull(pattern); + } + + @Override + public boolean apply(CharSequence t) { + return pattern.matcher(t).find(); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof ContainsPatternPredicate) { + ContainsPatternPredicate that = (ContainsPatternPredicate) obj; + + // Pattern uses Object (identity) equality, so we have to reach + // inside to compare individual fields. + return Objects.equal(pattern.pattern(), that.pattern.pattern()) + && Objects.equal(pattern.flags(), that.pattern.flags()); + } + return false; + } + + @Override + public int hashCode() { + // Pattern uses Object.hashCode, so we have to reach + // inside to build a hashCode consistent with equals. + + return Objects.hashCode(pattern.pattern(), pattern.flags()); + } + + @Override + public String toString() { + String patternString = Objects.toStringHelper(pattern).add("pattern", pattern.pattern()) + .add("pattern.flags", pattern.flags()).toString(); + return "Predicates.contains(" + patternString + ")"; + } } - /** - * Returns a predicate that evaluates to {@code true} if the - * {@code CharSequence} being tested contains any match for the given regular - * expression pattern. The test used is equivalent to - * {@code pattern.matcher(arg).find()} - * - * @since 3.0 - */ - @GwtIncompatible(value = "java.util.regex.Pattern") - public static Predicate contains(Pattern pattern) { - return new ContainsPatternPredicate(pattern); + /** @see Predicates#in(Collection) */ + private static class InPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + + private final Collection target; + + private InPredicate(Collection target) { + this.target = checkNotNull(target); + } + + @Override + public boolean apply(@Nullable T t) { + try { + return target.contains(t); + } catch (NullPointerException e) { + return false; + } catch (ClassCastException e) { + return false; + } + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof InPredicate) { + InPredicate that = (InPredicate) obj; + return target.equals(that.target); + } + return false; + } + + @Override + public int hashCode() { + return target.hashCode(); + } + + @Override + public String toString() { + return "Predicates.in(" + target + ")"; + } } - // End public API, begin private implementation classes. + /** @see Predicates#instanceOf(Class) */ + @GwtIncompatible("Class.isInstance") + private static class InstanceOfPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + + private final Class clazz; + + private InstanceOfPredicate(Class clazz) { + this.clazz = checkNotNull(clazz); + } + + @Override + public boolean apply(@Nullable Object o) { + return clazz.isInstance(o); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof InstanceOfPredicate) { + InstanceOfPredicate that = (InstanceOfPredicate) obj; + return clazz == that.clazz; + } + return false; + } + + @Override + public int hashCode() { + return clazz.hashCode(); + } + + @Override + public String toString() { + return "Predicates.instanceOf(" + clazz.getName() + ")"; + } + } + + /** @see Predicates#equalTo(Object) */ + private static class IsEqualToPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + + private final T target; + + private IsEqualToPredicate(T target) { + this.target = target; + } + + @Override + public boolean apply(T t) { + return target.equals(t); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof IsEqualToPredicate) { + IsEqualToPredicate that = (IsEqualToPredicate) obj; + return target.equals(that.target); + } + return false; + } + + @Override + public int hashCode() { + return target.hashCode(); + } + + @Override + public String toString() { + return "Predicates.equalTo(" + target + ")"; + } + } + + /** @see Predicates#not(Predicate) */ + private static class NotPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + + final Predicate predicate; + + NotPredicate(Predicate predicate) { + this.predicate = checkNotNull(predicate); + } + + @Override + public boolean apply(@Nullable T t) { + return !predicate.apply(t); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof NotPredicate) { + NotPredicate that = (NotPredicate) obj; + return predicate.equals(that.predicate); + } + return false; + } + + @Override + public int hashCode() { + return ~predicate.hashCode(); + } + + @Override + public String toString() { + return "Predicates.not(" + predicate.toString() + ")"; + } + } // Package private for GWT serialization. enum ObjectPredicate implements Predicate { @@ -324,87 +431,10 @@ public final class Predicates { } } - /** @see Predicates#not(Predicate) */ - private static class NotPredicate implements Predicate, Serializable { - final Predicate predicate; - - NotPredicate(Predicate predicate) { - this.predicate = checkNotNull(predicate); - } - - @Override - public boolean apply(@Nullable T t) { - return !predicate.apply(t); - } - - @Override - public int hashCode() { - return ~predicate.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof NotPredicate) { - NotPredicate that = (NotPredicate) obj; - return predicate.equals(that.predicate); - } - return false; - } - - @Override - public String toString() { - return "Predicates.not(" + predicate.toString() + ")"; - } - - private static final long serialVersionUID = 0; - } - - private static final Joiner COMMA_JOINER = Joiner.on(','); - - /** @see Predicates#and(Iterable) */ - private static class AndPredicate implements Predicate, Serializable { - private final List> components; - - private AndPredicate(List> components) { - this.components = components; - } - - @Override - public boolean apply(@Nullable T t) { - // Avoid using the Iterator to avoid generating garbage (issue 820). - for (int i = 0; i < components.size(); i++) { - if (!components.get(i).apply(t)) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - // add a random number to avoid collisions with OrPredicate - return components.hashCode() + 0x12472c2c; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof AndPredicate) { - AndPredicate that = (AndPredicate) obj; - return components.equals(that.components); - } - return false; - } - - @Override - public String toString() { - return "Predicates.and(" + COMMA_JOINER.join(components) + ")"; - } - - private static final long serialVersionUID = 0; - } - /** @see Predicates#or(Iterable) */ private static class OrPredicate implements Predicate, Serializable { + private static final long serialVersionUID = 0; + private final List> components; private OrPredicate(List> components) { @@ -422,12 +452,6 @@ public final class Predicates { return false; } - @Override - public int hashCode() { - // add a random number to avoid collisions with AndPredicate - return components.hashCode() + 0x053c91cf; - } - @Override public boolean equals(@Nullable Object obj) { if (obj instanceof OrPredicate) { @@ -437,258 +461,69 @@ public final class Predicates { return false; } + @Override + public int hashCode() { + // add a random number to avoid collisions with AndPredicate + return components.hashCode() + 0x053c91cf; + } + @Override public String toString() { return "Predicates.or(" + COMMA_JOINER.join(components) + ")"; } - - private static final long serialVersionUID = 0; } - /** @see Predicates#equalTo(Object) */ - private static class IsEqualToPredicate implements Predicate, Serializable { - private final T target; + private static final Joiner COMMA_JOINER = Joiner.on(','); - private IsEqualToPredicate(T target) { - this.target = target; - } - - @Override - public boolean apply(T t) { - return target.equals(t); - } - - @Override - public int hashCode() { - return target.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof IsEqualToPredicate) { - IsEqualToPredicate that = (IsEqualToPredicate) obj; - return target.equals(that.target); - } - return false; - } - - @Override - public String toString() { - return "Predicates.equalTo(" + target + ")"; - } - - private static final long serialVersionUID = 0; + /** + * Returns a predicate that always evaluates to {@code false}. + */ + @GwtCompatible(serializable = true) + public static Predicate alwaysFalse() { + return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); } - /** @see Predicates#instanceOf(Class) */ - @GwtIncompatible("Class.isInstance") - private static class InstanceOfPredicate implements Predicate, Serializable { - private final Class clazz; - - private InstanceOfPredicate(Class clazz) { - this.clazz = checkNotNull(clazz); - } - - @Override - public boolean apply(@Nullable Object o) { - return clazz.isInstance(o); - } - - @Override - public int hashCode() { - return clazz.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof InstanceOfPredicate) { - InstanceOfPredicate that = (InstanceOfPredicate) obj; - return clazz == that.clazz; - } - return false; - } - - @Override - public String toString() { - return "Predicates.instanceOf(" + clazz.getName() + ")"; - } - - private static final long serialVersionUID = 0; + /** + * Returns a predicate that always evaluates to {@code true}. + */ + @GwtCompatible(serializable = true) + public static Predicate alwaysTrue() { + return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); } - /** @see Predicates#assignableFrom(Class) */ - @GwtIncompatible("Class.isAssignableFrom") - private static class AssignableFromPredicate implements Predicate>, Serializable { - private final Class clazz; - - private AssignableFromPredicate(Class clazz) { - this.clazz = checkNotNull(clazz); - } - - @Override - public boolean apply(Class input) { - return clazz.isAssignableFrom(input); - } - - @Override - public int hashCode() { - return clazz.hashCode(); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof AssignableFromPredicate) { - AssignableFromPredicate that = (AssignableFromPredicate) obj; - return clazz == that.clazz; - } - return false; - } - - @Override - public String toString() { - return "Predicates.assignableFrom(" + clazz.getName() + ")"; - } - - private static final long serialVersionUID = 0; + /** + * Returns a predicate that evaluates to {@code true} if each of its components + * evaluates to {@code true}. The components are evaluated in order, and + * evaluation will be "short-circuited" as soon as a false predicate is found. + * It defensively copies the iterable passed in, so future changes to it won't + * alter the behavior of this predicate. If {@code + * components} is empty, the returned predicate will always evaluate to {@code + * true}. + */ + public static Predicate and(Iterable> components) { + return new AndPredicate(defensiveCopy(components)); } - /** @see Predicates#in(Collection) */ - private static class InPredicate implements Predicate, Serializable { - private final Collection target; - - private InPredicate(Collection target) { - this.target = checkNotNull(target); - } - - @Override - public boolean apply(@Nullable T t) { - try { - return target.contains(t); - } catch (NullPointerException e) { - return false; - } catch (ClassCastException e) { - return false; - } - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof InPredicate) { - InPredicate that = (InPredicate) obj; - return target.equals(that.target); - } - return false; - } - - @Override - public int hashCode() { - return target.hashCode(); - } - - @Override - public String toString() { - return "Predicates.in(" + target + ")"; - } - - private static final long serialVersionUID = 0; + /** + * Returns a predicate that evaluates to {@code true} if each of its components + * evaluates to {@code true}. The components are evaluated in order, and + * evaluation will be "short-circuited" as soon as a false predicate is found. + * It defensively copies the array passed in, so future changes to it won't + * alter the behavior of this predicate. If {@code + * components} is empty, the returned predicate will always evaluate to {@code + * true}. + */ + public static Predicate and(Predicate... components) { + return new AndPredicate(defensiveCopy(components)); } - /** @see Predicates#compose(Predicate, Function) */ - private static class CompositionPredicate implements Predicate, Serializable { - final Predicate p; - final Function f; - - private CompositionPredicate(Predicate p, Function f) { - this.p = checkNotNull(p); - this.f = checkNotNull(f); - } - - @Override - public boolean apply(@Nullable A a) { - return p.apply(f.apply(a)); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof CompositionPredicate) { - CompositionPredicate that = (CompositionPredicate) obj; - return f.equals(that.f) && p.equals(that.p); - } - return false; - } - - @Override - public int hashCode() { - return f.hashCode() ^ p.hashCode(); - } - - @Override - public String toString() { - return p.toString() + "(" + f.toString() + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** @see Predicates#contains(Pattern) */ - @GwtIncompatible("Only used by other GWT-incompatible code.") - private static class ContainsPatternPredicate implements Predicate, Serializable { - final Pattern pattern; - - ContainsPatternPredicate(Pattern pattern) { - this.pattern = checkNotNull(pattern); - } - - @Override - public boolean apply(CharSequence t) { - return pattern.matcher(t).find(); - } - - @Override - public int hashCode() { - // Pattern uses Object.hashCode, so we have to reach - // inside to build a hashCode consistent with equals. - - return Objects.hashCode(pattern.pattern(), pattern.flags()); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof ContainsPatternPredicate) { - ContainsPatternPredicate that = (ContainsPatternPredicate) obj; - - // Pattern uses Object (identity) equality, so we have to reach - // inside to compare individual fields. - return Objects.equal(pattern.pattern(), that.pattern.pattern()) - && Objects.equal(pattern.flags(), that.pattern.flags()); - } - return false; - } - - @Override - public String toString() { - String patternString = Objects.toStringHelper(pattern).add("pattern", pattern.pattern()) - .add("pattern.flags", pattern.flags()).toString(); - return "Predicates.contains(" + patternString + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** @see Predicates#containsPattern(String) */ - @GwtIncompatible("Only used by other GWT-incompatible code.") - private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { - - ContainsPatternFromStringPredicate(String string) { - super(Pattern.compile(string)); - } - - @Override - public String toString() { - return "Predicates.containsPattern(" + pattern.pattern() + ")"; - } - - private static final long serialVersionUID = 0; + /** + * Returns a predicate that evaluates to {@code true} if both of its components + * evaluate to {@code true}. The components are evaluated in order, and + * evaluation will be "short-circuited" as soon as a false predicate is found. + */ + public static Predicate and(Predicate first, Predicate second) { + return new AndPredicate(Predicates.asList(checkNotNull(first), checkNotNull(second))); } private static List> asList(Predicate first, Predicate second) { @@ -696,8 +531,56 @@ public final class Predicates { return Arrays.>asList(first, second); } - private static List defensiveCopy(T... array) { - return defensiveCopy(Arrays.asList(array)); + /** + * Returns a predicate that evaluates to {@code true} if the class being tested + * is assignable from the given class. The returned predicate does not allow + * null inputs. + * + * @since 10.0 + */ + @GwtIncompatible("Class.isAssignableFrom") + @Beta + public static Predicate> assignableFrom(Class clazz) { + return new AssignableFromPredicate(clazz); + } + + // End public API, begin private implementation classes. + + /** + * Returns the composition of a function and a predicate. For every {@code x}, + * the generated predicate returns {@code predicate(function(x))}. + * + * @return the composition of the provided function and predicate + */ + public static Predicate compose(Predicate predicate, Function function) { + return new CompositionPredicate(predicate, function); + } + + /** + * Returns a predicate that evaluates to {@code true} if the + * {@code CharSequence} being tested contains any match for the given regular + * expression pattern. The test used is equivalent to + * {@code pattern.matcher(arg).find()} + * + * @since 3.0 + */ + @GwtIncompatible(value = "java.util.regex.Pattern") + public static Predicate contains(Pattern pattern) { + return new ContainsPatternPredicate(pattern); + } + + /** + * Returns a predicate that evaluates to {@code true} if the + * {@code CharSequence} being tested contains any match for the given regular + * expression pattern. The test used is equivalent to + * {@code Pattern.compile(pattern).matcher(arg).find()} + * + * @throws java.util.regex.PatternSyntaxException if the pattern is invalid + * @since 3.0 + */ + @GwtIncompatible(value = "java.util.regex.Pattern") + public static Predicate containsPattern(String pattern) { + return new ContainsPatternFromStringPredicate(pattern); } static List defensiveCopy(Iterable iterable) { @@ -707,4 +590,121 @@ public final class Predicates { } return list; } + + private static List defensiveCopy(T... array) { + return defensiveCopy(Arrays.asList(array)); + } + + /** + * Returns a predicate that evaluates to {@code true} if the object being tested + * {@code equals()} the given target or both are null. + */ + public static Predicate equalTo(@Nullable T target) { + return (target == null) ? Predicates.isNull() : new IsEqualToPredicate(target); + } + + /** + * Returns a predicate that evaluates to {@code true} if the object reference + * being tested is a member of the given collection. It does not defensively + * copy the collection passed in, so future changes to it will alter the + * behavior of the predicate. + * + *

+ * This method can technically accept any {@code Collection}, but using a + * typed collection helps prevent bugs. This approach doesn't block any + * potential users since it is always possible to use {@code + * Predicates.in()}. + * + * @param target the collection that may contain the function input + */ + public static Predicate in(Collection target) { + return new InPredicate(target); + } + + /** + * Returns a predicate that evaluates to {@code true} if the object being tested + * is an instance of the given class. If the object being tested is {@code null} + * this predicate evaluates to {@code false}. + * + *

+ * If you want to filter an {@code Iterable} to narrow its type, consider using + * {@link com.google.common.collect.Iterables#filter(Iterable, Class)} in + * preference. + * + *

+ * Warning: contrary to the typical assumptions about predicates (as + * documented at {@link Predicate#apply}), the returned predicate may not be + * consistent with equals. For example, {@code + * instanceOf(ArrayList.class)} will yield different results for the two equal + * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. + */ + @GwtIncompatible("Class.isInstance") + public static Predicate instanceOf(Class clazz) { + return new InstanceOfPredicate(clazz); + } + + /** + * Returns a predicate that evaluates to {@code true} if the object reference + * being tested is null. + */ + @GwtCompatible(serializable = true) + public static Predicate isNull() { + return ObjectPredicate.IS_NULL.withNarrowedType(); + } + + /** + * Returns a predicate that evaluates to {@code true} if the given predicate + * evaluates to {@code false}. + */ + public static Predicate not(Predicate predicate) { + return new NotPredicate(predicate); + } + + /** + * Returns a predicate that evaluates to {@code true} if the object reference + * being tested is not null. + */ + @GwtCompatible(serializable = true) + public static Predicate notNull() { + return ObjectPredicate.NOT_NULL.withNarrowedType(); + } + + /** + * Returns a predicate that evaluates to {@code true} if any one of its + * components evaluates to {@code true}. The components are evaluated in order, + * and evaluation will be "short-circuited" as soon as a true predicate is + * found. It defensively copies the iterable passed in, so future changes to it + * won't alter the behavior of this predicate. If {@code + * components} is empty, the returned predicate will always evaluate to {@code + * false}. + */ + public static Predicate or(Iterable> components) { + return new OrPredicate(defensiveCopy(components)); + } + + /** + * Returns a predicate that evaluates to {@code true} if any one of its + * components evaluates to {@code true}. The components are evaluated in order, + * and evaluation will be "short-circuited" as soon as a true predicate is + * found. It defensively copies the array passed in, so future changes to it + * won't alter the behavior of this predicate. If {@code + * components} is empty, the returned predicate will always evaluate to {@code + * false}. + */ + public static Predicate or(Predicate... components) { + return new OrPredicate(defensiveCopy(components)); + } + + /** + * Returns a predicate that evaluates to {@code true} if either of its + * components evaluates to {@code true}. The components are evaluated in order, + * and evaluation will be "short-circuited" as soon as a true predicate is + * found. + */ + public static Predicate or(Predicate first, Predicate second) { + return new OrPredicate(Predicates.asList(checkNotNull(first), checkNotNull(second))); + } + + private Predicates() { + } } diff --git a/src/main/java/com/google/common/base/Present.java b/src/main/java/com/google/common/base/Present.java index 1c19c400..28d765cc 100644 --- a/src/main/java/com/google/common/base/Present.java +++ b/src/main/java/com/google/common/base/Present.java @@ -30,6 +30,8 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible final class Present extends Optional { + private static final long serialVersionUID = 0; + private final T reference; Present(T reference) { @@ -37,8 +39,17 @@ final class Present extends Optional { } @Override - public boolean isPresent() { - return true; + public Set asSet() { + return Collections.singleton(reference); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof Present) { + Present other = (Present) object; + return reference.equals(other.reference); + } + return false; } @Override @@ -47,9 +58,13 @@ final class Present extends Optional { } @Override - public T or(T defaultValue) { - checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)"); - return reference; + public int hashCode() { + return 0x598df91c + reference.hashCode(); + } + + @Override + public boolean isPresent() { + return true; } @Override @@ -65,33 +80,14 @@ final class Present extends Optional { } @Override - public T orNull() { + public T or(T defaultValue) { + checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)"); return reference; } @Override - public Set asSet() { - return Collections.singleton(reference); - } - - @Override - public Optional transform(Function function) { - return new Present(checkNotNull(function.apply(reference), - "the Function passed to Optional.transform() must not return null.")); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof Present) { - Present other = (Present) object; - return reference.equals(other.reference); - } - return false; - } - - @Override - public int hashCode() { - return 0x598df91c + reference.hashCode(); + public T orNull() { + return reference; } @Override @@ -99,5 +95,9 @@ final class Present extends Optional { return "Optional.of(" + reference + ")"; } - private static final long serialVersionUID = 0; + @Override + public Optional transform(Function function) { + return new Present(checkNotNull(function.apply(reference), + "the Function passed to Optional.transform() must not return null.")); + } } diff --git a/src/main/java/com/google/common/base/SmallCharMatcher.java b/src/main/java/com/google/common/base/SmallCharMatcher.java index 24a8d3ae..153bc6ad 100644 --- a/src/main/java/com/google/common/base/SmallCharMatcher.java +++ b/src/main/java/com/google/common/base/SmallCharMatcher.java @@ -31,41 +31,8 @@ import com.google.common.base.CharMatcher.FastMatcher; @GwtIncompatible("no precomputation is done in GWT") final class SmallCharMatcher extends FastMatcher { static final int MAX_SIZE = 1023; - private final char[] table; - private final boolean containsZero; - private final long filter; - - private SmallCharMatcher(char[] table, long filter, boolean containsZero, String description) { - super(description); - this.table = table; - this.filter = filter; - this.containsZero = containsZero; - } - private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; - - /* - * This method was rewritten in Java from an intermediate step of the Murmur - * hash function in - * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which - * contained the following header: - * - * MurmurHash3 was written by Austin Appleby, and is placed in the public - * domain. The author hereby disclaims copyright to this source code. - */ - static int smear(int hashCode) { - return C2 * Integer.rotateLeft(hashCode * C1, 15); - } - - private boolean checkFilter(int c) { - return 1 == (1 & (filter >> c)); - } - - // This is all essentially copied from ImmutableSet, but we have to duplicate - // because - // of dependencies. - // Represents how tightly we can pack things, as a maximum. private static final double DESIRED_LOAD_FACTOR = 0.5; @@ -114,6 +81,40 @@ final class SmallCharMatcher extends FastMatcher { return new SmallCharMatcher(table, filter, containsZero, description); } + /* + * This method was rewritten in Java from an intermediate step of the Murmur + * hash function in + * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which + * contained the following header: + * + * MurmurHash3 was written by Austin Appleby, and is placed in the public + * domain. The author hereby disclaims copyright to this source code. + */ + static int smear(int hashCode) { + return C2 * Integer.rotateLeft(hashCode * C1, 15); + } + + private final char[] table; + + private final boolean containsZero; + + // This is all essentially copied from ImmutableSet, but we have to duplicate + // because + // of dependencies. + + private final long filter; + + private SmallCharMatcher(char[] table, long filter, boolean containsZero, String description) { + super(description); + this.table = table; + this.filter = filter; + this.containsZero = containsZero; + } + + private boolean checkFilter(int c) { + return 1 == (1 & (filter >> c)); + } + @Override public boolean matches(char c) { if (c == 0) { diff --git a/src/main/java/com/google/common/base/Splitter.java b/src/main/java/com/google/common/base/Splitter.java index e047c545..5a1a62c2 100644 --- a/src/main/java/com/google/common/base/Splitter.java +++ b/src/main/java/com/google/common/base/Splitter.java @@ -49,7 +49,8 @@ import com.google.common.annotations.GwtIncompatible; *
  *    {@code
  *
- *   Splitter.on(',').split("foo,bar,qux")}
+ * Splitter.on(',').split("foo,bar,qux")
+ * }
  * 
* * ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and @@ -62,7 +63,8 @@ import com.google.common.annotations.GwtIncompatible; *
  *    {@code
  *
- *   Splitter.on(',').split(" foo,,,  bar ,")}
+ * Splitter.on(',').split(" foo,,,  bar ,")
+ * }
  * 
* * ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this is @@ -127,376 +129,6 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) public final class Splitter { - private final CharMatcher trimmer; - private final boolean omitEmptyStrings; - private final Strategy strategy; - private final int limit; - - private Splitter(Strategy strategy) { - this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE); - } - - private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { - this.strategy = strategy; - this.omitEmptyStrings = omitEmptyStrings; - this.trimmer = trimmer; - this.limit = limit; - } - - /** - * Returns a splitter that uses the given single-character separator. For - * example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable - * containing {@code ["foo", "", "bar"]}. - * - * @param separator the character to recognize as a separator - * @return a splitter, with default settings, that recognizes that separator - */ - public static Splitter on(char separator) { - return on(CharMatcher.is(separator)); - } - - /** - * Returns a splitter that considers any single character matched by the given - * {@code CharMatcher} to be a separator. For example, {@code - * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an - * iterable containing {@code ["foo", "", "bar", "quux"]}. - * - * @param separatorMatcher a {@link CharMatcher} that determines whether a - * character is a separator - * @return a splitter, with default settings, that uses this matcher - */ - public static Splitter on(final CharMatcher separatorMatcher) { - checkNotNull(separatorMatcher); - - return new Splitter(new Strategy() { - @Override - public SplittingIterator iterator(Splitter splitter, final CharSequence toSplit) { - return new SplittingIterator(splitter, toSplit) { - @Override - int separatorStart(int start) { - return separatorMatcher.indexIn(toSplit, start); - } - - @Override - int separatorEnd(int separatorPosition) { - return separatorPosition + 1; - } - }; - } - }); - } - - /** - * Returns a splitter that uses the given fixed string as a separator. For - * example, {@code Splitter.on(", ").split("foo, bar,baz")} returns an iterable - * containing {@code ["foo", "bar,baz"]}. - * - * @param separator the literal, nonempty string to recognize as a separator - * @return a splitter, with default settings, that recognizes that separator - */ - public static Splitter on(final String separator) { - checkArgument(separator.length() != 0, "The separator may not be the empty string."); - - return new Splitter(new Strategy() { - @Override - public SplittingIterator iterator(Splitter splitter, CharSequence toSplit) { - return new SplittingIterator(splitter, toSplit) { - @Override - public int separatorStart(int start) { - int separatorLength = separator.length(); - - positions: for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) { - for (int i = 0; i < separatorLength; i++) { - if (toSplit.charAt(i + p) != separator.charAt(i)) { - continue positions; - } - } - return p; - } - return -1; - } - - @Override - public int separatorEnd(int separatorPosition) { - return separatorPosition + separator.length(); - } - }; - } - }); - } - - /** - * Returns a splitter that considers any subsequence matching {@code - * pattern} to be a separator. For example, {@code - * Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string into - * lines whether it uses DOS-style or UNIX-style line terminators. - * - * @param separatorPattern the pattern that determines whether a subsequence is - * a separator. This pattern may not match the empty - * string. - * @return a splitter, with default settings, that uses this pattern - * @throws IllegalArgumentException if {@code separatorPattern} matches the - * empty string - */ - @GwtIncompatible("java.util.regex") - public static Splitter on(final Pattern separatorPattern) { - checkNotNull(separatorPattern); - checkArgument(!separatorPattern.matcher("").matches(), "The pattern may not match the empty string: %s", - separatorPattern); - - return new Splitter(new Strategy() { - @Override - public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { - final Matcher matcher = separatorPattern.matcher(toSplit); - return new SplittingIterator(splitter, toSplit) { - @Override - public int separatorStart(int start) { - return matcher.find(start) ? matcher.start() : -1; - } - - @Override - public int separatorEnd(int separatorPosition) { - return matcher.end(); - } - }; - } - }); - } - - /** - * Returns a splitter that considers any subsequence matching a given pattern - * (regular expression) to be a separator. For example, {@code - * Splitter.onPattern("\r?\n").split(entireFile)} splits a string into lines - * whether it uses DOS-style or UNIX-style line terminators. This is equivalent - * to {@code Splitter.on(Pattern.compile(pattern))}. - * - * @param separatorPattern the pattern that determines whether a subsequence is - * a separator. This pattern may not match the empty - * string. - * @return a splitter, with default settings, that uses this pattern - * @throws java.util.regex.PatternSyntaxException if {@code separatorPattern} is - * a malformed expression - * @throws IllegalArgumentException if {@code separatorPattern} - * matches the empty string - */ - @GwtIncompatible("java.util.regex") - public static Splitter onPattern(String separatorPattern) { - return on(Pattern.compile(separatorPattern)); - } - - /** - * Returns a splitter that divides strings into pieces of the given length. For - * example, {@code Splitter.fixedLength(2).split("abcde")} returns an iterable - * containing {@code ["ab", "cd", "e"]}. The last piece can be smaller than - * {@code length} but will never be empty. - * - *

- * Exception: for consistency with separator-based splitters, {@code - * split("")} does not yield an empty iterable, but an iterable containing - * {@code ""}. This is the only case in which {@code - * Iterables.size(split(input))} does not equal {@code - * IntMath.divide(input.length(), length, CEILING)}. To avoid this behavior, use - * {@code omitEmptyStrings}. - * - * @param length the desired length of pieces after splitting, a positive - * integer - * @return a splitter, with default settings, that can split into fixed sized - * pieces - * @throws IllegalArgumentException if {@code length} is zero or negative - */ - public static Splitter fixedLength(final int length) { - checkArgument(length > 0, "The length may not be less than 1"); - - return new Splitter(new Strategy() { - @Override - public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { - return new SplittingIterator(splitter, toSplit) { - @Override - public int separatorStart(int start) { - int nextChunkStart = start + length; - return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); - } - - @Override - public int separatorEnd(int separatorPosition) { - return separatorPosition; - } - }; - } - }); - } - - /** - * Returns a splitter that behaves equivalently to {@code this} splitter, but - * automatically omits empty strings from the results. For example, {@code - * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an iterable - * containing only {@code ["a", "b", "c"]}. - * - *

- * If either {@code trimResults} option is also specified when creating a - * splitter, that splitter always trims results first before checking for - * emptiness. So, for example, {@code - * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns an - * empty iterable. - * - *

- * Note that it is ordinarily not possible for {@link #split(CharSequence)} to - * return an empty iterable, but when using this option, it can (if the input - * sequence consists of nothing but separators). - * - * @return a splitter with the desired configuration - */ - @CheckReturnValue - public Splitter omitEmptyStrings() { - return new Splitter(strategy, true, trimmer, limit); - } - - /** - * Returns a splitter that behaves equivalently to {@code this} splitter but - * stops splitting after it reaches the limit. The limit defines the maximum - * number of items returned by the iterator. - * - *

- * For example, {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an - * iterable containing {@code ["a", "b", "c,d"]}. When omitting empty strings, - * the omitted strings do no count. Hence, - * {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} - * returns an iterable containing {@code ["a", "b", "c,d"}. When trim is - * requested, all entries, including the last are trimmed. Hence - * {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")} - * results in @{code ["a", "b", "c , d"]}. - * - * @param limit the maximum number of items returns - * @return a splitter with the desired configuration - * @since 9.0 - */ - @CheckReturnValue - public Splitter limit(int limit) { - checkArgument(limit > 0, "must be greater than zero: %s", limit); - return new Splitter(strategy, omitEmptyStrings, trimmer, limit); - } - - /** - * Returns a splitter that behaves equivalently to {@code this} splitter, but - * automatically removes leading and trailing {@linkplain CharMatcher#WHITESPACE - * whitespace} from each returned substring; equivalent to - * {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code - * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable - * containing {@code ["a", "b", "c"]}. - * - * @return a splitter with the desired configuration - */ - @CheckReturnValue - public Splitter trimResults() { - return trimResults(CharMatcher.WHITESPACE); - } - - /** - * Returns a splitter that behaves equivalently to {@code this} splitter, but - * removes all leading or trailing characters matching the given {@code - * CharMatcher} from each returned substring. For example, {@code - * Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} - * returns an iterable containing {@code ["a ", "b_ ", "c"]}. - * - * @param trimmer a {@link CharMatcher} that determines whether a character - * should be removed from the beginning/end of a subsequence - * @return a splitter with the desired configuration - */ - // TODO(kevinb): throw if a trimmer was already specified! - @CheckReturnValue - public Splitter trimResults(CharMatcher trimmer) { - checkNotNull(trimmer); - return new Splitter(strategy, omitEmptyStrings, trimmer, limit); - } - - /** - * Splits {@code sequence} into string components and makes them available - * through an {@link Iterator}, which may be lazily evaluated. If you want an - * eagerly computed {@link List}, use {@link #splitToList(CharSequence)}. - * - * @param sequence the sequence of characters to split - * @return an iteration over the segments split from the parameter. - */ - public Iterable split(final CharSequence sequence) { - checkNotNull(sequence); - - return new Iterable() { - @Override - public Iterator iterator() { - return splittingIterator(sequence); - } - - @Override - public String toString() { - return Joiner.on(", ").appendTo(new StringBuilder().append('['), this).append(']').toString(); - } - }; - } - - private Iterator splittingIterator(CharSequence sequence) { - return strategy.iterator(this, sequence); - } - - /** - * Splits {@code sequence} into string components and returns them as an - * immutable list. If you want an {@link Iterable} which may be lazily - * evaluated, use {@link #split(CharSequence)}. - * - * @param sequence the sequence of characters to split - * @return an immutable list of the segments split from the parameter - * @since 15.0 - */ - @Beta - public List splitToList(CharSequence sequence) { - checkNotNull(sequence); - - Iterator iterator = splittingIterator(sequence); - List result = new ArrayList(); - - while (iterator.hasNext()) { - result.add(iterator.next()); - } - - return Collections.unmodifiableList(result); - } - - /** - * Returns a {@code MapSplitter} which splits entries based on this splitter, - * and splits entries into keys and values using the specified separator. - * - * @since 10.0 - */ - @CheckReturnValue - @Beta - public MapSplitter withKeyValueSeparator(String separator) { - return withKeyValueSeparator(on(separator)); - } - - /** - * Returns a {@code MapSplitter} which splits entries based on this splitter, - * and splits entries into keys and values using the specified separator. - * - * @since 14.0 - */ - @CheckReturnValue - @Beta - public MapSplitter withKeyValueSeparator(char separator) { - return withKeyValueSeparator(on(separator)); - } - - /** - * Returns a {@code MapSplitter} which splits entries based on this splitter, - * and splits entries into keys and values using the specified key-value - * splitter. - * - * @since 10.0 - */ - @CheckReturnValue - @Beta - public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { - return new MapSplitter(this, keyValueSplitter); - } - /** * An object that splits strings into maps as {@code Splitter} splits iterables * and lists. Like {@code Splitter}, it is thread-safe and immutable. @@ -548,29 +180,13 @@ public final class Splitter { } } - private interface Strategy { - Iterator iterator(Splitter splitter, CharSequence toSplit); - } - private abstract static class SplittingIterator extends AbstractIterator { final CharSequence toSplit; final CharMatcher trimmer; final boolean omitEmptyStrings; - /** - * Returns the first index in {@code toSplit} at or after {@code start} that - * contains the separator. - */ - abstract int separatorStart(int start); - - /** - * Returns the first index in {@code toSplit} after {@code - * separatorPosition} that does not contain a separator. This method is only - * invoked after a call to {@code separatorStart}. - */ - abstract int separatorEnd(int separatorPosition); - int offset = 0; + int limit; protected SplittingIterator(Splitter splitter, CharSequence toSplit) { @@ -646,5 +262,395 @@ public final class Splitter { } return endOfData(); } + + /** + * Returns the first index in {@code toSplit} after {@code + * separatorPosition} that does not contain a separator. This method is only + * invoked after a call to {@code separatorStart}. + */ + abstract int separatorEnd(int separatorPosition); + + /** + * Returns the first index in {@code toSplit} at or after {@code start} that + * contains the separator. + */ + abstract int separatorStart(int start); + } + + private interface Strategy { + Iterator iterator(Splitter splitter, CharSequence toSplit); + } + + /** + * Returns a splitter that divides strings into pieces of the given length. For + * example, {@code Splitter.fixedLength(2).split("abcde")} returns an iterable + * containing {@code ["ab", "cd", "e"]}. The last piece can be smaller than + * {@code length} but will never be empty. + * + *

+ * Exception: for consistency with separator-based splitters, {@code + * split("")} does not yield an empty iterable, but an iterable containing + * {@code ""}. This is the only case in which {@code + * Iterables.size(split(input))} does not equal {@code + * IntMath.divide(input.length(), length, CEILING)}. To avoid this behavior, use + * {@code omitEmptyStrings}. + * + * @param length the desired length of pieces after splitting, a positive + * integer + * @return a splitter, with default settings, that can split into fixed sized + * pieces + * @throws IllegalArgumentException if {@code length} is zero or negative + */ + public static Splitter fixedLength(final int length) { + checkArgument(length > 0, "The length may not be less than 1"); + + return new Splitter(new Strategy() { + @Override + public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { + return new SplittingIterator(splitter, toSplit) { + @Override + public int separatorEnd(int separatorPosition) { + return separatorPosition; + } + + @Override + public int separatorStart(int start) { + int nextChunkStart = start + length; + return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); + } + }; + } + }); + } + + /** + * Returns a splitter that uses the given single-character separator. For + * example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable + * containing {@code ["foo", "", "bar"]}. + * + * @param separator the character to recognize as a separator + * @return a splitter, with default settings, that recognizes that separator + */ + public static Splitter on(char separator) { + return on(CharMatcher.is(separator)); + } + + /** + * Returns a splitter that considers any single character matched by the given + * {@code CharMatcher} to be a separator. For example, {@code + * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an + * iterable containing {@code ["foo", "", "bar", "quux"]}. + * + * @param separatorMatcher a {@link CharMatcher} that determines whether a + * character is a separator + * @return a splitter, with default settings, that uses this matcher + */ + public static Splitter on(final CharMatcher separatorMatcher) { + checkNotNull(separatorMatcher); + + return new Splitter(new Strategy() { + @Override + public SplittingIterator iterator(Splitter splitter, final CharSequence toSplit) { + return new SplittingIterator(splitter, toSplit) { + @Override + int separatorEnd(int separatorPosition) { + return separatorPosition + 1; + } + + @Override + int separatorStart(int start) { + return separatorMatcher.indexIn(toSplit, start); + } + }; + } + }); + } + + /** + * Returns a splitter that considers any subsequence matching {@code + * pattern} to be a separator. For example, {@code + * Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string into + * lines whether it uses DOS-style or UNIX-style line terminators. + * + * @param separatorPattern the pattern that determines whether a subsequence is + * a separator. This pattern may not match the empty + * string. + * @return a splitter, with default settings, that uses this pattern + * @throws IllegalArgumentException if {@code separatorPattern} matches the + * empty string + */ + @GwtIncompatible("java.util.regex") + public static Splitter on(final Pattern separatorPattern) { + checkNotNull(separatorPattern); + checkArgument(!separatorPattern.matcher("").matches(), "The pattern may not match the empty string: %s", + separatorPattern); + + return new Splitter(new Strategy() { + @Override + public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { + final Matcher matcher = separatorPattern.matcher(toSplit); + return new SplittingIterator(splitter, toSplit) { + @Override + public int separatorEnd(int separatorPosition) { + return matcher.end(); + } + + @Override + public int separatorStart(int start) { + return matcher.find(start) ? matcher.start() : -1; + } + }; + } + }); + } + + /** + * Returns a splitter that uses the given fixed string as a separator. For + * example, {@code Splitter.on(", ").split("foo, bar,baz")} returns an iterable + * containing {@code ["foo", "bar,baz"]}. + * + * @param separator the literal, nonempty string to recognize as a separator + * @return a splitter, with default settings, that recognizes that separator + */ + public static Splitter on(final String separator) { + checkArgument(separator.length() != 0, "The separator may not be the empty string."); + + return new Splitter(new Strategy() { + @Override + public SplittingIterator iterator(Splitter splitter, CharSequence toSplit) { + return new SplittingIterator(splitter, toSplit) { + @Override + public int separatorEnd(int separatorPosition) { + return separatorPosition + separator.length(); + } + + @Override + public int separatorStart(int start) { + int separatorLength = separator.length(); + + positions: for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) { + for (int i = 0; i < separatorLength; i++) { + if (toSplit.charAt(i + p) != separator.charAt(i)) { + continue positions; + } + } + return p; + } + return -1; + } + }; + } + }); + } + + /** + * Returns a splitter that considers any subsequence matching a given pattern + * (regular expression) to be a separator. For example, {@code + * Splitter.onPattern("\r?\n").split(entireFile)} splits a string into lines + * whether it uses DOS-style or UNIX-style line terminators. This is equivalent + * to {@code Splitter.on(Pattern.compile(pattern))}. + * + * @param separatorPattern the pattern that determines whether a subsequence is + * a separator. This pattern may not match the empty + * string. + * @return a splitter, with default settings, that uses this pattern + * @throws java.util.regex.PatternSyntaxException if {@code separatorPattern} is + * a malformed expression + * @throws IllegalArgumentException if {@code separatorPattern} + * matches the empty string + */ + @GwtIncompatible("java.util.regex") + public static Splitter onPattern(String separatorPattern) { + return on(Pattern.compile(separatorPattern)); + } + + private final CharMatcher trimmer; + + private final boolean omitEmptyStrings; + + private final Strategy strategy; + + private final int limit; + + private Splitter(Strategy strategy) { + this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE); + } + + private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { + this.strategy = strategy; + this.omitEmptyStrings = omitEmptyStrings; + this.trimmer = trimmer; + this.limit = limit; + } + + /** + * Returns a splitter that behaves equivalently to {@code this} splitter but + * stops splitting after it reaches the limit. The limit defines the maximum + * number of items returned by the iterator. + * + *

+ * For example, {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an + * iterable containing {@code ["a", "b", "c,d"]}. When omitting empty strings, + * the omitted strings do no count. Hence, + * {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} + * returns an iterable containing {@code ["a", "b", "c,d"}. When trim is + * requested, all entries, including the last are trimmed. Hence + * {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")} + * results in @{code ["a", "b", "c , d"]}. + * + * @param limit the maximum number of items returns + * @return a splitter with the desired configuration + * @since 9.0 + */ + @CheckReturnValue + public Splitter limit(int limit) { + checkArgument(limit > 0, "must be greater than zero: %s", limit); + return new Splitter(strategy, omitEmptyStrings, trimmer, limit); + } + + /** + * Returns a splitter that behaves equivalently to {@code this} splitter, but + * automatically omits empty strings from the results. For example, {@code + * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an iterable + * containing only {@code ["a", "b", "c"]}. + * + *

+ * If either {@code trimResults} option is also specified when creating a + * splitter, that splitter always trims results first before checking for + * emptiness. So, for example, {@code + * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns an + * empty iterable. + * + *

+ * Note that it is ordinarily not possible for {@link #split(CharSequence)} to + * return an empty iterable, but when using this option, it can (if the input + * sequence consists of nothing but separators). + * + * @return a splitter with the desired configuration + */ + @CheckReturnValue + public Splitter omitEmptyStrings() { + return new Splitter(strategy, true, trimmer, limit); + } + + /** + * Splits {@code sequence} into string components and makes them available + * through an {@link Iterator}, which may be lazily evaluated. If you want an + * eagerly computed {@link List}, use {@link #splitToList(CharSequence)}. + * + * @param sequence the sequence of characters to split + * @return an iteration over the segments split from the parameter. + */ + public Iterable split(final CharSequence sequence) { + checkNotNull(sequence); + + return new Iterable() { + @Override + public Iterator iterator() { + return splittingIterator(sequence); + } + + @Override + public String toString() { + return Joiner.on(", ").appendTo(new StringBuilder().append('['), this).append(']').toString(); + } + }; + } + + private Iterator splittingIterator(CharSequence sequence) { + return strategy.iterator(this, sequence); + } + + /** + * Splits {@code sequence} into string components and returns them as an + * immutable list. If you want an {@link Iterable} which may be lazily + * evaluated, use {@link #split(CharSequence)}. + * + * @param sequence the sequence of characters to split + * @return an immutable list of the segments split from the parameter + * @since 15.0 + */ + @Beta + public List splitToList(CharSequence sequence) { + checkNotNull(sequence); + + Iterator iterator = splittingIterator(sequence); + List result = new ArrayList(); + + while (iterator.hasNext()) { + result.add(iterator.next()); + } + + return Collections.unmodifiableList(result); + } + + /** + * Returns a splitter that behaves equivalently to {@code this} splitter, but + * automatically removes leading and trailing {@linkplain CharMatcher#WHITESPACE + * whitespace} from each returned substring; equivalent to + * {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code + * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable + * containing {@code ["a", "b", "c"]}. + * + * @return a splitter with the desired configuration + */ + @CheckReturnValue + public Splitter trimResults() { + return trimResults(CharMatcher.WHITESPACE); + } + + /** + * Returns a splitter that behaves equivalently to {@code this} splitter, but + * removes all leading or trailing characters matching the given {@code + * CharMatcher} from each returned substring. For example, {@code + * Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} + * returns an iterable containing {@code ["a ", "b_ ", "c"]}. + * + * @param trimmer a {@link CharMatcher} that determines whether a character + * should be removed from the beginning/end of a subsequence + * @return a splitter with the desired configuration + */ + // TODO(kevinb): throw if a trimmer was already specified! + @CheckReturnValue + public Splitter trimResults(CharMatcher trimmer) { + checkNotNull(trimmer); + return new Splitter(strategy, omitEmptyStrings, trimmer, limit); + } + + /** + * Returns a {@code MapSplitter} which splits entries based on this splitter, + * and splits entries into keys and values using the specified separator. + * + * @since 14.0 + */ + @CheckReturnValue + @Beta + public MapSplitter withKeyValueSeparator(char separator) { + return withKeyValueSeparator(on(separator)); + } + + /** + * Returns a {@code MapSplitter} which splits entries based on this splitter, + * and splits entries into keys and values using the specified key-value + * splitter. + * + * @since 10.0 + */ + @CheckReturnValue + @Beta + public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { + return new MapSplitter(this, keyValueSplitter); + } + + /** + * Returns a {@code MapSplitter} which splits entries based on this splitter, + * and splits entries into keys and values using the specified separator. + * + * @since 10.0 + */ + @CheckReturnValue + @Beta + public MapSplitter withKeyValueSeparator(String separator) { + return withKeyValueSeparator(on(separator)); } } diff --git a/src/main/java/com/google/common/base/StandardSystemProperty.java b/src/main/java/com/google/common/base/StandardSystemProperty.java index d23f3c9b..4912a828 100644 --- a/src/main/java/com/google/common/base/StandardSystemProperty.java +++ b/src/main/java/com/google/common/base/StandardSystemProperty.java @@ -126,14 +126,6 @@ public enum StandardSystemProperty { return key; } - /** - * Returns the current value for this system property by delegating to - * {@link System#getProperty(String)}. - */ - public String value() { - return System.getProperty(key); - } - /** * Returns a string representation of this system property. */ @@ -141,4 +133,12 @@ public enum StandardSystemProperty { public String toString() { return key() + "=" + value(); } + + /** + * Returns the current value for this system property by delegating to + * {@link System#getProperty(String)}. + */ + public String value() { + return System.getProperty(key); + } } diff --git a/src/main/java/com/google/common/base/Strings.java b/src/main/java/com/google/common/base/Strings.java index bc693181..6f7469b1 100644 --- a/src/main/java/com/google/common/base/Strings.java +++ b/src/main/java/com/google/common/base/Strings.java @@ -35,153 +35,6 @@ import com.google.common.annotations.VisibleForTesting; */ @GwtCompatible public final class Strings { - private Strings() { - } - - /** - * Returns the given string if it is non-null; the empty string otherwise. - * - * @param string the string to test and possibly return - * @return {@code string} itself if it is non-null; {@code ""} if it is null - */ - public static String nullToEmpty(@Nullable String string) { - return (string == null) ? "" : string; - } - - /** - * Returns the given string if it is nonempty; {@code null} otherwise. - * - * @param string the string to test and possibly return - * @return {@code string} itself if it is nonempty; {@code null} if it is empty - * or null - */ - public static @Nullable String emptyToNull(@Nullable String string) { - return isNullOrEmpty(string) ? null : string; - } - - /** - * Returns {@code true} if the given string is null or is the empty string. - * - *

- * Consider normalizing your string references with {@link #nullToEmpty}. If you - * do, you can use {@link String#isEmpty()} instead of this method, and you - * won't need special null-safe forms of methods like {@link String#toUpperCase} - * either. Or, if you'd like to normalize "in the other direction," converting - * empty strings to {@code null}, you can use {@link #emptyToNull}. - * - * @param string a string reference to check - * @return {@code true} if the string is null or is the empty string - */ - public static boolean isNullOrEmpty(@Nullable String string) { - return string == null || string.length() == 0; // string.isEmpty() in Java 6 - } - - /** - * Returns a string, of length at least {@code minLength}, consisting of - * {@code string} prepended with as many copies of {@code padChar} as are - * necessary to reach that length. For example, - * - *

    - *
  • {@code padStart("7", 3, '0')} returns {@code "007"} - *
  • {@code padStart("2010", 3, '0')} returns {@code "2010"} - *
- * - *

- * See {@link Formatter} for a richer set of formatting capabilities. - * - * @param string the string which should appear at the end of the result - * @param minLength the minimum length the resulting string must have. Can be - * zero or negative, in which case the input string is always - * returned. - * @param padChar the character to insert at the beginning of the result until - * the minimum length is reached - * @return the padded string - */ - public static String padStart(String string, int minLength, char padChar) { - checkNotNull(string); // eager for GWT. - if (string.length() >= minLength) { - return string; - } - StringBuilder sb = new StringBuilder(minLength); - for (int i = string.length(); i < minLength; i++) { - sb.append(padChar); - } - sb.append(string); - return sb.toString(); - } - - /** - * Returns a string, of length at least {@code minLength}, consisting of - * {@code string} appended with as many copies of {@code padChar} as are - * necessary to reach that length. For example, - * - *

    - *
  • {@code padEnd("4.", 5, '0')} returns {@code "4.000"} - *
  • {@code padEnd("2010", 3, '!')} returns {@code "2010"} - *
- * - *

- * See {@link Formatter} for a richer set of formatting capabilities. - * - * @param string the string which should appear at the beginning of the - * result - * @param minLength the minimum length the resulting string must have. Can be - * zero or negative, in which case the input string is always - * returned. - * @param padChar the character to append to the end of the result until the - * minimum length is reached - * @return the padded string - */ - public static String padEnd(String string, int minLength, char padChar) { - checkNotNull(string); // eager for GWT. - if (string.length() >= minLength) { - return string; - } - StringBuilder sb = new StringBuilder(minLength); - sb.append(string); - for (int i = string.length(); i < minLength; i++) { - sb.append(padChar); - } - return sb.toString(); - } - - /** - * Returns a string consisting of a specific number of concatenated copies of an - * input string. For example, {@code repeat("hey", 3)} returns the string - * {@code "heyheyhey"}. - * - * @param string any non-null string - * @param count the number of times to repeat it; a nonnegative integer - * @return a string containing {@code string} repeated {@code count} times (the - * empty string if {@code count} is zero) - * @throws IllegalArgumentException if {@code count} is negative - */ - public static String repeat(String string, int count) { - checkNotNull(string); // eager for GWT. - - if (count <= 1) { - checkArgument(count >= 0, "invalid count: %s", count); - return (count == 0) ? "" : string; - } - - // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark - final int len = string.length(); - final long longSize = (long) len * (long) count; - final int size = (int) longSize; - if (size != longSize) { - throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); - } - - final char[] array = new char[size]; - string.getChars(0, len, array, 0); - int n; - for (n = len; n < size - n; n <<= 1) { - System.arraycopy(array, 0, array, n, n); - } - System.arraycopy(array, 0, array, n, size - n); - return new String(array); - } - /** * Returns the longest string {@code prefix} such that * {@code a.toString().startsWith(prefix) && b.toString().startsWith(prefix)}, @@ -228,6 +81,150 @@ public final class Strings { return a.subSequence(a.length() - s, a.length()).toString(); } + /** + * Returns the given string if it is nonempty; {@code null} otherwise. + * + * @param string the string to test and possibly return + * @return {@code string} itself if it is nonempty; {@code null} if it is empty + * or null + */ + public static @Nullable String emptyToNull(@Nullable String string) { + return isNullOrEmpty(string) ? null : string; + } + + /** + * Returns {@code true} if the given string is null or is the empty string. + * + *

+ * Consider normalizing your string references with {@link #nullToEmpty}. If you + * do, you can use {@link String#isEmpty()} instead of this method, and you + * won't need special null-safe forms of methods like {@link String#toUpperCase} + * either. Or, if you'd like to normalize "in the other direction," converting + * empty strings to {@code null}, you can use {@link #emptyToNull}. + * + * @param string a string reference to check + * @return {@code true} if the string is null or is the empty string + */ + public static boolean isNullOrEmpty(@Nullable String string) { + return string == null || string.length() == 0; // string.isEmpty() in Java 6 + } + + /** + * Returns the given string if it is non-null; the empty string otherwise. + * + * @param string the string to test and possibly return + * @return {@code string} itself if it is non-null; {@code ""} if it is null + */ + public static String nullToEmpty(@Nullable String string) { + return (string == null) ? "" : string; + } + + /** + * Returns a string, of length at least {@code minLength}, consisting of + * {@code string} appended with as many copies of {@code padChar} as are + * necessary to reach that length. For example, + * + *

    + *
  • {@code padEnd("4.", 5, '0')} returns {@code "4.000"} + *
  • {@code padEnd("2010", 3, '!')} returns {@code "2010"} + *
+ * + *

+ * See {@link Formatter} for a richer set of formatting capabilities. + * + * @param string the string which should appear at the beginning of the + * result + * @param minLength the minimum length the resulting string must have. Can be + * zero or negative, in which case the input string is always + * returned. + * @param padChar the character to append to the end of the result until the + * minimum length is reached + * @return the padded string + */ + public static String padEnd(String string, int minLength, char padChar) { + checkNotNull(string); // eager for GWT. + if (string.length() >= minLength) { + return string; + } + StringBuilder sb = new StringBuilder(minLength); + sb.append(string); + for (int i = string.length(); i < minLength; i++) { + sb.append(padChar); + } + return sb.toString(); + } + + /** + * Returns a string, of length at least {@code minLength}, consisting of + * {@code string} prepended with as many copies of {@code padChar} as are + * necessary to reach that length. For example, + * + *

    + *
  • {@code padStart("7", 3, '0')} returns {@code "007"} + *
  • {@code padStart("2010", 3, '0')} returns {@code "2010"} + *
+ * + *

+ * See {@link Formatter} for a richer set of formatting capabilities. + * + * @param string the string which should appear at the end of the result + * @param minLength the minimum length the resulting string must have. Can be + * zero or negative, in which case the input string is always + * returned. + * @param padChar the character to insert at the beginning of the result until + * the minimum length is reached + * @return the padded string + */ + public static String padStart(String string, int minLength, char padChar) { + checkNotNull(string); // eager for GWT. + if (string.length() >= minLength) { + return string; + } + StringBuilder sb = new StringBuilder(minLength); + for (int i = string.length(); i < minLength; i++) { + sb.append(padChar); + } + sb.append(string); + return sb.toString(); + } + + /** + * Returns a string consisting of a specific number of concatenated copies of an + * input string. For example, {@code repeat("hey", 3)} returns the string + * {@code "heyheyhey"}. + * + * @param string any non-null string + * @param count the number of times to repeat it; a nonnegative integer + * @return a string containing {@code string} repeated {@code count} times (the + * empty string if {@code count} is zero) + * @throws IllegalArgumentException if {@code count} is negative + */ + public static String repeat(String string, int count) { + checkNotNull(string); // eager for GWT. + + if (count <= 1) { + checkArgument(count >= 0, "invalid count: %s", count); + return (count == 0) ? "" : string; + } + + // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark + final int len = string.length(); + final long longSize = (long) len * (long) count; + final int size = (int) longSize; + if (size != longSize) { + throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); + } + + final char[] array = new char[size]; + string.getChars(0, len, array, 0); + int n; + for (n = len; n < size - n; n <<= 1) { + System.arraycopy(array, 0, array, n, n); + } + System.arraycopy(array, 0, array, n, size - n); + return new String(array); + } + /** * True when a valid surrogate pair starts at the given {@code index} in the * given {@code string}. Out-of-range indexes return false. @@ -237,4 +234,7 @@ public final class Strings { return index >= 0 && index <= (string.length() - 2) && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1)); } + + private Strings() { + } } diff --git a/src/main/java/com/google/common/base/Suppliers.java b/src/main/java/com/google/common/base/Suppliers.java index f1b6b79e..e1510aac 100644 --- a/src/main/java/com/google/common/base/Suppliers.java +++ b/src/main/java/com/google/common/base/Suppliers.java @@ -38,141 +38,13 @@ import com.google.common.annotations.VisibleForTesting; */ @GwtCompatible public final class Suppliers { - private Suppliers() { - } - - /** - * Returns a new supplier which is the composition of the provided function and - * supplier. In other words, the new supplier's value will be computed by - * retrieving the value from {@code supplier}, and then applying - * {@code function} to that value. Note that the resulting supplier will not - * call {@code supplier} or invoke {@code function} until it is called. - */ - public static Supplier compose(Function function, Supplier supplier) { - Preconditions.checkNotNull(function); - Preconditions.checkNotNull(supplier); - return new SupplierComposition(function, supplier); - } - - private static class SupplierComposition implements Supplier, Serializable { - final Function function; - final Supplier supplier; - - SupplierComposition(Function function, Supplier supplier) { - this.function = function; - this.supplier = supplier; - } - - @Override - public T get() { - return function.apply(supplier.get()); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof SupplierComposition) { - SupplierComposition that = (SupplierComposition) obj; - return function.equals(that.function) && supplier.equals(that.supplier); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hashCode(function, supplier); - } - - @Override - public String toString() { - return "Suppliers.compose(" + function + ", " + supplier + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a supplier which caches the instance retrieved during the first call - * to {@code get()} and returns that value on subsequent calls to {@code get()}. - * See: memoization - * - *

- * The returned supplier is thread-safe. The supplier's serialized form does not - * contain the cached value, which will be recalculated when {@code - * get()} is called on the reserialized instance. - * - *

- * If {@code delegate} is an instance created by an earlier call to {@code - * memoize}, it is returned directly. - */ - public static Supplier memoize(Supplier delegate) { - return (delegate instanceof MemoizingSupplier) ? delegate - : new MemoizingSupplier(Preconditions.checkNotNull(delegate)); - } - - @VisibleForTesting - static class MemoizingSupplier implements Supplier, Serializable { - final Supplier delegate; - transient volatile boolean initialized; - // "value" does not need to be volatile; visibility piggy-backs - // on volatile read of "initialized". - transient T value; - - MemoizingSupplier(Supplier delegate) { - this.delegate = delegate; - } - - @Override - public T get() { - // A 2-field variant of Double Checked Locking. - if (!initialized) { - synchronized (this) { - if (!initialized) { - T t = delegate.get(); - value = t; - initialized = true; - return t; - } - } - } - return value; - } - - @Override - public String toString() { - return "Suppliers.memoize(" + delegate + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a supplier that caches the instance supplied by the delegate and - * removes the cached value after the specified time has passed. Subsequent - * calls to {@code get()} return the cached value if the expiration time has not - * passed. After the expiration time, a new value is retrieved, cached, and - * returned. See: - * memoization - * - *

- * The returned supplier is thread-safe. The supplier's serialized form does not - * contain the cached value, which will be recalculated when {@code - * get()} is called on the reserialized instance. - * - * @param duration the length of time after a value is created that it should - * stop being returned by subsequent {@code get()} calls - * @param unit the unit that {@code duration} is expressed in - * @throws IllegalArgumentException if {@code duration} is not positive - * @since 2.0 - */ - public static Supplier memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit) { - return new ExpiringMemoizingSupplier(delegate, duration, unit); - } - @VisibleForTesting static class ExpiringMemoizingSupplier implements Supplier, Serializable { + private static final long serialVersionUID = 0; final Supplier delegate; final long durationNanos; transient volatile T value; + // The special value 0 means "not yet initialized". transient volatile long expirationNanos; @@ -214,92 +86,78 @@ public final class Suppliers { // but we don't want to store the unit just for toString return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)"; } + } + @VisibleForTesting + static class MemoizingSupplier implements Supplier, Serializable { private static final long serialVersionUID = 0; - } - - /** - * Returns a supplier that always supplies {@code instance}. - */ - public static Supplier ofInstance(@Nullable T instance) { - return new SupplierOfInstance(instance); - } - - private static class SupplierOfInstance implements Supplier, Serializable { - final T instance; - - SupplierOfInstance(@Nullable T instance) { - this.instance = instance; - } - - @Override - public T get() { - return instance; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof SupplierOfInstance) { - SupplierOfInstance that = (SupplierOfInstance) obj; - return Objects.equal(instance, that.instance); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hashCode(instance); - } - - @Override - public String toString() { - return "Suppliers.ofInstance(" + instance + ")"; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a supplier whose {@code get()} method synchronizes on - * {@code delegate} before calling it, making it thread-safe. - */ - public static Supplier synchronizedSupplier(Supplier delegate) { - return new ThreadSafeSupplier(Preconditions.checkNotNull(delegate)); - } - - private static class ThreadSafeSupplier implements Supplier, Serializable { final Supplier delegate; + transient volatile boolean initialized; - ThreadSafeSupplier(Supplier delegate) { + // "value" does not need to be volatile; visibility piggy-backs + // on volatile read of "initialized". + transient T value; + + MemoizingSupplier(Supplier delegate) { this.delegate = delegate; } @Override public T get() { - synchronized (delegate) { - return delegate.get(); + // A 2-field variant of Double Checked Locking. + if (!initialized) { + synchronized (this) { + if (!initialized) { + T t = delegate.get(); + value = t; + initialized = true; + return t; + } + } } + return value; } @Override public String toString() { - return "Suppliers.synchronizedSupplier(" + delegate + ")"; + return "Suppliers.memoize(" + delegate + ")"; } - - private static final long serialVersionUID = 0; } - /** - * Returns a function that accepts a supplier and returns the result of invoking - * {@link Supplier#get} on that supplier. - * - * @since 8.0 - */ - @Beta - public static Function, T> supplierFunction() { - @SuppressWarnings("unchecked") // implementation is "fully variant" - SupplierFunction sf = (SupplierFunction) SupplierFunctionImpl.INSTANCE; - return sf; + private static class SupplierComposition implements Supplier, Serializable { + private static final long serialVersionUID = 0; + final Function function; + + final Supplier supplier; + + SupplierComposition(Function function, Supplier supplier) { + this.function = function; + this.supplier = supplier; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof SupplierComposition) { + SupplierComposition that = (SupplierComposition) obj; + return function.equals(that.function) && supplier.equals(that.supplier); + } + return false; + } + + @Override + public T get() { + return function.apply(supplier.get()); + } + + @Override + public int hashCode() { + return Objects.hashCode(function, supplier); + } + + @Override + public String toString() { + return "Suppliers.compose(" + function + ", " + supplier + ")"; + } } private interface SupplierFunction extends Function, T> { @@ -319,4 +177,146 @@ public final class Suppliers { return "Suppliers.supplierFunction()"; } } + + private static class SupplierOfInstance implements Supplier, Serializable { + private static final long serialVersionUID = 0; + + final T instance; + + SupplierOfInstance(@Nullable T instance) { + this.instance = instance; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof SupplierOfInstance) { + SupplierOfInstance that = (SupplierOfInstance) obj; + return Objects.equal(instance, that.instance); + } + return false; + } + + @Override + public T get() { + return instance; + } + + @Override + public int hashCode() { + return Objects.hashCode(instance); + } + + @Override + public String toString() { + return "Suppliers.ofInstance(" + instance + ")"; + } + } + + private static class ThreadSafeSupplier implements Supplier, Serializable { + private static final long serialVersionUID = 0; + + final Supplier delegate; + + ThreadSafeSupplier(Supplier delegate) { + this.delegate = delegate; + } + + @Override + public T get() { + synchronized (delegate) { + return delegate.get(); + } + } + + @Override + public String toString() { + return "Suppliers.synchronizedSupplier(" + delegate + ")"; + } + } + + /** + * Returns a new supplier which is the composition of the provided function and + * supplier. In other words, the new supplier's value will be computed by + * retrieving the value from {@code supplier}, and then applying + * {@code function} to that value. Note that the resulting supplier will not + * call {@code supplier} or invoke {@code function} until it is called. + */ + public static Supplier compose(Function function, Supplier supplier) { + Preconditions.checkNotNull(function); + Preconditions.checkNotNull(supplier); + return new SupplierComposition(function, supplier); + } + + /** + * Returns a supplier which caches the instance retrieved during the first call + * to {@code get()} and returns that value on subsequent calls to {@code get()}. + * See: memoization + * + *

+ * The returned supplier is thread-safe. The supplier's serialized form does not + * contain the cached value, which will be recalculated when {@code + * get()} is called on the reserialized instance. + * + *

+ * If {@code delegate} is an instance created by an earlier call to {@code + * memoize}, it is returned directly. + */ + public static Supplier memoize(Supplier delegate) { + return (delegate instanceof MemoizingSupplier) ? delegate + : new MemoizingSupplier(Preconditions.checkNotNull(delegate)); + } + + /** + * Returns a supplier that caches the instance supplied by the delegate and + * removes the cached value after the specified time has passed. Subsequent + * calls to {@code get()} return the cached value if the expiration time has not + * passed. After the expiration time, a new value is retrieved, cached, and + * returned. See: + * memoization + * + *

+ * The returned supplier is thread-safe. The supplier's serialized form does not + * contain the cached value, which will be recalculated when {@code + * get()} is called on the reserialized instance. + * + * @param duration the length of time after a value is created that it should + * stop being returned by subsequent {@code get()} calls + * @param unit the unit that {@code duration} is expressed in + * @throws IllegalArgumentException if {@code duration} is not positive + * @since 2.0 + */ + public static Supplier memoizeWithExpiration(Supplier delegate, long duration, TimeUnit unit) { + return new ExpiringMemoizingSupplier(delegate, duration, unit); + } + + /** + * Returns a supplier that always supplies {@code instance}. + */ + public static Supplier ofInstance(@Nullable T instance) { + return new SupplierOfInstance(instance); + } + + /** + * Returns a function that accepts a supplier and returns the result of invoking + * {@link Supplier#get} on that supplier. + * + * @since 8.0 + */ + @Beta + public static Function, T> supplierFunction() { + @SuppressWarnings("unchecked") // implementation is "fully variant" + SupplierFunction sf = (SupplierFunction) SupplierFunctionImpl.INSTANCE; + return sf; + } + + /** + * Returns a supplier whose {@code get()} method synchronizes on + * {@code delegate} before calling it, making it thread-safe. + */ + public static Supplier synchronizedSupplier(Supplier delegate) { + return new ThreadSafeSupplier(Preconditions.checkNotNull(delegate)); + } + + private Suppliers() { + } } diff --git a/src/main/java/com/google/common/base/Throwables.java b/src/main/java/com/google/common/base/Throwables.java index 6cb87e64..bef79732 100644 --- a/src/main/java/com/google/common/base/Throwables.java +++ b/src/main/java/com/google/common/base/Throwables.java @@ -41,7 +41,91 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; * @since 1.0 */ public final class Throwables { - private Throwables() { + /** + * Gets a {@code Throwable} cause chain as a list. The first entry in the list + * will be {@code throwable} followed by its cause hierarchy. Note that this is + * a snapshot of the cause chain and will not reflect any subsequent changes to + * the cause chain. + * + *

+ * Here's an example of how it can be used to find specific types of exceptions + * in the cause chain: + * + *

+	 * Iterables.filter(Throwables.getCausalChain(e), IOException.class));
+	 * 
+ * + * @param throwable the non-null {@code Throwable} to extract causes from + * @return an unmodifiable list containing the cause chain starting with + * {@code throwable} + */ + @Beta // TODO(kevinb): decide best return type + public static List getCausalChain(Throwable throwable) { + checkNotNull(throwable); + List causes = new ArrayList(4); + while (throwable != null) { + causes.add(throwable); + throwable = throwable.getCause(); + } + return Collections.unmodifiableList(causes); + } + + /** + * Returns the innermost cause of {@code throwable}. The first throwable in a + * chain provides context from when the error or exception was initially + * detected. Example usage: + * + *
+	 * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
+	 * 
+ */ + public static Throwable getRootCause(Throwable throwable) { + Throwable cause; + while ((cause = throwable.getCause()) != null) { + throwable = cause; + } + return throwable; + } + + /** + * Returns a string containing the result of {@link Throwable#toString() + * toString()}, followed by the full, recursive stack trace of + * {@code throwable}. Note that you probably should not be parsing the resulting + * string; if you need programmatic access to the stack frames, you can call + * {@link Throwable#getStackTrace()}. + */ + public static String getStackTraceAsString(Throwable throwable) { + return EagRuntime.getStackTrace(throwable); + } + + /** + * Propagates {@code throwable} as-is if it is an instance of + * {@link RuntimeException} or {@link Error}, or else as a last resort, wraps it + * in a {@code RuntimeException} then propagates. + *

+ * This method always throws an exception. The {@code RuntimeException} return + * type is only for client code to make Java type system happy in case a return + * value is required by the enclosing method. Example usage: + * + *

+	 * T doSomething() {
+	 * 	try {
+	 * 		return someMethodThatCouldThrowAnything();
+	 * 	} catch (IKnowWhatToDoWithThisException e) {
+	 * 		return handle(e);
+	 * 	} catch (Throwable t) {
+	 * 		throw Throwables.propagate(t);
+	 * 	}
+	 * }
+	 * 
+ * + * @param throwable the Throwable to propagate + * @return nothing will ever be returned; this return type is only for your + * convenience, as illustrated in the example above + */ + public static RuntimeException propagate(Throwable throwable) { + propagateIfPossible(checkNotNull(throwable)); + throw new RuntimeException(throwable); } /** @@ -135,90 +219,6 @@ public final class Throwables { propagateIfPossible(throwable, declaredType2); } - /** - * Propagates {@code throwable} as-is if it is an instance of - * {@link RuntimeException} or {@link Error}, or else as a last resort, wraps it - * in a {@code RuntimeException} then propagates. - *

- * This method always throws an exception. The {@code RuntimeException} return - * type is only for client code to make Java type system happy in case a return - * value is required by the enclosing method. Example usage: - * - *

-	 * T doSomething() {
-	 * 	try {
-	 * 		return someMethodThatCouldThrowAnything();
-	 * 	} catch (IKnowWhatToDoWithThisException e) {
-	 * 		return handle(e);
-	 * 	} catch (Throwable t) {
-	 * 		throw Throwables.propagate(t);
-	 * 	}
-	 * }
-	 * 
- * - * @param throwable the Throwable to propagate - * @return nothing will ever be returned; this return type is only for your - * convenience, as illustrated in the example above - */ - public static RuntimeException propagate(Throwable throwable) { - propagateIfPossible(checkNotNull(throwable)); - throw new RuntimeException(throwable); - } - - /** - * Returns the innermost cause of {@code throwable}. The first throwable in a - * chain provides context from when the error or exception was initially - * detected. Example usage: - * - *
-	 * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage());
-	 * 
- */ - public static Throwable getRootCause(Throwable throwable) { - Throwable cause; - while ((cause = throwable.getCause()) != null) { - throwable = cause; - } - return throwable; - } - - /** - * Gets a {@code Throwable} cause chain as a list. The first entry in the list - * will be {@code throwable} followed by its cause hierarchy. Note that this is - * a snapshot of the cause chain and will not reflect any subsequent changes to - * the cause chain. - * - *

- * Here's an example of how it can be used to find specific types of exceptions - * in the cause chain: - * - *

-	 * Iterables.filter(Throwables.getCausalChain(e), IOException.class));
-	 * 
- * - * @param throwable the non-null {@code Throwable} to extract causes from - * @return an unmodifiable list containing the cause chain starting with - * {@code throwable} - */ - @Beta // TODO(kevinb): decide best return type - public static List getCausalChain(Throwable throwable) { - checkNotNull(throwable); - List causes = new ArrayList(4); - while (throwable != null) { - causes.add(throwable); - throwable = throwable.getCause(); - } - return Collections.unmodifiableList(causes); - } - - /** - * Returns a string containing the result of {@link Throwable#toString() - * toString()}, followed by the full, recursive stack trace of - * {@code throwable}. Note that you probably should not be parsing the resulting - * string; if you need programmatic access to the stack frames, you can call - * {@link Throwable#getStackTrace()}. - */ - public static String getStackTraceAsString(Throwable throwable) { - return EagRuntime.getStackTrace(throwable); + private Throwables() { } } diff --git a/src/main/java/com/google/common/base/Ticker.java b/src/main/java/com/google/common/base/Ticker.java index b921f92b..e305e3d9 100644 --- a/src/main/java/com/google/common/base/Ticker.java +++ b/src/main/java/com/google/common/base/Ticker.java @@ -36,6 +36,22 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible public abstract class Ticker { + private static final Ticker SYSTEM_TICKER = new Ticker() { + @Override + public long read() { + return Platform.systemNanoTime(); + } + }; + + /** + * A ticker that reads the current time using {@link System#nanoTime}. + * + * @since 10.0 + */ + public static Ticker systemTicker() { + return SYSTEM_TICKER; + } + /** * Constructor for use by subclasses. */ @@ -47,20 +63,4 @@ public abstract class Ticker { * reference. */ public abstract long read(); - - /** - * A ticker that reads the current time using {@link System#nanoTime}. - * - * @since 10.0 - */ - public static Ticker systemTicker() { - return SYSTEM_TICKER; - } - - private static final Ticker SYSTEM_TICKER = new Ticker() { - @Override - public long read() { - return Platform.systemNanoTime(); - } - }; } diff --git a/src/main/java/com/google/common/collect/AbstractBiMap.java b/src/main/java/com/google/common/collect/AbstractBiMap.java index 88ae332d..960dbd1c 100644 --- a/src/main/java/com/google/common/collect/AbstractBiMap.java +++ b/src/main/java/com/google/common/collect/AbstractBiMap.java @@ -49,150 +49,8 @@ import com.google.common.base.Objects; @GwtCompatible(emulated = true) abstract class AbstractBiMap extends ForwardingMap implements BiMap, Serializable { - private transient Map delegate; - transient AbstractBiMap inverse; - - /** Package-private constructor for creating a map-backed bimap. */ - AbstractBiMap(Map forward, Map backward) { - setDelegates(forward, backward); - } - - /** Private constructor for inverse bimap. */ - private AbstractBiMap(Map backward, AbstractBiMap forward) { - delegate = backward; - inverse = forward; - } - - @Override - protected Map delegate() { - return delegate; - } - - /** - * Returns its input, or throws an exception if this is not a valid key. - */ - K checkKey(@Nullable K key) { - return key; - } - - /** - * Returns its input, or throws an exception if this is not a valid value. - */ - V checkValue(@Nullable V value) { - return value; - } - - /** - * Specifies the delegate maps going in each direction. Called by the - * constructor and by subclasses during deserialization. - */ - void setDelegates(Map forward, Map backward) { - checkState(delegate == null); - checkState(inverse == null); - checkArgument(forward.isEmpty()); - checkArgument(backward.isEmpty()); - checkArgument(forward != backward); - delegate = forward; - inverse = new Inverse(backward, this); - } - - void setInverse(AbstractBiMap inverse) { - this.inverse = inverse; - } - - // Query Operations (optimizations) - - @Override - public boolean containsValue(@Nullable Object value) { - return inverse.containsKey(value); - } - - // Modification Operations - - @Override - public V put(@Nullable K key, @Nullable V value) { - return putInBothMaps(key, value, false); - } - - @Override - public V forcePut(@Nullable K key, @Nullable V value) { - return putInBothMaps(key, value, true); - } - - private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) { - checkKey(key); - checkValue(value); - boolean containedKey = containsKey(key); - if (containedKey && Objects.equal(value, get(key))) { - return value; - } - if (force) { - inverse().remove(value); - } else { - checkArgument(!containsValue(value), "value already present: %s", value); - } - V oldValue = delegate.put(key, value); - updateInverseMap(key, containedKey, oldValue, value); - return oldValue; - } - - private void updateInverseMap(K key, boolean containedKey, V oldValue, V newValue) { - if (containedKey) { - removeFromInverseMap(oldValue); - } - inverse.delegate.put(newValue, key); - } - - @Override - public V remove(@Nullable Object key) { - return containsKey(key) ? removeFromBothMaps(key) : null; - } - - private V removeFromBothMaps(Object key) { - V oldValue = delegate.remove(key); - removeFromInverseMap(oldValue); - return oldValue; - } - - private void removeFromInverseMap(V oldValue) { - inverse.delegate.remove(oldValue); - } - - // Bulk Operations - - @Override - public void putAll(Map map) { - for (Entry entry : map.entrySet()) { - put(entry.getKey(), entry.getValue()); - } - } - - @Override - public void clear() { - delegate.clear(); - inverse.delegate.clear(); - } - - // Views - - @Override - public BiMap inverse() { - return inverse; - } - - private transient Set keySet; - - @Override - public Set keySet() { - Set result = keySet; - return (result == null) ? keySet = new KeySet() : result; - } - - private class KeySet extends ForwardingSet { - @Override - protected Set delegate() { - return delegate.keySet(); - } + private class EntrySet extends ForwardingSet> { + final Set> esDelegate = delegate.entrySet(); @Override public void clear() { @@ -200,109 +58,21 @@ abstract class AbstractBiMap extends ForwardingMap implements BiMap< } @Override - public boolean remove(Object key) { - if (!contains(key)) { - return false; - } - removeFromBothMaps(key); - return true; + public boolean contains(Object o) { + return Maps.containsEntryImpl(delegate(), o); } @Override - public boolean removeAll(Collection keysToRemove) { - return standardRemoveAll(keysToRemove); + public boolean containsAll(Collection c) { + return standardContainsAll(c); } - @Override - public boolean retainAll(Collection keysToRetain) { - return standardRetainAll(keysToRetain); - } - - @Override - public Iterator iterator() { - return Maps.keyIterator(entrySet().iterator()); - } - } - - private transient Set valueSet; - - @Override - public Set values() { - /* - * We can almost reuse the inverse's keySet, except we have to fix the iteration - * order so that it is consistent with the forward map. - */ - Set result = valueSet; - return (result == null) ? valueSet = new ValueSet() : result; - } - - private class ValueSet extends ForwardingSet { - final Set valuesDelegate = inverse.keySet(); - - @Override - protected Set delegate() { - return valuesDelegate; - } - - @Override - public Iterator iterator() { - return Maps.valueIterator(entrySet().iterator()); - } - - @Override - public Object[] toArray() { - return standardToArray(); - } - - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - - @Override - public String toString() { - return standardToString(); - } - } - - private transient Set> entrySet; - - @Override - public Set> entrySet() { - Set> result = entrySet; - return (result == null) ? entrySet = new EntrySet() : result; - } - - private class EntrySet extends ForwardingSet> { - final Set> esDelegate = delegate.entrySet(); - @Override protected Set> delegate() { return esDelegate; } - @Override - public void clear() { - AbstractBiMap.this.clear(); - } - - @Override - public boolean remove(Object object) { - if (!esDelegate.contains(object)) { - return false; - } - - // safe because esDelgate.contains(object). - Entry entry = (Entry) object; - inverse.delegate.remove(entry.getValue()); - /* - * Remove the mapping in inverse before removing from esDelegate because if - * entry is part of esDelegate, entry might be invalidated after the mapping is - * removed from esDelegate. - */ - esDelegate.remove(entry); - return true; - } + // See java.util.Collections.CheckedEntrySet for details on attacks. @Override public Iterator> iterator() { @@ -353,26 +123,22 @@ abstract class AbstractBiMap extends ForwardingMap implements BiMap< }; } - // See java.util.Collections.CheckedEntrySet for details on attacks. - @Override - public Object[] toArray() { - return standardToArray(); - } + public boolean remove(Object object) { + if (!esDelegate.contains(object)) { + return false; + } - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - - @Override - public boolean contains(Object o) { - return Maps.containsEntryImpl(delegate(), o); - } - - @Override - public boolean containsAll(Collection c) { - return standardContainsAll(c); + // safe because esDelgate.contains(object). + Entry entry = (Entry) object; + inverse.delegate.remove(entry.getValue()); + /* + * Remove the mapping in inverse before removing from esDelegate because if + * entry is part of esDelegate, entry might be invalidated after the mapping is + * removed from esDelegate. + */ + esDelegate.remove(entry); + return true; } @Override @@ -384,13 +150,22 @@ abstract class AbstractBiMap extends ForwardingMap implements BiMap< public boolean retainAll(Collection c) { return standardRetainAll(c); } + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } } /** The inverse of any other {@code AbstractBiMap} subclass. */ private static class Inverse extends AbstractBiMap { - private Inverse(Map backward, AbstractBiMap forward) { - super(backward, forward); - } + @GwtIncompatible("Not needed in emulated source.") + private static final long serialVersionUID = 0; /* * Serialization stores the forward bimap, the inverse of this inverse. @@ -401,6 +176,10 @@ abstract class AbstractBiMap extends ForwardingMap implements BiMap< * instances have inverse() methods that return the other. */ + private Inverse(Map backward, AbstractBiMap forward) { + super(backward, forward); + } + @Override K checkKey(K key) { return inverse.checkValue(key); @@ -411,15 +190,6 @@ abstract class AbstractBiMap extends ForwardingMap implements BiMap< return inverse.checkKey(value); } - /** - * @serialData the forward bimap - */ - @GwtIncompatible("java.io.ObjectOuputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(inverse()); - } - @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { @@ -432,10 +202,241 @@ abstract class AbstractBiMap extends ForwardingMap implements BiMap< return inverse().inverse(); } - @GwtIncompatible("Not needed in emulated source.") - private static final long serialVersionUID = 0; + /** + * @serialData the forward bimap + */ + @GwtIncompatible("java.io.ObjectOuputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(inverse()); + } + } + + private class KeySet extends ForwardingSet { + @Override + public void clear() { + AbstractBiMap.this.clear(); + } + + @Override + protected Set delegate() { + return delegate.keySet(); + } + + @Override + public Iterator iterator() { + return Maps.keyIterator(entrySet().iterator()); + } + + @Override + public boolean remove(Object key) { + if (!contains(key)) { + return false; + } + removeFromBothMaps(key); + return true; + } + + @Override + public boolean removeAll(Collection keysToRemove) { + return standardRemoveAll(keysToRemove); + } + + @Override + public boolean retainAll(Collection keysToRetain) { + return standardRetainAll(keysToRetain); + } + } + + private class ValueSet extends ForwardingSet { + final Set valuesDelegate = inverse.keySet(); + + @Override + protected Set delegate() { + return valuesDelegate; + } + + @Override + public Iterator iterator() { + return Maps.valueIterator(entrySet().iterator()); + } + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } + + @Override + public String toString() { + return standardToString(); + } } @GwtIncompatible("Not needed in emulated source.") private static final long serialVersionUID = 0; + + private transient Map delegate; + + transient AbstractBiMap inverse; + + private transient Set keySet; + + private transient Set valueSet; + + // Query Operations (optimizations) + + private transient Set> entrySet; + + // Modification Operations + + /** Private constructor for inverse bimap. */ + private AbstractBiMap(Map backward, AbstractBiMap forward) { + delegate = backward; + inverse = forward; + } + + /** Package-private constructor for creating a map-backed bimap. */ + AbstractBiMap(Map forward, Map backward) { + setDelegates(forward, backward); + } + + /** + * Returns its input, or throws an exception if this is not a valid key. + */ + K checkKey(@Nullable K key) { + return key; + } + + /** + * Returns its input, or throws an exception if this is not a valid value. + */ + V checkValue(@Nullable V value) { + return value; + } + + @Override + public void clear() { + delegate.clear(); + inverse.delegate.clear(); + } + + @Override + public boolean containsValue(@Nullable Object value) { + return inverse.containsKey(value); + } + + @Override + protected Map delegate() { + return delegate; + } + + // Bulk Operations + + @Override + public Set> entrySet() { + Set> result = entrySet; + return (result == null) ? entrySet = new EntrySet() : result; + } + + @Override + public V forcePut(@Nullable K key, @Nullable V value) { + return putInBothMaps(key, value, true); + } + + // Views + + @Override + public BiMap inverse() { + return inverse; + } + + @Override + public Set keySet() { + Set result = keySet; + return (result == null) ? keySet = new KeySet() : result; + } + + @Override + public V put(@Nullable K key, @Nullable V value) { + return putInBothMaps(key, value, false); + } + + @Override + public void putAll(Map map) { + for (Entry entry : map.entrySet()) { + put(entry.getKey(), entry.getValue()); + } + } + + private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) { + checkKey(key); + checkValue(value); + boolean containedKey = containsKey(key); + if (containedKey && Objects.equal(value, get(key))) { + return value; + } + if (force) { + inverse().remove(value); + } else { + checkArgument(!containsValue(value), "value already present: %s", value); + } + V oldValue = delegate.put(key, value); + updateInverseMap(key, containedKey, oldValue, value); + return oldValue; + } + + @Override + public V remove(@Nullable Object key) { + return containsKey(key) ? removeFromBothMaps(key) : null; + } + + private V removeFromBothMaps(Object key) { + V oldValue = delegate.remove(key); + removeFromInverseMap(oldValue); + return oldValue; + } + + private void removeFromInverseMap(V oldValue) { + inverse.delegate.remove(oldValue); + } + + /** + * Specifies the delegate maps going in each direction. Called by the + * constructor and by subclasses during deserialization. + */ + void setDelegates(Map forward, Map backward) { + checkState(delegate == null); + checkState(inverse == null); + checkArgument(forward.isEmpty()); + checkArgument(backward.isEmpty()); + checkArgument(forward != backward); + delegate = forward; + inverse = new Inverse(backward, this); + } + + void setInverse(AbstractBiMap inverse) { + this.inverse = inverse; + } + + private void updateInverseMap(K key, boolean containedKey, V oldValue, V newValue) { + if (containedKey) { + removeFromInverseMap(oldValue); + } + inverse.delegate.put(newValue, key); + } + + @Override + public Set values() { + /* + * We can almost reuse the inverse's keySet, except we have to fix the iteration + * order so that it is consistent with the forward map. + */ + Set result = valueSet; + return (result == null) ? valueSet = new ValueSet() : result; + } } diff --git a/src/main/java/com/google/common/collect/AbstractIndexedListIterator.java b/src/main/java/com/google/common/collect/AbstractIndexedListIterator.java index a66f65b9..b7fd602a 100644 --- a/src/main/java/com/google/common/collect/AbstractIndexedListIterator.java +++ b/src/main/java/com/google/common/collect/AbstractIndexedListIterator.java @@ -35,12 +35,6 @@ abstract class AbstractIndexedListIterator extends UnmodifiableListIterator extends UnmodifiableListIterator 0; + } + @Override public final E next() { if (!hasNext()) { @@ -88,11 +93,6 @@ abstract class AbstractIndexedListIterator extends UnmodifiableListIterator 0; - } - @Override public final E previous() { if (!hasPrevious()) { diff --git a/src/main/java/com/google/common/collect/AbstractIterator.java b/src/main/java/com/google/common/collect/AbstractIterator.java index 160e0819..ae130ead 100644 --- a/src/main/java/com/google/common/collect/AbstractIterator.java +++ b/src/main/java/com/google/common/collect/AbstractIterator.java @@ -44,19 +44,20 @@ import com.google.common.annotations.GwtCompatible; *
  *    {@code
  *
- *   public static Iterator skipNulls(final Iterator in) {
- *     return new AbstractIterator() {
- *       protected String computeNext() {
- *         while (in.hasNext()) {
- *           String s = in.next();
- *           if (s != null) {
- *             return s;
- *           }
- *         }
- *         return endOfData();
- *       }
- *     };
- *   }}
+ * public static Iterator skipNulls(final Iterator in) {
+ * 	return new AbstractIterator() {
+ * 		protected String computeNext() {
+ * 			while (in.hasNext()) {
+ * 				String s = in.next();
+ * 				if (s != null) {
+ * 					return s;
+ * 				}
+ * 			}
+ * 			return endOfData();
+ * 		}
+ * 	};
+ * }
+ * }
  * 
* *

@@ -69,12 +70,6 @@ import com.google.common.annotations.GwtCompatible; // com.google.common.base.AbstractIterator @GwtCompatible public abstract class AbstractIterator extends UnmodifiableIterator { - private State state = State.NOT_READY; - - /** Constructor for use by subclasses. */ - protected AbstractIterator() { - } - private enum State { /** We have computed the next element and haven't returned it yet. */ READY, @@ -89,8 +84,14 @@ public abstract class AbstractIterator extends UnmodifiableIterator { FAILED, } + private State state = State.NOT_READY; + private T next; + /** Constructor for use by subclasses. */ + protected AbstractIterator() { + } + /** * Returns the next element. Note: the implementation must call * {@link #endOfData()} when there are no elements left in the iteration. @@ -151,16 +152,6 @@ public abstract class AbstractIterator extends UnmodifiableIterator { return tryToComputeNext(); } - private boolean tryToComputeNext() { - state = State.FAILED; // temporary pessimism - next = computeNext(); - if (state != State.DONE) { - state = State.READY; - return true; - } - return false; - } - @Override public final T next() { if (!hasNext()) { @@ -186,4 +177,14 @@ public abstract class AbstractIterator extends UnmodifiableIterator { } return next; } + + private boolean tryToComputeNext() { + state = State.FAILED; // temporary pessimism + next = computeNext(); + if (state != State.DONE) { + state = State.READY; + return true; + } + return false; + } } diff --git a/src/main/java/com/google/common/collect/AbstractListMultimap.java b/src/main/java/com/google/common/collect/AbstractListMultimap.java index caa5e960..55ca91e4 100644 --- a/src/main/java/com/google/common/collect/AbstractListMultimap.java +++ b/src/main/java/com/google/common/collect/AbstractListMultimap.java @@ -36,6 +36,8 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible abstract class AbstractListMultimap extends AbstractMapBasedMultimap implements ListMultimap { + private static final long serialVersionUID = 6588350623831699109L; + /** * Creates a new multimap that uses the provided map. * @@ -46,6 +48,20 @@ abstract class AbstractListMultimap extends AbstractMapBasedMultimap super(map); } + /** + * {@inheritDoc} + * + *

+ * Though the method signature doesn't say so explicitly, the returned map has + * {@link List} values. + */ + @Override + public Map> asMap() { + return super.asMap(); + } + + // Following Javadoc copied from ListMultimap. + @Override abstract List createCollection(); @@ -54,7 +70,18 @@ abstract class AbstractListMultimap extends AbstractMapBasedMultimap return ImmutableList.of(); } - // Following Javadoc copied from ListMultimap. + /** + * Compares the specified object to this multimap for equality. + * + *

+ * Two {@code ListMultimap} instances are equal if, for each key, they contain + * the same values in the same order. If the value orderings disagree, the + * multimaps will not be considered equal. + */ + @Override + public boolean equals(@Nullable Object object) { + return super.equals(object); + } /** * {@inheritDoc} @@ -69,6 +96,18 @@ abstract class AbstractListMultimap extends AbstractMapBasedMultimap return (List) super.get(key); } + /** + * Stores a key-value pair in the multimap. + * + * @param key key to store in the multimap + * @param value value to store in the multimap + * @return {@code true} always + */ + @Override + public boolean put(@Nullable K key, @Nullable V value) { + return super.put(key, value); + } + /** * {@inheritDoc} * @@ -94,43 +133,4 @@ abstract class AbstractListMultimap extends AbstractMapBasedMultimap public List replaceValues(@Nullable K key, Iterable values) { return (List) super.replaceValues(key, values); } - - /** - * Stores a key-value pair in the multimap. - * - * @param key key to store in the multimap - * @param value value to store in the multimap - * @return {@code true} always - */ - @Override - public boolean put(@Nullable K key, @Nullable V value) { - return super.put(key, value); - } - - /** - * {@inheritDoc} - * - *

- * Though the method signature doesn't say so explicitly, the returned map has - * {@link List} values. - */ - @Override - public Map> asMap() { - return super.asMap(); - } - - /** - * Compares the specified object to this multimap for equality. - * - *

- * Two {@code ListMultimap} instances are equal if, for each key, they contain - * the same values in the same order. If the value orderings disagree, the - * multimaps will not be considered equal. - */ - @Override - public boolean equals(@Nullable Object object) { - return super.equals(object); - } - - private static final long serialVersionUID = 6588350623831699109L; } diff --git a/src/main/java/com/google/common/collect/AbstractMapBasedMultimap.java b/src/main/java/com/google/common/collect/AbstractMapBasedMultimap.java index c11cd290..e129b3a8 100644 --- a/src/main/java/com/google/common/collect/AbstractMapBasedMultimap.java +++ b/src/main/java/com/google/common/collect/AbstractMapBasedMultimap.java @@ -115,1227 +115,11 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp * provided key, and if so replaces the delegate. */ - private transient Map> map; - private transient int totalSize; - - /** - * Creates a new multimap that uses the provided map. - * - * @param map place to store the mapping from each key to its corresponding - * values - * @throws IllegalArgumentException if {@code map} is not empty - */ - protected AbstractMapBasedMultimap(Map> map) { - checkArgument(map.isEmpty()); - this.map = map; - } - - /** Used during deserialization only. */ - final void setMap(Map> map) { - this.map = map; - totalSize = 0; - for (Collection values : map.values()) { - checkArgument(!values.isEmpty()); - totalSize += values.size(); - } - } - - /** - * Creates an unmodifiable, empty collection of values. - * - *

- * This is used in {@link #removeAll} on an empty key. - */ - Collection createUnmodifiableEmptyCollection() { - return unmodifiableCollectionSubclass(createCollection()); - } - - /** - * Creates the collection of values for a single key. - * - *

- * Collections with weak, soft, or phantom references are not supported. Each - * call to {@code createCollection} should create a new instance. - * - *

- * The returned collection class determines whether duplicate key-value pairs - * are allowed. - * - * @return an empty collection of values - */ - abstract Collection createCollection(); - - /** - * Creates the collection of values for an explicitly provided key. By default, - * it simply calls {@link #createCollection()}, which is the correct behavior - * for most implementations. The {@link LinkedHashMultimap} class overrides it. - * - * @param key key to associate with values in the collection - * @return an empty collection of values - */ - Collection createCollection(@Nullable K key) { - return createCollection(); - } - - Map> backingMap() { - return map; - } - - // Query Operations - - @Override - public int size() { - return totalSize; - } - - @Override - public boolean containsKey(@Nullable Object key) { - return map.containsKey(key); - } - - // Modification Operations - - @Override - public boolean put(@Nullable K key, @Nullable V value) { - Collection collection = map.get(key); - if (collection == null) { - collection = createCollection(key); - if (collection.add(value)) { - totalSize++; - map.put(key, collection); - return true; - } else { - throw new AssertionError("New Collection violated the Collection spec"); - } - } else if (collection.add(value)) { - totalSize++; - return true; - } else { - return false; - } - } - - private Collection getOrCreateCollection(@Nullable K key) { - Collection collection = map.get(key); - if (collection == null) { - collection = createCollection(key); - map.put(key, collection); - } - return collection; - } - - // Bulk Operations - - /** - * {@inheritDoc} - * - *

- * The returned collection is immutable. - */ - @Override - public Collection replaceValues(@Nullable K key, Iterable values) { - Iterator iterator = values.iterator(); - if (!iterator.hasNext()) { - return removeAll(key); - } - - // TODO(user): investigate atomic failure? - Collection collection = getOrCreateCollection(key); - Collection oldValues = createCollection(); - oldValues.addAll(collection); - - totalSize -= collection.size(); - collection.clear(); - - while (iterator.hasNext()) { - if (collection.add(iterator.next())) { - totalSize++; - } - } - - return unmodifiableCollectionSubclass(oldValues); - } - - /** - * {@inheritDoc} - * - *

- * The returned collection is immutable. - */ - @Override - public Collection removeAll(@Nullable Object key) { - Collection collection = map.remove(key); - - if (collection == null) { - return createUnmodifiableEmptyCollection(); - } - - Collection output = createCollection(); - output.addAll(collection); - totalSize -= collection.size(); - collection.clear(); - - return unmodifiableCollectionSubclass(output); - } - - Collection unmodifiableCollectionSubclass(Collection collection) { - // We don't deal with NavigableSet here yet for GWT reasons -- instead, - // non-GWT TreeMultimap explicitly overrides this and uses NavigableSet. - if (collection instanceof SortedSet) { - return Collections.unmodifiableSortedSet((SortedSet) collection); - } else if (collection instanceof Set) { - return Collections.unmodifiableSet((Set) collection); - } else if (collection instanceof List) { - return Collections.unmodifiableList((List) collection); - } else { - return Collections.unmodifiableCollection(collection); - } - } - - @Override - public void clear() { - // Clear each collection, to make previously returned collections empty. - for (Collection collection : map.values()) { - collection.clear(); - } - map.clear(); - totalSize = 0; - } - - // Views - - /** - * {@inheritDoc} - * - *

- * The returned collection is not serializable. - */ - @Override - public Collection get(@Nullable K key) { - Collection collection = map.get(key); - if (collection == null) { - collection = createCollection(key); - } - return wrapCollection(key, collection); - } - - /** - * Generates a decorated collection that remains consistent with the values in - * the multimap for the provided key. Changes to the multimap may alter the - * returned collection, and vice versa. - */ - Collection wrapCollection(@Nullable K key, Collection collection) { - // We don't deal with NavigableSet here yet for GWT reasons -- instead, - // non-GWT TreeMultimap explicitly overrides this and uses NavigableSet. - if (collection instanceof SortedSet) { - return new WrappedSortedSet(key, (SortedSet) collection, null); - } else if (collection instanceof Set) { - return new WrappedSet(key, (Set) collection); - } else if (collection instanceof List) { - return wrapList(key, (List) collection, null); - } else { - return new WrappedCollection(key, collection, null); - } - } - - private List wrapList(@Nullable K key, List list, @Nullable WrappedCollection ancestor) { - return (list instanceof RandomAccess) ? new RandomAccessWrappedList(key, list, ancestor) - : new WrappedList(key, list, ancestor); - } - - /** - * Collection decorator that stays in sync with the multimap values for a key. - * There are two kinds of wrapped collections: full and subcollections. Both - * have a delegate pointing to the underlying collection class. - * - *

- * Full collections, identified by a null ancestor field, contain all multimap - * values for a given key. Its delegate is a value in - * {@link AbstractMapBasedMultimap#map} whenever the delegate is non-empty. The - * {@code - * refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure - * that the {@code WrappedCollection} and map remain consistent. - * - *

- * A subcollection, such as a sublist, contains some of the values for a given - * key. Its ancestor field points to the full wrapped collection with all values - * for the key. The subcollection {@code refreshIfEmpty}, {@code - * removeIfEmpty}, and {@code addToMap} methods call the corresponding methods - * of the full wrapped collection. - */ - private class WrappedCollection extends AbstractCollection { - final K key; - Collection delegate; - final WrappedCollection ancestor; - final Collection ancestorDelegate; - - WrappedCollection(@Nullable K key, Collection delegate, @Nullable WrappedCollection ancestor) { - this.key = key; - this.delegate = delegate; - this.ancestor = ancestor; - this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate(); - } - - /** - * If the delegate collection is empty, but the multimap has values for the key, - * replace the delegate with the new collection for the key. - * - *

- * For a subcollection, refresh its ancestor and validate that the ancestor - * delegate hasn't changed. - */ - void refreshIfEmpty() { - if (ancestor != null) { - ancestor.refreshIfEmpty(); - if (ancestor.getDelegate() != ancestorDelegate) { - throw new ConcurrentModificationException(); - } - } else if (delegate.isEmpty()) { - Collection newDelegate = map.get(key); - if (newDelegate != null) { - delegate = newDelegate; - } - } - } - - /** - * If collection is empty, remove it from - * {@code AbstractMapBasedMultimap.this.map}. For subcollections, check whether - * the ancestor collection is empty. - */ - void removeIfEmpty() { - if (ancestor != null) { - ancestor.removeIfEmpty(); - } else if (delegate.isEmpty()) { - map.remove(key); - } - } - - K getKey() { - return key; - } - - /** - * Add the delegate to the map. Other {@code WrappedCollection} methods should - * call this method after adding elements to a previously empty collection. - * - *

- * Subcollection add the ancestor's delegate instead. - */ - void addToMap() { - if (ancestor != null) { - ancestor.addToMap(); - } else { - map.put(key, delegate); - } - } - - @Override - public int size() { - refreshIfEmpty(); - return delegate.size(); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object == this) { - return true; - } - refreshIfEmpty(); - return delegate.equals(object); - } - - @Override - public int hashCode() { - refreshIfEmpty(); - return delegate.hashCode(); - } - - @Override - public String toString() { - refreshIfEmpty(); - return delegate.toString(); - } - - Collection getDelegate() { - return delegate; - } - - @Override - public Iterator iterator() { - refreshIfEmpty(); - return new WrappedIterator(); - } - - /** Collection iterator for {@code WrappedCollection}. */ - class WrappedIterator implements Iterator { - final Iterator delegateIterator; - final Collection originalDelegate = delegate; - - WrappedIterator() { - delegateIterator = iteratorOrListIterator(delegate); - } - - WrappedIterator(Iterator delegateIterator) { - this.delegateIterator = delegateIterator; - } - - /** - * If the delegate changed since the iterator was created, the iterator is no - * longer valid. - */ - void validateIterator() { - refreshIfEmpty(); - if (delegate != originalDelegate) { - throw new ConcurrentModificationException(); - } - } - - @Override - public boolean hasNext() { - validateIterator(); - return delegateIterator.hasNext(); - } - - @Override - public V next() { - validateIterator(); - return delegateIterator.next(); - } - - @Override - public void remove() { - delegateIterator.remove(); - totalSize--; - removeIfEmpty(); - } - - Iterator getDelegateIterator() { - validateIterator(); - return delegateIterator; - } - } - - @Override - public boolean add(V value) { - refreshIfEmpty(); - boolean wasEmpty = delegate.isEmpty(); - boolean changed = delegate.add(value); - if (changed) { - totalSize++; - if (wasEmpty) { - addToMap(); - } - } - return changed; - } - - WrappedCollection getAncestor() { - return ancestor; - } - - // The following methods are provided for better performance. - - @Override - public boolean addAll(Collection collection) { - if (collection.isEmpty()) { - return false; - } - int oldSize = size(); // calls refreshIfEmpty - boolean changed = delegate.addAll(collection); - if (changed) { - int newSize = delegate.size(); - totalSize += (newSize - oldSize); - if (oldSize == 0) { - addToMap(); - } - } - return changed; - } - - @Override - public boolean contains(Object o) { - refreshIfEmpty(); - return delegate.contains(o); - } - - @Override - public boolean containsAll(Collection c) { - refreshIfEmpty(); - return delegate.containsAll(c); - } - - @Override - public void clear() { - int oldSize = size(); // calls refreshIfEmpty - if (oldSize == 0) { - return; - } - delegate.clear(); - totalSize -= oldSize; - removeIfEmpty(); // maybe shouldn't be removed if this is a sublist - } - - @Override - public boolean remove(Object o) { - refreshIfEmpty(); - boolean changed = delegate.remove(o); - if (changed) { - totalSize--; - removeIfEmpty(); - } - return changed; - } - - @Override - public boolean removeAll(Collection c) { - if (c.isEmpty()) { - return false; - } - int oldSize = size(); // calls refreshIfEmpty - boolean changed = delegate.removeAll(c); - if (changed) { - int newSize = delegate.size(); - totalSize += (newSize - oldSize); - removeIfEmpty(); - } - return changed; - } - - @Override - public boolean retainAll(Collection c) { - checkNotNull(c); - int oldSize = size(); // calls refreshIfEmpty - boolean changed = delegate.retainAll(c); - if (changed) { - int newSize = delegate.size(); - totalSize += (newSize - oldSize); - removeIfEmpty(); - } - return changed; - } - } - - private Iterator iteratorOrListIterator(Collection collection) { - return (collection instanceof List) ? ((List) collection).listIterator() : collection.iterator(); - } - - /** Set decorator that stays in sync with the multimap values for a key. */ - private class WrappedSet extends WrappedCollection implements Set { - WrappedSet(@Nullable K key, Set delegate) { - super(key, delegate, null); - } - - @Override - public boolean removeAll(Collection c) { - if (c.isEmpty()) { - return false; - } - int oldSize = size(); // calls refreshIfEmpty - - // Guava issue 1013: AbstractSet and most JDK set implementations are - // susceptible to quadratic removeAll performance on lists; - // use a slightly smarter implementation here - boolean changed = Sets.removeAllImpl((Set) delegate, c); - if (changed) { - int newSize = delegate.size(); - totalSize += (newSize - oldSize); - removeIfEmpty(); - } - return changed; - } - } - - /** - * SortedSet decorator that stays in sync with the multimap values for a key. - */ - private class WrappedSortedSet extends WrappedCollection implements SortedSet { - WrappedSortedSet(@Nullable K key, SortedSet delegate, @Nullable WrappedCollection ancestor) { - super(key, delegate, ancestor); - } - - SortedSet getSortedSetDelegate() { - return (SortedSet) getDelegate(); - } - - @Override - public Comparator comparator() { - return getSortedSetDelegate().comparator(); - } - - @Override - public V first() { - refreshIfEmpty(); - return getSortedSetDelegate().first(); - } - - @Override - public V last() { - refreshIfEmpty(); - return getSortedSetDelegate().last(); - } - - @Override - public SortedSet headSet(V toElement) { - refreshIfEmpty(); - return new WrappedSortedSet(getKey(), getSortedSetDelegate().headSet(toElement), - (getAncestor() == null) ? this : getAncestor()); - } - - @Override - public SortedSet subSet(V fromElement, V toElement) { - refreshIfEmpty(); - return new WrappedSortedSet(getKey(), getSortedSetDelegate().subSet(fromElement, toElement), - (getAncestor() == null) ? this : getAncestor()); - } - - @Override - public SortedSet tailSet(V fromElement) { - refreshIfEmpty(); - return new WrappedSortedSet(getKey(), getSortedSetDelegate().tailSet(fromElement), - (getAncestor() == null) ? this : getAncestor()); - } - } - - @GwtIncompatible("NavigableSet") - class WrappedNavigableSet extends WrappedSortedSet implements NavigableSet { - WrappedNavigableSet(@Nullable K key, NavigableSet delegate, @Nullable WrappedCollection ancestor) { - super(key, delegate, ancestor); - } - - @Override - NavigableSet getSortedSetDelegate() { - return (NavigableSet) super.getSortedSetDelegate(); - } - - @Override - public V lower(V v) { - return getSortedSetDelegate().lower(v); - } - - @Override - public V floor(V v) { - return getSortedSetDelegate().floor(v); - } - - @Override - public V ceiling(V v) { - return getSortedSetDelegate().ceiling(v); - } - - @Override - public V higher(V v) { - return getSortedSetDelegate().higher(v); - } - - @Override - public V pollFirst() { - return Iterators.pollNext(iterator()); - } - - @Override - public V pollLast() { - return Iterators.pollNext(descendingIterator()); - } - - private NavigableSet wrap(NavigableSet wrapped) { - return new WrappedNavigableSet(key, wrapped, (getAncestor() == null) ? this : getAncestor()); - } - - @Override - public NavigableSet descendingSet() { - return wrap(getSortedSetDelegate().descendingSet()); - } - - @Override - public Iterator descendingIterator() { - return new WrappedIterator(getSortedSetDelegate().descendingIterator()); - } - - @Override - public NavigableSet subSet(V fromElement, boolean fromInclusive, V toElement, boolean toInclusive) { - return wrap(getSortedSetDelegate().subSet(fromElement, fromInclusive, toElement, toInclusive)); - } - - @Override - public NavigableSet headSet(V toElement, boolean inclusive) { - return wrap(getSortedSetDelegate().headSet(toElement, inclusive)); - } - - @Override - public NavigableSet tailSet(V fromElement, boolean inclusive) { - return wrap(getSortedSetDelegate().tailSet(fromElement, inclusive)); - } - } - - /** List decorator that stays in sync with the multimap values for a key. */ - private class WrappedList extends WrappedCollection implements List { - WrappedList(@Nullable K key, List delegate, @Nullable WrappedCollection ancestor) { - super(key, delegate, ancestor); - } - - List getListDelegate() { - return (List) getDelegate(); - } - - @Override - public boolean addAll(int index, Collection c) { - if (c.isEmpty()) { - return false; - } - int oldSize = size(); // calls refreshIfEmpty - boolean changed = getListDelegate().addAll(index, c); - if (changed) { - int newSize = getDelegate().size(); - totalSize += (newSize - oldSize); - if (oldSize == 0) { - addToMap(); - } - } - return changed; - } - - @Override - public V get(int index) { - refreshIfEmpty(); - return getListDelegate().get(index); - } - - @Override - public V set(int index, V element) { - refreshIfEmpty(); - return getListDelegate().set(index, element); - } - - @Override - public void add(int index, V element) { - refreshIfEmpty(); - boolean wasEmpty = getDelegate().isEmpty(); - getListDelegate().add(index, element); - totalSize++; - if (wasEmpty) { - addToMap(); - } - } - - @Override - public V remove(int index) { - refreshIfEmpty(); - V value = getListDelegate().remove(index); - totalSize--; - removeIfEmpty(); - return value; - } - - @Override - public int indexOf(Object o) { - refreshIfEmpty(); - return getListDelegate().indexOf(o); - } - - @Override - public int lastIndexOf(Object o) { - refreshIfEmpty(); - return getListDelegate().lastIndexOf(o); - } - - @Override - public ListIterator listIterator() { - refreshIfEmpty(); - return new WrappedListIterator(); - } - - @Override - public ListIterator listIterator(int index) { - refreshIfEmpty(); - return new WrappedListIterator(index); - } - - @Override - public List subList(int fromIndex, int toIndex) { - refreshIfEmpty(); - return wrapList(getKey(), getListDelegate().subList(fromIndex, toIndex), - (getAncestor() == null) ? this : getAncestor()); - } - - /** ListIterator decorator. */ - private class WrappedListIterator extends WrappedIterator implements ListIterator { - WrappedListIterator() { - } - - public WrappedListIterator(int index) { - super(getListDelegate().listIterator(index)); - } - - private ListIterator getDelegateListIterator() { - return (ListIterator) getDelegateIterator(); - } - - @Override - public boolean hasPrevious() { - return getDelegateListIterator().hasPrevious(); - } - - @Override - public V previous() { - return getDelegateListIterator().previous(); - } - - @Override - public int nextIndex() { - return getDelegateListIterator().nextIndex(); - } - - @Override - public int previousIndex() { - return getDelegateListIterator().previousIndex(); - } - - @Override - public void set(V value) { - getDelegateListIterator().set(value); - } - - @Override - public void add(V value) { - boolean wasEmpty = isEmpty(); - getDelegateListIterator().add(value); - totalSize++; - if (wasEmpty) { - addToMap(); - } - } - } - } - - /** - * List decorator that stays in sync with the multimap values for a key and - * supports rapid random access. - */ - private class RandomAccessWrappedList extends WrappedList implements RandomAccess { - RandomAccessWrappedList(@Nullable K key, List delegate, @Nullable WrappedCollection ancestor) { - super(key, delegate, ancestor); - } - } - - @Override - Set createKeySet() { - // TreeMultimap uses NavigableKeySet explicitly, but we don't handle that here - // for GWT - // compatibility reasons - return (map instanceof SortedMap) ? new SortedKeySet((SortedMap>) map) : new KeySet(map); - } - - private class KeySet extends Maps.KeySet> { - KeySet(final Map> subMap) { - super(subMap); - } - - @Override - public Iterator iterator() { - final Iterator>> entryIterator = map().entrySet().iterator(); - return new Iterator() { - Map.Entry> entry; - - @Override - public boolean hasNext() { - return entryIterator.hasNext(); - } - - @Override - public K next() { - entry = entryIterator.next(); - return entry.getKey(); - } - - @Override - public void remove() { - checkRemove(entry != null); - Collection collection = entry.getValue(); - entryIterator.remove(); - totalSize -= collection.size(); - collection.clear(); - } - }; - } - - // The following methods are included for better performance. - - @Override - public boolean remove(Object key) { - int count = 0; - Collection collection = map().remove(key); - if (collection != null) { - count = collection.size(); - collection.clear(); - totalSize -= count; - } - return count > 0; - } - - @Override - public void clear() { - Iterators.clear(iterator()); - } - - @Override - public boolean containsAll(Collection c) { - return map().keySet().containsAll(c); - } - - @Override - public boolean equals(@Nullable Object object) { - return this == object || this.map().keySet().equals(object); - } - - @Override - public int hashCode() { - return map().keySet().hashCode(); - } - } - - private class SortedKeySet extends KeySet implements SortedSet { - - SortedKeySet(SortedMap> subMap) { - super(subMap); - } - - SortedMap> sortedMap() { - return (SortedMap>) super.map(); - } - - @Override - public Comparator comparator() { - return sortedMap().comparator(); - } - - @Override - public K first() { - return sortedMap().firstKey(); - } - - @Override - public SortedSet headSet(K toElement) { - return new SortedKeySet(sortedMap().headMap(toElement)); - } - - @Override - public K last() { - return sortedMap().lastKey(); - } - - @Override - public SortedSet subSet(K fromElement, K toElement) { - return new SortedKeySet(sortedMap().subMap(fromElement, toElement)); - } - - @Override - public SortedSet tailSet(K fromElement) { - return new SortedKeySet(sortedMap().tailMap(fromElement)); - } - } - - @GwtIncompatible("NavigableSet") - class NavigableKeySet extends SortedKeySet implements NavigableSet { - NavigableKeySet(NavigableMap> subMap) { - super(subMap); - } - - @Override - NavigableMap> sortedMap() { - return (NavigableMap>) super.sortedMap(); - } - - @Override - public K lower(K k) { - return sortedMap().lowerKey(k); - } - - @Override - public K floor(K k) { - return sortedMap().floorKey(k); - } - - @Override - public K ceiling(K k) { - return sortedMap().ceilingKey(k); - } - - @Override - public K higher(K k) { - return sortedMap().higherKey(k); - } - - @Override - public K pollFirst() { - return Iterators.pollNext(iterator()); - } - - @Override - public K pollLast() { - return Iterators.pollNext(descendingIterator()); - } - - @Override - public NavigableSet descendingSet() { - return new NavigableKeySet(sortedMap().descendingMap()); - } - - @Override - public Iterator descendingIterator() { - return descendingSet().iterator(); - } - - @Override - public NavigableSet headSet(K toElement) { - return headSet(toElement, false); - } - - @Override - public NavigableSet headSet(K toElement, boolean inclusive) { - return new NavigableKeySet(sortedMap().headMap(toElement, inclusive)); - } - - @Override - public NavigableSet subSet(K fromElement, K toElement) { - return subSet(fromElement, true, toElement, false); - } - - @Override - public NavigableSet subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) { - return new NavigableKeySet(sortedMap().subMap(fromElement, fromInclusive, toElement, toInclusive)); - } - - @Override - public NavigableSet tailSet(K fromElement) { - return tailSet(fromElement, true); - } - - @Override - public NavigableSet tailSet(K fromElement, boolean inclusive) { - return new NavigableKeySet(sortedMap().tailMap(fromElement, inclusive)); - } - } - - /** - * Removes all values for the provided key. Unlike {@link #removeAll}, it - * returns the number of removed mappings. - */ - private int removeValuesForKey(Object key) { - Collection collection = Maps.safeRemove(map, key); - - int count = 0; - if (collection != null) { - count = collection.size(); - collection.clear(); - totalSize -= count; - } - return count; - } - - private abstract class Itr implements Iterator { - final Iterator>> keyIterator; - K key; - Collection collection; - Iterator valueIterator; - - Itr() { - keyIterator = map.entrySet().iterator(); - key = null; - collection = null; - valueIterator = Iterators.emptyModifiableIterator(); - } - - abstract T output(K key, V value); - - @Override - public boolean hasNext() { - return keyIterator.hasNext() || valueIterator.hasNext(); - } - - @Override - public T next() { - if (!valueIterator.hasNext()) { - Map.Entry> mapEntry = keyIterator.next(); - key = mapEntry.getKey(); - collection = mapEntry.getValue(); - valueIterator = collection.iterator(); - } - return output(key, valueIterator.next()); - } - - @Override - public void remove() { - valueIterator.remove(); - if (collection.isEmpty()) { - keyIterator.remove(); - } - totalSize--; - } - } - - /** - * {@inheritDoc} - * - *

- * The iterator generated by the returned collection traverses the values for - * one key, followed by the values of a second key, and so on. - */ - @Override - public Collection values() { - return super.values(); - } - - @Override - Iterator valueIterator() { - return new Itr() { - @Override - V output(K key, V value) { - return value; - } - }; - } - - /* - * TODO(kevinb): should we copy this javadoc to each concrete class, so that - * classes like LinkedHashMultimap that need to say something different are - * still able to {@inheritDoc} all the way from Multimap? - */ - - /** - * {@inheritDoc} - * - *

- * The iterator generated by the returned collection traverses the values for - * one key, followed by the values of a second key, and so on. - * - *

- * Each entry is an immutable snapshot of a key-value mapping in the multimap, - * taken at the time the entry is returned by a method call to the collection or - * its iterator. - */ - @Override - public Collection> entries() { - return super.entries(); - } - - /** - * Returns an iterator across all key-value map entries, used by {@code - * entries().iterator()} and {@code values().iterator()}. The default behavior, - * which traverses the values for one key, the values for a second key, and so - * on, suffices for most {@code AbstractMapBasedMultimap} implementations. - * - * @return an iterator across map entries - */ - @Override - Iterator> entryIterator() { - return new Itr>() { - @Override - Entry output(K key, V value) { - return Maps.immutableEntry(key, value); - } - }; - } - - @Override - Map> createAsMap() { - // TreeMultimap uses NavigableAsMap explicitly, but we don't handle that here - // for GWT - // compatibility reasons - return (map instanceof SortedMap) ? new SortedAsMap((SortedMap>) map) : new AsMap(map); - } - private class AsMap extends ImprovedAbstractMap> { - /** - * Usually the same as map, but smaller for the headMap(), tailMap(), or - * subMap() of a SortedAsMap. - */ - final transient Map> submap; - - AsMap(Map> submap) { - this.submap = submap; - } - - @Override - protected Set>> createEntrySet() { - return new AsMapEntries(); - } - - // The following methods are included for performance. - - @Override - public boolean containsKey(Object key) { - return Maps.safeContainsKey(submap, key); - } - - @Override - public Collection get(Object key) { - Collection collection = Maps.safeGet(submap, key); - if (collection == null) { - return null; - } - @SuppressWarnings("unchecked") - K k = (K) key; - return wrapCollection(k, collection); - } - - @Override - public Set keySet() { - return AbstractMapBasedMultimap.this.keySet(); - } - - @Override - public int size() { - return submap.size(); - } - - @Override - public Collection remove(Object key) { - Collection collection = submap.remove(key); - if (collection == null) { - return null; - } - - Collection output = createCollection(); - output.addAll(collection); - totalSize -= collection.size(); - collection.clear(); - return output; - } - - @Override - public boolean equals(@Nullable Object object) { - return this == object || submap.equals(object); - } - - @Override - public int hashCode() { - return submap.hashCode(); - } - - @Override - public String toString() { - return submap.toString(); - } - - @Override - public void clear() { - if (submap == map) { - AbstractMapBasedMultimap.this.clear(); - } else { - Iterators.clear(new AsMapIterator()); - } - } - - Entry> wrapEntry(Entry> entry) { - K key = entry.getKey(); - return Maps.immutableEntry(key, wrapCollection(key, entry.getValue())); - } - class AsMapEntries extends Maps.EntrySet> { @Override - Map> map() { - return AsMap.this; + public boolean contains(Object o) { + return Collections2.safeContains(submap.entrySet(), o); } @Override @@ -1346,8 +130,8 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp // The following methods are included for performance. @Override - public boolean contains(Object o) { - return Collections2.safeContains(submap.entrySet(), o); + Map> map() { + return AsMap.this; } @Override @@ -1385,60 +169,200 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp collection.clear(); } } + + /** + * Usually the same as map, but smaller for the headMap(), tailMap(), or + * subMap() of a SortedAsMap. + */ + final transient Map> submap; + + // The following methods are included for performance. + + AsMap(Map> submap) { + this.submap = submap; + } + + @Override + public void clear() { + if (submap == map) { + AbstractMapBasedMultimap.this.clear(); + } else { + Iterators.clear(new AsMapIterator()); + } + } + + @Override + public boolean containsKey(Object key) { + return Maps.safeContainsKey(submap, key); + } + + @Override + protected Set>> createEntrySet() { + return new AsMapEntries(); + } + + @Override + public boolean equals(@Nullable Object object) { + return this == object || submap.equals(object); + } + + @Override + public Collection get(Object key) { + Collection collection = Maps.safeGet(submap, key); + if (collection == null) { + return null; + } + @SuppressWarnings("unchecked") + K k = (K) key; + return wrapCollection(k, collection); + } + + @Override + public int hashCode() { + return submap.hashCode(); + } + + @Override + public Set keySet() { + return AbstractMapBasedMultimap.this.keySet(); + } + + @Override + public Collection remove(Object key) { + Collection collection = submap.remove(key); + if (collection == null) { + return null; + } + + Collection output = createCollection(); + output.addAll(collection); + totalSize -= collection.size(); + collection.clear(); + return output; + } + + @Override + public int size() { + return submap.size(); + } + + @Override + public String toString() { + return submap.toString(); + } + + Entry> wrapEntry(Entry> entry) { + K key = entry.getKey(); + return Maps.immutableEntry(key, wrapCollection(key, entry.getValue())); + } } - private class SortedAsMap extends AsMap implements SortedMap> { - SortedAsMap(SortedMap> submap) { - super(submap); - } + private abstract class Itr implements Iterator { + final Iterator>> keyIterator; + K key; + Collection collection; + Iterator valueIterator; - SortedMap> sortedMap() { - return (SortedMap>) submap; + Itr() { + keyIterator = map.entrySet().iterator(); + key = null; + collection = null; + valueIterator = Iterators.emptyModifiableIterator(); } @Override - public Comparator comparator() { - return sortedMap().comparator(); + public boolean hasNext() { + return keyIterator.hasNext() || valueIterator.hasNext(); } @Override - public K firstKey() { - return sortedMap().firstKey(); + public T next() { + if (!valueIterator.hasNext()) { + Map.Entry> mapEntry = keyIterator.next(); + key = mapEntry.getKey(); + collection = mapEntry.getValue(); + valueIterator = collection.iterator(); + } + return output(key, valueIterator.next()); + } + + abstract T output(K key, V value); + + @Override + public void remove() { + valueIterator.remove(); + if (collection.isEmpty()) { + keyIterator.remove(); + } + totalSize--; + } + } + + private class KeySet extends Maps.KeySet> { + KeySet(final Map> subMap) { + super(subMap); } @Override - public K lastKey() { - return sortedMap().lastKey(); + public void clear() { + Iterators.clear(iterator()); + } + + // The following methods are included for better performance. + + @Override + public boolean containsAll(Collection c) { + return map().keySet().containsAll(c); } @Override - public SortedMap> headMap(K toKey) { - return new SortedAsMap(sortedMap().headMap(toKey)); + public boolean equals(@Nullable Object object) { + return this == object || this.map().keySet().equals(object); } @Override - public SortedMap> subMap(K fromKey, K toKey) { - return new SortedAsMap(sortedMap().subMap(fromKey, toKey)); + public int hashCode() { + return map().keySet().hashCode(); } @Override - public SortedMap> tailMap(K fromKey) { - return new SortedAsMap(sortedMap().tailMap(fromKey)); - } + public Iterator iterator() { + final Iterator>> entryIterator = map().entrySet().iterator(); + return new Iterator() { + Map.Entry> entry; - SortedSet sortedKeySet; + @Override + public boolean hasNext() { + return entryIterator.hasNext(); + } - // returns a SortedSet, even though returning a Set would be sufficient to - // satisfy the SortedMap.keySet() interface - @Override - public SortedSet keySet() { - SortedSet result = sortedKeySet; - return (result == null) ? sortedKeySet = createKeySet() : result; + @Override + public K next() { + entry = entryIterator.next(); + return entry.getKey(); + } + + @Override + public void remove() { + checkRemove(entry != null); + Collection collection = entry.getValue(); + entryIterator.remove(); + totalSize -= collection.size(); + collection.clear(); + } + }; } @Override - SortedSet createKeySet() { - return new SortedKeySet(sortedMap()); + public boolean remove(Object key) { + int count = 0; + Collection collection = map().remove(key); + if (collection != null) { + count = collection.size(); + collection.clear(); + totalSize -= count; + } + return count > 0; } } @@ -1449,33 +373,6 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp super(submap); } - @Override - NavigableMap> sortedMap() { - return (NavigableMap>) super.sortedMap(); - } - - @Override - public Entry> lowerEntry(K key) { - Entry> entry = sortedMap().lowerEntry(key); - return (entry == null) ? null : wrapEntry(entry); - } - - @Override - public K lowerKey(K key) { - return sortedMap().lowerKey(key); - } - - @Override - public Entry> floorEntry(K key) { - Entry> entry = sortedMap().floorEntry(key); - return (entry == null) ? null : wrapEntry(entry); - } - - @Override - public K floorKey(K key) { - return sortedMap().floorKey(key); - } - @Override public Entry> ceilingEntry(K key) { Entry> entry = sortedMap().ceilingEntry(key); @@ -1487,6 +384,48 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp return sortedMap().ceilingKey(key); } + @Override + NavigableSet createKeySet() { + return new NavigableKeySet(sortedMap()); + } + + @Override + public NavigableSet descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + @Override + public NavigableMap> descendingMap() { + return new NavigableAsMap(sortedMap().descendingMap()); + } + + @Override + public Entry> firstEntry() { + Entry> entry = sortedMap().firstEntry(); + return (entry == null) ? null : wrapEntry(entry); + } + + @Override + public Entry> floorEntry(K key) { + Entry> entry = sortedMap().floorEntry(key); + return (entry == null) ? null : wrapEntry(entry); + } + + @Override + public K floorKey(K key) { + return sortedMap().floorKey(key); + } + + @Override + public NavigableMap> headMap(K toKey) { + return headMap(toKey, false); + } + + @Override + public NavigableMap> headMap(K toKey, boolean inclusive) { + return new NavigableAsMap(sortedMap().headMap(toKey, inclusive)); + } + @Override public Entry> higherEntry(K key) { Entry> entry = sortedMap().higherEntry(key); @@ -1499,9 +438,8 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp } @Override - public Entry> firstEntry() { - Entry> entry = sortedMap().firstEntry(); - return (entry == null) ? null : wrapEntry(entry); + public NavigableSet keySet() { + return (NavigableSet) super.keySet(); } @Override @@ -1511,13 +449,19 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp } @Override - public Entry> pollFirstEntry() { - return pollAsMapEntry(entrySet().iterator()); + public Entry> lowerEntry(K key) { + Entry> entry = sortedMap().lowerEntry(key); + return (entry == null) ? null : wrapEntry(entry); } @Override - public Entry> pollLastEntry() { - return pollAsMapEntry(descendingMap().entrySet().iterator()); + public K lowerKey(K key) { + return sortedMap().lowerKey(key); + } + + @Override + public NavigableSet navigableKeySet() { + return keySet(); } Map.Entry> pollAsMapEntry(Iterator>> entryIterator) { @@ -1532,33 +476,18 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp } @Override - public NavigableMap> descendingMap() { - return new NavigableAsMap(sortedMap().descendingMap()); + public Entry> pollFirstEntry() { + return pollAsMapEntry(entrySet().iterator()); } @Override - public NavigableSet keySet() { - return (NavigableSet) super.keySet(); + public Entry> pollLastEntry() { + return pollAsMapEntry(descendingMap().entrySet().iterator()); } @Override - NavigableSet createKeySet() { - return new NavigableKeySet(sortedMap()); - } - - @Override - public NavigableSet navigableKeySet() { - return keySet(); - } - - @Override - public NavigableSet descendingKeySet() { - return descendingMap().navigableKeySet(); - } - - @Override - public NavigableMap> subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); + NavigableMap> sortedMap() { + return (NavigableMap>) super.sortedMap(); } @Override @@ -1567,13 +496,8 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp } @Override - public NavigableMap> headMap(K toKey) { - return headMap(toKey, false); - } - - @Override - public NavigableMap> headMap(K toKey, boolean inclusive) { - return new NavigableAsMap(sortedMap().headMap(toKey, inclusive)); + public NavigableMap> subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); } @Override @@ -1587,5 +511,1083 @@ abstract class AbstractMapBasedMultimap extends AbstractMultimap imp } } + @GwtIncompatible("NavigableSet") + class NavigableKeySet extends SortedKeySet implements NavigableSet { + NavigableKeySet(NavigableMap> subMap) { + super(subMap); + } + + @Override + public K ceiling(K k) { + return sortedMap().ceilingKey(k); + } + + @Override + public Iterator descendingIterator() { + return descendingSet().iterator(); + } + + @Override + public NavigableSet descendingSet() { + return new NavigableKeySet(sortedMap().descendingMap()); + } + + @Override + public K floor(K k) { + return sortedMap().floorKey(k); + } + + @Override + public NavigableSet headSet(K toElement) { + return headSet(toElement, false); + } + + @Override + public NavigableSet headSet(K toElement, boolean inclusive) { + return new NavigableKeySet(sortedMap().headMap(toElement, inclusive)); + } + + @Override + public K higher(K k) { + return sortedMap().higherKey(k); + } + + @Override + public K lower(K k) { + return sortedMap().lowerKey(k); + } + + @Override + public K pollFirst() { + return Iterators.pollNext(iterator()); + } + + @Override + public K pollLast() { + return Iterators.pollNext(descendingIterator()); + } + + @Override + NavigableMap> sortedMap() { + return (NavigableMap>) super.sortedMap(); + } + + @Override + public NavigableSet subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) { + return new NavigableKeySet(sortedMap().subMap(fromElement, fromInclusive, toElement, toInclusive)); + } + + @Override + public NavigableSet subSet(K fromElement, K toElement) { + return subSet(fromElement, true, toElement, false); + } + + @Override + public NavigableSet tailSet(K fromElement) { + return tailSet(fromElement, true); + } + + @Override + public NavigableSet tailSet(K fromElement, boolean inclusive) { + return new NavigableKeySet(sortedMap().tailMap(fromElement, inclusive)); + } + } + + /** + * List decorator that stays in sync with the multimap values for a key and + * supports rapid random access. + */ + private class RandomAccessWrappedList extends WrappedList implements RandomAccess { + RandomAccessWrappedList(@Nullable K key, List delegate, @Nullable WrappedCollection ancestor) { + super(key, delegate, ancestor); + } + } + + private class SortedAsMap extends AsMap implements SortedMap> { + SortedSet sortedKeySet; + + SortedAsMap(SortedMap> submap) { + super(submap); + } + + @Override + public Comparator comparator() { + return sortedMap().comparator(); + } + + @Override + SortedSet createKeySet() { + return new SortedKeySet(sortedMap()); + } + + @Override + public K firstKey() { + return sortedMap().firstKey(); + } + + @Override + public SortedMap> headMap(K toKey) { + return new SortedAsMap(sortedMap().headMap(toKey)); + } + + // returns a SortedSet, even though returning a Set would be sufficient to + // satisfy the SortedMap.keySet() interface + @Override + public SortedSet keySet() { + SortedSet result = sortedKeySet; + return (result == null) ? sortedKeySet = createKeySet() : result; + } + + @Override + public K lastKey() { + return sortedMap().lastKey(); + } + + SortedMap> sortedMap() { + return (SortedMap>) submap; + } + + @Override + public SortedMap> subMap(K fromKey, K toKey) { + return new SortedAsMap(sortedMap().subMap(fromKey, toKey)); + } + + @Override + public SortedMap> tailMap(K fromKey) { + return new SortedAsMap(sortedMap().tailMap(fromKey)); + } + } + + private class SortedKeySet extends KeySet implements SortedSet { + + SortedKeySet(SortedMap> subMap) { + super(subMap); + } + + @Override + public Comparator comparator() { + return sortedMap().comparator(); + } + + @Override + public K first() { + return sortedMap().firstKey(); + } + + @Override + public SortedSet headSet(K toElement) { + return new SortedKeySet(sortedMap().headMap(toElement)); + } + + @Override + public K last() { + return sortedMap().lastKey(); + } + + SortedMap> sortedMap() { + return (SortedMap>) super.map(); + } + + @Override + public SortedSet subSet(K fromElement, K toElement) { + return new SortedKeySet(sortedMap().subMap(fromElement, toElement)); + } + + @Override + public SortedSet tailSet(K fromElement) { + return new SortedKeySet(sortedMap().tailMap(fromElement)); + } + } + + // Query Operations + + /** + * Collection decorator that stays in sync with the multimap values for a key. + * There are two kinds of wrapped collections: full and subcollections. Both + * have a delegate pointing to the underlying collection class. + * + *

+ * Full collections, identified by a null ancestor field, contain all multimap + * values for a given key. Its delegate is a value in + * {@link AbstractMapBasedMultimap#map} whenever the delegate is non-empty. The + * {@code + * refreshIfEmpty}, {@code removeIfEmpty}, and {@code addToMap} methods ensure + * that the {@code WrappedCollection} and map remain consistent. + * + *

+ * A subcollection, such as a sublist, contains some of the values for a given + * key. Its ancestor field points to the full wrapped collection with all values + * for the key. The subcollection {@code refreshIfEmpty}, {@code + * removeIfEmpty}, and {@code addToMap} methods call the corresponding methods + * of the full wrapped collection. + */ + private class WrappedCollection extends AbstractCollection { + /** Collection iterator for {@code WrappedCollection}. */ + class WrappedIterator implements Iterator { + final Iterator delegateIterator; + final Collection originalDelegate = delegate; + + WrappedIterator() { + delegateIterator = iteratorOrListIterator(delegate); + } + + WrappedIterator(Iterator delegateIterator) { + this.delegateIterator = delegateIterator; + } + + Iterator getDelegateIterator() { + validateIterator(); + return delegateIterator; + } + + @Override + public boolean hasNext() { + validateIterator(); + return delegateIterator.hasNext(); + } + + @Override + public V next() { + validateIterator(); + return delegateIterator.next(); + } + + @Override + public void remove() { + delegateIterator.remove(); + totalSize--; + removeIfEmpty(); + } + + /** + * If the delegate changed since the iterator was created, the iterator is no + * longer valid. + */ + void validateIterator() { + refreshIfEmpty(); + if (delegate != originalDelegate) { + throw new ConcurrentModificationException(); + } + } + } + + final K key; + Collection delegate; + final WrappedCollection ancestor; + + final Collection ancestorDelegate; + + WrappedCollection(@Nullable K key, Collection delegate, @Nullable WrappedCollection ancestor) { + this.key = key; + this.delegate = delegate; + this.ancestor = ancestor; + this.ancestorDelegate = (ancestor == null) ? null : ancestor.getDelegate(); + } + + @Override + public boolean add(V value) { + refreshIfEmpty(); + boolean wasEmpty = delegate.isEmpty(); + boolean changed = delegate.add(value); + if (changed) { + totalSize++; + if (wasEmpty) { + addToMap(); + } + } + return changed; + } + + @Override + public boolean addAll(Collection collection) { + if (collection.isEmpty()) { + return false; + } + int oldSize = size(); // calls refreshIfEmpty + boolean changed = delegate.addAll(collection); + if (changed) { + int newSize = delegate.size(); + totalSize += (newSize - oldSize); + if (oldSize == 0) { + addToMap(); + } + } + return changed; + } + + /** + * Add the delegate to the map. Other {@code WrappedCollection} methods should + * call this method after adding elements to a previously empty collection. + * + *

+ * Subcollection add the ancestor's delegate instead. + */ + void addToMap() { + if (ancestor != null) { + ancestor.addToMap(); + } else { + map.put(key, delegate); + } + } + + @Override + public void clear() { + int oldSize = size(); // calls refreshIfEmpty + if (oldSize == 0) { + return; + } + delegate.clear(); + totalSize -= oldSize; + removeIfEmpty(); // maybe shouldn't be removed if this is a sublist + } + + @Override + public boolean contains(Object o) { + refreshIfEmpty(); + return delegate.contains(o); + } + + @Override + public boolean containsAll(Collection c) { + refreshIfEmpty(); + return delegate.containsAll(c); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object == this) { + return true; + } + refreshIfEmpty(); + return delegate.equals(object); + } + + WrappedCollection getAncestor() { + return ancestor; + } + + Collection getDelegate() { + return delegate; + } + + K getKey() { + return key; + } + + @Override + public int hashCode() { + refreshIfEmpty(); + return delegate.hashCode(); + } + + @Override + public Iterator iterator() { + refreshIfEmpty(); + return new WrappedIterator(); + } + + // The following methods are provided for better performance. + + /** + * If the delegate collection is empty, but the multimap has values for the key, + * replace the delegate with the new collection for the key. + * + *

+ * For a subcollection, refresh its ancestor and validate that the ancestor + * delegate hasn't changed. + */ + void refreshIfEmpty() { + if (ancestor != null) { + ancestor.refreshIfEmpty(); + if (ancestor.getDelegate() != ancestorDelegate) { + throw new ConcurrentModificationException(); + } + } else if (delegate.isEmpty()) { + Collection newDelegate = map.get(key); + if (newDelegate != null) { + delegate = newDelegate; + } + } + } + + @Override + public boolean remove(Object o) { + refreshIfEmpty(); + boolean changed = delegate.remove(o); + if (changed) { + totalSize--; + removeIfEmpty(); + } + return changed; + } + + @Override + public boolean removeAll(Collection c) { + if (c.isEmpty()) { + return false; + } + int oldSize = size(); // calls refreshIfEmpty + boolean changed = delegate.removeAll(c); + if (changed) { + int newSize = delegate.size(); + totalSize += (newSize - oldSize); + removeIfEmpty(); + } + return changed; + } + + /** + * If collection is empty, remove it from + * {@code AbstractMapBasedMultimap.this.map}. For subcollections, check whether + * the ancestor collection is empty. + */ + void removeIfEmpty() { + if (ancestor != null) { + ancestor.removeIfEmpty(); + } else if (delegate.isEmpty()) { + map.remove(key); + } + } + + @Override + public boolean retainAll(Collection c) { + checkNotNull(c); + int oldSize = size(); // calls refreshIfEmpty + boolean changed = delegate.retainAll(c); + if (changed) { + int newSize = delegate.size(); + totalSize += (newSize - oldSize); + removeIfEmpty(); + } + return changed; + } + + @Override + public int size() { + refreshIfEmpty(); + return delegate.size(); + } + + @Override + public String toString() { + refreshIfEmpty(); + return delegate.toString(); + } + } + + /** List decorator that stays in sync with the multimap values for a key. */ + private class WrappedList extends WrappedCollection implements List { + /** ListIterator decorator. */ + private class WrappedListIterator extends WrappedIterator implements ListIterator { + WrappedListIterator() { + } + + public WrappedListIterator(int index) { + super(getListDelegate().listIterator(index)); + } + + @Override + public void add(V value) { + boolean wasEmpty = isEmpty(); + getDelegateListIterator().add(value); + totalSize++; + if (wasEmpty) { + addToMap(); + } + } + + private ListIterator getDelegateListIterator() { + return (ListIterator) getDelegateIterator(); + } + + @Override + public boolean hasPrevious() { + return getDelegateListIterator().hasPrevious(); + } + + @Override + public int nextIndex() { + return getDelegateListIterator().nextIndex(); + } + + @Override + public V previous() { + return getDelegateListIterator().previous(); + } + + @Override + public int previousIndex() { + return getDelegateListIterator().previousIndex(); + } + + @Override + public void set(V value) { + getDelegateListIterator().set(value); + } + } + + WrappedList(@Nullable K key, List delegate, @Nullable WrappedCollection ancestor) { + super(key, delegate, ancestor); + } + + @Override + public void add(int index, V element) { + refreshIfEmpty(); + boolean wasEmpty = getDelegate().isEmpty(); + getListDelegate().add(index, element); + totalSize++; + if (wasEmpty) { + addToMap(); + } + } + + @Override + public boolean addAll(int index, Collection c) { + if (c.isEmpty()) { + return false; + } + int oldSize = size(); // calls refreshIfEmpty + boolean changed = getListDelegate().addAll(index, c); + if (changed) { + int newSize = getDelegate().size(); + totalSize += (newSize - oldSize); + if (oldSize == 0) { + addToMap(); + } + } + return changed; + } + + @Override + public V get(int index) { + refreshIfEmpty(); + return getListDelegate().get(index); + } + + List getListDelegate() { + return (List) getDelegate(); + } + + @Override + public int indexOf(Object o) { + refreshIfEmpty(); + return getListDelegate().indexOf(o); + } + + @Override + public int lastIndexOf(Object o) { + refreshIfEmpty(); + return getListDelegate().lastIndexOf(o); + } + + @Override + public ListIterator listIterator() { + refreshIfEmpty(); + return new WrappedListIterator(); + } + + @Override + public ListIterator listIterator(int index) { + refreshIfEmpty(); + return new WrappedListIterator(index); + } + + @Override + public V remove(int index) { + refreshIfEmpty(); + V value = getListDelegate().remove(index); + totalSize--; + removeIfEmpty(); + return value; + } + + @Override + public V set(int index, V element) { + refreshIfEmpty(); + return getListDelegate().set(index, element); + } + + @Override + public List subList(int fromIndex, int toIndex) { + refreshIfEmpty(); + return wrapList(getKey(), getListDelegate().subList(fromIndex, toIndex), + (getAncestor() == null) ? this : getAncestor()); + } + } + + // Modification Operations + + @GwtIncompatible("NavigableSet") + class WrappedNavigableSet extends WrappedSortedSet implements NavigableSet { + WrappedNavigableSet(@Nullable K key, NavigableSet delegate, @Nullable WrappedCollection ancestor) { + super(key, delegate, ancestor); + } + + @Override + public V ceiling(V v) { + return getSortedSetDelegate().ceiling(v); + } + + @Override + public Iterator descendingIterator() { + return new WrappedIterator(getSortedSetDelegate().descendingIterator()); + } + + @Override + public NavigableSet descendingSet() { + return wrap(getSortedSetDelegate().descendingSet()); + } + + @Override + public V floor(V v) { + return getSortedSetDelegate().floor(v); + } + + @Override + NavigableSet getSortedSetDelegate() { + return (NavigableSet) super.getSortedSetDelegate(); + } + + @Override + public NavigableSet headSet(V toElement, boolean inclusive) { + return wrap(getSortedSetDelegate().headSet(toElement, inclusive)); + } + + @Override + public V higher(V v) { + return getSortedSetDelegate().higher(v); + } + + @Override + public V lower(V v) { + return getSortedSetDelegate().lower(v); + } + + @Override + public V pollFirst() { + return Iterators.pollNext(iterator()); + } + + @Override + public V pollLast() { + return Iterators.pollNext(descendingIterator()); + } + + @Override + public NavigableSet subSet(V fromElement, boolean fromInclusive, V toElement, boolean toInclusive) { + return wrap(getSortedSetDelegate().subSet(fromElement, fromInclusive, toElement, toInclusive)); + } + + @Override + public NavigableSet tailSet(V fromElement, boolean inclusive) { + return wrap(getSortedSetDelegate().tailSet(fromElement, inclusive)); + } + + private NavigableSet wrap(NavigableSet wrapped) { + return new WrappedNavigableSet(key, wrapped, (getAncestor() == null) ? this : getAncestor()); + } + } + + /** Set decorator that stays in sync with the multimap values for a key. */ + private class WrappedSet extends WrappedCollection implements Set { + WrappedSet(@Nullable K key, Set delegate) { + super(key, delegate, null); + } + + @Override + public boolean removeAll(Collection c) { + if (c.isEmpty()) { + return false; + } + int oldSize = size(); // calls refreshIfEmpty + + // Guava issue 1013: AbstractSet and most JDK set implementations are + // susceptible to quadratic removeAll performance on lists; + // use a slightly smarter implementation here + boolean changed = Sets.removeAllImpl((Set) delegate, c); + if (changed) { + int newSize = delegate.size(); + totalSize += (newSize - oldSize); + removeIfEmpty(); + } + return changed; + } + } + + // Bulk Operations + + /** + * SortedSet decorator that stays in sync with the multimap values for a key. + */ + private class WrappedSortedSet extends WrappedCollection implements SortedSet { + WrappedSortedSet(@Nullable K key, SortedSet delegate, @Nullable WrappedCollection ancestor) { + super(key, delegate, ancestor); + } + + @Override + public Comparator comparator() { + return getSortedSetDelegate().comparator(); + } + + @Override + public V first() { + refreshIfEmpty(); + return getSortedSetDelegate().first(); + } + + SortedSet getSortedSetDelegate() { + return (SortedSet) getDelegate(); + } + + @Override + public SortedSet headSet(V toElement) { + refreshIfEmpty(); + return new WrappedSortedSet(getKey(), getSortedSetDelegate().headSet(toElement), + (getAncestor() == null) ? this : getAncestor()); + } + + @Override + public V last() { + refreshIfEmpty(); + return getSortedSetDelegate().last(); + } + + @Override + public SortedSet subSet(V fromElement, V toElement) { + refreshIfEmpty(); + return new WrappedSortedSet(getKey(), getSortedSetDelegate().subSet(fromElement, toElement), + (getAncestor() == null) ? this : getAncestor()); + } + + @Override + public SortedSet tailSet(V fromElement) { + refreshIfEmpty(); + return new WrappedSortedSet(getKey(), getSortedSetDelegate().tailSet(fromElement), + (getAncestor() == null) ? this : getAncestor()); + } + } + private static final long serialVersionUID = 2447537837011683357L; + + private transient Map> map; + + private transient int totalSize; + + // Views + + /** + * Creates a new multimap that uses the provided map. + * + * @param map place to store the mapping from each key to its corresponding + * values + * @throws IllegalArgumentException if {@code map} is not empty + */ + protected AbstractMapBasedMultimap(Map> map) { + checkArgument(map.isEmpty()); + this.map = map; + } + + Map> backingMap() { + return map; + } + + @Override + public void clear() { + // Clear each collection, to make previously returned collections empty. + for (Collection collection : map.values()) { + collection.clear(); + } + map.clear(); + totalSize = 0; + } + + @Override + public boolean containsKey(@Nullable Object key) { + return map.containsKey(key); + } + + @Override + Map> createAsMap() { + // TreeMultimap uses NavigableAsMap explicitly, but we don't handle that here + // for GWT + // compatibility reasons + return (map instanceof SortedMap) ? new SortedAsMap((SortedMap>) map) : new AsMap(map); + } + + /** + * Creates the collection of values for a single key. + * + *

+ * Collections with weak, soft, or phantom references are not supported. Each + * call to {@code createCollection} should create a new instance. + * + *

+ * The returned collection class determines whether duplicate key-value pairs + * are allowed. + * + * @return an empty collection of values + */ + abstract Collection createCollection(); + + /** + * Creates the collection of values for an explicitly provided key. By default, + * it simply calls {@link #createCollection()}, which is the correct behavior + * for most implementations. The {@link LinkedHashMultimap} class overrides it. + * + * @param key key to associate with values in the collection + * @return an empty collection of values + */ + Collection createCollection(@Nullable K key) { + return createCollection(); + } + + @Override + Set createKeySet() { + // TreeMultimap uses NavigableKeySet explicitly, but we don't handle that here + // for GWT + // compatibility reasons + return (map instanceof SortedMap) ? new SortedKeySet((SortedMap>) map) : new KeySet(map); + } + + /** + * Creates an unmodifiable, empty collection of values. + * + *

+ * This is used in {@link #removeAll} on an empty key. + */ + Collection createUnmodifiableEmptyCollection() { + return unmodifiableCollectionSubclass(createCollection()); + } + + /** + * {@inheritDoc} + * + *

+ * The iterator generated by the returned collection traverses the values for + * one key, followed by the values of a second key, and so on. + * + *

+ * Each entry is an immutable snapshot of a key-value mapping in the multimap, + * taken at the time the entry is returned by a method call to the collection or + * its iterator. + */ + @Override + public Collection> entries() { + return super.entries(); + } + + /** + * Returns an iterator across all key-value map entries, used by {@code + * entries().iterator()} and {@code values().iterator()}. The default behavior, + * which traverses the values for one key, the values for a second key, and so + * on, suffices for most {@code AbstractMapBasedMultimap} implementations. + * + * @return an iterator across map entries + */ + @Override + Iterator> entryIterator() { + return new Itr>() { + @Override + Entry output(K key, V value) { + return Maps.immutableEntry(key, value); + } + }; + } + + /** + * {@inheritDoc} + * + *

+ * The returned collection is not serializable. + */ + @Override + public Collection get(@Nullable K key) { + Collection collection = map.get(key); + if (collection == null) { + collection = createCollection(key); + } + return wrapCollection(key, collection); + } + + private Collection getOrCreateCollection(@Nullable K key) { + Collection collection = map.get(key); + if (collection == null) { + collection = createCollection(key); + map.put(key, collection); + } + return collection; + } + + private Iterator iteratorOrListIterator(Collection collection) { + return (collection instanceof List) ? ((List) collection).listIterator() : collection.iterator(); + } + + @Override + public boolean put(@Nullable K key, @Nullable V value) { + Collection collection = map.get(key); + if (collection == null) { + collection = createCollection(key); + if (collection.add(value)) { + totalSize++; + map.put(key, collection); + return true; + } else { + throw new AssertionError("New Collection violated the Collection spec"); + } + } else if (collection.add(value)) { + totalSize++; + return true; + } else { + return false; + } + } + + /** + * {@inheritDoc} + * + *

+ * The returned collection is immutable. + */ + @Override + public Collection removeAll(@Nullable Object key) { + Collection collection = map.remove(key); + + if (collection == null) { + return createUnmodifiableEmptyCollection(); + } + + Collection output = createCollection(); + output.addAll(collection); + totalSize -= collection.size(); + collection.clear(); + + return unmodifiableCollectionSubclass(output); + } + + /** + * Removes all values for the provided key. Unlike {@link #removeAll}, it + * returns the number of removed mappings. + */ + private int removeValuesForKey(Object key) { + Collection collection = Maps.safeRemove(map, key); + + int count = 0; + if (collection != null) { + count = collection.size(); + collection.clear(); + totalSize -= count; + } + return count; + } + + /** + * {@inheritDoc} + * + *

+ * The returned collection is immutable. + */ + @Override + public Collection replaceValues(@Nullable K key, Iterable values) { + Iterator iterator = values.iterator(); + if (!iterator.hasNext()) { + return removeAll(key); + } + + // TODO(user): investigate atomic failure? + Collection collection = getOrCreateCollection(key); + Collection oldValues = createCollection(); + oldValues.addAll(collection); + + totalSize -= collection.size(); + collection.clear(); + + while (iterator.hasNext()) { + if (collection.add(iterator.next())) { + totalSize++; + } + } + + return unmodifiableCollectionSubclass(oldValues); + } + + /* + * TODO(kevinb): should we copy this javadoc to each concrete class, so that + * classes like LinkedHashMultimap that need to say something different are + * still able to {@inheritDoc} all the way from Multimap? + */ + + /** Used during deserialization only. */ + final void setMap(Map> map) { + this.map = map; + totalSize = 0; + for (Collection values : map.values()) { + checkArgument(!values.isEmpty()); + totalSize += values.size(); + } + } + + @Override + public int size() { + return totalSize; + } + + Collection unmodifiableCollectionSubclass(Collection collection) { + // We don't deal with NavigableSet here yet for GWT reasons -- instead, + // non-GWT TreeMultimap explicitly overrides this and uses NavigableSet. + if (collection instanceof SortedSet) { + return Collections.unmodifiableSortedSet((SortedSet) collection); + } else if (collection instanceof Set) { + return Collections.unmodifiableSet((Set) collection); + } else if (collection instanceof List) { + return Collections.unmodifiableList((List) collection); + } else { + return Collections.unmodifiableCollection(collection); + } + } + + @Override + Iterator valueIterator() { + return new Itr() { + @Override + V output(K key, V value) { + return value; + } + }; + } + + /** + * {@inheritDoc} + * + *

+ * The iterator generated by the returned collection traverses the values for + * one key, followed by the values of a second key, and so on. + */ + @Override + public Collection values() { + return super.values(); + } + + /** + * Generates a decorated collection that remains consistent with the values in + * the multimap for the provided key. Changes to the multimap may alter the + * returned collection, and vice versa. + */ + Collection wrapCollection(@Nullable K key, Collection collection) { + // We don't deal with NavigableSet here yet for GWT reasons -- instead, + // non-GWT TreeMultimap explicitly overrides this and uses NavigableSet. + if (collection instanceof SortedSet) { + return new WrappedSortedSet(key, (SortedSet) collection, null); + } else if (collection instanceof Set) { + return new WrappedSet(key, (Set) collection); + } else if (collection instanceof List) { + return wrapList(key, (List) collection, null); + } else { + return new WrappedCollection(key, collection, null); + } + } + + private List wrapList(@Nullable K key, List list, @Nullable WrappedCollection ancestor) { + return (list instanceof RandomAccess) ? new RandomAccessWrappedList(key, list, ancestor) + : new WrappedList(key, list, ancestor); + } } diff --git a/src/main/java/com/google/common/collect/AbstractMapBasedMultiset.java b/src/main/java/com/google/common/collect/AbstractMapBasedMultiset.java index 4b200c3e..37bf1dbf 100644 --- a/src/main/java/com/google/common/collect/AbstractMapBasedMultiset.java +++ b/src/main/java/com/google/common/collect/AbstractMapBasedMultiset.java @@ -48,112 +48,6 @@ import com.google.common.primitives.Ints; @GwtCompatible(emulated = true) abstract class AbstractMapBasedMultiset extends AbstractMultiset implements Serializable { - private transient Map backingMap; - - /* - * Cache the size for efficiency. Using a long lets us avoid the need for - * overflow checking and ensures that size() will function correctly even if the - * multiset had once been larger than Integer.MAX_VALUE. - */ - private transient long size; - - /** Standard constructor. */ - protected AbstractMapBasedMultiset(Map backingMap) { - this.backingMap = checkNotNull(backingMap); - this.size = super.size(); - } - - /** Used during deserialization only. The backing map must be empty. */ - void setBackingMap(Map backingMap) { - this.backingMap = backingMap; - } - - // Required Implementations - - /** - * {@inheritDoc} - * - *

- * Invoking {@link Multiset.Entry#getCount} on an entry in the returned set - * always returns the current count of that element in the multiset, as opposed - * to the count at the time the entry was retrieved. - */ - @Override - public Set> entrySet() { - return super.entrySet(); - } - - @Override - Iterator> entryIterator() { - final Iterator> backingEntries = backingMap.entrySet().iterator(); - return new Iterator>() { - Map.Entry toRemove; - - @Override - public boolean hasNext() { - return backingEntries.hasNext(); - } - - @Override - public Multiset.Entry next() { - final Map.Entry mapEntry = backingEntries.next(); - toRemove = mapEntry; - return new Multisets.AbstractEntry() { - @Override - public E getElement() { - return mapEntry.getKey(); - } - - @Override - public int getCount() { - Count count = mapEntry.getValue(); - if (count == null || count.get() == 0) { - Count frequency = backingMap.get(getElement()); - if (frequency != null) { - return frequency.get(); - } - } - return (count == null) ? 0 : count.get(); - } - }; - } - - @Override - public void remove() { - checkRemove(toRemove != null); - size -= toRemove.getValue().getAndSet(0); - backingEntries.remove(); - toRemove = null; - } - }; - } - - @Override - public void clear() { - for (Count frequency : backingMap.values()) { - frequency.set(0); - } - backingMap.clear(); - size = 0L; - } - - @Override - int distinctElements() { - return backingMap.size(); - } - - // Optimizations - Query Operations - - @Override - public int size() { - return Ints.saturatedCast(size); - } - - @Override - public Iterator iterator() { - return new MapBasedMultisetIterator(); - } - /* * Not subclassing AbstractMultiset$MultisetIterator because next() needs to * retrieve the Map.Entry entry, which can then be used for a more @@ -200,13 +94,33 @@ abstract class AbstractMapBasedMultiset extends AbstractMultiset implement } } - @Override - public int count(@Nullable Object element) { - Count frequency = Maps.safeGet(backingMap, element); - return (frequency == null) ? 0 : frequency.get(); + @GwtIncompatible("not needed in emulated source.") + private static final long serialVersionUID = -2250766705698539974L; + + private static int getAndSet(Count i, int count) { + if (i == null) { + return 0; + } + + return i.getAndSet(count); } - // Optional Operations - Modification Operations + private transient Map backingMap; + + // Required Implementations + + /* + * Cache the size for efficiency. Using a long lets us avoid the need for + * overflow checking and ensures that size() will function correctly even if the + * multiset had once been larger than Integer.MAX_VALUE. + */ + private transient long size; + + /** Standard constructor. */ + protected AbstractMapBasedMultiset(Map backingMap) { + this.backingMap = checkNotNull(backingMap); + this.size = super.size(); + } /** * {@inheritDoc} @@ -236,6 +150,100 @@ abstract class AbstractMapBasedMultiset extends AbstractMultiset implement return oldCount; } + @Override + public void clear() { + for (Count frequency : backingMap.values()) { + frequency.set(0); + } + backingMap.clear(); + size = 0L; + } + + // Optimizations - Query Operations + + @Override + public int count(@Nullable Object element) { + Count frequency = Maps.safeGet(backingMap, element); + return (frequency == null) ? 0 : frequency.get(); + } + + @Override + int distinctElements() { + return backingMap.size(); + } + + @Override + Iterator> entryIterator() { + final Iterator> backingEntries = backingMap.entrySet().iterator(); + return new Iterator>() { + Map.Entry toRemove; + + @Override + public boolean hasNext() { + return backingEntries.hasNext(); + } + + @Override + public Multiset.Entry next() { + final Map.Entry mapEntry = backingEntries.next(); + toRemove = mapEntry; + return new Multisets.AbstractEntry() { + @Override + public int getCount() { + Count count = mapEntry.getValue(); + if (count == null || count.get() == 0) { + Count frequency = backingMap.get(getElement()); + if (frequency != null) { + return frequency.get(); + } + } + return (count == null) ? 0 : count.get(); + } + + @Override + public E getElement() { + return mapEntry.getKey(); + } + }; + } + + @Override + public void remove() { + checkRemove(toRemove != null); + size -= toRemove.getValue().getAndSet(0); + backingEntries.remove(); + toRemove = null; + } + }; + } + + /** + * {@inheritDoc} + * + *

+ * Invoking {@link Multiset.Entry#getCount} on an entry in the returned set + * always returns the current count of that element in the multiset, as opposed + * to the count at the time the entry was retrieved. + */ + @Override + public Set> entrySet() { + return super.entrySet(); + } + + // Optional Operations - Modification Operations + + @Override + public Iterator iterator() { + return new MapBasedMultisetIterator(); + } + + // Don't allow default serialization. + @GwtIncompatible("java.io.ObjectStreamException") + @SuppressWarnings("unused") // actually used during deserialization + private void readObjectNoData() throws ObjectStreamException { + throw new InvalidObjectException("Stream data required"); + } + @Override public int remove(@Nullable Object element, int occurrences) { if (occurrences == 0) { @@ -262,6 +270,11 @@ abstract class AbstractMapBasedMultiset extends AbstractMultiset implement return oldCount; } + /** Used during deserialization only. The backing map must be empty. */ + void setBackingMap(Map backingMap) { + this.backingMap = backingMap; + } + // Roughly a 33% performance improvement over AbstractMultiset.setCount(). @Override public int setCount(@Nullable E element, int count) { @@ -285,21 +298,8 @@ abstract class AbstractMapBasedMultiset extends AbstractMultiset implement return oldCount; } - private static int getAndSet(Count i, int count) { - if (i == null) { - return 0; - } - - return i.getAndSet(count); + @Override + public int size() { + return Ints.saturatedCast(size); } - - // Don't allow default serialization. - @GwtIncompatible("java.io.ObjectStreamException") - @SuppressWarnings("unused") // actually used during deserialization - private void readObjectNoData() throws ObjectStreamException { - throw new InvalidObjectException("Stream data required"); - } - - @GwtIncompatible("not needed in emulated source.") - private static final long serialVersionUID = -2250766705698539974L; } diff --git a/src/main/java/com/google/common/collect/AbstractMapEntry.java b/src/main/java/com/google/common/collect/AbstractMapEntry.java index 3cf53092..40e6ec51 100644 --- a/src/main/java/com/google/common/collect/AbstractMapEntry.java +++ b/src/main/java/com/google/common/collect/AbstractMapEntry.java @@ -32,17 +32,6 @@ import com.google.common.base.Objects; @GwtCompatible abstract class AbstractMapEntry implements Entry { - @Override - public abstract K getKey(); - - @Override - public abstract V getValue(); - - @Override - public V setValue(V value) { - throw new UnsupportedOperationException(); - } - @Override public boolean equals(@Nullable Object object) { if (object instanceof Entry) { @@ -52,6 +41,12 @@ abstract class AbstractMapEntry implements Entry { return false; } + @Override + public abstract K getKey(); + + @Override + public abstract V getValue(); + @Override public int hashCode() { K k = getKey(); @@ -59,6 +54,11 @@ abstract class AbstractMapEntry implements Entry { return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } + @Override + public V setValue(V value) { + throw new UnsupportedOperationException(); + } + /** * Returns a string representation of the form {@code {key}={value}}. */ diff --git a/src/main/java/com/google/common/collect/AbstractMultimap.java b/src/main/java/com/google/common/collect/AbstractMultimap.java index 1231e4df..2520a749 100644 --- a/src/main/java/com/google/common/collect/AbstractMultimap.java +++ b/src/main/java/com/google/common/collect/AbstractMultimap.java @@ -37,9 +37,72 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible abstract class AbstractMultimap implements Multimap { + private class Entries extends Multimaps.Entries { + @Override + public Iterator> iterator() { + return entryIterator(); + } + + @Override + Multimap multimap() { + return AbstractMultimap.this; + } + } + + private class EntrySet extends Entries implements Set> { + @Override + public boolean equals(@Nullable Object obj) { + return Sets.equalsImpl(this, obj); + } + + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); + } + } + + class Values extends AbstractCollection { + @Override + public void clear() { + AbstractMultimap.this.clear(); + } + + @Override + public boolean contains(@Nullable Object o) { + return AbstractMultimap.this.containsValue(o); + } + + @Override + public Iterator iterator() { + return valueIterator(); + } + + @Override + public int size() { + return AbstractMultimap.this.size(); + } + } + + private transient Collection> entries; + + private transient Set keySet; + + private transient Multiset keys; + + private transient Collection values; + + private transient Map> asMap; + @Override - public boolean isEmpty() { - return size() == 0; + public Map> asMap() { + Map> result = asMap; + return (result == null) ? asMap = createAsMap() : result; + } + + @Override + public boolean containsEntry(@Nullable Object key, @Nullable Object value) { + Collection collection = asMap().get(key); + return collection != null && collection.contains(value); } @Override @@ -53,16 +116,70 @@ abstract class AbstractMultimap implements Multimap { return false; } - @Override - public boolean containsEntry(@Nullable Object key, @Nullable Object value) { - Collection collection = asMap().get(key); - return collection != null && collection.contains(value); + abstract Map> createAsMap(); + + Collection> createEntries() { + if (this instanceof SetMultimap) { + return new EntrySet(); + } else { + return new Entries(); + } + } + + Multiset createKeys() { + return new Multimaps.Keys(this); + } + + Set createKeySet() { + return new Maps.KeySet>(asMap()); + } + + Collection createValues() { + return new Values(); } @Override - public boolean remove(@Nullable Object key, @Nullable Object value) { - Collection collection = asMap().get(key); - return collection != null && collection.remove(value); + public Collection> entries() { + Collection> result = entries; + return (result == null) ? entries = createEntries() : result; + } + + abstract Iterator> entryIterator(); + + @Override + public boolean equals(@Nullable Object object) { + return Multimaps.equalsImpl(this, object); + } + + /** + * Returns the hash code for this multimap. + * + *

+ * The hash code of a multimap is defined as the hash code of the map view, as + * returned by {@link Multimap#asMap}. + * + * @see Map#hashCode + */ + @Override + public int hashCode() { + return asMap().hashCode(); + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Override + public Multiset keys() { + Multiset result = keys; + return (result == null) ? keys = createKeys() : result; + } + + @Override + public Set keySet() { + Set result = keySet; + return (result == null) ? keySet = createKeySet() : result; } @Override @@ -93,6 +210,12 @@ abstract class AbstractMultimap implements Multimap { return changed; } + @Override + public boolean remove(@Nullable Object key, @Nullable Object value) { + Collection collection = asMap().get(key); + return collection != null && collection.remove(value); + } + @Override public Collection replaceValues(@Nullable K key, Iterable values) { checkNotNull(values); @@ -101,141 +224,8 @@ abstract class AbstractMultimap implements Multimap { return result; } - private transient Collection> entries; - - @Override - public Collection> entries() { - Collection> result = entries; - return (result == null) ? entries = createEntries() : result; - } - - Collection> createEntries() { - if (this instanceof SetMultimap) { - return new EntrySet(); - } else { - return new Entries(); - } - } - - private class Entries extends Multimaps.Entries { - @Override - Multimap multimap() { - return AbstractMultimap.this; - } - - @Override - public Iterator> iterator() { - return entryIterator(); - } - } - - private class EntrySet extends Entries implements Set> { - @Override - public int hashCode() { - return Sets.hashCodeImpl(this); - } - - @Override - public boolean equals(@Nullable Object obj) { - return Sets.equalsImpl(this, obj); - } - } - - abstract Iterator> entryIterator(); - - private transient Set keySet; - - @Override - public Set keySet() { - Set result = keySet; - return (result == null) ? keySet = createKeySet() : result; - } - - Set createKeySet() { - return new Maps.KeySet>(asMap()); - } - - private transient Multiset keys; - - @Override - public Multiset keys() { - Multiset result = keys; - return (result == null) ? keys = createKeys() : result; - } - - Multiset createKeys() { - return new Multimaps.Keys(this); - } - - private transient Collection values; - - @Override - public Collection values() { - Collection result = values; - return (result == null) ? values = createValues() : result; - } - - Collection createValues() { - return new Values(); - } - - class Values extends AbstractCollection { - @Override - public Iterator iterator() { - return valueIterator(); - } - - @Override - public int size() { - return AbstractMultimap.this.size(); - } - - @Override - public boolean contains(@Nullable Object o) { - return AbstractMultimap.this.containsValue(o); - } - - @Override - public void clear() { - AbstractMultimap.this.clear(); - } - } - - Iterator valueIterator() { - return Maps.valueIterator(entries().iterator()); - } - - private transient Map> asMap; - - @Override - public Map> asMap() { - Map> result = asMap; - return (result == null) ? asMap = createAsMap() : result; - } - - abstract Map> createAsMap(); - // Comparison and hashing - @Override - public boolean equals(@Nullable Object object) { - return Multimaps.equalsImpl(this, object); - } - - /** - * Returns the hash code for this multimap. - * - *

- * The hash code of a multimap is defined as the hash code of the map view, as - * returned by {@link Multimap#asMap}. - * - * @see Map#hashCode - */ - @Override - public int hashCode() { - return asMap().hashCode(); - } - /** * Returns a string representation of the multimap, generated by calling * {@code toString} on the map returned by {@link Multimap#asMap}. @@ -246,4 +236,14 @@ abstract class AbstractMultimap implements Multimap { public String toString() { return asMap().toString(); } + + Iterator valueIterator() { + return Maps.valueIterator(entries().iterator()); + } + + @Override + public Collection values() { + Collection result = values; + return (result == null) ? values = createValues() : result; + } } diff --git a/src/main/java/com/google/common/collect/AbstractMultiset.java b/src/main/java/com/google/common/collect/AbstractMultiset.java index 0af64f4e..543f3715 100644 --- a/src/main/java/com/google/common/collect/AbstractMultiset.java +++ b/src/main/java/com/google/common/collect/AbstractMultiset.java @@ -48,37 +48,33 @@ import com.google.common.base.Objects; abstract class AbstractMultiset extends AbstractCollection implements Multiset { // Query Operations - @Override - public int size() { - return Multisets.sizeImpl(this); - } - - @Override - public boolean isEmpty() { - return entrySet().isEmpty(); - } - - @Override - public boolean contains(@Nullable Object element) { - return count(element) > 0; - } - - @Override - public Iterator iterator() { - return Multisets.iteratorImpl(this); - } - - @Override - public int count(@Nullable Object element) { - for (Entry entry : entrySet()) { - if (Objects.equal(entry.getElement(), element)) { - return entry.getCount(); - } + class ElementSet extends Multisets.ElementSet { + @Override + Multiset multiset() { + return AbstractMultiset.this; } - return 0; } - // Modification Operations + class EntrySet extends Multisets.EntrySet { + @Override + public Iterator> iterator() { + return entryIterator(); + } + + @Override + Multiset multiset() { + return AbstractMultiset.this; + } + + @Override + public int size() { + return distinctElements(); + } + } + + private transient Set elementSet; + + private transient Set> entrySet; @Override public boolean add(@Nullable E element) { @@ -86,33 +82,13 @@ abstract class AbstractMultiset extends AbstractCollection implements Mult return true; } + // Modification Operations + @Override public int add(@Nullable E element, int occurrences) { throw new UnsupportedOperationException(); } - @Override - public boolean remove(@Nullable Object element) { - return remove(element, 1) > 0; - } - - @Override - public int remove(@Nullable Object element, int occurrences) { - throw new UnsupportedOperationException(); - } - - @Override - public int setCount(@Nullable E element, int count) { - return setCountImpl(this, element, count); - } - - @Override - public boolean setCount(@Nullable E element, int oldCount, int newCount) { - return setCountImpl(this, element, oldCount, newCount); - } - - // Bulk Operations - /** * {@inheritDoc} * @@ -125,32 +101,24 @@ abstract class AbstractMultiset extends AbstractCollection implements Mult return Multisets.addAllImpl(this, elementsToAdd); } - @Override - public boolean removeAll(Collection elementsToRemove) { - return Multisets.removeAllImpl(this, elementsToRemove); - } - - @Override - public boolean retainAll(Collection elementsToRetain) { - return Multisets.retainAllImpl(this, elementsToRetain); - } - @Override public void clear() { Iterators.clear(entryIterator()); } - // Views - - private transient Set elementSet; + @Override + public boolean contains(@Nullable Object element) { + return count(element) > 0; + } @Override - public Set elementSet() { - Set result = elementSet; - if (result == null) { - elementSet = result = createElementSet(); + public int count(@Nullable Object element) { + for (Entry entry : entrySet()) { + if (Objects.equal(entry.getElement(), element)) { + return entry.getCount(); + } } - return result; + return 0; } /** @@ -161,18 +129,26 @@ abstract class AbstractMultiset extends AbstractCollection implements Mult return new ElementSet(); } - class ElementSet extends Multisets.ElementSet { - @Override - Multiset multiset() { - return AbstractMultiset.this; + // Bulk Operations + + Set> createEntrySet() { + return new EntrySet(); + } + + abstract int distinctElements(); + + @Override + public Set elementSet() { + Set result = elementSet; + if (result == null) { + elementSet = result = createElementSet(); } + return result; } abstract Iterator> entryIterator(); - abstract int distinctElements(); - - private transient Set> entrySet; + // Views @Override public Set> entrySet() { @@ -180,29 +156,6 @@ abstract class AbstractMultiset extends AbstractCollection implements Mult return (result == null) ? entrySet = createEntrySet() : result; } - class EntrySet extends Multisets.EntrySet { - @Override - Multiset multiset() { - return AbstractMultiset.this; - } - - @Override - public Iterator> iterator() { - return entryIterator(); - } - - @Override - public int size() { - return distinctElements(); - } - } - - Set> createEntrySet() { - return new EntrySet(); - } - - // Object methods - /** * {@inheritDoc} * @@ -227,6 +180,53 @@ abstract class AbstractMultiset extends AbstractCollection implements Mult return entrySet().hashCode(); } + @Override + public boolean isEmpty() { + return entrySet().isEmpty(); + } + + @Override + public Iterator iterator() { + return Multisets.iteratorImpl(this); + } + + @Override + public boolean remove(@Nullable Object element) { + return remove(element, 1) > 0; + } + + @Override + public int remove(@Nullable Object element, int occurrences) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean removeAll(Collection elementsToRemove) { + return Multisets.removeAllImpl(this, elementsToRemove); + } + + @Override + public boolean retainAll(Collection elementsToRetain) { + return Multisets.retainAllImpl(this, elementsToRetain); + } + + @Override + public int setCount(@Nullable E element, int count) { + return setCountImpl(this, element, count); + } + + // Object methods + + @Override + public boolean setCount(@Nullable E element, int oldCount, int newCount) { + return setCountImpl(this, element, oldCount, newCount); + } + + @Override + public int size() { + return Multisets.sizeImpl(this); + } + /** * {@inheritDoc} * diff --git a/src/main/java/com/google/common/collect/AbstractNavigableMap.java b/src/main/java/com/google/common/collect/AbstractNavigableMap.java index 753f92d3..9955ee7a 100644 --- a/src/main/java/com/google/common/collect/AbstractNavigableMap.java +++ b/src/main/java/com/google/common/collect/AbstractNavigableMap.java @@ -34,9 +34,57 @@ import javax.annotation.Nullable; */ abstract class AbstractNavigableMap extends AbstractMap implements NavigableMap { + private final class DescendingMap extends Maps.DescendingMap { + @Override + Iterator> entryIterator() { + return descendingEntryIterator(); + } + + @Override + NavigableMap forward() { + return AbstractNavigableMap.this; + } + } + @Override @Nullable - public abstract V get(@Nullable Object key); + public Entry ceilingEntry(K key) { + return tailMap(key, true).firstEntry(); + } + + @Override + public K ceilingKey(K key) { + return Maps.keyOrNull(ceilingEntry(key)); + } + + abstract Iterator> descendingEntryIterator(); + + @Override + public NavigableSet descendingKeySet() { + return descendingMap().navigableKeySet(); + } + + @Override + public NavigableMap descendingMap() { + return new DescendingMap(); + } + + abstract Iterator> entryIterator(); + + @Override + public Set> entrySet() { + return new Maps.EntrySet() { + @Override + public Iterator> iterator() { + return entryIterator(); + } + + @Override + Map map() { + return AbstractNavigableMap.this; + } + }; + } @Override @Nullable @@ -44,24 +92,6 @@ abstract class AbstractNavigableMap extends AbstractMap implements N return Iterators.getNext(entryIterator(), null); } - @Override - @Nullable - public Entry lastEntry() { - return Iterators.getNext(descendingEntryIterator(), null); - } - - @Override - @Nullable - public Entry pollFirstEntry() { - return Iterators.pollNext(entryIterator()); - } - - @Override - @Nullable - public Entry pollLastEntry() { - return Iterators.pollNext(descendingEntryIterator()); - } - @Override public K firstKey() { Entry entry = firstEntry(); @@ -72,6 +102,48 @@ abstract class AbstractNavigableMap extends AbstractMap implements N } } + @Override + @Nullable + public Entry floorEntry(K key) { + return headMap(key, true).lastEntry(); + } + + @Override + public K floorKey(K key) { + return Maps.keyOrNull(floorEntry(key)); + } + + @Override + @Nullable + public abstract V get(@Nullable Object key); + + @Override + public SortedMap headMap(K toKey) { + return headMap(toKey, false); + } + + @Override + @Nullable + public Entry higherEntry(K key) { + return tailMap(key, false).firstEntry(); + } + + @Override + public K higherKey(K key) { + return Maps.keyOrNull(higherEntry(key)); + } + + @Override + public Set keySet() { + return navigableKeySet(); + } + + @Override + @Nullable + public Entry lastEntry() { + return Iterators.getNext(descendingEntryIterator(), null); + } + @Override public K lastKey() { Entry entry = lastEntry(); @@ -88,111 +160,39 @@ abstract class AbstractNavigableMap extends AbstractMap implements N return headMap(key, false).lastEntry(); } - @Override - @Nullable - public Entry floorEntry(K key) { - return headMap(key, true).lastEntry(); - } - - @Override - @Nullable - public Entry ceilingEntry(K key) { - return tailMap(key, true).firstEntry(); - } - - @Override - @Nullable - public Entry higherEntry(K key) { - return tailMap(key, false).firstEntry(); - } - @Override public K lowerKey(K key) { return Maps.keyOrNull(lowerEntry(key)); } - @Override - public K floorKey(K key) { - return Maps.keyOrNull(floorEntry(key)); - } - - @Override - public K ceilingKey(K key) { - return Maps.keyOrNull(ceilingEntry(key)); - } - - @Override - public K higherKey(K key) { - return Maps.keyOrNull(higherEntry(key)); - } - - abstract Iterator> entryIterator(); - - abstract Iterator> descendingEntryIterator(); - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); - } - - @Override - public SortedMap headMap(K toKey) { - return headMap(toKey, false); - } - - @Override - public SortedMap tailMap(K fromKey) { - return tailMap(fromKey, true); - } - @Override public NavigableSet navigableKeySet() { return new Maps.NavigableKeySet(this); } @Override - public Set keySet() { - return navigableKeySet(); + @Nullable + public Entry pollFirstEntry() { + return Iterators.pollNext(entryIterator()); + } + + @Override + @Nullable + public Entry pollLastEntry() { + return Iterators.pollNext(descendingEntryIterator()); } @Override public abstract int size(); @Override - public Set> entrySet() { - return new Maps.EntrySet() { - @Override - Map map() { - return AbstractNavigableMap.this; - } - - @Override - public Iterator> iterator() { - return entryIterator(); - } - }; + public SortedMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); } @Override - public NavigableSet descendingKeySet() { - return descendingMap().navigableKeySet(); - } - - @Override - public NavigableMap descendingMap() { - return new DescendingMap(); - } - - private final class DescendingMap extends Maps.DescendingMap { - @Override - NavigableMap forward() { - return AbstractNavigableMap.this; - } - - @Override - Iterator> entryIterator() { - return descendingEntryIterator(); - } + public SortedMap tailMap(K fromKey) { + return tailMap(fromKey, true); } } diff --git a/src/main/java/com/google/common/collect/AbstractRangeSet.java b/src/main/java/com/google/common/collect/AbstractRangeSet.java index e8fc0156..fe5f67be 100644 --- a/src/main/java/com/google/common/collect/AbstractRangeSet.java +++ b/src/main/java/com/google/common/collect/AbstractRangeSet.java @@ -25,44 +25,11 @@ abstract class AbstractRangeSet implements RangeSet { AbstractRangeSet() { } - @Override - public boolean contains(C value) { - return rangeContaining(value) != null; - } - - @Override - public abstract Range rangeContaining(C value); - - @Override - public boolean isEmpty() { - return asRanges().isEmpty(); - } - @Override public void add(Range range) { throw new UnsupportedOperationException(); } - @Override - public void remove(Range range) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - remove(Range.all()); - } - - @Override - public boolean enclosesAll(RangeSet other) { - for (Range range : other.asRanges()) { - if (!encloses(range)) { - return false; - } - } - return true; - } - @Override public void addAll(RangeSet other) { for (Range range : other.asRanges()) { @@ -71,15 +38,28 @@ abstract class AbstractRangeSet implements RangeSet { } @Override - public void removeAll(RangeSet other) { - for (Range range : other.asRanges()) { - remove(range); - } + public void clear() { + remove(Range.all()); + } + + @Override + public boolean contains(C value) { + return rangeContaining(value) != null; } @Override public abstract boolean encloses(Range otherRange); + @Override + public boolean enclosesAll(RangeSet other) { + for (Range range : other.asRanges()) { + if (!encloses(range)) { + return false; + } + } + return true; + } + @Override public boolean equals(@Nullable Object obj) { if (obj == this) { @@ -96,6 +76,26 @@ abstract class AbstractRangeSet implements RangeSet { return asRanges().hashCode(); } + @Override + public boolean isEmpty() { + return asRanges().isEmpty(); + } + + @Override + public abstract Range rangeContaining(C value); + + @Override + public void remove(Range range) { + throw new UnsupportedOperationException(); + } + + @Override + public void removeAll(RangeSet other) { + for (Range range : other.asRanges()) { + remove(range); + } + } + @Override public final String toString() { return asRanges().toString(); diff --git a/src/main/java/com/google/common/collect/AbstractSetMultimap.java b/src/main/java/com/google/common/collect/AbstractSetMultimap.java index fd072642..49c1fdea 100644 --- a/src/main/java/com/google/common/collect/AbstractSetMultimap.java +++ b/src/main/java/com/google/common/collect/AbstractSetMultimap.java @@ -34,6 +34,8 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible abstract class AbstractSetMultimap extends AbstractMapBasedMultimap implements SetMultimap { + private static final long serialVersionUID = 7431625294878419160L; + /** * Creates a new multimap that uses the provided map. * @@ -44,6 +46,20 @@ abstract class AbstractSetMultimap extends AbstractMapBasedMultimap super(map); } + /** + * {@inheritDoc} + * + *

+ * Though the method signature doesn't say so explicitly, the returned map has + * {@link Set} values. + */ + @Override + public Map> asMap() { + return super.asMap(); + } + + // Following Javadoc copied from SetMultimap. + @Override abstract Set createCollection(); @@ -52,7 +68,30 @@ abstract class AbstractSetMultimap extends AbstractMapBasedMultimap return ImmutableSet.of(); } - // Following Javadoc copied from SetMultimap. + /** + * {@inheritDoc} + * + *

+ * Because a {@code SetMultimap} has unique values for a given key, this method + * returns a {@link Set}, instead of the {@link Collection} specified in the + * {@link Multimap} interface. + */ + @Override + public Set> entries() { + return (Set>) super.entries(); + } + + /** + * Compares the specified object to this multimap for equality. + * + *

+ * Two {@code SetMultimap} instances are equal if, for each key, they contain + * the same values. Equality does not depend on the ordering of keys or values. + */ + @Override + public boolean equals(@Nullable Object object) { + return super.equals(object); + } /** * {@inheritDoc} @@ -68,16 +107,16 @@ abstract class AbstractSetMultimap extends AbstractMapBasedMultimap } /** - * {@inheritDoc} + * Stores a key-value pair in the multimap. * - *

- * Because a {@code SetMultimap} has unique values for a given key, this method - * returns a {@link Set}, instead of the {@link Collection} specified in the - * {@link Multimap} interface. + * @param key key to store in the multimap + * @param value value to store in the multimap + * @return {@code true} if the method increased the size of the multimap, or + * {@code false} if the multimap already contained the key-value pair */ @Override - public Set> entries() { - return (Set>) super.entries(); + public boolean put(@Nullable K key, @Nullable V value) { + return super.put(key, value); } /** @@ -108,43 +147,4 @@ abstract class AbstractSetMultimap extends AbstractMapBasedMultimap public Set replaceValues(@Nullable K key, Iterable values) { return (Set) super.replaceValues(key, values); } - - /** - * {@inheritDoc} - * - *

- * Though the method signature doesn't say so explicitly, the returned map has - * {@link Set} values. - */ - @Override - public Map> asMap() { - return super.asMap(); - } - - /** - * Stores a key-value pair in the multimap. - * - * @param key key to store in the multimap - * @param value value to store in the multimap - * @return {@code true} if the method increased the size of the multimap, or - * {@code false} if the multimap already contained the key-value pair - */ - @Override - public boolean put(@Nullable K key, @Nullable V value) { - return super.put(key, value); - } - - /** - * Compares the specified object to this multimap for equality. - * - *

- * Two {@code SetMultimap} instances are equal if, for each key, they contain - * the same values. Equality does not depend on the ordering of keys or values. - */ - @Override - public boolean equals(@Nullable Object object) { - return super.equals(object); - } - - private static final long serialVersionUID = 7431625294878419160L; } diff --git a/src/main/java/com/google/common/collect/AbstractSortedMultiset.java b/src/main/java/com/google/common/collect/AbstractSortedMultiset.java index 4f666890..d1fafd89 100644 --- a/src/main/java/com/google/common/collect/AbstractSortedMultiset.java +++ b/src/main/java/com/google/common/collect/AbstractSortedMultiset.java @@ -41,6 +41,8 @@ abstract class AbstractSortedMultiset extends AbstractMultiset implements @GwtTransient final Comparator comparator; + private transient SortedMultiset descendingMultiset; + // needed for serialization @SuppressWarnings("unchecked") AbstractSortedMultiset() { @@ -52,8 +54,27 @@ abstract class AbstractSortedMultiset extends AbstractMultiset implements } @Override - public NavigableSet elementSet() { - return (NavigableSet) super.elementSet(); + public Comparator comparator() { + return comparator; + } + + SortedMultiset createDescendingMultiset() { + return new DescendingMultiset() { + @Override + Iterator> entryIterator() { + return descendingEntryIterator(); + } + + @Override + SortedMultiset forwardMultiset() { + return AbstractSortedMultiset.this; + } + + @Override + public Iterator iterator() { + return descendingIterator(); + } + }; } @Override @@ -61,9 +82,21 @@ abstract class AbstractSortedMultiset extends AbstractMultiset implements return new SortedMultisets.NavigableElementSet(this); } + abstract Iterator> descendingEntryIterator(); + + Iterator descendingIterator() { + return Multisets.iteratorImpl(descendingMultiset()); + } + @Override - public Comparator comparator() { - return comparator; + public SortedMultiset descendingMultiset() { + SortedMultiset result = descendingMultiset; + return (result == null) ? descendingMultiset = createDescendingMultiset() : result; + } + + @Override + public NavigableSet elementSet() { + return (NavigableSet) super.elementSet(); } @Override @@ -111,37 +144,4 @@ abstract class AbstractSortedMultiset extends AbstractMultiset implements checkNotNull(toBoundType); return tailMultiset(fromElement, fromBoundType).headMultiset(toElement, toBoundType); } - - abstract Iterator> descendingEntryIterator(); - - Iterator descendingIterator() { - return Multisets.iteratorImpl(descendingMultiset()); - } - - private transient SortedMultiset descendingMultiset; - - @Override - public SortedMultiset descendingMultiset() { - SortedMultiset result = descendingMultiset; - return (result == null) ? descendingMultiset = createDescendingMultiset() : result; - } - - SortedMultiset createDescendingMultiset() { - return new DescendingMultiset() { - @Override - SortedMultiset forwardMultiset() { - return AbstractSortedMultiset.this; - } - - @Override - Iterator> entryIterator() { - return descendingEntryIterator(); - } - - @Override - public Iterator iterator() { - return descendingIterator(); - } - }; - } } diff --git a/src/main/java/com/google/common/collect/AbstractSortedSetMultimap.java b/src/main/java/com/google/common/collect/AbstractSortedSetMultimap.java index 52a2217d..dd21ebbe 100644 --- a/src/main/java/com/google/common/collect/AbstractSortedSetMultimap.java +++ b/src/main/java/com/google/common/collect/AbstractSortedSetMultimap.java @@ -36,6 +36,8 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible abstract class AbstractSortedSetMultimap extends AbstractSetMultimap implements SortedSetMultimap { + private static final long serialVersionUID = 430848587173315748L; + /** * Creates a new multimap that uses the provided map. * @@ -46,6 +48,29 @@ abstract class AbstractSortedSetMultimap extends AbstractSetMultimap super(map); } + /** + * Returns a map view that associates each key with the corresponding values in + * the multimap. Changes to the returned map, such as element removal, will + * update the underlying multimap. The map does not support {@code setValue} on + * its entries, {@code put}, or {@code putAll}. + * + *

+ * When passed a key that is present in the map, {@code + * asMap().get(Object)} has the same behavior as {@link #get}, returning a live + * collection. When passed a key that is not present, however, {@code + * asMap().get(Object)} returns {@code null} instead of an empty collection. + * + *

+ * Though the method signature doesn't say so explicitly, the returned map has + * {@link SortedSet} values. + */ + @Override + public Map> asMap() { + return super.asMap(); + } + + // Following Javadoc copied from Multimap and SortedSetMultimap. + @Override abstract SortedSet createCollection(); @@ -59,8 +84,6 @@ abstract class AbstractSortedSetMultimap extends AbstractSetMultimap } } - // Following Javadoc copied from Multimap and SortedSetMultimap. - /** * Returns a collection view of all values associated with a key. If no mappings * in the multimap have the provided key, an empty collection is returned. @@ -110,27 +133,6 @@ abstract class AbstractSortedSetMultimap extends AbstractSetMultimap return (SortedSet) super.replaceValues(key, values); } - /** - * Returns a map view that associates each key with the corresponding values in - * the multimap. Changes to the returned map, such as element removal, will - * update the underlying multimap. The map does not support {@code setValue} on - * its entries, {@code put}, or {@code putAll}. - * - *

- * When passed a key that is present in the map, {@code - * asMap().get(Object)} has the same behavior as {@link #get}, returning a live - * collection. When passed a key that is not present, however, {@code - * asMap().get(Object)} returns {@code null} instead of an empty collection. - * - *

- * Though the method signature doesn't say so explicitly, the returned map has - * {@link SortedSet} values. - */ - @Override - public Map> asMap() { - return super.asMap(); - } - /** * {@inheritDoc} * @@ -141,6 +143,4 @@ abstract class AbstractSortedSetMultimap extends AbstractSetMultimap public Collection values() { return super.values(); } - - private static final long serialVersionUID = 430848587173315748L; } diff --git a/src/main/java/com/google/common/collect/AbstractTable.java b/src/main/java/com/google/common/collect/AbstractTable.java index b7a6d2cd..063c9886 100644 --- a/src/main/java/com/google/common/collect/AbstractTable.java +++ b/src/main/java/com/google/common/collect/AbstractTable.java @@ -34,91 +34,12 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible abstract class AbstractTable implements Table { - @Override - public boolean containsRow(@Nullable Object rowKey) { - return Maps.safeContainsKey(rowMap(), rowKey); - } - - @Override - public boolean containsColumn(@Nullable Object columnKey) { - return Maps.safeContainsKey(columnMap(), columnKey); - } - - @Override - public Set rowKeySet() { - return rowMap().keySet(); - } - - @Override - public Set columnKeySet() { - return columnMap().keySet(); - } - - @Override - public boolean containsValue(@Nullable Object value) { - for (Map row : rowMap().values()) { - if (row.containsValue(value)) { - return true; - } - } - return false; - } - - @Override - public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { - Map row = Maps.safeGet(rowMap(), rowKey); - return row != null && Maps.safeContainsKey(row, columnKey); - } - - @Override - public V get(@Nullable Object rowKey, @Nullable Object columnKey) { - Map row = Maps.safeGet(rowMap(), rowKey); - return (row == null) ? null : Maps.safeGet(row, columnKey); - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public void clear() { - Iterators.clear(cellSet().iterator()); - } - - @Override - public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { - Map row = Maps.safeGet(rowMap(), rowKey); - return (row == null) ? null : Maps.safeRemove(row, columnKey); - } - - @Override - public V put(R rowKey, C columnKey, V value) { - return row(rowKey).put(columnKey, value); - } - - @Override - public void putAll(Table table) { - for (Table.Cell cell : table.cellSet()) { - put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); - } - } - - private transient Set> cellSet; - - @Override - public Set> cellSet() { - Set> result = cellSet; - return (result == null) ? cellSet = createCellSet() : result; - } - - Set> createCellSet() { - return new CellSet(); - } - - abstract Iterator> cellIterator(); - class CellSet extends AbstractSet> { + @Override + public void clear() { + AbstractTable.this.clear(); + } + @Override public boolean contains(Object o) { if (o instanceof Cell) { @@ -130,6 +51,11 @@ abstract class AbstractTable implements Table { return false; } + @Override + public Iterator> iterator() { + return cellIterator(); + } + @Override public boolean remove(@Nullable Object o) { if (o instanceof Cell) { @@ -141,14 +67,26 @@ abstract class AbstractTable implements Table { return false; } + @Override + public int size() { + return AbstractTable.this.size(); + } + } + + class Values extends AbstractCollection { @Override public void clear() { AbstractTable.this.clear(); } @Override - public Iterator> iterator() { - return cellIterator(); + public boolean contains(Object o) { + return containsValue(o); + } + + @Override + public Iterator iterator() { + return valuesIterator(); } @Override @@ -157,18 +95,120 @@ abstract class AbstractTable implements Table { } } + private transient Set> cellSet; + private transient Collection values; + abstract Iterator> cellIterator(); + + @Override + public Set> cellSet() { + Set> result = cellSet; + return (result == null) ? cellSet = createCellSet() : result; + } + + @Override + public void clear() { + Iterators.clear(cellSet().iterator()); + } + + @Override + public Set columnKeySet() { + return columnMap().keySet(); + } + + @Override + public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { + Map row = Maps.safeGet(rowMap(), rowKey); + return row != null && Maps.safeContainsKey(row, columnKey); + } + + @Override + public boolean containsColumn(@Nullable Object columnKey) { + return Maps.safeContainsKey(columnMap(), columnKey); + } + + @Override + public boolean containsRow(@Nullable Object rowKey) { + return Maps.safeContainsKey(rowMap(), rowKey); + } + + @Override + public boolean containsValue(@Nullable Object value) { + for (Map row : rowMap().values()) { + if (row.containsValue(value)) { + return true; + } + } + return false; + } + + Set> createCellSet() { + return new CellSet(); + } + + Collection createValues() { + return new Values(); + } + + @Override + public boolean equals(@Nullable Object obj) { + return Tables.equalsImpl(this, obj); + } + + @Override + public V get(@Nullable Object rowKey, @Nullable Object columnKey) { + Map row = Maps.safeGet(rowMap(), rowKey); + return (row == null) ? null : Maps.safeGet(row, columnKey); + } + + @Override + public int hashCode() { + return cellSet().hashCode(); + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + @Override + public V put(R rowKey, C columnKey, V value) { + return row(rowKey).put(columnKey, value); + } + + @Override + public void putAll(Table table) { + for (Table.Cell cell : table.cellSet()) { + put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); + } + } + + @Override + public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { + Map row = Maps.safeGet(rowMap(), rowKey); + return (row == null) ? null : Maps.safeRemove(row, columnKey); + } + + @Override + public Set rowKeySet() { + return rowMap().keySet(); + } + + /** + * Returns the string representation {@code rowMap().toString()}. + */ + @Override + public String toString() { + return rowMap().toString(); + } + @Override public Collection values() { Collection result = values; return (result == null) ? values = createValues() : result; } - Collection createValues() { - return new Values(); - } - Iterator valuesIterator() { return new TransformedIterator, V>(cellSet().iterator()) { @Override @@ -177,44 +217,4 @@ abstract class AbstractTable implements Table { } }; } - - class Values extends AbstractCollection { - @Override - public Iterator iterator() { - return valuesIterator(); - } - - @Override - public boolean contains(Object o) { - return containsValue(o); - } - - @Override - public void clear() { - AbstractTable.this.clear(); - } - - @Override - public int size() { - return AbstractTable.this.size(); - } - } - - @Override - public boolean equals(@Nullable Object obj) { - return Tables.equalsImpl(this, obj); - } - - @Override - public int hashCode() { - return cellSet().hashCode(); - } - - /** - * Returns the string representation {@code rowMap().toString()}. - */ - @Override - public String toString() { - return rowMap().toString(); - } } diff --git a/src/main/java/com/google/common/collect/AllEqualOrdering.java b/src/main/java/com/google/common/collect/AllEqualOrdering.java index de8a9253..363e234e 100644 --- a/src/main/java/com/google/common/collect/AllEqualOrdering.java +++ b/src/main/java/com/google/common/collect/AllEqualOrdering.java @@ -32,35 +32,35 @@ import com.google.common.annotations.GwtCompatible; final class AllEqualOrdering extends Ordering implements Serializable { static final AllEqualOrdering INSTANCE = new AllEqualOrdering(); + private static final long serialVersionUID = 0; + @Override public int compare(@Nullable Object left, @Nullable Object right) { return 0; } - @Override - public List sortedCopy(Iterable iterable) { - return Lists.newArrayList(iterable); - } - @Override public ImmutableList immutableSortedCopy(Iterable iterable) { return ImmutableList.copyOf(iterable); } + private Object readResolve() { + return INSTANCE; + } + @SuppressWarnings("unchecked") @Override public Ordering reverse() { return (Ordering) this; } - private Object readResolve() { - return INSTANCE; + @Override + public List sortedCopy(Iterable iterable) { + return Lists.newArrayList(iterable); } @Override public String toString() { return "Ordering.allEqual()"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ArrayListMultimap.java b/src/main/java/com/google/common/collect/ArrayListMultimap.java index 8fbef2f5..c75b8b79 100644 --- a/src/main/java/com/google/common/collect/ArrayListMultimap.java +++ b/src/main/java/com/google/common/collect/ArrayListMultimap.java @@ -53,7 +53,8 @@ import com.google.common.annotations.VisibleForTesting; * *

* The lists returned by {@link #get}, {@link #removeAll}, and - * {@link #replaceValues} all implement {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. + * {@link #replaceValues} all implement + * {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. * *

* This class is not threadsafe when any concurrent operations update the @@ -74,8 +75,8 @@ public final class ArrayListMultimap extends AbstractListMultimap { // Default from ArrayList private static final int DEFAULT_VALUES_PER_KEY = 3; - @VisibleForTesting - transient int expectedValuesPerKey; + @GwtIncompatible("Not needed in emulated source.") + private static final long serialVersionUID = 0; /** * Creates a new, empty {@code ArrayListMultimap} with the default initial @@ -108,6 +109,9 @@ public final class ArrayListMultimap extends AbstractListMultimap { return new ArrayListMultimap(multimap); } + @VisibleForTesting + transient int expectedValuesPerKey; + private ArrayListMultimap() { super(new HashMap>()); expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; @@ -135,6 +139,16 @@ public final class ArrayListMultimap extends AbstractListMultimap { return new ArrayList(expectedValuesPerKey); } + @GwtIncompatible("java.io.ObjectOutputStream") + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + expectedValuesPerKey = stream.readInt(); + int distinctKeys = Serialization.readCount(stream); + Map> map = Maps.newHashMapWithExpectedSize(distinctKeys); + setMap(map); + Serialization.populateMultimap(this, stream, distinctKeys); + } + /** * Reduces the memory used by this {@code ArrayListMultimap}, if feasible. */ @@ -156,17 +170,4 @@ public final class ArrayListMultimap extends AbstractListMultimap { stream.writeInt(expectedValuesPerKey); Serialization.writeMultimap(this, stream); } - - @GwtIncompatible("java.io.ObjectOutputStream") - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - expectedValuesPerKey = stream.readInt(); - int distinctKeys = Serialization.readCount(stream); - Map> map = Maps.newHashMapWithExpectedSize(distinctKeys); - setMap(map); - Serialization.populateMultimap(this, stream, distinctKeys); - } - - @GwtIncompatible("Not needed in emulated source.") - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ArrayTable.java b/src/main/java/com/google/common/collect/ArrayTable.java index 2f5dcbe2..a62fb117 100644 --- a/src/main/java/com/google/common/collect/ArrayTable.java +++ b/src/main/java/com/google/common/collect/ArrayTable.java @@ -93,6 +93,221 @@ import com.google.common.base.Objects; @GwtCompatible(emulated = true) public final class ArrayTable extends AbstractTable implements Serializable { + private abstract static class ArrayMap extends Maps.ImprovedAbstractMap { + private final ImmutableMap keyIndex; + + private ArrayMap(ImmutableMap keyIndex) { + this.keyIndex = keyIndex; + } + + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return keyIndex.containsKey(key); + } + + @Override + protected Set> createEntrySet() { + return new Maps.EntrySet() { + @Override + public Iterator> iterator() { + return new AbstractIndexedListIterator>(size()) { + @Override + protected Entry get(final int index) { + return new AbstractMapEntry() { + @Override + public K getKey() { + return ArrayMap.this.getKey(index); + } + + @Override + public V getValue() { + return ArrayMap.this.getValue(index); + } + + @Override + public V setValue(V value) { + return ArrayMap.this.setValue(index, value); + } + }; + } + }; + } + + @Override + Map map() { + return ArrayMap.this; + } + }; + } + + @Override + public V get(@Nullable Object key) { + Integer index = keyIndex.get(key); + if (index == null) { + return null; + } else { + return getValue(index); + } + } + + K getKey(int index) { + return keyIndex.keySet().asList().get(index); + } + + abstract String getKeyRole(); + + @Nullable + abstract V getValue(int index); + + @Override + public boolean isEmpty() { + return keyIndex.isEmpty(); + } + + // TODO(user): consider an optimized values() implementation + + @Override + public Set keySet() { + return keyIndex.keySet(); + } + + @Override + public V put(K key, V value) { + Integer index = keyIndex.get(key); + if (index == null) { + throw new IllegalArgumentException(getKeyRole() + " " + key + " not in " + keyIndex.keySet()); + } + return setValue(index, value); + } + + @Override + public V remove(Object key) { + throw new UnsupportedOperationException(); + } + + @Nullable + abstract V setValue(int index, V newValue); + + @Override + public int size() { + return keyIndex.size(); + } + } + + /* + * TODO(jlevy): Add factory methods taking an Enum class, instead of an + * iterable, to specify the allowed row keys and/or column keys. Note that + * custom serialization logic is needed to support different enum sizes during + * serialization and deserialization. + */ + + private class Column extends ArrayMap { + final int columnIndex; + + Column(int columnIndex) { + super(rowKeyToIndex); + this.columnIndex = columnIndex; + } + + @Override + String getKeyRole() { + return "Row"; + } + + @Override + V getValue(int index) { + return at(index, columnIndex); + } + + @Override + V setValue(int index, V newValue) { + return set(index, columnIndex, newValue); + } + } + + private class ColumnMap extends ArrayMap> { + private ColumnMap() { + super(columnKeyToIndex); + } + + @Override + String getKeyRole() { + return "Column"; + } + + @Override + Map getValue(int index) { + return new Column(index); + } + + @Override + public Map put(C key, Map value) { + throw new UnsupportedOperationException(); + } + + @Override + Map setValue(int index, Map newValue) { + throw new UnsupportedOperationException(); + } + } + + private class Row extends ArrayMap { + final int rowIndex; + + Row(int rowIndex) { + super(columnKeyToIndex); + this.rowIndex = rowIndex; + } + + @Override + String getKeyRole() { + return "Column"; + } + + @Override + V getValue(int index) { + return at(rowIndex, index); + } + + @Override + V setValue(int index, V newValue) { + return set(rowIndex, index, newValue); + } + } + + private class RowMap extends ArrayMap> { + private RowMap() { + super(rowKeyToIndex); + } + + @Override + String getKeyRole() { + return "Row"; + } + + @Override + Map getValue(int index) { + return new Row(index); + } + + @Override + public Map put(R key, Map value) { + throw new UnsupportedOperationException(); + } + + @Override + Map setValue(int index, Map newValue) { + throw new UnsupportedOperationException(); + } + } + + private static final long serialVersionUID = 0; + /** * Creates an empty {@code ArrayTable}. * @@ -107,13 +322,6 @@ public final class ArrayTable extends AbstractTable implements return new ArrayTable(rowKeys, columnKeys); } - /* - * TODO(jlevy): Add factory methods taking an Enum class, instead of an - * iterable, to specify the allowed row keys and/or column keys. Note that - * custom serialization logic is needed to support different enum sizes during - * serialization and deserialization. - */ - /** * Creates an {@code ArrayTable} with the mappings in the provided table. * @@ -143,14 +351,45 @@ public final class ArrayTable extends AbstractTable implements : new ArrayTable(table); } + private static ImmutableMap index(List list) { + ImmutableMap.Builder columnBuilder = ImmutableMap.builder(); + for (int i = 0; i < list.size(); i++) { + columnBuilder.put(list.get(i), i); + } + return columnBuilder.build(); + } + private final ImmutableList rowList; + private final ImmutableList columnList; // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex? private final ImmutableMap rowKeyToIndex; + private final ImmutableMap columnKeyToIndex; + private final V[][] array; + private transient ColumnMap columnMap; + + private transient RowMap rowMap; + + private ArrayTable(ArrayTable table) { + rowList = table.rowList; + columnList = table.columnList; + rowKeyToIndex = table.rowKeyToIndex; + columnKeyToIndex = table.columnKeyToIndex; + @SuppressWarnings("unchecked") + V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()]; + array = copy; + // Necessary because in GWT the arrays are initialized with "undefined" instead + // of null. + eraseAll(); + for (int i = 0; i < rowList.size(); i++) { + System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length); + } + } + private ArrayTable(Iterable rowKeys, Iterable columnKeys) { this.rowList = ImmutableList.copyOf(rowKeys); this.columnList = ImmutableList.copyOf(columnKeys); @@ -173,157 +412,11 @@ public final class ArrayTable extends AbstractTable implements eraseAll(); } - private static ImmutableMap index(List list) { - ImmutableMap.Builder columnBuilder = ImmutableMap.builder(); - for (int i = 0; i < list.size(); i++) { - columnBuilder.put(list.get(i), i); - } - return columnBuilder.build(); - } - private ArrayTable(Table table) { this(table.rowKeySet(), table.columnKeySet()); putAll(table); } - private ArrayTable(ArrayTable table) { - rowList = table.rowList; - columnList = table.columnList; - rowKeyToIndex = table.rowKeyToIndex; - columnKeyToIndex = table.columnKeyToIndex; - @SuppressWarnings("unchecked") - V[][] copy = (V[][]) new Object[rowList.size()][columnList.size()]; - array = copy; - // Necessary because in GWT the arrays are initialized with "undefined" instead - // of null. - eraseAll(); - for (int i = 0; i < rowList.size(); i++) { - System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length); - } - } - - private abstract static class ArrayMap extends Maps.ImprovedAbstractMap { - private final ImmutableMap keyIndex; - - private ArrayMap(ImmutableMap keyIndex) { - this.keyIndex = keyIndex; - } - - @Override - public Set keySet() { - return keyIndex.keySet(); - } - - K getKey(int index) { - return keyIndex.keySet().asList().get(index); - } - - abstract String getKeyRole(); - - @Nullable - abstract V getValue(int index); - - @Nullable - abstract V setValue(int index, V newValue); - - @Override - public int size() { - return keyIndex.size(); - } - - @Override - public boolean isEmpty() { - return keyIndex.isEmpty(); - } - - @Override - protected Set> createEntrySet() { - return new Maps.EntrySet() { - @Override - Map map() { - return ArrayMap.this; - } - - @Override - public Iterator> iterator() { - return new AbstractIndexedListIterator>(size()) { - @Override - protected Entry get(final int index) { - return new AbstractMapEntry() { - @Override - public K getKey() { - return ArrayMap.this.getKey(index); - } - - @Override - public V getValue() { - return ArrayMap.this.getValue(index); - } - - @Override - public V setValue(V value) { - return ArrayMap.this.setValue(index, value); - } - }; - } - }; - } - }; - } - - // TODO(user): consider an optimized values() implementation - - @Override - public boolean containsKey(@Nullable Object key) { - return keyIndex.containsKey(key); - } - - @Override - public V get(@Nullable Object key) { - Integer index = keyIndex.get(key); - if (index == null) { - return null; - } else { - return getValue(index); - } - } - - @Override - public V put(K key, V value) { - Integer index = keyIndex.get(key); - if (index == null) { - throw new IllegalArgumentException(getKeyRole() + " " + key + " not in " + keyIndex.keySet()); - } - return setValue(index, value); - } - - @Override - public V remove(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - } - - /** - * Returns, as an immutable list, the row keys provided when the table was - * constructed, including those that are mapped to null values only. - */ - public ImmutableList rowKeyList() { - return rowList; - } - - /** - * Returns, as an immutable list, the column keys provided when the table was - * constructed, including those that are mapped to null values only. - */ - public ImmutableList columnKeyList() { - return columnList; - } - /** * Returns the value corresponding to the specified row and column indices. The * same value is returned by {@code @@ -346,51 +439,51 @@ public final class ArrayTable extends AbstractTable implements return array[rowIndex][columnIndex]; } - /** - * Associates {@code value} with the specified row and column indices. The logic - * {@code - * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has - * the same behavior, but this method runs more quickly. - * - * @param rowIndex position of the row key in {@link #rowKeyList()} - * @param columnIndex position of the row key in {@link #columnKeyList()} - * @param value value to store in the table - * @return the previous value with the specified row and column - * @throws IndexOutOfBoundsException if either index is negative, {@code - * rowIndex} is greater then or equal to the number of - * allowed row keys, or {@code columnIndex} is - * greater then or equal to the number of - * allowed column keys - */ - public V set(int rowIndex, int columnIndex, @Nullable V value) { - // In GWT array access never throws IndexOutOfBoundsException. - checkElementIndex(rowIndex, rowList.size()); - checkElementIndex(columnIndex, columnList.size()); - V oldValue = array[rowIndex][columnIndex]; - array[rowIndex][columnIndex] = value; - return oldValue; + @Override + Iterator> cellIterator() { + return new AbstractIndexedListIterator>(size()) { + @Override + protected Cell get(final int index) { + return new Tables.AbstractCell() { + final int rowIndex = index / columnList.size(); + final int columnIndex = index % columnList.size(); + + @Override + public C getColumnKey() { + return columnList.get(columnIndex); + } + + @Override + public R getRowKey() { + return rowList.get(rowIndex); + } + + @Override + public V getValue() { + return at(rowIndex, columnIndex); + } + }; + } + }; } /** - * Returns a two-dimensional array with the table contents. The row and column - * indices correspond to the positions of the row and column in the iterables - * provided during table construction. If the table lacks a mapping for a given - * row and column, the corresponding array element is null. + * Returns an unmodifiable set of all row key / column key / value triplets. + * Changes to the table will update the returned set. * *

- * Subsequent table changes will not modify the array, and vice versa. + * The returned set's iterator traverses the mappings with the first row key, + * the mappings with the second row key, and so on. * - * @param valueClass class of values stored in the returned array + *

+ * The value in the returned cells may change if the table subsequently changes. + * + * @return set of table cells consisting of row key / column key / value + * triplets */ - @GwtIncompatible("reflection") - public V[][] toArray(Class valueClass) { - // Can change to use varargs in JDK 1.6 if we want - @SuppressWarnings("unchecked") // TODO: safe? - V[][] copy = (V[][]) Array.newInstance(valueClass, new int[] { rowList.size(), columnList.size() }); - for (int i = 0; i < rowList.size(); i++) { - System.arraycopy(array[i], 0, copy[i], 0, array[i].length); - } - return copy; + @Override + public Set> cellSet() { + return super.cellSet(); } /** @@ -406,13 +499,52 @@ public final class ArrayTable extends AbstractTable implements } /** - * Associates the value {@code null} with every pair of allowed row and column - * keys. + * Returns a view of all mappings that have the given column key. If the column + * key isn't in {@link #columnKeySet()}, an empty immutable map is returned. + * + *

+ * Otherwise, for each row key in {@link #rowKeySet()}, the returned map + * associates the row key with the corresponding value in the table. Changes to + * the returned map will update the underlying table, and vice versa. + * + * @param columnKey key of column to search for in the table + * @return the corresponding map from row keys to values */ - public void eraseAll() { - for (V[] row : array) { - Arrays.fill(row, null); - } + @Override + public Map column(C columnKey) { + checkNotNull(columnKey); + Integer columnIndex = columnKeyToIndex.get(columnKey); + return (columnIndex == null) ? ImmutableMap.of() : new Column(columnIndex); + } + + /** + * Returns, as an immutable list, the column keys provided when the table was + * constructed, including those that are mapped to null values only. + */ + public ImmutableList columnKeyList() { + return columnList; + } + + /** + * Returns an immutable set of the valid column keys, including those that are + * associated with null values only. + * + * @return immutable set of column keys + */ + @Override + public ImmutableSet columnKeySet() { + return columnKeyToIndex.keySet(); + } + + /* + * TODO(jlevy): Consider creating a merge() method, similar to putAll() but + * copying non-null values only. + */ + + @Override + public Map> columnMap() { + ColumnMap map = columnMap; + return (map == null) ? columnMap = new ColumnMap() : map; } /** @@ -433,6 +565,8 @@ public final class ArrayTable extends AbstractTable implements return columnKeyToIndex.containsKey(columnKey); } + // TODO(jlevy): Add eraseRow and eraseColumn methods? + /** * Returns {@code true} if the provided row key is among the row keys provided * when the table was constructed. @@ -454,6 +588,39 @@ public final class ArrayTable extends AbstractTable implements return false; } + /** + * Associates the value {@code null} with the specified keys, assuming both keys + * are valid. If either key is null or isn't among the keys provided during + * construction, this method has no effect. + * + *

+ * This method is equivalent to {@code put(rowKey, columnKey, null)} when both + * provided keys are valid. + * + * @param rowKey row key of mapping to be erased + * @param columnKey column key of mapping to be erased + * @return the value previously associated with the keys, or {@code null} if no + * mapping existed for the keys + */ + public V erase(@Nullable Object rowKey, @Nullable Object columnKey) { + Integer rowIndex = rowKeyToIndex.get(rowKey); + Integer columnIndex = columnKeyToIndex.get(columnKey); + if (rowIndex == null || columnIndex == null) { + return null; + } + return set(rowIndex, columnIndex, null); + } + + /** + * Associates the value {@code null} with every pair of allowed row and column + * keys. + */ + public void eraseAll() { + for (V[] row : array) { + Arrays.fill(row, null); + } + } + @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); @@ -487,11 +654,6 @@ public final class ArrayTable extends AbstractTable implements return set(rowIndex, columnIndex, value); } - /* - * TODO(jlevy): Consider creating a merge() method, similar to putAll() but - * copying non-null values only. - */ - /** * {@inheritDoc} * @@ -521,171 +683,6 @@ public final class ArrayTable extends AbstractTable implements throw new UnsupportedOperationException(); } - /** - * Associates the value {@code null} with the specified keys, assuming both keys - * are valid. If either key is null or isn't among the keys provided during - * construction, this method has no effect. - * - *

- * This method is equivalent to {@code put(rowKey, columnKey, null)} when both - * provided keys are valid. - * - * @param rowKey row key of mapping to be erased - * @param columnKey column key of mapping to be erased - * @return the value previously associated with the keys, or {@code null} if no - * mapping existed for the keys - */ - public V erase(@Nullable Object rowKey, @Nullable Object columnKey) { - Integer rowIndex = rowKeyToIndex.get(rowKey); - Integer columnIndex = columnKeyToIndex.get(columnKey); - if (rowIndex == null || columnIndex == null) { - return null; - } - return set(rowIndex, columnIndex, null); - } - - // TODO(jlevy): Add eraseRow and eraseColumn methods? - - @Override - public int size() { - return rowList.size() * columnList.size(); - } - - /** - * Returns an unmodifiable set of all row key / column key / value triplets. - * Changes to the table will update the returned set. - * - *

- * The returned set's iterator traverses the mappings with the first row key, - * the mappings with the second row key, and so on. - * - *

- * The value in the returned cells may change if the table subsequently changes. - * - * @return set of table cells consisting of row key / column key / value - * triplets - */ - @Override - public Set> cellSet() { - return super.cellSet(); - } - - @Override - Iterator> cellIterator() { - return new AbstractIndexedListIterator>(size()) { - @Override - protected Cell get(final int index) { - return new Tables.AbstractCell() { - final int rowIndex = index / columnList.size(); - final int columnIndex = index % columnList.size(); - - @Override - public R getRowKey() { - return rowList.get(rowIndex); - } - - @Override - public C getColumnKey() { - return columnList.get(columnIndex); - } - - @Override - public V getValue() { - return at(rowIndex, columnIndex); - } - }; - } - }; - } - - /** - * Returns a view of all mappings that have the given column key. If the column - * key isn't in {@link #columnKeySet()}, an empty immutable map is returned. - * - *

- * Otherwise, for each row key in {@link #rowKeySet()}, the returned map - * associates the row key with the corresponding value in the table. Changes to - * the returned map will update the underlying table, and vice versa. - * - * @param columnKey key of column to search for in the table - * @return the corresponding map from row keys to values - */ - @Override - public Map column(C columnKey) { - checkNotNull(columnKey); - Integer columnIndex = columnKeyToIndex.get(columnKey); - return (columnIndex == null) ? ImmutableMap.of() : new Column(columnIndex); - } - - private class Column extends ArrayMap { - final int columnIndex; - - Column(int columnIndex) { - super(rowKeyToIndex); - this.columnIndex = columnIndex; - } - - @Override - String getKeyRole() { - return "Row"; - } - - @Override - V getValue(int index) { - return at(index, columnIndex); - } - - @Override - V setValue(int index, V newValue) { - return set(index, columnIndex, newValue); - } - } - - /** - * Returns an immutable set of the valid column keys, including those that are - * associated with null values only. - * - * @return immutable set of column keys - */ - @Override - public ImmutableSet columnKeySet() { - return columnKeyToIndex.keySet(); - } - - private transient ColumnMap columnMap; - - @Override - public Map> columnMap() { - ColumnMap map = columnMap; - return (map == null) ? columnMap = new ColumnMap() : map; - } - - private class ColumnMap extends ArrayMap> { - private ColumnMap() { - super(columnKeyToIndex); - } - - @Override - String getKeyRole() { - return "Column"; - } - - @Override - Map getValue(int index) { - return new Column(index); - } - - @Override - Map setValue(int index, Map newValue) { - throw new UnsupportedOperationException(); - } - - @Override - public Map put(C key, Map value) { - throw new UnsupportedOperationException(); - } - } - /** * Returns a view of all mappings that have the given row key. If the row key * isn't in {@link #rowKeySet()}, an empty immutable map is returned. @@ -705,28 +702,12 @@ public final class ArrayTable extends AbstractTable implements return (rowIndex == null) ? ImmutableMap.of() : new Row(rowIndex); } - private class Row extends ArrayMap { - final int rowIndex; - - Row(int rowIndex) { - super(columnKeyToIndex); - this.rowIndex = rowIndex; - } - - @Override - String getKeyRole() { - return "Column"; - } - - @Override - V getValue(int index) { - return at(rowIndex, index); - } - - @Override - V setValue(int index, V newValue) { - return set(rowIndex, index, newValue); - } + /** + * Returns, as an immutable list, the row keys provided when the table was + * constructed, including those that are mapped to null values only. + */ + public ImmutableList rowKeyList() { + return rowList; } /** @@ -740,38 +721,62 @@ public final class ArrayTable extends AbstractTable implements return rowKeyToIndex.keySet(); } - private transient RowMap rowMap; - @Override public Map> rowMap() { RowMap map = rowMap; return (map == null) ? rowMap = new RowMap() : map; } - private class RowMap extends ArrayMap> { - private RowMap() { - super(rowKeyToIndex); - } + /** + * Associates {@code value} with the specified row and column indices. The logic + * {@code + * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has + * the same behavior, but this method runs more quickly. + * + * @param rowIndex position of the row key in {@link #rowKeyList()} + * @param columnIndex position of the row key in {@link #columnKeyList()} + * @param value value to store in the table + * @return the previous value with the specified row and column + * @throws IndexOutOfBoundsException if either index is negative, {@code + * rowIndex} is greater then or equal to the number of + * allowed row keys, or {@code columnIndex} is + * greater then or equal to the number of + * allowed column keys + */ + public V set(int rowIndex, int columnIndex, @Nullable V value) { + // In GWT array access never throws IndexOutOfBoundsException. + checkElementIndex(rowIndex, rowList.size()); + checkElementIndex(columnIndex, columnList.size()); + V oldValue = array[rowIndex][columnIndex]; + array[rowIndex][columnIndex] = value; + return oldValue; + } - @Override - String getKeyRole() { - return "Row"; - } + @Override + public int size() { + return rowList.size() * columnList.size(); + } - @Override - Map getValue(int index) { - return new Row(index); - } - - @Override - Map setValue(int index, Map newValue) { - throw new UnsupportedOperationException(); - } - - @Override - public Map put(R key, Map value) { - throw new UnsupportedOperationException(); + /** + * Returns a two-dimensional array with the table contents. The row and column + * indices correspond to the positions of the row and column in the iterables + * provided during table construction. If the table lacks a mapping for a given + * row and column, the corresponding array element is null. + * + *

+ * Subsequent table changes will not modify the array, and vice versa. + * + * @param valueClass class of values stored in the returned array + */ + @GwtIncompatible("reflection") + public V[][] toArray(Class valueClass) { + // Can change to use varargs in JDK 1.6 if we want + @SuppressWarnings("unchecked") // TODO: safe? + V[][] copy = (V[][]) Array.newInstance(valueClass, new int[] { rowList.size(), columnList.size() }); + for (int i = 0; i < rowList.size(); i++) { + System.arraycopy(array[i], 0, copy[i], 0, array[i].length); } + return copy; } /** @@ -788,6 +793,4 @@ public final class ArrayTable extends AbstractTable implements public Collection values() { return super.values(); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/BiMap.java b/src/main/java/com/google/common/collect/BiMap.java index c34fa390..7afce11a 100644 --- a/src/main/java/com/google/common/collect/BiMap.java +++ b/src/main/java/com/google/common/collect/BiMap.java @@ -41,18 +41,6 @@ import com.google.common.annotations.GwtCompatible; public interface BiMap extends Map { // Modification Operations - /** - * {@inheritDoc} - * - * @throws IllegalArgumentException if the given value is already bound to a - * different key in this bimap. The bimap will - * remain unmodified in this event. To avoid - * this exception, call {@link #forcePut} - * instead. - */ - @Override - V put(@Nullable K key, @Nullable V value); - /** * An alternate form of {@code put} that silently removes any existing entry * with the value {@code value} before proceeding with the {@link #put} @@ -74,8 +62,35 @@ public interface BiMap extends Map { */ V forcePut(@Nullable K key, @Nullable V value); + /** + * Returns the inverse view of this bimap, which maps each of this bimap's + * values to its associated key. The two bimaps are backed by the same data; any + * changes to one will appear in the other. + * + *

+ * Note:There is no guaranteed correspondence between the iteration order + * of a bimap and that of its inverse. + * + * @return the inverse view of this bimap + */ + BiMap inverse(); + // Bulk Operations + /** + * {@inheritDoc} + * + * @throws IllegalArgumentException if the given value is already bound to a + * different key in this bimap. The bimap will + * remain unmodified in this event. To avoid + * this exception, call {@link #forcePut} + * instead. + */ + @Override + V put(@Nullable K key, @Nullable V value); + + // Views + /** * {@inheritDoc} * @@ -91,8 +106,6 @@ public interface BiMap extends Map { @Override void putAll(Map map); - // Views - /** * {@inheritDoc} * @@ -102,17 +115,4 @@ public interface BiMap extends Map { */ @Override Set values(); - - /** - * Returns the inverse view of this bimap, which maps each of this bimap's - * values to its associated key. The two bimaps are backed by the same data; any - * changes to one will appear in the other. - * - *

- * Note:There is no guaranteed correspondence between the iteration order - * of a bimap and that of its inverse. - * - * @return the inverse view of this bimap - */ - BiMap inverse(); } diff --git a/src/main/java/com/google/common/collect/BinaryTreeTraverser.java b/src/main/java/com/google/common/collect/BinaryTreeTraverser.java index b3249b2c..8dfdcebe 100644 --- a/src/main/java/com/google/common/collect/BinaryTreeTraverser.java +++ b/src/main/java/com/google/common/collect/BinaryTreeTraverser.java @@ -40,92 +40,32 @@ public abstract class BinaryTreeTraverser extends TreeTraverser { // TODO(user): make this GWT-compatible when we've checked in ArrayDeque and // BitSet emulation - /** - * Returns the left child of the specified node, or {@link Optional#absent()} if - * the specified node has no left child. - */ - public abstract Optional leftChild(T root); - - /** - * Returns the right child of the specified node, or {@link Optional#absent()} - * if the specified node has no right child. - */ - public abstract Optional rightChild(T root); - - /** - * Returns the children of this node, in left-to-right order. - */ - @Override - public final Iterable children(final T root) { - checkNotNull(root); - return new FluentIterable() { - @Override - public Iterator iterator() { - return new AbstractIterator() { - boolean doneLeft; - boolean doneRight; - - @Override - protected T computeNext() { - if (!doneLeft) { - doneLeft = true; - Optional left = leftChild(root); - if (left.isPresent()) { - return left.get(); - } - } - if (!doneRight) { - doneRight = true; - Optional right = rightChild(root); - if (right.isPresent()) { - return right.get(); - } - } - return endOfData(); - } - }; - } - }; - } - - @Override - UnmodifiableIterator preOrderIterator(T root) { - return new PreOrderIterator(root); - } - - /* - * Optimized implementation of preOrderIterator for binary trees. - */ - private final class PreOrderIterator extends UnmodifiableIterator implements PeekingIterator { + private final class InOrderIterator extends AbstractIterator { private final Deque stack; + private final BitSet hasExpandedLeft; - PreOrderIterator(T root) { + InOrderIterator(T root) { this.stack = new ArrayDeque(); + this.hasExpandedLeft = new BitSet(); stack.addLast(root); } @Override - public boolean hasNext() { - return !stack.isEmpty(); + protected T computeNext() { + while (!stack.isEmpty()) { + T node = stack.getLast(); + if (hasExpandedLeft.get(stack.size() - 1)) { + stack.removeLast(); + hasExpandedLeft.clear(stack.size()); + pushIfPresent(stack, rightChild(node)); + return node; + } else { + hasExpandedLeft.set(stack.size() - 1); + pushIfPresent(stack, leftChild(node)); + } + } + return endOfData(); } - - @Override - public T next() { - T result = stack.removeLast(); - pushIfPresent(stack, rightChild(result)); - pushIfPresent(stack, leftChild(result)); - return result; - } - - @Override - public T peek() { - return stack.getLast(); - } - } - - @Override - UnmodifiableIterator postOrderIterator(T root) { - return new PostOrderIterator(root); } /* @@ -164,8 +104,77 @@ public abstract class BinaryTreeTraverser extends TreeTraverser { } } - // TODO(user): see if any significant optimizations are possible for - // breadthFirstIterator + /* + * Optimized implementation of preOrderIterator for binary trees. + */ + private final class PreOrderIterator extends UnmodifiableIterator implements PeekingIterator { + private final Deque stack; + + PreOrderIterator(T root) { + this.stack = new ArrayDeque(); + stack.addLast(root); + } + + @Override + public boolean hasNext() { + return !stack.isEmpty(); + } + + @Override + public T next() { + T result = stack.removeLast(); + pushIfPresent(stack, rightChild(result)); + pushIfPresent(stack, leftChild(result)); + return result; + } + + @Override + public T peek() { + return stack.getLast(); + } + } + + private static void pushIfPresent(Deque stack, Optional node) { + if (node.isPresent()) { + stack.addLast(node.get()); + } + } + + /** + * Returns the children of this node, in left-to-right order. + */ + @Override + public final Iterable children(final T root) { + checkNotNull(root); + return new FluentIterable() { + @Override + public Iterator iterator() { + return new AbstractIterator() { + boolean doneLeft; + boolean doneRight; + + @Override + protected T computeNext() { + if (!doneLeft) { + doneLeft = true; + Optional left = leftChild(root); + if (left.isPresent()) { + return left.get(); + } + } + if (!doneRight) { + doneRight = true; + Optional right = rightChild(root); + if (right.isPresent()) { + return right.get(); + } + } + return endOfData(); + } + }; + } + }; + } public final FluentIterable inOrderTraversal(final T root) { checkNotNull(root); @@ -177,37 +186,28 @@ public abstract class BinaryTreeTraverser extends TreeTraverser { }; } - private final class InOrderIterator extends AbstractIterator { - private final Deque stack; - private final BitSet hasExpandedLeft; + /** + * Returns the left child of the specified node, or {@link Optional#absent()} if + * the specified node has no left child. + */ + public abstract Optional leftChild(T root); - InOrderIterator(T root) { - this.stack = new ArrayDeque(); - this.hasExpandedLeft = new BitSet(); - stack.addLast(root); - } + // TODO(user): see if any significant optimizations are possible for + // breadthFirstIterator - @Override - protected T computeNext() { - while (!stack.isEmpty()) { - T node = stack.getLast(); - if (hasExpandedLeft.get(stack.size() - 1)) { - stack.removeLast(); - hasExpandedLeft.clear(stack.size()); - pushIfPresent(stack, rightChild(node)); - return node; - } else { - hasExpandedLeft.set(stack.size() - 1); - pushIfPresent(stack, leftChild(node)); - } - } - return endOfData(); - } + @Override + UnmodifiableIterator postOrderIterator(T root) { + return new PostOrderIterator(root); } - private static void pushIfPresent(Deque stack, Optional node) { - if (node.isPresent()) { - stack.addLast(node.get()); - } + @Override + UnmodifiableIterator preOrderIterator(T root) { + return new PreOrderIterator(root); } + + /** + * Returns the right child of the specified node, or {@link Optional#absent()} + * if the specified node has no right child. + */ + public abstract Optional rightChild(T root); } diff --git a/src/main/java/com/google/common/collect/ByFunctionOrdering.java b/src/main/java/com/google/common/collect/ByFunctionOrdering.java index 7094e0a3..6ad9659f 100644 --- a/src/main/java/com/google/common/collect/ByFunctionOrdering.java +++ b/src/main/java/com/google/common/collect/ByFunctionOrdering.java @@ -32,7 +32,9 @@ import com.google.common.base.Objects; */ @GwtCompatible(serializable = true) final class ByFunctionOrdering extends Ordering implements Serializable { + private static final long serialVersionUID = 0; final Function function; + final Ordering ordering; ByFunctionOrdering(Function function, Ordering ordering) { @@ -66,6 +68,4 @@ final class ByFunctionOrdering extends Ordering implements Serializable public String toString() { return ordering + ".onResultOf(" + function + ")"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/CartesianList.java b/src/main/java/com/google/common/collect/CartesianList.java index a7f51391..0fcd819c 100644 --- a/src/main/java/com/google/common/collect/CartesianList.java +++ b/src/main/java/com/google/common/collect/CartesianList.java @@ -34,9 +34,6 @@ import com.google.common.math.IntMath; @GwtCompatible final class CartesianList extends AbstractList> implements RandomAccess { - private transient final ImmutableList> axes; - private transient final int[] axesSizeProduct; - static List> create(List> lists) { ImmutableList.Builder> axesBuilder = new ImmutableList.Builder>(lists.size()); for (List list : lists) { @@ -49,6 +46,10 @@ final class CartesianList extends AbstractList> implements RandomAcce return new CartesianList(axesBuilder.build()); } + private transient final ImmutableList> axes; + + private transient final int[] axesSizeProduct; + CartesianList(ImmutableList> axes) { this.axes = axes; int[] axesSizeProduct = new int[axes.size() + 1]; @@ -63,39 +64,6 @@ final class CartesianList extends AbstractList> implements RandomAcce this.axesSizeProduct = axesSizeProduct; } - private int getAxisIndexForProductIndex(int index, int axis) { - return (index / axesSizeProduct[axis + 1]) % axes.get(axis).size(); - } - - @Override - public ImmutableList get(final int index) { - checkElementIndex(index, size()); - return new ImmutableList() { - - @Override - public int size() { - return axes.size(); - } - - @Override - public E get(int axis) { - checkElementIndex(axis, size()); - int axisIndex = getAxisIndexForProductIndex(index, axis); - return axes.get(axis).get(axisIndex); - } - - @Override - boolean isPartialView() { - return true; - } - }; - } - - @Override - public int size() { - return axesSizeProduct[0]; - } - @Override public boolean contains(@Nullable Object o) { if (!(o instanceof List)) { @@ -114,4 +82,37 @@ final class CartesianList extends AbstractList> implements RandomAcce } return true; } + + @Override + public ImmutableList get(final int index) { + checkElementIndex(index, size()); + return new ImmutableList() { + + @Override + public E get(int axis) { + checkElementIndex(axis, size()); + int axisIndex = getAxisIndexForProductIndex(index, axis); + return axes.get(axis).get(axisIndex); + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public int size() { + return axes.size(); + } + }; + } + + private int getAxisIndexForProductIndex(int index, int axis) { + return (index / axesSizeProduct[axis + 1]) % axes.get(axis).size(); + } + + @Override + public int size() { + return axesSizeProduct[0]; + } } diff --git a/src/main/java/com/google/common/collect/Collections2.java b/src/main/java/com/google/common/collect/Collections2.java index 6ef373de..146d0b1a 100644 --- a/src/main/java/com/google/common/collect/Collections2.java +++ b/src/main/java/com/google/common/collect/Collections2.java @@ -54,7 +54,377 @@ import com.google.common.primitives.Ints; */ @GwtCompatible public final class Collections2 { - private Collections2() { + static class FilteredCollection extends AbstractCollection { + final Collection unfiltered; + final Predicate predicate; + + FilteredCollection(Collection unfiltered, Predicate predicate) { + this.unfiltered = unfiltered; + this.predicate = predicate; + } + + @Override + public boolean add(E element) { + checkArgument(predicate.apply(element)); + return unfiltered.add(element); + } + + @Override + public boolean addAll(Collection collection) { + for (E element : collection) { + checkArgument(predicate.apply(element)); + } + return unfiltered.addAll(collection); + } + + @Override + public void clear() { + Iterables.removeIf(unfiltered, predicate); + } + + @Override + public boolean contains(@Nullable Object element) { + if (safeContains(unfiltered, element)) { + @SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E + E e = (E) element; + return predicate.apply(e); + } + return false; + } + + @Override + public boolean containsAll(Collection collection) { + return containsAllImpl(this, collection); + } + + FilteredCollection createCombined(Predicate newPredicate) { + return new FilteredCollection(unfiltered, Predicates.and(predicate, newPredicate)); + // . above needed to compile in JDK 5 + } + + @Override + public boolean isEmpty() { + return !Iterables.any(unfiltered, predicate); + } + + @Override + public Iterator iterator() { + return Iterators.filter(unfiltered.iterator(), predicate); + } + + @Override + public boolean remove(Object element) { + return contains(element) && unfiltered.remove(element); + } + + @Override + public boolean removeAll(final Collection collection) { + return Iterables.removeIf(unfiltered, and(predicate, (Predicate) in(collection))); + } + + @Override + public boolean retainAll(final Collection collection) { + return Iterables.removeIf(unfiltered, and(predicate, (Predicate) not(in(collection)))); + } + + @Override + public int size() { + return Iterators.size(iterator()); + } + + @Override + public Object[] toArray() { + // creating an ArrayList so filtering happens once + return Lists.newArrayList(iterator()).toArray(); + } + + @Override + public T[] toArray(T[] array) { + return Lists.newArrayList(iterator()).toArray(array); + } + } + + private static final class OrderedPermutationCollection extends AbstractCollection> { + /** + * The number of permutations with repeated elements is calculated as follows: + *

    + *
  • For an empty list, it is 1 (base case).
  • + *
  • When r numbers are added to a list of n-r elements, the number of + * permutations is increased by a factor of (n choose r).
  • + *
+ */ + private static int calculateSize(List sortedInputList, Comparator comparator) { + long permutations = 1; + int n = 1; + int r = 1; + while (n < sortedInputList.size()) { + int comparison = comparator.compare(sortedInputList.get(n - 1), sortedInputList.get(n)); + if (comparison < 0) { + // We move to the next non-repeated element. + permutations *= binomial(n, r); + r = 0; + if (!isPositiveInt(permutations)) { + return Integer.MAX_VALUE; + } + } + n++; + r++; + } + permutations *= binomial(n, r); + if (!isPositiveInt(permutations)) { + return Integer.MAX_VALUE; + } + return (int) permutations; + } + + final ImmutableList inputList; + final Comparator comparator; + + final int size; + + OrderedPermutationCollection(Iterable input, Comparator comparator) { + this.inputList = Ordering.from(comparator).immutableSortedCopy(input); + this.comparator = comparator; + this.size = calculateSize(inputList, comparator); + } + + @Override + public boolean contains(@Nullable Object obj) { + if (obj instanceof List) { + List list = (List) obj; + return isPermutation(inputList, list); + } + return false; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public Iterator> iterator() { + return new OrderedPermutationIterator(inputList, comparator); + } + + @Override + public int size() { + return size; + } + + @Override + public String toString() { + return "orderedPermutationCollection(" + inputList + ")"; + } + } + + private static final class OrderedPermutationIterator extends AbstractIterator> { + + List nextPermutation; + final Comparator comparator; + + OrderedPermutationIterator(List list, Comparator comparator) { + this.nextPermutation = Lists.newArrayList(list); + this.comparator = comparator; + } + + void calculateNextPermutation() { + int j = findNextJ(); + if (j == -1) { + nextPermutation = null; + return; + } + + int l = findNextL(j); + Collections.swap(nextPermutation, j, l); + int n = nextPermutation.size(); + Collections.reverse(nextPermutation.subList(j + 1, n)); + } + + @Override + protected List computeNext() { + if (nextPermutation == null) { + return endOfData(); + } + ImmutableList next = ImmutableList.copyOf(nextPermutation); + calculateNextPermutation(); + return next; + } + + int findNextJ() { + for (int k = nextPermutation.size() - 2; k >= 0; k--) { + if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) { + return k; + } + } + return -1; + } + + int findNextL(int j) { + E ak = nextPermutation.get(j); + for (int l = nextPermutation.size() - 1; l > j; l--) { + if (comparator.compare(ak, nextPermutation.get(l)) < 0) { + return l; + } + } + throw new AssertionError("this statement should be unreachable"); + } + } + + private static final class PermutationCollection extends AbstractCollection> { + final ImmutableList inputList; + + PermutationCollection(ImmutableList input) { + this.inputList = input; + } + + @Override + public boolean contains(@Nullable Object obj) { + if (obj instanceof List) { + List list = (List) obj; + return isPermutation(inputList, list); + } + return false; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public Iterator> iterator() { + return new PermutationIterator(inputList); + } + + @Override + public int size() { + return IntMath.factorial(inputList.size()); + } + + @Override + public String toString() { + return "permutations(" + inputList + ")"; + } + } + + private static class PermutationIterator extends AbstractIterator> { + final List list; + final int[] c; + final int[] o; + int j; + + PermutationIterator(List list) { + this.list = new ArrayList(list); + int n = list.size(); + c = new int[n]; + o = new int[n]; + Arrays.fill(c, 0); + Arrays.fill(o, 1); + j = Integer.MAX_VALUE; + } + + void calculateNextPermutation() { + j = list.size() - 1; + int s = 0; + + // Handle the special case of an empty list. Skip the calculation of the + // next permutation. + if (j == -1) { + return; + } + + while (true) { + int q = c[j] + o[j]; + if (q < 0) { + switchDirection(); + continue; + } + if (q == j + 1) { + if (j == 0) { + break; + } + s++; + switchDirection(); + continue; + } + + Collections.swap(list, j - c[j] + s, j - q + s); + c[j] = q; + break; + } + } + + @Override + protected List computeNext() { + if (j <= 0) { + return endOfData(); + } + ImmutableList next = ImmutableList.copyOf(list); + calculateNextPermutation(); + return next; + } + + void switchDirection() { + o[j] = -o[j]; + j--; + } + } + + static class TransformedCollection extends AbstractCollection { + final Collection fromCollection; + final Function function; + + TransformedCollection(Collection fromCollection, Function function) { + this.fromCollection = checkNotNull(fromCollection); + this.function = checkNotNull(function); + } + + @Override + public void clear() { + fromCollection.clear(); + } + + @Override + public boolean isEmpty() { + return fromCollection.isEmpty(); + } + + @Override + public Iterator iterator() { + return Iterators.transform(fromCollection.iterator(), function); + } + + @Override + public int size() { + return fromCollection.size(); + } + } + + static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null"); + + /** + * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + */ + static Collection cast(Iterable iterable) { + return (Collection) iterable; + } + + /** + * Returns {@code true} if the collection {@code self} contains all of the + * elements in the collection {@code c}. + * + *

+ * This method iterates over the specified collection {@code c}, checking each + * element returned by the iterator in turn to see if it is contained in the + * specified collection {@code self}. If all elements are so contained, + * {@code true} is returned, otherwise {@code false}. + * + * @param self a collection which might contain all elements in {@code c} + * @param c a collection whose elements might be contained by {@code self} + */ + static boolean containsAllImpl(Collection self, Collection c) { + return Iterables.all(c, Predicates.in(self)); } /** @@ -102,213 +472,19 @@ public final class Collections2 { } /** - * Delegates to {@link Collection#contains}. Returns {@code false} if the - * {@code contains} method throws a {@code ClassCastException} or - * {@code NullPointerException}. + * Returns {@code true} if the second list is a permutation of the first. */ - static boolean safeContains(Collection collection, @Nullable Object object) { - checkNotNull(collection); - try { - return collection.contains(object); - } catch (ClassCastException e) { - return false; - } catch (NullPointerException e) { + private static boolean isPermutation(List first, List second) { + if (first.size() != second.size()) { return false; } + Multiset firstMultiset = HashMultiset.create(first); + Multiset secondMultiset = HashMultiset.create(second); + return firstMultiset.equals(secondMultiset); } - /** - * Delegates to {@link Collection#remove}. Returns {@code false} if the - * {@code remove} method throws a {@code ClassCastException} or - * {@code NullPointerException}. - */ - static boolean safeRemove(Collection collection, @Nullable Object object) { - checkNotNull(collection); - try { - return collection.remove(object); - } catch (ClassCastException e) { - return false; - } catch (NullPointerException e) { - return false; - } - } - - static class FilteredCollection extends AbstractCollection { - final Collection unfiltered; - final Predicate predicate; - - FilteredCollection(Collection unfiltered, Predicate predicate) { - this.unfiltered = unfiltered; - this.predicate = predicate; - } - - FilteredCollection createCombined(Predicate newPredicate) { - return new FilteredCollection(unfiltered, Predicates.and(predicate, newPredicate)); - // . above needed to compile in JDK 5 - } - - @Override - public boolean add(E element) { - checkArgument(predicate.apply(element)); - return unfiltered.add(element); - } - - @Override - public boolean addAll(Collection collection) { - for (E element : collection) { - checkArgument(predicate.apply(element)); - } - return unfiltered.addAll(collection); - } - - @Override - public void clear() { - Iterables.removeIf(unfiltered, predicate); - } - - @Override - public boolean contains(@Nullable Object element) { - if (safeContains(unfiltered, element)) { - @SuppressWarnings("unchecked") // element is in unfiltered, so it must be an E - E e = (E) element; - return predicate.apply(e); - } - return false; - } - - @Override - public boolean containsAll(Collection collection) { - return containsAllImpl(this, collection); - } - - @Override - public boolean isEmpty() { - return !Iterables.any(unfiltered, predicate); - } - - @Override - public Iterator iterator() { - return Iterators.filter(unfiltered.iterator(), predicate); - } - - @Override - public boolean remove(Object element) { - return contains(element) && unfiltered.remove(element); - } - - @Override - public boolean removeAll(final Collection collection) { - return Iterables.removeIf(unfiltered, and(predicate, (Predicate)in(collection))); - } - - @Override - public boolean retainAll(final Collection collection) { - return Iterables.removeIf(unfiltered, and(predicate, (Predicate)not(in(collection)))); - } - - @Override - public int size() { - return Iterators.size(iterator()); - } - - @Override - public Object[] toArray() { - // creating an ArrayList so filtering happens once - return Lists.newArrayList(iterator()).toArray(); - } - - @Override - public T[] toArray(T[] array) { - return Lists.newArrayList(iterator()).toArray(array); - } - } - - /** - * Returns a collection that applies {@code function} to each element of - * {@code fromCollection}. The returned collection is a live view of {@code - * fromCollection}; changes to one affect the other. - * - *

- * The returned collection's {@code add()} and {@code addAll()} methods throw an - * {@link UnsupportedOperationException}. All other collection methods are - * supported, as long as {@code fromCollection} supports them. - * - *

- * The returned collection isn't threadsafe or serializable, even if - * {@code fromCollection} is. - * - *

- * When a live view is not needed, it may be faster to copy the - * transformed collection and use the copy. - * - *

- * If the input {@code Collection} is known to be a {@code List}, consider - * {@link Lists#transform}. If only an {@code Iterable} is available, use - * {@link Iterables#transform}. - */ - public static Collection transform(Collection fromCollection, Function function) { - return new TransformedCollection(fromCollection, function); - } - - static class TransformedCollection extends AbstractCollection { - final Collection fromCollection; - final Function function; - - TransformedCollection(Collection fromCollection, Function function) { - this.fromCollection = checkNotNull(fromCollection); - this.function = checkNotNull(function); - } - - @Override - public void clear() { - fromCollection.clear(); - } - - @Override - public boolean isEmpty() { - return fromCollection.isEmpty(); - } - - @Override - public Iterator iterator() { - return Iterators.transform(fromCollection.iterator(), function); - } - - @Override - public int size() { - return fromCollection.size(); - } - } - - /** - * Returns {@code true} if the collection {@code self} contains all of the - * elements in the collection {@code c}. - * - *

- * This method iterates over the specified collection {@code c}, checking each - * element returned by the iterator in turn to see if it is contained in the - * specified collection {@code self}. If all elements are so contained, - * {@code true} is returned, otherwise {@code false}. - * - * @param self a collection which might contain all elements in {@code c} - * @param c a collection whose elements might be contained by {@code self} - */ - static boolean containsAllImpl(Collection self, Collection c) { - return Iterables.all(c, Predicates.in(self)); - } - - /** - * An implementation of {@link Collection#toString()}. - */ - static String toStringImpl(final Collection collection) { - StringBuilder sb = newStringBuilderForCollection(collection.size()).append('['); - STANDARD_JOINER.appendTo(sb, Iterables.transform(collection, new Function() { - @Override - public Object apply(Object input) { - return input == collection ? "(this Collection)" : input; - } - })); - return sb.append(']').toString(); + private static boolean isPositiveInt(long n) { + return n >= 0 && n <= Integer.MAX_VALUE; } /** @@ -319,15 +495,6 @@ public final class Collections2 { return new StringBuilder((int) Math.min(size * 8L, Ints.MAX_POWER_OF_TWO)); } - /** - * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 - */ - static Collection cast(Iterable iterable) { - return (Collection) iterable; - } - - static final Joiner STANDARD_JOINER = Joiner.on(", ").useForNull("null"); - /** * Returns a {@link Collection} of all the permutations of the specified * {@link Iterable}. @@ -374,25 +541,26 @@ public final class Collections2 { *

 	 *    {@code
 	 *
-	 *   for (List perm : orderedPermutations(asList("b", "c", "a"))) {
-	 *     println(perm);
-	 *   }
-	 *   // -> ["a", "b", "c"]
-	 *   // -> ["a", "c", "b"]
-	 *   // -> ["b", "a", "c"]
-	 *   // -> ["b", "c", "a"]
-	 *   // -> ["c", "a", "b"]
-	 *   // -> ["c", "b", "a"]
+	 * for (List perm : orderedPermutations(asList("b", "c", "a"))) {
+	 * 	println(perm);
+	 * }
+	 * // -> ["a", "b", "c"]
+	 * // -> ["a", "c", "b"]
+	 * // -> ["b", "a", "c"]
+	 * // -> ["b", "c", "a"]
+	 * // -> ["c", "a", "b"]
+	 * // -> ["c", "b", "a"]
 	 *
-	 *   for (List perm : orderedPermutations(asList(1, 2, 2, 1))) {
-	 *     println(perm);
-	 *   }
-	 *   // -> [1, 1, 2, 2]
-	 *   // -> [1, 2, 1, 2]
-	 *   // -> [1, 2, 2, 1]
-	 *   // -> [2, 1, 1, 2]
-	 *   // -> [2, 1, 2, 1]
-	 *   // -> [2, 2, 1, 1]}
+	 * for (List perm : orderedPermutations(asList(1, 2, 2, 1))) {
+	 * 	println(perm);
+	 * }
+	 * // -> [1, 1, 2, 2]
+	 * // -> [1, 2, 1, 2]
+	 * // -> [1, 2, 2, 1]
+	 * // -> [2, 1, 1, 2]
+	 * // -> [2, 1, 2, 1]
+	 * // -> [2, 2, 1, 1]
+	 * }
 	 * 
* *

@@ -423,132 +591,6 @@ public final class Collections2 { return new OrderedPermutationCollection(elements, comparator); } - private static final class OrderedPermutationCollection extends AbstractCollection> { - final ImmutableList inputList; - final Comparator comparator; - final int size; - - OrderedPermutationCollection(Iterable input, Comparator comparator) { - this.inputList = Ordering.from(comparator).immutableSortedCopy(input); - this.comparator = comparator; - this.size = calculateSize(inputList, comparator); - } - - /** - * The number of permutations with repeated elements is calculated as follows: - *

    - *
  • For an empty list, it is 1 (base case).
  • - *
  • When r numbers are added to a list of n-r elements, the number of - * permutations is increased by a factor of (n choose r).
  • - *
- */ - private static int calculateSize(List sortedInputList, Comparator comparator) { - long permutations = 1; - int n = 1; - int r = 1; - while (n < sortedInputList.size()) { - int comparison = comparator.compare(sortedInputList.get(n - 1), sortedInputList.get(n)); - if (comparison < 0) { - // We move to the next non-repeated element. - permutations *= binomial(n, r); - r = 0; - if (!isPositiveInt(permutations)) { - return Integer.MAX_VALUE; - } - } - n++; - r++; - } - permutations *= binomial(n, r); - if (!isPositiveInt(permutations)) { - return Integer.MAX_VALUE; - } - return (int) permutations; - } - - @Override - public int size() { - return size; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Iterator> iterator() { - return new OrderedPermutationIterator(inputList, comparator); - } - - @Override - public boolean contains(@Nullable Object obj) { - if (obj instanceof List) { - List list = (List) obj; - return isPermutation(inputList, list); - } - return false; - } - - @Override - public String toString() { - return "orderedPermutationCollection(" + inputList + ")"; - } - } - - private static final class OrderedPermutationIterator extends AbstractIterator> { - - List nextPermutation; - final Comparator comparator; - - OrderedPermutationIterator(List list, Comparator comparator) { - this.nextPermutation = Lists.newArrayList(list); - this.comparator = comparator; - } - - @Override - protected List computeNext() { - if (nextPermutation == null) { - return endOfData(); - } - ImmutableList next = ImmutableList.copyOf(nextPermutation); - calculateNextPermutation(); - return next; - } - - void calculateNextPermutation() { - int j = findNextJ(); - if (j == -1) { - nextPermutation = null; - return; - } - - int l = findNextL(j); - Collections.swap(nextPermutation, j, l); - int n = nextPermutation.size(); - Collections.reverse(nextPermutation.subList(j + 1, n)); - } - - int findNextJ() { - for (int k = nextPermutation.size() - 2; k >= 0; k--) { - if (comparator.compare(nextPermutation.get(k), nextPermutation.get(k + 1)) < 0) { - return k; - } - } - return -1; - } - - int findNextL(int j) { - E ak = nextPermutation.get(j); - for (int l = nextPermutation.size() - 1; l > j; l--) { - if (comparator.compare(ak, nextPermutation.get(l)) < 0) { - return l; - } - } - throw new AssertionError("this statement should be unreachable"); - } - } - /** * Returns a {@link Collection} of all the permutations of the specified * {@link Collection}. @@ -577,119 +619,79 @@ public final class Collections2 { return new PermutationCollection(ImmutableList.copyOf(elements)); } - private static final class PermutationCollection extends AbstractCollection> { - final ImmutableList inputList; - - PermutationCollection(ImmutableList input) { - this.inputList = input; - } - - @Override - public int size() { - return IntMath.factorial(inputList.size()); - } - - @Override - public boolean isEmpty() { + /** + * Delegates to {@link Collection#contains}. Returns {@code false} if the + * {@code contains} method throws a {@code ClassCastException} or + * {@code NullPointerException}. + */ + static boolean safeContains(Collection collection, @Nullable Object object) { + checkNotNull(collection); + try { + return collection.contains(object); + } catch (ClassCastException e) { return false; - } - - @Override - public Iterator> iterator() { - return new PermutationIterator(inputList); - } - - @Override - public boolean contains(@Nullable Object obj) { - if (obj instanceof List) { - List list = (List) obj; - return isPermutation(inputList, list); - } + } catch (NullPointerException e) { return false; } - - @Override - public String toString() { - return "permutations(" + inputList + ")"; - } - } - - private static class PermutationIterator extends AbstractIterator> { - final List list; - final int[] c; - final int[] o; - int j; - - PermutationIterator(List list) { - this.list = new ArrayList(list); - int n = list.size(); - c = new int[n]; - o = new int[n]; - Arrays.fill(c, 0); - Arrays.fill(o, 1); - j = Integer.MAX_VALUE; - } - - @Override - protected List computeNext() { - if (j <= 0) { - return endOfData(); - } - ImmutableList next = ImmutableList.copyOf(list); - calculateNextPermutation(); - return next; - } - - void calculateNextPermutation() { - j = list.size() - 1; - int s = 0; - - // Handle the special case of an empty list. Skip the calculation of the - // next permutation. - if (j == -1) { - return; - } - - while (true) { - int q = c[j] + o[j]; - if (q < 0) { - switchDirection(); - continue; - } - if (q == j + 1) { - if (j == 0) { - break; - } - s++; - switchDirection(); - continue; - } - - Collections.swap(list, j - c[j] + s, j - q + s); - c[j] = q; - break; - } - } - - void switchDirection() { - o[j] = -o[j]; - j--; - } } /** - * Returns {@code true} if the second list is a permutation of the first. + * Delegates to {@link Collection#remove}. Returns {@code false} if the + * {@code remove} method throws a {@code ClassCastException} or + * {@code NullPointerException}. */ - private static boolean isPermutation(List first, List second) { - if (first.size() != second.size()) { + static boolean safeRemove(Collection collection, @Nullable Object object) { + checkNotNull(collection); + try { + return collection.remove(object); + } catch (ClassCastException e) { + return false; + } catch (NullPointerException e) { return false; } - Multiset firstMultiset = HashMultiset.create(first); - Multiset secondMultiset = HashMultiset.create(second); - return firstMultiset.equals(secondMultiset); } - private static boolean isPositiveInt(long n) { - return n >= 0 && n <= Integer.MAX_VALUE; + /** + * An implementation of {@link Collection#toString()}. + */ + static String toStringImpl(final Collection collection) { + StringBuilder sb = newStringBuilderForCollection(collection.size()).append('['); + STANDARD_JOINER.appendTo(sb, Iterables.transform(collection, new Function() { + @Override + public Object apply(Object input) { + return input == collection ? "(this Collection)" : input; + } + })); + return sb.append(']').toString(); + } + + /** + * Returns a collection that applies {@code function} to each element of + * {@code fromCollection}. The returned collection is a live view of {@code + * fromCollection}; changes to one affect the other. + * + *

+ * The returned collection's {@code add()} and {@code addAll()} methods throw an + * {@link UnsupportedOperationException}. All other collection methods are + * supported, as long as {@code fromCollection} supports them. + * + *

+ * The returned collection isn't threadsafe or serializable, even if + * {@code fromCollection} is. + * + *

+ * When a live view is not needed, it may be faster to copy the + * transformed collection and use the copy. + * + *

+ * If the input {@code Collection} is known to be a {@code List}, consider + * {@link Lists#transform}. If only an {@code Iterable} is available, use + * {@link Iterables#transform}. + */ + public static Collection transform(Collection fromCollection, Function function) { + return new TransformedCollection(fromCollection, function); + } + + private Collections2() { } } diff --git a/src/main/java/com/google/common/collect/ComparatorOrdering.java b/src/main/java/com/google/common/collect/ComparatorOrdering.java index 810586ca..a18ee1c5 100644 --- a/src/main/java/com/google/common/collect/ComparatorOrdering.java +++ b/src/main/java/com/google/common/collect/ComparatorOrdering.java @@ -28,6 +28,8 @@ import com.google.common.annotations.GwtCompatible; /** An ordering for a pre-existing comparator. */ @GwtCompatible(serializable = true) final class ComparatorOrdering extends Ordering implements Serializable { + private static final long serialVersionUID = 0; + final Comparator comparator; ComparatorOrdering(Comparator comparator) { @@ -60,6 +62,4 @@ final class ComparatorOrdering extends Ordering implements Serializable { public String toString() { return comparator.toString(); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ComparisonChain.java b/src/main/java/com/google/common/collect/ComparisonChain.java index 4209e0d9..dcf1716a 100644 --- a/src/main/java/com/google/common/collect/ComparisonChain.java +++ b/src/main/java/com/google/common/collect/ComparisonChain.java @@ -31,13 +31,11 @@ import com.google.common.primitives.Longs; *

  *    {@code
  *
- *   public int compareTo(Foo that) {
- *     return ComparisonChain.start()
- *         .compare(this.aString, that.aString)
- *         .compare(this.anInt, that.anInt)
- *         .compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast())
- *         .result();
- *   }}
+ * public int compareTo(Foo that) {
+ * 	return ComparisonChain.start().compare(this.aString, that.aString).compare(this.anInt, that.anInt)
+ * 			.compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()).result();
+ * }
+ * }
  * 
* *

@@ -65,73 +63,6 @@ import com.google.common.primitives.Longs; */ @GwtCompatible public abstract class ComparisonChain { - private ComparisonChain() { - } - - /** - * Begins a new chained comparison statement. See example in the class - * documentation. - */ - public static ComparisonChain start() { - return ACTIVE; - } - - private static final ComparisonChain ACTIVE = new ComparisonChain() { - @SuppressWarnings("unchecked") - @Override - public ComparisonChain compare(Comparable left, Comparable right) { - return classify(left.compareTo(right)); - } - - @Override - public ComparisonChain compare(@Nullable T left, @Nullable T right, Comparator comparator) { - return classify(comparator.compare(left, right)); - } - - @Override - public ComparisonChain compare(int left, int right) { - return classify(Ints.compare(left, right)); - } - - @Override - public ComparisonChain compare(long left, long right) { - return classify(Longs.compare(left, right)); - } - - @Override - public ComparisonChain compare(float left, float right) { - return classify(Float.compare(left, right)); - } - - @Override - public ComparisonChain compare(double left, double right) { - return classify(Double.compare(left, right)); - } - - @Override - public ComparisonChain compareTrueFirst(boolean left, boolean right) { - return classify(Booleans.compare(right, left)); // reversed - } - - @Override - public ComparisonChain compareFalseFirst(boolean left, boolean right) { - return classify(Booleans.compare(left, right)); - } - - ComparisonChain classify(int result) { - return (result < 0) ? LESS : (result > 0) ? GREATER : ACTIVE; - } - - @Override - public int result() { - return 0; - } - }; - - private static final ComparisonChain LESS = new InactiveComparisonChain(-1); - - private static final ComparisonChain GREATER = new InactiveComparisonChain(1); - private static final class InactiveComparisonChain extends ComparisonChain { final int result; @@ -145,7 +76,12 @@ public abstract class ComparisonChain { } @Override - public ComparisonChain compare(@Nullable T left, @Nullable T right, @Nullable Comparator comparator) { + public ComparisonChain compare(double left, double right) { + return this; + } + + @Override + public ComparisonChain compare(float left, float right) { return this; } @@ -160,17 +96,7 @@ public abstract class ComparisonChain { } @Override - public ComparisonChain compare(float left, float right) { - return this; - } - - @Override - public ComparisonChain compare(double left, double right) { - return this; - } - - @Override - public ComparisonChain compareTrueFirst(boolean left, boolean right) { + public ComparisonChain compare(@Nullable T left, @Nullable T right, @Nullable Comparator comparator) { return this; } @@ -179,12 +105,84 @@ public abstract class ComparisonChain { return this; } + @Override + public ComparisonChain compareTrueFirst(boolean left, boolean right) { + return this; + } + @Override public int result() { return result; } } + private static final ComparisonChain ACTIVE = new ComparisonChain() { + ComparisonChain classify(int result) { + return (result < 0) ? LESS : (result > 0) ? GREATER : ACTIVE; + } + + @SuppressWarnings("unchecked") + @Override + public ComparisonChain compare(Comparable left, Comparable right) { + return classify(left.compareTo(right)); + } + + @Override + public ComparisonChain compare(double left, double right) { + return classify(Double.compare(left, right)); + } + + @Override + public ComparisonChain compare(float left, float right) { + return classify(Float.compare(left, right)); + } + + @Override + public ComparisonChain compare(int left, int right) { + return classify(Ints.compare(left, right)); + } + + @Override + public ComparisonChain compare(long left, long right) { + return classify(Longs.compare(left, right)); + } + + @Override + public ComparisonChain compare(@Nullable T left, @Nullable T right, Comparator comparator) { + return classify(comparator.compare(left, right)); + } + + @Override + public ComparisonChain compareFalseFirst(boolean left, boolean right) { + return classify(Booleans.compare(left, right)); + } + + @Override + public ComparisonChain compareTrueFirst(boolean left, boolean right) { + return classify(Booleans.compare(right, left)); // reversed + } + + @Override + public int result() { + return 0; + } + }; + + private static final ComparisonChain LESS = new InactiveComparisonChain(-1); + + private static final ComparisonChain GREATER = new InactiveComparisonChain(1); + + /** + * Begins a new chained comparison statement. See example in the class + * documentation. + */ + public static ComparisonChain start() { + return ACTIVE; + } + + private ComparisonChain() { + } + /** * Compares two comparable objects as specified by {@link Comparable#compareTo}, * if the result of this comparison chain has not already been @@ -193,10 +191,18 @@ public abstract class ComparisonChain { public abstract ComparisonChain compare(Comparable left, Comparable right); /** - * Compares two objects using a comparator, if the result of this - * comparison chain has not already been determined. + * Compares two {@code double} values as specified by {@link Double#compare}, + * if the result of this comparison chain has not already been + * determined. */ - public abstract ComparisonChain compare(@Nullable T left, @Nullable T right, Comparator comparator); + public abstract ComparisonChain compare(double left, double right); + + /** + * Compares two {@code float} values as specified by {@link Float#compare}, + * if the result of this comparison chain has not already been + * determined. + */ + public abstract ComparisonChain compare(float left, float right); /** * Compares two {@code int} values as specified by {@link Ints#compare}, @@ -213,27 +219,10 @@ public abstract class ComparisonChain { public abstract ComparisonChain compare(long left, long right); /** - * Compares two {@code float} values as specified by {@link Float#compare}, - * if the result of this comparison chain has not already been - * determined. + * Compares two objects using a comparator, if the result of this + * comparison chain has not already been determined. */ - public abstract ComparisonChain compare(float left, float right); - - /** - * Compares two {@code double} values as specified by {@link Double#compare}, - * if the result of this comparison chain has not already been - * determined. - */ - public abstract ComparisonChain compare(double left, double right); - - /** - * Compares two {@code boolean} values, considering {@code true} to be less than - * {@code false}, if the result of this comparison chain has not already - * been determined. - * - * @since 12.0 - */ - public abstract ComparisonChain compareTrueFirst(boolean left, boolean right); + public abstract ComparisonChain compare(@Nullable T left, @Nullable T right, Comparator comparator); /** * Compares two {@code boolean} values, considering {@code false} to be less @@ -244,6 +233,15 @@ public abstract class ComparisonChain { */ public abstract ComparisonChain compareFalseFirst(boolean left, boolean right); + /** + * Compares two {@code boolean} values, considering {@code true} to be less than + * {@code false}, if the result of this comparison chain has not already + * been determined. + * + * @since 12.0 + */ + public abstract ComparisonChain compareTrueFirst(boolean left, boolean right); + /** * Ends this comparison chain and returns its result: a value having the same * sign as the first nonzero comparison result in the chain, or zero if every diff --git a/src/main/java/com/google/common/collect/CompoundOrdering.java b/src/main/java/com/google/common/collect/CompoundOrdering.java index 483eaf9b..5925ecc1 100644 --- a/src/main/java/com/google/common/collect/CompoundOrdering.java +++ b/src/main/java/com/google/common/collect/CompoundOrdering.java @@ -24,6 +24,8 @@ import com.google.common.annotations.GwtCompatible; /** An ordering that tries several comparators in order. */ @GwtCompatible(serializable = true) final class CompoundOrdering extends Ordering implements Serializable { + private static final long serialVersionUID = 0; + final ImmutableList> comparators; CompoundOrdering(Comparator primary, Comparator secondary) { @@ -68,6 +70,4 @@ final class CompoundOrdering extends Ordering implements Serializable { public String toString() { return "Ordering.compound(" + comparators + ")"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ComputationException.java b/src/main/java/com/google/common/collect/ComputationException.java index d0d12f2a..7b31546a 100644 --- a/src/main/java/com/google/common/collect/ComputationException.java +++ b/src/main/java/com/google/common/collect/ComputationException.java @@ -28,12 +28,12 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public class ComputationException extends RuntimeException { + private static final long serialVersionUID = 0; + /** * Creates a new instance with the given cause. */ public ComputationException(@Nullable Throwable cause) { super(cause); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/Constraint.java b/src/main/java/com/google/common/collect/Constraint.java index 2b8e276c..64f1aed5 100644 --- a/src/main/java/com/google/common/collect/Constraint.java +++ b/src/main/java/com/google/common/collect/Constraint.java @@ -26,12 +26,13 @@ import com.google.common.annotations.GwtCompatible; *

  *    {@code
  *
- *   public Object checkElement(Object element) {
- *     if (element == null) {
- *       throw new NullPointerException();
- *     }
- *     return element;
- *   }}
+ * public Object checkElement(Object element) {
+ * 	if (element == null) {
+ * 		throw new NullPointerException();
+ * 	}
+ * 	return element;
+ * }
+ * }
  * 
* *

diff --git a/src/main/java/com/google/common/collect/Constraints.java b/src/main/java/com/google/common/collect/Constraints.java index f141cad3..88842dca 100644 --- a/src/main/java/com/google/common/collect/Constraints.java +++ b/src/main/java/com/google/common/collect/Constraints.java @@ -35,26 +35,6 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible final class Constraints { - private Constraints() { - } - - /** - * Returns a constrained view of the specified collection, using the specified - * constraint. Any operations that add new elements to the collection will call - * the provided constraint. However, this method does not verify that existing - * elements satisfy the constraint. - * - *

- * The returned collection is not serializable. - * - * @param collection the collection to constrain - * @param constraint the constraint that validates added elements - * @return a constrained view of the collection - */ - public static Collection constrainedCollection(Collection collection, Constraint constraint) { - return new ConstrainedCollection(collection, constraint); - } - /** @see Constraints#constrainedCollection */ static class ConstrainedCollection extends ForwardingCollection { private final Collection delegate; @@ -65,143 +45,21 @@ final class Constraints { this.constraint = checkNotNull(constraint); } + @Override + public boolean add(E element) { + constraint.checkElement(element); + return delegate.add(element); + } + + @Override + public boolean addAll(Collection elements) { + return delegate.addAll(checkElements(elements, constraint)); + } + @Override protected Collection delegate() { return delegate; } - - @Override - public boolean add(E element) { - constraint.checkElement(element); - return delegate.add(element); - } - - @Override - public boolean addAll(Collection elements) { - return delegate.addAll(checkElements(elements, constraint)); - } - } - - /** - * Returns a constrained view of the specified set, using the specified - * constraint. Any operations that add new elements to the set will call the - * provided constraint. However, this method does not verify that existing - * elements satisfy the constraint. - * - *

- * The returned set is not serializable. - * - * @param set the set to constrain - * @param constraint the constraint that validates added elements - * @return a constrained view of the set - */ - public static Set constrainedSet(Set set, Constraint constraint) { - return new ConstrainedSet(set, constraint); - } - - /** @see Constraints#constrainedSet */ - static class ConstrainedSet extends ForwardingSet { - private final Set delegate; - private final Constraint constraint; - - public ConstrainedSet(Set delegate, Constraint constraint) { - this.delegate = checkNotNull(delegate); - this.constraint = checkNotNull(constraint); - } - - @Override - protected Set delegate() { - return delegate; - } - - @Override - public boolean add(E element) { - constraint.checkElement(element); - return delegate.add(element); - } - - @Override - public boolean addAll(Collection elements) { - return delegate.addAll(checkElements(elements, constraint)); - } - } - - /** - * Returns a constrained view of the specified sorted set, using the specified - * constraint. Any operations that add new elements to the sorted set will call - * the provided constraint. However, this method does not verify that existing - * elements satisfy the constraint. - * - *

- * The returned set is not serializable. - * - * @param sortedSet the sorted set to constrain - * @param constraint the constraint that validates added elements - * @return a constrained view of the sorted set - */ - public static SortedSet constrainedSortedSet(SortedSet sortedSet, Constraint constraint) { - return new ConstrainedSortedSet(sortedSet, constraint); - } - - /** @see Constraints#constrainedSortedSet */ - private static class ConstrainedSortedSet extends ForwardingSortedSet { - final SortedSet delegate; - final Constraint constraint; - - ConstrainedSortedSet(SortedSet delegate, Constraint constraint) { - this.delegate = checkNotNull(delegate); - this.constraint = checkNotNull(constraint); - } - - @Override - protected SortedSet delegate() { - return delegate; - } - - @Override - public SortedSet headSet(E toElement) { - return constrainedSortedSet(delegate.headSet(toElement), constraint); - } - - @Override - public SortedSet subSet(E fromElement, E toElement) { - return constrainedSortedSet(delegate.subSet(fromElement, toElement), constraint); - } - - @Override - public SortedSet tailSet(E fromElement) { - return constrainedSortedSet(delegate.tailSet(fromElement), constraint); - } - - @Override - public boolean add(E element) { - constraint.checkElement(element); - return delegate.add(element); - } - - @Override - public boolean addAll(Collection elements) { - return delegate.addAll(checkElements(elements, constraint)); - } - } - - /** - * Returns a constrained view of the specified list, using the specified - * constraint. Any operations that add new elements to the list will call the - * provided constraint. However, this method does not verify that existing - * elements satisfy the constraint. - * - *

- * If {@code list} implements {@link RandomAccess}, so will the returned list. - * The returned list is not serializable. - * - * @param list the list to constrain - * @param constraint the constraint that validates added elements - * @return a constrained view of the list - */ - public static List constrainedList(List list, Constraint constraint) { - return (list instanceof RandomAccess) ? new ConstrainedRandomAccessList(list, constraint) - : new ConstrainedList(list, constraint); } /** @see Constraints#constrainedList */ @@ -215,11 +73,6 @@ final class Constraints { this.constraint = checkNotNull(constraint); } - @Override - protected List delegate() { - return delegate; - } - @Override public boolean add(E element) { constraint.checkElement(element); @@ -242,6 +95,11 @@ final class Constraints { return delegate.addAll(index, checkElements(elements, constraint)); } + @Override + protected List delegate() { + return delegate; + } + @Override public ListIterator listIterator() { return constrainedListIterator(delegate.listIterator(), constraint); @@ -264,6 +122,34 @@ final class Constraints { } } + /** @see Constraints#constrainedListIterator */ + static class ConstrainedListIterator extends ForwardingListIterator { + private final ListIterator delegate; + private final Constraint constraint; + + public ConstrainedListIterator(ListIterator delegate, Constraint constraint) { + this.delegate = delegate; + this.constraint = constraint; + } + + @Override + public void add(E element) { + constraint.checkElement(element); + delegate.add(element); + } + + @Override + protected ListIterator delegate() { + return delegate; + } + + @Override + public void set(E element) { + constraint.checkElement(element); + delegate.set(element); + } + } + /** @see Constraints#constrainedList */ static class ConstrainedRandomAccessList extends ConstrainedList implements RandomAccess { ConstrainedRandomAccessList(List delegate, Constraint constraint) { @@ -271,6 +157,119 @@ final class Constraints { } } + /** @see Constraints#constrainedSet */ + static class ConstrainedSet extends ForwardingSet { + private final Set delegate; + private final Constraint constraint; + + public ConstrainedSet(Set delegate, Constraint constraint) { + this.delegate = checkNotNull(delegate); + this.constraint = checkNotNull(constraint); + } + + @Override + public boolean add(E element) { + constraint.checkElement(element); + return delegate.add(element); + } + + @Override + public boolean addAll(Collection elements) { + return delegate.addAll(checkElements(elements, constraint)); + } + + @Override + protected Set delegate() { + return delegate; + } + } + + /** @see Constraints#constrainedSortedSet */ + private static class ConstrainedSortedSet extends ForwardingSortedSet { + final SortedSet delegate; + final Constraint constraint; + + ConstrainedSortedSet(SortedSet delegate, Constraint constraint) { + this.delegate = checkNotNull(delegate); + this.constraint = checkNotNull(constraint); + } + + @Override + public boolean add(E element) { + constraint.checkElement(element); + return delegate.add(element); + } + + @Override + public boolean addAll(Collection elements) { + return delegate.addAll(checkElements(elements, constraint)); + } + + @Override + protected SortedSet delegate() { + return delegate; + } + + @Override + public SortedSet headSet(E toElement) { + return constrainedSortedSet(delegate.headSet(toElement), constraint); + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return constrainedSortedSet(delegate.subSet(fromElement, toElement), constraint); + } + + @Override + public SortedSet tailSet(E fromElement) { + return constrainedSortedSet(delegate.tailSet(fromElement), constraint); + } + } + + private static Collection checkElements(Collection elements, Constraint constraint) { + Collection copy = Lists.newArrayList(elements); + for (E element : copy) { + constraint.checkElement(element); + } + return copy; + } + + /** + * Returns a constrained view of the specified collection, using the specified + * constraint. Any operations that add new elements to the collection will call + * the provided constraint. However, this method does not verify that existing + * elements satisfy the constraint. + * + *

+ * The returned collection is not serializable. + * + * @param collection the collection to constrain + * @param constraint the constraint that validates added elements + * @return a constrained view of the collection + */ + public static Collection constrainedCollection(Collection collection, Constraint constraint) { + return new ConstrainedCollection(collection, constraint); + } + + /** + * Returns a constrained view of the specified list, using the specified + * constraint. Any operations that add new elements to the list will call the + * provided constraint. However, this method does not verify that existing + * elements satisfy the constraint. + * + *

+ * If {@code list} implements {@link RandomAccess}, so will the returned list. + * The returned list is not serializable. + * + * @param list the list to constrain + * @param constraint the constraint that validates added elements + * @return a constrained view of the list + */ + public static List constrainedList(List list, Constraint constraint) { + return (list instanceof RandomAccess) ? new ConstrainedRandomAccessList(list, constraint) + : new ConstrainedList(list, constraint); + } + /** * Returns a constrained view of the specified list iterator, using the * specified constraint. Any operations that would add new elements to the @@ -285,32 +284,38 @@ final class Constraints { return new ConstrainedListIterator(listIterator, constraint); } - /** @see Constraints#constrainedListIterator */ - static class ConstrainedListIterator extends ForwardingListIterator { - private final ListIterator delegate; - private final Constraint constraint; + /** + * Returns a constrained view of the specified set, using the specified + * constraint. Any operations that add new elements to the set will call the + * provided constraint. However, this method does not verify that existing + * elements satisfy the constraint. + * + *

+ * The returned set is not serializable. + * + * @param set the set to constrain + * @param constraint the constraint that validates added elements + * @return a constrained view of the set + */ + public static Set constrainedSet(Set set, Constraint constraint) { + return new ConstrainedSet(set, constraint); + } - public ConstrainedListIterator(ListIterator delegate, Constraint constraint) { - this.delegate = delegate; - this.constraint = constraint; - } - - @Override - protected ListIterator delegate() { - return delegate; - } - - @Override - public void add(E element) { - constraint.checkElement(element); - delegate.add(element); - } - - @Override - public void set(E element) { - constraint.checkElement(element); - delegate.set(element); - } + /** + * Returns a constrained view of the specified sorted set, using the specified + * constraint. Any operations that add new elements to the sorted set will call + * the provided constraint. However, this method does not verify that existing + * elements satisfy the constraint. + * + *

+ * The returned set is not serializable. + * + * @param sortedSet the sorted set to constrain + * @param constraint the constraint that validates added elements + * @return a constrained view of the sorted set + */ + public static SortedSet constrainedSortedSet(SortedSet sortedSet, Constraint constraint) { + return new ConstrainedSortedSet(sortedSet, constraint); } static Collection constrainedTypePreservingCollection(Collection collection, Constraint constraint) { @@ -330,11 +335,6 @@ final class Constraints { * having addAll() call add() repeatedly instead. */ - private static Collection checkElements(Collection elements, Constraint constraint) { - Collection copy = Lists.newArrayList(elements); - for (E element : copy) { - constraint.checkElement(element); - } - return copy; + private Constraints() { } } diff --git a/src/main/java/com/google/common/collect/ContiguousSet.java b/src/main/java/com/google/common/collect/ContiguousSet.java index b3b91ff6..d9252f25 100644 --- a/src/main/java/com/google/common/collect/ContiguousSet.java +++ b/src/main/java/com/google/common/collect/ContiguousSet.java @@ -43,6 +43,20 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(emulated = true) @SuppressWarnings("rawtypes") // allow ungenerified Comparable types public abstract class ContiguousSet extends ImmutableSortedSet { + /** + * Not supported. {@code ContiguousSet} instances are constructed with + * {@link #create}. This method exists only to hide {@link ImmutableSet#builder} + * from consumers of {@code + * ContiguousSet}. + * + * @throws UnsupportedOperationException always + * @deprecated Use {@link #create}. + */ + @Deprecated + public static ImmutableSortedSet.Builder builder() { + throw new UnsupportedOperationException(); + } + /** * Returns a {@code ContiguousSet} containing the same values in the given * domain {@linkplain Range#contains contained} by the range. @@ -95,51 +109,12 @@ public abstract class ContiguousSet extends ImmutableSorte return headSetImpl(checkNotNull(toElement), inclusive); } - @Override - public ContiguousSet subSet(C fromElement, C toElement) { - checkNotNull(fromElement); - checkNotNull(toElement); - checkArgument(comparator().compare(fromElement, toElement) <= 0); - return subSetImpl(fromElement, true, toElement, false); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public ContiguousSet subSet(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { - checkNotNull(fromElement); - checkNotNull(toElement); - checkArgument(comparator().compare(fromElement, toElement) <= 0); - return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); - } - - @Override - public ContiguousSet tailSet(C fromElement) { - return tailSetImpl(checkNotNull(fromElement), true); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public ContiguousSet tailSet(C fromElement, boolean inclusive) { - return tailSetImpl(checkNotNull(fromElement), inclusive); - } - /* * These methods perform most headSet, subSet, and tailSet logic, besides * parameter validation. */ /* @Override */ abstract ContiguousSet headSetImpl(C toElement, boolean inclusive); - /* @Override */ abstract ContiguousSet subSetImpl(C fromElement, boolean fromInclusive, C toElement, - boolean toInclusive); - - /* @Override */ abstract ContiguousSet tailSetImpl(C fromElement, boolean inclusive); - /** * Returns the set of values that are contained in both this set and the other. * @@ -174,6 +149,45 @@ public abstract class ContiguousSet extends ImmutableSorte */ public abstract Range range(BoundType lowerBoundType, BoundType upperBoundType); + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public ContiguousSet subSet(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { + checkNotNull(fromElement); + checkNotNull(toElement); + checkArgument(comparator().compare(fromElement, toElement) <= 0); + return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); + } + + @Override + public ContiguousSet subSet(C fromElement, C toElement) { + checkNotNull(fromElement); + checkNotNull(toElement); + checkArgument(comparator().compare(fromElement, toElement) <= 0); + return subSetImpl(fromElement, true, toElement, false); + } + + /* @Override */ abstract ContiguousSet subSetImpl(C fromElement, boolean fromInclusive, C toElement, + boolean toInclusive); + + @Override + public ContiguousSet tailSet(C fromElement) { + return tailSetImpl(checkNotNull(fromElement), true); + } + + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public ContiguousSet tailSet(C fromElement, boolean inclusive) { + return tailSetImpl(checkNotNull(fromElement), inclusive); + } + + /* @Override */ abstract ContiguousSet tailSetImpl(C fromElement, boolean inclusive); + /** * Returns a short-hand representation of the contents such as * {@code "[1..100]"}. @@ -182,18 +196,4 @@ public abstract class ContiguousSet extends ImmutableSorte public String toString() { return range().toString(); } - - /** - * Not supported. {@code ContiguousSet} instances are constructed with - * {@link #create}. This method exists only to hide {@link ImmutableSet#builder} - * from consumers of {@code - * ContiguousSet}. - * - * @throws UnsupportedOperationException always - * @deprecated Use {@link #create}. - */ - @Deprecated - public static ImmutableSortedSet.Builder builder() { - throw new UnsupportedOperationException(); - } } diff --git a/src/main/java/com/google/common/collect/Count.java b/src/main/java/com/google/common/collect/Count.java index ce9a3d32..58b904ff 100644 --- a/src/main/java/com/google/common/collect/Count.java +++ b/src/main/java/com/google/common/collect/Count.java @@ -34,6 +34,15 @@ final class Count implements Serializable { this.value = value; } + public int addAndGet(int delta) { + return value += delta; + } + + @Override + public boolean equals(@Nullable Object obj) { + return obj instanceof Count && ((Count) obj).value == value; + } + public int get() { return value; } @@ -44,14 +53,6 @@ final class Count implements Serializable { return result; } - public int addAndGet(int delta) { - return value += delta; - } - - public void set(int newValue) { - value = newValue; - } - public int getAndSet(int newValue) { int result = value; value = newValue; @@ -63,9 +64,8 @@ final class Count implements Serializable { return value; } - @Override - public boolean equals(@Nullable Object obj) { - return obj instanceof Count && ((Count) obj).value == value; + public void set(int newValue) { + value = newValue; } @Override diff --git a/src/main/java/com/google/common/collect/Cut.java b/src/main/java/com/google/common/collect/Cut.java index d45811b0..0d0ca92e 100644 --- a/src/main/java/com/google/common/collect/Cut.java +++ b/src/main/java/com/google/common/collect/Cut.java @@ -36,212 +36,18 @@ import com.google.common.primitives.Booleans; */ @GwtCompatible abstract class Cut implements Comparable>, Serializable { - final C endpoint; - - Cut(@Nullable C endpoint) { - this.endpoint = endpoint; - } - - abstract boolean isLessThan(C value); - - abstract BoundType typeAsLowerBound(); - - abstract BoundType typeAsUpperBound(); - - abstract Cut withLowerBoundType(BoundType boundType, DiscreteDomain domain); - - abstract Cut withUpperBoundType(BoundType boundType, DiscreteDomain domain); - - abstract void describeAsLowerBound(StringBuilder sb); - - abstract void describeAsUpperBound(StringBuilder sb); - - abstract C leastValueAbove(DiscreteDomain domain); - - abstract C greatestValueBelow(DiscreteDomain domain); - - /* - * The canonical form is a BelowValue cut whenever possible, otherwise - * ABOVE_ALL, or (only in the case of types that are unbounded below) BELOW_ALL. - */ - Cut canonical(DiscreteDomain domain) { - return this; - } - - // note: overriden by {BELOW,ABOVE}_ALL - @Override - public int compareTo(Cut that) { - if (that == belowAll()) { - return 1; - } - if (that == aboveAll()) { - return -1; - } - int result = Range.compareOrThrow(endpoint, that.endpoint); - if (result != 0) { - return result; - } - // same value. below comes before above - return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue); - } - - C endpoint() { - return endpoint; - } - - @SuppressWarnings("unchecked") // catching CCE - @Override - public boolean equals(Object obj) { - if (obj instanceof Cut) { - // It might not really be a Cut, but we'll catch a CCE if it's not - Cut that = (Cut) obj; - try { - int compareResult = compareTo(that); - return compareResult == 0; - } catch (ClassCastException ignored) { - } - } - return false; - } - - /* - * The implementation neither produces nor consumes any non-null instance of - * type C, so casting the type parameter is safe. - */ - @SuppressWarnings("unchecked") - static Cut belowAll() { - return (Cut) BelowAll.INSTANCE; - } - - private static final long serialVersionUID = 0; - - private static final class BelowAll extends Cut> { - private static final BelowAll INSTANCE = new BelowAll(); - - private BelowAll() { - super(null); - } - - @Override - Comparable endpoint() { - throw new IllegalStateException("range unbounded on this side"); - } - - @Override - boolean isLessThan(Comparable value) { - return true; - } - - @Override - BoundType typeAsLowerBound() { - throw new IllegalStateException(); - } - - @Override - BoundType typeAsUpperBound() { - throw new AssertionError("this statement should be unreachable"); - } - - @Override - Cut> withLowerBoundType(BoundType boundType, DiscreteDomain> domain) { - throw new IllegalStateException(); - } - - @Override - Cut> withUpperBoundType(BoundType boundType, DiscreteDomain> domain) { - throw new AssertionError("this statement should be unreachable"); - } - - @Override - void describeAsLowerBound(StringBuilder sb) { - sb.append("(-\u221e"); - } - - @Override - void describeAsUpperBound(StringBuilder sb) { - throw new AssertionError(); - } - - @Override - Comparable leastValueAbove(DiscreteDomain> domain) { - return domain.minValue(); - } - - @Override - Comparable greatestValueBelow(DiscreteDomain> domain) { - throw new AssertionError(); - } - - @Override - Cut> canonical(DiscreteDomain> domain) { - try { - return Cut.>belowValue(domain.minValue()); - } catch (NoSuchElementException e) { - return this; - } - } - - @Override - public int compareTo(Cut> o) { - return (o == this) ? 0 : -1; - } - - @Override - public String toString() { - return "-\u221e"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 0; - } - - /* - * The implementation neither produces nor consumes any non-null instance of - * type C, so casting the type parameter is safe. - */ - @SuppressWarnings("unchecked") - static Cut aboveAll() { - return (Cut) AboveAll.INSTANCE; - } - private static final class AboveAll extends Cut> { private static final AboveAll INSTANCE = new AboveAll(); + private static final long serialVersionUID = 0; + private AboveAll() { super(null); } @Override - Comparable endpoint() { - throw new IllegalStateException("range unbounded on this side"); - } - - @Override - boolean isLessThan(Comparable value) { - return false; - } - - @Override - BoundType typeAsLowerBound() { - throw new AssertionError("this statement should be unreachable"); - } - - @Override - BoundType typeAsUpperBound() { - throw new IllegalStateException(); - } - - @Override - Cut> withLowerBoundType(BoundType boundType, DiscreteDomain> domain) { - throw new AssertionError("this statement should be unreachable"); - } - - @Override - Cut> withUpperBoundType(BoundType boundType, DiscreteDomain> domain) { - throw new IllegalStateException(); + public int compareTo(Cut> o) { + return (o == this) ? 0 : 1; } @Override @@ -255,8 +61,8 @@ abstract class Cut implements Comparable>, Serializ } @Override - Comparable leastValueAbove(DiscreteDomain> domain) { - throw new AssertionError(); + Comparable endpoint() { + throw new IllegalStateException("range unbounded on this side"); } @Override @@ -265,8 +71,17 @@ abstract class Cut implements Comparable>, Serializ } @Override - public int compareTo(Cut> o) { - return (o == this) ? 0 : 1; + boolean isLessThan(Comparable value) { + return false; + } + + @Override + Comparable leastValueAbove(DiscreteDomain> domain) { + throw new AssertionError(); + } + + private Object readResolve() { + return INSTANCE; } @Override @@ -274,112 +89,75 @@ abstract class Cut implements Comparable>, Serializ return "+\u221e"; } - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 0; - } - - static Cut belowValue(C endpoint) { - return new BelowValue(endpoint); - } - - private static final class BelowValue extends Cut { - BelowValue(C endpoint) { - super(checkNotNull(endpoint)); - } - - @Override - boolean isLessThan(C value) { - return Range.compareOrThrow(endpoint, value) <= 0; - } - @Override BoundType typeAsLowerBound() { - return BoundType.CLOSED; + throw new AssertionError("this statement should be unreachable"); } @Override BoundType typeAsUpperBound() { - return BoundType.OPEN; + throw new IllegalStateException(); } @Override - Cut withLowerBoundType(BoundType boundType, DiscreteDomain domain) { - switch (boundType) { - case CLOSED: - return this; - case OPEN: - @Nullable - C previous = domain.previous(endpoint); - return (previous == null) ? Cut.belowAll() : new AboveValue(previous); - default: - throw new AssertionError(); - } + Cut> withLowerBoundType(BoundType boundType, DiscreteDomain> domain) { + throw new AssertionError("this statement should be unreachable"); } @Override - Cut withUpperBoundType(BoundType boundType, DiscreteDomain domain) { - switch (boundType) { - case CLOSED: - @Nullable - C previous = domain.previous(endpoint); - return (previous == null) ? Cut.aboveAll() : new AboveValue(previous); - case OPEN: - return this; - default: - throw new AssertionError(); - } + Cut> withUpperBoundType(BoundType boundType, DiscreteDomain> domain) { + throw new IllegalStateException(); } - - @Override - void describeAsLowerBound(StringBuilder sb) { - sb.append('[').append(endpoint); - } - - @Override - void describeAsUpperBound(StringBuilder sb) { - sb.append(endpoint).append(')'); - } - - @Override - C leastValueAbove(DiscreteDomain domain) { - return endpoint; - } - - @Override - C greatestValueBelow(DiscreteDomain domain) { - return domain.previous(endpoint); - } - - @Override - public int hashCode() { - return endpoint.hashCode(); - } - - @Override - public String toString() { - return "\\" + endpoint + "/"; - } - - private static final long serialVersionUID = 0; - } - - static Cut aboveValue(C endpoint) { - return new AboveValue(endpoint); } private static final class AboveValue extends Cut { + private static final long serialVersionUID = 0; + AboveValue(C endpoint) { super(checkNotNull(endpoint)); } + @Override + Cut canonical(DiscreteDomain domain) { + C next = leastValueAbove(domain); + return (next != null) ? belowValue(next) : Cut.aboveAll(); + } + + @Override + void describeAsLowerBound(StringBuilder sb) { + sb.append('(').append(endpoint); + } + + @Override + void describeAsUpperBound(StringBuilder sb) { + sb.append(endpoint).append(']'); + } + + @Override + C greatestValueBelow(DiscreteDomain domain) { + return endpoint; + } + + @Override + public int hashCode() { + return ~endpoint.hashCode(); + } + @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) < 0; } + @Override + C leastValueAbove(DiscreteDomain domain) { + return domain.next(endpoint); + } + + @Override + public String toString() { + return "/" + endpoint + "\\"; + } + @Override BoundType typeAsLowerBound() { return BoundType.OPEN; @@ -417,43 +195,265 @@ abstract class Cut implements Comparable>, Serializ throw new AssertionError(); } } + } + + private static final class BelowAll extends Cut> { + private static final BelowAll INSTANCE = new BelowAll(); + + private static final long serialVersionUID = 0; + + private BelowAll() { + super(null); + } + + @Override + Cut> canonical(DiscreteDomain> domain) { + try { + return Cut.>belowValue(domain.minValue()); + } catch (NoSuchElementException e) { + return this; + } + } + + @Override + public int compareTo(Cut> o) { + return (o == this) ? 0 : -1; + } @Override void describeAsLowerBound(StringBuilder sb) { - sb.append('(').append(endpoint); + sb.append("(-\u221e"); } @Override void describeAsUpperBound(StringBuilder sb) { - sb.append(endpoint).append(']'); + throw new AssertionError(); } @Override - C leastValueAbove(DiscreteDomain domain) { - return domain.next(endpoint); + Comparable endpoint() { + throw new IllegalStateException("range unbounded on this side"); } @Override - C greatestValueBelow(DiscreteDomain domain) { - return endpoint; + Comparable greatestValueBelow(DiscreteDomain> domain) { + throw new AssertionError(); } @Override - Cut canonical(DiscreteDomain domain) { - C next = leastValueAbove(domain); - return (next != null) ? belowValue(next) : Cut.aboveAll(); + boolean isLessThan(Comparable value) { + return true; } @Override - public int hashCode() { - return ~endpoint.hashCode(); + Comparable leastValueAbove(DiscreteDomain> domain) { + return domain.minValue(); + } + + private Object readResolve() { + return INSTANCE; } @Override public String toString() { - return "/" + endpoint + "\\"; + return "-\u221e"; } - private static final long serialVersionUID = 0; + @Override + BoundType typeAsLowerBound() { + throw new IllegalStateException(); + } + + @Override + BoundType typeAsUpperBound() { + throw new AssertionError("this statement should be unreachable"); + } + + @Override + Cut> withLowerBoundType(BoundType boundType, DiscreteDomain> domain) { + throw new IllegalStateException(); + } + + @Override + Cut> withUpperBoundType(BoundType boundType, DiscreteDomain> domain) { + throw new AssertionError("this statement should be unreachable"); + } } + + private static final class BelowValue extends Cut { + private static final long serialVersionUID = 0; + + BelowValue(C endpoint) { + super(checkNotNull(endpoint)); + } + + @Override + void describeAsLowerBound(StringBuilder sb) { + sb.append('[').append(endpoint); + } + + @Override + void describeAsUpperBound(StringBuilder sb) { + sb.append(endpoint).append(')'); + } + + @Override + C greatestValueBelow(DiscreteDomain domain) { + return domain.previous(endpoint); + } + + @Override + public int hashCode() { + return endpoint.hashCode(); + } + + @Override + boolean isLessThan(C value) { + return Range.compareOrThrow(endpoint, value) <= 0; + } + + @Override + C leastValueAbove(DiscreteDomain domain) { + return endpoint; + } + + @Override + public String toString() { + return "\\" + endpoint + "/"; + } + + @Override + BoundType typeAsLowerBound() { + return BoundType.CLOSED; + } + + @Override + BoundType typeAsUpperBound() { + return BoundType.OPEN; + } + + @Override + Cut withLowerBoundType(BoundType boundType, DiscreteDomain domain) { + switch (boundType) { + case CLOSED: + return this; + case OPEN: + @Nullable + C previous = domain.previous(endpoint); + return (previous == null) ? Cut.belowAll() : new AboveValue(previous); + default: + throw new AssertionError(); + } + } + + @Override + Cut withUpperBoundType(BoundType boundType, DiscreteDomain domain) { + switch (boundType) { + case CLOSED: + @Nullable + C previous = domain.previous(endpoint); + return (previous == null) ? Cut.aboveAll() : new AboveValue(previous); + case OPEN: + return this; + default: + throw new AssertionError(); + } + } + } + + private static final long serialVersionUID = 0; + + /* + * The implementation neither produces nor consumes any non-null instance of + * type C, so casting the type parameter is safe. + */ + @SuppressWarnings("unchecked") + static Cut aboveAll() { + return (Cut) AboveAll.INSTANCE; + } + + static Cut aboveValue(C endpoint) { + return new AboveValue(endpoint); + } + + /* + * The implementation neither produces nor consumes any non-null instance of + * type C, so casting the type parameter is safe. + */ + @SuppressWarnings("unchecked") + static Cut belowAll() { + return (Cut) BelowAll.INSTANCE; + } + + static Cut belowValue(C endpoint) { + return new BelowValue(endpoint); + } + + final C endpoint; + + Cut(@Nullable C endpoint) { + this.endpoint = endpoint; + } + + /* + * The canonical form is a BelowValue cut whenever possible, otherwise + * ABOVE_ALL, or (only in the case of types that are unbounded below) BELOW_ALL. + */ + Cut canonical(DiscreteDomain domain) { + return this; + } + + // note: overriden by {BELOW,ABOVE}_ALL + @Override + public int compareTo(Cut that) { + if (that == belowAll()) { + return 1; + } + if (that == aboveAll()) { + return -1; + } + int result = Range.compareOrThrow(endpoint, that.endpoint); + if (result != 0) { + return result; + } + // same value. below comes before above + return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue); + } + + abstract void describeAsLowerBound(StringBuilder sb); + + abstract void describeAsUpperBound(StringBuilder sb); + + C endpoint() { + return endpoint; + } + + @SuppressWarnings("unchecked") // catching CCE + @Override + public boolean equals(Object obj) { + if (obj instanceof Cut) { + // It might not really be a Cut, but we'll catch a CCE if it's not + Cut that = (Cut) obj; + try { + int compareResult = compareTo(that); + return compareResult == 0; + } catch (ClassCastException ignored) { + } + } + return false; + } + + abstract C greatestValueBelow(DiscreteDomain domain); + + abstract boolean isLessThan(C value); + + abstract C leastValueAbove(DiscreteDomain domain); + + abstract BoundType typeAsLowerBound(); + + abstract BoundType typeAsUpperBound(); + + abstract Cut withLowerBoundType(BoundType boundType, DiscreteDomain domain); + + abstract Cut withUpperBoundType(BoundType boundType, DiscreteDomain domain); } diff --git a/src/main/java/com/google/common/collect/DenseImmutableTable.java b/src/main/java/com/google/common/collect/DenseImmutableTable.java index 8e171a9d..7e3fa20a 100644 --- a/src/main/java/com/google/common/collect/DenseImmutableTable.java +++ b/src/main/java/com/google/common/collect/DenseImmutableTable.java @@ -29,15 +29,165 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible @Immutable final class DenseImmutableTable extends RegularImmutableTable { - private final ImmutableMap rowKeyToIndex; - private final ImmutableMap columnKeyToIndex; - private final ImmutableMap> rowMap; - private final ImmutableMap> columnMap; - private final int[] rowCounts; - private final int[] columnCounts; - private final V[][] values; - private final int[] iterationOrderRow; - private final int[] iterationOrderColumn; + private final class Column extends ImmutableArrayMap { + private final int columnIndex; + + Column(int columnIndex) { + super(columnCounts[columnIndex]); + this.columnIndex = columnIndex; + } + + @Override + V getValue(int keyIndex) { + return values[keyIndex][columnIndex]; + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + ImmutableMap keyToIndex() { + return rowKeyToIndex; + } + } + + private final class ColumnMap extends ImmutableArrayMap> { + private ColumnMap() { + super(columnCounts.length); + } + + @Override + Map getValue(int keyIndex) { + return new Column(keyIndex); + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + ImmutableMap keyToIndex() { + return columnKeyToIndex; + } + } + + /** + * An immutable map implementation backed by an indexed nullable array. + */ + private abstract static class ImmutableArrayMap extends ImmutableMap { + private final int size; + + ImmutableArrayMap(int size) { + this.size = size; + } + + @Override + ImmutableSet> createEntrySet() { + return new ImmutableMapEntrySet() { + @Override + public UnmodifiableIterator> iterator() { + return new AbstractIterator>() { + private int index = -1; + private final int maxIndex = keyToIndex().size(); + + @Override + protected Entry computeNext() { + for (index++; index < maxIndex; index++) { + V value = getValue(index); + if (value != null) { + return Maps.immutableEntry(getKey(index), value); + } + } + return endOfData(); + } + }; + } + + @Override + ImmutableMap map() { + return ImmutableArrayMap.this; + } + }; + } + + @Override + ImmutableSet createKeySet() { + return isFull() ? keyToIndex().keySet() : super.createKeySet(); + } + + @Override + public V get(@Nullable Object key) { + Integer keyIndex = keyToIndex().get(key); + return (keyIndex == null) ? null : getValue(keyIndex); + } + + K getKey(int index) { + return keyToIndex().keySet().asList().get(index); + } + + @Nullable + abstract V getValue(int keyIndex); + + // True if getValue never returns null. + private boolean isFull() { + return size == keyToIndex().size(); + } + + abstract ImmutableMap keyToIndex(); + + @Override + public int size() { + return size; + } + } + + private final class Row extends ImmutableArrayMap { + private final int rowIndex; + + Row(int rowIndex) { + super(rowCounts[rowIndex]); + this.rowIndex = rowIndex; + } + + @Override + V getValue(int keyIndex) { + return values[rowIndex][keyIndex]; + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + ImmutableMap keyToIndex() { + return columnKeyToIndex; + } + } + + private final class RowMap extends ImmutableArrayMap> { + private RowMap() { + super(rowCounts.length); + } + + @Override + Map getValue(int keyIndex) { + return new Row(keyIndex); + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + ImmutableMap keyToIndex() { + return rowKeyToIndex; + } + } private static ImmutableMap makeIndex(ImmutableSet set) { ImmutableMap.Builder indexBuilder = ImmutableMap.builder(); @@ -49,6 +199,22 @@ final class DenseImmutableTable extends RegularImmutableTable return indexBuilder.build(); } + private final ImmutableMap rowKeyToIndex; + private final ImmutableMap columnKeyToIndex; + private final ImmutableMap> rowMap; + + private final ImmutableMap> columnMap; + + private final int[] rowCounts; + + private final int[] columnCounts; + + private final V[][] values; + + private final int[] iterationOrderRow; + + private final int[] iterationOrderColumn; + DenseImmutableTable(ImmutableList> cellList, ImmutableSet rowSpace, ImmutableSet columnSpace) { @SuppressWarnings("unchecked") V[][] array = (V[][]) new Object[rowSpace.size()][columnSpace.size()]; @@ -79,176 +245,11 @@ final class DenseImmutableTable extends RegularImmutableTable this.columnMap = new ColumnMap(); } - /** - * An immutable map implementation backed by an indexed nullable array. - */ - private abstract static class ImmutableArrayMap extends ImmutableMap { - private final int size; - - ImmutableArrayMap(int size) { - this.size = size; - } - - abstract ImmutableMap keyToIndex(); - - // True if getValue never returns null. - private boolean isFull() { - return size == keyToIndex().size(); - } - - K getKey(int index) { - return keyToIndex().keySet().asList().get(index); - } - - @Nullable - abstract V getValue(int keyIndex); - - @Override - ImmutableSet createKeySet() { - return isFull() ? keyToIndex().keySet() : super.createKeySet(); - } - - @Override - public int size() { - return size; - } - - @Override - public V get(@Nullable Object key) { - Integer keyIndex = keyToIndex().get(key); - return (keyIndex == null) ? null : getValue(keyIndex); - } - - @Override - ImmutableSet> createEntrySet() { - return new ImmutableMapEntrySet() { - @Override - ImmutableMap map() { - return ImmutableArrayMap.this; - } - - @Override - public UnmodifiableIterator> iterator() { - return new AbstractIterator>() { - private int index = -1; - private final int maxIndex = keyToIndex().size(); - - @Override - protected Entry computeNext() { - for (index++; index < maxIndex; index++) { - V value = getValue(index); - if (value != null) { - return Maps.immutableEntry(getKey(index), value); - } - } - return endOfData(); - } - }; - } - }; - } - } - - private final class Row extends ImmutableArrayMap { - private final int rowIndex; - - Row(int rowIndex) { - super(rowCounts[rowIndex]); - this.rowIndex = rowIndex; - } - - @Override - ImmutableMap keyToIndex() { - return columnKeyToIndex; - } - - @Override - V getValue(int keyIndex) { - return values[rowIndex][keyIndex]; - } - - @Override - boolean isPartialView() { - return true; - } - } - - private final class Column extends ImmutableArrayMap { - private final int columnIndex; - - Column(int columnIndex) { - super(columnCounts[columnIndex]); - this.columnIndex = columnIndex; - } - - @Override - ImmutableMap keyToIndex() { - return rowKeyToIndex; - } - - @Override - V getValue(int keyIndex) { - return values[keyIndex][columnIndex]; - } - - @Override - boolean isPartialView() { - return true; - } - } - - private final class RowMap extends ImmutableArrayMap> { - private RowMap() { - super(rowCounts.length); - } - - @Override - ImmutableMap keyToIndex() { - return rowKeyToIndex; - } - - @Override - Map getValue(int keyIndex) { - return new Row(keyIndex); - } - - @Override - boolean isPartialView() { - return false; - } - } - - private final class ColumnMap extends ImmutableArrayMap> { - private ColumnMap() { - super(columnCounts.length); - } - - @Override - ImmutableMap keyToIndex() { - return columnKeyToIndex; - } - - @Override - Map getValue(int keyIndex) { - return new Column(keyIndex); - } - - @Override - boolean isPartialView() { - return false; - } - } - @Override public ImmutableMap> columnMap() { return columnMap; } - @Override - public ImmutableMap> rowMap() { - return rowMap; - } - @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); @@ -256,11 +257,6 @@ final class DenseImmutableTable extends RegularImmutableTable return ((rowIndex == null) || (columnIndex == null)) ? null : values[rowIndex][columnIndex]; } - @Override - public int size() { - return iterationOrderRow.length; - } - @Override Cell getCell(int index) { int rowIndex = iterationOrderRow[index]; @@ -275,4 +271,14 @@ final class DenseImmutableTable extends RegularImmutableTable V getValue(int index) { return values[iterationOrderRow[index]][iterationOrderColumn[index]]; } + + @Override + public ImmutableMap> rowMap() { + return rowMap; + } + + @Override + public int size() { + return iterationOrderRow.length; + } } diff --git a/src/main/java/com/google/common/collect/DescendingImmutableSortedMultiset.java b/src/main/java/com/google/common/collect/DescendingImmutableSortedMultiset.java index da2e2267..788b8705 100644 --- a/src/main/java/com/google/common/collect/DescendingImmutableSortedMultiset.java +++ b/src/main/java/com/google/common/collect/DescendingImmutableSortedMultiset.java @@ -34,11 +34,36 @@ final class DescendingImmutableSortedMultiset extends ImmutableSortedMultiset return forward.count(element); } + @Override + public ImmutableSortedMultiset descendingMultiset() { + return forward; + } + + @Override + public ImmutableSortedSet elementSet() { + return forward.elementSet().descendingSet(); + } + @Override public Entry firstEntry() { return forward.lastEntry(); } + @Override + Entry getEntry(int index) { + return forward.entrySet().asList().reverse().get(index); + } + + @Override + public ImmutableSortedMultiset headMultiset(E upperBound, BoundType boundType) { + return forward.tailMultiset(upperBound, boundType).descendingMultiset(); + } + + @Override + boolean isPartialView() { + return forward.isPartialView(); + } + @Override public Entry lastEntry() { return forward.firstEntry(); @@ -49,33 +74,8 @@ final class DescendingImmutableSortedMultiset extends ImmutableSortedMultiset return forward.size(); } - @Override - public ImmutableSortedSet elementSet() { - return forward.elementSet().descendingSet(); - } - - @Override - Entry getEntry(int index) { - return forward.entrySet().asList().reverse().get(index); - } - - @Override - public ImmutableSortedMultiset descendingMultiset() { - return forward; - } - - @Override - public ImmutableSortedMultiset headMultiset(E upperBound, BoundType boundType) { - return forward.tailMultiset(upperBound, boundType).descendingMultiset(); - } - @Override public ImmutableSortedMultiset tailMultiset(E lowerBound, BoundType boundType) { return forward.headMultiset(lowerBound, boundType).descendingMultiset(); } - - @Override - boolean isPartialView() { - return forward.isPartialView(); - } } diff --git a/src/main/java/com/google/common/collect/DescendingImmutableSortedSet.java b/src/main/java/com/google/common/collect/DescendingImmutableSortedSet.java index 003f31fb..cd28c604 100644 --- a/src/main/java/com/google/common/collect/DescendingImmutableSortedSet.java +++ b/src/main/java/com/google/common/collect/DescendingImmutableSortedSet.java @@ -34,34 +34,14 @@ class DescendingImmutableSortedSet extends ImmutableSortedSet { } @Override - public int size() { - return forward.size(); - } - - @Override - public UnmodifiableIterator iterator() { - return forward.descendingIterator(); - } - - @Override - ImmutableSortedSet headSetImpl(E toElement, boolean inclusive) { - return forward.tailSet(toElement, inclusive).descendingSet(); - } - - @Override - ImmutableSortedSet subSetImpl(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); - } - - @Override - ImmutableSortedSet tailSetImpl(E fromElement, boolean inclusive) { - return forward.headSet(fromElement, inclusive).descendingSet(); + public E ceiling(E element) { + return forward.floor(element); } @Override @GwtIncompatible("NavigableSet") - public ImmutableSortedSet descendingSet() { - return forward; + ImmutableSortedSet createDescendingSet() { + throw new AssertionError("should never be called"); } @Override @@ -72,13 +52,8 @@ class DescendingImmutableSortedSet extends ImmutableSortedSet { @Override @GwtIncompatible("NavigableSet") - ImmutableSortedSet createDescendingSet() { - throw new AssertionError("should never be called"); - } - - @Override - public E lower(E element) { - return forward.higher(element); + public ImmutableSortedSet descendingSet() { + return forward; } @Override @@ -87,8 +62,8 @@ class DescendingImmutableSortedSet extends ImmutableSortedSet { } @Override - public E ceiling(E element) { - return forward.floor(element); + ImmutableSortedSet headSetImpl(E toElement, boolean inclusive) { + return forward.tailSet(toElement, inclusive).descendingSet(); } @Override @@ -110,4 +85,29 @@ class DescendingImmutableSortedSet extends ImmutableSortedSet { boolean isPartialView() { return forward.isPartialView(); } + + @Override + public UnmodifiableIterator iterator() { + return forward.descendingIterator(); + } + + @Override + public E lower(E element) { + return forward.higher(element); + } + + @Override + public int size() { + return forward.size(); + } + + @Override + ImmutableSortedSet subSetImpl(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); + } + + @Override + ImmutableSortedSet tailSetImpl(E fromElement, boolean inclusive) { + return forward.headSet(fromElement, inclusive).descendingSet(); + } } diff --git a/src/main/java/com/google/common/collect/DescendingMultiset.java b/src/main/java/com/google/common/collect/DescendingMultiset.java index 449eb6f9..6876ac19 100644 --- a/src/main/java/com/google/common/collect/DescendingMultiset.java +++ b/src/main/java/com/google/common/collect/DescendingMultiset.java @@ -31,10 +31,12 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(emulated = true) abstract class DescendingMultiset extends ForwardingMultiset implements SortedMultiset { - abstract SortedMultiset forwardMultiset(); - private transient Comparator comparator; + private transient NavigableSet elementSet; + + private transient Set> entrySet; + @Override public Comparator comparator() { Comparator result = comparator; @@ -44,40 +46,23 @@ abstract class DescendingMultiset extends ForwardingMultiset implements So return result; } - private transient NavigableSet elementSet; + Set> createEntrySet() { + return new Multisets.EntrySet() { + @Override + public Iterator> iterator() { + return entryIterator(); + } - @Override - public NavigableSet elementSet() { - NavigableSet result = elementSet; - if (result == null) { - return elementSet = new SortedMultisets.NavigableElementSet(this); - } - return result; - } + @Override + Multiset multiset() { + return DescendingMultiset.this; + } - @Override - public Entry pollFirstEntry() { - return forwardMultiset().pollLastEntry(); - } - - @Override - public Entry pollLastEntry() { - return forwardMultiset().pollFirstEntry(); - } - - @Override - public SortedMultiset headMultiset(E toElement, BoundType boundType) { - return forwardMultiset().tailMultiset(toElement, boundType).descendingMultiset(); - } - - @Override - public SortedMultiset subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { - return forwardMultiset().subMultiset(toElement, toBoundType, fromElement, fromBoundType).descendingMultiset(); - } - - @Override - public SortedMultiset tailMultiset(E fromElement, BoundType boundType) { - return forwardMultiset().headMultiset(fromElement, boundType).descendingMultiset(); + @Override + public int size() { + return forwardMultiset().entrySet().size(); + } + }; } @Override @@ -91,42 +76,32 @@ abstract class DescendingMultiset extends ForwardingMultiset implements So } @Override - public Entry firstEntry() { - return forwardMultiset().lastEntry(); - } - - @Override - public Entry lastEntry() { - return forwardMultiset().firstEntry(); + public NavigableSet elementSet() { + NavigableSet result = elementSet; + if (result == null) { + return elementSet = new SortedMultisets.NavigableElementSet(this); + } + return result; } abstract Iterator> entryIterator(); - private transient Set> entrySet; - @Override public Set> entrySet() { Set> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } - Set> createEntrySet() { - return new Multisets.EntrySet() { - @Override - Multiset multiset() { - return DescendingMultiset.this; - } + @Override + public Entry firstEntry() { + return forwardMultiset().lastEntry(); + } - @Override - public Iterator> iterator() { - return entryIterator(); - } + abstract SortedMultiset forwardMultiset(); - @Override - public int size() { - return forwardMultiset().entrySet().size(); - } - }; + @Override + public SortedMultiset headMultiset(E toElement, BoundType boundType) { + return forwardMultiset().tailMultiset(toElement, boundType).descendingMultiset(); } @Override @@ -134,6 +109,31 @@ abstract class DescendingMultiset extends ForwardingMultiset implements So return Multisets.iteratorImpl(this); } + @Override + public Entry lastEntry() { + return forwardMultiset().firstEntry(); + } + + @Override + public Entry pollFirstEntry() { + return forwardMultiset().pollLastEntry(); + } + + @Override + public Entry pollLastEntry() { + return forwardMultiset().pollFirstEntry(); + } + + @Override + public SortedMultiset subMultiset(E fromElement, BoundType fromBoundType, E toElement, BoundType toBoundType) { + return forwardMultiset().subMultiset(toElement, toBoundType, fromElement, fromBoundType).descendingMultiset(); + } + + @Override + public SortedMultiset tailMultiset(E fromElement, BoundType boundType) { + return forwardMultiset().headMultiset(fromElement, boundType).descendingMultiset(); + } + @Override public Object[] toArray() { return standardToArray(); diff --git a/src/main/java/com/google/common/collect/DiscreteDomain.java b/src/main/java/com/google/common/collect/DiscreteDomain.java index 33c3bc3d..3e58bee8 100644 --- a/src/main/java/com/google/common/collect/DiscreteDomain.java +++ b/src/main/java/com/google/common/collect/DiscreteDomain.java @@ -47,18 +47,59 @@ import com.google.common.annotations.GwtCompatible; @Beta public abstract class DiscreteDomain { - /** - * Returns the discrete domain for values of type {@code Integer}. - * - * @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()}) - */ - public static DiscreteDomain integers() { - return IntegerDomain.INSTANCE; + private static final class BigIntegerDomain extends DiscreteDomain implements Serializable { + private static final BigIntegerDomain INSTANCE = new BigIntegerDomain(); + + private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); + private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); + + private static final long serialVersionUID = 0; + + @Override + public long distance(BigInteger start, BigInteger end) { + return end.subtract(start).max(MIN_LONG).min(MAX_LONG).longValue(); + } + + @Override + public BigInteger next(BigInteger value) { + return value.add(BigInteger.ONE); + } + + @Override + public BigInteger previous(BigInteger value) { + return value.subtract(BigInteger.ONE); + } + + private Object readResolve() { + return INSTANCE; + } + + @Override + public String toString() { + return "DiscreteDomain.bigIntegers()"; + } } private static final class IntegerDomain extends DiscreteDomain implements Serializable { private static final IntegerDomain INSTANCE = new IntegerDomain(); + private static final long serialVersionUID = 0; + + @Override + public long distance(Integer start, Integer end) { + return (long) end - start; + } + + @Override + public Integer maxValue() { + return Integer.MAX_VALUE; + } + + @Override + public Integer minValue() { + return Integer.MIN_VALUE; + } + @Override public Integer next(Integer value) { int i = value; @@ -71,21 +112,6 @@ public abstract class DiscreteDomain { return (i == Integer.MIN_VALUE) ? null : i - 1; } - @Override - public long distance(Integer start, Integer end) { - return (long) end - start; - } - - @Override - public Integer minValue() { - return Integer.MIN_VALUE; - } - - @Override - public Integer maxValue() { - return Integer.MAX_VALUE; - } - private Object readResolve() { return INSTANCE; } @@ -94,33 +120,12 @@ public abstract class DiscreteDomain { public String toString() { return "DiscreteDomain.integers()"; } - - private static final long serialVersionUID = 0; - } - - /** - * Returns the discrete domain for values of type {@code Long}. - * - * @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()}) - */ - public static DiscreteDomain longs() { - return LongDomain.INSTANCE; } private static final class LongDomain extends DiscreteDomain implements Serializable { private static final LongDomain INSTANCE = new LongDomain(); - @Override - public Long next(Long value) { - long l = value; - return (l == Long.MAX_VALUE) ? null : l + 1; - } - - @Override - public Long previous(Long value) { - long l = value; - return (l == Long.MIN_VALUE) ? null : l - 1; - } + private static final long serialVersionUID = 0; @Override public long distance(Long start, Long end) { @@ -134,14 +139,26 @@ public abstract class DiscreteDomain { return result; } + @Override + public Long maxValue() { + return Long.MAX_VALUE; + } + @Override public Long minValue() { return Long.MIN_VALUE; } @Override - public Long maxValue() { - return Long.MAX_VALUE; + public Long next(Long value) { + long l = value; + return (l == Long.MAX_VALUE) ? null : l + 1; + } + + @Override + public Long previous(Long value) { + long l = value; + return (l == Long.MIN_VALUE) ? null : l - 1; } private Object readResolve() { @@ -152,8 +169,6 @@ public abstract class DiscreteDomain { public String toString() { return "DiscreteDomain.longs()"; } - - private static final long serialVersionUID = 0; } /** @@ -165,43 +180,76 @@ public abstract class DiscreteDomain { return BigIntegerDomain.INSTANCE; } - private static final class BigIntegerDomain extends DiscreteDomain implements Serializable { - private static final BigIntegerDomain INSTANCE = new BigIntegerDomain(); + /** + * Returns the discrete domain for values of type {@code Integer}. + * + * @since 14.0 (since 10.0 as {@code DiscreteDomains.integers()}) + */ + public static DiscreteDomain integers() { + return IntegerDomain.INSTANCE; + } - private static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE); - private static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE); - - @Override - public BigInteger next(BigInteger value) { - return value.add(BigInteger.ONE); - } - - @Override - public BigInteger previous(BigInteger value) { - return value.subtract(BigInteger.ONE); - } - - @Override - public long distance(BigInteger start, BigInteger end) { - return end.subtract(start).max(MIN_LONG).min(MAX_LONG).longValue(); - } - - private Object readResolve() { - return INSTANCE; - } - - @Override - public String toString() { - return "DiscreteDomain.bigIntegers()"; - } - - private static final long serialVersionUID = 0; + /** + * Returns the discrete domain for values of type {@code Long}. + * + * @since 14.0 (since 10.0 as {@code DiscreteDomains.longs()}) + */ + public static DiscreteDomain longs() { + return LongDomain.INSTANCE; } /** Constructor for use by subclasses. */ protected DiscreteDomain() { } + /** + * Returns a signed value indicating how many nested invocations of + * {@link #next} (if positive) or {@link #previous} (if negative) are needed to + * reach {@code end} starting from {@code start}. For example, if {@code end = + * next(next(next(start)))}, then {@code distance(start, end) == 3} and {@code + * distance(end, start) == -3}. As well, {@code distance(a, a)} is always zero. + * + *

+ * Note that this function is necessarily well-defined for any discrete type. + * + * @return the distance as described above, or {@link Long#MIN_VALUE} or + * {@link Long#MAX_VALUE} if the distance is too small or too large, + * respectively. + */ + public abstract long distance(C start, C end); + + /** + * Returns the maximum value of type {@code C}, if it has one. The maximum value + * is the unique value for which {@link Comparable#compareTo(Object)} never + * returns a negative value for any input of type {@code C}. + * + *

+ * The default implementation throws {@code NoSuchElementException}. + * + * @return the maximum value of type {@code C}; never null + * @throws NoSuchElementException if the type has no (practical) maximum value; + * for example, {@link java.math.BigInteger} + */ + public C maxValue() { + throw new NoSuchElementException(); + } + + /** + * Returns the minimum value of type {@code C}, if it has one. The minimum value + * is the unique value for which {@link Comparable#compareTo(Object)} never + * returns a positive value for any input of type {@code C}. + * + *

+ * The default implementation throws {@code NoSuchElementException}. + * + * @return the minimum value of type {@code C}; never null + * @throws NoSuchElementException if the type has no (practical) minimum value; + * for example, {@link java.math.BigInteger} + */ + public C minValue() { + throw new NoSuchElementException(); + } + /** * Returns the unique least value of type {@code C} that is greater than * {@code value}, or {@code null} if none exists. Inverse operation to @@ -224,52 +272,4 @@ public abstract class DiscreteDomain { */ public abstract C previous(C value); - /** - * Returns a signed value indicating how many nested invocations of - * {@link #next} (if positive) or {@link #previous} (if negative) are needed to - * reach {@code end} starting from {@code start}. For example, if {@code end = - * next(next(next(start)))}, then {@code distance(start, end) == 3} and {@code - * distance(end, start) == -3}. As well, {@code distance(a, a)} is always zero. - * - *

- * Note that this function is necessarily well-defined for any discrete type. - * - * @return the distance as described above, or {@link Long#MIN_VALUE} or - * {@link Long#MAX_VALUE} if the distance is too small or too large, - * respectively. - */ - public abstract long distance(C start, C end); - - /** - * Returns the minimum value of type {@code C}, if it has one. The minimum value - * is the unique value for which {@link Comparable#compareTo(Object)} never - * returns a positive value for any input of type {@code C}. - * - *

- * The default implementation throws {@code NoSuchElementException}. - * - * @return the minimum value of type {@code C}; never null - * @throws NoSuchElementException if the type has no (practical) minimum value; - * for example, {@link java.math.BigInteger} - */ - public C minValue() { - throw new NoSuchElementException(); - } - - /** - * Returns the maximum value of type {@code C}, if it has one. The maximum value - * is the unique value for which {@link Comparable#compareTo(Object)} never - * returns a negative value for any input of type {@code C}. - * - *

- * The default implementation throws {@code NoSuchElementException}. - * - * @return the maximum value of type {@code C}; never null - * @throws NoSuchElementException if the type has no (practical) maximum value; - * for example, {@link java.math.BigInteger} - */ - public C maxValue() { - throw new NoSuchElementException(); - } - } diff --git a/src/main/java/com/google/common/collect/EmptyContiguousSet.java b/src/main/java/com/google/common/collect/EmptyContiguousSet.java index c3fd961c..08f1512f 100644 --- a/src/main/java/com/google/common/collect/EmptyContiguousSet.java +++ b/src/main/java/com/google/common/collect/EmptyContiguousSet.java @@ -30,23 +30,69 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class EmptyContiguousSet extends ContiguousSet { + @GwtIncompatible("serialization") + private static final class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + private final DiscreteDomain domain; + + private SerializedForm(DiscreteDomain domain) { + this.domain = domain; + } + + private Object readResolve() { + return new EmptyContiguousSet(domain); + } + } + EmptyContiguousSet(DiscreteDomain domain) { super(domain); } + @Override + public ImmutableList asList() { + return ImmutableList.of(); + } + + @GwtIncompatible("NavigableSet") + ImmutableSortedSet createDescendingSet() { + return new EmptyImmutableSortedSet(Ordering.natural().reverse()); + } + + @GwtIncompatible("NavigableSet") + @Override + public UnmodifiableIterator descendingIterator() { + return Iterators.emptyIterator(); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof Set) { + Set that = (Set) object; + return that.isEmpty(); + } + return false; + } + @Override public C first() { throw new NoSuchElementException(); } @Override - public C last() { - throw new NoSuchElementException(); + public int hashCode() { + return 0; } @Override - public int size() { - return 0; + ContiguousSet headSetImpl(C toElement, boolean inclusive) { + return this; + } + + @GwtIncompatible("not used by GWT emulation") + @Override + int indexOf(Object target) { + return -1; } @Override @@ -54,6 +100,26 @@ final class EmptyContiguousSet extends ContiguousSet { return this; } + @Override + public boolean isEmpty() { + return true; + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public UnmodifiableIterator iterator() { + return Iterators.emptyIterator(); + } + + @Override + public C last() { + throw new NoSuchElementException(); + } + @Override public Range range() { throw new NoSuchElementException(); @@ -65,8 +131,8 @@ final class EmptyContiguousSet extends ContiguousSet { } @Override - ContiguousSet headSetImpl(C toElement, boolean inclusive) { - return this; + public int size() { + return 0; } @Override @@ -79,80 +145,14 @@ final class EmptyContiguousSet extends ContiguousSet { return this; } - @GwtIncompatible("not used by GWT emulation") - @Override - int indexOf(Object target) { - return -1; - } - - @Override - public UnmodifiableIterator iterator() { - return Iterators.emptyIterator(); - } - - @GwtIncompatible("NavigableSet") - @Override - public UnmodifiableIterator descendingIterator() { - return Iterators.emptyIterator(); - } - - @Override - boolean isPartialView() { - return false; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public ImmutableList asList() { - return ImmutableList.of(); - } - @Override public String toString() { return "[]"; } - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof Set) { - Set that = (Set) object; - return that.isEmpty(); - } - return false; - } - - @Override - public int hashCode() { - return 0; - } - - @GwtIncompatible("serialization") - private static final class SerializedForm implements Serializable { - private final DiscreteDomain domain; - - private SerializedForm(DiscreteDomain domain) { - this.domain = domain; - } - - private Object readResolve() { - return new EmptyContiguousSet(domain); - } - - private static final long serialVersionUID = 0; - } - @GwtIncompatible("serialization") @Override Object writeReplace() { return new SerializedForm(domain); } - - @GwtIncompatible("NavigableSet") - ImmutableSortedSet createDescendingSet() { - return new EmptyImmutableSortedSet(Ordering.natural().reverse()); - } } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableBiMap.java b/src/main/java/com/google/common/collect/EmptyImmutableBiMap.java index 73604afe..4a1e7ce4 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableBiMap.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableBiMap.java @@ -34,28 +34,8 @@ final class EmptyImmutableBiMap extends ImmutableBiMap { } @Override - public ImmutableBiMap inverse() { - return this; - } - - @Override - public int size() { - return 0; - } - - @Override - public boolean isEmpty() { - return true; - } - - @Override - public Object get(@Nullable Object key) { - return null; - } - - @Override - public ImmutableSet> entrySet() { - return ImmutableSet.of(); + public ImmutableSetMultimap asMultimap() { + return ImmutableSetMultimap.of(); } @Override @@ -64,13 +44,23 @@ final class EmptyImmutableBiMap extends ImmutableBiMap { } @Override - public ImmutableSetMultimap asMultimap() { - return ImmutableSetMultimap.of(); + public ImmutableSet> entrySet() { + return ImmutableSet.of(); } @Override - public ImmutableSet keySet() { - return ImmutableSet.of(); + public Object get(@Nullable Object key) { + return null; + } + + @Override + public ImmutableBiMap inverse() { + return this; + } + + @Override + public boolean isEmpty() { + return true; } @Override @@ -78,7 +68,17 @@ final class EmptyImmutableBiMap extends ImmutableBiMap { return false; } + @Override + public ImmutableSet keySet() { + return ImmutableSet.of(); + } + Object readResolve() { return INSTANCE; // preserve singleton property } + + @Override + public int size() { + return 0; + } } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableListMultimap.java b/src/main/java/com/google/common/collect/EmptyImmutableListMultimap.java index 3cd20ef9..f397ffe8 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableListMultimap.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableListMultimap.java @@ -27,6 +27,8 @@ import com.google.common.annotations.GwtCompatible; class EmptyImmutableListMultimap extends ImmutableListMultimap { static final EmptyImmutableListMultimap INSTANCE = new EmptyImmutableListMultimap(); + private static final long serialVersionUID = 0; + private EmptyImmutableListMultimap() { super(ImmutableMap.>of(), 0); } @@ -34,6 +36,4 @@ class EmptyImmutableListMultimap extends ImmutableListMultimap { private Object readResolve() { return INSTANCE; // preserve singleton property } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableSet.java b/src/main/java/com/google/common/collect/EmptyImmutableSet.java index d047cd0c..062fb353 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableSet.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableSet.java @@ -32,17 +32,14 @@ import com.google.common.annotations.GwtCompatible; final class EmptyImmutableSet extends ImmutableSet { static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet(); + private static final long serialVersionUID = 0; + private EmptyImmutableSet() { } @Override - public int size() { - return 0; - } - - @Override - public boolean isEmpty() { - return true; + public ImmutableList asList() { + return ImmutableList.of(); } @Override @@ -55,26 +52,11 @@ final class EmptyImmutableSet extends ImmutableSet { return targets.isEmpty(); } - @Override - public UnmodifiableIterator iterator() { - return Iterators.emptyIterator(); - } - - @Override - boolean isPartialView() { - return false; - } - @Override int copyIntoArray(Object[] dst, int offset) { return offset; } - @Override - public ImmutableList asList() { - return ImmutableList.of(); - } - @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { @@ -89,19 +71,37 @@ final class EmptyImmutableSet extends ImmutableSet { return 0; } + @Override + public boolean isEmpty() { + return true; + } + @Override boolean isHashCodeFast() { return true; } @Override - public String toString() { - return "[]"; + boolean isPartialView() { + return false; + } + + @Override + public UnmodifiableIterator iterator() { + return Iterators.emptyIterator(); } Object readResolve() { return INSTANCE; // preserve singleton property } - private static final long serialVersionUID = 0; + @Override + public int size() { + return 0; + } + + @Override + public String toString() { + return "[]"; + } } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableSetMultimap.java b/src/main/java/com/google/common/collect/EmptyImmutableSetMultimap.java index abafa5a7..163eae3b 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableSetMultimap.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableSetMultimap.java @@ -27,6 +27,8 @@ import com.google.common.annotations.GwtCompatible; class EmptyImmutableSetMultimap extends ImmutableSetMultimap { static final EmptyImmutableSetMultimap INSTANCE = new EmptyImmutableSetMultimap(); + private static final long serialVersionUID = 0; + private EmptyImmutableSetMultimap() { super(ImmutableMap.>of(), 0, null); } @@ -34,6 +36,4 @@ class EmptyImmutableSetMultimap extends ImmutableSetMultimap { private Object readResolve() { return INSTANCE; // preserve singleton property } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableSortedMap.java b/src/main/java/com/google/common/collect/EmptyImmutableSortedMap.java index d25ff2c9..959f32b5 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableSortedMap.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableSortedMap.java @@ -42,11 +42,47 @@ final class EmptyImmutableSortedMap extends ImmutableSortedMap { this.keySet = ImmutableSortedSet.emptySet(comparator); } + @Override + public ImmutableSetMultimap asMultimap() { + return ImmutableSetMultimap.of(); + } + + @Override + ImmutableSortedMap createDescendingMap() { + return new EmptyImmutableSortedMap(Ordering.from(comparator()).reverse(), this); + } + + @Override + ImmutableSet> createEntrySet() { + throw new AssertionError("should never be called"); + } + + @Override + public ImmutableSet> entrySet() { + return ImmutableSet.of(); + } + @Override public V get(@Nullable Object key) { return null; } + @Override + public ImmutableSortedMap headMap(K toKey, boolean inclusive) { + checkNotNull(toKey); + return this; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + boolean isPartialView() { + return false; + } + @Override public ImmutableSortedSet keySet() { return keySet; @@ -58,13 +94,9 @@ final class EmptyImmutableSortedMap extends ImmutableSortedMap { } @Override - public boolean isEmpty() { - return true; - } - - @Override - public ImmutableCollection values() { - return ImmutableList.of(); + public ImmutableSortedMap tailMap(K fromKey, boolean inclusive) { + checkNotNull(fromKey); + return this; } @Override @@ -73,39 +105,7 @@ final class EmptyImmutableSortedMap extends ImmutableSortedMap { } @Override - boolean isPartialView() { - return false; - } - - @Override - public ImmutableSet> entrySet() { - return ImmutableSet.of(); - } - - @Override - ImmutableSet> createEntrySet() { - throw new AssertionError("should never be called"); - } - - @Override - public ImmutableSetMultimap asMultimap() { - return ImmutableSetMultimap.of(); - } - - @Override - public ImmutableSortedMap headMap(K toKey, boolean inclusive) { - checkNotNull(toKey); - return this; - } - - @Override - public ImmutableSortedMap tailMap(K fromKey, boolean inclusive) { - checkNotNull(fromKey); - return this; - } - - @Override - ImmutableSortedMap createDescendingMap() { - return new EmptyImmutableSortedMap(Ordering.from(comparator()).reverse(), this); + public ImmutableCollection values() { + return ImmutableList.of(); } } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableSortedMultiset.java b/src/main/java/com/google/common/collect/EmptyImmutableSortedMultiset.java index df290cb8..5868d79f 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableSortedMultiset.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableSortedMultiset.java @@ -35,18 +35,8 @@ final class EmptyImmutableSortedMultiset extends ImmutableSortedMultiset { } @Override - public Entry firstEntry() { - return null; - } - - @Override - public Entry lastEntry() { - return null; - } - - @Override - public int count(@Nullable Object element) { - return 0; + public ImmutableList asList() { + return ImmutableList.of(); } @Override @@ -55,7 +45,12 @@ final class EmptyImmutableSortedMultiset extends ImmutableSortedMultiset { } @Override - public int size() { + int copyIntoArray(Object[] dst, int offset) { + return offset; + } + + @Override + public int count(@Nullable Object element) { return 0; } @@ -64,6 +59,20 @@ final class EmptyImmutableSortedMultiset extends ImmutableSortedMultiset { return elementSet; } + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof Multiset) { + Multiset other = (Multiset) object; + return other.isEmpty(); + } + return false; + } + + @Override + public Entry firstEntry() { + return null; + } + @Override Entry getEntry(int index) { throw new AssertionError("should never be called"); @@ -77,10 +86,8 @@ final class EmptyImmutableSortedMultiset extends ImmutableSortedMultiset { } @Override - public ImmutableSortedMultiset tailMultiset(E lowerBound, BoundType boundType) { - checkNotNull(lowerBound); - checkNotNull(boundType); - return this; + boolean isPartialView() { + return false; } @Override @@ -89,26 +96,19 @@ final class EmptyImmutableSortedMultiset extends ImmutableSortedMultiset { } @Override - public boolean equals(@Nullable Object object) { - if (object instanceof Multiset) { - Multiset other = (Multiset) object; - return other.isEmpty(); - } - return false; + public Entry lastEntry() { + return null; } @Override - boolean isPartialView() { - return false; + public int size() { + return 0; } @Override - int copyIntoArray(Object[] dst, int offset) { - return offset; - } - - @Override - public ImmutableList asList() { - return ImmutableList.of(); + public ImmutableSortedMultiset tailMultiset(E lowerBound, BoundType boundType) { + checkNotNull(lowerBound); + checkNotNull(boundType); + return this; } } diff --git a/src/main/java/com/google/common/collect/EmptyImmutableSortedSet.java b/src/main/java/com/google/common/collect/EmptyImmutableSortedSet.java index 1d383e4e..b068ad85 100644 --- a/src/main/java/com/google/common/collect/EmptyImmutableSortedSet.java +++ b/src/main/java/com/google/common/collect/EmptyImmutableSortedSet.java @@ -39,13 +39,8 @@ class EmptyImmutableSortedSet extends ImmutableSortedSet { } @Override - public int size() { - return 0; - } - - @Override - public boolean isEmpty() { - return true; + public ImmutableList asList() { + return ImmutableList.of(); } @Override @@ -59,8 +54,13 @@ class EmptyImmutableSortedSet extends ImmutableSortedSet { } @Override - public UnmodifiableIterator iterator() { - return Iterators.emptyIterator(); + int copyIntoArray(Object[] dst, int offset) { + return offset; + } + + @Override + ImmutableSortedSet createDescendingSet() { + return new EmptyImmutableSortedSet(Ordering.from(comparator).reverse()); } @GwtIncompatible("NavigableSet") @@ -69,21 +69,6 @@ class EmptyImmutableSortedSet extends ImmutableSortedSet { return Iterators.emptyIterator(); } - @Override - boolean isPartialView() { - return false; - } - - @Override - public ImmutableList asList() { - return ImmutableList.of(); - } - - @Override - int copyIntoArray(Object[] dst, int offset) { - return offset; - } - @Override public boolean equals(@Nullable Object object) { if (object instanceof Set) { @@ -93,19 +78,39 @@ class EmptyImmutableSortedSet extends ImmutableSortedSet { return false; } + @Override + public E first() { + throw new NoSuchElementException(); + } + @Override public int hashCode() { return 0; } @Override - public String toString() { - return "[]"; + ImmutableSortedSet headSetImpl(E toElement, boolean inclusive) { + return this; } @Override - public E first() { - throw new NoSuchElementException(); + int indexOf(@Nullable Object target) { + return -1; + } + + @Override + public boolean isEmpty() { + return true; + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public UnmodifiableIterator iterator() { + return Iterators.emptyIterator(); } @Override @@ -114,8 +119,8 @@ class EmptyImmutableSortedSet extends ImmutableSortedSet { } @Override - ImmutableSortedSet headSetImpl(E toElement, boolean inclusive) { - return this; + public int size() { + return 0; } @Override @@ -129,12 +134,7 @@ class EmptyImmutableSortedSet extends ImmutableSortedSet { } @Override - int indexOf(@Nullable Object target) { - return -1; - } - - @Override - ImmutableSortedSet createDescendingSet() { - return new EmptyImmutableSortedSet(Ordering.from(comparator).reverse()); + public String toString() { + return "[]"; } } diff --git a/src/main/java/com/google/common/collect/EnumBiMap.java b/src/main/java/com/google/common/collect/EnumBiMap.java index ffec2ead..624376e3 100644 --- a/src/main/java/com/google/common/collect/EnumBiMap.java +++ b/src/main/java/com/google/common/collect/EnumBiMap.java @@ -43,8 +43,8 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) public final class EnumBiMap, V extends Enum> extends AbstractBiMap { - private transient Class keyType; - private transient Class valueType; + @GwtIncompatible("not needed in emulated source.") + private static final long serialVersionUID = 0; /** * Returns a new, empty {@code EnumBiMap} using the specified key and value @@ -73,12 +73,6 @@ public final class EnumBiMap, V extends Enum> extends Abstr return bimap; } - private EnumBiMap(Class keyType, Class valueType) { - super(WellBehavedMap.wrap(new EnumMap(keyType)), WellBehavedMap.wrap(new EnumMap(valueType))); - this.keyType = keyType; - this.valueType = valueType; - } - static > Class inferKeyType(Map map) { if (map instanceof EnumBiMap) { return ((EnumBiMap) map).keyType(); @@ -98,14 +92,14 @@ public final class EnumBiMap, V extends Enum> extends Abstr return map.values().iterator().next().getDeclaringClass(); } - /** Returns the associated key type. */ - public Class keyType() { - return keyType; - } + private transient Class keyType; - /** Returns the associated value type. */ - public Class valueType() { - return valueType; + private transient Class valueType; + + private EnumBiMap(Class keyType, Class valueType) { + super(WellBehavedMap.wrap(new EnumMap(keyType)), WellBehavedMap.wrap(new EnumMap(valueType))); + this.keyType = keyType; + this.valueType = valueType; } @Override @@ -118,16 +112,9 @@ public final class EnumBiMap, V extends Enum> extends Abstr return checkNotNull(value); } - /** - * @serialData the key class, value class, number of entries, first key, first - * value, second key, second value, and so on. - */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(keyType); - stream.writeObject(valueType); - Serialization.writeMap(this, stream); + /** Returns the associated key type. */ + public Class keyType() { + return keyType; } @SuppressWarnings("unchecked") // reading fields populated by writeObject @@ -141,6 +128,20 @@ public final class EnumBiMap, V extends Enum> extends Abstr Serialization.populateMap(this, stream); } - @GwtIncompatible("not needed in emulated source.") - private static final long serialVersionUID = 0; + /** Returns the associated value type. */ + public Class valueType() { + return valueType; + } + + /** + * @serialData the key class, value class, number of entries, first key, first + * value, second key, second value, and so on. + */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(keyType); + stream.writeObject(valueType); + Serialization.writeMap(this, stream); + } } diff --git a/src/main/java/com/google/common/collect/EnumHashBiMap.java b/src/main/java/com/google/common/collect/EnumHashBiMap.java index 8ebb4fc9..9af77207 100644 --- a/src/main/java/com/google/common/collect/EnumHashBiMap.java +++ b/src/main/java/com/google/common/collect/EnumHashBiMap.java @@ -46,7 +46,8 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) public final class EnumHashBiMap, V> extends AbstractBiMap { - private transient Class keyType; + @GwtIncompatible("only needed in emulated source.") + private static final long serialVersionUID = 0; /** * Returns a new, empty {@code EnumHashBiMap} using the specified key type. @@ -74,24 +75,21 @@ public final class EnumHashBiMap, V> extends AbstractBiMap keyType; + + // Overriding these 3 methods to show that values may be null (but not keys) + private EnumHashBiMap(Class keyType) { super(WellBehavedMap.wrap(new EnumMap(keyType)), Maps.newHashMapWithExpectedSize(keyType.getEnumConstants().length)); this.keyType = keyType; } - // Overriding these 3 methods to show that values may be null (but not keys) - @Override K checkKey(K key) { return checkNotNull(key); } - @Override - public V put(K key, @Nullable V value) { - return super.put(key, value); - } - @Override public V forcePut(K key, @Nullable V value) { return super.forcePut(key, value); @@ -102,15 +100,9 @@ public final class EnumHashBiMap, V> extends AbstractBiMap, V> extends AbstractBiMap> extends AbstractMapBasedMultiset { + @GwtIncompatible("Not needed in emulated source") + private static final long serialVersionUID = 0; + /** Creates an empty {@code EnumMultiset}. */ public static > EnumMultiset create(Class type) { return new EnumMultiset(type); @@ -82,13 +85,6 @@ public final class EnumMultiset> extends AbstractMapBasedMulti this.type = type; } - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(type); - Serialization.writeMultiset(this, stream); - } - /** * @serialData the {@code Class} for the enum type, the number of distinct * elements, the first element, its count, the second element, its @@ -104,6 +100,10 @@ public final class EnumMultiset> extends AbstractMapBasedMulti Serialization.populateMultiset(this, stream); } - @GwtIncompatible("Not needed in emulated source") - private static final long serialVersionUID = 0; + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(type); + Serialization.writeMultiset(this, stream); + } } diff --git a/src/main/java/com/google/common/collect/EvictingQueue.java b/src/main/java/com/google/common/collect/EvictingQueue.java index dfd4094f..2664d57b 100644 --- a/src/main/java/com/google/common/collect/EvictingQueue.java +++ b/src/main/java/com/google/common/collect/EvictingQueue.java @@ -48,16 +48,7 @@ import com.google.common.annotations.VisibleForTesting; @GwtIncompatible("java.util.ArrayDeque") public final class EvictingQueue extends ForwardingQueue implements Serializable { - private final Queue delegate; - - @VisibleForTesting - final int maxSize; - - private EvictingQueue(int maxSize) { - checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize); - this.delegate = new ArrayDeque(maxSize); - this.maxSize = maxSize; - } + private static final long serialVersionUID = 0L; /** * Creates and returns a new evicting queue that will hold up to {@code maxSize} @@ -71,30 +62,15 @@ public final class EvictingQueue extends ForwardingQueue implements Serial return new EvictingQueue(maxSize); } - /** - * Returns the number of additional elements that this queue can accept without - * evicting; zero if the queue is currently full. - * - * @since 16.0 - */ - public int remainingCapacity() { - return maxSize - size(); - } + private final Queue delegate; - @Override - protected Queue delegate() { - return delegate; - } + @VisibleForTesting + final int maxSize; - /** - * Adds the given element to this queue. If the queue is currently full, the - * element at the head of the queue is evicted to make room. - * - * @return {@code true} always - */ - @Override - public boolean offer(E e) { - return add(e); + private EvictingQueue(int maxSize) { + checkArgument(maxSize >= 0, "maxSize (%s) must >= 0", maxSize); + this.delegate = new ArrayDeque(maxSize); + this.maxSize = maxSize; } /** @@ -127,12 +103,36 @@ public final class EvictingQueue extends ForwardingQueue implements Serial } @Override - public boolean remove(Object object) { - return delegate().remove(checkNotNull(object)); + protected Queue delegate() { + return delegate; + } + + /** + * Adds the given element to this queue. If the queue is currently full, the + * element at the head of the queue is evicted to make room. + * + * @return {@code true} always + */ + @Override + public boolean offer(E e) { + return add(e); + } + + /** + * Returns the number of additional elements that this queue can accept without + * evicting; zero if the queue is currently full. + * + * @since 16.0 + */ + public int remainingCapacity() { + return maxSize - size(); } // TODO(user): Do we want to checkNotNull each element in containsAll, // removeAll, and retainAll? - private static final long serialVersionUID = 0L; + @Override + public boolean remove(Object object) { + return delegate().remove(checkNotNull(object)); + } } diff --git a/src/main/java/com/google/common/collect/ExplicitOrdering.java b/src/main/java/com/google/common/collect/ExplicitOrdering.java index 07e99f0c..1a6747e3 100644 --- a/src/main/java/com/google/common/collect/ExplicitOrdering.java +++ b/src/main/java/com/google/common/collect/ExplicitOrdering.java @@ -26,28 +26,7 @@ import com.google.common.annotations.GwtCompatible; /** An ordering that compares objects according to a given order. */ @GwtCompatible(serializable = true) final class ExplicitOrdering extends Ordering implements Serializable { - final ImmutableMap rankMap; - - ExplicitOrdering(List valuesInOrder) { - this(buildRankMap(valuesInOrder)); - } - - ExplicitOrdering(ImmutableMap rankMap) { - this.rankMap = rankMap; - } - - @Override - public int compare(T left, T right) { - return rank(left) - rank(right); // safe because both are nonnegative - } - - private int rank(T value) { - Integer rank = rankMap.get(value); - if (rank == null) { - throw new IncomparableValueException(value); - } - return rank; - } + private static final long serialVersionUID = 0; private static ImmutableMap buildRankMap(List valuesInOrder) { ImmutableMap.Builder builder = ImmutableMap.builder(); @@ -58,6 +37,21 @@ final class ExplicitOrdering extends Ordering implements Serializable { return builder.build(); } + final ImmutableMap rankMap; + + ExplicitOrdering(ImmutableMap rankMap) { + this.rankMap = rankMap; + } + + ExplicitOrdering(List valuesInOrder) { + this(buildRankMap(valuesInOrder)); + } + + @Override + public int compare(T left, T right) { + return rank(left) - rank(right); // safe because both are nonnegative + } + @Override public boolean equals(@Nullable Object object) { if (object instanceof ExplicitOrdering) { @@ -72,10 +66,16 @@ final class ExplicitOrdering extends Ordering implements Serializable { return rankMap.hashCode(); } + private int rank(T value) { + Integer rank = rankMap.get(value); + if (rank == null) { + throw new IncomparableValueException(value); + } + return rank; + } + @Override public String toString() { return "Ordering.explicit(" + rankMap.keySet() + ")"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/FilteredEntryMultimap.java b/src/main/java/com/google/common/collect/FilteredEntryMultimap.java index 677d5b73..d0f549ec 100644 --- a/src/main/java/com/google/common/collect/FilteredEntryMultimap.java +++ b/src/main/java/com/google/common/collect/FilteredEntryMultimap.java @@ -44,200 +44,20 @@ import com.google.common.collect.Maps.ImprovedAbstractMap; */ @GwtCompatible class FilteredEntryMultimap extends AbstractMultimap implements FilteredMultimap { - final Multimap unfiltered; - final Predicate> predicate; - - FilteredEntryMultimap(Multimap unfiltered, Predicate> predicate) { - this.unfiltered = checkNotNull(unfiltered); - this.predicate = checkNotNull(predicate); - } - - @Override - public Multimap unfiltered() { - return unfiltered; - } - - @Override - public Predicate> entryPredicate() { - return predicate; - } - - @Override - public int size() { - return entries().size(); - } - - private boolean satisfies(K key, V value) { - return predicate.apply(Maps.immutableEntry(key, value)); - } - - final class ValuePredicate implements Predicate { - private final K key; - - ValuePredicate(K key) { - this.key = key; - } - - @Override - public boolean apply(@Nullable V value) { - return satisfies(key, value); - } - } - - static Collection filterCollection(Collection collection, Predicate predicate) { - if (collection instanceof Set) { - return Sets.filter((Set) collection, predicate); - } else { - return Collections2.filter(collection, predicate); - } - } - - @Override - public boolean containsKey(@Nullable Object key) { - return asMap().get(key) != null; - } - - @Override - public Collection removeAll(@Nullable Object key) { - return Objects.firstNonNull(asMap().remove(key), unmodifiableEmptyCollection()); - } - - Collection unmodifiableEmptyCollection() { - // These return false, rather than throwing a UOE, on remove calls. - return (unfiltered instanceof SetMultimap) ? Collections.emptySet() : Collections.emptyList(); - } - - @Override - public void clear() { - entries().clear(); - } - - @Override - public Collection get(final K key) { - return filterCollection(unfiltered.get(key), new ValuePredicate(key)); - } - - @Override - Collection> createEntries() { - return filterCollection(unfiltered.entries(), predicate); - } - - @Override - Collection createValues() { - return new FilteredMultimapValues(this); - } - - @Override - Iterator> entryIterator() { - throw new AssertionError("should never be called"); - } - - @Override - Map> createAsMap() { - return new AsMap(); - } - - @Override - public Set keySet() { - return asMap().keySet(); - } - - boolean removeEntriesIf(Predicate>> predicate) { - Iterator>> entryIterator = unfiltered.asMap().entrySet().iterator(); - boolean changed = false; - while (entryIterator.hasNext()) { - Entry> entry = entryIterator.next(); - K key = entry.getKey(); - Collection collection = filterCollection(entry.getValue(), new ValuePredicate(key)); - if (!collection.isEmpty() && predicate.apply(Maps.immutableEntry(key, collection))) { - if (collection.size() == entry.getValue().size()) { - entryIterator.remove(); - } else { - collection.clear(); - } - changed = true; - } - } - return changed; - } - class AsMap extends ImprovedAbstractMap> { - @Override - public boolean containsKey(@Nullable Object key) { - return get(key) != null; - } - @Override public void clear() { FilteredEntryMultimap.this.clear(); } @Override - public Collection get(@Nullable Object key) { - Collection result = unfiltered.asMap().get(key); - if (result == null) { - return null; - } - @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself - K k = (K) key; - result = filterCollection(result, new ValuePredicate(k)); - return result.isEmpty() ? null : result; - } - - @Override - public Collection remove(@Nullable Object key) { - Collection collection = unfiltered.asMap().get(key); - if (collection == null) { - return null; - } - @SuppressWarnings("unchecked") // it's definitely equal to a K - K k = (K) key; - List result = Lists.newArrayList(); - Iterator itr = collection.iterator(); - while (itr.hasNext()) { - V v = itr.next(); - if (satisfies(k, v)) { - itr.remove(); - result.add(v); - } - } - if (result.isEmpty()) { - return null; - } else if (unfiltered instanceof SetMultimap) { - return Collections.unmodifiableSet(Sets.newLinkedHashSet(result)); - } else { - return Collections.unmodifiableList(result); - } - } - - @Override - Set createKeySet() { - return new Maps.KeySet>(this) { - @Override - public boolean removeAll(Collection c) { - return removeEntriesIf(Maps.keyPredicateOnEntries(in(c))); - } - - @Override - public boolean retainAll(Collection c) { - return removeEntriesIf(Maps.keyPredicateOnEntries(not(in(c)))); - } - - @Override - public boolean remove(@Nullable Object o) { - return AsMap.this.remove(o) != null; - } - }; + public boolean containsKey(@Nullable Object key) { + return get(key) != null; } @Override Set>> createEntrySet() { return new Maps.EntrySet>() { - @Override - Map> map() { - return AsMap.this; - } - @Override public Iterator>> iterator() { return new AbstractIterator>>() { @@ -259,6 +79,11 @@ class FilteredEntryMultimap extends AbstractMultimap implements Filt }; } + @Override + Map> map() { + return AsMap.this; + } + @Override public boolean removeAll(Collection c) { return removeEntriesIf(in(c)); @@ -276,6 +101,26 @@ class FilteredEntryMultimap extends AbstractMultimap implements Filt }; } + @Override + Set createKeySet() { + return new Maps.KeySet>(this) { + @Override + public boolean remove(@Nullable Object o) { + return AsMap.this.remove(o) != null; + } + + @Override + public boolean removeAll(Collection c) { + return removeEntriesIf(Maps.keyPredicateOnEntries(in(c))); + } + + @Override + public boolean retainAll(Collection c) { + return removeEntriesIf(Maps.keyPredicateOnEntries(not(in(c)))); + } + }; + } + @Override Collection> createValues() { return new Maps.Values>(AsMap.this) { @@ -312,11 +157,44 @@ class FilteredEntryMultimap extends AbstractMultimap implements Filt } }; } - } - @Override - Multiset createKeys() { - return new Keys(); + @Override + public Collection get(@Nullable Object key) { + Collection result = unfiltered.asMap().get(key); + if (result == null) { + return null; + } + @SuppressWarnings("unchecked") // key is equal to a K, if not a K itself + K k = (K) key; + result = filterCollection(result, new ValuePredicate(k)); + return result.isEmpty() ? null : result; + } + + @Override + public Collection remove(@Nullable Object key) { + Collection collection = unfiltered.asMap().get(key); + if (collection == null) { + return null; + } + @SuppressWarnings("unchecked") // it's definitely equal to a K + K k = (K) key; + List result = Lists.newArrayList(); + Iterator itr = collection.iterator(); + while (itr.hasNext()) { + V v = itr.next(); + if (satisfies(k, v)) { + itr.remove(); + result.add(v); + } + } + if (result.isEmpty()) { + return null; + } else if (unfiltered instanceof SetMultimap) { + return Collections.unmodifiableSet(Sets.newLinkedHashSet(result)); + } else { + return Collections.unmodifiableList(result); + } + } } class Keys extends Multimaps.Keys { @@ -324,6 +202,46 @@ class FilteredEntryMultimap extends AbstractMultimap implements Filt super(FilteredEntryMultimap.this); } + @Override + public Set> entrySet() { + return new Multisets.EntrySet() { + + @Override + public Iterator> iterator() { + return Keys.this.entryIterator(); + } + + @Override + Multiset multiset() { + return Keys.this; + } + + @Override + public boolean removeAll(Collection c) { + return removeEntriesIf(in(c)); + } + + private boolean removeEntriesIf(final Predicate> predicate) { + return FilteredEntryMultimap.this.removeEntriesIf(new Predicate>>() { + @Override + public boolean apply(Map.Entry> entry) { + return predicate.apply(Multisets.immutableEntry(entry.getKey(), entry.getValue().size())); + } + }); + } + + @Override + public boolean retainAll(Collection c) { + return removeEntriesIf(not(in(c))); + } + + @Override + public int size() { + return FilteredEntryMultimap.this.keySet().size(); + } + }; + } + @Override public int remove(@Nullable Object key, int occurrences) { checkNonnegative(occurrences, "occurrences"); @@ -349,45 +267,128 @@ class FilteredEntryMultimap extends AbstractMultimap implements Filt } return oldCount; } + } + + final class ValuePredicate implements Predicate { + private final K key; + + ValuePredicate(K key) { + this.key = key; + } @Override - public Set> entrySet() { - return new Multisets.EntrySet() { - - @Override - Multiset multiset() { - return Keys.this; - } - - @Override - public Iterator> iterator() { - return Keys.this.entryIterator(); - } - - @Override - public int size() { - return FilteredEntryMultimap.this.keySet().size(); - } - - private boolean removeEntriesIf(final Predicate> predicate) { - return FilteredEntryMultimap.this.removeEntriesIf(new Predicate>>() { - @Override - public boolean apply(Map.Entry> entry) { - return predicate.apply(Multisets.immutableEntry(entry.getKey(), entry.getValue().size())); - } - }); - } - - @Override - public boolean removeAll(Collection c) { - return removeEntriesIf(in(c)); - } - - @Override - public boolean retainAll(Collection c) { - return removeEntriesIf(not(in(c))); - } - }; + public boolean apply(@Nullable V value) { + return satisfies(key, value); } } + + static Collection filterCollection(Collection collection, Predicate predicate) { + if (collection instanceof Set) { + return Sets.filter((Set) collection, predicate); + } else { + return Collections2.filter(collection, predicate); + } + } + + final Multimap unfiltered; + + final Predicate> predicate; + + FilteredEntryMultimap(Multimap unfiltered, Predicate> predicate) { + this.unfiltered = checkNotNull(unfiltered); + this.predicate = checkNotNull(predicate); + } + + @Override + public void clear() { + entries().clear(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return asMap().get(key) != null; + } + + @Override + Map> createAsMap() { + return new AsMap(); + } + + @Override + Collection> createEntries() { + return filterCollection(unfiltered.entries(), predicate); + } + + @Override + Multiset createKeys() { + return new Keys(); + } + + @Override + Collection createValues() { + return new FilteredMultimapValues(this); + } + + @Override + Iterator> entryIterator() { + throw new AssertionError("should never be called"); + } + + @Override + public Predicate> entryPredicate() { + return predicate; + } + + @Override + public Collection get(final K key) { + return filterCollection(unfiltered.get(key), new ValuePredicate(key)); + } + + @Override + public Set keySet() { + return asMap().keySet(); + } + + @Override + public Collection removeAll(@Nullable Object key) { + return Objects.firstNonNull(asMap().remove(key), unmodifiableEmptyCollection()); + } + + boolean removeEntriesIf(Predicate>> predicate) { + Iterator>> entryIterator = unfiltered.asMap().entrySet().iterator(); + boolean changed = false; + while (entryIterator.hasNext()) { + Entry> entry = entryIterator.next(); + K key = entry.getKey(); + Collection collection = filterCollection(entry.getValue(), new ValuePredicate(key)); + if (!collection.isEmpty() && predicate.apply(Maps.immutableEntry(key, collection))) { + if (collection.size() == entry.getValue().size()) { + entryIterator.remove(); + } else { + collection.clear(); + } + changed = true; + } + } + return changed; + } + + private boolean satisfies(K key, V value) { + return predicate.apply(Maps.immutableEntry(key, value)); + } + + @Override + public int size() { + return entries().size(); + } + + @Override + public Multimap unfiltered() { + return unfiltered; + } + + Collection unmodifiableEmptyCollection() { + // These return false, rather than throwing a UOE, on remove calls. + return (unfiltered instanceof SetMultimap) ? Collections.emptySet() : Collections.emptyList(); + } } diff --git a/src/main/java/com/google/common/collect/FilteredEntrySetMultimap.java b/src/main/java/com/google/common/collect/FilteredEntrySetMultimap.java index 9bc9016c..44c3ade4 100644 --- a/src/main/java/com/google/common/collect/FilteredEntrySetMultimap.java +++ b/src/main/java/com/google/common/collect/FilteredEntrySetMultimap.java @@ -35,8 +35,13 @@ final class FilteredEntrySetMultimap extends FilteredEntryMultimap i } @Override - public SetMultimap unfiltered() { - return (SetMultimap) unfiltered; + Set> createEntries() { + return Sets.filter(unfiltered().entries(), entryPredicate()); + } + + @Override + public Set> entries() { + return (Set>) super.entries(); } @Override @@ -55,12 +60,7 @@ final class FilteredEntrySetMultimap extends FilteredEntryMultimap i } @Override - Set> createEntries() { - return Sets.filter(unfiltered().entries(), entryPredicate()); - } - - @Override - public Set> entries() { - return (Set>) super.entries(); + public SetMultimap unfiltered() { + return (SetMultimap) unfiltered; } } diff --git a/src/main/java/com/google/common/collect/FilteredKeyListMultimap.java b/src/main/java/com/google/common/collect/FilteredKeyListMultimap.java index 5742c42e..d64a8c77 100644 --- a/src/main/java/com/google/common/collect/FilteredKeyListMultimap.java +++ b/src/main/java/com/google/common/collect/FilteredKeyListMultimap.java @@ -34,11 +34,6 @@ final class FilteredKeyListMultimap extends FilteredKeyMultimap impl super(unfiltered, keyPredicate); } - @Override - public ListMultimap unfiltered() { - return (ListMultimap) super.unfiltered(); - } - @Override public List get(K key) { return (List) super.get(key); @@ -53,4 +48,9 @@ final class FilteredKeyListMultimap extends FilteredKeyMultimap impl public List replaceValues(K key, Iterable values) { return (List) super.replaceValues(key, values); } + + @Override + public ListMultimap unfiltered() { + return (ListMultimap) super.unfiltered(); + } } diff --git a/src/main/java/com/google/common/collect/FilteredKeyMultimap.java b/src/main/java/com/google/common/collect/FilteredKeyMultimap.java index c8fa782b..2e0e1b1a 100644 --- a/src/main/java/com/google/common/collect/FilteredKeyMultimap.java +++ b/src/main/java/com/google/common/collect/FilteredKeyMultimap.java @@ -37,74 +37,41 @@ import com.google.common.base.Predicate; */ @GwtCompatible class FilteredKeyMultimap extends AbstractMultimap implements FilteredMultimap { - final Multimap unfiltered; - final Predicate keyPredicate; + static class AddRejectingList extends ForwardingList { + final K key; - FilteredKeyMultimap(Multimap unfiltered, Predicate keyPredicate) { - this.unfiltered = checkNotNull(unfiltered); - this.keyPredicate = checkNotNull(keyPredicate); - } - - @Override - public Multimap unfiltered() { - return unfiltered; - } - - @Override - public Predicate> entryPredicate() { - return Maps.keyPredicateOnEntries(keyPredicate); - } - - @Override - public int size() { - int size = 0; - for (Collection collection : asMap().values()) { - size += collection.size(); + AddRejectingList(K key) { + this.key = key; } - return size; - } - @Override - public boolean containsKey(@Nullable Object key) { - if (unfiltered.containsKey(key)) { - @SuppressWarnings("unchecked") // k is equal to a K, if not one itself - K k = (K) key; - return keyPredicate.apply(k); + @Override + public void add(int index, V element) { + checkPositionIndex(index, 0); + throw new IllegalArgumentException("Key does not satisfy predicate: " + key); } - return false; - } - @Override - public Collection removeAll(Object key) { - return containsKey(key) ? unfiltered.removeAll(key) : unmodifiableEmptyCollection(); - } - - Collection unmodifiableEmptyCollection() { - if (unfiltered instanceof SetMultimap) { - return ImmutableSet.of(); - } else { - return ImmutableList.of(); + @Override + public boolean add(V v) { + add(0, v); + return true; } - } - @Override - public void clear() { - keySet().clear(); - } + @Override + public boolean addAll(Collection collection) { + addAll(0, collection); + return true; + } - @Override - Set createKeySet() { - return Sets.filter(unfiltered.keySet(), keyPredicate); - } + @Override + public boolean addAll(int index, Collection elements) { + checkNotNull(elements); + checkPositionIndex(index, 0); + throw new IllegalArgumentException("Key does not satisfy predicate: " + key); + } - @Override - public Collection get(K key) { - if (keyPredicate.apply(key)) { - return unfiltered.get(key); - } else if (unfiltered instanceof SetMultimap) { - return new AddRejectingSet(key); - } else { - return new AddRejectingList(key); + @Override + protected List delegate() { + return Collections.emptyList(); } } @@ -132,54 +99,6 @@ class FilteredKeyMultimap extends AbstractMultimap implements Filter } } - static class AddRejectingList extends ForwardingList { - final K key; - - AddRejectingList(K key) { - this.key = key; - } - - @Override - public boolean add(V v) { - add(0, v); - return true; - } - - @Override - public boolean addAll(Collection collection) { - addAll(0, collection); - return true; - } - - @Override - public void add(int index, V element) { - checkPositionIndex(index, 0); - throw new IllegalArgumentException("Key does not satisfy predicate: " + key); - } - - @Override - public boolean addAll(int index, Collection elements) { - checkNotNull(elements); - checkPositionIndex(index, 0); - throw new IllegalArgumentException("Key does not satisfy predicate: " + key); - } - - @Override - protected List delegate() { - return Collections.emptyList(); - } - } - - @Override - Iterator> entryIterator() { - throw new AssertionError("should never be called"); - } - - @Override - Collection> createEntries() { - return new Entries(); - } - class Entries extends ForwardingCollection> { @Override protected Collection> delegate() { @@ -201,9 +120,28 @@ class FilteredKeyMultimap extends AbstractMultimap implements Filter } } + final Multimap unfiltered; + + final Predicate keyPredicate; + + FilteredKeyMultimap(Multimap unfiltered, Predicate keyPredicate) { + this.unfiltered = checkNotNull(unfiltered); + this.keyPredicate = checkNotNull(keyPredicate); + } + @Override - Collection createValues() { - return new FilteredMultimapValues(this); + public void clear() { + keySet().clear(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + if (unfiltered.containsKey(key)) { + @SuppressWarnings("unchecked") // k is equal to a K, if not one itself + K k = (K) key; + return keyPredicate.apply(k); + } + return false; } @Override @@ -211,8 +149,71 @@ class FilteredKeyMultimap extends AbstractMultimap implements Filter return Maps.filterKeys(unfiltered.asMap(), keyPredicate); } + @Override + Collection> createEntries() { + return new Entries(); + } + @Override Multiset createKeys() { return Multisets.filter(unfiltered.keys(), keyPredicate); } + + @Override + Set createKeySet() { + return Sets.filter(unfiltered.keySet(), keyPredicate); + } + + @Override + Collection createValues() { + return new FilteredMultimapValues(this); + } + + @Override + Iterator> entryIterator() { + throw new AssertionError("should never be called"); + } + + @Override + public Predicate> entryPredicate() { + return Maps.keyPredicateOnEntries(keyPredicate); + } + + @Override + public Collection get(K key) { + if (keyPredicate.apply(key)) { + return unfiltered.get(key); + } else if (unfiltered instanceof SetMultimap) { + return new AddRejectingSet(key); + } else { + return new AddRejectingList(key); + } + } + + @Override + public Collection removeAll(Object key) { + return containsKey(key) ? unfiltered.removeAll(key) : unmodifiableEmptyCollection(); + } + + @Override + public int size() { + int size = 0; + for (Collection collection : asMap().values()) { + size += collection.size(); + } + return size; + } + + @Override + public Multimap unfiltered() { + return unfiltered; + } + + Collection unmodifiableEmptyCollection() { + if (unfiltered instanceof SetMultimap) { + return ImmutableSet.of(); + } else { + return ImmutableList.of(); + } + } } diff --git a/src/main/java/com/google/common/collect/FilteredKeySetMultimap.java b/src/main/java/com/google/common/collect/FilteredKeySetMultimap.java index 8913ac2e..21903ade 100644 --- a/src/main/java/com/google/common/collect/FilteredKeySetMultimap.java +++ b/src/main/java/com/google/common/collect/FilteredKeySetMultimap.java @@ -32,13 +32,30 @@ import com.google.common.base.Predicate; @GwtCompatible final class FilteredKeySetMultimap extends FilteredKeyMultimap implements FilteredSetMultimap { + class EntrySet extends Entries implements Set> { + @Override + public boolean equals(@Nullable Object o) { + return Sets.equalsImpl(this, o); + } + + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); + } + } + FilteredKeySetMultimap(SetMultimap unfiltered, Predicate keyPredicate) { super(unfiltered, keyPredicate); } @Override - public SetMultimap unfiltered() { - return (SetMultimap) unfiltered; + Set> createEntries() { + return new EntrySet(); + } + + @Override + public Set> entries() { + return (Set>) super.entries(); } @Override @@ -57,24 +74,7 @@ final class FilteredKeySetMultimap extends FilteredKeyMultimap imple } @Override - public Set> entries() { - return (Set>) super.entries(); - } - - @Override - Set> createEntries() { - return new EntrySet(); - } - - class EntrySet extends Entries implements Set> { - @Override - public int hashCode() { - return Sets.hashCodeImpl(this); - } - - @Override - public boolean equals(@Nullable Object o) { - return Sets.equalsImpl(this, o); - } + public SetMultimap unfiltered() { + return (SetMultimap) unfiltered; } } diff --git a/src/main/java/com/google/common/collect/FilteredMultimap.java b/src/main/java/com/google/common/collect/FilteredMultimap.java index 17a6abd2..3521fd25 100644 --- a/src/main/java/com/google/common/collect/FilteredMultimap.java +++ b/src/main/java/com/google/common/collect/FilteredMultimap.java @@ -28,7 +28,7 @@ import com.google.common.base.Predicate; */ @GwtCompatible interface FilteredMultimap extends Multimap { - Multimap unfiltered(); - Predicate> entryPredicate(); + + Multimap unfiltered(); } diff --git a/src/main/java/com/google/common/collect/FilteredMultimapValues.java b/src/main/java/com/google/common/collect/FilteredMultimapValues.java index 8e8af6bd..ecef3955 100644 --- a/src/main/java/com/google/common/collect/FilteredMultimapValues.java +++ b/src/main/java/com/google/common/collect/FilteredMultimapValues.java @@ -43,8 +43,8 @@ final class FilteredMultimapValues extends AbstractCollection { } @Override - public Iterator iterator() { - return Maps.valueIterator(multimap.entries().iterator()); + public void clear() { + multimap.clear(); } @Override @@ -53,8 +53,8 @@ final class FilteredMultimapValues extends AbstractCollection { } @Override - public int size() { - return multimap.size(); + public Iterator iterator() { + return Maps.valueIterator(multimap.entries().iterator()); } @Override @@ -88,7 +88,7 @@ final class FilteredMultimapValues extends AbstractCollection { } @Override - public void clear() { - multimap.clear(); + public int size() { + return multimap.size(); } } diff --git a/src/main/java/com/google/common/collect/FluentIterable.java b/src/main/java/com/google/common/collect/FluentIterable.java index 12860b9d..4e32094d 100644 --- a/src/main/java/com/google/common/collect/FluentIterable.java +++ b/src/main/java/com/google/common/collect/FluentIterable.java @@ -58,12 +58,9 @@ import com.google.common.base.Predicate; *
  *    {@code
  *
- *   FluentIterable
- *       .from(database.getClientList())
- *       .filter(activeInLastMonth())
- *       .transform(Functions.toStringFunction())
- *       .limit(10)
- *       .toList();}
+ * FluentIterable.from(database.getClientList()).filter(activeInLastMonth()).transform(Functions.toStringFunction())
+ * 		.limit(10).toList();
+ * }
  * 
* *

@@ -77,31 +74,14 @@ import com.google.common.base.Predicate; */ @GwtCompatible(emulated = true) public abstract class FluentIterable implements Iterable { - // We store 'iterable' and use it instead of 'this' to allow Iterables to - // perform instanceof - // checks on the _original_ iterable when FluentIterable.from is used. - private final Iterable iterable; - - /** Constructor for use by subclasses. */ - protected FluentIterable() { - this.iterable = this; - } - - FluentIterable(Iterable iterable) { - this.iterable = checkNotNull(iterable); - } - /** - * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} - * itself if it is already a {@code FluentIterable}. + * Function that transforms {@code Iterable} into a fluent iterable. */ - public static FluentIterable from(final Iterable iterable) { - return (iterable instanceof FluentIterable) ? (FluentIterable) iterable : new FluentIterable(iterable) { - @Override - public Iterator iterator() { - return iterable.iterator(); - } - }; + private static class FromIterableFunction implements Function, FluentIterable> { + @Override + public FluentIterable apply(Iterable fromObject) { + return FluentIterable.from(fromObject); + } } /** @@ -119,19 +99,46 @@ public abstract class FluentIterable implements Iterable { } /** - * Returns a string representation of this fluent iterable, with the format - * {@code [e1, e2, ..., en]}. + * Returns a fluent iterable that wraps {@code iterable}, or {@code iterable} + * itself if it is already a {@code FluentIterable}. */ - @Override - public String toString() { - return Iterables.toString(iterable); + public static FluentIterable from(final Iterable iterable) { + return (iterable instanceof FluentIterable) ? (FluentIterable) iterable : new FluentIterable(iterable) { + @Override + public Iterator iterator() { + return iterable.iterator(); + } + }; + } + + // We store 'iterable' and use it instead of 'this' to allow Iterables to + // perform instanceof + // checks on the _original_ iterable when FluentIterable.from is used. + private final Iterable iterable; + + /** Constructor for use by subclasses. */ + protected FluentIterable() { + this.iterable = this; + } + + FluentIterable(Iterable iterable) { + this.iterable = checkNotNull(iterable); } /** - * Returns the number of elements in this fluent iterable. + * Returns {@code true} if every element in this fluent iterable satisfies the + * predicate. If this fluent iterable is empty, {@code true} is returned. */ - public final int size() { - return Iterables.size(iterable); + public final boolean allMatch(Predicate predicate) { + return Iterables.all(iterable, predicate); + } + + /** + * Returns {@code true} if any element in this fluent iterable satisfies the + * predicate. + */ + public final boolean anyMatch(Predicate predicate) { + return Iterables.any(iterable, predicate); } /** @@ -142,6 +149,26 @@ public abstract class FluentIterable implements Iterable { return Iterables.contains(iterable, element); } + /** + * Copies all the elements from this fluent iterable to {@code collection}. This + * is equivalent to calling {@code Iterables.addAll(collection, this)}. + * + * @param collection the collection to copy elements to + * @return {@code collection}, for convenience + * @since 14.0 + */ + public final > C copyInto(C collection) { + checkNotNull(collection); + if (iterable instanceof Collection) { + collection.addAll(Collections2.cast(iterable)); + } else { + for (E item : iterable) { + collection.add(item); + } + } + return collection; + } + /** * Returns a fluent iterable whose {@code Iterator} cycles indefinitely over the * elements of this fluent iterable. @@ -162,15 +189,6 @@ public abstract class FluentIterable implements Iterable { return from(Iterables.cycle(iterable)); } - /** - * Returns the elements from this fluent iterable that satisfy a predicate. The - * resulting fluent iterable's iterator does not support {@code remove()}. - */ - @CheckReturnValue - public final FluentIterable filter(Predicate predicate) { - return from(Iterables.filter(iterable, predicate)); - } - /** * Returns the elements from this fluent iterable that are instances of class * {@code type}. @@ -184,19 +202,25 @@ public abstract class FluentIterable implements Iterable { } /** - * Returns {@code true} if any element in this fluent iterable satisfies the - * predicate. + * Returns the elements from this fluent iterable that satisfy a predicate. The + * resulting fluent iterable's iterator does not support {@code remove()}. */ - public final boolean anyMatch(Predicate predicate) { - return Iterables.any(iterable, predicate); + @CheckReturnValue + public final FluentIterable filter(Predicate predicate) { + return from(Iterables.filter(iterable, predicate)); } /** - * Returns {@code true} if every element in this fluent iterable satisfies the - * predicate. If this fluent iterable is empty, {@code true} is returned. + * Returns an {@link Optional} containing the first element in this fluent + * iterable. If the iterable is empty, {@code Optional.absent()} is returned. + * + * @throws NullPointerException if the first element is null; if this is a + * possibility, use {@code iterator().next()} or + * {@link Iterables#getFirst} instead. */ - public final boolean allMatch(Predicate predicate) { - return Iterables.all(iterable, predicate); + public final Optional first() { + Iterator iterator = iterable.iterator(); + return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.absent(); } /** @@ -213,46 +237,48 @@ public abstract class FluentIterable implements Iterable { } /** - * Returns a fluent iterable that applies {@code function} to each element of - * this fluent iterable. + * Returns the element at the specified position in this fluent iterable. * - *

- * The returned fluent iterable's iterator supports {@code remove()} if this - * iterable's iterator does. After a successful {@code remove()} call, this - * fluent iterable no longer contains the corresponding element. + * @param position position of the element to return + * @return the element at the specified position in this fluent iterable + * @throws IndexOutOfBoundsException if {@code position} is negative or greater + * than or equal to the size of this fluent + * iterable */ - public final FluentIterable transform(Function function) { - return from(Iterables.transform(iterable, function)); + public final E get(int position) { + return Iterables.get(iterable, position); } /** - * Applies {@code function} to each element of this fluent iterable and returns - * a fluent iterable with the concatenated combination of results. - * {@code function} returns an Iterable of results. + * Creates an index {@code ImmutableListMultimap} that contains the results of + * applying a specified function to each item in this {@code FluentIterable} of + * values. Each element of this iterable will be stored as a value in the + * resulting multimap, yielding a multimap with the same size as this iterable. + * The key used to store that value in the multimap will be the result of + * calling the function on that value. The resulting multimap is created as an + * immutable snapshot. In the returned multimap, keys appear in the order they + * are first encountered, and the values corresponding to each key appear in the + * same order as they are encountered. * - *

- * The returned fluent iterable's iterator supports {@code remove()} if this - * function-returned iterables' iterator does. After a successful - * {@code remove()} call, the returned fluent iterable no longer contains the - * corresponding element. - * - * @since 13.0 (required {@code Function>} until 14.0) + * @param keyFunction the function used to produce the key for each value + * @throws NullPointerException if any of the following cases is true: + *

    + *
  • {@code keyFunction} is null + *
  • An element in this fluent iterable is null + *
  • {@code keyFunction} returns {@code null} for + * any element of this iterable + *
+ * @since 14.0 */ - public FluentIterable transformAndConcat(Function> function) { - return from(Iterables.concat(transform(function))); + public final ImmutableListMultimap index(Function keyFunction) { + return Multimaps.index(iterable, keyFunction); } /** - * Returns an {@link Optional} containing the first element in this fluent - * iterable. If the iterable is empty, {@code Optional.absent()} is returned. - * - * @throws NullPointerException if the first element is null; if this is a - * possibility, use {@code iterator().next()} or - * {@link Iterables#getFirst} instead. + * Determines whether this fluent iterable is empty. */ - public final Optional first() { - Iterator iterator = iterable.iterator(); - return iterator.hasNext() ? Optional.of(iterator.next()) : Optional.absent(); + public final boolean isEmpty() { + return !iterable.iterator().hasNext(); } /** @@ -297,6 +323,28 @@ public abstract class FluentIterable implements Iterable { } } + /** + * Creates a fluent iterable with the first {@code size} elements of this fluent + * iterable. If this fluent iterable does not contain that many elements, the + * returned fluent iterable will have the same behavior as this fluent iterable. + * The returned fluent iterable's iterator supports {@code remove()} if this + * fluent iterable's iterator does. + * + * @param size the maximum number of elements in the returned fluent iterable + * @throws IllegalArgumentException if {@code size} is negative + */ + @CheckReturnValue + public final FluentIterable limit(int size) { + return from(Iterables.limit(iterable, size)); + } + + /** + * Returns the number of elements in this fluent iterable. + */ + public final int size() { + return Iterables.size(iterable); + } + /** * Returns a view of this fluent iterable that skips its first * {@code numberToSkip} elements. If this fluent iterable contains fewer than @@ -323,25 +371,16 @@ public abstract class FluentIterable implements Iterable { } /** - * Creates a fluent iterable with the first {@code size} elements of this fluent - * iterable. If this fluent iterable does not contain that many elements, the - * returned fluent iterable will have the same behavior as this fluent iterable. - * The returned fluent iterable's iterator supports {@code remove()} if this - * fluent iterable's iterator does. + * Returns an array containing all of the elements from this fluent iterable in + * iteration order. * - * @param size the maximum number of elements in the returned fluent iterable - * @throws IllegalArgumentException if {@code size} is negative + * @param type the type of the elements + * @return a newly-allocated array into which all the elements of this fluent + * iterable have been copied */ - @CheckReturnValue - public final FluentIterable limit(int size) { - return from(Iterables.limit(iterable, size)); - } - - /** - * Determines whether this fluent iterable is empty. - */ - public final boolean isEmpty() { - return !iterable.iterator().hasNext(); + @GwtIncompatible("Array.newArray(Class, int)") + public final E[] toArray(Class type) { + return Iterables.toArray(iterable, type); } /** @@ -354,6 +393,32 @@ public abstract class FluentIterable implements Iterable { return ImmutableList.copyOf(iterable); } + /** + * Returns an immutable map for which the elements of this + * {@code FluentIterable} are the keys in the same order, mapped to values by + * the given function. If this iterable contains duplicate elements, the + * returned map will contain each distinct element once in the order it first + * appears. + * + * @throws NullPointerException if any element of this iterable is {@code null}, + * or if {@code + * valueFunction} produces {@code null} for any key + * @since 14.0 + */ + public final ImmutableMap toMap(Function valueFunction) { + return Maps.toMap(iterable, valueFunction); + } + + /** + * Returns an {@code ImmutableSet} containing all of the elements from this + * fluent iterable with duplicates removed. + * + * @since 14.0 (since 12.0 as {@code toImmutableSet()}). + */ + public final ImmutableSet toSet() { + return ImmutableSet.copyOf(iterable); + } + /** * Returns an {@code ImmutableList} containing all of the elements from this * {@code @@ -371,16 +436,6 @@ public abstract class FluentIterable implements Iterable { return Ordering.from(comparator).immutableSortedCopy(iterable); } - /** - * Returns an {@code ImmutableSet} containing all of the elements from this - * fluent iterable with duplicates removed. - * - * @since 14.0 (since 12.0 as {@code toImmutableSet()}). - */ - public final ImmutableSet toSet() { - return ImmutableSet.copyOf(iterable); - } - /** * Returns an {@code ImmutableSortedSet} containing all of the elements from * this {@code @@ -398,44 +453,42 @@ public abstract class FluentIterable implements Iterable { } /** - * Returns an immutable map for which the elements of this - * {@code FluentIterable} are the keys in the same order, mapped to values by - * the given function. If this iterable contains duplicate elements, the - * returned map will contain each distinct element once in the order it first - * appears. - * - * @throws NullPointerException if any element of this iterable is {@code null}, - * or if {@code - * valueFunction} produces {@code null} for any key - * @since 14.0 + * Returns a string representation of this fluent iterable, with the format + * {@code [e1, e2, ..., en]}. */ - public final ImmutableMap toMap(Function valueFunction) { - return Maps.toMap(iterable, valueFunction); + @Override + public String toString() { + return Iterables.toString(iterable); } /** - * Creates an index {@code ImmutableListMultimap} that contains the results of - * applying a specified function to each item in this {@code FluentIterable} of - * values. Each element of this iterable will be stored as a value in the - * resulting multimap, yielding a multimap with the same size as this iterable. - * The key used to store that value in the multimap will be the result of - * calling the function on that value. The resulting multimap is created as an - * immutable snapshot. In the returned multimap, keys appear in the order they - * are first encountered, and the values corresponding to each key appear in the - * same order as they are encountered. + * Returns a fluent iterable that applies {@code function} to each element of + * this fluent iterable. * - * @param keyFunction the function used to produce the key for each value - * @throws NullPointerException if any of the following cases is true: - *
    - *
  • {@code keyFunction} is null - *
  • An element in this fluent iterable is null - *
  • {@code keyFunction} returns {@code null} for - * any element of this iterable - *
- * @since 14.0 + *

+ * The returned fluent iterable's iterator supports {@code remove()} if this + * iterable's iterator does. After a successful {@code remove()} call, this + * fluent iterable no longer contains the corresponding element. */ - public final ImmutableListMultimap index(Function keyFunction) { - return Multimaps.index(iterable, keyFunction); + public final FluentIterable transform(Function function) { + return from(Iterables.transform(iterable, function)); + } + + /** + * Applies {@code function} to each element of this fluent iterable and returns + * a fluent iterable with the concatenated combination of results. + * {@code function} returns an Iterable of results. + * + *

+ * The returned fluent iterable's iterator supports {@code remove()} if this + * function-returned iterables' iterator does. After a successful + * {@code remove()} call, the returned fluent iterable no longer contains the + * corresponding element. + * + * @since 13.0 (required {@code Function>} until 14.0) + */ + public FluentIterable transformAndConcat(Function> function) { + return from(Iterables.concat(transform(function))); } /** @@ -455,60 +508,4 @@ public abstract class FluentIterable implements Iterable { public final ImmutableMap uniqueIndex(Function keyFunction) { return Maps.uniqueIndex(iterable, keyFunction); } - - /** - * Returns an array containing all of the elements from this fluent iterable in - * iteration order. - * - * @param type the type of the elements - * @return a newly-allocated array into which all the elements of this fluent - * iterable have been copied - */ - @GwtIncompatible("Array.newArray(Class, int)") - public final E[] toArray(Class type) { - return Iterables.toArray(iterable, type); - } - - /** - * Copies all the elements from this fluent iterable to {@code collection}. This - * is equivalent to calling {@code Iterables.addAll(collection, this)}. - * - * @param collection the collection to copy elements to - * @return {@code collection}, for convenience - * @since 14.0 - */ - public final > C copyInto(C collection) { - checkNotNull(collection); - if (iterable instanceof Collection) { - collection.addAll(Collections2.cast(iterable)); - } else { - for (E item : iterable) { - collection.add(item); - } - } - return collection; - } - - /** - * Returns the element at the specified position in this fluent iterable. - * - * @param position position of the element to return - * @return the element at the specified position in this fluent iterable - * @throws IndexOutOfBoundsException if {@code position} is negative or greater - * than or equal to the size of this fluent - * iterable - */ - public final E get(int position) { - return Iterables.get(iterable, position); - } - - /** - * Function that transforms {@code Iterable} into a fluent iterable. - */ - private static class FromIterableFunction implements Function, FluentIterable> { - @Override - public FluentIterable apply(Iterable fromObject) { - return FluentIterable.from(fromObject); - } - } } diff --git a/src/main/java/com/google/common/collect/ForwardingCollection.java b/src/main/java/com/google/common/collect/ForwardingCollection.java index 7377087f..14702c35 100644 --- a/src/main/java/com/google/common/collect/ForwardingCollection.java +++ b/src/main/java/com/google/common/collect/ForwardingCollection.java @@ -55,72 +55,84 @@ public abstract class ForwardingCollection extends ForwardingObject implement protected ForwardingCollection() { } - @Override - protected abstract Collection delegate(); - - @Override - public Iterator iterator() { - return delegate().iterator(); - } - - @Override - public int size() { - return delegate().size(); - } - - @Override - public boolean removeAll(Collection collection) { - return delegate().removeAll(collection); - } - - @Override - public boolean isEmpty() { - return delegate().isEmpty(); - } - - @Override - public boolean contains(Object object) { - return delegate().contains(object); - } - @Override public boolean add(E element) { return delegate().add(element); } - @Override - public boolean remove(Object object) { - return delegate().remove(object); - } - - @Override - public boolean containsAll(Collection collection) { - return delegate().containsAll(collection); - } - @Override public boolean addAll(Collection collection) { return delegate().addAll(collection); } - @Override - public boolean retainAll(Collection collection) { - return delegate().retainAll(collection); - } - @Override public void clear() { delegate().clear(); } @Override - public Object[] toArray() { - return delegate().toArray(); + public boolean contains(Object object) { + return delegate().contains(object); } @Override - public T[] toArray(T[] array) { - return delegate().toArray(array); + public boolean containsAll(Collection collection) { + return delegate().containsAll(collection); + } + + @Override + protected abstract Collection delegate(); + + @Override + public boolean isEmpty() { + return delegate().isEmpty(); + } + + @Override + public Iterator iterator() { + return delegate().iterator(); + } + + @Override + public boolean remove(Object object) { + return delegate().remove(object); + } + + @Override + public boolean removeAll(Collection collection) { + return delegate().removeAll(collection); + } + + @Override + public boolean retainAll(Collection collection) { + return delegate().retainAll(collection); + } + + @Override + public int size() { + return delegate().size(); + } + + /** + * A sensible definition of {@link #addAll} in terms of {@link #add}. If you + * override {@link #add}, you may wish to override {@link #addAll} to forward to + * this implementation. + * + * @since 7.0 + */ + protected boolean standardAddAll(Collection collection) { + return Iterators.addAll(this, collection.iterator()); + } + + /** + * A sensible definition of {@link #clear} in terms of {@link #iterator}, using + * the iterator's {@code remove} method. If you override {@link #iterator}, you + * may wish to override {@link #clear} to forward to this implementation. + * + * @since 7.0 + */ + protected void standardClear() { + Iterators.clear(iterator()); } /** @@ -146,14 +158,15 @@ public abstract class ForwardingCollection extends ForwardingObject implement } /** - * A sensible definition of {@link #addAll} in terms of {@link #add}. If you - * override {@link #add}, you may wish to override {@link #addAll} to forward to - * this implementation. + * A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}. If + * you override {@link #isEmpty}, you may wish to override {@link #isEmpty} to + * forward to this implementation. Alternately, it may be more efficient to + * implement {@code isEmpty} as {@code size() == 0}. * * @since 7.0 */ - protected boolean standardAddAll(Collection collection) { - return Iterators.addAll(this, collection.iterator()); + protected boolean standardIsEmpty() { + return !iterator().hasNext(); } /** @@ -198,40 +211,6 @@ public abstract class ForwardingCollection extends ForwardingObject implement return Iterators.retainAll(iterator(), collection); } - /** - * A sensible definition of {@link #clear} in terms of {@link #iterator}, using - * the iterator's {@code remove} method. If you override {@link #iterator}, you - * may wish to override {@link #clear} to forward to this implementation. - * - * @since 7.0 - */ - protected void standardClear() { - Iterators.clear(iterator()); - } - - /** - * A sensible definition of {@link #isEmpty} as {@code !iterator().hasNext}. If - * you override {@link #isEmpty}, you may wish to override {@link #isEmpty} to - * forward to this implementation. Alternately, it may be more efficient to - * implement {@code isEmpty} as {@code size() == 0}. - * - * @since 7.0 - */ - protected boolean standardIsEmpty() { - return !iterator().hasNext(); - } - - /** - * A sensible definition of {@link #toString} in terms of {@link #iterator}. If - * you override {@link #iterator}, you may wish to override {@link #toString} to - * forward to this implementation. - * - * @since 7.0 - */ - protected String standardToString() { - return Collections2.toStringImpl(this); - } - /** * A sensible definition of {@link #toArray()} in terms of * {@link #toArray(Object[])}. If you override {@link #toArray(Object[])}, you @@ -254,4 +233,25 @@ public abstract class ForwardingCollection extends ForwardingObject implement protected T[] standardToArray(T[] array) { return ObjectArrays.toArrayImpl(this, array); } + + /** + * A sensible definition of {@link #toString} in terms of {@link #iterator}. If + * you override {@link #iterator}, you may wish to override {@link #toString} to + * forward to this implementation. + * + * @since 7.0 + */ + protected String standardToString() { + return Collections2.toStringImpl(this); + } + + @Override + public Object[] toArray() { + return delegate().toArray(); + } + + @Override + public T[] toArray(T[] array) { + return delegate().toArray(array); + } } diff --git a/src/main/java/com/google/common/collect/ForwardingDeque.java b/src/main/java/com/google/common/collect/ForwardingDeque.java index 3145c1d8..e47d5bf1 100644 --- a/src/main/java/com/google/common/collect/ForwardingDeque.java +++ b/src/main/java/com/google/common/collect/ForwardingDeque.java @@ -42,9 +42,6 @@ public abstract class ForwardingDeque extends ForwardingQueue implements D protected ForwardingDeque() { } - @Override - protected abstract Deque delegate(); - @Override public void addFirst(E e) { delegate().addFirst(e); @@ -55,6 +52,9 @@ public abstract class ForwardingDeque extends ForwardingQueue implements D delegate().addLast(e); } + @Override + protected abstract Deque delegate(); + @Override public Iterator descendingIterator() { return delegate().descendingIterator(); @@ -116,13 +116,13 @@ public abstract class ForwardingDeque extends ForwardingQueue implements D } @Override - public E removeLast() { - return delegate().removeLast(); + public boolean removeFirstOccurrence(Object o) { + return delegate().removeFirstOccurrence(o); } @Override - public boolean removeFirstOccurrence(Object o) { - return delegate().removeFirstOccurrence(o); + public E removeLast() { + return delegate().removeLast(); } @Override diff --git a/src/main/java/com/google/common/collect/ForwardingList.java b/src/main/java/com/google/common/collect/ForwardingList.java index e1cdd3f2..e0819433 100644 --- a/src/main/java/com/google/common/collect/ForwardingList.java +++ b/src/main/java/com/google/common/collect/ForwardingList.java @@ -34,9 +34,10 @@ import com.google.common.annotations.GwtCompatible; * pattern. * *

- * This class does not implement {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. If the delegate - * supports random access, the {@code ForwardingList} subclass should implement - * the {@code RandomAccess} interface. + * This class does not implement + * {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. If the delegate supports + * random access, the {@code ForwardingList} subclass should implement the + * {@code RandomAccess} interface. * *

* Warning: The methods of {@code ForwardingList} forward @@ -63,9 +64,6 @@ public abstract class ForwardingList extends ForwardingCollection implemen protected ForwardingList() { } - @Override - protected abstract List delegate(); - @Override public void add(int index, E element) { delegate().add(index, element); @@ -76,11 +74,24 @@ public abstract class ForwardingList extends ForwardingCollection implemen return delegate().addAll(index, elements); } + @Override + protected abstract List delegate(); + + @Override + public boolean equals(@Nullable Object object) { + return object == this || delegate().equals(object); + } + @Override public E get(int index) { return delegate().get(index); } + @Override + public int hashCode() { + return delegate().hashCode(); + } + @Override public int indexOf(Object element) { return delegate().indexOf(element); @@ -111,21 +122,6 @@ public abstract class ForwardingList extends ForwardingCollection implemen return delegate().set(index, element); } - @Override - public List subList(int fromIndex, int toIndex) { - return delegate().subList(fromIndex, toIndex); - } - - @Override - public boolean equals(@Nullable Object object) { - return object == this || delegate().equals(object); - } - - @Override - public int hashCode() { - return delegate().hashCode(); - } - /** * A sensible default implementation of {@link #add(Object)}, in terms of * {@link #add(int, Object)}. If you override {@link #add(int, Object)}, you may @@ -150,6 +146,30 @@ public abstract class ForwardingList extends ForwardingCollection implemen return Lists.addAllImpl(this, index, elements); } + /** + * A sensible definition of {@link #equals(Object)} in terms of {@link #size} + * and {@link #iterator}. If you override either of those methods, you may wish + * to override {@link #equals(Object)} to forward to this implementation. + * + * @since 7.0 + */ + @Beta + protected boolean standardEquals(@Nullable Object object) { + return Lists.equalsImpl(this, object); + } + + /** + * A sensible definition of {@link #hashCode} in terms of {@link #iterator}. If + * you override {@link #iterator}, you may wish to override {@link #hashCode} to + * forward to this implementation. + * + * @since 7.0 + */ + @Beta + protected int standardHashCode() { + return Lists.hashCodeImpl(this); + } + /** * A sensible default implementation of {@link #indexOf}, in terms of * {@link #listIterator()}. If you override {@link #listIterator()}, you may @@ -161,17 +181,6 @@ public abstract class ForwardingList extends ForwardingCollection implemen return Lists.indexOfImpl(this, element); } - /** - * A sensible default implementation of {@link #lastIndexOf}, in terms of - * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you - * may wish to override {@link #lastIndexOf} to forward to this implementation. - * - * @since 7.0 - */ - protected int standardLastIndexOf(@Nullable Object element) { - return Lists.lastIndexOfImpl(this, element); - } - /** * A sensible default implementation of {@link #iterator}, in terms of * {@link #listIterator()}. If you override {@link #listIterator()}, you may @@ -183,6 +192,17 @@ public abstract class ForwardingList extends ForwardingCollection implemen return listIterator(); } + /** + * A sensible default implementation of {@link #lastIndexOf}, in terms of + * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you + * may wish to override {@link #lastIndexOf} to forward to this implementation. + * + * @since 7.0 + */ + protected int standardLastIndexOf(@Nullable Object element) { + return Lists.lastIndexOfImpl(this, element); + } + /** * A sensible default implementation of {@link #listIterator()}, in terms of * {@link #listIterator(int)}. If you override {@link #listIterator(int)}, you @@ -221,27 +241,8 @@ public abstract class ForwardingList extends ForwardingCollection implemen return Lists.subListImpl(this, fromIndex, toIndex); } - /** - * A sensible definition of {@link #equals(Object)} in terms of {@link #size} - * and {@link #iterator}. If you override either of those methods, you may wish - * to override {@link #equals(Object)} to forward to this implementation. - * - * @since 7.0 - */ - @Beta - protected boolean standardEquals(@Nullable Object object) { - return Lists.equalsImpl(this, object); - } - - /** - * A sensible definition of {@link #hashCode} in terms of {@link #iterator}. If - * you override {@link #iterator}, you may wish to override {@link #hashCode} to - * forward to this implementation. - * - * @since 7.0 - */ - @Beta - protected int standardHashCode() { - return Lists.hashCodeImpl(this); + @Override + public List subList(int fromIndex, int toIndex) { + return delegate().subList(fromIndex, toIndex); } } diff --git a/src/main/java/com/google/common/collect/ForwardingListIterator.java b/src/main/java/com/google/common/collect/ForwardingListIterator.java index bde0cf68..85599f27 100644 --- a/src/main/java/com/google/common/collect/ForwardingListIterator.java +++ b/src/main/java/com/google/common/collect/ForwardingListIterator.java @@ -37,14 +37,14 @@ public abstract class ForwardingListIterator extends ForwardingIterator im protected ForwardingListIterator() { } - @Override - protected abstract ListIterator delegate(); - @Override public void add(E element) { delegate().add(element); } + @Override + protected abstract ListIterator delegate(); + @Override public boolean hasPrevious() { return delegate().hasPrevious(); diff --git a/src/main/java/com/google/common/collect/ForwardingMap.java b/src/main/java/com/google/common/collect/ForwardingMap.java index 98156537..8c89dc60 100644 --- a/src/main/java/com/google/common/collect/ForwardingMap.java +++ b/src/main/java/com/google/common/collect/ForwardingMap.java @@ -63,28 +63,69 @@ import com.google.common.base.Objects; public abstract class ForwardingMap extends ForwardingObject implements Map { // TODO(user): identify places where thread safety is actually lost + /** + * A sensible implementation of {@link Map#entrySet} in terms of the following + * methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey}, + * {@link ForwardingMap#get}, {@link ForwardingMap#isEmpty}, + * {@link ForwardingMap#remove}, and {@link ForwardingMap#size}. In many cases, + * you may wish to override {@link #entrySet} to forward to this implementation + * or a subclass thereof. + * + * @since 10.0 + */ + @Beta + protected abstract class StandardEntrySet extends Maps.EntrySet { + /** Constructor for use by subclasses. */ + public StandardEntrySet() { + } + + @Override + Map map() { + return ForwardingMap.this; + } + } + + /** + * A sensible implementation of {@link Map#keySet} in terms of the following + * methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey}, + * {@link ForwardingMap#isEmpty}, {@link ForwardingMap#remove}, + * {@link ForwardingMap#size}, and the {@link Set#iterator} method of + * {@link ForwardingMap#entrySet}. In many cases, you may wish to override + * {@link ForwardingMap#keySet} to forward to this implementation or a subclass + * thereof. + * + * @since 10.0 + */ + @Beta + protected class StandardKeySet extends Maps.KeySet { + /** Constructor for use by subclasses. */ + public StandardKeySet() { + super(ForwardingMap.this); + } + } + + /** + * A sensible implementation of {@link Map#values} in terms of the following + * methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsValue}, + * {@link ForwardingMap#isEmpty}, {@link ForwardingMap#size}, and the + * {@link Set#iterator} method of {@link ForwardingMap#entrySet}. In many cases, + * you may wish to override {@link ForwardingMap#values} to forward to this + * implementation or a subclass thereof. + * + * @since 10.0 + */ + @Beta + protected class StandardValues extends Maps.Values { + /** Constructor for use by subclasses. */ + public StandardValues() { + super(ForwardingMap.this); + } + } + /** Constructor for use by subclasses. */ protected ForwardingMap() { } - @Override - protected abstract Map delegate(); - - @Override - public int size() { - return delegate().size(); - } - - @Override - public boolean isEmpty() { - return delegate().isEmpty(); - } - - @Override - public V remove(Object object) { - return delegate().remove(object); - } - @Override public void clear() { delegate().clear(); @@ -100,11 +141,39 @@ public abstract class ForwardingMap extends ForwardingObject implements Ma return delegate().containsValue(value); } + @Override + protected abstract Map delegate(); + + @Override + public Set> entrySet() { + return delegate().entrySet(); + } + + @Override + public boolean equals(@Nullable Object object) { + return object == this || delegate().equals(object); + } + @Override public V get(@Nullable Object key) { return delegate().get(key); } + @Override + public int hashCode() { + return delegate().hashCode(); + } + + @Override + public boolean isEmpty() { + return delegate().isEmpty(); + } + + @Override + public Set keySet() { + return delegate().keySet(); + } + @Override public V put(K key, V value) { return delegate().put(key, value); @@ -116,28 +185,82 @@ public abstract class ForwardingMap extends ForwardingObject implements Ma } @Override - public Set keySet() { - return delegate().keySet(); + public V remove(Object object) { + return delegate().remove(object); } @Override - public Collection values() { - return delegate().values(); + public int size() { + return delegate().size(); } - @Override - public Set> entrySet() { - return delegate().entrySet(); + /** + * A sensible definition of {@link #clear} in terms of the {@code iterator} + * method of {@link #entrySet}. In many cases, you may wish to override + * {@link #clear} to forward to this implementation. + * + * @since 7.0 + */ + protected void standardClear() { + Iterators.clear(entrySet().iterator()); } - @Override - public boolean equals(@Nullable Object object) { - return object == this || delegate().equals(object); + /** + * A sensible, albeit inefficient, definition of {@link #containsKey} in terms + * of the {@code iterator} method of {@link #entrySet}. If you override + * {@link #entrySet}, you may wish to override {@link #containsKey} to forward + * to this implementation. + * + * @since 7.0 + */ + @Beta + protected boolean standardContainsKey(@Nullable Object key) { + return Maps.containsKeyImpl(this, key); } - @Override - public int hashCode() { - return delegate().hashCode(); + /** + * A sensible definition of {@link #containsValue} in terms of the {@code + * iterator} method of {@link #entrySet}. If you override {@link #entrySet}, you + * may wish to override {@link #containsValue} to forward to this + * implementation. + * + * @since 7.0 + */ + protected boolean standardContainsValue(@Nullable Object value) { + return Maps.containsValueImpl(this, value); + } + + /** + * A sensible definition of {@link #equals} in terms of the {@code equals} + * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish + * to override {@link #equals} to forward to this implementation. + * + * @since 7.0 + */ + protected boolean standardEquals(@Nullable Object object) { + return Maps.equalsImpl(this, object); + } + + /** + * A sensible definition of {@link #hashCode} in terms of the {@code iterator} + * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish + * to override {@link #hashCode} to forward to this implementation. + * + * @since 7.0 + */ + protected int standardHashCode() { + return Sets.hashCodeImpl(entrySet()); + } + + /** + * A sensible definition of {@link #isEmpty} in terms of the {@code iterator} + * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish + * to override {@link #isEmpty} to forward to this implementation. + * + * @since 7.0 + */ + protected boolean standardIsEmpty() { + return !entrySet().iterator().hasNext(); } /** @@ -178,134 +301,6 @@ public abstract class ForwardingMap extends ForwardingObject implements Ma return null; } - /** - * A sensible definition of {@link #clear} in terms of the {@code iterator} - * method of {@link #entrySet}. In many cases, you may wish to override - * {@link #clear} to forward to this implementation. - * - * @since 7.0 - */ - protected void standardClear() { - Iterators.clear(entrySet().iterator()); - } - - /** - * A sensible implementation of {@link Map#keySet} in terms of the following - * methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey}, - * {@link ForwardingMap#isEmpty}, {@link ForwardingMap#remove}, - * {@link ForwardingMap#size}, and the {@link Set#iterator} method of - * {@link ForwardingMap#entrySet}. In many cases, you may wish to override - * {@link ForwardingMap#keySet} to forward to this implementation or a subclass - * thereof. - * - * @since 10.0 - */ - @Beta - protected class StandardKeySet extends Maps.KeySet { - /** Constructor for use by subclasses. */ - public StandardKeySet() { - super(ForwardingMap.this); - } - } - - /** - * A sensible, albeit inefficient, definition of {@link #containsKey} in terms - * of the {@code iterator} method of {@link #entrySet}. If you override - * {@link #entrySet}, you may wish to override {@link #containsKey} to forward - * to this implementation. - * - * @since 7.0 - */ - @Beta - protected boolean standardContainsKey(@Nullable Object key) { - return Maps.containsKeyImpl(this, key); - } - - /** - * A sensible implementation of {@link Map#values} in terms of the following - * methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsValue}, - * {@link ForwardingMap#isEmpty}, {@link ForwardingMap#size}, and the - * {@link Set#iterator} method of {@link ForwardingMap#entrySet}. In many cases, - * you may wish to override {@link ForwardingMap#values} to forward to this - * implementation or a subclass thereof. - * - * @since 10.0 - */ - @Beta - protected class StandardValues extends Maps.Values { - /** Constructor for use by subclasses. */ - public StandardValues() { - super(ForwardingMap.this); - } - } - - /** - * A sensible definition of {@link #containsValue} in terms of the {@code - * iterator} method of {@link #entrySet}. If you override {@link #entrySet}, you - * may wish to override {@link #containsValue} to forward to this - * implementation. - * - * @since 7.0 - */ - protected boolean standardContainsValue(@Nullable Object value) { - return Maps.containsValueImpl(this, value); - } - - /** - * A sensible implementation of {@link Map#entrySet} in terms of the following - * methods: {@link ForwardingMap#clear}, {@link ForwardingMap#containsKey}, - * {@link ForwardingMap#get}, {@link ForwardingMap#isEmpty}, - * {@link ForwardingMap#remove}, and {@link ForwardingMap#size}. In many cases, - * you may wish to override {@link #entrySet} to forward to this implementation - * or a subclass thereof. - * - * @since 10.0 - */ - @Beta - protected abstract class StandardEntrySet extends Maps.EntrySet { - /** Constructor for use by subclasses. */ - public StandardEntrySet() { - } - - @Override - Map map() { - return ForwardingMap.this; - } - } - - /** - * A sensible definition of {@link #isEmpty} in terms of the {@code iterator} - * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish - * to override {@link #isEmpty} to forward to this implementation. - * - * @since 7.0 - */ - protected boolean standardIsEmpty() { - return !entrySet().iterator().hasNext(); - } - - /** - * A sensible definition of {@link #equals} in terms of the {@code equals} - * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish - * to override {@link #equals} to forward to this implementation. - * - * @since 7.0 - */ - protected boolean standardEquals(@Nullable Object object) { - return Maps.equalsImpl(this, object); - } - - /** - * A sensible definition of {@link #hashCode} in terms of the {@code iterator} - * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish - * to override {@link #hashCode} to forward to this implementation. - * - * @since 7.0 - */ - protected int standardHashCode() { - return Sets.hashCodeImpl(entrySet()); - } - /** * A sensible definition of {@link #toString} in terms of the {@code iterator} * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish @@ -316,4 +311,9 @@ public abstract class ForwardingMap extends ForwardingObject implements Ma protected String standardToString() { return Maps.toStringImpl(this); } + + @Override + public Collection values() { + return delegate().values(); + } } diff --git a/src/main/java/com/google/common/collect/ForwardingMapEntry.java b/src/main/java/com/google/common/collect/ForwardingMapEntry.java index ecaba0ba..760209f0 100644 --- a/src/main/java/com/google/common/collect/ForwardingMapEntry.java +++ b/src/main/java/com/google/common/collect/ForwardingMapEntry.java @@ -66,6 +66,11 @@ public abstract class ForwardingMapEntry extends ForwardingObject implemen @Override protected abstract Map.Entry delegate(); + @Override + public boolean equals(@Nullable Object object) { + return delegate().equals(object); + } + @Override public K getKey() { return delegate().getKey(); @@ -76,21 +81,16 @@ public abstract class ForwardingMapEntry extends ForwardingObject implemen return delegate().getValue(); } - @Override - public V setValue(V value) { - return delegate().setValue(value); - } - - @Override - public boolean equals(@Nullable Object object) { - return delegate().equals(object); - } - @Override public int hashCode() { return delegate().hashCode(); } + @Override + public V setValue(V value) { + return delegate().setValue(value); + } + /** * A sensible definition of {@link #equals(Object)} in terms of * {@link #getKey()} and {@link #getValue()}. If you override either of these diff --git a/src/main/java/com/google/common/collect/ForwardingMultimap.java b/src/main/java/com/google/common/collect/ForwardingMultimap.java index 7dda3bfa..d638a8bd 100644 --- a/src/main/java/com/google/common/collect/ForwardingMultimap.java +++ b/src/main/java/com/google/common/collect/ForwardingMultimap.java @@ -42,9 +42,6 @@ public abstract class ForwardingMultimap extends ForwardingObject implemen protected ForwardingMultimap() { } - @Override - protected abstract Multimap delegate(); - @Override public Map> asMap() { return delegate().asMap(); @@ -70,16 +67,29 @@ public abstract class ForwardingMultimap extends ForwardingObject implemen return delegate().containsValue(value); } + @Override + protected abstract Multimap delegate(); + @Override public Collection> entries() { return delegate().entries(); } + @Override + public boolean equals(@Nullable Object object) { + return object == this || delegate().equals(object); + } + @Override public Collection get(@Nullable K key) { return delegate().get(key); } + @Override + public int hashCode() { + return delegate().hashCode(); + } + @Override public boolean isEmpty() { return delegate().isEmpty(); @@ -134,14 +144,4 @@ public abstract class ForwardingMultimap extends ForwardingObject implemen public Collection values() { return delegate().values(); } - - @Override - public boolean equals(@Nullable Object object) { - return object == this || delegate().equals(object); - } - - @Override - public int hashCode() { - return delegate().hashCode(); - } } diff --git a/src/main/java/com/google/common/collect/ForwardingMultiset.java b/src/main/java/com/google/common/collect/ForwardingMultiset.java index 70a20003..9a8cb473 100644 --- a/src/main/java/com/google/common/collect/ForwardingMultiset.java +++ b/src/main/java/com/google/common/collect/ForwardingMultiset.java @@ -54,16 +54,33 @@ import com.google.common.base.Objects; @GwtCompatible public abstract class ForwardingMultiset extends ForwardingCollection implements Multiset { - /** Constructor for use by subclasses. */ - protected ForwardingMultiset() { + /** + * A sensible implementation of {@link Multiset#elementSet} in terms of the + * following methods: {@link ForwardingMultiset#clear}, + * {@link ForwardingMultiset#contains}, {@link ForwardingMultiset#containsAll}, + * {@link ForwardingMultiset#count}, {@link ForwardingMultiset#isEmpty}, the + * {@link Set#size} and {@link Set#iterator} methods of + * {@link ForwardingMultiset#entrySet}, and + * {@link ForwardingMultiset#remove(Object, int)}. In many situations, you may + * wish to override {@link ForwardingMultiset#elementSet} to forward to this + * implementation or a subclass thereof. + * + * @since 10.0 + */ + @Beta + protected class StandardElementSet extends Multisets.ElementSet { + /** Constructor for use by subclasses. */ + public StandardElementSet() { + } + + @Override + Multiset multiset() { + return ForwardingMultiset.this; + } } - @Override - protected abstract Multiset delegate(); - - @Override - public int count(Object element) { - return delegate().count(element); + /** Constructor for use by subclasses. */ + protected ForwardingMultiset() { } @Override @@ -72,10 +89,13 @@ public abstract class ForwardingMultiset extends ForwardingCollection impl } @Override - public int remove(Object element, int occurrences) { - return delegate().remove(element, occurrences); + public int count(Object element) { + return delegate().count(element); } + @Override + protected abstract Multiset delegate(); + @Override public Set elementSet() { return delegate().elementSet(); @@ -96,6 +116,11 @@ public abstract class ForwardingMultiset extends ForwardingCollection impl return delegate().hashCode(); } + @Override + public int remove(Object element, int occurrences) { + return delegate().remove(element, occurrences); + } + @Override public int setCount(E element, int count) { return delegate().setCount(element, count); @@ -106,47 +131,6 @@ public abstract class ForwardingMultiset extends ForwardingCollection impl return delegate().setCount(element, oldCount, newCount); } - /** - * A sensible definition of {@link #contains} in terms of {@link #count}. If you - * override {@link #count}, you may wish to override {@link #contains} to - * forward to this implementation. - * - * @since 7.0 - */ - @Override - protected boolean standardContains(@Nullable Object object) { - return count(object) > 0; - } - - /** - * A sensible definition of {@link #clear} in terms of the {@code iterator} - * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish - * to override {@link #clear} to forward to this implementation. - * - * @since 7.0 - */ - @Override - protected void standardClear() { - Iterators.clear(entrySet().iterator()); - } - - /** - * A sensible, albeit inefficient, definition of {@link #count} in terms of - * {@link #entrySet}. If you override {@link #entrySet}, you may wish to - * override {@link #count} to forward to this implementation. - * - * @since 7.0 - */ - @Beta - protected int standardCount(@Nullable Object object) { - for (Entry entry : this.entrySet()) { - if (Objects.equal(entry.getElement(), object)) { - return entry.getCount(); - } - } - return 0; - } - /** * A sensible definition of {@link #add(Object)} in terms of * {@link #add(Object, int)}. If you override {@link #add(Object, int)}, you may @@ -173,6 +157,81 @@ public abstract class ForwardingMultiset extends ForwardingCollection impl return Multisets.addAllImpl(this, elementsToAdd); } + /** + * A sensible definition of {@link #clear} in terms of the {@code iterator} + * method of {@link #entrySet}. If you override {@link #entrySet}, you may wish + * to override {@link #clear} to forward to this implementation. + * + * @since 7.0 + */ + @Override + protected void standardClear() { + Iterators.clear(entrySet().iterator()); + } + + /** + * A sensible definition of {@link #contains} in terms of {@link #count}. If you + * override {@link #count}, you may wish to override {@link #contains} to + * forward to this implementation. + * + * @since 7.0 + */ + @Override + protected boolean standardContains(@Nullable Object object) { + return count(object) > 0; + } + + /** + * A sensible, albeit inefficient, definition of {@link #count} in terms of + * {@link #entrySet}. If you override {@link #entrySet}, you may wish to + * override {@link #count} to forward to this implementation. + * + * @since 7.0 + */ + @Beta + protected int standardCount(@Nullable Object object) { + for (Entry entry : this.entrySet()) { + if (Objects.equal(entry.getElement(), object)) { + return entry.getCount(); + } + } + return 0; + } + + /** + * A sensible, albeit inefficient, definition of {@link #size} in terms of + * {@code entrySet().size()} and {@link #count}. If you override either of these + * methods, you may wish to override {@link #size} to forward to this + * implementation. + * + * @since 7.0 + */ + protected boolean standardEquals(@Nullable Object object) { + return Multisets.equalsImpl(this, object); + } + + /** + * A sensible definition of {@link #hashCode} as {@code entrySet().hashCode()} . + * If you override {@link #entrySet}, you may wish to override {@link #hashCode} + * to forward to this implementation. + * + * @since 7.0 + */ + protected int standardHashCode() { + return entrySet().hashCode(); + } + + /** + * A sensible definition of {@link #iterator} in terms of {@link #entrySet} and + * {@link #remove(Object)}. If you override either of these methods, you may + * wish to override {@link #iterator} to forward to this implementation. + * + * @since 7.0 + */ + protected Iterator standardIterator() { + return Multisets.iteratorImpl(this); + } + /** * A sensible definition of {@link #remove(Object)} in terms of * {@link #remove(Object, int)}. If you override {@link #remove(Object, int)}, @@ -237,42 +296,6 @@ public abstract class ForwardingMultiset extends ForwardingCollection impl return Multisets.setCountImpl(this, element, oldCount, newCount); } - /** - * A sensible implementation of {@link Multiset#elementSet} in terms of the - * following methods: {@link ForwardingMultiset#clear}, - * {@link ForwardingMultiset#contains}, {@link ForwardingMultiset#containsAll}, - * {@link ForwardingMultiset#count}, {@link ForwardingMultiset#isEmpty}, the - * {@link Set#size} and {@link Set#iterator} methods of - * {@link ForwardingMultiset#entrySet}, and - * {@link ForwardingMultiset#remove(Object, int)}. In many situations, you may - * wish to override {@link ForwardingMultiset#elementSet} to forward to this - * implementation or a subclass thereof. - * - * @since 10.0 - */ - @Beta - protected class StandardElementSet extends Multisets.ElementSet { - /** Constructor for use by subclasses. */ - public StandardElementSet() { - } - - @Override - Multiset multiset() { - return ForwardingMultiset.this; - } - } - - /** - * A sensible definition of {@link #iterator} in terms of {@link #entrySet} and - * {@link #remove(Object)}. If you override either of these methods, you may - * wish to override {@link #iterator} to forward to this implementation. - * - * @since 7.0 - */ - protected Iterator standardIterator() { - return Multisets.iteratorImpl(this); - } - /** * A sensible, albeit inefficient, definition of {@link #size} in terms of * {@link #entrySet}. If you override {@link #entrySet}, you may wish to @@ -284,29 +307,6 @@ public abstract class ForwardingMultiset extends ForwardingCollection impl return Multisets.sizeImpl(this); } - /** - * A sensible, albeit inefficient, definition of {@link #size} in terms of - * {@code entrySet().size()} and {@link #count}. If you override either of these - * methods, you may wish to override {@link #size} to forward to this - * implementation. - * - * @since 7.0 - */ - protected boolean standardEquals(@Nullable Object object) { - return Multisets.equalsImpl(this, object); - } - - /** - * A sensible definition of {@link #hashCode} as {@code entrySet().hashCode()} . - * If you override {@link #entrySet}, you may wish to override {@link #hashCode} - * to forward to this implementation. - * - * @since 7.0 - */ - protected int standardHashCode() { - return entrySet().hashCode(); - } - /** * A sensible definition of {@link #toString} as {@code entrySet().toString()} . * If you override {@link #entrySet}, you may wish to override {@link #toString} diff --git a/src/main/java/com/google/common/collect/ForwardingNavigableMap.java b/src/main/java/com/google/common/collect/ForwardingNavigableMap.java index 0996692c..cc7c5039 100644 --- a/src/main/java/com/google/common/collect/ForwardingNavigableMap.java +++ b/src/main/java/com/google/common/collect/ForwardingNavigableMap.java @@ -58,222 +58,6 @@ import com.google.common.annotations.Beta; */ public abstract class ForwardingNavigableMap extends ForwardingSortedMap implements NavigableMap { - /** Constructor for use by subclasses. */ - protected ForwardingNavigableMap() { - } - - @Override - protected abstract NavigableMap delegate(); - - @Override - public Entry lowerEntry(K key) { - return delegate().lowerEntry(key); - } - - /** - * A sensible definition of {@link #lowerEntry} in terms of the - * {@code lastEntry()} of {@link #headMap(Object, boolean)}. If you override - * {@code headMap}, you may wish to override {@code lowerEntry} to forward to - * this implementation. - */ - protected Entry standardLowerEntry(K key) { - return headMap(key, false).lastEntry(); - } - - @Override - public K lowerKey(K key) { - return delegate().lowerKey(key); - } - - /** - * A sensible definition of {@link #lowerKey} in terms of {@code lowerEntry}. If - * you override {@link #lowerEntry}, you may wish to override {@code lowerKey} - * to forward to this implementation. - */ - protected K standardLowerKey(K key) { - return keyOrNull(lowerEntry(key)); - } - - @Override - public Entry floorEntry(K key) { - return delegate().floorEntry(key); - } - - /** - * A sensible definition of {@link #floorEntry} in terms of the - * {@code lastEntry()} of {@link #headMap(Object, boolean)}. If you override - * {@code headMap}, you may wish to override {@code floorEntry} to forward to - * this implementation. - */ - protected Entry standardFloorEntry(K key) { - return headMap(key, true).lastEntry(); - } - - @Override - public K floorKey(K key) { - return delegate().floorKey(key); - } - - /** - * A sensible definition of {@link #floorKey} in terms of {@code floorEntry}. If - * you override {@code floorEntry}, you may wish to override {@code floorKey} to - * forward to this implementation. - */ - protected K standardFloorKey(K key) { - return keyOrNull(floorEntry(key)); - } - - @Override - public Entry ceilingEntry(K key) { - return delegate().ceilingEntry(key); - } - - /** - * A sensible definition of {@link #ceilingEntry} in terms of the - * {@code firstEntry()} of {@link #tailMap(Object, boolean)}. If you override - * {@code tailMap}, you may wish to override {@code ceilingEntry} to forward to - * this implementation. - */ - protected Entry standardCeilingEntry(K key) { - return tailMap(key, true).firstEntry(); - } - - @Override - public K ceilingKey(K key) { - return delegate().ceilingKey(key); - } - - /** - * A sensible definition of {@link #ceilingKey} in terms of - * {@code ceilingEntry}. If you override {@code ceilingEntry}, you may wish to - * override {@code ceilingKey} to forward to this implementation. - */ - protected K standardCeilingKey(K key) { - return keyOrNull(ceilingEntry(key)); - } - - @Override - public Entry higherEntry(K key) { - return delegate().higherEntry(key); - } - - /** - * A sensible definition of {@link #higherEntry} in terms of the - * {@code firstEntry()} of {@link #tailMap(Object, boolean)}. If you override - * {@code tailMap}, you may wish to override {@code higherEntry} to forward to - * this implementation. - */ - protected Entry standardHigherEntry(K key) { - return tailMap(key, false).firstEntry(); - } - - @Override - public K higherKey(K key) { - return delegate().higherKey(key); - } - - /** - * A sensible definition of {@link #higherKey} in terms of {@code higherEntry}. - * If you override {@code higherEntry}, you may wish to override - * {@code higherKey} to forward to this implementation. - */ - protected K standardHigherKey(K key) { - return keyOrNull(higherEntry(key)); - } - - @Override - public Entry firstEntry() { - return delegate().firstEntry(); - } - - /** - * A sensible definition of {@link #firstEntry} in terms of the - * {@code iterator()} of {@link #entrySet}. If you override {@code entrySet}, - * you may wish to override {@code firstEntry} to forward to this - * implementation. - */ - protected Entry standardFirstEntry() { - return Iterables.getFirst(entrySet(), null); - } - - /** - * A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If - * you override {@code firstEntry}, you may wish to override {@code firstKey} to - * forward to this implementation. - */ - protected K standardFirstKey() { - Entry entry = firstEntry(); - if (entry == null) { - throw new NoSuchElementException(); - } else { - return entry.getKey(); - } - } - - @Override - public Entry lastEntry() { - return delegate().lastEntry(); - } - - /** - * A sensible definition of {@link #lastEntry} in terms of the - * {@code iterator()} of the {@link #entrySet} of {@link #descendingMap}. If you - * override {@code descendingMap}, you may wish to override {@code lastEntry} to - * forward to this implementation. - */ - protected Entry standardLastEntry() { - return Iterables.getFirst(descendingMap().entrySet(), null); - } - - /** - * A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If - * you override {@code lastEntry}, you may wish to override {@code lastKey} to - * forward to this implementation. - */ - protected K standardLastKey() { - Entry entry = lastEntry(); - if (entry == null) { - throw new NoSuchElementException(); - } else { - return entry.getKey(); - } - } - - @Override - public Entry pollFirstEntry() { - return delegate().pollFirstEntry(); - } - - /** - * A sensible definition of {@link #pollFirstEntry} in terms of the - * {@code iterator} of {@code entrySet}. If you override {@code entrySet}, you - * may wish to override {@code pollFirstEntry} to forward to this - * implementation. - */ - protected Entry standardPollFirstEntry() { - return Iterators.pollNext(entrySet().iterator()); - } - - @Override - public Entry pollLastEntry() { - return delegate().pollLastEntry(); - } - - /** - * A sensible definition of {@link #pollFirstEntry} in terms of the - * {@code iterator} of the {@code entrySet} of {@code descendingMap}. If you - * override {@code descendingMap}, you may wish to override - * {@code pollFirstEntry} to forward to this implementation. - */ - protected Entry standardPollLastEntry() { - return Iterators.pollNext(descendingMap().entrySet().iterator()); - } - - @Override - public NavigableMap descendingMap() { - return delegate().descendingMap(); - } - /** * A sensible implementation of {@link NavigableMap#descendingMap} in terms of * the methods of this {@code NavigableMap}. In many cases, you may wish to @@ -294,11 +78,6 @@ public abstract class ForwardingNavigableMap extends ForwardingSortedMap forward() { - return ForwardingNavigableMap.this; - } - @Override protected Iterator> entryIterator() { return new Iterator>() { @@ -331,11 +110,11 @@ public abstract class ForwardingNavigableMap extends ForwardingSortedMap navigableKeySet() { - return delegate().navigableKeySet(); + @Override + NavigableMap forward() { + return ForwardingNavigableMap.this; + } } /** @@ -354,11 +133,112 @@ public abstract class ForwardingNavigableMap extends ForwardingSortedMap ceilingEntry(K key) { + return delegate().ceilingEntry(key); + } + + @Override + public K ceilingKey(K key) { + return delegate().ceilingKey(key); + } + + @Override + protected abstract NavigableMap delegate(); + @Override public NavigableSet descendingKeySet() { return delegate().descendingKeySet(); } + @Override + public NavigableMap descendingMap() { + return delegate().descendingMap(); + } + + @Override + public Entry firstEntry() { + return delegate().firstEntry(); + } + + @Override + public Entry floorEntry(K key) { + return delegate().floorEntry(key); + } + + @Override + public K floorKey(K key) { + return delegate().floorKey(key); + } + + @Override + public NavigableMap headMap(K toKey, boolean inclusive) { + return delegate().headMap(toKey, inclusive); + } + + @Override + public Entry higherEntry(K key) { + return delegate().higherEntry(key); + } + + @Override + public K higherKey(K key) { + return delegate().higherKey(key); + } + + @Override + public Entry lastEntry() { + return delegate().lastEntry(); + } + + @Override + public Entry lowerEntry(K key) { + return delegate().lowerEntry(key); + } + + @Override + public K lowerKey(K key) { + return delegate().lowerKey(key); + } + + @Override + public NavigableSet navigableKeySet() { + return delegate().navigableKeySet(); + } + + @Override + public Entry pollFirstEntry() { + return delegate().pollFirstEntry(); + } + + @Override + public Entry pollLastEntry() { + return delegate().pollLastEntry(); + } + + /** + * A sensible definition of {@link #ceilingEntry} in terms of the + * {@code firstEntry()} of {@link #tailMap(Object, boolean)}. If you override + * {@code tailMap}, you may wish to override {@code ceilingEntry} to forward to + * this implementation. + */ + protected Entry standardCeilingEntry(K key) { + return tailMap(key, true).firstEntry(); + } + + /** + * A sensible definition of {@link #ceilingKey} in terms of + * {@code ceilingEntry}. If you override {@code ceilingEntry}, you may wish to + * override {@code ceilingKey} to forward to this implementation. + */ + protected K standardCeilingKey(K key) { + return keyOrNull(ceilingEntry(key)); + } + /** * A sensible definition of {@link #descendingKeySet} as the * {@code navigableKeySet} of {@link #descendingMap}. (The @@ -373,29 +253,46 @@ public abstract class ForwardingNavigableMap extends ForwardingSortedMap standardSubMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); + protected Entry standardFirstEntry() { + return Iterables.getFirst(entrySet(), null); } - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive); + /** + * A sensible definition of {@link #firstKey} in terms of {@code firstEntry}. If + * you override {@code firstEntry}, you may wish to override {@code firstKey} to + * forward to this implementation. + */ + protected K standardFirstKey() { + Entry entry = firstEntry(); + if (entry == null) { + throw new NoSuchElementException(); + } else { + return entry.getKey(); + } } - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - return delegate().headMap(toKey, inclusive); + /** + * A sensible definition of {@link #floorEntry} in terms of the + * {@code lastEntry()} of {@link #headMap(Object, boolean)}. If you override + * {@code headMap}, you may wish to override {@code floorEntry} to forward to + * this implementation. + */ + protected Entry standardFloorEntry(K key) { + return headMap(key, true).lastEntry(); } - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - return delegate().tailMap(fromKey, inclusive); + /** + * A sensible definition of {@link #floorKey} in terms of {@code floorEntry}. If + * you override {@code floorEntry}, you may wish to override {@code floorKey} to + * forward to this implementation. + */ + protected K standardFloorKey(K key) { + return keyOrNull(floorEntry(key)); } /** @@ -408,6 +305,99 @@ public abstract class ForwardingNavigableMap extends ForwardingSortedMap standardHigherEntry(K key) { + return tailMap(key, false).firstEntry(); + } + + /** + * A sensible definition of {@link #higherKey} in terms of {@code higherEntry}. + * If you override {@code higherEntry}, you may wish to override + * {@code higherKey} to forward to this implementation. + */ + protected K standardHigherKey(K key) { + return keyOrNull(higherEntry(key)); + } + + /** + * A sensible definition of {@link #lastEntry} in terms of the + * {@code iterator()} of the {@link #entrySet} of {@link #descendingMap}. If you + * override {@code descendingMap}, you may wish to override {@code lastEntry} to + * forward to this implementation. + */ + protected Entry standardLastEntry() { + return Iterables.getFirst(descendingMap().entrySet(), null); + } + + /** + * A sensible definition of {@link #lastKey} in terms of {@code lastEntry}. If + * you override {@code lastEntry}, you may wish to override {@code lastKey} to + * forward to this implementation. + */ + protected K standardLastKey() { + Entry entry = lastEntry(); + if (entry == null) { + throw new NoSuchElementException(); + } else { + return entry.getKey(); + } + } + + /** + * A sensible definition of {@link #lowerEntry} in terms of the + * {@code lastEntry()} of {@link #headMap(Object, boolean)}. If you override + * {@code headMap}, you may wish to override {@code lowerEntry} to forward to + * this implementation. + */ + protected Entry standardLowerEntry(K key) { + return headMap(key, false).lastEntry(); + } + + /** + * A sensible definition of {@link #lowerKey} in terms of {@code lowerEntry}. If + * you override {@link #lowerEntry}, you may wish to override {@code lowerKey} + * to forward to this implementation. + */ + protected K standardLowerKey(K key) { + return keyOrNull(lowerEntry(key)); + } + + /** + * A sensible definition of {@link #pollFirstEntry} in terms of the + * {@code iterator} of {@code entrySet}. If you override {@code entrySet}, you + * may wish to override {@code pollFirstEntry} to forward to this + * implementation. + */ + protected Entry standardPollFirstEntry() { + return Iterators.pollNext(entrySet().iterator()); + } + + /** + * A sensible definition of {@link #pollFirstEntry} in terms of the + * {@code iterator} of the {@code entrySet} of {@code descendingMap}. If you + * override {@code descendingMap}, you may wish to override + * {@code pollFirstEntry} to forward to this implementation. + */ + protected Entry standardPollLastEntry() { + return Iterators.pollNext(descendingMap().entrySet().iterator()); + } + + /** + * A sensible definition of {@link #subMap(Object, Object)} in terms of + * {@link #subMap(Object, boolean, Object, boolean)}. If you override + * {@code subMap(K, boolean, K, boolean)}, you may wish to override + * {@code subMap} to forward to this implementation. + */ + @Override + protected SortedMap standardSubMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); + } + /** * A sensible definition of {@link #tailMap(Object)} in terms of * {@link #tailMap(Object, boolean)}. If you override @@ -417,4 +407,14 @@ public abstract class ForwardingNavigableMap extends ForwardingSortedMap standardTailMap(K fromKey) { return tailMap(fromKey, true); } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return delegate().subMap(fromKey, fromInclusive, toKey, toInclusive); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return delegate().tailMap(fromKey, inclusive); + } } diff --git a/src/main/java/com/google/common/collect/ForwardingNavigableSet.java b/src/main/java/com/google/common/collect/ForwardingNavigableSet.java index 66a3b021..ea179bd5 100644 --- a/src/main/java/com/google/common/collect/ForwardingNavigableSet.java +++ b/src/main/java/com/google/common/collect/ForwardingNavigableSet.java @@ -53,115 +53,6 @@ import com.google.common.annotations.Beta; */ public abstract class ForwardingNavigableSet extends ForwardingSortedSet implements NavigableSet { - /** Constructor for use by subclasses. */ - protected ForwardingNavigableSet() { - } - - @Override - protected abstract NavigableSet delegate(); - - @Override - public E lower(E e) { - return delegate().lower(e); - } - - /** - * A sensible definition of {@link #lower} in terms of the - * {@code descendingIterator} method of {@link #headSet(Object, boolean)}. If - * you override {@link #headSet(Object, boolean)}, you may wish to override - * {@link #lower} to forward to this implementation. - */ - protected E standardLower(E e) { - return Iterators.getNext(headSet(e, false).descendingIterator(), null); - } - - @Override - public E floor(E e) { - return delegate().floor(e); - } - - /** - * A sensible definition of {@link #floor} in terms of the - * {@code descendingIterator} method of {@link #headSet(Object, boolean)}. If - * you override {@link #headSet(Object, boolean)}, you may wish to override - * {@link #floor} to forward to this implementation. - */ - protected E standardFloor(E e) { - return Iterators.getNext(headSet(e, true).descendingIterator(), null); - } - - @Override - public E ceiling(E e) { - return delegate().ceiling(e); - } - - /** - * A sensible definition of {@link #ceiling} in terms of the {@code iterator} - * method of {@link #tailSet(Object, boolean)}. If you override - * {@link #tailSet(Object, boolean)}, you may wish to override {@link #ceiling} - * to forward to this implementation. - */ - protected E standardCeiling(E e) { - return Iterators.getNext(tailSet(e, true).iterator(), null); - } - - @Override - public E higher(E e) { - return delegate().higher(e); - } - - /** - * A sensible definition of {@link #higher} in terms of the {@code iterator} - * method of {@link #tailSet(Object, boolean)}. If you override - * {@link #tailSet(Object, boolean)}, you may wish to override {@link #higher} - * to forward to this implementation. - */ - protected E standardHigher(E e) { - return Iterators.getNext(tailSet(e, false).iterator(), null); - } - - @Override - public E pollFirst() { - return delegate().pollFirst(); - } - - /** - * A sensible definition of {@link #pollFirst} in terms of the {@code iterator} - * method. If you override {@link #iterator} you may wish to override - * {@link #pollFirst} to forward to this implementation. - */ - protected E standardPollFirst() { - return Iterators.pollNext(iterator()); - } - - @Override - public E pollLast() { - return delegate().pollLast(); - } - - /** - * A sensible definition of {@link #pollLast} in terms of the - * {@code descendingIterator} method. If you override - * {@link #descendingIterator} you may wish to override {@link #pollLast} to - * forward to this implementation. - */ - protected E standardPollLast() { - return Iterators.pollNext(descendingIterator()); - } - - protected E standardFirst() { - return iterator().next(); - } - - protected E standardLast() { - return descendingIterator().next(); - } - - @Override - public NavigableSet descendingSet() { - return delegate().descendingSet(); - } - /** * A sensible implementation of {@link NavigableSet#descendingSet} in terms of * the other methods of {@link NavigableSet}, notably including @@ -182,14 +73,133 @@ public abstract class ForwardingNavigableSet extends ForwardingSortedSet i } } + /** Constructor for use by subclasses. */ + protected ForwardingNavigableSet() { + } + + @Override + public E ceiling(E e) { + return delegate().ceiling(e); + } + + @Override + protected abstract NavigableSet delegate(); + @Override public Iterator descendingIterator() { return delegate().descendingIterator(); } @Override - public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return delegate().subSet(fromElement, fromInclusive, toElement, toInclusive); + public NavigableSet descendingSet() { + return delegate().descendingSet(); + } + + @Override + public E floor(E e) { + return delegate().floor(e); + } + + @Override + public NavigableSet headSet(E toElement, boolean inclusive) { + return delegate().headSet(toElement, inclusive); + } + + @Override + public E higher(E e) { + return delegate().higher(e); + } + + @Override + public E lower(E e) { + return delegate().lower(e); + } + + @Override + public E pollFirst() { + return delegate().pollFirst(); + } + + @Override + public E pollLast() { + return delegate().pollLast(); + } + + /** + * A sensible definition of {@link #ceiling} in terms of the {@code iterator} + * method of {@link #tailSet(Object, boolean)}. If you override + * {@link #tailSet(Object, boolean)}, you may wish to override {@link #ceiling} + * to forward to this implementation. + */ + protected E standardCeiling(E e) { + return Iterators.getNext(tailSet(e, true).iterator(), null); + } + + protected E standardFirst() { + return iterator().next(); + } + + /** + * A sensible definition of {@link #floor} in terms of the + * {@code descendingIterator} method of {@link #headSet(Object, boolean)}. If + * you override {@link #headSet(Object, boolean)}, you may wish to override + * {@link #floor} to forward to this implementation. + */ + protected E standardFloor(E e) { + return Iterators.getNext(headSet(e, true).descendingIterator(), null); + } + + /** + * A sensible definition of {@link #headSet(Object)} in terms of the + * {@link #headSet(Object, boolean)} method. If you override + * {@link #headSet(Object, boolean)}, you may wish to override + * {@link #headSet(Object)} to forward to this implementation. + */ + protected SortedSet standardHeadSet(E toElement) { + return headSet(toElement, false); + } + + /** + * A sensible definition of {@link #higher} in terms of the {@code iterator} + * method of {@link #tailSet(Object, boolean)}. If you override + * {@link #tailSet(Object, boolean)}, you may wish to override {@link #higher} + * to forward to this implementation. + */ + protected E standardHigher(E e) { + return Iterators.getNext(tailSet(e, false).iterator(), null); + } + + protected E standardLast() { + return descendingIterator().next(); + } + + /** + * A sensible definition of {@link #lower} in terms of the + * {@code descendingIterator} method of {@link #headSet(Object, boolean)}. If + * you override {@link #headSet(Object, boolean)}, you may wish to override + * {@link #lower} to forward to this implementation. + */ + protected E standardLower(E e) { + return Iterators.getNext(headSet(e, false).descendingIterator(), null); + } + + /** + * A sensible definition of {@link #pollFirst} in terms of the {@code iterator} + * method. If you override {@link #iterator} you may wish to override + * {@link #pollFirst} to forward to this implementation. + */ + protected E standardPollFirst() { + return Iterators.pollNext(iterator()); + } + + /** + * A sensible definition of {@link #pollLast} in terms of the + * {@code descendingIterator} method. If you override + * {@link #descendingIterator} you may wish to override {@link #pollLast} to + * forward to this implementation. + */ + protected E standardPollLast() { + return Iterators.pollNext(descendingIterator()); } /** @@ -214,26 +224,6 @@ public abstract class ForwardingNavigableSet extends ForwardingSortedSet i return subSet(fromElement, true, toElement, false); } - @Override - public NavigableSet headSet(E toElement, boolean inclusive) { - return delegate().headSet(toElement, inclusive); - } - - /** - * A sensible definition of {@link #headSet(Object)} in terms of the - * {@link #headSet(Object, boolean)} method. If you override - * {@link #headSet(Object, boolean)}, you may wish to override - * {@link #headSet(Object)} to forward to this implementation. - */ - protected SortedSet standardHeadSet(E toElement) { - return headSet(toElement, false); - } - - @Override - public NavigableSet tailSet(E fromElement, boolean inclusive) { - return delegate().tailSet(fromElement, inclusive); - } - /** * A sensible definition of {@link #tailSet(Object)} in terms of the * {@link #tailSet(Object, boolean)} method. If you override @@ -243,4 +233,14 @@ public abstract class ForwardingNavigableSet extends ForwardingSortedSet i protected SortedSet standardTailSet(E fromElement) { return tailSet(fromElement, true); } + + @Override + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return delegate().subSet(fromElement, fromInclusive, toElement, toInclusive); + } + + @Override + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return delegate().tailSet(fromElement, inclusive); + } } diff --git a/src/main/java/com/google/common/collect/ForwardingQueue.java b/src/main/java/com/google/common/collect/ForwardingQueue.java index 440c9648..1604a2cd 100644 --- a/src/main/java/com/google/common/collect/ForwardingQueue.java +++ b/src/main/java/com/google/common/collect/ForwardingQueue.java @@ -54,11 +54,21 @@ public abstract class ForwardingQueue extends ForwardingCollection impleme @Override protected abstract Queue delegate(); + @Override + public E element() { + return delegate().element(); + } + @Override public boolean offer(E o) { return delegate().offer(o); } + @Override + public E peek() { + return delegate().peek(); + } + @Override public E poll() { return delegate().poll(); @@ -69,16 +79,6 @@ public abstract class ForwardingQueue extends ForwardingCollection impleme return delegate().remove(); } - @Override - public E peek() { - return delegate().peek(); - } - - @Override - public E element() { - return delegate().element(); - } - /** * A sensible definition of {@link #offer} in terms of {@link #add}. If you * override {@link #add}, you may wish to override {@link #offer} to forward to diff --git a/src/main/java/com/google/common/collect/ForwardingSet.java b/src/main/java/com/google/common/collect/ForwardingSet.java index 49e66c7a..4d84579d 100644 --- a/src/main/java/com/google/common/collect/ForwardingSet.java +++ b/src/main/java/com/google/common/collect/ForwardingSet.java @@ -69,19 +69,6 @@ public abstract class ForwardingSet extends ForwardingCollection implement return delegate().hashCode(); } - /** - * A sensible definition of {@link #removeAll} in terms of {@link #iterator} and - * {@link #remove}. If you override {@code iterator} or {@code remove}, you may - * wish to override {@link #removeAll} to forward to this implementation. - * - * @since 7.0 (this version overrides the {@code ForwardingCollection} version - * as of 12.0) - */ - @Override - protected boolean standardRemoveAll(Collection collection) { - return Sets.removeAllImpl(this, checkNotNull(collection)); // for GWT - } - /** * A sensible definition of {@link #equals} in terms of {@link #size} and * {@link #containsAll}. If you override either of those methods, you may wish @@ -103,4 +90,17 @@ public abstract class ForwardingSet extends ForwardingCollection implement protected int standardHashCode() { return Sets.hashCodeImpl(this); } + + /** + * A sensible definition of {@link #removeAll} in terms of {@link #iterator} and + * {@link #remove}. If you override {@code iterator} or {@code remove}, you may + * wish to override {@link #removeAll} to forward to this implementation. + * + * @since 7.0 (this version overrides the {@code ForwardingCollection} version + * as of 12.0) + */ + @Override + protected boolean standardRemoveAll(Collection collection) { + return Sets.removeAllImpl(this, checkNotNull(collection)); // for GWT + } } diff --git a/src/main/java/com/google/common/collect/ForwardingSortedMap.java b/src/main/java/com/google/common/collect/ForwardingSortedMap.java index 269c5966..737983d3 100644 --- a/src/main/java/com/google/common/collect/ForwardingSortedMap.java +++ b/src/main/java/com/google/common/collect/ForwardingSortedMap.java @@ -60,43 +60,6 @@ import com.google.common.annotations.GwtCompatible; public abstract class ForwardingSortedMap extends ForwardingMap implements SortedMap { // TODO(user): identify places where thread safety is actually lost - /** Constructor for use by subclasses. */ - protected ForwardingSortedMap() { - } - - @Override - protected abstract SortedMap delegate(); - - @Override - public Comparator comparator() { - return delegate().comparator(); - } - - @Override - public K firstKey() { - return delegate().firstKey(); - } - - @Override - public SortedMap headMap(K toKey) { - return delegate().headMap(toKey); - } - - @Override - public K lastKey() { - return delegate().lastKey(); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return delegate().subMap(fromKey, toKey); - } - - @Override - public SortedMap tailMap(K fromKey) { - return delegate().tailMap(fromKey); - } - /** * A sensible implementation of {@link SortedMap#keySet} in terms of the methods * of {@code ForwardingSortedMap}. In many cases, you may wish to override @@ -113,15 +76,31 @@ public abstract class ForwardingSortedMap extends ForwardingMap impl } } - // unsafe, but worst case is a CCE is thrown, which callers will be expecting - @SuppressWarnings("unchecked") - private int unsafeCompare(Object k1, Object k2) { - Comparator comparator = comparator(); - if (comparator == null) { - return ((Comparable) k1).compareTo(k2); - } else { - return ((Comparator) comparator).compare(k1, k2); - } + /** Constructor for use by subclasses. */ + protected ForwardingSortedMap() { + } + + @Override + public Comparator comparator() { + return delegate().comparator(); + } + + @Override + protected abstract SortedMap delegate(); + + @Override + public K firstKey() { + return delegate().firstKey(); + } + + @Override + public SortedMap headMap(K toKey) { + return delegate().headMap(toKey); + } + + @Override + public K lastKey() { + return delegate().lastKey(); } /** @@ -162,4 +141,25 @@ public abstract class ForwardingSortedMap extends ForwardingMap impl checkArgument(unsafeCompare(fromKey, toKey) <= 0, "fromKey must be <= toKey"); return tailMap(fromKey).headMap(toKey); } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + return delegate().subMap(fromKey, toKey); + } + + @Override + public SortedMap tailMap(K fromKey) { + return delegate().tailMap(fromKey); + } + + // unsafe, but worst case is a CCE is thrown, which callers will be expecting + @SuppressWarnings("unchecked") + private int unsafeCompare(Object k1, Object k2) { + Comparator comparator = comparator(); + if (comparator == null) { + return ((Comparable) k1).compareTo(k2); + } else { + return ((Comparator) comparator).compare(k1, k2); + } + } } diff --git a/src/main/java/com/google/common/collect/ForwardingSortedMultiset.java b/src/main/java/com/google/common/collect/ForwardingSortedMultiset.java index 2ce1991d..782b452e 100644 --- a/src/main/java/com/google/common/collect/ForwardingSortedMultiset.java +++ b/src/main/java/com/google/common/collect/ForwardingSortedMultiset.java @@ -48,16 +48,26 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible(emulated = true) public abstract class ForwardingSortedMultiset extends ForwardingMultiset implements SortedMultiset { - /** Constructor for use by subclasses. */ - protected ForwardingSortedMultiset() { - } + /** + * A skeleton implementation of a descending multiset view. Normally, + * {@link #descendingMultiset()} will not reflect any changes you make to the + * behavior of methods such as {@link #add(Object)} or {@link #pollFirstEntry}. + * This skeleton implementation correctly delegates each of its operations to + * the appropriate methods of this {@code + * ForwardingSortedMultiset}. + * + * In many cases, you may wish to override {@link #descendingMultiset()} to + * return an instance of a subclass of {@code StandardDescendingMultiset}. + */ + protected abstract class StandardDescendingMultiset extends DescendingMultiset { + /** Constructor for use by subclasses. */ + public StandardDescendingMultiset() { + } - @Override - protected abstract SortedMultiset delegate(); - - @Override - public NavigableSet elementSet() { - return (NavigableSet) super.elementSet(); + @Override + SortedMultiset forwardMultiset() { + return ForwardingSortedMultiset.this; + } } /** @@ -81,36 +91,26 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset } } + /** Constructor for use by subclasses. */ + protected ForwardingSortedMultiset() { + } + @Override public Comparator comparator() { return delegate().comparator(); } + @Override + protected abstract SortedMultiset delegate(); + @Override public SortedMultiset descendingMultiset() { return delegate().descendingMultiset(); } - /** - * A skeleton implementation of a descending multiset view. Normally, - * {@link #descendingMultiset()} will not reflect any changes you make to the - * behavior of methods such as {@link #add(Object)} or {@link #pollFirstEntry}. - * This skeleton implementation correctly delegates each of its operations to - * the appropriate methods of this {@code - * ForwardingSortedMultiset}. - * - * In many cases, you may wish to override {@link #descendingMultiset()} to - * return an instance of a subclass of {@code StandardDescendingMultiset}. - */ - protected abstract class StandardDescendingMultiset extends DescendingMultiset { - /** Constructor for use by subclasses. */ - public StandardDescendingMultiset() { - } - - @Override - SortedMultiset forwardMultiset() { - return ForwardingSortedMultiset.this; - } + @Override + public NavigableSet elementSet() { + return (NavigableSet) super.elementSet(); } @Override @@ -118,6 +118,26 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset return delegate().firstEntry(); } + @Override + public SortedMultiset headMultiset(E upperBound, BoundType boundType) { + return delegate().headMultiset(upperBound, boundType); + } + + @Override + public Entry lastEntry() { + return delegate().lastEntry(); + } + + @Override + public Entry pollFirstEntry() { + return delegate().pollFirstEntry(); + } + + @Override + public Entry pollLastEntry() { + return delegate().pollLastEntry(); + } + /** * A sensible definition of {@link #firstEntry()} in terms of * {@code entrySet().iterator()}. @@ -134,11 +154,6 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset return Multisets.immutableEntry(entry.getElement(), entry.getCount()); } - @Override - public Entry lastEntry() { - return delegate().lastEntry(); - } - /** * A sensible definition of {@link #lastEntry()} in terms of {@code * descendingMultiset().entrySet().iterator()}. @@ -155,11 +170,6 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset return Multisets.immutableEntry(entry.getElement(), entry.getCount()); } - @Override - public Entry pollFirstEntry() { - return delegate().pollFirstEntry(); - } - /** * A sensible definition of {@link #pollFirstEntry()} in terms of * {@code entrySet().iterator()}. @@ -178,11 +188,6 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset return entry; } - @Override - public Entry pollLastEntry() { - return delegate().pollLastEntry(); - } - /** * A sensible definition of {@link #pollLastEntry()} in terms of {@code * descendingMultiset().entrySet().iterator()}. @@ -201,17 +206,6 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset return entry; } - @Override - public SortedMultiset headMultiset(E upperBound, BoundType boundType) { - return delegate().headMultiset(upperBound, boundType); - } - - @Override - public SortedMultiset subMultiset(E lowerBound, BoundType lowerBoundType, E upperBound, - BoundType upperBoundType) { - return delegate().subMultiset(lowerBound, lowerBoundType, upperBound, upperBoundType); - } - /** * A sensible definition of * {@link #subMultiset(Object, BoundType, Object, BoundType)} in terms of @@ -227,6 +221,12 @@ public abstract class ForwardingSortedMultiset extends ForwardingMultiset return tailMultiset(lowerBound, lowerBoundType).headMultiset(upperBound, upperBoundType); } + @Override + public SortedMultiset subMultiset(E lowerBound, BoundType lowerBoundType, E upperBound, + BoundType upperBoundType) { + return delegate().subMultiset(lowerBound, lowerBoundType, upperBound, upperBoundType); + } + @Override public SortedMultiset tailMultiset(E lowerBound, BoundType boundType) { return delegate().tailMultiset(lowerBound, boundType); diff --git a/src/main/java/com/google/common/collect/ForwardingSortedSet.java b/src/main/java/com/google/common/collect/ForwardingSortedSet.java index b9e53ec5..984a7548 100644 --- a/src/main/java/com/google/common/collect/ForwardingSortedSet.java +++ b/src/main/java/com/google/common/collect/ForwardingSortedSet.java @@ -64,14 +64,14 @@ public abstract class ForwardingSortedSet extends ForwardingSet implements protected ForwardingSortedSet() { } - @Override - protected abstract SortedSet delegate(); - @Override public Comparator comparator() { return delegate().comparator(); } + @Override + protected abstract SortedSet delegate(); + @Override public E first() { return delegate().first(); @@ -87,24 +87,6 @@ public abstract class ForwardingSortedSet extends ForwardingSet implements return delegate().last(); } - @Override - public SortedSet subSet(E fromElement, E toElement) { - return delegate().subSet(fromElement, toElement); - } - - @Override - public SortedSet tailSet(E fromElement) { - return delegate().tailSet(fromElement); - } - - // unsafe, but worst case is a CCE is thrown, which callers will be expecting - @SuppressWarnings("unchecked") - private int unsafeCompare(Object o1, Object o2) { - Comparator comparator = comparator(); - return (comparator == null) ? ((Comparable) o1).compareTo(o2) - : ((Comparator) comparator).compare(o1, o2); - } - /** * A sensible definition of {@link #contains} in terms of the {@code first()} * method of {@link #tailSet}. If you override {@link #tailSet}, you may wish to @@ -172,4 +154,22 @@ public abstract class ForwardingSortedSet extends ForwardingSet implements protected SortedSet standardSubSet(E fromElement, E toElement) { return tailSet(fromElement).headSet(toElement); } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return delegate().subSet(fromElement, toElement); + } + + @Override + public SortedSet tailSet(E fromElement) { + return delegate().tailSet(fromElement); + } + + // unsafe, but worst case is a CCE is thrown, which callers will be expecting + @SuppressWarnings("unchecked") + private int unsafeCompare(Object o1, Object o2) { + Comparator comparator = comparator(); + return (comparator == null) ? ((Comparable) o1).compareTo(o2) + : ((Comparator) comparator).compare(o1, o2); + } } diff --git a/src/main/java/com/google/common/collect/ForwardingTable.java b/src/main/java/com/google/common/collect/ForwardingTable.java index a4d5f725..56fedf44 100644 --- a/src/main/java/com/google/common/collect/ForwardingTable.java +++ b/src/main/java/com/google/common/collect/ForwardingTable.java @@ -38,9 +38,6 @@ public abstract class ForwardingTable extends ForwardingObject implemen protected ForwardingTable() { } - @Override - protected abstract Table delegate(); - @Override public Set> cellSet() { return delegate().cellSet(); @@ -86,11 +83,24 @@ public abstract class ForwardingTable extends ForwardingObject implemen return delegate().containsValue(value); } + @Override + protected abstract Table delegate(); + + @Override + public boolean equals(Object obj) { + return (obj == this) || delegate().equals(obj); + } + @Override public V get(Object rowKey, Object columnKey) { return delegate().get(rowKey, columnKey); } + @Override + public int hashCode() { + return delegate().hashCode(); + } + @Override public boolean isEmpty() { return delegate().isEmpty(); @@ -135,14 +145,4 @@ public abstract class ForwardingTable extends ForwardingObject implemen public Collection values() { return delegate().values(); } - - @Override - public boolean equals(Object obj) { - return (obj == this) || delegate().equals(obj); - } - - @Override - public int hashCode() { - return delegate().hashCode(); - } } diff --git a/src/main/java/com/google/common/collect/GeneralRange.java b/src/main/java/com/google/common/collect/GeneralRange.java index 6e2ff0d6..ab7893b3 100644 --- a/src/main/java/com/google/common/collect/GeneralRange.java +++ b/src/main/java/com/google/common/collect/GeneralRange.java @@ -40,21 +40,6 @@ import com.google.common.base.Objects; */ @GwtCompatible(serializable = true) final class GeneralRange implements Serializable { - /** - * Converts a Range to a GeneralRange. - */ - static GeneralRange from(Range range) { - @Nullable - T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null; - BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN; - - @Nullable - T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null; - BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN; - return new GeneralRange(Ordering.natural(), range.hasLowerBound(), lowerEndpoint, lowerBoundType, - range.hasUpperBound(), upperEndpoint, upperBoundType); - } - /** * Returns the whole range relative to the specified comparator. */ @@ -71,11 +56,18 @@ final class GeneralRange implements Serializable { } /** - * Returns everything below the endpoint relative to the specified comparator, - * with the specified endpoint behavior. + * Converts a Range to a GeneralRange. */ - static GeneralRange upTo(Comparator comparator, @Nullable T endpoint, BoundType boundType) { - return new GeneralRange(comparator, false, null, OPEN, true, endpoint, boundType); + static GeneralRange from(Range range) { + @Nullable + T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null; + BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN; + + @Nullable + T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null; + BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN; + return new GeneralRange(Ordering.natural(), range.hasLowerBound(), lowerEndpoint, lowerBoundType, + range.hasUpperBound(), upperEndpoint, upperBoundType); } /** @@ -87,6 +79,14 @@ final class GeneralRange implements Serializable { return new GeneralRange(comparator, true, lower, lowerType, true, upper, upperType); } + /** + * Returns everything below the endpoint relative to the specified comparator, + * with the specified endpoint behavior. + */ + static GeneralRange upTo(Comparator comparator, @Nullable T endpoint, BoundType boundType) { + return new GeneralRange(comparator, false, null, OPEN, true, endpoint, boundType); + } + private final Comparator comparator; private final boolean hasLowerBound; @Nullable @@ -97,6 +97,8 @@ final class GeneralRange implements Serializable { private final T upperEndpoint; private final BoundType upperBoundType; + private transient GeneralRange reverse; + private GeneralRange(Comparator comparator, boolean hasLowerBound, @Nullable T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound, @Nullable T upperEndpoint, BoundType upperBoundType) { this.comparator = checkNotNull(comparator); @@ -127,6 +129,45 @@ final class GeneralRange implements Serializable { return comparator; } + boolean contains(@Nullable T t) { + return !tooLow(t) && !tooHigh(t); + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof GeneralRange) { + GeneralRange r = (GeneralRange) obj; + return comparator.equals(r.comparator) && hasLowerBound == r.hasLowerBound + && hasUpperBound == r.hasUpperBound && getLowerBoundType().equals(r.getLowerBoundType()) + && getUpperBoundType().equals(r.getUpperBoundType()) + && Objects.equal(getLowerEndpoint(), r.getLowerEndpoint()) + && Objects.equal(getUpperEndpoint(), r.getUpperEndpoint()); + } + return false; + } + + BoundType getLowerBoundType() { + return lowerBoundType; + } + + T getLowerEndpoint() { + return lowerEndpoint; + } + + BoundType getUpperBoundType() { + return upperBoundType; + } + + T getUpperEndpoint() { + return upperEndpoint; + } + + @Override + public int hashCode() { + return Objects.hashCode(comparator, getLowerEndpoint(), getLowerBoundType(), getUpperEndpoint(), + getUpperBoundType()); + } + boolean hasLowerBound() { return hasLowerBound; } @@ -135,32 +176,6 @@ final class GeneralRange implements Serializable { return hasUpperBound; } - boolean isEmpty() { - return (hasUpperBound() && tooLow(getUpperEndpoint())) || (hasLowerBound() && tooHigh(getLowerEndpoint())); - } - - boolean tooLow(@Nullable T t) { - if (!hasLowerBound()) { - return false; - } - T lbound = getLowerEndpoint(); - int cmp = comparator.compare(t, lbound); - return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN); - } - - boolean tooHigh(@Nullable T t) { - if (!hasUpperBound()) { - return false; - } - T ubound = getUpperEndpoint(); - int cmp = comparator.compare(t, ubound); - return cmp > 0 | (cmp == 0 & getUpperBoundType() == OPEN); - } - - boolean contains(@Nullable T t) { - return !tooLow(t) && !tooHigh(t); - } - /** * Returns the intersection of the two ranges, or an empty range if their * intersection is empty. @@ -214,27 +229,10 @@ final class GeneralRange implements Serializable { return new GeneralRange(comparator, hasLowBound, lowEnd, lowType, hasUpBound, upEnd, upType); } - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof GeneralRange) { - GeneralRange r = (GeneralRange) obj; - return comparator.equals(r.comparator) && hasLowerBound == r.hasLowerBound - && hasUpperBound == r.hasUpperBound && getLowerBoundType().equals(r.getLowerBoundType()) - && getUpperBoundType().equals(r.getUpperBoundType()) - && Objects.equal(getLowerEndpoint(), r.getLowerEndpoint()) - && Objects.equal(getUpperEndpoint(), r.getUpperEndpoint()); - } - return false; + boolean isEmpty() { + return (hasUpperBound() && tooLow(getUpperEndpoint())) || (hasLowerBound() && tooHigh(getLowerEndpoint())); } - @Override - public int hashCode() { - return Objects.hashCode(comparator, getLowerEndpoint(), getLowerBoundType(), getUpperEndpoint(), - getUpperBoundType()); - } - - private transient GeneralRange reverse; - /** * Returns the same range relative to the reversed comparator. */ @@ -249,6 +247,24 @@ final class GeneralRange implements Serializable { return result; } + boolean tooHigh(@Nullable T t) { + if (!hasUpperBound()) { + return false; + } + T ubound = getUpperEndpoint(); + int cmp = comparator.compare(t, ubound); + return cmp > 0 | (cmp == 0 & getUpperBoundType() == OPEN); + } + + boolean tooLow(@Nullable T t) { + if (!hasLowerBound()) { + return false; + } + T lbound = getLowerEndpoint(); + int cmp = comparator.compare(t, lbound); + return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN); + } + @Override public String toString() { return new StringBuilder().append(comparator).append(":").append(lowerBoundType == CLOSED ? '[' : '(') @@ -256,20 +272,4 @@ final class GeneralRange implements Serializable { .append(hasUpperBound ? upperEndpoint : "\u221e").append(upperBoundType == CLOSED ? ']' : ')') .toString(); } - - T getLowerEndpoint() { - return lowerEndpoint; - } - - BoundType getLowerBoundType() { - return lowerBoundType; - } - - T getUpperEndpoint() { - return upperEndpoint; - } - - BoundType getUpperBoundType() { - return upperBoundType; - } } diff --git a/src/main/java/com/google/common/collect/HashBasedTable.java b/src/main/java/com/google/common/collect/HashBasedTable.java index a5677a19..27dd8981 100644 --- a/src/main/java/com/google/common/collect/HashBasedTable.java +++ b/src/main/java/com/google/common/collect/HashBasedTable.java @@ -59,6 +59,8 @@ import com.google.common.base.Supplier; @GwtCompatible(serializable = true) public class HashBasedTable extends StandardTable { private static class Factory implements Supplier>, Serializable { + private static final long serialVersionUID = 0; + final int expectedSize; Factory(int expectedSize) { @@ -69,10 +71,10 @@ public class HashBasedTable extends StandardTable { public Map get() { return Maps.newHashMapWithExpectedSize(expectedSize); } - - private static final long serialVersionUID = 0; } + private static final long serialVersionUID = 0; + /** * Creates an empty {@code HashBasedTable}. */ @@ -109,12 +111,12 @@ public class HashBasedTable extends StandardTable { return result; } + // Overriding so NullPointerTester test passes. + HashBasedTable(Map> backingMap, Factory factory) { super(backingMap, factory); } - // Overriding so NullPointerTester test passes. - @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { return super.contains(rowKey, columnKey); @@ -136,19 +138,17 @@ public class HashBasedTable extends StandardTable { } @Override - public V get(@Nullable Object rowKey, @Nullable Object columnKey) { - return super.get(rowKey, columnKey); + public boolean equals(@Nullable Object obj) { + return super.equals(obj); } @Override - public boolean equals(@Nullable Object obj) { - return super.equals(obj); + public V get(@Nullable Object rowKey, @Nullable Object columnKey) { + return super.get(rowKey, columnKey); } @Override public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { return super.remove(rowKey, columnKey); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/HashBiMap.java b/src/main/java/com/google/common/collect/HashBiMap.java index 83dcc840..0b50a797 100644 --- a/src/main/java/com/google/common/collect/HashBiMap.java +++ b/src/main/java/com/google/common/collect/HashBiMap.java @@ -52,6 +52,325 @@ import com.google.common.base.Objects; @GwtCompatible(emulated = true) public final class HashBiMap extends AbstractMap implements BiMap, Serializable { + private static final class BiEntry extends ImmutableEntry { + final int keyHash; + final int valueHash; + + @Nullable + BiEntry nextInKToVBucket; + + @Nullable + BiEntry nextInVToKBucket; + + BiEntry(K key, int keyHash, V value, int valueHash) { + super(key, value); + this.keyHash = keyHash; + this.valueHash = valueHash; + } + } + + private final class EntrySet extends Maps.EntrySet { + @Override + public Iterator> iterator() { + return new Itr>() { + class MapEntry extends AbstractMapEntry { + BiEntry delegate; + + MapEntry(BiEntry entry) { + this.delegate = entry; + } + + @Override + public K getKey() { + return delegate.key; + } + + @Override + public V getValue() { + return delegate.value; + } + + @Override + public V setValue(V value) { + V oldValue = delegate.value; + int valueHash = hash(value); + if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) { + return value; + } + checkArgument(seekByValue(value, valueHash) == null, "value already present: %s", value); + delete(delegate); + BiEntry newEntry = new BiEntry(delegate.key, delegate.keyHash, value, valueHash); + insert(newEntry); + expectedModCount = modCount; + if (toRemove == delegate) { + toRemove = newEntry; + } + delegate = newEntry; + return oldValue; + } + } + + @Override + Entry output(BiEntry entry) { + return new MapEntry(entry); + } + }; + } + + @Override + Map map() { + return HashBiMap.this; + } + } + + private final class Inverse extends AbstractMap implements BiMap, Serializable { + private final class InverseKeySet extends Maps.KeySet { + InverseKeySet() { + super(Inverse.this); + } + + @Override + public Iterator iterator() { + return new Itr() { + @Override + V output(BiEntry entry) { + return entry.value; + } + }; + } + + @Override + public boolean remove(@Nullable Object o) { + BiEntry entry = seekByValue(o, hash(o)); + if (entry == null) { + return false; + } else { + delete(entry); + return true; + } + } + } + + @Override + public void clear() { + forward().clear(); + } + + @Override + public boolean containsKey(@Nullable Object value) { + return forward().containsValue(value); + } + + @Override + public Set> entrySet() { + return new Maps.EntrySet() { + + @Override + public Iterator> iterator() { + return new Itr>() { + class InverseEntry extends AbstractMapEntry { + BiEntry delegate; + + InverseEntry(BiEntry entry) { + this.delegate = entry; + } + + @Override + public V getKey() { + return delegate.value; + } + + @Override + public K getValue() { + return delegate.key; + } + + @Override + public K setValue(K key) { + K oldKey = delegate.key; + int keyHash = hash(key); + if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) { + return key; + } + checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key); + delete(delegate); + BiEntry newEntry = new BiEntry(key, keyHash, delegate.value, + delegate.valueHash); + insert(newEntry); + expectedModCount = modCount; + // This is safe because entries can only get bumped up to earlier in the + // iteration, + // so they can't get revisited. + return oldKey; + } + } + + @Override + Entry output(BiEntry entry) { + return new InverseEntry(entry); + } + }; + } + + @Override + Map map() { + return Inverse.this; + } + }; + } + + @Override + public K forcePut(@Nullable V value, @Nullable K key) { + return putInverse(value, key, true); + } + + BiMap forward() { + return HashBiMap.this; + } + + @Override + public K get(@Nullable Object value) { + BiEntry entry = seekByValue(value, hash(value)); + return (entry == null) ? null : entry.key; + } + + @Override + public BiMap inverse() { + return forward(); + } + + @Override + public Set keySet() { + return new InverseKeySet(); + } + + @Override + public K put(@Nullable V value, @Nullable K key) { + return putInverse(value, key, false); + } + + @Override + public K remove(@Nullable Object value) { + BiEntry entry = seekByValue(value, hash(value)); + if (entry == null) { + return null; + } else { + delete(entry); + return entry.key; + } + } + + @Override + public int size() { + return size; + } + + @Override + public Set values() { + return forward().keySet(); + } + + Object writeReplace() { + return new InverseSerializedForm(HashBiMap.this); + } + } + + private static final class InverseSerializedForm implements Serializable { + private final HashBiMap bimap; + + InverseSerializedForm(HashBiMap bimap) { + this.bimap = bimap; + } + + Object readResolve() { + return bimap.inverse(); + } + } + + abstract class Itr implements Iterator { + int nextBucket = 0; + BiEntry next = null; + BiEntry toRemove = null; + int expectedModCount = modCount; + + private void checkForConcurrentModification() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + @Override + public boolean hasNext() { + checkForConcurrentModification(); + if (next != null) { + return true; + } + while (nextBucket < hashTableKToV.length) { + if (hashTableKToV[nextBucket] != null) { + next = hashTableKToV[nextBucket++]; + return true; + } + nextBucket++; + } + return false; + } + + @Override + public T next() { + checkForConcurrentModification(); + if (!hasNext()) { + throw new NoSuchElementException(); + } + + BiEntry entry = next; + next = entry.nextInKToVBucket; + toRemove = entry; + return output(entry); + } + + abstract T output(BiEntry entry); + + @Override + public void remove() { + checkForConcurrentModification(); + checkRemove(toRemove != null); + delete(toRemove); + expectedModCount = modCount; + toRemove = null; + } + } + + private final class KeySet extends Maps.KeySet { + KeySet() { + super(HashBiMap.this); + } + + @Override + public Iterator iterator() { + return new Itr() { + @Override + K output(BiEntry entry) { + return entry.key; + } + }; + } + + @Override + public boolean remove(@Nullable Object o) { + BiEntry entry = seekByKey(o, hash(o)); + if (entry == null) { + return false; + } else { + delete(entry); + return true; + } + } + } + + private static final double LOAD_FACTOR = 1.0; + @GwtIncompatible("Not needed in emulated source") + private static final long serialVersionUID = 0; + /** * Returns a new, empty {@code HashBiMap} with the default initial capacity * (16). @@ -81,43 +400,47 @@ public final class HashBiMap extends AbstractMap implements BiMap extends ImmutableEntry { - final int keyHash; - final int valueHash; - - @Nullable - BiEntry nextInKToVBucket; - - @Nullable - BiEntry nextInVToKBucket; - - BiEntry(K key, int keyHash, V value, int valueHash) { - super(key, value); - this.keyHash = keyHash; - this.valueHash = valueHash; - } + private static int hash(@Nullable Object o) { + return Hashing.smear((o == null) ? 0 : o.hashCode()); } - private static final double LOAD_FACTOR = 1.0; - private transient BiEntry[] hashTableKToV; + private transient BiEntry[] hashTableVToK; + private transient int size; + private transient int mask; + private transient int modCount; + private transient BiMap inverse; + private HashBiMap(int expectedSize) { init(expectedSize); } - private void init(int expectedSize) { - checkNonnegative(expectedSize, "expectedSize"); - int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); - this.hashTableKToV = createTable(tableSize); - this.hashTableVToK = createTable(tableSize); - this.mask = tableSize - 1; - this.modCount = 0; - this.size = 0; + @Override + public void clear() { + size = 0; + Arrays.fill(hashTableKToV, null); + Arrays.fill(hashTableVToK, null); + modCount++; + } + + @Override + public boolean containsKey(@Nullable Object key) { + return seekByKey(key, hash(key)) != null; + } + + @Override + public boolean containsValue(@Nullable Object value) { + return seekByValue(value, hash(value)) != null; + } + + @SuppressWarnings("unchecked") + private BiEntry[] createTable(int length) { + return new BiEntry[length]; } /** @@ -157,6 +480,33 @@ public final class HashBiMap extends AbstractMap implements BiMap> entrySet() { + return new EntrySet(); + } + + @Override + public V forcePut(@Nullable K key, @Nullable V value) { + return put(key, value, true); + } + + @Nullable + @Override + public V get(@Nullable Object key) { + BiEntry entry = seekByKey(key, hash(key)); + return (entry == null) ? null : entry.value; + } + + private void init(int expectedSize) { + checkNonnegative(expectedSize, "expectedSize"); + int tableSize = Hashing.closedTableSize(expectedSize, LOAD_FACTOR); + this.hashTableKToV = createTable(tableSize); + this.hashTableVToK = createTable(tableSize); + this.mask = tableSize - 1; + this.modCount = 0; + this.size = 0; + } + private void insert(BiEntry entry) { int keyBucket = entry.keyHash & mask; entry.nextInKToVBucket = hashTableKToV[keyBucket]; @@ -170,43 +520,14 @@ public final class HashBiMap extends AbstractMap implements BiMap seekByKey(@Nullable Object key, int keyHash) { - for (BiEntry entry = hashTableKToV[keyHash & mask]; entry != null; entry = entry.nextInKToVBucket) { - if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) { - return entry; - } - } - return null; - } - - private BiEntry seekByValue(@Nullable Object value, int valueHash) { - for (BiEntry entry = hashTableVToK[valueHash & mask]; entry != null; entry = entry.nextInVToKBucket) { - if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) { - return entry; - } - } - return null; + @Override + public BiMap inverse() { + return (inverse == null) ? inverse = new Inverse() : inverse; } @Override - public boolean containsKey(@Nullable Object key) { - return seekByKey(key, hash(key)) != null; - } - - @Override - public boolean containsValue(@Nullable Object value) { - return seekByValue(value, hash(value)) != null; - } - - @Nullable - @Override - public V get(@Nullable Object key) { - BiEntry entry = seekByKey(key, hash(key)); - return (entry == null) ? null : entry.value; + public Set keySet() { + return new KeySet(); } @Override @@ -214,11 +535,6 @@ public final class HashBiMap extends AbstractMap implements BiMap extends AbstractMap implements BiMap[] oldKToV = hashTableKToV; if (Hashing.needsResizing(size, oldKToV.length, LOAD_FACTOR)) { @@ -298,11 +622,6 @@ public final class HashBiMap extends AbstractMap implements BiMap[] createTable(int length) { - return new BiEntry[length]; - } - @Override public V remove(@Nullable Object key) { BiEntry entry = seekByKey(key, hash(key)); @@ -314,12 +633,22 @@ public final class HashBiMap extends AbstractMap implements BiMap seekByKey(@Nullable Object key, int keyHash) { + for (BiEntry entry = hashTableKToV[keyHash & mask]; entry != null; entry = entry.nextInKToVBucket) { + if (keyHash == entry.keyHash && Objects.equal(key, entry.key)) { + return entry; + } + } + return null; + } + + private BiEntry seekByValue(@Nullable Object value, int valueHash) { + for (BiEntry entry = hashTableVToK[valueHash & mask]; entry != null; entry = entry.nextInVToKBucket) { + if (valueHash == entry.valueHash && Objects.equal(value, entry.value)) { + return entry; + } + } + return null; } @Override @@ -327,326 +656,11 @@ public final class HashBiMap extends AbstractMap implements BiMap implements Iterator { - int nextBucket = 0; - BiEntry next = null; - BiEntry toRemove = null; - int expectedModCount = modCount; - - private void checkForConcurrentModification() { - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - } - - @Override - public boolean hasNext() { - checkForConcurrentModification(); - if (next != null) { - return true; - } - while (nextBucket < hashTableKToV.length) { - if (hashTableKToV[nextBucket] != null) { - next = hashTableKToV[nextBucket++]; - return true; - } - nextBucket++; - } - return false; - } - - @Override - public T next() { - checkForConcurrentModification(); - if (!hasNext()) { - throw new NoSuchElementException(); - } - - BiEntry entry = next; - next = entry.nextInKToVBucket; - toRemove = entry; - return output(entry); - } - - @Override - public void remove() { - checkForConcurrentModification(); - checkRemove(toRemove != null); - delete(toRemove); - expectedModCount = modCount; - toRemove = null; - } - - abstract T output(BiEntry entry); - } - - @Override - public Set keySet() { - return new KeySet(); - } - - private final class KeySet extends Maps.KeySet { - KeySet() { - super(HashBiMap.this); - } - - @Override - public Iterator iterator() { - return new Itr() { - @Override - K output(BiEntry entry) { - return entry.key; - } - }; - } - - @Override - public boolean remove(@Nullable Object o) { - BiEntry entry = seekByKey(o, hash(o)); - if (entry == null) { - return false; - } else { - delete(entry); - return true; - } - } - } - @Override public Set values() { return inverse().keySet(); } - @Override - public Set> entrySet() { - return new EntrySet(); - } - - private final class EntrySet extends Maps.EntrySet { - @Override - Map map() { - return HashBiMap.this; - } - - @Override - public Iterator> iterator() { - return new Itr>() { - @Override - Entry output(BiEntry entry) { - return new MapEntry(entry); - } - - class MapEntry extends AbstractMapEntry { - BiEntry delegate; - - MapEntry(BiEntry entry) { - this.delegate = entry; - } - - @Override - public K getKey() { - return delegate.key; - } - - @Override - public V getValue() { - return delegate.value; - } - - @Override - public V setValue(V value) { - V oldValue = delegate.value; - int valueHash = hash(value); - if (valueHash == delegate.valueHash && Objects.equal(value, oldValue)) { - return value; - } - checkArgument(seekByValue(value, valueHash) == null, "value already present: %s", value); - delete(delegate); - BiEntry newEntry = new BiEntry(delegate.key, delegate.keyHash, value, valueHash); - insert(newEntry); - expectedModCount = modCount; - if (toRemove == delegate) { - toRemove = newEntry; - } - delegate = newEntry; - return oldValue; - } - } - }; - } - } - - private transient BiMap inverse; - - @Override - public BiMap inverse() { - return (inverse == null) ? inverse = new Inverse() : inverse; - } - - private final class Inverse extends AbstractMap implements BiMap, Serializable { - BiMap forward() { - return HashBiMap.this; - } - - @Override - public int size() { - return size; - } - - @Override - public void clear() { - forward().clear(); - } - - @Override - public boolean containsKey(@Nullable Object value) { - return forward().containsValue(value); - } - - @Override - public K get(@Nullable Object value) { - BiEntry entry = seekByValue(value, hash(value)); - return (entry == null) ? null : entry.key; - } - - @Override - public K put(@Nullable V value, @Nullable K key) { - return putInverse(value, key, false); - } - - @Override - public K forcePut(@Nullable V value, @Nullable K key) { - return putInverse(value, key, true); - } - - @Override - public K remove(@Nullable Object value) { - BiEntry entry = seekByValue(value, hash(value)); - if (entry == null) { - return null; - } else { - delete(entry); - return entry.key; - } - } - - @Override - public BiMap inverse() { - return forward(); - } - - @Override - public Set keySet() { - return new InverseKeySet(); - } - - private final class InverseKeySet extends Maps.KeySet { - InverseKeySet() { - super(Inverse.this); - } - - @Override - public boolean remove(@Nullable Object o) { - BiEntry entry = seekByValue(o, hash(o)); - if (entry == null) { - return false; - } else { - delete(entry); - return true; - } - } - - @Override - public Iterator iterator() { - return new Itr() { - @Override - V output(BiEntry entry) { - return entry.value; - } - }; - } - } - - @Override - public Set values() { - return forward().keySet(); - } - - @Override - public Set> entrySet() { - return new Maps.EntrySet() { - - @Override - Map map() { - return Inverse.this; - } - - @Override - public Iterator> iterator() { - return new Itr>() { - @Override - Entry output(BiEntry entry) { - return new InverseEntry(entry); - } - - class InverseEntry extends AbstractMapEntry { - BiEntry delegate; - - InverseEntry(BiEntry entry) { - this.delegate = entry; - } - - @Override - public V getKey() { - return delegate.value; - } - - @Override - public K getValue() { - return delegate.key; - } - - @Override - public K setValue(K key) { - K oldKey = delegate.key; - int keyHash = hash(key); - if (keyHash == delegate.keyHash && Objects.equal(key, oldKey)) { - return key; - } - checkArgument(seekByKey(key, keyHash) == null, "value already present: %s", key); - delete(delegate); - BiEntry newEntry = new BiEntry(key, keyHash, delegate.value, - delegate.valueHash); - insert(newEntry); - expectedModCount = modCount; - // This is safe because entries can only get bumped up to earlier in the - // iteration, - // so they can't get revisited. - return oldKey; - } - } - }; - } - }; - } - - Object writeReplace() { - return new InverseSerializedForm(HashBiMap.this); - } - } - - private static final class InverseSerializedForm implements Serializable { - private final HashBiMap bimap; - - InverseSerializedForm(HashBiMap bimap) { - this.bimap = bimap; - } - - Object readResolve() { - return bimap.inverse(); - } - } - /** * @serialData the number of entries, first key, first value, second key, second * value, and so on. @@ -656,15 +670,4 @@ public final class HashBiMap extends AbstractMap implements BiMap extends AbstractSetMultimap { private static final int DEFAULT_VALUES_PER_KEY = 2; - @VisibleForTesting - transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; + @GwtIncompatible("Not needed in emulated source") + private static final long serialVersionUID = 0; /** * Creates a new, empty {@code HashMultimap} with the default initial @@ -88,6 +88,9 @@ public final class HashMultimap extends AbstractSetMultimap { return new HashMultimap(multimap); } + @VisibleForTesting + transient int expectedValuesPerKey = DEFAULT_VALUES_PER_KEY; + private HashMultimap() { super(new HashMap>()); } @@ -116,6 +119,16 @@ public final class HashMultimap extends AbstractSetMultimap { return Sets.newHashSetWithExpectedSize(expectedValuesPerKey); } + @GwtIncompatible("java.io.ObjectInputStream") + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + expectedValuesPerKey = stream.readInt(); + int distinctKeys = Serialization.readCount(stream); + Map> map = Maps.newHashMapWithExpectedSize(distinctKeys); + setMap(map); + Serialization.populateMultimap(this, stream, distinctKeys); + } + /** * @serialData expectedValuesPerKey, number of distinct keys, and then for each * distinct key: the key, number of values for that key, and the @@ -127,17 +140,4 @@ public final class HashMultimap extends AbstractSetMultimap { stream.writeInt(expectedValuesPerKey); Serialization.writeMultimap(this, stream); } - - @GwtIncompatible("java.io.ObjectInputStream") - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - expectedValuesPerKey = stream.readInt(); - int distinctKeys = Serialization.readCount(stream); - Map> map = Maps.newHashMapWithExpectedSize(distinctKeys); - setMap(map); - Serialization.populateMultimap(this, stream, distinctKeys); - } - - @GwtIncompatible("Not needed in emulated source") - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/HashMultiset.java b/src/main/java/com/google/common/collect/HashMultiset.java index fe5b7b8a..0da02ae9 100644 --- a/src/main/java/com/google/common/collect/HashMultiset.java +++ b/src/main/java/com/google/common/collect/HashMultiset.java @@ -34,6 +34,9 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(serializable = true, emulated = true) public final class HashMultiset extends AbstractMapBasedMultiset { + @GwtIncompatible("Not needed in emulated source.") + private static final long serialVersionUID = 0; + /** * Creates a new, empty {@code HashMultiset} using the default initial capacity. */ @@ -75,6 +78,14 @@ public final class HashMultiset extends AbstractMapBasedMultiset { super(Maps.newHashMapWithExpectedSize(distinctElements)); } + @GwtIncompatible("java.io.ObjectInputStream") + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + int distinctElements = Serialization.readCount(stream); + setBackingMap(Maps.newHashMapWithExpectedSize(distinctElements)); + Serialization.populateMultiset(this, stream, distinctElements); + } + /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on @@ -84,15 +95,4 @@ public final class HashMultiset extends AbstractMapBasedMultiset { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } - - @GwtIncompatible("java.io.ObjectInputStream") - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - int distinctElements = Serialization.readCount(stream); - setBackingMap(Maps.newHashMapWithExpectedSize(distinctElements)); - Serialization.populateMultiset(this, stream, distinctElements); - } - - @GwtIncompatible("Not needed in emulated source.") - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/Hashing.java b/src/main/java/com/google/common/collect/Hashing.java index 8ae5f49f..f8ecedd2 100644 --- a/src/main/java/com/google/common/collect/Hashing.java +++ b/src/main/java/com/google/common/collect/Hashing.java @@ -30,29 +30,9 @@ import com.google.common.primitives.Ints; */ @GwtCompatible final class Hashing { - private Hashing() { - } - private static final int C1 = 0xcc9e2d51; + private static final int C2 = 0x1b873593; - - /* - * This method was rewritten in Java from an intermediate step of the Murmur - * hash function in - * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which - * contained the following header: - * - * MurmurHash3 was written by Austin Appleby, and is placed in the public - * domain. The author hereby disclaims copyright to this source code. - */ - static int smear(int hashCode) { - return C2 * Integer.rotateLeft(hashCode * C1, 15); - } - - static int smearedHash(@Nullable Object o) { - return smear((o == null) ? 0 : o.hashCode()); - } - private static int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; static int closedTableSize(int expectedEntries, double loadFactor) { @@ -71,4 +51,24 @@ final class Hashing { static boolean needsResizing(int size, int tableSize, double loadFactor) { return size > loadFactor * tableSize && tableSize < MAX_TABLE_SIZE; } + + /* + * This method was rewritten in Java from an intermediate step of the Murmur + * hash function in + * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which + * contained the following header: + * + * MurmurHash3 was written by Austin Appleby, and is placed in the public + * domain. The author hereby disclaims copyright to this source code. + */ + static int smear(int hashCode) { + return C2 * Integer.rotateLeft(hashCode * C1, 15); + } + + static int smearedHash(@Nullable Object o) { + return smear((o == null) ? 0 : o.hashCode()); + } + + private Hashing() { + } } diff --git a/src/main/java/com/google/common/collect/ImmutableAsList.java b/src/main/java/com/google/common/collect/ImmutableAsList.java index f36dbfdb..2f489184 100644 --- a/src/main/java/com/google/common/collect/ImmutableAsList.java +++ b/src/main/java/com/google/common/collect/ImmutableAsList.java @@ -33,7 +33,23 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") abstract class ImmutableAsList extends ImmutableList { - abstract ImmutableCollection delegateCollection(); + /** + * Serialized form that leads to the same performance as the original list. + */ + @GwtIncompatible("serialization") + static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + final ImmutableCollection collection; + + SerializedForm(ImmutableCollection collection) { + this.collection = collection; + } + + Object readResolve() { + return collection.asList(); + } + } @Override public boolean contains(Object target) { @@ -42,10 +58,7 @@ abstract class ImmutableAsList extends ImmutableList { return delegateCollection().contains(target); } - @Override - public int size() { - return delegateCollection().size(); - } + abstract ImmutableCollection delegateCollection(); @Override public boolean isEmpty() { @@ -57,29 +70,16 @@ abstract class ImmutableAsList extends ImmutableList { return delegateCollection().isPartialView(); } - /** - * Serialized form that leads to the same performance as the original list. - */ - @GwtIncompatible("serialization") - static class SerializedForm implements Serializable { - final ImmutableCollection collection; - - SerializedForm(ImmutableCollection collection) { - this.collection = collection; - } - - Object readResolve() { - return collection.asList(); - } - - private static final long serialVersionUID = 0; - } - @GwtIncompatible("serialization") private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } + @Override + public int size() { + return delegateCollection().size(); + } + @GwtIncompatible("serialization") @Override Object writeReplace() { diff --git a/src/main/java/com/google/common/collect/ImmutableBiMap.java b/src/main/java/com/google/common/collect/ImmutableBiMap.java index 29b7dd75..7a8a568a 100644 --- a/src/main/java/com/google/common/collect/ImmutableBiMap.java +++ b/src/main/java/com/google/common/collect/ImmutableBiMap.java @@ -42,6 +42,150 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible(serializable = true, emulated = true) public abstract class ImmutableBiMap extends ImmutableMap implements BiMap { + /** + * A builder for creating immutable bimap instances, especially {@code public + * static final} bimaps ("constant bimaps"). Example: + * + *
+	 * {
+	 * 	@code
+	 *
+	 * 	static final ImmutableBiMap WORD_TO_INT = new ImmutableBiMap.Builder()
+	 * 			.put("one", 1).put("two", 2).put("three", 3).build();
+	 * }
+	 * 
+ * + *

+ * For small immutable bimaps, the {@code ImmutableBiMap.of()} methods + * are even more convenient. + * + *

+ * Builder instances can be reused - it is safe to call {@link #build} multiple + * times to build multiple bimaps in series. Each bimap is a superset of the + * bimaps created before it. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static final class Builder extends ImmutableMap.Builder { + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableBiMap#builder}. + */ + public Builder() { + } + + /** + * Returns a newly-created immutable bimap. + * + * @throws IllegalArgumentException if duplicate keys or values were added + */ + @Override + public ImmutableBiMap build() { + switch (size) { + case 0: + return of(); + case 1: + return of(entries[0].getKey(), entries[0].getValue()); + default: + return new RegularImmutableBiMap(size, entries); + } + } + + /** + * Associates {@code key} with {@code value} in the built bimap. Duplicate keys + * or values are not allowed, and will cause {@link #build} to fail. + */ + @Override + public Builder put(K key, V value) { + super.put(key, value); + return this; + } + + /** + * Associates all of the given map's keys and values in the built bimap. + * Duplicate keys or values are not allowed, and will cause {@link #build} to + * fail. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + @Override + public Builder putAll(Map map) { + super.putAll(map); + return this; + } + } + + /** + * Serialized type for all ImmutableBiMap instances. It captures the logical + * contents and they are reconstructed using public factory methods. This + * ensures that the implementation types remain as implementation details. + * + * Since the bimap is immutable, ImmutableBiMap doesn't require special logic + * for keeping the bimap and its inverse in sync during serialization, the way + * AbstractBiMap does. + */ + private static class SerializedForm extends ImmutableMap.SerializedForm { + private static final long serialVersionUID = 0; + + SerializedForm(ImmutableBiMap bimap) { + super(bimap); + } + + @Override + Object readResolve() { + Builder builder = new Builder(); + return createMap(builder); + } + } + + private static final Entry[] EMPTY_ENTRY_ARRAY = new Entry[0]; + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns an immutable bimap containing the same entries as {@code map}. If + * {@code map} somehow contains entries with duplicate keys (for example, if it + * is a {@code SortedMap} whose comparator is not consistent with + * equals), the results of this method are undefined. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws IllegalArgumentException if two keys have the same value + * @throws NullPointerException if any key or value in {@code map} is null + */ + public static ImmutableBiMap copyOf(Map map) { + if (map instanceof ImmutableBiMap) { + @SuppressWarnings("unchecked") // safe since map is not writable + ImmutableBiMap bimap = (ImmutableBiMap) map; + // TODO(user): if we need to make a copy of a BiMap because the + // forward map is a view, don't make a copy of the non-view delegate map + if (!bimap.isPartialView()) { + return bimap; + } + } + Entry[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); + switch (entries.length) { + case 0: + return of(); + case 1: + @SuppressWarnings("unchecked") // safe covariant cast in this context + Entry entry = (Entry) entries[0]; + return of(entry.getKey(), entry.getValue()); + default: + return new RegularImmutableBiMap(entries); + } + } + /** * Returns the empty bimap. */ @@ -51,6 +195,8 @@ public abstract class ImmutableBiMap extends ImmutableMap implements return (ImmutableBiMap) EmptyImmutableBiMap.INSTANCE; } + // looking for of() with > 5 entries? Use the builder instead. + /** * Returns an immutable bimap containing a single entry. */ @@ -95,132 +241,21 @@ public abstract class ImmutableBiMap extends ImmutableMap implements entryOf(k5, v5)); } - // looking for of() with > 5 entries? Use the builder instead. - - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * A builder for creating immutable bimap instances, especially {@code public - * static final} bimaps ("constant bimaps"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	static final ImmutableBiMap WORD_TO_INT = new ImmutableBiMap.Builder()
-	 * 			.put("one", 1).put("two", 2).put("three", 3).build();
-	 * }
-	 * 
- * - *

- * For small immutable bimaps, the {@code ImmutableBiMap.of()} methods - * are even more convenient. - * - *

- * Builder instances can be reused - it is safe to call {@link #build} multiple - * times to build multiple bimaps in series. Each bimap is a superset of the - * bimaps created before it. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static final class Builder extends ImmutableMap.Builder { - - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableBiMap#builder}. - */ - public Builder() { - } - - /** - * Associates {@code key} with {@code value} in the built bimap. Duplicate keys - * or values are not allowed, and will cause {@link #build} to fail. - */ - @Override - public Builder put(K key, V value) { - super.put(key, value); - return this; - } - - /** - * Associates all of the given map's keys and values in the built bimap. - * Duplicate keys or values are not allowed, and will cause {@link #build} to - * fail. - * - * @throws NullPointerException if any key or value in {@code map} is null - */ - @Override - public Builder putAll(Map map) { - super.putAll(map); - return this; - } - - /** - * Returns a newly-created immutable bimap. - * - * @throws IllegalArgumentException if duplicate keys or values were added - */ - @Override - public ImmutableBiMap build() { - switch (size) { - case 0: - return of(); - case 1: - return of(entries[0].getKey(), entries[0].getValue()); - default: - return new RegularImmutableBiMap(size, entries); - } - } - } - - /** - * Returns an immutable bimap containing the same entries as {@code map}. If - * {@code map} somehow contains entries with duplicate keys (for example, if it - * is a {@code SortedMap} whose comparator is not consistent with - * equals), the results of this method are undefined. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws IllegalArgumentException if two keys have the same value - * @throws NullPointerException if any key or value in {@code map} is null - */ - public static ImmutableBiMap copyOf(Map map) { - if (map instanceof ImmutableBiMap) { - @SuppressWarnings("unchecked") // safe since map is not writable - ImmutableBiMap bimap = (ImmutableBiMap) map; - // TODO(user): if we need to make a copy of a BiMap because the - // forward map is a view, don't make a copy of the non-view delegate map - if (!bimap.isPartialView()) { - return bimap; - } - } - Entry[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); - switch (entries.length) { - case 0: - return of(); - case 1: - @SuppressWarnings("unchecked") // safe covariant cast in this context - Entry entry = (Entry) entries[0]; - return of(entry.getKey(), entry.getValue()); - default: - return new RegularImmutableBiMap(entries); - } - } - - private static final Entry[] EMPTY_ENTRY_ARRAY = new Entry[0]; - ImmutableBiMap() { } + /** + * Guaranteed to throw an exception and leave the bimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public V forcePut(K key, V value) { + throw new UnsupportedOperationException(); + } + /** * {@inheritDoc} * @@ -239,41 +274,6 @@ public abstract class ImmutableBiMap extends ImmutableMap implements return inverse().keySet(); } - /** - * Guaranteed to throw an exception and leave the bimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public V forcePut(K key, V value) { - throw new UnsupportedOperationException(); - } - - /** - * Serialized type for all ImmutableBiMap instances. It captures the logical - * contents and they are reconstructed using public factory methods. This - * ensures that the implementation types remain as implementation details. - * - * Since the bimap is immutable, ImmutableBiMap doesn't require special logic - * for keeping the bimap and its inverse in sync during serialization, the way - * AbstractBiMap does. - */ - private static class SerializedForm extends ImmutableMap.SerializedForm { - SerializedForm(ImmutableBiMap bimap) { - super(bimap); - } - - @Override - Object readResolve() { - Builder builder = new Builder(); - return createMap(builder); - } - - private static final long serialVersionUID = 0; - } - @Override Object writeReplace() { return new SerializedForm(this); diff --git a/src/main/java/com/google/common/collect/ImmutableClassToInstanceMap.java b/src/main/java/com/google/common/collect/ImmutableClassToInstanceMap.java index ab5aa17e..777b0a1e 100644 --- a/src/main/java/com/google/common/collect/ImmutableClassToInstanceMap.java +++ b/src/main/java/com/google/common/collect/ImmutableClassToInstanceMap.java @@ -35,14 +35,6 @@ import com.google.common.primitives.Primitives; public final class ImmutableClassToInstanceMap extends ForwardingMap, B> implements ClassToInstanceMap, Serializable { - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - /** * A builder for creating immutable class-to-instance maps. Example: * @@ -64,8 +56,22 @@ public final class ImmutableClassToInstanceMap extends ForwardingMap { + private static T cast(Class type, B value) { + return Primitives.wrap(type).cast(value); + } + private final ImmutableMap.Builder, B> mapBuilder = ImmutableMap.builder(); + /** + * Returns a new immutable class-to-instance map containing the entries provided + * to this builder. + * + * @throws IllegalArgumentException if duplicate keys were added + */ + public ImmutableClassToInstanceMap build() { + return new ImmutableClassToInstanceMap(mapBuilder.build()); + } + /** * Associates {@code key} with {@code value} in the built map. Duplicate keys * are not allowed, and will cause {@link #build} to fail. @@ -91,20 +97,14 @@ public final class ImmutableClassToInstanceMap extends ForwardingMap T cast(Class type, B value) { - return Primitives.wrap(type).cast(value); - } - - /** - * Returns a new immutable class-to-instance map containing the entries provided - * to this builder. - * - * @throws IllegalArgumentException if duplicate keys were added - */ - public ImmutableClassToInstanceMap build() { - return new ImmutableClassToInstanceMap(mapBuilder.build()); - } + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); } /** diff --git a/src/main/java/com/google/common/collect/ImmutableCollection.java b/src/main/java/com/google/common/collect/ImmutableCollection.java index 3f674cfb..14d7e7bd 100644 --- a/src/main/java/com/google/common/collect/ImmutableCollection.java +++ b/src/main/java/com/google/common/collect/ImmutableCollection.java @@ -49,166 +49,53 @@ import com.google.common.annotations.GwtCompatible; @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableCollection extends AbstractCollection implements Serializable { - ImmutableCollection() { - } + abstract static class ArrayBasedBuilder extends ImmutableCollection.Builder { + Object[] contents; + int size; - /** - * Returns an unmodifiable iterator across the elements in this collection. - */ - @Override - public abstract UnmodifiableIterator iterator(); - - @Override - public final Object[] toArray() { - int size = size(); - if (size == 0) { - return ObjectArrays.EMPTY_ARRAY; + ArrayBasedBuilder(int initialCapacity) { + checkNonnegative(initialCapacity, "initialCapacity"); + this.contents = new Object[initialCapacity]; + this.size = 0; } - Object[] result = new Object[size()]; - copyIntoArray(result, 0); - return result; - } - @Override - public final T[] toArray(T[] other) { - checkNotNull(other); - int size = size(); - if (other.length < size) { - other = ObjectArrays.newArray(other, size); - } else if (other.length > size) { - other[size] = null; + @Override + public ArrayBasedBuilder add(E element) { + checkNotNull(element); + ensureCapacity(size + 1); + contents[size++] = element; + return this; } - copyIntoArray(other, 0); - return other; - } - @Override - public boolean contains(@Nullable Object object) { - return object != null && super.contains(object); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final boolean add(E e) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final boolean remove(Object object) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final boolean addAll(Collection newElements) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final boolean removeAll(Collection oldElements) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final boolean retainAll(Collection elementsToKeep) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final void clear() { - throw new UnsupportedOperationException(); - } - - /* - * TODO(kevinb): Restructure code so ImmutableList doesn't contain this - * variable, which it doesn't use. - */ - private transient ImmutableList asList; - - /** - * Returns a list view of the collection. - * - * @since 2.0 - */ - public ImmutableList asList() { - ImmutableList list = asList; - return (list == null) ? (asList = createAsList()) : list; - } - - ImmutableList createAsList() { - switch (size()) { - case 0: - return ImmutableList.of(); - case 1: - return ImmutableList.of(iterator().next()); - default: - return new RegularImmutableAsList(this, toArray()); + @Override + public Builder add(E... elements) { + checkElementsNotNull(elements); + ensureCapacity(size + elements.length); + System.arraycopy(elements, 0, contents, size, elements.length); + size += elements.length; + return this; } - } - /** - * Returns {@code true} if this immutable collection's implementation contains - * references to user-created objects that aren't accessible via this - * collection's methods. This is generally used to determine whether - * {@code copyOf} implementations should make an explicit copy to avoid memory - * leaks. - */ - abstract boolean isPartialView(); - - /** - * Copies the contents of this immutable collection into the specified array at - * the specified offset. Returns {@code offset + size()}. - */ - int copyIntoArray(Object[] dst, int offset) { - for (E e : this) { - dst[offset++] = e; + @Override + public Builder addAll(Iterable elements) { + if (elements instanceof Collection) { + Collection collection = (Collection) elements; + ensureCapacity(size + collection.size()); + } + super.addAll(elements); + return this; } - return offset; - } - Object writeReplace() { - // We serialize by default to ImmutableList, the simplest thing that works. - return new ImmutableList.SerializedForm(toArray()); + /** + * Expand the absolute capacity of the builder so it can accept at least the + * specified number of elements without being resized. + */ + private void ensureCapacity(int minCapacity) { + if (contents.length < minCapacity) { + this.contents = ObjectArrays.arraysCopyOf(this.contents, + expandedCapacity(contents.length, minCapacity)); + } + } } /** @@ -322,52 +209,165 @@ public abstract class ImmutableCollection extends AbstractCollection imple public abstract ImmutableCollection build(); } - abstract static class ArrayBasedBuilder extends ImmutableCollection.Builder { - Object[] contents; - int size; + /* + * TODO(kevinb): Restructure code so ImmutableList doesn't contain this + * variable, which it doesn't use. + */ + private transient ImmutableList asList; - ArrayBasedBuilder(int initialCapacity) { - checkNonnegative(initialCapacity, "initialCapacity"); - this.contents = new Object[initialCapacity]; - this.size = 0; + ImmutableCollection() { + } + + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final boolean add(E e) { + throw new UnsupportedOperationException(); + } + + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final boolean addAll(Collection newElements) { + throw new UnsupportedOperationException(); + } + + /** + * Returns a list view of the collection. + * + * @since 2.0 + */ + public ImmutableList asList() { + ImmutableList list = asList; + return (list == null) ? (asList = createAsList()) : list; + } + + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final void clear() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean contains(@Nullable Object object) { + return object != null && super.contains(object); + } + + /** + * Copies the contents of this immutable collection into the specified array at + * the specified offset. Returns {@code offset + size()}. + */ + int copyIntoArray(Object[] dst, int offset) { + for (E e : this) { + dst[offset++] = e; } + return offset; + } - /** - * Expand the absolute capacity of the builder so it can accept at least the - * specified number of elements without being resized. - */ - private void ensureCapacity(int minCapacity) { - if (contents.length < minCapacity) { - this.contents = ObjectArrays.arraysCopyOf(this.contents, - expandedCapacity(contents.length, minCapacity)); - } - } - - @Override - public ArrayBasedBuilder add(E element) { - checkNotNull(element); - ensureCapacity(size + 1); - contents[size++] = element; - return this; - } - - @Override - public Builder add(E... elements) { - checkElementsNotNull(elements); - ensureCapacity(size + elements.length); - System.arraycopy(elements, 0, contents, size, elements.length); - size += elements.length; - return this; - } - - @Override - public Builder addAll(Iterable elements) { - if (elements instanceof Collection) { - Collection collection = (Collection) elements; - ensureCapacity(size + collection.size()); - } - super.addAll(elements); - return this; + ImmutableList createAsList() { + switch (size()) { + case 0: + return ImmutableList.of(); + case 1: + return ImmutableList.of(iterator().next()); + default: + return new RegularImmutableAsList(this, toArray()); } } + + /** + * Returns {@code true} if this immutable collection's implementation contains + * references to user-created objects that aren't accessible via this + * collection's methods. This is generally used to determine whether + * {@code copyOf} implementations should make an explicit copy to avoid memory + * leaks. + */ + abstract boolean isPartialView(); + + /** + * Returns an unmodifiable iterator across the elements in this collection. + */ + @Override + public abstract UnmodifiableIterator iterator(); + + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final boolean remove(Object object) { + throw new UnsupportedOperationException(); + } + + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final boolean removeAll(Collection oldElements) { + throw new UnsupportedOperationException(); + } + + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final boolean retainAll(Collection elementsToKeep) { + throw new UnsupportedOperationException(); + } + + @Override + public final Object[] toArray() { + int size = size(); + if (size == 0) { + return ObjectArrays.EMPTY_ARRAY; + } + Object[] result = new Object[size()]; + copyIntoArray(result, 0); + return result; + } + + @Override + public final T[] toArray(T[] other) { + checkNotNull(other); + int size = size(); + if (other.length < size) { + other = ObjectArrays.newArray(other, size); + } else if (other.length > size) { + other[size] = null; + } + copyIntoArray(other, 0); + return other; + } + + Object writeReplace() { + // We serialize by default to ImmutableList, the simplest thing that works. + return new ImmutableList.SerializedForm(toArray()); + } } diff --git a/src/main/java/com/google/common/collect/ImmutableEntry.java b/src/main/java/com/google/common/collect/ImmutableEntry.java index 577e89fa..96721982 100644 --- a/src/main/java/com/google/common/collect/ImmutableEntry.java +++ b/src/main/java/com/google/common/collect/ImmutableEntry.java @@ -27,7 +27,9 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(serializable = true) class ImmutableEntry extends AbstractMapEntry implements Serializable { + private static final long serialVersionUID = 0; final K key; + final V value; ImmutableEntry(@Nullable K key, @Nullable V value) { @@ -51,6 +53,4 @@ class ImmutableEntry extends AbstractMapEntry implements Serializabl public final V setValue(V value) { throw new UnsupportedOperationException(); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ImmutableEnumMap.java b/src/main/java/com/google/common/collect/ImmutableEnumMap.java index a1532916..4dc265d8 100644 --- a/src/main/java/com/google/common/collect/ImmutableEnumMap.java +++ b/src/main/java/com/google/common/collect/ImmutableEnumMap.java @@ -34,6 +34,23 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization final class ImmutableEnumMap, V> extends ImmutableMap { + /* + * This class is used to serialize ImmutableEnumSet instances. + */ + private static class EnumSerializedForm, V> implements Serializable { + private static final long serialVersionUID = 0; + + final EnumMap delegate; + + EnumSerializedForm(EnumMap delegate) { + this.delegate = delegate; + } + + Object readResolve() { + return new ImmutableEnumMap(delegate); + } + } + static , V> ImmutableMap asImmutable(EnumMap map) { switch (map.size()) { case 0: @@ -54,56 +71,15 @@ final class ImmutableEnumMap, V> extends ImmutableMap { checkArgument(!delegate.isEmpty()); } - @Override - ImmutableSet createKeySet() { - return new ImmutableSet() { - - @Override - public boolean contains(Object object) { - return delegate.containsKey(object); - } - - @Override - public int size() { - return ImmutableEnumMap.this.size(); - } - - @Override - public UnmodifiableIterator iterator() { - return Iterators.unmodifiableIterator(delegate.keySet().iterator()); - } - - @Override - boolean isPartialView() { - return true; - } - }; - } - - @Override - public int size() { - return delegate.size(); - } - @Override public boolean containsKey(@Nullable Object key) { return delegate.containsKey(key); } - @Override - public V get(Object key) { - return delegate.get(key); - } - @Override ImmutableSet> createEntrySet() { return new ImmutableMapEntrySet() { - @Override - ImmutableMap map() { - return ImmutableEnumMap.this; - } - @Override public UnmodifiableIterator> iterator() { return new UnmodifiableIterator>() { @@ -121,34 +97,58 @@ final class ImmutableEnumMap, V> extends ImmutableMap { } }; } + + @Override + ImmutableMap map() { + return ImmutableEnumMap.this; + } }; } + @Override + ImmutableSet createKeySet() { + return new ImmutableSet() { + + @Override + public boolean contains(Object object) { + return delegate.containsKey(object); + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public UnmodifiableIterator iterator() { + return Iterators.unmodifiableIterator(delegate.keySet().iterator()); + } + + @Override + public int size() { + return ImmutableEnumMap.this.size(); + } + }; + } + + @Override + public V get(Object key) { + return delegate.get(key); + } + @Override boolean isPartialView() { return false; } + @Override + public int size() { + return delegate.size(); + } + // All callers of the constructor are restricted to >. @Override Object writeReplace() { return new EnumSerializedForm(delegate); } - - /* - * This class is used to serialize ImmutableEnumSet instances. - */ - private static class EnumSerializedForm, V> implements Serializable { - final EnumMap delegate; - - EnumSerializedForm(EnumMap delegate) { - this.delegate = delegate; - } - - Object readResolve() { - return new ImmutableEnumMap(delegate); - } - - private static final long serialVersionUID = 0; - } } diff --git a/src/main/java/com/google/common/collect/ImmutableEnumSet.java b/src/main/java/com/google/common/collect/ImmutableEnumSet.java index 84381e4a..72ff9fbe 100644 --- a/src/main/java/com/google/common/collect/ImmutableEnumSet.java +++ b/src/main/java/com/google/common/collect/ImmutableEnumSet.java @@ -31,6 +31,24 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization final class ImmutableEnumSet> extends ImmutableSet { + /* + * This class is used to serialize ImmutableEnumSet instances. + */ + private static class EnumSerializedForm> implements Serializable { + private static final long serialVersionUID = 0; + + final EnumSet delegate; + + EnumSerializedForm(EnumSet delegate) { + this.delegate = delegate; + } + + Object readResolve() { + // EJ2 #76: Write readObject() methods defensively. + return new ImmutableEnumSet(delegate.clone()); + } + } + static > ImmutableSet asImmutable(EnumSet set) { switch (set.size()) { case 0: @@ -52,10 +70,38 @@ final class ImmutableEnumSet> extends ImmutableSet { */ private final transient EnumSet delegate; + private transient int hashCode; + private ImmutableEnumSet(EnumSet delegate) { this.delegate = delegate; } + @Override + public boolean contains(Object object) { + return delegate.contains(object); + } + + @Override + public boolean containsAll(Collection collection) { + return delegate.containsAll(collection); + } + + @Override + public boolean equals(Object object) { + return object == this || delegate.equals(object); + } + + @Override + public int hashCode() { + int result = hashCode; + return (result == 0) ? hashCode = delegate.hashCode() : result; + } + + @Override + public boolean isEmpty() { + return delegate.isEmpty(); + } + @Override boolean isPartialView() { return false; @@ -71,34 +117,6 @@ final class ImmutableEnumSet> extends ImmutableSet { return delegate.size(); } - @Override - public boolean contains(Object object) { - return delegate.contains(object); - } - - @Override - public boolean containsAll(Collection collection) { - return delegate.containsAll(collection); - } - - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - @Override - public boolean equals(Object object) { - return object == this || delegate.equals(object); - } - - private transient int hashCode; - - @Override - public int hashCode() { - int result = hashCode; - return (result == 0) ? hashCode = delegate.hashCode() : result; - } - @Override public String toString() { return delegate.toString(); @@ -109,22 +127,4 @@ final class ImmutableEnumSet> extends ImmutableSet { Object writeReplace() { return new EnumSerializedForm(delegate); } - - /* - * This class is used to serialize ImmutableEnumSet instances. - */ - private static class EnumSerializedForm> implements Serializable { - final EnumSet delegate; - - EnumSerializedForm(EnumSet delegate) { - this.delegate = delegate; - } - - Object readResolve() { - // EJ2 #76: Write readObject() methods defensively. - return new ImmutableEnumSet(delegate.clone()); - } - - private static final long serialVersionUID = 0; - } } diff --git a/src/main/java/com/google/common/collect/ImmutableList.java b/src/main/java/com/google/common/collect/ImmutableList.java index 0e00986b..3b0f037b 100644 --- a/src/main/java/com/google/common/collect/ImmutableList.java +++ b/src/main/java/com/google/common/collect/ImmutableList.java @@ -66,8 +66,344 @@ import com.google.common.annotations.GwtCompatible; @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableList extends ImmutableCollection implements List, RandomAccess { + /** + * A builder for creating immutable list instances, especially {@code public + * static final} lists ("constant lists"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	public static final ImmutableList GOOGLE_COLORS = new ImmutableList.Builder()
+	 * 			.addAll(WEBSAFE_COLORS).add(new Color(0, 191, 255)).build();
+	 * }
+	 * 
+ * + *

+ * Builder instances can be reused; it is safe to call {@link #build} multiple + * times to build multiple lists in series. Each new list contains all the + * elements of the ones created before it. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static final class Builder extends ImmutableCollection.ArrayBasedBuilder { + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableList#builder}. + */ + public Builder() { + this(DEFAULT_INITIAL_CAPACITY); + } + + // TODO(user): consider exposing this + Builder(int capacity) { + super(capacity); + } + + /** + * Adds {@code element} to the {@code ImmutableList}. + * + * @param element the element to add + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + */ + @Override + public Builder add(E element) { + super.add(element); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableList}. + * + * @param elements the {@code Iterable} to add to the {@code ImmutableList} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder add(E... elements) { + super.add(elements); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableList}. + * + * @param elements the {@code Iterable} to add to the {@code ImmutableList} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder addAll(Iterable elements) { + super.addAll(elements); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableList}. + * + * @param elements the {@code Iterable} to add to the {@code ImmutableList} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder addAll(Iterator elements) { + super.addAll(elements); + return this; + } + + /** + * Returns a newly-created {@code ImmutableList} based on the contents of the + * {@code Builder}. + */ + @Override + public ImmutableList build() { + return asImmutableList(contents, size); + } + } + + private static class ReverseImmutableList extends ImmutableList { + private final transient ImmutableList forwardList; + + ReverseImmutableList(ImmutableList backingList) { + this.forwardList = backingList; + } + + @Override + public boolean contains(@Nullable Object object) { + return forwardList.contains(object); + } + + @Override + public E get(int index) { + checkElementIndex(index, size()); + return forwardList.get(reverseIndex(index)); + } + + @Override + public int indexOf(@Nullable Object object) { + int index = forwardList.lastIndexOf(object); + return (index >= 0) ? reverseIndex(index) : -1; + } + + @Override + boolean isPartialView() { + return forwardList.isPartialView(); + } + + @Override + public int lastIndexOf(@Nullable Object object) { + int index = forwardList.indexOf(object); + return (index >= 0) ? reverseIndex(index) : -1; + } + + @Override + public ImmutableList reverse() { + return forwardList; + } + + private int reverseIndex(int index) { + return (size() - 1) - index; + } + + private int reversePosition(int index) { + return size() - index; + } + + @Override + public int size() { + return forwardList.size(); + } + + @Override + public ImmutableList subList(int fromIndex, int toIndex) { + checkPositionIndexes(fromIndex, toIndex, size()); + return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse(); + } + } + + /* + * Serializes ImmutableLists as their logical contents. This ensures that + * implementation types do not leak into the serialized representation. + */ + static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + final Object[] elements; + + SerializedForm(Object[] elements) { + this.elements = elements; + } + + Object readResolve() { + return copyOf(elements); + } + } + + class SubList extends ImmutableList { + transient final int offset; + transient final int length; + + SubList(int offset, int length) { + this.offset = offset; + this.length = length; + } + + @Override + public E get(int index) { + checkElementIndex(index, length); + return ImmutableList.this.get(index + offset); + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public int size() { + return length; + } + + @Override + public ImmutableList subList(int fromIndex, int toIndex) { + checkPositionIndexes(fromIndex, toIndex, length); + return ImmutableList.this.subList(fromIndex + offset, toIndex + offset); + } + } + private static final ImmutableList EMPTY = new RegularImmutableList(ObjectArrays.EMPTY_ARRAY); + /** + * Views the array as an immutable list. Does not check for nulls; does not + * copy. + * + *

+ * The array must be internally created. + */ + static ImmutableList asImmutableList(Object[] elements) { + return asImmutableList(elements, elements.length); + } + + /** + * Views the array as an immutable list. Copies if the specified range does not + * cover the complete array. Does not check for nulls. + */ + static ImmutableList asImmutableList(Object[] elements, int length) { + switch (length) { + case 0: + return of(); + case 1: + @SuppressWarnings("unchecked") // collection had only Es in it + ImmutableList list = new SingletonImmutableList((E) elements[0]); + return list; + default: + if (length < elements.length) { + elements = arraysCopyOf(elements, length); + } + return new RegularImmutableList(elements); + } + } + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Views the array as an immutable list. Checks for nulls; does not copy. + */ + private static ImmutableList construct(Object... elements) { + return asImmutableList(checkElementsNotNull(elements)); + } + + /** + * Returns an immutable list containing the given elements, in order. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * Note that if {@code list} is a {@code List}, then {@code + * ImmutableList.copyOf(list)} returns an {@code ImmutableList} + * containing each of the strings in {@code list}, while ImmutableList.of(list)} + * returns an {@code ImmutableList>} containing one element (the + * given list itself). + * + *

+ * This method is safe to use even when {@code elements} is a synchronized or + * concurrent collection that is currently being modified by another thread. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableList copyOf(Collection elements) { + if (elements instanceof ImmutableCollection) { + @SuppressWarnings("unchecked") // all supported methods are covariant + ImmutableList list = ((ImmutableCollection) elements).asList(); + return list.isPartialView() ? ImmutableList.asImmutableList(list.toArray()) : list; + } + return construct(elements.toArray()); + } + + /** + * Returns an immutable list containing the given elements, in order. + * + * @throws NullPointerException if any of {@code elements} is null + * @since 3.0 + */ + public static ImmutableList copyOf(E[] elements) { + switch (elements.length) { + case 0: + return ImmutableList.of(); + case 1: + return new SingletonImmutableList(elements[0]); + default: + return new RegularImmutableList(checkElementsNotNull(elements.clone())); + } + } + + /** + * Returns an immutable list containing the given elements, in order. If + * {@code elements} is a {@link Collection}, this method behaves exactly as + * {@link #copyOf(Collection)}; otherwise, it behaves exactly as {@code + * copyOf(elements.iterator()}. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableList copyOf(Iterable elements) { + checkNotNull(elements); // TODO(kevinb): is this here only for GWT? + return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); + } + + /** + * Returns an immutable list containing the given elements, in order. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableList copyOf(Iterator elements) { + // We special-case for 0 or 1 elements, but going further is madness. + if (!elements.hasNext()) { + return of(); + } + E first = elements.next(); + if (!elements.hasNext()) { + return of(first); + } else { + return new ImmutableList.Builder().add(first).addAll(elements).build(); + } + } + + // These go up to eleven. After that, you just get the varargs form, and + // whatever warnings might come along with it. :( + /** * Returns the empty immutable list. This set behaves and performs comparably to * {@link Collections#emptyList}, and is preferable mainly for consistency and @@ -181,9 +517,6 @@ public abstract class ImmutableList extends ImmutableCollection implements return construct(e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); } - // These go up to eleven. After that, you just get the varargs form, and - // whatever warnings might come along with it. :( - /** * Returns an immutable list containing the given elements, in order. * @@ -209,125 +542,83 @@ public abstract class ImmutableList extends ImmutableCollection implements return construct(array); } - /** - * Returns an immutable list containing the given elements, in order. If - * {@code elements} is a {@link Collection}, this method behaves exactly as - * {@link #copyOf(Collection)}; otherwise, it behaves exactly as {@code - * copyOf(elements.iterator()}. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableList copyOf(Iterable elements) { - checkNotNull(elements); // TODO(kevinb): is this here only for GWT? - return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); - } - - /** - * Returns an immutable list containing the given elements, in order. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * Note that if {@code list} is a {@code List}, then {@code - * ImmutableList.copyOf(list)} returns an {@code ImmutableList} - * containing each of the strings in {@code list}, while ImmutableList.of(list)} - * returns an {@code ImmutableList>} containing one element (the - * given list itself). - * - *

- * This method is safe to use even when {@code elements} is a synchronized or - * concurrent collection that is currently being modified by another thread. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableList copyOf(Collection elements) { - if (elements instanceof ImmutableCollection) { - @SuppressWarnings("unchecked") // all supported methods are covariant - ImmutableList list = ((ImmutableCollection) elements).asList(); - return list.isPartialView() ? ImmutableList.asImmutableList(list.toArray()) : list; - } - return construct(elements.toArray()); - } - - /** - * Returns an immutable list containing the given elements, in order. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableList copyOf(Iterator elements) { - // We special-case for 0 or 1 elements, but going further is madness. - if (!elements.hasNext()) { - return of(); - } - E first = elements.next(); - if (!elements.hasNext()) { - return of(first); - } else { - return new ImmutableList.Builder().add(first).addAll(elements).build(); - } - } - - /** - * Returns an immutable list containing the given elements, in order. - * - * @throws NullPointerException if any of {@code elements} is null - * @since 3.0 - */ - public static ImmutableList copyOf(E[] elements) { - switch (elements.length) { - case 0: - return ImmutableList.of(); - case 1: - return new SingletonImmutableList(elements[0]); - default: - return new RegularImmutableList(checkElementsNotNull(elements.clone())); - } - } - - /** - * Views the array as an immutable list. Checks for nulls; does not copy. - */ - private static ImmutableList construct(Object... elements) { - return asImmutableList(checkElementsNotNull(elements)); - } - - /** - * Views the array as an immutable list. Does not check for nulls; does not - * copy. - * - *

- * The array must be internally created. - */ - static ImmutableList asImmutableList(Object[] elements) { - return asImmutableList(elements, elements.length); - } - - /** - * Views the array as an immutable list. Copies if the specified range does not - * cover the complete array. Does not check for nulls. - */ - static ImmutableList asImmutableList(Object[] elements, int length) { - switch (length) { - case 0: - return of(); - case 1: - @SuppressWarnings("unchecked") // collection had only Es in it - ImmutableList list = new SingletonImmutableList((E) elements[0]); - return list; - default: - if (length < elements.length) { - elements = arraysCopyOf(elements, length); - } - return new RegularImmutableList(elements); - } - } - ImmutableList() { } + /** + * Guaranteed to throw an exception and leave the list unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final void add(int index, E element) { + throw new UnsupportedOperationException(); + } + + // constrain the return type to ImmutableList + + /** + * Guaranteed to throw an exception and leave the list unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final boolean addAll(int index, Collection newElements) { + throw new UnsupportedOperationException(); + } + + /** + * Returns this list instance. + * + * @since 2.0 + */ + @Override + public final ImmutableList asList() { + return this; + } + + @Override + public boolean contains(@Nullable Object object) { + return indexOf(object) >= 0; + } + + @Override + int copyIntoArray(Object[] dst, int offset) { + // this loop is faster for RandomAccess instances, which ImmutableLists are + int size = size(); + for (int i = 0; i < size; i++) { + dst[offset + i] = get(i); + } + return offset + size; + } + + @Override + public boolean equals(@Nullable Object obj) { + return Lists.equalsImpl(this, obj); + } + + @Override + public int hashCode() { + int hashCode = 1; + int n = size(); + for (int i = 0; i < n; i++) { + hashCode = 31 * hashCode + get(i).hashCode(); + + hashCode = ~~hashCode; + // needed to deal with GWT integer overflow + } + return hashCode; + } + + @Override + public int indexOf(@Nullable Object object) { + return (object == null) ? -1 : Lists.indexOfImpl(this, object); + } + // This declaration is needed to make List.iterator() and // ImmutableCollection.iterator() consistent. @Override @@ -335,6 +626,11 @@ public abstract class ImmutableList extends ImmutableCollection implements return listIterator(); } + @Override + public int lastIndexOf(@Nullable Object object) { + return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object); + } + @Override public UnmodifiableListIterator listIterator() { return listIterator(0); @@ -350,22 +646,45 @@ public abstract class ImmutableList extends ImmutableCollection implements }; } - @Override - public int indexOf(@Nullable Object object) { - return (object == null) ? -1 : Lists.indexOfImpl(this, object); + private void readObject(ObjectInputStream stream) throws InvalidObjectException { + throw new InvalidObjectException("Use SerializedForm"); } + /** + * Guaranteed to throw an exception and leave the list unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated @Override - public int lastIndexOf(@Nullable Object object) { - return (object == null) ? -1 : Lists.lastIndexOfImpl(this, object); + public final E remove(int index) { + throw new UnsupportedOperationException(); } - @Override - public boolean contains(@Nullable Object object) { - return indexOf(object) >= 0; + /** + * Returns a view of this immutable list in reverse order. For example, {@code + * ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code + * ImmutableList.of(3, 2, 1)}. + * + * @return a view of this immutable list in reverse order + * @since 7.0 + */ + public ImmutableList reverse() { + return new ReverseImmutableList(this); } - // constrain the return type to ImmutableList + /** + * Guaranteed to throw an exception and leave the list unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final E set(int index, E element) { + throw new UnsupportedOperationException(); + } /** * Returns an immutable list of the elements between the specified {@code @@ -395,327 +714,8 @@ public abstract class ImmutableList extends ImmutableCollection implements return new SubList(fromIndex, toIndex - fromIndex); } - class SubList extends ImmutableList { - transient final int offset; - transient final int length; - - SubList(int offset, int length) { - this.offset = offset; - this.length = length; - } - - @Override - public int size() { - return length; - } - - @Override - public E get(int index) { - checkElementIndex(index, length); - return ImmutableList.this.get(index + offset); - } - - @Override - public ImmutableList subList(int fromIndex, int toIndex) { - checkPositionIndexes(fromIndex, toIndex, length); - return ImmutableList.this.subList(fromIndex + offset, toIndex + offset); - } - - @Override - boolean isPartialView() { - return true; - } - } - - /** - * Guaranteed to throw an exception and leave the list unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final boolean addAll(int index, Collection newElements) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the list unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final E set(int index, E element) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the list unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final void add(int index, E element) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the list unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final E remove(int index) { - throw new UnsupportedOperationException(); - } - - /** - * Returns this list instance. - * - * @since 2.0 - */ - @Override - public final ImmutableList asList() { - return this; - } - - @Override - int copyIntoArray(Object[] dst, int offset) { - // this loop is faster for RandomAccess instances, which ImmutableLists are - int size = size(); - for (int i = 0; i < size; i++) { - dst[offset + i] = get(i); - } - return offset + size; - } - - /** - * Returns a view of this immutable list in reverse order. For example, {@code - * ImmutableList.of(1, 2, 3).reverse()} is equivalent to {@code - * ImmutableList.of(3, 2, 1)}. - * - * @return a view of this immutable list in reverse order - * @since 7.0 - */ - public ImmutableList reverse() { - return new ReverseImmutableList(this); - } - - private static class ReverseImmutableList extends ImmutableList { - private final transient ImmutableList forwardList; - - ReverseImmutableList(ImmutableList backingList) { - this.forwardList = backingList; - } - - private int reverseIndex(int index) { - return (size() - 1) - index; - } - - private int reversePosition(int index) { - return size() - index; - } - - @Override - public ImmutableList reverse() { - return forwardList; - } - - @Override - public boolean contains(@Nullable Object object) { - return forwardList.contains(object); - } - - @Override - public int indexOf(@Nullable Object object) { - int index = forwardList.lastIndexOf(object); - return (index >= 0) ? reverseIndex(index) : -1; - } - - @Override - public int lastIndexOf(@Nullable Object object) { - int index = forwardList.indexOf(object); - return (index >= 0) ? reverseIndex(index) : -1; - } - - @Override - public ImmutableList subList(int fromIndex, int toIndex) { - checkPositionIndexes(fromIndex, toIndex, size()); - return forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex)).reverse(); - } - - @Override - public E get(int index) { - checkElementIndex(index, size()); - return forwardList.get(reverseIndex(index)); - } - - @Override - public int size() { - return forwardList.size(); - } - - @Override - boolean isPartialView() { - return forwardList.isPartialView(); - } - } - - @Override - public boolean equals(@Nullable Object obj) { - return Lists.equalsImpl(this, obj); - } - - @Override - public int hashCode() { - int hashCode = 1; - int n = size(); - for (int i = 0; i < n; i++) { - hashCode = 31 * hashCode + get(i).hashCode(); - - hashCode = ~~hashCode; - // needed to deal with GWT integer overflow - } - return hashCode; - } - - /* - * Serializes ImmutableLists as their logical contents. This ensures that - * implementation types do not leak into the serialized representation. - */ - static class SerializedForm implements Serializable { - final Object[] elements; - - SerializedForm(Object[] elements) { - this.elements = elements; - } - - Object readResolve() { - return copyOf(elements); - } - - private static final long serialVersionUID = 0; - } - - private void readObject(ObjectInputStream stream) throws InvalidObjectException { - throw new InvalidObjectException("Use SerializedForm"); - } - @Override Object writeReplace() { return new SerializedForm(toArray()); } - - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * A builder for creating immutable list instances, especially {@code public - * static final} lists ("constant lists"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	public static final ImmutableList GOOGLE_COLORS = new ImmutableList.Builder()
-	 * 			.addAll(WEBSAFE_COLORS).add(new Color(0, 191, 255)).build();
-	 * }
-	 * 
- * - *

- * Builder instances can be reused; it is safe to call {@link #build} multiple - * times to build multiple lists in series. Each new list contains all the - * elements of the ones created before it. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static final class Builder extends ImmutableCollection.ArrayBasedBuilder { - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableList#builder}. - */ - public Builder() { - this(DEFAULT_INITIAL_CAPACITY); - } - - // TODO(user): consider exposing this - Builder(int capacity) { - super(capacity); - } - - /** - * Adds {@code element} to the {@code ImmutableList}. - * - * @param element the element to add - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - */ - @Override - public Builder add(E element) { - super.add(element); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableList}. - * - * @param elements the {@code Iterable} to add to the {@code ImmutableList} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder addAll(Iterable elements) { - super.addAll(elements); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableList}. - * - * @param elements the {@code Iterable} to add to the {@code ImmutableList} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder add(E... elements) { - super.add(elements); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableList}. - * - * @param elements the {@code Iterable} to add to the {@code ImmutableList} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder addAll(Iterator elements) { - super.addAll(elements); - return this; - } - - /** - * Returns a newly-created {@code ImmutableList} based on the contents of the - * {@code Builder}. - */ - @Override - public ImmutableList build() { - return asImmutableList(contents, size); - } - } } diff --git a/src/main/java/com/google/common/collect/ImmutableListMultimap.java b/src/main/java/com/google/common/collect/ImmutableListMultimap.java index 727b0c49..cde988c6 100644 --- a/src/main/java/com/google/common/collect/ImmutableListMultimap.java +++ b/src/main/java/com/google/common/collect/ImmutableListMultimap.java @@ -58,6 +58,151 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(serializable = true, emulated = true) public class ImmutableListMultimap extends ImmutableMultimap implements ListMultimap { + /** + * A builder for creating immutable {@code ListMultimap} instances, especially + * {@code public static final} multimaps ("constant multimaps"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	static final Multimap STRING_TO_INTEGER_MULTIMAP = new ImmutableListMultimap.Builder()
+	 * 			.put("one", 1).putAll("several", 1, 2, 3).putAll("many", 1, 2, 3, 4, 5).build();
+	 * }
+	 * 
+ * + *

+ * Builder instances can be reused; it is safe to call {@link #build} multiple + * times to build multiple multimaps in series. Each multimap contains the + * key-value mappings in the previously created multimaps. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static final class Builder extends ImmutableMultimap.Builder { + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableListMultimap#builder}. + */ + public Builder() { + } + + /** + * Returns a newly-created immutable list multimap. + */ + @Override + public ImmutableListMultimap build() { + return (ImmutableListMultimap) super.build(); + } + + /** + * {@inheritDoc} + * + * @since 8.0 + */ + @Override + public Builder orderKeysBy(Comparator keyComparator) { + super.orderKeysBy(keyComparator); + return this; + } + + /** + * {@inheritDoc} + * + * @since 8.0 + */ + @Override + public Builder orderValuesBy(Comparator valueComparator) { + super.orderValuesBy(valueComparator); + return this; + } + + /** + * {@inheritDoc} + * + * @since 11.0 + */ + @Override + public Builder put(Entry entry) { + super.put(entry); + return this; + } + + @Override + public Builder put(K key, V value) { + super.put(key, value); + return this; + } + + @Override + public Builder putAll(K key, Iterable values) { + super.putAll(key, values); + return this; + } + + @Override + public Builder putAll(K key, V... values) { + super.putAll(key, values); + return this; + } + + @Override + public Builder putAll(Multimap multimap) { + super.putAll(multimap); + return this; + } + } + + @GwtIncompatible("Not needed in emulated source") + private static final long serialVersionUID = 0; + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns an immutable multimap containing the same mappings as {@code + * multimap}. The generated multimap's key and value orderings correspond to the + * iteration ordering of the {@code multimap.asMap()} view. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if any key or value in {@code multimap} is null + */ + public static ImmutableListMultimap copyOf(Multimap multimap) { + if (multimap.isEmpty()) { + return of(); + } + + // TODO(user): copy ImmutableSetMultimap by using asList() on the sets + if (multimap instanceof ImmutableListMultimap) { + @SuppressWarnings("unchecked") // safe since multimap is not writable + ImmutableListMultimap kvMultimap = (ImmutableListMultimap) multimap; + if (!kvMultimap.isPartialView()) { + return kvMultimap; + } + } + + ImmutableMap.Builder> builder = ImmutableMap.builder(); + int size = 0; + + for (Entry> entry : multimap.asMap().entrySet()) { + ImmutableList list = ImmutableList.copyOf(entry.getValue()); + if (!list.isEmpty()) { + builder.put(entry.getKey(), list); + size += list.size(); + } + } + + return new ImmutableListMultimap(builder.build(), size); + } + /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") @@ -74,6 +219,8 @@ public class ImmutableListMultimap extends ImmutableMultimap impleme return builder.build(); } + // looking for of() with > 5 entries? Use the builder instead. + /** * Returns an immutable multimap containing the given entries, in order. */ @@ -120,156 +267,14 @@ public class ImmutableListMultimap extends ImmutableMultimap impleme return builder.build(); } - // looking for of() with > 5 entries? Use the builder instead. + // views - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * A builder for creating immutable {@code ListMultimap} instances, especially - * {@code public static final} multimaps ("constant multimaps"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	static final Multimap STRING_TO_INTEGER_MULTIMAP = new ImmutableListMultimap.Builder()
-	 * 			.put("one", 1).putAll("several", 1, 2, 3).putAll("many", 1, 2, 3, 4, 5).build();
-	 * }
-	 * 
- * - *

- * Builder instances can be reused; it is safe to call {@link #build} multiple - * times to build multiple multimaps in series. Each multimap contains the - * key-value mappings in the previously created multimaps. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static final class Builder extends ImmutableMultimap.Builder { - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableListMultimap#builder}. - */ - public Builder() { - } - - @Override - public Builder put(K key, V value) { - super.put(key, value); - return this; - } - - /** - * {@inheritDoc} - * - * @since 11.0 - */ - @Override - public Builder put(Entry entry) { - super.put(entry); - return this; - } - - @Override - public Builder putAll(K key, Iterable values) { - super.putAll(key, values); - return this; - } - - @Override - public Builder putAll(K key, V... values) { - super.putAll(key, values); - return this; - } - - @Override - public Builder putAll(Multimap multimap) { - super.putAll(multimap); - return this; - } - - /** - * {@inheritDoc} - * - * @since 8.0 - */ - @Override - public Builder orderKeysBy(Comparator keyComparator) { - super.orderKeysBy(keyComparator); - return this; - } - - /** - * {@inheritDoc} - * - * @since 8.0 - */ - @Override - public Builder orderValuesBy(Comparator valueComparator) { - super.orderValuesBy(valueComparator); - return this; - } - - /** - * Returns a newly-created immutable list multimap. - */ - @Override - public ImmutableListMultimap build() { - return (ImmutableListMultimap) super.build(); - } - } - - /** - * Returns an immutable multimap containing the same mappings as {@code - * multimap}. The generated multimap's key and value orderings correspond to the - * iteration ordering of the {@code multimap.asMap()} view. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if any key or value in {@code multimap} is null - */ - public static ImmutableListMultimap copyOf(Multimap multimap) { - if (multimap.isEmpty()) { - return of(); - } - - // TODO(user): copy ImmutableSetMultimap by using asList() on the sets - if (multimap instanceof ImmutableListMultimap) { - @SuppressWarnings("unchecked") // safe since multimap is not writable - ImmutableListMultimap kvMultimap = (ImmutableListMultimap) multimap; - if (!kvMultimap.isPartialView()) { - return kvMultimap; - } - } - - ImmutableMap.Builder> builder = ImmutableMap.builder(); - int size = 0; - - for (Entry> entry : multimap.asMap().entrySet()) { - ImmutableList list = ImmutableList.copyOf(entry.getValue()); - if (!list.isEmpty()) { - builder.put(entry.getKey(), list); - size += list.size(); - } - } - - return new ImmutableListMultimap(builder.build(), size); - } + private transient ImmutableListMultimap inverse; ImmutableListMultimap(ImmutableMap> map, int size) { super(map, size); } - // views - /** * Returns an immutable list of the values for the given key. If no mappings in * the multimap have the provided key, an empty immutable list is returned. The @@ -282,8 +287,6 @@ public class ImmutableListMultimap extends ImmutableMultimap impleme return (list == null) ? ImmutableList.of() : list; } - private transient ImmutableListMultimap inverse; - /** * {@inheritDoc} * @@ -311,40 +314,6 @@ public class ImmutableListMultimap extends ImmutableMultimap impleme return invertedMultimap; } - /** - * Guaranteed to throw an exception and leave the multimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public ImmutableList removeAll(Object key) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the multimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public ImmutableList replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - /** - * @serialData number of distinct keys, and then for each distinct key: the key, - * the number of values for that key, and the key's values - */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - Serialization.writeMultimap(this, stream); - } - @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @@ -381,6 +350,37 @@ public class ImmutableListMultimap extends ImmutableMultimap impleme FieldSettersHolder.SIZE_FIELD_SETTER.set(this, tmpSize); } - @GwtIncompatible("Not needed in emulated source") - private static final long serialVersionUID = 0; + /** + * Guaranteed to throw an exception and leave the multimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public ImmutableList removeAll(Object key) { + throw new UnsupportedOperationException(); + } + + /** + * Guaranteed to throw an exception and leave the multimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public ImmutableList replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + /** + * @serialData number of distinct keys, and then for each distinct key: the key, + * the number of values for that key, and the key's values + */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + Serialization.writeMultimap(this, stream); + } } diff --git a/src/main/java/com/google/common/collect/ImmutableMap.java b/src/main/java/com/google/common/collect/ImmutableMap.java index 139938bf..b2acd433 100644 --- a/src/main/java/com/google/common/collect/ImmutableMap.java +++ b/src/main/java/com/google/common/collect/ImmutableMap.java @@ -64,6 +64,300 @@ import com.google.common.collect.ImmutableMapEntry.TerminalEntry; @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableMap implements Map, Serializable { + /** + * A builder for creating immutable map instances, especially {@code public + * static final} maps ("constant maps"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	static final ImmutableMap WORD_TO_INT = new ImmutableMap.Builder()
+	 * 			.put("one", 1).put("two", 2).put("three", 3).build();
+	 * }
+	 * 
+ * + *

+ * For small immutable maps, the {@code ImmutableMap.of()} methods are + * even more convenient. + * + *

+ * Builder instances can be reused - it is safe to call {@link #build} multiple + * times to build multiple maps in series. Each map is a superset of the maps + * created before it. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static class Builder { + TerminalEntry[] entries; + int size; + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableMap#builder}. + */ + public Builder() { + this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); + } + + @SuppressWarnings("unchecked") + Builder(int initialCapacity) { + this.entries = new TerminalEntry[initialCapacity]; + this.size = 0; + } + + /** + * Returns a newly-created immutable map. + * + * @throws IllegalArgumentException if duplicate keys were added + */ + public ImmutableMap build() { + switch (size) { + case 0: + return of(); + case 1: + return of(entries[0].getKey(), entries[0].getValue()); + default: + return new RegularImmutableMap(size, entries); + } + } + + private void ensureCapacity(int minCapacity) { + if (minCapacity > entries.length) { + entries = ObjectArrays.arraysCopyOf(entries, + ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity)); + } + } + + /** + * Adds the given {@code entry} to the map, making it immutable if necessary. + * Duplicate keys are not allowed, and will cause {@link #build} to fail. + * + * @since 11.0 + */ + public Builder put(Entry entry) { + return put(entry.getKey(), entry.getValue()); + } + + /** + * Associates {@code key} with {@code value} in the built map. Duplicate keys + * are not allowed, and will cause {@link #build} to fail. + */ + public Builder put(K key, V value) { + ensureCapacity(size + 1); + TerminalEntry entry = entryOf(key, value); + // don't inline this: we want to fail atomically if key or value is null + entries[size++] = entry; + return this; + } + + /* + * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap + * versions throw an IllegalStateException instead? + */ + + /** + * Associates all of the given map's keys and values in the built map. Duplicate + * keys are not allowed, and will cause {@link #build} to fail. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + public Builder putAll(Map map) { + ensureCapacity(size + map.size()); + for (Entry entry : map.entrySet()) { + put(entry); + } + return this; + } + } + + private static final class MapViewOfValuesAsSingletonSets extends ImmutableMap> { + private final ImmutableMap delegate; + + MapViewOfValuesAsSingletonSets(ImmutableMap delegate) { + this.delegate = checkNotNull(delegate); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return delegate.containsKey(key); + } + + @Override + ImmutableSet>> createEntrySet() { + return new ImmutableMapEntrySet>() { + @Override + public UnmodifiableIterator>> iterator() { + final Iterator> backingIterator = delegate.entrySet().iterator(); + return new UnmodifiableIterator>>() { + @Override + public boolean hasNext() { + return backingIterator.hasNext(); + } + + @Override + public Entry> next() { + final Entry backingEntry = backingIterator.next(); + return new AbstractMapEntry>() { + @Override + public K getKey() { + return backingEntry.getKey(); + } + + @Override + public ImmutableSet getValue() { + return ImmutableSet.of(backingEntry.getValue()); + } + }; + } + }; + } + + @Override + ImmutableMap> map() { + return MapViewOfValuesAsSingletonSets.this; + } + }; + } + + @Override + public ImmutableSet get(@Nullable Object key) { + V outerValue = delegate.get(key); + return (outerValue == null) ? null : ImmutableSet.of(outerValue); + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public int size() { + return delegate.size(); + } + } + + /** + * Serialized type for all ImmutableMap instances. It captures the logical + * contents and they are reconstructed using public factory methods. This + * ensures that the implementation types remain as implementation details. + */ + static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + private final Object[] keys; + + private final Object[] values; + + SerializedForm(ImmutableMap map) { + keys = new Object[map.size()]; + values = new Object[map.size()]; + int i = 0; + for (Entry entry : map.entrySet()) { + keys[i] = entry.getKey(); + values[i] = entry.getValue(); + i++; + } + } + + Object createMap(Builder builder) { + for (int i = 0; i < keys.length; i++) { + builder.put(keys[i], values[i]); + } + return builder.build(); + } + + Object readResolve() { + Builder builder = new Builder(); + return createMap(builder); + } + } + + private static final Entry[] EMPTY_ENTRY_ARRAY = new Entry[0]; + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + static void checkNoConflict(boolean safe, String conflictDescription, Entry entry1, Entry entry2) { + if (!safe) { + throw new IllegalArgumentException( + "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2); + } + } + + // looking for of() with > 5 entries? Use the builder instead. + + /** + * Returns an immutable map containing the same entries as {@code map}. If + * {@code map} somehow contains entries with duplicate keys (for example, if it + * is a {@code SortedMap} whose comparator is not consistent with + * equals), the results of this method are undefined. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + public static ImmutableMap copyOf(Map map) { + if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) { + // TODO(user): Make ImmutableMap.copyOf(immutableBiMap) call copyOf() + // on the ImmutableMap delegate(), rather than the bimap itself + + @SuppressWarnings("unchecked") // safe since map is not writable + ImmutableMap kvMap = (ImmutableMap) map; + if (!kvMap.isPartialView()) { + return kvMap; + } + } else if (map instanceof EnumMap) { + return copyOfEnumMapUnsafe(map); + } + Entry[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); + switch (entries.length) { + case 0: + return of(); + case 1: + @SuppressWarnings("unchecked") // all entries will be Entry's + Entry onlyEntry = (Entry) entries[0]; + return of(onlyEntry.getKey(), onlyEntry.getValue()); + default: + return new RegularImmutableMap(entries); + } + } + + private static , V> ImmutableMap copyOfEnumMap(Map original) { + EnumMap copy = new EnumMap(original); + for (Map.Entry entry : copy.entrySet()) { + checkEntryNotNull(entry.getKey(), entry.getValue()); + } + return ImmutableEnumMap.asImmutable(copy); + } + + // If the map is an EnumMap, it must have key type K for some >. + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static ImmutableMap copyOfEnumMapUnsafe(Map map) { + return copyOfEnumMap((EnumMap) map); + } + + /** + * Verifies that {@code key} and {@code value} are non-null, and returns a new + * immutable entry with those values. + * + *

+ * A call to {@link Map.Entry#setValue} on the returned entry will always throw + * {@link UnsupportedOperationException}. + */ + static TerminalEntry entryOf(K key, V value) { + checkEntryNotNull(key, value); + return new TerminalEntry(key, value); + } + /** * Returns the empty map. This map behaves and performs comparably to * {@link Collections#emptyMap}, and is preferable mainly for consistency and @@ -120,202 +414,105 @@ public abstract class ImmutableMap implements Map, Serializable { entryOf(k5, v5)); } - // looking for of() with > 5 entries? Use the builder instead. + private transient ImmutableSet> entrySet; - /** - * Verifies that {@code key} and {@code value} are non-null, and returns a new - * immutable entry with those values. - * - *

- * A call to {@link Map.Entry#setValue} on the returned entry will always throw - * {@link UnsupportedOperationException}. - */ - static TerminalEntry entryOf(K key, V value) { - checkEntryNotNull(key, value); - return new TerminalEntry(key, value); - } + private transient ImmutableSet keySet; - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } + private transient ImmutableCollection values; - static void checkNoConflict(boolean safe, String conflictDescription, Entry entry1, Entry entry2) { - if (!safe) { - throw new IllegalArgumentException( - "Multiple entries with same " + conflictDescription + ": " + entry1 + " and " + entry2); - } - } - - /** - * A builder for creating immutable map instances, especially {@code public - * static final} maps ("constant maps"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	static final ImmutableMap WORD_TO_INT = new ImmutableMap.Builder()
-	 * 			.put("one", 1).put("two", 2).put("three", 3).build();
-	 * }
-	 * 
- * - *

- * For small immutable maps, the {@code ImmutableMap.of()} methods are - * even more convenient. - * - *

- * Builder instances can be reused - it is safe to call {@link #build} multiple - * times to build multiple maps in series. Each map is a superset of the maps - * created before it. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static class Builder { - TerminalEntry[] entries; - int size; - - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableMap#builder}. - */ - public Builder() { - this(ImmutableCollection.Builder.DEFAULT_INITIAL_CAPACITY); - } - - @SuppressWarnings("unchecked") - Builder(int initialCapacity) { - this.entries = new TerminalEntry[initialCapacity]; - this.size = 0; - } - - private void ensureCapacity(int minCapacity) { - if (minCapacity > entries.length) { - entries = ObjectArrays.arraysCopyOf(entries, - ImmutableCollection.Builder.expandedCapacity(entries.length, minCapacity)); - } - } - - /** - * Associates {@code key} with {@code value} in the built map. Duplicate keys - * are not allowed, and will cause {@link #build} to fail. - */ - public Builder put(K key, V value) { - ensureCapacity(size + 1); - TerminalEntry entry = entryOf(key, value); - // don't inline this: we want to fail atomically if key or value is null - entries[size++] = entry; - return this; - } - - /** - * Adds the given {@code entry} to the map, making it immutable if necessary. - * Duplicate keys are not allowed, and will cause {@link #build} to fail. - * - * @since 11.0 - */ - public Builder put(Entry entry) { - return put(entry.getKey(), entry.getValue()); - } - - /** - * Associates all of the given map's keys and values in the built map. Duplicate - * keys are not allowed, and will cause {@link #build} to fail. - * - * @throws NullPointerException if any key or value in {@code map} is null - */ - public Builder putAll(Map map) { - ensureCapacity(size + map.size()); - for (Entry entry : map.entrySet()) { - put(entry); - } - return this; - } - - /* - * TODO(kevinb): Should build() and the ImmutableBiMap & ImmutableSortedMap - * versions throw an IllegalStateException instead? - */ - - /** - * Returns a newly-created immutable map. - * - * @throws IllegalArgumentException if duplicate keys were added - */ - public ImmutableMap build() { - switch (size) { - case 0: - return of(); - case 1: - return of(entries[0].getKey(), entries[0].getValue()); - default: - return new RegularImmutableMap(size, entries); - } - } - } - - /** - * Returns an immutable map containing the same entries as {@code map}. If - * {@code map} somehow contains entries with duplicate keys (for example, if it - * is a {@code SortedMap} whose comparator is not consistent with - * equals), the results of this method are undefined. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if any key or value in {@code map} is null - */ - public static ImmutableMap copyOf(Map map) { - if ((map instanceof ImmutableMap) && !(map instanceof ImmutableSortedMap)) { - // TODO(user): Make ImmutableMap.copyOf(immutableBiMap) call copyOf() - // on the ImmutableMap delegate(), rather than the bimap itself - - @SuppressWarnings("unchecked") // safe since map is not writable - ImmutableMap kvMap = (ImmutableMap) map; - if (!kvMap.isPartialView()) { - return kvMap; - } - } else if (map instanceof EnumMap) { - return copyOfEnumMapUnsafe(map); - } - Entry[] entries = map.entrySet().toArray(EMPTY_ENTRY_ARRAY); - switch (entries.length) { - case 0: - return of(); - case 1: - @SuppressWarnings("unchecked") // all entries will be Entry's - Entry onlyEntry = (Entry) entries[0]; - return of(onlyEntry.getKey(), onlyEntry.getValue()); - default: - return new RegularImmutableMap(entries); - } - } - - // If the map is an EnumMap, it must have key type K for some >. - @SuppressWarnings({ "unchecked", "rawtypes" }) - private static ImmutableMap copyOfEnumMapUnsafe(Map map) { - return copyOfEnumMap((EnumMap) map); - } - - private static , V> ImmutableMap copyOfEnumMap(Map original) { - EnumMap copy = new EnumMap(original); - for (Map.Entry entry : copy.entrySet()) { - checkEntryNotNull(entry.getKey(), entry.getValue()); - } - return ImmutableEnumMap.asImmutable(copy); - } - - private static final Entry[] EMPTY_ENTRY_ARRAY = new Entry[0]; + // cached so that this.multimapView().inverse() only computes inverse once + private transient ImmutableSetMultimap multimapView; ImmutableMap() { } + /** + * Returns a multimap view of the map. + * + * @since 14.0 + */ + @Beta + public ImmutableSetMultimap asMultimap() { + ImmutableSetMultimap result = multimapView; + return (result == null) ? (multimapView = createMultimapView()) : result; + } + + /** + * Guaranteed to throw an exception and leave the map unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final void clear() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return get(key) != null; + } + + @Override + public boolean containsValue(@Nullable Object value) { + return values().contains(value); + } + + abstract ImmutableSet> createEntrySet(); + + ImmutableSet createKeySet() { + return new ImmutableMapKeySet(this); + } + + private ImmutableSetMultimap createMultimapView() { + ImmutableMap> map = viewMapValuesAsSingletonSets(); + return new ImmutableSetMultimap(map, map.size(), null); + } + + /** + * Returns an immutable set of the mappings in this map. The entries are in the + * same order as the parameters used to build this map. + */ + @Override + public ImmutableSet> entrySet() { + ImmutableSet> result = entrySet; + return (result == null) ? entrySet = createEntrySet() : result; + } + + @Override + public boolean equals(@Nullable Object object) { + return Maps.equalsImpl(this, object); + } + + // Overriding to mark it Nullable + @Override + public abstract V get(@Nullable Object key); + + @Override + public int hashCode() { + // not caching hash code since it could change if map values are mutable + // in a way that modifies their hash codes + return entrySet().hashCode(); + } + + @Override + public boolean isEmpty() { + return size() == 0; + } + + abstract boolean isPartialView(); + + /** + * Returns an immutable set of the keys in this map. These keys are in the same + * order as the parameters used to build this map. + */ + @Override + public ImmutableSet keySet() { + ImmutableSet result = keySet; + return (result == null) ? keySet = createKeySet() : result; + } + /** * Guaranteed to throw an exception and leave the map unmodified. * @@ -328,18 +525,6 @@ public abstract class ImmutableMap implements Map, Serializable { throw new UnsupportedOperationException(); } - /** - * Guaranteed to throw an exception and leave the map unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final V remove(Object o) { - throw new UnsupportedOperationException(); - } - /** * Guaranteed to throw an exception and leave the map unmodified. * @@ -360,61 +545,15 @@ public abstract class ImmutableMap implements Map, Serializable { */ @Deprecated @Override - public final void clear() { + public final V remove(Object o) { throw new UnsupportedOperationException(); } @Override - public boolean isEmpty() { - return size() == 0; + public String toString() { + return Maps.toStringImpl(this); } - @Override - public boolean containsKey(@Nullable Object key) { - return get(key) != null; - } - - @Override - public boolean containsValue(@Nullable Object value) { - return values().contains(value); - } - - // Overriding to mark it Nullable - @Override - public abstract V get(@Nullable Object key); - - private transient ImmutableSet> entrySet; - - /** - * Returns an immutable set of the mappings in this map. The entries are in the - * same order as the parameters used to build this map. - */ - @Override - public ImmutableSet> entrySet() { - ImmutableSet> result = entrySet; - return (result == null) ? entrySet = createEntrySet() : result; - } - - abstract ImmutableSet> createEntrySet(); - - private transient ImmutableSet keySet; - - /** - * Returns an immutable set of the keys in this map. These keys are in the same - * order as the parameters used to build this map. - */ - @Override - public ImmutableSet keySet() { - ImmutableSet result = keySet; - return (result == null) ? keySet = createKeySet() : result; - } - - ImmutableSet createKeySet() { - return new ImmutableMapKeySet(this); - } - - private transient ImmutableCollection values; - /** * Returns an immutable collection of the values in this map. The values are in * the same order as the parameters used to build this map. @@ -425,149 +564,10 @@ public abstract class ImmutableMap implements Map, Serializable { return (result == null) ? values = new ImmutableMapValues(this) : result; } - // cached so that this.multimapView().inverse() only computes inverse once - private transient ImmutableSetMultimap multimapView; - - /** - * Returns a multimap view of the map. - * - * @since 14.0 - */ - @Beta - public ImmutableSetMultimap asMultimap() { - ImmutableSetMultimap result = multimapView; - return (result == null) ? (multimapView = createMultimapView()) : result; - } - - private ImmutableSetMultimap createMultimapView() { - ImmutableMap> map = viewMapValuesAsSingletonSets(); - return new ImmutableSetMultimap(map, map.size(), null); - } - private ImmutableMap> viewMapValuesAsSingletonSets() { return new MapViewOfValuesAsSingletonSets(this); } - private static final class MapViewOfValuesAsSingletonSets extends ImmutableMap> { - private final ImmutableMap delegate; - - MapViewOfValuesAsSingletonSets(ImmutableMap delegate) { - this.delegate = checkNotNull(delegate); - } - - @Override - public int size() { - return delegate.size(); - } - - @Override - public boolean containsKey(@Nullable Object key) { - return delegate.containsKey(key); - } - - @Override - public ImmutableSet get(@Nullable Object key) { - V outerValue = delegate.get(key); - return (outerValue == null) ? null : ImmutableSet.of(outerValue); - } - - @Override - boolean isPartialView() { - return false; - } - - @Override - ImmutableSet>> createEntrySet() { - return new ImmutableMapEntrySet>() { - @Override - ImmutableMap> map() { - return MapViewOfValuesAsSingletonSets.this; - } - - @Override - public UnmodifiableIterator>> iterator() { - final Iterator> backingIterator = delegate.entrySet().iterator(); - return new UnmodifiableIterator>>() { - @Override - public boolean hasNext() { - return backingIterator.hasNext(); - } - - @Override - public Entry> next() { - final Entry backingEntry = backingIterator.next(); - return new AbstractMapEntry>() { - @Override - public K getKey() { - return backingEntry.getKey(); - } - - @Override - public ImmutableSet getValue() { - return ImmutableSet.of(backingEntry.getValue()); - } - }; - } - }; - } - }; - } - } - - @Override - public boolean equals(@Nullable Object object) { - return Maps.equalsImpl(this, object); - } - - abstract boolean isPartialView(); - - @Override - public int hashCode() { - // not caching hash code since it could change if map values are mutable - // in a way that modifies their hash codes - return entrySet().hashCode(); - } - - @Override - public String toString() { - return Maps.toStringImpl(this); - } - - /** - * Serialized type for all ImmutableMap instances. It captures the logical - * contents and they are reconstructed using public factory methods. This - * ensures that the implementation types remain as implementation details. - */ - static class SerializedForm implements Serializable { - private final Object[] keys; - private final Object[] values; - - SerializedForm(ImmutableMap map) { - keys = new Object[map.size()]; - values = new Object[map.size()]; - int i = 0; - for (Entry entry : map.entrySet()) { - keys[i] = entry.getKey(); - values[i] = entry.getValue(); - i++; - } - } - - Object readResolve() { - Builder builder = new Builder(); - return createMap(builder); - } - - Object createMap(Builder builder) { - for (int i = 0; i < keys.length; i++) { - builder.put(keys[i], values[i]); - } - return builder.build(); - } - - private static final long serialVersionUID = 0; - } - Object writeReplace() { return new SerializedForm(this); } diff --git a/src/main/java/com/google/common/collect/ImmutableMapEntry.java b/src/main/java/com/google/common/collect/ImmutableMapEntry.java index aad5174c..43538a52 100644 --- a/src/main/java/com/google/common/collect/ImmutableMapEntry.java +++ b/src/main/java/com/google/common/collect/ImmutableMapEntry.java @@ -32,22 +32,6 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtIncompatible("unnecessary") abstract class ImmutableMapEntry extends ImmutableEntry { - ImmutableMapEntry(K key, V value) { - super(key, value); - checkEntryNotNull(key, value); - } - - ImmutableMapEntry(ImmutableMapEntry contents) { - super(contents.getKey(), contents.getValue()); - // null check would be redundant - } - - @Nullable - abstract ImmutableMapEntry getNextInKeyBucket(); - - @Nullable - abstract ImmutableMapEntry getNextInValueBucket(); - static final class TerminalEntry extends ImmutableMapEntry { TerminalEntry(ImmutableMapEntry contents) { super(contents); @@ -69,4 +53,20 @@ abstract class ImmutableMapEntry extends ImmutableEntry { return null; } } + + ImmutableMapEntry(ImmutableMapEntry contents) { + super(contents.getKey(), contents.getValue()); + // null check would be redundant + } + + ImmutableMapEntry(K key, V value) { + super(key, value); + checkEntryNotNull(key, value); + } + + @Nullable + abstract ImmutableMapEntry getNextInKeyBucket(); + + @Nullable + abstract ImmutableMapEntry getNextInValueBucket(); } diff --git a/src/main/java/com/google/common/collect/ImmutableMapEntrySet.java b/src/main/java/com/google/common/collect/ImmutableMapEntrySet.java index 01610ae3..cb227b33 100644 --- a/src/main/java/com/google/common/collect/ImmutableMapEntrySet.java +++ b/src/main/java/com/google/common/collect/ImmutableMapEntrySet.java @@ -32,14 +32,22 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) abstract class ImmutableMapEntrySet extends ImmutableSet> { - ImmutableMapEntrySet() { + @GwtIncompatible("serialization") + private static class EntrySetSerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + final ImmutableMap map; + + EntrySetSerializedForm(ImmutableMap map) { + this.map = map; + } + + Object readResolve() { + return map.entrySet(); + } } - abstract ImmutableMap map(); - - @Override - public int size() { - return map().size(); + ImmutableMapEntrySet() { } @Override @@ -57,24 +65,16 @@ abstract class ImmutableMapEntrySet extends ImmutableSet> { return map().isPartialView(); } + abstract ImmutableMap map(); + + @Override + public int size() { + return map().size(); + } + @GwtIncompatible("serialization") @Override Object writeReplace() { return new EntrySetSerializedForm(map()); } - - @GwtIncompatible("serialization") - private static class EntrySetSerializedForm implements Serializable { - final ImmutableMap map; - - EntrySetSerializedForm(ImmutableMap map) { - this.map = map; - } - - Object readResolve() { - return map.entrySet(); - } - - private static final long serialVersionUID = 0; - } } diff --git a/src/main/java/com/google/common/collect/ImmutableMapKeySet.java b/src/main/java/com/google/common/collect/ImmutableMapKeySet.java index aeecfd53..0ed05297 100644 --- a/src/main/java/com/google/common/collect/ImmutableMapKeySet.java +++ b/src/main/java/com/google/common/collect/ImmutableMapKeySet.java @@ -32,22 +32,27 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) final class ImmutableMapKeySet extends ImmutableSet { + @GwtIncompatible("serialization") + private static class KeySetSerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + final ImmutableMap map; + + KeySetSerializedForm(ImmutableMap map) { + this.map = map; + } + + Object readResolve() { + return map.keySet(); + } + } + private final ImmutableMap map; ImmutableMapKeySet(ImmutableMap map) { this.map = map; } - @Override - public int size() { - return map.size(); - } - - @Override - public UnmodifiableIterator iterator() { - return asList().iterator(); - } - @Override public boolean contains(@Nullable Object object) { return map.containsKey(object); @@ -59,13 +64,13 @@ final class ImmutableMapKeySet extends ImmutableSet { return new ImmutableAsList() { @Override - public K get(int index) { - return entryList.get(index).getKey(); + ImmutableCollection delegateCollection() { + return ImmutableMapKeySet.this; } @Override - ImmutableCollection delegateCollection() { - return ImmutableMapKeySet.this; + public K get(int index) { + return entryList.get(index).getKey(); } }; @@ -76,24 +81,19 @@ final class ImmutableMapKeySet extends ImmutableSet { return true; } + @Override + public UnmodifiableIterator iterator() { + return asList().iterator(); + } + + @Override + public int size() { + return map.size(); + } + @GwtIncompatible("serialization") @Override Object writeReplace() { return new KeySetSerializedForm(map); } - - @GwtIncompatible("serialization") - private static class KeySetSerializedForm implements Serializable { - final ImmutableMap map; - - KeySetSerializedForm(ImmutableMap map) { - this.map = map; - } - - Object readResolve() { - return map.keySet(); - } - - private static final long serialVersionUID = 0; - } } diff --git a/src/main/java/com/google/common/collect/ImmutableMapValues.java b/src/main/java/com/google/common/collect/ImmutableMapValues.java index c33fee2f..bd910685 100644 --- a/src/main/java/com/google/common/collect/ImmutableMapValues.java +++ b/src/main/java/com/google/common/collect/ImmutableMapValues.java @@ -32,56 +32,10 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) final class ImmutableMapValues extends ImmutableCollection { - private final ImmutableMap map; - - ImmutableMapValues(ImmutableMap map) { - this.map = map; - } - - @Override - public int size() { - return map.size(); - } - - @Override - public UnmodifiableIterator iterator() { - return Maps.valueIterator(map.entrySet().iterator()); - } - - @Override - public boolean contains(@Nullable Object object) { - return object != null && Iterators.contains(iterator(), object); - } - - @Override - boolean isPartialView() { - return true; - } - - @Override - ImmutableList createAsList() { - final ImmutableList> entryList = map.entrySet().asList(); - return new ImmutableAsList() { - @Override - public V get(int index) { - return entryList.get(index).getValue(); - } - - @Override - ImmutableCollection delegateCollection() { - return ImmutableMapValues.this; - } - }; - } - - @GwtIncompatible("serialization") - @Override - Object writeReplace() { - return new SerializedForm(map); - } - @GwtIncompatible("serialization") private static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + final ImmutableMap map; SerializedForm(ImmutableMap map) { @@ -91,7 +45,53 @@ final class ImmutableMapValues extends ImmutableCollection { Object readResolve() { return map.values(); } + } - private static final long serialVersionUID = 0; + private final ImmutableMap map; + + ImmutableMapValues(ImmutableMap map) { + this.map = map; + } + + @Override + public boolean contains(@Nullable Object object) { + return object != null && Iterators.contains(iterator(), object); + } + + @Override + ImmutableList createAsList() { + final ImmutableList> entryList = map.entrySet().asList(); + return new ImmutableAsList() { + @Override + ImmutableCollection delegateCollection() { + return ImmutableMapValues.this; + } + + @Override + public V get(int index) { + return entryList.get(index).getValue(); + } + }; + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public UnmodifiableIterator iterator() { + return Maps.valueIterator(map.entrySet().iterator()); + } + + @Override + public int size() { + return map.size(); + } + + @GwtIncompatible("serialization") + @Override + Object writeReplace() { + return new SerializedForm(map); } } diff --git a/src/main/java/com/google/common/collect/ImmutableMultimap.java b/src/main/java/com/google/common/collect/ImmutableMultimap.java index d7c7fe6b..9784f547 100644 --- a/src/main/java/com/google/common/collect/ImmutableMultimap.java +++ b/src/main/java/com/google/common/collect/ImmutableMultimap.java @@ -67,74 +67,6 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(emulated = true) public abstract class ImmutableMultimap extends AbstractMultimap implements Serializable { - /** Returns an empty multimap. */ - public static ImmutableMultimap of() { - return ImmutableListMultimap.of(); - } - - /** - * Returns an immutable multimap containing a single entry. - */ - public static ImmutableMultimap of(K k1, V v1) { - return ImmutableListMultimap.of(k1, v1); - } - - /** - * Returns an immutable multimap containing the given entries, in order. - */ - public static ImmutableMultimap of(K k1, V v1, K k2, V v2) { - return ImmutableListMultimap.of(k1, v1, k2, v2); - } - - /** - * Returns an immutable multimap containing the given entries, in order. - */ - public static ImmutableMultimap of(K k1, V v1, K k2, V v2, K k3, V v3) { - return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3); - } - - /** - * Returns an immutable multimap containing the given entries, in order. - */ - public static ImmutableMultimap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { - return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4); - } - - /** - * Returns an immutable multimap containing the given entries, in order. - */ - public static ImmutableMultimap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { - return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); - } - - // looking for of() with > 5 entries? Use the builder instead. - - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Multimap for {@link ImmutableMultimap.Builder} that maintains key and value - * orderings, allows duplicate values, and performs better than - * {@link LinkedListMultimap}. - */ - private static class BuilderMultimap extends AbstractMapBasedMultimap { - BuilderMultimap() { - super(new LinkedHashMap>()); - } - - @Override - Collection createCollection() { - return Lists.newArrayList(); - } - - private static final long serialVersionUID = 0; - } - /** * A builder for creating immutable multimap instances, especially * {@code public static final} multimaps ("constant multimaps"). Example: @@ -168,11 +100,44 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp } /** - * Adds a key-value mapping to the built multimap. + * Returns a newly-created immutable multimap. */ - public Builder put(K key, V value) { - checkEntryNotNull(key, value); - builderMultimap.put(key, value); + public ImmutableMultimap build() { + if (valueComparator != null) { + for (Collection values : builderMultimap.asMap().values()) { + List list = (List) values; + Collections.sort(list, valueComparator); + } + } + if (keyComparator != null) { + Multimap sortedCopy = new BuilderMultimap(); + List>> entries = Lists.newArrayList(builderMultimap.asMap().entrySet()); + Collections.sort(entries, Ordering.from(keyComparator).onKeys()); + for (Map.Entry> entry : entries) { + sortedCopy.putAll(entry.getKey(), entry.getValue()); + } + builderMultimap = sortedCopy; + } + return copyOf(builderMultimap); + } + + /** + * Specifies the ordering of the generated multimap's keys. + * + * @since 8.0 + */ + public Builder orderKeysBy(Comparator keyComparator) { + this.keyComparator = checkNotNull(keyComparator); + return this; + } + + /** + * Specifies the ordering of the generated multimap's values for each key. + * + * @since 8.0 + */ + public Builder orderValuesBy(Comparator valueComparator) { + this.valueComparator = checkNotNull(valueComparator); return this; } @@ -185,6 +150,15 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp return put(entry.getKey(), entry.getValue()); } + /** + * Adds a key-value mapping to the built multimap. + */ + public Builder put(K key, V value) { + checkEntryNotNull(key, value); + builderMultimap.put(key, value); + return this; + } + /** * Stores a collection of values with the same key in the built multimap. * @@ -229,48 +203,180 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp } return this; } + } - /** - * Specifies the ordering of the generated multimap's keys. - * - * @since 8.0 - */ - public Builder orderKeysBy(Comparator keyComparator) { - this.keyComparator = checkNotNull(keyComparator); - return this; + /** + * Multimap for {@link ImmutableMultimap.Builder} that maintains key and value + * orderings, allows duplicate values, and performs better than + * {@link LinkedListMultimap}. + */ + private static class BuilderMultimap extends AbstractMapBasedMultimap { + private static final long serialVersionUID = 0; + + BuilderMultimap() { + super(new LinkedHashMap>()); } - /** - * Specifies the ordering of the generated multimap's values for each key. - * - * @since 8.0 - */ - public Builder orderValuesBy(Comparator valueComparator) { - this.valueComparator = checkNotNull(valueComparator); - return this; + @Override + Collection createCollection() { + return Lists.newArrayList(); + } + } + + private static class EntryCollection extends ImmutableCollection> { + private static final long serialVersionUID = 0; + + final ImmutableMultimap multimap; + + EntryCollection(ImmutableMultimap multimap) { + this.multimap = multimap; } - /** - * Returns a newly-created immutable multimap. - */ - public ImmutableMultimap build() { - if (valueComparator != null) { - for (Collection values : builderMultimap.asMap().values()) { - List list = (List) values; - Collections.sort(list, valueComparator); - } + @Override + public boolean contains(Object object) { + if (object instanceof Entry) { + Entry entry = (Entry) object; + return multimap.containsEntry(entry.getKey(), entry.getValue()); } - if (keyComparator != null) { - Multimap sortedCopy = new BuilderMultimap(); - List>> entries = Lists.newArrayList(builderMultimap.asMap().entrySet()); - Collections.sort(entries, Ordering.from(keyComparator).onKeys()); - for (Map.Entry> entry : entries) { - sortedCopy.putAll(entry.getKey(), entry.getValue()); - } - builderMultimap = sortedCopy; - } - return copyOf(builderMultimap); + return false; } + + @Override + boolean isPartialView() { + return multimap.isPartialView(); + } + + @Override + public UnmodifiableIterator> iterator() { + return multimap.entryIterator(); + } + + @Override + public int size() { + return multimap.size(); + } + } + + // These constants allow the deserialization code to set final fields. This + // holder class makes sure they are not initialized unless an instance is + // deserialized. + @GwtIncompatible("java serialization is not supported") + static class FieldSettersHolder { + static final Serialization.FieldSetter MAP_FIELD_SETTER = Serialization + .getFieldSetter(ImmutableMultimap.class, "map"); + static final Serialization.FieldSetter SIZE_FIELD_SETTER = Serialization + .getFieldSetter(ImmutableMultimap.class, "size"); + static final Serialization.FieldSetter EMPTY_SET_FIELD_SETTER = Serialization + .getFieldSetter(ImmutableSetMultimap.class, "emptySet"); + } + + private abstract class Itr extends UnmodifiableIterator { + final Iterator>> mapIterator = asMap().entrySet().iterator(); + K key = null; + Iterator valueIterator = Iterators.emptyIterator(); + + @Override + public boolean hasNext() { + return mapIterator.hasNext() || valueIterator.hasNext(); + } + + @Override + public T next() { + if (!valueIterator.hasNext()) { + Entry> mapEntry = mapIterator.next(); + key = mapEntry.getKey(); + valueIterator = mapEntry.getValue().iterator(); + } + return output(key, valueIterator.next()); + } + + abstract T output(K key, V value); + } + + @SuppressWarnings("serial") // Uses writeReplace, not default serialization + class Keys extends ImmutableMultiset { + @Override + public boolean contains(@Nullable Object object) { + return containsKey(object); + } + + @Override + public int count(@Nullable Object element) { + Collection values = map.get(element); + return (values == null) ? 0 : values.size(); + } + + @Override + public Set elementSet() { + return keySet(); + } + + @Override + Multiset.Entry getEntry(int index) { + Map.Entry> entry = map.entrySet().asList().get(index); + return Multisets.immutableEntry(entry.getKey(), entry.getValue().size()); + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public int size() { + return ImmutableMultimap.this.size(); + } + } + + // looking for of() with > 5 entries? Use the builder instead. + + private static final class Values extends ImmutableCollection { + private static final long serialVersionUID = 0; + + private transient final ImmutableMultimap multimap; + + Values(ImmutableMultimap multimap) { + this.multimap = multimap; + } + + @Override + public boolean contains(@Nullable Object object) { + return multimap.containsValue(object); + } + + @GwtIncompatible("not present in emulated superclass") + @Override + int copyIntoArray(Object[] dst, int offset) { + for (ImmutableCollection valueCollection : multimap.map.values()) { + offset = valueCollection.copyIntoArray(dst, offset); + } + return offset; + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public UnmodifiableIterator iterator() { + return multimap.valueIterator(); + } + + @Override + public int size() { + return multimap.size(); + } + } + + private static final long serialVersionUID = 0; + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); } /** @@ -296,51 +402,65 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp return ImmutableListMultimap.copyOf(multimap); } - final transient ImmutableMap> map; - final transient int size; - - // These constants allow the deserialization code to set final fields. This - // holder class makes sure they are not initialized unless an instance is - // deserialized. - @GwtIncompatible("java serialization is not supported") - static class FieldSettersHolder { - static final Serialization.FieldSetter MAP_FIELD_SETTER = Serialization - .getFieldSetter(ImmutableMultimap.class, "map"); - static final Serialization.FieldSetter SIZE_FIELD_SETTER = Serialization - .getFieldSetter(ImmutableMultimap.class, "size"); - static final Serialization.FieldSetter EMPTY_SET_FIELD_SETTER = Serialization - .getFieldSetter(ImmutableSetMultimap.class, "emptySet"); + /** Returns an empty multimap. */ + public static ImmutableMultimap of() { + return ImmutableListMultimap.of(); } + /** + * Returns an immutable multimap containing a single entry. + */ + public static ImmutableMultimap of(K k1, V v1) { + return ImmutableListMultimap.of(k1, v1); + } + + /** + * Returns an immutable multimap containing the given entries, in order. + */ + public static ImmutableMultimap of(K k1, V v1, K k2, V v2) { + return ImmutableListMultimap.of(k1, v1, k2, v2); + } + + /** + * Returns an immutable multimap containing the given entries, in order. + */ + public static ImmutableMultimap of(K k1, V v1, K k2, V v2, K k3, V v3) { + return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3); + } + + // mutators (not supported) + + /** + * Returns an immutable multimap containing the given entries, in order. + */ + public static ImmutableMultimap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { + return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4); + } + + /** + * Returns an immutable multimap containing the given entries, in order. + */ + public static ImmutableMultimap of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { + return ImmutableListMultimap.of(k1, v1, k2, v2, k3, v3, k4, v4, k5, v5); + } + + final transient ImmutableMap> map; + + final transient int size; + ImmutableMultimap(ImmutableMap> map, int size) { this.map = map; this.size = size; } - // mutators (not supported) - /** - * Guaranteed to throw an exception and leave the multimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. + * Returns an immutable map that associates each key with its corresponding + * values in the multimap. */ - @Deprecated @Override - public ImmutableCollection removeAll(Object key) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the multimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public ImmutableCollection replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); + @SuppressWarnings("unchecked") // a widening cast + public ImmutableMap> asMap() { + return (ImmutableMap) map; } /** @@ -355,6 +475,60 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp throw new UnsupportedOperationException(); } + @Override + public boolean containsKey(@Nullable Object key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(@Nullable Object value) { + return value != null && super.containsValue(value); + } + + @Override + Map> createAsMap() { + throw new AssertionError("should never be called"); + } + + // accessors + + @Override + ImmutableCollection> createEntries() { + return new EntryCollection(this); + } + + @Override + ImmutableMultiset createKeys() { + return new Keys(); + } + + @Override + ImmutableCollection createValues() { + return new Values(this); + } + + // views + + /** + * Returns an immutable collection of all key-value pairs in the multimap. Its + * iterator traverses the values for the first key, the values for the second + * key, and so on. + */ + @Override + public ImmutableCollection> entries() { + return (ImmutableCollection>) super.entries(); + } + + @Override + UnmodifiableIterator> entryIterator() { + return new Itr>() { + @Override + Entry output(K key, V value) { + return Maps.immutableEntry(key, value); + } + }; + } + /** * Returns an immutable collection of the values for the given key. If no * mappings in the multimap have the provided key, an empty immutable collection @@ -373,6 +547,37 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp */ public abstract ImmutableMultimap inverse(); + /** + * Returns {@code true} if this immutable multimap's implementation contains + * references to user-created objects that aren't accessible via this multimap's + * methods. This is generally used to determine whether {@code copyOf} + * implementations should make an explicit copy to avoid memory leaks. + */ + boolean isPartialView() { + return map.isPartialView(); + } + + /** + * Returns a collection, which may contain duplicates, of all keys. The number + * of times a key appears in the returned multiset equals the number of mappings + * the key has in the multimap. Duplicate keys appear consecutively in the + * multiset's iteration order. + */ + @Override + public ImmutableMultiset keys() { + return (ImmutableMultiset) super.keys(); + } + + /** + * Returns an immutable set of the distinct keys in this multimap. These keys + * are ordered according to when they first appeared during the construction of + * this multimap. + */ + @Override + public ImmutableSet keySet() { + return map.keySet(); + } + /** * Guaranteed to throw an exception and leave the multimap unmodified. * @@ -422,25 +627,27 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp } /** - * Returns {@code true} if this immutable multimap's implementation contains - * references to user-created objects that aren't accessible via this multimap's - * methods. This is generally used to determine whether {@code copyOf} - * implementations should make an explicit copy to avoid memory leaks. + * Guaranteed to throw an exception and leave the multimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. */ - boolean isPartialView() { - return map.isPartialView(); + @Deprecated + @Override + public ImmutableCollection removeAll(Object key) { + throw new UnsupportedOperationException(); } - // accessors - + /** + * Guaranteed to throw an exception and leave the multimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated @Override - public boolean containsKey(@Nullable Object key) { - return map.containsKey(key); - } - - @Override - public boolean containsValue(@Nullable Object value) { - return value != null && super.containsValue(value); + public ImmutableCollection replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); } @Override @@ -448,181 +655,6 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp return size; } - // views - - /** - * Returns an immutable set of the distinct keys in this multimap. These keys - * are ordered according to when they first appeared during the construction of - * this multimap. - */ - @Override - public ImmutableSet keySet() { - return map.keySet(); - } - - /** - * Returns an immutable map that associates each key with its corresponding - * values in the multimap. - */ - @Override - @SuppressWarnings("unchecked") // a widening cast - public ImmutableMap> asMap() { - return (ImmutableMap) map; - } - - @Override - Map> createAsMap() { - throw new AssertionError("should never be called"); - } - - /** - * Returns an immutable collection of all key-value pairs in the multimap. Its - * iterator traverses the values for the first key, the values for the second - * key, and so on. - */ - @Override - public ImmutableCollection> entries() { - return (ImmutableCollection>) super.entries(); - } - - @Override - ImmutableCollection> createEntries() { - return new EntryCollection(this); - } - - private static class EntryCollection extends ImmutableCollection> { - final ImmutableMultimap multimap; - - EntryCollection(ImmutableMultimap multimap) { - this.multimap = multimap; - } - - @Override - public UnmodifiableIterator> iterator() { - return multimap.entryIterator(); - } - - @Override - boolean isPartialView() { - return multimap.isPartialView(); - } - - @Override - public int size() { - return multimap.size(); - } - - @Override - public boolean contains(Object object) { - if (object instanceof Entry) { - Entry entry = (Entry) object; - return multimap.containsEntry(entry.getKey(), entry.getValue()); - } - return false; - } - - private static final long serialVersionUID = 0; - } - - private abstract class Itr extends UnmodifiableIterator { - final Iterator>> mapIterator = asMap().entrySet().iterator(); - K key = null; - Iterator valueIterator = Iterators.emptyIterator(); - - abstract T output(K key, V value); - - @Override - public boolean hasNext() { - return mapIterator.hasNext() || valueIterator.hasNext(); - } - - @Override - public T next() { - if (!valueIterator.hasNext()) { - Entry> mapEntry = mapIterator.next(); - key = mapEntry.getKey(); - valueIterator = mapEntry.getValue().iterator(); - } - return output(key, valueIterator.next()); - } - } - - @Override - UnmodifiableIterator> entryIterator() { - return new Itr>() { - @Override - Entry output(K key, V value) { - return Maps.immutableEntry(key, value); - } - }; - } - - /** - * Returns a collection, which may contain duplicates, of all keys. The number - * of times a key appears in the returned multiset equals the number of mappings - * the key has in the multimap. Duplicate keys appear consecutively in the - * multiset's iteration order. - */ - @Override - public ImmutableMultiset keys() { - return (ImmutableMultiset) super.keys(); - } - - @Override - ImmutableMultiset createKeys() { - return new Keys(); - } - - @SuppressWarnings("serial") // Uses writeReplace, not default serialization - class Keys extends ImmutableMultiset { - @Override - public boolean contains(@Nullable Object object) { - return containsKey(object); - } - - @Override - public int count(@Nullable Object element) { - Collection values = map.get(element); - return (values == null) ? 0 : values.size(); - } - - @Override - public Set elementSet() { - return keySet(); - } - - @Override - public int size() { - return ImmutableMultimap.this.size(); - } - - @Override - Multiset.Entry getEntry(int index) { - Map.Entry> entry = map.entrySet().asList().get(index); - return Multisets.immutableEntry(entry.getKey(), entry.getValue().size()); - } - - @Override - boolean isPartialView() { - return true; - } - } - - /** - * Returns an immutable collection of the values in this multimap. Its iterator - * traverses the values for the first key, the values for the second key, and so - * on. - */ - @Override - public ImmutableCollection values() { - return (ImmutableCollection) super.values(); - } - - @Override - ImmutableCollection createValues() { - return new Values(this); - } - @Override UnmodifiableIterator valueIterator() { return new Itr() { @@ -633,44 +665,13 @@ public abstract class ImmutableMultimap extends AbstractMultimap imp }; } - private static final class Values extends ImmutableCollection { - private transient final ImmutableMultimap multimap; - - Values(ImmutableMultimap multimap) { - this.multimap = multimap; - } - - @Override - public boolean contains(@Nullable Object object) { - return multimap.containsValue(object); - } - - @Override - public UnmodifiableIterator iterator() { - return multimap.valueIterator(); - } - - @GwtIncompatible("not present in emulated superclass") - @Override - int copyIntoArray(Object[] dst, int offset) { - for (ImmutableCollection valueCollection : multimap.map.values()) { - offset = valueCollection.copyIntoArray(dst, offset); - } - return offset; - } - - @Override - public int size() { - return multimap.size(); - } - - @Override - boolean isPartialView() { - return true; - } - - private static final long serialVersionUID = 0; + /** + * Returns an immutable collection of the values in this multimap. Its iterator + * traverses the values for the first key, the values for the second key, and so + * on. + */ + @Override + public ImmutableCollection values() { + return (ImmutableCollection) super.values(); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ImmutableMultiset.java b/src/main/java/com/google/common/collect/ImmutableMultiset.java index 7f083363..b3d603f9 100644 --- a/src/main/java/com/google/common/collect/ImmutableMultiset.java +++ b/src/main/java/com/google/common/collect/ImmutableMultiset.java @@ -52,9 +52,350 @@ import com.google.common.primitives.Ints; // TODO(user): write an efficient asList() implementation public abstract class ImmutableMultiset extends ImmutableCollection implements Multiset { + /** + * A builder for creating immutable multiset instances, especially {@code + * public static final} multisets ("constant multisets"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	public static final ImmutableMultiset BEANS = new ImmutableMultiset.Builder()
+	 * 			.addCopies(Bean.COCOA, 4).addCopies(Bean.GARDEN, 6).addCopies(Bean.RED, 8)
+	 * 			.addCopies(Bean.BLACK_EYED, 10).build();
+	 * }
+	 * 
+ * + *

+ * Builder instances can be reused; it is safe to call {@link #build} multiple + * times to build multiple multisets in series. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static class Builder extends ImmutableCollection.Builder { + final Multiset contents; + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableMultiset#builder}. + */ + public Builder() { + this(LinkedHashMultiset.create()); + } + + Builder(Multiset contents) { + this.contents = contents; + } + + /** + * Adds {@code element} to the {@code ImmutableMultiset}. + * + * @param element the element to add + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + */ + @Override + public Builder add(E element) { + contents.add(checkNotNull(element)); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableMultiset}. + * + * @param elements the elements to add + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder add(E... elements) { + super.add(elements); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableMultiset}. + * + * @param elements the {@code Iterable} to add to the {@code + * ImmutableMultiset} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder addAll(Iterable elements) { + if (elements instanceof Multiset) { + Multiset multiset = Multisets.cast(elements); + for (Entry entry : multiset.entrySet()) { + addCopies(entry.getElement(), entry.getCount()); + } + } else { + super.addAll(elements); + } + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableMultiset}. + * + * @param elements the elements to add to the {@code ImmutableMultiset} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder addAll(Iterator elements) { + super.addAll(elements); + return this; + } + + /** + * Adds a number of occurrences of an element to this {@code + * ImmutableMultiset}. + * + * @param element the element to add + * @param occurrences the number of occurrences of the element to add. May be + * zero, in which case no change will be made. + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + * @throws IllegalArgumentException if {@code occurrences} is negative, or if + * this operation would result in more than + * {@link Integer#MAX_VALUE} occurrences of the + * element + */ + public Builder addCopies(E element, int occurrences) { + contents.add(checkNotNull(element), occurrences); + return this; + } + + /** + * Returns a newly-created {@code ImmutableMultiset} based on the contents of + * the {@code Builder}. + */ + @Override + public ImmutableMultiset build() { + return copyOf(contents); + } + + /** + * Adds or removes the necessary occurrences of an element such that the element + * attains the desired count. + * + * @param element the element to add or remove occurrences of + * @param count the desired count of the element in this multiset + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + * @throws IllegalArgumentException if {@code count} is negative + */ + public Builder setCount(E element, int count) { + contents.setCount(checkNotNull(element), count); + return this; + } + } + + private final class EntrySet extends ImmutableSet> { + private static final long serialVersionUID = 0; + + @Override + public boolean contains(Object o) { + if (o instanceof Entry) { + Entry entry = (Entry) o; + if (entry.getCount() <= 0) { + return false; + } + int count = count(entry.getElement()); + return count == entry.getCount(); + } + return false; + } + + @Override + ImmutableList> createAsList() { + return new ImmutableAsList>() { + @Override + ImmutableCollection> delegateCollection() { + return EntrySet.this; + } + + @Override + public Entry get(int index) { + return getEntry(index); + } + }; + } + + @Override + public int hashCode() { + return ImmutableMultiset.this.hashCode(); + } + + @Override + boolean isPartialView() { + return ImmutableMultiset.this.isPartialView(); + } + + @Override + public UnmodifiableIterator> iterator() { + return asList().iterator(); + } + + @Override + public int size() { + return elementSet().size(); + } + + // We can't label this with @Override, because it doesn't override anything + // in the GWT emulated version. + // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead + Object writeReplace() { + return new EntrySetSerializedForm(ImmutableMultiset.this); + } + } + + static class EntrySetSerializedForm implements Serializable { + final ImmutableMultiset multiset; + + EntrySetSerializedForm(ImmutableMultiset multiset) { + this.multiset = multiset; + } + + Object readResolve() { + return multiset.entrySet(); + } + } + + private static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + final Object[] elements; + + final int[] counts; + + SerializedForm(Multiset multiset) { + int distinct = multiset.entrySet().size(); + elements = new Object[distinct]; + counts = new int[distinct]; + int i = 0; + for (Entry entry : multiset.entrySet()) { + elements[i] = entry.getElement(); + counts[i] = entry.getCount(); + i++; + } + } + + Object readResolve() { + LinkedHashMultiset multiset = LinkedHashMultiset.create(elements.length); + for (int i = 0; i < elements.length; i++) { + multiset.add(elements[i], counts[i]); + } + return ImmutableMultiset.copyOf(multiset); + } + } + private static final ImmutableMultiset EMPTY = new RegularImmutableMultiset( ImmutableMap.of(), 0); + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + static ImmutableMultiset copyFromEntries(Collection> entries) { + long size = 0; + ImmutableMap.Builder builder = ImmutableMap.builder(); + for (Entry entry : entries) { + int count = entry.getCount(); + if (count > 0) { + // Since ImmutableMap.Builder throws an NPE if an element is null, no + // other null checks are needed. + builder.put(entry.getElement(), count); + size += count; + } + } + + if (size == 0) { + return of(); + } + return new RegularImmutableMultiset(builder.build(), Ints.saturatedCast(size)); + } + + /** + * Returns an immutable multiset containing the given elements. + * + *

+ * The multiset is ordered by the first occurrence of each element. For example, + * {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset with + * elements in the order {@code 2, 3, 3, 1}. + * + * @throws NullPointerException if any of {@code elements} is null + * @since 6.0 + */ + public static ImmutableMultiset copyOf(E[] elements) { + return copyOf(Arrays.asList(elements)); + } + + /** + * Returns an immutable multiset containing the given elements. + * + *

+ * The multiset is ordered by the first occurrence of each element. For example, + * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields a multiset + * with elements in the order {@code 2, 3, 3, 1}. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * Note: Despite what the method name suggests, if {@code elements} is an + * {@code ImmutableMultiset}, no copy will actually be performed, and the given + * multiset itself will be returned. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableMultiset copyOf(Iterable elements) { + if (elements instanceof ImmutableMultiset) { + @SuppressWarnings("unchecked") // all supported methods are covariant + ImmutableMultiset result = (ImmutableMultiset) elements; + if (!result.isPartialView()) { + return result; + } + } + + Multiset multiset = (elements instanceof Multiset) ? Multisets.cast(elements) + : LinkedHashMultiset.create(elements); + + return copyOfInternal(multiset); + } + + /** + * Returns an immutable multiset containing the given elements. + * + *

+ * The multiset is ordered by the first occurrence of each element. For example, + * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())} yields + * a multiset with elements in the order {@code 2, 3, 3, 1}. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableMultiset copyOf(Iterator elements) { + Multiset multiset = LinkedHashMultiset.create(); + Iterators.addAll(multiset, elements); + return copyOfInternal(multiset); + } + + private static ImmutableMultiset copyOfInternal(E... elements) { + return copyOf(Arrays.asList(elements)); + } + + private static ImmutableMultiset copyOfInternal(Multiset multiset) { + return copyFromEntries(multiset.entrySet()); + } + /** * Returns the empty immutable multiset. */ @@ -129,102 +470,65 @@ public abstract class ImmutableMultiset extends ImmutableCollection implem return new Builder().add(e1).add(e2).add(e3).add(e4).add(e5).add(e6).add(others).build(); } - /** - * Returns an immutable multiset containing the given elements. - * - *

- * The multiset is ordered by the first occurrence of each element. For example, - * {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset with - * elements in the order {@code 2, 3, 3, 1}. - * - * @throws NullPointerException if any of {@code elements} is null - * @since 6.0 - */ - public static ImmutableMultiset copyOf(E[] elements) { - return copyOf(Arrays.asList(elements)); - } - - /** - * Returns an immutable multiset containing the given elements. - * - *

- * The multiset is ordered by the first occurrence of each element. For example, - * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields a multiset - * with elements in the order {@code 2, 3, 3, 1}. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * Note: Despite what the method name suggests, if {@code elements} is an - * {@code ImmutableMultiset}, no copy will actually be performed, and the given - * multiset itself will be returned. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableMultiset copyOf(Iterable elements) { - if (elements instanceof ImmutableMultiset) { - @SuppressWarnings("unchecked") // all supported methods are covariant - ImmutableMultiset result = (ImmutableMultiset) elements; - if (!result.isPartialView()) { - return result; - } - } - - Multiset multiset = (elements instanceof Multiset) ? Multisets.cast(elements) - : LinkedHashMultiset.create(elements); - - return copyOfInternal(multiset); - } - - private static ImmutableMultiset copyOfInternal(E... elements) { - return copyOf(Arrays.asList(elements)); - } - - private static ImmutableMultiset copyOfInternal(Multiset multiset) { - return copyFromEntries(multiset.entrySet()); - } - - static ImmutableMultiset copyFromEntries(Collection> entries) { - long size = 0; - ImmutableMap.Builder builder = ImmutableMap.builder(); - for (Entry entry : entries) { - int count = entry.getCount(); - if (count > 0) { - // Since ImmutableMap.Builder throws an NPE if an element is null, no - // other null checks are needed. - builder.put(entry.getElement(), count); - size += count; - } - } - - if (size == 0) { - return of(); - } - return new RegularImmutableMultiset(builder.build(), Ints.saturatedCast(size)); - } - - /** - * Returns an immutable multiset containing the given elements. - * - *

- * The multiset is ordered by the first occurrence of each element. For example, - * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())} yields - * a multiset with elements in the order {@code 2, 3, 3, 1}. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableMultiset copyOf(Iterator elements) { - Multiset multiset = LinkedHashMultiset.create(); - Iterators.addAll(multiset, elements); - return copyOfInternal(multiset); - } + private transient ImmutableSet> entrySet; ImmutableMultiset() { } + /** + * Guaranteed to throw an exception and leave the collection unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final int add(E element, int occurrences) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean contains(@Nullable Object object) { + return count(object) > 0; + } + + @Override + public boolean containsAll(Collection targets) { + return elementSet().containsAll(targets); + } + + @GwtIncompatible("not present in emulated superclass") + @Override + int copyIntoArray(Object[] dst, int offset) { + for (Multiset.Entry entry : entrySet()) { + Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement()); + offset += entry.getCount(); + } + return offset; + } + + private final ImmutableSet> createEntrySet() { + return isEmpty() ? ImmutableSet.>of() : new EntrySet(); + } + + @Override + public ImmutableSet> entrySet() { + ImmutableSet> es = entrySet; + return (es == null) ? (entrySet = createEntrySet()) : es; + } + + @Override + public boolean equals(@Nullable Object object) { + return Multisets.equalsImpl(this, object); + } + + abstract Entry getEntry(int index); + + @Override + public int hashCode() { + return Sets.hashCodeImpl(entrySet()); + } + @Override public UnmodifiableIterator iterator() { final Iterator> entryIterator = entrySet().iterator(); @@ -250,28 +554,6 @@ public abstract class ImmutableMultiset extends ImmutableCollection implem }; } - @Override - public boolean contains(@Nullable Object object) { - return count(object) > 0; - } - - @Override - public boolean containsAll(Collection targets) { - return elementSet().containsAll(targets); - } - - /** - * Guaranteed to throw an exception and leave the collection unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final int add(E element, int occurrences) { - throw new UnsupportedOperationException(); - } - /** * Guaranteed to throw an exception and leave the collection unmodified. * @@ -308,296 +590,14 @@ public abstract class ImmutableMultiset extends ImmutableCollection implem throw new UnsupportedOperationException(); } - @GwtIncompatible("not present in emulated superclass") - @Override - int copyIntoArray(Object[] dst, int offset) { - for (Multiset.Entry entry : entrySet()) { - Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement()); - offset += entry.getCount(); - } - return offset; - } - - @Override - public boolean equals(@Nullable Object object) { - return Multisets.equalsImpl(this, object); - } - - @Override - public int hashCode() { - return Sets.hashCodeImpl(entrySet()); - } - @Override public String toString() { return entrySet().toString(); } - private transient ImmutableSet> entrySet; - - @Override - public ImmutableSet> entrySet() { - ImmutableSet> es = entrySet; - return (es == null) ? (entrySet = createEntrySet()) : es; - } - - private final ImmutableSet> createEntrySet() { - return isEmpty() ? ImmutableSet.>of() : new EntrySet(); - } - - abstract Entry getEntry(int index); - - private final class EntrySet extends ImmutableSet> { - @Override - boolean isPartialView() { - return ImmutableMultiset.this.isPartialView(); - } - - @Override - public UnmodifiableIterator> iterator() { - return asList().iterator(); - } - - @Override - ImmutableList> createAsList() { - return new ImmutableAsList>() { - @Override - public Entry get(int index) { - return getEntry(index); - } - - @Override - ImmutableCollection> delegateCollection() { - return EntrySet.this; - } - }; - } - - @Override - public int size() { - return elementSet().size(); - } - - @Override - public boolean contains(Object o) { - if (o instanceof Entry) { - Entry entry = (Entry) o; - if (entry.getCount() <= 0) { - return false; - } - int count = count(entry.getElement()); - return count == entry.getCount(); - } - return false; - } - - @Override - public int hashCode() { - return ImmutableMultiset.this.hashCode(); - } - - // We can't label this with @Override, because it doesn't override anything - // in the GWT emulated version. - // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead - Object writeReplace() { - return new EntrySetSerializedForm(ImmutableMultiset.this); - } - - private static final long serialVersionUID = 0; - } - - static class EntrySetSerializedForm implements Serializable { - final ImmutableMultiset multiset; - - EntrySetSerializedForm(ImmutableMultiset multiset) { - this.multiset = multiset; - } - - Object readResolve() { - return multiset.entrySet(); - } - } - - private static class SerializedForm implements Serializable { - final Object[] elements; - final int[] counts; - - SerializedForm(Multiset multiset) { - int distinct = multiset.entrySet().size(); - elements = new Object[distinct]; - counts = new int[distinct]; - int i = 0; - for (Entry entry : multiset.entrySet()) { - elements[i] = entry.getElement(); - counts[i] = entry.getCount(); - i++; - } - } - - Object readResolve() { - LinkedHashMultiset multiset = LinkedHashMultiset.create(elements.length); - for (int i = 0; i < elements.length; i++) { - multiset.add(elements[i], counts[i]); - } - return ImmutableMultiset.copyOf(multiset); - } - - private static final long serialVersionUID = 0; - } - // We can't label this with @Override, because it doesn't override anything // in the GWT emulated version. Object writeReplace() { return new SerializedForm(this); } - - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * A builder for creating immutable multiset instances, especially {@code - * public static final} multisets ("constant multisets"). Example: - * - *
-	 * {
-	 * 	@code
-	 *
-	 * 	public static final ImmutableMultiset BEANS = new ImmutableMultiset.Builder()
-	 * 			.addCopies(Bean.COCOA, 4).addCopies(Bean.GARDEN, 6).addCopies(Bean.RED, 8)
-	 * 			.addCopies(Bean.BLACK_EYED, 10).build();
-	 * }
-	 * 
- * - *

- * Builder instances can be reused; it is safe to call {@link #build} multiple - * times to build multiple multisets in series. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static class Builder extends ImmutableCollection.Builder { - final Multiset contents; - - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableMultiset#builder}. - */ - public Builder() { - this(LinkedHashMultiset.create()); - } - - Builder(Multiset contents) { - this.contents = contents; - } - - /** - * Adds {@code element} to the {@code ImmutableMultiset}. - * - * @param element the element to add - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - */ - @Override - public Builder add(E element) { - contents.add(checkNotNull(element)); - return this; - } - - /** - * Adds a number of occurrences of an element to this {@code - * ImmutableMultiset}. - * - * @param element the element to add - * @param occurrences the number of occurrences of the element to add. May be - * zero, in which case no change will be made. - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - * @throws IllegalArgumentException if {@code occurrences} is negative, or if - * this operation would result in more than - * {@link Integer#MAX_VALUE} occurrences of the - * element - */ - public Builder addCopies(E element, int occurrences) { - contents.add(checkNotNull(element), occurrences); - return this; - } - - /** - * Adds or removes the necessary occurrences of an element such that the element - * attains the desired count. - * - * @param element the element to add or remove occurrences of - * @param count the desired count of the element in this multiset - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - * @throws IllegalArgumentException if {@code count} is negative - */ - public Builder setCount(E element, int count) { - contents.setCount(checkNotNull(element), count); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableMultiset}. - * - * @param elements the elements to add - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder add(E... elements) { - super.add(elements); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableMultiset}. - * - * @param elements the {@code Iterable} to add to the {@code - * ImmutableMultiset} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder addAll(Iterable elements) { - if (elements instanceof Multiset) { - Multiset multiset = Multisets.cast(elements); - for (Entry entry : multiset.entrySet()) { - addCopies(entry.getElement(), entry.getCount()); - } - } else { - super.addAll(elements); - } - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableMultiset}. - * - * @param elements the elements to add to the {@code ImmutableMultiset} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder addAll(Iterator elements) { - super.addAll(elements); - return this; - } - - /** - * Returns a newly-created {@code ImmutableMultiset} based on the contents of - * the {@code Builder}. - */ - @Override - public ImmutableMultiset build() { - return copyOf(contents); - } - } } diff --git a/src/main/java/com/google/common/collect/ImmutableRangeMap.java b/src/main/java/com/google/common/collect/ImmutableRangeMap.java index d938ca70..620339e3 100644 --- a/src/main/java/com/google/common/collect/ImmutableRangeMap.java +++ b/src/main/java/com/google/common/collect/ImmutableRangeMap.java @@ -44,46 +44,6 @@ import com.google.common.collect.SortedLists.KeyPresentBehavior; @GwtIncompatible("NavigableMap") public class ImmutableRangeMap, V> implements RangeMap { - private static final ImmutableRangeMap, Object> EMPTY = new ImmutableRangeMap, Object>( - ImmutableList.>>of(), ImmutableList.of()); - - /** - * Returns an empty immutable range map. - */ - @SuppressWarnings("unchecked") - public static , V> ImmutableRangeMap of() { - return (ImmutableRangeMap) EMPTY; - } - - /** - * Returns an immutable range map mapping a single range to a single value. - */ - public static , V> ImmutableRangeMap of(Range range, V value) { - return new ImmutableRangeMap(ImmutableList.of(range), ImmutableList.of(value)); - } - - @SuppressWarnings("unchecked") - public static , V> ImmutableRangeMap copyOf(RangeMap rangeMap) { - if (rangeMap instanceof ImmutableRangeMap) { - return (ImmutableRangeMap) rangeMap; - } - Map, ? extends V> map = rangeMap.asMapOfRanges(); - ImmutableList.Builder> rangesBuilder = new ImmutableList.Builder>(map.size()); - ImmutableList.Builder valuesBuilder = new ImmutableList.Builder(map.size()); - for (Entry, ? extends V> entry : map.entrySet()) { - rangesBuilder.add(entry.getKey()); - valuesBuilder.add(entry.getValue()); - } - return new ImmutableRangeMap(rangesBuilder.build(), valuesBuilder.build()); - } - - /** - * Returns a new builder for an immutable range map. - */ - public static , V> Builder builder() { - return new Builder(); - } - /** * A builder for immutable range maps. Overlapping ranges are prohibited. */ @@ -96,6 +56,21 @@ public class ImmutableRangeMap, V> implements RangeMap build() { + Map, V> map = rangeMap.asMapOfRanges(); + ImmutableList.Builder> rangesBuilder = new ImmutableList.Builder>(map.size()); + ImmutableList.Builder valuesBuilder = new ImmutableList.Builder(map.size()); + for (Entry, V> entry : map.entrySet()) { + rangesBuilder.add(entry.getKey()); + valuesBuilder.add(entry.getValue()); + } + return new ImmutableRangeMap(rangesBuilder.build(), valuesBuilder.build()); + } + /** * Associates the specified range with the specified value. * @@ -134,21 +109,46 @@ public class ImmutableRangeMap, V> implements RangeMap build() { - Map, V> map = rangeMap.asMapOfRanges(); - ImmutableList.Builder> rangesBuilder = new ImmutableList.Builder>(map.size()); - ImmutableList.Builder valuesBuilder = new ImmutableList.Builder(map.size()); - for (Entry, V> entry : map.entrySet()) { - rangesBuilder.add(entry.getKey()); - valuesBuilder.add(entry.getValue()); - } - return new ImmutableRangeMap(rangesBuilder.build(), valuesBuilder.build()); + private static final ImmutableRangeMap, Object> EMPTY = new ImmutableRangeMap, Object>( + ImmutableList.>>of(), ImmutableList.of()); + + /** + * Returns a new builder for an immutable range map. + */ + public static , V> Builder builder() { + return new Builder(); + } + + @SuppressWarnings("unchecked") + public static , V> ImmutableRangeMap copyOf(RangeMap rangeMap) { + if (rangeMap instanceof ImmutableRangeMap) { + return (ImmutableRangeMap) rangeMap; } + Map, ? extends V> map = rangeMap.asMapOfRanges(); + ImmutableList.Builder> rangesBuilder = new ImmutableList.Builder>(map.size()); + ImmutableList.Builder valuesBuilder = new ImmutableList.Builder(map.size()); + for (Entry, ? extends V> entry : map.entrySet()) { + rangesBuilder.add(entry.getKey()); + valuesBuilder.add(entry.getValue()); + } + return new ImmutableRangeMap(rangesBuilder.build(), valuesBuilder.build()); + } + + /** + * Returns an empty immutable range map. + */ + @SuppressWarnings("unchecked") + public static , V> ImmutableRangeMap of() { + return (ImmutableRangeMap) EMPTY; + } + + /** + * Returns an immutable range map mapping a single range to a single value. + */ + public static , V> ImmutableRangeMap of(Range range, V value) { + return new ImmutableRangeMap(ImmutableList.of(range), ImmutableList.of(value)); } private final ImmutableList> ranges; @@ -159,6 +159,30 @@ public class ImmutableRangeMap, V> implements RangeMap, V> asMapOfRanges() { + if (ranges.isEmpty()) { + return ImmutableMap.of(); + } + RegularImmutableSortedSet> rangeSet = new RegularImmutableSortedSet>(ranges, + Range.RANGE_LEX_ORDERING); + return new RegularImmutableSortedMap, V>(rangeSet, values); + } + + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean equals(@Nullable Object o) { + if (o instanceof RangeMap) { + RangeMap rangeMap = (RangeMap) o; + return asMapOfRanges().equals(rangeMap.asMapOfRanges()); + } + return false; + } + @Override @Nullable public V get(K key) { @@ -186,13 +210,8 @@ public class ImmutableRangeMap, V> implements RangeMap span() { - if (ranges.isEmpty()) { - throw new NoSuchElementException(); - } - Range firstRange = ranges.get(0); - Range lastRange = ranges.get(ranges.size() - 1); - return Range.create(firstRange.lowerBound, lastRange.upperBound); + public int hashCode() { + return asMapOfRanges().hashCode(); } @Override @@ -205,24 +224,19 @@ public class ImmutableRangeMap, V> implements RangeMap range) { throw new UnsupportedOperationException(); } @Override - public ImmutableMap, V> asMapOfRanges() { + public Range span() { if (ranges.isEmpty()) { - return ImmutableMap.of(); + throw new NoSuchElementException(); } - RegularImmutableSortedSet> rangeSet = new RegularImmutableSortedSet>(ranges, - Range.RANGE_LEX_ORDERING); - return new RegularImmutableSortedMap, V>(rangeSet, values); + Range firstRange = ranges.get(0); + Range lastRange = ranges.get(ranges.size() - 1); + return Range.create(firstRange.lowerBound, lastRange.upperBound); } @Override @@ -242,11 +256,6 @@ public class ImmutableRangeMap, V> implements RangeMap> subRanges = new ImmutableList>() { - @Override - public int size() { - return len; - } - @Override public Range get(int index) { checkElementIndex(index, len); @@ -261,6 +270,11 @@ public class ImmutableRangeMap, V> implements RangeMap outer = this; return new ImmutableRangeMap(subRanges, values.subList(lowerIndex, upperIndex)) { @@ -275,20 +289,6 @@ public class ImmutableRangeMap, V> implements RangeMap rangeMap = (RangeMap) o; - return asMapOfRanges().equals(rangeMap.asMapOfRanges()); - } - return false; - } - @Override public String toString() { return asMapOfRanges().toString(); diff --git a/src/main/java/com/google/common/collect/ImmutableRangeSet.java b/src/main/java/com/google/common/collect/ImmutableRangeSet.java index 54ccadcd..2e5a4719 100644 --- a/src/main/java/com/google/common/collect/ImmutableRangeSet.java +++ b/src/main/java/com/google/common/collect/ImmutableRangeSet.java @@ -42,370 +42,28 @@ import com.google.common.primitives.Ints; @Beta public final class ImmutableRangeSet extends AbstractRangeSet implements Serializable { - private static final ImmutableRangeSet> EMPTY = new ImmutableRangeSet>( - ImmutableList.>>of()); - - private static final ImmutableRangeSet> ALL = new ImmutableRangeSet>( - ImmutableList.of(Range.>all())); - - /** - * Returns an empty immutable range set. - */ - @SuppressWarnings("unchecked") - public static ImmutableRangeSet of() { - return (ImmutableRangeSet) EMPTY; - } - - /** - * Returns an immutable range set containing the single range - * {@link Range#all()}. - */ - @SuppressWarnings("unchecked") - static ImmutableRangeSet all() { - return (ImmutableRangeSet) ALL; - } - - /** - * Returns an immutable range set containing the specified single range. If - * {@link Range#isEmpty() range.isEmpty()}, this is equivalent to - * {@link ImmutableRangeSet#of()}. - */ - public static ImmutableRangeSet of(Range range) { - checkNotNull(range); - if (range.isEmpty()) { - return of(); - } else if (range.equals(Range.all())) { - return all(); - } else { - return new ImmutableRangeSet(ImmutableList.of(range)); - } - } - - /** - * Returns an immutable copy of the specified {@code RangeSet}. - */ - public static ImmutableRangeSet copyOf(RangeSet rangeSet) { - checkNotNull(rangeSet); - if (rangeSet.isEmpty()) { - return of(); - } else if (rangeSet.encloses(Range.all())) { - return all(); - } - - if (rangeSet instanceof ImmutableRangeSet) { - ImmutableRangeSet immutableRangeSet = (ImmutableRangeSet) rangeSet; - if (!immutableRangeSet.isPartialView()) { - return immutableRangeSet; - } - } - return new ImmutableRangeSet(ImmutableList.copyOf(rangeSet.asRanges())); - } - - ImmutableRangeSet(ImmutableList> ranges) { - this.ranges = ranges; - } - - private ImmutableRangeSet(ImmutableList> ranges, ImmutableRangeSet complement) { - this.ranges = ranges; - this.complement = complement; - } - - private transient final ImmutableList> ranges; - - @Override - public boolean encloses(Range otherRange) { - int index = SortedLists.binarySearch(ranges, Range.lowerBoundFn(), otherRange.lowerBound, Ordering.natural(), - ANY_PRESENT, NEXT_LOWER); - return index != -1 && ranges.get(index).encloses(otherRange); - } - - @Override - public Range rangeContaining(C value) { - int index = SortedLists.binarySearch(ranges, Range.lowerBoundFn(), Cut.belowValue(value), Ordering.natural(), - ANY_PRESENT, NEXT_LOWER); - if (index != -1) { - Range range = ranges.get(index); - return range.contains(value) ? range : null; - } - return null; - } - - @Override - public Range span() { - if (ranges.isEmpty()) { - throw new NoSuchElementException(); - } - return Range.create(ranges.get(0).lowerBound, ranges.get(ranges.size() - 1).upperBound); - } - - @Override - public boolean isEmpty() { - return ranges.isEmpty(); - } - - @Override - public void add(Range range) { - throw new UnsupportedOperationException(); - } - - @Override - public void addAll(RangeSet other) { - throw new UnsupportedOperationException(); - } - - @Override - public void remove(Range range) { - throw new UnsupportedOperationException(); - } - - @Override - public void removeAll(RangeSet other) { - throw new UnsupportedOperationException(); - } - - @Override - public ImmutableSet> asRanges() { - if (ranges.isEmpty()) { - return ImmutableSet.of(); - } - return new RegularImmutableSortedSet>(ranges, Range.RANGE_LEX_ORDERING); - } - - private transient ImmutableRangeSet complement; - - private final class ComplementRanges extends ImmutableList> { - // True if the "positive" range set is empty or bounded below. - private final boolean positiveBoundedBelow; - - // True if the "positive" range set is empty or bounded above. - private final boolean positiveBoundedAbove; - - private final int size; - - ComplementRanges() { - this.positiveBoundedBelow = ranges.get(0).hasLowerBound(); - this.positiveBoundedAbove = Iterables.getLast(ranges).hasUpperBound(); - - int size = ranges.size() - 1; - if (positiveBoundedBelow) { - size++; - } - if (positiveBoundedAbove) { - size++; - } - this.size = size; - } - - @Override - public int size() { - return size; - } - - @Override - public Range get(int index) { - checkElementIndex(index, size); - - Cut lowerBound; - if (positiveBoundedBelow) { - lowerBound = (index == 0) ? Cut.belowAll() : ranges.get(index - 1).upperBound; - } else { - lowerBound = ranges.get(index).upperBound; - } - - Cut upperBound; - if (positiveBoundedAbove && index == size - 1) { - upperBound = Cut.aboveAll(); - } else { - upperBound = ranges.get(index + (positiveBoundedBelow ? 0 : 1)).lowerBound; - } - - return Range.create(lowerBound, upperBound); - } - - @Override - boolean isPartialView() { - return true; - } - } - - @Override - public ImmutableRangeSet complement() { - ImmutableRangeSet result = complement; - if (result != null) { - return result; - } else if (ranges.isEmpty()) { - return complement = all(); - } else if (ranges.size() == 1 && ranges.get(0).equals(Range.all())) { - return complement = of(); - } else { - ImmutableList> complementRanges = new ComplementRanges(); - result = complement = new ImmutableRangeSet(complementRanges, this); - } - return result; - } - - /** - * Returns a list containing the nonempty intersections of {@code range} with - * the ranges in this range set. - */ - private ImmutableList> intersectRanges(final Range range) { - if (ranges.isEmpty() || range.isEmpty()) { - return ImmutableList.of(); - } else if (range.encloses(span())) { - return ranges; - } - - final int fromIndex; - if (range.hasLowerBound()) { - fromIndex = SortedLists.binarySearch(ranges, Range.upperBoundFn(), range.lowerBound, - KeyPresentBehavior.FIRST_AFTER, KeyAbsentBehavior.NEXT_HIGHER); - } else { - fromIndex = 0; - } - - int toIndex; - if (range.hasUpperBound()) { - toIndex = SortedLists.binarySearch(ranges, Range.lowerBoundFn(), range.upperBound, - KeyPresentBehavior.FIRST_PRESENT, KeyAbsentBehavior.NEXT_HIGHER); - } else { - toIndex = ranges.size(); - } - final int length = toIndex - fromIndex; - if (length == 0) { - return ImmutableList.of(); - } else { - return new ImmutableList>() { - @Override - public int size() { - return length; - } - - @Override - public Range get(int index) { - checkElementIndex(index, length); - if (index == 0 || index == length - 1) { - return ranges.get(index + fromIndex).intersection(range); - } else { - return ranges.get(index + fromIndex); - } - } - - @Override - boolean isPartialView() { - return true; - } - }; - } - } - - /** - * Returns a view of the intersection of this range set with the given range. - */ - @Override - public ImmutableRangeSet subRangeSet(Range range) { - if (!isEmpty()) { - Range span = span(); - if (range.encloses(span)) { - return this; - } else if (range.isConnected(span)) { - return new ImmutableRangeSet(intersectRanges(range)); - } - } - return of(); - } - - /** - * Returns an {@link ImmutableSortedSet} containing the same values in the given - * domain {@linkplain RangeSet#contains contained} by this range set. - * - *

- * Note: {@code a.asSet(d).equals(b.asSet(d))} does not imply - * {@code a.equals(b)}! For example, {@code a} and {@code b} could be - * {@code [2..4]} and {@code (1..5)}, or the empty ranges {@code [3..3)} and - * {@code [4..4)}. - * - *

- * Warning: Be extremely careful what you do with the {@code asSet} view - * of a large range set (such as - * {@code ImmutableRangeSet.of(Range.greaterThan(0))}). Certain operations on - * such a set can be performed efficiently, but others (such as - * {@link Set#hashCode} or {@link Collections#frequency}) can cause major - * performance problems. - * - *

- * The returned set's {@link Object#toString} method returns a short-hand form - * of the set's contents, such as {@code "[1..100]}"}. - * - * @throws IllegalArgumentException if neither this range nor the domain has a - * lower bound, or if neither has an upper - * bound - */ - public ImmutableSortedSet asSet(DiscreteDomain domain) { - checkNotNull(domain); - if (isEmpty()) { - return ImmutableSortedSet.of(); - } - Range span = span().canonical(domain); - if (!span.hasLowerBound()) { - // according to the spec of canonical, neither this ImmutableRangeSet nor - // the range have a lower bound - throw new IllegalArgumentException("Neither the DiscreteDomain nor this range set are bounded below"); - } else if (!span.hasUpperBound()) { - try { - domain.maxValue(); - } catch (NoSuchElementException e) { - throw new IllegalArgumentException("Neither the DiscreteDomain nor this range set are bounded above"); - } - } - - return new AsSet(domain); - } - private final class AsSet extends ImmutableSortedSet { private final DiscreteDomain domain; + private transient Integer size; + AsSet(DiscreteDomain domain) { super(Ordering.natural()); this.domain = domain; } - private transient Integer size; - @Override - public int size() { - // racy single-check idiom - Integer result = size; - if (result == null) { - long total = 0; - for (Range range : ranges) { - total += ContiguousSet.create(range, domain).size(); - if (total >= Integer.MAX_VALUE) { - break; - } - } - result = size = Ints.saturatedCast(total); + public boolean contains(@Nullable Object o) { + if (o == null) { + return false; + } + try { + @SuppressWarnings("unchecked") // we catch CCE's + C c = (C) o; + return ImmutableRangeSet.this.contains(c); + } catch (ClassCastException e) { + return false; } - return result.intValue(); - } - - @Override - public UnmodifiableIterator iterator() { - return new AbstractIterator() { - final Iterator> rangeItr = ranges.iterator(); - Iterator elemItr = Iterators.emptyIterator(); - - @Override - protected C computeNext() { - while (!elemItr.hasNext()) { - if (rangeItr.hasNext()) { - elemItr = ContiguousSet.create(rangeItr.next(), domain).iterator(); - } else { - return endOfData(); - } - } - return elemItr.next(); - } - }; } @Override @@ -429,43 +87,11 @@ public final class ImmutableRangeSet extends AbstractRange }; } - ImmutableSortedSet subSet(Range range) { - return subRangeSet(range).asSet(domain); - } - @Override ImmutableSortedSet headSetImpl(C toElement, boolean inclusive) { return subSet(Range.upTo(toElement, BoundType.forBoolean(inclusive))); } - @Override - ImmutableSortedSet subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { - if (!fromInclusive && !toInclusive && Range.compareOrThrow(fromElement, toElement) == 0) { - return ImmutableSortedSet.of(); - } - return subSet(Range.range(fromElement, BoundType.forBoolean(fromInclusive), toElement, - BoundType.forBoolean(toInclusive))); - } - - @Override - ImmutableSortedSet tailSetImpl(C fromElement, boolean inclusive) { - return subSet(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); - } - - @Override - public boolean contains(@Nullable Object o) { - if (o == null) { - return false; - } - try { - @SuppressWarnings("unchecked") // we catch CCE's - C c = (C) o; - return ImmutableRangeSet.this.contains(c); - } catch (ClassCastException e) { - return false; - } - } - @Override int indexOf(Object target) { if (contains(target)) { @@ -489,6 +115,61 @@ public final class ImmutableRangeSet extends AbstractRange return ranges.isPartialView(); } + @Override + public UnmodifiableIterator iterator() { + return new AbstractIterator() { + final Iterator> rangeItr = ranges.iterator(); + Iterator elemItr = Iterators.emptyIterator(); + + @Override + protected C computeNext() { + while (!elemItr.hasNext()) { + if (rangeItr.hasNext()) { + elemItr = ContiguousSet.create(rangeItr.next(), domain).iterator(); + } else { + return endOfData(); + } + } + return elemItr.next(); + } + }; + } + + @Override + public int size() { + // racy single-check idiom + Integer result = size; + if (result == null) { + long total = 0; + for (Range range : ranges) { + total += ContiguousSet.create(range, domain).size(); + if (total >= Integer.MAX_VALUE) { + break; + } + } + result = size = Ints.saturatedCast(total); + } + return result.intValue(); + } + + ImmutableSortedSet subSet(Range range) { + return subRangeSet(range).asSet(domain); + } + + @Override + ImmutableSortedSet subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { + if (!fromInclusive && !toInclusive && Range.compareOrThrow(fromElement, toElement) == 0) { + return ImmutableSortedSet.of(); + } + return subSet(Range.range(fromElement, BoundType.forBoolean(fromInclusive), toElement, + BoundType.forBoolean(toInclusive))); + } + + @Override + ImmutableSortedSet tailSetImpl(C fromElement, boolean inclusive) { + return subSet(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); + } + @Override public String toString() { return ranges.toString(); @@ -514,23 +195,6 @@ public final class ImmutableRangeSet extends AbstractRange } } - /** - * Returns {@code true} if this immutable range set's implementation contains - * references to user-created objects that aren't accessible via this range - * set's methods. This is generally used to determine whether {@code copyOf} - * implementations should make an explicit copy to avoid memory leaks. - */ - boolean isPartialView() { - return ranges.isPartialView(); - } - - /** - * Returns a new builder for an immutable range set. - */ - public static > Builder builder() { - return new Builder(); - } - /** * A builder for immutable range sets. */ @@ -584,6 +248,61 @@ public final class ImmutableRangeSet extends AbstractRange } } + private final class ComplementRanges extends ImmutableList> { + // True if the "positive" range set is empty or bounded below. + private final boolean positiveBoundedBelow; + + // True if the "positive" range set is empty or bounded above. + private final boolean positiveBoundedAbove; + + private final int size; + + ComplementRanges() { + this.positiveBoundedBelow = ranges.get(0).hasLowerBound(); + this.positiveBoundedAbove = Iterables.getLast(ranges).hasUpperBound(); + + int size = ranges.size() - 1; + if (positiveBoundedBelow) { + size++; + } + if (positiveBoundedAbove) { + size++; + } + this.size = size; + } + + @Override + public Range get(int index) { + checkElementIndex(index, size); + + Cut lowerBound; + if (positiveBoundedBelow) { + lowerBound = (index == 0) ? Cut.belowAll() : ranges.get(index - 1).upperBound; + } else { + lowerBound = ranges.get(index).upperBound; + } + + Cut upperBound; + if (positiveBoundedAbove && index == size - 1) { + upperBound = Cut.aboveAll(); + } else { + upperBound = ranges.get(index + (positiveBoundedBelow ? 0 : 1)).lowerBound; + } + + return Range.create(lowerBound, upperBound); + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public int size() { + return size; + } + } + private static final class SerializedForm implements Serializable { private final ImmutableList> ranges; @@ -602,6 +321,287 @@ public final class ImmutableRangeSet extends AbstractRange } } + private static final ImmutableRangeSet> EMPTY = new ImmutableRangeSet>( + ImmutableList.>>of()); + + private static final ImmutableRangeSet> ALL = new ImmutableRangeSet>( + ImmutableList.of(Range.>all())); + + /** + * Returns an immutable range set containing the single range + * {@link Range#all()}. + */ + @SuppressWarnings("unchecked") + static ImmutableRangeSet all() { + return (ImmutableRangeSet) ALL; + } + + /** + * Returns a new builder for an immutable range set. + */ + public static > Builder builder() { + return new Builder(); + } + + /** + * Returns an immutable copy of the specified {@code RangeSet}. + */ + public static ImmutableRangeSet copyOf(RangeSet rangeSet) { + checkNotNull(rangeSet); + if (rangeSet.isEmpty()) { + return of(); + } else if (rangeSet.encloses(Range.all())) { + return all(); + } + + if (rangeSet instanceof ImmutableRangeSet) { + ImmutableRangeSet immutableRangeSet = (ImmutableRangeSet) rangeSet; + if (!immutableRangeSet.isPartialView()) { + return immutableRangeSet; + } + } + return new ImmutableRangeSet(ImmutableList.copyOf(rangeSet.asRanges())); + } + + /** + * Returns an empty immutable range set. + */ + @SuppressWarnings("unchecked") + public static ImmutableRangeSet of() { + return (ImmutableRangeSet) EMPTY; + } + + /** + * Returns an immutable range set containing the specified single range. If + * {@link Range#isEmpty() range.isEmpty()}, this is equivalent to + * {@link ImmutableRangeSet#of()}. + */ + public static ImmutableRangeSet of(Range range) { + checkNotNull(range); + if (range.isEmpty()) { + return of(); + } else if (range.equals(Range.all())) { + return all(); + } else { + return new ImmutableRangeSet(ImmutableList.of(range)); + } + } + + private transient final ImmutableList> ranges; + + private transient ImmutableRangeSet complement; + + ImmutableRangeSet(ImmutableList> ranges) { + this.ranges = ranges; + } + + private ImmutableRangeSet(ImmutableList> ranges, ImmutableRangeSet complement) { + this.ranges = ranges; + this.complement = complement; + } + + @Override + public void add(Range range) { + throw new UnsupportedOperationException(); + } + + @Override + public void addAll(RangeSet other) { + throw new UnsupportedOperationException(); + } + + @Override + public ImmutableSet> asRanges() { + if (ranges.isEmpty()) { + return ImmutableSet.of(); + } + return new RegularImmutableSortedSet>(ranges, Range.RANGE_LEX_ORDERING); + } + + /** + * Returns an {@link ImmutableSortedSet} containing the same values in the given + * domain {@linkplain RangeSet#contains contained} by this range set. + * + *

+ * Note: {@code a.asSet(d).equals(b.asSet(d))} does not imply + * {@code a.equals(b)}! For example, {@code a} and {@code b} could be + * {@code [2..4]} and {@code (1..5)}, or the empty ranges {@code [3..3)} and + * {@code [4..4)}. + * + *

+ * Warning: Be extremely careful what you do with the {@code asSet} view + * of a large range set (such as + * {@code ImmutableRangeSet.of(Range.greaterThan(0))}). Certain operations on + * such a set can be performed efficiently, but others (such as + * {@link Set#hashCode} or {@link Collections#frequency}) can cause major + * performance problems. + * + *

+ * The returned set's {@link Object#toString} method returns a short-hand form + * of the set's contents, such as {@code "[1..100]}"}. + * + * @throws IllegalArgumentException if neither this range nor the domain has a + * lower bound, or if neither has an upper + * bound + */ + public ImmutableSortedSet asSet(DiscreteDomain domain) { + checkNotNull(domain); + if (isEmpty()) { + return ImmutableSortedSet.of(); + } + Range span = span().canonical(domain); + if (!span.hasLowerBound()) { + // according to the spec of canonical, neither this ImmutableRangeSet nor + // the range have a lower bound + throw new IllegalArgumentException("Neither the DiscreteDomain nor this range set are bounded below"); + } else if (!span.hasUpperBound()) { + try { + domain.maxValue(); + } catch (NoSuchElementException e) { + throw new IllegalArgumentException("Neither the DiscreteDomain nor this range set are bounded above"); + } + } + + return new AsSet(domain); + } + + @Override + public ImmutableRangeSet complement() { + ImmutableRangeSet result = complement; + if (result != null) { + return result; + } else if (ranges.isEmpty()) { + return complement = all(); + } else if (ranges.size() == 1 && ranges.get(0).equals(Range.all())) { + return complement = of(); + } else { + ImmutableList> complementRanges = new ComplementRanges(); + result = complement = new ImmutableRangeSet(complementRanges, this); + } + return result; + } + + @Override + public boolean encloses(Range otherRange) { + int index = SortedLists.binarySearch(ranges, Range.lowerBoundFn(), otherRange.lowerBound, Ordering.natural(), + ANY_PRESENT, NEXT_LOWER); + return index != -1 && ranges.get(index).encloses(otherRange); + } + + /** + * Returns a list containing the nonempty intersections of {@code range} with + * the ranges in this range set. + */ + private ImmutableList> intersectRanges(final Range range) { + if (ranges.isEmpty() || range.isEmpty()) { + return ImmutableList.of(); + } else if (range.encloses(span())) { + return ranges; + } + + final int fromIndex; + if (range.hasLowerBound()) { + fromIndex = SortedLists.binarySearch(ranges, Range.upperBoundFn(), range.lowerBound, + KeyPresentBehavior.FIRST_AFTER, KeyAbsentBehavior.NEXT_HIGHER); + } else { + fromIndex = 0; + } + + int toIndex; + if (range.hasUpperBound()) { + toIndex = SortedLists.binarySearch(ranges, Range.lowerBoundFn(), range.upperBound, + KeyPresentBehavior.FIRST_PRESENT, KeyAbsentBehavior.NEXT_HIGHER); + } else { + toIndex = ranges.size(); + } + final int length = toIndex - fromIndex; + if (length == 0) { + return ImmutableList.of(); + } else { + return new ImmutableList>() { + @Override + public Range get(int index) { + checkElementIndex(index, length); + if (index == 0 || index == length - 1) { + return ranges.get(index + fromIndex).intersection(range); + } else { + return ranges.get(index + fromIndex); + } + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public int size() { + return length; + } + }; + } + } + + @Override + public boolean isEmpty() { + return ranges.isEmpty(); + } + + /** + * Returns {@code true} if this immutable range set's implementation contains + * references to user-created objects that aren't accessible via this range + * set's methods. This is generally used to determine whether {@code copyOf} + * implementations should make an explicit copy to avoid memory leaks. + */ + boolean isPartialView() { + return ranges.isPartialView(); + } + + @Override + public Range rangeContaining(C value) { + int index = SortedLists.binarySearch(ranges, Range.lowerBoundFn(), Cut.belowValue(value), Ordering.natural(), + ANY_PRESENT, NEXT_LOWER); + if (index != -1) { + Range range = ranges.get(index); + return range.contains(value) ? range : null; + } + return null; + } + + @Override + public void remove(Range range) { + throw new UnsupportedOperationException(); + } + + @Override + public void removeAll(RangeSet other) { + throw new UnsupportedOperationException(); + } + + @Override + public Range span() { + if (ranges.isEmpty()) { + throw new NoSuchElementException(); + } + return Range.create(ranges.get(0).lowerBound, ranges.get(ranges.size() - 1).upperBound); + } + + /** + * Returns a view of the intersection of this range set with the given range. + */ + @Override + public ImmutableRangeSet subRangeSet(Range range) { + if (!isEmpty()) { + Range span = span(); + if (range.encloses(span)) { + return this; + } else if (range.isConnected(span)) { + return new ImmutableRangeSet(intersectRanges(range)); + } + } + return of(); + } + Object writeReplace() { return new SerializedForm(ranges); } diff --git a/src/main/java/com/google/common/collect/ImmutableSet.java b/src/main/java/com/google/common/collect/ImmutableSet.java index 8763eeb6..2c4cbe04 100644 --- a/src/main/java/com/google/common/collect/ImmutableSet.java +++ b/src/main/java/com/google/common/collect/ImmutableSet.java @@ -77,375 +77,6 @@ import com.google.common.primitives.Ints; @GwtCompatible(serializable = true, emulated = true) @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableSet extends ImmutableCollection implements Set { - /** - * Returns the empty immutable set. This set behaves and performs comparably to - * {@link Collections#emptySet}, and is preferable mainly for consistency and - * maintainability of your code. - */ - // Casting to any type is safe because the set will never hold any elements. - @SuppressWarnings({ "unchecked" }) - public static ImmutableSet of() { - return (ImmutableSet) EmptyImmutableSet.INSTANCE; - } - - /** - * Returns an immutable set containing a single element. This set behaves and - * performs comparably to {@link Collections#singleton}, but will not accept a - * null element. It is preferable mainly for consistency and maintainability of - * your code. - */ - public static ImmutableSet of(E element) { - return new SingletonImmutableSet(element); - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any element is null - */ - public static ImmutableSet of(E e1, E e2) { - return construct(2, e1, e2); - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any element is null - */ - public static ImmutableSet of(E e1, E e2, E e3) { - return construct(3, e1, e2, e3); - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any element is null - */ - public static ImmutableSet of(E e1, E e2, E e3, E e4) { - return construct(4, e1, e2, e3, e4); - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any element is null - */ - public static ImmutableSet of(E e1, E e2, E e3, E e4, E e5) { - return construct(5, e1, e2, e3, e4, e5); - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any element is null - * @since 3.0 (source-compatible since 2.0) - */ - public static ImmutableSet of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { - final int paramCount = 6; - Object[] elements = new Object[paramCount + others.length]; - elements[0] = e1; - elements[1] = e2; - elements[2] = e3; - elements[3] = e4; - elements[4] = e5; - elements[5] = e6; - System.arraycopy(others, 0, elements, paramCount, others.length); - return construct(elements.length, elements); - } - - /** - * Constructs an {@code ImmutableSet} from the first {@code n} elements of the - * specified array. If {@code k} is the size of the returned - * {@code ImmutableSet}, then the unique elements of {@code elements} will be in - * the first {@code k} positions, and {@code elements[i] == null} for - * {@code k <= i < n}. - * - *

- * This may modify {@code elements}. Additionally, if - * {@code n == elements.length} and {@code elements} contains no duplicates, - * {@code elements} may be used without copying in the returned - * {@code ImmutableSet}, in which case it may no longer be modified. - * - *

- * {@code elements} may contain only values of type {@code E}. - * - * @throws NullPointerException if any of the first {@code n} elements of - * {@code elements} is null - */ - private static ImmutableSet construct(int n, Object... elements) { - switch (n) { - case 0: - return of(); - case 1: - @SuppressWarnings("unchecked") // safe; elements contains only E's - E elem = (E) elements[0]; - return of(elem); - default: - // continue below to handle the general case - } - int tableSize = chooseTableSize(n); - Object[] table = new Object[tableSize]; - int mask = tableSize - 1; - int hashCode = 0; - int uniques = 0; - for (int i = 0; i < n; i++) { - Object element = checkElementNotNull(elements[i], i); - int hash = element.hashCode(); - for (int j = Hashing.smear(hash);; j++) { - int index = j & mask; - Object value = table[index]; - if (value == null) { - // Came to an empty slot. Put the element here. - elements[uniques++] = element; - table[index] = element; - hashCode += hash; - break; - } else if (value.equals(element)) { - break; - } - } - } - Arrays.fill(elements, uniques, n, null); - if (uniques == 1) { - // There is only one element or elements are all duplicates - @SuppressWarnings("unchecked") // we are careful to only pass in E - E element = (E) elements[0]; - return new SingletonImmutableSet(element, hashCode); - } else if (tableSize != chooseTableSize(uniques)) { - // Resize the table when the array includes too many duplicates. - // when this happens, we have already made a copy - return construct(uniques, elements); - } else { - Object[] uniqueElements = (uniques < elements.length) ? ObjectArrays.arraysCopyOf(elements, uniques) - : elements; - return new RegularImmutableSet(uniqueElements, hashCode, table, mask); - } - } - - // We use power-of-2 tables, and this is the highest int that's a power of 2 - static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; - - // Represents how tightly we can pack things, as a maximum. - private static final double DESIRED_LOAD_FACTOR = 0.7; - - // If the set has this many elements, it will "max out" the table size - private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR); - - /** - * Returns an array size suitable for the backing array of a hash table that - * uses open addressing with linear probing in its implementation. The returned - * size is the smallest power of two that can hold setSize elements with the - * desired load factor. - * - *

- * Do not call this method with setSize < 2. - */ - @VisibleForTesting - static int chooseTableSize(int setSize) { - // Correct the size for open addressing to match desired load factor. - if (setSize < CUTOFF) { - // Round up to the next highest power of 2. - int tableSize = Integer.highestOneBit(setSize - 1) << 1; - while (tableSize * DESIRED_LOAD_FACTOR < setSize) { - tableSize <<= 1; - } - return tableSize; - } - - // The table can't be completely full or we'll get infinite reprobes - checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); - return MAX_TABLE_SIZE; - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any of {@code elements} is null - * @since 3.0 - */ - public static ImmutableSet copyOf(E[] elements) { - switch (elements.length) { - case 0: - return of(); - case 1: - return of(elements[0]); - default: - return construct(elements.length, elements.clone()); - } - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. This method iterates over {@code elements} at most once. - * - *

- * Note that if {@code s} is a {@code Set}, then {@code - * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet} containing - * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns a - * {@code ImmutableSet>} containing one element (the given set - * itself). - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableSet copyOf(Iterable elements) { - return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. - * - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableSet copyOf(Iterator elements) { - // We special-case for 0 or 1 elements, but anything further is madness. - if (!elements.hasNext()) { - return of(); - } - E first = elements.next(); - if (!elements.hasNext()) { - return of(first); - } else { - return new ImmutableSet.Builder().add(first).addAll(elements).build(); - } - } - - /** - * Returns an immutable set containing the given elements, in order. Repeated - * occurrences of an element (according to {@link Object#equals}) after the - * first are ignored. This method iterates over {@code elements} at most once. - * - *

- * Note that if {@code s} is a {@code Set}, then {@code - * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet} containing - * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns a - * {@code ImmutableSet>} containing one element (the given set - * itself). - * - *

- * Note: Despite what the method name suggests, {@code copyOf} will - * return constant-space views, rather than linear-space copies, of some inputs - * known to be immutable. For some other immutable inputs, such as key sets of - * an {@code ImmutableMap}, it still performs a copy in order to avoid holding - * references to the values of the map. The heuristics used in this decision are - * undocumented and subject to change except that: - *

    - *
  • A full copy will be done of any {@code ImmutableSortedSet}.
  • - *
  • {@code ImmutableSet.copyOf()} is idempotent with respect to pointer - * equality.
  • - *
- * - *

- * This method is safe to use even when {@code elements} is a synchronized or - * concurrent collection that is currently being modified by another thread. - * - * @throws NullPointerException if any of {@code elements} is null - * @since 7.0 (source-compatible since 2.0) - */ - public static ImmutableSet copyOf(Collection elements) { - /* - * TODO(user): consider checking for ImmutableAsList here TODO(user): consider - * checking for Multiset here - */ - if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { - @SuppressWarnings("unchecked") // all supported methods are covariant - ImmutableSet set = (ImmutableSet) elements; - if (!set.isPartialView()) { - return set; - } - } else if (elements instanceof EnumSet) { - return copyOfEnumSet((EnumSet) elements); - } - Object[] array = elements.toArray(); - return construct(array.length, array); - } - - private static > ImmutableSet copyOfEnumSet(EnumSet enumSet) { - return ImmutableEnumSet.asImmutable(EnumSet.copyOf(enumSet)); - } - - ImmutableSet() { - } - - /** Returns {@code true} if the {@code hashCode()} method runs quickly. */ - boolean isHashCodeFast() { - return false; - } - - @Override - public boolean equals(@Nullable Object object) { - if (object == this) { - return true; - } else if (object instanceof ImmutableSet && isHashCodeFast() && ((ImmutableSet) object).isHashCodeFast() - && hashCode() != object.hashCode()) { - return false; - } - return Sets.equalsImpl(this, object); - } - - @Override - public int hashCode() { - return Sets.hashCodeImpl(this); - } - - // This declaration is needed to make Set.iterator() and - // ImmutableCollection.iterator() consistent. - @Override - public abstract UnmodifiableIterator iterator(); - - /* - * This class is used to serialize all ImmutableSet instances, except for - * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It - * captures their "logical contents" and they are reconstructed using public - * static factories. This is necessary to ensure that the existence of a - * particular implementation type is an implementation detail. - */ - private static class SerializedForm implements Serializable { - final Object[] elements; - - SerializedForm(Object[] elements) { - this.elements = elements; - } - - Object readResolve() { - return copyOf(elements); - } - - private static final long serialVersionUID = 0; - } - - @Override - Object writeReplace() { - return new SerializedForm(toArray()); - } - - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. - */ - public static Builder builder() { - return new Builder(); - } - /** * A builder for creating immutable set instances, especially {@code public * static final} sets ("constant sets"). Example: @@ -553,4 +184,373 @@ public abstract class ImmutableSet extends ImmutableCollection implements return result; } } + + /* + * This class is used to serialize all ImmutableSet instances, except for + * ImmutableEnumSet/ImmutableSortedSet, regardless of implementation type. It + * captures their "logical contents" and they are reconstructed using public + * static factories. This is necessary to ensure that the existence of a + * particular implementation type is an implementation detail. + */ + private static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + final Object[] elements; + + SerializedForm(Object[] elements) { + this.elements = elements; + } + + Object readResolve() { + return copyOf(elements); + } + } + + // We use power-of-2 tables, and this is the highest int that's a power of 2 + static final int MAX_TABLE_SIZE = Ints.MAX_POWER_OF_TWO; + + // Represents how tightly we can pack things, as a maximum. + private static final double DESIRED_LOAD_FACTOR = 0.7; + + // If the set has this many elements, it will "max out" the table size + private static final int CUTOFF = (int) (MAX_TABLE_SIZE * DESIRED_LOAD_FACTOR); + + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder} constructor. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns an array size suitable for the backing array of a hash table that + * uses open addressing with linear probing in its implementation. The returned + * size is the smallest power of two that can hold setSize elements with the + * desired load factor. + * + *

+ * Do not call this method with setSize < 2. + */ + @VisibleForTesting + static int chooseTableSize(int setSize) { + // Correct the size for open addressing to match desired load factor. + if (setSize < CUTOFF) { + // Round up to the next highest power of 2. + int tableSize = Integer.highestOneBit(setSize - 1) << 1; + while (tableSize * DESIRED_LOAD_FACTOR < setSize) { + tableSize <<= 1; + } + return tableSize; + } + + // The table can't be completely full or we'll get infinite reprobes + checkArgument(setSize < MAX_TABLE_SIZE, "collection too large"); + return MAX_TABLE_SIZE; + } + + /** + * Constructs an {@code ImmutableSet} from the first {@code n} elements of the + * specified array. If {@code k} is the size of the returned + * {@code ImmutableSet}, then the unique elements of {@code elements} will be in + * the first {@code k} positions, and {@code elements[i] == null} for + * {@code k <= i < n}. + * + *

+ * This may modify {@code elements}. Additionally, if + * {@code n == elements.length} and {@code elements} contains no duplicates, + * {@code elements} may be used without copying in the returned + * {@code ImmutableSet}, in which case it may no longer be modified. + * + *

+ * {@code elements} may contain only values of type {@code E}. + * + * @throws NullPointerException if any of the first {@code n} elements of + * {@code elements} is null + */ + private static ImmutableSet construct(int n, Object... elements) { + switch (n) { + case 0: + return of(); + case 1: + @SuppressWarnings("unchecked") // safe; elements contains only E's + E elem = (E) elements[0]; + return of(elem); + default: + // continue below to handle the general case + } + int tableSize = chooseTableSize(n); + Object[] table = new Object[tableSize]; + int mask = tableSize - 1; + int hashCode = 0; + int uniques = 0; + for (int i = 0; i < n; i++) { + Object element = checkElementNotNull(elements[i], i); + int hash = element.hashCode(); + for (int j = Hashing.smear(hash);; j++) { + int index = j & mask; + Object value = table[index]; + if (value == null) { + // Came to an empty slot. Put the element here. + elements[uniques++] = element; + table[index] = element; + hashCode += hash; + break; + } else if (value.equals(element)) { + break; + } + } + } + Arrays.fill(elements, uniques, n, null); + if (uniques == 1) { + // There is only one element or elements are all duplicates + @SuppressWarnings("unchecked") // we are careful to only pass in E + E element = (E) elements[0]; + return new SingletonImmutableSet(element, hashCode); + } else if (tableSize != chooseTableSize(uniques)) { + // Resize the table when the array includes too many duplicates. + // when this happens, we have already made a copy + return construct(uniques, elements); + } else { + Object[] uniqueElements = (uniques < elements.length) ? ObjectArrays.arraysCopyOf(elements, uniques) + : elements; + return new RegularImmutableSet(uniqueElements, hashCode, table, mask); + } + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. This method iterates over {@code elements} at most once. + * + *

+ * Note that if {@code s} is a {@code Set}, then {@code + * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet} containing + * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns a + * {@code ImmutableSet>} containing one element (the given set + * itself). + * + *

+ * Note: Despite what the method name suggests, {@code copyOf} will + * return constant-space views, rather than linear-space copies, of some inputs + * known to be immutable. For some other immutable inputs, such as key sets of + * an {@code ImmutableMap}, it still performs a copy in order to avoid holding + * references to the values of the map. The heuristics used in this decision are + * undocumented and subject to change except that: + *

    + *
  • A full copy will be done of any {@code ImmutableSortedSet}.
  • + *
  • {@code ImmutableSet.copyOf()} is idempotent with respect to pointer + * equality.
  • + *
+ * + *

+ * This method is safe to use even when {@code elements} is a synchronized or + * concurrent collection that is currently being modified by another thread. + * + * @throws NullPointerException if any of {@code elements} is null + * @since 7.0 (source-compatible since 2.0) + */ + public static ImmutableSet copyOf(Collection elements) { + /* + * TODO(user): consider checking for ImmutableAsList here TODO(user): consider + * checking for Multiset here + */ + if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { + @SuppressWarnings("unchecked") // all supported methods are covariant + ImmutableSet set = (ImmutableSet) elements; + if (!set.isPartialView()) { + return set; + } + } else if (elements instanceof EnumSet) { + return copyOfEnumSet((EnumSet) elements); + } + Object[] array = elements.toArray(); + return construct(array.length, array); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any of {@code elements} is null + * @since 3.0 + */ + public static ImmutableSet copyOf(E[] elements) { + switch (elements.length) { + case 0: + return of(); + case 1: + return of(elements[0]); + default: + return construct(elements.length, elements.clone()); + } + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. This method iterates over {@code elements} at most once. + * + *

+ * Note that if {@code s} is a {@code Set}, then {@code + * ImmutableSet.copyOf(s)} returns an {@code ImmutableSet} containing + * each of the strings in {@code s}, while {@code ImmutableSet.of(s)} returns a + * {@code ImmutableSet>} containing one element (the given set + * itself). + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableSet copyOf(Iterable elements) { + return (elements instanceof Collection) ? copyOf(Collections2.cast(elements)) : copyOf(elements.iterator()); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableSet copyOf(Iterator elements) { + // We special-case for 0 or 1 elements, but anything further is madness. + if (!elements.hasNext()) { + return of(); + } + E first = elements.next(); + if (!elements.hasNext()) { + return of(first); + } else { + return new ImmutableSet.Builder().add(first).addAll(elements).build(); + } + } + + private static > ImmutableSet copyOfEnumSet(EnumSet enumSet) { + return ImmutableEnumSet.asImmutable(EnumSet.copyOf(enumSet)); + } + + /** + * Returns the empty immutable set. This set behaves and performs comparably to + * {@link Collections#emptySet}, and is preferable mainly for consistency and + * maintainability of your code. + */ + // Casting to any type is safe because the set will never hold any elements. + @SuppressWarnings({ "unchecked" }) + public static ImmutableSet of() { + return (ImmutableSet) EmptyImmutableSet.INSTANCE; + } + + /** + * Returns an immutable set containing a single element. This set behaves and + * performs comparably to {@link Collections#singleton}, but will not accept a + * null element. It is preferable mainly for consistency and maintainability of + * your code. + */ + public static ImmutableSet of(E element) { + return new SingletonImmutableSet(element); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any element is null + */ + public static ImmutableSet of(E e1, E e2) { + return construct(2, e1, e2); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any element is null + */ + public static ImmutableSet of(E e1, E e2, E e3) { + return construct(3, e1, e2, e3); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any element is null + */ + public static ImmutableSet of(E e1, E e2, E e3, E e4) { + return construct(4, e1, e2, e3, e4); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any element is null + */ + public static ImmutableSet of(E e1, E e2, E e3, E e4, E e5) { + return construct(5, e1, e2, e3, e4, e5); + } + + /** + * Returns an immutable set containing the given elements, in order. Repeated + * occurrences of an element (according to {@link Object#equals}) after the + * first are ignored. + * + * @throws NullPointerException if any element is null + * @since 3.0 (source-compatible since 2.0) + */ + public static ImmutableSet of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { + final int paramCount = 6; + Object[] elements = new Object[paramCount + others.length]; + elements[0] = e1; + elements[1] = e2; + elements[2] = e3; + elements[3] = e4; + elements[4] = e5; + elements[5] = e6; + System.arraycopy(others, 0, elements, paramCount, others.length); + return construct(elements.length, elements); + } + + ImmutableSet() { + } + + @Override + public boolean equals(@Nullable Object object) { + if (object == this) { + return true; + } else if (object instanceof ImmutableSet && isHashCodeFast() && ((ImmutableSet) object).isHashCodeFast() + && hashCode() != object.hashCode()) { + return false; + } + return Sets.equalsImpl(this, object); + } + + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); + } + + /** Returns {@code true} if the {@code hashCode()} method runs quickly. */ + boolean isHashCodeFast() { + return false; + } + + // This declaration is needed to make Set.iterator() and + // ImmutableCollection.iterator() consistent. + @Override + public abstract UnmodifiableIterator iterator(); + + @Override + Object writeReplace() { + return new SerializedForm(toArray()); + } } diff --git a/src/main/java/com/google/common/collect/ImmutableSetMultimap.java b/src/main/java/com/google/common/collect/ImmutableSetMultimap.java index 0050f97e..ba420a31 100644 --- a/src/main/java/com/google/common/collect/ImmutableSetMultimap.java +++ b/src/main/java/com/google/common/collect/ImmutableSetMultimap.java @@ -67,6 +67,237 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(serializable = true, emulated = true) public class ImmutableSetMultimap extends ImmutableMultimap implements SetMultimap { + /** + * A builder for creating immutable {@code SetMultimap} instances, especially + * {@code public static final} multimaps ("constant multimaps"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	static final Multimap STRING_TO_INTEGER_MULTIMAP = new ImmutableSetMultimap.Builder()
+	 * 			.put("one", 1).putAll("several", 1, 2, 3).putAll("many", 1, 2, 3, 4, 5).build();
+	 * }
+	 * 
+ * + *

+ * Builder instances can be reused; it is safe to call {@link #build} multiple + * times to build multiple multimaps in series. Each multimap contains the + * key-value mappings in the previously created multimaps. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static final class Builder extends ImmutableMultimap.Builder { + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableSetMultimap#builder}. + */ + public Builder() { + builderMultimap = new BuilderMultimap(); + } + + /** + * Returns a newly-created immutable set multimap. + */ + @Override + public ImmutableSetMultimap build() { + if (keyComparator != null) { + Multimap sortedCopy = new BuilderMultimap(); + List>> entries = Lists.newArrayList(builderMultimap.asMap().entrySet()); + Collections.sort(entries, Ordering.from(keyComparator).onKeys()); + for (Map.Entry> entry : entries) { + sortedCopy.putAll(entry.getKey(), entry.getValue()); + } + builderMultimap = sortedCopy; + } + return copyOf(builderMultimap, valueComparator); + } + + /** + * {@inheritDoc} + * + * @since 8.0 + */ + @Override + public Builder orderKeysBy(Comparator keyComparator) { + this.keyComparator = checkNotNull(keyComparator); + return this; + } + + /** + * Specifies the ordering of the generated multimap's values for each key. + * + *

+ * If this method is called, the sets returned by the {@code get()} method of + * the generated multimap and its {@link Multimap#asMap()} view are + * {@link ImmutableSortedSet} instances. However, serialization does not + * preserve that property, though it does maintain the key and value ordering. + * + * @since 8.0 + */ + // TODO: Make serialization behavior consistent. + @Override + public Builder orderValuesBy(Comparator valueComparator) { + super.orderValuesBy(valueComparator); + return this; + } + + /** + * Adds an entry to the built multimap if it is not already present. + * + * @since 11.0 + */ + @Override + public Builder put(Entry entry) { + builderMultimap.put(checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); + return this; + } + + /** + * Adds a key-value mapping to the built multimap if it is not already present. + */ + @Override + public Builder put(K key, V value) { + builderMultimap.put(checkNotNull(key), checkNotNull(value)); + return this; + } + + @Override + public Builder putAll(K key, Iterable values) { + Collection collection = builderMultimap.get(checkNotNull(key)); + for (V value : values) { + collection.add(checkNotNull(value)); + } + return this; + } + + @Override + public Builder putAll(K key, V... values) { + return putAll(key, Arrays.asList(values)); + } + + @Override + public Builder putAll(Multimap multimap) { + for (Entry> entry : multimap.asMap().entrySet()) { + putAll(entry.getKey(), entry.getValue()); + } + return this; + } + } + + /** + * Multimap for {@link ImmutableSetMultimap.Builder} that maintains key and + * value orderings and performs better than {@link LinkedHashMultimap}. + */ + private static class BuilderMultimap extends AbstractMapBasedMultimap { + private static final long serialVersionUID = 0; + + BuilderMultimap() { + super(new LinkedHashMap>()); + } + + @Override + Collection createCollection() { + return Sets.newLinkedHashSet(); + } + } + + private static final class EntrySet extends ImmutableSet> { + private transient final ImmutableSetMultimap multimap; + + EntrySet(ImmutableSetMultimap multimap) { + this.multimap = multimap; + } + + @Override + public boolean contains(@Nullable Object object) { + if (object instanceof Entry) { + Entry entry = (Entry) object; + return multimap.containsEntry(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public UnmodifiableIterator> iterator() { + return multimap.entryIterator(); + } + + @Override + public int size() { + return multimap.size(); + } + } + + @GwtIncompatible("not needed in emulated source.") + private static final long serialVersionUID = 0; + + /** + * Returns a new {@link Builder}. + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns an immutable set multimap containing the same mappings as + * {@code multimap}. The generated multimap's key and value orderings correspond + * to the iteration ordering of the {@code multimap.asMap()} view. Repeated + * occurrences of an entry in the multimap after the first are ignored. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if any key or value in {@code multimap} is null + */ + public static ImmutableSetMultimap copyOf(Multimap multimap) { + return copyOf(multimap, null); + } + + // looking for of() with > 5 entries? Use the builder instead. + + private static ImmutableSetMultimap copyOf(Multimap multimap, + Comparator valueComparator) { + checkNotNull(multimap); // eager for GWT + if (multimap.isEmpty() && valueComparator == null) { + return of(); + } + + if (multimap instanceof ImmutableSetMultimap) { + @SuppressWarnings("unchecked") // safe since multimap is not writable + ImmutableSetMultimap kvMultimap = (ImmutableSetMultimap) multimap; + if (!kvMultimap.isPartialView()) { + return kvMultimap; + } + } + + ImmutableMap.Builder> builder = ImmutableMap.builder(); + int size = 0; + + for (Entry> entry : multimap.asMap().entrySet()) { + K key = entry.getKey(); + Collection values = entry.getValue(); + ImmutableSet set = valueSet(valueComparator, values); + if (!set.isEmpty()) { + builder.put(key, set); + size += set.size(); + } + } + + return new ImmutableSetMultimap(builder.build(), size, valueComparator); + } + + private static ImmutableSet emptySet(@Nullable Comparator valueComparator) { + return (valueComparator == null) ? ImmutableSet.of() : ImmutableSortedSet.emptySet(valueComparator); + } + /** Returns the empty multimap. */ // Casting is safe because the multimap will never hold any elements. @SuppressWarnings("unchecked") @@ -122,6 +353,8 @@ public class ImmutableSetMultimap extends ImmutableMultimap implemen return builder.build(); } + // views + /** * Returns an immutable multimap containing the given entries, in order. * Repeated occurrences of an entry (according to {@link Object#equals}) after @@ -137,196 +370,10 @@ public class ImmutableSetMultimap extends ImmutableMultimap implemen return builder.build(); } - // looking for of() with > 5 entries? Use the builder instead. - - /** - * Returns a new {@link Builder}. - */ - public static Builder builder() { - return new Builder(); - } - - /** - * Multimap for {@link ImmutableSetMultimap.Builder} that maintains key and - * value orderings and performs better than {@link LinkedHashMultimap}. - */ - private static class BuilderMultimap extends AbstractMapBasedMultimap { - BuilderMultimap() { - super(new LinkedHashMap>()); - } - - @Override - Collection createCollection() { - return Sets.newLinkedHashSet(); - } - - private static final long serialVersionUID = 0; - } - - /** - * A builder for creating immutable {@code SetMultimap} instances, especially - * {@code public static final} multimaps ("constant multimaps"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	static final Multimap STRING_TO_INTEGER_MULTIMAP = new ImmutableSetMultimap.Builder()
-	 * 			.put("one", 1).putAll("several", 1, 2, 3).putAll("many", 1, 2, 3, 4, 5).build();
-	 * }
-	 * 
- * - *

- * Builder instances can be reused; it is safe to call {@link #build} multiple - * times to build multiple multimaps in series. Each multimap contains the - * key-value mappings in the previously created multimaps. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static final class Builder extends ImmutableMultimap.Builder { - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableSetMultimap#builder}. - */ - public Builder() { - builderMultimap = new BuilderMultimap(); - } - - /** - * Adds a key-value mapping to the built multimap if it is not already present. - */ - @Override - public Builder put(K key, V value) { - builderMultimap.put(checkNotNull(key), checkNotNull(value)); - return this; - } - - /** - * Adds an entry to the built multimap if it is not already present. - * - * @since 11.0 - */ - @Override - public Builder put(Entry entry) { - builderMultimap.put(checkNotNull(entry.getKey()), checkNotNull(entry.getValue())); - return this; - } - - @Override - public Builder putAll(K key, Iterable values) { - Collection collection = builderMultimap.get(checkNotNull(key)); - for (V value : values) { - collection.add(checkNotNull(value)); - } - return this; - } - - @Override - public Builder putAll(K key, V... values) { - return putAll(key, Arrays.asList(values)); - } - - @Override - public Builder putAll(Multimap multimap) { - for (Entry> entry : multimap.asMap().entrySet()) { - putAll(entry.getKey(), entry.getValue()); - } - return this; - } - - /** - * {@inheritDoc} - * - * @since 8.0 - */ - @Override - public Builder orderKeysBy(Comparator keyComparator) { - this.keyComparator = checkNotNull(keyComparator); - return this; - } - - /** - * Specifies the ordering of the generated multimap's values for each key. - * - *

- * If this method is called, the sets returned by the {@code get()} method of - * the generated multimap and its {@link Multimap#asMap()} view are - * {@link ImmutableSortedSet} instances. However, serialization does not - * preserve that property, though it does maintain the key and value ordering. - * - * @since 8.0 - */ - // TODO: Make serialization behavior consistent. - @Override - public Builder orderValuesBy(Comparator valueComparator) { - super.orderValuesBy(valueComparator); - return this; - } - - /** - * Returns a newly-created immutable set multimap. - */ - @Override - public ImmutableSetMultimap build() { - if (keyComparator != null) { - Multimap sortedCopy = new BuilderMultimap(); - List>> entries = Lists.newArrayList(builderMultimap.asMap().entrySet()); - Collections.sort(entries, Ordering.from(keyComparator).onKeys()); - for (Map.Entry> entry : entries) { - sortedCopy.putAll(entry.getKey(), entry.getValue()); - } - builderMultimap = sortedCopy; - } - return copyOf(builderMultimap, valueComparator); - } - } - - /** - * Returns an immutable set multimap containing the same mappings as - * {@code multimap}. The generated multimap's key and value orderings correspond - * to the iteration ordering of the {@code multimap.asMap()} view. Repeated - * occurrences of an entry in the multimap after the first are ignored. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if any key or value in {@code multimap} is null - */ - public static ImmutableSetMultimap copyOf(Multimap multimap) { - return copyOf(multimap, null); - } - - private static ImmutableSetMultimap copyOf(Multimap multimap, - Comparator valueComparator) { - checkNotNull(multimap); // eager for GWT - if (multimap.isEmpty() && valueComparator == null) { - return of(); - } - - if (multimap instanceof ImmutableSetMultimap) { - @SuppressWarnings("unchecked") // safe since multimap is not writable - ImmutableSetMultimap kvMultimap = (ImmutableSetMultimap) multimap; - if (!kvMultimap.isPartialView()) { - return kvMultimap; - } - } - - ImmutableMap.Builder> builder = ImmutableMap.builder(); - int size = 0; - - for (Entry> entry : multimap.asMap().entrySet()) { - K key = entry.getKey(); - Collection values = entry.getValue(); - ImmutableSet set = valueSet(valueComparator, values); - if (!set.isEmpty()) { - builder.put(key, set); - size += set.size(); - } - } - - return new ImmutableSetMultimap(builder.build(), size, valueComparator); + private static ImmutableSet valueSet(@Nullable Comparator valueComparator, + Collection values) { + return (valueComparator == null) ? ImmutableSet.copyOf(values) + : ImmutableSortedSet.copyOf(valueComparator, values); } /** @@ -335,13 +382,26 @@ public class ImmutableSetMultimap extends ImmutableMultimap implemen */ private final transient ImmutableSet emptySet; + private transient ImmutableSetMultimap inverse; + + private transient ImmutableSet> entries; + ImmutableSetMultimap(ImmutableMap> map, int size, @Nullable Comparator valueComparator) { super(map, size); this.emptySet = emptySet(valueComparator); } - // views + /** + * Returns an immutable collection of all key-value pairs in the multimap. Its + * iterator traverses the values for the first key, the values for the second + * key, and so on. + */ + @Override + public ImmutableSet> entries() { + ImmutableSet> result = entries; + return (result == null) ? (entries = new EntrySet(this)) : result; + } /** * Returns an immutable set of the values for the given key. If no mappings in @@ -355,8 +415,6 @@ public class ImmutableSetMultimap extends ImmutableMultimap implemen return firstNonNull(set, emptySet); } - private transient ImmutableSetMultimap inverse; - /** * {@inheritDoc} * @@ -383,101 +441,6 @@ public class ImmutableSetMultimap extends ImmutableMultimap implemen return invertedMultimap; } - /** - * Guaranteed to throw an exception and leave the multimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public ImmutableSet removeAll(Object key) { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the multimap unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public ImmutableSet replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - private transient ImmutableSet> entries; - - /** - * Returns an immutable collection of all key-value pairs in the multimap. Its - * iterator traverses the values for the first key, the values for the second - * key, and so on. - */ - @Override - public ImmutableSet> entries() { - ImmutableSet> result = entries; - return (result == null) ? (entries = new EntrySet(this)) : result; - } - - private static final class EntrySet extends ImmutableSet> { - private transient final ImmutableSetMultimap multimap; - - EntrySet(ImmutableSetMultimap multimap) { - this.multimap = multimap; - } - - @Override - public boolean contains(@Nullable Object object) { - if (object instanceof Entry) { - Entry entry = (Entry) object; - return multimap.containsEntry(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public int size() { - return multimap.size(); - } - - @Override - public UnmodifiableIterator> iterator() { - return multimap.entryIterator(); - } - - @Override - boolean isPartialView() { - return false; - } - } - - private static ImmutableSet valueSet(@Nullable Comparator valueComparator, - Collection values) { - return (valueComparator == null) ? ImmutableSet.copyOf(values) - : ImmutableSortedSet.copyOf(valueComparator, values); - } - - private static ImmutableSet emptySet(@Nullable Comparator valueComparator) { - return (valueComparator == null) ? ImmutableSet.of() : ImmutableSortedSet.emptySet(valueComparator); - } - - /** - * @serialData number of distinct keys, and then for each distinct key: the key, - * the number of values for that key, and the key's values - */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(valueComparator()); - Serialization.writeMultimap(this, stream); - } - - @Nullable - Comparator valueComparator() { - return emptySet instanceof ImmutableSortedSet ? ((ImmutableSortedSet) emptySet).comparator() : null; - } - @GwtIncompatible("java.io.ObjectInputStream") // Serialization type safety is at the caller's mercy. @SuppressWarnings("unchecked") @@ -522,6 +485,43 @@ public class ImmutableSetMultimap extends ImmutableMultimap implemen FieldSettersHolder.EMPTY_SET_FIELD_SETTER.set(this, emptySet(valueComparator)); } - @GwtIncompatible("not needed in emulated source.") - private static final long serialVersionUID = 0; + /** + * Guaranteed to throw an exception and leave the multimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public ImmutableSet removeAll(Object key) { + throw new UnsupportedOperationException(); + } + + /** + * Guaranteed to throw an exception and leave the multimap unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public ImmutableSet replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + @Nullable + Comparator valueComparator() { + return emptySet instanceof ImmutableSortedSet ? ((ImmutableSortedSet) emptySet).comparator() : null; + } + + /** + * @serialData number of distinct keys, and then for each distinct key: the key, + * the number of values for that key, and the key's values + */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(valueComparator()); + Serialization.writeMultimap(this, stream); + } } diff --git a/src/main/java/com/google/common/collect/ImmutableSortedAsList.java b/src/main/java/com/google/common/collect/ImmutableSortedAsList.java index 62603a11..3a579094 100644 --- a/src/main/java/com/google/common/collect/ImmutableSortedAsList.java +++ b/src/main/java/com/google/common/collect/ImmutableSortedAsList.java @@ -35,18 +35,24 @@ final class ImmutableSortedAsList extends RegularImmutableAsList implement super(backingSet, backingList); } - @Override - ImmutableSortedSet delegateCollection() { - return (ImmutableSortedSet) super.delegateCollection(); - } - @Override public Comparator comparator() { return delegateCollection().comparator(); } + @Override + public boolean contains(Object target) { + // Necessary for ISS's with comparators inconsistent with equals. + return indexOf(target) >= 0; + } + // Override indexOf() and lastIndexOf() to be O(log N) instead of O(N). + @Override + ImmutableSortedSet delegateCollection() { + return (ImmutableSortedSet) super.delegateCollection(); + } + @GwtIncompatible("ImmutableSortedSet.indexOf") // TODO(cpovirk): consider manual binary search under GWT to preserve O(log N) // lookup @@ -68,12 +74,6 @@ final class ImmutableSortedAsList extends RegularImmutableAsList implement return indexOf(target); } - @Override - public boolean contains(Object target) { - // Necessary for ISS's with comparators inconsistent with equals. - return indexOf(target) >= 0; - } - @GwtIncompatible("super.subListUnchecked does not exist; inherited subList is valid if slow") /* * TODO(cpovirk): if we start to override indexOf/lastIndexOf under GWT, we'll diff --git a/src/main/java/com/google/common/collect/ImmutableSortedMap.java b/src/main/java/com/google/common/collect/ImmutableSortedMap.java index 6908186f..bc487797 100644 --- a/src/main/java/com/google/common/collect/ImmutableSortedMap.java +++ b/src/main/java/com/google/common/collect/ImmutableSortedMap.java @@ -61,6 +61,115 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible(serializable = true, emulated = true) public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxverideShim implements NavigableMap { + /** + * A builder for creating immutable sorted map instances, especially {@code + * public static final} maps ("constant maps"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	static final ImmutableSortedMap INT_TO_WORD = new ImmutableSortedMap.Builder(
+	 * 			Ordering.natural()).put(1, "one").put(2, "two").put(3, "three").build();
+	 * }
+	 * 
+ * + *

+ * For small immutable sorted maps, the {@code ImmutableSortedMap.of()} + * methods are even more convenient. + * + *

+ * Builder instances can be reused - it is safe to call {@link #build} multiple + * times to build multiple maps in series. Each map is a superset of the maps + * created before it. + * + * @since 2.0 (imported from Google Collections Library) + */ + public static class Builder extends ImmutableMap.Builder { + private final Comparator comparator; + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableSortedMap#orderedBy}. + */ + @SuppressWarnings("unchecked") + public Builder(Comparator comparator) { + this.comparator = checkNotNull(comparator); + } + + /** + * Returns a newly-created immutable sorted map. + * + * @throws IllegalArgumentException if any two keys are equal according to the + * comparator (which might be the keys' natural + * order) + */ + @Override + public ImmutableSortedMap build() { + return fromEntries(comparator, false, size, entries); + } + + /** + * Adds the given {@code entry} to the map, making it immutable if necessary. + * Duplicate keys, according to the comparator (which might be the keys' natural + * order), are not allowed, and will cause {@link #build} to fail. + * + * @since 11.0 + */ + @Override + public Builder put(Entry entry) { + super.put(entry); + return this; + } + + /** + * Associates {@code key} with {@code value} in the built map. Duplicate keys, + * according to the comparator (which might be the keys' natural order), are not + * allowed, and will cause {@link #build} to fail. + */ + @Override + public Builder put(K key, V value) { + super.put(key, value); + return this; + } + + /** + * Associates all of the given map's keys and values in the built map. Duplicate + * keys, according to the comparator (which might be the keys' natural order), + * are not allowed, and will cause {@link #build} to fail. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + @Override + public Builder putAll(Map map) { + super.putAll(map); + return this; + } + } + + /** + * Serialized type for all ImmutableSortedMap instances. It captures the logical + * contents and they are reconstructed using public factory methods. This + * ensures that the implementation types remain as implementation details. + */ + private static class SerializedForm extends ImmutableMap.SerializedForm { + private static final long serialVersionUID = 0; + + private final Comparator comparator; + + @SuppressWarnings("unchecked") + SerializedForm(ImmutableSortedMap sortedMap) { + super(sortedMap); + comparator = (Comparator) sortedMap.comparator(); + } + + @Override + Object readResolve() { + Builder builder = new Builder(comparator); + return createMap(builder); + } + } + /* * TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and uses * less memory than TreeMap; then say so in the class Javadoc. @@ -70,6 +179,105 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver private static final ImmutableSortedMap NATURAL_EMPTY_MAP = new EmptyImmutableSortedMap( NATURAL_ORDER); + // This class is never actually serialized directly, but we have to make the + // warning go away (and suppressing would suppress for all nested classes too) + private static final long serialVersionUID = 0; + + /** + * Returns an immutable map containing the same entries as {@code map}, sorted + * by the natural ordering of the keys. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * This method is not type-safe, as it may be called on a map with keys that are + * not mutually comparable. + * + * @throws ClassCastException if the keys in {@code map} are not mutually + * comparable + * @throws NullPointerException if any key or value in {@code map} is null + * @throws IllegalArgumentException if any two keys are equal according to their + * natural ordering + */ + public static ImmutableSortedMap copyOf(Map map) { + // Hack around K not being a subtype of Comparable. + // Unsafe, see ImmutableSortedSetFauxverideShim. + @SuppressWarnings("unchecked") + Ordering naturalOrder = (Ordering) Ordering.natural(); + return copyOfInternal(map, naturalOrder); + } + + /** + * Returns an immutable map containing the same entries as {@code map}, with + * keys sorted by the provided comparator. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if any key or value in {@code map} is null + * @throws IllegalArgumentException if any two keys are equal according to the + * comparator + */ + public static ImmutableSortedMap copyOf(Map map, + Comparator comparator) { + return copyOfInternal(map, checkNotNull(comparator)); + } + + private static ImmutableSortedMap copyOfInternal(Map map, + Comparator comparator) { + boolean sameComparator = false; + if (map instanceof SortedMap) { + SortedMap sortedMap = (SortedMap) map; + Comparator comparator2 = sortedMap.comparator(); + sameComparator = (comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2); + } + + if (sameComparator && (map instanceof ImmutableSortedMap)) { + // TODO(kevinb): Prove that this cast is safe, even though + // Collections.unmodifiableSortedMap requires the same key type. + @SuppressWarnings("unchecked") + ImmutableSortedMap kvMap = (ImmutableSortedMap) map; + if (!kvMap.isPartialView()) { + return kvMap; + } + } + + // "adding" type params to an array of a raw type should be safe as + // long as no one can ever cast that same array instance back to a + // raw type. + @SuppressWarnings("unchecked") + Entry[] entries = map.entrySet().toArray(new Entry[0]); + + return fromEntries(comparator, sameComparator, entries.length, entries); + } + + /** + * Returns an immutable map containing the same entries as the provided sorted + * map, with the same ordering. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if any key or value in {@code map} is null + */ + @SuppressWarnings("unchecked") + public static ImmutableSortedMap copyOfSorted(SortedMap map) { + Comparator comparator = map.comparator(); + if (comparator == null) { + // If map has a null comparator, the keys should have a natural ordering, + // even though K doesn't explicitly implement Comparable. + comparator = (Comparator) NATURAL_ORDER; + } + return copyOfInternal(map, comparator); + } + static ImmutableSortedMap emptyMap(Comparator comparator) { if (Ordering.natural().equals(comparator)) { return of(); @@ -78,6 +286,28 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver } } + static ImmutableSortedMap from(ImmutableSortedSet keySet, ImmutableList valueList) { + if (keySet.isEmpty()) { + return emptyMap(keySet.comparator()); + } else { + return new RegularImmutableSortedMap((RegularImmutableSortedSet) keySet, valueList); + } + } + + static ImmutableSortedMap fromEntries(Comparator comparator, boolean sameComparator, + int size, Entry... entries) { + for (int i = 0; i < size; i++) { + Entry entry = entries[i]; + entries[i] = entryOf(entry.getKey(), entry.getValue()); + } + if (!sameComparator) { + sortEntries(comparator, size, entries); + validateEntries(size, entries, comparator); + } + + return fromSortedEntries(comparator, size, entries); + } + static ImmutableSortedMap fromSortedEntries(Comparator comparator, int size, Entry[] entries) { if (size == 0) { @@ -96,12 +326,13 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver valueBuilder.build()); } - static ImmutableSortedMap from(ImmutableSortedSet keySet, ImmutableList valueList) { - if (keySet.isEmpty()) { - return emptyMap(keySet.comparator()); - } else { - return new RegularImmutableSortedMap((RegularImmutableSortedSet) keySet, valueList); - } + /** + * Returns a builder that creates immutable sorted maps whose keys are ordered + * by their natural ordering. The sorted maps use {@link Ordering#natural()} as + * the comparator. + */ + public static , V> Builder naturalOrder() { + return new Builder(Ordering.natural()); } /** @@ -173,135 +404,6 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver entryOf(k4, v4), entryOf(k5, v5)); } - /** - * Returns an immutable map containing the same entries as {@code map}, sorted - * by the natural ordering of the keys. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * This method is not type-safe, as it may be called on a map with keys that are - * not mutually comparable. - * - * @throws ClassCastException if the keys in {@code map} are not mutually - * comparable - * @throws NullPointerException if any key or value in {@code map} is null - * @throws IllegalArgumentException if any two keys are equal according to their - * natural ordering - */ - public static ImmutableSortedMap copyOf(Map map) { - // Hack around K not being a subtype of Comparable. - // Unsafe, see ImmutableSortedSetFauxverideShim. - @SuppressWarnings("unchecked") - Ordering naturalOrder = (Ordering) Ordering.natural(); - return copyOfInternal(map, naturalOrder); - } - - /** - * Returns an immutable map containing the same entries as {@code map}, with - * keys sorted by the provided comparator. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if any key or value in {@code map} is null - * @throws IllegalArgumentException if any two keys are equal according to the - * comparator - */ - public static ImmutableSortedMap copyOf(Map map, - Comparator comparator) { - return copyOfInternal(map, checkNotNull(comparator)); - } - - /** - * Returns an immutable map containing the same entries as the provided sorted - * map, with the same ordering. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if any key or value in {@code map} is null - */ - @SuppressWarnings("unchecked") - public static ImmutableSortedMap copyOfSorted(SortedMap map) { - Comparator comparator = map.comparator(); - if (comparator == null) { - // If map has a null comparator, the keys should have a natural ordering, - // even though K doesn't explicitly implement Comparable. - comparator = (Comparator) NATURAL_ORDER; - } - return copyOfInternal(map, comparator); - } - - private static ImmutableSortedMap copyOfInternal(Map map, - Comparator comparator) { - boolean sameComparator = false; - if (map instanceof SortedMap) { - SortedMap sortedMap = (SortedMap) map; - Comparator comparator2 = sortedMap.comparator(); - sameComparator = (comparator2 == null) ? comparator == NATURAL_ORDER : comparator.equals(comparator2); - } - - if (sameComparator && (map instanceof ImmutableSortedMap)) { - // TODO(kevinb): Prove that this cast is safe, even though - // Collections.unmodifiableSortedMap requires the same key type. - @SuppressWarnings("unchecked") - ImmutableSortedMap kvMap = (ImmutableSortedMap) map; - if (!kvMap.isPartialView()) { - return kvMap; - } - } - - // "adding" type params to an array of a raw type should be safe as - // long as no one can ever cast that same array instance back to a - // raw type. - @SuppressWarnings("unchecked") - Entry[] entries = map.entrySet().toArray(new Entry[0]); - - return fromEntries(comparator, sameComparator, entries.length, entries); - } - - static ImmutableSortedMap fromEntries(Comparator comparator, boolean sameComparator, - int size, Entry... entries) { - for (int i = 0; i < size; i++) { - Entry entry = entries[i]; - entries[i] = entryOf(entry.getKey(), entry.getValue()); - } - if (!sameComparator) { - sortEntries(comparator, size, entries); - validateEntries(size, entries, comparator); - } - - return fromSortedEntries(comparator, size, entries); - } - - private static void sortEntries(final Comparator comparator, int size, Entry[] entries) { - Arrays.sort(entries, 0, size, Ordering.from(comparator).onKeys()); - } - - private static void validateEntries(int size, Entry[] entries, Comparator comparator) { - for (int i = 1; i < size; i++) { - checkNoConflict(comparator.compare(entries[i - 1].getKey(), entries[i].getKey()) != 0, "key", - entries[i - 1], entries[i]); - } - } - - /** - * Returns a builder that creates immutable sorted maps whose keys are ordered - * by their natural ordering. The sorted maps use {@link Ordering#natural()} as - * the comparator. - */ - public static , V> Builder naturalOrder() { - return new Builder(Ordering.natural()); - } - /** * Returns a builder that creates immutable sorted maps with an explicit * comparator. If the comparator has a more general type than the map's keys, @@ -322,92 +424,19 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver return new Builder(Ordering.natural().reverse()); } - /** - * A builder for creating immutable sorted map instances, especially {@code - * public static final} maps ("constant maps"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	static final ImmutableSortedMap INT_TO_WORD = new ImmutableSortedMap.Builder(
-	 * 			Ordering.natural()).put(1, "one").put(2, "two").put(3, "three").build();
-	 * }
-	 * 
- * - *

- * For small immutable sorted maps, the {@code ImmutableSortedMap.of()} - * methods are even more convenient. - * - *

- * Builder instances can be reused - it is safe to call {@link #build} multiple - * times to build multiple maps in series. Each map is a superset of the maps - * created before it. - * - * @since 2.0 (imported from Google Collections Library) - */ - public static class Builder extends ImmutableMap.Builder { - private final Comparator comparator; + private static void sortEntries(final Comparator comparator, int size, Entry[] entries) { + Arrays.sort(entries, 0, size, Ordering.from(comparator).onKeys()); + } - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableSortedMap#orderedBy}. - */ - @SuppressWarnings("unchecked") - public Builder(Comparator comparator) { - this.comparator = checkNotNull(comparator); - } - - /** - * Associates {@code key} with {@code value} in the built map. Duplicate keys, - * according to the comparator (which might be the keys' natural order), are not - * allowed, and will cause {@link #build} to fail. - */ - @Override - public Builder put(K key, V value) { - super.put(key, value); - return this; - } - - /** - * Adds the given {@code entry} to the map, making it immutable if necessary. - * Duplicate keys, according to the comparator (which might be the keys' natural - * order), are not allowed, and will cause {@link #build} to fail. - * - * @since 11.0 - */ - @Override - public Builder put(Entry entry) { - super.put(entry); - return this; - } - - /** - * Associates all of the given map's keys and values in the built map. Duplicate - * keys, according to the comparator (which might be the keys' natural order), - * are not allowed, and will cause {@link #build} to fail. - * - * @throws NullPointerException if any key or value in {@code map} is null - */ - @Override - public Builder putAll(Map map) { - super.putAll(map); - return this; - } - - /** - * Returns a newly-created immutable sorted map. - * - * @throws IllegalArgumentException if any two keys are equal according to the - * comparator (which might be the keys' natural - * order) - */ - @Override - public ImmutableSortedMap build() { - return fromEntries(comparator, false, size, entries); + private static void validateEntries(int size, Entry[] entries, Comparator comparator) { + for (int i = 1; i < size; i++) { + checkNoConflict(comparator.compare(entries[i - 1].getKey(), entries[i].getKey()) != 0, "key", + entries[i - 1], entries[i]); } } + private transient ImmutableSortedMap descendingMap; + ImmutableSortedMap() { } @@ -416,42 +445,15 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver } @Override - public int size() { - return values().size(); + public Entry ceilingEntry(K key) { + return tailMap(key, true).firstEntry(); } @Override - public boolean containsValue(@Nullable Object value) { - return values().contains(value); + public K ceilingKey(K key) { + return keyOrNull(ceilingEntry(key)); } - @Override - boolean isPartialView() { - return keySet().isPartialView() || values().isPartialView(); - } - - /** - * Returns an immutable set of the mappings in this map, sorted by the key - * ordering. - */ - @Override - public ImmutableSet> entrySet() { - return super.entrySet(); - } - - /** - * Returns an immutable sorted set of the keys in this map. - */ - @Override - public abstract ImmutableSortedSet keySet(); - - /** - * Returns an immutable collection of the values in this map, sorted by the - * ordering of the corresponding keys. - */ - @Override - public abstract ImmutableCollection values(); - /** * Returns the comparator that orders the keys, which is * {@link Ordering#natural()} when the natural ordering of the keys is used. @@ -463,14 +465,54 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver return keySet().comparator(); } + @Override + public boolean containsValue(@Nullable Object value) { + return values().contains(value); + } + + abstract ImmutableSortedMap createDescendingMap(); + + @Override + public ImmutableSortedSet descendingKeySet() { + return keySet().descendingSet(); + } + + @Override + public ImmutableSortedMap descendingMap() { + ImmutableSortedMap result = descendingMap; + if (result == null) { + result = descendingMap = createDescendingMap(); + } + return result; + } + + /** + * Returns an immutable set of the mappings in this map, sorted by the key + * ordering. + */ + @Override + public ImmutableSet> entrySet() { + return super.entrySet(); + } + + @Override + public Entry firstEntry() { + return isEmpty() ? null : entrySet().asList().get(0); + } + @Override public K firstKey() { return keySet().first(); } @Override - public K lastKey() { - return keySet().last(); + public Entry floorEntry(K key) { + return headMap(key, true).lastEntry(); + } + + @Override + public K floorKey(K key) { + return keyOrNull(floorEntry(key)); } /** @@ -505,23 +547,79 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver @Override public abstract ImmutableSortedMap headMap(K toKey, boolean inclusive); + @Override + public Entry higherEntry(K key) { + return tailMap(key, false).firstEntry(); + } + + @Override + public K higherKey(K key) { + return keyOrNull(higherEntry(key)); + } + + @Override + boolean isPartialView() { + return keySet().isPartialView() || values().isPartialView(); + } + /** - * This method returns a {@code ImmutableSortedMap}, consisting of the entries - * whose keys ranges from {@code fromKey}, inclusive, to {@code toKey}, - * exclusive. - * - *

- * The {@link SortedMap#subMap} documentation states that a submap of a submap - * throws an {@link IllegalArgumentException} if passed a {@code - * fromKey} less than an earlier {@code fromKey}. However, this method doesn't - * throw an exception in that situation, but instead keeps the original {@code - * fromKey}. Similarly, this method keeps the original {@code toKey}, instead of - * throwing an exception, if passed a {@code toKey} greater than an earlier - * {@code toKey}. + * Returns an immutable sorted set of the keys in this map. */ @Override - public ImmutableSortedMap subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); + public abstract ImmutableSortedSet keySet(); + + @Override + public Entry lastEntry() { + return isEmpty() ? null : entrySet().asList().get(size() - 1); + } + + @Override + public K lastKey() { + return keySet().last(); + } + + @Override + public Entry lowerEntry(K key) { + return headMap(key, false).lastEntry(); + } + + @Override + public K lowerKey(K key) { + return keyOrNull(lowerEntry(key)); + } + + @Override + public ImmutableSortedSet navigableKeySet() { + return keySet(); + } + + /** + * Guaranteed to throw an exception and leave the map unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final Entry pollFirstEntry() { + throw new UnsupportedOperationException(); + } + + /** + * Guaranteed to throw an exception and leave the map unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated + @Override + public final Entry pollLastEntry() { + throw new UnsupportedOperationException(); + } + + @Override + public int size() { + return values().size(); } /** @@ -549,6 +647,25 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver return headMap(toKey, toInclusive).tailMap(fromKey, fromInclusive); } + /** + * This method returns a {@code ImmutableSortedMap}, consisting of the entries + * whose keys ranges from {@code fromKey}, inclusive, to {@code toKey}, + * exclusive. + * + *

+ * The {@link SortedMap#subMap} documentation states that a submap of a submap + * throws an {@link IllegalArgumentException} if passed a {@code + * fromKey} less than an earlier {@code fromKey}. However, this method doesn't + * throw an exception in that situation, but instead keeps the original {@code + * fromKey}. Similarly, this method keeps the original {@code toKey}, instead of + * throwing an exception, if passed a {@code toKey} greater than an earlier + * {@code toKey}. + */ + @Override + public ImmutableSortedMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); + } + /** * This method returns a {@code ImmutableSortedMap}, consisting of the entries * whose keys are greater than or equals to {@code fromKey}. @@ -582,132 +699,15 @@ public abstract class ImmutableSortedMap extends ImmutableSortedMapFauxver @Override public abstract ImmutableSortedMap tailMap(K fromKey, boolean inclusive); - @Override - public Entry lowerEntry(K key) { - return headMap(key, false).lastEntry(); - } - - @Override - public K lowerKey(K key) { - return keyOrNull(lowerEntry(key)); - } - - @Override - public Entry floorEntry(K key) { - return headMap(key, true).lastEntry(); - } - - @Override - public K floorKey(K key) { - return keyOrNull(floorEntry(key)); - } - - @Override - public Entry ceilingEntry(K key) { - return tailMap(key, true).firstEntry(); - } - - @Override - public K ceilingKey(K key) { - return keyOrNull(ceilingEntry(key)); - } - - @Override - public Entry higherEntry(K key) { - return tailMap(key, false).firstEntry(); - } - - @Override - public K higherKey(K key) { - return keyOrNull(higherEntry(key)); - } - - @Override - public Entry firstEntry() { - return isEmpty() ? null : entrySet().asList().get(0); - } - - @Override - public Entry lastEntry() { - return isEmpty() ? null : entrySet().asList().get(size() - 1); - } - /** - * Guaranteed to throw an exception and leave the map unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. + * Returns an immutable collection of the values in this map, sorted by the + * ordering of the corresponding keys. */ - @Deprecated @Override - public final Entry pollFirstEntry() { - throw new UnsupportedOperationException(); - } - - /** - * Guaranteed to throw an exception and leave the map unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated - @Override - public final Entry pollLastEntry() { - throw new UnsupportedOperationException(); - } - - private transient ImmutableSortedMap descendingMap; - - @Override - public ImmutableSortedMap descendingMap() { - ImmutableSortedMap result = descendingMap; - if (result == null) { - result = descendingMap = createDescendingMap(); - } - return result; - } - - abstract ImmutableSortedMap createDescendingMap(); - - @Override - public ImmutableSortedSet navigableKeySet() { - return keySet(); - } - - @Override - public ImmutableSortedSet descendingKeySet() { - return keySet().descendingSet(); - } - - /** - * Serialized type for all ImmutableSortedMap instances. It captures the logical - * contents and they are reconstructed using public factory methods. This - * ensures that the implementation types remain as implementation details. - */ - private static class SerializedForm extends ImmutableMap.SerializedForm { - private final Comparator comparator; - - @SuppressWarnings("unchecked") - SerializedForm(ImmutableSortedMap sortedMap) { - super(sortedMap); - comparator = (Comparator) sortedMap.comparator(); - } - - @Override - Object readResolve() { - Builder builder = new Builder(comparator); - return createMap(builder); - } - - private static final long serialVersionUID = 0; - } + public abstract ImmutableCollection values(); @Override Object writeReplace() { return new SerializedForm(this); } - - // This class is never actually serialized directly, but we have to make the - // warning go away (and suppressing would suppress for all nested classes too) - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ImmutableSortedMultiset.java b/src/main/java/com/google/common/collect/ImmutableSortedMultiset.java index 08c092b4..da1cbdd2 100644 --- a/src/main/java/com/google/common/collect/ImmutableSortedMultiset.java +++ b/src/main/java/com/google/common/collect/ImmutableSortedMultiset.java @@ -98,11 +98,349 @@ public abstract class ImmutableSortedMultiset extends ImmutableSortedMultiset implements SortedMultiset { // TODO(user): GWT compatibility + /** + * A builder for creating immutable multiset instances, especially + * {@code public static final} multisets ("constant multisets"). Example: + * + *
+	 * {
+	 * 	@code
+	 *
+	 * 	public static final ImmutableSortedMultiset BEANS = new ImmutableSortedMultiset.Builder()
+	 * 			.addCopies(Bean.COCOA, 4).addCopies(Bean.GARDEN, 6).addCopies(Bean.RED, 8).addCopies(Bean.BLACK_EYED, 10)
+	 * 			.build();
+	 * }
+	 * 
+ * + *

+ * Builder instances can be reused; it is safe to call {@link #build} multiple + * times to build multiple multisets in series. + * + * @since 12.0 + */ + public static class Builder extends ImmutableMultiset.Builder { + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableSortedMultiset#orderedBy(Comparator)}. + */ + public Builder(Comparator comparator) { + super(TreeMultiset.create(checkNotNull(comparator))); + } + + /** + * Adds {@code element} to the {@code ImmutableSortedMultiset}. + * + * @param element the element to add + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + */ + @Override + public Builder add(E element) { + super.add(element); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. + * + * @param elements the elements to add + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder add(E... elements) { + super.add(elements); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. + * + * @param elements the {@code Iterable} to add to the + * {@code ImmutableSortedMultiset} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder addAll(Iterable elements) { + super.addAll(elements); + return this; + } + + /** + * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. + * + * @param elements the elements to add to the {@code ImmutableSortedMultiset} + * @return this {@code Builder} object + * @throws NullPointerException if {@code elements} is null or contains a null + * element + */ + @Override + public Builder addAll(Iterator elements) { + super.addAll(elements); + return this; + } + + /** + * Adds a number of occurrences of an element to this + * {@code ImmutableSortedMultiset}. + * + * @param element the element to add + * @param occurrences the number of occurrences of the element to add. May be + * zero, in which case no change will be made. + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + * @throws IllegalArgumentException if {@code occurrences} is negative, or if + * this operation would result in more than + * {@link Integer#MAX_VALUE} occurrences of the + * element + */ + @Override + public Builder addCopies(E element, int occurrences) { + super.addCopies(element, occurrences); + return this; + } + + /** + * Returns a newly-created {@code ImmutableSortedMultiset} based on the contents + * of the {@code + * Builder}. + */ + @Override + public ImmutableSortedMultiset build() { + return copyOfSorted((SortedMultiset) contents); + } + + /** + * Adds or removes the necessary occurrences of an element such that the element + * attains the desired count. + * + * @param element the element to add or remove occurrences of + * @param count the desired count of the element in this multiset + * @return this {@code Builder} object + * @throws NullPointerException if {@code element} is null + * @throws IllegalArgumentException if {@code count} is negative + */ + @Override + public Builder setCount(E element, int count) { + super.setCount(element, count); + return this; + } + } + + private static final class SerializedForm implements Serializable { + Comparator comparator; + E[] elements; + int[] counts; + + @SuppressWarnings("unchecked") + SerializedForm(SortedMultiset multiset) { + this.comparator = multiset.comparator(); + int n = multiset.entrySet().size(); + elements = (E[]) new Object[n]; + counts = new int[n]; + int i = 0; + for (Entry entry : multiset.entrySet()) { + elements[i] = entry.getElement(); + counts[i] = entry.getCount(); + i++; + } + } + + Object readResolve() { + int n = elements.length; + Builder builder = new Builder(comparator); + for (int i = 0; i < n; i++) { + builder.addCopies(elements[i], counts[i]); + } + return builder.build(); + } + } + private static final Comparator NATURAL_ORDER = Ordering.natural(); private static final ImmutableSortedMultiset NATURAL_EMPTY_MULTISET = new EmptyImmutableSortedMultiset( NATURAL_ORDER); + /** + * Returns an immutable sorted multiset containing the given elements sorted by + * the given {@code + * Comparator}. This method iterates over {@code elements} at most once. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if {@code comparator} or any of {@code elements} + * is null + */ + public static ImmutableSortedMultiset copyOf(Comparator comparator, + Iterable elements) { + if (elements instanceof ImmutableSortedMultiset) { + @SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts + ImmutableSortedMultiset multiset = (ImmutableSortedMultiset) elements; + if (comparator.equals(multiset.comparator())) { + if (multiset.isPartialView()) { + return copyOfSortedEntries(comparator, multiset.entrySet().asList()); + } else { + return multiset; + } + } + } + elements = Lists.newArrayList(elements); // defensive copy + TreeMultiset sortedCopy = TreeMultiset.create(checkNotNull(comparator)); + Iterables.addAll(sortedCopy, elements); + return copyOfSortedEntries(comparator, sortedCopy.entrySet()); + } + + /** + * Returns an immutable sorted multiset containing the given elements sorted by + * the given {@code + * Comparator}. + * + * @throws NullPointerException if {@code comparator} or any of {@code elements} + * is null + */ + public static ImmutableSortedMultiset copyOf(Comparator comparator, + Iterator elements) { + checkNotNull(comparator); + return new Builder(comparator).addAll(elements).build(); + } + + /** + * Returns an immutable sorted multiset containing the given elements sorted by + * their natural ordering. + * + * @throws NullPointerException if any of {@code elements} is null + */ + public static > ImmutableSortedMultiset copyOf(E[] elements) { + return copyOf(Ordering.natural(), Arrays.asList(elements)); + } + + /** + * Returns an immutable sorted multiset containing the given elements sorted by + * their natural ordering. To create a copy of a {@code SortedMultiset} that + * preserves the comparator, call {@link #copyOfSorted} instead. This method + * iterates over {@code elements} at most once. + * + *

+ * Note that if {@code s} is a {@code multiset}, then {@code + * ImmutableSortedMultiset.copyOf(s)} returns an + * {@code ImmutableSortedMultiset} containing each of the strings in + * {@code s}, while {@code ImmutableSortedMultiset.of(s)} returns an + * {@code ImmutableSortedMultiset>} containing one element (the + * given multiset itself). + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * This method is not type-safe, as it may be called on elements that are not + * mutually comparable. + * + * @throws ClassCastException if the elements are not mutually comparable + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableSortedMultiset copyOf(Iterable elements) { + // Hack around E not being a subtype of Comparable. + // Unsafe, see ImmutableSortedMultisetFauxverideShim. + @SuppressWarnings("unchecked") + Ordering naturalOrder = (Ordering) Ordering.natural(); + return copyOf(naturalOrder, elements); + } + + /** + * Returns an immutable sorted multiset containing the given elements sorted by + * their natural ordering. + * + *

+ * This method is not type-safe, as it may be called on elements that are not + * mutually comparable. + * + * @throws ClassCastException if the elements are not mutually comparable + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableSortedMultiset copyOf(Iterator elements) { + // Hack around E not being a subtype of Comparable. + // Unsafe, see ImmutableSortedMultisetFauxverideShim. + @SuppressWarnings("unchecked") + Ordering naturalOrder = (Ordering) Ordering.natural(); + return copyOf(naturalOrder, elements); + } + + /** + * Returns an immutable sorted multiset containing the elements of a sorted + * multiset, sorted by the same {@code Comparator}. That behavior differs from + * {@link #copyOf(Iterable)}, which always uses the natural ordering of the + * elements. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * This method is safe to use even when {@code sortedMultiset} is a synchronized + * or concurrent collection that is currently being modified by another thread. + * + * @throws NullPointerException if {@code sortedMultiset} or any of its elements + * is null + */ + public static ImmutableSortedMultiset copyOfSorted(SortedMultiset sortedMultiset) { + return copyOfSortedEntries(sortedMultiset.comparator(), Lists.newArrayList(sortedMultiset.entrySet())); + } + + private static ImmutableSortedMultiset copyOfSortedEntries(Comparator comparator, + Collection> entries) { + if (entries.isEmpty()) { + return emptyMultiset(comparator); + } + ImmutableList.Builder elementsBuilder = new ImmutableList.Builder(entries.size()); + int[] counts = new int[entries.size()]; + long[] cumulativeCounts = new long[entries.size() + 1]; + int i = 0; + for (Entry entry : entries) { + elementsBuilder.add(entry.getElement()); + counts[i] = entry.getCount(); + cumulativeCounts[i + 1] = cumulativeCounts[i] + counts[i]; + i++; + } + return new RegularImmutableSortedMultiset( + new RegularImmutableSortedSet(elementsBuilder.build(), comparator), counts, cumulativeCounts, 0, + entries.size()); + } + + @SuppressWarnings("unchecked") + static ImmutableSortedMultiset emptyMultiset(Comparator comparator) { + if (NATURAL_ORDER.equals(comparator)) { + return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET; + } + return new EmptyImmutableSortedMultiset(comparator); + } + + /** + * Returns a builder that creates immutable sorted multisets whose elements are + * ordered by their natural ordering. The sorted multisets use + * {@link Ordering#natural()} as the comparator. This method provides more + * type-safety than {@link #builder}, as it can be called only for classes that + * implement {@link Comparable}. + * + *

+ * Note: the type parameter {@code E} extends {@code Comparable} rather than + * {@code + * Comparable} as a workaround for javac + * bug + * 6468354. + */ + public static > Builder naturalOrder() { + return new Builder(Ordering.natural()); + } + /** * Returns the empty immutable sorted multiset. */ @@ -182,163 +520,34 @@ public abstract class ImmutableSortedMultiset extends ImmutableSortedMultiset } /** - * Returns an immutable sorted multiset containing the given elements sorted by - * their natural ordering. + * Returns a builder that creates immutable sorted multisets with an explicit + * comparator. If the comparator has a more general type than the set being + * generated, such as creating a {@code + * SortedMultiset} with a {@code Comparator}, use the + * {@link Builder} constructor instead. * - * @throws NullPointerException if any of {@code elements} is null + * @throws NullPointerException if {@code comparator} is null */ - public static > ImmutableSortedMultiset copyOf(E[] elements) { - return copyOf(Ordering.natural(), Arrays.asList(elements)); + public static Builder orderedBy(Comparator comparator) { + return new Builder(comparator); } /** - * Returns an immutable sorted multiset containing the given elements sorted by - * their natural ordering. To create a copy of a {@code SortedMultiset} that - * preserves the comparator, call {@link #copyOfSorted} instead. This method - * iterates over {@code elements} at most once. + * Returns a builder that creates immutable sorted multisets whose elements are + * ordered by the reverse of their natural ordering. * *

- * Note that if {@code s} is a {@code multiset}, then {@code - * ImmutableSortedMultiset.copyOf(s)} returns an - * {@code ImmutableSortedMultiset} containing each of the strings in - * {@code s}, while {@code ImmutableSortedMultiset.of(s)} returns an - * {@code ImmutableSortedMultiset>} containing one element (the - * given multiset itself). - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * This method is not type-safe, as it may be called on elements that are not - * mutually comparable. - * - * @throws ClassCastException if the elements are not mutually comparable - * @throws NullPointerException if any of {@code elements} is null + * Note: the type parameter {@code E} extends {@code Comparable} rather than + * {@code + * Comparable} as a workaround for javac + * bug + * 6468354. */ - public static ImmutableSortedMultiset copyOf(Iterable elements) { - // Hack around E not being a subtype of Comparable. - // Unsafe, see ImmutableSortedMultisetFauxverideShim. - @SuppressWarnings("unchecked") - Ordering naturalOrder = (Ordering) Ordering.natural(); - return copyOf(naturalOrder, elements); + public static > Builder reverseOrder() { + return new Builder(Ordering.natural().reverse()); } - /** - * Returns an immutable sorted multiset containing the given elements sorted by - * their natural ordering. - * - *

- * This method is not type-safe, as it may be called on elements that are not - * mutually comparable. - * - * @throws ClassCastException if the elements are not mutually comparable - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableSortedMultiset copyOf(Iterator elements) { - // Hack around E not being a subtype of Comparable. - // Unsafe, see ImmutableSortedMultisetFauxverideShim. - @SuppressWarnings("unchecked") - Ordering naturalOrder = (Ordering) Ordering.natural(); - return copyOf(naturalOrder, elements); - } - - /** - * Returns an immutable sorted multiset containing the given elements sorted by - * the given {@code - * Comparator}. - * - * @throws NullPointerException if {@code comparator} or any of {@code elements} - * is null - */ - public static ImmutableSortedMultiset copyOf(Comparator comparator, - Iterator elements) { - checkNotNull(comparator); - return new Builder(comparator).addAll(elements).build(); - } - - /** - * Returns an immutable sorted multiset containing the given elements sorted by - * the given {@code - * Comparator}. This method iterates over {@code elements} at most once. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if {@code comparator} or any of {@code elements} - * is null - */ - public static ImmutableSortedMultiset copyOf(Comparator comparator, - Iterable elements) { - if (elements instanceof ImmutableSortedMultiset) { - @SuppressWarnings("unchecked") // immutable collections are always safe for covariant casts - ImmutableSortedMultiset multiset = (ImmutableSortedMultiset) elements; - if (comparator.equals(multiset.comparator())) { - if (multiset.isPartialView()) { - return copyOfSortedEntries(comparator, multiset.entrySet().asList()); - } else { - return multiset; - } - } - } - elements = Lists.newArrayList(elements); // defensive copy - TreeMultiset sortedCopy = TreeMultiset.create(checkNotNull(comparator)); - Iterables.addAll(sortedCopy, elements); - return copyOfSortedEntries(comparator, sortedCopy.entrySet()); - } - - /** - * Returns an immutable sorted multiset containing the elements of a sorted - * multiset, sorted by the same {@code Comparator}. That behavior differs from - * {@link #copyOf(Iterable)}, which always uses the natural ordering of the - * elements. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * This method is safe to use even when {@code sortedMultiset} is a synchronized - * or concurrent collection that is currently being modified by another thread. - * - * @throws NullPointerException if {@code sortedMultiset} or any of its elements - * is null - */ - public static ImmutableSortedMultiset copyOfSorted(SortedMultiset sortedMultiset) { - return copyOfSortedEntries(sortedMultiset.comparator(), Lists.newArrayList(sortedMultiset.entrySet())); - } - - private static ImmutableSortedMultiset copyOfSortedEntries(Comparator comparator, - Collection> entries) { - if (entries.isEmpty()) { - return emptyMultiset(comparator); - } - ImmutableList.Builder elementsBuilder = new ImmutableList.Builder(entries.size()); - int[] counts = new int[entries.size()]; - long[] cumulativeCounts = new long[entries.size() + 1]; - int i = 0; - for (Entry entry : entries) { - elementsBuilder.add(entry.getElement()); - counts[i] = entry.getCount(); - cumulativeCounts[i + 1] = cumulativeCounts[i] + counts[i]; - i++; - } - return new RegularImmutableSortedMultiset( - new RegularImmutableSortedSet(elementsBuilder.build(), comparator), counts, cumulativeCounts, 0, - entries.size()); - } - - @SuppressWarnings("unchecked") - static ImmutableSortedMultiset emptyMultiset(Comparator comparator) { - if (NATURAL_ORDER.equals(comparator)) { - return (ImmutableSortedMultiset) NATURAL_EMPTY_MULTISET; - } - return new EmptyImmutableSortedMultiset(comparator); - } + transient ImmutableSortedMultiset descendingMultiset; ImmutableSortedMultiset() { } @@ -348,11 +557,6 @@ public abstract class ImmutableSortedMultiset extends ImmutableSortedMultiset return elementSet().comparator(); } - @Override - public abstract ImmutableSortedSet elementSet(); - - transient ImmutableSortedMultiset descendingMultiset; - @Override public ImmutableSortedMultiset descendingMultiset() { ImmutableSortedMultiset result = descendingMultiset; @@ -362,6 +566,12 @@ public abstract class ImmutableSortedMultiset extends ImmutableSortedMultiset return result; } + @Override + public abstract ImmutableSortedSet elementSet(); + + @Override + public abstract ImmutableSortedMultiset headMultiset(E upperBound, BoundType boundType); + /** * {@inheritDoc} * @@ -394,9 +604,6 @@ public abstract class ImmutableSortedMultiset extends ImmutableSortedMultiset throw new UnsupportedOperationException(); } - @Override - public abstract ImmutableSortedMultiset headMultiset(E upperBound, BoundType boundType); - @Override public ImmutableSortedMultiset subMultiset(E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { @@ -408,213 +615,6 @@ public abstract class ImmutableSortedMultiset extends ImmutableSortedMultiset @Override public abstract ImmutableSortedMultiset tailMultiset(E lowerBound, BoundType boundType); - /** - * Returns a builder that creates immutable sorted multisets with an explicit - * comparator. If the comparator has a more general type than the set being - * generated, such as creating a {@code - * SortedMultiset} with a {@code Comparator}, use the - * {@link Builder} constructor instead. - * - * @throws NullPointerException if {@code comparator} is null - */ - public static Builder orderedBy(Comparator comparator) { - return new Builder(comparator); - } - - /** - * Returns a builder that creates immutable sorted multisets whose elements are - * ordered by the reverse of their natural ordering. - * - *

- * Note: the type parameter {@code E} extends {@code Comparable} rather than - * {@code - * Comparable} as a workaround for javac - * bug - * 6468354. - */ - public static > Builder reverseOrder() { - return new Builder(Ordering.natural().reverse()); - } - - /** - * Returns a builder that creates immutable sorted multisets whose elements are - * ordered by their natural ordering. The sorted multisets use - * {@link Ordering#natural()} as the comparator. This method provides more - * type-safety than {@link #builder}, as it can be called only for classes that - * implement {@link Comparable}. - * - *

- * Note: the type parameter {@code E} extends {@code Comparable} rather than - * {@code - * Comparable} as a workaround for javac - * bug - * 6468354. - */ - public static > Builder naturalOrder() { - return new Builder(Ordering.natural()); - } - - /** - * A builder for creating immutable multiset instances, especially - * {@code public static final} multisets ("constant multisets"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	public static final ImmutableSortedMultiset BEANS = new ImmutableSortedMultiset.Builder()
-	 * 			.addCopies(Bean.COCOA, 4).addCopies(Bean.GARDEN, 6).addCopies(Bean.RED, 8).addCopies(Bean.BLACK_EYED, 10)
-	 * 			.build();
-	 * }
-	 * 
- * - *

- * Builder instances can be reused; it is safe to call {@link #build} multiple - * times to build multiple multisets in series. - * - * @since 12.0 - */ - public static class Builder extends ImmutableMultiset.Builder { - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableSortedMultiset#orderedBy(Comparator)}. - */ - public Builder(Comparator comparator) { - super(TreeMultiset.create(checkNotNull(comparator))); - } - - /** - * Adds {@code element} to the {@code ImmutableSortedMultiset}. - * - * @param element the element to add - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - */ - @Override - public Builder add(E element) { - super.add(element); - return this; - } - - /** - * Adds a number of occurrences of an element to this - * {@code ImmutableSortedMultiset}. - * - * @param element the element to add - * @param occurrences the number of occurrences of the element to add. May be - * zero, in which case no change will be made. - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - * @throws IllegalArgumentException if {@code occurrences} is negative, or if - * this operation would result in more than - * {@link Integer#MAX_VALUE} occurrences of the - * element - */ - @Override - public Builder addCopies(E element, int occurrences) { - super.addCopies(element, occurrences); - return this; - } - - /** - * Adds or removes the necessary occurrences of an element such that the element - * attains the desired count. - * - * @param element the element to add or remove occurrences of - * @param count the desired count of the element in this multiset - * @return this {@code Builder} object - * @throws NullPointerException if {@code element} is null - * @throws IllegalArgumentException if {@code count} is negative - */ - @Override - public Builder setCount(E element, int count) { - super.setCount(element, count); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. - * - * @param elements the elements to add - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder add(E... elements) { - super.add(elements); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. - * - * @param elements the {@code Iterable} to add to the - * {@code ImmutableSortedMultiset} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder addAll(Iterable elements) { - super.addAll(elements); - return this; - } - - /** - * Adds each element of {@code elements} to the {@code ImmutableSortedMultiset}. - * - * @param elements the elements to add to the {@code ImmutableSortedMultiset} - * @return this {@code Builder} object - * @throws NullPointerException if {@code elements} is null or contains a null - * element - */ - @Override - public Builder addAll(Iterator elements) { - super.addAll(elements); - return this; - } - - /** - * Returns a newly-created {@code ImmutableSortedMultiset} based on the contents - * of the {@code - * Builder}. - */ - @Override - public ImmutableSortedMultiset build() { - return copyOfSorted((SortedMultiset) contents); - } - } - - private static final class SerializedForm implements Serializable { - Comparator comparator; - E[] elements; - int[] counts; - - @SuppressWarnings("unchecked") - SerializedForm(SortedMultiset multiset) { - this.comparator = multiset.comparator(); - int n = multiset.entrySet().size(); - elements = (E[]) new Object[n]; - counts = new int[n]; - int i = 0; - for (Entry entry : multiset.entrySet()) { - elements[i] = entry.getElement(); - counts[i] = entry.getCount(); - i++; - } - } - - Object readResolve() { - int n = elements.length; - Builder builder = new Builder(comparator); - for (int i = 0; i < n; i++) { - builder.addCopies(elements[i], counts[i]); - } - return builder.build(); - } - } - @Override Object writeReplace() { return new SerializedForm(this); diff --git a/src/main/java/com/google/common/collect/ImmutableSortedMultisetFauxverideShim.java b/src/main/java/com/google/common/collect/ImmutableSortedMultisetFauxverideShim.java index 57a43466..a705e498 100644 --- a/src/main/java/com/google/common/collect/ImmutableSortedMultisetFauxverideShim.java +++ b/src/main/java/com/google/common/collect/ImmutableSortedMultisetFauxverideShim.java @@ -51,6 +51,21 @@ abstract class ImmutableSortedMultisetFauxverideShim extends ImmutableMultise throw new UnsupportedOperationException(); } + /** + * Not supported. You are attempting to create a multiset that may contain + * non-{@code + * Comparable} elements. Proper calls will resolve to the version in {@code + * ImmutableSortedMultiset}, not this dummy version. + * + * @throws UnsupportedOperationException always + * @deprecated Pass parameters of type {@code Comparable} to use + * {@link ImmutableSortedMultiset#copyOf(Comparable[])}. + */ + @Deprecated + public static ImmutableSortedMultiset copyOf(E[] elements) { + throw new UnsupportedOperationException(); + } + /** * Not supported. You are attempting to create a multiset that may contain a * non-{@code @@ -144,21 +159,6 @@ abstract class ImmutableSortedMultisetFauxverideShim extends ImmutableMultise throw new UnsupportedOperationException(); } - /** - * Not supported. You are attempting to create a multiset that may contain - * non-{@code - * Comparable} elements. Proper calls will resolve to the version in {@code - * ImmutableSortedMultiset}, not this dummy version. - * - * @throws UnsupportedOperationException always - * @deprecated Pass parameters of type {@code Comparable} to use - * {@link ImmutableSortedMultiset#copyOf(Comparable[])}. - */ - @Deprecated - public static ImmutableSortedMultiset copyOf(E[] elements) { - throw new UnsupportedOperationException(); - } - /* * We would like to include an unsupported " copyOf(Iterable)" here, * providing only the properly typed diff --git a/src/main/java/com/google/common/collect/ImmutableSortedSet.java b/src/main/java/com/google/common/collect/ImmutableSortedSet.java index e90b1999..57d76f4e 100644 --- a/src/main/java/com/google/common/collect/ImmutableSortedSet.java +++ b/src/main/java/com/google/common/collect/ImmutableSortedSet.java @@ -108,374 +108,6 @@ import com.google.common.annotations.GwtIncompatible; public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxverideShim implements NavigableSet, SortedIterable { - private static final Comparator NATURAL_ORDER = Ordering.natural(); - - private static final ImmutableSortedSet NATURAL_EMPTY_SET = new EmptyImmutableSortedSet( - NATURAL_ORDER); - - @SuppressWarnings("unchecked") - private static ImmutableSortedSet emptySet() { - return (ImmutableSortedSet) NATURAL_EMPTY_SET; - } - - static ImmutableSortedSet emptySet(Comparator comparator) { - if (NATURAL_ORDER.equals(comparator)) { - return emptySet(); - } else { - return new EmptyImmutableSortedSet(comparator); - } - } - - /** - * Returns the empty immutable sorted set. - */ - public static ImmutableSortedSet of() { - return emptySet(); - } - - /** - * Returns an immutable sorted set containing a single element. - */ - public static > ImmutableSortedSet of(E element) { - return new RegularImmutableSortedSet(ImmutableList.of(element), Ordering.natural()); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@link Comparable#compareTo}, only the first one specified is included. - * - * @throws NullPointerException if any element is null - */ - @SuppressWarnings("unchecked") - public static > ImmutableSortedSet of(E e1, E e2) { - return construct(Ordering.natural(), 2, e1, e2); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@link Comparable#compareTo}, only the first one specified is included. - * - * @throws NullPointerException if any element is null - */ - @SuppressWarnings("unchecked") - public static > ImmutableSortedSet of(E e1, E e2, E e3) { - return construct(Ordering.natural(), 3, e1, e2, e3); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@link Comparable#compareTo}, only the first one specified is included. - * - * @throws NullPointerException if any element is null - */ - @SuppressWarnings("unchecked") - public static > ImmutableSortedSet of(E e1, E e2, E e3, E e4) { - return construct(Ordering.natural(), 4, e1, e2, e3, e4); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@link Comparable#compareTo}, only the first one specified is included. - * - * @throws NullPointerException if any element is null - */ - @SuppressWarnings("unchecked") - public static > ImmutableSortedSet of(E e1, E e2, E e3, E e4, E e5) { - return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@link Comparable#compareTo}, only the first one specified is included. - * - * @throws NullPointerException if any element is null - * @since 3.0 (source-compatible since 2.0) - */ - @SuppressWarnings("unchecked") - public static > ImmutableSortedSet of(E e1, E e2, E e3, E e4, E e5, E e6, - E... remaining) { - Comparable[] contents = new Comparable[6 + remaining.length]; - contents[0] = e1; - contents[1] = e2; - contents[2] = e3; - contents[3] = e4; - contents[4] = e5; - contents[5] = e6; - System.arraycopy(remaining, 0, contents, 6, remaining.length); - return construct(Ordering.natural(), contents.length, (E[]) contents); - } - - // TODO(kevinb): Consider factory methods that reject duplicates - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@link Comparable#compareTo}, only the first one specified is included. - * - * @throws NullPointerException if any of {@code elements} is null - * @since 3.0 - */ - public static > ImmutableSortedSet copyOf(E[] elements) { - return construct(Ordering.natural(), elements.length, elements.clone()); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@code compareTo()}, only the first one specified is included. To create a - * copy of a {@code SortedSet} that preserves the comparator, call - * {@link #copyOfSorted} instead. This method iterates over {@code elements} at - * most once. - * - * - *

- * Note that if {@code s} is a {@code Set}, then {@code - * ImmutableSortedSet.copyOf(s)} returns an {@code ImmutableSortedSet} - * containing each of the strings in {@code s}, while {@code - * ImmutableSortedSet.of(s)} returns an {@code - * ImmutableSortedSet>} containing one element (the given set - * itself). - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * This method is not type-safe, as it may be called on elements that are not - * mutually comparable. - * - * @throws ClassCastException if the elements are not mutually comparable - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableSortedSet copyOf(Iterable elements) { - // Hack around E not being a subtype of Comparable. - // Unsafe, see ImmutableSortedSetFauxverideShim. - @SuppressWarnings("unchecked") - Ordering naturalOrder = (Ordering) Ordering.natural(); - return copyOf(naturalOrder, elements); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@code compareTo()}, only the first one specified is included. To create a - * copy of a {@code SortedSet} that preserves the comparator, call - * {@link #copyOfSorted} instead. This method iterates over {@code elements} at - * most once. - * - *

- * Note that if {@code s} is a {@code Set}, then - * {@code ImmutableSortedSet.copyOf(s)} returns an - * {@code ImmutableSortedSet} containing each of the strings in - * {@code s}, while {@code ImmutableSortedSet.of(s)} returns an - * {@code ImmutableSortedSet>} containing one element (the given set - * itself). - * - *

- * Note: Despite what the method name suggests, if {@code elements} is an - * {@code ImmutableSortedSet}, it may be returned instead of a copy. - * - *

- * This method is not type-safe, as it may be called on elements that are not - * mutually comparable. - * - *

- * This method is safe to use even when {@code elements} is a synchronized or - * concurrent collection that is currently being modified by another thread. - * - * @throws ClassCastException if the elements are not mutually comparable - * @throws NullPointerException if any of {@code elements} is null - * @since 7.0 (source-compatible since 2.0) - */ - public static ImmutableSortedSet copyOf(Collection elements) { - // Hack around E not being a subtype of Comparable. - // Unsafe, see ImmutableSortedSetFauxverideShim. - @SuppressWarnings("unchecked") - Ordering naturalOrder = (Ordering) Ordering.natural(); - return copyOf(naturalOrder, elements); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by their - * natural ordering. When multiple elements are equivalent according to - * {@code compareTo()}, only the first one specified is included. - * - *

- * This method is not type-safe, as it may be called on elements that are not - * mutually comparable. - * - * @throws ClassCastException if the elements are not mutually comparable - * @throws NullPointerException if any of {@code elements} is null - */ - public static ImmutableSortedSet copyOf(Iterator elements) { - // Hack around E not being a subtype of Comparable. - // Unsafe, see ImmutableSortedSetFauxverideShim. - @SuppressWarnings("unchecked") - Ordering naturalOrder = (Ordering) Ordering.natural(); - return copyOf(naturalOrder, elements); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by the - * given {@code Comparator}. When multiple elements are equivalent according to - * {@code compareTo()}, only the first one specified is included. - * - * @throws NullPointerException if {@code comparator} or any of {@code elements} - * is null - */ - public static ImmutableSortedSet copyOf(Comparator comparator, Iterator elements) { - return new Builder(comparator).addAll(elements).build(); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by the - * given {@code Comparator}. When multiple elements are equivalent according to - * {@code compare()}, only the first one specified is included. This method - * iterates over {@code elements} at most once. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - * @throws NullPointerException if {@code comparator} or any of {@code - * elements} is null - */ - public static ImmutableSortedSet copyOf(Comparator comparator, Iterable elements) { - checkNotNull(comparator); - boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements); - - if (hasSameComparator && (elements instanceof ImmutableSortedSet)) { - @SuppressWarnings("unchecked") - ImmutableSortedSet original = (ImmutableSortedSet) elements; - if (!original.isPartialView()) { - return original; - } - } - @SuppressWarnings("unchecked") // elements only contains E's; it's safe. - E[] array = (E[]) Iterables.toArray(elements); - return construct(comparator, array.length, array); - } - - /** - * Returns an immutable sorted set containing the given elements sorted by the - * given {@code Comparator}. When multiple elements are equivalent according to - * {@code compareTo()}, only the first one specified is included. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * This method is safe to use even when {@code elements} is a synchronized or - * concurrent collection that is currently being modified by another thread. - * - * @throws NullPointerException if {@code comparator} or any of {@code elements} - * is null - * @since 7.0 (source-compatible since 2.0) - */ - public static ImmutableSortedSet copyOf(Comparator comparator, Collection elements) { - return copyOf(comparator, (Iterable) elements); - } - - /** - * Returns an immutable sorted set containing the elements of a sorted set, - * sorted by the same {@code Comparator}. That behavior differs from - * {@link #copyOf(Iterable)}, which always uses the natural ordering of the - * elements. - * - *

- * Despite the method name, this method attempts to avoid actually copying the - * data when it is safe to do so. The exact circumstances under which a copy - * will or will not be performed are undocumented and subject to change. - * - *

- * This method is safe to use even when {@code sortedSet} is a synchronized or - * concurrent collection that is currently being modified by another thread. - * - * @throws NullPointerException if {@code sortedSet} or any of its elements is - * null - */ - public static ImmutableSortedSet copyOfSorted(SortedSet sortedSet) { - Comparator comparator = SortedIterables.comparator(sortedSet); - ImmutableList list = ImmutableList.copyOf(sortedSet); - if (list.isEmpty()) { - return emptySet(comparator); - } else { - return new RegularImmutableSortedSet(list, comparator); - } - } - - /** - * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of - * {@code contents}. If {@code k} is the size of the returned - * {@code ImmutableSortedSet}, then the sorted unique elements are in the first - * {@code k} positions of {@code contents}, and {@code contents[i] == null} for - * {@code k <= i < n}. - * - *

- * If {@code k == contents.length}, then {@code contents} may no longer be safe - * for modification. - * - * @throws NullPointerException if any of the first {@code n} elements of - * {@code contents} is null - */ - static ImmutableSortedSet construct(Comparator comparator, int n, E... contents) { - if (n == 0) { - return emptySet(comparator); - } - checkElementsNotNull(contents, n); - Arrays.sort(contents, 0, n, comparator); - int uniques = 1; - for (int i = 1; i < n; i++) { - E cur = contents[i]; - E prev = contents[uniques - 1]; - if (comparator.compare(cur, prev) != 0) { - contents[uniques++] = cur; - } - } - Arrays.fill(contents, uniques, n, null); - return new RegularImmutableSortedSet(ImmutableList.asImmutableList(contents, uniques), comparator); - } - - /** - * Returns a builder that creates immutable sorted sets with an explicit - * comparator. If the comparator has a more general type than the set being - * generated, such as creating a {@code SortedSet} with a - * {@code Comparator}, use the {@link Builder} constructor instead. - * - * @throws NullPointerException if {@code comparator} is null - */ - public static Builder orderedBy(Comparator comparator) { - return new Builder(comparator); - } - - /** - * Returns a builder that creates immutable sorted sets whose elements are - * ordered by the reverse of their natural ordering. - */ - public static > Builder reverseOrder() { - return new Builder(Ordering.natural().reverse()); - } - - /** - * Returns a builder that creates immutable sorted sets whose elements are - * ordered by their natural ordering. The sorted sets use - * {@link Ordering#natural()} as the comparator. This method provides more - * type-safety than {@link #builder}, as it can be called only for classes that - * implement {@link Comparable}. - */ - public static > Builder naturalOrder() { - return new Builder(Ordering.natural()); - } - /** * A builder for creating immutable sorted set instances, especially {@code * public static final} sets ("constant sets"), with a given comparator. @@ -579,8 +211,395 @@ public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxveride } } - int unsafeCompare(Object a, Object b) { - return unsafeCompare(comparator, a, b); + /* + * This class is used to serialize all ImmutableSortedSet instances, regardless + * of implementation type. It captures their "logical contents" only. This is + * necessary to ensure that the existence of a particular implementation type is + * an implementation detail. + */ + private static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + final Comparator comparator; + + final Object[] elements; + + public SerializedForm(Comparator comparator, Object[] elements) { + this.comparator = comparator; + this.elements = elements; + } + + @SuppressWarnings("unchecked") + Object readResolve() { + return new Builder(comparator).add((E[]) elements).build(); + } + } + + private static final Comparator NATURAL_ORDER = Ordering.natural(); + + private static final ImmutableSortedSet NATURAL_EMPTY_SET = new EmptyImmutableSortedSet( + NATURAL_ORDER); + + /** + * Constructs an {@code ImmutableSortedSet} from the first {@code n} elements of + * {@code contents}. If {@code k} is the size of the returned + * {@code ImmutableSortedSet}, then the sorted unique elements are in the first + * {@code k} positions of {@code contents}, and {@code contents[i] == null} for + * {@code k <= i < n}. + * + *

+ * If {@code k == contents.length}, then {@code contents} may no longer be safe + * for modification. + * + * @throws NullPointerException if any of the first {@code n} elements of + * {@code contents} is null + */ + static ImmutableSortedSet construct(Comparator comparator, int n, E... contents) { + if (n == 0) { + return emptySet(comparator); + } + checkElementsNotNull(contents, n); + Arrays.sort(contents, 0, n, comparator); + int uniques = 1; + for (int i = 1; i < n; i++) { + E cur = contents[i]; + E prev = contents[uniques - 1]; + if (comparator.compare(cur, prev) != 0) { + contents[uniques++] = cur; + } + } + Arrays.fill(contents, uniques, n, null); + return new RegularImmutableSortedSet(ImmutableList.asImmutableList(contents, uniques), comparator); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@code compareTo()}, only the first one specified is included. To create a + * copy of a {@code SortedSet} that preserves the comparator, call + * {@link #copyOfSorted} instead. This method iterates over {@code elements} at + * most once. + * + *

+ * Note that if {@code s} is a {@code Set}, then + * {@code ImmutableSortedSet.copyOf(s)} returns an + * {@code ImmutableSortedSet} containing each of the strings in + * {@code s}, while {@code ImmutableSortedSet.of(s)} returns an + * {@code ImmutableSortedSet>} containing one element (the given set + * itself). + * + *

+ * Note: Despite what the method name suggests, if {@code elements} is an + * {@code ImmutableSortedSet}, it may be returned instead of a copy. + * + *

+ * This method is not type-safe, as it may be called on elements that are not + * mutually comparable. + * + *

+ * This method is safe to use even when {@code elements} is a synchronized or + * concurrent collection that is currently being modified by another thread. + * + * @throws ClassCastException if the elements are not mutually comparable + * @throws NullPointerException if any of {@code elements} is null + * @since 7.0 (source-compatible since 2.0) + */ + public static ImmutableSortedSet copyOf(Collection elements) { + // Hack around E not being a subtype of Comparable. + // Unsafe, see ImmutableSortedSetFauxverideShim. + @SuppressWarnings("unchecked") + Ordering naturalOrder = (Ordering) Ordering.natural(); + return copyOf(naturalOrder, elements); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by the + * given {@code Comparator}. When multiple elements are equivalent according to + * {@code compareTo()}, only the first one specified is included. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * This method is safe to use even when {@code elements} is a synchronized or + * concurrent collection that is currently being modified by another thread. + * + * @throws NullPointerException if {@code comparator} or any of {@code elements} + * is null + * @since 7.0 (source-compatible since 2.0) + */ + public static ImmutableSortedSet copyOf(Comparator comparator, Collection elements) { + return copyOf(comparator, (Iterable) elements); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by the + * given {@code Comparator}. When multiple elements are equivalent according to + * {@code compare()}, only the first one specified is included. This method + * iterates over {@code elements} at most once. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + * @throws NullPointerException if {@code comparator} or any of {@code + * elements} is null + */ + public static ImmutableSortedSet copyOf(Comparator comparator, Iterable elements) { + checkNotNull(comparator); + boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements); + + if (hasSameComparator && (elements instanceof ImmutableSortedSet)) { + @SuppressWarnings("unchecked") + ImmutableSortedSet original = (ImmutableSortedSet) elements; + if (!original.isPartialView()) { + return original; + } + } + @SuppressWarnings("unchecked") // elements only contains E's; it's safe. + E[] array = (E[]) Iterables.toArray(elements); + return construct(comparator, array.length, array); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by the + * given {@code Comparator}. When multiple elements are equivalent according to + * {@code compareTo()}, only the first one specified is included. + * + * @throws NullPointerException if {@code comparator} or any of {@code elements} + * is null + */ + public static ImmutableSortedSet copyOf(Comparator comparator, Iterator elements) { + return new Builder(comparator).addAll(elements).build(); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@link Comparable#compareTo}, only the first one specified is included. + * + * @throws NullPointerException if any of {@code elements} is null + * @since 3.0 + */ + public static > ImmutableSortedSet copyOf(E[] elements) { + return construct(Ordering.natural(), elements.length, elements.clone()); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@code compareTo()}, only the first one specified is included. To create a + * copy of a {@code SortedSet} that preserves the comparator, call + * {@link #copyOfSorted} instead. This method iterates over {@code elements} at + * most once. + * + * + *

+ * Note that if {@code s} is a {@code Set}, then {@code + * ImmutableSortedSet.copyOf(s)} returns an {@code ImmutableSortedSet} + * containing each of the strings in {@code s}, while {@code + * ImmutableSortedSet.of(s)} returns an {@code + * ImmutableSortedSet>} containing one element (the given set + * itself). + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * This method is not type-safe, as it may be called on elements that are not + * mutually comparable. + * + * @throws ClassCastException if the elements are not mutually comparable + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableSortedSet copyOf(Iterable elements) { + // Hack around E not being a subtype of Comparable. + // Unsafe, see ImmutableSortedSetFauxverideShim. + @SuppressWarnings("unchecked") + Ordering naturalOrder = (Ordering) Ordering.natural(); + return copyOf(naturalOrder, elements); + } + + // TODO(kevinb): Consider factory methods that reject duplicates + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@code compareTo()}, only the first one specified is included. + * + *

+ * This method is not type-safe, as it may be called on elements that are not + * mutually comparable. + * + * @throws ClassCastException if the elements are not mutually comparable + * @throws NullPointerException if any of {@code elements} is null + */ + public static ImmutableSortedSet copyOf(Iterator elements) { + // Hack around E not being a subtype of Comparable. + // Unsafe, see ImmutableSortedSetFauxverideShim. + @SuppressWarnings("unchecked") + Ordering naturalOrder = (Ordering) Ordering.natural(); + return copyOf(naturalOrder, elements); + } + + /** + * Returns an immutable sorted set containing the elements of a sorted set, + * sorted by the same {@code Comparator}. That behavior differs from + * {@link #copyOf(Iterable)}, which always uses the natural ordering of the + * elements. + * + *

+ * Despite the method name, this method attempts to avoid actually copying the + * data when it is safe to do so. The exact circumstances under which a copy + * will or will not be performed are undocumented and subject to change. + * + *

+ * This method is safe to use even when {@code sortedSet} is a synchronized or + * concurrent collection that is currently being modified by another thread. + * + * @throws NullPointerException if {@code sortedSet} or any of its elements is + * null + */ + public static ImmutableSortedSet copyOfSorted(SortedSet sortedSet) { + Comparator comparator = SortedIterables.comparator(sortedSet); + ImmutableList list = ImmutableList.copyOf(sortedSet); + if (list.isEmpty()) { + return emptySet(comparator); + } else { + return new RegularImmutableSortedSet(list, comparator); + } + } + + @SuppressWarnings("unchecked") + private static ImmutableSortedSet emptySet() { + return (ImmutableSortedSet) NATURAL_EMPTY_SET; + } + + static ImmutableSortedSet emptySet(Comparator comparator) { + if (NATURAL_ORDER.equals(comparator)) { + return emptySet(); + } else { + return new EmptyImmutableSortedSet(comparator); + } + } + + /** + * Returns a builder that creates immutable sorted sets whose elements are + * ordered by their natural ordering. The sorted sets use + * {@link Ordering#natural()} as the comparator. This method provides more + * type-safety than {@link #builder}, as it can be called only for classes that + * implement {@link Comparable}. + */ + public static > Builder naturalOrder() { + return new Builder(Ordering.natural()); + } + + /** + * Returns the empty immutable sorted set. + */ + public static ImmutableSortedSet of() { + return emptySet(); + } + + /** + * Returns an immutable sorted set containing a single element. + */ + public static > ImmutableSortedSet of(E element) { + return new RegularImmutableSortedSet(ImmutableList.of(element), Ordering.natural()); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@link Comparable#compareTo}, only the first one specified is included. + * + * @throws NullPointerException if any element is null + */ + @SuppressWarnings("unchecked") + public static > ImmutableSortedSet of(E e1, E e2) { + return construct(Ordering.natural(), 2, e1, e2); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@link Comparable#compareTo}, only the first one specified is included. + * + * @throws NullPointerException if any element is null + */ + @SuppressWarnings("unchecked") + public static > ImmutableSortedSet of(E e1, E e2, E e3) { + return construct(Ordering.natural(), 3, e1, e2, e3); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@link Comparable#compareTo}, only the first one specified is included. + * + * @throws NullPointerException if any element is null + */ + @SuppressWarnings("unchecked") + public static > ImmutableSortedSet of(E e1, E e2, E e3, E e4) { + return construct(Ordering.natural(), 4, e1, e2, e3, e4); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@link Comparable#compareTo}, only the first one specified is included. + * + * @throws NullPointerException if any element is null + */ + @SuppressWarnings("unchecked") + public static > ImmutableSortedSet of(E e1, E e2, E e3, E e4, E e5) { + return construct(Ordering.natural(), 5, e1, e2, e3, e4, e5); + } + + /** + * Returns an immutable sorted set containing the given elements sorted by their + * natural ordering. When multiple elements are equivalent according to + * {@link Comparable#compareTo}, only the first one specified is included. + * + * @throws NullPointerException if any element is null + * @since 3.0 (source-compatible since 2.0) + */ + @SuppressWarnings("unchecked") + public static > ImmutableSortedSet of(E e1, E e2, E e3, E e4, E e5, E e6, + E... remaining) { + Comparable[] contents = new Comparable[6 + remaining.length]; + contents[0] = e1; + contents[1] = e2; + contents[2] = e3; + contents[3] = e4; + contents[4] = e5; + contents[5] = e6; + System.arraycopy(remaining, 0, contents, 6, remaining.length); + return construct(Ordering.natural(), contents.length, (E[]) contents); + } + + /** + * Returns a builder that creates immutable sorted sets with an explicit + * comparator. If the comparator has a more general type than the set being + * generated, such as creating a {@code SortedSet} with a + * {@code Comparator}, use the {@link Builder} constructor instead. + * + * @throws NullPointerException if {@code comparator} is null + */ + public static Builder orderedBy(Comparator comparator) { + return new Builder(comparator); + } + + /** + * Returns a builder that creates immutable sorted sets whose elements are + * ordered by the reverse of their natural ordering. + */ + public static > Builder reverseOrder() { + return new Builder(Ordering.natural().reverse()); } static int unsafeCompare(Comparator comparator, Object a, Object b) { @@ -594,10 +613,22 @@ public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxveride final transient Comparator comparator; + @GwtIncompatible("NavigableSet") + transient ImmutableSortedSet descendingSet; + ImmutableSortedSet(Comparator comparator) { this.comparator = comparator; } + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public E ceiling(E e) { + return Iterables.getFirst(tailSet(e, true), null); + } + /** * Returns the comparator that orders the elements, which is * {@link Ordering#natural()} when the natural ordering of the elements is used. @@ -609,8 +640,46 @@ public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxveride return comparator; } - @Override // needed to unify the iterator() methods in Collection and SortedIterable - public abstract UnmodifiableIterator iterator(); + @GwtIncompatible("NavigableSet") + ImmutableSortedSet createDescendingSet() { + return new DescendingImmutableSortedSet(this); + } + + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public abstract UnmodifiableIterator descendingIterator(); + + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public ImmutableSortedSet descendingSet() { + // racy single-check idiom + ImmutableSortedSet result = descendingSet; + if (result == null) { + result = descendingSet = createDescendingSet(); + result.descendingSet = this; + } + return result; + } + + @Override + public E first() { + return iterator().next(); + } + + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public E floor(E e) { + return Iterators.getNext(headSet(e, true).descendingIterator(), null); + } /** * {@inheritDoc} @@ -639,102 +708,12 @@ public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxveride return headSetImpl(checkNotNull(toElement), inclusive); } - /** - * {@inheritDoc} - * - *

- * This method returns a serializable {@code ImmutableSortedSet}. - * - *

- * The {@link SortedSet#subSet} documentation states that a subset of a subset - * throws an {@link IllegalArgumentException} if passed a {@code fromElement} - * smaller than an earlier {@code fromElement}. However, this method doesn't - * throw an exception in that situation, but instead keeps the original - * {@code fromElement}. Similarly, this method keeps the original - * {@code toElement}, instead of throwing an exception, if passed a - * {@code toElement} greater than an earlier {@code toElement}. - */ - @Override - public ImmutableSortedSet subSet(E fromElement, E toElement) { - return subSet(fromElement, true, toElement, false); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public ImmutableSortedSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - checkNotNull(fromElement); - checkNotNull(toElement); - checkArgument(comparator.compare(fromElement, toElement) <= 0); - return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); - } - - /** - * {@inheritDoc} - * - *

- * This method returns a serializable {@code ImmutableSortedSet}. - * - *

- * The {@link SortedSet#tailSet} documentation states that a subset of a subset - * throws an {@link IllegalArgumentException} if passed a {@code fromElement} - * smaller than an earlier {@code fromElement}. However, this method doesn't - * throw an exception in that situation, but instead keeps the original - * {@code fromElement}. - */ - @Override - public ImmutableSortedSet tailSet(E fromElement) { - return tailSet(fromElement, true); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public ImmutableSortedSet tailSet(E fromElement, boolean inclusive) { - return tailSetImpl(checkNotNull(fromElement), inclusive); - } - /* * These methods perform most headSet, subSet, and tailSet logic, besides * parameter validation. */ abstract ImmutableSortedSet headSetImpl(E toElement, boolean inclusive); - abstract ImmutableSortedSet subSetImpl(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive); - - abstract ImmutableSortedSet tailSetImpl(E fromElement, boolean inclusive); - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public E lower(E e) { - return Iterators.getNext(headSet(e, false).descendingIterator(), null); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public E floor(E e) { - return Iterators.getNext(headSet(e, true).descendingIterator(), null); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public E ceiling(E e) { - return Iterables.getFirst(tailSet(e, true), null); - } - /** * @since 12.0 */ @@ -744,16 +723,28 @@ public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxveride return Iterables.getFirst(tailSet(e, false), null); } - @Override - public E first() { - return iterator().next(); - } + /** + * Returns the position of an element within the set, or -1 if not present. + */ + abstract int indexOf(@Nullable Object target); + + @Override // needed to unify the iterator() methods in Collection and SortedIterable + public abstract UnmodifiableIterator iterator(); @Override public E last() { return descendingIterator().next(); } + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public E lower(E e) { + return Iterators.getNext(headSet(e, false).descendingIterator(), null); + } + /** * Guaranteed to throw an exception and leave the set unmodified. * @@ -782,68 +773,77 @@ public abstract class ImmutableSortedSet extends ImmutableSortedSetFauxveride throw new UnsupportedOperationException(); } - @GwtIncompatible("NavigableSet") - transient ImmutableSortedSet descendingSet; - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public ImmutableSortedSet descendingSet() { - // racy single-check idiom - ImmutableSortedSet result = descendingSet; - if (result == null) { - result = descendingSet = createDescendingSet(); - result.descendingSet = this; - } - return result; - } - - @GwtIncompatible("NavigableSet") - ImmutableSortedSet createDescendingSet() { - return new DescendingImmutableSortedSet(this); - } - - /** - * @since 12.0 - */ - @GwtIncompatible("NavigableSet") - @Override - public abstract UnmodifiableIterator descendingIterator(); - - /** - * Returns the position of an element within the set, or -1 if not present. - */ - abstract int indexOf(@Nullable Object target); - - /* - * This class is used to serialize all ImmutableSortedSet instances, regardless - * of implementation type. It captures their "logical contents" only. This is - * necessary to ensure that the existence of a particular implementation type is - * an implementation detail. - */ - private static class SerializedForm implements Serializable { - final Comparator comparator; - final Object[] elements; - - public SerializedForm(Comparator comparator, Object[] elements) { - this.comparator = comparator; - this.elements = elements; - } - - @SuppressWarnings("unchecked") - Object readResolve() { - return new Builder(comparator).add((E[]) elements).build(); - } - - private static final long serialVersionUID = 0; - } - private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Use SerializedForm"); } + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public ImmutableSortedSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + checkNotNull(fromElement); + checkNotNull(toElement); + checkArgument(comparator.compare(fromElement, toElement) <= 0); + return subSetImpl(fromElement, fromInclusive, toElement, toInclusive); + } + + /** + * {@inheritDoc} + * + *

+ * This method returns a serializable {@code ImmutableSortedSet}. + * + *

+ * The {@link SortedSet#subSet} documentation states that a subset of a subset + * throws an {@link IllegalArgumentException} if passed a {@code fromElement} + * smaller than an earlier {@code fromElement}. However, this method doesn't + * throw an exception in that situation, but instead keeps the original + * {@code fromElement}. Similarly, this method keeps the original + * {@code toElement}, instead of throwing an exception, if passed a + * {@code toElement} greater than an earlier {@code toElement}. + */ + @Override + public ImmutableSortedSet subSet(E fromElement, E toElement) { + return subSet(fromElement, true, toElement, false); + } + + abstract ImmutableSortedSet subSetImpl(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive); + + /** + * {@inheritDoc} + * + *

+ * This method returns a serializable {@code ImmutableSortedSet}. + * + *

+ * The {@link SortedSet#tailSet} documentation states that a subset of a subset + * throws an {@link IllegalArgumentException} if passed a {@code fromElement} + * smaller than an earlier {@code fromElement}. However, this method doesn't + * throw an exception in that situation, but instead keeps the original + * {@code fromElement}. + */ + @Override + public ImmutableSortedSet tailSet(E fromElement) { + return tailSet(fromElement, true); + } + + /** + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + @Override + public ImmutableSortedSet tailSet(E fromElement, boolean inclusive) { + return tailSetImpl(checkNotNull(fromElement), inclusive); + } + + abstract ImmutableSortedSet tailSetImpl(E fromElement, boolean inclusive); + + int unsafeCompare(Object a, Object b) { + return unsafeCompare(comparator, a, b); + } + @Override Object writeReplace() { return new SerializedForm(comparator, toArray()); diff --git a/src/main/java/com/google/common/collect/ImmutableSortedSetFauxverideShim.java b/src/main/java/com/google/common/collect/ImmutableSortedSetFauxverideShim.java index f8ab7b3a..c0a32e8f 100644 --- a/src/main/java/com/google/common/collect/ImmutableSortedSetFauxverideShim.java +++ b/src/main/java/com/google/common/collect/ImmutableSortedSetFauxverideShim.java @@ -52,6 +52,20 @@ abstract class ImmutableSortedSetFauxverideShim extends ImmutableSet { throw new UnsupportedOperationException(); } + /** + * Not supported. You are attempting to create a set that may contain + * non-{@code Comparable} elements. Proper calls will resolve to the version + * in {@code ImmutableSortedSet}, not this dummy version. + * + * @throws UnsupportedOperationException always + * @deprecated Pass parameters of type {@code Comparable} to use + * {@link ImmutableSortedSet#copyOf(Comparable[])}. + */ + @Deprecated + public static ImmutableSortedSet copyOf(E[] elements) { + throw new UnsupportedOperationException(); + } + /** * Not supported. You are attempting to create a set that may contain a * non-{@code Comparable} element. Proper calls will resolve to the version @@ -139,20 +153,6 @@ abstract class ImmutableSortedSetFauxverideShim extends ImmutableSet { throw new UnsupportedOperationException(); } - /** - * Not supported. You are attempting to create a set that may contain - * non-{@code Comparable} elements. Proper calls will resolve to the version - * in {@code ImmutableSortedSet}, not this dummy version. - * - * @throws UnsupportedOperationException always - * @deprecated Pass parameters of type {@code Comparable} to use - * {@link ImmutableSortedSet#copyOf(Comparable[])}. - */ - @Deprecated - public static ImmutableSortedSet copyOf(E[] elements) { - throw new UnsupportedOperationException(); - } - /* * We would like to include an unsupported " copyOf(Iterable)" here, * providing only the properly typed diff --git a/src/main/java/com/google/common/collect/ImmutableTable.java b/src/main/java/com/google/common/collect/ImmutableTable.java index faf8bde9..11de739e 100644 --- a/src/main/java/com/google/common/collect/ImmutableTable.java +++ b/src/main/java/com/google/common/collect/ImmutableTable.java @@ -48,18 +48,141 @@ import com.google.common.base.Objects; @GwtCompatible // TODO(gak): make serializable public abstract class ImmutableTable extends AbstractTable { + /** + * A builder for creating immutable table instances, especially {@code public + * static final} tables ("constant tables"). Example: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	static final ImmutableTable SPREADSHEET = new ImmutableTable.Builder()
+	 * 			.put(1, 'A', "foo").put(1, 'B', "bar").put(2, 'A', "baz").build();
+	 * }
+	 * 
+ * + *

+ * By default, the order in which cells are added to the builder determines the + * iteration ordering of all views in the returned table, with {@link #putAll} + * following the {@link Table#cellSet()} iteration order. However, if + * {@link #orderRowsBy} or {@link #orderColumnsBy} is called, the views are + * sorted by the supplied comparators. + * + * For empty or single-cell immutable tables, {@link #of()} and + * {@link #of(Object, Object, Object)} are even more convenient. + * + *

+ * Builder instances can be reused - it is safe to call {@link #build} multiple + * times to build multiple tables in series. Each table is a superset of the + * tables created before it. + * + * @since 11.0 + */ + public static final class Builder { + private final List> cells = Lists.newArrayList(); + private Comparator rowComparator; + private Comparator columnComparator; + + /** + * Creates a new builder. The returned builder is equivalent to the builder + * generated by {@link ImmutableTable#builder}. + */ + public Builder() { + } + + /** + * Returns a newly-created immutable table. + * + * @throws IllegalArgumentException if duplicate key pairs were added + */ + public ImmutableTable build() { + int size = cells.size(); + switch (size) { + case 0: + return of(); + case 1: + return new SingletonImmutableTable(Iterables.getOnlyElement(cells)); + default: + return RegularImmutableTable.forCells(cells, rowComparator, columnComparator); + } + } + + /** + * Specifies the ordering of the generated table's columns. + */ + public Builder orderColumnsBy(Comparator columnComparator) { + this.columnComparator = checkNotNull(columnComparator); + return this; + } + + /** + * Specifies the ordering of the generated table's rows. + */ + public Builder orderRowsBy(Comparator rowComparator) { + this.rowComparator = checkNotNull(rowComparator); + return this; + } + + /** + * Adds the given {@code cell} to the table, making it immutable if necessary. + * Duplicate key pairs are not allowed and will cause {@link #build} to fail. + */ + public Builder put(Cell cell) { + if (cell instanceof Tables.ImmutableCell) { + checkNotNull(cell.getRowKey()); + checkNotNull(cell.getColumnKey()); + checkNotNull(cell.getValue()); + @SuppressWarnings("unchecked") // all supported methods are covariant + Cell immutableCell = (Cell) cell; + cells.add(immutableCell); + } else { + put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); + } + return this; + } + + /** + * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code + * value} in the built table. Duplicate key pairs are not allowed and will cause + * {@link #build} to fail. + */ + public Builder put(R rowKey, C columnKey, V value) { + cells.add(cellOf(rowKey, columnKey, value)); + return this; + } + + /** + * Associates all of the given table's keys and values in the built table. + * Duplicate row key column key pairs are not allowed, and will cause + * {@link #build} to fail. + * + * @throws NullPointerException if any key or value in {@code table} is null + */ + public Builder putAll(Table table) { + for (Cell cell : table.cellSet()) { + put(cell); + } + return this; + } + } + private static final ImmutableTable EMPTY = new SparseImmutableTable( ImmutableList.>of(), ImmutableSet.of(), ImmutableSet.of()); - /** Returns an empty immutable table. */ - @SuppressWarnings("unchecked") - public static ImmutableTable of() { - return (ImmutableTable) EMPTY; + /** + * Returns a new builder. The generated builder is equivalent to the builder + * created by the {@link Builder#ImmutableTable.Builder()} constructor. + */ + public static Builder builder() { + return new Builder(); } - /** Returns an immutable table containing a single cell. */ - public static ImmutableTable of(R rowKey, C columnKey, V value) { - return new SingletonImmutableTable(rowKey, columnKey, value); + /** + * Verifies that {@code rowKey}, {@code columnKey} and {@code value} are + * non-null, and returns a new entry with those values. + */ + static Cell cellOf(R rowKey, C columnKey, V value) { + return Tables.immutableCell(checkNotNull(rowKey), checkNotNull(columnKey), checkNotNull(value)); } /** @@ -105,167 +228,40 @@ public abstract class ImmutableTable extends AbstractTable { } } - /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder#ImmutableTable.Builder()} constructor. - */ - public static Builder builder() { - return new Builder(); + /** Returns an empty immutable table. */ + @SuppressWarnings("unchecked") + public static ImmutableTable of() { + return (ImmutableTable) EMPTY; } - /** - * Verifies that {@code rowKey}, {@code columnKey} and {@code value} are - * non-null, and returns a new entry with those values. - */ - static Cell cellOf(R rowKey, C columnKey, V value) { - return Tables.immutableCell(checkNotNull(rowKey), checkNotNull(columnKey), checkNotNull(value)); - } - - /** - * A builder for creating immutable table instances, especially {@code public - * static final} tables ("constant tables"). Example: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	static final ImmutableTable SPREADSHEET = new ImmutableTable.Builder()
-	 * 			.put(1, 'A', "foo").put(1, 'B', "bar").put(2, 'A', "baz").build();
-	 * }
-	 * 
- * - *

- * By default, the order in which cells are added to the builder determines the - * iteration ordering of all views in the returned table, with {@link #putAll} - * following the {@link Table#cellSet()} iteration order. However, if - * {@link #orderRowsBy} or {@link #orderColumnsBy} is called, the views are - * sorted by the supplied comparators. - * - * For empty or single-cell immutable tables, {@link #of()} and - * {@link #of(Object, Object, Object)} are even more convenient. - * - *

- * Builder instances can be reused - it is safe to call {@link #build} multiple - * times to build multiple tables in series. Each table is a superset of the - * tables created before it. - * - * @since 11.0 - */ - public static final class Builder { - private final List> cells = Lists.newArrayList(); - private Comparator rowComparator; - private Comparator columnComparator; - - /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link ImmutableTable#builder}. - */ - public Builder() { - } - - /** - * Specifies the ordering of the generated table's rows. - */ - public Builder orderRowsBy(Comparator rowComparator) { - this.rowComparator = checkNotNull(rowComparator); - return this; - } - - /** - * Specifies the ordering of the generated table's columns. - */ - public Builder orderColumnsBy(Comparator columnComparator) { - this.columnComparator = checkNotNull(columnComparator); - return this; - } - - /** - * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code - * value} in the built table. Duplicate key pairs are not allowed and will cause - * {@link #build} to fail. - */ - public Builder put(R rowKey, C columnKey, V value) { - cells.add(cellOf(rowKey, columnKey, value)); - return this; - } - - /** - * Adds the given {@code cell} to the table, making it immutable if necessary. - * Duplicate key pairs are not allowed and will cause {@link #build} to fail. - */ - public Builder put(Cell cell) { - if (cell instanceof Tables.ImmutableCell) { - checkNotNull(cell.getRowKey()); - checkNotNull(cell.getColumnKey()); - checkNotNull(cell.getValue()); - @SuppressWarnings("unchecked") // all supported methods are covariant - Cell immutableCell = (Cell) cell; - cells.add(immutableCell); - } else { - put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); - } - return this; - } - - /** - * Associates all of the given table's keys and values in the built table. - * Duplicate row key column key pairs are not allowed, and will cause - * {@link #build} to fail. - * - * @throws NullPointerException if any key or value in {@code table} is null - */ - public Builder putAll(Table table) { - for (Cell cell : table.cellSet()) { - put(cell); - } - return this; - } - - /** - * Returns a newly-created immutable table. - * - * @throws IllegalArgumentException if duplicate key pairs were added - */ - public ImmutableTable build() { - int size = cells.size(); - switch (size) { - case 0: - return of(); - case 1: - return new SingletonImmutableTable(Iterables.getOnlyElement(cells)); - default: - return RegularImmutableTable.forCells(cells, rowComparator, columnComparator); - } - } + /** Returns an immutable table containing a single cell. */ + public static ImmutableTable of(R rowKey, C columnKey, V value) { + return new SingletonImmutableTable(rowKey, columnKey, value); } ImmutableTable() { } - @Override - public ImmutableSet> cellSet() { - return (ImmutableSet>) super.cellSet(); - } - - @Override - abstract ImmutableSet> createCellSet(); - @Override final UnmodifiableIterator> cellIterator() { throw new AssertionError("should never be called"); } @Override - public ImmutableCollection values() { - return (ImmutableCollection) super.values(); + public ImmutableSet> cellSet() { + return (ImmutableSet>) super.cellSet(); } + /** + * Guaranteed to throw an exception and leave the table unmodified. + * + * @throws UnsupportedOperationException always + * @deprecated Unsupported operation. + */ + @Deprecated @Override - abstract ImmutableCollection createValues(); - - @Override - final Iterator valuesIterator() { - throw new AssertionError("should never be called"); + public final void clear() { + throw new UnsupportedOperationException(); } /** @@ -294,32 +290,6 @@ public abstract class ImmutableTable extends AbstractTable { @Override public abstract ImmutableMap> columnMap(); - /** - * {@inheritDoc} - * - * @throws NullPointerException if {@code rowKey} is {@code null} - */ - @Override - public ImmutableMap row(R rowKey) { - checkNotNull(rowKey); - return Objects.firstNonNull((ImmutableMap) rowMap().get(rowKey), ImmutableMap.of()); - } - - @Override - public ImmutableSet rowKeySet() { - return rowMap().keySet(); - } - - /** - * {@inheritDoc} - * - *

- * The value {@code Map} instances in the returned map are - * {@link ImmutableMap} instances as well. - */ - @Override - public abstract ImmutableMap> rowMap(); - @Override public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { return get(rowKey, columnKey) != null; @@ -330,17 +300,11 @@ public abstract class ImmutableTable extends AbstractTable { return values().contains(value); } - /** - * Guaranteed to throw an exception and leave the table unmodified. - * - * @throws UnsupportedOperationException always - * @deprecated Unsupported operation. - */ - @Deprecated @Override - public final void clear() { - throw new UnsupportedOperationException(); - } + abstract ImmutableSet> createCellSet(); + + @Override + abstract ImmutableCollection createValues(); /** * Guaranteed to throw an exception and leave the table unmodified. @@ -377,4 +341,40 @@ public abstract class ImmutableTable extends AbstractTable { public final V remove(Object rowKey, Object columnKey) { throw new UnsupportedOperationException(); } + + /** + * {@inheritDoc} + * + * @throws NullPointerException if {@code rowKey} is {@code null} + */ + @Override + public ImmutableMap row(R rowKey) { + checkNotNull(rowKey); + return Objects.firstNonNull((ImmutableMap) rowMap().get(rowKey), ImmutableMap.of()); + } + + @Override + public ImmutableSet rowKeySet() { + return rowMap().keySet(); + } + + /** + * {@inheritDoc} + * + *

+ * The value {@code Map} instances in the returned map are + * {@link ImmutableMap} instances as well. + */ + @Override + public abstract ImmutableMap> rowMap(); + + @Override + public ImmutableCollection values() { + return (ImmutableCollection) super.values(); + } + + @Override + final Iterator valuesIterator() { + throw new AssertionError("should never be called"); + } } diff --git a/src/main/java/com/google/common/collect/Iterables.java b/src/main/java/com/google/common/collect/Iterables.java index e4bc5e8a..a17d59e9 100644 --- a/src/main/java/com/google/common/collect/Iterables.java +++ b/src/main/java/com/google/common/collect/Iterables.java @@ -60,27 +60,21 @@ import com.google.common.base.Predicate; */ @GwtCompatible(emulated = true) public final class Iterables { - private Iterables() { - } + private static class ConsumingQueueIterator extends AbstractIterator { + private final Queue queue; - /** Returns an unmodifiable view of {@code iterable}. */ - public static Iterable unmodifiableIterable(final Iterable iterable) { - checkNotNull(iterable); - if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { - return iterable; + private ConsumingQueueIterator(Queue queue) { + this.queue = queue; } - return new UnmodifiableIterable(iterable); - } - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ - @Deprecated - public static Iterable unmodifiableIterable(ImmutableCollection iterable) { - return checkNotNull(iterable); + @Override + public T computeNext() { + try { + return queue.remove(); + } catch (NoSuchElementException e) { + return endOfData(); + } + } } private static final class UnmodifiableIterable extends FluentIterable { @@ -102,234 +96,6 @@ public final class Iterables { // no equals and hashCode; it would break the contract! } - /** - * Returns the number of elements in {@code iterable}. - */ - public static int size(Iterable iterable) { - return (iterable instanceof Collection) ? ((Collection) iterable).size() - : Iterators.size(iterable.iterator()); - } - - /** - * Returns {@code true} if {@code iterable} contains any object for which - * {@code equals(element)} is true. - */ - public static boolean contains(Iterable iterable, @Nullable Object element) { - if (iterable instanceof Collection) { - Collection collection = (Collection) iterable; - return Collections2.safeContains(collection, element); - } - return Iterators.contains(iterable.iterator(), element); - } - - /** - * Removes, from an iterable, every element that belongs to the provided - * collection. - * - *

- * This method calls {@link Collection#removeAll} if {@code iterable} is a - * collection, and {@link Iterators#removeAll} otherwise. - * - * @param removeFrom the iterable to (potentially) remove elements from - * @param elementsToRemove the elements to remove - * @return {@code true} if any element was removed from {@code iterable} - */ - public static boolean removeAll(Iterable removeFrom, Collection elementsToRemove) { - return (removeFrom instanceof Collection) - ? ((Collection) removeFrom).removeAll(checkNotNull(elementsToRemove)) - : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); - } - - /** - * Removes, from an iterable, every element that does not belong to the provided - * collection. - * - *

- * This method calls {@link Collection#retainAll} if {@code iterable} is a - * collection, and {@link Iterators#retainAll} otherwise. - * - * @param removeFrom the iterable to (potentially) remove elements from - * @param elementsToRetain the elements to retain - * @return {@code true} if any element was removed from {@code iterable} - */ - public static boolean retainAll(Iterable removeFrom, Collection elementsToRetain) { - return (removeFrom instanceof Collection) - ? ((Collection) removeFrom).retainAll(checkNotNull(elementsToRetain)) - : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); - } - - /** - * Removes, from an iterable, every element that satisfies the provided - * predicate. - * - * @param removeFrom the iterable to (potentially) remove elements from - * @param predicate a predicate that determines whether an element should be - * removed - * @return {@code true} if any elements were removed from the iterable - * - * @throws UnsupportedOperationException if the iterable does not support - * {@code remove()}. - * @since 2.0 - */ - public static boolean removeIf(Iterable removeFrom, Predicate predicate) { - if (removeFrom instanceof RandomAccess && removeFrom instanceof List) { - return removeIfFromRandomAccessList((List) removeFrom, checkNotNull(predicate)); - } - return Iterators.removeIf(removeFrom.iterator(), predicate); - } - - private static boolean removeIfFromRandomAccessList(List list, Predicate predicate) { - // Note: Not all random access lists support set() so we need to deal with - // those that don't and attempt the slower remove() based solution. - int from = 0; - int to = 0; - - for (; from < list.size(); from++) { - T element = list.get(from); - if (!predicate.apply(element)) { - if (from > to) { - try { - list.set(to, element); - } catch (UnsupportedOperationException e) { - slowRemoveIfForRemainingElements(list, predicate, to, from); - return true; - } - } - to++; - } - } - - // Clear the tail of any remaining items - list.subList(to, list.size()).clear(); - return from != to; - } - - private static void slowRemoveIfForRemainingElements(List list, Predicate predicate, int to, - int from) { - // Here we know that: - // * (to < from) and that both are valid indices. - // * Everything with (index < to) should be kept. - // * Everything with (to <= index < from) should be removed. - // * The element with (index == from) should be kept. - // * Everything with (index > from) has not been checked yet. - - // Check from the end of the list backwards (minimize expected cost of - // moving elements when remove() is called). Stop before 'from' because - // we already know that should be kept. - for (int n = list.size() - 1; n > from; n--) { - if (predicate.apply(list.get(n))) { - list.remove(n); - } - } - // And now remove everything in the range [to, from) (going backwards). - for (int n = from - 1; n >= to; n--) { - list.remove(n); - } - } - - /** - * Removes and returns the first matching element, or returns {@code null} if - * there is none. - */ - @Nullable - static T removeFirstMatching(Iterable removeFrom, Predicate predicate) { - checkNotNull(predicate); - Iterator iterator = removeFrom.iterator(); - while (iterator.hasNext()) { - T next = iterator.next(); - if (predicate.apply(next)) { - iterator.remove(); - return next; - } - } - return null; - } - - /** - * Determines whether two iterables contain equal elements in the same order. - * More specifically, this method returns {@code true} if {@code iterable1} and - * {@code iterable2} contain the same number of elements and every element of - * {@code iterable1} is equal to the corresponding element of {@code iterable2}. - */ - public static boolean elementsEqual(Iterable iterable1, Iterable iterable2) { - if (iterable1 instanceof Collection && iterable2 instanceof Collection) { - Collection collection1 = (Collection) iterable1; - Collection collection2 = (Collection) iterable2; - if (collection1.size() != collection2.size()) { - return false; - } - } - return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); - } - - /** - * Returns a string representation of {@code iterable}, with the format {@code - * [e1, e2, ..., en]} (that is, identical to {@link java.util.Arrays - * Arrays}{@code .toString(Iterables.toArray(iterable))}). Note that for - * most implementations of {@link Collection}, {@code - * collection.toString()} also gives the same result, but that behavior is not - * generally guaranteed. - */ - public static String toString(Iterable iterable) { - return Iterators.toString(iterable.iterator()); - } - - /** - * Returns the single element contained in {@code iterable}. - * - * @throws NoSuchElementException if the iterable is empty - * @throws IllegalArgumentException if the iterable contains multiple elements - */ - public static T getOnlyElement(Iterable iterable) { - return Iterators.getOnlyElement(iterable.iterator()); - } - - /** - * Returns the single element contained in {@code iterable}, or {@code - * defaultValue} if the iterable is empty. - * - * @throws IllegalArgumentException if the iterator contains multiple elements - */ - @Nullable - public static T getOnlyElement(Iterable iterable, @Nullable T defaultValue) { - return Iterators.getOnlyElement(iterable.iterator(), defaultValue); - } - - /** - * Copies an iterable's elements into an array. - * - * @param iterable the iterable to copy - * @param type the type of the elements - * @return a newly-allocated array into which all the elements of the iterable - * have been copied - */ - @GwtIncompatible("Array.newInstance(Class, int)") - public static T[] toArray(Iterable iterable, Class type) { - Collection collection = toCollection(iterable); - T[] array = ObjectArrays.newArray(type, collection.size()); - return collection.toArray(array); - } - - /** - * Copies an iterable's elements into an array. - * - * @param iterable the iterable to copy - * @return a newly-allocated array into which all the elements of the iterable - * have been copied - */ - static Object[] toArray(Iterable iterable) { - return toCollection(iterable).toArray(); - } - - /** - * Converts an iterable into a collection. If the iterable is already a - * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is - * created with the contents of the iterable in the same iteration order. - */ - private static Collection toCollection(Iterable iterable) { - return (iterable instanceof Collection) ? (Collection) iterable : Lists.newArrayList(iterable.iterator()); - } - /** * Adds all elements in {@code iterable} to {@code collection}. * @@ -345,19 +111,159 @@ public final class Iterables { } /** - * Returns the number of elements in the specified iterable that equal the - * specified object. This implementation avoids a full iteration when the - * iterable is a {@link Multiset} or {@link Set}. - * - * @see Collections#frequency + * Returns {@code true} if every element in {@code iterable} satisfies the + * predicate. If {@code iterable} is empty, {@code true} is returned. */ - public static int frequency(Iterable iterable, @Nullable Object element) { - if ((iterable instanceof Multiset)) { - return ((Multiset) iterable).count(element); - } else if ((iterable instanceof Set)) { - return ((Set) iterable).contains(element) ? 1 : 0; + public static boolean all(Iterable iterable, Predicate predicate) { + return Iterators.all(iterable.iterator(), predicate); + } + + /** + * Returns {@code true} if any element in {@code iterable} satisfies the + * predicate. + */ + public static boolean any(Iterable iterable, Predicate predicate) { + return Iterators.any(iterable.iterator(), predicate); + } + + /** + * Combines multiple iterables into a single iterable. The returned iterable has + * an iterator that traverses the elements of each iterable in {@code inputs}. + * The input iterators are not polled until necessary. + * + *

+ * The returned iterable's iterator supports {@code remove()} when the + * corresponding input iterator supports it. The methods of the returned + * iterable may throw {@code NullPointerException} if any of the input iterators + * is null. + */ + public static Iterable concat(final Iterable> inputs) { + checkNotNull(inputs); + return new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.concat(iterators(inputs)); + } + }; + } + + /** + * Combines multiple iterables into a single iterable. The returned iterable has + * an iterator that traverses the elements of each iterable in {@code inputs}. + * The input iterators are not polled until necessary. + * + *

+ * The returned iterable's iterator supports {@code remove()} when the + * corresponding input iterator supports it. + * + * @throws NullPointerException if any of the provided iterables is null + */ + public static Iterable concat(Iterable... inputs) { + return concat(ImmutableList.copyOf(inputs)); + } + + /** + * Combines two iterables into a single iterable. The returned iterable has an + * iterator that traverses the elements in {@code a}, followed by the elements + * in {@code b}. The source iterators are not polled until necessary. + * + *

+ * The returned iterable's iterator supports {@code remove()} when the + * corresponding input iterator supports it. + */ + public static Iterable concat(Iterable a, Iterable b) { + return concat(ImmutableList.of(a, b)); + } + + /** + * Combines three iterables into a single iterable. The returned iterable has an + * iterator that traverses the elements in {@code a}, followed by the elements + * in {@code b}, followed by the elements in {@code c}. The source iterators are + * not polled until necessary. + * + *

+ * The returned iterable's iterator supports {@code remove()} when the + * corresponding input iterator supports it. + */ + public static Iterable concat(Iterable a, Iterable b, Iterable c) { + return concat(ImmutableList.of(a, b, c)); + } + + /** + * Combines four iterables into a single iterable. The returned iterable has an + * iterator that traverses the elements in {@code a}, followed by the elements + * in {@code b}, followed by the elements in {@code c}, followed by the elements + * in {@code d}. The source iterators are not polled until necessary. + * + *

+ * The returned iterable's iterator supports {@code remove()} when the + * corresponding input iterator supports it. + */ + public static Iterable concat(Iterable a, Iterable b, Iterable c, + Iterable d) { + return concat(ImmutableList.of(a, b, c, d)); + } + + /** + * Returns a view of the supplied iterable that wraps each generated + * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}. + * + *

+ * Note: If {@code iterable} is a {@link Queue}, the returned iterable will get + * entries from {@link Queue#remove()} since {@link Queue}'s iteration order is + * undefined. Calling {@link Iterator#hasNext()} on a generated iterator from + * the returned iterable may cause an item to be immediately dequeued for return + * on a subsequent call to {@link Iterator#next()}. + * + * @param iterable the iterable to wrap + * @return a view of the supplied iterable that wraps each generated iterator + * through {@link Iterators#consumingIterator(Iterator)}; for queues, an + * iterable that generates iterators that return and consume the queue's + * elements in queue order + * + * @see Iterators#consumingIterator(Iterator) + * @since 2.0 + */ + public static Iterable consumingIterable(final Iterable iterable) { + if (iterable instanceof Queue) { + return new FluentIterable() { + @Override + public Iterator iterator() { + return new ConsumingQueueIterator((Queue) iterable); + } + + @Override + public String toString() { + return "Iterables.consumingIterable(...)"; + } + }; } - return Iterators.frequency(iterable.iterator(), element); + + checkNotNull(iterable); + + return new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.consumingIterator(iterable.iterator()); + } + + @Override + public String toString() { + return "Iterables.consumingIterable(...)"; + } + }; + } + + /** + * Returns {@code true} if {@code iterable} contains any object for which + * {@code equals(element)} is true. + */ + public static boolean contains(Iterable iterable, @Nullable Object element) { + if (iterable instanceof Collection) { + Collection collection = (Collection) iterable; + return Collections2.safeContains(collection, element); + } + return Iterators.contains(iterable.iterator(), element); } /** @@ -420,83 +326,262 @@ public final class Iterables { } /** - * Combines two iterables into a single iterable. The returned iterable has an - * iterator that traverses the elements in {@code a}, followed by the elements - * in {@code b}. The source iterators are not polled until necessary. - * - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. + * Determines whether two iterables contain equal elements in the same order. + * More specifically, this method returns {@code true} if {@code iterable1} and + * {@code iterable2} contain the same number of elements and every element of + * {@code iterable1} is equal to the corresponding element of {@code iterable2}. */ - public static Iterable concat(Iterable a, Iterable b) { - return concat(ImmutableList.of(a, b)); + public static boolean elementsEqual(Iterable iterable1, Iterable iterable2) { + if (iterable1 instanceof Collection && iterable2 instanceof Collection) { + Collection collection1 = (Collection) iterable1; + Collection collection2 = (Collection) iterable2; + if (collection1.size() != collection2.size()) { + return false; + } + } + return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** - * Combines three iterables into a single iterable. The returned iterable has an - * iterator that traverses the elements in {@code a}, followed by the elements - * in {@code b}, followed by the elements in {@code c}. The source iterators are - * not polled until necessary. + * Returns all instances of class {@code type} in {@code unfiltered}. The + * returned iterable has elements whose class is {@code type} or a subclass of + * {@code type}. The returned iterable's iterator does not support + * {@code remove()}. * - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. + * @param unfiltered an iterable containing objects of any type + * @param type the type of elements desired + * @return an unmodifiable iterable containing all elements of the original + * iterable that were of the requested type */ - public static Iterable concat(Iterable a, Iterable b, Iterable c) { - return concat(ImmutableList.of(a, b, c)); - } - - /** - * Combines four iterables into a single iterable. The returned iterable has an - * iterator that traverses the elements in {@code a}, followed by the elements - * in {@code b}, followed by the elements in {@code c}, followed by the elements - * in {@code d}. The source iterators are not polled until necessary. - * - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. - */ - public static Iterable concat(Iterable a, Iterable b, Iterable c, - Iterable d) { - return concat(ImmutableList.of(a, b, c, d)); - } - - /** - * Combines multiple iterables into a single iterable. The returned iterable has - * an iterator that traverses the elements of each iterable in {@code inputs}. - * The input iterators are not polled until necessary. - * - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. - * - * @throws NullPointerException if any of the provided iterables is null - */ - public static Iterable concat(Iterable... inputs) { - return concat(ImmutableList.copyOf(inputs)); - } - - /** - * Combines multiple iterables into a single iterable. The returned iterable has - * an iterator that traverses the elements of each iterable in {@code inputs}. - * The input iterators are not polled until necessary. - * - *

- * The returned iterable's iterator supports {@code remove()} when the - * corresponding input iterator supports it. The methods of the returned - * iterable may throw {@code NullPointerException} if any of the input iterators - * is null. - */ - public static Iterable concat(final Iterable> inputs) { - checkNotNull(inputs); + @GwtIncompatible("Class.isInstance") + public static Iterable filter(final Iterable unfiltered, final Class type) { + checkNotNull(unfiltered); + checkNotNull(type); return new FluentIterable() { @Override public Iterator iterator() { - return Iterators.concat(iterators(inputs)); + return Iterators.filter(unfiltered.iterator(), type); } }; } + /** + * Returns the elements of {@code unfiltered} that satisfy a predicate. The + * resulting iterable's iterator does not support {@code remove()}. + */ + public static Iterable filter(final Iterable unfiltered, final Predicate predicate) { + checkNotNull(unfiltered); + checkNotNull(predicate); + return new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.filter(unfiltered.iterator(), predicate); + } + }; + } + + /** + * Returns the first element in {@code iterable} that satisfies the given + * predicate, or {@code defaultValue} if none found. Note that this can usually + * be handled more naturally using {@code + * tryFind(iterable, predicate).or(defaultValue)}. + * + * @since 7.0 + */ + @Nullable + public static T find(Iterable iterable, Predicate predicate, @Nullable T defaultValue) { + return Iterators.find(iterable.iterator(), predicate, defaultValue); + } + + /** + * Returns the first element in {@code iterable} that satisfies the given + * predicate; use this method only when such an element is known to exist. If it + * is possible that no element will match, use {@link #tryFind} or + * {@link #find(Iterable, Predicate, Object)} instead. + * + * @throws NoSuchElementException if no element in {@code iterable} matches the + * given predicate + */ + public static T find(Iterable iterable, Predicate predicate) { + return Iterators.find(iterable.iterator(), predicate); + } + + /** + * Returns the number of elements in the specified iterable that equal the + * specified object. This implementation avoids a full iteration when the + * iterable is a {@link Multiset} or {@link Set}. + * + * @see Collections#frequency + */ + public static int frequency(Iterable iterable, @Nullable Object element) { + if ((iterable instanceof Multiset)) { + return ((Multiset) iterable).count(element); + } else if ((iterable instanceof Set)) { + return ((Set) iterable).contains(element) ? 1 : 0; + } + return Iterators.frequency(iterable.iterator(), element); + } + + /** + * Returns the element at the specified position in an iterable or a default + * value otherwise. + * + * @param position position of the element to return + * @param defaultValue the default value to return if {@code position} is + * greater than or equal to the size of the iterable + * @return the element at the specified position in {@code iterable} or + * {@code defaultValue} if {@code iterable} contains fewer than + * {@code position + 1} elements. + * @throws IndexOutOfBoundsException if {@code position} is negative + * @since 4.0 + */ + @Nullable + public static T get(Iterable iterable, int position, @Nullable T defaultValue) { + checkNotNull(iterable); + Iterators.checkNonnegative(position); + if (iterable instanceof List) { + List list = Lists.cast(iterable); + return (position < list.size()) ? list.get(position) : defaultValue; + } else { + Iterator iterator = iterable.iterator(); + Iterators.advance(iterator, position); + return Iterators.getNext(iterator, defaultValue); + } + } + + /** + * Returns the element at the specified position in an iterable. + * + * @param position position of the element to return + * @return the element at the specified position in {@code iterable} + * @throws IndexOutOfBoundsException if {@code position} is negative or greater + * than or equal to the size of + * {@code iterable} + */ + public static T get(Iterable iterable, int position) { + checkNotNull(iterable); + return (iterable instanceof List) ? ((List) iterable).get(position) + : Iterators.get(iterable.iterator(), position); + } + + /** + * Returns the first element in {@code iterable} or {@code defaultValue} if the + * iterable is empty. The {@link Iterators} analog to this method is + * {@link Iterators#getNext}. + * + *

+ * If no default value is desired (and the caller instead wants a + * {@link NoSuchElementException} to be thrown), it is recommended that + * {@code iterable.iterator().next()} is used instead. + * + * @param defaultValue the default value to return if the iterable is empty + * @return the first element of {@code iterable} or the default value + * @since 7.0 + */ + @Nullable + public static T getFirst(Iterable iterable, @Nullable T defaultValue) { + return Iterators.getNext(iterable.iterator(), defaultValue); + } + + /** + * Returns the last element of {@code iterable} or {@code defaultValue} if the + * iterable is empty. + * + * @param defaultValue the value to return if {@code iterable} is empty + * @return the last element of {@code iterable} or the default value + * @since 3.0 + */ + @Nullable + public static T getLast(Iterable iterable, @Nullable T defaultValue) { + if (iterable instanceof Collection) { + Collection c = Collections2.cast(iterable); + if (c.isEmpty()) { + return defaultValue; + } else if (iterable instanceof List) { + return getLastInNonemptyList(Lists.cast(iterable)); + } + } + + return Iterators.getLast(iterable.iterator(), defaultValue); + } + + /** + * Returns the last element of {@code iterable}. + * + * @return the last element of {@code iterable} + * @throws NoSuchElementException if the iterable is empty + */ + public static T getLast(Iterable iterable) { + // TODO(kevinb): Support a concurrently modified collection? + if (iterable instanceof List) { + List list = (List) iterable; + if (list.isEmpty()) { + throw new NoSuchElementException(); + } + return getLastInNonemptyList(list); + } + + return Iterators.getLast(iterable.iterator()); + } + + private static T getLastInNonemptyList(List list) { + return list.get(list.size() - 1); + } + + /** + * Returns the single element contained in {@code iterable}, or {@code + * defaultValue} if the iterable is empty. + * + * @throws IllegalArgumentException if the iterator contains multiple elements + */ + @Nullable + public static T getOnlyElement(Iterable iterable, @Nullable T defaultValue) { + return Iterators.getOnlyElement(iterable.iterator(), defaultValue); + } + + /** + * Returns the single element contained in {@code iterable}. + * + * @throws NoSuchElementException if the iterable is empty + * @throws IllegalArgumentException if the iterable contains multiple elements + */ + public static T getOnlyElement(Iterable iterable) { + return Iterators.getOnlyElement(iterable.iterator()); + } + + /** + * Returns the index in {@code iterable} of the first element that satisfies the + * provided {@code predicate}, or {@code -1} if the Iterable has no such + * elements. + * + *

+ * More formally, returns the lowest index {@code i} such that + * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or + * {@code -1} if there is no such index. + * + * @since 2.0 + */ + public static int indexOf(Iterable iterable, Predicate predicate) { + return Iterators.indexOf(iterable.iterator(), predicate); + } + + /** + * Determines if the given iterable contains no elements. + * + *

+ * There is no precise {@link Iterator} equivalent to this method, since one can + * only ask an iterator whether it has any elements remaining (which one + * does using {@link Iterator#hasNext}). + * + * @return {@code true} if the iterable contains no elements + */ + public static boolean isEmpty(Iterable iterable) { + if (iterable instanceof Collection) { + return ((Collection) iterable).isEmpty(); + } + return !iterable.iterator().hasNext(); + } + /** * Returns an iterator over the iterators of the given iterables. */ @@ -509,6 +594,86 @@ public final class Iterables { }; } + /** + * Creates an iterable with the first {@code limitSize} elements of the given + * iterable. If the original iterable does not contain that many elements, the + * returned iterable will have the same behavior as the original iterable. The + * returned iterable's iterator supports {@code remove()} if the original + * iterator does. + * + * @param iterable the iterable to limit + * @param limitSize the maximum number of elements in the returned iterable + * @throws IllegalArgumentException if {@code limitSize} is negative + * @since 3.0 + */ + public static Iterable limit(final Iterable iterable, final int limitSize) { + checkNotNull(iterable); + checkArgument(limitSize >= 0, "limit is negative"); + return new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.limit(iterable.iterator(), limitSize); + } + }; + } + + /** + * Returns an iterable over the merged contents of all given {@code iterables}. + * Equivalent entries will not be de-duplicated. + * + *

+ * Callers must ensure that the source {@code iterables} are in non-descending + * order as this method does not sort its input. + * + *

+ * For any equivalent elements across all {@code iterables}, it is undefined + * which element is returned first. + * + * @since 11.0 + */ + @Beta + public static Iterable mergeSorted(final Iterable> iterables, + final Comparator comparator) { + checkNotNull(iterables, "iterables"); + checkNotNull(comparator, "comparator"); + Iterable iterable = new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.mergeSorted(Iterables.transform(iterables, Iterables.toIterator()), comparator); + } + }; + return new UnmodifiableIterable(iterable); + } + + /** + * Divides an iterable into unmodifiable sublists of the given size, padding the + * final iterable with null values if necessary. For example, partitioning an + * iterable containing {@code [a, b, c, d, e]} with a partition size of 3 yields + * {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing two inner + * lists of three elements each, all in the original order. + * + *

+ * Iterators returned by the returned iterable do not support the + * {@link Iterator#remove()} method. + * + * @param iterable the iterable to return a partitioned view of + * @param size the desired size of each partition + * @return an iterable of unmodifiable lists containing the elements of {@code + * iterable} divided into partitions (the final iterable may have trailing + * null elements) + * @throws IllegalArgumentException if {@code size} is nonpositive + */ + public static Iterable> paddedPartition(final Iterable iterable, final int size) { + checkNotNull(iterable); + checkArgument(size > 0); + return new FluentIterable>() { + @Override + public Iterator> iterator() { + return Iterators.paddedPartition(iterable.iterator(), size); + } + }; + } + /** * Divides an iterable into unmodifiable sublists of the given size (the final * iterable may be smaller). For example, partitioning an iterable containing @@ -543,275 +708,111 @@ public final class Iterables { } /** - * Divides an iterable into unmodifiable sublists of the given size, padding the - * final iterable with null values if necessary. For example, partitioning an - * iterable containing {@code [a, b, c, d, e]} with a partition size of 3 yields - * {@code [[a, b, c], [d, e, null]]} -- an outer iterable containing two inner - * lists of three elements each, all in the original order. + * Removes, from an iterable, every element that belongs to the provided + * collection. * *

- * Iterators returned by the returned iterable do not support the - * {@link Iterator#remove()} method. + * This method calls {@link Collection#removeAll} if {@code iterable} is a + * collection, and {@link Iterators#removeAll} otherwise. * - * @param iterable the iterable to return a partitioned view of - * @param size the desired size of each partition - * @return an iterable of unmodifiable lists containing the elements of {@code - * iterable} divided into partitions (the final iterable may have trailing - * null elements) - * @throws IllegalArgumentException if {@code size} is nonpositive + * @param removeFrom the iterable to (potentially) remove elements from + * @param elementsToRemove the elements to remove + * @return {@code true} if any element was removed from {@code iterable} */ - public static Iterable> paddedPartition(final Iterable iterable, final int size) { - checkNotNull(iterable); - checkArgument(size > 0); - return new FluentIterable>() { - @Override - public Iterator> iterator() { - return Iterators.paddedPartition(iterable.iterator(), size); - } - }; + public static boolean removeAll(Iterable removeFrom, Collection elementsToRemove) { + return (removeFrom instanceof Collection) + ? ((Collection) removeFrom).removeAll(checkNotNull(elementsToRemove)) + : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** - * Returns the elements of {@code unfiltered} that satisfy a predicate. The - * resulting iterable's iterator does not support {@code remove()}. - */ - public static Iterable filter(final Iterable unfiltered, final Predicate predicate) { - checkNotNull(unfiltered); - checkNotNull(predicate); - return new FluentIterable() { - @Override - public Iterator iterator() { - return Iterators.filter(unfiltered.iterator(), predicate); - } - }; - } - - /** - * Returns all instances of class {@code type} in {@code unfiltered}. The - * returned iterable has elements whose class is {@code type} or a subclass of - * {@code type}. The returned iterable's iterator does not support - * {@code remove()}. - * - * @param unfiltered an iterable containing objects of any type - * @param type the type of elements desired - * @return an unmodifiable iterable containing all elements of the original - * iterable that were of the requested type - */ - @GwtIncompatible("Class.isInstance") - public static Iterable filter(final Iterable unfiltered, final Class type) { - checkNotNull(unfiltered); - checkNotNull(type); - return new FluentIterable() { - @Override - public Iterator iterator() { - return Iterators.filter(unfiltered.iterator(), type); - } - }; - } - - /** - * Returns {@code true} if any element in {@code iterable} satisfies the - * predicate. - */ - public static boolean any(Iterable iterable, Predicate predicate) { - return Iterators.any(iterable.iterator(), predicate); - } - - /** - * Returns {@code true} if every element in {@code iterable} satisfies the - * predicate. If {@code iterable} is empty, {@code true} is returned. - */ - public static boolean all(Iterable iterable, Predicate predicate) { - return Iterators.all(iterable.iterator(), predicate); - } - - /** - * Returns the first element in {@code iterable} that satisfies the given - * predicate; use this method only when such an element is known to exist. If it - * is possible that no element will match, use {@link #tryFind} or - * {@link #find(Iterable, Predicate, Object)} instead. - * - * @throws NoSuchElementException if no element in {@code iterable} matches the - * given predicate - */ - public static T find(Iterable iterable, Predicate predicate) { - return Iterators.find(iterable.iterator(), predicate); - } - - /** - * Returns the first element in {@code iterable} that satisfies the given - * predicate, or {@code defaultValue} if none found. Note that this can usually - * be handled more naturally using {@code - * tryFind(iterable, predicate).or(defaultValue)}. - * - * @since 7.0 + * Removes and returns the first matching element, or returns {@code null} if + * there is none. */ @Nullable - public static T find(Iterable iterable, Predicate predicate, @Nullable T defaultValue) { - return Iterators.find(iterable.iterator(), predicate, defaultValue); + static T removeFirstMatching(Iterable removeFrom, Predicate predicate) { + checkNotNull(predicate); + Iterator iterator = removeFrom.iterator(); + while (iterator.hasNext()) { + T next = iterator.next(); + if (predicate.apply(next)) { + iterator.remove(); + return next; + } + } + return null; } /** - * Returns an {@link Optional} containing the first element in {@code - * iterable} that satisfies the given predicate, if such an element exists. + * Removes, from an iterable, every element that satisfies the provided + * predicate. * - *

- * Warning: avoid using a {@code predicate} that matches {@code - * null}. If {@code null} is matched in {@code iterable}, a NullPointerException - * will be thrown. - * - * @since 11.0 - */ - public static Optional tryFind(Iterable iterable, Predicate predicate) { - return Iterators.tryFind(iterable.iterator(), predicate); - } - - /** - * Returns the index in {@code iterable} of the first element that satisfies the - * provided {@code predicate}, or {@code -1} if the Iterable has no such - * elements. - * - *

- * More formally, returns the lowest index {@code i} such that - * {@code predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or - * {@code -1} if there is no such index. + * @param removeFrom the iterable to (potentially) remove elements from + * @param predicate a predicate that determines whether an element should be + * removed + * @return {@code true} if any elements were removed from the iterable * + * @throws UnsupportedOperationException if the iterable does not support + * {@code remove()}. * @since 2.0 */ - public static int indexOf(Iterable iterable, Predicate predicate) { - return Iterators.indexOf(iterable.iterator(), predicate); - } - - /** - * Returns an iterable that applies {@code function} to each element of {@code - * fromIterable}. - * - *

- * The returned iterable's iterator supports {@code remove()} if the provided - * iterator does. After a successful {@code remove()} call, {@code fromIterable} - * no longer contains the corresponding element. - * - *

- * If the input {@code Iterable} is known to be a {@code List} or other - * {@code Collection}, consider {@link Lists#transform} and - * {@link Collections2#transform}. - */ - public static Iterable transform(final Iterable fromIterable, - final Function function) { - checkNotNull(fromIterable); - checkNotNull(function); - return new FluentIterable() { - @Override - public Iterator iterator() { - return Iterators.transform(fromIterable.iterator(), function); - } - }; - } - - /** - * Returns the element at the specified position in an iterable. - * - * @param position position of the element to return - * @return the element at the specified position in {@code iterable} - * @throws IndexOutOfBoundsException if {@code position} is negative or greater - * than or equal to the size of - * {@code iterable} - */ - public static T get(Iterable iterable, int position) { - checkNotNull(iterable); - return (iterable instanceof List) ? ((List) iterable).get(position) - : Iterators.get(iterable.iterator(), position); - } - - /** - * Returns the element at the specified position in an iterable or a default - * value otherwise. - * - * @param position position of the element to return - * @param defaultValue the default value to return if {@code position} is - * greater than or equal to the size of the iterable - * @return the element at the specified position in {@code iterable} or - * {@code defaultValue} if {@code iterable} contains fewer than - * {@code position + 1} elements. - * @throws IndexOutOfBoundsException if {@code position} is negative - * @since 4.0 - */ - @Nullable - public static T get(Iterable iterable, int position, @Nullable T defaultValue) { - checkNotNull(iterable); - Iterators.checkNonnegative(position); - if (iterable instanceof List) { - List list = Lists.cast(iterable); - return (position < list.size()) ? list.get(position) : defaultValue; - } else { - Iterator iterator = iterable.iterator(); - Iterators.advance(iterator, position); - return Iterators.getNext(iterator, defaultValue); + public static boolean removeIf(Iterable removeFrom, Predicate predicate) { + if (removeFrom instanceof RandomAccess && removeFrom instanceof List) { + return removeIfFromRandomAccessList((List) removeFrom, checkNotNull(predicate)); } + return Iterators.removeIf(removeFrom.iterator(), predicate); } - /** - * Returns the first element in {@code iterable} or {@code defaultValue} if the - * iterable is empty. The {@link Iterators} analog to this method is - * {@link Iterators#getNext}. - * - *

- * If no default value is desired (and the caller instead wants a - * {@link NoSuchElementException} to be thrown), it is recommended that - * {@code iterable.iterator().next()} is used instead. - * - * @param defaultValue the default value to return if the iterable is empty - * @return the first element of {@code iterable} or the default value - * @since 7.0 - */ - @Nullable - public static T getFirst(Iterable iterable, @Nullable T defaultValue) { - return Iterators.getNext(iterable.iterator(), defaultValue); - } + private static boolean removeIfFromRandomAccessList(List list, Predicate predicate) { + // Note: Not all random access lists support set() so we need to deal with + // those that don't and attempt the slower remove() based solution. + int from = 0; + int to = 0; - /** - * Returns the last element of {@code iterable}. - * - * @return the last element of {@code iterable} - * @throws NoSuchElementException if the iterable is empty - */ - public static T getLast(Iterable iterable) { - // TODO(kevinb): Support a concurrently modified collection? - if (iterable instanceof List) { - List list = (List) iterable; - if (list.isEmpty()) { - throw new NoSuchElementException(); - } - return getLastInNonemptyList(list); - } - - return Iterators.getLast(iterable.iterator()); - } - - /** - * Returns the last element of {@code iterable} or {@code defaultValue} if the - * iterable is empty. - * - * @param defaultValue the value to return if {@code iterable} is empty - * @return the last element of {@code iterable} or the default value - * @since 3.0 - */ - @Nullable - public static T getLast(Iterable iterable, @Nullable T defaultValue) { - if (iterable instanceof Collection) { - Collection c = Collections2.cast(iterable); - if (c.isEmpty()) { - return defaultValue; - } else if (iterable instanceof List) { - return getLastInNonemptyList(Lists.cast(iterable)); + for (; from < list.size(); from++) { + T element = list.get(from); + if (!predicate.apply(element)) { + if (from > to) { + try { + list.set(to, element); + } catch (UnsupportedOperationException e) { + slowRemoveIfForRemainingElements(list, predicate, to, from); + return true; + } + } + to++; } } - return Iterators.getLast(iterable.iterator(), defaultValue); + // Clear the tail of any remaining items + list.subList(to, list.size()).clear(); + return from != to; } - private static T getLastInNonemptyList(List list) { - return list.get(list.size() - 1); + /** + * Removes, from an iterable, every element that does not belong to the provided + * collection. + * + *

+ * This method calls {@link Collection#retainAll} if {@code iterable} is a + * collection, and {@link Iterators#retainAll} otherwise. + * + * @param removeFrom the iterable to (potentially) remove elements from + * @param elementsToRetain the elements to retain + * @return {@code true} if any element was removed from {@code iterable} + */ + public static boolean retainAll(Iterable removeFrom, Collection elementsToRetain) { + return (removeFrom instanceof Collection) + ? ((Collection) removeFrom).retainAll(checkNotNull(elementsToRetain)) + : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); + } + + /** + * Returns the number of elements in {@code iterable}. + */ + public static int size(Iterable iterable) { + return (iterable instanceof Collection) ? ((Collection) iterable).size() + : Iterators.size(iterable.iterator()); } /** @@ -888,141 +889,62 @@ public final class Iterables { }; } - /** - * Creates an iterable with the first {@code limitSize} elements of the given - * iterable. If the original iterable does not contain that many elements, the - * returned iterable will have the same behavior as the original iterable. The - * returned iterable's iterator supports {@code remove()} if the original - * iterator does. - * - * @param iterable the iterable to limit - * @param limitSize the maximum number of elements in the returned iterable - * @throws IllegalArgumentException if {@code limitSize} is negative - * @since 3.0 - */ - public static Iterable limit(final Iterable iterable, final int limitSize) { - checkNotNull(iterable); - checkArgument(limitSize >= 0, "limit is negative"); - return new FluentIterable() { - @Override - public Iterator iterator() { - return Iterators.limit(iterable.iterator(), limitSize); + private static void slowRemoveIfForRemainingElements(List list, Predicate predicate, int to, + int from) { + // Here we know that: + // * (to < from) and that both are valid indices. + // * Everything with (index < to) should be kept. + // * Everything with (to <= index < from) should be removed. + // * The element with (index == from) should be kept. + // * Everything with (index > from) has not been checked yet. + + // Check from the end of the list backwards (minimize expected cost of + // moving elements when remove() is called). Stop before 'from' because + // we already know that should be kept. + for (int n = list.size() - 1; n > from; n--) { + if (predicate.apply(list.get(n))) { + list.remove(n); } - }; - } - - /** - * Returns a view of the supplied iterable that wraps each generated - * {@link Iterator} through {@link Iterators#consumingIterator(Iterator)}. - * - *

- * Note: If {@code iterable} is a {@link Queue}, the returned iterable will get - * entries from {@link Queue#remove()} since {@link Queue}'s iteration order is - * undefined. Calling {@link Iterator#hasNext()} on a generated iterator from - * the returned iterable may cause an item to be immediately dequeued for return - * on a subsequent call to {@link Iterator#next()}. - * - * @param iterable the iterable to wrap - * @return a view of the supplied iterable that wraps each generated iterator - * through {@link Iterators#consumingIterator(Iterator)}; for queues, an - * iterable that generates iterators that return and consume the queue's - * elements in queue order - * - * @see Iterators#consumingIterator(Iterator) - * @since 2.0 - */ - public static Iterable consumingIterable(final Iterable iterable) { - if (iterable instanceof Queue) { - return new FluentIterable() { - @Override - public Iterator iterator() { - return new ConsumingQueueIterator((Queue) iterable); - } - - @Override - public String toString() { - return "Iterables.consumingIterable(...)"; - } - }; } - - checkNotNull(iterable); - - return new FluentIterable() { - @Override - public Iterator iterator() { - return Iterators.consumingIterator(iterable.iterator()); - } - - @Override - public String toString() { - return "Iterables.consumingIterable(...)"; - } - }; - } - - private static class ConsumingQueueIterator extends AbstractIterator { - private final Queue queue; - - private ConsumingQueueIterator(Queue queue) { - this.queue = queue; - } - - @Override - public T computeNext() { - try { - return queue.remove(); - } catch (NoSuchElementException e) { - return endOfData(); - } + // And now remove everything in the range [to, from) (going backwards). + for (int n = from - 1; n >= to; n--) { + list.remove(n); } } - // Methods only in Iterables, not in Iterators - /** - * Determines if the given iterable contains no elements. + * Copies an iterable's elements into an array. * - *

- * There is no precise {@link Iterator} equivalent to this method, since one can - * only ask an iterator whether it has any elements remaining (which one - * does using {@link Iterator#hasNext}). - * - * @return {@code true} if the iterable contains no elements + * @param iterable the iterable to copy + * @return a newly-allocated array into which all the elements of the iterable + * have been copied */ - public static boolean isEmpty(Iterable iterable) { - if (iterable instanceof Collection) { - return ((Collection) iterable).isEmpty(); - } - return !iterable.iterator().hasNext(); + static Object[] toArray(Iterable iterable) { + return toCollection(iterable).toArray(); } /** - * Returns an iterable over the merged contents of all given {@code iterables}. - * Equivalent entries will not be de-duplicated. + * Copies an iterable's elements into an array. * - *

- * Callers must ensure that the source {@code iterables} are in non-descending - * order as this method does not sort its input. - * - *

- * For any equivalent elements across all {@code iterables}, it is undefined - * which element is returned first. - * - * @since 11.0 + * @param iterable the iterable to copy + * @param type the type of the elements + * @return a newly-allocated array into which all the elements of the iterable + * have been copied */ - @Beta - public static Iterable mergeSorted(final Iterable> iterables, - final Comparator comparator) { - checkNotNull(iterables, "iterables"); - checkNotNull(comparator, "comparator"); - Iterable iterable = new FluentIterable() { - @Override - public Iterator iterator() { - return Iterators.mergeSorted(Iterables.transform(iterables, Iterables.toIterator()), comparator); - } - }; - return new UnmodifiableIterable(iterable); + @GwtIncompatible("Array.newInstance(Class, int)") + public static T[] toArray(Iterable iterable, Class type) { + Collection collection = toCollection(iterable); + T[] array = ObjectArrays.newArray(type, collection.size()); + return collection.toArray(array); + } + + /** + * Converts an iterable into a collection. If the iterable is already a + * collection, it is returned. Otherwise, an {@link java.util.ArrayList} is + * created with the contents of the iterable in the same iteration order. + */ + private static Collection toCollection(Iterable iterable) { + return (iterable instanceof Collection) ? (Collection) iterable : Lists.newArrayList(iterable.iterator()); } // TODO(user): Is this the best place for this? Move to fluent functions? @@ -1035,4 +957,82 @@ public final class Iterables { } }; } + + /** + * Returns a string representation of {@code iterable}, with the format {@code + * [e1, e2, ..., en]} (that is, identical to {@link java.util.Arrays + * Arrays}{@code .toString(Iterables.toArray(iterable))}). Note that for + * most implementations of {@link Collection}, {@code + * collection.toString()} also gives the same result, but that behavior is not + * generally guaranteed. + */ + public static String toString(Iterable iterable) { + return Iterators.toString(iterable.iterator()); + } + + /** + * Returns an iterable that applies {@code function} to each element of {@code + * fromIterable}. + * + *

+ * The returned iterable's iterator supports {@code remove()} if the provided + * iterator does. After a successful {@code remove()} call, {@code fromIterable} + * no longer contains the corresponding element. + * + *

+ * If the input {@code Iterable} is known to be a {@code List} or other + * {@code Collection}, consider {@link Lists#transform} and + * {@link Collections2#transform}. + */ + public static Iterable transform(final Iterable fromIterable, + final Function function) { + checkNotNull(fromIterable); + checkNotNull(function); + return new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.transform(fromIterable.iterator(), function); + } + }; + } + + /** + * Returns an {@link Optional} containing the first element in {@code + * iterable} that satisfies the given predicate, if such an element exists. + * + *

+ * Warning: avoid using a {@code predicate} that matches {@code + * null}. If {@code null} is matched in {@code iterable}, a NullPointerException + * will be thrown. + * + * @since 11.0 + */ + public static Optional tryFind(Iterable iterable, Predicate predicate) { + return Iterators.tryFind(iterable.iterator(), predicate); + } + + // Methods only in Iterables, not in Iterators + + /** + * Simply returns its argument. + * + * @deprecated no need to use this + * @since 10.0 + */ + @Deprecated + public static Iterable unmodifiableIterable(ImmutableCollection iterable) { + return checkNotNull(iterable); + } + + /** Returns an unmodifiable view of {@code iterable}. */ + public static Iterable unmodifiableIterable(final Iterable iterable) { + checkNotNull(iterable); + if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { + return iterable; + } + return new UnmodifiableIterable(iterable); + } + + private Iterables() { + } } diff --git a/src/main/java/com/google/common/collect/Iterators.java b/src/main/java/com/google/common/collect/Iterators.java index 7a6609be..ddaa5b07 100644 --- a/src/main/java/com/google/common/collect/Iterators.java +++ b/src/main/java/com/google/common/collect/Iterators.java @@ -69,7 +69,98 @@ import com.google.common.base.Predicate; */ @GwtCompatible(emulated = true) public final class Iterators { - private Iterators() { + /** + * An iterator that performs a lazy N-way merge, calculating the next value each + * time the iterator is polled. This amortizes the sorting cost over the + * iteration and requires less memory than sorting all elements at once. + * + *

+ * Retrieving a single element takes approximately O(log(M)) time, where M is + * the number of iterators. (Retrieving all elements takes approximately + * O(N*log(M)) time, where N is the total number of elements.) + */ + private static class MergingIterator extends UnmodifiableIterator { + final Queue> queue; + + public MergingIterator(Iterable> iterators, + final Comparator itemComparator) { + // A comparator that's used by the heap, allowing the heap + // to be sorted based on the top of each iterator. + Comparator> heapComparator = new Comparator>() { + @Override + public int compare(PeekingIterator o1, PeekingIterator o2) { + return itemComparator.compare(o1.peek(), o2.peek()); + } + }; + + queue = new PriorityQueue>(2, heapComparator); + + for (Iterator iterator : iterators) { + if (iterator.hasNext()) { + queue.add(Iterators.peekingIterator(iterator)); + } + } + } + + @Override + public boolean hasNext() { + return !queue.isEmpty(); + } + + @Override + public T next() { + PeekingIterator nextIter = queue.remove(); + T next = nextIter.next(); + if (nextIter.hasNext()) { + queue.add(nextIter); + } + return next; + } + } + + /** + * Implementation of PeekingIterator that avoids peeking unless necessary. + */ + private static class PeekingImpl implements PeekingIterator { + + private final Iterator iterator; + private boolean hasPeeked; + private E peekedElement; + + public PeekingImpl(Iterator iterator) { + this.iterator = checkNotNull(iterator); + } + + @Override + public boolean hasNext() { + return hasPeeked || iterator.hasNext(); + } + + @Override + public E next() { + if (!hasPeeked) { + return iterator.next(); + } + E result = peekedElement; + hasPeeked = false; + peekedElement = null; + return result; + } + + @Override + public E peek() { + if (!hasPeeked) { + peekedElement = iterator.next(); + hasPeeked = true; + } + return peekedElement; + } + + @Override + public void remove() { + checkState(!hasPeeked, "Can't remove after you've peeked at next"); + iterator.remove(); + } } static final UnmodifiableListIterator EMPTY_LIST_ITERATOR = new UnmodifiableListIterator() { @@ -78,18 +169,13 @@ public final class Iterators { return false; } - @Override - public Object next() { - throw new NoSuchElementException(); - } - @Override public boolean hasPrevious() { return false; } @Override - public Object previous() { + public Object next() { throw new NoSuchElementException(); } @@ -98,34 +184,17 @@ public final class Iterators { return 0; } + @Override + public Object previous() { + throw new NoSuchElementException(); + } + @Override public int previousIndex() { return -1; } }; - /** - * Returns the empty iterator. - * - *

- * The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}. - */ - public static UnmodifiableIterator emptyIterator() { - return emptyListIterator(); - } - - /** - * Returns the empty iterator. - * - *

- * The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}. - */ - // Casting to any type is safe since there are no actual elements. - @SuppressWarnings("unchecked") - static UnmodifiableListIterator emptyListIterator() { - return (UnmodifiableListIterator) EMPTY_LIST_ITERATOR; - } - private static final Iterator EMPTY_MODIFIABLE_ITERATOR = new Iterator() { @Override public boolean hasNext() { @@ -143,203 +212,6 @@ public final class Iterators { } }; - /** - * Returns the empty {@code Iterator} that throws {@link IllegalStateException} - * instead of {@link UnsupportedOperationException} on a call to - * {@link Iterator#remove()}. - */ - // Casting to any type is safe since there are no actual elements. - @SuppressWarnings("unchecked") - static Iterator emptyModifiableIterator() { - return (Iterator) EMPTY_MODIFIABLE_ITERATOR; - } - - /** Returns an unmodifiable view of {@code iterator}. */ - public static UnmodifiableIterator unmodifiableIterator(final Iterator iterator) { - checkNotNull(iterator); - if (iterator instanceof UnmodifiableIterator) { - return (UnmodifiableIterator) iterator; - } - return new UnmodifiableIterator() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - return iterator.next(); - } - }; - } - - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ - @Deprecated - public static UnmodifiableIterator unmodifiableIterator(UnmodifiableIterator iterator) { - return checkNotNull(iterator); - } - - /** - * Returns the number of elements remaining in {@code iterator}. The iterator - * will be left exhausted: its {@code hasNext()} method will return - * {@code false}. - */ - public static int size(Iterator iterator) { - int count = 0; - while (iterator.hasNext()) { - iterator.next(); - count++; - } - return count; - } - - /** - * Returns {@code true} if {@code iterator} contains {@code element}. - */ - public static boolean contains(Iterator iterator, @Nullable Object element) { - return any(iterator, equalTo(element)); - } - - /** - * Traverses an iterator and removes every element that belongs to the provided - * collection. The iterator will be left exhausted: its {@code hasNext()} method - * will return {@code false}. - * - * @param removeFrom the iterator to (potentially) remove elements from - * @param elementsToRemove the elements to remove - * @return {@code true} if any element was removed from {@code iterator} - */ - public static boolean removeAll(Iterator removeFrom, Collection elementsToRemove) { - return removeIf(removeFrom, in(elementsToRemove)); - } - - /** - * Removes every element that satisfies the provided predicate from the - * iterator. The iterator will be left exhausted: its {@code hasNext()} method - * will return {@code false}. - * - * @param removeFrom the iterator to (potentially) remove elements from - * @param predicate a predicate that determines whether an element should be - * removed - * @return {@code true} if any elements were removed from the iterator - * @since 2.0 - */ - public static boolean removeIf(Iterator removeFrom, Predicate predicate) { - checkNotNull(predicate); - boolean modified = false; - while (removeFrom.hasNext()) { - if (predicate.apply(removeFrom.next())) { - removeFrom.remove(); - modified = true; - } - } - return modified; - } - - /** - * Traverses an iterator and removes every element that does not belong to the - * provided collection. The iterator will be left exhausted: its - * {@code hasNext()} method will return {@code false}. - * - * @param removeFrom the iterator to (potentially) remove elements from - * @param elementsToRetain the elements to retain - * @return {@code true} if any element was removed from {@code iterator} - */ - public static boolean retainAll(Iterator removeFrom, Collection elementsToRetain) { - return removeIf(removeFrom, not(in(elementsToRetain))); - } - - /** - * Determines whether two iterators contain equal elements in the same order. - * More specifically, this method returns {@code true} if {@code iterator1} and - * {@code iterator2} contain the same number of elements and every element of - * {@code iterator1} is equal to the corresponding element of {@code iterator2}. - * - *

- * Note that this will modify the supplied iterators, since they will have been - * advanced some number of elements forward. - */ - public static boolean elementsEqual(Iterator iterator1, Iterator iterator2) { - while (iterator1.hasNext()) { - if (!iterator2.hasNext()) { - return false; - } - Object o1 = iterator1.next(); - Object o2 = iterator2.next(); - if (!Objects.equal(o1, o2)) { - return false; - } - } - return !iterator2.hasNext(); - } - - /** - * Returns a string representation of {@code iterator}, with the format - * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its - * {@code hasNext()} method will return {@code false}. - */ - public static String toString(Iterator iterator) { - return Collections2.STANDARD_JOINER.appendTo(new StringBuilder().append('['), iterator).append(']').toString(); - } - - /** - * Returns the single element contained in {@code iterator}. - * - * @throws NoSuchElementException if the iterator is empty - * @throws IllegalArgumentException if the iterator contains multiple elements. - * The state of the iterator is unspecified. - */ - public static T getOnlyElement(Iterator iterator) { - T first = iterator.next(); - if (!iterator.hasNext()) { - return first; - } - - StringBuilder sb = new StringBuilder(); - sb.append("expected one element but was: <" + first); - for (int i = 0; i < 4 && iterator.hasNext(); i++) { - sb.append(", " + iterator.next()); - } - if (iterator.hasNext()) { - sb.append(", ..."); - } - sb.append('>'); - - throw new IllegalArgumentException(sb.toString()); - } - - /** - * Returns the single element contained in {@code iterator}, or {@code - * defaultValue} if the iterator is empty. - * - * @throws IllegalArgumentException if the iterator contains multiple elements. - * The state of the iterator is unspecified. - */ - @Nullable - public static T getOnlyElement(Iterator iterator, @Nullable T defaultValue) { - return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; - } - - /** - * Copies an iterator's elements into an array. The iterator will be left - * exhausted: its {@code hasNext()} method will return {@code false}. - * - * @param iterator the iterator to copy - * @param type the type of the elements - * @return a newly-allocated array into which all the elements of the iterator - * have been copied - */ - @GwtIncompatible("Array.newInstance(Class, int)") - public static T[] toArray(Iterator iterator, Class type) { - List list = Lists.newArrayList(iterator); - return Iterables.toArray(list, type); - } - /** * Adds all elements in {@code iterator} to {@code collection}. The iterator * will be left exhausted: its {@code hasNext()} method will return @@ -359,14 +231,272 @@ public final class Iterators { } /** - * Returns the number of elements in the specified iterator that equal the - * specified object. The iterator will be left exhausted: its {@code hasNext()} - * method will return {@code false}. + * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} + * times or until {@code hasNext()} returns {@code false}, whichever comes + * first. * - * @see Collections#frequency + * @return the number of elements the iterator was advanced + * @since 13.0 (since 3.0 as {@code Iterators.skip}) */ - public static int frequency(Iterator iterator, @Nullable Object element) { - return size(filter(iterator, equalTo(element))); + public static int advance(Iterator iterator, int numberToAdvance) { + checkNotNull(iterator); + checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative"); + + int i; + for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) { + iterator.next(); + } + return i; + } + + /** + * Returns {@code true} if every element returned by {@code iterator} satisfies + * the given predicate. If {@code iterator} is empty, {@code true} is returned. + */ + public static boolean all(Iterator iterator, Predicate predicate) { + checkNotNull(predicate); + while (iterator.hasNext()) { + T element = iterator.next(); + if (!predicate.apply(element)) { + return false; + } + } + return true; + } + + /** + * Returns {@code true} if one or more elements returned by {@code iterator} + * satisfy the given predicate. + */ + public static boolean any(Iterator iterator, Predicate predicate) { + return indexOf(iterator, predicate) != -1; + } + + /** + * Adapts an {@code Iterator} to the {@code Enumeration} interface. + * + *

+ * The {@code Iterable} equivalent of this method is either + * {@link Collections#enumeration} (if you have a {@link Collection}), or + * {@code Iterators.asEnumeration(collection.iterator())}. + */ + public static Enumeration asEnumeration(final Iterator iterator) { + checkNotNull(iterator); + return new Enumeration() { + @Override + public boolean hasMoreElements() { + return iterator.hasNext(); + } + + @Override + public T nextElement() { + return iterator.next(); + } + }; + } + + /** + * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + */ + static ListIterator cast(Iterator iterator) { + return (ListIterator) iterator; + } + + static void checkNonnegative(int position) { + if (position < 0) { + throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); + } + } + + /** + * Clears the iterator using its remove method. + */ + static void clear(Iterator iterator) { + checkNotNull(iterator); + while (iterator.hasNext()) { + iterator.next(); + iterator.remove(); + } + } + + /** + * Combines multiple iterators into a single iterator. The returned iterator + * iterates across the elements of each iterator in {@code inputs}. The input + * iterators are not polled until necessary. + * + *

+ * The returned iterator supports {@code remove()} when the corresponding input + * iterator supports it. The methods of the returned iterator may throw + * {@code NullPointerException} if any of the input iterators is null. + * + *

+ * Note: the current implementation is not suitable for nested + * concatenated iterators, i.e. the following should be avoided when in a loop: + * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over + * the resulting iterator has a cubic complexity to the depth of the nesting. + */ + public static Iterator concat(final Iterator> inputs) { + checkNotNull(inputs); + return new Iterator() { + Iterator current = emptyIterator(); + Iterator removeFrom; + + @Override + public boolean hasNext() { + // http://code.google.com/p/google-collections/issues/detail?id=151 + // current.hasNext() might be relatively expensive, worth minimizing. + boolean currentHasNext; + // checkNotNull eager for GWT + // note: it must be here & not where 'current' is assigned, + // because otherwise we'll have called inputs.next() before throwing + // the first NPE, and the next time around we'll call inputs.next() + // again, incorrectly moving beyond the error. + while (!(currentHasNext = checkNotNull(current).hasNext()) && inputs.hasNext()) { + current = inputs.next(); + } + return currentHasNext; + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + removeFrom = current; + return current.next(); + } + + @Override + public void remove() { + checkRemove(removeFrom != null); + removeFrom.remove(); + removeFrom = null; + } + }; + } + + /** + * Combines multiple iterators into a single iterator. The returned iterator + * iterates across the elements of each iterator in {@code inputs}. The input + * iterators are not polled until necessary. + * + *

+ * The returned iterator supports {@code remove()} when the corresponding input + * iterator supports it. + * + *

+ * Note: the current implementation is not suitable for nested + * concatenated iterators, i.e. the following should be avoided when in a loop: + * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over + * the resulting iterator has a cubic complexity to the depth of the nesting. + * + * @throws NullPointerException if any of the provided iterators is null + */ + public static Iterator concat(Iterator... inputs) { + return concat(ImmutableList.copyOf(inputs).iterator()); + } + + /** + * Combines two iterators into a single iterator. The returned iterator iterates + * across the elements in {@code a}, followed by the elements in {@code b}. The + * source iterators are not polled until necessary. + * + *

+ * The returned iterator supports {@code remove()} when the corresponding input + * iterator supports it. + * + *

+ * Note: the current implementation is not suitable for nested + * concatenated iterators, i.e. the following should be avoided when in a loop: + * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over + * the resulting iterator has a cubic complexity to the depth of the nesting. + */ + public static Iterator concat(Iterator a, Iterator b) { + return concat(ImmutableList.of(a, b).iterator()); + } + + /** + * Combines three iterators into a single iterator. The returned iterator + * iterates across the elements in {@code a}, followed by the elements in + * {@code b}, followed by the elements in {@code c}. The source iterators are + * not polled until necessary. + * + *

+ * The returned iterator supports {@code remove()} when the corresponding input + * iterator supports it. + * + *

+ * Note: the current implementation is not suitable for nested + * concatenated iterators, i.e. the following should be avoided when in a loop: + * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over + * the resulting iterator has a cubic complexity to the depth of the nesting. + */ + public static Iterator concat(Iterator a, Iterator b, Iterator c) { + return concat(ImmutableList.of(a, b, c).iterator()); + } + + /** + * Combines four iterators into a single iterator. The returned iterator + * iterates across the elements in {@code a}, followed by the elements in + * {@code b}, followed by the elements in {@code c}, followed by the elements in + * {@code d}. The source iterators are not polled until necessary. + * + *

+ * The returned iterator supports {@code remove()} when the corresponding input + * iterator supports it. + * + *

+ * Note: the current implementation is not suitable for nested + * concatenated iterators, i.e. the following should be avoided when in a loop: + * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over + * the resulting iterator has a cubic complexity to the depth of the nesting. + */ + public static Iterator concat(Iterator a, Iterator b, Iterator c, + Iterator d) { + return concat(ImmutableList.of(a, b, c, d).iterator()); + } + + /** + * Returns a view of the supplied {@code iterator} that removes each element + * from the supplied {@code iterator} as it is returned. + * + *

+ * The provided iterator must support {@link Iterator#remove()} or else the + * returned iterator will fail on the first call to {@code + * next}. + * + * @param iterator the iterator to remove and return elements from + * @return an iterator that removes and returns elements from the supplied + * iterator + * @since 2.0 + */ + public static Iterator consumingIterator(final Iterator iterator) { + checkNotNull(iterator); + return new UnmodifiableIterator() { + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public T next() { + T next = iterator.next(); + iterator.remove(); + return next; + } + + @Override + public String toString() { + return "Iterators.consumingIterator(...)"; + } + }; + } + + /** + * Returns {@code true} if {@code iterator} contains {@code element}. + */ + public static boolean contains(Iterator iterator, @Nullable Object element) { + return any(iterator, equalTo(element)); } /** @@ -436,212 +566,76 @@ public final class Iterators { } /** - * Combines two iterators into a single iterator. The returned iterator iterates - * across the elements in {@code a}, followed by the elements in {@code b}. The - * source iterators are not polled until necessary. + * Determines whether two iterators contain equal elements in the same order. + * More specifically, this method returns {@code true} if {@code iterator1} and + * {@code iterator2} contain the same number of elements and every element of + * {@code iterator1} is equal to the corresponding element of {@code iterator2}. * *

- * The returned iterator supports {@code remove()} when the corresponding input - * iterator supports it. - * - *

- * Note: the current implementation is not suitable for nested - * concatenated iterators, i.e. the following should be avoided when in a loop: - * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over - * the resulting iterator has a cubic complexity to the depth of the nesting. + * Note that this will modify the supplied iterators, since they will have been + * advanced some number of elements forward. */ - public static Iterator concat(Iterator a, Iterator b) { - return concat(ImmutableList.of(a, b).iterator()); - } - - /** - * Combines three iterators into a single iterator. The returned iterator - * iterates across the elements in {@code a}, followed by the elements in - * {@code b}, followed by the elements in {@code c}. The source iterators are - * not polled until necessary. - * - *

- * The returned iterator supports {@code remove()} when the corresponding input - * iterator supports it. - * - *

- * Note: the current implementation is not suitable for nested - * concatenated iterators, i.e. the following should be avoided when in a loop: - * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over - * the resulting iterator has a cubic complexity to the depth of the nesting. - */ - public static Iterator concat(Iterator a, Iterator b, Iterator c) { - return concat(ImmutableList.of(a, b, c).iterator()); - } - - /** - * Combines four iterators into a single iterator. The returned iterator - * iterates across the elements in {@code a}, followed by the elements in - * {@code b}, followed by the elements in {@code c}, followed by the elements in - * {@code d}. The source iterators are not polled until necessary. - * - *

- * The returned iterator supports {@code remove()} when the corresponding input - * iterator supports it. - * - *

- * Note: the current implementation is not suitable for nested - * concatenated iterators, i.e. the following should be avoided when in a loop: - * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over - * the resulting iterator has a cubic complexity to the depth of the nesting. - */ - public static Iterator concat(Iterator a, Iterator b, Iterator c, - Iterator d) { - return concat(ImmutableList.of(a, b, c, d).iterator()); - } - - /** - * Combines multiple iterators into a single iterator. The returned iterator - * iterates across the elements of each iterator in {@code inputs}. The input - * iterators are not polled until necessary. - * - *

- * The returned iterator supports {@code remove()} when the corresponding input - * iterator supports it. - * - *

- * Note: the current implementation is not suitable for nested - * concatenated iterators, i.e. the following should be avoided when in a loop: - * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over - * the resulting iterator has a cubic complexity to the depth of the nesting. - * - * @throws NullPointerException if any of the provided iterators is null - */ - public static Iterator concat(Iterator... inputs) { - return concat(ImmutableList.copyOf(inputs).iterator()); - } - - /** - * Combines multiple iterators into a single iterator. The returned iterator - * iterates across the elements of each iterator in {@code inputs}. The input - * iterators are not polled until necessary. - * - *

- * The returned iterator supports {@code remove()} when the corresponding input - * iterator supports it. The methods of the returned iterator may throw - * {@code NullPointerException} if any of the input iterators is null. - * - *

- * Note: the current implementation is not suitable for nested - * concatenated iterators, i.e. the following should be avoided when in a loop: - * {@code iterator = Iterators.concat(iterator, suffix);}, since iteration over - * the resulting iterator has a cubic complexity to the depth of the nesting. - */ - public static Iterator concat(final Iterator> inputs) { - checkNotNull(inputs); - return new Iterator() { - Iterator current = emptyIterator(); - Iterator removeFrom; - - @Override - public boolean hasNext() { - // http://code.google.com/p/google-collections/issues/detail?id=151 - // current.hasNext() might be relatively expensive, worth minimizing. - boolean currentHasNext; - // checkNotNull eager for GWT - // note: it must be here & not where 'current' is assigned, - // because otherwise we'll have called inputs.next() before throwing - // the first NPE, and the next time around we'll call inputs.next() - // again, incorrectly moving beyond the error. - while (!(currentHasNext = checkNotNull(current).hasNext()) && inputs.hasNext()) { - current = inputs.next(); - } - return currentHasNext; + public static boolean elementsEqual(Iterator iterator1, Iterator iterator2) { + while (iterator1.hasNext()) { + if (!iterator2.hasNext()) { + return false; } - - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - removeFrom = current; - return current.next(); + Object o1 = iterator1.next(); + Object o2 = iterator2.next(); + if (!Objects.equal(o1, o2)) { + return false; } - - @Override - public void remove() { - checkRemove(removeFrom != null); - removeFrom.remove(); - removeFrom = null; - } - }; + } + return !iterator2.hasNext(); } /** - * Divides an iterator into unmodifiable sublists of the given size (the final - * list may be smaller). For example, partitioning an iterator containing - * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code - * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of three - * and two elements, all in the original order. + * Returns the empty iterator. * *

- * The returned lists implement {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. - * - * @param iterator the iterator to return a partitioned view of - * @param size the desired size of each partition (the last may be smaller) - * @return an iterator of immutable lists containing the elements of {@code - * iterator} divided into partitions - * @throws IllegalArgumentException if {@code size} is nonpositive + * The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}. */ - public static UnmodifiableIterator> partition(Iterator iterator, int size) { - return partitionImpl(iterator, size, false); + public static UnmodifiableIterator emptyIterator() { + return emptyListIterator(); } /** - * Divides an iterator into unmodifiable sublists of the given size, padding the - * final iterator with null values if necessary. For example, partitioning an - * iterator containing {@code [a, b, c, d, e]} with a partition size of 3 yields - * {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing two inner - * lists of three elements each, all in the original order. + * Returns the empty iterator. * *

- * The returned lists implement {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. - * - * @param iterator the iterator to return a partitioned view of - * @param size the desired size of each partition - * @return an iterator of immutable lists containing the elements of {@code - * iterator} divided into partitions (the final iterable may have trailing - * null elements) - * @throws IllegalArgumentException if {@code size} is nonpositive + * The {@link Iterable} equivalent of this method is {@link ImmutableSet#of()}. */ - public static UnmodifiableIterator> paddedPartition(Iterator iterator, int size) { - return partitionImpl(iterator, size, true); + // Casting to any type is safe since there are no actual elements. + @SuppressWarnings("unchecked") + static UnmodifiableListIterator emptyListIterator() { + return (UnmodifiableListIterator) EMPTY_LIST_ITERATOR; } - private static UnmodifiableIterator> partitionImpl(final Iterator iterator, final int size, - final boolean pad) { - checkNotNull(iterator); - checkArgument(size > 0); - return new UnmodifiableIterator>() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } + /** + * Returns the empty {@code Iterator} that throws {@link IllegalStateException} + * instead of {@link UnsupportedOperationException} on a call to + * {@link Iterator#remove()}. + */ + // Casting to any type is safe since there are no actual elements. + @SuppressWarnings("unchecked") + static Iterator emptyModifiableIterator() { + return (Iterator) EMPTY_MODIFIABLE_ITERATOR; + } - @Override - public List next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - Object[] array = new Object[size]; - int count = 0; - for (; count < size && iterator.hasNext(); count++) { - array[count] = iterator.next(); - } - for (int i = count; i < size; i++) { - array[i] = null; // for GWT - } - - @SuppressWarnings("unchecked") // we only put Ts in it - List list = Collections.unmodifiableList((List) Arrays.asList(array)); - return (pad || count == size) ? list : list.subList(0, count); - } - }; + /** + * Returns all instances of class {@code type} in {@code unfiltered}. The + * returned iterator has elements whose class is {@code type} or a subclass of + * {@code type}. + * + * @param unfiltered an iterator containing objects of any type + * @param type the type of elements desired + * @return an unmodifiable iterator containing all elements of the original + * iterator that were of the requested type + */ + @SuppressWarnings("unchecked") // can cast to because non-Ts are removed + @GwtIncompatible("Class.isInstance") + public static UnmodifiableIterator filter(Iterator unfiltered, Class type) { + return (UnmodifiableIterator) filter(unfiltered, instanceOf(type)); } /** @@ -665,60 +659,6 @@ public final class Iterators { }; } - /** - * Returns all instances of class {@code type} in {@code unfiltered}. The - * returned iterator has elements whose class is {@code type} or a subclass of - * {@code type}. - * - * @param unfiltered an iterator containing objects of any type - * @param type the type of elements desired - * @return an unmodifiable iterator containing all elements of the original - * iterator that were of the requested type - */ - @SuppressWarnings("unchecked") // can cast to because non-Ts are removed - @GwtIncompatible("Class.isInstance") - public static UnmodifiableIterator filter(Iterator unfiltered, Class type) { - return (UnmodifiableIterator) filter(unfiltered, instanceOf(type)); - } - - /** - * Returns {@code true} if one or more elements returned by {@code iterator} - * satisfy the given predicate. - */ - public static boolean any(Iterator iterator, Predicate predicate) { - return indexOf(iterator, predicate) != -1; - } - - /** - * Returns {@code true} if every element returned by {@code iterator} satisfies - * the given predicate. If {@code iterator} is empty, {@code true} is returned. - */ - public static boolean all(Iterator iterator, Predicate predicate) { - checkNotNull(predicate); - while (iterator.hasNext()) { - T element = iterator.next(); - if (!predicate.apply(element)) { - return false; - } - } - return true; - } - - /** - * Returns the first element in {@code iterator} that satisfies the given - * predicate; use this method only when such an element is known to exist. If no - * such element is found, the iterator will be left exhausted: its {@code - * hasNext()} method will return {@code false}. If it is possible that no - * element will match, use {@link #tryFind} or - * {@link #find(Iterator, Predicate, Object)} instead. - * - * @throws NoSuchElementException if no element in {@code iterator} matches the - * given predicate - */ - public static T find(Iterator iterator, Predicate predicate) { - return filter(iterator, predicate).next(); - } - /** * Returns the first element in {@code iterator} that satisfies the given * predicate. If no such element is found, {@code defaultValue} will be returned @@ -735,281 +675,18 @@ public final class Iterators { } /** - * Returns an {@link Optional} containing the first element in {@code - * iterator} that satisfies the given predicate, if such an element exists. If - * no such element is found, an empty {@link Optional} will be returned from - * this method and the iterator will be left exhausted: its {@code - * hasNext()} method will return {@code false}. + * Returns the first element in {@code iterator} that satisfies the given + * predicate; use this method only when such an element is known to exist. If no + * such element is found, the iterator will be left exhausted: its {@code + * hasNext()} method will return {@code false}. If it is possible that no + * element will match, use {@link #tryFind} or + * {@link #find(Iterator, Predicate, Object)} instead. * - *

- * Warning: avoid using a {@code predicate} that matches {@code - * null}. If {@code null} is matched in {@code iterator}, a NullPointerException - * will be thrown. - * - * @since 11.0 + * @throws NoSuchElementException if no element in {@code iterator} matches the + * given predicate */ - public static Optional tryFind(Iterator iterator, Predicate predicate) { - UnmodifiableIterator filteredIterator = filter(iterator, predicate); - return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.absent(); - } - - /** - * Returns the index in {@code iterator} of the first element that satisfies the - * provided {@code predicate}, or {@code -1} if the Iterator has no such - * elements. - * - *

- * More formally, returns the lowest index {@code i} such that - * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true}, or - * {@code -1} if there is no such index. - * - *

- * If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} - * method will return {@code false}. Otherwise, the iterator will be set to the - * element which satisfies the {@code predicate}. - * - * @since 2.0 - */ - public static int indexOf(Iterator iterator, Predicate predicate) { - checkNotNull(predicate, "predicate"); - for (int i = 0; iterator.hasNext(); i++) { - T current = iterator.next(); - if (predicate.apply(current)) { - return i; - } - } - return -1; - } - - /** - * Returns an iterator that applies {@code function} to each element of {@code - * fromIterator}. - * - *

- * The returned iterator supports {@code remove()} if the provided iterator - * does. After a successful {@code remove()} call, {@code fromIterator} no - * longer contains the corresponding element. - */ - public static Iterator transform(final Iterator fromIterator, - final Function function) { - checkNotNull(function); - return new TransformedIterator(fromIterator) { - @Override - T transform(F from) { - return function.apply(from); - } - }; - } - - /** - * Advances {@code iterator} {@code position + 1} times, returning the element - * at the {@code position}th position. - * - * @param position position of the element to return - * @return the element at the specified position in {@code iterator} - * @throws IndexOutOfBoundsException if {@code position} is negative or greater - * than or equal to the number of elements - * remaining in {@code iterator} - */ - public static T get(Iterator iterator, int position) { - checkNonnegative(position); - int skipped = advance(iterator, position); - if (!iterator.hasNext()) { - throw new IndexOutOfBoundsException("position (" + position - + ") must be less than the number of elements that remained (" + skipped + ")"); - } - return iterator.next(); - } - - static void checkNonnegative(int position) { - if (position < 0) { - throw new IndexOutOfBoundsException("position (" + position + ") must not be negative"); - } - } - - /** - * Advances {@code iterator} {@code position + 1} times, returning the element - * at the {@code position}th position or {@code defaultValue} otherwise. - * - * @param position position of the element to return - * @param defaultValue the default value to return if the iterator is empty or - * if {@code position} is greater than the number of - * elements remaining in {@code iterator} - * @return the element at the specified position in {@code iterator} or - * {@code defaultValue} if {@code iterator} produces fewer than - * {@code position + 1} elements. - * @throws IndexOutOfBoundsException if {@code position} is negative - * @since 4.0 - */ - @Nullable - public static T get(Iterator iterator, int position, @Nullable T defaultValue) { - checkNonnegative(position); - advance(iterator, position); - return getNext(iterator, defaultValue); - } - - /** - * Returns the next element in {@code iterator} or {@code defaultValue} if the - * iterator is empty. The {@link Iterables} analog to this method is - * {@link Iterables#getFirst}. - * - * @param defaultValue the default value to return if the iterator is empty - * @return the next element of {@code iterator} or the default value - * @since 7.0 - */ - @Nullable - public static T getNext(Iterator iterator, @Nullable T defaultValue) { - return iterator.hasNext() ? iterator.next() : defaultValue; - } - - /** - * Advances {@code iterator} to the end, returning the last element. - * - * @return the last element of {@code iterator} - * @throws NoSuchElementException if the iterator is empty - */ - public static T getLast(Iterator iterator) { - while (true) { - T current = iterator.next(); - if (!iterator.hasNext()) { - return current; - } - } - } - - /** - * Advances {@code iterator} to the end, returning the last element or - * {@code defaultValue} if the iterator is empty. - * - * @param defaultValue the default value to return if the iterator is empty - * @return the last element of {@code iterator} - * @since 3.0 - */ - @Nullable - public static T getLast(Iterator iterator, @Nullable T defaultValue) { - return iterator.hasNext() ? getLast(iterator) : defaultValue; - } - - /** - * Calls {@code next()} on {@code iterator}, either {@code numberToAdvance} - * times or until {@code hasNext()} returns {@code false}, whichever comes - * first. - * - * @return the number of elements the iterator was advanced - * @since 13.0 (since 3.0 as {@code Iterators.skip}) - */ - public static int advance(Iterator iterator, int numberToAdvance) { - checkNotNull(iterator); - checkArgument(numberToAdvance >= 0, "numberToAdvance must be nonnegative"); - - int i; - for (i = 0; i < numberToAdvance && iterator.hasNext(); i++) { - iterator.next(); - } - return i; - } - - /** - * Creates an iterator returning the first {@code limitSize} elements of the - * given iterator. If the original iterator does not contain that many elements, - * the returned iterator will have the same behavior as the original iterator. - * The returned iterator supports {@code remove()} if the original iterator - * does. - * - * @param iterator the iterator to limit - * @param limitSize the maximum number of elements in the returned iterator - * @throws IllegalArgumentException if {@code limitSize} is negative - * @since 3.0 - */ - public static Iterator limit(final Iterator iterator, final int limitSize) { - checkNotNull(iterator); - checkArgument(limitSize >= 0, "limit is negative"); - return new Iterator() { - private int count; - - @Override - public boolean hasNext() { - return count < limitSize && iterator.hasNext(); - } - - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - count++; - return iterator.next(); - } - - @Override - public void remove() { - iterator.remove(); - } - }; - } - - /** - * Returns a view of the supplied {@code iterator} that removes each element - * from the supplied {@code iterator} as it is returned. - * - *

- * The provided iterator must support {@link Iterator#remove()} or else the - * returned iterator will fail on the first call to {@code - * next}. - * - * @param iterator the iterator to remove and return elements from - * @return an iterator that removes and returns elements from the supplied - * iterator - * @since 2.0 - */ - public static Iterator consumingIterator(final Iterator iterator) { - checkNotNull(iterator); - return new UnmodifiableIterator() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public T next() { - T next = iterator.next(); - iterator.remove(); - return next; - } - - @Override - public String toString() { - return "Iterators.consumingIterator(...)"; - } - }; - } - - /** - * Deletes and returns the next value from the iterator, or returns {@code null} - * if there is no such value. - */ - @Nullable - static T pollNext(Iterator iterator) { - if (iterator.hasNext()) { - T result = iterator.next(); - iterator.remove(); - return result; - } else { - return null; - } - } - - // Methods only in Iterators, not in Iterables - - /** - * Clears the iterator using its remove method. - */ - static void clear(Iterator iterator) { - checkNotNull(iterator); - while (iterator.hasNext()) { - iterator.next(); - iterator.remove(); - } + public static T find(Iterator iterator, Predicate predicate) { + return filter(iterator, predicate).next(); } /** @@ -1063,33 +740,6 @@ public final class Iterators { }; } - /** - * Returns an iterator containing only {@code value}. - * - *

- * The {@link Iterable} equivalent of this method is - * {@link Collections#singleton}. - */ - public static UnmodifiableIterator singletonIterator(@Nullable final T value) { - return new UnmodifiableIterator() { - boolean done; - - @Override - public boolean hasNext() { - return !done; - } - - @Override - public T next() { - if (done) { - throw new NoSuchElementException(); - } - done = true; - return value; - } - }; - } - /** * Adapts an {@code Enumeration} to the {@code Iterator} interface. * @@ -1115,71 +765,300 @@ public final class Iterators { } /** - * Adapts an {@code Iterator} to the {@code Enumeration} interface. + * Returns the number of elements in the specified iterator that equal the + * specified object. The iterator will be left exhausted: its {@code hasNext()} + * method will return {@code false}. + * + * @see Collections#frequency + */ + public static int frequency(Iterator iterator, @Nullable Object element) { + return size(filter(iterator, equalTo(element))); + } + + /** + * Advances {@code iterator} {@code position + 1} times, returning the element + * at the {@code position}th position or {@code defaultValue} otherwise. + * + * @param position position of the element to return + * @param defaultValue the default value to return if the iterator is empty or + * if {@code position} is greater than the number of + * elements remaining in {@code iterator} + * @return the element at the specified position in {@code iterator} or + * {@code defaultValue} if {@code iterator} produces fewer than + * {@code position + 1} elements. + * @throws IndexOutOfBoundsException if {@code position} is negative + * @since 4.0 + */ + @Nullable + public static T get(Iterator iterator, int position, @Nullable T defaultValue) { + checkNonnegative(position); + advance(iterator, position); + return getNext(iterator, defaultValue); + } + + /** + * Advances {@code iterator} {@code position + 1} times, returning the element + * at the {@code position}th position. + * + * @param position position of the element to return + * @return the element at the specified position in {@code iterator} + * @throws IndexOutOfBoundsException if {@code position} is negative or greater + * than or equal to the number of elements + * remaining in {@code iterator} + */ + public static T get(Iterator iterator, int position) { + checkNonnegative(position); + int skipped = advance(iterator, position); + if (!iterator.hasNext()) { + throw new IndexOutOfBoundsException("position (" + position + + ") must be less than the number of elements that remained (" + skipped + ")"); + } + return iterator.next(); + } + + /** + * Advances {@code iterator} to the end, returning the last element or + * {@code defaultValue} if the iterator is empty. + * + * @param defaultValue the default value to return if the iterator is empty + * @return the last element of {@code iterator} + * @since 3.0 + */ + @Nullable + public static T getLast(Iterator iterator, @Nullable T defaultValue) { + return iterator.hasNext() ? getLast(iterator) : defaultValue; + } + + /** + * Advances {@code iterator} to the end, returning the last element. + * + * @return the last element of {@code iterator} + * @throws NoSuchElementException if the iterator is empty + */ + public static T getLast(Iterator iterator) { + while (true) { + T current = iterator.next(); + if (!iterator.hasNext()) { + return current; + } + } + } + + /** + * Returns the next element in {@code iterator} or {@code defaultValue} if the + * iterator is empty. The {@link Iterables} analog to this method is + * {@link Iterables#getFirst}. + * + * @param defaultValue the default value to return if the iterator is empty + * @return the next element of {@code iterator} or the default value + * @since 7.0 + */ + @Nullable + public static T getNext(Iterator iterator, @Nullable T defaultValue) { + return iterator.hasNext() ? iterator.next() : defaultValue; + } + + /** + * Returns the single element contained in {@code iterator}, or {@code + * defaultValue} if the iterator is empty. + * + * @throws IllegalArgumentException if the iterator contains multiple elements. + * The state of the iterator is unspecified. + */ + @Nullable + public static T getOnlyElement(Iterator iterator, @Nullable T defaultValue) { + return iterator.hasNext() ? getOnlyElement(iterator) : defaultValue; + } + + /** + * Returns the single element contained in {@code iterator}. + * + * @throws NoSuchElementException if the iterator is empty + * @throws IllegalArgumentException if the iterator contains multiple elements. + * The state of the iterator is unspecified. + */ + public static T getOnlyElement(Iterator iterator) { + T first = iterator.next(); + if (!iterator.hasNext()) { + return first; + } + + StringBuilder sb = new StringBuilder(); + sb.append("expected one element but was: <" + first); + for (int i = 0; i < 4 && iterator.hasNext(); i++) { + sb.append(", " + iterator.next()); + } + if (iterator.hasNext()) { + sb.append(", ..."); + } + sb.append('>'); + + throw new IllegalArgumentException(sb.toString()); + } + + /** + * Returns the index in {@code iterator} of the first element that satisfies the + * provided {@code predicate}, or {@code -1} if the Iterator has no such + * elements. * *

- * The {@code Iterable} equivalent of this method is either - * {@link Collections#enumeration} (if you have a {@link Collection}), or - * {@code Iterators.asEnumeration(collection.iterator())}. + * More formally, returns the lowest index {@code i} such that + * {@code predicate.apply(Iterators.get(iterator, i))} returns {@code true}, or + * {@code -1} if there is no such index. + * + *

+ * If -1 is returned, the iterator will be left exhausted: its {@code hasNext()} + * method will return {@code false}. Otherwise, the iterator will be set to the + * element which satisfies the {@code predicate}. + * + * @since 2.0 */ - public static Enumeration asEnumeration(final Iterator iterator) { + public static int indexOf(Iterator iterator, Predicate predicate) { + checkNotNull(predicate, "predicate"); + for (int i = 0; iterator.hasNext(); i++) { + T current = iterator.next(); + if (predicate.apply(current)) { + return i; + } + } + return -1; + } + + /** + * Creates an iterator returning the first {@code limitSize} elements of the + * given iterator. If the original iterator does not contain that many elements, + * the returned iterator will have the same behavior as the original iterator. + * The returned iterator supports {@code remove()} if the original iterator + * does. + * + * @param iterator the iterator to limit + * @param limitSize the maximum number of elements in the returned iterator + * @throws IllegalArgumentException if {@code limitSize} is negative + * @since 3.0 + */ + public static Iterator limit(final Iterator iterator, final int limitSize) { checkNotNull(iterator); - return new Enumeration() { + checkArgument(limitSize >= 0, "limit is negative"); + return new Iterator() { + private int count; + @Override - public boolean hasMoreElements() { - return iterator.hasNext(); + public boolean hasNext() { + return count < limitSize && iterator.hasNext(); } @Override - public T nextElement() { + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + count++; return iterator.next(); } + + @Override + public void remove() { + iterator.remove(); + } }; } /** - * Implementation of PeekingIterator that avoids peeking unless necessary. + * Returns an iterator over the merged contents of all given {@code iterators}, + * traversing every element of the input iterators. Equivalent entries will not + * be de-duplicated. + * + *

+ * Callers must ensure that the source {@code iterators} are in non-descending + * order as this method does not sort its input. + * + *

+ * For any equivalent elements across all {@code iterators}, it is undefined + * which element is returned first. + * + * @since 11.0 */ - private static class PeekingImpl implements PeekingIterator { + @Beta + public static UnmodifiableIterator mergeSorted(Iterable> iterators, + Comparator comparator) { + checkNotNull(iterators, "iterators"); + checkNotNull(comparator, "comparator"); - private final Iterator iterator; - private boolean hasPeeked; - private E peekedElement; + return new MergingIterator(iterators, comparator); + } - public PeekingImpl(Iterator iterator) { - this.iterator = checkNotNull(iterator); - } + /** + * Divides an iterator into unmodifiable sublists of the given size, padding the + * final iterator with null values if necessary. For example, partitioning an + * iterator containing {@code [a, b, c, d, e]} with a partition size of 3 yields + * {@code [[a, b, c], [d, e, null]]} -- an outer iterator containing two inner + * lists of three elements each, all in the original order. + * + *

+ * The returned lists implement + * {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. + * + * @param iterator the iterator to return a partitioned view of + * @param size the desired size of each partition + * @return an iterator of immutable lists containing the elements of {@code + * iterator} divided into partitions (the final iterable may have trailing + * null elements) + * @throws IllegalArgumentException if {@code size} is nonpositive + */ + public static UnmodifiableIterator> paddedPartition(Iterator iterator, int size) { + return partitionImpl(iterator, size, true); + } - @Override - public boolean hasNext() { - return hasPeeked || iterator.hasNext(); - } + /** + * Divides an iterator into unmodifiable sublists of the given size (the final + * list may be smaller). For example, partitioning an iterator containing + * {@code [a, b, c, d, e]} with a partition size of 3 yields {@code + * [[a, b, c], [d, e]]} -- an outer iterator containing two inner lists of three + * and two elements, all in the original order. + * + *

+ * The returned lists implement + * {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. + * + * @param iterator the iterator to return a partitioned view of + * @param size the desired size of each partition (the last may be smaller) + * @return an iterator of immutable lists containing the elements of {@code + * iterator} divided into partitions + * @throws IllegalArgumentException if {@code size} is nonpositive + */ + public static UnmodifiableIterator> partition(Iterator iterator, int size) { + return partitionImpl(iterator, size, false); + } - @Override - public E next() { - if (!hasPeeked) { - return iterator.next(); + private static UnmodifiableIterator> partitionImpl(final Iterator iterator, final int size, + final boolean pad) { + checkNotNull(iterator); + checkArgument(size > 0); + return new UnmodifiableIterator>() { + @Override + public boolean hasNext() { + return iterator.hasNext(); } - E result = peekedElement; - hasPeeked = false; - peekedElement = null; - return result; - } - @Override - public void remove() { - checkState(!hasPeeked, "Can't remove after you've peeked at next"); - iterator.remove(); - } + @Override + public List next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + Object[] array = new Object[size]; + int count = 0; + for (; count < size && iterator.hasNext(); count++) { + array[count] = iterator.next(); + } + for (int i = count; i < size; i++) { + array[i] = null; // for GWT + } - @Override - public E peek() { - if (!hasPeeked) { - peekedElement = iterator.next(); - hasPeeked = true; + @SuppressWarnings("unchecked") // we only put Ts in it + List list = Collections.unmodifiableList((List) Arrays.asList(array)); + return (pad || count == size) ? list : list.subList(0, count); } - return peekedElement; - } + }; } /** @@ -1194,11 +1073,11 @@ public final class Iterators { *

 	 *    {@code
 	 *
-	 *   PeekingIterator peekingIterator =
-	 *       Iterators.peekingIterator(Iterators.forArray("a", "b"));
-	 *   String a1 = peekingIterator.peek(); // returns "a"
-	 *   String a2 = peekingIterator.peek(); // also returns "a"
-	 *   String a3 = peekingIterator.next(); // also returns "a"}
+	 * PeekingIterator peekingIterator = Iterators.peekingIterator(Iterators.forArray("a", "b"));
+	 * String a1 = peekingIterator.peek(); // returns "a"
+	 * String a2 = peekingIterator.peek(); // also returns "a"
+	 * String a3 = peekingIterator.next(); // also returns "a"
+	 * }
 	 * 
* *

@@ -1252,82 +1131,205 @@ public final class Iterators { } /** - * Returns an iterator over the merged contents of all given {@code iterators}, - * traversing every element of the input iterators. Equivalent entries will not - * be de-duplicated. + * Deletes and returns the next value from the iterator, or returns {@code null} + * if there is no such value. + */ + @Nullable + static T pollNext(Iterator iterator) { + if (iterator.hasNext()) { + T result = iterator.next(); + iterator.remove(); + return result; + } else { + return null; + } + } + + // Methods only in Iterators, not in Iterables + + /** + * Traverses an iterator and removes every element that belongs to the provided + * collection. The iterator will be left exhausted: its {@code hasNext()} method + * will return {@code false}. + * + * @param removeFrom the iterator to (potentially) remove elements from + * @param elementsToRemove the elements to remove + * @return {@code true} if any element was removed from {@code iterator} + */ + public static boolean removeAll(Iterator removeFrom, Collection elementsToRemove) { + return removeIf(removeFrom, in(elementsToRemove)); + } + + /** + * Removes every element that satisfies the provided predicate from the + * iterator. The iterator will be left exhausted: its {@code hasNext()} method + * will return {@code false}. + * + * @param removeFrom the iterator to (potentially) remove elements from + * @param predicate a predicate that determines whether an element should be + * removed + * @return {@code true} if any elements were removed from the iterator + * @since 2.0 + */ + public static boolean removeIf(Iterator removeFrom, Predicate predicate) { + checkNotNull(predicate); + boolean modified = false; + while (removeFrom.hasNext()) { + if (predicate.apply(removeFrom.next())) { + removeFrom.remove(); + modified = true; + } + } + return modified; + } + + /** + * Traverses an iterator and removes every element that does not belong to the + * provided collection. The iterator will be left exhausted: its + * {@code hasNext()} method will return {@code false}. + * + * @param removeFrom the iterator to (potentially) remove elements from + * @param elementsToRetain the elements to retain + * @return {@code true} if any element was removed from {@code iterator} + */ + public static boolean retainAll(Iterator removeFrom, Collection elementsToRetain) { + return removeIf(removeFrom, not(in(elementsToRetain))); + } + + /** + * Returns an iterator containing only {@code value}. * *

- * Callers must ensure that the source {@code iterators} are in non-descending - * order as this method does not sort its input. + * The {@link Iterable} equivalent of this method is + * {@link Collections#singleton}. + */ + public static UnmodifiableIterator singletonIterator(@Nullable final T value) { + return new UnmodifiableIterator() { + boolean done; + + @Override + public boolean hasNext() { + return !done; + } + + @Override + public T next() { + if (done) { + throw new NoSuchElementException(); + } + done = true; + return value; + } + }; + } + + /** + * Returns the number of elements remaining in {@code iterator}. The iterator + * will be left exhausted: its {@code hasNext()} method will return + * {@code false}. + */ + public static int size(Iterator iterator) { + int count = 0; + while (iterator.hasNext()) { + iterator.next(); + count++; + } + return count; + } + + /** + * Copies an iterator's elements into an array. The iterator will be left + * exhausted: its {@code hasNext()} method will return {@code false}. + * + * @param iterator the iterator to copy + * @param type the type of the elements + * @return a newly-allocated array into which all the elements of the iterator + * have been copied + */ + @GwtIncompatible("Array.newInstance(Class, int)") + public static T[] toArray(Iterator iterator, Class type) { + List list = Lists.newArrayList(iterator); + return Iterables.toArray(list, type); + } + + /** + * Returns a string representation of {@code iterator}, with the format + * {@code [e1, e2, ..., en]}. The iterator will be left exhausted: its + * {@code hasNext()} method will return {@code false}. + */ + public static String toString(Iterator iterator) { + return Collections2.STANDARD_JOINER.appendTo(new StringBuilder().append('['), iterator).append(']').toString(); + } + + /** + * Returns an iterator that applies {@code function} to each element of {@code + * fromIterator}. * *

- * For any equivalent elements across all {@code iterators}, it is undefined - * which element is returned first. + * The returned iterator supports {@code remove()} if the provided iterator + * does. After a successful {@code remove()} call, {@code fromIterator} no + * longer contains the corresponding element. + */ + public static Iterator transform(final Iterator fromIterator, + final Function function) { + checkNotNull(function); + return new TransformedIterator(fromIterator) { + @Override + T transform(F from) { + return function.apply(from); + } + }; + } + + /** + * Returns an {@link Optional} containing the first element in {@code + * iterator} that satisfies the given predicate, if such an element exists. If + * no such element is found, an empty {@link Optional} will be returned from + * this method and the iterator will be left exhausted: its {@code + * hasNext()} method will return {@code false}. + * + *

+ * Warning: avoid using a {@code predicate} that matches {@code + * null}. If {@code null} is matched in {@code iterator}, a NullPointerException + * will be thrown. * * @since 11.0 */ - @Beta - public static UnmodifiableIterator mergeSorted(Iterable> iterators, - Comparator comparator) { - checkNotNull(iterators, "iterators"); - checkNotNull(comparator, "comparator"); + public static Optional tryFind(Iterator iterator, Predicate predicate) { + UnmodifiableIterator filteredIterator = filter(iterator, predicate); + return filteredIterator.hasNext() ? Optional.of(filteredIterator.next()) : Optional.absent(); + } - return new MergingIterator(iterators, comparator); + /** Returns an unmodifiable view of {@code iterator}. */ + public static UnmodifiableIterator unmodifiableIterator(final Iterator iterator) { + checkNotNull(iterator); + if (iterator instanceof UnmodifiableIterator) { + return (UnmodifiableIterator) iterator; + } + return new UnmodifiableIterator() { + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public T next() { + return iterator.next(); + } + }; } /** - * An iterator that performs a lazy N-way merge, calculating the next value each - * time the iterator is polled. This amortizes the sorting cost over the - * iteration and requires less memory than sorting all elements at once. + * Simply returns its argument. * - *

- * Retrieving a single element takes approximately O(log(M)) time, where M is - * the number of iterators. (Retrieving all elements takes approximately - * O(N*log(M)) time, where N is the total number of elements.) + * @deprecated no need to use this + * @since 10.0 */ - private static class MergingIterator extends UnmodifiableIterator { - final Queue> queue; - - public MergingIterator(Iterable> iterators, - final Comparator itemComparator) { - // A comparator that's used by the heap, allowing the heap - // to be sorted based on the top of each iterator. - Comparator> heapComparator = new Comparator>() { - @Override - public int compare(PeekingIterator o1, PeekingIterator o2) { - return itemComparator.compare(o1.peek(), o2.peek()); - } - }; - - queue = new PriorityQueue>(2, heapComparator); - - for (Iterator iterator : iterators) { - if (iterator.hasNext()) { - queue.add(Iterators.peekingIterator(iterator)); - } - } - } - - @Override - public boolean hasNext() { - return !queue.isEmpty(); - } - - @Override - public T next() { - PeekingIterator nextIter = queue.remove(); - T next = nextIter.next(); - if (nextIter.hasNext()) { - queue.add(nextIter); - } - return next; - } + @Deprecated + public static UnmodifiableIterator unmodifiableIterator(UnmodifiableIterator iterator) { + return checkNotNull(iterator); } - /** - * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 - */ - static ListIterator cast(Iterator iterator) { - return (ListIterator) iterator; + private Iterators() { } } diff --git a/src/main/java/com/google/common/collect/LexicographicalOrdering.java b/src/main/java/com/google/common/collect/LexicographicalOrdering.java index bc294e31..21dea200 100644 --- a/src/main/java/com/google/common/collect/LexicographicalOrdering.java +++ b/src/main/java/com/google/common/collect/LexicographicalOrdering.java @@ -29,6 +29,8 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(serializable = true) final class LexicographicalOrdering extends Ordering> implements Serializable { + private static final long serialVersionUID = 0; + final Ordering elementOrder; LexicographicalOrdering(Ordering elementOrder) { @@ -75,6 +77,4 @@ final class LexicographicalOrdering extends Ordering> implements public String toString() { return elementOrder + ".lexicographical()"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/LinkedHashMultimap.java b/src/main/java/com/google/common/collect/LinkedHashMultimap.java index b9cac768..2f36fd36 100644 --- a/src/main/java/com/google/common/collect/LinkedHashMultimap.java +++ b/src/main/java/com/google/common/collect/LinkedHashMultimap.java @@ -87,70 +87,6 @@ import com.google.common.base.Objects; @GwtCompatible(serializable = true, emulated = true) public final class LinkedHashMultimap extends AbstractSetMultimap { - /** - * Creates a new, empty {@code LinkedHashMultimap} with the default initial - * capacities. - */ - public static LinkedHashMultimap create() { - return new LinkedHashMultimap(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY); - } - - /** - * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold - * the specified numbers of keys and values without rehashing. - * - * @param expectedKeys the expected number of distinct keys - * @param expectedValuesPerKey the expected average number of values per key - * @throws IllegalArgumentException if {@code expectedKeys} or {@code - * expectedValuesPerKey} is negative - */ - public static LinkedHashMultimap create(int expectedKeys, int expectedValuesPerKey) { - return new LinkedHashMultimap(Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey)); - } - - /** - * Constructs a {@code LinkedHashMultimap} with the same mappings as the - * specified multimap. If a key-value mapping appears multiple times in the - * input multimap, it only appears once in the constructed multimap. The new - * multimap has the same {@link Multimap#entries()} iteration order as the input - * multimap, except for excluding duplicate mappings. - * - * @param multimap the multimap whose contents are copied to this multimap - */ - public static LinkedHashMultimap create(Multimap multimap) { - LinkedHashMultimap result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY); - result.putAll(multimap); - return result; - } - - private interface ValueSetLink { - ValueSetLink getPredecessorInValueSet(); - - ValueSetLink getSuccessorInValueSet(); - - void setPredecessorInValueSet(ValueSetLink entry); - - void setSuccessorInValueSet(ValueSetLink entry); - } - - private static void succeedsInValueSet(ValueSetLink pred, ValueSetLink succ) { - pred.setSuccessorInValueSet(succ); - succ.setPredecessorInValueSet(pred); - } - - private static void succeedsInMultimap(ValueEntry pred, ValueEntry succ) { - pred.setSuccessorInMultimap(succ); - succ.setPredecessorInMultimap(pred); - } - - private static void deleteFromValueSet(ValueSetLink entry) { - succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet()); - } - - private static void deleteFromMultimap(ValueEntry entry) { - succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap()); - } - /** * LinkedHashMultimap entries are in no less than three coexisting linked lists: * a bucket in the hash table for a Set associated with a key, the linked @@ -177,8 +113,8 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { this.nextInValueBucket = nextInValueBucket; } - boolean matchesValue(@Nullable Object v, int smearedVHash) { - return smearedValueHash == smearedVHash && Objects.equal(getValue(), v); + public ValueEntry getPredecessorInMultimap() { + return predecessorInMultimap; } @Override @@ -186,132 +122,38 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { return predecessorInValueSet; } + public ValueEntry getSuccessorInMultimap() { + return successorInMultimap; + } + @Override public ValueSetLink getSuccessorInValueSet() { return successorInValueSet; } + boolean matchesValue(@Nullable Object v, int smearedVHash) { + return smearedValueHash == smearedVHash && Objects.equal(getValue(), v); + } + + public void setPredecessorInMultimap(ValueEntry multimapPredecessor) { + this.predecessorInMultimap = multimapPredecessor; + } + @Override public void setPredecessorInValueSet(ValueSetLink entry) { predecessorInValueSet = entry; } - @Override - public void setSuccessorInValueSet(ValueSetLink entry) { - successorInValueSet = entry; - } - - public ValueEntry getPredecessorInMultimap() { - return predecessorInMultimap; - } - - public ValueEntry getSuccessorInMultimap() { - return successorInMultimap; - } - public void setSuccessorInMultimap(ValueEntry multimapSuccessor) { this.successorInMultimap = multimapSuccessor; } - public void setPredecessorInMultimap(ValueEntry multimapPredecessor) { - this.predecessorInMultimap = multimapPredecessor; + @Override + public void setSuccessorInValueSet(ValueSetLink entry) { + successorInValueSet = entry; } } - private static final int DEFAULT_KEY_CAPACITY = 16; - private static final int DEFAULT_VALUE_SET_CAPACITY = 2; - @VisibleForTesting - static final double VALUE_SET_LOAD_FACTOR = 1.0; - - @VisibleForTesting - transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; - private transient ValueEntry multimapHeaderEntry; - - private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) { - super(new LinkedHashMap>(keyCapacity)); - checkNonnegative(valueSetCapacity, "expectedValuesPerKey"); - - this.valueSetCapacity = valueSetCapacity; - this.multimapHeaderEntry = new ValueEntry(null, null, 0, null); - succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); - } - - /** - * {@inheritDoc} - * - *

- * Creates an empty {@code LinkedHashSet} for a collection of values for one - * key. - * - * @return a new {@code LinkedHashSet} containing a collection of values for one - * key - */ - @Override - Set createCollection() { - return new LinkedHashSet(valueSetCapacity); - } - - /** - * {@inheritDoc} - * - *

- * Creates a decorated insertion-ordered set that also keeps track of the order - * in which key-value pairs are added to the multimap. - * - * @param key key to associate with values in the collection - * @return a new decorated set containing a collection of values for one key - */ - @Override - Collection createCollection(K key) { - return new ValueSet(key, valueSetCapacity); - } - - /** - * {@inheritDoc} - * - *

- * If {@code values} is not empty and the multimap already contains a mapping - * for {@code key}, the {@code keySet()} ordering is unchanged. However, the - * provided values always come last in the {@link #entries()} and - * {@link #values()} iteration orderings. - */ - @Override - public Set replaceValues(@Nullable K key, Iterable values) { - return super.replaceValues(key, values); - } - - /** - * Returns a set of all key-value pairs. Changes to the returned set will update - * the underlying multimap, and vice versa. The entries set does not support the - * {@code add} or {@code addAll} operations. - * - *

- * The iterator generated by the returned set traverses the entries in the order - * they were added to the multimap. - * - *

- * Each entry is an immutable snapshot of a key-value mapping in the multimap, - * taken at the time the entry is returned by a method call to the collection or - * its iterator. - */ - @Override - public Set> entries() { - return super.entries(); - } - - /** - * Returns a collection of all values in the multimap. Changes to the returned - * collection will update the underlying multimap, and vice versa. - * - *

- * The iterator generated by the returned collection traverses the values in the - * order they were added to the multimap. - */ - @Override - public Collection values() { - return super.values(); - } - @VisibleForTesting final class ValueSet extends Sets.ImprovedAbstractSet implements ValueSetLink { /* @@ -343,8 +185,51 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { this.hashTable = hashTable; } - private int mask() { - return hashTable.length - 1; + @Override + public boolean add(@Nullable V value) { + int smearedHash = Hashing.smearedHash(value); + int bucket = smearedHash & mask(); + ValueEntry rowHead = hashTable[bucket]; + for (ValueEntry entry = rowHead; entry != null; entry = entry.nextInValueBucket) { + if (entry.matchesValue(value, smearedHash)) { + return false; + } + } + + ValueEntry newEntry = new ValueEntry(key, value, smearedHash, rowHead); + succeedsInValueSet(lastEntry, newEntry); + succeedsInValueSet(newEntry, this); + succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry); + succeedsInMultimap(newEntry, multimapHeaderEntry); + hashTable[bucket] = newEntry; + size++; + modCount++; + rehashIfNecessary(); + return true; + } + + @Override + public void clear() { + Arrays.fill(hashTable, null); + size = 0; + for (ValueSetLink entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { + ValueEntry valueEntry = (ValueEntry) entry; + deleteFromMultimap(valueEntry); + } + succeedsInValueSet(this, this); + modCount++; + } + + @Override + public boolean contains(@Nullable Object o) { + int smearedHash = Hashing.smearedHash(o); + for (ValueEntry entry = hashTable[smearedHash + & mask()]; entry != null; entry = entry.nextInValueBucket) { + if (entry.matchesValue(o, smearedHash)) { + return true; + } + } + return false; } @Override @@ -357,16 +242,6 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { return firstEntry; } - @Override - public void setPredecessorInValueSet(ValueSetLink entry) { - lastEntry = entry; - } - - @Override - public void setSuccessorInValueSet(ValueSetLink entry) { - firstEntry = entry; - } - @Override public Iterator iterator() { return new Iterator() { @@ -409,44 +284,8 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { }; } - @Override - public int size() { - return size; - } - - @Override - public boolean contains(@Nullable Object o) { - int smearedHash = Hashing.smearedHash(o); - for (ValueEntry entry = hashTable[smearedHash - & mask()]; entry != null; entry = entry.nextInValueBucket) { - if (entry.matchesValue(o, smearedHash)) { - return true; - } - } - return false; - } - - @Override - public boolean add(@Nullable V value) { - int smearedHash = Hashing.smearedHash(value); - int bucket = smearedHash & mask(); - ValueEntry rowHead = hashTable[bucket]; - for (ValueEntry entry = rowHead; entry != null; entry = entry.nextInValueBucket) { - if (entry.matchesValue(value, smearedHash)) { - return false; - } - } - - ValueEntry newEntry = new ValueEntry(key, value, smearedHash, rowHead); - succeedsInValueSet(lastEntry, newEntry); - succeedsInValueSet(newEntry, this); - succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry); - succeedsInMultimap(newEntry, multimapHeaderEntry); - hashTable[bucket] = newEntry; - size++; - modCount++; - rehashIfNecessary(); - return true; + private int mask() { + return hashTable.length - 1; } private void rehashIfNecessary() { @@ -488,16 +327,162 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { } @Override - public void clear() { - Arrays.fill(hashTable, null); - size = 0; - for (ValueSetLink entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { - ValueEntry valueEntry = (ValueEntry) entry; - deleteFromMultimap(valueEntry); - } - succeedsInValueSet(this, this); - modCount++; + public void setPredecessorInValueSet(ValueSetLink entry) { + lastEntry = entry; } + + @Override + public void setSuccessorInValueSet(ValueSetLink entry) { + firstEntry = entry; + } + + @Override + public int size() { + return size; + } + } + + private interface ValueSetLink { + ValueSetLink getPredecessorInValueSet(); + + ValueSetLink getSuccessorInValueSet(); + + void setPredecessorInValueSet(ValueSetLink entry); + + void setSuccessorInValueSet(ValueSetLink entry); + } + + private static final int DEFAULT_KEY_CAPACITY = 16; + + private static final int DEFAULT_VALUE_SET_CAPACITY = 2; + + @VisibleForTesting + static final double VALUE_SET_LOAD_FACTOR = 1.0; + + @GwtIncompatible("java serialization not supported") + private static final long serialVersionUID = 1; + + /** + * Creates a new, empty {@code LinkedHashMultimap} with the default initial + * capacities. + */ + public static LinkedHashMultimap create() { + return new LinkedHashMultimap(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY); + } + + /** + * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold + * the specified numbers of keys and values without rehashing. + * + * @param expectedKeys the expected number of distinct keys + * @param expectedValuesPerKey the expected average number of values per key + * @throws IllegalArgumentException if {@code expectedKeys} or {@code + * expectedValuesPerKey} is negative + */ + public static LinkedHashMultimap create(int expectedKeys, int expectedValuesPerKey) { + return new LinkedHashMultimap(Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey)); + } + + /** + * Constructs a {@code LinkedHashMultimap} with the same mappings as the + * specified multimap. If a key-value mapping appears multiple times in the + * input multimap, it only appears once in the constructed multimap. The new + * multimap has the same {@link Multimap#entries()} iteration order as the input + * multimap, except for excluding duplicate mappings. + * + * @param multimap the multimap whose contents are copied to this multimap + */ + public static LinkedHashMultimap create(Multimap multimap) { + LinkedHashMultimap result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY); + result.putAll(multimap); + return result; + } + + private static void deleteFromMultimap(ValueEntry entry) { + succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap()); + } + + private static void deleteFromValueSet(ValueSetLink entry) { + succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet()); + } + + private static void succeedsInMultimap(ValueEntry pred, ValueEntry succ) { + pred.setSuccessorInMultimap(succ); + succ.setPredecessorInMultimap(pred); + } + + private static void succeedsInValueSet(ValueSetLink pred, ValueSetLink succ) { + pred.setSuccessorInValueSet(succ); + succ.setPredecessorInValueSet(pred); + } + + @VisibleForTesting + transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; + + private transient ValueEntry multimapHeaderEntry; + + private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) { + super(new LinkedHashMap>(keyCapacity)); + checkNonnegative(valueSetCapacity, "expectedValuesPerKey"); + + this.valueSetCapacity = valueSetCapacity; + this.multimapHeaderEntry = new ValueEntry(null, null, 0, null); + succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); + } + + @Override + public void clear() { + super.clear(); + succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); + } + + /** + * {@inheritDoc} + * + *

+ * Creates an empty {@code LinkedHashSet} for a collection of values for one + * key. + * + * @return a new {@code LinkedHashSet} containing a collection of values for one + * key + */ + @Override + Set createCollection() { + return new LinkedHashSet(valueSetCapacity); + } + + /** + * {@inheritDoc} + * + *

+ * Creates a decorated insertion-ordered set that also keeps track of the order + * in which key-value pairs are added to the multimap. + * + * @param key key to associate with values in the collection + * @return a new decorated set containing a collection of values for one key + */ + @Override + Collection createCollection(K key) { + return new ValueSet(key, valueSetCapacity); + } + + /** + * Returns a set of all key-value pairs. Changes to the returned set will update + * the underlying multimap, and vice versa. The entries set does not support the + * {@code add} or {@code addAll} operations. + * + *

+ * The iterator generated by the returned set traverses the entries in the order + * they were added to the multimap. + * + *

+ * Each entry is an immutable snapshot of a key-value mapping in the multimap, + * taken at the time the entry is returned by a method call to the collection or + * its iterator. + */ + @Override + public Set> entries() { + return super.entries(); } @Override @@ -531,36 +516,6 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { }; } - @Override - Iterator valueIterator() { - return Maps.valueIterator(entryIterator()); - } - - @Override - public void clear() { - super.clear(); - succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); - } - - /** - * @serialData the expected values per key, the number of distinct keys, the - * number of entries, and the entries in order - */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeInt(valueSetCapacity); - stream.writeInt(keySet().size()); - for (K key : keySet()) { - stream.writeObject(key); - } - stream.writeInt(size()); - for (Map.Entry entry : entries()) { - stream.writeObject(entry.getKey()); - stream.writeObject(entry.getValue()); - } - } - @GwtIncompatible("java.io.ObjectInputStream") private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @@ -585,6 +540,54 @@ public final class LinkedHashMultimap extends AbstractSetMultimap { setMap(map); } - @GwtIncompatible("java serialization not supported") - private static final long serialVersionUID = 1; + /** + * {@inheritDoc} + * + *

+ * If {@code values} is not empty and the multimap already contains a mapping + * for {@code key}, the {@code keySet()} ordering is unchanged. However, the + * provided values always come last in the {@link #entries()} and + * {@link #values()} iteration orderings. + */ + @Override + public Set replaceValues(@Nullable K key, Iterable values) { + return super.replaceValues(key, values); + } + + @Override + Iterator valueIterator() { + return Maps.valueIterator(entryIterator()); + } + + /** + * Returns a collection of all values in the multimap. Changes to the returned + * collection will update the underlying multimap, and vice versa. + * + *

+ * The iterator generated by the returned collection traverses the values in the + * order they were added to the multimap. + */ + @Override + public Collection values() { + return super.values(); + } + + /** + * @serialData the expected values per key, the number of distinct keys, the + * number of entries, and the entries in order + */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeInt(valueSetCapacity); + stream.writeInt(keySet().size()); + for (K key : keySet()) { + stream.writeObject(key); + } + stream.writeInt(size()); + for (Map.Entry entry : entries()) { + stream.writeObject(entry.getKey()); + stream.writeObject(entry.getValue()); + } + } } diff --git a/src/main/java/com/google/common/collect/LinkedHashMultiset.java b/src/main/java/com/google/common/collect/LinkedHashMultiset.java index ffeb9901..678867d6 100644 --- a/src/main/java/com/google/common/collect/LinkedHashMultiset.java +++ b/src/main/java/com/google/common/collect/LinkedHashMultiset.java @@ -45,6 +45,9 @@ import com.google.common.annotations.GwtIncompatible; @SuppressWarnings("serial") // we're overriding default serialization public final class LinkedHashMultiset extends AbstractMapBasedMultiset { + @GwtIncompatible("not needed in emulated source") + private static final long serialVersionUID = 0; + /** * Creates a new, empty {@code LinkedHashMultiset} using the default initial * capacity. @@ -88,6 +91,14 @@ public final class LinkedHashMultiset extends AbstractMapBasedMultiset { super(new LinkedHashMap(Maps.capacity(distinctElements))); } + @GwtIncompatible("java.io.ObjectInputStream") + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + int distinctElements = Serialization.readCount(stream); + setBackingMap(new LinkedHashMap(Maps.capacity(distinctElements))); + Serialization.populateMultiset(this, stream, distinctElements); + } + /** * @serialData the number of distinct elements, the first element, its count, * the second element, its count, and so on @@ -97,15 +108,4 @@ public final class LinkedHashMultiset extends AbstractMapBasedMultiset { stream.defaultWriteObject(); Serialization.writeMultiset(this, stream); } - - @GwtIncompatible("java.io.ObjectInputStream") - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - int distinctElements = Serialization.readCount(stream); - setBackingMap(new LinkedHashMap(Maps.capacity(distinctElements))); - Serialization.populateMultiset(this, stream, distinctElements); - } - - @GwtIncompatible("not needed in emulated source") - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/LinkedListMultimap.java b/src/main/java/com/google/common/collect/LinkedListMultimap.java index a7ceebae..e0367525 100644 --- a/src/main/java/com/google/common/collect/LinkedListMultimap.java +++ b/src/main/java/com/google/common/collect/LinkedListMultimap.java @@ -67,7 +67,8 @@ import com.google.common.annotations.GwtIncompatible; *

  *    {@code
  *
- *   map.remove(key1, foo);}
+ * map.remove(key1, foo);
+ * }
  * 
* *

@@ -124,6 +125,61 @@ public class LinkedListMultimap extends AbstractMultimap implements * ValueForKeyIterator} in constant time. */ + /** An {@code Iterator} over distinct keys in key head order. */ + private class DistinctKeyIterator implements Iterator { + final Set seenKeys = Sets.newHashSetWithExpectedSize(keySet().size()); + Node next = head; + Node current; + int expectedModCount = modCount; + + private void checkForConcurrentModification() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + @Override + public boolean hasNext() { + checkForConcurrentModification(); + return next != null; + } + + @Override + public K next() { + checkForConcurrentModification(); + checkElement(next); + current = next; + seenKeys.add(current.key); + do { // skip ahead to next unseen key + next = next.next; + } while ((next != null) && !seenKeys.add(next.key)); + return current.key; + } + + @Override + public void remove() { + checkForConcurrentModification(); + checkRemove(current != null); + removeAllNodes(current.key); + current = null; + expectedModCount = modCount; + } + } + + private static class KeyList { + Node head; + Node tail; + int count; + + KeyList(Node firstNode) { + this.head = firstNode; + this.tail = firstNode; + firstNode.previousSibling = null; + firstNode.nextSibling = null; + this.count = 1; + } + } + private static final class Node extends AbstractMapEntry { final K key; V value; @@ -155,32 +211,229 @@ public class LinkedListMultimap extends AbstractMultimap implements } } - private static class KeyList { - Node head; - Node tail; - int count; + /** An {@code Iterator} over all nodes. */ + private class NodeIterator implements ListIterator> { + int nextIndex; + Node next; + Node current; + Node previous; + int expectedModCount = modCount; - KeyList(Node firstNode) { - this.head = firstNode; - this.tail = firstNode; - firstNode.previousSibling = null; - firstNode.nextSibling = null; - this.count = 1; + NodeIterator(int index) { + int size = size(); + checkPositionIndex(index, size); + if (index >= (size / 2)) { + previous = tail; + nextIndex = size; + while (index++ < size) { + previous(); + } + } else { + next = head; + while (index-- > 0) { + next(); + } + } + current = null; + } + + @Override + public void add(Entry e) { + throw new UnsupportedOperationException(); + } + + private void checkForConcurrentModification() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + @Override + public boolean hasNext() { + checkForConcurrentModification(); + return next != null; + } + + @Override + public boolean hasPrevious() { + checkForConcurrentModification(); + return previous != null; + } + + @Override + public Node next() { + checkForConcurrentModification(); + checkElement(next); + previous = current = next; + next = next.next; + nextIndex++; + return current; + } + + @Override + public int nextIndex() { + return nextIndex; + } + + @Override + public Node previous() { + checkForConcurrentModification(); + checkElement(previous); + next = current = previous; + previous = previous.previous; + nextIndex--; + return current; + } + + @Override + public int previousIndex() { + return nextIndex - 1; + } + + @Override + public void remove() { + checkForConcurrentModification(); + checkRemove(current != null); + if (current != next) { // after call to next() + previous = current.previous; + nextIndex--; + } else { // after call to previous() + next = current.next; + } + removeNode(current); + current = null; + expectedModCount = modCount; + } + + @Override + public void set(Entry e) { + throw new UnsupportedOperationException(); + } + + void setValue(V value) { + checkState(current != null); + current.value = value; } } - private transient Node head; // the head for all keys - private transient Node tail; // the tail for all keys - private transient Map> keyToKeyList; - private transient int size; + /** A {@code ListIterator} over values for a specified key. */ + private class ValueForKeyIterator implements ListIterator { + final Object key; + int nextIndex; + Node next; + Node current; + Node previous; - /* - * Tracks modifications to keyToKeyList so that addition or removal of keys - * invalidates preexisting iterators. This does *not* track simple additions and - * removals of values that are not the first to be added or last to be removed - * for their key. - */ - private transient int modCount; + /** Constructs a new iterator over all values for the specified key. */ + ValueForKeyIterator(@Nullable Object key) { + this.key = key; + KeyList keyList = keyToKeyList.get(key); + next = (keyList == null) ? null : keyList.head; + } + + /** + * Constructs a new iterator over all values for the specified key starting at + * the specified index. This constructor is optimized so that it starts at + * either the head or the tail, depending on which is closer to the specified + * index. This allows adds to the tail to be done in constant time. + * + * @throws IndexOutOfBoundsException if index is invalid + */ + public ValueForKeyIterator(@Nullable Object key, int index) { + KeyList keyList = keyToKeyList.get(key); + int size = (keyList == null) ? 0 : keyList.count; + checkPositionIndex(index, size); + if (index >= (size / 2)) { + previous = (keyList == null) ? null : keyList.tail; + nextIndex = size; + while (index++ < size) { + previous(); + } + } else { + next = (keyList == null) ? null : keyList.head; + while (index-- > 0) { + next(); + } + } + this.key = key; + current = null; + } + + @Override + @SuppressWarnings("unchecked") + public void add(V value) { + previous = addNode((K) key, value, next); + nextIndex++; + current = null; + } + + @Override + public boolean hasNext() { + return next != null; + } + + @Override + public boolean hasPrevious() { + return previous != null; + } + + @Override + public V next() { + checkElement(next); + previous = current = next; + next = next.nextSibling; + nextIndex++; + return current.value; + } + + @Override + public int nextIndex() { + return nextIndex; + } + + @Override + public V previous() { + checkElement(previous); + next = current = previous; + previous = previous.previousSibling; + nextIndex--; + return current.value; + } + + @Override + public int previousIndex() { + return nextIndex - 1; + } + + @Override + public void remove() { + checkRemove(current != null); + if (current != next) { // after call to next() + previous = current.previousSibling; + nextIndex--; + } else { // after call to previous() + next = current.nextSibling; + } + removeNode(current); + current = null; + } + + @Override + public void set(V value) { + checkState(current != null); + current.value = value; + } + } + + @GwtIncompatible("java serialization not supported") + private static final long serialVersionUID = 0; + + /** Helper method for verifying that an iterator element is present. */ + private static void checkElement(@Nullable Object node) { + if (node == null) { + throw new NoSuchElementException(); + } + } /** * Creates a new, empty {@code LinkedListMultimap} with the default initial @@ -212,6 +465,22 @@ public class LinkedListMultimap extends AbstractMultimap implements return new LinkedListMultimap(multimap); } + private transient Node head; // the head for all keys + + private transient Node tail; // the tail for all keys + + private transient Map> keyToKeyList; + + private transient int size; + + /* + * Tracks modifications to keyToKeyList so that addition or removal of keys + * invalidates preexisting iterators. This does *not* track simple additions and + * removals of values that are not the first to be added or last to be removed + * for their key. + */ + private transient int modCount; + LinkedListMultimap() { keyToKeyList = Maps.newHashMap(); } @@ -276,6 +545,216 @@ public class LinkedListMultimap extends AbstractMultimap implements return node; } + @Override + public void clear() { + head = null; + tail = null; + keyToKeyList.clear(); + size = 0; + modCount++; + } + + // Query Operations + + @Override + public boolean containsKey(@Nullable Object key) { + return keyToKeyList.containsKey(key); + } + + @Override + public boolean containsValue(@Nullable Object value) { + return values().contains(value); + } + + @Override + Map> createAsMap() { + return new Multimaps.AsMap(this); + } + + @Override + List> createEntries() { + return new AbstractSequentialList>() { + @Override + public ListIterator> listIterator(int index) { + return new NodeIterator(index); + } + + @Override + public int size() { + return size; + } + }; + } + + // Modification Operations + + @Override + Set createKeySet() { + return new Sets.ImprovedAbstractSet() { + @Override + public boolean contains(Object key) { // for performance + return containsKey(key); + } + + @Override + public Iterator iterator() { + return new DistinctKeyIterator(); + } + + @Override + public boolean remove(Object o) { // for performance + return !LinkedListMultimap.this.removeAll(o).isEmpty(); + } + + @Override + public int size() { + return keyToKeyList.size(); + } + }; + } + + // Bulk Operations + + @Override + List createValues() { + return new AbstractSequentialList() { + @Override + public ListIterator listIterator(int index) { + final NodeIterator nodeItr = new NodeIterator(index); + return new TransformedListIterator, V>(nodeItr) { + @Override + public void set(V value) { + nodeItr.setValue(value); + } + + @Override + V transform(Entry entry) { + return entry.getValue(); + } + }; + } + + @Override + public int size() { + return size; + } + }; + } + + /** + * {@inheritDoc} + * + *

+ * The iterator generated by the returned collection traverses the entries in + * the order they were added to the multimap. Because the entries may have + * duplicates and follow the insertion ordering, this method returns a + * {@link List}, instead of the {@link Collection} specified in the + * {@link ListMultimap} interface. + * + *

+ * An entry's {@link Entry#getKey} method always returns the same key, + * regardless of what happens subsequently. As long as the corresponding + * key-value mapping is not removed from the multimap, {@link Entry#getValue} + * returns the value from the multimap, which may change over time, and + * {@link Entry#setValue} modifies that value. Removing the mapping from the + * multimap does not alter the value returned by {@code getValue()}, though a + * subsequent {@code setValue()} call won't update the multimap but will lead to + * a revised value being returned by {@code getValue()}. + */ + @Override + public List> entries() { + return (List>) super.entries(); + } + + @Override + Iterator> entryIterator() { + throw new AssertionError("should never be called"); + } + + /** + * {@inheritDoc} + * + *

+ * If the multimap is modified while an iteration over the list is in progress + * (except through the iterator's own {@code add}, {@code set} or {@code remove} + * operations) the results of the iteration are undefined. + * + *

+ * The returned list is not serializable and does not have random access. + */ + @Override + public List get(final @Nullable K key) { + return new AbstractSequentialList() { + @Override + public ListIterator listIterator(int index) { + return new ValueForKeyIterator(key, index); + } + + @Override + public int size() { + KeyList keyList = keyToKeyList.get(key); + return (keyList == null) ? 0 : keyList.count; + } + }; + } + + // Views + + private List getCopy(@Nullable Object key) { + return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key))); + } + + @Override + public boolean isEmpty() { + return head == null; + } + + /** + * Stores a key-value pair in the multimap. + * + * @param key key to store in the multimap + * @param value value to store in the multimap + * @return {@code true} always + */ + @Override + public boolean put(@Nullable K key, @Nullable V value) { + addNode(key, value, null); + return true; + } + + @GwtIncompatible("java.io.ObjectInputStream") + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + keyToKeyList = Maps.newLinkedHashMap(); + int size = stream.readInt(); + for (int i = 0; i < size; i++) { + @SuppressWarnings("unchecked") // reading data stored by writeObject + K key = (K) stream.readObject(); + @SuppressWarnings("unchecked") // reading data stored by writeObject + V value = (V) stream.readObject(); + put(key, value); + } + } + + /** + * {@inheritDoc} + * + *

+ * The returned list is immutable and implements + * {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. + */ + @Override + public List removeAll(@Nullable Object key) { + List oldValues = getCopy(key); + removeAllNodes(key); + return oldValues; + } + + /** Removes all nodes for the specified key. */ + private void removeAllNodes(@Nullable Object key) { + Iterators.clear(new ValueForKeyIterator(key)); + } + /** * Removes the specified node from the linked list. This method is only intended * to be used from the {@code Iterator} classes. See also @@ -315,312 +794,6 @@ public class LinkedListMultimap extends AbstractMultimap implements size--; } - /** Removes all nodes for the specified key. */ - private void removeAllNodes(@Nullable Object key) { - Iterators.clear(new ValueForKeyIterator(key)); - } - - /** Helper method for verifying that an iterator element is present. */ - private static void checkElement(@Nullable Object node) { - if (node == null) { - throw new NoSuchElementException(); - } - } - - /** An {@code Iterator} over all nodes. */ - private class NodeIterator implements ListIterator> { - int nextIndex; - Node next; - Node current; - Node previous; - int expectedModCount = modCount; - - NodeIterator(int index) { - int size = size(); - checkPositionIndex(index, size); - if (index >= (size / 2)) { - previous = tail; - nextIndex = size; - while (index++ < size) { - previous(); - } - } else { - next = head; - while (index-- > 0) { - next(); - } - } - current = null; - } - - private void checkForConcurrentModification() { - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - } - - @Override - public boolean hasNext() { - checkForConcurrentModification(); - return next != null; - } - - @Override - public Node next() { - checkForConcurrentModification(); - checkElement(next); - previous = current = next; - next = next.next; - nextIndex++; - return current; - } - - @Override - public void remove() { - checkForConcurrentModification(); - checkRemove(current != null); - if (current != next) { // after call to next() - previous = current.previous; - nextIndex--; - } else { // after call to previous() - next = current.next; - } - removeNode(current); - current = null; - expectedModCount = modCount; - } - - @Override - public boolean hasPrevious() { - checkForConcurrentModification(); - return previous != null; - } - - @Override - public Node previous() { - checkForConcurrentModification(); - checkElement(previous); - next = current = previous; - previous = previous.previous; - nextIndex--; - return current; - } - - @Override - public int nextIndex() { - return nextIndex; - } - - @Override - public int previousIndex() { - return nextIndex - 1; - } - - @Override - public void set(Entry e) { - throw new UnsupportedOperationException(); - } - - @Override - public void add(Entry e) { - throw new UnsupportedOperationException(); - } - - void setValue(V value) { - checkState(current != null); - current.value = value; - } - } - - /** An {@code Iterator} over distinct keys in key head order. */ - private class DistinctKeyIterator implements Iterator { - final Set seenKeys = Sets.newHashSetWithExpectedSize(keySet().size()); - Node next = head; - Node current; - int expectedModCount = modCount; - - private void checkForConcurrentModification() { - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - } - - @Override - public boolean hasNext() { - checkForConcurrentModification(); - return next != null; - } - - @Override - public K next() { - checkForConcurrentModification(); - checkElement(next); - current = next; - seenKeys.add(current.key); - do { // skip ahead to next unseen key - next = next.next; - } while ((next != null) && !seenKeys.add(next.key)); - return current.key; - } - - @Override - public void remove() { - checkForConcurrentModification(); - checkRemove(current != null); - removeAllNodes(current.key); - current = null; - expectedModCount = modCount; - } - } - - /** A {@code ListIterator} over values for a specified key. */ - private class ValueForKeyIterator implements ListIterator { - final Object key; - int nextIndex; - Node next; - Node current; - Node previous; - - /** Constructs a new iterator over all values for the specified key. */ - ValueForKeyIterator(@Nullable Object key) { - this.key = key; - KeyList keyList = keyToKeyList.get(key); - next = (keyList == null) ? null : keyList.head; - } - - /** - * Constructs a new iterator over all values for the specified key starting at - * the specified index. This constructor is optimized so that it starts at - * either the head or the tail, depending on which is closer to the specified - * index. This allows adds to the tail to be done in constant time. - * - * @throws IndexOutOfBoundsException if index is invalid - */ - public ValueForKeyIterator(@Nullable Object key, int index) { - KeyList keyList = keyToKeyList.get(key); - int size = (keyList == null) ? 0 : keyList.count; - checkPositionIndex(index, size); - if (index >= (size / 2)) { - previous = (keyList == null) ? null : keyList.tail; - nextIndex = size; - while (index++ < size) { - previous(); - } - } else { - next = (keyList == null) ? null : keyList.head; - while (index-- > 0) { - next(); - } - } - this.key = key; - current = null; - } - - @Override - public boolean hasNext() { - return next != null; - } - - @Override - public V next() { - checkElement(next); - previous = current = next; - next = next.nextSibling; - nextIndex++; - return current.value; - } - - @Override - public boolean hasPrevious() { - return previous != null; - } - - @Override - public V previous() { - checkElement(previous); - next = current = previous; - previous = previous.previousSibling; - nextIndex--; - return current.value; - } - - @Override - public int nextIndex() { - return nextIndex; - } - - @Override - public int previousIndex() { - return nextIndex - 1; - } - - @Override - public void remove() { - checkRemove(current != null); - if (current != next) { // after call to next() - previous = current.previousSibling; - nextIndex--; - } else { // after call to previous() - next = current.nextSibling; - } - removeNode(current); - current = null; - } - - @Override - public void set(V value) { - checkState(current != null); - current.value = value; - } - - @Override - @SuppressWarnings("unchecked") - public void add(V value) { - previous = addNode((K) key, value, next); - nextIndex++; - current = null; - } - } - - // Query Operations - - @Override - public int size() { - return size; - } - - @Override - public boolean isEmpty() { - return head == null; - } - - @Override - public boolean containsKey(@Nullable Object key) { - return keyToKeyList.containsKey(key); - } - - @Override - public boolean containsValue(@Nullable Object value) { - return values().contains(value); - } - - // Modification Operations - - /** - * Stores a key-value pair in the multimap. - * - * @param key key to store in the multimap - * @param value value to store in the multimap - * @return {@code true} always - */ - @Override - public boolean put(@Nullable K key, @Nullable V value) { - addNode(key, value, null); - return true; - } - - // Bulk Operations - /** * {@inheritDoc} * @@ -629,7 +802,8 @@ public class LinkedListMultimap extends AbstractMultimap implements * their values are changed in-place without affecting the iteration order. * *

- * The returned list is immutable and implements {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. + * The returned list is immutable and implements + * {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. */ @Override public List replaceValues(@Nullable K key, Iterable values) { @@ -657,84 +831,9 @@ public class LinkedListMultimap extends AbstractMultimap implements return oldValues; } - private List getCopy(@Nullable Object key) { - return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key))); - } - - /** - * {@inheritDoc} - * - *

- * The returned list is immutable and implements {@link net.lax1dude.eaglercraft.v1_8.RandomAccess}. - */ @Override - public List removeAll(@Nullable Object key) { - List oldValues = getCopy(key); - removeAllNodes(key); - return oldValues; - } - - @Override - public void clear() { - head = null; - tail = null; - keyToKeyList.clear(); - size = 0; - modCount++; - } - - // Views - - /** - * {@inheritDoc} - * - *

- * If the multimap is modified while an iteration over the list is in progress - * (except through the iterator's own {@code add}, {@code set} or {@code remove} - * operations) the results of the iteration are undefined. - * - *

- * The returned list is not serializable and does not have random access. - */ - @Override - public List get(final @Nullable K key) { - return new AbstractSequentialList() { - @Override - public int size() { - KeyList keyList = keyToKeyList.get(key); - return (keyList == null) ? 0 : keyList.count; - } - - @Override - public ListIterator listIterator(int index) { - return new ValueForKeyIterator(key, index); - } - }; - } - - @Override - Set createKeySet() { - return new Sets.ImprovedAbstractSet() { - @Override - public int size() { - return keyToKeyList.size(); - } - - @Override - public Iterator iterator() { - return new DistinctKeyIterator(); - } - - @Override - public boolean contains(Object key) { // for performance - return containsKey(key); - } - - @Override - public boolean remove(Object o) { // for performance - return !LinkedListMultimap.this.removeAll(o).isEmpty(); - } - }; + public int size() { + return size; } /** @@ -752,82 +851,6 @@ public class LinkedListMultimap extends AbstractMultimap implements return (List) super.values(); } - @Override - List createValues() { - return new AbstractSequentialList() { - @Override - public int size() { - return size; - } - - @Override - public ListIterator listIterator(int index) { - final NodeIterator nodeItr = new NodeIterator(index); - return new TransformedListIterator, V>(nodeItr) { - @Override - V transform(Entry entry) { - return entry.getValue(); - } - - @Override - public void set(V value) { - nodeItr.setValue(value); - } - }; - } - }; - } - - /** - * {@inheritDoc} - * - *

- * The iterator generated by the returned collection traverses the entries in - * the order they were added to the multimap. Because the entries may have - * duplicates and follow the insertion ordering, this method returns a - * {@link List}, instead of the {@link Collection} specified in the - * {@link ListMultimap} interface. - * - *

- * An entry's {@link Entry#getKey} method always returns the same key, - * regardless of what happens subsequently. As long as the corresponding - * key-value mapping is not removed from the multimap, {@link Entry#getValue} - * returns the value from the multimap, which may change over time, and - * {@link Entry#setValue} modifies that value. Removing the mapping from the - * multimap does not alter the value returned by {@code getValue()}, though a - * subsequent {@code setValue()} call won't update the multimap but will lead to - * a revised value being returned by {@code getValue()}. - */ - @Override - public List> entries() { - return (List>) super.entries(); - } - - @Override - List> createEntries() { - return new AbstractSequentialList>() { - @Override - public int size() { - return size; - } - - @Override - public ListIterator> listIterator(int index) { - return new NodeIterator(index); - } - }; - } - - @Override - Iterator> entryIterator() { - throw new AssertionError("should never be called"); - } - - @Override - Map> createAsMap() { - return new Multimaps.AsMap(this); - } - /** * @serialData the number of distinct keys, and then for each distinct key: the * first key, the number of values for that key, and the key's @@ -843,21 +866,4 @@ public class LinkedListMultimap extends AbstractMultimap implements stream.writeObject(entry.getValue()); } } - - @GwtIncompatible("java.io.ObjectInputStream") - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - keyToKeyList = Maps.newLinkedHashMap(); - int size = stream.readInt(); - for (int i = 0; i < size; i++) { - @SuppressWarnings("unchecked") // reading data stored by writeObject - K key = (K) stream.readObject(); - @SuppressWarnings("unchecked") // reading data stored by writeObject - V value = (V) stream.readObject(); - put(key, value); - } - } - - @GwtIncompatible("java serialization not supported") - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ListMultimap.java b/src/main/java/com/google/common/collect/ListMultimap.java index b5665716..7c574c1a 100644 --- a/src/main/java/com/google/common/collect/ListMultimap.java +++ b/src/main/java/com/google/common/collect/ListMultimap.java @@ -44,6 +44,32 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public interface ListMultimap extends Multimap { + /** + * {@inheritDoc} + * + *

+ * Note: The returned map's values are guaranteed to be of type + * {@link List}. To obtain this map with the more specific generic type + * {@code Map>}, call {@link Multimaps#asMap(ListMultimap)} instead. + */ + @Override + Map> asMap(); + + /** + * Compares the specified object to this multimap for equality. + * + *

+ * Two {@code ListMultimap} instances are equal if, for each key, they contain + * the same values in the same order. If the value orderings disagree, the + * multimaps will not be considered equal. + * + *

+ * An empty {@code ListMultimap} is equal to any other empty {@code + * Multimap}, including an empty {@code SetMultimap}. + */ + @Override + boolean equals(@Nullable Object obj); + /** * {@inheritDoc} * @@ -76,30 +102,4 @@ public interface ListMultimap extends Multimap { */ @Override List replaceValues(K key, Iterable values); - - /** - * {@inheritDoc} - * - *

- * Note: The returned map's values are guaranteed to be of type - * {@link List}. To obtain this map with the more specific generic type - * {@code Map>}, call {@link Multimaps#asMap(ListMultimap)} instead. - */ - @Override - Map> asMap(); - - /** - * Compares the specified object to this multimap for equality. - * - *

- * Two {@code ListMultimap} instances are equal if, for each key, they contain - * the same values in the same order. If the value orderings disagree, the - * multimaps will not be considered equal. - * - *

- * An empty {@code ListMultimap} is equal to any other empty {@code - * Multimap}, including an empty {@code SetMultimap}. - */ - @Override - boolean equals(@Nullable Object obj); } diff --git a/src/main/java/com/google/common/collect/Lists.java b/src/main/java/com/google/common/collect/Lists.java index 1774b070..74934bdf 100644 --- a/src/main/java/com/google/common/collect/Lists.java +++ b/src/main/java/com/google/common/collect/Lists.java @@ -66,11 +66,766 @@ import com.google.common.primitives.Ints; */ @GwtCompatible(emulated = true) public final class Lists { - private Lists() { + private static class AbstractListWrapper extends AbstractList { + final List backingList; + + AbstractListWrapper(List backingList) { + this.backingList = checkNotNull(backingList); + } + + @Override + public void add(int index, E element) { + backingList.add(index, element); + } + + @Override + public boolean addAll(int index, Collection c) { + return backingList.addAll(index, c); + } + + @Override + public boolean contains(Object o) { + return backingList.contains(o); + } + + @Override + public E get(int index) { + return backingList.get(index); + } + + @Override + public E remove(int index) { + return backingList.remove(index); + } + + @Override + public E set(int index, E element) { + return backingList.set(index, element); + } + + @Override + public int size() { + return backingList.size(); + } } // ArrayList + private static final class CharSequenceAsList extends AbstractList { + private final CharSequence sequence; + + CharSequenceAsList(CharSequence sequence) { + this.sequence = sequence; + } + + @Override + public Character get(int index) { + checkElementIndex(index, size()); // for GWT + return sequence.charAt(index); + } + + @Override + public int size() { + return sequence.length(); + } + } + + /** @see Lists#asList(Object, Object[]) */ + private static class OnePlusArrayList extends AbstractList implements Serializable, RandomAccess { + private static final long serialVersionUID = 0; + final E first; + + final E[] rest; + + OnePlusArrayList(@Nullable E first, E[] rest) { + this.first = first; + this.rest = checkNotNull(rest); + } + + @Override + public E get(int index) { + // check explicitly so the IOOBE will have the right message + checkElementIndex(index, size()); + return (index == 0) ? first : rest[index - 1]; + } + + @Override + public int size() { + return rest.length + 1; + } + } + + private static class Partition extends AbstractList> { + final List list; + final int size; + + Partition(List list, int size) { + this.list = list; + this.size = size; + } + + @Override + public List get(int index) { + checkElementIndex(index, size()); + int start = index * size; + int end = Math.min(start + size, list.size()); + return list.subList(start, end); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public int size() { + return IntMath.divide(list.size(), size, RoundingMode.CEILING); + } + } + + private static class RandomAccessListWrapper extends AbstractListWrapper implements RandomAccess { + RandomAccessListWrapper(List backingList) { + super(backingList); + } + } + + private static class RandomAccessPartition extends Partition implements RandomAccess { + RandomAccessPartition(List list, int size) { + super(list, size); + } + } + + private static class RandomAccessReverseList extends ReverseList implements RandomAccess { + RandomAccessReverseList(List forwardList) { + super(forwardList); + } + } + + private static class ReverseList extends AbstractList { + private final List forwardList; + + ReverseList(List forwardList) { + this.forwardList = checkNotNull(forwardList); + } + + @Override + public void add(int index, @Nullable T element) { + forwardList.add(reversePosition(index), element); + } + + @Override + public void clear() { + forwardList.clear(); + } + + @Override + public T get(int index) { + return forwardList.get(reverseIndex(index)); + } + + List getForwardList() { + return forwardList; + } + + @Override + public Iterator iterator() { + return listIterator(); + } + + @Override + public ListIterator listIterator(int index) { + int start = reversePosition(index); + final ListIterator forwardIterator = forwardList.listIterator(start); + return new ListIterator() { + + boolean canRemoveOrSet; + + @Override + public void add(T e) { + forwardIterator.add(e); + forwardIterator.previous(); + canRemoveOrSet = false; + } + + @Override + public boolean hasNext() { + return forwardIterator.hasPrevious(); + } + + @Override + public boolean hasPrevious() { + return forwardIterator.hasNext(); + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + canRemoveOrSet = true; + return forwardIterator.previous(); + } + + @Override + public int nextIndex() { + return reversePosition(forwardIterator.nextIndex()); + } + + @Override + public T previous() { + if (!hasPrevious()) { + throw new NoSuchElementException(); + } + canRemoveOrSet = true; + return forwardIterator.next(); + } + + @Override + public int previousIndex() { + return nextIndex() - 1; + } + + @Override + public void remove() { + checkRemove(canRemoveOrSet); + forwardIterator.remove(); + canRemoveOrSet = false; + } + + @Override + public void set(T e) { + checkState(canRemoveOrSet); + forwardIterator.set(e); + } + }; + } + + @Override + public T remove(int index) { + return forwardList.remove(reverseIndex(index)); + } + + @Override + protected void removeRange(int fromIndex, int toIndex) { + subList(fromIndex, toIndex).clear(); + } + + private int reverseIndex(int index) { + int size = size(); + checkElementIndex(index, size); + return (size - 1) - index; + } + + private int reversePosition(int index) { + int size = size(); + checkPositionIndex(index, size); + return size - index; + } + + @Override + public T set(int index, @Nullable T element) { + return forwardList.set(reverseIndex(index), element); + } + + @Override + public int size() { + return forwardList.size(); + } + + @Override + public List subList(int fromIndex, int toIndex) { + checkPositionIndexes(fromIndex, toIndex, size()); + return reverse(forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex))); + } + } + + // LinkedList + + @SuppressWarnings("serial") // serialized using ImmutableList serialization + private static final class StringAsImmutableList extends ImmutableList { + + private final String string; + + StringAsImmutableList(String string) { + this.string = string; + } + + @Override + public Character get(int index) { + checkElementIndex(index, size()); // for GWT + return string.charAt(index); + } + + @Override + public int indexOf(@Nullable Object object) { + return (object instanceof Character) ? string.indexOf((Character) object) : -1; + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public int lastIndexOf(@Nullable Object object) { + return (object instanceof Character) ? string.lastIndexOf((Character) object) : -1; + } + + @Override + public int size() { + return string.length(); + } + + @Override + public ImmutableList subList(int fromIndex, int toIndex) { + checkPositionIndexes(fromIndex, toIndex, size()); // for GWT + return charactersOf(string.substring(fromIndex, toIndex)); + } + } + + /** + * Implementation of a transforming random access list. We try to make as many + * of these methods pass-through to the source list as possible so that the + * performance characteristics of the source list and transformed list are + * similar. + * + * @see Lists#transform + */ + private static class TransformingRandomAccessList extends AbstractList + implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final List fromList; + + final Function function; + + TransformingRandomAccessList(List fromList, Function function) { + this.fromList = checkNotNull(fromList); + this.function = checkNotNull(function); + } + + @Override + public void clear() { + fromList.clear(); + } + + @Override + public T get(int index) { + return function.apply(fromList.get(index)); + } + + @Override + public boolean isEmpty() { + return fromList.isEmpty(); + } + + @Override + public Iterator iterator() { + return listIterator(); + } + + @Override + public ListIterator listIterator(int index) { + return new TransformedListIterator(fromList.listIterator(index)) { + @Override + T transform(F from) { + return function.apply(from); + } + }; + } + + @Override + public T remove(int index) { + return function.apply(fromList.remove(index)); + } + + @Override + public int size() { + return fromList.size(); + } + } + + /** + * Implementation of a sequential transforming list. + * + * @see Lists#transform + */ + private static class TransformingSequentialList extends AbstractSequentialList implements Serializable { + private static final long serialVersionUID = 0; + final List fromList; + + final Function function; + + TransformingSequentialList(List fromList, Function function) { + this.fromList = checkNotNull(fromList); + this.function = checkNotNull(function); + } + + /** + * The default implementation inherited is based on iteration and removal of + * each element which can be overkill. That's why we forward this call directly + * to the backing list. + */ + @Override + public void clear() { + fromList.clear(); + } + + @Override + public ListIterator listIterator(final int index) { + return new TransformedListIterator(fromList.listIterator(index)) { + @Override + T transform(F from) { + return function.apply(from); + } + }; + } + + @Override + public int size() { + return fromList.size(); + } + } + + /** @see Lists#asList(Object, Object, Object[]) */ + private static class TwoPlusArrayList extends AbstractList implements Serializable, RandomAccess { + private static final long serialVersionUID = 0; + final E first; + final E second; + + final E[] rest; + + TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) { + this.first = first; + this.second = second; + this.rest = checkNotNull(rest); + } + + @Override + public E get(int index) { + switch (index) { + case 0: + return first; + case 1: + return second; + default: + // check explicitly so the IOOBE will have the right message + checkElementIndex(index, size()); + return rest[index - 2]; + } + } + + @Override + public int size() { + return rest.length + 2; + } + } + + /** + * An implementation of {@link List#addAll(int, Collection)}. + */ + static boolean addAllImpl(List list, int index, Iterable elements) { + boolean changed = false; + ListIterator listIterator = list.listIterator(index); + for (E e : elements) { + listIterator.add(e); + changed = true; + } + return changed; + } + + /** + * Returns an unmodifiable list containing the specified first and second + * element, and backed by the specified array of additional elements. Changes to + * the {@code rest} array will be reflected in the returned list. Unlike + * {@link Arrays#asList}, the returned list is unmodifiable. + * + *

+ * This is useful when a varargs method needs to use a signature such as + * {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid + * overload ambiguity or to enforce a minimum argument count. + * + *

+ * The returned list is serializable and implements {@link RandomAccess}. + * + * @param first the first element + * @param second the second element + * @param rest an array of additional elements, possibly empty + * @return an unmodifiable list containing the specified elements + */ + public static List asList(@Nullable E first, @Nullable E second, E[] rest) { + return new TwoPlusArrayList(first, second, rest); + } + + /** + * Returns an unmodifiable list containing the specified first element and + * backed by the specified array of additional elements. Changes to the {@code + * rest} array will be reflected in the returned list. Unlike + * {@link Arrays#asList}, the returned list is unmodifiable. + * + *

+ * This is useful when a varargs method needs to use a signature such as + * {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload ambiguity + * or to enforce a minimum argument count. + * + *

+ * The returned list is serializable and implements {@link RandomAccess}. + * + * @param first the first element + * @param rest an array of additional elements, possibly empty + * @return an unmodifiable list containing the specified elements + */ + public static List asList(@Nullable E first, E[] rest) { + return new OnePlusArrayList(first, rest); + } + + /** + * Returns every possible list that can be formed by choosing one element from + * each of the given lists in order; the "n-ary + * Cartesian + * product" of the lists. For example: + * + *

+	 *    {@code
+	 *
+	 * Lists.cartesianProduct(ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of("A", "B", "C")))
+	 * }
+	 * 
+ * + *

+ * returns a list containing six lists in the following order: + * + *

    + *
  • {@code ImmutableList.of(1, "A")} + *
  • {@code ImmutableList.of(1, "B")} + *
  • {@code ImmutableList.of(1, "C")} + *
  • {@code ImmutableList.of(2, "A")} + *
  • {@code ImmutableList.of(2, "B")} + *
  • {@code ImmutableList.of(2, "C")} + *
+ * + *

+ * The result is guaranteed to be in the "traditional", lexicographical order + * for Cartesian products that you would get from nesting for loops: + * + *

+	 *    {@code
+	 *
+	 *   for (B b0 : lists.get(0)) {
+	 *     for (B b1 : lists.get(1)) {
+	 *       ...
+	 *       ImmutableList tuple = ImmutableList.of(b0, b1, ...);
+	 *       // operate on tuple
+	 *     }
+	 *   }}
+	 * 
+ * + *

+ * Note that if any input list is empty, the Cartesian product will also be + * empty. If no lists at all are provided (an empty list), the resulting + * Cartesian product has one element, an empty list (counter-intuitive, but + * mathematically consistent). + * + *

+ * Performance notes: while the cartesian product of lists of size + * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory + * consumption is much smaller. When the cartesian product is constructed, the + * input lists are merely copied. Only as the resulting list is iterated are the + * individual lists created, and these are not retained after iteration. + * + * @param lists the lists to choose elements from, in the order that the + * elements chosen from those lists should appear in the resulting + * lists + * @param any common base class shared by all axes (often just + * {@link Object}) + * @return the Cartesian product, as an immutable list containing immutable + * lists + * @throws IllegalArgumentException if the size of the cartesian product would + * be greater than {@link Integer#MAX_VALUE} + * @throws NullPointerException if {@code lists}, any one of the + * {@code lists}, or any element of a provided + * list is null + */ + static List> cartesianProduct(List... lists) { + return cartesianProduct(Arrays.asList(lists)); + } + + /** + * Returns every possible list that can be formed by choosing one element from + * each of the given lists in order; the "n-ary + * Cartesian + * product" of the lists. For example: + * + *

+	 *    {@code
+	 *
+	 * Lists.cartesianProduct(ImmutableList.of(ImmutableList.of(1, 2), ImmutableList.of("A", "B", "C")))
+	 * }
+	 * 
+ * + *

+ * returns a list containing six lists in the following order: + * + *

    + *
  • {@code ImmutableList.of(1, "A")} + *
  • {@code ImmutableList.of(1, "B")} + *
  • {@code ImmutableList.of(1, "C")} + *
  • {@code ImmutableList.of(2, "A")} + *
  • {@code ImmutableList.of(2, "B")} + *
  • {@code ImmutableList.of(2, "C")} + *
+ * + *

+ * The result is guaranteed to be in the "traditional", lexicographical order + * for Cartesian products that you would get from nesting for loops: + * + *

+	 *    {@code
+	 *
+	 *   for (B b0 : lists.get(0)) {
+	 *     for (B b1 : lists.get(1)) {
+	 *       ...
+	 *       ImmutableList tuple = ImmutableList.of(b0, b1, ...);
+	 *       // operate on tuple
+	 *     }
+	 *   }}
+	 * 
+ * + *

+ * Note that if any input list is empty, the Cartesian product will also be + * empty. If no lists at all are provided (an empty list), the resulting + * Cartesian product has one element, an empty list (counter-intuitive, but + * mathematically consistent). + * + *

+ * Performance notes: while the cartesian product of lists of size + * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory + * consumption is much smaller. When the cartesian product is constructed, the + * input lists are merely copied. Only as the resulting list is iterated are the + * individual lists created, and these are not retained after iteration. + * + * @param lists the lists to choose elements from, in the order that the + * elements chosen from those lists should appear in the resulting + * lists + * @param any common base class shared by all axes (often just + * {@link Object}) + * @return the Cartesian product, as an immutable list containing immutable + * lists + * @throws IllegalArgumentException if the size of the cartesian product would + * be greater than {@link Integer#MAX_VALUE} + * @throws NullPointerException if {@code lists}, any one of the + * {@code lists}, or any element of a provided + * list is null + */ + static List> cartesianProduct(List> lists) { + return CartesianList.create(lists); + } + + /** + * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + */ + static List cast(Iterable iterable) { + return (List) iterable; + } + + /** + * Returns a view of the specified {@code CharSequence} as a {@code + * List}, viewing {@code sequence} as a sequence of Unicode code + * units. The view does not support any modification operations, but reflects + * any changes to the underlying character sequence. + * + * @param sequence the character sequence to view as a {@code List} of + * characters + * @return an {@code List} view of the character sequence + * @since 7.0 + */ + @Beta + public static List charactersOf(CharSequence sequence) { + return new CharSequenceAsList(checkNotNull(sequence)); + } + + /** + * Returns a view of the specified string as an immutable list of {@code + * Character} values. + * + * @since 7.0 + */ + @Beta + public static ImmutableList charactersOf(String string) { + return new StringAsImmutableList(checkNotNull(string)); + } + + @VisibleForTesting + static int computeArrayListCapacity(int arraySize) { + checkNonnegative(arraySize, "arraySize"); + + // TODO(kevinb): Figure out the right behavior, and document it + return Ints.saturatedCast(5L + arraySize + (arraySize / 10)); + } + + /** + * An implementation of {@link List#equals(Object)}. + */ + static boolean equalsImpl(List list, @Nullable Object object) { + if (object == checkNotNull(list)) { + return true; + } + if (!(object instanceof List)) { + return false; + } + + List o = (List) object; + + return list.size() == o.size() && Iterators.elementsEqual(list.iterator(), o.iterator()); + } + + /** + * An implementation of {@link List#hashCode()}. + */ + static int hashCodeImpl(List list) { + // TODO(user): worth optimizing for RandomAccess? + int hashCode = 1; + for (Object o : list) { + hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); + + hashCode = ~~hashCode; + // needed to deal with GWT integer overflow + } + return hashCode; + } + + /** + * An implementation of {@link List#indexOf(Object)}. + */ + static int indexOfImpl(List list, @Nullable Object element) { + ListIterator listIterator = list.listIterator(); + while (listIterator.hasNext()) { + if (Objects.equal(element, listIterator.next())) { + return listIterator.previousIndex(); + } + } + return -1; + } + + /** + * An implementation of {@link List#lastIndexOf(Object)}. + */ + static int lastIndexOfImpl(List list, @Nullable Object element) { + ListIterator listIterator = list.listIterator(list.size()); + while (listIterator.hasPrevious()) { + if (Objects.equal(element, listIterator.previous())) { + return listIterator.nextIndex(); + } + } + return -1; + } + + /** + * Returns an implementation of {@link List#listIterator(int)}. + */ + static ListIterator listIteratorImpl(List list, int index) { + return new AbstractListWrapper(list).listIterator(index); + } + /** * Creates a mutable, empty {@code ArrayList} instance. * @@ -107,14 +862,6 @@ public final class Lists { return list; } - @VisibleForTesting - static int computeArrayListCapacity(int arraySize) { - checkNonnegative(arraySize, "arraySize"); - - // TODO(kevinb): Figure out the right behavior, and document it - return Ints.saturatedCast(5L + arraySize + (arraySize / 10)); - } - /** * Creates a mutable {@code ArrayList} instance containing the given * elements. @@ -200,8 +947,6 @@ public final class Lists { return new ArrayList(computeArrayListCapacity(estimatedSize)); } - // LinkedList - /** * Creates an empty {@code LinkedList} instance. * @@ -230,251 +975,78 @@ public final class Lists { } /** - * Returns an unmodifiable list containing the specified first element and - * backed by the specified array of additional elements. Changes to the {@code - * rest} array will be reflected in the returned list. Unlike - * {@link Arrays#asList}, the returned list is unmodifiable. + * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, + * each of the same size (the final list may be smaller). For example, + * partitioning a list containing {@code [a, b, c, d, e]} with a partition size + * of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing two inner + * lists of three and two elements, all in the original order. * *

- * This is useful when a varargs method needs to use a signature such as - * {@code (Foo firstFoo, Foo... moreFoos)}, in order to avoid overload ambiguity - * or to enforce a minimum argument count. + * The outer list is unmodifiable, but reflects the latest state of the source + * list. The inner lists are sublist views of the original list, produced on + * demand using {@link List#subList(int, int)}, and are subject to all the usual + * caveats about modification as explained in that API. * - *

- * The returned list is serializable and implements {@link RandomAccess}. - * - * @param first the first element - * @param rest an array of additional elements, possibly empty - * @return an unmodifiable list containing the specified elements + * @param list the list to return consecutive sublists of + * @param size the desired size of each sublist (the last may be smaller) + * @return a list of consecutive sublists + * @throws IllegalArgumentException if {@code partitionSize} is nonpositive */ - public static List asList(@Nullable E first, E[] rest) { - return new OnePlusArrayList(first, rest); - } - - /** @see Lists#asList(Object, Object[]) */ - private static class OnePlusArrayList extends AbstractList implements Serializable, RandomAccess { - final E first; - final E[] rest; - - OnePlusArrayList(@Nullable E first, E[] rest) { - this.first = first; - this.rest = checkNotNull(rest); - } - - @Override - public int size() { - return rest.length + 1; - } - - @Override - public E get(int index) { - // check explicitly so the IOOBE will have the right message - checkElementIndex(index, size()); - return (index == 0) ? first : rest[index - 1]; - } - - private static final long serialVersionUID = 0; + public static List> partition(List list, int size) { + checkNotNull(list); + checkArgument(size > 0); + return (list instanceof RandomAccess) ? new RandomAccessPartition(list, size) : new Partition(list, size); } /** - * Returns an unmodifiable list containing the specified first and second - * element, and backed by the specified array of additional elements. Changes to - * the {@code rest} array will be reflected in the returned list. Unlike - * {@link Arrays#asList}, the returned list is unmodifiable. + * Returns a reversed view of the specified list. For example, {@code + * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3, + * 2, 1}. The returned list is backed by this list, so changes in the returned + * list are reflected in this list, and vice-versa. The returned list supports + * all of the optional list operations supported by this list. * *

- * This is useful when a varargs method needs to use a signature such as - * {@code (Foo firstFoo, Foo secondFoo, Foo... moreFoos)}, in order to avoid - * overload ambiguity or to enforce a minimum argument count. + * The returned list is random-access if the specified list is random access. * - *

- * The returned list is serializable and implements {@link RandomAccess}. - * - * @param first the first element - * @param second the second element - * @param rest an array of additional elements, possibly empty - * @return an unmodifiable list containing the specified elements + * @since 7.0 */ - public static List asList(@Nullable E first, @Nullable E second, E[] rest) { - return new TwoPlusArrayList(first, second, rest); - } - - /** @see Lists#asList(Object, Object, Object[]) */ - private static class TwoPlusArrayList extends AbstractList implements Serializable, RandomAccess { - final E first; - final E second; - final E[] rest; - - TwoPlusArrayList(@Nullable E first, @Nullable E second, E[] rest) { - this.first = first; - this.second = second; - this.rest = checkNotNull(rest); + public static List reverse(List list) { + if (list instanceof ImmutableList) { + return ((ImmutableList) list).reverse(); + } else if (list instanceof ReverseList) { + return ((ReverseList) list).getForwardList(); + } else if (list instanceof RandomAccess) { + return new RandomAccessReverseList(list); + } else { + return new ReverseList(list); } - - @Override - public int size() { - return rest.length + 2; - } - - @Override - public E get(int index) { - switch (index) { - case 0: - return first; - case 1: - return second; - default: - // check explicitly so the IOOBE will have the right message - checkElementIndex(index, size()); - return rest[index - 2]; - } - } - - private static final long serialVersionUID = 0; } /** - * Returns every possible list that can be formed by choosing one element from - * each of the given lists in order; the "n-ary - * Cartesian - * product" of the lists. For example: - * - *

-	 *    {@code
-	 *
-	 *   Lists.cartesianProduct(ImmutableList.of(
-	 *       ImmutableList.of(1, 2),
-	 *       ImmutableList.of("A", "B", "C")))}
-	 * 
- * - *

- * returns a list containing six lists in the following order: - * - *

    - *
  • {@code ImmutableList.of(1, "A")} - *
  • {@code ImmutableList.of(1, "B")} - *
  • {@code ImmutableList.of(1, "C")} - *
  • {@code ImmutableList.of(2, "A")} - *
  • {@code ImmutableList.of(2, "B")} - *
  • {@code ImmutableList.of(2, "C")} - *
- * - *

- * The result is guaranteed to be in the "traditional", lexicographical order - * for Cartesian products that you would get from nesting for loops: - * - *

-	 *    {@code
-	 *
-	 *   for (B b0 : lists.get(0)) {
-	 *     for (B b1 : lists.get(1)) {
-	 *       ...
-	 *       ImmutableList tuple = ImmutableList.of(b0, b1, ...);
-	 *       // operate on tuple
-	 *     }
-	 *   }}
-	 * 
- * - *

- * Note that if any input list is empty, the Cartesian product will also be - * empty. If no lists at all are provided (an empty list), the resulting - * Cartesian product has one element, an empty list (counter-intuitive, but - * mathematically consistent). - * - *

- * Performance notes: while the cartesian product of lists of size - * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory - * consumption is much smaller. When the cartesian product is constructed, the - * input lists are merely copied. Only as the resulting list is iterated are the - * individual lists created, and these are not retained after iteration. - * - * @param lists the lists to choose elements from, in the order that the - * elements chosen from those lists should appear in the resulting - * lists - * @param any common base class shared by all axes (often just - * {@link Object}) - * @return the Cartesian product, as an immutable list containing immutable - * lists - * @throws IllegalArgumentException if the size of the cartesian product would - * be greater than {@link Integer#MAX_VALUE} - * @throws NullPointerException if {@code lists}, any one of the - * {@code lists}, or any element of a provided - * list is null + * An implementation of {@link List#subList(int, int)}. */ - static List> cartesianProduct(List> lists) { - return CartesianList.create(lists); - } + static List subListImpl(final List list, int fromIndex, int toIndex) { + List wrapper; + if (list instanceof RandomAccess) { + wrapper = new RandomAccessListWrapper(list) { + private static final long serialVersionUID = 0; - /** - * Returns every possible list that can be formed by choosing one element from - * each of the given lists in order; the "n-ary - * Cartesian - * product" of the lists. For example: - * - *

-	 *    {@code
-	 *
-	 *   Lists.cartesianProduct(ImmutableList.of(
-	 *       ImmutableList.of(1, 2),
-	 *       ImmutableList.of("A", "B", "C")))}
-	 * 
- * - *

- * returns a list containing six lists in the following order: - * - *

    - *
  • {@code ImmutableList.of(1, "A")} - *
  • {@code ImmutableList.of(1, "B")} - *
  • {@code ImmutableList.of(1, "C")} - *
  • {@code ImmutableList.of(2, "A")} - *
  • {@code ImmutableList.of(2, "B")} - *
  • {@code ImmutableList.of(2, "C")} - *
- * - *

- * The result is guaranteed to be in the "traditional", lexicographical order - * for Cartesian products that you would get from nesting for loops: - * - *

-	 *    {@code
-	 *
-	 *   for (B b0 : lists.get(0)) {
-	 *     for (B b1 : lists.get(1)) {
-	 *       ...
-	 *       ImmutableList tuple = ImmutableList.of(b0, b1, ...);
-	 *       // operate on tuple
-	 *     }
-	 *   }}
-	 * 
- * - *

- * Note that if any input list is empty, the Cartesian product will also be - * empty. If no lists at all are provided (an empty list), the resulting - * Cartesian product has one element, an empty list (counter-intuitive, but - * mathematically consistent). - * - *

- * Performance notes: while the cartesian product of lists of size - * {@code m, n, p} is a list of size {@code m x n x p}, its actual memory - * consumption is much smaller. When the cartesian product is constructed, the - * input lists are merely copied. Only as the resulting list is iterated are the - * individual lists created, and these are not retained after iteration. - * - * @param lists the lists to choose elements from, in the order that the - * elements chosen from those lists should appear in the resulting - * lists - * @param any common base class shared by all axes (often just - * {@link Object}) - * @return the Cartesian product, as an immutable list containing immutable - * lists - * @throws IllegalArgumentException if the size of the cartesian product would - * be greater than {@link Integer#MAX_VALUE} - * @throws NullPointerException if {@code lists}, any one of the - * {@code lists}, or any element of a provided - * list is null - */ - static List> cartesianProduct(List... lists) { - return cartesianProduct(Arrays.asList(lists)); + @Override + public ListIterator listIterator(int index) { + return backingList.listIterator(index); + } + }; + } else { + wrapper = new AbstractListWrapper(list) { + private static final long serialVersionUID = 0; + + @Override + public ListIterator listIterator(int index) { + return backingList.listIterator(index); + } + }; + } + return wrapper.subList(fromIndex, toIndex); } /** @@ -518,580 +1090,6 @@ public final class Lists { : new TransformingSequentialList(fromList, function); } - /** - * Implementation of a sequential transforming list. - * - * @see Lists#transform - */ - private static class TransformingSequentialList extends AbstractSequentialList implements Serializable { - final List fromList; - final Function function; - - TransformingSequentialList(List fromList, Function function) { - this.fromList = checkNotNull(fromList); - this.function = checkNotNull(function); - } - - /** - * The default implementation inherited is based on iteration and removal of - * each element which can be overkill. That's why we forward this call directly - * to the backing list. - */ - @Override - public void clear() { - fromList.clear(); - } - - @Override - public int size() { - return fromList.size(); - } - - @Override - public ListIterator listIterator(final int index) { - return new TransformedListIterator(fromList.listIterator(index)) { - @Override - T transform(F from) { - return function.apply(from); - } - }; - } - - private static final long serialVersionUID = 0; - } - - /** - * Implementation of a transforming random access list. We try to make as many - * of these methods pass-through to the source list as possible so that the - * performance characteristics of the source list and transformed list are - * similar. - * - * @see Lists#transform - */ - private static class TransformingRandomAccessList extends AbstractList - implements RandomAccess, Serializable { - final List fromList; - final Function function; - - TransformingRandomAccessList(List fromList, Function function) { - this.fromList = checkNotNull(fromList); - this.function = checkNotNull(function); - } - - @Override - public void clear() { - fromList.clear(); - } - - @Override - public T get(int index) { - return function.apply(fromList.get(index)); - } - - @Override - public Iterator iterator() { - return listIterator(); - } - - @Override - public ListIterator listIterator(int index) { - return new TransformedListIterator(fromList.listIterator(index)) { - @Override - T transform(F from) { - return function.apply(from); - } - }; - } - - @Override - public boolean isEmpty() { - return fromList.isEmpty(); - } - - @Override - public T remove(int index) { - return function.apply(fromList.remove(index)); - } - - @Override - public int size() { - return fromList.size(); - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, - * each of the same size (the final list may be smaller). For example, - * partitioning a list containing {@code [a, b, c, d, e]} with a partition size - * of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list containing two inner - * lists of three and two elements, all in the original order. - * - *

- * The outer list is unmodifiable, but reflects the latest state of the source - * list. The inner lists are sublist views of the original list, produced on - * demand using {@link List#subList(int, int)}, and are subject to all the usual - * caveats about modification as explained in that API. - * - * @param list the list to return consecutive sublists of - * @param size the desired size of each sublist (the last may be smaller) - * @return a list of consecutive sublists - * @throws IllegalArgumentException if {@code partitionSize} is nonpositive - */ - public static List> partition(List list, int size) { - checkNotNull(list); - checkArgument(size > 0); - return (list instanceof RandomAccess) ? new RandomAccessPartition(list, size) : new Partition(list, size); - } - - private static class Partition extends AbstractList> { - final List list; - final int size; - - Partition(List list, int size) { - this.list = list; - this.size = size; - } - - @Override - public List get(int index) { - checkElementIndex(index, size()); - int start = index * size; - int end = Math.min(start + size, list.size()); - return list.subList(start, end); - } - - @Override - public int size() { - return IntMath.divide(list.size(), size, RoundingMode.CEILING); - } - - @Override - public boolean isEmpty() { - return list.isEmpty(); - } - } - - private static class RandomAccessPartition extends Partition implements RandomAccess { - RandomAccessPartition(List list, int size) { - super(list, size); - } - } - - /** - * Returns a view of the specified string as an immutable list of {@code - * Character} values. - * - * @since 7.0 - */ - @Beta - public static ImmutableList charactersOf(String string) { - return new StringAsImmutableList(checkNotNull(string)); - } - - @SuppressWarnings("serial") // serialized using ImmutableList serialization - private static final class StringAsImmutableList extends ImmutableList { - - private final String string; - - StringAsImmutableList(String string) { - this.string = string; - } - - @Override - public int indexOf(@Nullable Object object) { - return (object instanceof Character) ? string.indexOf((Character) object) : -1; - } - - @Override - public int lastIndexOf(@Nullable Object object) { - return (object instanceof Character) ? string.lastIndexOf((Character) object) : -1; - } - - @Override - public ImmutableList subList(int fromIndex, int toIndex) { - checkPositionIndexes(fromIndex, toIndex, size()); // for GWT - return charactersOf(string.substring(fromIndex, toIndex)); - } - - @Override - boolean isPartialView() { - return false; - } - - @Override - public Character get(int index) { - checkElementIndex(index, size()); // for GWT - return string.charAt(index); - } - - @Override - public int size() { - return string.length(); - } - } - - /** - * Returns a view of the specified {@code CharSequence} as a {@code - * List}, viewing {@code sequence} as a sequence of Unicode code - * units. The view does not support any modification operations, but reflects - * any changes to the underlying character sequence. - * - * @param sequence the character sequence to view as a {@code List} of - * characters - * @return an {@code List} view of the character sequence - * @since 7.0 - */ - @Beta - public static List charactersOf(CharSequence sequence) { - return new CharSequenceAsList(checkNotNull(sequence)); - } - - private static final class CharSequenceAsList extends AbstractList { - private final CharSequence sequence; - - CharSequenceAsList(CharSequence sequence) { - this.sequence = sequence; - } - - @Override - public Character get(int index) { - checkElementIndex(index, size()); // for GWT - return sequence.charAt(index); - } - - @Override - public int size() { - return sequence.length(); - } - } - - /** - * Returns a reversed view of the specified list. For example, {@code - * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3, - * 2, 1}. The returned list is backed by this list, so changes in the returned - * list are reflected in this list, and vice-versa. The returned list supports - * all of the optional list operations supported by this list. - * - *

- * The returned list is random-access if the specified list is random access. - * - * @since 7.0 - */ - public static List reverse(List list) { - if (list instanceof ImmutableList) { - return ((ImmutableList) list).reverse(); - } else if (list instanceof ReverseList) { - return ((ReverseList) list).getForwardList(); - } else if (list instanceof RandomAccess) { - return new RandomAccessReverseList(list); - } else { - return new ReverseList(list); - } - } - - private static class ReverseList extends AbstractList { - private final List forwardList; - - ReverseList(List forwardList) { - this.forwardList = checkNotNull(forwardList); - } - - List getForwardList() { - return forwardList; - } - - private int reverseIndex(int index) { - int size = size(); - checkElementIndex(index, size); - return (size - 1) - index; - } - - private int reversePosition(int index) { - int size = size(); - checkPositionIndex(index, size); - return size - index; - } - - @Override - public void add(int index, @Nullable T element) { - forwardList.add(reversePosition(index), element); - } - - @Override - public void clear() { - forwardList.clear(); - } - - @Override - public T remove(int index) { - return forwardList.remove(reverseIndex(index)); - } - - @Override - protected void removeRange(int fromIndex, int toIndex) { - subList(fromIndex, toIndex).clear(); - } - - @Override - public T set(int index, @Nullable T element) { - return forwardList.set(reverseIndex(index), element); - } - - @Override - public T get(int index) { - return forwardList.get(reverseIndex(index)); - } - - @Override - public int size() { - return forwardList.size(); - } - - @Override - public List subList(int fromIndex, int toIndex) { - checkPositionIndexes(fromIndex, toIndex, size()); - return reverse(forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex))); - } - - @Override - public Iterator iterator() { - return listIterator(); - } - - @Override - public ListIterator listIterator(int index) { - int start = reversePosition(index); - final ListIterator forwardIterator = forwardList.listIterator(start); - return new ListIterator() { - - boolean canRemoveOrSet; - - @Override - public void add(T e) { - forwardIterator.add(e); - forwardIterator.previous(); - canRemoveOrSet = false; - } - - @Override - public boolean hasNext() { - return forwardIterator.hasPrevious(); - } - - @Override - public boolean hasPrevious() { - return forwardIterator.hasNext(); - } - - @Override - public T next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - canRemoveOrSet = true; - return forwardIterator.previous(); - } - - @Override - public int nextIndex() { - return reversePosition(forwardIterator.nextIndex()); - } - - @Override - public T previous() { - if (!hasPrevious()) { - throw new NoSuchElementException(); - } - canRemoveOrSet = true; - return forwardIterator.next(); - } - - @Override - public int previousIndex() { - return nextIndex() - 1; - } - - @Override - public void remove() { - checkRemove(canRemoveOrSet); - forwardIterator.remove(); - canRemoveOrSet = false; - } - - @Override - public void set(T e) { - checkState(canRemoveOrSet); - forwardIterator.set(e); - } - }; - } - } - - private static class RandomAccessReverseList extends ReverseList implements RandomAccess { - RandomAccessReverseList(List forwardList) { - super(forwardList); - } - } - - /** - * An implementation of {@link List#hashCode()}. - */ - static int hashCodeImpl(List list) { - // TODO(user): worth optimizing for RandomAccess? - int hashCode = 1; - for (Object o : list) { - hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); - - hashCode = ~~hashCode; - // needed to deal with GWT integer overflow - } - return hashCode; - } - - /** - * An implementation of {@link List#equals(Object)}. - */ - static boolean equalsImpl(List list, @Nullable Object object) { - if (object == checkNotNull(list)) { - return true; - } - if (!(object instanceof List)) { - return false; - } - - List o = (List) object; - - return list.size() == o.size() && Iterators.elementsEqual(list.iterator(), o.iterator()); - } - - /** - * An implementation of {@link List#addAll(int, Collection)}. - */ - static boolean addAllImpl(List list, int index, Iterable elements) { - boolean changed = false; - ListIterator listIterator = list.listIterator(index); - for (E e : elements) { - listIterator.add(e); - changed = true; - } - return changed; - } - - /** - * An implementation of {@link List#indexOf(Object)}. - */ - static int indexOfImpl(List list, @Nullable Object element) { - ListIterator listIterator = list.listIterator(); - while (listIterator.hasNext()) { - if (Objects.equal(element, listIterator.next())) { - return listIterator.previousIndex(); - } - } - return -1; - } - - /** - * An implementation of {@link List#lastIndexOf(Object)}. - */ - static int lastIndexOfImpl(List list, @Nullable Object element) { - ListIterator listIterator = list.listIterator(list.size()); - while (listIterator.hasPrevious()) { - if (Objects.equal(element, listIterator.previous())) { - return listIterator.nextIndex(); - } - } - return -1; - } - - /** - * Returns an implementation of {@link List#listIterator(int)}. - */ - static ListIterator listIteratorImpl(List list, int index) { - return new AbstractListWrapper(list).listIterator(index); - } - - /** - * An implementation of {@link List#subList(int, int)}. - */ - static List subListImpl(final List list, int fromIndex, int toIndex) { - List wrapper; - if (list instanceof RandomAccess) { - wrapper = new RandomAccessListWrapper(list) { - @Override - public ListIterator listIterator(int index) { - return backingList.listIterator(index); - } - - private static final long serialVersionUID = 0; - }; - } else { - wrapper = new AbstractListWrapper(list) { - @Override - public ListIterator listIterator(int index) { - return backingList.listIterator(index); - } - - private static final long serialVersionUID = 0; - }; - } - return wrapper.subList(fromIndex, toIndex); - } - - private static class AbstractListWrapper extends AbstractList { - final List backingList; - - AbstractListWrapper(List backingList) { - this.backingList = checkNotNull(backingList); - } - - @Override - public void add(int index, E element) { - backingList.add(index, element); - } - - @Override - public boolean addAll(int index, Collection c) { - return backingList.addAll(index, c); - } - - @Override - public E get(int index) { - return backingList.get(index); - } - - @Override - public E remove(int index) { - return backingList.remove(index); - } - - @Override - public E set(int index, E element) { - return backingList.set(index, element); - } - - @Override - public boolean contains(Object o) { - return backingList.contains(o); - } - - @Override - public int size() { - return backingList.size(); - } - } - - private static class RandomAccessListWrapper extends AbstractListWrapper implements RandomAccess { - RandomAccessListWrapper(List backingList) { - super(backingList); - } - } - - /** - * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 - */ - static List cast(Iterable iterable) { - return (List) iterable; + private Lists() { } } diff --git a/src/main/java/com/google/common/collect/MapConstraint.java b/src/main/java/com/google/common/collect/MapConstraint.java index f22a207f..67392caa 100644 --- a/src/main/java/com/google/common/collect/MapConstraint.java +++ b/src/main/java/com/google/common/collect/MapConstraint.java @@ -30,11 +30,12 @@ import com.google.common.annotations.GwtCompatible; *

  *    {@code
  *
- *   public void checkKeyValue(Object key, Object value) {
- *     if (key == null || value == null) {
- *       throw new NullPointerException();
- *     }
- *   }}
+ * public void checkKeyValue(Object key, Object value) {
+ * 	if (key == null || value == null) {
+ * 		throw new NullPointerException();
+ * 	}
+ * }
+ * }
  * 
* *

diff --git a/src/main/java/com/google/common/collect/MapConstraints.java b/src/main/java/com/google/common/collect/MapConstraints.java index 7a3a2a60..0bd7427d 100644 --- a/src/main/java/com/google/common/collect/MapConstraints.java +++ b/src/main/java/com/google/common/collect/MapConstraints.java @@ -44,309 +44,159 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible public final class MapConstraints { - private MapConstraints() { - } + /** @see MapConstraints#constrainedAsMapEntries */ + static class ConstrainedAsMapEntries extends ForwardingSet>> { + private final MapConstraint constraint; + private final Set>> entries; - /** - * Returns a constraint that verifies that neither the key nor the value is - * null. If either is null, a {@link NullPointerException} is thrown. - */ - public static MapConstraint notNull() { - return NotNullMapConstraint.INSTANCE; - } - - // enum singleton pattern - private enum NotNullMapConstraint implements MapConstraint { - INSTANCE; - - @Override - public void checkKeyValue(Object key, Object value) { - checkNotNull(key); - checkNotNull(value); + ConstrainedAsMapEntries(Set>> entries, MapConstraint constraint) { + this.entries = entries; + this.constraint = constraint; } @Override - public String toString() { - return "Not null"; - } - } - - /** - * Returns a constrained view of the specified map, using the specified - * constraint. Any operations that add new mappings will call the provided - * constraint. However, this method does not verify that existing mappings - * satisfy the constraint. - * - *

- * The returned map is not serializable. - * - * @param map the map to constrain - * @param constraint the constraint that validates added entries - * @return a constrained view of the specified map - */ - public static Map constrainedMap(Map map, MapConstraint constraint) { - return new ConstrainedMap(map, constraint); - } - - /** - * Returns a constrained view of the specified multimap, using the specified - * constraint. Any operations that add new mappings will call the provided - * constraint. However, this method does not verify that existing mappings - * satisfy the constraint. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are not - * constrained. - * - *

- * The returned multimap is not serializable. - * - * @param multimap the multimap to constrain - * @param constraint the constraint that validates added entries - * @return a constrained view of the multimap - */ - public static Multimap constrainedMultimap(Multimap multimap, - MapConstraint constraint) { - return new ConstrainedMultimap(multimap, constraint); - } - - /** - * Returns a constrained view of the specified list multimap, using the - * specified constraint. Any operations that add new mappings will call the - * provided constraint. However, this method does not verify that existing - * mappings satisfy the constraint. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are not - * constrained. - * - *

- * The returned multimap is not serializable. - * - * @param multimap the multimap to constrain - * @param constraint the constraint that validates added entries - * @return a constrained view of the specified multimap - */ - public static ListMultimap constrainedListMultimap(ListMultimap multimap, - MapConstraint constraint) { - return new ConstrainedListMultimap(multimap, constraint); - } - - /** - * Returns a constrained view of the specified set multimap, using the specified - * constraint. Any operations that add new mappings will call the provided - * constraint. However, this method does not verify that existing mappings - * satisfy the constraint. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are not - * constrained. - *

- * The returned multimap is not serializable. - * - * @param multimap the multimap to constrain - * @param constraint the constraint that validates added entries - * @return a constrained view of the specified multimap - */ - public static SetMultimap constrainedSetMultimap(SetMultimap multimap, - MapConstraint constraint) { - return new ConstrainedSetMultimap(multimap, constraint); - } - - /** - * Returns a constrained view of the specified sorted-set multimap, using the - * specified constraint. Any operations that add new mappings will call the - * provided constraint. However, this method does not verify that existing - * mappings satisfy the constraint. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are not - * constrained. - *

- * The returned multimap is not serializable. - * - * @param multimap the multimap to constrain - * @param constraint the constraint that validates added entries - * @return a constrained view of the specified multimap - */ - public static SortedSetMultimap constrainedSortedSetMultimap(SortedSetMultimap multimap, - MapConstraint constraint) { - return new ConstrainedSortedSetMultimap(multimap, constraint); - } - - /** - * Returns a constrained view of the specified entry, using the specified - * constraint. The {@link Entry#setValue} operation will be verified with the - * constraint. - * - * @param entry the entry to constrain - * @param constraint the constraint for the entry - * @return a constrained view of the specified entry - */ - private static Entry constrainedEntry(final Entry entry, - final MapConstraint constraint) { - checkNotNull(entry); - checkNotNull(constraint); - return new ForwardingMapEntry() { - @Override - protected Entry delegate() { - return entry; - } - - @Override - public V setValue(V value) { - constraint.checkKeyValue(getKey(), value); - return entry.setValue(value); - } - }; - } - - /** - * Returns a constrained view of the specified {@code asMap} entry, using the - * specified constraint. The {@link Entry#setValue} operation will be verified - * with the constraint, and the collection returned by {@link Entry#getValue} - * will be similarly constrained. - * - * @param entry the {@code asMap} entry to constrain - * @param constraint the constraint for the entry - * @return a constrained view of the specified entry - */ - private static Entry> constrainedAsMapEntry(final Entry> entry, - final MapConstraint constraint) { - checkNotNull(entry); - checkNotNull(constraint); - return new ForwardingMapEntry>() { - @Override - protected Entry> delegate() { - return entry; - } - - @Override - public Collection getValue() { - return Constraints.constrainedTypePreservingCollection(entry.getValue(), new Constraint() { - @Override - public V checkElement(V value) { - constraint.checkKeyValue(getKey(), value); - return value; - } - }); - } - }; - } - - /** - * Returns a constrained view of the specified set of {@code asMap} entries, - * using the specified constraint. The {@link Entry#setValue} operation will be - * verified with the constraint, and the collection returned by - * {@link Entry#getValue} will be similarly constrained. The {@code add} and - * {@code - * addAll} operations simply forward to the underlying set, which throws an - * {@link UnsupportedOperationException} per the multimap specification. - * - * @param entries the entries to constrain - * @param constraint the constraint for the entries - * @return a constrained view of the entries - */ - private static Set>> constrainedAsMapEntries(Set>> entries, - MapConstraint constraint) { - return new ConstrainedAsMapEntries(entries, constraint); - } - - /** - * Returns a constrained view of the specified collection (or set) of entries, - * using the specified constraint. The {@link Entry#setValue} operation will be - * verified with the constraint, along with add operations on the returned - * collection. The {@code add} and {@code addAll} operations simply forward to - * the underlying collection, which throws an - * {@link UnsupportedOperationException} per the map and multimap specification. - * - * @param entries the entries to constrain - * @param constraint the constraint for the entries - * @return a constrained view of the specified entries - */ - private static Collection> constrainedEntries(Collection> entries, - MapConstraint constraint) { - if (entries instanceof Set) { - return constrainedEntrySet((Set>) entries, constraint); - } - return new ConstrainedEntries(entries, constraint); - } - - /** - * Returns a constrained view of the specified set of entries, using the - * specified constraint. The {@link Entry#setValue} operation will be verified - * with the constraint, along with add operations on the returned set. The - * {@code add} and {@code addAll} operations simply forward to the underlying - * set, which throws an {@link UnsupportedOperationException} per the map and - * multimap specification. - * - *

- * The returned multimap is not serializable. - * - * @param entries the entries to constrain - * @param constraint the constraint for the entries - * @return a constrained view of the specified entries - */ - private static Set> constrainedEntrySet(Set> entries, - MapConstraint constraint) { - return new ConstrainedEntrySet(entries, constraint); - } - - /** @see MapConstraints#constrainedMap */ - static class ConstrainedMap extends ForwardingMap { - private final Map delegate; - final MapConstraint constraint; - private transient Set> entrySet; - - ConstrainedMap(Map delegate, MapConstraint constraint) { - this.delegate = checkNotNull(delegate); - this.constraint = checkNotNull(constraint); + public boolean contains(Object o) { + return Maps.containsEntryImpl(delegate(), o); } @Override - protected Map delegate() { + public boolean containsAll(Collection c) { + return standardContainsAll(c); + } + + // See Collections.CheckedMap.CheckedEntrySet for details on attacks. + + @Override + protected Set>> delegate() { + return entries; + } + + @Override + public boolean equals(@Nullable Object object) { + return standardEquals(object); + } + + @Override + public int hashCode() { + return standardHashCode(); + } + + @Override + public Iterator>> iterator() { + final Iterator>> iterator = entries.iterator(); + return new ForwardingIterator>>() { + @Override + protected Iterator>> delegate() { + return iterator; + } + + @Override + public Entry> next() { + return constrainedAsMapEntry(iterator.next(), constraint); + } + }; + } + + @Override + public boolean remove(Object o) { + return Maps.removeEntryImpl(delegate(), o); + } + + @Override + public boolean removeAll(Collection c) { + return standardRemoveAll(c); + } + + @Override + public boolean retainAll(Collection c) { + return standardRetainAll(c); + } + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } + } + + /** @see ConstrainedMultimap#asMap */ + private static class ConstrainedAsMapValues extends ForwardingCollection> { + final Collection> delegate; + final Set>> entrySet; + + /** + * @param entrySet map entries, linking each key with its corresponding values, + * that already enforce the constraint + */ + ConstrainedAsMapValues(Collection> delegate, Set>> entrySet) { + this.delegate = delegate; + this.entrySet = entrySet; + } + + @Override + public boolean contains(Object o) { + return standardContains(o); + } + + @Override + public boolean containsAll(Collection c) { + return standardContainsAll(c); + } + + @Override + protected Collection> delegate() { return delegate; } @Override - public Set> entrySet() { - Set> result = entrySet; - if (result == null) { - entrySet = result = constrainedEntrySet(delegate.entrySet(), constraint); - } - return result; + public Iterator> iterator() { + final Iterator>> iterator = entrySet.iterator(); + return new Iterator>() { + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public Collection next() { + return iterator.next().getValue(); + } + + @Override + public void remove() { + iterator.remove(); + } + }; } @Override - public V put(K key, V value) { - constraint.checkKeyValue(key, value); - return delegate.put(key, value); + public boolean remove(Object o) { + return standardRemove(o); } @Override - public void putAll(Map map) { - delegate.putAll(checkMap(map, constraint)); + public boolean removeAll(Collection c) { + return standardRemoveAll(c); } - } - /** - * Returns a constrained view of the specified bimap, using the specified - * constraint. Any operations that modify the bimap will have the associated - * keys and values verified with the constraint. - * - *

- * The returned bimap is not serializable. - * - * @param map the bimap to constrain - * @param constraint the constraint that validates added entries - * @return a constrained view of the specified bimap - */ - public static BiMap constrainedBiMap(BiMap map, MapConstraint constraint) { - return new ConstrainedBiMap(map, null, constraint); + @Override + public boolean retainAll(Collection c) { + return standardRetainAll(c); + } + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } } /** @see MapConstraints#constrainedBiMap */ @@ -397,17 +247,149 @@ public final class MapConstraints { } } - /** @see MapConstraints#constrainedBiMap */ - private static class InverseConstraint implements MapConstraint { - final MapConstraint constraint; + /** @see MapConstraints#constrainedEntries */ + private static class ConstrainedEntries extends ForwardingCollection> { + final MapConstraint constraint; + final Collection> entries; - public InverseConstraint(MapConstraint constraint) { + ConstrainedEntries(Collection> entries, MapConstraint constraint) { + this.entries = entries; + this.constraint = constraint; + } + + @Override + public boolean contains(Object o) { + return Maps.containsEntryImpl(delegate(), o); + } + + @Override + public boolean containsAll(Collection c) { + return standardContainsAll(c); + } + + // See Collections.CheckedMap.CheckedEntrySet for details on attacks. + + @Override + protected Collection> delegate() { + return entries; + } + + @Override + public Iterator> iterator() { + final Iterator> iterator = entries.iterator(); + return new ForwardingIterator>() { + @Override + protected Iterator> delegate() { + return iterator; + } + + @Override + public Entry next() { + return constrainedEntry(iterator.next(), constraint); + } + }; + } + + @Override + public boolean remove(Object o) { + return Maps.removeEntryImpl(delegate(), o); + } + + @Override + public boolean removeAll(Collection c) { + return standardRemoveAll(c); + } + + @Override + public boolean retainAll(Collection c) { + return standardRetainAll(c); + } + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } + } + + /** @see MapConstraints#constrainedEntrySet */ + static class ConstrainedEntrySet extends ConstrainedEntries implements Set> { + ConstrainedEntrySet(Set> entries, MapConstraint constraint) { + super(entries, constraint); + } + + // See Collections.CheckedMap.CheckedEntrySet for details on attacks. + + @Override + public boolean equals(@Nullable Object object) { + return Sets.equalsImpl(this, object); + } + + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); + } + } + + private static class ConstrainedListMultimap extends ConstrainedMultimap implements ListMultimap { + ConstrainedListMultimap(ListMultimap delegate, MapConstraint constraint) { + super(delegate, constraint); + } + + @Override + public List get(K key) { + return (List) super.get(key); + } + + @Override + public List removeAll(Object key) { + return (List) super.removeAll(key); + } + + @Override + public List replaceValues(K key, Iterable values) { + return (List) super.replaceValues(key, values); + } + } + + /** @see MapConstraints#constrainedMap */ + static class ConstrainedMap extends ForwardingMap { + private final Map delegate; + final MapConstraint constraint; + private transient Set> entrySet; + + ConstrainedMap(Map delegate, MapConstraint constraint) { + this.delegate = checkNotNull(delegate); this.constraint = checkNotNull(constraint); } @Override - public void checkKeyValue(K key, V value) { - constraint.checkKeyValue(value, key); + protected Map delegate() { + return delegate; + } + + @Override + public Set> entrySet() { + Set> result = entrySet; + if (result == null) { + entrySet = result = constrainedEntrySet(delegate.entrySet(), constraint); + } + return result; + } + + @Override + public V put(K key, V value) { + constraint.checkKeyValue(key, value); + return delegate.put(key, value); + } + + @Override + public void putAll(Map map) { + delegate.putAll(checkMap(map, constraint)); } } @@ -423,11 +405,6 @@ public final class MapConstraints { this.constraint = checkNotNull(constraint); } - @Override - protected Multimap delegate() { - return delegate; - } - @Override public Map> asMap() { Map> result = asMap; @@ -438,6 +415,11 @@ public final class MapConstraints { Set>> entrySet; Collection> values; + @Override + public boolean containsValue(Object o) { + return values().contains(o); + } + @Override protected Map> delegate() { return asMapDelegate; @@ -471,16 +453,16 @@ public final class MapConstraints { } return result; } - - @Override - public boolean containsValue(Object o) { - return values().contains(o); - } }; } return result; } + @Override + protected Multimap delegate() { + return delegate; + } + @Override public Collection> entries() { Collection> result = entries; @@ -527,283 +509,19 @@ public final class MapConstraints { } } - /** @see ConstrainedMultimap#asMap */ - private static class ConstrainedAsMapValues extends ForwardingCollection> { - final Collection> delegate; - final Set>> entrySet; - - /** - * @param entrySet map entries, linking each key with its corresponding values, - * that already enforce the constraint - */ - ConstrainedAsMapValues(Collection> delegate, Set>> entrySet) { - this.delegate = delegate; - this.entrySet = entrySet; - } - - @Override - protected Collection> delegate() { - return delegate; - } - - @Override - public Iterator> iterator() { - final Iterator>> iterator = entrySet.iterator(); - return new Iterator>() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Collection next() { - return iterator.next().getValue(); - } - - @Override - public void remove() { - iterator.remove(); - } - }; - } - - @Override - public Object[] toArray() { - return standardToArray(); - } - - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - - @Override - public boolean contains(Object o) { - return standardContains(o); - } - - @Override - public boolean containsAll(Collection c) { - return standardContainsAll(c); - } - - @Override - public boolean remove(Object o) { - return standardRemove(o); - } - - @Override - public boolean removeAll(Collection c) { - return standardRemoveAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return standardRetainAll(c); - } - } - - /** @see MapConstraints#constrainedEntries */ - private static class ConstrainedEntries extends ForwardingCollection> { - final MapConstraint constraint; - final Collection> entries; - - ConstrainedEntries(Collection> entries, MapConstraint constraint) { - this.entries = entries; - this.constraint = constraint; - } - - @Override - protected Collection> delegate() { - return entries; - } - - @Override - public Iterator> iterator() { - final Iterator> iterator = entries.iterator(); - return new ForwardingIterator>() { - @Override - public Entry next() { - return constrainedEntry(iterator.next(), constraint); - } - - @Override - protected Iterator> delegate() { - return iterator; - } - }; - } - - // See Collections.CheckedMap.CheckedEntrySet for details on attacks. - - @Override - public Object[] toArray() { - return standardToArray(); - } - - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - - @Override - public boolean contains(Object o) { - return Maps.containsEntryImpl(delegate(), o); - } - - @Override - public boolean containsAll(Collection c) { - return standardContainsAll(c); - } - - @Override - public boolean remove(Object o) { - return Maps.removeEntryImpl(delegate(), o); - } - - @Override - public boolean removeAll(Collection c) { - return standardRemoveAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return standardRetainAll(c); - } - } - - /** @see MapConstraints#constrainedEntrySet */ - static class ConstrainedEntrySet extends ConstrainedEntries implements Set> { - ConstrainedEntrySet(Set> entries, MapConstraint constraint) { - super(entries, constraint); - } - - // See Collections.CheckedMap.CheckedEntrySet for details on attacks. - - @Override - public boolean equals(@Nullable Object object) { - return Sets.equalsImpl(this, object); - } - - @Override - public int hashCode() { - return Sets.hashCodeImpl(this); - } - } - - /** @see MapConstraints#constrainedAsMapEntries */ - static class ConstrainedAsMapEntries extends ForwardingSet>> { - private final MapConstraint constraint; - private final Set>> entries; - - ConstrainedAsMapEntries(Set>> entries, MapConstraint constraint) { - this.entries = entries; - this.constraint = constraint; - } - - @Override - protected Set>> delegate() { - return entries; - } - - @Override - public Iterator>> iterator() { - final Iterator>> iterator = entries.iterator(); - return new ForwardingIterator>>() { - @Override - public Entry> next() { - return constrainedAsMapEntry(iterator.next(), constraint); - } - - @Override - protected Iterator>> delegate() { - return iterator; - } - }; - } - - // See Collections.CheckedMap.CheckedEntrySet for details on attacks. - - @Override - public Object[] toArray() { - return standardToArray(); - } - - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - - @Override - public boolean contains(Object o) { - return Maps.containsEntryImpl(delegate(), o); - } - - @Override - public boolean containsAll(Collection c) { - return standardContainsAll(c); - } - - @Override - public boolean equals(@Nullable Object object) { - return standardEquals(object); - } - - @Override - public int hashCode() { - return standardHashCode(); - } - - @Override - public boolean remove(Object o) { - return Maps.removeEntryImpl(delegate(), o); - } - - @Override - public boolean removeAll(Collection c) { - return standardRemoveAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return standardRetainAll(c); - } - } - - private static class ConstrainedListMultimap extends ConstrainedMultimap implements ListMultimap { - ConstrainedListMultimap(ListMultimap delegate, MapConstraint constraint) { - super(delegate, constraint); - } - - @Override - public List get(K key) { - return (List) super.get(key); - } - - @Override - public List removeAll(Object key) { - return (List) super.removeAll(key); - } - - @Override - public List replaceValues(K key, Iterable values) { - return (List) super.replaceValues(key, values); - } - } - private static class ConstrainedSetMultimap extends ConstrainedMultimap implements SetMultimap { ConstrainedSetMultimap(SetMultimap delegate, MapConstraint constraint) { super(delegate, constraint); } @Override - public Set get(K key) { - return (Set) super.get(key); + public Set> entries() { + return (Set>) super.entries(); } @Override - public Set> entries() { - return (Set>) super.entries(); + public Set get(K key) { + return (Set) super.get(key); } @Override @@ -844,13 +562,34 @@ public final class MapConstraints { } } - private static Collection checkValues(K key, Iterable values, - MapConstraint constraint) { - Collection copy = Lists.newArrayList(values); - for (V value : copy) { - constraint.checkKeyValue(key, value); + /** @see MapConstraints#constrainedBiMap */ + private static class InverseConstraint implements MapConstraint { + final MapConstraint constraint; + + public InverseConstraint(MapConstraint constraint) { + this.constraint = checkNotNull(constraint); + } + + @Override + public void checkKeyValue(K key, V value) { + constraint.checkKeyValue(value, key); + } + } + + // enum singleton pattern + private enum NotNullMapConstraint implements MapConstraint { + INSTANCE; + + @Override + public void checkKeyValue(Object key, Object value) { + checkNotNull(key); + checkNotNull(value); + } + + @Override + public String toString() { + return "Not null"; } - return copy; } private static Map checkMap(Map map, @@ -861,4 +600,265 @@ public final class MapConstraints { } return copy; } + + private static Collection checkValues(K key, Iterable values, + MapConstraint constraint) { + Collection copy = Lists.newArrayList(values); + for (V value : copy) { + constraint.checkKeyValue(key, value); + } + return copy; + } + + /** + * Returns a constrained view of the specified set of {@code asMap} entries, + * using the specified constraint. The {@link Entry#setValue} operation will be + * verified with the constraint, and the collection returned by + * {@link Entry#getValue} will be similarly constrained. The {@code add} and + * {@code + * addAll} operations simply forward to the underlying set, which throws an + * {@link UnsupportedOperationException} per the multimap specification. + * + * @param entries the entries to constrain + * @param constraint the constraint for the entries + * @return a constrained view of the entries + */ + private static Set>> constrainedAsMapEntries(Set>> entries, + MapConstraint constraint) { + return new ConstrainedAsMapEntries(entries, constraint); + } + + /** + * Returns a constrained view of the specified {@code asMap} entry, using the + * specified constraint. The {@link Entry#setValue} operation will be verified + * with the constraint, and the collection returned by {@link Entry#getValue} + * will be similarly constrained. + * + * @param entry the {@code asMap} entry to constrain + * @param constraint the constraint for the entry + * @return a constrained view of the specified entry + */ + private static Entry> constrainedAsMapEntry(final Entry> entry, + final MapConstraint constraint) { + checkNotNull(entry); + checkNotNull(constraint); + return new ForwardingMapEntry>() { + @Override + protected Entry> delegate() { + return entry; + } + + @Override + public Collection getValue() { + return Constraints.constrainedTypePreservingCollection(entry.getValue(), new Constraint() { + @Override + public V checkElement(V value) { + constraint.checkKeyValue(getKey(), value); + return value; + } + }); + } + }; + } + + /** + * Returns a constrained view of the specified bimap, using the specified + * constraint. Any operations that modify the bimap will have the associated + * keys and values verified with the constraint. + * + *

+ * The returned bimap is not serializable. + * + * @param map the bimap to constrain + * @param constraint the constraint that validates added entries + * @return a constrained view of the specified bimap + */ + public static BiMap constrainedBiMap(BiMap map, MapConstraint constraint) { + return new ConstrainedBiMap(map, null, constraint); + } + + /** + * Returns a constrained view of the specified collection (or set) of entries, + * using the specified constraint. The {@link Entry#setValue} operation will be + * verified with the constraint, along with add operations on the returned + * collection. The {@code add} and {@code addAll} operations simply forward to + * the underlying collection, which throws an + * {@link UnsupportedOperationException} per the map and multimap specification. + * + * @param entries the entries to constrain + * @param constraint the constraint for the entries + * @return a constrained view of the specified entries + */ + private static Collection> constrainedEntries(Collection> entries, + MapConstraint constraint) { + if (entries instanceof Set) { + return constrainedEntrySet((Set>) entries, constraint); + } + return new ConstrainedEntries(entries, constraint); + } + + /** + * Returns a constrained view of the specified entry, using the specified + * constraint. The {@link Entry#setValue} operation will be verified with the + * constraint. + * + * @param entry the entry to constrain + * @param constraint the constraint for the entry + * @return a constrained view of the specified entry + */ + private static Entry constrainedEntry(final Entry entry, + final MapConstraint constraint) { + checkNotNull(entry); + checkNotNull(constraint); + return new ForwardingMapEntry() { + @Override + protected Entry delegate() { + return entry; + } + + @Override + public V setValue(V value) { + constraint.checkKeyValue(getKey(), value); + return entry.setValue(value); + } + }; + } + + /** + * Returns a constrained view of the specified set of entries, using the + * specified constraint. The {@link Entry#setValue} operation will be verified + * with the constraint, along with add operations on the returned set. The + * {@code add} and {@code addAll} operations simply forward to the underlying + * set, which throws an {@link UnsupportedOperationException} per the map and + * multimap specification. + * + *

+ * The returned multimap is not serializable. + * + * @param entries the entries to constrain + * @param constraint the constraint for the entries + * @return a constrained view of the specified entries + */ + private static Set> constrainedEntrySet(Set> entries, + MapConstraint constraint) { + return new ConstrainedEntrySet(entries, constraint); + } + + /** + * Returns a constrained view of the specified list multimap, using the + * specified constraint. Any operations that add new mappings will call the + * provided constraint. However, this method does not verify that existing + * mappings satisfy the constraint. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are not + * constrained. + * + *

+ * The returned multimap is not serializable. + * + * @param multimap the multimap to constrain + * @param constraint the constraint that validates added entries + * @return a constrained view of the specified multimap + */ + public static ListMultimap constrainedListMultimap(ListMultimap multimap, + MapConstraint constraint) { + return new ConstrainedListMultimap(multimap, constraint); + } + + /** + * Returns a constrained view of the specified map, using the specified + * constraint. Any operations that add new mappings will call the provided + * constraint. However, this method does not verify that existing mappings + * satisfy the constraint. + * + *

+ * The returned map is not serializable. + * + * @param map the map to constrain + * @param constraint the constraint that validates added entries + * @return a constrained view of the specified map + */ + public static Map constrainedMap(Map map, MapConstraint constraint) { + return new ConstrainedMap(map, constraint); + } + + /** + * Returns a constrained view of the specified multimap, using the specified + * constraint. Any operations that add new mappings will call the provided + * constraint. However, this method does not verify that existing mappings + * satisfy the constraint. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are not + * constrained. + * + *

+ * The returned multimap is not serializable. + * + * @param multimap the multimap to constrain + * @param constraint the constraint that validates added entries + * @return a constrained view of the multimap + */ + public static Multimap constrainedMultimap(Multimap multimap, + MapConstraint constraint) { + return new ConstrainedMultimap(multimap, constraint); + } + + /** + * Returns a constrained view of the specified set multimap, using the specified + * constraint. Any operations that add new mappings will call the provided + * constraint. However, this method does not verify that existing mappings + * satisfy the constraint. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are not + * constrained. + *

+ * The returned multimap is not serializable. + * + * @param multimap the multimap to constrain + * @param constraint the constraint that validates added entries + * @return a constrained view of the specified multimap + */ + public static SetMultimap constrainedSetMultimap(SetMultimap multimap, + MapConstraint constraint) { + return new ConstrainedSetMultimap(multimap, constraint); + } + + /** + * Returns a constrained view of the specified sorted-set multimap, using the + * specified constraint. Any operations that add new mappings will call the + * provided constraint. However, this method does not verify that existing + * mappings satisfy the constraint. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are not + * constrained. + *

+ * The returned multimap is not serializable. + * + * @param multimap the multimap to constrain + * @param constraint the constraint that validates added entries + * @return a constrained view of the specified multimap + */ + public static SortedSetMultimap constrainedSortedSetMultimap(SortedSetMultimap multimap, + MapConstraint constraint) { + return new ConstrainedSortedSetMultimap(multimap, constraint); + } + + /** + * Returns a constraint that verifies that neither the key nor the value is + * null. If either is null, a {@link NullPointerException} is thrown. + */ + public static MapConstraint notNull() { + return NotNullMapConstraint.INSTANCE; + } + + private MapConstraints() { + } } diff --git a/src/main/java/com/google/common/collect/MapDifference.java b/src/main/java/com/google/common/collect/MapDifference.java index 6d094219..40fe5c71 100644 --- a/src/main/java/com/google/common/collect/MapDifference.java +++ b/src/main/java/com/google/common/collect/MapDifference.java @@ -30,12 +30,57 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public interface MapDifference { + /** + * A difference between the mappings from two maps with the same key. The + * {@link #leftValue} and {@link #rightValue} are not equal, and one but not + * both of them may be null. + * + * @since 2.0 (imported from Google Collections Library) + */ + interface ValueDifference { + /** + * Two instances are considered equal if their {@link #leftValue()} values are + * equal and their {@link #rightValue()} values are also equal. + */ + @Override + boolean equals(@Nullable Object other); + + /** + * The hash code equals the value + * {@code Arrays.asList(leftValue(), rightValue()).hashCode()}. + */ + @Override + int hashCode(); + + /** + * Returns the value from the left map (possibly null). + */ + V leftValue(); + + /** + * Returns the value from the right map (possibly null). + */ + V rightValue(); + } + /** * Returns {@code true} if there are no differences between the two maps; that * is, if the maps are equal. */ boolean areEqual(); + /** + * Returns an unmodifiable map describing keys that appear in both maps, but + * with different values. + */ + Map> entriesDiffering(); + + /** + * Returns an unmodifiable map containing the entries that appear in both maps; + * that is, the intersection of the two maps. + */ + Map entriesInCommon(); + /** * Returns an unmodifiable map containing the entries from the left map whose * keys are not present in the right map. @@ -48,18 +93,6 @@ public interface MapDifference { */ Map entriesOnlyOnRight(); - /** - * Returns an unmodifiable map containing the entries that appear in both maps; - * that is, the intersection of the two maps. - */ - Map entriesInCommon(); - - /** - * Returns an unmodifiable map describing keys that appear in both maps, but - * with different values. - */ - Map> entriesDiffering(); - /** * Compares the specified object with this instance for equality. Returns * {@code true} if the given object is also a {@code MapDifference} and the @@ -76,44 +109,11 @@ public interface MapDifference { *

 	 *    {@code
 	 *
-	 *   Arrays.asList(entriesOnlyOnLeft(), entriesOnlyOnRight(),
-	 *       entriesInCommon(), entriesDiffering())}
+	 * Arrays.asList(entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering())
+	 * }
 	 * 
*/ @Override int hashCode(); - /** - * A difference between the mappings from two maps with the same key. The - * {@link #leftValue} and {@link #rightValue} are not equal, and one but not - * both of them may be null. - * - * @since 2.0 (imported from Google Collections Library) - */ - interface ValueDifference { - /** - * Returns the value from the left map (possibly null). - */ - V leftValue(); - - /** - * Returns the value from the right map (possibly null). - */ - V rightValue(); - - /** - * Two instances are considered equal if their {@link #leftValue()} values are - * equal and their {@link #rightValue()} values are also equal. - */ - @Override - boolean equals(@Nullable Object other); - - /** - * The hash code equals the value - * {@code Arrays.asList(leftValue(), rightValue()).hashCode()}. - */ - @Override - int hashCode(); - } - } diff --git a/src/main/java/com/google/common/collect/Maps.java b/src/main/java/com/google/common/collect/Maps.java index 2647ad3e..07362590 100644 --- a/src/main/java/com/google/common/collect/Maps.java +++ b/src/main/java/com/google/common/collect/Maps.java @@ -80,7 +80,375 @@ import com.google.common.primitives.Ints; */ @GwtCompatible(emulated = true) public final class Maps { - private Maps() { + private abstract static class AbstractFilteredMap extends ImprovedAbstractMap { + final Map unfiltered; + final Predicate> predicate; + + AbstractFilteredMap(Map unfiltered, Predicate> predicate) { + this.unfiltered = unfiltered; + this.predicate = predicate; + } + + boolean apply(@Nullable Object key, @Nullable V value) { + // This method is called only when the key is in the map, implying that + // key is a K. + @SuppressWarnings("unchecked") + K k = (K) key; + return predicate.apply(Maps.immutableEntry(k, value)); + } + + @Override + public boolean containsKey(Object key) { + return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); + } + + @Override + Collection createValues() { + return new FilteredMapValues(this, unfiltered, predicate); + } + + @Override + public V get(Object key) { + V value = unfiltered.get(key); + return ((value != null) && apply(key, value)) ? value : null; + } + + @Override + public boolean isEmpty() { + return entrySet().isEmpty(); + } + + @Override + public V put(K key, V value) { + checkArgument(apply(key, value)); + return unfiltered.put(key, value); + } + + @Override + public void putAll(Map map) { + for (Entry entry : map.entrySet()) { + checkArgument(apply(entry.getKey(), entry.getValue())); + } + unfiltered.putAll(map); + } + + @Override + public V remove(Object key) { + return containsKey(key) ? unfiltered.remove(key) : null; + } + } + + private static class AsMapView extends ImprovedAbstractMap { + + private final Set set; + final Function function; + + AsMapView(Set set, Function function) { + this.set = checkNotNull(set); + this.function = checkNotNull(function); + } + + Set backingSet() { + return set; + } + + @Override + public void clear() { + backingSet().clear(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return backingSet().contains(key); + } + + @Override + protected Set> createEntrySet() { + return new EntrySet() { + @Override + public Iterator> iterator() { + return asMapEntryIterator(backingSet(), function); + } + + @Override + Map map() { + return AsMapView.this; + } + }; + } + + @Override + public Set createKeySet() { + return removeOnlySet(backingSet()); + } + + @Override + Collection createValues() { + return Collections2.transform(set, function); + } + + @Override + public V get(@Nullable Object key) { + if (Collections2.safeContains(backingSet(), key)) { + @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it + K k = (K) key; + return function.apply(k); + } else { + return null; + } + } + + @Override + public V remove(@Nullable Object key) { + if (backingSet().remove(key)) { + @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it + K k = (K) key; + return function.apply(k); + } else { + return null; + } + } + + @Override + public int size() { + return backingSet().size(); + } + } + + private static final class BiMapConverter extends Converter implements Serializable { + private static final long serialVersionUID = 0L; + + private static Y convert(BiMap bimap, X input) { + Y output = bimap.get(input); + checkArgument(output != null, "No non-null mapping present for input: %s", input); + return output; + } + + private final BiMap bimap; + + BiMapConverter(BiMap bimap) { + this.bimap = checkNotNull(bimap); + } + + @Override + protected A doBackward(B b) { + return convert(bimap.inverse(), b); + } + + @Override + protected B doForward(A a) { + return convert(bimap, a); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof BiMapConverter) { + BiMapConverter that = (BiMapConverter) object; + return this.bimap.equals(that.bimap); + } + return false; + } + + @Override + public int hashCode() { + return bimap.hashCode(); + } + + // There's really no good way to implement toString() without printing the + // entire BiMap, right? + @Override + public String toString() { + return "Maps.asConverter(" + bimap + ")"; + } + } + + @GwtIncompatible("NavigableMap") + abstract static class DescendingMap extends ForwardingMap implements NavigableMap { + + // If we inline this, we get a javac error. + private static Ordering reverse(Comparator forward) { + return Ordering.from(forward).reverse(); + } + + private transient Comparator comparator; + + private transient Set> entrySet; + + private transient NavigableSet navigableKeySet; + + @Override + public Entry ceilingEntry(K key) { + return forward().floorEntry(key); + } + + @Override + public K ceilingKey(K key) { + return forward().floorKey(key); + } + + @SuppressWarnings("unchecked") + @Override + public Comparator comparator() { + Comparator result = comparator; + if (result == null) { + Comparator forwardCmp = forward().comparator(); + if (forwardCmp == null) { + forwardCmp = (Comparator) Ordering.natural(); + } + result = comparator = reverse(forwardCmp); + } + return result; + } + + Set> createEntrySet() { + return new EntrySet() { + @Override + public Iterator> iterator() { + return entryIterator(); + } + + @Override + Map map() { + return DescendingMap.this; + } + }; + } + + @Override + protected final Map delegate() { + return forward(); + } + + @Override + public NavigableSet descendingKeySet() { + return forward().navigableKeySet(); + } + + @Override + public NavigableMap descendingMap() { + return forward(); + } + + abstract Iterator> entryIterator(); + + @Override + public Set> entrySet() { + Set> result = entrySet; + return (result == null) ? entrySet = createEntrySet() : result; + } + + @Override + public Entry firstEntry() { + return forward().lastEntry(); + } + + @Override + public K firstKey() { + return forward().lastKey(); + } + + @Override + public Entry floorEntry(K key) { + return forward().ceilingEntry(key); + } + + @Override + public K floorKey(K key) { + return forward().ceilingKey(key); + } + + abstract NavigableMap forward(); + + @Override + public SortedMap headMap(K toKey) { + return headMap(toKey, false); + } + + @Override + public NavigableMap headMap(K toKey, boolean inclusive) { + return forward().tailMap(toKey, inclusive).descendingMap(); + } + + @Override + public Entry higherEntry(K key) { + return forward().lowerEntry(key); + } + + @Override + public K higherKey(K key) { + return forward().lowerKey(key); + } + + @Override + public Set keySet() { + return navigableKeySet(); + } + + @Override + public Entry lastEntry() { + return forward().firstEntry(); + } + + @Override + public K lastKey() { + return forward().firstKey(); + } + + @Override + public Entry lowerEntry(K key) { + return forward().higherEntry(key); + } + + @Override + public K lowerKey(K key) { + return forward().higherKey(key); + } + + @Override + public NavigableSet navigableKeySet() { + NavigableSet result = navigableKeySet; + return (result == null) ? navigableKeySet = new NavigableKeySet(this) : result; + } + + @Override + public Entry pollFirstEntry() { + return forward().pollLastEntry(); + } + + @Override + public Entry pollLastEntry() { + return forward().pollFirstEntry(); + } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); + } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); + } + + @Override + public SortedMap tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return forward().headMap(fromKey, inclusive).descendingMap(); + } + + @Override + public String toString() { + return standardToString(); + } + + @Override + public Collection values() { + return new Values(this); + } } private enum EntryFunction implements Function, Object> { @@ -100,339 +468,622 @@ public final class Maps { }; } - @SuppressWarnings("unchecked") - static Function, K> keyFunction() { - return (Function) EntryFunction.KEY; - } + abstract static class EntrySet extends Sets.ImprovedAbstractSet> { + @Override + public void clear() { + map().clear(); + } - @SuppressWarnings("unchecked") - static Function, V> valueFunction() { - return (Function) EntryFunction.VALUE; - } - - static Iterator keyIterator(Iterator> entryIterator) { - return Iterators.transform(entryIterator, Maps.keyFunction()); - } - - static Iterator valueIterator(Iterator> entryIterator) { - return Iterators.transform(entryIterator, Maps.valueFunction()); - } - - static UnmodifiableIterator valueIterator(final UnmodifiableIterator> entryIterator) { - return new UnmodifiableIterator() { - @Override - public boolean hasNext() { - return entryIterator.hasNext(); + @Override + public boolean contains(Object o) { + if (o instanceof Entry) { + Entry entry = (Entry) o; + Object key = entry.getKey(); + V value = Maps.safeGet(map(), key); + return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); } + return false; + } - @Override - public V next() { - return entryIterator.next().getValue(); + @Override + public boolean isEmpty() { + return map().isEmpty(); + } + + abstract Map map(); + + @Override + public boolean remove(Object o) { + if (contains(o)) { + Entry entry = (Entry) o; + return map().keySet().remove(entry.getKey()); } - }; - } + return false; + } - /** - * Returns an immutable map instance containing the given entries. Internally, - * the returned map will be backed by an {@link EnumMap}. - * - *

- * The iteration order of the returned map follows the enum's iteration order, - * not the order in which the elements appear in the given map. - * - * @param map the map to make an immutable copy of - * @return an immutable map containing those entries - * @since 14.0 - */ - @GwtCompatible(serializable = true) - @Beta - public static , V> ImmutableMap immutableEnumMap(Map map) { - if (map instanceof ImmutableEnumMap) { - @SuppressWarnings("unchecked") // safe covariant cast - ImmutableEnumMap result = (ImmutableEnumMap) map; - return result; - } else if (map.isEmpty()) { - return ImmutableMap.of(); - } else { - for (Map.Entry entry : map.entrySet()) { - checkNotNull(entry.getKey()); - checkNotNull(entry.getValue()); + @Override + public boolean removeAll(Collection c) { + try { + return super.removeAll(checkNotNull(c)); + } catch (UnsupportedOperationException e) { + // if the iterators don't support remove + return Sets.removeAllImpl(this, c.iterator()); } - return ImmutableEnumMap.asImmutable(new EnumMap(map)); } - } - /** - * Creates a mutable, empty {@code HashMap} instance. - * - *

- * Note: if mutability is not required, use {@link ImmutableMap#of()} - * instead. - * - *

- * Note: if {@code K} is an {@code enum} type, use {@link #newEnumMap} - * instead. - * - * @return a new, empty {@code HashMap} - */ - public static HashMap newHashMap() { - return new HashMap(); - } - - /** - * Creates a {@code HashMap} instance, with a high enough "initial capacity" - * that it should hold {@code expectedSize} elements without growth. This - * behavior cannot be broadly guaranteed, but it is observed to be true for - * OpenJDK 1.6. It also can't be guaranteed that the method isn't inadvertently - * oversizing the returned map. - * - * @param expectedSize the number of elements you expect to add to the returned - * map - * @return a new, empty {@code HashMap} with enough capacity to hold {@code - * expectedSize} elements without resizing - * @throws IllegalArgumentException if {@code expectedSize} is negative - */ - public static HashMap newHashMapWithExpectedSize(int expectedSize) { - return new HashMap(capacity(expectedSize)); - } - - /** - * Returns a capacity that is sufficient to keep the map from being resized as - * long as it grows no larger than expectedSize and the load factor is >= its - * default (0.75). - */ - static int capacity(int expectedSize) { - if (expectedSize < 3) { - checkNonnegative(expectedSize, "expectedSize"); - return expectedSize + 1; - } - if (expectedSize < Ints.MAX_POWER_OF_TWO) { - return expectedSize + expectedSize / 3; - } - return Integer.MAX_VALUE; // any large value - } - - /** - * Creates a mutable {@code HashMap} instance with the same mappings as - * the specified map. - * - *

- * Note: if mutability is not required, use - * {@link ImmutableMap#copyOf(Map)} instead. - * - *

- * Note: if {@code K} is an {@link Enum} type, use {@link #newEnumMap} - * instead. - * - * @param map the mappings to be placed in the new map - * @return a new {@code HashMap} initialized with the mappings from {@code - * map} - */ - public static HashMap newHashMap(Map map) { - return new HashMap(map); - } - - /** - * Creates a mutable, empty, insertion-ordered {@code LinkedHashMap} - * instance. - * - *

- * Note: if mutability is not required, use {@link ImmutableMap#of()} - * instead. - * - * @return a new, empty {@code LinkedHashMap} - */ - public static LinkedHashMap newLinkedHashMap() { - return new LinkedHashMap(); - } - - /** - * Creates a mutable, insertion-ordered {@code LinkedHashMap} instance - * with the same mappings as the specified map. - * - *

- * Note: if mutability is not required, use - * {@link ImmutableMap#copyOf(Map)} instead. - * - * @param map the mappings to be placed in the new map - * @return a new, {@code LinkedHashMap} initialized with the mappings from - * {@code map} - */ - public static LinkedHashMap newLinkedHashMap(Map map) { - return new LinkedHashMap(map); - } - - /** - * Creates a mutable, empty {@code TreeMap} instance using the natural - * ordering of its elements. - * - *

- * Note: if mutability is not required, use - * {@link ImmutableSortedMap#of()} instead. - * - * @return a new, empty {@code TreeMap} - */ - public static TreeMap newTreeMap() { - return new TreeMap(); - } - - /** - * Creates a mutable {@code TreeMap} instance with the same mappings as - * the specified map and using the same ordering as the specified map. - * - *

- * Note: if mutability is not required, use - * {@link ImmutableSortedMap#copyOfSorted(SortedMap)} instead. - * - * @param map the sorted map whose mappings are to be placed in the new map and - * whose comparator is to be used to sort the new map - * @return a new {@code TreeMap} initialized with the mappings from {@code - * map} and using the comparator of {@code map} - */ - public static TreeMap newTreeMap(SortedMap map) { - return new TreeMap(map); - } - - /** - * Creates a mutable, empty {@code TreeMap} instance using the given - * comparator. - * - *

- * Note: if mutability is not required, use {@code - * ImmutableSortedMap.orderedBy(comparator).build()} instead. - * - * @param comparator the comparator to sort the keys with - * @return a new, empty {@code TreeMap} - */ - public static TreeMap newTreeMap(@Nullable Comparator comparator) { - // Ideally, the extra type parameter "C" shouldn't be necessary. It is a - // work-around of a compiler type inference quirk that prevents the - // following code from being compiled: - // Comparator> comparator = null; - // Map, String> map = newTreeMap(comparator); - return new TreeMap(comparator); - } - - /** - * Creates an {@code EnumMap} instance. - * - * @param type the key type for this map - * @return a new, empty {@code EnumMap} - */ - public static , V> EnumMap newEnumMap(Class type) { - return new EnumMap(checkNotNull(type)); - } - - /** - * Creates an {@code EnumMap} with the same mappings as the specified map. - * - * @param map the map from which to initialize this {@code EnumMap} - * @return a new {@code EnumMap} initialized with the mappings from {@code - * map} - * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} - * instance and contains no mappings - */ - public static , V> EnumMap newEnumMap(Map map) { - return new EnumMap(map); - } - - /** - * Creates an {@code IdentityHashMap} instance. - * - * @return a new, empty {@code IdentityHashMap} - */ - public static IdentityHashMap newIdentityHashMap() { - return new IdentityHashMap(); - } - - /** - * Computes the difference between two maps. This difference is an immutable - * snapshot of the state of the maps at the time this method is called. It will - * never change, even if the maps change at a later time. - * - *

- * Since this method uses {@code HashMap} instances internally, the keys of the - * supplied maps must be well-behaved with respect to {@link Object#equals} and - * {@link Object#hashCode}. - * - *

- * Note:If you only need to know whether two maps have the same mappings, - * call {@code left.equals(right)} instead of this method. - * - * @param left the map to treat as the "left" map for purposes of comparison - * @param right the map to treat as the "right" map for purposes of comparison - * @return the difference between the two maps - */ - @SuppressWarnings("unchecked") - public static MapDifference difference(Map left, - Map right) { - if (left instanceof SortedMap) { - SortedMap sortedLeft = (SortedMap) left; - SortedMapDifference result = difference(sortedLeft, right); - return result; - } - return difference(left, right, Equivalence.equals()); - } - - /** - * Computes the difference between two maps. This difference is an immutable - * snapshot of the state of the maps at the time this method is called. It will - * never change, even if the maps change at a later time. - * - *

- * Values are compared using a provided equivalence, in the case of equality, - * the value on the 'left' is returned in the difference. - * - *

- * Since this method uses {@code HashMap} instances internally, the keys of the - * supplied maps must be well-behaved with respect to {@link Object#equals} and - * {@link Object#hashCode}. - * - * @param left the map to treat as the "left" map for purposes of - * comparison - * @param right the map to treat as the "right" map for purposes of - * comparison - * @param valueEquivalence the equivalence relationship to use to compare values - * @return the difference between the two maps - * @since 10.0 - */ - @Beta - public static MapDifference difference(Map left, - Map right, Equivalence valueEquivalence) { - Preconditions.checkNotNull(valueEquivalence); - - Map onlyOnLeft = newHashMap(); - Map onlyOnRight = new HashMap(right); // will whittle it down - Map onBoth = newHashMap(); - Map> differences = newHashMap(); - doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences); - return new MapDifferenceImpl(onlyOnLeft, onlyOnRight, onBoth, differences); - } - - private static void doDifference(Map left, Map right, - Equivalence valueEquivalence, Map onlyOnLeft, Map onlyOnRight, Map onBoth, - Map> differences) { - for (Entry entry : left.entrySet()) { - K leftKey = entry.getKey(); - V leftValue = entry.getValue(); - if (right.containsKey(leftKey)) { - V rightValue = onlyOnRight.remove(leftKey); - if (valueEquivalence.equivalent(leftValue, rightValue)) { - onBoth.put(leftKey, leftValue); - } else { - differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); + @Override + public boolean retainAll(Collection c) { + try { + return super.retainAll(checkNotNull(c)); + } catch (UnsupportedOperationException e) { + // if the iterators don't support remove + Set keys = Sets.newHashSetWithExpectedSize(c.size()); + for (Object o : c) { + if (contains(o)) { + Entry entry = (Entry) o; + keys.add(entry.getKey()); + } } - } else { - onlyOnLeft.put(leftKey, leftValue); + return map().keySet().retainAll(keys); } } + + @Override + public int size() { + return map().size(); + } } - private static Map unmodifiableMap(Map map) { - if (map instanceof SortedMap) { - return Collections.unmodifiableSortedMap((SortedMap) map); - } else { - return Collections.unmodifiableMap(map); + /** + * A transformation of the value of a key-value pair, using both key and value + * as inputs. To apply the transformation to a map, use + * {@link Maps#transformEntries(Map, EntryTransformer)}. + * + * @param the key type of the input and output entries + * @param the value type of the input entry + * @param the value type of the output entry + * @since 7.0 + */ + public interface EntryTransformer { + /** + * Determines an output value based on a key-value pair. This method is + * generally expected, but not absolutely required, to have the following + * properties: + * + *
    + *
  • Its execution does not cause any observable side effects. + *
  • The computation is consistent with equals; that is, + * {@link Objects#equal Objects.equal}{@code (k1, k2) &&} + * {@link Objects#equal}{@code (v1, v2)} implies that {@code + * Objects.equal(transformer.transform(k1, v1), + * transformer.transform(k2, v2))}. + *
+ * + * @throws NullPointerException if the key or value is null and this transformer + * does not accept null arguments + */ + V2 transformEntry(@Nullable K key, @Nullable V1 value); + } + + static final class FilteredEntryBiMap extends FilteredEntryMap implements BiMap { + private static Predicate> inversePredicate( + final Predicate> forwardPredicate) { + return new Predicate>() { + @Override + public boolean apply(Entry input) { + return forwardPredicate.apply(Maps.immutableEntry(input.getValue(), input.getKey())); + } + }; + } + + private final BiMap inverse; + + FilteredEntryBiMap(BiMap delegate, Predicate> predicate) { + super(delegate, predicate); + this.inverse = new FilteredEntryBiMap(delegate.inverse(), inversePredicate(predicate), this); + } + + private FilteredEntryBiMap(BiMap delegate, Predicate> predicate, + BiMap inverse) { + super(delegate, predicate); + this.inverse = inverse; + } + + @Override + public V forcePut(@Nullable K key, @Nullable V value) { + checkArgument(apply(key, value)); + return unfiltered().forcePut(key, value); + } + + @Override + public BiMap inverse() { + return inverse; + } + + BiMap unfiltered() { + return (BiMap) unfiltered; + } + + @Override + public Set values() { + return inverse.keySet(); + } + } + + static class FilteredEntryMap extends AbstractFilteredMap { + private class EntrySet extends ForwardingSet> { + @Override + protected Set> delegate() { + return filteredEntrySet; + } + + @Override + public Iterator> iterator() { + return new TransformedIterator, Entry>(filteredEntrySet.iterator()) { + @Override + Entry transform(final Entry entry) { + return new ForwardingMapEntry() { + @Override + protected Entry delegate() { + return entry; + } + + @Override + public V setValue(V newValue) { + checkArgument(apply(getKey(), newValue)); + return super.setValue(newValue); + } + }; + } + }; + } + } + + class KeySet extends Maps.KeySet { + KeySet() { + super(FilteredEntryMap.this); + } + + @Override + public boolean remove(Object o) { + if (containsKey(o)) { + unfiltered.remove(o); + return true; + } + return false; + } + + @Override + public boolean removeAll(Collection c) { + return removeIf(in(c)); + } + + private boolean removeIf(Predicate keyPredicate) { + return Iterables.removeIf(unfiltered.entrySet(), + Predicates.>and(predicate, Maps.keyPredicateOnEntries(keyPredicate))); + } + + @Override + public boolean retainAll(Collection c) { + return removeIf(not(in(c))); + } + + @Override + public Object[] toArray() { + // creating an ArrayList so filtering happens once + return Lists.newArrayList(iterator()).toArray(); + } + + @Override + public T[] toArray(T[] array) { + return Lists.newArrayList(iterator()).toArray(array); + } + } + + /** + * Entries in this set satisfy the predicate, but they don't validate the input + * to {@code Entry.setValue()}. + */ + final Set> filteredEntrySet; + + FilteredEntryMap(Map unfiltered, Predicate> entryPredicate) { + super(unfiltered, entryPredicate); + filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); + } + + @Override + protected Set> createEntrySet() { + return new EntrySet(); + } + + @Override + Set createKeySet() { + return new KeySet(); + } + } + + @GwtIncompatible("NavigableMap") + private static class FilteredEntryNavigableMap extends AbstractNavigableMap { + /* + * It's less code to extend AbstractNavigableMap and forward the filtering logic + * to FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all + * the NavigableMap methods. + */ + + private final NavigableMap unfiltered; + private final Predicate> entryPredicate; + private final Map filteredDelegate; + + FilteredEntryNavigableMap(NavigableMap unfiltered, Predicate> entryPredicate) { + this.unfiltered = checkNotNull(unfiltered); + this.entryPredicate = entryPredicate; + this.filteredDelegate = new FilteredEntryMap(unfiltered, entryPredicate); + } + + @Override + public void clear() { + filteredDelegate.clear(); + } + + @Override + public Comparator comparator() { + return unfiltered.comparator(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return filteredDelegate.containsKey(key); + } + + @Override + Iterator> descendingEntryIterator() { + return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate); + } + + @Override + public NavigableMap descendingMap() { + return filterEntries(unfiltered.descendingMap(), entryPredicate); + } + + @Override + Iterator> entryIterator() { + return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate); + } + + @Override + public Set> entrySet() { + return filteredDelegate.entrySet(); + } + + @Override + @Nullable + public V get(@Nullable Object key) { + return filteredDelegate.get(key); + } + + @Override + public NavigableMap headMap(K toKey, boolean inclusive) { + return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate); + } + + @Override + public NavigableSet navigableKeySet() { + return new Maps.NavigableKeySet(this) { + @Override + public boolean removeAll(Collection c) { + return Iterators.removeIf(unfiltered.entrySet().iterator(), + Predicates.>and(entryPredicate, Maps.keyPredicateOnEntries(in(c)))); + } + + @Override + public boolean retainAll(Collection c) { + return Iterators.removeIf(unfiltered.entrySet().iterator(), + Predicates.>and(entryPredicate, Maps.keyPredicateOnEntries(not(in(c))))); + } + }; + } + + @Override + public Entry pollFirstEntry() { + return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate); + } + + @Override + public Entry pollLastEntry() { + return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate); + } + + @Override + public V put(K key, V value) { + return filteredDelegate.put(key, value); + } + + @Override + public void putAll(Map m) { + filteredDelegate.putAll(m); + } + + @Override + public V remove(@Nullable Object key) { + return filteredDelegate.remove(key); + } + + @Override + public int size() { + return filteredDelegate.size(); + } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return filterEntries(unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate); + } + + @Override + public Collection values() { + return new FilteredMapValues(this, unfiltered, entryPredicate); + } + } + + private static class FilteredEntrySortedMap extends FilteredEntryMap implements SortedMap { + + class SortedKeySet extends KeySet implements SortedSet { + @Override + public Comparator comparator() { + return sortedMap().comparator(); + } + + @Override + public K first() { + return firstKey(); + } + + @Override + public SortedSet headSet(K toElement) { + return (SortedSet) headMap(toElement).keySet(); + } + + @Override + public K last() { + return lastKey(); + } + + @Override + public SortedSet subSet(K fromElement, K toElement) { + return (SortedSet) subMap(fromElement, toElement).keySet(); + } + + @Override + public SortedSet tailSet(K fromElement) { + return (SortedSet) tailMap(fromElement).keySet(); + } + } + + FilteredEntrySortedMap(SortedMap unfiltered, Predicate> entryPredicate) { + super(unfiltered, entryPredicate); + } + + @Override + public Comparator comparator() { + return sortedMap().comparator(); + } + + @Override + SortedSet createKeySet() { + return new SortedKeySet(); + } + + @Override + public K firstKey() { + // correctly throws NoSuchElementException when filtered map is empty. + return keySet().iterator().next(); + } + + @Override + public SortedMap headMap(K toKey) { + return new FilteredEntrySortedMap(sortedMap().headMap(toKey), predicate); + } + + @Override + public SortedSet keySet() { + return (SortedSet) super.keySet(); + } + + @Override + public K lastKey() { + SortedMap headMap = sortedMap(); + while (true) { + // correctly throws NoSuchElementException when filtered map is empty. + K key = headMap.lastKey(); + if (apply(key, unfiltered.get(key))) { + return key; + } + headMap = sortedMap().headMap(key); + } + } + + SortedMap sortedMap() { + return (SortedMap) unfiltered; + } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + return new FilteredEntrySortedMap(sortedMap().subMap(fromKey, toKey), predicate); + } + + @Override + public SortedMap tailMap(K fromKey) { + return new FilteredEntrySortedMap(sortedMap().tailMap(fromKey), predicate); + } + } + + private static class FilteredKeyMap extends AbstractFilteredMap { + Predicate keyPredicate; + + FilteredKeyMap(Map unfiltered, Predicate keyPredicate, + Predicate> entryPredicate) { + super(unfiltered, entryPredicate); + this.keyPredicate = keyPredicate; + } + + // The cast is called only when the key is in the unfiltered map, implying + // that key is a K. + @Override + @SuppressWarnings("unchecked") + public boolean containsKey(Object key) { + return unfiltered.containsKey(key) && keyPredicate.apply((K) key); + } + + @Override + protected Set> createEntrySet() { + return Sets.filter(unfiltered.entrySet(), predicate); + } + + @Override + Set createKeySet() { + return Sets.filter(unfiltered.keySet(), keyPredicate); + } + } + + private static final class FilteredMapValues extends Maps.Values { + Map unfiltered; + Predicate> predicate; + + FilteredMapValues(Map filteredMap, Map unfiltered, Predicate> predicate) { + super(filteredMap); + this.unfiltered = unfiltered; + this.predicate = predicate; + } + + @Override + public boolean remove(Object o) { + return Iterables.removeFirstMatching(unfiltered.entrySet(), + Predicates.>and(predicate, Maps.valuePredicateOnEntries(equalTo(o)))) != null; + } + + @Override + public boolean removeAll(Collection collection) { + return removeIf(in(collection)); + } + + private boolean removeIf(Predicate valuePredicate) { + return Iterables.removeIf(unfiltered.entrySet(), + Predicates.>and(predicate, Maps.valuePredicateOnEntries(valuePredicate))); + } + + @Override + public boolean retainAll(Collection collection) { + return removeIf(not(in(collection))); + } + + @Override + public Object[] toArray() { + // creating an ArrayList so filtering happens once + return Lists.newArrayList(iterator()).toArray(); + } + + @Override + public T[] toArray(T[] array) { + return Lists.newArrayList(iterator()).toArray(array); + } + } + + /** + * {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code + * entrySet().isEmpty()} instead of {@code size() == 0} to speed up + * implementations where {@code size()} is O(n), and it delegates the {@code + * isEmpty()} methods of its key set and value collection to this + * implementation. + */ + @GwtCompatible + abstract static class ImprovedAbstractMap extends AbstractMap { + private transient Set> entrySet; + + private transient Set keySet; + + private transient Collection values; + + /** + * Creates the entry set to be returned by {@link #entrySet()}. This method is + * invoked at most once on a given map, at the time when {@code entrySet} is + * first called. + */ + abstract Set> createEntrySet(); + + Set createKeySet() { + return new KeySet(this); + } + + Collection createValues() { + return new Values(this); + } + + @Override + public Set> entrySet() { + Set> result = entrySet; + return (result == null) ? entrySet = createEntrySet() : result; + } + + @Override + public Set keySet() { + Set result = keySet; + return (result == null) ? keySet = createKeySet() : result; + } + + @Override + public Collection values() { + Collection result = values; + return (result == null) ? values = createValues() : result; + } + } + + static class KeySet extends Sets.ImprovedAbstractSet { + final Map map; + + KeySet(Map map) { + this.map = checkNotNull(map); + } + + @Override + public void clear() { + map().clear(); + } + + @Override + public boolean contains(Object o) { + return map().containsKey(o); + } + + @Override + public boolean isEmpty() { + return map().isEmpty(); + } + + @Override + public Iterator iterator() { + return keyIterator(map().entrySet().iterator()); + } + + Map map() { + return map; + } + + @Override + public boolean remove(Object o) { + if (contains(o)) { + map().remove(o); + return true; + } + return false; + } + + @Override + public int size() { + return map().size(); } } @@ -456,13 +1107,8 @@ public final class Maps { } @Override - public Map entriesOnlyOnLeft() { - return onlyOnLeft; - } - - @Override - public Map entriesOnlyOnRight() { - return onlyOnRight; + public Map> entriesDiffering() { + return differences; } @Override @@ -471,8 +1117,13 @@ public final class Maps { } @Override - public Map> entriesDiffering() { - return differences; + public Map entriesOnlyOnLeft() { + return onlyOnLeft; + } + + @Override + public Map entriesOnlyOnRight() { + return onlyOnRight; } @Override @@ -515,82 +1166,252 @@ public final class Maps { } } - static class ValueDifferenceImpl implements MapDifference.ValueDifference { - private final V left; - private final V right; + @GwtIncompatible("NavigableMap") + private static final class NavigableAsMapView extends AbstractNavigableMap { + /* + * Using AbstractNavigableMap is simpler than extending SortedAsMapView and + * rewriting all the NavigableMap methods. + */ - static ValueDifference create(@Nullable V left, @Nullable V right) { - return new ValueDifferenceImpl(left, right); - } + private final NavigableSet set; + private final Function function; - private ValueDifferenceImpl(@Nullable V left, @Nullable V right) { - this.left = left; - this.right = right; + NavigableAsMapView(NavigableSet ks, Function vFunction) { + this.set = checkNotNull(ks); + this.function = checkNotNull(vFunction); } @Override - public V leftValue() { - return left; + public void clear() { + set.clear(); } @Override - public V rightValue() { - return right; + public Comparator comparator() { + return set.comparator(); } @Override - public boolean equals(@Nullable Object object) { - if (object instanceof MapDifference.ValueDifference) { - MapDifference.ValueDifference that = (MapDifference.ValueDifference) object; - return Objects.equal(this.left, that.leftValue()) && Objects.equal(this.right, that.rightValue()); + Iterator> descendingEntryIterator() { + return descendingMap().entrySet().iterator(); + } + + @Override + public NavigableMap descendingMap() { + return asMap(set.descendingSet(), function); + } + + @Override + Iterator> entryIterator() { + return asMapEntryIterator(set, function); + } + + @Override + @Nullable + public V get(@Nullable Object key) { + if (Collections2.safeContains(set, key)) { + @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it + K k = (K) key; + return function.apply(k); + } else { + return null; } - return false; } @Override - public int hashCode() { - return Objects.hashCode(left, right); + public NavigableMap headMap(K toKey, boolean inclusive) { + return asMap(set.headSet(toKey, inclusive), function); } @Override - public String toString() { - return "(" + left + ", " + right + ")"; + public NavigableSet navigableKeySet() { + return removeOnlyNavigableSet(set); + } + + @Override + public int size() { + return set.size(); + } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return asMap(set.tailSet(fromKey, inclusive), function); } } - /** - * Computes the difference between two sorted maps, using the comparator of the - * left map, or {@code Ordering.natural()} if the left map uses the natural - * ordering of its elements. This difference is an immutable snapshot of the - * state of the maps at the time this method is called. It will never change, - * even if the maps change at a later time. - * - *

- * Since this method uses {@code TreeMap} instances internally, the keys of the - * right map must all compare as distinct according to the comparator of the - * left map. - * - *

- * Note:If you only need to know whether two sorted maps have the same - * mappings, call {@code left.equals(right)} instead of this method. - * - * @param left the map to treat as the "left" map for purposes of comparison - * @param right the map to treat as the "right" map for purposes of comparison - * @return the difference between the two maps - * @since 11.0 - */ - public static SortedMapDifference difference(SortedMap left, - Map right) { - checkNotNull(left); - checkNotNull(right); - Comparator comparator = orNaturalOrder(left.comparator()); - SortedMap onlyOnLeft = Maps.newTreeMap(comparator); - SortedMap onlyOnRight = Maps.newTreeMap(comparator); - onlyOnRight.putAll(right); // will whittle it down - SortedMap onBoth = Maps.newTreeMap(comparator); - SortedMap> differences = Maps.newTreeMap(comparator); - doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences); - return new SortedMapDifferenceImpl(onlyOnLeft, onlyOnRight, onBoth, differences); + @GwtIncompatible("NavigableMap") + static class NavigableKeySet extends SortedKeySet implements NavigableSet { + NavigableKeySet(NavigableMap map) { + super(map); + } + + @Override + public K ceiling(K e) { + return map().ceilingKey(e); + } + + @Override + public Iterator descendingIterator() { + return descendingSet().iterator(); + } + + @Override + public NavigableSet descendingSet() { + return map().descendingKeySet(); + } + + @Override + public K floor(K e) { + return map().floorKey(e); + } + + @Override + public SortedSet headSet(K toElement) { + return headSet(toElement, false); + } + + @Override + public NavigableSet headSet(K toElement, boolean inclusive) { + return map().headMap(toElement, inclusive).navigableKeySet(); + } + + @Override + public K higher(K e) { + return map().higherKey(e); + } + + @Override + public K lower(K e) { + return map().lowerKey(e); + } + + @Override + NavigableMap map() { + return (NavigableMap) map; + } + + @Override + public K pollFirst() { + return keyOrNull(map().pollFirstEntry()); + } + + @Override + public K pollLast() { + return keyOrNull(map().pollLastEntry()); + } + + @Override + public NavigableSet subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) { + return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); + } + + @Override + public SortedSet subSet(K fromElement, K toElement) { + return subSet(fromElement, true, toElement, false); + } + + @Override + public SortedSet tailSet(K fromElement) { + return tailSet(fromElement, true); + } + + @Override + public NavigableSet tailSet(K fromElement, boolean inclusive) { + return map().tailMap(fromElement, inclusive).navigableKeySet(); + } + } + + private static class SortedAsMapView extends AsMapView implements SortedMap { + + SortedAsMapView(SortedSet set, Function function) { + super(set, function); + } + + @Override + SortedSet backingSet() { + return (SortedSet) super.backingSet(); + } + + @Override + public Comparator comparator() { + return backingSet().comparator(); + } + + @Override + public K firstKey() { + return backingSet().first(); + } + + @Override + public SortedMap headMap(K toKey) { + return asMap(backingSet().headSet(toKey), function); + } + + @Override + public Set keySet() { + return removeOnlySortedSet(backingSet()); + } + + @Override + public K lastKey() { + return backingSet().last(); + } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + return asMap(backingSet().subSet(fromKey, toKey), function); + } + + @Override + public SortedMap tailMap(K fromKey) { + return asMap(backingSet().tailSet(fromKey), function); + } + } + + static class SortedKeySet extends KeySet implements SortedSet { + SortedKeySet(SortedMap map) { + super(map); + } + + @Override + public Comparator comparator() { + return map().comparator(); + } + + @Override + public K first() { + return map().firstKey(); + } + + @Override + public SortedSet headSet(K toElement) { + return new SortedKeySet(map().headMap(toElement)); + } + + @Override + public K last() { + return map().lastKey(); + } + + @Override + SortedMap map() { + return (SortedMap) super.map(); + } + + @Override + public SortedSet subSet(K fromElement, K toElement) { + return new SortedKeySet(map().subMap(fromElement, toElement)); + } + + @Override + public SortedSet tailSet(K fromElement) { + return new SortedKeySet(map().tailMap(fromElement)); + } } static class SortedMapDifferenceImpl extends MapDifferenceImpl implements SortedMapDifference { @@ -620,17 +1441,687 @@ public final class Maps { } } - /** - * Returns the specified comparator if not null; otherwise returns {@code - * Ordering.natural()}. This method is an abomination of generics; the only - * purpose of this method is to contain the ugly type-casting in one place. - */ - @SuppressWarnings("unchecked") - static Comparator orNaturalOrder(@Nullable Comparator comparator) { - if (comparator != null) { // can't use ? : because of javac bug 5080917 - return comparator; + static class TransformedEntriesMap extends ImprovedAbstractMap { + final Map fromMap; + final EntryTransformer transformer; + + TransformedEntriesMap(Map fromMap, EntryTransformer transformer) { + this.fromMap = checkNotNull(fromMap); + this.transformer = checkNotNull(transformer); } - return (Comparator) Ordering.natural(); + + @Override + public void clear() { + fromMap.clear(); + } + + @Override + public boolean containsKey(Object key) { + return fromMap.containsKey(key); + } + + @Override + protected Set> createEntrySet() { + return new EntrySet() { + @Override + public Iterator> iterator() { + return Iterators.transform(fromMap.entrySet().iterator(), + Maps.asEntryToEntryFunction(transformer)); + } + + @Override + Map map() { + return TransformedEntriesMap.this; + } + }; + } + + // safe as long as the user followed the Warning in the javadoc + @SuppressWarnings("unchecked") + @Override + public V2 get(Object key) { + V1 value = fromMap.get(key); + return (value != null || fromMap.containsKey(key)) ? transformer.transformEntry((K) key, value) : null; + } + + @Override + public Set keySet() { + return fromMap.keySet(); + } + + // safe as long as the user followed the Warning in the javadoc + @SuppressWarnings("unchecked") + @Override + public V2 remove(Object key) { + return fromMap.containsKey(key) ? transformer.transformEntry((K) key, fromMap.remove(key)) : null; + } + + @Override + public int size() { + return fromMap.size(); + } + } + + @GwtIncompatible("NavigableMap") + private static class TransformedEntriesNavigableMap extends TransformedEntriesSortedMap + implements NavigableMap { + + TransformedEntriesNavigableMap(NavigableMap fromMap, + EntryTransformer transformer) { + super(fromMap, transformer); + } + + @Override + public Entry ceilingEntry(K key) { + return transformEntry(fromMap().ceilingEntry(key)); + } + + @Override + public K ceilingKey(K key) { + return fromMap().ceilingKey(key); + } + + @Override + public NavigableSet descendingKeySet() { + return fromMap().descendingKeySet(); + } + + @Override + public NavigableMap descendingMap() { + return transformEntries(fromMap().descendingMap(), transformer); + } + + @Override + public Entry firstEntry() { + return transformEntry(fromMap().firstEntry()); + } + + @Override + public Entry floorEntry(K key) { + return transformEntry(fromMap().floorEntry(key)); + } + + @Override + public K floorKey(K key) { + return fromMap().floorKey(key); + } + + @Override + protected NavigableMap fromMap() { + return (NavigableMap) super.fromMap(); + } + + @Override + public NavigableMap headMap(K toKey) { + return headMap(toKey, false); + } + + @Override + public NavigableMap headMap(K toKey, boolean inclusive) { + return transformEntries(fromMap().headMap(toKey, inclusive), transformer); + } + + @Override + public Entry higherEntry(K key) { + return transformEntry(fromMap().higherEntry(key)); + } + + @Override + public K higherKey(K key) { + return fromMap().higherKey(key); + } + + @Override + public Entry lastEntry() { + return transformEntry(fromMap().lastEntry()); + } + + @Override + public Entry lowerEntry(K key) { + return transformEntry(fromMap().lowerEntry(key)); + } + + @Override + public K lowerKey(K key) { + return fromMap().lowerKey(key); + } + + @Override + public NavigableSet navigableKeySet() { + return fromMap().navigableKeySet(); + } + + @Override + public Entry pollFirstEntry() { + return transformEntry(fromMap().pollFirstEntry()); + } + + @Override + public Entry pollLastEntry() { + return transformEntry(fromMap().pollLastEntry()); + } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return transformEntries(fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer); + } + + @Override + public NavigableMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); + } + + @Override + public NavigableMap tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer); + } + + @Nullable + private Entry transformEntry(@Nullable Entry entry) { + return (entry == null) ? null : Maps.transformEntry(transformer, entry); + } + } + + static class TransformedEntriesSortedMap extends TransformedEntriesMap + implements SortedMap { + + TransformedEntriesSortedMap(SortedMap fromMap, EntryTransformer transformer) { + super(fromMap, transformer); + } + + @Override + public Comparator comparator() { + return fromMap().comparator(); + } + + @Override + public K firstKey() { + return fromMap().firstKey(); + } + + protected SortedMap fromMap() { + return (SortedMap) fromMap; + } + + @Override + public SortedMap headMap(K toKey) { + return transformEntries(fromMap().headMap(toKey), transformer); + } + + @Override + public K lastKey() { + return fromMap().lastKey(); + } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + return transformEntries(fromMap().subMap(fromKey, toKey), transformer); + } + + @Override + public SortedMap tailMap(K fromKey) { + return transformEntries(fromMap().tailMap(fromKey), transformer); + } + } + + /** @see Maps#unmodifiableBiMap(BiMap) */ + private static class UnmodifiableBiMap extends ForwardingMap implements BiMap, Serializable { + private static final long serialVersionUID = 0; + final Map unmodifiableMap; + final BiMap delegate; + BiMap inverse; + + transient Set values; + + UnmodifiableBiMap(BiMap delegate, @Nullable BiMap inverse) { + unmodifiableMap = Collections.unmodifiableMap(delegate); + this.delegate = delegate; + this.inverse = inverse; + } + + @Override + protected Map delegate() { + return unmodifiableMap; + } + + @Override + public V forcePut(K key, V value) { + throw new UnsupportedOperationException(); + } + + @Override + public BiMap inverse() { + BiMap result = inverse; + return (result == null) ? inverse = new UnmodifiableBiMap(delegate.inverse(), this) : result; + } + + @Override + public Set values() { + Set result = values; + return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result; + } + } + + /** @see Multimaps#unmodifiableEntries */ + static class UnmodifiableEntries extends ForwardingCollection> { + private final Collection> entries; + + UnmodifiableEntries(Collection> entries) { + this.entries = entries; + } + + @Override + protected Collection> delegate() { + return entries; + } + + @Override + public Iterator> iterator() { + final Iterator> delegate = super.iterator(); + return new UnmodifiableIterator>() { + @Override + public boolean hasNext() { + return delegate.hasNext(); + } + + @Override + public Entry next() { + return unmodifiableEntry(delegate.next()); + } + }; + } + + // See java.util.Collections.UnmodifiableEntrySet for details on attacks. + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } + } + + /** @see Maps#unmodifiableEntrySet(Set) */ + static class UnmodifiableEntrySet extends UnmodifiableEntries implements Set> { + UnmodifiableEntrySet(Set> entries) { + super(entries); + } + + // See java.util.Collections.UnmodifiableEntrySet for details on attacks. + + @Override + public boolean equals(@Nullable Object object) { + return Sets.equalsImpl(this, object); + } + + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); + } + } + + @GwtIncompatible("NavigableMap") + static class UnmodifiableNavigableMap extends ForwardingSortedMap + implements NavigableMap, Serializable { + private final NavigableMap delegate; + + private transient UnmodifiableNavigableMap descendingMap; + + UnmodifiableNavigableMap(NavigableMap delegate) { + this.delegate = delegate; + } + + UnmodifiableNavigableMap(NavigableMap delegate, UnmodifiableNavigableMap descendingMap) { + this.delegate = delegate; + this.descendingMap = descendingMap; + } + + @Override + public Entry ceilingEntry(K key) { + return unmodifiableOrNull(delegate.ceilingEntry(key)); + } + + @Override + public K ceilingKey(K key) { + return delegate.ceilingKey(key); + } + + @Override + protected SortedMap delegate() { + return Collections.unmodifiableSortedMap(delegate); + } + + @Override + public NavigableSet descendingKeySet() { + return Sets.unmodifiableNavigableSet(delegate.descendingKeySet()); + } + + @Override + public NavigableMap descendingMap() { + UnmodifiableNavigableMap result = descendingMap; + return (result == null) ? descendingMap = new UnmodifiableNavigableMap(delegate.descendingMap(), this) + : result; + } + + @Override + public Entry firstEntry() { + return unmodifiableOrNull(delegate.firstEntry()); + } + + @Override + public Entry floorEntry(K key) { + return unmodifiableOrNull(delegate.floorEntry(key)); + } + + @Override + public K floorKey(K key) { + return delegate.floorKey(key); + } + + @Override + public SortedMap headMap(K toKey) { + return headMap(toKey, false); + } + + @Override + public NavigableMap headMap(K toKey, boolean inclusive) { + return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive)); + } + + @Override + public Entry higherEntry(K key) { + return unmodifiableOrNull(delegate.higherEntry(key)); + } + + @Override + public K higherKey(K key) { + return delegate.higherKey(key); + } + + @Override + public Set keySet() { + return navigableKeySet(); + } + + @Override + public Entry lastEntry() { + return unmodifiableOrNull(delegate.lastEntry()); + } + + @Override + public Entry lowerEntry(K key) { + return unmodifiableOrNull(delegate.lowerEntry(key)); + } + + @Override + public K lowerKey(K key) { + return delegate.lowerKey(key); + } + + @Override + public NavigableSet navigableKeySet() { + return Sets.unmodifiableNavigableSet(delegate.navigableKeySet()); + } + + @Override + public final Entry pollFirstEntry() { + throw new UnsupportedOperationException(); + } + + @Override + public final Entry pollLastEntry() { + throw new UnsupportedOperationException(); + } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return Maps.unmodifiableNavigableMap(delegate.subMap(fromKey, fromInclusive, toKey, toInclusive)); + } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + return subMap(fromKey, true, toKey, false); + } + + @Override + public SortedMap tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive)); + } + } + + static class ValueDifferenceImpl implements MapDifference.ValueDifference { + static ValueDifference create(@Nullable V left, @Nullable V right) { + return new ValueDifferenceImpl(left, right); + } + + private final V left; + + private final V right; + + private ValueDifferenceImpl(@Nullable V left, @Nullable V right) { + this.left = left; + this.right = right; + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof MapDifference.ValueDifference) { + MapDifference.ValueDifference that = (MapDifference.ValueDifference) object; + return Objects.equal(this.left, that.leftValue()) && Objects.equal(this.right, that.rightValue()); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hashCode(left, right); + } + + @Override + public V leftValue() { + return left; + } + + @Override + public V rightValue() { + return right; + } + + @Override + public String toString() { + return "(" + left + ", " + right + ")"; + } + } + + static class Values extends AbstractCollection { + final Map map; + + Values(Map map) { + this.map = checkNotNull(map); + } + + @Override + public void clear() { + map().clear(); + } + + @Override + public boolean contains(@Nullable Object o) { + return map().containsValue(o); + } + + @Override + public boolean isEmpty() { + return map().isEmpty(); + } + + @Override + public Iterator iterator() { + return valueIterator(map().entrySet().iterator()); + } + + final Map map() { + return map; + } + + @Override + public boolean remove(Object o) { + try { + return super.remove(o); + } catch (UnsupportedOperationException e) { + for (Entry entry : map().entrySet()) { + if (Objects.equal(o, entry.getValue())) { + map().remove(entry.getKey()); + return true; + } + } + return false; + } + } + + @Override + public boolean removeAll(Collection c) { + try { + return super.removeAll(checkNotNull(c)); + } catch (UnsupportedOperationException e) { + Set toRemove = Sets.newHashSet(); + for (Entry entry : map().entrySet()) { + if (c.contains(entry.getValue())) { + toRemove.add(entry.getKey()); + } + } + return map().keySet().removeAll(toRemove); + } + } + + @Override + public boolean retainAll(Collection c) { + try { + return super.retainAll(checkNotNull(c)); + } catch (UnsupportedOperationException e) { + Set toRetain = Sets.newHashSet(); + for (Entry entry : map().entrySet()) { + if (c.contains(entry.getValue())) { + toRetain.add(entry.getKey()); + } + } + return map().keySet().retainAll(toRetain); + } + } + + @Override + public int size() { + return map().size(); + } + } + + static final MapJoiner STANDARD_JOINER = Collections2.STANDARD_JOINER.withKeyValueSeparator("="); + + /** + * Returns a {@link Converter} that converts values using {@link BiMap#get + * bimap.get()}, and whose inverse view converts values using + * {@link BiMap#inverse bimap.inverse()}{@code .get()}. + * + *

+ * To use a plain {@link Map} as a {@link Function}, see + * {@link com.google.common.base.Functions#forMap(Map)} or + * {@link com.google.common.base.Functions#forMap(Map, Object)}. + * + * @since 16.0 + */ + @Beta + public static Converter asConverter(final BiMap bimap) { + return new BiMapConverter(bimap); + } + + /** + * Views an entry transformer as a function from entries to entries. + */ + static Function, Entry> asEntryToEntryFunction( + final EntryTransformer transformer) { + checkNotNull(transformer); + return new Function, Entry>() { + @Override + public Entry apply(final Entry entry) { + return transformEntry(transformer, entry); + } + }; + } + + /** + * Views an entry transformer as a function from {@code Entry} to values. + */ + static Function, V2> asEntryToValueFunction( + final EntryTransformer transformer) { + checkNotNull(transformer); + return new Function, V2>() { + @Override + public V2 apply(Entry entry) { + return transformer.transformEntry(entry.getKey(), entry.getValue()); + } + }; + } + + /** + * Views a function as an entry transformer that ignores the entry key. + */ + static EntryTransformer asEntryTransformer(final Function function) { + checkNotNull(function); + return new EntryTransformer() { + @Override + public V2 transformEntry(K key, V1 value) { + return function.apply(value); + } + }; + } + + /** + * Returns a view of the navigable set as a map, mapping keys from the set + * according to the specified function. + * + *

+ * Specifically, for each {@code k} in the backing set, the returned map has an + * entry mapping {@code k} to {@code function.apply(k)}. The {@code + * keySet}, {@code values}, and {@code entrySet} views of the returned map + * iterate in the same order as the backing set. + * + *

+ * Modifications to the backing set are read through to the returned map. The + * returned map supports removal operations if the backing set does. Removal + * operations write through to the backing set. The returned map does not + * support put operations. + * + *

+ * Warning: If the function rejects {@code null}, caution is required to + * make sure the set does not contain {@code null}, because the view cannot stop + * {@code null} from being added to the set. + * + *

+ * Warning: This method assumes that for any instance {@code k} of key + * type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of type + * {@code K}. Using a key type for which this may not hold, such as + * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods + * on the resulting map view. + * + * @since 14.0 + */ + @Beta + @GwtIncompatible("NavigableMap") + public static NavigableMap asMap(NavigableSet set, Function function) { + return new NavigableAsMapView(set, function); } /** @@ -708,123 +2199,6 @@ public final class Maps { return Platform.mapsAsMapSortedSet(set, function); } - static SortedMap asMapSortedIgnoreNavigable(SortedSet set, Function function) { - return new SortedAsMapView(set, function); - } - - /** - * Returns a view of the navigable set as a map, mapping keys from the set - * according to the specified function. - * - *

- * Specifically, for each {@code k} in the backing set, the returned map has an - * entry mapping {@code k} to {@code function.apply(k)}. The {@code - * keySet}, {@code values}, and {@code entrySet} views of the returned map - * iterate in the same order as the backing set. - * - *

- * Modifications to the backing set are read through to the returned map. The - * returned map supports removal operations if the backing set does. Removal - * operations write through to the backing set. The returned map does not - * support put operations. - * - *

- * Warning: If the function rejects {@code null}, caution is required to - * make sure the set does not contain {@code null}, because the view cannot stop - * {@code null} from being added to the set. - * - *

- * Warning: This method assumes that for any instance {@code k} of key - * type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of type - * {@code K}. Using a key type for which this may not hold, such as - * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods - * on the resulting map view. - * - * @since 14.0 - */ - @Beta - @GwtIncompatible("NavigableMap") - public static NavigableMap asMap(NavigableSet set, Function function) { - return new NavigableAsMapView(set, function); - } - - private static class AsMapView extends ImprovedAbstractMap { - - private final Set set; - final Function function; - - Set backingSet() { - return set; - } - - AsMapView(Set set, Function function) { - this.set = checkNotNull(set); - this.function = checkNotNull(function); - } - - @Override - public Set createKeySet() { - return removeOnlySet(backingSet()); - } - - @Override - Collection createValues() { - return Collections2.transform(set, function); - } - - @Override - public int size() { - return backingSet().size(); - } - - @Override - public boolean containsKey(@Nullable Object key) { - return backingSet().contains(key); - } - - @Override - public V get(@Nullable Object key) { - if (Collections2.safeContains(backingSet(), key)) { - @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it - K k = (K) key; - return function.apply(k); - } else { - return null; - } - } - - @Override - public V remove(@Nullable Object key) { - if (backingSet().remove(key)) { - @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it - K k = (K) key; - return function.apply(k); - } else { - return null; - } - } - - @Override - public void clear() { - backingSet().clear(); - } - - @Override - protected Set> createEntrySet() { - return new EntrySet() { - @Override - Map map() { - return AsMapView.this; - } - - @Override - public Iterator> iterator() { - return asMapEntryIterator(backingSet(), function); - } - }; - } - } - static Iterator> asMapEntryIterator(Set set, final Function function) { return new TransformedIterator>(set.iterator()) { @Override @@ -834,1029 +2208,8 @@ public final class Maps { }; } - private static class SortedAsMapView extends AsMapView implements SortedMap { - - SortedAsMapView(SortedSet set, Function function) { - super(set, function); - } - - @Override - SortedSet backingSet() { - return (SortedSet) super.backingSet(); - } - - @Override - public Comparator comparator() { - return backingSet().comparator(); - } - - @Override - public Set keySet() { - return removeOnlySortedSet(backingSet()); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return asMap(backingSet().subSet(fromKey, toKey), function); - } - - @Override - public SortedMap headMap(K toKey) { - return asMap(backingSet().headSet(toKey), function); - } - - @Override - public SortedMap tailMap(K fromKey) { - return asMap(backingSet().tailSet(fromKey), function); - } - - @Override - public K firstKey() { - return backingSet().first(); - } - - @Override - public K lastKey() { - return backingSet().last(); - } - } - - @GwtIncompatible("NavigableMap") - private static final class NavigableAsMapView extends AbstractNavigableMap { - /* - * Using AbstractNavigableMap is simpler than extending SortedAsMapView and - * rewriting all the NavigableMap methods. - */ - - private final NavigableSet set; - private final Function function; - - NavigableAsMapView(NavigableSet ks, Function vFunction) { - this.set = checkNotNull(ks); - this.function = checkNotNull(vFunction); - } - - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function); - } - - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - return asMap(set.headSet(toKey, inclusive), function); - } - - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - return asMap(set.tailSet(fromKey, inclusive), function); - } - - @Override - public Comparator comparator() { - return set.comparator(); - } - - @Override - @Nullable - public V get(@Nullable Object key) { - if (Collections2.safeContains(set, key)) { - @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it - K k = (K) key; - return function.apply(k); - } else { - return null; - } - } - - @Override - public void clear() { - set.clear(); - } - - @Override - Iterator> entryIterator() { - return asMapEntryIterator(set, function); - } - - @Override - Iterator> descendingEntryIterator() { - return descendingMap().entrySet().iterator(); - } - - @Override - public NavigableSet navigableKeySet() { - return removeOnlyNavigableSet(set); - } - - @Override - public int size() { - return set.size(); - } - - @Override - public NavigableMap descendingMap() { - return asMap(set.descendingSet(), function); - } - } - - private static Set removeOnlySet(final Set set) { - return new ForwardingSet() { - @Override - protected Set delegate() { - return set; - } - - @Override - public boolean add(E element) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAll(Collection es) { - throw new UnsupportedOperationException(); - } - }; - } - - private static SortedSet removeOnlySortedSet(final SortedSet set) { - return new ForwardingSortedSet() { - @Override - protected SortedSet delegate() { - return set; - } - - @Override - public boolean add(E element) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAll(Collection es) { - throw new UnsupportedOperationException(); - } - - @Override - public SortedSet headSet(E toElement) { - return removeOnlySortedSet(super.headSet(toElement)); - } - - @Override - public SortedSet subSet(E fromElement, E toElement) { - return removeOnlySortedSet(super.subSet(fromElement, toElement)); - } - - @Override - public SortedSet tailSet(E fromElement) { - return removeOnlySortedSet(super.tailSet(fromElement)); - } - }; - } - - @GwtIncompatible("NavigableSet") - private static NavigableSet removeOnlyNavigableSet(final NavigableSet set) { - return new ForwardingNavigableSet() { - @Override - protected NavigableSet delegate() { - return set; - } - - @Override - public boolean add(E element) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAll(Collection es) { - throw new UnsupportedOperationException(); - } - - @Override - public SortedSet headSet(E toElement) { - return removeOnlySortedSet(super.headSet(toElement)); - } - - @Override - public SortedSet subSet(E fromElement, E toElement) { - return removeOnlySortedSet(super.subSet(fromElement, toElement)); - } - - @Override - public SortedSet tailSet(E fromElement) { - return removeOnlySortedSet(super.tailSet(fromElement)); - } - - @Override - public NavigableSet headSet(E toElement, boolean inclusive) { - return removeOnlyNavigableSet(super.headSet(toElement, inclusive)); - } - - @Override - public NavigableSet tailSet(E fromElement, boolean inclusive) { - return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive)); - } - - @Override - public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return removeOnlyNavigableSet(super.subSet(fromElement, fromInclusive, toElement, toInclusive)); - } - - @Override - public NavigableSet descendingSet() { - return removeOnlyNavigableSet(super.descendingSet()); - } - }; - } - - /** - * Returns an immutable map whose keys are the distinct elements of {@code - * keys} and whose value for each key was computed by {@code valueFunction}. The - * map's iteration order is the order of the first appearance of each key in - * {@code keys}. - * - *

- * If {@code keys} is a {@link Set}, a live view can be obtained instead of a - * copy using {@link Maps#asMap(Set, Function)}. - * - * @throws NullPointerException if any element of {@code keys} is {@code null}, - * or if {@code valueFunction} produces - * {@code null} for any key - * @since 14.0 - */ - @Beta - public static ImmutableMap toMap(Iterable keys, Function valueFunction) { - return toMap(keys.iterator(), valueFunction); - } - - /** - * Returns an immutable map whose keys are the distinct elements of {@code - * keys} and whose value for each key was computed by {@code valueFunction}. The - * map's iteration order is the order of the first appearance of each key in - * {@code keys}. - * - * @throws NullPointerException if any element of {@code keys} is {@code null}, - * or if {@code valueFunction} produces - * {@code null} for any key - * @since 14.0 - */ - @Beta - public static ImmutableMap toMap(Iterator keys, Function valueFunction) { - checkNotNull(valueFunction); - // Using LHM instead of a builder so as not to fail on duplicate keys - Map builder = newLinkedHashMap(); - while (keys.hasNext()) { - K key = keys.next(); - builder.put(key, valueFunction.apply(key)); - } - return ImmutableMap.copyOf(builder); - } - - /** - * Returns an immutable map for which the {@link Map#values} are the given - * elements in the given order, and each key is the product of invoking a - * supplied function on its corresponding value. - * - * @param values the values to use when constructing the {@code Map} - * @param keyFunction the function used to produce the key for each value - * @return a map mapping the result of evaluating the function {@code - * keyFunction} on each value in the input collection to that value - * @throws IllegalArgumentException if {@code keyFunction} produces the same key - * for more than one value in the input - * collection - * @throws NullPointerException if any elements of {@code values} is null, - * or if {@code keyFunction} produces - * {@code null} for any value - */ - public static ImmutableMap uniqueIndex(Iterable values, Function keyFunction) { - return uniqueIndex(values.iterator(), keyFunction); - } - - /** - * Returns an immutable map for which the {@link Map#values} are the given - * elements in the given order, and each key is the product of invoking a - * supplied function on its corresponding value. - * - * @param values the values to use when constructing the {@code Map} - * @param keyFunction the function used to produce the key for each value - * @return a map mapping the result of evaluating the function {@code - * keyFunction} on each value in the input collection to that value - * @throws IllegalArgumentException if {@code keyFunction} produces the same key - * for more than one value in the input - * collection - * @throws NullPointerException if any elements of {@code values} is null, - * or if {@code keyFunction} produces - * {@code null} for any value - * @since 10.0 - */ - public static ImmutableMap uniqueIndex(Iterator values, Function keyFunction) { - checkNotNull(keyFunction); - ImmutableMap.Builder builder = ImmutableMap.builder(); - while (values.hasNext()) { - V value = values.next(); - builder.put(keyFunction.apply(value), value); - } - return builder.build(); - } - - /** - * Creates an {@code ImmutableMap} from a {@code Properties} - * instance. Properties normally derive from {@code Map}, but - * they typically contain strings, which is awkward. This method lets you get a - * plain-old-{@code Map} out of a {@code Properties}. - * - * @param properties a {@code Properties} object to be converted - * @return an immutable map containing all the entries in {@code properties} - * @throws ClassCastException if any key in {@code Properties} is not a {@code - * String} - * @throws NullPointerException if any key or value in {@code Properties} is - * null - */ - @GwtIncompatible("java.util.Properties") - public static ImmutableMap fromProperties(Properties properties) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - - for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { - String key = (String) e.nextElement(); - builder.put(key, properties.getProperty(key)); - } - - return builder.build(); - } - - /** - * Returns an immutable map entry with the specified key and value. The - * {@link Entry#setValue} operation throws an - * {@link UnsupportedOperationException}. - * - *

- * The returned entry is serializable. - * - * @param key the key to be associated with the returned entry - * @param value the value to be associated with the returned entry - */ - @GwtCompatible(serializable = true) - public static Entry immutableEntry(@Nullable K key, @Nullable V value) { - return new ImmutableEntry(key, value); - } - - /** - * Returns an unmodifiable view of the specified set of entries. The - * {@link Entry#setValue} operation throws an - * {@link UnsupportedOperationException}, as do any operations that would modify - * the returned set. - * - * @param entrySet the entries for which to return an unmodifiable view - * @return an unmodifiable view of the entries - */ - static Set> unmodifiableEntrySet(Set> entrySet) { - return new UnmodifiableEntrySet(Collections.unmodifiableSet(entrySet)); - } - - /** - * Returns an unmodifiable view of the specified map entry. The - * {@link Entry#setValue} operation throws an - * {@link UnsupportedOperationException}. This also has the side-effect of - * redefining {@code equals} to comply with the Entry contract, to avoid a - * possible nefarious implementation of equals. - * - * @param entry the entry for which to return an unmodifiable view - * @return an unmodifiable view of the entry - */ - static Entry unmodifiableEntry(final Entry entry) { - checkNotNull(entry); - return new AbstractMapEntry() { - @Override - public K getKey() { - return entry.getKey(); - } - - @Override - public V getValue() { - return entry.getValue(); - } - }; - } - - /** @see Multimaps#unmodifiableEntries */ - static class UnmodifiableEntries extends ForwardingCollection> { - private final Collection> entries; - - UnmodifiableEntries(Collection> entries) { - this.entries = entries; - } - - @Override - protected Collection> delegate() { - return entries; - } - - @Override - public Iterator> iterator() { - final Iterator> delegate = super.iterator(); - return new UnmodifiableIterator>() { - @Override - public boolean hasNext() { - return delegate.hasNext(); - } - - @Override - public Entry next() { - return unmodifiableEntry(delegate.next()); - } - }; - } - - // See java.util.Collections.UnmodifiableEntrySet for details on attacks. - - @Override - public Object[] toArray() { - return standardToArray(); - } - - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - } - - /** @see Maps#unmodifiableEntrySet(Set) */ - static class UnmodifiableEntrySet extends UnmodifiableEntries implements Set> { - UnmodifiableEntrySet(Set> entries) { - super(entries); - } - - // See java.util.Collections.UnmodifiableEntrySet for details on attacks. - - @Override - public boolean equals(@Nullable Object object) { - return Sets.equalsImpl(this, object); - } - - @Override - public int hashCode() { - return Sets.hashCodeImpl(this); - } - } - - /** - * Returns a {@link Converter} that converts values using {@link BiMap#get - * bimap.get()}, and whose inverse view converts values using - * {@link BiMap#inverse bimap.inverse()}{@code .get()}. - * - *

- * To use a plain {@link Map} as a {@link Function}, see - * {@link com.google.common.base.Functions#forMap(Map)} or - * {@link com.google.common.base.Functions#forMap(Map, Object)}. - * - * @since 16.0 - */ - @Beta - public static Converter asConverter(final BiMap bimap) { - return new BiMapConverter(bimap); - } - - private static final class BiMapConverter extends Converter implements Serializable { - private final BiMap bimap; - - BiMapConverter(BiMap bimap) { - this.bimap = checkNotNull(bimap); - } - - @Override - protected B doForward(A a) { - return convert(bimap, a); - } - - @Override - protected A doBackward(B b) { - return convert(bimap.inverse(), b); - } - - private static Y convert(BiMap bimap, X input) { - Y output = bimap.get(input); - checkArgument(output != null, "No non-null mapping present for input: %s", input); - return output; - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof BiMapConverter) { - BiMapConverter that = (BiMapConverter) object; - return this.bimap.equals(that.bimap); - } - return false; - } - - @Override - public int hashCode() { - return bimap.hashCode(); - } - - // There's really no good way to implement toString() without printing the - // entire BiMap, right? - @Override - public String toString() { - return "Maps.asConverter(" + bimap + ")"; - } - - private static final long serialVersionUID = 0L; - } - - /** - * Returns a synchronized (thread-safe) bimap backed by the specified bimap. In - * order to guarantee serial access, it is critical that all access to - * the backing bimap is accomplished through the returned bimap. - * - *

- * It is imperative that the user manually synchronize on the returned map when - * accessing any of its collection views: - * - *

-	 *    {@code
-	 *
-	 *   BiMap map = Maps.synchronizedBiMap(
-	 *       HashBiMap.create());
-	 *   ...
-	 *   Set set = map.keySet();  // Needn't be in synchronized block
-	 *   ...
-	 *   synchronized (map) {  // Synchronizing on map, not set!
-	 *     Iterator it = set.iterator(); // Must be in synchronized block
-	 *     while (it.hasNext()) {
-	 *       foo(it.next());
-	 *     }
-	 *   }}
-	 * 
- * - *

- * Failure to follow this advice may result in non-deterministic behavior. - * - *

- * The returned bimap will be serializable if the specified bimap is - * serializable. - * - * @param bimap the bimap to be wrapped in a synchronized view - * @return a sychronized view of the specified bimap - */ - public static BiMap synchronizedBiMap(BiMap bimap) { - return Synchronized.biMap(bimap, null); - } - - /** - * Returns an unmodifiable view of the specified bimap. This method allows - * modules to provide users with "read-only" access to internal bimaps. Query - * operations on the returned bimap "read through" to the specified bimap, and - * attempts to modify the returned map, whether direct or via its collection - * views, result in an {@code UnsupportedOperationException}. - * - *

- * The returned bimap will be serializable if the specified bimap is - * serializable. - * - * @param bimap the bimap for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified bimap - */ - public static BiMap unmodifiableBiMap(BiMap bimap) { - return new UnmodifiableBiMap(bimap, null); - } - - /** @see Maps#unmodifiableBiMap(BiMap) */ - private static class UnmodifiableBiMap extends ForwardingMap implements BiMap, Serializable { - final Map unmodifiableMap; - final BiMap delegate; - BiMap inverse; - transient Set values; - - UnmodifiableBiMap(BiMap delegate, @Nullable BiMap inverse) { - unmodifiableMap = Collections.unmodifiableMap(delegate); - this.delegate = delegate; - this.inverse = inverse; - } - - @Override - protected Map delegate() { - return unmodifiableMap; - } - - @Override - public V forcePut(K key, V value) { - throw new UnsupportedOperationException(); - } - - @Override - public BiMap inverse() { - BiMap result = inverse; - return (result == null) ? inverse = new UnmodifiableBiMap(delegate.inverse(), this) : result; - } - - @Override - public Set values() { - Set result = values; - return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a view of a map where each value is transformed by a function. All - * other properties of the map, such as iteration order, are left intact. For - * example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	Map map = ImmutableMap.of("a", 4, "b", 9);
-	 * 	Function sqrt = new Function() {
-	 * 		public Double apply(Integer in) {
-	 * 			return Math.sqrt((int) in);
-	 * 		}
-	 * 	};
-	 * 	Map transformed = Maps.transformValues(map, sqrt);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {a=2.0, b=3.0}}. - * - *

- * Changes in the underlying map are reflected in this view. Conversely, this - * view supports removal operations, and these are reflected in the underlying - * map. - * - *

- * It's acceptable for the underlying map to contain null keys, and even null - * values provided that the function is capable of accepting null input. The - * transformed map might contain null values, if the function sometimes gives a - * null result. - * - *

- * The returned map is not thread-safe or serializable, even if the underlying - * map is. - * - *

- * The function is applied lazily, invoked when needed. This is necessary for - * the returned map to be a view, but it means that the function will be applied - * many times for bulk operations like {@link Map#containsValue} and - * {@code Map.toString()}. For this to perform well, {@code function} should be - * fast. To avoid lazy evaluation when the returned map doesn't need to be a - * view, copy the returned map into a new map of your choosing. - */ - public static Map transformValues(Map fromMap, Function function) { - return transformEntries(fromMap, asEntryTransformer(function)); - } - - /** - * Returns a view of a sorted map where each value is transformed by a function. - * All other properties of the map, such as iteration order, are left intact. - * For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	SortedMap map = ImmutableSortedMap.of("a", 4, "b", 9);
-	 * 	Function sqrt = new Function() {
-	 * 		public Double apply(Integer in) {
-	 * 			return Math.sqrt((int) in);
-	 * 		}
-	 * 	};
-	 * 	SortedMap transformed = Maps.transformValues(map, sqrt);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {a=2.0, b=3.0}}. - * - *

- * Changes in the underlying map are reflected in this view. Conversely, this - * view supports removal operations, and these are reflected in the underlying - * map. - * - *

- * It's acceptable for the underlying map to contain null keys, and even null - * values provided that the function is capable of accepting null input. The - * transformed map might contain null values, if the function sometimes gives a - * null result. - * - *

- * The returned map is not thread-safe or serializable, even if the underlying - * map is. - * - *

- * The function is applied lazily, invoked when needed. This is necessary for - * the returned map to be a view, but it means that the function will be applied - * many times for bulk operations like {@link Map#containsValue} and - * {@code Map.toString()}. For this to perform well, {@code function} should be - * fast. To avoid lazy evaluation when the returned map doesn't need to be a - * view, copy the returned map into a new map of your choosing. - * - * @since 11.0 - */ - public static SortedMap transformValues(SortedMap fromMap, - Function function) { - return transformEntries(fromMap, asEntryTransformer(function)); - } - - /** - * Returns a view of a navigable map where each value is transformed by a - * function. All other properties of the map, such as iteration order, are left - * intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	NavigableMap map = Maps.newTreeMap();
-	 * 	map.put("a", 4);
-	 * 	map.put("b", 9);
-	 * 	Function sqrt = new Function() {
-	 * 		public Double apply(Integer in) {
-	 * 			return Math.sqrt((int) in);
-	 * 		}
-	 * 	};
-	 * 	NavigableMap transformed = Maps.transformNavigableValues(map, sqrt);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {a=2.0, b=3.0}}. - * - * Changes in the underlying map are reflected in this view. Conversely, this - * view supports removal operations, and these are reflected in the underlying - * map. - * - *

- * It's acceptable for the underlying map to contain null keys, and even null - * values provided that the function is capable of accepting null input. The - * transformed map might contain null values, if the function sometimes gives a - * null result. - * - *

- * The returned map is not thread-safe or serializable, even if the underlying - * map is. - * - *

- * The function is applied lazily, invoked when needed. This is necessary for - * the returned map to be a view, but it means that the function will be applied - * many times for bulk operations like {@link Map#containsValue} and - * {@code Map.toString()}. For this to perform well, {@code function} should be - * fast. To avoid lazy evaluation when the returned map doesn't need to be a - * view, copy the returned map into a new map of your choosing. - * - * @since 13.0 - */ - @GwtIncompatible("NavigableMap") - public static NavigableMap transformValues(NavigableMap fromMap, - Function function) { - return transformEntries(fromMap, asEntryTransformer(function)); - } - - /** - * Returns a view of a map whose values are derived from the original map's - * entries. In contrast to {@link #transformValues}, this method's - * entry-transformation logic may depend on the key as well as the value. - * - *

- * All other properties of the transformed map, such as iteration order, are - * left intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	Map options = ImmutableMap.of("verbose", true, "sort", false);
-	 * 	EntryTransformer flagPrefixer = new EntryTransformer() {
-	 * 		public String transformEntry(String key, Boolean value) {
-	 * 			return value ? key : "no" + key;
-	 * 		}
-	 * 	};
-	 * 	Map transformed = Maps.transformEntries(options, flagPrefixer);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {verbose=verbose, sort=nosort}}. - * - *

- * Changes in the underlying map are reflected in this view. Conversely, this - * view supports removal operations, and these are reflected in the underlying - * map. - * - *

- * It's acceptable for the underlying map to contain null keys and null values - * provided that the transformer is capable of accepting null inputs. The - * transformed map might contain null values if the transformer sometimes gives - * a null result. - * - *

- * The returned map is not thread-safe or serializable, even if the underlying - * map is. - * - *

- * The transformer is applied lazily, invoked when needed. This is necessary for - * the returned map to be a view, but it means that the transformer will be - * applied many times for bulk operations like {@link Map#containsValue} and - * {@link Object#toString}. For this to perform well, {@code transformer} should - * be fast. To avoid lazy evaluation when the returned map doesn't need to be a - * view, copy the returned map into a new map of your choosing. - * - *

- * Warning: This method assumes that for any instance {@code k} of - * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies - * that {@code k2} is also of type {@code K}. Using an {@code - * EntryTransformer} key type for which this may not hold, such as {@code - * ArrayList}, may risk a {@code ClassCastException} when calling methods on the - * transformed map. - * - * @since 7.0 - */ - public static Map transformEntries(Map fromMap, - EntryTransformer transformer) { - if (fromMap instanceof SortedMap) { - return transformEntries((SortedMap) fromMap, transformer); - } - return new TransformedEntriesMap(fromMap, transformer); - } - - /** - * Returns a view of a sorted map whose values are derived from the original - * sorted map's entries. In contrast to {@link #transformValues}, this method's - * entry-transformation logic may depend on the key as well as the value. - * - *

- * All other properties of the transformed map, such as iteration order, are - * left intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	Map options = ImmutableSortedMap.of("verbose", true, "sort", false);
-	 * 	EntryTransformer flagPrefixer = new EntryTransformer() {
-	 * 		public String transformEntry(String key, Boolean value) {
-	 * 			return value ? key : "yes" + key;
-	 * 		}
-	 * 	};
-	 * 	SortedMap transformed = Maps.transformEntries(options, flagPrefixer);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {sort=yessort, verbose=verbose}}. - * - *

- * Changes in the underlying map are reflected in this view. Conversely, this - * view supports removal operations, and these are reflected in the underlying - * map. - * - *

- * It's acceptable for the underlying map to contain null keys and null values - * provided that the transformer is capable of accepting null inputs. The - * transformed map might contain null values if the transformer sometimes gives - * a null result. - * - *

- * The returned map is not thread-safe or serializable, even if the underlying - * map is. - * - *

- * The transformer is applied lazily, invoked when needed. This is necessary for - * the returned map to be a view, but it means that the transformer will be - * applied many times for bulk operations like {@link Map#containsValue} and - * {@link Object#toString}. For this to perform well, {@code transformer} should - * be fast. To avoid lazy evaluation when the returned map doesn't need to be a - * view, copy the returned map into a new map of your choosing. - * - *

- * Warning: This method assumes that for any instance {@code k} of - * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies - * that {@code k2} is also of type {@code K}. Using an {@code - * EntryTransformer} key type for which this may not hold, such as {@code - * ArrayList}, may risk a {@code ClassCastException} when calling methods on the - * transformed map. - * - * @since 11.0 - */ - public static SortedMap transformEntries(SortedMap fromMap, - EntryTransformer transformer) { - return Platform.mapsTransformEntriesSortedMap(fromMap, transformer); - } - - /** - * Returns a view of a navigable map whose values are derived from the original - * navigable map's entries. In contrast to {@link #transformValues}, this - * method's entry-transformation logic may depend on the key as well as the - * value. - * - *

- * All other properties of the transformed map, such as iteration order, are - * left intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	NavigableMap options = Maps.newTreeMap();
-	 * 	options.put("verbose", false);
-	 * 	options.put("sort", true);
-	 * 	EntryTransformer flagPrefixer = new EntryTransformer() {
-	 * 		public String transformEntry(String key, Boolean value) {
-	 * 			return value ? key : ("yes" + key);
-	 * 		}
-	 * 	};
-	 * 	NavigableMap transformed = LabsMaps.transformNavigableEntries(options, flagPrefixer);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {sort=yessort, verbose=verbose}}. - * - *

- * Changes in the underlying map are reflected in this view. Conversely, this - * view supports removal operations, and these are reflected in the underlying - * map. - * - *

- * It's acceptable for the underlying map to contain null keys and null values - * provided that the transformer is capable of accepting null inputs. The - * transformed map might contain null values if the transformer sometimes gives - * a null result. - * - *

- * The returned map is not thread-safe or serializable, even if the underlying - * map is. - * - *

- * The transformer is applied lazily, invoked when needed. This is necessary for - * the returned map to be a view, but it means that the transformer will be - * applied many times for bulk operations like {@link Map#containsValue} and - * {@link Object#toString}. For this to perform well, {@code transformer} should - * be fast. To avoid lazy evaluation when the returned map doesn't need to be a - * view, copy the returned map into a new map of your choosing. - * - *

- * Warning: This method assumes that for any instance {@code k} of - * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies - * that {@code k2} is also of type {@code K}. Using an {@code - * EntryTransformer} key type for which this may not hold, such as {@code - * ArrayList}, may risk a {@code ClassCastException} when calling methods on the - * transformed map. - * - * @since 13.0 - */ - @GwtIncompatible("NavigableMap") - public static NavigableMap transformEntries(final NavigableMap fromMap, - EntryTransformer transformer) { - return new TransformedEntriesNavigableMap(fromMap, transformer); - } - - static SortedMap transformEntriesIgnoreNavigable(SortedMap fromMap, - EntryTransformer transformer) { - return new TransformedEntriesSortedMap(fromMap, transformer); - } - - /** - * A transformation of the value of a key-value pair, using both key and value - * as inputs. To apply the transformation to a map, use - * {@link Maps#transformEntries(Map, EntryTransformer)}. - * - * @param the key type of the input and output entries - * @param the value type of the input entry - * @param the value type of the output entry - * @since 7.0 - */ - public interface EntryTransformer { - /** - * Determines an output value based on a key-value pair. This method is - * generally expected, but not absolutely required, to have the following - * properties: - * - *

    - *
  • Its execution does not cause any observable side effects. - *
  • The computation is consistent with equals; that is, - * {@link Objects#equal Objects.equal}{@code (k1, k2) &&} - * {@link Objects#equal}{@code (v1, v2)} implies that {@code - * Objects.equal(transformer.transform(k1, v1), - * transformer.transform(k2, v2))}. - *
- * - * @throws NullPointerException if the key or value is null and this transformer - * does not accept null arguments - */ - V2 transformEntry(@Nullable K key, @Nullable V1 value); - } - - /** - * Views a function as an entry transformer that ignores the entry key. - */ - static EntryTransformer asEntryTransformer(final Function function) { - checkNotNull(function); - return new EntryTransformer() { - @Override - public V2 transformEntry(K key, V1 value) { - return function.apply(value); - } - }; + static SortedMap asMapSortedIgnoreNavigable(SortedSet set, Function function) { + return new SortedAsMapView(set, function); } static Function asValueToValueFunction(final EntryTransformer transformer, @@ -1871,599 +2224,201 @@ public final class Maps { } /** - * Views an entry transformer as a function from {@code Entry} to values. + * Returns a capacity that is sufficient to keep the map from being resized as + * long as it grows no larger than expectedSize and the load factor is >= its + * default (0.75). */ - static Function, V2> asEntryToValueFunction( - final EntryTransformer transformer) { - checkNotNull(transformer); - return new Function, V2>() { - @Override - public V2 apply(Entry entry) { - return transformer.transformEntry(entry.getKey(), entry.getValue()); - } - }; + static int capacity(int expectedSize) { + if (expectedSize < 3) { + checkNonnegative(expectedSize, "expectedSize"); + return expectedSize + 1; + } + if (expectedSize < Ints.MAX_POWER_OF_TWO) { + return expectedSize + expectedSize / 3; + } + return Integer.MAX_VALUE; // any large value } /** - * Returns a view of an entry transformed by the specified transformer. + * Implements {@code Collection.contains} safely for forwarding collections of + * map entries. If {@code o} is an instance of {@code Map.Entry}, it is wrapped + * using {@link #unmodifiableEntry} to protect against a possible nefarious + * equals method. + * + *

+ * Note that {@code c} is the backing (delegate) collection, rather than the + * forwarding collection. + * + * @param c the delegate (unwrapped) collection of map entries + * @param o the object that might be contained in {@code c} + * @return {@code true} if {@code c} contains {@code o} */ - static Entry transformEntry(final EntryTransformer transformer, - final Entry entry) { - checkNotNull(transformer); - checkNotNull(entry); - return new AbstractMapEntry() { - @Override - public K getKey() { - return entry.getKey(); - } - - @Override - public V2 getValue() { - return transformer.transformEntry(entry.getKey(), entry.getValue()); - } - }; + static boolean containsEntryImpl(Collection> c, Object o) { + if (!(o instanceof Entry)) { + return false; + } + return c.contains(unmodifiableEntry((Entry) o)); } /** - * Views an entry transformer as a function from entries to entries. + * An admittedly inefficient implementation of {@link Map#containsKey}. */ - static Function, Entry> asEntryToEntryFunction( - final EntryTransformer transformer) { - checkNotNull(transformer); - return new Function, Entry>() { - @Override - public Entry apply(final Entry entry) { - return transformEntry(transformer, entry); - } - }; - } - - static class TransformedEntriesMap extends ImprovedAbstractMap { - final Map fromMap; - final EntryTransformer transformer; - - TransformedEntriesMap(Map fromMap, EntryTransformer transformer) { - this.fromMap = checkNotNull(fromMap); - this.transformer = checkNotNull(transformer); - } - - @Override - public int size() { - return fromMap.size(); - } - - @Override - public boolean containsKey(Object key) { - return fromMap.containsKey(key); - } - - // safe as long as the user followed the Warning in the javadoc - @SuppressWarnings("unchecked") - @Override - public V2 get(Object key) { - V1 value = fromMap.get(key); - return (value != null || fromMap.containsKey(key)) ? transformer.transformEntry((K) key, value) : null; - } - - // safe as long as the user followed the Warning in the javadoc - @SuppressWarnings("unchecked") - @Override - public V2 remove(Object key) { - return fromMap.containsKey(key) ? transformer.transformEntry((K) key, fromMap.remove(key)) : null; - } - - @Override - public void clear() { - fromMap.clear(); - } - - @Override - public Set keySet() { - return fromMap.keySet(); - } - - @Override - protected Set> createEntrySet() { - return new EntrySet() { - @Override - Map map() { - return TransformedEntriesMap.this; - } - - @Override - public Iterator> iterator() { - return Iterators.transform(fromMap.entrySet().iterator(), - Maps.asEntryToEntryFunction(transformer)); - } - }; - } - } - - static class TransformedEntriesSortedMap extends TransformedEntriesMap - implements SortedMap { - - protected SortedMap fromMap() { - return (SortedMap) fromMap; - } - - TransformedEntriesSortedMap(SortedMap fromMap, EntryTransformer transformer) { - super(fromMap, transformer); - } - - @Override - public Comparator comparator() { - return fromMap().comparator(); - } - - @Override - public K firstKey() { - return fromMap().firstKey(); - } - - @Override - public SortedMap headMap(K toKey) { - return transformEntries(fromMap().headMap(toKey), transformer); - } - - @Override - public K lastKey() { - return fromMap().lastKey(); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return transformEntries(fromMap().subMap(fromKey, toKey), transformer); - } - - @Override - public SortedMap tailMap(K fromKey) { - return transformEntries(fromMap().tailMap(fromKey), transformer); - } - } - - @GwtIncompatible("NavigableMap") - private static class TransformedEntriesNavigableMap extends TransformedEntriesSortedMap - implements NavigableMap { - - TransformedEntriesNavigableMap(NavigableMap fromMap, - EntryTransformer transformer) { - super(fromMap, transformer); - } - - @Override - public Entry ceilingEntry(K key) { - return transformEntry(fromMap().ceilingEntry(key)); - } - - @Override - public K ceilingKey(K key) { - return fromMap().ceilingKey(key); - } - - @Override - public NavigableSet descendingKeySet() { - return fromMap().descendingKeySet(); - } - - @Override - public NavigableMap descendingMap() { - return transformEntries(fromMap().descendingMap(), transformer); - } - - @Override - public Entry firstEntry() { - return transformEntry(fromMap().firstEntry()); - } - - @Override - public Entry floorEntry(K key) { - return transformEntry(fromMap().floorEntry(key)); - } - - @Override - public K floorKey(K key) { - return fromMap().floorKey(key); - } - - @Override - public NavigableMap headMap(K toKey) { - return headMap(toKey, false); - } - - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - return transformEntries(fromMap().headMap(toKey, inclusive), transformer); - } - - @Override - public Entry higherEntry(K key) { - return transformEntry(fromMap().higherEntry(key)); - } - - @Override - public K higherKey(K key) { - return fromMap().higherKey(key); - } - - @Override - public Entry lastEntry() { - return transformEntry(fromMap().lastEntry()); - } - - @Override - public Entry lowerEntry(K key) { - return transformEntry(fromMap().lowerEntry(key)); - } - - @Override - public K lowerKey(K key) { - return fromMap().lowerKey(key); - } - - @Override - public NavigableSet navigableKeySet() { - return fromMap().navigableKeySet(); - } - - @Override - public Entry pollFirstEntry() { - return transformEntry(fromMap().pollFirstEntry()); - } - - @Override - public Entry pollLastEntry() { - return transformEntry(fromMap().pollLastEntry()); - } - - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - return transformEntries(fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer); - } - - @Override - public NavigableMap subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); - } - - @Override - public NavigableMap tailMap(K fromKey) { - return tailMap(fromKey, true); - } - - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer); - } - - @Nullable - private Entry transformEntry(@Nullable Entry entry) { - return (entry == null) ? null : Maps.transformEntry(transformer, entry); - } - - @Override - protected NavigableMap fromMap() { - return (NavigableMap) super.fromMap(); - } - } - - static Predicate> keyPredicateOnEntries(Predicate keyPredicate) { - return compose(keyPredicate, Maps.keyFunction()); - } - - static Predicate> valuePredicateOnEntries(Predicate valuePredicate) { - return compose(valuePredicate, Maps.valueFunction()); + static boolean containsKeyImpl(Map map, @Nullable Object key) { + return Iterators.contains(keyIterator(map.entrySet().iterator()), key); } /** - * Returns a map containing the mappings in {@code unfiltered} whose keys - * satisfy a predicate. The returned map is a live view of {@code unfiltered}; - * changes to one affect the other. - * - *

- * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code - * values()} views have iterators that don't support {@code remove()}, but all - * other methods are supported by the map and its views. When given a key that - * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} - * methods throw an {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered map or its views, only mappings whose keys satisfy the filter - * will be removed from the underlying map. - * - *

- * The returned map isn't threadsafe or serializable, even if {@code - * unfiltered} is. - * - *

- * Many of the filtered map's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying map and determine which satisfy the - * filter. When a live view is not needed, it may be faster to copy the - * filtered map and use the copy. - * - *

- * Warning: {@code keyPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. + * An implementation of {@link Map#containsValue}. */ - public static Map filterKeys(Map unfiltered, final Predicate keyPredicate) { - if (unfiltered instanceof SortedMap) { - return filterKeys((SortedMap) unfiltered, keyPredicate); - } else if (unfiltered instanceof BiMap) { - return filterKeys((BiMap) unfiltered, keyPredicate); - } - checkNotNull(keyPredicate); - Predicate> entryPredicate = keyPredicateOnEntries(keyPredicate); - return (unfiltered instanceof AbstractFilteredMap) - ? filterFiltered((AbstractFilteredMap) unfiltered, entryPredicate) - : new FilteredKeyMap(checkNotNull(unfiltered), keyPredicate, entryPredicate); + static boolean containsValueImpl(Map map, @Nullable Object value) { + return Iterators.contains(valueIterator(map.entrySet().iterator()), value); } /** - * Returns a sorted map containing the mappings in {@code unfiltered} whose keys - * satisfy a predicate. The returned map is a live view of {@code - * unfiltered}; changes to one affect the other. + * Computes the difference between two maps. This difference is an immutable + * snapshot of the state of the maps at the time this method is called. It will + * never change, even if the maps change at a later time. * *

- * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code - * values()} views have iterators that don't support {@code remove()}, but all - * other methods are supported by the map and its views. When given a key that - * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} - * methods throw an {@link IllegalArgumentException}. + * Since this method uses {@code HashMap} instances internally, the keys of the + * supplied maps must be well-behaved with respect to {@link Object#equals} and + * {@link Object#hashCode}. * *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered map or its views, only mappings whose keys satisfy the filter - * will be removed from the underlying map. + * Note:If you only need to know whether two maps have the same mappings, + * call {@code left.equals(right)} instead of this method. + * + * @param left the map to treat as the "left" map for purposes of comparison + * @param right the map to treat as the "right" map for purposes of comparison + * @return the difference between the two maps + */ + @SuppressWarnings("unchecked") + public static MapDifference difference(Map left, + Map right) { + if (left instanceof SortedMap) { + SortedMap sortedLeft = (SortedMap) left; + SortedMapDifference result = difference(sortedLeft, right); + return result; + } + return difference(left, right, Equivalence.equals()); + } + + /** + * Computes the difference between two maps. This difference is an immutable + * snapshot of the state of the maps at the time this method is called. It will + * never change, even if the maps change at a later time. * *

- * The returned map isn't threadsafe or serializable, even if {@code - * unfiltered} is. + * Values are compared using a provided equivalence, in the case of equality, + * the value on the 'left' is returned in the difference. * *

- * Many of the filtered map's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying map and determine which satisfy the - * filter. When a live view is not needed, it may be faster to copy the - * filtered map and use the copy. + * Since this method uses {@code HashMap} instances internally, the keys of the + * supplied maps must be well-behaved with respect to {@link Object#equals} and + * {@link Object#hashCode}. + * + * @param left the map to treat as the "left" map for purposes of + * comparison + * @param right the map to treat as the "right" map for purposes of + * comparison + * @param valueEquivalence the equivalence relationship to use to compare values + * @return the difference between the two maps + * @since 10.0 + */ + @Beta + public static MapDifference difference(Map left, + Map right, Equivalence valueEquivalence) { + Preconditions.checkNotNull(valueEquivalence); + + Map onlyOnLeft = newHashMap(); + Map onlyOnRight = new HashMap(right); // will whittle it down + Map onBoth = newHashMap(); + Map> differences = newHashMap(); + doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences); + return new MapDifferenceImpl(onlyOnLeft, onlyOnRight, onBoth, differences); + } + + /** + * Computes the difference between two sorted maps, using the comparator of the + * left map, or {@code Ordering.natural()} if the left map uses the natural + * ordering of its elements. This difference is an immutable snapshot of the + * state of the maps at the time this method is called. It will never change, + * even if the maps change at a later time. * *

- * Warning: {@code keyPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. + * Since this method uses {@code TreeMap} instances internally, the keys of the + * right map must all compare as distinct according to the comparator of the + * left map. * + *

+ * Note:If you only need to know whether two sorted maps have the same + * mappings, call {@code left.equals(right)} instead of this method. + * + * @param left the map to treat as the "left" map for purposes of comparison + * @param right the map to treat as the "right" map for purposes of comparison + * @return the difference between the two maps * @since 11.0 */ - public static SortedMap filterKeys(SortedMap unfiltered, - final Predicate keyPredicate) { - // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better - // performance. - return filterEntries(unfiltered, Maps.keyPredicateOnEntries(keyPredicate)); + public static SortedMapDifference difference(SortedMap left, + Map right) { + checkNotNull(left); + checkNotNull(right); + Comparator comparator = orNaturalOrder(left.comparator()); + SortedMap onlyOnLeft = Maps.newTreeMap(comparator); + SortedMap onlyOnRight = Maps.newTreeMap(comparator); + onlyOnRight.putAll(right); // will whittle it down + SortedMap onBoth = Maps.newTreeMap(comparator); + SortedMap> differences = Maps.newTreeMap(comparator); + doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences); + return new SortedMapDifferenceImpl(onlyOnLeft, onlyOnRight, onBoth, differences); + } + + private static void doDifference(Map left, Map right, + Equivalence valueEquivalence, Map onlyOnLeft, Map onlyOnRight, Map onBoth, + Map> differences) { + for (Entry entry : left.entrySet()) { + K leftKey = entry.getKey(); + V leftValue = entry.getValue(); + if (right.containsKey(leftKey)) { + V rightValue = onlyOnRight.remove(leftKey); + if (valueEquivalence.equivalent(leftValue, rightValue)) { + onBoth.put(leftKey, leftValue); + } else { + differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); + } + } else { + onlyOnLeft.put(leftKey, leftValue); + } + } } /** - * Returns a navigable map containing the mappings in {@code unfiltered} whose - * keys satisfy a predicate. The returned map is a live view of {@code - * unfiltered}; changes to one affect the other. - * - *

- * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code - * values()} views have iterators that don't support {@code remove()}, but all - * other methods are supported by the map and its views. When given a key that - * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} - * methods throw an {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered map or its views, only mappings whose keys satisfy the filter - * will be removed from the underlying map. - * - *

- * The returned map isn't threadsafe or serializable, even if {@code - * unfiltered} is. - * - *

- * Many of the filtered map's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying map and determine which satisfy the - * filter. When a live view is not needed, it may be faster to copy the - * filtered map and use the copy. - * - *

- * Warning: {@code keyPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 14.0 + * An implementation of {@link Map#equals}. */ - @GwtIncompatible("NavigableMap") - public static NavigableMap filterKeys(NavigableMap unfiltered, - final Predicate keyPredicate) { - // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better - // performance. - return filterEntries(unfiltered, Maps.keyPredicateOnEntries(keyPredicate)); + static boolean equalsImpl(Map map, Object object) { + if (map == object) { + return true; + } else if (object instanceof Map) { + Map o = (Map) object; + return map.entrySet().equals(o.entrySet()); + } + return false; } /** - * Returns a bimap containing the mappings in {@code unfiltered} whose keys - * satisfy a predicate. The returned bimap is a live view of {@code unfiltered}; - * changes to one affect the other. + * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a + * predicate. The returned bimap is a live view of {@code unfiltered}; changes + * to one affect the other. * *

* The resulting bimap's {@code keySet()}, {@code entrySet()}, and * {@code values()} views have iterators that don't support {@code remove()}, * but all other methods are supported by the bimap and its views. When given a - * key that doesn't satisfy the predicate, the bimap's {@code - * put()}, {@code forcePut()} and {@code putAll()} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered bimap or its views, only mappings that satisfy the filter will - * be removed from the underlying bimap. - * - *

- * The returned bimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered bimap's methods, such as {@code size()}, iterate across - * every key in the underlying bimap and determine which satisfy the filter. - * When a live view is not needed, it may be faster to copy the filtered - * bimap and use the copy. - * - *

- * Warning: {@code entryPredicate} must be consistent with equals - * , as documented at {@link Predicate#apply}. - * - * @since 14.0 - */ - public static BiMap filterKeys(BiMap unfiltered, final Predicate keyPredicate) { - checkNotNull(keyPredicate); - return filterEntries(unfiltered, Maps.keyPredicateOnEntries(keyPredicate)); - } - - /** - * Returns a map containing the mappings in {@code unfiltered} whose values - * satisfy a predicate. The returned map is a live view of {@code unfiltered}; - * changes to one affect the other. - * - *

- * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code - * values()} views have iterators that don't support {@code remove()}, but all - * other methods are supported by the map and its views. When given a value that - * doesn't satisfy the predicate, the map's {@code put()}, {@code - * putAll()}, and {@link Entry#setValue} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered map or its views, only mappings whose values satisfy the filter - * will be removed from the underlying map. - * - *

- * The returned map isn't threadsafe or serializable, even if {@code - * unfiltered} is. - * - *

- * Many of the filtered map's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying map and determine which satisfy the - * filter. When a live view is not needed, it may be faster to copy the - * filtered map and use the copy. - * - *

- * Warning: {@code valuePredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - */ - public static Map filterValues(Map unfiltered, final Predicate valuePredicate) { - if (unfiltered instanceof SortedMap) { - return filterValues((SortedMap) unfiltered, valuePredicate); - } else if (unfiltered instanceof BiMap) { - return filterValues((BiMap) unfiltered, valuePredicate); - } - return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); - } - - /** - * Returns a sorted map containing the mappings in {@code unfiltered} whose - * values satisfy a predicate. The returned map is a live view of {@code - * unfiltered}; changes to one affect the other. - * - *

- * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code - * values()} views have iterators that don't support {@code remove()}, but all - * other methods are supported by the map and its views. When given a value that - * doesn't satisfy the predicate, the map's {@code put()}, {@code - * putAll()}, and {@link Entry#setValue} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered map or its views, only mappings whose values satisfy the filter - * will be removed from the underlying map. - * - *

- * The returned map isn't threadsafe or serializable, even if {@code - * unfiltered} is. - * - *

- * Many of the filtered map's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying map and determine which satisfy the - * filter. When a live view is not needed, it may be faster to copy the - * filtered map and use the copy. - * - *

- * Warning: {@code valuePredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 11.0 - */ - public static SortedMap filterValues(SortedMap unfiltered, - final Predicate valuePredicate) { - return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); - } - - /** - * Returns a navigable map containing the mappings in {@code unfiltered} whose - * values satisfy a predicate. The returned map is a live view of {@code - * unfiltered}; changes to one affect the other. - * - *

- * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code - * values()} views have iterators that don't support {@code remove()}, but all - * other methods are supported by the map and its views. When given a value that - * doesn't satisfy the predicate, the map's {@code put()}, {@code - * putAll()}, and {@link Entry#setValue} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered map or its views, only mappings whose values satisfy the filter - * will be removed from the underlying map. - * - *

- * The returned map isn't threadsafe or serializable, even if {@code - * unfiltered} is. - * - *

- * Many of the filtered map's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying map and determine which satisfy the - * filter. When a live view is not needed, it may be faster to copy the - * filtered map and use the copy. - * - *

- * Warning: {@code valuePredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 14.0 - */ - @GwtIncompatible("NavigableMap") - public static NavigableMap filterValues(NavigableMap unfiltered, - final Predicate valuePredicate) { - return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); - } - - /** - * Returns a bimap containing the mappings in {@code unfiltered} whose values - * satisfy a predicate. The returned bimap is a live view of {@code unfiltered}; - * changes to one affect the other. - * - *

- * The resulting bimap's {@code keySet()}, {@code entrySet()}, and - * {@code values()} views have iterators that don't support {@code remove()}, - * but all other methods are supported by the bimap and its views. When given a - * value that doesn't satisfy the predicate, the bimap's {@code put()}, + * key/value pair that doesn't satisfy the predicate, the bimap's {@code put()}, * {@code forcePut()} and {@code putAll()} methods throw an - * {@link IllegalArgumentException}. Similarly, the map's entries have a + * {@link IllegalArgumentException}. Similarly, the map's entries have an * {@link Entry#setValue} method that throws an {@link IllegalArgumentException} - * when the provided value doesn't satisfy the predicate. + * when the existing key and the provided value don't satisfy the predicate. * *

* When methods such as {@code removeAll()} and {@code clear()} are called on @@ -2476,9 +2431,9 @@ public final class Maps { * *

* Many of the filtered bimap's methods, such as {@code size()}, iterate across - * every value in the underlying bimap and determine which satisfy the filter. - * When a live view is not needed, it may be faster to copy the filtered - * bimap and use the copy. + * every key/value mapping in the underlying bimap and determine which satisfy + * the filter. When a live view is not needed, it may be faster to copy + * the filtered bimap and use the copy. * *

* Warning: {@code entryPredicate} must be consistent with equals @@ -2486,8 +2441,13 @@ public final class Maps { * * @since 14.0 */ - public static BiMap filterValues(BiMap unfiltered, final Predicate valuePredicate) { - return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + public static BiMap filterEntries(BiMap unfiltered, + Predicate> entryPredicate) { + checkNotNull(unfiltered); + checkNotNull(entryPredicate); + return (unfiltered instanceof FilteredEntryBiMap) + ? filterFiltered((FilteredEntryBiMap) unfiltered, entryPredicate) + : new FilteredEntryBiMap(unfiltered, entryPredicate); } /** @@ -2570,19 +2530,15 @@ public final class Maps { * Warning: {@code entryPredicate} must be consistent with equals, * as documented at {@link Predicate#apply}. * - * @since 11.0 + * @since 14.0 */ - public static SortedMap filterEntries(SortedMap unfiltered, - Predicate> entryPredicate) { - return Platform.mapsFilterSortedMap(unfiltered, entryPredicate); - } - - static SortedMap filterSortedIgnoreNavigable(SortedMap unfiltered, + @GwtIncompatible("NavigableMap") + public static NavigableMap filterEntries(NavigableMap unfiltered, Predicate> entryPredicate) { checkNotNull(entryPredicate); - return (unfiltered instanceof FilteredEntrySortedMap) - ? filterFiltered((FilteredEntrySortedMap) unfiltered, entryPredicate) - : new FilteredEntrySortedMap(checkNotNull(unfiltered), entryPredicate); + return (unfiltered instanceof FilteredEntryNavigableMap) + ? filterFiltered((FilteredEntryNavigableMap) unfiltered, entryPredicate) + : new FilteredEntryNavigableMap(checkNotNull(unfiltered), entryPredicate); } /** @@ -2619,60 +2575,11 @@ public final class Maps { * Warning: {@code entryPredicate} must be consistent with equals, * as documented at {@link Predicate#apply}. * - * @since 14.0 + * @since 11.0 */ - @GwtIncompatible("NavigableMap") - public static NavigableMap filterEntries(NavigableMap unfiltered, + public static SortedMap filterEntries(SortedMap unfiltered, Predicate> entryPredicate) { - checkNotNull(entryPredicate); - return (unfiltered instanceof FilteredEntryNavigableMap) - ? filterFiltered((FilteredEntryNavigableMap) unfiltered, entryPredicate) - : new FilteredEntryNavigableMap(checkNotNull(unfiltered), entryPredicate); - } - - /** - * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a - * predicate. The returned bimap is a live view of {@code unfiltered}; changes - * to one affect the other. - * - *

- * The resulting bimap's {@code keySet()}, {@code entrySet()}, and - * {@code values()} views have iterators that don't support {@code remove()}, - * but all other methods are supported by the bimap and its views. When given a - * key/value pair that doesn't satisfy the predicate, the bimap's {@code put()}, - * {@code forcePut()} and {@code putAll()} methods throw an - * {@link IllegalArgumentException}. Similarly, the map's entries have an - * {@link Entry#setValue} method that throws an {@link IllegalArgumentException} - * when the existing key and the provided value don't satisfy the predicate. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered bimap or its views, only mappings that satisfy the filter will - * be removed from the underlying bimap. - * - *

- * The returned bimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered bimap's methods, such as {@code size()}, iterate across - * every key/value mapping in the underlying bimap and determine which satisfy - * the filter. When a live view is not needed, it may be faster to copy - * the filtered bimap and use the copy. - * - *

- * Warning: {@code entryPredicate} must be consistent with equals - * , as documented at {@link Predicate#apply}. - * - * @since 14.0 - */ - public static BiMap filterEntries(BiMap unfiltered, - Predicate> entryPredicate) { - checkNotNull(unfiltered); - checkNotNull(entryPredicate); - return (unfiltered instanceof FilteredEntryBiMap) - ? filterFiltered((FilteredEntryBiMap) unfiltered, entryPredicate) - : new FilteredEntryBiMap(unfiltered, entryPredicate); + return Platform.mapsFilterSortedMap(unfiltered, entryPredicate); } /** @@ -2684,327 +2591,14 @@ public final class Maps { return new FilteredEntryMap(map.unfiltered, Predicates.>and(map.predicate, entryPredicate)); } - private abstract static class AbstractFilteredMap extends ImprovedAbstractMap { - final Map unfiltered; - final Predicate> predicate; - - AbstractFilteredMap(Map unfiltered, Predicate> predicate) { - this.unfiltered = unfiltered; - this.predicate = predicate; - } - - boolean apply(@Nullable Object key, @Nullable V value) { - // This method is called only when the key is in the map, implying that - // key is a K. - @SuppressWarnings("unchecked") - K k = (K) key; - return predicate.apply(Maps.immutableEntry(k, value)); - } - - @Override - public V put(K key, V value) { - checkArgument(apply(key, value)); - return unfiltered.put(key, value); - } - - @Override - public void putAll(Map map) { - for (Entry entry : map.entrySet()) { - checkArgument(apply(entry.getKey(), entry.getValue())); - } - unfiltered.putAll(map); - } - - @Override - public boolean containsKey(Object key) { - return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); - } - - @Override - public V get(Object key) { - V value = unfiltered.get(key); - return ((value != null) && apply(key, value)) ? value : null; - } - - @Override - public boolean isEmpty() { - return entrySet().isEmpty(); - } - - @Override - public V remove(Object key) { - return containsKey(key) ? unfiltered.remove(key) : null; - } - - @Override - Collection createValues() { - return new FilteredMapValues(this, unfiltered, predicate); - } - } - - private static final class FilteredMapValues extends Maps.Values { - Map unfiltered; - Predicate> predicate; - - FilteredMapValues(Map filteredMap, Map unfiltered, Predicate> predicate) { - super(filteredMap); - this.unfiltered = unfiltered; - this.predicate = predicate; - } - - @Override - public boolean remove(Object o) { - return Iterables.removeFirstMatching(unfiltered.entrySet(), - Predicates.>and(predicate, Maps.valuePredicateOnEntries(equalTo(o)))) != null; - } - - private boolean removeIf(Predicate valuePredicate) { - return Iterables.removeIf(unfiltered.entrySet(), - Predicates.>and(predicate, Maps.valuePredicateOnEntries(valuePredicate))); - } - - @Override - public boolean removeAll(Collection collection) { - return removeIf(in(collection)); - } - - @Override - public boolean retainAll(Collection collection) { - return removeIf(not(in(collection))); - } - - @Override - public Object[] toArray() { - // creating an ArrayList so filtering happens once - return Lists.newArrayList(iterator()).toArray(); - } - - @Override - public T[] toArray(T[] array) { - return Lists.newArrayList(iterator()).toArray(array); - } - } - - private static class FilteredKeyMap extends AbstractFilteredMap { - Predicate keyPredicate; - - FilteredKeyMap(Map unfiltered, Predicate keyPredicate, - Predicate> entryPredicate) { - super(unfiltered, entryPredicate); - this.keyPredicate = keyPredicate; - } - - @Override - protected Set> createEntrySet() { - return Sets.filter(unfiltered.entrySet(), predicate); - } - - @Override - Set createKeySet() { - return Sets.filter(unfiltered.keySet(), keyPredicate); - } - - // The cast is called only when the key is in the unfiltered map, implying - // that key is a K. - @Override - @SuppressWarnings("unchecked") - public boolean containsKey(Object key) { - return unfiltered.containsKey(key) && keyPredicate.apply((K) key); - } - } - - static class FilteredEntryMap extends AbstractFilteredMap { - /** - * Entries in this set satisfy the predicate, but they don't validate the input - * to {@code Entry.setValue()}. - */ - final Set> filteredEntrySet; - - FilteredEntryMap(Map unfiltered, Predicate> entryPredicate) { - super(unfiltered, entryPredicate); - filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); - } - - @Override - protected Set> createEntrySet() { - return new EntrySet(); - } - - private class EntrySet extends ForwardingSet> { - @Override - protected Set> delegate() { - return filteredEntrySet; - } - - @Override - public Iterator> iterator() { - return new TransformedIterator, Entry>(filteredEntrySet.iterator()) { - @Override - Entry transform(final Entry entry) { - return new ForwardingMapEntry() { - @Override - protected Entry delegate() { - return entry; - } - - @Override - public V setValue(V newValue) { - checkArgument(apply(getKey(), newValue)); - return super.setValue(newValue); - } - }; - } - }; - } - } - - @Override - Set createKeySet() { - return new KeySet(); - } - - class KeySet extends Maps.KeySet { - KeySet() { - super(FilteredEntryMap.this); - } - - @Override - public boolean remove(Object o) { - if (containsKey(o)) { - unfiltered.remove(o); - return true; - } - return false; - } - - private boolean removeIf(Predicate keyPredicate) { - return Iterables.removeIf(unfiltered.entrySet(), - Predicates.>and(predicate, Maps.keyPredicateOnEntries(keyPredicate))); - } - - @Override - public boolean removeAll(Collection c) { - return removeIf(in(c)); - } - - @Override - public boolean retainAll(Collection c) { - return removeIf(not(in(c))); - } - - @Override - public Object[] toArray() { - // creating an ArrayList so filtering happens once - return Lists.newArrayList(iterator()).toArray(); - } - - @Override - public T[] toArray(T[] array) { - return Lists.newArrayList(iterator()).toArray(array); - } - } - } - /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when - * filtering a filtered sorted map. + * filtering a filtered map. */ - private static SortedMap filterFiltered(FilteredEntrySortedMap map, + private static BiMap filterFiltered(FilteredEntryBiMap map, Predicate> entryPredicate) { Predicate> predicate = Predicates.and(map.predicate, entryPredicate); - return new FilteredEntrySortedMap(map.sortedMap(), predicate); - } - - private static class FilteredEntrySortedMap extends FilteredEntryMap implements SortedMap { - - FilteredEntrySortedMap(SortedMap unfiltered, Predicate> entryPredicate) { - super(unfiltered, entryPredicate); - } - - SortedMap sortedMap() { - return (SortedMap) unfiltered; - } - - @Override - public SortedSet keySet() { - return (SortedSet) super.keySet(); - } - - @Override - SortedSet createKeySet() { - return new SortedKeySet(); - } - - class SortedKeySet extends KeySet implements SortedSet { - @Override - public Comparator comparator() { - return sortedMap().comparator(); - } - - @Override - public SortedSet subSet(K fromElement, K toElement) { - return (SortedSet) subMap(fromElement, toElement).keySet(); - } - - @Override - public SortedSet headSet(K toElement) { - return (SortedSet) headMap(toElement).keySet(); - } - - @Override - public SortedSet tailSet(K fromElement) { - return (SortedSet) tailMap(fromElement).keySet(); - } - - @Override - public K first() { - return firstKey(); - } - - @Override - public K last() { - return lastKey(); - } - } - - @Override - public Comparator comparator() { - return sortedMap().comparator(); - } - - @Override - public K firstKey() { - // correctly throws NoSuchElementException when filtered map is empty. - return keySet().iterator().next(); - } - - @Override - public K lastKey() { - SortedMap headMap = sortedMap(); - while (true) { - // correctly throws NoSuchElementException when filtered map is empty. - K key = headMap.lastKey(); - if (apply(key, unfiltered.get(key))) { - return key; - } - headMap = sortedMap().headMap(key); - } - } - - @Override - public SortedMap headMap(K toKey) { - return new FilteredEntrySortedMap(sortedMap().headMap(toKey), predicate); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return new FilteredEntrySortedMap(sortedMap().subMap(fromKey, toKey), predicate); - } - - @Override - public SortedMap tailMap(K fromKey) { - return new FilteredEntrySortedMap(sortedMap().tailMap(fromKey), predicate); - } + return new FilteredEntryBiMap(map.unfiltered(), predicate); } /** @@ -3018,349 +2612,849 @@ public final class Maps { return new FilteredEntryNavigableMap(map.unfiltered, predicate); } - @GwtIncompatible("NavigableMap") - private static class FilteredEntryNavigableMap extends AbstractNavigableMap { - /* - * It's less code to extend AbstractNavigableMap and forward the filtering logic - * to FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all - * the NavigableMap methods. - */ - - private final NavigableMap unfiltered; - private final Predicate> entryPredicate; - private final Map filteredDelegate; - - FilteredEntryNavigableMap(NavigableMap unfiltered, Predicate> entryPredicate) { - this.unfiltered = checkNotNull(unfiltered); - this.entryPredicate = entryPredicate; - this.filteredDelegate = new FilteredEntryMap(unfiltered, entryPredicate); - } - - @Override - public Comparator comparator() { - return unfiltered.comparator(); - } - - @Override - public NavigableSet navigableKeySet() { - return new Maps.NavigableKeySet(this) { - @Override - public boolean removeAll(Collection c) { - return Iterators.removeIf(unfiltered.entrySet().iterator(), - Predicates.>and(entryPredicate, Maps.keyPredicateOnEntries(in(c)))); - } - - @Override - public boolean retainAll(Collection c) { - return Iterators.removeIf(unfiltered.entrySet().iterator(), - Predicates.>and(entryPredicate, Maps.keyPredicateOnEntries(not(in(c))))); - } - }; - } - - @Override - public Collection values() { - return new FilteredMapValues(this, unfiltered, entryPredicate); - } - - @Override - Iterator> entryIterator() { - return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate); - } - - @Override - Iterator> descendingEntryIterator() { - return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate); - } - - @Override - public int size() { - return filteredDelegate.size(); - } - - @Override - @Nullable - public V get(@Nullable Object key) { - return filteredDelegate.get(key); - } - - @Override - public boolean containsKey(@Nullable Object key) { - return filteredDelegate.containsKey(key); - } - - @Override - public V put(K key, V value) { - return filteredDelegate.put(key, value); - } - - @Override - public V remove(@Nullable Object key) { - return filteredDelegate.remove(key); - } - - @Override - public void putAll(Map m) { - filteredDelegate.putAll(m); - } - - @Override - public void clear() { - filteredDelegate.clear(); - } - - @Override - public Set> entrySet() { - return filteredDelegate.entrySet(); - } - - @Override - public Entry pollFirstEntry() { - return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate); - } - - @Override - public Entry pollLastEntry() { - return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate); - } - - @Override - public NavigableMap descendingMap() { - return filterEntries(unfiltered.descendingMap(), entryPredicate); - } - - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - return filterEntries(unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate); - } - - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate); - } - - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate); - } - } - /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when - * filtering a filtered map. + * filtering a filtered sorted map. */ - private static BiMap filterFiltered(FilteredEntryBiMap map, + private static SortedMap filterFiltered(FilteredEntrySortedMap map, Predicate> entryPredicate) { Predicate> predicate = Predicates.and(map.predicate, entryPredicate); - return new FilteredEntryBiMap(map.unfiltered(), predicate); - } - - static final class FilteredEntryBiMap extends FilteredEntryMap implements BiMap { - private final BiMap inverse; - - private static Predicate> inversePredicate( - final Predicate> forwardPredicate) { - return new Predicate>() { - @Override - public boolean apply(Entry input) { - return forwardPredicate.apply(Maps.immutableEntry(input.getValue(), input.getKey())); - } - }; - } - - FilteredEntryBiMap(BiMap delegate, Predicate> predicate) { - super(delegate, predicate); - this.inverse = new FilteredEntryBiMap(delegate.inverse(), inversePredicate(predicate), this); - } - - private FilteredEntryBiMap(BiMap delegate, Predicate> predicate, - BiMap inverse) { - super(delegate, predicate); - this.inverse = inverse; - } - - BiMap unfiltered() { - return (BiMap) unfiltered; - } - - @Override - public V forcePut(@Nullable K key, @Nullable V value) { - checkArgument(apply(key, value)); - return unfiltered().forcePut(key, value); - } - - @Override - public BiMap inverse() { - return inverse; - } - - @Override - public Set values() { - return inverse.keySet(); - } + return new FilteredEntrySortedMap(map.sortedMap(), predicate); } /** - * Returns an unmodifiable view of the specified navigable map. Query operations - * on the returned map read through to the specified map, and attempts to modify - * the returned map, whether direct or via its views, result in an - * {@code UnsupportedOperationException}. + * Returns a bimap containing the mappings in {@code unfiltered} whose keys + * satisfy a predicate. The returned bimap is a live view of {@code unfiltered}; + * changes to one affect the other. * *

- * The returned navigable map will be serializable if the specified navigable - * map is serializable. + * The resulting bimap's {@code keySet()}, {@code entrySet()}, and + * {@code values()} views have iterators that don't support {@code remove()}, + * but all other methods are supported by the bimap and its views. When given a + * key that doesn't satisfy the predicate, the bimap's {@code + * put()}, {@code forcePut()} and {@code putAll()} methods throw an + * {@link IllegalArgumentException}. * - * @param map the navigable map for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified navigable map - * @since 12.0 + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered bimap or its views, only mappings that satisfy the filter will + * be removed from the underlying bimap. + * + *

+ * The returned bimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered bimap's methods, such as {@code size()}, iterate across + * every key in the underlying bimap and determine which satisfy the filter. + * When a live view is not needed, it may be faster to copy the filtered + * bimap and use the copy. + * + *

+ * Warning: {@code entryPredicate} must be consistent with equals + * , as documented at {@link Predicate#apply}. + * + * @since 14.0 + */ + public static BiMap filterKeys(BiMap unfiltered, final Predicate keyPredicate) { + checkNotNull(keyPredicate); + return filterEntries(unfiltered, Maps.keyPredicateOnEntries(keyPredicate)); + } + + /** + * Returns a map containing the mappings in {@code unfiltered} whose keys + * satisfy a predicate. The returned map is a live view of {@code unfiltered}; + * changes to one affect the other. + * + *

+ * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code + * values()} views have iterators that don't support {@code remove()}, but all + * other methods are supported by the map and its views. When given a key that + * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} + * methods throw an {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered map or its views, only mappings whose keys satisfy the filter + * will be removed from the underlying map. + * + *

+ * The returned map isn't threadsafe or serializable, even if {@code + * unfiltered} is. + * + *

+ * Many of the filtered map's methods, such as {@code size()}, iterate across + * every key/value mapping in the underlying map and determine which satisfy the + * filter. When a live view is not needed, it may be faster to copy the + * filtered map and use the copy. + * + *

+ * Warning: {@code keyPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + */ + public static Map filterKeys(Map unfiltered, final Predicate keyPredicate) { + if (unfiltered instanceof SortedMap) { + return filterKeys((SortedMap) unfiltered, keyPredicate); + } else if (unfiltered instanceof BiMap) { + return filterKeys((BiMap) unfiltered, keyPredicate); + } + checkNotNull(keyPredicate); + Predicate> entryPredicate = keyPredicateOnEntries(keyPredicate); + return (unfiltered instanceof AbstractFilteredMap) + ? filterFiltered((AbstractFilteredMap) unfiltered, entryPredicate) + : new FilteredKeyMap(checkNotNull(unfiltered), keyPredicate, entryPredicate); + } + + /** + * Returns a navigable map containing the mappings in {@code unfiltered} whose + * keys satisfy a predicate. The returned map is a live view of {@code + * unfiltered}; changes to one affect the other. + * + *

+ * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code + * values()} views have iterators that don't support {@code remove()}, but all + * other methods are supported by the map and its views. When given a key that + * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} + * methods throw an {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered map or its views, only mappings whose keys satisfy the filter + * will be removed from the underlying map. + * + *

+ * The returned map isn't threadsafe or serializable, even if {@code + * unfiltered} is. + * + *

+ * Many of the filtered map's methods, such as {@code size()}, iterate across + * every key/value mapping in the underlying map and determine which satisfy the + * filter. When a live view is not needed, it may be faster to copy the + * filtered map and use the copy. + * + *

+ * Warning: {@code keyPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 14.0 */ @GwtIncompatible("NavigableMap") - public static NavigableMap unmodifiableNavigableMap(NavigableMap map) { - checkNotNull(map); - if (map instanceof UnmodifiableNavigableMap) { - return map; - } else { - return new UnmodifiableNavigableMap(map); + public static NavigableMap filterKeys(NavigableMap unfiltered, + final Predicate keyPredicate) { + // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better + // performance. + return filterEntries(unfiltered, Maps.keyPredicateOnEntries(keyPredicate)); + } + + /** + * Returns a sorted map containing the mappings in {@code unfiltered} whose keys + * satisfy a predicate. The returned map is a live view of {@code + * unfiltered}; changes to one affect the other. + * + *

+ * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code + * values()} views have iterators that don't support {@code remove()}, but all + * other methods are supported by the map and its views. When given a key that + * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} + * methods throw an {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered map or its views, only mappings whose keys satisfy the filter + * will be removed from the underlying map. + * + *

+ * The returned map isn't threadsafe or serializable, even if {@code + * unfiltered} is. + * + *

+ * Many of the filtered map's methods, such as {@code size()}, iterate across + * every key/value mapping in the underlying map and determine which satisfy the + * filter. When a live view is not needed, it may be faster to copy the + * filtered map and use the copy. + * + *

+ * Warning: {@code keyPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 11.0 + */ + public static SortedMap filterKeys(SortedMap unfiltered, + final Predicate keyPredicate) { + // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better + // performance. + return filterEntries(unfiltered, Maps.keyPredicateOnEntries(keyPredicate)); + } + + static SortedMap filterSortedIgnoreNavigable(SortedMap unfiltered, + Predicate> entryPredicate) { + checkNotNull(entryPredicate); + return (unfiltered instanceof FilteredEntrySortedMap) + ? filterFiltered((FilteredEntrySortedMap) unfiltered, entryPredicate) + : new FilteredEntrySortedMap(checkNotNull(unfiltered), entryPredicate); + } + + /** + * Returns a bimap containing the mappings in {@code unfiltered} whose values + * satisfy a predicate. The returned bimap is a live view of {@code unfiltered}; + * changes to one affect the other. + * + *

+ * The resulting bimap's {@code keySet()}, {@code entrySet()}, and + * {@code values()} views have iterators that don't support {@code remove()}, + * but all other methods are supported by the bimap and its views. When given a + * value that doesn't satisfy the predicate, the bimap's {@code put()}, + * {@code forcePut()} and {@code putAll()} methods throw an + * {@link IllegalArgumentException}. Similarly, the map's entries have a + * {@link Entry#setValue} method that throws an {@link IllegalArgumentException} + * when the provided value doesn't satisfy the predicate. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered bimap or its views, only mappings that satisfy the filter will + * be removed from the underlying bimap. + * + *

+ * The returned bimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered bimap's methods, such as {@code size()}, iterate across + * every value in the underlying bimap and determine which satisfy the filter. + * When a live view is not needed, it may be faster to copy the filtered + * bimap and use the copy. + * + *

+ * Warning: {@code entryPredicate} must be consistent with equals + * , as documented at {@link Predicate#apply}. + * + * @since 14.0 + */ + public static BiMap filterValues(BiMap unfiltered, final Predicate valuePredicate) { + return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + } + + /** + * Returns a map containing the mappings in {@code unfiltered} whose values + * satisfy a predicate. The returned map is a live view of {@code unfiltered}; + * changes to one affect the other. + * + *

+ * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code + * values()} views have iterators that don't support {@code remove()}, but all + * other methods are supported by the map and its views. When given a value that + * doesn't satisfy the predicate, the map's {@code put()}, {@code + * putAll()}, and {@link Entry#setValue} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered map or its views, only mappings whose values satisfy the filter + * will be removed from the underlying map. + * + *

+ * The returned map isn't threadsafe or serializable, even if {@code + * unfiltered} is. + * + *

+ * Many of the filtered map's methods, such as {@code size()}, iterate across + * every key/value mapping in the underlying map and determine which satisfy the + * filter. When a live view is not needed, it may be faster to copy the + * filtered map and use the copy. + * + *

+ * Warning: {@code valuePredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + */ + public static Map filterValues(Map unfiltered, final Predicate valuePredicate) { + if (unfiltered instanceof SortedMap) { + return filterValues((SortedMap) unfiltered, valuePredicate); + } else if (unfiltered instanceof BiMap) { + return filterValues((BiMap) unfiltered, valuePredicate); } + return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + } + + /** + * Returns a navigable map containing the mappings in {@code unfiltered} whose + * values satisfy a predicate. The returned map is a live view of {@code + * unfiltered}; changes to one affect the other. + * + *

+ * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code + * values()} views have iterators that don't support {@code remove()}, but all + * other methods are supported by the map and its views. When given a value that + * doesn't satisfy the predicate, the map's {@code put()}, {@code + * putAll()}, and {@link Entry#setValue} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered map or its views, only mappings whose values satisfy the filter + * will be removed from the underlying map. + * + *

+ * The returned map isn't threadsafe or serializable, even if {@code + * unfiltered} is. + * + *

+ * Many of the filtered map's methods, such as {@code size()}, iterate across + * every key/value mapping in the underlying map and determine which satisfy the + * filter. When a live view is not needed, it may be faster to copy the + * filtered map and use the copy. + * + *

+ * Warning: {@code valuePredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 14.0 + */ + @GwtIncompatible("NavigableMap") + public static NavigableMap filterValues(NavigableMap unfiltered, + final Predicate valuePredicate) { + return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + } + + /** + * Returns a sorted map containing the mappings in {@code unfiltered} whose + * values satisfy a predicate. The returned map is a live view of {@code + * unfiltered}; changes to one affect the other. + * + *

+ * The resulting map's {@code keySet()}, {@code entrySet()}, and {@code + * values()} views have iterators that don't support {@code remove()}, but all + * other methods are supported by the map and its views. When given a value that + * doesn't satisfy the predicate, the map's {@code put()}, {@code + * putAll()}, and {@link Entry#setValue} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered map or its views, only mappings whose values satisfy the filter + * will be removed from the underlying map. + * + *

+ * The returned map isn't threadsafe or serializable, even if {@code + * unfiltered} is. + * + *

+ * Many of the filtered map's methods, such as {@code size()}, iterate across + * every key/value mapping in the underlying map and determine which satisfy the + * filter. When a live view is not needed, it may be faster to copy the + * filtered map and use the copy. + * + *

+ * Warning: {@code valuePredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 11.0 + */ + public static SortedMap filterValues(SortedMap unfiltered, + final Predicate valuePredicate) { + return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + } + + /** + * Creates an {@code ImmutableMap} from a {@code Properties} + * instance. Properties normally derive from {@code Map}, but + * they typically contain strings, which is awkward. This method lets you get a + * plain-old-{@code Map} out of a {@code Properties}. + * + * @param properties a {@code Properties} object to be converted + * @return an immutable map containing all the entries in {@code properties} + * @throws ClassCastException if any key in {@code Properties} is not a {@code + * String} + * @throws NullPointerException if any key or value in {@code Properties} is + * null + */ + @GwtIncompatible("java.util.Properties") + public static ImmutableMap fromProperties(Properties properties) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + + for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { + String key = (String) e.nextElement(); + builder.put(key, properties.getProperty(key)); + } + + return builder.build(); + } + + /** + * Returns an immutable map entry with the specified key and value. The + * {@link Entry#setValue} operation throws an + * {@link UnsupportedOperationException}. + * + *

+ * The returned entry is serializable. + * + * @param key the key to be associated with the returned entry + * @param value the value to be associated with the returned entry + */ + @GwtCompatible(serializable = true) + public static Entry immutableEntry(@Nullable K key, @Nullable V value) { + return new ImmutableEntry(key, value); + } + + /** + * Returns an immutable map instance containing the given entries. Internally, + * the returned map will be backed by an {@link EnumMap}. + * + *

+ * The iteration order of the returned map follows the enum's iteration order, + * not the order in which the elements appear in the given map. + * + * @param map the map to make an immutable copy of + * @return an immutable map containing those entries + * @since 14.0 + */ + @GwtCompatible(serializable = true) + @Beta + public static , V> ImmutableMap immutableEnumMap(Map map) { + if (map instanceof ImmutableEnumMap) { + @SuppressWarnings("unchecked") // safe covariant cast + ImmutableEnumMap result = (ImmutableEnumMap) map; + return result; + } else if (map.isEmpty()) { + return ImmutableMap.of(); + } else { + for (Map.Entry entry : map.entrySet()) { + checkNotNull(entry.getKey()); + checkNotNull(entry.getValue()); + } + return ImmutableEnumMap.asImmutable(new EnumMap(map)); + } + } + + @SuppressWarnings("unchecked") + static Function, K> keyFunction() { + return (Function) EntryFunction.KEY; + } + + static Iterator keyIterator(Iterator> entryIterator) { + return Iterators.transform(entryIterator, Maps.keyFunction()); } @Nullable - private static Entry unmodifiableOrNull(@Nullable Entry entry) { - return (entry == null) ? null : Maps.unmodifiableEntry(entry); + static K keyOrNull(@Nullable Entry entry) { + return (entry == null) ? null : entry.getKey(); } - @GwtIncompatible("NavigableMap") - static class UnmodifiableNavigableMap extends ForwardingSortedMap - implements NavigableMap, Serializable { - private final NavigableMap delegate; + static Predicate> keyPredicateOnEntries(Predicate keyPredicate) { + return compose(keyPredicate, Maps.keyFunction()); + } - UnmodifiableNavigableMap(NavigableMap delegate) { - this.delegate = delegate; + /** + * Creates an {@code EnumMap} instance. + * + * @param type the key type for this map + * @return a new, empty {@code EnumMap} + */ + public static , V> EnumMap newEnumMap(Class type) { + return new EnumMap(checkNotNull(type)); + } + + /** + * Creates an {@code EnumMap} with the same mappings as the specified map. + * + * @param map the map from which to initialize this {@code EnumMap} + * @return a new {@code EnumMap} initialized with the mappings from {@code + * map} + * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} + * instance and contains no mappings + */ + public static , V> EnumMap newEnumMap(Map map) { + return new EnumMap(map); + } + + /** + * Creates a mutable, empty {@code HashMap} instance. + * + *

+ * Note: if mutability is not required, use {@link ImmutableMap#of()} + * instead. + * + *

+ * Note: if {@code K} is an {@code enum} type, use {@link #newEnumMap} + * instead. + * + * @return a new, empty {@code HashMap} + */ + public static HashMap newHashMap() { + return new HashMap(); + } + + /** + * Creates a mutable {@code HashMap} instance with the same mappings as + * the specified map. + * + *

+ * Note: if mutability is not required, use + * {@link ImmutableMap#copyOf(Map)} instead. + * + *

+ * Note: if {@code K} is an {@link Enum} type, use {@link #newEnumMap} + * instead. + * + * @param map the mappings to be placed in the new map + * @return a new {@code HashMap} initialized with the mappings from {@code + * map} + */ + public static HashMap newHashMap(Map map) { + return new HashMap(map); + } + + /** + * Creates a {@code HashMap} instance, with a high enough "initial capacity" + * that it should hold {@code expectedSize} elements without growth. This + * behavior cannot be broadly guaranteed, but it is observed to be true for + * OpenJDK 1.6. It also can't be guaranteed that the method isn't inadvertently + * oversizing the returned map. + * + * @param expectedSize the number of elements you expect to add to the returned + * map + * @return a new, empty {@code HashMap} with enough capacity to hold {@code + * expectedSize} elements without resizing + * @throws IllegalArgumentException if {@code expectedSize} is negative + */ + public static HashMap newHashMapWithExpectedSize(int expectedSize) { + return new HashMap(capacity(expectedSize)); + } + + /** + * Creates an {@code IdentityHashMap} instance. + * + * @return a new, empty {@code IdentityHashMap} + */ + public static IdentityHashMap newIdentityHashMap() { + return new IdentityHashMap(); + } + + /** + * Creates a mutable, empty, insertion-ordered {@code LinkedHashMap} + * instance. + * + *

+ * Note: if mutability is not required, use {@link ImmutableMap#of()} + * instead. + * + * @return a new, empty {@code LinkedHashMap} + */ + public static LinkedHashMap newLinkedHashMap() { + return new LinkedHashMap(); + } + + /** + * Creates a mutable, insertion-ordered {@code LinkedHashMap} instance + * with the same mappings as the specified map. + * + *

+ * Note: if mutability is not required, use + * {@link ImmutableMap#copyOf(Map)} instead. + * + * @param map the mappings to be placed in the new map + * @return a new, {@code LinkedHashMap} initialized with the mappings from + * {@code map} + */ + public static LinkedHashMap newLinkedHashMap(Map map) { + return new LinkedHashMap(map); + } + + /** + * Creates a mutable, empty {@code TreeMap} instance using the natural + * ordering of its elements. + * + *

+ * Note: if mutability is not required, use + * {@link ImmutableSortedMap#of()} instead. + * + * @return a new, empty {@code TreeMap} + */ + public static TreeMap newTreeMap() { + return new TreeMap(); + } + + /** + * Creates a mutable, empty {@code TreeMap} instance using the given + * comparator. + * + *

+ * Note: if mutability is not required, use {@code + * ImmutableSortedMap.orderedBy(comparator).build()} instead. + * + * @param comparator the comparator to sort the keys with + * @return a new, empty {@code TreeMap} + */ + public static TreeMap newTreeMap(@Nullable Comparator comparator) { + // Ideally, the extra type parameter "C" shouldn't be necessary. It is a + // work-around of a compiler type inference quirk that prevents the + // following code from being compiled: + // Comparator> comparator = null; + // Map, String> map = newTreeMap(comparator); + return new TreeMap(comparator); + } + + /** + * Creates a mutable {@code TreeMap} instance with the same mappings as + * the specified map and using the same ordering as the specified map. + * + *

+ * Note: if mutability is not required, use + * {@link ImmutableSortedMap#copyOfSorted(SortedMap)} instead. + * + * @param map the sorted map whose mappings are to be placed in the new map and + * whose comparator is to be used to sort the new map + * @return a new {@code TreeMap} initialized with the mappings from {@code + * map} and using the comparator of {@code map} + */ + public static TreeMap newTreeMap(SortedMap map) { + return new TreeMap(map); + } + + /** + * Returns the specified comparator if not null; otherwise returns {@code + * Ordering.natural()}. This method is an abomination of generics; the only + * purpose of this method is to contain the ugly type-casting in one place. + */ + @SuppressWarnings("unchecked") + static Comparator orNaturalOrder(@Nullable Comparator comparator) { + if (comparator != null) { // can't use ? : because of javac bug 5080917 + return comparator; } + return (Comparator) Ordering.natural(); + } - UnmodifiableNavigableMap(NavigableMap delegate, UnmodifiableNavigableMap descendingMap) { - this.delegate = delegate; - this.descendingMap = descendingMap; + /** + * An implementation of {@link Map#putAll}. + */ + static void putAllImpl(Map self, Map map) { + for (Map.Entry entry : map.entrySet()) { + self.put(entry.getKey(), entry.getValue()); } + } - @Override - protected SortedMap delegate() { - return Collections.unmodifiableSortedMap(delegate); + /** + * Implements {@code Collection.remove} safely for forwarding collections of map + * entries. If {@code o} is an instance of {@code Map.Entry}, it is wrapped + * using {@link #unmodifiableEntry} to protect against a possible nefarious + * equals method. + * + *

+ * Note that {@code c} is backing (delegate) collection, rather than the + * forwarding collection. + * + * @param c the delegate (unwrapped) collection of map entries + * @param o the object to remove from {@code c} + * @return {@code true} if {@code c} was changed + */ + static boolean removeEntryImpl(Collection> c, Object o) { + if (!(o instanceof Entry)) { + return false; } + return c.remove(unmodifiableEntry((Entry) o)); + } - @Override - public Entry lowerEntry(K key) { - return unmodifiableOrNull(delegate.lowerEntry(key)); + @GwtIncompatible("NavigableSet") + private static NavigableSet removeOnlyNavigableSet(final NavigableSet set) { + return new ForwardingNavigableSet() { + @Override + public boolean add(E element) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(Collection es) { + throw new UnsupportedOperationException(); + } + + @Override + protected NavigableSet delegate() { + return set; + } + + @Override + public NavigableSet descendingSet() { + return removeOnlyNavigableSet(super.descendingSet()); + } + + @Override + public SortedSet headSet(E toElement) { + return removeOnlySortedSet(super.headSet(toElement)); + } + + @Override + public NavigableSet headSet(E toElement, boolean inclusive) { + return removeOnlyNavigableSet(super.headSet(toElement, inclusive)); + } + + @Override + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return removeOnlyNavigableSet(super.subSet(fromElement, fromInclusive, toElement, toInclusive)); + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return removeOnlySortedSet(super.subSet(fromElement, toElement)); + } + + @Override + public SortedSet tailSet(E fromElement) { + return removeOnlySortedSet(super.tailSet(fromElement)); + } + + @Override + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive)); + } + }; + } + + private static Set removeOnlySet(final Set set) { + return new ForwardingSet() { + @Override + public boolean add(E element) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(Collection es) { + throw new UnsupportedOperationException(); + } + + @Override + protected Set delegate() { + return set; + } + }; + } + + private static SortedSet removeOnlySortedSet(final SortedSet set) { + return new ForwardingSortedSet() { + @Override + public boolean add(E element) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(Collection es) { + throw new UnsupportedOperationException(); + } + + @Override + protected SortedSet delegate() { + return set; + } + + @Override + public SortedSet headSet(E toElement) { + return removeOnlySortedSet(super.headSet(toElement)); + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return removeOnlySortedSet(super.subSet(fromElement, toElement)); + } + + @Override + public SortedSet tailSet(E fromElement) { + return removeOnlySortedSet(super.tailSet(fromElement)); + } + }; + } + + /** + * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code + * ClassCastException} and {@code NullPointerException}. + */ + static boolean safeContainsKey(Map map, Object key) { + checkNotNull(map); + try { + return map.containsKey(key); + } catch (ClassCastException e) { + return false; + } catch (NullPointerException e) { + return false; } + } - @Override - public K lowerKey(K key) { - return delegate.lowerKey(key); + /** + * Delegates to {@link Map#get}. Returns {@code null} on {@code + * ClassCastException} and {@code NullPointerException}. + */ + static V safeGet(Map map, @Nullable Object key) { + checkNotNull(map); + try { + return map.get(key); + } catch (ClassCastException e) { + return null; + } catch (NullPointerException e) { + return null; } + } - @Override - public Entry floorEntry(K key) { - return unmodifiableOrNull(delegate.floorEntry(key)); + /** + * Delegates to {@link Map#remove}. Returns {@code null} on {@code + * ClassCastException} and {@code NullPointerException}. + */ + static V safeRemove(Map map, Object key) { + checkNotNull(map); + try { + return map.remove(key); + } catch (ClassCastException e) { + return null; + } catch (NullPointerException e) { + return null; } + } - @Override - public K floorKey(K key) { - return delegate.floorKey(key); - } - - @Override - public Entry ceilingEntry(K key) { - return unmodifiableOrNull(delegate.ceilingEntry(key)); - } - - @Override - public K ceilingKey(K key) { - return delegate.ceilingKey(key); - } - - @Override - public Entry higherEntry(K key) { - return unmodifiableOrNull(delegate.higherEntry(key)); - } - - @Override - public K higherKey(K key) { - return delegate.higherKey(key); - } - - @Override - public Entry firstEntry() { - return unmodifiableOrNull(delegate.firstEntry()); - } - - @Override - public Entry lastEntry() { - return unmodifiableOrNull(delegate.lastEntry()); - } - - @Override - public final Entry pollFirstEntry() { - throw new UnsupportedOperationException(); - } - - @Override - public final Entry pollLastEntry() { - throw new UnsupportedOperationException(); - } - - private transient UnmodifiableNavigableMap descendingMap; - - @Override - public NavigableMap descendingMap() { - UnmodifiableNavigableMap result = descendingMap; - return (result == null) ? descendingMap = new UnmodifiableNavigableMap(delegate.descendingMap(), this) - : result; - } - - @Override - public Set keySet() { - return navigableKeySet(); - } - - @Override - public NavigableSet navigableKeySet() { - return Sets.unmodifiableNavigableSet(delegate.navigableKeySet()); - } - - @Override - public NavigableSet descendingKeySet() { - return Sets.unmodifiableNavigableSet(delegate.descendingKeySet()); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); - } - - @Override - public SortedMap headMap(K toKey) { - return headMap(toKey, false); - } - - @Override - public SortedMap tailMap(K fromKey) { - return tailMap(fromKey, true); - } - - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - return Maps.unmodifiableNavigableMap(delegate.subMap(fromKey, fromInclusive, toKey, toInclusive)); - } - - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive)); - } - - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive)); - } + /** + * Returns a synchronized (thread-safe) bimap backed by the specified bimap. In + * order to guarantee serial access, it is critical that all access to + * the backing bimap is accomplished through the returned bimap. + * + *

+ * It is imperative that the user manually synchronize on the returned map when + * accessing any of its collection views: + * + *

+	 *    {@code
+	 *
+	 *   BiMap map = Maps.synchronizedBiMap(
+	 *       HashBiMap.create());
+	 *   ...
+	 *   Set set = map.keySet();  // Needn't be in synchronized block
+	 *   ...
+	 *   synchronized (map) {  // Synchronizing on map, not set!
+	 *     Iterator it = set.iterator(); // Must be in synchronized block
+	 *     while (it.hasNext()) {
+	 *       foo(it.next());
+	 *     }
+	 *   }}
+	 * 
+ * + *

+ * Failure to follow this advice may result in non-deterministic behavior. + * + *

+ * The returned bimap will be serializable if the specified bimap is + * serializable. + * + * @param bimap the bimap to be wrapped in a synchronized view + * @return a sychronized view of the specified bimap + */ + public static BiMap synchronizedBiMap(BiMap bimap) { + return Synchronized.biMap(bimap, null); } /** @@ -3433,170 +3527,48 @@ public final class Maps { } /** - * {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code - * entrySet().isEmpty()} instead of {@code size() == 0} to speed up - * implementations where {@code size()} is O(n), and it delegates the {@code - * isEmpty()} methods of its key set and value collection to this - * implementation. - */ - @GwtCompatible - abstract static class ImprovedAbstractMap extends AbstractMap { - /** - * Creates the entry set to be returned by {@link #entrySet()}. This method is - * invoked at most once on a given map, at the time when {@code entrySet} is - * first called. - */ - abstract Set> createEntrySet(); - - private transient Set> entrySet; - - @Override - public Set> entrySet() { - Set> result = entrySet; - return (result == null) ? entrySet = createEntrySet() : result; - } - - private transient Set keySet; - - @Override - public Set keySet() { - Set result = keySet; - return (result == null) ? keySet = createKeySet() : result; - } - - Set createKeySet() { - return new KeySet(this); - } - - private transient Collection values; - - @Override - public Collection values() { - Collection result = values; - return (result == null) ? values = createValues() : result; - } - - Collection createValues() { - return new Values(this); - } - } - - /** - * Delegates to {@link Map#get}. Returns {@code null} on {@code - * ClassCastException} and {@code NullPointerException}. - */ - static V safeGet(Map map, @Nullable Object key) { - checkNotNull(map); - try { - return map.get(key); - } catch (ClassCastException e) { - return null; - } catch (NullPointerException e) { - return null; - } - } - - /** - * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code - * ClassCastException} and {@code NullPointerException}. - */ - static boolean safeContainsKey(Map map, Object key) { - checkNotNull(map); - try { - return map.containsKey(key); - } catch (ClassCastException e) { - return false; - } catch (NullPointerException e) { - return false; - } - } - - /** - * Delegates to {@link Map#remove}. Returns {@code null} on {@code - * ClassCastException} and {@code NullPointerException}. - */ - static V safeRemove(Map map, Object key) { - checkNotNull(map); - try { - return map.remove(key); - } catch (ClassCastException e) { - return null; - } catch (NullPointerException e) { - return null; - } - } - - /** - * An admittedly inefficient implementation of {@link Map#containsKey}. - */ - static boolean containsKeyImpl(Map map, @Nullable Object key) { - return Iterators.contains(keyIterator(map.entrySet().iterator()), key); - } - - /** - * An implementation of {@link Map#containsValue}. - */ - static boolean containsValueImpl(Map map, @Nullable Object value) { - return Iterators.contains(valueIterator(map.entrySet().iterator()), value); - } - - /** - * Implements {@code Collection.contains} safely for forwarding collections of - * map entries. If {@code o} is an instance of {@code Map.Entry}, it is wrapped - * using {@link #unmodifiableEntry} to protect against a possible nefarious - * equals method. + * Returns an immutable map whose keys are the distinct elements of {@code + * keys} and whose value for each key was computed by {@code valueFunction}. The + * map's iteration order is the order of the first appearance of each key in + * {@code keys}. * *

- * Note that {@code c} is the backing (delegate) collection, rather than the - * forwarding collection. + * If {@code keys} is a {@link Set}, a live view can be obtained instead of a + * copy using {@link Maps#asMap(Set, Function)}. * - * @param c the delegate (unwrapped) collection of map entries - * @param o the object that might be contained in {@code c} - * @return {@code true} if {@code c} contains {@code o} + * @throws NullPointerException if any element of {@code keys} is {@code null}, + * or if {@code valueFunction} produces + * {@code null} for any key + * @since 14.0 */ - static boolean containsEntryImpl(Collection> c, Object o) { - if (!(o instanceof Entry)) { - return false; - } - return c.contains(unmodifiableEntry((Entry) o)); + @Beta + public static ImmutableMap toMap(Iterable keys, Function valueFunction) { + return toMap(keys.iterator(), valueFunction); } /** - * Implements {@code Collection.remove} safely for forwarding collections of map - * entries. If {@code o} is an instance of {@code Map.Entry}, it is wrapped - * using {@link #unmodifiableEntry} to protect against a possible nefarious - * equals method. + * Returns an immutable map whose keys are the distinct elements of {@code + * keys} and whose value for each key was computed by {@code valueFunction}. The + * map's iteration order is the order of the first appearance of each key in + * {@code keys}. * - *

- * Note that {@code c} is backing (delegate) collection, rather than the - * forwarding collection. - * - * @param c the delegate (unwrapped) collection of map entries - * @param o the object to remove from {@code c} - * @return {@code true} if {@code c} was changed + * @throws NullPointerException if any element of {@code keys} is {@code null}, + * or if {@code valueFunction} produces + * {@code null} for any key + * @since 14.0 */ - static boolean removeEntryImpl(Collection> c, Object o) { - if (!(o instanceof Entry)) { - return false; + @Beta + public static ImmutableMap toMap(Iterator keys, Function valueFunction) { + checkNotNull(valueFunction); + // Using LHM instead of a builder so as not to fail on duplicate keys + Map builder = newLinkedHashMap(); + while (keys.hasNext()) { + K key = keys.next(); + builder.put(key, valueFunction.apply(key)); } - return c.remove(unmodifiableEntry((Entry) o)); + return ImmutableMap.copyOf(builder); } - /** - * An implementation of {@link Map#equals}. - */ - static boolean equalsImpl(Map map, Object object) { - if (map == object) { - return true; - } else if (object instanceof Map) { - Map o = (Map) object; - return map.entrySet().equals(o.entrySet()); - } - return false; - } - - static final MapJoiner STANDARD_JOINER = Collections2.STANDARD_JOINER.withKeyValueSeparator("="); - /** * An implementation of {@link Map#toString}. */ @@ -3607,63 +3579,545 @@ public final class Maps { } /** - * An implementation of {@link Map#putAll}. + * Returns a view of a map whose values are derived from the original map's + * entries. In contrast to {@link #transformValues}, this method's + * entry-transformation logic may depend on the key as well as the value. + * + *

+ * All other properties of the transformed map, such as iteration order, are + * left intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	Map options = ImmutableMap.of("verbose", true, "sort", false);
+	 * 	EntryTransformer flagPrefixer = new EntryTransformer() {
+	 * 		public String transformEntry(String key, Boolean value) {
+	 * 			return value ? key : "no" + key;
+	 * 		}
+	 * 	};
+	 * 	Map transformed = Maps.transformEntries(options, flagPrefixer);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {verbose=verbose, sort=nosort}}. + * + *

+ * Changes in the underlying map are reflected in this view. Conversely, this + * view supports removal operations, and these are reflected in the underlying + * map. + * + *

+ * It's acceptable for the underlying map to contain null keys and null values + * provided that the transformer is capable of accepting null inputs. The + * transformed map might contain null values if the transformer sometimes gives + * a null result. + * + *

+ * The returned map is not thread-safe or serializable, even if the underlying + * map is. + * + *

+ * The transformer is applied lazily, invoked when needed. This is necessary for + * the returned map to be a view, but it means that the transformer will be + * applied many times for bulk operations like {@link Map#containsValue} and + * {@link Object#toString}. For this to perform well, {@code transformer} should + * be fast. To avoid lazy evaluation when the returned map doesn't need to be a + * view, copy the returned map into a new map of your choosing. + * + *

+ * Warning: This method assumes that for any instance {@code k} of + * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies + * that {@code k2} is also of type {@code K}. Using an {@code + * EntryTransformer} key type for which this may not hold, such as {@code + * ArrayList}, may risk a {@code ClassCastException} when calling methods on the + * transformed map. + * + * @since 7.0 */ - static void putAllImpl(Map self, Map map) { - for (Map.Entry entry : map.entrySet()) { - self.put(entry.getKey(), entry.getValue()); + public static Map transformEntries(Map fromMap, + EntryTransformer transformer) { + if (fromMap instanceof SortedMap) { + return transformEntries((SortedMap) fromMap, transformer); + } + return new TransformedEntriesMap(fromMap, transformer); + } + + /** + * Returns a view of a navigable map whose values are derived from the original + * navigable map's entries. In contrast to {@link #transformValues}, this + * method's entry-transformation logic may depend on the key as well as the + * value. + * + *

+ * All other properties of the transformed map, such as iteration order, are + * left intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	NavigableMap options = Maps.newTreeMap();
+	 * 	options.put("verbose", false);
+	 * 	options.put("sort", true);
+	 * 	EntryTransformer flagPrefixer = new EntryTransformer() {
+	 * 		public String transformEntry(String key, Boolean value) {
+	 * 			return value ? key : ("yes" + key);
+	 * 		}
+	 * 	};
+	 * 	NavigableMap transformed = LabsMaps.transformNavigableEntries(options, flagPrefixer);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {sort=yessort, verbose=verbose}}. + * + *

+ * Changes in the underlying map are reflected in this view. Conversely, this + * view supports removal operations, and these are reflected in the underlying + * map. + * + *

+ * It's acceptable for the underlying map to contain null keys and null values + * provided that the transformer is capable of accepting null inputs. The + * transformed map might contain null values if the transformer sometimes gives + * a null result. + * + *

+ * The returned map is not thread-safe or serializable, even if the underlying + * map is. + * + *

+ * The transformer is applied lazily, invoked when needed. This is necessary for + * the returned map to be a view, but it means that the transformer will be + * applied many times for bulk operations like {@link Map#containsValue} and + * {@link Object#toString}. For this to perform well, {@code transformer} should + * be fast. To avoid lazy evaluation when the returned map doesn't need to be a + * view, copy the returned map into a new map of your choosing. + * + *

+ * Warning: This method assumes that for any instance {@code k} of + * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies + * that {@code k2} is also of type {@code K}. Using an {@code + * EntryTransformer} key type for which this may not hold, such as {@code + * ArrayList}, may risk a {@code ClassCastException} when calling methods on the + * transformed map. + * + * @since 13.0 + */ + @GwtIncompatible("NavigableMap") + public static NavigableMap transformEntries(final NavigableMap fromMap, + EntryTransformer transformer) { + return new TransformedEntriesNavigableMap(fromMap, transformer); + } + + /** + * Returns a view of a sorted map whose values are derived from the original + * sorted map's entries. In contrast to {@link #transformValues}, this method's + * entry-transformation logic may depend on the key as well as the value. + * + *

+ * All other properties of the transformed map, such as iteration order, are + * left intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	Map options = ImmutableSortedMap.of("verbose", true, "sort", false);
+	 * 	EntryTransformer flagPrefixer = new EntryTransformer() {
+	 * 		public String transformEntry(String key, Boolean value) {
+	 * 			return value ? key : "yes" + key;
+	 * 		}
+	 * 	};
+	 * 	SortedMap transformed = Maps.transformEntries(options, flagPrefixer);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {sort=yessort, verbose=verbose}}. + * + *

+ * Changes in the underlying map are reflected in this view. Conversely, this + * view supports removal operations, and these are reflected in the underlying + * map. + * + *

+ * It's acceptable for the underlying map to contain null keys and null values + * provided that the transformer is capable of accepting null inputs. The + * transformed map might contain null values if the transformer sometimes gives + * a null result. + * + *

+ * The returned map is not thread-safe or serializable, even if the underlying + * map is. + * + *

+ * The transformer is applied lazily, invoked when needed. This is necessary for + * the returned map to be a view, but it means that the transformer will be + * applied many times for bulk operations like {@link Map#containsValue} and + * {@link Object#toString}. For this to perform well, {@code transformer} should + * be fast. To avoid lazy evaluation when the returned map doesn't need to be a + * view, copy the returned map into a new map of your choosing. + * + *

+ * Warning: This method assumes that for any instance {@code k} of + * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies + * that {@code k2} is also of type {@code K}. Using an {@code + * EntryTransformer} key type for which this may not hold, such as {@code + * ArrayList}, may risk a {@code ClassCastException} when calling methods on the + * transformed map. + * + * @since 11.0 + */ + public static SortedMap transformEntries(SortedMap fromMap, + EntryTransformer transformer) { + return Platform.mapsTransformEntriesSortedMap(fromMap, transformer); + } + + static SortedMap transformEntriesIgnoreNavigable(SortedMap fromMap, + EntryTransformer transformer) { + return new TransformedEntriesSortedMap(fromMap, transformer); + } + + /** + * Returns a view of an entry transformed by the specified transformer. + */ + static Entry transformEntry(final EntryTransformer transformer, + final Entry entry) { + checkNotNull(transformer); + checkNotNull(entry); + return new AbstractMapEntry() { + @Override + public K getKey() { + return entry.getKey(); + } + + @Override + public V2 getValue() { + return transformer.transformEntry(entry.getKey(), entry.getValue()); + } + }; + } + + /** + * Returns a view of a map where each value is transformed by a function. All + * other properties of the map, such as iteration order, are left intact. For + * example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	Map map = ImmutableMap.of("a", 4, "b", 9);
+	 * 	Function sqrt = new Function() {
+	 * 		public Double apply(Integer in) {
+	 * 			return Math.sqrt((int) in);
+	 * 		}
+	 * 	};
+	 * 	Map transformed = Maps.transformValues(map, sqrt);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {a=2.0, b=3.0}}. + * + *

+ * Changes in the underlying map are reflected in this view. Conversely, this + * view supports removal operations, and these are reflected in the underlying + * map. + * + *

+ * It's acceptable for the underlying map to contain null keys, and even null + * values provided that the function is capable of accepting null input. The + * transformed map might contain null values, if the function sometimes gives a + * null result. + * + *

+ * The returned map is not thread-safe or serializable, even if the underlying + * map is. + * + *

+ * The function is applied lazily, invoked when needed. This is necessary for + * the returned map to be a view, but it means that the function will be applied + * many times for bulk operations like {@link Map#containsValue} and + * {@code Map.toString()}. For this to perform well, {@code function} should be + * fast. To avoid lazy evaluation when the returned map doesn't need to be a + * view, copy the returned map into a new map of your choosing. + */ + public static Map transformValues(Map fromMap, Function function) { + return transformEntries(fromMap, asEntryTransformer(function)); + } + + /** + * Returns a view of a navigable map where each value is transformed by a + * function. All other properties of the map, such as iteration order, are left + * intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	NavigableMap map = Maps.newTreeMap();
+	 * 	map.put("a", 4);
+	 * 	map.put("b", 9);
+	 * 	Function sqrt = new Function() {
+	 * 		public Double apply(Integer in) {
+	 * 			return Math.sqrt((int) in);
+	 * 		}
+	 * 	};
+	 * 	NavigableMap transformed = Maps.transformNavigableValues(map, sqrt);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {a=2.0, b=3.0}}. + * + * Changes in the underlying map are reflected in this view. Conversely, this + * view supports removal operations, and these are reflected in the underlying + * map. + * + *

+ * It's acceptable for the underlying map to contain null keys, and even null + * values provided that the function is capable of accepting null input. The + * transformed map might contain null values, if the function sometimes gives a + * null result. + * + *

+ * The returned map is not thread-safe or serializable, even if the underlying + * map is. + * + *

+ * The function is applied lazily, invoked when needed. This is necessary for + * the returned map to be a view, but it means that the function will be applied + * many times for bulk operations like {@link Map#containsValue} and + * {@code Map.toString()}. For this to perform well, {@code function} should be + * fast. To avoid lazy evaluation when the returned map doesn't need to be a + * view, copy the returned map into a new map of your choosing. + * + * @since 13.0 + */ + @GwtIncompatible("NavigableMap") + public static NavigableMap transformValues(NavigableMap fromMap, + Function function) { + return transformEntries(fromMap, asEntryTransformer(function)); + } + + /** + * Returns a view of a sorted map where each value is transformed by a function. + * All other properties of the map, such as iteration order, are left intact. + * For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	SortedMap map = ImmutableSortedMap.of("a", 4, "b", 9);
+	 * 	Function sqrt = new Function() {
+	 * 		public Double apply(Integer in) {
+	 * 			return Math.sqrt((int) in);
+	 * 		}
+	 * 	};
+	 * 	SortedMap transformed = Maps.transformValues(map, sqrt);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {a=2.0, b=3.0}}. + * + *

+ * Changes in the underlying map are reflected in this view. Conversely, this + * view supports removal operations, and these are reflected in the underlying + * map. + * + *

+ * It's acceptable for the underlying map to contain null keys, and even null + * values provided that the function is capable of accepting null input. The + * transformed map might contain null values, if the function sometimes gives a + * null result. + * + *

+ * The returned map is not thread-safe or serializable, even if the underlying + * map is. + * + *

+ * The function is applied lazily, invoked when needed. This is necessary for + * the returned map to be a view, but it means that the function will be applied + * many times for bulk operations like {@link Map#containsValue} and + * {@code Map.toString()}. For this to perform well, {@code function} should be + * fast. To avoid lazy evaluation when the returned map doesn't need to be a + * view, copy the returned map into a new map of your choosing. + * + * @since 11.0 + */ + public static SortedMap transformValues(SortedMap fromMap, + Function function) { + return transformEntries(fromMap, asEntryTransformer(function)); + } + + /** + * Returns an immutable map for which the {@link Map#values} are the given + * elements in the given order, and each key is the product of invoking a + * supplied function on its corresponding value. + * + * @param values the values to use when constructing the {@code Map} + * @param keyFunction the function used to produce the key for each value + * @return a map mapping the result of evaluating the function {@code + * keyFunction} on each value in the input collection to that value + * @throws IllegalArgumentException if {@code keyFunction} produces the same key + * for more than one value in the input + * collection + * @throws NullPointerException if any elements of {@code values} is null, + * or if {@code keyFunction} produces + * {@code null} for any value + */ + public static ImmutableMap uniqueIndex(Iterable values, Function keyFunction) { + return uniqueIndex(values.iterator(), keyFunction); + } + + /** + * Returns an immutable map for which the {@link Map#values} are the given + * elements in the given order, and each key is the product of invoking a + * supplied function on its corresponding value. + * + * @param values the values to use when constructing the {@code Map} + * @param keyFunction the function used to produce the key for each value + * @return a map mapping the result of evaluating the function {@code + * keyFunction} on each value in the input collection to that value + * @throws IllegalArgumentException if {@code keyFunction} produces the same key + * for more than one value in the input + * collection + * @throws NullPointerException if any elements of {@code values} is null, + * or if {@code keyFunction} produces + * {@code null} for any value + * @since 10.0 + */ + public static ImmutableMap uniqueIndex(Iterator values, Function keyFunction) { + checkNotNull(keyFunction); + ImmutableMap.Builder builder = ImmutableMap.builder(); + while (values.hasNext()) { + V value = values.next(); + builder.put(keyFunction.apply(value), value); + } + return builder.build(); + } + + /** + * Returns an unmodifiable view of the specified bimap. This method allows + * modules to provide users with "read-only" access to internal bimaps. Query + * operations on the returned bimap "read through" to the specified bimap, and + * attempts to modify the returned map, whether direct or via its collection + * views, result in an {@code UnsupportedOperationException}. + * + *

+ * The returned bimap will be serializable if the specified bimap is + * serializable. + * + * @param bimap the bimap for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified bimap + */ + public static BiMap unmodifiableBiMap(BiMap bimap) { + return new UnmodifiableBiMap(bimap, null); + } + + /** + * Returns an unmodifiable view of the specified map entry. The + * {@link Entry#setValue} operation throws an + * {@link UnsupportedOperationException}. This also has the side-effect of + * redefining {@code equals} to comply with the Entry contract, to avoid a + * possible nefarious implementation of equals. + * + * @param entry the entry for which to return an unmodifiable view + * @return an unmodifiable view of the entry + */ + static Entry unmodifiableEntry(final Entry entry) { + checkNotNull(entry); + return new AbstractMapEntry() { + @Override + public K getKey() { + return entry.getKey(); + } + + @Override + public V getValue() { + return entry.getValue(); + } + }; + } + + /** + * Returns an unmodifiable view of the specified set of entries. The + * {@link Entry#setValue} operation throws an + * {@link UnsupportedOperationException}, as do any operations that would modify + * the returned set. + * + * @param entrySet the entries for which to return an unmodifiable view + * @return an unmodifiable view of the entries + */ + static Set> unmodifiableEntrySet(Set> entrySet) { + return new UnmodifiableEntrySet(Collections.unmodifiableSet(entrySet)); + } + + private static Map unmodifiableMap(Map map) { + if (map instanceof SortedMap) { + return Collections.unmodifiableSortedMap((SortedMap) map); + } else { + return Collections.unmodifiableMap(map); } } - static class KeySet extends Sets.ImprovedAbstractSet { - final Map map; - - KeySet(Map map) { - this.map = checkNotNull(map); - } - - Map map() { + /** + * Returns an unmodifiable view of the specified navigable map. Query operations + * on the returned map read through to the specified map, and attempts to modify + * the returned map, whether direct or via its views, result in an + * {@code UnsupportedOperationException}. + * + *

+ * The returned navigable map will be serializable if the specified navigable + * map is serializable. + * + * @param map the navigable map for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified navigable map + * @since 12.0 + */ + @GwtIncompatible("NavigableMap") + public static NavigableMap unmodifiableNavigableMap(NavigableMap map) { + checkNotNull(map); + if (map instanceof UnmodifiableNavigableMap) { return map; - } - - @Override - public Iterator iterator() { - return keyIterator(map().entrySet().iterator()); - } - - @Override - public int size() { - return map().size(); - } - - @Override - public boolean isEmpty() { - return map().isEmpty(); - } - - @Override - public boolean contains(Object o) { - return map().containsKey(o); - } - - @Override - public boolean remove(Object o) { - if (contains(o)) { - map().remove(o); - return true; - } - return false; - } - - @Override - public void clear() { - map().clear(); + } else { + return new UnmodifiableNavigableMap(map); } } @Nullable - static K keyOrNull(@Nullable Entry entry) { - return (entry == null) ? null : entry.getKey(); + private static Entry unmodifiableOrNull(@Nullable Entry entry) { + return (entry == null) ? null : Maps.unmodifiableEntry(entry); + } + + @SuppressWarnings("unchecked") + static Function, V> valueFunction() { + return (Function) EntryFunction.VALUE; + } + + static Iterator valueIterator(Iterator> entryIterator) { + return Iterators.transform(entryIterator, Maps.valueFunction()); + } + + static UnmodifiableIterator valueIterator(final UnmodifiableIterator> entryIterator) { + return new UnmodifiableIterator() { + @Override + public boolean hasNext() { + return entryIterator.hasNext(); + } + + @Override + public V next() { + return entryIterator.next().getValue(); + } + }; } @Nullable @@ -3671,463 +4125,10 @@ public final class Maps { return (entry == null) ? null : entry.getValue(); } - static class SortedKeySet extends KeySet implements SortedSet { - SortedKeySet(SortedMap map) { - super(map); - } - - @Override - SortedMap map() { - return (SortedMap) super.map(); - } - - @Override - public Comparator comparator() { - return map().comparator(); - } - - @Override - public SortedSet subSet(K fromElement, K toElement) { - return new SortedKeySet(map().subMap(fromElement, toElement)); - } - - @Override - public SortedSet headSet(K toElement) { - return new SortedKeySet(map().headMap(toElement)); - } - - @Override - public SortedSet tailSet(K fromElement) { - return new SortedKeySet(map().tailMap(fromElement)); - } - - @Override - public K first() { - return map().firstKey(); - } - - @Override - public K last() { - return map().lastKey(); - } + static Predicate> valuePredicateOnEntries(Predicate valuePredicate) { + return compose(valuePredicate, Maps.valueFunction()); } - @GwtIncompatible("NavigableMap") - static class NavigableKeySet extends SortedKeySet implements NavigableSet { - NavigableKeySet(NavigableMap map) { - super(map); - } - - @Override - NavigableMap map() { - return (NavigableMap) map; - } - - @Override - public K lower(K e) { - return map().lowerKey(e); - } - - @Override - public K floor(K e) { - return map().floorKey(e); - } - - @Override - public K ceiling(K e) { - return map().ceilingKey(e); - } - - @Override - public K higher(K e) { - return map().higherKey(e); - } - - @Override - public K pollFirst() { - return keyOrNull(map().pollFirstEntry()); - } - - @Override - public K pollLast() { - return keyOrNull(map().pollLastEntry()); - } - - @Override - public NavigableSet descendingSet() { - return map().descendingKeySet(); - } - - @Override - public Iterator descendingIterator() { - return descendingSet().iterator(); - } - - @Override - public NavigableSet subSet(K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) { - return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); - } - - @Override - public NavigableSet headSet(K toElement, boolean inclusive) { - return map().headMap(toElement, inclusive).navigableKeySet(); - } - - @Override - public NavigableSet tailSet(K fromElement, boolean inclusive) { - return map().tailMap(fromElement, inclusive).navigableKeySet(); - } - - @Override - public SortedSet subSet(K fromElement, K toElement) { - return subSet(fromElement, true, toElement, false); - } - - @Override - public SortedSet headSet(K toElement) { - return headSet(toElement, false); - } - - @Override - public SortedSet tailSet(K fromElement) { - return tailSet(fromElement, true); - } - } - - static class Values extends AbstractCollection { - final Map map; - - Values(Map map) { - this.map = checkNotNull(map); - } - - final Map map() { - return map; - } - - @Override - public Iterator iterator() { - return valueIterator(map().entrySet().iterator()); - } - - @Override - public boolean remove(Object o) { - try { - return super.remove(o); - } catch (UnsupportedOperationException e) { - for (Entry entry : map().entrySet()) { - if (Objects.equal(o, entry.getValue())) { - map().remove(entry.getKey()); - return true; - } - } - return false; - } - } - - @Override - public boolean removeAll(Collection c) { - try { - return super.removeAll(checkNotNull(c)); - } catch (UnsupportedOperationException e) { - Set toRemove = Sets.newHashSet(); - for (Entry entry : map().entrySet()) { - if (c.contains(entry.getValue())) { - toRemove.add(entry.getKey()); - } - } - return map().keySet().removeAll(toRemove); - } - } - - @Override - public boolean retainAll(Collection c) { - try { - return super.retainAll(checkNotNull(c)); - } catch (UnsupportedOperationException e) { - Set toRetain = Sets.newHashSet(); - for (Entry entry : map().entrySet()) { - if (c.contains(entry.getValue())) { - toRetain.add(entry.getKey()); - } - } - return map().keySet().retainAll(toRetain); - } - } - - @Override - public int size() { - return map().size(); - } - - @Override - public boolean isEmpty() { - return map().isEmpty(); - } - - @Override - public boolean contains(@Nullable Object o) { - return map().containsValue(o); - } - - @Override - public void clear() { - map().clear(); - } - } - - abstract static class EntrySet extends Sets.ImprovedAbstractSet> { - abstract Map map(); - - @Override - public int size() { - return map().size(); - } - - @Override - public void clear() { - map().clear(); - } - - @Override - public boolean contains(Object o) { - if (o instanceof Entry) { - Entry entry = (Entry) o; - Object key = entry.getKey(); - V value = Maps.safeGet(map(), key); - return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); - } - return false; - } - - @Override - public boolean isEmpty() { - return map().isEmpty(); - } - - @Override - public boolean remove(Object o) { - if (contains(o)) { - Entry entry = (Entry) o; - return map().keySet().remove(entry.getKey()); - } - return false; - } - - @Override - public boolean removeAll(Collection c) { - try { - return super.removeAll(checkNotNull(c)); - } catch (UnsupportedOperationException e) { - // if the iterators don't support remove - return Sets.removeAllImpl(this, c.iterator()); - } - } - - @Override - public boolean retainAll(Collection c) { - try { - return super.retainAll(checkNotNull(c)); - } catch (UnsupportedOperationException e) { - // if the iterators don't support remove - Set keys = Sets.newHashSetWithExpectedSize(c.size()); - for (Object o : c) { - if (contains(o)) { - Entry entry = (Entry) o; - keys.add(entry.getKey()); - } - } - return map().keySet().retainAll(keys); - } - } - } - - @GwtIncompatible("NavigableMap") - abstract static class DescendingMap extends ForwardingMap implements NavigableMap { - - abstract NavigableMap forward(); - - @Override - protected final Map delegate() { - return forward(); - } - - private transient Comparator comparator; - - @SuppressWarnings("unchecked") - @Override - public Comparator comparator() { - Comparator result = comparator; - if (result == null) { - Comparator forwardCmp = forward().comparator(); - if (forwardCmp == null) { - forwardCmp = (Comparator) Ordering.natural(); - } - result = comparator = reverse(forwardCmp); - } - return result; - } - - // If we inline this, we get a javac error. - private static Ordering reverse(Comparator forward) { - return Ordering.from(forward).reverse(); - } - - @Override - public K firstKey() { - return forward().lastKey(); - } - - @Override - public K lastKey() { - return forward().firstKey(); - } - - @Override - public Entry lowerEntry(K key) { - return forward().higherEntry(key); - } - - @Override - public K lowerKey(K key) { - return forward().higherKey(key); - } - - @Override - public Entry floorEntry(K key) { - return forward().ceilingEntry(key); - } - - @Override - public K floorKey(K key) { - return forward().ceilingKey(key); - } - - @Override - public Entry ceilingEntry(K key) { - return forward().floorEntry(key); - } - - @Override - public K ceilingKey(K key) { - return forward().floorKey(key); - } - - @Override - public Entry higherEntry(K key) { - return forward().lowerEntry(key); - } - - @Override - public K higherKey(K key) { - return forward().lowerKey(key); - } - - @Override - public Entry firstEntry() { - return forward().lastEntry(); - } - - @Override - public Entry lastEntry() { - return forward().firstEntry(); - } - - @Override - public Entry pollFirstEntry() { - return forward().pollLastEntry(); - } - - @Override - public Entry pollLastEntry() { - return forward().pollFirstEntry(); - } - - @Override - public NavigableMap descendingMap() { - return forward(); - } - - private transient Set> entrySet; - - @Override - public Set> entrySet() { - Set> result = entrySet; - return (result == null) ? entrySet = createEntrySet() : result; - } - - abstract Iterator> entryIterator(); - - Set> createEntrySet() { - return new EntrySet() { - @Override - Map map() { - return DescendingMap.this; - } - - @Override - public Iterator> iterator() { - return entryIterator(); - } - }; - } - - @Override - public Set keySet() { - return navigableKeySet(); - } - - private transient NavigableSet navigableKeySet; - - @Override - public NavigableSet navigableKeySet() { - NavigableSet result = navigableKeySet; - return (result == null) ? navigableKeySet = new NavigableKeySet(this) : result; - } - - @Override - public NavigableSet descendingKeySet() { - return forward().navigableKeySet(); - } - - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); - } - - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - return forward().tailMap(toKey, inclusive).descendingMap(); - } - - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - return forward().headMap(fromKey, inclusive).descendingMap(); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); - } - - @Override - public SortedMap headMap(K toKey) { - return headMap(toKey, false); - } - - @Override - public SortedMap tailMap(K fromKey) { - return tailMap(fromKey, true); - } - - @Override - public Collection values() { - return new Values(this); - } - - @Override - public String toString() { - return standardToString(); - } + private Maps() { } } diff --git a/src/main/java/com/google/common/collect/MinMaxPriorityQueue.java b/src/main/java/com/google/common/collect/MinMaxPriorityQueue.java index 13497a19..2e085bfc 100644 --- a/src/main/java/com/google/common/collect/MinMaxPriorityQueue.java +++ b/src/main/java/com/google/common/collect/MinMaxPriorityQueue.java @@ -95,51 +95,6 @@ import com.google.common.math.IntMath; @Beta public final class MinMaxPriorityQueue extends AbstractQueue { - /** - * Creates a new min-max priority queue with default settings: natural order, no - * maximum size, no initial contents, and an initial expected size of 11. - */ - public static > MinMaxPriorityQueue create() { - return new Builder(Ordering.natural()).create(); - } - - /** - * Creates a new min-max priority queue using natural order, no maximum size, - * and initially containing the given elements. - */ - public static > MinMaxPriorityQueue create(Iterable initialContents) { - return new Builder(Ordering.natural()).create(initialContents); - } - - /** - * Creates and returns a new builder, configured to build {@code - * MinMaxPriorityQueue} instances that use {@code comparator} to determine the - * least and greatest elements. - */ - public static Builder orderedBy(Comparator comparator) { - return new Builder(comparator); - } - - /** - * Creates and returns a new builder, configured to build {@code - * MinMaxPriorityQueue} instances sized appropriately to hold {@code - * expectedSize} elements. - */ - public static Builder expectedSize(int expectedSize) { - return new Builder(Ordering.natural()).expectedSize(expectedSize); - } - - /** - * Creates and returns a new builder, configured to build {@code - * MinMaxPriorityQueue} instances that are limited to {@code maximumSize} - * elements. Each time a queue grows beyond this bound, it immediately removes - * its greatest element (according to its comparator), which might be the - * element that was just added. - */ - public static Builder maximumSize(int maximumSize) { - return new Builder(Ordering.natural()).maximumSize(maximumSize); - } - /** * The builder class used in creation of min-max priority queues. Instead of * constructing one directly, use @@ -169,6 +124,27 @@ public final class MinMaxPriorityQueue extends AbstractQueue { this.comparator = checkNotNull(comparator); } + /** + * Builds a new min-max priority queue using the previously specified options, + * and having no initial contents. + */ + public MinMaxPriorityQueue create() { + return create(Collections.emptySet()); + } + + /** + * Builds a new min-max priority queue using the previously specified options, + * and having the given initial elements. + */ + public MinMaxPriorityQueue create(Iterable initialContents) { + MinMaxPriorityQueue queue = new MinMaxPriorityQueue(this, + initialQueueSize(expectedSize, maximumSize, initialContents)); + for (T element : initialContents) { + queue.offer(element); + } + return queue; + } + /** * Configures this builder to build min-max priority queues with an initial * expected size of {@code expectedSize}. @@ -191,39 +167,467 @@ public final class MinMaxPriorityQueue extends AbstractQueue { return this; } - /** - * Builds a new min-max priority queue using the previously specified options, - * and having no initial contents. - */ - public MinMaxPriorityQueue create() { - return create(Collections.emptySet()); - } - - /** - * Builds a new min-max priority queue using the previously specified options, - * and having the given initial elements. - */ - public MinMaxPriorityQueue create(Iterable initialContents) { - MinMaxPriorityQueue queue = new MinMaxPriorityQueue(this, - initialQueueSize(expectedSize, maximumSize, initialContents)); - for (T element : initialContents) { - queue.offer(element); - } - return queue; - } - @SuppressWarnings("unchecked") // safe "contravariant cast" private Ordering ordering() { return Ordering.from((Comparator) comparator); } } + /** + * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap: a + * min-heap and a max-heap. Conceptually, these might each have their own array + * for storage, but for efficiency's sake they are stored interleaved on + * alternate heap levels in the same array (MMPQ.queue). + */ + private class Heap { + final Ordering ordering; + Heap otherHeap; + + Heap(Ordering ordering) { + this.ordering = ordering; + } + + /** + * Bubbles a value from {@code index} up the appropriate heap if required. + */ + void bubbleUp(int index, E x) { + int crossOver = crossOverUp(index, x); + + Heap heap; + if (crossOver == index) { + heap = this; + } else { + index = crossOver; + heap = otherHeap; + } + heap.bubbleUpAlternatingLevels(index, x); + } + + /** + * Bubbles a value from {@code index} up the levels of this heap, and returns + * the index the element ended up at. + */ + int bubbleUpAlternatingLevels(int index, E x) { + while (index > 2) { + int grandParentIndex = getGrandparentIndex(index); + E e = elementData(grandParentIndex); + if (ordering.compare(e, x) <= 0) { + break; + } + queue[index] = e; + index = grandParentIndex; + } + queue[index] = x; + return index; + } + + int compareElements(int a, int b) { + return ordering.compare(elementData(a), elementData(b)); + } + + /** + * Crosses an element over to the opposite heap by moving it one level down (or + * up if there are no elements below it). + * + * Returns the new position of the element. + */ + int crossOver(int index, E x) { + int minChildIndex = findMinChild(index); + // TODO(kevinb): split the && into two if's and move crossOverUp so it's + // only called when there's no child. + if ((minChildIndex > 0) && (ordering.compare(elementData(minChildIndex), x) < 0)) { + queue[index] = elementData(minChildIndex); + queue[minChildIndex] = x; + return minChildIndex; + } + return crossOverUp(index, x); + } + + /** + * Moves an element one level up from a min level to a max level (or vice + * versa). Returns the new position of the element. + */ + int crossOverUp(int index, E x) { + if (index == 0) { + queue[0] = x; + return 0; + } + int parentIndex = getParentIndex(index); + E parentElement = elementData(parentIndex); + if (parentIndex != 0) { + // This is a guard for the case of the childless uncle. + // Since the end of the array is actually the middle of the heap, + // a smaller childless uncle can become a child of x when we + // bubble up alternate levels, violating the invariant. + int grandparentIndex = getParentIndex(parentIndex); + int uncleIndex = getRightChildIndex(grandparentIndex); + if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { + E uncleElement = elementData(uncleIndex); + if (ordering.compare(uncleElement, parentElement) < 0) { + parentIndex = uncleIndex; + parentElement = uncleElement; + } + } + } + if (ordering.compare(parentElement, x) < 0) { + queue[index] = parentElement; + queue[parentIndex] = x; + return parentIndex; + } + queue[index] = x; + return index; + } + + /** + * Fills the hole at {@code index} by moving in the least of its grandchildren + * to this position, then recursively filling the new hole created. + * + * @return the position of the new hole (where the lowest grandchild moved from, + * that had no grandchild to replace it) + */ + int fillHoleAt(int index) { + int minGrandchildIndex; + while ((minGrandchildIndex = findMinGrandChild(index)) > 0) { + queue[index] = elementData(minGrandchildIndex); + index = minGrandchildIndex; + } + return index; + } + + /** + * Returns the index of minimum value between {@code index} and + * {@code index + len}, or {@code -1} if {@code index} is greater than + * {@code size}. + */ + int findMin(int index, int len) { + if (index >= size) { + return -1; + } + checkState(index > 0); + int limit = Math.min(index, size - len) + len; + int minIndex = index; + for (int i = index + 1; i < limit; i++) { + if (compareElements(i, minIndex) < 0) { + minIndex = i; + } + } + return minIndex; + } + + /** + * Returns the minimum child or {@code -1} if no child exists. + */ + int findMinChild(int index) { + return findMin(getLeftChildIndex(index), 2); + } + + /** + * Returns the minimum grand child or -1 if no grand child exists. + */ + int findMinGrandChild(int index) { + int leftChildIndex = getLeftChildIndex(index); + if (leftChildIndex < 0) { + return -1; + } + return findMin(getLeftChildIndex(leftChildIndex), 4); + } + + /** + * Returns the conceptually correct last element of the heap. + * + *

+ * Since the last element of the array is actually in the middle of the sorted + * structure, a childless uncle node could be smaller, which would corrupt the + * invariant if this element becomes the new parent of the uncle. In that case, + * we first switch the last element with its uncle, before returning. + */ + int getCorrectLastElement(E actualLastElement) { + int parentIndex = getParentIndex(size); + if (parentIndex != 0) { + int grandparentIndex = getParentIndex(parentIndex); + int uncleIndex = getRightChildIndex(grandparentIndex); + if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { + E uncleElement = elementData(uncleIndex); + if (ordering.compare(uncleElement, actualLastElement) < 0) { + queue[uncleIndex] = actualLastElement; + queue[size] = uncleElement; + return uncleIndex; + } + } + } + return size; + } + + private int getGrandparentIndex(int i) { + return getParentIndex(getParentIndex(i)); // (i - 3) / 4 + } + + private int getLeftChildIndex(int i) { + return i * 2 + 1; + } + + // These would be static if inner classes could have static members. + + private int getParentIndex(int i) { + return (i - 1) / 2; + } + + private int getRightChildIndex(int i) { + return i * 2 + 2; + } + + /** + * Tries to move {@code toTrickle} from a min to a max level and bubble up + * there. If it moved before {@code removeIndex} this method returns a pair as + * described in {@link #removeAt}. + */ + MoveDesc tryCrossOverAndBubbleUp(int removeIndex, int vacated, E toTrickle) { + int crossOver = crossOver(vacated, toTrickle); + if (crossOver == vacated) { + return null; + } + // Successfully crossed over from min to max. + // Bubble up max levels. + E parent; + // If toTrickle is moved up to a parent of removeIndex, the parent is + // placed in removeIndex position. We must return that to the iterator so + // that it knows to skip it. + if (crossOver < removeIndex) { + // We crossed over to the parent level in crossOver, so the parent + // has already been moved. + parent = elementData(removeIndex); + } else { + parent = elementData(getParentIndex(removeIndex)); + } + // bubble it up the opposite heap + if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle) < removeIndex) { + return new MoveDesc(toTrickle, parent); + } else { + return null; + } + } + + private boolean verifyIndex(int i) { + if ((getLeftChildIndex(i) < size) && (compareElements(i, getLeftChildIndex(i)) > 0)) { + return false; + } + if ((getRightChildIndex(i) < size) && (compareElements(i, getRightChildIndex(i)) > 0)) { + return false; + } + if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) { + return false; + } + if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) { + return false; + } + return true; + } + } + + // Returned from removeAt() to iterator.remove() + static class MoveDesc { + final E toTrickle; + final E replaced; + + MoveDesc(E toTrickle, E replaced) { + this.toTrickle = toTrickle; + this.replaced = replaced; + } + } + + /** + * Iterates the elements of the queue in no particular order. + * + * If the underlying queue is modified during iteration an exception will be + * thrown. + */ + private class QueueIterator implements Iterator { + private int cursor = -1; + private int expectedModCount = modCount; + private Queue forgetMeNot; + private List skipMe; + private E lastFromForgetMeNot; + private boolean canRemove; + + void checkModCount() { + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + // Finds only this exact instance, not others that are equals() + private boolean containsExact(Iterable elements, E target) { + for (E element : elements) { + if (element == target) { + return true; + } + } + return false; + } + + @Override + public boolean hasNext() { + checkModCount(); + return (nextNotInSkipMe(cursor + 1) < size()) || ((forgetMeNot != null) && !forgetMeNot.isEmpty()); + } + + @Override + public E next() { + checkModCount(); + int tempCursor = nextNotInSkipMe(cursor + 1); + if (tempCursor < size()) { + cursor = tempCursor; + canRemove = true; + return elementData(cursor); + } else if (forgetMeNot != null) { + cursor = size(); + lastFromForgetMeNot = forgetMeNot.poll(); + if (lastFromForgetMeNot != null) { + canRemove = true; + return lastFromForgetMeNot; + } + } + throw new NoSuchElementException("iterator moved past last element in queue."); + } + + /** + * Returns the index of the first element after {@code c} that is not in + * {@code skipMe} and returns {@code size()} if there is no such element. + */ + private int nextNotInSkipMe(int c) { + if (skipMe != null) { + while (c < size() && containsExact(skipMe, elementData(c))) { + c++; + } + } + return c; + } + + @Override + public void remove() { + checkRemove(canRemove); + checkModCount(); + canRemove = false; + expectedModCount++; + if (cursor < size()) { + MoveDesc moved = removeAt(cursor); + if (moved != null) { + if (forgetMeNot == null) { + forgetMeNot = new ArrayDeque(); + skipMe = new ArrayList(3); + } + forgetMeNot.add(moved.toTrickle); + skipMe.add(moved.replaced); + } + cursor--; + } else { // we must have set lastFromForgetMeNot in next() + checkState(removeExact(lastFromForgetMeNot)); + lastFromForgetMeNot = null; + } + } + + // Removes only this exact instance, not others that are equals() + boolean removeExact(Object target) { + for (int i = 0; i < size; i++) { + if (queue[i] == target) { + removeAt(i); + return true; + } + } + return false; + } + } + + private static final int EVEN_POWERS_OF_TWO = 0x55555555; + + private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa; + + private static final int DEFAULT_CAPACITY = 11; + + /** There's no reason for the queueSize to ever be more than maxSize + 1 */ + private static int capAtMaximumSize(int queueSize, int maximumSize) { + return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow + } + + /** + * Creates a new min-max priority queue with default settings: natural order, no + * maximum size, no initial contents, and an initial expected size of 11. + */ + public static > MinMaxPriorityQueue create() { + return new Builder(Ordering.natural()).create(); + } + + /** + * Creates a new min-max priority queue using natural order, no maximum size, + * and initially containing the given elements. + */ + public static > MinMaxPriorityQueue create(Iterable initialContents) { + return new Builder(Ordering.natural()).create(initialContents); + } + + /** + * Creates and returns a new builder, configured to build {@code + * MinMaxPriorityQueue} instances sized appropriately to hold {@code + * expectedSize} elements. + */ + public static Builder expectedSize(int expectedSize) { + return new Builder(Ordering.natural()).expectedSize(expectedSize); + } + + @VisibleForTesting + static int initialQueueSize(int configuredExpectedSize, int maximumSize, Iterable initialContents) { + // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY + int result = (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE) ? DEFAULT_CAPACITY + : configuredExpectedSize; + + // Enlarge to contain initial contents + if (initialContents instanceof Collection) { + int initialSize = ((Collection) initialContents).size(); + result = Math.max(result, initialSize); + } + + // Now cap it at maxSize + 1 + return capAtMaximumSize(result, maximumSize); + } + + @VisibleForTesting + static boolean isEvenLevel(int index) { + int oneBased = index + 1; + checkState(oneBased > 0, "negative index"); + return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO); + } + + /** + * Creates and returns a new builder, configured to build {@code + * MinMaxPriorityQueue} instances that are limited to {@code maximumSize} + * elements. Each time a queue grows beyond this bound, it immediately removes + * its greatest element (according to its comparator), which might be the + * element that was just added. + */ + public static Builder maximumSize(int maximumSize) { + return new Builder(Ordering.natural()).maximumSize(maximumSize); + } + + /** + * Creates and returns a new builder, configured to build {@code + * MinMaxPriorityQueue} instances that use {@code comparator} to determine the + * least and greatest elements. + */ + public static Builder orderedBy(Comparator comparator) { + return new Builder(comparator); + } + private final Heap minHeap; + private final Heap maxHeap; + @VisibleForTesting final int maximumSize; + private Object[] queue; + private int size; + private int modCount; private MinMaxPriorityQueue(Builder builder, int queueSize) { @@ -238,11 +642,6 @@ public final class MinMaxPriorityQueue extends AbstractQueue { this.queue = new Object[queueSize]; } - @Override - public int size() { - return size; - } - /** * Adds the given element to this queue. If this queue has a maximum size, after * adding {@code element} the queue will automatically evict its greatest @@ -267,6 +666,136 @@ public final class MinMaxPriorityQueue extends AbstractQueue { return modified; } + /** Returns ~2x the old capacity if small; ~1.5x otherwise. */ + private int calculateNewCapacity() { + int oldCapacity = queue.length; + int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3); + return capAtMaximumSize(newCapacity, maximumSize); + } + + @VisibleForTesting + int capacity() { + return queue.length; + } + + @Override + public void clear() { + for (int i = 0; i < size; i++) { + queue[i] = null; + } + size = 0; + } + + /** + * Returns the comparator used to order the elements in this queue. Obeys the + * general contract of {@link PriorityQueue#comparator}, but returns + * {@link Ordering#natural} instead of {@code null} to indicate natural + * ordering. + */ + public Comparator comparator() { + return minHeap.ordering; + } + + @SuppressWarnings("unchecked") // we must carefully only allow Es to get in + E elementData(int index) { + return (E) queue[index]; + } + + private MoveDesc fillHole(int index, E toTrickle) { + Heap heap = heapForIndex(index); + // We consider elementData(index) a "hole", and we want to fill it + // with the last element of the heap, toTrickle. + // Since the last element of the heap is from the bottom level, we + // optimistically fill index position with elements from lower levels, + // moving the hole down. In most cases this reduces the number of + // comparisons with toTrickle, but in some cases we will need to bubble it + // all the way up again. + int vacated = heap.fillHoleAt(index); + // Try to see if toTrickle can be bubbled up min levels. + int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle); + if (bubbledTo == vacated) { + // Could not bubble toTrickle up min levels, try moving + // it from min level to max level (or max to min level) and bubble up + // there. + return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle); + } else { + return (bubbledTo < index) ? new MoveDesc(toTrickle, elementData(index)) : null; + } + } + + /** + * Returns the index of the max element. + */ + private int getMaxElementIndex() { + switch (size) { + case 1: + return 0; // The lone element in the queue is the maximum. + case 2: + return 1; // The lone element in the maxHeap is the maximum. + default: + // The max element must sit on the first level of the maxHeap. It is + // actually the *lesser* of the two from the maxHeap's perspective. + return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2; + } + } + + private void growIfNeeded() { + if (size > queue.length) { + int newCapacity = calculateNewCapacity(); + Object[] newQueue = new Object[newCapacity]; + System.arraycopy(queue, 0, newQueue, 0, queue.length); + queue = newQueue; + } + } + + private Heap heapForIndex(int i) { + return isEvenLevel(i) ? minHeap : maxHeap; + } + + /** + * Returns {@code true} if the MinMax heap structure holds. This is only used in + * testing. + * + * TODO(kevinb): move to the test class? + */ + @VisibleForTesting + boolean isIntact() { + for (int i = 1; i < size; i++) { + if (!heapForIndex(i).verifyIndex(i)) { + return false; + } + } + return true; + } + + /** + * Returns an iterator over the elements contained in this collection, in no + * particular order. + * + *

+ * The iterator is fail-fast: If the MinMaxPriorityQueue is modified at + * any time after the iterator is created, in any way except through the + * iterator's own remove method, the iterator will generally throw a + * {@link ConcurrentModificationException}. Thus, in the face of concurrent + * modification, the iterator fails quickly and cleanly, rather than risking + * arbitrary, non-deterministic behavior at an undetermined time in the future. + * + *

+ * Note that the fail-fast behavior of an iterator cannot be guaranteed as it + * is, generally speaking, impossible to make any hard guarantees in the + * presence of unsynchronized concurrent modification. Fail-fast iterators throw + * {@code ConcurrentModificationException} on a best-effort basis. Therefore, it + * would be wrong to write a program that depended on this exception for its + * correctness: the fail-fast behavior of iterators should be used only to + * detect bugs. + * + * @return an iterator over the elements contained in this collection + */ + @Override + public Iterator iterator() { + return new QueueIterator(); + } + /** * Adds the given element to this queue. If this queue has a maximum size, after * adding {@code element} the queue will automatically evict its greatest @@ -287,54 +816,11 @@ public final class MinMaxPriorityQueue extends AbstractQueue { return size <= maximumSize || pollLast() != element; } - @Override - public E poll() { - return isEmpty() ? null : removeAndGet(0); - } - - @SuppressWarnings("unchecked") // we must carefully only allow Es to get in - E elementData(int index) { - return (E) queue[index]; - } - @Override public E peek() { return isEmpty() ? null : elementData(0); } - /** - * Returns the index of the max element. - */ - private int getMaxElementIndex() { - switch (size) { - case 1: - return 0; // The lone element in the queue is the maximum. - case 2: - return 1; // The lone element in the maxHeap is the maximum. - default: - // The max element must sit on the first level of the maxHeap. It is - // actually the *lesser* of the two from the maxHeap's perspective. - return (maxHeap.compareElements(1, 2) <= 0) ? 1 : 2; - } - } - - /** - * Removes and returns the least element of this queue, or returns {@code - * null} if the queue is empty. - */ - public E pollFirst() { - return poll(); - } - - /** - * Removes and returns the least element of this queue. - * - * @throws NoSuchElementException if the queue is empty - */ - public E removeFirst() { - return remove(); - } - /** * Retrieves, but does not remove, the least element of this queue, or returns * {@code null} if the queue is empty. @@ -343,6 +829,27 @@ public final class MinMaxPriorityQueue extends AbstractQueue { return peek(); } + /** + * Retrieves, but does not remove, the greatest element of this queue, or + * returns {@code null} if the queue is empty. + */ + public E peekLast() { + return isEmpty() ? null : elementData(getMaxElementIndex()); + } + + @Override + public E poll() { + return isEmpty() ? null : removeAndGet(0); + } + + /** + * Removes and returns the least element of this queue, or returns {@code + * null} if the queue is empty. + */ + public E pollFirst() { + return poll(); + } + /** * Removes and returns the greatest element of this queue, or returns {@code * null} if the queue is empty. @@ -352,24 +859,15 @@ public final class MinMaxPriorityQueue extends AbstractQueue { } /** - * Removes and returns the greatest element of this queue. - * - * @throws NoSuchElementException if the queue is empty + * Removes and returns the value at {@code index}. */ - public E removeLast() { - if (isEmpty()) { - throw new NoSuchElementException(); - } - return removeAndGet(getMaxElementIndex()); + private E removeAndGet(int index) { + E value = elementData(index); + removeAt(index); + return value; } - /** - * Retrieves, but does not remove, the greatest element of this queue, or - * returns {@code null} if the queue is empty. - */ - public E peekLast() { - return isEmpty() ? null : elementData(getMaxElementIndex()); - } + // Size/capacity-related methods /** * Removes the element at position {@code index}. @@ -417,466 +915,30 @@ public final class MinMaxPriorityQueue extends AbstractQueue { return changes; } - private MoveDesc fillHole(int index, E toTrickle) { - Heap heap = heapForIndex(index); - // We consider elementData(index) a "hole", and we want to fill it - // with the last element of the heap, toTrickle. - // Since the last element of the heap is from the bottom level, we - // optimistically fill index position with elements from lower levels, - // moving the hole down. In most cases this reduces the number of - // comparisons with toTrickle, but in some cases we will need to bubble it - // all the way up again. - int vacated = heap.fillHoleAt(index); - // Try to see if toTrickle can be bubbled up min levels. - int bubbledTo = heap.bubbleUpAlternatingLevels(vacated, toTrickle); - if (bubbledTo == vacated) { - // Could not bubble toTrickle up min levels, try moving - // it from min level to max level (or max to min level) and bubble up - // there. - return heap.tryCrossOverAndBubbleUp(index, vacated, toTrickle); - } else { - return (bubbledTo < index) ? new MoveDesc(toTrickle, elementData(index)) : null; - } - } - - // Returned from removeAt() to iterator.remove() - static class MoveDesc { - final E toTrickle; - final E replaced; - - MoveDesc(E toTrickle, E replaced) { - this.toTrickle = toTrickle; - this.replaced = replaced; - } + /** + * Removes and returns the least element of this queue. + * + * @throws NoSuchElementException if the queue is empty + */ + public E removeFirst() { + return remove(); } /** - * Removes and returns the value at {@code index}. - */ - private E removeAndGet(int index) { - E value = elementData(index); - removeAt(index); - return value; - } - - private Heap heapForIndex(int i) { - return isEvenLevel(i) ? minHeap : maxHeap; - } - - private static final int EVEN_POWERS_OF_TWO = 0x55555555; - private static final int ODD_POWERS_OF_TWO = 0xaaaaaaaa; - - @VisibleForTesting - static boolean isEvenLevel(int index) { - int oneBased = index + 1; - checkState(oneBased > 0, "negative index"); - return (oneBased & EVEN_POWERS_OF_TWO) > (oneBased & ODD_POWERS_OF_TWO); - } - - /** - * Returns {@code true} if the MinMax heap structure holds. This is only used in - * testing. + * Removes and returns the greatest element of this queue. * - * TODO(kevinb): move to the test class? + * @throws NoSuchElementException if the queue is empty */ - @VisibleForTesting - boolean isIntact() { - for (int i = 1; i < size; i++) { - if (!heapForIndex(i).verifyIndex(i)) { - return false; - } + public E removeLast() { + if (isEmpty()) { + throw new NoSuchElementException(); } - return true; - } - - /** - * Each instance of MinMaxPriortyQueue encapsulates two instances of Heap: a - * min-heap and a max-heap. Conceptually, these might each have their own array - * for storage, but for efficiency's sake they are stored interleaved on - * alternate heap levels in the same array (MMPQ.queue). - */ - private class Heap { - final Ordering ordering; - Heap otherHeap; - - Heap(Ordering ordering) { - this.ordering = ordering; - } - - int compareElements(int a, int b) { - return ordering.compare(elementData(a), elementData(b)); - } - - /** - * Tries to move {@code toTrickle} from a min to a max level and bubble up - * there. If it moved before {@code removeIndex} this method returns a pair as - * described in {@link #removeAt}. - */ - MoveDesc tryCrossOverAndBubbleUp(int removeIndex, int vacated, E toTrickle) { - int crossOver = crossOver(vacated, toTrickle); - if (crossOver == vacated) { - return null; - } - // Successfully crossed over from min to max. - // Bubble up max levels. - E parent; - // If toTrickle is moved up to a parent of removeIndex, the parent is - // placed in removeIndex position. We must return that to the iterator so - // that it knows to skip it. - if (crossOver < removeIndex) { - // We crossed over to the parent level in crossOver, so the parent - // has already been moved. - parent = elementData(removeIndex); - } else { - parent = elementData(getParentIndex(removeIndex)); - } - // bubble it up the opposite heap - if (otherHeap.bubbleUpAlternatingLevels(crossOver, toTrickle) < removeIndex) { - return new MoveDesc(toTrickle, parent); - } else { - return null; - } - } - - /** - * Bubbles a value from {@code index} up the appropriate heap if required. - */ - void bubbleUp(int index, E x) { - int crossOver = crossOverUp(index, x); - - Heap heap; - if (crossOver == index) { - heap = this; - } else { - index = crossOver; - heap = otherHeap; - } - heap.bubbleUpAlternatingLevels(index, x); - } - - /** - * Bubbles a value from {@code index} up the levels of this heap, and returns - * the index the element ended up at. - */ - int bubbleUpAlternatingLevels(int index, E x) { - while (index > 2) { - int grandParentIndex = getGrandparentIndex(index); - E e = elementData(grandParentIndex); - if (ordering.compare(e, x) <= 0) { - break; - } - queue[index] = e; - index = grandParentIndex; - } - queue[index] = x; - return index; - } - - /** - * Returns the index of minimum value between {@code index} and - * {@code index + len}, or {@code -1} if {@code index} is greater than - * {@code size}. - */ - int findMin(int index, int len) { - if (index >= size) { - return -1; - } - checkState(index > 0); - int limit = Math.min(index, size - len) + len; - int minIndex = index; - for (int i = index + 1; i < limit; i++) { - if (compareElements(i, minIndex) < 0) { - minIndex = i; - } - } - return minIndex; - } - - /** - * Returns the minimum child or {@code -1} if no child exists. - */ - int findMinChild(int index) { - return findMin(getLeftChildIndex(index), 2); - } - - /** - * Returns the minimum grand child or -1 if no grand child exists. - */ - int findMinGrandChild(int index) { - int leftChildIndex = getLeftChildIndex(index); - if (leftChildIndex < 0) { - return -1; - } - return findMin(getLeftChildIndex(leftChildIndex), 4); - } - - /** - * Moves an element one level up from a min level to a max level (or vice - * versa). Returns the new position of the element. - */ - int crossOverUp(int index, E x) { - if (index == 0) { - queue[0] = x; - return 0; - } - int parentIndex = getParentIndex(index); - E parentElement = elementData(parentIndex); - if (parentIndex != 0) { - // This is a guard for the case of the childless uncle. - // Since the end of the array is actually the middle of the heap, - // a smaller childless uncle can become a child of x when we - // bubble up alternate levels, violating the invariant. - int grandparentIndex = getParentIndex(parentIndex); - int uncleIndex = getRightChildIndex(grandparentIndex); - if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { - E uncleElement = elementData(uncleIndex); - if (ordering.compare(uncleElement, parentElement) < 0) { - parentIndex = uncleIndex; - parentElement = uncleElement; - } - } - } - if (ordering.compare(parentElement, x) < 0) { - queue[index] = parentElement; - queue[parentIndex] = x; - return parentIndex; - } - queue[index] = x; - return index; - } - - /** - * Returns the conceptually correct last element of the heap. - * - *

- * Since the last element of the array is actually in the middle of the sorted - * structure, a childless uncle node could be smaller, which would corrupt the - * invariant if this element becomes the new parent of the uncle. In that case, - * we first switch the last element with its uncle, before returning. - */ - int getCorrectLastElement(E actualLastElement) { - int parentIndex = getParentIndex(size); - if (parentIndex != 0) { - int grandparentIndex = getParentIndex(parentIndex); - int uncleIndex = getRightChildIndex(grandparentIndex); - if (uncleIndex != parentIndex && getLeftChildIndex(uncleIndex) >= size) { - E uncleElement = elementData(uncleIndex); - if (ordering.compare(uncleElement, actualLastElement) < 0) { - queue[uncleIndex] = actualLastElement; - queue[size] = uncleElement; - return uncleIndex; - } - } - } - return size; - } - - /** - * Crosses an element over to the opposite heap by moving it one level down (or - * up if there are no elements below it). - * - * Returns the new position of the element. - */ - int crossOver(int index, E x) { - int minChildIndex = findMinChild(index); - // TODO(kevinb): split the && into two if's and move crossOverUp so it's - // only called when there's no child. - if ((minChildIndex > 0) && (ordering.compare(elementData(minChildIndex), x) < 0)) { - queue[index] = elementData(minChildIndex); - queue[minChildIndex] = x; - return minChildIndex; - } - return crossOverUp(index, x); - } - - /** - * Fills the hole at {@code index} by moving in the least of its grandchildren - * to this position, then recursively filling the new hole created. - * - * @return the position of the new hole (where the lowest grandchild moved from, - * that had no grandchild to replace it) - */ - int fillHoleAt(int index) { - int minGrandchildIndex; - while ((minGrandchildIndex = findMinGrandChild(index)) > 0) { - queue[index] = elementData(minGrandchildIndex); - index = minGrandchildIndex; - } - return index; - } - - private boolean verifyIndex(int i) { - if ((getLeftChildIndex(i) < size) && (compareElements(i, getLeftChildIndex(i)) > 0)) { - return false; - } - if ((getRightChildIndex(i) < size) && (compareElements(i, getRightChildIndex(i)) > 0)) { - return false; - } - if ((i > 0) && (compareElements(i, getParentIndex(i)) > 0)) { - return false; - } - if ((i > 2) && (compareElements(getGrandparentIndex(i), i) > 0)) { - return false; - } - return true; - } - - // These would be static if inner classes could have static members. - - private int getLeftChildIndex(int i) { - return i * 2 + 1; - } - - private int getRightChildIndex(int i) { - return i * 2 + 2; - } - - private int getParentIndex(int i) { - return (i - 1) / 2; - } - - private int getGrandparentIndex(int i) { - return getParentIndex(getParentIndex(i)); // (i - 3) / 4 - } - } - - /** - * Iterates the elements of the queue in no particular order. - * - * If the underlying queue is modified during iteration an exception will be - * thrown. - */ - private class QueueIterator implements Iterator { - private int cursor = -1; - private int expectedModCount = modCount; - private Queue forgetMeNot; - private List skipMe; - private E lastFromForgetMeNot; - private boolean canRemove; - - @Override - public boolean hasNext() { - checkModCount(); - return (nextNotInSkipMe(cursor + 1) < size()) || ((forgetMeNot != null) && !forgetMeNot.isEmpty()); - } - - @Override - public E next() { - checkModCount(); - int tempCursor = nextNotInSkipMe(cursor + 1); - if (tempCursor < size()) { - cursor = tempCursor; - canRemove = true; - return elementData(cursor); - } else if (forgetMeNot != null) { - cursor = size(); - lastFromForgetMeNot = forgetMeNot.poll(); - if (lastFromForgetMeNot != null) { - canRemove = true; - return lastFromForgetMeNot; - } - } - throw new NoSuchElementException("iterator moved past last element in queue."); - } - - @Override - public void remove() { - checkRemove(canRemove); - checkModCount(); - canRemove = false; - expectedModCount++; - if (cursor < size()) { - MoveDesc moved = removeAt(cursor); - if (moved != null) { - if (forgetMeNot == null) { - forgetMeNot = new ArrayDeque(); - skipMe = new ArrayList(3); - } - forgetMeNot.add(moved.toTrickle); - skipMe.add(moved.replaced); - } - cursor--; - } else { // we must have set lastFromForgetMeNot in next() - checkState(removeExact(lastFromForgetMeNot)); - lastFromForgetMeNot = null; - } - } - - // Finds only this exact instance, not others that are equals() - private boolean containsExact(Iterable elements, E target) { - for (E element : elements) { - if (element == target) { - return true; - } - } - return false; - } - - // Removes only this exact instance, not others that are equals() - boolean removeExact(Object target) { - for (int i = 0; i < size; i++) { - if (queue[i] == target) { - removeAt(i); - return true; - } - } - return false; - } - - void checkModCount() { - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - } - - /** - * Returns the index of the first element after {@code c} that is not in - * {@code skipMe} and returns {@code size()} if there is no such element. - */ - private int nextNotInSkipMe(int c) { - if (skipMe != null) { - while (c < size() && containsExact(skipMe, elementData(c))) { - c++; - } - } - return c; - } - } - - /** - * Returns an iterator over the elements contained in this collection, in no - * particular order. - * - *

- * The iterator is fail-fast: If the MinMaxPriorityQueue is modified at - * any time after the iterator is created, in any way except through the - * iterator's own remove method, the iterator will generally throw a - * {@link ConcurrentModificationException}. Thus, in the face of concurrent - * modification, the iterator fails quickly and cleanly, rather than risking - * arbitrary, non-deterministic behavior at an undetermined time in the future. - * - *

- * Note that the fail-fast behavior of an iterator cannot be guaranteed as it - * is, generally speaking, impossible to make any hard guarantees in the - * presence of unsynchronized concurrent modification. Fail-fast iterators throw - * {@code ConcurrentModificationException} on a best-effort basis. Therefore, it - * would be wrong to write a program that depended on this exception for its - * correctness: the fail-fast behavior of iterators should be used only to - * detect bugs. - * - * @return an iterator over the elements contained in this collection - */ - @Override - public Iterator iterator() { - return new QueueIterator(); + return removeAndGet(getMaxElementIndex()); } @Override - public void clear() { - for (int i = 0; i < size; i++) { - queue[i] = null; - } - size = 0; + public int size() { + return size; } @Override @@ -885,60 +947,4 @@ public final class MinMaxPriorityQueue extends AbstractQueue { System.arraycopy(queue, 0, copyTo, 0, size); return copyTo; } - - /** - * Returns the comparator used to order the elements in this queue. Obeys the - * general contract of {@link PriorityQueue#comparator}, but returns - * {@link Ordering#natural} instead of {@code null} to indicate natural - * ordering. - */ - public Comparator comparator() { - return minHeap.ordering; - } - - @VisibleForTesting - int capacity() { - return queue.length; - } - - // Size/capacity-related methods - - private static final int DEFAULT_CAPACITY = 11; - - @VisibleForTesting - static int initialQueueSize(int configuredExpectedSize, int maximumSize, Iterable initialContents) { - // Start with what they said, if they said it, otherwise DEFAULT_CAPACITY - int result = (configuredExpectedSize == Builder.UNSET_EXPECTED_SIZE) ? DEFAULT_CAPACITY - : configuredExpectedSize; - - // Enlarge to contain initial contents - if (initialContents instanceof Collection) { - int initialSize = ((Collection) initialContents).size(); - result = Math.max(result, initialSize); - } - - // Now cap it at maxSize + 1 - return capAtMaximumSize(result, maximumSize); - } - - private void growIfNeeded() { - if (size > queue.length) { - int newCapacity = calculateNewCapacity(); - Object[] newQueue = new Object[newCapacity]; - System.arraycopy(queue, 0, newQueue, 0, queue.length); - queue = newQueue; - } - } - - /** Returns ~2x the old capacity if small; ~1.5x otherwise. */ - private int calculateNewCapacity() { - int oldCapacity = queue.length; - int newCapacity = (oldCapacity < 64) ? (oldCapacity + 1) * 2 : IntMath.checkedMultiply(oldCapacity / 2, 3); - return capAtMaximumSize(newCapacity, maximumSize); - } - - /** There's no reason for the queueSize to ever be more than maxSize + 1 */ - private static int capAtMaximumSize(int queueSize, int maximumSize) { - return Math.min(queueSize - 1, maximumSize) + 1; // don't overflow - } } diff --git a/src/main/java/com/google/common/collect/Multimap.java b/src/main/java/com/google/common/collect/Multimap.java index 0c3f3c6f..2f0e031d 100644 --- a/src/main/java/com/google/common/collect/Multimap.java +++ b/src/main/java/com/google/common/collect/Multimap.java @@ -186,191 +186,6 @@ import com.google.common.annotations.GwtCompatible; public interface Multimap { // Query Operations - /** - * Returns the number of key-value pairs in this multimap. - * - *

- * Note: this method does not return the number of distinct keys - * in the multimap, which is given by {@code keySet().size()} or - * {@code asMap().size()}. See the opening section of the {@link Multimap} class - * documentation for clarification. - */ - int size(); - - /** - * Returns {@code true} if this multimap contains no key-value pairs. Equivalent - * to {@code size() == 0}, but can in some cases be more efficient. - */ - boolean isEmpty(); - - /** - * Returns {@code true} if this multimap contains at least one key-value pair - * with the key {@code key}. - */ - boolean containsKey(@Nullable Object key); - - /** - * Returns {@code true} if this multimap contains at least one key-value pair - * with the value {@code value}. - */ - boolean containsValue(@Nullable Object value); - - /** - * Returns {@code true} if this multimap contains at least one key-value pair - * with the key {@code key} and the value {@code value}. - */ - boolean containsEntry(@Nullable Object key, @Nullable Object value); - - // Modification Operations - - /** - * Stores a key-value pair in this multimap. - * - *

- * Some multimap implementations allow duplicate key-value pairs, in which case - * {@code put} always adds a new key-value pair and increases the multimap size - * by 1. Other implementations prohibit duplicates, and storing a key-value pair - * that's already in the multimap has no effect. - * - * @return {@code true} if the method increased the size of the multimap, or - * {@code false} if the multimap already contained the key-value pair - * and doesn't allow duplicates - */ - boolean put(@Nullable K key, @Nullable V value); - - /** - * Removes a single key-value pair with the key {@code key} and the value - * {@code value} from this multimap, if such exists. If multiple key-value pairs - * in the multimap fit this description, which one is removed is unspecified. - * - * @return {@code true} if the multimap changed - */ - boolean remove(@Nullable Object key, @Nullable Object value); - - // Bulk Operations - - /** - * Stores a key-value pair in this multimap for each of {@code values}, all - * using the same key, {@code key}. Equivalent to (but expected to be more - * efficient than): - * - *

-	 *    {@code
-	 * 
-	 *   for (V value : values) {
-	 *     put(key, value);
-	 *   }}
-	 * 
- * - *

- * In particular, this is a no-op if {@code values} is empty. - * - * @return {@code true} if the multimap changed - */ - boolean putAll(@Nullable K key, Iterable values); - - /** - * Stores all key-value pairs of {@code multimap} in this multimap, in the order - * returned by {@code multimap.entries()}. - * - * @return {@code true} if the multimap changed - */ - boolean putAll(Multimap multimap); - - /** - * Stores a collection of values with the same key, replacing any existing - * values for that key. - * - *

- * If {@code values} is empty, this is equivalent to {@link #removeAll(Object) - * removeAll(key)}. - * - * @return the collection of replaced values, or an empty collection if no - * values were previously associated with the key. The collection - * may be modifiable, but updating it will have no effect on the - * multimap. - */ - Collection replaceValues(@Nullable K key, Iterable values); - - /** - * Removes all values associated with the key {@code key}. - * - *

- * Once this method returns, {@code key} will not be mapped to any values, so it - * will not appear in {@link #keySet()}, {@link #asMap()}, or any other views. - * - * @return the values that were removed (possibly empty). The returned - * collection may be modifiable, but updating it will have no - * effect on the multimap. - */ - Collection removeAll(@Nullable Object key); - - /** - * Removes all key-value pairs from the multimap, leaving it - * {@linkplain #isEmpty empty}. - */ - void clear(); - - // Views - - /** - * Returns a view collection of the values associated with {@code key} in this - * multimap, if any. Note that when {@code containsKey(key)} is false, this - * returns an empty collection, not {@code null}. - * - *

- * Changes to the returned collection will update the underlying multimap, and - * vice versa. - */ - Collection get(@Nullable K key); - - /** - * Returns a view collection of all distinct keys contained in this - * multimap. Note that the key set contains a key if and only if this multimap - * maps that key to at least one value. - * - *

- * Changes to the returned set will update the underlying multimap, and vice - * versa. However, adding to the returned set is not possible. - */ - Set keySet(); - - /** - * Returns a view collection containing the key from each key-value pair in this - * multimap, without collapsing duplicates. This collection has the same - * size as this multimap, and {@code keys().count(k) == - * get(k).size()} for all {@code k}. - * - *

- * Changes to the returned multiset will update the underlying multimap, and - * vice versa. However, adding to the returned collection is not - * possible. - */ - Multiset keys(); - - /** - * Returns a view collection containing the value from each key-value - * pair contained in this multimap, without collapsing duplicates (so {@code - * values().size() == size()}). - * - *

- * Changes to the returned collection will update the underlying multimap, and - * vice versa. However, adding to the returned collection is not - * possible. - */ - Collection values(); - - /** - * Returns a view collection of all key-value pairs contained in this multimap, - * as {@link Map.Entry} instances. - * - *

- * Changes to the returned collection or the entries it contains will update the - * underlying multimap, and vice versa. However, adding to the returned - * collection is not possible. - */ - Collection> entries(); - /** * Returns a view of this multimap as a {@code Map} from each distinct key to * the nonempty collection of that key's associated values. Note that @@ -386,7 +201,42 @@ public interface Multimap { */ Map> asMap(); - // Comparison and hashing + /** + * Removes all key-value pairs from the multimap, leaving it + * {@linkplain #isEmpty empty}. + */ + void clear(); + + /** + * Returns {@code true} if this multimap contains at least one key-value pair + * with the key {@code key} and the value {@code value}. + */ + boolean containsEntry(@Nullable Object key, @Nullable Object value); + + /** + * Returns {@code true} if this multimap contains at least one key-value pair + * with the key {@code key}. + */ + boolean containsKey(@Nullable Object key); + + /** + * Returns {@code true} if this multimap contains at least one key-value pair + * with the value {@code value}. + */ + boolean containsValue(@Nullable Object value); + + // Modification Operations + + /** + * Returns a view collection of all key-value pairs contained in this multimap, + * as {@link Map.Entry} instances. + * + *

+ * Changes to the returned collection or the entries it contains will update the + * underlying multimap, and vice versa. However, adding to the returned + * collection is not possible. + */ + Collection> entries(); /** * Compares the specified object with this multimap for equality. Two multimaps @@ -409,6 +259,19 @@ public interface Multimap { @Override boolean equals(@Nullable Object obj); + // Bulk Operations + + /** + * Returns a view collection of the values associated with {@code key} in this + * multimap, if any. Note that when {@code containsKey(key)} is false, this + * returns an empty collection, not {@code null}. + * + *

+ * Changes to the returned collection will update the underlying multimap, and + * vice versa. + */ + Collection get(@Nullable K key); + /** * Returns the hash code for this multimap. * @@ -418,4 +281,142 @@ public interface Multimap { */ @Override int hashCode(); + + /** + * Returns {@code true} if this multimap contains no key-value pairs. Equivalent + * to {@code size() == 0}, but can in some cases be more efficient. + */ + boolean isEmpty(); + + /** + * Returns a view collection containing the key from each key-value pair in this + * multimap, without collapsing duplicates. This collection has the same + * size as this multimap, and {@code keys().count(k) == + * get(k).size()} for all {@code k}. + * + *

+ * Changes to the returned multiset will update the underlying multimap, and + * vice versa. However, adding to the returned collection is not + * possible. + */ + Multiset keys(); + + /** + * Returns a view collection of all distinct keys contained in this + * multimap. Note that the key set contains a key if and only if this multimap + * maps that key to at least one value. + * + *

+ * Changes to the returned set will update the underlying multimap, and vice + * versa. However, adding to the returned set is not possible. + */ + Set keySet(); + + // Views + + /** + * Stores a key-value pair in this multimap. + * + *

+ * Some multimap implementations allow duplicate key-value pairs, in which case + * {@code put} always adds a new key-value pair and increases the multimap size + * by 1. Other implementations prohibit duplicates, and storing a key-value pair + * that's already in the multimap has no effect. + * + * @return {@code true} if the method increased the size of the multimap, or + * {@code false} if the multimap already contained the key-value pair + * and doesn't allow duplicates + */ + boolean put(@Nullable K key, @Nullable V value); + + /** + * Stores a key-value pair in this multimap for each of {@code values}, all + * using the same key, {@code key}. Equivalent to (but expected to be more + * efficient than): + * + *

+	 *    {@code
+	 * 
+	 * for (V value : values) {
+	 * 	put(key, value);
+	 * }
+	 * }
+	 * 
+ * + *

+ * In particular, this is a no-op if {@code values} is empty. + * + * @return {@code true} if the multimap changed + */ + boolean putAll(@Nullable K key, Iterable values); + + /** + * Stores all key-value pairs of {@code multimap} in this multimap, in the order + * returned by {@code multimap.entries()}. + * + * @return {@code true} if the multimap changed + */ + boolean putAll(Multimap multimap); + + /** + * Removes a single key-value pair with the key {@code key} and the value + * {@code value} from this multimap, if such exists. If multiple key-value pairs + * in the multimap fit this description, which one is removed is unspecified. + * + * @return {@code true} if the multimap changed + */ + boolean remove(@Nullable Object key, @Nullable Object value); + + /** + * Removes all values associated with the key {@code key}. + * + *

+ * Once this method returns, {@code key} will not be mapped to any values, so it + * will not appear in {@link #keySet()}, {@link #asMap()}, or any other views. + * + * @return the values that were removed (possibly empty). The returned + * collection may be modifiable, but updating it will have no + * effect on the multimap. + */ + Collection removeAll(@Nullable Object key); + + /** + * Stores a collection of values with the same key, replacing any existing + * values for that key. + * + *

+ * If {@code values} is empty, this is equivalent to {@link #removeAll(Object) + * removeAll(key)}. + * + * @return the collection of replaced values, or an empty collection if no + * values were previously associated with the key. The collection + * may be modifiable, but updating it will have no effect on the + * multimap. + */ + Collection replaceValues(@Nullable K key, Iterable values); + + // Comparison and hashing + + /** + * Returns the number of key-value pairs in this multimap. + * + *

+ * Note: this method does not return the number of distinct keys + * in the multimap, which is given by {@code keySet().size()} or + * {@code asMap().size()}. See the opening section of the {@link Multimap} class + * documentation for clarification. + */ + int size(); + + /** + * Returns a view collection containing the value from each key-value + * pair contained in this multimap, without collapsing duplicates (so {@code + * values().size() == size()}). + * + *

+ * Changes to the returned collection will update the underlying multimap, and + * vice versa. However, adding to the returned collection is not + * possible. + */ + Collection values(); } diff --git a/src/main/java/com/google/common/collect/MultimapBuilder.java b/src/main/java/com/google/common/collect/MultimapBuilder.java index 1ca9caa7..11de862d 100644 --- a/src/main/java/com/google/common/collect/MultimapBuilder.java +++ b/src/main/java/com/google/common/collect/MultimapBuilder.java @@ -81,11 +81,303 @@ public abstract class MultimapBuilder { * same technique. */ - private MultimapBuilder() { + private static final class ArrayListSupplier implements Supplier>, Serializable { + private final int expectedValuesPerKey; + + ArrayListSupplier(int expectedValuesPerKey) { + this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); + } + + @Override + public List get() { + return new ArrayList(expectedValuesPerKey); + } + } + + private static final class EnumSetSupplier> implements Supplier>, Serializable { + private final Class clazz; + + EnumSetSupplier(Class clazz) { + this.clazz = checkNotNull(clazz); + } + + @Override + public Set get() { + return EnumSet.noneOf(clazz); + } + } + + private static final class HashSetSupplier implements Supplier>, Serializable { + private final int expectedValuesPerKey; + + HashSetSupplier(int expectedValuesPerKey) { + this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); + } + + @Override + public Set get() { + return new HashSet(expectedValuesPerKey); + } + } + + private static final class LinkedHashSetSupplier implements Supplier>, Serializable { + private final int expectedValuesPerKey; + + LinkedHashSetSupplier(int expectedValuesPerKey) { + this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); + } + + @Override + public Set get() { + return new LinkedHashSet(expectedValuesPerKey); + } + } + + private enum LinkedListSupplier implements Supplier> { + INSTANCE; + + public static Supplier> instance() { + // Each call generates a fresh LinkedList, which can serve as a List for any + // V. + @SuppressWarnings({ "rawtypes", "unchecked" }) + Supplier> result = (Supplier) INSTANCE; + return result; + } + + @Override + public List get() { + return new LinkedList(); + } + } + + /** + * A specialization of {@link MultimapBuilder} that generates + * {@link ListMultimap} instances. + */ + public abstract static class ListMultimapBuilder extends MultimapBuilder { + ListMultimapBuilder() { + } + + @Override + public abstract ListMultimap build(); + + @Override + public ListMultimap build(Multimap multimap) { + return (ListMultimap) super.build(multimap); + } + } + + /** + * An intermediate stage in a {@link MultimapBuilder} in which the key-value + * collection map implementation has been specified, but the value collection + * implementation has not. + * + * @param The upper bound on the key type of the generated multimap. + */ + public abstract static class MultimapBuilderWithKeys { + + private static final int DEFAULT_EXPECTED_VALUES_PER_KEY = 2; + + MultimapBuilderWithKeys() { + } + + /** + * Uses an {@link ArrayList} to store value collections. + */ + public ListMultimapBuilder arrayListValues() { + return arrayListValues(DEFAULT_EXPECTED_VALUES_PER_KEY); + } + + /** + * Uses an {@link ArrayList} to store value collections, initialized to expect + * the specified number of values per key. + * + * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} + */ + public ListMultimapBuilder arrayListValues(final int expectedValuesPerKey) { + checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); + return new ListMultimapBuilder() { + @Override + public ListMultimap build() { + return Multimaps.newListMultimap(MultimapBuilderWithKeys.this.createMap(), + new ArrayListSupplier(expectedValuesPerKey)); + } + }; + } + + abstract Map> createMap(); + + /** + * Uses an {@link EnumSet} to store value collections. + */ + public > SetMultimapBuilder enumSetValues(final Class valueClass) { + checkNotNull(valueClass, "valueClass"); + return new SetMultimapBuilder() { + @Override + public SetMultimap build() { + // V must actually be V0, since enums are effectively final + // (their subclasses are inaccessible) + @SuppressWarnings({ "unchecked", "rawtypes" }) + Supplier> factory = (Supplier) new EnumSetSupplier(valueClass); + return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), factory); + } + }; + } + + /** + * Uses a {@link HashSet} to store value collections. + */ + public SetMultimapBuilder hashSetValues() { + return hashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY); + } + + /** + * Uses a {@link HashSet} to store value collections, initialized to expect the + * specified number of values per key. + * + * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} + */ + public SetMultimapBuilder hashSetValues(final int expectedValuesPerKey) { + checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); + return new SetMultimapBuilder() { + @Override + public SetMultimap build() { + return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), + new HashSetSupplier(expectedValuesPerKey)); + } + }; + } + + /** + * Uses a {@link LinkedHashSet} to store value collections. + */ + public SetMultimapBuilder linkedHashSetValues() { + return linkedHashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY); + } + + /** + * Uses a {@link LinkedHashSet} to store value collections, initialized to + * expect the specified number of values per key. + * + * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} + */ + public SetMultimapBuilder linkedHashSetValues(final int expectedValuesPerKey) { + checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); + return new SetMultimapBuilder() { + @Override + public SetMultimap build() { + return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), + new LinkedHashSetSupplier(expectedValuesPerKey)); + } + }; + } + + /** + * Uses a {@link LinkedList} to store value collections. + */ + public ListMultimapBuilder linkedListValues() { + return new ListMultimapBuilder() { + @Override + public ListMultimap build() { + return Multimaps.newListMultimap(MultimapBuilderWithKeys.this.createMap(), + LinkedListSupplier.instance()); + } + }; + } + + /** + * Uses a naturally-ordered {@link TreeSet} to store value collections. + */ + @SuppressWarnings("rawtypes") + public SortedSetMultimapBuilder treeSetValues() { + return treeSetValues(Ordering.natural()); + } + + /** + * Uses a {@link TreeSet} ordered by the specified comparator to store value + * collections. + * + *

+ * Multimaps generated by the resulting builder will not be serializable if + * {@code comparator} is not serializable. + */ + public SortedSetMultimapBuilder treeSetValues(final Comparator comparator) { + checkNotNull(comparator, "comparator"); + return new SortedSetMultimapBuilder() { + @Override + public SortedSetMultimap build() { + return Multimaps.newSortedSetMultimap(MultimapBuilderWithKeys.this.createMap(), + new TreeSetSupplier(comparator)); + } + }; + } + } + + /** + * A specialization of {@link MultimapBuilder} that generates + * {@link SetMultimap} instances. + */ + public abstract static class SetMultimapBuilder extends MultimapBuilder { + SetMultimapBuilder() { + } + + @Override + public abstract SetMultimap build(); + + @Override + public SetMultimap build(Multimap multimap) { + return (SetMultimap) super.build(multimap); + } + } + + /** + * A specialization of {@link MultimapBuilder} that generates + * {@link SortedSetMultimap} instances. + */ + public abstract static class SortedSetMultimapBuilder extends SetMultimapBuilder { + SortedSetMultimapBuilder() { + } + + @Override + public abstract SortedSetMultimap build(); + + @Override + public SortedSetMultimap build(Multimap multimap) { + return (SortedSetMultimap) super.build(multimap); + } + } + + private static final class TreeSetSupplier implements Supplier>, Serializable { + private final Comparator comparator; + + TreeSetSupplier(Comparator comparator) { + this.comparator = checkNotNull(comparator); + } + + @Override + public SortedSet get() { + return new TreeSet(comparator); + } } private static final int DEFAULT_EXPECTED_KEYS = 8; + /** + * Uses an {@link EnumMap} to map keys to value collections. + */ + public static > MultimapBuilderWithKeys enumKeys(final Class keyClass) { + checkNotNull(keyClass); + return new MultimapBuilderWithKeys() { + @SuppressWarnings("unchecked") + @Override + Map> createMap() { + // K must actually be K0, since enums are effectively final + // (their subclasses are inaccessible) + return (Map>) new EnumMap>(keyClass); + } + }; + } + /** * Uses a {@link HashMap} to map keys to value collections. */ @@ -192,248 +484,7 @@ public abstract class MultimapBuilder { }; } - /** - * Uses an {@link EnumMap} to map keys to value collections. - */ - public static > MultimapBuilderWithKeys enumKeys(final Class keyClass) { - checkNotNull(keyClass); - return new MultimapBuilderWithKeys() { - @SuppressWarnings("unchecked") - @Override - Map> createMap() { - // K must actually be K0, since enums are effectively final - // (their subclasses are inaccessible) - return (Map>) new EnumMap>(keyClass); - } - }; - } - - private static final class ArrayListSupplier implements Supplier>, Serializable { - private final int expectedValuesPerKey; - - ArrayListSupplier(int expectedValuesPerKey) { - this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); - } - - @Override - public List get() { - return new ArrayList(expectedValuesPerKey); - } - } - - private enum LinkedListSupplier implements Supplier> { - INSTANCE; - - public static Supplier> instance() { - // Each call generates a fresh LinkedList, which can serve as a List for any - // V. - @SuppressWarnings({ "rawtypes", "unchecked" }) - Supplier> result = (Supplier) INSTANCE; - return result; - } - - @Override - public List get() { - return new LinkedList(); - } - } - - private static final class HashSetSupplier implements Supplier>, Serializable { - private final int expectedValuesPerKey; - - HashSetSupplier(int expectedValuesPerKey) { - this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); - } - - @Override - public Set get() { - return new HashSet(expectedValuesPerKey); - } - } - - private static final class LinkedHashSetSupplier implements Supplier>, Serializable { - private final int expectedValuesPerKey; - - LinkedHashSetSupplier(int expectedValuesPerKey) { - this.expectedValuesPerKey = checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); - } - - @Override - public Set get() { - return new LinkedHashSet(expectedValuesPerKey); - } - } - - private static final class TreeSetSupplier implements Supplier>, Serializable { - private final Comparator comparator; - - TreeSetSupplier(Comparator comparator) { - this.comparator = checkNotNull(comparator); - } - - @Override - public SortedSet get() { - return new TreeSet(comparator); - } - } - - private static final class EnumSetSupplier> implements Supplier>, Serializable { - private final Class clazz; - - EnumSetSupplier(Class clazz) { - this.clazz = checkNotNull(clazz); - } - - @Override - public Set get() { - return EnumSet.noneOf(clazz); - } - } - - /** - * An intermediate stage in a {@link MultimapBuilder} in which the key-value - * collection map implementation has been specified, but the value collection - * implementation has not. - * - * @param The upper bound on the key type of the generated multimap. - */ - public abstract static class MultimapBuilderWithKeys { - - private static final int DEFAULT_EXPECTED_VALUES_PER_KEY = 2; - - MultimapBuilderWithKeys() { - } - - abstract Map> createMap(); - - /** - * Uses an {@link ArrayList} to store value collections. - */ - public ListMultimapBuilder arrayListValues() { - return arrayListValues(DEFAULT_EXPECTED_VALUES_PER_KEY); - } - - /** - * Uses an {@link ArrayList} to store value collections, initialized to expect - * the specified number of values per key. - * - * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} - */ - public ListMultimapBuilder arrayListValues(final int expectedValuesPerKey) { - checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); - return new ListMultimapBuilder() { - @Override - public ListMultimap build() { - return Multimaps.newListMultimap(MultimapBuilderWithKeys.this.createMap(), - new ArrayListSupplier(expectedValuesPerKey)); - } - }; - } - - /** - * Uses a {@link LinkedList} to store value collections. - */ - public ListMultimapBuilder linkedListValues() { - return new ListMultimapBuilder() { - @Override - public ListMultimap build() { - return Multimaps.newListMultimap(MultimapBuilderWithKeys.this.createMap(), - LinkedListSupplier.instance()); - } - }; - } - - /** - * Uses a {@link HashSet} to store value collections. - */ - public SetMultimapBuilder hashSetValues() { - return hashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY); - } - - /** - * Uses a {@link HashSet} to store value collections, initialized to expect the - * specified number of values per key. - * - * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} - */ - public SetMultimapBuilder hashSetValues(final int expectedValuesPerKey) { - checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); - return new SetMultimapBuilder() { - @Override - public SetMultimap build() { - return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), - new HashSetSupplier(expectedValuesPerKey)); - } - }; - } - - /** - * Uses a {@link LinkedHashSet} to store value collections. - */ - public SetMultimapBuilder linkedHashSetValues() { - return linkedHashSetValues(DEFAULT_EXPECTED_VALUES_PER_KEY); - } - - /** - * Uses a {@link LinkedHashSet} to store value collections, initialized to - * expect the specified number of values per key. - * - * @throws IllegalArgumentException if {@code expectedValuesPerKey < 0} - */ - public SetMultimapBuilder linkedHashSetValues(final int expectedValuesPerKey) { - checkNonnegative(expectedValuesPerKey, "expectedValuesPerKey"); - return new SetMultimapBuilder() { - @Override - public SetMultimap build() { - return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), - new LinkedHashSetSupplier(expectedValuesPerKey)); - } - }; - } - - /** - * Uses a naturally-ordered {@link TreeSet} to store value collections. - */ - @SuppressWarnings("rawtypes") - public SortedSetMultimapBuilder treeSetValues() { - return treeSetValues(Ordering.natural()); - } - - /** - * Uses a {@link TreeSet} ordered by the specified comparator to store value - * collections. - * - *

- * Multimaps generated by the resulting builder will not be serializable if - * {@code comparator} is not serializable. - */ - public SortedSetMultimapBuilder treeSetValues(final Comparator comparator) { - checkNotNull(comparator, "comparator"); - return new SortedSetMultimapBuilder() { - @Override - public SortedSetMultimap build() { - return Multimaps.newSortedSetMultimap(MultimapBuilderWithKeys.this.createMap(), - new TreeSetSupplier(comparator)); - } - }; - } - - /** - * Uses an {@link EnumSet} to store value collections. - */ - public > SetMultimapBuilder enumSetValues(final Class valueClass) { - checkNotNull(valueClass, "valueClass"); - return new SetMultimapBuilder() { - @Override - public SetMultimap build() { - // V must actually be V0, since enums are effectively final - // (their subclasses are inaccessible) - @SuppressWarnings({ "unchecked", "rawtypes" }) - Supplier> factory = (Supplier) new EnumSetSupplier(valueClass); - return Multimaps.newSetMultimap(MultimapBuilderWithKeys.this.createMap(), factory); - } - }; - } + private MultimapBuilder() { } /** @@ -450,55 +501,4 @@ public abstract class MultimapBuilder { result.putAll(multimap); return result; } - - /** - * A specialization of {@link MultimapBuilder} that generates - * {@link ListMultimap} instances. - */ - public abstract static class ListMultimapBuilder extends MultimapBuilder { - ListMultimapBuilder() { - } - - @Override - public abstract ListMultimap build(); - - @Override - public ListMultimap build(Multimap multimap) { - return (ListMultimap) super.build(multimap); - } - } - - /** - * A specialization of {@link MultimapBuilder} that generates - * {@link SetMultimap} instances. - */ - public abstract static class SetMultimapBuilder extends MultimapBuilder { - SetMultimapBuilder() { - } - - @Override - public abstract SetMultimap build(); - - @Override - public SetMultimap build(Multimap multimap) { - return (SetMultimap) super.build(multimap); - } - } - - /** - * A specialization of {@link MultimapBuilder} that generates - * {@link SortedSetMultimap} instances. - */ - public abstract static class SortedSetMultimapBuilder extends SetMultimapBuilder { - SortedSetMultimapBuilder() { - } - - @Override - public abstract SortedSetMultimap build(); - - @Override - public SortedSetMultimap build(Multimap multimap) { - return (SortedSetMultimap) super.build(multimap); - } - } } diff --git a/src/main/java/com/google/common/collect/Multimaps.java b/src/main/java/com/google/common/collect/Multimaps.java index 13efddaa..c1855311 100644 --- a/src/main/java/com/google/common/collect/Multimaps.java +++ b/src/main/java/com/google/common/collect/Multimaps.java @@ -64,145 +64,93 @@ import com.google.common.collect.Maps.EntryTransformer; */ @GwtCompatible(emulated = true) public final class Multimaps { - private Multimaps() { - } - /** - * Creates a new {@code Multimap} backed by {@code map}, whose internal value - * collections are generated by {@code factory}. - * - * Warning: do not use this method when the collections returned by - * {@code factory} implement either {@link List} or {@code Set}! Use the more - * specific method {@link #newListMultimap}, {@link #newSetMultimap} or - * {@link #newSortedSetMultimap} instead, to avoid very surprising behavior from - * {@link Multimap#equals}. - * - *

- * The {@code factory}-generated and {@code map} classes determine the multimap - * iteration order. They also specify the behavior of the {@code equals}, - * {@code hashCode}, and {@code toString} methods for the multimap and its - * returned views. However, the multimap's {@code get} method returns instances - * of a different class than {@code factory.get()} does. - * - *

- * The multimap is serializable if {@code map}, {@code factory}, the collections - * generated by {@code factory}, and the multimap contents are all serializable. - * - *

- * The multimap is not threadsafe when any concurrent operations update the - * multimap, even if {@code map} and the instances generated by {@code factory} - * are. Concurrent read operations will work correctly. To allow concurrent - * update operations, wrap the multimap with a call to - * {@link #synchronizedMultimap}. - * - *

- * Call this method only when the simpler methods - * {@link ArrayListMultimap#create()}, {@link HashMultimap#create()}, - * {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()}, - * {@link TreeMultimap#create()}, and - * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. - * - *

- * Note: the multimap assumes complete ownership over of {@code map} and the - * collections returned by {@code factory}. Those objects should not be manually - * updated and they should not use soft, weak, or phantom references. - * - * @param map place to store the mapping from each key to its corresponding - * values - * @param factory supplier of new, empty collections that will each hold all - * values for a given key - * @throws IllegalArgumentException if {@code map} is not empty + * A skeleton implementation of {@link Multimap#asMap()}. */ - public static Multimap newMultimap(Map> map, - final Supplier> factory) { - return new CustomMultimap(map, factory); - } + static final class AsMap extends Maps.ImprovedAbstractMap> { + class EntrySet extends Maps.EntrySet> { + @Override + public Iterator>> iterator() { + return Maps.asMapEntryIterator(multimap.keySet(), new Function>() { + @Override + public Collection apply(K key) { + return multimap.get(key); + } + }); + } - private static class CustomMultimap extends AbstractMapBasedMultimap { - transient Supplier> factory; + @Override + Map> map() { + return AsMap.this; + } - CustomMultimap(Map> map, Supplier> factory) { - super(map); - this.factory = checkNotNull(factory); + @Override + public boolean remove(Object o) { + if (!contains(o)) { + return false; + } + Map.Entry entry = (Map.Entry) o; + removeValuesForKey(entry.getKey()); + return true; + } + } + + private final Multimap multimap; + + AsMap(Multimap multimap) { + this.multimap = checkNotNull(multimap); } @Override - protected Collection createCollection() { - return factory.get(); + public void clear() { + multimap.clear(); } - // can't use Serialization writeMultimap and populateMultimap methods since - // there's no way to generate the empty backing map. - - /** @serialData the factory and the backing map */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(factory); - stream.writeObject(backingMap()); + @Override + public boolean containsKey(Object key) { + return multimap.containsKey(key); } - @GwtIncompatible("java.io.ObjectInputStream") - @SuppressWarnings("unchecked") // reading data stored by writeObject - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - factory = (Supplier>) stream.readObject(); - Map> map = (Map>) stream.readObject(); - setMap(map); + @Override + protected Set>> createEntrySet() { + return new EntrySet(); } - @GwtIncompatible("java serialization not supported") - private static final long serialVersionUID = 0; - } + @SuppressWarnings("unchecked") + @Override + public Collection get(Object key) { + return containsKey(key) ? multimap.get((K) key) : null; + } - /** - * Creates a new {@code ListMultimap} that uses the provided map and factory. It - * can generate a multimap based on arbitrary {@link Map} and {@link List} - * classes. - * - *

- * The {@code factory}-generated and {@code map} classes determine the multimap - * iteration order. They also specify the behavior of the {@code equals}, - * {@code hashCode}, and {@code toString} methods for the multimap and its - * returned views. The multimap's {@code get}, {@code - * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} - * lists if the factory does. However, the multimap's {@code get} method returns - * instances of a different class than does {@code factory.get()}. - * - *

- * The multimap is serializable if {@code map}, {@code factory}, the lists - * generated by {@code factory}, and the multimap contents are all serializable. - * - *

- * The multimap is not threadsafe when any concurrent operations update the - * multimap, even if {@code map} and the instances generated by {@code factory} - * are. Concurrent read operations will work correctly. To allow concurrent - * update operations, wrap the multimap with a call to - * {@link #synchronizedListMultimap}. - * - *

- * Call this method only when the simpler methods - * {@link ArrayListMultimap#create()} and {@link LinkedListMultimap#create()} - * won't suffice. - * - *

- * Note: the multimap assumes complete ownership over of {@code map} and the - * lists returned by {@code factory}. Those objects should not be manually - * updated, they should be empty when provided, and they should not use soft, - * weak, or phantom references. - * - * @param map place to store the mapping from each key to its corresponding - * values - * @param factory supplier of new, empty lists that will each hold all values - * for a given key - * @throws IllegalArgumentException if {@code map} is not empty - */ - public static ListMultimap newListMultimap(Map> map, - final Supplier> factory) { - return new CustomListMultimap(map, factory); + @Override + public boolean isEmpty() { + return multimap.isEmpty(); + } + + @Override + public Set keySet() { + return multimap.keySet(); + } + + @Override + public Collection remove(Object key) { + return containsKey(key) ? multimap.removeAll(key) : null; + } + + void removeValuesForKey(Object key) { + multimap.keySet().remove(key); + } + + @Override + public int size() { + return multimap.keySet().size(); + } } private static class CustomListMultimap extends AbstractListMultimap { + @GwtIncompatible("java serialization not supported") + private static final long serialVersionUID = 0; + transient Supplier> factory; CustomListMultimap(Map> map, Supplier> factory) { @@ -215,14 +163,6 @@ public final class Multimaps { return factory.get(); } - /** @serialData the factory and the backing map */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(factory); - stream.writeObject(backingMap()); - } - @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { @@ -232,55 +172,56 @@ public final class Multimaps { setMap(map); } - @GwtIncompatible("java serialization not supported") - private static final long serialVersionUID = 0; + /** @serialData the factory and the backing map */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(factory); + stream.writeObject(backingMap()); + } } - /** - * Creates a new {@code SetMultimap} that uses the provided map and factory. It - * can generate a multimap based on arbitrary {@link Map} and {@link Set} - * classes. - * - *

- * The {@code factory}-generated and {@code map} classes determine the multimap - * iteration order. They also specify the behavior of the {@code equals}, - * {@code hashCode}, and {@code toString} methods for the multimap and its - * returned views. However, the multimap's {@code get} method returns instances - * of a different class than {@code factory.get()} does. - * - *

- * The multimap is serializable if {@code map}, {@code factory}, the sets - * generated by {@code factory}, and the multimap contents are all serializable. - * - *

- * The multimap is not threadsafe when any concurrent operations update the - * multimap, even if {@code map} and the instances generated by {@code factory} - * are. Concurrent read operations will work correctly. To allow concurrent - * update operations, wrap the multimap with a call to - * {@link #synchronizedSetMultimap}. - * - *

- * Call this method only when the simpler methods {@link HashMultimap#create()}, - * {@link LinkedHashMultimap#create()}, {@link TreeMultimap#create()}, and - * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. - * - *

- * Note: the multimap assumes complete ownership over of {@code map} and the - * sets returned by {@code factory}. Those objects should not be manually - * updated and they should not use soft, weak, or phantom references. - * - * @param map place to store the mapping from each key to its corresponding - * values - * @param factory supplier of new, empty sets that will each hold all values for - * a given key - * @throws IllegalArgumentException if {@code map} is not empty - */ - public static SetMultimap newSetMultimap(Map> map, - final Supplier> factory) { - return new CustomSetMultimap(map, factory); + private static class CustomMultimap extends AbstractMapBasedMultimap { + @GwtIncompatible("java serialization not supported") + private static final long serialVersionUID = 0; + + transient Supplier> factory; + + CustomMultimap(Map> map, Supplier> factory) { + super(map); + this.factory = checkNotNull(factory); + } + + // can't use Serialization writeMultimap and populateMultimap methods since + // there's no way to generate the empty backing map. + + @Override + protected Collection createCollection() { + return factory.get(); + } + + @GwtIncompatible("java.io.ObjectInputStream") + @SuppressWarnings("unchecked") // reading data stored by writeObject + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + factory = (Supplier>) stream.readObject(); + Map> map = (Map>) stream.readObject(); + setMap(map); + } + + /** @serialData the factory and the backing map */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(factory); + stream.writeObject(backingMap()); + } } private static class CustomSetMultimap extends AbstractSetMultimap { + @GwtIncompatible("not needed in emulated source") + private static final long serialVersionUID = 0; + transient Supplier> factory; CustomSetMultimap(Map> map, Supplier> factory) { @@ -293,14 +234,6 @@ public final class Multimaps { return factory.get(); } - /** @serialData the factory and the backing map */ - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { - stream.defaultWriteObject(); - stream.writeObject(factory); - stream.writeObject(backingMap()); - } - @GwtIncompatible("java.io.ObjectInputStream") @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { @@ -310,55 +243,20 @@ public final class Multimaps { setMap(map); } - @GwtIncompatible("not needed in emulated source") - private static final long serialVersionUID = 0; - } - - /** - * Creates a new {@code SortedSetMultimap} that uses the provided map and - * factory. It can generate a multimap based on arbitrary {@link Map} and - * {@link SortedSet} classes. - * - *

- * The {@code factory}-generated and {@code map} classes determine the multimap - * iteration order. They also specify the behavior of the {@code equals}, - * {@code hashCode}, and {@code toString} methods for the multimap and its - * returned views. However, the multimap's {@code get} method returns instances - * of a different class than {@code factory.get()} does. - * - *

- * The multimap is serializable if {@code map}, {@code factory}, the sets - * generated by {@code factory}, and the multimap contents are all serializable. - * - *

- * The multimap is not threadsafe when any concurrent operations update the - * multimap, even if {@code map} and the instances generated by {@code factory} - * are. Concurrent read operations will work correctly. To allow concurrent - * update operations, wrap the multimap with a call to - * {@link #synchronizedSortedSetMultimap}. - * - *

- * Call this method only when the simpler methods {@link TreeMultimap#create()} - * and {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. - * - *

- * Note: the multimap assumes complete ownership over of {@code map} and the - * sets returned by {@code factory}. Those objects should not be manually - * updated and they should not use soft, weak, or phantom references. - * - * @param map place to store the mapping from each key to its corresponding - * values - * @param factory supplier of new, empty sorted sets that will each hold all - * values for a given key - * @throws IllegalArgumentException if {@code map} is not empty - */ - public static SortedSetMultimap newSortedSetMultimap(Map> map, - final Supplier> factory) { - return new CustomSortedSetMultimap(map, factory); + /** @serialData the factory and the backing map */ + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { + stream.defaultWriteObject(); + stream.writeObject(factory); + stream.writeObject(backingMap()); + } } private static class CustomSortedSetMultimap extends AbstractSortedSetMultimap { + @GwtIncompatible("not needed in emulated source") + private static final long serialVersionUID = 0; transient Supplier> factory; + transient Comparator valueComparator; CustomSortedSetMultimap(Map> map, Supplier> factory) { @@ -372,6 +270,16 @@ public final class Multimaps { return factory.get(); } + @GwtIncompatible("java.io.ObjectInputStream") + @SuppressWarnings("unchecked") // reading data stored by writeObject + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + factory = (Supplier>) stream.readObject(); + valueComparator = factory.get().comparator(); + Map> map = (Map>) stream.readObject(); + setMap(map); + } + @Override public Comparator valueComparator() { return valueComparator; @@ -384,143 +292,500 @@ public final class Multimaps { stream.writeObject(factory); stream.writeObject(backingMap()); } + } - @GwtIncompatible("java.io.ObjectInputStream") - @SuppressWarnings("unchecked") // reading data stored by writeObject - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - factory = (Supplier>) stream.readObject(); - valueComparator = factory.get().comparator(); - Map> map = (Map>) stream.readObject(); - setMap(map); + /** + * A skeleton implementation of {@link Multimap#entries()}. + */ + abstract static class Entries extends AbstractCollection> { + @Override + public void clear() { + multimap().clear(); } - @GwtIncompatible("not needed in emulated source") + @Override + public boolean contains(@Nullable Object o) { + if (o instanceof Map.Entry) { + Map.Entry entry = (Map.Entry) o; + return multimap().containsEntry(entry.getKey(), entry.getValue()); + } + return false; + } + + abstract Multimap multimap(); + + @Override + public boolean remove(@Nullable Object o) { + if (o instanceof Map.Entry) { + Map.Entry entry = (Map.Entry) o; + return multimap().remove(entry.getKey(), entry.getValue()); + } + return false; + } + + @Override + public int size() { + return multimap().size(); + } + } + + static class Keys extends AbstractMultiset { + class KeysEntrySet extends Multisets.EntrySet { + @Override + public boolean contains(@Nullable Object o) { + if (o instanceof Multiset.Entry) { + Multiset.Entry entry = (Multiset.Entry) o; + Collection collection = multimap.asMap().get(entry.getElement()); + return collection != null && collection.size() == entry.getCount(); + } + return false; + } + + @Override + public boolean isEmpty() { + return multimap.isEmpty(); + } + + @Override + public Iterator> iterator() { + return entryIterator(); + } + + @Override + Multiset multiset() { + return Keys.this; + } + + @Override + public boolean remove(@Nullable Object o) { + if (o instanceof Multiset.Entry) { + Multiset.Entry entry = (Multiset.Entry) o; + Collection collection = multimap.asMap().get(entry.getElement()); + if (collection != null && collection.size() == entry.getCount()) { + collection.clear(); + return true; + } + } + return false; + } + + @Override + public int size() { + return distinctElements(); + } + } + + final Multimap multimap; + + Keys(Multimap multimap) { + this.multimap = multimap; + } + + @Override + public void clear() { + multimap.clear(); + } + + @Override + public boolean contains(@Nullable Object element) { + return multimap.containsKey(element); + } + + @Override + public int count(@Nullable Object element) { + Collection values = Maps.safeGet(multimap.asMap(), element); + return (values == null) ? 0 : values.size(); + } + + @Override + Set> createEntrySet() { + return new KeysEntrySet(); + } + + @Override + int distinctElements() { + return multimap.asMap().size(); + } + + @Override + public Set elementSet() { + return multimap.keySet(); + } + + @Override + Iterator> entryIterator() { + return new TransformedIterator>, Multiset.Entry>( + multimap.asMap().entrySet().iterator()) { + @Override + Multiset.Entry transform(final Map.Entry> backingEntry) { + return new Multisets.AbstractEntry() { + @Override + public int getCount() { + return backingEntry.getValue().size(); + } + + @Override + public K getElement() { + return backingEntry.getKey(); + } + }; + } + }; + } + + @Override + public Iterator iterator() { + return Maps.keyIterator(multimap.entries().iterator()); + } + + @Override + public int remove(@Nullable Object element, int occurrences) { + checkNonnegative(occurrences, "occurrences"); + if (occurrences == 0) { + return count(element); + } + + Collection values = Maps.safeGet(multimap.asMap(), element); + + if (values == null) { + return 0; + } + + int oldCount = values.size(); + if (occurrences >= oldCount) { + values.clear(); + } else { + Iterator iterator = values.iterator(); + for (int i = 0; i < occurrences; i++) { + iterator.next(); + iterator.remove(); + } + } + return oldCount; + } + } + + /** @see Multimaps#forMap */ + private static class MapMultimap extends AbstractMultimap implements SetMultimap, Serializable { + private static final long serialVersionUID = 7845222491160860175L; + + final Map map; + + MapMultimap(Map map) { + this.map = checkNotNull(map); + } + + @Override + public void clear() { + map.clear(); + } + + @Override + public boolean containsEntry(Object key, Object value) { + return map.entrySet().contains(Maps.immutableEntry(key, value)); + } + + @Override + public boolean containsKey(Object key) { + return map.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return map.containsValue(value); + } + + @Override + Map> createAsMap() { + return new AsMap(this); + } + + @Override + public Set> entries() { + return map.entrySet(); + } + + @Override + Iterator> entryIterator() { + return map.entrySet().iterator(); + } + + @Override + public Set get(final K key) { + return new Sets.ImprovedAbstractSet() { + @Override + public Iterator iterator() { + return new Iterator() { + int i; + + @Override + public boolean hasNext() { + return (i == 0) && map.containsKey(key); + } + + @Override + public V next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + i++; + return map.get(key); + } + + @Override + public void remove() { + checkRemove(i == 1); + i = -1; + map.remove(key); + } + }; + } + + @Override + public int size() { + return map.containsKey(key) ? 1 : 0; + } + }; + } + + @Override + public int hashCode() { + return map.hashCode(); + } + + @Override + public Set keySet() { + return map.keySet(); + } + + @Override + public boolean put(K key, V value) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean putAll(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean putAll(Multimap multimap) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean remove(Object key, Object value) { + return map.entrySet().remove(Maps.immutableEntry(key, value)); + } + + @Override + public Set removeAll(Object key) { + Set values = new HashSet(2); + if (!map.containsKey(key)) { + return values; + } + values.add(map.remove(key)); + return values; + } + + @Override + public Set replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public Collection values() { + return map.values(); + } + } + + private static final class TransformedEntriesListMultimap extends TransformedEntriesMultimap + implements ListMultimap { + + TransformedEntriesListMultimap(ListMultimap fromMultimap, + EntryTransformer transformer) { + super(fromMultimap, transformer); + } + + @Override + public List get(K key) { + return transform(key, fromMultimap.get(key)); + } + + @SuppressWarnings("unchecked") + @Override + public List removeAll(Object key) { + return transform((K) key, fromMultimap.removeAll(key)); + } + + @Override + public List replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + @Override + List transform(K key, Collection values) { + return Lists.transform((List) values, Maps.asValueToValueFunction(transformer, key)); + } + } + + private static class TransformedEntriesMultimap extends AbstractMultimap { + final Multimap fromMultimap; + final EntryTransformer transformer; + + TransformedEntriesMultimap(Multimap fromMultimap, + final EntryTransformer transformer) { + this.fromMultimap = checkNotNull(fromMultimap); + this.transformer = checkNotNull(transformer); + } + + @Override + public void clear() { + fromMultimap.clear(); + } + + @Override + public boolean containsKey(Object key) { + return fromMultimap.containsKey(key); + } + + @Override + Map> createAsMap() { + return Maps.transformEntries(fromMultimap.asMap(), + new EntryTransformer, Collection>() { + @Override + public Collection transformEntry(K key, Collection value) { + return transform(key, value); + } + }); + } + + @Override + Collection createValues() { + return Collections2.transform(fromMultimap.entries(), Maps.asEntryToValueFunction(transformer)); + } + + @Override + Iterator> entryIterator() { + return Iterators.transform(fromMultimap.entries().iterator(), + Maps.asEntryToEntryFunction(transformer)); + } + + @Override + public Collection get(final K key) { + return transform(key, fromMultimap.get(key)); + } + + @Override + public boolean isEmpty() { + return fromMultimap.isEmpty(); + } + + @Override + public Multiset keys() { + return fromMultimap.keys(); + } + + @Override + public Set keySet() { + return fromMultimap.keySet(); + } + + @Override + public boolean put(K key, V2 value) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean putAll(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean putAll(Multimap multimap) { + throw new UnsupportedOperationException(); + } + + @SuppressWarnings("unchecked") + @Override + public boolean remove(Object key, Object value) { + return get((K) key).remove(value); + } + + @SuppressWarnings("unchecked") + @Override + public Collection removeAll(Object key) { + return transform((K) key, fromMultimap.removeAll(key)); + } + + @Override + public Collection replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); + } + + @Override + public int size() { + return fromMultimap.size(); + } + + Collection transform(K key, Collection values) { + Function function = Maps.asValueToValueFunction(transformer, key); + if (values instanceof List) { + return Lists.transform((List) values, function); + } else { + return Collections2.transform(values, function); + } + } + } + + private static class UnmodifiableListMultimap extends UnmodifiableMultimap + implements ListMultimap { private static final long serialVersionUID = 0; - } - /** - * Copies each key-value mapping in {@code source} into {@code dest}, with its - * key and value reversed. - * - *

- * If {@code source} is an {@link ImmutableMultimap}, consider using - * {@link ImmutableMultimap#inverse} instead. - * - * @param source any multimap - * @param dest the multimap to copy into; usually empty - * @return {@code dest} - */ - public static > M invertFrom(Multimap source, M dest) { - checkNotNull(dest); - for (Map.Entry entry : source.entries()) { - dest.put(entry.getValue(), entry.getKey()); + UnmodifiableListMultimap(ListMultimap delegate) { + super(delegate); } - return dest; - } - /** - * Returns a synchronized (thread-safe) multimap backed by the specified - * multimap. In order to guarantee serial access, it is critical that all - * access to the backing multimap is accomplished through the returned multimap. - * - *

- * It is imperative that the user manually synchronize on the returned multimap - * when accessing any of its collection views: - * - *

-	 *    {@code
-	 *
-	 *   Multimap multimap = Multimaps.synchronizedMultimap(
-	 *       HashMultimap.create());
-	 *   ...
-	 *   Collection values = multimap.get(key);  // Needn't be in synchronized block
-	 *   ...
-	 *   synchronized (multimap) {  // Synchronizing on multimap, not values!
-	 *     Iterator i = values.iterator(); // Must be in synchronized block
-	 *     while (i.hasNext()) {
-	 *       foo(i.next());
-	 *     }
-	 *   }}
-	 * 
- * - *

- * Failure to follow this advice may result in non-deterministic behavior. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that aren't - * synchronized. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param multimap the multimap to be wrapped in a synchronized view - * @return a synchronized view of the specified multimap - */ - public static Multimap synchronizedMultimap(Multimap multimap) { - return Synchronized.multimap(multimap, null); - } - - /** - * Returns an unmodifiable view of the specified multimap. Query operations on - * the returned multimap "read through" to the specified multimap, and attempts - * to modify the returned multimap, either directly or through the multimap's - * views, result in an {@code UnsupportedOperationException}. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are - * modifiable. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param delegate the multimap for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified multimap - */ - public static Multimap unmodifiableMultimap(Multimap delegate) { - if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) { - return delegate; + @Override + public ListMultimap delegate() { + return (ListMultimap) super.delegate(); } - return new UnmodifiableMultimap(delegate); - } - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ - @Deprecated - public static Multimap unmodifiableMultimap(ImmutableMultimap delegate) { - return checkNotNull(delegate); + @Override + public List get(K key) { + return Collections.unmodifiableList(delegate().get(key)); + } + + @Override + public List removeAll(Object key) { + throw new UnsupportedOperationException(); + } + + @Override + public List replaceValues(K key, Iterable values) { + throw new UnsupportedOperationException(); + } } private static class UnmodifiableMultimap extends ForwardingMultimap implements Serializable { + private static final long serialVersionUID = 0; final Multimap delegate; transient Collection> entries; transient Multiset keys; transient Set keySet; transient Collection values; + transient Map> map; UnmodifiableMultimap(final Multimap delegate) { this.delegate = checkNotNull(delegate); } - @Override - protected Multimap delegate() { - return delegate; - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - @Override public Map> asMap() { Map> result = map; @@ -536,6 +801,16 @@ public final class Multimaps { return result; } + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + @Override + protected Multimap delegate() { + return delegate; + } + @Override public Collection> entries() { Collection> result = entries; @@ -606,40 +881,11 @@ public final class Multimaps { } return result; } - - private static final long serialVersionUID = 0; - } - - private static class UnmodifiableListMultimap extends UnmodifiableMultimap - implements ListMultimap { - UnmodifiableListMultimap(ListMultimap delegate) { - super(delegate); - } - - @Override - public ListMultimap delegate() { - return (ListMultimap) super.delegate(); - } - - @Override - public List get(K key) { - return Collections.unmodifiableList(delegate().get(key)); - } - - @Override - public List removeAll(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public List replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - private static final long serialVersionUID = 0; } private static class UnmodifiableSetMultimap extends UnmodifiableMultimap implements SetMultimap { + private static final long serialVersionUID = 0; + UnmodifiableSetMultimap(SetMultimap delegate) { super(delegate); } @@ -649,6 +895,11 @@ public final class Multimaps { return (SetMultimap) super.delegate(); } + @Override + public Set> entries() { + return Maps.unmodifiableEntrySet(delegate().entries()); + } + @Override public Set get(K key) { /* @@ -658,11 +909,6 @@ public final class Multimaps { return Collections.unmodifiableSet(delegate().get(key)); } - @Override - public Set> entries() { - return Maps.unmodifiableEntrySet(delegate().entries()); - } - @Override public Set removeAll(Object key) { throw new UnsupportedOperationException(); @@ -672,12 +918,12 @@ public final class Multimaps { public Set replaceValues(K key, Iterable values) { throw new UnsupportedOperationException(); } - - private static final long serialVersionUID = 0; } private static class UnmodifiableSortedSetMultimap extends UnmodifiableSetMultimap implements SortedSetMultimap { + private static final long serialVersionUID = 0; + UnmodifiableSortedSetMultimap(SortedSetMultimap delegate) { super(delegate); } @@ -706,192 +952,6 @@ public final class Multimaps { public Comparator valueComparator() { return delegate().valueComparator(); } - - private static final long serialVersionUID = 0; - } - - /** - * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the - * specified multimap. - * - *

- * You must follow the warnings described in {@link #synchronizedMultimap}. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param multimap the multimap to be wrapped - * @return a synchronized view of the specified multimap - */ - public static SetMultimap synchronizedSetMultimap(SetMultimap multimap) { - return Synchronized.setMultimap(multimap, null); - } - - /** - * Returns an unmodifiable view of the specified {@code SetMultimap}. Query - * operations on the returned multimap "read through" to the specified multimap, - * and attempts to modify the returned multimap, either directly or through the - * multimap's views, result in an {@code UnsupportedOperationException}. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are - * modifiable. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param delegate the multimap for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified multimap - */ - public static SetMultimap unmodifiableSetMultimap(SetMultimap delegate) { - if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) { - return delegate; - } - return new UnmodifiableSetMultimap(delegate); - } - - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ - @Deprecated - public static SetMultimap unmodifiableSetMultimap(ImmutableSetMultimap delegate) { - return checkNotNull(delegate); - } - - /** - * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by the - * specified multimap. - * - *

- * You must follow the warnings described in {@link #synchronizedMultimap}. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param multimap the multimap to be wrapped - * @return a synchronized view of the specified multimap - */ - public static SortedSetMultimap synchronizedSortedSetMultimap(SortedSetMultimap multimap) { - return Synchronized.sortedSetMultimap(multimap, null); - } - - /** - * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. - * Query operations on the returned multimap "read through" to the specified - * multimap, and attempts to modify the returned multimap, either directly or - * through the multimap's views, result in an - * {@code UnsupportedOperationException}. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are - * modifiable. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param delegate the multimap for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified multimap - */ - public static SortedSetMultimap unmodifiableSortedSetMultimap(SortedSetMultimap delegate) { - if (delegate instanceof UnmodifiableSortedSetMultimap) { - return delegate; - } - return new UnmodifiableSortedSetMultimap(delegate); - } - - /** - * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the - * specified multimap. - * - *

- * You must follow the warnings described in {@link #synchronizedMultimap}. - * - * @param multimap the multimap to be wrapped - * @return a synchronized view of the specified multimap - */ - public static ListMultimap synchronizedListMultimap(ListMultimap multimap) { - return Synchronized.listMultimap(multimap, null); - } - - /** - * Returns an unmodifiable view of the specified {@code ListMultimap}. Query - * operations on the returned multimap "read through" to the specified multimap, - * and attempts to modify the returned multimap, either directly or through the - * multimap's views, result in an {@code UnsupportedOperationException}. - * - *

- * Note that the generated multimap's {@link Multimap#removeAll} and - * {@link Multimap#replaceValues} methods return collections that are - * modifiable. - * - *

- * The returned multimap will be serializable if the specified multimap is - * serializable. - * - * @param delegate the multimap for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified multimap - */ - public static ListMultimap unmodifiableListMultimap(ListMultimap delegate) { - if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) { - return delegate; - } - return new UnmodifiableListMultimap(delegate); - } - - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ - @Deprecated - public static ListMultimap unmodifiableListMultimap(ImmutableListMultimap delegate) { - return checkNotNull(delegate); - } - - /** - * Returns an unmodifiable view of the specified collection, preserving the - * interface for instances of {@code SortedSet}, {@code Set}, {@code List} and - * {@code Collection}, in that order of preference. - * - * @param collection the collection for which to return an unmodifiable view - * @return an unmodifiable view of the collection - */ - private static Collection unmodifiableValueCollection(Collection collection) { - if (collection instanceof SortedSet) { - return Collections.unmodifiableSortedSet((SortedSet) collection); - } else if (collection instanceof Set) { - return Collections.unmodifiableSet((Set) collection); - } else if (collection instanceof List) { - return Collections.unmodifiableList((List) collection); - } - return Collections.unmodifiableCollection(collection); - } - - /** - * Returns an unmodifiable view of the specified collection of entries. The - * {@link Entry#setValue} operation throws an - * {@link UnsupportedOperationException}. If the specified collection is a - * {@code - * Set}, the returned collection is also a {@code Set}. - * - * @param entries the entries for which to return an unmodifiable view - * @return an unmodifiable view of the entries - */ - private static Collection> unmodifiableEntries(Collection> entries) { - if (entries instanceof Set) { - return Maps.unmodifiableEntrySet((Set>) entries); - } - return new Maps.UnmodifiableEntries(Collections.unmodifiableCollection(entries)); } /** @@ -907,6 +967,17 @@ public final class Multimaps { return (Map>) (Map) multimap.asMap(); } + /** + * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for parity + * with the other more strongly-typed {@code asMap()} implementations. + * + * @since 15.0 + */ + @Beta + public static Map> asMap(Multimap multimap) { + return multimap.asMap(); + } + /** * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected * from {@code Map>} to {@code Map>}. @@ -933,15 +1004,351 @@ public final class Multimaps { return (Map>) (Map) multimap.asMap(); } + static boolean equalsImpl(Multimap multimap, @Nullable Object object) { + if (object == multimap) { + return true; + } + if (object instanceof Multimap) { + Multimap that = (Multimap) object; + return multimap.asMap().equals(that.asMap()); + } + return false; + } + /** - * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for parity - * with the other more strongly-typed {@code asMap()} implementations. + * Returns a multimap containing the mappings in {@code unfiltered} that satisfy + * a predicate. The returned multimap is a live view of {@code unfiltered}; + * changes to one affect the other. * - * @since 15.0 + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a key/value pair that doesn't satisfy the predicate, + * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} + * methods throw an {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose keys satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code entryPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. + * + * @since 11.0 */ - @Beta - public static Map> asMap(Multimap multimap) { - return multimap.asMap(); + public static Multimap filterEntries(Multimap unfiltered, + Predicate> entryPredicate) { + checkNotNull(entryPredicate); + if (unfiltered instanceof SetMultimap) { + return filterEntries((SetMultimap) unfiltered, entryPredicate); + } + return (unfiltered instanceof FilteredMultimap) + ? filterFiltered((FilteredMultimap) unfiltered, entryPredicate) + : new FilteredEntryMultimap(checkNotNull(unfiltered), entryPredicate); + } + + /** + * Returns a multimap containing the mappings in {@code unfiltered} that satisfy + * a predicate. The returned multimap is a live view of {@code unfiltered}; + * changes to one affect the other. + * + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a key/value pair that doesn't satisfy the predicate, + * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} + * methods throw an {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose keys satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code entryPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. + * + * @since 14.0 + */ + public static SetMultimap filterEntries(SetMultimap unfiltered, + Predicate> entryPredicate) { + checkNotNull(entryPredicate); + return (unfiltered instanceof FilteredSetMultimap) + ? filterFiltered((FilteredSetMultimap) unfiltered, entryPredicate) + : new FilteredEntrySetMultimap(checkNotNull(unfiltered), entryPredicate); + } + + /** + * Support removal operations when filtering a filtered multimap. Since a + * filtered multimap has iterators that don't support remove, passing one to the + * FilteredEntryMultimap constructor would lead to a multimap whose removal + * operations would fail. This method combines the predicates to avoid that + * problem. + */ + private static Multimap filterFiltered(FilteredMultimap multimap, + Predicate> entryPredicate) { + Predicate> predicate = Predicates.and(multimap.entryPredicate(), entryPredicate); + return new FilteredEntryMultimap(multimap.unfiltered(), predicate); + } + + /** + * Support removal operations when filtering a filtered multimap. Since a + * filtered multimap has iterators that don't support remove, passing one to the + * FilteredEntryMultimap constructor would lead to a multimap whose removal + * operations would fail. This method combines the predicates to avoid that + * problem. + */ + private static SetMultimap filterFiltered(FilteredSetMultimap multimap, + Predicate> entryPredicate) { + Predicate> predicate = Predicates.and(multimap.entryPredicate(), entryPredicate); + return new FilteredEntrySetMultimap(multimap.unfiltered(), predicate); + } + + /** + * Returns a multimap containing the mappings in {@code unfiltered} whose keys + * satisfy a predicate. The returned multimap is a live view of + * {@code unfiltered}; changes to one affect the other. + * + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a key that doesn't satisfy the predicate, the multimap's + * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose keys satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code keyPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 14.0 + */ + public static ListMultimap filterKeys(ListMultimap unfiltered, + final Predicate keyPredicate) { + if (unfiltered instanceof FilteredKeyListMultimap) { + FilteredKeyListMultimap prev = (FilteredKeyListMultimap) unfiltered; + return new FilteredKeyListMultimap(prev.unfiltered(), + Predicates.and(prev.keyPredicate, keyPredicate)); + } else { + return new FilteredKeyListMultimap(unfiltered, keyPredicate); + } + } + + /** + * Returns a multimap containing the mappings in {@code unfiltered} whose keys + * satisfy a predicate. The returned multimap is a live view of + * {@code unfiltered}; changes to one affect the other. + * + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a key that doesn't satisfy the predicate, the multimap's + * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose keys satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code keyPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 11.0 + */ + public static Multimap filterKeys(Multimap unfiltered, final Predicate keyPredicate) { + if (unfiltered instanceof SetMultimap) { + return filterKeys((SetMultimap) unfiltered, keyPredicate); + } else if (unfiltered instanceof ListMultimap) { + return filterKeys((ListMultimap) unfiltered, keyPredicate); + } else if (unfiltered instanceof FilteredKeyMultimap) { + FilteredKeyMultimap prev = (FilteredKeyMultimap) unfiltered; + return new FilteredKeyMultimap(prev.unfiltered, Predicates.and(prev.keyPredicate, keyPredicate)); + } else if (unfiltered instanceof FilteredMultimap) { + FilteredMultimap prev = (FilteredMultimap) unfiltered; + return filterFiltered(prev, Maps.keyPredicateOnEntries(keyPredicate)); + } else { + return new FilteredKeyMultimap(unfiltered, keyPredicate); + } + } + + /** + * Returns a multimap containing the mappings in {@code unfiltered} whose keys + * satisfy a predicate. The returned multimap is a live view of + * {@code unfiltered}; changes to one affect the other. + * + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a key that doesn't satisfy the predicate, the multimap's + * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose keys satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code keyPredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 14.0 + */ + public static SetMultimap filterKeys(SetMultimap unfiltered, + final Predicate keyPredicate) { + if (unfiltered instanceof FilteredKeySetMultimap) { + FilteredKeySetMultimap prev = (FilteredKeySetMultimap) unfiltered; + return new FilteredKeySetMultimap(prev.unfiltered(), Predicates.and(prev.keyPredicate, keyPredicate)); + } else if (unfiltered instanceof FilteredSetMultimap) { + FilteredSetMultimap prev = (FilteredSetMultimap) unfiltered; + return filterFiltered(prev, Maps.keyPredicateOnEntries(keyPredicate)); + } else { + return new FilteredKeySetMultimap(unfiltered, keyPredicate); + } + } + + /** + * Returns a multimap containing the mappings in {@code unfiltered} whose values + * satisfy a predicate. The returned multimap is a live view of + * {@code unfiltered}; changes to one affect the other. + * + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a value that doesn't satisfy the predicate, the multimap's + * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose value satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code valuePredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 11.0 + */ + public static Multimap filterValues(Multimap unfiltered, + final Predicate valuePredicate) { + return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + } + + /** + * Returns a multimap containing the mappings in {@code unfiltered} whose values + * satisfy a predicate. The returned multimap is a live view of + * {@code unfiltered}; changes to one affect the other. + * + *

+ * The resulting multimap's views have iterators that don't support + * {@code remove()}, but all other methods are supported by the multimap and its + * views. When adding a value that doesn't satisfy the predicate, the multimap's + * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an + * {@link IllegalArgumentException}. + * + *

+ * When methods such as {@code removeAll()} and {@code clear()} are called on + * the filtered multimap or its views, only mappings whose value satisfy the + * filter will be removed from the underlying multimap. + * + *

+ * The returned multimap isn't threadsafe or serializable, even if + * {@code unfiltered} is. + * + *

+ * Many of the filtered multimap's methods, such as {@code size()}, iterate + * across every key/value mapping in the underlying multimap and determine which + * satisfy the filter. When a live view is not needed, it may be faster + * to copy the filtered multimap and use the copy. + * + *

+ * Warning: {@code valuePredicate} must be consistent with equals, + * as documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. + * + * @since 14.0 + */ + public static SetMultimap filterValues(SetMultimap unfiltered, + final Predicate valuePredicate) { + return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); } /** @@ -967,533 +1374,6 @@ public final class Multimaps { return new MapMultimap(map); } - /** @see Multimaps#forMap */ - private static class MapMultimap extends AbstractMultimap implements SetMultimap, Serializable { - final Map map; - - MapMultimap(Map map) { - this.map = checkNotNull(map); - } - - @Override - public int size() { - return map.size(); - } - - @Override - public boolean containsKey(Object key) { - return map.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - return map.containsValue(value); - } - - @Override - public boolean containsEntry(Object key, Object value) { - return map.entrySet().contains(Maps.immutableEntry(key, value)); - } - - @Override - public Set get(final K key) { - return new Sets.ImprovedAbstractSet() { - @Override - public Iterator iterator() { - return new Iterator() { - int i; - - @Override - public boolean hasNext() { - return (i == 0) && map.containsKey(key); - } - - @Override - public V next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - i++; - return map.get(key); - } - - @Override - public void remove() { - checkRemove(i == 1); - i = -1; - map.remove(key); - } - }; - } - - @Override - public int size() { - return map.containsKey(key) ? 1 : 0; - } - }; - } - - @Override - public boolean put(K key, V value) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean putAll(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean putAll(Multimap multimap) { - throw new UnsupportedOperationException(); - } - - @Override - public Set replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean remove(Object key, Object value) { - return map.entrySet().remove(Maps.immutableEntry(key, value)); - } - - @Override - public Set removeAll(Object key) { - Set values = new HashSet(2); - if (!map.containsKey(key)) { - return values; - } - values.add(map.remove(key)); - return values; - } - - @Override - public void clear() { - map.clear(); - } - - @Override - public Set keySet() { - return map.keySet(); - } - - @Override - public Collection values() { - return map.values(); - } - - @Override - public Set> entries() { - return map.entrySet(); - } - - @Override - Iterator> entryIterator() { - return map.entrySet().iterator(); - } - - @Override - Map> createAsMap() { - return new AsMap(this); - } - - @Override - public int hashCode() { - return map.hashCode(); - } - - private static final long serialVersionUID = 7845222491160860175L; - } - - /** - * Returns a view of a multimap where each value is transformed by a function. - * All other properties of the multimap, such as iteration order, are left - * intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	Multimap multimap = ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
-	 * 	Function square = new Function() {
-	 * 		public String apply(Integer in) {
-	 * 			return Integer.toString(in * in);
-	 * 		}
-	 * 	};
-	 * 	Multimap transformed = Multimaps.transformValues(multimap, square);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}. - * - *

- * Changes in the underlying multimap are reflected in this view. Conversely, - * this view supports removal operations, and these are reflected in the - * underlying multimap. - * - *

- * It's acceptable for the underlying multimap to contain null keys, and even - * null values provided that the function is capable of accepting null input. - * The transformed multimap might contain null values, if the function sometimes - * gives a null result. - * - *

- * The returned multimap is not thread-safe or serializable, even if the - * underlying multimap is. The {@code equals} and {@code hashCode} methods of - * the returned multimap are meaningless, since there is not a definition of - * {@code equals} or {@code hashCode} for general collections, and {@code get()} - * will return a general {@code Collection} as opposed to a {@code List} or a - * {@code Set}. - * - *

- * The function is applied lazily, invoked when needed. This is necessary for - * the returned multimap to be a view, but it means that the function will be - * applied many times for bulk operations like {@link Multimap#containsValue} - * and {@code Multimap.toString()}. For this to perform well, {@code function} - * should be fast. To avoid lazy evaluation when the returned multimap doesn't - * need to be a view, copy the returned multimap into a new multimap of your - * choosing. - * - * @since 7.0 - */ - public static Multimap transformValues(Multimap fromMultimap, - final Function function) { - checkNotNull(function); - EntryTransformer transformer = Maps.asEntryTransformer(function); - return transformEntries(fromMultimap, transformer); - } - - /** - * Returns a view of a multimap whose values are derived from the original - * multimap's entries. In contrast to {@link #transformValues}, this method's - * entry-transformation logic may depend on the key as well as the value. - * - *

- * All other properties of the transformed multimap, such as iteration order, - * are left intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	SetMultimap multimap = ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
-	 * 	EntryTransformer transformer = new EntryTransformer() {
-	 * 		public String transformEntry(String key, Integer value) {
-	 * 			return (value >= 0) ? key : "no" + key;
-	 * 		}
-	 * 	};
-	 * 	Multimap transformed = Multimaps.transformEntries(multimap, transformer);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {a=[a, a], b=[nob]}}. - * - *

- * Changes in the underlying multimap are reflected in this view. Conversely, - * this view supports removal operations, and these are reflected in the - * underlying multimap. - * - *

- * It's acceptable for the underlying multimap to contain null keys and null - * values provided that the transformer is capable of accepting null inputs. The - * transformed multimap might contain null values if the transformer sometimes - * gives a null result. - * - *

- * The returned multimap is not thread-safe or serializable, even if the - * underlying multimap is. The {@code equals} and {@code hashCode} methods of - * the returned multimap are meaningless, since there is not a definition of - * {@code equals} or {@code hashCode} for general collections, and {@code get()} - * will return a general {@code Collection} as opposed to a {@code List} or a - * {@code Set}. - * - *

- * The transformer is applied lazily, invoked when needed. This is necessary for - * the returned multimap to be a view, but it means that the transformer will be - * applied many times for bulk operations like {@link Multimap#containsValue} - * and {@link Object#toString}. For this to perform well, {@code transformer} - * should be fast. To avoid lazy evaluation when the returned multimap doesn't - * need to be a view, copy the returned multimap into a new multimap of your - * choosing. - * - *

- * Warning: This method assumes that for any instance {@code k} of - * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies - * that {@code k2} is also of type {@code K}. Using an {@code - * EntryTransformer} key type for which this may not hold, such as {@code - * ArrayList}, may risk a {@code ClassCastException} when calling methods on the - * transformed multimap. - * - * @since 7.0 - */ - public static Multimap transformEntries(Multimap fromMap, - EntryTransformer transformer) { - return new TransformedEntriesMultimap(fromMap, transformer); - } - - private static class TransformedEntriesMultimap extends AbstractMultimap { - final Multimap fromMultimap; - final EntryTransformer transformer; - - TransformedEntriesMultimap(Multimap fromMultimap, - final EntryTransformer transformer) { - this.fromMultimap = checkNotNull(fromMultimap); - this.transformer = checkNotNull(transformer); - } - - Collection transform(K key, Collection values) { - Function function = Maps.asValueToValueFunction(transformer, key); - if (values instanceof List) { - return Lists.transform((List) values, function); - } else { - return Collections2.transform(values, function); - } - } - - @Override - Map> createAsMap() { - return Maps.transformEntries(fromMultimap.asMap(), - new EntryTransformer, Collection>() { - @Override - public Collection transformEntry(K key, Collection value) { - return transform(key, value); - } - }); - } - - @Override - public void clear() { - fromMultimap.clear(); - } - - @Override - public boolean containsKey(Object key) { - return fromMultimap.containsKey(key); - } - - @Override - Iterator> entryIterator() { - return Iterators.transform(fromMultimap.entries().iterator(), - Maps.asEntryToEntryFunction(transformer)); - } - - @Override - public Collection get(final K key) { - return transform(key, fromMultimap.get(key)); - } - - @Override - public boolean isEmpty() { - return fromMultimap.isEmpty(); - } - - @Override - public Set keySet() { - return fromMultimap.keySet(); - } - - @Override - public Multiset keys() { - return fromMultimap.keys(); - } - - @Override - public boolean put(K key, V2 value) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean putAll(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean putAll(Multimap multimap) { - throw new UnsupportedOperationException(); - } - - @SuppressWarnings("unchecked") - @Override - public boolean remove(Object key, Object value) { - return get((K) key).remove(value); - } - - @SuppressWarnings("unchecked") - @Override - public Collection removeAll(Object key) { - return transform((K) key, fromMultimap.removeAll(key)); - } - - @Override - public Collection replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - - @Override - public int size() { - return fromMultimap.size(); - } - - @Override - Collection createValues() { - return Collections2.transform(fromMultimap.entries(), Maps.asEntryToValueFunction(transformer)); - } - } - - /** - * Returns a view of a {@code ListMultimap} where each value is transformed by a - * function. All other properties of the multimap, such as iteration order, are - * left intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	ListMultimap multimap = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
-	 * 	Function sqrt = new Function() {
-	 * 		public Double apply(Integer in) {
-	 * 			return Math.sqrt((int) in);
-	 * 		}
-	 * 	};
-	 * 	ListMultimap transformed = Multimaps.transformValues(map, sqrt);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}. - * - *

- * Changes in the underlying multimap are reflected in this view. Conversely, - * this view supports removal operations, and these are reflected in the - * underlying multimap. - * - *

- * It's acceptable for the underlying multimap to contain null keys, and even - * null values provided that the function is capable of accepting null input. - * The transformed multimap might contain null values, if the function sometimes - * gives a null result. - * - *

- * The returned multimap is not thread-safe or serializable, even if the - * underlying multimap is. - * - *

- * The function is applied lazily, invoked when needed. This is necessary for - * the returned multimap to be a view, but it means that the function will be - * applied many times for bulk operations like {@link Multimap#containsValue} - * and {@code Multimap.toString()}. For this to perform well, {@code function} - * should be fast. To avoid lazy evaluation when the returned multimap doesn't - * need to be a view, copy the returned multimap into a new multimap of your - * choosing. - * - * @since 7.0 - */ - public static ListMultimap transformValues(ListMultimap fromMultimap, - final Function function) { - checkNotNull(function); - EntryTransformer transformer = Maps.asEntryTransformer(function); - return transformEntries(fromMultimap, transformer); - } - - /** - * Returns a view of a {@code ListMultimap} whose values are derived from the - * original multimap's entries. In contrast to - * {@link #transformValues(ListMultimap, Function)}, this method's - * entry-transformation logic may depend on the key as well as the value. - * - *

- * All other properties of the transformed multimap, such as iteration order, - * are left intact. For example, the code: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	Multimap multimap = ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
-	 * 	EntryTransformer transformer = new EntryTransformer() {
-	 * 		public String transformEntry(String key, Integer value) {
-	 * 			return key + value;
-	 * 		}
-	 * 	};
-	 * 	Multimap transformed = Multimaps.transformEntries(multimap, transformer);
-	 * 	System.out.println(transformed);
-	 * }
-	 * 
- * - * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}. - * - *

- * Changes in the underlying multimap are reflected in this view. Conversely, - * this view supports removal operations, and these are reflected in the - * underlying multimap. - * - *

- * It's acceptable for the underlying multimap to contain null keys and null - * values provided that the transformer is capable of accepting null inputs. The - * transformed multimap might contain null values if the transformer sometimes - * gives a null result. - * - *

- * The returned multimap is not thread-safe or serializable, even if the - * underlying multimap is. - * - *

- * The transformer is applied lazily, invoked when needed. This is necessary for - * the returned multimap to be a view, but it means that the transformer will be - * applied many times for bulk operations like {@link Multimap#containsValue} - * and {@link Object#toString}. For this to perform well, {@code transformer} - * should be fast. To avoid lazy evaluation when the returned multimap doesn't - * need to be a view, copy the returned multimap into a new multimap of your - * choosing. - * - *

- * Warning: This method assumes that for any instance {@code k} of - * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies - * that {@code k2} is also of type {@code K}. Using an {@code - * EntryTransformer} key type for which this may not hold, such as {@code - * ArrayList}, may risk a {@code ClassCastException} when calling methods on the - * transformed multimap. - * - * @since 7.0 - */ - public static ListMultimap transformEntries(ListMultimap fromMap, - EntryTransformer transformer) { - return new TransformedEntriesListMultimap(fromMap, transformer); - } - - private static final class TransformedEntriesListMultimap extends TransformedEntriesMultimap - implements ListMultimap { - - TransformedEntriesListMultimap(ListMultimap fromMultimap, - EntryTransformer transformer) { - super(fromMultimap, transformer); - } - - @Override - List transform(K key, Collection values) { - return Lists.transform((List) values, Maps.asValueToValueFunction(transformer, key)); - } - - @Override - public List get(K key) { - return transform(key, fromMultimap.get(key)); - } - - @SuppressWarnings("unchecked") - @Override - public List removeAll(Object key) { - return transform((K) key, fromMultimap.removeAll(key)); - } - - @Override - public List replaceValues(K key, Iterable values) { - throw new UnsupportedOperationException(); - } - } - /** * Creates an index {@code ImmutableListMultimap} that contains the results of * applying a specified function to each item in an {@code Iterable} of values. @@ -1618,605 +1498,725 @@ public final class Multimaps { return builder.build(); } - static class Keys extends AbstractMultiset { - final Multimap multimap; - - Keys(Multimap multimap) { - this.multimap = multimap; - } - - @Override - Iterator> entryIterator() { - return new TransformedIterator>, Multiset.Entry>( - multimap.asMap().entrySet().iterator()) { - @Override - Multiset.Entry transform(final Map.Entry> backingEntry) { - return new Multisets.AbstractEntry() { - @Override - public K getElement() { - return backingEntry.getKey(); - } - - @Override - public int getCount() { - return backingEntry.getValue().size(); - } - }; - } - }; - } - - @Override - int distinctElements() { - return multimap.asMap().size(); - } - - @Override - Set> createEntrySet() { - return new KeysEntrySet(); - } - - class KeysEntrySet extends Multisets.EntrySet { - @Override - Multiset multiset() { - return Keys.this; - } - - @Override - public Iterator> iterator() { - return entryIterator(); - } - - @Override - public int size() { - return distinctElements(); - } - - @Override - public boolean isEmpty() { - return multimap.isEmpty(); - } - - @Override - public boolean contains(@Nullable Object o) { - if (o instanceof Multiset.Entry) { - Multiset.Entry entry = (Multiset.Entry) o; - Collection collection = multimap.asMap().get(entry.getElement()); - return collection != null && collection.size() == entry.getCount(); - } - return false; - } - - @Override - public boolean remove(@Nullable Object o) { - if (o instanceof Multiset.Entry) { - Multiset.Entry entry = (Multiset.Entry) o; - Collection collection = multimap.asMap().get(entry.getElement()); - if (collection != null && collection.size() == entry.getCount()) { - collection.clear(); - return true; - } - } - return false; - } - } - - @Override - public boolean contains(@Nullable Object element) { - return multimap.containsKey(element); - } - - @Override - public Iterator iterator() { - return Maps.keyIterator(multimap.entries().iterator()); - } - - @Override - public int count(@Nullable Object element) { - Collection values = Maps.safeGet(multimap.asMap(), element); - return (values == null) ? 0 : values.size(); - } - - @Override - public int remove(@Nullable Object element, int occurrences) { - checkNonnegative(occurrences, "occurrences"); - if (occurrences == 0) { - return count(element); - } - - Collection values = Maps.safeGet(multimap.asMap(), element); - - if (values == null) { - return 0; - } - - int oldCount = values.size(); - if (occurrences >= oldCount) { - values.clear(); - } else { - Iterator iterator = values.iterator(); - for (int i = 0; i < occurrences; i++) { - iterator.next(); - iterator.remove(); - } - } - return oldCount; - } - - @Override - public void clear() { - multimap.clear(); - } - - @Override - public Set elementSet() { - return multimap.keySet(); + /** + * Copies each key-value mapping in {@code source} into {@code dest}, with its + * key and value reversed. + * + *

+ * If {@code source} is an {@link ImmutableMultimap}, consider using + * {@link ImmutableMultimap#inverse} instead. + * + * @param source any multimap + * @param dest the multimap to copy into; usually empty + * @return {@code dest} + */ + public static > M invertFrom(Multimap source, M dest) { + checkNotNull(dest); + for (Map.Entry entry : source.entries()) { + dest.put(entry.getValue(), entry.getKey()); } + return dest; } /** - * A skeleton implementation of {@link Multimap#entries()}. + * Creates a new {@code ListMultimap} that uses the provided map and factory. It + * can generate a multimap based on arbitrary {@link Map} and {@link List} + * classes. + * + *

+ * The {@code factory}-generated and {@code map} classes determine the multimap + * iteration order. They also specify the behavior of the {@code equals}, + * {@code hashCode}, and {@code toString} methods for the multimap and its + * returned views. The multimap's {@code get}, {@code + * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} + * lists if the factory does. However, the multimap's {@code get} method returns + * instances of a different class than does {@code factory.get()}. + * + *

+ * The multimap is serializable if {@code map}, {@code factory}, the lists + * generated by {@code factory}, and the multimap contents are all serializable. + * + *

+ * The multimap is not threadsafe when any concurrent operations update the + * multimap, even if {@code map} and the instances generated by {@code factory} + * are. Concurrent read operations will work correctly. To allow concurrent + * update operations, wrap the multimap with a call to + * {@link #synchronizedListMultimap}. + * + *

+ * Call this method only when the simpler methods + * {@link ArrayListMultimap#create()} and {@link LinkedListMultimap#create()} + * won't suffice. + * + *

+ * Note: the multimap assumes complete ownership over of {@code map} and the + * lists returned by {@code factory}. Those objects should not be manually + * updated, they should be empty when provided, and they should not use soft, + * weak, or phantom references. + * + * @param map place to store the mapping from each key to its corresponding + * values + * @param factory supplier of new, empty lists that will each hold all values + * for a given key + * @throws IllegalArgumentException if {@code map} is not empty */ - abstract static class Entries extends AbstractCollection> { - abstract Multimap multimap(); - - @Override - public int size() { - return multimap().size(); - } - - @Override - public boolean contains(@Nullable Object o) { - if (o instanceof Map.Entry) { - Map.Entry entry = (Map.Entry) o; - return multimap().containsEntry(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public boolean remove(@Nullable Object o) { - if (o instanceof Map.Entry) { - Map.Entry entry = (Map.Entry) o; - return multimap().remove(entry.getKey(), entry.getValue()); - } - return false; - } - - @Override - public void clear() { - multimap().clear(); - } + public static ListMultimap newListMultimap(Map> map, + final Supplier> factory) { + return new CustomListMultimap(map, factory); } /** - * A skeleton implementation of {@link Multimap#asMap()}. + * Creates a new {@code Multimap} backed by {@code map}, whose internal value + * collections are generated by {@code factory}. + * + * Warning: do not use this method when the collections returned by + * {@code factory} implement either {@link List} or {@code Set}! Use the more + * specific method {@link #newListMultimap}, {@link #newSetMultimap} or + * {@link #newSortedSetMultimap} instead, to avoid very surprising behavior from + * {@link Multimap#equals}. + * + *

+ * The {@code factory}-generated and {@code map} classes determine the multimap + * iteration order. They also specify the behavior of the {@code equals}, + * {@code hashCode}, and {@code toString} methods for the multimap and its + * returned views. However, the multimap's {@code get} method returns instances + * of a different class than {@code factory.get()} does. + * + *

+ * The multimap is serializable if {@code map}, {@code factory}, the collections + * generated by {@code factory}, and the multimap contents are all serializable. + * + *

+ * The multimap is not threadsafe when any concurrent operations update the + * multimap, even if {@code map} and the instances generated by {@code factory} + * are. Concurrent read operations will work correctly. To allow concurrent + * update operations, wrap the multimap with a call to + * {@link #synchronizedMultimap}. + * + *

+ * Call this method only when the simpler methods + * {@link ArrayListMultimap#create()}, {@link HashMultimap#create()}, + * {@link LinkedHashMultimap#create()}, {@link LinkedListMultimap#create()}, + * {@link TreeMultimap#create()}, and + * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. + * + *

+ * Note: the multimap assumes complete ownership over of {@code map} and the + * collections returned by {@code factory}. Those objects should not be manually + * updated and they should not use soft, weak, or phantom references. + * + * @param map place to store the mapping from each key to its corresponding + * values + * @param factory supplier of new, empty collections that will each hold all + * values for a given key + * @throws IllegalArgumentException if {@code map} is not empty */ - static final class AsMap extends Maps.ImprovedAbstractMap> { - private final Multimap multimap; - - AsMap(Multimap multimap) { - this.multimap = checkNotNull(multimap); - } - - @Override - public int size() { - return multimap.keySet().size(); - } - - @Override - protected Set>> createEntrySet() { - return new EntrySet(); - } - - void removeValuesForKey(Object key) { - multimap.keySet().remove(key); - } - - class EntrySet extends Maps.EntrySet> { - @Override - Map> map() { - return AsMap.this; - } - - @Override - public Iterator>> iterator() { - return Maps.asMapEntryIterator(multimap.keySet(), new Function>() { - @Override - public Collection apply(K key) { - return multimap.get(key); - } - }); - } - - @Override - public boolean remove(Object o) { - if (!contains(o)) { - return false; - } - Map.Entry entry = (Map.Entry) o; - removeValuesForKey(entry.getKey()); - return true; - } - } - - @SuppressWarnings("unchecked") - @Override - public Collection get(Object key) { - return containsKey(key) ? multimap.get((K) key) : null; - } - - @Override - public Collection remove(Object key) { - return containsKey(key) ? multimap.removeAll(key) : null; - } - - @Override - public Set keySet() { - return multimap.keySet(); - } - - @Override - public boolean isEmpty() { - return multimap.isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return multimap.containsKey(key); - } - - @Override - public void clear() { - multimap.clear(); - } + public static Multimap newMultimap(Map> map, + final Supplier> factory) { + return new CustomMultimap(map, factory); } /** - * Returns a multimap containing the mappings in {@code unfiltered} whose keys - * satisfy a predicate. The returned multimap is a live view of - * {@code unfiltered}; changes to one affect the other. + * Creates a new {@code SetMultimap} that uses the provided map and factory. It + * can generate a multimap based on arbitrary {@link Map} and {@link Set} + * classes. * *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a key that doesn't satisfy the predicate, the multimap's - * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an - * {@link IllegalArgumentException}. + * The {@code factory}-generated and {@code map} classes determine the multimap + * iteration order. They also specify the behavior of the {@code equals}, + * {@code hashCode}, and {@code toString} methods for the multimap and its + * returned views. However, the multimap's {@code get} method returns instances + * of a different class than {@code factory.get()} does. * *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose keys satisfy the - * filter will be removed from the underlying multimap. + * The multimap is serializable if {@code map}, {@code factory}, the sets + * generated by {@code factory}, and the multimap contents are all serializable. * *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. + * The multimap is not threadsafe when any concurrent operations update the + * multimap, even if {@code map} and the instances generated by {@code factory} + * are. Concurrent read operations will work correctly. To allow concurrent + * update operations, wrap the multimap with a call to + * {@link #synchronizedSetMultimap}. * *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. + * Call this method only when the simpler methods {@link HashMultimap#create()}, + * {@link LinkedHashMultimap#create()}, {@link TreeMultimap#create()}, and + * {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. * *

- * Warning: {@code keyPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. + * Note: the multimap assumes complete ownership over of {@code map} and the + * sets returned by {@code factory}. Those objects should not be manually + * updated and they should not use soft, weak, or phantom references. * - * @since 11.0 + * @param map place to store the mapping from each key to its corresponding + * values + * @param factory supplier of new, empty sets that will each hold all values for + * a given key + * @throws IllegalArgumentException if {@code map} is not empty */ - public static Multimap filterKeys(Multimap unfiltered, final Predicate keyPredicate) { - if (unfiltered instanceof SetMultimap) { - return filterKeys((SetMultimap) unfiltered, keyPredicate); - } else if (unfiltered instanceof ListMultimap) { - return filterKeys((ListMultimap) unfiltered, keyPredicate); - } else if (unfiltered instanceof FilteredKeyMultimap) { - FilteredKeyMultimap prev = (FilteredKeyMultimap) unfiltered; - return new FilteredKeyMultimap(prev.unfiltered, Predicates.and(prev.keyPredicate, keyPredicate)); - } else if (unfiltered instanceof FilteredMultimap) { - FilteredMultimap prev = (FilteredMultimap) unfiltered; - return filterFiltered(prev, Maps.keyPredicateOnEntries(keyPredicate)); - } else { - return new FilteredKeyMultimap(unfiltered, keyPredicate); + public static SetMultimap newSetMultimap(Map> map, + final Supplier> factory) { + return new CustomSetMultimap(map, factory); + } + + /** + * Creates a new {@code SortedSetMultimap} that uses the provided map and + * factory. It can generate a multimap based on arbitrary {@link Map} and + * {@link SortedSet} classes. + * + *

+ * The {@code factory}-generated and {@code map} classes determine the multimap + * iteration order. They also specify the behavior of the {@code equals}, + * {@code hashCode}, and {@code toString} methods for the multimap and its + * returned views. However, the multimap's {@code get} method returns instances + * of a different class than {@code factory.get()} does. + * + *

+ * The multimap is serializable if {@code map}, {@code factory}, the sets + * generated by {@code factory}, and the multimap contents are all serializable. + * + *

+ * The multimap is not threadsafe when any concurrent operations update the + * multimap, even if {@code map} and the instances generated by {@code factory} + * are. Concurrent read operations will work correctly. To allow concurrent + * update operations, wrap the multimap with a call to + * {@link #synchronizedSortedSetMultimap}. + * + *

+ * Call this method only when the simpler methods {@link TreeMultimap#create()} + * and {@link TreeMultimap#create(Comparator, Comparator)} won't suffice. + * + *

+ * Note: the multimap assumes complete ownership over of {@code map} and the + * sets returned by {@code factory}. Those objects should not be manually + * updated and they should not use soft, weak, or phantom references. + * + * @param map place to store the mapping from each key to its corresponding + * values + * @param factory supplier of new, empty sorted sets that will each hold all + * values for a given key + * @throws IllegalArgumentException if {@code map} is not empty + */ + public static SortedSetMultimap newSortedSetMultimap(Map> map, + final Supplier> factory) { + return new CustomSortedSetMultimap(map, factory); + } + + /** + * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the + * specified multimap. + * + *

+ * You must follow the warnings described in {@link #synchronizedMultimap}. + * + * @param multimap the multimap to be wrapped + * @return a synchronized view of the specified multimap + */ + public static ListMultimap synchronizedListMultimap(ListMultimap multimap) { + return Synchronized.listMultimap(multimap, null); + } + + /** + * Returns a synchronized (thread-safe) multimap backed by the specified + * multimap. In order to guarantee serial access, it is critical that all + * access to the backing multimap is accomplished through the returned multimap. + * + *

+ * It is imperative that the user manually synchronize on the returned multimap + * when accessing any of its collection views: + * + *

+	 *    {@code
+	 *
+	 *   Multimap multimap = Multimaps.synchronizedMultimap(
+	 *       HashMultimap.create());
+	 *   ...
+	 *   Collection values = multimap.get(key);  // Needn't be in synchronized block
+	 *   ...
+	 *   synchronized (multimap) {  // Synchronizing on multimap, not values!
+	 *     Iterator i = values.iterator(); // Must be in synchronized block
+	 *     while (i.hasNext()) {
+	 *       foo(i.next());
+	 *     }
+	 *   }}
+	 * 
+ * + *

+ * Failure to follow this advice may result in non-deterministic behavior. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that aren't + * synchronized. + * + *

+ * The returned multimap will be serializable if the specified multimap is + * serializable. + * + * @param multimap the multimap to be wrapped in a synchronized view + * @return a synchronized view of the specified multimap + */ + public static Multimap synchronizedMultimap(Multimap multimap) { + return Synchronized.multimap(multimap, null); + } + + /** + * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the + * specified multimap. + * + *

+ * You must follow the warnings described in {@link #synchronizedMultimap}. + * + *

+ * The returned multimap will be serializable if the specified multimap is + * serializable. + * + * @param multimap the multimap to be wrapped + * @return a synchronized view of the specified multimap + */ + public static SetMultimap synchronizedSetMultimap(SetMultimap multimap) { + return Synchronized.setMultimap(multimap, null); + } + + /** + * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by the + * specified multimap. + * + *

+ * You must follow the warnings described in {@link #synchronizedMultimap}. + * + *

+ * The returned multimap will be serializable if the specified multimap is + * serializable. + * + * @param multimap the multimap to be wrapped + * @return a synchronized view of the specified multimap + */ + public static SortedSetMultimap synchronizedSortedSetMultimap(SortedSetMultimap multimap) { + return Synchronized.sortedSetMultimap(multimap, null); + } + + /** + * Returns a view of a {@code ListMultimap} whose values are derived from the + * original multimap's entries. In contrast to + * {@link #transformValues(ListMultimap, Function)}, this method's + * entry-transformation logic may depend on the key as well as the value. + * + *

+ * All other properties of the transformed multimap, such as iteration order, + * are left intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	Multimap multimap = ImmutableMultimap.of("a", 1, "a", 4, "b", 6);
+	 * 	EntryTransformer transformer = new EntryTransformer() {
+	 * 		public String transformEntry(String key, Integer value) {
+	 * 			return key + value;
+	 * 		}
+	 * 	};
+	 * 	Multimap transformed = Multimaps.transformEntries(multimap, transformer);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}. + * + *

+ * Changes in the underlying multimap are reflected in this view. Conversely, + * this view supports removal operations, and these are reflected in the + * underlying multimap. + * + *

+ * It's acceptable for the underlying multimap to contain null keys and null + * values provided that the transformer is capable of accepting null inputs. The + * transformed multimap might contain null values if the transformer sometimes + * gives a null result. + * + *

+ * The returned multimap is not thread-safe or serializable, even if the + * underlying multimap is. + * + *

+ * The transformer is applied lazily, invoked when needed. This is necessary for + * the returned multimap to be a view, but it means that the transformer will be + * applied many times for bulk operations like {@link Multimap#containsValue} + * and {@link Object#toString}. For this to perform well, {@code transformer} + * should be fast. To avoid lazy evaluation when the returned multimap doesn't + * need to be a view, copy the returned multimap into a new multimap of your + * choosing. + * + *

+ * Warning: This method assumes that for any instance {@code k} of + * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies + * that {@code k2} is also of type {@code K}. Using an {@code + * EntryTransformer} key type for which this may not hold, such as {@code + * ArrayList}, may risk a {@code ClassCastException} when calling methods on the + * transformed multimap. + * + * @since 7.0 + */ + public static ListMultimap transformEntries(ListMultimap fromMap, + EntryTransformer transformer) { + return new TransformedEntriesListMultimap(fromMap, transformer); + } + + /** + * Returns a view of a multimap whose values are derived from the original + * multimap's entries. In contrast to {@link #transformValues}, this method's + * entry-transformation logic may depend on the key as well as the value. + * + *

+ * All other properties of the transformed multimap, such as iteration order, + * are left intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	SetMultimap multimap = ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6);
+	 * 	EntryTransformer transformer = new EntryTransformer() {
+	 * 		public String transformEntry(String key, Integer value) {
+	 * 			return (value >= 0) ? key : "no" + key;
+	 * 		}
+	 * 	};
+	 * 	Multimap transformed = Multimaps.transformEntries(multimap, transformer);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {a=[a, a], b=[nob]}}. + * + *

+ * Changes in the underlying multimap are reflected in this view. Conversely, + * this view supports removal operations, and these are reflected in the + * underlying multimap. + * + *

+ * It's acceptable for the underlying multimap to contain null keys and null + * values provided that the transformer is capable of accepting null inputs. The + * transformed multimap might contain null values if the transformer sometimes + * gives a null result. + * + *

+ * The returned multimap is not thread-safe or serializable, even if the + * underlying multimap is. The {@code equals} and {@code hashCode} methods of + * the returned multimap are meaningless, since there is not a definition of + * {@code equals} or {@code hashCode} for general collections, and {@code get()} + * will return a general {@code Collection} as opposed to a {@code List} or a + * {@code Set}. + * + *

+ * The transformer is applied lazily, invoked when needed. This is necessary for + * the returned multimap to be a view, but it means that the transformer will be + * applied many times for bulk operations like {@link Multimap#containsValue} + * and {@link Object#toString}. For this to perform well, {@code transformer} + * should be fast. To avoid lazy evaluation when the returned multimap doesn't + * need to be a view, copy the returned multimap into a new multimap of your + * choosing. + * + *

+ * Warning: This method assumes that for any instance {@code k} of + * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies + * that {@code k2} is also of type {@code K}. Using an {@code + * EntryTransformer} key type for which this may not hold, such as {@code + * ArrayList}, may risk a {@code ClassCastException} when calling methods on the + * transformed multimap. + * + * @since 7.0 + */ + public static Multimap transformEntries(Multimap fromMap, + EntryTransformer transformer) { + return new TransformedEntriesMultimap(fromMap, transformer); + } + + /** + * Returns a view of a {@code ListMultimap} where each value is transformed by a + * function. All other properties of the multimap, such as iteration order, are + * left intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	ListMultimap multimap = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9);
+	 * 	Function sqrt = new Function() {
+	 * 		public Double apply(Integer in) {
+	 * 			return Math.sqrt((int) in);
+	 * 		}
+	 * 	};
+	 * 	ListMultimap transformed = Multimaps.transformValues(map, sqrt);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}. + * + *

+ * Changes in the underlying multimap are reflected in this view. Conversely, + * this view supports removal operations, and these are reflected in the + * underlying multimap. + * + *

+ * It's acceptable for the underlying multimap to contain null keys, and even + * null values provided that the function is capable of accepting null input. + * The transformed multimap might contain null values, if the function sometimes + * gives a null result. + * + *

+ * The returned multimap is not thread-safe or serializable, even if the + * underlying multimap is. + * + *

+ * The function is applied lazily, invoked when needed. This is necessary for + * the returned multimap to be a view, but it means that the function will be + * applied many times for bulk operations like {@link Multimap#containsValue} + * and {@code Multimap.toString()}. For this to perform well, {@code function} + * should be fast. To avoid lazy evaluation when the returned multimap doesn't + * need to be a view, copy the returned multimap into a new multimap of your + * choosing. + * + * @since 7.0 + */ + public static ListMultimap transformValues(ListMultimap fromMultimap, + final Function function) { + checkNotNull(function); + EntryTransformer transformer = Maps.asEntryTransformer(function); + return transformEntries(fromMultimap, transformer); + } + + /** + * Returns a view of a multimap where each value is transformed by a function. + * All other properties of the multimap, such as iteration order, are left + * intact. For example, the code: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	Multimap multimap = ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6);
+	 * 	Function square = new Function() {
+	 * 		public String apply(Integer in) {
+	 * 			return Integer.toString(in * in);
+	 * 		}
+	 * 	};
+	 * 	Multimap transformed = Multimaps.transformValues(multimap, square);
+	 * 	System.out.println(transformed);
+	 * }
+	 * 
+ * + * ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}. + * + *

+ * Changes in the underlying multimap are reflected in this view. Conversely, + * this view supports removal operations, and these are reflected in the + * underlying multimap. + * + *

+ * It's acceptable for the underlying multimap to contain null keys, and even + * null values provided that the function is capable of accepting null input. + * The transformed multimap might contain null values, if the function sometimes + * gives a null result. + * + *

+ * The returned multimap is not thread-safe or serializable, even if the + * underlying multimap is. The {@code equals} and {@code hashCode} methods of + * the returned multimap are meaningless, since there is not a definition of + * {@code equals} or {@code hashCode} for general collections, and {@code get()} + * will return a general {@code Collection} as opposed to a {@code List} or a + * {@code Set}. + * + *

+ * The function is applied lazily, invoked when needed. This is necessary for + * the returned multimap to be a view, but it means that the function will be + * applied many times for bulk operations like {@link Multimap#containsValue} + * and {@code Multimap.toString()}. For this to perform well, {@code function} + * should be fast. To avoid lazy evaluation when the returned multimap doesn't + * need to be a view, copy the returned multimap into a new multimap of your + * choosing. + * + * @since 7.0 + */ + public static Multimap transformValues(Multimap fromMultimap, + final Function function) { + checkNotNull(function); + EntryTransformer transformer = Maps.asEntryTransformer(function); + return transformEntries(fromMultimap, transformer); + } + + /** + * Returns an unmodifiable view of the specified collection of entries. The + * {@link Entry#setValue} operation throws an + * {@link UnsupportedOperationException}. If the specified collection is a + * {@code + * Set}, the returned collection is also a {@code Set}. + * + * @param entries the entries for which to return an unmodifiable view + * @return an unmodifiable view of the entries + */ + private static Collection> unmodifiableEntries(Collection> entries) { + if (entries instanceof Set) { + return Maps.unmodifiableEntrySet((Set>) entries); } + return new Maps.UnmodifiableEntries(Collections.unmodifiableCollection(entries)); } /** - * Returns a multimap containing the mappings in {@code unfiltered} whose keys - * satisfy a predicate. The returned multimap is a live view of - * {@code unfiltered}; changes to one affect the other. + * Simply returns its argument. * - *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a key that doesn't satisfy the predicate, the multimap's - * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose keys satisfy the - * filter will be removed from the underlying multimap. - * - *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. - * - *

- * Warning: {@code keyPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 14.0 + * @deprecated no need to use this + * @since 10.0 */ - public static SetMultimap filterKeys(SetMultimap unfiltered, - final Predicate keyPredicate) { - if (unfiltered instanceof FilteredKeySetMultimap) { - FilteredKeySetMultimap prev = (FilteredKeySetMultimap) unfiltered; - return new FilteredKeySetMultimap(prev.unfiltered(), Predicates.and(prev.keyPredicate, keyPredicate)); - } else if (unfiltered instanceof FilteredSetMultimap) { - FilteredSetMultimap prev = (FilteredSetMultimap) unfiltered; - return filterFiltered(prev, Maps.keyPredicateOnEntries(keyPredicate)); - } else { - return new FilteredKeySetMultimap(unfiltered, keyPredicate); + @Deprecated + public static ListMultimap unmodifiableListMultimap(ImmutableListMultimap delegate) { + return checkNotNull(delegate); + } + + /** + * Returns an unmodifiable view of the specified {@code ListMultimap}. Query + * operations on the returned multimap "read through" to the specified multimap, + * and attempts to modify the returned multimap, either directly or through the + * multimap's views, result in an {@code UnsupportedOperationException}. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are + * modifiable. + * + *

+ * The returned multimap will be serializable if the specified multimap is + * serializable. + * + * @param delegate the multimap for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified multimap + */ + public static ListMultimap unmodifiableListMultimap(ListMultimap delegate) { + if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) { + return delegate; } + return new UnmodifiableListMultimap(delegate); } /** - * Returns a multimap containing the mappings in {@code unfiltered} whose keys - * satisfy a predicate. The returned multimap is a live view of - * {@code unfiltered}; changes to one affect the other. + * Simply returns its argument. * - *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a key that doesn't satisfy the predicate, the multimap's - * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose keys satisfy the - * filter will be removed from the underlying multimap. - * - *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. - * - *

- * Warning: {@code keyPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 14.0 + * @deprecated no need to use this + * @since 10.0 */ - public static ListMultimap filterKeys(ListMultimap unfiltered, - final Predicate keyPredicate) { - if (unfiltered instanceof FilteredKeyListMultimap) { - FilteredKeyListMultimap prev = (FilteredKeyListMultimap) unfiltered; - return new FilteredKeyListMultimap(prev.unfiltered(), - Predicates.and(prev.keyPredicate, keyPredicate)); - } else { - return new FilteredKeyListMultimap(unfiltered, keyPredicate); + @Deprecated + public static Multimap unmodifiableMultimap(ImmutableMultimap delegate) { + return checkNotNull(delegate); + } + + /** + * Returns an unmodifiable view of the specified multimap. Query operations on + * the returned multimap "read through" to the specified multimap, and attempts + * to modify the returned multimap, either directly or through the multimap's + * views, result in an {@code UnsupportedOperationException}. + * + *

+ * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are + * modifiable. + * + *

+ * The returned multimap will be serializable if the specified multimap is + * serializable. + * + * @param delegate the multimap for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified multimap + */ + public static Multimap unmodifiableMultimap(Multimap delegate) { + if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) { + return delegate; } + return new UnmodifiableMultimap(delegate); } /** - * Returns a multimap containing the mappings in {@code unfiltered} whose values - * satisfy a predicate. The returned multimap is a live view of - * {@code unfiltered}; changes to one affect the other. + * Simply returns its argument. * - *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a value that doesn't satisfy the predicate, the multimap's - * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an - * {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose value satisfy the - * filter will be removed from the underlying multimap. - * - *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. - * - *

- * Warning: {@code valuePredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 11.0 + * @deprecated no need to use this + * @since 10.0 */ - public static Multimap filterValues(Multimap unfiltered, - final Predicate valuePredicate) { - return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); + @Deprecated + public static SetMultimap unmodifiableSetMultimap(ImmutableSetMultimap delegate) { + return checkNotNull(delegate); } /** - * Returns a multimap containing the mappings in {@code unfiltered} whose values - * satisfy a predicate. The returned multimap is a live view of - * {@code unfiltered}; changes to one affect the other. + * Returns an unmodifiable view of the specified {@code SetMultimap}. Query + * operations on the returned multimap "read through" to the specified multimap, + * and attempts to modify the returned multimap, either directly or through the + * multimap's views, result in an {@code UnsupportedOperationException}. * *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a value that doesn't satisfy the predicate, the multimap's - * {@code put()}, {@code putAll()}, and {@code replaceValues()} methods throw an - * {@link IllegalArgumentException}. + * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are + * modifiable. * *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose value satisfy the - * filter will be removed from the underlying multimap. + * The returned multimap will be serializable if the specified multimap is + * serializable. * - *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. - * - *

- * Warning: {@code valuePredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. - * - * @since 14.0 + * @param delegate the multimap for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified multimap */ - public static SetMultimap filterValues(SetMultimap unfiltered, - final Predicate valuePredicate) { - return filterEntries(unfiltered, Maps.valuePredicateOnEntries(valuePredicate)); - } - - /** - * Returns a multimap containing the mappings in {@code unfiltered} that satisfy - * a predicate. The returned multimap is a live view of {@code unfiltered}; - * changes to one affect the other. - * - *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a key/value pair that doesn't satisfy the predicate, - * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} - * methods throw an {@link IllegalArgumentException}. - * - *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose keys satisfy the - * filter will be removed from the underlying multimap. - * - *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. - * - *

- * Warning: {@code entryPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. - * - * @since 11.0 - */ - public static Multimap filterEntries(Multimap unfiltered, - Predicate> entryPredicate) { - checkNotNull(entryPredicate); - if (unfiltered instanceof SetMultimap) { - return filterEntries((SetMultimap) unfiltered, entryPredicate); + public static SetMultimap unmodifiableSetMultimap(SetMultimap delegate) { + if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) { + return delegate; } - return (unfiltered instanceof FilteredMultimap) - ? filterFiltered((FilteredMultimap) unfiltered, entryPredicate) - : new FilteredEntryMultimap(checkNotNull(unfiltered), entryPredicate); + return new UnmodifiableSetMultimap(delegate); } /** - * Returns a multimap containing the mappings in {@code unfiltered} that satisfy - * a predicate. The returned multimap is a live view of {@code unfiltered}; - * changes to one affect the other. + * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. + * Query operations on the returned multimap "read through" to the specified + * multimap, and attempts to modify the returned multimap, either directly or + * through the multimap's views, result in an + * {@code UnsupportedOperationException}. * *

- * The resulting multimap's views have iterators that don't support - * {@code remove()}, but all other methods are supported by the multimap and its - * views. When adding a key/value pair that doesn't satisfy the predicate, - * multimap's {@code put()}, {@code putAll()}, and {@code replaceValues()} - * methods throw an {@link IllegalArgumentException}. + * Note that the generated multimap's {@link Multimap#removeAll} and + * {@link Multimap#replaceValues} methods return collections that are + * modifiable. * *

- * When methods such as {@code removeAll()} and {@code clear()} are called on - * the filtered multimap or its views, only mappings whose keys satisfy the - * filter will be removed from the underlying multimap. + * The returned multimap will be serializable if the specified multimap is + * serializable. * - *

- * The returned multimap isn't threadsafe or serializable, even if - * {@code unfiltered} is. - * - *

- * Many of the filtered multimap's methods, such as {@code size()}, iterate - * across every key/value mapping in the underlying multimap and determine which - * satisfy the filter. When a live view is not needed, it may be faster - * to copy the filtered multimap and use the copy. - * - *

- * Warning: {@code entryPredicate} must be consistent with equals, - * as documented at {@link Predicate#apply}. - * - * @since 14.0 + * @param delegate the multimap for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified multimap */ - public static SetMultimap filterEntries(SetMultimap unfiltered, - Predicate> entryPredicate) { - checkNotNull(entryPredicate); - return (unfiltered instanceof FilteredSetMultimap) - ? filterFiltered((FilteredSetMultimap) unfiltered, entryPredicate) - : new FilteredEntrySetMultimap(checkNotNull(unfiltered), entryPredicate); - } - - /** - * Support removal operations when filtering a filtered multimap. Since a - * filtered multimap has iterators that don't support remove, passing one to the - * FilteredEntryMultimap constructor would lead to a multimap whose removal - * operations would fail. This method combines the predicates to avoid that - * problem. - */ - private static Multimap filterFiltered(FilteredMultimap multimap, - Predicate> entryPredicate) { - Predicate> predicate = Predicates.and(multimap.entryPredicate(), entryPredicate); - return new FilteredEntryMultimap(multimap.unfiltered(), predicate); - } - - /** - * Support removal operations when filtering a filtered multimap. Since a - * filtered multimap has iterators that don't support remove, passing one to the - * FilteredEntryMultimap constructor would lead to a multimap whose removal - * operations would fail. This method combines the predicates to avoid that - * problem. - */ - private static SetMultimap filterFiltered(FilteredSetMultimap multimap, - Predicate> entryPredicate) { - Predicate> predicate = Predicates.and(multimap.entryPredicate(), entryPredicate); - return new FilteredEntrySetMultimap(multimap.unfiltered(), predicate); - } - - static boolean equalsImpl(Multimap multimap, @Nullable Object object) { - if (object == multimap) { - return true; + public static SortedSetMultimap unmodifiableSortedSetMultimap(SortedSetMultimap delegate) { + if (delegate instanceof UnmodifiableSortedSetMultimap) { + return delegate; } - if (object instanceof Multimap) { - Multimap that = (Multimap) object; - return multimap.asMap().equals(that.asMap()); + return new UnmodifiableSortedSetMultimap(delegate); + } + + /** + * Returns an unmodifiable view of the specified collection, preserving the + * interface for instances of {@code SortedSet}, {@code Set}, {@code List} and + * {@code Collection}, in that order of preference. + * + * @param collection the collection for which to return an unmodifiable view + * @return an unmodifiable view of the collection + */ + private static Collection unmodifiableValueCollection(Collection collection) { + if (collection instanceof SortedSet) { + return Collections.unmodifiableSortedSet((SortedSet) collection); + } else if (collection instanceof Set) { + return Collections.unmodifiableSet((Set) collection); + } else if (collection instanceof List) { + return Collections.unmodifiableList((List) collection); } - return false; + return Collections.unmodifiableCollection(collection); + } + + private Multimaps() { } // TODO(jlevy): Create methods that filter a SortedSetMultimap. diff --git a/src/main/java/com/google/common/collect/Multiset.java b/src/main/java/com/google/common/collect/Multiset.java index 58b03380..712e9786 100644 --- a/src/main/java/com/google/common/collect/Multiset.java +++ b/src/main/java/com/google/common/collect/Multiset.java @@ -98,24 +98,108 @@ public interface Multiset extends Collection { // Query Operations /** - * Returns the number of occurrences of an element in this multiset (the - * count of the element). Note that for an {@link Object#equals}-based - * multiset, this gives the same result as {@link Collections#frequency} (which - * would presumably perform more poorly). + * An unmodifiable element-count pair for a multiset. The + * {@link Multiset#entrySet} method returns a view of the multiset whose + * elements are of this class. A multiset implementation may return Entry + * instances that are either live "read-through" views to the Multiset, or + * immutable snapshots. Note that this type is unrelated to the similarly-named + * type {@code Map.Entry}. * - *

- * Note: the utility method {@link Iterables#frequency} generalizes this - * operation; it correctly delegates to this method when dealing with a - * multiset, but it can also accept any other iterable type. - * - * @param element the element to count occurrences of - * @return the number of occurrences of the element in this multiset; possibly - * zero but never negative + * @since 2.0 (imported from Google Collections Library) */ - int count(@Nullable Object element); + interface Entry { + + /** + * {@inheritDoc} + * + *

+ * Returns {@code true} if the given object is also a multiset entry and the two + * entries represent the same element and count. That is, two entries {@code a} + * and {@code b} are equal if: + * + *

+		 *    {@code
+		 *
+		 * Objects.equal(a.getElement(), b.getElement()) && a.getCount() == b.getCount()
+		 * }
+		 * 
+ */ + @Override + // TODO(kevinb): check this wrt TreeMultiset? + boolean equals(Object o); + + /** + * Returns the count of the associated element in the underlying multiset. This + * count may either be an unchanging snapshot of the count at the time the entry + * was retrieved, or a live view of the current count of the element in the + * multiset, depending on the implementation. Note that in the former case, this + * method can never return zero, while in the latter, it will return zero if all + * occurrences of the element were since removed from the multiset. + * + * @return the count of the element; never negative + */ + int getCount(); + + /** + * Returns the multiset element corresponding to this entry. Multiple calls to + * this method always return the same instance. + * + * @return the element corresponding to this entry + */ + E getElement(); + + /** + * {@inheritDoc} + * + *

+ * The hash code of a multiset entry for element {@code element} and count + * {@code count} is defined as: + * + *

+		 *    {@code
+		 *
+		 * ((element == null) ? 0 : element.hashCode()) ^ count
+		 * }
+		 * 
+ */ + @Override + int hashCode(); + + /** + * Returns the canonical string representation of this entry, defined as + * follows. If the count for this entry is one, this is simply the string + * representation of the corresponding element. Otherwise, it is the string + * representation of the element, followed by the three characters {@code + * " x "} (space, letter x, space), followed by the count. + */ + @Override + String toString(); + } // Bulk Operations + /** + * Adds a single occurrence of the specified element to this multiset. + * + *

+ * This method refines {@link Collection#add}, which only ensures the + * presence of the element, to further specify that a successful call must + * always increment the count of the element, and the overall size of the + * collection, by one. + * + * @param element the element to add one occurrence of; may be null only if + * explicitly allowed by the implementation + * @return {@code true} always, since this call is required to modify the + * multiset, unlike other {@link Collection} types + * @throws NullPointerException if {@code element} is null and this + * implementation does not permit null elements + * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences of + * {@code element} are already contained in + * this multiset + */ + @Override + boolean add(E element); + /** * Adds a number of occurrences of an element to this multiset. Note that if * {@code occurrences == 1}, this method has the identical effect to @@ -141,62 +225,65 @@ public interface Multiset extends Collection { int add(@Nullable E element, int occurrences); /** - * Removes a number of occurrences of the specified element from this multiset. - * If the multiset contains fewer than this number of occurrences to begin with, - * all occurrences will be removed. Note that if {@code occurrences == 1}, this - * is functionally equivalent to the call {@code remove(element)}. + * Determines whether this multiset contains the specified element. * - * @param element the element to conditionally remove occurrences of - * @param occurrences the number of occurrences of the element to remove. May be - * zero, in which case no change will be made. - * @return the count of the element before the operation; possibly zero - * @throws IllegalArgumentException if {@code occurrences} is negative + *

+ * This method refines {@link Collection#contains} to further specify that it + * may not throw an exception in response to {@code element} being null + * or of the wrong type. + * + * @param element the element to check for + * @return {@code true} if this multiset contains at least one occurrence of the + * element */ - int remove(@Nullable Object element, int occurrences); + @Override + boolean contains(@Nullable Object element); /** - * Adds or removes the necessary occurrences of an element such that the element - * attains the desired count. + * Returns {@code true} if this multiset contains at least one occurrence of + * each element in the specified collection. * - * @param element the element to add or remove occurrences of; may be null only - * if explicitly allowed by the implementation - * @param count the desired count of the element in this multiset - * @return the count of the element before the operation; possibly zero - * @throws IllegalArgumentException if {@code count} is negative - * @throws NullPointerException if {@code element} is null and this - * implementation does not permit null - * elements. Note that if {@code - * count} is zero, the implementor may optionally - * return zero instead. - */ - int setCount(E element, int count); - - /** - * Conditionally sets the count of an element to a new value, as described in - * {@link #setCount(Object, int)}, provided that the element has the expected - * current count. If the current count is not {@code oldCount}, no change is - * made. + *

+ * This method refines {@link Collection#containsAll} to further specify that it + * may not throw an exception in response to any of {@code + * elements} being null or of the wrong type. * - * @param element the element to conditionally set the count of; may be null - * only if explicitly allowed by the implementation - * @param oldCount the expected present count of the element in this multiset - * @param newCount the desired count of the element in this multiset - * @return {@code true} if the condition for modification was met. This implies - * that the multiset was indeed modified, unless - * {@code oldCount == newCount}. - * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is - * negative - * @throws NullPointerException if {@code element} is null and the - * implementation does not permit null - * elements. Note that if {@code - * oldCount} and {@code newCount} are both zero, the - * implementor may optionally return - * {@code true} instead. + *

+ * Note: this method does not take into account the occurrence count of + * an element in the two collections; it may still return {@code + * true} even if {@code elements} contains several occurrences of an element and + * this multiset contains only one. This is no different than any other + * collection type like {@link List}, but it may be unexpected to the user of a + * multiset. + * + * @param elements the collection of elements to be checked for containment in + * this multiset + * @return {@code true} if this multiset contains at least one occurrence of + * each element contained in {@code elements} + * @throws NullPointerException if {@code elements} is null */ - boolean setCount(E element, int oldCount, int newCount); + @Override + boolean containsAll(Collection elements); // Views + /** + * Returns the number of occurrences of an element in this multiset (the + * count of the element). Note that for an {@link Object#equals}-based + * multiset, this gives the same result as {@link Collections#frequency} (which + * would presumably perform more poorly). + * + *

+ * Note: the utility method {@link Iterables#frequency} generalizes this + * operation; it correctly delegates to this method when dealing with a + * multiset, but it can also accept any other iterable type. + * + * @param element the element to count occurrences of + * @return the number of occurrences of the element in this multiset; possibly + * zero but never negative + */ + int count(@Nullable Object element); + /** * Returns the set of distinct elements contained in this multiset. The element * set is backed by the same data as the multiset, so any change to either is @@ -239,84 +326,6 @@ public interface Multiset extends Collection { */ Set> entrySet(); - /** - * An unmodifiable element-count pair for a multiset. The - * {@link Multiset#entrySet} method returns a view of the multiset whose - * elements are of this class. A multiset implementation may return Entry - * instances that are either live "read-through" views to the Multiset, or - * immutable snapshots. Note that this type is unrelated to the similarly-named - * type {@code Map.Entry}. - * - * @since 2.0 (imported from Google Collections Library) - */ - interface Entry { - - /** - * Returns the multiset element corresponding to this entry. Multiple calls to - * this method always return the same instance. - * - * @return the element corresponding to this entry - */ - E getElement(); - - /** - * Returns the count of the associated element in the underlying multiset. This - * count may either be an unchanging snapshot of the count at the time the entry - * was retrieved, or a live view of the current count of the element in the - * multiset, depending on the implementation. Note that in the former case, this - * method can never return zero, while in the latter, it will return zero if all - * occurrences of the element were since removed from the multiset. - * - * @return the count of the element; never negative - */ - int getCount(); - - /** - * {@inheritDoc} - * - *

- * Returns {@code true} if the given object is also a multiset entry and the two - * entries represent the same element and count. That is, two entries {@code a} - * and {@code b} are equal if: - * - *

-		 *    {@code
-		 *
-		 *   Objects.equal(a.getElement(), b.getElement())
-		 *       && a.getCount() == b.getCount()}
-		 * 
- */ - @Override - // TODO(kevinb): check this wrt TreeMultiset? - boolean equals(Object o); - - /** - * {@inheritDoc} - * - *

- * The hash code of a multiset entry for element {@code element} and count - * {@code count} is defined as: - * - *

-		 *    {@code
-		 *
-		 *   ((element == null) ? 0 : element.hashCode()) ^ count}
-		 * 
- */ - @Override - int hashCode(); - - /** - * Returns the canonical string representation of this entry, defined as - * follows. If the count for this entry is one, this is simply the string - * representation of the corresponding element. Otherwise, it is the string - * representation of the element, followed by the three characters {@code - * " x "} (space, letter x, space), followed by the count. - */ - @Override - String toString(); - } - // Comparison and hashing /** @@ -334,7 +343,8 @@ public interface Multiset extends Collection { *
 	 *    {@code
 	 *
-	 *   ((element == null) ? 0 : element.hashCode()) ^ count(element)}
+	 * ((element == null) ? 0 : element.hashCode()) ^ count(element)
+	 * }
 	 * 
* *

@@ -344,19 +354,6 @@ public interface Multiset extends Collection { @Override int hashCode(); - /** - * {@inheritDoc} - * - *

- * It is recommended, though not mandatory, that this method return the result - * of invoking {@link #toString} on the {@link #entrySet}, yielding a result - * such as {@code [a x 3, c, d x 2, e]}. - */ - @Override - String toString(); - - // Refined Collection Methods - /** * {@inheritDoc} * @@ -367,68 +364,7 @@ public interface Multiset extends Collection { @Override Iterator iterator(); - /** - * Determines whether this multiset contains the specified element. - * - *

- * This method refines {@link Collection#contains} to further specify that it - * may not throw an exception in response to {@code element} being null - * or of the wrong type. - * - * @param element the element to check for - * @return {@code true} if this multiset contains at least one occurrence of the - * element - */ - @Override - boolean contains(@Nullable Object element); - - /** - * Returns {@code true} if this multiset contains at least one occurrence of - * each element in the specified collection. - * - *

- * This method refines {@link Collection#containsAll} to further specify that it - * may not throw an exception in response to any of {@code - * elements} being null or of the wrong type. - * - *

- * Note: this method does not take into account the occurrence count of - * an element in the two collections; it may still return {@code - * true} even if {@code elements} contains several occurrences of an element and - * this multiset contains only one. This is no different than any other - * collection type like {@link List}, but it may be unexpected to the user of a - * multiset. - * - * @param elements the collection of elements to be checked for containment in - * this multiset - * @return {@code true} if this multiset contains at least one occurrence of - * each element contained in {@code elements} - * @throws NullPointerException if {@code elements} is null - */ - @Override - boolean containsAll(Collection elements); - - /** - * Adds a single occurrence of the specified element to this multiset. - * - *

- * This method refines {@link Collection#add}, which only ensures the - * presence of the element, to further specify that a successful call must - * always increment the count of the element, and the overall size of the - * collection, by one. - * - * @param element the element to add one occurrence of; may be null only if - * explicitly allowed by the implementation - * @return {@code true} always, since this call is required to modify the - * multiset, unlike other {@link Collection} types - * @throws NullPointerException if {@code element} is null and this - * implementation does not permit null elements - * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences of - * {@code element} are already contained in - * this multiset - */ - @Override - boolean add(E element); + // Refined Collection Methods /** * Removes a single occurrence of the specified element from this @@ -445,6 +381,20 @@ public interface Multiset extends Collection { @Override boolean remove(@Nullable Object element); + /** + * Removes a number of occurrences of the specified element from this multiset. + * If the multiset contains fewer than this number of occurrences to begin with, + * all occurrences will be removed. Note that if {@code occurrences == 1}, this + * is functionally equivalent to the call {@code remove(element)}. + * + * @param element the element to conditionally remove occurrences of + * @param occurrences the number of occurrences of the element to remove. May be + * zero, in which case no change will be made. + * @return the count of the element before the operation; possibly zero + * @throws IllegalArgumentException if {@code occurrences} is negative + */ + int remove(@Nullable Object element, int occurrences); + /** * {@inheritDoc} * @@ -480,4 +430,56 @@ public interface Multiset extends Collection { */ @Override boolean retainAll(Collection c); + + /** + * Adds or removes the necessary occurrences of an element such that the element + * attains the desired count. + * + * @param element the element to add or remove occurrences of; may be null only + * if explicitly allowed by the implementation + * @param count the desired count of the element in this multiset + * @return the count of the element before the operation; possibly zero + * @throws IllegalArgumentException if {@code count} is negative + * @throws NullPointerException if {@code element} is null and this + * implementation does not permit null + * elements. Note that if {@code + * count} is zero, the implementor may optionally + * return zero instead. + */ + int setCount(E element, int count); + + /** + * Conditionally sets the count of an element to a new value, as described in + * {@link #setCount(Object, int)}, provided that the element has the expected + * current count. If the current count is not {@code oldCount}, no change is + * made. + * + * @param element the element to conditionally set the count of; may be null + * only if explicitly allowed by the implementation + * @param oldCount the expected present count of the element in this multiset + * @param newCount the desired count of the element in this multiset + * @return {@code true} if the condition for modification was met. This implies + * that the multiset was indeed modified, unless + * {@code oldCount == newCount}. + * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is + * negative + * @throws NullPointerException if {@code element} is null and the + * implementation does not permit null + * elements. Note that if {@code + * oldCount} and {@code newCount} are both zero, the + * implementor may optionally return + * {@code true} instead. + */ + boolean setCount(E element, int oldCount, int newCount); + + /** + * {@inheritDoc} + * + *

+ * It is recommended, though not mandatory, that this method return the result + * of invoking {@link #toString} on the {@link #entrySet}, yielding a result + * such as {@code [a x 3, c, d x 2, e]}. + */ + @Override + String toString(); } diff --git a/src/main/java/com/google/common/collect/Multisets.java b/src/main/java/com/google/common/collect/Multisets.java index c33ab0fa..b5bbfde1 100644 --- a/src/main/java/com/google/common/collect/Multisets.java +++ b/src/main/java/com/google/common/collect/Multisets.java @@ -55,51 +55,324 @@ import com.google.common.primitives.Ints; */ @GwtCompatible public final class Multisets { - private Multisets() { - } - /** - * Returns an unmodifiable view of the specified multiset. Query operations on - * the returned multiset "read through" to the specified multiset, and attempts - * to modify the returned multiset result in an - * {@link UnsupportedOperationException}. - * - *

- * The returned multiset will be serializable if the specified multiset is - * serializable. - * - * @param multiset the multiset for which an unmodifiable view is to be - * generated - * @return an unmodifiable view of the multiset + * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} + * methods of {@link Multiset.Entry}. */ - public static Multiset unmodifiableMultiset(Multiset multiset) { - if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) { - // Since it's unmodifiable, the covariant cast is safe - @SuppressWarnings("unchecked") - Multiset result = (Multiset) multiset; - return result; + abstract static class AbstractEntry implements Multiset.Entry { + /** + * Indicates whether an object equals this entry, following the behavior + * specified in {@link Multiset.Entry#equals}. + */ + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof Multiset.Entry) { + Multiset.Entry that = (Multiset.Entry) object; + return this.getCount() == that.getCount() && Objects.equal(this.getElement(), that.getElement()); + } + return false; + } + + /** + * Return this entry's hash code, following the behavior specified in + * {@link Multiset.Entry#hashCode}. + */ + @Override + public int hashCode() { + E e = getElement(); + return ((e == null) ? 0 : e.hashCode()) ^ getCount(); + } + + /** + * Returns a string representation of this multiset entry. The string + * representation consists of the associated element if the associated count is + * one, and otherwise the associated element followed by the characters " x " + * (space, x and space) followed by the count. Elements and counts are converted + * to strings as by {@code String.valueOf}. + */ + @Override + public String toString() { + String text = String.valueOf(getElement()); + int n = getCount(); + return (n == 1) ? text : (text + " x " + n); } - return new UnmodifiableMultiset(checkNotNull(multiset)); } - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ - @Deprecated - public static Multiset unmodifiableMultiset(ImmutableMultiset multiset) { - return checkNotNull(multiset); + abstract static class ElementSet extends Sets.ImprovedAbstractSet { + @Override + public void clear() { + multiset().clear(); + } + + @Override + public boolean contains(Object o) { + return multiset().contains(o); + } + + @Override + public boolean containsAll(Collection c) { + return multiset().containsAll(c); + } + + @Override + public boolean isEmpty() { + return multiset().isEmpty(); + } + + @Override + public Iterator iterator() { + return new TransformedIterator, E>(multiset().entrySet().iterator()) { + @Override + E transform(Entry entry) { + return entry.getElement(); + } + }; + } + + abstract Multiset multiset(); + + @Override + public boolean remove(Object o) { + int count = multiset().count(o); + if (count > 0) { + multiset().remove(o, count); + return true; + } + return false; + } + + @Override + public int size() { + return multiset().entrySet().size(); + } + } + + abstract static class EntrySet extends Sets.ImprovedAbstractSet> { + @Override + public void clear() { + multiset().clear(); + } + + @Override + public boolean contains(@Nullable Object o) { + if (o instanceof Entry) { + /* + * The GWT compiler wrongly issues a warning here. + */ + @SuppressWarnings("cast") + Entry entry = (Entry) o; + if (entry.getCount() <= 0) { + return false; + } + int count = multiset().count(entry.getElement()); + return count == entry.getCount(); + + } + return false; + } + + abstract Multiset multiset(); + + // GWT compiler warning; see contains(). + @SuppressWarnings("cast") + @Override + public boolean remove(Object object) { + if (object instanceof Multiset.Entry) { + Entry entry = (Entry) object; + Object element = entry.getElement(); + int entryCount = entry.getCount(); + if (entryCount != 0) { + // Safe as long as we never add a new entry, which we won't. + @SuppressWarnings("unchecked") + Multiset multiset = (Multiset) multiset(); + return multiset.setCount(element, entryCount, 0); + } + } + return false; + } + } + + private static final class FilteredMultiset extends AbstractMultiset { + final Multiset unfiltered; + final Predicate predicate; + + FilteredMultiset(Multiset unfiltered, Predicate predicate) { + this.unfiltered = checkNotNull(unfiltered); + this.predicate = checkNotNull(predicate); + } + + @Override + public int add(@Nullable E element, int occurrences) { + checkArgument(predicate.apply(element), "Element %s does not match predicate %s", element, predicate); + return unfiltered.add(element, occurrences); + } + + @Override + public void clear() { + elementSet().clear(); + } + + @Override + public int count(@Nullable Object element) { + int count = unfiltered.count(element); + if (count > 0) { + @SuppressWarnings("unchecked") // element is equal to an E + E e = (E) element; + return predicate.apply(e) ? count : 0; + } + return 0; + } + + @Override + Set createElementSet() { + return Sets.filter(unfiltered.elementSet(), predicate); + } + + @Override + Set> createEntrySet() { + return Sets.filter(unfiltered.entrySet(), new Predicate>() { + @Override + public boolean apply(Entry entry) { + return predicate.apply(entry.getElement()); + } + }); + } + + @Override + int distinctElements() { + return elementSet().size(); + } + + @Override + Iterator> entryIterator() { + throw new AssertionError("should never be called"); + } + + @Override + public UnmodifiableIterator iterator() { + return Iterators.filter(unfiltered.iterator(), predicate); + } + + @Override + public int remove(@Nullable Object element, int occurrences) { + checkNonnegative(occurrences, "occurrences"); + if (occurrences == 0) { + return count(element); + } else { + return contains(element) ? unfiltered.remove(element, occurrences) : 0; + } + } + } + + static final class ImmutableEntry extends AbstractEntry implements Serializable { + private static final long serialVersionUID = 0; + @Nullable + final E element; + + final int count; + + ImmutableEntry(@Nullable E element, int count) { + this.element = element; + this.count = count; + checkNonnegative(count, "count"); + } + + @Override + public int getCount() { + return count; + } + + @Override + @Nullable + public E getElement() { + return element; + } + } + + static final class MultisetIteratorImpl implements Iterator { + private final Multiset multiset; + private final Iterator> entryIterator; + private Entry currentEntry; + /** Count of subsequent elements equal to current element */ + private int laterCount; + /** Count of all elements equal to current element */ + private int totalCount; + private boolean canRemove; + + MultisetIteratorImpl(Multiset multiset, Iterator> entryIterator) { + this.multiset = multiset; + this.entryIterator = entryIterator; + } + + @Override + public boolean hasNext() { + return laterCount > 0 || entryIterator.hasNext(); + } + + @Override + public E next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + if (laterCount == 0) { + currentEntry = entryIterator.next(); + totalCount = laterCount = currentEntry.getCount(); + } + laterCount--; + canRemove = true; + return currentEntry.getElement(); + } + + @Override + public void remove() { + checkRemove(canRemove); + if (totalCount == 1) { + entryIterator.remove(); + } else { + multiset.remove(currentEntry.getElement()); + } + totalCount--; + canRemove = false; + } } static class UnmodifiableMultiset extends ForwardingMultiset implements Serializable { + private static final long serialVersionUID = 0; + final Multiset delegate; + transient Set elementSet; + + transient Set> entrySet; + UnmodifiableMultiset(Multiset delegate) { this.delegate = delegate; } + @Override + public boolean add(E element) { + throw new UnsupportedOperationException(); + } + + @Override + public int add(E element, int occurences) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean addAll(Collection elementsToAdd) { + throw new UnsupportedOperationException(); + } + + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + Set createElementSet() { + return Collections.unmodifiableSet(delegate.elementSet()); + } + @SuppressWarnings("unchecked") @Override protected Multiset delegate() { @@ -107,20 +380,12 @@ public final class Multisets { return (Multiset) delegate; } - transient Set elementSet; - - Set createElementSet() { - return Collections.unmodifiableSet(delegate.elementSet()); - } - @Override public Set elementSet() { Set es = elementSet; return (es == null) ? elementSet = createElementSet() : es; } - transient Set> entrySet; - @SuppressWarnings("unchecked") @Override public Set> entrySet() { @@ -139,21 +404,6 @@ public final class Multisets { return (Iterator) Iterators.unmodifiableIterator(delegate.iterator()); } - @Override - public boolean add(E element) { - throw new UnsupportedOperationException(); - } - - @Override - public int add(E element, int occurences) { - throw new UnsupportedOperationException(); - } - - @Override - public boolean addAll(Collection elementsToAdd) { - throw new UnsupportedOperationException(); - } - @Override public boolean remove(Object element) { throw new UnsupportedOperationException(); @@ -174,11 +424,6 @@ public final class Multisets { throw new UnsupportedOperationException(); } - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - @Override public int setCount(E element, int count) { throw new UnsupportedOperationException(); @@ -188,66 +433,152 @@ public final class Multisets { public boolean setCount(E element, int oldCount, int newCount) { throw new UnsupportedOperationException(); } + } - private static final long serialVersionUID = 0; + private static final Ordering> DECREASING_COUNT_ORDERING = new Ordering>() { + @Override + public int compare(Entry entry1, Entry entry2) { + return Ints.compare(entry2.getCount(), entry1.getCount()); + } + }; + + /** + * An implementation of {@link Multiset#addAll}. + */ + static boolean addAllImpl(Multiset self, Collection elements) { + if (elements.isEmpty()) { + return false; + } + if (elements instanceof Multiset) { + Multiset that = cast(elements); + for (Entry entry : that.entrySet()) { + self.add(entry.getElement(), entry.getCount()); + } + } else { + Iterators.addAll(self, elements.iterator()); + } + return true; } /** - * Returns an unmodifiable view of the specified sorted multiset. Query - * operations on the returned multiset "read through" to the specified multiset, - * and attempts to modify the returned multiset result in an - * {@link UnsupportedOperationException}. + * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + */ + static Multiset cast(Iterable iterable) { + return (Multiset) iterable; + } + + /** + * Returns {@code true} if {@code subMultiset.count(o) <= + * superMultiset.count(o)} for all {@code o}. * - *

- * The returned multiset will be serializable if the specified multiset is - * serializable. + * @since 10.0 + */ + public static boolean containsOccurrences(Multiset superMultiset, Multiset subMultiset) { + checkNotNull(superMultiset); + checkNotNull(subMultiset); + for (Entry entry : subMultiset.entrySet()) { + int superCount = superMultiset.count(entry.getElement()); + if (superCount < entry.getCount()) { + return false; + } + } + return true; + } + + /** + * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose + * iteration order is highest count first, with ties broken by the iteration + * order of the original multiset. * - * @param sortedMultiset the sorted multiset for which an unmodifiable view is - * to be generated - * @return an unmodifiable view of the multiset * @since 11.0 */ @Beta - public static SortedMultiset unmodifiableSortedMultiset(SortedMultiset sortedMultiset) { - // it's in its own file so it can be emulated for GWT - return new UnmodifiableSortedMultiset(checkNotNull(sortedMultiset)); + public static ImmutableMultiset copyHighestCountFirst(Multiset multiset) { + List> sortedEntries = Multisets.DECREASING_COUNT_ORDERING.immutableSortedCopy(multiset.entrySet()); + return ImmutableMultiset.copyFromEntries(sortedEntries); } /** - * Returns an immutable multiset entry with the specified element and count. The - * entry will be serializable if {@code e} is. + * Returns an unmodifiable view of the difference of two multisets. In the + * returned multiset, the count of each element is the result of the + * zero-truncated subtraction of its count in the second multiset from + * its count in the first multiset, with elements that would have a count of 0 + * not included. The iteration order of the returned multiset matches that of + * the element set of {@code multiset1}, with repeated occurrences of the same + * element appearing consecutively. * - * @param e the element to be associated with the returned entry - * @param n the count to be associated with the returned entry - * @throws IllegalArgumentException if {@code n} is negative + *

+ * Results are undefined if {@code multiset1} and {@code multiset2} are based on + * different equivalence relations (as {@code HashMultiset} and + * {@code TreeMultiset} are). + * + * @since 14.0 */ - public static Multiset.Entry immutableEntry(@Nullable E e, int n) { - return new ImmutableEntry(e, n); + @Beta + public static Multiset difference(final Multiset multiset1, final Multiset multiset2) { + checkNotNull(multiset1); + checkNotNull(multiset2); + + // TODO(user): consider making the entries live views + return new AbstractMultiset() { + @Override + public int count(@Nullable Object element) { + int count1 = multiset1.count(element); + return (count1 == 0) ? 0 : Math.max(0, count1 - multiset2.count(element)); + } + + @Override + int distinctElements() { + return Iterators.size(entryIterator()); + } + + @Override + Iterator> entryIterator() { + final Iterator> iterator1 = multiset1.entrySet().iterator(); + return new AbstractIterator>() { + @Override + protected Entry computeNext() { + while (iterator1.hasNext()) { + Entry entry1 = iterator1.next(); + E element = entry1.getElement(); + int count = entry1.getCount() - multiset2.count(element); + if (count > 0) { + return immutableEntry(element, count); + } + } + return endOfData(); + } + }; + } + }; } - static final class ImmutableEntry extends AbstractEntry implements Serializable { - @Nullable - final E element; - final int count; - - ImmutableEntry(@Nullable E element, int count) { - this.element = element; - this.count = count; - checkNonnegative(count, "count"); + /** + * An implementation of {@link Multiset#equals}. + */ + static boolean equalsImpl(Multiset multiset, @Nullable Object object) { + if (object == multiset) { + return true; } + if (object instanceof Multiset) { + Multiset that = (Multiset) object; + /* + * We can't simply check whether the entry sets are equal, since that approach + * fails when a TreeMultiset has a comparator that returns 0 when passed unequal + * elements. + */ - @Override - @Nullable - public E getElement() { - return element; + if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) { + return false; + } + for (Entry entry : that.entrySet()) { + if (multiset.count(entry.getElement()) != entry.getCount()) { + return false; + } + } + return true; } - - @Override - public int getCount() { - return count; - } - - private static final long serialVersionUID = 0; + return false; } /** @@ -296,76 +627,16 @@ public final class Multisets { return new FilteredMultiset(unfiltered, predicate); } - private static final class FilteredMultiset extends AbstractMultiset { - final Multiset unfiltered; - final Predicate predicate; - - FilteredMultiset(Multiset unfiltered, Predicate predicate) { - this.unfiltered = checkNotNull(unfiltered); - this.predicate = checkNotNull(predicate); - } - - @Override - public UnmodifiableIterator iterator() { - return Iterators.filter(unfiltered.iterator(), predicate); - } - - @Override - Set createElementSet() { - return Sets.filter(unfiltered.elementSet(), predicate); - } - - @Override - Set> createEntrySet() { - return Sets.filter(unfiltered.entrySet(), new Predicate>() { - @Override - public boolean apply(Entry entry) { - return predicate.apply(entry.getElement()); - } - }); - } - - @Override - Iterator> entryIterator() { - throw new AssertionError("should never be called"); - } - - @Override - int distinctElements() { - return elementSet().size(); - } - - @Override - public int count(@Nullable Object element) { - int count = unfiltered.count(element); - if (count > 0) { - @SuppressWarnings("unchecked") // element is equal to an E - E e = (E) element; - return predicate.apply(e) ? count : 0; - } - return 0; - } - - @Override - public int add(@Nullable E element, int occurrences) { - checkArgument(predicate.apply(element), "Element %s does not match predicate %s", element, predicate); - return unfiltered.add(element, occurrences); - } - - @Override - public int remove(@Nullable Object element, int occurrences) { - checkNonnegative(occurrences, "occurrences"); - if (occurrences == 0) { - return count(element); - } else { - return contains(element) ? unfiltered.remove(element, occurrences) : 0; - } - } - - @Override - public void clear() { - elementSet().clear(); - } + /** + * Returns an immutable multiset entry with the specified element and count. The + * entry will be serializable if {@code e} is. + * + * @param e the element to be associated with the returned entry + * @param n the count to be associated with the returned entry + * @throws IllegalArgumentException if {@code n} is negative + */ + public static Multiset.Entry immutableEntry(@Nullable E e, int n) { + return new ImmutableEntry(e, n); } /** @@ -381,81 +652,6 @@ public final class Multisets { return 11; // initial capacity will be rounded up to 16 } - /** - * Returns an unmodifiable view of the union of two multisets. In the returned - * multiset, the count of each element is the maximum of its counts in - * the two backing multisets. The iteration order of the returned multiset - * matches that of the element set of {@code multiset1} followed by the members - * of the element set of {@code multiset2} that are not contained in - * {@code multiset1}, with repeated occurrences of the same element appearing - * consecutively. - * - *

- * Results are undefined if {@code multiset1} and {@code multiset2} are based on - * different equivalence relations (as {@code HashMultiset} and - * {@code TreeMultiset} are). - * - * @since 14.0 - */ - @Beta - public static Multiset union(final Multiset multiset1, final Multiset multiset2) { - checkNotNull(multiset1); - checkNotNull(multiset2); - - return new AbstractMultiset() { - @Override - public boolean contains(@Nullable Object element) { - return multiset1.contains(element) || multiset2.contains(element); - } - - @Override - public boolean isEmpty() { - return multiset1.isEmpty() && multiset2.isEmpty(); - } - - @Override - public int count(Object element) { - return Math.max(multiset1.count(element), multiset2.count(element)); - } - - @Override - Set createElementSet() { - return Sets.union(multiset1.elementSet(), multiset2.elementSet()); - } - - @Override - Iterator> entryIterator() { - final Iterator> iterator1 = multiset1.entrySet().iterator(); - final Iterator> iterator2 = multiset2.entrySet().iterator(); - // TODO(user): consider making the entries live views - return new AbstractIterator>() { - @Override - protected Entry computeNext() { - if (iterator1.hasNext()) { - Entry entry1 = iterator1.next(); - E element = entry1.getElement(); - int count = Math.max(entry1.getCount(), multiset2.count(element)); - return immutableEntry(element, count); - } - while (iterator2.hasNext()) { - Entry entry2 = iterator2.next(); - E element = entry2.getElement(); - if (!multiset1.contains(element)) { - return immutableEntry(element, entry2.getCount()); - } - } - return endOfData(); - } - }; - } - - @Override - int distinctElements() { - return elementSet().size(); - } - }; - } - /** * Returns an unmodifiable view of the intersection of two multisets. In the * returned multiset, the count of each element is the minimum of its @@ -487,6 +683,11 @@ public final class Multisets { return Sets.intersection(multiset1.elementSet(), multiset2.elementSet()); } + @Override + int distinctElements() { + return elementSet().size(); + } + @Override Iterator> entryIterator() { final Iterator> iterator1 = multiset1.entrySet().iterator(); @@ -506,164 +707,95 @@ public final class Multisets { } }; } - - @Override - int distinctElements() { - return elementSet().size(); - } }; } /** - * Returns an unmodifiable view of the sum of two multisets. In the returned - * multiset, the count of each element is the sum of its counts in the - * two backing multisets. The iteration order of the returned multiset matches - * that of the element set of {@code multiset1} followed by the members of the - * element set of {@code multiset2} that are not contained in {@code multiset1}, - * with repeated occurrences of the same element appearing consecutively. + * An implementation of {@link Multiset#iterator}. + */ + static Iterator iteratorImpl(Multiset multiset) { + return new MultisetIteratorImpl(multiset, multiset.entrySet().iterator()); + } + + /** + * An implementation of {@link Multiset#removeAll}. + */ + static boolean removeAllImpl(Multiset self, Collection elementsToRemove) { + Collection collection = (elementsToRemove instanceof Multiset) + ? ((Multiset) elementsToRemove).elementSet() + : elementsToRemove; + + return self.elementSet().removeAll(collection); + } + + /** + * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, + * removes one occurrence of {@code e} in {@code multisetToModify}. * *

- * Results are undefined if {@code multiset1} and {@code multiset2} are based on - * different equivalence relations (as {@code HashMultiset} and - * {@code TreeMultiset} are). - * - * @since 14.0 - */ - @Beta - public static Multiset sum(final Multiset multiset1, final Multiset multiset2) { - checkNotNull(multiset1); - checkNotNull(multiset2); - - // TODO(user): consider making the entries live views - return new AbstractMultiset() { - @Override - public boolean contains(@Nullable Object element) { - return multiset1.contains(element) || multiset2.contains(element); - } - - @Override - public boolean isEmpty() { - return multiset1.isEmpty() && multiset2.isEmpty(); - } - - @Override - public int size() { - return multiset1.size() + multiset2.size(); - } - - @Override - public int count(Object element) { - return multiset1.count(element) + multiset2.count(element); - } - - @Override - Set createElementSet() { - return Sets.union(multiset1.elementSet(), multiset2.elementSet()); - } - - @Override - Iterator> entryIterator() { - final Iterator> iterator1 = multiset1.entrySet().iterator(); - final Iterator> iterator2 = multiset2.entrySet().iterator(); - return new AbstractIterator>() { - @Override - protected Entry computeNext() { - if (iterator1.hasNext()) { - Entry entry1 = iterator1.next(); - E element = entry1.getElement(); - int count = entry1.getCount() + multiset2.count(element); - return immutableEntry(element, count); - } - while (iterator2.hasNext()) { - Entry entry2 = iterator2.next(); - E element = entry2.getElement(); - if (!multiset1.contains(element)) { - return immutableEntry(element, entry2.getCount()); - } - } - return endOfData(); - } - }; - } - - @Override - int distinctElements() { - return elementSet().size(); - } - }; - } - - /** - * Returns an unmodifiable view of the difference of two multisets. In the - * returned multiset, the count of each element is the result of the - * zero-truncated subtraction of its count in the second multiset from - * its count in the first multiset, with elements that would have a count of 0 - * not included. The iteration order of the returned multiset matches that of - * the element set of {@code multiset1}, with repeated occurrences of the same - * element appearing consecutively. + * Equivalently, this method modifies {@code multisetToModify} so that + * {@code multisetToModify.count(e)} is set to + * {@code Math.max(0, multisetToModify.count(e) - + * occurrencesToRemove.count(e))}. * *

- * Results are undefined if {@code multiset1} and {@code multiset2} are based on - * different equivalence relations (as {@code HashMultiset} and - * {@code TreeMultiset} are). + * This is not the same as {@code multisetToModify.} + * {@link Multiset#removeAll removeAll}{@code (occurrencesToRemove)}, which + * removes all occurrences of elements that appear in + * {@code occurrencesToRemove}. However, this operation is equivalent to, + * albeit more efficient than, the following: + * + *

+	 *    {@code
 	 *
-	 * @since 14.0
-	 */
-	@Beta
-	public static  Multiset difference(final Multiset multiset1, final Multiset multiset2) {
-		checkNotNull(multiset1);
-		checkNotNull(multiset2);
-
-		// TODO(user): consider making the entries live views
-		return new AbstractMultiset() {
-			@Override
-			public int count(@Nullable Object element) {
-				int count1 = multiset1.count(element);
-				return (count1 == 0) ? 0 : Math.max(0, count1 - multiset2.count(element));
-			}
-
-			@Override
-			Iterator> entryIterator() {
-				final Iterator> iterator1 = multiset1.entrySet().iterator();
-				return new AbstractIterator>() {
-					@Override
-					protected Entry computeNext() {
-						while (iterator1.hasNext()) {
-							Entry entry1 = iterator1.next();
-							E element = entry1.getElement();
-							int count = entry1.getCount() - multiset2.count(element);
-							if (count > 0) {
-								return immutableEntry(element, count);
-							}
-						}
-						return endOfData();
-					}
-				};
-			}
-
-			@Override
-			int distinctElements() {
-				return Iterators.size(entryIterator());
-			}
-		};
-	}
-
-	/**
-	 * Returns {@code true} if {@code subMultiset.count(o) <=
-	 * superMultiset.count(o)} for all {@code o}.
+	 * for (E e : occurrencesToRemove) {
+	 * 	multisetToModify.remove(e);
+	 * }
+	 * }
+	 * 
* + * @return {@code true} if {@code multisetToModify} was changed as a result of + * this operation * @since 10.0 */ - public static boolean containsOccurrences(Multiset superMultiset, Multiset subMultiset) { - checkNotNull(superMultiset); - checkNotNull(subMultiset); - for (Entry entry : subMultiset.entrySet()) { - int superCount = superMultiset.count(entry.getElement()); - if (superCount < entry.getCount()) { - return false; + public static boolean removeOccurrences(Multiset multisetToModify, Multiset occurrencesToRemove) { + return removeOccurrencesImpl(multisetToModify, occurrencesToRemove); + } + + /** + * Delegate that cares about the element types in occurrencesToRemove. + */ + private static boolean removeOccurrencesImpl(Multiset multisetToModify, Multiset occurrencesToRemove) { + // TODO(user): generalize to removing an Iterable, perhaps + checkNotNull(multisetToModify); + checkNotNull(occurrencesToRemove); + + boolean changed = false; + Iterator> entryIterator = multisetToModify.entrySet().iterator(); + while (entryIterator.hasNext()) { + Entry entry = entryIterator.next(); + int removeCount = occurrencesToRemove.count(entry.getElement()); + if (removeCount >= entry.getCount()) { + entryIterator.remove(); + changed = true; + } else if (removeCount > 0) { + multisetToModify.remove(entry.getElement(), removeCount); + changed = true; } } - return true; + return changed; + } + + /** + * An implementation of {@link Multiset#retainAll}. + */ + static boolean retainAllImpl(Multiset self, Collection elementsToRetain) { + checkNotNull(elementsToRetain); + Collection collection = (elementsToRetain instanceof Multiset) + ? ((Multiset) elementsToRetain).elementSet() + : elementsToRetain; + + return self.elementSet().retainAll(collection); } /** @@ -714,175 +846,6 @@ public final class Multisets { return changed; } - /** - * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, - * removes one occurrence of {@code e} in {@code multisetToModify}. - * - *

- * Equivalently, this method modifies {@code multisetToModify} so that - * {@code multisetToModify.count(e)} is set to - * {@code Math.max(0, multisetToModify.count(e) - - * occurrencesToRemove.count(e))}. - * - *

- * This is not the same as {@code multisetToModify.} - * {@link Multiset#removeAll removeAll}{@code (occurrencesToRemove)}, which - * removes all occurrences of elements that appear in - * {@code occurrencesToRemove}. However, this operation is equivalent to, - * albeit more efficient than, the following: - * - *

-	 *    {@code
-	 *
-	 *   for (E e : occurrencesToRemove) {
-	 *     multisetToModify.remove(e);
-	 *   }}
-	 * 
- * - * @return {@code true} if {@code multisetToModify} was changed as a result of - * this operation - * @since 10.0 - */ - public static boolean removeOccurrences(Multiset multisetToModify, Multiset occurrencesToRemove) { - return removeOccurrencesImpl(multisetToModify, occurrencesToRemove); - } - - /** - * Delegate that cares about the element types in occurrencesToRemove. - */ - private static boolean removeOccurrencesImpl(Multiset multisetToModify, Multiset occurrencesToRemove) { - // TODO(user): generalize to removing an Iterable, perhaps - checkNotNull(multisetToModify); - checkNotNull(occurrencesToRemove); - - boolean changed = false; - Iterator> entryIterator = multisetToModify.entrySet().iterator(); - while (entryIterator.hasNext()) { - Entry entry = entryIterator.next(); - int removeCount = occurrencesToRemove.count(entry.getElement()); - if (removeCount >= entry.getCount()) { - entryIterator.remove(); - changed = true; - } else if (removeCount > 0) { - multisetToModify.remove(entry.getElement(), removeCount); - changed = true; - } - } - return changed; - } - - /** - * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} - * methods of {@link Multiset.Entry}. - */ - abstract static class AbstractEntry implements Multiset.Entry { - /** - * Indicates whether an object equals this entry, following the behavior - * specified in {@link Multiset.Entry#equals}. - */ - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof Multiset.Entry) { - Multiset.Entry that = (Multiset.Entry) object; - return this.getCount() == that.getCount() && Objects.equal(this.getElement(), that.getElement()); - } - return false; - } - - /** - * Return this entry's hash code, following the behavior specified in - * {@link Multiset.Entry#hashCode}. - */ - @Override - public int hashCode() { - E e = getElement(); - return ((e == null) ? 0 : e.hashCode()) ^ getCount(); - } - - /** - * Returns a string representation of this multiset entry. The string - * representation consists of the associated element if the associated count is - * one, and otherwise the associated element followed by the characters " x " - * (space, x and space) followed by the count. Elements and counts are converted - * to strings as by {@code String.valueOf}. - */ - @Override - public String toString() { - String text = String.valueOf(getElement()); - int n = getCount(); - return (n == 1) ? text : (text + " x " + n); - } - } - - /** - * An implementation of {@link Multiset#equals}. - */ - static boolean equalsImpl(Multiset multiset, @Nullable Object object) { - if (object == multiset) { - return true; - } - if (object instanceof Multiset) { - Multiset that = (Multiset) object; - /* - * We can't simply check whether the entry sets are equal, since that approach - * fails when a TreeMultiset has a comparator that returns 0 when passed unequal - * elements. - */ - - if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) { - return false; - } - for (Entry entry : that.entrySet()) { - if (multiset.count(entry.getElement()) != entry.getCount()) { - return false; - } - } - return true; - } - return false; - } - - /** - * An implementation of {@link Multiset#addAll}. - */ - static boolean addAllImpl(Multiset self, Collection elements) { - if (elements.isEmpty()) { - return false; - } - if (elements instanceof Multiset) { - Multiset that = cast(elements); - for (Entry entry : that.entrySet()) { - self.add(entry.getElement(), entry.getCount()); - } - } else { - Iterators.addAll(self, elements.iterator()); - } - return true; - } - - /** - * An implementation of {@link Multiset#removeAll}. - */ - static boolean removeAllImpl(Multiset self, Collection elementsToRemove) { - Collection collection = (elementsToRemove instanceof Multiset) - ? ((Multiset) elementsToRemove).elementSet() - : elementsToRemove; - - return self.elementSet().removeAll(collection); - } - - /** - * An implementation of {@link Multiset#retainAll}. - */ - static boolean retainAllImpl(Multiset self, Collection elementsToRetain) { - checkNotNull(elementsToRetain); - Collection collection = (elementsToRetain instanceof Multiset) - ? ((Multiset) elementsToRetain).elementSet() - : elementsToRetain; - - return self.elementSet().retainAll(collection); - } - /** * An implementation of {@link Multiset#setCount(Object, int)}. */ @@ -916,154 +879,6 @@ public final class Multisets { } } - abstract static class ElementSet extends Sets.ImprovedAbstractSet { - abstract Multiset multiset(); - - @Override - public void clear() { - multiset().clear(); - } - - @Override - public boolean contains(Object o) { - return multiset().contains(o); - } - - @Override - public boolean containsAll(Collection c) { - return multiset().containsAll(c); - } - - @Override - public boolean isEmpty() { - return multiset().isEmpty(); - } - - @Override - public Iterator iterator() { - return new TransformedIterator, E>(multiset().entrySet().iterator()) { - @Override - E transform(Entry entry) { - return entry.getElement(); - } - }; - } - - @Override - public boolean remove(Object o) { - int count = multiset().count(o); - if (count > 0) { - multiset().remove(o, count); - return true; - } - return false; - } - - @Override - public int size() { - return multiset().entrySet().size(); - } - } - - abstract static class EntrySet extends Sets.ImprovedAbstractSet> { - abstract Multiset multiset(); - - @Override - public boolean contains(@Nullable Object o) { - if (o instanceof Entry) { - /* - * The GWT compiler wrongly issues a warning here. - */ - @SuppressWarnings("cast") - Entry entry = (Entry) o; - if (entry.getCount() <= 0) { - return false; - } - int count = multiset().count(entry.getElement()); - return count == entry.getCount(); - - } - return false; - } - - // GWT compiler warning; see contains(). - @SuppressWarnings("cast") - @Override - public boolean remove(Object object) { - if (object instanceof Multiset.Entry) { - Entry entry = (Entry) object; - Object element = entry.getElement(); - int entryCount = entry.getCount(); - if (entryCount != 0) { - // Safe as long as we never add a new entry, which we won't. - @SuppressWarnings("unchecked") - Multiset multiset = (Multiset) multiset(); - return multiset.setCount(element, entryCount, 0); - } - } - return false; - } - - @Override - public void clear() { - multiset().clear(); - } - } - - /** - * An implementation of {@link Multiset#iterator}. - */ - static Iterator iteratorImpl(Multiset multiset) { - return new MultisetIteratorImpl(multiset, multiset.entrySet().iterator()); - } - - static final class MultisetIteratorImpl implements Iterator { - private final Multiset multiset; - private final Iterator> entryIterator; - private Entry currentEntry; - /** Count of subsequent elements equal to current element */ - private int laterCount; - /** Count of all elements equal to current element */ - private int totalCount; - private boolean canRemove; - - MultisetIteratorImpl(Multiset multiset, Iterator> entryIterator) { - this.multiset = multiset; - this.entryIterator = entryIterator; - } - - @Override - public boolean hasNext() { - return laterCount > 0 || entryIterator.hasNext(); - } - - @Override - public E next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - if (laterCount == 0) { - currentEntry = entryIterator.next(); - totalCount = laterCount = currentEntry.getCount(); - } - laterCount--; - canRemove = true; - return currentEntry.getElement(); - } - - @Override - public void remove() { - checkRemove(canRemove); - if (totalCount == 1) { - entryIterator.remove(); - } else { - multiset.remove(currentEntry.getElement()); - } - totalCount--; - canRemove = false; - } - } - /** * An implementation of {@link Multiset#size}. */ @@ -1076,29 +891,215 @@ public final class Multisets { } /** - * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + * Returns an unmodifiable view of the sum of two multisets. In the returned + * multiset, the count of each element is the sum of its counts in the + * two backing multisets. The iteration order of the returned multiset matches + * that of the element set of {@code multiset1} followed by the members of the + * element set of {@code multiset2} that are not contained in {@code multiset1}, + * with repeated occurrences of the same element appearing consecutively. + * + *

+ * Results are undefined if {@code multiset1} and {@code multiset2} are based on + * different equivalence relations (as {@code HashMultiset} and + * {@code TreeMultiset} are). + * + * @since 14.0 */ - static Multiset cast(Iterable iterable) { - return (Multiset) iterable; + @Beta + public static Multiset sum(final Multiset multiset1, final Multiset multiset2) { + checkNotNull(multiset1); + checkNotNull(multiset2); + + // TODO(user): consider making the entries live views + return new AbstractMultiset() { + @Override + public boolean contains(@Nullable Object element) { + return multiset1.contains(element) || multiset2.contains(element); + } + + @Override + public int count(Object element) { + return multiset1.count(element) + multiset2.count(element); + } + + @Override + Set createElementSet() { + return Sets.union(multiset1.elementSet(), multiset2.elementSet()); + } + + @Override + int distinctElements() { + return elementSet().size(); + } + + @Override + Iterator> entryIterator() { + final Iterator> iterator1 = multiset1.entrySet().iterator(); + final Iterator> iterator2 = multiset2.entrySet().iterator(); + return new AbstractIterator>() { + @Override + protected Entry computeNext() { + if (iterator1.hasNext()) { + Entry entry1 = iterator1.next(); + E element = entry1.getElement(); + int count = entry1.getCount() + multiset2.count(element); + return immutableEntry(element, count); + } + while (iterator2.hasNext()) { + Entry entry2 = iterator2.next(); + E element = entry2.getElement(); + if (!multiset1.contains(element)) { + return immutableEntry(element, entry2.getCount()); + } + } + return endOfData(); + } + }; + } + + @Override + public boolean isEmpty() { + return multiset1.isEmpty() && multiset2.isEmpty(); + } + + @Override + public int size() { + return multiset1.size() + multiset2.size(); + } + }; } - private static final Ordering> DECREASING_COUNT_ORDERING = new Ordering>() { - @Override - public int compare(Entry entry1, Entry entry2) { - return Ints.compare(entry2.getCount(), entry1.getCount()); - } - }; + /** + * Returns an unmodifiable view of the union of two multisets. In the returned + * multiset, the count of each element is the maximum of its counts in + * the two backing multisets. The iteration order of the returned multiset + * matches that of the element set of {@code multiset1} followed by the members + * of the element set of {@code multiset2} that are not contained in + * {@code multiset1}, with repeated occurrences of the same element appearing + * consecutively. + * + *

+ * Results are undefined if {@code multiset1} and {@code multiset2} are based on + * different equivalence relations (as {@code HashMultiset} and + * {@code TreeMultiset} are). + * + * @since 14.0 + */ + @Beta + public static Multiset union(final Multiset multiset1, final Multiset multiset2) { + checkNotNull(multiset1); + checkNotNull(multiset2); + + return new AbstractMultiset() { + @Override + public boolean contains(@Nullable Object element) { + return multiset1.contains(element) || multiset2.contains(element); + } + + @Override + public int count(Object element) { + return Math.max(multiset1.count(element), multiset2.count(element)); + } + + @Override + Set createElementSet() { + return Sets.union(multiset1.elementSet(), multiset2.elementSet()); + } + + @Override + int distinctElements() { + return elementSet().size(); + } + + @Override + Iterator> entryIterator() { + final Iterator> iterator1 = multiset1.entrySet().iterator(); + final Iterator> iterator2 = multiset2.entrySet().iterator(); + // TODO(user): consider making the entries live views + return new AbstractIterator>() { + @Override + protected Entry computeNext() { + if (iterator1.hasNext()) { + Entry entry1 = iterator1.next(); + E element = entry1.getElement(); + int count = Math.max(entry1.getCount(), multiset2.count(element)); + return immutableEntry(element, count); + } + while (iterator2.hasNext()) { + Entry entry2 = iterator2.next(); + E element = entry2.getElement(); + if (!multiset1.contains(element)) { + return immutableEntry(element, entry2.getCount()); + } + } + return endOfData(); + } + }; + } + + @Override + public boolean isEmpty() { + return multiset1.isEmpty() && multiset2.isEmpty(); + } + }; + } /** - * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose - * iteration order is highest count first, with ties broken by the iteration - * order of the original multiset. + * Simply returns its argument. * + * @deprecated no need to use this + * @since 10.0 + */ + @Deprecated + public static Multiset unmodifiableMultiset(ImmutableMultiset multiset) { + return checkNotNull(multiset); + } + + /** + * Returns an unmodifiable view of the specified multiset. Query operations on + * the returned multiset "read through" to the specified multiset, and attempts + * to modify the returned multiset result in an + * {@link UnsupportedOperationException}. + * + *

+ * The returned multiset will be serializable if the specified multiset is + * serializable. + * + * @param multiset the multiset for which an unmodifiable view is to be + * generated + * @return an unmodifiable view of the multiset + */ + public static Multiset unmodifiableMultiset(Multiset multiset) { + if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) { + // Since it's unmodifiable, the covariant cast is safe + @SuppressWarnings("unchecked") + Multiset result = (Multiset) multiset; + return result; + } + return new UnmodifiableMultiset(checkNotNull(multiset)); + } + + /** + * Returns an unmodifiable view of the specified sorted multiset. Query + * operations on the returned multiset "read through" to the specified multiset, + * and attempts to modify the returned multiset result in an + * {@link UnsupportedOperationException}. + * + *

+ * The returned multiset will be serializable if the specified multiset is + * serializable. + * + * @param sortedMultiset the sorted multiset for which an unmodifiable view is + * to be generated + * @return an unmodifiable view of the multiset * @since 11.0 */ @Beta - public static ImmutableMultiset copyHighestCountFirst(Multiset multiset) { - List> sortedEntries = Multisets.DECREASING_COUNT_ORDERING.immutableSortedCopy(multiset.entrySet()); - return ImmutableMultiset.copyFromEntries(sortedEntries); + public static SortedMultiset unmodifiableSortedMultiset(SortedMultiset sortedMultiset) { + // it's in its own file so it can be emulated for GWT + return new UnmodifiableSortedMultiset(checkNotNull(sortedMultiset)); + } + + private Multisets() { } } diff --git a/src/main/java/com/google/common/collect/MutableClassToInstanceMap.java b/src/main/java/com/google/common/collect/MutableClassToInstanceMap.java index 25fab7da..b22b8a81 100644 --- a/src/main/java/com/google/common/collect/MutableClassToInstanceMap.java +++ b/src/main/java/com/google/common/collect/MutableClassToInstanceMap.java @@ -37,6 +37,19 @@ import com.google.common.primitives.Primitives; public final class MutableClassToInstanceMap extends ConstrainedMap, B> implements ClassToInstanceMap { + private static final MapConstraint, Object> VALUE_CAN_BE_CAST_TO_KEY = new MapConstraint, Object>() { + @Override + public void checkKeyValue(Class key, Object value) { + cast(key, value); + } + }; + + private static final long serialVersionUID = 0; + + private static T cast(Class type, B value) { + return Primitives.wrap(type).cast(value); + } + /** * Returns a new {@code MutableClassToInstanceMap} instance backed by a * {@link HashMap} using the default initial capacity and load factor. @@ -58,26 +71,13 @@ public final class MutableClassToInstanceMap extends ConstrainedMap, Object> VALUE_CAN_BE_CAST_TO_KEY = new MapConstraint, Object>() { - @Override - public void checkKeyValue(Class key, Object value) { - cast(key, value); - } - }; - - @Override - public T putInstance(Class type, T value) { - return cast(type, put(type, value)); - } - @Override public T getInstance(Class type) { return cast(type, get(type)); } - private static T cast(Class type, B value) { - return Primitives.wrap(type).cast(value); + @Override + public T putInstance(Class type, T value) { + return cast(type, put(type, value)); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/NaturalOrdering.java b/src/main/java/com/google/common/collect/NaturalOrdering.java index 5e85c03e..9463c5aa 100644 --- a/src/main/java/com/google/common/collect/NaturalOrdering.java +++ b/src/main/java/com/google/common/collect/NaturalOrdering.java @@ -28,6 +28,11 @@ import com.google.common.annotations.GwtCompatible; final class NaturalOrdering extends Ordering implements Serializable { static final NaturalOrdering INSTANCE = new NaturalOrdering(); + private static final long serialVersionUID = 0; + + private NaturalOrdering() { + } + @Override public int compare(Comparable left, Comparable right) { checkNotNull(left); // for GWT @@ -35,23 +40,18 @@ final class NaturalOrdering extends Ordering implements Serializable return left.compareTo(right); } - @Override - public Ordering reverse() { - return (Ordering) ReverseNaturalOrdering.INSTANCE; - } - // preserving singleton-ness gives equals()/hashCode() for free private Object readResolve() { return INSTANCE; } + @Override + public Ordering reverse() { + return (Ordering) ReverseNaturalOrdering.INSTANCE; + } + @Override public String toString() { return "Ordering.natural()"; } - - private NaturalOrdering() { - } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/NullsFirstOrdering.java b/src/main/java/com/google/common/collect/NullsFirstOrdering.java index 6176fcca..cde158dc 100644 --- a/src/main/java/com/google/common/collect/NullsFirstOrdering.java +++ b/src/main/java/com/google/common/collect/NullsFirstOrdering.java @@ -25,6 +25,8 @@ import com.google.common.annotations.GwtCompatible; /** An ordering that treats {@code null} as less than all other values. */ @GwtCompatible(serializable = true) final class NullsFirstOrdering extends Ordering implements Serializable { + private static final long serialVersionUID = 0; + final Ordering ordering; NullsFirstOrdering(Ordering ordering) { @@ -45,23 +47,6 @@ final class NullsFirstOrdering extends Ordering implements Serializable { return ordering.compare(left, right); } - @Override - public Ordering reverse() { - // ordering.reverse() might be optimized, so let it do its thing - return ordering.reverse().nullsLast(); - } - - @SuppressWarnings("unchecked") // still need the right way to explain this - @Override - public Ordering nullsFirst() { - return (Ordering) this; - } - - @Override - public Ordering nullsLast() { - return ordering.nullsLast(); - } - @Override public boolean equals(@Nullable Object object) { if (object == this) { @@ -79,10 +64,25 @@ final class NullsFirstOrdering extends Ordering implements Serializable { return ordering.hashCode() ^ 957692532; // meaningless } + @SuppressWarnings("unchecked") // still need the right way to explain this + @Override + public Ordering nullsFirst() { + return (Ordering) this; + } + + @Override + public Ordering nullsLast() { + return ordering.nullsLast(); + } + + @Override + public Ordering reverse() { + // ordering.reverse() might be optimized, so let it do its thing + return ordering.reverse().nullsLast(); + } + @Override public String toString() { return ordering + ".nullsFirst()"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/NullsLastOrdering.java b/src/main/java/com/google/common/collect/NullsLastOrdering.java index d8cf6078..97d02884 100644 --- a/src/main/java/com/google/common/collect/NullsLastOrdering.java +++ b/src/main/java/com/google/common/collect/NullsLastOrdering.java @@ -25,6 +25,8 @@ import com.google.common.annotations.GwtCompatible; /** An ordering that treats {@code null} as greater than all other values. */ @GwtCompatible(serializable = true) final class NullsLastOrdering extends Ordering implements Serializable { + private static final long serialVersionUID = 0; + final Ordering ordering; NullsLastOrdering(Ordering ordering) { @@ -45,23 +47,6 @@ final class NullsLastOrdering extends Ordering implements Serializable { return ordering.compare(left, right); } - @Override - public Ordering reverse() { - // ordering.reverse() might be optimized, so let it do its thing - return ordering.reverse().nullsFirst(); - } - - @Override - public Ordering nullsFirst() { - return ordering.nullsFirst(); - } - - @SuppressWarnings("unchecked") // still need the right way to explain this - @Override - public Ordering nullsLast() { - return (Ordering) this; - } - @Override public boolean equals(@Nullable Object object) { if (object == this) { @@ -79,10 +64,25 @@ final class NullsLastOrdering extends Ordering implements Serializable { return ordering.hashCode() ^ -921210296; // meaningless } + @Override + public Ordering nullsFirst() { + return ordering.nullsFirst(); + } + + @SuppressWarnings("unchecked") // still need the right way to explain this + @Override + public Ordering nullsLast() { + return (Ordering) this; + } + + @Override + public Ordering reverse() { + // ordering.reverse() might be optimized, so let it do its thing + return ordering.reverse().nullsFirst(); + } + @Override public String toString() { return ordering + ".nullsLast()"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ObjectArrays.java b/src/main/java/com/google/common/collect/ObjectArrays.java index b0ee28f5..61fe1b25 100644 --- a/src/main/java/com/google/common/collect/ObjectArrays.java +++ b/src/main/java/com/google/common/collect/ObjectArrays.java @@ -36,45 +36,31 @@ import com.google.common.annotations.GwtIncompatible; public final class ObjectArrays { static final Object[] EMPTY_ARRAY = new Object[0]; - private ObjectArrays() { + /** GWT safe version of Arrays.copyOf. */ + static T[] arraysCopyOf(T[] original, int newLength) { + T[] copy = newArray(original, newLength); + System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); + return copy; } - /** - * Returns a new array of the given length with the specified component type. - * - * @param type the component type - * @param length the length of the new array - */ - @GwtIncompatible("Array.newInstance(Class, int)") - @SuppressWarnings("unchecked") - public static T[] newArray(Class type, int length) { - return (T[]) Array.newInstance(type, length); + // We do this instead of Preconditions.checkNotNull to save boxing and array + // creation cost. + static Object checkElementNotNull(Object element, int index) { + if (element == null) { + throw new NullPointerException("at index " + index); + } + return element; } - /** - * Returns a new array of the given length with the same type as a reference - * array. - * - * @param reference any array of the desired type - * @param length the length of the new array - */ - public static T[] newArray(T[] reference, int length) { - return Platform.newArray(reference, length); + static Object[] checkElementsNotNull(Object... array) { + return checkElementsNotNull(array, array.length); } - /** - * Returns a new array that contains the concatenated contents of two arrays. - * - * @param first the first array of elements to concatenate - * @param second the second array of elements to concatenate - * @param type the component type of the returned array - */ - @GwtIncompatible("Array.newInstance(Class, int)") - public static T[] concat(T[] first, T[] second, Class type) { - T[] result = newArray(type, first.length + second.length); - System.arraycopy(first, 0, result, 0, first.length); - System.arraycopy(second, 0, result, first.length, second.length); - return result; + static Object[] checkElementsNotNull(Object[] array, int length) { + for (int i = 0; i < length; i++) { + checkElementNotNull(array[i], i); + } + return array; } /** @@ -108,11 +94,93 @@ public final class ObjectArrays { return result; } - /** GWT safe version of Arrays.copyOf. */ - static T[] arraysCopyOf(T[] original, int newLength) { - T[] copy = newArray(original, newLength); - System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); - return copy; + /** + * Returns a new array that contains the concatenated contents of two arrays. + * + * @param first the first array of elements to concatenate + * @param second the second array of elements to concatenate + * @param type the component type of the returned array + */ + @GwtIncompatible("Array.newInstance(Class, int)") + public static T[] concat(T[] first, T[] second, Class type) { + T[] result = newArray(type, first.length + second.length); + System.arraycopy(first, 0, result, 0, first.length); + System.arraycopy(second, 0, result, first.length, second.length); + return result; + } + + /** + * Returns a copy of the specified subrange of the specified array that is + * literally an Object[], and not e.g. a {@code String[]}. + */ + static Object[] copyAsObjectArray(Object[] elements, int offset, int length) { + checkPositionIndexes(offset, offset + length, elements.length); + if (length == 0) { + return EMPTY_ARRAY; + } + Object[] result = new Object[length]; + System.arraycopy(elements, offset, result, 0, length); + return result; + } + + private static Object[] fillArray(Iterable elements, Object[] array) { + int i = 0; + for (Object element : elements) { + array[i++] = element; + } + return array; + } + + /** + * Returns a new array of the given length with the specified component type. + * + * @param type the component type + * @param length the length of the new array + */ + @GwtIncompatible("Array.newInstance(Class, int)") + @SuppressWarnings("unchecked") + public static T[] newArray(Class type, int length) { + return (T[]) Array.newInstance(type, length); + } + + /** + * Returns a new array of the given length with the same type as a reference + * array. + * + * @param reference any array of the desired type + * @param length the length of the new array + */ + public static T[] newArray(T[] reference, int length) { + return Platform.newArray(reference, length); + } + + /** + * Swaps {@code array[i]} with {@code array[j]}. + */ + static void swap(Object[] array, int i, int j) { + Object temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + /** + * Returns an array containing all of the elements in the specified collection. + * This method returns the elements in the order they are returned by the + * collection's iterator. The returned array is "safe" in that no references to + * it are maintained by the collection. The caller is thus free to modify the + * returned array. + * + *

+ * This method assumes that the collection size doesn't change while the method + * is running. + * + *

+ * TODO(kevinb): support concurrently modified collections? + * + * @param c the collection for which to return an array of elements + */ + static Object[] toArrayImpl(Collection c) { + return fillArray(c, new Object[c.size()]); } /** @@ -179,74 +247,6 @@ public final class ObjectArrays { return dst; } - /** - * Returns an array containing all of the elements in the specified collection. - * This method returns the elements in the order they are returned by the - * collection's iterator. The returned array is "safe" in that no references to - * it are maintained by the collection. The caller is thus free to modify the - * returned array. - * - *

- * This method assumes that the collection size doesn't change while the method - * is running. - * - *

- * TODO(kevinb): support concurrently modified collections? - * - * @param c the collection for which to return an array of elements - */ - static Object[] toArrayImpl(Collection c) { - return fillArray(c, new Object[c.size()]); - } - - /** - * Returns a copy of the specified subrange of the specified array that is - * literally an Object[], and not e.g. a {@code String[]}. - */ - static Object[] copyAsObjectArray(Object[] elements, int offset, int length) { - checkPositionIndexes(offset, offset + length, elements.length); - if (length == 0) { - return EMPTY_ARRAY; - } - Object[] result = new Object[length]; - System.arraycopy(elements, offset, result, 0, length); - return result; - } - - private static Object[] fillArray(Iterable elements, Object[] array) { - int i = 0; - for (Object element : elements) { - array[i++] = element; - } - return array; - } - - /** - * Swaps {@code array[i]} with {@code array[j]}. - */ - static void swap(Object[] array, int i, int j) { - Object temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - - static Object[] checkElementsNotNull(Object... array) { - return checkElementsNotNull(array, array.length); - } - - static Object[] checkElementsNotNull(Object[] array, int length) { - for (int i = 0; i < length; i++) { - checkElementNotNull(array[i], i); - } - return array; - } - - // We do this instead of Preconditions.checkNotNull to save boxing and array - // creation cost. - static Object checkElementNotNull(Object element, int index) { - if (element == null) { - throw new NullPointerException("at index " + index); - } - return element; + private ObjectArrays() { } } diff --git a/src/main/java/com/google/common/collect/Ordering.java b/src/main/java/com/google/common/collect/Ordering.java index dc070b39..a38c7e91 100644 --- a/src/main/java/com/google/common/collect/Ordering.java +++ b/src/main/java/com/google/common/collect/Ordering.java @@ -95,49 +95,92 @@ public abstract class Ordering implements Comparator { // Natural order /** - * Returns a serializable ordering that uses the natural order of the values. - * The ordering throws a {@link NullPointerException} when passed a null - * parameter. - * - *

- * The type specification is {@code }, instead of the - * technically correct {@code >}, to support - * legacy types from before Java 5. + * Exception thrown by a {@link Ordering#explicit(List)} or + * {@link Ordering#explicit(Object, Object[])} comparator when comparing a value + * outside the set of values it can compare. Extending + * {@link ClassCastException} may seem odd, but it is required. */ - @GwtCompatible(serializable = true) - @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this?? - public static Ordering natural() { - return (Ordering) NaturalOrdering.INSTANCE; + // TODO(kevinb): make this public, document it right + @VisibleForTesting + static class IncomparableValueException extends ClassCastException { + private static final long serialVersionUID = 0; + + final Object value; + + IncomparableValueException(Object value) { + super("Cannot compare value: " + value); + this.value = value; + } } // Static factories + // Never make these public + static final int LEFT_IS_GREATER = 1; + + static final int RIGHT_IS_GREATER = -1; + /** - * Returns an ordering based on an existing comparator instance. Note - * that it is unnecessary to create a new anonymous inner class - * implementing {@code Comparator} just to pass it in here. Instead, simply - * subclass {@code Ordering} and implement its {@code compare} method directly. + * Returns an ordering which treats all values as equal, indicating "no + * ordering." Passing this ordering to any stable sort algorithm results + * in no change to the order of elements. Note especially that + * {@link #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the + * returned instance these are implemented by simply copying the source list. * - * @param comparator the comparator that defines the order - * @return comparator itself if it is already an {@code Ordering}; otherwise an - * ordering that wraps that comparator + *

+ * Example: + * + *

+	 *    {@code
+	 *
+	 * Ordering.allEqual().nullsLast().sortedCopy(asList(t, null, e, s, null, t, null))
+	 * }
+	 * 
+ * + *

+ * Assuming {@code t}, {@code e} and {@code s} are non-null, this returns + * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison + * order of those three values (which might not even implement + * {@link Comparable} at all). + * + *

+ * Warning: by definition, this comparator is not consistent with + * equals (as defined {@linkplain Comparator here}). Avoid its use in APIs, + * such as {@link TreeSet#TreeSet(Comparator)}, where such consistency is + * expected. + * + *

+ * The returned comparator is serializable. */ @GwtCompatible(serializable = true) - public static Ordering from(Comparator comparator) { - return (comparator instanceof Ordering) ? (Ordering) comparator : new ComparatorOrdering(comparator); + @SuppressWarnings("unchecked") + public static Ordering allEqual() { + return AllEqualOrdering.INSTANCE; } /** - * Simply returns its argument. + * Returns an ordering which tries each given comparator in order until a + * non-zero result is found, returning that result, and returning zero only if + * all comparators return zero. The returned ordering is based on the state of + * the {@code comparators} iterable at the time it was provided to this method. * - * @deprecated no need to use this + *

+ * The returned ordering is equivalent to that produced using {@code + * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. + * + *

+ * Warning: Supplying an argument with undefined iteration order, such as + * a {@link HashSet}, will produce non-deterministic results. + * + * @param comparators the comparators to try in order */ @GwtCompatible(serializable = true) - @Deprecated - public static Ordering from(Ordering ordering) { - return checkNotNull(ordering); + public static Ordering compound(Iterable> comparators) { + return new CompoundOrdering(comparators); } + // Ordering singletons + /** * Returns an ordering that compares objects according to the order in which * they appear in the given list. Only objects present in the list (according to @@ -198,44 +241,50 @@ public abstract class Ordering implements Comparator { return explicit(Lists.asList(leastValue, remainingValuesInOrder)); } - // Ordering singletons + // Constructor /** - * Returns an ordering which treats all values as equal, indicating "no - * ordering." Passing this ordering to any stable sort algorithm results - * in no change to the order of elements. Note especially that - * {@link #sortedCopy} and {@link #immutableSortedCopy} are stable, and in the - * returned instance these are implemented by simply copying the source list. + * Returns an ordering based on an existing comparator instance. Note + * that it is unnecessary to create a new anonymous inner class + * implementing {@code Comparator} just to pass it in here. Instead, simply + * subclass {@code Ordering} and implement its {@code compare} method directly. * - *

- * Example: - * - *

-	 *    {@code
-	 *
-	 *   Ordering.allEqual().nullsLast().sortedCopy(
-	 *       asList(t, null, e, s, null, t, null))}
-	 * 
- * - *

- * Assuming {@code t}, {@code e} and {@code s} are non-null, this returns - * {@code [t, e, s, t, null, null, null]} regardlesss of the true comparison - * order of those three values (which might not even implement - * {@link Comparable} at all). - * - *

- * Warning: by definition, this comparator is not consistent with - * equals (as defined {@linkplain Comparator here}). Avoid its use in APIs, - * such as {@link TreeSet#TreeSet(Comparator)}, where such consistency is - * expected. - * - *

- * The returned comparator is serializable. + * @param comparator the comparator that defines the order + * @return comparator itself if it is already an {@code Ordering}; otherwise an + * ordering that wraps that comparator */ @GwtCompatible(serializable = true) - @SuppressWarnings("unchecked") - public static Ordering allEqual() { - return AllEqualOrdering.INSTANCE; + public static Ordering from(Comparator comparator) { + return (comparator instanceof Ordering) ? (Ordering) comparator : new ComparatorOrdering(comparator); + } + + // Instance-based factories (and any static equivalents) + + /** + * Simply returns its argument. + * + * @deprecated no need to use this + */ + @GwtCompatible(serializable = true) + @Deprecated + public static Ordering from(Ordering ordering) { + return checkNotNull(ordering); + } + + /** + * Returns a serializable ordering that uses the natural order of the values. + * The ordering throws a {@link NullPointerException} when passed a null + * parameter. + * + *

+ * The type specification is {@code }, instead of the + * technically correct {@code >}, to support + * legacy types from before Java 5. + */ + @GwtCompatible(serializable = true) + @SuppressWarnings("unchecked") // TODO(kevinb): right way to explain this?? + public static Ordering natural() { + return (Ordering) NaturalOrdering.INSTANCE; } /** @@ -251,8 +300,6 @@ public abstract class Ordering implements Comparator { return UsingToStringOrdering.INSTANCE; } - // Constructor - /** * Constructs a new instance of this class (only invokable by the subclass * constructor, typically implicit). @@ -260,62 +307,21 @@ public abstract class Ordering implements Comparator { protected Ordering() { } - // Instance-based factories (and any static equivalents) - /** - * Returns the reverse of this ordering; the {@code Ordering} equivalent to - * {@link Collections#reverseOrder(Comparator)}. - */ - // type parameter lets us avoid the extra in statements like: - // Ordering o = Ordering.natural().reverse(); - @GwtCompatible(serializable = true) - public Ordering reverse() { - return new ReverseOrdering(this); - } - - /** - * Returns an ordering that treats {@code null} as less than all other values - * and uses {@code this} to compare non-null values. - */ - // type parameter lets us avoid the extra in statements like: - // Ordering o = Ordering.natural().nullsFirst(); - @GwtCompatible(serializable = true) - public Ordering nullsFirst() { - return new NullsFirstOrdering(this); - } - - /** - * Returns an ordering that treats {@code null} as greater than all other values - * and uses this ordering to compare non-null values. - */ - // type parameter lets us avoid the extra in statements like: - // Ordering o = Ordering.natural().nullsLast(); - @GwtCompatible(serializable = true) - public Ordering nullsLast() { - return new NullsLastOrdering(this); - } - - /** - * Returns a new ordering on {@code F} which orders elements by first applying a - * function to them, then comparing those results using {@code this}. For - * example, to compare objects by their string forms, in a case-insensitive - * manner, use: - * - *

-	 *    {@code
+	 * {@link Collections#binarySearch(List, Object, Comparator) Searches}
+	 * {@code sortedList} for {@code key} using the binary search algorithm. The
+	 * list must be sorted using this ordering.
 	 *
-	 *   Ordering.from(String.CASE_INSENSITIVE_ORDER)
-	 *       .onResultOf(Functions.toStringFunction())}
-	 * 
+ * @param sortedList the list to be searched + * @param key the key to be searched for */ - @GwtCompatible(serializable = true) - public Ordering onResultOf(Function function) { - return new ByFunctionOrdering(function, this); + public int binarySearch(List sortedList, @Nullable T key) { + return Collections.binarySearch(sortedList, key, this); } - Ordering> onKeys() { - return onResultOf(Maps.keyFunction()); - } + // Override to add @Nullable + @Override + public abstract int compare(@Nullable T left, @Nullable T right); /** * Returns an ordering which first uses the ordering {@code this}, but which in @@ -335,211 +341,115 @@ public abstract class Ordering implements Comparator { } /** - * Returns an ordering which tries each given comparator in order until a - * non-zero result is found, returning that result, and returning zero only if - * all comparators return zero. The returned ordering is based on the state of - * the {@code comparators} iterable at the time it was provided to this method. + * Returns the {@code k} greatest elements of the given iterable according to + * this ordering, in order from greatest to least. If there are fewer than + * {@code k} elements present, all will be included. * *

- * The returned ordering is equivalent to that produced using {@code - * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. + * The implementation does not necessarily use a stable sorting + * algorithm; when multiple elements are equivalent, it is undefined which will + * come first. * - *

- * Warning: Supplying an argument with undefined iteration order, such as - * a {@link HashSet}, will produce non-deterministic results. - * - * @param comparators the comparators to try in order + * @return an immutable {@code RandomAccess} list of the {@code k} greatest + * elements in descending order + * @throws IllegalArgumentException if {@code k} is negative + * @since 8.0 */ - @GwtCompatible(serializable = true) - public static Ordering compound(Iterable> comparators) { - return new CompoundOrdering(comparators); - } - - /** - * Returns a new ordering which sorts iterables by comparing corresponding - * elements pairwise until a nonzero result is found; imposes "dictionary - * order". If the end of one iterable is reached, but not the other, the shorter - * iterable is considered to be less than the longer one. For example, a - * lexicographical natural ordering over integers considers {@code - * [] < [1] < [1, 1] < [1, 2] < [2]}. - * - *

- * Note that {@code ordering.lexicographical().reverse()} is not equivalent to - * {@code ordering.reverse().lexicographical()} (consider how each would order - * {@code [1]} and {@code [1, 1]}). - * - * @since 2.0 - */ - @GwtCompatible(serializable = true) - // type parameter lets us avoid the extra in statements like: - // Ordering> o = - // Ordering.natural().lexicographical(); - public Ordering> lexicographical() { - /* - * Note that technically the returned ordering should be capable of handling not - * just {@code Iterable} instances, but also any {@code Iterable}. However, the need for this comes up so rarely that it doesn't justify - * making everyone else deal with the very ugly wildcard. - */ - return new LexicographicalOrdering(this); + public List greatestOf(Iterable iterable, int k) { + // TODO(kevinb): see if delegation is hurting performance noticeably + // TODO(kevinb): if we change this implementation, add full unit tests. + return reverse().leastOf(iterable, k); } // Regular instance methods - // Override to add @Nullable - @Override - public abstract int compare(@Nullable T left, @Nullable T right); - /** - * Returns the least of the specified values according to this ordering. If - * there are multiple least values, the first of those is returned. The iterator - * will be left exhausted: its {@code hasNext()} method will return - * {@code false}. - * - * @param iterator the iterator whose minimum element is to be determined - * @throws NoSuchElementException if {@code iterator} is empty - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. - * - * @since 11.0 - */ - public E min(Iterator iterator) { - // let this throw NoSuchElementException as necessary - E minSoFar = iterator.next(); - - while (iterator.hasNext()) { - minSoFar = min(minSoFar, iterator.next()); - } - - return minSoFar; - } - - /** - * Returns the least of the specified values according to this ordering. If - * there are multiple least values, the first of those is returned. - * - * @param iterable the iterable whose minimum element is to be determined - * @throws NoSuchElementException if {@code iterable} is empty - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. - */ - public E min(Iterable iterable) { - return min(iterable.iterator()); - } - - /** - * Returns the lesser of the two values according to this ordering. If the - * values compare as 0, the first is returned. + * Returns the {@code k} greatest elements from the given iterator according to + * this ordering, in order from greatest to least. If there are fewer than + * {@code k} elements present, all will be included. * *

- * Implementation note: this method is invoked by the default - * implementations of the other {@code min} overloads, so overriding it will - * affect their behavior. + * The implementation does not necessarily use a stable sorting + * algorithm; when multiple elements are equivalent, it is undefined which will + * come first. * - * @param a value to compare, returned if less than or equal to b. - * @param b value to compare. - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. + * @return an immutable {@code RandomAccess} list of the {@code k} greatest + * elements in descending order + * @throws IllegalArgumentException if {@code k} is negative + * @since 14.0 */ - public E min(@Nullable E a, @Nullable E b) { - return (compare(a, b) <= 0) ? a : b; + public List greatestOf(Iterator iterator, int k) { + return reverse().leastOf(iterator, k); } /** - * Returns the least of the specified values according to this ordering. If - * there are multiple least values, the first of those is returned. - * - * @param a value to compare, returned if less than or equal to the rest. - * @param b value to compare - * @param c value to compare - * @param rest values to compare - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. - */ - public E min(@Nullable E a, @Nullable E b, @Nullable E c, E... rest) { - E minSoFar = min(min(a, b), c); - - for (E r : rest) { - minSoFar = min(minSoFar, r); - } - - return minSoFar; - } - - /** - * Returns the greatest of the specified values according to this ordering. If - * there are multiple greatest values, the first of those is returned. The - * iterator will be left exhausted: its {@code hasNext()} method will return - * {@code false}. - * - * @param iterator the iterator whose maximum element is to be determined - * @throws NoSuchElementException if {@code iterator} is empty - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. - * - * @since 11.0 - */ - public E max(Iterator iterator) { - // let this throw NoSuchElementException as necessary - E maxSoFar = iterator.next(); - - while (iterator.hasNext()) { - maxSoFar = max(maxSoFar, iterator.next()); - } - - return maxSoFar; - } - - /** - * Returns the greatest of the specified values according to this ordering. If - * there are multiple greatest values, the first of those is returned. - * - * @param iterable the iterable whose maximum element is to be determined - * @throws NoSuchElementException if {@code iterable} is empty - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. - */ - public E max(Iterable iterable) { - return max(iterable.iterator()); - } - - /** - * Returns the greater of the two values according to this ordering. If the - * values compare as 0, the first is returned. + * Returns an immutable list containing {@code elements} sorted by this + * ordering. The input is not modified. * *

- * Implementation note: this method is invoked by the default - * implementations of the other {@code max} overloads, so overriding it will - * affect their behavior. + * Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard + * elements that are duplicates according to the comparator. The sort performed + * is stable, meaning that such elements will appear in the returned list + * in the same order they appeared in {@code elements}. * - * @param a value to compare, returned if greater than or equal to b. - * @param b value to compare. - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. + *

+ * Performance note: According to our benchmarking on Open JDK 7, this + * method is the most efficient way to make a sorted copy of a collection. + * + * @throws NullPointerException if any of {@code elements} (or {@code + * elements} itself) is null + * @since 3.0 */ - public E max(@Nullable E a, @Nullable E b) { - return (compare(a, b) >= 0) ? a : b; + public ImmutableList immutableSortedCopy(Iterable elements) { + @SuppressWarnings("unchecked") // we'll only ever have E's in here + E[] array = (E[]) Iterables.toArray(elements); + for (E e : array) { + checkNotNull(e); + } + Arrays.sort(array, this); + return ImmutableList.asImmutableList(array); } /** - * Returns the greatest of the specified values according to this ordering. If - * there are multiple greatest values, the first of those is returned. - * - * @param a value to compare, returned if greater than or equal to the rest. - * @param b value to compare - * @param c value to compare - * @param rest values to compare - * @throws ClassCastException if the parameters are not mutually - * comparable under this ordering. + * Returns {@code true} if each element in {@code iterable} after the first is + * greater than or equal to the element that preceded it, according to this + * ordering. Note that this is always true when the iterable has fewer than two + * elements. */ - public E max(@Nullable E a, @Nullable E b, @Nullable E c, E... rest) { - E maxSoFar = max(max(a, b), c); - - for (E r : rest) { - maxSoFar = max(maxSoFar, r); + public boolean isOrdered(Iterable iterable) { + Iterator it = iterable.iterator(); + if (it.hasNext()) { + T prev = it.next(); + while (it.hasNext()) { + T next = it.next(); + if (compare(prev, next) > 0) { + return false; + } + prev = next; + } } + return true; + } - return maxSoFar; + /** + * Returns {@code true} if each element in {@code iterable} after the first is + * strictly greater than the element that preceded it, according to this + * ordering. Note that this is always true when the iterable has fewer than two + * elements. + */ + public boolean isStrictlyOrdered(Iterable iterable) { + Iterator it = iterable.iterator(); + if (it.hasNext()) { + T prev = it.next(); + while (it.hasNext()) { + T next = it.next(); + if (compare(prev, next) >= 0) { + return false; + } + prev = next; + } + } + return true; } /** @@ -682,6 +592,231 @@ public abstract class Ordering implements Comparator { // We can't use ImmutableList; we have to be null-friendly! } + /** + * Returns a new ordering which sorts iterables by comparing corresponding + * elements pairwise until a nonzero result is found; imposes "dictionary + * order". If the end of one iterable is reached, but not the other, the shorter + * iterable is considered to be less than the longer one. For example, a + * lexicographical natural ordering over integers considers {@code + * [] < [1] < [1, 1] < [1, 2] < [2]}. + * + *

+ * Note that {@code ordering.lexicographical().reverse()} is not equivalent to + * {@code ordering.reverse().lexicographical()} (consider how each would order + * {@code [1]} and {@code [1, 1]}). + * + * @since 2.0 + */ + @GwtCompatible(serializable = true) + // type parameter lets us avoid the extra in statements like: + // Ordering> o = + // Ordering.natural().lexicographical(); + public Ordering> lexicographical() { + /* + * Note that technically the returned ordering should be capable of handling not + * just {@code Iterable} instances, but also any {@code Iterable}. However, the need for this comes up so rarely that it doesn't justify + * making everyone else deal with the very ugly wildcard. + */ + return new LexicographicalOrdering(this); + } + + /** + * Returns the greater of the two values according to this ordering. If the + * values compare as 0, the first is returned. + * + *

+ * Implementation note: this method is invoked by the default + * implementations of the other {@code max} overloads, so overriding it will + * affect their behavior. + * + * @param a value to compare, returned if greater than or equal to b. + * @param b value to compare. + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + */ + public E max(@Nullable E a, @Nullable E b) { + return (compare(a, b) >= 0) ? a : b; + } + + /** + * Returns the greatest of the specified values according to this ordering. If + * there are multiple greatest values, the first of those is returned. + * + * @param a value to compare, returned if greater than or equal to the rest. + * @param b value to compare + * @param c value to compare + * @param rest values to compare + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + */ + public E max(@Nullable E a, @Nullable E b, @Nullable E c, E... rest) { + E maxSoFar = max(max(a, b), c); + + for (E r : rest) { + maxSoFar = max(maxSoFar, r); + } + + return maxSoFar; + } + + /** + * Returns the greatest of the specified values according to this ordering. If + * there are multiple greatest values, the first of those is returned. + * + * @param iterable the iterable whose maximum element is to be determined + * @throws NoSuchElementException if {@code iterable} is empty + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + */ + public E max(Iterable iterable) { + return max(iterable.iterator()); + } + + /** + * Returns the greatest of the specified values according to this ordering. If + * there are multiple greatest values, the first of those is returned. The + * iterator will be left exhausted: its {@code hasNext()} method will return + * {@code false}. + * + * @param iterator the iterator whose maximum element is to be determined + * @throws NoSuchElementException if {@code iterator} is empty + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + * + * @since 11.0 + */ + public E max(Iterator iterator) { + // let this throw NoSuchElementException as necessary + E maxSoFar = iterator.next(); + + while (iterator.hasNext()) { + maxSoFar = max(maxSoFar, iterator.next()); + } + + return maxSoFar; + } + + /** + * Returns the lesser of the two values according to this ordering. If the + * values compare as 0, the first is returned. + * + *

+ * Implementation note: this method is invoked by the default + * implementations of the other {@code min} overloads, so overriding it will + * affect their behavior. + * + * @param a value to compare, returned if less than or equal to b. + * @param b value to compare. + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + */ + public E min(@Nullable E a, @Nullable E b) { + return (compare(a, b) <= 0) ? a : b; + } + + /** + * Returns the least of the specified values according to this ordering. If + * there are multiple least values, the first of those is returned. + * + * @param a value to compare, returned if less than or equal to the rest. + * @param b value to compare + * @param c value to compare + * @param rest values to compare + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + */ + public E min(@Nullable E a, @Nullable E b, @Nullable E c, E... rest) { + E minSoFar = min(min(a, b), c); + + for (E r : rest) { + minSoFar = min(minSoFar, r); + } + + return minSoFar; + } + + /** + * Returns the least of the specified values according to this ordering. If + * there are multiple least values, the first of those is returned. + * + * @param iterable the iterable whose minimum element is to be determined + * @throws NoSuchElementException if {@code iterable} is empty + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + */ + public E min(Iterable iterable) { + return min(iterable.iterator()); + } + + /** + * Returns the least of the specified values according to this ordering. If + * there are multiple least values, the first of those is returned. The iterator + * will be left exhausted: its {@code hasNext()} method will return + * {@code false}. + * + * @param iterator the iterator whose minimum element is to be determined + * @throws NoSuchElementException if {@code iterator} is empty + * @throws ClassCastException if the parameters are not mutually + * comparable under this ordering. + * + * @since 11.0 + */ + public E min(Iterator iterator) { + // let this throw NoSuchElementException as necessary + E minSoFar = iterator.next(); + + while (iterator.hasNext()) { + minSoFar = min(minSoFar, iterator.next()); + } + + return minSoFar; + } + + /** + * Returns an ordering that treats {@code null} as less than all other values + * and uses {@code this} to compare non-null values. + */ + // type parameter lets us avoid the extra in statements like: + // Ordering o = Ordering.natural().nullsFirst(); + @GwtCompatible(serializable = true) + public Ordering nullsFirst() { + return new NullsFirstOrdering(this); + } + + /** + * Returns an ordering that treats {@code null} as greater than all other values + * and uses this ordering to compare non-null values. + */ + // type parameter lets us avoid the extra in statements like: + // Ordering o = Ordering.natural().nullsLast(); + @GwtCompatible(serializable = true) + public Ordering nullsLast() { + return new NullsLastOrdering(this); + } + + Ordering> onKeys() { + return onResultOf(Maps.keyFunction()); + } + + /** + * Returns a new ordering on {@code F} which orders elements by first applying a + * function to them, then comparing those results using {@code this}. For + * example, to compare objects by their string forms, in a case-insensitive + * manner, use: + * + *

+	 *    {@code
+	 *
+	 * Ordering.from(String.CASE_INSENSITIVE_ORDER).onResultOf(Functions.toStringFunction())
+	 * }
+	 * 
+ */ + @GwtCompatible(serializable = true) + public Ordering onResultOf(Function function) { + return new ByFunctionOrdering(function, this); + } + private int partition(E[] values, int left, int right, int pivotIndex) { E pivotValue = values[pivotIndex]; @@ -700,43 +835,14 @@ public abstract class Ordering implements Comparator { } /** - * Returns the {@code k} greatest elements of the given iterable according to - * this ordering, in order from greatest to least. If there are fewer than - * {@code k} elements present, all will be included. - * - *

- * The implementation does not necessarily use a stable sorting - * algorithm; when multiple elements are equivalent, it is undefined which will - * come first. - * - * @return an immutable {@code RandomAccess} list of the {@code k} greatest - * elements in descending order - * @throws IllegalArgumentException if {@code k} is negative - * @since 8.0 + * Returns the reverse of this ordering; the {@code Ordering} equivalent to + * {@link Collections#reverseOrder(Comparator)}. */ - public List greatestOf(Iterable iterable, int k) { - // TODO(kevinb): see if delegation is hurting performance noticeably - // TODO(kevinb): if we change this implementation, add full unit tests. - return reverse().leastOf(iterable, k); - } - - /** - * Returns the {@code k} greatest elements from the given iterator according to - * this ordering, in order from greatest to least. If there are fewer than - * {@code k} elements present, all will be included. - * - *

- * The implementation does not necessarily use a stable sorting - * algorithm; when multiple elements are equivalent, it is undefined which will - * come first. - * - * @return an immutable {@code RandomAccess} list of the {@code k} greatest - * elements in descending order - * @throws IllegalArgumentException if {@code k} is negative - * @since 14.0 - */ - public List greatestOf(Iterator iterator, int k) { - return reverse().leastOf(iterator, k); + // type parameter lets us avoid the extra in statements like: + // Ordering o = Ordering.natural().reverse(); + @GwtCompatible(serializable = true) + public Ordering reverse() { + return new ReverseOrdering(this); } /** @@ -763,109 +869,4 @@ public abstract class Ordering implements Comparator { Arrays.sort(array, this); return Lists.newArrayList(Arrays.asList(array)); } - - /** - * Returns an immutable list containing {@code elements} sorted by this - * ordering. The input is not modified. - * - *

- * Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard - * elements that are duplicates according to the comparator. The sort performed - * is stable, meaning that such elements will appear in the returned list - * in the same order they appeared in {@code elements}. - * - *

- * Performance note: According to our benchmarking on Open JDK 7, this - * method is the most efficient way to make a sorted copy of a collection. - * - * @throws NullPointerException if any of {@code elements} (or {@code - * elements} itself) is null - * @since 3.0 - */ - public ImmutableList immutableSortedCopy(Iterable elements) { - @SuppressWarnings("unchecked") // we'll only ever have E's in here - E[] array = (E[]) Iterables.toArray(elements); - for (E e : array) { - checkNotNull(e); - } - Arrays.sort(array, this); - return ImmutableList.asImmutableList(array); - } - - /** - * Returns {@code true} if each element in {@code iterable} after the first is - * greater than or equal to the element that preceded it, according to this - * ordering. Note that this is always true when the iterable has fewer than two - * elements. - */ - public boolean isOrdered(Iterable iterable) { - Iterator it = iterable.iterator(); - if (it.hasNext()) { - T prev = it.next(); - while (it.hasNext()) { - T next = it.next(); - if (compare(prev, next) > 0) { - return false; - } - prev = next; - } - } - return true; - } - - /** - * Returns {@code true} if each element in {@code iterable} after the first is - * strictly greater than the element that preceded it, according to this - * ordering. Note that this is always true when the iterable has fewer than two - * elements. - */ - public boolean isStrictlyOrdered(Iterable iterable) { - Iterator it = iterable.iterator(); - if (it.hasNext()) { - T prev = it.next(); - while (it.hasNext()) { - T next = it.next(); - if (compare(prev, next) >= 0) { - return false; - } - prev = next; - } - } - return true; - } - - /** - * {@link Collections#binarySearch(List, Object, Comparator) Searches} - * {@code sortedList} for {@code key} using the binary search algorithm. The - * list must be sorted using this ordering. - * - * @param sortedList the list to be searched - * @param key the key to be searched for - */ - public int binarySearch(List sortedList, @Nullable T key) { - return Collections.binarySearch(sortedList, key, this); - } - - /** - * Exception thrown by a {@link Ordering#explicit(List)} or - * {@link Ordering#explicit(Object, Object[])} comparator when comparing a value - * outside the set of values it can compare. Extending - * {@link ClassCastException} may seem odd, but it is required. - */ - // TODO(kevinb): make this public, document it right - @VisibleForTesting - static class IncomparableValueException extends ClassCastException { - final Object value; - - IncomparableValueException(Object value) { - super("Cannot compare value: " + value); - this.value = value; - } - - private static final long serialVersionUID = 0; - } - - // Never make these public - static final int LEFT_IS_GREATER = 1; - static final int RIGHT_IS_GREATER = -1; } diff --git a/src/main/java/com/google/common/collect/PeekingIterator.java b/src/main/java/com/google/common/collect/PeekingIterator.java index 6a16c69f..8a9e023b 100644 --- a/src/main/java/com/google/common/collect/PeekingIterator.java +++ b/src/main/java/com/google/common/collect/PeekingIterator.java @@ -34,6 +34,16 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public interface PeekingIterator extends Iterator { + /** + * {@inheritDoc} + * + *

+ * The objects returned by consecutive calls to {@link #peek()} then + * {@link #next()} are guaranteed to be equal to each other. + */ + @Override + E next(); + /** * Returns the next element in the iteration, without advancing the iteration. * @@ -47,16 +57,6 @@ public interface PeekingIterator extends Iterator { */ E peek(); - /** - * {@inheritDoc} - * - *

- * The objects returned by consecutive calls to {@link #peek()} then - * {@link #next()} are guaranteed to be equal to each other. - */ - @Override - E next(); - /** * {@inheritDoc} * diff --git a/src/main/java/com/google/common/collect/Platform.java b/src/main/java/com/google/common/collect/Platform.java index 08534085..30a8f069 100644 --- a/src/main/java/com/google/common/collect/Platform.java +++ b/src/main/java/com/google/common/collect/Platform.java @@ -37,6 +37,23 @@ import com.google.common.collect.Maps.EntryTransformer; */ @GwtCompatible(emulated = true) final class Platform { + static SortedMap mapsAsMapSortedSet(SortedSet set, Function function) { + return (set instanceof NavigableSet) ? Maps.asMap((NavigableSet) set, function) + : Maps.asMapSortedIgnoreNavigable(set, function); + } + + static SortedMap mapsFilterSortedMap(SortedMap map, + Predicate> predicate) { + return (map instanceof NavigableMap) ? Maps.filterEntries((NavigableMap) map, predicate) + : Maps.filterSortedIgnoreNavigable(map, predicate); + } + + static SortedMap mapsTransformEntriesSortedMap(SortedMap fromMap, + EntryTransformer transformer) { + return (fromMap instanceof NavigableMap) ? Maps.transformEntries((NavigableMap) fromMap, transformer) + : Maps.transformEntriesIgnoreNavigable(fromMap, transformer); + } + /** * Returns a new array of the given length with the same type as a reference * array. @@ -58,28 +75,11 @@ final class Platform { return Collections.newSetFromMap(map); } - static SortedMap mapsTransformEntriesSortedMap(SortedMap fromMap, - EntryTransformer transformer) { - return (fromMap instanceof NavigableMap) ? Maps.transformEntries((NavigableMap) fromMap, transformer) - : Maps.transformEntriesIgnoreNavigable(fromMap, transformer); - } - - static SortedMap mapsAsMapSortedSet(SortedSet set, Function function) { - return (set instanceof NavigableSet) ? Maps.asMap((NavigableSet) set, function) - : Maps.asMapSortedIgnoreNavigable(set, function); - } - static SortedSet setsFilterSortedSet(SortedSet set, Predicate predicate) { return (set instanceof NavigableSet) ? Sets.filter((NavigableSet) set, predicate) : Sets.filterSortedIgnoreNavigable(set, predicate); } - static SortedMap mapsFilterSortedMap(SortedMap map, - Predicate> predicate) { - return (map instanceof NavigableMap) ? Maps.filterEntries((NavigableMap) map, predicate) - : Maps.filterSortedIgnoreNavigable(map, predicate); - } - private Platform() { } } diff --git a/src/main/java/com/google/common/collect/Range.java b/src/main/java/com/google/common/collect/Range.java index 9521fef6..8fdbe8cc 100644 --- a/src/main/java/com/google/common/collect/Range.java +++ b/src/main/java/com/google/common/collect/Range.java @@ -166,11 +166,6 @@ public final class Range implements Predicate, Serializ } }; - @SuppressWarnings("unchecked") - static > Function, Cut> lowerBoundFn() { - return (Function) LOWER_BOUND_FN; - } - private static final Function UPPER_BOUND_FN = new Function() { @Override public Cut apply(Range range) { @@ -178,11 +173,6 @@ public final class Range implements Predicate, Serializ } }; - @SuppressWarnings("unchecked") - static > Function, Cut> upperBoundFn() { - return (Function) UPPER_BOUND_FN; - } - static final Ordering> RANGE_LEX_ORDERING = new Ordering>() { @Override public int compare(Range left, Range right) { @@ -191,20 +181,45 @@ public final class Range implements Predicate, Serializ } }; - static > Range create(Cut lowerBound, Cut upperBound) { - return new Range(lowerBound, upperBound); + private static final Range ALL = new Range(Cut.belowAll(), Cut.aboveAll()); + + private static final long serialVersionUID = 0; + + /** + * Returns a range that contains every value of type {@code C}. + * + * @since 14.0 + */ + @SuppressWarnings("unchecked") + public static > Range all() { + return (Range) ALL; } /** - * Returns a range that contains all values strictly greater than {@code - * lower} and strictly less than {@code upper}. + * Returns a range that contains all values greater than or equal to + * {@code endpoint}. * - * @throws IllegalArgumentException if {@code lower} is greater than or equal - * to {@code upper} * @since 14.0 */ - public static > Range open(C lower, C upper) { - return create(Cut.aboveValue(lower), Cut.belowValue(upper)); + public static > Range atLeast(C endpoint) { + return create(Cut.belowValue(endpoint), Cut.aboveAll()); + } + + /** + * Returns a range that contains all values less than or equal to + * {@code endpoint}. + * + * @since 14.0 + */ + public static > Range atMost(C endpoint) { + return create(Cut.belowAll(), Cut.aboveValue(endpoint)); + } + + /** + * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + */ + private static SortedSet cast(Iterable iterable) { + return (SortedSet) iterable; } /** @@ -231,6 +246,96 @@ public final class Range implements Predicate, Serializ return create(Cut.belowValue(lower), Cut.belowValue(upper)); } + @SuppressWarnings("unchecked") // this method may throw CCE + static int compareOrThrow(Comparable left, Comparable right) { + return left.compareTo(right); + } + + static > Range create(Cut lowerBound, Cut upperBound) { + return new Range(lowerBound, upperBound); + } + + /** + * Returns a range from the given endpoint, which may be either inclusive + * (closed) or exclusive (open), with no upper bound. + * + * @since 14.0 + */ + public static > Range downTo(C endpoint, BoundType boundType) { + switch (boundType) { + case OPEN: + return greaterThan(endpoint); + case CLOSED: + return atLeast(endpoint); + default: + throw new AssertionError(); + } + } + + /** + * Returns the minimal range that {@linkplain Range#contains(Comparable) + * contains} all of the given values. The returned range is + * {@linkplain BoundType#CLOSED closed} on both ends. + * + * @throws ClassCastException if the parameters are not mutually + * comparable + * @throws NoSuchElementException if {@code values} is empty + * @throws NullPointerException if any of {@code values} is null + * @since 14.0 + */ + public static > Range encloseAll(Iterable values) { + checkNotNull(values); + if (values instanceof ContiguousSet) { + return ((ContiguousSet) values).range(); + } + Iterator valueIterator = values.iterator(); + C min = checkNotNull(valueIterator.next()); + C max = min; + while (valueIterator.hasNext()) { + C value = checkNotNull(valueIterator.next()); + min = Ordering.natural().min(min, value); + max = Ordering.natural().max(max, value); + } + return closed(min, max); + } + + /** + * Returns a range that contains all values strictly greater than {@code + * endpoint}. + * + * @since 14.0 + */ + public static > Range greaterThan(C endpoint) { + return create(Cut.aboveValue(endpoint), Cut.aboveAll()); + } + + /** + * Returns a range that contains all values strictly less than {@code + * endpoint}. + * + * @since 14.0 + */ + public static > Range lessThan(C endpoint) { + return create(Cut.belowAll(), Cut.belowValue(endpoint)); + } + + @SuppressWarnings("unchecked") + static > Function, Cut> lowerBoundFn() { + return (Function) LOWER_BOUND_FN; + } + + /** + * Returns a range that contains all values strictly greater than {@code + * lower} and strictly less than {@code upper}. + * + * @throws IllegalArgumentException if {@code lower} is greater than or equal + * to {@code upper} + * @since 14.0 + */ + public static > Range open(C lower, C upper) { + return create(Cut.aboveValue(lower), Cut.belowValue(upper)); + } + /** * Returns a range that contains all values strictly greater than {@code * lower} and less than or equal to {@code upper}. @@ -262,23 +367,27 @@ public final class Range implements Predicate, Serializ } /** - * Returns a range that contains all values strictly less than {@code - * endpoint}. + * Returns a range that {@linkplain Range#contains(Comparable) contains} only + * the given value. The returned range is {@linkplain BoundType#CLOSED closed} + * on both ends. * * @since 14.0 */ - public static > Range lessThan(C endpoint) { - return create(Cut.belowAll(), Cut.belowValue(endpoint)); + public static > Range singleton(C value) { + return closed(value, value); } - /** - * Returns a range that contains all values less than or equal to - * {@code endpoint}. - * - * @since 14.0 - */ - public static > Range atMost(C endpoint) { - return create(Cut.belowAll(), Cut.aboveValue(endpoint)); + private static String toString(Cut lowerBound, Cut upperBound) { + StringBuilder sb = new StringBuilder(16); + lowerBound.describeAsLowerBound(sb); + sb.append('\u2025'); + upperBound.describeAsUpperBound(sb); + return sb.toString(); + } + + @SuppressWarnings("unchecked") + static > Function, Cut> upperBoundFn() { + return (Function) UPPER_BOUND_FN; } /** @@ -298,94 +407,8 @@ public final class Range implements Predicate, Serializ } } - /** - * Returns a range that contains all values strictly greater than {@code - * endpoint}. - * - * @since 14.0 - */ - public static > Range greaterThan(C endpoint) { - return create(Cut.aboveValue(endpoint), Cut.aboveAll()); - } - - /** - * Returns a range that contains all values greater than or equal to - * {@code endpoint}. - * - * @since 14.0 - */ - public static > Range atLeast(C endpoint) { - return create(Cut.belowValue(endpoint), Cut.aboveAll()); - } - - /** - * Returns a range from the given endpoint, which may be either inclusive - * (closed) or exclusive (open), with no upper bound. - * - * @since 14.0 - */ - public static > Range downTo(C endpoint, BoundType boundType) { - switch (boundType) { - case OPEN: - return greaterThan(endpoint); - case CLOSED: - return atLeast(endpoint); - default: - throw new AssertionError(); - } - } - - private static final Range ALL = new Range(Cut.belowAll(), Cut.aboveAll()); - - /** - * Returns a range that contains every value of type {@code C}. - * - * @since 14.0 - */ - @SuppressWarnings("unchecked") - public static > Range all() { - return (Range) ALL; - } - - /** - * Returns a range that {@linkplain Range#contains(Comparable) contains} only - * the given value. The returned range is {@linkplain BoundType#CLOSED closed} - * on both ends. - * - * @since 14.0 - */ - public static > Range singleton(C value) { - return closed(value, value); - } - - /** - * Returns the minimal range that {@linkplain Range#contains(Comparable) - * contains} all of the given values. The returned range is - * {@linkplain BoundType#CLOSED closed} on both ends. - * - * @throws ClassCastException if the parameters are not mutually - * comparable - * @throws NoSuchElementException if {@code values} is empty - * @throws NullPointerException if any of {@code values} is null - * @since 14.0 - */ - public static > Range encloseAll(Iterable values) { - checkNotNull(values); - if (values instanceof ContiguousSet) { - return ((ContiguousSet) values).range(); - } - Iterator valueIterator = values.iterator(); - C min = checkNotNull(valueIterator.next()); - C max = min; - while (valueIterator.hasNext()) { - C value = checkNotNull(valueIterator.next()); - min = Ordering.natural().min(min, value); - max = Ordering.natural().max(max, value); - } - return closed(min, max); - } - final Cut lowerBound; + final Cut upperBound; private Range(Cut lowerBound, Cut upperBound) { @@ -398,74 +421,47 @@ public final class Range implements Predicate, Serializ } /** - * Returns {@code true} if this range has a lower endpoint. + * @deprecated Provided only to satisfy the {@link Predicate} interface; use + * {@link #contains} instead. */ - public boolean hasLowerBound() { - return lowerBound != Cut.belowAll(); + @Deprecated + @Override + public boolean apply(C input) { + return contains(input); } /** - * Returns the lower endpoint of this range. + * Returns the canonical form of this range in the given domain. The canonical + * form has the following properties: * - * @throws IllegalStateException if this range is unbounded below (that is, - * {@link #hasLowerBound()} returns {@code false}) - */ - public C lowerEndpoint() { - return lowerBound.endpoint(); - } - - /** - * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the - * range includes its lower endpoint, {@link BoundType#OPEN} if it does not. - * - * @throws IllegalStateException if this range is unbounded below (that is, - * {@link #hasLowerBound()} returns {@code false}) - */ - public BoundType lowerBoundType() { - return lowerBound.typeAsLowerBound(); - } - - /** - * Returns {@code true} if this range has an upper endpoint. - */ - public boolean hasUpperBound() { - return upperBound != Cut.aboveAll(); - } - - /** - * Returns the upper endpoint of this range. - * - * @throws IllegalStateException if this range is unbounded above (that is, - * {@link #hasUpperBound()} returns {@code false}) - */ - public C upperEndpoint() { - return upperBound.endpoint(); - } - - /** - * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the - * range includes its upper endpoint, {@link BoundType#OPEN} if it does not. - * - * @throws IllegalStateException if this range is unbounded above (that is, - * {@link #hasUpperBound()} returns {@code false}) - */ - public BoundType upperBoundType() { - return upperBound.typeAsUpperBound(); - } - - /** - * Returns {@code true} if this range is of the form {@code [v..v)} or - * {@code (v..v]}. (This does not encompass ranges of the form {@code (v..v)}, - * because such ranges are invalid and can't be constructed at all.) + *

    + *
  • equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all + * {@code v} (in other words, + * {@code ContiguousSet.create(a.canonical(domain), domain).equals( + * ContiguousSet.create(a, domain))} + *
  • uniqueness: unless {@code a.isEmpty()}, + * {@code ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))} + * implies {@code a.canonical(domain).equals(b.canonical(domain))} + *
  • idempotence: + * {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))} + *
* *

- * Note that certain discrete ranges such as the integer range {@code (3..4)} - * are not considered empty, even though they contain no actual values. - * In these cases, it may be helpful to preprocess ranges with - * {@link #canonical(DiscreteDomain)}. + * Furthermore, this method guarantees that the range returned will be one of + * the following canonical forms: + * + *

    + *
  • [start..end) + *
  • [start..+∞) + *
  • (-∞..end) (only if type {@code C} is unbounded below) + *
  • (-∞..+∞) (only if type {@code C} is unbounded below) + *
*/ - public boolean isEmpty() { - return lowerBound.equals(upperBound); + public Range canonical(DiscreteDomain domain) { + checkNotNull(domain); + Cut lower = lowerBound.canonical(domain); + Cut upper = upperBound.canonical(domain); + return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper); } /** @@ -479,16 +475,6 @@ public final class Range implements Predicate, Serializ return lowerBound.isLessThan(value) && !upperBound.isLessThan(value); } - /** - * @deprecated Provided only to satisfy the {@link Predicate} interface; use - * {@link #contains} instead. - */ - @Deprecated - @Override - public boolean apply(C input) { - return contains(input); - } - /** * Returns {@code true} if every element in {@code values} is * {@linkplain #contains contained} in this range. @@ -547,38 +533,41 @@ public final class Range implements Predicate, Serializ } /** - * Returns {@code true} if there exists a (possibly empty) range which is - * {@linkplain #encloses enclosed} by both this range and {@code other}. - * - *

- * For example, - *

    - *
  • {@code [2, 4)} and {@code [5, 7)} are not connected - *
  • {@code [2, 4)} and {@code [3, 5)} are connected, because both enclose - * {@code [3, 4)} - *
  • {@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the - * empty range {@code [4, 4)} - *
- * - *

- * Note that this range and {@code other} have a well-defined {@linkplain #span - * union} and {@linkplain #intersection intersection} (as a single, - * possibly-empty range) if and only if this method returns {@code true}. - * - *

- * The connectedness relation is both reflexive and symmetric, but does not form - * an {@linkplain Equivalence equivalence relation} as it is not transitive. - * - *

- * Note that certain discrete ranges are not considered connected, even though - * there are no elements "between them." For example, {@code [3, 5]} is not - * considered connected to {@code - * [6, 10]}. In these cases, it may be desirable for both input ranges to be - * preprocessed with {@link #canonical(DiscreteDomain)} before testing for - * connectedness. + * Returns {@code true} if {@code object} is a range having the same endpoints + * and bound types as this range. Note that discrete ranges such as + * {@code (1..4)} and {@code [2..3]} are not equal to one another, + * despite the fact that they each contain precisely the same set of values. + * Similarly, empty ranges are not equal unless they have exactly the same + * representation, so {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all + * unequal. */ - public boolean isConnected(Range other) { - return lowerBound.compareTo(other.upperBound) <= 0 && other.lowerBound.compareTo(upperBound) <= 0; + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof Range) { + Range other = (Range) object; + return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound); + } + return false; + } + + /** Returns a hash code for this range. */ + @Override + public int hashCode() { + return lowerBound.hashCode() * 31 + upperBound.hashCode(); + } + + /** + * Returns {@code true} if this range has a lower endpoint. + */ + public boolean hasLowerBound() { + return lowerBound != Cut.belowAll(); + } + + /** + * Returns {@code true} if this range has an upper endpoint. + */ + public boolean hasUpperBound() { + return upperBound != Cut.aboveAll(); } /** @@ -616,6 +605,85 @@ public final class Range implements Predicate, Serializ } } + /** + * Returns {@code true} if there exists a (possibly empty) range which is + * {@linkplain #encloses enclosed} by both this range and {@code other}. + * + *

+ * For example, + *

    + *
  • {@code [2, 4)} and {@code [5, 7)} are not connected + *
  • {@code [2, 4)} and {@code [3, 5)} are connected, because both enclose + * {@code [3, 4)} + *
  • {@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the + * empty range {@code [4, 4)} + *
+ * + *

+ * Note that this range and {@code other} have a well-defined {@linkplain #span + * union} and {@linkplain #intersection intersection} (as a single, + * possibly-empty range) if and only if this method returns {@code true}. + * + *

+ * The connectedness relation is both reflexive and symmetric, but does not form + * an {@linkplain Equivalence equivalence relation} as it is not transitive. + * + *

+ * Note that certain discrete ranges are not considered connected, even though + * there are no elements "between them." For example, {@code [3, 5]} is not + * considered connected to {@code + * [6, 10]}. In these cases, it may be desirable for both input ranges to be + * preprocessed with {@link #canonical(DiscreteDomain)} before testing for + * connectedness. + */ + public boolean isConnected(Range other) { + return lowerBound.compareTo(other.upperBound) <= 0 && other.lowerBound.compareTo(upperBound) <= 0; + } + + /** + * Returns {@code true} if this range is of the form {@code [v..v)} or + * {@code (v..v]}. (This does not encompass ranges of the form {@code (v..v)}, + * because such ranges are invalid and can't be constructed at all.) + * + *

+ * Note that certain discrete ranges such as the integer range {@code (3..4)} + * are not considered empty, even though they contain no actual values. + * In these cases, it may be helpful to preprocess ranges with + * {@link #canonical(DiscreteDomain)}. + */ + public boolean isEmpty() { + return lowerBound.equals(upperBound); + } + + /** + * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the + * range includes its lower endpoint, {@link BoundType#OPEN} if it does not. + * + * @throws IllegalStateException if this range is unbounded below (that is, + * {@link #hasLowerBound()} returns {@code false}) + */ + public BoundType lowerBoundType() { + return lowerBound.typeAsLowerBound(); + } + + /** + * Returns the lower endpoint of this range. + * + * @throws IllegalStateException if this range is unbounded below (that is, + * {@link #hasLowerBound()} returns {@code false}) + */ + public C lowerEndpoint() { + return lowerBound.endpoint(); + } + + Object readResolve() { + if (this.equals(ALL)) { + return all(); + } else { + return this; + } + } + /** * Returns the minimal range that {@linkplain #encloses encloses} both this * range and {@code @@ -647,64 +715,6 @@ public final class Range implements Predicate, Serializ } } - /** - * Returns the canonical form of this range in the given domain. The canonical - * form has the following properties: - * - *

    - *
  • equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all - * {@code v} (in other words, - * {@code ContiguousSet.create(a.canonical(domain), domain).equals( - * ContiguousSet.create(a, domain))} - *
  • uniqueness: unless {@code a.isEmpty()}, - * {@code ContiguousSet.create(a, domain).equals(ContiguousSet.create(b, domain))} - * implies {@code a.canonical(domain).equals(b.canonical(domain))} - *
  • idempotence: - * {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))} - *
- * - *

- * Furthermore, this method guarantees that the range returned will be one of - * the following canonical forms: - * - *

    - *
  • [start..end) - *
  • [start..+∞) - *
  • (-∞..end) (only if type {@code C} is unbounded below) - *
  • (-∞..+∞) (only if type {@code C} is unbounded below) - *
- */ - public Range canonical(DiscreteDomain domain) { - checkNotNull(domain); - Cut lower = lowerBound.canonical(domain); - Cut upper = upperBound.canonical(domain); - return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper); - } - - /** - * Returns {@code true} if {@code object} is a range having the same endpoints - * and bound types as this range. Note that discrete ranges such as - * {@code (1..4)} and {@code [2..3]} are not equal to one another, - * despite the fact that they each contain precisely the same set of values. - * Similarly, empty ranges are not equal unless they have exactly the same - * representation, so {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all - * unequal. - */ - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof Range) { - Range other = (Range) object; - return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound); - } - return false; - } - - /** Returns a hash code for this range. */ - @Override - public int hashCode() { - return lowerBound.hashCode() * 31 + upperBound.hashCode(); - } - /** * Returns a string representation of this range, such as {@code "[3..5)"} * (other examples are listed in the class documentation). @@ -714,33 +724,24 @@ public final class Range implements Predicate, Serializ return toString(lowerBound, upperBound); } - private static String toString(Cut lowerBound, Cut upperBound) { - StringBuilder sb = new StringBuilder(16); - lowerBound.describeAsLowerBound(sb); - sb.append('\u2025'); - upperBound.describeAsUpperBound(sb); - return sb.toString(); + /** + * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the + * range includes its upper endpoint, {@link BoundType#OPEN} if it does not. + * + * @throws IllegalStateException if this range is unbounded above (that is, + * {@link #hasUpperBound()} returns {@code false}) + */ + public BoundType upperBoundType() { + return upperBound.typeAsUpperBound(); } /** - * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 + * Returns the upper endpoint of this range. + * + * @throws IllegalStateException if this range is unbounded above (that is, + * {@link #hasUpperBound()} returns {@code false}) */ - private static SortedSet cast(Iterable iterable) { - return (SortedSet) iterable; + public C upperEndpoint() { + return upperBound.endpoint(); } - - Object readResolve() { - if (this.equals(ALL)) { - return all(); - } else { - return this; - } - } - - @SuppressWarnings("unchecked") // this method may throw CCE - static int compareOrThrow(Comparable left, Comparable right) { - return left.compareTo(right); - } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/RangeMap.java b/src/main/java/com/google/common/collect/RangeMap.java index 37c947eb..150a9c76 100644 --- a/src/main/java/com/google/common/collect/RangeMap.java +++ b/src/main/java/com/google/common/collect/RangeMap.java @@ -37,6 +37,28 @@ import com.google.common.annotations.Beta; */ @Beta public interface RangeMap { + /** + * Returns a view of this range map as an unmodifiable {@code Map, V>}. + * Modifications to this range map are guaranteed to read through to the + * returned {@code Map}. + * + *

+ * It is guaranteed that no empty ranges will be in the returned {@code Map}. + */ + Map, V> asMapOfRanges(); + + /** + * Removes all associations from this range map (optional operation). + */ + void clear(); + + /** + * Returns {@code true} if {@code obj} is another {@code RangeMap} that has an + * equivalent {@link #asMapOfRanges()}. + */ + @Override + boolean equals(@Nullable Object o); + /** * Returns the value associated with the specified key, or {@code null} if there * is no such value. @@ -56,12 +78,10 @@ public interface RangeMap { Map.Entry, V> getEntry(K key); /** - * Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the - * ranges in this {@code RangeMap}. - * - * @throws NoSuchElementException if this range map is empty + * Returns {@code asMapOfRanges().hashCode()}. */ - Range span(); + @Override + int hashCode(); /** * Maps a range to a specified value (optional operation). @@ -82,11 +102,6 @@ public interface RangeMap { */ void putAll(RangeMap rangeMap); - /** - * Removes all associations from this range map (optional operation). - */ - void clear(); - /** * Removes all associations from this range map in the specified range (optional * operation). @@ -100,14 +115,12 @@ public interface RangeMap { void remove(Range range); /** - * Returns a view of this range map as an unmodifiable {@code Map, V>}. - * Modifications to this range map are guaranteed to read through to the - * returned {@code Map}. + * Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the + * ranges in this {@code RangeMap}. * - *

- * It is guaranteed that no empty ranges will be in the returned {@code Map}. + * @throws NoSuchElementException if this range map is empty */ - Map, V> asMapOfRanges(); + Range span(); /** * Returns a view of the part of this range map that intersects with @@ -130,19 +143,6 @@ public interface RangeMap { */ RangeMap subRangeMap(Range range); - /** - * Returns {@code true} if {@code obj} is another {@code RangeMap} that has an - * equivalent {@link #asMapOfRanges()}. - */ - @Override - boolean equals(@Nullable Object o); - - /** - * Returns {@code asMapOfRanges().hashCode()}. - */ - @Override - int hashCode(); - /** * Returns a readable string representation of this range map. */ diff --git a/src/main/java/com/google/common/collect/RangeSet.java b/src/main/java/com/google/common/collect/RangeSet.java index 48da68f2..22318921 100644 --- a/src/main/java/com/google/common/collect/RangeSet.java +++ b/src/main/java/com/google/common/collect/RangeSet.java @@ -32,12 +32,13 @@ import com.google.common.annotations.Beta; *

  *    {@code
  *
- *   RangeSet rangeSet = TreeRangeSet.create();
- *   rangeSet.add(Range.closed(1, 10)); // {[1, 10]}
- *   rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)}
- *   rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)}
- *   rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)}
- *   rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)}}
+ * RangeSet rangeSet = TreeRangeSet.create();
+ * rangeSet.add(Range.closed(1, 10)); // {[1, 10]}
+ * rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)}
+ * rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)}
+ * rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)}
+ * rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)}
+ * }
  * 
* *

@@ -58,18 +59,73 @@ public interface RangeSet { // Query methods + /** + * Adds the specified range to this {@code RangeSet} (optional operation). That + * is, for equal range sets a and b, the result of {@code a.add(range)} is that + * {@code a} will be the minimal range set for which both + * {@code a.enclosesAll(b)} and {@code a.encloses(range)}. + * + *

+ * Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with + * any ranges in the range set that are {@linkplain Range#isConnected(Range) + * connected} with it. Moreover, if {@code range} is empty, this is a no-op. + * + * @throws UnsupportedOperationException if this range set does not support the + * {@code add} operation + */ + void add(Range range); + + /** + * Adds all of the ranges from the specified range set to this range set + * (optional operation). After this operation, this range set is the minimal + * range set that {@linkplain #enclosesAll(RangeSet) encloses} both the original + * range set and {@code other}. + * + *

+ * This is equivalent to calling {@link #add} on each of the ranges in + * {@code other} in turn. + * + * @throws UnsupportedOperationException if this range set does not support the + * {@code addAll} operation + */ + void addAll(RangeSet other); + + /** + * Returns a view of the {@linkplain Range#isConnected disconnected} ranges that + * make up this range set. The returned set may be empty. The iterators returned + * by its {@link Iterable#iterator} method return the ranges in increasing order + * of lower bound (equivalently, of upper bound). + */ + Set> asRanges(); + + /** + * Removes all ranges from this {@code RangeSet} (optional operation). After + * this operation, {@code this.contains(c)} will return false for all {@code c}. + * + *

+ * This is equivalent to {@code remove(Range.all())}. + * + * @throws UnsupportedOperationException if this range set does not support the + * {@code clear} operation + */ + void clear(); + + /** + * Returns a view of the complement of this {@code RangeSet}. + * + *

+ * The returned view supports the {@link #add} operation if this + * {@code RangeSet} supports {@link #remove}, and vice versa. + */ + RangeSet complement(); + /** * Determines whether any of this range set's member ranges contains * {@code value}. */ boolean contains(C value); - /** - * Returns the unique range from this range set that {@linkplain Range#contains - * contains} {@code value}, or {@code null} if this range set does not contain - * {@code value}. - */ - Range rangeContaining(C value); + // Views /** * Returns {@code true} if there exists a member range in this range set which @@ -90,68 +146,32 @@ public interface RangeSet { */ boolean enclosesAll(RangeSet other); + /** + * Returns {@code true} if {@code obj} is another {@code RangeSet} that contains + * the same ranges according to {@link Range#equals(Object)}. + */ + @Override + boolean equals(@Nullable Object obj); + + // Modification + + /** + * Returns {@code asRanges().hashCode()}. + */ + @Override + int hashCode(); + /** * Returns {@code true} if this range set contains no ranges. */ boolean isEmpty(); /** - * Returns the minimal range which {@linkplain Range#encloses(Range) encloses} - * all ranges in this range set. - * - * @throws NoSuchElementException if this range set is {@linkplain #isEmpty() - * empty} + * Returns the unique range from this range set that {@linkplain Range#contains + * contains} {@code value}, or {@code null} if this range set does not contain + * {@code value}. */ - Range span(); - - // Views - - /** - * Returns a view of the {@linkplain Range#isConnected disconnected} ranges that - * make up this range set. The returned set may be empty. The iterators returned - * by its {@link Iterable#iterator} method return the ranges in increasing order - * of lower bound (equivalently, of upper bound). - */ - Set> asRanges(); - - /** - * Returns a view of the complement of this {@code RangeSet}. - * - *

- * The returned view supports the {@link #add} operation if this - * {@code RangeSet} supports {@link #remove}, and vice versa. - */ - RangeSet complement(); - - /** - * Returns a view of the intersection of this {@code RangeSet} with the - * specified range. - * - *

- * The returned view supports all optional operations supported by this - * {@code RangeSet}, with the caveat that an {@link IllegalArgumentException} is - * thrown on an attempt to {@linkplain #add(Range) add} any range not - * {@linkplain Range#encloses(Range) enclosed} by {@code view}. - */ - RangeSet subRangeSet(Range view); - - // Modification - - /** - * Adds the specified range to this {@code RangeSet} (optional operation). That - * is, for equal range sets a and b, the result of {@code a.add(range)} is that - * {@code a} will be the minimal range set for which both - * {@code a.enclosesAll(b)} and {@code a.encloses(range)}. - * - *

- * Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with - * any ranges in the range set that are {@linkplain Range#isConnected(Range) - * connected} with it. Moreover, if {@code range} is empty, this is a no-op. - * - * @throws UnsupportedOperationException if this range set does not support the - * {@code add} operation - */ - void add(Range range); + Range rangeContaining(C value); /** * Removes the specified range from this {@code RangeSet} (optional operation). @@ -166,33 +186,6 @@ public interface RangeSet { */ void remove(Range range); - /** - * Removes all ranges from this {@code RangeSet} (optional operation). After - * this operation, {@code this.contains(c)} will return false for all {@code c}. - * - *

- * This is equivalent to {@code remove(Range.all())}. - * - * @throws UnsupportedOperationException if this range set does not support the - * {@code clear} operation - */ - void clear(); - - /** - * Adds all of the ranges from the specified range set to this range set - * (optional operation). After this operation, this range set is the minimal - * range set that {@linkplain #enclosesAll(RangeSet) encloses} both the original - * range set and {@code other}. - * - *

- * This is equivalent to calling {@link #add} on each of the ranges in - * {@code other} in turn. - * - * @throws UnsupportedOperationException if this range set does not support the - * {@code addAll} operation - */ - void addAll(RangeSet other); - /** * Removes all of the ranges from the specified range set from this range set * (optional operation). After this operation, if {@code other.contains(c)}, @@ -210,23 +203,30 @@ public interface RangeSet { // Object methods /** - * Returns {@code true} if {@code obj} is another {@code RangeSet} that contains - * the same ranges according to {@link Range#equals(Object)}. + * Returns the minimal range which {@linkplain Range#encloses(Range) encloses} + * all ranges in this range set. + * + * @throws NoSuchElementException if this range set is {@linkplain #isEmpty() + * empty} */ - @Override - boolean equals(@Nullable Object obj); + Range span(); /** - * Returns {@code asRanges().hashCode()}. + * Returns a view of the intersection of this {@code RangeSet} with the + * specified range. + * + *

+ * The returned view supports all optional operations supported by this + * {@code RangeSet}, with the caveat that an {@link IllegalArgumentException} is + * thrown on an attempt to {@linkplain #add(Range) add} any range not + * {@linkplain Range#encloses(Range) enclosed} by {@code view}. */ - @Override - int hashCode(); + RangeSet subRangeSet(Range view); /** * Returns a readable string representation of this range set. For example, if * this {@code RangeSet} consisted of {@code Range.closed(1, 3)} and - * {@code Range.greaterThan(4)}, this might return - * {@code " [1‥3](4‥+∞)}"}. + * {@code Range.greaterThan(4)}, this might return {@code " [1‥3](4‥+∞)}"}. */ @Override String toString(); diff --git a/src/main/java/com/google/common/collect/RegularContiguousSet.java b/src/main/java/com/google/common/collect/RegularContiguousSet.java index 51ede32d..2e705589 100644 --- a/src/main/java/com/google/common/collect/RegularContiguousSet.java +++ b/src/main/java/com/google/common/collect/RegularContiguousSet.java @@ -35,92 +35,32 @@ import com.google.common.annotations.GwtIncompatible; @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class RegularContiguousSet extends ContiguousSet { - private final Range range; + @GwtIncompatible("serialization") + private static final class SerializedForm implements Serializable { + final Range range; + final DiscreteDomain domain; - RegularContiguousSet(Range range, DiscreteDomain domain) { - super(domain); - this.range = range; - } - - private ContiguousSet intersectionInCurrentDomain(Range other) { - return (range.isConnected(other)) ? ContiguousSet.create(range.intersection(other), domain) - : new EmptyContiguousSet(domain); - } - - @Override - ContiguousSet headSetImpl(C toElement, boolean inclusive) { - return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive))); - } - - @Override - ContiguousSet subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { - if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) { - // Range would reject our attempt to create (x, x). - return new EmptyContiguousSet(domain); + private SerializedForm(Range range, DiscreteDomain domain) { + this.range = range; + this.domain = domain; + } + + private Object readResolve() { + return new RegularContiguousSet(range, domain); } - return intersectionInCurrentDomain(Range.range(fromElement, BoundType.forBoolean(fromInclusive), toElement, - BoundType.forBoolean(toInclusive))); } - @Override - ContiguousSet tailSetImpl(C fromElement, boolean inclusive) { - return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); - } - - @GwtIncompatible("not used by GWT emulation") - @Override - int indexOf(Object target) { - return contains(target) ? (int) domain.distance(first(), (C) target) : -1; - } - - @Override - public UnmodifiableIterator iterator() { - return new AbstractSequentialIterator(first()) { - final C last = last(); - - @Override - protected C computeNext(C previous) { - return equalsOrThrow(previous, last) ? null : domain.next(previous); - } - }; - } - - @GwtIncompatible("NavigableSet") - @Override - public UnmodifiableIterator descendingIterator() { - return new AbstractSequentialIterator(last()) { - final C first = first(); - - @Override - protected C computeNext(C previous) { - return equalsOrThrow(previous, first) ? null : domain.previous(previous); - } - }; - } + private static final long serialVersionUID = 0; private static boolean equalsOrThrow(Comparable left, @Nullable Comparable right) { return right != null && Range.compareOrThrow(left, right) == 0; } - @Override - boolean isPartialView() { - return false; - } + private final Range range; - @Override - public C first() { - return range.lowerBound.leastValueAbove(domain); - } - - @Override - public C last() { - return range.upperBound.greatestValueBelow(domain); - } - - @Override - public int size() { - long distance = domain.distance(first(), last()); - return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1; + RegularContiguousSet(Range range, DiscreteDomain domain) { + super(domain); + this.range = range; } @Override @@ -140,9 +80,52 @@ final class RegularContiguousSet extends ContiguousSet return Collections2.containsAllImpl(this, targets); } + @GwtIncompatible("NavigableSet") @Override - public boolean isEmpty() { - return false; + public UnmodifiableIterator descendingIterator() { + return new AbstractSequentialIterator(last()) { + final C first = first(); + + @Override + protected C computeNext(C previous) { + return equalsOrThrow(previous, first) ? null : domain.previous(previous); + } + }; + } + + @Override + public boolean equals(@Nullable Object object) { + if (object == this) { + return true; + } else if (object instanceof RegularContiguousSet) { + RegularContiguousSet that = (RegularContiguousSet) object; + if (this.domain.equals(that.domain)) { + return this.first().equals(that.first()) && this.last().equals(that.last()); + } + } + return super.equals(object); + } + + @Override + public C first() { + return range.lowerBound.leastValueAbove(domain); + } + + // copied to make sure not to use the GWT-emulated version + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); + } + + @Override + ContiguousSet headSetImpl(C toElement, boolean inclusive) { + return intersectionInCurrentDomain(Range.upTo(toElement, BoundType.forBoolean(inclusive))); + } + + @GwtIncompatible("not used by GWT emulation") + @Override + int indexOf(Object target) { + return contains(target) ? (int) domain.distance(first(), (C) target) : -1; } @Override @@ -160,6 +143,38 @@ final class RegularContiguousSet extends ContiguousSet } } + private ContiguousSet intersectionInCurrentDomain(Range other) { + return (range.isConnected(other)) ? ContiguousSet.create(range.intersection(other), domain) + : new EmptyContiguousSet(domain); + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public UnmodifiableIterator iterator() { + return new AbstractSequentialIterator(first()) { + final C last = last(); + + @Override + protected C computeNext(C previous) { + return equalsOrThrow(previous, last) ? null : domain.next(previous); + } + }; + } + + @Override + public C last() { + return range.upperBound.greatestValueBelow(domain); + } + @Override public Range range() { return range(CLOSED, CLOSED); @@ -172,37 +187,24 @@ final class RegularContiguousSet extends ContiguousSet } @Override - public boolean equals(@Nullable Object object) { - if (object == this) { - return true; - } else if (object instanceof RegularContiguousSet) { - RegularContiguousSet that = (RegularContiguousSet) object; - if (this.domain.equals(that.domain)) { - return this.first().equals(that.first()) && this.last().equals(that.last()); - } - } - return super.equals(object); + public int size() { + long distance = domain.distance(first(), last()); + return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1; } - // copied to make sure not to use the GWT-emulated version @Override - public int hashCode() { - return Sets.hashCodeImpl(this); + ContiguousSet subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { + if (fromElement.compareTo(toElement) == 0 && !fromInclusive && !toInclusive) { + // Range would reject our attempt to create (x, x). + return new EmptyContiguousSet(domain); + } + return intersectionInCurrentDomain(Range.range(fromElement, BoundType.forBoolean(fromInclusive), toElement, + BoundType.forBoolean(toInclusive))); } - @GwtIncompatible("serialization") - private static final class SerializedForm implements Serializable { - final Range range; - final DiscreteDomain domain; - - private SerializedForm(Range range, DiscreteDomain domain) { - this.range = range; - this.domain = domain; - } - - private Object readResolve() { - return new RegularContiguousSet(range, domain); - } + @Override + ContiguousSet tailSetImpl(C fromElement, boolean inclusive) { + return intersectionInCurrentDomain(Range.downTo(fromElement, BoundType.forBoolean(inclusive))); } @GwtIncompatible("serialization") @@ -210,6 +212,4 @@ final class RegularContiguousSet extends ContiguousSet Object writeReplace() { return new SerializedForm(range, domain); } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/RegularImmutableAsList.java b/src/main/java/com/google/common/collect/RegularImmutableAsList.java index 52d5f2a8..67d45acd 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableAsList.java +++ b/src/main/java/com/google/common/collect/RegularImmutableAsList.java @@ -40,6 +40,12 @@ class RegularImmutableAsList extends ImmutableAsList { this(delegate, ImmutableList.asImmutableList(array)); } + @GwtIncompatible("not present in emulated superclass") + @Override + int copyIntoArray(Object[] dst, int offset) { + return delegateList.copyIntoArray(dst, offset); + } + @Override ImmutableCollection delegateCollection() { return delegate; @@ -49,20 +55,14 @@ class RegularImmutableAsList extends ImmutableAsList { return delegateList; } + @Override + public E get(int index) { + return delegateList.get(index); + } + @SuppressWarnings("unchecked") // safe covariant cast! @Override public UnmodifiableListIterator listIterator(int index) { return (UnmodifiableListIterator) delegateList.listIterator(index); } - - @GwtIncompatible("not present in emulated superclass") - @Override - int copyIntoArray(Object[] dst, int offset) { - return delegateList.copyIntoArray(dst, offset); - } - - @Override - public E get(int index) { - return delegateList.get(index); - } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableBiMap.java b/src/main/java/com/google/common/collect/RegularImmutableBiMap.java index 96e44a16..45d7e7c3 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableBiMap.java +++ b/src/main/java/com/google/common/collect/RegularImmutableBiMap.java @@ -34,16 +34,200 @@ import com.google.common.collect.ImmutableMapEntry.TerminalEntry; @SuppressWarnings("serial") // uses writeReplace(), not default serialization class RegularImmutableBiMap extends ImmutableBiMap { + private final class Inverse extends ImmutableBiMap { + + final class InverseEntrySet extends ImmutableMapEntrySet { + @Override + ImmutableList> createAsList() { + return new ImmutableAsList>() { + @Override + ImmutableCollection> delegateCollection() { + return InverseEntrySet.this; + } + + @Override + public Entry get(int index) { + Entry entry = entries[index]; + return Maps.immutableEntry(entry.getValue(), entry.getKey()); + } + }; + } + + @Override + public int hashCode() { + return hashCode; + } + + @Override + boolean isHashCodeFast() { + return true; + } + + @Override + public UnmodifiableIterator> iterator() { + return asList().iterator(); + } + + @Override + ImmutableMap map() { + return Inverse.this; + } + } + + @Override + ImmutableSet> createEntrySet() { + return new InverseEntrySet(); + } + + @Override + public K get(@Nullable Object value) { + if (value == null) { + return null; + } + int bucket = Hashing.smear(value.hashCode()) & mask; + for (ImmutableMapEntry entry = valueTable[bucket]; entry != null; entry = entry + .getNextInValueBucket()) { + if (value.equals(entry.getValue())) { + return entry.getKey(); + } + } + return null; + } + + @Override + public ImmutableBiMap inverse() { + return RegularImmutableBiMap.this; + } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public int size() { + return inverse().size(); + } + + @Override + Object writeReplace() { + return new InverseSerializedForm(RegularImmutableBiMap.this); + } + } + + private static class InverseSerializedForm implements Serializable { + private static final long serialVersionUID = 1; + + private final ImmutableBiMap forward; + + InverseSerializedForm(ImmutableBiMap forward) { + this.forward = forward; + } + + Object readResolve() { + return forward.inverse(); + } + } + + private static final class NonTerminalBiMapEntry extends ImmutableMapEntry { + @Nullable + private final ImmutableMapEntry nextInKeyBucket; + @Nullable + private final ImmutableMapEntry nextInValueBucket; + + NonTerminalBiMapEntry(ImmutableMapEntry contents, @Nullable ImmutableMapEntry nextInKeyBucket, + @Nullable ImmutableMapEntry nextInValueBucket) { + super(contents); + this.nextInKeyBucket = nextInKeyBucket; + this.nextInValueBucket = nextInValueBucket; + } + + NonTerminalBiMapEntry(K key, V value, @Nullable ImmutableMapEntry nextInKeyBucket, + @Nullable ImmutableMapEntry nextInValueBucket) { + super(key, value); + this.nextInKeyBucket = nextInKeyBucket; + this.nextInValueBucket = nextInValueBucket; + } + + @Override + @Nullable + ImmutableMapEntry getNextInKeyBucket() { + return nextInKeyBucket; + } + + @Override + @Nullable + ImmutableMapEntry getNextInValueBucket() { + return nextInValueBucket; + } + } + static final double MAX_LOAD_FACTOR = 1.2; + @SuppressWarnings("unchecked") + private static ImmutableMapEntry[] createEntryArray(int length) { + return new ImmutableMapEntry[length]; + } + private final transient ImmutableMapEntry[] keyTable; + private final transient ImmutableMapEntry[] valueTable; + private final transient ImmutableMapEntry[] entries; + private final transient int mask; + private final transient int hashCode; - RegularImmutableBiMap(TerminalEntry... entriesToAdd) { - this(entriesToAdd.length, entriesToAdd); + private transient ImmutableBiMap inverse; + + /** + * Constructor for RegularImmutableBiMap that makes no assumptions about the + * input entries. + */ + RegularImmutableBiMap(Entry[] entriesToAdd) { + int n = entriesToAdd.length; + int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR); + this.mask = tableSize - 1; + ImmutableMapEntry[] keyTable = createEntryArray(tableSize); + ImmutableMapEntry[] valueTable = createEntryArray(tableSize); + ImmutableMapEntry[] entries = createEntryArray(n); + int hashCode = 0; + + for (int i = 0; i < n; i++) { + @SuppressWarnings("unchecked") + Entry entry = (Entry) entriesToAdd[i]; + K key = entry.getKey(); + V value = entry.getValue(); + checkEntryNotNull(key, value); + int keyHash = key.hashCode(); + int valueHash = value.hashCode(); + int keyBucket = Hashing.smear(keyHash) & mask; + int valueBucket = Hashing.smear(valueHash) & mask; + + ImmutableMapEntry nextInKeyBucket = keyTable[keyBucket]; + for (ImmutableMapEntry keyEntry = nextInKeyBucket; keyEntry != null; keyEntry = keyEntry + .getNextInKeyBucket()) { + checkNoConflict(!key.equals(keyEntry.getKey()), "key", entry, keyEntry); + } + ImmutableMapEntry nextInValueBucket = valueTable[valueBucket]; + for (ImmutableMapEntry valueEntry = nextInValueBucket; valueEntry != null; valueEntry = valueEntry + .getNextInValueBucket()) { + checkNoConflict(!value.equals(valueEntry.getValue()), "value", entry, valueEntry); + } + ImmutableMapEntry newEntry = (nextInKeyBucket == null && nextInValueBucket == null) + ? new TerminalEntry(key, value) + : new NonTerminalBiMapEntry(key, value, nextInKeyBucket, nextInValueBucket); + keyTable[keyBucket] = newEntry; + valueTable[valueBucket] = newEntry; + entries[i] = newEntry; + hashCode += keyHash ^ valueHash; + } + + this.keyTable = keyTable; + this.valueTable = valueTable; + this.entries = entries; + this.hashCode = hashCode; } /** @@ -98,91 +282,38 @@ class RegularImmutableBiMap extends ImmutableBiMap { this.hashCode = hashCode; } - /** - * Constructor for RegularImmutableBiMap that makes no assumptions about the - * input entries. - */ - RegularImmutableBiMap(Entry[] entriesToAdd) { - int n = entriesToAdd.length; - int tableSize = Hashing.closedTableSize(n, MAX_LOAD_FACTOR); - this.mask = tableSize - 1; - ImmutableMapEntry[] keyTable = createEntryArray(tableSize); - ImmutableMapEntry[] valueTable = createEntryArray(tableSize); - ImmutableMapEntry[] entries = createEntryArray(n); - int hashCode = 0; - - for (int i = 0; i < n; i++) { - @SuppressWarnings("unchecked") - Entry entry = (Entry) entriesToAdd[i]; - K key = entry.getKey(); - V value = entry.getValue(); - checkEntryNotNull(key, value); - int keyHash = key.hashCode(); - int valueHash = value.hashCode(); - int keyBucket = Hashing.smear(keyHash) & mask; - int valueBucket = Hashing.smear(valueHash) & mask; - - ImmutableMapEntry nextInKeyBucket = keyTable[keyBucket]; - for (ImmutableMapEntry keyEntry = nextInKeyBucket; keyEntry != null; keyEntry = keyEntry - .getNextInKeyBucket()) { - checkNoConflict(!key.equals(keyEntry.getKey()), "key", entry, keyEntry); - } - ImmutableMapEntry nextInValueBucket = valueTable[valueBucket]; - for (ImmutableMapEntry valueEntry = nextInValueBucket; valueEntry != null; valueEntry = valueEntry - .getNextInValueBucket()) { - checkNoConflict(!value.equals(valueEntry.getValue()), "value", entry, valueEntry); - } - ImmutableMapEntry newEntry = (nextInKeyBucket == null && nextInValueBucket == null) - ? new TerminalEntry(key, value) - : new NonTerminalBiMapEntry(key, value, nextInKeyBucket, nextInValueBucket); - keyTable[keyBucket] = newEntry; - valueTable[valueBucket] = newEntry; - entries[i] = newEntry; - hashCode += keyHash ^ valueHash; - } - - this.keyTable = keyTable; - this.valueTable = valueTable; - this.entries = entries; - this.hashCode = hashCode; + RegularImmutableBiMap(TerminalEntry... entriesToAdd) { + this(entriesToAdd.length, entriesToAdd); } - private static final class NonTerminalBiMapEntry extends ImmutableMapEntry { - @Nullable - private final ImmutableMapEntry nextInKeyBucket; - @Nullable - private final ImmutableMapEntry nextInValueBucket; + @Override + ImmutableSet> createEntrySet() { + return new ImmutableMapEntrySet() { + @Override + ImmutableList> createAsList() { + return new RegularImmutableAsList>(this, entries); + } - NonTerminalBiMapEntry(K key, V value, @Nullable ImmutableMapEntry nextInKeyBucket, - @Nullable ImmutableMapEntry nextInValueBucket) { - super(key, value); - this.nextInKeyBucket = nextInKeyBucket; - this.nextInValueBucket = nextInValueBucket; - } + @Override + public int hashCode() { + return hashCode; + } - NonTerminalBiMapEntry(ImmutableMapEntry contents, @Nullable ImmutableMapEntry nextInKeyBucket, - @Nullable ImmutableMapEntry nextInValueBucket) { - super(contents); - this.nextInKeyBucket = nextInKeyBucket; - this.nextInValueBucket = nextInValueBucket; - } + @Override + boolean isHashCodeFast() { + return true; + } - @Override - @Nullable - ImmutableMapEntry getNextInKeyBucket() { - return nextInKeyBucket; - } + @Override + public UnmodifiableIterator> iterator() { + return asList().iterator(); + } - @Override - @Nullable - ImmutableMapEntry getNextInValueBucket() { - return nextInValueBucket; - } - } - - @SuppressWarnings("unchecked") - private static ImmutableMapEntry[] createEntryArray(int length) { - return new ImmutableMapEntry[length]; + @Override + ImmutableMap map() { + return RegularImmutableBiMap.this; + } + }; } @Override @@ -201,33 +332,9 @@ class RegularImmutableBiMap extends ImmutableBiMap { } @Override - ImmutableSet> createEntrySet() { - return new ImmutableMapEntrySet() { - @Override - ImmutableMap map() { - return RegularImmutableBiMap.this; - } - - @Override - public UnmodifiableIterator> iterator() { - return asList().iterator(); - } - - @Override - ImmutableList> createAsList() { - return new RegularImmutableAsList>(this, entries); - } - - @Override - boolean isHashCodeFast() { - return true; - } - - @Override - public int hashCode() { - return hashCode; - } - }; + public ImmutableBiMap inverse() { + ImmutableBiMap result = inverse; + return (result == null) ? inverse = new Inverse() : result; } @Override @@ -239,107 +346,4 @@ class RegularImmutableBiMap extends ImmutableBiMap { public int size() { return entries.length; } - - private transient ImmutableBiMap inverse; - - @Override - public ImmutableBiMap inverse() { - ImmutableBiMap result = inverse; - return (result == null) ? inverse = new Inverse() : result; - } - - private final class Inverse extends ImmutableBiMap { - - @Override - public int size() { - return inverse().size(); - } - - @Override - public ImmutableBiMap inverse() { - return RegularImmutableBiMap.this; - } - - @Override - public K get(@Nullable Object value) { - if (value == null) { - return null; - } - int bucket = Hashing.smear(value.hashCode()) & mask; - for (ImmutableMapEntry entry = valueTable[bucket]; entry != null; entry = entry - .getNextInValueBucket()) { - if (value.equals(entry.getValue())) { - return entry.getKey(); - } - } - return null; - } - - @Override - ImmutableSet> createEntrySet() { - return new InverseEntrySet(); - } - - final class InverseEntrySet extends ImmutableMapEntrySet { - @Override - ImmutableMap map() { - return Inverse.this; - } - - @Override - boolean isHashCodeFast() { - return true; - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public UnmodifiableIterator> iterator() { - return asList().iterator(); - } - - @Override - ImmutableList> createAsList() { - return new ImmutableAsList>() { - @Override - public Entry get(int index) { - Entry entry = entries[index]; - return Maps.immutableEntry(entry.getValue(), entry.getKey()); - } - - @Override - ImmutableCollection> delegateCollection() { - return InverseEntrySet.this; - } - }; - } - } - - @Override - boolean isPartialView() { - return false; - } - - @Override - Object writeReplace() { - return new InverseSerializedForm(RegularImmutableBiMap.this); - } - } - - private static class InverseSerializedForm implements Serializable { - private final ImmutableBiMap forward; - - InverseSerializedForm(ImmutableBiMap forward) { - this.forward = forward; - } - - Object readResolve() { - return forward.inverse(); - } - - private static final long serialVersionUID = 1; - } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableList.java b/src/main/java/com/google/common/collect/RegularImmutableList.java index dba33788..079bb7e3 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableList.java +++ b/src/main/java/com/google/common/collect/RegularImmutableList.java @@ -33,24 +33,14 @@ class RegularImmutableList extends ImmutableList { private final transient int size; private final transient Object[] array; - RegularImmutableList(Object[] array, int offset, int size) { - this.offset = offset; - this.size = size; - this.array = array; - } - RegularImmutableList(Object[] array) { this(array, 0, array.length); } - @Override - public int size() { - return size; - } - - @Override - boolean isPartialView() { - return size != array.length; + RegularImmutableList(Object[] array, int offset, int size) { + this.offset = offset; + this.size = size; + this.array = array; } @Override @@ -80,6 +70,11 @@ class RegularImmutableList extends ImmutableList { return -1; } + @Override + boolean isPartialView() { + return size != array.length; + } + @Override public int lastIndexOf(@Nullable Object object) { if (object == null) { @@ -93,11 +88,6 @@ class RegularImmutableList extends ImmutableList { return -1; } - @Override - ImmutableList subListUnchecked(int fromIndex, int toIndex) { - return new RegularImmutableList(array, offset + fromIndex, toIndex - fromIndex); - } - @SuppressWarnings("unchecked") @Override public UnmodifiableListIterator listIterator(int index) { @@ -106,6 +96,16 @@ class RegularImmutableList extends ImmutableList { return (UnmodifiableListIterator) Iterators.forArray(array, offset, size, index); } + @Override + public int size() { + return size; + } + + @Override + ImmutableList subListUnchecked(int fromIndex, int toIndex) { + return new RegularImmutableList(array, offset + fromIndex, toIndex - fromIndex); + } + // TODO(user): benchmark optimizations for equals() and see if they're // worthwhile } diff --git a/src/main/java/com/google/common/collect/RegularImmutableMap.java b/src/main/java/com/google/common/collect/RegularImmutableMap.java index 5fae2279..306ecd07 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableMap.java +++ b/src/main/java/com/google/common/collect/RegularImmutableMap.java @@ -33,15 +33,96 @@ import com.google.common.collect.ImmutableMapEntry.TerminalEntry; @GwtCompatible(serializable = true, emulated = true) final class RegularImmutableMap extends ImmutableMap { + @SuppressWarnings("serial") // uses writeReplace(), not default serialization + private class EntrySet extends ImmutableMapEntrySet { + @Override + ImmutableList> createAsList() { + return new RegularImmutableAsList>(this, entries); + } + + @Override + public UnmodifiableIterator> iterator() { + return asList().iterator(); + } + + @Override + ImmutableMap map() { + return RegularImmutableMap.this; + } + } + + private static final class NonTerminalMapEntry extends ImmutableMapEntry { + private final ImmutableMapEntry nextInKeyBucket; + + NonTerminalMapEntry(ImmutableMapEntry contents, ImmutableMapEntry nextInKeyBucket) { + super(contents); + this.nextInKeyBucket = nextInKeyBucket; + } + + NonTerminalMapEntry(K key, V value, ImmutableMapEntry nextInKeyBucket) { + super(key, value); + this.nextInKeyBucket = nextInKeyBucket; + } + + @Override + ImmutableMapEntry getNextInKeyBucket() { + return nextInKeyBucket; + } + + @Override + @Nullable + ImmutableMapEntry getNextInValueBucket() { + return null; + } + + } + + /** + * Closed addressing tends to perform well even with high load factors. Being + * conservative here ensures that the table is still likely to be relatively + * sparse (hence it misses fast) while saving space. + */ + private static final double MAX_LOAD_FACTOR = 1.2; + + // This class is never actually serialized directly, but we have to make the + // warning go away (and suppressing would suppress for all nested classes too) + private static final long serialVersionUID = 0; + // entries in insertion order private final transient ImmutableMapEntry[] entries; + // array of linked lists of entries private final transient ImmutableMapEntry[] table; + // 'and' with an int to get a table index private final transient int mask; - RegularImmutableMap(TerminalEntry... theEntries) { - this(theEntries.length, theEntries); + /** + * Constructor for RegularImmutableMap that makes no assumptions about the input + * entries. + */ + RegularImmutableMap(Entry[] theEntries) { + int size = theEntries.length; + entries = createEntryArray(size); + int tableSize = Hashing.closedTableSize(size, MAX_LOAD_FACTOR); + table = createEntryArray(tableSize); + mask = tableSize - 1; + for (int entryIndex = 0; entryIndex < size; entryIndex++) { + @SuppressWarnings("unchecked") // all our callers carefully put in only Entrys + Entry entry = (Entry) theEntries[entryIndex]; + K key = entry.getKey(); + V value = entry.getValue(); + checkEntryNotNull(key, value); + int tableIndex = Hashing.smear(key.hashCode()) & mask; + @Nullable + ImmutableMapEntry existing = table[tableIndex]; + // prepend, not append, so the entries can be immutable + ImmutableMapEntry newEntry = (existing == null) ? new TerminalEntry(key, value) + : new NonTerminalMapEntry(key, value, existing); + table[tableIndex] = newEntry; + entries[entryIndex] = newEntry; + checkNoConflictInBucket(key, newEntry, existing); + } } /** @@ -74,32 +155,8 @@ final class RegularImmutableMap extends ImmutableMap { } } - /** - * Constructor for RegularImmutableMap that makes no assumptions about the input - * entries. - */ - RegularImmutableMap(Entry[] theEntries) { - int size = theEntries.length; - entries = createEntryArray(size); - int tableSize = Hashing.closedTableSize(size, MAX_LOAD_FACTOR); - table = createEntryArray(tableSize); - mask = tableSize - 1; - for (int entryIndex = 0; entryIndex < size; entryIndex++) { - @SuppressWarnings("unchecked") // all our callers carefully put in only Entrys - Entry entry = (Entry) theEntries[entryIndex]; - K key = entry.getKey(); - V value = entry.getValue(); - checkEntryNotNull(key, value); - int tableIndex = Hashing.smear(key.hashCode()) & mask; - @Nullable - ImmutableMapEntry existing = table[tableIndex]; - // prepend, not append, so the entries can be immutable - ImmutableMapEntry newEntry = (existing == null) ? new TerminalEntry(key, value) - : new NonTerminalMapEntry(key, value, existing); - table[tableIndex] = newEntry; - entries[entryIndex] = newEntry; - checkNoConflictInBucket(key, newEntry, existing); - } + RegularImmutableMap(TerminalEntry... theEntries) { + this(theEntries.length, theEntries); } private void checkNoConflictInBucket(K key, ImmutableMapEntry entry, ImmutableMapEntry bucketHead) { @@ -108,39 +165,6 @@ final class RegularImmutableMap extends ImmutableMap { } } - private static final class NonTerminalMapEntry extends ImmutableMapEntry { - private final ImmutableMapEntry nextInKeyBucket; - - NonTerminalMapEntry(K key, V value, ImmutableMapEntry nextInKeyBucket) { - super(key, value); - this.nextInKeyBucket = nextInKeyBucket; - } - - NonTerminalMapEntry(ImmutableMapEntry contents, ImmutableMapEntry nextInKeyBucket) { - super(contents); - this.nextInKeyBucket = nextInKeyBucket; - } - - @Override - ImmutableMapEntry getNextInKeyBucket() { - return nextInKeyBucket; - } - - @Override - @Nullable - ImmutableMapEntry getNextInValueBucket() { - return null; - } - - } - - /** - * Closed addressing tends to perform well even with high load factors. Being - * conservative here ensures that the table is still likely to be relatively - * sparse (hence it misses fast) while saving space. - */ - private static final double MAX_LOAD_FACTOR = 1.2; - /** * Creates an {@code ImmutableMapEntry} array to hold parameterized entries. The * result must never be upcast back to ImmutableMapEntry[] (or Object[], etc.), @@ -151,6 +175,11 @@ final class RegularImmutableMap extends ImmutableMap { return new ImmutableMapEntry[size]; } + @Override + ImmutableSet> createEntrySet() { + return new EntrySet(); + } + @Override public V get(@Nullable Object key) { if (key == null) { @@ -173,40 +202,13 @@ final class RegularImmutableMap extends ImmutableMap { return null; } - @Override - public int size() { - return entries.length; - } - @Override boolean isPartialView() { return false; } @Override - ImmutableSet> createEntrySet() { - return new EntrySet(); + public int size() { + return entries.length; } - - @SuppressWarnings("serial") // uses writeReplace(), not default serialization - private class EntrySet extends ImmutableMapEntrySet { - @Override - ImmutableMap map() { - return RegularImmutableMap.this; - } - - @Override - public UnmodifiableIterator> iterator() { - return asList().iterator(); - } - - @Override - ImmutableList> createAsList() { - return new RegularImmutableAsList>(this, entries); - } - } - - // This class is never actually serialized directly, but we have to make the - // warning go away (and suppressing would suppress for all nested classes too) - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/RegularImmutableMultiset.java b/src/main/java/com/google/common/collect/RegularImmutableMultiset.java index 833c16c0..d9f4b8c1 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableMultiset.java +++ b/src/main/java/com/google/common/collect/RegularImmutableMultiset.java @@ -41,8 +41,8 @@ class RegularImmutableMultiset extends ImmutableMultiset { } @Override - boolean isPartialView() { - return map.isPartialView(); + public boolean contains(@Nullable Object element) { + return map.containsKey(element); } @Override @@ -51,16 +51,6 @@ class RegularImmutableMultiset extends ImmutableMultiset { return (value == null) ? 0 : value; } - @Override - public int size() { - return size; - } - - @Override - public boolean contains(@Nullable Object element) { - return map.containsKey(element); - } - @Override public ImmutableSet elementSet() { return map.keySet(); @@ -76,4 +66,14 @@ class RegularImmutableMultiset extends ImmutableMultiset { public int hashCode() { return map.hashCode(); } + + @Override + boolean isPartialView() { + return map.isPartialView(); + } + + @Override + public int size() { + return size; + } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableSet.java b/src/main/java/com/google/common/collect/RegularImmutableSet.java index 7064295e..440914bf 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableSet.java +++ b/src/main/java/com/google/common/collect/RegularImmutableSet.java @@ -58,17 +58,6 @@ final class RegularImmutableSet extends ImmutableSet { } } - @Override - public int size() { - return elements.length; - } - - @SuppressWarnings("unchecked") // all elements are E's - @Override - public UnmodifiableIterator iterator() { - return (UnmodifiableIterator) Iterators.forArray(elements); - } - @Override int copyIntoArray(Object[] dst, int offset) { System.arraycopy(elements, 0, dst, offset, elements.length); @@ -80,11 +69,6 @@ final class RegularImmutableSet extends ImmutableSet { return new RegularImmutableAsList(this, elements); } - @Override - boolean isPartialView() { - return false; - } - @Override public int hashCode() { return hashCode; @@ -94,4 +78,20 @@ final class RegularImmutableSet extends ImmutableSet { boolean isHashCodeFast() { return true; } + + @Override + boolean isPartialView() { + return false; + } + + @SuppressWarnings("unchecked") // all elements are E's + @Override + public UnmodifiableIterator iterator() { + return (UnmodifiableIterator) Iterators.forArray(elements); + } + + @Override + public int size() { + return elements.length; + } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableSortedMap.java b/src/main/java/com/google/common/collect/RegularImmutableSortedMap.java index 44c0046d..b3b83723 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableSortedMap.java +++ b/src/main/java/com/google/common/collect/RegularImmutableSortedMap.java @@ -29,7 +29,38 @@ import com.google.common.annotations.GwtCompatible; @GwtCompatible(emulated = true) @SuppressWarnings("serial") // uses writeReplace, not default serialization final class RegularImmutableSortedMap extends ImmutableSortedMap { + private class EntrySet extends ImmutableMapEntrySet { + @Override + ImmutableList> createAsList() { + return new ImmutableAsList>() { + // avoid additional indirection + private final ImmutableList keyList = keySet().asList(); + + @Override + ImmutableCollection> delegateCollection() { + return EntrySet.this; + } + + @Override + public Entry get(int index) { + return Maps.immutableEntry(keyList.get(index), valueList.get(index)); + } + }; + } + + @Override + public UnmodifiableIterator> iterator() { + return asList().iterator(); + } + + @Override + ImmutableMap map() { + return RegularImmutableSortedMap.this; + } + } + private final transient RegularImmutableSortedSet keySet; + private final transient ImmutableList valueList; RegularImmutableSortedMap(RegularImmutableSortedSet keySet, ImmutableList valueList) { @@ -44,51 +75,17 @@ final class RegularImmutableSortedMap extends ImmutableSortedMap { this.valueList = valueList; } + @Override + ImmutableSortedMap createDescendingMap() { + return new RegularImmutableSortedMap((RegularImmutableSortedSet) keySet.descendingSet(), + valueList.reverse(), this); + } + @Override ImmutableSet> createEntrySet() { return new EntrySet(); } - private class EntrySet extends ImmutableMapEntrySet { - @Override - public UnmodifiableIterator> iterator() { - return asList().iterator(); - } - - @Override - ImmutableList> createAsList() { - return new ImmutableAsList>() { - // avoid additional indirection - private final ImmutableList keyList = keySet().asList(); - - @Override - public Entry get(int index) { - return Maps.immutableEntry(keyList.get(index), valueList.get(index)); - } - - @Override - ImmutableCollection> delegateCollection() { - return EntrySet.this; - } - }; - } - - @Override - ImmutableMap map() { - return RegularImmutableSortedMap.this; - } - } - - @Override - public ImmutableSortedSet keySet() { - return keySet; - } - - @Override - public ImmutableCollection values() { - return valueList; - } - @Override public V get(@Nullable Object key) { int index = keySet.indexOf(key); @@ -110,15 +107,19 @@ final class RegularImmutableSortedMap extends ImmutableSortedMap { return getSubMap(0, keySet.headIndex(checkNotNull(toKey), inclusive)); } + @Override + public ImmutableSortedSet keySet() { + return keySet; + } + @Override public ImmutableSortedMap tailMap(K fromKey, boolean inclusive) { return getSubMap(keySet.tailIndex(checkNotNull(fromKey), inclusive), size()); } @Override - ImmutableSortedMap createDescendingMap() { - return new RegularImmutableSortedMap((RegularImmutableSortedSet) keySet.descendingSet(), - valueList.reverse(), this); + public ImmutableCollection values() { + return valueList; } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableSortedMultiset.java b/src/main/java/com/google/common/collect/RegularImmutableSortedMultiset.java index b91ea87f..73a2ea07 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableSortedMultiset.java +++ b/src/main/java/com/google/common/collect/RegularImmutableSortedMultiset.java @@ -44,46 +44,25 @@ final class RegularImmutableSortedMultiset extends ImmutableSortedMultiset this.length = length; } - @Override - Entry getEntry(int index) { - return Multisets.immutableEntry(elementSet.asList().get(index), counts[offset + index]); - } - - @Override - public Entry firstEntry() { - return getEntry(0); - } - - @Override - public Entry lastEntry() { - return getEntry(length - 1); - } - @Override public int count(@Nullable Object element) { int index = elementSet.indexOf(element); return (index == -1) ? 0 : counts[index + offset]; } - @Override - public int size() { - long size = cumulativeCounts[offset + length] - cumulativeCounts[offset]; - return Ints.saturatedCast(size); - } - @Override public ImmutableSortedSet elementSet() { return elementSet; } @Override - public ImmutableSortedMultiset headMultiset(E upperBound, BoundType boundType) { - return getSubMultiset(0, elementSet.headIndex(upperBound, checkNotNull(boundType) == CLOSED)); + public Entry firstEntry() { + return getEntry(0); } @Override - public ImmutableSortedMultiset tailMultiset(E lowerBound, BoundType boundType) { - return getSubMultiset(elementSet.tailIndex(lowerBound, checkNotNull(boundType) == CLOSED), length); + Entry getEntry(int index) { + return Multisets.immutableEntry(elementSet.asList().get(index), counts[offset + index]); } ImmutableSortedMultiset getSubMultiset(int from, int to) { @@ -99,8 +78,29 @@ final class RegularImmutableSortedMultiset extends ImmutableSortedMultiset } } + @Override + public ImmutableSortedMultiset headMultiset(E upperBound, BoundType boundType) { + return getSubMultiset(0, elementSet.headIndex(upperBound, checkNotNull(boundType) == CLOSED)); + } + @Override boolean isPartialView() { return offset > 0 || length < counts.length; } + + @Override + public Entry lastEntry() { + return getEntry(length - 1); + } + + @Override + public int size() { + long size = cumulativeCounts[offset + length] - cumulativeCounts[offset]; + return Ints.saturatedCast(size); + } + + @Override + public ImmutableSortedMultiset tailMultiset(E lowerBound, BoundType boundType) { + return getSubMultiset(elementSet.tailIndex(lowerBound, checkNotNull(boundType) == CLOSED), length); + } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableSortedSet.java b/src/main/java/com/google/common/collect/RegularImmutableSortedSet.java index 2c1ce799..6caa5469 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableSortedSet.java +++ b/src/main/java/com/google/common/collect/RegularImmutableSortedSet.java @@ -56,24 +56,9 @@ final class RegularImmutableSortedSet extends ImmutableSortedSet { } @Override - public UnmodifiableIterator iterator() { - return elements.iterator(); - } - - @GwtIncompatible("NavigableSet") - @Override - public UnmodifiableIterator descendingIterator() { - return elements.reverse().iterator(); - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public int size() { - return elements.size(); + public E ceiling(E element) { + int index = tailIndex(element, true); + return (index == size()) ? null : elements.get(index); } @Override @@ -136,20 +121,27 @@ final class RegularImmutableSortedSet extends ImmutableSortedSet { return false; } - private int unsafeBinarySearch(Object key) throws ClassCastException { - return Collections.binarySearch(elements, key, unsafeComparator()); - } - - @Override - boolean isPartialView() { - return elements.isPartialView(); - } - @Override int copyIntoArray(Object[] dst, int offset) { return elements.copyIntoArray(dst, offset); } + @Override + ImmutableList createAsList() { + return new ImmutableSortedAsList(this, elements); + } + + @Override + ImmutableSortedSet createDescendingSet() { + return new RegularImmutableSortedSet(elements.reverse(), Ordering.from(comparator).reverse()); + } + + @GwtIncompatible("NavigableSet") + @Override + public UnmodifiableIterator descendingIterator() { + return elements.reverse().iterator(); + } + @Override public boolean equals(@Nullable Object object) { if (object == this) { @@ -190,68 +182,12 @@ final class RegularImmutableSortedSet extends ImmutableSortedSet { return elements.get(0); } - @Override - public E last() { - return elements.get(size() - 1); - } - - @Override - public E lower(E element) { - int index = headIndex(element, false) - 1; - return (index == -1) ? null : elements.get(index); - } - @Override public E floor(E element) { int index = headIndex(element, true) - 1; return (index == -1) ? null : elements.get(index); } - @Override - public E ceiling(E element) { - int index = tailIndex(element, true); - return (index == size()) ? null : elements.get(index); - } - - @Override - public E higher(E element) { - int index = tailIndex(element, false); - return (index == size()) ? null : elements.get(index); - } - - @Override - ImmutableSortedSet headSetImpl(E toElement, boolean inclusive) { - return getSubSet(0, headIndex(toElement, inclusive)); - } - - int headIndex(E toElement, boolean inclusive) { - return SortedLists.binarySearch(elements, checkNotNull(toElement), comparator(), - inclusive ? FIRST_AFTER : FIRST_PRESENT, NEXT_HIGHER); - } - - @Override - ImmutableSortedSet subSetImpl(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return tailSetImpl(fromElement, fromInclusive).headSetImpl(toElement, toInclusive); - } - - @Override - ImmutableSortedSet tailSetImpl(E fromElement, boolean inclusive) { - return getSubSet(tailIndex(fromElement, inclusive), size()); - } - - int tailIndex(E fromElement, boolean inclusive) { - return SortedLists.binarySearch(elements, checkNotNull(fromElement), comparator(), - inclusive ? FIRST_PRESENT : FIRST_AFTER, NEXT_HIGHER); - } - - // Pretend the comparator can compare anything. If it turns out it can't - // compare two elements, it'll throw a CCE. Only methods that are specified to - // throw CCE should call this. - @SuppressWarnings("unchecked") - Comparator unsafeComparator() { - return (Comparator) comparator; - } - ImmutableSortedSet getSubSet(int newFromIndex, int newToIndex) { if (newFromIndex == 0 && newToIndex == size()) { return this; @@ -262,6 +198,22 @@ final class RegularImmutableSortedSet extends ImmutableSortedSet { } } + int headIndex(E toElement, boolean inclusive) { + return SortedLists.binarySearch(elements, checkNotNull(toElement), comparator(), + inclusive ? FIRST_AFTER : FIRST_PRESENT, NEXT_HIGHER); + } + + @Override + ImmutableSortedSet headSetImpl(E toElement, boolean inclusive) { + return getSubSet(0, headIndex(toElement, inclusive)); + } + + @Override + public E higher(E element) { + int index = tailIndex(element, false); + return (index == size()) ? null : elements.get(index); + } + @Override int indexOf(@Nullable Object target) { if (target == null) { @@ -278,12 +230,60 @@ final class RegularImmutableSortedSet extends ImmutableSortedSet { } @Override - ImmutableList createAsList() { - return new ImmutableSortedAsList(this, elements); + public boolean isEmpty() { + return false; } @Override - ImmutableSortedSet createDescendingSet() { - return new RegularImmutableSortedSet(elements.reverse(), Ordering.from(comparator).reverse()); + boolean isPartialView() { + return elements.isPartialView(); + } + + @Override + public UnmodifiableIterator iterator() { + return elements.iterator(); + } + + @Override + public E last() { + return elements.get(size() - 1); + } + + @Override + public E lower(E element) { + int index = headIndex(element, false) - 1; + return (index == -1) ? null : elements.get(index); + } + + @Override + public int size() { + return elements.size(); + } + + @Override + ImmutableSortedSet subSetImpl(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return tailSetImpl(fromElement, fromInclusive).headSetImpl(toElement, toInclusive); + } + + int tailIndex(E fromElement, boolean inclusive) { + return SortedLists.binarySearch(elements, checkNotNull(fromElement), comparator(), + inclusive ? FIRST_PRESENT : FIRST_AFTER, NEXT_HIGHER); + } + + @Override + ImmutableSortedSet tailSetImpl(E fromElement, boolean inclusive) { + return getSubSet(tailIndex(fromElement, inclusive), size()); + } + + private int unsafeBinarySearch(Object key) throws ClassCastException { + return Collections.binarySearch(elements, key, unsafeComparator()); + } + + // Pretend the comparator can compare anything. If it turns out it can't + // compare two elements, it'll throw a CCE. Only methods that are specified to + // throw CCE should call this. + @SuppressWarnings("unchecked") + Comparator unsafeComparator() { + return (Comparator) comparator; } } diff --git a/src/main/java/com/google/common/collect/RegularImmutableTable.java b/src/main/java/com/google/common/collect/RegularImmutableTable.java index 5684a658..e603ced0 100644 --- a/src/main/java/com/google/common/collect/RegularImmutableTable.java +++ b/src/main/java/com/google/common/collect/RegularImmutableTable.java @@ -32,42 +32,7 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible abstract class RegularImmutableTable extends ImmutableTable { - RegularImmutableTable() { - } - - abstract Cell getCell(int iterationIndex); - - @Override - final ImmutableSet> createCellSet() { - return isEmpty() ? ImmutableSet.>of() : new CellSet(); - } - private final class CellSet extends ImmutableSet> { - @Override - public int size() { - return RegularImmutableTable.this.size(); - } - - @Override - public UnmodifiableIterator> iterator() { - return asList().iterator(); - } - - @Override - ImmutableList> createAsList() { - return new ImmutableAsList>() { - @Override - public Cell get(int index) { - return getCell(index); - } - - @Override - ImmutableCollection> delegateCollection() { - return CellSet.this; - } - }; - } - @Override public boolean contains(@Nullable Object object) { if (object instanceof Cell) { @@ -78,25 +43,38 @@ abstract class RegularImmutableTable extends ImmutableTable { return false; } + @Override + ImmutableList> createAsList() { + return new ImmutableAsList>() { + @Override + ImmutableCollection> delegateCollection() { + return CellSet.this; + } + + @Override + public Cell get(int index) { + return getCell(index); + } + }; + } + @Override boolean isPartialView() { return false; } - } - abstract V getValue(int iterationIndex); + @Override + public UnmodifiableIterator> iterator() { + return asList().iterator(); + } - @Override - final ImmutableCollection createValues() { - return isEmpty() ? ImmutableList.of() : new Values(); - } - - private final class Values extends ImmutableList { @Override public int size() { return RegularImmutableTable.this.size(); } + } + private final class Values extends ImmutableList { @Override public V get(int index) { return getValue(index); @@ -106,6 +84,15 @@ abstract class RegularImmutableTable extends ImmutableTable { boolean isPartialView() { return true; } + + @Override + public int size() { + return RegularImmutableTable.this.size(); + } + } + + static RegularImmutableTable forCells(Iterable> cells) { + return forCellsInternal(cells, null, null); } static RegularImmutableTable forCells(List> cells, @@ -138,10 +125,6 @@ abstract class RegularImmutableTable extends ImmutableTable { return forCellsInternal(cells, rowComparator, columnComparator); } - static RegularImmutableTable forCells(Iterable> cells) { - return forCellsInternal(cells, null, null); - } - /** * A factory that chooses the most space-efficient representation of the table. */ @@ -174,4 +157,21 @@ abstract class RegularImmutableTable extends ImmutableTable { ? new DenseImmutableTable(cellList, rowSpace, columnSpace) : new SparseImmutableTable(cellList, rowSpace, columnSpace); } + + RegularImmutableTable() { + } + + @Override + final ImmutableSet> createCellSet() { + return isEmpty() ? ImmutableSet.>of() : new CellSet(); + } + + @Override + final ImmutableCollection createValues() { + return isEmpty() ? ImmutableList.of() : new Values(); + } + + abstract Cell getCell(int iterationIndex); + + abstract V getValue(int iterationIndex); } diff --git a/src/main/java/com/google/common/collect/ReverseNaturalOrdering.java b/src/main/java/com/google/common/collect/ReverseNaturalOrdering.java index 8d39a112..52494fcd 100644 --- a/src/main/java/com/google/common/collect/ReverseNaturalOrdering.java +++ b/src/main/java/com/google/common/collect/ReverseNaturalOrdering.java @@ -29,6 +29,13 @@ import com.google.common.annotations.GwtCompatible; final class ReverseNaturalOrdering extends Ordering implements Serializable { static final ReverseNaturalOrdering INSTANCE = new ReverseNaturalOrdering(); + private static final long serialVersionUID = 0; + + private ReverseNaturalOrdering() { + } + + // Override the min/max methods to "hoist" delegation outside loops + @Override public int compare(Comparable left, Comparable right) { checkNotNull(left); // right null is caught later @@ -39,33 +46,6 @@ final class ReverseNaturalOrdering extends Ordering implements Seria return right.compareTo(left); } - @Override - public Ordering reverse() { - return Ordering.natural(); - } - - // Override the min/max methods to "hoist" delegation outside loops - - @Override - public E min(E a, E b) { - return NaturalOrdering.INSTANCE.max(a, b); - } - - @Override - public E min(E a, E b, E c, E... rest) { - return NaturalOrdering.INSTANCE.max(a, b, c, rest); - } - - @Override - public E min(Iterator iterator) { - return NaturalOrdering.INSTANCE.max(iterator); - } - - @Override - public E min(Iterable iterable) { - return NaturalOrdering.INSTANCE.max(iterable); - } - @Override public E max(E a, E b) { return NaturalOrdering.INSTANCE.min(a, b); @@ -76,14 +56,34 @@ final class ReverseNaturalOrdering extends Ordering implements Seria return NaturalOrdering.INSTANCE.min(a, b, c, rest); } + @Override + public E max(Iterable iterable) { + return NaturalOrdering.INSTANCE.min(iterable); + } + @Override public E max(Iterator iterator) { return NaturalOrdering.INSTANCE.min(iterator); } @Override - public E max(Iterable iterable) { - return NaturalOrdering.INSTANCE.min(iterable); + public E min(E a, E b) { + return NaturalOrdering.INSTANCE.max(a, b); + } + + @Override + public E min(E a, E b, E c, E... rest) { + return NaturalOrdering.INSTANCE.max(a, b, c, rest); + } + + @Override + public E min(Iterable iterable) { + return NaturalOrdering.INSTANCE.max(iterable); + } + + @Override + public E min(Iterator iterator) { + return NaturalOrdering.INSTANCE.max(iterator); } // preserving singleton-ness gives equals()/hashCode() for free @@ -91,13 +91,13 @@ final class ReverseNaturalOrdering extends Ordering implements Seria return INSTANCE; } + @Override + public Ordering reverse() { + return Ordering.natural(); + } + @Override public String toString() { return "Ordering.natural().reverse()"; } - - private ReverseNaturalOrdering() { - } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/ReverseOrdering.java b/src/main/java/com/google/common/collect/ReverseOrdering.java index 59373a71..2f6db215 100644 --- a/src/main/java/com/google/common/collect/ReverseOrdering.java +++ b/src/main/java/com/google/common/collect/ReverseOrdering.java @@ -28,6 +28,8 @@ import com.google.common.annotations.GwtCompatible; /** An ordering that uses the reverse of a given order. */ @GwtCompatible(serializable = true) final class ReverseOrdering extends Ordering implements Serializable { + private static final long serialVersionUID = 0; + final Ordering forwardOrder; ReverseOrdering(Ordering forwardOrder) { @@ -39,59 +41,8 @@ final class ReverseOrdering extends Ordering implements Serializable { return forwardOrder.compare(b, a); } - @SuppressWarnings("unchecked") // how to explain? - @Override - public Ordering reverse() { - return (Ordering) forwardOrder; - } - // Override the min/max methods to "hoist" delegation outside loops - @Override - public E min(E a, E b) { - return forwardOrder.max(a, b); - } - - @Override - public E min(E a, E b, E c, E... rest) { - return forwardOrder.max(a, b, c, rest); - } - - @Override - public E min(Iterator iterator) { - return forwardOrder.max(iterator); - } - - @Override - public E min(Iterable iterable) { - return forwardOrder.max(iterable); - } - - @Override - public E max(E a, E b) { - return forwardOrder.min(a, b); - } - - @Override - public E max(E a, E b, E c, E... rest) { - return forwardOrder.min(a, b, c, rest); - } - - @Override - public E max(Iterator iterator) { - return forwardOrder.min(iterator); - } - - @Override - public E max(Iterable iterable) { - return forwardOrder.min(iterable); - } - - @Override - public int hashCode() { - return -forwardOrder.hashCode(); - } - @Override public boolean equals(@Nullable Object object) { if (object == this) { @@ -104,10 +55,59 @@ final class ReverseOrdering extends Ordering implements Serializable { return false; } + @Override + public int hashCode() { + return -forwardOrder.hashCode(); + } + + @Override + public E max(E a, E b) { + return forwardOrder.min(a, b); + } + + @Override + public E max(E a, E b, E c, E... rest) { + return forwardOrder.min(a, b, c, rest); + } + + @Override + public E max(Iterable iterable) { + return forwardOrder.min(iterable); + } + + @Override + public E max(Iterator iterator) { + return forwardOrder.min(iterator); + } + + @Override + public E min(E a, E b) { + return forwardOrder.max(a, b); + } + + @Override + public E min(E a, E b, E c, E... rest) { + return forwardOrder.max(a, b, c, rest); + } + + @Override + public E min(Iterable iterable) { + return forwardOrder.max(iterable); + } + + @Override + public E min(Iterator iterator) { + return forwardOrder.max(iterator); + } + + @SuppressWarnings("unchecked") // how to explain? + @Override + public Ordering reverse() { + return (Ordering) forwardOrder; + } + @Override public String toString() { return forwardOrder + ".reverse()"; } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/Serialization.java b/src/main/java/com/google/common/collect/Serialization.java index e821f05c..ce84da8f 100644 --- a/src/main/java/com/google/common/collect/Serialization.java +++ b/src/main/java/com/google/common/collect/Serialization.java @@ -33,7 +33,120 @@ import java.util.Map; * @author Jared Levy */ final class Serialization { - private Serialization() { + // Secret sauce for setting final fields; don't make it public. + static final class FieldSetter { + private final Field field; + + private FieldSetter(Field field) { + this.field = field; + field.setAccessible(true); + } + + void set(T instance, int value) { + try { + field.set(instance, value); + } catch (IllegalAccessException impossible) { + throw new AssertionError(impossible); + } + } + + void set(T instance, Object value) { + try { + field.set(instance, value); + } catch (IllegalAccessException impossible) { + throw new AssertionError(impossible); + } + } + } + + // Secret sauce for setting final fields; don't make it public. + static FieldSetter getFieldSetter(final Class clazz, String fieldName) { + try { + Field field = clazz.getDeclaredField(fieldName); + return new FieldSetter(field); + } catch (NoSuchFieldException e) { + throw new AssertionError(e); // programmer error + } + } + + /** + * Populates a map by reading an input stream, as part of deserialization. See + * {@link #writeMap} for the data format. + */ + static void populateMap(Map map, ObjectInputStream stream) throws IOException, ClassNotFoundException { + int size = stream.readInt(); + populateMap(map, stream, size); + } + + /** + * Populates a map by reading an input stream, as part of deserialization. See + * {@link #writeMap} for the data format. The size is determined by a prior call + * to {@link #readCount}. + */ + static void populateMap(Map map, ObjectInputStream stream, int size) + throws IOException, ClassNotFoundException { + for (int i = 0; i < size; i++) { + @SuppressWarnings("unchecked") // reading data stored by writeMap + K key = (K) stream.readObject(); + @SuppressWarnings("unchecked") // reading data stored by writeMap + V value = (V) stream.readObject(); + map.put(key, value); + } + } + + /** + * Populates a multimap by reading an input stream, as part of deserialization. + * See {@link #writeMultimap} for the data format. + */ + static void populateMultimap(Multimap multimap, ObjectInputStream stream) + throws IOException, ClassNotFoundException { + int distinctKeys = stream.readInt(); + populateMultimap(multimap, stream, distinctKeys); + } + + /** + * Populates a multimap by reading an input stream, as part of deserialization. + * See {@link #writeMultimap} for the data format. The number of distinct keys + * is determined by a prior call to {@link #readCount}. + */ + static void populateMultimap(Multimap multimap, ObjectInputStream stream, int distinctKeys) + throws IOException, ClassNotFoundException { + for (int i = 0; i < distinctKeys; i++) { + @SuppressWarnings("unchecked") // reading data stored by writeMultimap + K key = (K) stream.readObject(); + Collection values = multimap.get(key); + int valueCount = stream.readInt(); + for (int j = 0; j < valueCount; j++) { + @SuppressWarnings("unchecked") // reading data stored by writeMultimap + V value = (V) stream.readObject(); + values.add(value); + } + } + } + + /** + * Populates a multiset by reading an input stream, as part of deserialization. + * See {@link #writeMultiset} for the data format. + */ + static void populateMultiset(Multiset multiset, ObjectInputStream stream) + throws IOException, ClassNotFoundException { + int distinctElements = stream.readInt(); + populateMultiset(multiset, stream, distinctElements); + } + + /** + * Populates a multiset by reading an input stream, as part of deserialization. + * See {@link #writeMultiset} for the data format. The number of distinct + * elements is determined by a prior call to {@link #readCount}. + */ + static void populateMultiset(Multiset multiset, ObjectInputStream stream, int distinctElements) + throws IOException, ClassNotFoundException { + for (int i = 0; i < distinctElements; i++) { + @SuppressWarnings("unchecked") // reading data stored by writeMultiset + E element = (E) stream.readObject(); + int count = stream.readInt(); + multiset.add(element, count); + } } /** @@ -70,74 +183,6 @@ final class Serialization { } } - /** - * Populates a map by reading an input stream, as part of deserialization. See - * {@link #writeMap} for the data format. - */ - static void populateMap(Map map, ObjectInputStream stream) throws IOException, ClassNotFoundException { - int size = stream.readInt(); - populateMap(map, stream, size); - } - - /** - * Populates a map by reading an input stream, as part of deserialization. See - * {@link #writeMap} for the data format. The size is determined by a prior call - * to {@link #readCount}. - */ - static void populateMap(Map map, ObjectInputStream stream, int size) - throws IOException, ClassNotFoundException { - for (int i = 0; i < size; i++) { - @SuppressWarnings("unchecked") // reading data stored by writeMap - K key = (K) stream.readObject(); - @SuppressWarnings("unchecked") // reading data stored by writeMap - V value = (V) stream.readObject(); - map.put(key, value); - } - } - - /** - * Stores the contents of a multiset in an output stream, as part of - * serialization. It does not support concurrent multisets whose content may - * change while the method is running. - * - *

- * The serialized output consists of the number of distinct elements, the first - * element, its count, the second element, its count, and so on. - */ - static void writeMultiset(Multiset multiset, ObjectOutputStream stream) throws IOException { - int entryCount = multiset.entrySet().size(); - stream.writeInt(entryCount); - for (Multiset.Entry entry : multiset.entrySet()) { - stream.writeObject(entry.getElement()); - stream.writeInt(entry.getCount()); - } - } - - /** - * Populates a multiset by reading an input stream, as part of deserialization. - * See {@link #writeMultiset} for the data format. - */ - static void populateMultiset(Multiset multiset, ObjectInputStream stream) - throws IOException, ClassNotFoundException { - int distinctElements = stream.readInt(); - populateMultiset(multiset, stream, distinctElements); - } - - /** - * Populates a multiset by reading an input stream, as part of deserialization. - * See {@link #writeMultiset} for the data format. The number of distinct - * elements is determined by a prior call to {@link #readCount}. - */ - static void populateMultiset(Multiset multiset, ObjectInputStream stream, int distinctElements) - throws IOException, ClassNotFoundException { - for (int i = 0; i < distinctElements; i++) { - @SuppressWarnings("unchecked") // reading data stored by writeMultiset - E element = (E) stream.readObject(); - int count = stream.readInt(); - multiset.add(element, count); - } - } - /** * Stores the contents of a multimap in an output stream, as part of * serialization. It does not support concurrent multimaps whose content may @@ -161,68 +206,23 @@ final class Serialization { } /** - * Populates a multimap by reading an input stream, as part of deserialization. - * See {@link #writeMultimap} for the data format. + * Stores the contents of a multiset in an output stream, as part of + * serialization. It does not support concurrent multisets whose content may + * change while the method is running. + * + *

+ * The serialized output consists of the number of distinct elements, the first + * element, its count, the second element, its count, and so on. */ - static void populateMultimap(Multimap multimap, ObjectInputStream stream) - throws IOException, ClassNotFoundException { - int distinctKeys = stream.readInt(); - populateMultimap(multimap, stream, distinctKeys); - } - - /** - * Populates a multimap by reading an input stream, as part of deserialization. - * See {@link #writeMultimap} for the data format. The number of distinct keys - * is determined by a prior call to {@link #readCount}. - */ - static void populateMultimap(Multimap multimap, ObjectInputStream stream, int distinctKeys) - throws IOException, ClassNotFoundException { - for (int i = 0; i < distinctKeys; i++) { - @SuppressWarnings("unchecked") // reading data stored by writeMultimap - K key = (K) stream.readObject(); - Collection values = multimap.get(key); - int valueCount = stream.readInt(); - for (int j = 0; j < valueCount; j++) { - @SuppressWarnings("unchecked") // reading data stored by writeMultimap - V value = (V) stream.readObject(); - values.add(value); - } + static void writeMultiset(Multiset multiset, ObjectOutputStream stream) throws IOException { + int entryCount = multiset.entrySet().size(); + stream.writeInt(entryCount); + for (Multiset.Entry entry : multiset.entrySet()) { + stream.writeObject(entry.getElement()); + stream.writeInt(entry.getCount()); } } - // Secret sauce for setting final fields; don't make it public. - static FieldSetter getFieldSetter(final Class clazz, String fieldName) { - try { - Field field = clazz.getDeclaredField(fieldName); - return new FieldSetter(field); - } catch (NoSuchFieldException e) { - throw new AssertionError(e); // programmer error - } - } - - // Secret sauce for setting final fields; don't make it public. - static final class FieldSetter { - private final Field field; - - private FieldSetter(Field field) { - this.field = field; - field.setAccessible(true); - } - - void set(T instance, Object value) { - try { - field.set(instance, value); - } catch (IllegalAccessException impossible) { - throw new AssertionError(impossible); - } - } - - void set(T instance, int value) { - try { - field.set(instance, value); - } catch (IllegalAccessException impossible) { - throw new AssertionError(impossible); - } - } + private Serialization() { } } diff --git a/src/main/java/com/google/common/collect/SetMultimap.java b/src/main/java/com/google/common/collect/SetMultimap.java index e7e7c735..0c016fcc 100644 --- a/src/main/java/com/google/common/collect/SetMultimap.java +++ b/src/main/java/com/google/common/collect/SetMultimap.java @@ -57,6 +57,42 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public interface SetMultimap extends Multimap { + /** + * {@inheritDoc} + * + *

+ * Note: The returned map's values are guaranteed to be of type + * {@link Set}. To obtain this map with the more specific generic type + * {@code Map>}, call {@link Multimaps#asMap(SetMultimap)} instead. + */ + @Override + Map> asMap(); + + /** + * {@inheritDoc} + * + *

+ * Because a {@code SetMultimap} has unique values for a given key, this method + * returns a {@link Set}, instead of the {@link java.util.Collection} specified + * in the {@link Multimap} interface. + */ + @Override + Set> entries(); + + /** + * Compares the specified object to this multimap for equality. + * + *

+ * Two {@code SetMultimap} instances are equal if, for each key, they contain + * the same values. Equality does not depend on the ordering of keys or values. + * + *

+ * An empty {@code SetMultimap} is equal to any other empty {@code + * Multimap}, including an empty {@code ListMultimap}. + */ + @Override + boolean equals(@Nullable Object obj); + /** * {@inheritDoc} * @@ -92,40 +128,4 @@ public interface SetMultimap extends Multimap { */ @Override Set replaceValues(K key, Iterable values); - - /** - * {@inheritDoc} - * - *

- * Because a {@code SetMultimap} has unique values for a given key, this method - * returns a {@link Set}, instead of the {@link java.util.Collection} specified - * in the {@link Multimap} interface. - */ - @Override - Set> entries(); - - /** - * {@inheritDoc} - * - *

- * Note: The returned map's values are guaranteed to be of type - * {@link Set}. To obtain this map with the more specific generic type - * {@code Map>}, call {@link Multimaps#asMap(SetMultimap)} instead. - */ - @Override - Map> asMap(); - - /** - * Compares the specified object to this multimap for equality. - * - *

- * Two {@code SetMultimap} instances are equal if, for each key, they contain - * the same values. Equality does not depend on the ordering of keys or values. - * - *

- * An empty {@code SetMultimap} is equal to any other empty {@code - * Multimap}, including an empty {@code ListMultimap}. - */ - @Override - boolean equals(@Nullable Object obj); } diff --git a/src/main/java/com/google/common/collect/Sets.java b/src/main/java/com/google/common/collect/Sets.java index 094fbff0..9d99490b 100644 --- a/src/main/java/com/google/common/collect/Sets.java +++ b/src/main/java/com/google/common/collect/Sets.java @@ -61,682 +61,287 @@ import com.google.common.collect.Collections2.FilteredCollection; */ @GwtCompatible(emulated = true) public final class Sets { - private Sets() { - } + private static final class CartesianSet extends ForwardingCollection> implements Set> { + static Set> create(List> sets) { + ImmutableList.Builder> axesBuilder = new ImmutableList.Builder>( + sets.size()); + for (Set set : sets) { + ImmutableSet copy = ImmutableSet.copyOf(set); + if (copy.isEmpty()) { + return ImmutableSet.of(); + } + axesBuilder.add(copy); + } + final ImmutableList> axes = axesBuilder.build(); + ImmutableList> listAxes = new ImmutableList>() { - /** - * {@link AbstractSet} substitute without the potentially-quadratic - * {@code removeAll} implementation. - */ - abstract static class ImprovedAbstractSet extends AbstractSet { - @Override - public boolean removeAll(Collection c) { - return removeAllImpl(this, c); + @Override + public List get(int index) { + return axes.get(index).asList(); + } + + @Override + boolean isPartialView() { + return true; + } + + @Override + public int size() { + return axes.size(); + } + }; + return new CartesianSet(axes, new CartesianList(listAxes)); + } + + private transient final ImmutableList> axes; + + private transient final CartesianList delegate; + + private CartesianSet(ImmutableList> axes, CartesianList delegate) { + this.axes = axes; + this.delegate = delegate; } @Override - public boolean retainAll(Collection c) { - return super.retainAll(checkNotNull(c)); // GWT compatibility + protected Collection> delegate() { + return delegate; + } + + @Override + public boolean equals(@Nullable Object object) { + // Warning: this is broken if size() == 0, so it is critical that we + // substitute an empty ImmutableSet to the user in place of this + if (object instanceof CartesianSet) { + CartesianSet that = (CartesianSet) object; + return this.axes.equals(that.axes); + } + return super.equals(object); + } + + @Override + public int hashCode() { + // Warning: this is broken if size() == 0, so it is critical that we + // substitute an empty ImmutableSet to the user in place of this + + // It's a weird formula, but tests prove it works. + int adjust = size() - 1; + for (int i = 0; i < axes.size(); i++) { + adjust *= 31; + adjust = ~~adjust; + // in GWT, we have to deal with integer overflow carefully + } + int hash = 1; + for (Set axis : axes) { + hash = 31 * hash + (size() / axis.size() * axis.hashCode()); + + hash = ~~hash; + } + hash += adjust; + return ~~hash; } } - /** - * Returns an immutable set instance containing the given enum elements. - * Internally, the returned set will be backed by an {@link EnumSet}. - * - *

- * The iteration order of the returned set follows the enum's iteration order, - * not the order in which the elements are provided to the method. - * - * @param anElement one of the elements the set should contain - * @param otherElements the rest of the elements the set should contain - * @return an immutable set containing those elements, minus duplicates - */ - // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 - @GwtCompatible(serializable = true) - public static > ImmutableSet immutableEnumSet(E anElement, E... otherElements) { - return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements)); - } + @GwtIncompatible("NavigableSet") + static class DescendingSet extends ForwardingNavigableSet { + // If we inline this, we get a javac error. + private static Ordering reverse(Comparator forward) { + return Ordering.from(forward).reverse(); + } - /** - * Returns an immutable set instance containing the given enum elements. - * Internally, the returned set will be backed by an {@link EnumSet}. - * - *

- * The iteration order of the returned set follows the enum's iteration order, - * not the order in which the elements appear in the given collection. - * - * @param elements the elements, all of the same {@code enum} type, that the set - * should contain - * @return an immutable set containing those elements, minus duplicates - */ - // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 - @GwtCompatible(serializable = true) - public static > ImmutableSet immutableEnumSet(Iterable elements) { - if (elements instanceof ImmutableEnumSet) { - return (ImmutableEnumSet) elements; - } else if (elements instanceof Collection) { - Collection collection = (Collection) elements; - if (collection.isEmpty()) { - return ImmutableSet.of(); + private final NavigableSet forward; + + DescendingSet(NavigableSet forward) { + this.forward = forward; + } + + @Override + public E ceiling(E e) { + return forward.floor(e); + } + + @SuppressWarnings("unchecked") + @Override + public Comparator comparator() { + Comparator forwardComparator = forward.comparator(); + if (forwardComparator == null) { + return (Comparator) Ordering.natural().reverse(); } else { - return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection)); - } - } else { - Iterator itr = elements.iterator(); - if (itr.hasNext()) { - EnumSet enumSet = EnumSet.of(itr.next()); - Iterators.addAll(enumSet, itr); - return ImmutableEnumSet.asImmutable(enumSet); - } else { - return ImmutableSet.of(); + return reverse(forwardComparator); } } + + @Override + protected NavigableSet delegate() { + return forward; + } + + @Override + public Iterator descendingIterator() { + return forward.iterator(); + } + + @Override + public NavigableSet descendingSet() { + return forward; + } + + @Override + public E first() { + return forward.last(); + } + + @Override + public E floor(E e) { + return forward.ceiling(e); + } + + @Override + public SortedSet headSet(E toElement) { + return standardHeadSet(toElement); + } + + @Override + public NavigableSet headSet(E toElement, boolean inclusive) { + return forward.tailSet(toElement, inclusive).descendingSet(); + } + + @Override + public E higher(E e) { + return forward.lower(e); + } + + @Override + public Iterator iterator() { + return forward.descendingIterator(); + } + + @Override + public E last() { + return forward.first(); + } + + @Override + public E lower(E e) { + return forward.higher(e); + } + + @Override + public E pollFirst() { + return forward.pollLast(); + } + + @Override + public E pollLast() { + return forward.pollFirst(); + } + + @Override + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return standardSubSet(fromElement, toElement); + } + + @Override + public SortedSet tailSet(E fromElement) { + return standardTailSet(fromElement); + } + + @Override + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return forward.headSet(fromElement, inclusive).descendingSet(); + } + + @Override + public Object[] toArray() { + return standardToArray(); + } + + @Override + public T[] toArray(T[] array) { + return standardToArray(array); + } + + @Override + public String toString() { + return standardToString(); + } } - /** - * Returns a new {@code EnumSet} instance containing the given elements. Unlike - * {@link EnumSet#copyOf(Collection)}, this method does not produce an exception - * on an empty collection, and it may be called on any iterable, not just a - * {@code Collection}. - */ - public static > EnumSet newEnumSet(Iterable iterable, Class elementType) { - EnumSet set = EnumSet.noneOf(elementType); - Iterables.addAll(set, iterable); - return set; - } - - // HashSet - - /** - * Creates a mutable, empty {@code HashSet} instance. - * - *

- * Note: if mutability is not required, use {@link ImmutableSet#of()} - * instead. - * - *

- * Note: if {@code E} is an {@link Enum} type, use {@link EnumSet#noneOf} - * instead. - * - * @return a new, empty {@code HashSet} - */ - public static HashSet newHashSet() { - return new HashSet(); - } - - /** - * Creates a mutable {@code HashSet} instance containing the given - * elements in unspecified order. - * - *

- * Note: if mutability is not required and the elements are non-null, use - * an overload of {@link ImmutableSet#of()} (for varargs) or - * {@link ImmutableSet#copyOf(Object[])} (for an array) instead. - * - *

- * Note: if {@code E} is an {@link Enum} type, use - * {@link EnumSet#of(Enum, Enum[])} instead. - * - * @param elements the elements that the set should contain - * @return a new {@code HashSet} containing those elements (minus duplicates) - */ - public static HashSet newHashSet(E... elements) { - HashSet set = newHashSetWithExpectedSize(elements.length); - Collections.addAll(set, elements); - return set; - } - - /** - * Creates a {@code HashSet} instance, with a high enough "initial capacity" - * that it should hold {@code expectedSize} elements without growth. This - * behavior cannot be broadly guaranteed, but it is observed to be true for - * OpenJDK 1.6. It also can't be guaranteed that the method isn't inadvertently - * oversizing the returned set. - * - * @param expectedSize the number of elements you expect to add to the returned - * set - * @return a new, empty {@code HashSet} with enough capacity to hold {@code - * expectedSize} elements without resizing - * @throws IllegalArgumentException if {@code expectedSize} is negative - */ - public static HashSet newHashSetWithExpectedSize(int expectedSize) { - return new HashSet(Maps.capacity(expectedSize)); - } - - /** - * Creates a mutable {@code HashSet} instance containing the given - * elements in unspecified order. - * - *

- * Note: if mutability is not required and the elements are non-null, use - * {@link ImmutableSet#copyOf(Iterable)} instead. - * - *

- * Note: if {@code E} is an {@link Enum} type, use - * {@link #newEnumSet(Iterable, Class)} instead. - * - * @param elements the elements that the set should contain - * @return a new {@code HashSet} containing those elements (minus duplicates) - */ - public static HashSet newHashSet(Iterable elements) { - return (elements instanceof Collection) ? new HashSet(Collections2.cast(elements)) - : newHashSet(elements.iterator()); - } - - /** - * Creates a mutable {@code HashSet} instance containing the given - * elements in unspecified order. - * - *

- * Note: if mutability is not required and the elements are non-null, use - * {@link ImmutableSet#copyOf(Iterable)} instead. - * - *

- * Note: if {@code E} is an {@link Enum} type, you should create an - * {@link EnumSet} instead. - * - * @param elements the elements that the set should contain - * @return a new {@code HashSet} containing those elements (minus duplicates) - */ - public static HashSet newHashSet(Iterator elements) { - HashSet set = newHashSet(); - Iterators.addAll(set, elements); - return set; - } - - // LinkedHashSet - - /** - * Creates a mutable, empty {@code LinkedHashSet} instance. - * - *

- * Note: if mutability is not required, use {@link ImmutableSet#of()} - * instead. - * - * @return a new, empty {@code LinkedHashSet} - */ - public static LinkedHashSet newLinkedHashSet() { - return new LinkedHashSet(); - } - - /** - * Creates a {@code LinkedHashSet} instance, with a high enough "initial - * capacity" that it should hold {@code expectedSize} elements without - * growth. This behavior cannot be broadly guaranteed, but it is observed to be - * true for OpenJDK 1.6. It also can't be guaranteed that the method isn't - * inadvertently oversizing the returned set. - * - * @param expectedSize the number of elements you expect to add to the returned - * set - * @return a new, empty {@code LinkedHashSet} with enough capacity to hold - * {@code expectedSize} elements without resizing - * @throws IllegalArgumentException if {@code expectedSize} is negative - * @since 11.0 - */ - public static LinkedHashSet newLinkedHashSetWithExpectedSize(int expectedSize) { - return new LinkedHashSet(Maps.capacity(expectedSize)); - } - - /** - * Creates a mutable {@code LinkedHashSet} instance containing the given - * elements in order. - * - *

- * Note: if mutability is not required and the elements are non-null, use - * {@link ImmutableSet#copyOf(Iterable)} instead. - * - * @param elements the elements that the set should contain, in order - * @return a new {@code LinkedHashSet} containing those elements (minus - * duplicates) - */ - public static LinkedHashSet newLinkedHashSet(Iterable elements) { - if (elements instanceof Collection) { - return new LinkedHashSet(Collections2.cast(elements)); - } - LinkedHashSet set = newLinkedHashSet(); - Iterables.addAll(set, elements); - return set; - } - - // TreeSet - - /** - * Creates a mutable, empty {@code TreeSet} instance sorted by the - * natural sort ordering of its elements. - * - *

- * Note: if mutability is not required, use - * {@link ImmutableSortedSet#of()} instead. - * - * @return a new, empty {@code TreeSet} - */ - public static TreeSet newTreeSet() { - return new TreeSet(); - } - - /** - * Creates a mutable {@code TreeSet} instance containing the given - * elements sorted by their natural ordering. - * - *

- * Note: if mutability is not required, use - * {@link ImmutableSortedSet#copyOf(Iterable)} instead. - * - *

- * Note: If {@code elements} is a {@code SortedSet} with an explicit - * comparator, this method has different behavior than - * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with that - * comparator. - * - * @param elements the elements that the set should contain - * @return a new {@code TreeSet} containing those elements (minus duplicates) - */ - public static TreeSet newTreeSet(Iterable elements) { - TreeSet set = newTreeSet(); - Iterables.addAll(set, elements); - return set; - } - - /** - * Creates a mutable, empty {@code TreeSet} instance with the given - * comparator. - * - *

- * Note: if mutability is not required, use {@code - * ImmutableSortedSet.orderedBy(comparator).build()} instead. - * - * @param comparator the comparator to use to sort the set - * @return a new, empty {@code TreeSet} - * @throws NullPointerException if {@code comparator} is null - */ - public static TreeSet newTreeSet(Comparator comparator) { - return new TreeSet(checkNotNull(comparator)); - } - - /** - * Creates an empty {@code Set} that uses identity to determine equality. It - * compares object references, instead of calling {@code equals}, to determine - * whether a provided object matches an element in the set. For example, - * {@code contains} returns {@code false} when passed an object that equals a - * set member, but isn't the same instance. This behavior is similar to the way - * {@code IdentityHashMap} handles key lookups. - * - * @since 8.0 - */ - public static Set newIdentityHashSet() { - return Sets.newSetFromMap(Maps.newIdentityHashMap()); - } - - /** - * Creates an {@code EnumSet} consisting of all enum values that are not in the - * specified collection. If the collection is an {@link EnumSet}, this method - * has the same behavior as {@link EnumSet#complementOf}. Otherwise, the - * specified collection must contain at least one element, in order to determine - * the element type. If the collection could be empty, use - * {@link #complementOf(Collection, Class)} instead of this method. - * - * @param collection the collection whose complement should be stored in the - * enum set - * @return a new, modifiable {@code EnumSet} containing all values of the enum - * that aren't present in the given collection - * @throws IllegalArgumentException if {@code collection} is not an - * {@code EnumSet} instance and contains no - * elements - */ - public static > EnumSet complementOf(Collection collection) { - if (collection instanceof EnumSet) { - return EnumSet.complementOf((EnumSet) collection); - } - checkArgument(!collection.isEmpty(), "collection is empty; use the other version of this method"); - Class type = collection.iterator().next().getDeclaringClass(); - return makeComplementByHand(collection, type); - } - - /** - * Creates an {@code EnumSet} consisting of all enum values that are not in the - * specified collection. This is equivalent to {@link EnumSet#complementOf}, but - * can act on any input collection, as long as the elements are of enum type. - * - * @param collection the collection whose complement should be stored in the - * {@code EnumSet} - * @param type the type of the elements in the set - * @return a new, modifiable {@code EnumSet} initially containing all the values - * of the enum not present in the given collection - */ - public static > EnumSet complementOf(Collection collection, Class type) { - checkNotNull(collection); - return (collection instanceof EnumSet) ? EnumSet.complementOf((EnumSet) collection) - : makeComplementByHand(collection, type); - } - - private static > EnumSet makeComplementByHand(Collection collection, Class type) { - EnumSet result = EnumSet.allOf(type); - result.removeAll(collection); - return result; - } - - /** - * Returns a set backed by the specified map. The resulting set displays the - * same ordering, concurrency, and performance characteristics as the backing - * map. In essence, this factory method provides a {@link Set} implementation - * corresponding to any {@link Map} implementation. There is no need to use this - * method on a {@link Map} implementation that already has a corresponding - * {@link Set} implementation (such as {@link java.util.HashMap} or - * {@link java.util.TreeMap}). - * - *

- * Each method invocation on the set returned by this method results in exactly - * one method invocation on the backing map or its {@code keySet} view, with one - * exception. The {@code addAll} method is implemented as a sequence of - * {@code put} invocations on the backing map. - * - *

- * The specified map must be empty at the time this method is invoked, and - * should not be accessed directly after this method returns. These conditions - * are ensured if the map is created empty, passed directly to this method, and - * no reference to the map is retained, as illustrated in the following code - * fragment: - * - *

-	 * {
-	 * 	@code
-	 *
-	 * 	Set identityHashSet = Sets.newSetFromMap(new IdentityHashMap());
-	 * }
-	 * 
-	 *
-	 * 

- * This method has the same behavior as the JDK 6 method - * {@code Collections.newSetFromMap()}. The returned set is serializable if the - * backing map is. - * - * @param map the backing map - * @return the set backed by the map - * @throws IllegalArgumentException if {@code map} is not empty - */ - public static Set newSetFromMap(Map map) { - return Platform.newSetFromMap(map); - } - - /** - * An unmodifiable view of a set which may be backed by other sets; this view - * will change as the backing sets do. Contains methods to copy the data into a - * new set which will then remain stable. There is usually no reason to retain a - * reference of type {@code SetView}; typically, you either use it as a plain - * {@link Set}, or immediately invoke {@link #immutableCopy} or - * {@link #copyInto} and forget the {@code SetView} itself. - * - * @since 2.0 (imported from Google Collections Library) - */ - public abstract static class SetView extends AbstractSet { - private SetView() { - } // no subclasses but our own - - /** - * Returns an immutable copy of the current contents of this set view. Does not - * support null elements. - * - *

- * Warning: this may have unexpected results if a backing set of this - * view uses a nonstandard notion of equivalence, for example if it is a - * {@link TreeSet} using a comparator that is inconsistent with - * {@link Object#equals(Object)}. - */ - public ImmutableSet immutableCopy() { - return ImmutableSet.copyOf(this); + @GwtIncompatible("NavigableSet") + private static class FilteredNavigableSet extends FilteredSortedSet implements NavigableSet { + FilteredNavigableSet(NavigableSet unfiltered, Predicate predicate) { + super(unfiltered, predicate); } - /** - * Copies the current contents of this set view into an existing set. This - * method has equivalent behavior to {@code set.addAll(this)}, assuming that all - * the sets involved are based on the same notion of equivalence. - * - * @return a reference to {@code set}, for convenience - */ - // Note: S should logically extend Set but can't due to either - // some javac bug or some weirdness in the spec, not sure which. - public > S copyInto(S set) { - set.addAll(this); - return set; - } - } - - /** - * Returns an unmodifiable view of the union of two sets. The returned - * set contains all elements that are contained in either backing set. Iterating - * over the returned set iterates first over all the elements of {@code set1}, - * then over each element of {@code set2}, in order, that is not contained in - * {@code set1}. - * - *

- * Results are undefined if {@code set1} and {@code set2} are sets based on - * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and the - * {@link Map#keySet} of an {@code IdentityHashMap} all are). - * - *

- * Note: The returned view performs better when {@code set1} is the - * smaller of the two sets. If you have reason to believe one of your sets will - * generally be smaller than the other, pass it first. - * - *

- * Further, note that the current implementation is not suitable for nested - * {@code union} views, i.e. the following should be avoided when in a loop: - * {@code union = Sets.union(union, anotherSet);}, since iterating over the - * resulting set has a cubic complexity to the depth of the nesting. - */ - public static SetView union(final Set set1, final Set set2) { - checkNotNull(set1, "set1"); - checkNotNull(set2, "set2"); - - final Set set2minus1 = difference(set2, set1); - - return new SetView() { - @Override - public int size() { - return set1.size() + set2minus1.size(); - } - - @Override - public boolean isEmpty() { - return set1.isEmpty() && set2.isEmpty(); - } - - @Override - public Iterator iterator() { - return Iterators.unmodifiableIterator(Iterators.concat(set1.iterator(), set2minus1.iterator())); - } - - @Override - public boolean contains(Object object) { - return set1.contains(object) || set2.contains(object); - } - - @Override - public > S copyInto(S set) { - set.addAll(set1); - set.addAll(set2); - return set; - } - - @Override - public ImmutableSet immutableCopy() { - return new ImmutableSet.Builder().addAll(set1).addAll(set2).build(); - } - }; - } - - /** - * Returns an unmodifiable view of the intersection of two sets. The - * returned set contains all elements that are contained by both backing sets. - * The iteration order of the returned set matches that of {@code set1}. - * - *

- * Results are undefined if {@code set1} and {@code set2} are sets based on - * different equivalence relations (as {@code HashSet}, {@code TreeSet}, and the - * keySet of an {@code IdentityHashMap} all are). - * - *

- * Note: The returned view performs slightly better when {@code - * set1} is the smaller of the two sets. If you have reason to believe one of - * your sets will generally be smaller than the other, pass it first. - * Unfortunately, since this method sets the generic type of the returned set - * based on the type of the first set passed, this could in rare cases force you - * to make a cast, for example: - * - *

-	 *    {@code
-	 *
-	 *   Set aFewBadObjects = ...
-	 *   Set manyBadStrings = ...
-	 *
-	 *   // impossible for a non-String to be in the intersection
-	 *   SuppressWarnings("unchecked")
-	 *   Set badStrings = (Set) Sets.intersection(
-	 *       aFewBadObjects, manyBadStrings);}
-	 * 
-	 *
-	 * 

- * This is unfortunate, but should come up only very rarely. - */ - public static SetView intersection(final Set set1, final Set set2) { - checkNotNull(set1, "set1"); - checkNotNull(set2, "set2"); - - final Predicate inSet2 = Predicates.in(set2); - return new SetView() { - @Override - public Iterator iterator() { - return Iterators.filter(set1.iterator(), inSet2); - } - - @Override - public int size() { - return Iterators.size(iterator()); - } - - @Override - public boolean isEmpty() { - return !iterator().hasNext(); - } - - @Override - public boolean contains(Object object) { - return set1.contains(object) && set2.contains(object); - } - - @Override - public boolean containsAll(Collection collection) { - return set1.containsAll(collection) && set2.containsAll(collection); - } - }; - } - - /** - * Returns an unmodifiable view of the difference of two sets. The - * returned set contains all elements that are contained by {@code set1} and not - * contained by {@code set2}. {@code set2} may also contain elements not present - * in {@code set1}; these are simply ignored. The iteration order of the - * returned set matches that of {@code set1}. - * - *

- * Results are undefined if {@code set1} and {@code set2} are sets based on - * different equivalence relations (as {@code HashSet}, {@code TreeSet}, and the - * keySet of an {@code IdentityHashMap} all are). - */ - public static SetView difference(final Set set1, final Set set2) { - checkNotNull(set1, "set1"); - checkNotNull(set2, "set2"); - - final Predicate notInSet2 = Predicates.not(Predicates.in(set2)); - return new SetView() { - @Override - public Iterator iterator() { - return Iterators.filter(set1.iterator(), notInSet2); - } - - @Override - public int size() { - return Iterators.size(iterator()); - } - - @Override - public boolean isEmpty() { - return set2.containsAll(set1); - } - - @Override - public boolean contains(Object element) { - return set1.contains(element) && !set2.contains(element); - } - }; - } - - /** - * Returns an unmodifiable view of the symmetric difference of two sets. - * The returned set contains all elements that are contained in either - * {@code set1} or {@code set2} but not in both. The iteration order of the - * returned set is undefined. - * - *

- * Results are undefined if {@code set1} and {@code set2} are sets based on - * different equivalence relations (as {@code HashSet}, {@code TreeSet}, and the - * keySet of an {@code IdentityHashMap} all are). - * - * @since 3.0 - */ - public static SetView symmetricDifference(Set set1, Set set2) { - checkNotNull(set1, "set1"); - checkNotNull(set2, "set2"); - - // TODO(kevinb): Replace this with a more efficient implementation - return difference(union(set1, set2), intersection(set1, set2)); - } - - /** - * Returns the elements of {@code unfiltered} that satisfy a predicate. The - * returned set is a live view of {@code unfiltered}; changes to one affect the - * other. - * - *

- * The resulting set's iterator does not support {@code remove()}, but all other - * set methods are supported. When given an element that doesn't satisfy the - * predicate, the set's {@code add()} and {@code addAll()} methods throw an - * {@link IllegalArgumentException}. When methods such as {@code - * removeAll()} and {@code clear()} are called on the filtered set, only - * elements that satisfy the filter will be removed from the underlying set. - * - *

- * The returned set isn't threadsafe or serializable, even if {@code unfiltered} - * is. - * - *

- * Many of the filtered set's methods, such as {@code size()}, iterate across - * every element in the underlying set and determine which elements satisfy the - * filter. When a live view is not needed, it may be faster to copy - * {@code Iterables.filter(unfiltered, predicate)} and use the copy. - * - *

- * Warning: {@code predicate} must be consistent with equals, as - * documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. (See {@link Iterables#filter(Iterable, Class)} for related - * functionality.) - */ - // TODO(kevinb): how to omit that last sentence when building GWT javadoc? - public static Set filter(Set unfiltered, Predicate predicate) { - if (unfiltered instanceof SortedSet) { - return filter((SortedSet) unfiltered, predicate); - } - if (unfiltered instanceof FilteredSet) { - // Support clear(), removeAll(), and retainAll() when filtering a filtered - // collection. - FilteredSet filtered = (FilteredSet) unfiltered; - Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); - return new FilteredSet((Set) filtered.unfiltered, combinedPredicate); + @Override + public E ceiling(E e) { + return Iterables.getFirst(tailSet(e, true), null); } - return new FilteredSet(checkNotNull(unfiltered), checkNotNull(predicate)); + @Override + public Iterator descendingIterator() { + return Iterators.filter(unfiltered().descendingIterator(), predicate); + } + + @Override + public NavigableSet descendingSet() { + return Sets.filter(unfiltered().descendingSet(), predicate); + } + + @Override + @Nullable + public E floor(E e) { + return Iterators.getNext(headSet(e, true).descendingIterator(), null); + } + + @Override + public NavigableSet headSet(E toElement, boolean inclusive) { + return filter(unfiltered().headSet(toElement, inclusive), predicate); + } + + @Override + public E higher(E e) { + return Iterables.getFirst(tailSet(e, false), null); + } + + @Override + public E last() { + return descendingIterator().next(); + } + + @Override + @Nullable + public E lower(E e) { + return Iterators.getNext(headSet(e, false).descendingIterator(), null); + } + + @Override + public E pollFirst() { + return Iterables.removeFirstMatching(unfiltered(), predicate); + } + + @Override + public E pollLast() { + return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate); + } + + @Override + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return filter(unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate); + } + + @Override + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return filter(unfiltered().tailSet(fromElement, inclusive), predicate); + } + + NavigableSet unfiltered() { + return (NavigableSet) unfiltered; + } } private static class FilteredSet extends FilteredCollection implements Set { @@ -755,54 +360,6 @@ public final class Sets { } } - /** - * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy - * a predicate. The returned set is a live view of {@code unfiltered}; changes - * to one affect the other. - * - *

- * The resulting set's iterator does not support {@code remove()}, but all other - * set methods are supported. When given an element that doesn't satisfy the - * predicate, the set's {@code add()} and {@code addAll()} methods throw an - * {@link IllegalArgumentException}. When methods such as {@code removeAll()} - * and {@code clear()} are called on the filtered set, only elements that - * satisfy the filter will be removed from the underlying set. - * - *

- * The returned set isn't threadsafe or serializable, even if {@code unfiltered} - * is. - * - *

- * Many of the filtered set's methods, such as {@code size()}, iterate across - * every element in the underlying set and determine which elements satisfy the - * filter. When a live view is not needed, it may be faster to copy - * {@code Iterables.filter(unfiltered, predicate)} and use the copy. - * - *

- * Warning: {@code predicate} must be consistent with equals, as - * documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. (See {@link Iterables#filter(Iterable, Class)} for related - * functionality.) - * - * @since 11.0 - */ - public static SortedSet filter(SortedSet unfiltered, Predicate predicate) { - return Platform.setsFilterSortedSet(unfiltered, predicate); - } - - static SortedSet filterSortedIgnoreNavigable(SortedSet unfiltered, Predicate predicate) { - if (unfiltered instanceof FilteredSet) { - // Support clear(), removeAll(), and retainAll() when filtering a filtered - // collection. - FilteredSet filtered = (FilteredSet) unfiltered; - Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); - return new FilteredSortedSet((SortedSet) filtered.unfiltered, combinedPredicate); - } - - return new FilteredSortedSet(checkNotNull(unfiltered), checkNotNull(predicate)); - } - private static class FilteredSortedSet extends FilteredSet implements SortedSet { FilteredSortedSet(SortedSet unfiltered, Predicate predicate) { @@ -815,8 +372,8 @@ public final class Sets { } @Override - public SortedSet subSet(E fromElement, E toElement) { - return new FilteredSortedSet(((SortedSet) unfiltered).subSet(fromElement, toElement), predicate); + public E first() { + return iterator().next(); } @Override @@ -824,16 +381,6 @@ public final class Sets { return new FilteredSortedSet(((SortedSet) unfiltered).headSet(toElement), predicate); } - @Override - public SortedSet tailSet(E fromElement) { - return new FilteredSortedSet(((SortedSet) unfiltered).tailSet(fromElement), predicate); - } - - @Override - public E first() { - return iterator().next(); - } - @Override public E last() { SortedSet sortedUnfiltered = (SortedSet) unfiltered; @@ -845,127 +392,271 @@ public final class Sets { sortedUnfiltered = sortedUnfiltered.headSet(element); } } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return new FilteredSortedSet(((SortedSet) unfiltered).subSet(fromElement, toElement), predicate); + } + + @Override + public SortedSet tailSet(E fromElement) { + return new FilteredSortedSet(((SortedSet) unfiltered).tailSet(fromElement), predicate); + } + } + + // HashSet + + /** + * {@link AbstractSet} substitute without the potentially-quadratic + * {@code removeAll} implementation. + */ + abstract static class ImprovedAbstractSet extends AbstractSet { + @Override + public boolean removeAll(Collection c) { + return removeAllImpl(this, c); + } + + @Override + public boolean retainAll(Collection c) { + return super.retainAll(checkNotNull(c)); // GWT compatibility + } + } + + private static final class PowerSet extends AbstractSet> { + final ImmutableMap inputSet; + + PowerSet(Set input) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + int i = 0; + for (E e : checkNotNull(input)) { + builder.put(e, i++); + } + this.inputSet = builder.build(); + checkArgument(inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size()); + } + + @Override + public boolean contains(@Nullable Object obj) { + if (obj instanceof Set) { + Set set = (Set) obj; + return inputSet.keySet().containsAll(set); + } + return false; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (obj instanceof PowerSet) { + PowerSet that = (PowerSet) obj; + return inputSet.equals(that.inputSet); + } + return super.equals(obj); + } + + @Override + public int hashCode() { + /* + * The sum of the sums of the hash codes in each subset is just the sum of each + * input element's hash code times the number of sets that element appears in. + * Each element appears in exactly half of the 2^n sets, so: + */ + return inputSet.keySet().hashCode() << (inputSet.size() - 1); + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public Iterator> iterator() { + return new AbstractIndexedListIterator>(size()) { + @Override + protected Set get(final int setBits) { + return new SubSet(inputSet, setBits); + } + }; + } + + @Override + public int size() { + return 1 << inputSet.size(); + } + + @Override + public String toString() { + return "powerSet(" + inputSet + ")"; + } } /** - * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that - * satisfy a predicate. The returned set is a live view of {@code unfiltered}; - * changes to one affect the other. + * An unmodifiable view of a set which may be backed by other sets; this view + * will change as the backing sets do. Contains methods to copy the data into a + * new set which will then remain stable. There is usually no reason to retain a + * reference of type {@code SetView}; typically, you either use it as a plain + * {@link Set}, or immediately invoke {@link #immutableCopy} or + * {@link #copyInto} and forget the {@code SetView} itself. * - *

- * The resulting set's iterator does not support {@code remove()}, but all other - * set methods are supported. When given an element that doesn't satisfy the - * predicate, the set's {@code add()} and {@code addAll()} methods throw an - * {@link IllegalArgumentException}. When methods such as {@code removeAll()} - * and {@code clear()} are called on the filtered set, only elements that - * satisfy the filter will be removed from the underlying set. - * - *

- * The returned set isn't threadsafe or serializable, even if {@code unfiltered} - * is. - * - *

- * Many of the filtered set's methods, such as {@code size()}, iterate across - * every element in the underlying set and determine which elements satisfy the - * filter. When a live view is not needed, it may be faster to copy - * {@code Iterables.filter(unfiltered, predicate)} and use the copy. - * - *

- * Warning: {@code predicate} must be consistent with equals, as - * documented at {@link Predicate#apply}. Do not provide a predicate such as - * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with - * equals. (See {@link Iterables#filter(Iterable, Class)} for related - * functionality.) - * - * @since 14.0 + * @since 2.0 (imported from Google Collections Library) */ - @GwtIncompatible("NavigableSet") - @SuppressWarnings("unchecked") - public static NavigableSet filter(NavigableSet unfiltered, Predicate predicate) { - if (unfiltered instanceof FilteredSet) { - // Support clear(), removeAll(), and retainAll() when filtering a filtered - // collection. - FilteredSet filtered = (FilteredSet) unfiltered; - Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); - return new FilteredNavigableSet((NavigableSet) filtered.unfiltered, combinedPredicate); + public abstract static class SetView extends AbstractSet { + private SetView() { + } // no subclasses but our own + + /** + * Copies the current contents of this set view into an existing set. This + * method has equivalent behavior to {@code set.addAll(this)}, assuming that all + * the sets involved are based on the same notion of equivalence. + * + * @return a reference to {@code set}, for convenience + */ + // Note: S should logically extend Set but can't due to either + // some javac bug or some weirdness in the spec, not sure which. + public > S copyInto(S set) { + set.addAll(this); + return set; } - return new FilteredNavigableSet(checkNotNull(unfiltered), checkNotNull(predicate)); + /** + * Returns an immutable copy of the current contents of this set view. Does not + * support null elements. + * + *

+ * Warning: this may have unexpected results if a backing set of this + * view uses a nonstandard notion of equivalence, for example if it is a + * {@link TreeSet} using a comparator that is inconsistent with + * {@link Object#equals(Object)}. + */ + public ImmutableSet immutableCopy() { + return ImmutableSet.copyOf(this); + } + } + + private static final class SubSet extends AbstractSet { + private final ImmutableMap inputSet; + private final int mask; + + SubSet(ImmutableMap inputSet, int mask) { + this.inputSet = inputSet; + this.mask = mask; + } + + @Override + public boolean contains(@Nullable Object o) { + Integer index = inputSet.get(o); + return index != null && (mask & (1 << index)) != 0; + } + + @Override + public Iterator iterator() { + return new UnmodifiableIterator() { + final ImmutableList elements = inputSet.keySet().asList(); + int remainingSetBits = mask; + + @Override + public boolean hasNext() { + return remainingSetBits != 0; + } + + @Override + public E next() { + int index = Integer.numberOfTrailingZeros(remainingSetBits); + if (index == 32) { + throw new NoSuchElementException(); + } + remainingSetBits &= ~(1 << index); + return elements.get(index); + } + }; + } + + @Override + public int size() { + return Integer.bitCount(mask); + } } @GwtIncompatible("NavigableSet") - private static class FilteredNavigableSet extends FilteredSortedSet implements NavigableSet { - FilteredNavigableSet(NavigableSet unfiltered, Predicate predicate) { - super(unfiltered, predicate); - } + static final class UnmodifiableNavigableSet extends ForwardingSortedSet + implements NavigableSet, Serializable { + private static final long serialVersionUID = 0; - NavigableSet unfiltered() { - return (NavigableSet) unfiltered; - } + private final NavigableSet delegate; - @Override - @Nullable - public E lower(E e) { - return Iterators.getNext(headSet(e, false).descendingIterator(), null); - } + private transient UnmodifiableNavigableSet descendingSet; - @Override - @Nullable - public E floor(E e) { - return Iterators.getNext(headSet(e, true).descendingIterator(), null); + UnmodifiableNavigableSet(NavigableSet delegate) { + this.delegate = checkNotNull(delegate); } @Override public E ceiling(E e) { - return Iterables.getFirst(tailSet(e, true), null); + return delegate.ceiling(e); } @Override - public E higher(E e) { - return Iterables.getFirst(tailSet(e, false), null); - } - - @Override - public E pollFirst() { - return Iterables.removeFirstMatching(unfiltered(), predicate); - } - - @Override - public E pollLast() { - return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate); - } - - @Override - public NavigableSet descendingSet() { - return Sets.filter(unfiltered().descendingSet(), predicate); + protected SortedSet delegate() { + return Collections.unmodifiableSortedSet(delegate); } @Override public Iterator descendingIterator() { - return Iterators.filter(unfiltered().descendingIterator(), predicate); + return Iterators.unmodifiableIterator(delegate.descendingIterator()); } @Override - public E last() { - return descendingIterator().next(); + public NavigableSet descendingSet() { + UnmodifiableNavigableSet result = descendingSet; + if (result == null) { + result = descendingSet = new UnmodifiableNavigableSet(delegate.descendingSet()); + result.descendingSet = this; + } + return result; } @Override - public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return filter(unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate); + public E floor(E e) { + return delegate.floor(e); } @Override public NavigableSet headSet(E toElement, boolean inclusive) { - return filter(unfiltered().headSet(toElement, inclusive), predicate); + return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); + } + + @Override + public E higher(E e) { + return delegate.higher(e); + } + + @Override + public E lower(E e) { + return delegate.lower(e); + } + + @Override + public E pollFirst() { + throw new UnsupportedOperationException(); + } + + @Override + public E pollLast() { + throw new UnsupportedOperationException(); + } + + @Override + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return unmodifiableNavigableSet(delegate.subSet(fromElement, fromInclusive, toElement, toInclusive)); } @Override public NavigableSet tailSet(E fromElement, boolean inclusive) { - return filter(unfiltered().tailSet(fromElement, inclusive), predicate); + return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive)); } } + // LinkedHashSet + /** * Returns every possible list that can be formed by choosing one element from * each of the given sets in order; the "n-ary @@ -975,9 +666,8 @@ public final class Sets { *

 	 *    {@code
 	 *
-	 *   Sets.cartesianProduct(ImmutableList.of(
-	 *       ImmutableSet.of(1, 2),
-	 *       ImmutableSet.of("A", "B", "C")))}
+	 * Sets.cartesianProduct(ImmutableList.of(ImmutableSet.of(1, 2), ImmutableSet.of("A", "B", "C")))
+	 * }
 	 * 
* *

@@ -1043,9 +733,8 @@ public final class Sets { *

 	 *    {@code
 	 *
-	 *   Sets.cartesianProduct(
-	 *       ImmutableSet.of(1, 2),
-	 *       ImmutableSet.of("A", "B", "C"))}
+	 * Sets.cartesianProduct(ImmutableSet.of(1, 2), ImmutableSet.of("A", "B", "C"))
+	 * }
 	 * 
* *

@@ -1102,83 +791,660 @@ public final class Sets { return cartesianProduct(Arrays.asList(sets)); } - private static final class CartesianSet extends ForwardingCollection> implements Set> { - private transient final ImmutableList> axes; - private transient final CartesianList delegate; + /** + * Creates an {@code EnumSet} consisting of all enum values that are not in the + * specified collection. If the collection is an {@link EnumSet}, this method + * has the same behavior as {@link EnumSet#complementOf}. Otherwise, the + * specified collection must contain at least one element, in order to determine + * the element type. If the collection could be empty, use + * {@link #complementOf(Collection, Class)} instead of this method. + * + * @param collection the collection whose complement should be stored in the + * enum set + * @return a new, modifiable {@code EnumSet} containing all values of the enum + * that aren't present in the given collection + * @throws IllegalArgumentException if {@code collection} is not an + * {@code EnumSet} instance and contains no + * elements + */ + public static > EnumSet complementOf(Collection collection) { + if (collection instanceof EnumSet) { + return EnumSet.complementOf((EnumSet) collection); + } + checkArgument(!collection.isEmpty(), "collection is empty; use the other version of this method"); + Class type = collection.iterator().next().getDeclaringClass(); + return makeComplementByHand(collection, type); + } - static Set> create(List> sets) { - ImmutableList.Builder> axesBuilder = new ImmutableList.Builder>( - sets.size()); - for (Set set : sets) { - ImmutableSet copy = ImmutableSet.copyOf(set); - if (copy.isEmpty()) { - return ImmutableSet.of(); - } - axesBuilder.add(copy); + // TreeSet + + /** + * Creates an {@code EnumSet} consisting of all enum values that are not in the + * specified collection. This is equivalent to {@link EnumSet#complementOf}, but + * can act on any input collection, as long as the elements are of enum type. + * + * @param collection the collection whose complement should be stored in the + * {@code EnumSet} + * @param type the type of the elements in the set + * @return a new, modifiable {@code EnumSet} initially containing all the values + * of the enum not present in the given collection + */ + public static > EnumSet complementOf(Collection collection, Class type) { + checkNotNull(collection); + return (collection instanceof EnumSet) ? EnumSet.complementOf((EnumSet) collection) + : makeComplementByHand(collection, type); + } + + /** + * Returns an unmodifiable view of the difference of two sets. The + * returned set contains all elements that are contained by {@code set1} and not + * contained by {@code set2}. {@code set2} may also contain elements not present + * in {@code set1}; these are simply ignored. The iteration order of the + * returned set matches that of {@code set1}. + * + *

+ * Results are undefined if {@code set1} and {@code set2} are sets based on + * different equivalence relations (as {@code HashSet}, {@code TreeSet}, and the + * keySet of an {@code IdentityHashMap} all are). + */ + public static SetView difference(final Set set1, final Set set2) { + checkNotNull(set1, "set1"); + checkNotNull(set2, "set2"); + + final Predicate notInSet2 = Predicates.not(Predicates.in(set2)); + return new SetView() { + @Override + public boolean contains(Object element) { + return set1.contains(element) && !set2.contains(element); } - final ImmutableList> axes = axesBuilder.build(); - ImmutableList> listAxes = new ImmutableList>() { - @Override - public int size() { - return axes.size(); - } - - @Override - public List get(int index) { - return axes.get(index).asList(); - } - - @Override - boolean isPartialView() { - return true; - } - }; - return new CartesianSet(axes, new CartesianList(listAxes)); - } - - private CartesianSet(ImmutableList> axes, CartesianList delegate) { - this.axes = axes; - this.delegate = delegate; - } - - @Override - protected Collection> delegate() { - return delegate; - } - - @Override - public boolean equals(@Nullable Object object) { - // Warning: this is broken if size() == 0, so it is critical that we - // substitute an empty ImmutableSet to the user in place of this - if (object instanceof CartesianSet) { - CartesianSet that = (CartesianSet) object; - return this.axes.equals(that.axes); + @Override + public boolean isEmpty() { + return set2.containsAll(set1); } - return super.equals(object); + + @Override + public Iterator iterator() { + return Iterators.filter(set1.iterator(), notInSet2); + } + + @Override + public int size() { + return Iterators.size(iterator()); + } + }; + } + + /** + * An implementation for {@link Set#equals(Object)}. + */ + static boolean equalsImpl(Set s, @Nullable Object object) { + if (s == object) { + return true; + } + if (object instanceof Set) { + Set o = (Set) object; + + try { + return s.size() == o.size() && s.containsAll(o); + } catch (NullPointerException ignored) { + return false; + } catch (ClassCastException ignored) { + return false; + } + } + return false; + } + + /** + * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that + * satisfy a predicate. The returned set is a live view of {@code unfiltered}; + * changes to one affect the other. + * + *

+ * The resulting set's iterator does not support {@code remove()}, but all other + * set methods are supported. When given an element that doesn't satisfy the + * predicate, the set's {@code add()} and {@code addAll()} methods throw an + * {@link IllegalArgumentException}. When methods such as {@code removeAll()} + * and {@code clear()} are called on the filtered set, only elements that + * satisfy the filter will be removed from the underlying set. + * + *

+ * The returned set isn't threadsafe or serializable, even if {@code unfiltered} + * is. + * + *

+ * Many of the filtered set's methods, such as {@code size()}, iterate across + * every element in the underlying set and determine which elements satisfy the + * filter. When a live view is not needed, it may be faster to copy + * {@code Iterables.filter(unfiltered, predicate)} and use the copy. + * + *

+ * Warning: {@code predicate} must be consistent with equals, as + * documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. (See {@link Iterables#filter(Iterable, Class)} for related + * functionality.) + * + * @since 14.0 + */ + @GwtIncompatible("NavigableSet") + @SuppressWarnings("unchecked") + public static NavigableSet filter(NavigableSet unfiltered, Predicate predicate) { + if (unfiltered instanceof FilteredSet) { + // Support clear(), removeAll(), and retainAll() when filtering a filtered + // collection. + FilteredSet filtered = (FilteredSet) unfiltered; + Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); + return new FilteredNavigableSet((NavigableSet) filtered.unfiltered, combinedPredicate); } - @Override - public int hashCode() { - // Warning: this is broken if size() == 0, so it is critical that we - // substitute an empty ImmutableSet to the user in place of this + return new FilteredNavigableSet(checkNotNull(unfiltered), checkNotNull(predicate)); + } - // It's a weird formula, but tests prove it works. - int adjust = size() - 1; - for (int i = 0; i < axes.size(); i++) { - adjust *= 31; - adjust = ~~adjust; - // in GWT, we have to deal with integer overflow carefully - } - int hash = 1; - for (Set axis : axes) { - hash = 31 * hash + (size() / axis.size() * axis.hashCode()); - - hash = ~~hash; - } - hash += adjust; - return ~~hash; + /** + * Returns the elements of {@code unfiltered} that satisfy a predicate. The + * returned set is a live view of {@code unfiltered}; changes to one affect the + * other. + * + *

+ * The resulting set's iterator does not support {@code remove()}, but all other + * set methods are supported. When given an element that doesn't satisfy the + * predicate, the set's {@code add()} and {@code addAll()} methods throw an + * {@link IllegalArgumentException}. When methods such as {@code + * removeAll()} and {@code clear()} are called on the filtered set, only + * elements that satisfy the filter will be removed from the underlying set. + * + *

+ * The returned set isn't threadsafe or serializable, even if {@code unfiltered} + * is. + * + *

+ * Many of the filtered set's methods, such as {@code size()}, iterate across + * every element in the underlying set and determine which elements satisfy the + * filter. When a live view is not needed, it may be faster to copy + * {@code Iterables.filter(unfiltered, predicate)} and use the copy. + * + *

+ * Warning: {@code predicate} must be consistent with equals, as + * documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. (See {@link Iterables#filter(Iterable, Class)} for related + * functionality.) + */ + // TODO(kevinb): how to omit that last sentence when building GWT javadoc? + public static Set filter(Set unfiltered, Predicate predicate) { + if (unfiltered instanceof SortedSet) { + return filter((SortedSet) unfiltered, predicate); } + if (unfiltered instanceof FilteredSet) { + // Support clear(), removeAll(), and retainAll() when filtering a filtered + // collection. + FilteredSet filtered = (FilteredSet) unfiltered; + Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); + return new FilteredSet((Set) filtered.unfiltered, combinedPredicate); + } + + return new FilteredSet(checkNotNull(unfiltered), checkNotNull(predicate)); + } + + /** + * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy + * a predicate. The returned set is a live view of {@code unfiltered}; changes + * to one affect the other. + * + *

+ * The resulting set's iterator does not support {@code remove()}, but all other + * set methods are supported. When given an element that doesn't satisfy the + * predicate, the set's {@code add()} and {@code addAll()} methods throw an + * {@link IllegalArgumentException}. When methods such as {@code removeAll()} + * and {@code clear()} are called on the filtered set, only elements that + * satisfy the filter will be removed from the underlying set. + * + *

+ * The returned set isn't threadsafe or serializable, even if {@code unfiltered} + * is. + * + *

+ * Many of the filtered set's methods, such as {@code size()}, iterate across + * every element in the underlying set and determine which elements satisfy the + * filter. When a live view is not needed, it may be faster to copy + * {@code Iterables.filter(unfiltered, predicate)} and use the copy. + * + *

+ * Warning: {@code predicate} must be consistent with equals, as + * documented at {@link Predicate#apply}. Do not provide a predicate such as + * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with + * equals. (See {@link Iterables#filter(Iterable, Class)} for related + * functionality.) + * + * @since 11.0 + */ + public static SortedSet filter(SortedSet unfiltered, Predicate predicate) { + return Platform.setsFilterSortedSet(unfiltered, predicate); + } + + static SortedSet filterSortedIgnoreNavigable(SortedSet unfiltered, Predicate predicate) { + if (unfiltered instanceof FilteredSet) { + // Support clear(), removeAll(), and retainAll() when filtering a filtered + // collection. + FilteredSet filtered = (FilteredSet) unfiltered; + Predicate combinedPredicate = Predicates.and(filtered.predicate, predicate); + return new FilteredSortedSet((SortedSet) filtered.unfiltered, combinedPredicate); + } + + return new FilteredSortedSet(checkNotNull(unfiltered), checkNotNull(predicate)); + } + + /** + * An implementation for {@link Set#hashCode()}. + */ + static int hashCodeImpl(Set s) { + int hashCode = 0; + for (Object o : s) { + hashCode += o != null ? o.hashCode() : 0; + + hashCode = ~~hashCode; + // Needed to deal with unusual integer overflow in GWT. + } + return hashCode; + } + + /** + * Returns an immutable set instance containing the given enum elements. + * Internally, the returned set will be backed by an {@link EnumSet}. + * + *

+ * The iteration order of the returned set follows the enum's iteration order, + * not the order in which the elements are provided to the method. + * + * @param anElement one of the elements the set should contain + * @param otherElements the rest of the elements the set should contain + * @return an immutable set containing those elements, minus duplicates + */ + // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 + @GwtCompatible(serializable = true) + public static > ImmutableSet immutableEnumSet(E anElement, E... otherElements) { + return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements)); + } + + /** + * Returns an immutable set instance containing the given enum elements. + * Internally, the returned set will be backed by an {@link EnumSet}. + * + *

+ * The iteration order of the returned set follows the enum's iteration order, + * not the order in which the elements appear in the given collection. + * + * @param elements the elements, all of the same {@code enum} type, that the set + * should contain + * @return an immutable set containing those elements, minus duplicates + */ + // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 + @GwtCompatible(serializable = true) + public static > ImmutableSet immutableEnumSet(Iterable elements) { + if (elements instanceof ImmutableEnumSet) { + return (ImmutableEnumSet) elements; + } else if (elements instanceof Collection) { + Collection collection = (Collection) elements; + if (collection.isEmpty()) { + return ImmutableSet.of(); + } else { + return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection)); + } + } else { + Iterator itr = elements.iterator(); + if (itr.hasNext()) { + EnumSet enumSet = EnumSet.of(itr.next()); + Iterators.addAll(enumSet, itr); + return ImmutableEnumSet.asImmutable(enumSet); + } else { + return ImmutableSet.of(); + } + } + } + + /** + * Returns an unmodifiable view of the intersection of two sets. The + * returned set contains all elements that are contained by both backing sets. + * The iteration order of the returned set matches that of {@code set1}. + * + *

+ * Results are undefined if {@code set1} and {@code set2} are sets based on + * different equivalence relations (as {@code HashSet}, {@code TreeSet}, and the + * keySet of an {@code IdentityHashMap} all are). + * + *

+ * Note: The returned view performs slightly better when {@code + * set1} is the smaller of the two sets. If you have reason to believe one of + * your sets will generally be smaller than the other, pass it first. + * Unfortunately, since this method sets the generic type of the returned set + * based on the type of the first set passed, this could in rare cases force you + * to make a cast, for example: + * + *

+	 *    {@code
+	 *
+	 *   Set aFewBadObjects = ...
+	 *   Set manyBadStrings = ...
+	 *
+	 *   // impossible for a non-String to be in the intersection
+	 *   SuppressWarnings("unchecked")
+	 *   Set badStrings = (Set) Sets.intersection(
+	 *       aFewBadObjects, manyBadStrings);}
+	 * 
+	 *
+	 * 

+ * This is unfortunate, but should come up only very rarely. + */ + public static SetView intersection(final Set set1, final Set set2) { + checkNotNull(set1, "set1"); + checkNotNull(set2, "set2"); + + final Predicate inSet2 = Predicates.in(set2); + return new SetView() { + @Override + public boolean contains(Object object) { + return set1.contains(object) && set2.contains(object); + } + + @Override + public boolean containsAll(Collection collection) { + return set1.containsAll(collection) && set2.containsAll(collection); + } + + @Override + public boolean isEmpty() { + return !iterator().hasNext(); + } + + @Override + public Iterator iterator() { + return Iterators.filter(set1.iterator(), inSet2); + } + + @Override + public int size() { + return Iterators.size(iterator()); + } + }; + } + + private static > EnumSet makeComplementByHand(Collection collection, Class type) { + EnumSet result = EnumSet.allOf(type); + result.removeAll(collection); + return result; + } + + /** + * Returns a new {@code EnumSet} instance containing the given elements. Unlike + * {@link EnumSet#copyOf(Collection)}, this method does not produce an exception + * on an empty collection, and it may be called on any iterable, not just a + * {@code Collection}. + */ + public static > EnumSet newEnumSet(Iterable iterable, Class elementType) { + EnumSet set = EnumSet.noneOf(elementType); + Iterables.addAll(set, iterable); + return set; + } + + /** + * Creates a mutable, empty {@code HashSet} instance. + * + *

+ * Note: if mutability is not required, use {@link ImmutableSet#of()} + * instead. + * + *

+ * Note: if {@code E} is an {@link Enum} type, use {@link EnumSet#noneOf} + * instead. + * + * @return a new, empty {@code HashSet} + */ + public static HashSet newHashSet() { + return new HashSet(); + } + + /** + * Creates a mutable {@code HashSet} instance containing the given + * elements in unspecified order. + * + *

+ * Note: if mutability is not required and the elements are non-null, use + * an overload of {@link ImmutableSet#of()} (for varargs) or + * {@link ImmutableSet#copyOf(Object[])} (for an array) instead. + * + *

+ * Note: if {@code E} is an {@link Enum} type, use + * {@link EnumSet#of(Enum, Enum[])} instead. + * + * @param elements the elements that the set should contain + * @return a new {@code HashSet} containing those elements (minus duplicates) + */ + public static HashSet newHashSet(E... elements) { + HashSet set = newHashSetWithExpectedSize(elements.length); + Collections.addAll(set, elements); + return set; + } + + /** + * Creates a mutable {@code HashSet} instance containing the given + * elements in unspecified order. + * + *

+ * Note: if mutability is not required and the elements are non-null, use + * {@link ImmutableSet#copyOf(Iterable)} instead. + * + *

+ * Note: if {@code E} is an {@link Enum} type, use + * {@link #newEnumSet(Iterable, Class)} instead. + * + * @param elements the elements that the set should contain + * @return a new {@code HashSet} containing those elements (minus duplicates) + */ + public static HashSet newHashSet(Iterable elements) { + return (elements instanceof Collection) ? new HashSet(Collections2.cast(elements)) + : newHashSet(elements.iterator()); + } + + /** + * Creates a mutable {@code HashSet} instance containing the given + * elements in unspecified order. + * + *

+ * Note: if mutability is not required and the elements are non-null, use + * {@link ImmutableSet#copyOf(Iterable)} instead. + * + *

+ * Note: if {@code E} is an {@link Enum} type, you should create an + * {@link EnumSet} instead. + * + * @param elements the elements that the set should contain + * @return a new {@code HashSet} containing those elements (minus duplicates) + */ + public static HashSet newHashSet(Iterator elements) { + HashSet set = newHashSet(); + Iterators.addAll(set, elements); + return set; + } + + /** + * Creates a {@code HashSet} instance, with a high enough "initial capacity" + * that it should hold {@code expectedSize} elements without growth. This + * behavior cannot be broadly guaranteed, but it is observed to be true for + * OpenJDK 1.6. It also can't be guaranteed that the method isn't inadvertently + * oversizing the returned set. + * + * @param expectedSize the number of elements you expect to add to the returned + * set + * @return a new, empty {@code HashSet} with enough capacity to hold {@code + * expectedSize} elements without resizing + * @throws IllegalArgumentException if {@code expectedSize} is negative + */ + public static HashSet newHashSetWithExpectedSize(int expectedSize) { + return new HashSet(Maps.capacity(expectedSize)); + } + + /** + * Creates an empty {@code Set} that uses identity to determine equality. It + * compares object references, instead of calling {@code equals}, to determine + * whether a provided object matches an element in the set. For example, + * {@code contains} returns {@code false} when passed an object that equals a + * set member, but isn't the same instance. This behavior is similar to the way + * {@code IdentityHashMap} handles key lookups. + * + * @since 8.0 + */ + public static Set newIdentityHashSet() { + return Sets.newSetFromMap(Maps.newIdentityHashMap()); + } + + /** + * Creates a mutable, empty {@code LinkedHashSet} instance. + * + *

+ * Note: if mutability is not required, use {@link ImmutableSet#of()} + * instead. + * + * @return a new, empty {@code LinkedHashSet} + */ + public static LinkedHashSet newLinkedHashSet() { + return new LinkedHashSet(); + } + + /** + * Creates a mutable {@code LinkedHashSet} instance containing the given + * elements in order. + * + *

+ * Note: if mutability is not required and the elements are non-null, use + * {@link ImmutableSet#copyOf(Iterable)} instead. + * + * @param elements the elements that the set should contain, in order + * @return a new {@code LinkedHashSet} containing those elements (minus + * duplicates) + */ + public static LinkedHashSet newLinkedHashSet(Iterable elements) { + if (elements instanceof Collection) { + return new LinkedHashSet(Collections2.cast(elements)); + } + LinkedHashSet set = newLinkedHashSet(); + Iterables.addAll(set, elements); + return set; + } + + /** + * Creates a {@code LinkedHashSet} instance, with a high enough "initial + * capacity" that it should hold {@code expectedSize} elements without + * growth. This behavior cannot be broadly guaranteed, but it is observed to be + * true for OpenJDK 1.6. It also can't be guaranteed that the method isn't + * inadvertently oversizing the returned set. + * + * @param expectedSize the number of elements you expect to add to the returned + * set + * @return a new, empty {@code LinkedHashSet} with enough capacity to hold + * {@code expectedSize} elements without resizing + * @throws IllegalArgumentException if {@code expectedSize} is negative + * @since 11.0 + */ + public static LinkedHashSet newLinkedHashSetWithExpectedSize(int expectedSize) { + return new LinkedHashSet(Maps.capacity(expectedSize)); + } + + /** + * Returns a set backed by the specified map. The resulting set displays the + * same ordering, concurrency, and performance characteristics as the backing + * map. In essence, this factory method provides a {@link Set} implementation + * corresponding to any {@link Map} implementation. There is no need to use this + * method on a {@link Map} implementation that already has a corresponding + * {@link Set} implementation (such as {@link java.util.HashMap} or + * {@link java.util.TreeMap}). + * + *

+ * Each method invocation on the set returned by this method results in exactly + * one method invocation on the backing map or its {@code keySet} view, with one + * exception. The {@code addAll} method is implemented as a sequence of + * {@code put} invocations on the backing map. + * + *

+ * The specified map must be empty at the time this method is invoked, and + * should not be accessed directly after this method returns. These conditions + * are ensured if the map is created empty, passed directly to this method, and + * no reference to the map is retained, as illustrated in the following code + * fragment: + * + *

+	 * {
+	 * 	@code
+	 *
+	 * 	Set identityHashSet = Sets.newSetFromMap(new IdentityHashMap());
+	 * }
+	 * 
+	 *
+	 * 

+ * This method has the same behavior as the JDK 6 method + * {@code Collections.newSetFromMap()}. The returned set is serializable if the + * backing map is. + * + * @param map the backing map + * @return the set backed by the map + * @throws IllegalArgumentException if {@code map} is not empty + */ + public static Set newSetFromMap(Map map) { + return Platform.newSetFromMap(map); + } + + /** + * Creates a mutable, empty {@code TreeSet} instance sorted by the + * natural sort ordering of its elements. + * + *

+ * Note: if mutability is not required, use + * {@link ImmutableSortedSet#of()} instead. + * + * @return a new, empty {@code TreeSet} + */ + public static TreeSet newTreeSet() { + return new TreeSet(); + } + + /** + * Creates a mutable, empty {@code TreeSet} instance with the given + * comparator. + * + *

+ * Note: if mutability is not required, use {@code + * ImmutableSortedSet.orderedBy(comparator).build()} instead. + * + * @param comparator the comparator to use to sort the set + * @return a new, empty {@code TreeSet} + * @throws NullPointerException if {@code comparator} is null + */ + public static TreeSet newTreeSet(Comparator comparator) { + return new TreeSet(checkNotNull(comparator)); + } + + /** + * Creates a mutable {@code TreeSet} instance containing the given + * elements sorted by their natural ordering. + * + *

+ * Note: if mutability is not required, use + * {@link ImmutableSortedSet#copyOf(Iterable)} instead. + * + *

+ * Note: If {@code elements} is a {@code SortedSet} with an explicit + * comparator, this method has different behavior than + * {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code TreeSet} with that + * comparator. + * + * @param elements the elements that the set should contain + * @return a new {@code TreeSet} containing those elements (minus duplicates) + */ + public static TreeSet newTreeSet(Iterable elements) { + TreeSet set = newTreeSet(); + Iterables.addAll(set, elements); + return set; } /** @@ -1219,252 +1485,54 @@ public final class Sets { return new PowerSet(set); } - private static final class SubSet extends AbstractSet { - private final ImmutableMap inputSet; - private final int mask; - - SubSet(ImmutableMap inputSet, int mask) { - this.inputSet = inputSet; - this.mask = mask; + static boolean removeAllImpl(Set set, Collection collection) { + checkNotNull(collection); // for GWT + if (collection instanceof Multiset) { + collection = ((Multiset) collection).elementSet(); } - - @Override - public Iterator iterator() { - return new UnmodifiableIterator() { - final ImmutableList elements = inputSet.keySet().asList(); - int remainingSetBits = mask; - - @Override - public boolean hasNext() { - return remainingSetBits != 0; - } - - @Override - public E next() { - int index = Integer.numberOfTrailingZeros(remainingSetBits); - if (index == 32) { - throw new NoSuchElementException(); - } - remainingSetBits &= ~(1 << index); - return elements.get(index); - } - }; - } - - @Override - public int size() { - return Integer.bitCount(mask); - } - - @Override - public boolean contains(@Nullable Object o) { - Integer index = inputSet.get(o); - return index != null && (mask & (1 << index)) != 0; - } - } - - private static final class PowerSet extends AbstractSet> { - final ImmutableMap inputSet; - - PowerSet(Set input) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - int i = 0; - for (E e : checkNotNull(input)) { - builder.put(e, i++); - } - this.inputSet = builder.build(); - checkArgument(inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size()); - } - - @Override - public int size() { - return 1 << inputSet.size(); - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Iterator> iterator() { - return new AbstractIndexedListIterator>(size()) { - @Override - protected Set get(final int setBits) { - return new SubSet(inputSet, setBits); - } - }; - } - - @Override - public boolean contains(@Nullable Object obj) { - if (obj instanceof Set) { - Set set = (Set) obj; - return inputSet.keySet().containsAll(set); - } - return false; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof PowerSet) { - PowerSet that = (PowerSet) obj; - return inputSet.equals(that.inputSet); - } - return super.equals(obj); - } - - @Override - public int hashCode() { - /* - * The sum of the sums of the hash codes in each subset is just the sum of each - * input element's hash code times the number of sets that element appears in. - * Each element appears in exactly half of the 2^n sets, so: - */ - return inputSet.keySet().hashCode() << (inputSet.size() - 1); - } - - @Override - public String toString() { - return "powerSet(" + inputSet + ")"; + /* + * AbstractSet.removeAll(List) has quadratic behavior if the list size is just + * less than the set's size. We augment the test by assuming that sets have fast + * contains() performance, and other collections don't. See + * http://code.google.com/p/guava-libraries/issues/detail?id=1013 + */ + if (collection instanceof Set && collection.size() > set.size()) { + return Iterators.removeAll(set.iterator(), collection); + } else { + return removeAllImpl(set, collection.iterator()); } } /** - * An implementation for {@link Set#hashCode()}. + * Remove each element in an iterable from a set. */ - static int hashCodeImpl(Set s) { - int hashCode = 0; - for (Object o : s) { - hashCode += o != null ? o.hashCode() : 0; - - hashCode = ~~hashCode; - // Needed to deal with unusual integer overflow in GWT. + static boolean removeAllImpl(Set set, Iterator iterator) { + boolean changed = false; + while (iterator.hasNext()) { + changed |= set.remove(iterator.next()); } - return hashCode; + return changed; } /** - * An implementation for {@link Set#equals(Object)}. - */ - static boolean equalsImpl(Set s, @Nullable Object object) { - if (s == object) { - return true; - } - if (object instanceof Set) { - Set o = (Set) object; - - try { - return s.size() == o.size() && s.containsAll(o); - } catch (NullPointerException ignored) { - return false; - } catch (ClassCastException ignored) { - return false; - } - } - return false; - } - - /** - * Returns an unmodifiable view of the specified navigable set. This method - * allows modules to provide users with "read-only" access to internal navigable - * sets. Query operations on the returned set "read through" to the specified - * set, and attempts to modify the returned set, whether direct or via its - * collection views, result in an {@code UnsupportedOperationException}. + * Returns an unmodifiable view of the symmetric difference of two sets. + * The returned set contains all elements that are contained in either + * {@code set1} or {@code set2} but not in both. The iteration order of the + * returned set is undefined. * *

- * The returned navigable set will be serializable if the specified navigable - * set is serializable. + * Results are undefined if {@code set1} and {@code set2} are sets based on + * different equivalence relations (as {@code HashSet}, {@code TreeSet}, and the + * keySet of an {@code IdentityHashMap} all are). * - * @param set the navigable set for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified navigable set - * @since 12.0 + * @since 3.0 */ - @GwtIncompatible("NavigableSet") - public static NavigableSet unmodifiableNavigableSet(NavigableSet set) { - if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) { - return set; - } - return new UnmodifiableNavigableSet(set); - } + public static SetView symmetricDifference(Set set1, Set set2) { + checkNotNull(set1, "set1"); + checkNotNull(set2, "set2"); - @GwtIncompatible("NavigableSet") - static final class UnmodifiableNavigableSet extends ForwardingSortedSet - implements NavigableSet, Serializable { - private final NavigableSet delegate; - - UnmodifiableNavigableSet(NavigableSet delegate) { - this.delegate = checkNotNull(delegate); - } - - @Override - protected SortedSet delegate() { - return Collections.unmodifiableSortedSet(delegate); - } - - @Override - public E lower(E e) { - return delegate.lower(e); - } - - @Override - public E floor(E e) { - return delegate.floor(e); - } - - @Override - public E ceiling(E e) { - return delegate.ceiling(e); - } - - @Override - public E higher(E e) { - return delegate.higher(e); - } - - @Override - public E pollFirst() { - throw new UnsupportedOperationException(); - } - - @Override - public E pollLast() { - throw new UnsupportedOperationException(); - } - - private transient UnmodifiableNavigableSet descendingSet; - - @Override - public NavigableSet descendingSet() { - UnmodifiableNavigableSet result = descendingSet; - if (result == null) { - result = descendingSet = new UnmodifiableNavigableSet(delegate.descendingSet()); - result.descendingSet = this; - } - return result; - } - - @Override - public Iterator descendingIterator() { - return Iterators.unmodifiableIterator(delegate.descendingIterator()); - } - - @Override - public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return unmodifiableNavigableSet(delegate.subSet(fromElement, fromInclusive, toElement, toInclusive)); - } - - @Override - public NavigableSet headSet(E toElement, boolean inclusive) { - return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); - } - - @Override - public NavigableSet tailSet(E fromElement, boolean inclusive) { - return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive)); - } - - private static final long serialVersionUID = 0; + // TODO(kevinb): Replace this with a more efficient implementation + return difference(union(set1, set2), intersection(set1, set2)); } /** @@ -1528,161 +1596,92 @@ public final class Sets { } /** - * Remove each element in an iterable from a set. + * Returns an unmodifiable view of the union of two sets. The returned + * set contains all elements that are contained in either backing set. Iterating + * over the returned set iterates first over all the elements of {@code set1}, + * then over each element of {@code set2}, in order, that is not contained in + * {@code set1}. + * + *

+ * Results are undefined if {@code set1} and {@code set2} are sets based on + * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and the + * {@link Map#keySet} of an {@code IdentityHashMap} all are). + * + *

+ * Note: The returned view performs better when {@code set1} is the + * smaller of the two sets. If you have reason to believe one of your sets will + * generally be smaller than the other, pass it first. + * + *

+ * Further, note that the current implementation is not suitable for nested + * {@code union} views, i.e. the following should be avoided when in a loop: + * {@code union = Sets.union(union, anotherSet);}, since iterating over the + * resulting set has a cubic complexity to the depth of the nesting. */ - static boolean removeAllImpl(Set set, Iterator iterator) { - boolean changed = false; - while (iterator.hasNext()) { - changed |= set.remove(iterator.next()); - } - return changed; - } + public static SetView union(final Set set1, final Set set2) { + checkNotNull(set1, "set1"); + checkNotNull(set2, "set2"); - static boolean removeAllImpl(Set set, Collection collection) { - checkNotNull(collection); // for GWT - if (collection instanceof Multiset) { - collection = ((Multiset) collection).elementSet(); - } - /* - * AbstractSet.removeAll(List) has quadratic behavior if the list size is just - * less than the set's size. We augment the test by assuming that sets have fast - * contains() performance, and other collections don't. See - * http://code.google.com/p/guava-libraries/issues/detail?id=1013 - */ - if (collection instanceof Set && collection.size() > set.size()) { - return Iterators.removeAll(set.iterator(), collection); - } else { - return removeAllImpl(set, collection.iterator()); - } - } + final Set set2minus1 = difference(set2, set1); - @GwtIncompatible("NavigableSet") - static class DescendingSet extends ForwardingNavigableSet { - private final NavigableSet forward; - - DescendingSet(NavigableSet forward) { - this.forward = forward; - } - - @Override - protected NavigableSet delegate() { - return forward; - } - - @Override - public E lower(E e) { - return forward.higher(e); - } - - @Override - public E floor(E e) { - return forward.ceiling(e); - } - - @Override - public E ceiling(E e) { - return forward.floor(e); - } - - @Override - public E higher(E e) { - return forward.lower(e); - } - - @Override - public E pollFirst() { - return forward.pollLast(); - } - - @Override - public E pollLast() { - return forward.pollFirst(); - } - - @Override - public NavigableSet descendingSet() { - return forward; - } - - @Override - public Iterator descendingIterator() { - return forward.iterator(); - } - - @Override - public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { - return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); - } - - @Override - public NavigableSet headSet(E toElement, boolean inclusive) { - return forward.tailSet(toElement, inclusive).descendingSet(); - } - - @Override - public NavigableSet tailSet(E fromElement, boolean inclusive) { - return forward.headSet(fromElement, inclusive).descendingSet(); - } - - @SuppressWarnings("unchecked") - @Override - public Comparator comparator() { - Comparator forwardComparator = forward.comparator(); - if (forwardComparator == null) { - return (Comparator) Ordering.natural().reverse(); - } else { - return reverse(forwardComparator); + return new SetView() { + @Override + public boolean contains(Object object) { + return set1.contains(object) || set2.contains(object); } - } - // If we inline this, we get a javac error. - private static Ordering reverse(Comparator forward) { - return Ordering.from(forward).reverse(); - } + @Override + public > S copyInto(S set) { + set.addAll(set1); + set.addAll(set2); + return set; + } - @Override - public E first() { - return forward.last(); - } + @Override + public ImmutableSet immutableCopy() { + return new ImmutableSet.Builder().addAll(set1).addAll(set2).build(); + } - @Override - public SortedSet headSet(E toElement) { - return standardHeadSet(toElement); - } + @Override + public boolean isEmpty() { + return set1.isEmpty() && set2.isEmpty(); + } - @Override - public E last() { - return forward.first(); - } + @Override + public Iterator iterator() { + return Iterators.unmodifiableIterator(Iterators.concat(set1.iterator(), set2minus1.iterator())); + } - @Override - public SortedSet subSet(E fromElement, E toElement) { - return standardSubSet(fromElement, toElement); - } + @Override + public int size() { + return set1.size() + set2minus1.size(); + } + }; + } - @Override - public SortedSet tailSet(E fromElement) { - return standardTailSet(fromElement); + /** + * Returns an unmodifiable view of the specified navigable set. This method + * allows modules to provide users with "read-only" access to internal navigable + * sets. Query operations on the returned set "read through" to the specified + * set, and attempts to modify the returned set, whether direct or via its + * collection views, result in an {@code UnsupportedOperationException}. + * + *

+ * The returned navigable set will be serializable if the specified navigable + * set is serializable. + * + * @param set the navigable set for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified navigable set + * @since 12.0 + */ + @GwtIncompatible("NavigableSet") + public static NavigableSet unmodifiableNavigableSet(NavigableSet set) { + if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) { + return set; } + return new UnmodifiableNavigableSet(set); + } - @Override - public Iterator iterator() { - return forward.descendingIterator(); - } - - @Override - public Object[] toArray() { - return standardToArray(); - } - - @Override - public T[] toArray(T[] array) { - return standardToArray(array); - } - - @Override - public String toString() { - return standardToString(); - } + private Sets() { } } diff --git a/src/main/java/com/google/common/collect/SingletonImmutableBiMap.java b/src/main/java/com/google/common/collect/SingletonImmutableBiMap.java index ac0a6074..3ad92bb6 100644 --- a/src/main/java/com/google/common/collect/SingletonImmutableBiMap.java +++ b/src/main/java/com/google/common/collect/SingletonImmutableBiMap.java @@ -35,6 +35,12 @@ final class SingletonImmutableBiMap extends ImmutableBiMap { final transient K singleKey; final transient V singleValue; + transient ImmutableBiMap inverse; + + SingletonImmutableBiMap(Entry entry) { + this(entry.getKey(), entry.getValue()); + } + SingletonImmutableBiMap(K singleKey, V singleValue) { checkEntryNotNull(singleKey, singleValue); this.singleKey = singleKey; @@ -47,20 +53,6 @@ final class SingletonImmutableBiMap extends ImmutableBiMap { this.inverse = inverse; } - SingletonImmutableBiMap(Entry entry) { - this(entry.getKey(), entry.getValue()); - } - - @Override - public V get(@Nullable Object key) { - return singleKey.equals(key) ? singleValue : null; - } - - @Override - public int size() { - return 1; - } - @Override public boolean containsKey(@Nullable Object key) { return singleKey.equals(key); @@ -71,11 +63,6 @@ final class SingletonImmutableBiMap extends ImmutableBiMap { return singleValue.equals(value); } - @Override - boolean isPartialView() { - return false; - } - @Override ImmutableSet> createEntrySet() { return ImmutableSet.of(Maps.immutableEntry(singleKey, singleValue)); @@ -86,7 +73,10 @@ final class SingletonImmutableBiMap extends ImmutableBiMap { return ImmutableSet.of(singleKey); } - transient ImmutableBiMap inverse; + @Override + public V get(@Nullable Object key) { + return singleKey.equals(key) ? singleValue : null; + } @Override public ImmutableBiMap inverse() { @@ -98,4 +88,14 @@ final class SingletonImmutableBiMap extends ImmutableBiMap { return result; } } + + @Override + boolean isPartialView() { + return false; + } + + @Override + public int size() { + return 1; + } } diff --git a/src/main/java/com/google/common/collect/SingletonImmutableList.java b/src/main/java/com/google/common/collect/SingletonImmutableList.java index 42eb9bfd..1f8969b6 100644 --- a/src/main/java/com/google/common/collect/SingletonImmutableList.java +++ b/src/main/java/com/google/common/collect/SingletonImmutableList.java @@ -40,48 +40,17 @@ final class SingletonImmutableList extends ImmutableList { this.element = checkNotNull(element); } - @Override - public E get(int index) { - Preconditions.checkElementIndex(index, 1); - return element; - } - - @Override - public int indexOf(@Nullable Object object) { - return element.equals(object) ? 0 : -1; - } - - @Override - public UnmodifiableIterator iterator() { - return Iterators.singletonIterator(element); - } - - @Override - public int lastIndexOf(@Nullable Object object) { - return indexOf(object); - } - - @Override - public int size() { - return 1; - } - - @Override - public ImmutableList subList(int fromIndex, int toIndex) { - Preconditions.checkPositionIndexes(fromIndex, toIndex, 1); - return (fromIndex == toIndex) ? ImmutableList.of() : this; - } - - @Override - public ImmutableList reverse() { - return this; - } - @Override public boolean contains(@Nullable Object object) { return element.equals(object); } + @Override + int copyIntoArray(Object[] dst, int offset) { + dst[offset] = element; + return offset + 1; + } + @Override public boolean equals(@Nullable Object object) { if (object == this) { @@ -94,6 +63,12 @@ final class SingletonImmutableList extends ImmutableList { return false; } + @Override + public E get(int index) { + Preconditions.checkElementIndex(index, 1); + return element; + } + @Override public int hashCode() { // not caching hash code since it could change if the element is mutable @@ -102,10 +77,8 @@ final class SingletonImmutableList extends ImmutableList { } @Override - public String toString() { - String elementToString = element.toString(); - return new StringBuilder(elementToString.length() + 2).append('[').append(elementToString).append(']') - .toString(); + public int indexOf(@Nullable Object object) { + return element.equals(object) ? 0 : -1; } @Override @@ -119,8 +92,35 @@ final class SingletonImmutableList extends ImmutableList { } @Override - int copyIntoArray(Object[] dst, int offset) { - dst[offset] = element; - return offset + 1; + public UnmodifiableIterator iterator() { + return Iterators.singletonIterator(element); + } + + @Override + public int lastIndexOf(@Nullable Object object) { + return indexOf(object); + } + + @Override + public ImmutableList reverse() { + return this; + } + + @Override + public int size() { + return 1; + } + + @Override + public ImmutableList subList(int fromIndex, int toIndex) { + Preconditions.checkPositionIndexes(fromIndex, toIndex, 1); + return (fromIndex == toIndex) ? ImmutableList.of() : this; + } + + @Override + public String toString() { + String elementToString = element.toString(); + return new StringBuilder(elementToString.length() + 2).append('[').append(elementToString).append(']') + .toString(); } } diff --git a/src/main/java/com/google/common/collect/SingletonImmutableSet.java b/src/main/java/com/google/common/collect/SingletonImmutableSet.java index c8847e07..b0ee52f6 100644 --- a/src/main/java/com/google/common/collect/SingletonImmutableSet.java +++ b/src/main/java/com/google/common/collect/SingletonImmutableSet.java @@ -53,31 +53,11 @@ final class SingletonImmutableSet extends ImmutableSet { cachedHashCode = hashCode; } - @Override - public int size() { - return 1; - } - - @Override - public boolean isEmpty() { - return false; - } - @Override public boolean contains(Object target) { return element.equals(target); } - @Override - public UnmodifiableIterator iterator() { - return Iterators.singletonIterator(element); - } - - @Override - boolean isPartialView() { - return false; - } - @Override int copyIntoArray(Object[] dst, int offset) { dst[offset] = element; @@ -106,11 +86,31 @@ final class SingletonImmutableSet extends ImmutableSet { return code; } + @Override + public boolean isEmpty() { + return false; + } + @Override boolean isHashCodeFast() { return cachedHashCode != 0; } + @Override + boolean isPartialView() { + return false; + } + + @Override + public UnmodifiableIterator iterator() { + return Iterators.singletonIterator(element); + } + + @Override + public int size() { + return 1; + } + @Override public String toString() { String elementToString = element.toString(); diff --git a/src/main/java/com/google/common/collect/SingletonImmutableTable.java b/src/main/java/com/google/common/collect/SingletonImmutableTable.java index cc1aae98..bb3b2825 100644 --- a/src/main/java/com/google/common/collect/SingletonImmutableTable.java +++ b/src/main/java/com/google/common/collect/SingletonImmutableTable.java @@ -33,16 +33,16 @@ class SingletonImmutableTable extends ImmutableTable { final C singleColumnKey; final V singleValue; + SingletonImmutableTable(Cell cell) { + this(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); + } + SingletonImmutableTable(R rowKey, C columnKey, V value) { this.singleRowKey = checkNotNull(rowKey); this.singleColumnKey = checkNotNull(columnKey); this.singleValue = checkNotNull(value); } - SingletonImmutableTable(Cell cell) { - this(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); - } - @Override public ImmutableMap column(C columnKey) { checkNotNull(columnKey); @@ -54,16 +54,6 @@ class SingletonImmutableTable extends ImmutableTable { return ImmutableMap.of(singleColumnKey, (Map) ImmutableMap.of(singleRowKey, singleValue)); } - @Override - public ImmutableMap> rowMap() { - return ImmutableMap.of(singleRowKey, (Map) ImmutableMap.of(singleColumnKey, singleValue)); - } - - @Override - public int size() { - return 1; - } - @Override ImmutableSet> createCellSet() { return ImmutableSet.of(cellOf(singleRowKey, singleColumnKey, singleValue)); @@ -73,4 +63,14 @@ class SingletonImmutableTable extends ImmutableTable { ImmutableCollection createValues() { return ImmutableSet.of(singleValue); } + + @Override + public ImmutableMap> rowMap() { + return ImmutableMap.of(singleRowKey, (Map) ImmutableMap.of(singleColumnKey, singleValue)); + } + + @Override + public int size() { + return 1; + } } diff --git a/src/main/java/com/google/common/collect/SortedIterables.java b/src/main/java/com/google/common/collect/SortedIterables.java index 5a19e3fd..bc750e5a 100644 --- a/src/main/java/com/google/common/collect/SortedIterables.java +++ b/src/main/java/com/google/common/collect/SortedIterables.java @@ -28,7 +28,14 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible final class SortedIterables { - private SortedIterables() { + @SuppressWarnings("unchecked") + // if sortedSet.comparator() is null, the set must be naturally ordered + public static Comparator comparator(SortedSet sortedSet) { + Comparator result = sortedSet.comparator(); + if (result == null) { + result = (Comparator) Ordering.natural(); + } + return result; } /** @@ -49,13 +56,6 @@ final class SortedIterables { return comparator.equals(comparator2); } - @SuppressWarnings("unchecked") - // if sortedSet.comparator() is null, the set must be naturally ordered - public static Comparator comparator(SortedSet sortedSet) { - Comparator result = sortedSet.comparator(); - if (result == null) { - result = (Comparator) Ordering.natural(); - } - return result; + private SortedIterables() { } } diff --git a/src/main/java/com/google/common/collect/SortedLists.java b/src/main/java/com/google/common/collect/SortedLists.java index 1f67f86d..f23e9657 100644 --- a/src/main/java/com/google/common/collect/SortedLists.java +++ b/src/main/java/com/google/common/collect/SortedLists.java @@ -40,7 +40,55 @@ import com.google.common.base.Function; @GwtCompatible @Beta final class SortedLists { - private SortedLists() { + /** + * A specification for which index to return if the list contains no elements + * that compare as equal to the key. + */ + public enum KeyAbsentBehavior { + /** + * Return the index of the next lower element in the list, or {@code -1} if + * there is no such element. + */ + NEXT_LOWER { + @Override + int resultIndex(int higherIndex) { + return higherIndex - 1; + } + }, + /** + * Return the index of the next higher element in the list, or + * {@code list.size()} if there is no such element. + */ + NEXT_HIGHER { + @Override + public int resultIndex(int higherIndex) { + return higherIndex; + } + }, + /** + * Return {@code ~insertionIndex}, where {@code insertionIndex} is defined as + * the point at which the key would be inserted into the list: the index of the + * next higher element in the list, or {@code list.size()} if there is no such + * element. + * + *

+ * Note that the return value will be {@code >= 0} if and only if there is an + * element of the list that compares as equal to the key. + * + *

+ * This is equivalent to the behavior of + * {@link java.util.Collections#binarySearch(List, Object)} when the key isn't + * present, since {@code ~insertionIndex} is equal to + * {@code -1 - insertionIndex}. + */ + INVERTED_INSERTION_INDEX { + @Override + public int resultIndex(int higherIndex) { + return ~higherIndex; + } + }; + + abstract int resultIndex(int higherIndex); } /** @@ -133,101 +181,6 @@ final class SortedLists { abstract int resultIndex(Comparator comparator, E key, List list, int foundIndex); } - /** - * A specification for which index to return if the list contains no elements - * that compare as equal to the key. - */ - public enum KeyAbsentBehavior { - /** - * Return the index of the next lower element in the list, or {@code -1} if - * there is no such element. - */ - NEXT_LOWER { - @Override - int resultIndex(int higherIndex) { - return higherIndex - 1; - } - }, - /** - * Return the index of the next higher element in the list, or - * {@code list.size()} if there is no such element. - */ - NEXT_HIGHER { - @Override - public int resultIndex(int higherIndex) { - return higherIndex; - } - }, - /** - * Return {@code ~insertionIndex}, where {@code insertionIndex} is defined as - * the point at which the key would be inserted into the list: the index of the - * next higher element in the list, or {@code list.size()} if there is no such - * element. - * - *

- * Note that the return value will be {@code >= 0} if and only if there is an - * element of the list that compares as equal to the key. - * - *

- * This is equivalent to the behavior of - * {@link java.util.Collections#binarySearch(List, Object)} when the key isn't - * present, since {@code ~insertionIndex} is equal to - * {@code -1 - insertionIndex}. - */ - INVERTED_INSERTION_INDEX { - @Override - public int resultIndex(int higherIndex) { - return ~higherIndex; - } - }; - - abstract int resultIndex(int higherIndex); - } - - /** - * Searches the specified naturally ordered list for the specified object using - * the binary search algorithm. - * - *

- * Equivalent to - * {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} - * using {@link Ordering#natural}. - */ - public static int binarySearch(List list, E e, - KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { - checkNotNull(e); - return binarySearch(list, checkNotNull(e), Ordering.natural(), presentBehavior, absentBehavior); - } - - /** - * Binary searches the list for the specified key, using the specified key - * function. - * - *

- * Equivalent to - * {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} - * using {@link Ordering#natural}. - */ - public static int binarySearch(List list, Function keyFunction, - @Nullable K key, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { - return binarySearch(list, keyFunction, key, Ordering.natural(), presentBehavior, absentBehavior); - } - - /** - * Binary searches the list for the specified key, using the specified key - * function. - * - *

- * Equivalent to - * {@link #binarySearch(List, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} - * using {@link Lists#transform(List, Function) Lists.transform(list, - * keyFunction)}. - */ - public static int binarySearch(List list, Function keyFunction, @Nullable K key, - Comparator keyComparator, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { - return binarySearch(Lists.transform(list, keyFunction), key, keyComparator, presentBehavior, absentBehavior); - } - /** * Searches the specified list for the specified object using the binary search * algorithm. The list must be sorted into ascending order according to the @@ -284,4 +237,51 @@ final class SortedLists { } return absentBehavior.resultIndex(lower); } + + /** + * Searches the specified naturally ordered list for the specified object using + * the binary search algorithm. + * + *

+ * Equivalent to + * {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} + * using {@link Ordering#natural}. + */ + public static int binarySearch(List list, E e, + KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { + checkNotNull(e); + return binarySearch(list, checkNotNull(e), Ordering.natural(), presentBehavior, absentBehavior); + } + + /** + * Binary searches the list for the specified key, using the specified key + * function. + * + *

+ * Equivalent to + * {@link #binarySearch(List, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} + * using {@link Lists#transform(List, Function) Lists.transform(list, + * keyFunction)}. + */ + public static int binarySearch(List list, Function keyFunction, @Nullable K key, + Comparator keyComparator, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { + return binarySearch(Lists.transform(list, keyFunction), key, keyComparator, presentBehavior, absentBehavior); + } + + /** + * Binary searches the list for the specified key, using the specified key + * function. + * + *

+ * Equivalent to + * {@link #binarySearch(List, Function, Object, Comparator, KeyPresentBehavior, KeyAbsentBehavior)} + * using {@link Ordering#natural}. + */ + public static int binarySearch(List list, Function keyFunction, + @Nullable K key, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { + return binarySearch(list, keyFunction, key, Ordering.natural(), presentBehavior, absentBehavior); + } + + private SortedLists() { + } } diff --git a/src/main/java/com/google/common/collect/SortedMapDifference.java b/src/main/java/com/google/common/collect/SortedMapDifference.java index ffb345c5..d651782c 100644 --- a/src/main/java/com/google/common/collect/SortedMapDifference.java +++ b/src/main/java/com/google/common/collect/SortedMapDifference.java @@ -30,14 +30,14 @@ import com.google.common.annotations.GwtCompatible; public interface SortedMapDifference extends MapDifference { @Override - SortedMap entriesOnlyOnLeft(); - - @Override - SortedMap entriesOnlyOnRight(); + SortedMap> entriesDiffering(); @Override SortedMap entriesInCommon(); @Override - SortedMap> entriesDiffering(); + SortedMap entriesOnlyOnLeft(); + + @Override + SortedMap entriesOnlyOnRight(); } diff --git a/src/main/java/com/google/common/collect/SortedMultiset.java b/src/main/java/com/google/common/collect/SortedMultiset.java index 9c72f728..c011afcf 100644 --- a/src/main/java/com/google/common/collect/SortedMultiset.java +++ b/src/main/java/com/google/common/collect/SortedMultiset.java @@ -58,28 +58,10 @@ public interface SortedMultiset extends SortedMultisetBridge, SortedIterab Comparator comparator(); /** - * Returns the entry of the first element in this multiset, or {@code null} if - * this multiset is empty. + * Returns a descending view of this multiset. Modifications made to either map + * will be reflected in the other. */ - Entry firstEntry(); - - /** - * Returns the entry of the last element in this multiset, or {@code null} if - * this multiset is empty. - */ - Entry lastEntry(); - - /** - * Returns and removes the entry associated with the lowest element in this - * multiset, or returns {@code null} if this multiset is empty. - */ - Entry pollFirstEntry(); - - /** - * Returns and removes the entry associated with the greatest element in this - * multiset, or returns {@code null} if this multiset is empty. - */ - Entry pollLastEntry(); + SortedMultiset descendingMultiset(); /** * Returns a {@link NavigableSet} view of the distinct elements in this @@ -101,20 +83,10 @@ public interface SortedMultiset extends SortedMultisetBridge, SortedIterab Set> entrySet(); /** - * {@inheritDoc} - * - *

- * The iterator returns the elements in ascending order according to this - * multiset's comparator. + * Returns the entry of the first element in this multiset, or {@code null} if + * this multiset is empty. */ - @Override - Iterator iterator(); - - /** - * Returns a descending view of this multiset. Modifications made to either map - * will be reflected in the other. - */ - SortedMultiset descendingMultiset(); + Entry firstEntry(); /** * Returns a view of this multiset restricted to the elements less than @@ -129,6 +101,34 @@ public interface SortedMultiset extends SortedMultisetBridge, SortedIterab */ SortedMultiset headMultiset(E upperBound, BoundType boundType); + /** + * {@inheritDoc} + * + *

+ * The iterator returns the elements in ascending order according to this + * multiset's comparator. + */ + @Override + Iterator iterator(); + + /** + * Returns the entry of the last element in this multiset, or {@code null} if + * this multiset is empty. + */ + Entry lastEntry(); + + /** + * Returns and removes the entry associated with the lowest element in this + * multiset, or returns {@code null} if this multiset is empty. + */ + Entry pollFirstEntry(); + + /** + * Returns and removes the entry associated with the greatest element in this + * multiset, or returns {@code null} if this multiset is empty. + */ + Entry pollLastEntry(); + /** * Returns a view of this multiset restricted to the range between * {@code lowerBound} and {@code upperBound}. The returned multiset is a view of diff --git a/src/main/java/com/google/common/collect/SortedMultisets.java b/src/main/java/com/google/common/collect/SortedMultisets.java index 04b6c18b..b467d4ef 100644 --- a/src/main/java/com/google/common/collect/SortedMultisets.java +++ b/src/main/java/com/google/common/collect/SortedMultisets.java @@ -39,9 +39,6 @@ import com.google.common.collect.Multiset.Entry; */ @GwtCompatible(emulated = true) final class SortedMultisets { - private SortedMultisets() { - } - /** * A skeleton implementation for {@link SortedMultiset#elementSet}. */ @@ -52,40 +49,40 @@ final class SortedMultisets { this.multiset = multiset; } - @Override - final SortedMultiset multiset() { - return multiset; - } - @Override public Comparator comparator() { return multiset().comparator(); } - @Override - public SortedSet subSet(E fromElement, E toElement) { - return multiset().subMultiset(fromElement, CLOSED, toElement, OPEN).elementSet(); - } - - @Override - public SortedSet headSet(E toElement) { - return multiset().headMultiset(toElement, OPEN).elementSet(); - } - - @Override - public SortedSet tailSet(E fromElement) { - return multiset().tailMultiset(fromElement, CLOSED).elementSet(); - } - @Override public E first() { return getElementOrThrow(multiset().firstEntry()); } + @Override + public SortedSet headSet(E toElement) { + return multiset().headMultiset(toElement, OPEN).elementSet(); + } + @Override public E last() { return getElementOrThrow(multiset().lastEntry()); } + + @Override + final SortedMultiset multiset() { + return multiset; + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + return multiset().subMultiset(fromElement, CLOSED, toElement, OPEN).elementSet(); + } + + @Override + public SortedSet tailSet(E fromElement) { + return multiset().tailMultiset(fromElement, CLOSED).elementSet(); + } } /** @@ -97,24 +94,14 @@ final class SortedMultisets { super(multiset); } - @Override - public E lower(E e) { - return getElementOrNull(multiset().headMultiset(e, OPEN).lastEntry()); - } - - @Override - public E floor(E e) { - return getElementOrNull(multiset().headMultiset(e, CLOSED).lastEntry()); - } - @Override public E ceiling(E e) { return getElementOrNull(multiset().tailMultiset(e, CLOSED).firstEntry()); } @Override - public E higher(E e) { - return getElementOrNull(multiset().tailMultiset(e, OPEN).firstEntry()); + public Iterator descendingIterator() { + return descendingSet().iterator(); } @Override @@ -123,8 +110,23 @@ final class SortedMultisets { } @Override - public Iterator descendingIterator() { - return descendingSet().iterator(); + public E floor(E e) { + return getElementOrNull(multiset().headMultiset(e, CLOSED).lastEntry()); + } + + @Override + public NavigableSet headSet(E toElement, boolean inclusive) { + return new NavigableElementSet(multiset().headMultiset(toElement, BoundType.forBoolean(inclusive))); + } + + @Override + public E higher(E e) { + return getElementOrNull(multiset().tailMultiset(e, OPEN).firstEntry()); + } + + @Override + public E lower(E e) { + return getElementOrNull(multiset().headMultiset(e, OPEN).lastEntry()); } @Override @@ -143,17 +145,16 @@ final class SortedMultisets { toElement, BoundType.forBoolean(toInclusive))); } - @Override - public NavigableSet headSet(E toElement, boolean inclusive) { - return new NavigableElementSet(multiset().headMultiset(toElement, BoundType.forBoolean(inclusive))); - } - @Override public NavigableSet tailSet(E fromElement, boolean inclusive) { return new NavigableElementSet(multiset().tailMultiset(fromElement, BoundType.forBoolean(inclusive))); } } + private static E getElementOrNull(@Nullable Entry entry) { + return (entry == null) ? null : entry.getElement(); + } + private static E getElementOrThrow(Entry entry) { if (entry == null) { throw new NoSuchElementException(); @@ -161,7 +162,6 @@ final class SortedMultisets { return entry.getElement(); } - private static E getElementOrNull(@Nullable Entry entry) { - return (entry == null) ? null : entry.getElement(); + private SortedMultisets() { } } diff --git a/src/main/java/com/google/common/collect/SortedSetMultimap.java b/src/main/java/com/google/common/collect/SortedSetMultimap.java index 50a8c2fc..b80a659d 100644 --- a/src/main/java/com/google/common/collect/SortedSetMultimap.java +++ b/src/main/java/com/google/common/collect/SortedSetMultimap.java @@ -53,6 +53,27 @@ import com.google.common.annotations.GwtCompatible; public interface SortedSetMultimap extends SetMultimap { // Following Javadoc copied from Multimap. + /** + * Returns a map view that associates each key with the corresponding values in + * the multimap. Changes to the returned map, such as element removal, will + * update the underlying multimap. The map does not support {@code setValue()} + * on its entries, {@code put}, or {@code putAll}. + * + *

+ * When passed a key that is present in the map, {@code + * asMap().get(Object)} has the same behavior as {@link #get}, returning a live + * collection. When passed a key that is not present, however, {@code + * asMap().get(Object)} returns {@code null} instead of an empty collection. + * + *

+ * Note: The returned map's values are guaranteed to be of type + * {@link SortedSet}. To obtain this map with the more specific generic type + * {@code Map>}, call {@link Multimaps#asMap(SortedSetMultimap)} + * instead. + */ + @Override + Map> asMap(); + /** * Returns a collection view of all values associated with a key. If no mappings * in the multimap have the provided key, an empty collection is returned. @@ -95,27 +116,6 @@ public interface SortedSetMultimap extends SetMultimap { @Override SortedSet replaceValues(K key, Iterable values); - /** - * Returns a map view that associates each key with the corresponding values in - * the multimap. Changes to the returned map, such as element removal, will - * update the underlying multimap. The map does not support {@code setValue()} - * on its entries, {@code put}, or {@code putAll}. - * - *

- * When passed a key that is present in the map, {@code - * asMap().get(Object)} has the same behavior as {@link #get}, returning a live - * collection. When passed a key that is not present, however, {@code - * asMap().get(Object)} returns {@code null} instead of an empty collection. - * - *

- * Note: The returned map's values are guaranteed to be of type - * {@link SortedSet}. To obtain this map with the more specific generic type - * {@code Map>}, call {@link Multimaps#asMap(SortedSetMultimap)} - * instead. - */ - @Override - Map> asMap(); - /** * Returns the comparator that orders the multimap values, with {@code null} * indicating that natural ordering is used. diff --git a/src/main/java/com/google/common/collect/SparseImmutableTable.java b/src/main/java/com/google/common/collect/SparseImmutableTable.java index c19ac743..ccb24544 100644 --- a/src/main/java/com/google/common/collect/SparseImmutableTable.java +++ b/src/main/java/com/google/common/collect/SparseImmutableTable.java @@ -82,16 +82,6 @@ final class SparseImmutableTable extends RegularImmutableTable return columnMap; } - @Override - public ImmutableMap> rowMap() { - return rowMap; - } - - @Override - public int size() { - return iterationOrderRow.length; - } - @Override Cell getCell(int index) { int rowIndex = iterationOrderRow[index]; @@ -109,4 +99,14 @@ final class SparseImmutableTable extends RegularImmutableTable int columnIndex = iterationOrderColumn[index]; return row.values().asList().get(columnIndex); } + + @Override + public ImmutableMap> rowMap() { + return rowMap; + } + + @Override + public int size() { + return iterationOrderRow.length; + } } diff --git a/src/main/java/com/google/common/collect/StandardRowSortedTable.java b/src/main/java/com/google/common/collect/StandardRowSortedTable.java index 737e999d..bc8f1317 100644 --- a/src/main/java/com/google/common/collect/StandardRowSortedTable.java +++ b/src/main/java/com/google/common/collect/StandardRowSortedTable.java @@ -56,12 +56,61 @@ class StandardRowSortedTable extends StandardTable implements * RowSortedTable subinterface with the revised methods? */ + private class RowSortedMap extends RowMap implements SortedMap> { + @Override + public Comparator comparator() { + return sortedBackingMap().comparator(); + } + + @Override + SortedSet createKeySet() { + return new Maps.SortedKeySet>(this); + } + + @Override + public R firstKey() { + return sortedBackingMap().firstKey(); + } + + @Override + public SortedMap> headMap(R toKey) { + checkNotNull(toKey); + return new StandardRowSortedTable(sortedBackingMap().headMap(toKey), factory).rowMap(); + } + + @Override + public SortedSet keySet() { + return (SortedSet) super.keySet(); + } + + @Override + public R lastKey() { + return sortedBackingMap().lastKey(); + } + + @Override + public SortedMap> subMap(R fromKey, R toKey) { + checkNotNull(fromKey); + checkNotNull(toKey); + return new StandardRowSortedTable(sortedBackingMap().subMap(fromKey, toKey), factory).rowMap(); + } + + @Override + public SortedMap> tailMap(R fromKey) { + checkNotNull(fromKey); + return new StandardRowSortedTable(sortedBackingMap().tailMap(fromKey), factory).rowMap(); + } + } + + private static final long serialVersionUID = 0; + StandardRowSortedTable(SortedMap> backingMap, Supplier> factory) { super(backingMap, factory); } - private SortedMap> sortedBackingMap() { - return (SortedMap>) backingMap; + @Override + SortedMap> createRowMap() { + return new RowSortedMap(); } /** @@ -88,56 +137,7 @@ class StandardRowSortedTable extends StandardTable implements return (SortedMap>) super.rowMap(); } - @Override - SortedMap> createRowMap() { - return new RowSortedMap(); + private SortedMap> sortedBackingMap() { + return (SortedMap>) backingMap; } - - private class RowSortedMap extends RowMap implements SortedMap> { - @Override - public SortedSet keySet() { - return (SortedSet) super.keySet(); - } - - @Override - SortedSet createKeySet() { - return new Maps.SortedKeySet>(this); - } - - @Override - public Comparator comparator() { - return sortedBackingMap().comparator(); - } - - @Override - public R firstKey() { - return sortedBackingMap().firstKey(); - } - - @Override - public R lastKey() { - return sortedBackingMap().lastKey(); - } - - @Override - public SortedMap> headMap(R toKey) { - checkNotNull(toKey); - return new StandardRowSortedTable(sortedBackingMap().headMap(toKey), factory).rowMap(); - } - - @Override - public SortedMap> subMap(R fromKey, R toKey) { - checkNotNull(fromKey); - checkNotNull(toKey); - return new StandardRowSortedTable(sortedBackingMap().subMap(fromKey, toKey), factory).rowMap(); - } - - @Override - public SortedMap> tailMap(R fromKey) { - checkNotNull(fromKey); - return new StandardRowSortedTable(sortedBackingMap().tailMap(fromKey), factory).rowMap(); - } - } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/StandardTable.java b/src/main/java/com/google/common/collect/StandardTable.java index f3540b99..317c2732 100644 --- a/src/main/java/com/google/common/collect/StandardTable.java +++ b/src/main/java/com/google/common/collect/StandardTable.java @@ -68,174 +68,6 @@ import com.google.common.collect.Sets.ImprovedAbstractSet; */ @GwtCompatible class StandardTable extends AbstractTable implements Serializable { - @GwtTransient - final Map> backingMap; - @GwtTransient - final Supplier> factory; - - StandardTable(Map> backingMap, Supplier> factory) { - this.backingMap = backingMap; - this.factory = factory; - } - - // Accessors - - @Override - public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { - return rowKey != null && columnKey != null && super.contains(rowKey, columnKey); - } - - @Override - public boolean containsColumn(@Nullable Object columnKey) { - if (columnKey == null) { - return false; - } - for (Map map : backingMap.values()) { - if (safeContainsKey(map, columnKey)) { - return true; - } - } - return false; - } - - @Override - public boolean containsRow(@Nullable Object rowKey) { - return rowKey != null && safeContainsKey(backingMap, rowKey); - } - - @Override - public boolean containsValue(@Nullable Object value) { - return value != null && super.containsValue(value); - } - - @Override - public V get(@Nullable Object rowKey, @Nullable Object columnKey) { - return (rowKey == null || columnKey == null) ? null : super.get(rowKey, columnKey); - } - - @Override - public boolean isEmpty() { - return backingMap.isEmpty(); - } - - @Override - public int size() { - int size = 0; - for (Map map : backingMap.values()) { - size += map.size(); - } - return size; - } - - // Mutators - - @Override - public void clear() { - backingMap.clear(); - } - - private Map getOrCreate(R rowKey) { - Map map = backingMap.get(rowKey); - if (map == null) { - map = factory.get(); - backingMap.put(rowKey, map); - } - return map; - } - - @Override - public V put(R rowKey, C columnKey, V value) { - checkNotNull(rowKey); - checkNotNull(columnKey); - checkNotNull(value); - return getOrCreate(rowKey).put(columnKey, value); - } - - @Override - public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { - if ((rowKey == null) || (columnKey == null)) { - return null; - } - Map map = safeGet(backingMap, rowKey); - if (map == null) { - return null; - } - V value = map.remove(columnKey); - if (map.isEmpty()) { - backingMap.remove(rowKey); - } - return value; - } - - private Map removeColumn(Object column) { - Map output = new LinkedHashMap(); - Iterator>> iterator = backingMap.entrySet().iterator(); - while (iterator.hasNext()) { - Entry> entry = iterator.next(); - V value = entry.getValue().remove(column); - if (value != null) { - output.put(entry.getKey(), value); - if (entry.getValue().isEmpty()) { - iterator.remove(); - } - } - } - return output; - } - - private boolean containsMapping(Object rowKey, Object columnKey, Object value) { - return value != null && value.equals(get(rowKey, columnKey)); - } - - /** Remove a row key / column key / value mapping, if present. */ - private boolean removeMapping(Object rowKey, Object columnKey, Object value) { - if (containsMapping(rowKey, columnKey, value)) { - remove(rowKey, columnKey); - return true; - } - return false; - } - - // Views - - /** - * Abstract set whose {@code isEmpty()} returns whether the table is empty and - * whose {@code clear()} clears all table mappings. - */ - private abstract class TableSet extends ImprovedAbstractSet { - @Override - public boolean isEmpty() { - return backingMap.isEmpty(); - } - - @Override - public void clear() { - backingMap.clear(); - } - } - - /** - * {@inheritDoc} - * - *

- * The set's iterator traverses the mappings for the first row, the mappings for - * the second row, and so on. - * - *

- * Each cell is an immutable snapshot of a row key / column key / value mapping, - * taken at the time the cell is returned by a method call to the set or its - * iterator. - */ - @Override - public Set> cellSet() { - return super.cellSet(); - } - - @Override - Iterator> cellIterator() { - return new CellIterator(); - } - private class CellIterator implements Iterator> { final Iterator>> rowIterator = backingMap.entrySet().iterator(); Entry> rowEntry; @@ -265,229 +97,8 @@ class StandardTable extends AbstractTable implements Serializa } } - @Override - public Map row(R rowKey) { - return new Row(rowKey); - } - - class Row extends ImprovedAbstractMap { - final R rowKey; - - Row(R rowKey) { - this.rowKey = checkNotNull(rowKey); - } - - Map backingRowMap; - - Map backingRowMap() { - return (backingRowMap == null || (backingRowMap.isEmpty() && backingMap.containsKey(rowKey))) - ? backingRowMap = computeBackingRowMap() - : backingRowMap; - } - - Map computeBackingRowMap() { - return backingMap.get(rowKey); - } - - // Call this every time we perform a removal. - void maintainEmptyInvariant() { - if (backingRowMap() != null && backingRowMap.isEmpty()) { - backingMap.remove(rowKey); - backingRowMap = null; - } - } - - @Override - public boolean containsKey(Object key) { - Map backingRowMap = backingRowMap(); - return (key != null && backingRowMap != null) && Maps.safeContainsKey(backingRowMap, key); - } - - @Override - public V get(Object key) { - Map backingRowMap = backingRowMap(); - return (key != null && backingRowMap != null) ? Maps.safeGet(backingRowMap, key) : null; - } - - @Override - public V put(C key, V value) { - checkNotNull(key); - checkNotNull(value); - if (backingRowMap != null && !backingRowMap.isEmpty()) { - return backingRowMap.put(key, value); - } - return StandardTable.this.put(rowKey, key, value); - } - - @Override - public V remove(Object key) { - Map backingRowMap = backingRowMap(); - if (backingRowMap == null) { - return null; - } - V result = Maps.safeRemove(backingRowMap, key); - maintainEmptyInvariant(); - return result; - } - - @Override - public void clear() { - Map backingRowMap = backingRowMap(); - if (backingRowMap != null) { - backingRowMap.clear(); - } - maintainEmptyInvariant(); - } - - @Override - protected Set> createEntrySet() { - return new RowEntrySet(); - } - - private final class RowEntrySet extends Maps.EntrySet { - @Override - Map map() { - return Row.this; - } - - @Override - public int size() { - Map map = backingRowMap(); - return (map == null) ? 0 : map.size(); - } - - @Override - public Iterator> iterator() { - final Map map = backingRowMap(); - if (map == null) { - return Iterators.emptyModifiableIterator(); - } - final Iterator> iterator = map.entrySet().iterator(); - return new Iterator>() { - @Override - public boolean hasNext() { - return iterator.hasNext(); - } - - @Override - public Entry next() { - final Entry entry = iterator.next(); - return new ForwardingMapEntry() { - @Override - protected Entry delegate() { - return entry; - } - - @Override - public V setValue(V value) { - return super.setValue(checkNotNull(value)); - } - - @Override - public boolean equals(Object object) { - // TODO(user): identify why this affects GWT tests - return standardEquals(object); - } - }; - } - - @Override - public void remove() { - iterator.remove(); - maintainEmptyInvariant(); - } - }; - } - } - } - - /** - * {@inheritDoc} - * - *

- * The returned map's views have iterators that don't support {@code remove()}. - */ - @Override - public Map column(C columnKey) { - return new Column(columnKey); - } - private class Column extends ImprovedAbstractMap { - final C columnKey; - - Column(C columnKey) { - this.columnKey = checkNotNull(columnKey); - } - - @Override - public V put(R key, V value) { - return StandardTable.this.put(key, columnKey, value); - } - - @Override - public V get(Object key) { - return StandardTable.this.get(key, columnKey); - } - - @Override - public boolean containsKey(Object key) { - return StandardTable.this.contains(key, columnKey); - } - - @Override - public V remove(Object key) { - return StandardTable.this.remove(key, columnKey); - } - - /** - * Removes all {@code Column} mappings whose row key and value satisfy the given - * predicate. - */ - boolean removeFromColumnIf(Predicate> predicate) { - boolean changed = false; - Iterator>> iterator = backingMap.entrySet().iterator(); - while (iterator.hasNext()) { - Entry> entry = iterator.next(); - Map map = entry.getValue(); - V value = map.get(columnKey); - if (value != null && predicate.apply(Maps.immutableEntry(entry.getKey(), value))) { - map.remove(columnKey); - changed = true; - if (map.isEmpty()) { - iterator.remove(); - } - } - } - return changed; - } - - @Override - Set> createEntrySet() { - return new EntrySet(); - } - private class EntrySet extends ImprovedAbstractSet> { - @Override - public Iterator> iterator() { - return new EntrySetIterator(); - } - - @Override - public int size() { - int size = 0; - for (Map map : backingMap.values()) { - if (map.containsKey(columnKey)) { - size++; - } - } - return size; - } - - @Override - public boolean isEmpty() { - return !containsColumn(columnKey); - } - @Override public void clear() { removeFromColumnIf(alwaysTrue()); @@ -502,6 +113,16 @@ class StandardTable extends AbstractTable implements Serializa return false; } + @Override + public boolean isEmpty() { + return !containsColumn(columnKey); + } + + @Override + public Iterator> iterator() { + return new EntrySetIterator(); + } + @Override public boolean remove(Object obj) { if (obj instanceof Entry) { @@ -515,6 +136,17 @@ class StandardTable extends AbstractTable implements Serializa public boolean retainAll(Collection c) { return removeFromColumnIf(not(in(c))); } + + @Override + public int size() { + int size = 0; + for (Map map : backingMap.values()) { + if (map.containsKey(columnKey)) { + size++; + } + } + return size; + } } private class EntrySetIterator extends AbstractIterator> { @@ -547,11 +179,6 @@ class StandardTable extends AbstractTable implements Serializa } } - @Override - Set createKeySet() { - return new KeySet(); - } - private class KeySet extends Maps.KeySet { KeySet() { super(Column.this); @@ -573,11 +200,6 @@ class StandardTable extends AbstractTable implements Serializa } } - @Override - Collection createValues() { - return new Values(); - } - private class Values extends Maps.Values { Values() { super(Column.this); @@ -598,40 +220,107 @@ class StandardTable extends AbstractTable implements Serializa return removeFromColumnIf(Maps.valuePredicateOnEntries(not(in(c)))); } } - } - @Override - public Set rowKeySet() { - return rowMap().keySet(); - } + final C columnKey; - private transient Set columnKeySet; - - /** - * {@inheritDoc} - * - *

- * The returned set has an iterator that does not support {@code remove()}. - * - *

- * The set's iterator traverses the columns of the first row, the columns of the - * second row, etc., skipping any columns that have appeared previously. - */ - @Override - public Set columnKeySet() { - Set result = columnKeySet; - return (result == null) ? columnKeySet = new ColumnKeySet() : result; - } - - private class ColumnKeySet extends TableSet { - @Override - public Iterator iterator() { - return createColumnKeyIterator(); + Column(C columnKey) { + this.columnKey = checkNotNull(columnKey); } @Override - public int size() { - return Iterators.size(iterator()); + public boolean containsKey(Object key) { + return StandardTable.this.contains(key, columnKey); + } + + @Override + Set> createEntrySet() { + return new EntrySet(); + } + + @Override + Set createKeySet() { + return new KeySet(); + } + + @Override + Collection createValues() { + return new Values(); + } + + @Override + public V get(Object key) { + return StandardTable.this.get(key, columnKey); + } + + @Override + public V put(R key, V value) { + return StandardTable.this.put(key, columnKey, value); + } + + @Override + public V remove(Object key) { + return StandardTable.this.remove(key, columnKey); + } + + /** + * Removes all {@code Column} mappings whose row key and value satisfy the given + * predicate. + */ + boolean removeFromColumnIf(Predicate> predicate) { + boolean changed = false; + Iterator>> iterator = backingMap.entrySet().iterator(); + while (iterator.hasNext()) { + Entry> entry = iterator.next(); + Map map = entry.getValue(); + V value = map.get(columnKey); + if (value != null && predicate.apply(Maps.immutableEntry(entry.getKey(), value))) { + map.remove(columnKey); + changed = true; + if (map.isEmpty()) { + iterator.remove(); + } + } + } + return changed; + } + } + + private class ColumnKeyIterator extends AbstractIterator { + // Use the same map type to support TreeMaps with comparators that aren't + // consistent with equals(). + final Map seen = factory.get(); + final Iterator> mapIterator = backingMap.values().iterator(); + Iterator> entryIterator = Iterators.emptyIterator(); + + @Override + protected C computeNext() { + while (true) { + if (entryIterator.hasNext()) { + Entry entry = entryIterator.next(); + if (!seen.containsKey(entry.getKey())) { + seen.put(entry.getKey(), entry.getValue()); + return entry.getKey(); + } + } else if (mapIterator.hasNext()) { + entryIterator = mapIterator.next().entrySet().iterator(); + } else { + return endOfData(); + } + } + } + } + + // Accessors + + private class ColumnKeySet extends TableSet { + @Override + public boolean contains(Object obj) { + return containsColumn(obj); + } + + @Override + public Iterator iterator() { + return createColumnKeyIterator(); } @Override @@ -690,186 +379,13 @@ class StandardTable extends AbstractTable implements Serializa } @Override - public boolean contains(Object obj) { - return containsColumn(obj); + public int size() { + return Iterators.size(iterator()); } } - /** - * Creates an iterator that returns each column value with duplicates omitted. - */ - Iterator createColumnKeyIterator() { - return new ColumnKeyIterator(); - } - - private class ColumnKeyIterator extends AbstractIterator { - // Use the same map type to support TreeMaps with comparators that aren't - // consistent with equals(). - final Map seen = factory.get(); - final Iterator> mapIterator = backingMap.values().iterator(); - Iterator> entryIterator = Iterators.emptyIterator(); - - @Override - protected C computeNext() { - while (true) { - if (entryIterator.hasNext()) { - Entry entry = entryIterator.next(); - if (!seen.containsKey(entry.getKey())) { - seen.put(entry.getKey(), entry.getValue()); - return entry.getKey(); - } - } else if (mapIterator.hasNext()) { - entryIterator = mapIterator.next().entrySet().iterator(); - } else { - return endOfData(); - } - } - } - } - - /** - * {@inheritDoc} - * - *

- * The collection's iterator traverses the values for the first row, the values - * for the second row, and so on. - */ - @Override - public Collection values() { - return super.values(); - } - - private transient Map> rowMap; - - @Override - public Map> rowMap() { - Map> result = rowMap; - return (result == null) ? rowMap = createRowMap() : result; - } - - Map> createRowMap() { - return new RowMap(); - } - - class RowMap extends ImprovedAbstractMap> { - @Override - public boolean containsKey(Object key) { - return containsRow(key); - } - - // performing cast only when key is in backing map and has the correct type - @SuppressWarnings("unchecked") - @Override - public Map get(Object key) { - return containsRow(key) ? row((R) key) : null; - } - - @Override - public Map remove(Object key) { - return (key == null) ? null : backingMap.remove(key); - } - - @Override - protected Set>> createEntrySet() { - return new EntrySet(); - } - - class EntrySet extends TableSet>> { - @Override - public Iterator>> iterator() { - return Maps.asMapEntryIterator(backingMap.keySet(), new Function>() { - @Override - public Map apply(R rowKey) { - return row(rowKey); - } - }); - } - - @Override - public int size() { - return backingMap.size(); - } - - @Override - public boolean contains(Object obj) { - if (obj instanceof Entry) { - Entry entry = (Entry) obj; - return entry.getKey() != null && entry.getValue() instanceof Map - && Collections2.safeContains(backingMap.entrySet(), entry); - } - return false; - } - - @Override - public boolean remove(Object obj) { - if (obj instanceof Entry) { - Entry entry = (Entry) obj; - return entry.getKey() != null && entry.getValue() instanceof Map - && backingMap.entrySet().remove(entry); - } - return false; - } - } - } - - private transient ColumnMap columnMap; - - @Override - public Map> columnMap() { - ColumnMap result = columnMap; - return (result == null) ? columnMap = new ColumnMap() : result; - } - private class ColumnMap extends ImprovedAbstractMap> { - // The cast to C occurs only when the key is in the map, implying that it - // has the correct type. - @SuppressWarnings("unchecked") - @Override - public Map get(Object key) { - return containsColumn(key) ? column((C) key) : null; - } - - @Override - public boolean containsKey(Object key) { - return containsColumn(key); - } - - @Override - public Map remove(Object key) { - return containsColumn(key) ? removeColumn(key) : null; - } - - @Override - public Set>> createEntrySet() { - return new ColumnMapEntrySet(); - } - - @Override - public Set keySet() { - return columnKeySet(); - } - - @Override - Collection> createValues() { - return new ColumnMapValues(); - } - class ColumnMapEntrySet extends TableSet>> { - @Override - public Iterator>> iterator() { - return Maps.asMapEntryIterator(columnKeySet(), new Function>() { - @Override - public Map apply(C columnKey) { - return column(columnKey); - } - }); - } - - @Override - public int size() { - return columnKeySet().size(); - } - @Override public boolean contains(Object obj) { if (obj instanceof Entry) { @@ -885,6 +401,16 @@ class StandardTable extends AbstractTable implements Serializa return false; } + @Override + public Iterator>> iterator() { + return Maps.asMapEntryIterator(columnKeySet(), new Function>() { + @Override + public Map apply(C columnKey) { + return column(columnKey); + } + }); + } + @Override public boolean remove(Object obj) { if (contains(obj)) { @@ -918,6 +444,11 @@ class StandardTable extends AbstractTable implements Serializa } return changed; } + + @Override + public int size() { + return columnKeySet().size(); + } } private class ColumnMapValues extends Maps.Values> { @@ -962,7 +493,477 @@ class StandardTable extends AbstractTable implements Serializa return changed; } } + + @Override + public boolean containsKey(Object key) { + return containsColumn(key); + } + + @Override + public Set>> createEntrySet() { + return new ColumnMapEntrySet(); + } + + @Override + Collection> createValues() { + return new ColumnMapValues(); + } + + // The cast to C occurs only when the key is in the map, implying that it + // has the correct type. + @SuppressWarnings("unchecked") + @Override + public Map get(Object key) { + return containsColumn(key) ? column((C) key) : null; + } + + @Override + public Set keySet() { + return columnKeySet(); + } + + @Override + public Map remove(Object key) { + return containsColumn(key) ? removeColumn(key) : null; + } + } + + class Row extends ImprovedAbstractMap { + private final class RowEntrySet extends Maps.EntrySet { + @Override + public Iterator> iterator() { + final Map map = backingRowMap(); + if (map == null) { + return Iterators.emptyModifiableIterator(); + } + final Iterator> iterator = map.entrySet().iterator(); + return new Iterator>() { + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public Entry next() { + final Entry entry = iterator.next(); + return new ForwardingMapEntry() { + @Override + protected Entry delegate() { + return entry; + } + + @Override + public boolean equals(Object object) { + // TODO(user): identify why this affects GWT tests + return standardEquals(object); + } + + @Override + public V setValue(V value) { + return super.setValue(checkNotNull(value)); + } + }; + } + + @Override + public void remove() { + iterator.remove(); + maintainEmptyInvariant(); + } + }; + } + + @Override + Map map() { + return Row.this; + } + + @Override + public int size() { + Map map = backingRowMap(); + return (map == null) ? 0 : map.size(); + } + } + + final R rowKey; + + Map backingRowMap; + + Row(R rowKey) { + this.rowKey = checkNotNull(rowKey); + } + + Map backingRowMap() { + return (backingRowMap == null || (backingRowMap.isEmpty() && backingMap.containsKey(rowKey))) + ? backingRowMap = computeBackingRowMap() + : backingRowMap; + } + + @Override + public void clear() { + Map backingRowMap = backingRowMap(); + if (backingRowMap != null) { + backingRowMap.clear(); + } + maintainEmptyInvariant(); + } + + Map computeBackingRowMap() { + return backingMap.get(rowKey); + } + + @Override + public boolean containsKey(Object key) { + Map backingRowMap = backingRowMap(); + return (key != null && backingRowMap != null) && Maps.safeContainsKey(backingRowMap, key); + } + + @Override + protected Set> createEntrySet() { + return new RowEntrySet(); + } + + @Override + public V get(Object key) { + Map backingRowMap = backingRowMap(); + return (key != null && backingRowMap != null) ? Maps.safeGet(backingRowMap, key) : null; + } + + // Call this every time we perform a removal. + void maintainEmptyInvariant() { + if (backingRowMap() != null && backingRowMap.isEmpty()) { + backingMap.remove(rowKey); + backingRowMap = null; + } + } + + @Override + public V put(C key, V value) { + checkNotNull(key); + checkNotNull(value); + if (backingRowMap != null && !backingRowMap.isEmpty()) { + return backingRowMap.put(key, value); + } + return StandardTable.this.put(rowKey, key, value); + } + + @Override + public V remove(Object key) { + Map backingRowMap = backingRowMap(); + if (backingRowMap == null) { + return null; + } + V result = Maps.safeRemove(backingRowMap, key); + maintainEmptyInvariant(); + return result; + } + } + + class RowMap extends ImprovedAbstractMap> { + class EntrySet extends TableSet>> { + @Override + public boolean contains(Object obj) { + if (obj instanceof Entry) { + Entry entry = (Entry) obj; + return entry.getKey() != null && entry.getValue() instanceof Map + && Collections2.safeContains(backingMap.entrySet(), entry); + } + return false; + } + + @Override + public Iterator>> iterator() { + return Maps.asMapEntryIterator(backingMap.keySet(), new Function>() { + @Override + public Map apply(R rowKey) { + return row(rowKey); + } + }); + } + + @Override + public boolean remove(Object obj) { + if (obj instanceof Entry) { + Entry entry = (Entry) obj; + return entry.getKey() != null && entry.getValue() instanceof Map + && backingMap.entrySet().remove(entry); + } + return false; + } + + @Override + public int size() { + return backingMap.size(); + } + } + + @Override + public boolean containsKey(Object key) { + return containsRow(key); + } + + @Override + protected Set>> createEntrySet() { + return new EntrySet(); + } + + // performing cast only when key is in backing map and has the correct type + @SuppressWarnings("unchecked") + @Override + public Map get(Object key) { + return containsRow(key) ? row((R) key) : null; + } + + @Override + public Map remove(Object key) { + return (key == null) ? null : backingMap.remove(key); + } + } + + /** + * Abstract set whose {@code isEmpty()} returns whether the table is empty and + * whose {@code clear()} clears all table mappings. + */ + private abstract class TableSet extends ImprovedAbstractSet { + @Override + public void clear() { + backingMap.clear(); + } + + @Override + public boolean isEmpty() { + return backingMap.isEmpty(); + } } private static final long serialVersionUID = 0; + + @GwtTransient + final Map> backingMap; + + // Mutators + + @GwtTransient + final Supplier> factory; + + private transient Set columnKeySet; + + private transient Map> rowMap; + + private transient ColumnMap columnMap; + + StandardTable(Map> backingMap, Supplier> factory) { + this.backingMap = backingMap; + this.factory = factory; + } + + @Override + Iterator> cellIterator() { + return new CellIterator(); + } + + /** + * {@inheritDoc} + * + *

+ * The set's iterator traverses the mappings for the first row, the mappings for + * the second row, and so on. + * + *

+ * Each cell is an immutable snapshot of a row key / column key / value mapping, + * taken at the time the cell is returned by a method call to the set or its + * iterator. + */ + @Override + public Set> cellSet() { + return super.cellSet(); + } + + // Views + + @Override + public void clear() { + backingMap.clear(); + } + + /** + * {@inheritDoc} + * + *

+ * The returned map's views have iterators that don't support {@code remove()}. + */ + @Override + public Map column(C columnKey) { + return new Column(columnKey); + } + + /** + * {@inheritDoc} + * + *

+ * The returned set has an iterator that does not support {@code remove()}. + * + *

+ * The set's iterator traverses the columns of the first row, the columns of the + * second row, etc., skipping any columns that have appeared previously. + */ + @Override + public Set columnKeySet() { + Set result = columnKeySet; + return (result == null) ? columnKeySet = new ColumnKeySet() : result; + } + + @Override + public Map> columnMap() { + ColumnMap result = columnMap; + return (result == null) ? columnMap = new ColumnMap() : result; + } + + @Override + public boolean contains(@Nullable Object rowKey, @Nullable Object columnKey) { + return rowKey != null && columnKey != null && super.contains(rowKey, columnKey); + } + + @Override + public boolean containsColumn(@Nullable Object columnKey) { + if (columnKey == null) { + return false; + } + for (Map map : backingMap.values()) { + if (safeContainsKey(map, columnKey)) { + return true; + } + } + return false; + } + + private boolean containsMapping(Object rowKey, Object columnKey, Object value) { + return value != null && value.equals(get(rowKey, columnKey)); + } + + @Override + public boolean containsRow(@Nullable Object rowKey) { + return rowKey != null && safeContainsKey(backingMap, rowKey); + } + + @Override + public boolean containsValue(@Nullable Object value) { + return value != null && super.containsValue(value); + } + + /** + * Creates an iterator that returns each column value with duplicates omitted. + */ + Iterator createColumnKeyIterator() { + return new ColumnKeyIterator(); + } + + Map> createRowMap() { + return new RowMap(); + } + + @Override + public V get(@Nullable Object rowKey, @Nullable Object columnKey) { + return (rowKey == null || columnKey == null) ? null : super.get(rowKey, columnKey); + } + + private Map getOrCreate(R rowKey) { + Map map = backingMap.get(rowKey); + if (map == null) { + map = factory.get(); + backingMap.put(rowKey, map); + } + return map; + } + + @Override + public boolean isEmpty() { + return backingMap.isEmpty(); + } + + @Override + public V put(R rowKey, C columnKey, V value) { + checkNotNull(rowKey); + checkNotNull(columnKey); + checkNotNull(value); + return getOrCreate(rowKey).put(columnKey, value); + } + + @Override + public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { + if ((rowKey == null) || (columnKey == null)) { + return null; + } + Map map = safeGet(backingMap, rowKey); + if (map == null) { + return null; + } + V value = map.remove(columnKey); + if (map.isEmpty()) { + backingMap.remove(rowKey); + } + return value; + } + + private Map removeColumn(Object column) { + Map output = new LinkedHashMap(); + Iterator>> iterator = backingMap.entrySet().iterator(); + while (iterator.hasNext()) { + Entry> entry = iterator.next(); + V value = entry.getValue().remove(column); + if (value != null) { + output.put(entry.getKey(), value); + if (entry.getValue().isEmpty()) { + iterator.remove(); + } + } + } + return output; + } + + /** Remove a row key / column key / value mapping, if present. */ + private boolean removeMapping(Object rowKey, Object columnKey, Object value) { + if (containsMapping(rowKey, columnKey, value)) { + remove(rowKey, columnKey); + return true; + } + return false; + } + + @Override + public Map row(R rowKey) { + return new Row(rowKey); + } + + @Override + public Set rowKeySet() { + return rowMap().keySet(); + } + + @Override + public Map> rowMap() { + Map> result = rowMap; + return (result == null) ? rowMap = createRowMap() : result; + } + + @Override + public int size() { + int size = 0; + for (Map map : backingMap.values()) { + size += map.size(); + } + return size; + } + + /** + * {@inheritDoc} + * + *

+ * The collection's iterator traverses the values for the first row, the values + * for the second row, and so on. + */ + @Override + public Collection values() { + return super.values(); + } } diff --git a/src/main/java/com/google/common/collect/Synchronized.java b/src/main/java/com/google/common/collect/Synchronized.java index 3b96d86e..f8868779 100644 --- a/src/main/java/com/google/common/collect/Synchronized.java +++ b/src/main/java/com/google/common/collect/Synchronized.java @@ -60,63 +60,226 @@ import com.google.common.annotations.VisibleForTesting; */ @GwtCompatible(emulated = true) final class Synchronized { - private Synchronized() { - } + private static class SynchronizedAsMap extends SynchronizedMap> { + private static final long serialVersionUID = 0; + transient Set>> asMapEntrySet; - static class SynchronizedObject implements Serializable { - final Object delegate; - final Object mutex; + transient Collection> asMapValues; - SynchronizedObject(Object delegate, @Nullable Object mutex) { - this.delegate = checkNotNull(delegate); - this.mutex = (mutex == null) ? this : mutex; + SynchronizedAsMap(Map> delegate, @Nullable Object mutex) { + super(delegate, mutex); } - Object delegate() { - return delegate; - } - - // No equals and hashCode; see ForwardingObject for details. - @Override - public String toString() { + public boolean containsValue(Object o) { + // values() and its contains() method are both synchronized. + return values().contains(o); + } + + @Override + public Set>> entrySet() { synchronized (mutex) { - return delegate.toString(); + if (asMapEntrySet == null) { + asMapEntrySet = new SynchronizedAsMapEntries(delegate().entrySet(), mutex); + } + return asMapEntrySet; } } - // Serialization invokes writeObject only when it's private. - // The SynchronizedObject subclasses don't need a writeObject method since - // they don't contain any non-transient member variables, while the - // following writeObject() handles the SynchronizedObject members. - - @GwtIncompatible("java.io.ObjectOutputStream") - private void writeObject(ObjectOutputStream stream) throws IOException { + @Override + public Collection get(Object key) { synchronized (mutex) { - stream.defaultWriteObject(); + Collection collection = super.get(key); + return (collection == null) ? null : typePreservingCollection(collection, mutex); } } - @GwtIncompatible("not needed in emulated source") - private static final long serialVersionUID = 0; + @Override + public Collection> values() { + synchronized (mutex) { + if (asMapValues == null) { + asMapValues = new SynchronizedAsMapValues(delegate().values(), mutex); + } + return asMapValues; + } + } } - private static Collection collection(Collection collection, @Nullable Object mutex) { - return new SynchronizedCollection(collection, mutex); + private static class SynchronizedAsMapEntries extends SynchronizedSet>> { + private static final long serialVersionUID = 0; + + SynchronizedAsMapEntries(Set>> delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + // See Collections.CheckedMap.CheckedEntrySet for details on attacks. + + @Override + public boolean contains(Object o) { + synchronized (mutex) { + return Maps.containsEntryImpl(delegate(), o); + } + } + + @Override + public boolean containsAll(Collection c) { + synchronized (mutex) { + return Collections2.containsAllImpl(delegate(), c); + } + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + synchronized (mutex) { + return Sets.equalsImpl(delegate(), o); + } + } + + @Override + public Iterator>> iterator() { + // Must be manually synchronized. + final Iterator>> iterator = super.iterator(); + return new ForwardingIterator>>() { + @Override + protected Iterator>> delegate() { + return iterator; + } + + @Override + public Map.Entry> next() { + final Map.Entry> entry = super.next(); + return new ForwardingMapEntry>() { + @Override + protected Map.Entry> delegate() { + return entry; + } + + @Override + public Collection getValue() { + return typePreservingCollection(entry.getValue(), mutex); + } + }; + } + }; + } + + @Override + public boolean remove(Object o) { + synchronized (mutex) { + return Maps.removeEntryImpl(delegate(), o); + } + } + + @Override + public boolean removeAll(Collection c) { + synchronized (mutex) { + return Iterators.removeAll(delegate().iterator(), c); + } + } + + @Override + public boolean retainAll(Collection c) { + synchronized (mutex) { + return Iterators.retainAll(delegate().iterator(), c); + } + } + + @Override + public Object[] toArray() { + synchronized (mutex) { + return ObjectArrays.toArrayImpl(delegate()); + } + } + + @Override + public T[] toArray(T[] array) { + synchronized (mutex) { + return ObjectArrays.toArrayImpl(delegate(), array); + } + } + } + + private static class SynchronizedAsMapValues extends SynchronizedCollection> { + private static final long serialVersionUID = 0; + + SynchronizedAsMapValues(Collection> delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + public Iterator> iterator() { + // Must be manually synchronized. + final Iterator> iterator = super.iterator(); + return new ForwardingIterator>() { + @Override + protected Iterator> delegate() { + return iterator; + } + + @Override + public Collection next() { + return typePreservingCollection(super.next(), mutex); + } + }; + } + } + + @VisibleForTesting + static class SynchronizedBiMap extends SynchronizedMap implements BiMap, Serializable { + private static final long serialVersionUID = 0; + private transient Set valueSet; + + private transient BiMap inverse; + + private SynchronizedBiMap(BiMap delegate, @Nullable Object mutex, @Nullable BiMap inverse) { + super(delegate, mutex); + this.inverse = inverse; + } + + @Override + BiMap delegate() { + return (BiMap) super.delegate(); + } + + @Override + public V forcePut(K key, V value) { + synchronized (mutex) { + return delegate().forcePut(key, value); + } + } + + @Override + public BiMap inverse() { + synchronized (mutex) { + if (inverse == null) { + inverse = new SynchronizedBiMap(delegate().inverse(), mutex, this); + } + return inverse; + } + } + + @Override + public Set values() { + synchronized (mutex) { + if (valueSet == null) { + valueSet = set(delegate().values(), mutex); + } + return valueSet; + } + } } @VisibleForTesting static class SynchronizedCollection extends SynchronizedObject implements Collection { + private static final long serialVersionUID = 0; + private SynchronizedCollection(Collection delegate, @Nullable Object mutex) { super(delegate, mutex); } - @SuppressWarnings("unchecked") - @Override - Collection delegate() { - return (Collection) super.delegate(); - } - @Override public boolean add(E e) { synchronized (mutex) { @@ -152,6 +315,12 @@ final class Synchronized { } } + @SuppressWarnings("unchecked") + @Override + Collection delegate() { + return (Collection) super.delegate(); + } + @Override public boolean isEmpty() { synchronized (mutex) { @@ -205,33 +374,175 @@ final class Synchronized { return delegate().toArray(a); } } + } + + @GwtIncompatible("Deque") + private static final class SynchronizedDeque extends SynchronizedQueue implements Deque { private static final long serialVersionUID = 0; - } - @VisibleForTesting - static Set set(Set set, @Nullable Object mutex) { - return new SynchronizedSet(set, mutex); - } - - static class SynchronizedSet extends SynchronizedCollection implements Set { - - SynchronizedSet(Set delegate, @Nullable Object mutex) { + SynchronizedDeque(Deque delegate, @Nullable Object mutex) { super(delegate, mutex); } @Override - Set delegate() { - return (Set) super.delegate(); + public void addFirst(E e) { + synchronized (mutex) { + delegate().addFirst(e); + } } @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } + public void addLast(E e) { synchronized (mutex) { - return delegate().equals(o); + delegate().addLast(e); + } + } + + @Override + Deque delegate() { + return (Deque) super.delegate(); + } + + @Override + public Iterator descendingIterator() { + synchronized (mutex) { + return delegate().descendingIterator(); + } + } + + @Override + public E getFirst() { + synchronized (mutex) { + return delegate().getFirst(); + } + } + + @Override + public E getLast() { + synchronized (mutex) { + return delegate().getLast(); + } + } + + @Override + public boolean offerFirst(E e) { + synchronized (mutex) { + return delegate().offerFirst(e); + } + } + + @Override + public boolean offerLast(E e) { + synchronized (mutex) { + return delegate().offerLast(e); + } + } + + @Override + public E peekFirst() { + synchronized (mutex) { + return delegate().peekFirst(); + } + } + + @Override + public E peekLast() { + synchronized (mutex) { + return delegate().peekLast(); + } + } + + @Override + public E pollFirst() { + synchronized (mutex) { + return delegate().pollFirst(); + } + } + + @Override + public E pollLast() { + synchronized (mutex) { + return delegate().pollLast(); + } + } + + @Override + public E pop() { + synchronized (mutex) { + return delegate().pop(); + } + } + + @Override + public void push(E e) { + synchronized (mutex) { + delegate().push(e); + } + } + + @Override + public E removeFirst() { + synchronized (mutex) { + return delegate().removeFirst(); + } + } + + @Override + public boolean removeFirstOccurrence(Object o) { + synchronized (mutex) { + return delegate().removeFirstOccurrence(o); + } + } + + @Override + public E removeLast() { + synchronized (mutex) { + return delegate().removeLast(); + } + } + + @Override + public boolean removeLastOccurrence(Object o) { + synchronized (mutex) { + return delegate().removeLastOccurrence(o); + } + } + } + + @GwtIncompatible("works but is needed only for NavigableMap") + private static class SynchronizedEntry extends SynchronizedObject implements Entry { + + private static final long serialVersionUID = 0; + + SynchronizedEntry(Entry delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @SuppressWarnings("unchecked") // guaranteed by the constructor + @Override + Entry delegate() { + return (Entry) super.delegate(); + } + + @Override + public boolean equals(Object obj) { + synchronized (mutex) { + return delegate().equals(obj); + } + } + + @Override + public K getKey() { + synchronized (mutex) { + return delegate().getKey(); + } + } + + @Override + public V getValue() { + synchronized (mutex) { + return delegate().getValue(); } } @@ -242,83 +553,21 @@ final class Synchronized { } } - private static final long serialVersionUID = 0; - } - - private static SortedSet sortedSet(SortedSet set, @Nullable Object mutex) { - return new SynchronizedSortedSet(set, mutex); - } - - static class SynchronizedSortedSet extends SynchronizedSet implements SortedSet { - SynchronizedSortedSet(SortedSet delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - @Override - SortedSet delegate() { - return (SortedSet) super.delegate(); - } - - @Override - public Comparator comparator() { + public V setValue(V value) { synchronized (mutex) { - return delegate().comparator(); + return delegate().setValue(value); } } - - @Override - public SortedSet subSet(E fromElement, E toElement) { - synchronized (mutex) { - return sortedSet(delegate().subSet(fromElement, toElement), mutex); - } - } - - @Override - public SortedSet headSet(E toElement) { - synchronized (mutex) { - return sortedSet(delegate().headSet(toElement), mutex); - } - } - - @Override - public SortedSet tailSet(E fromElement) { - synchronized (mutex) { - return sortedSet(delegate().tailSet(fromElement), mutex); - } - } - - @Override - public E first() { - synchronized (mutex) { - return delegate().first(); - } - } - - @Override - public E last() { - synchronized (mutex) { - return delegate().last(); - } - } - - private static final long serialVersionUID = 0; - } - - private static List list(List list, @Nullable Object mutex) { - return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList(list, mutex) - : new SynchronizedList(list, mutex); } private static class SynchronizedList extends SynchronizedCollection implements List { + private static final long serialVersionUID = 0; + SynchronizedList(List delegate, @Nullable Object mutex) { super(delegate, mutex); } - @Override - List delegate() { - return (List) super.delegate(); - } - @Override public void add(int index, E element) { synchronized (mutex) { @@ -333,6 +582,21 @@ final class Synchronized { } } + @Override + List delegate() { + return (List) super.delegate(); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + synchronized (mutex) { + return delegate().equals(o); + } + } + @Override public E get(int index) { synchronized (mutex) { @@ -340,6 +604,13 @@ final class Synchronized { } } + @Override + public int hashCode() { + synchronized (mutex) { + return delegate().hashCode(); + } + } + @Override public int indexOf(Object o) { synchronized (mutex) { @@ -384,324 +655,12 @@ final class Synchronized { return list(delegate().subList(fromIndex, toIndex), mutex); } } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - synchronized (mutex) { - return delegate().equals(o); - } - } - - @Override - public int hashCode() { - synchronized (mutex) { - return delegate().hashCode(); - } - } - - private static final long serialVersionUID = 0; - } - - private static class SynchronizedRandomAccessList extends SynchronizedList implements RandomAccess { - SynchronizedRandomAccessList(List list, @Nullable Object mutex) { - super(list, mutex); - } - - private static final long serialVersionUID = 0; - } - - static Multiset multiset(Multiset multiset, @Nullable Object mutex) { - if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { - return multiset; - } - return new SynchronizedMultiset(multiset, mutex); - } - - private static class SynchronizedMultiset extends SynchronizedCollection implements Multiset { - transient Set elementSet; - transient Set> entrySet; - - SynchronizedMultiset(Multiset delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - Multiset delegate() { - return (Multiset) super.delegate(); - } - - @Override - public int count(Object o) { - synchronized (mutex) { - return delegate().count(o); - } - } - - @Override - public int add(E e, int n) { - synchronized (mutex) { - return delegate().add(e, n); - } - } - - @Override - public int remove(Object o, int n) { - synchronized (mutex) { - return delegate().remove(o, n); - } - } - - @Override - public int setCount(E element, int count) { - synchronized (mutex) { - return delegate().setCount(element, count); - } - } - - @Override - public boolean setCount(E element, int oldCount, int newCount) { - synchronized (mutex) { - return delegate().setCount(element, oldCount, newCount); - } - } - - @Override - public Set elementSet() { - synchronized (mutex) { - if (elementSet == null) { - elementSet = typePreservingSet(delegate().elementSet(), mutex); - } - return elementSet; - } - } - - @Override - public Set> entrySet() { - synchronized (mutex) { - if (entrySet == null) { - entrySet = typePreservingSet(delegate().entrySet(), mutex); - } - return entrySet; - } - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - synchronized (mutex) { - return delegate().equals(o); - } - } - - @Override - public int hashCode() { - synchronized (mutex) { - return delegate().hashCode(); - } - } - - private static final long serialVersionUID = 0; - } - - static Multimap multimap(Multimap multimap, @Nullable Object mutex) { - if (multimap instanceof SynchronizedMultimap || multimap instanceof ImmutableMultimap) { - return multimap; - } - return new SynchronizedMultimap(multimap, mutex); - } - - private static class SynchronizedMultimap extends SynchronizedObject implements Multimap { - transient Set keySet; - transient Collection valuesCollection; - transient Collection> entries; - transient Map> asMap; - transient Multiset keys; - - @SuppressWarnings("unchecked") - @Override - Multimap delegate() { - return (Multimap) super.delegate(); - } - - SynchronizedMultimap(Multimap delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - public int size() { - synchronized (mutex) { - return delegate().size(); - } - } - - @Override - public boolean isEmpty() { - synchronized (mutex) { - return delegate().isEmpty(); - } - } - - @Override - public boolean containsKey(Object key) { - synchronized (mutex) { - return delegate().containsKey(key); - } - } - - @Override - public boolean containsValue(Object value) { - synchronized (mutex) { - return delegate().containsValue(value); - } - } - - @Override - public boolean containsEntry(Object key, Object value) { - synchronized (mutex) { - return delegate().containsEntry(key, value); - } - } - - @Override - public Collection get(K key) { - synchronized (mutex) { - return typePreservingCollection(delegate().get(key), mutex); - } - } - - @Override - public boolean put(K key, V value) { - synchronized (mutex) { - return delegate().put(key, value); - } - } - - @Override - public boolean putAll(K key, Iterable values) { - synchronized (mutex) { - return delegate().putAll(key, values); - } - } - - @Override - public boolean putAll(Multimap multimap) { - synchronized (mutex) { - return delegate().putAll(multimap); - } - } - - @Override - public Collection replaceValues(K key, Iterable values) { - synchronized (mutex) { - return delegate().replaceValues(key, values); // copy not synchronized - } - } - - @Override - public boolean remove(Object key, Object value) { - synchronized (mutex) { - return delegate().remove(key, value); - } - } - - @Override - public Collection removeAll(Object key) { - synchronized (mutex) { - return delegate().removeAll(key); // copy not synchronized - } - } - - @Override - public void clear() { - synchronized (mutex) { - delegate().clear(); - } - } - - @Override - public Set keySet() { - synchronized (mutex) { - if (keySet == null) { - keySet = typePreservingSet(delegate().keySet(), mutex); - } - return keySet; - } - } - - @Override - public Collection values() { - synchronized (mutex) { - if (valuesCollection == null) { - valuesCollection = collection(delegate().values(), mutex); - } - return valuesCollection; - } - } - - @Override - public Collection> entries() { - synchronized (mutex) { - if (entries == null) { - entries = typePreservingCollection(delegate().entries(), mutex); - } - return entries; - } - } - - @Override - public Map> asMap() { - synchronized (mutex) { - if (asMap == null) { - asMap = new SynchronizedAsMap(delegate().asMap(), mutex); - } - return asMap; - } - } - - @Override - public Multiset keys() { - synchronized (mutex) { - if (keys == null) { - keys = multiset(delegate().keys(), mutex); - } - return keys; - } - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - synchronized (mutex) { - return delegate().equals(o); - } - } - - @Override - public int hashCode() { - synchronized (mutex) { - return delegate().hashCode(); - } - } - - private static final long serialVersionUID = 0; - } - - static ListMultimap listMultimap(ListMultimap multimap, @Nullable Object mutex) { - if (multimap instanceof SynchronizedListMultimap || multimap instanceof ImmutableListMultimap) { - return multimap; - } - return new SynchronizedListMultimap(multimap, mutex); } private static class SynchronizedListMultimap extends SynchronizedMultimap implements ListMultimap { + private static final long serialVersionUID = 0; + SynchronizedListMultimap(ListMultimap delegate, @Nullable Object mutex) { super(delegate, mutex); } @@ -731,250 +690,19 @@ final class Synchronized { return delegate().replaceValues(key, values); // copy not synchronized } } - - private static final long serialVersionUID = 0; - } - - static SetMultimap setMultimap(SetMultimap multimap, @Nullable Object mutex) { - if (multimap instanceof SynchronizedSetMultimap || multimap instanceof ImmutableSetMultimap) { - return multimap; - } - return new SynchronizedSetMultimap(multimap, mutex); - } - - private static class SynchronizedSetMultimap extends SynchronizedMultimap implements SetMultimap { - transient Set> entrySet; - - SynchronizedSetMultimap(SetMultimap delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - SetMultimap delegate() { - return (SetMultimap) super.delegate(); - } - - @Override - public Set get(K key) { - synchronized (mutex) { - return set(delegate().get(key), mutex); - } - } - - @Override - public Set removeAll(Object key) { - synchronized (mutex) { - return delegate().removeAll(key); // copy not synchronized - } - } - - @Override - public Set replaceValues(K key, Iterable values) { - synchronized (mutex) { - return delegate().replaceValues(key, values); // copy not synchronized - } - } - - @Override - public Set> entries() { - synchronized (mutex) { - if (entrySet == null) { - entrySet = set(delegate().entries(), mutex); - } - return entrySet; - } - } - - private static final long serialVersionUID = 0; - } - - static SortedSetMultimap sortedSetMultimap(SortedSetMultimap multimap, @Nullable Object mutex) { - if (multimap instanceof SynchronizedSortedSetMultimap) { - return multimap; - } - return new SynchronizedSortedSetMultimap(multimap, mutex); - } - - private static class SynchronizedSortedSetMultimap extends SynchronizedSetMultimap - implements SortedSetMultimap { - SynchronizedSortedSetMultimap(SortedSetMultimap delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - SortedSetMultimap delegate() { - return (SortedSetMultimap) super.delegate(); - } - - @Override - public SortedSet get(K key) { - synchronized (mutex) { - return sortedSet(delegate().get(key), mutex); - } - } - - @Override - public SortedSet removeAll(Object key) { - synchronized (mutex) { - return delegate().removeAll(key); // copy not synchronized - } - } - - @Override - public SortedSet replaceValues(K key, Iterable values) { - synchronized (mutex) { - return delegate().replaceValues(key, values); // copy not synchronized - } - } - - @Override - public Comparator valueComparator() { - synchronized (mutex) { - return delegate().valueComparator(); - } - } - - private static final long serialVersionUID = 0; - } - - private static Collection typePreservingCollection(Collection collection, @Nullable Object mutex) { - if (collection instanceof SortedSet) { - return sortedSet((SortedSet) collection, mutex); - } - if (collection instanceof Set) { - return set((Set) collection, mutex); - } - if (collection instanceof List) { - return list((List) collection, mutex); - } - return collection(collection, mutex); - } - - private static Set typePreservingSet(Set set, @Nullable Object mutex) { - if (set instanceof SortedSet) { - return sortedSet((SortedSet) set, mutex); - } else { - return set(set, mutex); - } - } - - private static class SynchronizedAsMapEntries extends SynchronizedSet>> { - SynchronizedAsMapEntries(Set>> delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - public Iterator>> iterator() { - // Must be manually synchronized. - final Iterator>> iterator = super.iterator(); - return new ForwardingIterator>>() { - @Override - protected Iterator>> delegate() { - return iterator; - } - - @Override - public Map.Entry> next() { - final Map.Entry> entry = super.next(); - return new ForwardingMapEntry>() { - @Override - protected Map.Entry> delegate() { - return entry; - } - - @Override - public Collection getValue() { - return typePreservingCollection(entry.getValue(), mutex); - } - }; - } - }; - } - - // See Collections.CheckedMap.CheckedEntrySet for details on attacks. - - @Override - public Object[] toArray() { - synchronized (mutex) { - return ObjectArrays.toArrayImpl(delegate()); - } - } - - @Override - public T[] toArray(T[] array) { - synchronized (mutex) { - return ObjectArrays.toArrayImpl(delegate(), array); - } - } - - @Override - public boolean contains(Object o) { - synchronized (mutex) { - return Maps.containsEntryImpl(delegate(), o); - } - } - - @Override - public boolean containsAll(Collection c) { - synchronized (mutex) { - return Collections2.containsAllImpl(delegate(), c); - } - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } - synchronized (mutex) { - return Sets.equalsImpl(delegate(), o); - } - } - - @Override - public boolean remove(Object o) { - synchronized (mutex) { - return Maps.removeEntryImpl(delegate(), o); - } - } - - @Override - public boolean removeAll(Collection c) { - synchronized (mutex) { - return Iterators.removeAll(delegate().iterator(), c); - } - } - - @Override - public boolean retainAll(Collection c) { - synchronized (mutex) { - return Iterators.retainAll(delegate().iterator(), c); - } - } - - private static final long serialVersionUID = 0; - } - - @VisibleForTesting - static Map map(Map map, @Nullable Object mutex) { - return new SynchronizedMap(map, mutex); } private static class SynchronizedMap extends SynchronizedObject implements Map { + private static final long serialVersionUID = 0; transient Set keySet; transient Collection values; + transient Set> entrySet; SynchronizedMap(Map delegate, @Nullable Object mutex) { super(delegate, mutex); } - @SuppressWarnings("unchecked") - @Override - Map delegate() { - return (Map) super.delegate(); - } - @Override public void clear() { synchronized (mutex) { @@ -996,6 +724,12 @@ final class Synchronized { } } + @SuppressWarnings("unchecked") + @Override + Map delegate() { + return (Map) super.delegate(); + } + @Override public Set> entrySet() { synchronized (mutex) { @@ -1006,6 +740,16 @@ final class Synchronized { } } + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + synchronized (mutex) { + return delegate().equals(o); + } + } + @Override public V get(Object key) { synchronized (mutex) { @@ -1013,6 +757,13 @@ final class Synchronized { } } + @Override + public int hashCode() { + synchronized (mutex) { + return delegate().hashCode(); + } + } + @Override public boolean isEmpty() { synchronized (mutex) { @@ -1067,6 +818,234 @@ final class Synchronized { return values; } } + } + + private static class SynchronizedMultimap extends SynchronizedObject implements Multimap { + private static final long serialVersionUID = 0; + transient Set keySet; + transient Collection valuesCollection; + transient Collection> entries; + transient Map> asMap; + + transient Multiset keys; + + SynchronizedMultimap(Multimap delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + public Map> asMap() { + synchronized (mutex) { + if (asMap == null) { + asMap = new SynchronizedAsMap(delegate().asMap(), mutex); + } + return asMap; + } + } + + @Override + public void clear() { + synchronized (mutex) { + delegate().clear(); + } + } + + @Override + public boolean containsEntry(Object key, Object value) { + synchronized (mutex) { + return delegate().containsEntry(key, value); + } + } + + @Override + public boolean containsKey(Object key) { + synchronized (mutex) { + return delegate().containsKey(key); + } + } + + @Override + public boolean containsValue(Object value) { + synchronized (mutex) { + return delegate().containsValue(value); + } + } + + @SuppressWarnings("unchecked") + @Override + Multimap delegate() { + return (Multimap) super.delegate(); + } + + @Override + public Collection> entries() { + synchronized (mutex) { + if (entries == null) { + entries = typePreservingCollection(delegate().entries(), mutex); + } + return entries; + } + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + synchronized (mutex) { + return delegate().equals(o); + } + } + + @Override + public Collection get(K key) { + synchronized (mutex) { + return typePreservingCollection(delegate().get(key), mutex); + } + } + + @Override + public int hashCode() { + synchronized (mutex) { + return delegate().hashCode(); + } + } + + @Override + public boolean isEmpty() { + synchronized (mutex) { + return delegate().isEmpty(); + } + } + + @Override + public Multiset keys() { + synchronized (mutex) { + if (keys == null) { + keys = multiset(delegate().keys(), mutex); + } + return keys; + } + } + + @Override + public Set keySet() { + synchronized (mutex) { + if (keySet == null) { + keySet = typePreservingSet(delegate().keySet(), mutex); + } + return keySet; + } + } + + @Override + public boolean put(K key, V value) { + synchronized (mutex) { + return delegate().put(key, value); + } + } + + @Override + public boolean putAll(K key, Iterable values) { + synchronized (mutex) { + return delegate().putAll(key, values); + } + } + + @Override + public boolean putAll(Multimap multimap) { + synchronized (mutex) { + return delegate().putAll(multimap); + } + } + + @Override + public boolean remove(Object key, Object value) { + synchronized (mutex) { + return delegate().remove(key, value); + } + } + + @Override + public Collection removeAll(Object key) { + synchronized (mutex) { + return delegate().removeAll(key); // copy not synchronized + } + } + + @Override + public Collection replaceValues(K key, Iterable values) { + synchronized (mutex) { + return delegate().replaceValues(key, values); // copy not synchronized + } + } + + @Override + public int size() { + synchronized (mutex) { + return delegate().size(); + } + } + + @Override + public Collection values() { + synchronized (mutex) { + if (valuesCollection == null) { + valuesCollection = collection(delegate().values(), mutex); + } + return valuesCollection; + } + } + } + + private static class SynchronizedMultiset extends SynchronizedCollection implements Multiset { + private static final long serialVersionUID = 0; + transient Set elementSet; + + transient Set> entrySet; + + SynchronizedMultiset(Multiset delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + public int add(E e, int n) { + synchronized (mutex) { + return delegate().add(e, n); + } + } + + @Override + public int count(Object o) { + synchronized (mutex) { + return delegate().count(o); + } + } + + @Override + Multiset delegate() { + return (Multiset) super.delegate(); + } + + @Override + public Set elementSet() { + synchronized (mutex) { + if (elementSet == null) { + elementSet = typePreservingSet(delegate().elementSet(), mutex); + } + return elementSet; + } + } + + @Override + public Set> entrySet() { + synchronized (mutex) { + if (entrySet == null) { + entrySet = typePreservingSet(delegate().entrySet(), mutex); + } + return entrySet; + } + } @Override public boolean equals(Object o) { @@ -1085,203 +1064,216 @@ final class Synchronized { } } - private static final long serialVersionUID = 0; - } - - static SortedMap sortedMap(SortedMap sortedMap, @Nullable Object mutex) { - return new SynchronizedSortedMap(sortedMap, mutex); - } - - static class SynchronizedSortedMap extends SynchronizedMap implements SortedMap { - - SynchronizedSortedMap(SortedMap delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - @Override - SortedMap delegate() { - return (SortedMap) super.delegate(); - } - - @Override - public Comparator comparator() { + public int remove(Object o, int n) { synchronized (mutex) { - return delegate().comparator(); + return delegate().remove(o, n); } } @Override - public K firstKey() { + public int setCount(E element, int count) { synchronized (mutex) { - return delegate().firstKey(); + return delegate().setCount(element, count); + } + } + + @Override + public boolean setCount(E element, int oldCount, int newCount) { + synchronized (mutex) { + return delegate().setCount(element, oldCount, newCount); + } + } + } + + @GwtIncompatible("NavigableMap") + @VisibleForTesting + static class SynchronizedNavigableMap extends SynchronizedSortedMap implements NavigableMap { + + private static final long serialVersionUID = 0; + + transient NavigableSet descendingKeySet; + + transient NavigableMap descendingMap; + + transient NavigableSet navigableKeySet; + + SynchronizedNavigableMap(NavigableMap delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + public Entry ceilingEntry(K key) { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); + } + } + + @Override + public K ceilingKey(K key) { + synchronized (mutex) { + return delegate().ceilingKey(key); + } + } + + @Override + NavigableMap delegate() { + return (NavigableMap) super.delegate(); + } + + @Override + public NavigableSet descendingKeySet() { + synchronized (mutex) { + if (descendingKeySet == null) { + return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); + } + return descendingKeySet; + } + } + + @Override + public NavigableMap descendingMap() { + synchronized (mutex) { + if (descendingMap == null) { + return descendingMap = navigableMap(delegate().descendingMap(), mutex); + } + return descendingMap; + } + } + + @Override + public Entry firstEntry() { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().firstEntry(), mutex); + } + } + + @Override + public Entry floorEntry(K key) { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); + } + } + + @Override + public K floorKey(K key) { + synchronized (mutex) { + return delegate().floorKey(key); } } @Override public SortedMap headMap(K toKey) { + return headMap(toKey, false); + } + + @Override + public NavigableMap headMap(K toKey, boolean inclusive) { synchronized (mutex) { - return sortedMap(delegate().headMap(toKey), mutex); + return navigableMap(delegate().headMap(toKey, inclusive), mutex); } } @Override - public K lastKey() { + public Entry higherEntry(K key) { synchronized (mutex) { - return delegate().lastKey(); + return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); + } + } + + @Override + public K higherKey(K key) { + synchronized (mutex) { + return delegate().higherKey(key); + } + } + + @Override + public Set keySet() { + return navigableKeySet(); + } + + @Override + public Entry lastEntry() { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().lastEntry(), mutex); + } + } + + @Override + public Entry lowerEntry(K key) { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); + } + } + + @Override + public K lowerKey(K key) { + synchronized (mutex) { + return delegate().lowerKey(key); + } + } + + @Override + public NavigableSet navigableKeySet() { + synchronized (mutex) { + if (navigableKeySet == null) { + return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); + } + return navigableKeySet; + } + } + + @Override + public Entry pollFirstEntry() { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); + } + } + + @Override + public Entry pollLastEntry() { + synchronized (mutex) { + return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); + } + } + + @Override + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + synchronized (mutex) { + return navigableMap(delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } @Override public SortedMap subMap(K fromKey, K toKey) { - synchronized (mutex) { - return sortedMap(delegate().subMap(fromKey, toKey), mutex); - } + return subMap(fromKey, true, toKey, false); } @Override public SortedMap tailMap(K fromKey) { + return tailMap(fromKey, true); + } + + @Override + public NavigableMap tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { - return sortedMap(delegate().tailMap(fromKey), mutex); + return navigableMap(delegate().tailMap(fromKey, inclusive), mutex); } } - - private static final long serialVersionUID = 0; - } - - static BiMap biMap(BiMap bimap, @Nullable Object mutex) { - if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { - return bimap; - } - return new SynchronizedBiMap(bimap, mutex, null); - } - - @VisibleForTesting - static class SynchronizedBiMap extends SynchronizedMap implements BiMap, Serializable { - private transient Set valueSet; - private transient BiMap inverse; - - private SynchronizedBiMap(BiMap delegate, @Nullable Object mutex, @Nullable BiMap inverse) { - super(delegate, mutex); - this.inverse = inverse; - } - - @Override - BiMap delegate() { - return (BiMap) super.delegate(); - } - - @Override - public Set values() { - synchronized (mutex) { - if (valueSet == null) { - valueSet = set(delegate().values(), mutex); - } - return valueSet; - } - } - - @Override - public V forcePut(K key, V value) { - synchronized (mutex) { - return delegate().forcePut(key, value); - } - } - - @Override - public BiMap inverse() { - synchronized (mutex) { - if (inverse == null) { - inverse = new SynchronizedBiMap(delegate().inverse(), mutex, this); - } - return inverse; - } - } - - private static final long serialVersionUID = 0; - } - - private static class SynchronizedAsMap extends SynchronizedMap> { - transient Set>> asMapEntrySet; - transient Collection> asMapValues; - - SynchronizedAsMap(Map> delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - public Collection get(Object key) { - synchronized (mutex) { - Collection collection = super.get(key); - return (collection == null) ? null : typePreservingCollection(collection, mutex); - } - } - - @Override - public Set>> entrySet() { - synchronized (mutex) { - if (asMapEntrySet == null) { - asMapEntrySet = new SynchronizedAsMapEntries(delegate().entrySet(), mutex); - } - return asMapEntrySet; - } - } - - @Override - public Collection> values() { - synchronized (mutex) { - if (asMapValues == null) { - asMapValues = new SynchronizedAsMapValues(delegate().values(), mutex); - } - return asMapValues; - } - } - - @Override - public boolean containsValue(Object o) { - // values() and its contains() method are both synchronized. - return values().contains(o); - } - - private static final long serialVersionUID = 0; - } - - private static class SynchronizedAsMapValues extends SynchronizedCollection> { - SynchronizedAsMapValues(Collection> delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @Override - public Iterator> iterator() { - // Must be manually synchronized. - final Iterator> iterator = super.iterator(); - return new ForwardingIterator>() { - @Override - protected Iterator> delegate() { - return iterator; - } - - @Override - public Collection next() { - return typePreservingCollection(super.next(), mutex); - } - }; - } - - private static final long serialVersionUID = 0; } @GwtIncompatible("NavigableSet") @VisibleForTesting static class SynchronizedNavigableSet extends SynchronizedSortedSet implements NavigableSet { + private static final long serialVersionUID = 0; + + transient NavigableSet descendingSet; + SynchronizedNavigableSet(NavigableSet delegate, @Nullable Object mutex) { super(delegate, mutex); } - @Override - NavigableSet delegate() { - return (NavigableSet) super.delegate(); - } - @Override public E ceiling(E e) { synchronized (mutex) { @@ -1289,13 +1281,16 @@ final class Synchronized { } } + @Override + NavigableSet delegate() { + return (NavigableSet) super.delegate(); + } + @Override public Iterator descendingIterator() { return delegate().descendingIterator(); // manually synchronized } - transient NavigableSet descendingSet; - @Override public NavigableSet descendingSet() { synchronized (mutex) { @@ -1315,6 +1310,11 @@ final class Synchronized { } } + @Override + public SortedSet headSet(E toElement) { + return headSet(toElement, false); + } + @Override public NavigableSet headSet(E toElement, boolean inclusive) { synchronized (mutex) { @@ -1358,18 +1358,6 @@ final class Synchronized { } } - @Override - public NavigableSet tailSet(E fromElement, boolean inclusive) { - synchronized (mutex) { - return Synchronized.navigableSet(delegate().tailSet(fromElement, inclusive), mutex); - } - } - - @Override - public SortedSet headSet(E toElement) { - return headSet(toElement, false); - } - @Override public SortedSet subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); @@ -1380,271 +1368,56 @@ final class Synchronized { return tailSet(fromElement, true); } + @Override + public NavigableSet tailSet(E fromElement, boolean inclusive) { + synchronized (mutex) { + return Synchronized.navigableSet(delegate().tailSet(fromElement, inclusive), mutex); + } + } + } + + static class SynchronizedObject implements Serializable { + @GwtIncompatible("not needed in emulated source") private static final long serialVersionUID = 0; - } + final Object delegate; - @GwtIncompatible("NavigableSet") - static NavigableSet navigableSet(NavigableSet navigableSet, @Nullable Object mutex) { - return new SynchronizedNavigableSet(navigableSet, mutex); - } + final Object mutex; - @GwtIncompatible("NavigableSet") - static NavigableSet navigableSet(NavigableSet navigableSet) { - return navigableSet(navigableSet, null); - } - - @GwtIncompatible("NavigableMap") - static NavigableMap navigableMap(NavigableMap navigableMap) { - return navigableMap(navigableMap, null); - } - - @GwtIncompatible("NavigableMap") - static NavigableMap navigableMap(NavigableMap navigableMap, @Nullable Object mutex) { - return new SynchronizedNavigableMap(navigableMap, mutex); - } - - @GwtIncompatible("NavigableMap") - @VisibleForTesting - static class SynchronizedNavigableMap extends SynchronizedSortedMap implements NavigableMap { - - SynchronizedNavigableMap(NavigableMap delegate, @Nullable Object mutex) { - super(delegate, mutex); + SynchronizedObject(Object delegate, @Nullable Object mutex) { + this.delegate = checkNotNull(delegate); + this.mutex = (mutex == null) ? this : mutex; } - @Override - NavigableMap delegate() { - return (NavigableMap) super.delegate(); + // No equals and hashCode; see ForwardingObject for details. + + Object delegate() { + return delegate; } + // Serialization invokes writeObject only when it's private. + // The SynchronizedObject subclasses don't need a writeObject method since + // they don't contain any non-transient member variables, while the + // following writeObject() handles the SynchronizedObject members. + @Override - public Entry ceilingEntry(K key) { + public String toString() { synchronized (mutex) { - return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); + return delegate.toString(); } } - @Override - public K ceilingKey(K key) { + @GwtIncompatible("java.io.ObjectOutputStream") + private void writeObject(ObjectOutputStream stream) throws IOException { synchronized (mutex) { - return delegate().ceilingKey(key); + stream.defaultWriteObject(); } } - - transient NavigableSet descendingKeySet; - - @Override - public NavigableSet descendingKeySet() { - synchronized (mutex) { - if (descendingKeySet == null) { - return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); - } - return descendingKeySet; - } - } - - transient NavigableMap descendingMap; - - @Override - public NavigableMap descendingMap() { - synchronized (mutex) { - if (descendingMap == null) { - return descendingMap = navigableMap(delegate().descendingMap(), mutex); - } - return descendingMap; - } - } - - @Override - public Entry firstEntry() { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().firstEntry(), mutex); - } - } - - @Override - public Entry floorEntry(K key) { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); - } - } - - @Override - public K floorKey(K key) { - synchronized (mutex) { - return delegate().floorKey(key); - } - } - - @Override - public NavigableMap headMap(K toKey, boolean inclusive) { - synchronized (mutex) { - return navigableMap(delegate().headMap(toKey, inclusive), mutex); - } - } - - @Override - public Entry higherEntry(K key) { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); - } - } - - @Override - public K higherKey(K key) { - synchronized (mutex) { - return delegate().higherKey(key); - } - } - - @Override - public Entry lastEntry() { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().lastEntry(), mutex); - } - } - - @Override - public Entry lowerEntry(K key) { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); - } - } - - @Override - public K lowerKey(K key) { - synchronized (mutex) { - return delegate().lowerKey(key); - } - } - - @Override - public Set keySet() { - return navigableKeySet(); - } - - transient NavigableSet navigableKeySet; - - @Override - public NavigableSet navigableKeySet() { - synchronized (mutex) { - if (navigableKeySet == null) { - return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); - } - return navigableKeySet; - } - } - - @Override - public Entry pollFirstEntry() { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); - } - } - - @Override - public Entry pollLastEntry() { - synchronized (mutex) { - return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); - } - } - - @Override - public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { - synchronized (mutex) { - return navigableMap(delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); - } - } - - @Override - public NavigableMap tailMap(K fromKey, boolean inclusive) { - synchronized (mutex) { - return navigableMap(delegate().tailMap(fromKey, inclusive), mutex); - } - } - - @Override - public SortedMap headMap(K toKey) { - return headMap(toKey, false); - } - - @Override - public SortedMap subMap(K fromKey, K toKey) { - return subMap(fromKey, true, toKey, false); - } - - @Override - public SortedMap tailMap(K fromKey) { - return tailMap(fromKey, true); - } - - private static final long serialVersionUID = 0; - } - - @GwtIncompatible("works but is needed only for NavigableMap") - private static Entry nullableSynchronizedEntry(@Nullable Entry entry, @Nullable Object mutex) { - if (entry == null) { - return null; - } - return new SynchronizedEntry(entry, mutex); - } - - @GwtIncompatible("works but is needed only for NavigableMap") - private static class SynchronizedEntry extends SynchronizedObject implements Entry { - - SynchronizedEntry(Entry delegate, @Nullable Object mutex) { - super(delegate, mutex); - } - - @SuppressWarnings("unchecked") // guaranteed by the constructor - @Override - Entry delegate() { - return (Entry) super.delegate(); - } - - @Override - public boolean equals(Object obj) { - synchronized (mutex) { - return delegate().equals(obj); - } - } - - @Override - public int hashCode() { - synchronized (mutex) { - return delegate().hashCode(); - } - } - - @Override - public K getKey() { - synchronized (mutex) { - return delegate().getKey(); - } - } - - @Override - public V getValue() { - synchronized (mutex) { - return delegate().getValue(); - } - } - - @Override - public V setValue(V value) { - synchronized (mutex) { - return delegate().setValue(value); - } - } - - private static final long serialVersionUID = 0; - } - - static Queue queue(Queue queue, @Nullable Object mutex) { - return (queue instanceof SynchronizedQueue) ? queue : new SynchronizedQueue(queue, mutex); } private static class SynchronizedQueue extends SynchronizedCollection implements Queue { + private static final long serialVersionUID = 0; + SynchronizedQueue(Queue delegate, @Nullable Object mutex) { super(delegate, mutex); } @@ -1688,8 +1461,255 @@ final class Synchronized { return delegate().remove(); } } + } + + private static class SynchronizedRandomAccessList extends SynchronizedList implements RandomAccess { + private static final long serialVersionUID = 0; + + SynchronizedRandomAccessList(List list, @Nullable Object mutex) { + super(list, mutex); + } + } + + static class SynchronizedSet extends SynchronizedCollection implements Set { private static final long serialVersionUID = 0; + + SynchronizedSet(Set delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + Set delegate() { + return (Set) super.delegate(); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + synchronized (mutex) { + return delegate().equals(o); + } + } + + @Override + public int hashCode() { + synchronized (mutex) { + return delegate().hashCode(); + } + } + } + + private static class SynchronizedSetMultimap extends SynchronizedMultimap implements SetMultimap { + private static final long serialVersionUID = 0; + + transient Set> entrySet; + + SynchronizedSetMultimap(SetMultimap delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + SetMultimap delegate() { + return (SetMultimap) super.delegate(); + } + + @Override + public Set> entries() { + synchronized (mutex) { + if (entrySet == null) { + entrySet = set(delegate().entries(), mutex); + } + return entrySet; + } + } + + @Override + public Set get(K key) { + synchronized (mutex) { + return set(delegate().get(key), mutex); + } + } + + @Override + public Set removeAll(Object key) { + synchronized (mutex) { + return delegate().removeAll(key); // copy not synchronized + } + } + + @Override + public Set replaceValues(K key, Iterable values) { + synchronized (mutex) { + return delegate().replaceValues(key, values); // copy not synchronized + } + } + } + + static class SynchronizedSortedMap extends SynchronizedMap implements SortedMap { + + private static final long serialVersionUID = 0; + + SynchronizedSortedMap(SortedMap delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + public Comparator comparator() { + synchronized (mutex) { + return delegate().comparator(); + } + } + + @Override + SortedMap delegate() { + return (SortedMap) super.delegate(); + } + + @Override + public K firstKey() { + synchronized (mutex) { + return delegate().firstKey(); + } + } + + @Override + public SortedMap headMap(K toKey) { + synchronized (mutex) { + return sortedMap(delegate().headMap(toKey), mutex); + } + } + + @Override + public K lastKey() { + synchronized (mutex) { + return delegate().lastKey(); + } + } + + @Override + public SortedMap subMap(K fromKey, K toKey) { + synchronized (mutex) { + return sortedMap(delegate().subMap(fromKey, toKey), mutex); + } + } + + @Override + public SortedMap tailMap(K fromKey) { + synchronized (mutex) { + return sortedMap(delegate().tailMap(fromKey), mutex); + } + } + } + + static class SynchronizedSortedSet extends SynchronizedSet implements SortedSet { + private static final long serialVersionUID = 0; + + SynchronizedSortedSet(SortedSet delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + public Comparator comparator() { + synchronized (mutex) { + return delegate().comparator(); + } + } + + @Override + SortedSet delegate() { + return (SortedSet) super.delegate(); + } + + @Override + public E first() { + synchronized (mutex) { + return delegate().first(); + } + } + + @Override + public SortedSet headSet(E toElement) { + synchronized (mutex) { + return sortedSet(delegate().headSet(toElement), mutex); + } + } + + @Override + public E last() { + synchronized (mutex) { + return delegate().last(); + } + } + + @Override + public SortedSet subSet(E fromElement, E toElement) { + synchronized (mutex) { + return sortedSet(delegate().subSet(fromElement, toElement), mutex); + } + } + + @Override + public SortedSet tailSet(E fromElement) { + synchronized (mutex) { + return sortedSet(delegate().tailSet(fromElement), mutex); + } + } + } + + private static class SynchronizedSortedSetMultimap extends SynchronizedSetMultimap + implements SortedSetMultimap { + private static final long serialVersionUID = 0; + + SynchronizedSortedSetMultimap(SortedSetMultimap delegate, @Nullable Object mutex) { + super(delegate, mutex); + } + + @Override + SortedSetMultimap delegate() { + return (SortedSetMultimap) super.delegate(); + } + + @Override + public SortedSet get(K key) { + synchronized (mutex) { + return sortedSet(delegate().get(key), mutex); + } + } + + @Override + public SortedSet removeAll(Object key) { + synchronized (mutex) { + return delegate().removeAll(key); // copy not synchronized + } + } + + @Override + public SortedSet replaceValues(K key, Iterable values) { + synchronized (mutex) { + return delegate().replaceValues(key, values); // copy not synchronized + } + } + + @Override + public Comparator valueComparator() { + synchronized (mutex) { + return delegate().valueComparator(); + } + } + } + + static BiMap biMap(BiMap bimap, @Nullable Object mutex) { + if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { + return bimap; + } + return new SynchronizedBiMap(bimap, mutex, null); + } + + private static Collection collection(Collection collection, @Nullable Object mutex) { + return new SynchronizedCollection(collection, mutex); } @GwtIncompatible("Deque") @@ -1697,137 +1717,117 @@ final class Synchronized { return new SynchronizedDeque(deque, mutex); } - @GwtIncompatible("Deque") - private static final class SynchronizedDeque extends SynchronizedQueue implements Deque { + private static List list(List list, @Nullable Object mutex) { + return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList(list, mutex) + : new SynchronizedList(list, mutex); + } - SynchronizedDeque(Deque delegate, @Nullable Object mutex) { - super(delegate, mutex); + static ListMultimap listMultimap(ListMultimap multimap, @Nullable Object mutex) { + if (multimap instanceof SynchronizedListMultimap || multimap instanceof ImmutableListMultimap) { + return multimap; } + return new SynchronizedListMultimap(multimap, mutex); + } - @Override - Deque delegate() { - return (Deque) super.delegate(); + @VisibleForTesting + static Map map(Map map, @Nullable Object mutex) { + return new SynchronizedMap(map, mutex); + } + + static Multimap multimap(Multimap multimap, @Nullable Object mutex) { + if (multimap instanceof SynchronizedMultimap || multimap instanceof ImmutableMultimap) { + return multimap; } + return new SynchronizedMultimap(multimap, mutex); + } - @Override - public void addFirst(E e) { - synchronized (mutex) { - delegate().addFirst(e); - } + static Multiset multiset(Multiset multiset, @Nullable Object mutex) { + if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { + return multiset; } + return new SynchronizedMultiset(multiset, mutex); + } - @Override - public void addLast(E e) { - synchronized (mutex) { - delegate().addLast(e); - } + @GwtIncompatible("NavigableMap") + static NavigableMap navigableMap(NavigableMap navigableMap) { + return navigableMap(navigableMap, null); + } + + @GwtIncompatible("NavigableMap") + static NavigableMap navigableMap(NavigableMap navigableMap, @Nullable Object mutex) { + return new SynchronizedNavigableMap(navigableMap, mutex); + } + + @GwtIncompatible("NavigableSet") + static NavigableSet navigableSet(NavigableSet navigableSet) { + return navigableSet(navigableSet, null); + } + + @GwtIncompatible("NavigableSet") + static NavigableSet navigableSet(NavigableSet navigableSet, @Nullable Object mutex) { + return new SynchronizedNavigableSet(navigableSet, mutex); + } + + @GwtIncompatible("works but is needed only for NavigableMap") + private static Entry nullableSynchronizedEntry(@Nullable Entry entry, @Nullable Object mutex) { + if (entry == null) { + return null; } + return new SynchronizedEntry(entry, mutex); + } - @Override - public boolean offerFirst(E e) { - synchronized (mutex) { - return delegate().offerFirst(e); - } + static Queue queue(Queue queue, @Nullable Object mutex) { + return (queue instanceof SynchronizedQueue) ? queue : new SynchronizedQueue(queue, mutex); + } + + @VisibleForTesting + static Set set(Set set, @Nullable Object mutex) { + return new SynchronizedSet(set, mutex); + } + + static SetMultimap setMultimap(SetMultimap multimap, @Nullable Object mutex) { + if (multimap instanceof SynchronizedSetMultimap || multimap instanceof ImmutableSetMultimap) { + return multimap; } + return new SynchronizedSetMultimap(multimap, mutex); + } - @Override - public boolean offerLast(E e) { - synchronized (mutex) { - return delegate().offerLast(e); - } + static SortedMap sortedMap(SortedMap sortedMap, @Nullable Object mutex) { + return new SynchronizedSortedMap(sortedMap, mutex); + } + + private static SortedSet sortedSet(SortedSet set, @Nullable Object mutex) { + return new SynchronizedSortedSet(set, mutex); + } + + static SortedSetMultimap sortedSetMultimap(SortedSetMultimap multimap, @Nullable Object mutex) { + if (multimap instanceof SynchronizedSortedSetMultimap) { + return multimap; } + return new SynchronizedSortedSetMultimap(multimap, mutex); + } - @Override - public E removeFirst() { - synchronized (mutex) { - return delegate().removeFirst(); - } + private static Collection typePreservingCollection(Collection collection, @Nullable Object mutex) { + if (collection instanceof SortedSet) { + return sortedSet((SortedSet) collection, mutex); } - - @Override - public E removeLast() { - synchronized (mutex) { - return delegate().removeLast(); - } + if (collection instanceof Set) { + return set((Set) collection, mutex); } - - @Override - public E pollFirst() { - synchronized (mutex) { - return delegate().pollFirst(); - } + if (collection instanceof List) { + return list((List) collection, mutex); } + return collection(collection, mutex); + } - @Override - public E pollLast() { - synchronized (mutex) { - return delegate().pollLast(); - } + private static Set typePreservingSet(Set set, @Nullable Object mutex) { + if (set instanceof SortedSet) { + return sortedSet((SortedSet) set, mutex); + } else { + return set(set, mutex); } + } - @Override - public E getFirst() { - synchronized (mutex) { - return delegate().getFirst(); - } - } - - @Override - public E getLast() { - synchronized (mutex) { - return delegate().getLast(); - } - } - - @Override - public E peekFirst() { - synchronized (mutex) { - return delegate().peekFirst(); - } - } - - @Override - public E peekLast() { - synchronized (mutex) { - return delegate().peekLast(); - } - } - - @Override - public boolean removeFirstOccurrence(Object o) { - synchronized (mutex) { - return delegate().removeFirstOccurrence(o); - } - } - - @Override - public boolean removeLastOccurrence(Object o) { - synchronized (mutex) { - return delegate().removeLastOccurrence(o); - } - } - - @Override - public void push(E e) { - synchronized (mutex) { - delegate().push(e); - } - } - - @Override - public E pop() { - synchronized (mutex) { - return delegate().pop(); - } - } - - @Override - public Iterator descendingIterator() { - synchronized (mutex) { - return delegate().descendingIterator(); - } - } - - private static final long serialVersionUID = 0; + private Synchronized() { } } diff --git a/src/main/java/com/google/common/collect/Table.java b/src/main/java/com/google/common/collect/Table.java index 1430d72b..fde30a93 100644 --- a/src/main/java/com/google/common/collect/Table.java +++ b/src/main/java/com/google/common/collect/Table.java @@ -64,6 +64,96 @@ public interface Table { // Accessors + /** + * Row key / column key / value triplet corresponding to a mapping in a table. + * + * @since 7.0 + */ + interface Cell { + /** + * Compares the specified object with this cell for equality. Two cells are + * equal when they have equal row keys, column keys, and values. + */ + @Override + boolean equals(@Nullable Object obj); + + /** + * Returns the column key of this cell. + */ + C getColumnKey(); + + /** + * Returns the row key of this cell. + */ + R getRowKey(); + + /** + * Returns the value of this cell. + */ + V getValue(); + + /** + * Returns the hash code of this cell. + * + *

+ * The hash code of a table cell is equal to + * {@link Objects#hashCode}{@code (e.getRowKey(), e.getColumnKey(), e.getValue())}. + */ + @Override + int hashCode(); + } + + /** + * Returns a set of all row key / column key / value triplets. Changes to the + * returned set will update the underlying table, and vice versa. The cell set + * does not support the {@code add} or {@code addAll} methods. + * + * @return set of table cells consisting of row key / column key / value + * triplets + */ + Set> cellSet(); + + /** Removes all mappings from the table. */ + void clear(); + + /** + * Returns a view of all mappings that have the given column key. For each row + * key / column key / value mapping in the table with that column key, the + * returned map associates the row key with the value. If no mappings in the + * table have the provided column key, an empty map is returned. + * + *

+ * Changes to the returned map will update the underlying table, and vice versa. + * + * @param columnKey key of column to search for in the table + * @return the corresponding map from row keys to values + */ + Map column(C columnKey); + + /** + * Returns a set of column keys that have one or more values in the table. + * Changes to the set will update the underlying table, and vice versa. + * + * @return set of column keys + */ + Set columnKeySet(); + + /** + * Returns a view that associates each column key with the corresponding map + * from row keys to values. Changes to the returned map will update this table. + * The returned map does not support {@code put()} or {@code putAll()}, or + * {@code setValue()} on its entries. + * + *

+ * In contrast, the maps returned by {@code columnMap().get()} have the same + * behavior as those returned by {@link #column}. Those maps may support + * {@code setValue()}, {@code put()}, and {@code putAll()}. + * + * @return a map view from each column key to a secondary map from row keys to + * values + */ + Map> columnMap(); + /** * Returns {@code true} if the table contains a mapping with the specified row * and column keys. @@ -73,14 +163,6 @@ public interface Table { */ boolean contains(@Nullable Object rowKey, @Nullable Object columnKey); - /** - * Returns {@code true} if the table contains a mapping with the specified row - * key. - * - * @param rowKey key of row to search for - */ - boolean containsRow(@Nullable Object rowKey); - /** * Returns {@code true} if the table contains a mapping with the specified * column. @@ -89,6 +171,16 @@ public interface Table { */ boolean containsColumn(@Nullable Object columnKey); + /** + * Returns {@code true} if the table contains a mapping with the specified row + * key. + * + * @param rowKey key of row to search for + */ + boolean containsRow(@Nullable Object rowKey); + + // Mutators + /** * Returns {@code true} if the table contains a mapping with the specified * value. @@ -97,6 +189,13 @@ public interface Table { */ boolean containsValue(@Nullable Object value); + /** + * Compares the specified object with this table for equality. Two tables are + * equal when their cell views, as returned by {@link #cellSet}, are equal. + */ + @Override + boolean equals(@Nullable Object obj); + /** * Returns the value corresponding to the given row and column keys, or * {@code null} if no such mapping exists. @@ -106,21 +205,6 @@ public interface Table { */ V get(@Nullable Object rowKey, @Nullable Object columnKey); - /** Returns {@code true} if the table contains no mappings. */ - boolean isEmpty(); - - /** - * Returns the number of row key / column key / value mappings in the table. - */ - int size(); - - /** - * Compares the specified object with this table for equality. Two tables are - * equal when their cell views, as returned by {@link #cellSet}, are equal. - */ - @Override - boolean equals(@Nullable Object obj); - /** * Returns the hash code for this table. The hash code of a table is defined as * the hash code of its cell view, as returned by {@link #cellSet}. @@ -128,10 +212,10 @@ public interface Table { @Override int hashCode(); - // Mutators + // Views - /** Removes all mappings from the table. */ - void clear(); + /** Returns {@code true} if the table contains no mappings. */ + boolean isEmpty(); /** * Associates the specified value with the specified keys. If the table already @@ -165,8 +249,6 @@ public interface Table { */ V remove(@Nullable Object rowKey, @Nullable Object columnKey); - // Views - /** * Returns a view of all mappings that have the given row key. For each row key * / column key / value mapping in the table with that row key, the returned map @@ -181,30 +263,6 @@ public interface Table { */ Map row(R rowKey); - /** - * Returns a view of all mappings that have the given column key. For each row - * key / column key / value mapping in the table with that column key, the - * returned map associates the row key with the value. If no mappings in the - * table have the provided column key, an empty map is returned. - * - *

- * Changes to the returned map will update the underlying table, and vice versa. - * - * @param columnKey key of column to search for in the table - * @return the corresponding map from row keys to values - */ - Map column(C columnKey); - - /** - * Returns a set of all row key / column key / value triplets. Changes to the - * returned set will update the underlying table, and vice versa. The cell set - * does not support the {@code add} or {@code addAll} methods. - * - * @return set of table cells consisting of row key / column key / value - * triplets - */ - Set> cellSet(); - /** * Returns a set of row keys that have one or more values in the table. Changes * to the set will update the underlying table, and vice versa. @@ -213,22 +271,6 @@ public interface Table { */ Set rowKeySet(); - /** - * Returns a set of column keys that have one or more values in the table. - * Changes to the set will update the underlying table, and vice versa. - * - * @return set of column keys - */ - Set columnKeySet(); - - /** - * Returns a collection of all values, which may contain duplicates. Changes to - * the returned collection will update the underlying table, and vice versa. - * - * @return collection of values - */ - Collection values(); - /** * Returns a view that associates each row key with the corresponding map from * column keys to values. Changes to the returned map will update this table. @@ -246,57 +288,15 @@ public interface Table { Map> rowMap(); /** - * Returns a view that associates each column key with the corresponding map - * from row keys to values. Changes to the returned map will update this table. - * The returned map does not support {@code put()} or {@code putAll()}, or - * {@code setValue()} on its entries. - * - *

- * In contrast, the maps returned by {@code columnMap().get()} have the same - * behavior as those returned by {@link #column}. Those maps may support - * {@code setValue()}, {@code put()}, and {@code putAll()}. - * - * @return a map view from each column key to a secondary map from row keys to - * values + * Returns the number of row key / column key / value mappings in the table. */ - Map> columnMap(); + int size(); /** - * Row key / column key / value triplet corresponding to a mapping in a table. + * Returns a collection of all values, which may contain duplicates. Changes to + * the returned collection will update the underlying table, and vice versa. * - * @since 7.0 + * @return collection of values */ - interface Cell { - /** - * Returns the row key of this cell. - */ - R getRowKey(); - - /** - * Returns the column key of this cell. - */ - C getColumnKey(); - - /** - * Returns the value of this cell. - */ - V getValue(); - - /** - * Compares the specified object with this cell for equality. Two cells are - * equal when they have equal row keys, column keys, and values. - */ - @Override - boolean equals(@Nullable Object obj); - - /** - * Returns the hash code of this cell. - * - *

- * The hash code of a table cell is equal to - * {@link Objects#hashCode}{@code (e.getRowKey(), e.getColumnKey(), e.getValue())}. - */ - @Override - int hashCode(); - } + Collection values(); } diff --git a/src/main/java/com/google/common/collect/Tables.java b/src/main/java/com/google/common/collect/Tables.java index 23954a22..8613ac3b 100644 --- a/src/main/java/com/google/common/collect/Tables.java +++ b/src/main/java/com/google/common/collect/Tables.java @@ -51,52 +51,6 @@ import com.google.common.collect.Table.Cell; */ @GwtCompatible public final class Tables { - private Tables() { - } - - /** - * Returns an immutable cell with the specified row key, column key, and value. - * - *

- * The returned cell is serializable. - * - * @param rowKey the row key to be associated with the returned cell - * @param columnKey the column key to be associated with the returned cell - * @param value the value to be associated with the returned cell - */ - public static Cell immutableCell(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { - return new ImmutableCell(rowKey, columnKey, value); - } - - static final class ImmutableCell extends AbstractCell implements Serializable { - private final R rowKey; - private final C columnKey; - private final V value; - - ImmutableCell(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { - this.rowKey = rowKey; - this.columnKey = columnKey; - this.value = value; - } - - @Override - public R getRowKey() { - return rowKey; - } - - @Override - public C getColumnKey() { - return columnKey; - } - - @Override - public V getValue() { - return value; - } - - private static final long serialVersionUID = 0; - } - abstract static class AbstractCell implements Cell { // needed for serialization AbstractCell() { @@ -127,33 +81,164 @@ public final class Tables { } } - /** - * Creates a transposed view of a given table that flips its row and column - * keys. In other words, calling {@code get(columnKey, rowKey)} on the generated - * table always returns the same value as calling {@code - * get(rowKey, columnKey)} on the original table. Updating the original table - * changes the contents of the transposed table and vice versa. - * - *

- * The returned table supports update operations as long as the input table - * supports the analogous operation with swapped rows and columns. For example, - * in a {@link HashBasedTable} instance, {@code - * rowKeySet().iterator()} supports {@code remove()} but {@code - * columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, - * it's the other way around. - */ - public static Table transpose(Table table) { - return (table instanceof TransposeTable) ? ((TransposeTable) table).original - : new TransposeTable(table); + static final class ImmutableCell extends AbstractCell implements Serializable { + private static final long serialVersionUID = 0; + private final R rowKey; + private final C columnKey; + + private final V value; + + ImmutableCell(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { + this.rowKey = rowKey; + this.columnKey = columnKey; + this.value = value; + } + + @Override + public C getColumnKey() { + return columnKey; + } + + @Override + public R getRowKey() { + return rowKey; + } + + @Override + public V getValue() { + return value; + } + } + + private static class TransformedTable extends AbstractTable { + final Table fromTable; + final Function function; + + TransformedTable(Table fromTable, Function function) { + this.fromTable = checkNotNull(fromTable); + this.function = checkNotNull(function); + } + + Function, Cell> cellFunction() { + return new Function, Cell>() { + @Override + public Cell apply(Cell cell) { + return immutableCell(cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue())); + } + }; + } + + @Override + Iterator> cellIterator() { + return Iterators.transform(fromTable.cellSet().iterator(), cellFunction()); + } + + @Override + public void clear() { + fromTable.clear(); + } + + @Override + public Map column(C columnKey) { + return Maps.transformValues(fromTable.column(columnKey), function); + } + + @Override + public Set columnKeySet() { + return fromTable.columnKeySet(); + } + + @Override + public Map> columnMap() { + Function, Map> columnFunction = new Function, Map>() { + @Override + public Map apply(Map column) { + return Maps.transformValues(column, function); + } + }; + return Maps.transformValues(fromTable.columnMap(), columnFunction); + } + + @Override + public boolean contains(Object rowKey, Object columnKey) { + return fromTable.contains(rowKey, columnKey); + } + + @Override + Collection createValues() { + return Collections2.transform(fromTable.values(), function); + } + + @Override + public V2 get(Object rowKey, Object columnKey) { + // The function is passed a null input only when the table contains a null + // value. + return contains(rowKey, columnKey) ? function.apply(fromTable.get(rowKey, columnKey)) : null; + } + + @Override + public V2 put(R rowKey, C columnKey, V2 value) { + throw new UnsupportedOperationException(); + } + + @Override + public void putAll(Table table) { + throw new UnsupportedOperationException(); + } + + @Override + public V2 remove(Object rowKey, Object columnKey) { + return contains(rowKey, columnKey) ? function.apply(fromTable.remove(rowKey, columnKey)) : null; + } + + @Override + public Map row(R rowKey) { + return Maps.transformValues(fromTable.row(rowKey), function); + } + + @Override + public Set rowKeySet() { + return fromTable.rowKeySet(); + } + + @Override + public Map> rowMap() { + Function, Map> rowFunction = new Function, Map>() { + @Override + public Map apply(Map row) { + return Maps.transformValues(row, function); + } + }; + return Maps.transformValues(fromTable.rowMap(), rowFunction); + } + + @Override + public int size() { + return fromTable.size(); + } } private static class TransposeTable extends AbstractTable { + // Will cast TRANSPOSE_CELL to a type that always succeeds + private static final Function, Cell> TRANSPOSE_CELL = new Function, Cell>() { + @Override + public Cell apply(Cell cell) { + return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue()); + } + }; + final Table original; TransposeTable(Table original) { this.original = checkNotNull(original); } + @SuppressWarnings("unchecked") + @Override + Iterator> cellIterator() { + return Iterators.transform(original.cellSet().iterator(), (Function) TRANSPOSE_CELL); + } + @Override public void clear() { original.clear(); @@ -238,20 +323,142 @@ public final class Tables { public Collection values() { return original.values(); } + } - // Will cast TRANSPOSE_CELL to a type that always succeeds - private static final Function, Cell> TRANSPOSE_CELL = new Function, Cell>() { - @Override - public Cell apply(Cell cell) { - return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue()); - } - }; + static final class UnmodifiableRowSortedMap extends UnmodifiableTable + implements RowSortedTable { - @SuppressWarnings("unchecked") - @Override - Iterator> cellIterator() { - return Iterators.transform(original.cellSet().iterator(), (Function) TRANSPOSE_CELL); + private static final long serialVersionUID = 0; + + public UnmodifiableRowSortedMap(RowSortedTable delegate) { + super(delegate); } + + @Override + protected RowSortedTable delegate() { + return (RowSortedTable) super.delegate(); + } + + @Override + public SortedSet rowKeySet() { + return Collections.unmodifiableSortedSet(delegate().rowKeySet()); + } + + @Override + public SortedMap> rowMap() { + Function, Map> wrapper = unmodifiableWrapper(); + return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper)); + } + } + + private static class UnmodifiableTable extends ForwardingTable implements Serializable { + private static final long serialVersionUID = 0; + + final Table delegate; + + UnmodifiableTable(Table delegate) { + this.delegate = checkNotNull(delegate); + } + + @Override + public Set> cellSet() { + return Collections.unmodifiableSet(super.cellSet()); + } + + @Override + public void clear() { + throw new UnsupportedOperationException(); + } + + @Override + public Map column(@Nullable C columnKey) { + return Collections.unmodifiableMap(super.column(columnKey)); + } + + @Override + public Set columnKeySet() { + return Collections.unmodifiableSet(super.columnKeySet()); + } + + @Override + public Map> columnMap() { + Function, Map> wrapper = unmodifiableWrapper(); + return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper)); + } + + @SuppressWarnings("unchecked") // safe, covariant cast + @Override + protected Table delegate() { + return (Table) delegate; + } + + @Override + public V put(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { + throw new UnsupportedOperationException(); + } + + @Override + public void putAll(Table table) { + throw new UnsupportedOperationException(); + } + + @Override + public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { + throw new UnsupportedOperationException(); + } + + @Override + public Map row(@Nullable R rowKey) { + return Collections.unmodifiableMap(super.row(rowKey)); + } + + @Override + public Set rowKeySet() { + return Collections.unmodifiableSet(super.rowKeySet()); + } + + @Override + public Map> rowMap() { + Function, Map> wrapper = unmodifiableWrapper(); + return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper)); + } + + @Override + public Collection values() { + return Collections.unmodifiableCollection(super.values()); + } + } + + private static final Function, ? extends Map> UNMODIFIABLE_WRAPPER = new Function, Map>() { + @Override + public Map apply(Map input) { + return Collections.unmodifiableMap(input); + } + }; + + static boolean equalsImpl(Table table, @Nullable Object obj) { + if (obj == table) { + return true; + } else if (obj instanceof Table) { + Table that = (Table) obj; + return table.cellSet().equals(that.cellSet()); + } else { + return false; + } + } + + /** + * Returns an immutable cell with the specified row key, column key, and value. + * + *

+ * The returned cell is serializable. + * + * @param rowKey the row key to be associated with the returned cell + * @param columnKey the column key to be associated with the returned cell + * @param value the value to be associated with the returned cell + */ + public static Cell immutableCell(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { + return new ImmutableCell(rowKey, columnKey, value); } /** @@ -345,213 +552,24 @@ public final class Tables { return new TransformedTable(fromTable, function); } - private static class TransformedTable extends AbstractTable { - final Table fromTable; - final Function function; - - TransformedTable(Table fromTable, Function function) { - this.fromTable = checkNotNull(fromTable); - this.function = checkNotNull(function); - } - - @Override - public boolean contains(Object rowKey, Object columnKey) { - return fromTable.contains(rowKey, columnKey); - } - - @Override - public V2 get(Object rowKey, Object columnKey) { - // The function is passed a null input only when the table contains a null - // value. - return contains(rowKey, columnKey) ? function.apply(fromTable.get(rowKey, columnKey)) : null; - } - - @Override - public int size() { - return fromTable.size(); - } - - @Override - public void clear() { - fromTable.clear(); - } - - @Override - public V2 put(R rowKey, C columnKey, V2 value) { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(Table table) { - throw new UnsupportedOperationException(); - } - - @Override - public V2 remove(Object rowKey, Object columnKey) { - return contains(rowKey, columnKey) ? function.apply(fromTable.remove(rowKey, columnKey)) : null; - } - - @Override - public Map row(R rowKey) { - return Maps.transformValues(fromTable.row(rowKey), function); - } - - @Override - public Map column(C columnKey) { - return Maps.transformValues(fromTable.column(columnKey), function); - } - - Function, Cell> cellFunction() { - return new Function, Cell>() { - @Override - public Cell apply(Cell cell) { - return immutableCell(cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue())); - } - }; - } - - @Override - Iterator> cellIterator() { - return Iterators.transform(fromTable.cellSet().iterator(), cellFunction()); - } - - @Override - public Set rowKeySet() { - return fromTable.rowKeySet(); - } - - @Override - public Set columnKeySet() { - return fromTable.columnKeySet(); - } - - @Override - Collection createValues() { - return Collections2.transform(fromTable.values(), function); - } - - @Override - public Map> rowMap() { - Function, Map> rowFunction = new Function, Map>() { - @Override - public Map apply(Map row) { - return Maps.transformValues(row, function); - } - }; - return Maps.transformValues(fromTable.rowMap(), rowFunction); - } - - @Override - public Map> columnMap() { - Function, Map> columnFunction = new Function, Map>() { - @Override - public Map apply(Map column) { - return Maps.transformValues(column, function); - } - }; - return Maps.transformValues(fromTable.columnMap(), columnFunction); - } - } - /** - * Returns an unmodifiable view of the specified table. This method allows - * modules to provide users with "read-only" access to internal tables. Query - * operations on the returned table "read through" to the specified table, and - * attempts to modify the returned table, whether direct or via its collection - * views, result in an {@code UnsupportedOperationException}. - * - *

- * The returned table will be serializable if the specified table is - * serializable. + * Creates a transposed view of a given table that flips its row and column + * keys. In other words, calling {@code get(columnKey, rowKey)} on the generated + * table always returns the same value as calling {@code + * get(rowKey, columnKey)} on the original table. Updating the original table + * changes the contents of the transposed table and vice versa. * *

- * Consider using an {@link ImmutableTable}, which is guaranteed never to - * change. - * - * @param table the table for which an unmodifiable view is to be returned - * @return an unmodifiable view of the specified table - * @since 11.0 + * The returned table supports update operations as long as the input table + * supports the analogous operation with swapped rows and columns. For example, + * in a {@link HashBasedTable} instance, {@code + * rowKeySet().iterator()} supports {@code remove()} but {@code + * columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, + * it's the other way around. */ - public static Table unmodifiableTable(Table table) { - return new UnmodifiableTable(table); - } - - private static class UnmodifiableTable extends ForwardingTable implements Serializable { - final Table delegate; - - UnmodifiableTable(Table delegate) { - this.delegate = checkNotNull(delegate); - } - - @SuppressWarnings("unchecked") // safe, covariant cast - @Override - protected Table delegate() { - return (Table) delegate; - } - - @Override - public Set> cellSet() { - return Collections.unmodifiableSet(super.cellSet()); - } - - @Override - public void clear() { - throw new UnsupportedOperationException(); - } - - @Override - public Map column(@Nullable C columnKey) { - return Collections.unmodifiableMap(super.column(columnKey)); - } - - @Override - public Set columnKeySet() { - return Collections.unmodifiableSet(super.columnKeySet()); - } - - @Override - public Map> columnMap() { - Function, Map> wrapper = unmodifiableWrapper(); - return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper)); - } - - @Override - public V put(@Nullable R rowKey, @Nullable C columnKey, @Nullable V value) { - throw new UnsupportedOperationException(); - } - - @Override - public void putAll(Table table) { - throw new UnsupportedOperationException(); - } - - @Override - public V remove(@Nullable Object rowKey, @Nullable Object columnKey) { - throw new UnsupportedOperationException(); - } - - @Override - public Map row(@Nullable R rowKey) { - return Collections.unmodifiableMap(super.row(rowKey)); - } - - @Override - public Set rowKeySet() { - return Collections.unmodifiableSet(super.rowKeySet()); - } - - @Override - public Map> rowMap() { - Function, Map> wrapper = unmodifiableWrapper(); - return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper)); - } - - @Override - public Collection values() { - return Collections.unmodifiableCollection(super.values()); - } - - private static final long serialVersionUID = 0; + public static Table transpose(Table table) { + return (table instanceof TransposeTable) ? ((TransposeTable) table).original + : new TransposeTable(table); } /** @@ -582,30 +600,27 @@ public final class Tables { return new UnmodifiableRowSortedMap(table); } - static final class UnmodifiableRowSortedMap extends UnmodifiableTable - implements RowSortedTable { - - public UnmodifiableRowSortedMap(RowSortedTable delegate) { - super(delegate); - } - - @Override - protected RowSortedTable delegate() { - return (RowSortedTable) super.delegate(); - } - - @Override - public SortedMap> rowMap() { - Function, Map> wrapper = unmodifiableWrapper(); - return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper)); - } - - @Override - public SortedSet rowKeySet() { - return Collections.unmodifiableSortedSet(delegate().rowKeySet()); - } - - private static final long serialVersionUID = 0; + /** + * Returns an unmodifiable view of the specified table. This method allows + * modules to provide users with "read-only" access to internal tables. Query + * operations on the returned table "read through" to the specified table, and + * attempts to modify the returned table, whether direct or via its collection + * views, result in an {@code UnsupportedOperationException}. + * + *

+ * The returned table will be serializable if the specified table is + * serializable. + * + *

+ * Consider using an {@link ImmutableTable}, which is guaranteed never to + * change. + * + * @param table the table for which an unmodifiable view is to be returned + * @return an unmodifiable view of the specified table + * @since 11.0 + */ + public static Table unmodifiableTable(Table table) { + return new UnmodifiableTable(table); } @SuppressWarnings("unchecked") @@ -613,21 +628,6 @@ public final class Tables { return (Function) UNMODIFIABLE_WRAPPER; } - private static final Function, ? extends Map> UNMODIFIABLE_WRAPPER = new Function, Map>() { - @Override - public Map apply(Map input) { - return Collections.unmodifiableMap(input); - } - }; - - static boolean equalsImpl(Table table, @Nullable Object obj) { - if (obj == table) { - return true; - } else if (obj instanceof Table) { - Table that = (Table) obj; - return table.cellSet().equals(that.cellSet()); - } else { - return false; - } + private Tables() { } } diff --git a/src/main/java/com/google/common/collect/TransformedIterator.java b/src/main/java/com/google/common/collect/TransformedIterator.java index 55a6ab26..3389a583 100644 --- a/src/main/java/com/google/common/collect/TransformedIterator.java +++ b/src/main/java/com/google/common/collect/TransformedIterator.java @@ -36,8 +36,6 @@ abstract class TransformedIterator implements Iterator { this.backingIterator = checkNotNull(backingIterator); } - abstract T transform(F from); - @Override public final boolean hasNext() { return backingIterator.hasNext(); @@ -52,4 +50,6 @@ abstract class TransformedIterator implements Iterator { public final void remove() { backingIterator.remove(); } + + abstract T transform(F from); } diff --git a/src/main/java/com/google/common/collect/TransformedListIterator.java b/src/main/java/com/google/common/collect/TransformedListIterator.java index b84d0a57..80d326ad 100644 --- a/src/main/java/com/google/common/collect/TransformedListIterator.java +++ b/src/main/java/com/google/common/collect/TransformedListIterator.java @@ -34,6 +34,11 @@ abstract class TransformedListIterator extends TransformedIterator i super(backingIterator); } + @Override + public void add(T element) { + throw new UnsupportedOperationException(); + } + private ListIterator backingIterator() { return Iterators.cast(backingIterator); } @@ -44,13 +49,13 @@ abstract class TransformedListIterator extends TransformedIterator i } @Override - public final T previous() { - return transform(backingIterator().previous()); + public final int nextIndex() { + return backingIterator().nextIndex(); } @Override - public final int nextIndex() { - return backingIterator().nextIndex(); + public final T previous() { + return transform(backingIterator().previous()); } @Override @@ -62,9 +67,4 @@ abstract class TransformedListIterator extends TransformedIterator i public void set(T element) { throw new UnsupportedOperationException(); } - - @Override - public void add(T element) { - throw new UnsupportedOperationException(); - } } diff --git a/src/main/java/com/google/common/collect/TreeBasedTable.java b/src/main/java/com/google/common/collect/TreeBasedTable.java index 999acd7b..33a2098f 100644 --- a/src/main/java/com/google/common/collect/TreeBasedTable.java +++ b/src/main/java/com/google/common/collect/TreeBasedTable.java @@ -83,9 +83,9 @@ import com.google.common.base.Supplier; @GwtCompatible(serializable = true) @Beta public class TreeBasedTable extends StandardRowSortedTable { - private final Comparator columnComparator; - private static class Factory implements Supplier>, Serializable { + private static final long serialVersionUID = 0; + final Comparator comparator; Factory(Comparator comparator) { @@ -96,10 +96,139 @@ public class TreeBasedTable extends StandardRowSortedTable { public TreeMap get() { return new TreeMap(comparator); } - - private static final long serialVersionUID = 0; } + private class TreeRow extends Row implements SortedMap { + @Nullable + final C lowerBound; + @Nullable + final C upperBound; + + transient SortedMap wholeRow; + + TreeRow(R rowKey) { + this(rowKey, null, null); + } + + TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) { + super(rowKey); + this.lowerBound = lowerBound; + this.upperBound = upperBound; + checkArgument(lowerBound == null || upperBound == null || compare(lowerBound, upperBound) <= 0); + } + + @Override + SortedMap backingRowMap() { + return (SortedMap) super.backingRowMap(); + } + + @Override + public Comparator comparator() { + return columnComparator(); + } + + int compare(Object a, Object b) { + // pretend we can compare anything + @SuppressWarnings({ "rawtypes", "unchecked" }) + Comparator cmp = (Comparator) comparator(); + return cmp.compare(a, b); + } + + @Override + SortedMap computeBackingRowMap() { + SortedMap map = wholeRow(); + if (map != null) { + if (lowerBound != null) { + map = map.tailMap(lowerBound); + } + if (upperBound != null) { + map = map.headMap(upperBound); + } + return map; + } + return null; + } + + @Override + public boolean containsKey(Object key) { + return rangeContains(key) && super.containsKey(key); + } + + @Override + public C firstKey() { + SortedMap backing = backingRowMap(); + if (backing == null) { + throw new NoSuchElementException(); + } + return backingRowMap().firstKey(); + } + + @Override + public SortedMap headMap(C toKey) { + checkArgument(rangeContains(checkNotNull(toKey))); + return new TreeRow(rowKey, lowerBound, toKey); + } + + @Override + public SortedSet keySet() { + return new Maps.SortedKeySet(this); + } + + @Override + public C lastKey() { + SortedMap backing = backingRowMap(); + if (backing == null) { + throw new NoSuchElementException(); + } + return backingRowMap().lastKey(); + } + + @Override + void maintainEmptyInvariant() { + if (wholeRow() != null && wholeRow.isEmpty()) { + backingMap.remove(rowKey); + wholeRow = null; + backingRowMap = null; + } + } + + @Override + public V put(C key, V value) { + checkArgument(rangeContains(checkNotNull(key))); + return super.put(key, value); + } + + boolean rangeContains(@Nullable Object o) { + return o != null && (lowerBound == null || compare(lowerBound, o) <= 0) + && (upperBound == null || compare(upperBound, o) > 0); + } + + @Override + public SortedMap subMap(C fromKey, C toKey) { + checkArgument(rangeContains(checkNotNull(fromKey)) && rangeContains(checkNotNull(toKey))); + return new TreeRow(rowKey, fromKey, toKey); + } + + @Override + public SortedMap tailMap(C fromKey) { + checkArgument(rangeContains(checkNotNull(fromKey))); + return new TreeRow(rowKey, fromKey, upperBound); + } + + /* + * If the row was previously empty, we check if there's a new row here every + * time we're queried. + */ + SortedMap wholeRow() { + if (wholeRow == null || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) { + wholeRow = (SortedMap) backingMap.get(rowKey); + } + return wholeRow; + } + } + + private static final long serialVersionUID = 0; + /** * Creates an empty {@code TreeBasedTable} that uses the natural orderings of * both row and column keys. @@ -138,20 +267,16 @@ public class TreeBasedTable extends StandardRowSortedTable { return result; } + // TODO(jlevy): Move to StandardRowSortedTable? + + private final Comparator columnComparator; + TreeBasedTable(Comparator rowComparator, Comparator columnComparator) { super(new TreeMap>(rowComparator), new Factory(columnComparator)); this.columnComparator = columnComparator; } - // TODO(jlevy): Move to StandardRowSortedTable? - - /** - * Returns the comparator that orders the rows. With natural ordering, - * {@link Ordering#natural()} is returned. - */ - public Comparator rowComparator() { - return rowKeySet().comparator(); - } + // TODO(user): make column return a SortedMap /** * Returns the comparator that orders the columns. With natural ordering, @@ -161,166 +286,6 @@ public class TreeBasedTable extends StandardRowSortedTable { return columnComparator; } - // TODO(user): make column return a SortedMap - - /** - * {@inheritDoc} - * - *

- * Because a {@code TreeBasedTable} has unique sorted values for a given row, - * this method returns a {@link SortedMap}, instead of the {@link Map} specified - * in the {@link Table} interface. - * - * @since 10.0 - * (mostly source-compatible since 7.0) - */ - @Override - public SortedMap row(R rowKey) { - return new TreeRow(rowKey); - } - - private class TreeRow extends Row implements SortedMap { - @Nullable - final C lowerBound; - @Nullable - final C upperBound; - - TreeRow(R rowKey) { - this(rowKey, null, null); - } - - TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) { - super(rowKey); - this.lowerBound = lowerBound; - this.upperBound = upperBound; - checkArgument(lowerBound == null || upperBound == null || compare(lowerBound, upperBound) <= 0); - } - - @Override - public SortedSet keySet() { - return new Maps.SortedKeySet(this); - } - - @Override - public Comparator comparator() { - return columnComparator(); - } - - int compare(Object a, Object b) { - // pretend we can compare anything - @SuppressWarnings({ "rawtypes", "unchecked" }) - Comparator cmp = (Comparator) comparator(); - return cmp.compare(a, b); - } - - boolean rangeContains(@Nullable Object o) { - return o != null && (lowerBound == null || compare(lowerBound, o) <= 0) - && (upperBound == null || compare(upperBound, o) > 0); - } - - @Override - public SortedMap subMap(C fromKey, C toKey) { - checkArgument(rangeContains(checkNotNull(fromKey)) && rangeContains(checkNotNull(toKey))); - return new TreeRow(rowKey, fromKey, toKey); - } - - @Override - public SortedMap headMap(C toKey) { - checkArgument(rangeContains(checkNotNull(toKey))); - return new TreeRow(rowKey, lowerBound, toKey); - } - - @Override - public SortedMap tailMap(C fromKey) { - checkArgument(rangeContains(checkNotNull(fromKey))); - return new TreeRow(rowKey, fromKey, upperBound); - } - - @Override - public C firstKey() { - SortedMap backing = backingRowMap(); - if (backing == null) { - throw new NoSuchElementException(); - } - return backingRowMap().firstKey(); - } - - @Override - public C lastKey() { - SortedMap backing = backingRowMap(); - if (backing == null) { - throw new NoSuchElementException(); - } - return backingRowMap().lastKey(); - } - - transient SortedMap wholeRow; - - /* - * If the row was previously empty, we check if there's a new row here every - * time we're queried. - */ - SortedMap wholeRow() { - if (wholeRow == null || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) { - wholeRow = (SortedMap) backingMap.get(rowKey); - } - return wholeRow; - } - - @Override - SortedMap backingRowMap() { - return (SortedMap) super.backingRowMap(); - } - - @Override - SortedMap computeBackingRowMap() { - SortedMap map = wholeRow(); - if (map != null) { - if (lowerBound != null) { - map = map.tailMap(lowerBound); - } - if (upperBound != null) { - map = map.headMap(upperBound); - } - return map; - } - return null; - } - - @Override - void maintainEmptyInvariant() { - if (wholeRow() != null && wholeRow.isEmpty()) { - backingMap.remove(rowKey); - wholeRow = null; - backingRowMap = null; - } - } - - @Override - public boolean containsKey(Object key) { - return rangeContains(key) && super.containsKey(key); - } - - @Override - public V put(C key, V value) { - checkArgument(rangeContains(checkNotNull(key))); - return super.put(key, value); - } - } - - // rowKeySet() and rowMap() are defined here so they appear in the Javadoc. - - @Override - public SortedSet rowKeySet() { - return super.rowKeySet(); - } - - @Override - public SortedMap> rowMap() { - return super.rowMap(); - } - /** * Overridden column iterator to return columns values in globally sorted order. */ @@ -358,5 +323,40 @@ public class TreeBasedTable extends StandardRowSortedTable { }; } - private static final long serialVersionUID = 0; + // rowKeySet() and rowMap() are defined here so they appear in the Javadoc. + + /** + * {@inheritDoc} + * + *

+ * Because a {@code TreeBasedTable} has unique sorted values for a given row, + * this method returns a {@link SortedMap}, instead of the {@link Map} specified + * in the {@link Table} interface. + * + * @since 10.0 + * (mostly source-compatible since 7.0) + */ + @Override + public SortedMap row(R rowKey) { + return new TreeRow(rowKey); + } + + /** + * Returns the comparator that orders the rows. With natural ordering, + * {@link Ordering#natural()} is returned. + */ + public Comparator rowComparator() { + return rowKeySet().comparator(); + } + + @Override + public SortedSet rowKeySet() { + return super.rowKeySet(); + } + + @Override + public SortedMap> rowMap() { + return super.rowMap(); + } } diff --git a/src/main/java/com/google/common/collect/TreeMultimap.java b/src/main/java/com/google/common/collect/TreeMultimap.java index ed1bf49e..f8943455 100644 --- a/src/main/java/com/google/common/collect/TreeMultimap.java +++ b/src/main/java/com/google/common/collect/TreeMultimap.java @@ -83,8 +83,8 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(serializable = true, emulated = true) public class TreeMultimap extends AbstractSortedKeySortedSetMultimap { - private transient Comparator keyComparator; - private transient Comparator valueComparator; + @GwtIncompatible("not needed in emulated source") + private static final long serialVersionUID = 0; /** * Creates an empty {@code TreeMultimap} ordered by the natural ordering of its @@ -118,6 +118,10 @@ public class TreeMultimap extends AbstractSortedKeySortedSetMultimap return new TreeMultimap(Ordering.natural(), Ordering.natural(), multimap); } + private transient Comparator keyComparator; + + private transient Comparator valueComparator; + TreeMultimap(Comparator keyComparator, Comparator valueComparator) { super(new TreeMap>(keyComparator)); this.keyComparator = keyComparator; @@ -130,6 +134,40 @@ public class TreeMultimap extends AbstractSortedKeySortedSetMultimap putAll(multimap); } + /** + * {@inheritDoc} + * + *

+ * Because a {@code TreeMultimap} has unique sorted keys, this method returns a + * {@link NavigableMap}, instead of the {@link java.util.Map} specified in the + * {@link Multimap} interface. + * + * @since 14.0 (present with return type {@code SortedMap} since 2.0) + */ + @Override + @GwtIncompatible("NavigableMap") + public NavigableMap> asMap() { + return (NavigableMap>) super.asMap(); + } + + @Override + @GwtIncompatible("NavigableMap") + NavigableMap> backingMap() { + return (NavigableMap>) super.backingMap(); + } + + @Override + @GwtIncompatible("NavigableMap") + NavigableMap> createAsMap() { + return new NavigableAsMap(backingMap()); + } + + /* + * The following @GwtIncompatible methods override the methods in + * AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM + * implementations, which return SortedSets and SortedMaps. + */ + /** * {@inheritDoc} * @@ -151,28 +189,10 @@ public class TreeMultimap extends AbstractSortedKeySortedSetMultimap return super.createCollection(key); } - /** - * Returns the comparator that orders the multimap keys. - */ - public Comparator keyComparator() { - return keyComparator; - } - @Override - public Comparator valueComparator() { - return valueComparator; - } - - /* - * The following @GwtIncompatible methods override the methods in - * AbstractSortedKeySortedSetMultimap, so GWT will fall back to the ASKSSM - * implementations, which return SortedSets and SortedMaps. - */ - - @Override - @GwtIncompatible("NavigableMap") - NavigableMap> backingMap() { - return (NavigableMap>) super.backingMap(); + @GwtIncompatible("NavigableSet") + NavigableSet createKeySet() { + return new NavigableKeySet(backingMap()); } /** @@ -184,16 +204,11 @@ public class TreeMultimap extends AbstractSortedKeySortedSetMultimap return (NavigableSet) super.get(key); } - @Override - @GwtIncompatible("NavigableSet") - Collection unmodifiableCollectionSubclass(Collection collection) { - return Sets.unmodifiableNavigableSet((NavigableSet) collection); - } - - @Override - @GwtIncompatible("NavigableSet") - Collection wrapCollection(K key, Collection collection) { - return new WrappedNavigableSet(key, (NavigableSet) collection, null); + /** + * Returns the comparator that orders the multimap keys. + */ + public Comparator keyComparator() { + return keyComparator; } /** @@ -212,32 +227,31 @@ public class TreeMultimap extends AbstractSortedKeySortedSetMultimap return (NavigableSet) super.keySet(); } + @GwtIncompatible("java.io.ObjectInputStream") + @SuppressWarnings("unchecked") // reading data stored by writeObject + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + keyComparator = checkNotNull((Comparator) stream.readObject()); + valueComparator = checkNotNull((Comparator) stream.readObject()); + setMap(new TreeMap>(keyComparator)); + Serialization.populateMultimap(this, stream); + } + @Override @GwtIncompatible("NavigableSet") - NavigableSet createKeySet() { - return new NavigableKeySet(backingMap()); - } - - /** - * {@inheritDoc} - * - *

- * Because a {@code TreeMultimap} has unique sorted keys, this method returns a - * {@link NavigableMap}, instead of the {@link java.util.Map} specified in the - * {@link Multimap} interface. - * - * @since 14.0 (present with return type {@code SortedMap} since 2.0) - */ - @Override - @GwtIncompatible("NavigableMap") - public NavigableMap> asMap() { - return (NavigableMap>) super.asMap(); + Collection unmodifiableCollectionSubclass(Collection collection) { + return Sets.unmodifiableNavigableSet((NavigableSet) collection); } @Override - @GwtIncompatible("NavigableMap") - NavigableMap> createAsMap() { - return new NavigableAsMap(backingMap()); + public Comparator valueComparator() { + return valueComparator; + } + + @Override + @GwtIncompatible("NavigableSet") + Collection wrapCollection(K key, Collection collection) { + return new WrappedNavigableSet(key, (NavigableSet) collection, null); } /** @@ -252,17 +266,4 @@ public class TreeMultimap extends AbstractSortedKeySortedSetMultimap stream.writeObject(valueComparator()); Serialization.writeMultimap(this, stream); } - - @GwtIncompatible("java.io.ObjectInputStream") - @SuppressWarnings("unchecked") // reading data stored by writeObject - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - keyComparator = checkNotNull((Comparator) stream.readObject()); - valueComparator = checkNotNull((Comparator) stream.readObject()); - setMap(new TreeMap>(keyComparator)); - Serialization.populateMultimap(this, stream); - } - - @GwtIncompatible("not needed in emulated source") - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/TreeMultiset.java b/src/main/java/com/google/common/collect/TreeMultiset.java index 31768fa1..166dd8b4 100644 --- a/src/main/java/com/google/common/collect/TreeMultiset.java +++ b/src/main/java/com/google/common/collect/TreeMultiset.java @@ -62,6 +62,474 @@ import com.google.common.primitives.Ints; @GwtCompatible(emulated = true) public final class TreeMultiset extends AbstractSortedMultiset implements Serializable { + /** + * A function which can be summed across a subtree. + */ + private enum Aggregate { + SIZE { + @Override + int nodeAggregate(AvlNode node) { + return node.elemCount; + } + + @Override + long treeAggregate(@Nullable AvlNode root) { + return (root == null) ? 0 : root.totalCount; + } + }, + DISTINCT { + @Override + int nodeAggregate(AvlNode node) { + return 1; + } + + @Override + long treeAggregate(@Nullable AvlNode root) { + return (root == null) ? 0 : root.distinctElements; + } + }; + + abstract int nodeAggregate(AvlNode node); + + abstract long treeAggregate(@Nullable AvlNode root); + } + + private static final class AvlNode extends Multisets.AbstractEntry { + private static int height(@Nullable AvlNode node) { + return (node == null) ? 0 : node.height; + } + + private static long totalCount(@Nullable AvlNode node) { + return (node == null) ? 0 : node.totalCount; + } + + @Nullable + private final E elem; + // elemCount is 0 iff this node has been deleted. + private int elemCount; + private int distinctElements; + private long totalCount; + private int height; + private AvlNode left; + private AvlNode right; + + private AvlNode pred; + + private AvlNode succ; + + AvlNode(@Nullable E elem, int elemCount) { + checkArgument(elemCount > 0); + this.elem = elem; + this.elemCount = elemCount; + this.totalCount = elemCount; + this.distinctElements = 1; + this.height = 1; + this.left = null; + this.right = null; + } + + AvlNode add(Comparator comparator, @Nullable E e, int count, int[] result) { + /* + * It speeds things up considerably to unconditionally add count to totalCount + * here, but that destroys failure atomicity in the case of count overflow. =( + */ + int cmp = comparator.compare(e, elem); + if (cmp < 0) { + AvlNode initLeft = left; + if (initLeft == null) { + result[0] = 0; + return addLeftChild(e, count); + } + int initHeight = initLeft.height; + + left = initLeft.add(comparator, e, count, result); + if (result[0] == 0) { + distinctElements++; + } + this.totalCount += count; + return (left.height == initHeight) ? this : rebalance(); + } else if (cmp > 0) { + AvlNode initRight = right; + if (initRight == null) { + result[0] = 0; + return addRightChild(e, count); + } + int initHeight = initRight.height; + + right = initRight.add(comparator, e, count, result); + if (result[0] == 0) { + distinctElements++; + } + this.totalCount += count; + return (right.height == initHeight) ? this : rebalance(); + } + + // adding count to me! No rebalance possible. + result[0] = elemCount; + long resultCount = (long) elemCount + count; + checkArgument(resultCount <= Integer.MAX_VALUE); + this.elemCount += count; + this.totalCount += count; + return this; + } + + private AvlNode addLeftChild(E e, int count) { + left = new AvlNode(e, count); + successor(pred, left, this); + height = Math.max(2, height); + distinctElements++; + totalCount += count; + return this; + } + + private AvlNode addRightChild(E e, int count) { + right = new AvlNode(e, count); + successor(this, right, succ); + height = Math.max(2, height); + distinctElements++; + totalCount += count; + return this; + } + + private int balanceFactor() { + return height(left) - height(right); + } + + @Nullable + private AvlNode ceiling(Comparator comparator, E e) { + int cmp = comparator.compare(e, elem); + if (cmp < 0) { + return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this); + } else if (cmp == 0) { + return this; + } else { + return (right == null) ? null : right.ceiling(comparator, e); + } + } + + public int count(Comparator comparator, E e) { + int cmp = comparator.compare(e, elem); + if (cmp < 0) { + return (left == null) ? 0 : left.count(comparator, e); + } else if (cmp > 0) { + return (right == null) ? 0 : right.count(comparator, e); + } else { + return elemCount; + } + } + + private AvlNode deleteMe() { + int oldElemCount = this.elemCount; + this.elemCount = 0; + successor(pred, succ); + if (left == null) { + return right; + } else if (right == null) { + return left; + } else if (left.height >= right.height) { + AvlNode newTop = pred; + // newTop is the maximum node in my left subtree + newTop.left = left.removeMax(newTop); + newTop.right = right; + newTop.distinctElements = distinctElements - 1; + newTop.totalCount = totalCount - oldElemCount; + return newTop.rebalance(); + } else { + AvlNode newTop = succ; + newTop.right = right.removeMin(newTop); + newTop.left = left; + newTop.distinctElements = distinctElements - 1; + newTop.totalCount = totalCount - oldElemCount; + return newTop.rebalance(); + } + } + + @Nullable + private AvlNode floor(Comparator comparator, E e) { + int cmp = comparator.compare(e, elem); + if (cmp > 0) { + return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this); + } else if (cmp == 0) { + return this; + } else { + return (left == null) ? null : left.floor(comparator, e); + } + } + + @Override + public int getCount() { + return elemCount; + } + + @Override + public E getElement() { + return elem; + } + + private AvlNode rebalance() { + switch (balanceFactor()) { + case -2: + if (right.balanceFactor() > 0) { + right = right.rotateRight(); + } + return rotateLeft(); + case 2: + if (left.balanceFactor() < 0) { + left = left.rotateLeft(); + } + return rotateRight(); + default: + recomputeHeight(); + return this; + } + } + + private void recompute() { + recomputeMultiset(); + recomputeHeight(); + } + + private void recomputeHeight() { + this.height = 1 + Math.max(height(left), height(right)); + } + + private void recomputeMultiset() { + this.distinctElements = 1 + TreeMultiset.distinctElements(left) + TreeMultiset.distinctElements(right); + this.totalCount = elemCount + totalCount(left) + totalCount(right); + } + + AvlNode remove(Comparator comparator, @Nullable E e, int count, int[] result) { + int cmp = comparator.compare(e, elem); + if (cmp < 0) { + AvlNode initLeft = left; + if (initLeft == null) { + result[0] = 0; + return this; + } + + left = initLeft.remove(comparator, e, count, result); + + if (result[0] > 0) { + if (count >= result[0]) { + this.distinctElements--; + this.totalCount -= result[0]; + } else { + this.totalCount -= count; + } + } + return (result[0] == 0) ? this : rebalance(); + } else if (cmp > 0) { + AvlNode initRight = right; + if (initRight == null) { + result[0] = 0; + return this; + } + + right = initRight.remove(comparator, e, count, result); + + if (result[0] > 0) { + if (count >= result[0]) { + this.distinctElements--; + this.totalCount -= result[0]; + } else { + this.totalCount -= count; + } + } + return rebalance(); + } + + // removing count from me! + result[0] = elemCount; + if (count >= elemCount) { + return deleteMe(); + } else { + this.elemCount -= count; + this.totalCount -= count; + return this; + } + } + + // Removes the maximum node from this subtree to be reused elsewhere + private AvlNode removeMax(AvlNode node) { + if (right == null) { + return left; + } else { + right = right.removeMax(node); + distinctElements--; + totalCount -= node.elemCount; + return rebalance(); + } + } + + // Removes the minimum node from this subtree to be reused elsewhere + private AvlNode removeMin(AvlNode node) { + if (left == null) { + return right; + } else { + left = left.removeMin(node); + distinctElements--; + totalCount -= node.elemCount; + return rebalance(); + } + } + + private AvlNode rotateLeft() { + checkState(right != null); + AvlNode newTop = right; + this.right = newTop.left; + newTop.left = this; + newTop.totalCount = this.totalCount; + newTop.distinctElements = this.distinctElements; + this.recompute(); + newTop.recomputeHeight(); + return newTop; + } + + private AvlNode rotateRight() { + checkState(left != null); + AvlNode newTop = left; + this.left = newTop.right; + newTop.right = this; + newTop.totalCount = this.totalCount; + newTop.distinctElements = this.distinctElements; + this.recompute(); + newTop.recomputeHeight(); + return newTop; + } + + AvlNode setCount(Comparator comparator, @Nullable E e, int expectedCount, int newCount, + int[] result) { + int cmp = comparator.compare(e, elem); + if (cmp < 0) { + AvlNode initLeft = left; + if (initLeft == null) { + result[0] = 0; + if (expectedCount == 0 && newCount > 0) { + return addLeftChild(e, newCount); + } + return this; + } + + left = initLeft.setCount(comparator, e, expectedCount, newCount, result); + + if (result[0] == expectedCount) { + if (newCount == 0 && result[0] != 0) { + this.distinctElements--; + } else if (newCount > 0 && result[0] == 0) { + this.distinctElements++; + } + this.totalCount += newCount - result[0]; + } + return rebalance(); + } else if (cmp > 0) { + AvlNode initRight = right; + if (initRight == null) { + result[0] = 0; + if (expectedCount == 0 && newCount > 0) { + return addRightChild(e, newCount); + } + return this; + } + + right = initRight.setCount(comparator, e, expectedCount, newCount, result); + + if (result[0] == expectedCount) { + if (newCount == 0 && result[0] != 0) { + this.distinctElements--; + } else if (newCount > 0 && result[0] == 0) { + this.distinctElements++; + } + this.totalCount += newCount - result[0]; + } + return rebalance(); + } + + // setting my count + result[0] = elemCount; + if (expectedCount == elemCount) { + if (newCount == 0) { + return deleteMe(); + } + this.totalCount += newCount - elemCount; + this.elemCount = newCount; + } + return this; + } + + AvlNode setCount(Comparator comparator, @Nullable E e, int count, int[] result) { + int cmp = comparator.compare(e, elem); + if (cmp < 0) { + AvlNode initLeft = left; + if (initLeft == null) { + result[0] = 0; + return (count > 0) ? addLeftChild(e, count) : this; + } + + left = initLeft.setCount(comparator, e, count, result); + + if (count == 0 && result[0] != 0) { + this.distinctElements--; + } else if (count > 0 && result[0] == 0) { + this.distinctElements++; + } + + this.totalCount += count - result[0]; + return rebalance(); + } else if (cmp > 0) { + AvlNode initRight = right; + if (initRight == null) { + result[0] = 0; + return (count > 0) ? addRightChild(e, count) : this; + } + + right = initRight.setCount(comparator, e, count, result); + + if (count == 0 && result[0] != 0) { + this.distinctElements--; + } else if (count > 0 && result[0] == 0) { + this.distinctElements++; + } + + this.totalCount += count - result[0]; + return rebalance(); + } + + // setting my count + result[0] = elemCount; + if (count == 0) { + return deleteMe(); + } + this.totalCount += count - elemCount; + this.elemCount = count; + return this; + } + + @Override + public String toString() { + return Multisets.immutableEntry(getElement(), getCount()).toString(); + } + } + + private static final class Reference { + @Nullable + private T value; + + public void checkAndSet(@Nullable T expected, T newValue) { + if (value != expected) { + throw new ConcurrentModificationException(); + } + value = newValue; + } + + @Nullable + public T get() { + return value; + } + } + + @GwtIncompatible("not needed in emulated source") + private static final long serialVersionUID = 1; + /** * Creates a new, empty multiset, sorted according to the elements' natural * order. All elements inserted into the multiset must implement the @@ -120,17 +588,26 @@ public final class TreeMultiset extends AbstractSortedMultiset implements return multiset; } - private final transient Reference> rootReference; - private final transient GeneralRange range; - private final transient AvlNode header; - - TreeMultiset(Reference> rootReference, GeneralRange range, AvlNode endLink) { - super(range.comparator()); - this.rootReference = rootReference; - this.range = range; - this.header = endLink; + static int distinctElements(@Nullable AvlNode node) { + return (node == null) ? 0 : node.distinctElements; } + private static void successor(AvlNode a, AvlNode b) { + a.succ = b; + b.pred = a; + } + + private static void successor(AvlNode a, AvlNode b, AvlNode c) { + successor(a, b); + successor(b, c); + } + + private final transient Reference> rootReference; + + private final transient GeneralRange range; + + private final transient AvlNode header; + TreeMultiset(Comparator comparator) { super(comparator); this.range = GeneralRange.all(comparator); @@ -139,69 +616,32 @@ public final class TreeMultiset extends AbstractSortedMultiset implements this.rootReference = new Reference>(); } - /** - * A function which can be summed across a subtree. - */ - private enum Aggregate { - SIZE { - @Override - int nodeAggregate(AvlNode node) { - return node.elemCount; - } - - @Override - long treeAggregate(@Nullable AvlNode root) { - return (root == null) ? 0 : root.totalCount; - } - }, - DISTINCT { - @Override - int nodeAggregate(AvlNode node) { - return 1; - } - - @Override - long treeAggregate(@Nullable AvlNode root) { - return (root == null) ? 0 : root.distinctElements; - } - }; - - abstract int nodeAggregate(AvlNode node); - - abstract long treeAggregate(@Nullable AvlNode root); + TreeMultiset(Reference> rootReference, GeneralRange range, AvlNode endLink) { + super(range.comparator()); + this.rootReference = rootReference; + this.range = range; + this.header = endLink; } - private long aggregateForEntries(Aggregate aggr) { + @Override + public int add(@Nullable E element, int occurrences) { + checkNonnegative(occurrences, "occurrences"); + if (occurrences == 0) { + return count(element); + } + checkArgument(range.contains(element)); AvlNode root = rootReference.get(); - long total = aggr.treeAggregate(root); - if (range.hasLowerBound()) { - total -= aggregateBelowRange(aggr, root); - } - if (range.hasUpperBound()) { - total -= aggregateAboveRange(aggr, root); - } - return total; - } - - private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode node) { - if (node == null) { + if (root == null) { + comparator().compare(element, element); + AvlNode newRoot = new AvlNode(element, occurrences); + successor(header, newRoot, header); + rootReference.checkAndSet(root, newRoot); return 0; } - int cmp = comparator().compare(range.getLowerEndpoint(), node.elem); - if (cmp < 0) { - return aggregateBelowRange(aggr, node.left); - } else if (cmp == 0) { - switch (range.getLowerBoundType()) { - case OPEN: - return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left); - case CLOSED: - return aggr.treeAggregate(node.left); - default: - throw new AssertionError(); - } - } else { - return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node) + aggregateBelowRange(aggr, node.right); - } + int[] result = new int[1]; // used as a mutable int reference to hold result + AvlNode newRoot = root.add(comparator(), element, occurrences, result); + rootReference.checkAndSet(root, newRoot); + return result[0]; } private long aggregateAboveRange(Aggregate aggr, @Nullable AvlNode node) { @@ -225,14 +665,37 @@ public final class TreeMultiset extends AbstractSortedMultiset implements } } - @Override - public int size() { - return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE)); + private long aggregateBelowRange(Aggregate aggr, @Nullable AvlNode node) { + if (node == null) { + return 0; + } + int cmp = comparator().compare(range.getLowerEndpoint(), node.elem); + if (cmp < 0) { + return aggregateBelowRange(aggr, node.left); + } else if (cmp == 0) { + switch (range.getLowerBoundType()) { + case OPEN: + return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left); + case CLOSED: + return aggr.treeAggregate(node.left); + default: + throw new AssertionError(); + } + } else { + return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node) + aggregateBelowRange(aggr, node.right); + } } - @Override - int distinctElements() { - return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT)); + private long aggregateForEntries(Aggregate aggr) { + AvlNode root = rootReference.get(); + long total = aggr.treeAggregate(root); + if (range.hasLowerBound()) { + total -= aggregateBelowRange(aggr, root); + } + if (range.hasUpperBound()) { + total -= aggregateAboveRange(aggr, root); + } + return total; } @Override @@ -253,24 +716,160 @@ public final class TreeMultiset extends AbstractSortedMultiset implements } @Override - public int add(@Nullable E element, int occurrences) { - checkNonnegative(occurrences, "occurrences"); - if (occurrences == 0) { - return count(element); - } - checkArgument(range.contains(element)); + Iterator> descendingEntryIterator() { + return new Iterator>() { + AvlNode current = lastNode(); + Entry prevEntry = null; + + @Override + public boolean hasNext() { + if (current == null) { + return false; + } else if (range.tooLow(current.getElement())) { + current = null; + return false; + } else { + return true; + } + } + + @Override + public Entry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + Entry result = wrapEntry(current); + prevEntry = result; + if (current.pred == header) { + current = null; + } else { + current = current.pred; + } + return result; + } + + @Override + public void remove() { + checkRemove(prevEntry != null); + setCount(prevEntry.getElement(), 0); + prevEntry = null; + } + }; + } + + @Override + int distinctElements() { + return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT)); + } + + @Override + Iterator> entryIterator() { + return new Iterator>() { + AvlNode current = firstNode(); + Entry prevEntry; + + @Override + public boolean hasNext() { + if (current == null) { + return false; + } else if (range.tooHigh(current.getElement())) { + current = null; + return false; + } else { + return true; + } + } + + @Override + public Entry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + Entry result = wrapEntry(current); + prevEntry = result; + if (current.succ == header) { + current = null; + } else { + current = current.succ; + } + return result; + } + + @Override + public void remove() { + checkRemove(prevEntry != null); + setCount(prevEntry.getElement(), 0); + prevEntry = null; + } + }; + } + + /** + * Returns the first node in the tree that is in range. + */ + @Nullable + private AvlNode firstNode() { AvlNode root = rootReference.get(); if (root == null) { - comparator().compare(element, element); - AvlNode newRoot = new AvlNode(element, occurrences); - successor(header, newRoot, header); - rootReference.checkAndSet(root, newRoot); - return 0; + return null; } - int[] result = new int[1]; // used as a mutable int reference to hold result - AvlNode newRoot = root.add(comparator(), element, occurrences, result); - rootReference.checkAndSet(root, newRoot); - return result[0]; + AvlNode node; + if (range.hasLowerBound()) { + E endpoint = range.getLowerEndpoint(); + node = rootReference.get().ceiling(comparator(), endpoint); + if (node == null) { + return null; + } + if (range.getLowerBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { + node = node.succ; + } + } else { + node = header.succ; + } + return (node == header || !range.contains(node.getElement())) ? null : node; + } + + @Override + public SortedMultiset headMultiset(@Nullable E upperBound, BoundType boundType) { + return new TreeMultiset(rootReference, + range.intersect(GeneralRange.upTo(comparator(), upperBound, boundType)), header); + } + + @Nullable + private AvlNode lastNode() { + AvlNode root = rootReference.get(); + if (root == null) { + return null; + } + AvlNode node; + if (range.hasUpperBound()) { + E endpoint = range.getUpperEndpoint(); + node = rootReference.get().floor(comparator(), endpoint); + if (node == null) { + return null; + } + if (range.getUpperBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { + node = node.pred; + } + } else { + node = header.pred; + } + return (node == header || !range.contains(node.getElement())) ? null : node; + } + + @GwtIncompatible("java.io.ObjectInputStream") + private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { + stream.defaultReadObject(); + @SuppressWarnings("unchecked") + // reading data stored by writeObject + Comparator comparator = (Comparator) stream.readObject(); + Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator); + Serialization.getFieldSetter(TreeMultiset.class, "range").set(this, GeneralRange.all(comparator)); + Serialization.getFieldSetter(TreeMultiset.class, "rootReference").set(this, new Reference>()); + AvlNode header = new AvlNode(null, 1); + Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header); + successor(header, header); + Serialization.populateMultiset(this, stream); } @Override @@ -342,13 +941,26 @@ public final class TreeMultiset extends AbstractSortedMultiset implements return result[0] == oldCount; } + @Override + public int size() { + return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE)); + } + + /* + * TODO(jlevy): Decide whether entrySet() should return entries with an equals() + * method that calls the comparator to compare the two keys. If that change is + * made, AbstractMultiset.equals() can simply check whether two multisets have + * equal entry sets. + */ + + @Override + public SortedMultiset tailMultiset(@Nullable E lowerBound, BoundType boundType) { + return new TreeMultiset(rootReference, + range.intersect(GeneralRange.downTo(comparator(), lowerBound, boundType)), header); + } + private Entry wrapEntry(final AvlNode baseEntry) { return new Multisets.AbstractEntry() { - @Override - public E getElement() { - return baseEntry.getElement(); - } - @Override public int getCount() { int result = baseEntry.getCount(); @@ -358,606 +970,14 @@ public final class TreeMultiset extends AbstractSortedMultiset implements return result; } } - }; - } - - /** - * Returns the first node in the tree that is in range. - */ - @Nullable - private AvlNode firstNode() { - AvlNode root = rootReference.get(); - if (root == null) { - return null; - } - AvlNode node; - if (range.hasLowerBound()) { - E endpoint = range.getLowerEndpoint(); - node = rootReference.get().ceiling(comparator(), endpoint); - if (node == null) { - return null; - } - if (range.getLowerBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { - node = node.succ; - } - } else { - node = header.succ; - } - return (node == header || !range.contains(node.getElement())) ? null : node; - } - - @Nullable - private AvlNode lastNode() { - AvlNode root = rootReference.get(); - if (root == null) { - return null; - } - AvlNode node; - if (range.hasUpperBound()) { - E endpoint = range.getUpperEndpoint(); - node = rootReference.get().floor(comparator(), endpoint); - if (node == null) { - return null; - } - if (range.getUpperBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { - node = node.pred; - } - } else { - node = header.pred; - } - return (node == header || !range.contains(node.getElement())) ? null : node; - } - - @Override - Iterator> entryIterator() { - return new Iterator>() { - AvlNode current = firstNode(); - Entry prevEntry; @Override - public boolean hasNext() { - if (current == null) { - return false; - } else if (range.tooHigh(current.getElement())) { - current = null; - return false; - } else { - return true; - } - } - - @Override - public Entry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - Entry result = wrapEntry(current); - prevEntry = result; - if (current.succ == header) { - current = null; - } else { - current = current.succ; - } - return result; - } - - @Override - public void remove() { - checkRemove(prevEntry != null); - setCount(prevEntry.getElement(), 0); - prevEntry = null; + public E getElement() { + return baseEntry.getElement(); } }; } - @Override - Iterator> descendingEntryIterator() { - return new Iterator>() { - AvlNode current = lastNode(); - Entry prevEntry = null; - - @Override - public boolean hasNext() { - if (current == null) { - return false; - } else if (range.tooLow(current.getElement())) { - current = null; - return false; - } else { - return true; - } - } - - @Override - public Entry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - Entry result = wrapEntry(current); - prevEntry = result; - if (current.pred == header) { - current = null; - } else { - current = current.pred; - } - return result; - } - - @Override - public void remove() { - checkRemove(prevEntry != null); - setCount(prevEntry.getElement(), 0); - prevEntry = null; - } - }; - } - - @Override - public SortedMultiset headMultiset(@Nullable E upperBound, BoundType boundType) { - return new TreeMultiset(rootReference, - range.intersect(GeneralRange.upTo(comparator(), upperBound, boundType)), header); - } - - @Override - public SortedMultiset tailMultiset(@Nullable E lowerBound, BoundType boundType) { - return new TreeMultiset(rootReference, - range.intersect(GeneralRange.downTo(comparator(), lowerBound, boundType)), header); - } - - static int distinctElements(@Nullable AvlNode node) { - return (node == null) ? 0 : node.distinctElements; - } - - private static final class Reference { - @Nullable - private T value; - - @Nullable - public T get() { - return value; - } - - public void checkAndSet(@Nullable T expected, T newValue) { - if (value != expected) { - throw new ConcurrentModificationException(); - } - value = newValue; - } - } - - private static final class AvlNode extends Multisets.AbstractEntry { - @Nullable - private final E elem; - - // elemCount is 0 iff this node has been deleted. - private int elemCount; - - private int distinctElements; - private long totalCount; - private int height; - private AvlNode left; - private AvlNode right; - private AvlNode pred; - private AvlNode succ; - - AvlNode(@Nullable E elem, int elemCount) { - checkArgument(elemCount > 0); - this.elem = elem; - this.elemCount = elemCount; - this.totalCount = elemCount; - this.distinctElements = 1; - this.height = 1; - this.left = null; - this.right = null; - } - - public int count(Comparator comparator, E e) { - int cmp = comparator.compare(e, elem); - if (cmp < 0) { - return (left == null) ? 0 : left.count(comparator, e); - } else if (cmp > 0) { - return (right == null) ? 0 : right.count(comparator, e); - } else { - return elemCount; - } - } - - private AvlNode addRightChild(E e, int count) { - right = new AvlNode(e, count); - successor(this, right, succ); - height = Math.max(2, height); - distinctElements++; - totalCount += count; - return this; - } - - private AvlNode addLeftChild(E e, int count) { - left = new AvlNode(e, count); - successor(pred, left, this); - height = Math.max(2, height); - distinctElements++; - totalCount += count; - return this; - } - - AvlNode add(Comparator comparator, @Nullable E e, int count, int[] result) { - /* - * It speeds things up considerably to unconditionally add count to totalCount - * here, but that destroys failure atomicity in the case of count overflow. =( - */ - int cmp = comparator.compare(e, elem); - if (cmp < 0) { - AvlNode initLeft = left; - if (initLeft == null) { - result[0] = 0; - return addLeftChild(e, count); - } - int initHeight = initLeft.height; - - left = initLeft.add(comparator, e, count, result); - if (result[0] == 0) { - distinctElements++; - } - this.totalCount += count; - return (left.height == initHeight) ? this : rebalance(); - } else if (cmp > 0) { - AvlNode initRight = right; - if (initRight == null) { - result[0] = 0; - return addRightChild(e, count); - } - int initHeight = initRight.height; - - right = initRight.add(comparator, e, count, result); - if (result[0] == 0) { - distinctElements++; - } - this.totalCount += count; - return (right.height == initHeight) ? this : rebalance(); - } - - // adding count to me! No rebalance possible. - result[0] = elemCount; - long resultCount = (long) elemCount + count; - checkArgument(resultCount <= Integer.MAX_VALUE); - this.elemCount += count; - this.totalCount += count; - return this; - } - - AvlNode remove(Comparator comparator, @Nullable E e, int count, int[] result) { - int cmp = comparator.compare(e, elem); - if (cmp < 0) { - AvlNode initLeft = left; - if (initLeft == null) { - result[0] = 0; - return this; - } - - left = initLeft.remove(comparator, e, count, result); - - if (result[0] > 0) { - if (count >= result[0]) { - this.distinctElements--; - this.totalCount -= result[0]; - } else { - this.totalCount -= count; - } - } - return (result[0] == 0) ? this : rebalance(); - } else if (cmp > 0) { - AvlNode initRight = right; - if (initRight == null) { - result[0] = 0; - return this; - } - - right = initRight.remove(comparator, e, count, result); - - if (result[0] > 0) { - if (count >= result[0]) { - this.distinctElements--; - this.totalCount -= result[0]; - } else { - this.totalCount -= count; - } - } - return rebalance(); - } - - // removing count from me! - result[0] = elemCount; - if (count >= elemCount) { - return deleteMe(); - } else { - this.elemCount -= count; - this.totalCount -= count; - return this; - } - } - - AvlNode setCount(Comparator comparator, @Nullable E e, int count, int[] result) { - int cmp = comparator.compare(e, elem); - if (cmp < 0) { - AvlNode initLeft = left; - if (initLeft == null) { - result[0] = 0; - return (count > 0) ? addLeftChild(e, count) : this; - } - - left = initLeft.setCount(comparator, e, count, result); - - if (count == 0 && result[0] != 0) { - this.distinctElements--; - } else if (count > 0 && result[0] == 0) { - this.distinctElements++; - } - - this.totalCount += count - result[0]; - return rebalance(); - } else if (cmp > 0) { - AvlNode initRight = right; - if (initRight == null) { - result[0] = 0; - return (count > 0) ? addRightChild(e, count) : this; - } - - right = initRight.setCount(comparator, e, count, result); - - if (count == 0 && result[0] != 0) { - this.distinctElements--; - } else if (count > 0 && result[0] == 0) { - this.distinctElements++; - } - - this.totalCount += count - result[0]; - return rebalance(); - } - - // setting my count - result[0] = elemCount; - if (count == 0) { - return deleteMe(); - } - this.totalCount += count - elemCount; - this.elemCount = count; - return this; - } - - AvlNode setCount(Comparator comparator, @Nullable E e, int expectedCount, int newCount, - int[] result) { - int cmp = comparator.compare(e, elem); - if (cmp < 0) { - AvlNode initLeft = left; - if (initLeft == null) { - result[0] = 0; - if (expectedCount == 0 && newCount > 0) { - return addLeftChild(e, newCount); - } - return this; - } - - left = initLeft.setCount(comparator, e, expectedCount, newCount, result); - - if (result[0] == expectedCount) { - if (newCount == 0 && result[0] != 0) { - this.distinctElements--; - } else if (newCount > 0 && result[0] == 0) { - this.distinctElements++; - } - this.totalCount += newCount - result[0]; - } - return rebalance(); - } else if (cmp > 0) { - AvlNode initRight = right; - if (initRight == null) { - result[0] = 0; - if (expectedCount == 0 && newCount > 0) { - return addRightChild(e, newCount); - } - return this; - } - - right = initRight.setCount(comparator, e, expectedCount, newCount, result); - - if (result[0] == expectedCount) { - if (newCount == 0 && result[0] != 0) { - this.distinctElements--; - } else if (newCount > 0 && result[0] == 0) { - this.distinctElements++; - } - this.totalCount += newCount - result[0]; - } - return rebalance(); - } - - // setting my count - result[0] = elemCount; - if (expectedCount == elemCount) { - if (newCount == 0) { - return deleteMe(); - } - this.totalCount += newCount - elemCount; - this.elemCount = newCount; - } - return this; - } - - private AvlNode deleteMe() { - int oldElemCount = this.elemCount; - this.elemCount = 0; - successor(pred, succ); - if (left == null) { - return right; - } else if (right == null) { - return left; - } else if (left.height >= right.height) { - AvlNode newTop = pred; - // newTop is the maximum node in my left subtree - newTop.left = left.removeMax(newTop); - newTop.right = right; - newTop.distinctElements = distinctElements - 1; - newTop.totalCount = totalCount - oldElemCount; - return newTop.rebalance(); - } else { - AvlNode newTop = succ; - newTop.right = right.removeMin(newTop); - newTop.left = left; - newTop.distinctElements = distinctElements - 1; - newTop.totalCount = totalCount - oldElemCount; - return newTop.rebalance(); - } - } - - // Removes the minimum node from this subtree to be reused elsewhere - private AvlNode removeMin(AvlNode node) { - if (left == null) { - return right; - } else { - left = left.removeMin(node); - distinctElements--; - totalCount -= node.elemCount; - return rebalance(); - } - } - - // Removes the maximum node from this subtree to be reused elsewhere - private AvlNode removeMax(AvlNode node) { - if (right == null) { - return left; - } else { - right = right.removeMax(node); - distinctElements--; - totalCount -= node.elemCount; - return rebalance(); - } - } - - private void recomputeMultiset() { - this.distinctElements = 1 + TreeMultiset.distinctElements(left) + TreeMultiset.distinctElements(right); - this.totalCount = elemCount + totalCount(left) + totalCount(right); - } - - private void recomputeHeight() { - this.height = 1 + Math.max(height(left), height(right)); - } - - private void recompute() { - recomputeMultiset(); - recomputeHeight(); - } - - private AvlNode rebalance() { - switch (balanceFactor()) { - case -2: - if (right.balanceFactor() > 0) { - right = right.rotateRight(); - } - return rotateLeft(); - case 2: - if (left.balanceFactor() < 0) { - left = left.rotateLeft(); - } - return rotateRight(); - default: - recomputeHeight(); - return this; - } - } - - private int balanceFactor() { - return height(left) - height(right); - } - - private AvlNode rotateLeft() { - checkState(right != null); - AvlNode newTop = right; - this.right = newTop.left; - newTop.left = this; - newTop.totalCount = this.totalCount; - newTop.distinctElements = this.distinctElements; - this.recompute(); - newTop.recomputeHeight(); - return newTop; - } - - private AvlNode rotateRight() { - checkState(left != null); - AvlNode newTop = left; - this.left = newTop.right; - newTop.right = this; - newTop.totalCount = this.totalCount; - newTop.distinctElements = this.distinctElements; - this.recompute(); - newTop.recomputeHeight(); - return newTop; - } - - private static long totalCount(@Nullable AvlNode node) { - return (node == null) ? 0 : node.totalCount; - } - - private static int height(@Nullable AvlNode node) { - return (node == null) ? 0 : node.height; - } - - @Nullable - private AvlNode ceiling(Comparator comparator, E e) { - int cmp = comparator.compare(e, elem); - if (cmp < 0) { - return (left == null) ? this : Objects.firstNonNull(left.ceiling(comparator, e), this); - } else if (cmp == 0) { - return this; - } else { - return (right == null) ? null : right.ceiling(comparator, e); - } - } - - @Nullable - private AvlNode floor(Comparator comparator, E e) { - int cmp = comparator.compare(e, elem); - if (cmp > 0) { - return (right == null) ? this : Objects.firstNonNull(right.floor(comparator, e), this); - } else if (cmp == 0) { - return this; - } else { - return (left == null) ? null : left.floor(comparator, e); - } - } - - @Override - public E getElement() { - return elem; - } - - @Override - public int getCount() { - return elemCount; - } - - @Override - public String toString() { - return Multisets.immutableEntry(getElement(), getCount()).toString(); - } - } - - private static void successor(AvlNode a, AvlNode b) { - a.succ = b; - b.pred = a; - } - - private static void successor(AvlNode a, AvlNode b, AvlNode c) { - successor(a, b); - successor(b, c); - } - - /* - * TODO(jlevy): Decide whether entrySet() should return entries with an equals() - * method that calls the comparator to compare the two keys. If that change is - * made, AbstractMultiset.equals() can simply check whether two multisets have - * equal entry sets. - */ - /** * @serialData the comparator, the number of distinct elements, the first * element, its count, the second element, its count, and so on @@ -968,22 +988,4 @@ public final class TreeMultiset extends AbstractSortedMultiset implements stream.writeObject(elementSet().comparator()); Serialization.writeMultiset(this, stream); } - - @GwtIncompatible("java.io.ObjectInputStream") - private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { - stream.defaultReadObject(); - @SuppressWarnings("unchecked") - // reading data stored by writeObject - Comparator comparator = (Comparator) stream.readObject(); - Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator); - Serialization.getFieldSetter(TreeMultiset.class, "range").set(this, GeneralRange.all(comparator)); - Serialization.getFieldSetter(TreeMultiset.class, "rootReference").set(this, new Reference>()); - AvlNode header = new AvlNode(null, 1); - Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header); - successor(header, header); - Serialization.populateMultiset(this, stream); - } - - @GwtIncompatible("not needed in emulated source") - private static final long serialVersionUID = 1; } diff --git a/src/main/java/com/google/common/collect/TreeRangeMap.java b/src/main/java/com/google/common/collect/TreeRangeMap.java index 87607019..4e601962 100644 --- a/src/main/java/com/google/common/collect/TreeRangeMap.java +++ b/src/main/java/com/google/common/collect/TreeRangeMap.java @@ -56,14 +56,41 @@ import com.google.common.base.Predicate; @GwtIncompatible("NavigableMap") public final class TreeRangeMap implements RangeMap { - private final NavigableMap, RangeMapEntry> entriesByLowerBound; + private final class AsMapOfRanges extends AbstractMap, V> { - public static TreeRangeMap create() { - return new TreeRangeMap(); - } + @Override + public boolean containsKey(@Nullable Object key) { + return get(key) != null; + } - private TreeRangeMap() { - this.entriesByLowerBound = Maps.newTreeMap(); + @Override + public Set, V>> entrySet() { + return new AbstractSet, V>>() { + + @SuppressWarnings("unchecked") // it's safe to upcast iterators + @Override + public Iterator, V>> iterator() { + return (Iterator) entriesByLowerBound.values().iterator(); + } + + @Override + public int size() { + return entriesByLowerBound.size(); + } + }; + } + + @Override + public V get(@Nullable Object key) { + if (key instanceof Range) { + Range range = (Range) key; + RangeMapEntry rangeMapEntry = entriesByLowerBound.get(range.lowerBound); + if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) { + return rangeMapEntry.getValue(); + } + } + return null; + } } private static final class RangeMapEntry extends AbstractMapEntry, V> { @@ -79,20 +106,15 @@ public final class TreeRangeMap implements RangeMap getKey() { return range; } - @Override - public V getValue() { - return value; - } - - public boolean contains(K value) { - return range.contains(value); - } - Cut getLowerBound() { return range.lowerBound; } @@ -100,6 +122,363 @@ public final class TreeRangeMap implements RangeMap getUpperBound() { return range.upperBound; } + + @Override + public V getValue() { + return value; + } + } + + private class SubRangeMap implements RangeMap { + + class SubRangeMapAsMap extends AbstractMap, V> { + + @Override + public void clear() { + SubRangeMap.this.clear(); + } + + @Override + public boolean containsKey(Object key) { + return get(key) != null; + } + + @Override + public Set, V>> entrySet() { + return new Maps.EntrySet, V>() { + @Override + public boolean isEmpty() { + return !iterator().hasNext(); + } + + @Override + public Iterator, V>> iterator() { + if (subRange.isEmpty()) { + return Iterators.emptyIterator(); + } + Cut cutToStart = Objects.firstNonNull(entriesByLowerBound.floorKey(subRange.lowerBound), + subRange.lowerBound); + final Iterator> backingItr = entriesByLowerBound.tailMap(cutToStart, true) + .values().iterator(); + return new AbstractIterator, V>>() { + + @Override + protected Entry, V> computeNext() { + while (backingItr.hasNext()) { + RangeMapEntry entry = backingItr.next(); + if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) { + break; + } else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) { + // this might not be true e.g. at the start of the iteration + return Maps.immutableEntry(entry.getKey().intersection(subRange), + entry.getValue()); + } + } + return endOfData(); + } + }; + } + + @Override + Map, V> map() { + return SubRangeMapAsMap.this; + } + + @Override + public boolean retainAll(Collection c) { + return removeEntryIf(not(in(c))); + } + + @Override + public int size() { + return Iterators.size(iterator()); + } + }; + } + + @Override + public V get(Object key) { + try { + if (key instanceof Range) { + @SuppressWarnings("unchecked") // we catch ClassCastExceptions + Range r = (Range) key; + if (!subRange.encloses(r) || r.isEmpty()) { + return null; + } + RangeMapEntry candidate = null; + if (r.lowerBound.compareTo(subRange.lowerBound) == 0) { + // r could be truncated on the left + Entry, RangeMapEntry> entry = entriesByLowerBound.floorEntry(r.lowerBound); + if (entry != null) { + candidate = entry.getValue(); + } + } else { + candidate = entriesByLowerBound.get(r.lowerBound); + } + + if (candidate != null && candidate.getKey().isConnected(subRange) + && candidate.getKey().intersection(subRange).equals(r)) { + return candidate.getValue(); + } + } + } catch (ClassCastException e) { + return null; + } + return null; + } + + @Override + public Set> keySet() { + return new Maps.KeySet, V>(SubRangeMapAsMap.this) { + @Override + public boolean remove(@Nullable Object o) { + return SubRangeMapAsMap.this.remove(o) != null; + } + + @Override + public boolean retainAll(Collection c) { + return removeEntryIf(compose(not(in(c)), Maps.>keyFunction())); + } + }; + } + + @Override + public V remove(Object key) { + V value = get(key); + if (value != null) { + @SuppressWarnings("unchecked") // it's definitely in the map, so safe + Range range = (Range) key; + TreeRangeMap.this.remove(range); + return value; + } + return null; + } + + private boolean removeEntryIf(Predicate, V>> predicate) { + List> toRemove = Lists.newArrayList(); + for (Entry, V> entry : entrySet()) { + if (predicate.apply(entry)) { + toRemove.add(entry.getKey()); + } + } + for (Range range : toRemove) { + TreeRangeMap.this.remove(range); + } + return !toRemove.isEmpty(); + } + + @Override + public Collection values() { + return new Maps.Values, V>(this) { + @Override + public boolean removeAll(Collection c) { + return removeEntryIf(compose(in(c), Maps.valueFunction())); + } + + @Override + public boolean retainAll(Collection c) { + return removeEntryIf(compose(not(in(c)), Maps.valueFunction())); + } + }; + } + } + + private final Range subRange; + + SubRangeMap(Range subRange) { + this.subRange = subRange; + } + + @Override + public Map, V> asMapOfRanges() { + return new SubRangeMapAsMap(); + } + + @Override + public void clear() { + TreeRangeMap.this.remove(subRange); + } + + @Override + public boolean equals(@Nullable Object o) { + if (o instanceof RangeMap) { + RangeMap rangeMap = (RangeMap) o; + return asMapOfRanges().equals(rangeMap.asMapOfRanges()); + } + return false; + } + + @Override + @Nullable + public V get(K key) { + return subRange.contains(key) ? TreeRangeMap.this.get(key) : null; + } + + @Override + @Nullable + public Entry, V> getEntry(K key) { + if (subRange.contains(key)) { + Entry, V> entry = TreeRangeMap.this.getEntry(key); + if (entry != null) { + return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue()); + } + } + return null; + } + + @Override + public int hashCode() { + return asMapOfRanges().hashCode(); + } + + @Override + public void put(Range range, V value) { + checkArgument(subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange); + TreeRangeMap.this.put(range, value); + } + + @Override + public void putAll(RangeMap rangeMap) { + if (rangeMap.asMapOfRanges().isEmpty()) { + return; + } + Range span = rangeMap.span(); + checkArgument(subRange.encloses(span), "Cannot putAll rangeMap with span %s into a subRangeMap(%s)", span, + subRange); + TreeRangeMap.this.putAll(rangeMap); + } + + @Override + public void remove(Range range) { + if (range.isConnected(subRange)) { + TreeRangeMap.this.remove(range.intersection(subRange)); + } + } + + @Override + public Range span() { + Cut lowerBound; + Entry, RangeMapEntry> lowerEntry = entriesByLowerBound.floorEntry(subRange.lowerBound); + if (lowerEntry != null && lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) { + lowerBound = subRange.lowerBound; + } else { + lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound); + if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) { + throw new NoSuchElementException(); + } + } + + Cut upperBound; + Entry, RangeMapEntry> upperEntry = entriesByLowerBound.lowerEntry(subRange.upperBound); + if (upperEntry == null) { + throw new NoSuchElementException(); + } else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) { + upperBound = subRange.upperBound; + } else { + upperBound = upperEntry.getValue().getUpperBound(); + } + return Range.create(lowerBound, upperBound); + } + + @Override + public RangeMap subRangeMap(Range range) { + if (!range.isConnected(subRange)) { + return emptySubRangeMap(); + } else { + return TreeRangeMap.this.subRangeMap(range.intersection(subRange)); + } + } + + @Override + public String toString() { + return asMapOfRanges().toString(); + } + } + + private static final RangeMap EMPTY_SUB_RANGE_MAP = new RangeMap() { + @Override + public Map asMapOfRanges() { + return Collections.emptyMap(); + } + + @Override + public void clear() { + } + + @Override + @Nullable + public Object get(Comparable key) { + return null; + } + + @Override + @Nullable + public Entry getEntry(Comparable key) { + return null; + } + + @Override + public void put(Range range, Object value) { + checkNotNull(range); + throw new IllegalArgumentException("Cannot insert range " + range + " into an empty subRangeMap"); + } + + @Override + public void putAll(RangeMap rangeMap) { + if (!rangeMap.asMapOfRanges().isEmpty()) { + throw new IllegalArgumentException("Cannot putAll(nonEmptyRangeMap) into an empty " + "subRangeMap"); + } + } + + @Override + public void remove(Range range) { + checkNotNull(range); + } + + @Override + public Range span() { + throw new NoSuchElementException(); + } + + @Override + public RangeMap subRangeMap(Range range) { + checkNotNull(range); + return this; + } + }; + + public static TreeRangeMap create() { + return new TreeRangeMap(); + } + + private final NavigableMap, RangeMapEntry> entriesByLowerBound; + + private TreeRangeMap() { + this.entriesByLowerBound = Maps.newTreeMap(); + } + + @Override + public Map, V> asMapOfRanges() { + return new AsMapOfRanges(); + } + + @Override + public void clear() { + entriesByLowerBound.clear(); + } + + @SuppressWarnings("unchecked") + private RangeMap emptySubRangeMap() { + return EMPTY_SUB_RANGE_MAP; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o instanceof RangeMap) { + RangeMap rangeMap = (RangeMap) o; + return asMapOfRanges().equals(rangeMap.asMapOfRanges()); + } + return false; } @Override @@ -120,6 +499,11 @@ public final class TreeRangeMap implements RangeMap range, V value) { if (!range.isEmpty()) { @@ -136,21 +520,6 @@ public final class TreeRangeMap implements RangeMap span() { - Entry, RangeMapEntry> firstEntry = entriesByLowerBound.firstEntry(); - Entry, RangeMapEntry> lastEntry = entriesByLowerBound.lastEntry(); - if (firstEntry == null) { - throw new NoSuchElementException(); - } - return Range.create(firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound); - } - private void putRangeMapEntry(Cut lowerBound, Cut upperBound, V value) { entriesByLowerBound.put(lowerBound, new RangeMapEntry(lowerBound, upperBound, value)); } @@ -201,45 +570,13 @@ public final class TreeRangeMap implements RangeMap, V> asMapOfRanges() { - return new AsMapOfRanges(); - } - - private final class AsMapOfRanges extends AbstractMap, V> { - - @Override - public boolean containsKey(@Nullable Object key) { - return get(key) != null; - } - - @Override - public V get(@Nullable Object key) { - if (key instanceof Range) { - Range range = (Range) key; - RangeMapEntry rangeMapEntry = entriesByLowerBound.get(range.lowerBound); - if (rangeMapEntry != null && rangeMapEntry.getKey().equals(range)) { - return rangeMapEntry.getValue(); - } - } - return null; - } - - @Override - public Set, V>> entrySet() { - return new AbstractSet, V>>() { - - @SuppressWarnings("unchecked") // it's safe to upcast iterators - @Override - public Iterator, V>> iterator() { - return (Iterator) entriesByLowerBound.values().iterator(); - } - - @Override - public int size() { - return entriesByLowerBound.size(); - } - }; + public Range span() { + Entry, RangeMapEntry> firstEntry = entriesByLowerBound.firstEntry(); + Entry, RangeMapEntry> lastEntry = entriesByLowerBound.lastEntry(); + if (firstEntry == null) { + throw new NoSuchElementException(); } + return Range.create(firstEntry.getValue().getKey().lowerBound, lastEntry.getValue().getKey().upperBound); } @Override @@ -251,343 +588,6 @@ public final class TreeRangeMap implements RangeMap emptySubRangeMap() { - return EMPTY_SUB_RANGE_MAP; - } - - private static final RangeMap EMPTY_SUB_RANGE_MAP = new RangeMap() { - @Override - @Nullable - public Object get(Comparable key) { - return null; - } - - @Override - @Nullable - public Entry getEntry(Comparable key) { - return null; - } - - @Override - public Range span() { - throw new NoSuchElementException(); - } - - @Override - public void put(Range range, Object value) { - checkNotNull(range); - throw new IllegalArgumentException("Cannot insert range " + range + " into an empty subRangeMap"); - } - - @Override - public void putAll(RangeMap rangeMap) { - if (!rangeMap.asMapOfRanges().isEmpty()) { - throw new IllegalArgumentException("Cannot putAll(nonEmptyRangeMap) into an empty " + "subRangeMap"); - } - } - - @Override - public void clear() { - } - - @Override - public void remove(Range range) { - checkNotNull(range); - } - - @Override - public Map asMapOfRanges() { - return Collections.emptyMap(); - } - - @Override - public RangeMap subRangeMap(Range range) { - checkNotNull(range); - return this; - } - }; - - private class SubRangeMap implements RangeMap { - - private final Range subRange; - - SubRangeMap(Range subRange) { - this.subRange = subRange; - } - - @Override - @Nullable - public V get(K key) { - return subRange.contains(key) ? TreeRangeMap.this.get(key) : null; - } - - @Override - @Nullable - public Entry, V> getEntry(K key) { - if (subRange.contains(key)) { - Entry, V> entry = TreeRangeMap.this.getEntry(key); - if (entry != null) { - return Maps.immutableEntry(entry.getKey().intersection(subRange), entry.getValue()); - } - } - return null; - } - - @Override - public Range span() { - Cut lowerBound; - Entry, RangeMapEntry> lowerEntry = entriesByLowerBound.floorEntry(subRange.lowerBound); - if (lowerEntry != null && lowerEntry.getValue().getUpperBound().compareTo(subRange.lowerBound) > 0) { - lowerBound = subRange.lowerBound; - } else { - lowerBound = entriesByLowerBound.ceilingKey(subRange.lowerBound); - if (lowerBound == null || lowerBound.compareTo(subRange.upperBound) >= 0) { - throw new NoSuchElementException(); - } - } - - Cut upperBound; - Entry, RangeMapEntry> upperEntry = entriesByLowerBound.lowerEntry(subRange.upperBound); - if (upperEntry == null) { - throw new NoSuchElementException(); - } else if (upperEntry.getValue().getUpperBound().compareTo(subRange.upperBound) >= 0) { - upperBound = subRange.upperBound; - } else { - upperBound = upperEntry.getValue().getUpperBound(); - } - return Range.create(lowerBound, upperBound); - } - - @Override - public void put(Range range, V value) { - checkArgument(subRange.encloses(range), "Cannot put range %s into a subRangeMap(%s)", range, subRange); - TreeRangeMap.this.put(range, value); - } - - @Override - public void putAll(RangeMap rangeMap) { - if (rangeMap.asMapOfRanges().isEmpty()) { - return; - } - Range span = rangeMap.span(); - checkArgument(subRange.encloses(span), "Cannot putAll rangeMap with span %s into a subRangeMap(%s)", span, - subRange); - TreeRangeMap.this.putAll(rangeMap); - } - - @Override - public void clear() { - TreeRangeMap.this.remove(subRange); - } - - @Override - public void remove(Range range) { - if (range.isConnected(subRange)) { - TreeRangeMap.this.remove(range.intersection(subRange)); - } - } - - @Override - public RangeMap subRangeMap(Range range) { - if (!range.isConnected(subRange)) { - return emptySubRangeMap(); - } else { - return TreeRangeMap.this.subRangeMap(range.intersection(subRange)); - } - } - - @Override - public Map, V> asMapOfRanges() { - return new SubRangeMapAsMap(); - } - - @Override - public boolean equals(@Nullable Object o) { - if (o instanceof RangeMap) { - RangeMap rangeMap = (RangeMap) o; - return asMapOfRanges().equals(rangeMap.asMapOfRanges()); - } - return false; - } - - @Override - public int hashCode() { - return asMapOfRanges().hashCode(); - } - - @Override - public String toString() { - return asMapOfRanges().toString(); - } - - class SubRangeMapAsMap extends AbstractMap, V> { - - @Override - public boolean containsKey(Object key) { - return get(key) != null; - } - - @Override - public V get(Object key) { - try { - if (key instanceof Range) { - @SuppressWarnings("unchecked") // we catch ClassCastExceptions - Range r = (Range) key; - if (!subRange.encloses(r) || r.isEmpty()) { - return null; - } - RangeMapEntry candidate = null; - if (r.lowerBound.compareTo(subRange.lowerBound) == 0) { - // r could be truncated on the left - Entry, RangeMapEntry> entry = entriesByLowerBound.floorEntry(r.lowerBound); - if (entry != null) { - candidate = entry.getValue(); - } - } else { - candidate = entriesByLowerBound.get(r.lowerBound); - } - - if (candidate != null && candidate.getKey().isConnected(subRange) - && candidate.getKey().intersection(subRange).equals(r)) { - return candidate.getValue(); - } - } - } catch (ClassCastException e) { - return null; - } - return null; - } - - @Override - public V remove(Object key) { - V value = get(key); - if (value != null) { - @SuppressWarnings("unchecked") // it's definitely in the map, so safe - Range range = (Range) key; - TreeRangeMap.this.remove(range); - return value; - } - return null; - } - - @Override - public void clear() { - SubRangeMap.this.clear(); - } - - private boolean removeEntryIf(Predicate, V>> predicate) { - List> toRemove = Lists.newArrayList(); - for (Entry, V> entry : entrySet()) { - if (predicate.apply(entry)) { - toRemove.add(entry.getKey()); - } - } - for (Range range : toRemove) { - TreeRangeMap.this.remove(range); - } - return !toRemove.isEmpty(); - } - - @Override - public Set> keySet() { - return new Maps.KeySet, V>(SubRangeMapAsMap.this) { - @Override - public boolean remove(@Nullable Object o) { - return SubRangeMapAsMap.this.remove(o) != null; - } - - @Override - public boolean retainAll(Collection c) { - return removeEntryIf(compose(not(in(c)), Maps.>keyFunction())); - } - }; - } - - @Override - public Set, V>> entrySet() { - return new Maps.EntrySet, V>() { - @Override - Map, V> map() { - return SubRangeMapAsMap.this; - } - - @Override - public Iterator, V>> iterator() { - if (subRange.isEmpty()) { - return Iterators.emptyIterator(); - } - Cut cutToStart = Objects.firstNonNull(entriesByLowerBound.floorKey(subRange.lowerBound), - subRange.lowerBound); - final Iterator> backingItr = entriesByLowerBound.tailMap(cutToStart, true) - .values().iterator(); - return new AbstractIterator, V>>() { - - @Override - protected Entry, V> computeNext() { - while (backingItr.hasNext()) { - RangeMapEntry entry = backingItr.next(); - if (entry.getLowerBound().compareTo(subRange.upperBound) >= 0) { - break; - } else if (entry.getUpperBound().compareTo(subRange.lowerBound) > 0) { - // this might not be true e.g. at the start of the iteration - return Maps.immutableEntry(entry.getKey().intersection(subRange), - entry.getValue()); - } - } - return endOfData(); - } - }; - } - - @Override - public boolean retainAll(Collection c) { - return removeEntryIf(not(in(c))); - } - - @Override - public int size() { - return Iterators.size(iterator()); - } - - @Override - public boolean isEmpty() { - return !iterator().hasNext(); - } - }; - } - - @Override - public Collection values() { - return new Maps.Values, V>(this) { - @Override - public boolean removeAll(Collection c) { - return removeEntryIf(compose(in(c), Maps.valueFunction())); - } - - @Override - public boolean retainAll(Collection c) { - return removeEntryIf(compose(not(in(c)), Maps.valueFunction())); - } - }; - } - } - } - - @Override - public boolean equals(@Nullable Object o) { - if (o instanceof RangeMap) { - RangeMap rangeMap = (RangeMap) o; - return asMapOfRanges().equals(rangeMap.asMapOfRanges()); - } - return false; - } - - @Override - public int hashCode() { - return asMapOfRanges().hashCode(); - } - @Override public String toString() { return entriesByLowerBound.values().toString(); diff --git a/src/main/java/com/google/common/collect/TreeRangeSet.java b/src/main/java/com/google/common/collect/TreeRangeSet.java index aec1eae0..7c67e8fe 100644 --- a/src/main/java/com/google/common/collect/TreeRangeSet.java +++ b/src/main/java/com/google/common/collect/TreeRangeSet.java @@ -43,342 +43,46 @@ import com.google.common.base.Objects; @GwtIncompatible("uses NavigableMap") public class TreeRangeSet> extends AbstractRangeSet { - @VisibleForTesting - final NavigableMap, Range> rangesByLowerBound; - - /** - * Creates an empty {@code TreeRangeSet} instance. - */ - public static > TreeRangeSet create() { - return new TreeRangeSet(new TreeMap, Range>()); - } - - /** - * Returns a {@code TreeRangeSet} initialized with the ranges in the specified - * range set. - */ - public static > TreeRangeSet create(RangeSet rangeSet) { - TreeRangeSet result = create(); - result.addAll(rangeSet); - return result; - } - - private TreeRangeSet(NavigableMap, Range> rangesByLowerCut) { - this.rangesByLowerBound = rangesByLowerCut; - } - - private transient Set> asRanges; - - @Override - public Set> asRanges() { - Set> result = asRanges; - return (result == null) ? asRanges = new AsRanges() : result; - } - final class AsRanges extends ForwardingCollection> implements Set> { @Override protected Collection> delegate() { return rangesByLowerBound.values(); } - @Override - public int hashCode() { - return Sets.hashCodeImpl(this); - } - @Override public boolean equals(@Nullable Object o) { return Sets.equalsImpl(this, o); } - } - @Override - @Nullable - public Range rangeContaining(C value) { - checkNotNull(value); - Entry, Range> floorEntry = rangesByLowerBound.floorEntry(Cut.belowValue(value)); - if (floorEntry != null && floorEntry.getValue().contains(value)) { - return floorEntry.getValue(); - } else { - // TODO(kevinb): revisit this design choice - return null; + @Override + public int hashCode() { + return Sets.hashCodeImpl(this); } } - @Override - public boolean encloses(Range range) { - checkNotNull(range); - Entry, Range> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); - return floorEntry != null && floorEntry.getValue().encloses(range); - } - - @Nullable - private Range rangeEnclosing(Range range) { - checkNotNull(range); - Entry, Range> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); - return (floorEntry != null && floorEntry.getValue().encloses(range)) ? floorEntry.getValue() : null; - } - - @Override - public Range span() { - Entry, Range> firstEntry = rangesByLowerBound.firstEntry(); - Entry, Range> lastEntry = rangesByLowerBound.lastEntry(); - if (firstEntry == null) { - throw new NoSuchElementException(); - } - return Range.create(firstEntry.getValue().lowerBound, lastEntry.getValue().upperBound); - } - - @Override - public void add(Range rangeToAdd) { - checkNotNull(rangeToAdd); - - if (rangeToAdd.isEmpty()) { - return; - } - - // We will use { } to illustrate ranges currently in the range set, and < > - // to illustrate rangeToAdd. - Cut lbToAdd = rangeToAdd.lowerBound; - Cut ubToAdd = rangeToAdd.upperBound; - - Entry, Range> entryBelowLB = rangesByLowerBound.lowerEntry(lbToAdd); - if (entryBelowLB != null) { - // { < - Range rangeBelowLB = entryBelowLB.getValue(); - if (rangeBelowLB.upperBound.compareTo(lbToAdd) >= 0) { - // { < }, and we will need to coalesce - if (rangeBelowLB.upperBound.compareTo(ubToAdd) >= 0) { - // { < > } - ubToAdd = rangeBelowLB.upperBound; - /* - * TODO(cpovirk): can we just "return;" here? Or, can we remove this if() - * entirely? If not, add tests to demonstrate the problem with each approach - */ - } - lbToAdd = rangeBelowLB.lowerBound; - } - } - - Entry, Range> entryBelowUB = rangesByLowerBound.floorEntry(ubToAdd); - if (entryBelowUB != null) { - // { > - Range rangeBelowUB = entryBelowUB.getValue(); - if (rangeBelowUB.upperBound.compareTo(ubToAdd) >= 0) { - // { > }, and we need to coalesce - ubToAdd = rangeBelowUB.upperBound; - } - } - - // Remove ranges which are strictly enclosed. - rangesByLowerBound.subMap(lbToAdd, ubToAdd).clear(); - - replaceRangeWithSameLowerBound(Range.create(lbToAdd, ubToAdd)); - } - - @Override - public void remove(Range rangeToRemove) { - checkNotNull(rangeToRemove); - - if (rangeToRemove.isEmpty()) { - return; - } - - // We will use { } to illustrate ranges currently in the range set, and < > - // to illustrate rangeToRemove. - - Entry, Range> entryBelowLB = rangesByLowerBound.lowerEntry(rangeToRemove.lowerBound); - if (entryBelowLB != null) { - // { < - Range rangeBelowLB = entryBelowLB.getValue(); - if (rangeBelowLB.upperBound.compareTo(rangeToRemove.lowerBound) >= 0) { - // { < }, and we will need to subdivide - if (rangeToRemove.hasUpperBound() && rangeBelowLB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { - // { < > } - replaceRangeWithSameLowerBound(Range.create(rangeToRemove.upperBound, rangeBelowLB.upperBound)); - } - replaceRangeWithSameLowerBound(Range.create(rangeBelowLB.lowerBound, rangeToRemove.lowerBound)); - } - } - - Entry, Range> entryBelowUB = rangesByLowerBound.floorEntry(rangeToRemove.upperBound); - if (entryBelowUB != null) { - // { > - Range rangeBelowUB = entryBelowUB.getValue(); - if (rangeToRemove.hasUpperBound() && rangeBelowUB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { - // { > } - replaceRangeWithSameLowerBound(Range.create(rangeToRemove.upperBound, rangeBelowUB.upperBound)); - } - } - - rangesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); - } - - private void replaceRangeWithSameLowerBound(Range range) { - if (range.isEmpty()) { - rangesByLowerBound.remove(range.lowerBound); - } else { - rangesByLowerBound.put(range.lowerBound, range); - } - } - - private transient RangeSet complement; - - @Override - public RangeSet complement() { - RangeSet result = complement; - return (result == null) ? complement = new Complement() : result; - } - - @VisibleForTesting - static final class RangesByUpperBound> extends AbstractNavigableMap, Range> { - private final NavigableMap, Range> rangesByLowerBound; - - /** - * upperBoundWindow represents the headMap/subMap/tailMap view of the entire - * "ranges by upper bound" map; it's a constraint on the *keys*, and does not - * affect the values. - */ - private final Range> upperBoundWindow; - - RangesByUpperBound(NavigableMap, Range> rangesByLowerBound) { - this.rangesByLowerBound = rangesByLowerBound; - this.upperBoundWindow = Range.all(); - } - - private RangesByUpperBound(NavigableMap, Range> rangesByLowerBound, Range> upperBoundWindow) { - this.rangesByLowerBound = rangesByLowerBound; - this.upperBoundWindow = upperBoundWindow; - } - - private NavigableMap, Range> subMap(Range> window) { - if (window.isConnected(upperBoundWindow)) { - return new RangesByUpperBound(rangesByLowerBound, window.intersection(upperBoundWindow)); - } else { - return ImmutableSortedMap.of(); - } + private final class Complement extends TreeRangeSet { + Complement() { + super(new ComplementRangesByLowerBound(TreeRangeSet.this.rangesByLowerBound)); } @Override - public NavigableMap, Range> subMap(Cut fromKey, boolean fromInclusive, Cut toKey, - boolean toInclusive) { - return subMap(Range.range(fromKey, BoundType.forBoolean(fromInclusive), toKey, - BoundType.forBoolean(toInclusive))); + public void add(Range rangeToAdd) { + TreeRangeSet.this.remove(rangeToAdd); } @Override - public NavigableMap, Range> headMap(Cut toKey, boolean inclusive) { - return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); + public RangeSet complement() { + return TreeRangeSet.this; } @Override - public NavigableMap, Range> tailMap(Cut fromKey, boolean inclusive) { - return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); + public boolean contains(C value) { + return !TreeRangeSet.this.contains(value); } @Override - public Comparator> comparator() { - return Ordering.>natural(); - } - - @Override - public boolean containsKey(@Nullable Object key) { - return get(key) != null; - } - - @Override - public Range get(@Nullable Object key) { - if (key instanceof Cut) { - try { - @SuppressWarnings("unchecked") // we catch CCEs - Cut cut = (Cut) key; - if (!upperBoundWindow.contains(cut)) { - return null; - } - Entry, Range> candidate = rangesByLowerBound.lowerEntry(cut); - if (candidate != null && candidate.getValue().upperBound.equals(cut)) { - return candidate.getValue(); - } - } catch (ClassCastException e) { - return null; - } - } - return null; - } - - @Override - Iterator, Range>> entryIterator() { - /* - * We want to start the iteration at the first range where the upper bound is in - * upperBoundWindow. - */ - final Iterator> backingItr; - if (!upperBoundWindow.hasLowerBound()) { - backingItr = rangesByLowerBound.values().iterator(); - } else { - Entry, Range> lowerEntry = rangesByLowerBound.lowerEntry(upperBoundWindow.lowerEndpoint()); - if (lowerEntry == null) { - backingItr = rangesByLowerBound.values().iterator(); - } else if (upperBoundWindow.lowerBound.isLessThan(lowerEntry.getValue().upperBound)) { - backingItr = rangesByLowerBound.tailMap(lowerEntry.getKey(), true).values().iterator(); - } else { - backingItr = rangesByLowerBound.tailMap(upperBoundWindow.lowerEndpoint(), true).values().iterator(); - } - } - return new AbstractIterator, Range>>() { - @Override - protected Entry, Range> computeNext() { - if (!backingItr.hasNext()) { - return endOfData(); - } - Range range = backingItr.next(); - if (upperBoundWindow.upperBound.isLessThan(range.upperBound)) { - return endOfData(); - } else { - return Maps.immutableEntry(range.upperBound, range); - } - } - }; - } - - @Override - Iterator, Range>> descendingEntryIterator() { - Collection> candidates; - if (upperBoundWindow.hasUpperBound()) { - candidates = rangesByLowerBound.headMap(upperBoundWindow.upperEndpoint(), false).descendingMap() - .values(); - } else { - candidates = rangesByLowerBound.descendingMap().values(); - } - final PeekingIterator> backingItr = Iterators.peekingIterator(candidates.iterator()); - if (backingItr.hasNext() && upperBoundWindow.upperBound.isLessThan(backingItr.peek().upperBound)) { - backingItr.next(); - } - return new AbstractIterator, Range>>() { - @Override - protected Entry, Range> computeNext() { - if (!backingItr.hasNext()) { - return endOfData(); - } - Range range = backingItr.next(); - return upperBoundWindow.lowerBound.isLessThan(range.upperBound) - ? Maps.immutableEntry(range.upperBound, range) - : endOfData(); - } - }; - } - - @Override - public int size() { - if (upperBoundWindow.equals(Range.all())) { - return rangesByLowerBound.size(); - } - return Iterators.size(entryIterator()); - } - - @Override - public boolean isEmpty() { - return upperBoundWindow.equals(Range.all()) ? rangesByLowerBound.isEmpty() : !entryIterator().hasNext(); + public void remove(Range rangeToRemove) { + TreeRangeSet.this.add(rangeToRemove); } } @@ -405,86 +109,14 @@ public class TreeRangeSet> extends AbstractRangeSet { this.complementLowerBoundWindow = window; } - private NavigableMap, Range> subMap(Range> subWindow) { - if (!complementLowerBoundWindow.isConnected(subWindow)) { - return ImmutableSortedMap.of(); - } else { - subWindow = subWindow.intersection(complementLowerBoundWindow); - return new ComplementRangesByLowerBound(positiveRangesByLowerBound, subWindow); - } - } - - @Override - public NavigableMap, Range> subMap(Cut fromKey, boolean fromInclusive, Cut toKey, - boolean toInclusive) { - return subMap(Range.range(fromKey, BoundType.forBoolean(fromInclusive), toKey, - BoundType.forBoolean(toInclusive))); - } - - @Override - public NavigableMap, Range> headMap(Cut toKey, boolean inclusive) { - return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); - } - - @Override - public NavigableMap, Range> tailMap(Cut fromKey, boolean inclusive) { - return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); - } - @Override public Comparator> comparator() { return Ordering.>natural(); } @Override - Iterator, Range>> entryIterator() { - /* - * firstComplementRangeLowerBound is the first complement range lower bound - * inside complementLowerBoundWindow. Complement range lower bounds are either - * positive range upper bounds, or Cut.belowAll(). - * - * positiveItr starts at the first positive range with lower bound greater than - * firstComplementRangeLowerBound. (Positive range lower bounds correspond to - * complement range upper bounds.) - */ - Collection> positiveRanges; - if (complementLowerBoundWindow.hasLowerBound()) { - positiveRanges = positiveRangesByUpperBound.tailMap(complementLowerBoundWindow.lowerEndpoint(), - complementLowerBoundWindow.lowerBoundType() == BoundType.CLOSED).values(); - } else { - positiveRanges = positiveRangesByUpperBound.values(); - } - final PeekingIterator> positiveItr = Iterators.peekingIterator(positiveRanges.iterator()); - final Cut firstComplementRangeLowerBound; - if (complementLowerBoundWindow.contains(Cut.belowAll()) - && (!positiveItr.hasNext() || positiveItr.peek().lowerBound != Cut.belowAll())) { - firstComplementRangeLowerBound = Cut.belowAll(); - } else if (positiveItr.hasNext()) { - firstComplementRangeLowerBound = positiveItr.next().upperBound; - } else { - return Iterators.emptyIterator(); - } - return new AbstractIterator, Range>>() { - Cut nextComplementRangeLowerBound = firstComplementRangeLowerBound; - - @Override - protected Entry, Range> computeNext() { - if (complementLowerBoundWindow.upperBound.isLessThan(nextComplementRangeLowerBound) - || nextComplementRangeLowerBound == Cut.aboveAll()) { - return endOfData(); - } - Range negativeRange; - if (positiveItr.hasNext()) { - Range positiveRange = positiveItr.next(); - negativeRange = Range.create(nextComplementRangeLowerBound, positiveRange.lowerBound); - nextComplementRangeLowerBound = positiveRange.upperBound; - } else { - negativeRange = Range.create(nextComplementRangeLowerBound, Cut.aboveAll()); - nextComplementRangeLowerBound = Cut.aboveAll(); - } - return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); - } - }; + public boolean containsKey(Object key) { + return get(key) != null; } @Override @@ -541,8 +173,54 @@ public class TreeRangeSet> extends AbstractRangeSet { } @Override - public int size() { - return Iterators.size(entryIterator()); + Iterator, Range>> entryIterator() { + /* + * firstComplementRangeLowerBound is the first complement range lower bound + * inside complementLowerBoundWindow. Complement range lower bounds are either + * positive range upper bounds, or Cut.belowAll(). + * + * positiveItr starts at the first positive range with lower bound greater than + * firstComplementRangeLowerBound. (Positive range lower bounds correspond to + * complement range upper bounds.) + */ + Collection> positiveRanges; + if (complementLowerBoundWindow.hasLowerBound()) { + positiveRanges = positiveRangesByUpperBound.tailMap(complementLowerBoundWindow.lowerEndpoint(), + complementLowerBoundWindow.lowerBoundType() == BoundType.CLOSED).values(); + } else { + positiveRanges = positiveRangesByUpperBound.values(); + } + final PeekingIterator> positiveItr = Iterators.peekingIterator(positiveRanges.iterator()); + final Cut firstComplementRangeLowerBound; + if (complementLowerBoundWindow.contains(Cut.belowAll()) + && (!positiveItr.hasNext() || positiveItr.peek().lowerBound != Cut.belowAll())) { + firstComplementRangeLowerBound = Cut.belowAll(); + } else if (positiveItr.hasNext()) { + firstComplementRangeLowerBound = positiveItr.next().upperBound; + } else { + return Iterators.emptyIterator(); + } + return new AbstractIterator, Range>>() { + Cut nextComplementRangeLowerBound = firstComplementRangeLowerBound; + + @Override + protected Entry, Range> computeNext() { + if (complementLowerBoundWindow.upperBound.isLessThan(nextComplementRangeLowerBound) + || nextComplementRangeLowerBound == Cut.aboveAll()) { + return endOfData(); + } + Range negativeRange; + if (positiveItr.hasNext()) { + Range positiveRange = positiveItr.next(); + negativeRange = Range.create(nextComplementRangeLowerBound, positiveRange.lowerBound); + nextComplementRangeLowerBound = positiveRange.upperBound; + } else { + negativeRange = Range.create(nextComplementRangeLowerBound, Cut.aboveAll()); + nextComplementRangeLowerBound = Cut.aboveAll(); + } + return Maps.immutableEntry(negativeRange.lowerBound, negativeRange); + } + }; } @Override @@ -565,34 +243,250 @@ public class TreeRangeSet> extends AbstractRangeSet { } @Override - public boolean containsKey(Object key) { - return get(key) != null; + public NavigableMap, Range> headMap(Cut toKey, boolean inclusive) { + return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); + } + + @Override + public int size() { + return Iterators.size(entryIterator()); + } + + @Override + public NavigableMap, Range> subMap(Cut fromKey, boolean fromInclusive, Cut toKey, + boolean toInclusive) { + return subMap(Range.range(fromKey, BoundType.forBoolean(fromInclusive), toKey, + BoundType.forBoolean(toInclusive))); + } + + private NavigableMap, Range> subMap(Range> subWindow) { + if (!complementLowerBoundWindow.isConnected(subWindow)) { + return ImmutableSortedMap.of(); + } else { + subWindow = subWindow.intersection(complementLowerBoundWindow); + return new ComplementRangesByLowerBound(positiveRangesByLowerBound, subWindow); + } + } + + @Override + public NavigableMap, Range> tailMap(Cut fromKey, boolean inclusive) { + return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); } } - private final class Complement extends TreeRangeSet { - Complement() { - super(new ComplementRangesByLowerBound(TreeRangeSet.this.rangesByLowerBound)); + @VisibleForTesting + static final class RangesByUpperBound> extends AbstractNavigableMap, Range> { + private final NavigableMap, Range> rangesByLowerBound; + + /** + * upperBoundWindow represents the headMap/subMap/tailMap view of the entire + * "ranges by upper bound" map; it's a constraint on the *keys*, and does not + * affect the values. + */ + private final Range> upperBoundWindow; + + RangesByUpperBound(NavigableMap, Range> rangesByLowerBound) { + this.rangesByLowerBound = rangesByLowerBound; + this.upperBoundWindow = Range.all(); + } + + private RangesByUpperBound(NavigableMap, Range> rangesByLowerBound, Range> upperBoundWindow) { + this.rangesByLowerBound = rangesByLowerBound; + this.upperBoundWindow = upperBoundWindow; + } + + @Override + public Comparator> comparator() { + return Ordering.>natural(); + } + + @Override + public boolean containsKey(@Nullable Object key) { + return get(key) != null; + } + + @Override + Iterator, Range>> descendingEntryIterator() { + Collection> candidates; + if (upperBoundWindow.hasUpperBound()) { + candidates = rangesByLowerBound.headMap(upperBoundWindow.upperEndpoint(), false).descendingMap() + .values(); + } else { + candidates = rangesByLowerBound.descendingMap().values(); + } + final PeekingIterator> backingItr = Iterators.peekingIterator(candidates.iterator()); + if (backingItr.hasNext() && upperBoundWindow.upperBound.isLessThan(backingItr.peek().upperBound)) { + backingItr.next(); + } + return new AbstractIterator, Range>>() { + @Override + protected Entry, Range> computeNext() { + if (!backingItr.hasNext()) { + return endOfData(); + } + Range range = backingItr.next(); + return upperBoundWindow.lowerBound.isLessThan(range.upperBound) + ? Maps.immutableEntry(range.upperBound, range) + : endOfData(); + } + }; + } + + @Override + Iterator, Range>> entryIterator() { + /* + * We want to start the iteration at the first range where the upper bound is in + * upperBoundWindow. + */ + final Iterator> backingItr; + if (!upperBoundWindow.hasLowerBound()) { + backingItr = rangesByLowerBound.values().iterator(); + } else { + Entry, Range> lowerEntry = rangesByLowerBound.lowerEntry(upperBoundWindow.lowerEndpoint()); + if (lowerEntry == null) { + backingItr = rangesByLowerBound.values().iterator(); + } else if (upperBoundWindow.lowerBound.isLessThan(lowerEntry.getValue().upperBound)) { + backingItr = rangesByLowerBound.tailMap(lowerEntry.getKey(), true).values().iterator(); + } else { + backingItr = rangesByLowerBound.tailMap(upperBoundWindow.lowerEndpoint(), true).values().iterator(); + } + } + return new AbstractIterator, Range>>() { + @Override + protected Entry, Range> computeNext() { + if (!backingItr.hasNext()) { + return endOfData(); + } + Range range = backingItr.next(); + if (upperBoundWindow.upperBound.isLessThan(range.upperBound)) { + return endOfData(); + } else { + return Maps.immutableEntry(range.upperBound, range); + } + } + }; + } + + @Override + public Range get(@Nullable Object key) { + if (key instanceof Cut) { + try { + @SuppressWarnings("unchecked") // we catch CCEs + Cut cut = (Cut) key; + if (!upperBoundWindow.contains(cut)) { + return null; + } + Entry, Range> candidate = rangesByLowerBound.lowerEntry(cut); + if (candidate != null && candidate.getValue().upperBound.equals(cut)) { + return candidate.getValue(); + } + } catch (ClassCastException e) { + return null; + } + } + return null; + } + + @Override + public NavigableMap, Range> headMap(Cut toKey, boolean inclusive) { + return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); + } + + @Override + public boolean isEmpty() { + return upperBoundWindow.equals(Range.all()) ? rangesByLowerBound.isEmpty() : !entryIterator().hasNext(); + } + + @Override + public int size() { + if (upperBoundWindow.equals(Range.all())) { + return rangesByLowerBound.size(); + } + return Iterators.size(entryIterator()); + } + + @Override + public NavigableMap, Range> subMap(Cut fromKey, boolean fromInclusive, Cut toKey, + boolean toInclusive) { + return subMap(Range.range(fromKey, BoundType.forBoolean(fromInclusive), toKey, + BoundType.forBoolean(toInclusive))); + } + + private NavigableMap, Range> subMap(Range> window) { + if (window.isConnected(upperBoundWindow)) { + return new RangesByUpperBound(rangesByLowerBound, window.intersection(upperBoundWindow)); + } else { + return ImmutableSortedMap.of(); + } + } + + @Override + public NavigableMap, Range> tailMap(Cut fromKey, boolean inclusive) { + return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); + } + } + + private final class SubRangeSet extends TreeRangeSet { + private final Range restriction; + + SubRangeSet(Range restriction) { + super(new SubRangeSetRangesByLowerBound(Range.>all(), restriction, + TreeRangeSet.this.rangesByLowerBound)); + this.restriction = restriction; } @Override public void add(Range rangeToAdd) { - TreeRangeSet.this.remove(rangeToAdd); + checkArgument(restriction.encloses(rangeToAdd), "Cannot add range %s to subRangeSet(%s)", rangeToAdd, + restriction); + super.add(rangeToAdd); } @Override - public void remove(Range rangeToRemove) { - TreeRangeSet.this.add(rangeToRemove); + public void clear() { + TreeRangeSet.this.remove(restriction); } @Override public boolean contains(C value) { - return !TreeRangeSet.this.contains(value); + return restriction.contains(value) && TreeRangeSet.this.contains(value); } @Override - public RangeSet complement() { - return TreeRangeSet.this; + public boolean encloses(Range range) { + if (!restriction.isEmpty() && restriction.encloses(range)) { + Range enclosing = TreeRangeSet.this.rangeEnclosing(range); + return enclosing != null && !enclosing.intersection(restriction).isEmpty(); + } + return false; + } + + @Override + @Nullable + public Range rangeContaining(C value) { + if (!restriction.contains(value)) { + return null; + } + Range result = TreeRangeSet.this.rangeContaining(value); + return (result == null) ? null : result.intersection(restriction); + } + + @Override + public void remove(Range rangeToRemove) { + if (rangeToRemove.isConnected(restriction)) { + TreeRangeSet.this.remove(rangeToRemove.intersection(restriction)); + } + } + + @Override + public RangeSet subRangeSet(Range view) { + if (view.encloses(restriction)) { + return this; + } else if (view.isConnected(restriction)) { + return new SubRangeSet(restriction.intersection(view)); + } else { + return ImmutableRangeSet.of(); + } } } @@ -621,32 +515,6 @@ public class TreeRangeSet> extends AbstractRangeSet { this.rangesByUpperBound = new RangesByUpperBound(rangesByLowerBound); } - private NavigableMap, Range> subMap(Range> window) { - if (!window.isConnected(lowerBoundWindow)) { - return ImmutableSortedMap.of(); - } else { - return new SubRangeSetRangesByLowerBound(lowerBoundWindow.intersection(window), restriction, - rangesByLowerBound); - } - } - - @Override - public NavigableMap, Range> subMap(Cut fromKey, boolean fromInclusive, Cut toKey, - boolean toInclusive) { - return subMap(Range.range(fromKey, BoundType.forBoolean(fromInclusive), toKey, - BoundType.forBoolean(toInclusive))); - } - - @Override - public NavigableMap, Range> headMap(Cut toKey, boolean inclusive) { - return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); - } - - @Override - public NavigableMap, Range> tailMap(Cut fromKey, boolean inclusive) { - return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); - } - @Override public Comparator> comparator() { return Ordering.>natural(); @@ -658,32 +526,34 @@ public class TreeRangeSet> extends AbstractRangeSet { } @Override - @Nullable - public Range get(@Nullable Object key) { - if (key instanceof Cut) { - try { - @SuppressWarnings("unchecked") // we catch CCE's - Cut cut = (Cut) key; - if (!lowerBoundWindow.contains(cut) || cut.compareTo(restriction.lowerBound) < 0 - || cut.compareTo(restriction.upperBound) >= 0) { - return null; - } else if (cut.equals(restriction.lowerBound)) { - // it might be present, truncated on the left - Range candidate = Maps.valueOrNull(rangesByLowerBound.floorEntry(cut)); - if (candidate != null && candidate.upperBound.compareTo(restriction.lowerBound) > 0) { - return candidate.intersection(restriction); - } - } else { - Range result = rangesByLowerBound.get(cut); - if (result != null) { - return result.intersection(restriction); - } - } - } catch (ClassCastException e) { - return null; - } + Iterator, Range>> descendingEntryIterator() { + if (restriction.isEmpty()) { + return Iterators.emptyIterator(); } - return null; + Cut> upperBoundOnLowerBounds = Ordering.natural().min(lowerBoundWindow.upperBound, + Cut.belowValue(restriction.upperBound)); + final Iterator> completeRangeItr = rangesByLowerBound + .headMap(upperBoundOnLowerBounds.endpoint(), + upperBoundOnLowerBounds.typeAsUpperBound() == BoundType.CLOSED) + .descendingMap().values().iterator(); + return new AbstractIterator, Range>>() { + @Override + protected Entry, Range> computeNext() { + if (!completeRangeItr.hasNext()) { + return endOfData(); + } + Range nextRange = completeRangeItr.next(); + if (restriction.lowerBound.compareTo(nextRange.upperBound) >= 0) { + return endOfData(); + } + nextRange = nextRange.intersection(restriction); + if (lowerBoundWindow.contains(nextRange.lowerBound)) { + return Maps.immutableEntry(nextRange.lowerBound, nextRange); + } else { + return endOfData(); + } + } + }; } @Override @@ -723,108 +593,238 @@ public class TreeRangeSet> extends AbstractRangeSet { } @Override - Iterator, Range>> descendingEntryIterator() { - if (restriction.isEmpty()) { - return Iterators.emptyIterator(); - } - Cut> upperBoundOnLowerBounds = Ordering.natural().min(lowerBoundWindow.upperBound, - Cut.belowValue(restriction.upperBound)); - final Iterator> completeRangeItr = rangesByLowerBound - .headMap(upperBoundOnLowerBounds.endpoint(), - upperBoundOnLowerBounds.typeAsUpperBound() == BoundType.CLOSED) - .descendingMap().values().iterator(); - return new AbstractIterator, Range>>() { - @Override - protected Entry, Range> computeNext() { - if (!completeRangeItr.hasNext()) { - return endOfData(); - } - Range nextRange = completeRangeItr.next(); - if (restriction.lowerBound.compareTo(nextRange.upperBound) >= 0) { - return endOfData(); - } - nextRange = nextRange.intersection(restriction); - if (lowerBoundWindow.contains(nextRange.lowerBound)) { - return Maps.immutableEntry(nextRange.lowerBound, nextRange); + @Nullable + public Range get(@Nullable Object key) { + if (key instanceof Cut) { + try { + @SuppressWarnings("unchecked") // we catch CCE's + Cut cut = (Cut) key; + if (!lowerBoundWindow.contains(cut) || cut.compareTo(restriction.lowerBound) < 0 + || cut.compareTo(restriction.upperBound) >= 0) { + return null; + } else if (cut.equals(restriction.lowerBound)) { + // it might be present, truncated on the left + Range candidate = Maps.valueOrNull(rangesByLowerBound.floorEntry(cut)); + if (candidate != null && candidate.upperBound.compareTo(restriction.lowerBound) > 0) { + return candidate.intersection(restriction); + } } else { - return endOfData(); + Range result = rangesByLowerBound.get(cut); + if (result != null) { + return result.intersection(restriction); + } } + } catch (ClassCastException e) { + return null; } - }; + } + return null; + } + + @Override + public NavigableMap, Range> headMap(Cut toKey, boolean inclusive) { + return subMap(Range.upTo(toKey, BoundType.forBoolean(inclusive))); } @Override public int size() { return Iterators.size(entryIterator()); } + + @Override + public NavigableMap, Range> subMap(Cut fromKey, boolean fromInclusive, Cut toKey, + boolean toInclusive) { + return subMap(Range.range(fromKey, BoundType.forBoolean(fromInclusive), toKey, + BoundType.forBoolean(toInclusive))); + } + + private NavigableMap, Range> subMap(Range> window) { + if (!window.isConnected(lowerBoundWindow)) { + return ImmutableSortedMap.of(); + } else { + return new SubRangeSetRangesByLowerBound(lowerBoundWindow.intersection(window), restriction, + rangesByLowerBound); + } + } + + @Override + public NavigableMap, Range> tailMap(Cut fromKey, boolean inclusive) { + return subMap(Range.downTo(fromKey, BoundType.forBoolean(inclusive))); + } + } + + /** + * Creates an empty {@code TreeRangeSet} instance. + */ + public static > TreeRangeSet create() { + return new TreeRangeSet(new TreeMap, Range>()); + } + + /** + * Returns a {@code TreeRangeSet} initialized with the ranges in the specified + * range set. + */ + public static > TreeRangeSet create(RangeSet rangeSet) { + TreeRangeSet result = create(); + result.addAll(rangeSet); + return result; + } + + @VisibleForTesting + final NavigableMap, Range> rangesByLowerBound; + + private transient Set> asRanges; + + private transient RangeSet complement; + + private TreeRangeSet(NavigableMap, Range> rangesByLowerCut) { + this.rangesByLowerBound = rangesByLowerCut; + } + + @Override + public void add(Range rangeToAdd) { + checkNotNull(rangeToAdd); + + if (rangeToAdd.isEmpty()) { + return; + } + + // We will use { } to illustrate ranges currently in the range set, and < > + // to illustrate rangeToAdd. + Cut lbToAdd = rangeToAdd.lowerBound; + Cut ubToAdd = rangeToAdd.upperBound; + + Entry, Range> entryBelowLB = rangesByLowerBound.lowerEntry(lbToAdd); + if (entryBelowLB != null) { + // { < + Range rangeBelowLB = entryBelowLB.getValue(); + if (rangeBelowLB.upperBound.compareTo(lbToAdd) >= 0) { + // { < }, and we will need to coalesce + if (rangeBelowLB.upperBound.compareTo(ubToAdd) >= 0) { + // { < > } + ubToAdd = rangeBelowLB.upperBound; + /* + * TODO(cpovirk): can we just "return;" here? Or, can we remove this if() + * entirely? If not, add tests to demonstrate the problem with each approach + */ + } + lbToAdd = rangeBelowLB.lowerBound; + } + } + + Entry, Range> entryBelowUB = rangesByLowerBound.floorEntry(ubToAdd); + if (entryBelowUB != null) { + // { > + Range rangeBelowUB = entryBelowUB.getValue(); + if (rangeBelowUB.upperBound.compareTo(ubToAdd) >= 0) { + // { > }, and we need to coalesce + ubToAdd = rangeBelowUB.upperBound; + } + } + + // Remove ranges which are strictly enclosed. + rangesByLowerBound.subMap(lbToAdd, ubToAdd).clear(); + + replaceRangeWithSameLowerBound(Range.create(lbToAdd, ubToAdd)); + } + + @Override + public Set> asRanges() { + Set> result = asRanges; + return (result == null) ? asRanges = new AsRanges() : result; + } + + @Override + public RangeSet complement() { + RangeSet result = complement; + return (result == null) ? complement = new Complement() : result; + } + + @Override + public boolean encloses(Range range) { + checkNotNull(range); + Entry, Range> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); + return floorEntry != null && floorEntry.getValue().encloses(range); + } + + @Override + @Nullable + public Range rangeContaining(C value) { + checkNotNull(value); + Entry, Range> floorEntry = rangesByLowerBound.floorEntry(Cut.belowValue(value)); + if (floorEntry != null && floorEntry.getValue().contains(value)) { + return floorEntry.getValue(); + } else { + // TODO(kevinb): revisit this design choice + return null; + } + } + + @Nullable + private Range rangeEnclosing(Range range) { + checkNotNull(range); + Entry, Range> floorEntry = rangesByLowerBound.floorEntry(range.lowerBound); + return (floorEntry != null && floorEntry.getValue().encloses(range)) ? floorEntry.getValue() : null; + } + + @Override + public void remove(Range rangeToRemove) { + checkNotNull(rangeToRemove); + + if (rangeToRemove.isEmpty()) { + return; + } + + // We will use { } to illustrate ranges currently in the range set, and < > + // to illustrate rangeToRemove. + + Entry, Range> entryBelowLB = rangesByLowerBound.lowerEntry(rangeToRemove.lowerBound); + if (entryBelowLB != null) { + // { < + Range rangeBelowLB = entryBelowLB.getValue(); + if (rangeBelowLB.upperBound.compareTo(rangeToRemove.lowerBound) >= 0) { + // { < }, and we will need to subdivide + if (rangeToRemove.hasUpperBound() && rangeBelowLB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { + // { < > } + replaceRangeWithSameLowerBound(Range.create(rangeToRemove.upperBound, rangeBelowLB.upperBound)); + } + replaceRangeWithSameLowerBound(Range.create(rangeBelowLB.lowerBound, rangeToRemove.lowerBound)); + } + } + + Entry, Range> entryBelowUB = rangesByLowerBound.floorEntry(rangeToRemove.upperBound); + if (entryBelowUB != null) { + // { > + Range rangeBelowUB = entryBelowUB.getValue(); + if (rangeToRemove.hasUpperBound() && rangeBelowUB.upperBound.compareTo(rangeToRemove.upperBound) >= 0) { + // { > } + replaceRangeWithSameLowerBound(Range.create(rangeToRemove.upperBound, rangeBelowUB.upperBound)); + } + } + + rangesByLowerBound.subMap(rangeToRemove.lowerBound, rangeToRemove.upperBound).clear(); + } + + private void replaceRangeWithSameLowerBound(Range range) { + if (range.isEmpty()) { + rangesByLowerBound.remove(range.lowerBound); + } else { + rangesByLowerBound.put(range.lowerBound, range); + } + } + + @Override + public Range span() { + Entry, Range> firstEntry = rangesByLowerBound.firstEntry(); + Entry, Range> lastEntry = rangesByLowerBound.lastEntry(); + if (firstEntry == null) { + throw new NoSuchElementException(); + } + return Range.create(firstEntry.getValue().lowerBound, lastEntry.getValue().upperBound); } @Override public RangeSet subRangeSet(Range view) { return view.equals(Range.all()) ? this : new SubRangeSet(view); } - - private final class SubRangeSet extends TreeRangeSet { - private final Range restriction; - - SubRangeSet(Range restriction) { - super(new SubRangeSetRangesByLowerBound(Range.>all(), restriction, - TreeRangeSet.this.rangesByLowerBound)); - this.restriction = restriction; - } - - @Override - public boolean encloses(Range range) { - if (!restriction.isEmpty() && restriction.encloses(range)) { - Range enclosing = TreeRangeSet.this.rangeEnclosing(range); - return enclosing != null && !enclosing.intersection(restriction).isEmpty(); - } - return false; - } - - @Override - @Nullable - public Range rangeContaining(C value) { - if (!restriction.contains(value)) { - return null; - } - Range result = TreeRangeSet.this.rangeContaining(value); - return (result == null) ? null : result.intersection(restriction); - } - - @Override - public void add(Range rangeToAdd) { - checkArgument(restriction.encloses(rangeToAdd), "Cannot add range %s to subRangeSet(%s)", rangeToAdd, - restriction); - super.add(rangeToAdd); - } - - @Override - public void remove(Range rangeToRemove) { - if (rangeToRemove.isConnected(restriction)) { - TreeRangeSet.this.remove(rangeToRemove.intersection(restriction)); - } - } - - @Override - public boolean contains(C value) { - return restriction.contains(value) && TreeRangeSet.this.contains(value); - } - - @Override - public void clear() { - TreeRangeSet.this.remove(restriction); - } - - @Override - public RangeSet subRangeSet(Range view) { - if (view.encloses(restriction)) { - return this; - } else if (view.isConnected(restriction)) { - return new SubRangeSet(restriction.intersection(view)); - } else { - return ImmutableRangeSet.of(); - } - } - } } diff --git a/src/main/java/com/google/common/collect/TreeTraverser.java b/src/main/java/com/google/common/collect/TreeTraverser.java index e749bc2d..cda4fe52 100644 --- a/src/main/java/com/google/common/collect/TreeTraverser.java +++ b/src/main/java/com/google/common/collect/TreeTraverser.java @@ -60,34 +60,68 @@ public abstract class TreeTraverser { // TODO(user): make this GWT-compatible when we've checked in ArrayDeque // emulation - /** - * Returns the children of the specified node. Must not contain null. - */ - public abstract Iterable children(T root); + private final class BreadthFirstIterator extends UnmodifiableIterator implements PeekingIterator { + private final Queue queue; - /** - * Returns an unmodifiable iterable over the nodes in a tree structure, using - * pre-order traversal. That is, each node's subtrees are traversed after the - * node itself is returned. - * - *

- * No guarantees are made about the behavior of the traversal when nodes change - * while iteration is in progress or when the iterators generated by - * {@link #children} are advanced. - */ - public final FluentIterable preOrderTraversal(final T root) { - checkNotNull(root); - return new FluentIterable() { - @Override - public UnmodifiableIterator iterator() { - return preOrderIterator(root); - } - }; + BreadthFirstIterator(T root) { + this.queue = new ArrayDeque(); + queue.add(root); + } + + @Override + public boolean hasNext() { + return !queue.isEmpty(); + } + + @Override + public T next() { + T result = queue.remove(); + Iterables.addAll(queue, children(result)); + return result; + } + + @Override + public T peek() { + return queue.element(); + } } - // overridden in BinaryTreeTraverser - UnmodifiableIterator preOrderIterator(T root) { - return new PreOrderIterator(root); + private final class PostOrderIterator extends AbstractIterator { + private final ArrayDeque> stack; + + PostOrderIterator(T root) { + this.stack = new ArrayDeque>(); + stack.addLast(expand(root)); + } + + @Override + protected T computeNext() { + while (!stack.isEmpty()) { + PostOrderNode top = stack.getLast(); + if (top.childIterator.hasNext()) { + T child = top.childIterator.next(); + stack.addLast(expand(child)); + } else { + stack.removeLast(); + return top.root; + } + } + return endOfData(); + } + + private PostOrderNode expand(T t) { + return new PostOrderNode(t, children(t).iterator()); + } + } + + private static final class PostOrderNode { + final T root; + final Iterator childIterator; + + PostOrderNode(T root, Iterator childIterator) { + this.root = checkNotNull(root); + this.childIterator = checkNotNull(childIterator); + } } private final class PreOrderIterator extends UnmodifiableIterator { @@ -118,6 +152,36 @@ public abstract class TreeTraverser { } } + /** + * Returns an unmodifiable iterable over the nodes in a tree structure, using + * breadth-first traversal. That is, all the nodes of depth 0 are returned, then + * depth 1, then 2, and so on. + * + *

+ * No guarantees are made about the behavior of the traversal when nodes change + * while iteration is in progress or when the iterators generated by + * {@link #children} are advanced. + */ + public final FluentIterable breadthFirstTraversal(final T root) { + checkNotNull(root); + return new FluentIterable() { + @Override + public UnmodifiableIterator iterator() { + return new BreadthFirstIterator(root); + } + }; + } + + /** + * Returns the children of the specified node. Must not contain null. + */ + public abstract Iterable children(T root); + + // overridden in BinaryTreeTraverser + UnmodifiableIterator postOrderIterator(T root) { + return new PostOrderIterator(root); + } + /** * Returns an unmodifiable iterable over the nodes in a tree structure, using * post-order traversal. That is, each node's subtrees are traversed before the @@ -139,91 +203,27 @@ public abstract class TreeTraverser { } // overridden in BinaryTreeTraverser - UnmodifiableIterator postOrderIterator(T root) { - return new PostOrderIterator(root); - } - - private static final class PostOrderNode { - final T root; - final Iterator childIterator; - - PostOrderNode(T root, Iterator childIterator) { - this.root = checkNotNull(root); - this.childIterator = checkNotNull(childIterator); - } - } - - private final class PostOrderIterator extends AbstractIterator { - private final ArrayDeque> stack; - - PostOrderIterator(T root) { - this.stack = new ArrayDeque>(); - stack.addLast(expand(root)); - } - - @Override - protected T computeNext() { - while (!stack.isEmpty()) { - PostOrderNode top = stack.getLast(); - if (top.childIterator.hasNext()) { - T child = top.childIterator.next(); - stack.addLast(expand(child)); - } else { - stack.removeLast(); - return top.root; - } - } - return endOfData(); - } - - private PostOrderNode expand(T t) { - return new PostOrderNode(t, children(t).iterator()); - } + UnmodifiableIterator preOrderIterator(T root) { + return new PreOrderIterator(root); } /** * Returns an unmodifiable iterable over the nodes in a tree structure, using - * breadth-first traversal. That is, all the nodes of depth 0 are returned, then - * depth 1, then 2, and so on. + * pre-order traversal. That is, each node's subtrees are traversed after the + * node itself is returned. * *

* No guarantees are made about the behavior of the traversal when nodes change * while iteration is in progress or when the iterators generated by * {@link #children} are advanced. */ - public final FluentIterable breadthFirstTraversal(final T root) { + public final FluentIterable preOrderTraversal(final T root) { checkNotNull(root); return new FluentIterable() { @Override public UnmodifiableIterator iterator() { - return new BreadthFirstIterator(root); + return preOrderIterator(root); } }; } - - private final class BreadthFirstIterator extends UnmodifiableIterator implements PeekingIterator { - private final Queue queue; - - BreadthFirstIterator(T root) { - this.queue = new ArrayDeque(); - queue.add(root); - } - - @Override - public boolean hasNext() { - return !queue.isEmpty(); - } - - @Override - public T peek() { - return queue.element(); - } - - @Override - public T next() { - T result = queue.remove(); - Iterables.addAll(queue, children(result)); - return result; - } - } } diff --git a/src/main/java/com/google/common/collect/UnmodifiableSortedMultiset.java b/src/main/java/com/google/common/collect/UnmodifiableSortedMultiset.java index 49ee196e..ce4588ce 100644 --- a/src/main/java/com/google/common/collect/UnmodifiableSortedMultiset.java +++ b/src/main/java/com/google/common/collect/UnmodifiableSortedMultiset.java @@ -32,15 +32,14 @@ import com.google.common.collect.Multisets.UnmodifiableMultiset; */ @GwtCompatible(emulated = true) final class UnmodifiableSortedMultiset extends UnmodifiableMultiset implements SortedMultiset { + private static final long serialVersionUID = 0; + + private transient UnmodifiableSortedMultiset descendingMultiset; + UnmodifiableSortedMultiset(SortedMultiset delegate) { super(delegate); } - @Override - protected SortedMultiset delegate() { - return (SortedMultiset) super.delegate(); - } - @Override public Comparator comparator() { return delegate().comparator(); @@ -52,12 +51,10 @@ final class UnmodifiableSortedMultiset extends UnmodifiableMultiset implem } @Override - public NavigableSet elementSet() { - return (NavigableSet) super.elementSet(); + protected SortedMultiset delegate() { + return (SortedMultiset) super.delegate(); } - private transient UnmodifiableSortedMultiset descendingMultiset; - @Override public SortedMultiset descendingMultiset() { UnmodifiableSortedMultiset result = descendingMultiset; @@ -69,11 +66,21 @@ final class UnmodifiableSortedMultiset extends UnmodifiableMultiset implem return result; } + @Override + public NavigableSet elementSet() { + return (NavigableSet) super.elementSet(); + } + @Override public Entry firstEntry() { return delegate().firstEntry(); } + @Override + public SortedMultiset headMultiset(E upperBound, BoundType boundType) { + return Multisets.unmodifiableSortedMultiset(delegate().headMultiset(upperBound, boundType)); + } + @Override public Entry lastEntry() { return delegate().lastEntry(); @@ -89,11 +96,6 @@ final class UnmodifiableSortedMultiset extends UnmodifiableMultiset implem throw new UnsupportedOperationException(); } - @Override - public SortedMultiset headMultiset(E upperBound, BoundType boundType) { - return Multisets.unmodifiableSortedMultiset(delegate().headMultiset(upperBound, boundType)); - } - @Override public SortedMultiset subMultiset(E lowerBound, BoundType lowerBoundType, E upperBound, BoundType upperBoundType) { @@ -105,6 +107,4 @@ final class UnmodifiableSortedMultiset extends UnmodifiableMultiset implem public SortedMultiset tailMultiset(E lowerBound, BoundType boundType) { return Multisets.unmodifiableSortedMultiset(delegate().tailMultiset(lowerBound, boundType)); } - - private static final long serialVersionUID = 0; } \ No newline at end of file diff --git a/src/main/java/com/google/common/collect/UsingToStringOrdering.java b/src/main/java/com/google/common/collect/UsingToStringOrdering.java index b08e7d23..63772a72 100644 --- a/src/main/java/com/google/common/collect/UsingToStringOrdering.java +++ b/src/main/java/com/google/common/collect/UsingToStringOrdering.java @@ -28,6 +28,11 @@ import com.google.common.annotations.GwtCompatible; final class UsingToStringOrdering extends Ordering implements Serializable { static final UsingToStringOrdering INSTANCE = new UsingToStringOrdering(); + private static final long serialVersionUID = 0; + + private UsingToStringOrdering() { + } + @Override public int compare(Object left, Object right) { return left.toString().compareTo(right.toString()); @@ -42,9 +47,4 @@ final class UsingToStringOrdering extends Ordering implements Serializab public String toString() { return "Ordering.usingToString()"; } - - private UsingToStringOrdering() { - } - - private static final long serialVersionUID = 0; } diff --git a/src/main/java/com/google/common/collect/WellBehavedMap.java b/src/main/java/com/google/common/collect/WellBehavedMap.java index 3213ff9d..39e015df 100644 --- a/src/main/java/com/google/common/collect/WellBehavedMap.java +++ b/src/main/java/com/google/common/collect/WellBehavedMap.java @@ -36,43 +36,7 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible final class WellBehavedMap extends ForwardingMap { - private final Map delegate; - private Set> entrySet; - - private WellBehavedMap(Map delegate) { - this.delegate = delegate; - } - - /** - * Wraps the given map into a {@code WellBehavedEntriesMap}, which intercepts - * its {@code entrySet()} method by taking the {@code Set keySet()} and - * transforming it to {@code Set>}. All other invocations are - * delegated as-is. - */ - static WellBehavedMap wrap(Map delegate) { - return new WellBehavedMap(delegate); - } - - @Override - protected Map delegate() { - return delegate; - } - - @Override - public Set> entrySet() { - Set> es = entrySet; - if (es != null) { - return es; - } - return entrySet = new EntrySet(); - } - private final class EntrySet extends Maps.EntrySet { - @Override - Map map() { - return WellBehavedMap.this; - } - @Override public Iterator> iterator() { return new TransformedIterator>(keySet().iterator()) { @@ -97,5 +61,42 @@ final class WellBehavedMap extends ForwardingMap { } }; } + + @Override + Map map() { + return WellBehavedMap.this; + } + } + + /** + * Wraps the given map into a {@code WellBehavedEntriesMap}, which intercepts + * its {@code entrySet()} method by taking the {@code Set keySet()} and + * transforming it to {@code Set>}. All other invocations are + * delegated as-is. + */ + static WellBehavedMap wrap(Map delegate) { + return new WellBehavedMap(delegate); + } + + private final Map delegate; + + private Set> entrySet; + + private WellBehavedMap(Map delegate) { + this.delegate = delegate; + } + + @Override + protected Map delegate() { + return delegate; + } + + @Override + public Set> entrySet() { + Set> es = entrySet; + if (es != null) { + return es; + } + return entrySet = new EntrySet(); } } diff --git a/src/main/java/com/google/common/escape/ArrayBasedCharEscaper.java b/src/main/java/com/google/common/escape/ArrayBasedCharEscaper.java index 7f47559b..eecb055a 100644 --- a/src/main/java/com/google/common/escape/ArrayBasedCharEscaper.java +++ b/src/main/java/com/google/common/escape/ArrayBasedCharEscaper.java @@ -60,25 +60,6 @@ public abstract class ArrayBasedCharEscaper extends CharEscaper { // The last character in the safe range. private final char safeMax; - /** - * Creates a new ArrayBasedCharEscaper instance with the given replacement map - * and specified safe range. If {@code safeMax < safeMin} then no characters are - * considered safe. - * - *

- * If a character has no mapped replacement then it is checked against the safe - * range. If it lies outside that, then {@link #escapeUnsafe} is called, - * otherwise no escaping is performed. - * - * @param replacementMap a map of characters to their escaped representations - * @param safeMin the lowest character value in the safe range - * @param safeMax the highest character value in the safe range - */ - protected ArrayBasedCharEscaper(Map replacementMap, char safeMin, char safeMax) { - - this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax); - } - /** * Creates a new ArrayBasedCharEscaper instance with the given replacement map * and specified safe range. If {@code safeMax < safeMin} then no characters are @@ -110,21 +91,23 @@ public abstract class ArrayBasedCharEscaper extends CharEscaper { this.safeMax = safeMax; } - /* - * This is overridden to improve performance. Rough benchmarking shows that this - * almost doubles the speed when processing strings that do not require any - * escaping. + /** + * Creates a new ArrayBasedCharEscaper instance with the given replacement map + * and specified safe range. If {@code safeMax < safeMin} then no characters are + * considered safe. + * + *

+ * If a character has no mapped replacement then it is checked against the safe + * range. If it lies outside that, then {@link #escapeUnsafe} is called, + * otherwise no escaping is performed. + * + * @param replacementMap a map of characters to their escaped representations + * @param safeMin the lowest character value in the safe range + * @param safeMax the highest character value in the safe range */ - @Override - public final String escape(String s) { - checkNotNull(s); // GWT specific check (do not optimize). - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if ((c < replacementsLength && replacements[c] != null) || c > safeMax || c < safeMin) { - return escapeSlow(s, i); - } - } - return s; + protected ArrayBasedCharEscaper(Map replacementMap, char safeMin, char safeMax) { + + this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax); } /** @@ -146,6 +129,23 @@ public abstract class ArrayBasedCharEscaper extends CharEscaper { return escapeUnsafe(c); } + /* + * This is overridden to improve performance. Rough benchmarking shows that this + * almost doubles the speed when processing strings that do not require any + * escaping. + */ + @Override + public final String escape(String s) { + checkNotNull(s); // GWT specific check (do not optimize). + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if ((c < replacementsLength && replacements[c] != null) || c > safeMax || c < safeMin) { + return escapeSlow(s, i); + } + } + return s; + } + /** * Escapes a {@code char} value that has no direct explicit value in the * replacement array and lies outside the stated safe range. Subclasses should diff --git a/src/main/java/com/google/common/escape/ArrayBasedEscaperMap.java b/src/main/java/com/google/common/escape/ArrayBasedEscaperMap.java index cc9406a5..6ad2508e 100644 --- a/src/main/java/com/google/common/escape/ArrayBasedEscaperMap.java +++ b/src/main/java/com/google/common/escape/ArrayBasedEscaperMap.java @@ -46,6 +46,9 @@ import com.google.common.annotations.VisibleForTesting; @Beta @GwtCompatible public final class ArrayBasedEscaperMap { + // Immutable empty array for when there are no replacements. + private static final char[][] EMPTY_REPLACEMENT_ARRAY = new char[0][0]; + /** * Returns a new ArrayBasedEscaperMap for creating ArrayBasedCharEscaper or * ArrayBasedUnicodeEscaper instances. @@ -56,19 +59,6 @@ public final class ArrayBasedEscaperMap { return new ArrayBasedEscaperMap(createReplacementArray(replacements)); } - // The underlying replacement array we can share between multiple escaper - // instances. - private final char[][] replacementArray; - - private ArrayBasedEscaperMap(char[][] replacementArray) { - this.replacementArray = replacementArray; - } - - // Returns the non-null array of replacements for fast lookup. - char[][] getReplacementArray() { - return replacementArray; - } - // Creates a replacement array from the given map. The returned array is a // linear lookup table of replacement character sequences indexed by the // original character value. @@ -86,6 +76,16 @@ public final class ArrayBasedEscaperMap { return replacements; } - // Immutable empty array for when there are no replacements. - private static final char[][] EMPTY_REPLACEMENT_ARRAY = new char[0][0]; + // The underlying replacement array we can share between multiple escaper + // instances. + private final char[][] replacementArray; + + private ArrayBasedEscaperMap(char[][] replacementArray) { + this.replacementArray = replacementArray; + } + + // Returns the non-null array of replacements for fast lookup. + char[][] getReplacementArray() { + return replacementArray; + } } diff --git a/src/main/java/com/google/common/escape/ArrayBasedUnicodeEscaper.java b/src/main/java/com/google/common/escape/ArrayBasedUnicodeEscaper.java index 52444b16..5b245b95 100644 --- a/src/main/java/com/google/common/escape/ArrayBasedUnicodeEscaper.java +++ b/src/main/java/com/google/common/escape/ArrayBasedUnicodeEscaper.java @@ -64,28 +64,6 @@ public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper { private final char safeMinChar; private final char safeMaxChar; - /** - * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement - * map and specified safe range. If {@code safeMax < safeMin} then no code - * points are considered safe. - * - *

- * If a code point has no mapped replacement then it is checked against the safe - * range. If it lies outside that, then {@link #escapeUnsafe} is called, - * otherwise no escaping is performed. - * - * @param replacementMap a map of characters to their escaped representations - * @param safeMin the lowest character value in the safe range - * @param safeMax the highest character value in the safe range - * @param unsafeReplacement the default replacement for unsafe characters or - * null if no default replacement is required - */ - protected ArrayBasedUnicodeEscaper(Map replacementMap, int safeMin, int safeMax, - @Nullable String unsafeReplacement) { - - this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax, unsafeReplacement); - } - /** * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement * map and specified safe range. If {@code safeMax < safeMin} then no code @@ -145,34 +123,26 @@ public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper { } } - /* - * This is overridden to improve performance. Rough benchmarking shows that this - * almost doubles the speed when processing strings that do not require any - * escaping. + /** + * Creates a new ArrayBasedUnicodeEscaper instance with the given replacement + * map and specified safe range. If {@code safeMax < safeMin} then no code + * points are considered safe. + * + *

+ * If a code point has no mapped replacement then it is checked against the safe + * range. If it lies outside that, then {@link #escapeUnsafe} is called, + * otherwise no escaping is performed. + * + * @param replacementMap a map of characters to their escaped representations + * @param safeMin the lowest character value in the safe range + * @param safeMax the highest character value in the safe range + * @param unsafeReplacement the default replacement for unsafe characters or + * null if no default replacement is required */ - @Override - public final String escape(String s) { - checkNotNull(s); // GWT specific check (do not optimize) - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if ((c < replacementsLength && replacements[c] != null) || c > safeMaxChar || c < safeMinChar) { - return escapeSlow(s, i); - } - } - return s; - } + protected ArrayBasedUnicodeEscaper(Map replacementMap, int safeMin, int safeMax, + @Nullable String unsafeReplacement) { - /* Overridden for performance. */ - @Override - protected final int nextEscapeIndex(CharSequence csq, int index, int end) { - while (index < end) { - char c = csq.charAt(index); - if ((c < replacementsLength && replacements[c] != null) || c > safeMaxChar || c < safeMinChar) { - break; - } - index++; - } - return index; + this(ArrayBasedEscaperMap.create(replacementMap), safeMin, safeMax, unsafeReplacement); } /** @@ -194,6 +164,23 @@ public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper { return escapeUnsafe(cp); } + /* + * This is overridden to improve performance. Rough benchmarking shows that this + * almost doubles the speed when processing strings that do not require any + * escaping. + */ + @Override + public final String escape(String s) { + checkNotNull(s); // GWT specific check (do not optimize) + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if ((c < replacementsLength && replacements[c] != null) || c > safeMaxChar || c < safeMinChar) { + return escapeSlow(s, i); + } + } + return s; + } + /** * Escapes a code point that has no direct explicit value in the replacement * array and lies outside the stated safe range. Subclasses should override this @@ -209,4 +196,17 @@ public abstract class ArrayBasedUnicodeEscaper extends UnicodeEscaper { * required */ protected abstract char[] escapeUnsafe(int cp); + + /* Overridden for performance. */ + @Override + protected final int nextEscapeIndex(CharSequence csq, int index, int end) { + while (index < end) { + char c = csq.charAt(index); + if ((c < replacementsLength && replacements[c] != null) || c > safeMaxChar || c < safeMinChar) { + break; + } + index++; + } + return index; + } } diff --git a/src/main/java/com/google/common/escape/CharEscaper.java b/src/main/java/com/google/common/escape/CharEscaper.java index 1ab7f971..51da0e93 100644 --- a/src/main/java/com/google/common/escape/CharEscaper.java +++ b/src/main/java/com/google/common/escape/CharEscaper.java @@ -51,10 +51,47 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible public abstract class CharEscaper extends Escaper { + /** + * The multiplier for padding to use when growing the escape buffer. + */ + private static final int DEST_PAD_MULTIPLIER = 2; + + /** + * Helper method to grow the character buffer as needed, this only happens once + * in a while so it's ok if it's in a method call. If the index passed in is 0 + * then no copying will be done. + */ + private static char[] growBuffer(char[] dest, int index, int size) { + char[] copy = new char[size]; + if (index > 0) { + System.arraycopy(dest, 0, copy, 0, index); + } + return copy; + } + /** Constructor for use by subclasses. */ protected CharEscaper() { } + /** + * Returns the escaped form of the given character, or {@code null} if this + * character does not need to be escaped. If an empty array is returned, this + * effectively strips the input character from the resulting text. + * + *

+ * If the character does not need to be escaped, this method should return + * {@code null}, rather than a one-character array containing the character + * itself. This enables the escaping algorithm to perform more efficiently. + * + *

+ * An escaper is expected to be able to deal with any {@code char} value, so + * this method should not throw any exceptions. + * + * @param c the character to escape if necessary + * @return the replacement characters, or {@code null} if no escaping was needed + */ + protected abstract char[] escape(char c); + /** * Returns the escaped form of a given literal string. * @@ -147,41 +184,4 @@ public abstract class CharEscaper extends Escaper { } return new String(dest, 0, destIndex); } - - /** - * Returns the escaped form of the given character, or {@code null} if this - * character does not need to be escaped. If an empty array is returned, this - * effectively strips the input character from the resulting text. - * - *

- * If the character does not need to be escaped, this method should return - * {@code null}, rather than a one-character array containing the character - * itself. This enables the escaping algorithm to perform more efficiently. - * - *

- * An escaper is expected to be able to deal with any {@code char} value, so - * this method should not throw any exceptions. - * - * @param c the character to escape if necessary - * @return the replacement characters, or {@code null} if no escaping was needed - */ - protected abstract char[] escape(char c); - - /** - * Helper method to grow the character buffer as needed, this only happens once - * in a while so it's ok if it's in a method call. If the index passed in is 0 - * then no copying will be done. - */ - private static char[] growBuffer(char[] dest, int index, int size) { - char[] copy = new char[size]; - if (index > 0) { - System.arraycopy(dest, 0, copy, 0, index); - } - return copy; - } - - /** - * The multiplier for padding to use when growing the escape buffer. - */ - private static final int DEST_PAD_MULTIPLIER = 2; } diff --git a/src/main/java/com/google/common/escape/CharEscaperBuilder.java b/src/main/java/com/google/common/escape/CharEscaperBuilder.java index f704af1a..6cf60b57 100644 --- a/src/main/java/com/google/common/escape/CharEscaperBuilder.java +++ b/src/main/java/com/google/common/escape/CharEscaperBuilder.java @@ -50,6 +50,11 @@ public final class CharEscaperBuilder { this.replaceLength = replacements.length; } + @Override + protected char[] escape(char c) { + return c < replaceLength ? replacements[c] : null; + } + /* * Overriding escape method to be slightly faster for this decorator. We test * the replacements array directly, saving a method call. @@ -65,11 +70,6 @@ public final class CharEscaperBuilder { } return s; } - - @Override - protected char[] escape(char c) { - return c < replaceLength ? replacements[c] : null; - } } // Replacement mappings. diff --git a/src/main/java/com/google/common/escape/Escaper.java b/src/main/java/com/google/common/escape/Escaper.java index df2d0860..ad7682d7 100644 --- a/src/main/java/com/google/common/escape/Escaper.java +++ b/src/main/java/com/google/common/escape/Escaper.java @@ -72,12 +72,27 @@ import com.google.common.base.Function; @Beta @GwtCompatible public abstract class Escaper { + private final Function asFunction = new Function() { + @Override + public String apply(String from) { + return escape(from); + } + }; + // TODO(user): evaluate custom implementations, considering package private // constructor. /** Constructor for use by subclasses. */ protected Escaper() { } + /** + * Returns a {@link Function} that invokes {@link #escape(String)} on this + * escaper. + */ + public final Function asFunction() { + return asFunction; + } + /** * Returns the escaped form of a given literal string. * @@ -104,19 +119,4 @@ public abstract class Escaper { * reason */ public abstract String escape(String string); - - private final Function asFunction = new Function() { - @Override - public String apply(String from) { - return escape(from); - } - }; - - /** - * Returns a {@link Function} that invokes {@link #escape(String)} on this - * escaper. - */ - public final Function asFunction() { - return asFunction; - } } diff --git a/src/main/java/com/google/common/escape/Escapers.java b/src/main/java/com/google/common/escape/Escapers.java index 87e138bf..0ed68d02 100644 --- a/src/main/java/com/google/common/escape/Escapers.java +++ b/src/main/java/com/google/common/escape/Escapers.java @@ -36,54 +36,6 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible public final class Escapers { - private Escapers() { - } - - /** - * Returns an {@link Escaper} that does no escaping, passing all character data - * through unchanged. - */ - public static Escaper nullEscaper() { - return NULL_ESCAPER; - } - - // An Escaper that efficiently performs no escaping. - // Extending CharEscaper (instead of Escaper) makes Escapers.compose() easier. - private static final Escaper NULL_ESCAPER = new CharEscaper() { - @Override - public String escape(String string) { - return checkNotNull(string); - } - - @Override - protected char[] escape(char c) { - // TODO: Fix tests not to call this directly and make it throw an error. - return null; - } - }; - - /** - * Returns a builder for creating simple, fast escapers. A builder instance can - * be reused and each escaper that is created will be a snapshot of the current - * builder state. Builders are not thread safe. - * - *

- * The initial state of the builder is such that: - *

    - *
  • There are no replacement mappings - *
  • - *
  • {@code safeMin == Character.MIN_VALUE}
  • - *
  • {@code safeMax == Character.MAX_VALUE}
  • - *
  • {@code unsafeReplacement == null}
  • - *
- *

- * For performance reasons escapers created by this builder are not Unicode - * aware and will not validate the well-formedness of their input. - */ - public static Builder builder() { - return new Builder(); - } - /** * A builder for simple, fast escapers. * @@ -108,35 +60,6 @@ public final class Escapers { private Builder() { } - /** - * Sets the safe range of characters for the escaper. Characters in this range - * that have no explicit replacement are considered 'safe' and remain unescaped - * in the output. If {@code safeMax < safeMin} then the safe range is empty. - * - * @param safeMin the lowest 'safe' character - * @param safeMax the highest 'safe' character - * @return the builder instance - */ - public Builder setSafeRange(char safeMin, char safeMax) { - this.safeMin = safeMin; - this.safeMax = safeMax; - return this; - } - - /** - * Sets the replacement string for any characters outside the 'safe' range that - * have no explicit replacement. If {@code unsafeReplacement} is {@code null} - * then no replacement will occur, if it is {@code ""} then the unsafe - * characters are removed from the output. - * - * @param unsafeReplacement the string to replace unsafe chracters - * @return the builder instance - */ - public Builder setUnsafeReplacement(@Nullable String unsafeReplacement) { - this.unsafeReplacement = unsafeReplacement; - return this; - } - /** * Adds a replacement string for the given input character. The specified * character will be replaced by the given string whenever it occurs in the @@ -168,8 +91,52 @@ public final class Escapers { } }; } + + /** + * Sets the safe range of characters for the escaper. Characters in this range + * that have no explicit replacement are considered 'safe' and remain unescaped + * in the output. If {@code safeMax < safeMin} then the safe range is empty. + * + * @param safeMin the lowest 'safe' character + * @param safeMax the highest 'safe' character + * @return the builder instance + */ + public Builder setSafeRange(char safeMin, char safeMax) { + this.safeMin = safeMin; + this.safeMax = safeMax; + return this; + } + + /** + * Sets the replacement string for any characters outside the 'safe' range that + * have no explicit replacement. If {@code unsafeReplacement} is {@code null} + * then no replacement will occur, if it is {@code ""} then the unsafe + * characters are removed from the output. + * + * @param unsafeReplacement the string to replace unsafe chracters + * @return the builder instance + */ + public Builder setUnsafeReplacement(@Nullable String unsafeReplacement) { + this.unsafeReplacement = unsafeReplacement; + return this; + } } + // An Escaper that efficiently performs no escaping. + // Extending CharEscaper (instead of Escaper) makes Escapers.compose() easier. + private static final Escaper NULL_ESCAPER = new CharEscaper() { + @Override + protected char[] escape(char c) { + // TODO: Fix tests not to call this directly and make it throw an error. + return null; + } + + @Override + public String escape(String string) { + return checkNotNull(string); + } + }; + /** * Returns a {@link UnicodeEscaper} equivalent to the given escaper instance. If * the escaper is already a UnicodeEscaper then it is simply returned, otherwise @@ -199,6 +166,28 @@ public final class Escapers { throw new IllegalArgumentException("Cannot create a UnicodeEscaper from: " + escaper.getClass().getName()); } + /** + * Returns a builder for creating simple, fast escapers. A builder instance can + * be reused and each escaper that is created will be a snapshot of the current + * builder state. Builders are not thread safe. + * + *

+ * The initial state of the builder is such that: + *

    + *
  • There are no replacement mappings + *
  • + *
  • {@code safeMin == Character.MIN_VALUE}
  • + *
  • {@code safeMax == Character.MAX_VALUE}
  • + *
  • {@code unsafeReplacement == null}
  • + *
+ *

+ * For performance reasons escapers created by this builder are not Unicode + * aware and will not validate the well-formedness of their input. + */ + public static Builder builder() { + return new Builder(); + } + /** * Returns a string that would replace the given character in the specified * escaper, or {@code null} if no replacement should be made. This method is @@ -227,6 +216,14 @@ public final class Escapers { return stringOrNull(escaper.escape(cp)); } + /** + * Returns an {@link Escaper} that does no escaping, passing all character data + * through unchanged. + */ + public static Escaper nullEscaper() { + return NULL_ESCAPER; + } + private static String stringOrNull(char[] in) { return (in == null) ? null : new String(in); } @@ -280,4 +277,7 @@ public final class Escapers { } }; } + + private Escapers() { + } } diff --git a/src/main/java/com/google/common/escape/Platform.java b/src/main/java/com/google/common/escape/Platform.java index f45a7082..4248bd33 100644 --- a/src/main/java/com/google/common/escape/Platform.java +++ b/src/main/java/com/google/common/escape/Platform.java @@ -25,14 +25,6 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(emulated = true) final class Platform { - private Platform() { - } - - /** Returns a thread-local 1024-char array. */ - static char[] charBufferFromThreadLocal() { - return DEST_TL.get(); - } - /** * A thread-local destination buffer to keep us from creating new buffers. The * starting size is 1024 characters. If we grow past this we don't put it back @@ -44,4 +36,12 @@ final class Platform { return new char[1024]; } }; + + /** Returns a thread-local 1024-char array. */ + static char[] charBufferFromThreadLocal() { + return DEST_TL.get(); + } + + private Platform() { + } } diff --git a/src/main/java/com/google/common/escape/UnicodeEscaper.java b/src/main/java/com/google/common/escape/UnicodeEscaper.java index 735b5990..eb3fc0fd 100644 --- a/src/main/java/com/google/common/escape/UnicodeEscaper.java +++ b/src/main/java/com/google/common/escape/UnicodeEscaper.java @@ -66,6 +66,80 @@ public abstract class UnicodeEscaper extends Escaper { /** The amount of padding (chars) to use when growing the escape buffer. */ private static final int DEST_PAD = 32; + /** + * Returns the Unicode code point of the character at the given index. + * + *

+ * Unlike {@link Character#codePointAt(CharSequence, int)} or + * {@link String#codePointAt(int)} this method will never fail silently when + * encountering an invalid surrogate pair. + * + *

+ * The behaviour of this method is as follows: + *

    + *
  1. If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. + *
  2. If the character at the specified index is not a surrogate, it is + * returned. + *
  3. If the first character was a high surrogate value, then an attempt is + * made to read the next character. + *
      + *
    1. If the end of the sequence was reached, the negated value of the + * trailing high surrogate is returned. + *
    2. If the next character was a valid low surrogate, the code point value + * of the high/low surrogate pair is returned. + *
    3. If the next character was not a low surrogate value, then + * {@link IllegalArgumentException} is thrown. + *
    + *
  4. If the first character was a low surrogate value, + * {@link IllegalArgumentException} is thrown. + *
+ * + * @param seq the sequence of characters from which to decode the code point + * @param index the index of the first character to decode + * @param end the index beyond the last valid character to decode + * @return the Unicode code point for the given index or the negated value of + * the trailing high surrogate character at the end of the sequence + */ + protected static int codePointAt(CharSequence seq, int index, int end) { + checkNotNull(seq); + if (index < end) { + char c1 = seq.charAt(index++); + if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { + // Fast path (first test is probably all we need to do) + return c1; + } else if (c1 <= Character.MAX_HIGH_SURROGATE) { + // If the high surrogate was the last character, return its inverse + if (index == end) { + return -c1; + } + // Otherwise look for the low surrogate following it + char c2 = seq.charAt(index); + if (Character.isLowSurrogate(c2)) { + return Character.toCodePoint(c1, c2); + } + throw new IllegalArgumentException("Expected low surrogate but got char '" + c2 + "' with value " + + (int) c2 + " at index " + index + " in '" + seq + "'"); + } else { + throw new IllegalArgumentException("Unexpected low surrogate character '" + c1 + "' with value " + + (int) c1 + " at index " + (index - 1) + " in '" + seq + "'"); + } + } + throw new IndexOutOfBoundsException("Index exceeds specified range"); + } + + /** + * Helper method to grow the character buffer as needed, this only happens once + * in a while so it's ok if it's in a method call. If the index passed in is 0 + * then no copying will be done. + */ + private static char[] growBuffer(char[] dest, int index, int size) { + char[] copy = new char[size]; + if (index > 0) { + System.arraycopy(dest, 0, copy, 0, index); + } + return copy; + } + /** Constructor for use by subclasses. */ protected UnicodeEscaper() { } @@ -97,45 +171,6 @@ public abstract class UnicodeEscaper extends Escaper { */ protected abstract char[] escape(int cp); - /** - * Scans a sub-sequence of characters from a given {@link CharSequence}, - * returning the index of the next character that requires escaping. - * - *

- * Note: When implementing an escaper, it is a good idea to override this - * method for efficiency. The base class implementation determines successive - * Unicode code points and invokes {@link #escape(int)} for each of them. If the - * semantics of your escaper are such that code points in the supplementary - * range are either all escaped or all unescaped, this method can be implemented - * more efficiently using {@link CharSequence#charAt(int)}. - * - *

- * Note however that if your escaper does not escape characters in the - * supplementary range, you should either continue to validate the correctness - * of any surrogate characters encountered or provide a clear warning to users - * that your escaper does not validate its input. - * - *

- * See {@link com.google.common.net.PercentEscaper} for an example. - * - * @param csq a sequence of characters - * @param start the index of the first character to be scanned - * @param end the index immediately after the last character to be scanned - * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} - * contains invalid surrogate pairs - */ - protected int nextEscapeIndex(CharSequence csq, int start, int end) { - int index = start; - while (index < end) { - int cp = codePointAt(csq, index, end); - if (cp < 0 || escape(cp) != null) { - break; - } - index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; - } - return index; - } - /** * Returns the escaped form of a given literal string. * @@ -245,76 +280,41 @@ public abstract class UnicodeEscaper extends Escaper { } /** - * Returns the Unicode code point of the character at the given index. + * Scans a sub-sequence of characters from a given {@link CharSequence}, + * returning the index of the next character that requires escaping. * *

- * Unlike {@link Character#codePointAt(CharSequence, int)} or - * {@link String#codePointAt(int)} this method will never fail silently when - * encountering an invalid surrogate pair. + * Note: When implementing an escaper, it is a good idea to override this + * method for efficiency. The base class implementation determines successive + * Unicode code points and invokes {@link #escape(int)} for each of them. If the + * semantics of your escaper are such that code points in the supplementary + * range are either all escaped or all unescaped, this method can be implemented + * more efficiently using {@link CharSequence#charAt(int)}. * *

- * The behaviour of this method is as follows: - *

    - *
  1. If {@code index >= end}, {@link IndexOutOfBoundsException} is thrown. - *
  2. If the character at the specified index is not a surrogate, it is - * returned. - *
  3. If the first character was a high surrogate value, then an attempt is - * made to read the next character. - *
      - *
    1. If the end of the sequence was reached, the negated value of the - * trailing high surrogate is returned. - *
    2. If the next character was a valid low surrogate, the code point value - * of the high/low surrogate pair is returned. - *
    3. If the next character was not a low surrogate value, then - * {@link IllegalArgumentException} is thrown. - *
    - *
  4. If the first character was a low surrogate value, - * {@link IllegalArgumentException} is thrown. - *
+ * Note however that if your escaper does not escape characters in the + * supplementary range, you should either continue to validate the correctness + * of any surrogate characters encountered or provide a clear warning to users + * that your escaper does not validate its input. * - * @param seq the sequence of characters from which to decode the code point - * @param index the index of the first character to decode - * @param end the index beyond the last valid character to decode - * @return the Unicode code point for the given index or the negated value of - * the trailing high surrogate character at the end of the sequence + *

+ * See {@link com.google.common.net.PercentEscaper} for an example. + * + * @param csq a sequence of characters + * @param start the index of the first character to be scanned + * @param end the index immediately after the last character to be scanned + * @throws IllegalArgumentException if the scanned sub-sequence of {@code csq} + * contains invalid surrogate pairs */ - protected static int codePointAt(CharSequence seq, int index, int end) { - checkNotNull(seq); - if (index < end) { - char c1 = seq.charAt(index++); - if (c1 < Character.MIN_HIGH_SURROGATE || c1 > Character.MAX_LOW_SURROGATE) { - // Fast path (first test is probably all we need to do) - return c1; - } else if (c1 <= Character.MAX_HIGH_SURROGATE) { - // If the high surrogate was the last character, return its inverse - if (index == end) { - return -c1; - } - // Otherwise look for the low surrogate following it - char c2 = seq.charAt(index); - if (Character.isLowSurrogate(c2)) { - return Character.toCodePoint(c1, c2); - } - throw new IllegalArgumentException("Expected low surrogate but got char '" + c2 + "' with value " - + (int) c2 + " at index " + index + " in '" + seq + "'"); - } else { - throw new IllegalArgumentException("Unexpected low surrogate character '" + c1 + "' with value " - + (int) c1 + " at index " + (index - 1) + " in '" + seq + "'"); + protected int nextEscapeIndex(CharSequence csq, int start, int end) { + int index = start; + while (index < end) { + int cp = codePointAt(csq, index, end); + if (cp < 0 || escape(cp) != null) { + break; } + index += Character.isSupplementaryCodePoint(cp) ? 2 : 1; } - throw new IndexOutOfBoundsException("Index exceeds specified range"); - } - - /** - * Helper method to grow the character buffer as needed, this only happens once - * in a while so it's ok if it's in a method call. If the index passed in is 0 - * then no copying will be done. - */ - private static char[] growBuffer(char[] dest, int index, int size) { - char[] copy = new char[size]; - if (index > 0) { - System.arraycopy(dest, 0, copy, 0, index); - } - return copy; + return index; } } diff --git a/src/main/java/com/google/common/hash/AbstractByteHasher.java b/src/main/java/com/google/common/hash/AbstractByteHasher.java index 9db0b4eb..a2b95a8c 100644 --- a/src/main/java/com/google/common/hash/AbstractByteHasher.java +++ b/src/main/java/com/google/common/hash/AbstractByteHasher.java @@ -38,6 +38,56 @@ abstract class AbstractByteHasher extends AbstractHasher { private final ByteBuffer scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN); + @Override + public Hasher putByte(byte b) { + update(b); + return this; + } + + @Override + public Hasher putBytes(byte[] bytes) { + checkNotNull(bytes); + update(bytes); + return this; + } + + @Override + public Hasher putBytes(byte[] bytes, int off, int len) { + checkPositionIndexes(off, off + len, bytes.length); + update(bytes, off, len); + return this; + } + + @Override + public Hasher putChar(char c) { + scratch.putChar(c); + return update(Chars.BYTES); + } + + @Override + public Hasher putInt(int i) { + scratch.putInt(i); + return update(Ints.BYTES); + } + + @Override + public Hasher putLong(long l) { + scratch.putLong(l); + return update(Longs.BYTES); + } + + @Override + public Hasher putObject(T instance, Funnel funnel) { + funnel.funnel(instance, this); + return this; + } + + @Override + public Hasher putShort(short s) { + scratch.putShort(s); + return update(Shorts.BYTES); + } + /** * Updates this hasher with the given byte. */ @@ -60,26 +110,6 @@ abstract class AbstractByteHasher extends AbstractHasher { } } - @Override - public Hasher putByte(byte b) { - update(b); - return this; - } - - @Override - public Hasher putBytes(byte[] bytes) { - checkNotNull(bytes); - update(bytes); - return this; - } - - @Override - public Hasher putBytes(byte[] bytes, int off, int len) { - checkPositionIndexes(off, off + len, bytes.length); - update(bytes, off, len); - return this; - } - /** * Updates the sink with the given number of bytes from the buffer. */ @@ -91,34 +121,4 @@ abstract class AbstractByteHasher extends AbstractHasher { } return this; } - - @Override - public Hasher putShort(short s) { - scratch.putShort(s); - return update(Shorts.BYTES); - } - - @Override - public Hasher putInt(int i) { - scratch.putInt(i); - return update(Ints.BYTES); - } - - @Override - public Hasher putLong(long l) { - scratch.putLong(l); - return update(Longs.BYTES); - } - - @Override - public Hasher putChar(char c) { - scratch.putChar(c); - return update(Chars.BYTES); - } - - @Override - public Hasher putObject(T instance, Funnel funnel) { - funnel.funnel(instance, this); - return this; - } } diff --git a/src/main/java/com/google/common/hash/AbstractCompositeHashFunction.java b/src/main/java/com/google/common/hash/AbstractCompositeHashFunction.java index 7465afe5..c4a951f7 100644 --- a/src/main/java/com/google/common/hash/AbstractCompositeHashFunction.java +++ b/src/main/java/com/google/common/hash/AbstractCompositeHashFunction.java @@ -29,6 +29,8 @@ import java.nio.charset.Charset; * @author Dimitris Andreou */ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFunction { + private static final long serialVersionUID = 0L; + final HashFunction[] functions; AbstractCompositeHashFunction(HashFunction... functions) { @@ -55,6 +57,19 @@ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFuncti hashers[i] = functions[i].newHasher(); } return new Hasher() { + @Override + public HashCode hash() { + return makeHash(hashers); + } + + @Override + public Hasher putBoolean(boolean b) { + for (Hasher hasher : hashers) { + hasher.putBoolean(b); + } + return this; + } + @Override public Hasher putByte(byte b) { for (Hasher hasher : hashers) { @@ -80,9 +95,25 @@ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFuncti } @Override - public Hasher putShort(short s) { + public Hasher putChar(char c) { for (Hasher hasher : hashers) { - hasher.putShort(s); + hasher.putChar(c); + } + return this; + } + + @Override + public Hasher putDouble(double d) { + for (Hasher hasher : hashers) { + hasher.putDouble(d); + } + return this; + } + + @Override + public Hasher putFloat(float f) { + for (Hasher hasher : hashers) { + hasher.putFloat(f); } return this; } @@ -104,41 +135,17 @@ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFuncti } @Override - public Hasher putFloat(float f) { + public Hasher putObject(T instance, Funnel funnel) { for (Hasher hasher : hashers) { - hasher.putFloat(f); + hasher.putObject(instance, funnel); } return this; } @Override - public Hasher putDouble(double d) { + public Hasher putShort(short s) { for (Hasher hasher : hashers) { - hasher.putDouble(d); - } - return this; - } - - @Override - public Hasher putBoolean(boolean b) { - for (Hasher hasher : hashers) { - hasher.putBoolean(b); - } - return this; - } - - @Override - public Hasher putChar(char c) { - for (Hasher hasher : hashers) { - hasher.putChar(c); - } - return this; - } - - @Override - public Hasher putUnencodedChars(CharSequence chars) { - for (Hasher hasher : hashers) { - hasher.putUnencodedChars(chars); + hasher.putShort(s); } return this; } @@ -152,19 +159,12 @@ abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFuncti } @Override - public Hasher putObject(T instance, Funnel funnel) { + public Hasher putUnencodedChars(CharSequence chars) { for (Hasher hasher : hashers) { - hasher.putObject(instance, funnel); + hasher.putUnencodedChars(chars); } return this; } - - @Override - public HashCode hash() { - return makeHash(hashers); - } }; } - - private static final long serialVersionUID = 0L; } diff --git a/src/main/java/com/google/common/hash/AbstractHasher.java b/src/main/java/com/google/common/hash/AbstractHasher.java index 7b6eb2cf..e86abf15 100644 --- a/src/main/java/com/google/common/hash/AbstractHasher.java +++ b/src/main/java/com/google/common/hash/AbstractHasher.java @@ -40,6 +40,11 @@ abstract class AbstractHasher implements Hasher { return putInt(Float.floatToRawIntBits(f)); } + @Override + public Hasher putString(CharSequence charSequence, Charset charset) { + return putBytes(charSequence.toString().getBytes(charset)); + } + @Override public Hasher putUnencodedChars(CharSequence charSequence) { for (int i = 0, len = charSequence.length(); i < len; i++) { @@ -47,9 +52,4 @@ abstract class AbstractHasher implements Hasher { } return this; } - - @Override - public Hasher putString(CharSequence charSequence, Charset charset) { - return putBytes(charSequence.toString().getBytes(charset)); - } } diff --git a/src/main/java/com/google/common/hash/AbstractNonStreamingHashFunction.java b/src/main/java/com/google/common/hash/AbstractNonStreamingHashFunction.java index 8ea1dbb3..8aefa9cb 100644 --- a/src/main/java/com/google/common/hash/AbstractNonStreamingHashFunction.java +++ b/src/main/java/com/google/common/hash/AbstractNonStreamingHashFunction.java @@ -31,63 +31,22 @@ import com.google.common.base.Preconditions; * @author Dimitris Andreou */ abstract class AbstractNonStreamingHashFunction implements HashFunction { - @Override - public Hasher newHasher() { - return new BufferingHasher(32); - } - - @Override - public Hasher newHasher(int expectedInputSize) { - Preconditions.checkArgument(expectedInputSize >= 0); - return new BufferingHasher(expectedInputSize); - } - - @Override - public HashCode hashObject(T instance, Funnel funnel) { - return newHasher().putObject(instance, funnel).hash(); - } - - @Override - public HashCode hashUnencodedChars(CharSequence input) { - int len = input.length(); - Hasher hasher = newHasher(len * 2); - for (int i = 0; i < len; i++) { - hasher.putChar(input.charAt(i)); - } - return hasher.hash(); - } - - @Override - public HashCode hashString(CharSequence input, Charset charset) { - return hashBytes(input.toString().getBytes(charset)); - } - - @Override - public HashCode hashInt(int input) { - return newHasher(4).putInt(input).hash(); - } - - @Override - public HashCode hashLong(long input) { - return newHasher(8).putLong(input).hash(); - } - - @Override - public HashCode hashBytes(byte[] input) { - return hashBytes(input, 0, input.length); - } - /** * In-memory stream-based implementation of Hasher. */ private final class BufferingHasher extends AbstractHasher { - final ExposedByteArrayOutputStream stream; static final int BOTTOM_BYTE = 0xFF; + final ExposedByteArrayOutputStream stream; BufferingHasher(int expectedInputSize) { this.stream = new ExposedByteArrayOutputStream(expectedInputSize); } + @Override + public HashCode hash() { + return hashBytes(stream.byteArray(), 0, stream.length()); + } + @Override public Hasher putByte(byte b) { stream.write(b); @@ -111,9 +70,9 @@ abstract class AbstractNonStreamingHashFunction implements HashFunction { } @Override - public Hasher putShort(short s) { - stream.write(s & BOTTOM_BYTE); - stream.write((s >>> 8) & BOTTOM_BYTE); + public Hasher putChar(char c) { + stream.write(c & BOTTOM_BYTE); + stream.write((c >>> 8) & BOTTOM_BYTE); return this; } @@ -134,13 +93,6 @@ abstract class AbstractNonStreamingHashFunction implements HashFunction { return this; } - @Override - public Hasher putChar(char c) { - stream.write(c & BOTTOM_BYTE); - stream.write((c >>> 8) & BOTTOM_BYTE); - return this; - } - @Override public Hasher putObject(T instance, Funnel funnel) { funnel.funnel(instance, this); @@ -148,8 +100,10 @@ abstract class AbstractNonStreamingHashFunction implements HashFunction { } @Override - public HashCode hash() { - return hashBytes(stream.byteArray(), 0, stream.length()); + public Hasher putShort(short s) { + stream.write(s & BOTTOM_BYTE); + stream.write((s >>> 8) & BOTTOM_BYTE); + return this; } } @@ -167,4 +121,50 @@ abstract class AbstractNonStreamingHashFunction implements HashFunction { return count; } } + + @Override + public HashCode hashBytes(byte[] input) { + return hashBytes(input, 0, input.length); + } + + @Override + public HashCode hashInt(int input) { + return newHasher(4).putInt(input).hash(); + } + + @Override + public HashCode hashLong(long input) { + return newHasher(8).putLong(input).hash(); + } + + @Override + public HashCode hashObject(T instance, Funnel funnel) { + return newHasher().putObject(instance, funnel).hash(); + } + + @Override + public HashCode hashString(CharSequence input, Charset charset) { + return hashBytes(input.toString().getBytes(charset)); + } + + @Override + public HashCode hashUnencodedChars(CharSequence input) { + int len = input.length(); + Hasher hasher = newHasher(len * 2); + for (int i = 0; i < len; i++) { + hasher.putChar(input.charAt(i)); + } + return hasher.hash(); + } + + @Override + public Hasher newHasher() { + return new BufferingHasher(32); + } + + @Override + public Hasher newHasher(int expectedInputSize) { + Preconditions.checkArgument(expectedInputSize >= 0); + return new BufferingHasher(expectedInputSize); + } } diff --git a/src/main/java/com/google/common/hash/AbstractStreamingHashFunction.java b/src/main/java/com/google/common/hash/AbstractStreamingHashFunction.java index ccece293..5208a52b 100644 --- a/src/main/java/com/google/common/hash/AbstractStreamingHashFunction.java +++ b/src/main/java/com/google/common/hash/AbstractStreamingHashFunction.java @@ -34,47 +34,6 @@ import com.google.common.base.Preconditions; * @author Kevin Bourrillion */ abstract class AbstractStreamingHashFunction implements HashFunction { - @Override - public HashCode hashObject(T instance, Funnel funnel) { - return newHasher().putObject(instance, funnel).hash(); - } - - @Override - public HashCode hashUnencodedChars(CharSequence input) { - return newHasher().putUnencodedChars(input).hash(); - } - - @Override - public HashCode hashString(CharSequence input, Charset charset) { - return newHasher().putString(input, charset).hash(); - } - - @Override - public HashCode hashInt(int input) { - return newHasher().putInt(input).hash(); - } - - @Override - public HashCode hashLong(long input) { - return newHasher().putLong(input).hash(); - } - - @Override - public HashCode hashBytes(byte[] input) { - return newHasher().putBytes(input).hash(); - } - - @Override - public HashCode hashBytes(byte[] input, int off, int len) { - return newHasher().putBytes(input, off, len).hash(); - } - - @Override - public Hasher newHasher(int expectedInputSize) { - Preconditions.checkArgument(expectedInputSize >= 0); - return newHasher(); - } - /** * A convenience base class for implementors of {@code Hasher}; handles * accumulating data until an entire "chunk" (of implementation-dependent @@ -128,6 +87,37 @@ abstract class AbstractStreamingHashFunction implements HashFunction { this.chunkSize = chunkSize; } + @Override + public final HashCode hash() { + munch(); + buffer.flip(); + if (buffer.remaining() > 0) { + processRemaining(buffer); + } + return makeHash(); + } + + abstract HashCode makeHash(); + + private void munch() { + buffer.flip(); + while (buffer.remaining() >= chunkSize) { + // we could limit the buffer to ensure process() does not read more than + // chunkSize number of bytes, but we trust the implementations + process(buffer); + } + buffer.compact(); // preserve any remaining data that do not make a full chunk + } + + // Process pent-up data in chunks + private void munchIfFull() { + if (buffer.remaining() < 8) { + // buffer is full; not enough room for a primitive. We have at least one full + // chunk. + munch(); + } + } + /** * Processes the available bytes of the buffer (at most {@code chunk} bytes). */ @@ -152,6 +142,13 @@ abstract class AbstractStreamingHashFunction implements HashFunction { process(bb); } + @Override + public final Hasher putByte(byte b) { + buffer.put(b); + munchIfFull(); + return this; + } + @Override public final Hasher putBytes(byte[] bytes) { return putBytes(bytes, 0, bytes.length); @@ -187,28 +184,6 @@ abstract class AbstractStreamingHashFunction implements HashFunction { return this; } - @Override - public final Hasher putUnencodedChars(CharSequence charSequence) { - for (int i = 0; i < charSequence.length(); i++) { - putChar(charSequence.charAt(i)); - } - return this; - } - - @Override - public final Hasher putByte(byte b) { - buffer.put(b); - munchIfFull(); - return this; - } - - @Override - public final Hasher putShort(short s) { - buffer.putShort(s); - munchIfFull(); - return this; - } - @Override public final Hasher putChar(char c) { buffer.putChar(c); @@ -237,34 +212,59 @@ abstract class AbstractStreamingHashFunction implements HashFunction { } @Override - public final HashCode hash() { - munch(); - buffer.flip(); - if (buffer.remaining() > 0) { - processRemaining(buffer); - } - return makeHash(); + public final Hasher putShort(short s) { + buffer.putShort(s); + munchIfFull(); + return this; } - abstract HashCode makeHash(); - - // Process pent-up data in chunks - private void munchIfFull() { - if (buffer.remaining() < 8) { - // buffer is full; not enough room for a primitive. We have at least one full - // chunk. - munch(); + @Override + public final Hasher putUnencodedChars(CharSequence charSequence) { + for (int i = 0; i < charSequence.length(); i++) { + putChar(charSequence.charAt(i)); } - } - - private void munch() { - buffer.flip(); - while (buffer.remaining() >= chunkSize) { - // we could limit the buffer to ensure process() does not read more than - // chunkSize number of bytes, but we trust the implementations - process(buffer); - } - buffer.compact(); // preserve any remaining data that do not make a full chunk + return this; } } + + @Override + public HashCode hashBytes(byte[] input) { + return newHasher().putBytes(input).hash(); + } + + @Override + public HashCode hashBytes(byte[] input, int off, int len) { + return newHasher().putBytes(input, off, len).hash(); + } + + @Override + public HashCode hashInt(int input) { + return newHasher().putInt(input).hash(); + } + + @Override + public HashCode hashLong(long input) { + return newHasher().putLong(input).hash(); + } + + @Override + public HashCode hashObject(T instance, Funnel funnel) { + return newHasher().putObject(instance, funnel).hash(); + } + + @Override + public HashCode hashString(CharSequence input, Charset charset) { + return newHasher().putString(input, charset).hash(); + } + + @Override + public HashCode hashUnencodedChars(CharSequence input) { + return newHasher().putUnencodedChars(input).hash(); + } + + @Override + public Hasher newHasher(int expectedInputSize) { + Preconditions.checkArgument(expectedInputSize >= 0); + return newHasher(); + } } diff --git a/src/main/java/com/google/common/hash/BloomFilter.java b/src/main/java/com/google/common/hash/BloomFilter.java index 2c249a10..0db567fa 100644 --- a/src/main/java/com/google/common/hash/BloomFilter.java +++ b/src/main/java/com/google/common/hash/BloomFilter.java @@ -57,6 +57,26 @@ import com.google.common.hash.BloomFilterStrategies.BitArray; */ @Beta public final class BloomFilter implements Predicate, Serializable { + private static class SerialForm implements Serializable { + private static final long serialVersionUID = 1; + final long[] data; + final int numHashFunctions; + final Funnel funnel; + + final Strategy strategy; + + SerialForm(BloomFilter bf) { + this.data = bf.bits.data; + this.numHashFunctions = bf.numHashFunctions; + this.funnel = bf.funnel; + this.strategy = bf.strategy; + } + + Object readResolve() { + return new BloomFilter(new BitArray(data), numHashFunctions, funnel, strategy); + } + } + /** * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. * @@ -65,15 +85,6 @@ public final class BloomFilter implements Predicate, Serializable { */ interface Strategy extends java.io.Serializable { - /** - * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user - * element. - * - *

- * Returns whether any bits changed as a result of this operation. - */ - boolean put(T object, Funnel funnel, int numHashFunctions, BitArray bits); - /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a * user element; returns {@code true} if and only if all selected bits are set. @@ -89,173 +100,15 @@ public final class BloomFilter implements Predicate, Serializable { * input). */ int ordinal(); - } - /** The bit set of the BloomFilter (not necessarily power of 2!) */ - private final BitArray bits; - - /** Number of hashes per element */ - private final int numHashFunctions; - - /** The funnel to translate Ts to bytes */ - private final Funnel funnel; - - /** - * The strategy we employ to map an element T to {@code numHashFunctions} bit - * indexes. - */ - private final Strategy strategy; - - /** - * Creates a BloomFilter. - */ - private BloomFilter(BitArray bits, int numHashFunctions, Funnel funnel, Strategy strategy) { - checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); - checkArgument(numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); - this.bits = checkNotNull(bits); - this.numHashFunctions = numHashFunctions; - this.funnel = checkNotNull(funnel); - this.strategy = checkNotNull(strategy); - } - - /** - * Creates a new {@code BloomFilter} that's a copy of this instance. The new - * instance is equal to this instance but shares no mutable state. - * - * @since 12.0 - */ - public BloomFilter copy() { - return new BloomFilter(bits.copy(), numHashFunctions, funnel, strategy); - } - - /** - * Returns {@code true} if the element might have been put in this Bloom - * filter, {@code false} if this is definitely not the case. - */ - public boolean mightContain(T object) { - return strategy.mightContain(object, funnel, numHashFunctions, bits); - } - - /** - * @deprecated Provided only to satisfy the {@link Predicate} interface; use - * {@link #mightContain} instead. - */ - @Deprecated - @Override - public boolean apply(T input) { - return mightContain(input); - } - - /** - * Puts an element into this {@code BloomFilter}. Ensures that subsequent - * invocations of {@link #mightContain(Object)} with the same element will - * always return {@code true}. - * - * @return true if the bloom filter's bits changed as a result of this - * operation. If the bits changed, this is definitely the first - * time {@code object} has been added to the filter. If the bits haven't - * changed, this might be the first time {@code object} has been - * added to the filter. Note that {@code put(t)} always returns the - * opposite result to what {@code mightContain(t)} would have - * returned at the time it is called." - * @since 12.0 (present in 11.0 with {@code void} return type}) - */ - public boolean put(T object) { - return strategy.put(object, funnel, numHashFunctions, bits); - } - - /** - * Returns the probability that {@linkplain #mightContain(Object)} will - * erroneously return {@code true} for an object that has not actually been put - * in the {@code BloomFilter}. - * - *

- * Ideally, this number should be close to the {@code fpp} parameter passed in - * {@linkplain #create(Funnel, int, double)}, or smaller. If it is significantly - * higher, it is usually the case that too many elements (more than expected) - * have been put in the {@code BloomFilter}, degenerating it. - * - * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) - */ - public double expectedFpp() { - // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last - // homie!) - return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); - } - - /** - * Returns the number of bits in the underlying bit array. - */ - @VisibleForTesting - long bitSize() { - return bits.bitSize(); - } - - /** - * Determines whether a given bloom filter is compatible with this bloom filter. - * For two bloom filters to be compatible, they must: - * - *

    - *
  • not be the same instance - *
  • have the same number of hash functions - *
  • have the same bit size - *
  • have the same strategy - *
  • have equal funnels - *
      - * - * @param that The bloom filter to check for compatibility. - * @since 15.0 - */ - public boolean isCompatible(BloomFilter that) { - checkNotNull(that); - return (this != that) && (this.numHashFunctions == that.numHashFunctions) && (this.bitSize() == that.bitSize()) - && (this.strategy.equals(that.strategy)) && (this.funnel.equals(that.funnel)); - } - - /** - * Combines this bloom filter with another bloom filter by performing a bitwise - * OR of the underlying data. The mutations happen to this instance. - * Callers must ensure the bloom filters are appropriately sized to avoid - * saturating them. - * - * @param that The bloom filter to combine this bloom filter with. It is not - * mutated. - * @throws IllegalArgumentException if {@code isCompatible(that) == false} - * - * @since 15.0 - */ - public void putAll(BloomFilter that) { - checkNotNull(that); - checkArgument(this != that, "Cannot combine a BloomFilter with itself."); - checkArgument(this.numHashFunctions == that.numHashFunctions, - "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, - that.numHashFunctions); - checkArgument(this.bitSize() == that.bitSize(), - "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), - that.bitSize()); - checkArgument(this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", - this.strategy, that.strategy); - checkArgument(this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, - that.funnel); - this.bits.putAll(that.bits); - } - - @Override - public boolean equals(@Nullable Object object) { - if (object == this) { - return true; - } - if (object instanceof BloomFilter) { - BloomFilter that = (BloomFilter) object; - return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) - && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); - } - return false; - } - - @Override - public int hashCode() { - return Objects.hashCode(numHashFunctions, funnel, strategy, bits); + /** + * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user + * element. + * + *

      + * Returns whether any bits changed as a result of this operation. + */ + boolean put(T object, Funnel funnel, int numHashFunctions, BitArray bits); } private static final Strategy DEFAULT_STRATEGY = getDefaultStrategyFromSystemProperty(); @@ -263,10 +116,28 @@ public final class BloomFilter implements Predicate, Serializable { @VisibleForTesting static final String USE_MITZ32_PROPERTY = "com.google.common.hash.BloomFilter.useMitz32"; - @VisibleForTesting - static Strategy getDefaultStrategyFromSystemProperty() { - return Boolean.parseBoolean(System.getProperty(USE_MITZ32_PROPERTY)) ? BloomFilterStrategies.MURMUR128_MITZ_32 - : BloomFilterStrategies.MURMUR128_MITZ_64; + /** + * Creates a {@link BloomFilter BloomFilter} with the expected number of + * insertions and a default expected false positive probability of 3%. + * + *

      + * Note that overflowing a {@code BloomFilter} with significantly more elements + * than specified, will result in its saturation, and a sharp deterioration of + * its false positive probability. + * + *

      + * The constructed {@code BloomFilter} will be serializable if the provided + * {@code Funnel} is. + * + * @param funnel the funnel of T's that the constructed + * {@code BloomFilter} will use + * @param expectedInsertions the number of expected insertions to the + * constructed {@code BloomFilter}; must be + * positive + * @return a {@code BloomFilter} + */ + public static BloomFilter create(Funnel funnel, int expectedInsertions /* n */) { + return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } /** @@ -326,54 +197,10 @@ public final class BloomFilter implements Predicate, Serializable { } } - /** - * Creates a {@link BloomFilter BloomFilter} with the expected number of - * insertions and a default expected false positive probability of 3%. - * - *

      - * Note that overflowing a {@code BloomFilter} with significantly more elements - * than specified, will result in its saturation, and a sharp deterioration of - * its false positive probability. - * - *

      - * The constructed {@code BloomFilter} will be serializable if the provided - * {@code Funnel} is. - * - * @param funnel the funnel of T's that the constructed - * {@code BloomFilter} will use - * @param expectedInsertions the number of expected insertions to the - * constructed {@code BloomFilter}; must be - * positive - * @return a {@code BloomFilter} - */ - public static BloomFilter create(Funnel funnel, int expectedInsertions /* n */) { - return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions - } - - /* - * Cheat sheet: - * - * m: total bits n: expected insertions b: m/n, bits per insertion p: expected - * false positive probability - * - * 1) Optimal k = b * ln2 2) p = (1 - e ^ (-kn/m))^k 3) For optimal k: p = 2 ^ - * (-k) ~= 0.6185^b 4) For optimal k: m = -nlnp / ((ln2) ^ 2) - */ - - /** - * Computes the optimal k (number of hashes per element inserted in Bloom - * filter), given the expected insertions and total number of bits in the Bloom - * filter. - * - * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the - * formula. - * - * @param n expected insertions (must be positive) - * @param m total number of bits in Bloom filter (must be positive) - */ @VisibleForTesting - static int optimalNumOfHashFunctions(long n, long m) { - return Math.max(1, (int) Math.round(m / n * Math.log(2))); + static Strategy getDefaultStrategyFromSystemProperty() { + return Boolean.parseBoolean(System.getProperty(USE_MITZ32_PROPERTY)) ? BloomFilterStrategies.MURMUR128_MITZ_32 + : BloomFilterStrategies.MURMUR128_MITZ_64; } /** @@ -394,27 +221,200 @@ public final class BloomFilter implements Predicate, Serializable { return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2))); } + /** + * Computes the optimal k (number of hashes per element inserted in Bloom + * filter), given the expected insertions and total number of bits in the Bloom + * filter. + * + * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the + * formula. + * + * @param n expected insertions (must be positive) + * @param m total number of bits in Bloom filter (must be positive) + */ + @VisibleForTesting + static int optimalNumOfHashFunctions(long n, long m) { + return Math.max(1, (int) Math.round(m / n * Math.log(2))); + } + + /** The bit set of the BloomFilter (not necessarily power of 2!) */ + private final BitArray bits; + + /** Number of hashes per element */ + private final int numHashFunctions; + + /** The funnel to translate Ts to bytes */ + private final Funnel funnel; + + /** + * The strategy we employ to map an element T to {@code numHashFunctions} bit + * indexes. + */ + private final Strategy strategy; + + /** + * Creates a BloomFilter. + */ + private BloomFilter(BitArray bits, int numHashFunctions, Funnel funnel, Strategy strategy) { + checkArgument(numHashFunctions > 0, "numHashFunctions (%s) must be > 0", numHashFunctions); + checkArgument(numHashFunctions <= 255, "numHashFunctions (%s) must be <= 255", numHashFunctions); + this.bits = checkNotNull(bits); + this.numHashFunctions = numHashFunctions; + this.funnel = checkNotNull(funnel); + this.strategy = checkNotNull(strategy); + } + + /** + * @deprecated Provided only to satisfy the {@link Predicate} interface; use + * {@link #mightContain} instead. + */ + @Deprecated + @Override + public boolean apply(T input) { + return mightContain(input); + } + + /** + * Returns the number of bits in the underlying bit array. + */ + @VisibleForTesting + long bitSize() { + return bits.bitSize(); + } + + /** + * Creates a new {@code BloomFilter} that's a copy of this instance. The new + * instance is equal to this instance but shares no mutable state. + * + * @since 12.0 + */ + public BloomFilter copy() { + return new BloomFilter(bits.copy(), numHashFunctions, funnel, strategy); + } + + @Override + public boolean equals(@Nullable Object object) { + if (object == this) { + return true; + } + if (object instanceof BloomFilter) { + BloomFilter that = (BloomFilter) object; + return this.numHashFunctions == that.numHashFunctions && this.funnel.equals(that.funnel) + && this.bits.equals(that.bits) && this.strategy.equals(that.strategy); + } + return false; + } + + /** + * Returns the probability that {@linkplain #mightContain(Object)} will + * erroneously return {@code true} for an object that has not actually been put + * in the {@code BloomFilter}. + * + *

      + * Ideally, this number should be close to the {@code fpp} parameter passed in + * {@linkplain #create(Funnel, int, double)}, or smaller. If it is significantly + * higher, it is usually the case that too many elements (more than expected) + * have been put in the {@code BloomFilter}, degenerating it. + * + * @since 14.0 (since 11.0 as expectedFalsePositiveProbability()) + */ + public double expectedFpp() { + // You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last + // homie!) + return Math.pow((double) bits.bitCount() / bitSize(), numHashFunctions); + } + + @Override + public int hashCode() { + return Objects.hashCode(numHashFunctions, funnel, strategy, bits); + } + + /** + * Determines whether a given bloom filter is compatible with this bloom filter. + * For two bloom filters to be compatible, they must: + * + *

        + *
      • not be the same instance + *
      • have the same number of hash functions + *
      • have the same bit size + *
      • have the same strategy + *
      • have equal funnels + *
          + * + * @param that The bloom filter to check for compatibility. + * @since 15.0 + */ + public boolean isCompatible(BloomFilter that) { + checkNotNull(that); + return (this != that) && (this.numHashFunctions == that.numHashFunctions) && (this.bitSize() == that.bitSize()) + && (this.strategy.equals(that.strategy)) && (this.funnel.equals(that.funnel)); + } + + /* + * Cheat sheet: + * + * m: total bits n: expected insertions b: m/n, bits per insertion p: expected + * false positive probability + * + * 1) Optimal k = b * ln2 2) p = (1 - e ^ (-kn/m))^k 3) For optimal k: p = 2 ^ + * (-k) ~= 0.6185^b 4) For optimal k: m = -nlnp / ((ln2) ^ 2) + */ + + /** + * Returns {@code true} if the element might have been put in this Bloom + * filter, {@code false} if this is definitely not the case. + */ + public boolean mightContain(T object) { + return strategy.mightContain(object, funnel, numHashFunctions, bits); + } + + /** + * Puts an element into this {@code BloomFilter}. Ensures that subsequent + * invocations of {@link #mightContain(Object)} with the same element will + * always return {@code true}. + * + * @return true if the bloom filter's bits changed as a result of this + * operation. If the bits changed, this is definitely the first + * time {@code object} has been added to the filter. If the bits haven't + * changed, this might be the first time {@code object} has been + * added to the filter. Note that {@code put(t)} always returns the + * opposite result to what {@code mightContain(t)} would have + * returned at the time it is called." + * @since 12.0 (present in 11.0 with {@code void} return type}) + */ + public boolean put(T object) { + return strategy.put(object, funnel, numHashFunctions, bits); + } + + /** + * Combines this bloom filter with another bloom filter by performing a bitwise + * OR of the underlying data. The mutations happen to this instance. + * Callers must ensure the bloom filters are appropriately sized to avoid + * saturating them. + * + * @param that The bloom filter to combine this bloom filter with. It is not + * mutated. + * @throws IllegalArgumentException if {@code isCompatible(that) == false} + * + * @since 15.0 + */ + public void putAll(BloomFilter that) { + checkNotNull(that); + checkArgument(this != that, "Cannot combine a BloomFilter with itself."); + checkArgument(this.numHashFunctions == that.numHashFunctions, + "BloomFilters must have the same number of hash functions (%s != %s)", this.numHashFunctions, + that.numHashFunctions); + checkArgument(this.bitSize() == that.bitSize(), + "BloomFilters must have the same size underlying bit arrays (%s != %s)", this.bitSize(), + that.bitSize()); + checkArgument(this.strategy.equals(that.strategy), "BloomFilters must have equal strategies (%s != %s)", + this.strategy, that.strategy); + checkArgument(this.funnel.equals(that.funnel), "BloomFilters must have equal funnels (%s != %s)", this.funnel, + that.funnel); + this.bits.putAll(that.bits); + } + private Object writeReplace() { return new SerialForm(this); } - - private static class SerialForm implements Serializable { - final long[] data; - final int numHashFunctions; - final Funnel funnel; - final Strategy strategy; - - SerialForm(BloomFilter bf) { - this.data = bf.bits.data; - this.numHashFunctions = bf.numHashFunctions; - this.funnel = bf.funnel; - this.strategy = bf.strategy; - } - - Object readResolve() { - return new BloomFilter(new BitArray(data), numHashFunctions, funnel, strategy); - } - - private static final long serialVersionUID = 1; - } } diff --git a/src/main/java/com/google/common/hash/BloomFilterStrategies.java b/src/main/java/com/google/common/hash/BloomFilterStrategies.java index 739969c4..31ef2ae8 100644 --- a/src/main/java/com/google/common/hash/BloomFilterStrategies.java +++ b/src/main/java/com/google/common/hash/BloomFilterStrategies.java @@ -44,25 +44,6 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { * two 32bit hash functions). */ MURMUR128_MITZ_32() { - @Override - public boolean put(T object, Funnel funnel, int numHashFunctions, BitArray bits) { - long bitSize = bits.bitSize(); - long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); - int hash1 = (int) hash64; - int hash2 = (int) (hash64 >>> 32); - - boolean bitsChanged = false; - for (int i = 1; i <= numHashFunctions; i++) { - int combinedHash = hash1 + (i * hash2); - // Flip all the bits if it's negative (guaranteed positive number) - if (combinedHash < 0) { - combinedHash = ~combinedHash; - } - bitsChanged |= bits.set(combinedHash % bitSize); - } - return bitsChanged; - } - @Override public boolean mightContain(T object, Funnel funnel, int numHashFunctions, BitArray bits) { long bitSize = bits.bitSize(); @@ -82,6 +63,25 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { } return true; } + + @Override + public boolean put(T object, Funnel funnel, int numHashFunctions, BitArray bits) { + long bitSize = bits.bitSize(); + long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); + int hash1 = (int) hash64; + int hash2 = (int) (hash64 >>> 32); + + boolean bitsChanged = false; + for (int i = 1; i <= numHashFunctions; i++) { + int combinedHash = hash1 + (i * hash2); + // Flip all the bits if it's negative (guaranteed positive number) + if (combinedHash < 0) { + combinedHash = ~combinedHash; + } + bitsChanged |= bits.set(combinedHash % bitSize); + } + return bitsChanged; + } }, /** * This strategy uses all 128 bits of {@link Hashing#murmur3_128} when hashing. @@ -91,21 +91,8 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { * Long.MAX_VALUE instead of flipping the bits. */ MURMUR128_MITZ_64() { - @Override - public boolean put(T object, Funnel funnel, int numHashFunctions, BitArray bits) { - long bitSize = bits.bitSize(); - byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal(); - long hash1 = lowerEight(bytes); - long hash2 = upperEight(bytes); - - boolean bitsChanged = false; - long combinedHash = hash1; - for (int i = 0; i < numHashFunctions; i++) { - // Make the combined hash positive and indexable - bitsChanged |= bits.set((combinedHash & Long.MAX_VALUE) % bitSize); - combinedHash += hash2; - } - return bitsChanged; + private /* static */ long lowerEight(byte[] bytes) { + return Longs.fromBytes(bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]); } @Override @@ -126,8 +113,21 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { return true; } - private /* static */ long lowerEight(byte[] bytes) { - return Longs.fromBytes(bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]); + @Override + public boolean put(T object, Funnel funnel, int numHashFunctions, BitArray bits) { + long bitSize = bits.bitSize(); + byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal(); + long hash1 = lowerEight(bytes); + long hash2 = upperEight(bytes); + + boolean bitsChanged = false; + long combinedHash = hash1; + for (int i = 0; i < numHashFunctions; i++) { + // Make the combined hash positive and indexable + bitsChanged |= bits.set((combinedHash & Long.MAX_VALUE) % bitSize); + combinedHash += hash2; + } + return bitsChanged; } private /* static */ long upperEight(byte[] bytes) { @@ -157,12 +157,25 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { this.bitCount = bitCount; } - /** Returns true if the bit changed value. */ - boolean set(long index) { - if (!get(index)) { - data[(int) (index >>> 6)] |= (1L << index); - bitCount++; - return true; + /** Number of set bits (1s) */ + long bitCount() { + return bitCount; + } + + /** Number of bits */ + long bitSize() { + return (long) data.length * Long.SIZE; + } + + BitArray copy() { + return new BitArray(data.clone()); + } + + @Override + public boolean equals(Object o) { + if (o instanceof BitArray) { + BitArray bitArray = (BitArray) o; + return Arrays.equals(data, bitArray.data); } return false; } @@ -171,18 +184,9 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { return (data[(int) (index >>> 6)] & (1L << index)) != 0; } - /** Number of bits */ - long bitSize() { - return (long) data.length * Long.SIZE; - } - - /** Number of set bits (1s) */ - long bitCount() { - return bitCount; - } - - BitArray copy() { - return new BitArray(data.clone()); + @Override + public int hashCode() { + return Arrays.hashCode(data); } /** Combines the two BitArrays using bitwise OR. */ @@ -196,18 +200,14 @@ enum BloomFilterStrategies implements BloomFilter.Strategy { } } - @Override - public boolean equals(Object o) { - if (o instanceof BitArray) { - BitArray bitArray = (BitArray) o; - return Arrays.equals(data, bitArray.data); + /** Returns true if the bit changed value. */ + boolean set(long index) { + if (!get(index)) { + data[(int) (index >>> 6)] |= (1L << index); + bitCount++; + return true; } return false; } - - @Override - public int hashCode() { - return Arrays.hashCode(data); - } } } diff --git a/src/main/java/com/google/common/hash/ChecksumHashFunction.java b/src/main/java/com/google/common/hash/ChecksumHashFunction.java index 82660b94..eb34e43b 100644 --- a/src/main/java/com/google/common/hash/ChecksumHashFunction.java +++ b/src/main/java/com/google/common/hash/ChecksumHashFunction.java @@ -29,8 +29,48 @@ import com.google.common.base.Supplier; */ final class ChecksumHashFunction extends AbstractStreamingHashFunction implements Serializable { + /** + * Hasher that updates a checksum. + */ + private final class ChecksumHasher extends AbstractByteHasher { + + private final Checksum checksum; + + private ChecksumHasher(Checksum checksum) { + this.checksum = checkNotNull(checksum); + } + + @Override + public HashCode hash() { + long value = checksum.getValue(); + if (bits == 32) { + /* + * The long returned from a 32-bit Checksum will have all 0s for its second + * word, so the cast won't lose any information and is necessary to return a + * HashCode of the correct size. + */ + return HashCode.fromInt((int) value); + } else { + return HashCode.fromLong(value); + } + } + + @Override + protected void update(byte b) { + checksum.update(b); + } + + @Override + protected void update(byte[] bytes, int off, int len) { + checksum.update(bytes, off, len); + } + } + + private static final long serialVersionUID = 0L; private final Supplier checksumSupplier; + private final int bits; + private final String toString; ChecksumHashFunction(Supplier checksumSupplier, int bits, String toString) { @@ -54,43 +94,4 @@ final class ChecksumHashFunction extends AbstractStreamingHashFunction implement public String toString() { return toString; } - - /** - * Hasher that updates a checksum. - */ - private final class ChecksumHasher extends AbstractByteHasher { - - private final Checksum checksum; - - private ChecksumHasher(Checksum checksum) { - this.checksum = checkNotNull(checksum); - } - - @Override - protected void update(byte b) { - checksum.update(b); - } - - @Override - protected void update(byte[] bytes, int off, int len) { - checksum.update(bytes, off, len); - } - - @Override - public HashCode hash() { - long value = checksum.getValue(); - if (bits == 32) { - /* - * The long returned from a 32-bit Checksum will have all 0s for its second - * word, so the cast won't lose any information and is necessary to return a - * HashCode of the correct size. - */ - return HashCode.fromInt((int) value); - } else { - return HashCode.fromLong(value); - } - } - } - - private static final long serialVersionUID = 0L; } diff --git a/src/main/java/com/google/common/hash/Funnel.java b/src/main/java/com/google/common/hash/Funnel.java index ecbf1218..2b1677a7 100644 --- a/src/main/java/com/google/common/hash/Funnel.java +++ b/src/main/java/com/google/common/hash/Funnel.java @@ -32,14 +32,15 @@ import com.google.common.annotations.Beta; * *
            *    {@code
          - *   public enum PersonFunnel implements Funnel {
          - *     INSTANCE;
          - *     public void funnel(Person person, PrimitiveSink into) {
          - *       into.putUnencodedChars(person.getFirstName())
          - *           .putUnencodedChars(person.getLastName())
          - *           .putInt(person.getAge());
          - *     }
          - *   }}
          + * public enum PersonFunnel implements Funnel {
          + * 	INSTANCE;
          + * 
          + * 	public void funnel(Person person, PrimitiveSink into) {
          + * 		into.putUnencodedChars(person.getFirstName()).putUnencodedChars(person.getLastName())
          + * 				.putInt(person.getAge());
          + * 	}
          + * }
          + * }
            * 
          * * @author Dimitris Andreou diff --git a/src/main/java/com/google/common/hash/Funnels.java b/src/main/java/com/google/common/hash/Funnels.java index 5b979021..9b082d31 100644 --- a/src/main/java/com/google/common/hash/Funnels.java +++ b/src/main/java/com/google/common/hash/Funnels.java @@ -31,16 +31,6 @@ import com.google.common.base.Preconditions; */ @Beta public final class Funnels { - private Funnels() { - } - - /** - * Returns a funnel that extracts the bytes from a {@code byte} array. - */ - public static Funnel byteArrayFunnel() { - return ByteArrayFunnel.INSTANCE; - } - private enum ByteArrayFunnel implements Funnel { INSTANCE; @@ -54,98 +44,6 @@ public final class Funnels { } } - /** - * Returns a funnel that extracts the characters from a {@code CharSequence}, a - * character at a time, without performing any encoding. If you need to use a - * specific encoding, use {@link Funnels#stringFunnel(Charset)} instead. - * - * @since 15.0 (since 11.0 as {@code Funnels.stringFunnel()}. - */ - public static Funnel unencodedCharsFunnel() { - return UnencodedCharsFunnel.INSTANCE; - } - - private enum UnencodedCharsFunnel implements Funnel { - INSTANCE; - - public void funnel(CharSequence from, PrimitiveSink into) { - into.putUnencodedChars(from); - } - - @Override - public String toString() { - return "Funnels.unencodedCharsFunnel()"; - } - } - - /** - * Returns a funnel that encodes the characters of a {@code CharSequence} with - * the specified {@code Charset}. - * - * @since 15.0 - */ - public static Funnel stringFunnel(Charset charset) { - return new StringCharsetFunnel(charset); - } - - private static class StringCharsetFunnel implements Funnel, Serializable { - private final Charset charset; - - StringCharsetFunnel(Charset charset) { - this.charset = Preconditions.checkNotNull(charset); - } - - public void funnel(CharSequence from, PrimitiveSink into) { - into.putString(from, charset); - } - - @Override - public String toString() { - return "Funnels.stringFunnel(" + charset.name() + ")"; - } - - @Override - public boolean equals(@Nullable Object o) { - if (o instanceof StringCharsetFunnel) { - StringCharsetFunnel funnel = (StringCharsetFunnel) o; - return this.charset.equals(funnel.charset); - } - return false; - } - - @Override - public int hashCode() { - return StringCharsetFunnel.class.hashCode() ^ charset.hashCode(); - } - - Object writeReplace() { - return new SerializedForm(charset); - } - - private static class SerializedForm implements Serializable { - private final String charsetCanonicalName; - - SerializedForm(Charset charset) { - this.charsetCanonicalName = charset.name(); - } - - private Object readResolve() { - return stringFunnel(Charset.forName(charsetCanonicalName)); - } - - private static final long serialVersionUID = 0; - } - } - - /** - * Returns a funnel for integers. - * - * @since 13.0 - */ - public static Funnel integerFunnel() { - return IntegerFunnel.INSTANCE; - } - private enum IntegerFunnel implements Funnel { INSTANCE; @@ -159,15 +57,17 @@ public final class Funnels { } } - /** - * Returns a funnel that processes an {@code Iterable} by funneling its elements - * in iteration order with the specified funnel. No separators are added between - * the elements. - * - * @since 15.0 - */ - public static Funnel> sequentialFunnel(Funnel elementFunnel) { - return new SequentialFunnel(elementFunnel); + private enum LongFunnel implements Funnel { + INSTANCE; + + public void funnel(Long from, PrimitiveSink into) { + into.putLong(from); + } + + @Override + public String toString() { + return "Funnels.longFunnel()"; + } } private static class SequentialFunnel implements Funnel>, Serializable { @@ -177,17 +77,6 @@ public final class Funnels { this.elementFunnel = Preconditions.checkNotNull(elementFunnel); } - public void funnel(Iterable from, PrimitiveSink into) { - for (E e : from) { - elementFunnel.funnel(e, into); - } - } - - @Override - public String toString() { - return "Funnels.sequentialFunnel(" + elementFunnel + ")"; - } - @Override public boolean equals(@Nullable Object o) { if (o instanceof SequentialFunnel) { @@ -197,31 +86,110 @@ public final class Funnels { return false; } + public void funnel(Iterable from, PrimitiveSink into) { + for (E e : from) { + elementFunnel.funnel(e, into); + } + } + @Override public int hashCode() { return SequentialFunnel.class.hashCode() ^ elementFunnel.hashCode(); } + + @Override + public String toString() { + return "Funnels.sequentialFunnel(" + elementFunnel + ")"; + } } - /** - * Returns a funnel for longs. - * - * @since 13.0 - */ - public static Funnel longFunnel() { - return LongFunnel.INSTANCE; - } + private static class SinkAsStream extends OutputStream { + final PrimitiveSink sink; - private enum LongFunnel implements Funnel { - INSTANCE; - - public void funnel(Long from, PrimitiveSink into) { - into.putLong(from); + SinkAsStream(PrimitiveSink sink) { + this.sink = Preconditions.checkNotNull(sink); } @Override public String toString() { - return "Funnels.longFunnel()"; + return "Funnels.asOutputStream(" + sink + ")"; + } + + @Override + public void write(byte[] bytes) { + sink.putBytes(bytes); + } + + @Override + public void write(byte[] bytes, int off, int len) { + sink.putBytes(bytes, off, len); + } + + @Override + public void write(int b) { + sink.putByte((byte) b); + } + } + + private static class StringCharsetFunnel implements Funnel, Serializable { + private static class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + + private final String charsetCanonicalName; + + SerializedForm(Charset charset) { + this.charsetCanonicalName = charset.name(); + } + + private Object readResolve() { + return stringFunnel(Charset.forName(charsetCanonicalName)); + } + } + + private final Charset charset; + + StringCharsetFunnel(Charset charset) { + this.charset = Preconditions.checkNotNull(charset); + } + + @Override + public boolean equals(@Nullable Object o) { + if (o instanceof StringCharsetFunnel) { + StringCharsetFunnel funnel = (StringCharsetFunnel) o; + return this.charset.equals(funnel.charset); + } + return false; + } + + public void funnel(CharSequence from, PrimitiveSink into) { + into.putString(from, charset); + } + + @Override + public int hashCode() { + return StringCharsetFunnel.class.hashCode() ^ charset.hashCode(); + } + + @Override + public String toString() { + return "Funnels.stringFunnel(" + charset.name() + ")"; + } + + Object writeReplace() { + return new SerializedForm(charset); + } + } + + private enum UnencodedCharsFunnel implements Funnel { + INSTANCE; + + public void funnel(CharSequence from, PrimitiveSink into) { + into.putUnencodedChars(from); + } + + @Override + public String toString() { + return "Funnels.unencodedCharsFunnel()"; } } @@ -240,31 +208,63 @@ public final class Funnels { return new SinkAsStream(sink); } - private static class SinkAsStream extends OutputStream { - final PrimitiveSink sink; + /** + * Returns a funnel that extracts the bytes from a {@code byte} array. + */ + public static Funnel byteArrayFunnel() { + return ByteArrayFunnel.INSTANCE; + } - SinkAsStream(PrimitiveSink sink) { - this.sink = Preconditions.checkNotNull(sink); - } + /** + * Returns a funnel for integers. + * + * @since 13.0 + */ + public static Funnel integerFunnel() { + return IntegerFunnel.INSTANCE; + } - @Override - public void write(int b) { - sink.putByte((byte) b); - } + /** + * Returns a funnel for longs. + * + * @since 13.0 + */ + public static Funnel longFunnel() { + return LongFunnel.INSTANCE; + } - @Override - public void write(byte[] bytes) { - sink.putBytes(bytes); - } + /** + * Returns a funnel that processes an {@code Iterable} by funneling its elements + * in iteration order with the specified funnel. No separators are added between + * the elements. + * + * @since 15.0 + */ + public static Funnel> sequentialFunnel(Funnel elementFunnel) { + return new SequentialFunnel(elementFunnel); + } - @Override - public void write(byte[] bytes, int off, int len) { - sink.putBytes(bytes, off, len); - } + /** + * Returns a funnel that encodes the characters of a {@code CharSequence} with + * the specified {@code Charset}. + * + * @since 15.0 + */ + public static Funnel stringFunnel(Charset charset) { + return new StringCharsetFunnel(charset); + } - @Override - public String toString() { - return "Funnels.asOutputStream(" + sink + ")"; - } + /** + * Returns a funnel that extracts the characters from a {@code CharSequence}, a + * character at a time, without performing any encoding. If you need to use a + * specific encoding, use {@link Funnels#stringFunnel(Charset)} instead. + * + * @since 15.0 (since 11.0 as {@code Funnels.stringFunnel()}. + */ + public static Funnel unencodedCharsFunnel() { + return UnencodedCharsFunnel.INSTANCE; + } + + private Funnels() { } } diff --git a/src/main/java/com/google/common/hash/HashCode.java b/src/main/java/com/google/common/hash/HashCode.java index af292e31..b0c6e679 100644 --- a/src/main/java/com/google/common/hash/HashCode.java +++ b/src/main/java/com/google/common/hash/HashCode.java @@ -37,95 +37,65 @@ import com.google.common.primitives.UnsignedInts; */ @Beta public abstract class HashCode { - HashCode() { - } + private static final class BytesHashCode extends HashCode implements Serializable { + private static final long serialVersionUID = 0; - /** - * Returns the number of bits in this hash code; a positive multiple of 8. - */ - public abstract int bits(); + final byte[] bytes; - /** - * Returns the first four bytes of {@linkplain #asBytes() this hashcode's - * bytes}, converted to an {@code int} value in little-endian order. - * - * @throws IllegalStateException if {@code bits() < 32} - */ - public abstract int asInt(); + BytesHashCode(byte[] bytes) { + this.bytes = checkNotNull(bytes); + } - /** - * Returns the first eight bytes of {@linkplain #asBytes() this hashcode's - * bytes}, converted to a {@code long} value in little-endian order. - * - * @throws IllegalStateException if {@code bits() < 64} - */ - public abstract long asLong(); + @Override + public byte[] asBytes() { + return bytes.clone(); + } - /** - * If this hashcode has enough bits, returns {@code asLong()}, otherwise returns - * a {@code long} value with {@code asBytes()} as the least-significant bytes - * and {@code 0x00} as the remaining most-significant bytes. - * - * @since 14.0 (since 11.0 as {@code Hashing.padToLong(HashCode)}) - */ - public abstract long padToLong(); + @Override + public int asInt() { + checkState(bytes.length >= 4, "HashCode#asInt() requires >= 4 bytes (it only has %s bytes).", bytes.length); + return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24); + } - /** - * Returns the value of this hash code as a byte array. The caller may modify - * the byte array; changes to it will not be reflected in this - * {@code HashCode} object or any other arrays returned by this method. - */ - // TODO(user): consider ByteString here, when that is available - public abstract byte[] asBytes(); - - /** - * Copies bytes from this hash code into {@code dest}. - * - * @param dest the byte array into which the hash code will be written - * @param offset the start offset in the data - * @param maxLength the maximum number of bytes to write - * @return the number of bytes written to {@code dest} - * @throws IndexOutOfBoundsException if there is not enough room in {@code dest} - */ - public int writeBytesTo(byte[] dest, int offset, int maxLength) { - maxLength = Ints.min(maxLength, bits() / 8); - Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); - writeBytesToImpl(dest, offset, maxLength); - return maxLength; - } - - abstract void writeBytesToImpl(byte[] dest, int offset, int maxLength); - - /** - * Returns a mutable view of the underlying bytes for the given {@code HashCode} - * if it is a byte-based hashcode. Otherwise it returns - * {@link HashCode#asBytes}. Do not mutate this array or else you will - * break the immutability contract of {@code HashCode}. - */ - byte[] getBytesInternal() { - return asBytes(); - } - - /** - * Creates a 32-bit {@code HashCode} representation of the given int value. The - * underlying bytes are interpreted in little endian order. - * - * @since 15.0 (since 12.0 in HashCodes) - */ - public static HashCode fromInt(int hash) { - return new IntHashCode(hash); - } - - private static final class IntHashCode extends HashCode implements Serializable { - final int hash; - - IntHashCode(int hash) { - this.hash = hash; + @Override + public long asLong() { + checkState(bytes.length >= 8, "HashCode#asLong() requires >= 8 bytes (it only has %s bytes).", + bytes.length); + return padToLong(); } @Override public int bits() { - return 32; + return bytes.length * 8; + } + + @Override + byte[] getBytesInternal() { + return bytes; + } + + @Override + public long padToLong() { + long retVal = (bytes[0] & 0xFF); + for (int i = 1; i < Math.min(bytes.length, 8); i++) { + retVal |= (bytes[i] & 0xFFL) << (i * 8); + } + return retVal; + } + + @Override + void writeBytesToImpl(byte[] dest, int offset, int maxLength) { + System.arraycopy(bytes, 0, dest, offset, maxLength); + } + } + + private static final class IntHashCode extends HashCode implements Serializable { + private static final long serialVersionUID = 0; + + final int hash; + + IntHashCode(int hash) { + this.hash = hash; } @Override @@ -143,6 +113,11 @@ public abstract class HashCode { throw new IllegalStateException("this HashCode only has 32 bits; cannot create a long"); } + @Override + public int bits() { + return 32; + } + @Override public long padToLong() { return UnsignedInts.toLong(hash); @@ -154,32 +129,17 @@ public abstract class HashCode { dest[offset + i] = (byte) (hash >> (i * 8)); } } - - private static final long serialVersionUID = 0; - } - - /** - * Creates a 64-bit {@code HashCode} representation of the given long value. The - * underlying bytes are interpreted in little endian order. - * - * @since 15.0 (since 12.0 in HashCodes) - */ - public static HashCode fromLong(long hash) { - return new LongHashCode(hash); } private static final class LongHashCode extends HashCode implements Serializable { + private static final long serialVersionUID = 0; + final long hash; LongHashCode(long hash) { this.hash = hash; } - @Override - public int bits() { - return 64; - } - @Override public byte[] asBytes() { return new byte[] { (byte) hash, (byte) (hash >> 8), (byte) (hash >> 16), (byte) (hash >> 24), @@ -196,6 +156,11 @@ public abstract class HashCode { return hash; } + @Override + public int bits() { + return 64; + } + @Override public long padToLong() { return hash; @@ -207,8 +172,18 @@ public abstract class HashCode { dest[offset + i] = (byte) (hash >> (i * 8)); } } + } - private static final long serialVersionUID = 0; + private static final char[] hexDigits = "0123456789abcdef".toCharArray(); + + private static int decode(char ch) { + if (ch >= '0' && ch <= '9') { + return ch - '0'; + } + if (ch >= 'a' && ch <= 'f') { + return ch - 'a' + 10; + } + throw new IllegalArgumentException("Illegal hexadecimal character: " + ch); } /** @@ -232,56 +207,24 @@ public abstract class HashCode { return new BytesHashCode(bytes); } - private static final class BytesHashCode extends HashCode implements Serializable { - final byte[] bytes; + /** + * Creates a 32-bit {@code HashCode} representation of the given int value. The + * underlying bytes are interpreted in little endian order. + * + * @since 15.0 (since 12.0 in HashCodes) + */ + public static HashCode fromInt(int hash) { + return new IntHashCode(hash); + } - BytesHashCode(byte[] bytes) { - this.bytes = checkNotNull(bytes); - } - - @Override - public int bits() { - return bytes.length * 8; - } - - @Override - public byte[] asBytes() { - return bytes.clone(); - } - - @Override - public int asInt() { - checkState(bytes.length >= 4, "HashCode#asInt() requires >= 4 bytes (it only has %s bytes).", bytes.length); - return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24); - } - - @Override - public long asLong() { - checkState(bytes.length >= 8, "HashCode#asLong() requires >= 8 bytes (it only has %s bytes).", - bytes.length); - return padToLong(); - } - - @Override - public long padToLong() { - long retVal = (bytes[0] & 0xFF); - for (int i = 1; i < Math.min(bytes.length, 8); i++) { - retVal |= (bytes[i] & 0xFFL) << (i * 8); - } - return retVal; - } - - @Override - void writeBytesToImpl(byte[] dest, int offset, int maxLength) { - System.arraycopy(bytes, 0, dest, offset, maxLength); - } - - @Override - byte[] getBytesInternal() { - return bytes; - } - - private static final long serialVersionUID = 0; + /** + * Creates a 64-bit {@code HashCode} representation of the given long value. The + * underlying bytes are interpreted in little endian order. + * + * @since 15.0 (since 12.0 in HashCodes) + */ + public static HashCode fromLong(long hash) { + return new LongHashCode(hash); } /** @@ -310,16 +253,38 @@ public abstract class HashCode { return fromBytesNoCopy(bytes); } - private static int decode(char ch) { - if (ch >= '0' && ch <= '9') { - return ch - '0'; - } - if (ch >= 'a' && ch <= 'f') { - return ch - 'a' + 10; - } - throw new IllegalArgumentException("Illegal hexadecimal character: " + ch); + HashCode() { } + /** + * Returns the value of this hash code as a byte array. The caller may modify + * the byte array; changes to it will not be reflected in this + * {@code HashCode} object or any other arrays returned by this method. + */ + // TODO(user): consider ByteString here, when that is available + public abstract byte[] asBytes(); + + /** + * Returns the first four bytes of {@linkplain #asBytes() this hashcode's + * bytes}, converted to an {@code int} value in little-endian order. + * + * @throws IllegalStateException if {@code bits() < 32} + */ + public abstract int asInt(); + + /** + * Returns the first eight bytes of {@linkplain #asBytes() this hashcode's + * bytes}, converted to a {@code long} value in little-endian order. + * + * @throws IllegalStateException if {@code bits() < 64} + */ + public abstract long asLong(); + + /** + * Returns the number of bits in this hash code; a positive multiple of 8. + */ + public abstract int bits(); + @Override public final boolean equals(@Nullable Object object) { if (object instanceof HashCode) { @@ -332,6 +297,16 @@ public abstract class HashCode { return false; } + /** + * Returns a mutable view of the underlying bytes for the given {@code HashCode} + * if it is a byte-based hashcode. Otherwise it returns + * {@link HashCode#asBytes}. Do not mutate this array or else you will + * break the immutability contract of {@code HashCode}. + */ + byte[] getBytesInternal() { + return asBytes(); + } + /** * Returns a "Java hash code" for this {@code HashCode} instance; this is * well-defined (so, for example, you can safely put {@code HashCode} instances @@ -355,6 +330,15 @@ public abstract class HashCode { return val; } + /** + * If this hashcode has enough bits, returns {@code asLong()}, otherwise returns + * a {@code long} value with {@code asBytes()} as the least-significant bytes + * and {@code 0x00} as the remaining most-significant bytes. + * + * @since 14.0 (since 11.0 as {@code Hashing.padToLong(HashCode)}) + */ + public abstract long padToLong(); + /** * Returns a string containing each byte of {@link #asBytes}, in order, as a * two-digit unsigned hexadecimal number in lower case. @@ -380,5 +364,21 @@ public abstract class HashCode { return sb.toString(); } - private static final char[] hexDigits = "0123456789abcdef".toCharArray(); + /** + * Copies bytes from this hash code into {@code dest}. + * + * @param dest the byte array into which the hash code will be written + * @param offset the start offset in the data + * @param maxLength the maximum number of bytes to write + * @return the number of bytes written to {@code dest} + * @throws IndexOutOfBoundsException if there is not enough room in {@code dest} + */ + public int writeBytesTo(byte[] dest, int offset, int maxLength) { + maxLength = Ints.min(maxLength, bits() / 8); + Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length); + writeBytesToImpl(dest, offset, maxLength); + return maxLength; + } + + abstract void writeBytesToImpl(byte[] dest, int offset, int maxLength); } diff --git a/src/main/java/com/google/common/hash/HashFunction.java b/src/main/java/com/google/common/hash/HashFunction.java index 90b52594..36dc5e18 100644 --- a/src/main/java/com/google/common/hash/HashFunction.java +++ b/src/main/java/com/google/common/hash/HashFunction.java @@ -151,6 +151,75 @@ import com.google.common.primitives.Ints; */ @Beta public interface HashFunction { + /** + * Returns the number of bits (a multiple of 32) that each hash code produced by + * this hash function has. + */ + int bits(); + + /** + * Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation + * might perform better than its longhand equivalent, but should not + * perform worse. + */ + HashCode hashBytes(byte[] input); + + /** + * Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The + * implementation might perform better than its longhand equivalent, but + * should not perform worse. + * + * @throws IndexOutOfBoundsException if {@code off < 0} or + * {@code off + len > bytes.length} or + * {@code len < 0} + */ + HashCode hashBytes(byte[] input, int off, int len); + + /** + * Shortcut for {@code newHasher().putInt(input).hash()}; returns the hash code + * for the given {@code int} value, interpreted in little-endian byte order. The + * implementation might perform better than its longhand equivalent, but + * should not perform worse. + * + * @since 12.0 + */ + HashCode hashInt(int input); + + /** + * Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code + * for the given {@code long} value, interpreted in little-endian byte order. + * The implementation might perform better than its longhand equivalent, + * but should not perform worse. + */ + HashCode hashLong(long input); + + /** + * Shortcut for {@code newHasher().putObject(instance, funnel).hash()}. The + * implementation might perform better than its longhand equivalent, but + * should not perform worse. + * + * @since 14.0 + */ + HashCode hashObject(T instance, Funnel funnel); + + /** + * Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters + * are encoded using the given {@link Charset}. The implementation might + * perform better than its longhand equivalent, but should not perform worse. + */ + HashCode hashString(CharSequence input, Charset charset); + + /** + * Shortcut for {@code newHasher().putUnencodedChars(input).hash()}. The + * implementation might perform better than its longhand equivalent, but + * should not perform worse. Note that no character encoding is performed; the + * low byte and high byte of each {@code char} are hashed directly (in that + * order). + * + * @since 15.0 (since 11.0 as hashString(CharSequence)). + */ + HashCode hashUnencodedChars(CharSequence input); + /** * Begins a new hash code computation by returning an initialized, stateful * {@code @@ -174,73 +243,4 @@ public interface HashFunction { * input before processing any of it). */ Hasher newHasher(int expectedInputSize); - - /** - * Shortcut for {@code newHasher().putInt(input).hash()}; returns the hash code - * for the given {@code int} value, interpreted in little-endian byte order. The - * implementation might perform better than its longhand equivalent, but - * should not perform worse. - * - * @since 12.0 - */ - HashCode hashInt(int input); - - /** - * Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code - * for the given {@code long} value, interpreted in little-endian byte order. - * The implementation might perform better than its longhand equivalent, - * but should not perform worse. - */ - HashCode hashLong(long input); - - /** - * Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation - * might perform better than its longhand equivalent, but should not - * perform worse. - */ - HashCode hashBytes(byte[] input); - - /** - * Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The - * implementation might perform better than its longhand equivalent, but - * should not perform worse. - * - * @throws IndexOutOfBoundsException if {@code off < 0} or - * {@code off + len > bytes.length} or - * {@code len < 0} - */ - HashCode hashBytes(byte[] input, int off, int len); - - /** - * Shortcut for {@code newHasher().putUnencodedChars(input).hash()}. The - * implementation might perform better than its longhand equivalent, but - * should not perform worse. Note that no character encoding is performed; the - * low byte and high byte of each {@code char} are hashed directly (in that - * order). - * - * @since 15.0 (since 11.0 as hashString(CharSequence)). - */ - HashCode hashUnencodedChars(CharSequence input); - - /** - * Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters - * are encoded using the given {@link Charset}. The implementation might - * perform better than its longhand equivalent, but should not perform worse. - */ - HashCode hashString(CharSequence input, Charset charset); - - /** - * Shortcut for {@code newHasher().putObject(instance, funnel).hash()}. The - * implementation might perform better than its longhand equivalent, but - * should not perform worse. - * - * @since 14.0 - */ - HashCode hashObject(T instance, Funnel funnel); - - /** - * Returns the number of bits (a multiple of 32) that each hash code produced by - * this hash function has. - */ - int bits(); } diff --git a/src/main/java/com/google/common/hash/Hasher.java b/src/main/java/com/google/common/hash/Hasher.java index 879f497a..6febb855 100644 --- a/src/main/java/com/google/common/hash/Hasher.java +++ b/src/main/java/com/google/common/hash/Hasher.java @@ -63,6 +63,19 @@ import com.google.common.annotations.Beta; */ @Beta public interface Hasher extends PrimitiveSink { + /** + * Computes a hash code based on the data that have been provided to this + * hasher. The result is unspecified if this method is called more than once on + * the same instance. + */ + HashCode hash(); + + /** + * Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}. + */ + @Override + Hasher putBoolean(boolean b); + @Override Hasher putByte(byte b); @@ -73,19 +86,7 @@ public interface Hasher extends PrimitiveSink { Hasher putBytes(byte[] bytes, int off, int len); @Override - Hasher putShort(short s); - - @Override - Hasher putInt(int i); - - @Override - Hasher putLong(long l); - - /** - * Equivalent to {@code putInt(Float.floatToRawIntBits(f))}. - */ - @Override - Hasher putFloat(float f); + Hasher putChar(char c); /** * Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}. @@ -94,13 +95,30 @@ public interface Hasher extends PrimitiveSink { Hasher putDouble(double d); /** - * Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}. + * Equivalent to {@code putInt(Float.floatToRawIntBits(f))}. */ @Override - Hasher putBoolean(boolean b); + Hasher putFloat(float f); @Override - Hasher putChar(char c); + Hasher putInt(int i); + + @Override + Hasher putLong(long l); + + /** + * A simple convenience for {@code funnel.funnel(object, this)}. + */ + Hasher putObject(T instance, Funnel funnel); + + @Override + Hasher putShort(short s); + + /** + * Equivalent to {@code putBytes(charSequence.toString().getBytes(charset))}. + */ + @Override + Hasher putString(CharSequence charSequence, Charset charset); /** * Equivalent to processing each {@code char} value in the {@code CharSequence}, @@ -110,22 +128,4 @@ public interface Hasher extends PrimitiveSink { */ @Override Hasher putUnencodedChars(CharSequence charSequence); - - /** - * Equivalent to {@code putBytes(charSequence.toString().getBytes(charset))}. - */ - @Override - Hasher putString(CharSequence charSequence, Charset charset); - - /** - * A simple convenience for {@code funnel.funnel(object, this)}. - */ - Hasher putObject(T instance, Funnel funnel); - - /** - * Computes a hash code based on the data that have been provided to this - * hasher. The result is unspecified if this method is called more than once on - * the same instance. - */ - HashCode hash(); } diff --git a/src/main/java/com/google/common/hash/Hashing.java b/src/main/java/com/google/common/hash/Hashing.java index 2a467cab..4f80d6e7 100644 --- a/src/main/java/com/google/common/hash/Hashing.java +++ b/src/main/java/com/google/common/hash/Hashing.java @@ -43,236 +43,10 @@ import com.google.common.base.Supplier; */ @Beta public final class Hashing { - /** - * Returns a general-purpose, temporary-use, non-cryptographic hash - * function. The algorithm the returned function implements is unspecified and - * subject to change without notice. - * - *

          - * Warning: a new random seed for these functions is chosen each time the - * {@code - * Hashing} class is loaded. Do not use this method if hash codes may - * escape the current process in any way, for example being sent over RPC, or - * saved to disk. - * - *

          - * Repeated calls to this method on the same loaded {@code Hashing} class, using - * the same value for {@code minimumBits}, will return identically-behaving - * {@link HashFunction} instances. - * - * @param minimumBits a positive integer (can be arbitrarily large) - * @return a hash function, described above, that produces hash codes of length - * {@code - * minimumBits} or greater - */ - public static HashFunction goodFastHash(int minimumBits) { - int bits = checkPositiveAndMakeMultipleOf32(minimumBits); - - if (bits == 32) { - return Murmur3_32Holder.GOOD_FAST_HASH_FUNCTION_32; - } - if (bits <= 128) { - return Murmur3_128Holder.GOOD_FAST_HASH_FUNCTION_128; - } - - // Otherwise, join together some 128-bit murmur3s - int hashFunctionsNeeded = (bits + 127) / 128; - HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; - hashFunctions[0] = Murmur3_128Holder.GOOD_FAST_HASH_FUNCTION_128; - int seed = GOOD_FAST_HASH_SEED; - for (int i = 1; i < hashFunctionsNeeded; i++) { - seed += 1500450271; // a prime; shouldn't matter - hashFunctions[i] = murmur3_128(seed); - } - return new ConcatenatedHashFunction(hashFunctions); - } - - /** - * Used to randomize {@link #goodFastHash} instances, so that programs which - * persist anything dependent on the hash codes they produce will fail sooner. - */ - private static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); - - /** - * Returns a hash function implementing the - * 32-bit - * murmur3 algorithm, x86 variant (little-endian variant), using the given - * seed value. - * - *

          - * The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). - */ - public static HashFunction murmur3_32(int seed) { - return new Murmur3_32HashFunction(seed); - } - - /** - * Returns a hash function implementing the - * 32-bit - * murmur3 algorithm, x86 variant (little-endian variant), using a seed - * value of zero. - * - *

          - * The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). - */ - public static HashFunction murmur3_32() { - return Murmur3_32Holder.MURMUR3_32; - } - - private static class Murmur3_32Holder { - static final HashFunction MURMUR3_32 = new Murmur3_32HashFunction(0); - - /** Returned by {@link #goodFastHash} when {@code minimumBits <= 32}. */ - static final HashFunction GOOD_FAST_HASH_FUNCTION_32 = murmur3_32(GOOD_FAST_HASH_SEED); - } - - /** - * Returns a hash function implementing the - * 128-bit - * murmur3 algorithm, x64 variant (little-endian variant), using the given - * seed value. - * - *

          - * The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). - */ - public static HashFunction murmur3_128(int seed) { - return new Murmur3_128HashFunction(seed); - } - - /** - * Returns a hash function implementing the - * 128-bit - * murmur3 algorithm, x64 variant (little-endian variant), using a seed - * value of zero. - * - *

          - * The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). - */ - public static HashFunction murmur3_128() { - return Murmur3_128Holder.MURMUR3_128; - } - - private static class Murmur3_128Holder { - static final HashFunction MURMUR3_128 = new Murmur3_128HashFunction(0); - - /** Returned by {@link #goodFastHash} when {@code 32 < minimumBits <= 128}. */ - static final HashFunction GOOD_FAST_HASH_FUNCTION_128 = murmur3_128(GOOD_FAST_HASH_SEED); - } - - /** - * Returns a hash function implementing the - * 64-bit SipHash-2-4 algorithm using - * a seed value of {@code k = 00 01 02 ...}. - * - * @since 15.0 - */ - public static HashFunction sipHash24() { - return SipHash24Holder.SIP_HASH_24; - } - - private static class SipHash24Holder { - static final HashFunction SIP_HASH_24 = new SipHashFunction(2, 4, 0x0706050403020100L, 0x0f0e0d0c0b0a0908L); - } - - /** - * Returns a hash function implementing the - * 64-bit SipHash-2-4 algorithm using - * the given seed. - * - * @since 15.0 - */ - public static HashFunction sipHash24(long k0, long k1) { - return new SipHashFunction(2, 4, k0, k1); - } - - /** - * Returns a hash function implementing the MD5 hash algorithm (128 hash bits) - * by delegating to the MD5 {@link MessageDigest}. - */ - public static HashFunction md5() { - return Md5Holder.MD5; - } - - private static class Md5Holder { - static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()"); - } - - /** - * Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by - * delegating to the SHA-1 {@link MessageDigest}. - */ - public static HashFunction sha1() { - return Sha1Holder.SHA_1; - } - - private static class Sha1Holder { - static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()"); - } - - /** - * Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by - * delegating to the SHA-256 {@link MessageDigest}. - */ - public static HashFunction sha256() { - return Sha256Holder.SHA_256; - } - - private static class Sha256Holder { - static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256", "Hashing.sha256()"); - } - - /** - * Returns a hash function implementing the SHA-512 algorithm (512 hash bits) by - * delegating to the SHA-512 {@link MessageDigest}. - */ - public static HashFunction sha512() { - return Sha512Holder.SHA_512; - } - - private static class Sha512Holder { - static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512", "Hashing.sha512()"); - } - - /** - * Returns a hash function implementing the CRC-32 checksum algorithm (32 hash - * bits) by delegating to the {@link CRC32} {@link Checksum}. - * - *

          - * To get the {@code long} value equivalent to {@link Checksum#getValue()} for a - * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. - * - * @since 14.0 - */ - public static HashFunction crc32() { - return Crc32Holder.CRC_32; - } - - private static class Crc32Holder { - static final HashFunction CRC_32 = checksumHashFunction(ChecksumType.CRC_32, "Hashing.crc32()"); - } - - /** - * Returns a hash function implementing the Adler-32 checksum algorithm (32 hash - * bits) by delegating to the {@link Adler32} {@link Checksum}. - * - *

          - * To get the {@code long} value equivalent to {@link Checksum#getValue()} for a - * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. - * - * @since 14.0 - */ - public static HashFunction adler32() { - return Adler32Holder.ADLER_32; - } - private static class Adler32Holder { static final HashFunction ADLER_32 = checksumHashFunction(ChecksumType.ADLER_32, "Hashing.adler32()"); } - private static HashFunction checksumHashFunction(ChecksumType type, String toString) { - return new ChecksumHashFunction(type, type.bits, toString); - } - enum ChecksumType implements Supplier { CRC_32(32) { @Override @@ -297,53 +71,149 @@ public final class Hashing { public abstract Checksum get(); } - /** - * Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in - * a uniform manner that minimizes the need for remapping as {@code buckets} - * grows. That is, {@code consistentHash(h, n)} equals: - * - *

            - *
          • {@code n - 1}, with approximate probability {@code 1/n} - *
          • {@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) - *
          - * - *

          - * See the wikipedia - * article on consistent hashing for more information. - */ - public static int consistentHash(HashCode hashCode, int buckets) { - return consistentHash(hashCode.padToLong(), buckets); + // TODO(kevinb): Maybe expose this class via a static Hashing method? + @VisibleForTesting + static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction { + private final int bits; + + ConcatenatedHashFunction(HashFunction... functions) { + super(functions); + int bitSum = 0; + for (HashFunction function : functions) { + bitSum += function.bits(); + } + this.bits = bitSum; + } + + @Override + public int bits() { + return bits; + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof ConcatenatedHashFunction) { + ConcatenatedHashFunction other = (ConcatenatedHashFunction) object; + if (bits != other.bits || functions.length != other.functions.length) { + return false; + } + for (int i = 0; i < functions.length; i++) { + if (!functions[i].equals(other.functions[i])) { + return false; + } + } + return true; + } + return false; + } + + @Override + public int hashCode() { + int hash = bits; + for (HashFunction function : functions) { + hash ^= function.hashCode(); + } + return hash; + } + + @Override + HashCode makeHash(Hasher[] hashers) { + byte[] bytes = new byte[bits / 8]; + int i = 0; + for (Hasher hasher : hashers) { + HashCode newHash = hasher.hash(); + i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8); + } + return HashCode.fromBytesNoCopy(bytes); + } + } + + private static class Crc32Holder { + static final HashFunction CRC_32 = checksumHashFunction(ChecksumType.CRC_32, "Hashing.crc32()"); } /** - * Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a - * uniform manner that minimizes the need for remapping as {@code buckets} - * grows. That is, {@code consistentHash(h, n)} equals: - * - *

            - *
          • {@code n - 1}, with approximate probability {@code 1/n} - *
          • {@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) - *
          + * Linear CongruentialGenerator to use for consistent hashing. See + * http://en.wikipedia.org/wiki/Linear_congruential_generator + */ + private static final class LinearCongruentialGenerator { + private long state; + + public LinearCongruentialGenerator(long seed) { + this.state = seed; + } + + public double nextDouble() { + state = 2862933555777941757L * state + 1; + return ((double) ((int) (state >>> 33) + 1)) / (0x1.0p31); + } + } + + private static class Md5Holder { + static final HashFunction MD5 = new MessageDigestHashFunction("MD5", "Hashing.md5()"); + } + + private static class Murmur3_128Holder { + static final HashFunction MURMUR3_128 = new Murmur3_128HashFunction(0); + + /** Returned by {@link #goodFastHash} when {@code 32 < minimumBits <= 128}. */ + static final HashFunction GOOD_FAST_HASH_FUNCTION_128 = murmur3_128(GOOD_FAST_HASH_SEED); + } + + private static class Murmur3_32Holder { + static final HashFunction MURMUR3_32 = new Murmur3_32HashFunction(0); + + /** Returned by {@link #goodFastHash} when {@code minimumBits <= 32}. */ + static final HashFunction GOOD_FAST_HASH_FUNCTION_32 = murmur3_32(GOOD_FAST_HASH_SEED); + } + + private static class Sha1Holder { + static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1", "Hashing.sha1()"); + } + + private static class Sha256Holder { + static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256", "Hashing.sha256()"); + } + + private static class Sha512Holder { + static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512", "Hashing.sha512()"); + } + + private static class SipHash24Holder { + static final HashFunction SIP_HASH_24 = new SipHashFunction(2, 4, 0x0706050403020100L, 0x0f0e0d0c0b0a0908L); + } + + /** + * Used to randomize {@link #goodFastHash} instances, so that programs which + * persist anything dependent on the hash codes they produce will fail sooner. + */ + private static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis(); + + /** + * Returns a hash function implementing the Adler-32 checksum algorithm (32 hash + * bits) by delegating to the {@link Adler32} {@link Checksum}. * *

          - * See the wikipedia - * article on consistent hashing for more information. + * To get the {@code long} value equivalent to {@link Checksum#getValue()} for a + * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. + * + * @since 14.0 */ - public static int consistentHash(long input, int buckets) { - checkArgument(buckets > 0, "buckets must be positive: %s", buckets); - LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input); - int candidate = 0; - int next; + public static HashFunction adler32() { + return Adler32Holder.ADLER_32; + } - // Jump from bucket to bucket until we go out of range - while (true) { - next = (int) ((candidate + 1) / generator.nextDouble()); - if (next >= 0 && next < buckets) { - candidate = next; - } else { - return candidate; - } - } + /** + * Checks that the passed argument is positive, and ceils it to a multiple of + * 32. + */ + static int checkPositiveAndMakeMultipleOf32(int bits) { + checkArgument(bits > 0, "Number of bits must be positive"); + return (bits + 31) & ~31; + } + + private static HashFunction checksumHashFunction(ChecksumType type, String toString) { + return new ChecksumHashFunction(type, type.bits, toString); } /** @@ -396,86 +266,216 @@ public final class Hashing { } /** - * Checks that the passed argument is positive, and ceils it to a multiple of - * 32. + * Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in + * a uniform manner that minimizes the need for remapping as {@code buckets} + * grows. That is, {@code consistentHash(h, n)} equals: + * + *

            + *
          • {@code n - 1}, with approximate probability {@code 1/n} + *
          • {@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) + *
          + * + *

          + * See the wikipedia + * article on consistent hashing for more information. */ - static int checkPositiveAndMakeMultipleOf32(int bits) { - checkArgument(bits > 0, "Number of bits must be positive"); - return (bits + 31) & ~31; + public static int consistentHash(HashCode hashCode, int buckets) { + return consistentHash(hashCode.padToLong(), buckets); } - // TODO(kevinb): Maybe expose this class via a static Hashing method? - @VisibleForTesting - static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction { - private final int bits; + /** + * Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a + * uniform manner that minimizes the need for remapping as {@code buckets} + * grows. That is, {@code consistentHash(h, n)} equals: + * + *

            + *
          • {@code n - 1}, with approximate probability {@code 1/n} + *
          • {@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n}) + *
          + * + *

          + * See the wikipedia + * article on consistent hashing for more information. + */ + public static int consistentHash(long input, int buckets) { + checkArgument(buckets > 0, "buckets must be positive: %s", buckets); + LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input); + int candidate = 0; + int next; - ConcatenatedHashFunction(HashFunction... functions) { - super(functions); - int bitSum = 0; - for (HashFunction function : functions) { - bitSum += function.bits(); + // Jump from bucket to bucket until we go out of range + while (true) { + next = (int) ((candidate + 1) / generator.nextDouble()); + if (next >= 0 && next < buckets) { + candidate = next; + } else { + return candidate; } - this.bits = bitSum; - } - - @Override - HashCode makeHash(Hasher[] hashers) { - byte[] bytes = new byte[bits / 8]; - int i = 0; - for (Hasher hasher : hashers) { - HashCode newHash = hasher.hash(); - i += newHash.writeBytesTo(bytes, i, newHash.bits() / 8); - } - return HashCode.fromBytesNoCopy(bytes); - } - - @Override - public int bits() { - return bits; - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof ConcatenatedHashFunction) { - ConcatenatedHashFunction other = (ConcatenatedHashFunction) object; - if (bits != other.bits || functions.length != other.functions.length) { - return false; - } - for (int i = 0; i < functions.length; i++) { - if (!functions[i].equals(other.functions[i])) { - return false; - } - } - return true; - } - return false; - } - - @Override - public int hashCode() { - int hash = bits; - for (HashFunction function : functions) { - hash ^= function.hashCode(); - } - return hash; } } /** - * Linear CongruentialGenerator to use for consistent hashing. See - * http://en.wikipedia.org/wiki/Linear_congruential_generator + * Returns a hash function implementing the CRC-32 checksum algorithm (32 hash + * bits) by delegating to the {@link CRC32} {@link Checksum}. + * + *

          + * To get the {@code long} value equivalent to {@link Checksum#getValue()} for a + * {@code HashCode} produced by this function, use {@link HashCode#padToLong()}. + * + * @since 14.0 */ - private static final class LinearCongruentialGenerator { - private long state; + public static HashFunction crc32() { + return Crc32Holder.CRC_32; + } - public LinearCongruentialGenerator(long seed) { - this.state = seed; + /** + * Returns a general-purpose, temporary-use, non-cryptographic hash + * function. The algorithm the returned function implements is unspecified and + * subject to change without notice. + * + *

          + * Warning: a new random seed for these functions is chosen each time the + * {@code + * Hashing} class is loaded. Do not use this method if hash codes may + * escape the current process in any way, for example being sent over RPC, or + * saved to disk. + * + *

          + * Repeated calls to this method on the same loaded {@code Hashing} class, using + * the same value for {@code minimumBits}, will return identically-behaving + * {@link HashFunction} instances. + * + * @param minimumBits a positive integer (can be arbitrarily large) + * @return a hash function, described above, that produces hash codes of length + * {@code + * minimumBits} or greater + */ + public static HashFunction goodFastHash(int minimumBits) { + int bits = checkPositiveAndMakeMultipleOf32(minimumBits); + + if (bits == 32) { + return Murmur3_32Holder.GOOD_FAST_HASH_FUNCTION_32; + } + if (bits <= 128) { + return Murmur3_128Holder.GOOD_FAST_HASH_FUNCTION_128; } - public double nextDouble() { - state = 2862933555777941757L * state + 1; - return ((double) ((int) (state >>> 33) + 1)) / (0x1.0p31); + // Otherwise, join together some 128-bit murmur3s + int hashFunctionsNeeded = (bits + 127) / 128; + HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded]; + hashFunctions[0] = Murmur3_128Holder.GOOD_FAST_HASH_FUNCTION_128; + int seed = GOOD_FAST_HASH_SEED; + for (int i = 1; i < hashFunctionsNeeded; i++) { + seed += 1500450271; // a prime; shouldn't matter + hashFunctions[i] = murmur3_128(seed); } + return new ConcatenatedHashFunction(hashFunctions); + } + + /** + * Returns a hash function implementing the MD5 hash algorithm (128 hash bits) + * by delegating to the MD5 {@link MessageDigest}. + */ + public static HashFunction md5() { + return Md5Holder.MD5; + } + + /** + * Returns a hash function implementing the + * 128-bit + * murmur3 algorithm, x64 variant (little-endian variant), using a seed + * value of zero. + * + *

          + * The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). + */ + public static HashFunction murmur3_128() { + return Murmur3_128Holder.MURMUR3_128; + } + + /** + * Returns a hash function implementing the + * 128-bit + * murmur3 algorithm, x64 variant (little-endian variant), using the given + * seed value. + * + *

          + * The exact C++ equivalent is the MurmurHash3_x64_128 function (Murmur3F). + */ + public static HashFunction murmur3_128(int seed) { + return new Murmur3_128HashFunction(seed); + } + + /** + * Returns a hash function implementing the + * 32-bit + * murmur3 algorithm, x86 variant (little-endian variant), using a seed + * value of zero. + * + *

          + * The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). + */ + public static HashFunction murmur3_32() { + return Murmur3_32Holder.MURMUR3_32; + } + + /** + * Returns a hash function implementing the + * 32-bit + * murmur3 algorithm, x86 variant (little-endian variant), using the given + * seed value. + * + *

          + * The exact C++ equivalent is the MurmurHash3_x86_32 function (Murmur3A). + */ + public static HashFunction murmur3_32(int seed) { + return new Murmur3_32HashFunction(seed); + } + + /** + * Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by + * delegating to the SHA-1 {@link MessageDigest}. + */ + public static HashFunction sha1() { + return Sha1Holder.SHA_1; + } + + /** + * Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by + * delegating to the SHA-256 {@link MessageDigest}. + */ + public static HashFunction sha256() { + return Sha256Holder.SHA_256; + } + + /** + * Returns a hash function implementing the SHA-512 algorithm (512 hash bits) by + * delegating to the SHA-512 {@link MessageDigest}. + */ + public static HashFunction sha512() { + return Sha512Holder.SHA_512; + } + + /** + * Returns a hash function implementing the + * 64-bit SipHash-2-4 algorithm using + * a seed value of {@code k = 00 01 02 ...}. + * + * @since 15.0 + */ + public static HashFunction sipHash24() { + return SipHash24Holder.SIP_HASH_24; + } + + /** + * Returns a hash function implementing the + * 64-bit SipHash-2-4 algorithm using + * the given seed. + * + * @since 15.0 + */ + public static HashFunction sipHash24(long k0, long k1) { + return new SipHashFunction(2, 4, k0, k1); } private Hashing() { diff --git a/src/main/java/com/google/common/hash/HashingInputStream.java b/src/main/java/com/google/common/hash/HashingInputStream.java index 4c11d4a6..1bc73b9f 100644 --- a/src/main/java/com/google/common/hash/HashingInputStream.java +++ b/src/main/java/com/google/common/hash/HashingInputStream.java @@ -44,6 +44,32 @@ public final class HashingInputStream extends FilterInputStream { this.hasher = checkNotNull(hashFunction.newHasher()); } + /** + * Returns the {@link HashCode} based on the data read from this stream. The + * result is unspecified if this method is called more than once on the same + * instance. + */ + public HashCode hash() { + return hasher.hash(); + } + + /** + * mark() is not supported for HashingInputStream + */ + @Override + public void mark(int readlimit) { + } + + /** + * mark() is not supported for HashingInputStream + * + * @return {@code false} always + */ + @Override + public boolean markSupported() { + return false; + } + /** * Reads the next byte of data from the underlying input stream and updates the * hasher with the byte read. @@ -70,23 +96,6 @@ public final class HashingInputStream extends FilterInputStream { return numOfBytesRead; } - /** - * mark() is not supported for HashingInputStream - * - * @return {@code false} always - */ - @Override - public boolean markSupported() { - return false; - } - - /** - * mark() is not supported for HashingInputStream - */ - @Override - public void mark(int readlimit) { - } - /** * reset() is not supported for HashingInputStream. * @@ -96,13 +105,4 @@ public final class HashingInputStream extends FilterInputStream { public void reset() throws IOException { throw new IOException("reset not supported"); } - - /** - * Returns the {@link HashCode} based on the data read from this stream. The - * result is unspecified if this method is called more than once on the same - * instance. - */ - public HashCode hash() { - return hasher.hash(); - } } diff --git a/src/main/java/com/google/common/hash/HashingOutputStream.java b/src/main/java/com/google/common/hash/HashingOutputStream.java index 3aa55322..298325d4 100644 --- a/src/main/java/com/google/common/hash/HashingOutputStream.java +++ b/src/main/java/com/google/common/hash/HashingOutputStream.java @@ -51,16 +51,14 @@ public final class HashingOutputStream extends FilterOutputStream { this.hasher = checkNotNull(hashFunction.newHasher()); } + // Overriding close() because FilterOutputStream's close() method pre-JDK8 has + // bad behavior: + // it silently ignores any exception thrown by flush(). Instead, just close the + // delegate stream. + // It should flush itself if necessary. @Override - public void write(int b) throws IOException { - hasher.putByte((byte) b); - out.write(b); - } - - @Override - public void write(byte[] bytes, int off, int len) throws IOException { - hasher.putBytes(bytes, off, len); - out.write(bytes, off, len); + public void close() throws IOException { + out.close(); } /** @@ -72,13 +70,15 @@ public final class HashingOutputStream extends FilterOutputStream { return hasher.hash(); } - // Overriding close() because FilterOutputStream's close() method pre-JDK8 has - // bad behavior: - // it silently ignores any exception thrown by flush(). Instead, just close the - // delegate stream. - // It should flush itself if necessary. @Override - public void close() throws IOException { - out.close(); + public void write(byte[] bytes, int off, int len) throws IOException { + hasher.putBytes(bytes, off, len); + out.write(bytes, off, len); + } + + @Override + public void write(int b) throws IOException { + hasher.putByte((byte) b); + out.write(b); } } diff --git a/src/main/java/com/google/common/hash/MessageDigestHashFunction.java b/src/main/java/com/google/common/hash/MessageDigestHashFunction.java index fc902400..9e70987d 100644 --- a/src/main/java/com/google/common/hash/MessageDigestHashFunction.java +++ b/src/main/java/com/google/common/hash/MessageDigestHashFunction.java @@ -30,88 +30,6 @@ import java.util.Arrays; * @author Dimitris Andreou */ final class MessageDigestHashFunction extends AbstractStreamingHashFunction implements Serializable { - private final MessageDigest prototype; - private final int bytes; - private final boolean supportsClone; - private final String toString; - - MessageDigestHashFunction(String algorithmName, String toString) { - this.prototype = getMessageDigest(algorithmName); - this.bytes = prototype.getDigestLength(); - this.toString = checkNotNull(toString); - this.supportsClone = supportsClone(); - } - - MessageDigestHashFunction(String algorithmName, int bytes, String toString) { - this.toString = checkNotNull(toString); - this.prototype = getMessageDigest(algorithmName); - int maxLength = prototype.getDigestLength(); - checkArgument(bytes >= 4 && bytes <= maxLength, "bytes (%s) must be >= 4 and < %s", bytes, maxLength); - this.bytes = bytes; - this.supportsClone = supportsClone(); - } - - private boolean supportsClone() { - try { - prototype.clone(); - return true; - } catch (CloneNotSupportedException e) { - return false; - } - } - - @Override - public int bits() { - return bytes * Byte.SIZE; - } - - @Override - public String toString() { - return toString; - } - - private static MessageDigest getMessageDigest(String algorithmName) { - try { - return MessageDigest.getInstance(algorithmName); - } catch (NoSuchAlgorithmException e) { - throw new AssertionError(e); - } - } - - @Override - public Hasher newHasher() { - if (supportsClone) { - try { - return new MessageDigestHasher((MessageDigest) prototype.clone(), bytes); - } catch (CloneNotSupportedException e) { - // falls through - } - } - return new MessageDigestHasher(getMessageDigest(prototype.getAlgorithm()), bytes); - } - - private static final class SerializedForm implements Serializable { - private final String algorithmName; - private final int bytes; - private final String toString; - - private SerializedForm(String algorithmName, int bytes, String toString) { - this.algorithmName = algorithmName; - this.bytes = bytes; - this.toString = toString; - } - - private Object readResolve() { - return new MessageDigestHashFunction(algorithmName, bytes, toString); - } - - private static final long serialVersionUID = 0; - } - - Object writeReplace() { - return new SerializedForm(prototype.getAlgorithm(), bytes, toString); - } - /** * Hasher that updates a message digest. */ @@ -126,6 +44,18 @@ final class MessageDigestHashFunction extends AbstractStreamingHashFunction impl this.bytes = bytes; } + private void checkNotDone() { + checkState(!done, "Cannot re-use a Hasher after calling hash() on it"); + } + + @Override + public HashCode hash() { + checkNotDone(); + done = true; + return (bytes == digest.getDigestLength()) ? HashCode.fromBytesNoCopy(digest.digest()) + : HashCode.fromBytesNoCopy(Arrays.copyOf(digest.digest(), bytes)); + } + @Override protected void update(byte b) { checkNotDone(); @@ -143,17 +73,90 @@ final class MessageDigestHashFunction extends AbstractStreamingHashFunction impl checkNotDone(); digest.update(b, off, len); } + } - private void checkNotDone() { - checkState(!done, "Cannot re-use a Hasher after calling hash() on it"); + private static final class SerializedForm implements Serializable { + private static final long serialVersionUID = 0; + private final String algorithmName; + private final int bytes; + + private final String toString; + + private SerializedForm(String algorithmName, int bytes, String toString) { + this.algorithmName = algorithmName; + this.bytes = bytes; + this.toString = toString; } - @Override - public HashCode hash() { - checkNotDone(); - done = true; - return (bytes == digest.getDigestLength()) ? HashCode.fromBytesNoCopy(digest.digest()) - : HashCode.fromBytesNoCopy(Arrays.copyOf(digest.digest(), bytes)); + private Object readResolve() { + return new MessageDigestHashFunction(algorithmName, bytes, toString); } } + + private static MessageDigest getMessageDigest(String algorithmName) { + try { + return MessageDigest.getInstance(algorithmName); + } catch (NoSuchAlgorithmException e) { + throw new AssertionError(e); + } + } + + private final MessageDigest prototype; + + private final int bytes; + + private final boolean supportsClone; + + private final String toString; + + MessageDigestHashFunction(String algorithmName, int bytes, String toString) { + this.toString = checkNotNull(toString); + this.prototype = getMessageDigest(algorithmName); + int maxLength = prototype.getDigestLength(); + checkArgument(bytes >= 4 && bytes <= maxLength, "bytes (%s) must be >= 4 and < %s", bytes, maxLength); + this.bytes = bytes; + this.supportsClone = supportsClone(); + } + + MessageDigestHashFunction(String algorithmName, String toString) { + this.prototype = getMessageDigest(algorithmName); + this.bytes = prototype.getDigestLength(); + this.toString = checkNotNull(toString); + this.supportsClone = supportsClone(); + } + + @Override + public int bits() { + return bytes * Byte.SIZE; + } + + @Override + public Hasher newHasher() { + if (supportsClone) { + try { + return new MessageDigestHasher((MessageDigest) prototype.clone(), bytes); + } catch (CloneNotSupportedException e) { + // falls through + } + } + return new MessageDigestHasher(getMessageDigest(prototype.getAlgorithm()), bytes); + } + + private boolean supportsClone() { + try { + prototype.clone(); + return true; + } catch (CloneNotSupportedException e) { + return false; + } + } + + @Override + public String toString() { + return toString; + } + + Object writeReplace() { + return new SerializedForm(prototype.getAlgorithm(), bytes, toString); + } } diff --git a/src/main/java/com/google/common/hash/Murmur3_128HashFunction.java b/src/main/java/com/google/common/hash/Murmur3_128HashFunction.java index 5145f4ff..0183d090 100644 --- a/src/main/java/com/google/common/hash/Murmur3_128HashFunction.java +++ b/src/main/java/com/google/common/hash/Murmur3_128HashFunction.java @@ -41,48 +41,38 @@ import javax.annotation.Nullable; * @author Dimitris Andreou */ final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implements Serializable { - // TODO(user): when the shortcuts are implemented, update BloomFilterStrategies - private final int seed; - - Murmur3_128HashFunction(int seed) { - this.seed = seed; - } - - @Override - public int bits() { - return 128; - } - - @Override - public Hasher newHasher() { - return new Murmur3_128Hasher(seed); - } - - @Override - public String toString() { - return "Hashing.murmur3_128(" + seed + ")"; - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof Murmur3_128HashFunction) { - Murmur3_128HashFunction other = (Murmur3_128HashFunction) object; - return seed == other.seed; - } - return false; - } - - @Override - public int hashCode() { - return getClass().hashCode() ^ seed; - } - private static final class Murmur3_128Hasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 16; private static final long C1 = 0x87c37b91114253d5L; private static final long C2 = 0x4cf5ad432745937fL; + + private static long fmix64(long k) { + k ^= k >>> 33; + k *= 0xff51afd7ed558ccdL; + k ^= k >>> 33; + k *= 0xc4ceb9fe1a85ec53L; + k ^= k >>> 33; + return k; + } + + private static long mixK1(long k1) { + k1 *= C1; + k1 = Long.rotateLeft(k1, 31); + k1 *= C2; + return k1; + } + + private static long mixK2(long k2) { + k2 *= C2; + k2 = Long.rotateLeft(k2, 33); + k2 *= C1; + return k2; + } + private long h1; + private long h2; + private int length; Murmur3_128Hasher(int seed) { @@ -92,14 +82,6 @@ final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implem this.length = 0; } - @Override - protected void process(ByteBuffer bb) { - long k1 = bb.getLong(); - long k2 = bb.getLong(); - bmix64(k1, k2); - length += CHUNK_SIZE; - } - private void bmix64(long k1, long k2) { h1 ^= mixK1(k1); @@ -114,6 +96,32 @@ final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implem h2 = h2 * 5 + 0x38495ab5; } + @Override + public HashCode makeHash() { + h1 ^= length; + h2 ^= length; + + h1 += h2; + h2 += h1; + + h1 = fmix64(h1); + h2 = fmix64(h2); + + h1 += h2; + h2 += h1; + + return HashCode.fromBytesNoCopy(ByteBuffer.wrap(new byte[CHUNK_SIZE]).order(ByteOrder.LITTLE_ENDIAN) + .putLong(h1).putLong(h2).array()); + } + + @Override + protected void process(ByteBuffer bb) { + long k1 = bb.getLong(); + long k2 = bb.getLong(); + bmix64(k1, k2); + length += CHUNK_SIZE; + } + @Override protected void processRemaining(ByteBuffer bb) { long k1 = 0; @@ -158,48 +166,43 @@ final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implem h1 ^= mixK1(k1); h2 ^= mixK2(k2); } - - @Override - public HashCode makeHash() { - h1 ^= length; - h2 ^= length; - - h1 += h2; - h2 += h1; - - h1 = fmix64(h1); - h2 = fmix64(h2); - - h1 += h2; - h2 += h1; - - return HashCode.fromBytesNoCopy(ByteBuffer.wrap(new byte[CHUNK_SIZE]).order(ByteOrder.LITTLE_ENDIAN) - .putLong(h1).putLong(h2).array()); - } - - private static long fmix64(long k) { - k ^= k >>> 33; - k *= 0xff51afd7ed558ccdL; - k ^= k >>> 33; - k *= 0xc4ceb9fe1a85ec53L; - k ^= k >>> 33; - return k; - } - - private static long mixK1(long k1) { - k1 *= C1; - k1 = Long.rotateLeft(k1, 31); - k1 *= C2; - return k1; - } - - private static long mixK2(long k2) { - k2 *= C2; - k2 = Long.rotateLeft(k2, 33); - k2 *= C1; - return k2; - } } private static final long serialVersionUID = 0L; + + // TODO(user): when the shortcuts are implemented, update BloomFilterStrategies + private final int seed; + + Murmur3_128HashFunction(int seed) { + this.seed = seed; + } + + @Override + public int bits() { + return 128; + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof Murmur3_128HashFunction) { + Murmur3_128HashFunction other = (Murmur3_128HashFunction) object; + return seed == other.seed; + } + return false; + } + + @Override + public int hashCode() { + return getClass().hashCode() ^ seed; + } + + @Override + public Hasher newHasher() { + return new Murmur3_128Hasher(seed); + } + + @Override + public String toString() { + return "Hashing.murmur3_128(" + seed + ")"; + } } diff --git a/src/main/java/com/google/common/hash/Murmur3_32HashFunction.java b/src/main/java/com/google/common/hash/Murmur3_32HashFunction.java index ab2aa4a3..e89641d5 100644 --- a/src/main/java/com/google/common/hash/Murmur3_32HashFunction.java +++ b/src/main/java/com/google/common/hash/Murmur3_32HashFunction.java @@ -45,9 +45,71 @@ import com.google.common.primitives.Longs; * @author Kurt Alfred Kluever */ final class Murmur3_32HashFunction extends AbstractStreamingHashFunction implements Serializable { + private static final class Murmur3_32Hasher extends AbstractStreamingHasher { + private static final int CHUNK_SIZE = 4; + private int h1; + private int length; + + Murmur3_32Hasher(int seed) { + super(CHUNK_SIZE); + this.h1 = seed; + this.length = 0; + } + + @Override + public HashCode makeHash() { + return Murmur3_32HashFunction.fmix(h1, length); + } + + @Override + protected void process(ByteBuffer bb) { + int k1 = Murmur3_32HashFunction.mixK1(bb.getInt()); + h1 = Murmur3_32HashFunction.mixH1(h1, k1); + length += CHUNK_SIZE; + } + + @Override + protected void processRemaining(ByteBuffer bb) { + length += bb.remaining(); + int k1 = 0; + for (int i = 0; bb.hasRemaining(); i += 8) { + k1 ^= toInt(bb.get()) << i; + } + h1 ^= Murmur3_32HashFunction.mixK1(k1); + } + } + private static final int C1 = 0xcc9e2d51; + private static final int C2 = 0x1b873593; + private static final long serialVersionUID = 0L; + + // Finalization mix - force all bits of a hash block to avalanche + private static HashCode fmix(int h1, int length) { + h1 ^= length; + h1 ^= h1 >>> 16; + h1 *= 0x85ebca6b; + h1 ^= h1 >>> 13; + h1 *= 0xc2b2ae35; + h1 ^= h1 >>> 16; + return HashCode.fromInt(h1); + } + + private static int mixH1(int h1, int k1) { + h1 ^= k1; + h1 = Integer.rotateLeft(h1, 13); + h1 = h1 * 5 + 0xe6546b64; + return h1; + } + + private static int mixK1(int k1) { + k1 *= C1; + k1 = Integer.rotateLeft(k1, 15); + k1 *= C2; + return k1; + } + private final int seed; Murmur3_32HashFunction(int seed) { @@ -59,16 +121,6 @@ final class Murmur3_32HashFunction extends AbstractStreamingHashFunction impleme return 32; } - @Override - public Hasher newHasher() { - return new Murmur3_32Hasher(seed); - } - - @Override - public String toString() { - return "Hashing.murmur3_32(" + seed + ")"; - } - @Override public boolean equals(@Nullable Object object) { if (object instanceof Murmur3_32HashFunction) { @@ -127,64 +179,13 @@ final class Murmur3_32HashFunction extends AbstractStreamingHashFunction impleme return fmix(h1, Chars.BYTES * input.length()); } - private static int mixK1(int k1) { - k1 *= C1; - k1 = Integer.rotateLeft(k1, 15); - k1 *= C2; - return k1; + @Override + public Hasher newHasher() { + return new Murmur3_32Hasher(seed); } - private static int mixH1(int h1, int k1) { - h1 ^= k1; - h1 = Integer.rotateLeft(h1, 13); - h1 = h1 * 5 + 0xe6546b64; - return h1; + @Override + public String toString() { + return "Hashing.murmur3_32(" + seed + ")"; } - - // Finalization mix - force all bits of a hash block to avalanche - private static HashCode fmix(int h1, int length) { - h1 ^= length; - h1 ^= h1 >>> 16; - h1 *= 0x85ebca6b; - h1 ^= h1 >>> 13; - h1 *= 0xc2b2ae35; - h1 ^= h1 >>> 16; - return HashCode.fromInt(h1); - } - - private static final class Murmur3_32Hasher extends AbstractStreamingHasher { - private static final int CHUNK_SIZE = 4; - private int h1; - private int length; - - Murmur3_32Hasher(int seed) { - super(CHUNK_SIZE); - this.h1 = seed; - this.length = 0; - } - - @Override - protected void process(ByteBuffer bb) { - int k1 = Murmur3_32HashFunction.mixK1(bb.getInt()); - h1 = Murmur3_32HashFunction.mixH1(h1, k1); - length += CHUNK_SIZE; - } - - @Override - protected void processRemaining(ByteBuffer bb) { - length += bb.remaining(); - int k1 = 0; - for (int i = 0; bb.hasRemaining(); i += 8) { - k1 ^= toInt(bb.get()) << i; - } - h1 ^= Murmur3_32HashFunction.mixK1(k1); - } - - @Override - public HashCode makeHash() { - return Murmur3_32HashFunction.fmix(h1, length); - } - } - - private static final long serialVersionUID = 0L; } diff --git a/src/main/java/com/google/common/hash/PrimitiveSink.java b/src/main/java/com/google/common/hash/PrimitiveSink.java index 5d1706de..c57251b7 100644 --- a/src/main/java/com/google/common/hash/PrimitiveSink.java +++ b/src/main/java/com/google/common/hash/PrimitiveSink.java @@ -26,6 +26,11 @@ import com.google.common.annotations.Beta; */ @Beta public interface PrimitiveSink { + /** + * Puts a boolean into this sink. + */ + PrimitiveSink putBoolean(boolean b); + /** * Puts a byte into this sink. * @@ -57,9 +62,19 @@ public interface PrimitiveSink { PrimitiveSink putBytes(byte[] bytes, int off, int len); /** - * Puts a short into this sink. + * Puts a character into this sink. */ - PrimitiveSink putShort(short s); + PrimitiveSink putChar(char c); + + /** + * Puts a double into this sink. + */ + PrimitiveSink putDouble(double d); + + /** + * Puts a float into this sink. + */ + PrimitiveSink putFloat(float f); /** * Puts an int into this sink. @@ -72,24 +87,14 @@ public interface PrimitiveSink { PrimitiveSink putLong(long l); /** - * Puts a float into this sink. + * Puts a short into this sink. */ - PrimitiveSink putFloat(float f); + PrimitiveSink putShort(short s); /** - * Puts a double into this sink. + * Puts a string into this sink using the given charset. */ - PrimitiveSink putDouble(double d); - - /** - * Puts a boolean into this sink. - */ - PrimitiveSink putBoolean(boolean b); - - /** - * Puts a character into this sink. - */ - PrimitiveSink putChar(char c); + PrimitiveSink putString(CharSequence charSequence, Charset charset); /** * Puts each 16-bit code unit from the {@link CharSequence} into this sink. @@ -97,9 +102,4 @@ public interface PrimitiveSink { * @since 15.0 (since 11.0 as putString(CharSequence)) */ PrimitiveSink putUnencodedChars(CharSequence charSequence); - - /** - * Puts a string into this sink using the given charset. - */ - PrimitiveSink putString(CharSequence charSequence, Charset charset); } diff --git a/src/main/java/com/google/common/hash/SipHashFunction.java b/src/main/java/com/google/common/hash/SipHashFunction.java index 322738b7..97a55439 100644 --- a/src/main/java/com/google/common/hash/SipHashFunction.java +++ b/src/main/java/com/google/common/hash/SipHashFunction.java @@ -35,60 +35,6 @@ import javax.annotation.Nullable; */ final class SipHashFunction extends AbstractStreamingHashFunction implements Serializable { - // The number of compression rounds. - private final int c; - // The number of finalization rounds. - private final int d; - // Two 64-bit keys (represent a single 128-bit key). - private final long k0; - private final long k1; - - /** - * @param c the number of compression rounds (must be positive) - * @param d the number of finalization rounds (must be positive) - * @param k0 the first half of the key - * @param k1 the second half of the key - */ - SipHashFunction(int c, int d, long k0, long k1) { - checkArgument(c > 0, "The number of SipRound iterations (c=%s) during Compression must be positive.", c); - checkArgument(d > 0, "The number of SipRound iterations (d=%s) during Finalization must be positive.", d); - this.c = c; - this.d = d; - this.k0 = k0; - this.k1 = k1; - } - - @Override - public int bits() { - return 64; - } - - @Override - public Hasher newHasher() { - return new SipHasher(c, d, k0, k1); - } - - // TODO(user): Implement and benchmark the hashFoo() shortcuts. - - @Override - public String toString() { - return "Hashing.sipHash" + c + "" + d + "(" + k0 + ", " + k1 + ")"; - } - - @Override - public boolean equals(@Nullable Object object) { - if (object instanceof SipHashFunction) { - SipHashFunction other = (SipHashFunction) object; - return (c == other.c) && (d == other.d) && (k0 == other.k0) && (k1 == other.k1); - } - return false; - } - - @Override - public int hashCode() { - return (int) (getClass().hashCode() ^ c ^ d ^ k0 ^ k1); - } - private static final class SipHasher extends AbstractStreamingHasher { private static final int CHUNK_SIZE = 8; @@ -126,20 +72,6 @@ final class SipHashFunction extends AbstractStreamingHashFunction implements Ser this.v3 ^= k1; } - @Override - protected void process(ByteBuffer buffer) { - b += CHUNK_SIZE; - processM(buffer.getLong()); - } - - @Override - protected void processRemaining(ByteBuffer buffer) { - b += buffer.remaining(); - for (int i = 0; buffer.hasRemaining(); i += 8) { - finalM ^= (buffer.get() & 0xFFL) << i; - } - } - @Override public HashCode makeHash() { // End with a byte encoding the positive integer b mod 256. @@ -152,12 +84,26 @@ final class SipHashFunction extends AbstractStreamingHashFunction implements Ser return HashCode.fromLong(v0 ^ v1 ^ v2 ^ v3); } + @Override + protected void process(ByteBuffer buffer) { + b += CHUNK_SIZE; + processM(buffer.getLong()); + } + private void processM(long m) { v3 ^= m; sipRound(c); v0 ^= m; } + @Override + protected void processRemaining(ByteBuffer buffer) { + b += buffer.remaining(); + for (int i = 0; buffer.hasRemaining(); i += 8) { + finalM ^= (buffer.get() & 0xFFL) << i; + } + } + private void sipRound(int iterations) { for (int i = 0; i < iterations; i++) { v0 += v1; @@ -179,4 +125,59 @@ final class SipHashFunction extends AbstractStreamingHashFunction implements Ser } private static final long serialVersionUID = 0L; + // The number of compression rounds. + private final int c; + // The number of finalization rounds. + private final int d; + + // Two 64-bit keys (represent a single 128-bit key). + private final long k0; + + private final long k1; + + /** + * @param c the number of compression rounds (must be positive) + * @param d the number of finalization rounds (must be positive) + * @param k0 the first half of the key + * @param k1 the second half of the key + */ + SipHashFunction(int c, int d, long k0, long k1) { + checkArgument(c > 0, "The number of SipRound iterations (c=%s) during Compression must be positive.", c); + checkArgument(d > 0, "The number of SipRound iterations (d=%s) during Finalization must be positive.", d); + this.c = c; + this.d = d; + this.k0 = k0; + this.k1 = k1; + } + + // TODO(user): Implement and benchmark the hashFoo() shortcuts. + + @Override + public int bits() { + return 64; + } + + @Override + public boolean equals(@Nullable Object object) { + if (object instanceof SipHashFunction) { + SipHashFunction other = (SipHashFunction) object; + return (c == other.c) && (d == other.d) && (k0 == other.k0) && (k1 == other.k1); + } + return false; + } + + @Override + public int hashCode() { + return (int) (getClass().hashCode() ^ c ^ d ^ k0 ^ k1); + } + + @Override + public Hasher newHasher() { + return new SipHasher(c, d, k0, k1); + } + + @Override + public String toString() { + return "Hashing.sipHash" + c + "" + d + "(" + k0 + ", " + k1 + ")"; + } } diff --git a/src/main/java/com/google/common/html/HtmlEscapers.java b/src/main/java/com/google/common/html/HtmlEscapers.java index 4e8020fb..f1837de9 100644 --- a/src/main/java/com/google/common/html/HtmlEscapers.java +++ b/src/main/java/com/google/common/html/HtmlEscapers.java @@ -41,6 +41,13 @@ import com.google.common.escape.Escapers; @Beta @GwtCompatible public final class HtmlEscapers { + private static final Escaper HTML_ESCAPER = Escapers.builder().addEscape('"', """) + // Note: "'" is not defined in HTML 4.01. + .addEscape('\'', "'").addEscape('&', "&").addEscape('<', "<").addEscape('>', ">").build(); + + // For each xxxEscaper() method, please add links to external reference pages + // that are considered authoritative for the behavior of that escaper. + /** * Returns an {@link Escaper} instance that escapes HTML metacharacters as * specified by HTML 4.01. The @@ -61,13 +68,6 @@ public final class HtmlEscapers { return HTML_ESCAPER; } - // For each xxxEscaper() method, please add links to external reference pages - // that are considered authoritative for the behavior of that escaper. - - private static final Escaper HTML_ESCAPER = Escapers.builder().addEscape('"', """) - // Note: "'" is not defined in HTML 4.01. - .addEscape('\'', "'").addEscape('&', "&").addEscape('<', "<").addEscape('>', ">").build(); - private HtmlEscapers() { } } diff --git a/src/main/java/com/google/common/io/AppendableWriter.java b/src/main/java/com/google/common/io/AppendableWriter.java index 990db9c7..01c23658 100644 --- a/src/main/java/com/google/common/io/AppendableWriter.java +++ b/src/main/java/com/google/common/io/AppendableWriter.java @@ -51,54 +51,6 @@ class AppendableWriter extends Writer { * Abstract methods from Writer */ - @Override - public void write(char cbuf[], int off, int len) throws IOException { - checkNotClosed(); - // It turns out that creating a new String is usually as fast, or faster - // than wrapping cbuf in a light-weight CharSequence. - target.append(new String(cbuf, off, len)); - } - - @Override - public void flush() throws IOException { - checkNotClosed(); - if (target instanceof Flushable) { - ((Flushable) target).flush(); - } - } - - @Override - public void close() throws IOException { - this.closed = true; - if (target instanceof Closeable) { - ((Closeable) target).close(); - } - } - - /* - * Override a few functions for performance reasons to avoid creating - * unnecessary strings. - */ - - @Override - public void write(int c) throws IOException { - checkNotClosed(); - target.append((char) c); - } - - @Override - public void write(@Nullable String str) throws IOException { - checkNotClosed(); - target.append(str); - } - - @Override - public void write(@Nullable String str, int off, int len) throws IOException { - checkNotClosed(); - // tricky: append takes start, end pair... - target.append(str, off, off + len); - } - @Override public Writer append(char c) throws IOException { checkNotClosed(); @@ -120,9 +72,57 @@ class AppendableWriter extends Writer { return this; } + /* + * Override a few functions for performance reasons to avoid creating + * unnecessary strings. + */ + private void checkNotClosed() throws IOException { if (closed) { throw new IOException("Cannot write to a closed writer."); } } + + @Override + public void close() throws IOException { + this.closed = true; + if (target instanceof Closeable) { + ((Closeable) target).close(); + } + } + + @Override + public void flush() throws IOException { + checkNotClosed(); + if (target instanceof Flushable) { + ((Flushable) target).flush(); + } + } + + @Override + public void write(char cbuf[], int off, int len) throws IOException { + checkNotClosed(); + // It turns out that creating a new String is usually as fast, or faster + // than wrapping cbuf in a light-weight CharSequence. + target.append(new String(cbuf, off, len)); + } + + @Override + public void write(int c) throws IOException { + checkNotClosed(); + target.append((char) c); + } + + @Override + public void write(@Nullable String str) throws IOException { + checkNotClosed(); + target.append(str); + } + + @Override + public void write(@Nullable String str, int off, int len) throws IOException { + checkNotClosed(); + // tricky: append takes start, end pair... + target.append(str, off, off + len); + } } diff --git a/src/main/java/com/google/common/io/BaseEncoding.java b/src/main/java/com/google/common/io/BaseEncoding.java index e9e2a7a3..695ee7d8 100644 --- a/src/main/java/com/google/common/io/BaseEncoding.java +++ b/src/main/java/com/google/common/io/BaseEncoding.java @@ -58,7 +58,8 @@ import com.google.common.io.GwtWorkarounds.CharOutput; * *

            *    {@code
          - *   BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII))}
          + * BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII))
          + * }
            * 
          * *

          @@ -82,7 +83,8 @@ import com.google.common.io.GwtWorkarounds.CharOutput; * *

            *    {@code
          - *  BaseEncoding.base16().lowerCase().decode("deadbeef");}
          + * BaseEncoding.base16().lowerCase().decode("deadbeef");
          + * }
            * 
          * *

          @@ -92,10 +94,11 @@ import com.google.common.io.GwtWorkarounds.CharOutput; * *

            *    {@code
          - *   // Do NOT do this
          - *   BaseEncoding hex = BaseEncoding.base16();
          - *   hex.lowerCase(); // does nothing!
          - *   return hex.decode("deadbeef"); // throws an IllegalArgumentException}
          + * // Do NOT do this
          + * BaseEncoding hex = BaseEncoding.base16();
          + * hex.lowerCase(); // does nothing!
          + * return hex.decode("deadbeef"); // throws an IllegalArgumentException
          + * }
            * 
          * *

          @@ -156,344 +159,6 @@ import com.google.common.io.GwtWorkarounds.CharOutput; public abstract class BaseEncoding { // TODO(user): consider adding encodeTo(Appendable, byte[], [int, int]) - BaseEncoding() { - } - - /** - * Exception indicating invalid base-encoded input encountered while decoding. - * - * @author Louis Wasserman - * @since 15.0 - */ - public static final class DecodingException extends IOException { - DecodingException(String message) { - super(message); - } - - DecodingException(Throwable cause) { - super(cause); - } - } - - /** - * Encodes the specified byte array, and returns the encoded {@code String}. - */ - public String encode(byte[] bytes) { - return encode(checkNotNull(bytes), 0, bytes.length); - } - - /** - * Encodes the specified range of the specified byte array, and returns the - * encoded {@code String}. - */ - public final String encode(byte[] bytes, int off, int len) { - checkNotNull(bytes); - checkPositionIndexes(off, off + len, bytes.length); - CharOutput result = stringBuilderOutput(maxEncodedSize(len)); - ByteOutput byteOutput = encodingStream(result); - try { - for (int i = 0; i < len; i++) { - byteOutput.write(bytes[off + i]); - } - byteOutput.close(); - } catch (IOException impossible) { - throw new AssertionError("impossible"); - } - return result.toString(); - } - - /** - * Returns an {@code OutputStream} that encodes bytes using this encoding into - * the specified {@code Writer}. When the returned {@code OutputStream} is - * closed, so is the backing {@code Writer}. - */ - @GwtIncompatible("Writer,OutputStream") - public final OutputStream encodingStream(Writer writer) { - return asOutputStream(encodingStream(asCharOutput(writer))); - } - - /** - * Returns a {@code ByteSink} that writes base-encoded bytes to the specified - * {@code CharSink}. - */ - @GwtIncompatible("ByteSink,CharSink") - public final ByteSink encodingSink(final CharSink encodedSink) { - checkNotNull(encodedSink); - return new ByteSink() { - @Override - public OutputStream openStream() throws IOException { - return encodingStream(encodedSink.openStream()); - } - }; - } - - // TODO(user): document the extent of leniency, probably after adding - // ignore(CharMatcher) - - private static byte[] extract(byte[] result, int length) { - if (length == result.length) { - return result; - } else { - byte[] trunc = new byte[length]; - System.arraycopy(result, 0, trunc, 0, length); - return trunc; - } - } - - /** - * Decodes the specified character sequence, and returns the resulting - * {@code byte[]}. This is the inverse operation to {@link #encode(byte[])}. - * - * @throws IllegalArgumentException if the input is not a valid encoded string - * according to this encoding. - */ - public final byte[] decode(CharSequence chars) { - try { - return decodeChecked(chars); - } catch (DecodingException badInput) { - throw new IllegalArgumentException(badInput); - } - } - - /** - * Decodes the specified character sequence, and returns the resulting - * {@code byte[]}. This is the inverse operation to {@link #encode(byte[])}. - * - * @throws DecodingException if the input is not a valid encoded string - * according to this encoding. - */ - final byte[] decodeChecked(CharSequence chars) throws DecodingException { - chars = padding().trimTrailingFrom(chars); - ByteInput decodedInput = decodingStream(asCharInput(chars)); - byte[] tmp = new byte[maxDecodedSize(chars.length())]; - int index = 0; - try { - for (int i = decodedInput.read(); i != -1; i = decodedInput.read()) { - tmp[index++] = (byte) i; - } - } catch (DecodingException badInput) { - throw badInput; - } catch (IOException impossible) { - throw new AssertionError(impossible); - } - return extract(tmp, index); - } - - /** - * Returns an {@code InputStream} that decodes base-encoded input from the - * specified {@code Reader}. The returned stream throws a - * {@link DecodingException} upon decoding-specific errors. - */ - @GwtIncompatible("Reader,InputStream") - public final InputStream decodingStream(Reader reader) { - return asInputStream(decodingStream(asCharInput(reader))); - } - - /** - * Returns a {@code ByteSource} that reads base-encoded bytes from the specified - * {@code CharSource}. - */ - @GwtIncompatible("ByteSource,CharSource") - public final ByteSource decodingSource(final CharSource encodedSource) { - checkNotNull(encodedSource); - return new ByteSource() { - @Override - public InputStream openStream() throws IOException { - return decodingStream(encodedSource.openStream()); - } - }; - } - - // Implementations for encoding/decoding - - abstract int maxEncodedSize(int bytes); - - abstract ByteOutput encodingStream(CharOutput charOutput); - - abstract int maxDecodedSize(int chars); - - abstract ByteInput decodingStream(CharInput charInput); - - abstract CharMatcher padding(); - - // Modified encoding generators - - /** - * Returns an encoding that behaves equivalently to this encoding, but omits any - * padding characters as specified by - * RFC 4648 section - * 3.2, Padding of Encoded Data. - */ - @CheckReturnValue - public abstract BaseEncoding omitPadding(); - - /** - * Returns an encoding that behaves equivalently to this encoding, but uses an - * alternate character for padding. - * - * @throws IllegalArgumentException if this padding character is already used in - * the alphabet or a separator - */ - @CheckReturnValue - public abstract BaseEncoding withPadChar(char padChar); - - /** - * Returns an encoding that behaves equivalently to this encoding, but adds a - * separator string after every {@code n} characters. Any occurrences of any - * characters that occur in the separator are skipped over in decoding. - * - * @throws IllegalArgumentException if any alphabet or padding characters - * appear in the separator string, or if - * {@code n <= 0} - * @throws UnsupportedOperationException if this encoding already uses a - * separator - */ - @CheckReturnValue - public abstract BaseEncoding withSeparator(String separator, int n); - - /** - * Returns an encoding that behaves equivalently to this encoding, but encodes - * and decodes with uppercase letters. Padding and separator characters remain - * in their original case. - * - * @throws IllegalStateException if the alphabet used by this encoding contains - * mixed upper- and lower-case characters - */ - @CheckReturnValue - public abstract BaseEncoding upperCase(); - - /** - * Returns an encoding that behaves equivalently to this encoding, but encodes - * and decodes with lowercase letters. Padding and separator characters remain - * in their original case. - * - * @throws IllegalStateException if the alphabet used by this encoding contains - * mixed upper- and lower-case characters - */ - @CheckReturnValue - public abstract BaseEncoding lowerCase(); - - private static final BaseEncoding BASE64 = new StandardBaseEncoding("base64()", - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '='); - - /** - * The "base64" base encoding specified by - * RFC 4648 section - * 4, Base 64 Encoding. (This is the same as the base 64 encoding from - * RFC 3548.) - * - *

          - * The character {@code '='} is used for padding, but can be - * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) - * replaced}. - * - *

          - * No line feeds are added by default, as per - * RFC 4648 section - * 3.1, Line Feeds in Encoded Data. Line feeds may be added using - * {@link #withSeparator(String, int)}. - */ - public static BaseEncoding base64() { - return BASE64; - } - - private static final BaseEncoding BASE64_URL = new StandardBaseEncoding("base64Url()", - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '='); - - /** - * The "base64url" encoding specified by - * RFC 4648 section - * 5, Base 64 Encoding with URL and Filename Safe Alphabet, also sometimes - * referred to as the "web safe Base64." (This is the same as the base 64 - * encoding with URL and filename safe alphabet from - * RFC 3548.) - * - *

          - * The character {@code '='} is used for padding, but can be - * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) - * replaced}. - * - *

          - * No line feeds are added by default, as per - * RFC 4648 section - * 3.1, Line Feeds in Encoded Data. Line feeds may be added using - * {@link #withSeparator(String, int)}. - */ - public static BaseEncoding base64Url() { - return BASE64_URL; - } - - private static final BaseEncoding BASE32 = new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - '='); - - /** - * The "base32" encoding specified by - * RFC 4648 section - * 6, Base 32 Encoding. (This is the same as the base 32 encoding from - * RFC 3548.) - * - *

          - * The character {@code '='} is used for padding, but can be - * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) - * replaced}. - * - *

          - * No line feeds are added by default, as per - * RFC 4648 section - * 3.1, Line Feeds in Encoded Data. Line feeds may be added using - * {@link #withSeparator(String, int)}. - */ - public static BaseEncoding base32() { - return BASE32; - } - - private static final BaseEncoding BASE32_HEX = new StandardBaseEncoding("base32Hex()", - "0123456789ABCDEFGHIJKLMNOPQRSTUV", '='); - - /** - * The "base32hex" encoding specified by - * RFC 4648 section - * 7, Base 32 Encoding with Extended Hex Alphabet. There is no corresponding - * encoding in RFC 3548. - * - *

          - * The character {@code '='} is used for padding, but can be - * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) - * replaced}. - * - *

          - * No line feeds are added by default, as per - * RFC 4648 section - * 3.1, Line Feeds in Encoded Data. Line feeds may be added using - * {@link #withSeparator(String, int)}. - */ - public static BaseEncoding base32Hex() { - return BASE32_HEX; - } - - private static final BaseEncoding BASE16 = new StandardBaseEncoding("base16()", "0123456789ABCDEF", null); - - /** - * The "base16" encoding specified by - * RFC 4648 section - * 8, Base 16 Encoding. (This is the same as the base 16 encoding from - * RFC 3548.) This is - * commonly known as "hexadecimal" format. - * - *

          - * No padding is necessary in base 16, so {@link #withPadChar(char)} and - * {@link #omitPadding()} have no effect. - * - *

          - * No line feeds are added by default, as per - * RFC 4648 section - * 3.1, Line Feeds in Encoded Data. Line feeds may be added using - * {@link #withSeparator(String, int)}. - */ - public static BaseEncoding base16() { - return BASE16; - } - private static final class Alphabet extends CharMatcher { private final String name; // this is meant to be immutable -- don't modify it! @@ -542,14 +207,6 @@ public abstract class BaseEncoding { this.validPadding = validPadding; } - char encode(int bits) { - return chars[bits]; - } - - boolean isValidPaddingStartPosition(int index) { - return validPadding[index % charsPerChunk]; - } - int decode(char ch) throws IOException { if (ch > Ascii.MAX || decodabet[ch] == -1) { throw new DecodingException("Unrecognized character: " + ch); @@ -557,6 +214,10 @@ public abstract class BaseEncoding { return decodabet[ch]; } + char encode(int bits) { + return chars[bits]; + } + private boolean hasLowerCase() { for (char c : chars) { if (Ascii.isLowerCase(c)) { @@ -575,17 +236,8 @@ public abstract class BaseEncoding { return false; } - Alphabet upperCase() { - if (!hasLowerCase()) { - return this; - } else { - checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); - char[] upperCased = new char[chars.length]; - for (int i = 0; i < chars.length; i++) { - upperCased[i] = Ascii.toUpperCase(chars[i]); - } - return new Alphabet(name + ".upperCase()", upperCased); - } + boolean isValidPaddingStartPosition(int index) { + return validPadding[index % charsPerChunk]; } Alphabet lowerCase() { @@ -610,6 +262,107 @@ public abstract class BaseEncoding { public String toString() { return name; } + + Alphabet upperCase() { + if (!hasLowerCase()) { + return this; + } else { + checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); + char[] upperCased = new char[chars.length]; + for (int i = 0; i < chars.length; i++) { + upperCased[i] = Ascii.toUpperCase(chars[i]); + } + return new Alphabet(name + ".upperCase()", upperCased); + } + } + } + + /** + * Exception indicating invalid base-encoded input encountered while decoding. + * + * @author Louis Wasserman + * @since 15.0 + */ + public static final class DecodingException extends IOException { + DecodingException(String message) { + super(message); + } + + DecodingException(Throwable cause) { + super(cause); + } + } + + static final class SeparatedBaseEncoding extends BaseEncoding { + private final BaseEncoding delegate; + private final String separator; + private final int afterEveryChars; + private final CharMatcher separatorChars; + + SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) { + this.delegate = checkNotNull(delegate); + this.separator = checkNotNull(separator); + this.afterEveryChars = afterEveryChars; + checkArgument(afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars); + this.separatorChars = CharMatcher.anyOf(separator).precomputed(); + } + + @Override + ByteInput decodingStream(final CharInput input) { + return delegate.decodingStream(ignoringInput(input, separatorChars)); + } + + @Override + ByteOutput encodingStream(final CharOutput output) { + return delegate.encodingStream(separatingOutput(output, separator, afterEveryChars)); + } + + @Override + public BaseEncoding lowerCase() { + return delegate.lowerCase().withSeparator(separator, afterEveryChars); + } + + @Override + int maxDecodedSize(int chars) { + return delegate.maxDecodedSize(chars); + } + + @Override + int maxEncodedSize(int bytes) { + int unseparatedSize = delegate.maxEncodedSize(bytes); + return unseparatedSize + + separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR); + } + + @Override + public BaseEncoding omitPadding() { + return delegate.omitPadding().withSeparator(separator, afterEveryChars); + } + + @Override + CharMatcher padding() { + return delegate.padding(); + } + + @Override + public String toString() { + return delegate.toString() + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")"; + } + + @Override + public BaseEncoding upperCase() { + return delegate.upperCase().withSeparator(separator, afterEveryChars); + } + + @Override + public BaseEncoding withPadChar(char padChar) { + return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars); + } + + @Override + public BaseEncoding withSeparator(String separator, int afterEveryChars) { + throw new UnsupportedOperationException("Already have a separator"); + } } static final class StandardBaseEncoding extends BaseEncoding { @@ -619,9 +372,9 @@ public abstract class BaseEncoding { @Nullable private final Character paddingChar; - StandardBaseEncoding(String name, String alphabetChars, @Nullable Character paddingChar) { - this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); - } + private transient BaseEncoding upperCase; + + private transient BaseEncoding lowerCase; StandardBaseEncoding(Alphabet alphabet, @Nullable Character paddingChar) { this.alphabet = checkNotNull(alphabet); @@ -630,63 +383,8 @@ public abstract class BaseEncoding { this.paddingChar = paddingChar; } - @Override - CharMatcher padding() { - return (paddingChar == null) ? CharMatcher.NONE : CharMatcher.is(paddingChar.charValue()); - } - - @Override - int maxEncodedSize(int bytes) { - return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING); - } - - @Override - ByteOutput encodingStream(final CharOutput out) { - checkNotNull(out); - return new ByteOutput() { - int bitBuffer = 0; - int bitBufferLength = 0; - int writtenChars = 0; - - @Override - public void write(byte b) throws IOException { - bitBuffer <<= 8; - bitBuffer |= b & 0xFF; - bitBufferLength += 8; - while (bitBufferLength >= alphabet.bitsPerChar) { - int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask; - out.write(alphabet.encode(charIndex)); - writtenChars++; - bitBufferLength -= alphabet.bitsPerChar; - } - } - - @Override - public void flush() throws IOException { - out.flush(); - } - - @Override - public void close() throws IOException { - if (bitBufferLength > 0) { - int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask; - out.write(alphabet.encode(charIndex)); - writtenChars++; - if (paddingChar != null) { - while (writtenChars % alphabet.charsPerChunk != 0) { - out.write(paddingChar.charValue()); - writtenChars++; - } - } - } - out.close(); - } - }; - } - - @Override - int maxDecodedSize(int chars) { - return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L); + StandardBaseEncoding(String name, String alphabetChars, @Nullable Character paddingChar) { + this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); } @Override @@ -699,6 +397,11 @@ public abstract class BaseEncoding { boolean hitPadding = false; final CharMatcher paddingMatcher = padding(); + @Override + public void close() throws IOException { + reader.close(); + } + @Override public int read() throws IOException { while (true) { @@ -732,19 +435,107 @@ public abstract class BaseEncoding { } } } + }; + } + + @Override + ByteOutput encodingStream(final CharOutput out) { + checkNotNull(out); + return new ByteOutput() { + int bitBuffer = 0; + int bitBufferLength = 0; + int writtenChars = 0; @Override public void close() throws IOException { - reader.close(); + if (bitBufferLength > 0) { + int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask; + out.write(alphabet.encode(charIndex)); + writtenChars++; + if (paddingChar != null) { + while (writtenChars % alphabet.charsPerChunk != 0) { + out.write(paddingChar.charValue()); + writtenChars++; + } + } + } + out.close(); + } + + @Override + public void flush() throws IOException { + out.flush(); + } + + @Override + public void write(byte b) throws IOException { + bitBuffer <<= 8; + bitBuffer |= b & 0xFF; + bitBufferLength += 8; + while (bitBufferLength >= alphabet.bitsPerChar) { + int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask; + out.write(alphabet.encode(charIndex)); + writtenChars++; + bitBufferLength -= alphabet.bitsPerChar; + } } }; } + @Override + public BaseEncoding lowerCase() { + BaseEncoding result = lowerCase; + if (result == null) { + Alphabet lower = alphabet.lowerCase(); + result = lowerCase = (lower == alphabet) ? this : new StandardBaseEncoding(lower, paddingChar); + } + return result; + } + + @Override + int maxDecodedSize(int chars) { + return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L); + } + + @Override + int maxEncodedSize(int bytes) { + return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING); + } + @Override public BaseEncoding omitPadding() { return (paddingChar == null) ? this : new StandardBaseEncoding(alphabet, null); } + @Override + CharMatcher padding() { + return (paddingChar == null) ? CharMatcher.NONE : CharMatcher.is(paddingChar.charValue()); + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder("BaseEncoding."); + builder.append(alphabet.toString()); + if (8 % alphabet.bitsPerChar != 0) { + if (paddingChar == null) { + builder.append(".omitPadding()"); + } else { + builder.append(".withPadChar(").append(paddingChar).append(')'); + } + } + return builder.toString(); + } + + @Override + public BaseEncoding upperCase() { + BaseEncoding result = upperCase; + if (result == null) { + Alphabet upper = alphabet.upperCase(); + result = upperCase = (upper == alphabet) ? this : new StandardBaseEncoding(upper, paddingChar); + } + return result; + } + @Override public BaseEncoding withPadChar(char padChar) { if (8 % alphabet.bitsPerChar == 0 || (paddingChar != null && paddingChar.charValue() == padChar)) { @@ -761,42 +552,141 @@ public abstract class BaseEncoding { "Separator cannot contain alphabet or padding characters"); return new SeparatedBaseEncoding(this, separator, afterEveryChars); } + } - private transient BaseEncoding upperCase; - private transient BaseEncoding lowerCase; + private static final BaseEncoding BASE64 = new StandardBaseEncoding("base64()", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '='); - @Override - public BaseEncoding upperCase() { - BaseEncoding result = upperCase; - if (result == null) { - Alphabet upper = alphabet.upperCase(); - result = upperCase = (upper == alphabet) ? this : new StandardBaseEncoding(upper, paddingChar); - } + private static final BaseEncoding BASE64_URL = new StandardBaseEncoding("base64Url()", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '='); + + // TODO(user): document the extent of leniency, probably after adding + // ignore(CharMatcher) + + private static final BaseEncoding BASE32 = new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + '='); + + private static final BaseEncoding BASE32_HEX = new StandardBaseEncoding("base32Hex()", + "0123456789ABCDEFGHIJKLMNOPQRSTUV", '='); + + private static final BaseEncoding BASE16 = new StandardBaseEncoding("base16()", "0123456789ABCDEF", null); + + /** + * The "base16" encoding specified by + * RFC 4648 section + * 8, Base 16 Encoding. (This is the same as the base 16 encoding from + * RFC 3548.) This is + * commonly known as "hexadecimal" format. + * + *

          + * No padding is necessary in base 16, so {@link #withPadChar(char)} and + * {@link #omitPadding()} have no effect. + * + *

          + * No line feeds are added by default, as per + * RFC 4648 section + * 3.1, Line Feeds in Encoded Data. Line feeds may be added using + * {@link #withSeparator(String, int)}. + */ + public static BaseEncoding base16() { + return BASE16; + } + + /** + * The "base32" encoding specified by + * RFC 4648 section + * 6, Base 32 Encoding. (This is the same as the base 32 encoding from + * RFC 3548.) + * + *

          + * The character {@code '='} is used for padding, but can be + * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) + * replaced}. + * + *

          + * No line feeds are added by default, as per + * RFC 4648 section + * 3.1, Line Feeds in Encoded Data. Line feeds may be added using + * {@link #withSeparator(String, int)}. + */ + public static BaseEncoding base32() { + return BASE32; + } + + // Implementations for encoding/decoding + + /** + * The "base32hex" encoding specified by + * RFC 4648 section + * 7, Base 32 Encoding with Extended Hex Alphabet. There is no corresponding + * encoding in RFC 3548. + * + *

          + * The character {@code '='} is used for padding, but can be + * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) + * replaced}. + * + *

          + * No line feeds are added by default, as per + * RFC 4648 section + * 3.1, Line Feeds in Encoded Data. Line feeds may be added using + * {@link #withSeparator(String, int)}. + */ + public static BaseEncoding base32Hex() { + return BASE32_HEX; + } + + /** + * The "base64" base encoding specified by + * RFC 4648 section + * 4, Base 64 Encoding. (This is the same as the base 64 encoding from + * RFC 3548.) + * + *

          + * The character {@code '='} is used for padding, but can be + * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) + * replaced}. + * + *

          + * No line feeds are added by default, as per + * RFC 4648 section + * 3.1, Line Feeds in Encoded Data. Line feeds may be added using + * {@link #withSeparator(String, int)}. + */ + public static BaseEncoding base64() { + return BASE64; + } + + /** + * The "base64url" encoding specified by + * RFC 4648 section + * 5, Base 64 Encoding with URL and Filename Safe Alphabet, also sometimes + * referred to as the "web safe Base64." (This is the same as the base 64 + * encoding with URL and filename safe alphabet from + * RFC 3548.) + * + *

          + * The character {@code '='} is used for padding, but can be + * {@linkplain #omitPadding() omitted} or {@linkplain #withPadChar(char) + * replaced}. + * + *

          + * No line feeds are added by default, as per + * RFC 4648 section + * 3.1, Line Feeds in Encoded Data. Line feeds may be added using + * {@link #withSeparator(String, int)}. + */ + public static BaseEncoding base64Url() { + return BASE64_URL; + } + + private static byte[] extract(byte[] result, int length) { + if (length == result.length) { return result; - } - - @Override - public BaseEncoding lowerCase() { - BaseEncoding result = lowerCase; - if (result == null) { - Alphabet lower = alphabet.lowerCase(); - result = lowerCase = (lower == alphabet) ? this : new StandardBaseEncoding(lower, paddingChar); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder("BaseEncoding."); - builder.append(alphabet.toString()); - if (8 % alphabet.bitsPerChar != 0) { - if (paddingChar == null) { - builder.append(".omitPadding()"); - } else { - builder.append(".withPadChar(").append(paddingChar).append(')'); - } - } - return builder.toString(); + } else { + byte[] trunc = new byte[length]; + System.arraycopy(result, 0, trunc, 0, length); + return trunc; } } @@ -804,6 +694,11 @@ public abstract class BaseEncoding { checkNotNull(delegate); checkNotNull(toIgnore); return new CharInput() { + @Override + public void close() throws IOException { + delegate.close(); + } + @Override public int read() throws IOException { int readChar; @@ -812,14 +707,11 @@ public abstract class BaseEncoding { } while (readChar != -1 && toIgnore.matches((char) readChar)); return readChar; } - - @Override - public void close() throws IOException { - delegate.close(); - } }; } + // Modified encoding generators + static CharOutput separatingOutput(final CharOutput delegate, final String separator, final int afterEveryChars) { checkNotNull(delegate); checkNotNull(separator); @@ -827,6 +719,16 @@ public abstract class BaseEncoding { return new CharOutput() { int charsUntilSeparator = afterEveryChars; + @Override + public void close() throws IOException { + delegate.close(); + } + + @Override + public void flush() throws IOException { + delegate.flush(); + } + @Override public void write(char c) throws IOException { if (charsUntilSeparator == 0) { @@ -838,88 +740,190 @@ public abstract class BaseEncoding { delegate.write(c); charsUntilSeparator--; } + }; + } - @Override - public void flush() throws IOException { - delegate.flush(); + BaseEncoding() { + } + + /** + * Decodes the specified character sequence, and returns the resulting + * {@code byte[]}. This is the inverse operation to {@link #encode(byte[])}. + * + * @throws IllegalArgumentException if the input is not a valid encoded string + * according to this encoding. + */ + public final byte[] decode(CharSequence chars) { + try { + return decodeChecked(chars); + } catch (DecodingException badInput) { + throw new IllegalArgumentException(badInput); + } + } + + /** + * Decodes the specified character sequence, and returns the resulting + * {@code byte[]}. This is the inverse operation to {@link #encode(byte[])}. + * + * @throws DecodingException if the input is not a valid encoded string + * according to this encoding. + */ + final byte[] decodeChecked(CharSequence chars) throws DecodingException { + chars = padding().trimTrailingFrom(chars); + ByteInput decodedInput = decodingStream(asCharInput(chars)); + byte[] tmp = new byte[maxDecodedSize(chars.length())]; + int index = 0; + try { + for (int i = decodedInput.read(); i != -1; i = decodedInput.read()) { + tmp[index++] = (byte) i; } + } catch (DecodingException badInput) { + throw badInput; + } catch (IOException impossible) { + throw new AssertionError(impossible); + } + return extract(tmp, index); + } + /** + * Returns a {@code ByteSource} that reads base-encoded bytes from the specified + * {@code CharSource}. + */ + @GwtIncompatible("ByteSource,CharSource") + public final ByteSource decodingSource(final CharSource encodedSource) { + checkNotNull(encodedSource); + return new ByteSource() { @Override - public void close() throws IOException { - delegate.close(); + public InputStream openStream() throws IOException { + return decodingStream(encodedSource.openStream()); } }; } - static final class SeparatedBaseEncoding extends BaseEncoding { - private final BaseEncoding delegate; - private final String separator; - private final int afterEveryChars; - private final CharMatcher separatorChars; + abstract ByteInput decodingStream(CharInput charInput); - SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) { - this.delegate = checkNotNull(delegate); - this.separator = checkNotNull(separator); - this.afterEveryChars = afterEveryChars; - checkArgument(afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars); - this.separatorChars = CharMatcher.anyOf(separator).precomputed(); - } - - @Override - CharMatcher padding() { - return delegate.padding(); - } - - @Override - int maxEncodedSize(int bytes) { - int unseparatedSize = delegate.maxEncodedSize(bytes); - return unseparatedSize - + separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR); - } - - @Override - ByteOutput encodingStream(final CharOutput output) { - return delegate.encodingStream(separatingOutput(output, separator, afterEveryChars)); - } - - @Override - int maxDecodedSize(int chars) { - return delegate.maxDecodedSize(chars); - } - - @Override - ByteInput decodingStream(final CharInput input) { - return delegate.decodingStream(ignoringInput(input, separatorChars)); - } - - @Override - public BaseEncoding omitPadding() { - return delegate.omitPadding().withSeparator(separator, afterEveryChars); - } - - @Override - public BaseEncoding withPadChar(char padChar) { - return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars); - } - - @Override - public BaseEncoding withSeparator(String separator, int afterEveryChars) { - throw new UnsupportedOperationException("Already have a separator"); - } - - @Override - public BaseEncoding upperCase() { - return delegate.upperCase().withSeparator(separator, afterEveryChars); - } - - @Override - public BaseEncoding lowerCase() { - return delegate.lowerCase().withSeparator(separator, afterEveryChars); - } - - @Override - public String toString() { - return delegate.toString() + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")"; - } + /** + * Returns an {@code InputStream} that decodes base-encoded input from the + * specified {@code Reader}. The returned stream throws a + * {@link DecodingException} upon decoding-specific errors. + */ + @GwtIncompatible("Reader,InputStream") + public final InputStream decodingStream(Reader reader) { + return asInputStream(decodingStream(asCharInput(reader))); } + + /** + * Encodes the specified byte array, and returns the encoded {@code String}. + */ + public String encode(byte[] bytes) { + return encode(checkNotNull(bytes), 0, bytes.length); + } + + /** + * Encodes the specified range of the specified byte array, and returns the + * encoded {@code String}. + */ + public final String encode(byte[] bytes, int off, int len) { + checkNotNull(bytes); + checkPositionIndexes(off, off + len, bytes.length); + CharOutput result = stringBuilderOutput(maxEncodedSize(len)); + ByteOutput byteOutput = encodingStream(result); + try { + for (int i = 0; i < len; i++) { + byteOutput.write(bytes[off + i]); + } + byteOutput.close(); + } catch (IOException impossible) { + throw new AssertionError("impossible"); + } + return result.toString(); + } + + /** + * Returns a {@code ByteSink} that writes base-encoded bytes to the specified + * {@code CharSink}. + */ + @GwtIncompatible("ByteSink,CharSink") + public final ByteSink encodingSink(final CharSink encodedSink) { + checkNotNull(encodedSink); + return new ByteSink() { + @Override + public OutputStream openStream() throws IOException { + return encodingStream(encodedSink.openStream()); + } + }; + } + + abstract ByteOutput encodingStream(CharOutput charOutput); + + /** + * Returns an {@code OutputStream} that encodes bytes using this encoding into + * the specified {@code Writer}. When the returned {@code OutputStream} is + * closed, so is the backing {@code Writer}. + */ + @GwtIncompatible("Writer,OutputStream") + public final OutputStream encodingStream(Writer writer) { + return asOutputStream(encodingStream(asCharOutput(writer))); + } + + /** + * Returns an encoding that behaves equivalently to this encoding, but encodes + * and decodes with lowercase letters. Padding and separator characters remain + * in their original case. + * + * @throws IllegalStateException if the alphabet used by this encoding contains + * mixed upper- and lower-case characters + */ + @CheckReturnValue + public abstract BaseEncoding lowerCase(); + + abstract int maxDecodedSize(int chars); + + abstract int maxEncodedSize(int bytes); + + /** + * Returns an encoding that behaves equivalently to this encoding, but omits any + * padding characters as specified by + * RFC 4648 section + * 3.2, Padding of Encoded Data. + */ + @CheckReturnValue + public abstract BaseEncoding omitPadding(); + + abstract CharMatcher padding(); + + /** + * Returns an encoding that behaves equivalently to this encoding, but encodes + * and decodes with uppercase letters. Padding and separator characters remain + * in their original case. + * + * @throws IllegalStateException if the alphabet used by this encoding contains + * mixed upper- and lower-case characters + */ + @CheckReturnValue + public abstract BaseEncoding upperCase(); + + /** + * Returns an encoding that behaves equivalently to this encoding, but uses an + * alternate character for padding. + * + * @throws IllegalArgumentException if this padding character is already used in + * the alphabet or a separator + */ + @CheckReturnValue + public abstract BaseEncoding withPadChar(char padChar); + + /** + * Returns an encoding that behaves equivalently to this encoding, but adds a + * separator string after every {@code n} characters. Any occurrences of any + * characters that occur in the separator are skipped over in decoding. + * + * @throws IllegalArgumentException if any alphabet or padding characters + * appear in the separator string, or if + * {@code n <= 0} + * @throws UnsupportedOperationException if this encoding already uses a + * separator + */ + @CheckReturnValue + public abstract BaseEncoding withSeparator(String separator, int n); } diff --git a/src/main/java/com/google/common/io/ByteArrayDataInput.java b/src/main/java/com/google/common/io/ByteArrayDataInput.java index f8dbb35a..ef227b6f 100644 --- a/src/main/java/com/google/common/io/ByteArrayDataInput.java +++ b/src/main/java/com/google/common/io/ByteArrayDataInput.java @@ -34,48 +34,48 @@ import java.io.IOException; * @since 1.0 */ public interface ByteArrayDataInput extends DataInput { - @Override - void readFully(byte b[]); - - @Override - void readFully(byte b[], int off, int len); - - @Override - int skipBytes(int n); - @Override boolean readBoolean(); @Override byte readByte(); - @Override - int readUnsignedByte(); - - @Override - short readShort(); - - @Override - int readUnsignedShort(); - @Override char readChar(); - @Override - int readInt(); - - @Override - long readLong(); - - @Override - float readFloat(); - @Override double readDouble(); + @Override + float readFloat(); + + @Override + void readFully(byte b[]); + + @Override + void readFully(byte b[], int off, int len); + + @Override + int readInt(); + @Override String readLine(); + @Override + long readLong(); + + @Override + short readShort(); + + @Override + int readUnsignedByte(); + + @Override + int readUnsignedShort(); + @Override String readUTF(); + + @Override + int skipBytes(int n); } diff --git a/src/main/java/com/google/common/io/ByteArrayDataOutput.java b/src/main/java/com/google/common/io/ByteArrayDataOutput.java index c136c904..e88552d1 100644 --- a/src/main/java/com/google/common/io/ByteArrayDataOutput.java +++ b/src/main/java/com/google/common/io/ByteArrayDataOutput.java @@ -27,8 +27,11 @@ import java.io.IOException; * @since 1.0 */ public interface ByteArrayDataOutput extends DataOutput { - @Override - void write(int b); + /** + * Returns the contents that have been written to this instance, as a byte + * array. + */ + byte[] toByteArray(); @Override void write(byte b[]); @@ -36,36 +39,15 @@ public interface ByteArrayDataOutput extends DataOutput { @Override void write(byte b[], int off, int len); + @Override + void write(int b); + @Override void writeBoolean(boolean v); @Override void writeByte(int v); - @Override - void writeShort(int v); - - @Override - void writeChar(int v); - - @Override - void writeInt(int v); - - @Override - void writeLong(long v); - - @Override - void writeFloat(float v); - - @Override - void writeDouble(double v); - - @Override - void writeChars(String s); - - @Override - void writeUTF(String s); - /** * @deprecated This method is dangerous as it discards the high byte of every * character. For UTF-8, use @@ -75,9 +57,27 @@ public interface ByteArrayDataOutput extends DataOutput { @Override void writeBytes(String s); - /** - * Returns the contents that have been written to this instance, as a byte - * array. - */ - byte[] toByteArray(); + @Override + void writeChar(int v); + + @Override + void writeChars(String s); + + @Override + void writeDouble(double v); + + @Override + void writeFloat(float v); + + @Override + void writeInt(int v); + + @Override + void writeLong(long v); + + @Override + void writeShort(int v); + + @Override + void writeUTF(String s); } diff --git a/src/main/java/com/google/common/io/ByteProcessor.java b/src/main/java/com/google/common/io/ByteProcessor.java index f1a7ed6c..f92383d2 100644 --- a/src/main/java/com/google/common/io/ByteProcessor.java +++ b/src/main/java/com/google/common/io/ByteProcessor.java @@ -32,6 +32,9 @@ import com.google.common.annotations.Beta; */ @Beta public interface ByteProcessor { + /** Return the result of processing all the bytes. */ + T getResult(); + /** * This method will be called for each chunk of bytes in an input stream. The * implementation should process the bytes from {@code buf[off]} through @@ -43,7 +46,4 @@ public interface ByteProcessor { * @return true to continue processing, false to stop */ boolean processBytes(byte[] buf, int off, int len) throws IOException; - - /** Return the result of processing all the bytes. */ - T getResult(); } diff --git a/src/main/java/com/google/common/io/ByteSink.java b/src/main/java/com/google/common/io/ByteSink.java index 1e0d092e..0c7aea72 100644 --- a/src/main/java/com/google/common/io/ByteSink.java +++ b/src/main/java/com/google/common/io/ByteSink.java @@ -49,6 +49,29 @@ import java.nio.charset.Charset; */ public abstract class ByteSink implements OutputSupplier { + /** + * A char sink that encodes written characters with a charset and writes + * resulting bytes to this byte sink. + */ + private final class AsCharSink extends CharSink { + + private final Charset charset; + + private AsCharSink(Charset charset) { + this.charset = checkNotNull(charset); + } + + @Override + public Writer openStream() throws IOException { + return new OutputStreamWriter(ByteSink.this.openStream(), charset); + } + + @Override + public String toString() { + return ByteSink.this.toString() + ".asCharSink(" + charset + ")"; + } + } + /** * Constructor for use by subclasses. */ @@ -64,18 +87,6 @@ public abstract class ByteSink implements OutputSupplier { return new AsCharSink(charset); } - /** - * Opens a new {@link OutputStream} for writing to this sink. This method should - * return a new, independent stream each time it is called. - * - *

          - * The caller is responsible for ensuring that the returned stream is closed. - * - * @throws IOException if an I/O error occurs in the process of opening the - * stream - */ - public abstract OutputStream openStream() throws IOException; - /** * This method is a temporary method provided for easing migration from * suppliers to sources and sinks. @@ -112,6 +123,18 @@ public abstract class ByteSink implements OutputSupplier { return (out instanceof BufferedOutputStream) ? (BufferedOutputStream) out : new BufferedOutputStream(out); } + /** + * Opens a new {@link OutputStream} for writing to this sink. This method should + * return a new, independent stream each time it is called. + * + *

          + * The caller is responsible for ensuring that the returned stream is closed. + * + * @throws IOException if an I/O error occurs in the process of opening the + * stream + */ + public abstract OutputStream openStream() throws IOException; + /** * Writes all the given bytes to this sink. * @@ -154,27 +177,4 @@ public abstract class ByteSink implements OutputSupplier { closer.close(); } } - - /** - * A char sink that encodes written characters with a charset and writes - * resulting bytes to this byte sink. - */ - private final class AsCharSink extends CharSink { - - private final Charset charset; - - private AsCharSink(Charset charset) { - this.charset = checkNotNull(charset); - } - - @Override - public Writer openStream() throws IOException { - return new OutputStreamWriter(ByteSink.this.openStream(), charset); - } - - @Override - public String toString() { - return ByteSink.this.toString() + ".asCharSink(" + charset + ")"; - } - } } diff --git a/src/main/java/com/google/common/io/ByteSource.java b/src/main/java/com/google/common/io/ByteSource.java index f31491c0..ab175fe0 100644 --- a/src/main/java/com/google/common/io/ByteSource.java +++ b/src/main/java/com/google/common/io/ByteSource.java @@ -62,8 +62,295 @@ import net.lax1dude.eaglercraft.v1_8.EaglerInputStream; */ public abstract class ByteSource implements InputSupplier { + /** + * A char source that reads bytes from this source and decodes them as + * characters using a charset. + */ + private final class AsCharSource extends CharSource { + + private final Charset charset; + + private AsCharSource(Charset charset) { + this.charset = checkNotNull(charset); + } + + @Override + public Reader openStream() throws IOException { + return new InputStreamReader(ByteSource.this.openStream(), charset); + } + + @Override + public String toString() { + return ByteSource.this.toString() + ".asCharSource(" + charset + ")"; + } + } + + private static class ByteArrayByteSource extends ByteSource { + + protected final byte[] bytes; + + protected ByteArrayByteSource(byte[] bytes) { + this.bytes = checkNotNull(bytes); + } + + @Override + public long copyTo(OutputStream output) throws IOException { + output.write(bytes); + return bytes.length; + } + + @Override + public HashCode hash(HashFunction hashFunction) throws IOException { + return hashFunction.hashBytes(bytes); + } + + @Override + public boolean isEmpty() { + return bytes.length == 0; + } + + @Override + public InputStream openBufferedStream() throws IOException { + return openStream(); + } + + @Override + public InputStream openStream() { + return new EaglerInputStream(bytes); + } + + @Override + public byte[] read() { + return bytes.clone(); + } + + @Override + public T read(ByteProcessor processor) throws IOException { + processor.processBytes(bytes, 0, bytes.length); + return processor.getResult(); + } + + @Override + public long size() { + return bytes.length; + } + + // TODO(user): Possibly override slice() + + @Override + public String toString() { + return "ByteSource.wrap(" + Ascii.truncate(BaseEncoding.base16().encode(bytes), 30, "...") + ")"; + } + } + + private static final class ConcatenatedByteSource extends ByteSource { + + private final Iterable sources; + + ConcatenatedByteSource(Iterable sources) { + this.sources = checkNotNull(sources); + } + + @Override + public boolean isEmpty() throws IOException { + for (ByteSource source : sources) { + if (!source.isEmpty()) { + return false; + } + } + return true; + } + + @Override + public InputStream openStream() throws IOException { + return new MultiInputStream(sources.iterator()); + } + + @Override + public long size() throws IOException { + long result = 0L; + for (ByteSource source : sources) { + result += source.size(); + } + return result; + } + + @Override + public String toString() { + return "ByteSource.concat(" + sources + ")"; + } + } + + private static final class EmptyByteSource extends ByteArrayByteSource { + + private static final EmptyByteSource INSTANCE = new EmptyByteSource(); + + private EmptyByteSource() { + super(new byte[0]); + } + + @Override + public CharSource asCharSource(Charset charset) { + checkNotNull(charset); + return CharSource.empty(); + } + + @Override + public byte[] read() { + return bytes; // length is 0, no need to clone + } + + @Override + public String toString() { + return "ByteSource.empty()"; + } + } + + /** + * A view of a subsection of the containing byte source. + */ + private final class SlicedByteSource extends ByteSource { + + private final long offset; + private final long length; + + private SlicedByteSource(long offset, long length) { + checkArgument(offset >= 0, "offset (%s) may not be negative", offset); + checkArgument(length >= 0, "length (%s) may not be negative", length); + this.offset = offset; + this.length = length; + } + + @Override + public boolean isEmpty() throws IOException { + return length == 0 || super.isEmpty(); + } + + @Override + public InputStream openBufferedStream() throws IOException { + return sliceStream(ByteSource.this.openBufferedStream()); + } + + @Override + public InputStream openStream() throws IOException { + return sliceStream(ByteSource.this.openStream()); + } + + @Override + public ByteSource slice(long offset, long length) { + checkArgument(offset >= 0, "offset (%s) may not be negative", offset); + checkArgument(length >= 0, "length (%s) may not be negative", length); + long maxLength = this.length - offset; + return ByteSource.this.slice(this.offset + offset, Math.min(length, maxLength)); + } + + private InputStream sliceStream(InputStream in) throws IOException { + if (offset > 0) { + try { + ByteStreams.skipFully(in, offset); + } catch (Throwable e) { + Closer closer = Closer.create(); + closer.register(in); + try { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + } + return ByteStreams.limit(in, length); + } + + @Override + public String toString() { + return ByteSource.this.toString() + ".slice(" + offset + ", " + length + ")"; + } + } + private static final int BUF_SIZE = 0x1000; // 4K + private static final byte[] countBuffer = new byte[BUF_SIZE]; + + /** + * Concatenates multiple {@link ByteSource} instances into a single source. + * Streams returned from the source will contain the concatenated data from the + * streams of the underlying sources. + * + *

          + * Only one underlying stream will be open at a time. Closing the concatenated + * stream will close the open underlying stream. + * + * @param sources the sources to concatenate + * @return a {@code ByteSource} containing the concatenated data + * @throws NullPointerException if any of {@code sources} is {@code null} + * @since 15.0 + */ + public static ByteSource concat(ByteSource... sources) { + return concat(ImmutableList.copyOf(sources)); + } + + /** + * Concatenates multiple {@link ByteSource} instances into a single source. + * Streams returned from the source will contain the concatenated data from the + * streams of the underlying sources. + * + *

          + * Only one underlying stream will be open at a time. Closing the concatenated + * stream will close the open underlying stream. + * + * @param sources the sources to concatenate + * @return a {@code ByteSource} containing the concatenated data + * @since 15.0 + */ + public static ByteSource concat(Iterable sources) { + return new ConcatenatedByteSource(sources); + } + + /** + * Concatenates multiple {@link ByteSource} instances into a single source. + * Streams returned from the source will contain the concatenated data from the + * streams of the underlying sources. + * + *

          + * Only one underlying stream will be open at a time. Closing the concatenated + * stream will close the open underlying stream. + * + *

          + * Note: The input {@code Iterator} will be copied to an {@code ImmutableList} + * when this method is called. This will fail if the iterator is infinite and + * may cause problems if the iterator eagerly fetches data for each source when + * iterated (rather than producing sources that only load data through their + * streams). Prefer using the {@link #concat(Iterable)} overload if possible. + * + * @param sources the sources to concatenate + * @return a {@code ByteSource} containing the concatenated data + * @throws NullPointerException if any of {@code sources} is {@code null} + * @since 15.0 + */ + public static ByteSource concat(Iterator sources) { + return concat(ImmutableList.copyOf(sources)); + } + + /** + * Returns an immutable {@link ByteSource} that contains no bytes. + * + * @since 15.0 + */ + public static ByteSource empty() { + return EmptyByteSource.INSTANCE; + } + + /** + * Returns a view of the given byte array as a {@link ByteSource}. To view only + * a specific range in the array, use + * {@code ByteSource.wrap(b).slice(offset, length)}. + * + * @since 15.0 (since 14.0 as {@code ByteStreams.asByteSource(byte[])}). + */ + public static ByteSource wrap(byte[] b) { + return new ByteArrayByteSource(b); + } + /** * Constructor for use by subclasses. */ @@ -79,16 +366,114 @@ public abstract class ByteSource implements InputSupplier { } /** - * Opens a new {@link InputStream} for reading from this source. This method - * should return a new, independent stream each time it is called. + * Checks that the contents of this byte source are equal to the contents of the + * given byte source. * - *

          - * The caller is responsible for ensuring that the returned stream is closed. - * - * @throws IOException if an I/O error occurs in the process of opening the - * stream + * @throws IOException if an I/O error occurs in the process of reading from + * this source or {@code other} */ - public abstract InputStream openStream() throws IOException; + public boolean contentEquals(ByteSource other) throws IOException { + checkNotNull(other); + + byte[] buf1 = new byte[BUF_SIZE]; + byte[] buf2 = new byte[BUF_SIZE]; + + Closer closer = Closer.create(); + try { + InputStream in1 = closer.register(openStream()); + InputStream in2 = closer.register(other.openStream()); + while (true) { + int read1 = ByteStreams.read(in1, buf1, 0, BUF_SIZE); + int read2 = ByteStreams.read(in2, buf2, 0, BUF_SIZE); + if (read1 != read2 || !Arrays.equals(buf1, buf2)) { + return false; + } else if (read1 != BUF_SIZE) { + return true; + } + } + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + + /** + * Copies the contents of this byte source to the given {@code ByteSink}. + * + * @throws IOException if an I/O error occurs in the process of reading from + * this source or writing to {@code sink} + */ + public long copyTo(ByteSink sink) throws IOException { + checkNotNull(sink); + + Closer closer = Closer.create(); + try { + InputStream in = closer.register(openStream()); + OutputStream out = closer.register(sink.openStream()); + return ByteStreams.copy(in, out); + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + + /** + * Copies the contents of this byte source to the given {@code OutputStream}. + * Does not close {@code output}. + * + * @throws IOException if an I/O error occurs in the process of reading from + * this source or writing to {@code output} + */ + public long copyTo(OutputStream output) throws IOException { + checkNotNull(output); + + Closer closer = Closer.create(); + try { + InputStream in = closer.register(openStream()); + return ByteStreams.copy(in, output); + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + + private long countByReading(InputStream in) throws IOException { + long count = 0; + long read; + while ((read = in.read(countBuffer)) != -1) { + count += read; + } + return count; + } + + /** + * Counts the bytes in the given input stream using skip if possible. Returns + * SKIP_FAILED if the first call to skip threw, in which case skip may just not + * be supported. + */ + private long countBySkipping(InputStream in) throws IOException { + long count = 0; + while (true) { + // don't try to skip more than available() + // things may work really wrong with FileInputStream otherwise + long skipped = in.skip(Math.min(in.available(), Integer.MAX_VALUE)); + if (skipped <= 0) { + if (in.read() == -1) { + return count; + } else if (count == 0 && in.available() == 0) { + // if available is still zero after reading a single byte, it + // will probably always be zero, so we should countByReading + throw new IOException(); + } + count++; + } else { + count += skipped; + } + } + } /** * This method is a temporary method provided for easing migration from @@ -106,6 +491,37 @@ public abstract class ByteSource implements InputSupplier { return openStream(); } + /** + * Hashes the contents of this byte source using the given hash function. + * + * @throws IOException if an I/O error occurs in the process of reading from + * this source + */ + public HashCode hash(HashFunction hashFunction) throws IOException { + Hasher hasher = hashFunction.newHasher(); + copyTo(Funnels.asOutputStream(hasher)); + return hasher.hash(); + } + + /** + * Returns whether the source has zero bytes. The default implementation is to + * open a stream and check for EOF. + * + * @throws IOException if an I/O error occurs + * @since 15.0 + */ + public boolean isEmpty() throws IOException { + Closer closer = Closer.create(); + try { + InputStream in = closer.register(openStream()); + return in.read() == -1; + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + /** * Opens a new buffered {@link InputStream} for reading from this source. The * returned stream is not required to be a {@link BufferedInputStream} in order @@ -127,28 +543,53 @@ public abstract class ByteSource implements InputSupplier { } /** - * Returns a view of a slice of this byte source that is at most {@code length} - * bytes long starting at the given {@code offset}. + * Opens a new {@link InputStream} for reading from this source. This method + * should return a new, independent stream each time it is called. * - * @throws IllegalArgumentException if {@code offset} or {@code length} is - * negative + *

          + * The caller is responsible for ensuring that the returned stream is closed. + * + * @throws IOException if an I/O error occurs in the process of opening the + * stream */ - public ByteSource slice(long offset, long length) { - return new SlicedByteSource(offset, length); - } + public abstract InputStream openStream() throws IOException; /** - * Returns whether the source has zero bytes. The default implementation is to - * open a stream and check for EOF. + * Reads the full contents of this byte source as a byte array. * - * @throws IOException if an I/O error occurs - * @since 15.0 + * @throws IOException if an I/O error occurs in the process of reading from + * this source */ - public boolean isEmpty() throws IOException { + public byte[] read() throws IOException { Closer closer = Closer.create(); try { InputStream in = closer.register(openStream()); - return in.read() == -1; + return ByteStreams.toByteArray(in); + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + + /** + * Reads the contents of this byte source using the given {@code processor} to + * process bytes as they are read. Stops when all bytes have been read or the + * consumer returns {@code false}. Returns the result produced by the processor. + * + * @throws IOException if an I/O error occurs in the process of reading from + * this source or if {@code processor} throws an + * {@code IOException} + * @since 16.0 + */ + @Beta + public T read(ByteProcessor processor) throws IOException { + checkNotNull(processor); + + Closer closer = Closer.create(); + try { + InputStream in = closer.register(openStream()); + return ByteStreams.readBytes(in, processor); } catch (Throwable e) { throw closer.rethrow(e); } finally { @@ -199,454 +640,13 @@ public abstract class ByteSource implements InputSupplier { } /** - * Counts the bytes in the given input stream using skip if possible. Returns - * SKIP_FAILED if the first call to skip threw, in which case skip may just not - * be supported. + * Returns a view of a slice of this byte source that is at most {@code length} + * bytes long starting at the given {@code offset}. + * + * @throws IllegalArgumentException if {@code offset} or {@code length} is + * negative */ - private long countBySkipping(InputStream in) throws IOException { - long count = 0; - while (true) { - // don't try to skip more than available() - // things may work really wrong with FileInputStream otherwise - long skipped = in.skip(Math.min(in.available(), Integer.MAX_VALUE)); - if (skipped <= 0) { - if (in.read() == -1) { - return count; - } else if (count == 0 && in.available() == 0) { - // if available is still zero after reading a single byte, it - // will probably always be zero, so we should countByReading - throw new IOException(); - } - count++; - } else { - count += skipped; - } - } - } - - private static final byte[] countBuffer = new byte[BUF_SIZE]; - - private long countByReading(InputStream in) throws IOException { - long count = 0; - long read; - while ((read = in.read(countBuffer)) != -1) { - count += read; - } - return count; - } - - /** - * Copies the contents of this byte source to the given {@code OutputStream}. - * Does not close {@code output}. - * - * @throws IOException if an I/O error occurs in the process of reading from - * this source or writing to {@code output} - */ - public long copyTo(OutputStream output) throws IOException { - checkNotNull(output); - - Closer closer = Closer.create(); - try { - InputStream in = closer.register(openStream()); - return ByteStreams.copy(in, output); - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Copies the contents of this byte source to the given {@code ByteSink}. - * - * @throws IOException if an I/O error occurs in the process of reading from - * this source or writing to {@code sink} - */ - public long copyTo(ByteSink sink) throws IOException { - checkNotNull(sink); - - Closer closer = Closer.create(); - try { - InputStream in = closer.register(openStream()); - OutputStream out = closer.register(sink.openStream()); - return ByteStreams.copy(in, out); - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Reads the full contents of this byte source as a byte array. - * - * @throws IOException if an I/O error occurs in the process of reading from - * this source - */ - public byte[] read() throws IOException { - Closer closer = Closer.create(); - try { - InputStream in = closer.register(openStream()); - return ByteStreams.toByteArray(in); - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Reads the contents of this byte source using the given {@code processor} to - * process bytes as they are read. Stops when all bytes have been read or the - * consumer returns {@code false}. Returns the result produced by the processor. - * - * @throws IOException if an I/O error occurs in the process of reading from - * this source or if {@code processor} throws an - * {@code IOException} - * @since 16.0 - */ - @Beta - public T read(ByteProcessor processor) throws IOException { - checkNotNull(processor); - - Closer closer = Closer.create(); - try { - InputStream in = closer.register(openStream()); - return ByteStreams.readBytes(in, processor); - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Hashes the contents of this byte source using the given hash function. - * - * @throws IOException if an I/O error occurs in the process of reading from - * this source - */ - public HashCode hash(HashFunction hashFunction) throws IOException { - Hasher hasher = hashFunction.newHasher(); - copyTo(Funnels.asOutputStream(hasher)); - return hasher.hash(); - } - - /** - * Checks that the contents of this byte source are equal to the contents of the - * given byte source. - * - * @throws IOException if an I/O error occurs in the process of reading from - * this source or {@code other} - */ - public boolean contentEquals(ByteSource other) throws IOException { - checkNotNull(other); - - byte[] buf1 = new byte[BUF_SIZE]; - byte[] buf2 = new byte[BUF_SIZE]; - - Closer closer = Closer.create(); - try { - InputStream in1 = closer.register(openStream()); - InputStream in2 = closer.register(other.openStream()); - while (true) { - int read1 = ByteStreams.read(in1, buf1, 0, BUF_SIZE); - int read2 = ByteStreams.read(in2, buf2, 0, BUF_SIZE); - if (read1 != read2 || !Arrays.equals(buf1, buf2)) { - return false; - } else if (read1 != BUF_SIZE) { - return true; - } - } - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Concatenates multiple {@link ByteSource} instances into a single source. - * Streams returned from the source will contain the concatenated data from the - * streams of the underlying sources. - * - *

          - * Only one underlying stream will be open at a time. Closing the concatenated - * stream will close the open underlying stream. - * - * @param sources the sources to concatenate - * @return a {@code ByteSource} containing the concatenated data - * @since 15.0 - */ - public static ByteSource concat(Iterable sources) { - return new ConcatenatedByteSource(sources); - } - - /** - * Concatenates multiple {@link ByteSource} instances into a single source. - * Streams returned from the source will contain the concatenated data from the - * streams of the underlying sources. - * - *

          - * Only one underlying stream will be open at a time. Closing the concatenated - * stream will close the open underlying stream. - * - *

          - * Note: The input {@code Iterator} will be copied to an {@code ImmutableList} - * when this method is called. This will fail if the iterator is infinite and - * may cause problems if the iterator eagerly fetches data for each source when - * iterated (rather than producing sources that only load data through their - * streams). Prefer using the {@link #concat(Iterable)} overload if possible. - * - * @param sources the sources to concatenate - * @return a {@code ByteSource} containing the concatenated data - * @throws NullPointerException if any of {@code sources} is {@code null} - * @since 15.0 - */ - public static ByteSource concat(Iterator sources) { - return concat(ImmutableList.copyOf(sources)); - } - - /** - * Concatenates multiple {@link ByteSource} instances into a single source. - * Streams returned from the source will contain the concatenated data from the - * streams of the underlying sources. - * - *

          - * Only one underlying stream will be open at a time. Closing the concatenated - * stream will close the open underlying stream. - * - * @param sources the sources to concatenate - * @return a {@code ByteSource} containing the concatenated data - * @throws NullPointerException if any of {@code sources} is {@code null} - * @since 15.0 - */ - public static ByteSource concat(ByteSource... sources) { - return concat(ImmutableList.copyOf(sources)); - } - - /** - * Returns a view of the given byte array as a {@link ByteSource}. To view only - * a specific range in the array, use - * {@code ByteSource.wrap(b).slice(offset, length)}. - * - * @since 15.0 (since 14.0 as {@code ByteStreams.asByteSource(byte[])}). - */ - public static ByteSource wrap(byte[] b) { - return new ByteArrayByteSource(b); - } - - /** - * Returns an immutable {@link ByteSource} that contains no bytes. - * - * @since 15.0 - */ - public static ByteSource empty() { - return EmptyByteSource.INSTANCE; - } - - /** - * A char source that reads bytes from this source and decodes them as - * characters using a charset. - */ - private final class AsCharSource extends CharSource { - - private final Charset charset; - - private AsCharSource(Charset charset) { - this.charset = checkNotNull(charset); - } - - @Override - public Reader openStream() throws IOException { - return new InputStreamReader(ByteSource.this.openStream(), charset); - } - - @Override - public String toString() { - return ByteSource.this.toString() + ".asCharSource(" + charset + ")"; - } - } - - /** - * A view of a subsection of the containing byte source. - */ - private final class SlicedByteSource extends ByteSource { - - private final long offset; - private final long length; - - private SlicedByteSource(long offset, long length) { - checkArgument(offset >= 0, "offset (%s) may not be negative", offset); - checkArgument(length >= 0, "length (%s) may not be negative", length); - this.offset = offset; - this.length = length; - } - - @Override - public InputStream openStream() throws IOException { - return sliceStream(ByteSource.this.openStream()); - } - - @Override - public InputStream openBufferedStream() throws IOException { - return sliceStream(ByteSource.this.openBufferedStream()); - } - - private InputStream sliceStream(InputStream in) throws IOException { - if (offset > 0) { - try { - ByteStreams.skipFully(in, offset); - } catch (Throwable e) { - Closer closer = Closer.create(); - closer.register(in); - try { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - } - return ByteStreams.limit(in, length); - } - - @Override - public ByteSource slice(long offset, long length) { - checkArgument(offset >= 0, "offset (%s) may not be negative", offset); - checkArgument(length >= 0, "length (%s) may not be negative", length); - long maxLength = this.length - offset; - return ByteSource.this.slice(this.offset + offset, Math.min(length, maxLength)); - } - - @Override - public boolean isEmpty() throws IOException { - return length == 0 || super.isEmpty(); - } - - @Override - public String toString() { - return ByteSource.this.toString() + ".slice(" + offset + ", " + length + ")"; - } - } - - private static class ByteArrayByteSource extends ByteSource { - - protected final byte[] bytes; - - protected ByteArrayByteSource(byte[] bytes) { - this.bytes = checkNotNull(bytes); - } - - @Override - public InputStream openStream() { - return new EaglerInputStream(bytes); - } - - @Override - public InputStream openBufferedStream() throws IOException { - return openStream(); - } - - @Override - public boolean isEmpty() { - return bytes.length == 0; - } - - @Override - public long size() { - return bytes.length; - } - - @Override - public byte[] read() { - return bytes.clone(); - } - - @Override - public long copyTo(OutputStream output) throws IOException { - output.write(bytes); - return bytes.length; - } - - @Override - public T read(ByteProcessor processor) throws IOException { - processor.processBytes(bytes, 0, bytes.length); - return processor.getResult(); - } - - @Override - public HashCode hash(HashFunction hashFunction) throws IOException { - return hashFunction.hashBytes(bytes); - } - - // TODO(user): Possibly override slice() - - @Override - public String toString() { - return "ByteSource.wrap(" + Ascii.truncate(BaseEncoding.base16().encode(bytes), 30, "...") + ")"; - } - } - - private static final class EmptyByteSource extends ByteArrayByteSource { - - private static final EmptyByteSource INSTANCE = new EmptyByteSource(); - - private EmptyByteSource() { - super(new byte[0]); - } - - @Override - public CharSource asCharSource(Charset charset) { - checkNotNull(charset); - return CharSource.empty(); - } - - @Override - public byte[] read() { - return bytes; // length is 0, no need to clone - } - - @Override - public String toString() { - return "ByteSource.empty()"; - } - } - - private static final class ConcatenatedByteSource extends ByteSource { - - private final Iterable sources; - - ConcatenatedByteSource(Iterable sources) { - this.sources = checkNotNull(sources); - } - - @Override - public InputStream openStream() throws IOException { - return new MultiInputStream(sources.iterator()); - } - - @Override - public boolean isEmpty() throws IOException { - for (ByteSource source : sources) { - if (!source.isEmpty()) { - return false; - } - } - return true; - } - - @Override - public long size() throws IOException { - long result = 0L; - for (ByteSource source : sources) { - result += source.size(); - } - return result; - } - - @Override - public String toString() { - return "ByteSource.concat(" + sources + ")"; - } + public ByteSource slice(long offset, long length) { + return new SlicedByteSource(offset, length); } } diff --git a/src/main/java/com/google/common/io/ByteStreams.java b/src/main/java/com/google/common/io/ByteStreams.java index 011fab3e..4b10b155 100644 --- a/src/main/java/com/google/common/io/ByteStreams.java +++ b/src/main/java/com/google/common/io/ByteStreams.java @@ -20,6 +20,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; @@ -52,266 +53,6 @@ import net.lax1dude.eaglercraft.v1_8.EaglerInputStream; */ @Beta public final class ByteStreams { - private static final int BUF_SIZE = 0x1000; // 4K - - private ByteStreams() { - } - - /** - * Returns a factory that will supply instances of {@link ByteArrayInputStream} - * that read from the given byte array. - * - * @param b the input buffer - * @return the factory - * @deprecated Use {@link ByteSource#wrap(byte[])} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Deprecated - public static InputSupplier newInputStreamSupplier(byte[] b) { - return asInputSupplier(ByteSource.wrap(b)); - } - - /** - * Returns a factory that will supply instances of {@link ByteArrayInputStream} - * that read from the given byte array. - * - * @param b the input buffer - * @param off the offset in the buffer of the first byte to read - * @param len the maximum number of bytes to read from the buffer - * @return the factory - * @deprecated Use {@code ByteSource.wrap(b).slice(off, len)} instead. This - * method is scheduled for removal in Guava 18.0. - */ - @Deprecated - public static InputSupplier newInputStreamSupplier(final byte[] b, final int off, - final int len) { - return asInputSupplier(ByteSource.wrap(b).slice(off, len)); - } - - /** - * Writes a byte array to an output stream from the given supplier. - * - * @param from the bytes to write - * @param to the output supplier - * @throws IOException if an I/O error occurs - * @deprecated Use {@link ByteSink#write(byte[])} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Deprecated - public static void write(byte[] from, OutputSupplier to) throws IOException { - asByteSink(to).write(from); - } - - /** - * Opens input and output streams from the given suppliers, copies all bytes - * from the input to the output, and closes the streams. - * - * @param from the input factory - * @param to the output factory - * @return the number of bytes copied - * @throws IOException if an I/O error occurs - * @deprecated Use {@link ByteSource#copyTo(ByteSink)} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Deprecated - public static long copy(InputSupplier from, OutputSupplier to) - throws IOException { - return asByteSource(from).copyTo(asByteSink(to)); - } - - /** - * Opens an input stream from the supplier, copies all bytes from the input to - * the output, and closes the input stream. Does not close or flush the output - * stream. - * - * @param from the input factory - * @param to the output stream to write to - * @return the number of bytes copied - * @throws IOException if an I/O error occurs - * @deprecated Use {@link ByteSource#copyTo(OutputStream)} instead. This method - * is scheduled for removal in Guava 18.0. - */ - @Deprecated - public static long copy(InputSupplier from, OutputStream to) throws IOException { - return asByteSource(from).copyTo(to); - } - - /** - * Opens an output stream from the supplier, copies all bytes from the input to - * the output, and closes the output stream. Does not close or flush the input - * stream. - * - * @param from the input stream to read from - * @param to the output factory - * @return the number of bytes copied - * @throws IOException if an I/O error occurs - * @since 10.0 - * @deprecated Use {@link ByteSink#writeFrom(InputStream)} instead. This method - * is scheduled for removal in Guava 18.0. - */ - @Deprecated - public static long copy(InputStream from, OutputSupplier to) throws IOException { - return asByteSink(to).writeFrom(from); - } - - /** - * Copies all bytes from the input stream to the output stream. Does not close - * or flush either stream. - * - * @param from the input stream to read from - * @param to the output stream to write to - * @return the number of bytes copied - * @throws IOException if an I/O error occurs - */ - public static long copy(InputStream from, OutputStream to) throws IOException { - checkNotNull(from); - checkNotNull(to); - byte[] buf = new byte[BUF_SIZE]; - long total = 0; - while (true) { - int r = from.read(buf); - if (r == -1) { - break; - } - to.write(buf, 0, r); - total += r; - } - return total; - } - - /** - * Copies all bytes from the readable channel to the writable channel. Does not - * close or flush either channel. - * - * @param from the readable channel to read from - * @param to the writable channel to write to - * @return the number of bytes copied - * @throws IOException if an I/O error occurs - */ - public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { - checkNotNull(from); - checkNotNull(to); - ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); - long total = 0; - while (from.read(buf) != -1) { - buf.flip(); - while (buf.hasRemaining()) { - total += to.write(buf); - } - buf.clear(); - } - return total; - } - - /** - * Reads all bytes from an input stream into a byte array. Does not close the - * stream. - * - * @param in the input stream to read from - * @return a byte array containing all the bytes from the stream - * @throws IOException if an I/O error occurs - */ - public static byte[] toByteArray(InputStream in) throws IOException { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - copy(in, out); - return out.toByteArray(); - } - - /** - * Reads all bytes from an input stream into a byte array. The given expected - * size is used to create an initial byte array, but if the actual number of - * bytes read from the stream differs, the correct result will be returned - * anyway. - */ - static byte[] toByteArray(InputStream in, int expectedSize) throws IOException { - byte[] bytes = new byte[expectedSize]; - int remaining = expectedSize; - - while (remaining > 0) { - int off = expectedSize - remaining; - int read = in.read(bytes, off, remaining); - if (read == -1) { - // end of stream before reading expectedSize bytes - // just return the bytes read so far - return Arrays.copyOf(bytes, off); - } - remaining -= read; - } - - // bytes is now full - int b = in.read(); - if (b == -1) { - return bytes; - } - - // the stream was longer, so read the rest normally - FastByteArrayOutputStream out = new FastByteArrayOutputStream(); - out.write(b); // write the byte we read when testing for end of stream - copy(in, out); - - byte[] result = new byte[bytes.length + out.size()]; - System.arraycopy(bytes, 0, result, 0, bytes.length); - out.writeTo(result, bytes.length); - return result; - } - - /** - * BAOS that provides limited access to its internal byte array. - */ - private static final class FastByteArrayOutputStream extends ByteArrayOutputStream { - /** - * Writes the contents of the internal buffer to the given array starting at the - * given offset. Assumes the array has space to hold count bytes. - */ - void writeTo(byte[] b, int off) { - System.arraycopy(buf, 0, b, off, count); - } - } - - /** - * Returns the data from a {@link InputStream} factory as a byte array. - * - * @param supplier the factory - * @throws IOException if an I/O error occurs - * @deprecated Use {@link ByteSource#read()} instead. This method is scheduled - * for removal in Guava 18.0. - */ - @Deprecated - public static byte[] toByteArray(InputSupplier supplier) throws IOException { - return asByteSource(supplier).read(); - } - - /** - * Returns a new {@link ByteArrayDataInput} instance to read from the {@code - * bytes} array from the beginning. - */ - public static ByteArrayDataInput newDataInput(byte[] bytes) { - return newDataInput(new EaglerInputStream(bytes)); - } - - /** - * Returns a new {@link ByteArrayDataInput} instance to read from the {@code - * bytes} array, starting at the given position. - * - * @throws IndexOutOfBoundsException if {@code start} is negative or greater - * than the length of the array - */ - public static ByteArrayDataInput newDataInput(byte[] bytes, int start) { - checkPositionIndex(start, bytes.length); - return newDataInput(new EaglerInputStream(bytes, start, bytes.length - start)); - } - - /** - * Returns a new {@link ByteArrayDataInput} instance to read from the given - * {@code ByteArrayInputStream}. The given input stream is not reset before - * being read from by the returned {@code ByteArrayDataInput}. - * - * @since 17.0 - */ - public static ByteArrayDataInput newDataInput(EaglerInputStream byteArrayInputStream) { - return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream)); - } - private static class ByteArrayDataInputStream implements ByteArrayDataInput { final DataInput input; @@ -319,33 +60,6 @@ public final class ByteStreams { this.input = new DataInputStream(byteArrayInputStream); } - @Override - public void readFully(byte b[]) { - try { - input.readFully(b); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public void readFully(byte b[], int off, int len) { - try { - input.readFully(b, off, len); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public int skipBytes(int n) { - try { - return input.skipBytes(n); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - @Override public boolean readBoolean() { try { @@ -366,33 +80,6 @@ public final class ByteStreams { } } - @Override - public int readUnsignedByte() { - try { - return input.readUnsignedByte(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public short readShort() { - try { - return input.readShort(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public int readUnsignedShort() { - try { - return input.readUnsignedShort(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - @Override public char readChar() { try { @@ -402,33 +89,6 @@ public final class ByteStreams { } } - @Override - public int readInt() { - try { - return input.readInt(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public long readLong() { - try { - return input.readLong(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - - @Override - public float readFloat() { - try { - return input.readFloat(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - } - @Override public double readDouble() { try { @@ -438,6 +98,42 @@ public final class ByteStreams { } } + @Override + public float readFloat() { + try { + return input.readFloat(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public void readFully(byte b[]) { + try { + input.readFully(b); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public void readFully(byte b[], int off, int len) { + try { + input.readFully(b, off, len); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public int readInt() { + try { + return input.readInt(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + @Override public String readLine() { try { @@ -447,6 +143,42 @@ public final class ByteStreams { } } + @Override + public long readLong() { + try { + return input.readLong(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public short readShort() { + try { + return input.readShort(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public int readUnsignedByte() { + try { + return input.readUnsignedByte(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + + @Override + public int readUnsignedShort() { + try { + return input.readUnsignedShort(); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } + @Override public String readUTF() { try { @@ -455,43 +187,15 @@ public final class ByteStreams { throw new IllegalStateException(e); } } - } - /** - * Returns a new {@link ByteArrayDataOutput} instance with a default size. - */ - public static ByteArrayDataOutput newDataOutput() { - return newDataOutput(new ByteArrayOutputStream()); - } - - /** - * Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} - * bytes before resizing. - * - * @throws IllegalArgumentException if {@code size} is negative - */ - public static ByteArrayDataOutput newDataOutput(int size) { - checkArgument(size >= 0, "Invalid size: %s", size); - return newDataOutput(new ByteArrayOutputStream(size)); - } - - /** - * Returns a new {@link ByteArrayDataOutput} instance which writes to the given - * {@code ByteArrayOutputStream}. The given output stream is not reset before - * being written to by the returned {@code ByteArrayDataOutput} and new data - * will be appended to any existing content. - * - *

          - * Note that if the given output stream was not empty or is modified after the - * {@code ByteArrayDataOutput} is created, the contract for - * {@link ByteArrayDataOutput#toByteArray} will not be honored (the bytes - * returned in the byte array may not be exactly what was written via calls to - * {@code ByteArrayDataOutput}). - * - * @since 17.0 - */ - public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputSteam) { - return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputSteam)); + @Override + public int skipBytes(int n) { + try { + return input.skipBytes(n); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } } @SuppressWarnings("deprecation") // for writeBytes @@ -506,12 +210,8 @@ public final class ByteStreams { } @Override - public void write(int b) { - try { - output.write(b); - } catch (IOException impossible) { - throw new AssertionError(impossible); - } + public byte[] toByteArray() { + return byteArrayOutputSteam.toByteArray(); } @Override @@ -532,6 +232,15 @@ public final class ByteStreams { } } + @Override + public void write(int b) { + try { + output.write(b); + } catch (IOException impossible) { + throw new AssertionError(impossible); + } + } + @Override public void writeBoolean(boolean v) { try { @@ -630,56 +339,19 @@ public final class ByteStreams { throw new AssertionError(impossible); } } - - @Override - public byte[] toByteArray() { - return byteArrayOutputSteam.toByteArray(); - } - } - - private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { - /** Discards the specified byte. */ - @Override - public void write(int b) { - } - - /** Discards the specified byte array. */ - @Override - public void write(byte[] b) { - checkNotNull(b); - } - - /** Discards the specified byte array. */ - @Override - public void write(byte[] b, int off, int len) { - checkNotNull(b); - } - - @Override - public String toString() { - return "ByteStreams.nullOutputStream()"; - } - }; - - /** - * Returns an {@link OutputStream} that simply discards written bytes. - * - * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) - */ - public static OutputStream nullOutputStream() { - return NULL_OUTPUT_STREAM; } /** - * Wraps a {@link InputStream}, limiting the number of bytes which can be read. - * - * @param in the input stream to be wrapped - * @param limit the maximum number of bytes to be read - * @return a length-limited {@link InputStream} - * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) + * BAOS that provides limited access to its internal byte array. */ - public static InputStream limit(InputStream in, long limit) { - return new LimitedInputStream(in, limit); + private static final class FastByteArrayOutputStream extends ByteArrayOutputStream { + /** + * Writes the contents of the internal buffer to the given array starting at the + * given offset. Assumes the array has space to hold count bytes. + */ + void writeTo(byte[] b, int off) { + System.arraycopy(buf, 0, b, off, count); + } } private static final class LimitedInputStream extends FilterInputStream { @@ -755,15 +427,201 @@ public final class ByteStreams { } } + private static final int BUF_SIZE = 0x1000; // 4K + + private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { + @Override + public String toString() { + return "ByteStreams.nullOutputStream()"; + } + + /** Discards the specified byte array. */ + @Override + public void write(byte[] b) { + checkNotNull(b); + } + + /** Discards the specified byte array. */ + @Override + public void write(byte[] b, int off, int len) { + checkNotNull(b); + } + + /** Discards the specified byte. */ + @Override + public void write(int b) { + } + }; + /** - * Returns the length of a supplied input stream, in bytes. + * Returns a view of the given {@code OutputStream} supplier as a + * {@code ByteSink}. * - * @deprecated Use {@link ByteSource#size()} instead. This method is scheduled - * for removal in Guava 18.0. + *

          + * This method is a temporary method provided for easing migration from + * suppliers to sources and sinks. + * + * @since 15.0 + * @deprecated Convert all {@code OutputSupplier} + * implementations to extend {@link ByteSink} or provide a method + * for viewing the object as a {@code ByteSink}. This method is + * scheduled for removal in Guava 18.0. */ @Deprecated - public static long length(InputSupplier supplier) throws IOException { - return asByteSource(supplier).size(); + public static ByteSink asByteSink(final OutputSupplier supplier) { + checkNotNull(supplier); + return new ByteSink() { + @Override + public OutputStream openStream() throws IOException { + return supplier.getOutput(); + } + + @Override + public String toString() { + return "ByteStreams.asByteSink(" + supplier + ")"; + } + }; + } + + /** + * Returns a view of the given {@code InputStream} supplier as a + * {@code ByteSource}. + * + *

          + * This method is a temporary method provided for easing migration from + * suppliers to sources and sinks. + * + * @since 15.0 + * @deprecated Convert all {@code InputSupplier} + * implementations to extend {@link ByteSource} or provide a method + * for viewing the object as a {@code ByteSource}. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static ByteSource asByteSource(final InputSupplier supplier) { + checkNotNull(supplier); + return new ByteSource() { + @Override + public InputStream openStream() throws IOException { + return supplier.getInput(); + } + + @Override + public String toString() { + return "ByteStreams.asByteSource(" + supplier + ")"; + } + }; + } + + @SuppressWarnings("unchecked") // used internally where known to be safe + static InputSupplier asInputSupplier(final ByteSource source) { + return (InputSupplier) checkNotNull(source); + } + + @SuppressWarnings("unchecked") // used internally where known to be safe + static OutputSupplier asOutputSupplier(final ByteSink sink) { + return (OutputSupplier) checkNotNull(sink); + } + + /** + * Copies all bytes from the input stream to the output stream. Does not close + * or flush either stream. + * + * @param from the input stream to read from + * @param to the output stream to write to + * @return the number of bytes copied + * @throws IOException if an I/O error occurs + */ + public static long copy(InputStream from, OutputStream to) throws IOException { + checkNotNull(from); + checkNotNull(to); + byte[] buf = new byte[BUF_SIZE]; + long total = 0; + while (true) { + int r = from.read(buf); + if (r == -1) { + break; + } + to.write(buf, 0, r); + total += r; + } + return total; + } + + /** + * Opens an output stream from the supplier, copies all bytes from the input to + * the output, and closes the output stream. Does not close or flush the input + * stream. + * + * @param from the input stream to read from + * @param to the output factory + * @return the number of bytes copied + * @throws IOException if an I/O error occurs + * @since 10.0 + * @deprecated Use {@link ByteSink#writeFrom(InputStream)} instead. This method + * is scheduled for removal in Guava 18.0. + */ + @Deprecated + public static long copy(InputStream from, OutputSupplier to) throws IOException { + return asByteSink(to).writeFrom(from); + } + + /** + * Opens an input stream from the supplier, copies all bytes from the input to + * the output, and closes the input stream. Does not close or flush the output + * stream. + * + * @param from the input factory + * @param to the output stream to write to + * @return the number of bytes copied + * @throws IOException if an I/O error occurs + * @deprecated Use {@link ByteSource#copyTo(OutputStream)} instead. This method + * is scheduled for removal in Guava 18.0. + */ + @Deprecated + public static long copy(InputSupplier from, OutputStream to) throws IOException { + return asByteSource(from).copyTo(to); + } + + /** + * Opens input and output streams from the given suppliers, copies all bytes + * from the input to the output, and closes the streams. + * + * @param from the input factory + * @param to the output factory + * @return the number of bytes copied + * @throws IOException if an I/O error occurs + * @deprecated Use {@link ByteSource#copyTo(ByteSink)} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static long copy(InputSupplier from, OutputSupplier to) + throws IOException { + return asByteSource(from).copyTo(asByteSink(to)); + } + + /** + * Copies all bytes from the readable channel to the writable channel. Does not + * close or flush either channel. + * + * @param from the readable channel to read from + * @param to the writable channel to write to + * @return the number of bytes copied + * @throws IOException if an I/O error occurs + */ + public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { + checkNotNull(from); + checkNotNull(to); + ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); + long total = 0; + while (from.read(buf) != -1) { + buf.flip(); + while (buf.hasRemaining()) { + total += to.write(buf); + } + buf.clear(); + } + return total; } /** @@ -779,6 +637,291 @@ public final class ByteStreams { return asByteSource(supplier1).contentEquals(asByteSource(supplier2)); } + /** + * Computes the hash code of the data supplied by {@code supplier} using {@code + * hashFunction}. + * + * @param supplier the input stream factory + * @param hashFunction the hash function to use to hash the data + * @return the {@link HashCode} of all of the bytes in the input stream + * @throws IOException if an I/O error occurs + * @since 12.0 + * @deprecated Use {@link ByteSource#hash(HashFunction)} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static HashCode hash(InputSupplier supplier, HashFunction hashFunction) + throws IOException { + return asByteSource(supplier).hash(hashFunction); + } + + /** + * Varargs form of {@link #join(Iterable)}. + * + * @deprecated Use {@link ByteSource#concat(ByteSource[])} instead. This method + * is scheduled for removal in Guava 18.0. + */ + @Deprecated + @SuppressWarnings("unchecked") // suppress "possible heap pollution" warning in JDK7 + public static InputSupplier join(InputSupplier... suppliers) { + return join(Arrays.asList(suppliers)); + } + + /** + * Joins multiple {@link InputStream} suppliers into a single supplier. Streams + * returned from the supplier will contain the concatenated data from the + * streams of the underlying suppliers. + * + *

          + * Only one underlying input stream will be open at a time. Closing the joined + * stream will close the open underlying stream. + * + *

          + * Reading from the joined stream will throw a {@link NullPointerException} if + * any of the suppliers are null or return null. + * + * @param suppliers the suppliers to concatenate + * @return a supplier that will return a stream containing the concatenated + * stream data + * @deprecated Use {@link ByteSource#concat(Iterable)} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static InputSupplier join( + final Iterable> suppliers) { + checkNotNull(suppliers); + Iterable sources = Iterables.transform(suppliers, + new Function, ByteSource>() { + @Override + public ByteSource apply(InputSupplier input) { + return asByteSource(input); + } + }); + return asInputSupplier(ByteSource.concat(sources)); + } + + /** + * Returns the length of a supplied input stream, in bytes. + * + * @deprecated Use {@link ByteSource#size()} instead. This method is scheduled + * for removal in Guava 18.0. + */ + @Deprecated + public static long length(InputSupplier supplier) throws IOException { + return asByteSource(supplier).size(); + } + + /** + * Wraps a {@link InputStream}, limiting the number of bytes which can be read. + * + * @param in the input stream to be wrapped + * @param limit the maximum number of bytes to be read + * @return a length-limited {@link InputStream} + * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) + */ + public static InputStream limit(InputStream in, long limit) { + return new LimitedInputStream(in, limit); + } + + /** + * Returns a new {@link ByteArrayDataInput} instance to read from the {@code + * bytes} array from the beginning. + */ + public static ByteArrayDataInput newDataInput(byte[] bytes) { + return newDataInput(new EaglerInputStream(bytes)); + } + + /** + * Returns a new {@link ByteArrayDataInput} instance to read from the {@code + * bytes} array, starting at the given position. + * + * @throws IndexOutOfBoundsException if {@code start} is negative or greater + * than the length of the array + */ + public static ByteArrayDataInput newDataInput(byte[] bytes, int start) { + checkPositionIndex(start, bytes.length); + return newDataInput(new EaglerInputStream(bytes, start, bytes.length - start)); + } + + /** + * Returns a new {@link ByteArrayDataInput} instance to read from the given + * {@code ByteArrayInputStream}. The given input stream is not reset before + * being read from by the returned {@code ByteArrayDataInput}. + * + * @since 17.0 + */ + public static ByteArrayDataInput newDataInput(EaglerInputStream byteArrayInputStream) { + return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream)); + } + + /** + * Returns a new {@link ByteArrayDataOutput} instance with a default size. + */ + public static ByteArrayDataOutput newDataOutput() { + return newDataOutput(new ByteArrayOutputStream()); + } + + /** + * Returns a new {@link ByteArrayDataOutput} instance which writes to the given + * {@code ByteArrayOutputStream}. The given output stream is not reset before + * being written to by the returned {@code ByteArrayDataOutput} and new data + * will be appended to any existing content. + * + *

          + * Note that if the given output stream was not empty or is modified after the + * {@code ByteArrayDataOutput} is created, the contract for + * {@link ByteArrayDataOutput#toByteArray} will not be honored (the bytes + * returned in the byte array may not be exactly what was written via calls to + * {@code ByteArrayDataOutput}). + * + * @since 17.0 + */ + public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputSteam) { + return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputSteam)); + } + + /** + * Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} + * bytes before resizing. + * + * @throws IllegalArgumentException if {@code size} is negative + */ + public static ByteArrayDataOutput newDataOutput(int size) { + checkArgument(size >= 0, "Invalid size: %s", size); + return newDataOutput(new ByteArrayOutputStream(size)); + } + + /** + * Returns a factory that will supply instances of {@link ByteArrayInputStream} + * that read from the given byte array. + * + * @param b the input buffer + * @return the factory + * @deprecated Use {@link ByteSource#wrap(byte[])} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static InputSupplier newInputStreamSupplier(byte[] b) { + return asInputSupplier(ByteSource.wrap(b)); + } + + /** + * Returns a factory that will supply instances of {@link ByteArrayInputStream} + * that read from the given byte array. + * + * @param b the input buffer + * @param off the offset in the buffer of the first byte to read + * @param len the maximum number of bytes to read from the buffer + * @return the factory + * @deprecated Use {@code ByteSource.wrap(b).slice(off, len)} instead. This + * method is scheduled for removal in Guava 18.0. + */ + @Deprecated + public static InputSupplier newInputStreamSupplier(final byte[] b, final int off, + final int len) { + return asInputSupplier(ByteSource.wrap(b).slice(off, len)); + } + + /** + * Returns an {@link OutputStream} that simply discards written bytes. + * + * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) + */ + public static OutputStream nullOutputStream() { + return NULL_OUTPUT_STREAM; + } + + /** + * Reads some bytes from an input stream and stores them into the buffer array + * {@code b}. This method blocks until {@code len} bytes of input data have been + * read into the array, or end of file is detected. The number of bytes read is + * returned, possibly zero. Does not close the stream. + * + *

          + * A caller can detect EOF if the number of bytes read is less than {@code len}. + * All subsequent calls on the same stream will return zero. + * + *

          + * If {@code b} is null, a {@code NullPointerException} is thrown. If + * {@code off} is negative, or {@code len} is negative, or {@code off+len} is + * greater than the length of the array {@code b}, then an + * {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no + * bytes are read. Otherwise, the first byte read is stored into element + * {@code b[off]}, the next one into {@code b[off+1]}, and so on. The number of + * bytes read is, at most, equal to {@code len}. + * + * @param in the input stream to read from + * @param b the buffer into which the data is read + * @param off an int specifying the offset into the data + * @param len an int specifying the number of bytes to read + * @return the number of bytes read + * @throws IOException if an I/O error occurs + */ + public static int read(InputStream in, byte[] b, int off, int len) throws IOException { + checkNotNull(in); + checkNotNull(b); + if (len < 0) { + throw new IndexOutOfBoundsException("len is negative"); + } + int total = 0; + while (total < len) { + int result = in.read(b, off + total, len - total); + if (result == -1) { + break; + } + total += result; + } + return total; + } + + /** + * Process the bytes of the given input stream using the given processor. + * + * @param input the input stream to process + * @param processor the object to which to pass the bytes of the stream + * @return the result of the byte processor + * @throws IOException if an I/O error occurs + * @since 14.0 + */ + public static T readBytes(InputStream input, ByteProcessor processor) throws IOException { + checkNotNull(input); + checkNotNull(processor); + + byte[] buf = new byte[BUF_SIZE]; + int read; + do { + read = input.read(buf); + } while (read != -1 && processor.processBytes(buf, 0, read)); + return processor.getResult(); + } + + /** + * Process the bytes of a supplied stream + * + * @param supplier the input stream factory + * @param processor the object to which to pass the bytes of the stream + * @return the result of the byte processor + * @throws IOException if an I/O error occurs + * @deprecated Use {@link ByteSource#read(ByteProcessor)} instead. This method + * is scheduled for removal in Guava 18.0. + */ + @Deprecated + public static T readBytes(InputSupplier supplier, ByteProcessor processor) + throws IOException { + checkNotNull(supplier); + checkNotNull(processor); + + Closer closer = Closer.create(); + try { + InputStream in = closer.register(supplier.getInput()); + return readBytes(in, processor); + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + /** * Attempts to read enough bytes from the stream to fill the given byte array, * with the same behavior as {@link DataInput#readFully(byte[])}. Does not close @@ -844,115 +987,6 @@ public final class ByteStreams { } } - /** - * Process the bytes of a supplied stream - * - * @param supplier the input stream factory - * @param processor the object to which to pass the bytes of the stream - * @return the result of the byte processor - * @throws IOException if an I/O error occurs - * @deprecated Use {@link ByteSource#read(ByteProcessor)} instead. This method - * is scheduled for removal in Guava 18.0. - */ - @Deprecated - public static T readBytes(InputSupplier supplier, ByteProcessor processor) - throws IOException { - checkNotNull(supplier); - checkNotNull(processor); - - Closer closer = Closer.create(); - try { - InputStream in = closer.register(supplier.getInput()); - return readBytes(in, processor); - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Process the bytes of the given input stream using the given processor. - * - * @param input the input stream to process - * @param processor the object to which to pass the bytes of the stream - * @return the result of the byte processor - * @throws IOException if an I/O error occurs - * @since 14.0 - */ - public static T readBytes(InputStream input, ByteProcessor processor) throws IOException { - checkNotNull(input); - checkNotNull(processor); - - byte[] buf = new byte[BUF_SIZE]; - int read; - do { - read = input.read(buf); - } while (read != -1 && processor.processBytes(buf, 0, read)); - return processor.getResult(); - } - - /** - * Computes the hash code of the data supplied by {@code supplier} using {@code - * hashFunction}. - * - * @param supplier the input stream factory - * @param hashFunction the hash function to use to hash the data - * @return the {@link HashCode} of all of the bytes in the input stream - * @throws IOException if an I/O error occurs - * @since 12.0 - * @deprecated Use {@link ByteSource#hash(HashFunction)} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Deprecated - public static HashCode hash(InputSupplier supplier, HashFunction hashFunction) - throws IOException { - return asByteSource(supplier).hash(hashFunction); - } - - /** - * Reads some bytes from an input stream and stores them into the buffer array - * {@code b}. This method blocks until {@code len} bytes of input data have been - * read into the array, or end of file is detected. The number of bytes read is - * returned, possibly zero. Does not close the stream. - * - *

          - * A caller can detect EOF if the number of bytes read is less than {@code len}. - * All subsequent calls on the same stream will return zero. - * - *

          - * If {@code b} is null, a {@code NullPointerException} is thrown. If - * {@code off} is negative, or {@code len} is negative, or {@code off+len} is - * greater than the length of the array {@code b}, then an - * {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no - * bytes are read. Otherwise, the first byte read is stored into element - * {@code b[off]}, the next one into {@code b[off+1]}, and so on. The number of - * bytes read is, at most, equal to {@code len}. - * - * @param in the input stream to read from - * @param b the buffer into which the data is read - * @param off an int specifying the offset into the data - * @param len an int specifying the number of bytes to read - * @return the number of bytes read - * @throws IOException if an I/O error occurs - */ - public static int read(InputStream in, byte[] b, int off, int len) throws IOException { - checkNotNull(in); - checkNotNull(b); - if (len < 0) { - throw new IndexOutOfBoundsException("len is negative"); - } - int total = 0; - while (total < len) { - int result = in.read(b, off + total, len - total); - if (result == -1) { - break; - } - total += result; - } - return total; - } - /** * Returns an {@link InputSupplier} that returns input streams from the an * underlying supplier, where each stream starts at the given offset and is @@ -973,119 +1007,86 @@ public final class ByteStreams { } /** - * Joins multiple {@link InputStream} suppliers into a single supplier. Streams - * returned from the supplier will contain the concatenated data from the - * streams of the underlying suppliers. + * Reads all bytes from an input stream into a byte array. Does not close the + * stream. * - *

          - * Only one underlying input stream will be open at a time. Closing the joined - * stream will close the open underlying stream. - * - *

          - * Reading from the joined stream will throw a {@link NullPointerException} if - * any of the suppliers are null or return null. - * - * @param suppliers the suppliers to concatenate - * @return a supplier that will return a stream containing the concatenated - * stream data - * @deprecated Use {@link ByteSource#concat(Iterable)} instead. This method is - * scheduled for removal in Guava 18.0. + * @param in the input stream to read from + * @return a byte array containing all the bytes from the stream + * @throws IOException if an I/O error occurs */ - @Deprecated - public static InputSupplier join( - final Iterable> suppliers) { - checkNotNull(suppliers); - Iterable sources = Iterables.transform(suppliers, - new Function, ByteSource>() { - @Override - public ByteSource apply(InputSupplier input) { - return asByteSource(input); - } - }); - return asInputSupplier(ByteSource.concat(sources)); - } - - /** - * Varargs form of {@link #join(Iterable)}. - * - * @deprecated Use {@link ByteSource#concat(ByteSource[])} instead. This method - * is scheduled for removal in Guava 18.0. - */ - @Deprecated - @SuppressWarnings("unchecked") // suppress "possible heap pollution" warning in JDK7 - public static InputSupplier join(InputSupplier... suppliers) { - return join(Arrays.asList(suppliers)); + public static byte[] toByteArray(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + copy(in, out); + return out.toByteArray(); } // TODO(user): Remove these once Input/OutputSupplier methods are removed /** - * Returns a view of the given {@code InputStream} supplier as a - * {@code ByteSource}. - * - *

          - * This method is a temporary method provided for easing migration from - * suppliers to sources and sinks. - * - * @since 15.0 - * @deprecated Convert all {@code InputSupplier} - * implementations to extend {@link ByteSource} or provide a method - * for viewing the object as a {@code ByteSource}. This method is - * scheduled for removal in Guava 18.0. + * Reads all bytes from an input stream into a byte array. The given expected + * size is used to create an initial byte array, but if the actual number of + * bytes read from the stream differs, the correct result will be returned + * anyway. */ - @Deprecated - public static ByteSource asByteSource(final InputSupplier supplier) { - checkNotNull(supplier); - return new ByteSource() { - @Override - public InputStream openStream() throws IOException { - return supplier.getInput(); - } + static byte[] toByteArray(InputStream in, int expectedSize) throws IOException { + byte[] bytes = new byte[expectedSize]; + int remaining = expectedSize; - @Override - public String toString() { - return "ByteStreams.asByteSource(" + supplier + ")"; + while (remaining > 0) { + int off = expectedSize - remaining; + int read = in.read(bytes, off, remaining); + if (read == -1) { + // end of stream before reading expectedSize bytes + // just return the bytes read so far + return Arrays.copyOf(bytes, off); } - }; + remaining -= read; + } + + // bytes is now full + int b = in.read(); + if (b == -1) { + return bytes; + } + + // the stream was longer, so read the rest normally + FastByteArrayOutputStream out = new FastByteArrayOutputStream(); + out.write(b); // write the byte we read when testing for end of stream + copy(in, out); + + byte[] result = new byte[bytes.length + out.size()]; + System.arraycopy(bytes, 0, result, 0, bytes.length); + out.writeTo(result, bytes.length); + return result; } /** - * Returns a view of the given {@code OutputStream} supplier as a - * {@code ByteSink}. + * Returns the data from a {@link InputStream} factory as a byte array. * - *

          - * This method is a temporary method provided for easing migration from - * suppliers to sources and sinks. + * @param supplier the factory + * @throws IOException if an I/O error occurs + * @deprecated Use {@link ByteSource#read()} instead. This method is scheduled + * for removal in Guava 18.0. + */ + @Deprecated + public static byte[] toByteArray(InputSupplier supplier) throws IOException { + return asByteSource(supplier).read(); + } + + /** + * Writes a byte array to an output stream from the given supplier. * - * @since 15.0 - * @deprecated Convert all {@code OutputSupplier} - * implementations to extend {@link ByteSink} or provide a method - * for viewing the object as a {@code ByteSink}. This method is + * @param from the bytes to write + * @param to the output supplier + * @throws IOException if an I/O error occurs + * @deprecated Use {@link ByteSink#write(byte[])} instead. This method is * scheduled for removal in Guava 18.0. */ @Deprecated - public static ByteSink asByteSink(final OutputSupplier supplier) { - checkNotNull(supplier); - return new ByteSink() { - @Override - public OutputStream openStream() throws IOException { - return supplier.getOutput(); - } - - @Override - public String toString() { - return "ByteStreams.asByteSink(" + supplier + ")"; - } - }; + public static void write(byte[] from, OutputSupplier to) throws IOException { + asByteSink(to).write(from); } - @SuppressWarnings("unchecked") // used internally where known to be safe - static InputSupplier asInputSupplier(final ByteSource source) { - return (InputSupplier) checkNotNull(source); - } - - @SuppressWarnings("unchecked") // used internally where known to be safe - static OutputSupplier asOutputSupplier(final ByteSink sink) { - return (OutputSupplier) checkNotNull(sink); + private ByteStreams() { } } diff --git a/src/main/java/com/google/common/io/CharSequenceReader.java b/src/main/java/com/google/common/io/CharSequenceReader.java index cc24e300..588df9ac 100644 --- a/src/main/java/com/google/common/io/CharSequenceReader.java +++ b/src/main/java/com/google/common/io/CharSequenceReader.java @@ -50,26 +50,25 @@ final class CharSequenceReader extends Reader { } } + @Override + public synchronized void close() throws IOException { + seq = null; + } + private boolean hasRemaining() { return remaining() > 0; } - private int remaining() { - return seq.length() - pos; + @Override + public synchronized void mark(int readAheadLimit) throws IOException { + checkArgument(readAheadLimit >= 0, "readAheadLimit (%s) may not be negative", readAheadLimit); + checkOpen(); + mark = pos; } @Override - public synchronized int read(CharBuffer target) throws IOException { - checkNotNull(target); - checkOpen(); - if (!hasRemaining()) { - return -1; - } - int charsToRead = Math.min(target.remaining(), remaining()); - for (int i = 0; i < charsToRead; i++) { - target.put(seq.charAt(pos++)); - } - return charsToRead; + public boolean markSupported() { + return true; } @Override @@ -93,12 +92,17 @@ final class CharSequenceReader extends Reader { } @Override - public synchronized long skip(long n) throws IOException { - checkArgument(n >= 0, "n (%s) may not be negative", n); + public synchronized int read(CharBuffer target) throws IOException { + checkNotNull(target); checkOpen(); - int charsToSkip = (int) Math.min(remaining(), n); // safe because remaining is an int - pos += charsToSkip; - return charsToSkip; + if (!hasRemaining()) { + return -1; + } + int charsToRead = Math.min(target.remaining(), remaining()); + for (int i = 0; i < charsToRead; i++) { + target.put(seq.charAt(pos++)); + } + return charsToRead; } @Override @@ -107,16 +111,8 @@ final class CharSequenceReader extends Reader { return true; } - @Override - public boolean markSupported() { - return true; - } - - @Override - public synchronized void mark(int readAheadLimit) throws IOException { - checkArgument(readAheadLimit >= 0, "readAheadLimit (%s) may not be negative", readAheadLimit); - checkOpen(); - mark = pos; + private int remaining() { + return seq.length() - pos; } @Override @@ -126,7 +122,11 @@ final class CharSequenceReader extends Reader { } @Override - public synchronized void close() throws IOException { - seq = null; + public synchronized long skip(long n) throws IOException { + checkArgument(n >= 0, "n (%s) may not be negative", n); + checkOpen(); + int charsToSkip = (int) Math.min(remaining(), n); // safe because remaining is an int + pos += charsToSkip; + return charsToSkip; } } diff --git a/src/main/java/com/google/common/io/CharSink.java b/src/main/java/com/google/common/io/CharSink.java index 50907e5a..434a7717 100644 --- a/src/main/java/com/google/common/io/CharSink.java +++ b/src/main/java/com/google/common/io/CharSink.java @@ -59,18 +59,6 @@ public abstract class CharSink implements OutputSupplier { protected CharSink() { } - /** - * Opens a new {@link Writer} for writing to this sink. This method should - * return a new, independent writer each time it is called. - * - *

          - * The caller is responsible for ensuring that the returned writer is closed. - * - * @throws IOException if an I/O error occurs in the process of opening the - * writer - */ - public abstract Writer openStream() throws IOException; - /** * This method is a temporary method provided for easing migration from * suppliers to sources and sinks. @@ -106,6 +94,18 @@ public abstract class CharSink implements OutputSupplier { return (writer instanceof BufferedWriter) ? (BufferedWriter) writer : new BufferedWriter(writer); } + /** + * Opens a new {@link Writer} for writing to this sink. This method should + * return a new, independent writer each time it is called. + * + *

          + * The caller is responsible for ensuring that the returned writer is closed. + * + * @throws IOException if an I/O error occurs in the process of opening the + * writer + */ + public abstract Writer openStream() throws IOException; + /** * Writes the given character sequence to this sink. * @@ -126,6 +126,30 @@ public abstract class CharSink implements OutputSupplier { } } + /** + * Writes all the text from the given {@link Readable} (such as a + * {@link Reader}) to this sink. Does not close {@code readable} if it is + * {@code Closeable}. + * + * @throws IOException if an I/O error occurs in the process of reading from + * {@code readable} or writing to this sink + */ + public long writeFrom(Readable readable) throws IOException { + checkNotNull(readable); + + Closer closer = Closer.create(); + try { + Writer out = closer.register(openStream()); + long written = CharStreams.copy(readable, out); + out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 + return written; + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + /** * Writes the given lines of text to this sink with each line (including the * last) terminated with the operating system's default line separator. This @@ -163,28 +187,4 @@ public abstract class CharSink implements OutputSupplier { closer.close(); } } - - /** - * Writes all the text from the given {@link Readable} (such as a - * {@link Reader}) to this sink. Does not close {@code readable} if it is - * {@code Closeable}. - * - * @throws IOException if an I/O error occurs in the process of reading from - * {@code readable} or writing to this sink - */ - public long writeFrom(Readable readable) throws IOException { - checkNotNull(readable); - - Closer closer = Closer.create(); - try { - Writer out = closer.register(openStream()); - long written = CharStreams.copy(readable, out); - out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 - return written; - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } } diff --git a/src/main/java/com/google/common/io/CharSource.java b/src/main/java/com/google/common/io/CharSource.java index be869678..9273a5bf 100644 --- a/src/main/java/com/google/common/io/CharSource.java +++ b/src/main/java/com/google/common/io/CharSource.java @@ -71,55 +71,216 @@ import com.google.common.collect.Lists; */ public abstract class CharSource implements InputSupplier { + private static class CharSequenceCharSource extends CharSource { + + private static final Splitter LINE_SPLITTER = Splitter.on(Pattern.compile("\r\n|\n|\r")); + + private final CharSequence seq; + + protected CharSequenceCharSource(CharSequence seq) { + this.seq = checkNotNull(seq); + } + + @Override + public boolean isEmpty() { + return seq.length() == 0; + } + + /** + * Returns an iterable over the lines in the string. If the string ends in a + * newline, a final empty string is not included to match the behavior of + * BufferedReader/LineReader.readLine(). + */ + private Iterable lines() { + return new Iterable() { + @Override + public Iterator iterator() { + return new AbstractIterator() { + Iterator lines = LINE_SPLITTER.split(seq).iterator(); + + @Override + protected String computeNext() { + if (lines.hasNext()) { + String next = lines.next(); + // skip last line if it's empty + if (lines.hasNext() || !next.isEmpty()) { + return next; + } + } + return endOfData(); + } + }; + } + }; + } + + @Override + public Reader openStream() { + return new CharSequenceReader(seq); + } + + @Override + public String read() { + return seq.toString(); + } + + @Override + public String readFirstLine() { + Iterator lines = lines().iterator(); + return lines.hasNext() ? lines.next() : null; + } + + @Override + public ImmutableList readLines() { + return ImmutableList.copyOf(lines()); + } + + @Override + public T readLines(LineProcessor processor) throws IOException { + for (String line : lines()) { + if (!processor.processLine(line)) { + break; + } + } + return processor.getResult(); + } + + @Override + public String toString() { + return "CharSource.wrap(" + Ascii.truncate(seq, 30, "...") + ")"; + } + } + + private static final class ConcatenatedCharSource extends CharSource { + + private final Iterable sources; + + ConcatenatedCharSource(Iterable sources) { + this.sources = checkNotNull(sources); + } + + @Override + public boolean isEmpty() throws IOException { + for (CharSource source : sources) { + if (!source.isEmpty()) { + return false; + } + } + return true; + } + + @Override + public Reader openStream() throws IOException { + return new MultiReader(sources.iterator()); + } + + @Override + public String toString() { + return "CharSource.concat(" + sources + ")"; + } + } + + private static final class EmptyCharSource extends CharSequenceCharSource { + + private static final EmptyCharSource INSTANCE = new EmptyCharSource(); + + private EmptyCharSource() { + super(""); + } + + @Override + public String toString() { + return "CharSource.empty()"; + } + } + + /** + * Concatenates multiple {@link CharSource} instances into a single source. + * Streams returned from the source will contain the concatenated data from the + * streams of the underlying sources. + * + *

          + * Only one underlying stream will be open at a time. Closing the concatenated + * stream will close the open underlying stream. + * + * @param sources the sources to concatenate + * @return a {@code CharSource} containing the concatenated data + * @throws NullPointerException if any of {@code sources} is {@code null} + * @since 15.0 + */ + public static CharSource concat(CharSource... sources) { + return concat(ImmutableList.copyOf(sources)); + } + + /** + * Concatenates multiple {@link CharSource} instances into a single source. + * Streams returned from the source will contain the concatenated data from the + * streams of the underlying sources. + * + *

          + * Only one underlying stream will be open at a time. Closing the concatenated + * stream will close the open underlying stream. + * + * @param sources the sources to concatenate + * @return a {@code CharSource} containing the concatenated data + * @since 15.0 + */ + public static CharSource concat(Iterable sources) { + return new ConcatenatedCharSource(sources); + } + + /** + * Concatenates multiple {@link CharSource} instances into a single source. + * Streams returned from the source will contain the concatenated data from the + * streams of the underlying sources. + * + *

          + * Only one underlying stream will be open at a time. Closing the concatenated + * stream will close the open underlying stream. + * + *

          + * Note: The input {@code Iterator} will be copied to an {@code ImmutableList} + * when this method is called. This will fail if the iterator is infinite and + * may cause problems if the iterator eagerly fetches data for each source when + * iterated (rather than producing sources that only load data through their + * streams). Prefer using the {@link #concat(Iterable)} overload if possible. + * + * @param sources the sources to concatenate + * @return a {@code CharSource} containing the concatenated data + * @throws NullPointerException if any of {@code sources} is {@code null} + * @since 15.0 + */ + public static CharSource concat(Iterator sources) { + return concat(ImmutableList.copyOf(sources)); + } + + /** + * Returns an immutable {@link CharSource} that contains no characters. + * + * @since 15.0 + */ + public static CharSource empty() { + return EmptyCharSource.INSTANCE; + } + + /** + * Returns a view of the given character sequence as a {@link CharSource}. The + * behavior of the returned {@code CharSource} and any {@code Reader} instances + * created by it is unspecified if the {@code charSequence} is mutated while it + * is being read, so don't do that. + * + * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)}) + */ + public static CharSource wrap(CharSequence charSequence) { + return new CharSequenceCharSource(charSequence); + } + /** * Constructor for use by subclasses. */ protected CharSource() { } - /** - * Opens a new {@link Reader} for reading from this source. This method should - * return a new, independent reader each time it is called. - * - *

          - * The caller is responsible for ensuring that the returned reader is closed. - * - * @throws IOException if an I/O error occurs in the process of opening the - * reader - */ - public abstract Reader openStream() throws IOException; - - /** - * This method is a temporary method provided for easing migration from - * suppliers to sources and sinks. - * - * @since 15.0 - * @deprecated This method is only provided for temporary compatibility with the - * {@link InputSupplier} interface and should not be called - * directly. Use {@link #openStream} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Override - @Deprecated - public final Reader getInput() throws IOException { - return openStream(); - } - - /** - * Opens a new {@link BufferedReader} for reading from this source. This method - * should return a new, independent reader each time it is called. - * - *

          - * The caller is responsible for ensuring that the returned reader is closed. - * - * @throws IOException if an I/O error occurs in the process of opening the - * reader - */ - public BufferedReader openBufferedStream() throws IOException { - Reader reader = openStream(); - return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader); - } - /** * Appends the contents of this source to the given {@link Appendable} (such as * a {@link Writer}). Does not close {@code appendable} if it is @@ -163,6 +324,68 @@ public abstract class CharSource implements InputSupplier { } } + /** + * This method is a temporary method provided for easing migration from + * suppliers to sources and sinks. + * + * @since 15.0 + * @deprecated This method is only provided for temporary compatibility with the + * {@link InputSupplier} interface and should not be called + * directly. Use {@link #openStream} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Override + @Deprecated + public final Reader getInput() throws IOException { + return openStream(); + } + + /** + * Returns whether the source has zero chars. The default implementation is to + * open a stream and check for EOF. + * + * @throws IOException if an I/O error occurs + * @since 15.0 + */ + public boolean isEmpty() throws IOException { + Closer closer = Closer.create(); + try { + Reader reader = closer.register(openStream()); + return reader.read() == -1; + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + + /** + * Opens a new {@link BufferedReader} for reading from this source. This method + * should return a new, independent reader each time it is called. + * + *

          + * The caller is responsible for ensuring that the returned reader is closed. + * + * @throws IOException if an I/O error occurs in the process of opening the + * reader + */ + public BufferedReader openBufferedStream() throws IOException { + Reader reader = openStream(); + return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader); + } + + /** + * Opens a new {@link Reader} for reading from this source. This method should + * return a new, independent reader each time it is called. + * + *

          + * The caller is responsible for ensuring that the returned reader is closed. + * + * @throws IOException if an I/O error occurs in the process of opening the + * reader + */ + public abstract Reader openStream() throws IOException; + /** * Reads the contents of this source as a string. * @@ -267,227 +490,4 @@ public abstract class CharSource implements InputSupplier { closer.close(); } } - - /** - * Returns whether the source has zero chars. The default implementation is to - * open a stream and check for EOF. - * - * @throws IOException if an I/O error occurs - * @since 15.0 - */ - public boolean isEmpty() throws IOException { - Closer closer = Closer.create(); - try { - Reader reader = closer.register(openStream()); - return reader.read() == -1; - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Concatenates multiple {@link CharSource} instances into a single source. - * Streams returned from the source will contain the concatenated data from the - * streams of the underlying sources. - * - *

          - * Only one underlying stream will be open at a time. Closing the concatenated - * stream will close the open underlying stream. - * - * @param sources the sources to concatenate - * @return a {@code CharSource} containing the concatenated data - * @since 15.0 - */ - public static CharSource concat(Iterable sources) { - return new ConcatenatedCharSource(sources); - } - - /** - * Concatenates multiple {@link CharSource} instances into a single source. - * Streams returned from the source will contain the concatenated data from the - * streams of the underlying sources. - * - *

          - * Only one underlying stream will be open at a time. Closing the concatenated - * stream will close the open underlying stream. - * - *

          - * Note: The input {@code Iterator} will be copied to an {@code ImmutableList} - * when this method is called. This will fail if the iterator is infinite and - * may cause problems if the iterator eagerly fetches data for each source when - * iterated (rather than producing sources that only load data through their - * streams). Prefer using the {@link #concat(Iterable)} overload if possible. - * - * @param sources the sources to concatenate - * @return a {@code CharSource} containing the concatenated data - * @throws NullPointerException if any of {@code sources} is {@code null} - * @since 15.0 - */ - public static CharSource concat(Iterator sources) { - return concat(ImmutableList.copyOf(sources)); - } - - /** - * Concatenates multiple {@link CharSource} instances into a single source. - * Streams returned from the source will contain the concatenated data from the - * streams of the underlying sources. - * - *

          - * Only one underlying stream will be open at a time. Closing the concatenated - * stream will close the open underlying stream. - * - * @param sources the sources to concatenate - * @return a {@code CharSource} containing the concatenated data - * @throws NullPointerException if any of {@code sources} is {@code null} - * @since 15.0 - */ - public static CharSource concat(CharSource... sources) { - return concat(ImmutableList.copyOf(sources)); - } - - /** - * Returns a view of the given character sequence as a {@link CharSource}. The - * behavior of the returned {@code CharSource} and any {@code Reader} instances - * created by it is unspecified if the {@code charSequence} is mutated while it - * is being read, so don't do that. - * - * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)}) - */ - public static CharSource wrap(CharSequence charSequence) { - return new CharSequenceCharSource(charSequence); - } - - /** - * Returns an immutable {@link CharSource} that contains no characters. - * - * @since 15.0 - */ - public static CharSource empty() { - return EmptyCharSource.INSTANCE; - } - - private static class CharSequenceCharSource extends CharSource { - - private static final Splitter LINE_SPLITTER = Splitter.on(Pattern.compile("\r\n|\n|\r")); - - private final CharSequence seq; - - protected CharSequenceCharSource(CharSequence seq) { - this.seq = checkNotNull(seq); - } - - @Override - public Reader openStream() { - return new CharSequenceReader(seq); - } - - @Override - public String read() { - return seq.toString(); - } - - @Override - public boolean isEmpty() { - return seq.length() == 0; - } - - /** - * Returns an iterable over the lines in the string. If the string ends in a - * newline, a final empty string is not included to match the behavior of - * BufferedReader/LineReader.readLine(). - */ - private Iterable lines() { - return new Iterable() { - @Override - public Iterator iterator() { - return new AbstractIterator() { - Iterator lines = LINE_SPLITTER.split(seq).iterator(); - - @Override - protected String computeNext() { - if (lines.hasNext()) { - String next = lines.next(); - // skip last line if it's empty - if (lines.hasNext() || !next.isEmpty()) { - return next; - } - } - return endOfData(); - } - }; - } - }; - } - - @Override - public String readFirstLine() { - Iterator lines = lines().iterator(); - return lines.hasNext() ? lines.next() : null; - } - - @Override - public ImmutableList readLines() { - return ImmutableList.copyOf(lines()); - } - - @Override - public T readLines(LineProcessor processor) throws IOException { - for (String line : lines()) { - if (!processor.processLine(line)) { - break; - } - } - return processor.getResult(); - } - - @Override - public String toString() { - return "CharSource.wrap(" + Ascii.truncate(seq, 30, "...") + ")"; - } - } - - private static final class EmptyCharSource extends CharSequenceCharSource { - - private static final EmptyCharSource INSTANCE = new EmptyCharSource(); - - private EmptyCharSource() { - super(""); - } - - @Override - public String toString() { - return "CharSource.empty()"; - } - } - - private static final class ConcatenatedCharSource extends CharSource { - - private final Iterable sources; - - ConcatenatedCharSource(Iterable sources) { - this.sources = checkNotNull(sources); - } - - @Override - public Reader openStream() throws IOException { - return new MultiReader(sources.iterator()); - } - - @Override - public boolean isEmpty() throws IOException { - for (CharSource source : sources) { - if (!source.isEmpty()) { - return false; - } - } - return true; - } - - @Override - public String toString() { - return "CharSource.concat(" + sources + ")"; - } - } } diff --git a/src/main/java/com/google/common/io/CharStreams.java b/src/main/java/com/google/common/io/CharStreams.java index f9b69306..52b5acfb 100644 --- a/src/main/java/com/google/common/io/CharStreams.java +++ b/src/main/java/com/google/common/io/CharStreams.java @@ -31,6 +31,7 @@ import java.io.StringReader; import java.io.Writer; import java.nio.CharBuffer; import java.nio.charset.Charset; +import java.nio.file.Files; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -59,90 +60,177 @@ import com.google.common.collect.Iterables; */ @Beta public final class CharStreams { + private static final class NullWriter extends Writer { + + private static final NullWriter INSTANCE = new NullWriter(); + + @Override + public Writer append(char c) { + return this; + } + + @Override + public Writer append(CharSequence csq) { + checkNotNull(csq); + return this; + } + + @Override + public Writer append(CharSequence csq, int start, int end) { + checkPositionIndexes(start, end, csq.length()); + return this; + } + + @Override + public void close() { + } + + @Override + public void flush() { + } + + @Override + public String toString() { + return "CharStreams.nullWriter()"; + } + + @Override + public void write(char[] cbuf) { + checkNotNull(cbuf); + } + + @Override + public void write(char[] cbuf, int off, int len) { + checkPositionIndexes(off, off + len, cbuf.length); + } + + @Override + public void write(int c) { + } + + @Override + public void write(String str) { + checkNotNull(str); + } + + @Override + public void write(String str, int off, int len) { + checkPositionIndexes(off, off + len, str.length()); + } + } + private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes) - private CharStreams() { - } - /** - * Returns a factory that will supply instances of {@link StringReader} that - * read a string value. + * Returns a view of the given {@code Appendable} supplier as a + * {@code CharSink}. * - * @param value the string to read - * @return the factory - * @deprecated Use {@link CharSource#wrap(CharSequence)} instead. This method is + *

          + * This method is a temporary method provided for easing migration from + * suppliers to sources and sinks. + * + * @since 15.0 + * @deprecated Convert all {@code OutputSupplier} + * implementations to extend {@link CharSink} or provide a method + * for viewing the object as a {@code CharSink}. This method is * scheduled for removal in Guava 18.0. */ @Deprecated - public static InputSupplier newReaderSupplier(final String value) { - return asInputSupplier(CharSource.wrap(value)); + public static CharSink asCharSink(final OutputSupplier supplier) { + checkNotNull(supplier); + return new CharSink() { + @Override + public Writer openStream() throws IOException { + return asWriter(supplier.getOutput()); + } + + @Override + public String toString() { + return "CharStreams.asCharSink(" + supplier + ")"; + } + }; } /** - * Returns a factory that will supply instances of {@link InputStreamReader}, - * using the given {@link InputStream} factory and character set. + * Returns a view of the given {@code Readable} supplier as a + * {@code CharSource}. * - * @param in the factory that will be used to open input streams - * @param charset the charset used to decode the input stream; see - * {@link Charsets} for helpful predefined constants - * @return the factory - * @deprecated Use {@link ByteSource#asCharSource(Charset)} instead. This method - * is scheduled for removal in Guava 18.0. - */ - @Deprecated - public static InputSupplier newReaderSupplier(final InputSupplier in, - final Charset charset) { - return asInputSupplier(ByteStreams.asByteSource(in).asCharSource(charset)); - } - - /** - * Returns a factory that will supply instances of {@link OutputStreamWriter}, - * using the given {@link OutputStream} factory and character set. + *

          + * This method is a temporary method provided for easing migration from + * suppliers to sources and sinks. * - * @param out the factory that will be used to open output streams - * @param charset the charset used to encode the output stream; see - * {@link Charsets} for helpful predefined constants - * @return the factory - * @deprecated Use {@link ByteSink#asCharSink(Charset)} instead. This method is + * @since 15.0 + * @deprecated Convert all {@code InputSupplier} + * implementations to extend {@link CharSource} or provide a method + * for viewing the object as a {@code CharSource}. This method is * scheduled for removal in Guava 18.0. */ @Deprecated - public static OutputSupplier newWriterSupplier(final OutputSupplier out, - final Charset charset) { - return asOutputSupplier(ByteStreams.asByteSink(out).asCharSink(charset)); + public static CharSource asCharSource(final InputSupplier supplier) { + checkNotNull(supplier); + return new CharSource() { + @Override + public Reader openStream() throws IOException { + return asReader(supplier.getInput()); + } + + @Override + public String toString() { + return "CharStreams.asCharSource(" + supplier + ")"; + } + }; + } + + @SuppressWarnings("unchecked") // used internally where known to be safe + static InputSupplier asInputSupplier(CharSource source) { + return (InputSupplier) checkNotNull(source); + } + + @SuppressWarnings("unchecked") // used internally where known to be safe + static OutputSupplier asOutputSupplier(CharSink sink) { + return (OutputSupplier) checkNotNull(sink); + } + + static Reader asReader(final Readable readable) { + checkNotNull(readable); + if (readable instanceof Reader) { + return (Reader) readable; + } + return new Reader() { + @Override + public void close() throws IOException { + if (readable instanceof Closeable) { + ((Closeable) readable).close(); + } + } + + @Override + public int read(char[] cbuf, int off, int len) throws IOException { + return read(CharBuffer.wrap(cbuf, off, len)); + } + + @Override + public int read(CharBuffer target) throws IOException { + return readable.read(target); + } + }; } /** - * Writes a character sequence (such as a string) to an appendable object from - * the given supplier. + * Returns a Writer that sends all output to the given {@link Appendable} + * target. Closing the writer will close the target if it is {@link Closeable}, + * and flushing the writer will flush the target if it is + * {@link java.io.Flushable}. * - * @param from the character sequence to write - * @param to the output supplier - * @throws IOException if an I/O error occurs - * @deprecated Use {@link CharSink#write(CharSequence)} instead. This method is - * scheduled for removal in Guava 18.0. + * @param target the object to which output will be sent + * @return a new Writer object, unless target is a Writer, in which case the + * target is returned */ - @Deprecated - public static void write(CharSequence from, OutputSupplier to) - throws IOException { - asCharSink(to).write(from); - } - - /** - * Opens {@link Readable} and {@link Appendable} objects from the given - * factories, copies all characters between the two, and closes them. - * - * @param from the input factory - * @param to the output factory - * @return the number of characters copied - * @throws IOException if an I/O error occurs - * @deprecated Use {@link CharSource#copyTo(CharSink)} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Deprecated - public static long copy(InputSupplier from, - OutputSupplier to) throws IOException { - return asCharSource(from).copyTo(asCharSink(to)); + public static Writer asWriter(Appendable target) { + if (target instanceof Writer) { + return (Writer) target; + } + return new AppendableWriter(target); } /** @@ -162,6 +250,23 @@ public final class CharStreams { return asCharSource(from).copyTo(to); } + /** + * Opens {@link Readable} and {@link Appendable} objects from the given + * factories, copies all characters between the two, and closes them. + * + * @param from the input factory + * @param to the output factory + * @return the number of characters copied + * @throws IOException if an I/O error occurs + * @deprecated Use {@link CharSource#copyTo(CharSink)} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static long copy(InputSupplier from, + OutputSupplier to) throws IOException { + return asCharSource(from).copyTo(asCharSink(to)); + } + /** * Copies all characters between the {@link Readable} and {@link Appendable} * objects. Does not close or flush either object. @@ -186,44 +291,103 @@ public final class CharStreams { } /** - * Reads all characters from a {@link Readable} object into a {@link String}. - * Does not close the {@code Readable}. + * Varargs form of {@link #join(Iterable)}. * - * @param r the object to read from - * @return a string containing all the characters - * @throws IOException if an I/O error occurs - */ - public static String toString(Readable r) throws IOException { - return toStringBuilder(r).toString(); - } - - /** - * Returns the characters from a {@link Readable} & {@link Closeable} object - * supplied by a factory as a {@link String}. - * - * @param supplier the factory to read from - * @return a string containing all the characters - * @throws IOException if an I/O error occurs - * @deprecated Use {@link CharSource#read()} instead. This method is scheduled - * for removal in Guava 18.0. + * @deprecated Use {@link CharSource#concat(CharSource[])} instead. This method + * is scheduled for removal in Guava 18.0. */ @Deprecated - public static String toString(InputSupplier supplier) throws IOException { - return asCharSource(supplier).read(); + @SuppressWarnings("unchecked") // suppress "possible heap pollution" warning in JDK7 + public static InputSupplier join(InputSupplier... suppliers) { + return join(Arrays.asList(suppliers)); } /** - * Reads all characters from a {@link Readable} object into a new - * {@link StringBuilder} instance. Does not close the {@code Readable}. + * Joins multiple {@link Reader} suppliers into a single supplier. Reader + * returned from the supplier will contain the concatenated data from the + * readers of the underlying suppliers. * - * @param r the object to read from - * @return a {@link StringBuilder} containing all the characters - * @throws IOException if an I/O error occurs + *

          + * Reading from the joined reader will throw a {@link NullPointerException} if + * any of the suppliers are null or return null. + * + *

          + * Only one underlying reader will be open at a time. Closing the joined reader + * will close the open underlying reader. + * + * @param suppliers the suppliers to concatenate + * @return a supplier that will return a reader containing the concatenated data + * @deprecated Use {@link CharSource#concat(Iterable)} instead. This method is + * scheduled for removal in Guava 18.0. */ - private static StringBuilder toStringBuilder(Readable r) throws IOException { - StringBuilder sb = new StringBuilder(); - copy(r, sb); - return sb; + @Deprecated + public static InputSupplier join(final Iterable> suppliers) { + checkNotNull(suppliers); + Iterable sources = Iterables.transform(suppliers, + new Function, CharSource>() { + @Override + public CharSource apply(InputSupplier input) { + return asCharSource(input); + } + }); + return asInputSupplier(CharSource.concat(sources)); + } + + /** + * Returns a factory that will supply instances of {@link InputStreamReader}, + * using the given {@link InputStream} factory and character set. + * + * @param in the factory that will be used to open input streams + * @param charset the charset used to decode the input stream; see + * {@link Charsets} for helpful predefined constants + * @return the factory + * @deprecated Use {@link ByteSource#asCharSource(Charset)} instead. This method + * is scheduled for removal in Guava 18.0. + */ + @Deprecated + public static InputSupplier newReaderSupplier(final InputSupplier in, + final Charset charset) { + return asInputSupplier(ByteStreams.asByteSource(in).asCharSource(charset)); + } + + /** + * Returns a factory that will supply instances of {@link StringReader} that + * read a string value. + * + * @param value the string to read + * @return the factory + * @deprecated Use {@link CharSource#wrap(CharSequence)} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static InputSupplier newReaderSupplier(final String value) { + return asInputSupplier(CharSource.wrap(value)); + } + + /** + * Returns a factory that will supply instances of {@link OutputStreamWriter}, + * using the given {@link OutputStream} factory and character set. + * + * @param out the factory that will be used to open output streams + * @param charset the charset used to encode the output stream; see + * {@link Charsets} for helpful predefined constants + * @return the factory + * @deprecated Use {@link ByteSink#asCharSink(Charset)} instead. This method is + * scheduled for removal in Guava 18.0. + */ + @Deprecated + public static OutputSupplier newWriterSupplier(final OutputSupplier out, + final Charset charset) { + return asOutputSupplier(ByteStreams.asByteSink(out).asCharSink(charset)); + } + + /** + * Returns a {@link Writer} that simply discards written chars. + * + * @since 15.0 + */ + public static Writer nullWriter() { + return NullWriter.INSTANCE; } /** @@ -268,6 +432,35 @@ public final class CharStreams { } } + /** + * Streams lines from a {@link Readable} and {@link Closeable} object supplied + * by a factory, stopping when our callback returns false, or we have read all + * of the lines. + * + * @param supplier the factory to read from + * @param callback the LineProcessor to use to handle the lines + * @return the output of processing the lines + * @throws IOException if an I/O error occurs + * @deprecated Use {@link CharSource#readLines(LineProcessor)} instead. This + * method is scheduled for removal in Guava 18.0. + */ + @Deprecated + public static T readLines(InputSupplier supplier, LineProcessor callback) + throws IOException { + checkNotNull(supplier); + checkNotNull(callback); + + Closer closer = Closer.create(); + try { + R r = closer.register(supplier.getInput()); + return readLines(r, callback); + } catch (Throwable e) { + throw closer.rethrow(e); + } finally { + closer.close(); + } + } + /** * Reads all of the lines from a {@link Readable} object. The lines do not * include line-termination characters, but do include other leading and @@ -315,78 +508,6 @@ public final class CharStreams { return processor.getResult(); } - /** - * Streams lines from a {@link Readable} and {@link Closeable} object supplied - * by a factory, stopping when our callback returns false, or we have read all - * of the lines. - * - * @param supplier the factory to read from - * @param callback the LineProcessor to use to handle the lines - * @return the output of processing the lines - * @throws IOException if an I/O error occurs - * @deprecated Use {@link CharSource#readLines(LineProcessor)} instead. This - * method is scheduled for removal in Guava 18.0. - */ - @Deprecated - public static T readLines(InputSupplier supplier, LineProcessor callback) - throws IOException { - checkNotNull(supplier); - checkNotNull(callback); - - Closer closer = Closer.create(); - try { - R r = closer.register(supplier.getInput()); - return readLines(r, callback); - } catch (Throwable e) { - throw closer.rethrow(e); - } finally { - closer.close(); - } - } - - /** - * Joins multiple {@link Reader} suppliers into a single supplier. Reader - * returned from the supplier will contain the concatenated data from the - * readers of the underlying suppliers. - * - *

          - * Reading from the joined reader will throw a {@link NullPointerException} if - * any of the suppliers are null or return null. - * - *

          - * Only one underlying reader will be open at a time. Closing the joined reader - * will close the open underlying reader. - * - * @param suppliers the suppliers to concatenate - * @return a supplier that will return a reader containing the concatenated data - * @deprecated Use {@link CharSource#concat(Iterable)} instead. This method is - * scheduled for removal in Guava 18.0. - */ - @Deprecated - public static InputSupplier join(final Iterable> suppliers) { - checkNotNull(suppliers); - Iterable sources = Iterables.transform(suppliers, - new Function, CharSource>() { - @Override - public CharSource apply(InputSupplier input) { - return asCharSource(input); - } - }); - return asInputSupplier(CharSource.concat(sources)); - } - - /** - * Varargs form of {@link #join(Iterable)}. - * - * @deprecated Use {@link CharSource#concat(CharSource[])} instead. This method - * is scheduled for removal in Guava 18.0. - */ - @Deprecated - @SuppressWarnings("unchecked") // suppress "possible heap pollution" warning in JDK7 - public static InputSupplier join(InputSupplier... suppliers) { - return join(Arrays.asList(suppliers)); - } - /** * Discards {@code n} characters of data from the reader. This method will block * until the full amount has been skipped. Does not close the reader. @@ -413,185 +534,65 @@ public final class CharStreams { } } - /** - * Returns a {@link Writer} that simply discards written chars. - * - * @since 15.0 - */ - public static Writer nullWriter() { - return NullWriter.INSTANCE; - } - - private static final class NullWriter extends Writer { - - private static final NullWriter INSTANCE = new NullWriter(); - - @Override - public void write(int c) { - } - - @Override - public void write(char[] cbuf) { - checkNotNull(cbuf); - } - - @Override - public void write(char[] cbuf, int off, int len) { - checkPositionIndexes(off, off + len, cbuf.length); - } - - @Override - public void write(String str) { - checkNotNull(str); - } - - @Override - public void write(String str, int off, int len) { - checkPositionIndexes(off, off + len, str.length()); - } - - @Override - public Writer append(CharSequence csq) { - checkNotNull(csq); - return this; - } - - @Override - public Writer append(CharSequence csq, int start, int end) { - checkPositionIndexes(start, end, csq.length()); - return this; - } - - @Override - public Writer append(char c) { - return this; - } - - @Override - public void flush() { - } - - @Override - public void close() { - } - - @Override - public String toString() { - return "CharStreams.nullWriter()"; - } - } - - /** - * Returns a Writer that sends all output to the given {@link Appendable} - * target. Closing the writer will close the target if it is {@link Closeable}, - * and flushing the writer will flush the target if it is - * {@link java.io.Flushable}. - * - * @param target the object to which output will be sent - * @return a new Writer object, unless target is a Writer, in which case the - * target is returned - */ - public static Writer asWriter(Appendable target) { - if (target instanceof Writer) { - return (Writer) target; - } - return new AppendableWriter(target); - } - // TODO(user): Remove these once Input/OutputSupplier methods are removed - static Reader asReader(final Readable readable) { - checkNotNull(readable); - if (readable instanceof Reader) { - return (Reader) readable; - } - return new Reader() { - @Override - public int read(char[] cbuf, int off, int len) throws IOException { - return read(CharBuffer.wrap(cbuf, off, len)); - } - - @Override - public int read(CharBuffer target) throws IOException { - return readable.read(target); - } - - @Override - public void close() throws IOException { - if (readable instanceof Closeable) { - ((Closeable) readable).close(); - } - } - }; + /** + * Returns the characters from a {@link Readable} & {@link Closeable} object + * supplied by a factory as a {@link String}. + * + * @param supplier the factory to read from + * @return a string containing all the characters + * @throws IOException if an I/O error occurs + * @deprecated Use {@link CharSource#read()} instead. This method is scheduled + * for removal in Guava 18.0. + */ + @Deprecated + public static String toString(InputSupplier supplier) throws IOException { + return asCharSource(supplier).read(); } /** - * Returns a view of the given {@code Readable} supplier as a - * {@code CharSource}. + * Reads all characters from a {@link Readable} object into a {@link String}. + * Does not close the {@code Readable}. * - *

          - * This method is a temporary method provided for easing migration from - * suppliers to sources and sinks. - * - * @since 15.0 - * @deprecated Convert all {@code InputSupplier} - * implementations to extend {@link CharSource} or provide a method - * for viewing the object as a {@code CharSource}. This method is - * scheduled for removal in Guava 18.0. + * @param r the object to read from + * @return a string containing all the characters + * @throws IOException if an I/O error occurs */ - @Deprecated - public static CharSource asCharSource(final InputSupplier supplier) { - checkNotNull(supplier); - return new CharSource() { - @Override - public Reader openStream() throws IOException { - return asReader(supplier.getInput()); - } - - @Override - public String toString() { - return "CharStreams.asCharSource(" + supplier + ")"; - } - }; + public static String toString(Readable r) throws IOException { + return toStringBuilder(r).toString(); } /** - * Returns a view of the given {@code Appendable} supplier as a - * {@code CharSink}. + * Reads all characters from a {@link Readable} object into a new + * {@link StringBuilder} instance. Does not close the {@code Readable}. * - *

          - * This method is a temporary method provided for easing migration from - * suppliers to sources and sinks. + * @param r the object to read from + * @return a {@link StringBuilder} containing all the characters + * @throws IOException if an I/O error occurs + */ + private static StringBuilder toStringBuilder(Readable r) throws IOException { + StringBuilder sb = new StringBuilder(); + copy(r, sb); + return sb; + } + + /** + * Writes a character sequence (such as a string) to an appendable object from + * the given supplier. * - * @since 15.0 - * @deprecated Convert all {@code OutputSupplier} - * implementations to extend {@link CharSink} or provide a method - * for viewing the object as a {@code CharSink}. This method is + * @param from the character sequence to write + * @param to the output supplier + * @throws IOException if an I/O error occurs + * @deprecated Use {@link CharSink#write(CharSequence)} instead. This method is * scheduled for removal in Guava 18.0. */ @Deprecated - public static CharSink asCharSink(final OutputSupplier supplier) { - checkNotNull(supplier); - return new CharSink() { - @Override - public Writer openStream() throws IOException { - return asWriter(supplier.getOutput()); - } - - @Override - public String toString() { - return "CharStreams.asCharSink(" + supplier + ")"; - } - }; + public static void write(CharSequence from, OutputSupplier to) + throws IOException { + asCharSink(to).write(from); } - @SuppressWarnings("unchecked") // used internally where known to be safe - static InputSupplier asInputSupplier(CharSource source) { - return (InputSupplier) checkNotNull(source); - } - - @SuppressWarnings("unchecked") // used internally where known to be safe - static OutputSupplier asOutputSupplier(CharSink sink) { - return (OutputSupplier) checkNotNull(sink); + private CharStreams() { } } diff --git a/src/main/java/com/google/common/io/Closeables.java b/src/main/java/com/google/common/io/Closeables.java index 1b608f91..a7384480 100644 --- a/src/main/java/com/google/common/io/Closeables.java +++ b/src/main/java/com/google/common/io/Closeables.java @@ -39,9 +39,6 @@ public final class Closeables { @VisibleForTesting static final Logger logger = Logger.getLogger(Closeables.class.getName()); - private Closeables() { - } - /** * Closes a {@link Closeable}, with control over whether an {@code IOException} * may be thrown. This is primarily useful in a finally block, where a thrown @@ -58,17 +55,18 @@ public final class Closeables { *

           	 *    {@code
           	 *
          -	 *   public void useStreamNicely() throws IOException {
          -	 *     SomeStream stream = new SomeStream("foo");
          -	 *     boolean threw = true;
          -	 *     try {
          -	 *       // ... code which does something with the stream ...
          -	 *       threw = false;
          -	 *     } finally {
          -	 *       // If an exception occurs, rethrow it only if threw==false:
          -	 *       Closeables.close(stream, threw);
          -	 *     }
          -	 *   }}
          +	 * public void useStreamNicely() throws IOException {
          +	 * 	SomeStream stream = new SomeStream("foo");
          +	 * 	boolean threw = true;
          +	 * 	try {
          +	 * 		// ... code which does something with the stream ...
          +	 * 		threw = false;
          +	 * 	} finally {
          +	 * 		// If an exception occurs, rethrow it only if threw==false:
          +	 * 		Closeables.close(stream, threw);
          +	 * 	}
          +	 * }
          +	 * }
           	 * 
          * * @param closeable the {@code Closeable} object to be closed, or null, @@ -140,4 +138,7 @@ public final class Closeables { throw new AssertionError(impossible); } } + + private Closeables() { + } } diff --git a/src/main/java/com/google/common/io/Closer.java b/src/main/java/com/google/common/io/Closer.java index 5ca7fad8..04cc6a8c 100644 --- a/src/main/java/com/google/common/io/Closer.java +++ b/src/main/java/com/google/common/io/Closer.java @@ -105,6 +105,74 @@ import com.google.common.base.Throwables; @Beta public final class Closer implements Closeable { + /** + * Suppresses exceptions by logging them. + */ + @VisibleForTesting + static final class LoggingSuppressor implements Suppressor { + + static final LoggingSuppressor INSTANCE = new LoggingSuppressor(); + + @Override + public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { + // log to the same place as Closeables + Closeables.logger.log(Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); + } + } + + /** + * Suppresses exceptions by adding them to the exception that will be thrown + * using JDK7's addSuppressed(Throwable) mechanism. + */ + @VisibleForTesting + static final class SuppressingSuppressor implements Suppressor { + + static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor(); + + static final Method addSuppressed = getAddSuppressed(); + + private static Method getAddSuppressed() { + try { + return Throwable.class.getMethod("addSuppressed", Throwable.class); + } catch (Throwable e) { + return null; + } + } + + static boolean isAvailable() { + return addSuppressed != null; + } + + @Override + public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { + // ensure no exceptions from addSuppressed + if (thrown == suppressed) { + return; + } + try { + addSuppressed.invoke(thrown, suppressed); + } catch (Throwable e) { + // if, somehow, IllegalAccessException or another exception is thrown, fall back + // to logging + LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed); + } + } + } + + /** + * Suppression strategy interface. + */ + @VisibleForTesting + interface Suppressor { + /** + * Suppresses the given exception ({@code suppressed}) which was thrown when + * attempting to close the given closeable. {@code thrown} is the exception that + * is actually being thrown from the method. Implementations of this method + * should not throw under any circumstances. + */ + void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); + } + /** * The suppressor implementation to use for the current Java version. */ @@ -124,6 +192,7 @@ public final class Closer implements Closeable { // only need space for 2 elements in most cases, so try to use the smallest // array possible private final Deque stack = new ArrayDeque(4); + private Throwable thrown; @VisibleForTesting @@ -131,6 +200,38 @@ public final class Closer implements Closeable { this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests } + /** + * Closes all {@code Closeable} instances that have been added to this + * {@code Closer}. If an exception was thrown in the try block and passed to one + * of the {@code exceptionThrown} methods, any exceptions thrown when attempting + * to close a closeable will be suppressed. Otherwise, the first + * exception to be thrown from an attempt to close a closeable will be thrown + * and any additional exceptions that are thrown after that will be suppressed. + */ + @Override + public void close() throws IOException { + Throwable throwable = thrown; + + // close closeables in LIFO order + while (!stack.isEmpty()) { + Closeable closeable = stack.removeFirst(); + try { + closeable.close(); + } catch (Throwable e) { + if (throwable == null) { + throwable = e; + } else { + suppressor.suppress(closeable, throwable, e); + } + } + } + + if (thrown == null && throwable != null) { + Throwables.propagateIfPossible(throwable, IOException.class); + throw new AssertionError(throwable); // not possible + } + } + /** * Registers the given {@code closeable} to be closed when this {@code Closer} * is {@linkplain #close closed}. @@ -221,104 +322,4 @@ public final class Closer implements Closeable { Throwables.propagateIfPossible(e, declaredType1, declaredType2); throw new RuntimeException(e); } - - /** - * Closes all {@code Closeable} instances that have been added to this - * {@code Closer}. If an exception was thrown in the try block and passed to one - * of the {@code exceptionThrown} methods, any exceptions thrown when attempting - * to close a closeable will be suppressed. Otherwise, the first - * exception to be thrown from an attempt to close a closeable will be thrown - * and any additional exceptions that are thrown after that will be suppressed. - */ - @Override - public void close() throws IOException { - Throwable throwable = thrown; - - // close closeables in LIFO order - while (!stack.isEmpty()) { - Closeable closeable = stack.removeFirst(); - try { - closeable.close(); - } catch (Throwable e) { - if (throwable == null) { - throwable = e; - } else { - suppressor.suppress(closeable, throwable, e); - } - } - } - - if (thrown == null && throwable != null) { - Throwables.propagateIfPossible(throwable, IOException.class); - throw new AssertionError(throwable); // not possible - } - } - - /** - * Suppression strategy interface. - */ - @VisibleForTesting - interface Suppressor { - /** - * Suppresses the given exception ({@code suppressed}) which was thrown when - * attempting to close the given closeable. {@code thrown} is the exception that - * is actually being thrown from the method. Implementations of this method - * should not throw under any circumstances. - */ - void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); - } - - /** - * Suppresses exceptions by logging them. - */ - @VisibleForTesting - static final class LoggingSuppressor implements Suppressor { - - static final LoggingSuppressor INSTANCE = new LoggingSuppressor(); - - @Override - public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { - // log to the same place as Closeables - Closeables.logger.log(Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); - } - } - - /** - * Suppresses exceptions by adding them to the exception that will be thrown - * using JDK7's addSuppressed(Throwable) mechanism. - */ - @VisibleForTesting - static final class SuppressingSuppressor implements Suppressor { - - static final SuppressingSuppressor INSTANCE = new SuppressingSuppressor(); - - static boolean isAvailable() { - return addSuppressed != null; - } - - static final Method addSuppressed = getAddSuppressed(); - - private static Method getAddSuppressed() { - try { - return Throwable.class.getMethod("addSuppressed", Throwable.class); - } catch (Throwable e) { - return null; - } - } - - @Override - public void suppress(Closeable closeable, Throwable thrown, Throwable suppressed) { - // ensure no exceptions from addSuppressed - if (thrown == suppressed) { - return; - } - try { - addSuppressed.invoke(thrown, suppressed); - } catch (Throwable e) { - // if, somehow, IllegalAccessException or another exception is thrown, fall back - // to logging - LoggingSuppressor.INSTANCE.suppress(closeable, thrown, suppressed); - } - } - } } diff --git a/src/main/java/com/google/common/io/CountingInputStream.java b/src/main/java/com/google/common/io/CountingInputStream.java index ec91df0a..44d44370 100644 --- a/src/main/java/com/google/common/io/CountingInputStream.java +++ b/src/main/java/com/google/common/io/CountingInputStream.java @@ -50,6 +50,13 @@ public final class CountingInputStream extends FilterInputStream { return count; } + @Override + public synchronized void mark(int readlimit) { + in.mark(readlimit); + mark = count; + // it's okay to mark even if mark isn't supported, as reset won't work + } + @Override public int read() throws IOException { int result = in.read(); @@ -68,20 +75,6 @@ public final class CountingInputStream extends FilterInputStream { return result; } - @Override - public long skip(long n) throws IOException { - long result = in.skip(n); - count += result; - return result; - } - - @Override - public synchronized void mark(int readlimit) { - in.mark(readlimit); - mark = count; - // it's okay to mark even if mark isn't supported, as reset won't work - } - @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { @@ -94,4 +87,11 @@ public final class CountingInputStream extends FilterInputStream { in.reset(); count = mark; } + + @Override + public long skip(long n) throws IOException { + long result = in.skip(n); + count += result; + return result; + } } diff --git a/src/main/java/com/google/common/io/CountingOutputStream.java b/src/main/java/com/google/common/io/CountingOutputStream.java index d7f4f837..c5f86e67 100644 --- a/src/main/java/com/google/common/io/CountingOutputStream.java +++ b/src/main/java/com/google/common/io/CountingOutputStream.java @@ -44,6 +44,16 @@ public final class CountingOutputStream extends FilterOutputStream { super(out); } + // Overriding close() because FilterOutputStream's close() method pre-JDK8 has + // bad behavior: + // it silently ignores any exception thrown by flush(). Instead, just close the + // delegate stream. + // It should flush itself if necessary. + @Override + public void close() throws IOException { + out.close(); + } + /** Returns the number of bytes written. */ public long getCount() { return count; @@ -60,14 +70,4 @@ public final class CountingOutputStream extends FilterOutputStream { out.write(b); count++; } - - // Overriding close() because FilterOutputStream's close() method pre-JDK8 has - // bad behavior: - // it silently ignores any exception thrown by flush(). Instead, just close the - // delegate stream. - // It should flush itself if necessary. - @Override - public void close() throws IOException { - out.close(); - } } diff --git a/src/main/java/com/google/common/io/Flushables.java b/src/main/java/com/google/common/io/Flushables.java index 6c70f9d6..94ccbd2e 100644 --- a/src/main/java/com/google/common/io/Flushables.java +++ b/src/main/java/com/google/common/io/Flushables.java @@ -33,9 +33,6 @@ import com.google.common.annotations.Beta; public final class Flushables { private static final Logger logger = Logger.getLogger(Flushables.class.getName()); - private Flushables() { - } - /** * Flush a {@link Flushable}, with control over whether an {@code IOException} * may be thrown. @@ -76,4 +73,7 @@ public final class Flushables { logger.log(Level.SEVERE, "IOException should not have been thrown.", e); } } + + private Flushables() { + } } diff --git a/src/main/java/com/google/common/io/GwtWorkarounds.java b/src/main/java/com/google/common/io/GwtWorkarounds.java index 7c28dd70..fdedd996 100644 --- a/src/main/java/com/google/common/io/GwtWorkarounds.java +++ b/src/main/java/com/google/common/io/GwtWorkarounds.java @@ -36,35 +36,44 @@ import com.google.common.annotations.GwtIncompatible; */ @GwtCompatible(emulated = true) final class GwtWorkarounds { - private GwtWorkarounds() { + /** + * A GWT-compatible substitute for an {@code InputStream}. + */ + interface ByteInput { + void close() throws IOException; + + int read() throws IOException; + } + + /** + * A GWT-compatible substitute for an {@code OutputStream}. + */ + interface ByteOutput { + void close() throws IOException; + + void flush() throws IOException; + + void write(byte b) throws IOException; } /** * A GWT-compatible substitute for a {@code Reader}. */ interface CharInput { - int read() throws IOException; - void close() throws IOException; + + int read() throws IOException; } /** - * Views a {@code Reader} as a {@code CharInput}. + * A GWT-compatible substitute for a {@code Writer}. */ - @GwtIncompatible("Reader") - static CharInput asCharInput(final Reader reader) { - checkNotNull(reader); - return new CharInput() { - @Override - public int read() throws IOException { - return reader.read(); - } + interface CharOutput { + void close() throws IOException; - @Override - public void close() throws IOException { - reader.close(); - } - }; + void flush() throws IOException; + + void write(char c) throws IOException; } /** @@ -75,6 +84,11 @@ final class GwtWorkarounds { return new CharInput() { int index = 0; + @Override + public void close() { + index = chars.length(); + } + @Override public int read() { if (index < chars.length()) { @@ -83,21 +97,50 @@ final class GwtWorkarounds { return -1; } } + }; + } + + /** + * Views a {@code Reader} as a {@code CharInput}. + */ + @GwtIncompatible("Reader") + static CharInput asCharInput(final Reader reader) { + checkNotNull(reader); + return new CharInput() { + @Override + public void close() throws IOException { + reader.close(); + } @Override - public void close() { - index = chars.length(); + public int read() throws IOException { + return reader.read(); } }; } /** - * A GWT-compatible substitute for an {@code InputStream}. + * Views a {@code Writer} as a {@code CharOutput}. */ - interface ByteInput { - int read() throws IOException; + @GwtIncompatible("Writer") + static CharOutput asCharOutput(final Writer writer) { + checkNotNull(writer); + return new CharOutput() { + @Override + public void close() throws IOException { + writer.close(); + } - void close() throws IOException; + @Override + public void flush() throws IOException { + writer.flush(); + } + + @Override + public void write(char c) throws IOException { + writer.append(c); + } + }; } /** @@ -107,6 +150,11 @@ final class GwtWorkarounds { static InputStream asInputStream(final ByteInput input) { checkNotNull(input); return new InputStream() { + @Override + public void close() throws IOException { + input.close(); + } + @Override public int read() throws IOException { return input.read(); @@ -133,25 +181,9 @@ final class GwtWorkarounds { } return len; } - - @Override - public void close() throws IOException { - input.close(); - } }; } - /** - * A GWT-compatible substitute for an {@code OutputStream}. - */ - interface ByteOutput { - void write(byte b) throws IOException; - - void flush() throws IOException; - - void close() throws IOException; - } - /** * Views a {@code ByteOutput} as an {@code OutputStream}. */ @@ -160,8 +192,8 @@ final class GwtWorkarounds { checkNotNull(output); return new OutputStream() { @Override - public void write(int b) throws IOException { - output.write((byte) b); + public void close() throws IOException { + output.close(); } @Override @@ -170,43 +202,8 @@ final class GwtWorkarounds { } @Override - public void close() throws IOException { - output.close(); - } - }; - } - - /** - * A GWT-compatible substitute for a {@code Writer}. - */ - interface CharOutput { - void write(char c) throws IOException; - - void flush() throws IOException; - - void close() throws IOException; - } - - /** - * Views a {@code Writer} as a {@code CharOutput}. - */ - @GwtIncompatible("Writer") - static CharOutput asCharOutput(final Writer writer) { - checkNotNull(writer); - return new CharOutput() { - @Override - public void write(char c) throws IOException { - writer.append(c); - } - - @Override - public void flush() throws IOException { - writer.flush(); - } - - @Override - public void close() throws IOException { - writer.close(); + public void write(int b) throws IOException { + output.write((byte) b); } }; } @@ -220,22 +217,25 @@ final class GwtWorkarounds { return new CharOutput() { @Override - public void write(char c) { - builder.append(c); + public void close() { } @Override public void flush() { } - @Override - public void close() { - } - @Override public String toString() { return builder.toString(); } + + @Override + public void write(char c) { + builder.append(c); + } }; } + + private GwtWorkarounds() { + } } diff --git a/src/main/java/com/google/common/io/LineBuffer.java b/src/main/java/com/google/common/io/LineBuffer.java index cacd1f3a..e633e1ea 100644 --- a/src/main/java/com/google/common/io/LineBuffer.java +++ b/src/main/java/com/google/common/io/LineBuffer.java @@ -84,14 +84,6 @@ abstract class LineBuffer { line.append(cbuf, start, off + len - start); } - /** Called when a line is complete. */ - private boolean finishLine(boolean sawNewline) throws IOException { - handleLine(line.toString(), sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : "")); - line = new StringBuilder(); - sawReturn = false; - return sawNewline; - } - /** * Subclasses must call this method after finishing character processing, in * order to ensure that any unterminated line in the buffer is passed to @@ -105,6 +97,14 @@ abstract class LineBuffer { } } + /** Called when a line is complete. */ + private boolean finishLine(boolean sawNewline) throws IOException { + handleLine(line.toString(), sawReturn ? (sawNewline ? "\r\n" : "\r") : (sawNewline ? "\n" : "")); + line = new StringBuilder(); + sawReturn = false; + return sawNewline; + } + /** * Called for each line found in the character data passed to {@link #add}. * diff --git a/src/main/java/com/google/common/io/LineProcessor.java b/src/main/java/com/google/common/io/LineProcessor.java index b6d866c5..00cc6a24 100644 --- a/src/main/java/com/google/common/io/LineProcessor.java +++ b/src/main/java/com/google/common/io/LineProcessor.java @@ -33,6 +33,9 @@ import com.google.common.annotations.Beta; @Beta public interface LineProcessor { + /** Return the result of processing all the lines. */ + T getResult(); + /** * This method will be called once for each line. * @@ -40,7 +43,4 @@ public interface LineProcessor { * @return true to continue processing, false to stop */ boolean processLine(String line) throws IOException; - - /** Return the result of processing all the lines. */ - T getResult(); } diff --git a/src/main/java/com/google/common/io/LittleEndianDataInputStream.java b/src/main/java/com/google/common/io/LittleEndianDataInputStream.java index 25c5fdf5..f005df66 100644 --- a/src/main/java/com/google/common/io/LittleEndianDataInputStream.java +++ b/src/main/java/com/google/common/io/LittleEndianDataInputStream.java @@ -53,11 +53,70 @@ public final class LittleEndianDataInputStream extends FilterInputStream impleme } /** - * This method will throw an {@link UnsupportedOperationException}. + * Reads a byte from the input stream checking that the end of file (EOF) has + * not been encountered. + * + * @return byte read from input + * @throws IOException if an error is encountered while reading + * @throws EOFException if the end of file (EOF) is encountered. + */ + private byte readAndCheckByte() throws IOException, EOFException { + int b1 = in.read(); + + if (-1 == b1) { + throw new EOFException(); + } + + return (byte) b1; + } + + @Override + public boolean readBoolean() throws IOException { + return readUnsignedByte() != 0; + } + + @Override + public byte readByte() throws IOException { + return (byte) readUnsignedByte(); + } + + /** + * Reads a char as specified by {@link DataInputStream#readChar()}, except using + * little-endian byte order. + * + * @return the next two bytes of the input stream, interpreted as a {@code char} + * in little-endian byte order + * @throws IOException if an I/O error occurs */ @Override - public String readLine() { - throw new UnsupportedOperationException("readLine is not supported"); + public char readChar() throws IOException { + return (char) readUnsignedShort(); + } + + /** + * Reads a {@code double} as specified by {@link DataInputStream#readDouble()}, + * except using little-endian byte order. + * + * @return the next eight bytes of the input stream, interpreted as a + * {@code double} in little-endian byte order + * @throws IOException if an I/O error occurs + */ + @Override + public double readDouble() throws IOException { + return Double.longBitsToDouble(readLong()); + } + + /** + * Reads a {@code float} as specified by {@link DataInputStream#readFloat()}, + * except using little-endian byte order. + * + * @return the next four bytes of the input stream, interpreted as a + * {@code float} in little-endian byte order + * @throws IOException if an I/O error occurs + */ + @Override + public float readFloat() throws IOException { + return Float.intBitsToFloat(readInt()); } @Override @@ -70,9 +129,65 @@ public final class LittleEndianDataInputStream extends FilterInputStream impleme ByteStreams.readFully(this, b, off, len); } + /** + * Reads an integer as specified by {@link DataInputStream#readInt()}, except + * using little-endian byte order. + * + * @return the next four bytes of the input stream, interpreted as an + * {@code int} in little-endian byte order + * @throws IOException if an I/O error occurs + */ @Override - public int skipBytes(int n) throws IOException { - return (int) in.skip(n); + public int readInt() throws IOException { + byte b1 = readAndCheckByte(); + byte b2 = readAndCheckByte(); + byte b3 = readAndCheckByte(); + byte b4 = readAndCheckByte(); + + return Ints.fromBytes(b4, b3, b2, b1); + } + + /** + * This method will throw an {@link UnsupportedOperationException}. + */ + @Override + public String readLine() { + throw new UnsupportedOperationException("readLine is not supported"); + } + + /** + * Reads a {@code long} as specified by {@link DataInputStream#readLong()}, + * except using little-endian byte order. + * + * @return the next eight bytes of the input stream, interpreted as a + * {@code long} in little-endian byte order + * @throws IOException if an I/O error occurs + */ + @Override + public long readLong() throws IOException { + byte b1 = readAndCheckByte(); + byte b2 = readAndCheckByte(); + byte b3 = readAndCheckByte(); + byte b4 = readAndCheckByte(); + byte b5 = readAndCheckByte(); + byte b6 = readAndCheckByte(); + byte b7 = readAndCheckByte(); + byte b8 = readAndCheckByte(); + + return Longs.fromBytes(b8, b7, b6, b5, b4, b3, b2, b1); + } + + /** + * Reads a {@code short} as specified by {@link DataInputStream#readShort()}, + * except using little-endian byte order. + * + * @return the next two bytes of the input stream, interpreted as a + * {@code short} in little-endian byte order. + * @throws IOException if an I/O error occurs. + */ + @Override + public short readShort() throws IOException { + return (short) readUnsignedShort(); } @Override @@ -102,129 +217,14 @@ public final class LittleEndianDataInputStream extends FilterInputStream impleme return Ints.fromBytes((byte) 0, (byte) 0, b2, b1); } - /** - * Reads an integer as specified by {@link DataInputStream#readInt()}, except - * using little-endian byte order. - * - * @return the next four bytes of the input stream, interpreted as an - * {@code int} in little-endian byte order - * @throws IOException if an I/O error occurs - */ - @Override - public int readInt() throws IOException { - byte b1 = readAndCheckByte(); - byte b2 = readAndCheckByte(); - byte b3 = readAndCheckByte(); - byte b4 = readAndCheckByte(); - - return Ints.fromBytes(b4, b3, b2, b1); - } - - /** - * Reads a {@code long} as specified by {@link DataInputStream#readLong()}, - * except using little-endian byte order. - * - * @return the next eight bytes of the input stream, interpreted as a - * {@code long} in little-endian byte order - * @throws IOException if an I/O error occurs - */ - @Override - public long readLong() throws IOException { - byte b1 = readAndCheckByte(); - byte b2 = readAndCheckByte(); - byte b3 = readAndCheckByte(); - byte b4 = readAndCheckByte(); - byte b5 = readAndCheckByte(); - byte b6 = readAndCheckByte(); - byte b7 = readAndCheckByte(); - byte b8 = readAndCheckByte(); - - return Longs.fromBytes(b8, b7, b6, b5, b4, b3, b2, b1); - } - - /** - * Reads a {@code float} as specified by {@link DataInputStream#readFloat()}, - * except using little-endian byte order. - * - * @return the next four bytes of the input stream, interpreted as a - * {@code float} in little-endian byte order - * @throws IOException if an I/O error occurs - */ - @Override - public float readFloat() throws IOException { - return Float.intBitsToFloat(readInt()); - } - - /** - * Reads a {@code double} as specified by {@link DataInputStream#readDouble()}, - * except using little-endian byte order. - * - * @return the next eight bytes of the input stream, interpreted as a - * {@code double} in little-endian byte order - * @throws IOException if an I/O error occurs - */ - @Override - public double readDouble() throws IOException { - return Double.longBitsToDouble(readLong()); - } - @Override public String readUTF() throws IOException { return new DataInputStream(in).readUTF(); } - /** - * Reads a {@code short} as specified by {@link DataInputStream#readShort()}, - * except using little-endian byte order. - * - * @return the next two bytes of the input stream, interpreted as a - * {@code short} in little-endian byte order. - * @throws IOException if an I/O error occurs. - */ @Override - public short readShort() throws IOException { - return (short) readUnsignedShort(); - } - - /** - * Reads a char as specified by {@link DataInputStream#readChar()}, except using - * little-endian byte order. - * - * @return the next two bytes of the input stream, interpreted as a {@code char} - * in little-endian byte order - * @throws IOException if an I/O error occurs - */ - @Override - public char readChar() throws IOException { - return (char) readUnsignedShort(); - } - - @Override - public byte readByte() throws IOException { - return (byte) readUnsignedByte(); - } - - @Override - public boolean readBoolean() throws IOException { - return readUnsignedByte() != 0; - } - - /** - * Reads a byte from the input stream checking that the end of file (EOF) has - * not been encountered. - * - * @return byte read from input - * @throws IOException if an error is encountered while reading - * @throws EOFException if the end of file (EOF) is encountered. - */ - private byte readAndCheckByte() throws IOException, EOFException { - int b1 = in.read(); - - if (-1 == b1) { - throw new EOFException(); - } - - return (byte) b1; + public int skipBytes(int n) throws IOException { + return (int) in.skip(n); } } diff --git a/src/main/java/com/google/common/io/LittleEndianDataOutputStream.java b/src/main/java/com/google/common/io/LittleEndianDataOutputStream.java index 7e71821f..77494f7f 100644 --- a/src/main/java/com/google/common/io/LittleEndianDataOutputStream.java +++ b/src/main/java/com/google/common/io/LittleEndianDataOutputStream.java @@ -51,6 +51,16 @@ public class LittleEndianDataOutputStream extends FilterOutputStream implements super(new DataOutputStream(Preconditions.checkNotNull(out))); } + // Overriding close() because FilterOutputStream's close() method pre-JDK8 has + // bad behavior: + // it silently ignores any exception thrown by flush(). Instead, just close the + // delegate stream. + // It should flush itself if necessary. + @Override + public void close() throws IOException { + out.close(); + } + @Override public void write(byte[] b, int off, int len) throws IOException { // Override slow FilterOutputStream impl @@ -171,14 +181,4 @@ public class LittleEndianDataOutputStream extends FilterOutputStream implements public void writeUTF(String str) throws IOException { ((DataOutputStream) out).writeUTF(str); } - - // Overriding close() because FilterOutputStream's close() method pre-JDK8 has - // bad behavior: - // it silently ignores any exception thrown by flush(). Instead, just close the - // delegate stream. - // It should flush itself if necessary. - @Override - public void close() throws IOException { - out.close(); - } } diff --git a/src/main/java/com/google/common/io/MultiInputStream.java b/src/main/java/com/google/common/io/MultiInputStream.java index c116c643..187bb1bb 100644 --- a/src/main/java/com/google/common/io/MultiInputStream.java +++ b/src/main/java/com/google/common/io/MultiInputStream.java @@ -46,17 +46,6 @@ final class MultiInputStream extends InputStream { advance(); } - @Override - public void close() throws IOException { - if (in != null) { - try { - in.close(); - } finally { - in = null; - } - } - } - /** * Closes the current input stream and opens the next one, if any. */ @@ -75,6 +64,17 @@ final class MultiInputStream extends InputStream { return in.available(); } + @Override + public void close() throws IOException { + if (in != null) { + try { + in.close(); + } finally { + in = null; + } + } + } + @Override public boolean markSupported() { return false; diff --git a/src/main/java/com/google/common/io/MultiReader.java b/src/main/java/com/google/common/io/MultiReader.java index a8d930b7..907e7ff5 100644 --- a/src/main/java/com/google/common/io/MultiReader.java +++ b/src/main/java/com/google/common/io/MultiReader.java @@ -49,6 +49,17 @@ class MultiReader extends Reader { } } + @Override + public void close() throws IOException { + if (current != null) { + try { + current.close(); + } finally { + current = null; + } + } + } + @Override public int read(@Nullable char cbuf[], int off, int len) throws IOException { if (current == null) { @@ -62,6 +73,11 @@ class MultiReader extends Reader { return result; } + @Override + public boolean ready() throws IOException { + return (current != null) && current.ready(); + } + @Override public long skip(long n) throws IOException { Preconditions.checkArgument(n >= 0, "n is negative"); @@ -76,20 +92,4 @@ class MultiReader extends Reader { } return 0; } - - @Override - public boolean ready() throws IOException { - return (current != null) && current.ready(); - } - - @Override - public void close() throws IOException { - if (current != null) { - try { - current.close(); - } finally { - current = null; - } - } - } } diff --git a/src/main/java/com/google/common/io/Resources.java b/src/main/java/com/google/common/io/Resources.java index 40fd2078..1df798c9 100644 --- a/src/main/java/com/google/common/io/Resources.java +++ b/src/main/java/com/google/common/io/Resources.java @@ -47,32 +47,6 @@ import com.google.common.collect.Lists; */ @Beta public final class Resources { - private Resources() { - } - - /** - * Returns a factory that will supply instances of {@link InputStream} that read - * from the given URL. - * - * @param url the URL to read from - * @return the factory - * @deprecated Use {@link #asByteSource(URL)} instead. This method is scheduled - * for removal in Guava 18.0. - */ - @Deprecated - public static InputSupplier newInputStreamSupplier(URL url) { - return ByteStreams.asInputSupplier(asByteSource(url)); - } - - /** - * Returns a {@link ByteSource} that reads from the given URL. - * - * @since 14.0 - */ - public static ByteSource asByteSource(URL url) { - return new UrlByteSource(url); - } - /** * A byte source that reads from a URL using {@link URL#openStream()}. */ @@ -95,6 +69,84 @@ public final class Resources { } } + /** + * Returns a {@link ByteSource} that reads from the given URL. + * + * @since 14.0 + */ + public static ByteSource asByteSource(URL url) { + return new UrlByteSource(url); + } + + /** + * Returns a {@link CharSource} that reads from the given URL using the given + * character set. + * + * @since 14.0 + */ + public static CharSource asCharSource(URL url, Charset charset) { + return asByteSource(url).asCharSource(charset); + } + + /** + * Copies all bytes from a URL to an output stream. + * + * @param from the URL to read from + * @param to the output stream + * @throws IOException if an I/O error occurs + */ + public static void copy(URL from, OutputStream to) throws IOException { + asByteSource(from).copyTo(to); + } + + /** + * Given a {@code resourceName} that is relative to {@code contextClass}, + * returns a {@code URL} pointing to the named resource. + * + * @throws IllegalArgumentException if the resource is not found + */ + public static URL getResource(Class contextClass, String resourceName) { + URL url = contextClass.getResource(resourceName); + checkArgument(url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName()); + return url; + } + + /** + * Returns a {@code URL} pointing to {@code resourceName} if the resource is + * found using the {@linkplain Thread#getContextClassLoader() context class + * loader}. In simple environments, the context class loader will find resources + * from the class path. In environments where different threads can have + * different class loaders, for example app servers, the context class loader + * will typically have been set to an appropriate loader for the current thread. + * + *

          + * In the unusual case where the context class loader is null, the class loader + * that loaded this class ({@code Resources}) will be used instead. + * + * @throws IllegalArgumentException if the resource is not found + */ + public static URL getResource(String resourceName) { + ClassLoader loader = Objects.firstNonNull(Thread.currentThread().getContextClassLoader(), + Resources.class.getClassLoader()); + URL url = loader.getResource(resourceName); + checkArgument(url != null, "resource %s not found.", resourceName); + return url; + } + + /** + * Returns a factory that will supply instances of {@link InputStream} that read + * from the given URL. + * + * @param url the URL to read from + * @return the factory + * @deprecated Use {@link #asByteSource(URL)} instead. This method is scheduled + * for removal in Guava 18.0. + */ + @Deprecated + public static InputSupplier newInputStreamSupplier(URL url) { + return ByteStreams.asInputSupplier(asByteSource(url)); + } + /** * Returns a factory that will supply instances of {@link InputStreamReader} * that read a URL using the given character set. @@ -112,13 +164,51 @@ public final class Resources { } /** - * Returns a {@link CharSource} that reads from the given URL using the given - * character set. + * Reads all of the lines from a URL. The lines do not include line-termination + * characters, but do include other leading and trailing whitespace. * - * @since 14.0 + *

          + * This method returns a mutable {@code List}. For an {@code ImmutableList}, use + * {@code Resources.asCharSource(url, charset).readLines()}. + * + * @param url the URL to read from + * @param charset the charset used to decode the input stream; see + * {@link Charsets} for helpful predefined constants + * @return a mutable {@link List} containing all the lines + * @throws IOException if an I/O error occurs */ - public static CharSource asCharSource(URL url, Charset charset) { - return asByteSource(url).asCharSource(charset); + public static List readLines(URL url, Charset charset) throws IOException { + // don't use asCharSource(url, charset).readLines() because that returns + // an immutable list, which would change the behavior of this method + return readLines(url, charset, new LineProcessor>() { + final List result = Lists.newArrayList(); + + @Override + public List getResult() { + return result; + } + + @Override + public boolean processLine(String line) { + result.add(line); + return true; + } + }); + } + + /** + * Streams lines from a URL, stopping when our callback returns false, or we + * have read all of the lines. + * + * @param url the URL to read from + * @param charset the charset used to decode the input stream; see + * {@link Charsets} for helpful predefined constants + * @param callback the LineProcessor to use to handle the lines + * @return the output of processing the lines + * @throws IOException if an I/O error occurs + */ + public static T readLines(URL url, Charset charset, LineProcessor callback) throws IOException { + return CharStreams.readLines(newReaderSupplier(url, charset), callback); } /** @@ -146,96 +236,6 @@ public final class Resources { return asCharSource(url, charset).read(); } - /** - * Streams lines from a URL, stopping when our callback returns false, or we - * have read all of the lines. - * - * @param url the URL to read from - * @param charset the charset used to decode the input stream; see - * {@link Charsets} for helpful predefined constants - * @param callback the LineProcessor to use to handle the lines - * @return the output of processing the lines - * @throws IOException if an I/O error occurs - */ - public static T readLines(URL url, Charset charset, LineProcessor callback) throws IOException { - return CharStreams.readLines(newReaderSupplier(url, charset), callback); - } - - /** - * Reads all of the lines from a URL. The lines do not include line-termination - * characters, but do include other leading and trailing whitespace. - * - *

          - * This method returns a mutable {@code List}. For an {@code ImmutableList}, use - * {@code Resources.asCharSource(url, charset).readLines()}. - * - * @param url the URL to read from - * @param charset the charset used to decode the input stream; see - * {@link Charsets} for helpful predefined constants - * @return a mutable {@link List} containing all the lines - * @throws IOException if an I/O error occurs - */ - public static List readLines(URL url, Charset charset) throws IOException { - // don't use asCharSource(url, charset).readLines() because that returns - // an immutable list, which would change the behavior of this method - return readLines(url, charset, new LineProcessor>() { - final List result = Lists.newArrayList(); - - @Override - public boolean processLine(String line) { - result.add(line); - return true; - } - - @Override - public List getResult() { - return result; - } - }); - } - - /** - * Copies all bytes from a URL to an output stream. - * - * @param from the URL to read from - * @param to the output stream - * @throws IOException if an I/O error occurs - */ - public static void copy(URL from, OutputStream to) throws IOException { - asByteSource(from).copyTo(to); - } - - /** - * Returns a {@code URL} pointing to {@code resourceName} if the resource is - * found using the {@linkplain Thread#getContextClassLoader() context class - * loader}. In simple environments, the context class loader will find resources - * from the class path. In environments where different threads can have - * different class loaders, for example app servers, the context class loader - * will typically have been set to an appropriate loader for the current thread. - * - *

          - * In the unusual case where the context class loader is null, the class loader - * that loaded this class ({@code Resources}) will be used instead. - * - * @throws IllegalArgumentException if the resource is not found - */ - public static URL getResource(String resourceName) { - ClassLoader loader = Objects.firstNonNull(Thread.currentThread().getContextClassLoader(), - Resources.class.getClassLoader()); - URL url = loader.getResource(resourceName); - checkArgument(url != null, "resource %s not found.", resourceName); - return url; - } - - /** - * Given a {@code resourceName} that is relative to {@code contextClass}, - * returns a {@code URL} pointing to the named resource. - * - * @throws IllegalArgumentException if the resource is not found - */ - public static URL getResource(Class contextClass, String resourceName) { - URL url = contextClass.getResource(resourceName); - checkArgument(url != null, "resource %s relative to %s not found.", resourceName, contextClass.getName()); - return url; + private Resources() { } } diff --git a/src/main/java/com/google/common/math/BigIntegerMath.java b/src/main/java/com/google/common/math/BigIntegerMath.java index 3efbfb6c..63470f6f 100644 --- a/src/main/java/com/google/common/math/BigIntegerMath.java +++ b/src/main/java/com/google/common/math/BigIntegerMath.java @@ -51,65 +51,6 @@ import com.google.common.annotations.VisibleForTesting; */ @GwtCompatible(emulated = true) public final class BigIntegerMath { - /** - * Returns {@code true} if {@code x} represents a power of two. - */ - public static boolean isPowerOfTwo(BigInteger x) { - checkNotNull(x); - return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1; - } - - /** - * Returns the base-2 logarithm of {@code x}, rounded according to the specified - * rounding mode. - * - * @throws IllegalArgumentException if {@code x <= 0} - * @throws ArithmeticException if {@code mode} is - * {@link RoundingMode#UNNECESSARY} and - * {@code x} is not a power of two - */ - @SuppressWarnings("fallthrough") - // TODO(kevinb): remove after this warning is disabled globally - public static int log2(BigInteger x, RoundingMode mode) { - checkPositive("x", checkNotNull(x)); - int logFloor = x.bitLength() - 1; - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through - case DOWN: - case FLOOR: - return logFloor; - - case UP: - case CEILING: - return isPowerOfTwo(x) ? logFloor : logFloor + 1; - - case HALF_DOWN: - case HALF_UP: - case HALF_EVEN: - if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) { - BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor); - if (x.compareTo(halfPower) <= 0) { - return logFloor; - } else { - return logFloor + 1; - } - } - /* - * Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 - * - * To determine which side of logFloor.5 the logarithm is, we compare x^2 to - * 2^(2 * logFloor + 1). - */ - BigInteger x2 = x.pow(2); - int logX2Floor = x2.bitLength() - 1; - return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1; - - default: - throw new AssertionError(); - } - } - /* * The maximum number of bits in a square root for which we'll precompute an * explicit half power of two. This can be any value, but higher values incur @@ -122,182 +63,62 @@ public final class BigIntegerMath { static final BigInteger SQRT2_PRECOMPUTED_BITS = new BigInteger( "16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16); - /** - * Returns the base-10 logarithm of {@code x}, rounded according to the - * specified rounding mode. - * - * @throws IllegalArgumentException if {@code x <= 0} - * @throws ArithmeticException if {@code mode} is - * {@link RoundingMode#UNNECESSARY} and - * {@code x} is not a power of ten - */ - @GwtIncompatible("TODO") - @SuppressWarnings("fallthrough") - public static int log10(BigInteger x, RoundingMode mode) { - checkPositive("x", x); - if (fitsInLong(x)) { - return LongMath.log10(x.longValue(), mode); - } - - int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10); - BigInteger approxPow = BigInteger.TEN.pow(approxLog10); - int approxCmp = approxPow.compareTo(x); - - /* - * We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) - * and 10^floor(log10(x)). - */ - - if (approxCmp > 0) { - /* - * The code is written so that even completely incorrect approximations will - * still yield the correct answer eventually, but in practice this branch should - * almost never be entered, and even then the loop should not run more than - * once. - */ - do { - approxLog10--; - approxPow = approxPow.divide(BigInteger.TEN); - approxCmp = approxPow.compareTo(x); - } while (approxCmp > 0); - } else { - BigInteger nextPow = BigInteger.TEN.multiply(approxPow); - int nextCmp = nextPow.compareTo(x); - while (nextCmp <= 0) { - approxLog10++; - approxPow = nextPow; - approxCmp = nextCmp; - nextPow = BigInteger.TEN.multiply(approxPow); - nextCmp = nextPow.compareTo(x); - } - } - - int floorLog = approxLog10; - BigInteger floorPow = approxPow; - int floorCmp = approxCmp; - - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(floorCmp == 0); - // fall through - case FLOOR: - case DOWN: - return floorLog; - - case CEILING: - case UP: - return floorPow.equals(x) ? floorLog : floorLog + 1; - - case HALF_DOWN: - case HALF_UP: - case HALF_EVEN: - // Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5 - BigInteger x2 = x.pow(2); - BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN); - return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1; - default: - throw new AssertionError(); - } - } - private static final double LN_10 = Math.log(10); + private static final double LN_2 = Math.log(2); /** - * Returns the square root of {@code x}, rounded with the specified rounding - * mode. + * Returns {@code n} choose {@code k}, also known as the binomial coefficient of + * {@code n} and {@code k}, that is, {@code n! / (k! (n - k)!)}. * - * @throws IllegalArgumentException if {@code x < 0} - * @throws ArithmeticException if {@code mode} is - * {@link RoundingMode#UNNECESSARY} and - * {@code sqrt(x)} is not an integer + *

          + * Warning: the result can take as much as O(k log n) space. + * + * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or + * {@code k > n} */ - @GwtIncompatible("TODO") - @SuppressWarnings("fallthrough") - public static BigInteger sqrt(BigInteger x, RoundingMode mode) { - checkNonNegative("x", x); - if (fitsInLong(x)) { - return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode)); + public static BigInteger binomial(int n, int k) { + checkNonNegative("n", n); + checkNonNegative("k", k); + checkArgument(k <= n, "k (%s) > n (%s)", k, n); + if (k > (n >> 1)) { + k = n - k; } - BigInteger sqrtFloor = sqrtFloor(x); - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through - case FLOOR: - case DOWN: - return sqrtFloor; - case CEILING: - case UP: - int sqrtFloorInt = sqrtFloor.intValue(); - boolean sqrtFloorIsExact = (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32 - && sqrtFloor.pow(2).equals(x); // slow exact check - return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); - case HALF_DOWN: - case HALF_UP: - case HALF_EVEN: - BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor); - /* - * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. - * Since both x and halfSquare are integers, this is equivalent to testing - * whether or not x <= halfSquare. - */ - return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); - default: - throw new AssertionError(); + if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) { + return BigInteger.valueOf(LongMath.binomial(n, k)); } - } - @GwtIncompatible("TODO") - private static BigInteger sqrtFloor(BigInteger x) { - /* - * Adapted from Hacker's Delight, Figure 11-1. - * - * Using DoubleUtils.bigToDouble, getting a double approximation of x is - * extremely fast, and then we can get a double approximation of the square - * root. Then, we iteratively improve this guess with an application of Newton's - * method, which sets guess := (guess + (x / guess)) / 2. This iteration has the - * following two properties: - * - * a) every iteration (except potentially the first) has guess >= - * floor(sqrt(x)). This is because guess' is the arithmetic mean of guess and x - * / guess, sqrt(x) is the geometric mean, and the arithmetic mean is always - * higher than the geometric mean. - * - * b) this iteration converges to floor(sqrt(x)). In fact, the number of correct - * digits doubles with each iteration, so this algorithm takes O(log(digits)) - * iterations. - * - * We start out with a double-precision approximation, which may be higher or - * lower than the true value. Therefore, we perform at least one Newton - * iteration to get a guess that's definitely >= floor(sqrt(x)), and then - * continue the iteration until we reach a fixed point. - */ - BigInteger sqrt0; - int log2 = log2(x, FLOOR); - if (log2 < Double.MAX_EXPONENT) { - sqrt0 = sqrtApproxWithDoubles(x); - } else { - int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even! - /* - * We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) - * will be 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift). - */ - sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1); - } - BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); - if (sqrt0.equals(sqrt1)) { - return sqrt0; - } - do { - sqrt0 = sqrt1; - sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); - } while (sqrt1.compareTo(sqrt0) < 0); - return sqrt0; - } + BigInteger accum = BigInteger.ONE; - @GwtIncompatible("TODO") - private static BigInteger sqrtApproxWithDoubles(BigInteger x) { - return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN); + long numeratorAccum = n; + long denominatorAccum = 1; + + int bits = LongMath.log2(n, RoundingMode.CEILING); + + int numeratorBits = bits; + + for (int i = 1; i < k; i++) { + int p = n - i; + int q = i + 1; + + // log2(p) >= bits - 1, because p >= n/2 + + if (numeratorBits + bits >= Long.SIZE - 1) { + // The numerator is as big as it can get without risking overflow. + // Multiply numeratorAccum / denominatorAccum into accum. + accum = accum.multiply(BigInteger.valueOf(numeratorAccum)).divide(BigInteger.valueOf(denominatorAccum)); + numeratorAccum = p; + denominatorAccum = q; + numeratorBits = bits; + } else { + // We can definitely multiply into the long accumulators without overflowing + // them. + numeratorAccum *= p; + denominatorAccum *= q; + numeratorBits += bits; + } + } + return accum.multiply(BigInteger.valueOf(numeratorAccum)).divide(BigInteger.valueOf(denominatorAccum)); } /** @@ -384,6 +205,20 @@ public final class BigIntegerMath { return listProduct(bignums).shiftLeft(shift); } + // Returns true if BigInteger.valueOf(x.longValue()).equals(x). + @GwtIncompatible("TODO") + static boolean fitsInLong(BigInteger x) { + return x.bitLength() <= Long.SIZE - 1; + } + + /** + * Returns {@code true} if {@code x} represents a power of two. + */ + public static boolean isPowerOfTwo(BigInteger x) { + checkNotNull(x); + return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1; + } + static BigInteger listProduct(List nums) { return listProduct(nums, 0, nums.size()); } @@ -406,63 +241,229 @@ public final class BigIntegerMath { } /** - * Returns {@code n} choose {@code k}, also known as the binomial coefficient of - * {@code n} and {@code k}, that is, {@code n! / (k! (n - k)!)}. + * Returns the base-10 logarithm of {@code x}, rounded according to the + * specified rounding mode. * - *

          - * Warning: the result can take as much as O(k log n) space. - * - * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or - * {@code k > n} + * @throws IllegalArgumentException if {@code x <= 0} + * @throws ArithmeticException if {@code mode} is + * {@link RoundingMode#UNNECESSARY} and + * {@code x} is not a power of ten */ - public static BigInteger binomial(int n, int k) { - checkNonNegative("n", n); - checkNonNegative("k", k); - checkArgument(k <= n, "k (%s) > n (%s)", k, n); - if (k > (n >> 1)) { - k = n - k; - } - if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) { - return BigInteger.valueOf(LongMath.binomial(n, k)); + @GwtIncompatible("TODO") + @SuppressWarnings("fallthrough") + public static int log10(BigInteger x, RoundingMode mode) { + checkPositive("x", x); + if (fitsInLong(x)) { + return LongMath.log10(x.longValue(), mode); } - BigInteger accum = BigInteger.ONE; + int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10); + BigInteger approxPow = BigInteger.TEN.pow(approxLog10); + int approxCmp = approxPow.compareTo(x); - long numeratorAccum = n; - long denominatorAccum = 1; + /* + * We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) + * and 10^floor(log10(x)). + */ - int bits = LongMath.log2(n, RoundingMode.CEILING); - - int numeratorBits = bits; - - for (int i = 1; i < k; i++) { - int p = n - i; - int q = i + 1; - - // log2(p) >= bits - 1, because p >= n/2 - - if (numeratorBits + bits >= Long.SIZE - 1) { - // The numerator is as big as it can get without risking overflow. - // Multiply numeratorAccum / denominatorAccum into accum. - accum = accum.multiply(BigInteger.valueOf(numeratorAccum)).divide(BigInteger.valueOf(denominatorAccum)); - numeratorAccum = p; - denominatorAccum = q; - numeratorBits = bits; - } else { - // We can definitely multiply into the long accumulators without overflowing - // them. - numeratorAccum *= p; - denominatorAccum *= q; - numeratorBits += bits; + if (approxCmp > 0) { + /* + * The code is written so that even completely incorrect approximations will + * still yield the correct answer eventually, but in practice this branch should + * almost never be entered, and even then the loop should not run more than + * once. + */ + do { + approxLog10--; + approxPow = approxPow.divide(BigInteger.TEN); + approxCmp = approxPow.compareTo(x); + } while (approxCmp > 0); + } else { + BigInteger nextPow = BigInteger.TEN.multiply(approxPow); + int nextCmp = nextPow.compareTo(x); + while (nextCmp <= 0) { + approxLog10++; + approxPow = nextPow; + approxCmp = nextCmp; + nextPow = BigInteger.TEN.multiply(approxPow); + nextCmp = nextPow.compareTo(x); } } - return accum.multiply(BigInteger.valueOf(numeratorAccum)).divide(BigInteger.valueOf(denominatorAccum)); + + int floorLog = approxLog10; + BigInteger floorPow = approxPow; + int floorCmp = approxCmp; + + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(floorCmp == 0); + // fall through + case FLOOR: + case DOWN: + return floorLog; + + case CEILING: + case UP: + return floorPow.equals(x) ? floorLog : floorLog + 1; + + case HALF_DOWN: + case HALF_UP: + case HALF_EVEN: + // Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5 + BigInteger x2 = x.pow(2); + BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN); + return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1; + default: + throw new AssertionError(); + } } - // Returns true if BigInteger.valueOf(x.longValue()).equals(x). + /** + * Returns the base-2 logarithm of {@code x}, rounded according to the specified + * rounding mode. + * + * @throws IllegalArgumentException if {@code x <= 0} + * @throws ArithmeticException if {@code mode} is + * {@link RoundingMode#UNNECESSARY} and + * {@code x} is not a power of two + */ + @SuppressWarnings("fallthrough") + // TODO(kevinb): remove after this warning is disabled globally + public static int log2(BigInteger x, RoundingMode mode) { + checkPositive("x", checkNotNull(x)); + int logFloor = x.bitLength() - 1; + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through + case DOWN: + case FLOOR: + return logFloor; + + case UP: + case CEILING: + return isPowerOfTwo(x) ? logFloor : logFloor + 1; + + case HALF_DOWN: + case HALF_UP: + case HALF_EVEN: + if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) { + BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight(SQRT2_PRECOMPUTE_THRESHOLD - logFloor); + if (x.compareTo(halfPower) <= 0) { + return logFloor; + } else { + return logFloor + 1; + } + } + /* + * Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 + * + * To determine which side of logFloor.5 the logarithm is, we compare x^2 to + * 2^(2 * logFloor + 1). + */ + BigInteger x2 = x.pow(2); + int logX2Floor = x2.bitLength() - 1; + return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1; + + default: + throw new AssertionError(); + } + } + + /** + * Returns the square root of {@code x}, rounded with the specified rounding + * mode. + * + * @throws IllegalArgumentException if {@code x < 0} + * @throws ArithmeticException if {@code mode} is + * {@link RoundingMode#UNNECESSARY} and + * {@code sqrt(x)} is not an integer + */ @GwtIncompatible("TODO") - static boolean fitsInLong(BigInteger x) { - return x.bitLength() <= Long.SIZE - 1; + @SuppressWarnings("fallthrough") + public static BigInteger sqrt(BigInteger x, RoundingMode mode) { + checkNonNegative("x", x); + if (fitsInLong(x)) { + return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode)); + } + BigInteger sqrtFloor = sqrtFloor(x); + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through + case FLOOR: + case DOWN: + return sqrtFloor; + case CEILING: + case UP: + int sqrtFloorInt = sqrtFloor.intValue(); + boolean sqrtFloorIsExact = (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32 + && sqrtFloor.pow(2).equals(x); // slow exact check + return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); + case HALF_DOWN: + case HALF_UP: + case HALF_EVEN: + BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor); + /* + * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. + * Since both x and halfSquare are integers, this is equivalent to testing + * whether or not x <= halfSquare. + */ + return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); + default: + throw new AssertionError(); + } + } + + @GwtIncompatible("TODO") + private static BigInteger sqrtApproxWithDoubles(BigInteger x) { + return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN); + } + + @GwtIncompatible("TODO") + private static BigInteger sqrtFloor(BigInteger x) { + /* + * Adapted from Hacker's Delight, Figure 11-1. + * + * Using DoubleUtils.bigToDouble, getting a double approximation of x is + * extremely fast, and then we can get a double approximation of the square + * root. Then, we iteratively improve this guess with an application of Newton's + * method, which sets guess := (guess + (x / guess)) / 2. This iteration has the + * following two properties: + * + * a) every iteration (except potentially the first) has guess >= + * floor(sqrt(x)). This is because guess' is the arithmetic mean of guess and x + * / guess, sqrt(x) is the geometric mean, and the arithmetic mean is always + * higher than the geometric mean. + * + * b) this iteration converges to floor(sqrt(x)). In fact, the number of correct + * digits doubles with each iteration, so this algorithm takes O(log(digits)) + * iterations. + * + * We start out with a double-precision approximation, which may be higher or + * lower than the true value. Therefore, we perform at least one Newton + * iteration to get a guess that's definitely >= floor(sqrt(x)), and then + * continue the iteration until we reach a fixed point. + */ + BigInteger sqrt0; + int log2 = log2(x, FLOOR); + if (log2 < Double.MAX_EXPONENT) { + sqrt0 = sqrtApproxWithDoubles(x); + } else { + int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even! + /* + * We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) + * will be 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift). + */ + sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1); + } + BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); + if (sqrt0.equals(sqrt1)) { + return sqrt0; + } + do { + sqrt0 = sqrt1; + sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); + } while (sqrt1.compareTo(sqrt0) < 0); + return sqrt0; } private BigIntegerMath() { diff --git a/src/main/java/com/google/common/math/DoubleMath.java b/src/main/java/com/google/common/math/DoubleMath.java index 26c01a5a..27485dad 100644 --- a/src/main/java/com/google/common/math/DoubleMath.java +++ b/src/main/java/com/google/common/math/DoubleMath.java @@ -50,6 +50,308 @@ import com.google.common.primitives.Booleans; */ @GwtCompatible(emulated = true) public final class DoubleMath { + @GwtIncompatible("com.google.common.math.DoubleUtils") + private static final class MeanAccumulator { + + private long count = 0; + private double mean = 0.0; + + void add(double value) { + checkArgument(isFinite(value)); + ++count; + // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) + mean += (value - mean) / count; + } + + double mean() { + checkArgument(count > 0, "Cannot take mean of 0 values"); + return mean; + } + } + + private static final double MIN_INT_AS_DOUBLE = -0x1p31; + + private static final double MAX_INT_AS_DOUBLE = 0x1p31 - 1.0; + private static final double MIN_LONG_AS_DOUBLE = -0x1p63; + + /* + * We cannot store Long.MAX_VALUE as a double without losing precision. Instead, + * we store Long.MAX_VALUE + 1 == -Long.MIN_VALUE, and then offset all + * comparisons by 1. + */ + private static final double MAX_LONG_AS_DOUBLE_PLUS_ONE = 0x1p63; + + private static final double LN_2 = log(2); + @VisibleForTesting + static final int MAX_FACTORIAL = 170; + + @VisibleForTesting + static final double[] everySixteenthFactorial = { 0x1.0p0, 0x1.30777758p44, 0x1.956ad0aae33a4p117, + 0x1.ee69a78d72cb6p202, 0x1.fe478ee34844ap295, 0x1.c619094edabffp394, 0x1.3638dd7bd6347p498, + 0x1.7cac197cfe503p605, 0x1.1e5dfc140e1e5p716, 0x1.8ce85fadb707ep829, 0x1.95d5f3d928edep945 }; + + /** + * Returns {@code n!}, that is, the product of the first {@code n} positive + * integers, {@code 1} if {@code n == 0}, or e n!}, or + * {@link Double#POSITIVE_INFINITY} if {@code n! > Double.MAX_VALUE}. + * + *

          + * The result is within 1 ulp of the true value. + * + * @throws IllegalArgumentException if {@code n < 0} + */ + public static double factorial(int n) { + checkNonNegative("n", n); + if (n > MAX_FACTORIAL) { + return Double.POSITIVE_INFINITY; + } else { + // Multiplying the last (n & 0xf) values into their own accumulator gives a more + // accurate + // result than multiplying by everySixteenthFactorial[n >> 4] directly. + double accum = 1.0; + for (int i = 1 + (n & ~0xf); i <= n; i++) { + accum *= i; + } + return accum * everySixteenthFactorial[n >> 4]; + } + } + + /** + * Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal + * values. + * + *

          + * This method is equivalent to + * {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a, b)}. In + * particular, like {@link Double#compare(double, double)}, it treats all NaN + * values as equal and greater than all other values (including + * {@link Double#POSITIVE_INFINITY}). + * + *

          + * This is not a total ordering and is not suitable for use in + * {@link Comparable#compareTo} implementations. In particular, it is not + * transitive. + * + * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN + * @since 13.0 + */ + public static int fuzzyCompare(double a, double b, double tolerance) { + if (fuzzyEquals(a, b, tolerance)) { + return 0; + } else if (a < b) { + return -1; + } else if (a > b) { + return 1; + } else { + return Booleans.compare(Double.isNaN(a), Double.isNaN(b)); + } + } + + /** + * Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} + * of each other. + * + *

          + * Technically speaking, this is equivalent to + * {@code Math.abs(a - b) <= tolerance || Double.valueOf(a).equals(Double.valueOf(b))}. + * + *

          + * Notable special cases include: + *

            + *
          • All NaNs are fuzzily equal. + *
          • If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal. + *
          • Positive and negative zero are always fuzzily equal. + *
          • If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, + * then {@code a} and {@code b} are fuzzily equal if and only if {@code a == b}. + *
          • With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are + * fuzzily equal. + *
          • With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code + * Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves.
          • + * + *

            + * This is reflexive and symmetric, but not transitive, so it is + * not an equivalence relation and not suitable for use in + * {@link Object#equals} implementations. + * + * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN + * @since 13.0 + */ + public static boolean fuzzyEquals(double a, double b, double tolerance) { + MathPreconditions.checkNonNegative("tolerance", tolerance); + return Math.copySign(a - b, 1.0) <= tolerance + // copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN + // semantics + || (a == b) // needed to ensure that infinities equal themselves + || (Double.isNaN(a) && Double.isNaN(b)); + } + + /** + * Returns {@code true} if {@code x} represents a mathematical integer. + * + *

            + * This is equivalent to, but not necessarily implemented as, the expression + * {@code + * !Double.isNaN(x) && !Double.isInfinite(x) && x == Math.rint(x)}. + */ + @GwtIncompatible("java.lang.Math.getExponent, com.google.common.math.DoubleUtils") + public static boolean isMathematicalInteger(double x) { + return isFinite(x) + && (x == 0.0 || SIGNIFICAND_BITS - Long.numberOfTrailingZeros(getSignificand(x)) <= getExponent(x)); + } + + /** + * Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some + * finite integer {@code k}. + */ + @GwtIncompatible("com.google.common.math.DoubleUtils") + public static boolean isPowerOfTwo(double x) { + return x > 0.0 && isFinite(x) && LongMath.isPowerOfTwo(getSignificand(x)); + } + + /** + * Returns the base 2 logarithm of a double value. + * + *

            + * Special cases: + *

              + *
            • If {@code x} is NaN or less than zero, the result is NaN. + *
            • If {@code x} is positive infinity, the result is positive infinity. + *
            • If {@code x} is positive or negative zero, the result is negative + * infinity. + *
            + * + *

            + * The computed result is within 1 ulp of the exact result. + * + *

            + * If the result of this method will be immediately rounded to an {@code int}, + * {@link #log2(double, RoundingMode)} is faster. + */ + public static double log2(double x) { + return log(x) / LN_2; // surprisingly within 1 ulp according to tests + } + + /** + * Returns the base 2 logarithm of a double value, rounded with the specified + * rounding mode to an {@code int}. + * + *

            + * Regardless of the rounding mode, this is faster than {@code (int) log2(x)}. + * + * @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or + * {@code x} is infinite + */ + @GwtIncompatible("java.lang.Math.getExponent, com.google.common.math.DoubleUtils") + @SuppressWarnings("fallthrough") + public static int log2(double x, RoundingMode mode) { + checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite"); + int exponent = getExponent(x); + if (!isNormal(x)) { + return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS; + // Do the calculation on a normal value. + } + // x is positive, finite, and normal + boolean increment; + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(isPowerOfTwo(x)); + // fall through + case FLOOR: + increment = false; + break; + case CEILING: + increment = !isPowerOfTwo(x); + break; + case DOWN: + increment = exponent < 0 & !isPowerOfTwo(x); + break; + case UP: + increment = exponent >= 0 & !isPowerOfTwo(x); + break; + case HALF_DOWN: + case HALF_EVEN: + case HALF_UP: + double xScaled = scaleNormalize(x); + // sqrt(2) is irrational, and the spec is relative to the "exact numerical + // result," + // so log2(x) is never exactly exponent + 0.5. + increment = (xScaled * xScaled) > 2.0; + break; + default: + throw new AssertionError(); + } + return increment ? exponent + 1 : exponent; + } + + /** + * Returns the arithmetic mean of the values. There must be at least one value, + * and they must all be finite. + */ + @GwtIncompatible("MeanAccumulator") + public static double mean(double... values) { + MeanAccumulator accumulator = new MeanAccumulator(); + for (double value : values) { + accumulator.add(value); + } + return accumulator.mean(); + } + + /** + * Returns the arithmetic mean of the values. There must be at least one value. + * The values will be converted to doubles, which does not cause any loss of + * precision for ints. + */ + @GwtIncompatible("MeanAccumulator") + public static double mean(int... values) { + MeanAccumulator accumulator = new MeanAccumulator(); + for (int value : values) { + accumulator.add(value); + } + return accumulator.mean(); + } + + /** + * Returns the arithmetic mean of the values. There must be at least one value, + * and they must all be finite. The values will be converted to doubles, which + * may cause loss of precision for some numeric types. + */ + @GwtIncompatible("MeanAccumulator") + public static double mean(Iterable values) { + MeanAccumulator accumulator = new MeanAccumulator(); + for (Number value : values) { + accumulator.add(value.doubleValue()); + } + return accumulator.mean(); + } + + /** + * Returns the arithmetic mean of the values. There must be at least one value, + * and they must all be finite. The values will be converted to doubles, which + * may cause loss of precision for some numeric types. + */ + @GwtIncompatible("MeanAccumulator") + public static double mean(Iterator values) { + MeanAccumulator accumulator = new MeanAccumulator(); + while (values.hasNext()) { + accumulator.add(values.next().doubleValue()); + } + return accumulator.mean(); + } + + /** + * Returns the arithmetic mean of the values. There must be at least one value. + * The values will be converted to doubles, which causes loss of precision for + * longs of magnitude over 2^53 (slightly over 9e15). + */ + @GwtIncompatible("MeanAccumulator") + public static double mean(long... values) { + MeanAccumulator accumulator = new MeanAccumulator(); + for (long value : values) { + accumulator.add(value); + } + return accumulator.mean(); + } + /* * This method returns a value y such that rounding y DOWN (towards zero) gives * the same result as rounding x according to the specified mode. @@ -114,6 +416,29 @@ public final class DoubleMath { } } + /** + * Returns the {@code BigInteger} value that is equal to {@code x} rounded with + * the specified rounding mode, if possible. + * + * @throws ArithmeticException if + *

              + *
            • {@code x} is infinite or NaN + *
            • {@code x} is not a mathematical integer and + * {@code mode} is {@link RoundingMode#UNNECESSARY} + *
            + */ + @GwtIncompatible("#roundIntermediate, java.lang.Math.getExponent, " + "com.google.common.math.DoubleUtils") + public static BigInteger roundToBigInteger(double x, RoundingMode mode) { + x = roundIntermediate(x, mode); + if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) { + return BigInteger.valueOf((long) x); + } + int exponent = getExponent(x); + long significand = getSignificand(x); + BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS); + return (x < 0) ? result.negate() : result; + } + /** * Returns the {@code int} value that is equal to {@code x} rounded with the * specified rounding mode, if possible. @@ -137,9 +462,6 @@ public final class DoubleMath { return (int) z; } - private static final double MIN_INT_AS_DOUBLE = -0x1p31; - private static final double MAX_INT_AS_DOUBLE = 0x1p31 - 1.0; - /** * Returns the {@code long} value that is equal to {@code x} rounded with the * specified rounding mode, if possible. @@ -163,328 +485,6 @@ public final class DoubleMath { return (long) z; } - private static final double MIN_LONG_AS_DOUBLE = -0x1p63; - /* - * We cannot store Long.MAX_VALUE as a double without losing precision. Instead, - * we store Long.MAX_VALUE + 1 == -Long.MIN_VALUE, and then offset all - * comparisons by 1. - */ - private static final double MAX_LONG_AS_DOUBLE_PLUS_ONE = 0x1p63; - - /** - * Returns the {@code BigInteger} value that is equal to {@code x} rounded with - * the specified rounding mode, if possible. - * - * @throws ArithmeticException if - *
              - *
            • {@code x} is infinite or NaN - *
            • {@code x} is not a mathematical integer and - * {@code mode} is {@link RoundingMode#UNNECESSARY} - *
            - */ - @GwtIncompatible("#roundIntermediate, java.lang.Math.getExponent, " + "com.google.common.math.DoubleUtils") - public static BigInteger roundToBigInteger(double x, RoundingMode mode) { - x = roundIntermediate(x, mode); - if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) { - return BigInteger.valueOf((long) x); - } - int exponent = getExponent(x); - long significand = getSignificand(x); - BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS); - return (x < 0) ? result.negate() : result; - } - - /** - * Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some - * finite integer {@code k}. - */ - @GwtIncompatible("com.google.common.math.DoubleUtils") - public static boolean isPowerOfTwo(double x) { - return x > 0.0 && isFinite(x) && LongMath.isPowerOfTwo(getSignificand(x)); - } - - /** - * Returns the base 2 logarithm of a double value. - * - *

            - * Special cases: - *

              - *
            • If {@code x} is NaN or less than zero, the result is NaN. - *
            • If {@code x} is positive infinity, the result is positive infinity. - *
            • If {@code x} is positive or negative zero, the result is negative - * infinity. - *
            - * - *

            - * The computed result is within 1 ulp of the exact result. - * - *

            - * If the result of this method will be immediately rounded to an {@code int}, - * {@link #log2(double, RoundingMode)} is faster. - */ - public static double log2(double x) { - return log(x) / LN_2; // surprisingly within 1 ulp according to tests - } - - private static final double LN_2 = log(2); - - /** - * Returns the base 2 logarithm of a double value, rounded with the specified - * rounding mode to an {@code int}. - * - *

            - * Regardless of the rounding mode, this is faster than {@code (int) log2(x)}. - * - * @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or - * {@code x} is infinite - */ - @GwtIncompatible("java.lang.Math.getExponent, com.google.common.math.DoubleUtils") - @SuppressWarnings("fallthrough") - public static int log2(double x, RoundingMode mode) { - checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite"); - int exponent = getExponent(x); - if (!isNormal(x)) { - return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS; - // Do the calculation on a normal value. - } - // x is positive, finite, and normal - boolean increment; - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(isPowerOfTwo(x)); - // fall through - case FLOOR: - increment = false; - break; - case CEILING: - increment = !isPowerOfTwo(x); - break; - case DOWN: - increment = exponent < 0 & !isPowerOfTwo(x); - break; - case UP: - increment = exponent >= 0 & !isPowerOfTwo(x); - break; - case HALF_DOWN: - case HALF_EVEN: - case HALF_UP: - double xScaled = scaleNormalize(x); - // sqrt(2) is irrational, and the spec is relative to the "exact numerical - // result," - // so log2(x) is never exactly exponent + 0.5. - increment = (xScaled * xScaled) > 2.0; - break; - default: - throw new AssertionError(); - } - return increment ? exponent + 1 : exponent; - } - - /** - * Returns {@code true} if {@code x} represents a mathematical integer. - * - *

            - * This is equivalent to, but not necessarily implemented as, the expression - * {@code - * !Double.isNaN(x) && !Double.isInfinite(x) && x == Math.rint(x)}. - */ - @GwtIncompatible("java.lang.Math.getExponent, com.google.common.math.DoubleUtils") - public static boolean isMathematicalInteger(double x) { - return isFinite(x) - && (x == 0.0 || SIGNIFICAND_BITS - Long.numberOfTrailingZeros(getSignificand(x)) <= getExponent(x)); - } - - /** - * Returns {@code n!}, that is, the product of the first {@code n} positive - * integers, {@code 1} if {@code n == 0}, or e n!}, or - * {@link Double#POSITIVE_INFINITY} if {@code n! > Double.MAX_VALUE}. - * - *

            - * The result is within 1 ulp of the true value. - * - * @throws IllegalArgumentException if {@code n < 0} - */ - public static double factorial(int n) { - checkNonNegative("n", n); - if (n > MAX_FACTORIAL) { - return Double.POSITIVE_INFINITY; - } else { - // Multiplying the last (n & 0xf) values into their own accumulator gives a more - // accurate - // result than multiplying by everySixteenthFactorial[n >> 4] directly. - double accum = 1.0; - for (int i = 1 + (n & ~0xf); i <= n; i++) { - accum *= i; - } - return accum * everySixteenthFactorial[n >> 4]; - } - } - - @VisibleForTesting - static final int MAX_FACTORIAL = 170; - - @VisibleForTesting - static final double[] everySixteenthFactorial = { 0x1.0p0, 0x1.30777758p44, 0x1.956ad0aae33a4p117, - 0x1.ee69a78d72cb6p202, 0x1.fe478ee34844ap295, 0x1.c619094edabffp394, 0x1.3638dd7bd6347p498, - 0x1.7cac197cfe503p605, 0x1.1e5dfc140e1e5p716, 0x1.8ce85fadb707ep829, 0x1.95d5f3d928edep945 }; - - /** - * Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} - * of each other. - * - *

            - * Technically speaking, this is equivalent to - * {@code Math.abs(a - b) <= tolerance || Double.valueOf(a).equals(Double.valueOf(b))}. - * - *

            - * Notable special cases include: - *

              - *
            • All NaNs are fuzzily equal. - *
            • If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal. - *
            • Positive and negative zero are always fuzzily equal. - *
            • If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, - * then {@code a} and {@code b} are fuzzily equal if and only if {@code a == b}. - *
            • With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are - * fuzzily equal. - *
            • With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code - * Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves.
            • - * - *

              - * This is reflexive and symmetric, but not transitive, so it is - * not an equivalence relation and not suitable for use in - * {@link Object#equals} implementations. - * - * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN - * @since 13.0 - */ - public static boolean fuzzyEquals(double a, double b, double tolerance) { - MathPreconditions.checkNonNegative("tolerance", tolerance); - return Math.copySign(a - b, 1.0) <= tolerance - // copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN - // semantics - || (a == b) // needed to ensure that infinities equal themselves - || (Double.isNaN(a) && Double.isNaN(b)); - } - - /** - * Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal - * values. - * - *

              - * This method is equivalent to - * {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a, b)}. In - * particular, like {@link Double#compare(double, double)}, it treats all NaN - * values as equal and greater than all other values (including - * {@link Double#POSITIVE_INFINITY}). - * - *

              - * This is not a total ordering and is not suitable for use in - * {@link Comparable#compareTo} implementations. In particular, it is not - * transitive. - * - * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN - * @since 13.0 - */ - public static int fuzzyCompare(double a, double b, double tolerance) { - if (fuzzyEquals(a, b, tolerance)) { - return 0; - } else if (a < b) { - return -1; - } else if (a > b) { - return 1; - } else { - return Booleans.compare(Double.isNaN(a), Double.isNaN(b)); - } - } - - @GwtIncompatible("com.google.common.math.DoubleUtils") - private static final class MeanAccumulator { - - private long count = 0; - private double mean = 0.0; - - void add(double value) { - checkArgument(isFinite(value)); - ++count; - // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) - mean += (value - mean) / count; - } - - double mean() { - checkArgument(count > 0, "Cannot take mean of 0 values"); - return mean; - } - } - - /** - * Returns the arithmetic mean of the values. There must be at least one value, - * and they must all be finite. - */ - @GwtIncompatible("MeanAccumulator") - public static double mean(double... values) { - MeanAccumulator accumulator = new MeanAccumulator(); - for (double value : values) { - accumulator.add(value); - } - return accumulator.mean(); - } - - /** - * Returns the arithmetic mean of the values. There must be at least one value. - * The values will be converted to doubles, which does not cause any loss of - * precision for ints. - */ - @GwtIncompatible("MeanAccumulator") - public static double mean(int... values) { - MeanAccumulator accumulator = new MeanAccumulator(); - for (int value : values) { - accumulator.add(value); - } - return accumulator.mean(); - } - - /** - * Returns the arithmetic mean of the values. There must be at least one value. - * The values will be converted to doubles, which causes loss of precision for - * longs of magnitude over 2^53 (slightly over 9e15). - */ - @GwtIncompatible("MeanAccumulator") - public static double mean(long... values) { - MeanAccumulator accumulator = new MeanAccumulator(); - for (long value : values) { - accumulator.add(value); - } - return accumulator.mean(); - } - - /** - * Returns the arithmetic mean of the values. There must be at least one value, - * and they must all be finite. The values will be converted to doubles, which - * may cause loss of precision for some numeric types. - */ - @GwtIncompatible("MeanAccumulator") - public static double mean(Iterable values) { - MeanAccumulator accumulator = new MeanAccumulator(); - for (Number value : values) { - accumulator.add(value.doubleValue()); - } - return accumulator.mean(); - } - - /** - * Returns the arithmetic mean of the values. There must be at least one value, - * and they must all be finite. The values will be converted to doubles, which - * may cause loss of precision for some numeric types. - */ - @GwtIncompatible("MeanAccumulator") - public static double mean(Iterator values) { - MeanAccumulator accumulator = new MeanAccumulator(); - while (values.hasNext()) { - accumulator.add(values.next().doubleValue()); - } - return accumulator.mean(); - } - private DoubleMath() { } } diff --git a/src/main/java/com/google/common/math/DoubleUtils.java b/src/main/java/com/google/common/math/DoubleUtils.java index ef4c6925..ce287251 100644 --- a/src/main/java/com/google/common/math/DoubleUtils.java +++ b/src/main/java/com/google/common/math/DoubleUtils.java @@ -33,13 +33,6 @@ import java.math.BigInteger; * @author Louis Wasserman */ final class DoubleUtils { - private DoubleUtils() { - } - - static double nextDown(double d) { - return -Math.nextUp(-d); - } - // The mask for the significand, according to the {@link // Double#doubleToRawLongBits(double)} spec. static final long SIGNIFICAND_MASK = 0x000fffffffffffffL; @@ -61,30 +54,7 @@ final class DoubleUtils { */ static final long IMPLICIT_BIT = SIGNIFICAND_MASK + 1; - static long getSignificand(double d) { - checkArgument(isFinite(d), "not a normal value"); - int exponent = getExponent(d); - long bits = doubleToRawLongBits(d); - bits &= SIGNIFICAND_MASK; - return (exponent == MIN_EXPONENT - 1) ? bits << 1 : bits | IMPLICIT_BIT; - } - - static boolean isFinite(double d) { - return getExponent(d) <= MAX_EXPONENT; - } - - static boolean isNormal(double d) { - return getExponent(d) >= MIN_EXPONENT; - } - - /* - * Returns x scaled by a power of 2 such that it is in the range [1, 2). Assumes - * x is positive, normal, and finite. - */ - static double scaleNormalize(double x) { - long significand = doubleToRawLongBits(x) & SIGNIFICAND_MASK; - return longBitsToDouble(significand | ONE_BITS); - } + private static final long ONE_BITS = doubleToRawLongBits(1.0); static double bigToDouble(BigInteger x) { // This is an extremely fast implementation of BigInteger.doubleValue(). JDK @@ -144,5 +114,35 @@ final class DoubleUtils { } } - private static final long ONE_BITS = doubleToRawLongBits(1.0); + static long getSignificand(double d) { + checkArgument(isFinite(d), "not a normal value"); + int exponent = getExponent(d); + long bits = doubleToRawLongBits(d); + bits &= SIGNIFICAND_MASK; + return (exponent == MIN_EXPONENT - 1) ? bits << 1 : bits | IMPLICIT_BIT; + } + + static boolean isFinite(double d) { + return getExponent(d) <= MAX_EXPONENT; + } + + static boolean isNormal(double d) { + return getExponent(d) >= MIN_EXPONENT; + } + + static double nextDown(double d) { + return -Math.nextUp(-d); + } + + /* + * Returns x scaled by a power of 2 such that it is in the range [1, 2). Assumes + * x is positive, normal, and finite. + */ + static double scaleNormalize(double x) { + long significand = doubleToRawLongBits(x) & SIGNIFICAND_MASK; + return longBitsToDouble(significand | ONE_BITS); + } + + private DoubleUtils() { + } } diff --git a/src/main/java/com/google/common/math/IntMath.java b/src/main/java/com/google/common/math/IntMath.java index 55e7d183..66d4d811 100644 --- a/src/main/java/com/google/common/math/IntMath.java +++ b/src/main/java/com/google/common/math/IntMath.java @@ -56,6 +56,288 @@ public final class IntMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | // instead of &&, || + /** The biggest half power of two that can fit in an unsigned int. */ + @VisibleForTesting + static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333; + + // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) + @VisibleForTesting + static final byte[] maxLog10ForLeadingZeros = { 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, + 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 }; + + @VisibleForTesting + static final int[] powersOf10 = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + + // halfPowersOf10[i] = largest int less than 10^(i + 0.5) + @VisibleForTesting + static final int[] halfPowersOf10 = { 3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, + Integer.MAX_VALUE }; + + @VisibleForTesting + static final int FLOOR_SQRT_MAX_INT = 46340; + + private static final int[] factorials = { 1, 1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, 1 * 2 * 3 * 4 * 5, + 1 * 2 * 3 * 4 * 5 * 6, 1 * 2 * 3 * 4 * 5 * 6 * 7, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8, + 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, + 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 }; + + // binomial(biggestBinomials[k], k) fits in an int, but not + // binomial(biggestBinomials[k]+1,k). + @VisibleForTesting + static int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, 65536, 2345, 477, 193, 110, 75, 58, 49, 43, + 39, 37, 35, 34, 34, 33 }; + + /** + * Returns {@code n} choose {@code k}, also known as the binomial coefficient of + * {@code n} and {@code k}, or {@link Integer#MAX_VALUE} if the result does not + * fit in an {@code int}. + * + * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or + * {@code k > n} + */ + @GwtIncompatible("need BigIntegerMath to adequately test") + public static int binomial(int n, int k) { + checkNonNegative("n", n); + checkNonNegative("k", k); + checkArgument(k <= n, "k (%s) > n (%s)", k, n); + if (k > (n >> 1)) { + k = n - k; + } + if (k >= biggestBinomials.length || n > biggestBinomials[k]) { + return Integer.MAX_VALUE; + } + switch (k) { + case 0: + return 1; + case 1: + return n; + default: + long result = 1; + for (int i = 0; i < k; i++) { + result *= n - i; + result /= i + 1; + } + return (int) result; + } + } + + /** + * Returns the sum of {@code a} and {@code b}, provided it does not overflow. + * + * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} + * arithmetic + */ + public static int checkedAdd(int a, int b) { + long result = (long) a + b; + checkNoOverflow(result == (int) result); + return (int) result; + } + + /** + * Returns the product of {@code a} and {@code b}, provided it does not + * overflow. + * + * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} + * arithmetic + */ + public static int checkedMultiply(int a, int b) { + long result = (long) a * b; + checkNoOverflow(result == (int) result); + return (int) result; + } + + /** + * Returns the {@code b} to the {@code k}th power, provided it does not + * overflow. + * + *

              + * {@link #pow} may be faster, but does not check for overflow. + * + * @throws ArithmeticException if {@code b} to the {@code k}th power overflows + * in signed {@code int} arithmetic + */ + public static int checkedPow(int b, int k) { + checkNonNegative("exponent", k); + switch (b) { + case 0: + return (k == 0) ? 1 : 0; + case 1: + return 1; + case (-1): + return ((k & 1) == 0) ? 1 : -1; + case 2: + checkNoOverflow(k < Integer.SIZE - 1); + return 1 << k; + case (-2): + checkNoOverflow(k < Integer.SIZE); + return ((k & 1) == 0) ? 1 << k : -1 << k; + default: + // continue below to handle the general case + } + int accum = 1; + while (true) { + switch (k) { + case 0: + return accum; + case 1: + return checkedMultiply(accum, b); + default: + if ((k & 1) != 0) { + accum = checkedMultiply(accum, b); + } + k >>= 1; + if (k > 0) { + checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT); + b *= b; + } + } + } + } + + /** + * Returns the difference of {@code a} and {@code b}, provided it does not + * overflow. + * + * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} + * arithmetic + */ + public static int checkedSubtract(int a, int b) { + long result = (long) a - b; + checkNoOverflow(result == (int) result); + return (int) result; + } + + /** + * Returns the result of dividing {@code p} by {@code q}, rounding using the + * specified {@code RoundingMode}. + * + * @throws ArithmeticException if {@code q == 0}, or if + * {@code mode == UNNECESSARY} and {@code a} is not + * an integer multiple of {@code b} + */ + @SuppressWarnings("fallthrough") + public static int divide(int p, int q, RoundingMode mode) { + checkNotNull(mode); + if (q == 0) { + throw new ArithmeticException("/ by zero"); // for GWT + } + int div = p / q; + int rem = p - q * div; // equal to p % q + + if (rem == 0) { + return div; + } + + /* + * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. + * We just have to deal with the cases where rounding towards 0 is wrong, which + * typically depends on the sign of p / q. + * + * signum is 1 if p and q are both nonnegative or both negative, and -1 + * otherwise. + */ + int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1)); + boolean increment; + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(rem == 0); + // fall through + case DOWN: + increment = false; + break; + case UP: + increment = true; + break; + case CEILING: + increment = signum > 0; + break; + case FLOOR: + increment = signum < 0; + break; + case HALF_EVEN: + case HALF_DOWN: + case HALF_UP: + int absRem = abs(rem); + int cmpRemToHalfDivisor = absRem - (abs(q) - absRem); + // subtracting two nonnegative ints can't overflow + // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). + if (cmpRemToHalfDivisor == 0) { // exactly on the half mark + increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0)); + } else { + increment = cmpRemToHalfDivisor > 0; // closer to the UP value + } + break; + default: + throw new AssertionError(); + } + return increment ? div + signum : div; + } + + /** + * Returns {@code n!}, that is, the product of the first {@code n} positive + * integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the + * result does not fit in a {@code int}. + * + * @throws IllegalArgumentException if {@code n < 0} + */ + public static int factorial(int n) { + checkNonNegative("n", n); + return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE; + } + + /** + * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if + * {@code a == 0 && b == 0}. + * + * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} + */ + public static int gcd(int a, int b) { + /* + * The reason we require both arguments to be >= 0 is because otherwise, what do + * you return on gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive + * 2^31, but positive 2^31 isn't an int. + */ + checkNonNegative("a", a); + checkNonNegative("b", b); + if (a == 0) { + // 0 % b == 0, so b divides a, but the converse doesn't hold. + // BigInteger.gcd is consistent with this decision. + return b; + } else if (b == 0) { + return a; // similar logic + } + /* + * Uses the binary GCD algorithm; see + * http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is >40% faster than + * the Euclidean algorithm in benchmarks. + */ + int aTwos = Integer.numberOfTrailingZeros(a); + a >>= aTwos; // divide out all 2s + int bTwos = Integer.numberOfTrailingZeros(b); + b >>= bTwos; // divide out all 2s + while (a != b) { // both a, b are odd + // The key to the binary GCD algorithm is as follows: + // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). + // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers + // of two. + + // We bend over backwards to avoid branching, adapting a technique from + // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax + + int delta = a - b; // can't overflow, since a and b are nonnegative + + int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1)); + // equivalent to Math.min(delta, 0) + + a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) + // a is now nonnegative and even + + b += minDeltaOrZero; // sets b to min(old a, b) + a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b + } + return a << min(aTwos, bTwos); + } + /** * Returns {@code true} if {@code x} represents a power of two. * @@ -82,50 +364,6 @@ public final class IntMath { return ~~(x - y) >>> (Integer.SIZE - 1); } - /** - * Returns the base-2 logarithm of {@code x}, rounded according to the specified - * rounding mode. - * - * @throws IllegalArgumentException if {@code x <= 0} - * @throws ArithmeticException if {@code mode} is - * {@link RoundingMode#UNNECESSARY} and - * {@code x} is not a power of two - */ - @SuppressWarnings("fallthrough") - // TODO(kevinb): remove after this warning is disabled globally - public static int log2(int x, RoundingMode mode) { - checkPositive("x", x); - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(isPowerOfTwo(x)); - // fall through - case DOWN: - case FLOOR: - return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x); - - case UP: - case CEILING: - return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1); - - case HALF_DOWN: - case HALF_UP: - case HALF_EVEN: - // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 - int leadingZeros = Integer.numberOfLeadingZeros(x); - int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; - // floor(2^(logFloor + 0.5)) - int logFloor = (Integer.SIZE - 1) - leadingZeros; - return logFloor + lessThanBranchFree(cmp, x); - - default: - throw new AssertionError(); - } - } - - /** The biggest half power of two that can fit in an unsigned int. */ - @VisibleForTesting - static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333; - /** * Returns the base-10 logarithm of {@code x}, rounded according to the * specified rounding mode. @@ -180,18 +418,88 @@ public final class IntMath { return y - lessThanBranchFree(x, powersOf10[y]); } - // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) - @VisibleForTesting - static final byte[] maxLog10ForLeadingZeros = { 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, - 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 }; + /** + * Returns the base-2 logarithm of {@code x}, rounded according to the specified + * rounding mode. + * + * @throws IllegalArgumentException if {@code x <= 0} + * @throws ArithmeticException if {@code mode} is + * {@link RoundingMode#UNNECESSARY} and + * {@code x} is not a power of two + */ + @SuppressWarnings("fallthrough") + // TODO(kevinb): remove after this warning is disabled globally + public static int log2(int x, RoundingMode mode) { + checkPositive("x", x); + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(isPowerOfTwo(x)); + // fall through + case DOWN: + case FLOOR: + return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x); - @VisibleForTesting - static final int[] powersOf10 = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; + case UP: + case CEILING: + return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1); - // halfPowersOf10[i] = largest int less than 10^(i + 0.5) - @VisibleForTesting - static final int[] halfPowersOf10 = { 3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, - Integer.MAX_VALUE }; + case HALF_DOWN: + case HALF_UP: + case HALF_EVEN: + // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 + int leadingZeros = Integer.numberOfLeadingZeros(x); + int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; + // floor(2^(logFloor + 0.5)) + int logFloor = (Integer.SIZE - 1) - leadingZeros; + return logFloor + lessThanBranchFree(cmp, x); + + default: + throw new AssertionError(); + } + } + + /** + * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards + * negative infinity. This method is overflow resilient. + * + * @since 14.0 + */ + public static int mean(int x, int y) { + // Efficient method for computing the arithmetic mean. + // The alternative (x + y) / 2 fails for large values. + // The alternative (x + y) >>> 1 fails for negative values. + return (x & y) + ((x ^ y) >> 1); + } + + /** + * Returns {@code x mod m}, a non-negative value less than {@code m}. This + * differs from {@code x % m}, which might be negative. + * + *

              + * For example: + * + *

              +	 *  {@code
              +	 *
              +	 * mod(7, 4) == 3
              +	 * mod(-7, 4) == 1
              +	 * mod(-1, 4) == 3
              +	 * mod(-8, 4) == 0
              +	 * mod(8, 4) == 0}
              +	 * 
              + * + * @throws ArithmeticException if {@code m <= 0} + * @see + * Remainder Operator + */ + public static int mod(int x, int m) { + if (m <= 0) { + throw new ArithmeticException("Modulus " + m + " must be > 0"); + } + int result = x % m; + return (result >= 0) ? result : result + m; + } /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it @@ -287,314 +595,6 @@ public final class IntMath { return (int) Math.sqrt(x); } - /** - * Returns the result of dividing {@code p} by {@code q}, rounding using the - * specified {@code RoundingMode}. - * - * @throws ArithmeticException if {@code q == 0}, or if - * {@code mode == UNNECESSARY} and {@code a} is not - * an integer multiple of {@code b} - */ - @SuppressWarnings("fallthrough") - public static int divide(int p, int q, RoundingMode mode) { - checkNotNull(mode); - if (q == 0) { - throw new ArithmeticException("/ by zero"); // for GWT - } - int div = p / q; - int rem = p - q * div; // equal to p % q - - if (rem == 0) { - return div; - } - - /* - * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. - * We just have to deal with the cases where rounding towards 0 is wrong, which - * typically depends on the sign of p / q. - * - * signum is 1 if p and q are both nonnegative or both negative, and -1 - * otherwise. - */ - int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1)); - boolean increment; - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(rem == 0); - // fall through - case DOWN: - increment = false; - break; - case UP: - increment = true; - break; - case CEILING: - increment = signum > 0; - break; - case FLOOR: - increment = signum < 0; - break; - case HALF_EVEN: - case HALF_DOWN: - case HALF_UP: - int absRem = abs(rem); - int cmpRemToHalfDivisor = absRem - (abs(q) - absRem); - // subtracting two nonnegative ints can't overflow - // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). - if (cmpRemToHalfDivisor == 0) { // exactly on the half mark - increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0)); - } else { - increment = cmpRemToHalfDivisor > 0; // closer to the UP value - } - break; - default: - throw new AssertionError(); - } - return increment ? div + signum : div; - } - - /** - * Returns {@code x mod m}, a non-negative value less than {@code m}. This - * differs from {@code x % m}, which might be negative. - * - *

              - * For example: - * - *

              -	 *  {@code
              -	 *
              -	 * mod(7, 4) == 3
              -	 * mod(-7, 4) == 1
              -	 * mod(-1, 4) == 3
              -	 * mod(-8, 4) == 0
              -	 * mod(8, 4) == 0}
              -	 * 
              - * - * @throws ArithmeticException if {@code m <= 0} - * @see - * Remainder Operator - */ - public static int mod(int x, int m) { - if (m <= 0) { - throw new ArithmeticException("Modulus " + m + " must be > 0"); - } - int result = x % m; - return (result >= 0) ? result : result + m; - } - - /** - * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if - * {@code a == 0 && b == 0}. - * - * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} - */ - public static int gcd(int a, int b) { - /* - * The reason we require both arguments to be >= 0 is because otherwise, what do - * you return on gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive - * 2^31, but positive 2^31 isn't an int. - */ - checkNonNegative("a", a); - checkNonNegative("b", b); - if (a == 0) { - // 0 % b == 0, so b divides a, but the converse doesn't hold. - // BigInteger.gcd is consistent with this decision. - return b; - } else if (b == 0) { - return a; // similar logic - } - /* - * Uses the binary GCD algorithm; see - * http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is >40% faster than - * the Euclidean algorithm in benchmarks. - */ - int aTwos = Integer.numberOfTrailingZeros(a); - a >>= aTwos; // divide out all 2s - int bTwos = Integer.numberOfTrailingZeros(b); - b >>= bTwos; // divide out all 2s - while (a != b) { // both a, b are odd - // The key to the binary GCD algorithm is as follows: - // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). - // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers - // of two. - - // We bend over backwards to avoid branching, adapting a technique from - // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax - - int delta = a - b; // can't overflow, since a and b are nonnegative - - int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1)); - // equivalent to Math.min(delta, 0) - - a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) - // a is now nonnegative and even - - b += minDeltaOrZero; // sets b to min(old a, b) - a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b - } - return a << min(aTwos, bTwos); - } - - /** - * Returns the sum of {@code a} and {@code b}, provided it does not overflow. - * - * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} - * arithmetic - */ - public static int checkedAdd(int a, int b) { - long result = (long) a + b; - checkNoOverflow(result == (int) result); - return (int) result; - } - - /** - * Returns the difference of {@code a} and {@code b}, provided it does not - * overflow. - * - * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} - * arithmetic - */ - public static int checkedSubtract(int a, int b) { - long result = (long) a - b; - checkNoOverflow(result == (int) result); - return (int) result; - } - - /** - * Returns the product of {@code a} and {@code b}, provided it does not - * overflow. - * - * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} - * arithmetic - */ - public static int checkedMultiply(int a, int b) { - long result = (long) a * b; - checkNoOverflow(result == (int) result); - return (int) result; - } - - /** - * Returns the {@code b} to the {@code k}th power, provided it does not - * overflow. - * - *

              - * {@link #pow} may be faster, but does not check for overflow. - * - * @throws ArithmeticException if {@code b} to the {@code k}th power overflows - * in signed {@code int} arithmetic - */ - public static int checkedPow(int b, int k) { - checkNonNegative("exponent", k); - switch (b) { - case 0: - return (k == 0) ? 1 : 0; - case 1: - return 1; - case (-1): - return ((k & 1) == 0) ? 1 : -1; - case 2: - checkNoOverflow(k < Integer.SIZE - 1); - return 1 << k; - case (-2): - checkNoOverflow(k < Integer.SIZE); - return ((k & 1) == 0) ? 1 << k : -1 << k; - default: - // continue below to handle the general case - } - int accum = 1; - while (true) { - switch (k) { - case 0: - return accum; - case 1: - return checkedMultiply(accum, b); - default: - if ((k & 1) != 0) { - accum = checkedMultiply(accum, b); - } - k >>= 1; - if (k > 0) { - checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT); - b *= b; - } - } - } - } - - @VisibleForTesting - static final int FLOOR_SQRT_MAX_INT = 46340; - - /** - * Returns {@code n!}, that is, the product of the first {@code n} positive - * integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the - * result does not fit in a {@code int}. - * - * @throws IllegalArgumentException if {@code n < 0} - */ - public static int factorial(int n) { - checkNonNegative("n", n); - return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE; - } - - private static final int[] factorials = { 1, 1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, 1 * 2 * 3 * 4 * 5, - 1 * 2 * 3 * 4 * 5 * 6, 1 * 2 * 3 * 4 * 5 * 6 * 7, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8, - 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, - 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 }; - - /** - * Returns {@code n} choose {@code k}, also known as the binomial coefficient of - * {@code n} and {@code k}, or {@link Integer#MAX_VALUE} if the result does not - * fit in an {@code int}. - * - * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or - * {@code k > n} - */ - @GwtIncompatible("need BigIntegerMath to adequately test") - public static int binomial(int n, int k) { - checkNonNegative("n", n); - checkNonNegative("k", k); - checkArgument(k <= n, "k (%s) > n (%s)", k, n); - if (k > (n >> 1)) { - k = n - k; - } - if (k >= biggestBinomials.length || n > biggestBinomials[k]) { - return Integer.MAX_VALUE; - } - switch (k) { - case 0: - return 1; - case 1: - return n; - default: - long result = 1; - for (int i = 0; i < k; i++) { - result *= n - i; - result /= i + 1; - } - return (int) result; - } - } - - // binomial(biggestBinomials[k], k) fits in an int, but not - // binomial(biggestBinomials[k]+1,k). - @VisibleForTesting - static int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, 65536, 2345, 477, 193, 110, 75, 58, 49, 43, - 39, 37, 35, 34, 34, 33 }; - - /** - * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards - * negative infinity. This method is overflow resilient. - * - * @since 14.0 - */ - public static int mean(int x, int y) { - // Efficient method for computing the arithmetic mean. - // The alternative (x + y) / 2 fails for large values. - // The alternative (x + y) >>> 1 fails for negative values. - return (x & y) + ((x ^ y) >> 1); - } - private IntMath() { } } diff --git a/src/main/java/com/google/common/math/LongMath.java b/src/main/java/com/google/common/math/LongMath.java index 69f41d7c..a420ffe1 100644 --- a/src/main/java/com/google/common/math/LongMath.java +++ b/src/main/java/com/google/common/math/LongMath.java @@ -57,6 +57,377 @@ public final class LongMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | // instead of &&, || + /** The biggest half power of two that fits into an unsigned long */ + @VisibleForTesting + static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; + + // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) + @VisibleForTesting + static final byte[] maxLog10ForLeadingZeros = { 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, + 14, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, + 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; + + @GwtIncompatible("TODO") + @VisibleForTesting + static final long[] powersOf10 = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, + 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, + 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; + + // halfPowersOf10[i] = largest long less than 10^(i + 0.5) + @GwtIncompatible("TODO") + @VisibleForTesting + static final long[] halfPowersOf10 = { 3L, 31L, 316L, 3162L, 31622L, 316227L, 3162277L, 31622776L, 316227766L, + 3162277660L, 31622776601L, 316227766016L, 3162277660168L, 31622776601683L, 316227766016837L, + 3162277660168379L, 31622776601683793L, 316227766016837933L, 3162277660168379331L }; + + @VisibleForTesting + static final long FLOOR_SQRT_MAX_LONG = 3037000499L; + + static final long[] factorials = { 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, + 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, + 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 }; + + /* + * binomial(biggestBinomials[k], k) fits in a long, but not + * binomial(biggestBinomials[k] + 1, k). + */ + static final int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, + 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, + 67, 67, 66, 66, 66, 66 }; + + /* + * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower + * GCD-based impl, but binomial(biggestSimpleBinomials[k] + 1, k) does. + */ + @VisibleForTesting + static final int[] biggestSimpleBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, + 86251, 11724, 3218, 1313, 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, + 62, 62, 61, 61, 61 }; + // These values were generated by using checkedMultiply to see when the simple + // multiply/divide + // algorithm would lead to an overflow. + + /** + * Returns {@code n} choose {@code k}, also known as the binomial coefficient of + * {@code n} and {@code k}, or {@link Long#MAX_VALUE} if the result does not fit + * in a {@code long}. + * + * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or + * {@code k > n} + */ + public static long binomial(int n, int k) { + checkNonNegative("n", n); + checkNonNegative("k", k); + checkArgument(k <= n, "k (%s) > n (%s)", k, n); + if (k > (n >> 1)) { + k = n - k; + } + switch (k) { + case 0: + return 1; + case 1: + return n; + default: + if (n < factorials.length) { + return factorials[n] / (factorials[k] * factorials[n - k]); + } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { + return Long.MAX_VALUE; + } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { + // guaranteed not to overflow + long result = n--; + for (int i = 2; i <= k; n--, i++) { + result *= n; + result /= i; + } + return result; + } else { + int nBits = LongMath.log2(n, RoundingMode.CEILING); + + long result = 1; + long numerator = n--; + long denominator = 1; + + int numeratorBits = nBits; + // This is an upper bound on log2(numerator, ceiling). + + /* + * We want to do this in long math for speed, but want to avoid overflow. We + * adapt the technique previously used by BigIntegerMath: maintain separate + * numerator and denominator accumulators, multiplying the fraction into result + * when near overflow. + */ + for (int i = 2; i <= k; i++, n--) { + if (numeratorBits + nBits < Long.SIZE - 1) { + // It's definitely safe to multiply into numerator and denominator. + numerator *= n; + denominator *= i; + numeratorBits += nBits; + } else { + // It might not be safe to multiply into numerator and denominator, + // so multiply (numerator / denominator) into result. + result = multiplyFraction(result, numerator, denominator); + numerator = n; + denominator = i; + numeratorBits = nBits; + } + } + return multiplyFraction(result, numerator, denominator); + } + } + } + + /** + * Returns the sum of {@code a} and {@code b}, provided it does not overflow. + * + * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} + * arithmetic + */ + @GwtIncompatible("TODO") + public static long checkedAdd(long a, long b) { + long result = a + b; + checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0); + return result; + } + + /** + * Returns the product of {@code a} and {@code b}, provided it does not + * overflow. + * + * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} + * arithmetic + */ + @GwtIncompatible("TODO") + public static long checkedMultiply(long a, long b) { + // Hacker's Delight, Section 2-12 + int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + + Long.numberOfLeadingZeros(~b); + /* + * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE + * it's definitely bad. We do the leadingZeros check to avoid the division below + * if at all possible. + * + * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 + * and 1. We take care of all a < 0 with their own check, because in particular, + * the case a == -1 will incorrectly pass the division check below. + * + * In all other cases, we check that either a is 0 or the result is consistent + * with division. + */ + if (leadingZeros > Long.SIZE + 1) { + return a * b; + } + checkNoOverflow(leadingZeros >= Long.SIZE); + checkNoOverflow(a >= 0 | b != Long.MIN_VALUE); + long result = a * b; + checkNoOverflow(a == 0 || result / a == b); + return result; + } + + /** + * Returns the {@code b} to the {@code k}th power, provided it does not + * overflow. + * + * @throws ArithmeticException if {@code b} to the {@code k}th power overflows + * in signed {@code long} arithmetic + */ + @GwtIncompatible("TODO") + public static long checkedPow(long b, int k) { + checkNonNegative("exponent", k); + if (b >= -2 & b <= 2) { + switch ((int) b) { + case 0: + return (k == 0) ? 1 : 0; + case 1: + return 1; + case (-1): + return ((k & 1) == 0) ? 1 : -1; + case 2: + checkNoOverflow(k < Long.SIZE - 1); + return 1L << k; + case (-2): + checkNoOverflow(k < Long.SIZE); + return ((k & 1) == 0) ? (1L << k) : (-1L << k); + default: + throw new AssertionError(); + } + } + long accum = 1; + while (true) { + switch (k) { + case 0: + return accum; + case 1: + return checkedMultiply(accum, b); + default: + if ((k & 1) != 0) { + accum = checkedMultiply(accum, b); + } + k >>= 1; + if (k > 0) { + checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG); + b *= b; + } + } + } + } + + /** + * Returns the difference of {@code a} and {@code b}, provided it does not + * overflow. + * + * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} + * arithmetic + */ + @GwtIncompatible("TODO") + public static long checkedSubtract(long a, long b) { + long result = a - b; + checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0); + return result; + } + + /** + * Returns the result of dividing {@code p} by {@code q}, rounding using the + * specified {@code RoundingMode}. + * + * @throws ArithmeticException if {@code q == 0}, or if + * {@code mode == UNNECESSARY} and {@code a} is not + * an integer multiple of {@code b} + */ + @GwtIncompatible("TODO") + @SuppressWarnings("fallthrough") + public static long divide(long p, long q, RoundingMode mode) { + checkNotNull(mode); + long div = p / q; // throws if q == 0 + long rem = p - q * div; // equals p % q + + if (rem == 0) { + return div; + } + + /* + * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. + * We just have to deal with the cases where rounding towards 0 is wrong, which + * typically depends on the sign of p / q. + * + * signum is 1 if p and q are both nonnegative or both negative, and -1 + * otherwise. + */ + int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1)); + boolean increment; + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(rem == 0); + // fall through + case DOWN: + increment = false; + break; + case UP: + increment = true; + break; + case CEILING: + increment = signum > 0; + break; + case FLOOR: + increment = signum < 0; + break; + case HALF_EVEN: + case HALF_DOWN: + case HALF_UP: + long absRem = abs(rem); + long cmpRemToHalfDivisor = absRem - (abs(q) - absRem); + // subtracting two nonnegative longs can't overflow + // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). + if (cmpRemToHalfDivisor == 0) { // exactly on the half mark + increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0)); + } else { + increment = cmpRemToHalfDivisor > 0; // closer to the UP value + } + break; + default: + throw new AssertionError(); + } + return increment ? div + signum : div; + } + + /** + * Returns {@code n!}, that is, the product of the first {@code n} positive + * integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the + * result does not fit in a {@code long}. + * + * @throws IllegalArgumentException if {@code n < 0} + */ + @GwtIncompatible("TODO") + public static long factorial(int n) { + checkNonNegative("n", n); + return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE; + } + + static boolean fitsInInt(long x) { + return (int) x == x; + } + + /** + * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if + * {@code a == 0 && b == 0}. + * + * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} + */ + public static long gcd(long a, long b) { + /* + * The reason we require both arguments to be >= 0 is because otherwise, what do + * you return on gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive + * 2^63, but positive 2^63 isn't an int. + */ + checkNonNegative("a", a); + checkNonNegative("b", b); + if (a == 0) { + // 0 % b == 0, so b divides a, but the converse doesn't hold. + // BigInteger.gcd is consistent with this decision. + return b; + } else if (b == 0) { + return a; // similar logic + } + /* + * Uses the binary GCD algorithm; see + * http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is >60% faster than + * the Euclidean algorithm in benchmarks. + */ + int aTwos = Long.numberOfTrailingZeros(a); + a >>= aTwos; // divide out all 2s + int bTwos = Long.numberOfTrailingZeros(b); + b >>= bTwos; // divide out all 2s + while (a != b) { // both a, b are odd + // The key to the binary GCD algorithm is as follows: + // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). + // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers + // of two. + + // We bend over backwards to avoid branching, adapting a technique from + // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax + + long delta = a - b; // can't overflow, since a and b are nonnegative + + long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); + // equivalent to Math.min(delta, 0) + + a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) + // a is now nonnegative and even + + b += minDeltaOrZero; // sets b to min(old a, b) + a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b + } + return a << min(aTwos, bTwos); + } + /** * Returns {@code true} if {@code x} represents a power of two. * @@ -81,50 +452,6 @@ public final class LongMath { return (int) (~~(x - y) >>> (Long.SIZE - 1)); } - /** - * Returns the base-2 logarithm of {@code x}, rounded according to the specified - * rounding mode. - * - * @throws IllegalArgumentException if {@code x <= 0} - * @throws ArithmeticException if {@code mode} is - * {@link RoundingMode#UNNECESSARY} and - * {@code x} is not a power of two - */ - @SuppressWarnings("fallthrough") - // TODO(kevinb): remove after this warning is disabled globally - public static int log2(long x, RoundingMode mode) { - checkPositive("x", x); - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(isPowerOfTwo(x)); - // fall through - case DOWN: - case FLOOR: - return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); - - case UP: - case CEILING: - return Long.SIZE - Long.numberOfLeadingZeros(x - 1); - - case HALF_DOWN: - case HALF_UP: - case HALF_EVEN: - // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 - int leadingZeros = Long.numberOfLeadingZeros(x); - long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; - // floor(2^(logFloor + 0.5)) - int logFloor = (Long.SIZE - 1) - leadingZeros; - return logFloor + lessThanBranchFree(cmp, x); - - default: - throw new AssertionError("impossible"); - } - } - - /** The biggest half power of two that fits into an unsigned long */ - @VisibleForTesting - static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; - /** * Returns the base-10 logarithm of {@code x}, rounded according to the * specified rounding mode. @@ -181,24 +508,133 @@ public final class LongMath { return y - lessThanBranchFree(x, powersOf10[y]); } - // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) - @VisibleForTesting - static final byte[] maxLog10ForLeadingZeros = { 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, - 14, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, - 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; + /** + * Returns the base-2 logarithm of {@code x}, rounded according to the specified + * rounding mode. + * + * @throws IllegalArgumentException if {@code x <= 0} + * @throws ArithmeticException if {@code mode} is + * {@link RoundingMode#UNNECESSARY} and + * {@code x} is not a power of two + */ + @SuppressWarnings("fallthrough") + // TODO(kevinb): remove after this warning is disabled globally + public static int log2(long x, RoundingMode mode) { + checkPositive("x", x); + switch (mode) { + case UNNECESSARY: + checkRoundingUnnecessary(isPowerOfTwo(x)); + // fall through + case DOWN: + case FLOOR: + return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); - @GwtIncompatible("TODO") - @VisibleForTesting - static final long[] powersOf10 = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, - 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, - 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; + case UP: + case CEILING: + return Long.SIZE - Long.numberOfLeadingZeros(x - 1); - // halfPowersOf10[i] = largest long less than 10^(i + 0.5) + case HALF_DOWN: + case HALF_UP: + case HALF_EVEN: + // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 + int leadingZeros = Long.numberOfLeadingZeros(x); + long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; + // floor(2^(logFloor + 0.5)) + int logFloor = (Long.SIZE - 1) - leadingZeros; + return logFloor + lessThanBranchFree(cmp, x); + + default: + throw new AssertionError("impossible"); + } + } + + /** + * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward + * negative infinity. This method is resilient to overflow. + * + * @since 14.0 + */ + public static long mean(long x, long y) { + // Efficient method for computing the arithmetic mean. + // The alternative (x + y) / 2 fails for large values. + // The alternative (x + y) >>> 1 fails for negative values. + return (x & y) + ((x ^ y) >> 1); + } + + /** + * Returns {@code x mod m}, a non-negative value less than {@code m}. This + * differs from {@code x % m}, which might be negative. + * + *

              + * For example: + * + *

              +	 *  {@code
              +	 *
              +	 * mod(7, 4) == 3
              +	 * mod(-7, 4) == 1
              +	 * mod(-1, 4) == 3
              +	 * mod(-8, 4) == 0
              +	 * mod(8, 4) == 0}
              +	 * 
              + * + * @throws ArithmeticException if {@code m <= 0} + * @see + * Remainder Operator + */ @GwtIncompatible("TODO") - @VisibleForTesting - static final long[] halfPowersOf10 = { 3L, 31L, 316L, 3162L, 31622L, 316227L, 3162277L, 31622776L, 316227766L, - 3162277660L, 31622776601L, 316227766016L, 3162277660168L, 31622776601683L, 316227766016837L, - 3162277660168379L, 31622776601683793L, 316227766016837933L, 3162277660168379331L }; + public static int mod(long x, int m) { + // Cast is safe because the result is guaranteed in the range [0, m) + return (int) mod(x, (long) m); + } + + /** + * Returns {@code x mod m}, a non-negative value less than {@code m}. This + * differs from {@code x % m}, which might be negative. + * + *

              + * For example: + * + *

              +	 *  {@code
              +	 *
              +	 * mod(7, 4) == 3
              +	 * mod(-7, 4) == 1
              +	 * mod(-1, 4) == 3
              +	 * mod(-8, 4) == 0
              +	 * mod(8, 4) == 0}
              +	 * 
              + * + * @throws ArithmeticException if {@code m <= 0} + * @see + * Remainder Operator + */ + @GwtIncompatible("TODO") + public static long mod(long x, long m) { + if (m <= 0) { + throw new ArithmeticException("Modulus must be positive"); + } + long result = x % m; + return (result >= 0) ? result : result + m; + } + + /** + * Returns (x * numerator / denominator), which is assumed to come out to an + * integral value. + */ + static long multiplyFraction(long x, long numerator, long denominator) { + if (x == 1) { + return numerator / denominator; + } + long commonDivisor = gcd(x, denominator); + x /= commonDivisor; + denominator /= commonDivisor; + // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, + // so denominator must be a divisor of numerator. + return x * (numerator / denominator); + } /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it @@ -314,442 +750,6 @@ public final class LongMath { } } - /** - * Returns the result of dividing {@code p} by {@code q}, rounding using the - * specified {@code RoundingMode}. - * - * @throws ArithmeticException if {@code q == 0}, or if - * {@code mode == UNNECESSARY} and {@code a} is not - * an integer multiple of {@code b} - */ - @GwtIncompatible("TODO") - @SuppressWarnings("fallthrough") - public static long divide(long p, long q, RoundingMode mode) { - checkNotNull(mode); - long div = p / q; // throws if q == 0 - long rem = p - q * div; // equals p % q - - if (rem == 0) { - return div; - } - - /* - * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. - * We just have to deal with the cases where rounding towards 0 is wrong, which - * typically depends on the sign of p / q. - * - * signum is 1 if p and q are both nonnegative or both negative, and -1 - * otherwise. - */ - int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1)); - boolean increment; - switch (mode) { - case UNNECESSARY: - checkRoundingUnnecessary(rem == 0); - // fall through - case DOWN: - increment = false; - break; - case UP: - increment = true; - break; - case CEILING: - increment = signum > 0; - break; - case FLOOR: - increment = signum < 0; - break; - case HALF_EVEN: - case HALF_DOWN: - case HALF_UP: - long absRem = abs(rem); - long cmpRemToHalfDivisor = absRem - (abs(q) - absRem); - // subtracting two nonnegative longs can't overflow - // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). - if (cmpRemToHalfDivisor == 0) { // exactly on the half mark - increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0)); - } else { - increment = cmpRemToHalfDivisor > 0; // closer to the UP value - } - break; - default: - throw new AssertionError(); - } - return increment ? div + signum : div; - } - - /** - * Returns {@code x mod m}, a non-negative value less than {@code m}. This - * differs from {@code x % m}, which might be negative. - * - *

              - * For example: - * - *

              -	 *  {@code
              -	 *
              -	 * mod(7, 4) == 3
              -	 * mod(-7, 4) == 1
              -	 * mod(-1, 4) == 3
              -	 * mod(-8, 4) == 0
              -	 * mod(8, 4) == 0}
              -	 * 
              - * - * @throws ArithmeticException if {@code m <= 0} - * @see - * Remainder Operator - */ - @GwtIncompatible("TODO") - public static int mod(long x, int m) { - // Cast is safe because the result is guaranteed in the range [0, m) - return (int) mod(x, (long) m); - } - - /** - * Returns {@code x mod m}, a non-negative value less than {@code m}. This - * differs from {@code x % m}, which might be negative. - * - *

              - * For example: - * - *

              -	 *  {@code
              -	 *
              -	 * mod(7, 4) == 3
              -	 * mod(-7, 4) == 1
              -	 * mod(-1, 4) == 3
              -	 * mod(-8, 4) == 0
              -	 * mod(8, 4) == 0}
              -	 * 
              - * - * @throws ArithmeticException if {@code m <= 0} - * @see - * Remainder Operator - */ - @GwtIncompatible("TODO") - public static long mod(long x, long m) { - if (m <= 0) { - throw new ArithmeticException("Modulus must be positive"); - } - long result = x % m; - return (result >= 0) ? result : result + m; - } - - /** - * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if - * {@code a == 0 && b == 0}. - * - * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} - */ - public static long gcd(long a, long b) { - /* - * The reason we require both arguments to be >= 0 is because otherwise, what do - * you return on gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive - * 2^63, but positive 2^63 isn't an int. - */ - checkNonNegative("a", a); - checkNonNegative("b", b); - if (a == 0) { - // 0 % b == 0, so b divides a, but the converse doesn't hold. - // BigInteger.gcd is consistent with this decision. - return b; - } else if (b == 0) { - return a; // similar logic - } - /* - * Uses the binary GCD algorithm; see - * http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is >60% faster than - * the Euclidean algorithm in benchmarks. - */ - int aTwos = Long.numberOfTrailingZeros(a); - a >>= aTwos; // divide out all 2s - int bTwos = Long.numberOfTrailingZeros(b); - b >>= bTwos; // divide out all 2s - while (a != b) { // both a, b are odd - // The key to the binary GCD algorithm is as follows: - // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). - // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers - // of two. - - // We bend over backwards to avoid branching, adapting a technique from - // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax - - long delta = a - b; // can't overflow, since a and b are nonnegative - - long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); - // equivalent to Math.min(delta, 0) - - a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) - // a is now nonnegative and even - - b += minDeltaOrZero; // sets b to min(old a, b) - a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b - } - return a << min(aTwos, bTwos); - } - - /** - * Returns the sum of {@code a} and {@code b}, provided it does not overflow. - * - * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} - * arithmetic - */ - @GwtIncompatible("TODO") - public static long checkedAdd(long a, long b) { - long result = a + b; - checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0); - return result; - } - - /** - * Returns the difference of {@code a} and {@code b}, provided it does not - * overflow. - * - * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} - * arithmetic - */ - @GwtIncompatible("TODO") - public static long checkedSubtract(long a, long b) { - long result = a - b; - checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0); - return result; - } - - /** - * Returns the product of {@code a} and {@code b}, provided it does not - * overflow. - * - * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} - * arithmetic - */ - @GwtIncompatible("TODO") - public static long checkedMultiply(long a, long b) { - // Hacker's Delight, Section 2-12 - int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) - + Long.numberOfLeadingZeros(~b); - /* - * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE - * it's definitely bad. We do the leadingZeros check to avoid the division below - * if at all possible. - * - * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 - * and 1. We take care of all a < 0 with their own check, because in particular, - * the case a == -1 will incorrectly pass the division check below. - * - * In all other cases, we check that either a is 0 or the result is consistent - * with division. - */ - if (leadingZeros > Long.SIZE + 1) { - return a * b; - } - checkNoOverflow(leadingZeros >= Long.SIZE); - checkNoOverflow(a >= 0 | b != Long.MIN_VALUE); - long result = a * b; - checkNoOverflow(a == 0 || result / a == b); - return result; - } - - /** - * Returns the {@code b} to the {@code k}th power, provided it does not - * overflow. - * - * @throws ArithmeticException if {@code b} to the {@code k}th power overflows - * in signed {@code long} arithmetic - */ - @GwtIncompatible("TODO") - public static long checkedPow(long b, int k) { - checkNonNegative("exponent", k); - if (b >= -2 & b <= 2) { - switch ((int) b) { - case 0: - return (k == 0) ? 1 : 0; - case 1: - return 1; - case (-1): - return ((k & 1) == 0) ? 1 : -1; - case 2: - checkNoOverflow(k < Long.SIZE - 1); - return 1L << k; - case (-2): - checkNoOverflow(k < Long.SIZE); - return ((k & 1) == 0) ? (1L << k) : (-1L << k); - default: - throw new AssertionError(); - } - } - long accum = 1; - while (true) { - switch (k) { - case 0: - return accum; - case 1: - return checkedMultiply(accum, b); - default: - if ((k & 1) != 0) { - accum = checkedMultiply(accum, b); - } - k >>= 1; - if (k > 0) { - checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG); - b *= b; - } - } - } - } - - @VisibleForTesting - static final long FLOOR_SQRT_MAX_LONG = 3037000499L; - - /** - * Returns {@code n!}, that is, the product of the first {@code n} positive - * integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the - * result does not fit in a {@code long}. - * - * @throws IllegalArgumentException if {@code n < 0} - */ - @GwtIncompatible("TODO") - public static long factorial(int n) { - checkNonNegative("n", n); - return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE; - } - - static final long[] factorials = { 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, - 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, - 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 }; - - /** - * Returns {@code n} choose {@code k}, also known as the binomial coefficient of - * {@code n} and {@code k}, or {@link Long#MAX_VALUE} if the result does not fit - * in a {@code long}. - * - * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or - * {@code k > n} - */ - public static long binomial(int n, int k) { - checkNonNegative("n", n); - checkNonNegative("k", k); - checkArgument(k <= n, "k (%s) > n (%s)", k, n); - if (k > (n >> 1)) { - k = n - k; - } - switch (k) { - case 0: - return 1; - case 1: - return n; - default: - if (n < factorials.length) { - return factorials[n] / (factorials[k] * factorials[n - k]); - } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { - return Long.MAX_VALUE; - } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { - // guaranteed not to overflow - long result = n--; - for (int i = 2; i <= k; n--, i++) { - result *= n; - result /= i; - } - return result; - } else { - int nBits = LongMath.log2(n, RoundingMode.CEILING); - - long result = 1; - long numerator = n--; - long denominator = 1; - - int numeratorBits = nBits; - // This is an upper bound on log2(numerator, ceiling). - - /* - * We want to do this in long math for speed, but want to avoid overflow. We - * adapt the technique previously used by BigIntegerMath: maintain separate - * numerator and denominator accumulators, multiplying the fraction into result - * when near overflow. - */ - for (int i = 2; i <= k; i++, n--) { - if (numeratorBits + nBits < Long.SIZE - 1) { - // It's definitely safe to multiply into numerator and denominator. - numerator *= n; - denominator *= i; - numeratorBits += nBits; - } else { - // It might not be safe to multiply into numerator and denominator, - // so multiply (numerator / denominator) into result. - result = multiplyFraction(result, numerator, denominator); - numerator = n; - denominator = i; - numeratorBits = nBits; - } - } - return multiplyFraction(result, numerator, denominator); - } - } - } - - /** - * Returns (x * numerator / denominator), which is assumed to come out to an - * integral value. - */ - static long multiplyFraction(long x, long numerator, long denominator) { - if (x == 1) { - return numerator / denominator; - } - long commonDivisor = gcd(x, denominator); - x /= commonDivisor; - denominator /= commonDivisor; - // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, - // so denominator must be a divisor of numerator. - return x * (numerator / denominator); - } - - /* - * binomial(biggestBinomials[k], k) fits in a long, but not - * binomial(biggestBinomials[k] + 1, k). - */ - static final int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, - 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, - 67, 67, 66, 66, 66, 66 }; - - /* - * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower - * GCD-based impl, but binomial(biggestSimpleBinomials[k] + 1, k) does. - */ - @VisibleForTesting - static final int[] biggestSimpleBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, - 86251, 11724, 3218, 1313, 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, - 62, 62, 61, 61, 61 }; - // These values were generated by using checkedMultiply to see when the simple - // multiply/divide - // algorithm would lead to an overflow. - - static boolean fitsInInt(long x) { - return (int) x == x; - } - - /** - * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward - * negative infinity. This method is resilient to overflow. - * - * @since 14.0 - */ - public static long mean(long x, long y) { - // Efficient method for computing the arithmetic mean. - // The alternative (x + y) / 2 fails for large values. - // The alternative (x + y) >>> 1 fails for negative values. - return (x & y) + ((x ^ y) >> 1); - } - private LongMath() { } } diff --git a/src/main/java/com/google/common/math/MathPreconditions.java b/src/main/java/com/google/common/math/MathPreconditions.java index 3786021c..e8a314a8 100644 --- a/src/main/java/com/google/common/math/MathPreconditions.java +++ b/src/main/java/com/google/common/math/MathPreconditions.java @@ -27,23 +27,22 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible final class MathPreconditions { - static int checkPositive(@Nullable String role, int x) { - if (x <= 0) { - throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); + static void checkInRange(boolean condition) { + if (!condition) { + throw new ArithmeticException("not in range"); + } + } + + static BigInteger checkNonNegative(@Nullable String role, BigInteger x) { + if (x.signum() < 0) { + throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } - static long checkPositive(@Nullable String role, long x) { - if (x <= 0) { - throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); - } - return x; - } - - static BigInteger checkPositive(@Nullable String role, BigInteger x) { - if (x.signum() <= 0) { - throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); + static double checkNonNegative(@Nullable String role, double x) { + if (!(x >= 0)) { // not x < 0, to work with NaN. + throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } @@ -62,16 +61,29 @@ final class MathPreconditions { return x; } - static BigInteger checkNonNegative(@Nullable String role, BigInteger x) { - if (x.signum() < 0) { - throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); + static void checkNoOverflow(boolean condition) { + if (!condition) { + throw new ArithmeticException("overflow"); + } + } + + static BigInteger checkPositive(@Nullable String role, BigInteger x) { + if (x.signum() <= 0) { + throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } - static double checkNonNegative(@Nullable String role, double x) { - if (!(x >= 0)) { // not x < 0, to work with NaN. - throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); + static int checkPositive(@Nullable String role, int x) { + if (x <= 0) { + throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); + } + return x; + } + + static long checkPositive(@Nullable String role, long x) { + if (x <= 0) { + throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } @@ -82,18 +94,6 @@ final class MathPreconditions { } } - static void checkInRange(boolean condition) { - if (!condition) { - throw new ArithmeticException("not in range"); - } - } - - static void checkNoOverflow(boolean condition) { - if (!condition) { - throw new ArithmeticException("overflow"); - } - } - private MathPreconditions() { } } diff --git a/src/main/java/com/google/common/primitives/Booleans.java b/src/main/java/com/google/common/primitives/Booleans.java index 5c60d1e0..c0749797 100644 --- a/src/main/java/com/google/common/primitives/Booleans.java +++ b/src/main/java/com/google/common/primitives/Booleans.java @@ -48,18 +48,174 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible public final class Booleans { - private Booleans() { + @GwtCompatible + private static class BooleanArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final boolean[] array; + final int start; + + final int end; + + BooleanArrayAsList(boolean[] array) { + this(array, 0, array.length); + } + + BooleanArrayAsList(boolean[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Boolean) && Booleans.indexOf(array, (Boolean) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof BooleanArrayAsList) { + BooleanArrayAsList that = (BooleanArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Boolean get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Booleans.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Boolean) { + int i = Booleans.indexOf(array, (Boolean) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Boolean) { + int i = Booleans.lastIndexOf(array, (Boolean) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Boolean set(int index, Boolean element) { + checkElementIndex(index, size()); + boolean oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new BooleanArrayAsList(array, start + fromIndex, start + toIndex); + } + + boolean[] toBooleanArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + boolean[] result = new boolean[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 7); + builder.append(array[start] ? "[true" : "[false"); + for (int i = start + 1; i < end; i++) { + builder.append(array[i] ? ", true" : ", false"); + } + return builder.append(']').toString(); + } + } + + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(boolean[] left, boolean[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Booleans.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } } /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Boolean) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * - * @param value a primitive {@code boolean} value - * @return a hash code for the value + *

              + * The returned list maintains the values, but not the identities, of + * {@code Boolean} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(boolean value) { - return value ? 1231 : 1237; + public static List asList(boolean... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new BooleanArrayAsList(backingArray); } /** @@ -80,6 +236,29 @@ public final class Booleans { return (a == b) ? 0 : (a ? 1 : -1); } + /** + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new boolean[] {a, b}, new boolean[] {}, new boolean[] + * {c}} returns the array {@code {a, b, c}}. + * + * @param arrays zero or more {@code boolean} arrays + * @return a single array containing all the values from the source arrays, in + * order + */ + public static boolean[] concat(boolean[]... arrays) { + int length = 0; + for (boolean[] array : arrays) { + length += array.length; + } + boolean[] result = new boolean[length]; + int pos = 0; + for (boolean[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; + } + /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. @@ -104,6 +283,62 @@ public final class Booleans { return false; } + // Arrays.copyOf() requires Java 6 + private static boolean[] copyOf(boolean[] original, int length) { + boolean[] copy = new boolean[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns the number of {@code values} that are {@code true}. + * + * @since 16.0 + */ + @Beta + public static int countTrue(boolean... values) { + int count = 0; + for (boolean value : values) { + if (value) { + count++; + } + } + return count; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static boolean[] ensureCapacity(boolean[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Boolean) value).hashCode()}. + * + * @param value a primitive {@code boolean} value + * @return a hash code for the value + */ + public static int hashCode(boolean value) { + return value ? 1231 : 1237; + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. @@ -161,81 +396,6 @@ public final class Booleans { return -1; } - /** - * Returns the index of the last appearance of the value {@code target} in - * {@code array}. - * - * @param array an array of {@code boolean} values, possibly empty - * @param target a primitive {@code boolean} value - * @return the greatest index {@code i} for which {@code array[i] == target}, or - * {@code -1} if no such index exists. - */ - public static int lastIndexOf(boolean[] array, boolean target) { - return lastIndexOf(array, target, 0, array.length); - } - - // TODO(kevinb): consider making this public - private static int lastIndexOf(boolean[] array, boolean target, int start, int end) { - for (int i = end - 1; i >= start; i--) { - if (array[i] == target) { - return i; - } - } - return -1; - } - - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new boolean[] {a, b}, new boolean[] {}, new boolean[] - * {c}} returns the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code boolean} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static boolean[] concat(boolean[]... arrays) { - int length = 0; - for (boolean[] array : arrays) { - length += array.length; - } - boolean[] result = new boolean[length]; - int pos = 0; - for (boolean[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static boolean[] ensureCapacity(boolean[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static boolean[] copyOf(boolean[] original, int length) { - boolean[] copy = new boolean[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; - } - /** * Returns a string containing the supplied {@code boolean} values separated by * {@code separator}. For example, {@code join("-", false, true, false)} returns @@ -260,6 +420,29 @@ public final class Booleans { return builder.toString(); } + /** + * Returns the index of the last appearance of the value {@code target} in + * {@code array}. + * + * @param array an array of {@code boolean} values, possibly empty + * @param target a primitive {@code boolean} value + * @return the greatest index {@code i} for which {@code array[i] == target}, or + * {@code -1} if no such index exists. + */ + public static int lastIndexOf(boolean[] array, boolean target) { + return lastIndexOf(array, target, 0, array.length); + } + + // TODO(kevinb): consider making this public + private static int lastIndexOf(boolean[] array, boolean target, int start, int end) { + for (int i = end - 1; i >= start; i--) { + if (array[i] == target) { + return i; + } + } + return -1; + } + /** * Returns a comparator that compares two {@code boolean} arrays * lexicographically. That is, it compares, using @@ -281,22 +464,6 @@ public final class Booleans { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(boolean[] left, boolean[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Booleans.compare(left[i], right[i]); - if (result != 0) { - return result; - } - } - return left.length - right.length; - } - } - /** * Copies a collection of {@code Boolean} instances into a new array of * primitive {@code boolean} values. @@ -331,173 +498,6 @@ public final class Booleans { return array; } - /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. - * - *

              - * The returned list maintains the values, but not the identities, of - * {@code Boolean} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - * @param backingArray the array to back the list - * @return a list view of the array - */ - public static List asList(boolean... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new BooleanArrayAsList(backingArray); - } - - @GwtCompatible - private static class BooleanArrayAsList extends AbstractList implements RandomAccess, Serializable { - final boolean[] array; - final int start; - final int end; - - BooleanArrayAsList(boolean[] array) { - this(array, 0, array.length); - } - - BooleanArrayAsList(boolean[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Boolean get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Boolean) && Booleans.indexOf(array, (Boolean) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Boolean) { - int i = Booleans.indexOf(array, (Boolean) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Boolean) { - int i = Booleans.lastIndexOf(array, (Boolean) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Boolean set(int index, Boolean element) { - checkElementIndex(index, size()); - boolean oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new BooleanArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof BooleanArrayAsList) { - BooleanArrayAsList that = (BooleanArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Booleans.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 7); - builder.append(array[start] ? "[true" : "[false"); - for (int i = start + 1; i < end; i++) { - builder.append(array[i] ? ", true" : ", false"); - } - return builder.append(']').toString(); - } - - boolean[] toBooleanArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - boolean[] result = new boolean[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; - } - - /** - * Returns the number of {@code values} that are {@code true}. - * - * @since 16.0 - */ - @Beta - public static int countTrue(boolean... values) { - int count = 0; - for (boolean value : values) { - if (value) { - count++; - } - } - return count; + private Booleans() { } } diff --git a/src/main/java/com/google/common/primitives/Bytes.java b/src/main/java/com/google/common/primitives/Bytes.java index 895fc479..ef628fff 100644 --- a/src/main/java/com/google/common/primitives/Bytes.java +++ b/src/main/java/com/google/common/primitives/Bytes.java @@ -50,18 +50,181 @@ import com.google.common.annotations.GwtCompatible; // javadoc? @GwtCompatible public final class Bytes { - private Bytes() { + @GwtCompatible + private static class ByteArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final byte[] array; + final int start; + + final int end; + + ByteArrayAsList(byte[] array) { + this(array, 0, array.length); + } + + ByteArrayAsList(byte[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof ByteArrayAsList) { + ByteArrayAsList that = (ByteArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Byte get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Bytes.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Byte) { + int i = Bytes.indexOf(array, (Byte) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Byte) { + int i = Bytes.lastIndexOf(array, (Byte) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Byte set(int index, Byte element) { + checkElementIndex(index, size()); + byte oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new ByteArrayAsList(array, start + fromIndex, start + toIndex); + } + + byte[] toByteArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + byte[] result = new byte[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 5); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } } /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Byte) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * - * @param value a primitive {@code byte} value - * @return a hash code for the value + *

              + * The returned list maintains the values, but not the identities, of + * {@code Byte} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(byte value) { - return value; + public static List asList(byte... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new ByteArrayAsList(backingArray); + } + + /** + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new byte[] {a, b}, new byte[] {}, new byte[] {c}} + * returns the array {@code {a, b, c}}. + * + * @param arrays zero or more {@code byte} arrays + * @return a single array containing all the values from the source arrays, in + * order + */ + public static byte[] concat(byte[]... arrays) { + int length = 0; + for (byte[] array : arrays) { + length += array.length; + } + byte[] result = new byte[length]; + int pos = 0; + for (byte[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; } /** @@ -82,6 +245,46 @@ public final class Bytes { return false; } + // Arrays.copyOf() requires Java 6 + private static byte[] copyOf(byte[] original, int length) { + byte[] copy = new byte[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static byte[] ensureCapacity(byte[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Byte) value).hashCode()}. + * + * @param value a primitive {@code byte} value + * @return a hash code for the value + */ + public static int hashCode(byte value) { + return value; + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. @@ -158,58 +361,6 @@ public final class Bytes { return -1; } - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new byte[] {a, b}, new byte[] {}, new byte[] {c}} - * returns the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code byte} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static byte[] concat(byte[]... arrays) { - int length = 0; - for (byte[] array : arrays) { - length += array.length; - } - byte[] result = new byte[length]; - int pos = 0; - for (byte[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static byte[] ensureCapacity(byte[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static byte[] copyOf(byte[] original, int length) { - byte[] copy = new byte[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; - } - /** * Returns an array containing each value of {@code collection}, converted to a * {@code byte} value in the manner of {@link Number#byteValue}. @@ -241,157 +392,6 @@ public final class Bytes { return array; } - /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. - * - *

              - * The returned list maintains the values, but not the identities, of - * {@code Byte} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - * @param backingArray the array to back the list - * @return a list view of the array - */ - public static List asList(byte... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new ByteArrayAsList(backingArray); - } - - @GwtCompatible - private static class ByteArrayAsList extends AbstractList implements RandomAccess, Serializable { - final byte[] array; - final int start; - final int end; - - ByteArrayAsList(byte[] array) { - this(array, 0, array.length); - } - - ByteArrayAsList(byte[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Byte get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Byte) { - int i = Bytes.indexOf(array, (Byte) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Byte) { - int i = Bytes.lastIndexOf(array, (Byte) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Byte set(int index, Byte element) { - checkElementIndex(index, size()); - byte oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new ByteArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof ByteArrayAsList) { - ByteArrayAsList that = (ByteArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Bytes.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 5); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - byte[] toByteArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - byte[] result = new byte[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; + private Bytes() { } } diff --git a/src/main/java/com/google/common/primitives/Chars.java b/src/main/java/com/google/common/primitives/Chars.java index 7ab1f00b..f6e763db 100644 --- a/src/main/java/com/google/common/primitives/Chars.java +++ b/src/main/java/com/google/common/primitives/Chars.java @@ -50,7 +50,152 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible(emulated = true) public final class Chars { - private Chars() { + @GwtCompatible + private static class CharArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final char[] array; + final int start; + + final int end; + + CharArrayAsList(char[] array) { + this(array, 0, array.length); + } + + CharArrayAsList(char[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof CharArrayAsList) { + CharArrayAsList that = (CharArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Character get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Chars.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Character) { + int i = Chars.indexOf(array, (Character) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Character) { + int i = Chars.lastIndexOf(array, (Character) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Character set(int index, Character element) { + checkElementIndex(index, size()); + char oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new CharArrayAsList(array, start + fromIndex, start + toIndex); + } + + char[] toCharArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + char[] result = new char[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 3); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } + } + + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(char[] left, char[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Chars.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } } /** @@ -59,14 +204,25 @@ public final class Chars { public static final int BYTES = Character.SIZE / Byte.SIZE; /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Character) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * - * @param value a primitive {@code char} value - * @return a hash code for the value + *

              + * The returned list maintains the values, but not the identities, of + * {@code Character} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(char value) { - return value; + public static List asList(char... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new CharArrayAsList(backingArray); } /** @@ -87,24 +243,6 @@ public final class Chars { return result; } - /** - * Returns the {@code char} nearest in value to {@code value}. - * - * @param value any {@code long} value - * @return the same value cast to {@code char} if it is in the range of the - * {@code char} type, {@link Character#MAX_VALUE} if it is too large, or - * {@link Character#MIN_VALUE} if it is too small - */ - public static char saturatedCast(long value) { - if (value > Character.MAX_VALUE) { - return Character.MAX_VALUE; - } - if (value < Character.MIN_VALUE) { - return Character.MIN_VALUE; - } - return (char) value; - } - /** * Compares the two specified {@code char} values. The sign of the value * returned is the same as that of {@code ((Character) a).compareTo(b)}. @@ -123,6 +261,29 @@ public final class Chars { return a - b; // safe due to restricted range } + /** + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new char[] {a, b}, new char[] {}, new char[] {c}} + * returns the array {@code {a, b, c}}. + * + * @param arrays zero or more {@code char} arrays + * @return a single array containing all the values from the source arrays, in + * order + */ + public static char[] concat(char[]... arrays) { + int length = 0; + for (char[] array : arrays) { + length += array.length; + } + char[] result = new char[length]; + int pos = 0; + for (char[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; + } + /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. @@ -141,6 +302,46 @@ public final class Chars { return false; } + // Arrays.copyOf() requires Java 6 + private static char[] copyOf(char[] original, int length) { + char[] copy = new char[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static char[] ensureCapacity(char[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Character) value).hashCode()}. + * + * @param value a primitive {@code char} value + * @return a hash code for the value + */ + public static int hashCode(char value) { + return value; + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. @@ -194,119 +395,6 @@ public final class Chars { return -1; } - /** - * Returns the index of the last appearance of the value {@code target} in - * {@code array}. - * - * @param array an array of {@code char} values, possibly empty - * @param target a primitive {@code char} value - * @return the greatest index {@code i} for which {@code array[i] == target}, or - * {@code -1} if no such index exists. - */ - public static int lastIndexOf(char[] array, char target) { - return lastIndexOf(array, target, 0, array.length); - } - - // TODO(kevinb): consider making this public - private static int lastIndexOf(char[] array, char target, int start, int end) { - for (int i = end - 1; i >= start; i--) { - if (array[i] == target) { - return i; - } - } - return -1; - } - - /** - * Returns the least value present in {@code array}. - * - * @param array a nonempty array of {@code char} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static char min(char... array) { - checkArgument(array.length > 0); - char min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - return min; - } - - /** - * Returns the greatest value present in {@code array}. - * - * @param array a nonempty array of {@code char} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static char max(char... array) { - checkArgument(array.length > 0); - char max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - return max; - } - - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new char[] {a, b}, new char[] {}, new char[] {c}} - * returns the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code char} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static char[] concat(char[]... arrays) { - int length = 0; - for (char[] array : arrays) { - length += array.length; - } - char[] result = new char[length]; - int pos = 0; - for (char[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static char[] ensureCapacity(char[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static char[] copyOf(char[] original, int length) { - char[] copy = new char[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; - } - /** * Returns a string containing the supplied {@code char} values separated by * {@code separator}. For example, {@code join("-", '1', '2', '3')} returns the @@ -331,6 +419,29 @@ public final class Chars { return builder.toString(); } + /** + * Returns the index of the last appearance of the value {@code target} in + * {@code array}. + * + * @param array an array of {@code char} values, possibly empty + * @param target a primitive {@code char} value + * @return the greatest index {@code i} for which {@code array[i] == target}, or + * {@code -1} if no such index exists. + */ + public static int lastIndexOf(char[] array, char target) { + return lastIndexOf(array, target, 0, array.length); + } + + // TODO(kevinb): consider making this public + private static int lastIndexOf(char[] array, char target, int start, int end) { + for (int i = end - 1; i >= start; i--) { + if (array[i] == target) { + return i; + } + } + return -1; + } + /** * Returns a comparator that compares two {@code char} arrays lexicographically. * That is, it compares, using {@link #compare(char, char)}), the first pair of @@ -351,20 +462,60 @@ public final class Chars { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(char[] left, char[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Chars.compare(left[i], right[i]); - if (result != 0) { - return result; - } + /** + * Returns the greatest value present in {@code array}. + * + * @param array a nonempty array of {@code char} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static char max(char... array) { + checkArgument(array.length > 0); + char max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; } - return left.length - right.length; } + return max; + } + + /** + * Returns the least value present in {@code array}. + * + * @param array a nonempty array of {@code char} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static char min(char... array) { + checkArgument(array.length > 0); + char min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + return min; + } + + /** + * Returns the {@code char} nearest in value to {@code value}. + * + * @param value any {@code long} value + * @return the same value cast to {@code char} if it is in the range of the + * {@code char} type, {@link Character#MAX_VALUE} if it is too large, or + * {@link Character#MIN_VALUE} if it is too small + */ + public static char saturatedCast(long value) { + if (value > Character.MAX_VALUE) { + return Character.MAX_VALUE; + } + if (value < Character.MIN_VALUE) { + return Character.MIN_VALUE; + } + return (char) value; } /** @@ -397,157 +548,6 @@ public final class Chars { return array; } - /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. - * - *

              - * The returned list maintains the values, but not the identities, of - * {@code Character} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - * @param backingArray the array to back the list - * @return a list view of the array - */ - public static List asList(char... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new CharArrayAsList(backingArray); - } - - @GwtCompatible - private static class CharArrayAsList extends AbstractList implements RandomAccess, Serializable { - final char[] array; - final int start; - final int end; - - CharArrayAsList(char[] array) { - this(array, 0, array.length); - } - - CharArrayAsList(char[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Character get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Character) { - int i = Chars.indexOf(array, (Character) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Character) { - int i = Chars.lastIndexOf(array, (Character) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Character set(int index, Character element) { - checkElementIndex(index, size()); - char oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new CharArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof CharArrayAsList) { - CharArrayAsList that = (CharArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Chars.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 3); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - char[] toCharArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - char[] result = new char[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; + private Chars() { } } diff --git a/src/main/java/com/google/common/primitives/Doubles.java b/src/main/java/com/google/common/primitives/Doubles.java index f9ee47e2..8f69aceb 100644 --- a/src/main/java/com/google/common/primitives/Doubles.java +++ b/src/main/java/com/google/common/primitives/Doubles.java @@ -54,7 +54,177 @@ import com.google.common.base.Converter; */ @GwtCompatible(emulated = true) public final class Doubles { - private Doubles() { + @GwtCompatible + private static class DoubleArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final double[] array; + final int start; + + final int end; + + DoubleArrayAsList(double[] array) { + this(array, 0, array.length); + } + + DoubleArrayAsList(double[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Double) && Doubles.indexOf(array, (Double) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof DoubleArrayAsList) { + DoubleArrayAsList that = (DoubleArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Double get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Doubles.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Double) { + int i = Doubles.indexOf(array, (Double) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Double) { + int i = Doubles.lastIndexOf(array, (Double) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Double set(int index, Double element) { + checkElementIndex(index, size()); + double oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); + } + + double[] toDoubleArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + double[] result = new double[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 12); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } + } + + private static final class DoubleConverter extends Converter implements Serializable { + static final DoubleConverter INSTANCE = new DoubleConverter(); + + private static final long serialVersionUID = 1; + + @Override + protected String doBackward(Double value) { + return value.toString(); + } + + @Override + protected Double doForward(String value) { + return Double.valueOf(value); + } + + private Object readResolve() { + return INSTANCE; + } + + @Override + public String toString() { + return "Doubles.stringConverter()"; + } + } + + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(double[] left, double[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Doubles.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } } /** @@ -65,17 +235,38 @@ public final class Doubles { public static final int BYTES = Double.SIZE / Byte.SIZE; /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Double) value).hashCode()}. - * - * @param value a primitive {@code double} value - * @return a hash code for the value + * This is adapted from the regex suggested by {@link Double#valueOf(String)} + * for prevalidating inputs. All valid inputs must pass this regex, but it's + * semantically fine if not all inputs that pass this regex are valid -- only a + * performance hit is incurred, not a semantics bug. */ - public static int hashCode(double value) { - return ((Double) value).hashCode(); - // TODO(kevinb): do it this way when we can (GWT problem): - // long bits = Double.doubleToLongBits(value); - // return (int) (bits ^ (bits >>> 32)); + @GwtIncompatible("regular expressions") + static final Pattern FLOATING_POINT_PATTERN = fpPattern(); + + /** + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. + * + *

              + * The returned list maintains the values, but not the identities, of + * {@code Double} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + *

              + * The returned list may have unexpected behavior if it contains {@code + * NaN}, or if {@code NaN} is used as a parameter to any of its methods. + * + * @param backingArray the array to back the list + * @return a list view of the array + */ + public static List asList(double... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new DoubleArrayAsList(backingArray); } /** @@ -100,14 +291,26 @@ public final class Doubles { } /** - * Returns {@code true} if {@code value} represents a real number. This is - * equivalent to, but not necessarily implemented as, - * {@code !(Double.isInfinite(value) || Double.isNaN(value))}. + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new double[] {a, b}, new double[] {}, new double[] + * {c}} returns the array {@code {a, b, c}}. * - * @since 10.0 + * @param arrays zero or more {@code double} arrays + * @return a single array containing all the values from the source arrays, in + * order */ - public static boolean isFinite(double value) { - return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; + public static double[] concat(double[]... arrays) { + int length = 0; + for (double[] array : arrays) { + length += array.length; + } + double[] result = new double[length]; + int pos = 0; + for (double[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; } /** @@ -129,6 +332,59 @@ public final class Doubles { return false; } + // Arrays.copyOf() requires Java 6 + private static double[] copyOf(double[] original, int length) { + double[] copy = new double[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static double[] ensureCapacity(double[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + @GwtIncompatible("regular expressions") + private static Pattern fpPattern() { + String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)"; + String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?"; + String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)"; + String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?"; + String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; + return Pattern.compile(fpPattern); + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Double) value).hashCode()}. + * + * @param value a primitive {@code double} value + * @return a hash code for the value + */ + public static int hashCode(double value) { + return ((Double) value).hashCode(); + // TODO(kevinb): do it this way when we can (GWT problem): + // long bits = Double.doubleToLongBits(value); + // return (int) (bits ^ (bits >>> 32)); + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} @@ -188,151 +444,14 @@ public final class Doubles { } /** - * Returns the index of the last appearance of the value {@code target} in - * {@code array}. Note that this always returns {@code -1} when {@code target} - * is {@code NaN}. + * Returns {@code true} if {@code value} represents a real number. This is + * equivalent to, but not necessarily implemented as, + * {@code !(Double.isInfinite(value) || Double.isNaN(value))}. * - * @param array an array of {@code double} values, possibly empty - * @param target a primitive {@code double} value - * @return the greatest index {@code i} for which {@code array[i] == target}, or - * {@code -1} if no such index exists. + * @since 10.0 */ - public static int lastIndexOf(double[] array, double target) { - return lastIndexOf(array, target, 0, array.length); - } - - // TODO(kevinb): consider making this public - private static int lastIndexOf(double[] array, double target, int start, int end) { - for (int i = end - 1; i >= start; i--) { - if (array[i] == target) { - return i; - } - } - return -1; - } - - /** - * Returns the least value present in {@code array}, using the same rules of - * comparison as {@link Math#min(double, double)}. - * - * @param array a nonempty array of {@code double} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static double min(double... array) { - checkArgument(array.length > 0); - double min = array[0]; - for (int i = 1; i < array.length; i++) { - min = Math.min(min, array[i]); - } - return min; - } - - /** - * Returns the greatest value present in {@code array}, using the same rules of - * comparison as {@link Math#max(double, double)}. - * - * @param array a nonempty array of {@code double} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static double max(double... array) { - checkArgument(array.length > 0); - double max = array[0]; - for (int i = 1; i < array.length; i++) { - max = Math.max(max, array[i]); - } - return max; - } - - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new double[] {a, b}, new double[] {}, new double[] - * {c}} returns the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code double} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static double[] concat(double[]... arrays) { - int length = 0; - for (double[] array : arrays) { - length += array.length; - } - double[] result = new double[length]; - int pos = 0; - for (double[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - private static final class DoubleConverter extends Converter implements Serializable { - static final DoubleConverter INSTANCE = new DoubleConverter(); - - @Override - protected Double doForward(String value) { - return Double.valueOf(value); - } - - @Override - protected String doBackward(Double value) { - return value.toString(); - } - - @Override - public String toString() { - return "Doubles.stringConverter()"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; - } - - /** - * Returns a serializable converter object that converts between strings and - * doubles using {@link Double#valueOf} and {@link Double#toString()}. - * - * @since 16.0 - */ - @Beta - public static Converter stringConverter() { - return DoubleConverter.INSTANCE; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static double[] ensureCapacity(double[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static double[] copyOf(double[] original, int length) { - double[] copy = new double[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; + public static boolean isFinite(double value) { + return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; } /** @@ -365,6 +484,30 @@ public final class Doubles { return builder.toString(); } + /** + * Returns the index of the last appearance of the value {@code target} in + * {@code array}. Note that this always returns {@code -1} when {@code target} + * is {@code NaN}. + * + * @param array an array of {@code double} values, possibly empty + * @param target a primitive {@code double} value + * @return the greatest index {@code i} for which {@code array[i] == target}, or + * {@code -1} if no such index exists. + */ + public static int lastIndexOf(double[] array, double target) { + return lastIndexOf(array, target, 0, array.length); + } + + // TODO(kevinb): consider making this public + private static int lastIndexOf(double[] array, double target, int start, int end) { + for (int i = end - 1; i >= start; i--) { + if (array[i] == target) { + return i; + } + } + return -1; + } + /** * Returns a comparator that compares two {@code double} arrays * lexicographically. That is, it compares, using @@ -385,20 +528,51 @@ public final class Doubles { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(double[] left, double[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Doubles.compare(left[i], right[i]); - if (result != 0) { - return result; - } - } - return left.length - right.length; + /** + * Returns the greatest value present in {@code array}, using the same rules of + * comparison as {@link Math#max(double, double)}. + * + * @param array a nonempty array of {@code double} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static double max(double... array) { + checkArgument(array.length > 0); + double max = array[0]; + for (int i = 1; i < array.length; i++) { + max = Math.max(max, array[i]); } + return max; + } + + /** + * Returns the least value present in {@code array}, using the same rules of + * comparison as {@link Math#min(double, double)}. + * + * @param array a nonempty array of {@code double} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static double min(double... array) { + checkArgument(array.length > 0); + double min = array[0]; + for (int i = 1; i < array.length; i++) { + min = Math.min(min, array[i]); + } + return min; + } + + /** + * Returns a serializable converter object that converts between strings and + * doubles using {@link Double#valueOf} and {@link Double#toString()}. + * + * @since 16.0 + */ + @Beta + public static Converter stringConverter() { + return DoubleConverter.INSTANCE; } /** @@ -432,183 +606,6 @@ public final class Doubles { return array; } - /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. - * - *

              - * The returned list maintains the values, but not the identities, of - * {@code Double} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - *

              - * The returned list may have unexpected behavior if it contains {@code - * NaN}, or if {@code NaN} is used as a parameter to any of its methods. - * - * @param backingArray the array to back the list - * @return a list view of the array - */ - public static List asList(double... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new DoubleArrayAsList(backingArray); - } - - @GwtCompatible - private static class DoubleArrayAsList extends AbstractList implements RandomAccess, Serializable { - final double[] array; - final int start; - final int end; - - DoubleArrayAsList(double[] array) { - this(array, 0, array.length); - } - - DoubleArrayAsList(double[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Double get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Double) && Doubles.indexOf(array, (Double) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Double) { - int i = Doubles.indexOf(array, (Double) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Double) { - int i = Doubles.lastIndexOf(array, (Double) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Double set(int index, Double element) { - checkElementIndex(index, size()); - double oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof DoubleArrayAsList) { - DoubleArrayAsList that = (DoubleArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Doubles.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 12); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - double[] toDoubleArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - double[] result = new double[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; - } - - /** - * This is adapted from the regex suggested by {@link Double#valueOf(String)} - * for prevalidating inputs. All valid inputs must pass this regex, but it's - * semantically fine if not all inputs that pass this regex are valid -- only a - * performance hit is incurred, not a semantics bug. - */ - @GwtIncompatible("regular expressions") - static final Pattern FLOATING_POINT_PATTERN = fpPattern(); - - @GwtIncompatible("regular expressions") - private static Pattern fpPattern() { - String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)"; - String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?"; - String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)"; - String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?"; - String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; - return Pattern.compile(fpPattern); - } - /** * Parses the specified string as a double-precision floating point value. The * ASCII character {@code '-'} ('\u002D') is recognized as the @@ -646,4 +643,7 @@ public final class Doubles { } return null; } + + private Doubles() { + } } diff --git a/src/main/java/com/google/common/primitives/Floats.java b/src/main/java/com/google/common/primitives/Floats.java index 4ddc9348..fe3dc866 100644 --- a/src/main/java/com/google/common/primitives/Floats.java +++ b/src/main/java/com/google/common/primitives/Floats.java @@ -53,7 +53,177 @@ import com.google.common.base.Converter; */ @GwtCompatible(emulated = true) public final class Floats { - private Floats() { + @GwtCompatible + private static class FloatArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final float[] array; + final int start; + + final int end; + + FloatArrayAsList(float[] array) { + this(array, 0, array.length); + } + + FloatArrayAsList(float[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof FloatArrayAsList) { + FloatArrayAsList that = (FloatArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Float get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Floats.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Float) { + int i = Floats.indexOf(array, (Float) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Float) { + int i = Floats.lastIndexOf(array, (Float) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Float set(int index, Float element) { + checkElementIndex(index, size()); + float oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new FloatArrayAsList(array, start + fromIndex, start + toIndex); + } + + float[] toFloatArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + float[] result = new float[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 12); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } + } + + private static final class FloatConverter extends Converter implements Serializable { + static final FloatConverter INSTANCE = new FloatConverter(); + + private static final long serialVersionUID = 1; + + @Override + protected String doBackward(Float value) { + return value.toString(); + } + + @Override + protected Float doForward(String value) { + return Float.valueOf(value); + } + + private Object readResolve() { + return INSTANCE; + } + + @Override + public String toString() { + return "Floats.stringConverter()"; + } + } + + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(float[] left, float[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Floats.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } } /** @@ -64,15 +234,29 @@ public final class Floats { public static final int BYTES = Float.SIZE / Byte.SIZE; /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Float) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * - * @param value a primitive {@code float} value - * @return a hash code for the value + *

              + * The returned list maintains the values, but not the identities, of + * {@code Float} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + *

              + * The returned list may have unexpected behavior if it contains {@code + * NaN}, or if {@code NaN} is used as a parameter to any of its methods. + * + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(float value) { - // TODO(kevinb): is there a better way, that's still gwt-safe? - return ((Float) value).hashCode(); + public static List asList(float... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new FloatArrayAsList(backingArray); } /** @@ -95,14 +279,26 @@ public final class Floats { } /** - * Returns {@code true} if {@code value} represents a real number. This is - * equivalent to, but not necessarily implemented as, - * {@code !(Float.isInfinite(value) || Float.isNaN(value))}. + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new float[] {a, b}, new float[] {}, new float[] {c}} + * returns the array {@code {a, b, c}}. * - * @since 10.0 + * @param arrays zero or more {@code float} arrays + * @return a single array containing all the values from the source arrays, in + * order */ - public static boolean isFinite(float value) { - return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; + public static float[] concat(float[]... arrays) { + int length = 0; + for (float[] array : arrays) { + length += array.length; + } + float[] result = new float[length]; + int pos = 0; + for (float[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; } /** @@ -124,6 +320,47 @@ public final class Floats { return false; } + // Arrays.copyOf() requires Java 6 + private static float[] copyOf(float[] original, int length) { + float[] copy = new float[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static float[] ensureCapacity(float[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Float) value).hashCode()}. + * + * @param value a primitive {@code float} value + * @return a hash code for the value + */ + public static int hashCode(float value) { + // TODO(kevinb): is there a better way, that's still gwt-safe? + return ((Float) value).hashCode(); + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} @@ -183,151 +420,14 @@ public final class Floats { } /** - * Returns the index of the last appearance of the value {@code target} in - * {@code array}. Note that this always returns {@code -1} when {@code target} - * is {@code NaN}. + * Returns {@code true} if {@code value} represents a real number. This is + * equivalent to, but not necessarily implemented as, + * {@code !(Float.isInfinite(value) || Float.isNaN(value))}. * - * @param array an array of {@code float} values, possibly empty - * @param target a primitive {@code float} value - * @return the greatest index {@code i} for which {@code array[i] == target}, or - * {@code -1} if no such index exists. + * @since 10.0 */ - public static int lastIndexOf(float[] array, float target) { - return lastIndexOf(array, target, 0, array.length); - } - - // TODO(kevinb): consider making this public - private static int lastIndexOf(float[] array, float target, int start, int end) { - for (int i = end - 1; i >= start; i--) { - if (array[i] == target) { - return i; - } - } - return -1; - } - - /** - * Returns the least value present in {@code array}, using the same rules of - * comparison as {@link Math#min(float, float)}. - * - * @param array a nonempty array of {@code float} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static float min(float... array) { - checkArgument(array.length > 0); - float min = array[0]; - for (int i = 1; i < array.length; i++) { - min = Math.min(min, array[i]); - } - return min; - } - - /** - * Returns the greatest value present in {@code array}, using the same rules of - * comparison as {@link Math#min(float, float)}. - * - * @param array a nonempty array of {@code float} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static float max(float... array) { - checkArgument(array.length > 0); - float max = array[0]; - for (int i = 1; i < array.length; i++) { - max = Math.max(max, array[i]); - } - return max; - } - - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new float[] {a, b}, new float[] {}, new float[] {c}} - * returns the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code float} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static float[] concat(float[]... arrays) { - int length = 0; - for (float[] array : arrays) { - length += array.length; - } - float[] result = new float[length]; - int pos = 0; - for (float[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - private static final class FloatConverter extends Converter implements Serializable { - static final FloatConverter INSTANCE = new FloatConverter(); - - @Override - protected Float doForward(String value) { - return Float.valueOf(value); - } - - @Override - protected String doBackward(Float value) { - return value.toString(); - } - - @Override - public String toString() { - return "Floats.stringConverter()"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; - } - - /** - * Returns a serializable converter object that converts between strings and - * floats using {@link Float#valueOf} and {@link Float#toString()}. - * - * @since 16.0 - */ - @Beta - public static Converter stringConverter() { - return FloatConverter.INSTANCE; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static float[] ensureCapacity(float[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static float[] copyOf(float[] original, int length) { - float[] copy = new float[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; + public static boolean isFinite(float value) { + return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; } /** @@ -360,6 +460,30 @@ public final class Floats { return builder.toString(); } + /** + * Returns the index of the last appearance of the value {@code target} in + * {@code array}. Note that this always returns {@code -1} when {@code target} + * is {@code NaN}. + * + * @param array an array of {@code float} values, possibly empty + * @param target a primitive {@code float} value + * @return the greatest index {@code i} for which {@code array[i] == target}, or + * {@code -1} if no such index exists. + */ + public static int lastIndexOf(float[] array, float target) { + return lastIndexOf(array, target, 0, array.length); + } + + // TODO(kevinb): consider making this public + private static int lastIndexOf(float[] array, float target, int start, int end) { + for (int i = end - 1; i >= start; i--) { + if (array[i] == target) { + return i; + } + } + return -1; + } + /** * Returns a comparator that compares two {@code float} arrays * lexicographically. That is, it compares, using @@ -381,20 +505,51 @@ public final class Floats { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(float[] left, float[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Floats.compare(left[i], right[i]); - if (result != 0) { - return result; - } - } - return left.length - right.length; + /** + * Returns the greatest value present in {@code array}, using the same rules of + * comparison as {@link Math#min(float, float)}. + * + * @param array a nonempty array of {@code float} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static float max(float... array) { + checkArgument(array.length > 0); + float max = array[0]; + for (int i = 1; i < array.length; i++) { + max = Math.max(max, array[i]); } + return max; + } + + /** + * Returns the least value present in {@code array}, using the same rules of + * comparison as {@link Math#min(float, float)}. + * + * @param array a nonempty array of {@code float} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static float min(float... array) { + checkArgument(array.length > 0); + float min = array[0]; + for (int i = 1; i < array.length; i++) { + min = Math.min(min, array[i]); + } + return min; + } + + /** + * Returns a serializable converter object that converts between strings and + * floats using {@link Float#valueOf} and {@link Float#toString()}. + * + * @since 16.0 + */ + @Beta + public static Converter stringConverter() { + return FloatConverter.INSTANCE; } /** @@ -428,164 +583,6 @@ public final class Floats { return array; } - /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. - * - *

              - * The returned list maintains the values, but not the identities, of - * {@code Float} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - *

              - * The returned list may have unexpected behavior if it contains {@code - * NaN}, or if {@code NaN} is used as a parameter to any of its methods. - * - * @param backingArray the array to back the list - * @return a list view of the array - */ - public static List asList(float... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new FloatArrayAsList(backingArray); - } - - @GwtCompatible - private static class FloatArrayAsList extends AbstractList implements RandomAccess, Serializable { - final float[] array; - final int start; - final int end; - - FloatArrayAsList(float[] array) { - this(array, 0, array.length); - } - - FloatArrayAsList(float[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Float get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Float) { - int i = Floats.indexOf(array, (Float) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Float) { - int i = Floats.lastIndexOf(array, (Float) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Float set(int index, Float element) { - checkElementIndex(index, size()); - float oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new FloatArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof FloatArrayAsList) { - FloatArrayAsList that = (FloatArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Floats.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 12); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - float[] toFloatArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - float[] result = new float[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; - } - /** * Parses the specified string as a single-precision floating point value. The * ASCII character {@code '-'} ('\u002D') is recognized as the @@ -623,4 +620,7 @@ public final class Floats { } return null; } + + private Floats() { + } } diff --git a/src/main/java/com/google/common/primitives/Ints.java b/src/main/java/com/google/common/primitives/Ints.java index dd3e929a..6563bc8f 100644 --- a/src/main/java/com/google/common/primitives/Ints.java +++ b/src/main/java/com/google/common/primitives/Ints.java @@ -51,7 +51,177 @@ import com.google.common.base.Converter; */ @GwtCompatible(emulated = true) public final class Ints { - private Ints() { + @GwtCompatible + private static class IntArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final int[] array; + final int start; + + final int end; + + IntArrayAsList(int[] array) { + this(array, 0, array.length); + } + + IntArrayAsList(int[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof IntArrayAsList) { + IntArrayAsList that = (IntArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Integer get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Ints.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Integer) { + int i = Ints.indexOf(array, (Integer) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Integer) { + int i = Ints.lastIndexOf(array, (Integer) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Integer set(int index, Integer element) { + checkElementIndex(index, size()); + int oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new IntArrayAsList(array, start + fromIndex, start + toIndex); + } + + int[] toIntArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + int[] result = new int[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 5); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } + } + + private static final class IntConverter extends Converter implements Serializable { + static final IntConverter INSTANCE = new IntConverter(); + + private static final long serialVersionUID = 1; + + @Override + protected String doBackward(Integer value) { + return value.toString(); + } + + @Override + protected Integer doForward(String value) { + return Integer.decode(value); + } + + private Object readResolve() { + return INSTANCE; + } + + @Override + public String toString() { + return "Ints.stringConverter()"; + } + } + + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(int[] left, int[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Ints.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } } /** @@ -66,15 +236,39 @@ public final class Ints { */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); + private static final byte[] asciiDigits = new byte[128]; + + static { + Arrays.fill(asciiDigits, (byte) -1); + for (int i = 0; i <= 9; i++) { + asciiDigits['0' + i] = (byte) i; + } + for (int i = 0; i <= 26; i++) { + asciiDigits['A' + i] = (byte) (10 + i); + asciiDigits['a' + i] = (byte) (10 + i); + } + } + /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Integer) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * - * @param value a primitive {@code int} value - * @return a hash code for the value + *

              + * The returned list maintains the values, but not the identities, of + * {@code Integer} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(int value) { - return value; + public static List asList(int... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new IntArrayAsList(backingArray); } /** @@ -95,24 +289,6 @@ public final class Ints { return result; } - /** - * Returns the {@code int} nearest in value to {@code value}. - * - * @param value any {@code long} value - * @return the same value cast to {@code int} if it is in the range of the - * {@code int} type, {@link Integer#MAX_VALUE} if it is too large, or - * {@link Integer#MIN_VALUE} if it is too small - */ - public static int saturatedCast(long value) { - if (value > Integer.MAX_VALUE) { - return Integer.MAX_VALUE; - } - if (value < Integer.MIN_VALUE) { - return Integer.MIN_VALUE; - } - return (int) value; - } - /** * Compares the two specified {@code int} values. The sign of the value returned * is the same as that of {@code ((Integer) a).compareTo(b)}. @@ -131,6 +307,29 @@ public final class Ints { return (a < b) ? -1 : ((a > b) ? 1 : 0); } + /** + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns + * the array {@code {a, b, c}}. + * + * @param arrays zero or more {@code int} arrays + * @return a single array containing all the values from the source arrays, in + * order + */ + public static int[] concat(int[]... arrays) { + int length = 0; + for (int[] array : arrays) { + length += array.length; + } + int[] result = new int[length]; + int pos = 0; + for (int[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; + } + /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. @@ -149,6 +348,82 @@ public final class Ints { return false; } + // Arrays.copyOf() requires Java 6 + private static int[] copyOf(int[] original, int length) { + int[] copy = new int[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + private static int digit(char c) { + return (c < 128) ? asciiDigits[c] : -1; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static int[] ensureCapacity(int[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns the {@code int} value whose big-endian representation is stored in + * the first 4 bytes of {@code bytes}; equivalent to {@code + * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array + * {@code {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value + * {@code + * 0x12131415}. + * + *

              + * Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library + * exposes much more flexibility at little cost in readability. + * + * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements + */ + @GwtIncompatible("doesn't work") + public static int fromByteArray(byte[] bytes) { + checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); + return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); + } + + /** + * Returns the {@code int} value whose byte representation is the given 4 bytes, + * in big-endian order; equivalent to {@code Ints.fromByteArray(new byte[] {b1, + * b2, b3, b4})}. + * + * @since 7.0 + */ + @GwtIncompatible("doesn't work") + public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { + return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Integer) value).hashCode()}. + * + * @param value a primitive {@code int} value + * @return a hash code for the value + */ + public static int hashCode(int value) { + return value; + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. @@ -202,204 +477,6 @@ public final class Ints { return -1; } - /** - * Returns the index of the last appearance of the value {@code target} in - * {@code array}. - * - * @param array an array of {@code int} values, possibly empty - * @param target a primitive {@code int} value - * @return the greatest index {@code i} for which {@code array[i] == target}, or - * {@code -1} if no such index exists. - */ - public static int lastIndexOf(int[] array, int target) { - return lastIndexOf(array, target, 0, array.length); - } - - // TODO(kevinb): consider making this public - private static int lastIndexOf(int[] array, int target, int start, int end) { - for (int i = end - 1; i >= start; i--) { - if (array[i] == target) { - return i; - } - } - return -1; - } - - /** - * Returns the least value present in {@code array}. - * - * @param array a nonempty array of {@code int} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static int min(int... array) { - checkArgument(array.length > 0); - int min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - return min; - } - - /** - * Returns the greatest value present in {@code array}. - * - * @param array a nonempty array of {@code int} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static int max(int... array) { - checkArgument(array.length > 0); - int max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - return max; - } - - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns - * the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code int} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static int[] concat(int[]... arrays) { - int length = 0; - for (int[] array : arrays) { - length += array.length; - } - int[] result = new int[length]; - int pos = 0; - for (int[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - /** - * Returns a big-endian representation of {@code value} in a 4-element byte - * array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}. - * For example, the input value {@code 0x12131415} would yield the byte array - * {@code {0x12, 0x13, 0x14, 0x15}}. - * - *

              - * If you need to convert and concatenate several values (possibly even of - * different types), use a shared {@link java.nio.ByteBuffer} instance, or use - * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable - * buffer. - */ - @GwtIncompatible("doesn't work") - public static byte[] toByteArray(int value) { - return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; - } - - /** - * Returns the {@code int} value whose big-endian representation is stored in - * the first 4 bytes of {@code bytes}; equivalent to {@code - * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array - * {@code {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value - * {@code - * 0x12131415}. - * - *

              - * Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library - * exposes much more flexibility at little cost in readability. - * - * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements - */ - @GwtIncompatible("doesn't work") - public static int fromByteArray(byte[] bytes) { - checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); - return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); - } - - /** - * Returns the {@code int} value whose byte representation is the given 4 bytes, - * in big-endian order; equivalent to {@code Ints.fromByteArray(new byte[] {b1, - * b2, b3, b4})}. - * - * @since 7.0 - */ - @GwtIncompatible("doesn't work") - public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { - return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); - } - - private static final class IntConverter extends Converter implements Serializable { - static final IntConverter INSTANCE = new IntConverter(); - - @Override - protected Integer doForward(String value) { - return Integer.decode(value); - } - - @Override - protected String doBackward(Integer value) { - return value.toString(); - } - - @Override - public String toString() { - return "Ints.stringConverter()"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; - } - - /** - * Returns a serializable converter object that converts between strings and - * integers using {@link Integer#decode} and {@link Integer#toString()}. - * - * @since 16.0 - */ - @Beta - public static Converter stringConverter() { - return IntConverter.INSTANCE; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static int[] ensureCapacity(int[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static int[] copyOf(int[] original, int length) { - int[] copy = new int[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; - } - /** * Returns a string containing the supplied {@code int} values separated by * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string @@ -424,6 +501,29 @@ public final class Ints { return builder.toString(); } + /** + * Returns the index of the last appearance of the value {@code target} in + * {@code array}. + * + * @param array an array of {@code int} values, possibly empty + * @param target a primitive {@code int} value + * @return the greatest index {@code i} for which {@code array[i] == target}, or + * {@code -1} if no such index exists. + */ + public static int lastIndexOf(int[] array, int target) { + return lastIndexOf(array, target, 0, array.length); + } + + // TODO(kevinb): consider making this public + private static int lastIndexOf(int[] array, int target, int start, int end) { + for (int i = end - 1; i >= start; i--) { + if (array[i] == target) { + return i; + } + } + return -1; + } + /** * Returns a comparator that compares two {@code int} arrays lexicographically. * That is, it compares, using {@link #compare(int, int)}), the first pair of @@ -444,20 +544,71 @@ public final class Ints { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(int[] left, int[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Ints.compare(left[i], right[i]); - if (result != 0) { - return result; - } + /** + * Returns the greatest value present in {@code array}. + * + * @param array a nonempty array of {@code int} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static int max(int... array) { + checkArgument(array.length > 0); + int max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; } - return left.length - right.length; } + return max; + } + + /** + * Returns the least value present in {@code array}. + * + * @param array a nonempty array of {@code int} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static int min(int... array) { + checkArgument(array.length > 0); + int min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + return min; + } + + /** + * Returns the {@code int} nearest in value to {@code value}. + * + * @param value any {@code long} value + * @return the same value cast to {@code int} if it is in the range of the + * {@code int} type, {@link Integer#MAX_VALUE} if it is too large, or + * {@link Integer#MIN_VALUE} if it is too small + */ + public static int saturatedCast(long value) { + if (value > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } + if (value < Integer.MIN_VALUE) { + return Integer.MIN_VALUE; + } + return (int) value; + } + + /** + * Returns a serializable converter object that converts between strings and + * integers using {@link Integer#decode} and {@link Integer#toString()}. + * + * @since 16.0 + */ + @Beta + public static Converter stringConverter() { + return IntConverter.INSTANCE; } /** @@ -492,174 +643,20 @@ public final class Ints { } /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. + * Returns a big-endian representation of {@code value} in a 4-element byte + * array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}. + * For example, the input value {@code 0x12131415} would yield the byte array + * {@code {0x12, 0x13, 0x14, 0x15}}. * *

              - * The returned list maintains the values, but not the identities, of - * {@code Integer} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - * @param backingArray the array to back the list - * @return a list view of the array + * If you need to convert and concatenate several values (possibly even of + * different types), use a shared {@link java.nio.ByteBuffer} instance, or use + * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable + * buffer. */ - public static List asList(int... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new IntArrayAsList(backingArray); - } - - @GwtCompatible - private static class IntArrayAsList extends AbstractList implements RandomAccess, Serializable { - final int[] array; - final int start; - final int end; - - IntArrayAsList(int[] array) { - this(array, 0, array.length); - } - - IntArrayAsList(int[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Integer get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Integer) { - int i = Ints.indexOf(array, (Integer) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Integer) { - int i = Ints.lastIndexOf(array, (Integer) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Integer set(int index, Integer element) { - checkElementIndex(index, size()); - int oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new IntArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof IntArrayAsList) { - IntArrayAsList that = (IntArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Ints.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 5); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - int[] toIntArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - int[] result = new int[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; - } - - private static final byte[] asciiDigits = new byte[128]; - - static { - Arrays.fill(asciiDigits, (byte) -1); - for (int i = 0; i <= 9; i++) { - asciiDigits['0' + i] = (byte) i; - } - for (int i = 0; i <= 26; i++) { - asciiDigits['A' + i] = (byte) (10 + i); - asciiDigits['a' + i] = (byte) (10 + i); - } - } - - private static int digit(char c) { - return (c < 128) ? asciiDigits[c] : -1; + @GwtIncompatible("doesn't work") + public static byte[] toByteArray(int value) { + return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; } /** @@ -757,4 +754,7 @@ public final class Ints { return -accum; } } + + private Ints() { + } } diff --git a/src/main/java/com/google/common/primitives/Longs.java b/src/main/java/com/google/common/primitives/Longs.java index d56b6b2c..b23b23c7 100644 --- a/src/main/java/com/google/common/primitives/Longs.java +++ b/src/main/java/com/google/common/primitives/Longs.java @@ -48,7 +48,177 @@ import com.google.common.base.Converter; */ @GwtCompatible public final class Longs { - private Longs() { + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(long[] left, long[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Longs.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } + } + + @GwtCompatible + private static class LongArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final long[] array; + final int start; + + final int end; + + LongArrayAsList(long[] array) { + this(array, 0, array.length); + } + + LongArrayAsList(long[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof LongArrayAsList) { + LongArrayAsList that = (LongArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Long get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Longs.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Long) { + int i = Longs.indexOf(array, (Long) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Long) { + int i = Longs.lastIndexOf(array, (Long) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Long set(int index, Long element) { + checkElementIndex(index, size()); + long oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new LongArrayAsList(array, start + fromIndex, start + toIndex); + } + + long[] toLongArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + long[] result = new long[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 10); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } + } + + private static final class LongConverter extends Converter implements Serializable { + static final LongConverter INSTANCE = new LongConverter(); + + private static final long serialVersionUID = 1; + + @Override + protected String doBackward(Long value) { + return value.toString(); + } + + @Override + protected Long doForward(String value) { + return Long.decode(value); + } + + private Object readResolve() { + return INSTANCE; + } + + @Override + public String toString() { + return "Longs.stringConverter()"; + } } /** @@ -64,19 +234,25 @@ public final class Longs { public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Long) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * *

              - * This method always return the value specified by {@link Long#hashCode()} in - * java, which might be different from {@code ((Long) value).hashCode()} in GWT - * because {@link Long#hashCode()} in GWT does not obey the JRE contract. + * The returned list maintains the values, but not the identities, of + * {@code Long} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. * - * @param value a primitive {@code long} value - * @return a hash code for the value + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(long value) { - return (int) (value ^ (value >>> 32)); + public static List asList(long... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new LongArrayAsList(backingArray); } /** @@ -97,6 +273,29 @@ public final class Longs { return (a < b) ? -1 : ((a > b) ? 1 : 0); } + /** + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new long[] {a, b}, new long[] {}, new long[] {c}} + * returns the array {@code {a, b, c}}. + * + * @param arrays zero or more {@code long} arrays + * @return a single array containing all the values from the source arrays, in + * order + */ + public static long[] concat(long[]... arrays) { + int length = 0; + for (long[] array : arrays) { + length += array.length; + } + long[] result = new long[length]; + int pos = 0; + for (long[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; + } + /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. @@ -115,6 +314,81 @@ public final class Longs { return false; } + // Arrays.copyOf() requires Java 6 + private static long[] copyOf(long[] original, int length) { + long[] copy = new long[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static long[] ensureCapacity(long[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns the {@code long} value whose big-endian representation is stored in + * the first 8 bytes of {@code bytes}; equivalent to {@code + * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array + * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the + * {@code long} value {@code 0x1213141516171819L}. + * + *

              + * Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library + * exposes much more flexibility at little cost in readability. + * + * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements + */ + public static long fromByteArray(byte[] bytes) { + checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); + return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]); + } + + /** + * Returns the {@code long} value whose byte representation is the given 8 + * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new + * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. + * + * @since 7.0 + */ + public static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { + return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 + | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Long) value).hashCode()}. + * + *

              + * This method always return the value specified by {@link Long#hashCode()} in + * java, which might be different from {@code ((Long) value).hashCode()} in GWT + * because {@link Long#hashCode()} in GWT does not obey the JRE contract. + * + * @param value a primitive {@code long} value + * @return a hash code for the value + */ + public static int hashCode(long value) { + return (int) (value ^ (value >>> 32)); + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. @@ -168,6 +442,30 @@ public final class Longs { return -1; } + /** + * Returns a string containing the supplied {@code long} values separated by + * {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns the + * string {@code "1-2-3"}. + * + * @param separator the text that should appear between consecutive values in + * the resulting string (but not at the start or end) + * @param array an array of {@code long} values, possibly empty + */ + public static String join(String separator, long... array) { + checkNotNull(separator); + if (array.length == 0) { + return ""; + } + + // For pre-sizing a builder, just get the right order of magnitude + StringBuilder builder = new StringBuilder(array.length * 10); + builder.append(array[0]); + for (int i = 1; i < array.length; i++) { + builder.append(separator).append(array[i]); + } + return builder.toString(); + } + /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. @@ -192,22 +490,23 @@ public final class Longs { } /** - * Returns the least value present in {@code array}. + * Returns a comparator that compares two {@code long} arrays lexicographically. + * That is, it compares, using {@link #compare(long, long)}), the first pair of + * values that follow any common prefix, or when one array is a prefix of the + * other, treats the shorter array as the lesser. For example, + * {@code [] < [1L] < [1L, 2L] < [2L]}. * - * @param array a nonempty array of {@code long} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty + *

              + * The returned comparator is inconsistent with {@link Object#equals(Object)} + * (since arrays support only identity equality), but it is consistent with + * {@link Arrays#equals(long[], long[])}. + * + * @see + * Lexicographical order article at Wikipedia + * @since 2.0 */ - public static long min(long... array) { - checkArgument(array.length > 0); - long min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - return min; + public static Comparator lexicographicalComparator() { + return LexicographicalComparator.INSTANCE; } /** @@ -230,26 +529,64 @@ public final class Longs { } /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new long[] {a, b}, new long[] {}, new long[] {c}} - * returns the array {@code {a, b, c}}. + * Returns the least value present in {@code array}. * - * @param arrays zero or more {@code long} arrays - * @return a single array containing all the values from the source arrays, in - * order + * @param array a nonempty array of {@code long} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty */ - public static long[] concat(long[]... arrays) { - int length = 0; - for (long[] array : arrays) { - length += array.length; + public static long min(long... array) { + checkArgument(array.length > 0); + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } } - long[] result = new long[length]; - int pos = 0; - for (long[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; + return min; + } + + /** + * Returns a serializable converter object that converts between strings and + * longs using {@link Long#decode} and {@link Long#toString()}. + * + * @since 16.0 + */ + @Beta + public static Converter stringConverter() { + return LongConverter.INSTANCE; + } + + /** + * Returns an array containing each value of {@code collection}, converted to a + * {@code long} value in the manner of {@link Number#longValue}. + * + *

              + * Elements are copied from the argument collection as if by {@code + * collection.toArray()}. Calling this method is as thread-safe as calling that + * method. + * + * @param collection a collection of {@code Number} instances + * @return an array containing the same values as {@code collection}, in the + * same order, converted to primitives + * @throws NullPointerException if {@code collection} or any of its elements is + * null + * @since 1.0 (parameter was {@code Collection} before 12.0) + */ + public static long[] toArray(Collection collection) { + if (collection instanceof LongArrayAsList) { + return ((LongArrayAsList) collection).toLongArray(); } - return result; + + Object[] boxedArray = collection.toArray(); + int len = boxedArray.length; + long[] array = new long[len]; + for (int i = 0; i < len; i++) { + // checkNotNull for GWT (do not optimize) + array[i] = ((Number) checkNotNull(boxedArray[i])).longValue(); + } + return array; } /** @@ -275,36 +612,6 @@ public final class Longs { return result; } - /** - * Returns the {@code long} value whose big-endian representation is stored in - * the first 8 bytes of {@code bytes}; equivalent to {@code - * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array - * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the - * {@code long} value {@code 0x1213141516171819L}. - * - *

              - * Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library - * exposes much more flexibility at little cost in readability. - * - * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements - */ - public static long fromByteArray(byte[] bytes) { - checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); - return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]); - } - - /** - * Returns the {@code long} value whose byte representation is the given 8 - * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new - * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. - * - * @since 7.0 - */ - public static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { - return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 - | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); - } - /** * Parses the specified string as a signed decimal long value. The ASCII * character {@code '-'} ('\u002D') is recognized as the minus @@ -362,313 +669,6 @@ public final class Longs { } } - private static final class LongConverter extends Converter implements Serializable { - static final LongConverter INSTANCE = new LongConverter(); - - @Override - protected Long doForward(String value) { - return Long.decode(value); - } - - @Override - protected String doBackward(Long value) { - return value.toString(); - } - - @Override - public String toString() { - return "Longs.stringConverter()"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; - } - - /** - * Returns a serializable converter object that converts between strings and - * longs using {@link Long#decode} and {@link Long#toString()}. - * - * @since 16.0 - */ - @Beta - public static Converter stringConverter() { - return LongConverter.INSTANCE; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static long[] ensureCapacity(long[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static long[] copyOf(long[] original, int length) { - long[] copy = new long[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; - } - - /** - * Returns a string containing the supplied {@code long} values separated by - * {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns the - * string {@code "1-2-3"}. - * - * @param separator the text that should appear between consecutive values in - * the resulting string (but not at the start or end) - * @param array an array of {@code long} values, possibly empty - */ - public static String join(String separator, long... array) { - checkNotNull(separator); - if (array.length == 0) { - return ""; - } - - // For pre-sizing a builder, just get the right order of magnitude - StringBuilder builder = new StringBuilder(array.length * 10); - builder.append(array[0]); - for (int i = 1; i < array.length; i++) { - builder.append(separator).append(array[i]); - } - return builder.toString(); - } - - /** - * Returns a comparator that compares two {@code long} arrays lexicographically. - * That is, it compares, using {@link #compare(long, long)}), the first pair of - * values that follow any common prefix, or when one array is a prefix of the - * other, treats the shorter array as the lesser. For example, - * {@code [] < [1L] < [1L, 2L] < [2L]}. - * - *

              - * The returned comparator is inconsistent with {@link Object#equals(Object)} - * (since arrays support only identity equality), but it is consistent with - * {@link Arrays#equals(long[], long[])}. - * - * @see - * Lexicographical order article at Wikipedia - * @since 2.0 - */ - public static Comparator lexicographicalComparator() { - return LexicographicalComparator.INSTANCE; - } - - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(long[] left, long[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Longs.compare(left[i], right[i]); - if (result != 0) { - return result; - } - } - return left.length - right.length; - } - } - - /** - * Returns an array containing each value of {@code collection}, converted to a - * {@code long} value in the manner of {@link Number#longValue}. - * - *

              - * Elements are copied from the argument collection as if by {@code - * collection.toArray()}. Calling this method is as thread-safe as calling that - * method. - * - * @param collection a collection of {@code Number} instances - * @return an array containing the same values as {@code collection}, in the - * same order, converted to primitives - * @throws NullPointerException if {@code collection} or any of its elements is - * null - * @since 1.0 (parameter was {@code Collection} before 12.0) - */ - public static long[] toArray(Collection collection) { - if (collection instanceof LongArrayAsList) { - return ((LongArrayAsList) collection).toLongArray(); - } - - Object[] boxedArray = collection.toArray(); - int len = boxedArray.length; - long[] array = new long[len]; - for (int i = 0; i < len; i++) { - // checkNotNull for GWT (do not optimize) - array[i] = ((Number) checkNotNull(boxedArray[i])).longValue(); - } - return array; - } - - /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. - * - *

              - * The returned list maintains the values, but not the identities, of - * {@code Long} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - * @param backingArray the array to back the list - * @return a list view of the array - */ - public static List asList(long... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new LongArrayAsList(backingArray); - } - - @GwtCompatible - private static class LongArrayAsList extends AbstractList implements RandomAccess, Serializable { - final long[] array; - final int start; - final int end; - - LongArrayAsList(long[] array) { - this(array, 0, array.length); - } - - LongArrayAsList(long[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Long get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Long) { - int i = Longs.indexOf(array, (Long) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Long) { - int i = Longs.lastIndexOf(array, (Long) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Long set(int index, Long element) { - checkElementIndex(index, size()); - long oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new LongArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof LongArrayAsList) { - LongArrayAsList that = (LongArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Longs.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 10); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - long[] toLongArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - long[] result = new long[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; + private Longs() { } } diff --git a/src/main/java/com/google/common/primitives/ParseRequest.java b/src/main/java/com/google/common/primitives/ParseRequest.java index a3ff3379..77b88e17 100644 --- a/src/main/java/com/google/common/primitives/ParseRequest.java +++ b/src/main/java/com/google/common/primitives/ParseRequest.java @@ -21,14 +21,6 @@ import com.google.common.annotations.GwtCompatible; */ @GwtCompatible final class ParseRequest { - final String rawValue; - final int radix; - - private ParseRequest(String rawValue, int radix) { - this.rawValue = rawValue; - this.radix = radix; - } - static ParseRequest fromString(String stringValue) { if (stringValue.length() == 0) { throw new NumberFormatException("empty string"); @@ -54,4 +46,13 @@ final class ParseRequest { return new ParseRequest(rawValue, radix); } + + final String rawValue; + + final int radix; + + private ParseRequest(String rawValue, int radix) { + this.rawValue = rawValue; + this.radix = radix; + } } diff --git a/src/main/java/com/google/common/primitives/Primitives.java b/src/main/java/com/google/common/primitives/Primitives.java index 69484e16..8c2d2f77 100644 --- a/src/main/java/com/google/common/primitives/Primitives.java +++ b/src/main/java/com/google/common/primitives/Primitives.java @@ -31,17 +31,12 @@ import java.util.Set; * @since 1.0 */ public final class Primitives { - private Primitives() { - } - /** A map from primitive types to their corresponding wrapper types. */ private static final Map, Class> PRIMITIVE_TO_WRAPPER_TYPE; /** A map from wrapper types to their corresponding primitive types. */ private static final Map, Class> WRAPPER_TO_PRIMITIVE_TYPE; - // Sad that we can't use a BiMap. :( - static { Map, Class> primToWrap = new HashMap, Class>(16); Map, Class> wrapToPrim = new HashMap, Class>(16); @@ -60,6 +55,8 @@ public final class Primitives { WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim); } + // Sad that we can't use a BiMap. :( + private static void add(Map, Class> forward, Map, Class> backward, Class key, Class value) { forward.put(key, value); @@ -97,6 +94,25 @@ public final class Primitives { return WRAPPER_TO_PRIMITIVE_TYPE.containsKey(checkNotNull(type)); } + /** + * Returns the corresponding primitive type of {@code type} if it is a wrapper + * type; otherwise returns {@code type} itself. Idempotent. + * + *

              +	 *     unwrap(Integer.class) == int.class
              +	 *     unwrap(int.class) == int.class
              +	 *     unwrap(String.class) == String.class
              +	 * 
              + */ + public static Class unwrap(Class type) { + checkNotNull(type); + + // cast is safe: long.class and Long.class are both of type Class + @SuppressWarnings("unchecked") + Class unwrapped = (Class) WRAPPER_TO_PRIMITIVE_TYPE.get(type); + return (unwrapped == null) ? type : unwrapped; + } + /** * Returns the corresponding wrapper type of {@code type} if it is a primitive * type; otherwise returns {@code type} itself. Idempotent. @@ -116,22 +132,6 @@ public final class Primitives { return (wrapped == null) ? type : wrapped; } - /** - * Returns the corresponding primitive type of {@code type} if it is a wrapper - * type; otherwise returns {@code type} itself. Idempotent. - * - *
              -	 *     unwrap(Integer.class) == int.class
              -	 *     unwrap(int.class) == int.class
              -	 *     unwrap(String.class) == String.class
              -	 * 
              - */ - public static Class unwrap(Class type) { - checkNotNull(type); - - // cast is safe: long.class and Long.class are both of type Class - @SuppressWarnings("unchecked") - Class unwrapped = (Class) WRAPPER_TO_PRIMITIVE_TYPE.get(type); - return (unwrapped == null) ? type : unwrapped; + private Primitives() { } } diff --git a/src/main/java/com/google/common/primitives/Shorts.java b/src/main/java/com/google/common/primitives/Shorts.java index 5f149166..c74c008b 100644 --- a/src/main/java/com/google/common/primitives/Shorts.java +++ b/src/main/java/com/google/common/primitives/Shorts.java @@ -49,7 +49,177 @@ import com.google.common.base.Converter; */ @GwtCompatible(emulated = true) public final class Shorts { - private Shorts() { + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(short[] left, short[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = Shorts.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } + } + + @GwtCompatible + private static class ShortArrayAsList extends AbstractList implements RandomAccess, Serializable { + private static final long serialVersionUID = 0; + final short[] array; + final int start; + + final int end; + + ShortArrayAsList(short[] array) { + this(array, 0, array.length); + } + + ShortArrayAsList(short[] array, int start, int end) { + this.array = array; + this.start = start; + this.end = end; + } + + @Override + public boolean contains(Object target) { + // Overridden to prevent a ton of boxing + return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; + } + + @Override + public boolean equals(Object object) { + if (object == this) { + return true; + } + if (object instanceof ShortArrayAsList) { + ShortArrayAsList that = (ShortArrayAsList) object; + int size = size(); + if (that.size() != size) { + return false; + } + for (int i = 0; i < size; i++) { + if (array[start + i] != that.array[that.start + i]) { + return false; + } + } + return true; + } + return super.equals(object); + } + + @Override + public Short get(int index) { + checkElementIndex(index, size()); + return array[start + index]; + } + + @Override + public int hashCode() { + int result = 1; + for (int i = start; i < end; i++) { + result = 31 * result + Shorts.hashCode(array[i]); + } + return result; + } + + @Override + public int indexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Short) { + int i = Shorts.indexOf(array, (Short) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public boolean isEmpty() { + return false; + } + + @Override + public int lastIndexOf(Object target) { + // Overridden to prevent a ton of boxing + if (target instanceof Short) { + int i = Shorts.lastIndexOf(array, (Short) target, start, end); + if (i >= 0) { + return i - start; + } + } + return -1; + } + + @Override + public Short set(int index, Short element) { + checkElementIndex(index, size()); + short oldValue = array[start + index]; + // checkNotNull for GWT (do not optimize) + array[start + index] = checkNotNull(element); + return oldValue; + } + + @Override + public int size() { + return end - start; + } + + @Override + public List subList(int fromIndex, int toIndex) { + int size = size(); + checkPositionIndexes(fromIndex, toIndex, size); + if (fromIndex == toIndex) { + return Collections.emptyList(); + } + return new ShortArrayAsList(array, start + fromIndex, start + toIndex); + } + + short[] toShortArray() { + // Arrays.copyOfRange() is not available under GWT + int size = size(); + short[] result = new short[size]; + System.arraycopy(array, start, result, 0, size); + return result; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(size() * 6); + builder.append('[').append(array[start]); + for (int i = start + 1; i < end; i++) { + builder.append(", ").append(array[i]); + } + return builder.append(']').toString(); + } + } + + private static final class ShortConverter extends Converter implements Serializable { + static final ShortConverter INSTANCE = new ShortConverter(); + + private static final long serialVersionUID = 1; + + @Override + protected String doBackward(Short value) { + return value.toString(); + } + + @Override + protected Short doForward(String value) { + return Short.decode(value); + } + + private Object readResolve() { + return INSTANCE; + } + + @Override + public String toString() { + return "Shorts.stringConverter()"; + } } /** @@ -65,14 +235,25 @@ public final class Shorts { public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); /** - * Returns a hash code for {@code value}; equal to the result of invoking - * {@code ((Short) value).hashCode()}. + * Returns a fixed-size list backed by the specified array, similar to + * {@link Arrays#asList(Object[])}. The list supports + * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} + * will result in a {@link NullPointerException}. * - * @param value a primitive {@code short} value - * @return a hash code for the value + *

              + * The returned list maintains the values, but not the identities, of + * {@code Short} objects written to or read from it. For example, whether + * {@code list.get(0) == list.get(0)} is true for the returned list is + * unspecified. + * + * @param backingArray the array to back the list + * @return a list view of the array */ - public static int hashCode(short value) { - return value; + public static List asList(short... backingArray) { + if (backingArray.length == 0) { + return Collections.emptyList(); + } + return new ShortArrayAsList(backingArray); } /** @@ -93,24 +274,6 @@ public final class Shorts { return result; } - /** - * Returns the {@code short} nearest in value to {@code value}. - * - * @param value any {@code long} value - * @return the same value cast to {@code short} if it is in the range of the - * {@code short} type, {@link Short#MAX_VALUE} if it is too large, or - * {@link Short#MIN_VALUE} if it is too small - */ - public static short saturatedCast(long value) { - if (value > Short.MAX_VALUE) { - return Short.MAX_VALUE; - } - if (value < Short.MIN_VALUE) { - return Short.MIN_VALUE; - } - return (short) value; - } - /** * Compares the two specified {@code short} values. The sign of the value * returned is the same as that of {@code ((Short) a).compareTo(b)}. @@ -129,6 +292,29 @@ public final class Shorts { return a - b; // safe due to restricted range } + /** + * Returns the values from each provided array combined into a single array. For + * example, {@code concat(new short[] {a, b}, new short[] {}, new short[] {c}} + * returns the array {@code {a, b, c}}. + * + * @param arrays zero or more {@code short} arrays + * @return a single array containing all the values from the source arrays, in + * order + */ + public static short[] concat(short[]... arrays) { + int length = 0; + for (short[] array : arrays) { + length += array.length; + } + short[] result = new short[length]; + int pos = 0; + for (short[] array : arrays) { + System.arraycopy(array, 0, result, pos, array.length); + pos += array.length; + } + return result; + } + /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. @@ -147,6 +333,76 @@ public final class Shorts { return false; } + // Arrays.copyOf() requires Java 6 + private static short[] copyOf(short[] original, int length) { + short[] copy = new short[length]; + System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); + return copy; + } + + /** + * Returns an array containing the same values as {@code array}, but guaranteed + * to be of a specified minimum length. If {@code array} already has a length of + * at least {@code minLength}, it is returned directly. Otherwise, a new array + * of size {@code minLength + padding} is returned, containing the values of + * {@code array}, and zeroes in the remaining places. + * + * @param array the source array + * @param minLength the minimum length the returned array must guarantee + * @param padding an extra amount to "grow" the array by if growth is + * necessary + * @throws IllegalArgumentException if {@code minLength} or {@code padding} is + * negative + * @return an array containing the values of {@code array}, with guaranteed + * minimum length {@code minLength} + */ + public static short[] ensureCapacity(short[] array, int minLength, int padding) { + checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); + checkArgument(padding >= 0, "Invalid padding: %s", padding); + return (array.length < minLength) ? copyOf(array, minLength + padding) : array; + } + + /** + * Returns the {@code short} value whose big-endian representation is stored in + * the first 2 bytes of {@code bytes}; equivalent to {@code + * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array + * {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. + * + *

              + * Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library + * exposes much more flexibility at little cost in readability. + * + * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements + */ + @GwtIncompatible("doesn't work") + public static short fromByteArray(byte[] bytes) { + checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); + return fromBytes(bytes[0], bytes[1]); + } + + /** + * Returns the {@code short} value whose byte representation is the given 2 + * bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new + * byte[] {b1, b2})}. + * + * @since 7.0 + */ + @GwtIncompatible("doesn't work") + public static short fromBytes(byte b1, byte b2) { + return (short) ((b1 << 8) | (b2 & 0xFF)); + } + + /** + * Returns a hash code for {@code value}; equal to the result of invoking + * {@code ((Short) value).hashCode()}. + * + * @param value a primitive {@code short} value + * @return a hash code for the value + */ + public static int hashCode(short value) { + return value; + } + /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. @@ -200,202 +456,6 @@ public final class Shorts { return -1; } - /** - * Returns the index of the last appearance of the value {@code target} in - * {@code array}. - * - * @param array an array of {@code short} values, possibly empty - * @param target a primitive {@code short} value - * @return the greatest index {@code i} for which {@code array[i] == target}, or - * {@code -1} if no such index exists. - */ - public static int lastIndexOf(short[] array, short target) { - return lastIndexOf(array, target, 0, array.length); - } - - // TODO(kevinb): consider making this public - private static int lastIndexOf(short[] array, short target, int start, int end) { - for (int i = end - 1; i >= start; i--) { - if (array[i] == target) { - return i; - } - } - return -1; - } - - /** - * Returns the least value present in {@code array}. - * - * @param array a nonempty array of {@code short} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static short min(short... array) { - checkArgument(array.length > 0); - short min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - return min; - } - - /** - * Returns the greatest value present in {@code array}. - * - * @param array a nonempty array of {@code short} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static short max(short... array) { - checkArgument(array.length > 0); - short max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - return max; - } - - /** - * Returns the values from each provided array combined into a single array. For - * example, {@code concat(new short[] {a, b}, new short[] {}, new short[] {c}} - * returns the array {@code {a, b, c}}. - * - * @param arrays zero or more {@code short} arrays - * @return a single array containing all the values from the source arrays, in - * order - */ - public static short[] concat(short[]... arrays) { - int length = 0; - for (short[] array : arrays) { - length += array.length; - } - short[] result = new short[length]; - int pos = 0; - for (short[] array : arrays) { - System.arraycopy(array, 0, result, pos, array.length); - pos += array.length; - } - return result; - } - - /** - * Returns a big-endian representation of {@code value} in a 2-element byte - * array; equivalent to {@code - * ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value - * {@code (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}. - * - *

              - * If you need to convert and concatenate several values (possibly even of - * different types), use a shared {@link java.nio.ByteBuffer} instance, or use - * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable - * buffer. - */ - @GwtIncompatible("doesn't work") - public static byte[] toByteArray(short value) { - return new byte[] { (byte) (value >> 8), (byte) value }; - } - - /** - * Returns the {@code short} value whose big-endian representation is stored in - * the first 2 bytes of {@code bytes}; equivalent to {@code - * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array - * {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. - * - *

              - * Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library - * exposes much more flexibility at little cost in readability. - * - * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements - */ - @GwtIncompatible("doesn't work") - public static short fromByteArray(byte[] bytes) { - checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); - return fromBytes(bytes[0], bytes[1]); - } - - /** - * Returns the {@code short} value whose byte representation is the given 2 - * bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new - * byte[] {b1, b2})}. - * - * @since 7.0 - */ - @GwtIncompatible("doesn't work") - public static short fromBytes(byte b1, byte b2) { - return (short) ((b1 << 8) | (b2 & 0xFF)); - } - - private static final class ShortConverter extends Converter implements Serializable { - static final ShortConverter INSTANCE = new ShortConverter(); - - @Override - protected Short doForward(String value) { - return Short.decode(value); - } - - @Override - protected String doBackward(Short value) { - return value.toString(); - } - - @Override - public String toString() { - return "Shorts.stringConverter()"; - } - - private Object readResolve() { - return INSTANCE; - } - - private static final long serialVersionUID = 1; - } - - /** - * Returns a serializable converter object that converts between strings and - * shorts using {@link Short#decode} and {@link Short#toString()}. - * - * @since 16.0 - */ - @Beta - public static Converter stringConverter() { - return ShortConverter.INSTANCE; - } - - /** - * Returns an array containing the same values as {@code array}, but guaranteed - * to be of a specified minimum length. If {@code array} already has a length of - * at least {@code minLength}, it is returned directly. Otherwise, a new array - * of size {@code minLength + padding} is returned, containing the values of - * {@code array}, and zeroes in the remaining places. - * - * @param array the source array - * @param minLength the minimum length the returned array must guarantee - * @param padding an extra amount to "grow" the array by if growth is - * necessary - * @throws IllegalArgumentException if {@code minLength} or {@code padding} is - * negative - * @return an array containing the values of {@code array}, with guaranteed - * minimum length {@code minLength} - */ - public static short[] ensureCapacity(short[] array, int minLength, int padding) { - checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); - checkArgument(padding >= 0, "Invalid padding: %s", padding); - return (array.length < minLength) ? copyOf(array, minLength + padding) : array; - } - - // Arrays.copyOf() requires Java 6 - private static short[] copyOf(short[] original, int length) { - short[] copy = new short[length]; - System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); - return copy; - } - /** * Returns a string containing the supplied {@code short} values separated by * {@code separator}. For example, {@code join("-", (short) 1, (short) 2, @@ -420,6 +480,29 @@ public final class Shorts { return builder.toString(); } + /** + * Returns the index of the last appearance of the value {@code target} in + * {@code array}. + * + * @param array an array of {@code short} values, possibly empty + * @param target a primitive {@code short} value + * @return the greatest index {@code i} for which {@code array[i] == target}, or + * {@code -1} if no such index exists. + */ + public static int lastIndexOf(short[] array, short target) { + return lastIndexOf(array, target, 0, array.length); + } + + // TODO(kevinb): consider making this public + private static int lastIndexOf(short[] array, short target, int start, int end) { + for (int i = end - 1; i >= start; i--) { + if (array[i] == target) { + return i; + } + } + return -1; + } + /** * Returns a comparator that compares two {@code short} arrays * lexicographically. That is, it compares, using @@ -441,20 +524,71 @@ public final class Shorts { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(short[] left, short[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = Shorts.compare(left[i], right[i]); - if (result != 0) { - return result; - } + /** + * Returns the greatest value present in {@code array}. + * + * @param array a nonempty array of {@code short} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static short max(short... array) { + checkArgument(array.length > 0); + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; } - return left.length - right.length; } + return max; + } + + /** + * Returns the least value present in {@code array}. + * + * @param array a nonempty array of {@code short} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static short min(short... array) { + checkArgument(array.length > 0); + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + return min; + } + + /** + * Returns the {@code short} nearest in value to {@code value}. + * + * @param value any {@code long} value + * @return the same value cast to {@code short} if it is in the range of the + * {@code short} type, {@link Short#MAX_VALUE} if it is too large, or + * {@link Short#MIN_VALUE} if it is too small + */ + public static short saturatedCast(long value) { + if (value > Short.MAX_VALUE) { + return Short.MAX_VALUE; + } + if (value < Short.MIN_VALUE) { + return Short.MIN_VALUE; + } + return (short) value; + } + + /** + * Returns a serializable converter object that converts between strings and + * shorts using {@link Short#decode} and {@link Short#toString()}. + * + * @since 16.0 + */ + @Beta + public static Converter stringConverter() { + return ShortConverter.INSTANCE; } /** @@ -489,156 +623,22 @@ public final class Shorts { } /** - * Returns a fixed-size list backed by the specified array, similar to - * {@link Arrays#asList(Object[])}. The list supports - * {@link List#set(int, Object)}, but any attempt to set a value to {@code null} - * will result in a {@link NullPointerException}. + * Returns a big-endian representation of {@code value} in a 2-element byte + * array; equivalent to {@code + * ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value + * {@code (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}. * *

              - * The returned list maintains the values, but not the identities, of - * {@code Short} objects written to or read from it. For example, whether - * {@code list.get(0) == list.get(0)} is true for the returned list is - * unspecified. - * - * @param backingArray the array to back the list - * @return a list view of the array + * If you need to convert and concatenate several values (possibly even of + * different types), use a shared {@link java.nio.ByteBuffer} instance, or use + * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable + * buffer. */ - public static List asList(short... backingArray) { - if (backingArray.length == 0) { - return Collections.emptyList(); - } - return new ShortArrayAsList(backingArray); + @GwtIncompatible("doesn't work") + public static byte[] toByteArray(short value) { + return new byte[] { (byte) (value >> 8), (byte) value }; } - @GwtCompatible - private static class ShortArrayAsList extends AbstractList implements RandomAccess, Serializable { - final short[] array; - final int start; - final int end; - - ShortArrayAsList(short[] array) { - this(array, 0, array.length); - } - - ShortArrayAsList(short[] array, int start, int end) { - this.array = array; - this.start = start; - this.end = end; - } - - @Override - public int size() { - return end - start; - } - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public Short get(int index) { - checkElementIndex(index, size()); - return array[start + index]; - } - - @Override - public boolean contains(Object target) { - // Overridden to prevent a ton of boxing - return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; - } - - @Override - public int indexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Short) { - int i = Shorts.indexOf(array, (Short) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object target) { - // Overridden to prevent a ton of boxing - if (target instanceof Short) { - int i = Shorts.lastIndexOf(array, (Short) target, start, end); - if (i >= 0) { - return i - start; - } - } - return -1; - } - - @Override - public Short set(int index, Short element) { - checkElementIndex(index, size()); - short oldValue = array[start + index]; - // checkNotNull for GWT (do not optimize) - array[start + index] = checkNotNull(element); - return oldValue; - } - - @Override - public List subList(int fromIndex, int toIndex) { - int size = size(); - checkPositionIndexes(fromIndex, toIndex, size); - if (fromIndex == toIndex) { - return Collections.emptyList(); - } - return new ShortArrayAsList(array, start + fromIndex, start + toIndex); - } - - @Override - public boolean equals(Object object) { - if (object == this) { - return true; - } - if (object instanceof ShortArrayAsList) { - ShortArrayAsList that = (ShortArrayAsList) object; - int size = size(); - if (that.size() != size) { - return false; - } - for (int i = 0; i < size; i++) { - if (array[start + i] != that.array[that.start + i]) { - return false; - } - } - return true; - } - return super.equals(object); - } - - @Override - public int hashCode() { - int result = 1; - for (int i = start; i < end; i++) { - result = 31 * result + Shorts.hashCode(array[i]); - } - return result; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(size() * 6); - builder.append('[').append(array[start]); - for (int i = start + 1; i < end; i++) { - builder.append(", ").append(array[i]); - } - return builder.append(']').toString(); - } - - short[] toShortArray() { - // Arrays.copyOfRange() is not available under GWT - int size = size(); - short[] result = new short[size]; - System.arraycopy(array, start, result, 0, size); - return result; - } - - private static final long serialVersionUID = 0; + private Shorts() { } } diff --git a/src/main/java/com/google/common/primitives/SignedBytes.java b/src/main/java/com/google/common/primitives/SignedBytes.java index 5acca63e..eb6490ea 100644 --- a/src/main/java/com/google/common/primitives/SignedBytes.java +++ b/src/main/java/com/google/common/primitives/SignedBytes.java @@ -41,7 +41,20 @@ import com.google.common.annotations.GwtCompatible; // javadoc? @GwtCompatible public final class SignedBytes { - private SignedBytes() { + private enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(byte[] left, byte[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + int result = SignedBytes.compare(left[i], right[i]); + if (result != 0) { + return result; + } + } + return left.length - right.length; + } } /** @@ -69,24 +82,6 @@ public final class SignedBytes { return result; } - /** - * Returns the {@code byte} nearest in value to {@code value}. - * - * @param value any {@code long} value - * @return the same value cast to {@code byte} if it is in the range of the - * {@code byte} type, {@link Byte#MAX_VALUE} if it is too large, or - * {@link Byte#MIN_VALUE} if it is too small - */ - public static byte saturatedCast(long value) { - if (value > Byte.MAX_VALUE) { - return Byte.MAX_VALUE; - } - if (value < Byte.MIN_VALUE) { - return Byte.MIN_VALUE; - } - return (byte) value; - } - /** * Compares the two specified {@code byte} values. The sign of the value * returned is the same as that of {@code ((Byte) a).compareTo(b)}. @@ -107,44 +102,6 @@ public final class SignedBytes { return a - b; // safe due to restricted range } - /** - * Returns the least value present in {@code array}. - * - * @param array a nonempty array of {@code byte} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static byte min(byte... array) { - checkArgument(array.length > 0); - byte min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - return min; - } - - /** - * Returns the greatest value present in {@code array}. - * - * @param array a nonempty array of {@code byte} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty - */ - public static byte max(byte... array) { - checkArgument(array.length > 0); - byte max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - return max; - } - /** * Returns a string containing the supplied {@code byte} values separated by * {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)} returns @@ -190,19 +147,62 @@ public final class SignedBytes { return LexicographicalComparator.INSTANCE; } - private enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(byte[] left, byte[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - int result = SignedBytes.compare(left[i], right[i]); - if (result != 0) { - return result; - } + /** + * Returns the greatest value present in {@code array}. + * + * @param array a nonempty array of {@code byte} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static byte max(byte... array) { + checkArgument(array.length > 0); + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; } - return left.length - right.length; } + return max; + } + + /** + * Returns the least value present in {@code array}. + * + * @param array a nonempty array of {@code byte} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty + */ + public static byte min(byte... array) { + checkArgument(array.length > 0); + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + return min; + } + + /** + * Returns the {@code byte} nearest in value to {@code value}. + * + * @param value any {@code long} value + * @return the same value cast to {@code byte} if it is in the range of the + * {@code byte} type, {@link Byte#MAX_VALUE} if it is too large, or + * {@link Byte#MIN_VALUE} if it is too small + */ + public static byte saturatedCast(long value) { + if (value > Byte.MAX_VALUE) { + return Byte.MAX_VALUE; + } + if (value < Byte.MIN_VALUE) { + return Byte.MIN_VALUE; + } + return (byte) value; + } + + private SignedBytes() { } } diff --git a/src/main/java/com/google/common/primitives/UnsignedBytes.java b/src/main/java/com/google/common/primitives/UnsignedBytes.java index cb0adb82..70fa9227 100644 --- a/src/main/java/com/google/common/primitives/UnsignedBytes.java +++ b/src/main/java/com/google/common/primitives/UnsignedBytes.java @@ -40,9 +40,6 @@ import com.google.common.annotations.Beta; * @since 1.0 */ public final class UnsignedBytes { - private UnsignedBytes() { - } - /** * The largest power of two that can be represented as an unsigned {@code * byte}. @@ -60,17 +57,6 @@ public final class UnsignedBytes { private static final int UNSIGNED_MASK = 0xFF; - /** - * Returns the value of the given byte as an integer, when treated as unsigned. - * That is, returns {@code value + 256} if {@code value} is negative; - * {@code value} itself otherwise. - * - * @since 6.0 - */ - public static int toInt(byte value) { - return value & UNSIGNED_MASK; - } - /** * Returns the {@code byte} value that, when treated as unsigned, is equal to * {@code value}, if possible. @@ -89,24 +75,6 @@ public final class UnsignedBytes { return (byte) value; } - /** - * Returns the {@code byte} value that, when treated as unsigned, is nearest in - * value to {@code value}. - * - * @param value any {@code long} value - * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if - * {@code value <= 0}, and {@code value} cast to {@code byte} otherwise - */ - public static byte saturatedCast(long value) { - if (value > toInt(MAX_VALUE)) { - return MAX_VALUE; // -1 - } - if (value < 0) { - return (byte) 0; - } - return (byte) value; - } - /** * Compares the two specified {@code byte} values, treating them as unsigned * values between 0 and 255 inclusive. For example, {@code (byte) -127} is @@ -124,23 +92,27 @@ public final class UnsignedBytes { } /** - * Returns the least value present in {@code array}. + * Returns a string containing the supplied {@code byte} values separated by + * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2, + * (byte) 255)} returns the string {@code "1:2:255"}. * - * @param array a nonempty array of {@code byte} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array - * @throws IllegalArgumentException if {@code array} is empty + * @param separator the text that should appear between consecutive values in + * the resulting string (but not at the start or end) + * @param array an array of {@code byte} values, possibly empty */ - public static byte min(byte... array) { - checkArgument(array.length > 0); - int min = toInt(array[0]); - for (int i = 1; i < array.length; i++) { - int next = toInt(array[i]); - if (next < min) { - min = next; - } + public static String join(String separator, byte... array) { + checkNotNull(separator); + if (array.length == 0) { + return ""; } - return (byte) min; + + // For pre-sizing a builder, just get the right order of magnitude + StringBuilder builder = new StringBuilder(array.length * (3 + separator.length())); + builder.append(toInt(array[0])); + for (int i = 1; i < array.length; i++) { + builder.append(separator).append(toString(array[i])); + } + return builder.toString(); } /** @@ -164,32 +136,23 @@ public final class UnsignedBytes { } /** - * Returns a string representation of x, where x is treated as unsigned. + * Returns the least value present in {@code array}. * - * @since 13.0 + * @param array a nonempty array of {@code byte} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array + * @throws IllegalArgumentException if {@code array} is empty */ - @Beta - public static String toString(byte x) { - return toString(x, 10); - } - - /** - * Returns a string representation of {@code x} for the given radix, where - * {@code x} is treated as unsigned. - * - * @param x the value to convert to a string. - * @param radix the radix to use while working with {@code x} - * @throws IllegalArgumentException if {@code radix} is not between - * {@link Character#MIN_RADIX} and - * {@link Character#MAX_RADIX}. - * @since 13.0 - */ - @Beta - public static String toString(byte x, int radix) { - checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, - "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); - // Benchmarks indicate this is probably not worth optimizing. - return Integer.toString(toInt(x), radix); + public static byte min(byte... array) { + checkArgument(array.length > 0); + int min = toInt(array[0]); + for (int i = 1; i < array.length; i++) { + int next = toInt(array[i]); + if (next < min) { + min = next; + } + } + return (byte) min; } /** @@ -236,27 +199,64 @@ public final class UnsignedBytes { } /** - * Returns a string containing the supplied {@code byte} values separated by - * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2, - * (byte) 255)} returns the string {@code "1:2:255"}. + * Returns the {@code byte} value that, when treated as unsigned, is nearest in + * value to {@code value}. * - * @param separator the text that should appear between consecutive values in - * the resulting string (but not at the start or end) - * @param array an array of {@code byte} values, possibly empty + * @param value any {@code long} value + * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if + * {@code value <= 0}, and {@code value} cast to {@code byte} otherwise */ - public static String join(String separator, byte... array) { - checkNotNull(separator); - if (array.length == 0) { - return ""; + public static byte saturatedCast(long value) { + if (value > toInt(MAX_VALUE)) { + return MAX_VALUE; // -1 } + if (value < 0) { + return (byte) 0; + } + return (byte) value; + } - // For pre-sizing a builder, just get the right order of magnitude - StringBuilder builder = new StringBuilder(array.length * (3 + separator.length())); - builder.append(toInt(array[0])); - for (int i = 1; i < array.length; i++) { - builder.append(separator).append(toString(array[i])); - } - return builder.toString(); + /** + * Returns the value of the given byte as an integer, when treated as unsigned. + * That is, returns {@code value + 256} if {@code value} is negative; + * {@code value} itself otherwise. + * + * @since 6.0 + */ + public static int toInt(byte value) { + return value & UNSIGNED_MASK; + } + + /** + * Returns a string representation of x, where x is treated as unsigned. + * + * @since 13.0 + */ + @Beta + public static String toString(byte x) { + return toString(x, 10); + } + + /** + * Returns a string representation of {@code x} for the given radix, where + * {@code x} is treated as unsigned. + * + * @param x the value to convert to a string. + * @param radix the radix to use while working with {@code x} + * @throws IllegalArgumentException if {@code radix} is not between + * {@link Character#MIN_RADIX} and + * {@link Character#MAX_RADIX}. + * @since 13.0 + */ + @Beta + public static String toString(byte x, int radix) { + checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, + "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); + // Benchmarks indicate this is probably not worth optimizing. + return Integer.toString(toInt(x), radix); + } + + private UnsignedBytes() { } } diff --git a/src/main/java/com/google/common/primitives/UnsignedInteger.java b/src/main/java/com/google/common/primitives/UnsignedInteger.java index 93992d34..26d7380d 100644 --- a/src/main/java/com/google/common/primitives/UnsignedInteger.java +++ b/src/main/java/com/google/common/primitives/UnsignedInteger.java @@ -51,14 +51,6 @@ public final class UnsignedInteger extends Number implements Comparable other}. */ - @CheckReturnValue - @GwtIncompatible("Does not truncate correctly") - public UnsignedInteger times(UnsignedInteger val) { - // TODO(user): make this GWT-compatible - return fromIntBits(value * checkNotNull(val).value); + @Override + public int compareTo(UnsignedInteger other) { + checkNotNull(other); + return compare(value, other.value); } /** @@ -174,14 +157,37 @@ public final class UnsignedInteger extends Number implements Comparable other}. + * Returns the result of multiplying this and {@code val}. If the result would + * have more than 32 bits, returns the low 32 bits of the result. + * + * @since 14.0 */ - @Override - public int compareTo(UnsignedInteger other) { - checkNotNull(other); - return compare(value, other.value); - } - - @Override - public int hashCode() { - return value; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof UnsignedInteger) { - UnsignedInteger other = (UnsignedInteger) obj; - return value == other.value; - } - return false; + @CheckReturnValue + @GwtIncompatible("Does not truncate correctly") + public UnsignedInteger times(UnsignedInteger val) { + // TODO(user): make this GWT-compatible + return fromIntBits(value * checkNotNull(val).value); } /** diff --git a/src/main/java/com/google/common/primitives/UnsignedInts.java b/src/main/java/com/google/common/primitives/UnsignedInts.java index 22f82484..f08ff43c 100644 --- a/src/main/java/com/google/common/primitives/UnsignedInts.java +++ b/src/main/java/com/google/common/primitives/UnsignedInts.java @@ -52,15 +52,23 @@ import com.google.common.annotations.GwtCompatible; @Beta @GwtCompatible public final class UnsignedInts { + enum LexicographicalComparator implements Comparator { + INSTANCE; + + @Override + public int compare(int[] left, int[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + if (left[i] != right[i]) { + return UnsignedInts.compare(left[i], right[i]); + } + } + return left.length - right.length; + } + } + static final long INT_MASK = 0xffffffffL; - private UnsignedInts() { - } - - static int flip(int value) { - return value ^ Integer.MIN_VALUE; - } - /** * Compares the two specified {@code int} values, treating them as unsigned * values between {@code 0} and {@code 2^32 - 1} inclusive. @@ -76,53 +84,48 @@ public final class UnsignedInts { } /** - * Returns the value of the given {@code int} as a {@code long}, when treated as - * unsigned. + * Returns the unsigned {@code int} value represented by the given string. + * + * Accepts a decimal, hexadecimal, or octal number given by specifying the + * following prefix: + * + *

                + *
              • {@code 0x}HexDigits + *
              • {@code 0X}HexDigits + *
              • {@code #}HexDigits + *
              • {@code 0}OctalDigits + *
              + * + * @throws NumberFormatException if the string does not contain a valid unsigned + * {@code int} value + * @since 13.0 */ - public static long toLong(int value) { - return value & INT_MASK; + public static int decode(String stringValue) { + ParseRequest request = ParseRequest.fromString(stringValue); + + try { + return parseUnsignedInt(request.rawValue, request.radix); + } catch (NumberFormatException e) { + NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); + decodeException.initCause(e); + throw decodeException; + } } /** - * Returns the least value present in {@code array}, treating values as - * unsigned. + * Returns dividend / divisor, where the dividend and divisor are treated as + * unsigned 32-bit quantities. * - * @param array a nonempty array of unsigned {@code int} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array according to {@link #compare} - * @throws IllegalArgumentException if {@code array} is empty + * @param dividend the dividend (numerator) + * @param divisor the divisor (denominator) + * @throws ArithmeticException if divisor is 0 */ - public static int min(int... array) { - checkArgument(array.length > 0); - int min = flip(array[0]); - for (int i = 1; i < array.length; i++) { - int next = flip(array[i]); - if (next < min) { - min = next; - } - } - return flip(min); + public static int divide(int dividend, int divisor) { + return (int) (toLong(dividend) / toLong(divisor)); } - /** - * Returns the greatest value present in {@code array}, treating values as - * unsigned. - * - * @param array a nonempty array of unsigned {@code int} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array according to {@link #compare} - * @throws IllegalArgumentException if {@code array} is empty - */ - public static int max(int... array) { - checkArgument(array.length > 0); - int max = flip(array[0]); - for (int i = 1; i < array.length; i++) { - int next = flip(array[i]); - if (next > max) { - max = next; - } - } - return flip(max); + static int flip(int value) { + return value ^ Integer.MIN_VALUE; } /** @@ -168,72 +171,46 @@ public final class UnsignedInts { return LexicographicalComparator.INSTANCE; } - enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(int[] left, int[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - if (left[i] != right[i]) { - return UnsignedInts.compare(left[i], right[i]); - } + /** + * Returns the greatest value present in {@code array}, treating values as + * unsigned. + * + * @param array a nonempty array of unsigned {@code int} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array according to {@link #compare} + * @throws IllegalArgumentException if {@code array} is empty + */ + public static int max(int... array) { + checkArgument(array.length > 0); + int max = flip(array[0]); + for (int i = 1; i < array.length; i++) { + int next = flip(array[i]); + if (next > max) { + max = next; } - return left.length - right.length; } + return flip(max); } /** - * Returns dividend / divisor, where the dividend and divisor are treated as - * unsigned 32-bit quantities. + * Returns the least value present in {@code array}, treating values as + * unsigned. * - * @param dividend the dividend (numerator) - * @param divisor the divisor (denominator) - * @throws ArithmeticException if divisor is 0 + * @param array a nonempty array of unsigned {@code int} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array according to {@link #compare} + * @throws IllegalArgumentException if {@code array} is empty */ - public static int divide(int dividend, int divisor) { - return (int) (toLong(dividend) / toLong(divisor)); - } - - /** - * Returns dividend % divisor, where the dividend and divisor are treated as - * unsigned 32-bit quantities. - * - * @param dividend the dividend (numerator) - * @param divisor the divisor (denominator) - * @throws ArithmeticException if divisor is 0 - */ - public static int remainder(int dividend, int divisor) { - return (int) (toLong(dividend) % toLong(divisor)); - } - - /** - * Returns the unsigned {@code int} value represented by the given string. - * - * Accepts a decimal, hexadecimal, or octal number given by specifying the - * following prefix: - * - *
                - *
              • {@code 0x}HexDigits - *
              • {@code 0X}HexDigits - *
              • {@code #}HexDigits - *
              • {@code 0}OctalDigits - *
              - * - * @throws NumberFormatException if the string does not contain a valid unsigned - * {@code int} value - * @since 13.0 - */ - public static int decode(String stringValue) { - ParseRequest request = ParseRequest.fromString(stringValue); - - try { - return parseUnsignedInt(request.rawValue, request.radix); - } catch (NumberFormatException e) { - NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); - decodeException.initCause(e); - throw decodeException; + public static int min(int... array) { + checkArgument(array.length > 0); + int min = flip(array[0]); + for (int i = 1; i < array.length; i++) { + int next = flip(array[i]); + if (next < min) { + min = next; + } } + return flip(min); } /** @@ -272,6 +249,26 @@ public final class UnsignedInts { return (int) result; } + /** + * Returns dividend % divisor, where the dividend and divisor are treated as + * unsigned 32-bit quantities. + * + * @param dividend the dividend (numerator) + * @param divisor the divisor (denominator) + * @throws ArithmeticException if divisor is 0 + */ + public static int remainder(int dividend, int divisor) { + return (int) (toLong(dividend) % toLong(divisor)); + } + + /** + * Returns the value of the given {@code int} as a {@code long}, when treated as + * unsigned. + */ + public static long toLong(int value) { + return value & INT_MASK; + } + /** * Returns a string representation of x, where x is treated as unsigned. */ @@ -293,4 +290,7 @@ public final class UnsignedInts { long asLong = x & INT_MASK; return Long.toString(asLong, radix); } + + private UnsignedInts() { + } } diff --git a/src/main/java/com/google/common/primitives/UnsignedLong.java b/src/main/java/com/google/common/primitives/UnsignedLong.java index d0fbd3a8..322d9cda 100644 --- a/src/main/java/com/google/common/primitives/UnsignedLong.java +++ b/src/main/java/com/google/common/primitives/UnsignedLong.java @@ -52,12 +52,6 @@ public final class UnsignedLong extends Number implements Comparable= 0, "value (%s) is outside the range for an unsigned long value", value); - return fromLongBits(value); - } - /** * Returns a {@code UnsignedLong} representing the same value as the specified * {@code BigInteger}. This is the inverse operation of @@ -106,6 +88,18 @@ public final class UnsignedLong extends Number implements Comparable= 0, "value (%s) is outside the range for an unsigned long value", value); + return fromLongBits(value); + } + /** * Returns an {@code UnsignedLong} holding the value of the specified * {@code String}, parsed as an unsigned {@code long} value. @@ -131,35 +125,27 @@ public final class UnsignedLong extends Number implements Comparable { + INSTANCE; + + @Override + public int compare(long[] left, long[] right) { + int minLength = Math.min(left.length, right.length); + for (int i = 0; i < minLength; i++) { + if (left[i] != right[i]) { + return UnsignedLongs.compare(left[i], right[i]); + } + } + return left.length - right.length; + } } public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 - /** - * A (self-inverse) bijection which converts the ordering on unsigned longs to - * the ordering on longs, that is, {@code a <= b} as unsigned longs if and only - * if {@code flip(a) <= flip(b)} as signed longs. - */ - private static long flip(long a) { - return a ^ Long.MIN_VALUE; + // calculated as 0xffffffffffffffff / radix + private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; + + private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; + + private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; + + static { + BigInteger overflow = new BigInteger("10000000000000000", 16); + for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { + maxValueDivs[i] = divide(MAX_VALUE, i); + maxValueMods[i] = (int) remainder(MAX_VALUE, i); + maxSafeDigits[i] = overflow.toString(i).length() - 1; + } } /** @@ -84,45 +103,74 @@ public final class UnsignedLongs { } /** - * Returns the least value present in {@code array}, treating values as - * unsigned. + * Returns the unsigned {@code long} value represented by the given string. * - * @param array a nonempty array of unsigned {@code long} values - * @return the value present in {@code array} that is less than or equal to - * every other value in the array according to {@link #compare} - * @throws IllegalArgumentException if {@code array} is empty + * Accepts a decimal, hexadecimal, or octal number given by specifying the + * following prefix: + * + *
                + *
              • {@code 0x}HexDigits + *
              • {@code 0X}HexDigits + *
              • {@code #}HexDigits + *
              • {@code 0}OctalDigits + *
              + * + * @throws NumberFormatException if the string does not contain a valid unsigned + * {@code long} value + * @since 13.0 */ - public static long min(long... array) { - checkArgument(array.length > 0); - long min = flip(array[0]); - for (int i = 1; i < array.length; i++) { - long next = flip(array[i]); - if (next < min) { - min = next; - } + public static long decode(String stringValue) { + ParseRequest request = ParseRequest.fromString(stringValue); + + try { + return parseUnsignedLong(request.rawValue, request.radix); + } catch (NumberFormatException e) { + NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); + decodeException.initCause(e); + throw decodeException; } - return flip(min); } /** - * Returns the greatest value present in {@code array}, treating values as - * unsigned. + * Returns dividend / divisor, where the dividend and divisor are treated as + * unsigned 64-bit quantities. * - * @param array a nonempty array of unsigned {@code long} values - * @return the value present in {@code array} that is greater than or equal to - * every other value in the array according to {@link #compare} - * @throws IllegalArgumentException if {@code array} is empty + * @param dividend the dividend (numerator) + * @param divisor the divisor (denominator) + * @throws ArithmeticException if divisor is 0 */ - public static long max(long... array) { - checkArgument(array.length > 0); - long max = flip(array[0]); - for (int i = 1; i < array.length; i++) { - long next = flip(array[i]); - if (next > max) { - max = next; + public static long divide(long dividend, long divisor) { + if (divisor < 0) { // i.e., divisor >= 2^63: + if (compare(dividend, divisor) < 0) { + return 0; // dividend < divisor + } else { + return 1; // dividend >= divisor } } - return flip(max); + + // Optimization - use signed division if dividend < 2^63 + if (dividend >= 0) { + return dividend / divisor; + } + + /* + * Otherwise, approximate the quotient, check, and correct if necessary. Our + * approximation is guaranteed to be either exact or one less than the correct + * value. This follows from fact that floor(floor(x)/i) == floor(x/i) for any + * real x and integer i != 0. The proof is not quite trivial. + */ + long quotient = ((dividend >>> 1) / divisor) << 1; + long rem = dividend - quotient * divisor; + return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); + } + + /** + * A (self-inverse) bijection which converts the ordering on unsigned longs to + * the ordering on longs, that is, {@code a <= b} as unsigned longs if and only + * if {@code flip(a) <= flip(b)} as signed longs. + */ + private static long flip(long a) { + return a ^ Long.MIN_VALUE; } /** @@ -169,86 +217,69 @@ public final class UnsignedLongs { return LexicographicalComparator.INSTANCE; } - enum LexicographicalComparator implements Comparator { - INSTANCE; - - @Override - public int compare(long[] left, long[] right) { - int minLength = Math.min(left.length, right.length); - for (int i = 0; i < minLength; i++) { - if (left[i] != right[i]) { - return UnsignedLongs.compare(left[i], right[i]); - } + /** + * Returns the greatest value present in {@code array}, treating values as + * unsigned. + * + * @param array a nonempty array of unsigned {@code long} values + * @return the value present in {@code array} that is greater than or equal to + * every other value in the array according to {@link #compare} + * @throws IllegalArgumentException if {@code array} is empty + */ + public static long max(long... array) { + checkArgument(array.length > 0); + long max = flip(array[0]); + for (int i = 1; i < array.length; i++) { + long next = flip(array[i]); + if (next > max) { + max = next; } - return left.length - right.length; } + return flip(max); } /** - * Returns dividend / divisor, where the dividend and divisor are treated as - * unsigned 64-bit quantities. + * Returns the least value present in {@code array}, treating values as + * unsigned. * - * @param dividend the dividend (numerator) - * @param divisor the divisor (denominator) - * @throws ArithmeticException if divisor is 0 + * @param array a nonempty array of unsigned {@code long} values + * @return the value present in {@code array} that is less than or equal to + * every other value in the array according to {@link #compare} + * @throws IllegalArgumentException if {@code array} is empty */ - public static long divide(long dividend, long divisor) { - if (divisor < 0) { // i.e., divisor >= 2^63: - if (compare(dividend, divisor) < 0) { - return 0; // dividend < divisor - } else { - return 1; // dividend >= divisor + public static long min(long... array) { + checkArgument(array.length > 0); + long min = flip(array[0]); + for (int i = 1; i < array.length; i++) { + long next = flip(array[i]); + if (next < min) { + min = next; } } - - // Optimization - use signed division if dividend < 2^63 - if (dividend >= 0) { - return dividend / divisor; - } - - /* - * Otherwise, approximate the quotient, check, and correct if necessary. Our - * approximation is guaranteed to be either exact or one less than the correct - * value. This follows from fact that floor(floor(x)/i) == floor(x/i) for any - * real x and integer i != 0. The proof is not quite trivial. - */ - long quotient = ((dividend >>> 1) / divisor) << 1; - long rem = dividend - quotient * divisor; - return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); + return flip(min); } /** - * Returns dividend % divisor, where the dividend and divisor are treated as - * unsigned 64-bit quantities. - * - * @param dividend the dividend (numerator) - * @param divisor the divisor (denominator) - * @throws ArithmeticException if divisor is 0 - * @since 11.0 + * Returns true if (current * radix) + digit is a number too large to be + * represented by an unsigned long. This is useful for detecting overflow while + * parsing a string representation of a number. Does not verify whether supplied + * radix is valid, passing an invalid radix will give undefined results or an + * ArrayIndexOutOfBoundsException. */ - public static long remainder(long dividend, long divisor) { - if (divisor < 0) { // i.e., divisor >= 2^63: - if (compare(dividend, divisor) < 0) { - return dividend; // dividend < divisor - } else { - return dividend - divisor; // dividend >= divisor + private static boolean overflowInParse(long current, int digit, int radix) { + if (current >= 0) { + if (current < maxValueDivs[radix]) { + return false; } + if (current > maxValueDivs[radix]) { + return true; + } + // current == maxValueDivs[radix] + return (digit > maxValueMods[radix]); } - // Optimization - use signed modulus if dividend < 2^63 - if (dividend >= 0) { - return dividend % divisor; - } - - /* - * Otherwise, approximate the quotient, check, and correct if necessary. Our - * approximation is guaranteed to be either exact or one less than the correct - * value. This follows from fact that floor(floor(x)/i) == floor(x/i) for any - * real x and integer i != 0. The proof is not quite trivial. - */ - long quotient = ((dividend >>> 1) / divisor) << 1; - long rem = dividend - quotient * divisor; - return rem - (compare(rem, divisor) >= 0 ? divisor : 0); + // current < 0: high bit is set + return true; } /** @@ -264,35 +295,6 @@ public final class UnsignedLongs { return parseUnsignedLong(s, 10); } - /** - * Returns the unsigned {@code long} value represented by the given string. - * - * Accepts a decimal, hexadecimal, or octal number given by specifying the - * following prefix: - * - *
                - *
              • {@code 0x}HexDigits - *
              • {@code 0X}HexDigits - *
              • {@code #}HexDigits - *
              • {@code 0}OctalDigits - *
              - * - * @throws NumberFormatException if the string does not contain a valid unsigned - * {@code long} value - * @since 13.0 - */ - public static long decode(String stringValue) { - ParseRequest request = ParseRequest.fromString(stringValue); - - try { - return parseUnsignedLong(request.rawValue, request.radix); - } catch (NumberFormatException e) { - NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); - decodeException.initCause(e); - throw decodeException; - } - } - /** * Returns the unsigned {@code long} value represented by a string with the * given radix. @@ -334,26 +336,37 @@ public final class UnsignedLongs { } /** - * Returns true if (current * radix) + digit is a number too large to be - * represented by an unsigned long. This is useful for detecting overflow while - * parsing a string representation of a number. Does not verify whether supplied - * radix is valid, passing an invalid radix will give undefined results or an - * ArrayIndexOutOfBoundsException. + * Returns dividend % divisor, where the dividend and divisor are treated as + * unsigned 64-bit quantities. + * + * @param dividend the dividend (numerator) + * @param divisor the divisor (denominator) + * @throws ArithmeticException if divisor is 0 + * @since 11.0 */ - private static boolean overflowInParse(long current, int digit, int radix) { - if (current >= 0) { - if (current < maxValueDivs[radix]) { - return false; + public static long remainder(long dividend, long divisor) { + if (divisor < 0) { // i.e., divisor >= 2^63: + if (compare(dividend, divisor) < 0) { + return dividend; // dividend < divisor + } else { + return dividend - divisor; // dividend >= divisor } - if (current > maxValueDivs[radix]) { - return true; - } - // current == maxValueDivs[radix] - return (digit > maxValueMods[radix]); } - // current < 0: high bit is set - return true; + // Optimization - use signed modulus if dividend < 2^63 + if (dividend >= 0) { + return dividend % divisor; + } + + /* + * Otherwise, approximate the quotient, check, and correct if necessary. Our + * approximation is guaranteed to be either exact or one less than the correct + * value. This follows from fact that floor(floor(x)/i) == floor(x/i) for any + * real x and integer i != 0. The proof is not quite trivial. + */ + long quotient = ((dividend >>> 1) / divisor) << 1; + long rem = dividend - quotient * divisor; + return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } /** @@ -400,16 +413,6 @@ public final class UnsignedLongs { } } - // calculated as 0xffffffffffffffff / radix - private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; - private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; - private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; - static { - BigInteger overflow = new BigInteger("10000000000000000", 16); - for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { - maxValueDivs[i] = divide(MAX_VALUE, i); - maxValueMods[i] = (int) remainder(MAX_VALUE, i); - maxSafeDigits[i] = overflow.toString(i).length() - 1; - } + private UnsignedLongs() { } } diff --git a/src/main/java/com/google/common/xml/XmlEscapers.java b/src/main/java/com/google/common/xml/XmlEscapers.java index 68a4ac83..c4acaf00 100644 --- a/src/main/java/com/google/common/xml/XmlEscapers.java +++ b/src/main/java/com/google/common/xml/XmlEscapers.java @@ -49,11 +49,10 @@ import com.google.common.escape.Escapers; @Beta @GwtCompatible public class XmlEscapers { - private XmlEscapers() { - } - private static final char MIN_ASCII_CONTROL_CHAR = 0x00; + private static final char MAX_ASCII_CONTROL_CHAR = 0x1F; + private static final Escaper XML_ESCAPER; // For each xxxEscaper() method, please add links to external reference pages // that are considered authoritative for the behavior of that escaper. @@ -65,60 +64,10 @@ public class XmlEscapers { // 2.2 of // the XML specification. - /** - * Returns an {@link Escaper} instance that escapes special characters in a - * string so it can safely be included in an XML document as element content. - * See section - * 2.4 of the - * XML specification. - * - *

              - * Note: Double and single quotes are not escaped, so it is not - * safe to use this escaper to escape attribute values. Use - * {@link #xmlContentEscaper} if the output can appear in element content or - * {@link #xmlAttributeEscaper} in attribute values. - * - *

              - * This escaper does not escape non-ASCII characters to their numeric character - * references (NCR). Any non-ASCII characters appearing in the input will be - * preserved in the output. Specifically "\r" (carriage return) is preserved in - * the output, which may result in it being silently converted to "\n" when the - * XML is parsed. - * - *

              - * This escaper does not treat surrogate pairs specially and does not perform - * Unicode validation on its input. - */ - public static Escaper xmlContentEscaper() { - return XML_CONTENT_ESCAPER; - } - - /** - * Returns an {@link Escaper} instance that escapes special characters in a - * string so it can safely be included in XML document as an attribute value. - * See section - * 3.3.3 - * of the XML specification. - * - *

              - * This escaper does not escape non-ASCII characters to their numeric character - * references (NCR). However, horizontal tab {@code '\t'}, line feed - * {@code '\n'} and carriage return {@code '\r'} are escaped to a corresponding - * NCR {@code " "}, {@code " "}, and {@code " "} respectively. Any - * other non-ASCII characters appearing in the input will be preserved in the - * output. - * - *

              - * This escaper does not treat surrogate pairs specially and does not perform - * Unicode validation on its input. - */ - public static Escaper xmlAttributeEscaper() { - return XML_ATTRIBUTE_ESCAPER; - } - - private static final Escaper XML_ESCAPER; private static final Escaper XML_CONTENT_ESCAPER; + private static final Escaper XML_ATTRIBUTE_ESCAPER; + static { Escapers.Builder builder = Escapers.builder(); // The char values \uFFFE and \uFFFF are explicitly not allowed in XML @@ -154,4 +103,58 @@ public class XmlEscapers { builder.addEscape('\r', " "); XML_ATTRIBUTE_ESCAPER = builder.build(); } + + /** + * Returns an {@link Escaper} instance that escapes special characters in a + * string so it can safely be included in XML document as an attribute value. + * See section + * 3.3.3 + * of the XML specification. + * + *

              + * This escaper does not escape non-ASCII characters to their numeric character + * references (NCR). However, horizontal tab {@code '\t'}, line feed + * {@code '\n'} and carriage return {@code '\r'} are escaped to a corresponding + * NCR {@code " "}, {@code " "}, and {@code " "} respectively. Any + * other non-ASCII characters appearing in the input will be preserved in the + * output. + * + *

              + * This escaper does not treat surrogate pairs specially and does not perform + * Unicode validation on its input. + */ + public static Escaper xmlAttributeEscaper() { + return XML_ATTRIBUTE_ESCAPER; + } + + /** + * Returns an {@link Escaper} instance that escapes special characters in a + * string so it can safely be included in an XML document as element content. + * See section + * 2.4 of the + * XML specification. + * + *

              + * Note: Double and single quotes are not escaped, so it is not + * safe to use this escaper to escape attribute values. Use + * {@link #xmlContentEscaper} if the output can appear in element content or + * {@link #xmlAttributeEscaper} in attribute values. + * + *

              + * This escaper does not escape non-ASCII characters to their numeric character + * references (NCR). Any non-ASCII characters appearing in the input will be + * preserved in the output. Specifically "\r" (carriage return) is preserved in + * the output, which may result in it being silently converted to "\n" when the + * XML is parsed. + * + *

              + * This escaper does not treat surrogate pairs specially and does not perform + * Unicode validation on its input. + */ + public static Escaper xmlContentEscaper() { + return XML_CONTENT_ESCAPER; + } + + private XmlEscapers() { + } } diff --git a/src/main/java/com/google/thirdparty/publicsuffix/PublicSuffixType.java b/src/main/java/com/google/thirdparty/publicsuffix/PublicSuffixType.java index 28b3c6eb..c0687c76 100644 --- a/src/main/java/com/google/thirdparty/publicsuffix/PublicSuffixType.java +++ b/src/main/java/com/google/thirdparty/publicsuffix/PublicSuffixType.java @@ -29,25 +29,6 @@ enum PublicSuffixType { /** ICANN definition of a top-level domain */ ICANN('!', '?'); - /** The character used for an inner node in the trie encoding */ - private final char innerNodeCode; - - /** The character used for a leaf node in the trie encoding */ - private final char leafNodeCode; - - private PublicSuffixType(char innerNodeCode, char leafNodeCode) { - this.innerNodeCode = innerNodeCode; - this.leafNodeCode = leafNodeCode; - } - - char getLeafNodeCode() { - return leafNodeCode; - } - - char getInnerNodeCode() { - return innerNodeCode; - } - /** Returns a PublicSuffixType of the right type according to the given code */ static PublicSuffixType fromCode(char code) { for (PublicSuffixType value : values()) { @@ -61,4 +42,23 @@ enum PublicSuffixType { static PublicSuffixType fromIsPrivate(boolean isPrivate) { return isPrivate ? PRIVATE : ICANN; } + + /** The character used for an inner node in the trie encoding */ + private final char innerNodeCode; + + /** The character used for a leaf node in the trie encoding */ + private final char leafNodeCode; + + private PublicSuffixType(char innerNodeCode, char leafNodeCode) { + this.innerNodeCode = innerNodeCode; + this.leafNodeCode = leafNodeCode; + } + + char getInnerNodeCode() { + return innerNodeCode; + } + + char getLeafNodeCode() { + return leafNodeCode; + } } diff --git a/src/main/java/com/google/thirdparty/publicsuffix/TrieParser.java b/src/main/java/com/google/thirdparty/publicsuffix/TrieParser.java index 99081e2b..707a55cd 100644 --- a/src/main/java/com/google/thirdparty/publicsuffix/TrieParser.java +++ b/src/main/java/com/google/thirdparty/publicsuffix/TrieParser.java @@ -31,21 +31,6 @@ class TrieParser { private static final Joiner PREFIX_JOINER = Joiner.on(""); - /** - * Parses a serialized trie representation of a map of reversed public suffixes - * into an immutable map of public suffixes. - */ - static ImmutableMap parseTrie(CharSequence encoded) { - ImmutableMap.Builder builder = ImmutableMap.builder(); - int encodedLen = encoded.length(); - int idx = 0; - while (idx < encodedLen) { - idx += doParseTrieToBuilder(Lists.newLinkedList(), encoded.subSequence(idx, encodedLen), - builder); - } - return builder.build(); - } - /** * Parses a trie node and returns the number of characters consumed. * @@ -100,6 +85,21 @@ class TrieParser { return idx; } + /** + * Parses a serialized trie representation of a map of reversed public suffixes + * into an immutable map of public suffixes. + */ + static ImmutableMap parseTrie(CharSequence encoded) { + ImmutableMap.Builder builder = ImmutableMap.builder(); + int encodedLen = encoded.length(); + int idx = 0; + while (idx < encodedLen) { + idx += doParseTrieToBuilder(Lists.newLinkedList(), encoded.subSequence(idx, encodedLen), + builder); + } + return builder.build(); + } + /** * Reverses a character sequence. This is borrowed from * https://code.google.com/p/google-web-toolkit/source/detail?r=11591# and can diff --git a/src/main/java/javax/annotation/Generated.java b/src/main/java/javax/annotation/Generated.java index 0db0dbbe..e7761c17 100644 --- a/src/main/java/javax/annotation/Generated.java +++ b/src/main/java/javax/annotation/Generated.java @@ -84,11 +84,10 @@ import java.lang.annotation.Target; @Target({ PACKAGE, TYPE, ANNOTATION_TYPE, METHOD, CONSTRUCTOR, FIELD, LOCAL_VARIABLE, PARAMETER }) public @interface Generated { /** - * The value element must have the name of the code generator. The recommended - * convention is to use the fully qualified name of the code generator. For - * example: com.acme.generator.CodeGen. + * A place holder for any comments that the code generator may want to include + * in the generated code. */ - String[] value(); + String comments() default ""; /** * Date when the source was generated. @@ -96,8 +95,9 @@ public @interface Generated { String date() default ""; /** - * A place holder for any comments that the code generator may want to include - * in the generated code. + * The value element must have the name of the code generator. The recommended + * convention is to use the fully qualified name of the code generator. For + * example: com.acme.generator.CodeGen. */ - String comments() default ""; + String[] value(); } diff --git a/src/main/java/javax/annotation/MatchesPattern.java b/src/main/java/javax/annotation/MatchesPattern.java index 8428e64f..a794c96c 100644 --- a/src/main/java/javax/annotation/MatchesPattern.java +++ b/src/main/java/javax/annotation/MatchesPattern.java @@ -20,11 +20,6 @@ import javax.annotation.meta.When; @TypeQualifier(applicableTo = String.class) @Retention(RetentionPolicy.RUNTIME) public @interface MatchesPattern { - @RegEx - String value(); - - int flags() default 0; - static class Checker implements TypeQualifierValidator { public When forConstantValue(MatchesPattern annotation, Object value) { Pattern p = Pattern.compile(annotation.value(), annotation.flags()); @@ -34,4 +29,9 @@ public @interface MatchesPattern { } } + + int flags() default 0; + + @RegEx + String value(); } diff --git a/src/main/java/javax/annotation/Nonnegative.java b/src/main/java/javax/annotation/Nonnegative.java index 7e3eefaa..18f50cbf 100644 --- a/src/main/java/javax/annotation/Nonnegative.java +++ b/src/main/java/javax/annotation/Nonnegative.java @@ -19,8 +19,6 @@ import javax.annotation.meta.When; @TypeQualifier(applicableTo = Number.class) @Retention(RetentionPolicy.RUNTIME) public @interface Nonnegative { - When when() default When.ALWAYS; - class Checker implements TypeQualifierValidator { public When forConstantValue(Nonnegative annotation, Object v) { @@ -44,4 +42,6 @@ public @interface Nonnegative { } } + + When when() default When.ALWAYS; } diff --git a/src/main/java/javax/annotation/Nonnull.java b/src/main/java/javax/annotation/Nonnull.java index 04d1bbe8..2b05d3e8 100644 --- a/src/main/java/javax/annotation/Nonnull.java +++ b/src/main/java/javax/annotation/Nonnull.java @@ -20,8 +20,6 @@ import javax.annotation.meta.When; @TypeQualifier @Retention(RetentionPolicy.RUNTIME) public @interface Nonnull { - When when() default When.ALWAYS; - class Checker implements TypeQualifierValidator { public When forConstantValue(Nonnull qualifierArgument, Object value) { @@ -30,4 +28,6 @@ public @interface Nonnull { return When.ALWAYS; } } + + When when() default When.ALWAYS; } diff --git a/src/main/java/javax/annotation/RegEx.java b/src/main/java/javax/annotation/RegEx.java index a04b7bab..2b332f20 100644 --- a/src/main/java/javax/annotation/RegEx.java +++ b/src/main/java/javax/annotation/RegEx.java @@ -22,8 +22,6 @@ import javax.annotation.meta.When; @TypeQualifierNickname @Retention(RetentionPolicy.RUNTIME) public @interface RegEx { - When when() default When.ALWAYS; - static class Checker implements TypeQualifierValidator { public When forConstantValue(RegEx annotation, Object value) { @@ -41,4 +39,6 @@ public @interface RegEx { } + When when() default When.ALWAYS; + } diff --git a/src/main/java/javax/annotation/Resource.java b/src/main/java/javax/annotation/Resource.java index b6e8f5f3..c712a966 100644 --- a/src/main/java/javax/annotation/Resource.java +++ b/src/main/java/javax/annotation/Resource.java @@ -73,31 +73,6 @@ import java.lang.annotation.Target; @Retention(RUNTIME) @Repeatable(Resources.class) public @interface Resource { - /** - * The JNDI name of the resource. For field annotations, the default is the - * field name. For method annotations, the default is the JavaBeans property - * name corresponding to the method. For class annotations, there is no default - * and this must be specified. - */ - String name() default ""; - - /** - * The name of the resource that the reference points to. It can link to any - * compatible resource using the global JNDI names. - * - * @since 1.7, Common Annotations 1.1 - */ - - String lookup() default ""; - - /** - * The Java type of the resource. For field annotations, the default is the type - * of the field. For method annotations, the default is the type of the - * JavaBeans property. For class annotations, there is no default and this must - * be specified. - */ - Class type() default java.lang.Object.class; - /** * The two possible authentication types for a resource. */ @@ -113,12 +88,21 @@ public @interface Resource { AuthenticationType authenticationType() default AuthenticationType.CONTAINER; /** - * Indicates whether this resource can be shared between this component and - * other components. This may be specified for resources representing a - * connection factory of any supported type, and must not be specified for - * resources of other types. + * Description of this resource. The description is expected to be in the + * default language of the system on which the application is deployed. The + * description can be presented to the Deployer to help in choosing the correct + * resource. */ - boolean shareable() default true; + String description() default ""; + + /** + * The name of the resource that the reference points to. It can link to any + * compatible resource using the global JNDI names. + * + * @since 1.7, Common Annotations 1.1 + */ + + String lookup() default ""; /** * A product-specific name that this resource should be mapped to. The @@ -135,10 +119,26 @@ public @interface Resource { String mappedName() default ""; /** - * Description of this resource. The description is expected to be in the - * default language of the system on which the application is deployed. The - * description can be presented to the Deployer to help in choosing the correct - * resource. + * The JNDI name of the resource. For field annotations, the default is the + * field name. For method annotations, the default is the JavaBeans property + * name corresponding to the method. For class annotations, there is no default + * and this must be specified. */ - String description() default ""; + String name() default ""; + + /** + * Indicates whether this resource can be shared between this component and + * other components. This may be specified for resources representing a + * connection factory of any supported type, and must not be specified for + * resources of other types. + */ + boolean shareable() default true; + + /** + * The Java type of the resource. For field annotations, the default is the type + * of the field. For method annotations, the default is the type of the + * JavaBeans property. For class annotations, there is no default and this must + * be specified. + */ + Class type() default java.lang.Object.class; } diff --git a/src/main/java/javax/annotation/sql/DataSourceDefinition.java b/src/main/java/javax/annotation/sql/DataSourceDefinition.java index dbda762a..03a14cee 100644 --- a/src/main/java/javax/annotation/sql/DataSourceDefinition.java +++ b/src/main/java/javax/annotation/sql/DataSourceDefinition.java @@ -174,13 +174,6 @@ import java.lang.annotation.Target; @Repeatable(DataSourceDefinitions.class) public @interface DataSourceDefinition { - /** - * JNDI name by which the data source will be registered. - * - * @since 1.1 - */ - String name(); - /** * Name of a DataSource class that implements javax.sql.DataSource * or javax.sql.XADataSource or @@ -190,36 +183,6 @@ public @interface DataSourceDefinition { */ String className(); - /** - * Description of this data source - * - * @since 1.1 - */ - String description() default ""; - - /** - * A JDBC URL. If the url annotation element contains a DataSource - * property that was also specified using the corresponding annotation element, - * the precedence order is undefined and implementation specific. - * - * @since 1.1 - */ - String url() default ""; - - /** - * User name to use for connection authentication. - * - * @since 1.1 - */ - String user() default ""; - - /** - * Password to use for connection authentication. - * - * @since 1.1 - */ - String password() default ""; - /** * Name of a database on a server. * @@ -228,18 +191,21 @@ public @interface DataSourceDefinition { String databaseName() default ""; /** - * Port number where a server is listening for requests. + * Description of this data source * * @since 1.1 */ - int portNumber() default -1; + String description() default ""; /** - * Database server name. + * Number of connections that should be created when a connection pool is + * initialized. + *

              + * Default is vendor-specific * * @since 1.1 */ - String serverName() default "localhost"; + int initialPoolSize() default -1; /** * Isolation level for connections. The Isolation level must be one of the @@ -260,43 +226,16 @@ public @interface DataSourceDefinition { int isolationLevel() default -1; /** - * Set to false if connections should not participate in - * transactions. - *

              - * Default is to enlist in a transaction when one is active or becomes active. - * - * @since 1.1 - */ - boolean transactional() default true; - - /** - * Number of connections that should be created when a connection pool is - * initialized. - *

              - * Default is vendor-specific - * - * @since 1.1 - */ - int initialPoolSize() default -1; - - /** - * Maximum number of connections that should be concurrently allocated for a - * connection pool. + * Sets the maximum time in seconds that this data source will wait while + * attempting to connect to a database. A value of zero specifies that the + * timeout is the default system timeout if there is one; otherwise, it + * specifies that there is no timeout. *

              * Default is vendor-specific. * * @since 1.1 */ - int maxPoolSize() default -1; - - /** - * Minimum number of connections that should be allocated for a connection pool. - *

              - * Default is vendor-specific. - * - * @since 1.1 - */ - int minPoolSize() default -1; + int loginTimeout() default 0; /** * The number of seconds that a physical connection should remain unused in the @@ -308,6 +247,16 @@ public @interface DataSourceDefinition { */ int maxIdleTime() default -1; + /** + * Maximum number of connections that should be concurrently allocated for a + * connection pool. + *

              + * Default is vendor-specific. + * + * @since 1.1 + */ + int maxPoolSize() default -1; + /** * The total number of statements that a connection pool should keep open. A * value of 0 indicates that the caching of statements is disabled for a @@ -319,6 +268,36 @@ public @interface DataSourceDefinition { */ int maxStatements() default -1; + /** + * Minimum number of connections that should be allocated for a connection pool. + *

              + * Default is vendor-specific. + * + * @since 1.1 + */ + int minPoolSize() default -1; + + /** + * JNDI name by which the data source will be registered. + * + * @since 1.1 + */ + String name(); + + /** + * Password to use for connection authentication. + * + * @since 1.1 + */ + String password() default ""; + + /** + * Port number where a server is listening for requests. + * + * @since 1.1 + */ + int portNumber() default -1; + /** * Used to specify vendor-specific properties and less commonly used * DataSource properties such as: @@ -342,14 +321,35 @@ public @interface DataSourceDefinition { String[] properties() default {}; /** - * Sets the maximum time in seconds that this data source will wait while - * attempting to connect to a database. A value of zero specifies that the - * timeout is the default system timeout if there is one; otherwise, it - * specifies that there is no timeout. - *

              - * Default is vendor-specific. + * Database server name. * * @since 1.1 */ - int loginTimeout() default 0; + String serverName() default "localhost"; + + /** + * Set to false if connections should not participate in + * transactions. + *

              + * Default is to enlist in a transaction when one is active or becomes active. + * + * @since 1.1 + */ + boolean transactional() default true; + + /** + * A JDBC URL. If the url annotation element contains a DataSource + * property that was also specified using the corresponding annotation element, + * the precedence order is undefined and implementation specific. + * + * @since 1.1 + */ + String url() default ""; + + /** + * User name to use for connection authentication. + * + * @since 1.1 + */ + String user() default ""; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/ArrayUtils.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/ArrayUtils.java index 8335246e..13826f29 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/ArrayUtils.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/ArrayUtils.java @@ -7,25 +7,22 @@ import net.minecraft.client.settings.KeyBinding; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ArrayUtils { - public static KeyBinding[] clone(KeyBinding[] keyBinding) { - KeyBinding[] clone = new KeyBinding[keyBinding.length]; - System.arraycopy(keyBinding, 0, clone, 0, keyBinding.length); - return clone; - } + private static final String hex = "0123456789abcdef"; public static KeyBinding[] addAll(KeyBinding[] arr1, KeyBinding[] arr2) { KeyBinding[] clone = new KeyBinding[arr1.length + arr2.length]; @@ -34,47 +31,51 @@ public class ArrayUtils { return clone; } - public static String[] subarray(String[] stackTrace, int i, int j) { - String[] ret = new String[j - i]; - System.arraycopy(stackTrace, i, ret, 0, j - i); - return ret; - } - public static String asciiString(byte[] bytes) { char[] str = new char[bytes.length]; - for(int i = 0; i < bytes.length; ++i) { - str[i] = (char)((int) bytes[i] & 0xFF); + for (int i = 0; i < bytes.length; ++i) { + str[i] = (char) ((int) bytes[i] & 0xFF); } return new String(str); } - + public static byte[] asciiString(String string) { byte[] str = new byte[string.length()]; - for(int i = 0; i < str.length; ++i) { - str[i] = (byte)string.charAt(i); + for (int i = 0; i < str.length; ++i) { + str[i] = (byte) string.charAt(i); } return str; } - - private static final String hex = "0123456789abcdef"; - - public static String hexString(byte[] bytesIn) { - char[] ret = new char[bytesIn.length << 1]; - for(int i = 0; i < bytesIn.length; ++i) { - ret[i << 1] = hex.charAt((bytesIn[i] >> 4) & 15); - ret[(i << 1) + 1] = hex.charAt(bytesIn[i] & 15); - } - return new String(ret); + + public static KeyBinding[] clone(KeyBinding[] keyBinding) { + KeyBinding[] clone = new KeyBinding[keyBinding.length]; + System.arraycopy(keyBinding, 0, clone, 0, keyBinding.length); + return clone; } public static void eaglerShuffle(List list, EaglercraftRandom rnd) { T k; for (int i = list.size() - 1, j; i > 0; --i) { - j = rnd.nextInt(i + 1); - k = list.get(j); - list.set(j, list.get(i)); - list.set(i, k); - } - } + j = rnd.nextInt(i + 1); + k = list.get(j); + list.set(j, list.get(i)); + list.set(i, k); + } + } + + public static String hexString(byte[] bytesIn) { + char[] ret = new char[bytesIn.length << 1]; + for (int i = 0; i < bytesIn.length; ++i) { + ret[i << 1] = hex.charAt((bytesIn[i] >>> 4) & 15); + ret[(i << 1) + 1] = hex.charAt(bytesIn[i] & 15); + } + return new String(ret); + } + + public static String[] subarray(String[] stackTrace, int i, int j) { + String[] ret = new String[j - i]; + System.arraycopy(stackTrace, i, ret, 0, j - i); + return ret; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Base64.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Base64.java index 177b54ee..ad892688 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Base64.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Base64.java @@ -116,30 +116,18 @@ public class Base64 extends BaseNCodec { 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 // 70-7a p-z }; - public static int lookupCharInt(char c) { - return c < 123 ? DECODE_TABLE[c] : -1; - } - - public static char lookupIntChar(int i) { - return (char)STANDARD_ENCODE_TABLE[i]; - } - /** * Base64 uses 6-bit fields. */ /** Mask used to extract 6 bits, used when encoding */ private static final int MASK_6BITS = 0x3f; + /** Mask used to extract 4 bits, used when decoding final trailing character. */ private static final int MASK_4BITS = 0xf; + /** Mask used to extract 2 bits, used when decoding final trailing character. */ private static final int MASK_2BITS = 0x3; - // The static final fields above are used for the original static byte[] methods - // on Base64. - // The private member fields below are used with the new streaming approach, - // which requires - // some state be preserved between calls of encode() and decode(). - /** * Decodes Base64 data into octets. *

              @@ -169,6 +157,12 @@ public class Base64 extends BaseNCodec { return new Base64().decode(base64String); } + // The static final fields above are used for the original static byte[] methods + // on Base64. + // The private member fields below are used with the new streaming approach, + // which requires + // some state be preserved between calls of encode() and decode(). + // Implementation of integer encoding used for crypto /** * Decodes a byte64-encoded integer according to crypto standards such as W3C's @@ -382,6 +376,14 @@ public class Base64 extends BaseNCodec { return isBase64(base64.getBytes(Charset.forName("UTF-8"))); } + public static int lookupCharInt(char c) { + return c < 123 ? DECODE_TABLE[c] : -1; + } + + public static char lookupIntChar(int i) { + return (char) STANDARD_ENCODE_TABLE[i]; + } + /** * Returns a byte-array representation of a {@code BigInteger} without sign bit. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/ClientUUIDLoadingCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/ClientUUIDLoadingCache.java index aa60cda4..117ae6e3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/ClientUUIDLoadingCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/ClientUUIDLoadingCache.java @@ -15,125 +15,21 @@ import net.minecraft.entity.player.EntityPlayerMP; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ClientUUIDLoadingCache { - private static final Logger logger = LogManager.getLogger("ClientUUIDLoadingCache"); - - public static final EaglercraftUUID NULL_UUID = new EaglercraftUUID(0l, 0l); - public static final EaglercraftUUID PENDING_UUID = new EaglercraftUUID(0x6969696969696969l, 0x6969696969696969l); - public static final EaglercraftUUID VANILLA_UUID = new EaglercraftUUID(0x1DCE015CD384374El, 0x85030A4DE95E5736l); - - /** - * For client devs, allows you to get EaglercraftVersion.clientBrandUUID of - * other players on a server, to detect other players who also use your client. - * - * Requires EaglerXBungee 1.3.0 or EaglerXVelocity 1.1.0 - * - * @return NULL_UUID if not found, PENDING_UUID if pending, - * VANILLA_UUID if vanilla, or the remote player's - * client's EaglercraftVersion.clientBrandUUID - */ - public static EaglercraftUUID getPlayerClientBrandUUID(EntityPlayer player) { - EaglercraftUUID ret = null; - if(player instanceof AbstractClientPlayer) { - ret = ((AbstractClientPlayer)player).clientBrandUUIDCache; - if(ret == null) { - Minecraft mc = Minecraft.getMinecraft(); - if(mc != null && mc.thePlayer != null && mc.thePlayer.sendQueue.getEaglerMessageProtocol().ver >= 4) { - ret = PENDING_UUID; - EaglercraftUUID playerUUID = player.getUniqueID(); - if(!waitingUUIDs.containsKey(playerUUID) && !evictedUUIDs.containsKey(playerUUID)) { - int reqID = ++requestId & 0x3FFF; - WaitingLookup newLookup = new WaitingLookup(reqID, playerUUID, EagRuntime.steadyTimeMillis(), - (AbstractClientPlayer) player); - waitingIDs.put(reqID, newLookup); - waitingUUIDs.put(playerUUID, newLookup); - mc.thePlayer.sendQueue.sendEaglerMessage( - new CPacketGetOtherClientUUIDV4EAG(reqID, newLookup.uuid.msb, newLookup.uuid.lsb)); - } - } - } - }else if(player instanceof EntityPlayerMP) { - ret = ((EntityPlayerMP)player).clientBrandUUID; - } - if(ret == null) { - ret = NULL_UUID; - } - return ret; - } - - private static final Map waitingIDs = new HashMap<>(); - private static final Map waitingUUIDs = new HashMap<>(); - private static final Map evictedUUIDs = new HashMap<>(); - - private static int requestId = 0; - private static long lastFlushReq = EagRuntime.steadyTimeMillis(); - private static long lastFlushEvict = EagRuntime.steadyTimeMillis(); - - public static void update() { - long timestamp = EagRuntime.steadyTimeMillis(); - if(timestamp - lastFlushReq > 5000l) { - lastFlushReq = timestamp; - if(!waitingIDs.isEmpty()) { - Iterator itr = waitingIDs.values().iterator(); - while(itr.hasNext()) { - WaitingLookup lookup = itr.next(); - if(timestamp - lookup.timestamp > 15000l) { - itr.remove(); - waitingUUIDs.remove(lookup.uuid); - } - } - } - } - if(timestamp - lastFlushEvict > 1000l) { - lastFlushEvict = timestamp; - if(!evictedUUIDs.isEmpty()) { - Iterator evictItr = evictedUUIDs.values().iterator(); - while(evictItr.hasNext()) { - if(timestamp - evictItr.next().longValue() > 3000l) { - evictItr.remove(); - } - } - } - } - } - - public static void flushRequestCache() { - waitingIDs.clear(); - waitingUUIDs.clear(); - evictedUUIDs.clear(); - } - - public static void handleResponse(int requestId, EaglercraftUUID clientId) { - WaitingLookup lookup = waitingIDs.remove(requestId); - if(lookup != null) { - lookup.player.clientBrandUUIDCache = clientId; - waitingUUIDs.remove(lookup.uuid); - }else { - logger.warn("Unsolicited client brand UUID lookup response #{} recieved! (Brand UUID: {})", requestId, clientId); - } - } - - public static void evict(EaglercraftUUID clientId) { - evictedUUIDs.put(clientId, Long.valueOf(EagRuntime.steadyTimeMillis())); - WaitingLookup lk = waitingUUIDs.remove(clientId); - if(lk != null) { - waitingIDs.remove(lk.reqID); - } - } - private static class WaitingLookup { private final int reqID; @@ -149,4 +45,110 @@ public class ClientUUIDLoadingCache { } } + + private static final Logger logger = LogManager.getLogger("ClientUUIDLoadingCache"); + public static final EaglercraftUUID NULL_UUID = new EaglercraftUUID(0l, 0l); + public static final EaglercraftUUID PENDING_UUID = new EaglercraftUUID(0x6969696969696969l, 0x6969696969696969l); + + public static final EaglercraftUUID VANILLA_UUID = new EaglercraftUUID(0x1DCE015CD384374El, 0x85030A4DE95E5736l); + + private static final Map waitingIDs = new HashMap<>(); + private static final Map waitingUUIDs = new HashMap<>(); + private static final Map evictedUUIDs = new HashMap<>(); + + private static int requestId = 0; + private static long lastFlushReq = EagRuntime.steadyTimeMillis(); + private static long lastFlushEvict = EagRuntime.steadyTimeMillis(); + + public static void evict(EaglercraftUUID clientId) { + evictedUUIDs.put(clientId, Long.valueOf(EagRuntime.steadyTimeMillis())); + WaitingLookup lk = waitingUUIDs.remove(clientId); + if (lk != null) { + waitingIDs.remove(lk.reqID); + } + } + + public static void flushRequestCache() { + waitingIDs.clear(); + waitingUUIDs.clear(); + evictedUUIDs.clear(); + } + + /** + * For client devs, allows you to get EaglercraftVersion.clientBrandUUID of + * other players on a server, to detect other players who also use your client. + * + * Requires EaglerXBungee 1.3.0 or EaglerXVelocity 1.1.0 + * + * @return NULL_UUID if not found, PENDING_UUID if pending, VANILLA_UUID if + * vanilla, or the remote player's client's + * EaglercraftVersion.clientBrandUUID + */ + public static EaglercraftUUID getPlayerClientBrandUUID(EntityPlayer player) { + EaglercraftUUID ret = null; + if (player instanceof AbstractClientPlayer) { + ret = ((AbstractClientPlayer) player).clientBrandUUIDCache; + if (ret == null) { + Minecraft mc = Minecraft.getMinecraft(); + if (mc != null && mc.thePlayer != null && mc.thePlayer.sendQueue.getEaglerMessageProtocol().ver >= 4) { + ret = PENDING_UUID; + EaglercraftUUID playerUUID = player.getUniqueID(); + if (!waitingUUIDs.containsKey(playerUUID) && !evictedUUIDs.containsKey(playerUUID)) { + int reqID = ++requestId & 0x3FFF; + WaitingLookup newLookup = new WaitingLookup(reqID, playerUUID, EagRuntime.steadyTimeMillis(), + (AbstractClientPlayer) player); + waitingIDs.put(reqID, newLookup); + waitingUUIDs.put(playerUUID, newLookup); + mc.thePlayer.sendQueue.sendEaglerMessage( + new CPacketGetOtherClientUUIDV4EAG(reqID, newLookup.uuid.msb, newLookup.uuid.lsb)); + } + } + } + } else if (player instanceof EntityPlayerMP) { + ret = ((EntityPlayerMP) player).clientBrandUUID; + } + if (ret == null) { + ret = NULL_UUID; + } + return ret; + } + + public static void handleResponse(int requestId, EaglercraftUUID clientId) { + WaitingLookup lookup = waitingIDs.remove(requestId); + if (lookup != null) { + lookup.player.clientBrandUUIDCache = clientId; + waitingUUIDs.remove(lookup.uuid); + } else { + logger.warn("Unsolicited client brand UUID lookup response #{} recieved! (Brand UUID: {})", requestId, + clientId); + } + } + + public static void update() { + long timestamp = EagRuntime.steadyTimeMillis(); + if (timestamp - lastFlushReq > 5000l) { + lastFlushReq = timestamp; + if (!waitingIDs.isEmpty()) { + Iterator itr = waitingIDs.values().iterator(); + while (itr.hasNext()) { + WaitingLookup lookup = itr.next(); + if (timestamp - lookup.timestamp > 15000l) { + itr.remove(); + waitingUUIDs.remove(lookup.uuid); + } + } + } + } + if (timestamp - lastFlushEvict > 1000l) { + lastFlushEvict = timestamp; + if (!evictedUUIDs.isEmpty()) { + Iterator evictItr = evictedUUIDs.values().iterator(); + while (evictItr.hasNext()) { + if (timestamp - evictItr.next().longValue() > 3000l) { + evictItr.remove(); + } + } + } + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/DecoderException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/DecoderException.java index 1816cb52..febc3d51 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/DecoderException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/DecoderException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -21,14 +22,14 @@ public class DecoderException extends RuntimeException { super(); } - public DecoderException(String message, Throwable cause) { - super(message, cause); - } - public DecoderException(String message) { super(message); } + public DecoderException(String message, Throwable cause) { + super(message, cause); + } + public DecoderException(Throwable cause) { super(cause); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Display.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Display.java index db9f1587..26e25258 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Display.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Display.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,14 +24,35 @@ public class Display { private static long lastDPIUpdate = -250l; private static float cacheDPI = 1.0f; - public static int getWidth() { - return PlatformInput.getWindowWidth(); + public static boolean contextLost() { + return PlatformInput.contextLost(); } - + + public static void create() { + + } + + public static float getDPI() { + long millis = EagRuntime.steadyTimeMillis(); + if (millis - lastDPIUpdate > 250l) { + lastDPIUpdate = millis; + cacheDPI = PlatformInput.getDPI(); + } + return cacheDPI; + } + public static int getHeight() { return PlatformInput.getWindowHeight(); } + public static int getVisualViewportH() { + return PlatformInput.getVisualViewportH(); + } + + public static int getVisualViewportW() { + return PlatformInput.getVisualViewportW(); + } + public static int getVisualViewportX() { return PlatformInput.getVisualViewportX(); } @@ -39,58 +61,58 @@ public class Display { return PlatformInput.getVisualViewportY(); } - public static int getVisualViewportW() { - return PlatformInput.getVisualViewportW(); - } - - public static int getVisualViewportH() { - return PlatformInput.getVisualViewportH(); + public static int getWidth() { + return PlatformInput.getWindowWidth(); } public static boolean isActive() { return PlatformInput.getWindowFocused(); } - public static void create() { - - } - - public static void setTitle(String string) { - - } - public static boolean isCloseRequested() { return PlatformInput.isCloseRequested(); } - public static void setVSync(boolean enable) { - PlatformInput.setVSync(enable); + public static boolean isFullscreen() { + return PlatformInput.isFullscreen(); } public static boolean isVSyncSupported() { return PlatformInput.isVSyncSupported(); } - public static void update() { - PlatformInput.update(); + public static void setTitle(String string) { + + } + + public static void setVSync(boolean enable) { + PlatformInput.setVSync(enable); + } + + public static boolean supportsFullscreen() { + return PlatformInput.supportsFullscreen(); } public static void sync(int limitFramerate) { boolean limitFPS = limitFramerate > 0 && limitFramerate < 1000; - - if(limitFPS) { + + if (limitFPS) { long millis = EagRuntime.steadyTimeMillis(); long frameMillis = (1000l / limitFramerate) - (millis - lastSwap); - if(frameMillis > 0l) { + if (frameMillis > 0l) { EagUtils.sleep(frameMillis); } } - + lastSwap = EagRuntime.steadyTimeMillis(); } - public static boolean contextLost() { - return PlatformInput.contextLost(); + public static void toggleFullscreen() { + PlatformInput.toggleFullscreen(); + } + + public static void update() { + PlatformInput.update(); } public static boolean wasResized() { @@ -101,25 +123,4 @@ public class Display { return PlatformInput.wasVisualViewportResized(); } - public static boolean supportsFullscreen() { - return PlatformInput.supportsFullscreen(); - } - - public static boolean isFullscreen() { - return PlatformInput.isFullscreen(); - } - - public static void toggleFullscreen() { - PlatformInput.toggleFullscreen(); - } - - public static float getDPI() { - long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastDPIUpdate > 250l) { - lastDPIUpdate = millis; - cacheDPI = PlatformInput.getDPI(); - } - return cacheDPI; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EagRuntime.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EagRuntime.java index 9aeb060d..bb993fc3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EagRuntime.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EagRuntime.java @@ -4,9 +4,6 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @@ -22,6 +19,9 @@ import net.lax1dude.eaglercraft.v1_8.internal.IClientConfigAdapter; import net.lax1dude.eaglercraft.v1_8.internal.PlatformApplication; import net.lax1dude.eaglercraft.v1_8.internal.PlatformAssets; import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; @@ -31,14 +31,15 @@ import net.lax1dude.eaglercraft.v1_8.update.UpdateService; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,11 +54,23 @@ public class EagRuntime { private static String userAgentString = null; private static EnumPlatformOS operatingSystem = null; private static EnumPlatformANGLE angleBackend = null; - - public static String getVersion() { - return "EagRuntimeX 1.0"; + + public static ByteBuffer allocateByteBuffer(int length) { + return PlatformRuntime.allocateByteBuffer(length); } - + + public static FloatBuffer allocateFloatBuffer(int length) { + return PlatformRuntime.allocateFloatBuffer(length); + } + + public static IntBuffer allocateIntBuffer(int length) { + return PlatformRuntime.allocateIntBuffer(length); + } + + public static void clearFileChooserResult() { + PlatformApplication.clearFileChooserResult(); + } + public static void create() { logger.info("Version: {}", getVersion()); PlatformRuntime.create(); @@ -74,132 +87,18 @@ public class EagRuntime { PlatformRuntime.postCreate(); } - public static void destroy() { - PlatformRuntime.destroy(); + public static String currentThreadName() { + return PlatformRuntime.currentThreadName(); } - public static EnumPlatformType getPlatformType() { - return PlatformRuntime.getPlatformType(); - } - - public static EnumPlatformAgent getPlatformAgent() { - return userAgent; - } - - public static String getUserAgentString() { - return userAgentString; - } - - public static EnumPlatformOS getPlatformOS() { - return operatingSystem; - } - - public static EnumPlatformANGLE getPlatformANGLE() { - return angleBackend; - } - - public static ByteBuffer allocateByteBuffer(int length) { - return PlatformRuntime.allocateByteBuffer(length); - } - - public static IntBuffer allocateIntBuffer(int length) { - return PlatformRuntime.allocateIntBuffer(length); - } - - public static FloatBuffer allocateFloatBuffer(int length) { - return PlatformRuntime.allocateFloatBuffer(length); - } - - public static void freeByteBuffer(ByteBuffer floatBuffer) { - PlatformRuntime.freeByteBuffer(floatBuffer); - } - - public static void freeIntBuffer(IntBuffer intBuffer) { - PlatformRuntime.freeIntBuffer(intBuffer); - } - - public static void freeFloatBuffer(FloatBuffer byteBuffer) { - PlatformRuntime.freeFloatBuffer(byteBuffer); - } - - public static boolean getResourceExists(String path) { - return PlatformAssets.getResourceExists(path); - } - - public static byte[] getResourceBytes(String path) { - return PlatformAssets.getResourceBytes(path); - } - - public static byte[] getRequiredResourceBytes(String path) { - byte[] ret = PlatformAssets.getResourceBytes(path); - if(ret == null) { - throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); - } - return ret; - } - - public static InputStream getResourceStream(String path) { - byte[] b = PlatformAssets.getResourceBytes(path); - if(b != null) { - return new EaglerInputStream(b); - }else { - return null; - } - } - - public static InputStream getRequiredResourceStream(String path) { - byte[] ret = PlatformAssets.getResourceBytes(path); - if(ret == null) { - throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); - } - return new EaglerInputStream(ret); - } - - public static String getResourceString(String path) { - byte[] bytes = PlatformAssets.getResourceBytes(path); - return bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null; - } - - public static String getRequiredResourceString(String path) { - byte[] ret = PlatformAssets.getResourceBytes(path); - if(ret == null) { - throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); - } - return new String(ret, StandardCharsets.UTF_8); - } - - public static List getResourceLines(String path) { - byte[] bytes = PlatformAssets.getResourceBytes(path); - if(bytes != null) { - List ret = new ArrayList<>(); - try { - BufferedReader rd = new BufferedReader(new InputStreamReader(new EaglerInputStream(bytes), StandardCharsets.UTF_8)); - String s; - while((s = rd.readLine()) != null) { - ret.add(s); - } - }catch(IOException ex) { - // ?? - return null; - } - return ret; - }else { - return null; - } - } - - public static List getRequiredResourceLines(String path) { - List ret = getResourceLines(path); - if(ret == null) { - throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); - } - return ret; + public static void debugPrintStackTrace(Throwable t) { + exceptionLogger.error(t); } public static void debugPrintStackTraceToSTDERR(Throwable t) { debugPrintStackTraceToSTDERR0("", t); Throwable c = t.getCause(); - while(c != null) { + while (c != null) { debugPrintStackTraceToSTDERR0("Caused by: ", c); c = c.getCause(); } @@ -207,72 +106,51 @@ public class EagRuntime { private static void debugPrintStackTraceToSTDERR0(String pfx, Throwable t) { System.err.println(pfx + t.toString()); - if(!PlatformRuntime.printJSExceptionIfBrowser(t)) { + if (!PlatformRuntime.printJSExceptionIfBrowser(t)) { getStackTrace(t, (s) -> { System.err.println(" at " + s); }); } } - - public static void getStackTrace(Throwable t, Consumer ret) { - PlatformRuntime.getStackTrace(t, ret); + + public static void destroy() { + PlatformRuntime.destroy(); } - - public static String[] getStackTraceElements(Throwable t) { - List lst = new ArrayList<>(); - PlatformRuntime.getStackTrace(t, (s) -> { - lst.add(s); - }); - return lst.toArray(new String[lst.size()]); + + public static void displayFileChooser(String mime, String ext) { + PlatformApplication.displayFileChooser(mime, ext); } - - public static String getStackTrace(Throwable t) { - StringBuilder sb = new StringBuilder(); - getStackTrace0(t, sb); - Throwable c = t.getCause(); - while(c != null) { - sb.append("\nCaused by: "); - getStackTrace0(c, sb); - c = c.getCause(); - } - return sb.toString(); + + public static void downloadFileWithName(String fileName, byte[] fileContents) { + PlatformApplication.downloadFileWithName(fileName, fileContents); } - - private static void getStackTrace0(Throwable t, StringBuilder sb) { - sb.append(t.toString()); - getStackTrace(t, (s) -> { - sb.append('\n').append(" at ").append(s); - }); - } - - public static void debugPrintStackTrace(Throwable t) { - exceptionLogger.error(t); - } - + public static void dumpStack() { try { throw new Exception("Stack Trace"); - }catch(Exception ex) { + } catch (Exception ex) { exceptionLogger.error(ex); } } - + public static void exit() { PlatformRuntime.exit(); } - /** - * Note to skids: This doesn't do anything in javascript runtime! - */ - public static long maxMemory() { - return PlatformRuntime.maxMemory(); + public static boolean fileChooserHasResult() { + return PlatformApplication.fileChooserHasResult(); } - /** - * Note to skids: This doesn't do anything in javascript runtime! - */ - public static long totalMemory() { - return PlatformRuntime.totalMemory(); + public static void freeByteBuffer(ByteBuffer floatBuffer) { + PlatformRuntime.freeByteBuffer(floatBuffer); + } + + public static void freeFloatBuffer(FloatBuffer byteBuffer) { + PlatformRuntime.freeFloatBuffer(byteBuffer); + } + + public static void freeIntBuffer(IntBuffer intBuffer) { + PlatformRuntime.freeIntBuffer(intBuffer); } /** @@ -282,72 +160,185 @@ public class EagRuntime { return PlatformRuntime.freeMemory(); } - public static boolean requireSSL() { - return ssl; - } - - public static boolean isOfflineDownloadURL() { - return offlineDownloadURL; - } - - public static void showPopup(String msg) { - PlatformApplication.showPopup(msg); - } - public static String getClipboard() { return PlatformApplication.getClipboard(); } - public static void setClipboard(String text) { - PlatformApplication.setClipboard(text); - } - - public static void openLink(String url) { - PlatformApplication.openLink(url); - } - - public static void displayFileChooser(String mime, String ext) { - PlatformApplication.displayFileChooser(mime, ext); - } - - public static boolean fileChooserHasResult() { - return PlatformApplication.fileChooserHasResult(); - } - - public static FileChooserResult getFileChooserResult() { - return PlatformApplication.getFileChooserResult(); - } - - public static void clearFileChooserResult() { - PlatformApplication.clearFileChooserResult(); - } - - public static void setStorage(String name, byte[] data) { - PlatformApplication.setLocalStorage(name, data); - } - - public static byte[] getStorage(String data) { - return PlatformApplication.getLocalStorage(data); - } - public static IClientConfigAdapter getConfiguration() { return PlatformRuntime.getClientConfigAdapter(); } + public static FileChooserResult getFileChooserResult() { + return PlatformApplication.getFileChooserResult(); + } + + public static EnumPlatformAgent getPlatformAgent() { + return userAgent; + } + + public static EnumPlatformANGLE getPlatformANGLE() { + return angleBackend; + } + + public static EnumPlatformOS getPlatformOS() { + return operatingSystem; + } + + public static EnumPlatformType getPlatformType() { + return PlatformRuntime.getPlatformType(); + } + + public static byte[] getRequiredResourceBytes(String path) { + byte[] ret = PlatformAssets.getResourceBytes(path); + if (ret == null) { + throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); + } + return ret; + } + + public static List getRequiredResourceLines(String path) { + List ret = getResourceLines(path); + if (ret == null) { + throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); + } + return ret; + } + + public static InputStream getRequiredResourceStream(String path) { + byte[] ret = PlatformAssets.getResourceBytes(path); + if (ret == null) { + throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); + } + return new EaglerInputStream(ret); + } + + public static String getRequiredResourceString(String path) { + byte[] ret = PlatformAssets.getResourceBytes(path); + if (ret == null) { + throw new EaglerMissingResourceException("Could not load required resource from EPK: " + path); + } + return new String(ret, StandardCharsets.UTF_8); + } + + public static byte[] getResourceBytes(String path) { + return PlatformAssets.getResourceBytes(path); + } + + public static boolean getResourceExists(String path) { + return PlatformAssets.getResourceExists(path); + } + + public static List getResourceLines(String path) { + byte[] bytes = PlatformAssets.getResourceBytes(path); + if (bytes != null) { + List ret = new ArrayList<>(); + try { + BufferedReader rd = new BufferedReader( + new InputStreamReader(new EaglerInputStream(bytes), StandardCharsets.UTF_8)); + String s; + while ((s = rd.readLine()) != null) { + ret.add(s); + } + } catch (IOException ex) { + // ?? + return null; + } + return ret; + } else { + return null; + } + } + + public static InputStream getResourceStream(String path) { + byte[] b = PlatformAssets.getResourceBytes(path); + if (b != null) { + return new EaglerInputStream(b); + } else { + return null; + } + } + + public static String getResourceString(String path) { + byte[] bytes = PlatformAssets.getResourceBytes(path); + return bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null; + } + + public static String getStackTrace(Throwable t) { + StringBuilder sb = new StringBuilder(); + getStackTrace0(t, sb); + Throwable c = t.getCause(); + while (c != null) { + sb.append("\nCaused by: "); + getStackTrace0(c, sb); + c = c.getCause(); + } + return sb.toString(); + } + + public static void getStackTrace(Throwable t, Consumer ret) { + PlatformRuntime.getStackTrace(t, ret); + } + + private static void getStackTrace0(Throwable t, StringBuilder sb) { + sb.append(t.toString()); + getStackTrace(t, (s) -> { + sb.append('\n').append(" at ").append(s); + }); + } + + public static String[] getStackTraceElements(Throwable t) { + List lst = new ArrayList<>(); + PlatformRuntime.getStackTrace(t, (s) -> { + lst.add(s); + }); + return lst.toArray(new String[lst.size()]); + } + + public static byte[] getStorage(String data) { + return PlatformApplication.getLocalStorage(data); + } + + public static String getUserAgentString() { + return userAgentString; + } + + public static String getVersion() { + return "EagRuntimeX 1.0"; + } + + public static void immediateContinue() { + PlatformRuntime.immediateContinue(); + } + + public static boolean isOfflineDownloadURL() { + return offlineDownloadURL; + } + + /** + * Note to skids: This doesn't do anything in javascript runtime! + */ + public static long maxMemory() { + return PlatformRuntime.maxMemory(); + } + + public static long nanoTime() { + return PlatformRuntime.nanoTime(); + } + public static void openCreditsPopup(String text) { PlatformApplication.openCreditsPopup(text); } - public static void downloadFileWithName(String fileName, byte[] fileContents) { - PlatformApplication.downloadFileWithName(fileName, fileContents); + public static void openLink(String url) { + PlatformApplication.openLink(url); } - public static String currentThreadName() { - return PlatformRuntime.currentThreadName(); + public static boolean requireSSL() { + return ssl; } - public static void showDebugConsole() { - PlatformApplication.showDebugConsole(); + public static void setClipboard(String text) { + PlatformApplication.setClipboard(text); } public static void setDisplayBootMenuNextRefresh(boolean en) { @@ -358,16 +349,27 @@ public class EagRuntime { PlatformApplication.setMCServerWindowGlobal(url); } + public static void setStorage(String name, byte[] data) { + PlatformApplication.setLocalStorage(name, data); + } + + public static void showDebugConsole() { + PlatformApplication.showDebugConsole(); + } + + public static void showPopup(String msg) { + PlatformApplication.showPopup(msg); + } + public static long steadyTimeMillis() { return PlatformRuntime.steadyTimeMillis(); } - public static long nanoTime() { - return PlatformRuntime.nanoTime(); - } - - public static void immediateContinue() { - PlatformRuntime.immediateContinue(); + /** + * Note to skids: This doesn't do anything in javascript runtime! + */ + public static long totalMemory() { + return PlatformRuntime.totalMemory(); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EagUtils.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EagUtils.java index 808aa6c5..980e7653 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EagUtils.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EagUtils.java @@ -8,26 +8,43 @@ import java.util.regex.Pattern; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EagUtils { - + private static final String hex = "0123456789ABCDEF"; public static final Pattern splitPattern = Pattern.compile("(\\r\\n|\\n|\\r)"); - + + public static int decodeHex(CharSequence num) { + int ret = 0; + for (int i = 0, l = num.length(); i < l; ++i) { + ret = ret << 4; + int v = hex.indexOf(num.charAt(i)); + if (v >= 0) { + ret |= v; + } + } + return ret; + } + + public static int decodeHexByte(CharSequence str, int off) { + return str.length() < off + 2 ? decodeHex(str.subSequence(off, 2)) : 0; + } + public static String hexString(int value, int digits) { String ret = ""; - for(int i = 0, l = digits << 2; i < l; i += 4) { + for (int i = 0, l = digits << 2; i < l; i += 4) { ret = hex.charAt((value >> i) & 0xF) + ret; } return ret; @@ -36,55 +53,10 @@ public class EagUtils { public static String[] linesArray(String input) { return splitPattern.split(input); } - + public static List linesList(String input) { return Arrays.asList(splitPattern.split(input)); } - - public static int decodeHex(CharSequence num) { - int ret = 0; - for(int i = 0, l = num.length(); i < l; ++i) { - ret = ret << 4; - int v = hex.indexOf(num.charAt(i)); - if(v >= 0) { - ret |= v; - } - } - return ret; - } - - public static int decodeHexByte(CharSequence str, int off) { - return str.length() < off + 2 ? decodeHex(str.subSequence(off, 2)) : 0; - } - - public static void sleep(long millis) { - try { - Thread.sleep(millis); - }catch(InterruptedException ex) { - } - } - - public static String toASCIIEagler(String str) { - char[] ascii = new char[str.length()]; - for(int i = 0; i < ascii.length; ++i) { - int c = (int)str.charAt(i); - if(c < 32 || c > 126) { - ascii[i] = '_'; - }else { - ascii[i] = (char)c; - } - } - return new String(ascii); - } - - public static void validateASCIIEagler(String str) { - for(int i = 0, l = str.length(); i < l; ++i) { - int c = (int)str.charAt(i); - if(c < 32 || c > 126) { - throw new IllegalArgumentException("invalid ascii"); - } - } - } public static EaglercraftUUID makeClientBrandUUID(String name) { return EaglercraftUUID.nameUUIDFromBytes(("EaglercraftXClient:" + name).getBytes(StandardCharsets.UTF_8)); @@ -94,4 +66,33 @@ public class EagUtils { return EaglercraftUUID.nameUUIDFromBytes(("EaglercraftXClientOld:" + name).getBytes(StandardCharsets.UTF_8)); } + public static void sleep(long millis) { + try { + Thread.sleep(millis); + } catch (InterruptedException ex) { + } + } + + public static String toASCIIEagler(String str) { + char[] ascii = new char[str.length()]; + for (int i = 0; i < ascii.length; ++i) { + int c = (int) str.charAt(i); + if (c < 32 || c > 126) { + ascii[i] = '_'; + } else { + ascii[i] = (char) c; + } + } + return new String(ascii); + } + + public static void validateASCIIEagler(String str) { + for (int i = 0, l = str.length(); i < l; ++i) { + int c = (int) str.charAt(i); + if (c < 32 || c > 126) { + throw new IllegalArgumentException("invalid ascii"); + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerInputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerInputStream.java index bf1466cc..47f6aa40 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerInputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerInputStream.java @@ -9,36 +9,113 @@ import java.util.Arrays; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerInputStream extends InputStream { + public static byte[] inputStreamToBytes(InputStream is) throws IOException { + try { + if (is instanceof EaglerInputStream) { + return ((EaglerInputStream) is).getAsArray(); + } else if (is instanceof ByteArrayInputStream) { + byte[] ret = new byte[is.available()]; + is.read(ret); + return ret; + } else { + EaglerOutputStream os = new EaglerOutputStream(1024); + byte[] buf = new byte[1024]; + int i; + while ((i = is.read(buf)) != -1) { + os.write(buf, 0, i); + } + return os.toByteArray(); + } + } finally { + is.close(); + } + } + + public static byte[] inputStreamToBytesQuiet(InputStream is) { + if (is == null) { + return null; + } + try { + return inputStreamToBytes(is); + } catch (IOException ex) { + return null; + } + } + protected byte buf[]; protected int pos; + protected int mark = 0; + protected int count; + public EaglerInputStream(byte buf[], int offset, int length) { + this.buf = buf; + this.pos = offset; + this.count = Math.min(offset + length, buf.length); + this.mark = offset; + } + public EaglerInputStream(byte[] buf) { this.buf = buf; this.pos = 0; this.count = buf.length; } - public EaglerInputStream(byte buf[], int offset, int length) { - this.buf = buf; - this.pos = offset; - this.count = Math.min(offset + length, buf.length); - this.mark = offset; + public int available() { + return count - pos; + } + + public boolean canUseArrayDirectly() { + return pos == 0 && count == buf.length; + } + + public void close() throws IOException { + } + + public byte[] getAsArray() { + if (pos == 0 && count == buf.length) { + return buf; + } else { + byte[] ret = new byte[count]; + System.arraycopy(buf, pos, ret, 0, count); + return ret; + } + } + + public int getCount() { + return count; + } + + public int getMark() { + return mark; + } + + public int getPosition() { + return pos; + } + + public void mark(int readAheadLimit) { + mark = pos; + } + + public boolean markSupported() { + return true; } public int read() { @@ -73,22 +150,8 @@ public class EaglerInputStream extends InputStream { return n == -1 ? 0 : n; } - public long transferTo(OutputStream out) throws IOException { - int len = count - pos; - out.write(buf, pos, len); - pos = count; - return len; - } - - public static byte[] inputStreamToBytesQuiet(InputStream is) { - if (is == null) { - return null; - } - try { - return inputStreamToBytes(is); - } catch (IOException ex) { - return null; - } + public void reset() { + pos = mark; } public long skip(long n) { @@ -101,71 +164,11 @@ public class EaglerInputStream extends InputStream { return k; } - public int available() { - return count - pos; - } - - public boolean markSupported() { - return true; - } - - public void mark(int readAheadLimit) { - mark = pos; - } - - public void reset() { - pos = mark; - } - - public void close() throws IOException { - } - - public static byte[] inputStreamToBytes(InputStream is) throws IOException { - try { - if (is instanceof EaglerInputStream) { - return ((EaglerInputStream) is).getAsArray(); - } else if (is instanceof ByteArrayInputStream) { - byte[] ret = new byte[is.available()]; - is.read(ret); - return ret; - } else { - EaglerOutputStream os = new EaglerOutputStream(1024); - byte[] buf = new byte[1024]; - int i; - while ((i = is.read(buf)) != -1) { - os.write(buf, 0, i); - } - return os.toByteArray(); - } - }finally { - is.close(); - } - } - - public byte[] getAsArray() { - if (pos == 0 && count == buf.length) { - return buf; - } else { - byte[] ret = new byte[count]; - System.arraycopy(buf, pos, ret, 0, count); - return ret; - } - } - - public boolean canUseArrayDirectly() { - return pos == 0 && count == buf.length; - } - - public int getPosition() { - return pos; - } - - public int getMark() { - return mark; - } - - public int getCount() { - return count; + public long transferTo(OutputStream out) throws IOException { + int len = count - pos; + out.write(buf, pos, len); + pos = count; + return len; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerOutputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerOutputStream.java index 3f4864bc..cfd40b80 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerOutputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerOutputStream.java @@ -7,14 +7,15 @@ import java.util.Arrays; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,9 @@ public class EaglerOutputStream extends OutputStream { buf = new byte[size]; } + public void close() throws IOException { + } + private void ensureCapacity(int minCapacity) { if (buf.length < minCapacity) { minCapacity = Math.max(minCapacity, buf.length * 3 / 2); @@ -42,34 +46,10 @@ public class EaglerOutputStream extends OutputStream { } } - public void write(int b) { - ensureCapacity(count + 1); - buf[count] = (byte) b; - count += 1; - } - - public void write(byte b[], int off, int len) { - ensureCapacity(count + len); - System.arraycopy(b, off, buf, count, len); - count += len; - } - - public void writeBytes(byte b[]) { - write(b, 0, b.length); - } - - public void writeTo(OutputStream out) throws IOException { - out.write(buf, 0, count); - } - public void reset() { count = 0; } - public byte[] toByteArray() { - return Arrays.copyOf(buf, count); - } - public int size() { return count; } @@ -79,6 +59,27 @@ public class EaglerOutputStream extends OutputStream { count += num; } - public void close() throws IOException { + public byte[] toByteArray() { + return Arrays.copyOf(buf, count); + } + + public void write(byte b[], int off, int len) { + ensureCapacity(count + len); + System.arraycopy(b, off, buf, count, len); + count += len; + } + + public void write(int b) { + ensureCapacity(count + 1); + buf[count] = (byte) b; + count += 1; + } + + public void writeBytes(byte b[]) { + write(b, 0, b.length); + } + + public void writeTo(OutputStream out) throws IOException { + out.write(buf, 0, count); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerXBungeeVersion.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerXBungeeVersion.java index d1bd0fdf..343692b5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerXBungeeVersion.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerXBungeeVersion.java @@ -5,14 +5,15 @@ import org.json.JSONObject; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,14 +28,16 @@ public class EaglerXBungeeVersion { private static String pluginButton = null; private static String pluginFilename = null; - public static void initialize() { - String pluginVersionJson = EagRuntime.getRequiredResourceString("plugin_version.json"); - JSONObject json = new JSONObject(pluginVersionJson); - pluginName = json.getString("pluginName"); - pluginVersion = json.getString("pluginVersion"); - pluginVersionLong = getVersionAsLong(pluginVersion); - pluginButton = json.getString("pluginButton"); - pluginFilename = json.getString("pluginFilename"); + public static String getPluginButton() { + return pluginButton; + } + + public static byte[] getPluginDownload() { + return EagRuntime.getRequiredResourceBytes(pluginFileEPK); + } + + public static String getPluginFilename() { + return pluginFilename; } public static String getPluginName() { @@ -49,42 +52,40 @@ public class EaglerXBungeeVersion { return pluginVersionLong; } - public static String getPluginButton() { - return pluginButton; - } - - public static String getPluginFilename() { - return pluginFilename; - } - public static long getVersionAsLong(String vers) { try { String[] verz = vers.split("\\."); long ret = 0; long div = 1000000000000l; - for(int i = 0; i < verz.length; ++i) { + for (int i = 0; i < verz.length; ++i) { ret += div * Long.parseLong(verz[i]); div /= 10000l; } return ret; - }catch(Throwable t) { + } catch (Throwable t) { return -1l; } } - public static byte[] getPluginDownload() { - return EagRuntime.getRequiredResourceBytes(pluginFileEPK); - } - - public static void startPluginDownload() { - EagRuntime.downloadFileWithName(pluginFilename, getPluginDownload()); + public static void initialize() { + String pluginVersionJson = EagRuntime.getRequiredResourceString("plugin_version.json"); + JSONObject json = new JSONObject(pluginVersionJson); + pluginName = json.getString("pluginName"); + pluginVersion = json.getString("pluginVersion"); + pluginVersionLong = getVersionAsLong(pluginVersion); + pluginButton = json.getString("pluginButton"); + pluginFilename = json.getString("pluginFilename"); } public static boolean isUpdateToPluginAvailable(String brand, String vers) { - if(pluginVersionLong == -1l || !pluginName.equals(brand)) { + if (pluginVersionLong == -1l || !pluginName.equals(brand)) { return false; } long verz = getVersionAsLong(vers); return verz != -1l && verz < pluginVersionLong; } + + public static void startPluginDownload() { + EagRuntime.downloadFileWithName(pluginFilename, getPluginDownload()); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerZLIB.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerZLIB.java index 839a481a..a32f1427 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerZLIB.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglerZLIB.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,17 +27,17 @@ public class EaglerZLIB { public static OutputStream newDeflaterOutputStream(OutputStream os) throws IOException { return PlatformRuntime.newDeflaterOutputStream(os); } - - public static OutputStream newGZIPOutputStream(OutputStream os) throws IOException { - return PlatformRuntime.newGZIPOutputStream(os); - } - - public static InputStream newInflaterInputStream(InputStream is) throws IOException { - return PlatformRuntime.newInflaterInputStream(is); - } - + public static InputStream newGZIPInputStream(InputStream is) throws IOException { return PlatformRuntime.newGZIPInputStream(is); } + public static OutputStream newGZIPOutputStream(OutputStream os) throws IOException { + return PlatformRuntime.newGZIPOutputStream(os); + } + + public static InputStream newInflaterInputStream(InputStream is) throws IOException { + return PlatformRuntime.newInflaterInputStream(is); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftRandom.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftRandom.java index 93484c5d..4225f8e7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftRandom.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftRandom.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,21 +25,31 @@ public class EaglercraftRandom { private static final long mask = (1L << 48) - 1; private static final double DOUBLE_UNIT = 0x1.0p-53; + + private static long initialScramble(long seed) { + return (seed ^ multiplier) & mask; + } + private long seed = 69; + private final boolean enableScramble; + private double nextNextGaussian; + + private boolean haveNextNextGaussian = false; + public EaglercraftRandom() { this(PlatformRuntime.randomSeed()); } - public EaglercraftRandom(long seed) { - this(seed, true); - } - public EaglercraftRandom(boolean scramble) { this(PlatformRuntime.randomSeed(), scramble); } + public EaglercraftRandom(long seed) { + this(seed, true); + } + /** * Older versions of EaglercraftX (and Eaglercraft) are missing the * "initialScramble" function from their setSeed function, which was what caused @@ -50,19 +61,6 @@ public class EaglercraftRandom { setSeed(seed); } - private static long initialScramble(long seed) { - return (seed ^ multiplier) & mask; - } - - public void setSeed(long yeed) { - if(enableScramble) { - seed = initialScramble(yeed); - }else { - seed = yeed; - } - haveNextNextGaussian = true; - } - public boolean isScramble() { return enableScramble; } @@ -72,12 +70,43 @@ public class EaglercraftRandom { return (int) (seed >>> (48 - bits)); } + public boolean nextBoolean() { + return next(1) != 0; + } + public void nextBytes(byte[] bytes) { for (int i = 0, len = bytes.length; i < len;) for (int rnd = nextInt(), n = Math.min(len - i, Integer.SIZE / Byte.SIZE); n-- > 0; rnd >>= Byte.SIZE) bytes[i++] = (byte) rnd; } + public double nextDouble() { + return (((long) (next(26)) << 27) + next(27)) * DOUBLE_UNIT; + } + + public float nextFloat() { + return next(24) / ((float) (1 << 24)); + } + + public double nextGaussian() { + // See Knuth, ACP, Section 3.4.1 Algorithm C. + if (haveNextNextGaussian) { + haveNextNextGaussian = false; + return nextNextGaussian; + } else { + double v1, v2, s; + do { + v1 = 2 * nextDouble() - 1; // between -1 and 1 + v2 = 2 * nextDouble() - 1; // between -1 and 1 + s = v1 * v1 + v2 * v2; + } while (s >= 1 || s == 0); + double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s); + nextNextGaussian = v2 * multiplier; + haveNextNextGaussian = true; + return v1 * multiplier; + } + } + public int nextInt() { return next(32); } @@ -98,37 +127,12 @@ public class EaglercraftRandom { return ((long) (next(32)) << 32) + next(32); } - public boolean nextBoolean() { - return next(1) != 0; - } - - public float nextFloat() { - return next(24) / ((float) (1 << 24)); - } - - public double nextDouble() { - return (((long) (next(26)) << 27) + next(27)) * DOUBLE_UNIT; - } - - private double nextNextGaussian; - private boolean haveNextNextGaussian = false; - - public double nextGaussian() { - // See Knuth, ACP, Section 3.4.1 Algorithm C. - if (haveNextNextGaussian) { - haveNextNextGaussian = false; - return nextNextGaussian; + public void setSeed(long yeed) { + if (enableScramble) { + seed = initialScramble(yeed); } else { - double v1, v2, s; - do { - v1 = 2 * nextDouble() - 1; // between -1 and 1 - v2 = 2 * nextDouble() - 1; // between -1 and 1 - s = v1 * v1 + v2 * v2; - } while (s >= 1 || s == 0); - double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s) / s); - nextNextGaussian = v2 * multiplier; - haveNextNextGaussian = true; - return v1 * multiplier; + seed = yeed; } + haveNextNextGaussian = true; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftSoundManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftSoundManager.java index 86fff434..1021ff30 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftSoundManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftSoundManager.java @@ -27,41 +27,42 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglercraftSoundManager { - + protected static class ActiveSoundEvent { protected final EaglercraftSoundManager manager; - + protected final ISound soundInstance; protected final SoundCategory soundCategory; protected final SoundPoolEntry soundConfig; protected IAudioHandle soundHandle; - + protected float activeX; protected float activeY; protected float activeZ; - + protected float activePitch; protected float activeGain; - + protected int repeatCounter = 0; protected boolean paused = false; - - protected ActiveSoundEvent(EaglercraftSoundManager manager, ISound soundInstance, - SoundCategory soundCategory, SoundPoolEntry soundConfig, IAudioHandle soundHandle) { + + protected ActiveSoundEvent(EaglercraftSoundManager manager, ISound soundInstance, SoundCategory soundCategory, + SoundPoolEntry soundConfig, IAudioHandle soundHandle) { this.manager = manager; this.soundInstance = soundInstance; this.soundCategory = soundCategory; @@ -73,271 +74,155 @@ public class EaglercraftSoundManager { this.activePitch = soundInstance.getPitch(); this.activeGain = soundInstance.getVolume(); } - + protected void updateLocation() { float x = soundInstance.getXPosF(); float y = soundInstance.getYPosF(); float z = soundInstance.getZPosF(); float pitch = soundInstance.getPitch(); float gain = soundInstance.getVolume(); - if(x != activeX || y != activeY || z != activeZ) { + if (x != activeX || y != activeY || z != activeZ) { soundHandle.move(x, y, z); activeX = x; activeY = y; activeZ = z; } - if(pitch != activePitch) { - soundHandle.pitch(MathHelper.clamp_float(pitch * (float)soundConfig.getPitch(), 0.5f, 2.0f)); + if (pitch != activePitch) { + soundHandle.pitch(MathHelper.clamp_float(pitch * (float) soundConfig.getPitch(), 0.5f, 2.0f)); activePitch = pitch; } - if(gain != activeGain) { - float attenuatedGain = gain * manager.categoryVolumes[SoundCategory.MASTER.getCategoryId()] * - (soundCategory == SoundCategory.MASTER ? 1.0f : manager.categoryVolumes[soundCategory.getCategoryId()]) - * (float)soundConfig.getVolume(); + if (gain != activeGain) { + float attenuatedGain = gain * manager.categoryVolumes[SoundCategory.MASTER.getCategoryId()] + * (soundCategory == SoundCategory.MASTER ? 1.0f + : manager.categoryVolumes[soundCategory.getCategoryId()]) + * (float) soundConfig.getVolume(); soundHandle.gain(MathHelper.clamp_float(attenuatedGain, 0.0f, 1.0f)); activeGain = gain; } } - + } - + protected static class WaitingSoundEvent { - + protected final ISound playSound; protected int playTicks; protected boolean paused = false; - + private WaitingSoundEvent(ISound playSound, int playTicks) { this.playSound = playSound; this.playTicks = playTicks; } - + } - + private static final Logger logger = LogManager.getLogger("SoundManager"); - + private final GameSettings settings; private final SoundHandler handler; private final float[] categoryVolumes; private final List activeSounds; private final List queuedSounds; + private final PlatformAudio.IAudioCacheLoader browserResourcePackLoader = filename -> { + try { + return EaglerInputStream.inputStreamToBytesQuiet(Minecraft.getMinecraft().getResourceManager() + .getResource(new ResourceLocation(filename)).getInputStream()); + } catch (Throwable t) { + return null; + } + }; + public EaglercraftSoundManager(GameSettings settings, SoundHandler handler) { this.settings = settings; this.handler = handler; - categoryVolumes = new float[] { - settings.getSoundLevel(SoundCategory.MASTER), settings.getSoundLevel(SoundCategory.MUSIC), - settings.getSoundLevel(SoundCategory.RECORDS), settings.getSoundLevel(SoundCategory.WEATHER), - settings.getSoundLevel(SoundCategory.BLOCKS), settings.getSoundLevel(SoundCategory.MOBS), - settings.getSoundLevel(SoundCategory.ANIMALS), settings.getSoundLevel(SoundCategory.PLAYERS), - settings.getSoundLevel(SoundCategory.AMBIENT) - }; + categoryVolumes = new float[] { settings.getSoundLevel(SoundCategory.MASTER), + settings.getSoundLevel(SoundCategory.MUSIC), settings.getSoundLevel(SoundCategory.RECORDS), + settings.getSoundLevel(SoundCategory.WEATHER), settings.getSoundLevel(SoundCategory.BLOCKS), + settings.getSoundLevel(SoundCategory.MOBS), settings.getSoundLevel(SoundCategory.ANIMALS), + settings.getSoundLevel(SoundCategory.PLAYERS), settings.getSoundLevel(SoundCategory.AMBIENT) }; activeSounds = new LinkedList<>(); queuedSounds = new LinkedList<>(); } - public void unloadSoundSystem() { - // handled by PlatformApplication - } - - public void reloadSoundSystem() { - PlatformAudio.flushAudioCache(); - } - - public void setSoundCategoryVolume(SoundCategory category, float volume) { - categoryVolumes[category.getCategoryId()] = volume; - Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { - ActiveSoundEvent evt = soundItr.next(); - if((category == SoundCategory.MASTER || evt.soundCategory == category) - && !evt.soundHandle.shouldFree()) { - float newVolume = (evt.activeGain = evt.soundInstance.getVolume()) * categoryVolumes[SoundCategory.MASTER.getCategoryId()] * - (evt.soundCategory == SoundCategory.MASTER ? 1.0f : categoryVolumes[evt.soundCategory.getCategoryId()]) - * (float)evt.soundConfig.getVolume(); - newVolume = MathHelper.clamp_float(newVolume, 0.0f, 1.0f); - if(newVolume > 0.0f) { - evt.soundHandle.gain(newVolume); - }else { - evt.soundHandle.end(); - soundItr.remove(); - } - } - } - } - - public void stopAllSounds() { - Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { - ActiveSoundEvent evt = soundItr.next(); - if(!evt.soundHandle.shouldFree()) { - evt.soundHandle.end(); - } - } - activeSounds.clear(); - } - - public void pauseAllSounds() { - Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { - ActiveSoundEvent evt = soundItr.next(); - if(!evt.soundHandle.shouldFree()) { - evt.soundHandle.pause(true); - evt.paused = true; - } - } - Iterator soundItr2 = queuedSounds.iterator(); - while(soundItr2.hasNext()) { - soundItr2.next().paused = true; - } - } - - public void resumeAllSounds() { - Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { - ActiveSoundEvent evt = soundItr.next(); - if(!evt.soundHandle.shouldFree()) { - evt.soundHandle.pause(false); - evt.paused = false; - } - } - Iterator soundItr2 = queuedSounds.iterator(); - while(soundItr2.hasNext()) { - soundItr2.next().paused = false; - } - } - - public void updateAllSounds() { - Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { - ActiveSoundEvent evt = soundItr.next(); - if(!evt.paused && (evt.soundInstance instanceof ITickable)) { - boolean destroy = false; - try { - ((ITickable)evt.soundInstance).update(); - if ((evt.soundInstance instanceof ITickableSound) - && ((ITickableSound) evt.soundInstance).isDonePlaying()) { - destroy = true; - } - }catch(Throwable t) { - logger.error("Error ticking sound: {}", t.toString()); - logger.error(t); - destroy = true; - } - if(destroy) { - if(!evt.soundHandle.shouldFree()) { - evt.soundHandle.end(); - } - soundItr.remove(); - } - } - if(evt.soundHandle.shouldFree()) { - if(evt.soundInstance.canRepeat()) { - if(!evt.paused && ++evt.repeatCounter > evt.soundInstance.getRepeatDelay()) { - evt.repeatCounter = 0; - evt.updateLocation(); - evt.soundHandle.restart(); - } - }else { - soundItr.remove(); - } - }else { - evt.updateLocation(); - } - } - Iterator soundItr2 = queuedSounds.iterator(); - while(soundItr2.hasNext()) { - WaitingSoundEvent evt = soundItr2.next(); - if(!evt.paused && --evt.playTicks <= 0) { - soundItr2.remove(); - playSound(evt.playSound); - } - } - PlatformAudio.clearAudioCache(); - } - public boolean isSoundPlaying(ISound sound) { Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { + while (soundItr.hasNext()) { ActiveSoundEvent evt = soundItr.next(); - if(evt.soundInstance == sound) { + if (evt.soundInstance == sound) { return !evt.soundHandle.shouldFree(); } } return false; } - - public void stopSound(ISound sound) { + + public void pauseAllSounds() { Iterator soundItr = activeSounds.iterator(); - while(soundItr.hasNext()) { + while (soundItr.hasNext()) { ActiveSoundEvent evt = soundItr.next(); - if(evt.soundInstance == sound) { - if(!evt.soundHandle.shouldFree()) { - evt.soundHandle.end(); - soundItr.remove(); - return; - } + if (!evt.soundHandle.shouldFree()) { + evt.soundHandle.pause(true); + evt.paused = true; } } Iterator soundItr2 = queuedSounds.iterator(); - while(soundItr2.hasNext()) { - if(soundItr2.next().playSound == sound) { - soundItr2.remove(); - } + while (soundItr2.hasNext()) { + soundItr2.next().paused = true; } } - private final PlatformAudio.IAudioCacheLoader browserResourcePackLoader = filename -> { - try { - return EaglerInputStream.inputStreamToBytesQuiet(Minecraft.getMinecraft().getResourceManager() - .getResource(new ResourceLocation(filename)).getInputStream()); - }catch(Throwable t) { - return null; - } - }; + public void playDelayedSound(ISound sound, int delay) { + queuedSounds.add(new WaitingSoundEvent(sound, delay)); + } public void playSound(ISound sound) { - if(!PlatformAudio.available()) { + if (!PlatformAudio.available()) { return; } - if(sound != null && categoryVolumes[SoundCategory.MASTER.getCategoryId()] > 0.0f) { + if (sound != null && categoryVolumes[SoundCategory.MASTER.getCategoryId()] > 0.0f) { SoundEventAccessorComposite accessor = handler.getSound(sound.getSoundLocation()); - if(accessor == null) { + if (accessor == null) { logger.warn("Unable to play unknown soundEvent(1): {}", sound.getSoundLocation().toString()); - }else { + } else { SoundPoolEntry etr = accessor.cloneEntry(); if (etr == SoundHandler.missing_sound) { logger.warn("Unable to play empty soundEvent(2): {}", etr.getSoundPoolEntryLocation().toString()); - }else { + } else { ResourceLocation lc = etr.getSoundPoolEntryLocation(); IAudioResource trk; - if(EagRuntime.getPlatformType() != EnumPlatformType.DESKTOP) { - trk = PlatformAudio.loadAudioDataNew(lc.toString(), !etr.isStreamingSound(), browserResourcePackLoader); - }else { + if (EagRuntime.getPlatformType() != EnumPlatformType.DESKTOP) { + trk = PlatformAudio.loadAudioDataNew(lc.toString(), !etr.isStreamingSound(), + browserResourcePackLoader); + } else { trk = PlatformAudio.loadAudioData( - "/assets/" + lc.getResourceDomain() + "/" + lc.getResourcePath(), !etr.isStreamingSound()); + "/assets/" + lc.getResourceDomain() + "/" + lc.getResourcePath(), + !etr.isStreamingSound()); } - if(trk == null) { + if (trk == null) { logger.warn("Unable to play unknown soundEvent(3): {}", sound.getSoundLocation().toString()); - }else { - - ActiveSoundEvent newSound = new ActiveSoundEvent(this, sound, accessor.getSoundCategory(), etr, null); + } else { + + ActiveSoundEvent newSound = new ActiveSoundEvent(this, sound, accessor.getSoundCategory(), etr, + null); + + float pitch = MathHelper.clamp_float(newSound.activePitch * (float) etr.getPitch(), 0.5f, 2.0f); + float attenuatedGain = newSound.activeGain + * categoryVolumes[SoundCategory.MASTER.getCategoryId()] + * (accessor.getSoundCategory() == SoundCategory.MASTER ? 1.0f + : categoryVolumes[accessor.getSoundCategory().getCategoryId()]) + * (float) etr.getVolume(); - float pitch = MathHelper.clamp_float(newSound.activePitch * (float)etr.getPitch(), 0.5f, 2.0f); - float attenuatedGain = newSound.activeGain * categoryVolumes[SoundCategory.MASTER.getCategoryId()] * - (accessor.getSoundCategory() == SoundCategory.MASTER ? 1.0f : - categoryVolumes[accessor.getSoundCategory().getCategoryId()]) * (float)etr.getVolume(); - AttenuationType tp = sound.getAttenuationType(); - if(tp == AttenuationType.LINEAR) { + if (tp == AttenuationType.LINEAR) { newSound.soundHandle = PlatformAudio.beginPlayback(trk, newSound.activeX, newSound.activeY, newSound.activeZ, attenuatedGain, pitch); - }else { + } else { newSound.soundHandle = PlatformAudio.beginPlaybackStatic(trk, attenuatedGain, pitch); } - - if(newSound.soundHandle == null) { + + if (newSound.soundHandle == null) { logger.error("Unable to play soundEvent(4): {}", sound.getSoundLocation().toString()); - }else { + } else { activeSounds.add(newSound); } } @@ -345,28 +230,150 @@ public class EaglercraftSoundManager { } } } - - public void playDelayedSound(ISound sound, int delay) { - queuedSounds.add(new WaitingSoundEvent(sound, delay)); + + public void reloadSoundSystem() { + PlatformAudio.flushAudioCache(); } - + + public void resumeAllSounds() { + Iterator soundItr = activeSounds.iterator(); + while (soundItr.hasNext()) { + ActiveSoundEvent evt = soundItr.next(); + if (!evt.soundHandle.shouldFree()) { + evt.soundHandle.pause(false); + evt.paused = false; + } + } + Iterator soundItr2 = queuedSounds.iterator(); + while (soundItr2.hasNext()) { + soundItr2.next().paused = false; + } + } + public void setListener(EntityPlayer player, float partialTicks) { - if(!PlatformAudio.available()) { + if (!PlatformAudio.available()) { return; } - if(player != null) { + if (player != null) { try { float f = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * partialTicks; float f1 = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * partialTicks; double d0 = player.prevPosX + (player.posX - player.prevPosX) * (double) partialTicks; - double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double) partialTicks + (double) player.getEyeHeight(); + double d1 = player.prevPosY + (player.posY - player.prevPosY) * (double) partialTicks + + (double) player.getEyeHeight(); double d2 = player.prevPosZ + (player.posZ - player.prevPosZ) * (double) partialTicks; - PlatformAudio.setListener((float)d0, (float)d1, (float)d2, f, f1); - }catch(Throwable t) { + PlatformAudio.setListener((float) d0, (float) d1, (float) d2, f, f1); + } catch (Throwable t) { // eaglercraft 1.5.2 had Infinity/NaN crashes for this function which // couldn't be resolved via if statement checks in the above variables } } } - + + public void setSoundCategoryVolume(SoundCategory category, float volume) { + categoryVolumes[category.getCategoryId()] = volume; + Iterator soundItr = activeSounds.iterator(); + while (soundItr.hasNext()) { + ActiveSoundEvent evt = soundItr.next(); + if ((category == SoundCategory.MASTER || evt.soundCategory == category) && !evt.soundHandle.shouldFree()) { + float newVolume = (evt.activeGain = evt.soundInstance.getVolume()) + * categoryVolumes[SoundCategory.MASTER.getCategoryId()] + * (evt.soundCategory == SoundCategory.MASTER ? 1.0f + : categoryVolumes[evt.soundCategory.getCategoryId()]) + * (float) evt.soundConfig.getVolume(); + newVolume = MathHelper.clamp_float(newVolume, 0.0f, 1.0f); + if (newVolume > 0.0f) { + evt.soundHandle.gain(newVolume); + } else { + evt.soundHandle.end(); + soundItr.remove(); + } + } + } + } + + public void stopAllSounds() { + Iterator soundItr = activeSounds.iterator(); + while (soundItr.hasNext()) { + ActiveSoundEvent evt = soundItr.next(); + if (!evt.soundHandle.shouldFree()) { + evt.soundHandle.end(); + } + } + activeSounds.clear(); + } + + public void stopSound(ISound sound) { + Iterator soundItr = activeSounds.iterator(); + while (soundItr.hasNext()) { + ActiveSoundEvent evt = soundItr.next(); + if (evt.soundInstance == sound) { + if (!evt.soundHandle.shouldFree()) { + evt.soundHandle.end(); + soundItr.remove(); + return; + } + } + } + Iterator soundItr2 = queuedSounds.iterator(); + while (soundItr2.hasNext()) { + if (soundItr2.next().playSound == sound) { + soundItr2.remove(); + } + } + } + + public void unloadSoundSystem() { + // handled by PlatformApplication + } + + public void updateAllSounds() { + Iterator soundItr = activeSounds.iterator(); + while (soundItr.hasNext()) { + ActiveSoundEvent evt = soundItr.next(); + if (!evt.paused && (evt.soundInstance instanceof ITickable)) { + boolean destroy = false; + try { + ((ITickable) evt.soundInstance).update(); + if ((evt.soundInstance instanceof ITickableSound) + && ((ITickableSound) evt.soundInstance).isDonePlaying()) { + destroy = true; + } + } catch (Throwable t) { + logger.error("Error ticking sound: {}", t.toString()); + logger.error(t); + destroy = true; + } + if (destroy) { + if (!evt.soundHandle.shouldFree()) { + evt.soundHandle.end(); + } + soundItr.remove(); + } + } + if (evt.soundHandle.shouldFree()) { + if (evt.soundInstance.canRepeat()) { + if (!evt.paused && ++evt.repeatCounter > evt.soundInstance.getRepeatDelay()) { + evt.repeatCounter = 0; + evt.updateLocation(); + evt.soundHandle.restart(); + } + } else { + soundItr.remove(); + } + } else { + evt.updateLocation(); + } + } + Iterator soundItr2 = queuedSounds.iterator(); + while (soundItr2.hasNext()) { + WaitingSoundEvent evt = soundItr2.next(); + if (!evt.paused && --evt.playTicks <= 0) { + soundItr2.remove(); + playSound(evt.playSound); + } + } + PlatformAudio.clearAudioCache(); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftUUID.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftUUID.java index 8e75d8bb..2136ce43 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftUUID.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftUUID.java @@ -5,172 +5,28 @@ import net.lax1dude.eaglercraft.v1_8.crypto.MD5Digest; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglercraftUUID implements Comparable { - public final long msb; - public final long lsb; - private int hash = 0; - private boolean hasHash; - - public EaglercraftUUID(long msb, long lsb) { - this.msb = msb; - this.lsb = lsb; - } - - public EaglercraftUUID(byte[] uuid) { - long msb = 0; - long lsb = 0; - for (int i = 0; i < 8; i++) - msb = (msb << 8) | (uuid[i] & 0xff); - for (int i = 8; i < 16; i++) - lsb = (lsb << 8) | (uuid[i] & 0xff); - this.msb = msb; - this.lsb = lsb; - } - - public EaglercraftUUID(String uuid) { - String[] components = uuid.split("-"); - if (components.length != 5) - throw new IllegalArgumentException("Invalid UUID string: " + uuid); - for (int i = 0; i < 5; i++) - components[i] = "0x" + components[i]; - - long mostSigBits = Long.decode(components[0]).longValue(); - mostSigBits <<= 16; - mostSigBits |= Long.decode(components[1]).longValue(); - mostSigBits <<= 16; - mostSigBits |= Long.decode(components[2]).longValue(); - - long leastSigBits = Long.decode(components[3]).longValue(); - leastSigBits <<= 48; - leastSigBits |= Long.decode(components[4]).longValue(); - - this.msb = mostSigBits; - this.lsb = leastSigBits; - } - - private static byte long7(long x) { - return (byte) (x >> 56); - } - - private static byte long6(long x) { - return (byte) (x >> 48); - } - - private static byte long5(long x) { - return (byte) (x >> 40); - } - - private static byte long4(long x) { - return (byte) (x >> 32); - } - - private static byte long3(long x) { - return (byte) (x >> 24); - } - - private static byte long2(long x) { - return (byte) (x >> 16); - } - - private static byte long1(long x) { - return (byte) (x >> 8); - } - - private static byte long0(long x) { - return (byte) (x); - } - - public byte[] getBytes() { - byte[] ret = new byte[16]; - ret[0] = long7(msb); - ret[1] = long6(msb); - ret[2] = long5(msb); - ret[3] = long4(msb); - ret[4] = long3(msb); - ret[5] = long2(msb); - ret[6] = long1(msb); - ret[7] = long0(msb); - ret[8] = long7(lsb); - ret[9] = long6(lsb); - ret[10] = long5(lsb); - ret[11] = long4(lsb); - ret[12] = long3(lsb); - ret[13] = long2(lsb); - ret[14] = long1(lsb); - ret[15] = long0(lsb); - return ret; - } - - @Override - public String toString() { - return (digits(msb >> 32, 8) + "-" + digits(msb >> 16, 4) + "-" + digits(msb, 4) + "-" + digits(lsb >> 48, 4) - + "-" + digits(lsb, 12)); - } + private static final String HEX = "0123456789ABCDEF"; private static String digits(long val, int digits) { long hi = 1L << (digits * 4); return Long.toHexString(hi | (val & (hi - 1))).substring(1); } - @Override - public int hashCode() { - if(hash == 0 && !hasHash) { - long hilo = msb ^ lsb; - hash = ((int) (hilo >> 32)) ^ (int) hilo; - hasHash = true; - } - return hash; - } - - @Override - public boolean equals(Object o) { - if(!(o instanceof EaglercraftUUID)) return false; - EaglercraftUUID oo = (EaglercraftUUID)o; - return (hasHash && oo.hasHash) - ? (hash == oo.hash && msb == oo.msb && lsb == oo.lsb) - : (msb == oo.msb && lsb == oo.lsb); - } - - public long getMostSignificantBits() { - return msb; - } - - public long getLeastSignificantBits() { - return lsb; - } - - private static final String HEX = "0123456789ABCDEF"; - - private static int nibbleValue(char c) { - int v = HEX.indexOf(Character.toUpperCase(c)); - if (v == -1) { - return 0; - } else { - return v; - } - } - - private static long parse4Nibbles(String name, int pos) { - int ch1 = nibbleValue(name.charAt(pos)); - int ch2 = nibbleValue(name.charAt(pos + 1)); - int ch3 = nibbleValue(name.charAt(pos + 2)); - int ch4 = nibbleValue(name.charAt(pos + 3)); - return (ch1 << 12) | (ch2 << 8) | (ch3 << 4) | ch4; - } - public static EaglercraftUUID fromString(String name) { if (name.length() == 36) { char ch1 = name.charAt(8); @@ -223,6 +79,38 @@ public class EaglercraftUUID implements Comparable { return new EaglercraftUUID(mostSigBits, leastSigBits); } + private static byte long0(long x) { + return (byte) (x); + } + + private static byte long1(long x) { + return (byte) (x >> 8); + } + + private static byte long2(long x) { + return (byte) (x >> 16); + } + + private static byte long3(long x) { + return (byte) (x >> 24); + } + + private static byte long4(long x) { + return (byte) (x >> 32); + } + + private static byte long5(long x) { + return (byte) (x >> 40); + } + + private static byte long6(long x) { + return (byte) (x >> 48); + } + + private static byte long7(long x) { + return (byte) (x >> 56); + } + public static EaglercraftUUID nameUUIDFromBytes(byte[] bytes) { MD5Digest dg = new MD5Digest(); dg.update(bytes, 0, bytes.length); @@ -235,6 +123,23 @@ public class EaglercraftUUID implements Comparable { return new EaglercraftUUID(md5Bytes); } + private static int nibbleValue(char c) { + int v = HEX.indexOf(Character.toUpperCase(c)); + if (v == -1) { + return 0; + } else { + return v; + } + } + + private static long parse4Nibbles(String name, int pos) { + int ch1 = nibbleValue(name.charAt(pos)); + int ch2 = nibbleValue(name.charAt(pos + 1)); + int ch3 = nibbleValue(name.charAt(pos + 2)); + int ch4 = nibbleValue(name.charAt(pos + 3)); + return (ch1 << 12) | (ch2 << 8) | (ch3 << 4) | ch4; + } + public static EaglercraftUUID randomUUID() { byte[] randomBytes = new byte[16]; (new EaglercraftRandom()).nextBytes(randomBytes); @@ -245,10 +150,109 @@ public class EaglercraftUUID implements Comparable { return new EaglercraftUUID(randomBytes); } + public final long msb; + + public final long lsb; + + private int hash = 0; + + private boolean hasHash; + + public EaglercraftUUID(byte[] uuid) { + long msb = 0; + long lsb = 0; + for (int i = 0; i < 8; i++) + msb = (msb << 8) | (uuid[i] & 0xff); + for (int i = 8; i < 16; i++) + lsb = (lsb << 8) | (uuid[i] & 0xff); + this.msb = msb; + this.lsb = lsb; + } + + public EaglercraftUUID(long msb, long lsb) { + this.msb = msb; + this.lsb = lsb; + } + + public EaglercraftUUID(String uuid) { + String[] components = uuid.split("-"); + if (components.length != 5) + throw new IllegalArgumentException("Invalid UUID string: " + uuid); + for (int i = 0; i < 5; i++) + components[i] = "0x" + components[i]; + + long mostSigBits = Long.decode(components[0]).longValue(); + mostSigBits <<= 16; + mostSigBits |= Long.decode(components[1]).longValue(); + mostSigBits <<= 16; + mostSigBits |= Long.decode(components[2]).longValue(); + + long leastSigBits = Long.decode(components[3]).longValue(); + leastSigBits <<= 48; + leastSigBits |= Long.decode(components[4]).longValue(); + + this.msb = mostSigBits; + this.lsb = leastSigBits; + } + @Override public int compareTo(EaglercraftUUID val) { return (this.msb < val.msb ? -1 : (this.msb > val.msb ? 1 : (this.lsb < val.lsb ? -1 : (this.lsb > val.lsb ? 1 : 0)))); } + @Override + public boolean equals(Object o) { + if (!(o instanceof EaglercraftUUID)) + return false; + EaglercraftUUID oo = (EaglercraftUUID) o; + return (hasHash && oo.hasHash) ? (hash == oo.hash && msb == oo.msb && lsb == oo.lsb) + : (msb == oo.msb && lsb == oo.lsb); + } + + public byte[] getBytes() { + byte[] ret = new byte[16]; + ret[0] = long7(msb); + ret[1] = long6(msb); + ret[2] = long5(msb); + ret[3] = long4(msb); + ret[4] = long3(msb); + ret[5] = long2(msb); + ret[6] = long1(msb); + ret[7] = long0(msb); + ret[8] = long7(lsb); + ret[9] = long6(lsb); + ret[10] = long5(lsb); + ret[11] = long4(lsb); + ret[12] = long3(lsb); + ret[13] = long2(lsb); + ret[14] = long1(lsb); + ret[15] = long0(lsb); + return ret; + } + + public long getLeastSignificantBits() { + return lsb; + } + + public long getMostSignificantBits() { + return msb; + } + + @Override + public int hashCode() { + if (hash == 0 && !hasHash) { + long hilo = msb ^ lsb; + hash = ((int) (hilo >> 32)) ^ (int) hilo; + hasHash = true; + } + return hash; + } + + @Override + public String toString() { + return (digits(msb >> 32, 8) + "-" + digits(msb >> 16, 4) + "-" + digits(msb, 4) + "-" + digits(lsb >> 48, 4) + + "-" + digits(lsb, 12)); + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftVersion.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftVersion.java index 2466b22d..1c2847a7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftVersion.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EaglercraftVersion.java @@ -3,63 +3,63 @@ package net.lax1dude.eaglercraft.v1_8; import java.math.BigInteger; public class EaglercraftVersion { - - + ////////////////////////////////////////////////////////////////////// - + /// Customize these to fit your fork: - + public static final String projectForkName = "Starlike Client"; - public static final String projectForkVersion = "0.1.1"; - public static final String projectForkVendor = "SpeedSlicer & zumbiepig"; - + public static final String projectForkVersion = "0.2.0"; + public static final String projectForkVendor = "SpeedSlicer and zumbiepig"; + public static final String projectForkURL = ""; - + ////////////////////////////////////////////////////////////////////// - + public static final String projectOriginName = "EaglercraftX"; public static final String projectOriginAuthor = "lax1dude"; public static final String projectOriginRevision = "1.8"; - public static final String projectOriginVersion = "u37"; - - public static final String projectOriginURL = "https://gitlab.com/lax1dude/eaglercraftx-1.8"; // rest in peace - - - - // Updating configuration - - public static final boolean enableUpdateService = false; + public static final String projectOriginVersion = "u39"; - public static final String updateBundlePackageName = "net.lax1dude.eaglercraft.v1_8.client"; - public static final int updateBundlePackageVersionInt = 37; + public static final String projectOriginURL = "https://gitlab.com/lax1dude/eaglercraftx-1.8"; // rest in peace + + // EPK Version Identifier + + public static final String EPKVersionIdentifier = projectForkVersion; // Set to null to disable EPK version check + + // Updating configuration + + public static final boolean enableUpdateService = true; + + public static final String updateBundlePackageName = "dev.zumbiepig.starlikeclient.client"; + public static final int updateBundlePackageVersionInt = 200; // (0.2.1 would be 000201 or just 201) public static final String updateLatestLocalStorageKey = "latestUpdate_" + updateBundlePackageName; // public key modulus for official 1.8 updates - public static final BigInteger updateSignatureModulus = new BigInteger("14419476194820052109078379102436982757438300194194974078260570958862225232043861026588258585967060437391326494976080031137298500457111529693806931143421725626747051503616606418909609840275122831550688481329699012469742002429706330734797679859799085213517354399295425740214330234086361416936984593337389989505613123225737002654977194421571825036717017788527234114501215218715499682638139386636103589791643964827904791195488978835113700772208317974307363542114867750505953323167521731238542123593257269990619007858952216110012513121779359926747737258698347806747854986471035713105133999027704095451858121831297923962641"); - - - + public static final BigInteger updateSignatureModulus = new BigInteger( + "28154007251851793016096675136645490267059674193477673066016405606156842861664902840486152246081162714389866569681190683516064018400350723835699291801143446801871211423563444580124984720927762511096224794499752181575422000985856618499073349425764147909008336707018656178546729409024747183847557655756025152351818612306562908429371421145128154560905733480315537161717618356180392502066269414984054854075976130472279535788141377012879285566510859864540548496184877426481234244151342696367793929688648467759736793075080029025728010655173323780256289815694871723570008993011506495225395230611688881103726309118671731354057"); + // Client brand identification system configuration - + public static final EaglercraftUUID clientBrandUUID = EagUtils.makeClientBrandUUID(projectForkName); - public static final EaglercraftUUID legacyClientUUIDInSharedWorld = EagUtils.makeClientBrandUUIDLegacy(projectOriginName); - - + public static final EaglercraftUUID legacyClientUUIDInSharedWorld = EagUtils + .makeClientBrandUUIDLegacy(projectOriginName); + // Miscellaneous variables: public static final String mainMenuStringA = "Minecraft 1.8.8*"; - public static final String mainMenuStringB = projectOriginName + " " + - projectOriginRevision + "-" + projectOriginVersion + " ultimate"; - public static final String mainMenuStringC = ""; - public static final String mainMenuStringD = "Resources Copyright Mojang AB"; + public static final String mainMenuStringB = projectOriginName + " " + projectOriginRevision + "-" + + projectOriginVersion; + public static final String mainMenuStringC = null; + public static final String mainMenuStringD = "Copyright Mojang AB. Do not distribute!"; public static final String mainMenuStringE = projectForkName + " " + projectForkVersion; public static final String mainMenuStringF = "Made by " + projectForkVendor; - public static final String mainMenuStringG = "Collector's Edition"; - public static final String mainMenuStringH = "PBR Shaders"; + public static final String mainMenuStringG = null; + public static final String mainMenuStringH = null; public static final long demoWorldSeed = (long) "North Carolina".hashCode(); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/EncoderException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/EncoderException.java index e4ab2a2b..6527c7e9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/EncoderException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/EncoderException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -21,14 +22,14 @@ public class EncoderException extends RuntimeException { super(); } - public EncoderException(String message, Throwable cause) { - super(message, cause); - } - public EncoderException(String message) { super(message); } + public EncoderException(String message, Throwable cause) { + super(message, cause); + } + public EncoderException(Throwable cause) { super(cause); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/ExceptionUtils.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/ExceptionUtils.java index 07afb769..e16af0a0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/ExceptionUtils.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/ExceptionUtils.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -19,7 +20,7 @@ public class ExceptionUtils { public static Throwable getRootCause(Throwable exception) { Throwable t2; - while((t2 = exception.getCause()) != null) { + while ((t2 = exception.getCause()) != null) { exception = t2; } return exception; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Filesystem.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Filesystem.java index 2755d2d1..6526b8bd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Filesystem.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Filesystem.java @@ -14,58 +14,26 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Filesystem { - private static final Logger logger = LogManager.getLogger("PlatformFilesystem"); - - private static final Map openFilesystems = new HashMap<>(); - - public static IEaglerFilesystem getHandleFor(String dbName) { - FilesystemHandle handle = openFilesystems.get(dbName); - if(handle != null) { - ++handle.refCount; - return new FilesystemHandleWrapper(handle); - } - IEaglerFilesystem handleImpl = null; - if(!EagRuntime.getConfiguration().isRamdiskMode()) { - handleImpl = PlatformFilesystem.initializePersist(dbName); - } - if(handleImpl == null) { - handleImpl = new RamdiskFilesystemImpl(dbName); - } - if(handleImpl.isRamdisk()) { - logger.warn("Using RAMDisk filesystem for database \"{}\", data will not be saved to local storage!", dbName); - } - handle = new FilesystemHandle(handleImpl); - openFilesystems.put(dbName, handle); - return new FilesystemHandleWrapper(handle); - } - - public static void closeAllHandles() { - for(FilesystemHandle handle : openFilesystems.values()) { - handle.refCount = 0; - handle.handle.closeHandle(); - } - openFilesystems.clear(); - } - private static class FilesystemHandle { private final IEaglerFilesystem handle; private int refCount; - + private FilesystemHandle(IEaglerFilesystem handle) { this.handle = handle; this.refCount = 1; @@ -85,6 +53,59 @@ public class Filesystem { this.closed = false; } + @Override + public void closeHandle() { + if (!closed && handle.refCount > 0) { + closed = true; + --handle.refCount; + if (handle.refCount <= 0) { + logger.info("Releasing filesystem handle for: \"{}\"", handleImpl.getFilesystemName()); + handleImpl.closeHandle(); + openFilesystems.remove(handleImpl.getFilesystemName()); + } + } + } + + @Override + public int eaglerCopy(String pathNameOld, String pathNameNew) { + return handleImpl.eaglerCopy(pathNameOld, pathNameNew); + } + + @Override + public boolean eaglerDelete(String pathName) { + return handleImpl.eaglerDelete(pathName); + } + + @Override + public boolean eaglerExists(String pathName) { + return handleImpl.eaglerExists(pathName); + } + + @Override + public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { + handleImpl.eaglerIterate(pathName, itr, recursive); + } + + @Override + public boolean eaglerMove(String pathNameOld, String pathNameNew) { + return handleImpl.eaglerMove(pathNameOld, pathNameNew); + } + + @Override + public ByteBuffer eaglerRead(String pathName) { + return handleImpl.eaglerRead(pathName); + } + + @Override + public int eaglerSize(String pathName) { + return handleImpl.eaglerSize(pathName); + } + + @Override + public void eaglerWrite(String pathName, ByteBuffer data) { + handleImpl.eaglerWrite(pathName, data); + } + @Override public String getFilesystemName() { return handleImpl.getFilesystemName(); @@ -100,59 +121,40 @@ public class Filesystem { return handleImpl.isRamdisk(); } - @Override - public boolean eaglerDelete(String pathName) { - return handleImpl.eaglerDelete(pathName); - } + } - @Override - public ByteBuffer eaglerRead(String pathName) { - return handleImpl.eaglerRead(pathName); - } + private static final Logger logger = LogManager.getLogger("PlatformFilesystem"); - @Override - public void eaglerWrite(String pathName, ByteBuffer data) { - handleImpl.eaglerWrite(pathName, data); - } + private static final Map openFilesystems = new HashMap<>(); - @Override - public boolean eaglerExists(String pathName) { - return handleImpl.eaglerExists(pathName); + public static void closeAllHandles() { + for (FilesystemHandle handle : openFilesystems.values()) { + handle.refCount = 0; + handle.handle.closeHandle(); } + openFilesystems.clear(); + } - @Override - public boolean eaglerMove(String pathNameOld, String pathNameNew) { - return handleImpl.eaglerMove(pathNameOld, pathNameNew); + public static IEaglerFilesystem getHandleFor(String dbName) { + FilesystemHandle handle = openFilesystems.get(dbName); + if (handle != null) { + ++handle.refCount; + return new FilesystemHandleWrapper(handle); } - - @Override - public int eaglerCopy(String pathNameOld, String pathNameNew) { - return handleImpl.eaglerCopy(pathNameOld, pathNameNew); + IEaglerFilesystem handleImpl = null; + if (!EagRuntime.getConfiguration().isRamdiskMode()) { + handleImpl = PlatformFilesystem.initializePersist(dbName); } - - @Override - public int eaglerSize(String pathName) { - return handleImpl.eaglerSize(pathName); + if (handleImpl == null) { + handleImpl = new RamdiskFilesystemImpl(dbName); } - - @Override - public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { - handleImpl.eaglerIterate(pathName, itr, recursive); + if (handleImpl.isRamdisk()) { + logger.warn("Using RAMDisk filesystem for database \"{}\", data will not be saved to local storage!", + dbName); } - - @Override - public void closeHandle() { - if(!closed && handle.refCount > 0) { - closed = true; - --handle.refCount; - if(handle.refCount <= 0) { - logger.info("Releasing filesystem handle for: \"{}\"", handleImpl.getFilesystemName()); - handleImpl.closeHandle(); - openFilesystems.remove(handleImpl.getFilesystemName()); - } - } - } - + handle = new FilesystemHandle(handleImpl); + openFilesystems.put(dbName, handle); + return new FilesystemHandleWrapper(handle); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Gamepad.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Gamepad.java index 2c90683c..ee1681d3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Gamepad.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Gamepad.java @@ -9,24 +9,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Gamepad { - private static final boolean[] buttonsLastState = new boolean[24]; - private static final List buttonEvents = new LinkedList<>(); - private static VirtualButtonEvent currentVEvent = null; - private static class VirtualButtonEvent { private final int button; @@ -39,65 +36,13 @@ public class Gamepad { } - public static int getValidDeviceCount() { - return PlatformInput.gamepadGetValidDeviceCount(); - } + private static final boolean[] buttonsLastState = new boolean[24]; + private static final List buttonEvents = new LinkedList<>(); - public static String getDeviceName(int deviceId) { - return PlatformInput.gamepadGetDeviceName(deviceId); - } + private static VirtualButtonEvent currentVEvent = null; - public static void setSelectedDevice(int deviceId) { - PlatformInput.gamepadSetSelectedDevice(deviceId); - } - - public static void update() { - PlatformInput.gamepadUpdate(); - if(isValid()) { - for(int i = 0; i < buttonsLastState.length; ++i) { - boolean b = PlatformInput.gamepadGetButtonState(i); - if(b != buttonsLastState[i]) { - buttonsLastState[i] = b; - buttonEvents.add(new VirtualButtonEvent(i, b)); - if(buttonEvents.size() > 64) { - buttonEvents.remove(0); - } - } - } - }else { - for(int i = 0; i < buttonsLastState.length; ++i) { - buttonsLastState[i] = false; - } - } - } - - public static boolean next() { - currentVEvent = null; - return !buttonEvents.isEmpty() && (currentVEvent = buttonEvents.remove(0)) != null; - } - - public static int getEventButton() { - return currentVEvent != null ? currentVEvent.button : -1; - } - - public static boolean getEventButtonState() { - return currentVEvent != null ? currentVEvent.state : false; - } - - public static boolean isValid() { - return PlatformInput.gamepadIsValid(); - } - - public static String getName() { - return PlatformInput.gamepadGetName(); - } - - public static boolean getButtonState(int button) { - return PlatformInput.gamepadGetButtonState(button); - } - - public static String getButtonName(int button) { - return GamepadConstants.getButtonName(button); + public static void clearEventBuffer() { + buttonEvents.clear(); } public static float getAxis(int axis) { @@ -108,8 +53,65 @@ public class Gamepad { return GamepadConstants.getAxisName(button); } - public static void clearEventBuffer() { - buttonEvents.clear(); + public static String getButtonName(int button) { + return GamepadConstants.getButtonName(button); + } + + public static boolean getButtonState(int button) { + return PlatformInput.gamepadGetButtonState(button); + } + + public static String getDeviceName(int deviceId) { + return PlatformInput.gamepadGetDeviceName(deviceId); + } + + public static int getEventButton() { + return currentVEvent != null ? currentVEvent.button : -1; + } + + public static boolean getEventButtonState() { + return currentVEvent != null ? currentVEvent.state : false; + } + + public static String getName() { + return PlatformInput.gamepadGetName(); + } + + public static int getValidDeviceCount() { + return PlatformInput.gamepadGetValidDeviceCount(); + } + + public static boolean isValid() { + return PlatformInput.gamepadIsValid(); + } + + public static boolean next() { + currentVEvent = null; + return !buttonEvents.isEmpty() && (currentVEvent = buttonEvents.remove(0)) != null; + } + + public static void setSelectedDevice(int deviceId) { + PlatformInput.gamepadSetSelectedDevice(deviceId); + } + + public static void update() { + PlatformInput.gamepadUpdate(); + if (isValid()) { + for (int i = 0; i < buttonsLastState.length; ++i) { + boolean b = PlatformInput.gamepadGetButtonState(i); + if (b != buttonsLastState[i]) { + buttonsLastState[i] = b; + buttonEvents.add(new VirtualButtonEvent(i, b)); + if (buttonEvents.size() > 64) { + buttonEvents.remove(0); + } + } + } + } else { + for (int i = 0; i < buttonsLastState.length; ++i) { + buttonsLastState[i] = false; + } + } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/HFormatter.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/HFormatter.java index f4a0167e..c3a12956 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/HFormatter.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/HFormatter.java @@ -396,43 +396,6 @@ import java.util.UnknownFormatConversionException; */ public final class HFormatter implements Closeable, Flushable { - public static class MissingFormatArgumentException extends IllegalArgumentException { - - public MissingFormatArgumentException() { - } - - public MissingFormatArgumentException(String s) { - super(s); - } - - } - - public static class DuplicateFormatFlagsException extends IllegalArgumentException { - - public DuplicateFormatFlagsException() { - } - - public DuplicateFormatFlagsException(String s) { - super(s); - } - - } - - public static class IllegalFormatWidthException extends IllegalArgumentException { - - public IllegalFormatWidthException() { - } - - public IllegalFormatWidthException(String s) { - super(s); - } - - public IllegalFormatWidthException(int i) { - super(Integer.toString(i)); - } - - } - /** * The enumeration giving the available styles for formatting very large decimal * numbers. @@ -448,1689 +411,25 @@ public final class HFormatter implements Closeable, Flushable { DECIMAL_FLOAT } - private Appendable out; - - private Locale locale; - - private boolean closed = false; - - private IOException lastIOException; - - /** - * Constructs a {@code Formatter}. - * - * The output is written to a {@code StringBuilder} which can be acquired by - * invoking {@link #out()} and whose content can be obtained by calling - * {@code toString()}. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - */ - public HFormatter() { - this(new StringBuilder(), Locale.getDefault()); - } - - /** - * Constructs a {@code Formatter} whose output will be written to the specified - * {@code Appendable}. - * - * The locale for the {@code Formatter} is the default {@code Locale}. - * - * @param a the output destination of the {@code Formatter}. If {@code a} is - * {@code null}, then a {@code StringBuilder} will be used. - */ - public HFormatter(Appendable a) { - this(a, Locale.getDefault()); - } - - /** - * Constructs a {@code Formatter} with the specified {@code Locale}. - * - * The output is written to a {@code StringBuilder} which can be acquired by - * invoking {@link #out()} and whose content can be obtained by calling - * {@code toString()}. - * - * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is - * {@code null}, then no localization will be used. - */ - public HFormatter(Locale l) { - this(new StringBuilder(), l); - } - - /** - * Constructs a {@code Formatter} with the specified {@code Locale} and whose - * output will be written to the specified {@code Appendable}. - * - * @param a the output destination of the {@code Formatter}. If {@code a} is - * {@code null}, then a {@code StringBuilder} will be used. - * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is - * {@code null}, then no localization will be used. - */ - public HFormatter(Appendable a, Locale l) { - if (null == a) { - out = new StringBuilder(); - } else { - out = a; - } - locale = l; - } - - /** - * Constructs a {@code Formatter} whose output is written to the specified file. - * - * The charset of the {@code Formatter} is the default charset. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param fileName the filename of the file that is used as the output - * destination for the {@code Formatter}. The file will be - * truncated to zero size if the file exists, or else a new file - * will be created. The output of the {@code Formatter} is - * buffered. - * @throws FileNotFoundException if the filename does not denote a normal and - * writable file, or if a new file cannot be - * created, or if any error arises when opening or - * creating the file. - * @throws SecurityException if there is a {@code SecurityManager} in place - * which denies permission to write to the file in - * {@code checkWrite(file.getPath())}. - */ - public HFormatter(String fileName) throws FileNotFoundException { - this(new File(fileName)); - - } - - /** - * Constructs a {@code Formatter} whose output is written to the specified file. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param fileName the filename of the file that is used as the output - * destination for the {@code Formatter}. The file will be - * truncated to zero size if the file exists, or else a new file - * will be created. The output of the {@code Formatter} is - * buffered. - * @param csn the name of the charset for the {@code Formatter}. - * @throws FileNotFoundException if the filename does not denote a normal - * and writable file, or if a new file - * cannot be created, or if any error - * arises when opening or creating the - * file. - * @throws SecurityException if there is a {@code SecurityManager} in - * place which denies permission to write - * to the file in - * {@code checkWrite(file.getPath())}. - * @throws UnsupportedEncodingException if the charset with the specified name - * is not supported. - */ - public HFormatter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { - this(new File(fileName), csn); - } - - /** - * Constructs a {@code Formatter} with the given {@code Locale} and charset, and - * whose output is written to the specified file. - * - * @param fileName the filename of the file that is used as the output - * destination for the {@code Formatter}. The file will be - * truncated to zero size if the file exists, or else a new file - * will be created. The output of the {@code Formatter} is - * buffered. - * @param csn the name of the charset for the {@code Formatter}. - * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is - * {@code null}, then no localization will be used. - * @throws FileNotFoundException if the filename does not denote a normal - * and writable file, or if a new file - * cannot be created, or if any error - * arises when opening or creating the - * file. - * @throws SecurityException if there is a {@code SecurityManager} in - * place which denies permission to write - * to the file in - * {@code checkWrite(file.getPath())}. - * @throws UnsupportedEncodingException if the charset with the specified name - * is not supported. - */ - public HFormatter(String fileName, String csn, Locale l) - throws FileNotFoundException, UnsupportedEncodingException { - - this(new File(fileName), csn, l); - } - - /** - * Constructs a {@code Formatter} whose output is written to the specified - * {@code File}. - * - * The charset of the {@code Formatter} is the default charset. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param file the {@code File} that is used as the output destination for the - * {@code Formatter}. The {@code File} will be truncated to zero - * size if the {@code File} exists, or else a new {@code File} will - * be created. The output of the {@code Formatter} is buffered. - * @throws FileNotFoundException if the {@code File} is not a normal and - * writable {@code File}, or if a new {@code File} - * cannot be created, or if any error rises when - * opening or creating the {@code File}. - * @throws SecurityException if there is a {@code SecurityManager} in place - * which denies permission to write to the - * {@code File} in - * {@code checkWrite(file.getPath())}. - */ - public HFormatter(File file) throws FileNotFoundException { - this(new FileOutputStream(file)); - } - - /** - * Constructs a {@code Formatter} with the given charset, and whose output is - * written to the specified {@code File}. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param file the {@code File} that is used as the output destination for the - * {@code Formatter}. The {@code File} will be truncated to zero - * size if the {@code File} exists, or else a new {@code File} will - * be created. The output of the {@code Formatter} is buffered. - * @param csn the name of the charset for the {@code Formatter}. - * @throws FileNotFoundException if the {@code File} is not a normal and - * writable {@code File}, or if a new - * {@code File} cannot be created, or if - * any error rises when opening or creating - * the {@code File}. - * @throws SecurityException if there is a {@code SecurityManager} in - * place which denies permission to write - * to the {@code File} in - * {@code checkWrite(file.getPath())}. - * @throws UnsupportedEncodingException if the charset with the specified name - * is not supported. - */ - public HFormatter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { - this(file, csn, Locale.getDefault()); - } - - /** - * Constructs a {@code Formatter} with the given {@code Locale} and charset, and - * whose output is written to the specified {@code File}. - * - * @param file the {@code File} that is used as the output destination for the - * {@code Formatter}. The {@code File} will be truncated to zero - * size if the {@code File} exists, or else a new {@code File} will - * be created. The output of the {@code Formatter} is buffered. - * @param csn the name of the charset for the {@code Formatter}. - * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is - * {@code null}, then no localization will be used. - * @throws FileNotFoundException if the {@code File} is not a normal and - * writable {@code File}, or if a new - * {@code File} cannot be created, or if - * any error rises when opening or creating - * the {@code File}. - * @throws SecurityException if there is a {@code SecurityManager} in - * place which denies permission to write - * to the {@code File} in - * {@code checkWrite(file.getPath())}. - * @throws UnsupportedEncodingException if the charset with the specified name - * is not supported. - */ - public HFormatter(File file, String csn, Locale l) throws FileNotFoundException, UnsupportedEncodingException { - FileOutputStream fout = null; - try { - fout = new FileOutputStream(file); - OutputStreamWriter writer = new OutputStreamWriter(fout, csn); - out = new BufferedWriter(writer); - } catch (RuntimeException e) { - closeOutputStream(fout); - throw e; - } catch (UnsupportedEncodingException e) { - closeOutputStream(fout); - throw e; - } - - locale = l; - } - - /** - * Constructs a {@code Formatter} whose output is written to the specified - * {@code OutputStream}. - * - * The charset of the {@code Formatter} is the default charset. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param os the stream to be used as the destination of the {@code Formatter}. - */ - public HFormatter(OutputStream os) { - OutputStreamWriter writer = new OutputStreamWriter(os, Charset.defaultCharset()); - out = new BufferedWriter(writer); - locale = Locale.getDefault(); - } - - /** - * Constructs a {@code Formatter} with the given charset, and whose output is - * written to the specified {@code OutputStream}. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param os the stream to be used as the destination of the {@code Formatter}. - * @param csn the name of the charset for the {@code Formatter}. - * @throws UnsupportedEncodingException if the charset with the specified name - * is not supported. - */ - public HFormatter(OutputStream os, String csn) throws UnsupportedEncodingException { - - this(os, csn, Locale.getDefault()); - } - - /** - * Constructs a {@code Formatter} with the given {@code Locale} and charset, and - * whose output is written to the specified {@code OutputStream}. - * - * @param os the stream to be used as the destination of the {@code Formatter}. - * @param csn the name of the charset for the {@code Formatter}. - * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is - * {@code null}, then no localization will be used. - * @throws UnsupportedEncodingException if the charset with the specified name - * is not supported. - */ - public HFormatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException { - - OutputStreamWriter writer = new OutputStreamWriter(os, csn); - out = new BufferedWriter(writer); - - locale = l; - } - - /** - * Constructs a {@code Formatter} whose output is written to the specified - * {@code PrintStream}. - * - * The charset of the {@code Formatter} is the default charset. - * - * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. - * - * @param ps the {@code PrintStream} used as destination of the - * {@code Formatter}. If {@code ps} is {@code null}, then a - * {@code NullPointerException} will be raised. - */ - public HFormatter(PrintStream ps) { - if (null == ps) { - throw new NullPointerException(); - } - out = ps; - locale = Locale.getDefault(); - } - - private void checkClosed() { - if (closed) { - throw new IllegalStateException("Formatter is closed"); - } - } - - /** - * Returns the {@code Locale} of the {@code Formatter}. - * - * @return the {@code Locale} for the {@code Formatter} or {@code null} for no - * {@code Locale}. - * @throws FormatterClosedException if the {@code Formatter} has been closed. - */ - public Locale locale() { - checkClosed(); - return locale; - } - - /** - * Returns the output destination of the {@code Formatter}. - * - * @return the output destination of the {@code Formatter}. - * @throws FormatterClosedException if the {@code Formatter} has been closed. - */ - public Appendable out() { - checkClosed(); - return out; - } - - /** - * Returns the content by calling the {@code toString()} method of the output - * destination. - * - * @return the content by calling the {@code toString()} method of the output - * destination. - * @throws FormatterClosedException if the {@code Formatter} has been closed. - */ - @Override - public String toString() { - checkClosed(); - return out.toString(); - } - - /** - * Flushes the {@code Formatter}. If the output destination is - * {@link Flushable}, then the method {@code flush()} will be called on that - * destination. - * - * @throws FormatterClosedException if the {@code Formatter} has been closed. - */ - public void flush() { - checkClosed(); - if (out instanceof Flushable) { - try { - ((Flushable) out).flush(); - } catch (IOException e) { - lastIOException = e; - } - } - } - - /** - * Closes the {@code Formatter}. If the output destination is {@link Closeable}, - * then the method {@code close()} will be called on that destination. - * - * If the {@code Formatter} has been closed, then calling the this method will - * have no effect. - * - * Any method but the {@link #ioException()} that is called after the - * {@code Formatter} has been closed will raise a - * {@code FormatterClosedException}. - */ - public void close() { - closed = true; - try { - if (out instanceof Closeable) { - ((Closeable) out).close(); - } - } catch (IOException e) { - - lastIOException = e; - } - } - - /** - * Returns the last {@code IOException} thrown by the {@code Formatter}'s output - * destination. If the {@code append()} method of the destination does not throw - * {@code IOException}s, the {@code ioException()} method will always return - * {@code null}. - * - * @return the last {@code IOException} thrown by the {@code Formatter}'s output - * destination. - */ - public IOException ioException() { - return lastIOException; - } - - /** - * Writes a formatted string to the output destination of the {@code Formatter}. - * - * @param format a format string. - * @param args the arguments list used in the {@code format()} method. If - * there are more arguments than those specified by the format - * string, then the additional arguments are ignored. - * @return this {@code Formatter}. - * @throws IllegalFormatException if the format string is illegal or - * incompatible with the arguments, or if fewer - * arguments are sent than those required by - * the format string, or any other illegal - * situation. - * @throws FormatterClosedException if the {@code Formatter} has been closed. - */ - public HFormatter format(String format, Object... args) { - return format(locale, format, args); - } - - /** - * Writes a formatted string to the output destination of the {@code Formatter}. - * - * @param l the {@code Locale} used in the method. If {@code locale} is - * {@code null}, then no localization will be applied. This - * parameter does not influence the {@code Locale} specified - * during construction. - * @param format a format string. - * @param args the arguments list used in the {@code format()} method. If - * there are more arguments than those specified by the format - * string, then the additional arguments are ignored. - * @return this {@code Formatter}. - * @throws IllegalFormatException if the format string is illegal or - * incompatible with the arguments, or if fewer - * arguments are sent than those required by - * the format string, or any other illegal - * situation. - * @throws FormatterClosedException if the {@code Formatter} has been closed. - */ - public HFormatter format(Locale l, String format, Object... args) { - checkClosed(); - CharBuffer formatBuffer = CharBuffer.wrap(format); - ParserStateMachine parser = new ParserStateMachine(formatBuffer); - Transformer transformer = new Transformer(this, l); - - int currentObjectIndex = 0; - Object lastArgument = null; - boolean hasLastArgumentSet = false; - while (formatBuffer.hasRemaining()) { - parser.reset(); - FormatToken token = parser.getNextFormatToken(); - String result; - String plainText = token.getPlainText(); - if (token.getConversionType() == (char) FormatToken.UNSET) { - result = plainText; - } else { - plainText = plainText.substring(0, plainText.indexOf('%')); - Object argument = null; - if (token.requireArgument()) { - int index = token.getArgIndex() == FormatToken.UNSET ? currentObjectIndex++ : token.getArgIndex(); - argument = getArgument(args, index, token, lastArgument, hasLastArgumentSet); - lastArgument = argument; - hasLastArgumentSet = true; - } - result = transformer.transform(token, argument); - result = (null == result ? plainText : plainText + result); - } - // if output is made by formattable callback - if (null != result) { - try { - out.append(result); - } catch (IOException e) { - lastIOException = e; - } - } - } - return this; - } - - private Object getArgument(Object[] args, int index, FormatToken token, Object lastArgument, - boolean hasLastArgumentSet) { - if (index == FormatToken.LAST_ARGUMENT_INDEX && !hasLastArgumentSet) { - throw new MissingFormatArgumentException("<"); //$NON-NLS-1$ - } - - if (null == args) { - return null; - } - - if (index >= args.length) { - throw new MissingFormatArgumentException(token.getPlainText()); - } - - if (index == FormatToken.LAST_ARGUMENT_INDEX) { - return lastArgument; - } - - return args[index]; - } - - private static void closeOutputStream(OutputStream os) { - if (null == os) { - return; - } - try { - os.close(); - - } catch (IOException e) { - // silently - } - } - - /* - * Information about the format string of a specified argument, which includes - * the conversion type, flags, width, precision and the argument index as well - * as the plainText that contains the whole format string used as the result for - * output if necessary. Besides, the string for flags is recorded to construct - * corresponding FormatExceptions if necessary. - */ - private static class FormatToken { - - static final int LAST_ARGUMENT_INDEX = -2; - - static final int UNSET = -1; - - static final int FLAGS_UNSET = 0; - - static final int DEFAULT_PRECISION = 6; - - static final int FLAG_MINUS = 1; - - static final int FLAG_SHARP = 1 << 1; - - static final int FLAG_ADD = 1 << 2; - - static final int FLAG_SPACE = 1 << 3; - - static final int FLAG_ZERO = 1 << 4; - - static final int FLAG_COMMA = 1 << 5; - - static final int FLAG_PARENTHESIS = 1 << 6; - - private static final int FLAGT_TYPE_COUNT = 6; - - private int formatStringStartIndex; - - private String plainText; - - private int argIndex = UNSET; - - private int flags = 0; - - private int width = UNSET; - - private int precision = UNSET; - - private StringBuilder strFlags = new StringBuilder(FLAGT_TYPE_COUNT); - - private char dateSuffix;// will be used in new feature. - - private char conversionType = (char) UNSET; - - boolean isPrecisionSet() { - return precision != UNSET; - } - - boolean isWidthSet() { - return width != UNSET; - } - - boolean isFlagSet(int flag) { - return 0 != (flags & flag); - } - - int getArgIndex() { - return argIndex; - } - - void setArgIndex(int index) { - argIndex = index; - } - - String getPlainText() { - return plainText; - } - - void setPlainText(String plainText) { - this.plainText = plainText; - } - - int getWidth() { - return width; - } - - void setWidth(int width) { - this.width = width; - } - - int getPrecision() { - return precision; - } - - void setPrecision(int precise) { - this.precision = precise; - } - - String getStrFlags() { - return strFlags.toString(); - } - - int getFlags() { - return flags; - } - - void setFlags(int flags) { - this.flags = flags; - } - - /* - * Sets qualified char as one of the flags. If the char is qualified, sets it as - * a flag and returns true. Or else returns false. - */ - boolean setFlag(char c) { - int newFlag; - switch (c) { - case '-': { - newFlag = FLAG_MINUS; - break; - } - case '#': { - newFlag = FLAG_SHARP; - break; - } - case '+': { - newFlag = FLAG_ADD; - break; - } - case ' ': { - newFlag = FLAG_SPACE; - break; - } - case '0': { - newFlag = FLAG_ZERO; - break; - } - case ',': { - newFlag = FLAG_COMMA; - return true; - } - case '(': { - newFlag = FLAG_PARENTHESIS; - break; - } - default: - return false; - } - if (0 != (flags & newFlag)) { - throw new DuplicateFormatFlagsException(String.valueOf(c)); - } - flags = (flags | newFlag); - strFlags.append(c); - return true; - - } - - int getFormatStringStartIndex() { - return formatStringStartIndex; - } - - void setFormatStringStartIndex(int index) { - formatStringStartIndex = index; - } - - char getConversionType() { - return conversionType; - } - - void setConversionType(char c) { - conversionType = c; - } - - char getDateSuffix() { - return dateSuffix; - } - - void setDateSuffix(char c) { - dateSuffix = c; - } - - boolean requireArgument() { - return conversionType != '%' && conversionType != 'n'; - } - } - - /* - * Transforms the argument to the formatted string according to the format - * information contained in the format token. - */ - private static class Transformer { - - private HFormatter formatter; - - private FormatToken formatToken; - - private Object arg; - - private Locale locale; - - private static String lineSeparator; - - private NumberFormat numberFormat; - - private DecimalFormatSymbols decimalFormatSymbols; - - private DateTimeUtil dateTimeUtil; - - Transformer(HFormatter formatter, Locale locale) { - this.formatter = formatter; - this.locale = (null == locale ? Locale.US : locale); - } - - private NumberFormat getNumberFormat() { - if (null == numberFormat) { - numberFormat = NumberFormat.getInstance(locale); - } - return numberFormat; - } - - private DecimalFormatSymbols getDecimalFormatSymbols() { - if (null == decimalFormatSymbols) { - decimalFormatSymbols = new DecimalFormatSymbols(locale); - } - return decimalFormatSymbols; - } - - /* - * Gets the formatted string according to the format token and the argument. - */ - String transform(FormatToken token, Object argument) { - - /* init data member to print */ - this.formatToken = token; - this.arg = argument; - - String result; - switch (token.getConversionType()) { - case 'B': - case 'b': { - result = transformFromBoolean(); - break; - } - case 'H': - case 'h': { - result = transformFromHashCode(); - break; - } - case 'S': - case 's': { - result = transformFromString(); - break; - } - case 'C': - case 'c': { - result = transformFromCharacter(); - break; - } - case 'd': - case 'o': - case 'x': - case 'X': { - if (null == arg || arg instanceof BigInteger) { - result = transformFromBigInteger(); - } else { - result = transformFromInteger(); - } - break; - } - case 'e': - case 'E': - case 'g': - case 'G': - case 'f': - case 'a': - case 'A': { - result = transformFromFloat(); - break; - } - case '%': { - result = transformFromPercent(); - break; - } - case 'n': { - result = transformFromLineSeparator(); - break; - } - case 't': - case 'T': { - result = transformFromDateTime(); - break; - } - default: { - throw new UnknownFormatConversionException(String.valueOf(token.getConversionType())); - } - } - - if (Character.isUpperCase(token.getConversionType())) { - if (null != result) { - result = result.toUpperCase(Locale.US); - } - } - return result; - } - - /* - * Transforms the Boolean argument to a formatted string. - */ - private String transformFromBoolean() { + private static class DateTimeUtil { + private static String paddingZeros(long number, int length) { + int len = length; StringBuilder result = new StringBuilder(); + result.append(number); int startIndex = 0; - int flags = formatToken.getFlags(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + formatToken.getConversionType()); - } - - // only '-' is valid for flags - if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - - if (null == arg) { - result.append("false"); //$NON-NLS-1$ - } else if (arg instanceof Boolean) { - result.append(arg); - } else { - result.append("true"); //$NON-NLS-1$ - } - return padding(result, startIndex); - } - - /* - * Transforms the hashcode of the argument to a formatted string. - */ - private String transformFromHashCode() { - StringBuilder result = new StringBuilder(); - - int startIndex = 0; - int flags = formatToken.getFlags(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + formatToken.getConversionType()); - } - - // only '-' is valid for flags - if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - - if (null == arg) { - result.append("null"); //$NON-NLS-1$ - } else { - result.append(Integer.toHexString(arg.hashCode())); - } - return padding(result, startIndex); - } - - /* - * Transforms the String to a formatted string. - */ - private String transformFromString() { - StringBuilder result = new StringBuilder(); - int startIndex = 0; - int flags = formatToken.getFlags(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + formatToken.getConversionType()); - } - - // only '-' is valid for flags if the argument is not an - // instance of Formattable - if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - - result.append(arg); - return padding(result, startIndex); - } - - /* - * Transforms the Character to a formatted string. - */ - private String transformFromCharacter() { - StringBuilder result = new StringBuilder(); - - int startIndex = 0; - int flags = formatToken.getFlags(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + formatToken.getConversionType()); - } - - // only '-' is valid for flags - if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - - if (formatToken.isPrecisionSet()) { - throw new IllegalFormatPrecisionException(formatToken.getPrecision()); - } - - if (null == arg) { - result.append("null"); //$NON-NLS-1$ - } else { - if (arg instanceof Character) { - result.append(arg); - } else if (arg instanceof Byte) { - byte b = ((Byte) arg).byteValue(); - if (!Character.isValidCodePoint(b)) { - throw new IllegalFormatCodePointException(b); - } - result.append((char) b); - } else if (arg instanceof Short) { - short s = ((Short) arg).shortValue(); - if (!Character.isValidCodePoint(s)) { - throw new IllegalFormatCodePointException(s); - } - result.append((char) s); - } else if (arg instanceof Integer) { - int codePoint = ((Integer) arg).intValue(); - if (!Character.isValidCodePoint(codePoint)) { - throw new IllegalFormatCodePointException(codePoint); - } - result.append(String.valueOf(Character.toChars(codePoint))); - } else { - // argument of other class is not acceptable. - throw new IllegalFormatConversionException(formatToken.getConversionType(), arg.getClass()); - } - } - return padding(result, startIndex); - } - - /* - * Transforms percent to a formatted string. Only '-' is legal flag. Precision - * is illegal. - */ - private String transformFromPercent() { - StringBuilder result = new StringBuilder("%"); //$NON-NLS-1$ - - int startIndex = 0; - int flags = formatToken.getFlags(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + formatToken.getConversionType()); - } - - if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - if (formatToken.isPrecisionSet()) { - throw new IllegalFormatPrecisionException(formatToken.getPrecision()); - } - return padding(result, startIndex); - } - - /* - * Transforms line separator to a formatted string. Any flag, the width or the - * precision is illegal. - */ - private String transformFromLineSeparator() { - if (formatToken.isPrecisionSet()) { - throw new IllegalFormatPrecisionException(formatToken.getPrecision()); - } - - if (formatToken.isWidthSet()) { - throw new IllegalFormatWidthException(formatToken.getWidth()); - } - - int flags = formatToken.getFlags(); - if (FormatToken.FLAGS_UNSET != flags) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if (null == lineSeparator) { - lineSeparator = AccessController.doPrivileged(new PrivilegedAction() { - - public String run() { - return System.getProperty("line.separator"); //$NON-NLS-1$ - } - }); - } - return lineSeparator; - } - - /* - * Pads characters to the formatted string. - */ - private String padding(StringBuilder source, int startIndex) { - int start = startIndex; - boolean paddingRight = formatToken.isFlagSet(FormatToken.FLAG_MINUS); - char paddingChar = '\u0020';// space as padding char. - if (formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - if ('d' == formatToken.getConversionType()) { - paddingChar = getDecimalFormatSymbols().getZeroDigit(); - } else { - paddingChar = '0'; - } - } else { - // if padding char is space, always padding from the head - // location. - start = 0; - } - int width = formatToken.getWidth(); - int precision = formatToken.getPrecision(); - - int length = source.length(); - if (precision >= 0) { - length = Math.min(length, precision); - source.delete(length, source.length()); - } - if (width > 0) { - width = Math.max(source.length(), width); - } - if (length >= width) { - return source.toString(); - } - - char[] paddings = new char[width - length]; - Arrays.fill(paddings, paddingChar); - String insertString = new String(paddings); - - if (paddingRight) { - source.append(insertString); - } else { - source.insert(start, insertString); - } - return source.toString(); - } - - /* - * Transforms the Integer to a formatted string. - */ - private String transformFromInteger() { - int startIndex = 0; - boolean isNegative = false; - StringBuilder result = new StringBuilder(); - char currentConversionType = formatToken.getConversionType(); - long value; - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) || formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - if (!formatToken.isWidthSet()) { - throw new MissingFormatWidthException(formatToken.getStrFlags()); - } - } - // Combination of '+' & ' ' is illegal. - if (formatToken.isFlagSet(FormatToken.FLAG_ADD) && formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - if (formatToken.isPrecisionSet()) { - throw new IllegalFormatPrecisionException(formatToken.getPrecision()); - } - if (arg instanceof Long) { - value = ((Long) arg).longValue(); - } else if (arg instanceof Integer) { - value = ((Integer) arg).longValue(); - } else if (arg instanceof Short) { - value = ((Short) arg).longValue(); - } else if (arg instanceof Byte) { - value = ((Byte) arg).longValue(); - } else { - throw new IllegalFormatConversionException(formatToken.getConversionType(), arg.getClass()); - } - if ('d' != currentConversionType) { - if (formatToken.isFlagSet(FormatToken.FLAG_ADD) || formatToken.isFlagSet(FormatToken.FLAG_SPACE) - || formatToken.isFlagSet(FormatToken.FLAG_COMMA) - || formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } - } - - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { - if ('d' == currentConversionType) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), - formatToken.getConversionType()); - } else if ('o' == currentConversionType) { - result.append("0"); //$NON-NLS-1$ - startIndex += 1; - } else { - result.append("0x"); //$NON-NLS-1$ - startIndex += 2; - } - } - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if (value < 0) { - isNegative = true; - } - - if ('d' == currentConversionType) { -// NumberFormat numberFormat = getNumberFormat(); -// if (formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { -// numberFormat.setGroupingUsed(true); -// } else { -// numberFormat.setGroupingUsed(false); -// } -// result.append(numberFormat.format(arg)); - result.append(arg); //TODO: why is TeaVM's NumberFormat broken? (it always puts commas) - } else { - long BYTE_MASK = 0x00000000000000FFL; - long SHORT_MASK = 0x000000000000FFFFL; - long INT_MASK = 0x00000000FFFFFFFFL; - if (isNegative) { - if (arg instanceof Byte) { - value &= BYTE_MASK; - } else if (arg instanceof Short) { - value &= SHORT_MASK; - } else if (arg instanceof Integer) { - value &= INT_MASK; - } - } - if ('o' == currentConversionType) { - result.append(Long.toOctalString(value)); - } else { - result.append(Long.toHexString(value)); - } - isNegative = false; - } - - if (!isNegative) { - if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { - result.insert(0, '+'); - startIndex += 1; - } - if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - result.insert(0, ' '); - startIndex += 1; - } - } - - /* pad paddingChar to the output */ - if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { - result = wrapParentheses(result); - return result.toString(); - - } - if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - startIndex++; - } - return padding(result, startIndex); - } - - /* - * add () to the output,if the value is negative and - * formatToken.FLAG_PARENTHESIS is set. 'result' is used as an in-out parameter. - */ - private StringBuilder wrapParentheses(StringBuilder result) { - // delete the '-' - result.deleteCharAt(0); - result.insert(0, '('); - if (formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - formatToken.setWidth(formatToken.getWidth() - 1); - padding(result, 1); - result.append(')'); - } else { - result.append(')'); - padding(result, 0); - } - return result; - } - - private String transformFromSpecialNumber() { - String source = null; - - if (!(arg instanceof Number) || arg instanceof BigDecimal) { - return null; - } - - Number number = (Number) arg; - double d = number.doubleValue(); - if (Double.isNaN(d)) { - source = "NaN"; //$NON-NLS-1$ - } else if (Double.isInfinite(d)) { - if (d >= 0) { - if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { - source = "+Infinity"; //$NON-NLS-1$ - } else if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - source = " Infinity"; //$NON-NLS-1$ - } else { - source = "Infinity"; //$NON-NLS-1$ - } - } else { - if (formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { - source = "(Infinity)"; //$NON-NLS-1$ - } else { - source = "-Infinity"; //$NON-NLS-1$ - } - } - } - - if (null != source) { - formatToken.setPrecision(FormatToken.UNSET); - formatToken.setFlags(formatToken.getFlags() & (~FormatToken.FLAG_ZERO)); - source = padding(new StringBuilder(source), 0); - } - return source; - } - - private String transformFromNull() { - formatToken.setFlags(formatToken.getFlags() & (~FormatToken.FLAG_ZERO)); - return padding(new StringBuilder("null"), 0); //$NON-NLS-1$ - } - - /* - * Transforms a BigInteger to a formatted string. - */ - private String transformFromBigInteger() { - int startIndex = 0; - boolean isNegative = false; - StringBuilder result = new StringBuilder(); - BigInteger bigInt = (BigInteger) arg; - char currentConversionType = formatToken.getConversionType(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) || formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - if (!formatToken.isWidthSet()) { - throw new MissingFormatWidthException(formatToken.getStrFlags()); - } - } - - // Combination of '+' & ' ' is illegal. - if (formatToken.isFlagSet(FormatToken.FLAG_ADD) && formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - // Combination of '-' & '0' is illegal. - if (formatToken.isFlagSet(FormatToken.FLAG_ZERO) && formatToken.isFlagSet(FormatToken.FLAG_MINUS)) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if (formatToken.isPrecisionSet()) { - throw new IllegalFormatPrecisionException(formatToken.getPrecision()); - } - - if ('d' != currentConversionType && formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); - } - - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP) && 'd' == currentConversionType) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); - } - - if (null == bigInt) { - return transformFromNull(); - } - - isNegative = (bigInt.compareTo(BigInteger.ZERO) < 0); - - if ('d' == currentConversionType) { -// NumberFormat numberFormat = getNumberFormat(); -// boolean readableName = formatToken.isFlagSet(FormatToken.FLAG_COMMA); -// numberFormat.setGroupingUsed(readableName); -// result.append(numberFormat.format(bigInt)); - result.append(bigInt); //TODO: why is TeaVM's NumberFormat broken? (it always puts commas) - } else if ('o' == currentConversionType) { - // convert BigInteger to a string presentation using radix 8 - result.append(bigInt.toString(8)); - } else { - // convert BigInteger to a string presentation using radix 16 - result.append(bigInt.toString(16)); - } - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { - startIndex = isNegative ? 1 : 0; - if ('o' == currentConversionType) { - result.insert(startIndex, "0"); //$NON-NLS-1$ - startIndex += 1; - } else if ('x' == currentConversionType || 'X' == currentConversionType) { - result.insert(startIndex, "0x"); //$NON-NLS-1$ - startIndex += 2; - } - } - - if (!isNegative) { - if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { - result.insert(0, '+'); - startIndex += 1; - } - if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - result.insert(0, ' '); - startIndex += 1; - } - } - - /* pad paddingChar to the output */ - if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { - result = wrapParentheses(result); - return result.toString(); - - } - if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - startIndex++; - } - return padding(result, startIndex); - } - - /* - * Transforms a Float,Double or BigDecimal to a formatted string. - */ - private String transformFromFloat() { - StringBuilder result = new StringBuilder(); - int startIndex = 0; - char currentConversionType = formatToken.getConversionType(); - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS | FormatToken.FLAG_ZERO)) { - if (!formatToken.isWidthSet()) { - throw new MissingFormatWidthException(formatToken.getStrFlags()); - } - } - - if (formatToken.isFlagSet(FormatToken.FLAG_ADD) && formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { - throw new IllegalFormatFlagsException(formatToken.getStrFlags()); - } - - if ('e' == Character.toLowerCase(currentConversionType)) { - if (formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); - } - } - - if ('g' == Character.toLowerCase(currentConversionType)) { - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); - } - } - - if ('a' == Character.toLowerCase(currentConversionType)) { - if (formatToken.isFlagSet(FormatToken.FLAG_COMMA) - || formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); - } - } - - if (null == arg) { - return transformFromNull(); - } - - if (!(arg instanceof Float || arg instanceof Double || arg instanceof BigDecimal)) { - throw new IllegalFormatConversionException(currentConversionType, arg.getClass()); - } - - String specialNumberResult = transformFromSpecialNumber(); - if (null != specialNumberResult) { - return specialNumberResult; - } - - if ('a' != Character.toLowerCase(currentConversionType)) { - formatToken.setPrecision( - formatToken.isPrecisionSet() ? formatToken.getPrecision() : FormatToken.DEFAULT_PRECISION); - } - // output result - FloatUtil floatUtil = new FloatUtil(result, formatToken, (DecimalFormat) NumberFormat.getInstance(locale), - arg); - floatUtil.transform(formatToken, result); - - formatToken.setPrecision(FormatToken.UNSET); - - if (getDecimalFormatSymbols().getMinusSign() == result.charAt(0)) { - if (formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { - result = wrapParentheses(result); - return result.toString(); - } - } else { - if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { - result.insert(0, ' '); - startIndex++; - } - if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { - result.insert(0, floatUtil.getAddSign()); - startIndex++; - } - } - - char firstChar = result.charAt(0); - if (formatToken.isFlagSet(FormatToken.FLAG_ZERO) - && (firstChar == floatUtil.getAddSign() || firstChar == floatUtil.getMinusSign())) { + if (number < 0) { + len++; startIndex = 1; } - - if ('a' == Character.toLowerCase(currentConversionType)) { - startIndex += 2; - } - return padding(result, startIndex); - } - - /* - * Transforms a Date to a formatted string. - */ - private String transformFromDateTime() { - int startIndex = 0; - char currentConversionType = formatToken.getConversionType(); - - if (formatToken.isPrecisionSet()) { - throw new IllegalFormatPrecisionException(formatToken.getPrecision()); - } - - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { - throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); - } - - if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && FormatToken.UNSET == formatToken.getWidth()) { - throw new MissingFormatWidthException("-" //$NON-NLS-1$ - + currentConversionType); - } - - if (null == arg) { - return transformFromNull(); - } - - Calendar calendar; - if (arg instanceof Calendar) { - calendar = (Calendar) arg; - } else { - Date date = null; - if (arg instanceof Long) { - date = new Date(((Long) arg).longValue()); - } else if (arg instanceof Date) { - date = (Date) arg; - } else { - throw new IllegalFormatConversionException(currentConversionType, arg.getClass()); - } - calendar = Calendar.getInstance(locale); - calendar.setTime(date); - } - - if (null == dateTimeUtil) { - dateTimeUtil = new DateTimeUtil(locale); - } - StringBuilder result = new StringBuilder(); - // output result - dateTimeUtil.transform(formatToken, calendar, result); - return padding(result, startIndex); - } - } - - private static class FloatUtil { - private StringBuilder result; - - private DecimalFormat decimalFormat; - - private FormatToken formatToken; - - private Object argument; - - private char minusSign; - - FloatUtil(StringBuilder result, FormatToken formatToken, DecimalFormat decimalFormat, Object argument) { - this.result = result; - this.formatToken = formatToken; - this.decimalFormat = decimalFormat; - this.argument = argument; - this.minusSign = decimalFormat.getDecimalFormatSymbols().getMinusSign(); - } - - void transform(FormatToken aFormatToken, StringBuilder aResult) { - this.result = aResult; - this.formatToken = aFormatToken; - switch (formatToken.getConversionType()) { - case 'e': - case 'E': { - transform_e(); - break; - } - case 'f': { - transform_f(); - break; - } - case 'g': - case 'G': { - transform_g(); - break; - } - case 'a': - case 'A': { - transform_a(); - break; - } - default: { - throw new UnknownFormatConversionException(String.valueOf(formatToken.getConversionType())); - } - } - } - - char getMinusSign() { - return minusSign; - } - - char getAddSign() { - return '+'; - } - - void transform_e() { - StringBuilder pattern = new StringBuilder(); - pattern.append('0'); - if (formatToken.getPrecision() > 0) { - pattern.append('.'); - char[] zeros = new char[formatToken.getPrecision()]; + len -= result.length(); + if (len > 0) { + char[] zeros = new char[len]; Arrays.fill(zeros, '0'); - pattern.append(zeros); - } - pattern.append('E'); - pattern.append("+00"); //$NON-NLS-1$ - decimalFormat.applyPattern(pattern.toString()); - String formattedString = decimalFormat.format(argument); - result.append(formattedString.replace('E', 'e')); - - // if the flag is sharp and decimal seperator is always given - // out. - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP) && 0 == formatToken.getPrecision()) { - int indexOfE = result.indexOf("e"); //$NON-NLS-1$ - char dot = decimalFormat.getDecimalFormatSymbols().getDecimalSeparator(); - result.insert(indexOfE, dot); + result.insert(startIndex, zeros); } + return result.toString(); } - void transform_g() { - int precision = formatToken.getPrecision(); - precision = (0 == precision ? 1 : precision); - formatToken.setPrecision(precision); - - if (0.0 == ((Number) argument).doubleValue()) { - precision--; - formatToken.setPrecision(precision); - transform_f(); - return; - } - - boolean requireScientificRepresentation = true; - double d = ((Number) argument).doubleValue(); - d = Math.abs(d); - if (Double.isInfinite(d)) { - precision = formatToken.getPrecision(); - precision--; - formatToken.setPrecision(precision); - transform_e(); - return; - } - BigDecimal b = new BigDecimal(d, new MathContext(precision)); - d = b.doubleValue(); - long l = b.longValue(); - - if (d >= 1 && d < Math.pow(10, precision)) { - if (l < Math.pow(10, precision)) { - requireScientificRepresentation = false; - precision -= String.valueOf(l).length(); - precision = precision < 0 ? 0 : precision; - l = Math.round(d * Math.pow(10, precision + 1)); - if (String.valueOf(l).length() <= formatToken.getPrecision()) { - precision++; - } - formatToken.setPrecision(precision); - } - - } else { - l = b.movePointRight(4).longValue(); - if (d >= Math.pow(10, -4) && d < 1) { - requireScientificRepresentation = false; - precision += 4 - String.valueOf(l).length(); - l = b.movePointRight(precision + 1).longValue(); - if (String.valueOf(l).length() <= formatToken.getPrecision()) { - precision++; - } - l = b.movePointRight(precision).longValue(); - if (l >= Math.pow(10, precision - 4)) { - formatToken.setPrecision(precision); - } - } - } - if (requireScientificRepresentation) { - precision = formatToken.getPrecision(); - precision--; - formatToken.setPrecision(precision); - transform_e(); - } else { - transform_f(); - } - - } - - void transform_f() { - StringBuilder pattern = new StringBuilder(); - if (formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { - - pattern.append(','); - int groupingSize = decimalFormat.getGroupingSize(); - if (groupingSize > 1) { - char[] sharps = new char[groupingSize - 1]; - Arrays.fill(sharps, '#'); - pattern.append(sharps); - } - } - - pattern.append(0); - - if (formatToken.getPrecision() > 0) { - pattern.append('.'); - char[] zeros = new char[formatToken.getPrecision()]; - Arrays.fill(zeros, '0'); - pattern.append(zeros); - } - decimalFormat.applyPattern(pattern.toString()); - result.append(decimalFormat.format(argument)); - // if the flag is sharp and decimal seperator is always given - // out. - if (formatToken.isFlagSet(FormatToken.FLAG_SHARP) && 0 == formatToken.getPrecision()) { - char dot = decimalFormat.getDecimalFormatSymbols().getDecimalSeparator(); - result.append(dot); - } - - } - - void transform_a() { - char currentConversionType = formatToken.getConversionType(); - - if (argument instanceof Float) { - Float F = (Float) argument; - result.append(Float.toHexString(F.floatValue())); - - } else if (argument instanceof Double) { - Double D = (Double) argument; - result.append(Double.toHexString(D.doubleValue())); - } else { - // BigInteger is not supported. - throw new IllegalFormatConversionException(currentConversionType, argument.getClass()); - } - - if (!formatToken.isPrecisionSet()) { - return; - } - - int precision = formatToken.getPrecision(); - precision = (0 == precision ? 1 : precision); - int indexOfFirstFracitoanlDigit = result.indexOf(".") + 1; //$NON-NLS-1$ - int indexOfP = result.indexOf("p"); //$NON-NLS-1$ - int fractionalLength = indexOfP - indexOfFirstFracitoanlDigit; - - if (fractionalLength == precision) { - return; - } - - if (fractionalLength < precision) { - char zeros[] = new char[precision - fractionalLength]; - Arrays.fill(zeros, '0'); - result.insert(indexOfP, zeros); - return; - } - result.delete(indexOfFirstFracitoanlDigit + precision, indexOfP); - } - } - - private static class DateTimeUtil { private Calendar calendar; private Locale locale; @@ -2143,6 +442,13 @@ public final class HFormatter implements Closeable, Flushable { this.locale = locale; } + private DateFormatSymbols getDateFormatSymbols() { + if (null == dateFormatSymbols) { + dateFormatSymbols = new DateFormatSymbols(locale); + } + return dateFormatSymbols; + } + void transform(FormatToken formatToken, Calendar aCalendar, StringBuilder aResult) { this.result = aResult; this.calendar = aCalendar; @@ -2278,46 +584,6 @@ public final class HFormatter implements Closeable, Flushable { } } - private void transform_e() { - int day = calendar.get(Calendar.DAY_OF_MONTH); - result.append(day); - } - - private void transform_d() { - int day = calendar.get(Calendar.DAY_OF_MONTH); - result.append(paddingZeros(day, 2)); - } - - private void transform_m() { - int month = calendar.get(Calendar.MONTH); - // The returned month starts from zero, which needs to be - // incremented by 1. - month++; - result.append(paddingZeros(month, 2)); - } - - private void transform_j() { - int day = calendar.get(Calendar.DAY_OF_YEAR); - result.append(paddingZeros(day, 3)); - } - - private void transform_y() { - int year = calendar.get(Calendar.YEAR); - year %= 100; - result.append(paddingZeros(year, 2)); - } - - private void transform_Y() { - int year = calendar.get(Calendar.YEAR); - result.append(paddingZeros(year, 4)); - } - - private void transform_C() { - int year = calendar.get(Calendar.YEAR); - year /= 100; - result.append(paddingZeros(year, 2)); - } - private void transform_a() { int day = calendar.get(Calendar.DAY_OF_WEEK); result.append(getDateFormatSymbols().getShortWeekdays()[day]); @@ -2338,128 +604,6 @@ public final class HFormatter implements Closeable, Flushable { result.append(getDateFormatSymbols().getMonths()[month]); } - private void transform_Q() { - long milliSeconds = calendar.getTimeInMillis(); - result.append(milliSeconds); - } - - private void transform_s() { - long milliSeconds = calendar.getTimeInMillis(); - milliSeconds /= 1000; - result.append(milliSeconds); - } - - private void transform_Z() { - TimeZone timeZone = calendar.getTimeZone(); - result.append(timeZone.getDisplayName(timeZone.inDaylightTime(calendar.getTime()), TimeZone.SHORT, locale)); - } - - private void transform_z() { - int zoneOffset = calendar.get(Calendar.ZONE_OFFSET); - zoneOffset /= 3600000; - zoneOffset *= 100; - if (zoneOffset >= 0) { - result.append('+'); - } - result.append(paddingZeros(zoneOffset, 4)); - } - - private void transform_p(boolean isLowerCase) { - int i = calendar.get(Calendar.AM_PM); - String s = getDateFormatSymbols().getAmPmStrings()[i]; - if (isLowerCase) { - s = s.toLowerCase(locale); - } - result.append(s); - } - - private void transform_N() { - // TODO System.nanoTime(); - long nanosecond = calendar.get(Calendar.MILLISECOND) * 1000000L; - result.append(paddingZeros(nanosecond, 9)); - } - - private void transform_L() { - int millisecond = calendar.get(Calendar.MILLISECOND); - result.append(paddingZeros(millisecond, 3)); - } - - private void transform_S() { - int second = calendar.get(Calendar.SECOND); - result.append(paddingZeros(second, 2)); - } - - private void transform_M() { - int minute = calendar.get(Calendar.MINUTE); - result.append(paddingZeros(minute, 2)); - } - - private void transform_l() { - int hour = calendar.get(Calendar.HOUR); - if (0 == hour) { - hour = 12; - } - result.append(hour); - } - - private void transform_k() { - int hour = calendar.get(Calendar.HOUR_OF_DAY); - result.append(hour); - } - - private void transform_I() { - int hour = calendar.get(Calendar.HOUR); - if (0 == hour) { - hour = 12; - } - result.append(paddingZeros(hour, 2)); - } - - private void transform_H() { - int hour = calendar.get(Calendar.HOUR_OF_DAY); - result.append(paddingZeros(hour, 2)); - } - - private void transform_R() { - transform_H(); - result.append(':'); - transform_M(); - } - - private void transform_T() { - transform_H(); - result.append(':'); - transform_M(); - result.append(':'); - transform_S(); - } - - private void transform_r() { - transform_I(); - result.append(':'); - transform_M(); - result.append(':'); - transform_S(); - result.append(' '); - transform_p(false); - } - - private void transform_D() { - transform_m(); - result.append('/'); - transform_d(); - result.append('/'); - transform_y(); - } - - private void transform_F() { - transform_Y(); - result.append('-'); - transform_m(); - result.append('-'); - transform_d(); - } - private void transform_c() { transform_a(); result.append(' '); @@ -2474,30 +618,602 @@ public final class HFormatter implements Closeable, Flushable { transform_Y(); } - private static String paddingZeros(long number, int length) { - int len = length; - StringBuilder result = new StringBuilder(); - result.append(number); - int startIndex = 0; - if (number < 0) { - len++; - startIndex = 1; - } - len -= result.length(); - if (len > 0) { - char[] zeros = new char[len]; - Arrays.fill(zeros, '0'); - result.insert(startIndex, zeros); - } - return result.toString(); + private void transform_C() { + int year = calendar.get(Calendar.YEAR); + year /= 100; + result.append(paddingZeros(year, 2)); } - private DateFormatSymbols getDateFormatSymbols() { - if (null == dateFormatSymbols) { - dateFormatSymbols = new DateFormatSymbols(locale); - } - return dateFormatSymbols; + private void transform_d() { + int day = calendar.get(Calendar.DAY_OF_MONTH); + result.append(paddingZeros(day, 2)); } + + private void transform_D() { + transform_m(); + result.append('/'); + transform_d(); + result.append('/'); + transform_y(); + } + + private void transform_e() { + int day = calendar.get(Calendar.DAY_OF_MONTH); + result.append(day); + } + + private void transform_F() { + transform_Y(); + result.append('-'); + transform_m(); + result.append('-'); + transform_d(); + } + + private void transform_H() { + int hour = calendar.get(Calendar.HOUR_OF_DAY); + result.append(paddingZeros(hour, 2)); + } + + private void transform_I() { + int hour = calendar.get(Calendar.HOUR); + if (0 == hour) { + hour = 12; + } + result.append(paddingZeros(hour, 2)); + } + + private void transform_j() { + int day = calendar.get(Calendar.DAY_OF_YEAR); + result.append(paddingZeros(day, 3)); + } + + private void transform_k() { + int hour = calendar.get(Calendar.HOUR_OF_DAY); + result.append(hour); + } + + private void transform_l() { + int hour = calendar.get(Calendar.HOUR); + if (0 == hour) { + hour = 12; + } + result.append(hour); + } + + private void transform_L() { + int millisecond = calendar.get(Calendar.MILLISECOND); + result.append(paddingZeros(millisecond, 3)); + } + + private void transform_m() { + int month = calendar.get(Calendar.MONTH); + // The returned month starts from zero, which needs to be + // incremented by 1. + month++; + result.append(paddingZeros(month, 2)); + } + + private void transform_M() { + int minute = calendar.get(Calendar.MINUTE); + result.append(paddingZeros(minute, 2)); + } + + private void transform_N() { + // TODO System.nanoTime(); + long nanosecond = calendar.get(Calendar.MILLISECOND) * 1000000L; + result.append(paddingZeros(nanosecond, 9)); + } + + private void transform_p(boolean isLowerCase) { + int i = calendar.get(Calendar.AM_PM); + String s = getDateFormatSymbols().getAmPmStrings()[i]; + if (isLowerCase) { + s = s.toLowerCase(locale); + } + result.append(s); + } + + private void transform_Q() { + long milliSeconds = calendar.getTimeInMillis(); + result.append(milliSeconds); + } + + private void transform_r() { + transform_I(); + result.append(':'); + transform_M(); + result.append(':'); + transform_S(); + result.append(' '); + transform_p(false); + } + + private void transform_R() { + transform_H(); + result.append(':'); + transform_M(); + } + + private void transform_s() { + long milliSeconds = calendar.getTimeInMillis(); + milliSeconds /= 1000; + result.append(milliSeconds); + } + + private void transform_S() { + int second = calendar.get(Calendar.SECOND); + result.append(paddingZeros(second, 2)); + } + + private void transform_T() { + transform_H(); + result.append(':'); + transform_M(); + result.append(':'); + transform_S(); + } + + private void transform_y() { + int year = calendar.get(Calendar.YEAR); + year %= 100; + result.append(paddingZeros(year, 2)); + } + + private void transform_Y() { + int year = calendar.get(Calendar.YEAR); + result.append(paddingZeros(year, 4)); + } + + private void transform_z() { + int zoneOffset = calendar.get(Calendar.ZONE_OFFSET); + zoneOffset /= 3600000; + zoneOffset *= 100; + if (zoneOffset >= 0) { + result.append('+'); + } + result.append(paddingZeros(zoneOffset, 4)); + } + + private void transform_Z() { + TimeZone timeZone = calendar.getTimeZone(); + result.append(timeZone.getDisplayName(timeZone.inDaylightTime(calendar.getTime()), TimeZone.SHORT, locale)); + } + } + + public static class DuplicateFormatFlagsException extends IllegalArgumentException { + + public DuplicateFormatFlagsException() { + } + + public DuplicateFormatFlagsException(String s) { + super(s); + } + + } + + private static class FloatUtil { + private StringBuilder result; + + private DecimalFormat decimalFormat; + + private FormatToken formatToken; + + private Object argument; + + private char minusSign; + + FloatUtil(StringBuilder result, FormatToken formatToken, DecimalFormat decimalFormat, Object argument) { + this.result = result; + this.formatToken = formatToken; + this.decimalFormat = decimalFormat; + this.argument = argument; + this.minusSign = decimalFormat.getDecimalFormatSymbols().getMinusSign(); + } + + char getAddSign() { + return '+'; + } + + char getMinusSign() { + return minusSign; + } + + void transform(FormatToken aFormatToken, StringBuilder aResult) { + this.result = aResult; + this.formatToken = aFormatToken; + switch (formatToken.getConversionType()) { + case 'e': + case 'E': { + transform_e(); + break; + } + case 'f': { + transform_f(); + break; + } + case 'g': + case 'G': { + transform_g(); + break; + } + case 'a': + case 'A': { + transform_a(); + break; + } + default: { + throw new UnknownFormatConversionException(String.valueOf(formatToken.getConversionType())); + } + } + } + + void transform_a() { + char currentConversionType = formatToken.getConversionType(); + + if (argument instanceof Float) { + Float F = (Float) argument; + result.append(Float.toHexString(F.floatValue())); + + } else if (argument instanceof Double) { + Double D = (Double) argument; + result.append(Double.toHexString(D.doubleValue())); + } else { + // BigInteger is not supported. + throw new IllegalFormatConversionException(currentConversionType, argument.getClass()); + } + + if (!formatToken.isPrecisionSet()) { + return; + } + + int precision = formatToken.getPrecision(); + precision = (0 == precision ? 1 : precision); + int indexOfFirstFracitoanlDigit = result.indexOf(".") + 1; //$NON-NLS-1$ + int indexOfP = result.indexOf("p"); //$NON-NLS-1$ + int fractionalLength = indexOfP - indexOfFirstFracitoanlDigit; + + if (fractionalLength == precision) { + return; + } + + if (fractionalLength < precision) { + char zeros[] = new char[precision - fractionalLength]; + Arrays.fill(zeros, '0'); + result.insert(indexOfP, zeros); + return; + } + result.delete(indexOfFirstFracitoanlDigit + precision, indexOfP); + } + + void transform_e() { + StringBuilder pattern = new StringBuilder(); + pattern.append('0'); + if (formatToken.getPrecision() > 0) { + pattern.append('.'); + char[] zeros = new char[formatToken.getPrecision()]; + Arrays.fill(zeros, '0'); + pattern.append(zeros); + } + pattern.append('E'); + pattern.append("+00"); //$NON-NLS-1$ + decimalFormat.applyPattern(pattern.toString()); + String formattedString = decimalFormat.format(argument); + result.append(formattedString.replace('E', 'e')); + + // if the flag is sharp and decimal seperator is always given + // out. + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP) && 0 == formatToken.getPrecision()) { + int indexOfE = result.indexOf("e"); //$NON-NLS-1$ + char dot = decimalFormat.getDecimalFormatSymbols().getDecimalSeparator(); + result.insert(indexOfE, dot); + } + } + + void transform_f() { + StringBuilder pattern = new StringBuilder(); + if (formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { + + pattern.append(','); + int groupingSize = decimalFormat.getGroupingSize(); + if (groupingSize > 1) { + char[] sharps = new char[groupingSize - 1]; + Arrays.fill(sharps, '#'); + pattern.append(sharps); + } + } + + pattern.append(0); + + if (formatToken.getPrecision() > 0) { + pattern.append('.'); + char[] zeros = new char[formatToken.getPrecision()]; + Arrays.fill(zeros, '0'); + pattern.append(zeros); + } + decimalFormat.applyPattern(pattern.toString()); + result.append(decimalFormat.format(argument)); + // if the flag is sharp and decimal seperator is always given + // out. + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP) && 0 == formatToken.getPrecision()) { + char dot = decimalFormat.getDecimalFormatSymbols().getDecimalSeparator(); + result.append(dot); + } + + } + + void transform_g() { + int precision = formatToken.getPrecision(); + precision = (0 == precision ? 1 : precision); + formatToken.setPrecision(precision); + + if (0.0 == ((Number) argument).doubleValue()) { + precision--; + formatToken.setPrecision(precision); + transform_f(); + return; + } + + boolean requireScientificRepresentation = true; + double d = ((Number) argument).doubleValue(); + d = Math.abs(d); + if (Double.isInfinite(d)) { + precision = formatToken.getPrecision(); + precision--; + formatToken.setPrecision(precision); + transform_e(); + return; + } + BigDecimal b = new BigDecimal(d, new MathContext(precision)); + d = b.doubleValue(); + long l = b.longValue(); + + if (d >= 1 && d < Math.pow(10, precision)) { + if (l < Math.pow(10, precision)) { + requireScientificRepresentation = false; + precision -= String.valueOf(l).length(); + precision = precision < 0 ? 0 : precision; + l = Math.round(d * Math.pow(10, precision + 1)); + if (String.valueOf(l).length() <= formatToken.getPrecision()) { + precision++; + } + formatToken.setPrecision(precision); + } + + } else { + l = b.movePointRight(4).longValue(); + if (d >= Math.pow(10, -4) && d < 1) { + requireScientificRepresentation = false; + precision += 4 - String.valueOf(l).length(); + l = b.movePointRight(precision + 1).longValue(); + if (String.valueOf(l).length() <= formatToken.getPrecision()) { + precision++; + } + l = b.movePointRight(precision).longValue(); + if (l >= Math.pow(10, precision - 4)) { + formatToken.setPrecision(precision); + } + } + } + if (requireScientificRepresentation) { + precision = formatToken.getPrecision(); + precision--; + formatToken.setPrecision(precision); + transform_e(); + } else { + transform_f(); + } + + } + } + + /* + * Information about the format string of a specified argument, which includes + * the conversion type, flags, width, precision and the argument index as well + * as the plainText that contains the whole format string used as the result for + * output if necessary. Besides, the string for flags is recorded to construct + * corresponding FormatExceptions if necessary. + */ + private static class FormatToken { + + static final int LAST_ARGUMENT_INDEX = -2; + + static final int UNSET = -1; + + static final int FLAGS_UNSET = 0; + + static final int DEFAULT_PRECISION = 6; + + static final int FLAG_MINUS = 1; + + static final int FLAG_SHARP = 1 << 1; + + static final int FLAG_ADD = 1 << 2; + + static final int FLAG_SPACE = 1 << 3; + + static final int FLAG_ZERO = 1 << 4; + + static final int FLAG_COMMA = 1 << 5; + + static final int FLAG_PARENTHESIS = 1 << 6; + + private static final int FLAGT_TYPE_COUNT = 6; + + private int formatStringStartIndex; + + private String plainText; + + private int argIndex = UNSET; + + private int flags = 0; + + private int width = UNSET; + + private int precision = UNSET; + + private StringBuilder strFlags = new StringBuilder(FLAGT_TYPE_COUNT); + + private char dateSuffix;// will be used in new feature. + + private char conversionType = (char) UNSET; + + int getArgIndex() { + return argIndex; + } + + char getConversionType() { + return conversionType; + } + + char getDateSuffix() { + return dateSuffix; + } + + int getFlags() { + return flags; + } + + int getFormatStringStartIndex() { + return formatStringStartIndex; + } + + String getPlainText() { + return plainText; + } + + int getPrecision() { + return precision; + } + + String getStrFlags() { + return strFlags.toString(); + } + + int getWidth() { + return width; + } + + boolean isFlagSet(int flag) { + return 0 != (flags & flag); + } + + boolean isPrecisionSet() { + return precision != UNSET; + } + + boolean isWidthSet() { + return width != UNSET; + } + + boolean requireArgument() { + return conversionType != '%' && conversionType != 'n'; + } + + void setArgIndex(int index) { + argIndex = index; + } + + void setConversionType(char c) { + conversionType = c; + } + + void setDateSuffix(char c) { + dateSuffix = c; + } + + /* + * Sets qualified char as one of the flags. If the char is qualified, sets it as + * a flag and returns true. Or else returns false. + */ + boolean setFlag(char c) { + int newFlag; + switch (c) { + case '-': { + newFlag = FLAG_MINUS; + break; + } + case '#': { + newFlag = FLAG_SHARP; + break; + } + case '+': { + newFlag = FLAG_ADD; + break; + } + case ' ': { + newFlag = FLAG_SPACE; + break; + } + case '0': { + newFlag = FLAG_ZERO; + break; + } + case ',': { + newFlag = FLAG_COMMA; + return true; + } + case '(': { + newFlag = FLAG_PARENTHESIS; + break; + } + default: + return false; + } + if (0 != (flags & newFlag)) { + throw new DuplicateFormatFlagsException(String.valueOf(c)); + } + flags = (flags | newFlag); + strFlags.append(c); + return true; + + } + + void setFlags(int flags) { + this.flags = flags; + } + + void setFormatStringStartIndex(int index) { + formatStringStartIndex = index; + } + + void setPlainText(String plainText) { + this.plainText = plainText; + } + + void setPrecision(int precise) { + this.precision = precise; + } + + void setWidth(int width) { + this.width = width; + } + } + + public static class IllegalFormatWidthException extends IllegalArgumentException { + + public IllegalFormatWidthException() { + } + + public IllegalFormatWidthException(int i) { + super(Integer.toString(i)); + } + + public IllegalFormatWidthException(String s) { + super(s); + } + + } + + public static class MissingFormatArgumentException extends IllegalArgumentException { + + public MissingFormatArgumentException() { + } + + public MissingFormatArgumentException(String s) { + super(s); + } + } private static class ParserStateMachine { @@ -2532,10 +1248,22 @@ public final class HFormatter implements Closeable, Flushable { this.format = format; } - void reset() { - this.currentChar = (char) FormatToken.UNSET; - this.state = ENTRY_STATE; - this.token = null; + private String getFormatString() { + int end = format.position(); + format.rewind(); + String formatString = format.subSequence(token.getFormatStringStartIndex(), end).toString(); + format.position(end); + return formatString; + } + + /* + * Gets next char from the format string. + */ + private char getNextFormatChar() { + if (format.hasRemaining()) { + return format.get(); + } + return EOS; } /* @@ -2599,21 +1327,35 @@ public final class HFormatter implements Closeable, Flushable { } /* - * Gets next char from the format string. + * Parses integer value from the given buffer */ - private char getNextFormatChar() { - if (format.hasRemaining()) { - return format.get(); + private int parseInt(CharBuffer buffer) { + int start = buffer.position() - 1; + int end = buffer.limit(); + while (buffer.hasRemaining()) { + if (!Character.isDigit(buffer.get())) { + end = buffer.position() - 1; + break; + } + } + buffer.position(0); + String intStr = buffer.subSequence(start, end).toString(); + buffer.position(end); + try { + return Integer.parseInt(intStr); + } catch (NumberFormatException e) { + return FormatToken.UNSET; } - return EOS; } - private String getFormatString() { - int end = format.position(); - format.rewind(); - String formatString = format.subSequence(token.getFormatStringStartIndex(), end).toString(); - format.position(end); - return formatString; + private void process_CONVERSION_TYPE_STATE() { + token.setConversionType(currentChar); + if ('t' == currentChar || 'T' == currentChar) { + state = SUFFIX_STATE; + } else { + state = EXIT_STATE; + } + } private void process_ENTRY_STATE() { @@ -2626,6 +1368,36 @@ public final class HFormatter implements Closeable, Flushable { // else remains in ENTRY_STATE } + private void process_EXIT_STATE() { + token.setPlainText(getFormatString()); + } + + private void process_FlAGS_STATE() { + if (token.setFlag(currentChar)) { + // remains in FLAGS_STATE + } else if (Character.isDigit(currentChar)) { + token.setWidth(parseInt(format)); + state = WIDTH_STATE; + } else if ('.' == currentChar) { + state = PRECISION_STATE; + } else { + state = CONVERSION_TYPE_STATE; + // do not get the next char. + format.position(format.position() - 1); + } + } + + private void process_PRECISION_STATE() { + if (Character.isDigit(currentChar)) { + token.setPrecision(parseInt(format)); + } else { + // the precision is required but not given by the + // format string. + throw new UnknownFormatConversionException(getFormatString()); + } + state = CONVERSION_TYPE_STATE; + } + private void process_START_CONVERSION_STATE() { if (Character.isDigit(currentChar)) { int position = format.position() - 1; @@ -2671,19 +1443,9 @@ public final class HFormatter implements Closeable, Flushable { } - private void process_FlAGS_STATE() { - if (token.setFlag(currentChar)) { - // remains in FLAGS_STATE - } else if (Character.isDigit(currentChar)) { - token.setWidth(parseInt(format)); - state = WIDTH_STATE; - } else if ('.' == currentChar) { - state = PRECISION_STATE; - } else { - state = CONVERSION_TYPE_STATE; - // do not get the next char. - format.position(format.position() - 1); - } + private void process_SUFFIX_STATE() { + token.setDateSuffix(currentChar); + state = EXIT_STATE; } private void process_WIDTH_STATE() { @@ -2696,56 +1458,1294 @@ public final class HFormatter implements Closeable, Flushable { } } - private void process_PRECISION_STATE() { - if (Character.isDigit(currentChar)) { - token.setPrecision(parseInt(format)); - } else { - // the precision is required but not given by the - // format string. - throw new UnknownFormatConversionException(getFormatString()); + void reset() { + this.currentChar = (char) FormatToken.UNSET; + this.state = ENTRY_STATE; + this.token = null; + } + } + + /* + * Transforms the argument to the formatted string according to the format + * information contained in the format token. + */ + private static class Transformer { + + private static String lineSeparator; + + private HFormatter formatter; + + private FormatToken formatToken; + + private Object arg; + + private Locale locale; + + private NumberFormat numberFormat; + + private DecimalFormatSymbols decimalFormatSymbols; + + private DateTimeUtil dateTimeUtil; + + Transformer(HFormatter formatter, Locale locale) { + this.formatter = formatter; + this.locale = (null == locale ? Locale.US : locale); + } + + private DecimalFormatSymbols getDecimalFormatSymbols() { + if (null == decimalFormatSymbols) { + decimalFormatSymbols = new DecimalFormatSymbols(locale); } - state = CONVERSION_TYPE_STATE; + return decimalFormatSymbols; } - private void process_CONVERSION_TYPE_STATE() { - token.setConversionType(currentChar); - if ('t' == currentChar || 'T' == currentChar) { - state = SUFFIX_STATE; - } else { - state = EXIT_STATE; + private NumberFormat getNumberFormat() { + if (null == numberFormat) { + numberFormat = NumberFormat.getInstance(locale); } - - } - - private void process_SUFFIX_STATE() { - token.setDateSuffix(currentChar); - state = EXIT_STATE; - } - - private void process_EXIT_STATE() { - token.setPlainText(getFormatString()); + return numberFormat; } /* - * Parses integer value from the given buffer + * Pads characters to the formatted string. */ - private int parseInt(CharBuffer buffer) { - int start = buffer.position() - 1; - int end = buffer.limit(); - while (buffer.hasRemaining()) { - if (!Character.isDigit(buffer.get())) { - end = buffer.position() - 1; - break; + private String padding(StringBuilder source, int startIndex) { + int start = startIndex; + boolean paddingRight = formatToken.isFlagSet(FormatToken.FLAG_MINUS); + char paddingChar = '\u0020';// space as padding char. + if (formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + if ('d' == formatToken.getConversionType()) { + paddingChar = getDecimalFormatSymbols().getZeroDigit(); + } else { + paddingChar = '0'; + } + } else { + // if padding char is space, always padding from the head + // location. + start = 0; + } + int width = formatToken.getWidth(); + int precision = formatToken.getPrecision(); + + int length = source.length(); + if (precision >= 0) { + length = Math.min(length, precision); + source.delete(length, source.length()); + } + if (width > 0) { + width = Math.max(source.length(), width); + } + if (length >= width) { + return source.toString(); + } + + char[] paddings = new char[width - length]; + Arrays.fill(paddings, paddingChar); + String insertString = new String(paddings); + + if (paddingRight) { + source.append(insertString); + } else { + source.insert(start, insertString); + } + return source.toString(); + } + + /* + * Gets the formatted string according to the format token and the argument. + */ + String transform(FormatToken token, Object argument) { + + /* init data member to print */ + this.formatToken = token; + this.arg = argument; + + String result; + switch (token.getConversionType()) { + case 'B': + case 'b': { + result = transformFromBoolean(); + break; + } + case 'H': + case 'h': { + result = transformFromHashCode(); + break; + } + case 'S': + case 's': { + result = transformFromString(); + break; + } + case 'C': + case 'c': { + result = transformFromCharacter(); + break; + } + case 'd': + case 'o': + case 'x': + case 'X': { + if (null == arg || arg instanceof BigInteger) { + result = transformFromBigInteger(); + } else { + result = transformFromInteger(); + } + break; + } + case 'e': + case 'E': + case 'g': + case 'G': + case 'f': + case 'a': + case 'A': { + result = transformFromFloat(); + break; + } + case '%': { + result = transformFromPercent(); + break; + } + case 'n': { + result = transformFromLineSeparator(); + break; + } + case 't': + case 'T': { + result = transformFromDateTime(); + break; + } + default: { + throw new UnknownFormatConversionException(String.valueOf(token.getConversionType())); + } + } + + if (Character.isUpperCase(token.getConversionType())) { + if (null != result) { + result = result.toUpperCase(Locale.US); } } - buffer.position(0); - String intStr = buffer.subSequence(start, end).toString(); - buffer.position(end); + return result; + } + + /* + * Transforms a BigInteger to a formatted string. + */ + private String transformFromBigInteger() { + int startIndex = 0; + boolean isNegative = false; + StringBuilder result = new StringBuilder(); + BigInteger bigInt = (BigInteger) arg; + char currentConversionType = formatToken.getConversionType(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) || formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + if (!formatToken.isWidthSet()) { + throw new MissingFormatWidthException(formatToken.getStrFlags()); + } + } + + // Combination of '+' & ' ' is illegal. + if (formatToken.isFlagSet(FormatToken.FLAG_ADD) && formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + + // Combination of '-' & '0' is illegal. + if (formatToken.isFlagSet(FormatToken.FLAG_ZERO) && formatToken.isFlagSet(FormatToken.FLAG_MINUS)) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + + if (formatToken.isPrecisionSet()) { + throw new IllegalFormatPrecisionException(formatToken.getPrecision()); + } + + if ('d' != currentConversionType && formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); + } + + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP) && 'd' == currentConversionType) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); + } + + if (null == bigInt) { + return transformFromNull(); + } + + isNegative = (bigInt.compareTo(BigInteger.ZERO) < 0); + + if ('d' == currentConversionType) { +// NumberFormat numberFormat = getNumberFormat(); +// boolean readableName = formatToken.isFlagSet(FormatToken.FLAG_COMMA); +// numberFormat.setGroupingUsed(readableName); +// result.append(numberFormat.format(bigInt)); + result.append(bigInt); // TODO: why is TeaVM's NumberFormat broken? (it always puts commas) + } else if ('o' == currentConversionType) { + // convert BigInteger to a string presentation using radix 8 + result.append(bigInt.toString(8)); + } else { + // convert BigInteger to a string presentation using radix 16 + result.append(bigInt.toString(16)); + } + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { + startIndex = isNegative ? 1 : 0; + if ('o' == currentConversionType) { + result.insert(startIndex, "0"); //$NON-NLS-1$ + startIndex += 1; + } else if ('x' == currentConversionType || 'X' == currentConversionType) { + result.insert(startIndex, "0x"); //$NON-NLS-1$ + startIndex += 2; + } + } + + if (!isNegative) { + if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { + result.insert(0, '+'); + startIndex += 1; + } + if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + result.insert(0, ' '); + startIndex += 1; + } + } + + /* pad paddingChar to the output */ + if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { + result = wrapParentheses(result); + return result.toString(); + + } + if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + startIndex++; + } + return padding(result, startIndex); + } + + /* + * Transforms the Boolean argument to a formatted string. + */ + private String transformFromBoolean() { + StringBuilder result = new StringBuilder(); + int startIndex = 0; + int flags = formatToken.getFlags(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { + throw new MissingFormatWidthException("-" //$NON-NLS-1$ + + formatToken.getConversionType()); + } + + // only '-' is valid for flags + if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } + + if (null == arg) { + result.append("false"); //$NON-NLS-1$ + } else if (arg instanceof Boolean) { + result.append(arg); + } else { + result.append("true"); //$NON-NLS-1$ + } + return padding(result, startIndex); + } + + /* + * Transforms the Character to a formatted string. + */ + private String transformFromCharacter() { + StringBuilder result = new StringBuilder(); + + int startIndex = 0; + int flags = formatToken.getFlags(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { + throw new MissingFormatWidthException("-" //$NON-NLS-1$ + + formatToken.getConversionType()); + } + + // only '-' is valid for flags + if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } + + if (formatToken.isPrecisionSet()) { + throw new IllegalFormatPrecisionException(formatToken.getPrecision()); + } + + if (null == arg) { + result.append("null"); //$NON-NLS-1$ + } else { + if (arg instanceof Character) { + result.append(arg); + } else if (arg instanceof Byte) { + byte b = ((Byte) arg).byteValue(); + if (!Character.isValidCodePoint(b)) { + throw new IllegalFormatCodePointException(b); + } + result.append((char) b); + } else if (arg instanceof Short) { + short s = ((Short) arg).shortValue(); + if (!Character.isValidCodePoint(s)) { + throw new IllegalFormatCodePointException(s); + } + result.append((char) s); + } else if (arg instanceof Integer) { + int codePoint = ((Integer) arg).intValue(); + if (!Character.isValidCodePoint(codePoint)) { + throw new IllegalFormatCodePointException(codePoint); + } + result.append(String.valueOf(Character.toChars(codePoint))); + } else { + // argument of other class is not acceptable. + throw new IllegalFormatConversionException(formatToken.getConversionType(), arg.getClass()); + } + } + return padding(result, startIndex); + } + + /* + * Transforms a Date to a formatted string. + */ + private String transformFromDateTime() { + int startIndex = 0; + char currentConversionType = formatToken.getConversionType(); + + if (formatToken.isPrecisionSet()) { + throw new IllegalFormatPrecisionException(formatToken.getPrecision()); + } + + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); + } + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && FormatToken.UNSET == formatToken.getWidth()) { + throw new MissingFormatWidthException("-" //$NON-NLS-1$ + + currentConversionType); + } + + if (null == arg) { + return transformFromNull(); + } + + Calendar calendar; + if (arg instanceof Calendar) { + calendar = (Calendar) arg; + } else { + Date date = null; + if (arg instanceof Long) { + date = new Date(((Long) arg).longValue()); + } else if (arg instanceof Date) { + date = (Date) arg; + } else { + throw new IllegalFormatConversionException(currentConversionType, arg.getClass()); + } + calendar = Calendar.getInstance(locale); + calendar.setTime(date); + } + + if (null == dateTimeUtil) { + dateTimeUtil = new DateTimeUtil(locale); + } + StringBuilder result = new StringBuilder(); + // output result + dateTimeUtil.transform(formatToken, calendar, result); + return padding(result, startIndex); + } + + /* + * Transforms a Float,Double or BigDecimal to a formatted string. + */ + private String transformFromFloat() { + StringBuilder result = new StringBuilder(); + int startIndex = 0; + char currentConversionType = formatToken.getConversionType(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS | FormatToken.FLAG_ZERO)) { + if (!formatToken.isWidthSet()) { + throw new MissingFormatWidthException(formatToken.getStrFlags()); + } + } + + if (formatToken.isFlagSet(FormatToken.FLAG_ADD) && formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + + if ('e' == Character.toLowerCase(currentConversionType)) { + if (formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); + } + } + + if ('g' == Character.toLowerCase(currentConversionType)) { + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); + } + } + + if ('a' == Character.toLowerCase(currentConversionType)) { + if (formatToken.isFlagSet(FormatToken.FLAG_COMMA) + || formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), currentConversionType); + } + } + + if (null == arg) { + return transformFromNull(); + } + + if (!(arg instanceof Float || arg instanceof Double || arg instanceof BigDecimal)) { + throw new IllegalFormatConversionException(currentConversionType, arg.getClass()); + } + + String specialNumberResult = transformFromSpecialNumber(); + if (null != specialNumberResult) { + return specialNumberResult; + } + + if ('a' != Character.toLowerCase(currentConversionType)) { + formatToken.setPrecision( + formatToken.isPrecisionSet() ? formatToken.getPrecision() : FormatToken.DEFAULT_PRECISION); + } + // output result + FloatUtil floatUtil = new FloatUtil(result, formatToken, (DecimalFormat) NumberFormat.getInstance(locale), + arg); + floatUtil.transform(formatToken, result); + + formatToken.setPrecision(FormatToken.UNSET); + + if (getDecimalFormatSymbols().getMinusSign() == result.charAt(0)) { + if (formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { + result = wrapParentheses(result); + return result.toString(); + } + } else { + if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + result.insert(0, ' '); + startIndex++; + } + if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { + result.insert(0, floatUtil.getAddSign()); + startIndex++; + } + } + + char firstChar = result.charAt(0); + if (formatToken.isFlagSet(FormatToken.FLAG_ZERO) + && (firstChar == floatUtil.getAddSign() || firstChar == floatUtil.getMinusSign())) { + startIndex = 1; + } + + if ('a' == Character.toLowerCase(currentConversionType)) { + startIndex += 2; + } + return padding(result, startIndex); + } + + /* + * Transforms the hashcode of the argument to a formatted string. + */ + private String transformFromHashCode() { + StringBuilder result = new StringBuilder(); + + int startIndex = 0; + int flags = formatToken.getFlags(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { + throw new MissingFormatWidthException("-" //$NON-NLS-1$ + + formatToken.getConversionType()); + } + + // only '-' is valid for flags + if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } + + if (null == arg) { + result.append("null"); //$NON-NLS-1$ + } else { + result.append(Integer.toHexString(arg.hashCode())); + } + return padding(result, startIndex); + } + + /* + * Transforms the Integer to a formatted string. + */ + private String transformFromInteger() { + int startIndex = 0; + boolean isNegative = false; + StringBuilder result = new StringBuilder(); + char currentConversionType = formatToken.getConversionType(); + long value; + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) || formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + if (!formatToken.isWidthSet()) { + throw new MissingFormatWidthException(formatToken.getStrFlags()); + } + } + // Combination of '+' & ' ' is illegal. + if (formatToken.isFlagSet(FormatToken.FLAG_ADD) && formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + if (formatToken.isPrecisionSet()) { + throw new IllegalFormatPrecisionException(formatToken.getPrecision()); + } + if (arg instanceof Long) { + value = ((Long) arg).longValue(); + } else if (arg instanceof Integer) { + value = ((Integer) arg).longValue(); + } else if (arg instanceof Short) { + value = ((Short) arg).longValue(); + } else if (arg instanceof Byte) { + value = ((Byte) arg).longValue(); + } else { + throw new IllegalFormatConversionException(formatToken.getConversionType(), arg.getClass()); + } + if ('d' != currentConversionType) { + if (formatToken.isFlagSet(FormatToken.FLAG_ADD) || formatToken.isFlagSet(FormatToken.FLAG_SPACE) + || formatToken.isFlagSet(FormatToken.FLAG_COMMA) + || formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } + } + + if (formatToken.isFlagSet(FormatToken.FLAG_SHARP)) { + if ('d' == currentConversionType) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } else if ('o' == currentConversionType) { + result.append("0"); //$NON-NLS-1$ + startIndex += 1; + } else { + result.append("0x"); //$NON-NLS-1$ + startIndex += 2; + } + } + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + + if (value < 0) { + isNegative = true; + } + + if ('d' == currentConversionType) { +// NumberFormat numberFormat = getNumberFormat(); +// if (formatToken.isFlagSet(FormatToken.FLAG_COMMA)) { +// numberFormat.setGroupingUsed(true); +// } else { +// numberFormat.setGroupingUsed(false); +// } +// result.append(numberFormat.format(arg)); + result.append(arg); // TODO: why is TeaVM's NumberFormat broken? (it always puts commas) + } else { + long BYTE_MASK = 0x00000000000000FFL; + long SHORT_MASK = 0x000000000000FFFFL; + long INT_MASK = 0x00000000FFFFFFFFL; + if (isNegative) { + if (arg instanceof Byte) { + value &= BYTE_MASK; + } else if (arg instanceof Short) { + value &= SHORT_MASK; + } else if (arg instanceof Integer) { + value &= INT_MASK; + } + } + if ('o' == currentConversionType) { + result.append(Long.toOctalString(value)); + } else { + result.append(Long.toHexString(value)); + } + isNegative = false; + } + + if (!isNegative) { + if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { + result.insert(0, '+'); + startIndex += 1; + } + if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + result.insert(0, ' '); + startIndex += 1; + } + } + + /* pad paddingChar to the output */ + if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { + result = wrapParentheses(result); + return result.toString(); + + } + if (isNegative && formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + startIndex++; + } + return padding(result, startIndex); + } + + /* + * Transforms line separator to a formatted string. Any flag, the width or the + * precision is illegal. + */ + private String transformFromLineSeparator() { + if (formatToken.isPrecisionSet()) { + throw new IllegalFormatPrecisionException(formatToken.getPrecision()); + } + + if (formatToken.isWidthSet()) { + throw new IllegalFormatWidthException(formatToken.getWidth()); + } + + int flags = formatToken.getFlags(); + if (FormatToken.FLAGS_UNSET != flags) { + throw new IllegalFormatFlagsException(formatToken.getStrFlags()); + } + + if (null == lineSeparator) { + lineSeparator = AccessController.doPrivileged(new PrivilegedAction() { + + public String run() { + return System.getProperty("line.separator"); //$NON-NLS-1$ + } + }); + } + return lineSeparator; + } + + private String transformFromNull() { + formatToken.setFlags(formatToken.getFlags() & (~FormatToken.FLAG_ZERO)); + return padding(new StringBuilder("null"), 0); //$NON-NLS-1$ + } + + /* + * Transforms percent to a formatted string. Only '-' is legal flag. Precision + * is illegal. + */ + private String transformFromPercent() { + StringBuilder result = new StringBuilder("%"); //$NON-NLS-1$ + + int startIndex = 0; + int flags = formatToken.getFlags(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { + throw new MissingFormatWidthException("-" //$NON-NLS-1$ + + formatToken.getConversionType()); + } + + if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } + if (formatToken.isPrecisionSet()) { + throw new IllegalFormatPrecisionException(formatToken.getPrecision()); + } + return padding(result, startIndex); + } + + private String transformFromSpecialNumber() { + String source = null; + + if (!(arg instanceof Number) || arg instanceof BigDecimal) { + return null; + } + + Number number = (Number) arg; + double d = number.doubleValue(); + if (Double.isNaN(d)) { + source = "NaN"; //$NON-NLS-1$ + } else if (Double.isInfinite(d)) { + if (d >= 0) { + if (formatToken.isFlagSet(FormatToken.FLAG_ADD)) { + source = "+Infinity"; //$NON-NLS-1$ + } else if (formatToken.isFlagSet(FormatToken.FLAG_SPACE)) { + source = " Infinity"; //$NON-NLS-1$ + } else { + source = "Infinity"; //$NON-NLS-1$ + } + } else { + if (formatToken.isFlagSet(FormatToken.FLAG_PARENTHESIS)) { + source = "(Infinity)"; //$NON-NLS-1$ + } else { + source = "-Infinity"; //$NON-NLS-1$ + } + } + } + + if (null != source) { + formatToken.setPrecision(FormatToken.UNSET); + formatToken.setFlags(formatToken.getFlags() & (~FormatToken.FLAG_ZERO)); + source = padding(new StringBuilder(source), 0); + } + return source; + } + + /* + * Transforms the String to a formatted string. + */ + private String transformFromString() { + StringBuilder result = new StringBuilder(); + int startIndex = 0; + int flags = formatToken.getFlags(); + + if (formatToken.isFlagSet(FormatToken.FLAG_MINUS) && !formatToken.isWidthSet()) { + throw new MissingFormatWidthException("-" //$NON-NLS-1$ + + formatToken.getConversionType()); + } + + // only '-' is valid for flags if the argument is not an + // instance of Formattable + if (FormatToken.FLAGS_UNSET != flags && FormatToken.FLAG_MINUS != flags) { + throw new FormatFlagsConversionMismatchException(formatToken.getStrFlags(), + formatToken.getConversionType()); + } + + result.append(arg); + return padding(result, startIndex); + } + + /* + * add () to the output,if the value is negative and + * formatToken.FLAG_PARENTHESIS is set. 'result' is used as an in-out parameter. + */ + private StringBuilder wrapParentheses(StringBuilder result) { + // delete the '-' + result.deleteCharAt(0); + result.insert(0, '('); + if (formatToken.isFlagSet(FormatToken.FLAG_ZERO)) { + formatToken.setWidth(formatToken.getWidth() - 1); + padding(result, 1); + result.append(')'); + } else { + result.append(')'); + padding(result, 0); + } + return result; + } + } + + private static void closeOutputStream(OutputStream os) { + if (null == os) { + return; + } + try { + os.close(); + + } catch (IOException e) { + // silently + } + } + + private Appendable out; + + private Locale locale; + + private boolean closed = false; + + private IOException lastIOException; + + /** + * Constructs a {@code Formatter}. + * + * The output is written to a {@code StringBuilder} which can be acquired by + * invoking {@link #out()} and whose content can be obtained by calling + * {@code toString()}. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + */ + public HFormatter() { + this(new StringBuilder(), Locale.getDefault()); + } + + /** + * Constructs a {@code Formatter} whose output will be written to the specified + * {@code Appendable}. + * + * The locale for the {@code Formatter} is the default {@code Locale}. + * + * @param a the output destination of the {@code Formatter}. If {@code a} is + * {@code null}, then a {@code StringBuilder} will be used. + */ + public HFormatter(Appendable a) { + this(a, Locale.getDefault()); + } + + /** + * Constructs a {@code Formatter} with the specified {@code Locale} and whose + * output will be written to the specified {@code Appendable}. + * + * @param a the output destination of the {@code Formatter}. If {@code a} is + * {@code null}, then a {@code StringBuilder} will be used. + * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is + * {@code null}, then no localization will be used. + */ + public HFormatter(Appendable a, Locale l) { + if (null == a) { + out = new StringBuilder(); + } else { + out = a; + } + locale = l; + } + + /** + * Constructs a {@code Formatter} whose output is written to the specified + * {@code File}. + * + * The charset of the {@code Formatter} is the default charset. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param file the {@code File} that is used as the output destination for the + * {@code Formatter}. The {@code File} will be truncated to zero + * size if the {@code File} exists, or else a new {@code File} will + * be created. The output of the {@code Formatter} is buffered. + * @throws FileNotFoundException if the {@code File} is not a normal and + * writable {@code File}, or if a new {@code File} + * cannot be created, or if any error rises when + * opening or creating the {@code File}. + * @throws SecurityException if there is a {@code SecurityManager} in place + * which denies permission to write to the + * {@code File} in + * {@code checkWrite(file.getPath())}. + */ + public HFormatter(File file) throws FileNotFoundException { + this(new FileOutputStream(file)); + } + + /** + * Constructs a {@code Formatter} with the given charset, and whose output is + * written to the specified {@code File}. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param file the {@code File} that is used as the output destination for the + * {@code Formatter}. The {@code File} will be truncated to zero + * size if the {@code File} exists, or else a new {@code File} will + * be created. The output of the {@code Formatter} is buffered. + * @param csn the name of the charset for the {@code Formatter}. + * @throws FileNotFoundException if the {@code File} is not a normal and + * writable {@code File}, or if a new + * {@code File} cannot be created, or if + * any error rises when opening or creating + * the {@code File}. + * @throws SecurityException if there is a {@code SecurityManager} in + * place which denies permission to write + * to the {@code File} in + * {@code checkWrite(file.getPath())}. + * @throws UnsupportedEncodingException if the charset with the specified name + * is not supported. + */ + public HFormatter(File file, String csn) throws FileNotFoundException, UnsupportedEncodingException { + this(file, csn, Locale.getDefault()); + } + + /** + * Constructs a {@code Formatter} with the given {@code Locale} and charset, and + * whose output is written to the specified {@code File}. + * + * @param file the {@code File} that is used as the output destination for the + * {@code Formatter}. The {@code File} will be truncated to zero + * size if the {@code File} exists, or else a new {@code File} will + * be created. The output of the {@code Formatter} is buffered. + * @param csn the name of the charset for the {@code Formatter}. + * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is + * {@code null}, then no localization will be used. + * @throws FileNotFoundException if the {@code File} is not a normal and + * writable {@code File}, or if a new + * {@code File} cannot be created, or if + * any error rises when opening or creating + * the {@code File}. + * @throws SecurityException if there is a {@code SecurityManager} in + * place which denies permission to write + * to the {@code File} in + * {@code checkWrite(file.getPath())}. + * @throws UnsupportedEncodingException if the charset with the specified name + * is not supported. + */ + public HFormatter(File file, String csn, Locale l) throws FileNotFoundException, UnsupportedEncodingException { + FileOutputStream fout = null; + try { + fout = new FileOutputStream(file); + OutputStreamWriter writer = new OutputStreamWriter(fout, csn); + out = new BufferedWriter(writer); + } catch (RuntimeException e) { + closeOutputStream(fout); + throw e; + } catch (UnsupportedEncodingException e) { + closeOutputStream(fout); + throw e; + } + + locale = l; + } + + /** + * Constructs a {@code Formatter} with the specified {@code Locale}. + * + * The output is written to a {@code StringBuilder} which can be acquired by + * invoking {@link #out()} and whose content can be obtained by calling + * {@code toString()}. + * + * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is + * {@code null}, then no localization will be used. + */ + public HFormatter(Locale l) { + this(new StringBuilder(), l); + } + + /** + * Constructs a {@code Formatter} whose output is written to the specified + * {@code OutputStream}. + * + * The charset of the {@code Formatter} is the default charset. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param os the stream to be used as the destination of the {@code Formatter}. + */ + public HFormatter(OutputStream os) { + OutputStreamWriter writer = new OutputStreamWriter(os, Charset.defaultCharset()); + out = new BufferedWriter(writer); + locale = Locale.getDefault(); + } + + /** + * Constructs a {@code Formatter} with the given charset, and whose output is + * written to the specified {@code OutputStream}. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param os the stream to be used as the destination of the {@code Formatter}. + * @param csn the name of the charset for the {@code Formatter}. + * @throws UnsupportedEncodingException if the charset with the specified name + * is not supported. + */ + public HFormatter(OutputStream os, String csn) throws UnsupportedEncodingException { + + this(os, csn, Locale.getDefault()); + } + + /** + * Constructs a {@code Formatter} with the given {@code Locale} and charset, and + * whose output is written to the specified {@code OutputStream}. + * + * @param os the stream to be used as the destination of the {@code Formatter}. + * @param csn the name of the charset for the {@code Formatter}. + * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is + * {@code null}, then no localization will be used. + * @throws UnsupportedEncodingException if the charset with the specified name + * is not supported. + */ + public HFormatter(OutputStream os, String csn, Locale l) throws UnsupportedEncodingException { + + OutputStreamWriter writer = new OutputStreamWriter(os, csn); + out = new BufferedWriter(writer); + + locale = l; + } + + /** + * Constructs a {@code Formatter} whose output is written to the specified + * {@code PrintStream}. + * + * The charset of the {@code Formatter} is the default charset. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param ps the {@code PrintStream} used as destination of the + * {@code Formatter}. If {@code ps} is {@code null}, then a + * {@code NullPointerException} will be raised. + */ + public HFormatter(PrintStream ps) { + if (null == ps) { + throw new NullPointerException(); + } + out = ps; + locale = Locale.getDefault(); + } + + /** + * Constructs a {@code Formatter} whose output is written to the specified file. + * + * The charset of the {@code Formatter} is the default charset. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param fileName the filename of the file that is used as the output + * destination for the {@code Formatter}. The file will be + * truncated to zero size if the file exists, or else a new file + * will be created. The output of the {@code Formatter} is + * buffered. + * @throws FileNotFoundException if the filename does not denote a normal and + * writable file, or if a new file cannot be + * created, or if any error arises when opening or + * creating the file. + * @throws SecurityException if there is a {@code SecurityManager} in place + * which denies permission to write to the file in + * {@code checkWrite(file.getPath())}. + */ + public HFormatter(String fileName) throws FileNotFoundException { + this(new File(fileName)); + + } + + /** + * Constructs a {@code Formatter} whose output is written to the specified file. + * + * The {@code Locale} for the {@code Formatter} is the default {@code Locale}. + * + * @param fileName the filename of the file that is used as the output + * destination for the {@code Formatter}. The file will be + * truncated to zero size if the file exists, or else a new file + * will be created. The output of the {@code Formatter} is + * buffered. + * @param csn the name of the charset for the {@code Formatter}. + * @throws FileNotFoundException if the filename does not denote a normal + * and writable file, or if a new file + * cannot be created, or if any error + * arises when opening or creating the + * file. + * @throws SecurityException if there is a {@code SecurityManager} in + * place which denies permission to write + * to the file in + * {@code checkWrite(file.getPath())}. + * @throws UnsupportedEncodingException if the charset with the specified name + * is not supported. + */ + public HFormatter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException { + this(new File(fileName), csn); + } + + /** + * Constructs a {@code Formatter} with the given {@code Locale} and charset, and + * whose output is written to the specified file. + * + * @param fileName the filename of the file that is used as the output + * destination for the {@code Formatter}. The file will be + * truncated to zero size if the file exists, or else a new file + * will be created. The output of the {@code Formatter} is + * buffered. + * @param csn the name of the charset for the {@code Formatter}. + * @param l the {@code Locale} of the {@code Formatter}. If {@code l} is + * {@code null}, then no localization will be used. + * @throws FileNotFoundException if the filename does not denote a normal + * and writable file, or if a new file + * cannot be created, or if any error + * arises when opening or creating the + * file. + * @throws SecurityException if there is a {@code SecurityManager} in + * place which denies permission to write + * to the file in + * {@code checkWrite(file.getPath())}. + * @throws UnsupportedEncodingException if the charset with the specified name + * is not supported. + */ + public HFormatter(String fileName, String csn, Locale l) + throws FileNotFoundException, UnsupportedEncodingException { + + this(new File(fileName), csn, l); + } + + private void checkClosed() { + if (closed) { + throw new IllegalStateException("Formatter is closed"); + } + } + + /** + * Closes the {@code Formatter}. If the output destination is {@link Closeable}, + * then the method {@code close()} will be called on that destination. + * + * If the {@code Formatter} has been closed, then calling the this method will + * have no effect. + * + * Any method but the {@link #ioException()} that is called after the + * {@code Formatter} has been closed will raise a + * {@code FormatterClosedException}. + */ + public void close() { + closed = true; + try { + if (out instanceof Closeable) { + ((Closeable) out).close(); + } + } catch (IOException e) { + + lastIOException = e; + } + } + + /** + * Flushes the {@code Formatter}. If the output destination is + * {@link Flushable}, then the method {@code flush()} will be called on that + * destination. + * + * @throws FormatterClosedException if the {@code Formatter} has been closed. + */ + public void flush() { + checkClosed(); + if (out instanceof Flushable) { try { - return Integer.parseInt(intStr); - } catch (NumberFormatException e) { - return FormatToken.UNSET; + ((Flushable) out).flush(); + } catch (IOException e) { + lastIOException = e; } } } + + /** + * Writes a formatted string to the output destination of the {@code Formatter}. + * + * @param l the {@code Locale} used in the method. If {@code locale} is + * {@code null}, then no localization will be applied. This + * parameter does not influence the {@code Locale} specified + * during construction. + * @param format a format string. + * @param args the arguments list used in the {@code format()} method. If + * there are more arguments than those specified by the format + * string, then the additional arguments are ignored. + * @return this {@code Formatter}. + * @throws IllegalFormatException if the format string is illegal or + * incompatible with the arguments, or if fewer + * arguments are sent than those required by + * the format string, or any other illegal + * situation. + * @throws FormatterClosedException if the {@code Formatter} has been closed. + */ + public HFormatter format(Locale l, String format, Object... args) { + checkClosed(); + CharBuffer formatBuffer = CharBuffer.wrap(format); + ParserStateMachine parser = new ParserStateMachine(formatBuffer); + Transformer transformer = new Transformer(this, l); + + int currentObjectIndex = 0; + Object lastArgument = null; + boolean hasLastArgumentSet = false; + while (formatBuffer.hasRemaining()) { + parser.reset(); + FormatToken token = parser.getNextFormatToken(); + String result; + String plainText = token.getPlainText(); + if (token.getConversionType() == (char) FormatToken.UNSET) { + result = plainText; + } else { + plainText = plainText.substring(0, plainText.indexOf('%')); + Object argument = null; + if (token.requireArgument()) { + int index = token.getArgIndex() == FormatToken.UNSET ? currentObjectIndex++ : token.getArgIndex(); + argument = getArgument(args, index, token, lastArgument, hasLastArgumentSet); + lastArgument = argument; + hasLastArgumentSet = true; + } + result = transformer.transform(token, argument); + result = (null == result ? plainText : plainText + result); + } + // if output is made by formattable callback + if (null != result) { + try { + out.append(result); + } catch (IOException e) { + lastIOException = e; + } + } + } + return this; + } + + /** + * Writes a formatted string to the output destination of the {@code Formatter}. + * + * @param format a format string. + * @param args the arguments list used in the {@code format()} method. If + * there are more arguments than those specified by the format + * string, then the additional arguments are ignored. + * @return this {@code Formatter}. + * @throws IllegalFormatException if the format string is illegal or + * incompatible with the arguments, or if fewer + * arguments are sent than those required by + * the format string, or any other illegal + * situation. + * @throws FormatterClosedException if the {@code Formatter} has been closed. + */ + public HFormatter format(String format, Object... args) { + return format(locale, format, args); + } + + private Object getArgument(Object[] args, int index, FormatToken token, Object lastArgument, + boolean hasLastArgumentSet) { + if (index == FormatToken.LAST_ARGUMENT_INDEX && !hasLastArgumentSet) { + throw new MissingFormatArgumentException("<"); //$NON-NLS-1$ + } + + if (null == args) { + return null; + } + + if (index >= args.length) { + throw new MissingFormatArgumentException(token.getPlainText()); + } + + if (index == FormatToken.LAST_ARGUMENT_INDEX) { + return lastArgument; + } + + return args[index]; + } + + /** + * Returns the last {@code IOException} thrown by the {@code Formatter}'s output + * destination. If the {@code append()} method of the destination does not throw + * {@code IOException}s, the {@code ioException()} method will always return + * {@code null}. + * + * @return the last {@code IOException} thrown by the {@code Formatter}'s output + * destination. + */ + public IOException ioException() { + return lastIOException; + } + + /** + * Returns the {@code Locale} of the {@code Formatter}. + * + * @return the {@code Locale} for the {@code Formatter} or {@code null} for no + * {@code Locale}. + * @throws FormatterClosedException if the {@code Formatter} has been closed. + */ + public Locale locale() { + checkClosed(); + return locale; + } + + /** + * Returns the output destination of the {@code Formatter}. + * + * @return the output destination of the {@code Formatter}. + * @throws FormatterClosedException if the {@code Formatter} has been closed. + */ + public Appendable out() { + checkClosed(); + return out; + } + + /** + * Returns the content by calling the {@code toString()} method of the output + * destination. + * + * @return the content by calling the {@code toString()} method of the output + * destination. + * @throws FormatterClosedException if the {@code Formatter} has been closed. + */ + @Override + public String toString() { + checkClosed(); + return out.toString(); + } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/HString.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/HString.java index eeccb1d6..b281d3c9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/HString.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/HString.java @@ -3,22 +3,23 @@ package net.lax1dude.eaglercraft.v1_8; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class HString { - public static String format(String format, Object... args) { - return new HFormatter().format(format, args).toString(); - } + public static String format(String format, Object... args) { + return new HFormatter().format(format, args).toString(); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/HashKey.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/HashKey.java index 75cd5582..693ad1d8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/HashKey.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/HashKey.java @@ -5,14 +5,15 @@ import java.util.Arrays; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -22,23 +23,18 @@ public class HashKey { public final byte[] key; public final int hash; - public HashKey(byte[] key, int hashCode) { - this.key = key; - this.hash = hashCode; - } - public HashKey(byte[] key) { this.key = key; this.hash = Arrays.hashCode(key); } - public Object clone() { - return new HashKey(key, hash); + public HashKey(byte[] key, int hashCode) { + this.key = key; + this.hash = hashCode; } - @Override - public int hashCode() { - return hash; + public Object clone() { + return new HashKey(key, hash); } @Override @@ -51,4 +47,9 @@ public class HashKey { return hash == other.hash && Arrays.equals(key, other.key); } + @Override + public int hashCode() { + return hash; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/IOUtils.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/IOUtils.java index 83655734..6c3464f4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/IOUtils.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/IOUtils.java @@ -13,59 +13,41 @@ import java.util.List; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IOUtils { - public static List readLines(InputStream parInputStream, Charset charset) { - if(parInputStream instanceof EaglerInputStream) { - return Arrays.asList( - new String(((EaglerInputStream) parInputStream).getAsArray(), charset).split("(\\r\\n|\\n|\\r)")); - }else { - List ret = new ArrayList<>(); - try(InputStream is = parInputStream) { - BufferedReader rd = new BufferedReader(new InputStreamReader(is, charset)); - String s; - while((s = rd.readLine()) != null) { - ret.add(s); - } - }catch(IOException ex) { - return null; - } - return ret; - } - } - public static void closeQuietly(Closeable reResourcePack) { try { reResourcePack.close(); - }catch(Throwable t) { + } catch (Throwable t) { } } - + public static String inputStreamToString(InputStream is, Charset c) throws IOException { - if(is instanceof EaglerInputStream) { - return new String(((EaglerInputStream)is).getAsArray(), c); - }else { + if (is instanceof EaglerInputStream) { + return new String(((EaglerInputStream) is).getAsArray(), c); + } else { try { StringBuilder b = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, c)); String s; - while((s = rd.readLine()) != null) { + while ((s = rd.readLine()) != null) { b.append(s).append('\n'); } return b.toString(); - }finally { + } finally { is.close(); } } @@ -73,15 +55,34 @@ public class IOUtils { public static int readFully(InputStream is, byte[] out) throws IOException { int i = 0, j; - while(i < out.length && (j = is.read(out, i, out.length - i)) != -1) { + while (i < out.length && (j = is.read(out, i, out.length - i)) != -1) { i += j; } return i; } + public static List readLines(InputStream parInputStream, Charset charset) { + if (parInputStream instanceof EaglerInputStream) { + return Arrays.asList( + new String(((EaglerInputStream) parInputStream).getAsArray(), charset).split("(\\r\\n|\\n|\\r)")); + } else { + List ret = new ArrayList<>(); + try (InputStream is = parInputStream) { + BufferedReader rd = new BufferedReader(new InputStreamReader(is, charset)); + String s; + while ((s = rd.readLine()) != null) { + ret.add(s); + } + } catch (IOException ex) { + return null; + } + return ret; + } + } + public static long skipFully(InputStream is, long skip) throws IOException { long i = 0, j; - while(i < skip && (j = is.skip(skip - i)) != 0) { + while (i < skip && (j = is.skip(skip - i)) != 0) { i += j; } return i; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/JDKBackports.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/JDKBackports.java index 5ab8570f..8c954b5c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/JDKBackports.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/JDKBackports.java @@ -5,20 +5,39 @@ import java.util.function.Supplier; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JDKBackports { - + + public static T javaUtilObject_requireNonNull(T obj) { + if (obj == null) + throw new NullPointerException(); + return obj; + } + + public static T javaUtilObject_requireNonNull(T obj, String message) { + if (obj == null) + throw new NullPointerException(message); + return obj; + } + + public static T javaUtilObject_requireNonNull(T obj, Supplier messageSupplier) { + if (obj == null) + throw new NullPointerException(messageSupplier.get()); + return obj; + } + public static long parseLong(CharSequence s, int beginIndex, int endIndex, int radix) throws NumberFormatException { if (beginIndex < 0 || beginIndex > endIndex || endIndex > s.length()) { throw new IndexOutOfBoundsException(); @@ -68,23 +87,5 @@ public class JDKBackports { throw new NumberFormatException(""); } } - - public static T javaUtilObject_requireNonNull(T obj, Supplier messageSupplier) { - if (obj == null) - throw new NullPointerException(messageSupplier.get()); - return obj; - } - - public static T javaUtilObject_requireNonNull(T obj, String message) { - if (obj == null) - throw new NullPointerException(message); - return obj; - } - - public static T javaUtilObject_requireNonNull(T obj) { - if (obj == null) - throw new NullPointerException(); - return obj; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Keyboard.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Keyboard.java index 9355a7f0..f50e5528 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Keyboard.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Keyboard.java @@ -7,34 +7,27 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Keyboard { - + public static void enableRepeatEvents(boolean b) { PlatformInput.keyboardEnableRepeatEvents(b); } - public static boolean isCreated() { - return true; - } - - public static boolean next() { - return PlatformInput.keyboardNext(); - } - - public static boolean getEventKeyState() { - return PlatformInput.keyboardGetEventKeyState(); + public static void fireEvent(EnumFireKeyboardEvent eventType, int eagKey, char keyChar) { + PlatformInput.keyboardFireEvent(eventType, eagKey, keyChar); } public static char getEventCharacter() { @@ -45,24 +38,32 @@ public class Keyboard { return PlatformInput.keyboardGetEventKey(); } - public static void setFunctionKeyModifier(int key) { - PlatformInput.setFunctionKeyModifier(key); - } - - public static boolean isKeyDown(int key) { - return PlatformInput.keyboardIsKeyDown(key); + public static boolean getEventKeyState() { + return PlatformInput.keyboardGetEventKeyState(); } public static String getKeyName(int key) { return KeyboardConstants.getKeyName(key); } + public static boolean isCreated() { + return true; + } + + public static boolean isKeyDown(int key) { + return PlatformInput.keyboardIsKeyDown(key); + } + public static boolean isRepeatEvent() { return PlatformInput.keyboardIsRepeatEvent(); } - public static void fireEvent(EnumFireKeyboardEvent eventType, int eagKey, char keyChar) { - PlatformInput.keyboardFireEvent(eventType, eagKey, keyChar); + public static boolean next() { + return PlatformInput.keyboardNext(); + } + + public static void setFunctionKeyModifier(int key) { + PlatformInput.setFunctionKeyModifier(key); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Mouse.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Mouse.java index da236bac..830787f4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Mouse.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Mouse.java @@ -7,68 +7,41 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Mouse { - public static int getEventDWheel() { - return PlatformInput.mouseGetEventDWheel(); + private static int customCursorCounter = 0; + + private static EnumCursorType currentCursorType = EnumCursorType.DEFAULT; + + public static void fireButtonEvent(EnumFireMouseEvent eventType, int posX, int posY, int button) { + PlatformInput.mouseFireButtonEvent(eventType, posX, posY, button); } - public static int getX() { - return PlatformInput.mouseGetX(); + public static void fireMoveEvent(EnumFireMouseEvent eventType, int posX, int posY) { + PlatformInput.mouseFireMoveEvent(eventType, posX, posY); } - public static int getY() { - return PlatformInput.mouseGetY(); - } - - public static boolean getEventButtonState() { - return PlatformInput.mouseGetEventButtonState(); - } - - public static boolean isCreated() { - return true; - } - - public static boolean next() { - return PlatformInput.mouseNext(); - } - - public static int getEventX() { - return PlatformInput.mouseGetEventX(); - } - - public static int getEventY() { - return PlatformInput.mouseGetEventY(); - } - - public static int getEventButton() { - return PlatformInput.mouseGetEventButton(); - } - - public static boolean isButtonDown(int i) { - return PlatformInput.mouseIsButtonDown(i); + public static void fireWheelEvent(EnumFireMouseEvent eventType, int posX, int posY, float wheel) { + PlatformInput.mouseFireWheelEvent(eventType, posX, posY, wheel); } public static int getDWheel() { return PlatformInput.mouseGetDWheel(); } - public static void setGrabbed(boolean grab) { - PlatformInput.mouseSetGrabbed(grab); - } - public static int getDX() { return PlatformInput.mouseGetDX(); } @@ -77,18 +50,50 @@ public class Mouse { return PlatformInput.mouseGetDY(); } - public static void setCursorPosition(int x, int y) { - PlatformInput.mouseSetCursorPosition(x, y); + public static int getEventButton() { + return PlatformInput.mouseGetEventButton(); } - public static boolean isInsideWindow() { - return PlatformInput.mouseIsInsideWindow(); + public static boolean getEventButtonState() { + return PlatformInput.mouseGetEventButtonState(); + } + + public static int getEventDWheel() { + return PlatformInput.mouseGetEventDWheel(); + } + + public static int getEventX() { + return PlatformInput.mouseGetEventX(); + } + + public static int getEventY() { + return PlatformInput.mouseGetEventY(); + } + + public static int getX() { + return PlatformInput.mouseGetX(); + } + + public static int getY() { + return PlatformInput.mouseGetY(); } public static boolean isActuallyGrabbed() { return PlatformInput.isPointerLocked(); } + public static boolean isButtonDown(int i) { + return PlatformInput.mouseIsButtonDown(i); + } + + public static boolean isCreated() { + return true; + } + + public static boolean isInsideWindow() { + return PlatformInput.mouseIsInsideWindow(); + } + public static boolean isMouseGrabbed() { return PlatformInput.isMouseGrabbed(); } @@ -97,25 +102,22 @@ public class Mouse { return PlatformInput.mouseGrabSupported(); } - public static void fireMoveEvent(EnumFireMouseEvent eventType, int posX, int posY) { - PlatformInput.mouseFireMoveEvent(eventType, posX, posY); + public static boolean next() { + return PlatformInput.mouseNext(); } - public static void fireButtonEvent(EnumFireMouseEvent eventType, int posX, int posY, int button) { - PlatformInput.mouseFireButtonEvent(eventType, posX, posY, button); + public static void setCursorPosition(int x, int y) { + PlatformInput.mouseSetCursorPosition(x, y); } - public static void fireWheelEvent(EnumFireMouseEvent eventType, int posX, int posY, float wheel) { - PlatformInput.mouseFireWheelEvent(eventType, posX, posY, wheel); + public static void setGrabbed(boolean grab) { + PlatformInput.mouseSetGrabbed(grab); } - private static int customCursorCounter = 0; - private static EnumCursorType currentCursorType = EnumCursorType.DEFAULT; - public static void showCursor(EnumCursorType cursor) { - if(EagRuntime.getConfiguration().useSpecialCursors()) { + if (EagRuntime.getConfiguration().useSpecialCursors()) { customCursorCounter = 2; - if(currentCursorType != cursor) { + if (currentCursorType != cursor) { PlatformInput.showCursor(cursor); currentCursorType = cursor; } @@ -123,10 +125,10 @@ public class Mouse { } public static void tickCursorShape() { - if(EagRuntime.getConfiguration().useSpecialCursors()) { - if(customCursorCounter > 0) { - if(--customCursorCounter == 0) { - if(currentCursorType != EnumCursorType.DEFAULT) { + if (EagRuntime.getConfiguration().useSpecialCursors()) { + if (customCursorCounter > 0) { + if (--customCursorCounter == 0) { + if (currentCursorType != EnumCursorType.DEFAULT) { PlatformInput.showCursor(EnumCursorType.DEFAULT); currentCursorType = EnumCursorType.DEFAULT; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/PauseMenuCustomizeState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/PauseMenuCustomizeState.java index 3dc81252..ec8e1520 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/PauseMenuCustomizeState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/PauseMenuCustomizeState.java @@ -19,22 +19,34 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PauseMenuCustomizeState { - private static final Logger logger = LogManager.getLogger("PauseMenuCustomizeState"); + private static class PauseMenuSprite { + private final ResourceLocation loc; + private final EaglerSkinTexture tex; + + public PauseMenuSprite(EaglerSkinTexture tex) { + this.loc = newLoc(); + this.tex = tex; + } + + } + + private static final Logger logger = LogManager.getLogger("PauseMenuCustomizeState"); public static ResourceLocation icon_title_L; public static float icon_title_L_aspect = 1.0f; public static ResourceLocation icon_title_R; @@ -74,52 +86,70 @@ public class PauseMenuCustomizeState { public static ResourceLocation icon_watermark_pause; public static float icon_watermark_pause_aspect = 1.0f; public static ResourceLocation icon_watermark_all; - public static float icon_watermark_all_aspect = 1.0f; + public static float icon_watermark_all_aspect = 1.0f; public static final int SERVER_INFO_MODE_NONE = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_MODE_NONE; public static final int SERVER_INFO_MODE_EXTERNAL_URL = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_MODE_EXTERNAL_URL; public static final int SERVER_INFO_MODE_SHOW_EMBED_OVER_HTTP = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_MODE_SHOW_EMBED_OVER_HTTP; - public static final int SERVER_INFO_MODE_SHOW_EMBED_OVER_WS = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_MODE_SHOW_EMBED_OVER_WS; + public static final int SERVER_INFO_MODE_SHOW_EMBED_OVER_WS = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_MODE_SHOW_EMBED_OVER_WS; public static final int SERVER_INFO_EMBED_PERMS_JAVASCRIPT = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_EMBED_PERMS_JAVASCRIPT; public static final int SERVER_INFO_EMBED_PERMS_MESSAGE_API = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_EMBED_PERMS_MESSAGE_API; + public static final int SERVER_INFO_EMBED_PERMS_STRICT_CSP = SPacketCustomizePauseMenuV4EAG.SERVER_INFO_EMBED_PERMS_STRICT_CSP; - public static final int DISCORD_MODE_NONE = SPacketCustomizePauseMenuV4EAG.DISCORD_MODE_NONE; - public static final int DISCORD_MODE_INVITE_URL = SPacketCustomizePauseMenuV4EAG.DISCORD_MODE_INVITE_URL; + public static final int DISCORD_MODE_INVITE_URL = SPacketCustomizePauseMenuV4EAG.DISCORD_MODE_INVITE_URL; public static int serverInfoMode; public static int serverInfoEmbedPerms = SERVER_INFO_EMBED_PERMS_STRICT_CSP; public static String serverInfoEmbedTitle; public static String serverInfoButtonText; public static String serverInfoURL; - public static byte[] serverInfoHash; + public static byte[] serverInfoHash; public static int discordButtonMode; public static String discordButtonText; + public static String discordInviteURL; private static final List toFree = new ArrayList<>(); private static int textureId = 0; - private static class PauseMenuSprite { - - private final ResourceLocation loc; - private final EaglerSkinTexture tex; - - public PauseMenuSprite(EaglerSkinTexture tex) { - this.loc = newLoc(); - this.tex = tex; + private static ResourceLocation cacheLoadHelperFunction(String name, Map lookup, + Map spriteCache, List sourceData, Consumer aspectCB) { + Integer i = lookup.get(name); + if (i == null) { + return null; } - + PauseMenuSprite ret = spriteCache.get(i); + if (ret != null) { + if (name.startsWith("icon_background_") + && ImageData.isNPOTStatic(ret.tex.getWidth(), ret.tex.getHeight())) { + logger.warn( + "An NPOT (non-power-of-two) texture was used for \"{}\", this texture's width and height must be powers of two for this texture to display properly on all hardware"); + } + aspectCB.accept((float) ret.tex.getWidth() / ret.tex.getHeight()); + return ret.loc; + } + int ii = i.intValue(); + if (ii < 0 || ii >= sourceData.size()) { + return null; + } + PacketImageData data = sourceData.get(ii); + ret = new PauseMenuSprite(new EaglerSkinTexture(ImageData.swapRB(data.rgba), data.width, data.height)); + Minecraft.getMinecraft().getTextureManager().loadTexture(ret.loc, ret.tex); + spriteCache.put(i, ret); + toFree.add(ret); + aspectCB.accept((float) data.width / data.height); + return ret.loc; } public static void loadPacket(SPacketCustomizePauseMenuV4EAG packet) { reset(); - + serverInfoMode = packet.serverInfoMode; - switch(packet.serverInfoMode) { + switch (packet.serverInfoMode) { case SERVER_INFO_MODE_NONE: default: serverInfoButtonText = null; @@ -143,9 +173,9 @@ public class PauseMenuCustomizeState { serverInfoEmbedTitle = packet.serverInfoEmbedTitle; break; } - + discordButtonMode = packet.discordButtonMode; - switch(packet.discordButtonMode) { + switch (packet.discordButtonMode) { case DISCORD_MODE_NONE: default: discordButtonText = null; @@ -157,58 +187,50 @@ public class PauseMenuCustomizeState { discordInviteURL = packet.discordInviteURL; break; } - - if(packet.imageMappings != null) { - Map spriteCache = new HashMap<>(); - icon_title_L = cacheLoadHelperFunction("icon_title_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_title_L_aspect = a); - icon_title_R = cacheLoadHelperFunction("icon_title_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_title_R_aspect = a); - icon_backToGame_L = cacheLoadHelperFunction("icon_backToGame_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_backToGame_L_aspect = a); - icon_backToGame_R = cacheLoadHelperFunction("icon_backToGame_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_backToGame_R_aspect = a); - icon_achievements_L = cacheLoadHelperFunction("icon_achievements_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_achievements_L_aspect = a); - icon_achievements_R = cacheLoadHelperFunction("icon_achievements_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_achievements_R_aspect = a); - icon_statistics_L = cacheLoadHelperFunction("icon_statistics_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_statistics_L_aspect = a); - icon_statistics_R = cacheLoadHelperFunction("icon_statistics_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_statistics_R_aspect = a); - icon_serverInfo_L = cacheLoadHelperFunction("icon_serverInfo_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_serverInfo_L_aspect = a); - icon_serverInfo_R = cacheLoadHelperFunction("icon_serverInfo_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_serverInfo_R_aspect = a); - icon_options_L = cacheLoadHelperFunction("icon_options_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_options_L_aspect = a); - icon_options_R = cacheLoadHelperFunction("icon_options_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_options_R_aspect = a); - icon_discord_L = cacheLoadHelperFunction("icon_discord_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_discord_L_aspect = a); - icon_discord_R = cacheLoadHelperFunction("icon_discord_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_discord_R_aspect = a); - icon_disconnect_L = cacheLoadHelperFunction("icon_disconnect_L", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_disconnect_L_aspect = a); - icon_disconnect_R = cacheLoadHelperFunction("icon_disconnect_R", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_disconnect_R_aspect = a); - icon_background_pause = cacheLoadHelperFunction("icon_background_pause", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_background_pause_aspect = a); - icon_background_all = cacheLoadHelperFunction("icon_background_all", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_background_all_aspect = a); - icon_watermark_pause = cacheLoadHelperFunction("icon_watermark_pause", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_watermark_pause_aspect = a); - icon_watermark_all = cacheLoadHelperFunction("icon_watermark_all", packet.imageMappings, spriteCache, packet.imageData, (a) -> icon_watermark_all_aspect = a); - } - } - private static ResourceLocation cacheLoadHelperFunction(String name, Map lookup, - Map spriteCache, - List sourceData, Consumer aspectCB) { - Integer i = lookup.get(name); - if(i == null) { - return null; + if (packet.imageMappings != null) { + Map spriteCache = new HashMap<>(); + icon_title_L = cacheLoadHelperFunction("icon_title_L", packet.imageMappings, spriteCache, packet.imageData, + (a) -> icon_title_L_aspect = a); + icon_title_R = cacheLoadHelperFunction("icon_title_R", packet.imageMappings, spriteCache, packet.imageData, + (a) -> icon_title_R_aspect = a); + icon_backToGame_L = cacheLoadHelperFunction("icon_backToGame_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_backToGame_L_aspect = a); + icon_backToGame_R = cacheLoadHelperFunction("icon_backToGame_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_backToGame_R_aspect = a); + icon_achievements_L = cacheLoadHelperFunction("icon_achievements_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_achievements_L_aspect = a); + icon_achievements_R = cacheLoadHelperFunction("icon_achievements_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_achievements_R_aspect = a); + icon_statistics_L = cacheLoadHelperFunction("icon_statistics_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_statistics_L_aspect = a); + icon_statistics_R = cacheLoadHelperFunction("icon_statistics_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_statistics_R_aspect = a); + icon_serverInfo_L = cacheLoadHelperFunction("icon_serverInfo_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_serverInfo_L_aspect = a); + icon_serverInfo_R = cacheLoadHelperFunction("icon_serverInfo_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_serverInfo_R_aspect = a); + icon_options_L = cacheLoadHelperFunction("icon_options_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_options_L_aspect = a); + icon_options_R = cacheLoadHelperFunction("icon_options_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_options_R_aspect = a); + icon_discord_L = cacheLoadHelperFunction("icon_discord_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_discord_L_aspect = a); + icon_discord_R = cacheLoadHelperFunction("icon_discord_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_discord_R_aspect = a); + icon_disconnect_L = cacheLoadHelperFunction("icon_disconnect_L", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_disconnect_L_aspect = a); + icon_disconnect_R = cacheLoadHelperFunction("icon_disconnect_R", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_disconnect_R_aspect = a); + icon_background_pause = cacheLoadHelperFunction("icon_background_pause", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_background_pause_aspect = a); + icon_background_all = cacheLoadHelperFunction("icon_background_all", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_background_all_aspect = a); + icon_watermark_pause = cacheLoadHelperFunction("icon_watermark_pause", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_watermark_pause_aspect = a); + icon_watermark_all = cacheLoadHelperFunction("icon_watermark_all", packet.imageMappings, spriteCache, + packet.imageData, (a) -> icon_watermark_all_aspect = a); } - PauseMenuSprite ret = spriteCache.get(i); - if(ret != null) { - if(name.startsWith("icon_background_") && ImageData.isNPOTStatic(ret.tex.getWidth(), ret.tex.getHeight())) { - logger.warn("An NPOT (non-power-of-two) texture was used for \"{}\", this texture's width and height must be powers of two for this texture to display properly on all hardware"); - } - aspectCB.accept((float)ret.tex.getWidth() / ret.tex.getHeight()); - return ret.loc; - } - int ii = i.intValue(); - if(ii < 0 || ii >= sourceData.size()) { - return null; - } - PacketImageData data = sourceData.get(ii); - ret = new PauseMenuSprite(new EaglerSkinTexture(ImageData.swapRB(data.rgba), data.width, data.height)); - Minecraft.getMinecraft().getTextureManager().loadTexture(ret.loc, ret.tex); - spriteCache.put(i, ret); - toFree.add(ret); - aspectCB.accept((float)data.width / data.height); - return ret.loc; } private static ResourceLocation newLoc() { @@ -245,9 +267,9 @@ public class PauseMenuCustomizeState { discordButtonMode = 0; discordButtonText = null; discordInviteURL = null; - if(!toFree.isEmpty()) { + if (!toFree.isEmpty()) { TextureManager mgr = Minecraft.getMinecraft().getTextureManager(); - for(PauseMenuSprite rc : toFree) { + for (PauseMenuSprite rc : toFree) { mgr.deleteTexture(rc.loc); } toFree.clear(); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/PointerInputAbstraction.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/PointerInputAbstraction.java index c3ed1ca2..7a5bd953 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/PointerInputAbstraction.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/PointerInputAbstraction.java @@ -6,14 +6,15 @@ import net.minecraft.client.Minecraft; /** * Copyright (c) 2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,6 +41,50 @@ public class PointerInputAbstraction { protected static boolean draggingNotTouching = false; protected static boolean touchMode = false; + public static void enterMouseModeHook() { + if (touchMode) { + touchMode = false; + touchingScreen = false; + touchingScreenNotButton = false; + if (mc.inGameHasFocus && mc.mouseGrabSupported) { + mc.mouseHelper.grabMouseCursor(); + } + } + } + + public static void enterTouchModeHook() { + if (!touchMode) { + touchMode = true; + if (mc.mouseGrabSupported) { + mc.mouseHelper.ungrabMouseCursor(); + } + } + } + + public static boolean getVCursorButtonDown(int bt) { + return (touchingScreenNotButton && bt == 0) || Mouse.isButtonDown(bt); + } + + public static int getVCursorDX() { + int tmp = cursorDX; + cursorDX = 0; + return tmp; + } + + public static int getVCursorDY() { + int tmp = cursorDY; + cursorDY = 0; + return tmp; + } + + public static int getVCursorX() { + return cursorX; + } + + public static int getVCursorY() { + return cursorY; + } + public static void init(Minecraft mcIn) { mc = mcIn; oldMX = -1; @@ -61,10 +106,26 @@ public class PointerInputAbstraction { touchMode = !mcIn.mouseGrabSupported; } + public static boolean isDraggingNotTouching() { + return draggingNotTouching; + } + + public static boolean isTouchingScreen() { + return touchingScreen; + } + + public static boolean isTouchingScreenNotButton() { + return touchingScreenNotButton; + } + + public static boolean isTouchMode() { + return touchMode; + } + public static void runGameLoop() { - if(touchMode) { + if (touchMode) { runTouchUpdate(); - }else { + } else { oldTX = -1; oldTY = -1; cursorX = oldMX = Mouse.getX(); @@ -74,22 +135,51 @@ public class PointerInputAbstraction { } } + private static void runTouchDeltaUpdate(int uid) { + if (uid != dragUID) { + dragStartX = oldTX; + dragStartY = oldTY; + dragStepStartX = -1; + dragStepStartY = -1; + dragUID = uid; + draggingNotTouching = false; + return; + } + if (dragStepStartX != -1) { + cursorDX += oldTX - dragStepStartX; + } + dragStepStartX = oldTX; + if (dragStepStartY != -1) { + cursorDY += oldTY - dragStepStartY; + } + dragStepStartY = oldTY; + if (dragStartX != -1 && dragStartY != -1) { + int dx = oldTX - dragStartX; + int dy = oldTY - dragStartY; + int len = dx * dx + dy * dy; + int dm = Math.max((int) (6 * Display.getDPI()), 2); + if (len > dm * dm) { + draggingNotTouching = true; + } + } + } + private static void runTouchUpdate() { int tc = Touch.touchPointCount(); if (tc > 0) { TouchControls.update(true); touchingScreen = true; - for(int i = 0; i < tc; ++i) { + for (int i = 0; i < tc; ++i) { int uid = Touch.touchPointUID(i); - if(TouchControls.touchControls.containsKey(uid)) { + if (TouchControls.touchControls.containsKey(uid)) { continue; } int tx = Touch.touchPointX(i); int ty = Touch.touchPointY(i); - if(TouchControls.overlappingControl(tx, ty) != null) { + if (TouchControls.overlappingControl(tx, ty) != null) { continue; } - if(mc.currentScreen == null && mc.ingameGUI.isTouchOverlapEagler(uid, tx, ty)) { + if (mc.currentScreen == null && mc.ingameGUI.isTouchOverlapEagler(uid, tx, ty)) { continue; } cursorX = oldTX = tx; @@ -112,7 +202,7 @@ public class PointerInputAbstraction { dragUID = -1; final int tmp = Mouse.getX(); final int tmp2 = Mouse.getY(); - if(oldTX == -1 || oldTY == -1) { + if (oldTX == -1 || oldTY == -1) { cursorX = oldMX = tmp; cursorY = oldMY = tmp2; cursorDX += Mouse.getDX(); @@ -126,7 +216,7 @@ public class PointerInputAbstraction { if (oldMX == tmp && oldMY == tmp2) { cursorX = oldTX; cursorY = oldTY; - }else { + } else { cursorX = oldMX = tmp; cursorY = oldMY = tmp2; cursorDX += Mouse.getDX(); @@ -135,93 +225,4 @@ public class PointerInputAbstraction { } } - private static void runTouchDeltaUpdate(int uid) { - if(uid != dragUID) { - dragStartX = oldTX; - dragStartY = oldTY; - dragStepStartX = -1; - dragStepStartY = -1; - dragUID = uid; - draggingNotTouching = false; - return; - } - if(dragStepStartX != -1) { - cursorDX += oldTX - dragStepStartX; - } - dragStepStartX = oldTX; - if(dragStepStartY != -1) { - cursorDY += oldTY - dragStepStartY; - } - dragStepStartY = oldTY; - if(dragStartX != -1 && dragStartY != -1) { - int dx = oldTX - dragStartX; - int dy = oldTY - dragStartY; - int len = dx * dx + dy * dy; - int dm = Math.max((int)(6 * Display.getDPI()), 2); - if(len > dm * dm) { - draggingNotTouching = true; - } - } - } - - public static boolean isTouchMode() { - return touchMode; - } - - public static boolean isTouchingScreen() { - return touchingScreen; - } - - public static boolean isTouchingScreenNotButton() { - return touchingScreenNotButton; - } - - public static boolean isDraggingNotTouching() { - return draggingNotTouching; - } - - public static void enterTouchModeHook() { - if(!touchMode) { - touchMode = true; - if(mc.mouseGrabSupported) { - mc.mouseHelper.ungrabMouseCursor(); - } - } - } - - public static void enterMouseModeHook() { - if(touchMode) { - touchMode = false; - touchingScreen = false; - touchingScreenNotButton = false; - if(mc.inGameHasFocus && mc.mouseGrabSupported) { - mc.mouseHelper.grabMouseCursor(); - } - } - } - - public static int getVCursorX() { - return cursorX; - } - - public static int getVCursorY() { - return cursorY; - } - - public static int getVCursorDX() { - int tmp = cursorDX; - cursorDX = 0; - return tmp; - } - - public static int getVCursorDY() { - int tmp = cursorDY; - cursorDY = 0; - return tmp; - } - - public static boolean getVCursorButtonDown(int bt) { - return (touchingScreenNotButton && bt == 0) || Mouse.isButtonDown(bt); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/ThreadLocalRandom.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/ThreadLocalRandom.java index 57ef6d3c..f61d88b1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/ThreadLocalRandom.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/ThreadLocalRandom.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -22,5 +23,5 @@ public class ThreadLocalRandom { public static EaglercraftRandom current() { return rand; } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/Touch.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/Touch.java index eb27322d..66816f18 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/Touch.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/Touch.java @@ -6,38 +6,63 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Touch { - public static boolean next() { - return PlatformInput.touchNext(); + public static boolean checkPointTouching(int uid) { + int cnt = PlatformInput.touchPointCount(); + if (cnt > 0) { + for (int i = 0; i < cnt; ++i) { + if (PlatformInput.touchPointUID(i) == uid) { + return true; + } + } + } + return false; } - public static EnumTouchEvent getEventType() { - return PlatformInput.touchGetEventType(); + public static void closeDeviceKeyboard() { + PlatformInput.touchCloseDeviceKeyboard(); + } + + public static int fetchPointIdx(int uid) { + int cnt = PlatformInput.touchPointCount(); + if (cnt > 0) { + for (int i = 0; i < cnt; ++i) { + if (PlatformInput.touchPointUID(i) == uid) { + return i; + } + } + } + return -1; + } + + public static float getEventTouchForce(int pointId) { + return PlatformInput.touchGetEventTouchForce(pointId); } public static int getEventTouchPointCount() { return PlatformInput.touchGetEventTouchPointCount(); } - public static int getEventTouchX(int pointId) { - return PlatformInput.touchGetEventTouchX(pointId); + public static int getEventTouchPointUID(int pointId) { + return PlatformInput.touchGetEventTouchPointUID(pointId); } - public static int getEventTouchY(int pointId) { - return PlatformInput.touchGetEventTouchY(pointId); + public static float getEventTouchRadiusMixed(int pointId) { + return PlatformInput.touchGetEventTouchRadiusMixed(pointId); } public static float getEventTouchRadiusX(int pointId) { @@ -48,28 +73,40 @@ public class Touch { return PlatformInput.touchGetEventTouchRadiusY(pointId); } - public static float getEventTouchRadiusMixed(int pointId) { - return PlatformInput.touchGetEventTouchRadiusMixed(pointId); + public static int getEventTouchX(int pointId) { + return PlatformInput.touchGetEventTouchX(pointId); } - public static float getEventTouchForce(int pointId) { - return PlatformInput.touchGetEventTouchForce(pointId); + public static int getEventTouchY(int pointId) { + return PlatformInput.touchGetEventTouchY(pointId); } - public static int getEventTouchPointUID(int pointId) { - return PlatformInput.touchGetEventTouchPointUID(pointId); + public static EnumTouchEvent getEventType() { + return PlatformInput.touchGetEventType(); + } + + public static String getPastedString() { + return PlatformInput.touchGetPastedString(); + } + + public static boolean isDeviceKeyboardOpenMAYBE() { + return PlatformInput.touchIsDeviceKeyboardOpenMAYBE(); + } + + public static boolean next() { + return PlatformInput.touchNext(); } public static int touchPointCount() { return PlatformInput.touchPointCount(); } - public static int touchPointX(int pointId) { - return PlatformInput.touchPointX(pointId); + public static float touchPointForce(int pointId) { + return PlatformInput.touchForce(pointId); } - public static int touchPointY(int pointId) { - return PlatformInput.touchPointY(pointId); + public static float touchPointRadiusMixed(int pointId) { + return PlatformInput.touchRadiusMixed(pointId); } public static float touchPointRadiusX(int pointId) { @@ -80,55 +117,19 @@ public class Touch { return PlatformInput.touchRadiusY(pointId); } - public static float touchPointRadiusMixed(int pointId) { - return PlatformInput.touchRadiusMixed(pointId); - } - - public static float touchPointForce(int pointId) { - return PlatformInput.touchForce(pointId); - } - public static int touchPointUID(int pointId) { return PlatformInput.touchPointUID(pointId); } + public static int touchPointX(int pointId) { + return PlatformInput.touchPointX(pointId); + } + + public static int touchPointY(int pointId) { + return PlatformInput.touchPointY(pointId); + } + public static void touchSetOpenKeyboardZone(int x, int y, int w, int h) { PlatformInput.touchSetOpenKeyboardZone(x, y, w, h); } - - public static void closeDeviceKeyboard() { - PlatformInput.touchCloseDeviceKeyboard(); - } - - public static boolean isDeviceKeyboardOpenMAYBE() { - return PlatformInput.touchIsDeviceKeyboardOpenMAYBE(); - } - - public static String getPastedString() { - return PlatformInput.touchGetPastedString(); - } - - public static boolean checkPointTouching(int uid) { - int cnt = PlatformInput.touchPointCount(); - if(cnt > 0) { - for(int i = 0; i < cnt; ++i) { - if(PlatformInput.touchPointUID(i) == uid) { - return true; - } - } - } - return false; - } - - public static int fetchPointIdx(int uid) { - int cnt = PlatformInput.touchPointCount(); - if(cnt > 0) { - for(int i = 0; i < cnt; ++i) { - if(PlatformInput.touchPointUID(i) == uid) { - return i; - } - } - } - return -1; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/boot_menu/GuiScreenEnterBootMenu.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/boot_menu/GuiScreenEnterBootMenu.java index e5f5b6c5..2fdfb7ff 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/boot_menu/GuiScreenEnterBootMenu.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/boot_menu/GuiScreenEnterBootMenu.java @@ -8,14 +8,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,6 +29,19 @@ public class GuiScreenEnterBootMenu extends GuiScreen { this.parent = parent; } + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + this.mc.displayGuiScreen(parent); + } + } + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, I18n.format("enterBootMenu.title"), this.width / 2, 70, 11184810); + this.drawCenteredString(fontRendererObj, I18n.format("enterBootMenu.text0"), this.width / 2, 90, 16777215); + super.drawScreen(par1, par2, par3); + } + public void initGui() { EagRuntime.setDisplayBootMenuNextRefresh(true); this.buttonList.clear(); @@ -38,17 +52,4 @@ public class GuiScreenEnterBootMenu extends GuiScreen { EagRuntime.setDisplayBootMenuNextRefresh(false); } - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, I18n.format("enterBootMenu.title"), this.width / 2, 70, 11184810); - this.drawCenteredString(fontRendererObj, I18n.format("enterBootMenu.text0"), this.width / 2, 90, 16777215); - super.drawScreen(par1, par2, par3); - } - - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - this.mc.displayGuiScreen(parent); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerCacheProvider.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerCacheProvider.java index 13f11769..d098d8ef 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerCacheProvider.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerCacheProvider.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.cache; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerLoadingCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerLoadingCache.java index 54d55a00..5c88b440 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerLoadingCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cache/EaglerLoadingCache.java @@ -6,14 +6,15 @@ import java.util.Map; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,7 +31,7 @@ public class EaglerLoadingCache { public V get(K key) { V etr = cacheMap.get(key); - if(etr == null) { + if (etr == null) { etr = provider.create(key); cacheMap.put(key, etr); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenInspectSessionToken.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenInspectSessionToken.java index ea9897cb..f41c9a96 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenInspectSessionToken.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenInspectSessionToken.java @@ -11,14 +11,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,39 +34,35 @@ public class GuiScreenInspectSessionToken extends GuiScreen { this.cookie = cookie; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 106, I18n.format("gui.done"))); + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + this.mc.displayGuiScreen(parent); + } } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); String[][] toDraw = new String[][] { - { - I18n.format("inspectSessionToken.details.server"), - I18n.format("inspectSessionToken.details.expires"), - I18n.format("inspectSessionToken.details.length") - }, - { - cookie.server.length() > 32 ? cookie.server.substring(0, 30) + "..." : cookie.server, - (new SimpleDateFormat("M/d/yyyy h:mm aa")).format(new Date(cookie.expires)), - Integer.toString(cookie.cookie.length) - } - }; + { I18n.format("inspectSessionToken.details.server"), I18n.format("inspectSessionToken.details.expires"), + I18n.format("inspectSessionToken.details.length") }, + { cookie.server.length() > 32 ? cookie.server.substring(0, 30) + "..." : cookie.server, + (new SimpleDateFormat("M/d/yyyy h:mm aa")).format(new Date(cookie.expires)), + Integer.toString(cookie.cookie.length) } }; int[] maxWidth = new int[2]; - for(int i = 0; i < 2; ++i) { + for (int i = 0; i < 2; ++i) { String[] strs = toDraw[i]; int w = 0; - for(int j = 0; j < strs.length; ++j) { + for (int j = 0; j < strs.length; ++j) { int k = fontRendererObj.getStringWidth(strs[j]); - if(k > w) { + if (k > w) { w = k; } } maxWidth[i] = w + 10; } int totalWidth = maxWidth[0] + maxWidth[1]; - this.drawCenteredString(fontRendererObj, I18n.format("inspectSessionToken.title"), this.width / 2, 70, 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("inspectSessionToken.title"), this.width / 2, 70, + 16777215); this.drawString(fontRendererObj, toDraw[0][0], (this.width - totalWidth) / 2, 90, 11184810); this.drawString(fontRendererObj, toDraw[0][1], (this.width - totalWidth) / 2, 104, 11184810); this.drawString(fontRendererObj, toDraw[0][2], (this.width - totalWidth) / 2, 118, 11184810); @@ -75,10 +72,9 @@ public class GuiScreenInspectSessionToken extends GuiScreen { super.drawScreen(par1, par2, par3); } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - this.mc.displayGuiScreen(parent); - } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 106, I18n.format("gui.done"))); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenRevokeSessionToken.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenRevokeSessionToken.java index 6d42d00c..bf4436fb 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenRevokeSessionToken.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenRevokeSessionToken.java @@ -14,36 +14,116 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenRevokeSessionToken extends GuiScreen { + class List extends GuiSlot { + private final java.util.List cookieNames = Lists.newArrayList(); + + public List(Minecraft mcIn) { + super(mcIn, GuiScreenRevokeSessionToken.this.width, GuiScreenRevokeSessionToken.this.height, 32, + GuiScreenRevokeSessionToken.this.height - 75 + 4, 18); + ServerCookieDataStore.flush(); + cookieNames.addAll(ServerCookieDataStore.getRevokableServers()); + Collections.sort(cookieNames); + } + + protected void drawBackground() { + GuiScreenRevokeSessionToken.this.drawDefaultBackground(); + } + + protected void drawSlot(int i, int var2, int j, int var4, int var5, int var6) { + GuiScreenRevokeSessionToken.this.drawCenteredString(GuiScreenRevokeSessionToken.this.fontRendererObj, + this.cookieNames.get(i), this.width / 2, j + 1, 16777215); + } + + protected void elementClicked(int i, boolean var2, int var3, int var4) { + selectedElement = i; + GuiScreenRevokeSessionToken.this.updateButtons(); + } + + protected int getContentHeight() { + return this.getSize() * 18; + } + + protected String getSelectedItem() { + return selectedElement == -1 ? null : cookieNames.get(selectedElement); + } + + protected int getSize() { + return this.cookieNames.size(); + } + + protected boolean isSelected(int i) { + return selectedElement == i; + } + } + protected GuiScreen parentScreen; private GuiScreenRevokeSessionToken.List list; private GuiButton inspectButton; + private GuiButton revokeButton; public GuiScreenRevokeSessionToken(GuiScreen parent) { this.parentScreen = parent; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(this.inspectButton = new GuiButton(10, this.width / 2 - 154, this.height - 38, 100, 20, I18n.format("revokeSessionToken.inspect"))); - this.buttonList.add(this.revokeButton = new GuiButton(9, this.width / 2 - 50, this.height - 38, 100, 20, I18n.format("revokeSessionToken.revoke"))); - this.buttonList.add(new GuiButton(6, this.width / 2 + 54, this.height - 38, 100, 20, I18n.format("gui.done"))); - this.list = new GuiScreenRevokeSessionToken.List(this.mc); - this.list.registerScrollButtons(7, 8); - updateButtons(); + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.enabled) { + switch (parGuiButton.id) { + case 6: + this.mc.displayGuiScreen(this.parentScreen); + break; + case 9: + String s1 = list.getSelectedItem(); + if (s1 != null) { + ServerCookieDataStore.ServerCookie cookie = ServerCookieDataStore.loadCookie(s1); + if (cookie != null) { + this.mc.displayGuiScreen(new GuiScreenSendRevokeRequest(this, cookie)); + } else { + this.initGui(); + } + } + break; + case 10: + String s2 = list.getSelectedItem(); + if (s2 != null) { + ServerCookieDataStore.ServerCookie cookie = ServerCookieDataStore.loadCookie(s2); + if (cookie != null) { + this.mc.displayGuiScreen(new GuiScreenInspectSessionToken(this, cookie)); + } else { + this.initGui(); + } + } + break; + default: + this.list.actionPerformed(parGuiButton); + } + + } + } + + public void drawScreen(int i, int j, float f) { + this.list.drawScreen(i, j, f); + this.drawCenteredString(this.fontRendererObj, I18n.format("revokeSessionToken.title"), this.width / 2, 16, + 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("revokeSessionToken.note.0"), this.width / 2, + this.height - 66, 8421504); + this.drawCenteredString(this.fontRendererObj, I18n.format("revokeSessionToken.note.1"), this.width / 2, + this.height - 56, 8421504); + super.drawScreen(i, j, f); } public void handleMouseInput() throws IOException { @@ -56,91 +136,19 @@ public class GuiScreenRevokeSessionToken extends GuiScreen { this.list.handleTouchInput(); } - protected void actionPerformed(GuiButton parGuiButton) { - if (parGuiButton.enabled) { - switch (parGuiButton.id) { - case 6: - this.mc.displayGuiScreen(this.parentScreen); - break; - case 9: - String s1 = list.getSelectedItem(); - if(s1 != null) { - ServerCookieDataStore.ServerCookie cookie = ServerCookieDataStore.loadCookie(s1); - if(cookie != null) { - this.mc.displayGuiScreen(new GuiScreenSendRevokeRequest(this, cookie)); - }else { - this.initGui(); - } - } - break; - case 10: - String s2 = list.getSelectedItem(); - if(s2 != null) { - ServerCookieDataStore.ServerCookie cookie = ServerCookieDataStore.loadCookie(s2); - if(cookie != null) { - this.mc.displayGuiScreen(new GuiScreenInspectSessionToken(this, cookie)); - }else { - this.initGui(); - } - } - break; - default: - this.list.actionPerformed(parGuiButton); - } - - } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(this.inspectButton = new GuiButton(10, this.width / 2 - 154, this.height - 38, 100, 20, + I18n.format("revokeSessionToken.inspect"))); + this.buttonList.add(this.revokeButton = new GuiButton(9, this.width / 2 - 50, this.height - 38, 100, 20, + I18n.format("revokeSessionToken.revoke"))); + this.buttonList.add(new GuiButton(6, this.width / 2 + 54, this.height - 38, 100, 20, I18n.format("gui.done"))); + this.list = new GuiScreenRevokeSessionToken.List(this.mc); + this.list.registerScrollButtons(7, 8); + updateButtons(); } protected void updateButtons() { inspectButton.enabled = revokeButton.enabled = list.getSelectedItem() != null; } - - public void drawScreen(int i, int j, float f) { - this.list.drawScreen(i, j, f); - this.drawCenteredString(this.fontRendererObj, I18n.format("revokeSessionToken.title"), this.width / 2, 16, 16777215); - this.drawCenteredString(this.fontRendererObj, I18n.format("revokeSessionToken.note.0"), this.width / 2, this.height - 66, 8421504); - this.drawCenteredString(this.fontRendererObj, I18n.format("revokeSessionToken.note.1"), this.width / 2, this.height - 56, 8421504); - super.drawScreen(i, j, f); - } - - class List extends GuiSlot { - private final java.util.List cookieNames = Lists.newArrayList(); - - public List(Minecraft mcIn) { - super(mcIn, GuiScreenRevokeSessionToken.this.width, GuiScreenRevokeSessionToken.this.height, 32, GuiScreenRevokeSessionToken.this.height - 75 + 4, 18); - ServerCookieDataStore.flush(); - cookieNames.addAll(ServerCookieDataStore.getRevokableServers()); - Collections.sort(cookieNames); - } - - protected int getSize() { - return this.cookieNames.size(); - } - - protected void elementClicked(int i, boolean var2, int var3, int var4) { - selectedElement = i; - GuiScreenRevokeSessionToken.this.updateButtons(); - } - - protected boolean isSelected(int i) { - return selectedElement == i; - } - - protected String getSelectedItem() { - return selectedElement == -1 ? null : cookieNames.get(selectedElement); - } - - protected int getContentHeight() { - return this.getSize() * 18; - } - - protected void drawBackground() { - GuiScreenRevokeSessionToken.this.drawDefaultBackground(); - } - - protected void drawSlot(int i, int var2, int j, int var4, int var5, int var6) { - GuiScreenRevokeSessionToken.this.drawCenteredString(GuiScreenRevokeSessionToken.this.fontRendererObj, - this.cookieNames.get(i), this.width / 2, j + 1, 16777215); - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenSendRevokeRequest.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenSendRevokeRequest.java index fb3b60d4..3149645a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenSendRevokeRequest.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/GuiScreenSendRevokeRequest.java @@ -16,14 +16,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,9 +49,11 @@ public class GuiScreenSendRevokeRequest extends GuiScreen { this.message = I18n.format("revokeSendingScreen.message.opening", cookie.server); } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("gui.cancel"))); + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + cancelRequested = true; + par1GuiButton.enabled = false; + } } public void drawScreen(int par1, int par2, float par3) { @@ -59,56 +62,67 @@ public class GuiScreenSendRevokeRequest extends GuiScreen { this.drawCenteredString(fontRendererObj, message, this.width / 2, 90, 16777215); super.drawScreen(par1, par2, par3); } - + + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("gui.cancel"))); + } + public void updateScreen() { ++timer; if (timer > 1) { - if(query == null) { + if (query == null) { logger.info("Attempting to revoke session tokens for: {}", cookie.server); query = ServerQueryDispatch.sendServerQuery(cookie.server, "revoke_session_token"); - if(query == null) { - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.connectionError", parent)); + if (query == null) { + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.connectionError", parent)); return; } - }else { + } else { query.update(); QueryResponse resp = query.getResponse(); - if(resp != null) { - if(resp.responseType.equalsIgnoreCase("revoke_session_token") && (hasSentPacket ? resp.isResponseJSON() : resp.isResponseString())) { - if(!hasSentPacket) { + if (resp != null) { + if (resp.responseType.equalsIgnoreCase("revoke_session_token") + && (hasSentPacket ? resp.isResponseJSON() : resp.isResponseString())) { + if (!hasSentPacket) { String str = resp.getResponseString(); - if("ready".equalsIgnoreCase(str)) { + if ("ready".equalsIgnoreCase(str)) { hasSentPacket = true; message = I18n.format("revokeSendingScreen.message.sending"); query.send(cookie.cookie); return; - }else { - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.clientError", parent)); + } else { + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.clientError", parent)); return; } - }else { + } else { JSONObject json = resp.getResponseJSON(); String stat = json.optString("status"); - if("ok".equalsIgnoreCase(stat)) { - if(hasSentPacket) { + if ("ok".equalsIgnoreCase(stat)) { + if (hasSentPacket) { query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeSuccess.title", "revokeSuccess.desc", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeSuccess.title", + "revokeSuccess.desc", parent)); ServerCookieDataStore.clearCookie(cookie.server); return; - }else { + } else { query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.clientError", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.clientError", parent)); return; } - }else if("error".equalsIgnoreCase(stat)) { + } else if ("error".equalsIgnoreCase(stat)) { int code = json.optInt("code", -1); - if(code == -1) { + if (code == -1) { query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.clientError", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.clientError", parent)); return; - }else { + } else { String key; - switch(code) { + switch (code) { case 1: key = "revokeFailure.desc.notSupported"; break; @@ -127,51 +141,50 @@ public class GuiScreenSendRevokeRequest extends GuiScreen { } logger.error("Recieved error code {}! ({})", code, key); query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", key, parent)); - if(json.optBoolean("delete", false)) { + this.mc.displayGuiScreen( + new GuiScreenGenericErrorMessage("revokeFailure.title", key, parent)); + if (json.optBoolean("delete", false)) { ServerCookieDataStore.clearCookie(cookie.server); } return; } - }else { + } else { logger.error("Recieved unknown status \"{}\"!", stat); query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.clientError", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.clientError", parent)); return; } } - }else { + } else { query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.clientError", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.clientError", parent)); return; } } - if(query.isClosed()) { - if(!hasSentPacket || query.responsesAvailable() == 0) { - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.connectionError", parent)); + if (query.isClosed()) { + if (!hasSentPacket || query.responsesAvailable() == 0) { + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.connectionError", parent)); return; } - }else { - if(timer > 400) { + } else { + if (timer > 400) { query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.connectionError", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.connectionError", parent)); return; } } - if(cancelRequested) { + if (cancelRequested) { query.close(); - this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", "revokeFailure.desc.cancelled", parent)); + this.mc.displayGuiScreen(new GuiScreenGenericErrorMessage("revokeFailure.title", + "revokeFailure.desc.cancelled", parent)); return; } } } } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - cancelRequested = true; - par1GuiButton.enabled = false; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/HardwareFingerprint.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/HardwareFingerprint.java index 8fd21769..0da31213 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/HardwareFingerprint.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/HardwareFingerprint.java @@ -1,5 +1,64 @@ package net.lax1dude.eaglercraft.v1_8.cookie; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetInteger; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameterf; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.checkAnisotropicFilteringSupport; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.getAllExtensions; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RENDERER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAX_ANISOTROPY; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VENDOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VIEWPORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT0; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_FRAMEBUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_HALF_FLOAT; + +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; + +import com.google.common.collect.Lists; + +import net.lax1dude.eaglercraft.v1_8.Base64; +import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; +import net.lax1dude.eaglercraft.v1_8.crypto.GeneralDigest; +import net.lax1dude.eaglercraft.v1_8.crypto.SHA256Digest; import net.lax1dude.eaglercraft.v1_8.internal.IFramebufferGL; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -16,39 +75,24 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; import net.lax1dude.eaglercraft.v1_8.opengl.VSHInputLayoutParser; import net.minecraft.client.renderer.texture.TextureUtil; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; - -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.List; - -import com.google.common.collect.Lists; - -import net.lax1dude.eaglercraft.v1_8.Base64; -import net.lax1dude.eaglercraft.v1_8.EagRuntime; -import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; -import net.lax1dude.eaglercraft.v1_8.crypto.GeneralDigest; -import net.lax1dude.eaglercraft.v1_8.crypto.SHA256Digest; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class HardwareFingerprint { - + // This is used for generating encryption keys for storing cookies, // its supposed to make session hijacking more difficult for skids @@ -60,30 +104,36 @@ public class HardwareFingerprint { public static final Logger logger = LogManager.getLogger("HardwareFingerprint"); - public static byte[] getFingerprint() { - if(fingerprint == null) { - try { - fingerprint = generateFingerprint(); - }catch(Throwable t) { - fingerprint = new byte[0]; - } - if(fingerprint.length == 0) { - logger.error("Failed to calculate hardware fingerprint, server cookies will not be encrypted!"); - } - } - return fingerprint; + private static void digestInts(GeneralDigest digest, int i1, int i2, int i3, int i4, byte[] tmpBuffer) { + tmpBuffer[0] = (byte) (i1 >>> 24); + tmpBuffer[1] = (byte) (i1 >>> 16); + tmpBuffer[2] = (byte) (i1 >>> 8); + tmpBuffer[3] = (byte) (i1 & 0xFF); + tmpBuffer[4] = (byte) (i2 >>> 24); + tmpBuffer[5] = (byte) (i2 >>> 16); + tmpBuffer[6] = (byte) (i2 >>> 8); + tmpBuffer[7] = (byte) (i2 & 0xFF); + tmpBuffer[8] = (byte) (i3 >>> 24); + tmpBuffer[9] = (byte) (i3 >>> 16); + tmpBuffer[10] = (byte) (i3 >>> 8); + tmpBuffer[11] = (byte) (i3 & 0xFF); + tmpBuffer[12] = (byte) (i4 >>> 24); + tmpBuffer[13] = (byte) (i4 >>> 16); + tmpBuffer[14] = (byte) (i4 >>> 8); + tmpBuffer[15] = (byte) (i4 & 0xFF); + digest.update(tmpBuffer, 0, 16); } private static byte[] generateFingerprint() { ImageData img = PlatformAssets.loadImageFile(Base64.decodeBase64(fingerprintIMG), "image/jpeg"); - if(img == null) { + if (img == null) { logger.error("Input image data is corrupt!"); return new byte[0]; } - + int[][] mipmapLevels = TextureUtil.generateMipmapData(7, 128, new int[][] { img.pixels, null, null, null, null, null, null, null }); - + int helperTexture = GlStateManager.generateTexture(); GlStateManager.bindTexture(helperTexture); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); @@ -91,64 +141,65 @@ public class HardwareFingerprint { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); TextureUtil.allocateTextureImpl(helperTexture, 7, 128, 128); TextureUtil.uploadTextureMipmap(mipmapLevels, 128, 128, 0, 0, false, false); - if(checkAnisotropicFilteringSupport()) { + if (checkAnisotropicFilteringSupport()) { _wglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY, 16.0f); } - + IShaderGL vert; List vertLayout; - if(DrawUtils.vshLocal != null) { + if (DrawUtils.vshLocal != null) { vert = DrawUtils.vshLocal; vertLayout = DrawUtils.vshLocalLayout; - }else { + } else { String vshLocalSrc = EagRuntime.getRequiredResourceString("/assets/eagler/glsl/local.vsh"); vertLayout = VSHInputLayoutParser.getShaderInputs(vshLocalSrc); vert = _wglCreateShader(GL_VERTEX_SHADER); _wglShaderSource(vert, GLSLHeader.getVertexHeaderCompat(vshLocalSrc, DrawUtils.vertexShaderPrecision)); _wglCompileShader(vert); - if(_wglGetShaderi(vert, GL_COMPILE_STATUS) != GL_TRUE) { + if (_wglGetShaderi(vert, GL_COMPILE_STATUS) != GL_TRUE) { _wglDeleteShader(vert); GlStateManager.deleteTexture(helperTexture); return new byte[0]; } } - + IShaderGL frag = _wglCreateShader(GL_FRAGMENT_SHADER); - _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(EagRuntime.getRequiredResourceString("/assets/eagler/glsl/hw_fingerprint.fsh"), shaderPrecision)); + _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat( + EagRuntime.getRequiredResourceString("/assets/eagler/glsl/hw_fingerprint.fsh"), shaderPrecision)); _wglCompileShader(frag); - if(_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { + if (_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { _wglDeleteShader(vert); _wglDeleteShader(frag); GlStateManager.deleteTexture(helperTexture); return new byte[0]; } - + IProgramGL program = _wglCreateProgram(); - + _wglAttachShader(program, vert); _wglAttachShader(program, frag); - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { VSHInputLayoutParser.applyLayout(program, vertLayout); } _wglLinkProgram(program); _wglDetachShader(program, vert); _wglDetachShader(program, frag); - if(DrawUtils.vshLocal == null) { + if (DrawUtils.vshLocal == null) { _wglDeleteShader(vert); } _wglDeleteShader(frag); - - if(_wglGetProgrami(program, GL_LINK_STATUS) != GL_TRUE) { + + if (_wglGetProgrami(program, GL_LINK_STATUS) != GL_TRUE) { _wglDeleteProgram(program); GlStateManager.deleteTexture(helperTexture); return new byte[0]; } - + EaglercraftGPU.bindGLShaderProgram(program); _wglUniform1i(_wglGetUniformLocation(program, "u_inputTexture"), 0); - + float fovy = 90.0f; float aspect = 1.0f; float zNear = 0.01f; @@ -156,7 +207,7 @@ public class HardwareFingerprint { FloatBuffer matrixUploadBuffer = EagRuntime.allocateFloatBuffer(16); float toRad = 0.0174532925f; float cotangent = (float) Math.cos(fovy * toRad * 0.5f) / (float) Math.sin(fovy * toRad * 0.5f); - + matrixUploadBuffer.put(cotangent / aspect); matrixUploadBuffer.put(0.0f); matrixUploadBuffer.put(0.0f); @@ -173,11 +224,11 @@ public class HardwareFingerprint { matrixUploadBuffer.put(0.0f); matrixUploadBuffer.put(-1.0f); matrixUploadBuffer.put(0.0f); - + matrixUploadBuffer.flip(); _wglUniformMatrix4fv(_wglGetUniformLocation(program, "u_textureMatrix"), false, matrixUploadBuffer); EagRuntime.freeFloatBuffer(matrixUploadBuffer); - + int[] oldViewport = new int[4]; EaglercraftGPU.glGetInteger(GL_VIEWPORT, oldViewport); IFramebufferGL framebuffer = _wglCreateFramebuffer(); @@ -187,63 +238,73 @@ public class HardwareFingerprint { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - + int dataLength; int type; - if(EaglercraftGPU.checkHDRFramebufferSupport(32)) { + if (EaglercraftGPU.checkHDRFramebufferSupport(32)) { dataLength = 256 * 256 * 4 * 4; type = GL_FLOAT; EaglercraftGPU.createFramebufferHDR32FTexture(GL_TEXTURE_2D, 0, 256, 256, GL_RGBA, false); - }else if(EaglercraftGPU.checkHDRFramebufferSupport(16)) { + } else if (EaglercraftGPU.checkHDRFramebufferSupport(16)) { dataLength = 256 * 256 * 4 * 2; type = _GL_HALF_FLOAT; EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 256, 256, GL_RGBA, false); - }else { + } else { dataLength = 256 * 256 * 4; type = GL_UNSIGNED_BYTE; - EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); + EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE, + (ByteBuffer) null); } - + _wglBindFramebuffer(_GL_FRAMEBUFFER, framebuffer); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(renderTexture), 0); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(renderTexture), 0); _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); - + GlStateManager.viewport(0, 0, 256, 256); GlStateManager.disableBlend(); GlStateManager.bindTexture(helperTexture); - + DrawUtils.drawStandardQuad2D(); - + _wglDeleteProgram(program); GlStateManager.deleteTexture(helperTexture); - + ByteBuffer readBuffer = EagRuntime.allocateByteBuffer(dataLength); EaglercraftGPU.glReadPixels(0, 0, 256, 256, GL_RGBA, type, readBuffer); - + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); _wglDeleteFramebuffer(framebuffer); GlStateManager.deleteTexture(renderTexture); GlStateManager.viewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); - + SHA256Digest digest = new SHA256Digest(); byte[] copyBuffer = new byte[1024]; - - byte[] b = ("eag" + EaglercraftGPU.glGetString(GL_VENDOR) + "; eag " + EaglercraftGPU.glGetString(GL_RENDERER)).getBytes(StandardCharsets.UTF_8); + + byte[] b = ("eag" + EaglercraftGPU.glGetString(GL_VENDOR) + "; eag " + EaglercraftGPU.glGetString(GL_RENDERER)) + .getBytes(StandardCharsets.UTF_8); digest.update(b, 0, b.length); - - digestInts(digest, _wglGetInteger(0x8869), _wglGetInteger(0x8DFB), _wglGetInteger(0x8B4C), _wglGetInteger(0x8DFC), copyBuffer); + + digestInts(digest, _wglGetInteger(0x8869), _wglGetInteger(0x8DFB), _wglGetInteger(0x8B4C), + _wglGetInteger(0x8DFC), copyBuffer); digestInts(digest, _wglGetInteger(0x8DFD), _wglGetInteger(0x8872), _wglGetInteger(0x84E8), 69, copyBuffer); digestInts(digest, _wglGetInteger(0x0D33), _wglGetInteger(0x851C), _wglGetInteger(0x8B4D), 69, copyBuffer); - - if(EaglercraftGPU.checkOpenGLESVersion() >= 300) { - digestInts(digest, _wglGetInteger(0x8B4A), _wglGetInteger(0x8A2B), _wglGetInteger(0x9122), _wglGetInteger(0x8B4B), copyBuffer); - digestInts(digest, _wglGetInteger(0x8C8A), _wglGetInteger(0x8C8B), _wglGetInteger(0x8C80), _wglGetInteger(0x8B49), copyBuffer); - digestInts(digest, _wglGetInteger(0x8A2D), _wglGetInteger(0x9125), _wglGetInteger(0x8904), _wglGetInteger(0x8905), copyBuffer); - digestInts(digest, _wglGetInteger(0x8824), _wglGetInteger(0x8073), _wglGetInteger(0x88FF), _wglGetInteger(0x84FD), copyBuffer); - digestInts(digest, _wglGetInteger(0x8CDF), _wglGetInteger(0x8A2F), _wglGetInteger(0x8A30), _wglGetInteger(0x8A34), copyBuffer); - digestInts(digest, _wglGetInteger(0x8A2E), _wglGetInteger(0x8A31), _wglGetInteger(0x8A33), _wglGetInteger(0x8D57), copyBuffer); + + if (EaglercraftGPU.checkOpenGLESVersion() >= 300) { + digestInts(digest, _wglGetInteger(0x8B4A), _wglGetInteger(0x8A2B), _wglGetInteger(0x9122), + _wglGetInteger(0x8B4B), copyBuffer); + digestInts(digest, _wglGetInteger(0x8C8A), _wglGetInteger(0x8C8B), _wglGetInteger(0x8C80), + _wglGetInteger(0x8B49), copyBuffer); + digestInts(digest, _wglGetInteger(0x8A2D), _wglGetInteger(0x9125), _wglGetInteger(0x8904), + _wglGetInteger(0x8905), copyBuffer); + digestInts(digest, _wglGetInteger(0x8824), _wglGetInteger(0x8073), _wglGetInteger(0x88FF), + _wglGetInteger(0x84FD), copyBuffer); + digestInts(digest, _wglGetInteger(0x8CDF), _wglGetInteger(0x8A2F), _wglGetInteger(0x8A30), + _wglGetInteger(0x8A34), copyBuffer); + digestInts(digest, _wglGetInteger(0x8A2E), _wglGetInteger(0x8A31), _wglGetInteger(0x8A33), + _wglGetInteger(0x8D57), copyBuffer); } - + try { List exts = Lists.newArrayList(getAllExtensions()); Collections.sort(exts); @@ -254,41 +315,35 @@ public class HardwareFingerprint { } b = String.join(":>", exts).getBytes(StandardCharsets.UTF_8); digest.update(b, 0, b.length); - }catch(Throwable t) { + } catch (Throwable t) { } - + int i; - while(readBuffer.hasRemaining()) { + while (readBuffer.hasRemaining()) { i = Math.min(readBuffer.remaining(), copyBuffer.length); readBuffer.get(copyBuffer, 0, i); digest.update(copyBuffer, 0, i); } - + EagRuntime.freeByteBuffer(readBuffer); - + byte[] hashOut = new byte[32]; digest.doFinal(hashOut, 0); - + return hashOut; } - private static void digestInts(GeneralDigest digest, int i1, int i2, int i3, int i4, byte[] tmpBuffer) { - tmpBuffer[0] = (byte)(i1 >>> 24); - tmpBuffer[1] = (byte)(i1 >>> 16); - tmpBuffer[2] = (byte)(i1 >>> 8); - tmpBuffer[3] = (byte)(i1 & 0xFF); - tmpBuffer[4] = (byte)(i2 >>> 24); - tmpBuffer[5] = (byte)(i2 >>> 16); - tmpBuffer[6] = (byte)(i2 >>> 8); - tmpBuffer[7] = (byte)(i2 & 0xFF); - tmpBuffer[8] = (byte)(i3 >>> 24); - tmpBuffer[9] = (byte)(i3 >>> 16); - tmpBuffer[10] = (byte)(i3 >>> 8); - tmpBuffer[11] = (byte)(i3 & 0xFF); - tmpBuffer[12] = (byte)(i4 >>> 24); - tmpBuffer[13] = (byte)(i4 >>> 16); - tmpBuffer[14] = (byte)(i4 >>> 8); - tmpBuffer[15] = (byte)(i4 & 0xFF); - digest.update(tmpBuffer, 0, 16); + public static byte[] getFingerprint() { + if (fingerprint == null) { + try { + fingerprint = generateFingerprint(); + } catch (Throwable t) { + fingerprint = new byte[0]; + } + if (fingerprint.length == 0) { + logger.error("Failed to calculate hardware fingerprint, server cookies will not be encrypted!"); + } + } + return fingerprint; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/ServerCookieDataStore.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/ServerCookieDataStore.java index 705da432..db00d134 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/ServerCookieDataStore.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/cookie/ServerCookieDataStore.java @@ -25,26 +25,21 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerCookieDataStore { - private static final Logger logger = LogManager.getLogger("ServerCookieDataStore"); - - private static final Map dataStore = new HashMap<>(); - - public static final String localStorageKey = "c"; - public static class ServerCookie { public final String server; @@ -53,7 +48,8 @@ public class ServerCookieDataStore { public final boolean revokeQuerySupported; public final boolean saveCookieToDisk; - public ServerCookie(String server, byte[] cookie, long expires, boolean revokeQuerySupported, boolean saveCookieToDisk) { + public ServerCookie(String server, byte[] cookie, long expires, boolean revokeQuerySupported, + boolean saveCookieToDisk) { this.server = server; this.cookie = cookie; this.expires = expires; @@ -63,59 +59,17 @@ public class ServerCookieDataStore { } - public static void load() { - if(EagRuntime.getConfiguration().isEnableServerCookies()) { - loadData(HardwareFingerprint.getFingerprint()); - } - } + private static final Logger logger = LogManager.getLogger("ServerCookieDataStore"); - public static ServerCookie loadCookie(String server) { - if(!EagRuntime.getConfiguration().isEnableServerCookies()) { - return null; - } - server = normalize(server); - ServerCookie cookie = dataStore.get(server); - if(cookie == null) { - return null; - } - long timestamp = System.currentTimeMillis(); - if(timestamp > cookie.expires) { - dataStore.remove(server); - saveData(HardwareFingerprint.getFingerprint()); - return null; - } - return cookie; - } + private static final Map dataStore = new HashMap<>(); - public static void saveCookie(String server, long expires, byte[] data, boolean revokeQuerySupported, boolean saveCookieToDisk) { - if(!EagRuntime.getConfiguration().isEnableServerCookies()) { - return; - } - server = normalize(server); - if(expires > 604800l) { - clearCookie(server); - logger.error("Server \"{}\" tried to set a cookie for {} days! (The max is 7 days)", server, (expires / 604800l)); - return; - } - if(data.length > 255) { - clearCookie(server); - logger.error("Server \"{}\" tried to set a {} byte cookie! (The max length is 255 bytes)", server, data.length); - return; - } - if(expires < 0l || data.length == 0) { - clearCookie(server); - return; - } - long expiresRelative = System.currentTimeMillis() + expires * 1000l; - dataStore.put(server, new ServerCookie(server, data, expiresRelative, revokeQuerySupported, saveCookieToDisk)); - saveData(HardwareFingerprint.getFingerprint()); - } + public static final String localStorageKey = "c"; public static void clearCookie(String server) { - if(!EagRuntime.getConfiguration().isEnableServerCookies()) { + if (!EagRuntime.getConfiguration().isEnableServerCookies()) { return; } - if(dataStore.remove(normalize(server)) != null) { + if (dataStore.remove(normalize(server)) != null) { saveData(HardwareFingerprint.getFingerprint()); } } @@ -124,22 +78,19 @@ public class ServerCookieDataStore { dataStore.clear(); } - private static String normalize(String server) { - int j = server.indexOf('/'); - if(j != -1) { - int i = server.indexOf("://"); - if(i != -1) { - j = server.indexOf('/', i + 3); - if(j == -1) { - return server.toLowerCase(); - }else { - return server.substring(0, j).toLowerCase() + server.substring(j); - } - }else { - return server.substring(0, j).toLowerCase() + server.substring(j); + public static void flush() { + Iterator itr = dataStore.values().iterator(); + boolean changed = false; + while (itr.hasNext()) { + long timestamp = System.currentTimeMillis(); + ServerCookie cookie = itr.next(); + if (timestamp > cookie.expires) { + itr.remove(); + changed = true; } - }else { - return server.toLowerCase(); + } + if (changed) { + saveData(HardwareFingerprint.getFingerprint()); } } @@ -149,85 +100,81 @@ public class ServerCookieDataStore { public static List getRevokableServers() { List ret = new ArrayList<>(dataStore.size()); - for(ServerCookie c : dataStore.values()) { - if(c.revokeQuerySupported) { + for (ServerCookie c : dataStore.values()) { + if (c.revokeQuerySupported) { ret.add(c.server); } } return ret; } - public static int size() { - return dataStore.size(); + public static void load() { + if (EagRuntime.getConfiguration().isEnableServerCookies()) { + loadData(HardwareFingerprint.getFingerprint()); + } } - public static int numRevokable() { - int i = 0; - for(ServerCookie c : dataStore.values()) { - if(c.revokeQuerySupported) { - ++i; - } + public static ServerCookie loadCookie(String server) { + if (!EagRuntime.getConfiguration().isEnableServerCookies()) { + return null; } - return i; - } - - public static void flush() { - Iterator itr = dataStore.values().iterator(); - boolean changed = false; - while(itr.hasNext()) { - long timestamp = System.currentTimeMillis(); - ServerCookie cookie = itr.next(); - if(timestamp > cookie.expires) { - itr.remove(); - changed = true; - } + server = normalize(server); + ServerCookie cookie = dataStore.get(server); + if (cookie == null) { + return null; } - if(changed) { + long timestamp = System.currentTimeMillis(); + if (timestamp > cookie.expires) { + dataStore.remove(server); saveData(HardwareFingerprint.getFingerprint()); + return null; } + return cookie; } private static void loadData(byte[] key) { dataStore.clear(); byte[] cookiesTag = PlatformApplication.getLocalStorage(localStorageKey, false); - if(cookiesTag == null) { + if (cookiesTag == null) { return; } - if(cookiesTag.length <= 25) { + if (cookiesTag.length <= 25) { PlatformApplication.setLocalStorage(localStorageKey, null, false); return; } try { byte[] decrypted; int decryptedLen; - switch(cookiesTag[0]) { + switch (cookiesTag[0]) { case 2: - if(key == null || key.length == 0) { + if (key == null || key.length == 0) { throw new IOException("Data is encrypted!"); } decrypted = new byte[cookiesTag.length - 5]; - decryptedLen = (cookiesTag[1] << 24) | (cookiesTag[2] << 16) | (cookiesTag[3] << 8) | (cookiesTag[4] & 0xFF); - if(decryptedLen < 25) { + decryptedLen = (cookiesTag[1] << 24) | (cookiesTag[2] << 16) | (cookiesTag[3] << 8) + | (cookiesTag[4] & 0xFF); + if (decryptedLen < 25) { throw new IOException("too short!"); } AESLightEngine aes = new AESLightEngine(); aes.init(false, key); int bs = aes.getBlockSize(); - if(decrypted.length % bs != 0) { + if (decrypted.length % bs != 0) { throw new IOException("length not aligned to block size!"); } byte[] cbcHelper = new byte[] { (byte) 29, (byte) 163, (byte) 4, (byte) 20, (byte) 207, (byte) 26, (byte) 140, (byte) 55, (byte) 246, (byte) 250, (byte) 141, (byte) 183, (byte) 153, (byte) 154, (byte) 59, (byte) 4 }; - for(int i = 0; i < decryptedLen; i += bs) { - processBlockDecryptHelper(aes, cookiesTag, 5 + i, decrypted, i, bs, Math.min(decryptedLen - i, bs), cbcHelper); + for (int i = 0; i < decryptedLen; i += bs) { + processBlockDecryptHelper(aes, cookiesTag, 5 + i, decrypted, i, bs, Math.min(decryptedLen - i, bs), + cbcHelper); } - if(decrypted[0] != (byte)0x69) { + if (decrypted[0] != (byte) 0x69) { throw new IOException("Data is corrupt!"); } break; case 1: - if(key != null && key.length > 0) { + if (key != null && key.length > 0) { throw new IOException("Data isn't encrypted!"); } decrypted = cookiesTag; @@ -240,73 +187,173 @@ public class ServerCookieDataStore { digest.update(decrypted, 25, decryptedLen - 25); byte[] digestOut = new byte[20]; digest.doFinal(digestOut, 0); - for(int i = 0; i < 20; ++i) { - if(digestOut[i] != decrypted[5 + i]) { + for (int i = 0; i < 20; ++i) { + if (digestOut[i] != decrypted[5 + i]) { throw new IOException("Invalid checksum!"); } } - int decompressedLen = (decrypted[1] << 24) | (decrypted[2] << 16) | (decrypted[3] << 8) | (decrypted[4] & 0xFF); + int decompressedLen = (decrypted[1] << 24) | (decrypted[2] << 16) | (decrypted[3] << 8) + | (decrypted[4] & 0xFF); byte[] decompressed = new byte[decompressedLen]; - try (InputStream zstream = EaglerZLIB.newInflaterInputStream(new EaglerInputStream(decrypted, 25, decryptedLen - 25))) { + try (InputStream zstream = EaglerZLIB + .newInflaterInputStream(new EaglerInputStream(decrypted, 25, decryptedLen - 25))) { int i = 0, j; - while(i < decompressedLen && (j = zstream.read(decompressed, i, decompressedLen - i)) != -1) { + while (i < decompressedLen && (j = zstream.read(decompressed, i, decompressedLen - i)) != -1) { i += j; } - if(i != decompressedLen) { + if (i != decompressedLen) { throw new IOException("Length does not match!"); } } DataInputStream dis = new DataInputStream(new EaglerInputStream(decompressed)); int readCount = dis.readInt(); long time = System.currentTimeMillis(); - for(int i = 0; i < readCount; ++i) { + for (int i = 0; i < readCount; ++i) { byte flags = dis.readByte(); long expires = dis.readLong(); int len = dis.readUnsignedShort(); String server = dis.readUTF(); - if(len == 0) { + if (len == 0) { continue; } - if(expires < time) { + if (expires < time) { dis.skipBytes(len); continue; } byte[] cookieData = new byte[len]; dis.readFully(cookieData); server = normalize(server); - dataStore.put(server, new ServerCookie(server, cookieData, expires, (flags & 1) != 0, (flags & 2) != 0)); + dataStore.put(server, + new ServerCookie(server, cookieData, expires, (flags & 1) != 0, (flags & 2) != 0)); } - if(dis.available() > 0) { + if (dis.available() > 0) { throw new IOException("Extra bytes remaining!"); } - }catch (IOException e) { + } catch (IOException e) { dataStore.clear(); PlatformApplication.setLocalStorage(localStorageKey, null, false); return; } } + private static String normalize(String server) { + int j = server.indexOf('/'); + if (j != -1) { + int i = server.indexOf("://"); + if (i != -1) { + j = server.indexOf('/', i + 3); + if (j == -1) { + return server.toLowerCase(); + } else { + return server.substring(0, j).toLowerCase() + server.substring(j); + } + } else { + return server.substring(0, j).toLowerCase() + server.substring(j); + } + } else { + return server.toLowerCase(); + } + } + + public static int numRevokable() { + int i = 0; + for (ServerCookie c : dataStore.values()) { + if (c.revokeQuerySupported) { + ++i; + } + } + return i; + } + + private static void processBlockDecryptHelper(AESLightEngine aes, byte[] in, int inOff, byte[] out, int outOff, + int paddedLen, int unpaddedLen, byte[] cbcHelper) throws IOException { + aes.processBlock(in, inOff, out, outOff); + for (int i = 0; i < paddedLen; ++i) { + out[i + outOff] ^= cbcHelper[i]; + } + if (unpaddedLen == paddedLen) { + System.arraycopy(in, inOff, cbcHelper, 0, paddedLen); + } else { + byte padValue = (byte) (paddedLen - unpaddedLen); + for (byte i = 0; i < padValue; ++i) { + if (out[outOff + unpaddedLen + i] != padValue) { + throw new IOException("Invalid padding!"); + } + } + } + } + + private static void processBlockEncryptHelper(AESLightEngine aes, byte[] in, int inOff, byte[] out, int outOff, + int len, byte[] cbcHelper) { + int clampedBlockLength = Math.min(in.length - inOff, len); + if (clampedBlockLength == len) { + for (int i = 0; i < len; ++i) { + in[i + inOff] ^= cbcHelper[i]; + } + aes.processBlock(in, inOff, out, outOff); + System.arraycopy(out, outOff, cbcHelper, 0, len); + } else { + byte[] paddedBlock = new byte[len]; + System.arraycopy(in, inOff, paddedBlock, 0, clampedBlockLength); + byte padValue = (byte) (len - clampedBlockLength); + for (byte i = 0; i < padValue; ++i) { + paddedBlock[clampedBlockLength + i] = padValue; + } + for (int i = 0; i < len; ++i) { + paddedBlock[i] ^= cbcHelper[i]; + } + aes.processBlock(paddedBlock, 0, out, outOff); + } + } + + public static void saveCookie(String server, long expires, byte[] data, boolean revokeQuerySupported, + boolean saveCookieToDisk) { + if (!EagRuntime.getConfiguration().isEnableServerCookies()) { + return; + } + server = normalize(server); + if (expires > 604800l) { + clearCookie(server); + logger.error("Server \"{}\" tried to set a cookie for {} days! (The max is 7 days)", server, + (expires / 604800l)); + return; + } + if (data.length > 255) { + clearCookie(server); + logger.error("Server \"{}\" tried to set a {} byte cookie! (The max length is 255 bytes)", server, + data.length); + return; + } + if (expires < 0l || data.length == 0) { + clearCookie(server); + return; + } + long expiresRelative = System.currentTimeMillis() + expires * 1000l; + dataStore.put(server, new ServerCookie(server, data, expiresRelative, revokeQuerySupported, saveCookieToDisk)); + saveData(HardwareFingerprint.getFingerprint()); + } + private static void saveData(byte[] key) { Iterator itr = dataStore.values().iterator(); List toSave = new ArrayList<>(dataStore.size()); - while(itr.hasNext()) { + while (itr.hasNext()) { long timestamp = System.currentTimeMillis(); ServerCookie cookie = itr.next(); - if(timestamp > cookie.expires || cookie.cookie.length > 255 || cookie.cookie.length == 0) { + if (timestamp > cookie.expires || cookie.cookie.length > 255 || cookie.cookie.length == 0) { itr.remove(); - }else if(cookie.saveCookieToDisk) { + } else if (cookie.saveCookieToDisk) { toSave.add(cookie); } } - if(toSave.size() == 0) { + if (toSave.size() == 0) { PlatformApplication.setLocalStorage(localStorageKey, null, false); - }else { + } else { EaglerOutputStream bao = new EaglerOutputStream(1024); bao.skipBytes(25); int totalUncompressedLen; - try(DataOutputStream zstream = new DataOutputStream(EaglerZLIB.newDeflaterOutputStream(bao))) { + try (DataOutputStream zstream = new DataOutputStream(EaglerZLIB.newDeflaterOutputStream(bao))) { zstream.writeInt(dataStore.size()); - for(Entry etr : dataStore.entrySet()) { + for (Entry etr : dataStore.entrySet()) { ServerCookie cookie = etr.getValue(); zstream.writeByte((cookie.revokeQuerySupported ? 1 : 0) | (cookie.saveCookieToDisk ? 2 : 0)); zstream.writeLong(cookie.expires); @@ -323,74 +370,37 @@ public class ServerCookieDataStore { SHA1Digest hash = new SHA1Digest(); hash.update(toEncrypt, 25, toEncrypt.length - 25); hash.doFinal(toEncrypt, 5); - toEncrypt[1] = (byte)(totalUncompressedLen >>> 24); - toEncrypt[2] = (byte)(totalUncompressedLen >>> 16); - toEncrypt[3] = (byte)(totalUncompressedLen >>> 8); - toEncrypt[4] = (byte)(totalUncompressedLen & 0xFF); - if(key != null && key.length > 0) { - toEncrypt[0] = (byte)0x69; + toEncrypt[1] = (byte) (totalUncompressedLen >>> 24); + toEncrypt[2] = (byte) (totalUncompressedLen >>> 16); + toEncrypt[3] = (byte) (totalUncompressedLen >>> 8); + toEncrypt[4] = (byte) (totalUncompressedLen & 0xFF); + if (key != null && key.length > 0) { + toEncrypt[0] = (byte) 0x69; AESLightEngine aes = new AESLightEngine(); aes.init(true, key); int bs = aes.getBlockSize(); int blockCount = (toEncrypt.length % bs) != 0 ? (toEncrypt.length / bs + 1) : (toEncrypt.length / bs); byte[] encrypted = new byte[blockCount * bs + 5]; - encrypted[0] = (byte)2; - encrypted[1] = (byte)(toEncrypt.length >>> 24); - encrypted[2] = (byte)(toEncrypt.length >>> 16); - encrypted[3] = (byte)(toEncrypt.length >>> 8); - encrypted[4] = (byte)(toEncrypt.length & 0xFF); + encrypted[0] = (byte) 2; + encrypted[1] = (byte) (toEncrypt.length >>> 24); + encrypted[2] = (byte) (toEncrypt.length >>> 16); + encrypted[3] = (byte) (toEncrypt.length >>> 8); + encrypted[4] = (byte) (toEncrypt.length & 0xFF); byte[] cbcHelper = new byte[] { (byte) 29, (byte) 163, (byte) 4, (byte) 20, (byte) 207, (byte) 26, (byte) 140, (byte) 55, (byte) 246, (byte) 250, (byte) 141, (byte) 183, (byte) 153, (byte) 154, (byte) 59, (byte) 4 }; - for(int i = 0; i < toEncrypt.length; i += bs) { + for (int i = 0; i < toEncrypt.length; i += bs) { processBlockEncryptHelper(aes, toEncrypt, i, encrypted, 5 + i, bs, cbcHelper); } PlatformApplication.setLocalStorage(localStorageKey, encrypted, false); - }else { - toEncrypt[0] = (byte)1; + } else { + toEncrypt[0] = (byte) 1; PlatformApplication.setLocalStorage(localStorageKey, toEncrypt, false); } } } - private static void processBlockEncryptHelper(AESLightEngine aes, byte[] in, int inOff, byte[] out, int outOff, - int len, byte[] cbcHelper) { - int clampedBlockLength = Math.min(in.length - inOff, len); - if(clampedBlockLength == len) { - for(int i = 0; i < len; ++i) { - in[i + inOff] ^= cbcHelper[i]; - } - aes.processBlock(in, inOff, out, outOff); - System.arraycopy(out, outOff, cbcHelper, 0, len); - }else { - byte[] paddedBlock = new byte[len]; - System.arraycopy(in, inOff, paddedBlock, 0, clampedBlockLength); - byte padValue = (byte)(len - clampedBlockLength); - for(byte i = 0; i < padValue; ++i) { - paddedBlock[clampedBlockLength + i] = padValue; - } - for(int i = 0; i < len; ++i) { - paddedBlock[i] ^= cbcHelper[i]; - } - aes.processBlock(paddedBlock, 0, out, outOff); - } - } - - private static void processBlockDecryptHelper(AESLightEngine aes, byte[] in, int inOff, byte[] out, int outOff, - int paddedLen, int unpaddedLen, byte[] cbcHelper) throws IOException { - aes.processBlock(in, inOff, out, outOff); - for(int i = 0; i < paddedLen; ++i) { - out[i + outOff] ^= cbcHelper[i]; - } - if(unpaddedLen == paddedLen) { - System.arraycopy(in, inOff, cbcHelper, 0, paddedLen); - }else { - byte padValue = (byte)(paddedLen - unpaddedLen); - for(byte i = 0; i < padValue; ++i) { - if(out[outOff + unpaddedLen + i] != padValue) { - throw new IOException("Invalid padding!"); - } - } - } + public static int size() { + return dataStore.size(); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/AESLightEngine.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/AESLightEngine.java index 6938e30f..565e269c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/AESLightEngine.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/AESLightEngine.java @@ -24,26 +24,28 @@ package net.lax1dude.eaglercraft.v1_8.crypto; /** * an implementation of the AES (Rijndael), from FIPS-197. *

              - * For further details see: https://csrc.nist.gov/encryption/aes/. + * For further details see: https://csrc.nist.gov/encryption/aes/. * - * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at - * https://fp.gladman.plus.com/cryptography_technology/rijndael/ + * This implementation is based on optimizations from Dr. Brian Gladman's paper + * and C code at https://fp.gladman.plus.com/cryptography_technology/rijndael/ * - * There are three levels of tradeoff of speed vs memory - * Because java has no preprocessor, they are written as three separate classes from which to choose + * There are three levels of tradeoff of speed vs memory Because java has no + * preprocessor, they are written as three separate classes from which to choose * - * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption - * and 4 for decryption. + * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 + * 256 word tables for encryption and 4 for decryption. * - * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, - * adding 12 rotate operations per round to compute the values contained in the other tables from - * the contents of the first + * The middle performance version uses only one 256 word table for each, for a + * total of 2Kbytes, adding 12 rotate operations per round to compute the values + * contained in the other tables from the contents of the first * - * The slowest version uses no static tables at all and computes the values - * in each round. + * The slowest version uses no static tables at all and computes the values in + * each round. *

              - * This file contains the slowest performance version with no static tables - * for round precomputation, but it has the smallest foot print. + * This file contains the slowest performance version with no static tables for + * round precomputation, but it has the smallest foot print. * */ public class AESLightEngine { @@ -113,17 +115,15 @@ public class AESLightEngine { private static final int[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; - private static int shift(int r, int shift) { - return (r >>> shift) | (r << -shift); - } + private static final int m1 = 0x80808080; /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ - private static final int m1 = 0x80808080; private static final int m2 = 0x7f7f7f7f; private static final int m3 = 0x0000001b; private static final int m4 = 0xC0C0C0C0; private static final int m5 = 0x3f3f3f3f; + private static final int BLOCK_SIZE = 16; private static int FFmulX(int x) { return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3)); @@ -136,21 +136,22 @@ public class AESLightEngine { return t0 ^ (t1 >>> 2) ^ (t1 >>> 5); } - /* - The following defines provide alternative definitions of FFmulX that might - give improved performance if a fast 32-bit multiply is not available. - - private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } - private static final int m4 = 0x1b1b1b1b; - private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } - + /* + * The following defines provide alternative definitions of FFmulX that might + * give improved performance if a fast 32-bit multiply is not available. + * + * private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) + * << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; + * private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u + * >>> 7)) & m4); } + * */ - private static int mcol(int x) { - int t0, t1; - t0 = shift(x, 8); - t1 = x ^ t0; - return shift(t1, 16) ^ t0 ^ FFmulX(t1); + public static void intToLittleEndian(int n, byte[] bs, int off) { + bs[off] = (byte) (n); + bs[++off] = (byte) (n >>> 8); + bs[++off] = (byte) (n >>> 16); + bs[++off] = (byte) (n >>> 24); } private static int inv_mcol(int x) { @@ -163,11 +164,6 @@ public class AESLightEngine { return t0; } - private static int subWord(int x) { - return (S[x & 255] & 255 | ((S[(x >> 8) & 255] & 255) << 8) | ((S[(x >> 16) & 255] & 255) << 16) - | S[(x >> 24) & 255] << 24); - } - private static int littleEndianToInt(byte[] bs, int off) { int n = bs[off] & 0xff; n |= (bs[++off] & 0xff) << 8; @@ -176,18 +172,157 @@ public class AESLightEngine { return n; } - public static void intToLittleEndian(int n, byte[] bs, int off) { - bs[off] = (byte) (n); - bs[++off] = (byte) (n >>> 8); - bs[++off] = (byte) (n >>> 16); - bs[++off] = (byte) (n >>> 24); + private static int mcol(int x) { + int t0, t1; + t0 = shift(x, 8); + t1 = x ^ t0; + return shift(t1, 16) ^ t0 ^ FFmulX(t1); + } + + private static int shift(int r, int shift) { + return (r >>> shift) | (r << -shift); + } + + private static int subWord(int x) { + return (S[x & 255] & 255 | ((S[(x >> 8) & 255] & 255) << 8) | ((S[(x >> 16) & 255] & 255) << 16) + | S[(x >> 24) & 255] << 24); + } + + private int ROUNDS; + private int[][] WorkingKey = null; + private boolean forEncryption; + + /** + * default constructor - 128 bit block size. + */ + public AESLightEngine() { + + } + + private int bitsOfSecurity() { + if (WorkingKey == null) { + return 256; + } + return (WorkingKey.length - 7) << 5; + } + + private void decryptBlock(byte[] in, int inOff, byte[] out, int outOff, int[][] KW) { + int C0 = littleEndianToInt(in, inOff + 0); + int C1 = littleEndianToInt(in, inOff + 4); + int C2 = littleEndianToInt(in, inOff + 8); + int C3 = littleEndianToInt(in, inOff + 12); + + int t0 = C0 ^ KW[ROUNDS][0]; + int t1 = C1 ^ KW[ROUNDS][1]; + int t2 = C2 ^ KW[ROUNDS][2]; + + int r = ROUNDS - 1, r0, r1, r2, r3 = C3 ^ KW[ROUNDS][3]; + while (r > 1) { + r0 = inv_mcol((Si[t0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) + ^ ((Si[(t2 >> 16) & 255] & 255) << 16) ^ (Si[(t1 >> 24) & 255] << 24)) ^ KW[r][0]; + r1 = inv_mcol((Si[t1 & 255] & 255) ^ ((Si[(t0 >> 8) & 255] & 255) << 8) + ^ ((Si[(r3 >> 16) & 255] & 255) << 16) ^ (Si[(t2 >> 24) & 255] << 24)) ^ KW[r][1]; + r2 = inv_mcol((Si[t2 & 255] & 255) ^ ((Si[(t1 >> 8) & 255] & 255) << 8) + ^ ((Si[(t0 >> 16) & 255] & 255) << 16) ^ (Si[(r3 >> 24) & 255] << 24)) ^ KW[r][2]; + r3 = inv_mcol((Si[r3 & 255] & 255) ^ ((Si[(t2 >> 8) & 255] & 255) << 8) + ^ ((Si[(t1 >> 16) & 255] & 255) << 16) ^ (Si[(t0 >> 24) & 255] << 24)) ^ KW[r--][3]; + t0 = inv_mcol((Si[r0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) + ^ ((Si[(r2 >> 16) & 255] & 255) << 16) ^ (Si[(r1 >> 24) & 255] << 24)) ^ KW[r][0]; + t1 = inv_mcol((Si[r1 & 255] & 255) ^ ((Si[(r0 >> 8) & 255] & 255) << 8) + ^ ((Si[(r3 >> 16) & 255] & 255) << 16) ^ (Si[(r2 >> 24) & 255] << 24)) ^ KW[r][1]; + t2 = inv_mcol((Si[r2 & 255] & 255) ^ ((Si[(r1 >> 8) & 255] & 255) << 8) + ^ ((Si[(r0 >> 16) & 255] & 255) << 16) ^ (Si[(r3 >> 24) & 255] << 24)) ^ KW[r][2]; + r3 = inv_mcol((Si[r3 & 255] & 255) ^ ((Si[(r2 >> 8) & 255] & 255) << 8) + ^ ((Si[(r1 >> 16) & 255] & 255) << 16) ^ (Si[(r0 >> 24) & 255] << 24)) ^ KW[r--][3]; + } + + r0 = inv_mcol((Si[t0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) ^ ((Si[(t2 >> 16) & 255] & 255) << 16) + ^ (Si[(t1 >> 24) & 255] << 24)) ^ KW[r][0]; + r1 = inv_mcol((Si[t1 & 255] & 255) ^ ((Si[(t0 >> 8) & 255] & 255) << 8) ^ ((Si[(r3 >> 16) & 255] & 255) << 16) + ^ (Si[(t2 >> 24) & 255] << 24)) ^ KW[r][1]; + r2 = inv_mcol((Si[t2 & 255] & 255) ^ ((Si[(t1 >> 8) & 255] & 255) << 8) ^ ((Si[(t0 >> 16) & 255] & 255) << 16) + ^ (Si[(r3 >> 24) & 255] << 24)) ^ KW[r][2]; + r3 = inv_mcol((Si[r3 & 255] & 255) ^ ((Si[(t2 >> 8) & 255] & 255) << 8) ^ ((Si[(t1 >> 16) & 255] & 255) << 16) + ^ (Si[(t0 >> 24) & 255] << 24)) ^ KW[r][3]; + + // the final round's table is a simple function of Si + + C0 = (Si[r0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) ^ ((Si[(r2 >> 16) & 255] & 255) << 16) + ^ (Si[(r1 >> 24) & 255] << 24) ^ KW[0][0]; + C1 = (Si[r1 & 255] & 255) ^ ((Si[(r0 >> 8) & 255] & 255) << 8) ^ ((Si[(r3 >> 16) & 255] & 255) << 16) + ^ (Si[(r2 >> 24) & 255] << 24) ^ KW[0][1]; + C2 = (Si[r2 & 255] & 255) ^ ((Si[(r1 >> 8) & 255] & 255) << 8) ^ ((Si[(r0 >> 16) & 255] & 255) << 16) + ^ (Si[(r3 >> 24) & 255] << 24) ^ KW[0][2]; + C3 = (Si[r3 & 255] & 255) ^ ((Si[(r2 >> 8) & 255] & 255) << 8) ^ ((Si[(r1 >> 16) & 255] & 255) << 16) + ^ (Si[(r0 >> 24) & 255] << 24) ^ KW[0][3]; + + intToLittleEndian(C0, out, outOff + 0); + intToLittleEndian(C1, out, outOff + 4); + intToLittleEndian(C2, out, outOff + 8); + intToLittleEndian(C3, out, outOff + 12); + } + + private void encryptBlock(byte[] in, int inOff, byte[] out, int outOff, int[][] KW) { + int C0 = littleEndianToInt(in, inOff + 0); + int C1 = littleEndianToInt(in, inOff + 4); + int C2 = littleEndianToInt(in, inOff + 8); + int C3 = littleEndianToInt(in, inOff + 12); + + int t0 = C0 ^ KW[0][0]; + int t1 = C1 ^ KW[0][1]; + int t2 = C2 ^ KW[0][2]; + + int r = 1, r0, r1, r2, r3 = C3 ^ KW[0][3]; + while (r < ROUNDS - 1) { + r0 = mcol((S[t0 & 255] & 255) ^ ((S[(t1 >> 8) & 255] & 255) << 8) ^ ((S[(t2 >> 16) & 255] & 255) << 16) + ^ (S[(r3 >> 24) & 255] << 24)) ^ KW[r][0]; + r1 = mcol((S[t1 & 255] & 255) ^ ((S[(t2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) + ^ (S[(t0 >> 24) & 255] << 24)) ^ KW[r][1]; + r2 = mcol((S[t2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(t0 >> 16) & 255] & 255) << 16) + ^ (S[(t1 >> 24) & 255] << 24)) ^ KW[r][2]; + r3 = mcol((S[r3 & 255] & 255) ^ ((S[(t0 >> 8) & 255] & 255) << 8) ^ ((S[(t1 >> 16) & 255] & 255) << 16) + ^ (S[(t2 >> 24) & 255] << 24)) ^ KW[r++][3]; + t0 = mcol((S[r0 & 255] & 255) ^ ((S[(r1 >> 8) & 255] & 255) << 8) ^ ((S[(r2 >> 16) & 255] & 255) << 16) + ^ (S[(r3 >> 24) & 255] << 24)) ^ KW[r][0]; + t1 = mcol((S[r1 & 255] & 255) ^ ((S[(r2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) + ^ (S[(r0 >> 24) & 255] << 24)) ^ KW[r][1]; + t2 = mcol((S[r2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(r0 >> 16) & 255] & 255) << 16) + ^ (S[(r1 >> 24) & 255] << 24)) ^ KW[r][2]; + r3 = mcol((S[r3 & 255] & 255) ^ ((S[(r0 >> 8) & 255] & 255) << 8) ^ ((S[(r1 >> 16) & 255] & 255) << 16) + ^ (S[(r2 >> 24) & 255] << 24)) ^ KW[r++][3]; + } + + r0 = mcol((S[t0 & 255] & 255) ^ ((S[(t1 >> 8) & 255] & 255) << 8) ^ ((S[(t2 >> 16) & 255] & 255) << 16) + ^ (S[(r3 >> 24) & 255] << 24)) ^ KW[r][0]; + r1 = mcol((S[t1 & 255] & 255) ^ ((S[(t2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) + ^ (S[(t0 >> 24) & 255] << 24)) ^ KW[r][1]; + r2 = mcol((S[t2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(t0 >> 16) & 255] & 255) << 16) + ^ (S[(t1 >> 24) & 255] << 24)) ^ KW[r][2]; + r3 = mcol((S[r3 & 255] & 255) ^ ((S[(t0 >> 8) & 255] & 255) << 8) ^ ((S[(t1 >> 16) & 255] & 255) << 16) + ^ (S[(t2 >> 24) & 255] << 24)) ^ KW[r++][3]; + + // the final round is a simple function of S + + C0 = (S[r0 & 255] & 255) ^ ((S[(r1 >> 8) & 255] & 255) << 8) ^ ((S[(r2 >> 16) & 255] & 255) << 16) + ^ (S[(r3 >> 24) & 255] << 24) ^ KW[r][0]; + C1 = (S[r1 & 255] & 255) ^ ((S[(r2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) + ^ (S[(r0 >> 24) & 255] << 24) ^ KW[r][1]; + C2 = (S[r2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(r0 >> 16) & 255] & 255) << 16) + ^ (S[(r1 >> 24) & 255] << 24) ^ KW[r][2]; + C3 = (S[r3 & 255] & 255) ^ ((S[(r0 >> 8) & 255] & 255) << 8) ^ ((S[(r1 >> 16) & 255] & 255) << 16) + ^ (S[(r2 >> 24) & 255] << 24) ^ KW[r][3]; + + intToLittleEndian(C0, out, outOff + 0); + intToLittleEndian(C1, out, outOff + 4); + intToLittleEndian(C2, out, outOff + 8); + intToLittleEndian(C3, out, outOff + 12); } /** - * Calculate the necessary round keys - * The number of calculations depends on key size and block size - * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits - * This code is written assuming those are the only possible values + * Calculate the necessary round keys The number of calculations depends on key + * size and block size AES specified a fixed block size of 128 bits and key + * sizes 128/192/256 bits This code is written assuming those are the only + * possible values */ private int[][] generateWorkingKey(byte[] key, boolean forEncryption) { int keyLen = key.length; @@ -346,33 +481,6 @@ public class AESLightEngine { return W; } - private int ROUNDS; - private int[][] WorkingKey = null; - private boolean forEncryption; - - private static final int BLOCK_SIZE = 16; - - /** - * default constructor - 128 bit block size. - */ - public AESLightEngine() { - - } - - /** - * initialise an AES cipher. - * - * @param forEncryption whether or not we are for encryption. - * @param params the parameters required to set up the cipher. - * @exception IllegalArgumentException if the params argument is - * inappropriate. - */ - public void init(boolean forEncryption, byte[] key) { - WorkingKey = generateWorkingKey(key, forEncryption); - this.forEncryption = forEncryption; - return; - } - public String getAlgorithmName() { return "AES"; } @@ -381,6 +489,19 @@ public class AESLightEngine { return BLOCK_SIZE; } + /** + * initialise an AES cipher. + * + * @param forEncryption whether or not we are for encryption. + * @param params the parameters required to set up the cipher. + * @exception IllegalArgumentException if the params argument is inappropriate. + */ + public void init(boolean forEncryption, byte[] key) { + WorkingKey = generateWorkingKey(key, forEncryption); + this.forEncryption = forEncryption; + return; + } + public int processBlock(byte[] in, int inOff, byte[] out, int outOff) { if (WorkingKey == null) { throw new IllegalStateException("AES engine not initialised"); @@ -405,123 +526,4 @@ public class AESLightEngine { public void reset() { } - - private void encryptBlock(byte[] in, int inOff, byte[] out, int outOff, int[][] KW) { - int C0 = littleEndianToInt(in, inOff + 0); - int C1 = littleEndianToInt(in, inOff + 4); - int C2 = littleEndianToInt(in, inOff + 8); - int C3 = littleEndianToInt(in, inOff + 12); - - int t0 = C0 ^ KW[0][0]; - int t1 = C1 ^ KW[0][1]; - int t2 = C2 ^ KW[0][2]; - - int r = 1, r0, r1, r2, r3 = C3 ^ KW[0][3]; - while (r < ROUNDS - 1) { - r0 = mcol((S[t0 & 255] & 255) ^ ((S[(t1 >> 8) & 255] & 255) << 8) ^ ((S[(t2 >> 16) & 255] & 255) << 16) - ^ (S[(r3 >> 24) & 255] << 24)) ^ KW[r][0]; - r1 = mcol((S[t1 & 255] & 255) ^ ((S[(t2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) - ^ (S[(t0 >> 24) & 255] << 24)) ^ KW[r][1]; - r2 = mcol((S[t2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(t0 >> 16) & 255] & 255) << 16) - ^ (S[(t1 >> 24) & 255] << 24)) ^ KW[r][2]; - r3 = mcol((S[r3 & 255] & 255) ^ ((S[(t0 >> 8) & 255] & 255) << 8) ^ ((S[(t1 >> 16) & 255] & 255) << 16) - ^ (S[(t2 >> 24) & 255] << 24)) ^ KW[r++][3]; - t0 = mcol((S[r0 & 255] & 255) ^ ((S[(r1 >> 8) & 255] & 255) << 8) ^ ((S[(r2 >> 16) & 255] & 255) << 16) - ^ (S[(r3 >> 24) & 255] << 24)) ^ KW[r][0]; - t1 = mcol((S[r1 & 255] & 255) ^ ((S[(r2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) - ^ (S[(r0 >> 24) & 255] << 24)) ^ KW[r][1]; - t2 = mcol((S[r2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(r0 >> 16) & 255] & 255) << 16) - ^ (S[(r1 >> 24) & 255] << 24)) ^ KW[r][2]; - r3 = mcol((S[r3 & 255] & 255) ^ ((S[(r0 >> 8) & 255] & 255) << 8) ^ ((S[(r1 >> 16) & 255] & 255) << 16) - ^ (S[(r2 >> 24) & 255] << 24)) ^ KW[r++][3]; - } - - r0 = mcol((S[t0 & 255] & 255) ^ ((S[(t1 >> 8) & 255] & 255) << 8) ^ ((S[(t2 >> 16) & 255] & 255) << 16) - ^ (S[(r3 >> 24) & 255] << 24)) ^ KW[r][0]; - r1 = mcol((S[t1 & 255] & 255) ^ ((S[(t2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) - ^ (S[(t0 >> 24) & 255] << 24)) ^ KW[r][1]; - r2 = mcol((S[t2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(t0 >> 16) & 255] & 255) << 16) - ^ (S[(t1 >> 24) & 255] << 24)) ^ KW[r][2]; - r3 = mcol((S[r3 & 255] & 255) ^ ((S[(t0 >> 8) & 255] & 255) << 8) ^ ((S[(t1 >> 16) & 255] & 255) << 16) - ^ (S[(t2 >> 24) & 255] << 24)) ^ KW[r++][3]; - - // the final round is a simple function of S - - C0 = (S[r0 & 255] & 255) ^ ((S[(r1 >> 8) & 255] & 255) << 8) ^ ((S[(r2 >> 16) & 255] & 255) << 16) - ^ (S[(r3 >> 24) & 255] << 24) ^ KW[r][0]; - C1 = (S[r1 & 255] & 255) ^ ((S[(r2 >> 8) & 255] & 255) << 8) ^ ((S[(r3 >> 16) & 255] & 255) << 16) - ^ (S[(r0 >> 24) & 255] << 24) ^ KW[r][1]; - C2 = (S[r2 & 255] & 255) ^ ((S[(r3 >> 8) & 255] & 255) << 8) ^ ((S[(r0 >> 16) & 255] & 255) << 16) - ^ (S[(r1 >> 24) & 255] << 24) ^ KW[r][2]; - C3 = (S[r3 & 255] & 255) ^ ((S[(r0 >> 8) & 255] & 255) << 8) ^ ((S[(r1 >> 16) & 255] & 255) << 16) - ^ (S[(r2 >> 24) & 255] << 24) ^ KW[r][3]; - - intToLittleEndian(C0, out, outOff + 0); - intToLittleEndian(C1, out, outOff + 4); - intToLittleEndian(C2, out, outOff + 8); - intToLittleEndian(C3, out, outOff + 12); - } - - private void decryptBlock(byte[] in, int inOff, byte[] out, int outOff, int[][] KW) { - int C0 = littleEndianToInt(in, inOff + 0); - int C1 = littleEndianToInt(in, inOff + 4); - int C2 = littleEndianToInt(in, inOff + 8); - int C3 = littleEndianToInt(in, inOff + 12); - - int t0 = C0 ^ KW[ROUNDS][0]; - int t1 = C1 ^ KW[ROUNDS][1]; - int t2 = C2 ^ KW[ROUNDS][2]; - - int r = ROUNDS - 1, r0, r1, r2, r3 = C3 ^ KW[ROUNDS][3]; - while (r > 1) { - r0 = inv_mcol((Si[t0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) - ^ ((Si[(t2 >> 16) & 255] & 255) << 16) ^ (Si[(t1 >> 24) & 255] << 24)) ^ KW[r][0]; - r1 = inv_mcol((Si[t1 & 255] & 255) ^ ((Si[(t0 >> 8) & 255] & 255) << 8) - ^ ((Si[(r3 >> 16) & 255] & 255) << 16) ^ (Si[(t2 >> 24) & 255] << 24)) ^ KW[r][1]; - r2 = inv_mcol((Si[t2 & 255] & 255) ^ ((Si[(t1 >> 8) & 255] & 255) << 8) - ^ ((Si[(t0 >> 16) & 255] & 255) << 16) ^ (Si[(r3 >> 24) & 255] << 24)) ^ KW[r][2]; - r3 = inv_mcol((Si[r3 & 255] & 255) ^ ((Si[(t2 >> 8) & 255] & 255) << 8) - ^ ((Si[(t1 >> 16) & 255] & 255) << 16) ^ (Si[(t0 >> 24) & 255] << 24)) ^ KW[r--][3]; - t0 = inv_mcol((Si[r0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) - ^ ((Si[(r2 >> 16) & 255] & 255) << 16) ^ (Si[(r1 >> 24) & 255] << 24)) ^ KW[r][0]; - t1 = inv_mcol((Si[r1 & 255] & 255) ^ ((Si[(r0 >> 8) & 255] & 255) << 8) - ^ ((Si[(r3 >> 16) & 255] & 255) << 16) ^ (Si[(r2 >> 24) & 255] << 24)) ^ KW[r][1]; - t2 = inv_mcol((Si[r2 & 255] & 255) ^ ((Si[(r1 >> 8) & 255] & 255) << 8) - ^ ((Si[(r0 >> 16) & 255] & 255) << 16) ^ (Si[(r3 >> 24) & 255] << 24)) ^ KW[r][2]; - r3 = inv_mcol((Si[r3 & 255] & 255) ^ ((Si[(r2 >> 8) & 255] & 255) << 8) - ^ ((Si[(r1 >> 16) & 255] & 255) << 16) ^ (Si[(r0 >> 24) & 255] << 24)) ^ KW[r--][3]; - } - - r0 = inv_mcol((Si[t0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) ^ ((Si[(t2 >> 16) & 255] & 255) << 16) - ^ (Si[(t1 >> 24) & 255] << 24)) ^ KW[r][0]; - r1 = inv_mcol((Si[t1 & 255] & 255) ^ ((Si[(t0 >> 8) & 255] & 255) << 8) ^ ((Si[(r3 >> 16) & 255] & 255) << 16) - ^ (Si[(t2 >> 24) & 255] << 24)) ^ KW[r][1]; - r2 = inv_mcol((Si[t2 & 255] & 255) ^ ((Si[(t1 >> 8) & 255] & 255) << 8) ^ ((Si[(t0 >> 16) & 255] & 255) << 16) - ^ (Si[(r3 >> 24) & 255] << 24)) ^ KW[r][2]; - r3 = inv_mcol((Si[r3 & 255] & 255) ^ ((Si[(t2 >> 8) & 255] & 255) << 8) ^ ((Si[(t1 >> 16) & 255] & 255) << 16) - ^ (Si[(t0 >> 24) & 255] << 24)) ^ KW[r][3]; - - // the final round's table is a simple function of Si - - C0 = (Si[r0 & 255] & 255) ^ ((Si[(r3 >> 8) & 255] & 255) << 8) ^ ((Si[(r2 >> 16) & 255] & 255) << 16) - ^ (Si[(r1 >> 24) & 255] << 24) ^ KW[0][0]; - C1 = (Si[r1 & 255] & 255) ^ ((Si[(r0 >> 8) & 255] & 255) << 8) ^ ((Si[(r3 >> 16) & 255] & 255) << 16) - ^ (Si[(r2 >> 24) & 255] << 24) ^ KW[0][1]; - C2 = (Si[r2 & 255] & 255) ^ ((Si[(r1 >> 8) & 255] & 255) << 8) ^ ((Si[(r0 >> 16) & 255] & 255) << 16) - ^ (Si[(r3 >> 24) & 255] << 24) ^ KW[0][2]; - C3 = (Si[r3 & 255] & 255) ^ ((Si[(r2 >> 8) & 255] & 255) << 8) ^ ((Si[(r1 >> 16) & 255] & 255) << 16) - ^ (Si[(r0 >> 24) & 255] << 24) ^ KW[0][3]; - - intToLittleEndian(C0, out, outOff + 0); - intToLittleEndian(C1, out, outOff + 4); - intToLittleEndian(C2, out, outOff + 8); - intToLittleEndian(C3, out, outOff + 12); - } - - private int bitsOfSecurity() { - if (WorkingKey == null) { - return 256; - } - return (WorkingKey.length - 7) << 5; - } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/GeneralDigest.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/GeneralDigest.java index d5117197..eb5584b1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/GeneralDigest.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/GeneralDigest.java @@ -51,6 +51,38 @@ public abstract class GeneralDigest { byteCount = t.byteCount; } + public void finish() { + long bitLength = (byteCount << 3); + + // + // add the pad bytes. + // + update((byte) 128); + + while (xBufOff != 0) { + update((byte) 0); + } + + processLength(bitLength); + + processBlock(); + } + + protected abstract void processBlock(); + + protected abstract void processLength(long bitLength); + + protected abstract void processWord(byte[] in, int inOff); + + public void reset() { + byteCount = 0; + + xBufOff = 0; + for (int i = 0; i < xBuf.length; i++) { + xBuf[i] = 0; + } + } + public void update(byte in) { xBuf[xBufOff++] = in; @@ -94,36 +126,4 @@ public abstract class GeneralDigest { len--; } } - - public void finish() { - long bitLength = (byteCount << 3); - - // - // add the pad bytes. - // - update((byte) 128); - - while (xBufOff != 0) { - update((byte) 0); - } - - processLength(bitLength); - - processBlock(); - } - - public void reset() { - byteCount = 0; - - xBufOff = 0; - for (int i = 0; i < xBuf.length; i++) { - xBuf[i] = 0; - } - } - - protected abstract void processWord(byte[] in, int inOff); - - protected abstract void processLength(long bitLength); - - protected abstract void processBlock(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/MD5Digest.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/MD5Digest.java index 1ca96c9f..6d2f051b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/MD5Digest.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/MD5Digest.java @@ -28,8 +28,46 @@ package net.lax1dude.eaglercraft.v1_8.crypto; public class MD5Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 16; - private int H1, H2, H3, H4; // IV's + // + // round 1 left rotates + // + private static final int S11 = 7; + private static final int S12 = 12; + private static final int S13 = 17; + + private static final int S14 = 22; + + // + // round 2 left rotates + // + private static final int S21 = 5; + + private static final int S22 = 9; + + private static final int S23 = 14; + + private static final int S24 = 20; + + // + // round 3 left rotates + // + private static final int S31 = 4; + + private static final int S32 = 11; + + private static final int S33 = 16; + + private static final int S34 = 23; + // + // round 4 left rotates + // + private static final int S41 = 6; + private static final int S42 = 10; + private static final int S43 = 15; + + private static final int S44 = 21; + private int H1, H2, H3, H4; // IV's private int[] X = new int[16]; private int xOff; @@ -40,39 +78,6 @@ public class MD5Digest extends GeneralDigest { reset(); } - public String getAlgorithmName() { - return "MD5"; - } - - public int getDigestSize() { - return DIGEST_LENGTH; - } - - protected void processWord(byte[] in, int inOff) { - X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8) | ((in[inOff + 2] & 0xff) << 16) - | ((in[inOff + 3] & 0xff) << 24); - - if (xOff == 16) { - processBlock(); - } - } - - protected void processLength(long bitLength) { - if (xOff > 14) { - processBlock(); - } - - X[14] = (int) (bitLength & 0xffffffff); - X[15] = (int) (bitLength >>> 32); - } - - private void unpackWord(int word, byte[] out, int outOff) { - out[outOff] = (byte) word; - out[outOff + 1] = (byte) (word >>> 8); - out[outOff + 2] = (byte) (word >>> 16); - out[outOff + 3] = (byte) (word >>> 24); - } - public int doFinal(byte[] out, int outOff) { finish(); @@ -86,63 +91,6 @@ public class MD5Digest extends GeneralDigest { return DIGEST_LENGTH; } - /** - * reset the chaining variables to the IV values. - */ - public void reset() { - super.reset(); - - H1 = 0x67452301; - H2 = 0xefcdab89; - H3 = 0x98badcfe; - H4 = 0x10325476; - - xOff = 0; - - for (int i = 0; i != X.length; i++) { - X[i] = 0; - } - } - - // - // round 1 left rotates - // - private static final int S11 = 7; - private static final int S12 = 12; - private static final int S13 = 17; - private static final int S14 = 22; - - // - // round 2 left rotates - // - private static final int S21 = 5; - private static final int S22 = 9; - private static final int S23 = 14; - private static final int S24 = 20; - - // - // round 3 left rotates - // - private static final int S31 = 4; - private static final int S32 = 11; - private static final int S33 = 16; - private static final int S34 = 23; - - // - // round 4 left rotates - // - private static final int S41 = 6; - private static final int S42 = 10; - private static final int S43 = 15; - private static final int S44 = 21; - - /* - * rotate int x left n bits. - */ - private int rotateLeft(int x, int n) { - return (x << n) | (x >>> (32 - n)); - } - /* * F, G, H and I are the basic MD5 functions. */ @@ -154,6 +102,14 @@ public class MD5Digest extends GeneralDigest { return (u & w) | (v & ~w); } + public String getAlgorithmName() { + return "MD5"; + } + + public int getDigestSize() { + return DIGEST_LENGTH; + } + private int H(int u, int v, int w) { return u ^ v ^ w; } @@ -262,4 +218,54 @@ public class MD5Digest extends GeneralDigest { } } + protected void processLength(long bitLength) { + if (xOff > 14) { + processBlock(); + } + + X[14] = (int) (bitLength & 0xffffffff); + X[15] = (int) (bitLength >>> 32); + } + + protected void processWord(byte[] in, int inOff) { + X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8) | ((in[inOff + 2] & 0xff) << 16) + | ((in[inOff + 3] & 0xff) << 24); + + if (xOff == 16) { + processBlock(); + } + } + + /** + * reset the chaining variables to the IV values. + */ + public void reset() { + super.reset(); + + H1 = 0x67452301; + H2 = 0xefcdab89; + H3 = 0x98badcfe; + H4 = 0x10325476; + + xOff = 0; + + for (int i = 0; i != X.length; i++) { + X[i] = 0; + } + } + + /* + * rotate int x left n bits. + */ + private int rotateLeft(int x, int n) { + return (x << n) | (x >>> (32 - n)); + } + + private void unpackWord(int word, byte[] out, int outOff) { + out[outOff] = (byte) word; + out[outOff + 1] = (byte) (word >>> 8); + out[outOff + 2] = (byte) (word >>> 16); + out[outOff + 3] = (byte) (word >>> 24); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA1Digest.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA1Digest.java index 2a06c47e..9e78aa3f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA1Digest.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA1Digest.java @@ -31,9 +31,20 @@ package net.lax1dude.eaglercraft.v1_8.crypto; public class SHA1Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 20; + // + // Additive constants + // + private static final int Y1 = 0x5a827999; + + private static final int Y2 = 0x6ed9eba1; + private static final int Y3 = 0x8f1bbcdc; + + private static final int Y4 = 0xca62c1d6; + private int H1, H2, H3, H4, H5; private int[] X = new int[80]; + private int xOff; /** @@ -59,39 +70,6 @@ public class SHA1Digest extends GeneralDigest { xOff = t.xOff; } - public String getAlgorithmName() { - return "SHA-1"; - } - - public int getDigestSize() { - return DIGEST_LENGTH; - } - - protected void processWord(byte[] in, int inOff) { - X[xOff++] = ((in[inOff] & 0xff) << 24) | ((in[inOff + 1] & 0xff) << 16) | ((in[inOff + 2] & 0xff) << 8) - | ((in[inOff + 3] & 0xff)); - - if (xOff == 16) { - processBlock(); - } - } - - private void unpackWord(int word, byte[] out, int outOff) { - out[outOff] = (byte) (word >>> 24); - out[outOff + 1] = (byte) (word >>> 16); - out[outOff + 2] = (byte) (word >>> 8); - out[outOff + 3] = (byte) word; - } - - protected void processLength(long bitLength) { - if (xOff > 14) { - processBlock(); - } - - X[14] = (int) (bitLength >>> 32); - X[15] = (int) (bitLength & 0xffffffff); - } - public int doFinal(byte[] out, int outOff) { finish(); @@ -106,46 +84,24 @@ public class SHA1Digest extends GeneralDigest { return DIGEST_LENGTH; } - /** - * reset the chaining variables - */ - public void reset() { - super.reset(); - - H1 = 0x67452301; - H2 = 0xefcdab89; - H3 = 0x98badcfe; - H4 = 0x10325476; - H5 = 0xc3d2e1f0; - - xOff = 0; - for (int i = 0; i != X.length; i++) { - X[i] = 0; - } - } - - // - // Additive constants - // - private static final int Y1 = 0x5a827999; - private static final int Y2 = 0x6ed9eba1; - private static final int Y3 = 0x8f1bbcdc; - private static final int Y4 = 0xca62c1d6; - private int f(int u, int v, int w) { return ((u & v) | ((~u) & w)); } - private int h(int u, int v, int w) { - return (u ^ v ^ w); - } - private int g(int u, int v, int w) { return ((u & v) | (u & w) | (v & w)); } - private int rotateLeft(int x, int n) { - return (x << n) | (x >>> (32 - n)); + public String getAlgorithmName() { + return "SHA-1"; + } + + public int getDigestSize() { + return DIGEST_LENGTH; + } + + private int h(int u, int v, int w) { + return (u ^ v ^ w); } protected void processBlock() { @@ -231,4 +187,51 @@ public class SHA1Digest extends GeneralDigest { X[i] = 0; } } + + protected void processLength(long bitLength) { + if (xOff > 14) { + processBlock(); + } + + X[14] = (int) (bitLength >>> 32); + X[15] = (int) (bitLength & 0xffffffff); + } + + protected void processWord(byte[] in, int inOff) { + X[xOff++] = ((in[inOff] & 0xff) << 24) | ((in[inOff + 1] & 0xff) << 16) | ((in[inOff + 2] & 0xff) << 8) + | ((in[inOff + 3] & 0xff)); + + if (xOff == 16) { + processBlock(); + } + } + + /** + * reset the chaining variables + */ + public void reset() { + super.reset(); + + H1 = 0x67452301; + H2 = 0xefcdab89; + H3 = 0x98badcfe; + H4 = 0x10325476; + H5 = 0xc3d2e1f0; + + xOff = 0; + for (int i = 0; i != X.length; i++) { + X[i] = 0; + } + } + + private int rotateLeft(int x, int n) { + return (x << n) | (x >>> (32 - n)); + } + + private void unpackWord(int word, byte[] out, int outOff) { + out[outOff] = (byte) (word >>> 24); + out[outOff + 1] = (byte) (word >>> 16); + out[outOff + 2] = (byte) (word >>> 8); + out[outOff + 3] = (byte) word; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA256Digest.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA256Digest.java index 2d799a84..3b6246fc 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA256Digest.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/crypto/SHA256Digest.java @@ -25,14 +25,18 @@ public class SHA256Digest extends GeneralDigest { private static final int DIGEST_LENGTH = 32; - private int H1, H2, H3, H4, H5, H6, H7, H8; - - private int[] X = new int[64]; - private int xOff; - - public SHA256Digest() { - reset(); - } + /* + * SHA-256 Constants (represent the first 32 bits of the fractional parts of the + * cube roots of the first sixty-four prime numbers) + */ + static final int K[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, + 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, + 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, + 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, + 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, + 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, + 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public static int bigEndianToInt(byte[] bs, int off) { int n = bs[off] << 24; @@ -49,6 +53,12 @@ public class SHA256Digest extends GeneralDigest { } } + /* SHA-256 functions */ + private static int Ch(int x, int y, int z) { + return (x & y) ^ ((~x) & z); +// return z ^ (x & (y ^ z)); + } + public static byte[] intToBigEndian(int n) { byte[] bs = new byte[4]; intToBigEndian(n, bs, 0); @@ -62,21 +72,35 @@ public class SHA256Digest extends GeneralDigest { bs[++off] = (byte) (n); } - protected void processWord(byte[] in, int inOff) { - X[xOff] = bigEndianToInt(in, inOff); - - if (++xOff == 16) { - processBlock(); - } + private static int Maj(int x, int y, int z) { +// return (x & y) ^ (x & z) ^ (y & z); + return (x & y) | (z & (x ^ y)); } - protected void processLength(long bitLength) { - if (xOff > 14) { - processBlock(); - } + private static int Sum0(int x) { + return ((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10)); + } - X[14] = (int) (bitLength >>> 32); - X[15] = (int) (bitLength & 0xffffffff); + private static int Sum1(int x) { + return ((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7)); + } + + private static int Theta0(int x) { + return ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3); + } + + private static int Theta1(int x) { + return ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10); + } + + private int H1, H2, H3, H4, H5, H6, H7, H8; + + private int[] X = new int[64]; + + private int xOff; + + public SHA256Digest() { + reset(); } public int doFinal(byte[] out, int outOff) { @@ -96,32 +120,6 @@ public class SHA256Digest extends GeneralDigest { return DIGEST_LENGTH; } - /** - * reset the chaining variables - */ - public void reset() { - super.reset(); - - /* - * SHA-256 initial hash value The first 32 bits of the fractional parts of the - * square roots of the first eight prime numbers - */ - - H1 = 0x6a09e667; - H2 = 0xbb67ae85; - H3 = 0x3c6ef372; - H4 = 0xa54ff53a; - H5 = 0x510e527f; - H6 = 0x9b05688c; - H7 = 0x1f83d9ab; - H8 = 0x5be0cd19; - - xOff = 0; - for (int i = 0; i != X.length; i++) { - X[i] = 0; - } - } - protected void processBlock() { // // expand 16 word block into 64 word blocks. @@ -211,44 +209,47 @@ public class SHA256Digest extends GeneralDigest { } } - /* SHA-256 functions */ - private static int Ch(int x, int y, int z) { - return (x & y) ^ ((~x) & z); -// return z ^ (x & (y ^ z)); + protected void processLength(long bitLength) { + if (xOff > 14) { + processBlock(); + } + + X[14] = (int) (bitLength >>> 32); + X[15] = (int) (bitLength & 0xffffffff); } - private static int Maj(int x, int y, int z) { -// return (x & y) ^ (x & z) ^ (y & z); - return (x & y) | (z & (x ^ y)); + protected void processWord(byte[] in, int inOff) { + X[xOff] = bigEndianToInt(in, inOff); + + if (++xOff == 16) { + processBlock(); + } } - private static int Sum0(int x) { - return ((x >>> 2) | (x << 30)) ^ ((x >>> 13) | (x << 19)) ^ ((x >>> 22) | (x << 10)); - } - - private static int Sum1(int x) { - return ((x >>> 6) | (x << 26)) ^ ((x >>> 11) | (x << 21)) ^ ((x >>> 25) | (x << 7)); - } - - private static int Theta0(int x) { - return ((x >>> 7) | (x << 25)) ^ ((x >>> 18) | (x << 14)) ^ (x >>> 3); - } - - private static int Theta1(int x) { - return ((x >>> 17) | (x << 15)) ^ ((x >>> 19) | (x << 13)) ^ (x >>> 10); - } - - /* - * SHA-256 Constants (represent the first 32 bits of the fractional parts of the - * cube roots of the first sixty-four prime numbers) + /** + * reset the chaining variables */ - static final int K[] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, - 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, - 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, - 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, - 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, - 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; + public void reset() { + super.reset(); + + /* + * SHA-256 initial hash value The first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers + */ + + H1 = 0x6a09e667; + H2 = 0xbb67ae85; + H3 = 0x3c6ef372; + H4 = 0xa54ff53a; + H5 = 0x510e527f; + H6 = 0x9b05688c; + H7 = 0x1f83d9ab; + H8 = 0x5be0cd19; + + xOff = 0; + for (int i = 0; i != X.length; i++) { + X[i] = 0; + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/CancellationException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/CancellationException.java index ac9a1b20..d3511fe8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/CancellationException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/CancellationException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.futures; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -18,7 +19,7 @@ package net.lax1dude.eaglercraft.v1_8.futures; public class CancellationException extends IllegalStateException { public CancellationException() { - + } public CancellationException(String s) { diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ExecutionException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ExecutionException.java index 87ed91f6..d15376fd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ExecutionException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ExecutionException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.futures; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,14 +21,14 @@ public class ExecutionException extends RuntimeException { public ExecutionException() { } - public ExecutionException(String message, Throwable cause) { - super(message, cause); - } - public ExecutionException(String message) { super(message); } + public ExecutionException(String message, Throwable cause) { + super(message, cause); + } + public ExecutionException(Throwable cause) { super(cause); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Executors.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Executors.java index 313cbe4a..f925282f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Executors.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Executors.java @@ -5,32 +5,21 @@ import java.util.concurrent.Callable; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Executors { - public static Callable callable(Runnable task, T result) { - if (task == null) - throw new NullPointerException(); - return new RunnableAdapter(task, result); - } - - public static Callable callable(Runnable task) { - if (task == null) - throw new NullPointerException(); - return new RunnableAdapter(task, null); - } - static final class RunnableAdapter implements Callable { final Runnable task; final T result; @@ -46,4 +35,16 @@ public class Executors { } } + public static Callable callable(Runnable task) { + if (task == null) + throw new NullPointerException(); + return new RunnableAdapter(task, null); + } + + public static Callable callable(Runnable task, T result) { + if (task == null) + throw new NullPointerException(); + return new RunnableAdapter(task, result); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Future.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Future.java index 48b2235b..47a20660 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Future.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Future.java @@ -5,14 +5,15 @@ import java.util.concurrent.TimeUnit; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -21,11 +22,11 @@ public interface Future { boolean cancel(boolean mayInterruptIfRunning); - boolean isCancelled(); - - boolean isDone(); - V get() throws InterruptedException, ExecutionException; V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException; + + boolean isCancelled(); + + boolean isDone(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/FutureTask.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/FutureTask.java index abd68491..1ec3ba99 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/FutureTask.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/FutureTask.java @@ -6,14 +6,15 @@ import java.util.concurrent.TimeUnit; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,41 +25,34 @@ public class FutureTask implements RunnableFuture { private boolean completed; private V result; private Callable callable; - + public FutureTask(Callable callable) { this.callable = callable; } @Override public boolean cancel(boolean mayInterruptIfRunning) { - if(!cancelled) { + if (!cancelled) { cancelled = true; - if(!completed) { + if (!completed) { done(); } } return true; } - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public boolean isDone() { - return cancelled || completed; + protected void done() { } @Override public V get() throws InterruptedException, ExecutionException { - if(!completed) { - if(!cancelled) { + if (!completed) { + if (!cancelled) { try { result = callable.call(); - }catch(Throwable t) { + } catch (Throwable t) { throw new ExecutionException(t); - }finally { + } finally { completed = true; done(); } @@ -72,6 +66,16 @@ public class FutureTask implements RunnableFuture { return get(); } + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public boolean isDone() { + return cancelled || completed; + } + @Override public void run() { try { @@ -82,8 +86,5 @@ public class FutureTask implements RunnableFuture { throw new ExecutionException(t); } } - - protected void done() { - } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Futures.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Futures.java index 769da205..b4ff68cb 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Futures.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/Futures.java @@ -13,20 +13,54 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Futures { + private static class ImmediateCancelledFuture extends ImmediateFuture { + + private final CancellationException thrown; + + ImmediateCancelledFuture() { + this.thrown = new CancellationException("Immediate cancelled future."); + } + + @Override + public V get() { + throw new CancellationException("Task was cancelled.", thrown); + } + + @Override + public boolean isCancelled() { + return true; + } + } + + private static class ImmediateFailedFuture extends ImmediateFuture { + + private final Throwable thrown; + + ImmediateFailedFuture(Throwable thrown) { + this.thrown = thrown; + } + + @Override + public V get() throws ExecutionException { + throw new ExecutionException(thrown); + } + } + private abstract static class ImmediateFuture implements ListenableFuture { private static final Logger log = LogManager.getLogger(ImmediateFuture.class.getName()); @@ -82,41 +116,8 @@ public class Futures { } } - private static class ImmediateFailedFuture extends ImmediateFuture { - - private final Throwable thrown; - - ImmediateFailedFuture(Throwable thrown) { - this.thrown = thrown; - } - - @Override - public V get() throws ExecutionException { - throw new ExecutionException(thrown); - } - } - - private static class ImmediateCancelledFuture extends ImmediateFuture { - - private final CancellationException thrown; - - ImmediateCancelledFuture() { - this.thrown = new CancellationException("Immediate cancelled future."); - } - - @Override - public boolean isCancelled() { - return true; - } - - @Override - public V get() { - throw new CancellationException("Task was cancelled.", thrown); - } - } - - public static ListenableFuture immediateFuture(@Nullable V value) { - return new ImmediateSuccessfulFuture(value); + public static ListenableFuture immediateCancelledFuture() { + return new ImmediateCancelledFuture(); } public static ListenableFuture immediateFailedFuture(Throwable throwable) { @@ -124,8 +125,8 @@ public class Futures { return new ImmediateFailedFuture(throwable); } - public static ListenableFuture immediateCancelledFuture() { - return new ImmediateCancelledFuture(); + public static ListenableFuture immediateFuture(@Nullable V value) { + return new ImmediateSuccessfulFuture(value); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFuture.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFuture.java index d7247aa0..0231bb8d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFuture.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFuture.java @@ -8,20 +8,21 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ListenableFuture extends Future { - + static final Logger futureExceptionLogger = LogManager.getLogger("ListenableFuture"); void addListener(Runnable listener, Executor executor); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFutureTask.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFutureTask.java index eb914064..612fa9c7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFutureTask.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/ListenableFutureTask.java @@ -8,20 +8,25 @@ import java.util.concurrent.Executor; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ListenableFutureTask extends FutureTask implements ListenableFuture { - + + public static ListenableFutureTask create(Callable callableToSchedule) { + return new ListenableFutureTask<>(callableToSchedule); + } + private final List listeners = new ArrayList<>(); public ListenableFutureTask(Callable callable) { @@ -36,16 +41,16 @@ public class ListenableFutureTask extends FutureTask implements Listenable public void run() { executor.execute(listener); // so dumb } - + }); } - + protected void done() { - for(int i = 0, l = listeners.size(); i < l; ++i) { + for (int i = 0, l = listeners.size(); i < l; ++i) { Runnable r = listeners.get(i); try { r.run(); - }catch(Throwable t) { + } catch (Throwable t) { ListenableFuture.futureExceptionLogger.error("Exception caught running future listener!"); ListenableFuture.futureExceptionLogger.error(t); } @@ -53,8 +58,4 @@ public class ListenableFutureTask extends FutureTask implements Listenable listeners.clear(); } - public static ListenableFutureTask create(Callable callableToSchedule) { - return new ListenableFutureTask<>(callableToSchedule); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/RunnableFuture.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/RunnableFuture.java index 6a653d94..08685b08 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/RunnableFuture.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/futures/RunnableFuture.java @@ -3,18 +3,19 @@ package net.lax1dude.eaglercraft.v1_8.futures; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface RunnableFuture extends Runnable, Future { - void run(); + void run(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/AbstractWebSocketClient.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/AbstractWebSocketClient.java index ff588197..3ce5c9c3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/AbstractWebSocketClient.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/AbstractWebSocketClient.java @@ -8,14 +8,15 @@ import java.util.List; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,119 +34,68 @@ public abstract class AbstractWebSocketClient implements IWebSocketClient { protected void addRecievedFrame(IWebSocketFrame frame) { boolean str = frame.isString(); - synchronized(recievedPacketBuffer) { + synchronized (recievedPacketBuffer) { recievedPacketBuffer.add(frame); - if(str) { + if (str) { ++availableStringFrames; - }else { + } else { ++availableBinaryFrames; } } } + @Override + public int availableBinaryFrames() { + synchronized (recievedPacketBuffer) { + return availableBinaryFrames; + } + } + @Override public int availableFrames() { - synchronized(recievedPacketBuffer) { + synchronized (recievedPacketBuffer) { return availableStringFrames + availableBinaryFrames; } } @Override - public IWebSocketFrame getNextFrame() { - synchronized(recievedPacketBuffer) { - if(!recievedPacketBuffer.isEmpty()) { - IWebSocketFrame frame = recievedPacketBuffer.remove(0); - if(frame.isString()) { - --availableStringFrames; - }else { - --availableBinaryFrames; - } - return frame; - }else { - return null; - } + public int availableStringFrames() { + synchronized (recievedPacketBuffer) { + return availableStringFrames; } } @Override - public List getNextFrames() { - synchronized(recievedPacketBuffer) { - if(!recievedPacketBuffer.isEmpty()) { - List ret = new ArrayList<>(recievedPacketBuffer); - recievedPacketBuffer.clear(); - availableStringFrames = 0; + public void clearBinaryFrames() { + synchronized (recievedPacketBuffer) { + if (availableBinaryFrames > 0) { + Iterator itr = recievedPacketBuffer.iterator(); + while (itr.hasNext()) { + IWebSocketFrame r = itr.next(); + if (!r.isString()) { + itr.remove(); + } + } availableBinaryFrames = 0; - return ret; - }else { - return null; } } } @Override public void clearFrames() { - synchronized(recievedPacketBuffer) { + synchronized (recievedPacketBuffer) { recievedPacketBuffer.clear(); } } - @Override - public int availableStringFrames() { - synchronized(recievedPacketBuffer) { - return availableStringFrames; - } - } - - @Override - public IWebSocketFrame getNextStringFrame() { - synchronized(recievedPacketBuffer) { - if(availableStringFrames > 0) { - Iterator itr = recievedPacketBuffer.iterator(); - while(itr.hasNext()) { - IWebSocketFrame r = itr.next(); - if(r.isString()) { - itr.remove(); - --availableStringFrames; - return r; - } - } - availableStringFrames = 0; - return null; - }else { - return null; - } - } - } - - @Override - public List getNextStringFrames() { - synchronized(recievedPacketBuffer) { - if(availableStringFrames > 0) { - List ret = new ArrayList<>(availableStringFrames); - Iterator itr = recievedPacketBuffer.iterator(); - while(itr.hasNext()) { - IWebSocketFrame r = itr.next(); - if(r.isString()) { - itr.remove(); - ret.add(r); - } - } - availableStringFrames = 0; - return ret; - }else { - return null; - } - } - } - @Override public void clearStringFrames() { - synchronized(recievedPacketBuffer) { - if(availableStringFrames > 0) { + synchronized (recievedPacketBuffer) { + if (availableStringFrames > 0) { Iterator itr = recievedPacketBuffer.iterator(); - while(itr.hasNext()) { + while (itr.hasNext()) { IWebSocketFrame r = itr.next(); - if(r.isString()) { + if (r.isString()) { itr.remove(); } } @@ -154,74 +104,125 @@ public abstract class AbstractWebSocketClient implements IWebSocketClient { } } - @Override - public int availableBinaryFrames() { - synchronized(recievedPacketBuffer) { - return availableBinaryFrames; - } - } - - @Override - public IWebSocketFrame getNextBinaryFrame() { - synchronized(recievedPacketBuffer) { - if(availableBinaryFrames > 0) { - Iterator itr = recievedPacketBuffer.iterator(); - while(itr.hasNext()) { - IWebSocketFrame r = itr.next(); - if(!r.isString()) { - itr.remove(); - --availableBinaryFrames; - return r; - } - } - availableBinaryFrames = 0; - return null; - }else { - return null; - } - } - } - - @Override - public List getNextBinaryFrames() { - synchronized(recievedPacketBuffer) { - if(availableBinaryFrames > 0) { - List ret = new ArrayList<>(availableBinaryFrames); - Iterator itr = recievedPacketBuffer.iterator(); - while(itr.hasNext()) { - IWebSocketFrame r = itr.next(); - if(!r.isString()) { - itr.remove(); - ret.add(r); - } - } - availableBinaryFrames = 0; - return ret; - }else { - return null; - } - } - } - - @Override - public void clearBinaryFrames() { - synchronized(recievedPacketBuffer) { - if(availableBinaryFrames > 0) { - Iterator itr = recievedPacketBuffer.iterator(); - while(itr.hasNext()) { - IWebSocketFrame r = itr.next(); - if(!r.isString()) { - itr.remove(); - } - } - availableBinaryFrames = 0; - } - } - } - @Override public String getCurrentURI() { return currentURI; } + @Override + public IWebSocketFrame getNextBinaryFrame() { + synchronized (recievedPacketBuffer) { + if (availableBinaryFrames > 0) { + Iterator itr = recievedPacketBuffer.iterator(); + while (itr.hasNext()) { + IWebSocketFrame r = itr.next(); + if (!r.isString()) { + itr.remove(); + --availableBinaryFrames; + return r; + } + } + availableBinaryFrames = 0; + return null; + } else { + return null; + } + } + } + + @Override + public List getNextBinaryFrames() { + synchronized (recievedPacketBuffer) { + if (availableBinaryFrames > 0) { + List ret = new ArrayList<>(availableBinaryFrames); + Iterator itr = recievedPacketBuffer.iterator(); + while (itr.hasNext()) { + IWebSocketFrame r = itr.next(); + if (!r.isString()) { + itr.remove(); + ret.add(r); + } + } + availableBinaryFrames = 0; + return ret; + } else { + return null; + } + } + } + + @Override + public IWebSocketFrame getNextFrame() { + synchronized (recievedPacketBuffer) { + if (!recievedPacketBuffer.isEmpty()) { + IWebSocketFrame frame = recievedPacketBuffer.remove(0); + if (frame.isString()) { + --availableStringFrames; + } else { + --availableBinaryFrames; + } + return frame; + } else { + return null; + } + } + } + + @Override + public List getNextFrames() { + synchronized (recievedPacketBuffer) { + if (!recievedPacketBuffer.isEmpty()) { + List ret = new ArrayList<>(recievedPacketBuffer); + recievedPacketBuffer.clear(); + availableStringFrames = 0; + availableBinaryFrames = 0; + return ret; + } else { + return null; + } + } + } + + @Override + public IWebSocketFrame getNextStringFrame() { + synchronized (recievedPacketBuffer) { + if (availableStringFrames > 0) { + Iterator itr = recievedPacketBuffer.iterator(); + while (itr.hasNext()) { + IWebSocketFrame r = itr.next(); + if (r.isString()) { + itr.remove(); + --availableStringFrames; + return r; + } + } + availableStringFrames = 0; + return null; + } else { + return null; + } + } + } + + @Override + public List getNextStringFrames() { + synchronized (recievedPacketBuffer) { + if (availableStringFrames > 0) { + List ret = new ArrayList<>(availableStringFrames); + Iterator itr = recievedPacketBuffer.iterator(); + while (itr.hasNext()) { + IWebSocketFrame r = itr.next(); + if (r.isString()) { + itr.remove(); + ret.add(r); + } + } + availableStringFrames = 0; + return ret; + } else { + return null; + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EaglerMissingResourceException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EaglerMissingResourceException.java index a4791d18..1fcc8729 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EaglerMissingResourceException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EaglerMissingResourceException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,14 +21,14 @@ public class EaglerMissingResourceException extends RuntimeException { public EaglerMissingResourceException() { } - public EaglerMissingResourceException(String message, Throwable cause) { - super(message, cause); - } - public EaglerMissingResourceException(String message) { super(message); } + public EaglerMissingResourceException(String message, Throwable cause) { + super(message, cause); + } + public EaglerMissingResourceException(Throwable cause) { super(cause); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumCursorType.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumCursorType.java index 11f6dd1a..4a24f030 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumCursorType.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumCursorType.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumEaglerConnectionState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumEaglerConnectionState.java index d44ed70e..93408a0d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumEaglerConnectionState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumEaglerConnectionState.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,18 +21,18 @@ public enum EnumEaglerConnectionState { private final boolean typeClosed; private final boolean typeOpen; - + private EnumEaglerConnectionState(boolean typeClosed, boolean typeOpen) { this.typeClosed = typeClosed; this.typeOpen = typeOpen; } - + public boolean isClosed() { return typeClosed; } - + public boolean isOpen() { return typeOpen; } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireKeyboardEvent.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireKeyboardEvent.java index b74e605e..e1481505 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireKeyboardEvent.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireKeyboardEvent.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireMouseEvent.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireMouseEvent.java index 5e29c32e..d49f344b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireMouseEvent.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumFireMouseEvent.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformANGLE.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformANGLE.java index 43fae4df..f423031a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformANGLE.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformANGLE.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,9 +25,48 @@ public enum EnumPlatformANGLE { OPENGLES(225283 /* GLFW_ANGLE_PLATFORM_TYPE_OPENGLES */, "opengles", "OpenGL ES"), METAL(225288 /* GLFW_ANGLE_PLATFORM_TYPE_METAL */, "metal", "Metal"), VULKAN(225287 /* GLFW_ANGLE_PLATFORM_TYPE_VULKAN */, "vulkan", "Vulkan"); - + + public static EnumPlatformANGLE fromGLRendererString(String str) { + str = str.toLowerCase(); + if (str.contains("direct3d11") || str.contains("d3d11")) { + return D3D11; + } else if (str.contains("direct3d9") || str.contains("d3d9")) { + return D3D9; + } else if (str.contains("opengl es")) { + return OPENGLES; + } else if (str.contains("opengl")) { + return OPENGL; + } else if (str.contains("metal")) { + return METAL; + } else if (str.contains("vulkan")) { + return VULKAN; + } else { + return DEFAULT; + } + } + + public static EnumPlatformANGLE fromId(String id) { + if (id.equals("d3d11") || id.equals("d3d") || id.equals("dx11")) { + return D3D11; + } else if (id.equals("d3d9") || id.equals("dx9")) { + return D3D9; + } else if (id.equals("opengl")) { + return OPENGL; + } else if (id.equals("opengles")) { + return OPENGLES; + } else if (id.equals("metal")) { + return METAL; + } else if (id.equals("vulkan")) { + return VULKAN; + } else { + return DEFAULT; + } + } + public final int eglEnum; + public final String id; + public final String name; private EnumPlatformANGLE(int eglEnum, String id, String name) { @@ -34,46 +74,9 @@ public enum EnumPlatformANGLE { this.id = id; this.name = name; } - + public String toString() { return id; } - - public static EnumPlatformANGLE fromId(String id) { - if(id.equals("d3d11") || id.equals("d3d") || id.equals("dx11")) { - return D3D11; - }else if(id.equals("d3d9") || id.equals("dx9")) { - return D3D9; - }else if(id.equals("opengl")) { - return OPENGL; - }else if(id.equals("opengles")) { - return OPENGLES; - }else if(id.equals("metal")) { - return METAL; - }else if(id.equals("vulkan")) { - return VULKAN; - }else { - return DEFAULT; - } - } - - public static EnumPlatformANGLE fromGLRendererString(String str) { - str = str.toLowerCase(); - if(str.contains("direct3d11") || str.contains("d3d11")) { - return D3D11; - }else if(str.contains("direct3d9") || str.contains("d3d9")) { - return D3D9; - }else if(str.contains("opengl es")) { - return OPENGLES; - }else if(str.contains("opengl")) { - return OPENGL; - }else if(str.contains("metal")) { - return METAL; - }else if(str.contains("vulkan")) { - return VULKAN; - }else { - return DEFAULT; - } - } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformAgent.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformAgent.java index dc0171e3..9230369b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformAgent.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformAgent.java @@ -3,63 +3,63 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum EnumPlatformAgent { - DESKTOP("LWJGL3"), CHROME("Chrome"), EDGE("Edge"), IE("IE"), - FIREFOX("Firefox"), SAFARI("Safari"), OPERA("Opera"), WEBKIT("WebKit"), - GECKO("Gecko"), UNKNOWN("Unknown"); - - private final String name; - - private EnumPlatformAgent(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public String toString() { - return name; - } - + DESKTOP("LWJGL3"), CHROME("Chrome"), EDGE("Edge"), IE("IE"), FIREFOX("Firefox"), SAFARI("Safari"), OPERA("Opera"), + WEBKIT("WebKit"), GECKO("Gecko"), UNKNOWN("Unknown"); + public static EnumPlatformAgent getFromUA(String ua) { - if(ua == null) { + if (ua == null) { return UNKNOWN; } ua = " " + ua.toLowerCase(); - if(ua.contains(" edg/")) { + if (ua.contains(" edg/")) { return EDGE; - }else if(ua.contains(" opr/")) { + } else if (ua.contains(" opr/")) { return OPERA; - }else if(ua.contains(" chrome/") || ua.contains(" chromium/")) { + } else if (ua.contains(" chrome/") || ua.contains(" chromium/")) { return CHROME; - }else if(ua.contains(" firefox/")) { + } else if (ua.contains(" firefox/")) { return FIREFOX; - }else if(ua.contains(" safari/")) { + } else if (ua.contains(" safari/")) { return SAFARI; - }else if(ua.contains(" trident/") || ua.contains(" msie")) { + } else if (ua.contains(" trident/") || ua.contains(" msie")) { return IE; - }else if(ua.contains(" webkit/")) { + } else if (ua.contains(" webkit/")) { return WEBKIT; - }else if(ua.contains(" gecko/")) { + } else if (ua.contains(" gecko/")) { return GECKO; - }else if(ua.contains(" desktop/")) { + } else if (ua.contains(" desktop/")) { return DESKTOP; - }else { + } else { return UNKNOWN; } } - + + private final String name; + + private EnumPlatformAgent(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public String toString() { + return name; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformOS.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformOS.java index bfa1eff3..eccb40e6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformOS.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformOS.java @@ -5,14 +5,15 @@ import net.minecraft.util.Util; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -21,60 +22,61 @@ public enum EnumPlatformOS { WINDOWS("Windows", Util.EnumOS.WINDOWS), MACOS("MacOS", Util.EnumOS.OSX), LINUX("Linux", Util.EnumOS.LINUX), CHROMEBOOK_LINUX("ChromeOS", Util.EnumOS.LINUX), OTHER("Unknown", Util.EnumOS.UNKNOWN); + public static EnumPlatformOS getFromJVM(String osNameProperty) { + if (osNameProperty == null) { + return OTHER; + } + osNameProperty = osNameProperty.toLowerCase(); + if (osNameProperty.contains("chrome")) { + return CHROMEBOOK_LINUX; + } else if (osNameProperty.contains("linux")) { + return LINUX; + } else if (osNameProperty.contains("windows") || osNameProperty.contains("win32")) { + return WINDOWS; + } else if (osNameProperty.contains("macos") || osNameProperty.contains("osx")) { + return MACOS; + } else { + return OTHER; + } + } + + public static EnumPlatformOS getFromUA(String ua) { + if (ua == null) { + return OTHER; + } + ua = " " + ua.toLowerCase(); + if (ua.contains(" cros")) { + return CHROMEBOOK_LINUX; + } else if (ua.contains(" linux")) { + return LINUX; + } else if (ua.contains(" windows") || ua.contains(" win32") || ua.contains(" win64")) { + return WINDOWS; + } else if (ua.contains(" macos") || ua.contains(" osx")) { + return MACOS; + } else { + return OTHER; + } + } + private final String name; + private final Util.EnumOS minecraftEnum; - + private EnumPlatformOS(String name, Util.EnumOS minecraftEnum) { this.name = name; this.minecraftEnum = minecraftEnum; } - - public String getName() { - return name; - } - + public Util.EnumOS getMinecraftEnum() { return minecraftEnum; } - + + public String getName() { + return name; + } + public String toString() { return name; } - - public static EnumPlatformOS getFromJVM(String osNameProperty) { - if(osNameProperty == null) { - return OTHER; - } - osNameProperty = osNameProperty.toLowerCase(); - if(osNameProperty.contains("chrome")) { - return CHROMEBOOK_LINUX; - }else if(osNameProperty.contains("linux")) { - return LINUX; - }else if(osNameProperty.contains("windows") || osNameProperty.contains("win32")) { - return WINDOWS; - }else if(osNameProperty.contains("macos") || osNameProperty.contains("osx")) { - return MACOS; - }else { - return OTHER; - } - } - - public static EnumPlatformOS getFromUA(String ua) { - if(ua == null) { - return OTHER; - } - ua = " " + ua.toLowerCase(); - if(ua.contains(" cros")) { - return CHROMEBOOK_LINUX; - }else if(ua.contains(" linux")) { - return LINUX; - }else if(ua.contains(" windows") || ua.contains(" win32") || ua.contains(" win64")) { - return WINDOWS; - }else if(ua.contains(" macos") || ua.contains(" osx")) { - return MACOS; - }else { - return OTHER; - } - } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformType.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformType.java index c0ba932e..59af2dec 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformType.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumPlatformType.java @@ -3,33 +3,34 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum EnumPlatformType { - DESKTOP("Desktop"), JAVASCRIPT("HTML5"); - + DESKTOP("Desktop"), JAVASCRIPT("JavaScript"), ASM("ASM"); + private final String name; - + private EnumPlatformType(String name) { this.name = name; } - + public String getName() { return name; } - + public String toString() { return name; } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumServerRateLimit.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumServerRateLimit.java index 84a4989b..122f9eb9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumServerRateLimit.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumServerRateLimit.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumTouchEvent.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumTouchEvent.java index a94c6537..fd9d01b4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumTouchEvent.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumTouchEvent.java @@ -3,41 +3,42 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum EnumTouchEvent { TOUCHSTART(0), TOUCHMOVE(1), TOUCHEND(2); - - public final int id; - - private EnumTouchEvent(int id) { - this.id = id; - } - - public static EnumTouchEvent getById(int id) { - if(id >= 0 && id < lookup.length) { - return lookup[id]; - }else { - return null; - } - } - + private static final EnumTouchEvent[] lookup = new EnumTouchEvent[3]; - + static { EnumTouchEvent[] v = values(); - for(int i = 0; i < v.length; ++i) { + for (int i = 0; i < v.length; ++i) { lookup[v[i].id] = v[i]; } } + + public static EnumTouchEvent getById(int id) { + if (id >= 0 && id < lookup.length) { + return lookup[id]; + } else { + return null; + } + } + + public final int id; + + private EnumTouchEvent(int id) { + this.id = id; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumWebViewContentMode.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumWebViewContentMode.java index 75ef2a4e..1a19b614 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumWebViewContentMode.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/EnumWebViewContentMode.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/FileChooserResult.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/FileChooserResult.java index e7c70769..24926ba6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/FileChooserResult.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/FileChooserResult.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GLObjectMap.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GLObjectMap.java index 680c1e09..75ec8888 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GLObjectMap.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GLObjectMap.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,7 +21,7 @@ public class GLObjectMap { private int size; private int insertIndex; public int allocatedObjects; - + public GLObjectMap(int initialSize) { this.values = new Object[initialSize]; this.size = initialSize; @@ -28,42 +29,48 @@ public class GLObjectMap { this.allocatedObjects = 0; } - public int register(T obj) { - int start = insertIndex; - do { - ++insertIndex; - if(insertIndex >= size) { - insertIndex = 0; - } - if(insertIndex == start) { - resize(); - return register(obj); - } - }while(values[insertIndex] != null); - values[insertIndex] = obj; - ++allocatedObjects; - return insertIndex + 1; + public void clear() { + if (allocatedObjects == 0) + return; + values = new Object[size]; + insertIndex = 0; + allocatedObjects = 0; } - + public T free(int obj) { --obj; - if(obj >= size || obj < 0) return null; + if (obj >= size || obj < 0) + return null; Object ret = values[obj]; values[obj] = null; --allocatedObjects; return (T) ret; } - + public T get(int obj) { --obj; - if(obj >= size || obj < 0) return null; + if (obj >= size || obj < 0) + return null; return (T) values[obj]; } - - public void set(int obj, T val) { - values[obj] = val; + + public int register(T obj) { + int start = insertIndex; + do { + ++insertIndex; + if (insertIndex >= size) { + insertIndex = 0; + } + if (insertIndex == start) { + resize(); + return register(obj); + } + } while (values[insertIndex] != null); + values[insertIndex] = obj; + ++allocatedObjects; + return insertIndex + 1; } - + private void resize() { int oldSize = size; size += size / 2; @@ -72,10 +79,7 @@ public class GLObjectMap { System.arraycopy(oldValues, 0, values, 0, oldSize); } - public void clear() { - if(allocatedObjects == 0) return; - values = new Object[size]; - insertIndex = 0; - allocatedObjects = 0; + public void set(int obj, T val) { + values[obj] = val; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GamepadConstants.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GamepadConstants.java index fbc04a55..109eea12 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GamepadConstants.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/GamepadConstants.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,20 +54,6 @@ public class GamepadConstants { GLFW_GAMEPAD_BUTTON_LEFT_THUMB = 9, GLFW_GAMEPAD_BUTTON_RIGHT_THUMB = 10, GLFW_GAMEPAD_BUTTON_DPAD_UP = 11, GLFW_GAMEPAD_BUTTON_DPAD_RIGHT = 12, GLFW_GAMEPAD_BUTTON_DPAD_DOWN = 13, GLFW_GAMEPAD_BUTTON_DPAD_LEFT = 14; - private static void registerBtn(int eaglerBtn, int glfwBtn, String name) { - if(eaglerButtonsToGLFW[eaglerBtn] != 0) throw new IllegalArgumentException("Duplicate eaglerButtonsToGLFW entry: " + eaglerBtn + " -> " + glfwBtn); - if(glfwBtn != -1 && glfwButtonsToEagler[glfwBtn] != 0) throw new IllegalArgumentException("Duplicate glfwButtonsToEAGLER entry: " + glfwBtn + " -> " + eaglerBtn); - eaglerButtonsToGLFW[eaglerBtn] = glfwBtn; - if(glfwBtn != -1) glfwButtonsToEagler[glfwBtn] = eaglerBtn; - if(buttonNames[eaglerBtn] != null) throw new IllegalArgumentException("Duplicate buttonNames entry: " + eaglerBtn); - buttonNames[eaglerBtn] = name; - } - - private static void registerAxis(int eaglerAxis, String name) { - if(axisNames[eaglerAxis] != null) throw new IllegalArgumentException("Duplicate axisNames entry: " + eaglerAxis); - axisNames[eaglerAxis] = name; - } - static { registerBtn(GAMEPAD_A, GLFW_GAMEPAD_BUTTON_A, "A"); registerBtn(GAMEPAD_B, GLFW_GAMEPAD_BUTTON_B, "B"); @@ -91,44 +78,63 @@ public class GamepadConstants { registerAxis(GAMEPAD_AXIS_RIGHT_STICK_Y, "Right Stick Y"); } - public static int getEaglerButtonFromBrowser(int button) { - return button; + public static String getAxisName(int button) { + if (button >= 0 && button < axisNames.length) { + return axisNames[button]; + } else { + return "Axis " + button; + } } public static int getBrowserButtonFromEagler(int button) { return button; } + public static String getButtonName(int button) { + if (button >= 0 && button < buttonNames.length) { + return buttonNames[button]; + } else { + return "Button " + button; + } + } + + public static int getEaglerButtonFromBrowser(int button) { + return button; + } + public static int getEaglerButtonFromGLFW(int button) { - if(button >= 0 && button < glfwButtonsToEagler.length) { + if (button >= 0 && button < glfwButtonsToEagler.length) { return glfwButtonsToEagler[button]; - }else { + } else { return -1; } } public static int getGLFWButtonFromEagler(int button) { - if(button >= 0 && button < eaglerButtonsToGLFW.length) { + if (button >= 0 && button < eaglerButtonsToGLFW.length) { return eaglerButtonsToGLFW[button]; - }else { + } else { return -1; } } - public static String getButtonName(int button) { - if(button >= 0 && button < buttonNames.length) { - return buttonNames[button]; - }else { - return "Button " + button; - } + private static void registerAxis(int eaglerAxis, String name) { + if (axisNames[eaglerAxis] != null) + throw new IllegalArgumentException("Duplicate axisNames entry: " + eaglerAxis); + axisNames[eaglerAxis] = name; } - public static String getAxisName(int button) { - if(button >= 0 && button < axisNames.length) { - return axisNames[button]; - }else { - return "Axis " + button; - } + private static void registerBtn(int eaglerBtn, int glfwBtn, String name) { + if (eaglerButtonsToGLFW[eaglerBtn] != 0) + throw new IllegalArgumentException("Duplicate eaglerButtonsToGLFW entry: " + eaglerBtn + " -> " + glfwBtn); + if (glfwBtn != -1 && glfwButtonsToEagler[glfwBtn] != 0) + throw new IllegalArgumentException("Duplicate glfwButtonsToEAGLER entry: " + glfwBtn + " -> " + eaglerBtn); + eaglerButtonsToGLFW[eaglerBtn] = glfwBtn; + if (glfwBtn != -1) + glfwButtonsToEagler[glfwBtn] = eaglerBtn; + if (buttonNames[eaglerBtn] != null) + throw new IllegalArgumentException("Duplicate buttonNames entry: " + eaglerBtn); + buttonNames[eaglerBtn] = name; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioHandle.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioHandle.java index 2080b6c0..952090d4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioHandle.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioHandle.java @@ -3,32 +3,33 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IAudioHandle { - void pause(boolean setPaused); - - void restart(); + void end(); + + void gain(float f); void move(float x, float y, float z); - + + void pause(boolean setPaused); + void pitch(float f); - - void gain(float f); - - void end(); - + + void restart(); + boolean shouldFree(); - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioResource.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioResource.java index c1d9d5b6..58923df4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioResource.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IAudioResource.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferArrayGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferArrayGL.java index 6a28b4dd..aba05534 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferArrayGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferArrayGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferGL.java index ce6479a6..3d1abca6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IBufferGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapter.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapter.java index fa6f350e..59698651 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapter.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapter.java @@ -2,20 +2,22 @@ package net.lax1dude.eaglercraft.v1_8.internal; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayEntry; import org.json.JSONObject; +import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayEntry; + /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,66 +38,66 @@ public interface IClientConfigAdapter { } + boolean allowUpdateDL(); + + boolean allowUpdateSvc(); + String getDefaultLocale(); List getDefaultServerList(); + String getDownloadOfflineButtonLink(); + + IClientConfigAdapterHooks getHooks(); + + JSONObject getIntegratedServerOpts(); + + String getLocalStorageNamespace(); + + List getRelays(); + + String getResourcePacksDB(); + String getServerToJoin(); String getWorldsDB(); - String getResourcePacksDB(); + boolean isAllowBootMenu(); - JSONObject getIntegratedServerOpts(); + boolean isAllowFNAWSkins(); - List getRelays(); + boolean isAllowServerRedirects(); + + boolean isAllowVoiceClient(); + + boolean isCheckRelaysForUpdates(); boolean isCheckShaderGLErrors(); boolean isDemo(); - boolean allowUpdateSvc(); - - boolean allowUpdateDL(); + boolean isEaglerNoDelay(); boolean isEnableDownloadOfflineButton(); - String getDownloadOfflineButtonLink(); - - boolean useSpecialCursors(); - - boolean isLogInvalidCerts(); - - boolean isCheckRelaysForUpdates(); - - boolean isEnableSignatureBadge(); - - boolean isAllowVoiceClient(); - - boolean isAllowFNAWSkins(); - - String getLocalStorageNamespace(); - boolean isEnableMinceraft(); boolean isEnableServerCookies(); - boolean isAllowServerRedirects(); - - boolean isOpenDebugConsoleOnLaunch(); - - boolean isForceWebViewSupport(); + boolean isEnableSignatureBadge(); boolean isEnableWebViewCSP(); - boolean isAllowBootMenu(); - boolean isForceProfanityFilter(); - boolean isEaglerNoDelay(); + boolean isForceWebViewSupport(); + + boolean isLogInvalidCerts(); + + boolean isOpenDebugConsoleOnLaunch(); boolean isRamdiskMode(); - IClientConfigAdapterHooks getHooks(); + boolean useSpecialCursors(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapterHooks.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapterHooks.java index 888e36f5..3e01419d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapterHooks.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IClientConfigAdapterHooks.java @@ -5,26 +5,28 @@ import java.util.function.Consumer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IClientConfigAdapterHooks { - void callLocalStorageSavedHook(String key, String base64); + void callCrashReportHook(String crashReport, Consumer customMessageCB); String callLocalStorageLoadHook(String key); - void callCrashReportHook(String crashReport, Consumer customMessageCB); + void callLocalStorageSavedHook(String key, String base64); - void callScreenChangedHook(String screenName, int scaledWidth, int scaledHeight, int realWidth, int realHeight, int scaleFactor); + void callScreenChangedHook(String screenName, int scaledWidth, int scaledHeight, int realWidth, int realHeight, + int scaleFactor); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IEaglerFilesystem.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IEaglerFilesystem.java index 8ec0faf4..950b0641 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IEaglerFilesystem.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IEaglerFilesystem.java @@ -5,42 +5,43 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IEaglerFilesystem { + void closeHandle(); + + int eaglerCopy(String pathNameOld, String pathNameNew); + + boolean eaglerDelete(String pathName); + + boolean eaglerExists(String pathName); + + void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive); + + boolean eaglerMove(String pathNameOld, String pathNameNew); + + ByteBuffer eaglerRead(String pathName); + + int eaglerSize(String pathName); + + void eaglerWrite(String pathName, ByteBuffer data); + String getFilesystemName(); String getInternalDBName(); boolean isRamdisk(); - boolean eaglerDelete(String pathName); - - ByteBuffer eaglerRead(String pathName); - - void eaglerWrite(String pathName, ByteBuffer data); - - boolean eaglerExists(String pathName); - - boolean eaglerMove(String pathNameOld, String pathNameNew); - - int eaglerCopy(String pathNameOld, String pathNameNew); - - int eaglerSize(String pathName); - - void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive); - - void closeHandle(); - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IFramebufferGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IFramebufferGL.java index a6c33f89..1a3f0ff3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IFramebufferGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IFramebufferGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IObjectGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IObjectGL.java index 14382bd3..1ee6a60a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IObjectGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IObjectGL.java @@ -3,20 +3,21 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IObjectGL { - + void free(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IPCPacketData.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IPCPacketData.java index 40f02b95..06f14f5a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IPCPacketData.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IPCPacketData.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IProgramGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IProgramGL.java index 31b38b1d..47a3957d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IProgramGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IProgramGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IQueryGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IQueryGL.java index 0dd58062..80449cd5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IQueryGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IQueryGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IRenderbufferGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IRenderbufferGL.java index 5fcb5300..766c39a7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IRenderbufferGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IRenderbufferGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IResourceHandle.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IResourceHandle.java index ea388c65..ce1428ed 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IResourceHandle.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IResourceHandle.java @@ -5,24 +5,25 @@ import java.io.InputStream; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IResourceHandle { - + String getPath(); InputStream inputStream(); - + byte[] toByteArray(); - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IServerQuery.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IServerQuery.java index fc331c75..b0d392d3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IServerQuery.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IServerQuery.java @@ -7,78 +7,60 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IServerQuery { - public static final long defaultTimeout = 10000l; - public static enum QueryReadyState { CONNECTING(true, false), OPEN(true, false), CLOSED(false, true), FAILED(false, true); - + private final boolean open; private final boolean closed; - + private QueryReadyState(boolean open, boolean closed) { this.open = open; this.closed = closed; } - - public boolean isOpen() { - return open; - } - + public boolean isClosed() { return closed; } + public boolean isOpen() { + return open; + } + } - void update(); + public static final long defaultTimeout = 10000l; - void send(String str); - - default void send(JSONObject json) { - send(json.toString()); + default QueryResponse awaitResponse() { + return awaitResponseAvailable() ? getResponse() : null; } - void send(byte[] bytes); - - int responsesAvailable(); - - QueryResponse getResponse(); - - int binaryResponsesAvailable(); - - byte[] getBinaryResponse(); - - QueryReadyState readyState(); - - default boolean isOpen() { - return readyState().isOpen(); + default QueryResponse awaitResponse(long timeout) { + return awaitResponseAvailable(timeout) ? getResponse() : null; } - default boolean isClosed() { - return readyState().isClosed(); + default boolean awaitResponseAvailable() { + return awaitResponseAvailable(defaultTimeout); } - void close(); - - EnumServerRateLimit getRateLimit(); - default boolean awaitResponseAvailable(long timeout) { long start = EagRuntime.steadyTimeMillis(); - while(isOpen() && responsesAvailable() <= 0 && (timeout <= 0l || EagRuntime.steadyTimeMillis() - start < timeout)) { + while (isOpen() && responsesAvailable() <= 0 + && (timeout <= 0l || EagRuntime.steadyTimeMillis() - start < timeout)) { try { Thread.sleep(0l, 250000); } catch (InterruptedException e) { @@ -86,14 +68,23 @@ public interface IServerQuery { } return responsesAvailable() > 0; } - - default boolean awaitResponseAvailable() { - return awaitResponseAvailable(defaultTimeout); + + default byte[] awaitResponseBinary() { + return awaitResponseBinaryAvailable() ? getBinaryResponse() : null; } - + + default byte[] awaitResponseBinary(long timeout) { + return awaitResponseBinaryAvailable(timeout) ? getBinaryResponse() : null; + } + + default boolean awaitResponseBinaryAvailable() { + return awaitResponseBinaryAvailable(defaultTimeout); + } + default boolean awaitResponseBinaryAvailable(long timeout) { long start = EagRuntime.steadyTimeMillis(); - while(isOpen() && binaryResponsesAvailable() <= 0 && (timeout <= 0l || EagRuntime.steadyTimeMillis() - start < timeout)) { + while (isOpen() && binaryResponsesAvailable() <= 0 + && (timeout <= 0l || EagRuntime.steadyTimeMillis() - start < timeout)) { try { Thread.sleep(0l, 250000); } catch (InterruptedException e) { @@ -102,24 +93,36 @@ public interface IServerQuery { return binaryResponsesAvailable() > 0; } - default boolean awaitResponseBinaryAvailable() { - return awaitResponseBinaryAvailable(defaultTimeout); + int binaryResponsesAvailable(); + + void close(); + + byte[] getBinaryResponse(); + + EnumServerRateLimit getRateLimit(); + + QueryResponse getResponse(); + + default boolean isClosed() { + return readyState().isClosed(); } - default QueryResponse awaitResponse(long timeout) { - return awaitResponseAvailable(timeout) ? getResponse() : null; - } - - default QueryResponse awaitResponse() { - return awaitResponseAvailable() ? getResponse() : null; - } - - default byte[] awaitResponseBinary(long timeout) { - return awaitResponseBinaryAvailable(timeout) ? getBinaryResponse() : null; + default boolean isOpen() { + return readyState().isOpen(); } - default byte[] awaitResponseBinary() { - return awaitResponseBinaryAvailable() ? getBinaryResponse() : null; + QueryReadyState readyState(); + + int responsesAvailable(); + + void send(byte[] bytes); + + default void send(JSONObject json) { + send(json.toString()); } + void send(String str); + + void update(); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IShaderGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IShaderGL.java index e685a306..fa638c59 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IShaderGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IShaderGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ITextureGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ITextureGL.java index c073a19e..d1eeb2f9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ITextureGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ITextureGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IUniformGL.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IUniformGL.java index b152dc7f..782faa4b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IUniformGL.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IUniformGL.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketClient.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketClient.java index 85aad5aa..b46f3a00 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketClient.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketClient.java @@ -5,58 +5,59 @@ import java.util.List; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IWebSocketClient { - EnumEaglerConnectionState getState(); - - boolean connectBlocking(int timeoutMS); - - boolean isOpen(); - - boolean isClosed(); - - void close(); + int availableBinaryFrames(); int availableFrames(); - IWebSocketFrame getNextFrame(); + int availableStringFrames(); - List getNextFrames(); + void clearBinaryFrames(); void clearFrames(); - int availableStringFrames(); - - IWebSocketFrame getNextStringFrame(); - - List getNextStringFrames(); - void clearStringFrames(); - int availableBinaryFrames(); + void close(); + + boolean connectBlocking(int timeoutMS); + + String getCurrentURI(); IWebSocketFrame getNextBinaryFrame(); List getNextBinaryFrames(); - void clearBinaryFrames(); + IWebSocketFrame getNextFrame(); - void send(String str); + List getNextFrames(); + + IWebSocketFrame getNextStringFrame(); + + List getNextStringFrames(); + + EnumEaglerConnectionState getState(); + + boolean isClosed(); + + boolean isOpen(); void send(byte[] bytes); - String getCurrentURI(); + void send(String str); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketFrame.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketFrame.java index 7ecec0f1..9aa73e34 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketFrame.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/IWebSocketFrame.java @@ -5,30 +5,31 @@ import java.io.InputStream; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IWebSocketFrame { - boolean isString(); - - String getString(); - byte[] getByteArray(); InputStream getInputStream(); int getLength(); + String getString(); + long getTimestamp(); + boolean isString(); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/KeyboardConstants.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/KeyboardConstants.java index 279c6d13..9b66d6b9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/KeyboardConstants.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/KeyboardConstants.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,7 +24,7 @@ public class KeyboardConstants { private static final int[] keyboardBrowserToEagler = new int[384 * 4]; private static final int[] keyboardEaglerToBrowser = new int[256]; private static final char[] keyboardChars = new char[256]; - + public static final int KEY_NONE = 0x00; public static final int KEY_ESCAPE = 0x01; public static final int KEY_1 = 0x02; @@ -155,7 +156,7 @@ public class KeyboardConstants { public static final int KEY_APPS = 0xDD; /* AppMenu key */ public static final int KEY_POWER = 0xDE; public static final int KEY_SLEEP = 0xDF; - + private static final int GLFW_KEY_SPACE = 32, GLFW_KEY_APOSTROPHE = 39, GLFW_KEY_COMMA = 44, GLFW_KEY_MINUS = 45, GLFW_KEY_PERIOD = 46, GLFW_KEY_SLASH = 47, GLFW_KEY_0 = 48, GLFW_KEY_1 = 49, GLFW_KEY_2 = 50, GLFW_KEY_3 = 51, GLFW_KEY_4 = 52, GLFW_KEY_5 = 53, GLFW_KEY_6 = 54, GLFW_KEY_7 = 55, GLFW_KEY_8 = 56, @@ -166,7 +167,7 @@ public class KeyboardConstants { GLFW_KEY_U = 85, GLFW_KEY_V = 86, GLFW_KEY_W = 87, GLFW_KEY_X = 88, GLFW_KEY_Y = 89, GLFW_KEY_Z = 90, GLFW_KEY_LEFT_BRACKET = 91, GLFW_KEY_BACKSLASH = 92, GLFW_KEY_RIGHT_BRACKET = 93, GLFW_KEY_GRAVE_ACCENT = 96, GLFW_KEY_WORLD_1 = 161, GLFW_KEY_WORLD_2 = 162; - + private static final int GLFW_KEY_ESCAPE = 256, GLFW_KEY_ENTER = 257, GLFW_KEY_TAB = 258, GLFW_KEY_BACKSPACE = 259, GLFW_KEY_INSERT = 260, GLFW_KEY_DELETE = 261, GLFW_KEY_RIGHT = 262, GLFW_KEY_LEFT = 263, GLFW_KEY_DOWN = 264, GLFW_KEY_UP = 265, GLFW_KEY_PAGE_UP = 266, GLFW_KEY_PAGE_DOWN = 267, @@ -184,44 +185,10 @@ public class KeyboardConstants { GLFW_KEY_LEFT_CONTROL = 341, GLFW_KEY_LEFT_ALT = 342, GLFW_KEY_LEFT_SUPER = 343, GLFW_KEY_RIGHT_SHIFT = 344, GLFW_KEY_RIGHT_CONTROL = 345, GLFW_KEY_RIGHT_ALT = 346, GLFW_KEY_RIGHT_SUPER = 347, GLFW_KEY_MENU = 348, GLFW_KEY_LAST = GLFW_KEY_MENU; - + private static final int DOM_KEY_LOCATION_STANDARD = 0, DOM_KEY_LOCATION_LEFT = 1, DOM_KEY_LOCATION_RIGHT = 2, DOM_KEY_LOCATION_NUMPAD = 3; - private static void register(int eaglerId, int glfwId, int browserId, int browserLocation, String name, char character) { - if(keyboardEaglerToGLFW[eaglerId] != 0) throw new IllegalArgumentException("Duplicate keyboardEaglerToGLFW entry: " + eaglerId + " -> " + glfwId); - keyboardEaglerToGLFW[eaglerId] = glfwId; - if(keyboardGLFWToEagler[glfwId] != 0) throw new IllegalArgumentException("Duplicate keyboardGLFWToEagler entry: " + glfwId + " -> " + eaglerId); - keyboardGLFWToEagler[glfwId] = eaglerId; - if(browserLocation == 0) { - if(keyboardEaglerToBrowser[eaglerId] != 0) throw new IllegalArgumentException("Duplicate keyboardEaglerToBrowser entry: " + eaglerId + " -> " + browserId + "(0)"); - keyboardEaglerToBrowser[eaglerId] = browserId; - if(keyboardBrowserToEagler[browserId] != 0) throw new IllegalArgumentException("Duplicate keyboardBrowserToEagler entry: " + browserId + "(0) -> " + eaglerId); - keyboardBrowserToEagler[browserId] = eaglerId; - }else { - browserLocation *= 384; - if(keyboardEaglerToBrowser[eaglerId] != 0) throw new IllegalArgumentException("Duplicate keyboardEaglerToBrowser entry: " + eaglerId + " -> " + browserId + "(" + browserLocation + ")"); - keyboardEaglerToBrowser[eaglerId] = browserId + browserLocation; - if(keyboardBrowserToEagler[browserId + browserLocation] != 0) throw new IllegalArgumentException("Duplicate keyboardBrowserToEagler entry: " + browserId + "(" + browserLocation + ") -> " + eaglerId); - keyboardBrowserToEagler[browserId + browserLocation] = eaglerId; - } - if(keyboardNames[eaglerId] != null) throw new IllegalArgumentException("Duplicate keyboardNames entry: " + eaglerId + " -> " + name); - keyboardNames[eaglerId] = name; - if(keyboardChars[eaglerId] != '\0') throw new IllegalArgumentException("Duplicate keyboardChars entry: " + eaglerId + " -> " + character); - keyboardChars[eaglerId] = character; - } - - private static void registerAlt(int eaglerId, int browserId, int browserLocation) { - if(browserLocation == 0) { - if(keyboardBrowserToEagler[browserId] != 0) throw new IllegalArgumentException("Duplicate (alt) keyboardBrowserToEagler entry: " + browserId + " -> " + eaglerId); - keyboardBrowserToEagler[browserId] = eaglerId; - }else { - browserLocation *= 384; - if(keyboardBrowserToEagler[browserId + browserLocation] != 0) throw new IllegalArgumentException("Duplicate (alt) keyboardBrowserToEagler entry: " + browserId + "(" + browserLocation + ") -> " + eaglerId); - keyboardBrowserToEagler[browserId + browserLocation] = eaglerId; - } - } - static { register(KEY_SPACE, GLFW_KEY_SPACE, 32, DOM_KEY_LOCATION_STANDARD, "Space", ' '); register(KEY_APOSTROPHE, GLFW_KEY_APOSTROPHE, 222, DOM_KEY_LOCATION_STANDARD, "Quote", '\''); @@ -329,11 +296,39 @@ public class KeyboardConstants { register(KEY_RMENU, GLFW_KEY_RIGHT_ALT, 18, DOM_KEY_LOCATION_RIGHT, "R. Alt", '\0'); } - public static String getKeyName(int key) { - if (key < 0 || key >= 256 || keyboardNames[key] == null) { - return "Unknown"; + public static int getBrowserKeyFromEagler(int key) { + if (key < 0 || key >= 256) { + return 0; } else { - return keyboardNames[key]; + return keyboardEaglerToBrowser[key] % 384; + } + } + + public static int getBrowserLocationFromEagler(int key) { + if (key < 0 || key >= 384) { + return 0; + } else { + return keyboardEaglerToBrowser[key] / 384; + } + } + + public static int getEaglerKeyFromBrowser(int key) { + return getEaglerKeyFromBrowser(key, 0); + } + + public static int getEaglerKeyFromBrowser(int key, int location) { + if (key < 0 || key >= 384) { + return 0; + } else { + if (location <= 0 || location >= 4) { + return keyboardBrowserToEagler[key]; + } else { + int i = keyboardBrowserToEagler[key + location * 384]; + if (i == 0) { + i = keyboardBrowserToEagler[key]; + } + return i; + } } } @@ -352,43 +347,7 @@ public class KeyboardConstants { return keyboardEaglerToGLFW[key]; } } - - public static int getEaglerKeyFromBrowser(int key) { - return getEaglerKeyFromBrowser(key, 0); - } - - public static int getEaglerKeyFromBrowser(int key, int location) { - if (key < 0 || key >= 384) { - return 0; - } else { - if(location <= 0 || location >= 4) { - return keyboardBrowserToEagler[key]; - }else { - int i = keyboardBrowserToEagler[key + location * 384]; - if(i == 0) { - i = keyboardBrowserToEagler[key]; - } - return i; - } - } - } - public static int getBrowserKeyFromEagler(int key) { - if (key < 0 || key >= 256) { - return 0; - } else { - return keyboardEaglerToBrowser[key] % 384; - } - } - - public static int getBrowserLocationFromEagler(int key) { - if (key < 0 || key >= 384) { - return 0; - } else { - return keyboardEaglerToBrowser[key] / 384; - } - } - public static char getKeyCharFromEagler(int key) { if (key < 0 || key >= 256) { return '\0'; @@ -396,5 +355,64 @@ public class KeyboardConstants { return keyboardChars[key]; } } - + + public static String getKeyName(int key) { + if (key < 0 || key >= 256 || keyboardNames[key] == null) { + return "Unknown"; + } else { + return keyboardNames[key]; + } + } + + private static void register(int eaglerId, int glfwId, int browserId, int browserLocation, String name, + char character) { + if (keyboardEaglerToGLFW[eaglerId] != 0) + throw new IllegalArgumentException("Duplicate keyboardEaglerToGLFW entry: " + eaglerId + " -> " + glfwId); + keyboardEaglerToGLFW[eaglerId] = glfwId; + if (keyboardGLFWToEagler[glfwId] != 0) + throw new IllegalArgumentException("Duplicate keyboardGLFWToEagler entry: " + glfwId + " -> " + eaglerId); + keyboardGLFWToEagler[glfwId] = eaglerId; + if (browserLocation == 0) { + if (keyboardEaglerToBrowser[eaglerId] != 0) + throw new IllegalArgumentException( + "Duplicate keyboardEaglerToBrowser entry: " + eaglerId + " -> " + browserId + "(0)"); + keyboardEaglerToBrowser[eaglerId] = browserId; + if (keyboardBrowserToEagler[browserId] != 0) + throw new IllegalArgumentException( + "Duplicate keyboardBrowserToEagler entry: " + browserId + "(0) -> " + eaglerId); + keyboardBrowserToEagler[browserId] = eaglerId; + } else { + browserLocation *= 384; + if (keyboardEaglerToBrowser[eaglerId] != 0) + throw new IllegalArgumentException("Duplicate keyboardEaglerToBrowser entry: " + eaglerId + " -> " + + browserId + "(" + browserLocation + ")"); + keyboardEaglerToBrowser[eaglerId] = browserId + browserLocation; + if (keyboardBrowserToEagler[browserId + browserLocation] != 0) + throw new IllegalArgumentException("Duplicate keyboardBrowserToEagler entry: " + browserId + "(" + + browserLocation + ") -> " + eaglerId); + keyboardBrowserToEagler[browserId + browserLocation] = eaglerId; + } + if (keyboardNames[eaglerId] != null) + throw new IllegalArgumentException("Duplicate keyboardNames entry: " + eaglerId + " -> " + name); + keyboardNames[eaglerId] = name; + if (keyboardChars[eaglerId] != '\0') + throw new IllegalArgumentException("Duplicate keyboardChars entry: " + eaglerId + " -> " + character); + keyboardChars[eaglerId] = character; + } + + private static void registerAlt(int eaglerId, int browserId, int browserLocation) { + if (browserLocation == 0) { + if (keyboardBrowserToEagler[browserId] != 0) + throw new IllegalArgumentException( + "Duplicate (alt) keyboardBrowserToEagler entry: " + browserId + " -> " + eaglerId); + keyboardBrowserToEagler[browserId] = eaglerId; + } else { + browserLocation *= 384; + if (keyboardBrowserToEagler[browserId + browserLocation] != 0) + throw new IllegalArgumentException("Duplicate (alt) keyboardBrowserToEagler entry: " + browserId + "(" + + browserLocation + ") -> " + eaglerId); + keyboardBrowserToEagler[browserId + browserLocation] = eaglerId; + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformIncompatibleException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformIncompatibleException.java new file mode 100644 index 00000000..dd2f518b --- /dev/null +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformIncompatibleException.java @@ -0,0 +1,25 @@ +package net.lax1dude.eaglercraft.v1_8.internal; + +/** + * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class PlatformIncompatibleException extends RuntimeException { + + public PlatformIncompatibleException(String s) { + super(s); + } + +} diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/QueryResponse.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/QueryResponse.java index f069acbe..1ea6be13 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/QueryResponse.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/QueryResponse.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,7 +31,7 @@ public class QueryResponse { public final long clientTime; public final boolean serverCracked; public final long ping; - + public QueryResponse(JSONObject obj, long ping) { this.responseType = obj.getString("type").toLowerCase(); this.ping = ping; @@ -42,21 +43,21 @@ public class QueryResponse { this.clientTime = EagRuntime.steadyTimeMillis(); this.serverCracked = obj.optBoolean("cracked", false); } - - public boolean isResponseString() { - return responseData instanceof String; + + public JSONObject getResponseJSON() { + return (JSONObject) responseData; } - + + public String getResponseString() { + return (String) responseData; + } + public boolean isResponseJSON() { return responseData instanceof JSONObject; } - - public String getResponseString() { - return (String)responseData; - } - - public JSONObject getResponseJSON() { - return (JSONObject)responseData; + + public boolean isResponseString() { + return responseData instanceof String; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RamdiskFilesystemImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RamdiskFilesystemImpl.java index 9302a899..08059485 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RamdiskFilesystemImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RamdiskFilesystemImpl.java @@ -8,14 +8,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,12 +24,96 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; public class RamdiskFilesystemImpl implements IEaglerFilesystem { protected final String filesystemName; - protected final Map filesystemMap = new TreeMap<>(); + protected final Map filesystemMap = new TreeMap<>(); public RamdiskFilesystemImpl(String filesystemName) { this.filesystemName = filesystemName; } + @Override + public void closeHandle() { + filesystemMap.clear(); + } + + @Override + public int eaglerCopy(String pathNameOld, String pathNameNew) { + byte[] dat = filesystemMap.get(pathNameOld); + if (dat != null) { + filesystemMap.put(pathNameNew, dat); + return dat.length; + } + return -1; + } + + @Override + public boolean eaglerDelete(String pathName) { + return filesystemMap.remove(pathName) != null; + } + + @Override + public boolean eaglerExists(String pathName) { + return filesystemMap.containsKey(pathName); + } + + @Override + public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { + if (!recursive) { + eaglerIterate(pathName, new VFSFilenameIteratorNonRecursive(itr, + VFSFilenameIteratorNonRecursive.countSlashes(pathName) + 1), true); + } else { + boolean b = pathName.length() == 0; + for (String key : filesystemMap.keySet()) { + if (b || key.startsWith(pathName)) { + itr.next(key); + } + } + } + } + + @Override + public boolean eaglerMove(String pathNameOld, String pathNameNew) { + byte[] dat = filesystemMap.remove(pathNameOld); + if (dat != null) { + filesystemMap.put(pathNameNew, dat); + return true; + } + return false; + } + + @Override + public ByteBuffer eaglerRead(String pathName) { + byte[] data = filesystemMap.get(pathName); + if (data != null) { + ByteBuffer buf = PlatformRuntime.castPrimitiveByteArray(data); + if (buf == null) { + buf = PlatformRuntime.allocateByteBuffer(data.length); + buf.put(data); + buf.flip(); + } + return buf; + } else { + return null; + } + } + + @Override + public int eaglerSize(String pathName) { + byte[] dat = filesystemMap.get(pathName); + return dat != null ? dat.length : -1; + } + + @Override + public void eaglerWrite(String pathName, ByteBuffer data) { + byte[] arr = PlatformRuntime.castNativeByteBuffer(data); + if (arr == null) { + arr = new byte[data.remaining()]; + int i = data.position(); + data.get(arr); + data.position(i); + } + filesystemMap.put(pathName, arr); + } + @Override public String getFilesystemName() { return filesystemName; @@ -44,88 +129,4 @@ public class RamdiskFilesystemImpl implements IEaglerFilesystem { return true; } - @Override - public boolean eaglerDelete(String pathName) { - return filesystemMap.remove(pathName) != null; - } - - @Override - public ByteBuffer eaglerRead(String pathName) { - byte[] data = filesystemMap.get(pathName); - if(data != null) { - ByteBuffer buf = PlatformRuntime.castPrimitiveByteArray(data); - if(buf == null) { - buf = PlatformRuntime.allocateByteBuffer(data.length); - buf.put(data); - buf.flip(); - } - return buf; - }else { - return null; - } - } - - @Override - public void eaglerWrite(String pathName, ByteBuffer data) { - byte[] arr = PlatformRuntime.castNativeByteBuffer(data); - if(arr == null) { - arr = new byte[data.remaining()]; - int i = data.position(); - data.get(arr); - data.position(i); - } - filesystemMap.put(pathName, arr); - } - - @Override - public boolean eaglerExists(String pathName) { - return filesystemMap.containsKey(pathName); - } - - @Override - public boolean eaglerMove(String pathNameOld, String pathNameNew) { - byte[] dat = filesystemMap.remove(pathNameOld); - if(dat != null) { - filesystemMap.put(pathNameNew, dat); - return true; - } - return false; - } - - @Override - public int eaglerCopy(String pathNameOld, String pathNameNew) { - byte[] dat = filesystemMap.get(pathNameOld); - if(dat != null) { - filesystemMap.put(pathNameNew, dat); - return dat.length; - } - return -1; - } - - @Override - public int eaglerSize(String pathName) { - byte[] dat = filesystemMap.get(pathName); - return dat != null ? dat.length : -1; - } - - @Override - public void eaglerIterate(String pathName, VFSFilenameIterator itr, boolean recursive) { - if(!recursive) { - eaglerIterate(pathName, new VFSFilenameIteratorNonRecursive(itr, - VFSFilenameIteratorNonRecursive.countSlashes(pathName) + 1), true); - }else { - boolean b = pathName.length() == 0; - for(String key : filesystemMap.keySet()) { - if(b || key.startsWith(pathName)) { - itr.next(key); - } - } - } - } - - @Override - public void closeHandle() { - filesystemMap.clear(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RuntimeInitializationFailureException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RuntimeInitializationFailureException.java new file mode 100644 index 00000000..9615fe91 --- /dev/null +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/RuntimeInitializationFailureException.java @@ -0,0 +1,29 @@ +package net.lax1dude.eaglercraft.v1_8.internal; + +/** + * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class RuntimeInitializationFailureException extends RuntimeException { + + public RuntimeInitializationFailureException(String s) { + super(s); + } + + public RuntimeInitializationFailureException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ScreenRecordParameters.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ScreenRecordParameters.java index 0c4d25ba..9fe22845 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ScreenRecordParameters.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/ScreenRecordParameters.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.recording.EnumScreenRecordingCodec; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIterator.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIterator.java index e90d99cc..35f5a95f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIterator.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIterator.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFSIterator2.BreakLoop; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIteratorNonRecursive.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIteratorNonRecursive.java index d10a3afb..702901ad 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIteratorNonRecursive.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/VFSFilenameIteratorNonRecursive.java @@ -3,21 +3,35 @@ package net.lax1dude.eaglercraft.v1_8.internal; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class VFSFilenameIteratorNonRecursive implements VFSFilenameIterator { + public static int countSlashes(String str) { + if (str.length() == 0) + return -1; + int j = 0; + for (int i = 0, l = str.length(); i < l; ++i) { + if (str.charAt(i) == '/') { + ++j; + } + } + return j; + } + private final VFSFilenameIterator child; + private final int pathCount; public VFSFilenameIteratorNonRecursive(VFSFilenameIterator child, int pathCount) { @@ -28,20 +42,9 @@ public class VFSFilenameIteratorNonRecursive implements VFSFilenameIterator { @Override public void next(String entry) { int i = countSlashes(entry); - if(i == pathCount) { + if (i == pathCount) { child.next(entry); } } - public static int countSlashes(String str) { - if(str.length() == 0) return -1; - int j = 0; - for(int i = 0, l = str.length(); i < l; ++i) { - if(str.charAt(i) == '/') { - ++j; - } - } - return j; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/WebViewOptions.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/WebViewOptions.java index 6015c73f..8c60a62d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/WebViewOptions.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/WebViewOptions.java @@ -8,32 +8,57 @@ import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WebViewOptions { + public static EaglercraftUUID getEmbedOriginUUID(byte[] sha256) { + byte[] vigg = "BlobOrigin:".getBytes(StandardCharsets.UTF_8); + byte[] eagler = new byte[sha256.length + vigg.length]; + System.arraycopy(vigg, 0, eagler, 0, vigg.length); + System.arraycopy(sha256, 0, eagler, vigg.length, sha256.length); + return EaglercraftUUID.nameUUIDFromBytes(eagler); + } + + public static EaglercraftUUID getURLOriginUUID(URI url) { + return EaglercraftUUID.nameUUIDFromBytes(("URLOrigin:" + url.toString()).getBytes(StandardCharsets.UTF_8)); + } + public EnumWebViewContentMode contentMode = EnumWebViewContentMode.BLOB_BASED; public String fallbackTitle = "WebView"; public boolean scriptEnabled = false; public boolean strictCSPEnable = true; public boolean serverMessageAPIEnabled = false; public URI url = null; + public byte[] blob = null; + public EaglercraftUUID permissionsOriginUUID = null; public WebViewOptions() { } + public WebViewOptions(boolean script, boolean serverMessageAPIEnabled, boolean strictCSPEnable, byte[] data, + EaglercraftUUID permissionsOriginUUID) { + this.contentMode = EnumWebViewContentMode.BLOB_BASED; + this.scriptEnabled = script; + this.strictCSPEnable = strictCSPEnable; + this.serverMessageAPIEnabled = serverMessageAPIEnabled; + this.blob = data; + this.permissionsOriginUUID = permissionsOriginUUID; + } + public WebViewOptions(boolean script, boolean serverMessageAPIEnabled, boolean strictCSPEnable, URI url) { this.contentMode = EnumWebViewContentMode.URL_BASED; this.scriptEnabled = script; @@ -43,25 +68,4 @@ public class WebViewOptions { this.permissionsOriginUUID = getURLOriginUUID(url); } - public WebViewOptions(boolean script, boolean serverMessageAPIEnabled, boolean strictCSPEnable, byte[] data, EaglercraftUUID permissionsOriginUUID) { - this.contentMode = EnumWebViewContentMode.BLOB_BASED; - this.scriptEnabled = script; - this.strictCSPEnable = strictCSPEnable; - this.serverMessageAPIEnabled = serverMessageAPIEnabled; - this.blob = data; - this.permissionsOriginUUID = permissionsOriginUUID; - } - - public static EaglercraftUUID getURLOriginUUID(URI url) { - return EaglercraftUUID.nameUUIDFromBytes(("URLOrigin:" + url.toString()).getBytes(StandardCharsets.UTF_8)); - } - - public static EaglercraftUUID getEmbedOriginUUID(byte[] sha256) { - byte[] vigg = "BlobOrigin:".getBytes(StandardCharsets.UTF_8); - byte[] eagler = new byte[sha256.length + vigg.length]; - System.arraycopy(vigg, 0, eagler, 0, vigg.length); - System.arraycopy(sha256, 0, eagler, vigg.length, sha256.length); - return EaglercraftUUID.nameUUIDFromBytes(eagler); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/Buffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/Buffer.java index ee27b232..f4ab0284 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/Buffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/Buffer.java @@ -3,25 +3,38 @@ package net.lax1dude.eaglercraft.v1_8.internal.buffer; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface Buffer { + static IndexOutOfBoundsException makeIOOBE(int idx) { + return new IndexOutOfBoundsException("Index out of range: " + idx); + } + + Object array(); + int capacity(); - int position(); + Buffer clear(); - Buffer position(int newPosition); + Buffer flip(); + + boolean hasArray(); + + boolean hasRemaining(); + + boolean isDirect(); int limit(); @@ -29,26 +42,14 @@ public interface Buffer { Buffer mark(); - Buffer reset(); + int position(); - Buffer clear(); - - Buffer flip(); - - Buffer rewind(); + Buffer position(int newPosition); int remaining(); - boolean hasRemaining(); + Buffer reset(); - boolean hasArray(); - - Object array(); - - boolean isDirect(); - - static IndexOutOfBoundsException makeIOOBE(int idx) { - return new IndexOutOfBoundsException("Index out of range: " + idx); - } + Buffer rewind(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ByteBuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ByteBuffer.java index 4ec39b18..19667c3e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ByteBuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ByteBuffer.java @@ -1,103 +1,103 @@ package net.lax1dude.eaglercraft.v1_8.internal.buffer; - /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ByteBuffer extends Buffer { - ByteBuffer duplicate(); - - byte get(); - - ByteBuffer put(byte b); - - byte get(int index); - - ByteBuffer put(int index, byte b); - - ByteBuffer get(byte[] dst, int offset, int length); - - ByteBuffer get(byte[] dst); - - ByteBuffer put(ByteBuffer src); - - ByteBuffer put(byte[] src, int offset, int length); - - ByteBuffer put(byte[] src); - - char getChar(); - - ByteBuffer putChar(char value); - - char getChar(int index); - - ByteBuffer putChar(int index, char value); - - short getShort(); - - ByteBuffer putShort(short value); - - short getShort(int index); - - ByteBuffer putShort(int index, short value); - - ShortBuffer asShortBuffer(); - - int getInt(); - - ByteBuffer putInt(int value); - - int getInt(int index); - - ByteBuffer putInt(int index, int value); - - IntBuffer asIntBuffer(); - - long getLong(); - - ByteBuffer putLong(long value); - - long getLong(int index); - - ByteBuffer putLong(int index, long value); - - float getFloat(); - - ByteBuffer putFloat(float value); - - float getFloat(int index); - - ByteBuffer putFloat(int index, float value); + byte[] array(); FloatBuffer asFloatBuffer(); - ByteBuffer mark(); + IntBuffer asIntBuffer(); - ByteBuffer reset(); + ShortBuffer asShortBuffer(); ByteBuffer clear(); + ByteBuffer duplicate(); + ByteBuffer flip(); - ByteBuffer rewind(); + byte get(); + + ByteBuffer get(byte[] dst); + + ByteBuffer get(byte[] dst, int offset, int length); + + byte get(int index); + + char getChar(); + + char getChar(int index); + + float getFloat(); + + float getFloat(int index); + + int getInt(); + + int getInt(int index); + + long getLong(); + + long getLong(int index); + + short getShort(); + + short getShort(int index); ByteBuffer limit(int newLimit); + ByteBuffer mark(); + ByteBuffer position(int newPosition); - byte[] array(); + ByteBuffer put(byte b); + + ByteBuffer put(byte[] src); + + ByteBuffer put(byte[] src, int offset, int length); + + ByteBuffer put(ByteBuffer src); + + ByteBuffer put(int index, byte b); + + ByteBuffer putChar(char value); + + ByteBuffer putChar(int index, char value); + + ByteBuffer putFloat(float value); + + ByteBuffer putFloat(int index, float value); + + ByteBuffer putInt(int value); + + ByteBuffer putInt(int index, int value); + + ByteBuffer putLong(int index, long value); + + ByteBuffer putLong(long value); + + ByteBuffer putShort(int index, short value); + + ByteBuffer putShort(short value); + + ByteBuffer reset(); + + ByteBuffer rewind(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerBufferInputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerBufferInputStream.java index d6fd8ee9..41b0b977 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerBufferInputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerBufferInputStream.java @@ -6,32 +6,38 @@ import java.io.InputStream; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerBufferInputStream extends InputStream { - + private final ByteBuffer buffer; - + public EaglerBufferInputStream(ByteBuffer buffer) { this.buffer = buffer; } + @Override + public int available() throws IOException { + return buffer.remaining(); + } + @Override public int read() throws IOException { - if(buffer.remaining() <= 0) { + if (buffer.remaining() <= 0) { return -1; } - return (int)buffer.get() & 0xFF; + return (int) buffer.get() & 0xFF; } @Override @@ -39,10 +45,10 @@ public class EaglerBufferInputStream extends InputStream { int p = buffer.position(); int l = buffer.limit(); int r = l - p; - if(r < len) { + if (r < len) { len = r; } - if(len > 0) { + if (len > 0) { buffer.get(b, off, len); } return len; @@ -53,18 +59,13 @@ public class EaglerBufferInputStream extends InputStream { int p = buffer.position(); int l = buffer.limit(); int r = l - p; - if(r < n) { + if (r < n) { n = r; } - if(n > 0) { - buffer.position(p + (int)n); + if (n > 0) { + buffer.position(p + (int) n); } return n; } - @Override - public int available() throws IOException { - return buffer.remaining(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/FloatBuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/FloatBuffer.java index ecaf25ff..3574fee5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/FloatBuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/FloatBuffer.java @@ -3,61 +3,61 @@ package net.lax1dude.eaglercraft.v1_8.internal.buffer; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface FloatBuffer extends Buffer { - FloatBuffer duplicate(); - - float get(); - - FloatBuffer put(float b); - - float get(int index); - - FloatBuffer put(int index, float b); - - float getElement(int index); - - void putElement(int index, float value); - - FloatBuffer get(float[] dst, int offset, int length); - - FloatBuffer get(float[] dst); - - FloatBuffer put(FloatBuffer src); - - FloatBuffer put(float[] src, int offset, int length); - - FloatBuffer put(float[] src); - - boolean isDirect(); - - FloatBuffer mark(); - - FloatBuffer reset(); + float[] array(); FloatBuffer clear(); + FloatBuffer duplicate(); + FloatBuffer flip(); - FloatBuffer rewind(); + float get(); + + FloatBuffer get(float[] dst); + + FloatBuffer get(float[] dst, int offset, int length); + + float get(int index); + + float getElement(int index); + + boolean isDirect(); FloatBuffer limit(int newLimit); + FloatBuffer mark(); + FloatBuffer position(int newPosition); - float[] array(); + FloatBuffer put(float b); + + FloatBuffer put(float[] src); + + FloatBuffer put(float[] src, int offset, int length); + + FloatBuffer put(FloatBuffer src); + + FloatBuffer put(int index, float b); + + void putElement(int index, float value); + + FloatBuffer reset(); + + FloatBuffer rewind(); } - diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/IntBuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/IntBuffer.java index 0d96de55..304ada1d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/IntBuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/IntBuffer.java @@ -3,61 +3,61 @@ package net.lax1dude.eaglercraft.v1_8.internal.buffer; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IntBuffer extends Buffer { - IntBuffer duplicate(); - - int get(); - - IntBuffer put(int b); - - int get(int index); - - IntBuffer put(int index, int b); - - int getElement(int index); - - void putElement(int index, int value); - - IntBuffer get(int[] dst, int offset, int length); - - IntBuffer get(int[] dst); - - IntBuffer put(IntBuffer src); - - IntBuffer put(int[] src, int offset, int length); - - IntBuffer put(int[] src); - - boolean isDirect(); - - IntBuffer mark(); - - IntBuffer reset(); + int[] array(); IntBuffer clear(); + IntBuffer duplicate(); + IntBuffer flip(); - IntBuffer rewind(); + int get(); + + int get(int index); + + IntBuffer get(int[] dst); + + IntBuffer get(int[] dst, int offset, int length); + + int getElement(int index); + + boolean isDirect(); IntBuffer limit(int newLimit); + IntBuffer mark(); + IntBuffer position(int newPosition); - int[] array(); + IntBuffer put(int b); + + IntBuffer put(int index, int b); + + IntBuffer put(int[] src); + + IntBuffer put(int[] src, int offset, int length); + + IntBuffer put(IntBuffer src); + + void putElement(int index, int value); + + IntBuffer reset(); + + IntBuffer rewind(); } - diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ShortBuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ShortBuffer.java index 56e54a54..e4100d8c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ShortBuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/ShortBuffer.java @@ -3,60 +3,61 @@ package net.lax1dude.eaglercraft.v1_8.internal.buffer; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ShortBuffer extends Buffer { - ShortBuffer duplicate(); - - short get(); - - ShortBuffer put(short b); - - short get(int index); - - ShortBuffer put(int index, short b); - - short getElement(int index); - - void putElement(int index, short value); - - ShortBuffer get(short[] dst, int offset, int length); - - ShortBuffer get(short[] dst); - - ShortBuffer put(ShortBuffer src); - - ShortBuffer put(short[] src, int offset, int length); - - ShortBuffer put(short[] src); - - boolean isDirect(); - - ShortBuffer mark(); - - ShortBuffer reset(); + short[] array(); ShortBuffer clear(); + ShortBuffer duplicate(); + ShortBuffer flip(); - ShortBuffer rewind(); + short get(); + + short get(int index); + + ShortBuffer get(short[] dst); + + ShortBuffer get(short[] dst, int offset, int length); + + short getElement(int index); + + boolean isDirect(); ShortBuffer limit(int newLimit); + ShortBuffer mark(); + ShortBuffer position(int newPosition); - short[] array(); + ShortBuffer put(int index, short b); + + ShortBuffer put(short b); + + ShortBuffer put(short[] src); + + ShortBuffer put(short[] src, int offset, int length); + + ShortBuffer put(ShortBuffer src); + + void putElement(int index, short value); + + ShortBuffer reset(); + + ShortBuffer rewind(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/EaglerFileSystemException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/EaglerFileSystemException.java index 30419d9b..ee4b7d24 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/EaglerFileSystemException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/EaglerFileSystemException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal.vfs2; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,14 +21,14 @@ public class EaglerFileSystemException extends RuntimeException { public EaglerFileSystemException() { } - public EaglerFileSystemException(String message, Throwable cause) { - super(message, cause); - } - public EaglerFileSystemException(String message) { super(message); } + public EaglerFileSystemException(String message, Throwable cause) { + super(message, cause); + } + public EaglerFileSystemException(Throwable cause) { super(cause); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSFilenameIteratorImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSFilenameIteratorImpl.java index 6bfec45d..2e5e2449 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSFilenameIteratorImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSFilenameIteratorImpl.java @@ -6,14 +6,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.VFSFilenameIterator; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSIterator2.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSIterator2.java index 4aa5f4f9..f8de9542 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSIterator2.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSIterator2.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.internal.vfs2; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -22,11 +23,11 @@ public interface VFSIterator2 { super("iterator loop break request"); } } - + public default void end() { throw new BreakLoop(); } - + public void next(VFile2 entry); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilenamesIteratorImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilenamesIteratorImpl.java index 7f7183d9..3d40cdcc 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilenamesIteratorImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilenamesIteratorImpl.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.VFSFilenameIterator; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilesIteratorImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilesIteratorImpl.java index 0e937743..c2307c73 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilesIteratorImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFSListFilesIteratorImpl.java @@ -8,14 +8,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.VFSFilenameIterator; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFile2.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFile2.java index f1114238..3e89fe0e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFile2.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFile2.java @@ -15,14 +15,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,252 +32,225 @@ public class VFile2 { public static final String pathSeperator = "/"; public static final String[] altPathSeperator = new String[] { "\\" }; - + static IEaglerFilesystem primaryFilesystem = null; - - public static void setPrimaryFilesystem(IEaglerFilesystem fs) { - primaryFilesystem = fs; + + public static int copyFile(VFile2 src, VFile2 dst) { + src.assertNotRelative(); + dst.assertNotRelative(); + IEaglerFilesystem sfs = src.getFS(); + if (sfs != dst.getFS()) { + throw new UnsupportedOperationException("Cannot copy file between filesystems!"); + } + return sfs.eaglerCopy(src.path, dst.path); } - - public static String normalizePath(String p) { - for(int i = 0; i < altPathSeperator.length; ++i) { - p = p.replace(altPathSeperator[i], pathSeperator); - } - if(p.startsWith(pathSeperator)) { - p = p.substring(1); - } - if(p.endsWith(pathSeperator)) { - p = p.substring(0, p.length() - pathSeperator.length()); - } - return p; + + public static VFile2 create(IEaglerFilesystem fs, Object... path) { + return new VFile2(createPath(path), fs); } - - public static String[] splitPath(String p) { - String[] pth = normalizePath(p).split(pathSeperator); - for(int i = 0; i < pth.length; ++i) { - pth[i] = pth[i].trim(); - } - return pth; + + public static VFile2 create(Supplier fs, Object... path) { + return new VFile2(createPath(path), fs); } - - protected String path; - protected IEaglerFilesystem myFilesystem; - protected Supplier myFilesystemProvider; - + public static String createPath(Object... p) { ArrayList r = new ArrayList<>(); - for(int i = 0; i < p.length; ++i) { - if(p[i] == null) { + for (int i = 0; i < p.length; ++i) { + if (p[i] == null) { continue; } String gg = p[i].toString(); - if(gg == null) { + if (gg == null) { continue; } String[] parts = splitPath(gg); - for(int j = 0; j < parts.length; ++j) { - if(parts[j] == null || parts[j].equals(".")) { + for (int j = 0; j < parts.length; ++j) { + if (parts[j] == null || parts[j].equals(".")) { continue; - }else if(parts[j].equals("..") && r.size() > 0) { + } else if (parts[j].equals("..") && r.size() > 0) { int k = r.size() - 1; - if(!r.get(k).equals("..")) { + if (!r.get(k).equals("..")) { r.remove(k); - }else { + } else { r.add(".."); } - }else { + } else { r.add(parts[j]); } } } - if(r.size() > 0) { + if (r.size() > 0) { StringBuilder s = new StringBuilder(); - for(int i = 0; i < r.size(); ++i) { - if(i > 0) { + for (int i = 0; i < r.size(); ++i) { + if (i > 0) { s.append(pathSeperator); } s.append(r.get(i)); } return s.toString(); - }else { + } else { return null; } } - - public static VFile2 create(IEaglerFilesystem fs, Object... path) { - return new VFile2(createPath(path), fs); - } - - public static VFile2 create(Supplier fs, Object... path) { - return new VFile2(createPath(path), fs); - } - - public VFile2(Object... path) { - this(createPath(path), primaryFilesystem); - } - - private VFile2(String path, IEaglerFilesystem fs) { - this.path = path; - this.myFilesystem = fs; - } - - private VFile2(String path, Supplier fs) { - this.path = path; - this.myFilesystemProvider = fs; - } - - protected IEaglerFilesystem getFS() { - if(myFilesystem == null) { - if(myFilesystemProvider != null) { - myFilesystem = myFilesystemProvider.get(); - }else { - myFilesystem = primaryFilesystem; - } - if(myFilesystem == null) { - throw new IllegalStateException("The filesystem has not been initialized yet!"); - } - } - return myFilesystem; - } - - public InputStream getInputStream() { - assertNotRelative(); - return new VFileInputStream(getFS().eaglerRead(path)); - } - - public OutputStream getOutputStream() { - assertNotRelative(); - return new VFileOutputStream(this); - } - - public String toString() { - return path; - } - - public boolean isRelative() { - return path == null || path.contains(".."); - } - - public void assertNotRelative() { - if(isRelative()) throw new EaglerFileSystemException("Relative paths are not allowed: " + path); - } - - public boolean canRead() { - return !isRelative() && getFS().eaglerExists(path); - } - - public String getPath() { - return path.equals("unnamed") ? null : path; - } - - public String getName() { - int i = path.lastIndexOf(pathSeperator); - return i == -1 ? path : path.substring(i + 1); - } - + public static String getNameFromPath(String path) { path = normalizePath(path); int i = path.lastIndexOf(pathSeperator); return i == -1 ? path : path.substring(i + 1); } - + + public static String normalizePath(String p) { + for (int i = 0; i < altPathSeperator.length; ++i) { + p = p.replace(altPathSeperator[i], pathSeperator); + } + if (p.startsWith(pathSeperator)) { + p = p.substring(1); + } + if (p.endsWith(pathSeperator)) { + p = p.substring(0, p.length() - pathSeperator.length()); + } + return p; + } + + public static void setPrimaryFilesystem(IEaglerFilesystem fs) { + primaryFilesystem = fs; + } + + public static String[] splitPath(String p) { + String[] pth = normalizePath(p).split(pathSeperator); + for (int i = 0; i < pth.length; ++i) { + pth[i] = pth[i].trim(); + } + return pth; + } + + protected String path; + + protected IEaglerFilesystem myFilesystem; + + protected Supplier myFilesystemProvider; + + public VFile2(Object... path) { + this(createPath(path), primaryFilesystem); + } + + private VFile2(String path, IEaglerFilesystem fs) { + this.path = path; + this.myFilesystem = fs; + } + + private VFile2(String path, Supplier fs) { + this.path = path; + this.myFilesystemProvider = fs; + } + + public void assertNotRelative() { + if (isRelative()) + throw new EaglerFileSystemException("Relative paths are not allowed: " + path); + } + + public boolean canRead() { + return !isRelative() && getFS().eaglerExists(path); + } + public boolean canWrite() { return !isRelative(); } - - public String getParent() { - if(path == null) { - return null; - } - int i = path.lastIndexOf(pathSeperator); - return i == -1 ? ".." : path.substring(0, i); - } - - public int hashCode() { - return path == null ? 0 : path.hashCode(); - } - - public boolean equals(Object o) { - return path != null && o != null && (o instanceof VFile2) && path.equals(((VFile2)o).path); - } - - public boolean exists() { - return !isRelative() && getFS().eaglerExists(path); - } - + public boolean delete() { return !isRelative() && getFS().eaglerDelete(path); } - - public boolean renameTo(String p) { - if(!isRelative() && getFS().eaglerMove(path, p)) { - return true; - } - return false; + + public boolean equals(Object o) { + return path != null && o != null && (o instanceof VFile2) && path.equals(((VFile2) o).path); } - - public boolean renameTo(VFile2 p) { - return renameTo(p.path); + + public boolean exists() { + return !isRelative() && getFS().eaglerExists(path); } - - public int length() { - return isRelative() ? -1 : getFS().eaglerSize(path); - } - + public byte[] getAllBytes() { assertNotRelative(); - if(!exists()) { + if (!exists()) { return null; } ByteBuffer readBuffer = getFS().eaglerRead(path); byte[] copyBuffer = PlatformRuntime.castNativeByteBuffer(readBuffer); - if(copyBuffer != null) { + if (copyBuffer != null) { return copyBuffer; } try { copyBuffer = new byte[readBuffer.remaining()]; readBuffer.get(copyBuffer); return copyBuffer; - }finally { + } finally { PlatformRuntime.freeByteBuffer(readBuffer); } } - + public String getAllChars() { assertNotRelative(); - if(!exists()) { + if (!exists()) { return null; } return new String(getAllBytes(), StandardCharsets.UTF_8); } - + public String[] getAllLines() { assertNotRelative(); - if(!exists()) { + if (!exists()) { return null; } return EagUtils.linesArray(new String(getAllBytes(), StandardCharsets.UTF_8)); } - - public void setAllChars(String bytes) { - setAllBytes(bytes.getBytes(StandardCharsets.UTF_8)); + + protected IEaglerFilesystem getFS() { + if (myFilesystem == null) { + if (myFilesystemProvider != null) { + myFilesystem = myFilesystemProvider.get(); + } else { + myFilesystem = primaryFilesystem; + } + if (myFilesystem == null) { + throw new IllegalStateException("The filesystem has not been initialized yet!"); + } + } + return myFilesystem; } - - public void setAllBytes(byte[] bytes) { + + public InputStream getInputStream() { assertNotRelative(); - ByteBuffer copyBuffer = PlatformRuntime.castPrimitiveByteArray(bytes); - if(copyBuffer != null) { - getFS().eaglerWrite(path, copyBuffer); - return; - } - copyBuffer = PlatformRuntime.allocateByteBuffer(bytes.length); - try { - copyBuffer.put(bytes); - copyBuffer.flip(); - getFS().eaglerWrite(path, copyBuffer); - }finally { - PlatformRuntime.freeByteBuffer(copyBuffer); + return new VFileInputStream(getFS().eaglerRead(path)); + } + + public String getName() { + int i = path.lastIndexOf(pathSeperator); + return i == -1 ? path : path.substring(i + 1); + } + + public OutputStream getOutputStream() { + assertNotRelative(); + return new VFileOutputStream(this); + } + + public String getParent() { + if (path == null) { + return null; } + int i = path.lastIndexOf(pathSeperator); + return i == -1 ? ".." : path.substring(0, i); + } + + public String getPath() { + return path.equals("unnamed") ? null : path; + } + + public int hashCode() { + return path == null ? 0 : path.hashCode(); + } + + public boolean isRelative() { + return path == null || path.contains(".."); } public void iterateFiles(VFSIterator2 itr, boolean recursive) { @@ -285,6 +259,10 @@ public class VFile2 { fs.eaglerIterate(path, new VFSFilenameIteratorImpl(fs, itr), recursive); } + public int length() { + return isRelative() ? -1 : getFS().eaglerSize(path); + } + public List listFilenames(boolean recursive) { List ret = new ArrayList<>(); getFS().eaglerIterate(path, new VFSListFilenamesIteratorImpl(ret), recursive); @@ -298,13 +276,39 @@ public class VFile2 { return ret; } - public static int copyFile(VFile2 src, VFile2 dst) { - src.assertNotRelative(); - dst.assertNotRelative(); - IEaglerFilesystem sfs = src.getFS(); - if(sfs != dst.getFS()) { - throw new UnsupportedOperationException("Cannot copy file between filesystems!"); + public boolean renameTo(String p) { + if (!isRelative() && getFS().eaglerMove(path, p)) { + return true; } - return sfs.eaglerCopy(src.path, dst.path); + return false; + } + + public boolean renameTo(VFile2 p) { + return renameTo(p.path); + } + + public void setAllBytes(byte[] bytes) { + assertNotRelative(); + ByteBuffer copyBuffer = PlatformRuntime.castPrimitiveByteArray(bytes); + if (copyBuffer != null) { + getFS().eaglerWrite(path, copyBuffer); + return; + } + copyBuffer = PlatformRuntime.allocateByteBuffer(bytes.length); + try { + copyBuffer.put(bytes); + copyBuffer.flip(); + getFS().eaglerWrite(path, copyBuffer); + } finally { + PlatformRuntime.freeByteBuffer(copyBuffer); + } + } + + public void setAllChars(String bytes) { + setAllBytes(bytes.getBytes(StandardCharsets.UTF_8)); + } + + public String toString() { + return path; } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileInputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileInputStream.java index ebd6dc11..2547957b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileInputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileInputStream.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,56 +25,11 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; class VFileInputStream extends InputStream { private ByteBuffer fileBuffer; - + VFileInputStream(ByteBuffer buffer) { this.fileBuffer = buffer; } - @Override - public int read() throws IOException { - if(fileBuffer == null) { - throw new IOException("Stream is closed"); - } - if(fileBuffer.remaining() <= 0) { - return -1; - } - return (int)fileBuffer.get() & 0xFF; - } - - @Override - public int read(byte b[], int off, int len) throws IOException { - if(fileBuffer == null) { - throw new IOException("Stream is closed"); - } - int p = fileBuffer.position(); - int l = fileBuffer.limit(); - int r = l - p; - if(r < len) { - len = r; - } - if(len > 0) { - fileBuffer.get(b, off, len); - } - return len <= 0 ? -1 : len; - } - - @Override - public long skip(long n) throws IOException { - if(fileBuffer == null) { - throw new IOException("Stream is closed"); - } - int p = fileBuffer.position(); - int l = fileBuffer.limit(); - int r = l - p; - if(r < n) { - n = r; - } - if(n > 0) { - fileBuffer.position(p + (int)n); - } - return n; - } - @Override public int available() throws IOException { return fileBuffer == null ? -1 : fileBuffer.remaining(); @@ -81,9 +37,54 @@ class VFileInputStream extends InputStream { @Override public void close() { - if(fileBuffer != null) { + if (fileBuffer != null) { PlatformRuntime.freeByteBuffer(fileBuffer); fileBuffer = null; } } + + @Override + public int read() throws IOException { + if (fileBuffer == null) { + throw new IOException("Stream is closed"); + } + if (fileBuffer.remaining() <= 0) { + return -1; + } + return (int) fileBuffer.get() & 0xFF; + } + + @Override + public int read(byte b[], int off, int len) throws IOException { + if (fileBuffer == null) { + throw new IOException("Stream is closed"); + } + int p = fileBuffer.position(); + int l = fileBuffer.limit(); + int r = l - p; + if (r < len) { + len = r; + } + if (len > 0) { + fileBuffer.get(b, off, len); + } + return len <= 0 ? -1 : len; + } + + @Override + public long skip(long n) throws IOException { + if (fileBuffer == null) { + throw new IOException("Stream is closed"); + } + int p = fileBuffer.position(); + int l = fileBuffer.limit(); + int r = l - p; + if (r < n) { + n = r; + } + if (n > 0) { + fileBuffer.position(p + (int) n); + } + return n; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileOutputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileOutputStream.java index 8be71750..a0e8faa3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileOutputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/internal/vfs2/VFileOutputStream.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,7 +34,7 @@ class VFileOutputStream extends EaglerOutputStream { @Override public void close() throws IOException { - if(!closed) { + if (!closed) { closed = true; ByteBuffer copyBuffer = PlatformRuntime.allocateByteBuffer(count); try { @@ -41,10 +42,10 @@ class VFileOutputStream extends EaglerOutputStream { copyBuffer.flip(); try { vfsFile.getFS().eaglerWrite(vfsFile.path, copyBuffer); - }catch(Throwable t) { + } catch (Throwable t) { throw new IOException("Could not write stream contents to file!", t); } - }finally { + } finally { PlatformRuntime.freeByteBuffer(copyBuffer); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONDataParserImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONDataParserImpl.java index 29bb5668..9e765d15 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONDataParserImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONDataParserImpl.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.json; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeCodec.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeCodec.java index 6299b4c4..43d56c06 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeCodec.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeCodec.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.json; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeDeserializer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeDeserializer.java index 73c575cd..d74067fe 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeDeserializer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeDeserializer.java @@ -5,30 +5,31 @@ import org.json.JSONException; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface JSONTypeDeserializer { - + + O deserialize(J json) throws JSONException; + default O deserializeFromJson(J json) throws JSONException { try { return deserialize(json); - }catch(JSONException obj) { + } catch (JSONException obj) { throw obj; - }catch(Throwable t) { + } catch (Throwable t) { throw new JSONException("Exception deserializing JSON object", t); } } - - O deserialize(J json) throws JSONException; - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeProvider.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeProvider.java index 3d0dd8be..b843221a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeProvider.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeProvider.java @@ -40,101 +40,34 @@ import net.minecraft.world.gen.ChunkProviderSettings; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JSONTypeProvider { - private static final Map,JSONTypeSerializer> serializers = new HashMap<>(); - private static final Map,JSONTypeDeserializer> deserializers = new HashMap<>(); - + private static final Map, JSONTypeSerializer> serializers = new HashMap<>(); + private static final Map, JSONTypeDeserializer> deserializers = new HashMap<>(); + private static final List parsers = new ArrayList<>(); - public static J serialize(Object object) throws JSONException { - JSONTypeSerializer ser = (JSONTypeSerializer) serializers.get(object.getClass()); - if(ser == null) { - for(Entry,JSONTypeSerializer> etr : serializers.entrySet()) { - if(etr.getKey().isInstance(object)) { - ser = (JSONTypeSerializer)etr.getValue(); - break; - } - } - } - if(ser != null) { - return ser.serializeToJson(object); - }else { - throw new JSONException("Could not find a serializer for " + object.getClass().getSimpleName()); - } - } - - public static O deserialize(Object object, Class clazz) throws JSONException { - return deserializeNoCast(parse(object), clazz); - } - - public static O deserializeNoCast(Object object, Class clazz) throws JSONException { - JSONTypeDeserializer ser = (JSONTypeDeserializer) deserializers.get(clazz); - if(ser != null) { - return (O)ser.deserializeFromJson(object); - }else { - throw new JSONException("Could not find a deserializer for " + object.getClass().getSimpleName()); - } - } - - public static JSONTypeSerializer getSerializer(Class object) { - return (JSONTypeSerializer)serializers.get(object); - } - - public static JSONTypeDeserializer getDeserializer(Class object) { - return (JSONTypeDeserializer)deserializers.get(object); - } - - public static Object parse(Object object) { - for(int i = 0, l = parsers.size(); i < l; ++i) { - JSONDataParserImpl parser = parsers.get(i); - if(parser.accepts(object)) { - return parser.parse(object); - } - } - return object; - } - - public static void registerType(Class clazz, Object obj) { - boolean valid = false; - if(obj instanceof JSONTypeSerializer) { - serializers.put(clazz, (JSONTypeSerializer)obj); - valid = true; - } - if(obj instanceof JSONTypeDeserializer) { - deserializers.put(clazz, (JSONTypeDeserializer)obj); - valid = true; - } - if(!valid) { - throw new IllegalArgumentException("Object " + obj.getClass().getSimpleName() + " is not a JsonSerializer or JsonDeserializer object"); - } - } - - public static void registerParser(JSONDataParserImpl obj) { - parsers.add(obj); - } - static { - + registerType(IChatComponent.class, new IChatComponent.Serializer()); registerType(ChatStyle.class, new ChatStyle.Serializer()); registerType(ServerStatusResponse.class, new ServerStatusResponse.Serializer()); registerType(ServerStatusResponse.MinecraftProtocolVersionIdentifier.class, new ServerStatusResponse.MinecraftProtocolVersionIdentifier.Serializer()); - registerType(ServerStatusResponse.PlayerCountData.class, - new ServerStatusResponse.PlayerCountData.Serializer()); + registerType(ServerStatusResponse.PlayerCountData.class, new ServerStatusResponse.PlayerCountData.Serializer()); registerType(ModelBlock.class, new ModelBlock.Deserializer()); registerType(BlockPart.class, new BlockPart.Deserializer()); registerType(BlockPartFace.class, new BlockPartFace.Deserializer()); @@ -155,7 +88,75 @@ public class JSONTypeProvider { registerParser(new JSONDataParserString()); registerParser(new JSONDataParserReader()); registerParser(new JSONDataParserStream()); - + + } + + public static O deserialize(Object object, Class clazz) throws JSONException { + return deserializeNoCast(parse(object), clazz); + } + + public static O deserializeNoCast(Object object, Class clazz) throws JSONException { + JSONTypeDeserializer ser = (JSONTypeDeserializer) deserializers.get(clazz); + if (ser != null) { + return (O) ser.deserializeFromJson(object); + } else { + throw new JSONException("Could not find a deserializer for " + object.getClass().getSimpleName()); + } + } + + public static JSONTypeDeserializer getDeserializer(Class object) { + return (JSONTypeDeserializer) deserializers.get(object); + } + + public static JSONTypeSerializer getSerializer(Class object) { + return (JSONTypeSerializer) serializers.get(object); + } + + public static Object parse(Object object) { + for (int i = 0, l = parsers.size(); i < l; ++i) { + JSONDataParserImpl parser = parsers.get(i); + if (parser.accepts(object)) { + return parser.parse(object); + } + } + return object; + } + + public static void registerParser(JSONDataParserImpl obj) { + parsers.add(obj); + } + + public static void registerType(Class clazz, Object obj) { + boolean valid = false; + if (obj instanceof JSONTypeSerializer) { + serializers.put(clazz, (JSONTypeSerializer) obj); + valid = true; + } + if (obj instanceof JSONTypeDeserializer) { + deserializers.put(clazz, (JSONTypeDeserializer) obj); + valid = true; + } + if (!valid) { + throw new IllegalArgumentException( + "Object " + obj.getClass().getSimpleName() + " is not a JsonSerializer or JsonDeserializer object"); + } + } + + public static J serialize(Object object) throws JSONException { + JSONTypeSerializer ser = (JSONTypeSerializer) serializers.get(object.getClass()); + if (ser == null) { + for (Entry, JSONTypeSerializer> etr : serializers.entrySet()) { + if (etr.getKey().isInstance(object)) { + ser = (JSONTypeSerializer) etr.getValue(); + break; + } + } + } + if (ser != null) { + return ser.serializeToJson(object); + } else { + throw new JSONException("Could not find a serializer for " + object.getClass().getSimpleName()); + } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeSerializer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeSerializer.java index 181b2d14..b2b0d690 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeSerializer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/JSONTypeSerializer.java @@ -5,30 +5,31 @@ import org.json.JSONException; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface JSONTypeSerializer { - + + J serialize(O object) throws JSONException; + default J serializeToJson(O object) throws JSONException { try { return serialize(object); - }catch(JSONException obj) { + } catch (JSONException obj) { throw obj; - }catch(Throwable t) { + } catch (Throwable t) { throw new JSONException("Exception serializing JSON object", t); } } - - J serialize(O object) throws JSONException; - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserReader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserReader.java index 1c355e19..b5072988 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserReader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserReader.java @@ -11,39 +11,40 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class JSONDataParserReader implements JSONDataParserImpl { - + public boolean accepts(Object type) { return type instanceof Reader; } @Override public Object parse(Object data) { - Reader r = (Reader)data; + Reader r = (Reader) data; StringBuilder builder = new StringBuilder(); char[] copyBuffer = new char[2048]; int i; try { try { - while((i = r.read(copyBuffer)) != -1) { + while ((i = r.read(copyBuffer)) != -1) { builder.append(copyBuffer, 0, i); } - }finally { + } finally { r.close(); } - }catch(IOException ex) { + } catch (IOException ex) { throw new JSONException("Could not deserialize from " + data.getClass().getSimpleName()); } return JSONTypeProvider.parse(builder.toString()); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserStream.java index 4b260f96..4d0602f0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserStream.java @@ -13,14 +13,15 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONTypeProvider; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,10 +35,10 @@ public class JSONDataParserStream implements JSONDataParserImpl { @Override public Object parse(Object data) { try { - InputStream s = (InputStream)data; + InputStream s = (InputStream) data; try { return JSONTypeProvider.parse(IOUtils.inputStreamToString(s, StandardCharsets.UTF_8)); - }finally { + } finally { s.close(); } } catch (IOException e) { diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserString.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserString.java index 2218bf03..44ba7c9b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserString.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/JSONDataParserString.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.json.JSONDataParserImpl; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,20 +30,20 @@ public class JSONDataParserString implements JSONDataParserImpl { @Override public Object parse(Object data) { - String s = ((String)data).trim(); + String s = ((String) data).trim(); try { - if(s.indexOf('{') == 0 && s.lastIndexOf('}') == s.length() - 1) { + if (s.indexOf('{') == 0 && s.lastIndexOf('}') == s.length() - 1) { return new JSONObject(s); - }else if(s.indexOf('[') == 0 && s.lastIndexOf(']') == s.length() - 1) { + } else if (s.indexOf('[') == 0 && s.lastIndexOf(']') == s.length() - 1) { return new JSONArray(s); - }else if ((s.indexOf('\"') == 0 && s.lastIndexOf('\"') == s.length() - 1) + } else if ((s.indexOf('\"') == 0 && s.lastIndexOf('\"') == s.length() - 1) || (s.indexOf('\'') == 0 && s.lastIndexOf('\'') == s.length() - 1)) { return (new JSONObject("{\"E\":" + s + "}")).getString("E"); - }else { - return (String)data; + } else { + return (String) data; } - }catch(JSONException ex) { - return (String)data; + } catch (JSONException ex) { + return (String) data; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/SoundMapDeserializer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/SoundMapDeserializer.java index 7e21dec9..55df2469 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/SoundMapDeserializer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/json/impl/SoundMapDeserializer.java @@ -14,14 +14,15 @@ import net.minecraft.client.audio.SoundList; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,7 +32,7 @@ public class SoundMapDeserializer implements JSONTypeDeserializer soundsMap = new HashMap<>(); - for(String str : json.keySet()) { + for (String str : json.keySet()) { soundsMap.put(str, JSONTypeProvider.deserialize(json.getJSONObject(str), SoundList.class)); } return new SoundMap(soundsMap); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/ILogRedirector.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/ILogRedirector.java index 9bf33950..4d92b489 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/ILogRedirector.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/ILogRedirector.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.log4j; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Level.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Level.java index e191613b..a6b23d35 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Level.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Level.java @@ -5,38 +5,38 @@ import java.io.PrintStream; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum Level { - - TRACE(0, "TRACE", false), DEBUG(1, "DEBUG", false), INFO(2, "INFO", false), - WARN(3, "WARN", false), ERROR(4, "ERROR", true), FATAL(5, "FATAL", true), - OFF(Integer.MAX_VALUE, "DISABLED", false); + + TRACE(0, "TRACE", false), DEBUG(1, "DEBUG", false), INFO(2, "INFO", false), WARN(3, "WARN", false), + ERROR(4, "ERROR", true), FATAL(5, "FATAL", true), OFF(Integer.MAX_VALUE, "DISABLED", false); public final int levelInt; public final String levelName; public final PrintStream stdout; public final boolean isErr; - + private Level(int levelInt, String levelName, boolean stderr) { this.levelInt = levelInt; this.levelName = levelName; this.stdout = stderr ? System.err : System.out; this.isErr = stderr; } - + PrintStream getPrintStream() { return stdout; } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/LogManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/LogManager.java index 2d295d36..8a020018 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/LogManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/LogManager.java @@ -6,41 +6,42 @@ import java.util.Map; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LogManager { - - private static final Map loggerInstances = new HashMap<>(); - + + private static final Map loggerInstances = new HashMap<>(); + public static final Object logLock = new Object(); public static Level logLevel = Level.DEBUG; public static ILogRedirector logRedirector = null; - + public static Logger getLogger() { return getLogger("Minecraft"); } - + public static Logger getLogger(String name) { Logger ret; - synchronized(loggerInstances) { + synchronized (loggerInstances) { ret = loggerInstances.get(name); - if(ret == null) { + if (ret == null) { ret = new Logger(name); } } return ret; } - + public static void setLevel(Level lv) { logLevel = lv; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Logger.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Logger.java index f734f35f..7c3eaadd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Logger.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/log4j/Logger.java @@ -9,167 +9,167 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class Logger { - - public final String loggerName; - Logger(String name) { - this.loggerName = name; - } - - public void trace(String msg) { - log(Level.TRACE, msg); - } - - public void trace(String msg, Object... args) { - log(Level.TRACE, msg, args); - } - - public void trace(Throwable msg) { - log(Level.WARN, msg); - } - - public void debug(String msg) { - log(Level.DEBUG, msg); - } - - public void debug(String msg, Object... args) { - log(Level.DEBUG, msg, args); - } - - public void debug(Throwable msg) { - log(Level.DEBUG, msg); - } - - public void info(String msg) { - log(Level.INFO, msg); - } - - public void info(String msg, Object... args) { - log(Level.INFO, msg, args); - } - - public void info(Throwable msg) { - log(Level.INFO, msg); - } - - public void warn(String msg) { - log(Level.WARN, msg); - } - - public void warn(String msg, Object... args) { - log(Level.WARN, msg, args); - } - - public void warn(Throwable msg) { - log(Level.WARN, msg); - } - - public void error(String msg) { - log(Level.ERROR, msg); - } - - public void error(String msg, Object... args) { - log(Level.ERROR, msg, args); - } - - public void error(Throwable msg) { - log(Level.ERROR, msg); - } - - public void fatal(String msg) { - log(Level.FATAL, msg); - } - - public void fatal(String msg, Object... args) { - log(Level.FATAL, msg, args); - } - - public void fatal(Throwable msg) { - log(Level.FATAL, msg); - } - private static final SimpleDateFormat fmt = new SimpleDateFormat("hh:mm:ss+SSS"); + private static final Date dateInstance = new Date(); - - public void log(Level level, String msg) { - if(level.levelInt >= LogManager.logLevel.levelInt) { - synchronized(LogManager.logLock) { - dateInstance.setTime(System.currentTimeMillis()); - String line = "[" + fmt.format(dateInstance) + "]" + - "[" + EagRuntime.currentThreadName() + "/" + level.levelName + "]" + - "[" + loggerName + "]: " + msg; - level.getPrintStream().println(line); - if(LogManager.logRedirector != null) { - LogManager.logRedirector.log(line, level.isErr); - } - } - } - } - - public void log(Level level, String msg, Object... args) { - if(level.levelInt >= LogManager.logLevel.levelInt) { - synchronized(LogManager.logLock) { - dateInstance.setTime(System.currentTimeMillis()); - String line = "[" + fmt.format(dateInstance) + "]" + - "[" + EagRuntime.currentThreadName() + "/" + level.levelName + "]" + - "[" + loggerName + "]: " + formatParams(msg, args); - level.getPrintStream().println(line); - if(LogManager.logRedirector != null) { - LogManager.logRedirector.log(line, level.isErr); - } - } - } - } public static String formatParams(String msg, Object... args) { - if(args.length > 0) { + if (args.length > 0) { StringBuilder builtString = new StringBuilder(); - for(int i = 0; i < args.length; ++i) { + for (int i = 0; i < args.length; ++i) { int idx = msg.indexOf("{}"); - if(idx != -1) { + if (idx != -1) { builtString.append(msg.substring(0, idx)); builtString.append(args[i]); msg = msg.substring(idx + 2); - }else { + } else { break; } } builtString.append(msg); return builtString.toString(); - }else { + } else { return msg; } } + public final String loggerName; + + Logger(String name) { + this.loggerName = name; + } + + public void debug(String msg) { + log(Level.DEBUG, msg); + } + + public void debug(String msg, Object... args) { + log(Level.DEBUG, msg, args); + } + + public void debug(Throwable msg) { + log(Level.DEBUG, msg); + } + + public void error(String msg) { + log(Level.ERROR, msg); + } + + public void error(String msg, Object... args) { + log(Level.ERROR, msg, args); + } + + public void error(Throwable msg) { + log(Level.ERROR, msg); + } + + public void fatal(String msg) { + log(Level.FATAL, msg); + } + + public void fatal(String msg, Object... args) { + log(Level.FATAL, msg, args); + } + + public void fatal(Throwable msg) { + log(Level.FATAL, msg); + } + + public void info(String msg) { + log(Level.INFO, msg); + } + + public void info(String msg, Object... args) { + log(Level.INFO, msg, args); + } + + public void info(Throwable msg) { + log(Level.INFO, msg); + } + + public boolean isDebugEnabled() { + return LogManager.logLevel.levelInt <= Level.DEBUG.levelInt; + } + + public void log(Level level, String msg) { + if (level.levelInt >= LogManager.logLevel.levelInt) { + synchronized (LogManager.logLock) { + dateInstance.setTime(System.currentTimeMillis()); + String line = "[" + fmt.format(dateInstance) + "]" + "[" + EagRuntime.currentThreadName() + "/" + + level.levelName + "]" + "[" + loggerName + "]: " + msg; + level.getPrintStream().println(line); + if (LogManager.logRedirector != null) { + LogManager.logRedirector.log(line, level.isErr); + } + } + } + } + + public void log(Level level, String msg, Object... args) { + if (level.levelInt >= LogManager.logLevel.levelInt) { + synchronized (LogManager.logLock) { + dateInstance.setTime(System.currentTimeMillis()); + String line = "[" + fmt.format(dateInstance) + "]" + "[" + EagRuntime.currentThreadName() + "/" + + level.levelName + "]" + "[" + loggerName + "]: " + formatParams(msg, args); + level.getPrintStream().println(line); + if (LogManager.logRedirector != null) { + LogManager.logRedirector.log(line, level.isErr); + } + } + } + } + public void log(Level level, Throwable msg) { logExcp(level, "Exception Thrown", msg); } - + private void logExcp(final Level level, String h, Throwable msg) { log(level, "{}: {}", h, msg.toString()); EagRuntime.getStackTrace(msg, (e) -> log(level, " at {}", e)); PlatformRuntime.printJSExceptionIfBrowser(msg); Throwable cause = msg.getCause(); - if(cause != null) { + if (cause != null) { logExcp(level, "Caused By", cause); } } - public boolean isDebugEnabled() { - return LogManager.logLevel.levelInt <= Level.DEBUG.levelInt; + public void trace(String msg) { + log(Level.TRACE, msg); } - + + public void trace(String msg, Object... args) { + log(Level.TRACE, msg, args); + } + + public void trace(Throwable msg) { + log(Level.WARN, msg); + } + + public void warn(String msg) { + log(Level.WARN, msg); + } + + public void warn(String msg, Object... args) { + log(Level.WARN, msg, args); + } + + public void warn(Throwable msg) { + log(Level.WARN, msg); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/AcceleratedEffectRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/AcceleratedEffectRenderer.java index 17278466..d57bda3e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/AcceleratedEffectRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/AcceleratedEffectRenderer.java @@ -9,14 +9,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,7 +37,7 @@ public class AcceleratedEffectRenderer implements IAcceleratedParticleEngine { this.partialTicks = partialTicks; InstancedParticleRenderer.begin(); Entity et = Minecraft.getMinecraft().getRenderViewEntity(); - if(et != null) { + if (et != null) { f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); @@ -51,20 +52,26 @@ public class AcceleratedEffectRenderer implements IAcceleratedParticleEngine { } @Override - public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, - int texSize, float particleSize, float r, float g, float b, float a) { - float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks - EntityFX.interpPosX); - float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks - EntityFX.interpPosY); - float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks - EntityFX.interpPosZ); + public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, int texSize, + float particleSize, float r, float g, float b, float a) { + float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks + - EntityFX.interpPosX); + float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks + - EntityFX.interpPosY); + float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks + - EntityFX.interpPosZ); drawParticle(xx, yy, zz, particleIndexX, particleIndexY, lightMapData, texSize, particleSize, r, g, b, a); } @Override - public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, - int texSize, float particleSize, int rgba) { - float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks - EntityFX.interpPosX); - float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks - EntityFX.interpPosY); - float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks - EntityFX.interpPosZ); + public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, int texSize, + float particleSize, int rgba) { + float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks + - EntityFX.interpPosX); + float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks + - EntityFX.interpPosY); + float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks + - EntityFX.interpPosZ); drawParticle(xx, yy, zz, particleIndexX, particleIndexY, lightMapData, texSize, particleSize, rgba); } @@ -72,14 +79,14 @@ public class AcceleratedEffectRenderer implements IAcceleratedParticleEngine { public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, int lightMapData, int texSize, float particleSize, float r, float g, float b, float a) { InstancedParticleRenderer.appendParticle(posX, posY, posZ, particleIndexX, particleIndexY, lightMapData & 0xFF, - (lightMapData >>> 16) & 0xFF, (int)(particleSize * 16.0f), texSize, r, g, b, a); + (lightMapData >>> 16) & 0xFF, (int) (particleSize * 16.0f), texSize, r, g, b, a); } @Override public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, int lightMapData, int texSize, float particleSize, int rgba) { InstancedParticleRenderer.appendParticle(posX, posY, posZ, particleIndexX, particleIndexY, lightMapData & 0xFF, - (lightMapData >>> 16) & 0xFF, (int)(particleSize * 16.0f), texSize, rgba); + (lightMapData >>> 16) & 0xFF, (int) (particleSize * 16.0f), texSize, rgba); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/ChunkUpdateManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/ChunkUpdateManager.java index 579a29dd..11f959c0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/ChunkUpdateManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/ChunkUpdateManager.java @@ -1,6 +1,6 @@ package net.lax1dude.eaglercraft.v1_8.minecraft; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE; import java.util.LinkedList; import java.util.List; @@ -23,29 +23,58 @@ import net.minecraft.util.EnumWorldBlockLayer; public class ChunkUpdateManager { + public static class EmptyBlockLayerException extends IllegalStateException { + } + private static final Logger LOGGER = LogManager.getLogger(); - private final WorldVertexBufferUploader worldVertexUploader; - private final RegionRenderCacheBuilder renderCache; + private final RegionRenderCacheBuilder renderCache; private int chunkUpdatesTotal = 0; private int chunkUpdatesTotalLast = 0; private int chunkUpdatesTotalImmediate = 0; private int chunkUpdatesTotalImmediateLast = 0; private int chunkUpdatesQueued = 0; private int chunkUpdatesQueuedLast = 0; + private long chunkUpdatesTotalLastUpdate = 0l; - + private final List queue = new LinkedList<>(); public ChunkUpdateManager() { worldVertexUploader = new WorldVertexBufferUploader(); renderCache = new RegionRenderCacheBuilder(); } - - public static class EmptyBlockLayerException extends IllegalStateException { + + public String getDebugInfo() { + long millis = EagRuntime.steadyTimeMillis(); + + if (millis - chunkUpdatesTotalLastUpdate > 500l) { + chunkUpdatesTotalLastUpdate = millis; + chunkUpdatesTotalLast = chunkUpdatesTotal; + chunkUpdatesTotalImmediateLast = chunkUpdatesTotalImmediate; + chunkUpdatesTotalImmediate = 0; + chunkUpdatesTotal = 0; + chunkUpdatesQueuedLast = chunkUpdatesQueued; + chunkUpdatesQueued -= chunkUpdatesTotalLast; + if (chunkUpdatesQueued < 0) { + chunkUpdatesQueued = 0; + } + } + + return "Uq: " + (chunkUpdatesTotalLast + chunkUpdatesTotalImmediateLast) + "/" + + (chunkUpdatesQueuedLast + chunkUpdatesTotalImmediateLast); } - + + public boolean isAlreadyQueued(RenderChunk update) { + for (int i = 0, l = queue.size(); i < l; ++i) { + if (queue.get(i).getRenderChunk() == update) { + return true; + } + } + return false; + } + private void runGenerator(ChunkCompileTaskGenerator generator, Entity entity) { generator.setRegionRenderCacheBuilder(renderCache); float f = (float) entity.posX; @@ -60,11 +89,13 @@ public class ChunkUpdateManager { try { r.resortTransparency(f, f1, f2, generator); CompiledChunk ch = generator.getCompiledChunk(); - if(ch.isLayerEmpty(EnumWorldBlockLayer.TRANSLUCENT) && ch.isLayerEmpty(EnumWorldBlockLayer.REALISTIC_WATER)) { + if (ch.isLayerEmpty(EnumWorldBlockLayer.TRANSLUCENT) + && ch.isLayerEmpty(EnumWorldBlockLayer.REALISTIC_WATER)) { throw new EmptyBlockLayerException(); } - }catch(EmptyBlockLayerException ex) { - LOGGER.error("RenderChunk {} tried to update it's TRANSLUCENT layer with no proper initialization", r.getPosition()); + } catch (EmptyBlockLayerException ex) { + LOGGER.error("RenderChunk {} tried to update it's TRANSLUCENT layer with no proper initialization", + r.getPosition()); generator.setStatus(ChunkCompileTaskGenerator.Status.DONE); return; // rip } @@ -86,13 +117,15 @@ public class ChunkUpdateManager { } generator.getRenderChunk().setCompiledChunk(compiledchunk); } else if (chunkcompiletaskgenerator$type == ChunkCompileTaskGenerator.Type.RESORT_TRANSPARENCY) { - if(!compiledchunk.isLayerEmpty(EnumWorldBlockLayer.TRANSLUCENT)) { - this.uploadChunk(EnumWorldBlockLayer.TRANSLUCENT, generator.getRegionRenderCacheBuilder() + if (!compiledchunk.isLayerEmpty(EnumWorldBlockLayer.TRANSLUCENT)) { + this.uploadChunk( + EnumWorldBlockLayer.TRANSLUCENT, generator.getRegionRenderCacheBuilder() .getWorldRendererByLayer(EnumWorldBlockLayer.TRANSLUCENT), generator.getRenderChunk(), compiledchunk); } - if(!compiledchunk.isLayerEmpty(EnumWorldBlockLayer.REALISTIC_WATER)) { - this.uploadChunk(EnumWorldBlockLayer.REALISTIC_WATER, generator.getRegionRenderCacheBuilder() + if (!compiledchunk.isLayerEmpty(EnumWorldBlockLayer.REALISTIC_WATER)) { + this.uploadChunk( + EnumWorldBlockLayer.REALISTIC_WATER, generator.getRegionRenderCacheBuilder() .getWorldRendererByLayer(EnumWorldBlockLayer.REALISTIC_WATER), generator.getRenderChunk(), compiledchunk); } @@ -100,39 +133,10 @@ public class ChunkUpdateManager { generator.setStatus(ChunkCompileTaskGenerator.Status.DONE); } } - - public boolean updateChunks(long timeout) { - Entity entity = Minecraft.getMinecraft().getRenderViewEntity(); - if (entity == null) { - queue.clear(); - chunkUpdatesQueued = 0; - return false; - }else { - boolean flag = false; - long millis = EagRuntime.steadyTimeMillis(); - List droppedUpdates = new LinkedList<>(); - while(!queue.isEmpty()) { - ChunkCompileTaskGenerator generator = queue.remove(0); - - if(!generator.canExecuteYet()) { - if(millis - generator.goddamnFuckingTimeout < 60000l) { - droppedUpdates.add(generator); - } - continue; - } - - runGenerator(generator, entity); - flag = true; - - ++chunkUpdatesTotal; - - if(timeout < EagRuntime.nanoTime()) { - break; - } - } - queue.addAll(droppedUpdates); - return flag; - } + + public void stopChunkUpdates() { + queue.clear(); + chunkUpdatesQueued = 0; } public boolean updateChunkLater(RenderChunk chunkRenderer) { @@ -140,11 +144,11 @@ public class ChunkUpdateManager { boolean flag = queue.size() < 100; if (!flag) { chunkcompiletaskgenerator.finish(); - }else { + } else { chunkcompiletaskgenerator.addFinishRunnable(new Runnable() { @Override public void run() { - if(queue.remove(chunkcompiletaskgenerator)) { + if (queue.remove(chunkcompiletaskgenerator)) { ++chunkUpdatesTotal; } } @@ -164,13 +168,42 @@ public class ChunkUpdateManager { return true; } - public void stopChunkUpdates() { - queue.clear(); - chunkUpdatesQueued = 0; + public boolean updateChunks(long timeout) { + Entity entity = Minecraft.getMinecraft().getRenderViewEntity(); + if (entity == null) { + queue.clear(); + chunkUpdatesQueued = 0; + return false; + } else { + boolean flag = false; + long millis = EagRuntime.steadyTimeMillis(); + List droppedUpdates = new LinkedList<>(); + while (!queue.isEmpty()) { + ChunkCompileTaskGenerator generator = queue.remove(0); + + if (!generator.canExecuteYet()) { + if (millis - generator.goddamnFuckingTimeout < 60000l) { + droppedUpdates.add(generator); + } + continue; + } + + runGenerator(generator, entity); + flag = true; + + ++chunkUpdatesTotal; + + if (timeout < EagRuntime.nanoTime()) { + break; + } + } + queue.addAll(droppedUpdates); + return flag; + } } public boolean updateTransparencyLater(RenderChunk chunkRenderer) { - if(isAlreadyQueued(chunkRenderer)) { + if (isAlreadyQueued(chunkRenderer)) { return true; } final ChunkCompileTaskGenerator chunkcompiletaskgenerator = chunkRenderer.makeCompileTaskTransparency(); @@ -178,11 +211,11 @@ public class ChunkUpdateManager { return true; } chunkcompiletaskgenerator.goddamnFuckingTimeout = EagRuntime.steadyTimeMillis(); - if(queue.size() < 100) { + if (queue.size() < 100) { chunkcompiletaskgenerator.addFinishRunnable(new Runnable() { @Override public void run() { - if(queue.remove(chunkcompiletaskgenerator)) { + if (queue.remove(chunkcompiletaskgenerator)) { ++chunkUpdatesTotal; } } @@ -190,7 +223,7 @@ public class ChunkUpdateManager { queue.add(chunkcompiletaskgenerator); ++chunkUpdatesQueued; return true; - }else { + } else { return false; } } @@ -210,33 +243,4 @@ public class ChunkUpdateManager { EaglercraftGPU.glEndList(); } - public boolean isAlreadyQueued(RenderChunk update) { - for(int i = 0, l = queue.size(); i < l; ++i) { - if(queue.get(i).getRenderChunk() == update) { - return true; - } - } - return false; - } - - public String getDebugInfo() { - long millis = EagRuntime.steadyTimeMillis(); - - if(millis - chunkUpdatesTotalLastUpdate > 500l) { - chunkUpdatesTotalLastUpdate = millis; - chunkUpdatesTotalLast = chunkUpdatesTotal; - chunkUpdatesTotalImmediateLast = chunkUpdatesTotalImmediate; - chunkUpdatesTotalImmediate = 0; - chunkUpdatesTotal = 0; - chunkUpdatesQueuedLast = chunkUpdatesQueued; - chunkUpdatesQueued -= chunkUpdatesTotalLast; - if(chunkUpdatesQueued < 0) { - chunkUpdatesQueued = 0; - } - } - - return "Uq: " + (chunkUpdatesTotalLast + chunkUpdatesTotalImmediateLast) + "/" - + (chunkUpdatesQueuedLast + chunkUpdatesTotalImmediateLast); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFolderResourcePack.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFolderResourcePack.java index e8ccb4f1..ba3c0354 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFolderResourcePack.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFolderResourcePack.java @@ -30,14 +30,15 @@ import net.minecraft.client.resources.AbstractResourcePack; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,270 +50,20 @@ public class EaglerFolderResourcePack extends AbstractResourcePack { public static final String SERVER_RESOURCE_PACKS = "srp"; public static final String RESOURCE_PACKS = "resourcepacks"; - private final String prefix; - private final String displayName; - private final Set domains; - private final long timestamp; - private static boolean isSupported = false; - public static void setSupported(boolean supported) { - isSupported = supported; - } - - public static boolean isSupported() { - return isSupported; - } - - public EaglerFolderResourcePack(String resourcePackFileIn, String displayName, String prefix, Set domains, long timestamp) { - super(resourcePackFileIn); - this.displayName = displayName; - this.prefix = prefix; - this.domains = domains; - this.timestamp = timestamp; - } - - @Override - public Set getResourceDomains() { - return domains; - } - - @Override - protected InputStream getInputStreamByName(String var1) throws IOException { - return (new VFile2(prefix, this.resourcePackFile, var1)).getInputStream(); - } - - @Override - protected boolean hasResourceName(String var1) { - return (new VFile2(prefix, this.resourcePackFile, var1)).exists(); - } - - public long getTimestamp() { - return timestamp; - } - - public String getDisplayName() { - return displayName; - } - - public static List getFolderResourcePacks(String prefix) { - if(!isSupported) { - return Collections.emptyList(); - } - String str = (new VFile2(prefix, "manifest.json")).getAllChars(); - if(str == null) { - return Collections.emptyList(); - } - try { - JSONArray json = (new JSONObject(str)).getJSONArray("resourcePacks"); - List ret = new ArrayList<>(json.length()); - for(int i = 0, l = json.length(); i < l; ++i) { - JSONObject jp = json.getJSONObject(i); - String folderName = jp.getString("folder"); - String displayName = jp.optString("name", folderName); - long timestamp = jp.getLong("timestamp"); - Set domains = Sets.newHashSet(); - JSONArray jsonDomains = jp.getJSONArray("domains"); - for(int j = 0, k = jsonDomains.length(); j < k; ++j) { - domains.add(jsonDomains.getString(j)); - } - ret.add(new EaglerFolderResourcePack(folderName, displayName, prefix, domains, timestamp)); - } - return ret; - }catch(JSONException ex) { - logger.error("Failed to load resource pack manifest!"); - logger.error(ex); - return Collections.emptyList(); - } - } - - public static EaglerFolderResourcePack importResourcePack(String name, String prefix, byte[] file) throws IOException { - if(!isSupported) { - return null; - } - logger.info("Importing resource pack: {}", name); - int idx = name.lastIndexOf('.'); - if(idx != -1) { - name = name.substring(0, idx); - } - String folderName = name.replaceAll("[^A-Za-z0-9\\-_ \\(\\)]", "_"); - - final List existingLst = getFolderResourcePacks(RESOURCE_PACKS); - - vigg: for(;;) { - for(int i = 0, l = existingLst.size(); i < l; ++i) { - EaglerFolderResourcePack rp = existingLst.get(i); - if(rp.resourcePackFile.equalsIgnoreCase(folderName)) { - folderName = folderName + "-"; - continue vigg; - } - } - break; - } - - List fileNames = Lists.newArrayList(); - - logger.info("Counting files..."); - ZipEntry zipEntry; - try(ZipInputStream ziss = new ZipInputStream(new EaglerInputStream(file))) { - while ((zipEntry = ziss.getNextEntry()) != null) { - if (!zipEntry.isDirectory()) { - fileNames.add(zipEntry.getName()); - } - } - } - - int prefixLen = Integer.MAX_VALUE; - for(int i = 0, l = fileNames.size(); i < l; ++i) { - String fn = fileNames.get(i); - if(fn.equals("pack.mcmeta") || fn.endsWith("/pack.mcmeta")) { - int currPrefixLen = fn.length() - 11; - if (prefixLen > currPrefixLen) { - prefixLen = currPrefixLen; - } - } - } - if (prefixLen == Integer.MAX_VALUE) { - prefixLen = 0; - } - - Set domainsList = Sets.newHashSet(); - String fn; - for(int i = 0, l = fileNames.size(); i < l; ++i) { - fn = fileNames.get(i); - if(fn.length() > prefixLen + 7) { - fn = fn.substring(prefixLen + 7); - int j = fn.indexOf('/'); - if(j != -1) { - domainsList.add(fn.substring(0, j)); - } - } - } - - VFile2 dstDir = new VFile2(prefix, folderName); - logger.info("Extracting to: {}", dstDir.getPath()); - - try { - int totalSize = 0; - int totalFiles = 0; - int lastProg = 0; - try(ZipInputStream ziss = new ZipInputStream(new EaglerInputStream(file))) { - int sz; - while ((zipEntry = ziss.getNextEntry()) != null) { - if (!zipEntry.isDirectory()) { - fn = zipEntry.getName(); - if(fn.length() > prefixLen) { - byte[] buffer; - sz = (int)zipEntry.getSize(); - if(sz >= 0) { - buffer = new byte[sz]; - int i = 0, j; - while(i < buffer.length && (j = ziss.read(buffer, i, buffer.length - i)) != -1) { - i += j; - } - }else { - buffer = EaglerInputStream.inputStreamToBytes(ziss); - } - (new VFile2(prefix, folderName, fn.substring(prefixLen))).setAllBytes(buffer); - totalSize += buffer.length; - ++totalFiles; - if(totalSize - lastProg > 25000) { - lastProg = totalSize; - logger.info("Extracted {} files, {} bytes from ZIP file...", totalFiles, totalSize); - } - } - } - } - } - }catch(IOException ex) { - logger.error("Encountered an error extracting zip file, deleting extracted files..."); - for(int i = 0, l = fileNames.size(); i < l; ++i) { - fn = fileNames.get(i); - if(fn.length() > prefixLen) { - (new VFile2(dstDir, fn.substring(prefixLen))).delete(); - } - } - throw ex; - } - - logger.info("Updating manifest..."); - - VFile2 manifestFile = new VFile2(prefix, "manifest.json"); - String str = manifestFile.getAllChars(); - JSONArray arr = null; - if(str != null) { - try { - arr = (new JSONObject(str)).getJSONArray("resourcePacks"); - }catch(JSONException ex) { - } - } - - if(arr == null) { - arr = new JSONArray(); - } - - JSONObject manifestEntry = new JSONObject(); - manifestEntry.put("folder", folderName); - manifestEntry.put("name", name); - long timestamp = System.currentTimeMillis(); - manifestEntry.put("timestamp", timestamp); - JSONArray domainsListJson = new JSONArray(); - for(String str2 : domainsList) { - domainsListJson.put(str2); - } - manifestEntry.put("domains", domainsListJson); - arr.put(manifestEntry); - - manifestFile.setAllChars((new JSONObject()).put("resourcePacks", arr).toString()); - - logger.info("Done!"); - return new EaglerFolderResourcePack(folderName, name, prefix, domainsList, timestamp); - } - - public static void loadRemoteResourcePack(String url, String hash, Consumer cb, Consumer ast, Runnable loading) { - if (!isSupported || !hash.matches("^[a-f0-9]{40}$")) { - cb.accept(null); + public static void deleteOldResourcePacks(String prefix, long maxAge) { + if (!isSupported) { return; } - final List lst = getFolderResourcePacks(SERVER_RESOURCE_PACKS); - for(int i = 0, l = lst.size(); i < l; ++i) { + long millis = System.currentTimeMillis(); + List lst = getFolderResourcePacks(prefix); + for (int i = 0, l = lst.size(); i < l; ++i) { EaglerFolderResourcePack rp = lst.get(i); - if(rp.resourcePackFile.equals(hash)) { - cb.accept(rp); - return; + if (millis - rp.timestamp > maxAge) { + deleteResourcePack(rp); } } - PlatformRuntime.downloadRemoteURIByteArray(url, arr -> { - ast.accept(() -> { - if (arr == null) { - cb.accept(null); - return; - } - SHA1Digest digest = new SHA1Digest(); - digest.update(arr, 0, arr.length); - byte[] hashOut = new byte[20]; - digest.doFinal(hashOut, 0); - if(!hash.equals(ArrayUtils.hexString(hashOut))) { - logger.error("Downloaded resource pack hash does not equal expected resource pack hash!"); - cb.accept(null); - return; - } - if(lst.size() >= 5) { - lst.sort(Comparator.comparingLong(pack -> pack.timestamp)); - for(int i = 0; i < lst.size() - 5; i++) { - deleteResourcePack(SERVER_RESOURCE_PACKS, lst.get(i).resourcePackFile); - } - } - loading.run(); - try { - cb.accept(importResourcePack(hash, SERVER_RESOURCE_PACKS, arr)); - }catch(IOException ex) { - logger.error("Failed to load resource pack downloaded from server!"); - logger.error(ex); - cb.accept(null); - } - }); - }); } public static void deleteResourcePack(EaglerFolderResourcePack pack) { @@ -327,38 +78,299 @@ public class EaglerFolderResourcePack extends AbstractResourcePack { (new VFile2(prefix, name)).listFiles(true).forEach(VFile2::delete); VFile2 manifestFile = new VFile2(prefix, "manifest.json"); String str = manifestFile.getAllChars(); - if(str != null) { + if (str != null) { try { JSONArray json = (new JSONObject(str)).getJSONArray("resourcePacks"); boolean changed = false; - for(int i = 0, l = json.length(); i < l; ++i) { - if(json.getJSONObject(i).getString("folder").equals(name)) { + for (int i = 0, l = json.length(); i < l; ++i) { + if (json.getJSONObject(i).getString("folder").equals(name)) { json.remove(i); changed = true; break; } } - if(changed) { + if (changed) { manifestFile.setAllChars((new JSONObject()).put("resourcePacks", json).toString()); - }else { - logger.warn("Failed to remove pack \"{}\" from manifest, it wasn't found in the list for some reason", name); + } else { + logger.warn( + "Failed to remove pack \"{}\" from manifest, it wasn't found in the list for some reason", + name); } - }catch(JSONException ex) { + } catch (JSONException ex) { } } } - public static void deleteOldResourcePacks(String prefix, long maxAge) { + public static List getFolderResourcePacks(String prefix) { if (!isSupported) { - return; + return Collections.emptyList(); } - long millis = System.currentTimeMillis(); - List lst = getFolderResourcePacks(prefix); - for(int i = 0, l = lst.size(); i < l; ++i) { - EaglerFolderResourcePack rp = lst.get(i); - if(millis - rp.timestamp > maxAge) { - deleteResourcePack(rp); + String str = (new VFile2(prefix, "manifest.json")).getAllChars(); + if (str == null) { + return Collections.emptyList(); + } + try { + JSONArray json = (new JSONObject(str)).getJSONArray("resourcePacks"); + List ret = new ArrayList<>(json.length()); + for (int i = 0, l = json.length(); i < l; ++i) { + JSONObject jp = json.getJSONObject(i); + String folderName = jp.getString("folder"); + String displayName = jp.optString("name", folderName); + long timestamp = jp.getLong("timestamp"); + Set domains = Sets.newHashSet(); + JSONArray jsonDomains = jp.getJSONArray("domains"); + for (int j = 0, k = jsonDomains.length(); j < k; ++j) { + domains.add(jsonDomains.getString(j)); + } + ret.add(new EaglerFolderResourcePack(folderName, displayName, prefix, domains, timestamp)); } + return ret; + } catch (JSONException ex) { + logger.error("Failed to load resource pack manifest!"); + logger.error(ex); + return Collections.emptyList(); } } + + public static EaglerFolderResourcePack importResourcePack(String name, String prefix, byte[] file) + throws IOException { + if (!isSupported) { + return null; + } + logger.info("Importing resource pack: {}", name); + int idx = name.lastIndexOf('.'); + if (idx != -1) { + name = name.substring(0, idx); + } + String folderName = name.replaceAll("[^A-Za-z0-9\\-_ \\(\\)]", "_"); + + final List existingLst = getFolderResourcePacks(RESOURCE_PACKS); + + vigg: for (;;) { + for (int i = 0, l = existingLst.size(); i < l; ++i) { + EaglerFolderResourcePack rp = existingLst.get(i); + if (rp.resourcePackFile.equalsIgnoreCase(folderName)) { + folderName = folderName + "-"; + continue vigg; + } + } + break; + } + + List fileNames = Lists.newArrayList(); + + logger.info("Counting files..."); + ZipEntry zipEntry; + try (ZipInputStream ziss = new ZipInputStream(new EaglerInputStream(file))) { + while ((zipEntry = ziss.getNextEntry()) != null) { + if (!zipEntry.isDirectory()) { + fileNames.add(zipEntry.getName()); + } + } + } + + int prefixLen = Integer.MAX_VALUE; + for (int i = 0, l = fileNames.size(); i < l; ++i) { + String fn = fileNames.get(i); + if (fn.equals("pack.mcmeta") || fn.endsWith("/pack.mcmeta")) { + int currPrefixLen = fn.length() - 11; + if (prefixLen > currPrefixLen) { + prefixLen = currPrefixLen; + } + } + } + if (prefixLen == Integer.MAX_VALUE) { + prefixLen = 0; + } + + Set domainsList = Sets.newHashSet(); + String fn; + for (int i = 0, l = fileNames.size(); i < l; ++i) { + fn = fileNames.get(i); + if (fn.length() > prefixLen + 7) { + fn = fn.substring(prefixLen + 7); + int j = fn.indexOf('/'); + if (j != -1) { + domainsList.add(fn.substring(0, j)); + } + } + } + + VFile2 dstDir = new VFile2(prefix, folderName); + logger.info("Extracting to: {}", dstDir.getPath()); + + try { + int totalSize = 0; + int totalFiles = 0; + int lastProg = 0; + try (ZipInputStream ziss = new ZipInputStream(new EaglerInputStream(file))) { + int sz; + while ((zipEntry = ziss.getNextEntry()) != null) { + if (!zipEntry.isDirectory()) { + fn = zipEntry.getName(); + if (fn.length() > prefixLen) { + byte[] buffer; + sz = (int) zipEntry.getSize(); + if (sz >= 0) { + buffer = new byte[sz]; + int i = 0, j; + while (i < buffer.length && (j = ziss.read(buffer, i, buffer.length - i)) != -1) { + i += j; + } + } else { + buffer = EaglerInputStream.inputStreamToBytes(ziss); + } + (new VFile2(prefix, folderName, fn.substring(prefixLen))).setAllBytes(buffer); + totalSize += buffer.length; + ++totalFiles; + if (totalSize - lastProg > 25000) { + lastProg = totalSize; + logger.info("Extracted {} files, {} bytes from ZIP file...", totalFiles, totalSize); + } + } + } + } + } + } catch (IOException ex) { + logger.error("Encountered an error extracting zip file, deleting extracted files..."); + for (int i = 0, l = fileNames.size(); i < l; ++i) { + fn = fileNames.get(i); + if (fn.length() > prefixLen) { + (new VFile2(dstDir, fn.substring(prefixLen))).delete(); + } + } + throw ex; + } + + logger.info("Updating manifest..."); + + VFile2 manifestFile = new VFile2(prefix, "manifest.json"); + String str = manifestFile.getAllChars(); + JSONArray arr = null; + if (str != null) { + try { + arr = (new JSONObject(str)).getJSONArray("resourcePacks"); + } catch (JSONException ex) { + } + } + + if (arr == null) { + arr = new JSONArray(); + } + + JSONObject manifestEntry = new JSONObject(); + manifestEntry.put("folder", folderName); + manifestEntry.put("name", name); + long timestamp = System.currentTimeMillis(); + manifestEntry.put("timestamp", timestamp); + JSONArray domainsListJson = new JSONArray(); + for (String str2 : domainsList) { + domainsListJson.put(str2); + } + manifestEntry.put("domains", domainsListJson); + arr.put(manifestEntry); + + manifestFile.setAllChars((new JSONObject()).put("resourcePacks", arr).toString()); + + logger.info("Done!"); + return new EaglerFolderResourcePack(folderName, name, prefix, domainsList, timestamp); + } + + public static boolean isSupported() { + return isSupported; + } + + public static void loadRemoteResourcePack(String url, String hash, Consumer cb, + Consumer ast, Runnable loading) { + if (!isSupported || !hash.matches("^[a-f0-9]{40}$")) { + logger.error("Invalid character in resource pack hash! (is it lowercase?)"); + cb.accept(null); + return; + } + final List lst = getFolderResourcePacks(SERVER_RESOURCE_PACKS); + for (int i = 0, l = lst.size(); i < l; ++i) { + EaglerFolderResourcePack rp = lst.get(i); + if (rp.resourcePackFile.equals(hash)) { + cb.accept(rp); + return; + } + } + PlatformRuntime.downloadRemoteURIByteArray(url, arr -> { + ast.accept(() -> { + if (arr == null) { + cb.accept(null); + return; + } + SHA1Digest digest = new SHA1Digest(); + digest.update(arr, 0, arr.length); + byte[] hashOut = new byte[20]; + digest.doFinal(hashOut, 0); + String hashOutStr = ArrayUtils.hexString(hashOut); + if (!hash.equals(hashOutStr)) { + logger.error("Downloaded resource pack hash does not equal expected resource pack hash! ({} != {})", + hashOutStr, hash); + cb.accept(null); + return; + } + if (lst.size() >= 5) { + lst.sort(Comparator.comparingLong(pack -> pack.timestamp)); + for (int i = 0; i < lst.size() - 5; i++) { + deleteResourcePack(SERVER_RESOURCE_PACKS, lst.get(i).resourcePackFile); + } + } + loading.run(); + try { + cb.accept(importResourcePack(hash, SERVER_RESOURCE_PACKS, arr)); + } catch (IOException ex) { + logger.error("Failed to load resource pack downloaded from server!"); + logger.error(ex); + cb.accept(null); + } + }); + }); + } + + public static void setSupported(boolean supported) { + isSupported = supported; + } + + private final String prefix; + + private final String displayName; + + private final Set domains; + + private final long timestamp; + + public EaglerFolderResourcePack(String resourcePackFileIn, String displayName, String prefix, Set domains, + long timestamp) { + super(resourcePackFileIn); + this.displayName = displayName; + this.prefix = prefix; + this.domains = domains; + this.timestamp = timestamp; + } + + public String getDisplayName() { + return displayName; + } + + @Override + protected InputStream getInputStreamByName(String var1) throws IOException { + return (new VFile2(prefix, this.resourcePackFile, var1)).getInputStream(); + } + + @Override + public Set getResourceDomains() { + return domains; + } + + public long getTimestamp() { + return timestamp; + } + + @Override + protected boolean hasResourceName(String var1) { + return (new VFile2(prefix, this.resourcePackFile, var1)).exists(); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFontRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFontRenderer.java index 0e0f561b..cd094e29 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFontRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerFontRenderer.java @@ -14,42 +14,72 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerFontRenderer extends FontRenderer { - private final int[] temporaryCodepointArray = new int[6553]; - public static FontRenderer createSupportedFontRenderer(GameSettings gameSettingsIn, ResourceLocation location, TextureManager textureManagerIn, boolean unicode) { - if(EaglercraftGPU.checkInstancingCapable()) { + if (EaglercraftGPU.checkInstancingCapable()) { return new EaglerFontRenderer(gameSettingsIn, location, textureManagerIn, unicode); - }else { + } else { return new FontRenderer(gameSettingsIn, location, textureManagerIn, unicode); } } + private final int[] temporaryCodepointArray = new int[6553]; + public EaglerFontRenderer(GameSettings gameSettingsIn, ResourceLocation location, TextureManager textureManagerIn, boolean unicode) { super(gameSettingsIn, location, textureManagerIn, unicode); } + private float appendCharToBuffer(int parInt1, int color, boolean boldStyle, boolean italicStyle) { + if (parInt1 == 32) { + return 4.0f; + } else { + int i = parInt1 % 16; + int j = parInt1 / 16; + float w = this.charWidth[parInt1]; + if (boldStyle) { + InstancedFontRenderer.appendBoldQuad((int) this.posX, (int) this.posY, i, j, color, italicStyle); + ++w; + } else { + InstancedFontRenderer.appendQuad((int) this.posX, (int) this.posY, i, j, color, italicStyle); + } + return w; + } + } + + private boolean decodeASCIICodepointsAndValidate(String str) { + for (int i = 0, l = str.length(); i < l; ++i) { + int j = FontMappingHelper.lookupChar(str.charAt(i), true); + if (j != -1) { + temporaryCodepointArray[i] = j; + } else { + return false; + } + } + return true; + } + public int drawString(String text, float x, float y, int color, boolean dropShadow) { if (text == null || text.length() == 0) { this.posX = x + (dropShadow ? 1 : 0); this.posY = y; } else { - if(this.unicodeFlag || !decodeASCIICodepointsAndValidate(text)) { + if (this.unicodeFlag || !decodeASCIICodepointsAndValidate(text)) { return super.drawString(text, x, y, color, dropShadow); } this.resetStyles(); @@ -69,10 +99,11 @@ public class EaglerFontRenderer extends FontRenderer { } protected void renderStringAtPos(String parString1, boolean parFlag) { - if(parString1 == null) return; - if(this.unicodeFlag || !decodeASCIICodepointsAndValidate(parString1)) { + if (parString1 == null) + return; + if (this.unicodeFlag || !decodeASCIICodepointsAndValidate(parString1)) { super.renderStringAtPos(parString1, parFlag); - }else { + } else { renderStringAtPos0(parString1, false); } } @@ -80,13 +111,13 @@ public class EaglerFontRenderer extends FontRenderer { private void renderStringAtPos0(String parString1, boolean parFlag) { renderEngine.bindTexture(locationFontTexture); InstancedFontRenderer.begin(); - + Tessellator tessellator = Tessellator.getInstance(); WorldRenderer worldrenderer = tessellator.getWorldRenderer(); worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); - + boolean hasStrike = false; - + for (int i = 0; i < parString1.length(); ++i) { char c0 = parString1.charAt(i); if (c0 == 167 && i + 1 < parString1.length()) { @@ -125,8 +156,9 @@ public class EaglerFontRenderer extends FontRenderer { ++i; } else { int j = temporaryCodepointArray[i]; - if(j > 255) continue; - + if (j > 255) + continue; + if (this.randomStyle && j != -1) { int k = this.getCharWidth(c0); char[] chars = FontRenderer.codepointLookup; @@ -163,8 +195,8 @@ public class EaglerFontRenderer extends FontRenderer { if (this.underlineStyle) { hasStrike = true; int l = this.underlineStyle ? -1 : 0; - worldrenderer.pos((double) (this.posX + (float) l), - (double) (this.posY + (float) this.FONT_HEIGHT), 0.0D).endVertex(); + worldrenderer.pos((double) (this.posX + (float) l), (double) (this.posY + (float) this.FONT_HEIGHT), + 0.0D).endVertex(); worldrenderer.pos((double) (this.posX + f), (double) (this.posY + (float) this.FONT_HEIGHT), 0.0D) .endVertex(); worldrenderer @@ -178,15 +210,15 @@ public class EaglerFontRenderer extends FontRenderer { this.posX += (float) ((int) f); } } - + float texScale = 0.0625f; - - if(!hasStrike) { + + if (!hasStrike) { worldrenderer.finishDrawing(); } - - if(parFlag) { - if(hasStrike) { + + if (parFlag) { + if (hasStrike) { GlStateManager.color(0.25f, 0.25f, 0.25f, 1.0f); GlStateManager.translate(1.0f, 1.0f, 0.0f); tessellator.draw(); @@ -194,49 +226,20 @@ public class EaglerFontRenderer extends FontRenderer { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); InstancedFontRenderer.render(8, 8, texScale, texScale, true); EaglercraftGPU.renderAgain(); - }else { + } else { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); InstancedFontRenderer.render(8, 8, texScale, texScale, true); } - }else { + } else { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - if(hasStrike) { + if (hasStrike) { tessellator.draw(); } InstancedFontRenderer.render(8, 8, texScale, texScale, false); } - - if(parFlag) { + + if (parFlag) { this.posX += 1.0f; } } - - private float appendCharToBuffer(int parInt1, int color, boolean boldStyle, boolean italicStyle) { - if (parInt1 == 32) { - return 4.0f; - }else { - int i = parInt1 % 16; - int j = parInt1 / 16; - float w = this.charWidth[parInt1]; - if(boldStyle) { - InstancedFontRenderer.appendBoldQuad((int)this.posX, (int)this.posY, i, j, color, italicStyle); - ++w; - }else { - InstancedFontRenderer.appendQuad((int)this.posX, (int)this.posY, i, j, color, italicStyle); - } - return w; - } - } - - private boolean decodeASCIICodepointsAndValidate(String str) { - for(int i = 0, l = str.length(); i < l; ++i) { - int j = FontMappingHelper.lookupChar(str.charAt(i), true); - if(j != -1) { - temporaryCodepointArray[i] = j; - }else { - return false; - } - } - return true; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerTextureAtlasSprite.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerTextureAtlasSprite.java index 125c6b6b..b99b5f00 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerTextureAtlasSprite.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EaglerTextureAtlasSprite.java @@ -25,14 +25,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,28 +42,21 @@ public class EaglerTextureAtlasSprite { private static final Logger logger = LogManager.getLogger("EaglerTextureAtlasSprite"); - protected final String iconName; - protected List framesTextureData = Lists.newArrayList(); - protected int[][] interpolatedFrameData; - protected AnimationMetadataSection animationMetadata; - protected boolean rotated; - protected int originX; - protected int originY; - protected int width; - protected int height; - protected float minU; - protected float maxU; - protected float minV; - protected float maxV; - protected int frameCounter; - protected int tickCounter; protected static String locationNameClock = "builtin/clock"; protected static String locationNameCompass = "builtin/compass"; - protected TextureAnimationCache animationCache = null; + protected static int[][] getFrameTextureData(int[][] data, int rows, int columns, int parInt3) { + int[][] aint = new int[data.length][]; - public EaglerTextureAtlasSprite(String spriteName) { - this.iconName = spriteName; + for (int i = 0; i < data.length; ++i) { + int[] aint1 = data[i]; + if (aint1 != null) { + aint[i] = new int[(rows >> i) * (columns >> i)]; + System.arraycopy(aint1, parInt3 * aint[i].length, aint[i], 0, aint[i].length); + } + } + + return aint; } public static EaglerTextureAtlasSprite makeAtlasSprite(ResourceLocation spriteResourceLocation) { @@ -79,16 +73,56 @@ public class EaglerTextureAtlasSprite { locationNameCompass = compassName; } - public void initSprite(int inX, int inY, int originInX, int originInY, boolean rotatedIn) { - this.originX = originInX; - this.originY = originInY; - this.rotated = rotatedIn; - float f = (float) (0.009999999776482582D / (double) inX); - float f1 = (float) (0.009999999776482582D / (double) inY); - this.minU = (float) originInX / (float) ((double) inX) + f; - this.maxU = (float) (originInX + this.width) / (float) ((double) inX) - f; - this.minV = (float) originInY / (float) inY + f1; - this.maxV = (float) (originInY + this.height) / (float) inY - f1; + protected final String iconName; + protected List framesTextureData = Lists.newArrayList(); + protected int[][] interpolatedFrameData; + protected AnimationMetadataSection animationMetadata; + protected boolean rotated; + protected int originX; + protected int originY; + protected int width; + protected int height; + protected float minU; + protected float maxU; + + protected float minV; + + protected float maxV; + + protected int frameCounter; + + protected int tickCounter; + + protected TextureAnimationCache animationCache = null; + + public EaglerTextureAtlasSprite(String spriteName) { + this.iconName = spriteName; + } + + protected void allocateFrameTextureData(int index) { + if (this.framesTextureData.size() <= index) { + for (int i = this.framesTextureData.size(); i <= index; ++i) { + this.framesTextureData.add((int[][]) null); + } + } + } + + public void bakeAnimationCache() { + if (animationMetadata != null) { + int mipLevels = framesTextureData.get(0).length; + if (animationCache == null) { + animationCache = new TextureAnimationCache(width, height, mipLevels); + } + animationCache.initialize(framesTextureData); + } + } + + public void clearFramesTextureData() { + this.framesTextureData.clear(); + if (this.animationCache != null) { + this.animationCache.free(); + this.animationCache = null; + } } public void copyFrom(EaglerTextureAtlasSprite atlasSpirit) { @@ -103,6 +137,89 @@ public class EaglerTextureAtlasSprite { this.maxV = atlasSpirit.maxV; } + public void generateMipmaps(int level) { + List arraylist = Lists.newArrayList(); + + for (int i = 0; i < this.framesTextureData.size(); ++i) { + final int[][] aint = this.framesTextureData.get(i); + if (aint != null) { + try { + arraylist.add(TextureUtil.generateMipmapData(level, this.width, aint)); + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Generating mipmaps for frame"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Frame being iterated"); + crashreportcategory.addCrashSection("Frame index", Integer.valueOf(i)); + crashreportcategory.addCrashSectionCallable("Frame sizes", new Callable() { + public String call() throws Exception { + StringBuilder stringbuilder = new StringBuilder(); + + for (int j = 0; j < aint.length; ++j) { + int[] aint1 = aint[j]; + if (stringbuilder.length() > 0) { + stringbuilder.append(", "); + } + + stringbuilder.append(aint1 == null ? "null" : Integer.valueOf(aint1.length)); + } + + return stringbuilder.toString(); + } + }); + throw new ReportedException(crashreport); + } + } + } + + this.setFramesTextureData(arraylist); + this.bakeAnimationCache(); + } + + public int getFrameCount() { + return this.framesTextureData.size(); + } + + public int[][] getFrameTextureData(int index) { + return (int[][]) this.framesTextureData.get(index); + } + + public int getIconHeight() { + return this.height; + } + + public String getIconName() { + return this.iconName; + } + + public int getIconWidth() { + return this.width; + } + + public float getInterpolatedU(double u) { + float f = this.maxU - this.minU; + return this.minU + f * (float) u / 16.0F; + } + + public float getInterpolatedV(double v) { + float f = this.maxV - this.minV; + return this.minV + f * ((float) v / 16.0F); + } + + public float getMaxU() { + return this.maxU; + } + + public float getMaxV() { + return this.maxV; + } + + public float getMinU() { + return this.minU; + } + + public float getMinV() { + return this.minV; + } + public int getOriginX() { return this.originX; } @@ -111,85 +228,20 @@ public class EaglerTextureAtlasSprite { return this.originY; } - public int getIconWidth() { - return this.width; + public boolean hasAnimationMetadata() { + return this.animationMetadata != null; } - public int getIconHeight() { - return this.height; - } - - public float getMinU() { - return this.minU; - } - - public float getMaxU() { - return this.maxU; - } - - public float getInterpolatedU(double u) { - float f = this.maxU - this.minU; - return this.minU + f * (float) u / 16.0F; - } - - public float getMinV() { - return this.minV; - } - - public float getMaxV() { - return this.maxV; - } - - public float getInterpolatedV(double v) { - float f = this.maxV - this.minV; - return this.minV + f * ((float) v / 16.0F); - } - - public String getIconName() { - return this.iconName; - } - - public void updateAnimation(IFramebufferGL[] copyColorFramebuffer) { - if(animationCache == null) { - throw new IllegalStateException("Animation cache for '" + this.iconName + "' was never baked!"); - } - ++this.tickCounter; - if (this.tickCounter >= this.animationMetadata.getFrameTimeSingle(this.frameCounter)) { - int i = this.animationMetadata.getFrameIndex(this.frameCounter); - int j = this.animationMetadata.getFrameCount() == 0 ? this.framesTextureData.size() - : this.animationMetadata.getFrameCount(); - this.frameCounter = (this.frameCounter + 1) % j; - this.tickCounter = 0; - int k = this.animationMetadata.getFrameIndex(this.frameCounter); - if (i != k && k >= 0 && k < this.framesTextureData.size()) { - animationCache.copyFrameLevelsToTex2D(k, this.originX, this.originY, this.width, this.height, copyColorFramebuffer); - } - } else if (this.animationMetadata.isInterpolate()) { - float f = 1.0f - (float) this.tickCounter / (float) this.animationMetadata.getFrameTimeSingle(this.frameCounter); - int i = this.animationMetadata.getFrameIndex(this.frameCounter); - int j = this.animationMetadata.getFrameCount() == 0 ? this.framesTextureData.size() - : this.animationMetadata.getFrameCount(); - int k = this.animationMetadata.getFrameIndex((this.frameCounter + 1) % j); - if (i != k && k >= 0 && k < this.framesTextureData.size()) { - animationCache.copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY, this.width, this.height, copyColorFramebuffer); - } - } - } - - public int[][] getFrameTextureData(int index) { - return (int[][]) this.framesTextureData.get(index); - } - - public int getFrameCount() { - return this.framesTextureData.size(); - } - - public void setIconWidth(int newWidth) { - this.width = newWidth; - } - - public void setIconHeight(int newHeight) { - this.height = newHeight; + public void initSprite(int inX, int inY, int originInX, int originInY, boolean rotatedIn) { + this.originX = originInX; + this.originY = originInY; + this.rotated = rotatedIn; + float f = (float) (0.009999999776482582D / (double) inX); + float f1 = (float) (0.009999999776482582D / (double) inY); + this.minU = (float) originInX / (float) ((double) inX) + f; + this.maxU = (float) (originInX + this.width) / (float) ((double) inX) - f; + this.minV = (float) originInY / (float) inY + f1; + this.maxV = (float) (originInY + this.height) / (float) inY - f1; } public void loadSprite(ImageData[] images, AnimationMetadataSection meta) throws IOException { @@ -256,89 +308,14 @@ public class EaglerTextureAtlasSprite { } - public void generateMipmaps(int level) { - List arraylist = Lists.newArrayList(); - - for (int i = 0; i < this.framesTextureData.size(); ++i) { - final int[][] aint = this.framesTextureData.get(i); - if (aint != null) { - try { - arraylist.add(TextureUtil.generateMipmapData(level, this.width, aint)); - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Generating mipmaps for frame"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Frame being iterated"); - crashreportcategory.addCrashSection("Frame index", Integer.valueOf(i)); - crashreportcategory.addCrashSectionCallable("Frame sizes", new Callable() { - public String call() throws Exception { - StringBuilder stringbuilder = new StringBuilder(); - - for (int j = 0; j < aint.length; ++j) { - int[] aint1 = aint[j]; - if (stringbuilder.length() > 0) { - stringbuilder.append(", "); - } - - stringbuilder.append(aint1 == null ? "null" : Integer.valueOf(aint1.length)); - } - - return stringbuilder.toString(); - } - }); - throw new ReportedException(crashreport); - } - } + public void loadSpritePBR(ImageData[][] imageDatas, AnimationMetadataSection animationmetadatasection, + boolean dontAnimateNormals, boolean dontAnimateMaterial) { + Throwable t = new UnsupportedOperationException("PBR is not enabled"); + try { + throw t; + } catch (Throwable tt) { + logger.error(t); } - - this.setFramesTextureData(arraylist); - this.bakeAnimationCache(); - } - - public void bakeAnimationCache() { - if(animationMetadata != null) { - int mipLevels = framesTextureData.get(0).length; - if(animationCache == null) { - animationCache = new TextureAnimationCache(width, height, mipLevels); - } - animationCache.initialize(framesTextureData); - } - } - - protected void allocateFrameTextureData(int index) { - if (this.framesTextureData.size() <= index) { - for (int i = this.framesTextureData.size(); i <= index; ++i) { - this.framesTextureData.add((int[][]) null); - } - } - } - - protected static int[][] getFrameTextureData(int[][] data, int rows, int columns, int parInt3) { - int[][] aint = new int[data.length][]; - - for (int i = 0; i < data.length; ++i) { - int[] aint1 = data[i]; - if (aint1 != null) { - aint[i] = new int[(rows >> i) * (columns >> i)]; - System.arraycopy(aint1, parInt3 * aint[i].length, aint[i], 0, aint[i].length); - } - } - - return aint; - } - - public void clearFramesTextureData() { - this.framesTextureData.clear(); - if(this.animationCache != null) { - this.animationCache.free(); - this.animationCache = null; - } - } - - public boolean hasAnimationMetadata() { - return this.animationMetadata != null; - } - - public void setFramesTextureData(List newFramesTextureData) { - this.framesTextureData = newFramesTextureData; } protected void resetSprite() { @@ -346,12 +323,24 @@ public class EaglerTextureAtlasSprite { this.setFramesTextureData(Lists.newArrayList()); this.frameCounter = 0; this.tickCounter = 0; - if(this.animationCache != null) { + if (this.animationCache != null) { this.animationCache.free(); this.animationCache = null; } } + public void setFramesTextureData(List newFramesTextureData) { + this.framesTextureData = newFramesTextureData; + } + + public void setIconHeight(int newHeight) { + this.height = newHeight; + } + + public void setIconWidth(int newWidth) { + this.width = newWidth; + } + public String toString() { return "TextureAtlasSprite{name=\'" + this.iconName + '\'' + ", frameCount=" + this.framesTextureData.size() + ", rotated=" + this.rotated + ", x=" + this.originX + ", y=" + this.originY + ", height=" @@ -359,21 +348,42 @@ public class EaglerTextureAtlasSprite { + this.minV + ", v1=" + this.maxV + '}'; } - public void loadSpritePBR(ImageData[][] imageDatas, AnimationMetadataSection animationmetadatasection, - boolean dontAnimateNormals, boolean dontAnimateMaterial) { - Throwable t = new UnsupportedOperationException("PBR is not enabled"); - try { - throw t; - }catch(Throwable tt) { - logger.error(t); + public void updateAnimation(IFramebufferGL[] copyColorFramebuffer) { + if (animationCache == null) { + throw new IllegalStateException("Animation cache for '" + this.iconName + "' was never baked!"); + } + ++this.tickCounter; + if (this.tickCounter >= this.animationMetadata.getFrameTimeSingle(this.frameCounter)) { + int i = this.animationMetadata.getFrameIndex(this.frameCounter); + int j = this.animationMetadata.getFrameCount() == 0 ? this.framesTextureData.size() + : this.animationMetadata.getFrameCount(); + this.frameCounter = (this.frameCounter + 1) % j; + this.tickCounter = 0; + int k = this.animationMetadata.getFrameIndex(this.frameCounter); + if (i != k && k >= 0 && k < this.framesTextureData.size()) { + animationCache.copyFrameLevelsToTex2D(k, this.originX, this.originY, this.width, this.height, + copyColorFramebuffer); + } + } else if (this.animationMetadata.isInterpolate()) { + float f = 1.0f + - (float) this.tickCounter / (float) this.animationMetadata.getFrameTimeSingle(this.frameCounter); + int i = this.animationMetadata.getFrameIndex(this.frameCounter); + int j = this.animationMetadata.getFrameCount() == 0 ? this.framesTextureData.size() + : this.animationMetadata.getFrameCount(); + int k = this.animationMetadata.getFrameIndex((this.frameCounter + 1) % j); + if (i != k && k >= 0 && k < this.framesTextureData.size()) { + animationCache.copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY, this.width, + this.height, copyColorFramebuffer); + } } } - public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, int materialTexOffset) { + public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, + int materialTexOffset) { Throwable t = new UnsupportedOperationException("PBR is not enabled"); try { throw t; - }catch(Throwable tt) { + } catch (Throwable tt) { logger.error(t); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EntityConstructor.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EntityConstructor.java index 212f2933..e6d48277 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EntityConstructor.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EntityConstructor.java @@ -5,14 +5,15 @@ import net.minecraft.world.World; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EnumInputEvent.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EnumInputEvent.java index 419e5366..567d6bc0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EnumInputEvent.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/EnumInputEvent.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.minecraft; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/FontMappingHelper.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/FontMappingHelper.java index 15e2553a..dddbff09 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/FontMappingHelper.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/FontMappingHelper.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.minecraft; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -18,7 +19,7 @@ package net.lax1dude.eaglercraft.v1_8.minecraft; public class FontMappingHelper { public static int lookupChar(char c, boolean incSel) { - switch(c) { + switch (c) { case 167: return incSel ? 256 : -1; case 192: diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiButtonWithStupidIcons.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiButtonWithStupidIcons.java index 80108669..14047619 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiButtonWithStupidIcons.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiButtonWithStupidIcons.java @@ -1,6 +1,7 @@ package net.lax1dude.eaglercraft.v1_8.minecraft; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; @@ -13,14 +14,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,10 +38,6 @@ public class GuiButtonWithStupidIcons extends GuiButton { super(buttonId, x, y, widthIn, heightIn, buttonText); } - public GuiButtonWithStupidIcons(int buttonId, int x, int y, String buttonText) { - super(buttonId, x, y, buttonText); - } - public GuiButtonWithStupidIcons(int buttonId, int x, int y, int widthIn, int heightIn, String buttonText, ResourceLocation leftIcon, float leftIconAspect, ResourceLocation rightIcon, float rightIconAspect) { super(buttonId, x, y, widthIn, heightIn, buttonText); @@ -49,6 +47,10 @@ public class GuiButtonWithStupidIcons extends GuiButton { this.rightIconAspect = rightIconAspect; } + public GuiButtonWithStupidIcons(int buttonId, int x, int y, String buttonText) { + super(buttonId, x, y, buttonText); + } + public GuiButtonWithStupidIcons(int buttonId, int x, int y, String buttonText, ResourceLocation leftIcon, float leftIconAspect, ResourceLocation rightIcon, float rightIconAspect) { super(buttonId, x, y, buttonText); @@ -58,24 +60,6 @@ public class GuiButtonWithStupidIcons extends GuiButton { this.rightIconAspect = rightIconAspect; } - public ResourceLocation getLeftIcon() { - return leftIcon; - } - - public ResourceLocation getRightIcon() { - return rightIcon; - } - - public void setLeftIcon(ResourceLocation leftIcon, float aspectRatio) { - this.leftIcon = leftIcon; - this.leftIconAspect = aspectRatio; - } - - public void setRightIcon(ResourceLocation rightIcon, float aspectRatio) { - this.rightIcon = rightIcon; - this.rightIconAspect = aspectRatio; - } - public void drawButton(Minecraft mc, int mouseX, int mouseY) { if (this.visible) { FontRenderer fontrenderer = mc.fontRendererObj; @@ -106,21 +90,23 @@ public class GuiButtonWithStupidIcons extends GuiButton { + (rightIcon != null ? (int) (16 * rightIconAspect) : 0); this.drawString(fontrenderer, this.displayString, this.xPosition + (this.width - strWidthAdj) / 2, this.yPosition + (this.height - 8) / 2, j); - if(leftIcon != null) { + if (leftIcon != null) { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); mc.getTextureManager().bindTexture(leftIcon); GlStateManager.pushMatrix(); - GlStateManager.translate(this.xPosition + (this.width - strWidthAdj) / 2 - 3 - 16 * leftIconAspect, this.yPosition + 2, 0.0f); + GlStateManager.translate(this.xPosition + (this.width - strWidthAdj) / 2 - 3 - 16 * leftIconAspect, + this.yPosition + 2, 0.0f); float f = 16.0f / 256.0f; GlStateManager.scale(f * leftIconAspect, f, f); this.drawTexturedModalRect(0, 0, 0, 0, 256, 256); GlStateManager.popMatrix(); } - if(rightIcon != null) { + if (rightIcon != null) { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); mc.getTextureManager().bindTexture(rightIcon); GlStateManager.pushMatrix(); - GlStateManager.translate(this.xPosition + (this.width - strWidthAdj) / 2 + strWidth + 3, this.yPosition + 2, 0.0f); + GlStateManager.translate(this.xPosition + (this.width - strWidthAdj) / 2 + strWidth + 3, + this.yPosition + 2, 0.0f); float f = 16.0f / 256.0f; GlStateManager.scale(f * rightIconAspect, f, f); this.drawTexturedModalRect(0, 0, 0, 0, 256, 256); @@ -129,4 +115,22 @@ public class GuiButtonWithStupidIcons extends GuiButton { } } + public ResourceLocation getLeftIcon() { + return leftIcon; + } + + public ResourceLocation getRightIcon() { + return rightIcon; + } + + public void setLeftIcon(ResourceLocation leftIcon, float aspectRatio) { + this.leftIcon = leftIcon; + this.leftIconAspect = aspectRatio; + } + + public void setRightIcon(ResourceLocation rightIcon, float aspectRatio) { + this.rightIcon = rightIcon; + this.rightIconAspect = aspectRatio; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenGenericErrorMessage.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenGenericErrorMessage.java index 6e8fa027..d5bd274a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenGenericErrorMessage.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenGenericErrorMessage.java @@ -9,14 +9,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,9 +34,10 @@ public class GuiScreenGenericErrorMessage extends GuiScreen { this.cont = cont; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("gui.done"))); + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + this.mc.displayGuiScreen(cont); + } } public void drawScreen(int par1, int par2, float par3) { @@ -45,10 +47,9 @@ public class GuiScreenGenericErrorMessage extends GuiScreen { super.drawScreen(par1, par2, par3); } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - this.mc.displayGuiScreen(cont); - } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("gui.done"))); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenVisualViewport.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenVisualViewport.java index 3a0e5aed..17301176 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenVisualViewport.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/GuiScreenVisualViewport.java @@ -8,14 +8,15 @@ import net.minecraft.client.gui.GuiScreen; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,31 +26,6 @@ public class GuiScreenVisualViewport extends GuiScreen { protected int offsetX; protected int offsetY; - @Override - public final void setWorldAndResolution(Minecraft mc, int width, int height) { - Display.wasVisualViewportResized(); // clear state - offsetX = Display.getVisualViewportX() * width / mc.displayWidth; - offsetY = Display.getVisualViewportY() * height / mc.displayHeight; - setWorldAndResolution0(mc, Display.getVisualViewportW() * width / mc.displayWidth, - Display.getVisualViewportH() * height / mc.displayHeight); - } - - protected void setWorldAndResolution0(Minecraft mc, int width, int height) { - super.setWorldAndResolution(mc, width, height); - } - - @Override - public final void updateScreen() { - if(Display.wasVisualViewportResized()) { - setWorldAndResolution(mc, mc.scaledResolution.getScaledWidth(), mc.scaledResolution.getScaledHeight()); - } - updateScreen0(); - } - - protected void updateScreen0() { - super.updateScreen(); - } - @Override public final void drawScreen(int i, int j, float var3) { i -= offsetX; @@ -75,6 +51,17 @@ public class GuiScreenVisualViewport extends GuiScreen { super.mouseClicked(parInt1, parInt2, parInt3); } + @Override + protected final void mouseClickMove(int var1, int var2, int var3, long var4) { + var1 -= offsetX; + var2 -= offsetY; + mouseClickMove0(var1, var2, var3, var4); + } + + protected void mouseClickMove0(int var1, int var2, int var3, long var4) { + super.mouseClickMove(var1, var2, var3, var4); + } + @Override protected final void mouseReleased(int i, int j, int k) { i -= offsetX; @@ -87,14 +74,16 @@ public class GuiScreenVisualViewport extends GuiScreen { } @Override - protected final void mouseClickMove(int var1, int var2, int var3, long var4) { - var1 -= offsetX; - var2 -= offsetY; - mouseClickMove0(var1, var2, var3, var4); + public final void setWorldAndResolution(Minecraft mc, int width, int height) { + Display.wasVisualViewportResized(); // clear state + offsetX = Display.getVisualViewportX() * width / mc.displayWidth; + offsetY = Display.getVisualViewportY() * height / mc.displayHeight; + setWorldAndResolution0(mc, Display.getVisualViewportW() * width / mc.displayWidth, + Display.getVisualViewportH() * height / mc.displayHeight); } - protected void mouseClickMove0(int var1, int var2, int var3, long var4) { - super.mouseClickMove(var1, var2, var3, var4); + protected void setWorldAndResolution0(Minecraft mc, int width, int height) { + super.setWorldAndResolution(mc, width, height); } @Override @@ -141,4 +130,16 @@ public class GuiScreenVisualViewport extends GuiScreen { super.touchTapped(parInt1, parInt2, parInt3); } + @Override + public final void updateScreen() { + if (Display.wasVisualViewportResized()) { + setWorldAndResolution(mc, mc.scaledResolution.getScaledWidth(), mc.scaledResolution.getScaledHeight()); + } + updateScreen0(); + } + + protected void updateScreen0() { + super.updateScreen(); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/IAcceleratedParticleEngine.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/IAcceleratedParticleEngine.java index 33e21a70..59a68054 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/IAcceleratedParticleEngine.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/IAcceleratedParticleEngine.java @@ -5,14 +5,15 @@ import net.minecraft.entity.Entity; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,16 +24,16 @@ public interface IAcceleratedParticleEngine { void draw(float texCoordWidth, float texCoordHeight); - void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, - int lightMapData, int texSize, float particleSize, float r, float g, float b, float a); + void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, int texSize, + float particleSize, float r, float g, float b, float a); - void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, - int lightMapData, int texSize, float particleSize, int rgba); + void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, int texSize, + float particleSize, int rgba); - void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, - int lightMapData, int texSize, float particleSize, float r, float g, float b, float a); + void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, int lightMapData, + int texSize, float particleSize, float r, float g, float b, float a); - void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, - int lightMapData, int texSize, float particleSize, int rgba); + void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, int lightMapData, + int texSize, float particleSize, int rgba); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/TextureAnimationCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/TextureAnimationCache.java index b20d3fc0..05bba76c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/TextureAnimationCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/minecraft/TextureAnimationCache.java @@ -1,7 +1,19 @@ package net.lax1dude.eaglercraft.v1_8.minecraft; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; import java.util.List; @@ -18,109 +30,56 @@ import net.minecraft.client.renderer.GLAllocation; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TextureAnimationCache { + public static final int _GL_FRAMEBUFFER = 0x8D40; public final int width; public final int height; + public final int mipLevels; private int frameCount = 1; private int[] cacheTextures = null; - public static final int _GL_FRAMEBUFFER = 0x8D40; - public TextureAnimationCache(int width, int height, int mipLevels) { this.width = width; this.height = height; this.mipLevels = mipLevels; } - public void initialize(List frames) { - if(cacheTextures == null) { - cacheTextures = new int[mipLevels]; - for(int i = 0; i < cacheTextures.length; ++i) { - cacheTextures[i] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(cacheTextures[i]); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } - } - - frameCount = frames.size(); - IntBuffer pixels = GLAllocation.createDirectIntBuffer(width * height * frameCount); - - try { - for(int i = 0; i < mipLevels; ++i) { - pixels.clear(); - - int lw = width >> i; - int lh = height >> i; - int tileLength = lw * lh; - - for(int j = 0; j < frameCount; ++j) { - int[][] frame = frames.get(j); - if(frame.length <= i) { - throw new IllegalArgumentException("Frame #" + j + " only has " + frame.length + " mipmap levels! (" + mipLevels + " were expected)"); - } - - int[] frameLevel = frame[i]; - if(frameLevel.length != tileLength) { - throw new IllegalArgumentException("Frame #" + j + " level " + i + " is " + frameLevel.length + " pixels large! (" + tileLength + " expected)"); - } - - pixels.put(frameLevel); - } - - pixels.flip(); - - GlStateManager.bindTexture(cacheTextures[i]); - EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, lw, lh * frameCount, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - } - }finally { - EagRuntime.freeIntBuffer(pixels); - } - } - - public void free() { - if(cacheTextures != null) { - for(int i = 0; i < cacheTextures.length; ++i) { - GlStateManager.deleteTexture(cacheTextures[i]); - } - cacheTextures = null; - } - } - - public void copyFrameLevelsToTex2D(int animationFrame, int dx, int dy, int w, int h, IFramebufferGL[] dstFramebuffers) { + public void copyFrameLevelsToTex2D(int animationFrame, int dx, int dy, int w, int h, + IFramebufferGL[] dstFramebuffers) { copyFrameLevelsToTex2D(animationFrame, mipLevels, dx, dy, w, h, dstFramebuffers); } /** - * WARNING: call _wglBindFramebuffer(_GL_FRAMEBUFFER, null); when complete + * WARNING: call _wglBindFramebuffer(_GL_FRAMEBUFFER, null); when + * complete */ - public void copyFrameLevelsToTex2D(int animationFrame, int levels, int dx, int dy, int w, int h, IFramebufferGL[] dstFramebuffers) { - for(int i = 0; i < levels; ++i) { + public void copyFrameLevelsToTex2D(int animationFrame, int levels, int dx, int dy, int w, int h, + IFramebufferGL[] dstFramebuffers) { + for (int i = 0; i < levels; ++i) { _wglBindFramebuffer(_GL_FRAMEBUFFER, dstFramebuffers[i]); copyFrameToTex2D(animationFrame, i, dx >> i, dy >> i, w >> i, h >> i); } } public void copyFrameToTex2D(int animationFrame, int level, int dx, int dy, int w, int h) { - if(cacheTextures == null) { + if (cacheTextures == null) { throw new IllegalStateException("Cannot copy from uninitialized TextureAnimationCache"); } GlStateManager.disableBlend(); @@ -132,56 +91,119 @@ public class TextureAnimationCache { public void copyInterpolatedFrameLevelsToTex2D(int animationFrameFrom, int animationFrameTo, float factor, int dx, int dy, int w, int h, IFramebufferGL[] dstFramebuffers) { - copyInterpolatedFrameLevelsToTex2D(animationFrameFrom, animationFrameTo, factor, mipLevels, dx, dy, w, h, dstFramebuffers); + copyInterpolatedFrameLevelsToTex2D(animationFrameFrom, animationFrameTo, factor, mipLevels, dx, dy, w, h, + dstFramebuffers); } /** - * WARNING: call _wglBindFramebuffer(_GL_FRAMEBUFFER, null); when complete + * WARNING: call _wglBindFramebuffer(_GL_FRAMEBUFFER, null); when + * complete */ public void copyInterpolatedFrameLevelsToTex2D(int animationFrameFrom, int animationFrameTo, float factor, int levels, int dx, int dy, int w, int h, IFramebufferGL[] dstFramebuffers) { - for(int i = 0; i < levels; ++i) { + for (int i = 0; i < levels; ++i) { _wglBindFramebuffer(_GL_FRAMEBUFFER, dstFramebuffers[i]); - copyInterpolatedFrameToTex2D(animationFrameFrom, animationFrameTo, factor, i, dx >> i, dy >> i, w >> i, h >> i); + copyInterpolatedFrameToTex2D(animationFrameFrom, animationFrameTo, factor, i, dx >> i, dy >> i, w >> i, + h >> i); } } public void copyInterpolatedFrameToTex2D(int animationFrameFrom, int animationFrameTo, float factor, int level, int dx, int dy, int w, int h) { - if(cacheTextures == null) { + if (cacheTextures == null) { throw new IllegalStateException("Cannot copy from uninitialized TextureAnimationCache"); } - + GlStateManager.viewport(dx, dy, w, h); GlStateManager.bindTexture(cacheTextures[level]); GlStateManager.disableBlend(); - + Matrix3f matrix = new Matrix3f(); matrix.m11 = 1.0f / frameCount; matrix.m21 = matrix.m11 * animationFrameFrom; - + SpriteLevelMixer.setMatrix3f(matrix); SpriteLevelMixer.setBlendColor(factor, factor, factor, factor); SpriteLevelMixer.setBiasColor(0.0f, 0.0f, 0.0f, 0.0f); - + SpriteLevelMixer.drawSprite(0); - + matrix.m21 = matrix.m11 * animationFrameTo; SpriteLevelMixer.setMatrix3f(matrix); float fac1 = 1.0f - factor; SpriteLevelMixer.setBlendColor(fac1, fac1, fac1, fac1); - + GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_ONE, GL_ONE); - + SpriteLevelMixer.drawSprite(0); - + GlStateManager.disableBlend(); GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } + public void free() { + if (cacheTextures != null) { + for (int i = 0; i < cacheTextures.length; ++i) { + GlStateManager.deleteTexture(cacheTextures[i]); + } + cacheTextures = null; + } + } + public int getFrameCount() { return frameCount; } + public void initialize(List frames) { + if (cacheTextures == null) { + cacheTextures = new int[mipLevels]; + for (int i = 0; i < cacheTextures.length; ++i) { + cacheTextures[i] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(cacheTextures[i]); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } + } + + frameCount = frames.size(); + IntBuffer pixels = GLAllocation.createDirectIntBuffer(width * height * frameCount); + + try { + for (int i = 0; i < mipLevels; ++i) { + pixels.clear(); + + int lw = width >> i; + int lh = height >> i; + int tileLength = lw * lh; + + for (int j = 0; j < frameCount; ++j) { + int[][] frame = frames.get(j); + if (frame.length <= i) { + throw new IllegalArgumentException("Frame #" + j + " only has " + frame.length + + " mipmap levels! (" + mipLevels + " were expected)"); + } + + int[] frameLevel = frame[i]; + if (frameLevel.length != tileLength) { + throw new IllegalArgumentException("Frame #" + j + " level " + i + " is " + frameLevel.length + + " pixels large! (" + tileLength + " expected)"); + } + + pixels.put(frameLevel); + } + + pixels.flip(); + + GlStateManager.bindTexture(cacheTextures[i]); + EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, lw, lh * frameCount, 0, GL_RGBA, + GL_UNSIGNED_BYTE, pixels); + } + } finally { + EagRuntime.freeIntBuffer(pixels); + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/GameProfile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/GameProfile.java index 7d45576f..5b17dd32 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/GameProfile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/GameProfile.java @@ -1,30 +1,31 @@ package net.lax1dude.eaglercraft.v1_8.mojang.authlib; -import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; - import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import com.google.common.collect.Multimap; import com.google.common.collect.MultimapBuilder; +import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; + /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GameProfile { - + private final EaglercraftUUID id; private final String name; @@ -45,18 +46,6 @@ public class GameProfile { this.properties = properties; } - public EaglercraftUUID getId() { - return this.id; - } - - public String getName() { - return this.name; - } - - public boolean isComplete() { - return (this.id != null && StringUtils.isNotBlank(getName())); - } - public boolean equals(Object o) { if (this == o) return true; @@ -70,19 +59,12 @@ public class GameProfile { return true; } - public int hashCode() { - int result = (this.id != null) ? this.id.hashCode() : 0; - result = 31 * result + ((this.name != null) ? this.name.hashCode() : 0); - return result; + public EaglercraftUUID getId() { + return this.id; } - public String toString() { - return (new ToStringBuilder(this)).append("id", this.id).append("name", this.name) - .append("legacy", false).toString(); - } - - public boolean isLegacy() { - return false; + public String getName() { + return this.name; } public Multimap getProperties() { @@ -90,9 +72,28 @@ public class GameProfile { } public TexturesProperty getTextures() { - if(textures == null) { + if (textures == null) { textures = TexturesProperty.parseProfile(this); } return textures; } + + public int hashCode() { + int result = (this.id != null) ? this.id.hashCode() : 0; + result = 31 * result + ((this.name != null) ? this.name.hashCode() : 0); + return result; + } + + public boolean isComplete() { + return (this.id != null && StringUtils.isNotBlank(getName())); + } + + public boolean isLegacy() { + return false; + } + + public String toString() { + return (new ToStringBuilder(this)).append("id", this.id).append("name", this.name).append("legacy", false) + .toString(); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/Property.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/Property.java index 81de8eb3..f89a10f9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/Property.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/Property.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.mojang.authlib; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,14 +35,14 @@ public class Property { return this.name; } - public String getValue() { - return this.value; - } - public String getSignature() { return this.signature; } + public String getValue() { + return this.value; + } + public boolean hasSignature() { return this.signature != null; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/TexturesProperty.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/TexturesProperty.java index bff12a8a..7e719ba1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/TexturesProperty.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/TexturesProperty.java @@ -10,52 +10,41 @@ import net.lax1dude.eaglercraft.v1_8.Base64; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TexturesProperty { - public final String skin; - public final String model; - public final String cape; - public final boolean eaglerPlayer; - public static final TexturesProperty defaultNull = new TexturesProperty(null, "default", null, false); - private TexturesProperty(String skin, String model, String cape, boolean eaglerPlayer) { - this.skin = skin; - this.model = model; - this.cape = cape; - this.eaglerPlayer = eaglerPlayer; - } - public static TexturesProperty parseProfile(GameProfile profile) { Collection etr = profile.getProperties().get("textures"); - if(!etr.isEmpty()) { + if (!etr.isEmpty()) { Property prop = etr.iterator().next(); String str; try { str = ArrayUtils.asciiString(Base64.decodeBase64(prop.getValue())); - }catch(Throwable t) { + } catch (Throwable t) { return defaultNull; } boolean isEagler = false; etr = profile.getProperties().get("isEaglerPlayer"); - if(!etr.isEmpty()) { + if (!etr.isEmpty()) { prop = etr.iterator().next(); isEagler = prop.getValue().equalsIgnoreCase("true"); } return parseTextures(str, isEagler); - }else { + } else { return defaultNull; } } @@ -67,23 +56,38 @@ public class TexturesProperty { try { JSONObject json = new JSONObject(string); json = json.optJSONObject("textures"); - if(json != null) { + if (json != null) { JSONObject skinObj = json.optJSONObject("SKIN"); - if(skinObj != null) { + if (skinObj != null) { skin = skinObj.optString("url"); JSONObject meta = skinObj.optJSONObject("metadata"); - if(meta != null) { + if (meta != null) { model = meta.optString("model", model); } } JSONObject capeObj = json.optJSONObject("CAPE"); - if(capeObj != null) { + if (capeObj != null) { cape = capeObj.optString("url"); } } - }catch(Throwable t) { + } catch (Throwable t) { } return new TexturesProperty(skin, model, cape, isEagler); } + public final String skin; + + public final String model; + + public final String cape; + + public final boolean eaglerPlayer; + + private TexturesProperty(String skin, String model, String cape, boolean eaglerPlayer) { + this.skin = skin; + this.model = model; + this.cape = cape; + this.eaglerPlayer = eaglerPlayer; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/UUIDTypeAdapter.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/UUIDTypeAdapter.java index 50abb69d..8cf615ec 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/UUIDTypeAdapter.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/mojang/authlib/UUIDTypeAdapter.java @@ -5,24 +5,26 @@ import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class UUIDTypeAdapter { + public static EaglercraftUUID fromString(String input) { + return EaglercraftUUID + .fromString(input.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); + } + public static String fromUUID(EaglercraftUUID value) { return value.toString().replace("-", ""); } - - public static EaglercraftUUID fromString(String input) { - return EaglercraftUUID.fromString(input.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/AbstractByteBuf.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/AbstractByteBuf.java index 65a691ab..6de72f16 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/AbstractByteBuf.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/AbstractByteBuf.java @@ -15,6 +15,8 @@ */ package net.lax1dude.eaglercraft.v1_8.netty; +import static net.lax1dude.eaglercraft.v1_8.netty.MathUtil.isOutOfBounds; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -22,7 +24,6 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; -import static net.lax1dude.eaglercraft.v1_8.netty.MathUtil.isOutOfBounds; import net.lax1dude.eaglercraft.v1_8.HString; /** @@ -46,55 +47,145 @@ public abstract class AbstractByteBuf extends ByteBuf { this.maxCapacity = maxCapacity; } - @Override - public int maxCapacity() { - return maxCapacity; - } + protected abstract byte _getByte(int index); - protected final void maxCapacity(int maxCapacity) { - this.maxCapacity = maxCapacity; - } + protected abstract int _getInt(int index); - @Override - public int readerIndex() { - return readerIndex; - } + protected abstract long _getLong(int index); - @Override - public ByteBuf readerIndex(int readerIndex) { - if (readerIndex < 0 || readerIndex > writerIndex) { - throw new IndexOutOfBoundsException(HString.format( - "readerIndex: %d (expected: 0 <= readerIndex <= writerIndex(%d))", readerIndex, writerIndex)); + protected abstract short _getShort(int index); + + protected abstract int _getUnsignedMedium(int index); + + protected abstract void _setByte(int index, int value); + + protected abstract void _setInt(int index, int value); + + protected abstract void _setLong(int index, long value); + + protected abstract void _setMedium(int index, int value); + + protected abstract void _setShort(int index, int value); + + protected final void adjustMarkers(int decrement) { + int markedReaderIndex = this.markedReaderIndex; + if (markedReaderIndex <= decrement) { + this.markedReaderIndex = 0; + int markedWriterIndex = this.markedWriterIndex; + if (markedWriterIndex <= decrement) { + this.markedWriterIndex = 0; + } else { + this.markedWriterIndex = markedWriterIndex - decrement; + } + } else { + this.markedReaderIndex = markedReaderIndex - decrement; + markedWriterIndex -= decrement; } - this.readerIndex = readerIndex; - return this; } @Override - public int writerIndex() { - return writerIndex; + public int bytesBefore(byte value) { + return bytesBefore(readerIndex(), readableBytes(), value); } @Override - public ByteBuf writerIndex(int writerIndex) { - if (writerIndex < readerIndex || writerIndex > capacity()) { + public int bytesBefore(int length, byte value) { + checkReadableBytes(length); + return bytesBefore(readerIndex(), length, value); + } + + @Override + public int bytesBefore(int index, int length, byte value) { + int endIndex = indexOf(index, index + length, value); + if (endIndex < 0) { + return -1; + } + return endIndex - index; + } + + private int calculateNewCapacity(int minNewCapacity) { + final int maxCapacity = this.maxCapacity; + final int threshold = 1048576 * 4; // 4 MiB page + + if (minNewCapacity == threshold) { + return threshold; + } + + // If over threshold, do not double but just increase by threshold. + if (minNewCapacity > threshold) { + int newCapacity = minNewCapacity / threshold * threshold; + if (newCapacity > maxCapacity - threshold) { + newCapacity = maxCapacity; + } else { + newCapacity += threshold; + } + return newCapacity; + } + + // Not over threshold. Double up to 4 MiB, starting from 64. + int newCapacity = 64; + while (newCapacity < minNewCapacity) { + newCapacity <<= 1; + } + + return Math.min(newCapacity, maxCapacity); + } + + protected final void checkDstIndex(int index, int length, int dstIndex, int dstCapacity) { + checkIndex(index, length); + if (isOutOfBounds(dstIndex, length, dstCapacity)) { throw new IndexOutOfBoundsException( - HString.format("writerIndex: %d (expected: readerIndex(%d) <= writerIndex <= capacity(%d))", - writerIndex, readerIndex, capacity())); + HString.format("dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dstCapacity)); } - this.writerIndex = writerIndex; - return this; } - @Override - public ByteBuf setIndex(int readerIndex, int writerIndex) { - if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { - throw new IndexOutOfBoundsException(HString.format( - "readerIndex: %d, writerIndex: %d (expected: 0 <= readerIndex <= writerIndex <= capacity(%d))", - readerIndex, writerIndex, capacity())); + protected final void checkIndex(int index) { + checkIndex(index, 1); + } + + protected final void checkIndex(int index, int fieldLength) { + checkIndex0(index, fieldLength); + } + + final void checkIndex0(int index, int fieldLength) { + if (isOutOfBounds(index, fieldLength, capacity())) { + throw new IndexOutOfBoundsException( + HString.format("index: %d, length: %d (expected: range(0, %d))", index, fieldLength, capacity())); + } + } + + protected final void checkNewCapacity(int newCapacity) { + if (newCapacity < 0 || newCapacity > maxCapacity()) { + throw new IllegalArgumentException("newCapacity: " + newCapacity + " (expected: 0-" + maxCapacity() + ')'); + } + } + + /** + * Throws an {@link IndexOutOfBoundsException} if the current + * {@linkplain #readableBytes() readable bytes} of this buffer is less than the + * specified value. + */ + protected final void checkReadableBytes(int minimumReadableBytes) { + if (minimumReadableBytes < 0) { + throw new IllegalArgumentException("minimumReadableBytes: " + minimumReadableBytes + " (expected: >= 0)"); + } + checkReadableBytes0(minimumReadableBytes); + } + + private void checkReadableBytes0(int minimumReadableBytes) { + if (readerIndex > writerIndex - minimumReadableBytes) { + throw new IndexOutOfBoundsException( + HString.format("readerIndex(%d) + length(%d) exceeds writerIndex(%d): %s", readerIndex, + minimumReadableBytes, writerIndex, this)); + } + } + + protected final void checkSrcIndex(int index, int length, int srcIndex, int srcCapacity) { + checkIndex(index, length); + if (isOutOfBounds(srcIndex, length, srcCapacity)) { + throw new IndexOutOfBoundsException( + HString.format("srcIndex: %d, length: %d (expected: range(0, %d))", srcIndex, length, srcCapacity)); } - setIndex0(readerIndex, writerIndex); - return this; } @Override @@ -104,62 +195,17 @@ public abstract class AbstractByteBuf extends ByteBuf { } @Override - public boolean isReadable() { - return writerIndex > readerIndex; + public int compareTo(ByteBuf that) { + return ByteBufUtil.compare(this, that); } @Override - public boolean isReadable(int numBytes) { - return writerIndex - readerIndex >= numBytes; + public ByteBuf copy() { + return copy(readerIndex, readableBytes()); } - @Override - public boolean isWritable() { - return capacity() > writerIndex; - } - - @Override - public boolean isWritable(int numBytes) { - return capacity() - writerIndex >= numBytes; - } - - @Override - public int readableBytes() { - return writerIndex - readerIndex; - } - - @Override - public int writableBytes() { - return capacity() - writerIndex; - } - - @Override - public int maxWritableBytes() { - return maxCapacity() - writerIndex; - } - - @Override - public ByteBuf markReaderIndex() { - markedReaderIndex = readerIndex; - return this; - } - - @Override - public ByteBuf resetReaderIndex() { - readerIndex(markedReaderIndex); - return this; - } - - @Override - public ByteBuf markWriterIndex() { - markedWriterIndex = writerIndex; - return this; - } - - @Override - public ByteBuf resetWriterIndex() { - writerIndex = markedWriterIndex; - return this; + final void discardMarks() { + markedReaderIndex = markedWriterIndex = 0; } @Override @@ -201,22 +247,6 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } - protected final void adjustMarkers(int decrement) { - int markedReaderIndex = this.markedReaderIndex; - if (markedReaderIndex <= decrement) { - this.markedReaderIndex = 0; - int markedWriterIndex = this.markedWriterIndex; - if (markedWriterIndex <= decrement) { - this.markedWriterIndex = 0; - } else { - this.markedWriterIndex = markedWriterIndex - decrement; - } - } else { - this.markedReaderIndex = markedReaderIndex - decrement; - markedWriterIndex -= decrement; - } - } - @Override public ByteBuf ensureWritable(int minWritableBytes) { if (minWritableBytes < 0) { @@ -227,24 +257,6 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } - final void ensureWritable0(int minWritableBytes) { - if (minWritableBytes <= writableBytes()) { - return; - } - - if (minWritableBytes > maxCapacity - writerIndex) { - throw new IndexOutOfBoundsException( - HString.format("writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s", writerIndex, - minWritableBytes, maxCapacity, this)); - } - - // Normalize the current capacity to the power of 2. - int newCapacity = calculateNewCapacity(writerIndex + minWritableBytes); - - // Adjust to the new capacity. - capacity(newCapacity); - } - @Override public int ensureWritable(int minWritableBytes, boolean force) { if (minWritableBytes < 0) { @@ -275,139 +287,44 @@ public abstract class AbstractByteBuf extends ByteBuf { return 2; } - private int calculateNewCapacity(int minNewCapacity) { - final int maxCapacity = this.maxCapacity; - final int threshold = 1048576 * 4; // 4 MiB page - - if (minNewCapacity == threshold) { - return threshold; + final void ensureWritable0(int minWritableBytes) { + if (minWritableBytes <= writableBytes()) { + return; } - // If over threshold, do not double but just increase by threshold. - if (minNewCapacity > threshold) { - int newCapacity = minNewCapacity / threshold * threshold; - if (newCapacity > maxCapacity - threshold) { - newCapacity = maxCapacity; - } else { - newCapacity += threshold; - } - return newCapacity; + if (minWritableBytes > maxCapacity - writerIndex) { + throw new IndexOutOfBoundsException( + HString.format("writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s", writerIndex, + minWritableBytes, maxCapacity, this)); } - // Not over threshold. Double up to 4 MiB, starting from 64. - int newCapacity = 64; - while (newCapacity < minNewCapacity) { - newCapacity <<= 1; - } + // Normalize the current capacity to the power of 2. + int newCapacity = calculateNewCapacity(writerIndex + minWritableBytes); - return Math.min(newCapacity, maxCapacity); + // Adjust to the new capacity. + capacity(newCapacity); } @Override - public ByteBuf order(ByteOrder endianness) { - if (endianness == null) { - throw new NullPointerException("endianness"); + public boolean equals(Object o) { + if (this == o) { + return true; } - if (endianness == order()) { - return this; + if (o instanceof ByteBuf) { + return ByteBufUtil.equals(this, (ByteBuf) o); } - - SwappedByteBuf swappedBuf = this.swappedBuf; - if (swappedBuf == null) { - this.swappedBuf = swappedBuf = newSwappedByteBuf(); - } - return swappedBuf; + return false; } - /** - * Creates a new {@link SwappedByteBuf} for this {@link ByteBuf} instance. - */ - protected SwappedByteBuf newSwappedByteBuf() { - return new SwappedByteBuf(this); - } - - @Override - public byte getByte(int index) { - checkIndex(index); - return _getByte(index); - } - - protected abstract byte _getByte(int index); - @Override public boolean getBoolean(int index) { return getByte(index) != 0; } @Override - public short getUnsignedByte(int index) { - return (short) (getByte(index) & 0xFF); - } - - @Override - public short getShort(int index) { - checkIndex(index, 2); - return _getShort(index); - } - - protected abstract short _getShort(int index); - - @Override - public int getUnsignedShort(int index) { - return getShort(index) & 0xFFFF; - } - - @Override - public int getUnsignedMedium(int index) { - checkIndex(index, 3); - return _getUnsignedMedium(index); - } - - protected abstract int _getUnsignedMedium(int index); - - @Override - public int getMedium(int index) { - int value = getUnsignedMedium(index); - if ((value & 0x800000) != 0) { - value |= 0xff000000; - } - return value; - } - - @Override - public int getInt(int index) { - checkIndex(index, 4); - return _getInt(index); - } - - protected abstract int _getInt(int index); - - @Override - public long getUnsignedInt(int index) { - return getInt(index) & 0xFFFFFFFFL; - } - - @Override - public long getLong(int index) { - checkIndex(index, 8); - return _getLong(index); - } - - protected abstract long _getLong(int index); - - @Override - public char getChar(int index) { - return (char) getShort(index); - } - - @Override - public float getFloat(int index) { - return Float.intBitsToFloat(getInt(index)); - } - - @Override - public double getDouble(int index) { - return Double.longBitsToDouble(getLong(index)); + public byte getByte(int index) { + checkIndex(index); + return _getByte(index); } @Override @@ -430,133 +347,165 @@ public abstract class AbstractByteBuf extends ByteBuf { } @Override - public ByteBuf setByte(int index, int value) { - checkIndex(index); - _setByte(index, value); - return this; - } - - protected abstract void _setByte(int index, int value); - - @Override - public ByteBuf setBoolean(int index, boolean value) { - setByte(index, value ? 1 : 0); - return this; + public char getChar(int index) { + return (char) getShort(index); } @Override - public ByteBuf setShort(int index, int value) { - checkIndex(index, 2); - _setShort(index, value); - return this; - } - - protected abstract void _setShort(int index, int value); - - @Override - public ByteBuf setChar(int index, int value) { - setShort(index, value); - return this; + public double getDouble(int index) { + return Double.longBitsToDouble(getLong(index)); } @Override - public ByteBuf setMedium(int index, int value) { - checkIndex(index, 3); - _setMedium(index, value); - return this; + public float getFloat(int index) { + return Float.intBitsToFloat(getInt(index)); } - protected abstract void _setMedium(int index, int value); - @Override - public ByteBuf setInt(int index, int value) { + public int getInt(int index) { checkIndex(index, 4); - _setInt(index, value); - return this; - } - - protected abstract void _setInt(int index, int value); - - @Override - public ByteBuf setFloat(int index, float value) { - setInt(index, Float.floatToRawIntBits(value)); - return this; + return _getInt(index); } @Override - public ByteBuf setLong(int index, long value) { + public long getLong(int index) { checkIndex(index, 8); - _setLong(index, value); - return this; - } - - protected abstract void _setLong(int index, long value); - - @Override - public ByteBuf setDouble(int index, double value) { - setLong(index, Double.doubleToRawLongBits(value)); - return this; + return _getLong(index); } @Override - public ByteBuf setBytes(int index, byte[] src) { - setBytes(index, src, 0, src.length); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src) { - setBytes(index, src, src.readableBytes()); - return this; - } - - @Override - public ByteBuf setBytes(int index, ByteBuf src, int length) { - checkIndex(index, length); - if (src == null) { - throw new NullPointerException("src"); - } - if (length > src.readableBytes()) { - throw new IndexOutOfBoundsException(HString.format( - "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); + public int getMedium(int index) { + int value = getUnsignedMedium(index); + if ((value & 0x800000) != 0) { + value |= 0xff000000; } + return value; + } - setBytes(index, src, src.readerIndex(), length); - src.readerIndex(src.readerIndex() + length); + @Override + public short getShort(int index) { + checkIndex(index, 2); + return _getShort(index); + } + + @Override + public short getUnsignedByte(int index) { + return (short) (getByte(index) & 0xFF); + } + + @Override + public long getUnsignedInt(int index) { + return getInt(index) & 0xFFFFFFFFL; + } + + @Override + public int getUnsignedMedium(int index) { + checkIndex(index, 3); + return _getUnsignedMedium(index); + } + + @Override + public int getUnsignedShort(int index) { + return getShort(index) & 0xFFFF; + } + + @Override + public int hashCode() { + return ByteBufUtil.hashCode(this); + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + return ByteBufUtil.indexOf(this, fromIndex, toIndex, value); + } + + @Override + public boolean isReadable() { + return writerIndex > readerIndex; + } + + @Override + public boolean isReadable(int numBytes) { + return writerIndex - readerIndex >= numBytes; + } + + @Override + public boolean isWritable() { + return capacity() > writerIndex; + } + + @Override + public boolean isWritable(int numBytes) { + return capacity() - writerIndex >= numBytes; + } + + @Override + public ByteBuf markReaderIndex() { + markedReaderIndex = readerIndex; return this; } @Override - public ByteBuf setZero(int index, int length) { - if (length == 0) { + public ByteBuf markWriterIndex() { + markedWriterIndex = writerIndex; + return this; + } + + @Override + public int maxCapacity() { + return maxCapacity; + } + + protected final void maxCapacity(int maxCapacity) { + this.maxCapacity = maxCapacity; + } + + @Override + public int maxWritableBytes() { + return maxCapacity() - writerIndex; + } + + /** + * Creates a new {@link SwappedByteBuf} for this {@link ByteBuf} instance. + */ + protected SwappedByteBuf newSwappedByteBuf() { + return new SwappedByteBuf(this); + } + + @Override + public ByteBuffer nioBuffer() { + return nioBuffer(readerIndex, readableBytes()); + } + + @Override + public ByteBuffer[] nioBuffers() { + return nioBuffers(readerIndex, readableBytes()); + } + + @Override + public ByteBuf order(ByteOrder endianness) { + if (endianness == null) { + throw new NullPointerException("endianness"); + } + if (endianness == order()) { return this; } - checkIndex(index, length); + SwappedByteBuf swappedBuf = this.swappedBuf; + if (swappedBuf == null) { + this.swappedBuf = swappedBuf = newSwappedByteBuf(); + } + return swappedBuf; + } - int nLong = length >>> 3; - int nBytes = length & 7; - for (int i = nLong; i > 0; i--) { - _setLong(index, 0); - index += 8; - } - if (nBytes == 4) { - _setInt(index, 0); - // Not need to update the index as we not will use it after this. - } else if (nBytes < 4) { - for (int i = nBytes; i > 0; i--) { - _setByte(index, (byte) 0); - index++; - } - } else { - _setInt(index, 0); - index += 4; - for (int i = nBytes - 4; i > 0; i--) { - _setByte(index, (byte) 0); - index++; - } - } - return this; + @Override + public int readableBytes() { + return writerIndex - readerIndex; + } + + @Override + public boolean readBoolean() { + return readByte() != 0; } @Override @@ -569,100 +518,9 @@ public abstract class AbstractByteBuf extends ByteBuf { } @Override - public boolean readBoolean() { - return readByte() != 0; - } - - @Override - public short readUnsignedByte() { - return (short) (readByte() & 0xFF); - } - - @Override - public short readShort() { - checkReadableBytes0(2); - short v = _getShort(readerIndex); - readerIndex += 2; - return v; - } - - @Override - public int readUnsignedShort() { - return readShort() & 0xFFFF; - } - - @Override - public int readMedium() { - int value = readUnsignedMedium(); - if ((value & 0x800000) != 0) { - value |= 0xff000000; - } - return value; - } - - @Override - public int readUnsignedMedium() { - checkReadableBytes0(3); - int v = _getUnsignedMedium(readerIndex); - readerIndex += 3; - return v; - } - - @Override - public int readInt() { - checkReadableBytes0(4); - int v = _getInt(readerIndex); - readerIndex += 4; - return v; - } - - @Override - public long readUnsignedInt() { - return readInt() & 0xFFFFFFFFL; - } - - @Override - public long readLong() { - checkReadableBytes0(8); - long v = _getLong(readerIndex); - readerIndex += 8; - return v; - } - - @Override - public char readChar() { - return (char) readShort(); - } - - @Override - public float readFloat() { - return Float.intBitsToFloat(readInt()); - } - - @Override - public double readDouble() { - return Double.longBitsToDouble(readLong()); - } - - @Override - public ByteBuf readBytes(int length) { - checkReadableBytes(length); - if (length == 0) { - return Unpooled.EMPTY_BUFFER; - } - - ByteBuf buf = Unpooled.buffer(length, maxCapacity); - buf.writeBytes(this, readerIndex, length); - readerIndex += length; - return buf; - } - - @Override - public ByteBuf readSlice(int length) { - checkReadableBytes(length); - ByteBuf slice = slice(readerIndex, length); - readerIndex += length; - return slice; + public ByteBuf readBytes(byte[] dst) { + readBytes(dst, 0, dst.length); + return this; } @Override @@ -673,12 +531,6 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } - @Override - public ByteBuf readBytes(byte[] dst) { - readBytes(dst, 0, dst.length); - return this; - } - @Override public ByteBuf readBytes(ByteBuf dst) { readBytes(dst, dst.writableBytes()); @@ -713,6 +565,19 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } + @Override + public ByteBuf readBytes(int length) { + checkReadableBytes(length); + if (length == 0) { + return Unpooled.EMPTY_BUFFER; + } + + ByteBuf buf = Unpooled.buffer(length, maxCapacity); + buf.writeBytes(this, readerIndex, length); + readerIndex += length; + return buf; + } + @Override public ByteBuf readBytes(OutputStream out, int length) throws IOException { checkReadableBytes(length); @@ -721,6 +586,248 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } + @Override + public char readChar() { + return (char) readShort(); + } + + @Override + public double readDouble() { + return Double.longBitsToDouble(readLong()); + } + + @Override + public int readerIndex() { + return readerIndex; + } + + @Override + public ByteBuf readerIndex(int readerIndex) { + if (readerIndex < 0 || readerIndex > writerIndex) { + throw new IndexOutOfBoundsException(HString.format( + "readerIndex: %d (expected: 0 <= readerIndex <= writerIndex(%d))", readerIndex, writerIndex)); + } + this.readerIndex = readerIndex; + return this; + } + + @Override + public float readFloat() { + return Float.intBitsToFloat(readInt()); + } + + @Override + public int readInt() { + checkReadableBytes0(4); + int v = _getInt(readerIndex); + readerIndex += 4; + return v; + } + + @Override + public long readLong() { + checkReadableBytes0(8); + long v = _getLong(readerIndex); + readerIndex += 8; + return v; + } + + @Override + public int readMedium() { + int value = readUnsignedMedium(); + if ((value & 0x800000) != 0) { + value |= 0xff000000; + } + return value; + } + + @Override + public short readShort() { + checkReadableBytes0(2); + short v = _getShort(readerIndex); + readerIndex += 2; + return v; + } + + @Override + public ByteBuf readSlice(int length) { + checkReadableBytes(length); + ByteBuf slice = slice(readerIndex, length); + readerIndex += length; + return slice; + } + + @Override + public short readUnsignedByte() { + return (short) (readByte() & 0xFF); + } + + @Override + public long readUnsignedInt() { + return readInt() & 0xFFFFFFFFL; + } + + @Override + public int readUnsignedMedium() { + checkReadableBytes0(3); + int v = _getUnsignedMedium(readerIndex); + readerIndex += 3; + return v; + } + + @Override + public int readUnsignedShort() { + return readShort() & 0xFFFF; + } + + @Override + public ByteBuf resetReaderIndex() { + readerIndex(markedReaderIndex); + return this; + } + + @Override + public ByteBuf resetWriterIndex() { + writerIndex = markedWriterIndex; + return this; + } + + @Override + public ByteBuf setBoolean(int index, boolean value) { + setByte(index, value ? 1 : 0); + return this; + } + + @Override + public ByteBuf setByte(int index, int value) { + checkIndex(index); + _setByte(index, value); + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src) { + setBytes(index, src, 0, src.length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src) { + setBytes(index, src, src.readableBytes()); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int length) { + checkIndex(index, length); + if (src == null) { + throw new NullPointerException("src"); + } + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(HString.format( + "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); + } + + setBytes(index, src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + return this; + } + + @Override + public ByteBuf setChar(int index, int value) { + setShort(index, value); + return this; + } + + @Override + public ByteBuf setDouble(int index, double value) { + setLong(index, Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf setFloat(int index, float value) { + setInt(index, Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf setIndex(int readerIndex, int writerIndex) { + if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { + throw new IndexOutOfBoundsException(HString.format( + "readerIndex: %d, writerIndex: %d (expected: 0 <= readerIndex <= writerIndex <= capacity(%d))", + readerIndex, writerIndex, capacity())); + } + setIndex0(readerIndex, writerIndex); + return this; + } + + final void setIndex0(int readerIndex, int writerIndex) { + this.readerIndex = readerIndex; + this.writerIndex = writerIndex; + } + + @Override + public ByteBuf setInt(int index, int value) { + checkIndex(index, 4); + _setInt(index, value); + return this; + } + + @Override + public ByteBuf setLong(int index, long value) { + checkIndex(index, 8); + _setLong(index, value); + return this; + } + + @Override + public ByteBuf setMedium(int index, int value) { + checkIndex(index, 3); + _setMedium(index, value); + return this; + } + + @Override + public ByteBuf setShort(int index, int value) { + checkIndex(index, 2); + _setShort(index, value); + return this; + } + + @Override + public ByteBuf setZero(int index, int length) { + if (length == 0) { + return this; + } + + checkIndex(index, length); + + int nLong = length >>> 3; + int nBytes = length & 7; + for (int i = nLong; i > 0; i--) { + _setLong(index, 0); + index += 8; + } + if (nBytes == 4) { + _setInt(index, 0); + // Not need to update the index as we not will use it after this. + } else if (nBytes < 4) { + for (int i = nBytes; i > 0; i--) { + _setByte(index, (byte) 0); + index++; + } + } else { + _setInt(index, 0); + index += 4; + for (int i = nBytes - 4; i > 0; i--) { + _setByte(index, (byte) 0); + index++; + } + } + return this; + } + @Override public ByteBuf skipBytes(int length) { checkReadableBytes(length); @@ -728,6 +835,44 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } + @Override + public ByteBuf slice() { + return slice(readerIndex, readableBytes()); + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder().append(this.getClass().getSimpleName()).append("(ridx: ") + .append(readerIndex).append(", widx: ").append(writerIndex).append(", cap: ").append(capacity()); + if (maxCapacity != Integer.MAX_VALUE) { + buf.append('/').append(maxCapacity); + } + + // Causes infinite loop + /* + * ByteBuf unwrapped = unwrap(); if (unwrapped != null) { + * buf.append(", unwrapped: ").append(unwrapped); } + */ + + buf.append(')'); + return buf.toString(); + } + + @Override + public String toString(Charset charset) { + return toString(readerIndex, readableBytes(), charset); + } + + @Override + public String toString(int index, int length, Charset charset) { + return ByteBufUtil.decodeString(this, index, length, charset); + } + + @Override + public int writableBytes() { + return capacity() - writerIndex; + } + @Override public ByteBuf writeBoolean(boolean value) { writeByte(value ? 1 : 0); @@ -742,52 +887,8 @@ public abstract class AbstractByteBuf extends ByteBuf { } @Override - public ByteBuf writeShort(int value) { - ensureWritable0(2); - _setShort(writerIndex, value); - writerIndex += 2; - return this; - } - - @Override - public ByteBuf writeMedium(int value) { - ensureWritable0(3); - _setMedium(writerIndex, value); - writerIndex += 3; - return this; - } - - @Override - public ByteBuf writeInt(int value) { - ensureWritable0(4); - _setInt(writerIndex, value); - writerIndex += 4; - return this; - } - - @Override - public ByteBuf writeLong(long value) { - ensureWritable0(8); - _setLong(writerIndex, value); - writerIndex += 8; - return this; - } - - @Override - public ByteBuf writeChar(int value) { - writeShort(value); - return this; - } - - @Override - public ByteBuf writeFloat(float value) { - writeInt(Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf writeDouble(double value) { - writeLong(Double.doubleToRawLongBits(value)); + public ByteBuf writeBytes(byte[] src) { + writeBytes(src, 0, src.length); return this; } @@ -799,12 +900,6 @@ public abstract class AbstractByteBuf extends ByteBuf { return this; } - @Override - public ByteBuf writeBytes(byte[] src) { - writeBytes(src, 0, src.length); - return this; - } - @Override public ByteBuf writeBytes(ByteBuf src) { writeBytes(src, src.readableBytes()); @@ -848,7 +943,73 @@ public abstract class AbstractByteBuf extends ByteBuf { } return writtenBytes; } - + + @Override + public ByteBuf writeChar(int value) { + writeShort(value); + return this; + } + + @Override + public ByteBuf writeDouble(double value) { + writeLong(Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf writeFloat(float value) { + writeInt(Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf writeInt(int value) { + ensureWritable0(4); + _setInt(writerIndex, value); + writerIndex += 4; + return this; + } + + @Override + public ByteBuf writeLong(long value) { + ensureWritable0(8); + _setLong(writerIndex, value); + writerIndex += 8; + return this; + } + + @Override + public ByteBuf writeMedium(int value) { + ensureWritable0(3); + _setMedium(writerIndex, value); + writerIndex += 3; + return this; + } + + @Override + public int writerIndex() { + return writerIndex; + } + + @Override + public ByteBuf writerIndex(int writerIndex) { + if (writerIndex < readerIndex || writerIndex > capacity()) { + throw new IndexOutOfBoundsException( + HString.format("writerIndex: %d (expected: readerIndex(%d) <= writerIndex <= capacity(%d))", + writerIndex, readerIndex, capacity())); + } + this.writerIndex = writerIndex; + return this; + } + + @Override + public ByteBuf writeShort(int value) { + ensureWritable0(2); + _setShort(writerIndex, value); + writerIndex += 2; + return this; + } + @Override public ByteBuf writeZero(int length) { if (length == 0) { @@ -884,166 +1045,4 @@ public abstract class AbstractByteBuf extends ByteBuf { writerIndex = wIndex; return this; } - - @Override - public ByteBuf copy() { - return copy(readerIndex, readableBytes()); - } - - @Override - public ByteBuf slice() { - return slice(readerIndex, readableBytes()); - } - - @Override - public ByteBuffer nioBuffer() { - return nioBuffer(readerIndex, readableBytes()); - } - - @Override - public ByteBuffer[] nioBuffers() { - return nioBuffers(readerIndex, readableBytes()); - } - - @Override - public String toString(Charset charset) { - return toString(readerIndex, readableBytes(), charset); - } - - @Override - public String toString(int index, int length, Charset charset) { - return ByteBufUtil.decodeString(this, index, length, charset); - } - - @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - return ByteBufUtil.indexOf(this, fromIndex, toIndex, value); - } - - @Override - public int bytesBefore(byte value) { - return bytesBefore(readerIndex(), readableBytes(), value); - } - - @Override - public int bytesBefore(int length, byte value) { - checkReadableBytes(length); - return bytesBefore(readerIndex(), length, value); - } - - @Override - public int bytesBefore(int index, int length, byte value) { - int endIndex = indexOf(index, index + length, value); - if (endIndex < 0) { - return -1; - } - return endIndex - index; - } - - @Override - public int hashCode() { - return ByteBufUtil.hashCode(this); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o instanceof ByteBuf) { - return ByteBufUtil.equals(this, (ByteBuf) o); - } - return false; - } - - @Override - public int compareTo(ByteBuf that) { - return ByteBufUtil.compare(this, that); - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder().append(this.getClass().getSimpleName()).append("(ridx: ") - .append(readerIndex).append(", widx: ").append(writerIndex).append(", cap: ").append(capacity()); - if (maxCapacity != Integer.MAX_VALUE) { - buf.append('/').append(maxCapacity); - } - - // Causes infinite loop - /* - ByteBuf unwrapped = unwrap(); - if (unwrapped != null) { - buf.append(", unwrapped: ").append(unwrapped); - } - */ - - buf.append(')'); - return buf.toString(); - } - - protected final void checkIndex(int index) { - checkIndex(index, 1); - } - - protected final void checkIndex(int index, int fieldLength) { - checkIndex0(index, fieldLength); - } - - final void checkIndex0(int index, int fieldLength) { - if (isOutOfBounds(index, fieldLength, capacity())) { - throw new IndexOutOfBoundsException( - HString.format("index: %d, length: %d (expected: range(0, %d))", index, fieldLength, capacity())); - } - } - - protected final void checkSrcIndex(int index, int length, int srcIndex, int srcCapacity) { - checkIndex(index, length); - if (isOutOfBounds(srcIndex, length, srcCapacity)) { - throw new IndexOutOfBoundsException( - HString.format("srcIndex: %d, length: %d (expected: range(0, %d))", srcIndex, length, srcCapacity)); - } - } - - protected final void checkDstIndex(int index, int length, int dstIndex, int dstCapacity) { - checkIndex(index, length); - if (isOutOfBounds(dstIndex, length, dstCapacity)) { - throw new IndexOutOfBoundsException( - HString.format("dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dstCapacity)); - } - } - - /** - * Throws an {@link IndexOutOfBoundsException} if the current - * {@linkplain #readableBytes() readable bytes} of this buffer is less than the - * specified value. - */ - protected final void checkReadableBytes(int minimumReadableBytes) { - if (minimumReadableBytes < 0) { - throw new IllegalArgumentException("minimumReadableBytes: " + minimumReadableBytes + " (expected: >= 0)"); - } - checkReadableBytes0(minimumReadableBytes); - } - - protected final void checkNewCapacity(int newCapacity) { - if (newCapacity < 0 || newCapacity > maxCapacity()) { - throw new IllegalArgumentException("newCapacity: " + newCapacity + " (expected: 0-" + maxCapacity() + ')'); - } - } - - private void checkReadableBytes0(int minimumReadableBytes) { - if (readerIndex > writerIndex - minimumReadableBytes) { - throw new IndexOutOfBoundsException( - HString.format("readerIndex(%d) + length(%d) exceeds writerIndex(%d): %s", readerIndex, - minimumReadableBytes, writerIndex, this)); - } - } - - final void setIndex0(int readerIndex, int writerIndex) { - this.readerIndex = readerIndex; - this.writerIndex = writerIndex; - } - - final void discardMarks() { - markedReaderIndex = markedWriterIndex = 0; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBuf.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBuf.java index cc561d5c..b33a5c9a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBuf.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBuf.java @@ -229,15 +229,77 @@ import java.nio.charset.UnsupportedCharsetException; */ @SuppressWarnings("ClassMayBeInterface") public abstract class ByteBuf implements Comparable { - - public static ByteBuf allocate(int length, int maxLength) { - return new ByteBufEaglercraftImpl(ByteBuffer.wrap(new byte[length]), maxLength); - } - + public static ByteBuf allocate(ByteBuffer data, int maxLength) { return new ByteBufEaglercraftImpl(data, maxLength); } + public static ByteBuf allocate(int length, int maxLength) { + return new ByteBufEaglercraftImpl(ByteBuffer.wrap(new byte[length]), maxLength); + } + + /** + * Returns the backing byte array of this buffer. + * + * @throws UnsupportedOperationException if there no accessible backing byte + * array + */ + public abstract byte[] array(); + + /** + * Returns the offset of the first byte within the backing byte array of this + * buffer. + * + * @throws UnsupportedOperationException if there no accessible backing byte + * array + */ + public abstract int arrayOffset(); + + /** + * Locates the first occurrence of the specified {@code value} in this buffer. + * The search takes place from the current {@code readerIndex} (inclusive) to + * the current {@code writerIndex} (exclusive). + *

              + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the number of bytes between the current {@code readerIndex} and the + * first occurrence if found. {@code -1} otherwise. + */ + public abstract int bytesBefore(byte value); + + /** + * Locates the first occurrence of the specified {@code value} in this buffer. + * The search starts from the current {@code readerIndex} (inclusive) and lasts + * for the specified {@code length}. + *

              + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the number of bytes between the current {@code readerIndex} and the + * first occurrence if found. {@code -1} otherwise. + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + */ + public abstract int bytesBefore(int length, byte value); + + /** + * Locates the first occurrence of the specified {@code value} in this buffer. + * The search starts from the specified {@code index} (inclusive) and lasts for + * the specified {@code length}. + *

              + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the number of bytes between the specified {@code index} and the first + * occurrence if found. {@code -1} otherwise. + * + * @throws IndexOutOfBoundsException if {@code index + length} is greater than + * {@code this.capacity} + */ + public abstract int bytesBefore(int index, int length, byte value); + /** * Returns the number of bytes (octets) this buffer can contain. */ @@ -252,168 +314,6 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf capacity(int newCapacity); - /** - * Returns the maximum allowed capacity of this buffer. If a user attempts to - * increase the capacity of this buffer beyond the maximum capacity using - * {@link #capacity(int)} or {@link #ensureWritable(int)}, those methods will - * raise an {@link IllegalArgumentException}. - */ - public abstract int maxCapacity(); - - /** - * Returns the endianness - * of this buffer. - */ - public abstract ByteOrder order(); - - /** - * Returns a buffer with the specified {@code endianness} which shares the whole - * region, indexes, and marks of this buffer. Modifying the content, the - * indexes, or the marks of the returned buffer or this buffer affects each - * other's content, indexes, and marks. If the specified {@code endianness} is - * identical to this buffer's byte order, this method can return {@code this}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf order(ByteOrder endianness); - - /** - * Return the underlying buffer instance if this buffer is a wrapper of another - * buffer. - * - * @return {@code null} if this buffer is not a wrapper - */ - public abstract ByteBuf unwrap(); - - /** - * Returns {@code true} if and only if this buffer is backed by an NIO direct - * buffer. - */ - public abstract boolean isDirect(); - - /** - * Returns the {@code readerIndex} of this buffer. - */ - public abstract int readerIndex(); - - /** - * Sets the {@code readerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is - * less than {@code 0} or greater than - * {@code this.writerIndex} - */ - public abstract ByteBuf readerIndex(int readerIndex); - - /** - * Returns the {@code writerIndex} of this buffer. - */ - public abstract int writerIndex(); - - /** - * Sets the {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code writerIndex} is - * less than {@code this.readerIndex} or - * greater than {@code this.capacity} - */ - public abstract ByteBuf writerIndex(int writerIndex); - - /** - * Sets the {@code readerIndex} and {@code writerIndex} of this buffer in one - * shot. This method is useful when you have to worry about the invocation order - * of {@link #readerIndex(int)} and {@link #writerIndex(int)} methods. For - * example, the following code will fail: - * - *

              -	 * // Create a buffer whose readerIndex, writerIndex and capacity are
              -	 * // 0, 0 and 8 respectively.
              -	 * {@link ByteBuf} buf = {@link Unpooled}.buffer(8);
              -	 *
              -	 * // IndexOutOfBoundsException is thrown because the specified
              -	 * // readerIndex (2) cannot be greater than the current writerIndex (0).
              -	 * buf.readerIndex(2);
              -	 * buf.writerIndex(4);
              -	 * 
              - * - * The following code will also fail: - * - *
              -	 * // Create a buffer whose readerIndex, writerIndex and capacity are
              -	 * // 0, 8 and 8 respectively.
              -	 * {@link ByteBuf} buf = {@link Unpooled}.wrappedBuffer(new byte[8]);
              -	 *
              -	 * // readerIndex becomes 8.
              -	 * buf.readLong();
              -	 *
              -	 * // IndexOutOfBoundsException is thrown because the specified
              -	 * // writerIndex (4) cannot be less than the current readerIndex (8).
              -	 * buf.writerIndex(4);
              -	 * buf.readerIndex(2);
              -	 * 
              - * - * By contrast, this method guarantees that it never throws an - * {@link IndexOutOfBoundsException} as long as the specified indexes meet basic - * constraints, regardless what the current index values of the buffer are: - * - *
              -	 * // No matter what the current state of the buffer is, the following
              -	 * // call always succeeds as long as the capacity of the buffer is not
              -	 * // less than 4.
              -	 * buf.setIndex(2, 4);
              -	 * 
              - * - * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is - * less than 0, if the specified - * {@code writerIndex} is less than the - * specified {@code readerIndex} or if the - * specified {@code writerIndex} is greater - * than {@code this.capacity} - */ - public abstract ByteBuf setIndex(int readerIndex, int writerIndex); - - /** - * Returns the number of readable bytes which is equal to - * {@code (this.writerIndex - this.readerIndex)}. - */ - public abstract int readableBytes(); - - /** - * Returns the number of writable bytes which is equal to - * {@code (this.capacity - this.writerIndex)}. - */ - public abstract int writableBytes(); - - /** - * Returns the maximum possible number of writable bytes, which is equal to - * {@code (this.maxCapacity - this.writerIndex)}. - */ - public abstract int maxWritableBytes(); - - /** - * Returns {@code true} if and only if - * {@code (this.writerIndex - this.readerIndex)} is greater than {@code 0}. - */ - public abstract boolean isReadable(); - - /** - * Returns {@code true} if and only if this buffer contains equal to or more - * than the specified number of elements. - */ - public abstract boolean isReadable(int size); - - /** - * Returns {@code true} if and only if - * {@code (this.capacity - this.writerIndex)} is greater than {@code 0}. - */ - public abstract boolean isWritable(); - - /** - * Returns {@code true} if and only if this buffer has enough room to allow - * writing the specified number of elements. - */ - public abstract boolean isWritable(int size); - /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to * {@code 0}. This method is identical to {@link #setIndex(int, int) setIndex(0, @@ -425,38 +325,29 @@ public abstract class ByteBuf implements Comparable { public abstract ByteBuf clear(); /** - * Marks the current {@code readerIndex} in this buffer. You can reposition the - * current {@code readerIndex} to the marked {@code readerIndex} by calling - * {@link #resetReaderIndex()}. The initial value of the marked - * {@code readerIndex} is {@code 0}. + * Compares the content of the specified buffer to the content of this buffer. + * Comparison is performed in the same manner with the string comparison + * functions of various languages such as {@code strcmp}, {@code memcmp} and + * {@link String#compareTo(String)}. */ - public abstract ByteBuf markReaderIndex(); + @Override + public abstract int compareTo(ByteBuf buffer); /** - * Repositions the current {@code readerIndex} to the marked {@code readerIndex} - * in this buffer. - * - * @throws IndexOutOfBoundsException if the current {@code writerIndex} is less - * than the marked {@code readerIndex} + * Returns a copy of this buffer's readable bytes. Modifying the content of the + * returned buffer or this buffer does not affect each other at all. This method + * is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. */ - public abstract ByteBuf resetReaderIndex(); + public abstract ByteBuf copy(); /** - * Marks the current {@code writerIndex} in this buffer. You can reposition the - * current {@code writerIndex} to the marked {@code writerIndex} by calling - * {@link #resetWriterIndex()}. The initial value of the marked - * {@code writerIndex} is {@code 0}. + * Returns a copy of this buffer's sub-region. Modifying the content of the + * returned buffer or this buffer does not affect each other at all. This method + * does not modify {@code readerIndex} or {@code writerIndex} of this buffer. */ - public abstract ByteBuf markWriterIndex(); - - /** - * Repositions the current {@code writerIndex} to the marked {@code writerIndex} - * in this buffer. - * - * @throws IndexOutOfBoundsException if the current {@code readerIndex} is - * greater than the marked {@code writerIndex} - */ - public abstract ByteBuf resetWriterIndex(); + public abstract ByteBuf copy(int index, int length); /** * Discards the bytes between the 0th index and {@code readerIndex}. It moves @@ -476,6 +367,23 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf discardSomeReadBytes(); + /** + * Returns a buffer which shares the whole region of this buffer. Modifying the + * content of the returned buffer or this buffer affects each other's content + * while they maintain separate indexes and marks. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + *

              + * The reader and writer marks will not be duplicated. Also be aware that this + * method will NOT call {@link #retain()} and so the reference count will NOT be + * increased. + * + * @return A buffer whose readable content is equivalent to the buffer returned + * by {@link #slice()}. However this buffer will share the capacity of + * the underlying buffer, and therefore allows access to all of the + * underlying content if necessary. + */ + public abstract ByteBuf duplicate(); + /** * Makes sure the number of {@linkplain #writableBytes() the writable bytes} is * equal to or greater than the specified value. If there is enough writable @@ -513,6 +421,20 @@ public abstract class ByteBuf implements Comparable { */ public abstract int ensureWritable(int minWritableBytes, boolean force); + /** + * Determines if the content of the specified buffer is identical to the content + * of this array. 'Identical' here means: + *

                + *
              • the size of the contents of the two buffers are same and
              • + *
              • every single byte of the content of the two buffers are same.
              • + *
              + * Please note that it does not compare {@link #readerIndex()} nor + * {@link #writerIndex()}. This method also returns {@code false} for + * {@code null} and an object which is not an instance of {@link ByteBuf} type. + */ + @Override + public abstract boolean equals(Object obj); + /** * Gets a boolean at the specified absolute (@code index) in this buffer. This * method does not modify the {@code readerIndex} or {@code writerIndex} of this @@ -536,125 +458,33 @@ public abstract class ByteBuf implements Comparable { public abstract byte getByte(int index); /** - * Gets an unsigned byte at the specified absolute {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index}. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer * * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 1} is greater - * than {@code this.capacity} + * {@code 0} or if {@code index + dst.length} + * is greater than {@code this.capacity} */ - public abstract short getUnsignedByte(int index); + public abstract ByteBuf getBytes(int index, byte[] dst); /** - * Gets a 16-bit short integer at the specified absolute {@code index} in this - * buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. + * Transfers this buffer's data to the specified destination starting at the + * specified absolute {@code index}. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 2} is greater - * than {@code this.capacity} + * {@code 0}, if the specified + * {@code dstIndex} is less than {@code 0}, if + * {@code index + length} is greater than + * {@code this.capacity}, or if + * {@code dstIndex + length} is greater than + * {@code dst.length} */ - public abstract short getShort(int index); - - /** - * Gets an unsigned 16-bit short integer at the specified absolute {@code index} - * in this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 2} is greater - * than {@code this.capacity} - */ - public abstract int getUnsignedShort(int index); - - /** - * Gets a 24-bit medium integer at the specified absolute {@code index} in this - * buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 3} is greater - * than {@code this.capacity} - */ - public abstract int getMedium(int index); - - /** - * Gets an unsigned 24-bit medium integer at the specified absolute - * {@code index} in this buffer. This method does not modify {@code readerIndex} - * or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 3} is greater - * than {@code this.capacity} - */ - public abstract int getUnsignedMedium(int index); - - /** - * Gets a 32-bit integer at the specified absolute {@code index} in this buffer. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 4} is greater - * than {@code this.capacity} - */ - public abstract int getInt(int index); - - /** - * Gets an unsigned 32-bit integer at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 4} is greater - * than {@code this.capacity} - */ - public abstract long getUnsignedInt(int index); - - /** - * Gets a 64-bit long integer at the specified absolute {@code index} in this - * buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 8} is greater - * than {@code this.capacity} - */ - public abstract long getLong(int index); - - /** - * Gets a 2-byte UTF-16 character at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 2} is greater - * than {@code this.capacity} - */ - public abstract char getChar(int index); - - /** - * Gets a 32-bit floating point number at the specified absolute {@code index} - * in this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 4} is greater - * than {@code this.capacity} - */ - public abstract float getFloat(int index); - - /** - * Gets a 64-bit floating point number at the specified absolute {@code index} - * in this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 8} is greater - * than {@code this.capacity} - */ - public abstract double getDouble(int index); + public abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at the @@ -711,35 +541,6 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length); - /** - * Transfers this buffer's data to the specified destination starting at the - * specified absolute {@code index}. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or if {@code index + dst.length} - * is greater than {@code this.capacity} - */ - public abstract ByteBuf getBytes(int index, byte[] dst); - - /** - * Transfers this buffer's data to the specified destination starting at the - * specified absolute {@code index}. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0}, if the specified - * {@code dstIndex} is less than {@code 0}, if - * {@code index + length} is greater than - * {@code this.capacity}, or if - * {@code dstIndex + length} is greater than - * {@code dst.length} - */ - public abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); - /** * Transfers this buffer's data to the specified destination starting at the * specified absolute {@code index} until the destination's position reaches its @@ -768,6 +569,634 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException; + /** + * Gets a 2-byte UTF-16 character at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 2} is greater + * than {@code this.capacity} + */ + public abstract char getChar(int index); + + /** + * Gets a 64-bit floating point number at the specified absolute {@code index} + * in this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 8} is greater + * than {@code this.capacity} + */ + public abstract double getDouble(int index); + + /** + * Gets a 32-bit floating point number at the specified absolute {@code index} + * in this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 4} is greater + * than {@code this.capacity} + */ + public abstract float getFloat(int index); + + /** + * Gets a 32-bit integer at the specified absolute {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 4} is greater + * than {@code this.capacity} + */ + public abstract int getInt(int index); + + /** + * Gets a 64-bit long integer at the specified absolute {@code index} in this + * buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 8} is greater + * than {@code this.capacity} + */ + public abstract long getLong(int index); + + /** + * Gets a 24-bit medium integer at the specified absolute {@code index} in this + * buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 3} is greater + * than {@code this.capacity} + */ + public abstract int getMedium(int index); + + /** + * Gets a 16-bit short integer at the specified absolute {@code index} in this + * buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 2} is greater + * than {@code this.capacity} + */ + public abstract short getShort(int index); + + /** + * Gets an unsigned byte at the specified absolute {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 1} is greater + * than {@code this.capacity} + */ + public abstract short getUnsignedByte(int index); + + /** + * Gets an unsigned 32-bit integer at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 4} is greater + * than {@code this.capacity} + */ + public abstract long getUnsignedInt(int index); + + /** + * Gets an unsigned 24-bit medium integer at the specified absolute + * {@code index} in this buffer. This method does not modify {@code readerIndex} + * or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 3} is greater + * than {@code this.capacity} + */ + public abstract int getUnsignedMedium(int index); + + /** + * Gets an unsigned 16-bit short integer at the specified absolute {@code index} + * in this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 2} is greater + * than {@code this.capacity} + */ + public abstract int getUnsignedShort(int index); + + /** + * Returns {@code true} if and only if this buffer has a backing byte array. If + * this method returns true, you can safely call {@link #array()} and + * {@link #arrayOffset()}. + */ + public abstract boolean hasArray(); + + /** + * Returns a hash code which was calculated from the content of this buffer. If + * there's a byte array which is {@linkplain #equals(Object) equal to} this + * array, both arrays should return the same value. + */ + @Override + public abstract int hashCode(); + + /** + * Returns {@code true} if and only if this buffer has a reference to the + * low-level memory address that points to the backing data. + */ + public abstract boolean hasMemoryAddress(); + + /** + * Locates the first occurrence of the specified {@code value} in this buffer. + * The search takes place from the specified {@code fromIndex} (inclusive) to + * the specified {@code toIndex} (exclusive). + *

              + * If {@code fromIndex} is greater than {@code toIndex}, the search is performed + * in a reversed order. + *

              + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the absolute index of the first occurrence if found. {@code -1} + * otherwise. + */ + public abstract int indexOf(int fromIndex, int toIndex, byte value); + + /** + * Internal use only: Exposes the internal NIO buffer. + */ + public abstract ByteBuffer internalNioBuffer(int index, int length); + + /** + * Returns {@code true} if and only if this buffer is backed by an NIO direct + * buffer. + */ + public abstract boolean isDirect(); + + /** + * Returns {@code true} if and only if + * {@code (this.writerIndex - this.readerIndex)} is greater than {@code 0}. + */ + public abstract boolean isReadable(); + + /** + * Returns {@code true} if and only if this buffer contains equal to or more + * than the specified number of elements. + */ + public abstract boolean isReadable(int size); + + /** + * Returns {@code true} if and only if + * {@code (this.capacity - this.writerIndex)} is greater than {@code 0}. + */ + public abstract boolean isWritable(); + + /** + * Returns {@code true} if and only if this buffer has enough room to allow + * writing the specified number of elements. + */ + public abstract boolean isWritable(int size); + + /** + * Marks the current {@code readerIndex} in this buffer. You can reposition the + * current {@code readerIndex} to the marked {@code readerIndex} by calling + * {@link #resetReaderIndex()}. The initial value of the marked + * {@code readerIndex} is {@code 0}. + */ + public abstract ByteBuf markReaderIndex(); + + /** + * Marks the current {@code writerIndex} in this buffer. You can reposition the + * current {@code writerIndex} to the marked {@code writerIndex} by calling + * {@link #resetWriterIndex()}. The initial value of the marked + * {@code writerIndex} is {@code 0}. + */ + public abstract ByteBuf markWriterIndex(); + + /** + * Returns the maximum allowed capacity of this buffer. If a user attempts to + * increase the capacity of this buffer beyond the maximum capacity using + * {@link #capacity(int)} or {@link #ensureWritable(int)}, those methods will + * raise an {@link IllegalArgumentException}. + */ + public abstract int maxCapacity(); + + /** + * Returns the maximum possible number of writable bytes, which is equal to + * {@code (this.maxCapacity - this.writerIndex)}. + */ + public abstract int maxWritableBytes(); + + /** + * Returns the low-level memory address that point to the first byte of ths + * backing data. + * + * @throws UnsupportedOperationException if this buffer does not support + * accessing the low-level memory address + */ + public abstract long memoryAddress(); + + /** + * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}. The + * returned buffer either share or contains the copied content of this buffer, + * while changing the position and limit of the returned NIO buffer does not + * affect the indexes and marks of this buffer. This method is identical to + * {@code buf.nioBuffer(buf.readerIndex(), buf.readableBytes())}. This method + * does not modify {@code readerIndex} or {@code writerIndex} of this buffer. + * Please note that the returned NIO buffer will not see the changes of this + * buffer if this buffer is a dynamic buffer and it adjusted its capacity. + * + * @throws UnsupportedOperationException if this buffer cannot create a + * {@link ByteBuffer} that shares the + * content with itself + * + * @see #nioBufferCount() + * @see #nioBuffers() + * @see #nioBuffers(int, int) + */ + public abstract ByteBuffer nioBuffer(); + + /** + * Exposes this buffer's sub-region as an NIO {@link ByteBuffer}. The returned + * buffer either share or contains the copied content of this buffer, while + * changing the position and limit of the returned NIO buffer does not affect + * the indexes and marks of this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. Please note that + * the returned NIO buffer will not see the changes of this buffer if this + * buffer is a dynamic buffer and it adjusted its capacity. + * + * @throws UnsupportedOperationException if this buffer cannot create a + * {@link ByteBuffer} that shares the + * content with itself + * + * @see #nioBufferCount() + * @see #nioBuffers() + * @see #nioBuffers(int, int) + */ + public abstract ByteBuffer nioBuffer(int index, int length); + + /** + * Returns the maximum number of NIO {@link ByteBuffer}s that consist this + * buffer. Note that {@link #nioBuffers()} or {@link #nioBuffers(int, int)} + * might return a less number of {@link ByteBuffer}s. + * + * @return {@code -1} if this buffer has no underlying {@link ByteBuffer}. the + * number of the underlying {@link ByteBuffer}s if this buffer has at + * least one underlying {@link ByteBuffer}. Note that this method does + * not return {@code 0} to avoid confusion. + * + * @see #nioBuffer() + * @see #nioBuffer(int, int) + * @see #nioBuffers() + * @see #nioBuffers(int, int) + */ + public abstract int nioBufferCount(); + + /** + * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}'s. The + * returned buffer either share or contains the copied content of this buffer, + * while changing the position and limit of the returned NIO buffer does not + * affect the indexes and marks of this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. Please note that + * the returned NIO buffer will not see the changes of this buffer if this + * buffer is a dynamic buffer and it adjusted its capacity. + * + * + * @throws UnsupportedOperationException if this buffer cannot create a + * {@link ByteBuffer} that shares the + * content with itself + * + * @see #nioBufferCount() + * @see #nioBuffer() + * @see #nioBuffer(int, int) + */ + public abstract ByteBuffer[] nioBuffers(); + + /** + * Exposes this buffer's bytes as an NIO {@link ByteBuffer}'s for the specified + * index and length The returned buffer either share or contains the copied + * content of this buffer, while changing the position and limit of the returned + * NIO buffer does not affect the indexes and marks of this buffer. This method + * does not modify {@code readerIndex} or {@code writerIndex} of this buffer. + * Please note that the returned NIO buffer will not see the changes of this + * buffer if this buffer is a dynamic buffer and it adjusted its capacity. + * + * @throws UnsupportedOperationException if this buffer cannot create a + * {@link ByteBuffer} that shares the + * content with itself + * + * @see #nioBufferCount() + * @see #nioBuffer() + * @see #nioBuffer(int, int) + */ + public abstract ByteBuffer[] nioBuffers(int index, int length); + + /** + * Returns the endianness + * of this buffer. + */ + public abstract ByteOrder order(); + + /** + * Returns a buffer with the specified {@code endianness} which shares the whole + * region, indexes, and marks of this buffer. Modifying the content, the + * indexes, or the marks of the returned buffer or this buffer affects each + * other's content, indexes, and marks. If the specified {@code endianness} is + * identical to this buffer's byte order, this method can return {@code this}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + */ + public abstract ByteBuf order(ByteOrder endianness); + + /** + * Returns the number of readable bytes which is equal to + * {@code (this.writerIndex - this.readerIndex)}. + */ + public abstract int readableBytes(); + + /** + * Gets a boolean at the current {@code readerIndex} and increases the + * {@code readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 1} + */ + public abstract boolean readBoolean(); + + /** + * Gets a byte at the current {@code readerIndex} and increases the + * {@code readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 1} + */ + public abstract byte readByte(); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code dst.length}). + * + * @throws IndexOutOfBoundsException if {@code dst.length} is greater than + * {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(byte[] dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is less + * than {@code 0}, if {@code length} is + * greater than {@code this.readableBytes}, or + * if {@code dstIndex + length} is greater + * than {@code dst.length} + */ + public abstract ByteBuf readBytes(byte[] dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} until the destination becomes non-writable, and + * increases the {@code readerIndex} by the number of the transferred bytes. + * This method is basically same with {@link #readBytes(ByteBuf, int, int)}, + * except that this method increases the {@code writerIndex} of the destination + * by the number of the transferred bytes while + * {@link #readBytes(ByteBuf, int, int)} does not. + * + * @throws IndexOutOfBoundsException if {@code dst.writableBytes} is greater + * than {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(ByteBuf dst); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). This method is basically + * same with {@link #readBytes(ByteBuf, int, int)}, except that this method + * increases the {@code writerIndex} of the destination by the number of the + * transferred bytes (= {@code length}) while + * {@link #readBytes(ByteBuf, int, int)} does not. + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} or if + * {@code length} is greater than + * {@code dst.writableBytes} + */ + public abstract ByteBuf readBytes(ByteBuf dst, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is less + * than {@code 0}, if {@code length} is + * greater than {@code this.readableBytes}, or + * if {@code dstIndex + length} is greater + * than {@code dst.capacity} + */ + public abstract ByteBuf readBytes(ByteBuf dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at the + * current {@code readerIndex} until the destination's position reaches its + * limit, and increases the {@code readerIndex} by the number of the transferred + * bytes. + * + * @throws IndexOutOfBoundsException if {@code dst.remaining()} is greater than + * {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(ByteBuffer dst); + + /** + * Transfers this buffer's data to a newly created buffer starting at the + * current {@code readerIndex} and increases the {@code readerIndex} by the + * number of the transferred bytes (= {@code length}). The returned buffer's + * {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code length} + * respectively. + * + * @param length the number of bytes to transfer + * + * @return the newly created buffer which contains the transferred bytes + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(int length); + + /** + * Transfers this buffer's data to the specified stream starting at the current + * {@code readerIndex}. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + * @throws IOException if the specified stream threw an exception + * during I/O + */ + public abstract ByteBuf readBytes(OutputStream out, int length) throws IOException; + + /** + * Gets a 2-byte UTF-16 character at the current {@code readerIndex} and + * increases the {@code readerIndex} by {@code 2} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 2} + */ + public abstract char readChar(); + + /** + * Gets a 64-bit floating point number at the current {@code readerIndex} and + * increases the {@code readerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 8} + */ + public abstract double readDouble(); + + /** + * Returns the {@code readerIndex} of this buffer. + */ + public abstract int readerIndex(); + + /** + * Sets the {@code readerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is + * less than {@code 0} or greater than + * {@code this.writerIndex} + */ + public abstract ByteBuf readerIndex(int readerIndex); + + /** + * Gets a 32-bit floating point number at the current {@code readerIndex} and + * increases the {@code readerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 4} + */ + public abstract float readFloat(); + + /** + * Gets a 32-bit integer at the current {@code readerIndex} and increases the + * {@code readerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 4} + */ + public abstract int readInt(); + + /** + * Gets a 64-bit integer at the current {@code readerIndex} and increases the + * {@code readerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 8} + */ + public abstract long readLong(); + + /** + * Gets a 24-bit medium integer at the current {@code readerIndex} and increases + * the {@code readerIndex} by {@code 3} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 3} + */ + public abstract int readMedium(); + + /** + * Gets a 16-bit short integer at the current {@code readerIndex} and increases + * the {@code readerIndex} by {@code 2} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 2} + */ + public abstract short readShort(); + + /** + * Returns a new slice of this buffer's sub-region starting at the current + * {@code readerIndex} and increases the {@code readerIndex} by the size of the + * new slice (= {@code length}). + *

              + * Also be aware that this method will NOT call {@link #retain()} and so the + * reference count will NOT be increased. + * + * @param length the size of the new slice + * + * @return the newly created slice + * + * @throws IndexOutOfBoundsException if {@code length} is greater than + * {@code this.readableBytes} + */ + public abstract ByteBuf readSlice(int length); + + /** + * Gets an unsigned byte at the current {@code readerIndex} and increases the + * {@code readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 1} + */ + public abstract short readUnsignedByte(); + + /** + * Gets an unsigned 32-bit integer at the current {@code readerIndex} and + * increases the {@code readerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 4} + */ + public abstract long readUnsignedInt(); + + /** + * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} and + * increases the {@code readerIndex} by {@code 3} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 3} + */ + public abstract int readUnsignedMedium(); + + /** + * Gets an unsigned 16-bit short integer at the current {@code readerIndex} and + * increases the {@code readerIndex} by {@code 2} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than + * {@code 2} + */ + public abstract int readUnsignedShort(); + + /** + * Repositions the current {@code readerIndex} to the marked {@code readerIndex} + * in this buffer. + * + * @throws IndexOutOfBoundsException if the current {@code writerIndex} is less + * than the marked {@code readerIndex} + */ + public abstract ByteBuf resetReaderIndex(); + + /** + * Repositions the current {@code writerIndex} to the marked {@code writerIndex} + * in this buffer. + * + * @throws IndexOutOfBoundsException if the current {@code readerIndex} is + * greater than the marked {@code writerIndex} + */ + public abstract ByteBuf resetWriterIndex(); + /** * Sets the specified boolean at the specified absolute {@code index} in this * buffer. This method does not modify {@code readerIndex} or @@ -792,84 +1221,30 @@ public abstract class ByteBuf implements Comparable { public abstract ByteBuf setByte(int index, int value); /** - * Sets the specified 16-bit short integer at the specified absolute - * {@code index} in this buffer. The 16 high-order bits of the specified value - * are ignored. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 2} is greater - * than {@code this.capacity} - */ - public abstract ByteBuf setShort(int index, int value); - - /** - * Sets the specified 24-bit medium integer at the specified absolute - * {@code index} in this buffer. Please note that the most significant byte is - * ignored in the specified value. This method does not modify + * Transfers the specified source array's data to this buffer starting at the + * specified absolute {@code index}. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 3} is greater - * than {@code this.capacity} + * {@code 0} or if {@code index + src.length} + * is greater than {@code this.capacity} */ - public abstract ByteBuf setMedium(int index, int value); + public abstract ByteBuf setBytes(int index, byte[] src); /** - * Sets the specified 32-bit integer at the specified absolute {@code index} in - * this buffer. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. + * Transfers the specified source array's data to this buffer starting at the + * specified absolute {@code index}. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 4} is greater - * than {@code this.capacity} + * {@code 0}, if the specified + * {@code srcIndex} is less than {@code 0}, if + * {@code index + length} is greater than + * {@code this.capacity}, or if + * {@code srcIndex + length} is greater than + * {@code src.length} */ - public abstract ByteBuf setInt(int index, int value); - - /** - * Sets the specified 64-bit long integer at the specified absolute - * {@code index} in this buffer. This method does not modify {@code readerIndex} - * or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 8} is greater - * than {@code this.capacity} - */ - public abstract ByteBuf setLong(int index, long value); - - /** - * Sets the specified 2-byte UTF-16 character at the specified absolute - * {@code index} in this buffer. The 16 high-order bits of the specified value - * are ignored. This method does not modify {@code readerIndex} or - * {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 2} is greater - * than {@code this.capacity} - */ - public abstract ByteBuf setChar(int index, int value); - - /** - * Sets the specified 32-bit floating-point number at the specified absolute - * {@code index} in this buffer. This method does not modify {@code readerIndex} - * or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 4} is greater - * than {@code this.capacity} - */ - public abstract ByteBuf setFloat(int index, float value); - - /** - * Sets the specified 64-bit floating-point number at the specified absolute - * {@code index} in this buffer. This method does not modify {@code readerIndex} - * or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or {@code index + 8} is greater - * than {@code this.capacity} - */ - public abstract ByteBuf setDouble(int index, double value); + public abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at the @@ -926,32 +1301,6 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length); - /** - * Transfers the specified source array's data to this buffer starting at the - * specified absolute {@code index}. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0} or if {@code index + src.length} - * is greater than {@code this.capacity} - */ - public abstract ByteBuf setBytes(int index, byte[] src); - - /** - * Transfers the specified source array's data to this buffer starting at the - * specified absolute {@code index}. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - * - * @throws IndexOutOfBoundsException if the specified {@code index} is less than - * {@code 0}, if the specified - * {@code srcIndex} is less than {@code 0}, if - * {@code index + length} is greater than - * {@code this.capacity}, or if - * {@code srcIndex + length} is greater than - * {@code src.length} - */ - public abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); - /** * Transfers the specified source buffer's data to this buffer starting at the * specified absolute {@code index} until the source buffer's position reaches @@ -983,6 +1332,139 @@ public abstract class ByteBuf implements Comparable { */ public abstract int setBytes(int index, InputStream in, int length) throws IOException; + /** + * Sets the specified 2-byte UTF-16 character at the specified absolute + * {@code index} in this buffer. The 16 high-order bits of the specified value + * are ignored. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 2} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setChar(int index, int value); + + /** + * Sets the specified 64-bit floating-point number at the specified absolute + * {@code index} in this buffer. This method does not modify {@code readerIndex} + * or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 8} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setDouble(int index, double value); + + /** + * Sets the specified 32-bit floating-point number at the specified absolute + * {@code index} in this buffer. This method does not modify {@code readerIndex} + * or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 4} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setFloat(int index, float value); + + /** + * Sets the {@code readerIndex} and {@code writerIndex} of this buffer in one + * shot. This method is useful when you have to worry about the invocation order + * of {@link #readerIndex(int)} and {@link #writerIndex(int)} methods. For + * example, the following code will fail: + * + *

              +	 * // Create a buffer whose readerIndex, writerIndex and capacity are
              +	 * // 0, 0 and 8 respectively.
              +	 * {@link ByteBuf} buf = {@link Unpooled}.buffer(8);
              +	 *
              +	 * // IndexOutOfBoundsException is thrown because the specified
              +	 * // readerIndex (2) cannot be greater than the current writerIndex (0).
              +	 * buf.readerIndex(2);
              +	 * buf.writerIndex(4);
              +	 * 
              + * + * The following code will also fail: + * + *
              +	 * // Create a buffer whose readerIndex, writerIndex and capacity are
              +	 * // 0, 8 and 8 respectively.
              +	 * {@link ByteBuf} buf = {@link Unpooled}.wrappedBuffer(new byte[8]);
              +	 *
              +	 * // readerIndex becomes 8.
              +	 * buf.readLong();
              +	 *
              +	 * // IndexOutOfBoundsException is thrown because the specified
              +	 * // writerIndex (4) cannot be less than the current readerIndex (8).
              +	 * buf.writerIndex(4);
              +	 * buf.readerIndex(2);
              +	 * 
              + * + * By contrast, this method guarantees that it never throws an + * {@link IndexOutOfBoundsException} as long as the specified indexes meet basic + * constraints, regardless what the current index values of the buffer are: + * + *
              +	 * // No matter what the current state of the buffer is, the following
              +	 * // call always succeeds as long as the capacity of the buffer is not
              +	 * // less than 4.
              +	 * buf.setIndex(2, 4);
              +	 * 
              + * + * @throws IndexOutOfBoundsException if the specified {@code readerIndex} is + * less than 0, if the specified + * {@code writerIndex} is less than the + * specified {@code readerIndex} or if the + * specified {@code writerIndex} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setIndex(int readerIndex, int writerIndex); + + /** + * Sets the specified 32-bit integer at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 4} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setInt(int index, int value); + + /** + * Sets the specified 64-bit long integer at the specified absolute + * {@code index} in this buffer. This method does not modify {@code readerIndex} + * or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 8} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setLong(int index, long value); + + /** + * Sets the specified 24-bit medium integer at the specified absolute + * {@code index} in this buffer. Please note that the most significant byte is + * ignored in the specified value. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 3} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setMedium(int index, int value); + + /** + * Sets the specified 16-bit short integer at the specified absolute + * {@code index} in this buffer. The 16 high-order bits of the specified value + * are ignored. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code index} is less than + * {@code 0} or {@code index + 2} is greater + * than {@code this.capacity} + */ + public abstract ByteBuf setShort(int index, int value); + /** * Fills this buffer with NUL (0x00) starting at the specified absolute * {@code index}. This method does not modify {@code readerIndex} or @@ -996,252 +1478,6 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf setZero(int index, int length); - /** - * Gets a boolean at the current {@code readerIndex} and increases the - * {@code readerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 1} - */ - public abstract boolean readBoolean(); - - /** - * Gets a byte at the current {@code readerIndex} and increases the - * {@code readerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 1} - */ - public abstract byte readByte(); - - /** - * Gets an unsigned byte at the current {@code readerIndex} and increases the - * {@code readerIndex} by {@code 1} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 1} - */ - public abstract short readUnsignedByte(); - - /** - * Gets a 16-bit short integer at the current {@code readerIndex} and increases - * the {@code readerIndex} by {@code 2} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 2} - */ - public abstract short readShort(); - - /** - * Gets an unsigned 16-bit short integer at the current {@code readerIndex} and - * increases the {@code readerIndex} by {@code 2} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 2} - */ - public abstract int readUnsignedShort(); - - /** - * Gets a 24-bit medium integer at the current {@code readerIndex} and increases - * the {@code readerIndex} by {@code 3} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 3} - */ - public abstract int readMedium(); - - /** - * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} and - * increases the {@code readerIndex} by {@code 3} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 3} - */ - public abstract int readUnsignedMedium(); - - /** - * Gets a 32-bit integer at the current {@code readerIndex} and increases the - * {@code readerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 4} - */ - public abstract int readInt(); - - /** - * Gets an unsigned 32-bit integer at the current {@code readerIndex} and - * increases the {@code readerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 4} - */ - public abstract long readUnsignedInt(); - - /** - * Gets a 64-bit integer at the current {@code readerIndex} and increases the - * {@code readerIndex} by {@code 8} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 8} - */ - public abstract long readLong(); - - /** - * Gets a 2-byte UTF-16 character at the current {@code readerIndex} and - * increases the {@code readerIndex} by {@code 2} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 2} - */ - public abstract char readChar(); - - /** - * Gets a 32-bit floating point number at the current {@code readerIndex} and - * increases the {@code readerIndex} by {@code 4} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 4} - */ - public abstract float readFloat(); - - /** - * Gets a 64-bit floating point number at the current {@code readerIndex} and - * increases the {@code readerIndex} by {@code 8} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.readableBytes} is less than - * {@code 8} - */ - public abstract double readDouble(); - - /** - * Transfers this buffer's data to a newly created buffer starting at the - * current {@code readerIndex} and increases the {@code readerIndex} by the - * number of the transferred bytes (= {@code length}). The returned buffer's - * {@code readerIndex} and {@code writerIndex} are {@code 0} and {@code length} - * respectively. - * - * @param length the number of bytes to transfer - * - * @return the newly created buffer which contains the transferred bytes - * - * @throws IndexOutOfBoundsException if {@code length} is greater than - * {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(int length); - - /** - * Returns a new slice of this buffer's sub-region starting at the current - * {@code readerIndex} and increases the {@code readerIndex} by the size of the - * new slice (= {@code length}). - *

              - * Also be aware that this method will NOT call {@link #retain()} and so the - * reference count will NOT be increased. - * - * @param length the size of the new slice - * - * @return the newly created slice - * - * @throws IndexOutOfBoundsException if {@code length} is greater than - * {@code this.readableBytes} - */ - public abstract ByteBuf readSlice(int length); - - /** - * Transfers this buffer's data to the specified destination starting at the - * current {@code readerIndex} until the destination becomes non-writable, and - * increases the {@code readerIndex} by the number of the transferred bytes. - * This method is basically same with {@link #readBytes(ByteBuf, int, int)}, - * except that this method increases the {@code writerIndex} of the destination - * by the number of the transferred bytes while - * {@link #readBytes(ByteBuf, int, int)} does not. - * - * @throws IndexOutOfBoundsException if {@code dst.writableBytes} is greater - * than {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(ByteBuf dst); - - /** - * Transfers this buffer's data to the specified destination starting at the - * current {@code readerIndex} and increases the {@code readerIndex} by the - * number of the transferred bytes (= {@code length}). This method is basically - * same with {@link #readBytes(ByteBuf, int, int)}, except that this method - * increases the {@code writerIndex} of the destination by the number of the - * transferred bytes (= {@code length}) while - * {@link #readBytes(ByteBuf, int, int)} does not. - * - * @throws IndexOutOfBoundsException if {@code length} is greater than - * {@code this.readableBytes} or if - * {@code length} is greater than - * {@code dst.writableBytes} - */ - public abstract ByteBuf readBytes(ByteBuf dst, int length); - - /** - * Transfers this buffer's data to the specified destination starting at the - * current {@code readerIndex} and increases the {@code readerIndex} by the - * number of the transferred bytes (= {@code length}). - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is less - * than {@code 0}, if {@code length} is - * greater than {@code this.readableBytes}, or - * if {@code dstIndex + length} is greater - * than {@code dst.capacity} - */ - public abstract ByteBuf readBytes(ByteBuf dst, int dstIndex, int length); - - /** - * Transfers this buffer's data to the specified destination starting at the - * current {@code readerIndex} and increases the {@code readerIndex} by the - * number of the transferred bytes (= {@code dst.length}). - * - * @throws IndexOutOfBoundsException if {@code dst.length} is greater than - * {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(byte[] dst); - - /** - * Transfers this buffer's data to the specified destination starting at the - * current {@code readerIndex} and increases the {@code readerIndex} by the - * number of the transferred bytes (= {@code length}). - * - * @param dstIndex the first index of the destination - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException if the specified {@code dstIndex} is less - * than {@code 0}, if {@code length} is - * greater than {@code this.readableBytes}, or - * if {@code dstIndex + length} is greater - * than {@code dst.length} - */ - public abstract ByteBuf readBytes(byte[] dst, int dstIndex, int length); - - /** - * Transfers this buffer's data to the specified destination starting at the - * current {@code readerIndex} until the destination's position reaches its - * limit, and increases the {@code readerIndex} by the number of the transferred - * bytes. - * - * @throws IndexOutOfBoundsException if {@code dst.remaining()} is greater than - * {@code this.readableBytes} - */ - public abstract ByteBuf readBytes(ByteBuffer dst); - - /** - * Transfers this buffer's data to the specified stream starting at the current - * {@code readerIndex}. - * - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException if {@code length} is greater than - * {@code this.readableBytes} - * @throws IOException if the specified stream threw an exception - * during I/O - */ - public abstract ByteBuf readBytes(OutputStream out, int length) throws IOException; - /** * Increases the current {@code readerIndex} by the specified {@code length} in * this buffer. @@ -1251,6 +1487,71 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf skipBytes(int length); + /** + * Returns a slice of this buffer's readable bytes. Modifying the content of the + * returned buffer or this buffer affects each other's content while they + * maintain separate indexes and marks. This method is identical to + * {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. This method does + * not modify {@code readerIndex} or {@code writerIndex} of this buffer. + *

              + * Also be aware that this method will NOT call {@link #retain()} and so the + * reference count will NOT be increased. + */ + public abstract ByteBuf slice(); + + /** + * Returns a slice of this buffer's sub-region. Modifying the content of the + * returned buffer or this buffer affects each other's content while they + * maintain separate indexes and marks. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + *

              + * Also be aware that this method will NOT call {@link #retain()} and so the + * reference count will NOT be increased. + */ + public abstract ByteBuf slice(int index, int length); + + /** + * Returns the string representation of this buffer. This method does not + * necessarily return the whole content of the buffer but returns the values of + * the key properties such as {@link #readerIndex()}, {@link #writerIndex()} and + * {@link #capacity()}. + */ + @Override + public abstract String toString(); + + /** + * Decodes this buffer's readable bytes into a string with the specified + * character set name. This method is identical to + * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws UnsupportedCharsetException if the specified character set name is + * not supported by the current VM + */ + public abstract String toString(Charset charset); + + /** + * Decodes this buffer's sub-region into a string with the specified character + * set. This method does not modify {@code readerIndex} or {@code writerIndex} + * of this buffer. + */ + public abstract String toString(int index, int length, Charset charset); + + /** + * Return the underlying buffer instance if this buffer is a wrapper of another + * buffer. + * + * @return {@code null} if this buffer is not a wrapper + */ + public abstract ByteBuf unwrap(); + + /** + * Returns the number of writable bytes which is equal to + * {@code (this.capacity - this.writerIndex)}. + */ + public abstract int writableBytes(); + /** * Sets the specified boolean at the current {@code writerIndex} and increases * the {@code writerIndex} by {@code 1} in this buffer. @@ -1271,71 +1572,30 @@ public abstract class ByteBuf implements Comparable { public abstract ByteBuf writeByte(int value); /** - * Sets the specified 16-bit short integer at the current {@code writerIndex} - * and increases the {@code writerIndex} by {@code 2} in this buffer. The 16 - * high-order bits of the specified value are ignored. + * Transfers the specified source array's data to this buffer starting at the + * current {@code writerIndex} and increases the {@code writerIndex} by the + * number of the transferred bytes (= {@code src.length}). * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 2} + * @throws IndexOutOfBoundsException if {@code src.length} is greater than + * {@code this.writableBytes} */ - public abstract ByteBuf writeShort(int value); + public abstract ByteBuf writeBytes(byte[] src); /** - * Sets the specified 24-bit medium integer at the current {@code writerIndex} - * and increases the {@code writerIndex} by {@code 3} in this buffer. + * Transfers the specified source array's data to this buffer starting at the + * current {@code writerIndex} and increases the {@code writerIndex} by the + * number of the transferred bytes (= {@code length}). * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 3} - */ - public abstract ByteBuf writeMedium(int value); - - /** - * Sets the specified 32-bit integer at the current {@code writerIndex} and - * increases the {@code writerIndex} by {@code 4} in this buffer. + * @param srcIndex the first index of the source + * @param length the number of bytes to transfer * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 4} + * @throws IndexOutOfBoundsException if the specified {@code srcIndex} is less + * than {@code 0}, if + * {@code srcIndex + length} is greater than + * {@code src.length}, or if {@code length} is + * greater than {@code this.writableBytes} */ - public abstract ByteBuf writeInt(int value); - - /** - * Sets the specified 64-bit long integer at the current {@code writerIndex} and - * increases the {@code writerIndex} by {@code 8} in this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 8} - */ - public abstract ByteBuf writeLong(long value); - - /** - * Sets the specified 2-byte UTF-16 character at the current {@code writerIndex} - * and increases the {@code writerIndex} by {@code 2} in this buffer. The 16 - * high-order bits of the specified value are ignored. - * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 2} - */ - public abstract ByteBuf writeChar(int value); - - /** - * Sets the specified 32-bit floating point number at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 4} in - * this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 4} - */ - public abstract ByteBuf writeFloat(float value); - - /** - * Sets the specified 64-bit floating point number at the current - * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} in - * this buffer. - * - * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than - * {@code 8} - */ - public abstract ByteBuf writeDouble(double value); + public abstract ByteBuf writeBytes(byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at the @@ -1385,32 +1645,6 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf writeBytes(ByteBuf src, int srcIndex, int length); - /** - * Transfers the specified source array's data to this buffer starting at the - * current {@code writerIndex} and increases the {@code writerIndex} by the - * number of the transferred bytes (= {@code src.length}). - * - * @throws IndexOutOfBoundsException if {@code src.length} is greater than - * {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(byte[] src); - - /** - * Transfers the specified source array's data to this buffer starting at the - * current {@code writerIndex} and increases the {@code writerIndex} by the - * number of the transferred bytes (= {@code length}). - * - * @param srcIndex the first index of the source - * @param length the number of bytes to transfer - * - * @throws IndexOutOfBoundsException if the specified {@code srcIndex} is less - * than {@code 0}, if - * {@code srcIndex + length} is greater than - * {@code src.length}, or if {@code length} is - * greater than {@code this.writableBytes} - */ - public abstract ByteBuf writeBytes(byte[] src, int srcIndex, int length); - /** * Transfers the specified source buffer's data to this buffer starting at the * current {@code writerIndex} until the source buffer's position reaches its @@ -1438,6 +1672,87 @@ public abstract class ByteBuf implements Comparable { */ public abstract int writeBytes(InputStream in, int length) throws IOException; + /** + * Sets the specified 2-byte UTF-16 character at the current {@code writerIndex} + * and increases the {@code writerIndex} by {@code 2} in this buffer. The 16 + * high-order bits of the specified value are ignored. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 2} + */ + public abstract ByteBuf writeChar(int value); + + /** + * Sets the specified 64-bit floating point number at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} in + * this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 8} + */ + public abstract ByteBuf writeDouble(double value); + + /** + * Sets the specified 32-bit floating point number at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 4} in + * this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 4} + */ + public abstract ByteBuf writeFloat(float value); + + /** + * Sets the specified 32-bit integer at the current {@code writerIndex} and + * increases the {@code writerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 4} + */ + public abstract ByteBuf writeInt(int value); + + /** + * Sets the specified 64-bit long integer at the current {@code writerIndex} and + * increases the {@code writerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 8} + */ + public abstract ByteBuf writeLong(long value); + + /** + * Sets the specified 24-bit medium integer at the current {@code writerIndex} + * and increases the {@code writerIndex} by {@code 3} in this buffer. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 3} + */ + public abstract ByteBuf writeMedium(int value); + + /** + * Returns the {@code writerIndex} of this buffer. + */ + public abstract int writerIndex(); + + /** + * Sets the {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException if the specified {@code writerIndex} is + * less than {@code this.readerIndex} or + * greater than {@code this.capacity} + */ + public abstract ByteBuf writerIndex(int writerIndex); + + /** + * Sets the specified 16-bit short integer at the current {@code writerIndex} + * and increases the {@code writerIndex} by {@code 2} in this buffer. The 16 + * high-order bits of the specified value are ignored. + * + * @throws IndexOutOfBoundsException if {@code this.writableBytes} is less than + * {@code 2} + */ + public abstract ByteBuf writeShort(int value); + /** * Fills this buffer with NUL (0x00) starting at the current * {@code writerIndex} and increases the {@code writerIndex} by the specified @@ -1450,318 +1765,4 @@ public abstract class ByteBuf implements Comparable { */ public abstract ByteBuf writeZero(int length); - /** - * Locates the first occurrence of the specified {@code value} in this buffer. - * The search takes place from the specified {@code fromIndex} (inclusive) to - * the specified {@code toIndex} (exclusive). - *

              - * If {@code fromIndex} is greater than {@code toIndex}, the search is performed - * in a reversed order. - *

              - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the absolute index of the first occurrence if found. {@code -1} - * otherwise. - */ - public abstract int indexOf(int fromIndex, int toIndex, byte value); - - /** - * Locates the first occurrence of the specified {@code value} in this buffer. - * The search takes place from the current {@code readerIndex} (inclusive) to - * the current {@code writerIndex} (exclusive). - *

              - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the number of bytes between the current {@code readerIndex} and the - * first occurrence if found. {@code -1} otherwise. - */ - public abstract int bytesBefore(byte value); - - /** - * Locates the first occurrence of the specified {@code value} in this buffer. - * The search starts from the current {@code readerIndex} (inclusive) and lasts - * for the specified {@code length}. - *

              - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the number of bytes between the current {@code readerIndex} and the - * first occurrence if found. {@code -1} otherwise. - * - * @throws IndexOutOfBoundsException if {@code length} is greater than - * {@code this.readableBytes} - */ - public abstract int bytesBefore(int length, byte value); - - /** - * Locates the first occurrence of the specified {@code value} in this buffer. - * The search starts from the specified {@code index} (inclusive) and lasts for - * the specified {@code length}. - *

              - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @return the number of bytes between the specified {@code index} and the first - * occurrence if found. {@code -1} otherwise. - * - * @throws IndexOutOfBoundsException if {@code index + length} is greater than - * {@code this.capacity} - */ - public abstract int bytesBefore(int index, int length, byte value); - /** - * Returns a copy of this buffer's readable bytes. Modifying the content of the - * returned buffer or this buffer does not affect each other at all. This method - * is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - */ - public abstract ByteBuf copy(); - - /** - * Returns a copy of this buffer's sub-region. Modifying the content of the - * returned buffer or this buffer does not affect each other at all. This method - * does not modify {@code readerIndex} or {@code writerIndex} of this buffer. - */ - public abstract ByteBuf copy(int index, int length); - - /** - * Returns a slice of this buffer's readable bytes. Modifying the content of the - * returned buffer or this buffer affects each other's content while they - * maintain separate indexes and marks. This method is identical to - * {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. This method does - * not modify {@code readerIndex} or {@code writerIndex} of this buffer. - *

              - * Also be aware that this method will NOT call {@link #retain()} and so the - * reference count will NOT be increased. - */ - public abstract ByteBuf slice(); - - /** - * Returns a slice of this buffer's sub-region. Modifying the content of the - * returned buffer or this buffer affects each other's content while they - * maintain separate indexes and marks. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - *

              - * Also be aware that this method will NOT call {@link #retain()} and so the - * reference count will NOT be increased. - */ - public abstract ByteBuf slice(int index, int length); - - /** - * Returns a buffer which shares the whole region of this buffer. Modifying the - * content of the returned buffer or this buffer affects each other's content - * while they maintain separate indexes and marks. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. - *

              - * The reader and writer marks will not be duplicated. Also be aware that this - * method will NOT call {@link #retain()} and so the reference count will NOT be - * increased. - * - * @return A buffer whose readable content is equivalent to the buffer returned - * by {@link #slice()}. However this buffer will share the capacity of - * the underlying buffer, and therefore allows access to all of the - * underlying content if necessary. - */ - public abstract ByteBuf duplicate(); - - /** - * Returns the maximum number of NIO {@link ByteBuffer}s that consist this - * buffer. Note that {@link #nioBuffers()} or {@link #nioBuffers(int, int)} - * might return a less number of {@link ByteBuffer}s. - * - * @return {@code -1} if this buffer has no underlying {@link ByteBuffer}. the - * number of the underlying {@link ByteBuffer}s if this buffer has at - * least one underlying {@link ByteBuffer}. Note that this method does - * not return {@code 0} to avoid confusion. - * - * @see #nioBuffer() - * @see #nioBuffer(int, int) - * @see #nioBuffers() - * @see #nioBuffers(int, int) - */ - public abstract int nioBufferCount(); - - /** - * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}. The - * returned buffer either share or contains the copied content of this buffer, - * while changing the position and limit of the returned NIO buffer does not - * affect the indexes and marks of this buffer. This method is identical to - * {@code buf.nioBuffer(buf.readerIndex(), buf.readableBytes())}. This method - * does not modify {@code readerIndex} or {@code writerIndex} of this buffer. - * Please note that the returned NIO buffer will not see the changes of this - * buffer if this buffer is a dynamic buffer and it adjusted its capacity. - * - * @throws UnsupportedOperationException if this buffer cannot create a - * {@link ByteBuffer} that shares the - * content with itself - * - * @see #nioBufferCount() - * @see #nioBuffers() - * @see #nioBuffers(int, int) - */ - public abstract ByteBuffer nioBuffer(); - - /** - * Exposes this buffer's sub-region as an NIO {@link ByteBuffer}. The returned - * buffer either share or contains the copied content of this buffer, while - * changing the position and limit of the returned NIO buffer does not affect - * the indexes and marks of this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. Please note that - * the returned NIO buffer will not see the changes of this buffer if this - * buffer is a dynamic buffer and it adjusted its capacity. - * - * @throws UnsupportedOperationException if this buffer cannot create a - * {@link ByteBuffer} that shares the - * content with itself - * - * @see #nioBufferCount() - * @see #nioBuffers() - * @see #nioBuffers(int, int) - */ - public abstract ByteBuffer nioBuffer(int index, int length); - - /** - * Internal use only: Exposes the internal NIO buffer. - */ - public abstract ByteBuffer internalNioBuffer(int index, int length); - - /** - * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}'s. The - * returned buffer either share or contains the copied content of this buffer, - * while changing the position and limit of the returned NIO buffer does not - * affect the indexes and marks of this buffer. This method does not modify - * {@code readerIndex} or {@code writerIndex} of this buffer. Please note that - * the returned NIO buffer will not see the changes of this buffer if this - * buffer is a dynamic buffer and it adjusted its capacity. - * - * - * @throws UnsupportedOperationException if this buffer cannot create a - * {@link ByteBuffer} that shares the - * content with itself - * - * @see #nioBufferCount() - * @see #nioBuffer() - * @see #nioBuffer(int, int) - */ - public abstract ByteBuffer[] nioBuffers(); - - /** - * Exposes this buffer's bytes as an NIO {@link ByteBuffer}'s for the specified - * index and length The returned buffer either share or contains the copied - * content of this buffer, while changing the position and limit of the returned - * NIO buffer does not affect the indexes and marks of this buffer. This method - * does not modify {@code readerIndex} or {@code writerIndex} of this buffer. - * Please note that the returned NIO buffer will not see the changes of this - * buffer if this buffer is a dynamic buffer and it adjusted its capacity. - * - * @throws UnsupportedOperationException if this buffer cannot create a - * {@link ByteBuffer} that shares the - * content with itself - * - * @see #nioBufferCount() - * @see #nioBuffer() - * @see #nioBuffer(int, int) - */ - public abstract ByteBuffer[] nioBuffers(int index, int length); - - /** - * Returns {@code true} if and only if this buffer has a backing byte array. If - * this method returns true, you can safely call {@link #array()} and - * {@link #arrayOffset()}. - */ - public abstract boolean hasArray(); - - /** - * Returns the backing byte array of this buffer. - * - * @throws UnsupportedOperationException if there no accessible backing byte - * array - */ - public abstract byte[] array(); - - /** - * Returns the offset of the first byte within the backing byte array of this - * buffer. - * - * @throws UnsupportedOperationException if there no accessible backing byte - * array - */ - public abstract int arrayOffset(); - - /** - * Returns {@code true} if and only if this buffer has a reference to the - * low-level memory address that points to the backing data. - */ - public abstract boolean hasMemoryAddress(); - - /** - * Returns the low-level memory address that point to the first byte of ths - * backing data. - * - * @throws UnsupportedOperationException if this buffer does not support - * accessing the low-level memory address - */ - public abstract long memoryAddress(); - - /** - * Decodes this buffer's readable bytes into a string with the specified - * character set name. This method is identical to - * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. - * This method does not modify {@code readerIndex} or {@code writerIndex} of - * this buffer. - * - * @throws UnsupportedCharsetException if the specified character set name is - * not supported by the current VM - */ - public abstract String toString(Charset charset); - - /** - * Decodes this buffer's sub-region into a string with the specified character - * set. This method does not modify {@code readerIndex} or {@code writerIndex} - * of this buffer. - */ - public abstract String toString(int index, int length, Charset charset); - - /** - * Returns a hash code which was calculated from the content of this buffer. If - * there's a byte array which is {@linkplain #equals(Object) equal to} this - * array, both arrays should return the same value. - */ - @Override - public abstract int hashCode(); - - /** - * Determines if the content of the specified buffer is identical to the content - * of this array. 'Identical' here means: - *

                - *
              • the size of the contents of the two buffers are same and
              • - *
              • every single byte of the content of the two buffers are same.
              • - *
              - * Please note that it does not compare {@link #readerIndex()} nor - * {@link #writerIndex()}. This method also returns {@code false} for - * {@code null} and an object which is not an instance of {@link ByteBuf} type. - */ - @Override - public abstract boolean equals(Object obj); - - /** - * Compares the content of the specified buffer to the content of this buffer. - * Comparison is performed in the same manner with the string comparison - * functions of various languages such as {@code strcmp}, {@code memcmp} and - * {@link String#compareTo(String)}. - */ - @Override - public abstract int compareTo(ByteBuf buffer); - - /** - * Returns the string representation of this buffer. This method does not - * necessarily return the whole content of the buffer but returns the values of - * the key properties such as {@link #readerIndex()}, {@link #writerIndex()} and - * {@link #capacity()}. - */ - @Override - public abstract String toString(); - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufEaglercraftImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufEaglercraftImpl.java index 118576e3..3f3c80a5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufEaglercraftImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufEaglercraftImpl.java @@ -9,14 +9,15 @@ import java.nio.ByteOrder; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,12 +25,12 @@ import java.nio.ByteOrder; public class ByteBufEaglercraftImpl extends AbstractByteBuf { private ByteBuffer internal; - + public ByteBufEaglercraftImpl(ByteBuffer internal, int maxCapacity) { super(maxCapacity); - if(internal.order() != ByteOrder.BIG_ENDIAN) { + if (internal.order() != ByteOrder.BIG_ENDIAN) { this.internal = internal.order(ByteOrder.BIG_ENDIAN); - }else { + } else { this.internal = internal; } } @@ -39,17 +40,6 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { return internal.get(index); } - @Override - protected short _getShort(int index) { - return internal.getShort(index); - } - - @Override - protected int _getUnsignedMedium(int index) { - return ((internal.get(index) & 0xFF) << 16) | ((internal.get(index + 1) & 0xFF) << 8) | - (internal.get(index + 2) & 0xFF); - } - @Override protected int _getInt(int index) { return internal.getInt(index); @@ -60,21 +50,20 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { return internal.getLong(index); } + @Override + protected short _getShort(int index) { + return internal.getShort(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return ((internal.get(index) & 0xFF) << 16) | ((internal.get(index + 1) & 0xFF) << 8) + | (internal.get(index + 2) & 0xFF); + } + @Override protected void _setByte(int index, int value) { - internal.put(index, (byte)value); - } - - @Override - protected void _setShort(int index, int value) { - internal.putShort(index, (short)value); - } - - @Override - protected void _setMedium(int index, int value) { - internal.put(index, (byte)((value >>> 16) & 0xFF)); - internal.put(index + 1, (byte)((value >>> 8) & 0xFF)); - internal.put(index + 2, (byte)(value & 0xFF)); + internal.put(index, (byte) value); } @Override @@ -87,6 +76,28 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { internal.putLong(index, value); } + @Override + protected void _setMedium(int index, int value) { + internal.put(index, (byte) ((value >>> 16) & 0xFF)); + internal.put(index + 1, (byte) ((value >>> 8) & 0xFF)); + internal.put(index + 2, (byte) (value & 0xFF)); + } + + @Override + protected void _setShort(int index, int value) { + internal.putShort(index, (short) value); + } + + @Override + public byte[] array() { + return internal.array(); + } + + @Override + public int arrayOffset() { + return 0; + } + @Override public int capacity() { return internal.capacity(); @@ -94,8 +105,8 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { @Override public ByteBuf capacity(int newCapacity) { - if(newCapacity > internal.capacity()) { - ByteBuffer newCap = ByteBuffer.wrap(new byte[(int)(newCapacity * 1.5f)]); + if (newCapacity > internal.capacity()) { + ByteBuffer newCap = ByteBuffer.wrap(new byte[(int) (newCapacity * 1.5f)]); NioBufferFunctions.put(newCap, 0, internal, 0, internal.capacity()); newCap.clear(); internal = newCap; @@ -104,32 +115,15 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { } @Override - public ByteOrder order() { - return ByteOrder.BIG_ENDIAN; + public ByteBuf copy(int index, int length) { + byte[] cpy = new byte[length]; + NioBufferFunctions.get(internal, index, cpy); + return new ByteBufEaglercraftImpl(ByteBuffer.wrap(cpy), maxCapacity()); } @Override - public ByteBuf order(ByteOrder endianness) { - throw new UnsupportedOperationException("Not supported as it is not used by Eaglercraft"); - } - - @Override - public ByteBuf unwrap() { - return this; - } - - @Override - public boolean isDirect() { - return false; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - if(!(dst instanceof ByteBufEaglercraftImpl)) { - throw new IllegalArgumentException("The buffer passed is not an Eaglercraft byte buffer!"); - } - NioBufferFunctions.put(((ByteBufEaglercraftImpl)dst).internal, dstIndex, internal, index, length); - return this; + public ByteBuf duplicate() { + return new ByteBufEaglercraftImpl(internal.duplicate(), maxCapacity()); } @Override @@ -138,6 +132,15 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { return this; } + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + if (!(dst instanceof ByteBufEaglercraftImpl)) { + throw new IllegalArgumentException("The buffer passed is not an Eaglercraft byte buffer!"); + } + NioBufferFunctions.put(((ByteBufEaglercraftImpl) dst).internal, dstIndex, internal, index, length); + return this; + } + @Override public ByteBuf getBytes(int index, ByteBuffer dst) { NioBufferFunctions.put(dst, dst.position(), internal, index, dst.remaining()); @@ -154,12 +157,56 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { } @Override - public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { - if(!(src instanceof ByteBufEaglercraftImpl)) { - throw new IllegalArgumentException("The buffer passed is not an Eaglercraft byte buffer!"); - } - NioBufferFunctions.put(internal, index, ((ByteBufEaglercraftImpl)src).internal, srcIndex, length); - return this; + public boolean hasArray() { + return true; + } + + @Override + public boolean hasMemoryAddress() { + return false; + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + internal.position(index).limit(index + length); + return internal; + } + + @Override + public boolean isDirect() { + return false; + } + + @Override + public long memoryAddress() { + return 0; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + // return internal.slice(index, length); + throw new UnsupportedOperationException("Not supported in JDK 8"); + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + // return new ByteBuffer[] { internal.slice(index, length) }; + throw new UnsupportedOperationException("Not supported in JDK 8"); + } + + @Override + public ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + @Override + public ByteBuf order(ByteOrder endianness) { + throw new UnsupportedOperationException("Not supported as it is not used by Eaglercraft"); } @Override @@ -168,6 +215,15 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { return this; } + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + if (!(src instanceof ByteBufEaglercraftImpl)) { + throw new IllegalArgumentException("The buffer passed is not an Eaglercraft byte buffer!"); + } + NioBufferFunctions.put(internal, index, ((ByteBufEaglercraftImpl) src).internal, srcIndex, length); + return this; + } + @Override public ByteBuf setBytes(int index, ByteBuffer src) { NioBufferFunctions.put(internal, index, src, src.position(), src.remaining()); @@ -179,76 +235,22 @@ public class ByteBufEaglercraftImpl extends AbstractByteBuf { public int setBytes(int index, InputStream in, int length) throws IOException { byte[] buf = new byte[length]; int r = in.read(buf, 0, length); - if(r > 0) { + if (r > 0) { NioBufferFunctions.put(internal, index, buf, 0, r); } return r; } - @Override - public ByteBuf copy(int index, int length) { - byte[] cpy = new byte[length]; - NioBufferFunctions.get(internal, index, cpy); - return new ByteBufEaglercraftImpl(ByteBuffer.wrap(cpy), maxCapacity()); - } - - @Override - public int nioBufferCount() { - return 1; - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - //return internal.slice(index, length); - throw new UnsupportedOperationException("Not supported in JDK 8"); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - internal.position(index).limit(index + length); - return internal; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - //return new ByteBuffer[] { internal.slice(index, length) }; - throw new UnsupportedOperationException("Not supported in JDK 8"); - } - - @Override - public boolean hasArray() { - return true; - } - - @Override - public byte[] array() { - return internal.array(); - } - - @Override - public int arrayOffset() { - return 0; - } - - @Override - public boolean hasMemoryAddress() { - return false; - } - - @Override - public long memoryAddress() { - return 0; - } - @Override public ByteBuf slice(int index, int length) { - //return new ByteBufEaglercraftImpl(internal.slice(index, length), maxCapacity()); + // return new ByteBufEaglercraftImpl(internal.slice(index, length), + // maxCapacity()); throw new UnsupportedOperationException("Not supported in JDK 8"); } @Override - public ByteBuf duplicate() { - return new ByteBufEaglercraftImpl(internal.duplicate(), maxCapacity()); + public ByteBuf unwrap() { + return this; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufInputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufInputStream.java index 92e0ae5d..5cf33218 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufInputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufInputStream.java @@ -50,6 +50,8 @@ public class ByteBufInputStream extends InputStream implements DataInput { */ private boolean releaseOnClose; + private final StringBuilder lineBuf = new StringBuilder(); + /** * Creates a new stream which reads data from the specified {@code buffer} * starting at the current {@code readerIndex} and ending at the current @@ -62,21 +64,6 @@ public class ByteBufInputStream extends InputStream implements DataInput { this(buffer, buffer.readableBytes()); } - /** - * Creates a new stream which reads data from the specified {@code buffer} - * starting at the current {@code readerIndex} and ending at - * {@code readerIndex + length}. - * - * @param buffer The buffer which provides the content for this - * {@link InputStream}. - * @param length The length of the buffer to use for this {@link InputStream}. - * @throws IndexOutOfBoundsException if {@code readerIndex + length} is greater - * than {@code writerIndex} - */ - public ByteBufInputStream(ByteBuf buffer, int length) { - this(buffer, length, false); - } - /** * Creates a new stream which reads data from the specified {@code buffer} * starting at the current {@code readerIndex} and ending at the current @@ -92,6 +79,21 @@ public class ByteBufInputStream extends InputStream implements DataInput { this(buffer, buffer.readableBytes(), releaseOnClose); } + /** + * Creates a new stream which reads data from the specified {@code buffer} + * starting at the current {@code readerIndex} and ending at + * {@code readerIndex + length}. + * + * @param buffer The buffer which provides the content for this + * {@link InputStream}. + * @param length The length of the buffer to use for this {@link InputStream}. + * @throws IndexOutOfBoundsException if {@code readerIndex + length} is greater + * than {@code writerIndex} + */ + public ByteBufInputStream(ByteBuf buffer, int length) { + this(buffer, length, false); + } + /** * Creates a new stream which reads data from the specified {@code buffer} * starting at the current {@code readerIndex} and ending at @@ -126,18 +128,20 @@ public class ByteBufInputStream extends InputStream implements DataInput { buffer.markReaderIndex(); } - /** - * Returns the number of read bytes by this stream so far. - */ - public int readBytes() { - return buffer.readerIndex() - startIndex; - } - @Override public int available() throws IOException { return endIndex - buffer.readerIndex(); } + private void checkAvailable(int fieldSize) throws IOException { + if (fieldSize < 0) { + throw new IndexOutOfBoundsException("fieldSize cannot be a negative number"); + } + if (fieldSize > available()) { + throw new EOFException("fieldSize is too long! Length is " + fieldSize + ", but maximum is " + available()); + } + } + @Override public void mark(int readlimit) { buffer.markReaderIndex(); @@ -168,20 +172,6 @@ public class ByteBufInputStream extends InputStream implements DataInput { return len; } - @Override - public void reset() throws IOException { - buffer.resetReaderIndex(); - } - - @Override - public long skip(long n) throws IOException { - if (n > Integer.MAX_VALUE) { - return skipBytes(Integer.MAX_VALUE); - } else { - return skipBytes((int) n); - } - } - @Override public boolean readBoolean() throws IOException { checkAvailable(1); @@ -196,6 +186,13 @@ public class ByteBufInputStream extends InputStream implements DataInput { return buffer.readByte(); } + /** + * Returns the number of read bytes by this stream so far. + */ + public int readBytes() { + return buffer.readerIndex() - startIndex; + } + @Override public char readChar() throws IOException { return (char) readShort(); @@ -228,8 +225,6 @@ public class ByteBufInputStream extends InputStream implements DataInput { return buffer.readInt(); } - private final StringBuilder lineBuf = new StringBuilder(); - @Override public String readLine() throws IOException { lineBuf.setLength(0); @@ -270,11 +265,6 @@ public class ByteBufInputStream extends InputStream implements DataInput { return buffer.readShort(); } - @Override - public String readUTF() throws IOException { - return DataInputStream.readUTF(this); - } - @Override public int readUnsignedByte() throws IOException { return readByte() & 0xff; @@ -285,19 +275,29 @@ public class ByteBufInputStream extends InputStream implements DataInput { return readShort() & 0xffff; } + @Override + public String readUTF() throws IOException { + return DataInputStream.readUTF(this); + } + + @Override + public void reset() throws IOException { + buffer.resetReaderIndex(); + } + + @Override + public long skip(long n) throws IOException { + if (n > Integer.MAX_VALUE) { + return skipBytes(Integer.MAX_VALUE); + } else { + return skipBytes((int) n); + } + } + @Override public int skipBytes(int n) throws IOException { int nBytes = Math.min(available(), n); buffer.skipBytes(nBytes); return nBytes; } - - private void checkAvailable(int fieldSize) throws IOException { - if (fieldSize < 0) { - throw new IndexOutOfBoundsException("fieldSize cannot be a negative number"); - } - if (fieldSize > available()) { - throw new EOFException("fieldSize is too long! Length is " + fieldSize + ", but maximum is " + available()); - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufOutputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufOutputStream.java index 38e80896..501a1181 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufOutputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufOutputStream.java @@ -52,10 +52,15 @@ public class ByteBufOutputStream extends OutputStream implements DataOutput { } /** - * Returns the number of written bytes by this stream so far. + * Returns the buffer where this stream is writing data. */ - public int writtenBytes() { - return buffer.writerIndex() - startIndex; + public ByteBuf buffer() { + return buffer; + } + + @Override + public void write(byte[] b) throws IOException { + buffer.writeBytes(b); } @Override @@ -67,11 +72,6 @@ public class ByteBufOutputStream extends OutputStream implements DataOutput { buffer.writeBytes(b, off, len); } - @Override - public void write(byte[] b) throws IOException { - buffer.writeBytes(b); - } - @Override public void write(int b) throws IOException { buffer.writeByte(b); @@ -136,9 +136,9 @@ public class ByteBufOutputStream extends OutputStream implements DataOutput { } /** - * Returns the buffer where this stream is writing data. + * Returns the number of written bytes by this stream so far. */ - public ByteBuf buffer() { - return buffer; + public int writtenBytes() { + return buffer.writerIndex() - startIndex; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufUtil.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufUtil.java index e0408238..5ff5c772 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufUtil.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ByteBufUtil.java @@ -15,7 +15,7 @@ */ package net.lax1dude.eaglercraft.v1_8.netty; -import net.lax1dude.eaglercraft.v1_8.EagUtils; +import static net.lax1dude.eaglercraft.v1_8.netty.ObjectUtil.checkNotNull; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -27,7 +27,7 @@ import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.StandardCharsets; -import static net.lax1dude.eaglercraft.v1_8.netty.ObjectUtil.checkNotNull; +import net.lax1dude.eaglercraft.v1_8.EagUtils; /** * A collection of utility methods that is related with handling @@ -39,93 +39,6 @@ public final class ByteBufUtil { private static final byte WRITE_UTF_UNKNOWN = (byte) '?'; private static final int MAX_BYTES_PER_CHAR_UTF8 = 3; - /** - * Decode a 2-digit hex byte from within a string. - */ - public static byte decodeHexByte(CharSequence s, int pos) { - return (byte)EagUtils.decodeHexByte(s, pos); - } - - /** - * Calculates the hash code of the specified buffer. This method is useful when - * implementing a new buffer type. - */ - public static int hashCode(ByteBuf buffer) { - final int aLen = buffer.readableBytes(); - final int intCount = aLen >>> 2; - final int byteCount = aLen & 3; - - int hashCode = 1; - int arrayIndex = buffer.readerIndex(); - if (buffer.order() == ByteOrder.BIG_ENDIAN) { - for (int i = intCount; i > 0; i--) { - hashCode = 31 * hashCode + buffer.getInt(arrayIndex); - arrayIndex += 4; - } - } else { - for (int i = intCount; i > 0; i--) { - hashCode = 31 * hashCode + swapInt(buffer.getInt(arrayIndex)); - arrayIndex += 4; - } - } - - for (int i = byteCount; i > 0; i--) { - hashCode = 31 * hashCode + buffer.getByte(arrayIndex++); - } - - if (hashCode == 0) { - hashCode = 1; - } - - return hashCode; - } - - /** - * Returns {@code true} if and only if the two specified buffers are identical - * to each other as described in {@code ChannelBuffer#equals(Object)}. This - * method is useful when implementing a new buffer type. - */ - public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { - final int aLen = bufferA.readableBytes(); - if (aLen != bufferB.readableBytes()) { - return false; - } - - final int longCount = aLen >>> 3; - final int byteCount = aLen & 7; - - int aIndex = bufferA.readerIndex(); - int bIndex = bufferB.readerIndex(); - - if (bufferA.order() == bufferB.order()) { - for (int i = longCount; i > 0; i--) { - if (bufferA.getLong(aIndex) != bufferB.getLong(bIndex)) { - return false; - } - aIndex += 8; - bIndex += 8; - } - } else { - for (int i = longCount; i > 0; i--) { - if (bufferA.getLong(aIndex) != swapLong(bufferB.getLong(bIndex))) { - return false; - } - aIndex += 8; - bIndex += 8; - } - } - - for (int i = byteCount; i > 0; i--) { - if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { - return false; - } - aIndex++; - bIndex++; - } - - return true; - } - /** * Compares the two specified buffers as described in * {@link ByteBuf#compareTo(ByteBuf)}. This method is useful when implementing a @@ -181,18 +94,6 @@ public final class ByteBufUtil { return 0; } - private static long compareUintLittleEndian(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, - int uintCountIncrement) { - for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { - long comp = (swapInt(bufferA.getInt(aIndex)) & 0xFFFFFFFFL) - - (swapInt(bufferB.getInt(bIndex)) & 0xFFFFFFFFL); - if (comp != 0) { - return comp; - } - } - return 0; - } - private static long compareUintBigEndianA(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, int uintCountIncrement) { for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { @@ -215,171 +116,49 @@ public final class ByteBufUtil { return 0; } - /** - * The default implementation of {@link ByteBuf#indexOf(int, int, byte)}. This - * method is useful when implementing a new buffer type. - */ - public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { - if (fromIndex <= toIndex) { - return firstIndexOf(buffer, fromIndex, toIndex, value); - } else { - return lastIndexOf(buffer, fromIndex, toIndex, value); - } - } - - /** - * Toggles the endianness of the specified 16-bit short integer. - */ - public static short swapShort(short value) { - return Short.reverseBytes(value); - } - - /** - * Toggles the endianness of the specified 24-bit medium integer. - */ - public static int swapMedium(int value) { - int swapped = value << 16 & 0xff0000 | value & 0xff00 | value >>> 16 & 0xff; - if ((swapped & 0x800000) != 0) { - swapped |= 0xff000000; - } - return swapped; - } - - /** - * Toggles the endianness of the specified 32-bit integer. - */ - public static int swapInt(int value) { - return Integer.reverseBytes(value); - } - - /** - * Toggles the endianness of the specified 64-bit long integer. - */ - public static long swapLong(long value) { - return Long.reverseBytes(value); - } - - /** - * Read the given amount of bytes into a new {@link ByteBuf} that is allocated - * from the {@link ByteBufAllocator}. - */ - public static ByteBuf readBytes(ByteBuf buffer, int length) { - ByteBuf dst = Unpooled.buffer(length); - buffer.readBytes(dst); - return dst; - } - - private static int firstIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { - fromIndex = Math.max(fromIndex, 0); - if (fromIndex >= toIndex || buffer.capacity() == 0) { - return -1; - } - for(int i = fromIndex; i < toIndex; ++i) { - if(buffer.getByte(i) == value) { - return i; + private static long compareUintLittleEndian(ByteBuf bufferA, ByteBuf bufferB, int aIndex, int bIndex, + int uintCountIncrement) { + for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4) { + long comp = (swapInt(bufferA.getInt(aIndex)) & 0xFFFFFFFFL) + - (swapInt(bufferB.getInt(bIndex)) & 0xFFFFFFFFL); + if (comp != 0) { + return comp; } } - return -1; - } - - private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { - fromIndex = Math.min(fromIndex, buffer.capacity()); - if (fromIndex < 0 || buffer.capacity() == 0) { - return -1; - } - for(int i = fromIndex; i > toIndex; --i) { - if(buffer.getByte(i) == value) { - return i; - } - } - return -1; + return 0; } /** - * Encode a {@link CharSequence} in - * UTF-8 and write it to a - * {@link ByteBuf} allocated with {@code alloc}. - * - * @param alloc The allocator used to allocate a new {@link ByteBuf}. - * @param seq The characters to write into a buffer. - * @return The {@link ByteBuf} which contains the - * UTF-8 encoded - * result. + * Decode a 2-digit hex byte from within a string. */ - public static ByteBuf writeUtf8(CharSequence seq) { - // UTF-8 uses max. 3 bytes per char, so calculate the worst case. - ByteBuf buf = Unpooled.buffer(seq.length() * MAX_BYTES_PER_CHAR_UTF8); - writeUtf8(buf, seq); - return buf; + public static byte decodeHexByte(CharSequence s, int pos) { + return (byte) EagUtils.decodeHexByte(s, pos); } - /** - * Encode a {@link CharSequence} in - * UTF-8 and write it to a - * {@link ByteBuf}. - * - * This method returns the actual number of bytes written. - */ - public static int writeUtf8(ByteBuf buf, CharSequence seq) { - final int len = seq.length(); - buf.ensureWritable(len * MAX_BYTES_PER_CHAR_UTF8); - byte[] bytes = seq.toString().getBytes(StandardCharsets.UTF_8); - buf.writeBytes(bytes); - return bytes.length; - } - - // Fast-Path implementation - private static int writeUtf8(AbstractByteBuf buffer, CharSequence seq, int len) { - int oldWriterIndex = buffer.writerIndex; - int writerIndex = oldWriterIndex; - - // We can use the _set methods as these not need to do any index checks and - // reference checks. - // This is possible as we called ensureWritable(...) before. - for (int i = 0; i < len; i++) { - char c = seq.charAt(i); - if (c < 0x80) { - buffer._setByte(writerIndex++, (byte) c); - } else if (c < 0x800) { - buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6))); - buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); - } else if (c >= '\uD800' && c <= '\uDFFF') { // isSurrogate(c) - if (!Character.isHighSurrogate(c)) { - buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); - continue; - } - final char c2; - try { - // Surrogate Pair consumes 2 characters. Optimistically try to get the next - // character to avoid - // duplicate bounds checking with charAt. If an IndexOutOfBoundsException is - // thrown we will - // re-throw a more informative exception describing the problem. - c2 = seq.charAt(++i); - } catch (IndexOutOfBoundsException e) { - buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); - break; - } - if (!Character.isLowSurrogate(c2)) { - buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); - buffer._setByte(writerIndex++, Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2); - continue; - } - int codePoint = Character.toCodePoint(c, c2); - // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. - buffer._setByte(writerIndex++, (byte) (0xf0 | (codePoint >> 18))); - buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 12) & 0x3f))); - buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 6) & 0x3f))); - buffer._setByte(writerIndex++, (byte) (0x80 | (codePoint & 0x3f))); - } else { - buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12))); - buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f))); - buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); - } + static String decodeString(ByteBuf src, int readerIndex, int len, Charset charset) { + if (len == 0) { + return ""; + } + final CharsetDecoder decoder = charset.newDecoder(); + final int maxLength = (int) ((double) len * decoder.maxCharsPerByte()); + CharBuffer dst = CharBuffer.wrap(new char[maxLength]); + decodeString(decoder, src.nioBuffer(readerIndex, len), dst); + return dst.flip().toString(); + } + + private static void decodeString(CharsetDecoder decoder, ByteBuffer src, CharBuffer dst) { + try { + CoderResult cr = decoder.decode(src, dst, true); + if (!cr.isUnderflow()) { + cr.throwException(); + } + cr = decoder.flush(dst); + if (!cr.isUnderflow()) { + cr.throwException(); + } + } catch (CharacterCodingException x) { + throw new IllegalStateException(x); } - // update the writerIndex without any extra checks for performance reasons - buffer.writerIndex = writerIndex; - return writerIndex - oldWriterIndex; } /** @@ -412,29 +191,108 @@ public final class ByteBufUtil { } } - static String decodeString(ByteBuf src, int readerIndex, int len, Charset charset) { - if (len == 0) { - return ""; + /** + * Returns {@code true} if and only if the two specified buffers are identical + * to each other as described in {@code ChannelBuffer#equals(Object)}. This + * method is useful when implementing a new buffer type. + */ + public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { + final int aLen = bufferA.readableBytes(); + if (aLen != bufferB.readableBytes()) { + return false; } - final CharsetDecoder decoder = charset.newDecoder(); - final int maxLength = (int) ((double) len * decoder.maxCharsPerByte()); - CharBuffer dst = CharBuffer.wrap(new char[maxLength]); - decodeString(decoder, src.nioBuffer(readerIndex, len), dst); - return dst.flip().toString(); + + final int longCount = aLen >>> 3; + final int byteCount = aLen & 7; + + int aIndex = bufferA.readerIndex(); + int bIndex = bufferB.readerIndex(); + + if (bufferA.order() == bufferB.order()) { + for (int i = longCount; i > 0; i--) { + if (bufferA.getLong(aIndex) != bufferB.getLong(bIndex)) { + return false; + } + aIndex += 8; + bIndex += 8; + } + } else { + for (int i = longCount; i > 0; i--) { + if (bufferA.getLong(aIndex) != swapLong(bufferB.getLong(bIndex))) { + return false; + } + aIndex += 8; + bIndex += 8; + } + } + + for (int i = byteCount; i > 0; i--) { + if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { + return false; + } + aIndex++; + bIndex++; + } + + return true; } - private static void decodeString(CharsetDecoder decoder, ByteBuffer src, CharBuffer dst) { - try { - CoderResult cr = decoder.decode(src, dst, true); - if (!cr.isUnderflow()) { - cr.throwException(); + private static int firstIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { + fromIndex = Math.max(fromIndex, 0); + if (fromIndex >= toIndex || buffer.capacity() == 0) { + return -1; + } + for (int i = fromIndex; i < toIndex; ++i) { + if (buffer.getByte(i) == value) { + return i; } - cr = decoder.flush(dst); - if (!cr.isUnderflow()) { - cr.throwException(); + } + return -1; + } + + /** + * Calculates the hash code of the specified buffer. This method is useful when + * implementing a new buffer type. + */ + public static int hashCode(ByteBuf buffer) { + final int aLen = buffer.readableBytes(); + final int intCount = aLen >>> 2; + final int byteCount = aLen & 3; + + int hashCode = 1; + int arrayIndex = buffer.readerIndex(); + if (buffer.order() == ByteOrder.BIG_ENDIAN) { + for (int i = intCount; i > 0; i--) { + hashCode = 31 * hashCode + buffer.getInt(arrayIndex); + arrayIndex += 4; } - } catch (CharacterCodingException x) { - throw new IllegalStateException(x); + } else { + for (int i = intCount; i > 0; i--) { + hashCode = 31 * hashCode + swapInt(buffer.getInt(arrayIndex)); + arrayIndex += 4; + } + } + + for (int i = byteCount; i > 0; i--) { + hashCode = 31 * hashCode + buffer.getByte(arrayIndex++); + } + + if (hashCode == 0) { + hashCode = 1; + } + + return hashCode; + } + + /** + * The default implementation of {@link ByteBuf#indexOf(int, int, byte)}. This + * method is useful when implementing a new buffer type. + */ + public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { + if (fromIndex <= toIndex) { + return firstIndexOf(buffer, fromIndex, toIndex, value); + } else { + return lastIndexOf(buffer, fromIndex, toIndex, value); } } @@ -593,6 +451,148 @@ public final class ByteBufUtil { return true; } + private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { + fromIndex = Math.min(fromIndex, buffer.capacity()); + if (fromIndex < 0 || buffer.capacity() == 0) { + return -1; + } + for (int i = fromIndex; i > toIndex; --i) { + if (buffer.getByte(i) == value) { + return i; + } + } + return -1; + } + + /** + * Read the given amount of bytes into a new {@link ByteBuf} that is allocated + * from the {@link ByteBufAllocator}. + */ + public static ByteBuf readBytes(ByteBuf buffer, int length) { + ByteBuf dst = Unpooled.buffer(length); + buffer.readBytes(dst); + return dst; + } + + /** + * Toggles the endianness of the specified 32-bit integer. + */ + public static int swapInt(int value) { + return Integer.reverseBytes(value); + } + + /** + * Toggles the endianness of the specified 64-bit long integer. + */ + public static long swapLong(long value) { + return Long.reverseBytes(value); + } + + /** + * Toggles the endianness of the specified 24-bit medium integer. + */ + public static int swapMedium(int value) { + int swapped = value << 16 & 0xff0000 | value & 0xff00 | value >>> 16 & 0xff; + if ((swapped & 0x800000) != 0) { + swapped |= 0xff000000; + } + return swapped; + } + + /** + * Toggles the endianness of the specified 16-bit short integer. + */ + public static short swapShort(short value) { + return Short.reverseBytes(value); + } + + // Fast-Path implementation + private static int writeUtf8(AbstractByteBuf buffer, CharSequence seq, int len) { + int oldWriterIndex = buffer.writerIndex; + int writerIndex = oldWriterIndex; + + // We can use the _set methods as these not need to do any index checks and + // reference checks. + // This is possible as we called ensureWritable(...) before. + for (int i = 0; i < len; i++) { + char c = seq.charAt(i); + if (c < 0x80) { + buffer._setByte(writerIndex++, (byte) c); + } else if (c < 0x800) { + buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6))); + buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); + } else if (c >= '\uD800' && c <= '\uDFFF') { // isSurrogate(c) + if (!Character.isHighSurrogate(c)) { + buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); + continue; + } + final char c2; + try { + // Surrogate Pair consumes 2 characters. Optimistically try to get the next + // character to avoid + // duplicate bounds checking with charAt. If an IndexOutOfBoundsException is + // thrown we will + // re-throw a more informative exception describing the problem. + c2 = seq.charAt(++i); + } catch (IndexOutOfBoundsException e) { + buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); + break; + } + if (!Character.isLowSurrogate(c2)) { + buffer._setByte(writerIndex++, WRITE_UTF_UNKNOWN); + buffer._setByte(writerIndex++, Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2); + continue; + } + int codePoint = Character.toCodePoint(c, c2); + // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630. + buffer._setByte(writerIndex++, (byte) (0xf0 | (codePoint >> 18))); + buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 12) & 0x3f))); + buffer._setByte(writerIndex++, (byte) (0x80 | ((codePoint >> 6) & 0x3f))); + buffer._setByte(writerIndex++, (byte) (0x80 | (codePoint & 0x3f))); + } else { + buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12))); + buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f))); + buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); + } + } + // update the writerIndex without any extra checks for performance reasons + buffer.writerIndex = writerIndex; + return writerIndex - oldWriterIndex; + } + + /** + * Encode a {@link CharSequence} in + * UTF-8 and write it to a + * {@link ByteBuf}. + * + * This method returns the actual number of bytes written. + */ + public static int writeUtf8(ByteBuf buf, CharSequence seq) { + final int len = seq.length(); + buf.ensureWritable(len * MAX_BYTES_PER_CHAR_UTF8); + byte[] bytes = seq.toString().getBytes(StandardCharsets.UTF_8); + buf.writeBytes(bytes); + return bytes.length; + } + + /** + * Encode a {@link CharSequence} in + * UTF-8 and write it to a + * {@link ByteBuf} allocated with {@code alloc}. + * + * @param alloc The allocator used to allocate a new {@link ByteBuf}. + * @param seq The characters to write into a buffer. + * @return The {@link ByteBuf} which contains the + * UTF-8 encoded + * result. + */ + public static ByteBuf writeUtf8(CharSequence seq) { + // UTF-8 uses max. 3 bytes per char, so calculate the worst case. + ByteBuf buf = Unpooled.buffer(seq.length() * MAX_BYTES_PER_CHAR_UTF8); + writeUtf8(buf, seq); + return buf; + } + private ByteBufUtil() { } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/MathUtil.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/MathUtil.java index 604bca6b..85c959ed 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/MathUtil.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/MathUtil.java @@ -19,62 +19,6 @@ package net.lax1dude.eaglercraft.v1_8.netty; */ public final class MathUtil { - private MathUtil() { - } - - /** - * Fast method of finding the next power of 2 greater than or equal to the - * supplied value. - * - *

              - * If the value is {@code <= 0} then 1 will be returned. This method is not - * suitable for {@link Integer#MIN_VALUE} or numbers greater than 2^30. - * - * @param value from which to search for next power of 2 - * @return The next power of 2 or the value itself if it is a power of 2 - */ - public static int findNextPositivePowerOfTwo(final int value) { - assert value > Integer.MIN_VALUE && value < 0x40000000; - return 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); - } - - /** - * Fast method of finding the next power of 2 greater than or equal to the - * supplied value. - *

              - * This method will do runtime bounds checking and call - * {@link #findNextPositivePowerOfTwo(int)} if within a valid range. - * - * @param value from which to search for next power of 2 - * @return The next power of 2 or the value itself if it is a power of 2. - *

              - * Special cases for return values are as follows: - *

                - *
              • {@code <= 0} -> 1
              • - *
              • {@code >= 2^30} -> 2^30
              • - *
              - */ - public static int safeFindNextPositivePowerOfTwo(final int value) { - return value <= 0 ? 1 : value >= 0x40000000 ? 0x40000000 : findNextPositivePowerOfTwo(value); - } - - /** - * Determine if the requested {@code index} and {@code length} will fit within - * {@code capacity}. - * - * @param index The starting index. - * @param length The length which will be utilized (starting from - * {@code index}). - * @param capacity The capacity that {@code index + length} is allowed to be - * within. - * @return {@code false} if the requested {@code index} and {@code length} will - * fit within {@code capacity}. {@code true} if this would result in an - * index out of bounds exception. - */ - public static boolean isOutOfBounds(int index, int length, int capacity) { - return (index | length | capacity | (index + length) | (capacity - (index + length))) < 0; - } - /** * Compares two {@code int} values. * @@ -103,4 +47,60 @@ public final class MathUtil { public static int compare(long x, long y) { return (x < y) ? -1 : (x > y) ? 1 : 0; } + + /** + * Fast method of finding the next power of 2 greater than or equal to the + * supplied value. + * + *

              + * If the value is {@code <= 0} then 1 will be returned. This method is not + * suitable for {@link Integer#MIN_VALUE} or numbers greater than 2^30. + * + * @param value from which to search for next power of 2 + * @return The next power of 2 or the value itself if it is a power of 2 + */ + public static int findNextPositivePowerOfTwo(final int value) { + assert value > Integer.MIN_VALUE && value < 0x40000000; + return 1 << (32 - Integer.numberOfLeadingZeros(value - 1)); + } + + /** + * Determine if the requested {@code index} and {@code length} will fit within + * {@code capacity}. + * + * @param index The starting index. + * @param length The length which will be utilized (starting from + * {@code index}). + * @param capacity The capacity that {@code index + length} is allowed to be + * within. + * @return {@code false} if the requested {@code index} and {@code length} will + * fit within {@code capacity}. {@code true} if this would result in an + * index out of bounds exception. + */ + public static boolean isOutOfBounds(int index, int length, int capacity) { + return (index | length | capacity | (index + length) | (capacity - (index + length))) < 0; + } + + /** + * Fast method of finding the next power of 2 greater than or equal to the + * supplied value. + *

              + * This method will do runtime bounds checking and call + * {@link #findNextPositivePowerOfTwo(int)} if within a valid range. + * + * @param value from which to search for next power of 2 + * @return The next power of 2 or the value itself if it is a power of 2. + *

              + * Special cases for return values are as follows: + *

                + *
              • {@code <= 0} -> 1
              • + *
              • {@code >= 2^30} -> 2^30
              • + *
              + */ + public static int safeFindNextPositivePowerOfTwo(final int value) { + return value <= 0 ? 1 : value >= 0x40000000 ? 0x40000000 : findNextPositivePowerOfTwo(value); + } + + private MathUtil() { + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/NioBufferFunctions.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/NioBufferFunctions.java index c1e7ed8b..7a7ee1f4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/NioBufferFunctions.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/NioBufferFunctions.java @@ -1,44 +1,45 @@ package net.lax1dude.eaglercraft.v1_8.netty; import java.nio.ByteBuffer; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; public class NioBufferFunctions { - - public static final void get(ByteBuffer src, int index, byte[] dst, int dstOffset, int length) { - for(int i = 0; i < length; ++i) { - dst[i + dstOffset] = src.get(i + index); - } - } - - public static final void put(ByteBuffer dst, int dstIndex, ByteBuffer src, int srcOffset, int length) { - for(int i = 0; i < length; ++i) { - dst.put(i + dstIndex, src.get(i + srcOffset)); - } - } - - public static final void put(ByteBuffer dst, int dstIndex, byte[] src, int srcOffset, int length) { - for(int i = 0; i < length; ++i) { - dst.put(i + dstIndex, src[i + srcOffset]); - } - } public static final void get(ByteBuffer src, int index, byte[] dst) { get(src, index, dst, 0, dst.length); } + public static final void get(ByteBuffer src, int index, byte[] dst, int dstOffset, int length) { + for (int i = 0; i < length; ++i) { + dst[i + dstOffset] = src.get(i + index); + } + } + public static void put(ByteBuffer newBuffer, ByteBuffer flip) { int len = flip.remaining(); - for(int i = 0; i < len; ++i) { + for (int i = 0; i < len; ++i) { newBuffer.put(flip.get()); } } + public static final void put(ByteBuffer dst, int dstIndex, byte[] src, int srcOffset, int length) { + for (int i = 0; i < length; ++i) { + dst.put(i + dstIndex, src[i + srcOffset]); + } + } + + public static final void put(ByteBuffer dst, int dstIndex, ByteBuffer src, int srcOffset, int length) { + for (int i = 0; i < length; ++i) { + dst.put(i + dstIndex, src.get(i + srcOffset)); + } + } + public static void put(IntBuffer intBuffer, int index, int[] data) { int p = intBuffer.position(); intBuffer.position(index); intBuffer.put(data); intBuffer.position(p); } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ObjectUtil.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ObjectUtil.java index 3c2c2e63..e26b1250 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ObjectUtil.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/ObjectUtil.java @@ -27,158 +27,6 @@ public final class ObjectUtil { private static final long LONG_ZERO = 0L; private static final int INT_ZERO = 0; - private ObjectUtil() { - } - - /** - * Checks that the given argument is not null. If it is, throws - * {@link NullPointerException}. Otherwise, returns the argument. - */ - public static T checkNotNull(T arg, String text) { - if (arg == null) { - throw new NullPointerException(text); - } - return arg; - } - - /** - * Check that the given varargs is not null and does not contain elements null - * elements. - * - * If it is, throws {@link NullPointerException}. Otherwise, returns the - * argument. - */ - public static T[] deepCheckNotNull(String text, T... varargs) { - if (varargs == null) { - throw new NullPointerException(text); - } - - for (int i = 0; i < varargs.length; ++i) { - if (varargs[i] == null) { - throw new NullPointerException(text); - } - } - return varargs; - } - - /** - * Checks that the given argument is not null. If it is, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static T checkNotNullWithIAE(final T arg, final String paramName) throws IllegalArgumentException { - if (arg == null) { - throw new IllegalArgumentException("Param '" + paramName + "' must not be null"); - } - return arg; - } - - /** - * Checks that the given argument is not null. If it is, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - * - * @param type of the given argument value. - * @param name of the parameter, belongs to the exception message. - * @param index of the array, belongs to the exception message. - * @param value to check. - * @return the given argument value. - * @throws IllegalArgumentException if value is null. - */ - public static T checkNotNullArrayParam(T value, int index, String name) throws IllegalArgumentException { - if (value == null) { - throw new IllegalArgumentException( - "Array index " + index + " of parameter '" + name + "' must not be null"); - } - return value; - } - - /** - * Checks that the given argument is strictly positive. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static int checkPositive(int i, String name) { - if (i <= INT_ZERO) { - throw new IllegalArgumentException(name + " : " + i + " (expected: > 0)"); - } - return i; - } - - /** - * Checks that the given argument is strictly positive. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static long checkPositive(long l, String name) { - if (l <= LONG_ZERO) { - throw new IllegalArgumentException(name + " : " + l + " (expected: > 0)"); - } - return l; - } - - /** - * Checks that the given argument is strictly positive. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static double checkPositive(final double d, final String name) { - if (d <= DOUBLE_ZERO) { - throw new IllegalArgumentException(name + " : " + d + " (expected: > 0)"); - } - return d; - } - - /** - * Checks that the given argument is strictly positive. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static float checkPositive(final float f, final String name) { - if (f <= FLOAT_ZERO) { - throw new IllegalArgumentException(name + " : " + f + " (expected: > 0)"); - } - return f; - } - - /** - * Checks that the given argument is positive or zero. If it is not , throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static int checkPositiveOrZero(int i, String name) { - if (i < INT_ZERO) { - throw new IllegalArgumentException(name + " : " + i + " (expected: >= 0)"); - } - return i; - } - - /** - * Checks that the given argument is positive or zero. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static long checkPositiveOrZero(long l, String name) { - if (l < LONG_ZERO) { - throw new IllegalArgumentException(name + " : " + l + " (expected: >= 0)"); - } - return l; - } - - /** - * Checks that the given argument is positive or zero. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static double checkPositiveOrZero(final double d, final String name) { - if (d < DOUBLE_ZERO) { - throw new IllegalArgumentException(name + " : " + d + " (expected: >= 0)"); - } - return d; - } - - /** - * Checks that the given argument is positive or zero. If it is not, throws - * {@link IllegalArgumentException}. Otherwise, returns the argument. - */ - public static float checkPositiveOrZero(final float f, final String name) { - if (f < FLOAT_ZERO) { - throw new IllegalArgumentException(name + " : " + f + " (expected: >= 0)"); - } - return f; - } - /** * Checks that the given argument is in range. If it is not, throws * {@link IllegalArgumentException}. Otherwise, returns the argument. @@ -201,19 +49,6 @@ public final class ObjectUtil { return l; } - /** - * Checks that the given argument is neither null nor empty. If it is, throws - * {@link NullPointerException} or {@link IllegalArgumentException}. Otherwise, - * returns the argument. - */ - public static T[] checkNonEmpty(T[] array, String name) { - // No String concatenation for check - if (checkNotNull(array, name).length == 0) { - throw new IllegalArgumentException("Param '" + name + "' must not be empty"); - } - return array; - } - /** * Checks that the given argument is neither null nor empty. If it is, throws * {@link NullPointerException} or {@link IllegalArgumentException}. Otherwise, @@ -245,12 +80,11 @@ public final class ObjectUtil { * {@link NullPointerException} or {@link IllegalArgumentException}. Otherwise, * returns the argument. */ - public static > T checkNonEmpty(T collection, String name) { - // No String concatenation for check - if (checkNotNull(collection, name).isEmpty()) { + public static CharSequence checkNonEmpty(final CharSequence value, final String name) { + if (checkNotNull(value, name).length() == 0) { throw new IllegalArgumentException("Param '" + name + "' must not be empty"); } - return collection; + return value; } /** @@ -265,6 +99,19 @@ public final class ObjectUtil { return value; } + /** + * Checks that the given argument is neither null nor empty. If it is, throws + * {@link NullPointerException} or {@link IllegalArgumentException}. Otherwise, + * returns the argument. + */ + public static > T checkNonEmpty(T collection, String name) { + // No String concatenation for check + if (checkNotNull(collection, name).isEmpty()) { + throw new IllegalArgumentException("Param '" + name + "' must not be empty"); + } + return collection; + } + /** * Checks that the given argument is neither null nor empty. If it is, throws * {@link NullPointerException} or {@link IllegalArgumentException}. Otherwise, @@ -282,11 +129,12 @@ public final class ObjectUtil { * {@link NullPointerException} or {@link IllegalArgumentException}. Otherwise, * returns the argument. */ - public static CharSequence checkNonEmpty(final CharSequence value, final String name) { - if (checkNotNull(value, name).length() == 0) { + public static T[] checkNonEmpty(T[] array, String name) { + // No String concatenation for check + if (checkNotNull(array, name).length == 0) { throw new IllegalArgumentException("Param '" + name + "' must not be empty"); } - return value; + return array; } /** @@ -305,6 +153,155 @@ public final class ObjectUtil { return checkNonEmpty(trimmed, name); } + /** + * Checks that the given argument is not null. If it is, throws + * {@link NullPointerException}. Otherwise, returns the argument. + */ + public static T checkNotNull(T arg, String text) { + if (arg == null) { + throw new NullPointerException(text); + } + return arg; + } + + /** + * Checks that the given argument is not null. If it is, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + * + * @param type of the given argument value. + * @param name of the parameter, belongs to the exception message. + * @param index of the array, belongs to the exception message. + * @param value to check. + * @return the given argument value. + * @throws IllegalArgumentException if value is null. + */ + public static T checkNotNullArrayParam(T value, int index, String name) throws IllegalArgumentException { + if (value == null) { + throw new IllegalArgumentException( + "Array index " + index + " of parameter '" + name + "' must not be null"); + } + return value; + } + + /** + * Checks that the given argument is not null. If it is, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static T checkNotNullWithIAE(final T arg, final String paramName) throws IllegalArgumentException { + if (arg == null) { + throw new IllegalArgumentException("Param '" + paramName + "' must not be null"); + } + return arg; + } + + /** + * Checks that the given argument is strictly positive. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static double checkPositive(final double d, final String name) { + if (d <= DOUBLE_ZERO) { + throw new IllegalArgumentException(name + " : " + d + " (expected: > 0)"); + } + return d; + } + + /** + * Checks that the given argument is strictly positive. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static float checkPositive(final float f, final String name) { + if (f <= FLOAT_ZERO) { + throw new IllegalArgumentException(name + " : " + f + " (expected: > 0)"); + } + return f; + } + + /** + * Checks that the given argument is strictly positive. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static int checkPositive(int i, String name) { + if (i <= INT_ZERO) { + throw new IllegalArgumentException(name + " : " + i + " (expected: > 0)"); + } + return i; + } + + /** + * Checks that the given argument is strictly positive. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static long checkPositive(long l, String name) { + if (l <= LONG_ZERO) { + throw new IllegalArgumentException(name + " : " + l + " (expected: > 0)"); + } + return l; + } + + /** + * Checks that the given argument is positive or zero. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static double checkPositiveOrZero(final double d, final String name) { + if (d < DOUBLE_ZERO) { + throw new IllegalArgumentException(name + " : " + d + " (expected: >= 0)"); + } + return d; + } + + /** + * Checks that the given argument is positive or zero. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static float checkPositiveOrZero(final float f, final String name) { + if (f < FLOAT_ZERO) { + throw new IllegalArgumentException(name + " : " + f + " (expected: >= 0)"); + } + return f; + } + + /** + * Checks that the given argument is positive or zero. If it is not , throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static int checkPositiveOrZero(int i, String name) { + if (i < INT_ZERO) { + throw new IllegalArgumentException(name + " : " + i + " (expected: >= 0)"); + } + return i; + } + + /** + * Checks that the given argument is positive or zero. If it is not, throws + * {@link IllegalArgumentException}. Otherwise, returns the argument. + */ + public static long checkPositiveOrZero(long l, String name) { + if (l < LONG_ZERO) { + throw new IllegalArgumentException(name + " : " + l + " (expected: >= 0)"); + } + return l; + } + + /** + * Check that the given varargs is not null and does not contain elements null + * elements. + * + * If it is, throws {@link NullPointerException}. Otherwise, returns the + * argument. + */ + public static T[] deepCheckNotNull(String text, T... varargs) { + if (varargs == null) { + throw new NullPointerException(text); + } + + for (int i = 0; i < varargs.length; ++i) { + if (varargs[i] == null) { + throw new NullPointerException(text); + } + } + return varargs; + } + /** * Resolves a possibly null Integer to a primitive int, using a default value. * @@ -326,4 +323,7 @@ public final class ObjectUtil { public static long longValue(Long wrapper, long defaultValue) { return wrapper != null ? wrapper : defaultValue; } + + private ObjectUtil() { + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/SwappedByteBuf.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/SwappedByteBuf.java index d66cdb38..13ec1afa 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/SwappedByteBuf.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/SwappedByteBuf.java @@ -43,24 +43,28 @@ public class SwappedByteBuf extends ByteBuf { } @Override - public ByteOrder order() { - return order; + public byte[] array() { + return buf.array(); } @Override - public ByteBuf order(ByteOrder endianness) { - if (endianness == null) { - throw new NullPointerException("endianness"); - } - if (endianness == order) { - return this; - } - return buf; + public int arrayOffset() { + return buf.arrayOffset(); } @Override - public ByteBuf unwrap() { - return buf; + public int bytesBefore(byte value) { + return buf.bytesBefore(value); + } + + @Override + public int bytesBefore(int length, byte value) { + return buf.bytesBefore(length, value); + } + + @Override + public int bytesBefore(int index, int length, byte value) { + return buf.bytesBefore(index, length, value); } @Override @@ -75,8 +79,195 @@ public class SwappedByteBuf extends ByteBuf { } @Override - public int maxCapacity() { - return buf.maxCapacity(); + public ByteBuf clear() { + buf.clear(); + return this; + } + + @Override + public int compareTo(ByteBuf buffer) { + return ByteBufUtil.compare(this, buffer); + } + + @Override + public ByteBuf copy() { + return buf.copy().order(order); + } + + @Override + public ByteBuf copy(int index, int length) { + return buf.copy(index, length).order(order); + } + + @Override + public ByteBuf discardReadBytes() { + buf.discardReadBytes(); + return this; + } + + @Override + public ByteBuf discardSomeReadBytes() { + buf.discardSomeReadBytes(); + return this; + } + + @Override + public ByteBuf duplicate() { + return buf.duplicate().order(order); + } + + @Override + public ByteBuf ensureWritable(int writableBytes) { + buf.ensureWritable(writableBytes); + return this; + } + + @Override + public int ensureWritable(int minWritableBytes, boolean force) { + return buf.ensureWritable(minWritableBytes, force); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof ByteBuf) { + return ByteBufUtil.equals(this, (ByteBuf) obj); + } + return false; + } + + @Override + public boolean getBoolean(int index) { + return buf.getBoolean(index); + } + + @Override + public byte getByte(int index) { + return buf.getByte(index); + } + + @Override + public ByteBuf getBytes(int index, byte[] dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + buf.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int length) { + buf.getBytes(index, dst, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + buf.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + buf.getBytes(index, out, length); + return this; + } + + @Override + public char getChar(int index) { + return (char) getShort(index); + } + + @Override + public double getDouble(int index) { + return Double.longBitsToDouble(getLong(index)); + } + + @Override + public float getFloat(int index) { + return Float.intBitsToFloat(getInt(index)); + } + + @Override + public int getInt(int index) { + return ByteBufUtil.swapInt(buf.getInt(index)); + } + + @Override + public long getLong(int index) { + return ByteBufUtil.swapLong(buf.getLong(index)); + } + + @Override + public int getMedium(int index) { + return ByteBufUtil.swapMedium(buf.getMedium(index)); + } + + @Override + public short getShort(int index) { + return ByteBufUtil.swapShort(buf.getShort(index)); + } + + @Override + public short getUnsignedByte(int index) { + return buf.getUnsignedByte(index); + } + + @Override + public long getUnsignedInt(int index) { + return getInt(index) & 0xFFFFFFFFL; + } + + @Override + public int getUnsignedMedium(int index) { + return getMedium(index) & 0xFFFFFF; + } + + @Override + public int getUnsignedShort(int index) { + return getShort(index) & 0xFFFF; + } + + @Override + public boolean hasArray() { + return buf.hasArray(); + } + + @Override + public int hashCode() { + return buf.hashCode(); + } + + @Override + public boolean hasMemoryAddress() { + return buf.hasMemoryAddress(); + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + return buf.indexOf(fromIndex, toIndex, value); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return nioBuffer(index, length); } @Override @@ -84,49 +275,6 @@ public class SwappedByteBuf extends ByteBuf { return buf.isDirect(); } - @Override - public int readerIndex() { - return buf.readerIndex(); - } - - @Override - public ByteBuf readerIndex(int readerIndex) { - buf.readerIndex(readerIndex); - return this; - } - - @Override - public int writerIndex() { - return buf.writerIndex(); - } - - @Override - public ByteBuf writerIndex(int writerIndex) { - buf.writerIndex(writerIndex); - return this; - } - - @Override - public ByteBuf setIndex(int readerIndex, int writerIndex) { - buf.setIndex(readerIndex, writerIndex); - return this; - } - - @Override - public int readableBytes() { - return buf.readableBytes(); - } - - @Override - public int writableBytes() { - return buf.writableBytes(); - } - - @Override - public int maxWritableBytes() { - return buf.maxWritableBytes(); - } - @Override public boolean isReadable() { return buf.isReadable(); @@ -147,166 +295,227 @@ public class SwappedByteBuf extends ByteBuf { return buf.isWritable(size); } - @Override - public ByteBuf clear() { - buf.clear(); - return this; - } - @Override public ByteBuf markReaderIndex() { buf.markReaderIndex(); return this; } - @Override - public ByteBuf resetReaderIndex() { - buf.resetReaderIndex(); - return this; - } - @Override public ByteBuf markWriterIndex() { buf.markWriterIndex(); return this; } + @Override + public int maxCapacity() { + return buf.maxCapacity(); + } + + @Override + public int maxWritableBytes() { + return buf.maxWritableBytes(); + } + + @Override + public long memoryAddress() { + return buf.memoryAddress(); + } + + @Override + public ByteBuffer nioBuffer() { + return buf.nioBuffer().order(order); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + return buf.nioBuffer(index, length).order(order); + } + + @Override + public int nioBufferCount() { + return buf.nioBufferCount(); + } + + @Override + public ByteBuffer[] nioBuffers() { + ByteBuffer[] nioBuffers = buf.nioBuffers(); + for (int i = 0; i < nioBuffers.length; i++) { + nioBuffers[i] = nioBuffers[i].order(order); + } + return nioBuffers; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + ByteBuffer[] nioBuffers = buf.nioBuffers(index, length); + for (int i = 0; i < nioBuffers.length; i++) { + nioBuffers[i] = nioBuffers[i].order(order); + } + return nioBuffers; + } + + @Override + public ByteOrder order() { + return order; + } + + @Override + public ByteBuf order(ByteOrder endianness) { + if (endianness == null) { + throw new NullPointerException("endianness"); + } + if (endianness == order) { + return this; + } + return buf; + } + + @Override + public int readableBytes() { + return buf.readableBytes(); + } + + @Override + public boolean readBoolean() { + return buf.readBoolean(); + } + + @Override + public byte readByte() { + return buf.readByte(); + } + + @Override + public ByteBuf readBytes(byte[] dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + buf.readBytes(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int length) { + buf.readBytes(dst, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + buf.readBytes(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(int length) { + return buf.readBytes(length).order(order()); + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + buf.readBytes(out, length); + return this; + } + + @Override + public char readChar() { + return (char) readShort(); + } + + @Override + public double readDouble() { + return Double.longBitsToDouble(readLong()); + } + + @Override + public int readerIndex() { + return buf.readerIndex(); + } + + @Override + public ByteBuf readerIndex(int readerIndex) { + buf.readerIndex(readerIndex); + return this; + } + + @Override + public float readFloat() { + return Float.intBitsToFloat(readInt()); + } + + @Override + public int readInt() { + return ByteBufUtil.swapInt(buf.readInt()); + } + + @Override + public long readLong() { + return ByteBufUtil.swapLong(buf.readLong()); + } + + @Override + public int readMedium() { + return ByteBufUtil.swapMedium(buf.readMedium()); + } + + @Override + public short readShort() { + return ByteBufUtil.swapShort(buf.readShort()); + } + + @Override + public ByteBuf readSlice(int length) { + return buf.readSlice(length).order(order); + } + + @Override + public short readUnsignedByte() { + return buf.readUnsignedByte(); + } + + @Override + public long readUnsignedInt() { + return readInt() & 0xFFFFFFFFL; + } + + @Override + public int readUnsignedMedium() { + return readMedium() & 0xFFFFFF; + } + + @Override + public int readUnsignedShort() { + return readShort() & 0xFFFF; + } + + @Override + public ByteBuf resetReaderIndex() { + buf.resetReaderIndex(); + return this; + } + @Override public ByteBuf resetWriterIndex() { buf.resetWriterIndex(); return this; } - @Override - public ByteBuf discardReadBytes() { - buf.discardReadBytes(); - return this; - } - - @Override - public ByteBuf discardSomeReadBytes() { - buf.discardSomeReadBytes(); - return this; - } - - @Override - public ByteBuf ensureWritable(int writableBytes) { - buf.ensureWritable(writableBytes); - return this; - } - - @Override - public int ensureWritable(int minWritableBytes, boolean force) { - return buf.ensureWritable(minWritableBytes, force); - } - - @Override - public boolean getBoolean(int index) { - return buf.getBoolean(index); - } - - @Override - public byte getByte(int index) { - return buf.getByte(index); - } - - @Override - public short getUnsignedByte(int index) { - return buf.getUnsignedByte(index); - } - - @Override - public short getShort(int index) { - return ByteBufUtil.swapShort(buf.getShort(index)); - } - - @Override - public int getUnsignedShort(int index) { - return getShort(index) & 0xFFFF; - } - - @Override - public int getMedium(int index) { - return ByteBufUtil.swapMedium(buf.getMedium(index)); - } - - @Override - public int getUnsignedMedium(int index) { - return getMedium(index) & 0xFFFFFF; - } - - @Override - public int getInt(int index) { - return ByteBufUtil.swapInt(buf.getInt(index)); - } - - @Override - public long getUnsignedInt(int index) { - return getInt(index) & 0xFFFFFFFFL; - } - - @Override - public long getLong(int index) { - return ByteBufUtil.swapLong(buf.getLong(index)); - } - - @Override - public char getChar(int index) { - return (char) getShort(index); - } - - @Override - public float getFloat(int index) { - return Float.intBitsToFloat(getInt(index)); - } - - @Override - public double getDouble(int index) { - return Double.longBitsToDouble(getLong(index)); - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int length) { - buf.getBytes(index, dst, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { - buf.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { - buf.getBytes(index, dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf getBytes(int index, ByteBuffer dst) { - buf.getBytes(index, dst); - return this; - } - - @Override - public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { - buf.getBytes(index, out, length); - return this; - } - @Override public ByteBuf setBoolean(int index, boolean value) { buf.setBoolean(index, value); @@ -320,44 +529,14 @@ public class SwappedByteBuf extends ByteBuf { } @Override - public ByteBuf setShort(int index, int value) { - buf.setShort(index, ByteBufUtil.swapShort((short) value)); + public ByteBuf setBytes(int index, byte[] src) { + buf.setBytes(index, src); return this; } @Override - public ByteBuf setMedium(int index, int value) { - buf.setMedium(index, ByteBufUtil.swapMedium(value)); - return this; - } - - @Override - public ByteBuf setInt(int index, int value) { - buf.setInt(index, ByteBufUtil.swapInt(value)); - return this; - } - - @Override - public ByteBuf setLong(int index, long value) { - buf.setLong(index, ByteBufUtil.swapLong(value)); - return this; - } - - @Override - public ByteBuf setChar(int index, int value) { - setShort(index, value); - return this; - } - - @Override - public ByteBuf setFloat(int index, float value) { - setInt(index, Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf setDouble(int index, double value) { - setLong(index, Double.doubleToRawLongBits(value)); + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + buf.setBytes(index, src, srcIndex, length); return this; } @@ -379,18 +558,6 @@ public class SwappedByteBuf extends ByteBuf { return this; } - @Override - public ByteBuf setBytes(int index, byte[] src) { - buf.setBytes(index, src); - return this; - } - - @Override - public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { - buf.setBytes(index, src, srcIndex, length); - return this; - } - @Override public ByteBuf setBytes(int index, ByteBuffer src) { buf.setBytes(index, src); @@ -401,136 +568,102 @@ public class SwappedByteBuf extends ByteBuf { public int setBytes(int index, InputStream in, int length) throws IOException { return buf.setBytes(index, in, length); } - + + @Override + public ByteBuf setChar(int index, int value) { + setShort(index, value); + return this; + } + + @Override + public ByteBuf setDouble(int index, double value) { + setLong(index, Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf setFloat(int index, float value) { + setInt(index, Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf setIndex(int readerIndex, int writerIndex) { + buf.setIndex(readerIndex, writerIndex); + return this; + } + + @Override + public ByteBuf setInt(int index, int value) { + buf.setInt(index, ByteBufUtil.swapInt(value)); + return this; + } + + @Override + public ByteBuf setLong(int index, long value) { + buf.setLong(index, ByteBufUtil.swapLong(value)); + return this; + } + + @Override + public ByteBuf setMedium(int index, int value) { + buf.setMedium(index, ByteBufUtil.swapMedium(value)); + return this; + } + + @Override + public ByteBuf setShort(int index, int value) { + buf.setShort(index, ByteBufUtil.swapShort((short) value)); + return this; + } + @Override public ByteBuf setZero(int index, int length) { buf.setZero(index, length); return this; } - @Override - public boolean readBoolean() { - return buf.readBoolean(); - } - - @Override - public byte readByte() { - return buf.readByte(); - } - - @Override - public short readUnsignedByte() { - return buf.readUnsignedByte(); - } - - @Override - public short readShort() { - return ByteBufUtil.swapShort(buf.readShort()); - } - - @Override - public int readUnsignedShort() { - return readShort() & 0xFFFF; - } - - @Override - public int readMedium() { - return ByteBufUtil.swapMedium(buf.readMedium()); - } - - @Override - public int readUnsignedMedium() { - return readMedium() & 0xFFFFFF; - } - - @Override - public int readInt() { - return ByteBufUtil.swapInt(buf.readInt()); - } - - @Override - public long readUnsignedInt() { - return readInt() & 0xFFFFFFFFL; - } - - @Override - public long readLong() { - return ByteBufUtil.swapLong(buf.readLong()); - } - - @Override - public char readChar() { - return (char) readShort(); - } - - @Override - public float readFloat() { - return Float.intBitsToFloat(readInt()); - } - - @Override - public double readDouble() { - return Double.longBitsToDouble(readLong()); - } - - @Override - public ByteBuf readBytes(int length) { - return buf.readBytes(length).order(order()); - } - - @Override - public ByteBuf readSlice(int length) { - return buf.readSlice(length).order(order); - } - - @Override - public ByteBuf readBytes(ByteBuf dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int length) { - buf.readBytes(dst, length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { - buf.readBytes(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { - buf.readBytes(dst, dstIndex, length); - return this; - } - - @Override - public ByteBuf readBytes(ByteBuffer dst) { - buf.readBytes(dst); - return this; - } - - @Override - public ByteBuf readBytes(OutputStream out, int length) throws IOException { - buf.readBytes(out, length); - return this; - } - @Override public ByteBuf skipBytes(int length) { buf.skipBytes(length); return this; } + @Override + public ByteBuf slice() { + return buf.slice().order(order); + } + + @Override + public ByteBuf slice(int index, int length) { + return buf.slice(index, length).order(order); + } + + @Override + public String toString() { + return "Swapped(" + buf.toString() + ')'; + } + + @Override + public String toString(Charset charset) { + return buf.toString(charset); + } + + @Override + public String toString(int index, int length, Charset charset) { + return buf.toString(index, length, charset); + } + + @Override + public ByteBuf unwrap() { + return buf; + } + + @Override + public int writableBytes() { + return buf.writableBytes(); + } + @Override public ByteBuf writeBoolean(boolean value) { buf.writeBoolean(value); @@ -544,44 +677,14 @@ public class SwappedByteBuf extends ByteBuf { } @Override - public ByteBuf writeShort(int value) { - buf.writeShort(ByteBufUtil.swapShort((short) value)); + public ByteBuf writeBytes(byte[] src) { + buf.writeBytes(src); return this; } @Override - public ByteBuf writeMedium(int value) { - buf.writeMedium(ByteBufUtil.swapMedium(value)); - return this; - } - - @Override - public ByteBuf writeInt(int value) { - buf.writeInt(ByteBufUtil.swapInt(value)); - return this; - } - - @Override - public ByteBuf writeLong(long value) { - buf.writeLong(ByteBufUtil.swapLong(value)); - return this; - } - - @Override - public ByteBuf writeChar(int value) { - writeShort(value); - return this; - } - - @Override - public ByteBuf writeFloat(float value) { - writeInt(Float.floatToRawIntBits(value)); - return this; - } - - @Override - public ByteBuf writeDouble(double value) { - writeLong(Double.doubleToRawLongBits(value)); + public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { + buf.writeBytes(src, srcIndex, length); return this; } @@ -603,18 +706,6 @@ public class SwappedByteBuf extends ByteBuf { return this; } - @Override - public ByteBuf writeBytes(byte[] src) { - buf.writeBytes(src); - return this; - } - - @Override - public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { - buf.writeBytes(src, srcIndex, length); - return this; - } - @Override public ByteBuf writeBytes(ByteBuffer src) { buf.writeBytes(src); @@ -627,152 +718,61 @@ public class SwappedByteBuf extends ByteBuf { } @Override - public ByteBuf writeZero(int length) { - buf.writeZero(length); + public ByteBuf writeChar(int value) { + writeShort(value); return this; } @Override - public int indexOf(int fromIndex, int toIndex, byte value) { - return buf.indexOf(fromIndex, toIndex, value); + public ByteBuf writeDouble(double value) { + writeLong(Double.doubleToRawLongBits(value)); + return this; } @Override - public int bytesBefore(byte value) { - return buf.bytesBefore(value); + public ByteBuf writeFloat(float value) { + writeInt(Float.floatToRawIntBits(value)); + return this; } @Override - public int bytesBefore(int length, byte value) { - return buf.bytesBefore(length, value); + public ByteBuf writeInt(int value) { + buf.writeInt(ByteBufUtil.swapInt(value)); + return this; } @Override - public int bytesBefore(int index, int length, byte value) { - return buf.bytesBefore(index, length, value); + public ByteBuf writeLong(long value) { + buf.writeLong(ByteBufUtil.swapLong(value)); + return this; } @Override - public ByteBuf copy() { - return buf.copy().order(order); + public ByteBuf writeMedium(int value) { + buf.writeMedium(ByteBufUtil.swapMedium(value)); + return this; } @Override - public ByteBuf copy(int index, int length) { - return buf.copy(index, length).order(order); + public int writerIndex() { + return buf.writerIndex(); } @Override - public ByteBuf slice() { - return buf.slice().order(order); + public ByteBuf writerIndex(int writerIndex) { + buf.writerIndex(writerIndex); + return this; } @Override - public ByteBuf slice(int index, int length) { - return buf.slice(index, length).order(order); + public ByteBuf writeShort(int value) { + buf.writeShort(ByteBufUtil.swapShort((short) value)); + return this; } @Override - public ByteBuf duplicate() { - return buf.duplicate().order(order); - } - - @Override - public int nioBufferCount() { - return buf.nioBufferCount(); - } - - @Override - public ByteBuffer nioBuffer() { - return buf.nioBuffer().order(order); - } - - @Override - public ByteBuffer nioBuffer(int index, int length) { - return buf.nioBuffer(index, length).order(order); - } - - @Override - public ByteBuffer internalNioBuffer(int index, int length) { - return nioBuffer(index, length); - } - - @Override - public ByteBuffer[] nioBuffers() { - ByteBuffer[] nioBuffers = buf.nioBuffers(); - for (int i = 0; i < nioBuffers.length; i++) { - nioBuffers[i] = nioBuffers[i].order(order); - } - return nioBuffers; - } - - @Override - public ByteBuffer[] nioBuffers(int index, int length) { - ByteBuffer[] nioBuffers = buf.nioBuffers(index, length); - for (int i = 0; i < nioBuffers.length; i++) { - nioBuffers[i] = nioBuffers[i].order(order); - } - return nioBuffers; - } - - @Override - public boolean hasArray() { - return buf.hasArray(); - } - - @Override - public byte[] array() { - return buf.array(); - } - - @Override - public int arrayOffset() { - return buf.arrayOffset(); - } - - @Override - public boolean hasMemoryAddress() { - return buf.hasMemoryAddress(); - } - - @Override - public long memoryAddress() { - return buf.memoryAddress(); - } - - @Override - public String toString(Charset charset) { - return buf.toString(charset); - } - - @Override - public String toString(int index, int length, Charset charset) { - return buf.toString(index, length, charset); - } - - @Override - public int hashCode() { - return buf.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof ByteBuf) { - return ByteBufUtil.equals(this, (ByteBuf) obj); - } - return false; - } - - @Override - public int compareTo(ByteBuf buffer) { - return ByteBufUtil.compare(this, buffer); - } - - @Override - public String toString() { - return "Swapped(" + buf.toString() + ')'; + public ByteBuf writeZero(int length) { + buf.writeZero(length); + return this; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/Unpooled.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/Unpooled.java index d25666ae..f0bf15d9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/Unpooled.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/netty/Unpooled.java @@ -5,14 +5,15 @@ import java.nio.ByteBuffer; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,6 +26,14 @@ public class Unpooled { return ByteBuf.allocate(256, Integer.MAX_VALUE); } + public static ByteBuf buffer(byte[] data, int maxLength) { + return ByteBuf.allocate(ByteBuffer.wrap(data), maxLength); + } + + public static ByteBuf buffer(ByteBuffer data, int maxLength) { + return ByteBuf.allocate(data, maxLength); + } + public static ByteBuf buffer(int length) { return ByteBuf.allocate(length, Integer.MAX_VALUE); } @@ -33,14 +42,6 @@ public class Unpooled { return ByteBuf.allocate(length, maxLength); } - public static ByteBuf buffer(ByteBuffer data, int maxLength) { - return ByteBuf.allocate(data, maxLength); - } - - public static ByteBuf buffer(byte[] data, int maxLength) { - return ByteBuf.allocate(ByteBuffer.wrap(data), maxLength); - } - public static ByteBuf wrappedBuffer(ByteBuf buf) { return buf.duplicate(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/CachedNotifBadgeTexture.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/CachedNotifBadgeTexture.java index 904e10ec..eafa4af9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/CachedNotifBadgeTexture.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/CachedNotifBadgeTexture.java @@ -7,14 +7,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ClickEventZone.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ClickEventZone.java index 939a61f3..ff0774ad 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ClickEventZone.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ClickEventZone.java @@ -5,14 +5,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiButtonNotifBell.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiButtonNotifBell.java index fc72d217..258486de 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiButtonNotifBell.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiButtonNotifBell.java @@ -10,14 +10,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,10 +33,6 @@ public class GuiButtonNotifBell extends GuiButton { super(buttonID, xPos, yPos, 20, 20, ""); } - public void setUnread(int num) { - unread = num; - } - public void drawButton(Minecraft minecraft, int i, int j) { if (this.visible) { minecraft.getTextureManager().bindTexture(eaglerTextures); @@ -51,14 +48,14 @@ public class GuiButtonNotifBell extends GuiButton { } drawTexturedModalRect(xPosition, yPosition, unread > 0 ? 116 : 136, k, width, height); - - if(unread > 0) { + + if (unread > 0) { GlStateManager.pushMatrix(); GlStateManager.translate(xPosition + 15.5f, yPosition + 11.0f, 0.0f); - if(unread >= 10) { + if (unread >= 10) { GlStateManager.translate(0.0f, 1.0f, 0.0f); GlStateManager.scale(0.5f, 0.5f, 0.5f); - }else { + } else { GlStateManager.scale(0.75f, 0.75f, 0.75f); } drawCenteredString(minecraft.fontRendererObj, Integer.toString(unread), 0, 0, c); @@ -66,4 +63,8 @@ public class GuiButtonNotifBell extends GuiButton { } } } + + public void setUnread(int num) { + unread = num; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiScreenNotifications.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiScreenNotifications.java index 80876fb4..ea5dd790 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiScreenNotifications.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiScreenNotifications.java @@ -16,30 +16,29 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenNotifications extends GuiScreen { - private static final String[] priorityLangKeys = new String[] { - "notifications.priority.low", - "notifications.priority.normal", - "notifications.priority.higher", - "notifications.priority.highest" - }; + private static final String[] priorityLangKeys = new String[] { "notifications.priority.low", + "notifications.priority.normal", "notifications.priority.higher", "notifications.priority.highest" }; - private static final int[] priorityOrder = new int[] { - 0, 3, 2, 1 - }; + private static final int[] priorityOrder = new int[] { 0, 3, 2, 1 }; + + static Minecraft getMinecraft(GuiScreenNotifications screen) { + return screen.mc; + } GuiScreen parent; int selected; @@ -48,88 +47,20 @@ public class GuiScreenNotifications extends GuiScreen { GuiButton priorityButton; int showPriority = 0; EnumBadgePriority selectedMaxPriority = EnumBadgePriority.LOW; + int lastUpdate = -1; public GuiScreenNotifications(GuiScreen parent) { this.parent = parent; } - public void initGui() { - selected = -1; - buttonList.clear(); - buttonList.add(new GuiButton(0, this.width / 2 + 54, this.height - 32, 100, 20, I18n.format("gui.done"))); - buttonList.add(clearAllButton = new GuiButton(1, this.width / 2 - 154, this.height - 32, 100, 20, - I18n.format("notifications.clearAll"))); - int i = priorityOrder[showPriority]; - buttonList.add(priorityButton = new GuiButton(2, this.width / 2 - 50, this.height - 32, 100, 20, - I18n.format("notifications.priority", I18n.format(priorityLangKeys[i])))); - selectedMaxPriority = EnumBadgePriority.getByID(i); - slots = new GuiSlotNotifications(this); - lastUpdate = -69420; - updateList(); - updateButtons(); - } - - void updateButtons() { - clearAllButton.enabled = !slots.currentDisplayNotifs.isEmpty(); - } - - void updateList() { - if(mc.thePlayer == null) return; - ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); - int verHash = showPriority | (mgr.getNotifListUpdateCount() << 2); - if(verHash != lastUpdate) { - lastUpdate = verHash; - EaglercraftUUID selectedUUID = null; - List lst = slots.currentDisplayNotifs; - int oldSelectedId = selected; - if(oldSelectedId >= 0 && oldSelectedId < lst.size()) { - selectedUUID = lst.get(oldSelectedId).badge.badgeUUID; - } - lst.clear(); - lst.addAll(Collections2.transform(Collections2.filter(mgr.getNotifLongHistory(), new Predicate() { - @Override - public boolean apply(NotificationBadge input) { - return input.priority.priority >= priorityOrder[showPriority]; - } - }), GuiSlotNotifications.NotifBadgeSlot::new)); - selected = -1; - if(selectedUUID != null) { - for(int i = 0, l = lst.size(); i < l; ++i) { - if(selectedUUID.equals(lst.get(i).badge.badgeUUID)) { - selected = i; - break; - } - } - } - if(selected != -1) { - if(oldSelectedId != selected) { - slots.scrollBy((selected - oldSelectedId) * slots.getSlotHeight()); - } - } - updateButtons(); - } - } - - public void updateScreen() { - if(mc.thePlayer == null) { - mc.displayGuiScreen(parent); - return; - } - updateList(); - } - - static Minecraft getMinecraft(GuiScreenNotifications screen) { - return screen.mc; - } - public void actionPerformed(GuiButton btn) { - switch(btn.id) { + switch (btn.id) { case 0: mc.displayGuiScreen(parent); break; case 1: - if(mc.thePlayer != null) { + if (mc.thePlayer != null) { ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); mgr.removeAllNotifFromActiveList(mgr.getNotifLongHistory()); clearAllButton.enabled = false; @@ -148,7 +79,8 @@ public class GuiScreenNotifications extends GuiScreen { } public void drawScreen(int par1, int par2, float par3) { - if(mc.thePlayer == null) return; + if (mc.thePlayer == null) + return; slots.drawScreen(par1, par2, par3); this.drawCenteredString(fontRendererObj, I18n.format("notifications.title"), this.width / 2, 16, 16777215); super.drawScreen(par1, par2, par3); @@ -164,9 +96,76 @@ public class GuiScreenNotifications extends GuiScreen { slots.handleTouchInput(); } + public void initGui() { + selected = -1; + buttonList.clear(); + buttonList.add(new GuiButton(0, this.width / 2 + 54, this.height - 32, 100, 20, I18n.format("gui.done"))); + buttonList.add(clearAllButton = new GuiButton(1, this.width / 2 - 154, this.height - 32, 100, 20, + I18n.format("notifications.clearAll"))); + int i = priorityOrder[showPriority]; + buttonList.add(priorityButton = new GuiButton(2, this.width / 2 - 50, this.height - 32, 100, 20, + I18n.format("notifications.priority", I18n.format(priorityLangKeys[i])))); + selectedMaxPriority = EnumBadgePriority.getByID(i); + slots = new GuiSlotNotifications(this); + lastUpdate = -69420; + updateList(); + updateButtons(); + } + public void onGuiClosed() { - if(mc.thePlayer != null) { + if (mc.thePlayer != null) { mc.thePlayer.sendQueue.getNotifManager().commitUnreadFlag(); } } + + void updateButtons() { + clearAllButton.enabled = !slots.currentDisplayNotifs.isEmpty(); + } + + void updateList() { + if (mc.thePlayer == null) + return; + ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); + int verHash = showPriority | (mgr.getNotifListUpdateCount() << 2); + if (verHash != lastUpdate) { + lastUpdate = verHash; + EaglercraftUUID selectedUUID = null; + List lst = slots.currentDisplayNotifs; + int oldSelectedId = selected; + if (oldSelectedId >= 0 && oldSelectedId < lst.size()) { + selectedUUID = lst.get(oldSelectedId).badge.badgeUUID; + } + lst.clear(); + lst.addAll(Collections2 + .transform(Collections2.filter(mgr.getNotifLongHistory(), new Predicate() { + @Override + public boolean apply(NotificationBadge input) { + return input.priority.priority >= priorityOrder[showPriority]; + } + }), GuiSlotNotifications.NotifBadgeSlot::new)); + selected = -1; + if (selectedUUID != null) { + for (int i = 0, l = lst.size(); i < l; ++i) { + if (selectedUUID.equals(lst.get(i).badge.badgeUUID)) { + selected = i; + break; + } + } + } + if (selected != -1) { + if (oldSelectedId != selected) { + slots.scrollBy((selected - oldSelectedId) * slots.getSlotHeight()); + } + } + updateButtons(); + } + } + + public void updateScreen() { + if (mc.thePlayer == null) { + mc.displayGuiScreen(parent); + return; + } + updateList(); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiSlotNotifications.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiSlotNotifications.java index e7b4ef3c..f6c0250c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiSlotNotifications.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/GuiSlotNotifications.java @@ -21,44 +21,46 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiSlotNotifications extends GuiSlot { - private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); - private static final ResourceLocation largeNotifBk = new ResourceLocation("eagler:gui/notif_bk_large.png"); - - private static final SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a"); - - final GuiScreenNotifications parent; - final List currentDisplayNotifs; - - int mouseX; - int mouseY; - protected static class NotifBadgeSlot { - + protected final NotificationBadge badge; protected final List cursorEvents = new ArrayList<>(); protected int currentScreenX = -69420; protected int currentScreenY = -69420; - + protected NotifBadgeSlot(NotificationBadge badge) { this.badge = badge; } - + } + private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); + + private static final ResourceLocation largeNotifBk = new ResourceLocation("eagler:gui/notif_bk_large.png"); + + private static final SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a"); + final GuiScreenNotifications parent; + + final List currentDisplayNotifs; + int mouseX; + + int mouseY; + public GuiSlotNotifications(GuiScreenNotifications parent) { super(GuiScreenNotifications.getMinecraft(parent), parent.width, parent.height, 32, parent.height - 44, 68); this.parent = parent; @@ -66,48 +68,242 @@ public class GuiSlotNotifications extends GuiSlot { } @Override - protected int getSize() { - return currentDisplayNotifs.size(); + protected void drawBackground() { + parent.drawBackground(0); + } + + @Override + public void drawScreen(int mouseXIn, int mouseYIn, float parFloat1) { + mouseX = mouseXIn; + mouseY = mouseYIn; + for (int i = 0, l = currentDisplayNotifs.size(); i < l; ++i) { + NotifBadgeSlot slot = currentDisplayNotifs.get(i); + slot.currentScreenX = -69420; + slot.currentScreenY = -69420; + } + super.drawScreen(mouseXIn, mouseYIn, parFloat1); + } + + @Override + protected void drawSlot(int id, int xx, int yy, int width, int height, int ii) { + if (id < currentDisplayNotifs.size()) { + NotifBadgeSlot slot = currentDisplayNotifs.get(id); + slot.currentScreenX = xx; + slot.currentScreenY = yy; + NotificationBadge bd = slot.badge; + if (yy + 32 > this.top && yy + 32 < this.bottom) { + bd.markRead(); + } + GlStateManager.pushMatrix(); + GlStateManager.translate(xx, yy, 0.0f); + mc.getTextureManager().bindTexture(largeNotifBk); + int badgeWidth = getListWidth() - 4; + int badgeHeight = getSlotHeight() - 4; + float r = ((bd.backgroundColor >> 16) & 0xFF) * 0.00392156f; + float g = ((bd.backgroundColor >> 8) & 0xFF) * 0.00392156f; + float b = (bd.backgroundColor & 0xFF) * 0.00392156f; + if (parent.selected != id) { + r *= 0.85f; + g *= 0.85f; + b *= 0.85f; + } + GlStateManager.color(r, g, b, 1.0f); + parent.drawTexturedModalRect(0, 0, 0, bd.unreadFlagRender ? 64 : 0, badgeWidth - 32, 64); + parent.drawTexturedModalRect(badgeWidth - 32, 0, 224, bd.unreadFlagRender ? 64 : 0, 32, 64); + mc.getTextureManager().bindTexture(eaglerGui); + if (bd.priority == EnumBadgePriority.LOW) { + parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 192, 176, 16, 16); + } + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + switch (bd.priority) { + default: + break; + case NORMAL: + parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 208, 176, 16, 16); + break; + case HIGHER: + parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 224, 176, 16, 16); + break; + case HIGHEST: + parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 240, 176, 16, 16); + break; + } + + int bodyYOffset = 16; + + int leftPadding = 6; + int rightPadding = 26; + + int mainIconSW = 32; + boolean mainIconEn = bd.mainIcon != null && bd.mainIcon.isValid(); + if (mainIconEn) { + int iw = bd.mainIcon.texture.getWidth(); + int ih = bd.mainIcon.texture.getHeight(); + float iaspect = (float) iw / (float) ih; + mainIconSW = (int) (32 * iaspect); + leftPadding += Math.min(mainIconSW, 64) + 3; + } + + int textZoneWidth = badgeWidth - leftPadding - rightPadding; + + if (mainIconEn) { + mc.getTextureManager().bindTexture(bd.mainIcon.resource); + ServerNotificationRenderer.drawTexturedRect(6, bodyYOffset, mainIconSW, 32); + } + + boolean titleIconEn = bd.titleIcon != null && bd.titleIcon.isValid(); + if (titleIconEn) { + mc.getTextureManager().bindTexture(bd.titleIcon.resource); + ServerNotificationRenderer.drawTexturedRect(6, 5, 8, 8); + } + + String titleText = ""; + IChatComponent titleComponent = bd.getTitleProfanityFilter(); + if (titleComponent != null) { + titleText = titleComponent.getFormattedText(); + } + + titleText += EnumChatFormatting.GRAY + (titleText.length() > 0 ? " @ " : "@ ") + + (bd.unreadFlagRender ? EnumChatFormatting.YELLOW : EnumChatFormatting.GRAY) + + formatAge(bd.serverTimestamp); + + GlStateManager.pushMatrix(); + GlStateManager.translate(6 + (titleIconEn ? 10 : 0), 6, 0.0f); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + mc.fontRendererObj.drawStringWithShadow(titleText, 0, 0, bd.titleTxtColor); + GlStateManager.popMatrix(); + + String sourceText = null; + IChatComponent sourceComponent = bd.getSourceProfanityFilter(); + if (sourceComponent != null) { + sourceText = sourceComponent.getFormattedText(); + if (sourceText.length() == 0) { + sourceText = null; + } + } + + List bodyLines = null; + float bodyFontSize = (sourceText != null || titleIconEn) ? 0.75f : 1.0f; + IChatComponent bodyComponent = bd.getBodyProfanityFilter(); + if (bodyComponent != null) { + bodyLines = GuiUtilRenderComponents.func_178908_a(bodyComponent, (int) (textZoneWidth / bodyFontSize), + mc.fontRendererObj, true, true); + + int maxHeight = badgeHeight - (sourceText != null ? 32 : 22); + int maxLines = MathHelper.floor_float(maxHeight / (9 * bodyFontSize)); + if (bodyLines.size() > maxLines) { + bodyLines = bodyLines.subList(0, maxLines); + IChatComponent cmp = bodyLines.get(maxLines - 1); + List siblings = cmp.getSiblings(); + IChatComponent dots = new ChatComponentText("..."); + if (siblings != null && siblings.size() > 0) { + dots.setChatStyle(siblings.get(siblings.size() - 1).getChatStyle()); + } + cmp.appendSibling(dots); + } + } + + slot.cursorEvents.clear(); + if (bodyLines != null && !bodyLines.isEmpty()) { + GlStateManager.pushMatrix(); + GlStateManager.translate(leftPadding, bodyYOffset, 0.0f); + int l = bodyLines.size(); + GlStateManager.scale(bodyFontSize, bodyFontSize, bodyFontSize); + IChatComponent toolTip = null; + for (int i = 0; i < l; ++i) { + int startXLocal = 0; + int startXReal = leftPadding; + for (IChatComponent comp : bodyLines.get(i)) { + int w = mc.fontRendererObj.drawStringWithShadow( + comp.getChatStyle().getFormattingCode() + comp.getUnformattedTextForChat(), startXLocal, + i * 9, bd.bodyTxtColor) - startXLocal; + ClickEvent clickEvent = comp.getChatStyle().getChatClickEvent(); + HoverEvent hoverEvent = toolTip == null ? comp.getChatStyle().getChatHoverEvent() : null; + if (clickEvent != null && !clickEvent.getAction().shouldAllowInChat()) { + clickEvent = null; + } + if (hoverEvent != null && !hoverEvent.getAction().shouldAllowInChat()) { + hoverEvent = null; + } + if (clickEvent != null) { + slot.cursorEvents.add(new ClickEventZone(startXReal + (int) (startXLocal * bodyFontSize), + bodyYOffset + (int) (i * 9 * bodyFontSize), (int) (w * bodyFontSize), + (int) (9 * bodyFontSize), comp, clickEvent != null, hoverEvent != null)); + } + if (hoverEvent != null) { + int px = xx + startXReal + (int) (startXLocal * bodyFontSize); + int py = yy + bodyYOffset + (int) (i * 9 * bodyFontSize); + if (mouseX >= px && mouseX < px + (int) (w * bodyFontSize) && mouseY >= py + && mouseY < py + (int) (9 * bodyFontSize)) { + toolTip = comp; + } + } + startXLocal += w; + } + } + GlStateManager.popMatrix(); + if (toolTip != null) { + parent.handleComponentHover(toolTip, mouseX - xx, mouseY - yy); + } + } + + if (sourceText != null) { + GlStateManager.pushMatrix(); + GlStateManager.translate(badgeWidth - 21, badgeHeight - 5, 0.0f); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + mc.fontRendererObj.drawStringWithShadow(sourceText, -mc.fontRendererObj.getStringWidth(sourceText) - 4, + -10, bd.sourceTxtColor); + GlStateManager.popMatrix(); + } + + GlStateManager.popMatrix(); + } } @Override protected void elementClicked(int id, boolean doubleClk, int xx, int yy) { - if(selectedElement != id) return; //workaround for vanilla bs - if(id < currentDisplayNotifs.size()) { + if (selectedElement != id) + return; // workaround for vanilla bs + if (id < currentDisplayNotifs.size()) { NotifBadgeSlot slot = currentDisplayNotifs.get(id); - if(slot.currentScreenY != -69420) { + if (slot.currentScreenY != -69420) { int w = getListWidth(); int localX = xx - slot.currentScreenX; int localY = yy - slot.currentScreenY; - if(localX >= w - 22 && localX < w - 5 && localY >= 5 && localY < 21) { + if (localX >= w - 22 && localX < w - 5 && localY >= 5 && localY < 21) { slot.badge.removeNotif(); - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); return; } IChatComponent cmp = slot.badge.bodyComponent; - if(cmp != null) { - if(doubleClk) { + if (cmp != null) { + if (doubleClk) { if (cmp.getChatStyle().getChatClickEvent() != null && cmp.getChatStyle().getChatClickEvent().getAction().shouldAllowInChat()) { - if(parent.handleComponentClick(cmp)) { - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + if (parent.handleComponentClick(cmp)) { + mc.getSoundHandler().playSound( + PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); return; } } - }else { - if(parent.selected != id) { + } else { + if (parent.selected != id) { parent.selected = id; - }else { + } else { List cursorEvents = slot.cursorEvents; - if(cursorEvents != null && !cursorEvents.isEmpty()) { - for(int j = 0, m = cursorEvents.size(); j < m; ++j) { + if (cursorEvents != null && !cursorEvents.isEmpty()) { + for (int j = 0, m = cursorEvents.size(); j < m; ++j) { ClickEventZone evt = cursorEvents.get(j); - if(evt.hasClickEvent) { + if (evt.hasClickEvent) { int offsetPosX = slot.currentScreenX + evt.posX; int offsetPosY = slot.currentScreenY + evt.posY; - if(xx >= offsetPosX && yy >= offsetPosY && xx < offsetPosX + evt.width && yy < offsetPosY + evt.height) { - if(parent.handleComponentClick(evt.chatComponent)) { - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + if (xx >= offsetPosX && yy >= offsetPosY && xx < offsetPosX + evt.width + && yy < offsetPosY + evt.height) { + if (parent.handleComponentClick(evt.chatComponent)) { + mc.getSoundHandler().playSound(PositionedSoundRecord + .create(new ResourceLocation("gui.button.press"), 1.0F)); return; } } @@ -121,199 +317,13 @@ public class GuiSlotNotifications extends GuiSlot { } } - @Override - protected boolean isSelected(int var1) { - return var1 == parent.selected; - } - - @Override - protected void drawBackground() { - parent.drawBackground(0); - } - - @Override - protected void drawSlot(int id, int xx, int yy, int width, int height, int ii) { - if(id < currentDisplayNotifs.size()) { - NotifBadgeSlot slot = currentDisplayNotifs.get(id); - slot.currentScreenX = xx; - slot.currentScreenY = yy; - NotificationBadge bd = slot.badge; - if(yy + 32 > this.top && yy + 32 < this.bottom) { - bd.markRead(); - } - GlStateManager.pushMatrix(); - GlStateManager.translate(xx, yy, 0.0f); - mc.getTextureManager().bindTexture(largeNotifBk); - int badgeWidth = getListWidth() - 4; - int badgeHeight = getSlotHeight() - 4; - float r = ((bd.backgroundColor >> 16) & 0xFF) * 0.00392156f; - float g = ((bd.backgroundColor >> 8) & 0xFF) * 0.00392156f; - float b = (bd.backgroundColor & 0xFF) * 0.00392156f; - if(parent.selected != id) { - r *= 0.85f; - g *= 0.85f; - b *= 0.85f; - } - GlStateManager.color(r, g, b, 1.0f); - parent.drawTexturedModalRect(0, 0, 0, bd.unreadFlagRender ? 64 : 0, badgeWidth - 32, 64); - parent.drawTexturedModalRect(badgeWidth - 32, 0, 224, bd.unreadFlagRender ? 64 : 0, 32, 64); - mc.getTextureManager().bindTexture(eaglerGui); - if(bd.priority == EnumBadgePriority.LOW) { - parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 192, 176, 16, 16); - } - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - switch(bd.priority) { - default: - break; - case NORMAL: - parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 208, 176, 16, 16); - break; - case HIGHER: - parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 224, 176, 16, 16); - break; - case HIGHEST: - parent.drawTexturedModalRect(badgeWidth - 21, badgeHeight - 21, 240, 176, 16, 16); - break; - } - - int bodyYOffset = 16; - - int leftPadding = 6; - int rightPadding = 26; - - int mainIconSW = 32; - boolean mainIconEn = bd.mainIcon != null && bd.mainIcon.isValid(); - if(mainIconEn) { - int iw = bd.mainIcon.texture.getWidth(); - int ih = bd.mainIcon.texture.getHeight(); - float iaspect = (float)iw / (float)ih; - mainIconSW = (int)(32 * iaspect); - leftPadding += Math.min(mainIconSW, 64) + 3; - } - - int textZoneWidth = badgeWidth - leftPadding - rightPadding; - - if(mainIconEn) { - mc.getTextureManager().bindTexture(bd.mainIcon.resource); - ServerNotificationRenderer.drawTexturedRect(6, bodyYOffset, mainIconSW, 32); - } - - boolean titleIconEn = bd.titleIcon != null && bd.titleIcon.isValid(); - if(titleIconEn) { - mc.getTextureManager().bindTexture(bd.titleIcon.resource); - ServerNotificationRenderer.drawTexturedRect(6, 5, 8, 8); - } - - String titleText = ""; - IChatComponent titleComponent = bd.getTitleProfanityFilter(); - if(titleComponent != null) { - titleText = titleComponent.getFormattedText(); - } - - titleText += EnumChatFormatting.GRAY + (titleText.length() > 0 ? " @ " : "@ ") - + (bd.unreadFlagRender ? EnumChatFormatting.YELLOW : EnumChatFormatting.GRAY) - + formatAge(bd.serverTimestamp); - - GlStateManager.pushMatrix(); - GlStateManager.translate(6 + (titleIconEn ? 10 : 0), 6, 0.0f); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - mc.fontRendererObj.drawStringWithShadow(titleText, 0, 0, bd.titleTxtColor); - GlStateManager.popMatrix(); - - String sourceText = null; - IChatComponent sourceComponent = bd.getSourceProfanityFilter(); - if(sourceComponent != null) { - sourceText = sourceComponent.getFormattedText(); - if(sourceText.length() == 0) { - sourceText = null; - } - } - - List bodyLines = null; - float bodyFontSize = (sourceText != null || titleIconEn) ? 0.75f : 1.0f; - IChatComponent bodyComponent = bd.getBodyProfanityFilter(); - if(bodyComponent != null) { - bodyLines = GuiUtilRenderComponents.func_178908_a(bodyComponent, (int) (textZoneWidth / bodyFontSize), - mc.fontRendererObj, true, true); - - int maxHeight = badgeHeight - (sourceText != null ? 32 : 22); - int maxLines = MathHelper.floor_float(maxHeight / (9 * bodyFontSize)); - if(bodyLines.size() > maxLines) { - bodyLines = bodyLines.subList(0, maxLines); - IChatComponent cmp = bodyLines.get(maxLines - 1); - List siblings = cmp.getSiblings(); - IChatComponent dots = new ChatComponentText("..."); - if(siblings != null && siblings.size() > 0) { - dots.setChatStyle(siblings.get(siblings.size() - 1).getChatStyle()); - } - cmp.appendSibling(dots); - } - } - - slot.cursorEvents.clear(); - if(bodyLines != null && !bodyLines.isEmpty()) { - GlStateManager.pushMatrix(); - GlStateManager.translate(leftPadding, bodyYOffset, 0.0f); - int l = bodyLines.size(); - GlStateManager.scale(bodyFontSize, bodyFontSize, bodyFontSize); - IChatComponent toolTip = null; - for(int i = 0; i < l; ++i) { - int startXLocal = 0; - int startXReal = leftPadding; - for(IChatComponent comp : bodyLines.get(i)) { - int w = mc.fontRendererObj.drawStringWithShadow( - comp.getChatStyle().getFormattingCode() + comp.getUnformattedTextForChat(), startXLocal, - i * 9, bd.bodyTxtColor) - startXLocal; - ClickEvent clickEvent = comp.getChatStyle().getChatClickEvent(); - HoverEvent hoverEvent = toolTip == null ? comp.getChatStyle().getChatHoverEvent() : null; - if(clickEvent != null && !clickEvent.getAction().shouldAllowInChat()) { - clickEvent = null; - } - if(hoverEvent != null && !hoverEvent.getAction().shouldAllowInChat()) { - hoverEvent = null; - } - if(clickEvent != null) { - slot.cursorEvents.add(new ClickEventZone(startXReal + (int) (startXLocal * bodyFontSize), - bodyYOffset + (int) (i * 9 * bodyFontSize), (int) (w * bodyFontSize), - (int) (9 * bodyFontSize), comp, clickEvent != null, hoverEvent != null)); - } - if(hoverEvent != null) { - int px = xx + startXReal + (int) (startXLocal * bodyFontSize); - int py = yy + bodyYOffset + (int) (i * 9 * bodyFontSize); - if (mouseX >= px && mouseX < px + (int) (w * bodyFontSize) && mouseY >= py - && mouseY < py + (int) (9 * bodyFontSize)) { - toolTip = comp; - } - } - startXLocal += w; - } - } - GlStateManager.popMatrix(); - if(toolTip != null) { - parent.handleComponentHover(toolTip, mouseX - xx, mouseY - yy); - } - } - - if(sourceText != null) { - GlStateManager.pushMatrix(); - GlStateManager.translate(badgeWidth - 21, badgeHeight - 5, 0.0f); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - mc.fontRendererObj.drawStringWithShadow(sourceText, -mc.fontRendererObj.getStringWidth(sourceText) - 4, -10, bd.sourceTxtColor); - GlStateManager.popMatrix(); - } - - GlStateManager.popMatrix(); - } - } - private String formatAge(long serverTimestamp) { long cur = System.currentTimeMillis(); long daysAgo = Math.round((cur - serverTimestamp) / 86400000.0); String ret = dateFormat.format(new Date(serverTimestamp)); - if(daysAgo > 0l) { + if (daysAgo > 0l) { ret += " (" + daysAgo + (daysAgo == 1l ? " day" : " days") + " ago)"; - }else if(daysAgo < 0l) { + } else if (daysAgo < 0l) { ret += " (in " + -daysAgo + (daysAgo == -1l ? " day" : " days") + ")"; } return ret; @@ -325,14 +335,12 @@ public class GuiSlotNotifications extends GuiSlot { } @Override - public void drawScreen(int mouseXIn, int mouseYIn, float parFloat1) { - mouseX = mouseXIn; - mouseY = mouseYIn; - for(int i = 0, l = currentDisplayNotifs.size(); i < l; ++i) { - NotifBadgeSlot slot = currentDisplayNotifs.get(i); - slot.currentScreenX = -69420; - slot.currentScreenY = -69420; - } - super.drawScreen(mouseXIn, mouseYIn, parFloat1); + protected int getSize() { + return currentDisplayNotifs.size(); + } + + @Override + protected boolean isSelected(int var1) { + return var1 == parent.selected; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationBadge.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationBadge.java index 6f17cb0b..cb43d619 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationBadge.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationBadge.java @@ -11,20 +11,21 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NotificationBadge { - + public final ServerNotificationManager mgr; public final EaglercraftUUID badgeUUID; public final IChatComponent bodyComponent; @@ -53,7 +54,7 @@ public class NotificationBadge { protected long hideAtMillis = -1l; protected boolean unreadFlag = true; protected boolean unreadFlagRender = true; - + protected NotificationBadge(ServerNotificationManager mgr, EaglercraftUUID badgeUUID, IChatComponent bodyComponent, IChatComponent titleComponent, IChatComponent sourceComponent, long clientTimestamp, long serverTimestamp, boolean silent, EnumBadgePriority priority, NotificationIcon mainIcon, NotificationIcon titleIcon, @@ -77,29 +78,41 @@ public class NotificationBadge { this.titleTxtColor = titleTxtColor; this.sourceTxtColor = sourceTxtColor; } - - protected void incrIconRefcounts() { - if(mainIcon != null) { - mainIcon.retain(); - } - if(titleIcon != null) { - titleIcon.retain(); - } - } - + protected void decrIconRefcounts() { deleteGLTexture(); - if(mainIcon != null) { + if (mainIcon != null) { mainIcon.release(); } - if(titleIcon != null) { + if (titleIcon != null) { titleIcon.release(); } } - protected CachedNotifBadgeTexture getGLTexture(ServerNotificationRenderer renderer, int scaleFactor, boolean showXButton) { + protected void deleteGLTexture() { + if (currentCacheGLTexture != null) { + GlStateManager.deleteTexture(currentCacheGLTexture.glTexture); + currentCacheGLTexture = null; + } + } + + public IChatComponent getBodyProfanityFilter() { + if (Minecraft.getMinecraft().isEnableProfanityFilter()) { + if (bodyComponentProfanityFilter == null && bodyComponent != null) { + bodyComponentProfanityFilter = ProfanityFilter.getInstance() + .profanityFilterChatComponent(bodyComponent); + } + return bodyComponentProfanityFilter; + } else { + return bodyComponent; + } + } + + protected CachedNotifBadgeTexture getGLTexture(ServerNotificationRenderer renderer, int scaleFactor, + boolean showXButton) { boolean profanityFilter = Minecraft.getMinecraft().isEnableProfanityFilter(); - if(currentCacheGLTexture == null || currentCacheScaleFac != scaleFactor || currentCacheXButton != showXButton || currentCacheProfanityFilter != profanityFilter) { + if (currentCacheGLTexture == null || currentCacheScaleFac != scaleFactor || currentCacheXButton != showXButton + || currentCacheProfanityFilter != profanityFilter) { deleteGLTexture(); currentCacheGLTexture = renderer.renderBadge(this, scaleFactor, showXButton); currentCacheScaleFac = scaleFactor; @@ -109,63 +122,56 @@ public class NotificationBadge { return currentCacheGLTexture; } - protected void deleteGLTexture() { - if(currentCacheGLTexture != null) { - GlStateManager.deleteTexture(currentCacheGLTexture.glTexture); - currentCacheGLTexture = null; + public IChatComponent getSourceProfanityFilter() { + if (Minecraft.getMinecraft().isEnableProfanityFilter()) { + if (sourceComponentProfanityFilter == null && sourceComponent != null) { + sourceComponentProfanityFilter = ProfanityFilter.getInstance() + .profanityFilterChatComponent(sourceComponent); + } + return sourceComponentProfanityFilter; + } else { + return sourceComponent; + } + } + + public IChatComponent getTitleProfanityFilter() { + if (Minecraft.getMinecraft().isEnableProfanityFilter()) { + if (titleComponentProfanityFilter == null && titleComponent != null) { + titleComponentProfanityFilter = ProfanityFilter.getInstance() + .profanityFilterChatComponent(titleComponent); + } + return titleComponentProfanityFilter; + } else { + return titleComponent; } } public void hideNotif() { - if(hideAtMillis == -1l) { + if (hideAtMillis == -1l) { markRead(); unreadFlagRender = false; hideAtMillis = EagRuntime.steadyTimeMillis(); } } + protected void incrIconRefcounts() { + if (mainIcon != null) { + mainIcon.retain(); + } + if (titleIcon != null) { + titleIcon.retain(); + } + } + + public void markRead() { + if (unreadFlag) { + unreadFlag = false; + --mgr.unreadCounter; + } + } + public void removeNotif() { mgr.removeNotifFromActiveList(badgeUUID); } - public void markRead() { - if(unreadFlag) { - unreadFlag = false; - --mgr.unreadCounter; - } - } - - public IChatComponent getBodyProfanityFilter() { - if(Minecraft.getMinecraft().isEnableProfanityFilter()) { - if(bodyComponentProfanityFilter == null && bodyComponent != null) { - bodyComponentProfanityFilter = ProfanityFilter.getInstance().profanityFilterChatComponent(bodyComponent); - } - return bodyComponentProfanityFilter; - }else { - return bodyComponent; - } - } - - public IChatComponent getTitleProfanityFilter() { - if(Minecraft.getMinecraft().isEnableProfanityFilter()) { - if(titleComponentProfanityFilter == null && titleComponent != null) { - titleComponentProfanityFilter = ProfanityFilter.getInstance().profanityFilterChatComponent(titleComponent); - } - return titleComponentProfanityFilter; - }else { - return titleComponent; - } - } - - public IChatComponent getSourceProfanityFilter() { - if(Minecraft.getMinecraft().isEnableProfanityFilter()) { - if(sourceComponentProfanityFilter == null && sourceComponent != null) { - sourceComponentProfanityFilter = ProfanityFilter.getInstance().profanityFilterChatComponent(sourceComponent); - } - return sourceComponentProfanityFilter; - }else { - return sourceComponent; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationIcon.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationIcon.java index e67df09c..fb1585ac 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationIcon.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/NotificationIcon.java @@ -7,14 +7,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,16 +37,16 @@ public class NotificationIcon { this.resource = new ResourceLocation("eagler:gui/server/notifs/tex_" + notifIconTmpId++); } - public void retain() { - ++refCount; + public boolean isValid() { + return serverRegistered || refCount > 0; } public void release() { --refCount; } - public boolean isValid() { - return serverRegistered || refCount > 0; + public void retain() { + ++refCount; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationManager.java index 27b51590..ccb741d2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationManager.java @@ -30,14 +30,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,33 +47,95 @@ public class ServerNotificationManager { private static final Logger logger = LogManager.getLogger("ServerNotificationManager"); - private final Map activeIcons = new HashMap<>(); - private final Map activeNotifications = new HashMap<>(); + protected static final Comparator clientAgeComparator = (a, b) -> { + return (int) (b.clientTimestamp - a.clientTimestamp); + }; + private final Map activeIcons = new HashMap<>(); + private final Map activeNotifications = new HashMap<>(); private List sortedNotifList = new ArrayList<>(0); private List sortedDisplayNotifList = new ArrayList<>(0); private int updateCounter = 0; private long lastCleanup = EagRuntime.steadyTimeMillis(); private final TextureManager textureMgr; + protected int unreadCounter = 0; public ServerNotificationManager() { this.textureMgr = Minecraft.getMinecraft().getTextureManager(); } + protected void addNotifToActiveList(NotificationBadge badge) { + NotificationBadge exists = activeNotifications.put(badge.badgeUUID, badge); + if (exists != null) { + exists.decrIconRefcounts(); + } + badge.incrIconRefcounts(); + resortLists(); + } + + public void commitUnreadFlag() { + for (NotificationBadge badge : activeNotifications.values()) { + badge.unreadFlagRender = badge.unreadFlag; + } + } + + public void destroy() { + for (NotificationIcon icn : activeIcons.values()) { + textureMgr.deleteTexture(icn.resource); + } + activeIcons.clear(); + activeNotifications.clear(); + sortedNotifList = null; + sortedDisplayNotifList = null; + } + + private NotificationIcon getIcon(long uuidMost, long uuidLeast) { + if (uuidMost == 0l && uuidLeast == 0l) { + return null; + } + return activeIcons.get(new EaglercraftUUID(uuidMost, uuidLeast)); + } + + public List getNotifBadgesToDisplay() { + return sortedDisplayNotifList; + } + + public int getNotifListUpdateCount() { + return updateCounter; + } + + public List getNotifLongHistory() { + return sortedNotifList; + } + + public int getUnread() { + if (unreadCounter < 0) + unreadCounter = 0; + return unreadCounter; + } + + public void markRead() { + for (NotificationBadge badge : activeNotifications.values()) { + badge.unreadFlag = false; + badge.unreadFlagRender = false; + } + unreadCounter = 0; + } + public void processPacketAddIcons(SPacketNotifIconsRegisterV4EAG packet) { - for(SPacketNotifIconsRegisterV4EAG.CreateIcon icn : packet.iconsToCreate) { - if(icn.uuidMost == 0 && icn.uuidLeast == 0) { + for (SPacketNotifIconsRegisterV4EAG.CreateIcon icn : packet.iconsToCreate) { + if (icn.uuidMost == 0 && icn.uuidLeast == 0) { logger.error("Skipping notification icon with UUID 0!"); continue; } EaglercraftUUID uuid = new EaglercraftUUID(icn.uuidMost, icn.uuidLeast); PacketImageData imageData = icn.imageData; NotificationIcon existing = activeIcons.get(uuid); - if(existing != null) { + if (existing != null) { if (existing.texture.getWidth() != imageData.width || existing.texture.getHeight() != imageData.height) { logger.error("Error: server tried to change the dimensions of icon {}!", uuid); - }else if(!Arrays.equals(existing.texture.getData(), imageData.rgba)) { + } else if (!Arrays.equals(existing.texture.getData(), imageData.rgba)) { existing.texture.copyPixelsIn(ImageData.swapRB(imageData.rgba)); } existing.serverRegistered = true; @@ -85,10 +148,14 @@ public class ServerNotificationManager { } } + public void processPacketHideBadge(SPacketNotifBadgeHideV4EAG packet) { + removeNotifFromActiveList(new EaglercraftUUID(packet.badgeUUIDLeast, packet.badgeUUIDMost)); + } + public void processPacketRemIcons(SPacketNotifIconsReleaseV4EAG packet) { - for(SPacketNotifIconsReleaseV4EAG.DestroyIcon icn : packet.iconsToDestroy) { + for (SPacketNotifIconsReleaseV4EAG.DestroyIcon icn : packet.iconsToDestroy) { NotificationIcon existing = activeIcons.get(new EaglercraftUUID(icn.uuidMost, icn.uuidLeast)); - if(existing != null) { + if (existing != null) { existing.serverRegistered = false; } } @@ -97,94 +164,67 @@ public class ServerNotificationManager { public void processPacketShowBadge(SPacketNotifBadgeShowV4EAG packet) { EaglercraftUUID newUuid = new EaglercraftUUID(packet.badgeUUIDMost, packet.badgeUUIDLeast); NotificationBadge existing = activeNotifications.get(newUuid); - if(existing != null) { + if (existing != null) { logger.error("Duplicate notification UUID {}, all notifications should have unique UUIDs!", newUuid); return; } NotificationBadge newBadge = new NotificationBadge(this, newUuid, - !StringUtils.isAllBlank(packet.bodyComponent) ? IChatComponent.Serializer.jsonToComponent(packet.bodyComponent) : null, - !StringUtils.isAllBlank(packet.titleComponent) ? IChatComponent.Serializer.jsonToComponent(packet.titleComponent) : null, - !StringUtils.isAllBlank(packet.sourceComponent) ? IChatComponent.Serializer.jsonToComponent(packet.sourceComponent) : null, + !StringUtils.isAllBlank(packet.bodyComponent) + ? IChatComponent.Serializer.jsonToComponent(packet.bodyComponent) + : null, + !StringUtils.isAllBlank(packet.titleComponent) + ? IChatComponent.Serializer.jsonToComponent(packet.titleComponent) + : null, + !StringUtils.isAllBlank(packet.sourceComponent) + ? IChatComponent.Serializer.jsonToComponent(packet.sourceComponent) + : null, EagRuntime.steadyTimeMillis(), packet.originalTimestampSec * 1000l, packet.silent, packet.priority, getIcon(packet.mainIconUUIDMost, packet.mainIconUUIDLeast), - getIcon(packet.titleIconUUIDMost, packet.titleIconUUIDLeast), packet.hideAfterSec, packet.expireAfterSec, - packet.backgroundColor, packet.bodyTxtColor, packet.titleTxtColor, packet.sourceTxtColor); + getIcon(packet.titleIconUUIDMost, packet.titleIconUUIDLeast), packet.hideAfterSec, + packet.expireAfterSec, packet.backgroundColor, packet.bodyTxtColor, packet.titleTxtColor, + packet.sourceTxtColor); ++unreadCounter; addNotifToActiveList(newBadge); } - private NotificationIcon getIcon(long uuidMost, long uuidLeast) { - if(uuidMost == 0l && uuidLeast == 0l) { - return null; - } - return activeIcons.get(new EaglercraftUUID(uuidMost, uuidLeast)); - } - - public void processPacketHideBadge(SPacketNotifBadgeHideV4EAG packet) { - removeNotifFromActiveList(new EaglercraftUUID(packet.badgeUUIDLeast, packet.badgeUUIDMost)); - } - - public int getNotifListUpdateCount() { - return updateCounter; - } - - public List getNotifBadgesToDisplay() { - return sortedDisplayNotifList; - } - - public List getNotifLongHistory() { - return sortedNotifList; - } - - protected void addNotifToActiveList(NotificationBadge badge) { - NotificationBadge exists = activeNotifications.put(badge.badgeUUID, badge); - if(exists != null) { - exists.decrIconRefcounts(); - } - badge.incrIconRefcounts(); - resortLists(); - } - - protected void removeNotifFromActiveList(EaglercraftUUID badge) { - NotificationBadge exists = activeNotifications.remove(badge); - if(exists != null) { - exists.decrIconRefcounts(); - resortLists(); - } - } - protected void removeAllNotifFromActiveList(Collection badges) { boolean resort = false; - for(NotificationBadge badge : badges) { + for (NotificationBadge badge : badges) { NotificationBadge exists = activeNotifications.remove(badge.badgeUUID); - if(exists != null) { + if (exists != null) { exists.decrIconRefcounts(); resort = true; } } - if(resort) { + if (resort) { resortLists(); } } - protected static final Comparator clientAgeComparator = (a, b) -> { - return (int)(b.clientTimestamp - a.clientTimestamp); - }; + protected void removeNotifFromActiveList(EaglercraftUUID badge) { + NotificationBadge exists = activeNotifications.remove(badge); + if (exists != null) { + exists.decrIconRefcounts(); + resortLists(); + } + } private void resortLists() { updateCounter++; int ll = activeNotifications.size(); - if(!sortedNotifList.isEmpty()) sortedNotifList = new ArrayList<>(ll); - if(!sortedDisplayNotifList.isEmpty()) sortedDisplayNotifList = new ArrayList<>(Math.min(ll, 4)); - if(ll > 0) { + if (!sortedNotifList.isEmpty()) + sortedNotifList = new ArrayList<>(ll); + if (!sortedDisplayNotifList.isEmpty()) + sortedDisplayNotifList = new ArrayList<>(Math.min(ll, 4)); + if (ll > 0) { sortedNotifList.addAll(activeNotifications.values()); Collections.sort(sortedNotifList, clientAgeComparator); long millis = EagRuntime.steadyTimeMillis(); - for(int i = 0, l = sortedNotifList.size(); i < l; ++i) { + for (int i = 0, l = sortedNotifList.size(); i < l; ++i) { NotificationBadge bd = sortedNotifList.get(i); - if(millis - bd.clientTimestamp < (long)(bd.hideAfterSec * 1000)) { + if (millis - bd.clientTimestamp < (long) (bd.hideAfterSec * 1000)) { sortedDisplayNotifList.add(bd); - }else { + } else { bd.deleteGLTexture(); } } @@ -193,85 +233,56 @@ public class ServerNotificationManager { public void runTick() { long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastCleanup > 2500l) { + if (millis - lastCleanup > 2500l) { lastCleanup = millis; int len = sortedNotifList.size(); - if(len > 128) { + if (len > 128) { removeAllNotifFromActiveList(new ArrayList(sortedNotifList.subList(128, len))); } Iterator itr = activeIcons.values().iterator(); - while(itr.hasNext()) { + while (itr.hasNext()) { NotificationIcon icn = itr.next(); - if(!icn.isValid()) { + if (!icn.isValid()) { itr.remove(); textureMgr.deleteTexture(icn.resource); } } - if(!sortedDisplayNotifList.isEmpty()) { + if (!sortedDisplayNotifList.isEmpty()) { Iterator itr2 = sortedDisplayNotifList.iterator(); - while(itr2.hasNext()) { + while (itr2.hasNext()) { NotificationBadge bd = itr2.next(); - if(bd.hideAtMillis != -1l) { - if(millis - bd.hideAtMillis > 500l) { + if (bd.hideAtMillis != -1l) { + if (millis - bd.hideAtMillis > 500l) { bd.deleteGLTexture(); itr2.remove(); } - }else { + } else { long age = millis - bd.clientTimestamp; - if(age > (long)(bd.hideAfterSec * 1000) || age > (long)(bd.expireAfterSec * 1000)) { + if (age > (long) (bd.hideAfterSec * 1000) || age > (long) (bd.expireAfterSec * 1000)) { bd.deleteGLTexture(); itr2.remove(); } } } } - if(!activeNotifications.isEmpty()) { + if (!activeNotifications.isEmpty()) { Iterator itr3 = activeNotifications.values().iterator(); List toDelete = null; - while(itr3.hasNext()) { + while (itr3.hasNext()) { NotificationBadge bd = itr3.next(); long age = millis - bd.clientTimestamp; - if(age > (long)(bd.expireAfterSec * 1000)) { - if(toDelete == null) { + if (age > (long) (bd.expireAfterSec * 1000)) { + if (toDelete == null) { toDelete = new ArrayList<>(); } toDelete.add(bd); } } - if(toDelete != null) { + if (toDelete != null) { removeAllNotifFromActiveList(toDelete); } } } } - public int getUnread() { - if(unreadCounter < 0) unreadCounter = 0; - return unreadCounter; - } - - public void commitUnreadFlag() { - for(NotificationBadge badge : activeNotifications.values()) { - badge.unreadFlagRender = badge.unreadFlag; - } - } - - public void markRead() { - for(NotificationBadge badge : activeNotifications.values()) { - badge.unreadFlag = false; - badge.unreadFlagRender = false; - } - unreadCounter = 0; - } - - public void destroy() { - for(NotificationIcon icn : activeIcons.values()) { - textureMgr.deleteTexture(icn.resource); - } - activeIcons.clear(); - activeNotifications.clear(); - sortedNotifList = null; - sortedDisplayNotifList = null; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationRenderer.java index b61b5434..5a8631d0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/notifications/ServerNotificationRenderer.java @@ -1,5 +1,30 @@ package net.lax1dude.eaglercraft.v1_8.notifications; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_QUADS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VIEWPORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT0; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_FRAMEBUFFER; + import java.util.ArrayList; import java.util.List; @@ -25,21 +50,18 @@ import net.minecraft.util.IChatComponent; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,441 +70,12 @@ public class ServerNotificationRenderer { protected static final Logger logger = LogManager.getLogger("ServerNotificationRenderer"); - protected Minecraft mc; - protected int width; - protected int height; - protected int scaleFactor; - - protected IFramebufferGL rendererFramebuffer; - protected static final int BADGE_WIDTH = 160; protected static final int BADGE_HEIGHT = 64; - private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); - public ServerNotificationRenderer() { - - } - - public void init() { - destroy(); - rendererFramebuffer = _wglCreateFramebuffer(); - } - - public void setResolution(Minecraft mc, int w, int h, int scaleFactor) { - this.mc = mc; - this.width = w; - this.height = h; - this.scaleFactor = scaleFactor; - } - - public boolean handleClicked(GuiScreen currentScreen, int posX, int posY) { - if(mc.thePlayer == null) return false; - ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); - List lst = mgr.getNotifBadgesToDisplay(); - if(!lst.isEmpty()) { - int baseOffset = mc.guiAchievement.getHeight(); - boolean showX = (currentScreen instanceof GuiChat); - if(showX) { - baseOffset += 25; // exit button in chat screen; - } - long millis = EagRuntime.steadyTimeMillis(); - for(int i = 0, l = lst.size(); i < l; ++i) { - NotificationBadge badge = lst.get(i); - CachedNotifBadgeTexture tex = badge.currentCacheGLTexture; - if(tex != null) { - int baseX = width - tex.width; - float texHeight = tex.height; - float timeRemainingSec; - long age = millis - badge.clientTimestamp; - if(badge.hideAtMillis != -1l) { - timeRemainingSec = (float)((double)(500l - (millis - badge.hideAtMillis)) * 0.001); - }else { - timeRemainingSec = (float)((double)((long)badge.hideAfterSec * 1000l - age) * 0.001); - } - timeRemainingSec = Math.min((float)(age * 0.001) + 0.001f, timeRemainingSec); - float f = MathHelper.clamp_float(timeRemainingSec * 3.0F, 0.0F, 1.0F); - f *= f; - texHeight *= f; - if(badge.hideAtMillis == -1l) { - if(posX >= baseX && posX < width && posY >= baseOffset && posY < baseOffset + texHeight) { - if(showX) { - int xposX = baseX + tex.width - 21; - int xposY = baseOffset + 5; - if(posX >= xposX && posY >= xposY && posX < xposX + 16 && posY < xposY + 16) { - badge.hideNotif(); - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - return true; - } - } - if(tex.rootClickEvent != null) { - if(currentScreen.handleComponentClick(tex.rootClickEvent)) { - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - return true; - } - } - List cursorEvents = tex.cursorEvents; - if(tex.hasClickEvents && cursorEvents != null) { - for(int j = 0, m = cursorEvents.size(); j < m; ++j) { - ClickEventZone evt = cursorEvents.get(j); - if(evt.hasClickEvent) { - int offsetPosX = baseX + evt.posX; - int offsetPosY = baseOffset + evt.posY; - if(posX >= offsetPosX && posY >= offsetPosY && posX < offsetPosX + evt.width && posY < offsetPosY + evt.height) { - if(currentScreen.handleComponentClick(evt.chatComponent)) { - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - return true; - } - } - } - } - } - } - } - baseOffset += texHeight; - } - } - } - return false; - } - - public void renderOverlay(int mouseX, int mouseY) { - if(mc.thePlayer == null) return; - ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); - List lst = mgr.getNotifBadgesToDisplay(); - if(!lst.isEmpty()) { - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - boolean showXButtons = false; - int baseOffset = mc.guiAchievement.getHeight(); - if(mc.currentScreen != null) { - if(mc.currentScreen instanceof GuiChat) { - baseOffset += 25; // exit button in chat screen; - showXButtons = true; - }else if(mc.currentScreen instanceof GuiScreenNotifications) { - return; - } - } - long millis = EagRuntime.steadyTimeMillis(); - boolean isBlend = false; - for(int i = 0, l = lst.size(); i < l; ++i) { - NotificationBadge badge = lst.get(i); - boolean isHiding = false; - if(badge.hideAtMillis != -1l) { - isHiding = true; - if(millis - badge.hideAtMillis > 500l) { - continue; - } - } - CachedNotifBadgeTexture tex = badge.getGLTexture(this, scaleFactor, showXButtons); - if(tex != null) { - GlStateManager.bindTexture(tex.glTexture); - float alphaTop = 1.0f; - float alphaBottom = 1.0f; - float timeRemainingSec; - long age = millis - badge.clientTimestamp; - if(isHiding) { - timeRemainingSec = (float)((double)(500l - (millis - badge.hideAtMillis)) * 0.001); - }else { - timeRemainingSec = (float)((double)((long)badge.hideAfterSec * 1000l - age) * 0.001); - } - timeRemainingSec = Math.min((float)(age * 0.001) + 0.001f, timeRemainingSec); - alphaTop *= MathHelper.clamp_float(timeRemainingSec * 3.0F, 0.0F, 1.0F); - alphaTop *= alphaTop; - alphaBottom *= MathHelper.clamp_float(timeRemainingSec * 2.0F, 0.0F, 1.0F); - alphaBottom *= alphaBottom; - if(alphaTop == 0.0F && alphaBottom == 0.0F) { - continue; - } - boolean blend = alphaTop < 1.0f || alphaBottom < 1.0f; - if(blend != isBlend) { - if(blend) { - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); - }else { - GlStateManager.disableBlend(); - } - isBlend = blend; - } - int px = width - tex.width; - drawTexturedGradientFBRect(px, baseOffset, tex.width, tex.height, - ((int) (alphaTop * 255.0f) << 24) | 0xFFFFFF, - ((int) (alphaBottom * 255.0f) << 24) | 0xFFFFFF, 200.0f); - if(showXButtons && tex.hasHoverEvents) { - if(mouseX >= px && mouseY >= baseOffset && mouseX < px + tex.width && mouseY < baseOffset + tex.height) { - List cursorEvents = tex.cursorEvents; - if(cursorEvents != null) { - for(int j = 0, m = cursorEvents.size(); j < m; ++j) { - ClickEventZone evt = cursorEvents.get(j); - if(evt.hasHoverEvent) { - int offsetPosX = px + evt.posX; - int offsetPosY = baseOffset + evt.posY; - if(mouseX >= offsetPosX && mouseY >= offsetPosY && mouseX < offsetPosX + evt.width - && mouseY < offsetPosY + evt.height) { - if(isBlend) { - GlStateManager.disableBlend(); - isBlend = false; - } - mc.currentScreen.handleComponentHover(evt.chatComponent, mouseX, mouseY); - } - } - } - } - } - } - baseOffset += tex.height * alphaTop; - } - } - if(isBlend) { - GlStateManager.disableBlend(); - } - } - } - - protected CachedNotifBadgeTexture renderBadge(NotificationBadge badge, int scaleFactor, boolean showXButton) { - int badgeWidth = BADGE_WIDTH; - int badgeHeight = 10; - - int leftPadding = 6; - int rightPadding = 26; - - int mainIconSW = 32; - if(badge.mainIcon != null) { - int iw = badge.mainIcon.texture.getWidth(); - int ih = badge.mainIcon.texture.getHeight(); - float iaspect = (float)iw / (float)ih; - mainIconSW = (int)(32 * iaspect); - leftPadding += Math.min(mainIconSW, 64) + 3; - } - - int textZoneWidth = badgeWidth - leftPadding - rightPadding; - int bodyYOffset = 5; - - String titleText = null; - IChatComponent titleComponent = badge.getTitleProfanityFilter(); - if(titleComponent != null) { - titleText = titleComponent.getFormattedText(); - if(titleText.length() > 0) { - badgeHeight += 12; - bodyYOffset += 12; - }else { - titleText = null; - } - } - - if(badge.titleIcon != null && titleText == null) { - badgeHeight += 12; - bodyYOffset += 12; - } - - float bodyFontSize = 0.75f; - List bodyLines = null; - List clickEvents = null; - IChatComponent rootClickEvt = null; - boolean hasClickEvents = false; - boolean hasHoverEvents = false; - - int bodyHeight = 0; - - IChatComponent bodyComponent = badge.getBodyProfanityFilter(); - if(bodyComponent != null) { - if (bodyComponent.getChatStyle().getChatClickEvent() != null - && bodyComponent.getChatStyle().getChatClickEvent().getAction().shouldAllowInChat()) { - rootClickEvt = bodyComponent; - } - bodyLines = GuiUtilRenderComponents.func_178908_a(bodyComponent, (int) (textZoneWidth / bodyFontSize), - mc.fontRendererObj, true, true); - - int maxHeight = BADGE_HEIGHT - 32; - int maxLines = MathHelper.floor_float(maxHeight / (9 * bodyFontSize)); - if(bodyLines.size() > maxLines) { - bodyLines = bodyLines.subList(0, maxLines); - bodyComponent = bodyLines.get(maxLines - 1); - List siblings = bodyComponent.getSiblings(); - IChatComponent dots = new ChatComponentText("..."); - if(siblings != null && siblings.size() > 0) { - dots.setChatStyle(siblings.get(siblings.size() - 1).getChatStyle()); - } - bodyComponent.appendSibling(dots); - } - bodyHeight = MathHelper.floor_float(bodyLines.size() * (9 * bodyFontSize)); - } - - String sourceText = null; - IChatComponent sourceComponent = badge.getSourceProfanityFilter(); - if(sourceComponent != null) { - sourceText = sourceComponent.getFormattedText(); - if(sourceText.length() == 0) { - sourceText = null; - } - } - - if(badge.mainIcon != null) { - bodyHeight = Math.max(sourceText != null ? 30 : 32, bodyHeight); - } - - if(sourceText != null) { - badgeHeight += 6; - } - - badgeHeight += bodyHeight; - - badgeHeight = Math.max(badgeHeight, showXButton ? 42 : 26); - - if(badgeHeight > BADGE_HEIGHT) { - logger.info("Warning: Badge {} was {} pixels too high!", badge.badgeUUID, BADGE_HEIGHT - badgeHeight); - badgeHeight = BADGE_HEIGHT; - } - - int glTex = GlStateManager.generateTexture(); - GlStateManager.bindTexture(glTex); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, badgeWidth * scaleFactor, badgeHeight * scaleFactor, 0, GL_RGBA, - GL_UNSIGNED_BYTE, (ByteBuffer) null); - _wglBindFramebuffer(_GL_FRAMEBUFFER, rendererFramebuffer); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(glTex), 0); - _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); - - int[] oldViewport = new int[4]; - EaglercraftGPU.glGetInteger(GL_VIEWPORT, oldViewport); - - GlStateManager.viewport(0, 0, badgeWidth * scaleFactor, badgeHeight * scaleFactor); - - GlStateManager.disableDepth(); - GlStateManager.depthMask(false); - GlStateManager.enableTexture2D(); - GlStateManager.disableLighting(); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.pushMatrix(); - GlStateManager.loadIdentity(); - GlStateManager.ortho(0.0D, badgeWidth, badgeHeight, 0.0D, 1000.0D, 3000.0D); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.pushMatrix(); - GlStateManager.loadIdentity(); - GlStateManager.translate(0.0F, 0.0F, -2000.0F); - - Tessellator tess = Tessellator.getInstance(); - WorldRenderer worldRenderer = tess.getWorldRenderer(); - - worldRenderer.begin(GL_QUADS, VertexFormat.POSITION_TEX_COLOR); - - mc.getTextureManager().bindTexture(eaglerGui); - - drawTexturedColoredRect(worldRenderer, 0, 0, 96, 192, 160, 8, (badge.backgroundColor >>> 16) & 0xFF, - (badge.backgroundColor >>> 8) & 0xFF, badge.backgroundColor & 0xFF, 0xFF); - - drawTexturedColoredRect(worldRenderer, 0, 8, 96, 192 + (BADGE_HEIGHT - badgeHeight + 8), 160, (badgeHeight - 8), - (badge.backgroundColor >>> 16) & 0xFF, (badge.backgroundColor >>> 8) & 0xFF, - badge.backgroundColor & 0xFF, 0xFF); - - switch(badge.priority) { - case LOW: - default: - drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 192, 176, 16, 16, (badge.backgroundColor >>> 16) & 0xFF, - (badge.backgroundColor >>> 8) & 0xFF, badge.backgroundColor & 0xFF, 0xFF); - break; - case NORMAL: - drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 208, 176, 16, 16, 0xFF, 0xFF, 0xFF, 0xFF); - break; - case HIGHER: - drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 224, 176, 16, 16, 0xFF, 0xFF, 0xFF, 0xFF); - break; - case HIGHEST: - drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 240, 176, 16, 16, 0xFF, 0xFF, 0xFF, 0xFF); - break; - } - - if(showXButton) { - drawTexturedColoredRect(worldRenderer, badgeWidth - 21, 5, 80, 208, 16, 16, 0xFF, 0xFF, 0xFF, 0xFF); - } - - tess.draw(); - - if(badge.mainIcon != null) { - mc.getTextureManager().bindTexture(badge.mainIcon.resource); - drawTexturedRect(6, bodyYOffset, mainIconSW, 32); - } - - if(badge.titleIcon != null) { - mc.getTextureManager().bindTexture(badge.titleIcon.resource); - drawTexturedRect(6, 5, 8, 8); - } - - if(titleText != null) { - GlStateManager.pushMatrix(); - GlStateManager.translate(6 + (badge.titleIcon != null ? 10 : 0), 6, 0.0f); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - mc.fontRendererObj.drawStringWithShadow(titleText, 0, 0, badge.titleTxtColor); - GlStateManager.popMatrix(); - } - - if(bodyLines != null && !bodyLines.isEmpty()) { - GlStateManager.pushMatrix(); - if(!showXButton && badge.mainIcon == null && titleText != null) { - bodyYOffset -= 2; - } - GlStateManager.translate(leftPadding, bodyYOffset, 0.0f); - int l = bodyLines.size(); - GlStateManager.scale(bodyFontSize, bodyFontSize, bodyFontSize); - for(int i = 0; i < l; ++i) { - int startXLocal = 0; - int startXReal = leftPadding; - for(IChatComponent comp : bodyLines.get(i)) { - int w = mc.fontRendererObj.drawStringWithShadow( - comp.getChatStyle().getFormattingCode() + comp.getUnformattedTextForChat(), startXLocal, - i * 9, badge.bodyTxtColor) - startXLocal; - ClickEvent clickEvent = comp.getChatStyle().getChatClickEvent(); - HoverEvent hoverEvent = comp.getChatStyle().getChatHoverEvent(); - if(clickEvent != null && !clickEvent.getAction().shouldAllowInChat()) { - clickEvent = null; - } - if(hoverEvent != null && !hoverEvent.getAction().shouldAllowInChat()) { - hoverEvent = null; - } - if(clickEvent != null || hoverEvent != null) { - hasClickEvents |= clickEvent != null; - hasHoverEvents |= hoverEvent != null; - if(clickEvents == null) { - clickEvents = new ArrayList<>(); - } - clickEvents.add(new ClickEventZone(startXReal + (int) (startXLocal * bodyFontSize), - bodyYOffset + (int) (i * 9 * bodyFontSize), (int) (w * bodyFontSize), - (int) (9 * bodyFontSize), comp, clickEvent != null, hoverEvent != null)); - } - startXLocal += w; - } - } - GlStateManager.popMatrix(); - } - - if(sourceText != null) { - GlStateManager.pushMatrix(); - GlStateManager.translate(badgeWidth - 21, badgeHeight - 5, 0.0f); - GlStateManager.scale(0.5f, 0.5f, 0.5f); - mc.fontRendererObj.drawStringWithShadow(sourceText, -mc.fontRendererObj.getStringWidth(sourceText) - 4, -10, badge.sourceTxtColor); - GlStateManager.popMatrix(); - } - - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.popMatrix(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.popMatrix(); - - GlStateManager.depthMask(true); - GlStateManager.enableDepth(); - - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - GlStateManager.viewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); - - return new CachedNotifBadgeTexture(glTex, scaleFactor, badgeWidth, badgeHeight, clickEvents, rootClickEvt, hasClickEvents, hasHoverEvents); - } - - static void drawTexturedColoredRect(WorldRenderer worldRenderer, float xCoord, float yCoord, int minU, - int minV, int width, int height, int r, int g, int b, int a) { + static void drawTexturedColoredRect(WorldRenderer worldRenderer, float xCoord, float yCoord, int minU, int minV, + int width, int height, int r, int g, int b, int a) { float f = 0.00390625F; float f1 = 0.00390625F; worldRenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) height), 0.0).color(r, g, b, a) @@ -495,7 +88,8 @@ public class ServerNotificationRenderer { .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + 0) * f1)).endVertex(); } - static void drawTexturedGradientFBRect(float xCoord, float yCoord, int width, int height, int rgbaTop, int rgbaBottom, float zIndex) { + static void drawTexturedGradientFBRect(float xCoord, float yCoord, int width, int height, int rgbaTop, + int rgbaBottom, float zIndex) { int topR = (rgbaTop >>> 16) & 0xFF; int topG = (rgbaTop >>> 8) & 0xFF; int topB = rgbaTop & 0xFF; @@ -523,17 +117,464 @@ public class ServerNotificationRenderer { WorldRenderer worldRenderer = tess.getWorldRenderer(); worldRenderer.begin(GL_QUADS, VertexFormat.POSITION_TEX); worldRenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) height), 0.0).tex(0.0, 1.0).endVertex(); - worldRenderer.pos((double) (xCoord + (float) width), (double) (yCoord + (float) height), 0.0).tex(1.0, 1.0).endVertex(); + worldRenderer.pos((double) (xCoord + (float) width), (double) (yCoord + (float) height), 0.0).tex(1.0, 1.0) + .endVertex(); worldRenderer.pos((double) (xCoord + (float) width), (double) (yCoord + 0.0F), 0.0).tex(1.0, 0.0).endVertex(); worldRenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + 0.0F), 0.0).tex(0.0, 0.0).endVertex(); tess.draw(); } + protected Minecraft mc; + + protected int width; + + protected int height; + + protected int scaleFactor; + + protected IFramebufferGL rendererFramebuffer; + + public ServerNotificationRenderer() { + + } + public void destroy() { - if(rendererFramebuffer != null) { + if (rendererFramebuffer != null) { _wglDeleteFramebuffer(rendererFramebuffer); rendererFramebuffer = null; } } + public boolean handleClicked(GuiScreen currentScreen, int posX, int posY) { + if (mc.thePlayer == null) + return false; + ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); + List lst = mgr.getNotifBadgesToDisplay(); + if (!lst.isEmpty()) { + int baseOffset = mc.guiAchievement.getHeight(); + boolean showX = (currentScreen instanceof GuiChat); + if (showX) { + baseOffset += 25; // exit button in chat screen; + } + long millis = EagRuntime.steadyTimeMillis(); + for (int i = 0, l = lst.size(); i < l; ++i) { + NotificationBadge badge = lst.get(i); + CachedNotifBadgeTexture tex = badge.currentCacheGLTexture; + if (tex != null) { + int baseX = width - tex.width; + float texHeight = tex.height; + float timeRemainingSec; + long age = millis - badge.clientTimestamp; + if (badge.hideAtMillis != -1l) { + timeRemainingSec = (float) ((double) (500l - (millis - badge.hideAtMillis)) * 0.001); + } else { + timeRemainingSec = (float) ((double) ((long) badge.hideAfterSec * 1000l - age) * 0.001); + } + timeRemainingSec = Math.min((float) (age * 0.001) + 0.001f, timeRemainingSec); + float f = MathHelper.clamp_float(timeRemainingSec * 3.0F, 0.0F, 1.0F); + f *= f; + texHeight *= f; + if (badge.hideAtMillis == -1l) { + if (posX >= baseX && posX < width && posY >= baseOffset && posY < baseOffset + texHeight) { + if (showX) { + int xposX = baseX + tex.width - 21; + int xposY = baseOffset + 5; + if (posX >= xposX && posY >= xposY && posX < xposX + 16 && posY < xposY + 16) { + badge.hideNotif(); + mc.getSoundHandler().playSound(PositionedSoundRecord + .create(new ResourceLocation("gui.button.press"), 1.0F)); + return true; + } + } + if (tex.rootClickEvent != null) { + if (currentScreen.handleComponentClick(tex.rootClickEvent)) { + mc.getSoundHandler().playSound(PositionedSoundRecord + .create(new ResourceLocation("gui.button.press"), 1.0F)); + return true; + } + } + List cursorEvents = tex.cursorEvents; + if (tex.hasClickEvents && cursorEvents != null) { + for (int j = 0, m = cursorEvents.size(); j < m; ++j) { + ClickEventZone evt = cursorEvents.get(j); + if (evt.hasClickEvent) { + int offsetPosX = baseX + evt.posX; + int offsetPosY = baseOffset + evt.posY; + if (posX >= offsetPosX && posY >= offsetPosY && posX < offsetPosX + evt.width + && posY < offsetPosY + evt.height) { + if (currentScreen.handleComponentClick(evt.chatComponent)) { + mc.getSoundHandler().playSound(PositionedSoundRecord + .create(new ResourceLocation("gui.button.press"), 1.0F)); + return true; + } + } + } + } + } + } + } + baseOffset += texHeight; + } + } + } + return false; + } + + public void init() { + destroy(); + rendererFramebuffer = _wglCreateFramebuffer(); + } + + protected CachedNotifBadgeTexture renderBadge(NotificationBadge badge, int scaleFactor, boolean showXButton) { + int badgeWidth = BADGE_WIDTH; + int badgeHeight = 10; + + int leftPadding = 6; + int rightPadding = 26; + + int mainIconSW = 32; + if (badge.mainIcon != null) { + int iw = badge.mainIcon.texture.getWidth(); + int ih = badge.mainIcon.texture.getHeight(); + float iaspect = (float) iw / (float) ih; + mainIconSW = (int) (32 * iaspect); + leftPadding += Math.min(mainIconSW, 64) + 3; + } + + int textZoneWidth = badgeWidth - leftPadding - rightPadding; + int bodyYOffset = 5; + + String titleText = null; + IChatComponent titleComponent = badge.getTitleProfanityFilter(); + if (titleComponent != null) { + titleText = titleComponent.getFormattedText(); + if (titleText.length() > 0) { + badgeHeight += 12; + bodyYOffset += 12; + } else { + titleText = null; + } + } + + if (badge.titleIcon != null && titleText == null) { + badgeHeight += 12; + bodyYOffset += 12; + } + + float bodyFontSize = 0.75f; + List bodyLines = null; + List clickEvents = null; + IChatComponent rootClickEvt = null; + boolean hasClickEvents = false; + boolean hasHoverEvents = false; + + int bodyHeight = 0; + + IChatComponent bodyComponent = badge.getBodyProfanityFilter(); + if (bodyComponent != null) { + if (bodyComponent.getChatStyle().getChatClickEvent() != null + && bodyComponent.getChatStyle().getChatClickEvent().getAction().shouldAllowInChat()) { + rootClickEvt = bodyComponent; + } + bodyLines = GuiUtilRenderComponents.func_178908_a(bodyComponent, (int) (textZoneWidth / bodyFontSize), + mc.fontRendererObj, true, true); + + int maxHeight = BADGE_HEIGHT - 32; + int maxLines = MathHelper.floor_float(maxHeight / (9 * bodyFontSize)); + if (bodyLines.size() > maxLines) { + bodyLines = bodyLines.subList(0, maxLines); + bodyComponent = bodyLines.get(maxLines - 1); + List siblings = bodyComponent.getSiblings(); + IChatComponent dots = new ChatComponentText("..."); + if (siblings != null && siblings.size() > 0) { + dots.setChatStyle(siblings.get(siblings.size() - 1).getChatStyle()); + } + bodyComponent.appendSibling(dots); + } + bodyHeight = MathHelper.floor_float(bodyLines.size() * (9 * bodyFontSize)); + } + + String sourceText = null; + IChatComponent sourceComponent = badge.getSourceProfanityFilter(); + if (sourceComponent != null) { + sourceText = sourceComponent.getFormattedText(); + if (sourceText.length() == 0) { + sourceText = null; + } + } + + if (badge.mainIcon != null) { + bodyHeight = Math.max(sourceText != null ? 30 : 32, bodyHeight); + } + + if (sourceText != null) { + badgeHeight += 6; + } + + badgeHeight += bodyHeight; + + badgeHeight = Math.max(badgeHeight, showXButton ? 42 : 26); + + if (badgeHeight > BADGE_HEIGHT) { + logger.info("Warning: Badge {} was {} pixels too high!", badge.badgeUUID, BADGE_HEIGHT - badgeHeight); + badgeHeight = BADGE_HEIGHT; + } + + int glTex = GlStateManager.generateTexture(); + GlStateManager.bindTexture(glTex); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, badgeWidth * scaleFactor, badgeHeight * scaleFactor, 0, + GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + _wglBindFramebuffer(_GL_FRAMEBUFFER, rendererFramebuffer); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(glTex), 0); + _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); + + int[] oldViewport = new int[4]; + EaglercraftGPU.glGetInteger(GL_VIEWPORT, oldViewport); + + GlStateManager.viewport(0, 0, badgeWidth * scaleFactor, badgeHeight * scaleFactor); + + GlStateManager.disableDepth(); + GlStateManager.depthMask(false); + GlStateManager.enableTexture2D(); + GlStateManager.disableLighting(); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); + GlStateManager.ortho(0.0D, badgeWidth, badgeHeight, 0.0D, 1000.0D, 3000.0D); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); + GlStateManager.translate(0.0F, 0.0F, -2000.0F); + + Tessellator tess = Tessellator.getInstance(); + WorldRenderer worldRenderer = tess.getWorldRenderer(); + + worldRenderer.begin(GL_QUADS, VertexFormat.POSITION_TEX_COLOR); + + mc.getTextureManager().bindTexture(eaglerGui); + + drawTexturedColoredRect(worldRenderer, 0, 0, 96, 192, 160, 8, (badge.backgroundColor >>> 16) & 0xFF, + (badge.backgroundColor >>> 8) & 0xFF, badge.backgroundColor & 0xFF, 0xFF); + + drawTexturedColoredRect(worldRenderer, 0, 8, 96, 192 + (BADGE_HEIGHT - badgeHeight + 8), 160, (badgeHeight - 8), + (badge.backgroundColor >>> 16) & 0xFF, (badge.backgroundColor >>> 8) & 0xFF, + badge.backgroundColor & 0xFF, 0xFF); + + switch (badge.priority) { + case LOW: + default: + drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 192, 176, 16, 16, + (badge.backgroundColor >>> 16) & 0xFF, (badge.backgroundColor >>> 8) & 0xFF, + badge.backgroundColor & 0xFF, 0xFF); + break; + case NORMAL: + drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 208, 176, 16, 16, 0xFF, 0xFF, + 0xFF, 0xFF); + break; + case HIGHER: + drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 224, 176, 16, 16, 0xFF, 0xFF, + 0xFF, 0xFF); + break; + case HIGHEST: + drawTexturedColoredRect(worldRenderer, badgeWidth - 21, badgeHeight - 21, 240, 176, 16, 16, 0xFF, 0xFF, + 0xFF, 0xFF); + break; + } + + if (showXButton) { + drawTexturedColoredRect(worldRenderer, badgeWidth - 21, 5, 80, 208, 16, 16, 0xFF, 0xFF, 0xFF, 0xFF); + } + + tess.draw(); + + if (badge.mainIcon != null) { + mc.getTextureManager().bindTexture(badge.mainIcon.resource); + drawTexturedRect(6, bodyYOffset, mainIconSW, 32); + } + + if (badge.titleIcon != null) { + mc.getTextureManager().bindTexture(badge.titleIcon.resource); + drawTexturedRect(6, 5, 8, 8); + } + + if (titleText != null) { + GlStateManager.pushMatrix(); + GlStateManager.translate(6 + (badge.titleIcon != null ? 10 : 0), 6, 0.0f); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + mc.fontRendererObj.drawStringWithShadow(titleText, 0, 0, badge.titleTxtColor); + GlStateManager.popMatrix(); + } + + if (bodyLines != null && !bodyLines.isEmpty()) { + GlStateManager.pushMatrix(); + if (!showXButton && badge.mainIcon == null && titleText != null) { + bodyYOffset -= 2; + } + GlStateManager.translate(leftPadding, bodyYOffset, 0.0f); + int l = bodyLines.size(); + GlStateManager.scale(bodyFontSize, bodyFontSize, bodyFontSize); + for (int i = 0; i < l; ++i) { + int startXLocal = 0; + int startXReal = leftPadding; + for (IChatComponent comp : bodyLines.get(i)) { + int w = mc.fontRendererObj.drawStringWithShadow( + comp.getChatStyle().getFormattingCode() + comp.getUnformattedTextForChat(), startXLocal, + i * 9, badge.bodyTxtColor) - startXLocal; + ClickEvent clickEvent = comp.getChatStyle().getChatClickEvent(); + HoverEvent hoverEvent = comp.getChatStyle().getChatHoverEvent(); + if (clickEvent != null && !clickEvent.getAction().shouldAllowInChat()) { + clickEvent = null; + } + if (hoverEvent != null && !hoverEvent.getAction().shouldAllowInChat()) { + hoverEvent = null; + } + if (clickEvent != null || hoverEvent != null) { + hasClickEvents |= clickEvent != null; + hasHoverEvents |= hoverEvent != null; + if (clickEvents == null) { + clickEvents = new ArrayList<>(); + } + clickEvents.add(new ClickEventZone(startXReal + (int) (startXLocal * bodyFontSize), + bodyYOffset + (int) (i * 9 * bodyFontSize), (int) (w * bodyFontSize), + (int) (9 * bodyFontSize), comp, clickEvent != null, hoverEvent != null)); + } + startXLocal += w; + } + } + GlStateManager.popMatrix(); + } + + if (sourceText != null) { + GlStateManager.pushMatrix(); + GlStateManager.translate(badgeWidth - 21, badgeHeight - 5, 0.0f); + GlStateManager.scale(0.5f, 0.5f, 0.5f); + mc.fontRendererObj.drawStringWithShadow(sourceText, -mc.fontRendererObj.getStringWidth(sourceText) - 4, -10, + badge.sourceTxtColor); + GlStateManager.popMatrix(); + } + + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.popMatrix(); + + GlStateManager.depthMask(true); + GlStateManager.enableDepth(); + + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + GlStateManager.viewport(oldViewport[0], oldViewport[1], oldViewport[2], oldViewport[3]); + + return new CachedNotifBadgeTexture(glTex, scaleFactor, badgeWidth, badgeHeight, clickEvents, rootClickEvt, + hasClickEvents, hasHoverEvents); + } + + public void renderOverlay(int mouseX, int mouseY) { + if (mc.thePlayer == null) + return; + ServerNotificationManager mgr = mc.thePlayer.sendQueue.getNotifManager(); + List lst = mgr.getNotifBadgesToDisplay(); + if (!lst.isEmpty()) { + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + boolean showXButtons = false; + int baseOffset = mc.guiAchievement.getHeight(); + if (mc.currentScreen != null) { + if (mc.currentScreen instanceof GuiChat) { + baseOffset += 25; // exit button in chat screen; + showXButtons = true; + } else if (mc.currentScreen instanceof GuiScreenNotifications) { + return; + } + } + long millis = EagRuntime.steadyTimeMillis(); + boolean isBlend = false; + for (int i = 0, l = lst.size(); i < l; ++i) { + NotificationBadge badge = lst.get(i); + boolean isHiding = false; + if (badge.hideAtMillis != -1l) { + isHiding = true; + if (millis - badge.hideAtMillis > 500l) { + continue; + } + } + CachedNotifBadgeTexture tex = badge.getGLTexture(this, scaleFactor, showXButtons); + if (tex != null) { + GlStateManager.bindTexture(tex.glTexture); + float alphaTop = 1.0f; + float alphaBottom = 1.0f; + float timeRemainingSec; + long age = millis - badge.clientTimestamp; + if (isHiding) { + timeRemainingSec = (float) ((double) (500l - (millis - badge.hideAtMillis)) * 0.001); + } else { + timeRemainingSec = (float) ((double) ((long) badge.hideAfterSec * 1000l - age) * 0.001); + } + timeRemainingSec = Math.min((float) (age * 0.001) + 0.001f, timeRemainingSec); + alphaTop *= MathHelper.clamp_float(timeRemainingSec * 3.0F, 0.0F, 1.0F); + alphaTop *= alphaTop; + alphaBottom *= MathHelper.clamp_float(timeRemainingSec * 2.0F, 0.0F, 1.0F); + alphaBottom *= alphaBottom; + if (alphaTop == 0.0F && alphaBottom == 0.0F) { + continue; + } + boolean blend = alphaTop < 1.0f || alphaBottom < 1.0f; + if (blend != isBlend) { + if (blend) { + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0); + } else { + GlStateManager.disableBlend(); + } + isBlend = blend; + } + int px = width - tex.width; + drawTexturedGradientFBRect(px, baseOffset, tex.width, tex.height, + ((int) (alphaTop * 255.0f) << 24) | 0xFFFFFF, + ((int) (alphaBottom * 255.0f) << 24) | 0xFFFFFF, 200.0f); + if (showXButtons && tex.hasHoverEvents) { + if (mouseX >= px && mouseY >= baseOffset && mouseX < px + tex.width + && mouseY < baseOffset + tex.height) { + List cursorEvents = tex.cursorEvents; + if (cursorEvents != null) { + for (int j = 0, m = cursorEvents.size(); j < m; ++j) { + ClickEventZone evt = cursorEvents.get(j); + if (evt.hasHoverEvent) { + int offsetPosX = px + evt.posX; + int offsetPosY = baseOffset + evt.posY; + if (mouseX >= offsetPosX && mouseY >= offsetPosY + && mouseX < offsetPosX + evt.width + && mouseY < offsetPosY + evt.height) { + if (isBlend) { + GlStateManager.disableBlend(); + isBlend = false; + } + mc.currentScreen.handleComponentHover(evt.chatComponent, mouseX, mouseY); + } + } + } + } + } + } + baseOffset += tex.height * alphaTop; + } + } + if (isBlend) { + GlStateManager.disableBlend(); + } + } + } + + public void setResolution(Minecraft mc, int w, int h, int scaleFactor) { + this.mc = mc; + this.width = w; + this.height = h; + this.scaleFactor = scaleFactor; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DisplayList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DisplayList.java index c840319f..5c34dad7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DisplayList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DisplayList.java @@ -6,14 +6,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.IBufferGL; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,5 +28,5 @@ class DisplayList { int count = 0; boolean bindQuad16 = false; boolean bindQuad32 = false; - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DrawUtils.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DrawUtils.java index 58872a1e..26f9d264 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DrawUtils.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/DrawUtils.java @@ -1,7 +1,20 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import java.util.List; @@ -14,14 +27,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,17 +52,45 @@ public class DrawUtils { public static IShaderGL vshLocal = null; public static List vshLocalLayout = null; + public static void destroy() { + if (standardQuad2DVAO != null) { + EaglercraftGPU.destroyGLBufferArray(standardQuad2DVAO); + standardQuad2DVAO = null; + } + if (standardQuad3DVAO != null) { + EaglercraftGPU.destroyGLBufferArray(standardQuad3DVAO); + standardQuad3DVAO = null; + } + if (standardQuadVBO != null) { + _wglDeleteBuffers(standardQuadVBO); + standardQuadVBO = null; + } + if (vshLocal != null) { + vshLocal.free(); + vshLocal = null; + vshLocalLayout = null; + } + } + + public static void drawStandardQuad2D() { + EaglercraftGPU.bindGLBufferArray(standardQuad2DVAO); + EaglercraftGPU.doDrawArrays(GL_TRIANGLES, 0, 6); + } + + public static void drawStandardQuad3D() { + EaglercraftGPU.bindGLBufferArray(standardQuad3DVAO); + EaglercraftGPU.doDrawArrays(GL_TRIANGLES, 0, 6); + } + static void init() { - if(standardQuad2DVAO == null) { + if (standardQuad2DVAO == null) { standardQuad2DVAO = EaglercraftGPU.createGLBufferArray(); standardQuad3DVAO = EaglercraftGPU.createGLBufferArray(); standardQuadVBO = _wglGenBuffers(); FloatBuffer verts = EagRuntime.allocateFloatBuffer(18); - verts.put(new float[] { - -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f - }); + verts.put(new float[] { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, + 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }); verts.flip(); EaglercraftGPU.bindVAOGLArrayBufferNow(standardQuadVBO); @@ -66,7 +108,7 @@ public class DrawUtils { EaglercraftGPU.vertexAttribPointer(0, 3, GL_FLOAT, false, 12, 0); } - if(vshLocal == null) { + if (vshLocal == null) { String vertexSource = EagRuntime.getRequiredResourceString(vertexShaderPath); vshLocalLayout = VSHInputLayoutParser.getShaderInputs(vertexSource); @@ -75,13 +117,13 @@ public class DrawUtils { _wglShaderSource(vshLocal, GLSLHeader.getVertexHeaderCompat(vertexSource, vertexShaderPrecision)); _wglCompileShader(vshLocal); - - if(_wglGetShaderi(vshLocal, GL_COMPILE_STATUS) != GL_TRUE) { + + if (_wglGetShaderi(vshLocal, GL_COMPILE_STATUS) != GL_TRUE) { EaglercraftGPU.logger.error("Failed to compile GL_VERTEX_SHADER \"" + vertexShaderPath + "\"!"); String log = _wglGetShaderInfoLog(vshLocal); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { EaglercraftGPU.logger.error("[VERT] {}", lines[i]); } } @@ -90,34 +132,4 @@ public class DrawUtils { } } - public static void drawStandardQuad2D() { - EaglercraftGPU.bindGLBufferArray(standardQuad2DVAO); - EaglercraftGPU.doDrawArrays(GL_TRIANGLES, 0, 6); - } - - public static void drawStandardQuad3D() { - EaglercraftGPU.bindGLBufferArray(standardQuad3DVAO); - EaglercraftGPU.doDrawArrays(GL_TRIANGLES, 0, 6); - } - - public static void destroy() { - if(standardQuad2DVAO != null) { - EaglercraftGPU.destroyGLBufferArray(standardQuad2DVAO); - standardQuad2DVAO = null; - } - if(standardQuad3DVAO != null) { - EaglercraftGPU.destroyGLBufferArray(standardQuad3DVAO); - standardQuad3DVAO = null; - } - if(standardQuadVBO != null) { - _wglDeleteBuffers(standardQuadVBO); - standardQuadVBO = null; - } - if(vshLocal != null) { - vshLocal.free(); - vshLocal = null; - vshLocalLayout = null; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglerMeshLoader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglerMeshLoader.java index cb1c7b60..746d1588 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglerMeshLoader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglerMeshLoader.java @@ -1,5 +1,14 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ELEMENT_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; + import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; @@ -17,20 +26,18 @@ import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,11 +49,11 @@ public class EaglerMeshLoader implements IResourceManagerReloadListener { private static final Map meshCache = new HashMap<>(); public static HighPolyMesh getEaglerMesh(ResourceLocation meshLoc) { - if(meshLoc.cachedPointerType == ResourceLocation.CACHED_POINTER_EAGLER_MESH) { - return (HighPolyMesh)meshLoc.cachedPointer; + if (meshLoc.cachedPointerType == ResourceLocation.CACHED_POINTER_EAGLER_MESH) { + return (HighPolyMesh) meshLoc.cachedPointer; } HighPolyMesh theMesh = meshCache.get(meshLoc); - if(theMesh == null) { + if (theMesh == null) { theMesh = new HighPolyMesh(); reloadMesh(meshLoc, theMesh, Minecraft.getMinecraft().getResourceManager()); } @@ -55,34 +62,35 @@ public class EaglerMeshLoader implements IResourceManagerReloadListener { return theMesh; } - private static void reloadMesh(ResourceLocation meshLoc, HighPolyMesh meshStruct, IResourceManager resourceManager) { + private static void reloadMesh(ResourceLocation meshLoc, HighPolyMesh meshStruct, + IResourceManager resourceManager) { IntBuffer up1 = null; try { int intsOfVertex, intsOfIndex, intsTotal, stride; - try(DataInputStream dis = new DataInputStream(resourceManager.getResource(meshLoc).getInputStream())) { + try (DataInputStream dis = new DataInputStream(resourceManager.getResource(meshLoc).getInputStream())) { byte[] header = new byte[8]; dis.read(header); - if(!Arrays.equals(header, new byte[] { (byte) 33, (byte) 69, (byte) 65, (byte) 71, (byte) 36, + if (!Arrays.equals(header, new byte[] { (byte) 33, (byte) 69, (byte) 65, (byte) 71, (byte) 36, (byte) 109, (byte) 100, (byte) 108 })) { throw new IOException("File is not an eaglercraft high-poly mesh!"); } - - char CT = (char)dis.read(); - - if(CT == 'C') { + + char CT = (char) dis.read(); + + if (CT == 'C') { meshStruct.hasTexture = false; - }else if(CT == 'T') { + } else if (CT == 'T') { meshStruct.hasTexture = true; - }else { + } else { throw new IOException("Unsupported mesh type '" + CT + "'!"); } - + dis.skipBytes(dis.readUnsignedShort()); meshStruct.vertexCount = dis.readInt(); meshStruct.indexCount = dis.readInt(); int byteIndexCount = meshStruct.indexCount; - if(byteIndexCount % 2 != 0) { // must round up to int + if (byteIndexCount % 2 != 0) { // must round up to int byteIndexCount += 1; } stride = meshStruct.hasTexture ? 24 : 16; @@ -91,72 +99,73 @@ public class EaglerMeshLoader implements IResourceManagerReloadListener { intsOfIndex = byteIndexCount / 2; intsTotal = intsOfIndex + intsOfVertex; up1 = EagRuntime.allocateIntBuffer(intsTotal); - - for(int i = 0; i < intsTotal; ++i) { + + for (int i = 0; i < intsTotal; ++i) { int ch1 = dis.read(); int ch2 = dis.read(); int ch3 = dis.read(); int ch4 = dis.read(); - if ((ch1 | ch2 | ch3 | ch4) < 0) throw new EOFException(); // rip + if ((ch1 | ch2 | ch3 | ch4) < 0) + throw new EOFException(); // rip up1.put((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0)); } } - if(meshStruct.vertexArray == null) { + if (meshStruct.vertexArray == null) { meshStruct.vertexArray = EaglercraftGPU.createGLBufferArray(); } - if(meshStruct.vertexBuffer == null) { + if (meshStruct.vertexBuffer == null) { meshStruct.vertexBuffer = _wglGenBuffers(); } - if(meshStruct.indexBuffer == null) { + if (meshStruct.indexBuffer == null) { meshStruct.indexBuffer = _wglGenBuffers(); } - + up1.position(0).limit(intsOfVertex); - + EaglercraftGPU.bindVAOGLArrayBufferNow(meshStruct.vertexBuffer); _wglBufferData(GL_ARRAY_BUFFER, up1, GL_STATIC_DRAW); - + EaglercraftGPU.bindGLBufferArray(meshStruct.vertexArray); - + up1.position(intsOfVertex).limit(intsTotal); - + EaglercraftGPU.bindVAOGLElementArrayBufferNow(meshStruct.indexBuffer); _wglBufferData(GL_ELEMENT_ARRAY_BUFFER, up1, GL_STATIC_DRAW); - + EaglercraftGPU.enableVertexAttribArray(0); EaglercraftGPU.vertexAttribPointer(0, 3, GL_FLOAT, false, stride, 0); - - if(meshStruct.hasTexture) { + + if (meshStruct.hasTexture) { EaglercraftGPU.enableVertexAttribArray(1); EaglercraftGPU.vertexAttribPointer(1, 2, GL_FLOAT, false, stride, 16); } - + EaglercraftGPU.enableVertexAttribArray(meshStruct.hasTexture ? 2 : 1); EaglercraftGPU.vertexAttribPointer(meshStruct.hasTexture ? 2 : 1, 4, GL_BYTE, true, stride, 12); - }catch(Throwable ex) { - if(meshStruct.vertexArray != null) { + } catch (Throwable ex) { + if (meshStruct.vertexArray != null) { EaglercraftGPU.destroyGLBufferArray(meshStruct.vertexArray); meshStruct.vertexArray = null; } - if(meshStruct.vertexBuffer != null) { + if (meshStruct.vertexBuffer != null) { _wglDeleteBuffers(meshStruct.vertexBuffer); meshStruct.vertexBuffer = null; } - if(meshStruct.indexBuffer != null) { + if (meshStruct.indexBuffer != null) { _wglDeleteBuffers(meshStruct.indexBuffer); meshStruct.indexBuffer = null; } - + meshStruct.vertexCount = 0; meshStruct.indexCount = 0; meshStruct.hasTexture = false; - + logger.error("Failed to load eaglercraft high-poly mesh: \"{}\"", meshLoc); logger.error(ex); - }finally { - if(up1 != null) { + } finally { + if (up1 != null) { EagRuntime.freeIntBuffer(up1); } } @@ -164,7 +173,7 @@ public class EaglerMeshLoader implements IResourceManagerReloadListener { @Override public void onResourceManagerReload(IResourceManager var1) { - for(Entry meshEntry : meshCache.entrySet()) { + for (Entry meshEntry : meshCache.entrySet()) { reloadMesh(meshEntry.getKey(), meshEntry.getValue(), var1); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglercraftGPU.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglercraftGPU.java index 87ac654d..9c66ac89 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglercraftGPU.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EaglercraftGPU.java @@ -1,11 +1,62 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; -import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; -import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -import net.minecraft.util.MathHelper; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglActiveTexture; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindBuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindBufferRange; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindVertexArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBlendEquation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCopyTexSubImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteTextures; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDisableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawArraysInstanced; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawElements; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawElementsInstanced; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenTextures; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetError; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetInteger; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetString; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLineWidth; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglReadPixels; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglReadPixels_u16; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2Df32; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2Du16; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameterf; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexStorage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexSubImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUseProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribDivisor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CONTEXT_LOST_WEBGL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ELEMENT_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FOG_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_INVALID_ENUM; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_INVALID_OPERATION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_INVALID_VALUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LUMINANCE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_OUT_OF_MEMORY; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_QUADS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RED; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGB; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_INT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VIEWPORT; import java.util.HashMap; import java.util.Map; @@ -18,21 +69,25 @@ import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IQueryGL; import net.lax1dude.eaglercraft.v1_8.internal.ITextureGL; import net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL; - -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.minecraft.util.MathHelper; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,258 +103,661 @@ public class EaglercraftGPU { static boolean emulatedVAOs = false; static SoftGLBufferState emulatedVAOState = new SoftGLBufferState(); - public static final String gluErrorString(int i) { - switch(i) { - case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; - case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; - case 1286: return "GL_INVALID_FRAMEBUFFER_OPERATION"; - case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; - case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; - case GL_CONTEXT_LOST_WEBGL: return "CONTEXT_LOST_WEBGL"; - default: return "Unknown Error"; + private static DisplayList currentList = null; + + private static ByteBuffer displayListBuffer = EagRuntime.allocateByteBuffer(0x100000); + + private static final Map stringCache = new HashMap<>(); + + static IBufferArrayGL currentBufferArray = null; + + static IBufferGL currentArrayBuffer = null; + // only used when VAOs are emulated + static IBufferGL currentVAOArrayBuffer = null; + + static IBufferGL currentEmulatedVAOIndexBuffer = null; + + static IBufferGL currentUniformBuffer = null; + + static IProgramGL currentShaderProgram = null; + + private static final IBufferGL[] currentUniformBlockBindings = new IBufferGL[16]; + + private static final int[] currentUniformBlockBindingOffset = new int[16]; + + private static final int[] currentUniformBlockBindingSize = new int[16]; + + public static final int CLEAR_BINDING_TEXTURE = 1; + + public static final int CLEAR_BINDING_TEXTURE0 = 2; + + public static final int CLEAR_BINDING_ACTIVE_TEXTURE = 4; + + public static final int CLEAR_BINDING_BUFFER_ARRAY = 8; + + public static final int CLEAR_BINDING_ARRAY_BUFFER = 16; + + public static final int CLEAR_BINDING_SHADER_PROGRAM = 32; + + public static final int ATTRIB_TEXTURE = 1; + + public static final int ATTRIB_COLOR = 2; + + public static final int ATTRIB_NORMAL = 4; + + public static final int ATTRIB_LIGHTMAP = 8; + + private static FixedFunctionPipeline lastRender = null; + + private static int lastMode = 0; + + private static int lastCount = 0; + + private static IBufferGL quad16EmulationBuffer = null; + + private static int quad16EmulationBufferSize = 0; + + private static IBufferGL quad32EmulationBuffer = null; + + private static int quad32EmulationBufferSize = 0; + + static int glesVers = -1; + + static boolean hasFramebufferHDR16FSupport = false; + + static boolean hasFramebufferHDR32FSupport = false; + + static boolean hasLinearHDR16FSupport = false; + + static boolean hasLinearHDR32FSupport = false; + + static boolean fboRenderMipmapCapable = false; + + static boolean vertexArrayCapable = false; + + static boolean instancingCapable = false; + + static boolean texStorageCapable = false; + + static boolean textureLODCapable = false; + + static boolean shader5Capable = false; + + static boolean npotCapable = false; + + static int uniformBufferOffsetAlignment = -1; + + public static final boolean areVAOsEmulated() { + return emulatedVAOs; + } + + public static final void attachQuad16EmulationBuffer(int vertexCount, boolean bind) { + IBufferGL buf = quad16EmulationBuffer; + if (buf == null) { + quad16EmulationBuffer = buf = _wglGenBuffers(); + int newSize = quad16EmulationBufferSize = (vertexCount & 0xFFFFF000) + 0x2000; + if (newSize > 0xFFFF) { + newSize = 0xFFFF; + } + EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); + resizeQuad16EmulationBuffer(newSize >> 2); + } else { + int cnt = quad16EmulationBufferSize; + if (cnt < vertexCount) { + int newSize = quad16EmulationBufferSize = (vertexCount & 0xFFFFF000) + 0x2000; + if (newSize > 0xFFFF) { + newSize = 0xFFFF; + } + EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); + resizeQuad16EmulationBuffer(newSize >> 2); + } else if (bind) { + EaglercraftGPU.bindVAOGLElementArrayBuffer(buf); + } } } - public static final void glTexParameteri(int target, int param, int value) { - _wglTexParameteri(target, param, value); + public static final void attachQuad32EmulationBuffer(int vertexCount, boolean bind) { + IBufferGL buf = quad32EmulationBuffer; + if (buf == null) { + quad32EmulationBuffer = buf = _wglGenBuffers(); + int newSize = quad32EmulationBufferSize = (vertexCount & 0xFFFFC000) + 0x8000; + EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); + resizeQuad32EmulationBuffer(newSize >> 2); + } else { + int cnt = quad32EmulationBufferSize; + if (cnt < vertexCount) { + int newSize = quad32EmulationBufferSize = (vertexCount & 0xFFFFC000) + 0x8000; + EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); + resizeQuad32EmulationBuffer(newSize >> 2); + } else if (bind) { + EaglercraftGPU.bindVAOGLElementArrayBuffer(buf); + } + } } - public static final void glTexParameterf(int target, int param, float value) { - _wglTexParameterf(target, param, value); + static final void bindEmulatedVAOIndexBuffer(IBufferGL buffer) { + if (currentEmulatedVAOIndexBuffer != buffer) { + _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); + currentEmulatedVAOIndexBuffer = buffer; + } + } + + public static final void bindGLArrayBuffer(IBufferGL buffer) { + if (currentArrayBuffer != buffer) { + _wglBindBuffer(GL_ARRAY_BUFFER, buffer); + currentArrayBuffer = buffer; + } + } + + public static final void bindGLBufferArray(IBufferArrayGL buffer) { + if (emulatedVAOs) { + currentBufferArray = buffer; + } else { + if (currentBufferArray != buffer) { + _wglBindVertexArray(buffer); + currentBufferArray = buffer; + } + } + } + + public static final void bindGLShaderProgram(IProgramGL prog) { + if (currentShaderProgram != prog) { + _wglUseProgram(prog); + currentShaderProgram = prog; + } + } + + public static final void bindGLUniformBuffer(IBufferGL buffer) { + if (currentUniformBuffer != buffer) { + _wglBindBuffer(0x8A11, buffer); + currentUniformBuffer = buffer; + } + } + + public static final void bindUniformBufferRange(int index, IBufferGL buffer, int offset, int size) { + if (currentUniformBlockBindings[index] != buffer || currentUniformBlockBindingOffset[index] != offset + || currentUniformBlockBindingSize[index] != size) { + _wglBindBufferRange(0x8A11, index, buffer, offset, size); + currentUniformBlockBindings[index] = buffer; + currentUniformBlockBindingOffset[index] = offset; + currentUniformBlockBindingSize[index] = size; + } + } + + public static final void bindVAOGLArrayBuffer(IBufferGL buffer) { + if (emulatedVAOs) { + currentVAOArrayBuffer = buffer; + } else { + if (currentArrayBuffer != buffer) { + _wglBindBuffer(GL_ARRAY_BUFFER, buffer); + currentArrayBuffer = buffer; + } + } + } + + public static final void bindVAOGLArrayBufferNow(IBufferGL buffer) { + if (emulatedVAOs) { + currentVAOArrayBuffer = buffer; + } + if (currentArrayBuffer != buffer) { + _wglBindBuffer(GL_ARRAY_BUFFER, buffer); + currentArrayBuffer = buffer; + } + } + + public static final void bindVAOGLElementArrayBuffer(IBufferGL buffer) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping set element array buffer with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).setIndexBuffer(buffer); + } else { + _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); + } + } + + static final void bindVAOGLElementArrayBufferNow(IBufferGL buffer) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping set element array buffer with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).setIndexBuffer(buffer); + if (currentEmulatedVAOIndexBuffer != buffer) { + _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); + currentEmulatedVAOIndexBuffer = buffer; + } + } else { + _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); + } + } + + public static final boolean checkFBORenderMipmapCapable() { + return fboRenderMipmapCapable; + } + + public static final boolean checkHasHDRFramebufferSupport() { + return hasFramebufferHDR16FSupport || hasFramebufferHDR32FSupport; + } + + public static final boolean checkHasHDRFramebufferSupportWithFilter() { + return (hasFramebufferHDR16FSupport && hasLinearHDR16FSupport) + || (hasFramebufferHDR32FSupport && hasLinearHDR32FSupport); + } + + public static final boolean checkHDRFramebufferSupport(int bits) { + switch (bits) { + case 16: + return hasFramebufferHDR16FSupport; + case 32: + return hasFramebufferHDR32FSupport; + default: + return false; + } + } + + public static final boolean checkInstancingCapable() { + return instancingCapable; + } + + // legacy + public static final boolean checkLinearHDR32FSupport() { + return hasLinearHDR32FSupport; + } + + public static final boolean checkLinearHDRFilteringSupport(int bits) { + switch (bits) { + case 16: + return hasLinearHDR16FSupport; + case 32: + return hasLinearHDR32FSupport; + default: + return false; + } + } + + public static final boolean checkNPOTCapable() { + return npotCapable; + } + + public static final int checkOpenGLESVersion() { + return glesVers; + } + + public static final boolean checkShader5Capable() { + return shader5Capable; + } + + public static final boolean checkTexStorageCapable() { + return texStorageCapable; + } + + public static final boolean checkTextureLODCapable() { + return textureLODCapable; + } + + public static final boolean checkVAOCapable() { + return vertexArrayCapable; + } + + public static final void clearCurrentBinding(int mask) { + if ((mask & CLEAR_BINDING_TEXTURE) != 0) { + int[] i = GlStateManager.boundTexture; + for (int j = 0; j < i.length; ++j) { + i[j] = -1; + } + } + if ((mask & CLEAR_BINDING_TEXTURE0) != 0) { + GlStateManager.boundTexture[0] = -1; + } + if ((mask & CLEAR_BINDING_ACTIVE_TEXTURE) != 0) { + GlStateManager.activeTexture = 0; + _wglActiveTexture(GL_TEXTURE0); + } + if ((mask & CLEAR_BINDING_BUFFER_ARRAY) != 0) { + currentBufferArray = null; + } + if ((mask & CLEAR_BINDING_ARRAY_BUFFER) != 0) { + currentArrayBuffer = currentVAOArrayBuffer = null; + } + if ((mask & CLEAR_BINDING_SHADER_PROGRAM) != 0) { + currentShaderProgram = null; + } + } + + public static final void createFramebufferHDR16FTexture(int target, int level, int w, int h, int format, + boolean allow32bitFallback) { + createFramebufferHDR16FTexture(target, level, w, h, format, allow32bitFallback, null); + } + + private static final void createFramebufferHDR16FTexture(int target, int level, int w, int h, int format, + boolean allow32bitFallback, ByteBuffer pixelData) { + if (hasFramebufferHDR16FSupport) { + int internalFormat; + switch (format) { + case GL_RED: + if (glesVers == 200) { + format = GL_LUMINANCE; + internalFormat = GL_LUMINANCE; + } else { + internalFormat = glesVers == 200 ? GL_LUMINANCE : 0x822D; // GL_R16F + } + break; + case 0x8227: // GL_RG + internalFormat = glesVers == 200 ? 0x8227 : 0x822F; // GL_RG16F + case GL_RGB: + throw new UnsupportedOperationException( + "GL_RGB16F isn't supported specifically in WebGL 2.0 for some goddamn reason"); + case GL_RGBA: + internalFormat = glesVers == 200 ? GL_RGBA : 0x881A; // GL_RGBA16F + break; + default: + throw new UnsupportedOperationException("Unknown format: " + format); + } + _wglTexImage2Du16(target, level, internalFormat, w, h, 0, format, glesVers == 200 ? 0x8D61 : 0x140B, + pixelData); + } else { + if (allow32bitFallback) { + if (hasFramebufferHDR32FSupport) { + createFramebufferHDR32FTexture(target, level, w, h, format, false, null); + } else { + throw new UnsupportedOperationException( + "No fallback 32-bit HDR (floating point) texture support is available on this device"); + } + } else { + throw new UnsupportedOperationException( + "16-bit HDR (floating point) textures are not supported on this device"); + } + } + } + + public static final void createFramebufferHDR16FTexture(int target, int level, int w, int h, int format, + ByteBuffer pixelData) { + createFramebufferHDR16FTexture(target, level, w, h, format, false, pixelData); + } + + public static final void createFramebufferHDR32FTexture(int target, int level, int w, int h, int format, + boolean allow16bitFallback) { + createFramebufferHDR32FTexture(target, level, w, h, format, allow16bitFallback, null); + } + + private static final void createFramebufferHDR32FTexture(int target, int level, int w, int h, int format, + boolean allow16bitFallback, ByteBuffer pixelData) { + if (hasFramebufferHDR32FSupport) { + int internalFormat; + switch (format) { + case GL_RED: + internalFormat = 0x822E; // GL_R32F + break; + case 0x8227: // GL_RG + internalFormat = 0x8230; // GL_RG32F + case GL_RGB: + throw new UnsupportedOperationException( + "GL_RGB32F isn't supported specifically in WebGL 2.0 for some goddamn reason"); + case GL_RGBA: + internalFormat = 0x8814; // GL_RGBA32F + break; + default: + throw new UnsupportedOperationException("Unknown format: " + format); + } + _wglTexImage2Df32(target, level, internalFormat, w, h, 0, format, GL_FLOAT, pixelData); + } else { + if (allow16bitFallback) { + if (hasFramebufferHDR16FSupport) { + createFramebufferHDR16FTexture(target, level, w, h, format, false); + } else { + throw new UnsupportedOperationException( + "No fallback 16-bit HDR (floating point) texture support is available on this device"); + } + } else { + throw new UnsupportedOperationException( + "32-bit HDR (floating point) textures are not supported on this device"); + } + } + } + + public static final void createFramebufferHDR32FTexture(int target, int level, int w, int h, int format, + ByteBuffer pixelData) { + createFramebufferHDR32FTexture(target, level, w, h, format, false, pixelData); + } + + public static final IBufferArrayGL createGLBufferArray() { + if (emulatedVAOs) { + return new SoftGLBufferArray(); + } else { + return _wglGenVertexArrays(); + } + } + + public static final void destroyCache() { + GLSLHeader.destroy(); + DrawUtils.destroy(); + SpriteLevelMixer.destroy(); + InstancedFontRenderer.destroy(); + InstancedParticleRenderer.destroy(); + EffectPipelineFXAA.destroy(); + TextureCopyUtil.destroy(); + emulatedVAOs = false; + emulatedVAOState = null; + glesVers = -1; + fboRenderMipmapCapable = false; + vertexArrayCapable = false; + instancingCapable = false; + hasFramebufferHDR16FSupport = false; + hasFramebufferHDR32FSupport = false; + hasLinearHDR32FSupport = false; + stringCache.clear(); + mapTexturesGL.clear(); + mapQueriesGL.clear(); + mapDisplayListsGL.clear(); + } + + public static final void destroyGLBufferArray(IBufferArrayGL buffer) { + if (!emulatedVAOs) { + _wglDeleteVertexArrays(buffer); + } + } + + public static final void disableVertexAttribArray(int index) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping disable attrib with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).enableAttrib(index, false); + } else { + _wglDisableVertexAttribArray(index); + } + } + + public static final void doDrawArrays(int mode, int first, int count) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping draw call with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).transitionToState(emulatedVAOState, false); + } + _wglDrawArrays(mode, first, count); + } + + public static final void doDrawArraysInstanced(int mode, int first, int count, int instances) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping instanced draw call with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).transitionToState(emulatedVAOState, false); + } + _wglDrawArraysInstanced(mode, first, count, instances); + } + + public static final void doDrawElements(int mode, int count, int type, int offset) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping draw call with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).transitionToState(emulatedVAOState, true); + } + _wglDrawElements(mode, count, type, offset); + } + + public static final void doDrawElementsInstanced(int mode, int count, int type, int offset, int instances) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping instanced draw call with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).transitionToState(emulatedVAOState, true); + } + _wglDrawElementsInstanced(mode, count, type, offset, instances); + } + + public static final void drawHighPoly(HighPolyMesh mesh) { + if (mesh.vertexCount == 0 || mesh.indexCount == 0 || mesh.vertexArray == null) { + return; + } + FixedFunctionPipeline p = FixedFunctionPipeline.setupRenderDisplayList(mesh.getAttribBits()).update(); + EaglercraftGPU.bindGLBufferArray(mesh.vertexArray); + p.drawElements(GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_SHORT, 0); + } + + public static final void enableVertexAttribArray(int index) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping enable attrib with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).enableAttrib(index, true); + } else { + _wglEnableVertexAttribArray(index); + } + } + + public static final void flushDisplayList(int displayList) { + DisplayList dp = mapDisplayListsGL.get(displayList); + if (dp == null) { + throw new NullPointerException("Tried to flush a display list that does not exist: " + displayList); + } + dp.attribs = -1; + if (dp.vertexArray != null) { + EaglercraftGPU.destroyGLBufferArray(dp.vertexArray); + dp.vertexArray = null; + } + if (dp.vertexBuffer != null) { + _wglDeleteBuffers(dp.vertexBuffer); + dp.vertexBuffer = null; + } + } + + public static final ITextureGL getNativeTexture(int tex) { + return mapTexturesGL.get(tex); + } + + public static final int getUniformBufferOffsetAlignment() { + return uniformBufferOffsetAlignment; + } + + public static final void glBlendEquation(int equation) { + if (equation != GlStateManager.stateBlendEquation) { + _wglBlendEquation(equation); + GlStateManager.stateBlendEquation = equation; + } + } + + public static final void glCallList(int displayList) { + DisplayList dp = mapDisplayListsGL.get(displayList); + if (dp == null) { + throw new NullPointerException("Tried to call a display list that does not exist: " + displayList); + } + if (dp.attribs != -1) { + FixedFunctionPipeline p = FixedFunctionPipeline.setupRenderDisplayList(dp.attribs).update(); + bindGLBufferArray(dp.vertexArray); + if (dp.mode == GL_QUADS) { + int cnt = dp.count; + if (cnt > 0xFFFF) { + if (!dp.bindQuad32) { + dp.bindQuad16 = false; + dp.bindQuad32 = true; + attachQuad32EmulationBuffer(cnt, true); + } else { + attachQuad32EmulationBuffer(cnt, false); + } + p.drawElements(GL_TRIANGLES, cnt + (cnt >> 1), GL_UNSIGNED_INT, 0); + } else { + if (!dp.bindQuad16) { + dp.bindQuad16 = true; + dp.bindQuad32 = false; + attachQuad16EmulationBuffer(cnt, true); + } else { + attachQuad16EmulationBuffer(cnt, false); + } + p.drawElements(GL_TRIANGLES, cnt + (cnt >> 1), GL_UNSIGNED_SHORT, 0); + } + } else { + p.drawArrays(dp.mode, 0, dp.count); + } + } } public static final void glCopyTexSubImage2D(int target, int level, int sx, int sy, int dx, int dy, int w, int h) { _wglCopyTexSubImage2D(target, level, sx, sy, dx, dy, w, h); } - - private static DisplayList currentList = null; - private static ByteBuffer displayListBuffer = EagRuntime.allocateByteBuffer(0x100000); - public static final void glNewList(int target, int op) { - if(currentList != null) { - throw new IllegalStateException("A display list is already being compiled you eagler!"); - } - if(op != GL_COMPILE) { - throw new UnsupportedOperationException("Only GL_COMPILE is supported by glNewList"); - } - DisplayList dp = currentList = mapDisplayListsGL.get(target); - if(dp == null) { - throw new IllegalArgumentException("Unknown display list: " + target); - } - if(dp.vertexArray != null && dp.attribs > 0) { - EaglercraftGPU.bindGLBufferArray(dp.vertexArray); - int c = 0; - if((dp.attribs & ATTRIB_TEXTURE) == ATTRIB_TEXTURE) { - EaglercraftGPU.disableVertexAttribArray(++c); + public static final void glDeleteLists(int id) { + DisplayList d = mapDisplayListsGL.free(id); + if (d != null) { + if (d.vertexArray != null) { + EaglercraftGPU.destroyGLBufferArray(d.vertexArray); } - if((dp.attribs & ATTRIB_COLOR) == ATTRIB_COLOR) { - EaglercraftGPU.disableVertexAttribArray(++c); + if (d.vertexBuffer != null) { + _wglDeleteBuffers(d.vertexBuffer); } - if((dp.attribs & ATTRIB_NORMAL) == ATTRIB_NORMAL) { - EaglercraftGPU.disableVertexAttribArray(++c); - } - if((dp.attribs & ATTRIB_LIGHTMAP) == ATTRIB_LIGHTMAP) { - EaglercraftGPU.disableVertexAttribArray(++c); - } - } - dp.attribs = -1; - dp.mode = -1; - dp.count = 0; - } - - private static final void growDisplayListBuffer(int len) { - int wantSize = displayListBuffer.position() + len; - if(displayListBuffer.capacity() < wantSize) { - int newSize = (wantSize & 0xFFFE0000) + 0x40000; - ByteBuffer newBuffer = EagRuntime.allocateByteBuffer(newSize); - newBuffer.put((ByteBuffer)displayListBuffer.flip()); - EagRuntime.freeByteBuffer(displayListBuffer); - displayListBuffer = newBuffer; } } public static final void glEndList() { DisplayList dp = currentList; - if(dp == null) { + if (dp == null) { throw new IllegalStateException("No list is currently being compiled!"); } - - if(dp.attribs == -1) { - if(dp.vertexArray != null) { + + if (dp.attribs == -1) { + if (dp.vertexArray != null) { EaglercraftGPU.destroyGLBufferArray(dp.vertexArray); dp.vertexArray = null; } - if(dp.vertexBuffer != null) { + if (dp.vertexBuffer != null) { _wglDeleteBuffers(dp.vertexBuffer); dp.vertexBuffer = null; } currentList = null; return; } - - if(dp.vertexArray == null) { + + if (dp.vertexArray == null) { dp.vertexArray = createGLBufferArray(); dp.bindQuad16 = false; dp.bindQuad32 = false; } - if(dp.vertexBuffer == null) { + if (dp.vertexBuffer == null) { dp.vertexBuffer = _wglGenBuffers(); } - + bindVAOGLArrayBufferNow(dp.vertexBuffer); displayListBuffer.flip(); _wglBufferData(GL_ARRAY_BUFFER, displayListBuffer, GL_STATIC_DRAW); displayListBuffer.clear(); - + FixedFunctionPipeline.setupDisplayList(dp); currentList = null; } - public static final void glCallList(int displayList) { - DisplayList dp = mapDisplayListsGL.get(displayList); - if(dp == null) { - throw new NullPointerException("Tried to call a display list that does not exist: " + displayList); - } - if(dp.attribs != -1) { - FixedFunctionPipeline p = FixedFunctionPipeline.setupRenderDisplayList(dp.attribs).update(); - bindGLBufferArray(dp.vertexArray); - if(dp.mode == GL_QUADS) { - int cnt = dp.count; - if(cnt > 0xFFFF) { - if(!dp.bindQuad32) { - dp.bindQuad16 = false; - dp.bindQuad32 = true; - attachQuad32EmulationBuffer(cnt, true); - }else { - attachQuad32EmulationBuffer(cnt, false); - } - p.drawElements(GL_TRIANGLES, cnt + (cnt >> 1), GL_UNSIGNED_INT, 0); - }else { - if(!dp.bindQuad16) { - dp.bindQuad16 = true; - dp.bindQuad32 = false; - attachQuad16EmulationBuffer(cnt, true); - }else { - attachQuad16EmulationBuffer(cnt, false); - } - p.drawElements(GL_TRIANGLES, cnt + (cnt >> 1), GL_UNSIGNED_SHORT, 0); - } - }else { - p.drawArrays(dp.mode, 0, dp.count); - } - } - } - - public static final void flushDisplayList(int displayList) { - DisplayList dp = mapDisplayListsGL.get(displayList); - if(dp == null) { - throw new NullPointerException("Tried to flush a display list that does not exist: " + displayList); - } - dp.attribs = -1; - if(dp.vertexArray != null) { - EaglercraftGPU.destroyGLBufferArray(dp.vertexArray); - dp.vertexArray = null; - } - if(dp.vertexBuffer != null) { - _wglDeleteBuffers(dp.vertexBuffer); - dp.vertexBuffer = null; - } - } - - public static final void glNormal3f(float x, float y, float z) { - GlStateManager.stateNormalX = x; - GlStateManager.stateNormalY = y; - GlStateManager.stateNormalZ = z; - ++GlStateManager.stateNormalSerial; - } - - private static final Map stringCache = new HashMap<>(); - - public static final String glGetString(int param) { - String str = stringCache.get(param); - if(str == null) { - str = _wglGetString(param); - stringCache.put(param, str); - } - return str; - } - - public static final void glGetInteger(int param, int[] values) { - switch(param) { - case GL_VIEWPORT: - values[0] = GlStateManager.viewportX; - values[1] = GlStateManager.viewportY; - values[2] = GlStateManager.viewportW; - values[3] = GlStateManager.viewportH; - break; - default: - throw new UnsupportedOperationException("glGetInteger only accepts GL_VIEWPORT as a parameter"); - } - } - - public static final int glGetInteger(int param) { - return _wglGetInteger(param); - } - - public static final void glTexImage2D(int target, int level, int internalFormat, int w, int h, int unused, - int format, int type, ByteBuffer pixels) { - if(glesVers >= 300) { - _wglTexImage2D(target, level, internalFormat, w, h, unused, format, type, pixels); - }else { - int tv = TextureFormatHelper.trivializeInternalFormatToGLES20(internalFormat); - _wglTexImage2D(target, level, tv, w, h, unused, tv, type, pixels); - } - } - - public static final void glTexImage2D(int target, int level, int internalFormat, int w, int h, int unused, - int format, int type, IntBuffer pixels) { - if(glesVers >= 300) { - _wglTexImage2D(target, level, internalFormat, w, h, unused, format, type, pixels); - }else { - int tv = TextureFormatHelper.trivializeInternalFormatToGLES20(internalFormat); - _wglTexImage2D(target, level, tv, w, h, unused, tv, type, pixels); - } - } - - public static final void glTexSubImage2D(int target, int level, int x, int y, int w, int h, int format, - int type, IntBuffer pixels) { - _wglTexSubImage2D(target, level, x, y, w, h, format, type, pixels); - } - - public static final void glTexStorage2D(int target, int levels, int internalFormat, int w, int h) { - if(texStorageCapable && (glesVers >= 300 || levels == 1 || (MathHelper.calculateLogBaseTwo(Math.max(w, h)) + 1) == levels)) { - _wglTexStorage2D(target, levels, internalFormat, w, h); - }else { - int tv = TextureFormatHelper.trivializeInternalFormatToGLES20(internalFormat); - int type = TextureFormatHelper.getTypeFromInternal(internalFormat); - for(int i = 0; i < levels; ++i) { - _wglTexImage2D(target, i, tv, Math.max(w >> i, 1), Math.max(h >> i, 1), 0, tv, type, (ByteBuffer)null); - } - } - } - - public static final void glReadPixels(int x, int y, int width, int height, int format, int type, ByteBuffer buffer) { - switch(type) { - case GL_FLOAT: - _wglReadPixels(x, y, width, height, format, GL_FLOAT, buffer.asFloatBuffer()); - break; - case 0x140B: // GL_HALF_FLOAT - _wglReadPixels_u16(x, y, width, height, format, glesVers == 200 ? 0x8D61 : 0x140B, buffer); - break; - case GL_UNSIGNED_BYTE: - default: - _wglReadPixels(x, y, width, height, format, type, buffer); - break; - } - } - - public static final void glLineWidth(float f) { - _wglLineWidth(f); - } - public static final void glFog(int param, FloatBuffer valueBuffer) { int pos = valueBuffer.position(); - switch(param) { + switch (param) { case GL_FOG_COLOR: GlStateManager.stateFogColorR = valueBuffer.get(); GlStateManager.stateFogColorG = valueBuffer.get(); @@ -321,318 +779,168 @@ public class EaglercraftGPU { return mapDisplayListsGL.register(new DisplayList()); } - public static final void glDeleteLists(int id) { - DisplayList d = mapDisplayListsGL.free(id); - if(d != null) { - if(d.vertexArray != null) { - EaglercraftGPU.destroyGLBufferArray(d.vertexArray); - } - if(d.vertexBuffer != null) { - _wglDeleteBuffers(d.vertexBuffer); - } - } - } - public static final int glGetError() { return _wglGetError(); } - public static final void glBlendEquation(int equation) { - if(equation != GlStateManager.stateBlendEquation) { - _wglBlendEquation(equation); - GlStateManager.stateBlendEquation = equation; + public static final int glGetInteger(int param) { + return _wglGetInteger(param); + } + + public static final void glGetInteger(int param, int[] values) { + switch (param) { + case GL_VIEWPORT: + values[0] = GlStateManager.viewportX; + values[1] = GlStateManager.viewportY; + values[2] = GlStateManager.viewportW; + values[3] = GlStateManager.viewportH; + break; + default: + throw new UnsupportedOperationException("glGetInteger only accepts GL_VIEWPORT as a parameter"); } } - public static final boolean areVAOsEmulated() { - return emulatedVAOs; - } - - public static final IBufferArrayGL createGLBufferArray() { - if(emulatedVAOs) { - return new SoftGLBufferArray(); - }else { - return _wglGenVertexArrays(); + public static final String glGetString(int param) { + String str = stringCache.get(param); + if (str == null) { + str = _wglGetString(param); + stringCache.put(param, str); } + return str; } - public static final void destroyGLBufferArray(IBufferArrayGL buffer) { - if(!emulatedVAOs) { - _wglDeleteVertexArrays(buffer); + public static final void glLineWidth(float f) { + _wglLineWidth(f); + } + + public static final void glNewList(int target, int op) { + if (currentList != null) { + throw new IllegalStateException("A display list is already being compiled you eagler!"); } - } - - public static final void enableVertexAttribArray(int index) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping enable attrib with emulated VAO because no known VAO is bound!"); - return; + if (op != GL_COMPILE) { + throw new UnsupportedOperationException("Only GL_COMPILE is supported by glNewList"); + } + DisplayList dp = currentList = mapDisplayListsGL.get(target); + if (dp == null) { + throw new IllegalArgumentException("Unknown display list: " + target); + } + if (dp.vertexArray != null && dp.attribs > 0) { + EaglercraftGPU.bindGLBufferArray(dp.vertexArray); + int c = 0; + if ((dp.attribs & ATTRIB_TEXTURE) == ATTRIB_TEXTURE) { + EaglercraftGPU.disableVertexAttribArray(++c); } - ((SoftGLBufferArray)currentBufferArray).enableAttrib(index, true); - }else { - _wglEnableVertexAttribArray(index); + if ((dp.attribs & ATTRIB_COLOR) == ATTRIB_COLOR) { + EaglercraftGPU.disableVertexAttribArray(++c); + } + if ((dp.attribs & ATTRIB_NORMAL) == ATTRIB_NORMAL) { + EaglercraftGPU.disableVertexAttribArray(++c); + } + if ((dp.attribs & ATTRIB_LIGHTMAP) == ATTRIB_LIGHTMAP) { + EaglercraftGPU.disableVertexAttribArray(++c); + } + } + dp.attribs = -1; + dp.mode = -1; + dp.count = 0; + } + + public static final void glNormal3f(float x, float y, float z) { + GlStateManager.stateNormalX = x; + GlStateManager.stateNormalY = y; + GlStateManager.stateNormalZ = z; + ++GlStateManager.stateNormalSerial; + } + + public static final void glReadPixels(int x, int y, int width, int height, int format, int type, + ByteBuffer buffer) { + switch (type) { + case GL_FLOAT: + _wglReadPixels(x, y, width, height, format, GL_FLOAT, buffer.asFloatBuffer()); + break; + case 0x140B: // GL_HALF_FLOAT + _wglReadPixels_u16(x, y, width, height, format, glesVers == 200 ? 0x8D61 : 0x140B, buffer); + break; + case GL_UNSIGNED_BYTE: + default: + _wglReadPixels(x, y, width, height, format, type, buffer); + break; } } - public static final void disableVertexAttribArray(int index) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping disable attrib with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).enableAttrib(index, false); - }else { - _wglDisableVertexAttribArray(index); + public static final void glTexImage2D(int target, int level, int internalFormat, int w, int h, int unused, + int format, int type, ByteBuffer pixels) { + if (glesVers >= 300) { + _wglTexImage2D(target, level, internalFormat, w, h, unused, format, type, pixels); + } else { + int tv = TextureFormatHelper.trivializeInternalFormatToGLES20(internalFormat); + _wglTexImage2D(target, level, tv, w, h, unused, tv, type, pixels); } } - public static final void vertexAttribPointer(int index, int size, int format, boolean normalized, int stride, int offset) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping vertexAttribPointer with emulated VAO because no known VAO is bound!"); - return; - } - if(currentVAOArrayBuffer == null) { - logger.warn("Skipping vertexAttribPointer with emulated VAO because no VAO array buffer is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).setAttrib(currentVAOArrayBuffer, index, size, format, normalized, stride, offset); - }else { - _wglVertexAttribPointer(index, size, format, normalized, stride, offset); + public static final void glTexImage2D(int target, int level, int internalFormat, int w, int h, int unused, + int format, int type, IntBuffer pixels) { + if (glesVers >= 300) { + _wglTexImage2D(target, level, internalFormat, w, h, unused, format, type, pixels); + } else { + int tv = TextureFormatHelper.trivializeInternalFormatToGLES20(internalFormat); + _wglTexImage2D(target, level, tv, w, h, unused, tv, type, pixels); } } - public static final void vertexAttribDivisor(int index, int divisor) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping vertexAttribPointer with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).setAttribDivisor(index, divisor); - }else { - _wglVertexAttribDivisor(index, divisor); - } + public static final void glTexParameterf(int target, int param, float value) { + _wglTexParameterf(target, param, value); } - public static final void doDrawArrays(int mode, int first, int count) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping draw call with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).transitionToState(emulatedVAOState, false); - } - _wglDrawArrays(mode, first, count); + public static final void glTexParameteri(int target, int param, int value) { + _wglTexParameteri(target, param, value); } - public static final void doDrawElements(int mode, int count, int type, int offset) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping draw call with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).transitionToState(emulatedVAOState, true); - } - _wglDrawElements(mode, count, type, offset); - } - - public static final void doDrawArraysInstanced(int mode, int first, int count, int instances) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping instanced draw call with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).transitionToState(emulatedVAOState, false); - } - _wglDrawArraysInstanced(mode, first, count, instances); - } - - public static final void doDrawElementsInstanced(int mode, int count, int type, int offset, int instances) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping instanced draw call with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).transitionToState(emulatedVAOState, true); - } - _wglDrawElementsInstanced(mode, count, type, offset, instances); - } - - static IBufferArrayGL currentBufferArray = null; - - public static final void bindGLBufferArray(IBufferArrayGL buffer) { - if(emulatedVAOs) { - currentBufferArray = buffer; - }else { - if(currentBufferArray != buffer) { - _wglBindVertexArray(buffer); - currentBufferArray = buffer; + public static final void glTexStorage2D(int target, int levels, int internalFormat, int w, int h) { + if (texStorageCapable + && (glesVers >= 300 || levels == 1 || (MathHelper.calculateLogBaseTwo(Math.max(w, h)) + 1) == levels)) { + _wglTexStorage2D(target, levels, internalFormat, w, h); + } else { + int tv = TextureFormatHelper.trivializeInternalFormatToGLES20(internalFormat); + int type = TextureFormatHelper.getTypeFromInternal(internalFormat); + for (int i = 0; i < levels; ++i) { + _wglTexImage2D(target, i, tv, Math.max(w >> i, 1), Math.max(h >> i, 1), 0, tv, type, (ByteBuffer) null); } } } - static IBufferGL currentArrayBuffer = null; + public static final void glTexSubImage2D(int target, int level, int x, int y, int w, int h, int format, int type, + IntBuffer pixels) { + _wglTexSubImage2D(target, level, x, y, w, h, format, type, pixels); + } - // only used when VAOs are emulated - static IBufferGL currentVAOArrayBuffer = null; - - public static final void bindVAOGLArrayBuffer(IBufferGL buffer) { - if(emulatedVAOs) { - currentVAOArrayBuffer = buffer; - }else { - if(currentArrayBuffer != buffer) { - _wglBindBuffer(GL_ARRAY_BUFFER, buffer); - currentArrayBuffer = buffer; - } + public static final String gluErrorString(int i) { + switch (i) { + case GL_INVALID_ENUM: + return "GL_INVALID_ENUM"; + case GL_INVALID_VALUE: + return "GL_INVALID_VALUE"; + case 1286: + return "GL_INVALID_FRAMEBUFFER_OPERATION"; + case GL_INVALID_OPERATION: + return "GL_INVALID_OPERATION"; + case GL_OUT_OF_MEMORY: + return "GL_OUT_OF_MEMORY"; + case GL_CONTEXT_LOST_WEBGL: + return "CONTEXT_LOST_WEBGL"; + default: + return "Unknown Error"; } } - public static final void bindVAOGLArrayBufferNow(IBufferGL buffer) { - if(emulatedVAOs) { - currentVAOArrayBuffer = buffer; - } - if(currentArrayBuffer != buffer) { - _wglBindBuffer(GL_ARRAY_BUFFER, buffer); - currentArrayBuffer = buffer; - } - } - - public static final void bindVAOGLElementArrayBuffer(IBufferGL buffer) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping set element array buffer with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).setIndexBuffer(buffer); - }else { - _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); - } - } - - static final void bindVAOGLElementArrayBufferNow(IBufferGL buffer) { - if(emulatedVAOs) { - if(currentBufferArray == null) { - logger.warn("Skipping set element array buffer with emulated VAO because no known VAO is bound!"); - return; - } - ((SoftGLBufferArray)currentBufferArray).setIndexBuffer(buffer); - if(currentEmulatedVAOIndexBuffer != buffer) { - _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); - currentEmulatedVAOIndexBuffer = buffer; - } - }else { - _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); - } - } - - static IBufferGL currentEmulatedVAOIndexBuffer = null; - - static final void bindEmulatedVAOIndexBuffer(IBufferGL buffer) { - if(currentEmulatedVAOIndexBuffer != buffer) { - _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer); - currentEmulatedVAOIndexBuffer = buffer; - } - } - - public static final void bindGLArrayBuffer(IBufferGL buffer) { - if(currentArrayBuffer != buffer) { - _wglBindBuffer(GL_ARRAY_BUFFER, buffer); - currentArrayBuffer = buffer; - } - } - - static IBufferGL currentUniformBuffer = null; - - public static final void bindGLUniformBuffer(IBufferGL buffer) { - if(currentUniformBuffer != buffer) { - _wglBindBuffer(0x8A11, buffer); - currentUniformBuffer = buffer; - } - } - - static IProgramGL currentShaderProgram = null; - - public static final void bindGLShaderProgram(IProgramGL prog) { - if(currentShaderProgram != prog) { - _wglUseProgram(prog); - currentShaderProgram = prog; - } - } - - private static final IBufferGL[] currentUniformBlockBindings = new IBufferGL[16]; - private static final int[] currentUniformBlockBindingOffset = new int[16]; - private static final int[] currentUniformBlockBindingSize = new int[16]; - - public static final void bindUniformBufferRange(int index, IBufferGL buffer, int offset, int size) { - if(currentUniformBlockBindings[index] != buffer || currentUniformBlockBindingOffset[index] != offset - || currentUniformBlockBindingSize[index] != size) { - _wglBindBufferRange(0x8A11, index, buffer, offset, size); - currentUniformBlockBindings[index] = buffer; - currentUniformBlockBindingOffset[index] = offset; - currentUniformBlockBindingSize[index] = size; - } - } - - public static final int CLEAR_BINDING_TEXTURE = 1; - public static final int CLEAR_BINDING_TEXTURE0 = 2; - public static final int CLEAR_BINDING_ACTIVE_TEXTURE = 4; - public static final int CLEAR_BINDING_BUFFER_ARRAY = 8; - public static final int CLEAR_BINDING_ARRAY_BUFFER = 16; - public static final int CLEAR_BINDING_SHADER_PROGRAM = 32; - - public static final void clearCurrentBinding(int mask) { - if((mask & CLEAR_BINDING_TEXTURE) != 0) { - int[] i = GlStateManager.boundTexture; - for(int j = 0; j < i.length; ++j) { - i[j] = -1; - } - } - if((mask & CLEAR_BINDING_TEXTURE0) != 0) { - GlStateManager.boundTexture[0] = -1; - } - if((mask & CLEAR_BINDING_ACTIVE_TEXTURE) != 0) { - GlStateManager.activeTexture = 0; - _wglActiveTexture(GL_TEXTURE0); - } - if((mask & CLEAR_BINDING_BUFFER_ARRAY) != 0) { - currentBufferArray = null; - } - if((mask & CLEAR_BINDING_ARRAY_BUFFER) != 0) { - currentArrayBuffer = currentVAOArrayBuffer = null; - } - if((mask & CLEAR_BINDING_SHADER_PROGRAM) != 0) { - currentShaderProgram = null; - } - } - - public static final int ATTRIB_TEXTURE = 1; - public static final int ATTRIB_COLOR = 2; - public static final int ATTRIB_NORMAL = 4; - public static final int ATTRIB_LIGHTMAP = 8; - - public static final void renderBuffer(ByteBuffer buffer, int attrib, int mode, int count) { - if(currentList != null) { - if(currentList.attribs == -1) { - currentList.attribs = attrib; - }else if(currentList.attribs != attrib) { - throw new UnsupportedOperationException("Inconsistent vertex format in display list (only one is allowed)"); - } - if(currentList.mode == -1) { - currentList.mode = mode; - }else if(currentList.mode != mode) { - throw new UnsupportedOperationException("Inconsistent draw mode in display list (only one is allowed)"); - } - currentList.count += count; - if(buffer.remaining() > displayListBuffer.remaining()) { - growDisplayListBuffer(buffer.remaining()); - } - displayListBuffer.put(buffer); - lastRender = null; - }else { - lastRender = FixedFunctionPipeline.setupDirect(buffer, attrib).update(); - lastRender.drawDirectArrays(mode, 0, count); - lastMode = mode; - lastCount = count; + private static final void growDisplayListBuffer(int len) { + int wantSize = displayListBuffer.position() + len; + if (displayListBuffer.capacity() < wantSize) { + int newSize = (wantSize & 0xFFFE0000) + 0x40000; + ByteBuffer newBuffer = EagRuntime.allocateByteBuffer(newSize); + newBuffer.put((ByteBuffer) displayListBuffer.flip()); + EagRuntime.freeByteBuffer(displayListBuffer); + displayListBuffer = newBuffer; } } @@ -640,72 +948,57 @@ public class EaglercraftGPU { FixedFunctionPipeline.optimize(); } - private static FixedFunctionPipeline lastRender = null; - private static int lastMode = 0; - private static int lastCount = 0; + public static final void regenerateTexture(int tex) { + ITextureGL webglTex = mapTexturesGL.get(tex); + if (webglTex != null) { + GlStateManager.unbindTextureIfCached(tex); + _wglDeleteTextures(webglTex); + mapTexturesGL.set(tex, _wglGenTextures()); + } else { + logger.error("Tried to regenerate a missing texture!"); + } + } public static final void renderAgain() { - if(lastRender == null) { - throw new UnsupportedOperationException("Cannot render the same verticies twice while generating display list"); + if (lastRender == null) { + throw new UnsupportedOperationException( + "Cannot render the same verticies twice while generating display list"); } EaglercraftGPU.bindGLBufferArray(lastRender.getDirectModeBufferArray()); lastRender.update().drawDirectArrays(lastMode, 0, lastCount); } - private static IBufferGL quad16EmulationBuffer = null; - private static int quad16EmulationBufferSize = 0; - - private static IBufferGL quad32EmulationBuffer = null; - private static int quad32EmulationBufferSize = 0; - - public static final void attachQuad16EmulationBuffer(int vertexCount, boolean bind) { - IBufferGL buf = quad16EmulationBuffer; - if(buf == null) { - quad16EmulationBuffer = buf = _wglGenBuffers(); - int newSize = quad16EmulationBufferSize = (vertexCount & 0xFFFFF000) + 0x2000; - if(newSize > 0xFFFF) { - newSize = 0xFFFF; + public static final void renderBuffer(ByteBuffer buffer, int attrib, int mode, int count) { + if (currentList != null) { + if (currentList.attribs == -1) { + currentList.attribs = attrib; + } else if (currentList.attribs != attrib) { + throw new UnsupportedOperationException( + "Inconsistent vertex format in display list (only one is allowed)"); } - EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); - resizeQuad16EmulationBuffer(newSize >> 2); - }else { - int cnt = quad16EmulationBufferSize; - if(cnt < vertexCount) { - int newSize = quad16EmulationBufferSize = (vertexCount & 0xFFFFF000) + 0x2000; - if(newSize > 0xFFFF) { - newSize = 0xFFFF; - } - EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); - resizeQuad16EmulationBuffer(newSize >> 2); - }else if(bind) { - EaglercraftGPU.bindVAOGLElementArrayBuffer(buf); + if (currentList.mode == -1) { + currentList.mode = mode; + } else if (currentList.mode != mode) { + throw new UnsupportedOperationException("Inconsistent draw mode in display list (only one is allowed)"); } + currentList.count += count; + if (buffer.remaining() > displayListBuffer.remaining()) { + growDisplayListBuffer(buffer.remaining()); + } + displayListBuffer.put(buffer); + lastRender = null; + } else { + lastRender = FixedFunctionPipeline.setupDirect(buffer, attrib).update(); + lastRender.drawDirectArrays(mode, 0, count); + lastMode = mode; + lastCount = count; } } - - public static final void attachQuad32EmulationBuffer(int vertexCount, boolean bind) { - IBufferGL buf = quad32EmulationBuffer; - if(buf == null) { - quad32EmulationBuffer = buf = _wglGenBuffers(); - int newSize = quad32EmulationBufferSize = (vertexCount & 0xFFFFC000) + 0x8000; - EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); - resizeQuad32EmulationBuffer(newSize >> 2); - }else { - int cnt = quad32EmulationBufferSize; - if(cnt < vertexCount) { - int newSize = quad32EmulationBufferSize = (vertexCount & 0xFFFFC000) + 0x8000; - EaglercraftGPU.bindVAOGLElementArrayBufferNow(buf); - resizeQuad32EmulationBuffer(newSize >> 2); - }else if(bind) { - EaglercraftGPU.bindVAOGLElementArrayBuffer(buf); - } - } - } - + private static final void resizeQuad16EmulationBuffer(int quadCount) { IntBuffer buf = EagRuntime.allocateIntBuffer(quadCount * 3); int v1, v2, v3, v4; - for(int i = 0; i < quadCount; ++i) { + for (int i = 0; i < quadCount; ++i) { v1 = i << 2; v2 = v1 + 1; v3 = v2 + 1; @@ -718,142 +1011,54 @@ public class EaglercraftGPU { _wglBufferData(GL_ELEMENT_ARRAY_BUFFER, buf, GL_STATIC_DRAW); EagRuntime.freeIntBuffer(buf); } - + private static final void resizeQuad32EmulationBuffer(int quadCount) { IntBuffer buf = EagRuntime.allocateIntBuffer(quadCount * 6); int v1, v2, v3, v4; - for(int i = 0; i < quadCount; ++i) { + for (int i = 0; i < quadCount; ++i) { v1 = i << 2; v2 = v1 + 1; v3 = v2 + 1; v4 = v3 + 1; - buf.put(v1); buf.put(v2); - buf.put(v4); buf.put(v2); - buf.put(v3); buf.put(v4); + buf.put(v1); + buf.put(v2); + buf.put(v4); + buf.put(v2); + buf.put(v3); + buf.put(v4); } buf.flip(); _wglBufferData(GL_ELEMENT_ARRAY_BUFFER, buf, GL_STATIC_DRAW); EagRuntime.freeIntBuffer(buf); } - public static final ITextureGL getNativeTexture(int tex) { - return mapTexturesGL.get(tex); - } - - public static final void regenerateTexture(int tex) { - ITextureGL webglTex = mapTexturesGL.get(tex); - if(webglTex != null) { - GlStateManager.unbindTextureIfCached(tex); - _wglDeleteTextures(webglTex); - mapTexturesGL.set(tex, _wglGenTextures()); - }else { - logger.error("Tried to regenerate a missing texture!"); + public static final void vertexAttribDivisor(int index, int divisor) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping vertexAttribPointer with emulated VAO because no known VAO is bound!"); + return; + } + ((SoftGLBufferArray) currentBufferArray).setAttribDivisor(index, divisor); + } else { + _wglVertexAttribDivisor(index, divisor); } } - public static final void drawHighPoly(HighPolyMesh mesh) { - if(mesh.vertexCount == 0 || mesh.indexCount == 0 || mesh.vertexArray == null) { - return; - } - FixedFunctionPipeline p = FixedFunctionPipeline.setupRenderDisplayList(mesh.getAttribBits()).update(); - EaglercraftGPU.bindGLBufferArray(mesh.vertexArray); - p.drawElements(GL_TRIANGLES, mesh.indexCount, GL_UNSIGNED_SHORT, 0); - } - - static int glesVers = -1; - static boolean hasFramebufferHDR16FSupport = false; - static boolean hasFramebufferHDR32FSupport = false; - static boolean hasLinearHDR16FSupport = false; - static boolean hasLinearHDR32FSupport = false; - static boolean fboRenderMipmapCapable = false; - static boolean vertexArrayCapable = false; - static boolean instancingCapable = false; - static boolean texStorageCapable = false; - static boolean textureLODCapable = false; - static boolean shader5Capable = false; - static boolean npotCapable = false; - static int uniformBufferOffsetAlignment = -1; - - public static final void createFramebufferHDR16FTexture(int target, int level, int w, int h, int format, boolean allow32bitFallback) { - createFramebufferHDR16FTexture(target, level, w, h, format, allow32bitFallback, null); - } - - public static final void createFramebufferHDR16FTexture(int target, int level, int w, int h, int format, ByteBuffer pixelData) { - createFramebufferHDR16FTexture(target, level, w, h, format, false, pixelData); - } - - private static final void createFramebufferHDR16FTexture(int target, int level, int w, int h, int format, boolean allow32bitFallback, ByteBuffer pixelData) { - if(hasFramebufferHDR16FSupport) { - int internalFormat; - switch(format) { - case GL_RED: - if(glesVers == 200) { - format = GL_LUMINANCE; - internalFormat = GL_LUMINANCE; - }else { - internalFormat = glesVers == 200 ? GL_LUMINANCE : 0x822D; // GL_R16F - } - break; - case 0x8227: // GL_RG - internalFormat = glesVers == 200 ? 0x8227 : 0x822F; // GL_RG16F - case GL_RGB: - throw new UnsupportedOperationException("GL_RGB16F isn't supported specifically in WebGL 2.0 for some goddamn reason"); - case GL_RGBA: - internalFormat = glesVers == 200 ? GL_RGBA : 0x881A; // GL_RGBA16F - break; - default: - throw new UnsupportedOperationException("Unknown format: " + format); + public static final void vertexAttribPointer(int index, int size, int format, boolean normalized, int stride, + int offset) { + if (emulatedVAOs) { + if (currentBufferArray == null) { + logger.warn("Skipping vertexAttribPointer with emulated VAO because no known VAO is bound!"); + return; } - _wglTexImage2Du16(target, level, internalFormat, w, h, 0, format, glesVers == 200 ? 0x8D61 : 0x140B, pixelData); - }else { - if(allow32bitFallback) { - if(hasFramebufferHDR32FSupport) { - createFramebufferHDR32FTexture(target, level, w, h, format, false, null); - }else { - throw new UnsupportedOperationException("No fallback 32-bit HDR (floating point) texture support is available on this device"); - } - }else { - throw new UnsupportedOperationException("16-bit HDR (floating point) textures are not supported on this device"); - } - } - } - - public static final void createFramebufferHDR32FTexture(int target, int level, int w, int h, int format, boolean allow16bitFallback) { - createFramebufferHDR32FTexture(target, level, w, h, format, allow16bitFallback, null); - } - - public static final void createFramebufferHDR32FTexture(int target, int level, int w, int h, int format, ByteBuffer pixelData) { - createFramebufferHDR32FTexture(target, level, w, h, format, false, pixelData); - } - - private static final void createFramebufferHDR32FTexture(int target, int level, int w, int h, int format, boolean allow16bitFallback, ByteBuffer pixelData) { - if(hasFramebufferHDR32FSupport) { - int internalFormat; - switch(format) { - case GL_RED: - internalFormat = 0x822E; // GL_R32F - break; - case 0x8227: // GL_RG - internalFormat = 0x8230; // GL_RG32F - case GL_RGB: - throw new UnsupportedOperationException("GL_RGB32F isn't supported specifically in WebGL 2.0 for some goddamn reason"); - case GL_RGBA: - internalFormat = 0x8814; //GL_RGBA32F - break; - default: - throw new UnsupportedOperationException("Unknown format: " + format); - } - _wglTexImage2Df32(target, level, internalFormat, w, h, 0, format, GL_FLOAT, pixelData); - }else { - if(allow16bitFallback) { - if(hasFramebufferHDR16FSupport) { - createFramebufferHDR16FTexture(target, level, w, h, format, false); - }else { - throw new UnsupportedOperationException("No fallback 16-bit HDR (floating point) texture support is available on this device"); - } - }else { - throw new UnsupportedOperationException("32-bit HDR (floating point) textures are not supported on this device"); + if (currentVAOArrayBuffer == null) { + logger.warn("Skipping vertexAttribPointer with emulated VAO because no VAO array buffer is bound!"); + return; } + ((SoftGLBufferArray) currentBufferArray).setAttrib(currentVAOArrayBuffer, index, size, format, normalized, + stride, offset); + } else { + _wglVertexAttribPointer(index, size, format, normalized, stride, offset); } } @@ -871,48 +1076,50 @@ public class EaglercraftGPU { shader5Capable = PlatformOpenGL.checkOESGPUShader5Capable() || PlatformOpenGL.checkEXTGPUShader5Capable(); npotCapable = PlatformOpenGL.checkNPOTCapable(); uniformBufferOffsetAlignment = glesVers >= 300 ? _wglGetInteger(0x8A34) : -1; - if(!npotCapable) { - logger.warn("NPOT texture support detected as false, texture wrapping must be set to GL_CLAMP_TO_EDGE if the texture's width or height is not a power of 2"); + if (!npotCapable) { + logger.warn( + "NPOT texture support detected as false, texture wrapping must be set to GL_CLAMP_TO_EDGE if the texture's width or height is not a power of 2"); } hasFramebufferHDR16FSupport = PlatformOpenGL.checkHDRFramebufferSupport(16); - if(hasFramebufferHDR16FSupport) { + if (hasFramebufferHDR16FSupport) { logger.info("16-bit HDR render target support: true"); - }else { + } else { logger.error("16-bit HDR render target support: false"); } hasLinearHDR16FSupport = PlatformOpenGL.checkLinearHDRFilteringSupport(16); - if(hasLinearHDR16FSupport) { + if (hasLinearHDR16FSupport) { logger.info("16-bit HDR linear filter support: true"); - }else { + } else { logger.error("16-bit HDR linear filter support: false"); } hasFramebufferHDR32FSupport = PlatformOpenGL.checkHDRFramebufferSupport(32); - if(hasFramebufferHDR32FSupport) { + if (hasFramebufferHDR32FSupport) { logger.info("32-bit HDR render target support: true"); - }else { + } else { logger.error("32-bit HDR render target support: false"); } hasLinearHDR32FSupport = PlatformOpenGL.checkLinearHDRFilteringSupport(32); - if(hasLinearHDR32FSupport) { + if (hasLinearHDR32FSupport) { logger.info("32-bit HDR linear filter support: true"); - }else { + } else { logger.error("32-bit HDR linear filter support: false"); } - if(!checkHasHDRFramebufferSupportWithFilter()) { + if (!checkHasHDRFramebufferSupportWithFilter()) { logger.error("No HDR render target support was detected! Shaders will be disabled."); } - if(emulatedVAOs) { + if (emulatedVAOs) { logger.info("Note: Could not unlock VAOs via OpenGL extensions, emulating them instead"); } - if(!instancingCapable) { - logger.info("Note: Could not unlock instancing via OpenGL extensions, using slow vanilla font and particle rendering"); + if (!instancingCapable) { + logger.info( + "Note: Could not unlock instancing via OpenGL extensions, using slow vanilla font and particle rendering"); } emulatedVAOState = emulatedVAOs ? new SoftGLBufferState() : null; PlatformOpenGL.enterVAOEmulationHook(); GLSLHeader.init(); DrawUtils.init(); SpriteLevelMixer.initialize(); - if(instancingCapable) { + if (instancingCapable) { InstancedFontRenderer.initialize(); InstancedParticleRenderer.initialize(); } @@ -922,98 +1129,4 @@ public class EaglercraftGPU { DrawUtils.vshLocal = null; } - public static final void destroyCache() { - stringCache.clear(); - mapTexturesGL.clear(); - mapQueriesGL.clear(); - mapDisplayListsGL.clear(); - emulatedVAOs = false; - emulatedVAOState = null; - glesVers = -1; - fboRenderMipmapCapable = false; - vertexArrayCapable = false; - instancingCapable = false; - hasFramebufferHDR16FSupport = false; - hasFramebufferHDR32FSupport = false; - hasLinearHDR32FSupport = false; - GLSLHeader.destroy(); - DrawUtils.destroy(); - SpriteLevelMixer.destroy(); - InstancedFontRenderer.destroy(); - InstancedParticleRenderer.destroy(); - EffectPipelineFXAA.destroy(); - TextureCopyUtil.destroy(); - } - - public static final int checkOpenGLESVersion() { - return glesVers; - } - - public static final boolean checkFBORenderMipmapCapable() { - return fboRenderMipmapCapable; - } - - public static final boolean checkVAOCapable() { - return vertexArrayCapable; - } - - public static final boolean checkInstancingCapable() { - return instancingCapable; - } - - public static final boolean checkTexStorageCapable() { - return texStorageCapable; - } - - public static final boolean checkTextureLODCapable() { - return textureLODCapable; - } - - public static final boolean checkShader5Capable() { - return shader5Capable; - } - - public static final boolean checkNPOTCapable() { - return npotCapable; - } - - public static final int getUniformBufferOffsetAlignment() { - return uniformBufferOffsetAlignment; - } - - public static final boolean checkHDRFramebufferSupport(int bits) { - switch(bits) { - case 16: - return hasFramebufferHDR16FSupport; - case 32: - return hasFramebufferHDR32FSupport; - default: - return false; - } - } - - public static final boolean checkLinearHDRFilteringSupport(int bits) { - switch(bits) { - case 16: - return hasLinearHDR16FSupport; - case 32: - return hasLinearHDR32FSupport; - default: - return false; - } - } - - public static final boolean checkHasHDRFramebufferSupport() { - return hasFramebufferHDR16FSupport || hasFramebufferHDR32FSupport; - } - - public static final boolean checkHasHDRFramebufferSupportWithFilter() { - return (hasFramebufferHDR16FSupport && hasLinearHDR16FSupport) || (hasFramebufferHDR32FSupport && hasLinearHDR32FSupport); - } - - //legacy - public static final boolean checkLinearHDR32FSupport() { - return hasLinearHDR32FSupport; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EffectPipelineFXAA.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EffectPipelineFXAA.java index 9166ec7f..379dc95a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EffectPipelineFXAA.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/EffectPipelineFXAA.java @@ -1,5 +1,49 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgramInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglRenderbufferStorage; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; + +import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IFramebufferGL; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IRenderbufferGL; @@ -9,22 +53,18 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - -import net.lax1dude.eaglercraft.v1_8.EagRuntime; - /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -53,6 +93,60 @@ public class EffectPipelineFXAA { private static int currentWidth = -1; private static int currentHeight = -1; + public static void begin(int width, int height) { + if (currentWidth != width || currentHeight != height) { + currentWidth = width; + currentHeight = height; + + GlStateManager.bindTexture(framebufferColor); + EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, + (ByteBuffer) null); + + _wglBindRenderbuffer(_GL_RENDERBUFFER, framebufferDepth); + _wglRenderbufferStorage(_GL_RENDERBUFFER, + EaglercraftGPU.checkOpenGLESVersion() == 200 ? _GL_DEPTH_COMPONENT16 : _GL_DEPTH_COMPONENT32F, + width, height); + } + + _wglBindFramebuffer(_GL_FRAMEBUFFER, framebuffer); + + GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 1.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + } + + public static void destroy() { + if (shaderProgram != null) { + _wglDeleteProgram(shaderProgram); + shaderProgram = null; + } + u_screenSize2f = null; + if (framebuffer != null) { + _wglDeleteFramebuffer(framebuffer); + framebuffer = null; + } + if (framebufferColor != -1) { + GlStateManager.deleteTexture(framebufferColor); + framebufferColor = -1; + } + if (framebufferDepth != null) { + _wglDeleteRenderbuffer(framebufferDepth); + framebufferDepth = null; + } + } + + public static void end() { + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + + EaglercraftGPU.bindGLShaderProgram(shaderProgram); + + GlStateManager.bindTexture(framebufferColor); + + _wglUniform2f(u_screenSize2f, 1.0f / currentWidth, 1.0f / currentHeight); + + DrawUtils.drawStandardQuad2D(); + } + static void initialize() { String fragmentSource = EagRuntime.getRequiredResourceString(fragmentShaderPath); @@ -61,12 +155,12 @@ public class EffectPipelineFXAA { _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(fragmentSource, fragmentShaderPrecision)); _wglCompileShader(frag); - if(_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { + if (_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { logger.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for EffectPipelineFXAA!"); String log = _wglGetShaderInfoLog(frag); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[FRAG] {}", lines[i]); } } @@ -78,7 +172,7 @@ public class EffectPipelineFXAA { _wglAttachShader(shaderProgram, DrawUtils.vshLocal); _wglAttachShader(shaderProgram, frag); - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { VSHInputLayoutParser.applyLayout(shaderProgram, DrawUtils.vshLocalLayout); } @@ -89,12 +183,12 @@ public class EffectPipelineFXAA { _wglDeleteShader(frag); - if(_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { + if (_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { logger.error("Failed to link shader program for EffectPipelineFXAA!"); String log = _wglGetProgramInfoLog(shaderProgram); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[LINK] {}", lines[i]); } } @@ -120,61 +214,11 @@ public class EffectPipelineFXAA { _wglBindRenderbuffer(_GL_RENDERBUFFER, framebufferDepth); _wglBindFramebuffer(_GL_FRAMEBUFFER, framebuffer); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(framebufferColor), 0); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(framebufferColor), 0); _wglFramebufferRenderbuffer(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, _GL_RENDERBUFFER, framebufferDepth); _wglBindFramebuffer(_GL_FRAMEBUFFER, null); } - public static void begin(int width, int height) { - if(currentWidth != width || currentHeight != height) { - currentWidth = width; - currentHeight = height; - - GlStateManager.bindTexture(framebufferColor); - EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - - _wglBindRenderbuffer(_GL_RENDERBUFFER, framebufferDepth); - _wglRenderbufferStorage(_GL_RENDERBUFFER, EaglercraftGPU.checkOpenGLESVersion() == 200 ? _GL_DEPTH_COMPONENT16 : _GL_DEPTH_COMPONENT32F, width, height); - } - - _wglBindFramebuffer(_GL_FRAMEBUFFER, framebuffer); - - GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 1.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - } - - public static void end() { - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - - EaglercraftGPU.bindGLShaderProgram(shaderProgram); - - GlStateManager.bindTexture(framebufferColor); - - _wglUniform2f(u_screenSize2f, 1.0f / currentWidth, 1.0f / currentHeight); - - DrawUtils.drawStandardQuad2D(); - } - - public static void destroy() { - if(shaderProgram != null) { - _wglDeleteProgram(shaderProgram); - shaderProgram = null; - } - u_screenSize2f = null; - if(framebuffer != null) { - _wglDeleteFramebuffer(framebuffer); - framebuffer = null; - } - if(framebufferColor != -1) { - GlStateManager.deleteTexture(framebufferColor); - framebufferColor = -2; - } - if(framebufferDepth != null) { - _wglDeleteRenderbuffer(framebufferDepth); - framebufferDepth = null; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionPipeline.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionPipeline.java index 8b65c2e5..3b130f84 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionPipeline.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionPipeline.java @@ -1,14 +1,103 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindAttribLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgramInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.ATTRIB_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.ATTRIB_LIGHTMAP; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.ATTRIB_NORMAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.ATTRIB_POSITION; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.ATTRIB_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.FILENAME_FSH; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.FILENAME_VSH; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ATTRIB_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ATTRIB_LIGHTMAP; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ATTRIB_NORMAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ATTRIB_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_ALPHA_TEST; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_ANISOTROPIC_FIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_BLEND_ADD; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_END_PORTAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_FOG; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_LIGHTMAP; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_MC_LIGHTING; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.MACRO_ENABLE_TEXTURE2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.PRECISION_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.PRECISION_INT; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.PRECISION_SAMPLER; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_ALPHA_TEST_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_BLEND_ADD_COLOR_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_BLEND_SRC_COLOR_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_COLOR_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_CONSTANT_NORMAL_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_FOG_COLOR_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_FOG_PARAM_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_LIGHTS_AMBIENT_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_LIGHTS_ENABLED_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_LIGHTS_VECTORS_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_MODEL_MATRIX_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_MODEL_PROJECTION_MATRIX_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_PROJECTION_MATRIX_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_ANISOTROPIC_FIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_COORDS_01_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_COORDS_02_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_MATRIX_01_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_MATRIX_02_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_UNIT_01_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEXTURE_UNIT_02_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEX_GEN_PLANE_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEX_GEN_Q_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEX_GEN_R_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEX_GEN_S_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.UNIFORM_TEX_GEN_T_NAME; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_ALPHA_TEST; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_ANISOTROPIC_FIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_BLEND_ADD; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_END_PORTAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_FOG; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_LIGHTMAP; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_MC_LIGHTING; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_ENABLE_TEXTURE2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_HAS_ATTRIB_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_HAS_ATTRIB_LIGHTMAP; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_HAS_ATTRIB_NORMAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.STATE_HAS_ATTRIB_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.fixedFunctionStatesBits; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EYE_PLANE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_QUADS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_INT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import java.util.ArrayList; import java.util.List; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; - import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; @@ -16,6 +105,8 @@ import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; import net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL; import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.opengl.StreamBuffer.StreamBufferInstance; @@ -24,295 +115,211 @@ import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; import net.lax1dude.eaglercraft.v1_8.vector.Vector4f; import net.minecraft.util.MathHelper; -import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionState.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionConstants.*; - /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FixedFunctionPipeline { - + private static final Logger LOGGER = LogManager.getLogger("FixedFunctionPipeline"); - static final int getFragmentState() { - return (GlStateManager.stateTexture[0] ? STATE_ENABLE_TEXTURE2D : 0) | - (GlStateManager.stateTexture[1] ? STATE_ENABLE_LIGHTMAP : 0) | - (GlStateManager.stateAlphaTest ? STATE_ENABLE_ALPHA_TEST : 0) | - ((GlStateManager.stateLighting && GlStateManager.stateMaterial) - ? STATE_ENABLE_MC_LIGHTING : 0) | - ((GlStateManager.stateTexture[0] && GlStateManager.stateTexGen) - ? STATE_ENABLE_END_PORTAL : 0) | - /* TODO: (GlStateManager.??? ? STATE_ENABLE_ANISOTROPIC_FIX : 0) | */ - ((GlStateManager.stateFog && GlStateManager.stateFogDensity > 0.0f) - ? STATE_ENABLE_FOG : 0) | - (GlStateManager.stateEnableShaderBlendColor ? STATE_ENABLE_BLEND_ADD : 0); - } - - static FixedFunctionPipeline setupDirect(ByteBuffer buffer, int attrib) { - FixedFunctionPipeline self; - int baseState = attrib | getFragmentState(); - if(GlStateManager.stateUseExtensionPipeline) { - if(extensionProvider != null) { - self = getPipelineInstanceExt(baseState, extensionProvider.getCurrentExtensionStateBits(baseState)); - }else { - throw new IllegalStateException("No extension pipeline is available!"); - } - }else { - self = getPipelineInstanceCore(baseState); - } - - StreamBufferInstance sb = self.streamBuffer.getBuffer(buffer.remaining()); - self.currentVertexArray = sb; - - EaglercraftGPU.bindGLBufferArray(sb.vertexArray); - EaglercraftGPU.bindGLArrayBuffer(sb.vertexBuffer); - - _wglBufferSubData(GL_ARRAY_BUFFER, 0, buffer); - - return self; - } - - static void setupDisplayList(DisplayList list) { - FixedFunctionPipeline self; - int baseState = list.attribs | getFragmentState(); - if(GlStateManager.stateUseExtensionPipeline) { - if(extensionProvider != null) { - self = getPipelineInstanceExt(baseState, extensionProvider.getCurrentExtensionStateBits(baseState)); - }else { - throw new IllegalStateException("No extension pipeline is available!"); - } - }else { - self = getPipelineInstanceCore(baseState); - } - - EaglercraftGPU.bindGLBufferArray(list.vertexArray); - EaglercraftGPU.bindVAOGLArrayBuffer(list.vertexBuffer); - - EaglercraftGPU.enableVertexAttribArray(0); - EaglercraftGPU.vertexAttribPointer(0, VertexFormat.COMPONENT_POSITION_SIZE, - VertexFormat.COMPONENT_POSITION_FORMAT, false, self.attribStride, 0); - - if(self.attribTextureIndex != -1) { - EaglercraftGPU.enableVertexAttribArray(self.attribTextureIndex); - EaglercraftGPU.vertexAttribPointer(self.attribTextureIndex, VertexFormat.COMPONENT_TEX_SIZE, - VertexFormat.COMPONENT_TEX_FORMAT, false, self.attribStride, self.attribTextureOffset); - } - - if(self.attribColorIndex != -1) { - EaglercraftGPU.enableVertexAttribArray(self.attribColorIndex); - EaglercraftGPU.vertexAttribPointer(self.attribColorIndex, VertexFormat.COMPONENT_COLOR_SIZE, - VertexFormat.COMPONENT_COLOR_FORMAT, true, self.attribStride, self.attribColorOffset); - } - - if(self.attribNormalIndex != -1) { - EaglercraftGPU.enableVertexAttribArray(self.attribNormalIndex); - EaglercraftGPU.vertexAttribPointer(self.attribNormalIndex, VertexFormat.COMPONENT_NORMAL_SIZE, - VertexFormat.COMPONENT_NORMAL_FORMAT, true, self.attribStride, self.attribNormalOffset); - } - - if(self.attribLightmapIndex != -1) { - EaglercraftGPU.enableVertexAttribArray(self.attribLightmapIndex); - EaglercraftGPU.vertexAttribPointer(self.attribLightmapIndex, VertexFormat.COMPONENT_LIGHTMAP_SIZE, - VertexFormat.COMPONENT_LIGHTMAP_FORMAT, false, self.attribStride, self.attribLightmapOffset); - } - - } - - static FixedFunctionPipeline setupRenderDisplayList(int attribs) { - int baseState = attribs | getFragmentState(); - if(GlStateManager.stateUseExtensionPipeline) { - if(extensionProvider != null) { - return getPipelineInstanceExt(baseState, extensionProvider.getCurrentExtensionStateBits(baseState)); - }else { - throw new IllegalStateException("No extension pipeline is available!"); - } - }else { - return getPipelineInstanceCore(baseState); - } - } - - void drawArrays(int mode, int offset, int count) { - EaglercraftGPU.bindGLShaderProgram(shaderProgram); - EaglercraftGPU.doDrawArrays(mode, offset, count); - } - - void drawDirectArrays(int mode, int offset, int count) { - EaglercraftGPU.bindGLShaderProgram(shaderProgram); - if(mode == GL_QUADS) { - StreamBufferInstance sb = currentVertexArray; - if(count > 0xFFFF) { - if(!sb.bindQuad32) { - sb.bindQuad16 = false; - sb.bindQuad32 = true; - EaglercraftGPU.attachQuad32EmulationBuffer(count, true); - }else { - EaglercraftGPU.attachQuad32EmulationBuffer(count, false); - } - EaglercraftGPU.doDrawElements(GL_TRIANGLES, count + (count >> 1), - GL_UNSIGNED_INT, 0); - }else { - if(!sb.bindQuad16) { - sb.bindQuad16 = true; - sb.bindQuad32 = false; - EaglercraftGPU.attachQuad16EmulationBuffer(count, true); - }else { - EaglercraftGPU.attachQuad16EmulationBuffer(count, false); - } - EaglercraftGPU.doDrawElements(GL_TRIANGLES, count + (count >> 1), - GL_UNSIGNED_SHORT, 0); - } - }else { - EaglercraftGPU.doDrawArrays(mode, offset, count); - } - } - - void drawElements(int mode, int count, int type, int offset) { - EaglercraftGPU.bindGLShaderProgram(shaderProgram); - EaglercraftGPU.doDrawElements(mode, count, type, offset); - } - private static IExtPipelineCompiler extensionProvider; - - public static void loadExtensionPipeline(IExtPipelineCompiler provider) { - flushCache(); - extensionProvider = provider; - } - private static final FixedFunctionPipeline[] pipelineStateCache = new FixedFunctionPipeline[fixedFunctionStatesBits + 1]; - private static final FixedFunctionPipeline[][] pipelineExtStateCache = new FixedFunctionPipeline[fixedFunctionStatesBits + 1][]; + private static final FixedFunctionPipeline[] pipelineStateCache = new FixedFunctionPipeline[fixedFunctionStatesBits + + 1]; + + private static final FixedFunctionPipeline[][] pipelineExtStateCache = new FixedFunctionPipeline[fixedFunctionStatesBits + + 1][]; + private static final List pipelineListTracker = new ArrayList<>(1024); private static String shaderSourceCacheVSH = null; + private static String shaderSourceCacheFSH = null; - + + private static final Matrix4f tmpMatrixForInv = new Matrix4f(); + + private static final Vector4f tmpVec4ForTex = new Vector4f(); + + private static FloatBuffer matrixCopyBuffer = null; + + public static void flushCache() { + shaderSourceCacheVSH = null; + shaderSourceCacheFSH = null; + FixedFunctionPipeline pp; + for (int i = 0; i < pipelineStateCache.length; ++i) { + pp = pipelineStateCache[i]; + if (pp != null) { + pp.destroy(); + pipelineStateCache[i] = null; + } + } + for (int i = 0; i < pipelineExtStateCache.length; ++i) { + FixedFunctionPipeline[] ppp = pipelineExtStateCache[i]; + if (ppp != null) { + for (int j = 0; j < ppp.length; ++j) { + FixedFunctionPipeline pppp = ppp[j]; + if (pppp != null) { + pppp.destroy(); + if (extensionProvider != null && pppp.extensionPointer != null) { + extensionProvider.destroyPipeline(pppp.shaderProgram, pppp.stateCoreBits, pppp.stateExtBits, + pppp.extensionPointer); + } + } + } + pipelineExtStateCache[i] = null; + } + } + pipelineListTracker.clear(); + } + + static final int getFragmentState() { + return (GlStateManager.stateTexture[0] ? STATE_ENABLE_TEXTURE2D : 0) + | (GlStateManager.stateTexture[1] ? STATE_ENABLE_LIGHTMAP : 0) + | (GlStateManager.stateAlphaTest ? STATE_ENABLE_ALPHA_TEST : 0) + | ((GlStateManager.stateLighting && GlStateManager.stateMaterial) ? STATE_ENABLE_MC_LIGHTING : 0) + | ((GlStateManager.stateTexture[0] && GlStateManager.stateTexGen) ? STATE_ENABLE_END_PORTAL : 0) | + /* TODO: (GlStateManager.??? ? STATE_ENABLE_ANISOTROPIC_FIX : 0) | */ + ((GlStateManager.stateFog && GlStateManager.stateFogDensity > 0.0f) ? STATE_ENABLE_FOG : 0) + | (GlStateManager.stateEnableShaderBlendColor ? STATE_ENABLE_BLEND_ADD : 0); + } + private static FixedFunctionPipeline getPipelineInstanceCore(int bits) { FixedFunctionPipeline pp = pipelineStateCache[bits]; - if(pp == null) { + if (pp == null) { pipelineStateCache[bits] = pp = makeNewPipeline(bits, 0, false); } return pp; } - + private static FixedFunctionPipeline getPipelineInstanceExt(int coreBits, int extBits) { coreBits &= (15 | extensionProvider.getCoreStateMask(extBits)); FixedFunctionPipeline[] pp = pipelineExtStateCache[coreBits]; - if(pp == null) { - pipelineExtStateCache[coreBits] = pp = new FixedFunctionPipeline[1 << extensionProvider.getExtensionStatesCount()]; + if (pp == null) { + pipelineExtStateCache[coreBits] = pp = new FixedFunctionPipeline[1 << extensionProvider + .getExtensionStatesCount()]; return pp[extBits] = makeNewPipeline(coreBits, extBits, true); - }else { + } else { FixedFunctionPipeline ppp = pp[extBits]; - if(ppp == null) { + if (ppp == null) { pp[extBits] = ppp = makeNewPipeline(coreBits, extBits, true); } return ppp; } } - + + public static void loadExtensionPipeline(IExtPipelineCompiler provider) { + flushCache(); + extensionProvider = provider; + } + private static FixedFunctionPipeline makeNewPipeline(int coreBits, int extBits, boolean enableExt) { String vshSource; String fshSource; - + Object[] extProviderUserPointer = null; - if(enableExt) { + if (enableExt) { extProviderUserPointer = new Object[1]; String[] extSource = extensionProvider.getShaderSource(coreBits, extBits, extProviderUserPointer); vshSource = extSource[0]; fshSource = extSource[1]; - }else { - if(shaderSourceCacheVSH == null) { + } else { + if (shaderSourceCacheVSH == null) { shaderSourceCacheVSH = EagRuntime.getRequiredResourceString(FILENAME_VSH); } vshSource = shaderSourceCacheVSH; - if(shaderSourceCacheFSH == null) { + if (shaderSourceCacheFSH == null) { shaderSourceCacheFSH = EagRuntime.getRequiredResourceString(FILENAME_FSH); } fshSource = shaderSourceCacheFSH; } - + StringBuilder macros = new StringBuilder(); - if((coreBits & STATE_HAS_ATTRIB_TEXTURE) != 0) { + if ((coreBits & STATE_HAS_ATTRIB_TEXTURE) != 0) { macros.append("#define " + MACRO_ATTRIB_TEXTURE + "\n"); } - if((coreBits & STATE_HAS_ATTRIB_COLOR) != 0) { + if ((coreBits & STATE_HAS_ATTRIB_COLOR) != 0) { macros.append("#define " + MACRO_ATTRIB_COLOR + "\n"); } - if((coreBits & STATE_HAS_ATTRIB_NORMAL) != 0) { + if ((coreBits & STATE_HAS_ATTRIB_NORMAL) != 0) { macros.append("#define " + MACRO_ATTRIB_NORMAL + "\n"); } - if((coreBits & STATE_HAS_ATTRIB_LIGHTMAP) != 0) { + if ((coreBits & STATE_HAS_ATTRIB_LIGHTMAP) != 0) { macros.append("#define " + MACRO_ATTRIB_LIGHTMAP + "\n"); } - if((coreBits & STATE_ENABLE_TEXTURE2D) != 0) { + if ((coreBits & STATE_ENABLE_TEXTURE2D) != 0) { macros.append("#define " + MACRO_ENABLE_TEXTURE2D + "\n"); } - if((coreBits & STATE_ENABLE_LIGHTMAP) != 0) { + if ((coreBits & STATE_ENABLE_LIGHTMAP) != 0) { macros.append("#define " + MACRO_ENABLE_LIGHTMAP + "\n"); } - if((coreBits & STATE_ENABLE_ALPHA_TEST) != 0) { + if ((coreBits & STATE_ENABLE_ALPHA_TEST) != 0) { macros.append("#define " + MACRO_ENABLE_ALPHA_TEST + "\n"); } - if((coreBits & STATE_ENABLE_MC_LIGHTING) != 0) { + if ((coreBits & STATE_ENABLE_MC_LIGHTING) != 0) { macros.append("#define " + MACRO_ENABLE_MC_LIGHTING + "\n"); } - if((coreBits & STATE_ENABLE_END_PORTAL) != 0) { + if ((coreBits & STATE_ENABLE_END_PORTAL) != 0) { macros.append("#define " + MACRO_ENABLE_END_PORTAL + "\n"); } - if((coreBits & STATE_ENABLE_ANISOTROPIC_FIX) != 0) { + if ((coreBits & STATE_ENABLE_ANISOTROPIC_FIX) != 0) { macros.append("#define " + MACRO_ENABLE_ANISOTROPIC_FIX + "\n"); } - if((coreBits & STATE_ENABLE_FOG) != 0) { + if ((coreBits & STATE_ENABLE_FOG) != 0) { macros.append("#define " + MACRO_ENABLE_FOG + "\n"); } - if((coreBits & STATE_ENABLE_BLEND_ADD) != 0) { + if ((coreBits & STATE_ENABLE_BLEND_ADD) != 0) { macros.append("#define " + MACRO_ENABLE_BLEND_ADD + "\n"); } macros.append("precision " + PRECISION_INT + " int;\n"); macros.append("precision " + PRECISION_FLOAT + " float;\n"); macros.append("precision " + PRECISION_SAMPLER + " sampler2D;\n\n"); - + IShaderGL vsh = _wglCreateShader(GL_VERTEX_SHADER); - + String macrosStr = macros.toString(); _wglShaderSource(vsh, GLSLHeader.getVertexHeaderCompat(vshSource, macrosStr)); _wglCompileShader(vsh); - - if(_wglGetShaderi(vsh, GL_COMPILE_STATUS) != GL_TRUE) { - LOGGER.error("Failed to compile GL_VERTEX_SHADER for state {} !", (visualizeBits(coreBits) + (enableExt && extBits != 0 ? " ext " + visualizeBits(extBits) : ""))); + + if (_wglGetShaderi(vsh, GL_COMPILE_STATUS) != GL_TRUE) { + LOGGER.error("Failed to compile GL_VERTEX_SHADER for state {} !", + (visualizeBits(coreBits) + (enableExt && extBits != 0 ? " ext " + visualizeBits(extBits) : ""))); String log = _wglGetShaderInfoLog(vsh); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { LOGGER.error("[VERT] {}", lines[i]); } } _wglDeleteShader(vsh); throw new IllegalStateException("Vertex shader could not be compiled!"); } - + IShaderGL fsh = _wglCreateShader(GL_FRAGMENT_SHADER); - + _wglShaderSource(fsh, GLSLHeader.getFragmentHeaderCompat(fshSource, macrosStr)); _wglCompileShader(fsh); - - if(_wglGetShaderi(fsh, GL_COMPILE_STATUS) != GL_TRUE) { - LOGGER.error("Failed to compile GL_FRAGMENT_SHADER for state {} !", (visualizeBits(coreBits) + (enableExt && extBits != 0 ? " ext " + visualizeBits(extBits) : ""))); + + if (_wglGetShaderi(fsh, GL_COMPILE_STATUS) != GL_TRUE) { + LOGGER.error("Failed to compile GL_FRAGMENT_SHADER for state {} !", + (visualizeBits(coreBits) + (enableExt && extBits != 0 ? " ext " + visualizeBits(extBits) : ""))); String log = _wglGetShaderInfoLog(fsh); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { LOGGER.error("[FRAG] {}", lines[i]); } } @@ -320,30 +327,30 @@ public class FixedFunctionPipeline { _wglDeleteShader(vsh); throw new IllegalStateException("Fragment shader could not be compiled!"); } - + IProgramGL prog = _wglCreateProgram(); _wglAttachShader(prog, vsh); _wglAttachShader(prog, fsh); - + FixedFunctionPipeline pp = null; IllegalStateException err = null; try { pp = new FixedFunctionPipeline(coreBits, extBits, prog); - }catch(IllegalStateException t) { + } catch (IllegalStateException t) { err = t; } - + _wglDetachShader(prog, vsh); _wglDetachShader(prog, fsh); _wglDeleteShader(fsh); _wglDeleteShader(vsh); - - if(err != null) { + + if (err != null) { _wglDeleteProgram(prog); throw err; - }else { - if(extProviderUserPointer != null) { + } else { + if (extProviderUserPointer != null) { pp.extensionPointer = extProviderUserPointer; extensionProvider.initializeNewShader(prog, pp.stateCoreBits, pp.stateExtBits, extProviderUserPointer); } @@ -352,22 +359,111 @@ public class FixedFunctionPipeline { } } + static void optimize() { + for (int i = 0, l = pipelineListTracker.size(); i < l; ++i) { + pipelineListTracker.get(i).streamBuffer.optimize(); + } + } + + static FixedFunctionPipeline setupDirect(ByteBuffer buffer, int attrib) { + FixedFunctionPipeline self; + int baseState = attrib | getFragmentState(); + if (GlStateManager.stateUseExtensionPipeline) { + if (extensionProvider != null) { + self = getPipelineInstanceExt(baseState, extensionProvider.getCurrentExtensionStateBits(baseState)); + } else { + throw new IllegalStateException("No extension pipeline is available!"); + } + } else { + self = getPipelineInstanceCore(baseState); + } + + StreamBufferInstance sb = self.streamBuffer.getBuffer(buffer.remaining()); + self.currentVertexArray = sb; + + EaglercraftGPU.bindGLBufferArray(sb.vertexArray); + EaglercraftGPU.bindGLArrayBuffer(sb.vertexBuffer); + + _wglBufferSubData(GL_ARRAY_BUFFER, 0, buffer); + + return self; + } + + static void setupDisplayList(DisplayList list) { + FixedFunctionPipeline self; + int baseState = list.attribs | getFragmentState(); + if (GlStateManager.stateUseExtensionPipeline) { + if (extensionProvider != null) { + self = getPipelineInstanceExt(baseState, extensionProvider.getCurrentExtensionStateBits(baseState)); + } else { + throw new IllegalStateException("No extension pipeline is available!"); + } + } else { + self = getPipelineInstanceCore(baseState); + } + + EaglercraftGPU.bindGLBufferArray(list.vertexArray); + EaglercraftGPU.bindVAOGLArrayBuffer(list.vertexBuffer); + + EaglercraftGPU.enableVertexAttribArray(0); + EaglercraftGPU.vertexAttribPointer(0, VertexFormat.COMPONENT_POSITION_SIZE, + VertexFormat.COMPONENT_POSITION_FORMAT, false, self.attribStride, 0); + + if (self.attribTextureIndex != -1) { + EaglercraftGPU.enableVertexAttribArray(self.attribTextureIndex); + EaglercraftGPU.vertexAttribPointer(self.attribTextureIndex, VertexFormat.COMPONENT_TEX_SIZE, + VertexFormat.COMPONENT_TEX_FORMAT, false, self.attribStride, self.attribTextureOffset); + } + + if (self.attribColorIndex != -1) { + EaglercraftGPU.enableVertexAttribArray(self.attribColorIndex); + EaglercraftGPU.vertexAttribPointer(self.attribColorIndex, VertexFormat.COMPONENT_COLOR_SIZE, + VertexFormat.COMPONENT_COLOR_FORMAT, true, self.attribStride, self.attribColorOffset); + } + + if (self.attribNormalIndex != -1) { + EaglercraftGPU.enableVertexAttribArray(self.attribNormalIndex); + EaglercraftGPU.vertexAttribPointer(self.attribNormalIndex, VertexFormat.COMPONENT_NORMAL_SIZE, + VertexFormat.COMPONENT_NORMAL_FORMAT, true, self.attribStride, self.attribNormalOffset); + } + + if (self.attribLightmapIndex != -1) { + EaglercraftGPU.enableVertexAttribArray(self.attribLightmapIndex); + EaglercraftGPU.vertexAttribPointer(self.attribLightmapIndex, VertexFormat.COMPONENT_LIGHTMAP_SIZE, + VertexFormat.COMPONENT_LIGHTMAP_FORMAT, false, self.attribStride, self.attribLightmapOffset); + } + + } + + static FixedFunctionPipeline setupRenderDisplayList(int attribs) { + int baseState = attribs | getFragmentState(); + if (GlStateManager.stateUseExtensionPipeline) { + if (extensionProvider != null) { + return getPipelineInstanceExt(baseState, extensionProvider.getCurrentExtensionStateBits(baseState)); + } else { + throw new IllegalStateException("No extension pipeline is available!"); + } + } else { + return getPipelineInstanceCore(baseState); + } + } + public static String visualizeBits(int i) { - if(i == 0) { + if (i == 0) { return "0"; } StringBuilder sb = new StringBuilder(); int j = 0, k = 0, l = 0; do { k = i & (1 << j); - if(k > 0) { - if(l++ > 0) { + if (k > 0) { + if (l++ > 0) { sb.append(' '); } sb.append(k); } ++j; - }while(i >= (1 << j)); + } while (i >= (1 << j)); return sb.toString(); } @@ -385,29 +481,29 @@ public class FixedFunctionPipeline { private final boolean stateEnableMCLighting; private final boolean stateEnableEndPortal; private final boolean stateEnableAnisotropicFix; + private final boolean stateEnableFog; private final boolean stateEnableBlendAdd; - private final int attribTextureIndex; private final int attribTextureOffset; private final int attribColorIndex; private final int attribColorOffset; private final int attribNormalIndex; private final int attribNormalOffset; - private final int attribLightmapIndex; - private final int attribLightmapOffset; - - private final int attribStride; + private final int attribLightmapIndex; + + private final int attribLightmapOffset; + + private final int attribStride; private final IProgramGL shaderProgram; - private final IUniformGL stateColorUniform4f; private float stateColorR = -999.0f; private float stateColorG = -999.0f; private float stateColorB = -999.0f; + private float stateColorA = -999.0f; private int stateColorSerial = -1; - private final IUniformGL stateShaderBlendSrcColorUniform4f; private float stateShaderBlendSrcColorR = -999.0f; private float stateShaderBlendSrcColorG = -999.0f; @@ -417,30 +513,30 @@ public class FixedFunctionPipeline { private float stateShaderBlendAddColorR = -999.0f; private float stateShaderBlendAddColorG = -999.0f; private float stateShaderBlendAddColorB = -999.0f; + private float stateShaderBlendAddColorA = -999.0f; private int stateShaderBlendColorSerial = -1; private final IUniformGL stateAlphaTestUniform1f; private float stateAlphaTestRef = -999.0f; - private final IUniformGL stateLightsEnabledUniform1i; private final IUniformGL[] stateLightsVectorsArrayUniform4f = new IUniformGL[4]; private int stateLightsEnabled = -1; + private final Vector4f[] stateLightsVectors = new Vector4f[4]; private int stateLightingSerial = -1; - private final IUniformGL stateLightingAmbientUniform3f; private float stateLightingAmbientR = -999.0f; private float stateLightingAmbientG = -999.0f; + private float stateLightingAmbientB = -999.0f; private int stateLightingAmbientSerial = -1; - private final IUniformGL stateNormalUniform3f; private float stateNormalX = -999.0f; private float stateNormalY = -999.0f; + private float stateNormalZ = -999.0f; private int stateNormalSerial = -1; - // X = Linear or Exp, Y = Density, Z = start, W = end private final IUniformGL stateFogParamUniform4f; private boolean stateFogEXP = false; @@ -451,9 +547,9 @@ public class FixedFunctionPipeline { private float stateFogColorR = -999.0f; private float stateFogColorG = -999.0f; private float stateFogColorB = -999.0f; + private float stateFogColorA = -999.0f; private int stateFogSerial = -1; - private final IUniformGL stateTexGenPlaneUniform4i; private int stateTexGenSPlane = -1; private final IUniformGL stateTexGenSVectorUniform4f; @@ -466,15 +562,13 @@ public class FixedFunctionPipeline { private final Vector4f stateTexGenRVector = new Vector4f(); private int stateTexGenQPlane = -1; private final IUniformGL stateTexGenQVectorUniform4f; + private final Vector4f stateTexGenQVector = new Vector4f(); private int stateTexGenSerial = -1; private final IUniformGL stateModelMatrixUniformMat4f; private int stateModelMatrixSerial = -1; - private static final Matrix4f tmpMatrixForInv = new Matrix4f(); - private static final Vector4f tmpVec4ForTex = new Vector4f(); - private final IUniformGL stateProjectionMatrixUniformMat4f; private int stateProjectionMatrixSerial = -1; @@ -484,7 +578,7 @@ public class FixedFunctionPipeline { private final IUniformGL stateTextureMatrix01UniformMat4f; private final IUniformGL stateTextureMatrix02UniformMat4f; private final int[] stateTextureMatrixSerial = new int[8]; - + private final IUniformGL stateTextureCoords01Uniform2f; private final IUniformGL stateTextureCoords02Uniform2f; private final float[] stateTextureCoordsX = new float[8]; @@ -500,79 +594,78 @@ public class FixedFunctionPipeline { private final StreamBuffer streamBuffer; private StreamBufferInstance currentVertexArray = null; - private static FloatBuffer matrixCopyBuffer = null; - private FixedFunctionPipeline(int bits, int extBits, IProgramGL compiledProg) { shaderProgram = compiledProg; - + stateBits = bits; stateHasAttribTexture = (bits & STATE_HAS_ATTRIB_TEXTURE) != 0; stateHasAttribColor = (bits & STATE_HAS_ATTRIB_COLOR) != 0; stateHasAttribNormal = (bits & STATE_HAS_ATTRIB_NORMAL) != 0; stateHasAttribLightmap = (bits & STATE_HAS_ATTRIB_LIGHTMAP) != 0; - + stateCoreBits = bits; stateExtBits = extBits; - + int index = 0; int stride = 0; - + _wglBindAttribLocation(compiledProg, index, ATTRIB_POSITION); - + stride += VertexFormat.COMPONENT_POSITION_STRIDE; // vec3f - if(stateHasAttribColor) { + if (stateHasAttribColor) { attribColorIndex = ++index; attribColorOffset = stride; _wglBindAttribLocation(compiledProg, index, ATTRIB_COLOR); stride += VertexFormat.COMPONENT_COLOR_STRIDE; // vec4b - }else { + } else { attribColorIndex = -1; attribColorOffset = -1; } - if(stateHasAttribTexture) { + if (stateHasAttribTexture) { attribTextureIndex = ++index; attribTextureOffset = stride; _wglBindAttribLocation(compiledProg, index, ATTRIB_TEXTURE); stride += VertexFormat.COMPONENT_TEX_STRIDE; // vec2f - }else { + } else { attribTextureIndex = -1; attribTextureOffset = -1; } - if(stateHasAttribNormal) { + if (stateHasAttribNormal) { attribNormalIndex = ++index; attribNormalOffset = stride; _wglBindAttribLocation(compiledProg, index, ATTRIB_NORMAL); stride += VertexFormat.COMPONENT_NORMAL_STRIDE; // vec4b - }else { + } else { attribNormalIndex = -1; attribNormalOffset = -1; } - if(stateHasAttribLightmap) { + if (stateHasAttribLightmap) { attribLightmapIndex = ++index; attribLightmapOffset = stride; _wglBindAttribLocation(compiledProg, index, ATTRIB_LIGHTMAP); stride += VertexFormat.COMPONENT_LIGHTMAP_STRIDE; // vec2s - }else { + } else { attribLightmapIndex = -1; attribLightmapOffset = -1; } - + attribStride = stride; - + _wglLinkProgram(compiledProg); - - if(_wglGetProgrami(compiledProg, GL_LINK_STATUS) != GL_TRUE) { - LOGGER.error("Program could not be linked for state {} !", (visualizeBits(bits) + (extensionProvider != null && extBits != 0 ? " ext " + visualizeBits(extBits) : ""))); + + if (_wglGetProgrami(compiledProg, GL_LINK_STATUS) != GL_TRUE) { + LOGGER.error("Program could not be linked for state {} !", (visualizeBits(bits) + + (extensionProvider != null && extBits != 0 ? " ext " + visualizeBits(extBits) : ""))); String log = _wglGetProgramInfoLog(compiledProg); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { LOGGER.error("[LINK] {}", lines[i]); } } throw new IllegalStateException("Program could not be linked!"); } - + streamBuffer = new StreamBuffer(FixedFunctionShader.initialSize, FixedFunctionShader.initialCount, FixedFunctionShader.maxCount, (vertexArray, vertexBuffer) -> { EaglercraftGPU.bindGLBufferArray(vertexArray); @@ -582,25 +675,25 @@ public class FixedFunctionPipeline { EaglercraftGPU.vertexAttribPointer(0, VertexFormat.COMPONENT_POSITION_SIZE, VertexFormat.COMPONENT_POSITION_FORMAT, false, attribStride, 0); - if(attribTextureIndex != -1) { + if (attribTextureIndex != -1) { EaglercraftGPU.enableVertexAttribArray(attribTextureIndex); EaglercraftGPU.vertexAttribPointer(attribTextureIndex, VertexFormat.COMPONENT_TEX_SIZE, VertexFormat.COMPONENT_TEX_FORMAT, false, attribStride, attribTextureOffset); } - - if(attribColorIndex != -1) { + + if (attribColorIndex != -1) { EaglercraftGPU.enableVertexAttribArray(attribColorIndex); EaglercraftGPU.vertexAttribPointer(attribColorIndex, VertexFormat.COMPONENT_COLOR_SIZE, VertexFormat.COMPONENT_COLOR_FORMAT, true, attribStride, attribColorOffset); } - - if(attribNormalIndex != -1) { + + if (attribNormalIndex != -1) { EaglercraftGPU.enableVertexAttribArray(attribNormalIndex); EaglercraftGPU.vertexAttribPointer(attribNormalIndex, VertexFormat.COMPONENT_NORMAL_SIZE, VertexFormat.COMPONENT_NORMAL_FORMAT, true, attribStride, attribNormalOffset); } - - if(attribLightmapIndex != -1) { + + if (attribLightmapIndex != -1) { EaglercraftGPU.enableVertexAttribArray(attribLightmapIndex); EaglercraftGPU.vertexAttribPointer(attribLightmapIndex, VertexFormat.COMPONENT_LIGHTMAP_SIZE, VertexFormat.COMPONENT_LIGHTMAP_FORMAT, false, attribStride, attribLightmapOffset); @@ -615,112 +708,168 @@ public class FixedFunctionPipeline { stateEnableAnisotropicFix = (bits & STATE_ENABLE_ANISOTROPIC_FIX) != 0; stateEnableFog = (bits & STATE_ENABLE_FOG) != 0; stateEnableBlendAdd = (bits & STATE_ENABLE_BLEND_ADD) != 0; - - for(int i = 0; i < stateLightsVectors.length; ++i) { + + for (int i = 0; i < stateLightsVectors.length; ++i) { stateLightsVectors[i] = new Vector4f(-999.0f, -999.0f, -999.0f, 0.0f); } - - for(int i = 0; i < stateTextureMatrixSerial.length; ++i) { + + for (int i = 0; i < stateTextureMatrixSerial.length; ++i) { stateTextureMatrixSerial[i] = -1; } - stateColorUniform4f = _wglGetUniformLocation(compiledProg, - UNIFORM_COLOR_NAME); - - stateAlphaTestUniform1f = stateEnableAlphaTest ? _wglGetUniformLocation(compiledProg, - UNIFORM_ALPHA_TEST_NAME) : null; - - stateLightsEnabledUniform1i = stateEnableMCLighting ? _wglGetUniformLocation(compiledProg, - UNIFORM_LIGHTS_ENABLED_NAME) : null; - - if(stateEnableMCLighting) { - for(int i = 0; i < stateLightsVectorsArrayUniform4f.length; ++i) { - stateLightsVectorsArrayUniform4f[i] =_wglGetUniformLocation(compiledProg, + stateColorUniform4f = _wglGetUniformLocation(compiledProg, UNIFORM_COLOR_NAME); + + stateAlphaTestUniform1f = stateEnableAlphaTest ? _wglGetUniformLocation(compiledProg, UNIFORM_ALPHA_TEST_NAME) + : null; + + stateLightsEnabledUniform1i = stateEnableMCLighting + ? _wglGetUniformLocation(compiledProg, UNIFORM_LIGHTS_ENABLED_NAME) + : null; + + if (stateEnableMCLighting) { + for (int i = 0; i < stateLightsVectorsArrayUniform4f.length; ++i) { + stateLightsVectorsArrayUniform4f[i] = _wglGetUniformLocation(compiledProg, UNIFORM_LIGHTS_VECTORS_NAME + "[" + i + "]"); } } - - stateLightingAmbientUniform3f = stateEnableMCLighting ? _wglGetUniformLocation(compiledProg, - UNIFORM_LIGHTS_AMBIENT_NAME) : null; - - stateNormalUniform3f = (!stateHasAttribNormal && stateEnableMCLighting) ? _wglGetUniformLocation(compiledProg, - UNIFORM_CONSTANT_NORMAL_NAME) : null; - - stateFogParamUniform4f = stateEnableFog ? _wglGetUniformLocation(compiledProg, - UNIFORM_FOG_PARAM_NAME) : null; - - stateFogColorUniform4f = stateEnableFog ? _wglGetUniformLocation(compiledProg, - UNIFORM_FOG_COLOR_NAME) : null; - - stateTexGenPlaneUniform4i = stateEnableEndPortal ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEX_GEN_PLANE_NAME) : null; - - stateTexGenSVectorUniform4f = stateEnableEndPortal ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEX_GEN_S_NAME) : null; - - stateTexGenTVectorUniform4f = stateEnableEndPortal ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEX_GEN_T_NAME) : null; - - stateTexGenRVectorUniform4f = stateEnableEndPortal ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEX_GEN_R_NAME) : null; - - stateTexGenQVectorUniform4f = stateEnableEndPortal ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEX_GEN_Q_NAME) : null; - - stateModelMatrixUniformMat4f = _wglGetUniformLocation(compiledProg, - UNIFORM_MODEL_MATRIX_NAME); - - stateProjectionMatrixUniformMat4f = _wglGetUniformLocation(compiledProg, - UNIFORM_PROJECTION_MATRIX_NAME); - + + stateLightingAmbientUniform3f = stateEnableMCLighting + ? _wglGetUniformLocation(compiledProg, UNIFORM_LIGHTS_AMBIENT_NAME) + : null; + + stateNormalUniform3f = (!stateHasAttribNormal && stateEnableMCLighting) + ? _wglGetUniformLocation(compiledProg, UNIFORM_CONSTANT_NORMAL_NAME) + : null; + + stateFogParamUniform4f = stateEnableFog ? _wglGetUniformLocation(compiledProg, UNIFORM_FOG_PARAM_NAME) : null; + + stateFogColorUniform4f = stateEnableFog ? _wglGetUniformLocation(compiledProg, UNIFORM_FOG_COLOR_NAME) : null; + + stateTexGenPlaneUniform4i = stateEnableEndPortal + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEX_GEN_PLANE_NAME) + : null; + + stateTexGenSVectorUniform4f = stateEnableEndPortal + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEX_GEN_S_NAME) + : null; + + stateTexGenTVectorUniform4f = stateEnableEndPortal + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEX_GEN_T_NAME) + : null; + + stateTexGenRVectorUniform4f = stateEnableEndPortal + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEX_GEN_R_NAME) + : null; + + stateTexGenQVectorUniform4f = stateEnableEndPortal + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEX_GEN_Q_NAME) + : null; + + stateModelMatrixUniformMat4f = _wglGetUniformLocation(compiledProg, UNIFORM_MODEL_MATRIX_NAME); + + stateProjectionMatrixUniformMat4f = _wglGetUniformLocation(compiledProg, UNIFORM_PROJECTION_MATRIX_NAME); + stateModelProjectionMatrixUniformMat4f = _wglGetUniformLocation(compiledProg, UNIFORM_MODEL_PROJECTION_MATRIX_NAME); - - stateTextureMatrix01UniformMat4f = (stateEnableEndPortal || stateHasAttribTexture) ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEXTURE_MATRIX_01_NAME) : null; - - stateTextureMatrix02UniformMat4f = stateHasAttribLightmap ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEXTURE_MATRIX_02_NAME) : null; - - stateTextureCoords01Uniform2f = (!stateHasAttribTexture && stateEnableTexture2D) ? _wglGetUniformLocation( - compiledProg, UNIFORM_TEXTURE_COORDS_01_NAME) : null; - - stateTextureCoords02Uniform2f = (!stateHasAttribLightmap && stateEnableLightmap) ? _wglGetUniformLocation( - compiledProg, UNIFORM_TEXTURE_COORDS_02_NAME) : null; - - stateAnisotropicFix2f = stateEnableAnisotropicFix ? _wglGetUniformLocation(compiledProg, - UNIFORM_TEXTURE_ANISOTROPIC_FIX) : null; - - stateShaderBlendSrcColorUniform4f = stateEnableBlendAdd ? _wglGetUniformLocation(compiledProg, - UNIFORM_BLEND_SRC_COLOR_NAME) : null; - - stateShaderBlendAddColorUniform4f = stateEnableBlendAdd ? _wglGetUniformLocation(compiledProg, - UNIFORM_BLEND_ADD_COLOR_NAME) : null; - - if(stateEnableTexture2D) { + + stateTextureMatrix01UniformMat4f = (stateEnableEndPortal || stateHasAttribTexture) + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_MATRIX_01_NAME) + : null; + + stateTextureMatrix02UniformMat4f = stateHasAttribLightmap + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_MATRIX_02_NAME) + : null; + + stateTextureCoords01Uniform2f = (!stateHasAttribTexture && stateEnableTexture2D) + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_COORDS_01_NAME) + : null; + + stateTextureCoords02Uniform2f = (!stateHasAttribLightmap && stateEnableLightmap) + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_COORDS_02_NAME) + : null; + + stateAnisotropicFix2f = stateEnableAnisotropicFix + ? _wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_ANISOTROPIC_FIX) + : null; + + stateShaderBlendSrcColorUniform4f = stateEnableBlendAdd + ? _wglGetUniformLocation(compiledProg, UNIFORM_BLEND_SRC_COLOR_NAME) + : null; + + stateShaderBlendAddColorUniform4f = stateEnableBlendAdd + ? _wglGetUniformLocation(compiledProg, UNIFORM_BLEND_ADD_COLOR_NAME) + : null; + + if (stateEnableTexture2D) { EaglercraftGPU.bindGLShaderProgram(compiledProg); _wglUniform1i(_wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_UNIT_01_NAME), 0); } - - if(stateEnableLightmap) { + + if (stateEnableLightmap) { EaglercraftGPU.bindGLShaderProgram(compiledProg); _wglUniform1i(_wglGetUniformLocation(compiledProg, UNIFORM_TEXTURE_UNIT_02_NAME), 1); } } - - public FixedFunctionPipeline update() { - + + public void destroy() { + PlatformOpenGL._wglDeleteProgram(shaderProgram); + streamBuffer.destroy(); + } + + void drawArrays(int mode, int offset, int count) { EaglercraftGPU.bindGLShaderProgram(shaderProgram); - + EaglercraftGPU.doDrawArrays(mode, offset, count); + } + + void drawDirectArrays(int mode, int offset, int count) { + EaglercraftGPU.bindGLShaderProgram(shaderProgram); + if (mode == GL_QUADS) { + StreamBufferInstance sb = currentVertexArray; + if (count > 0xFFFF) { + if (!sb.bindQuad32) { + sb.bindQuad16 = false; + sb.bindQuad32 = true; + EaglercraftGPU.attachQuad32EmulationBuffer(count, true); + } else { + EaglercraftGPU.attachQuad32EmulationBuffer(count, false); + } + EaglercraftGPU.doDrawElements(GL_TRIANGLES, count + (count >> 1), GL_UNSIGNED_INT, 0); + } else { + if (!sb.bindQuad16) { + sb.bindQuad16 = true; + sb.bindQuad32 = false; + EaglercraftGPU.attachQuad16EmulationBuffer(count, true); + } else { + EaglercraftGPU.attachQuad16EmulationBuffer(count, false); + } + EaglercraftGPU.doDrawElements(GL_TRIANGLES, count + (count >> 1), GL_UNSIGNED_SHORT, 0); + } + } else { + EaglercraftGPU.doDrawArrays(mode, offset, count); + } + } + + void drawElements(int mode, int count, int type, int offset) { + EaglercraftGPU.bindGLShaderProgram(shaderProgram); + EaglercraftGPU.doDrawElements(mode, count, type, offset); + } + + public IBufferArrayGL getDirectModeBufferArray() { + return currentVertexArray.vertexArray; + } + + public FixedFunctionPipeline update() { + + EaglercraftGPU.bindGLShaderProgram(shaderProgram); + int serial = GlStateManager.stateColorSerial; - if(stateColorSerial != serial) { + if (stateColorSerial != serial) { stateColorSerial = serial; float r = GlStateManager.stateColorR; float g = GlStateManager.stateColorG; float b = GlStateManager.stateColorB; float a = GlStateManager.stateColorA; - if(stateColorR != r || stateColorG != g || - stateColorB != b || stateColorA != a) { + if (stateColorR != r || stateColorG != g || stateColorB != b || stateColorA != a) { _wglUniform4f(stateColorUniform4f, r, g, b, a); stateColorR = r; stateColorG = g; @@ -728,68 +877,69 @@ public class FixedFunctionPipeline { stateColorA = a; } } - - if(matrixCopyBuffer == null) { + + if (matrixCopyBuffer == null) { matrixCopyBuffer = PlatformRuntime.allocateFloatBuffer(16); } - + int ptr; - if(stateModelProjectionMatrixUniformMat4f == null) { + if (stateModelProjectionMatrixUniformMat4f == null) { ptr = GlStateManager.modelMatrixStackPointer; serial = GlStateManager.modelMatrixStackAccessSerial[ptr]; - if(stateModelMatrixSerial != serial) { + if (stateModelMatrixSerial != serial) { stateModelMatrixSerial = serial; matrixCopyBuffer.clear(); GlStateManager.modelMatrixStack[ptr].store(matrixCopyBuffer); matrixCopyBuffer.flip(); _wglUniformMatrix4fv(stateModelMatrixUniformMat4f, false, matrixCopyBuffer); } - + ptr = GlStateManager.projectionMatrixStackPointer; serial = GlStateManager.projectionMatrixStackAccessSerial[ptr]; - if(stateProjectionMatrixSerial != serial) { + if (stateProjectionMatrixSerial != serial) { stateProjectionMatrixSerial = serial; matrixCopyBuffer.clear(); GlStateManager.projectionMatrixStack[ptr].store(matrixCopyBuffer); matrixCopyBuffer.flip(); _wglUniformMatrix4fv(stateProjectionMatrixUniformMat4f, false, matrixCopyBuffer); } - }else { + } else { ptr = GlStateManager.modelMatrixStackPointer; serial = GlStateManager.modelMatrixStackAccessSerial[ptr]; int ptr2 = GlStateManager.projectionMatrixStackPointer; int serial2 = GlStateManager.projectionMatrixStackAccessSerial[ptr2]; boolean b = stateModelMatrixSerial != serial; - if(b || stateProjectionMatrixSerial != serial2) { + if (b || stateProjectionMatrixSerial != serial2) { stateModelMatrixSerial = serial; stateProjectionMatrixSerial = serial2; - if(b && stateModelMatrixUniformMat4f != null) { + if (b && stateModelMatrixUniformMat4f != null) { matrixCopyBuffer.clear(); GlStateManager.modelMatrixStack[ptr].store(matrixCopyBuffer); matrixCopyBuffer.flip(); _wglUniformMatrix4fv(stateModelMatrixUniformMat4f, false, matrixCopyBuffer); } - Matrix4f.mul(GlStateManager.projectionMatrixStack[ptr2], GlStateManager.modelMatrixStack[ptr], tmpMatrixForInv); + Matrix4f.mul(GlStateManager.projectionMatrixStack[ptr2], GlStateManager.modelMatrixStack[ptr], + tmpMatrixForInv); matrixCopyBuffer.clear(); tmpMatrixForInv.store(matrixCopyBuffer); matrixCopyBuffer.flip(); _wglUniformMatrix4fv(stateModelProjectionMatrixUniformMat4f, false, matrixCopyBuffer); } } - - if(stateEnableAlphaTest) { + + if (stateEnableAlphaTest) { float v = GlStateManager.stateAlphaTestRef; - if(stateAlphaTestRef != v) { + if (stateAlphaTestRef != v) { stateAlphaTestRef = v; _wglUniform1f(stateAlphaTestUniform1f, v); } } - - if(stateEnableTexture2D) { + + if (stateEnableTexture2D) { ptr = GlStateManager.textureMatrixStackPointer[0]; serial = GlStateManager.textureMatrixStackAccessSerial[0][ptr]; - if(stateHasAttribTexture || stateEnableEndPortal) { - if(stateTextureMatrixSerial[0] != serial) { + if (stateHasAttribTexture || stateEnableEndPortal) { + if (stateTextureMatrixSerial[0] != serial) { stateTextureMatrixSerial[0] = serial; matrixCopyBuffer.clear(); GlStateManager.textureMatrixStack[0][ptr].store(matrixCopyBuffer); @@ -797,9 +947,9 @@ public class FixedFunctionPipeline { _wglUniformMatrix4fv(stateTextureMatrix01UniformMat4f, false, matrixCopyBuffer); } } - if(!stateHasAttribTexture && !stateEnableEndPortal) { + if (!stateHasAttribTexture && !stateEnableEndPortal) { int serial2 = GlStateManager.textureCoordsAccessSerial[0]; - if(stateTextureCoordsAccessSerial[0] != serial2 || stateTextureCoordsMatrixSerial[0] != serial) { + if (stateTextureCoordsAccessSerial[0] != serial2 || stateTextureCoordsMatrixSerial[0] != serial) { stateTextureCoordsAccessSerial[0] = serial2; stateTextureCoordsMatrixSerial[0] = serial; tmpVec4ForTex.x = GlStateManager.textureCoordsX[0]; @@ -809,7 +959,7 @@ public class FixedFunctionPipeline { Matrix4f.transform(GlStateManager.textureMatrixStack[0][ptr], tmpVec4ForTex, tmpVec4ForTex); float x = tmpVec4ForTex.x / tmpVec4ForTex.w; float y = tmpVec4ForTex.y / tmpVec4ForTex.w; - if(x != stateTextureCoordsX[0] || y != stateTextureCoordsY[0]) { + if (x != stateTextureCoordsX[0] || y != stateTextureCoordsY[0]) { stateTextureCoordsX[0] = x; stateTextureCoordsY[0] = y; _wglUniform2f(stateTextureCoords01Uniform2f, x, y); @@ -817,13 +967,13 @@ public class FixedFunctionPipeline { } } } - - if(stateEnableLightmap) { + + if (stateEnableLightmap) { ptr = GlStateManager.textureMatrixStackPointer[1]; serial = GlStateManager.textureMatrixStackAccessSerial[1][ptr]; - if(!stateHasAttribLightmap) { + if (!stateHasAttribLightmap) { int serial2 = GlStateManager.textureCoordsAccessSerial[1]; - if(stateTextureCoordsAccessSerial[1] != serial2 || stateTextureCoordsMatrixSerial[1] != serial) { + if (stateTextureCoordsAccessSerial[1] != serial2 || stateTextureCoordsMatrixSerial[1] != serial) { stateTextureCoordsAccessSerial[1] = serial2; stateTextureCoordsMatrixSerial[1] = serial; tmpVec4ForTex.x = GlStateManager.textureCoordsX[1]; @@ -833,14 +983,14 @@ public class FixedFunctionPipeline { Matrix4f.transform(GlStateManager.textureMatrixStack[1][ptr], tmpVec4ForTex, tmpVec4ForTex); float x = tmpVec4ForTex.x / tmpVec4ForTex.w; float y = tmpVec4ForTex.y / tmpVec4ForTex.w; - if(x != stateTextureCoordsX[1] || y != stateTextureCoordsY[1]) { + if (x != stateTextureCoordsX[1] || y != stateTextureCoordsY[1]) { stateTextureCoordsX[1] = x; stateTextureCoordsY[1] = y; _wglUniform2f(stateTextureCoords02Uniform2f, x, y); } } - }else { - if(stateTextureMatrixSerial[1] != serial) { + } else { + if (stateTextureMatrixSerial[1] != serial) { stateTextureMatrixSerial[1] = serial; matrixCopyBuffer.clear(); GlStateManager.textureMatrixStack[1][ptr].store(matrixCopyBuffer); @@ -849,51 +999,50 @@ public class FixedFunctionPipeline { } } } - - if(stateEnableMCLighting) { + + if (stateEnableMCLighting) { ptr = GlStateManager.stateLightsStackPointer; serial = GlStateManager.stateLightingSerial[ptr]; - if(stateLightingSerial != serial) { + if (stateLightingSerial != serial) { stateLightingSerial = serial; boolean[] en = GlStateManager.stateLightsEnabled[ptr]; int lightsCounter = 0; - for(int i = 0; i < en.length; ++i) { - if(en[i]) { + for (int i = 0; i < en.length; ++i) { + if (en[i]) { Vector4f lightDirOld = stateLightsVectors[lightsCounter]; Vector4f lightDirNew = GlStateManager.stateLightsStack[ptr][i]; float x = lightDirNew.x; float y = lightDirNew.y; float z = lightDirNew.z; float w = lightDirNew.w; - if(lightDirOld.x != x || lightDirOld.y != y || lightDirOld.z != z || lightDirOld.w != w) { + if (lightDirOld.x != x || lightDirOld.y != y || lightDirOld.z != z || lightDirOld.w != w) { lightDirOld.x = x; lightDirOld.y = y; lightDirOld.z = z; lightDirOld.w = w; _wglUniform4f(stateLightsVectorsArrayUniform4f[lightsCounter], x, y, z, w); } - if(++lightsCounter >= stateLightsVectors.length) { + if (++lightsCounter >= stateLightsVectors.length) { break; } } } - - if(stateLightsEnabled != lightsCounter) { + + if (stateLightsEnabled != lightsCounter) { stateLightsEnabled = lightsCounter; _wglUniform1i(stateLightsEnabledUniform1i, lightsCounter); } - + } - + serial = GlStateManager.stateLightingAmbientSerial; - if(stateLightingAmbientSerial != serial) { + if (stateLightingAmbientSerial != serial) { stateLightingAmbientSerial = serial; float r = GlStateManager.stateLightingAmbientR; float g = GlStateManager.stateLightingAmbientG; float b = GlStateManager.stateLightingAmbientB; - if(stateLightingAmbientR != r || stateLightingAmbientG != g || - stateLightingAmbientB != b) { + if (stateLightingAmbientR != r || stateLightingAmbientG != g || stateLightingAmbientB != b) { stateLightingAmbientR = r; stateLightingAmbientG = g; stateLightingAmbientB = b; @@ -901,18 +1050,20 @@ public class FixedFunctionPipeline { } } } - - if(stateEnableMCLighting || DynamicLightsStateManager.isInDynamicLightsPass()) { - if(!stateHasAttribNormal) { + + if (stateEnableMCLighting || DynamicLightsStateManager.isInDynamicLightsPass()) { + if (!stateHasAttribNormal) { serial = GlStateManager.stateNormalSerial; - if(stateNormalSerial != serial) { + if (stateNormalSerial != serial) { stateNormalSerial = serial; float x = GlStateManager.stateNormalX; float y = GlStateManager.stateNormalY; float z = GlStateManager.stateNormalZ; float c = 1.0f / MathHelper.sqrt_float(x * x + y * y + z * z); - x *= c; y *= c; z *= c; - if(stateNormalX != x || stateNormalY != y || stateNormalZ != z) { + x *= c; + y *= c; + z *= c; + if (stateNormalX != x || stateNormalY != y || stateNormalZ != z) { stateNormalX = x; stateNormalY = y; stateNormalZ = z; @@ -921,17 +1072,17 @@ public class FixedFunctionPipeline { } } } - - if(stateEnableFog) { + + if (stateEnableFog) { serial = GlStateManager.stateFogSerial; - if(stateFogSerial != serial) { + if (stateFogSerial != serial) { stateFogSerial = serial; boolean fogEXP = GlStateManager.stateFogEXP; float fogDensity = GlStateManager.stateFogDensity; float fogStart = GlStateManager.stateFogStart; float fogEnd = GlStateManager.stateFogEnd; - if(stateFogEXP != fogEXP || stateFogDensity != fogDensity || - stateFogStart != fogStart || stateFogEnd != fogEnd) { + if (stateFogEXP != fogEXP || stateFogDensity != fogDensity || stateFogStart != fogStart + || stateFogEnd != fogEnd) { stateFogEXP = fogEXP; stateFogDensity = fogDensity; stateFogStart = fogStart; @@ -942,8 +1093,7 @@ public class FixedFunctionPipeline { float g = GlStateManager.stateFogColorG; float b = GlStateManager.stateFogColorB; float a = GlStateManager.stateFogColorA; - if(stateFogColorR != r || stateFogColorG != g || - stateFogColorB != b || stateFogColorA != a) { + if (stateFogColorR != r || stateFogColorG != g || stateFogColorB != b || stateFogColorA != a) { stateFogColorR = r; stateFogColorG = g; stateFogColorB = b; @@ -952,31 +1102,31 @@ public class FixedFunctionPipeline { } } } - - if(stateEnableAnisotropicFix) { + + if (stateEnableAnisotropicFix) { serial = GlStateManager.stateAnisotropicFixSerial; - if(stateAnisotropicFixSerial != serial) { + if (stateAnisotropicFixSerial != serial) { stateAnisotropicFixSerial = serial; float w = GlStateManager.stateAnisotropicFixW; float h = GlStateManager.stateAnisotropicFixH; - if(stateAnisotropicFixW != w || stateAnisotropicFixH != h) { + if (stateAnisotropicFixW != w || stateAnisotropicFixH != h) { stateAnisotropicFixW = w; stateAnisotropicFixH = h; _wglUniform2f(stateAnisotropicFix2f, w, h); } } } - - if(stateEnableEndPortal) { + + if (stateEnableEndPortal) { serial = GlStateManager.stateTexGenSerial; - if(stateTexGenSerial != serial) { + if (stateTexGenSerial != serial) { stateTexGenSerial = serial; int planeS = GlStateManager.TexGen.S.plane; int planeT = GlStateManager.TexGen.T.plane; int planeR = GlStateManager.TexGen.R.plane; int planeQ = GlStateManager.TexGen.Q.plane; - if(stateTexGenSPlane != planeS || stateTexGenTPlane != planeT || - stateTexGenRPlane != planeR || stateTexGenQPlane != planeQ) { + if (stateTexGenSPlane != planeS || stateTexGenTPlane != planeT || stateTexGenRPlane != planeR + || stateTexGenQPlane != planeQ) { stateTexGenSPlane = planeS; stateTexGenTPlane = planeT; stateTexGenRPlane = planeR; @@ -986,8 +1136,8 @@ public class FixedFunctionPipeline { planeQ == GL_EYE_PLANE ? 1 : 0); } Vector4f vecS = GlStateManager.TexGen.S.vector; - if (stateTexGenSVector.x != vecS.x || stateTexGenSVector.y != vecS.y || - stateTexGenSVector.z != vecS.z || stateTexGenSVector.w != vecS.w) { + if (stateTexGenSVector.x != vecS.x || stateTexGenSVector.y != vecS.y || stateTexGenSVector.z != vecS.z + || stateTexGenSVector.w != vecS.w) { stateTexGenSVector.x = vecS.x; stateTexGenSVector.y = vecS.y; stateTexGenSVector.z = vecS.z; @@ -995,8 +1145,8 @@ public class FixedFunctionPipeline { _wglUniform4f(stateTexGenSVectorUniform4f, vecS.x, vecS.y, vecS.z, vecS.w); } Vector4f vecT = GlStateManager.TexGen.T.vector; - if (stateTexGenTVector.x != vecT.x || stateTexGenTVector.y != vecT.y || - stateTexGenTVector.z != vecT.z || stateTexGenTVector.w != vecT.w) { + if (stateTexGenTVector.x != vecT.x || stateTexGenTVector.y != vecT.y || stateTexGenTVector.z != vecT.z + || stateTexGenTVector.w != vecT.w) { stateTexGenTVector.x = vecT.x; stateTexGenTVector.y = vecT.y; stateTexGenTVector.z = vecT.z; @@ -1004,8 +1154,8 @@ public class FixedFunctionPipeline { _wglUniform4f(stateTexGenTVectorUniform4f, vecT.x, vecT.y, vecT.z, vecT.w); } Vector4f vecR = GlStateManager.TexGen.R.vector; - if (stateTexGenRVector.x != vecR.x || stateTexGenRVector.y != vecR.y || - stateTexGenRVector.z != vecR.z || stateTexGenRVector.w != vecR.w) { + if (stateTexGenRVector.x != vecR.x || stateTexGenRVector.y != vecR.y || stateTexGenRVector.z != vecR.z + || stateTexGenRVector.w != vecR.w) { stateTexGenRVector.x = vecR.x; stateTexGenRVector.y = vecR.y; stateTexGenRVector.z = vecR.z; @@ -1013,8 +1163,8 @@ public class FixedFunctionPipeline { _wglUniform4f(stateTexGenRVectorUniform4f, vecR.x, vecR.y, vecR.z, vecR.w); } Vector4f vecQ = GlStateManager.TexGen.Q.vector; - if (stateTexGenQVector.x != vecQ.x || stateTexGenQVector.y != vecQ.y || - stateTexGenQVector.z != vecQ.z || stateTexGenQVector.w != vecQ.w) { + if (stateTexGenQVector.x != vecQ.x || stateTexGenQVector.y != vecQ.y || stateTexGenQVector.z != vecQ.z + || stateTexGenQVector.w != vecQ.w) { stateTexGenQVector.x = vecQ.x; stateTexGenQVector.y = vecQ.y; stateTexGenQVector.z = vecQ.z; @@ -1023,17 +1173,17 @@ public class FixedFunctionPipeline { } } } - - if(stateEnableBlendAdd) { + + if (stateEnableBlendAdd) { serial = GlStateManager.stateShaderBlendColorSerial; - if(stateShaderBlendColorSerial != serial) { + if (stateShaderBlendColorSerial != serial) { stateShaderBlendColorSerial = serial; float r = GlStateManager.stateShaderBlendSrcColorR; float g = GlStateManager.stateShaderBlendSrcColorG; float b = GlStateManager.stateShaderBlendSrcColorB; float a = GlStateManager.stateShaderBlendSrcColorA; - if(stateShaderBlendSrcColorR != r || stateShaderBlendSrcColorG != g || - stateShaderBlendSrcColorB != b || stateShaderBlendSrcColorA != a) { + if (stateShaderBlendSrcColorR != r || stateShaderBlendSrcColorG != g || stateShaderBlendSrcColorB != b + || stateShaderBlendSrcColorA != a) { _wglUniform4f(stateShaderBlendSrcColorUniform4f, r, g, b, a); stateShaderBlendSrcColorR = r; stateShaderBlendSrcColorG = g; @@ -1044,8 +1194,8 @@ public class FixedFunctionPipeline { g = GlStateManager.stateShaderBlendAddColorG; b = GlStateManager.stateShaderBlendAddColorB; a = GlStateManager.stateShaderBlendAddColorA; - if(stateShaderBlendAddColorR != r || stateShaderBlendAddColorG != g || - stateShaderBlendAddColorB != b || stateShaderBlendAddColorA != a) { + if (stateShaderBlendAddColorR != r || stateShaderBlendAddColorG != g || stateShaderBlendAddColorB != b + || stateShaderBlendAddColorA != a) { _wglUniform4f(stateShaderBlendAddColorUniform4f, r, g, b, a); stateShaderBlendAddColorR = r; stateShaderBlendAddColorG = g; @@ -1054,55 +1204,11 @@ public class FixedFunctionPipeline { } } } - - if(extensionProvider != null && extensionPointer != null) { + + if (extensionProvider != null && extensionPointer != null) { extensionProvider.updatePipeline(shaderProgram, stateCoreBits, stateExtBits, extensionPointer); } - + return this; } - - static void optimize() { - for(int i = 0, l = pipelineListTracker.size(); i < l; ++i) { - pipelineListTracker.get(i).streamBuffer.optimize(); - } - } - - public static void flushCache() { - shaderSourceCacheVSH = null; - shaderSourceCacheFSH = null; - FixedFunctionPipeline pp; - for(int i = 0; i < pipelineStateCache.length; ++i) { - pp = pipelineStateCache[i]; - if(pp != null) { - pp.destroy(); - pipelineStateCache[i] = null; - } - } - for(int i = 0; i < pipelineExtStateCache.length; ++i) { - FixedFunctionPipeline[] ppp = pipelineExtStateCache[i]; - if(ppp != null) { - for(int j = 0; j < ppp.length; ++j) { - FixedFunctionPipeline pppp = ppp[j]; - if(pppp != null) { - pppp.destroy(); - if(extensionProvider != null && pppp.extensionPointer != null) { - extensionProvider.destroyPipeline(pppp.shaderProgram, pppp.stateCoreBits, pppp.stateExtBits, pppp.extensionPointer); - } - } - } - pipelineExtStateCache[i] = null; - } - } - pipelineListTracker.clear(); - } - - public void destroy() { - PlatformOpenGL._wglDeleteProgram(shaderProgram); - streamBuffer.destroy(); - } - - public IBufferArrayGL getDirectModeBufferArray() { - return currentVertexArray.vertexArray; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionShader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionShader.java index 392ad203..2a57d452 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionShader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/FixedFunctionShader.java @@ -3,45 +3,21 @@ package net.lax1dude.eaglercraft.v1_8.opengl; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class FixedFunctionShader { - public static final int initialSize = 0x8000; - public static final int initialCount = 3; - public static final int maxCount = 8; - - public class FixedFunctionState { - - public static final int fixedFunctionStatesCount = 12; - public static final int fixedFunctionStatesBits = (1 << 12) - 1; - public static final int extentionStateBits = fixedFunctionStatesBits ^ 0xFFFFFFFF; - - public static final int STATE_HAS_ATTRIB_TEXTURE = 1; - public static final int STATE_HAS_ATTRIB_COLOR = 2; - public static final int STATE_HAS_ATTRIB_NORMAL = 4; - public static final int STATE_HAS_ATTRIB_LIGHTMAP = 8; - public static final int STATE_ENABLE_TEXTURE2D = 16; - public static final int STATE_ENABLE_LIGHTMAP = 32; - public static final int STATE_ENABLE_ALPHA_TEST = 64; - public static final int STATE_ENABLE_MC_LIGHTING = 128; - public static final int STATE_ENABLE_END_PORTAL = 256; - public static final int STATE_ENABLE_ANISOTROPIC_FIX = 512; - public static final int STATE_ENABLE_FOG = 1024; - public static final int STATE_ENABLE_BLEND_ADD = 2048; - - } - public class FixedFunctionConstants { public static final String FILENAME_VSH = "/assets/eagler/glsl/core.vsh"; @@ -50,12 +26,12 @@ public class FixedFunctionShader { public static final String PRECISION_INT = "lowp"; public static final String PRECISION_FLOAT = "highp"; public static final String PRECISION_SAMPLER = "mediump"; - + public static final String MACRO_ATTRIB_TEXTURE = "COMPILE_TEXTURE_ATTRIB"; public static final String MACRO_ATTRIB_COLOR = "COMPILE_COLOR_ATTRIB"; public static final String MACRO_ATTRIB_NORMAL = "COMPILE_NORMAL_ATTRIB"; public static final String MACRO_ATTRIB_LIGHTMAP = "COMPILE_LIGHTMAP_ATTRIB"; - + public static final String MACRO_ENABLE_TEXTURE2D = "COMPILE_ENABLE_TEXTURE2D"; public static final String MACRO_ENABLE_LIGHTMAP = "COMPILE_ENABLE_LIGHTMAP"; public static final String MACRO_ENABLE_ALPHA_TEST = "COMPILE_ENABLE_ALPHA_TEST"; @@ -97,9 +73,36 @@ public class FixedFunctionShader { public static final String UNIFORM_TEXTURE_UNIT_01_NAME = "u_samplerTexture"; public static final String UNIFORM_TEXTURE_UNIT_02_NAME = "u_samplerLightmap"; - + public static final String OUTPUT_COLOR = "output4f"; } + public class FixedFunctionState { + + public static final int fixedFunctionStatesCount = 12; + public static final int fixedFunctionStatesBits = (1 << 12) - 1; + public static final int extentionStateBits = fixedFunctionStatesBits ^ 0xFFFFFFFF; + + public static final int STATE_HAS_ATTRIB_TEXTURE = 1; + public static final int STATE_HAS_ATTRIB_COLOR = 2; + public static final int STATE_HAS_ATTRIB_NORMAL = 4; + public static final int STATE_HAS_ATTRIB_LIGHTMAP = 8; + public static final int STATE_ENABLE_TEXTURE2D = 16; + public static final int STATE_ENABLE_LIGHTMAP = 32; + public static final int STATE_ENABLE_ALPHA_TEST = 64; + public static final int STATE_ENABLE_MC_LIGHTING = 128; + public static final int STATE_ENABLE_END_PORTAL = 256; + public static final int STATE_ENABLE_ANISOTROPIC_FIX = 512; + public static final int STATE_ENABLE_FOG = 1024; + public static final int STATE_ENABLE_BLEND_ADD = 2048; + + } + + public static final int initialSize = 0x8000; + + public static final int initialCount = 3; + + public static final int maxCount = 8; + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GLSLHeader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GLSLHeader.java index 5e93f199..8e3e5b91 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GLSLHeader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GLSLHeader.java @@ -6,14 +6,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,75 +26,82 @@ public class GLSLHeader { private static String header = null; private static String gles2CompatFile = null; + static void destroy() { + header = null; + } + + public static String getFragmentHeader(String shaderSrc) { + if (header == null) + throw new IllegalStateException(); + return header + "#define EAGLER_IS_FRAGMENT_SHADER\n" + shaderSrc; + } + + public static String getFragmentHeaderCompat(String shaderSrc, String precisions) { + if (header == null || gles2CompatFile == null) + throw new IllegalStateException(); + return header + "#define EAGLER_IS_FRAGMENT_SHADER\n" + (precisions == null ? "" : precisions + "\n") + + gles2CompatFile + "\n" + shaderSrc; + } + + public static String getHeader() { + if (header == null) + throw new IllegalStateException(); + return header; + } + + public static String getVertexHeader(String shaderSrc) { + if (header == null) + throw new IllegalStateException(); + return header + "#define EAGLER_IS_VERTEX_SHADER\n" + shaderSrc; + } + + public static String getVertexHeaderCompat(String shaderSrc, String precisions) { + if (header == null || gles2CompatFile == null) + throw new IllegalStateException(); + return header + "#define EAGLER_IS_VERTEX_SHADER\n" + (precisions == null ? "" : precisions + "\n") + + gles2CompatFile + "\n" + shaderSrc; + } + static void init() { gles2CompatFile = EagRuntime.getRequiredResourceString(GLES2_COMPAT_FILE_NAME); int glesVersion = EaglercraftGPU.checkOpenGLESVersion(); StringBuilder headerBuilder; - if(glesVersion >= 310) { + if (glesVersion >= 310) { headerBuilder = new StringBuilder("#version 310 es"); boolean oes5 = PlatformOpenGL.checkOESGPUShader5Capable(); boolean ext5 = !oes5 && PlatformOpenGL.checkEXTGPUShader5Capable(); - if(oes5) { + if (oes5) { headerBuilder.append("\n#extension GL_OES_gpu_shader5 : enable"); - }else if(ext5) { + } else if (ext5) { headerBuilder.append("\n#extension GL_EXT_gpu_shader5 : enable"); } headerBuilder.append("\n#define EAGLER_IS_GLES_310"); headerBuilder.append("\n#define EAGLER_HAS_GLES_310"); headerBuilder.append("\n#define EAGLER_HAS_GLES_300"); headerBuilder.append("\n#define EAGLER_HAS_GLES_200"); - if(oes5 || ext5) { + if (oes5 || ext5) { headerBuilder.append("\n#define EAGLER_HAS_GLES_310_SHADER_5"); } - }else if(glesVersion == 300) { + } else if (glesVersion == 300) { headerBuilder = new StringBuilder("#version 300 es"); headerBuilder.append("\n#define EAGLER_IS_GLES_300"); headerBuilder.append("\n#define EAGLER_HAS_GLES_300"); headerBuilder.append("\n#define EAGLER_HAS_GLES_200"); - }else if(glesVersion == 200) { + } else if (glesVersion == 200) { boolean texLOD = PlatformOpenGL.checkTextureLODCapable(); headerBuilder = new StringBuilder("#version 100"); - if(texLOD) { + if (texLOD) { headerBuilder.append("\n#extension GL_EXT_shader_texture_lod : enable"); } headerBuilder.append("\n#define EAGLER_HAS_GLES_200"); headerBuilder.append("\n#define EAGLER_IS_GLES_200"); - if(texLOD) { + if (texLOD) { headerBuilder.append("\n#define EAGLER_HAS_GLES_200_SHADER_TEXTURE_LOD"); } - }else { + } else { throw new IllegalStateException("Unsupported OpenGL ES version: " + glesVersion); } header = headerBuilder.append('\n').toString(); } - static void destroy() { - header = null; - } - - public static String getHeader() { - if(header == null) throw new IllegalStateException(); - return header; - } - - public static String getVertexHeader(String shaderSrc) { - if(header == null) throw new IllegalStateException(); - return header + "#define EAGLER_IS_VERTEX_SHADER\n" + shaderSrc; - } - - public static String getFragmentHeader(String shaderSrc) { - if(header == null) throw new IllegalStateException(); - return header + "#define EAGLER_IS_FRAGMENT_SHADER\n" + shaderSrc; - } - - public static String getVertexHeaderCompat(String shaderSrc, String precisions) { - if(header == null || gles2CompatFile == null) throw new IllegalStateException(); - return header + "#define EAGLER_IS_VERTEX_SHADER\n" + (precisions == null ? "" : precisions + "\n") + gles2CompatFile + "\n" + shaderSrc; - } - - public static String getFragmentHeaderCompat(String shaderSrc, String precisions) { - if(header == null || gles2CompatFile == null) throw new IllegalStateException(); - return header + "#define EAGLER_IS_FRAGMENT_SHADER\n"+ (precisions == null ? "" : precisions + "\n") + gles2CompatFile + "\n" + shaderSrc; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GameOverlayFramebuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GameOverlayFramebuffer.java index 9aec1e65..3b73c936 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GameOverlayFramebuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GameOverlayFramebuffer.java @@ -1,26 +1,43 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferRenderbuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglRenderbufferStorage; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; + +import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IFramebufferGL; import net.lax1dude.eaglercraft.v1_8.internal.IRenderbufferGL; import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - -import net.lax1dude.eaglercraft.v1_8.EagRuntime; - -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,7 +71,7 @@ public class GameOverlayFramebuffer { } public boolean beginRender(int width, int height) { - if(framebuffer == null) { + if (framebuffer == null) { framebuffer = _wglCreateFramebuffer(); depthBuffer = enableDepth ? _wglCreateRenderbuffer() : null; framebufferColor = GlStateManager.generateTexture(); @@ -64,20 +81,22 @@ public class GameOverlayFramebuffer { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(framebufferColor), 0); - if(enableDepth) { + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(framebufferColor), 0); + if (enableDepth) { _wglBindRenderbuffer(_GL_RENDERBUFFER, depthBuffer); _wglFramebufferRenderbuffer(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, _GL_RENDERBUFFER, depthBuffer); } } boolean resized = currentWidth != width || currentHeight != height; - if(resized) { + if (resized) { currentWidth = width; currentHeight = height; GlStateManager.bindTexture(framebufferColor); - EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - if(enableDepth) { + EaglercraftGPU.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, + (ByteBuffer) null); + if (enableDepth) { _wglBindRenderbuffer(_GL_RENDERBUFFER, depthBuffer); _wglRenderbufferStorage(_GL_RENDERBUFFER, _GL_DEPTH_COMPONENT16, width, height); } @@ -87,6 +106,21 @@ public class GameOverlayFramebuffer { return resized; } + public void destroy() { + if (framebuffer != null) { + _wglDeleteFramebuffer(framebuffer); + if (enableDepth) { + _wglDeleteRenderbuffer(depthBuffer); + } + GlStateManager.deleteTexture(framebufferColor); + framebuffer = null; + depthBuffer = null; + framebufferColor = -1; + age = -1l; + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + } + } + public void endRender() { _wglBindFramebuffer(_GL_FRAMEBUFFER, null); age = EagRuntime.steadyTimeMillis(); @@ -100,19 +134,4 @@ public class GameOverlayFramebuffer { return framebufferColor; } - public void destroy() { - if(framebuffer != null) { - _wglDeleteFramebuffer(framebuffer); - if(enableDepth) { - _wglDeleteRenderbuffer(depthBuffer); - } - GlStateManager.deleteTexture(framebufferColor); - framebuffer = null; - depthBuffer = null; - framebufferColor = -1; - age = -1l; - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GlStateManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GlStateManager.java index 537dfb50..81637ed2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GlStateManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/GlStateManager.java @@ -1,5 +1,49 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglActiveTexture; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindTexture; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBlendColor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBlendFunc; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBlendFuncSeparate; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglClear; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglClearColor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglClearDepth; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglColorMask; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCullFace; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteTextures; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDepthFunc; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDepthMask; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDisable; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnable; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenTextures; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglPolygonOffset; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglViewport; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BACK; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BLEND; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CULL_FACE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_TEST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EXP; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_EYE_PLANE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LESS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_OBJECT_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_OBJECT_PLANE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_POLYGON_OFFSET_FILL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_3D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MATRIX; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; @@ -7,47 +51,53 @@ import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; import net.lax1dude.eaglercraft.v1_8.vector.Vector4f; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GlStateManager { - - static final Logger logger = LogManager.getLogger("GlStateManager"); + public static enum TexGen { + S, T, R, Q; + + int source = GL_OBJECT_LINEAR; + int plane = GL_OBJECT_PLANE; + Vector4f vector = new Vector4f(); + + } + + static final Logger logger = LogManager.getLogger("GlStateManager"); static boolean stateDepthTest = false; static boolean stateDepthTestStash = false; static int stateDepthFunc = -1; - static boolean stateDepthMask = true; + static boolean stateDepthMask = true; static boolean stateCull = false; static boolean stateCullStash = false; - static int stateCullFace = GL_BACK; + static int stateCullFace = GL_BACK; static boolean statePolygonOffset = false; static float statePolygonOffsetFactor = 0.0f; - static float statePolygonOffsetUnits = 0.0f; + static float statePolygonOffsetUnits = 0.0f; static float stateColorR = 1.0f; static float stateColorG = 1.0f; static float stateColorB = 1.0f; static float stateColorA = 1.0f; - static int stateColorSerial = 0; + static int stateColorSerial = 0; static float stateShaderBlendSrcColorR = 1.0f; static float stateShaderBlendSrcColorG = 1.0f; static float stateShaderBlendSrcColorB = 1.0f; @@ -57,36 +107,36 @@ public class GlStateManager { static float stateShaderBlendAddColorB = 0.0f; static float stateShaderBlendAddColorA = 0.0f; static int stateShaderBlendColorSerial = 0; - static boolean stateEnableShaderBlendColor = false; + static boolean stateEnableShaderBlendColor = false; static boolean stateBlend = false; static boolean stateBlendStash = false; static boolean stateGlobalBlend = true; static int stateBlendEquation = -1; static int stateBlendSRC = -1; static int stateBlendDST = -1; - static boolean stateEnableOverlayFramebufferBlending = false; - - static boolean stateAlphaTest = false; - static float stateAlphaTestRef = 0.1f; + static boolean stateEnableOverlayFramebufferBlending = false; + static boolean stateAlphaTest = false; + + static float stateAlphaTestRef = 0.1f; static boolean stateMaterial = false; static boolean stateLighting = false; static int stateLightsStackPointer = 0; static final boolean[][] stateLightsEnabled = new boolean[4][8]; static final Vector4f[][] stateLightsStack = new Vector4f[4][8]; - static final int[] stateLightingSerial = new int[4]; + static final int[] stateLightingSerial = new int[4]; static float stateLightingAmbientR = 0.0f; static float stateLightingAmbientG = 0.0f; static float stateLightingAmbientB = 0.0f; + static int stateLightingAmbientSerial = 0; - static float stateNormalX = 0.0f; static float stateNormalY = 0.0f; static float stateNormalZ = -1.0f; - static int stateNormalSerial = 0; + static int stateNormalSerial = 0; static boolean stateFog = false; static boolean stateFogEXP = false; static float stateFogDensity = 1.0f; @@ -96,43 +146,32 @@ public class GlStateManager { static float stateFogColorG = 1.0f; static float stateFogColorB = 1.0f; static float stateFogColorA = 1.0f; + static int stateFogSerial = 0; - static int activeTexture = 0; static final boolean[] stateTexture = new boolean[16]; - static final int[] boundTexture = new int[] { - -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1 - }; + static final int[] boundTexture = new int[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; static float stateAnisotropicFixW = -999.0f; static float stateAnisotropicFixH = -999.0f; + static int stateAnisotropicFixSerial = 0; static boolean stateTexGen = false; - static int viewportX = -1; static int viewportY = -1; static int viewportW = -1; - static int viewportH = -1; - - static int colorMaskBits = 15; + static int viewportH = -1; + + static int colorMaskBits = 15; static float clearColorR = 0.0f; static float clearColorG = 0.0f; static float clearColorB = 0.0f; - static float clearColorA = 1.0f; - - static float clearDepth = -999.0f; - - public static enum TexGen { - S, T, R, Q; - int source = GL_OBJECT_LINEAR; - int plane = GL_OBJECT_PLANE; - Vector4f vector = new Vector4f(); - - } + static float clearColorA = 1.0f; + + static float clearDepth = -999.0f; static float blendConstantR = -999.0f; static float blendConstantG = -999.0f; @@ -142,12 +181,12 @@ public class GlStateManager { static int stateTexGenSerial = 0; static int stateMatrixMode = GL_MODELVIEW; - + static final Matrix4f[] modelMatrixStack = new Matrix4f[48]; static final int[] modelMatrixStackAccessSerial = new int[48]; private static int modelMatrixAccessSerial = 0; static int modelMatrixStackPointer = 0; - + static final Matrix4f[] projectionMatrixStack = new Matrix4f[8]; static final int[] projectionMatrixStackAccessSerial = new int[8]; private static int projectionMatrixAccessSerial = 0; @@ -156,192 +195,142 @@ public class GlStateManager { static final float[] textureCoordsX = new float[8]; static final float[] textureCoordsY = new float[8]; static final int[] textureCoordsAccessSerial = new int[8]; - + static final Matrix4f[][] textureMatrixStack = new Matrix4f[8][8]; static final int[][] textureMatrixStackAccessSerial = new int[8][8]; static int[] textureMatrixAccessSerial = new int[8]; static int[] textureMatrixStackPointer = new int[8]; - + static boolean stateUseExtensionPipeline = false; - + private static final Matrix4f tmpInvertedMatrix = new Matrix4f(); - + static { populateStack(modelMatrixStack); populateStack(projectionMatrixStack); populateStack(textureMatrixStack); populateStack(stateLightsStack); } - - static void populateStack(Matrix4f[] stack) { - for(int i = 0; i < stack.length; ++i) { - stack[i] = new Matrix4f(); - } - } - - static void populateStack(Matrix4f[][] stack) { - for(int i = 0; i < stack.length; ++i) { - populateStack(stack[i]); - } - } - - static void populateStack(Vector4f[][] stack) { - for(int i = 0; i < stack.length; ++i) { - for(int j = 0; j < stack[i].length; ++j) { - stack[i][j] = new Vector4f(0.0f, -1.0f, 0.0f, 0.0f); - } - } - } - - public static final void pushLightCoords() { - int push = stateLightsStackPointer + 1; - if(push < stateLightsStack.length) { - Vector4f[] copyFrom = stateLightsStack[stateLightsStackPointer]; - boolean[] copyFrom2 = stateLightsEnabled[stateLightsStackPointer]; - Vector4f[] copyTo = stateLightsStack[push]; - boolean[] copyTo2 = stateLightsEnabled[push]; - for(int i = 0; i < copyFrom.length; ++i) { - if(copyFrom2[i]) { - copyTo[i].set(copyFrom[i]); - copyTo2[i] = true; - }else { - copyTo2[i] = false; - } - } - stateLightingSerial[push] = stateLightingSerial[stateLightsStackPointer]; - stateLightsStackPointer = push; - }else { - Throwable t = new IndexOutOfBoundsException("GL_LIGHT direction stack overflow!" + - " Exceeded " + stateLightsStack.length + " calls to GlStateManager.pushLightCoords"); - logger.error(t); - } - } - public static final void popLightCoords() { - if(stateLightsStackPointer > 0) { - --stateLightsStackPointer; - }else { - Throwable t = new IndexOutOfBoundsException("GL_LIGHT direction stack underflow!" + - " Called GlStateManager.popLightCoords on an empty light stack"); - logger.error(t); - } - } + private static final Vector4f paramVector4 = new Vector4f(); - public static final void disableAlpha() { - stateAlphaTest = false; - } + private static final Vector3f paramVector = new Vector3f(); - public static final void enableAlpha() { - stateAlphaTest = true; - } + private static final float toRad = 0.0174532925f; + + private static final Matrix4f paramMatrix = new Matrix4f(); + + private static final Matrix4f unprojA = new Matrix4f(); + + private static final Matrix4f unprojB = new Matrix4f(); + + private static final Vector4f unprojC = new Vector4f(); public static final void alphaFunc(int func, float ref) { - if(func != GL_GREATER) { + if (func != GL_GREATER) { throw new UnsupportedOperationException("Only GL_GREATER alphaFunc is supported"); - }else { + } else { stateAlphaTestRef = ref; } } - public static final void enableLighting() { - stateLighting = true; - } - - public static final void disableLighting() { - stateLighting = false; - } - - public static final void enableExtensionPipeline() { - stateUseExtensionPipeline = true; - } - - public static final void disableExtensionPipeline() { - stateUseExtensionPipeline = false; - } - - public static final boolean isExtensionPipeline() { - return stateUseExtensionPipeline; - } - - private static final Vector4f paramVector4 = new Vector4f(); - public static final void enableMCLight(int light, float diffuse, double dirX, - double dirY, double dirZ, double dirW) { - paramVector4.x = (float)dirX; - paramVector4.y = (float)dirY; - paramVector4.z = (float)dirZ; - paramVector4.w = (float)dirW; - Matrix4f.transform(modelMatrixStack[modelMatrixStackPointer], paramVector4, paramVector4); - paramVector4.normalise(); - Vector4f dest = stateLightsStack[stateLightsStackPointer][light]; - dest.x = paramVector4.x; - dest.y = paramVector4.y; - dest.z = paramVector4.z; - dest.w = diffuse; - stateLightsEnabled[stateLightsStackPointer][light] = true; - ++stateLightingSerial[stateLightsStackPointer]; - } - - public static final void disableMCLight(int light) { - stateLightsEnabled[stateLightsStackPointer][light] = false; - ++stateLightingSerial[stateLightsStackPointer]; - } - - public static final void setMCLightAmbient(float r, float g, float b) { - stateLightingAmbientR = r; - stateLightingAmbientG = g; - stateLightingAmbientB = b; - ++stateLightingAmbientSerial; - } - - public static final void enableColorMaterial() { - stateMaterial = true; - } - - public static final void disableColorMaterial() { - stateMaterial = false; - } - - public static final void disableDepth() { - if(stateDepthTest) { - _wglDisable(GL_DEPTH_TEST); - stateDepthTest = false; + public static final void bindTexture(int texture) { + if (texture != boundTexture[activeTexture]) { + _wglBindTexture(GL_TEXTURE_2D, EaglercraftGPU.mapTexturesGL.get(texture)); + boundTexture[activeTexture] = texture; } } - public static final void enableDepth() { - if(!stateDepthTest) { - _wglEnable(GL_DEPTH_TEST); - stateDepthTest = true; + public static final void bindTexture3D(int texture) { + if (texture != boundTexture[activeTexture]) { + _wglBindTexture(GL_TEXTURE_3D, EaglercraftGPU.mapTexturesGL.get(texture)); + boundTexture[activeTexture] = texture; } } - public static final void eagPushStateForGLES2BlitHack() { - stateDepthTestStash = stateDepthTest; - stateCullStash = stateCull; - stateBlendStash = stateBlend; + public static final void blendFunc(int srcFactor, int dstFactor) { + if (stateEnableOverlayFramebufferBlending) { + tryBlendFuncSeparate(srcFactor, dstFactor, 0, 1); + return; + } + int srcBits = (srcFactor | (srcFactor << 16)); + int dstBits = (dstFactor | (dstFactor << 16)); + if (srcBits != stateBlendSRC || dstBits != stateBlendDST) { + _wglBlendFunc(srcFactor, dstFactor); + stateBlendSRC = srcBits; + stateBlendDST = dstBits; + } } - public static final void eagPopStateForGLES2BlitHack() { - if(stateDepthTestStash) { - enableDepth(); - }else { - disableDepth(); + public static final void callList(int list) { + EaglercraftGPU.glCallList(list); + } + + public static final void clear(int mask) { + _wglClear(mask); + } + + public static final void clearColor(float red, float green, float blue, float alpha) { + if (red != clearColorR || green != clearColorG || blue != clearColorB || alpha != clearColorA) { + _wglClearColor(red, green, blue, alpha); + clearColorR = red; + clearColorG = green; + clearColorB = blue; + clearColorA = alpha; } - if(stateCullStash) { - enableCull(); - }else { - disableCull(); + } + + public static final void clearDepth(float depth) { + depth = 1.0f - depth; + if (depth != clearDepth) { + _wglClearDepth(depth); + clearDepth = depth; } - if(stateBlendStash) { - enableBlend(); - }else { - disableBlend(); + } + + public static final void color(float colorRed, float colorGreen, float colorBlue) { + stateColorR = colorRed; + stateColorG = colorGreen; + stateColorB = colorBlue; + stateColorA = 1.0f; + ++stateColorSerial; + } + + public static final void color(float colorRed, float colorGreen, float colorBlue, float colorAlpha) { + stateColorR = colorRed; + stateColorG = colorGreen; + stateColorB = colorBlue; + stateColorA = colorAlpha; + ++stateColorSerial; + } + + public static final void colorLogicOp(int opcode) { + + } + + public static final void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { + int bits = (red ? 1 : 0) | (green ? 2 : 0) | (blue ? 4 : 0) | (alpha ? 8 : 0); + if (bits != colorMaskBits) { + _wglColorMask(red, green, blue, alpha); + colorMaskBits = bits; } } + public static final void cullFace(int mode) { + if (stateCullFace != mode) { + _wglCullFace(mode); + stateCullFace = mode; + } + } + + public static final void deleteTexture(int texture) { + unbindTextureIfCached(texture); + _wglDeleteTextures(EaglercraftGPU.mapTexturesGL.free(texture)); + } + public static final void depthFunc(int depthFunc) { int rev = depthFunc; - switch(depthFunc) { + switch (depthFunc) { case GL_GREATER: rev = GL_LESS; break; @@ -358,471 +347,236 @@ public class GlStateManager { rev = GL_GREATER; break; } - if(rev != stateDepthFunc) { + if (rev != stateDepthFunc) { _wglDepthFunc(rev); stateDepthFunc = rev; } } public static final void depthMask(boolean flagIn) { - if(flagIn != stateDepthMask) { + if (flagIn != stateDepthMask) { _wglDepthMask(flagIn); stateDepthMask = flagIn; } } + public static final void disableAlpha() { + stateAlphaTest = false; + } + public static final void disableBlend() { - if(stateBlend) { - if(stateGlobalBlend) _wglDisable(GL_BLEND); + if (stateBlend) { + if (stateGlobalBlend) + _wglDisable(GL_BLEND); stateBlend = false; } } - public static final void enableBlend() { - if(!stateBlend) { - if(stateGlobalBlend) _wglEnable(GL_BLEND); - stateBlend = true; + public static final void disableColorLogic() { + + } + + public static final void disableColorMaterial() { + stateMaterial = false; + } + + public static final void disableCull() { + if (stateCull) { + _wglDisable(GL_CULL_FACE); + stateCull = false; } } - public static final void globalDisableBlend() { - if(stateBlend) { - _wglDisable(GL_BLEND); - } - stateGlobalBlend = false; - } - - public static final void globalEnableBlend() { - if(stateBlend) { - _wglEnable(GL_BLEND); - } - stateGlobalBlend = true; - } - - public static final void blendFunc(int srcFactor, int dstFactor) { - if(stateEnableOverlayFramebufferBlending) { - tryBlendFuncSeparate(srcFactor, dstFactor, 0, 1); - return; - } - int srcBits = (srcFactor | (srcFactor << 16)); - int dstBits = (dstFactor | (dstFactor << 16)); - if(srcBits != stateBlendSRC || dstBits != stateBlendDST) { - _wglBlendFunc(srcFactor, dstFactor); - stateBlendSRC = srcBits; - stateBlendDST = dstBits; + public static final void disableDepth() { + if (stateDepthTest) { + _wglDisable(GL_DEPTH_TEST); + stateDepthTest = false; } } - public static final void tryBlendFuncSeparate(int srcFactor, int dstFactor, int srcFactorAlpha, int dstFactorAlpha) { - if(stateEnableOverlayFramebufferBlending) { // game overlay framebuffer in EntityRenderer.java - srcFactorAlpha = GL_ONE; - dstFactorAlpha = GL_ONE_MINUS_SRC_ALPHA; - } - int srcBits = (srcFactor | (srcFactorAlpha << 16)); - int dstBits = (dstFactor | (dstFactorAlpha << 16)); - if(srcBits != stateBlendSRC || dstBits != stateBlendDST) { - _wglBlendFuncSeparate(srcFactor, dstFactor, srcFactorAlpha, dstFactorAlpha); - stateBlendSRC = srcBits; - stateBlendDST = dstBits; - } - } - - public static final void enableOverlayFramebufferBlending() { - stateEnableOverlayFramebufferBlending = true; - } - - public static final void disableOverlayFramebufferBlending() { - stateEnableOverlayFramebufferBlending = false; - } - - public static final void setShaderBlendSrc(float r, float g, float b, float a) { - stateShaderBlendSrcColorR = r; - stateShaderBlendSrcColorG = g; - stateShaderBlendSrcColorB = b; - stateShaderBlendSrcColorA = a; - ++stateShaderBlendColorSerial; - } - - public static final void setShaderBlendAdd(float r, float g, float b, float a) { - stateShaderBlendAddColorR = r; - stateShaderBlendAddColorG = g; - stateShaderBlendAddColorB = b; - stateShaderBlendAddColorA = a; - ++stateShaderBlendColorSerial; - } - - public static final void enableShaderBlendAdd() { - stateEnableShaderBlendColor = true; - } - - public static final void disableShaderBlendAdd() { - stateEnableShaderBlendColor = false; - } - - public static final void setBlendConstants(float r, float g, float b, float a) { - if(r != blendConstantR || g != blendConstantG || b != blendConstantB || a != blendConstantA) { - _wglBlendColor(r, g, b, a); - blendConstantR = r; - blendConstantG = g; - blendConstantB = b; - blendConstantA = a; - } - } - - public static final void enableFog() { - stateFog = true; + public static final void disableExtensionPipeline() { + stateUseExtensionPipeline = false; } public static final void disableFog() { stateFog = false; } - public static final void setFog(int param) { - stateFogEXP = param == GL_EXP; - ++stateFogSerial; + public static final void disableLighting() { + stateLighting = false; } - public static final void setFogDensity(float param) { - stateFogDensity = param; - ++stateFogSerial; + public static final void disableMCLight(int light) { + stateLightsEnabled[stateLightsStackPointer][light] = false; + ++stateLightingSerial[stateLightsStackPointer]; } - public static final void setFogStart(float param) { - stateFogStart = param; - ++stateFogSerial; - } - - public static final void setFogEnd(float param) { - stateFogEnd = param; - ++stateFogSerial; - } - - public static final void enableCull() { - if(!stateCull) { - _wglEnable(GL_CULL_FACE); - stateCull = true; - } - } - - public static final void disableCull() { - if(stateCull) { - _wglDisable(GL_CULL_FACE); - stateCull = false; - } - } - - public static final void cullFace(int mode) { - if(stateCullFace != mode) { - _wglCullFace(mode); - stateCullFace = mode; - } - } - - public static final void enablePolygonOffset() { - if(!statePolygonOffset) { - _wglEnable(GL_POLYGON_OFFSET_FILL); - statePolygonOffset = true; - } + public static final void disableOverlayFramebufferBlending() { + stateEnableOverlayFramebufferBlending = false; } public static final void disablePolygonOffset() { - if(statePolygonOffset) { + if (statePolygonOffset) { _wglDisable(GL_POLYGON_OFFSET_FILL); statePolygonOffset = false; } } + public static final void disableRescaleNormal() { + + } + + public static final void disableShaderBlendAdd() { + stateEnableShaderBlendColor = false; + } + + public static final void disableTexGen() { + stateTexGen = false; + } + + public static final void disableTexture2D() { + stateTexture[activeTexture] = false; + } + public static final void doPolygonOffset(float factor, float units) { - if(factor != statePolygonOffsetFactor || units != statePolygonOffsetUnits) { + if (factor != statePolygonOffsetFactor || units != statePolygonOffsetUnits) { _wglPolygonOffset(-factor, units); statePolygonOffsetFactor = factor; statePolygonOffsetUnits = units; } } + public static final void eagPopStateForGLES2BlitHack() { + if (stateDepthTestStash) { + enableDepth(); + } else { + disableDepth(); + } + if (stateCullStash) { + enableCull(); + } else { + disableCull(); + } + if (stateBlendStash) { + enableBlend(); + } else { + disableBlend(); + } + } + + public static final void eagPushStateForGLES2BlitHack() { + stateDepthTestStash = stateDepthTest; + stateCullStash = stateCull; + stateBlendStash = stateBlend; + } + + public static final void enableAlpha() { + stateAlphaTest = true; + } + + public static final void enableBlend() { + if (!stateBlend) { + if (stateGlobalBlend) + _wglEnable(GL_BLEND); + stateBlend = true; + } + } + public static final void enableColorLogic() { throw new UnsupportedOperationException("Color logic op is not supported in OpenGL ES!"); } - public static final void disableColorLogic() { - + public static final void enableColorMaterial() { + stateMaterial = true; } - public static final void colorLogicOp(int opcode) { - - } - - public static final void enableTexGen() { - stateTexGen = true; - } - - public static final void disableTexGen() { - stateTexGen = false; - } - - public static final void texGen(GlStateManager.TexGen coord, int source) { - coord.source = source; - ++stateTexGenSerial; - } - - public static final void func_179105_a(GlStateManager.TexGen coord, int plane, FloatBuffer vector) { - coord.plane = plane; - coord.vector.load(vector); - if(plane == GL_EYE_PLANE) { - tmpInvertedMatrix.load(GlStateManager.modelMatrixStack[GlStateManager.modelMatrixStackPointer]).invert().transpose(); - Matrix4f.transform(tmpInvertedMatrix, coord.vector, coord.vector); - } - ++stateTexGenSerial; - } - - public static final void setActiveTexture(int texture) { - int textureIdx = texture - GL_TEXTURE0; - if(textureIdx != activeTexture) { - _wglActiveTexture(texture); - activeTexture = textureIdx; + public static final void enableCull() { + if (!stateCull) { + _wglEnable(GL_CULL_FACE); + stateCull = true; } } - public static final void enableTexture2D() { - stateTexture[activeTexture] = true; - } - - public static final void disableTexture2D() { - stateTexture[activeTexture] = false; - } - - public static final void texCoords2D(float x, float y) { - textureCoordsX[activeTexture] = x; - textureCoordsY[activeTexture] = y; - ++textureCoordsAccessSerial[activeTexture]; - } - - public static final void texCoords2DDirect(int tex, float x, float y) { - textureCoordsX[tex] = x; - textureCoordsY[tex] = y; - ++textureCoordsAccessSerial[tex]; - } - - public static final float getTexCoordX(int tex) { - return textureCoordsX[tex]; - } - - public static final float getTexCoordY(int tex) { - return textureCoordsY[tex]; - } - - public static final int generateTexture() { - return EaglercraftGPU.mapTexturesGL.register(_wglGenTextures()); - } - - public static final void deleteTexture(int texture) { - unbindTextureIfCached(texture); - _wglDeleteTextures(EaglercraftGPU.mapTexturesGL.free(texture)); - } - - static final void unbindTextureIfCached(int texture) { - boolean f1, f2 = false; - for(int i = 0; i < boundTexture.length; ++i) { - if(boundTexture[i] == texture) { - f1 = i != activeTexture; - if(f2 || f1) { - _wglActiveTexture(GL_TEXTURE0 + i); - f2 = f1; - } - _wglBindTexture(GL_TEXTURE_2D, null); - if(EaglercraftGPU.checkOpenGLESVersion() >= 300) { - _wglBindTexture(GL_TEXTURE_3D, null); - } - boundTexture[i] = -1; - } - } - if(f2) { - _wglActiveTexture(GL_TEXTURE0 + activeTexture); + public static final void enableDepth() { + if (!stateDepthTest) { + _wglEnable(GL_DEPTH_TEST); + stateDepthTest = true; } } - public static final void bindTexture(int texture) { - if(texture != boundTexture[activeTexture]) { - _wglBindTexture(GL_TEXTURE_2D, EaglercraftGPU.mapTexturesGL.get(texture)); - boundTexture[activeTexture] = texture; - } + public static final void enableExtensionPipeline() { + stateUseExtensionPipeline = true; } - public static final void bindTexture3D(int texture) { - if(texture != boundTexture[activeTexture]) { - _wglBindTexture(GL_TEXTURE_3D, EaglercraftGPU.mapTexturesGL.get(texture)); - boundTexture[activeTexture] = texture; - } + public static final void enableFog() { + stateFog = true; } - public static final void quickBindTexture(int unit, int texture) { - int unitBase = unit - GL_TEXTURE0; - if(texture != boundTexture[unitBase]) { - if(unitBase != activeTexture) { - _wglActiveTexture(unit); - } - _wglBindTexture(GL_TEXTURE_2D, EaglercraftGPU.mapTexturesGL.get(texture)); - boundTexture[unitBase] = texture; - if(unitBase != activeTexture) { - _wglActiveTexture(GL_TEXTURE0 + activeTexture); - } - } + public static final void enableLighting() { + stateLighting = true; } - public static final void shadeModel(int mode) { + public static final void enableMCLight(int light, float diffuse, double dirX, double dirY, double dirZ, + double dirW) { + paramVector4.x = (float) dirX; + paramVector4.y = (float) dirY; + paramVector4.z = (float) dirZ; + paramVector4.w = (float) dirW; + Matrix4f.transform(modelMatrixStack[modelMatrixStackPointer], paramVector4, paramVector4); + paramVector4.normalise(); + Vector4f dest = stateLightsStack[stateLightsStackPointer][light]; + dest.x = paramVector4.x; + dest.y = paramVector4.y; + dest.z = paramVector4.z; + dest.w = diffuse; + stateLightsEnabled[stateLightsStackPointer][light] = true; + ++stateLightingSerial[stateLightsStackPointer]; + } + public static final void enableOverlayFramebufferBlending() { + stateEnableOverlayFramebufferBlending = true; + } + + public static final void enablePolygonOffset() { + if (!statePolygonOffset) { + _wglEnable(GL_POLYGON_OFFSET_FILL); + statePolygonOffset = true; + } } public static final void enableRescaleNormal() { // still not sure what this is for } - public static final void disableRescaleNormal() { - + public static final void enableShaderBlendAdd() { + stateEnableShaderBlendColor = true; } - public static final void viewport(int x, int y, int w, int h) { - if(viewportX != x || viewportY != y || viewportW != w || viewportH != h) { - _wglViewport(x, y, w, h); - viewportX = x; - viewportY = y; - viewportW = w; - viewportH = h; + public static final void enableTexGen() { + stateTexGen = true; + } + + public static final void enableTexture2D() { + stateTexture[activeTexture] = true; + } + + public static final void func_179105_a(GlStateManager.TexGen coord, int plane, FloatBuffer vector) { + coord.plane = plane; + coord.vector.load(vector); + if (plane == GL_EYE_PLANE) { + tmpInvertedMatrix.load(GlStateManager.modelMatrixStack[GlStateManager.modelMatrixStackPointer]).invert() + .transpose(); + Matrix4f.transform(tmpInvertedMatrix, coord.vector, coord.vector); } + ++stateTexGenSerial; } - public static final void colorMask(boolean red, boolean green, boolean blue, boolean alpha) { - int bits = (red ? 1 : 0) | (green ? 2 : 0) | (blue ? 4 : 0) | (alpha ? 8 : 0); - if(bits != colorMaskBits) { - _wglColorMask(red, green, blue, alpha); - colorMaskBits = bits; - } - } - - public static final void clearDepth(float depth) { - depth = 1.0f - depth; - if(depth != clearDepth) { - _wglClearDepth(depth); - clearDepth = depth; - } - } - - public static final void clearColor(float red, float green, float blue, float alpha) { - if(red != clearColorR || green != clearColorG || blue != clearColorB || alpha != clearColorA) { - _wglClearColor(red, green, blue, alpha); - clearColorR = red; - clearColorG = green; - clearColorB = blue; - clearColorA = alpha; - } - } - - public static final void clear(int mask) { - _wglClear(mask); - } - - public static final void matrixMode(int mode) { - stateMatrixMode = mode; - } - - public static final void loadIdentity() { - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modelMatrixStack[modelMatrixStackPointer].setIdentity(); - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - projectionMatrixStack[projectionMatrixStackPointer].setIdentity(); - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - textureMatrixStack[activeTexture][textureMatrixStackPointer[activeTexture]].setIdentity(); - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - } - - public static final void pushMatrix() { - int push; - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - push = modelMatrixStackPointer + 1; - if(push < modelMatrixStack.length) { - modelMatrixStack[push].load(modelMatrixStack[modelMatrixStackPointer]); - modelMatrixStackAccessSerial[push] = modelMatrixStackAccessSerial[modelMatrixStackPointer]; - modelMatrixStackPointer = push; - }else { - Throwable t = new IndexOutOfBoundsException("GL_MODELVIEW matrix stack overflow!" + - " Exceeded " + modelMatrixStack.length + " calls to GlStateManager.pushMatrix"); - logger.error(t); - } - break; - case GL_PROJECTION: - push = projectionMatrixStackPointer + 1; - if(push < projectionMatrixStack.length) { - projectionMatrixStack[push].load(projectionMatrixStack[projectionMatrixStackPointer]); - projectionMatrixStackAccessSerial[push] = projectionMatrixStackAccessSerial[projectionMatrixStackPointer]; - projectionMatrixStackPointer = push; - }else { - Throwable t = new IndexOutOfBoundsException("GL_PROJECTION matrix stack overflow!" + - " Exceeded " + projectionMatrixStack.length + " calls to GlStateManager.pushMatrix"); - logger.error(t); - } - break; - case GL_TEXTURE: - push = textureMatrixStackPointer[activeTexture] + 1; - if(push < textureMatrixStack.length) { - int ptr = textureMatrixStackPointer[activeTexture]; - textureMatrixStack[activeTexture][push].load(textureMatrixStack[activeTexture][ptr]); - textureMatrixStackAccessSerial[activeTexture][push] = textureMatrixStackAccessSerial[activeTexture][ptr]; - textureMatrixStackPointer[activeTexture] = push; - }else { - Throwable t = new IndexOutOfBoundsException("GL_TEXTURE #" + activeTexture + " matrix stack overflow!" + - " Exceeded " + textureMatrixStack.length + " calls to GlStateManager.pushMatrix"); - logger.error(t); - } - break; - } - } - - public static final void popMatrix() { - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - if(modelMatrixStackPointer > 0) { - --modelMatrixStackPointer; - }else { - Throwable t = new IndexOutOfBoundsException("GL_MODELVIEW matrix stack underflow!" + - " Called GlStateManager.popMatrix on an empty matrix stack"); - logger.error(t); - } - break; - case GL_PROJECTION: - if(projectionMatrixStackPointer > 0) { - --projectionMatrixStackPointer; - }else { - Throwable t = new IndexOutOfBoundsException("GL_PROJECTION matrix stack underflow!" + - " Called GlStateManager.popMatrix on an empty matrix stack"); - logger.error(t); - } - break; - case GL_TEXTURE: - if(textureMatrixStackPointer[activeTexture] > 0) { - --textureMatrixStackPointer[activeTexture]; - }else { - Throwable t = new IndexOutOfBoundsException("GL_TEXTURE #" + activeTexture + - " matrix stack underflow! Called GlStateManager.popMatrix on an empty matrix stack"); - logger.error(t); - } - break; - } + public static final int generateTexture() { + return EaglercraftGPU.mapTexturesGL.register(_wglGenTextures()); } public static final void getFloat(int pname, float[] params) { - switch(pname) { + switch (pname) { case GL_MODELVIEW_MATRIX: modelMatrixStack[modelMatrixStackPointer].store(params); break; @@ -838,7 +592,7 @@ public class GlStateManager { } public static final void getFloat(int pname, FloatBuffer params) { - switch(pname) { + switch (pname) { case GL_MODELVIEW_MATRIX: modelMatrixStack[modelMatrixStackPointer].store(params); break; @@ -853,282 +607,54 @@ public class GlStateManager { } } - public static final void ortho(double left, double right, double bottom, double top, double zNear, double zFar) { - Matrix4f matrix; - switch(stateMatrixMode) { + public static final void getMatrix(Matrix4f mat) { + switch (stateMatrixMode) { case GL_MODELVIEW: - matrix = modelMatrixStack[modelMatrixStackPointer]; - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + mat.load(modelMatrixStack[modelMatrixStackPointer]); break; case GL_PROJECTION: default: - matrix = projectionMatrixStack[projectionMatrixStackPointer]; - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + mat.load(projectionMatrixStack[projectionMatrixStackPointer]); break; case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - matrix = textureMatrixStack[activeTexture][ptr]; - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - paramMatrix.m00 = 2.0f / (float)(right - left); - paramMatrix.m01 = 0.0f; - paramMatrix.m02 = 0.0f; - paramMatrix.m03 = 0.0f; - paramMatrix.m10 = 0.0f; - paramMatrix.m11 = 2.0f / (float)(top - bottom); - paramMatrix.m12 = 0.0f; - paramMatrix.m13 = 0.0f; - paramMatrix.m20 = 0.0f; - paramMatrix.m21 = 0.0f; - paramMatrix.m22 = 2.0f / (float)(zFar - zNear); - paramMatrix.m23 = 0.0f; - paramMatrix.m30 = (float)(-(right + left) / (right - left)); - paramMatrix.m31 = (float)(-(top + bottom) / (top - bottom)); - paramMatrix.m32 = (float)((zFar + zNear) / (zFar - zNear)); - paramMatrix.m33 = 1.0f; - Matrix4f.mul(matrix, paramMatrix, matrix); - } - - private static final Vector3f paramVector = new Vector3f(); - private static final float toRad = 0.0174532925f; - public static final void rotate(float angle, float x, float y, float z) { - paramVector.x = x; - paramVector.y = y; - paramVector.z = z; - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modelMatrixStack[modelMatrixStackPointer].rotate(angle * toRad, paramVector); - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - projectionMatrixStack[projectionMatrixStackPointer].rotate(angle * toRad, paramVector); - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - textureMatrixStack[activeTexture][ptr].rotate(angle * toRad, paramVector); - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; + mat.load(textureMatrixStack[activeTexture][textureMatrixStackPointer[activeTexture]]); break; } } - public static final void scale(float x, float y, float z) { - paramVector.x = x; - paramVector.y = y; - paramVector.z = z; - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modelMatrixStack[modelMatrixStackPointer].scale(paramVector); - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - projectionMatrixStack[projectionMatrixStackPointer].scale(paramVector); - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - textureMatrixStack[activeTexture][ptr].scale(paramVector); - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; + public static final Matrix4f getModelViewReference() { + return modelMatrixStack[modelMatrixStackPointer]; + } + + public static final int getModelViewSerial() { + return modelMatrixStackAccessSerial[modelMatrixStackPointer]; + } + + public static final float getTexCoordX(int tex) { + return textureCoordsX[tex]; + } + + public static final float getTexCoordY(int tex) { + return textureCoordsY[tex]; + } + + public static final void globalDisableBlend() { + if (stateBlend) { + _wglDisable(GL_BLEND); } + stateGlobalBlend = false; } - public static final void scale(double x, double y, double z) { - paramVector.x = (float)x; - paramVector.y = (float)y; - paramVector.z = (float)z; - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modelMatrixStack[modelMatrixStackPointer].scale(paramVector); - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - projectionMatrixStack[projectionMatrixStackPointer].scale(paramVector); - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - textureMatrixStack[activeTexture][ptr].scale(paramVector); - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; + public static final void globalEnableBlend() { + if (stateBlend) { + _wglEnable(GL_BLEND); } - } - - public static final void translate(float x, float y, float z) { - paramVector.x = x; - paramVector.y = y; - paramVector.z = z; - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modelMatrixStack[modelMatrixStackPointer].translate(paramVector); - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - projectionMatrixStack[projectionMatrixStackPointer].translate(paramVector); - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - textureMatrixStack[activeTexture][ptr].translate(paramVector); - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - } - - public static final void translate(double x, double y, double z) { - paramVector.x = (float)x; - paramVector.y = (float)y; - paramVector.z = (float)z; - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modelMatrixStack[modelMatrixStackPointer].translate(paramVector); - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - projectionMatrixStack[projectionMatrixStackPointer].translate(paramVector); - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - textureMatrixStack[activeTexture][ptr].translate(paramVector); - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - } - - private static final Matrix4f paramMatrix = new Matrix4f(); - public static final void multMatrix(float[] matrix) { - Matrix4f modeMatrix; - - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modeMatrix = modelMatrixStack[modelMatrixStackPointer]; - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - modeMatrix = projectionMatrixStack[projectionMatrixStackPointer]; - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - modeMatrix = textureMatrixStack[activeTexture][ptr]; - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - - paramMatrix.load(matrix); - - Matrix4f.mul(modeMatrix, paramMatrix, modeMatrix); - } - - public static final void multMatrix(Matrix4f matrix) { - Matrix4f modeMatrix; - - switch(stateMatrixMode) { - case GL_MODELVIEW: - default: - modeMatrix = modelMatrixStack[modelMatrixStackPointer]; - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - modeMatrix = projectionMatrixStack[projectionMatrixStackPointer]; - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - modeMatrix = textureMatrixStack[activeTexture][ptr]; - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - - Matrix4f.mul(modeMatrix, matrix, modeMatrix); - } - - public static final void color(float colorRed, float colorGreen, float colorBlue, float colorAlpha) { - stateColorR = colorRed; - stateColorG = colorGreen; - stateColorB = colorBlue; - stateColorA = colorAlpha; - ++stateColorSerial; - } - - public static final void color(float colorRed, float colorGreen, float colorBlue) { - stateColorR = colorRed; - stateColorG = colorGreen; - stateColorB = colorBlue; - stateColorA = 1.0f; - ++stateColorSerial; - } - - public static final void resetColor() { - stateColorR = 1.0f; - stateColorG = 1.0f; - stateColorB = 1.0f; - stateColorA = 1.0f; - ++stateColorSerial; - } - - public static final void callList(int list) { - EaglercraftGPU.glCallList(list); - } - - public static final void gluPerspective(float fovy, float aspect, float zNear, float zFar) { - Matrix4f matrix; - switch(stateMatrixMode) { - case GL_MODELVIEW: - matrix = modelMatrixStack[modelMatrixStackPointer]; - modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; - break; - case GL_PROJECTION: - default: - matrix = projectionMatrixStack[projectionMatrixStackPointer]; - projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; - break; - case GL_TEXTURE: - int ptr = textureMatrixStackPointer[activeTexture]; - matrix = textureMatrixStack[activeTexture][ptr]; - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; - break; - } - float cotangent = (float) Math.cos(fovy * toRad * 0.5f) / (float) Math.sin(fovy * toRad * 0.5f); - paramMatrix.m00 = cotangent / aspect; - paramMatrix.m01 = 0.0f; - paramMatrix.m02 = 0.0f; - paramMatrix.m03 = 0.0f; - paramMatrix.m10 = 0.0f; - paramMatrix.m11 = cotangent; - paramMatrix.m12 = 0.0f; - paramMatrix.m13 = 0.0f; - paramMatrix.m20 = 0.0f; - paramMatrix.m21 = 0.0f; - paramMatrix.m22 = (zFar + zNear) / (zFar - zNear); - paramMatrix.m23 = -1.0f; - paramMatrix.m30 = 0.0f; - paramMatrix.m31 = 0.0f; - paramMatrix.m32 = 2.0f * zFar * zNear / (zFar - zNear); - paramMatrix.m33 = 0.0f; - Matrix4f.mul(matrix, paramMatrix, matrix); + stateGlobalBlend = true; } public static final void gluLookAt(Vector3f eye, Vector3f center, Vector3f up) { Matrix4f matrix; - switch(stateMatrixMode) { + switch (stateMatrixMode) { case GL_MODELVIEW: matrix = modelMatrixStack[modelMatrixStackPointer]; modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; @@ -1141,8 +667,7 @@ public class GlStateManager { case GL_TEXTURE: int ptr = textureMatrixStackPointer[activeTexture]; matrix = textureMatrixStack[activeTexture][ptr]; - textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = - ++textureMatrixAccessSerial[activeTexture]; + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; break; } float x = center.x - eye.x; @@ -1184,57 +709,82 @@ public class GlStateManager { Matrix4f.mul(matrix, paramMatrix, matrix); } - public static final void transform(Vector4f vecIn, Vector4f vecOut) { + public static final void gluPerspective(float fovy, float aspect, float zNear, float zFar) { Matrix4f matrix; - switch(stateMatrixMode) { + switch (stateMatrixMode) { case GL_MODELVIEW: matrix = modelMatrixStack[modelMatrixStackPointer]; + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; break; case GL_PROJECTION: default: matrix = projectionMatrixStack[projectionMatrixStackPointer]; + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; break; case GL_TEXTURE: - matrix = textureMatrixStack[activeTexture][textureMatrixStackPointer[activeTexture]]; + int ptr = textureMatrixStackPointer[activeTexture]; + matrix = textureMatrixStack[activeTexture][ptr]; + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; break; } - Matrix4f.transform(matrix, vecIn, vecOut); + float cotangent = (float) Math.cos(fovy * toRad * 0.5f) / (float) Math.sin(fovy * toRad * 0.5f); + paramMatrix.m00 = cotangent / aspect; + paramMatrix.m01 = 0.0f; + paramMatrix.m02 = 0.0f; + paramMatrix.m03 = 0.0f; + paramMatrix.m10 = 0.0f; + paramMatrix.m11 = cotangent; + paramMatrix.m12 = 0.0f; + paramMatrix.m13 = 0.0f; + paramMatrix.m20 = 0.0f; + paramMatrix.m21 = 0.0f; + paramMatrix.m22 = (zFar + zNear) / (zFar - zNear); + paramMatrix.m23 = -1.0f; + paramMatrix.m30 = 0.0f; + paramMatrix.m31 = 0.0f; + paramMatrix.m32 = 2.0f * zFar * zNear / (zFar - zNear); + paramMatrix.m33 = 0.0f; + Matrix4f.mul(matrix, paramMatrix, matrix); } - private static final Matrix4f unprojA = new Matrix4f(); - private static final Matrix4f unprojB = new Matrix4f(); - private static final Vector4f unprojC = new Vector4f(); public static final void gluUnProject(float p1, float p2, float p3, float[] modelview, float[] projection, int[] viewport, float[] objectcoords) { unprojA.load(modelview); unprojB.load(projection); Matrix4f.mul(unprojA, unprojB, unprojB); unprojB.invert(); - unprojC.set(((p1 - (float)viewport[0]) / (float)viewport[2]) * 2f - 1f, - ((p2 - (float)viewport[1]) / (float)viewport[3]) * 2f - 1f, p3, 1.0f); + unprojC.set(((p1 - (float) viewport[0]) / (float) viewport[2]) * 2f - 1f, + ((p2 - (float) viewport[1]) / (float) viewport[3]) * 2f - 1f, p3, 1.0f); Matrix4f.transform(unprojB, unprojC, unprojC); objectcoords[0] = unprojC.x / unprojC.w; objectcoords[1] = unprojC.y / unprojC.w; objectcoords[2] = unprojC.z / unprojC.w; } - public static final void getMatrix(Matrix4f mat) { - switch(stateMatrixMode) { + public static final boolean isExtensionPipeline() { + return stateUseExtensionPipeline; + } + + public static final void loadIdentity() { + switch (stateMatrixMode) { case GL_MODELVIEW: - mat.load(modelMatrixStack[modelMatrixStackPointer]); + default: + modelMatrixStack[modelMatrixStackPointer].setIdentity(); + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; break; case GL_PROJECTION: - default: - mat.load(projectionMatrixStack[projectionMatrixStackPointer]); + projectionMatrixStack[projectionMatrixStackPointer].setIdentity(); + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; break; case GL_TEXTURE: - mat.load(textureMatrixStack[activeTexture][textureMatrixStackPointer[activeTexture]]); + textureMatrixStack[activeTexture][textureMatrixStackPointer[activeTexture]].setIdentity(); + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; break; } } public static final void loadMatrix(Matrix4f mat) { - switch(stateMatrixMode) { + switch (stateMatrixMode) { case GL_MODELVIEW: modelMatrixStack[modelMatrixStackPointer].load(mat); modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; @@ -1251,15 +801,504 @@ public class GlStateManager { } } - public static final int getModelViewSerial() { - return modelMatrixStackAccessSerial[modelMatrixStackPointer]; + public static final void matrixMode(int mode) { + stateMatrixMode = mode; } - public static final Matrix4f getModelViewReference() { - return modelMatrixStack[modelMatrixStackPointer]; + public static final void multMatrix(float[] matrix) { + Matrix4f modeMatrix; + + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modeMatrix = modelMatrixStack[modelMatrixStackPointer]; + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + modeMatrix = projectionMatrixStack[projectionMatrixStackPointer]; + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + modeMatrix = textureMatrixStack[activeTexture][ptr]; + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + + paramMatrix.load(matrix); + + Matrix4f.mul(modeMatrix, paramMatrix, modeMatrix); + } + + public static final void multMatrix(Matrix4f matrix) { + Matrix4f modeMatrix; + + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modeMatrix = modelMatrixStack[modelMatrixStackPointer]; + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + modeMatrix = projectionMatrixStack[projectionMatrixStackPointer]; + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + modeMatrix = textureMatrixStack[activeTexture][ptr]; + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + + Matrix4f.mul(modeMatrix, matrix, modeMatrix); + } + + public static final void ortho(double left, double right, double bottom, double top, double zNear, double zFar) { + Matrix4f matrix; + switch (stateMatrixMode) { + case GL_MODELVIEW: + matrix = modelMatrixStack[modelMatrixStackPointer]; + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + default: + matrix = projectionMatrixStack[projectionMatrixStackPointer]; + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + matrix = textureMatrixStack[activeTexture][ptr]; + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + paramMatrix.m00 = 2.0f / (float) (right - left); + paramMatrix.m01 = 0.0f; + paramMatrix.m02 = 0.0f; + paramMatrix.m03 = 0.0f; + paramMatrix.m10 = 0.0f; + paramMatrix.m11 = 2.0f / (float) (top - bottom); + paramMatrix.m12 = 0.0f; + paramMatrix.m13 = 0.0f; + paramMatrix.m20 = 0.0f; + paramMatrix.m21 = 0.0f; + paramMatrix.m22 = 2.0f / (float) (zFar - zNear); + paramMatrix.m23 = 0.0f; + paramMatrix.m30 = (float) (-(right + left) / (right - left)); + paramMatrix.m31 = (float) (-(top + bottom) / (top - bottom)); + paramMatrix.m32 = (float) ((zFar + zNear) / (zFar - zNear)); + paramMatrix.m33 = 1.0f; + Matrix4f.mul(matrix, paramMatrix, matrix); + } + + public static final void popLightCoords() { + if (stateLightsStackPointer > 0) { + --stateLightsStackPointer; + } else { + Throwable t = new IndexOutOfBoundsException("GL_LIGHT direction stack underflow!" + + " Called GlStateManager.popLightCoords on an empty light stack"); + logger.error(t); + } + } + + public static final void popMatrix() { + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + if (modelMatrixStackPointer > 0) { + --modelMatrixStackPointer; + } else { + Throwable t = new IndexOutOfBoundsException("GL_MODELVIEW matrix stack underflow!" + + " Called GlStateManager.popMatrix on an empty matrix stack"); + logger.error(t); + } + break; + case GL_PROJECTION: + if (projectionMatrixStackPointer > 0) { + --projectionMatrixStackPointer; + } else { + Throwable t = new IndexOutOfBoundsException("GL_PROJECTION matrix stack underflow!" + + " Called GlStateManager.popMatrix on an empty matrix stack"); + logger.error(t); + } + break; + case GL_TEXTURE: + if (textureMatrixStackPointer[activeTexture] > 0) { + --textureMatrixStackPointer[activeTexture]; + } else { + Throwable t = new IndexOutOfBoundsException("GL_TEXTURE #" + activeTexture + + " matrix stack underflow! Called GlStateManager.popMatrix on an empty matrix stack"); + logger.error(t); + } + break; + } + } + + static void populateStack(Matrix4f[] stack) { + for (int i = 0; i < stack.length; ++i) { + stack[i] = new Matrix4f(); + } + } + + static void populateStack(Matrix4f[][] stack) { + for (int i = 0; i < stack.length; ++i) { + populateStack(stack[i]); + } + } + + static void populateStack(Vector4f[][] stack) { + for (int i = 0; i < stack.length; ++i) { + for (int j = 0; j < stack[i].length; ++j) { + stack[i][j] = new Vector4f(0.0f, -1.0f, 0.0f, 0.0f); + } + } + } + + public static final void pushLightCoords() { + int push = stateLightsStackPointer + 1; + if (push < stateLightsStack.length) { + Vector4f[] copyFrom = stateLightsStack[stateLightsStackPointer]; + boolean[] copyFrom2 = stateLightsEnabled[stateLightsStackPointer]; + Vector4f[] copyTo = stateLightsStack[push]; + boolean[] copyTo2 = stateLightsEnabled[push]; + for (int i = 0; i < copyFrom.length; ++i) { + if (copyFrom2[i]) { + copyTo[i].set(copyFrom[i]); + copyTo2[i] = true; + } else { + copyTo2[i] = false; + } + } + stateLightingSerial[push] = stateLightingSerial[stateLightsStackPointer]; + stateLightsStackPointer = push; + } else { + Throwable t = new IndexOutOfBoundsException("GL_LIGHT direction stack overflow!" + " Exceeded " + + stateLightsStack.length + " calls to GlStateManager.pushLightCoords"); + logger.error(t); + } + } + + public static final void pushMatrix() { + int push; + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + push = modelMatrixStackPointer + 1; + if (push < modelMatrixStack.length) { + modelMatrixStack[push].load(modelMatrixStack[modelMatrixStackPointer]); + modelMatrixStackAccessSerial[push] = modelMatrixStackAccessSerial[modelMatrixStackPointer]; + modelMatrixStackPointer = push; + } else { + Throwable t = new IndexOutOfBoundsException("GL_MODELVIEW matrix stack overflow!" + " Exceeded " + + modelMatrixStack.length + " calls to GlStateManager.pushMatrix"); + logger.error(t); + } + break; + case GL_PROJECTION: + push = projectionMatrixStackPointer + 1; + if (push < projectionMatrixStack.length) { + projectionMatrixStack[push].load(projectionMatrixStack[projectionMatrixStackPointer]); + projectionMatrixStackAccessSerial[push] = projectionMatrixStackAccessSerial[projectionMatrixStackPointer]; + projectionMatrixStackPointer = push; + } else { + Throwable t = new IndexOutOfBoundsException("GL_PROJECTION matrix stack overflow!" + " Exceeded " + + projectionMatrixStack.length + " calls to GlStateManager.pushMatrix"); + logger.error(t); + } + break; + case GL_TEXTURE: + push = textureMatrixStackPointer[activeTexture] + 1; + if (push < textureMatrixStack.length) { + int ptr = textureMatrixStackPointer[activeTexture]; + textureMatrixStack[activeTexture][push].load(textureMatrixStack[activeTexture][ptr]); + textureMatrixStackAccessSerial[activeTexture][push] = textureMatrixStackAccessSerial[activeTexture][ptr]; + textureMatrixStackPointer[activeTexture] = push; + } else { + Throwable t = new IndexOutOfBoundsException("GL_TEXTURE #" + activeTexture + " matrix stack overflow!" + + " Exceeded " + textureMatrixStack.length + " calls to GlStateManager.pushMatrix"); + logger.error(t); + } + break; + } + } + + public static final void quickBindTexture(int unit, int texture) { + int unitBase = unit - GL_TEXTURE0; + if (texture != boundTexture[unitBase]) { + if (unitBase != activeTexture) { + _wglActiveTexture(unit); + } + _wglBindTexture(GL_TEXTURE_2D, EaglercraftGPU.mapTexturesGL.get(texture)); + boundTexture[unitBase] = texture; + if (unitBase != activeTexture) { + _wglActiveTexture(GL_TEXTURE0 + activeTexture); + } + } } public static void recompileShaders() { FixedFunctionPipeline.flushCache(); } + + public static final void resetColor() { + stateColorR = 1.0f; + stateColorG = 1.0f; + stateColorB = 1.0f; + stateColorA = 1.0f; + ++stateColorSerial; + } + + public static final void rotate(float angle, float x, float y, float z) { + paramVector.x = x; + paramVector.y = y; + paramVector.z = z; + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modelMatrixStack[modelMatrixStackPointer].rotate(angle * toRad, paramVector); + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + projectionMatrixStack[projectionMatrixStackPointer].rotate(angle * toRad, paramVector); + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + textureMatrixStack[activeTexture][ptr].rotate(angle * toRad, paramVector); + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + } + + public static final void scale(double x, double y, double z) { + paramVector.x = (float) x; + paramVector.y = (float) y; + paramVector.z = (float) z; + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modelMatrixStack[modelMatrixStackPointer].scale(paramVector); + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + projectionMatrixStack[projectionMatrixStackPointer].scale(paramVector); + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + textureMatrixStack[activeTexture][ptr].scale(paramVector); + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + } + + public static final void scale(float x, float y, float z) { + paramVector.x = x; + paramVector.y = y; + paramVector.z = z; + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modelMatrixStack[modelMatrixStackPointer].scale(paramVector); + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + projectionMatrixStack[projectionMatrixStackPointer].scale(paramVector); + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + textureMatrixStack[activeTexture][ptr].scale(paramVector); + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + } + + public static final void setActiveTexture(int texture) { + int textureIdx = texture - GL_TEXTURE0; + if (textureIdx != activeTexture) { + _wglActiveTexture(texture); + activeTexture = textureIdx; + } + } + + public static final void setBlendConstants(float r, float g, float b, float a) { + if (r != blendConstantR || g != blendConstantG || b != blendConstantB || a != blendConstantA) { + _wglBlendColor(r, g, b, a); + blendConstantR = r; + blendConstantG = g; + blendConstantB = b; + blendConstantA = a; + } + } + + public static final void setFog(int param) { + stateFogEXP = param == GL_EXP; + ++stateFogSerial; + } + + public static final void setFogDensity(float param) { + stateFogDensity = param; + ++stateFogSerial; + } + + public static final void setFogEnd(float param) { + stateFogEnd = param; + ++stateFogSerial; + } + + public static final void setFogStart(float param) { + stateFogStart = param; + ++stateFogSerial; + } + + public static final void setMCLightAmbient(float r, float g, float b) { + stateLightingAmbientR = r; + stateLightingAmbientG = g; + stateLightingAmbientB = b; + ++stateLightingAmbientSerial; + } + + public static final void setShaderBlendAdd(float r, float g, float b, float a) { + stateShaderBlendAddColorR = r; + stateShaderBlendAddColorG = g; + stateShaderBlendAddColorB = b; + stateShaderBlendAddColorA = a; + ++stateShaderBlendColorSerial; + } + + public static final void setShaderBlendSrc(float r, float g, float b, float a) { + stateShaderBlendSrcColorR = r; + stateShaderBlendSrcColorG = g; + stateShaderBlendSrcColorB = b; + stateShaderBlendSrcColorA = a; + ++stateShaderBlendColorSerial; + } + + public static final void shadeModel(int mode) { + + } + + public static final void texCoords2D(float x, float y) { + textureCoordsX[activeTexture] = x; + textureCoordsY[activeTexture] = y; + ++textureCoordsAccessSerial[activeTexture]; + } + + public static final void texCoords2DDirect(int tex, float x, float y) { + textureCoordsX[tex] = x; + textureCoordsY[tex] = y; + ++textureCoordsAccessSerial[tex]; + } + + public static final void texGen(GlStateManager.TexGen coord, int source) { + coord.source = source; + ++stateTexGenSerial; + } + + public static final void transform(Vector4f vecIn, Vector4f vecOut) { + Matrix4f matrix; + switch (stateMatrixMode) { + case GL_MODELVIEW: + matrix = modelMatrixStack[modelMatrixStackPointer]; + break; + case GL_PROJECTION: + default: + matrix = projectionMatrixStack[projectionMatrixStackPointer]; + break; + case GL_TEXTURE: + matrix = textureMatrixStack[activeTexture][textureMatrixStackPointer[activeTexture]]; + break; + } + Matrix4f.transform(matrix, vecIn, vecOut); + } + + public static final void translate(double x, double y, double z) { + paramVector.x = (float) x; + paramVector.y = (float) y; + paramVector.z = (float) z; + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modelMatrixStack[modelMatrixStackPointer].translate(paramVector); + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + projectionMatrixStack[projectionMatrixStackPointer].translate(paramVector); + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + textureMatrixStack[activeTexture][ptr].translate(paramVector); + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + } + + public static final void translate(float x, float y, float z) { + paramVector.x = x; + paramVector.y = y; + paramVector.z = z; + switch (stateMatrixMode) { + case GL_MODELVIEW: + default: + modelMatrixStack[modelMatrixStackPointer].translate(paramVector); + modelMatrixStackAccessSerial[modelMatrixStackPointer] = ++modelMatrixAccessSerial; + break; + case GL_PROJECTION: + projectionMatrixStack[projectionMatrixStackPointer].translate(paramVector); + projectionMatrixStackAccessSerial[projectionMatrixStackPointer] = ++projectionMatrixAccessSerial; + break; + case GL_TEXTURE: + int ptr = textureMatrixStackPointer[activeTexture]; + textureMatrixStack[activeTexture][ptr].translate(paramVector); + textureMatrixStackAccessSerial[activeTexture][textureMatrixStackPointer[activeTexture]] = ++textureMatrixAccessSerial[activeTexture]; + break; + } + } + + public static final void tryBlendFuncSeparate(int srcFactor, int dstFactor, int srcFactorAlpha, + int dstFactorAlpha) { + if (stateEnableOverlayFramebufferBlending) { // game overlay framebuffer in EntityRenderer.java + srcFactorAlpha = GL_ONE; + dstFactorAlpha = GL_ONE_MINUS_SRC_ALPHA; + } + int srcBits = (srcFactor | (srcFactorAlpha << 16)); + int dstBits = (dstFactor | (dstFactorAlpha << 16)); + if (srcBits != stateBlendSRC || dstBits != stateBlendDST) { + _wglBlendFuncSeparate(srcFactor, dstFactor, srcFactorAlpha, dstFactorAlpha); + stateBlendSRC = srcBits; + stateBlendDST = dstBits; + } + } + + static final void unbindTextureIfCached(int texture) { + boolean f1, f2 = false; + for (int i = 0; i < boundTexture.length; ++i) { + if (boundTexture[i] == texture) { + f1 = i != activeTexture; + if (f2 || f1) { + _wglActiveTexture(GL_TEXTURE0 + i); + f2 = f1; + } + _wglBindTexture(GL_TEXTURE_2D, null); + if (EaglercraftGPU.checkOpenGLESVersion() >= 300) { + _wglBindTexture(GL_TEXTURE_3D, null); + } + boundTexture[i] = -1; + } + } + if (f2) { + _wglActiveTexture(GL_TEXTURE0 + activeTexture); + } + } + + public static final void viewport(int x, int y, int w, int h) { + if (viewportX != x || viewportY != y || viewportW != w || viewportH != h) { + _wglViewport(x, y, w, h); + viewportX = x; + viewportY = y; + viewportW = w; + viewportH = h; + } + } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/HighPolyMesh.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/HighPolyMesh.java index 5dd7c5c1..393a05fa 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/HighPolyMesh.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/HighPolyMesh.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.opengl.FixedFunctionShader.FixedFunctionSta /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,6 +31,10 @@ public class HighPolyMesh { boolean hasTexture; + HighPolyMesh() { + + } + public HighPolyMesh(IBufferArrayGL vertexArray, IBufferGL vertexBuffer, IBufferGL indexBuffer, int vertexCount, int indexCount, boolean hasTexture) { this.vertexArray = vertexArray; @@ -40,27 +45,24 @@ public class HighPolyMesh { this.hasTexture = hasTexture; } - HighPolyMesh() { - - } - - public boolean isNull() { - return vertexArray == null; - } - - public int getVertexCount() { - return vertexCount; - } - - public int getIndexCount() { - return indexCount; + public int getAttribBits() { + return hasTexture ? (FixedFunctionState.STATE_HAS_ATTRIB_TEXTURE | FixedFunctionState.STATE_HAS_ATTRIB_NORMAL) + : FixedFunctionState.STATE_HAS_ATTRIB_NORMAL; } public boolean getHasTexture() { return hasTexture; } - public int getAttribBits() { - return hasTexture ? (FixedFunctionState.STATE_HAS_ATTRIB_TEXTURE | FixedFunctionState.STATE_HAS_ATTRIB_NORMAL) : FixedFunctionState.STATE_HAS_ATTRIB_NORMAL; + public int getIndexCount() { + return indexCount; + } + + public int getVertexCount() { + return vertexCount; + } + + public boolean isNull() { + return vertexArray == null; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/IExtPipelineCompiler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/IExtPipelineCompiler.java index 47f81355..7323eeb9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/IExtPipelineCompiler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/IExtPipelineCompiler.java @@ -5,35 +5,36 @@ import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IExtPipelineCompiler { + void destroyPipeline(IProgramGL shaderProgram, int stateCoreBits, int stateExtBits, Object[] userPointer); + + int getCoreStateMask(int stateExtBits); + + int getCurrentExtensionStateBits(int stateCoreBits); + + int getExtensionStatesCount(); + /** * @return new String[] { vshSource, fshSource } */ String[] getShaderSource(int stateCoreBits, int stateExtBits, Object[] userPointer); - int getExtensionStatesCount(); - - int getCurrentExtensionStateBits(int stateCoreBits); - - int getCoreStateMask(int stateExtBits); - void initializeNewShader(IProgramGL compiledProg, int stateCoreBits, int stateExtBits, Object[] userPointer); void updatePipeline(IProgramGL compiledProg, int stateCoreBits, int stateExtBits, Object[] userPointer); - void destroyPipeline(IProgramGL shaderProgram, int stateCoreBits, int stateExtBits, Object[] userPointer); - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ImageData.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ImageData.java index ec8cbb21..35b65610 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ImageData.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ImageData.java @@ -8,149 +8,147 @@ import net.lax1dude.eaglercraft.v1_8.internal.PlatformAssets; /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ImageData { - - public final int width; - public final int height; - public final int[] pixels; - public final boolean alpha; - - public ImageData(int width, int height, int[] pixels, boolean alpha) { - this.width = width; - this.height = height; - this.pixels = pixels; - this.alpha = alpha; - } - - public ImageData(int width, int height, boolean alpha) { - this.width = width; - this.height = height; - this.pixels = new int[width * height]; - this.alpha = alpha; - } - - public ImageData fillAlpha() { - for(int i = 0; i < pixels.length; ++i) { - pixels[i] = pixels[i] | 0xFF000000; - } - return this; - } - - public ImageData getSubImage(int x, int y, int pw, int ph) { - int[] img = new int[pw * ph]; - for(int i = 0; i < ph; ++i) { - System.arraycopy(pixels, (i + y) * this.width + x, img, i * pw, pw); - } - return new ImageData(pw, ph, img, alpha); - } public static String getMimeFromType(String nameOrPath) { - if(nameOrPath == null) return "image/png"; - nameOrPath = nameOrPath.toLowerCase(); - if(nameOrPath.endsWith(".png")) { + if (nameOrPath == null) return "image/png"; - }else if(nameOrPath.endsWith(".jpg") || nameOrPath.endsWith(".jpeg")) { + nameOrPath = nameOrPath.toLowerCase(); + if (nameOrPath.endsWith(".png")) { + return "image/png"; + } else if (nameOrPath.endsWith(".jpg") || nameOrPath.endsWith(".jpeg")) { return "image/jpeg"; - }else if(nameOrPath.endsWith(".gif")) { + } else if (nameOrPath.endsWith(".gif")) { return "image/gif"; - }else if(nameOrPath.endsWith(".bmp")) { + } else if (nameOrPath.endsWith(".bmp")) { return "image/bmp"; - }else { + } else { return "image/png"; // rip } } - public static final ImageData loadImageFile(String path) { - byte[] fileData = EagRuntime.getResourceBytes(path); - if(fileData != null) { - return loadImageFile(fileData); - }else { - return null; - } - } - - public static final ImageData loadImageFile(InputStream data) { - return PlatformAssets.loadImageFile(data); + public static boolean isNPOTStatic(int w, int h) { + return (w & (w - 1)) != 0 || (h & (h - 1)) != 0; } public static final ImageData loadImageFile(byte[] data) { return PlatformAssets.loadImageFile(data); } - public static final ImageData loadImageFile(String path, String mime) { - byte[] fileData = EagRuntime.getResourceBytes(path); - if(fileData != null) { - return loadImageFile(fileData, mime); - }else { - return null; - } + public static final ImageData loadImageFile(byte[] data, String mime) { + return PlatformAssets.loadImageFile(data, mime); + } + + public static final ImageData loadImageFile(InputStream data) { + return PlatformAssets.loadImageFile(data); } public static final ImageData loadImageFile(InputStream data, String mime) { return PlatformAssets.loadImageFile(data, mime); } - public static final ImageData loadImageFile(byte[] data, String mime) { - return PlatformAssets.loadImageFile(data, mime); + public static final ImageData loadImageFile(String path) { + byte[] fileData = EagRuntime.getResourceBytes(path); + if (fileData != null) { + return loadImageFile(fileData); + } else { + return null; + } } - public void getRGB(int startX, int startY, int w, int h, - int[] rgbArray, int offset, int scansize) { - for(int y = 0; y < h; ++y) { - System.arraycopy(pixels, offset + (y + startY) * scansize + startX, rgbArray, y * w, w); + public static final ImageData loadImageFile(String path, String mime) { + byte[] fileData = EagRuntime.getResourceBytes(path); + if (fileData != null) { + return loadImageFile(fileData, mime); + } else { + return null; } } - - public void copyPixelsFrom(ImageData input, int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2) { - if(sx2 - sx1 != dx2 - dx1) { - throw new IllegalArgumentException("Width of the copied region must match the" - + "width of the pasted region"); + + public static int swapRB(int c) { + return (c & 0xFF00FF00) | ((c & 0x00FF0000) >>> 16) | ((c & 0x000000FF) << 16); + } + + public static int[] swapRB(int[] arr) { + for (int i = 0; i < arr.length; ++i) { + int j = arr[i]; + arr[i] = (j & 0xFF00FF00) | ((j & 0x00FF0000) >>> 16) | ((j & 0x000000FF) << 16); + } + return arr; + } + + public final int width; + + public final int height; + + public final int[] pixels; + + public final boolean alpha; + + public ImageData(int width, int height, boolean alpha) { + this.width = width; + this.height = height; + this.pixels = new int[width * height]; + this.alpha = alpha; + } + + public ImageData(int width, int height, int[] pixels, boolean alpha) { + this.width = width; + this.height = height; + this.pixels = pixels; + this.alpha = alpha; + } + + public void copyPixelsFrom(ImageData input, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, + int sy2) { + if (sx2 - sx1 != dx2 - dx1) { + throw new IllegalArgumentException( + "Width of the copied region must match the" + "width of the pasted region"); } int cw = sx2 - sx1; - if(sy2 - sy1 != dy2 - dy1) { - throw new IllegalArgumentException("Height of the copied region must match the" - + "height of the pasted region"); + if (sy2 - sy1 != dy2 - dy1) { + throw new IllegalArgumentException( + "Height of the copied region must match the" + "height of the pasted region"); } int ch = sy2 - sy1; - for(int y = 0; y < ch; ++y) { + for (int y = 0; y < ch; ++y) { System.arraycopy(input.pixels, sx1 + (sy1 + y) * cw, pixels, dx1 + (dy1 + y) * cw, cw); } } - - public void drawLayer(ImageData input, int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2) { - if(sx2 - sx1 != dx2 - dx1) { - throw new IllegalArgumentException("Width of the copied region must match the" - + "width of the pasted region"); + + public void drawLayer(ImageData input, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2) { + if (sx2 - sx1 != dx2 - dx1) { + throw new IllegalArgumentException( + "Width of the copied region must match the" + "width of the pasted region"); } int cw = sx2 - sx1; - if(sy2 - sy1 != dy2 - dy1) { - throw new IllegalArgumentException("Height of the copied region must match the" - + "height of the pasted region"); + if (sy2 - sy1 != dy2 - dy1) { + throw new IllegalArgumentException( + "Height of the copied region must match the" + "height of the pasted region"); } int ch = sy2 - sy1; - for(int y = 0; y < ch; ++y) { - for(int x = 0; x < cw; ++x) { + for (int y = 0; y < ch; ++y) { + for (int x = 0; x < cw; ++x) { int si = (sy1 + y) * cw + sx1 + x; int di = (dy1 + y) * cw + dx1 + x; int spx = input.pixels[si]; int dpx = pixels[di]; - if((spx & 0xFF000000) == 0xFF000000 || (dpx & 0xFF000000) == 0) { + if ((spx & 0xFF000000) == 0xFF000000 || (dpx & 0xFF000000) == 0) { pixels[di] = spx; - }else { + } else { int sa = (spx >>> 24) & 0xFF; int da = (dpx >>> 24) & 0xFF; int r = ((spx >>> 16) & 0xFF) * sa / 255; @@ -161,41 +159,45 @@ public class ImageData { g += ((dpx >>> 8) & 0xFF) * aa / 65025; b += (dpx & 0xFF) * aa / 65025; sa += da; - if(sa > 0xFF) sa = 0xFF; + if (sa > 0xFF) + sa = 0xFF; pixels[di] = ((sa) << 24) | (r << 16) | (g << 8) | b; } } } } - - public ImageData swapRB() { - for(int i = 0; i < pixels.length; ++i) { - int j = pixels[i]; - pixels[i] = (j & 0xFF00FF00) | ((j & 0x00FF0000) >>> 16) | - ((j & 0x000000FF) << 16); + + public ImageData fillAlpha() { + for (int i = 0; i < pixels.length; ++i) { + pixels[i] = pixels[i] | 0xFF000000; } return this; } - - public static int swapRB(int c) { - return (c & 0xFF00FF00) | ((c & 0x00FF0000) >>> 16) | ((c & 0x000000FF) << 16); - } - - public static int[] swapRB(int[] arr) { - for(int i = 0; i < arr.length; ++i) { - int j = arr[i]; - arr[i] = (j & 0xFF00FF00) | ((j & 0x00FF0000) >>> 16) | - ((j & 0x000000FF) << 16); + + public void getRGB(int startX, int startY, int w, int h, int[] rgbArray, int offset, int scansize) { + for (int y = 0; y < h; ++y) { + System.arraycopy(pixels, offset + (y + startY) * scansize + startX, rgbArray, y * w, w); } - return arr; + } + + public ImageData getSubImage(int x, int y, int pw, int ph) { + int[] img = new int[pw * ph]; + for (int i = 0; i < ph; ++i) { + System.arraycopy(pixels, (i + y) * this.width + x, img, i * pw, pw); + } + return new ImageData(pw, ph, img, alpha); } public boolean isNPOT() { return (width & (width - 1)) != 0 || (height & (height - 1)) != 0; } - public static boolean isNPOTStatic(int w, int h) { - return (w & (w - 1)) != 0 || (h & (h - 1)) != 0; + public ImageData swapRB() { + for (int i = 0; i < pixels.length; ++i) { + int j = pixels[i]; + pixels[i] = (j & 0xFF00FF00) | ((j & 0x00FF0000) >>> 16) | ((j & 0x000000FF) << 16); + } + return this; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedFontRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedFontRenderer.java index 6c2839ab..86571560 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedFontRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedFontRenderer.java @@ -1,7 +1,39 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgramInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STREAM_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; @@ -20,14 +52,15 @@ import net.lax1dude.eaglercraft.v1_8.vector.Vector4f; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -68,17 +101,137 @@ public class InstancedFontRenderer { private static float stateColorBiasG = -999.0f; private static float stateColorBiasB = -999.0f; private static float stateColorBiasA = -999.0f; - + private static final Matrix4f tmpMatrix = new Matrix4f(); private static final Vector4f tmpVector = new Vector4f(); private static int stateModelMatrixSerial = -1; private static int stateProjectionMatrixSerial = -1; - + private static float charWidthValue = -1; private static float charHeightValue = -1; private static float charCoordWidthValue = -1.0f; private static float charCoordHeightValue = -1.0f; - + + private static ByteBuffer fontDataBuffer = null; + + private static int charactersDrawn = 0; + private static ByteBuffer fontBoldDataBuffer = null; + private static int boldCharactersDrawn = 0; + private static boolean hasOverflowed = false; + private static boolean hasBoldOverflowed = false; + private static boolean fogEnabled = false; + + private static int widthCalcLeast = Integer.MAX_VALUE; + private static int heightCalcLeast = Integer.MAX_VALUE; + private static int widthCalcMost = Integer.MAX_VALUE; + private static int heightCalcMost = Integer.MAX_VALUE; + + public static void appendBoldQuad(int x, int y, int cx, int cy, int color, boolean italic) { + if (hasBoldOverflowed) { + return; + } + if (boldCharactersDrawn >= CHARACTER_LIMIT) { + hasBoldOverflowed = true; + logger.error( + "Font renderer buffer has overflowed! Exceeded {} bold characters, no more bold characters will be rendered.", + CHARACTER_LIMIT); + return; + } + ++boldCharactersDrawn; + ByteBuffer buf = fontBoldDataBuffer; + buf.putShort((short) x); + buf.putShort((short) y); + buf.put((byte) cx); + buf.put((byte) cy); + color = ((color >>> 1) & 0x7F000000) | (color & 0xFFFFFF); + if (italic) { + color |= 0x80000000; + } + buf.putInt(color); + if (fogEnabled) { + updateBounds(x, y); + } + } + + public static void appendQuad(int x, int y, int cx, int cy, int color, boolean italic) { + if (hasOverflowed) { + return; + } + if (charactersDrawn >= CHARACTER_LIMIT) { + hasOverflowed = true; + logger.error( + "Font renderer buffer has overflowed! Exceeded {} regular characters, no more regular characters will be rendered.", + CHARACTER_LIMIT); + return; + } + ++charactersDrawn; + ByteBuffer buf = fontDataBuffer; + buf.putShort((short) x); + buf.putShort((short) y); + buf.put((byte) cx); + buf.put((byte) cy); + color = ((color >>> 1) & 0x7F000000) | (color & 0xFFFFFF); + if (italic) { + color |= 0x80000000; + } + buf.putInt(color); + if (fogEnabled) { + updateBounds(x, y); + } + } + + public static void begin() { + fontDataBuffer.clear(); + charactersDrawn = 0; + fontBoldDataBuffer.clear(); + boldCharactersDrawn = 0; + hasOverflowed = false; + hasBoldOverflowed = false; + fogEnabled = GlStateManager.stateFog && GlStateManager.stateFogDensity > 0.0f; + if (fogEnabled) { + widthCalcLeast = Integer.MAX_VALUE; + heightCalcLeast = Integer.MAX_VALUE; + widthCalcMost = Integer.MAX_VALUE; + heightCalcMost = Integer.MAX_VALUE; + } + } + + public static void destroy() { + if (fontDataBuffer != null) { + EagRuntime.freeByteBuffer(fontDataBuffer); + fontDataBuffer = null; + } + if (fontBoldDataBuffer != null) { + EagRuntime.freeByteBuffer(fontBoldDataBuffer); + fontBoldDataBuffer = null; + } + if (shaderProgram != null) { + _wglDeleteProgram(shaderProgram); + shaderProgram = null; + } + if (matrixCopyBuffer != null) { + EagRuntime.freeFloatBuffer(matrixCopyBuffer); + matrixCopyBuffer = null; + } + u_matrixTransform = null; + u_charSize2f = null; + u_charCoordSize2f = null; + u_color4f = null; + u_colorBias4f = null; + if (vertexArray != null) { + EaglercraftGPU.destroyGLBufferArray(vertexArray); + vertexArray = null; + } + if (vertexBuffer != null) { + _wglDeleteBuffers(vertexBuffer); + vertexBuffer = null; + } + if (instancesBuffer != null) { + _wglDeleteBuffers(instancesBuffer); + instancesBuffer = null; + } + } + static void initialize() { String vertexSource = EagRuntime.getRequiredResourceString(vertexShaderPath); String fragmentSource = EagRuntime.getRequiredResourceString(fragmentShaderPath); @@ -89,12 +242,12 @@ public class InstancedFontRenderer { _wglShaderSource(vert, GLSLHeader.getVertexHeaderCompat(vertexSource, vertexShaderPrecision)); _wglCompileShader(vert); - if(_wglGetShaderi(vert, GL_COMPILE_STATUS) != GL_TRUE) { + if (_wglGetShaderi(vert, GL_COMPILE_STATUS) != GL_TRUE) { logger.error("Failed to compile GL_VERTEX_SHADER \"" + vertexShaderPath + "\" for InstancedFontRenderer!"); String log = _wglGetShaderInfoLog(vert); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[VERT] {}", lines[i]); } } @@ -104,12 +257,13 @@ public class InstancedFontRenderer { _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(fragmentSource, fragmentShaderPrecision)); _wglCompileShader(frag); - if(_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { - logger.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for InstancedFontRenderer!"); + if (_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { + logger.error( + "Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for InstancedFontRenderer!"); String log = _wglGetShaderInfoLog(frag); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[FRAG] {}", lines[i]); } } @@ -121,7 +275,7 @@ public class InstancedFontRenderer { _wglAttachShader(shaderProgram, vert); _wglAttachShader(shaderProgram, frag); - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { VSHInputLayoutParser.applyLayout(shaderProgram, VSHInputLayoutParser.getShaderInputs(vertexSource)); } @@ -133,12 +287,12 @@ public class InstancedFontRenderer { _wglDeleteShader(vert); _wglDeleteShader(frag); - if(_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { + if (_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { logger.error("Failed to link shader program for InstancedFontRenderer!"); String log = _wglGetProgramInfoLog(shaderProgram); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[LINK] {}", lines[i]); } } @@ -167,25 +321,24 @@ public class InstancedFontRenderer { float paddingA = 0.005f; float paddingB = 1.0f - paddingA; verts.put(new float[] { - + // (0 - 6 - 12) regular: - - paddingA, paddingA, 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingA, 0.25f, - paddingB, paddingA, 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingB, 0.25f, - paddingA, paddingA, 0.0f, paddingA, paddingB, 0.0f, paddingB, paddingA, 0.0f, - paddingB, paddingA, 0.0f, paddingA, paddingB, 0.0f, paddingB, paddingB, 0.0f, + + paddingA, paddingA, 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingA, 0.25f, paddingB, paddingA, + 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingB, 0.25f, paddingA, paddingA, 0.0f, paddingA, + paddingB, 0.0f, paddingB, paddingA, 0.0f, paddingB, paddingA, 0.0f, paddingA, paddingB, 0.0f, paddingB, + paddingB, 0.0f, // (12 - 24 - 36) bold shadow: - paddingA, paddingA, 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingA, 0.25f, - paddingB, paddingA, 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingB, 0.25f, - paddingA, paddingA, 0.75f, paddingA, paddingB, 0.75f, paddingB, paddingA, 0.75f, - paddingB, paddingA, 0.75f, paddingA, paddingB, 0.75f, paddingB, paddingB, 0.75f, + paddingA, paddingA, 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingA, 0.25f, paddingB, paddingA, + 0.25f, paddingA, paddingB, 0.25f, paddingB, paddingB, 0.25f, paddingA, paddingA, 0.75f, paddingA, + paddingB, 0.75f, paddingB, paddingA, 0.75f, paddingB, paddingA, 0.75f, paddingA, paddingB, 0.75f, + paddingB, paddingB, 0.75f, - paddingA, paddingA, 0.0f, paddingA, paddingB, 0.0f, paddingB, paddingA, 0.0f, - paddingB, paddingA, 0.0f, paddingA, paddingB, 0.0f, paddingB, paddingB, 0.0f, - paddingA, paddingA, 0.5f, paddingA, paddingB, 0.5f, paddingB, paddingA, 0.5f, - paddingB, paddingA, 0.5f, paddingA, paddingB, 0.5f, paddingB, paddingB, 0.5f + paddingA, paddingA, 0.0f, paddingA, paddingB, 0.0f, paddingB, paddingA, 0.0f, paddingB, paddingA, 0.0f, + paddingA, paddingB, 0.0f, paddingB, paddingB, 0.0f, paddingA, paddingA, 0.5f, paddingA, paddingB, 0.5f, + paddingB, paddingA, 0.5f, paddingB, paddingA, 0.5f, paddingA, paddingB, 0.5f, paddingB, paddingB, 0.5f }); verts.flip(); @@ -215,61 +368,33 @@ public class InstancedFontRenderer { EaglercraftGPU.enableVertexAttribArray(3); EaglercraftGPU.vertexAttribPointer(3, 4, GL_UNSIGNED_BYTE, true, 10, 6); EaglercraftGPU.vertexAttribDivisor(3, 1); - + } - private static ByteBuffer fontDataBuffer = null; - private static int charactersDrawn = 0; - private static ByteBuffer fontBoldDataBuffer = null; - private static int boldCharactersDrawn = 0; - private static boolean hasOverflowed = false; - private static boolean hasBoldOverflowed = false; - - private static boolean fogEnabled = false; - private static int widthCalcLeast = Integer.MAX_VALUE; - private static int heightCalcLeast = Integer.MAX_VALUE; - private static int widthCalcMost = Integer.MAX_VALUE; - private static int heightCalcMost = Integer.MAX_VALUE; - - public static void begin() { - fontDataBuffer.clear(); - charactersDrawn = 0; - fontBoldDataBuffer.clear(); - boldCharactersDrawn = 0; - hasOverflowed = false; - hasBoldOverflowed = false; - fogEnabled = GlStateManager.stateFog && GlStateManager.stateFogDensity > 0.0f; - if(fogEnabled) { - widthCalcLeast = Integer.MAX_VALUE; - heightCalcLeast = Integer.MAX_VALUE; - widthCalcMost = Integer.MAX_VALUE; - heightCalcMost = Integer.MAX_VALUE; - } - } - - public static void render(float charWidth, float charHeight, float charCoordWidth, float charCoordHeight, boolean shadow) { - if(charactersDrawn == 0 && boldCharactersDrawn == 0) { + public static void render(float charWidth, float charHeight, float charCoordWidth, float charCoordHeight, + boolean shadow) { + if (charactersDrawn == 0 && boldCharactersDrawn == 0) { return; } EaglercraftGPU.bindGLShaderProgram(shaderProgram); - - if(charWidth != charWidthValue || charHeight != charHeightValue) { + + if (charWidth != charWidthValue || charHeight != charHeightValue) { charWidthValue = charWidth; charHeightValue = charHeight; - _wglUniform2f(u_charSize2f, (float)charWidth, (float)charHeight); + _wglUniform2f(u_charSize2f, (float) charWidth, (float) charHeight); } - - if(charCoordWidth != charCoordWidthValue || charCoordHeight != charCoordHeightValue) { + + if (charCoordWidth != charCoordWidthValue || charCoordHeight != charCoordHeightValue) { charCoordWidthValue = charCoordWidth; charCoordHeightValue = charCoordHeight; _wglUniform2f(u_charCoordSize2f, charCoordWidth, charCoordHeight); } - + int ptr1 = GlStateManager.modelMatrixStackPointer; int serial1 = GlStateManager.modelMatrixStackAccessSerial[ptr1]; int ptr2 = GlStateManager.projectionMatrixStackPointer; int serial2 = GlStateManager.projectionMatrixStackAccessSerial[ptr2]; - if(stateModelMatrixSerial != serial1 || stateProjectionMatrixSerial != serial2) { + if (stateModelMatrixSerial != serial1 || stateProjectionMatrixSerial != serial2) { stateModelMatrixSerial = serial1; stateProjectionMatrixSerial = serial2; Matrix4f.mul(GlStateManager.projectionMatrixStack[ptr2], GlStateManager.modelMatrixStack[ptr1], tmpMatrix); @@ -278,17 +403,16 @@ public class InstancedFontRenderer { matrixCopyBuffer.flip(); _wglUniformMatrix4fv(u_matrixTransform, false, matrixCopyBuffer); } - - if(!fogEnabled || DeferredStateManager.isInDeferredPass()) { + + if (!fogEnabled || DeferredStateManager.isInDeferredPass()) { int serial = GlStateManager.stateColorSerial; - if(stateColorSerial != serial) { + if (stateColorSerial != serial) { stateColorSerial = serial; float r = GlStateManager.stateColorR; float g = GlStateManager.stateColorG; float b = GlStateManager.stateColorB; float a = GlStateManager.stateColorA; - if(stateColorR != r || stateColorG != g || - stateColorB != b || stateColorA != a) { + if (stateColorR != r || stateColorG != g || stateColorB != b || stateColorA != a) { _wglUniform4f(u_color4f, r, g, b, a); stateColorR = r; stateColorG = g; @@ -296,19 +420,19 @@ public class InstancedFontRenderer { stateColorA = a; } } - if(stateColorBiasR != 0.0f || stateColorBiasG != 0.0f || - stateColorBiasB != 0.0f || stateColorBiasA != 0.0f) { + if (stateColorBiasR != 0.0f || stateColorBiasG != 0.0f || stateColorBiasB != 0.0f + || stateColorBiasA != 0.0f) { _wglUniform4f(u_colorBias4f, 0.0f, 0.0f, 0.0f, 0.0f); stateColorBiasR = 0.0f; stateColorBiasG = 0.0f; stateColorBiasB = 0.0f; stateColorBiasA = 0.0f; } - }else { + } else { stateColorSerial = -1; Vector4f vec4 = tmpVector; - vec4.x = (float)(widthCalcLeast + (widthCalcMost - widthCalcLeast + 1.0f) * 0.5f) * charWidth; - vec4.y = (float)(heightCalcLeast + (heightCalcMost - heightCalcLeast + 1.0f) * 0.5f)* charHeight; + vec4.x = (float) (widthCalcLeast + (widthCalcMost - widthCalcLeast + 1.0f) * 0.5f) * charWidth; + vec4.y = (float) (heightCalcLeast + (heightCalcMost - heightCalcLeast + 1.0f) * 0.5f) * charHeight; vec4.z = 0.0f; vec4.w = 1.0f; @@ -324,14 +448,17 @@ public class InstancedFontRenderer { vec4.z *= vec4.z; float fogFactor = (float) Math.sqrt(vec4.x + vec4.y + vec4.z); - if(GlStateManager.stateFogEXP) { + if (GlStateManager.stateFogEXP) { fogFactor = 1.0f - (float) Math.pow(2.718, -(GlStateManager.stateFogDensity * fogFactor)); - }else { - fogFactor = (fogFactor - GlStateManager.stateFogStart) / (GlStateManager.stateFogEnd - GlStateManager.stateFogStart); + } else { + fogFactor = (fogFactor - GlStateManager.stateFogStart) + / (GlStateManager.stateFogEnd - GlStateManager.stateFogStart); } - if(fogFactor > 1.0f) fogFactor = 1.0f; - if(fogFactor < 0.0f) fogFactor = 0.0f; + if (fogFactor > 1.0f) + fogFactor = 1.0f; + if (fogFactor < 0.0f) + fogFactor = 0.0f; float r = GlStateManager.stateColorR; float g = GlStateManager.stateColorG; @@ -343,8 +470,7 @@ public class InstancedFontRenderer { g *= fogFactor2; b *= fogFactor2; - if(stateColorR != r || stateColorG != g || - stateColorB != b || stateColorA != a) { + if (stateColorR != r || stateColorG != g || stateColorB != b || stateColorA != a) { _wglUniform4f(u_color4f, r, g, b, a); stateColorR = r; stateColorG = g; @@ -358,8 +484,8 @@ public class InstancedFontRenderer { float biasB = GlStateManager.stateFogColorB * fogFactor; float biasA = 0.0f; - if(stateColorBiasR != biasR || stateColorBiasG != biasG || - stateColorBiasB != biasB || stateColorBiasA != biasA) { + if (stateColorBiasR != biasR || stateColorBiasG != biasG || stateColorBiasB != biasB + || stateColorBiasA != biasA) { _wglUniform4f(u_colorBias4f, biasR, biasG, biasB, biasA); stateColorBiasR = biasR; stateColorBiasG = biasG; @@ -371,7 +497,7 @@ public class InstancedFontRenderer { EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); EaglercraftGPU.bindGLBufferArray(vertexArray); - if(charactersDrawn > 0) { + if (charactersDrawn > 0) { int p = fontDataBuffer.position(); int l = fontDataBuffer.limit(); @@ -384,7 +510,7 @@ public class InstancedFontRenderer { EaglercraftGPU.doDrawArraysInstanced(GL_TRIANGLES, shadow ? 0 : 6, shadow ? 12 : 6, charactersDrawn); } - if(boldCharactersDrawn > 0) { + if (boldCharactersDrawn > 0) { int p = fontBoldDataBuffer.position(); int l = fontBoldDataBuffer.limit(); @@ -398,97 +524,15 @@ public class InstancedFontRenderer { } } - public static void appendQuad(int x, int y, int cx, int cy, int color, boolean italic) { - if(hasOverflowed) { - return; - } - if(charactersDrawn >= CHARACTER_LIMIT) { - hasOverflowed = true; - logger.error("Font renderer buffer has overflowed! Exceeded {} regular characters, no more regular characters will be rendered.", CHARACTER_LIMIT); - return; - } - ++charactersDrawn; - ByteBuffer buf = fontDataBuffer; - buf.putShort((short)x); - buf.putShort((short)y); - buf.put((byte)cx); - buf.put((byte)cy); - color = ((color >>> 1) & 0x7F000000) | (color & 0xFFFFFF); - if(italic) { - color |= 0x80000000; - } - buf.putInt(color); - if(fogEnabled) { - updateBounds(x, y); - } - } - - public static void appendBoldQuad(int x, int y, int cx, int cy, int color, boolean italic) { - if(hasBoldOverflowed) { - return; - } - if(boldCharactersDrawn >= CHARACTER_LIMIT) { - hasBoldOverflowed = true; - logger.error("Font renderer buffer has overflowed! Exceeded {} bold characters, no more bold characters will be rendered.", CHARACTER_LIMIT); - return; - } - ++boldCharactersDrawn; - ByteBuffer buf = fontBoldDataBuffer; - buf.putShort((short)x); - buf.putShort((short)y); - buf.put((byte)cx); - buf.put((byte)cy); - color = ((color >>> 1) & 0x7F000000) | (color & 0xFFFFFF); - if(italic) { - color |= 0x80000000; - } - buf.putInt(color); - if(fogEnabled) { - updateBounds(x, y); - } - } - private static final void updateBounds(int x, int y) { - if(x < widthCalcLeast || widthCalcLeast == Integer.MAX_VALUE) widthCalcLeast = x; - if(x > widthCalcMost || widthCalcMost == Integer.MAX_VALUE) widthCalcMost = x; - if(y < heightCalcLeast || heightCalcLeast == Integer.MAX_VALUE) heightCalcLeast = y; - if(y > heightCalcMost || heightCalcMost == Integer.MAX_VALUE) heightCalcMost = y; - } - - public static void destroy() { - if(fontDataBuffer != null) { - EagRuntime.freeByteBuffer(fontDataBuffer); - fontDataBuffer = null; - } - if(fontBoldDataBuffer != null) { - EagRuntime.freeByteBuffer(fontBoldDataBuffer); - fontBoldDataBuffer = null; - } - if(shaderProgram != null) { - _wglDeleteProgram(shaderProgram); - shaderProgram = null; - } - if(matrixCopyBuffer != null) { - EagRuntime.freeFloatBuffer(matrixCopyBuffer); - matrixCopyBuffer = null; - } - u_matrixTransform = null; - u_charSize2f = null; - u_charCoordSize2f = null; - u_color4f = null; - u_colorBias4f = null; - if(vertexArray != null) { - EaglercraftGPU.destroyGLBufferArray(vertexArray); - vertexArray = null; - } - if(vertexBuffer != null) { - _wglDeleteBuffers(vertexBuffer); - vertexBuffer = null; - } - if(instancesBuffer != null) { - _wglDeleteBuffers(instancesBuffer); - instancesBuffer = null; - } + if (x < widthCalcLeast || widthCalcLeast == Integer.MAX_VALUE) + widthCalcLeast = x; + if (x > widthCalcMost || widthCalcMost == Integer.MAX_VALUE) + widthCalcMost = x; + if (y < heightCalcLeast || heightCalcLeast == Integer.MAX_VALUE) + heightCalcLeast = y; + if (y > heightCalcMost || heightCalcMost == Integer.MAX_VALUE) + heightCalcMost = y; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedParticleRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedParticleRenderer.java index 3ac10ab7..db5e8998 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedParticleRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/InstancedParticleRenderer.java @@ -1,7 +1,40 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgramInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STREAM_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; @@ -18,14 +51,15 @@ import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,7 +99,7 @@ public class InstancedParticleRenderer { private static float stateColorB = -999.0f; private static float stateColorA = -999.0f; private static int stateColorSerial = -1; - + private static final Matrix4f tmpMatrix = new Matrix4f(); private static int stateModelMatrixSerial = -1; private static int stateProjectionMatrixSerial = -1; @@ -80,6 +114,77 @@ public class InstancedParticleRenderer { private static float stateTransformParam4 = -999.0f; private static float stateTransformParam5 = -999.0f; + public static void appendParticle(float posX, float posY, float posZ, int particleTextureX, int particleTextureY, + int lightMapX, int lightMapY, int particleSize, int particleTexSize, float r, float g, float b, float a) { + int color = ((int) (a * 255.0f) << 24) | ((int) (r * 255.0f) << 16) | ((int) (g * 255.0f) << 8) + | (int) (b * 255.0f); + appendParticle(posX, posY, posZ, particleTextureX, particleTextureY, lightMapX, lightMapY, particleSize, + particleTexSize, color); + } + + public static void appendParticle(float posX, float posY, float posZ, int particleTextureX, int particleTextureY, + int lightMapX, int lightMapY, int particleSize, int particleTexSize, int rgba) { + if (particlesHasOverflowed) { + return; + } + if (particleCount >= PARTICLE_LIMIT) { + particlesHasOverflowed = true; + logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", + PARTICLE_LIMIT); + return; + } + ++particleCount; + ByteBuffer buf = particleBuffer; + buf.putFloat(posX); + buf.putFloat(posY); + buf.putFloat(posZ); + buf.putShort((short) particleTextureX); + buf.putShort((short) particleTextureY); + buf.put((byte) lightMapX); + buf.put((byte) lightMapY); + buf.put((byte) particleSize); + buf.put((byte) particleTexSize); + buf.putInt(rgba); + } + + public static void begin() { + particleBuffer.clear(); + particleCount = 0; + particlesHasOverflowed = false; + } + + public static void destroy() { + if (particleBuffer != null) { + EagRuntime.freeByteBuffer(particleBuffer); + particleBuffer = null; + } + if (shaderProgram != null) { + _wglDeleteProgram(shaderProgram); + shaderProgram = null; + } + if (matrixCopyBuffer != null) { + EagRuntime.freeFloatBuffer(matrixCopyBuffer); + matrixCopyBuffer = null; + } + u_matrixTransform = null; + u_texCoordSize2f_particleSize1f = null; + u_transformParam_1_2_5_f = null; + u_transformParam_3_4_f = null; + u_color4f = null; + if (vertexArray != null) { + EaglercraftGPU.destroyGLBufferArray(vertexArray); + vertexArray = null; + } + if (vertexBuffer != null) { + _wglDeleteBuffers(vertexBuffer); + vertexBuffer = null; + } + if (instancesBuffer != null) { + _wglDeleteBuffers(instancesBuffer); + instancesBuffer = null; + } + } + static void initialize() { String vertexSource = EagRuntime.getRequiredResourceString(vertexShaderPath); String fragmentSource = EagRuntime.getRequiredResourceString(fragmentShaderPath); @@ -90,12 +195,13 @@ public class InstancedParticleRenderer { _wglShaderSource(vert, GLSLHeader.getVertexHeaderCompat(vertexSource, vertexShaderPrecision)); _wglCompileShader(vert); - if(_wglGetShaderi(vert, GL_COMPILE_STATUS) != GL_TRUE) { - logger.error("Failed to compile GL_VERTEX_SHADER \"" + vertexShaderPath + "\" for InstancedParticleRenderer!"); + if (_wglGetShaderi(vert, GL_COMPILE_STATUS) != GL_TRUE) { + logger.error( + "Failed to compile GL_VERTEX_SHADER \"" + vertexShaderPath + "\" for InstancedParticleRenderer!"); String log = _wglGetShaderInfoLog(vert); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[VERT] {}", lines[i]); } } @@ -105,12 +211,13 @@ public class InstancedParticleRenderer { _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(fragmentSource, fragmentShaderPrecision)); _wglCompileShader(frag); - if(_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { - logger.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for InstancedParticleRenderer!"); + if (_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { + logger.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + + "\" for InstancedParticleRenderer!"); String log = _wglGetShaderInfoLog(frag); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[FRAG] {}", lines[i]); } } @@ -122,7 +229,7 @@ public class InstancedParticleRenderer { _wglAttachShader(shaderProgram, vert); _wglAttachShader(shaderProgram, frag); - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { VSHInputLayoutParser.applyLayout(shaderProgram, VSHInputLayoutParser.getShaderInputs(vertexSource)); } @@ -134,12 +241,12 @@ public class InstancedParticleRenderer { _wglDeleteShader(vert); _wglDeleteShader(frag); - if(_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { + if (_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { logger.error("Failed to link shader program for InstancedParticleRenderer!"); String log = _wglGetProgramInfoLog(shaderProgram); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[LINK] {}", lines[i]); } } @@ -165,10 +272,7 @@ public class InstancedParticleRenderer { instancesBuffer = _wglGenBuffers(); FloatBuffer verts = EagRuntime.allocateFloatBuffer(12); - verts.put(new float[] { - -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, - -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f - }); + verts.put(new float[] { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f }); verts.flip(); EaglercraftGPU.bindGLBufferArray(vertexArray); @@ -207,45 +311,9 @@ public class InstancedParticleRenderer { } - public static void begin() { - particleBuffer.clear(); - particleCount = 0; - particlesHasOverflowed = false; - } - - public static void appendParticle(float posX, float posY, float posZ, int particleTextureX, int particleTextureY, - int lightMapX, int lightMapY, int particleSize, int particleTexSize, float r, float g, float b, float a) { - int color = ((int)(a * 255.0f) << 24) | ((int)(r * 255.0f) << 16) | ((int)(g * 255.0f) << 8) | (int)(b * 255.0f); - appendParticle(posX, posY, posZ, particleTextureX, particleTextureY, lightMapX, lightMapY, particleSize, particleTexSize, color); - } - - public static void appendParticle(float posX, float posY, float posZ, int particleTextureX, int particleTextureY, - int lightMapX, int lightMapY, int particleSize, int particleTexSize, int rgba) { - if(particlesHasOverflowed) { - return; - } - if(particleCount >= PARTICLE_LIMIT) { - particlesHasOverflowed = true; - logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", PARTICLE_LIMIT); - return; - } - ++particleCount; - ByteBuffer buf = particleBuffer; - buf.putFloat(posX); - buf.putFloat(posY); - buf.putFloat(posZ); - buf.putShort((short)particleTextureX); - buf.putShort((short)particleTextureY); - buf.put((byte)lightMapX); - buf.put((byte)lightMapY); - buf.put((byte)particleSize); - buf.put((byte)particleTexSize); - buf.putInt(rgba); - } - public static void render(float texCoordWidth, float texCoordHeight, float particleCoordSize, float transformParam1, float transformParam2, float transformParam3, float transformParam4, float transformParam5) { - if(particleCount == 0) { + if (particleCount == 0) { return; } EaglercraftGPU.bindGLShaderProgram(shaderProgram); @@ -273,14 +341,13 @@ public class InstancedParticleRenderer { } int serial = GlStateManager.stateColorSerial; - if(stateColorSerial != serial) { + if (stateColorSerial != serial) { stateColorSerial = serial; float r = GlStateManager.stateColorR; float g = GlStateManager.stateColorG; float b = GlStateManager.stateColorB; float a = GlStateManager.stateColorA; - if(stateColorR != r || stateColorG != g || - stateColorB != b || stateColorA != a) { + if (stateColorR != r || stateColorG != g || stateColorB != b || stateColorA != a) { _wglUniform4f(u_color4f, r, g, b, a); stateColorR = r; stateColorG = g; @@ -293,7 +360,7 @@ public class InstancedParticleRenderer { int serial1 = GlStateManager.modelMatrixStackAccessSerial[ptr1]; int ptr2 = GlStateManager.projectionMatrixStackPointer; int serial2 = GlStateManager.projectionMatrixStackAccessSerial[ptr2]; - if(stateModelMatrixSerial != serial1 || stateProjectionMatrixSerial != serial2) { + if (stateModelMatrixSerial != serial1 || stateProjectionMatrixSerial != serial2) { stateModelMatrixSerial = serial1; stateProjectionMatrixSerial = serial2; Matrix4f.mul(GlStateManager.projectionMatrixStack[ptr2], GlStateManager.modelMatrixStack[ptr1], tmpMatrix); @@ -305,7 +372,7 @@ public class InstancedParticleRenderer { EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); EaglercraftGPU.bindGLBufferArray(vertexArray); - + int p = particleBuffer.position(); int l = particleBuffer.limit(); @@ -319,39 +386,8 @@ public class InstancedParticleRenderer { } public static void stupidColorSetHack(IUniformGL color4f) { - _wglUniform4f(color4f, GlStateManager.stateColorR, GlStateManager.stateColorG, GlStateManager.stateColorB, GlStateManager.stateColorA); - } - - public static void destroy() { - if(particleBuffer != null) { - EagRuntime.freeByteBuffer(particleBuffer); - particleBuffer = null; - } - if(shaderProgram != null) { - _wglDeleteProgram(shaderProgram); - shaderProgram = null; - } - if(matrixCopyBuffer != null) { - EagRuntime.freeFloatBuffer(matrixCopyBuffer); - matrixCopyBuffer = null; - } - u_matrixTransform = null; - u_texCoordSize2f_particleSize1f = null; - u_transformParam_1_2_5_f = null; - u_transformParam_3_4_f = null; - u_color4f = null; - if(vertexArray != null) { - EaglercraftGPU.destroyGLBufferArray(vertexArray); - vertexArray = null; - } - if(vertexBuffer != null) { - _wglDeleteBuffers(vertexBuffer); - vertexBuffer = null; - } - if(instancesBuffer != null) { - _wglDeleteBuffers(instancesBuffer); - instancesBuffer = null; - } + _wglUniform4f(color4f, GlStateManager.stateColorR, GlStateManager.stateColorG, GlStateManager.stateColorB, + GlStateManager.stateColorA); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/OpenGlHelper.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/OpenGlHelper.java index c110e6a6..9c673b88 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/OpenGlHelper.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/OpenGlHelper.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,6 +27,5 @@ public class OpenGlHelper { GlStateManager.texCoords2D(x, y); GlStateManager.setActiveTexture(defaultTexUnit); } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/RealOpenGLEnums.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/RealOpenGLEnums.java index a37d0b56..b960c8b0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/RealOpenGLEnums.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/RealOpenGLEnums.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl; /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferArray.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferArray.java index 1a111a80..850a05f0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferArray.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferArray.java @@ -1,187 +1,31 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDisableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribDivisor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; + import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; import net.lax1dude.eaglercraft.v1_8.internal.IBufferGL; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ class SoftGLBufferArray implements IBufferArrayGL { - Attrib[] attribs = new Attrib[4]; - int[] attribDivisors = null; - int hasAttribDivisorMask = 0; - int enabled = 0; - int enabledCnt = -1; - IBufferGL indexBuffer = null; - - SoftGLBufferArray() { - } - - void setAttrib(IBufferGL buffer, int index, int size, int format, boolean normalized, int stride, int offset) { - if(index >= attribs.length) { - int newLen = attribs.length << 1; - while(newLen <= index) { - newLen <<= 1; - } - Attrib[] newAttrib = new Attrib[newLen]; - System.arraycopy(attribs, 0, newAttrib, 0, attribs.length); - attribs = newAttrib; - } - attribs[index] = new Attrib(buffer, size, format, normalized, stride, offset); - } - - void setAttribDivisor(int index, int divisor) { - if(attribDivisors == null) { - if(divisor != 0) { - int newLen = 8; - while(newLen <= index) { - newLen <<= 1; - } - attribDivisors = new int[newLen]; - } - }else if(index >= attribDivisors.length) { - int newLen = attribDivisors.length << 1; - while(newLen <= index) { - newLen <<= 1; - } - int[] newDivisor = new int[newLen]; - System.arraycopy(attribDivisors, 0, newDivisor, 0, attribDivisors.length); - attribDivisors = newDivisor; - } - if(attribDivisors != null) { - attribDivisors[index] = divisor; - if(divisor != 0) { - hasAttribDivisorMask |= (1 << index); - }else { - hasAttribDivisorMask &= ~(1 << index); - } - } - } - - void enableAttrib(int index, boolean en) { - if(en) { - enabled |= (1 << index); - }else { - enabled &= ~(1 << index); - } - enabledCnt = 32 - Integer.numberOfLeadingZeros(enabled); - } - - void setIndexBuffer(IBufferGL buffer) { - indexBuffer = buffer; - } - - void transitionToState(SoftGLBufferState previousState, boolean elements) { - int oldEnabled = previousState.oldEnabled; - int oldEnabledCnt = previousState.oldEnabledCnt; - int[] oldAttribDivisors = previousState.attribDivisors; - int oldHasAttribDivisorMask = previousState.hasAttribDivisorMask; - Attrib[] oldAttrs = previousState.attribs; - boolean instancingCapable = EaglercraftGPU.checkInstancingCapable(); - int enCnt = enabledCnt; - int en = enabled; - Attrib[] attrs = attribs; - int[] divs = attribDivisors; - int hasDivs = hasAttribDivisorMask; - if(oldEnabledCnt >= 0) { - int enMax = Math.max(enCnt, oldEnabledCnt); - for(int i = 0, ii; i < enMax; ++i) { - ii = (1 << i); - boolean old = i < oldEnabledCnt && (oldEnabled & ii) != 0; - boolean _new = i < enCnt && (en & ii) != 0; - if(_new) { - if(!old) { - _wglEnableVertexAttribArray(i); - } - Attrib attr = i < attrs.length ? attrs[i] : null; - if(attr != null) { - Attrib oldAttr = oldAttrs[i]; - if(oldAttr == null || !oldAttr.equalsExplicit(attr)) { - EaglercraftGPU.bindGLArrayBuffer(attr.buffer); - _wglVertexAttribPointer(i, attr.size, attr.format, attr.normalized, attr.stride, attr.offset); - oldAttrs[i] = attr; - } - }else { - oldAttrs[i] = null; - } - if(instancingCapable) { - // instancing is uncommon - if((hasDivs & ii) != 0) { - int newDivisor = divs[i]; - if((oldHasAttribDivisorMask & ii) == 0 || newDivisor != oldAttribDivisors[i]) { - _wglVertexAttribDivisor(i, newDivisor); - oldAttribDivisors[i] = newDivisor; - previousState.hasAttribDivisorMask |= ii; - } - }else { - if((oldHasAttribDivisorMask & ii) != 0) { - _wglVertexAttribDivisor(i, 0); - oldAttribDivisors[i] = 0; - previousState.hasAttribDivisorMask &= ~ii; - } - } - } - }else if(old) { - _wglDisableVertexAttribArray(i); - } - } - }else { - // Bootstrap code for the emulator's first draw - for(int i = 0; i < enCnt; ++i) { - int ii = (1 << i); - if((en & ii) != 0) { - _wglEnableVertexAttribArray(i); - Attrib attr = attrs[i]; - if(attr != null) { - EaglercraftGPU.bindGLArrayBuffer(attr.buffer); - _wglVertexAttribPointer(i, attr.size, attr.format, attr.normalized, attr.stride, attr.offset); - oldAttrs[i] = attr; - }else { - oldAttrs[i] = null; - } - if(instancingCapable) { - if((hasDivs & ii) != 0) { - int newDivisor = divs[i]; - _wglVertexAttribDivisor(i, newDivisor); - oldAttribDivisors[i] = newDivisor; - previousState.hasAttribDivisorMask |= ii; - }else { - _wglVertexAttribDivisor(i, 0); - oldAttribDivisors[i] = 0; - } - } - } - } - } - if(elements) { - IBufferGL indexBufferL = indexBuffer; - if(indexBufferL != null) { - EaglercraftGPU.bindEmulatedVAOIndexBuffer(indexBufferL); - } - } - previousState.oldEnabled = en & ((1 << enCnt) - 1); - previousState.oldEnabledCnt = enCnt; - } - - @Override - public void free() { - } - static class Attrib { final IBufferGL buffer; @@ -205,21 +49,187 @@ class SoftGLBufferArray implements IBufferArrayGL { + stride) * 31 + offset; } + public boolean equals(Object obj) { + if (obj == this) + return true; + if (!(obj instanceof Attrib)) + return false; + Attrib o2 = (Attrib) obj; + return o2.hash == hash && o2.buffer == buffer && o2.checkVal == checkVal && o2.stride == stride + && o2.offset == offset; + } + + public boolean equalsExplicit(Attrib o2) { + return o2 == this || (o2.hash == hash && o2.buffer == buffer && o2.checkVal == checkVal + && o2.stride == stride && o2.offset == offset); + } + public int hashCode() { return hash; } - public boolean equals(Object obj) { - if(obj == this) return true; - if(!(obj instanceof Attrib)) return false; - Attrib o2 = (Attrib)obj; - return o2.hash == hash && o2.buffer == buffer && o2.checkVal == checkVal && o2.stride == stride && o2.offset == offset; - } + } - public boolean equalsExplicit(Attrib o2) { - return o2 == this || (o2.hash == hash && o2.buffer == buffer && o2.checkVal == checkVal && o2.stride == stride && o2.offset == offset); - } + Attrib[] attribs = new Attrib[4]; + int[] attribDivisors = null; + int hasAttribDivisorMask = 0; + int enabled = 0; + int enabledCnt = -1; + IBufferGL indexBuffer = null; + + SoftGLBufferArray() { + } + + void enableAttrib(int index, boolean en) { + if (en) { + enabled |= (1 << index); + } else { + enabled &= ~(1 << index); + } + enabledCnt = 32 - Integer.numberOfLeadingZeros(enabled); + } + + @Override + public void free() { + } + + void setAttrib(IBufferGL buffer, int index, int size, int format, boolean normalized, int stride, int offset) { + if (index >= attribs.length) { + int newLen = attribs.length << 1; + while (newLen <= index) { + newLen <<= 1; + } + Attrib[] newAttrib = new Attrib[newLen]; + System.arraycopy(attribs, 0, newAttrib, 0, attribs.length); + attribs = newAttrib; + } + attribs[index] = new Attrib(buffer, size, format, normalized, stride, offset); + } + + void setAttribDivisor(int index, int divisor) { + if (attribDivisors == null) { + if (divisor != 0) { + int newLen = 8; + while (newLen <= index) { + newLen <<= 1; + } + attribDivisors = new int[newLen]; + } + } else if (index >= attribDivisors.length) { + int newLen = attribDivisors.length << 1; + while (newLen <= index) { + newLen <<= 1; + } + int[] newDivisor = new int[newLen]; + System.arraycopy(attribDivisors, 0, newDivisor, 0, attribDivisors.length); + attribDivisors = newDivisor; + } + if (attribDivisors != null) { + attribDivisors[index] = divisor; + if (divisor != 0) { + hasAttribDivisorMask |= (1 << index); + } else { + hasAttribDivisorMask &= ~(1 << index); + } + } + } + + void setIndexBuffer(IBufferGL buffer) { + indexBuffer = buffer; + } + + void transitionToState(SoftGLBufferState previousState, boolean elements) { + int oldEnabled = previousState.oldEnabled; + int oldEnabledCnt = previousState.oldEnabledCnt; + int[] oldAttribDivisors = previousState.attribDivisors; + int oldHasAttribDivisorMask = previousState.hasAttribDivisorMask; + Attrib[] oldAttrs = previousState.attribs; + boolean instancingCapable = EaglercraftGPU.checkInstancingCapable(); + int enCnt = enabledCnt; + int en = enabled; + Attrib[] attrs = attribs; + int[] divs = attribDivisors; + int hasDivs = hasAttribDivisorMask; + if (oldEnabledCnt >= 0) { + int enMax = Math.max(enCnt, oldEnabledCnt); + for (int i = 0, ii; i < enMax; ++i) { + ii = (1 << i); + boolean old = i < oldEnabledCnt && (oldEnabled & ii) != 0; + boolean _new = i < enCnt && (en & ii) != 0; + if (_new) { + if (!old) { + _wglEnableVertexAttribArray(i); + } + Attrib attr = i < attrs.length ? attrs[i] : null; + if (attr != null) { + Attrib oldAttr = oldAttrs[i]; + if (oldAttr == null || !oldAttr.equalsExplicit(attr)) { + EaglercraftGPU.bindGLArrayBuffer(attr.buffer); + _wglVertexAttribPointer(i, attr.size, attr.format, attr.normalized, attr.stride, + attr.offset); + oldAttrs[i] = attr; + } + } else { + oldAttrs[i] = null; + } + if (instancingCapable) { + // instancing is uncommon + if ((hasDivs & ii) != 0) { + int newDivisor = divs[i]; + if ((oldHasAttribDivisorMask & ii) == 0 || newDivisor != oldAttribDivisors[i]) { + _wglVertexAttribDivisor(i, newDivisor); + oldAttribDivisors[i] = newDivisor; + previousState.hasAttribDivisorMask |= ii; + } + } else { + if ((oldHasAttribDivisorMask & ii) != 0) { + _wglVertexAttribDivisor(i, 0); + oldAttribDivisors[i] = 0; + previousState.hasAttribDivisorMask &= ~ii; + } + } + } + } else if (old) { + _wglDisableVertexAttribArray(i); + } + } + } else { + // Bootstrap code for the emulator's first draw + for (int i = 0; i < enCnt; ++i) { + int ii = (1 << i); + if ((en & ii) != 0) { + _wglEnableVertexAttribArray(i); + Attrib attr = attrs[i]; + if (attr != null) { + EaglercraftGPU.bindGLArrayBuffer(attr.buffer); + _wglVertexAttribPointer(i, attr.size, attr.format, attr.normalized, attr.stride, attr.offset); + oldAttrs[i] = attr; + } else { + oldAttrs[i] = null; + } + if (instancingCapable) { + if ((hasDivs & ii) != 0) { + int newDivisor = divs[i]; + _wglVertexAttribDivisor(i, newDivisor); + oldAttribDivisors[i] = newDivisor; + previousState.hasAttribDivisorMask |= ii; + } else { + _wglVertexAttribDivisor(i, 0); + oldAttribDivisors[i] = 0; + } + } + } + } + } + if (elements) { + IBufferGL indexBufferL = indexBuffer; + if (indexBufferL != null) { + EaglercraftGPU.bindEmulatedVAOIndexBuffer(indexBufferL); + } + } + previousState.oldEnabled = en & ((1 << enCnt) - 1); + previousState.oldEnabledCnt = enCnt; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferState.java index 611f4352..dfe4abfe 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SoftGLBufferState.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.opengl.SoftGLBufferArray.Attrib; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SpriteLevelMixer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SpriteLevelMixer.java index e01dbd39..11a4ae04 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SpriteLevelMixer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/SpriteLevelMixer.java @@ -1,7 +1,27 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgramInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix3fv; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; @@ -15,14 +35,15 @@ import net.lax1dude.eaglercraft.v1_8.vector.Matrix3f; /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,6 +81,54 @@ public class SpriteLevelMixer { private static final Matrix3f identityMatrix = new Matrix3f(); + public static void destroy() { + if (matrixCopyBuffer != null) { + EagRuntime.freeFloatBuffer(matrixCopyBuffer); + matrixCopyBuffer = null; + } + if (shaderProgram != null) { + _wglDeleteProgram(shaderProgram); + shaderProgram = null; + } + u_textureLod1f = null; + u_blendFactor4f = null; + u_blendBias4f = null; + u_matrixTransform = null; + } + + public static void drawSprite(float level) { + EaglercraftGPU.bindGLShaderProgram(shaderProgram); + + if (EaglercraftGPU.checkTextureLODCapable()) { + _wglUniform1f(u_textureLod1f, level); + } else { + if (level != 0.0f) { + LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", level); + } + _wglUniform1f(u_textureLod1f, 0.0f); + } + + if (blendColorChanged) { + _wglUniform4f(u_blendFactor4f, blendColorR, blendColorG, blendColorB, blendColorA); + blendColorChanged = false; + } + + if (biasColorChanged) { + _wglUniform4f(u_blendBias4f, biasColorR, biasColorG, biasColorB, biasColorA); + biasColorChanged = false; + } + + if (matrixChanged) { + matrixCopyBuffer.clear(); + transformMatrix.store(matrixCopyBuffer); + matrixCopyBuffer.flip(); + _wglUniformMatrix3fv(u_matrixTransform, false, matrixCopyBuffer); + matrixChanged = false; + } + + DrawUtils.drawStandardQuad2D(); + } + static void initialize() { String fragmentSource = EagRuntime.getRequiredResourceString(fragmentShaderPath); @@ -68,12 +137,12 @@ public class SpriteLevelMixer { _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(fragmentSource, fragmentShaderPrecision)); _wglCompileShader(frag); - if(_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { + if (_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { LOGGER.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for SpriteLevelMixer!"); String log = _wglGetShaderInfoLog(frag); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { LOGGER.error("[FRAG] {}", lines[i]); } } @@ -85,7 +154,7 @@ public class SpriteLevelMixer { _wglAttachShader(shaderProgram, DrawUtils.vshLocal); _wglAttachShader(shaderProgram, frag); - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { VSHInputLayoutParser.applyLayout(shaderProgram, DrawUtils.vshLocalLayout); } @@ -96,12 +165,12 @@ public class SpriteLevelMixer { _wglDeleteShader(frag); - if(_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { + if (_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { LOGGER.error("Failed to link shader program for SpriteLevelMixer!"); String log = _wglGetProgramInfoLog(shaderProgram); - if(log != null) { + if (log != null) { String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { LOGGER.error("[LINK] {}", lines[i]); } } @@ -121,18 +190,8 @@ public class SpriteLevelMixer { } - public static void setBlendColor(float r, float g, float b, float a) { - if(r != blendColorR || g != blendColorG || b != blendColorB || a != blendColorA) { - blendColorChanged = true; - blendColorR = r; - blendColorG = g; - blendColorB = b; - blendColorA = a; - } - } - public static void setBiasColor(float r, float g, float b, float a) { - if(r != biasColorR || g != biasColorG || b != biasColorB || a != biasColorA) { + if (r != biasColorR || g != biasColorG || b != biasColorB || a != biasColorA) { biasColorChanged = true; biasColorR = r; biasColorG = g; @@ -141,63 +200,25 @@ public class SpriteLevelMixer { } } + public static void setBlendColor(float r, float g, float b, float a) { + if (r != blendColorR || g != blendColorG || b != blendColorB || a != blendColorA) { + blendColorChanged = true; + blendColorR = r; + blendColorG = g; + blendColorB = b; + blendColorA = a; + } + } + public static void setIdentityMatrix() { setMatrix3f(identityMatrix); } public static void setMatrix3f(Matrix3f matrix) { - if(!matrix.equals(transformMatrix)) { + if (!matrix.equals(transformMatrix)) { matrixChanged = true; transformMatrix.load(matrix); } } - public static void drawSprite(float level) { - EaglercraftGPU.bindGLShaderProgram(shaderProgram); - - if(EaglercraftGPU.checkTextureLODCapable()) { - _wglUniform1f(u_textureLod1f, level); - }else { - if(level != 0.0f) { - LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", level); - } - _wglUniform1f(u_textureLod1f, 0.0f); - } - - if(blendColorChanged) { - _wglUniform4f(u_blendFactor4f, blendColorR, blendColorG, blendColorB, blendColorA); - blendColorChanged = false; - } - - if(biasColorChanged) { - _wglUniform4f(u_blendBias4f, biasColorR, biasColorG, biasColorB, biasColorA); - biasColorChanged = false; - } - - if(matrixChanged) { - matrixCopyBuffer.clear(); - transformMatrix.store(matrixCopyBuffer); - matrixCopyBuffer.flip(); - _wglUniformMatrix3fv(u_matrixTransform, false, matrixCopyBuffer); - matrixChanged = false; - } - - DrawUtils.drawStandardQuad2D(); - } - - public static void destroy() { - if(matrixCopyBuffer != null) { - EagRuntime.freeFloatBuffer(matrixCopyBuffer); - matrixCopyBuffer = null; - } - if(shaderProgram != null) { - _wglDeleteProgram(shaderProgram); - shaderProgram = null; - } - u_textureLod1f = null; - u_blendFactor4f = null; - u_blendBias4f = null; - u_matrixTransform = null; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/StreamBuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/StreamBuffer.java index 252830eb..c611b4a4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/StreamBuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/StreamBuffer.java @@ -1,38 +1,35 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STREAM_DRAW; + import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; import net.lax1dude.eaglercraft.v1_8.internal.IBufferGL; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class StreamBuffer { - public final int initialSize; - public final int initialCount; - public final int maxCount; - - protected StreamBufferInstance[] buffers; - - protected int currentBufferId = 0; - protected int overflowCounter = 0; - - protected final IStreamBufferInitializer initializer; + public static interface IStreamBufferInitializer { + void initialize(IBufferArrayGL vertexArray, IBufferGL vertexBuffer); + } public static class StreamBufferInstance { @@ -53,13 +50,22 @@ public class StreamBuffer { } - public static interface IStreamBufferInitializer { - void initialize(IBufferArrayGL vertexArray, IBufferGL vertexBuffer); - } + public final int initialSize; + + public final int initialCount; + + public final int maxCount; + protected StreamBufferInstance[] buffers; + + protected int currentBufferId = 0; + + protected int overflowCounter = 0; + + protected final IStreamBufferInitializer initializer; public StreamBuffer(int initialSize, int initialCount, int maxCount, IStreamBufferInitializer initializer) { this.buffers = new StreamBufferInstance[initialCount]; - for(int i = 0; i < this.buffers.length; ++i) { + for (int i = 0; i < this.buffers.length; ++i) { this.buffers[i] = new StreamBufferInstance(); } this.initialSize = initialSize; @@ -68,16 +74,32 @@ public class StreamBuffer { this.initializer = initializer; } + public void destroy() { + for (int i = 0; i < buffers.length; ++i) { + StreamBufferInstance next = buffers[i]; + if (next.vertexArray != null) { + EaglercraftGPU.destroyGLBufferArray(next.vertexArray); + } + if (next.vertexBuffer != null) { + _wglDeleteBuffers(next.vertexBuffer); + } + } + buffers = new StreamBufferInstance[initialCount]; + for (int i = 0; i < buffers.length; ++i) { + buffers[i] = new StreamBufferInstance(); + } + } + public StreamBufferInstance getBuffer(int requiredMemory) { StreamBufferInstance next = buffers[(currentBufferId++) % buffers.length]; - if(next.vertexBuffer == null) { + if (next.vertexBuffer == null) { next.vertexBuffer = _wglGenBuffers(); } - if(next.vertexArray == null) { + if (next.vertexArray == null) { next.vertexArray = EaglercraftGPU.createGLBufferArray(); initializer.initialize(next.vertexArray, next.vertexBuffer); } - if(next.vertexBufferSize < requiredMemory) { + if (next.vertexBufferSize < requiredMemory) { int newSize = (requiredMemory & 0xFFFFF000) + 0x2000; EaglercraftGPU.bindGLArrayBuffer(next.vertexBuffer); _wglBufferData(GL_ARRAY_BUFFER, newSize, GL_STREAM_DRAW); @@ -88,21 +110,21 @@ public class StreamBuffer { public void optimize() { overflowCounter += currentBufferId - buffers.length; - if(overflowCounter < -25) { + if (overflowCounter < -25) { int newCount = buffers.length - 1 + ((overflowCounter + 25) / 5); - if(newCount < initialCount) { + if (newCount < initialCount) { newCount = initialCount; } - if(newCount < buffers.length) { + if (newCount < buffers.length) { StreamBufferInstance[] newArray = new StreamBufferInstance[newCount]; - for(int i = 0; i < buffers.length; ++i) { - if(i < newArray.length) { + for (int i = 0; i < buffers.length; ++i) { + if (i < newArray.length) { newArray[i] = buffers[i]; - }else { - if(buffers[i].vertexArray != null) { + } else { + if (buffers[i].vertexArray != null) { EaglercraftGPU.destroyGLBufferArray(buffers[i].vertexArray); } - if(buffers[i].vertexBuffer != null) { + if (buffers[i].vertexBuffer != null) { _wglDeleteBuffers(buffers[i].vertexBuffer); } } @@ -110,17 +132,17 @@ public class StreamBuffer { buffers = newArray; } overflowCounter = 0; - }else if(overflowCounter > 15) { + } else if (overflowCounter > 15) { int newCount = buffers.length + 1 + ((overflowCounter - 15) / 5); - if(newCount > maxCount) { + if (newCount > maxCount) { newCount = maxCount; } - if(newCount > buffers.length) { + if (newCount > buffers.length) { StreamBufferInstance[] newArray = new StreamBufferInstance[newCount]; - for(int i = 0; i < newArray.length; ++i) { - if(i < buffers.length) { + for (int i = 0; i < newArray.length; ++i) { + if (i < buffers.length) { newArray[i] = buffers[i]; - }else { + } else { newArray[i] = new StreamBufferInstance(); } } @@ -131,20 +153,4 @@ public class StreamBuffer { currentBufferId = 0; } - public void destroy() { - for(int i = 0; i < buffers.length; ++i) { - StreamBufferInstance next = buffers[i]; - if(next.vertexArray != null) { - EaglercraftGPU.destroyGLBufferArray(next.vertexArray); - } - if(next.vertexBuffer != null) { - _wglDeleteBuffers(next.vertexBuffer); - } - } - buffers = new StreamBufferInstance[initialCount]; - for(int i = 0; i < buffers.length; ++i) { - buffers[i] = new StreamBufferInstance(); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureCopyUtil.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureCopyUtil.java index b5f6f9f4..9f83a541 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureCopyUtil.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureCopyUtil.java @@ -1,7 +1,27 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglAttachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCompileShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDetachShader; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgramInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetProgrami; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderInfoLog; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetShaderi; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglLinkProgram; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglShaderSource; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COMPILE_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINK_STATUS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRUE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import java.util.List; @@ -15,34 +35,21 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class TextureCopyUtil { - private static final Logger LOGGER = LogManager.getLogger("TextureCopyUtil"); - - public static final String vertexShaderPath = "/assets/eagler/glsl/texture_blit.vsh"; - public static final String vertexShaderPrecision = "precision lowp int;\nprecision highp float;\nprecision highp sampler2D;\n"; - - public static final String fragmentShaderPath = "/assets/eagler/glsl/texture_blit.fsh"; - public static final String fragmentShaderPrecision = "precision lowp int;\nprecision highp float;\nprecision highp sampler2D;\n"; - - private static String vshSource = null; - private static List vshSourceLayout = null; - private static String fshSource = null; - - private static IShaderGL vshShader = null; - private static class TextureCopyShader { private IProgramGL shaderProgram = null; private IUniformGL u_srcCoords4f = null; @@ -50,6 +57,7 @@ public class TextureCopyUtil { private IUniformGL u_textureLod1f = null; private IUniformGL u_pixelAlignmentSizes4f = null; private IUniformGL u_pixelAlignmentOffset2f = null; + private TextureCopyShader(IProgramGL shaderProgram) { this.shaderProgram = shaderProgram; EaglercraftGPU.bindGLShaderProgram(shaderProgram); @@ -59,8 +67,9 @@ public class TextureCopyUtil { this.u_pixelAlignmentSizes4f = _wglGetUniformLocation(shaderProgram, "u_pixelAlignmentSizes4f"); this.u_pixelAlignmentOffset2f = _wglGetUniformLocation(shaderProgram, "u_pixelAlignmentOffset2f"); } + private void destroy() { - if(shaderProgram != null) { + if (shaderProgram != null) { _wglDeleteProgram(shaderProgram); shaderProgram = null; } @@ -72,6 +81,20 @@ public class TextureCopyUtil { } } + private static final Logger LOGGER = LogManager.getLogger("TextureCopyUtil"); + public static final String vertexShaderPath = "/assets/eagler/glsl/texture_blit.vsh"; + + public static final String vertexShaderPrecision = "precision lowp int;\nprecision highp float;\nprecision highp sampler2D;\n"; + public static final String fragmentShaderPath = "/assets/eagler/glsl/texture_blit.fsh"; + + public static final String fragmentShaderPrecision = "precision lowp int;\nprecision highp float;\nprecision highp sampler2D;\n"; + private static String vshSource = null; + private static List vshSourceLayout = null; + + private static String fshSource = null; + + private static IShaderGL vshShader = null; + private static TextureCopyShader textureBlit = null; private static TextureCopyShader textureBlitAligned = null; private static TextureCopyShader textureBlitDepth = null; @@ -89,119 +112,6 @@ public class TextureCopyUtil { private static float alignOffsetX = 0.0f; private static float alignOffsetY = 0.0f; - static void initialize() { - vshSource = EagRuntime.getRequiredResourceString(vertexShaderPath); - fshSource = EagRuntime.getRequiredResourceString(fragmentShaderPath); - - vshShader = _wglCreateShader(GL_VERTEX_SHADER); - - _wglShaderSource(vshShader, GLSLHeader.getVertexHeaderCompat(vshSource, vertexShaderPrecision)); - _wglCompileShader(vshShader); - - if(_wglGetShaderi(vshShader, GL_COMPILE_STATUS) != GL_TRUE) { - LOGGER.error("Failed to compile GL_VERTEX_SHADER \"" + vertexShaderPath + "\" for TextureCopyUtil!"); - String log = _wglGetShaderInfoLog(vshShader); - if(log != null) { - String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { - LOGGER.error("[VERT] {}", lines[i]); - } - } - throw new IllegalStateException("Vertex shader \"" + vertexShaderPath + "\" could not be compiled!"); - } - - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { - vshSourceLayout = VSHInputLayoutParser.getShaderInputs(vshSource); - } - } - - private static TextureCopyShader compileShader(boolean align, boolean depth) { - IShaderGL frag = _wglCreateShader(GL_FRAGMENT_SHADER); - - _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(fshSource, fragmentShaderPrecision - + (align ? "#define COMPILE_PIXEL_ALIGNMENT\n" : "") + (depth ? "#define COMPILE_BLIT_DEPTH\n" : ""))); - _wglCompileShader(frag); - - if(_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { - LOGGER.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for TextureCopyUtil!"); - String log = _wglGetShaderInfoLog(frag); - if(log != null) { - String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { - LOGGER.error("[FRAG] {}", lines[i]); - } - } - throw new IllegalStateException("Fragment shader \"" + fragmentShaderPath + "\" could not be compiled!"); - } - - IProgramGL shaderProgram = _wglCreateProgram(); - - _wglAttachShader(shaderProgram, vshShader); - _wglAttachShader(shaderProgram, frag); - - if(EaglercraftGPU.checkOpenGLESVersion() == 200) { - VSHInputLayoutParser.applyLayout(shaderProgram, vshSourceLayout); - } - - _wglLinkProgram(shaderProgram); - - _wglDetachShader(shaderProgram, vshShader); - _wglDetachShader(shaderProgram, frag); - - _wglDeleteShader(frag); - - if(_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { - LOGGER.error("Failed to link shader program for TextureCopyUtil!"); - String log = _wglGetProgramInfoLog(shaderProgram); - if(log != null) { - String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { - LOGGER.error("[LINK] {}", lines[i]); - } - } - throw new IllegalStateException("Shader program for TextureCopyUtil could not be linked!"); - } - - return new TextureCopyShader(shaderProgram); - } - - private static TextureCopyShader getShaderObj(boolean align, boolean depth) { - if(align) { - if(depth) { - if(textureBlitDepthAligned == null) textureBlitDepthAligned = compileShader(true, true); - return textureBlitDepthAligned; - }else { - if(textureBlitAligned == null) textureBlitAligned = compileShader(true, false); - return textureBlitAligned; - } - }else { - if(depth) { - if(textureBlitDepth == null) textureBlitDepth = compileShader(false, true); - return textureBlitDepth; - }else { - if(textureBlit == null) textureBlit = compileShader(false, false); - return textureBlit; - } - } - } - - public static void srcSize(int w, int h) { - srcViewW = w; - srcViewH = h; - } - - public static void dstSize(int w, int h) { - dstViewW = w * 0.5f; - dstViewH = h * 0.5f; - } - - public static void srcDstSize(int w, int h) { - srcViewW = w; - srcViewH = h; - dstViewW = w * 0.5f; - dstViewH = h * 0.5f; - } - /** * this is reset after every blit */ @@ -220,8 +130,29 @@ public class TextureCopyUtil { alignPixels(dstW, dstH, (0.5f * dstW) / srcW, (0.5f * dstH) / srcH); } - public static void disableAlign() { - isAligned = false; + public static void blitTexture() { + blitTexture(0); + } + + public static void blitTexture(int lvl) { + TextureCopyShader shaderObj = getShaderObj(isAligned, false); + EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); + _wglUniform4f(shaderObj.u_srcCoords4f, 0.0f, 0.0f, 1.0f, 1.0f); + _wglUniform4f(shaderObj.u_dstCoords4f, -1.0f, -1.0f, 2.0f, 2.0f); + if (EaglercraftGPU.checkTextureLODCapable()) { + _wglUniform1f(shaderObj.u_textureLod1f, lvl); + } else { + if (lvl != 0.0f) { + LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); + } + _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); + } + if (isAligned) { + _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); + _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); + isAligned = false; + } + DrawUtils.drawStandardQuad2D(); } public static void blitTexture(int srcX, int srcY, int dstX, int dstY, int w, int h) { @@ -236,114 +167,23 @@ public class TextureCopyUtil { blitTexture(0, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); } - public static void blitTexture(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { + public static void blitTexture(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, + int dstH) { TextureCopyShader shaderObj = getShaderObj(isAligned, false); EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); - _wglUniform4f(shaderObj.u_srcCoords4f, (float)srcX / srcViewW, (float)srcY / srcViewH, (float)srcW / srcViewW, (float)srcH / srcViewH); + _wglUniform4f(shaderObj.u_srcCoords4f, (float) srcX / srcViewW, (float) srcY / srcViewH, + (float) srcW / srcViewW, (float) srcH / srcViewH); _wglUniform4f(shaderObj.u_dstCoords4f, (float) dstX / dstViewW - 1.0f, (float) dstY / dstViewH - 1.0f, (float) dstW / dstViewW, (float) dstH / dstViewH); - if(EaglercraftGPU.checkTextureLODCapable()) { + if (EaglercraftGPU.checkTextureLODCapable()) { _wglUniform1f(shaderObj.u_textureLod1f, lvl); - }else { - if(lvl != 0.0f) { + } else { + if (lvl != 0.0f) { LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); } _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); } - if(isAligned) { - _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); - _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); - isAligned = false; - } - DrawUtils.drawStandardQuad2D(); - } - - public static void blitTexture() { - blitTexture(0); - } - - public static void blitTexture(int lvl) { - TextureCopyShader shaderObj = getShaderObj(isAligned, false); - EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); - _wglUniform4f(shaderObj.u_srcCoords4f, 0.0f, 0.0f, 1.0f, 1.0f); - _wglUniform4f(shaderObj.u_dstCoords4f, -1.0f, -1.0f, 2.0f, 2.0f); - if(EaglercraftGPU.checkTextureLODCapable()) { - _wglUniform1f(shaderObj.u_textureLod1f, lvl); - }else { - if(lvl != 0.0f) { - LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); - } - _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); - } - if(isAligned) { - _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); - _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); - isAligned = false; - } - DrawUtils.drawStandardQuad2D(); - } - - public static void blitTextureUsingViewports(int srcX, int srcY, int dstX, int dstY, int w, int h) { - blitTextureUsingViewports(0, srcX, srcY, w, h, dstX, dstY, w, h); - } - - public static void blitTextureUsingViewports(int lvl, int srcX, int srcY, int dstX, int dstY, int w, int h) { - blitTextureUsingViewports(lvl, srcX, srcY, w, h, dstX, dstY, w, h); - } - - public static void blitTextureUsingViewports(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { - blitTextureUsingViewports(0, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); - } - - public static void blitTextureUsingViewports(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { - TextureCopyShader shaderObj = getShaderObj(isAligned, false); - EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); - GlStateManager.viewport(dstX, dstY, dstW, dstH); - _wglUniform4f(shaderObj.u_srcCoords4f, (float)srcX / srcViewW, (float)srcY / srcViewH, (float)srcW / srcViewW, (float)srcH / srcViewH); - _wglUniform4f(shaderObj.u_dstCoords4f, -1.0f, -1.0f, 2.0f, 2.0f); - if(EaglercraftGPU.checkTextureLODCapable()) { - _wglUniform1f(shaderObj.u_textureLod1f, lvl); - }else { - if(lvl != 0.0f) { - LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); - } - _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); - } - if(isAligned) { - _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); - _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); - isAligned = false; - } - DrawUtils.drawStandardQuad2D(); - } - - public static void blitTextureDepth(int srcX, int srcY, int dstX, int dstY, int w, int h) { - blitTextureDepth(0, srcX, srcY, w, h, dstX, dstY, w, h); - } - - public static void blitTextureDepth(int lvl, int srcX, int srcY, int dstX, int dstY, int w, int h) { - blitTextureDepth(lvl, srcX, srcY, w, h, dstX, dstY, w, h); - } - - public static void blitTextureDepth(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { - blitTextureDepth(0, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); - } - - public static void blitTextureDepth(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { - TextureCopyShader shaderObj = getShaderObj(isAligned, true); - EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); - _wglUniform4f(shaderObj.u_srcCoords4f, (float)srcX / srcViewW, (float)srcY / srcViewH, (float)srcW / srcViewW, (float)srcH / srcViewH); - _wglUniform4f(shaderObj.u_dstCoords4f, (float) dstX / dstViewW - 1.0f, (float) dstY / dstViewH - 1.0f, - (float) dstW / dstViewW, (float) dstH / dstViewH); - if(EaglercraftGPU.checkTextureLODCapable()) { - _wglUniform1f(shaderObj.u_textureLod1f, lvl); - }else { - if(lvl != 0.0f) { - LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); - } - _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); - } - if(isAligned) { + if (isAligned) { _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); isAligned = false; @@ -360,15 +200,52 @@ public class TextureCopyUtil { EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); _wglUniform4f(shaderObj.u_srcCoords4f, 0.0f, 0.0f, 1.0f, 1.0f); _wglUniform4f(shaderObj.u_dstCoords4f, -1.0f, -1.0f, 2.0f, 2.0f); - if(EaglercraftGPU.checkTextureLODCapable()) { + if (EaglercraftGPU.checkTextureLODCapable()) { _wglUniform1f(shaderObj.u_textureLod1f, lvl); - }else { - if(lvl != 0.0f) { + } else { + if (lvl != 0.0f) { LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); } _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); } - if(isAligned) { + if (isAligned) { + _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); + _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); + isAligned = false; + } + DrawUtils.drawStandardQuad2D(); + } + + public static void blitTextureDepth(int srcX, int srcY, int dstX, int dstY, int w, int h) { + blitTextureDepth(0, srcX, srcY, w, h, dstX, dstY, w, h); + } + + public static void blitTextureDepth(int lvl, int srcX, int srcY, int dstX, int dstY, int w, int h) { + blitTextureDepth(lvl, srcX, srcY, w, h, dstX, dstY, w, h); + } + + public static void blitTextureDepth(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, + int dstH) { + blitTextureDepth(0, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); + } + + public static void blitTextureDepth(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, + int dstH) { + TextureCopyShader shaderObj = getShaderObj(isAligned, true); + EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); + _wglUniform4f(shaderObj.u_srcCoords4f, (float) srcX / srcViewW, (float) srcY / srcViewH, + (float) srcW / srcViewW, (float) srcH / srcViewH); + _wglUniform4f(shaderObj.u_dstCoords4f, (float) dstX / dstViewW - 1.0f, (float) dstY / dstViewH - 1.0f, + (float) dstW / dstViewW, (float) dstH / dstViewH); + if (EaglercraftGPU.checkTextureLODCapable()) { + _wglUniform1f(shaderObj.u_textureLod1f, lvl); + } else { + if (lvl != 0.0f) { + LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); + } + _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); + } + if (isAligned) { _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); isAligned = false; @@ -384,25 +261,28 @@ public class TextureCopyUtil { blitTextureDepthUsingViewports(lvl, srcX, srcY, w, h, dstX, dstY, w, h); } - public static void blitTextureDepthUsingViewports(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { + public static void blitTextureDepthUsingViewports(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, + int dstW, int dstH) { blitTextureDepthUsingViewports(0, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); } - public static void blitTextureDepthUsingViewports(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, int dstH) { + public static void blitTextureDepthUsingViewports(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, + int dstY, int dstW, int dstH) { TextureCopyShader shaderObj = getShaderObj(isAligned, true); EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); GlStateManager.viewport(dstX, dstY, dstW, dstH); - _wglUniform4f(shaderObj.u_srcCoords4f, (float)srcX / srcViewW, (float)srcY / srcViewH, (float)srcW / srcViewW, (float)srcH / srcViewH); + _wglUniform4f(shaderObj.u_srcCoords4f, (float) srcX / srcViewW, (float) srcY / srcViewH, + (float) srcW / srcViewW, (float) srcH / srcViewH); _wglUniform4f(shaderObj.u_dstCoords4f, -1.0f, -1.0f, 2.0f, 2.0f); - if(EaglercraftGPU.checkTextureLODCapable()) { + if (EaglercraftGPU.checkTextureLODCapable()) { _wglUniform1f(shaderObj.u_textureLod1f, lvl); - }else { - if(lvl != 0.0f) { + } else { + if (lvl != 0.0f) { LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); } _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); } - if(isAligned) { + if (isAligned) { _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); isAligned = false; @@ -410,26 +290,184 @@ public class TextureCopyUtil { DrawUtils.drawStandardQuad2D(); } + public static void blitTextureUsingViewports(int srcX, int srcY, int dstX, int dstY, int w, int h) { + blitTextureUsingViewports(0, srcX, srcY, w, h, dstX, dstY, w, h); + } + + public static void blitTextureUsingViewports(int lvl, int srcX, int srcY, int dstX, int dstY, int w, int h) { + blitTextureUsingViewports(lvl, srcX, srcY, w, h, dstX, dstY, w, h); + } + + public static void blitTextureUsingViewports(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, int dstW, + int dstH) { + blitTextureUsingViewports(0, srcX, srcY, srcW, srcH, dstX, dstY, dstW, dstH); + } + + public static void blitTextureUsingViewports(int lvl, int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, + int dstW, int dstH) { + TextureCopyShader shaderObj = getShaderObj(isAligned, false); + EaglercraftGPU.bindGLShaderProgram(shaderObj.shaderProgram); + GlStateManager.viewport(dstX, dstY, dstW, dstH); + _wglUniform4f(shaderObj.u_srcCoords4f, (float) srcX / srcViewW, (float) srcY / srcViewH, + (float) srcW / srcViewW, (float) srcH / srcViewH); + _wglUniform4f(shaderObj.u_dstCoords4f, -1.0f, -1.0f, 2.0f, 2.0f); + if (EaglercraftGPU.checkTextureLODCapable()) { + _wglUniform1f(shaderObj.u_textureLod1f, lvl); + } else { + if (lvl != 0.0f) { + LOGGER.error("Tried to copy from mipmap level {}, but this GPU does not support textureLod!", lvl); + } + _wglUniform1f(shaderObj.u_textureLod1f, 0.0f); + } + if (isAligned) { + _wglUniform4f(shaderObj.u_pixelAlignmentSizes4f, alignW, alignH, 1.0f / alignW, 1.0f / alignH); + _wglUniform2f(shaderObj.u_pixelAlignmentOffset2f, alignOffsetX, alignOffsetY); + isAligned = false; + } + DrawUtils.drawStandardQuad2D(); + } + + private static TextureCopyShader compileShader(boolean align, boolean depth) { + IShaderGL frag = _wglCreateShader(GL_FRAGMENT_SHADER); + + _wglShaderSource(frag, GLSLHeader.getFragmentHeaderCompat(fshSource, fragmentShaderPrecision + + (align ? "#define COMPILE_PIXEL_ALIGNMENT\n" : "") + (depth ? "#define COMPILE_BLIT_DEPTH\n" : ""))); + _wglCompileShader(frag); + + if (_wglGetShaderi(frag, GL_COMPILE_STATUS) != GL_TRUE) { + LOGGER.error("Failed to compile GL_FRAGMENT_SHADER \"" + fragmentShaderPath + "\" for TextureCopyUtil!"); + String log = _wglGetShaderInfoLog(frag); + if (log != null) { + String[] lines = log.split("(\\r\\n|\\r|\\n)"); + for (int i = 0; i < lines.length; ++i) { + LOGGER.error("[FRAG] {}", lines[i]); + } + } + throw new IllegalStateException("Fragment shader \"" + fragmentShaderPath + "\" could not be compiled!"); + } + + IProgramGL shaderProgram = _wglCreateProgram(); + + _wglAttachShader(shaderProgram, vshShader); + _wglAttachShader(shaderProgram, frag); + + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { + VSHInputLayoutParser.applyLayout(shaderProgram, vshSourceLayout); + } + + _wglLinkProgram(shaderProgram); + + _wglDetachShader(shaderProgram, vshShader); + _wglDetachShader(shaderProgram, frag); + + _wglDeleteShader(frag); + + if (_wglGetProgrami(shaderProgram, GL_LINK_STATUS) != GL_TRUE) { + LOGGER.error("Failed to link shader program for TextureCopyUtil!"); + String log = _wglGetProgramInfoLog(shaderProgram); + if (log != null) { + String[] lines = log.split("(\\r\\n|\\r|\\n)"); + for (int i = 0; i < lines.length; ++i) { + LOGGER.error("[LINK] {}", lines[i]); + } + } + throw new IllegalStateException("Shader program for TextureCopyUtil could not be linked!"); + } + + return new TextureCopyShader(shaderProgram); + } + public static void destroy() { - if(vshShader != null) { + if (vshShader != null) { _wglDeleteShader(vshShader); vshShader = null; } - if(textureBlit != null) { + if (textureBlit != null) { textureBlit.destroy(); textureBlit = null; } - if(textureBlitAligned != null) { + if (textureBlitAligned != null) { textureBlitAligned.destroy(); textureBlitAligned = null; } - if(textureBlitDepth != null) { + if (textureBlitDepth != null) { textureBlitDepth.destroy(); textureBlitDepth = null; } - if(textureBlitDepthAligned != null) { + if (textureBlitDepthAligned != null) { textureBlitDepthAligned.destroy(); textureBlitDepthAligned = null; } } + + public static void disableAlign() { + isAligned = false; + } + + public static void dstSize(int w, int h) { + dstViewW = w * 0.5f; + dstViewH = h * 0.5f; + } + + private static TextureCopyShader getShaderObj(boolean align, boolean depth) { + if (align) { + if (depth) { + if (textureBlitDepthAligned == null) + textureBlitDepthAligned = compileShader(true, true); + return textureBlitDepthAligned; + } else { + if (textureBlitAligned == null) + textureBlitAligned = compileShader(true, false); + return textureBlitAligned; + } + } else { + if (depth) { + if (textureBlitDepth == null) + textureBlitDepth = compileShader(false, true); + return textureBlitDepth; + } else { + if (textureBlit == null) + textureBlit = compileShader(false, false); + return textureBlit; + } + } + } + + static void initialize() { + vshSource = EagRuntime.getRequiredResourceString(vertexShaderPath); + fshSource = EagRuntime.getRequiredResourceString(fragmentShaderPath); + + vshShader = _wglCreateShader(GL_VERTEX_SHADER); + + _wglShaderSource(vshShader, GLSLHeader.getVertexHeaderCompat(vshSource, vertexShaderPrecision)); + _wglCompileShader(vshShader); + + if (_wglGetShaderi(vshShader, GL_COMPILE_STATUS) != GL_TRUE) { + LOGGER.error("Failed to compile GL_VERTEX_SHADER \"" + vertexShaderPath + "\" for TextureCopyUtil!"); + String log = _wglGetShaderInfoLog(vshShader); + if (log != null) { + String[] lines = log.split("(\\r\\n|\\r|\\n)"); + for (int i = 0; i < lines.length; ++i) { + LOGGER.error("[VERT] {}", lines[i]); + } + } + throw new IllegalStateException("Vertex shader \"" + vertexShaderPath + "\" could not be compiled!"); + } + + if (EaglercraftGPU.checkOpenGLESVersion() == 200) { + vshSourceLayout = VSHInputLayoutParser.getShaderInputs(vshSource); + } + } + + public static void srcDstSize(int w, int h) { + srcViewW = w; + srcViewH = h; + dstViewW = w * 0.5f; + dstViewH = h * 0.5f; + } + + public static void srcSize(int w, int h) { + srcViewW = w; + srcViewH = h; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureFormatHelper.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureFormatHelper.java index 6049022f..82f4fae9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureFormatHelper.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/TextureFormatHelper.java @@ -1,19 +1,31 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LUMINANCE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RED; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGB; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGB8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_HALF_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_R8; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_RG; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_RG8; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_RGB16F; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -21,7 +33,7 @@ import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; public class TextureFormatHelper { public static int getFormatFromInternal(int internalFormat) { - switch(internalFormat) { + switch (internalFormat) { case _GL_R8: case 0x822D: // GL_R16F case 0x822E: // GL_R32F @@ -44,7 +56,7 @@ public class TextureFormatHelper { } public static int getTypeFromInternal(int internalFormat) { - switch(internalFormat) { + switch (internalFormat) { case _GL_R8: case _GL_RG8: case GL_RGB8: @@ -66,7 +78,7 @@ public class TextureFormatHelper { } public static int trivializeInternalFormatToGLES20(int internalFormat) { - switch(internalFormat) { + switch (internalFormat) { case _GL_R8: return GL_LUMINANCE; case GL_RGB8: diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VSHInputLayoutParser.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VSHInputLayoutParser.java index 0eaf2e9a..f31c9807 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VSHInputLayoutParser.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VSHInputLayoutParser.java @@ -1,24 +1,25 @@ package net.lax1dude.eaglercraft.v1_8.opengl; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindAttribLocation; + import java.util.ArrayList; import java.util.List; import net.lax1dude.eaglercraft.v1_8.EagUtils; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,37 +42,44 @@ public class VSHInputLayoutParser { public static class ShaderLayoutParseException extends RuntimeException { - public ShaderLayoutParseException(String message, Throwable cause) { - super(message, cause); - } - public ShaderLayoutParseException(String message) { super(message); } + public ShaderLayoutParseException(String message, Throwable cause) { + super(message, cause); + } + + } + + public static void applyLayout(IProgramGL program, List layout) { + for (int i = 0, l = layout.size(); i < l; ++i) { + ShaderInput itm = layout.get(i); + _wglBindAttribLocation(program, itm.index, itm.name); + } } public static List getShaderInputs(String vshSource) { int idx1 = vshSource.indexOf("EAGLER_VSH_LAYOUT_BEGIN()"); - if(idx1 == -1) { + if (idx1 == -1) { throw new ShaderLayoutParseException("Could not find \"EAGLER_VSH_LAYOUT_BEGIN()\" delimiter!"); } int idx2 = vshSource.indexOf("EAGLER_VSH_LAYOUT_END()", idx1 + 25); - if(idx2 == -1) { + if (idx2 == -1) { throw new ShaderLayoutParseException("Could not find \"EAGLER_VSH_LAYOUT_END()\" delimiter!"); } List lines = EagUtils.linesList(vshSource.substring(idx1 + 25, idx2)); List ret = new ArrayList<>(); - for(int i = 0, l = lines.size(); i < l; ++i) { + for (int i = 0, l = lines.size(); i < l; ++i) { String ln = lines.get(i); ln = ln.trim(); - if(ln.startsWith("EAGLER_IN(") && ln.endsWith(")")) { + if (ln.startsWith("EAGLER_IN(") && ln.endsWith(")")) { String[] tokens = ln.substring(10, ln.length() - 1).split(",", 3); - if(tokens.length == 3) { + if (tokens.length == 3) { int idx; try { idx = Integer.parseInt(tokens[0].trim()); - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { continue; } ret.add(new ShaderInput(idx, tokens[1].trim(), tokens[2].trim())); @@ -81,11 +89,4 @@ public class VSHInputLayoutParser { return ret; } - public static void applyLayout(IProgramGL program, List layout) { - for(int i = 0, l = layout.size(); i < l; ++i) { - ShaderInput itm = layout.get(i); - _wglBindAttribLocation(program, itm.index, itm.name); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VertexFormat.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VertexFormat.java index 934a55bc..4b47cc26 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VertexFormat.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/VertexFormat.java @@ -1,37 +1,34 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; /** * Copyright (c) 2022-2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum VertexFormat { - BLOCK(true, true, false, true), - BLOCK_SHADERS(true, true, true, true), - ITEM(true, true, true, false), - OLDMODEL_POSITION_TEX_NORMAL(true, false, true, false), - PARTICLE_POSITION_TEX_COLOR_LMAP(true, true, true, true), - POSITION(false, false, false, false), - POSITION_COLOR(false, true, false, false), - POSITION_TEX(true, false, false, false), - POSITION_NORMAL(false, false, true, false), - POSITION_TEX_COLOR(true, true, false, false), - POSITION_TEX_NORMAL(true, false, true, false), - POSITION_TEX_LMAP_COLOR(true, true, false, true), - POSITION_TEX_COLOR_NORMAL(true, true, true, false); + BLOCK(true, true, false, true), BLOCK_SHADERS(true, true, true, true), ITEM(true, true, true, false), + OLDMODEL_POSITION_TEX_NORMAL(true, false, true, false), PARTICLE_POSITION_TEX_COLOR_LMAP(true, true, true, true), + POSITION(false, false, false, false), POSITION_COLOR(false, true, false, false), + POSITION_TEX(true, false, false, false), POSITION_NORMAL(false, false, true, false), + POSITION_TEX_COLOR(true, true, false, false), POSITION_TEX_NORMAL(true, false, true, false), + POSITION_TEX_LMAP_COLOR(true, true, false, true), POSITION_TEX_COLOR_NORMAL(true, true, true, false); public static final int COMPONENT_POSITION_SIZE = 3; public static final int COMPONENT_POSITION_FORMAT = GL_FLOAT; @@ -95,15 +92,15 @@ public enum VertexFormat { public final int attribCount; public final int attribStride; - + public final int eaglercraftAttribBits; private VertexFormat(boolean texture, boolean color, boolean normal, boolean lightmap) { - + int index = 0; int bytes = 0; int bitfield = 0; - + attribPositionEnabled = true; attribPositionIndex = index++; attribPositionOffset = bytes; @@ -111,8 +108,8 @@ public enum VertexFormat { attribPositionNormalized = false; attribPositionSize = COMPONENT_POSITION_SIZE; bytes += COMPONENT_POSITION_STRIDE; - - if(color) { + + if (color) { attribColorEnabled = true; attribColorIndex = index++; attribColorOffset = bytes; @@ -121,7 +118,7 @@ public enum VertexFormat { attribColorSize = COMPONENT_COLOR_SIZE; bytes += COMPONENT_COLOR_STRIDE; bitfield |= EaglercraftGPU.ATTRIB_COLOR; - }else { + } else { attribColorEnabled = false; attribColorIndex = -1; attribColorOffset = -1; @@ -130,7 +127,7 @@ public enum VertexFormat { attribColorSize = -1; } - if(texture) { + if (texture) { attribTextureEnabled = true; attribTextureIndex = index++; attribTextureOffset = bytes; @@ -139,7 +136,7 @@ public enum VertexFormat { attribTextureSize = COMPONENT_TEX_SIZE; bytes += COMPONENT_TEX_STRIDE; bitfield |= EaglercraftGPU.ATTRIB_TEXTURE; - }else { + } else { attribTextureEnabled = false; attribTextureIndex = -1; attribTextureOffset = -1; @@ -147,8 +144,8 @@ public enum VertexFormat { attribTextureNormalized = false; attribTextureSize = -1; } - - if(normal) { + + if (normal) { attribNormalEnabled = true; attribNormalIndex = index++; attribNormalOffset = bytes; @@ -157,7 +154,7 @@ public enum VertexFormat { attribNormalSize = COMPONENT_NORMAL_SIZE; bytes += COMPONENT_NORMAL_STRIDE; bitfield |= EaglercraftGPU.ATTRIB_NORMAL; - }else { + } else { attribNormalEnabled = false; attribNormalIndex = -1; attribNormalOffset = -1; @@ -165,8 +162,8 @@ public enum VertexFormat { attribNormalNormalized = false; attribNormalSize = -1; } - - if(lightmap) { + + if (lightmap) { attribLightmapEnabled = true; attribLightmapIndex = index++; attribLightmapOffset = bytes; @@ -175,7 +172,7 @@ public enum VertexFormat { attribLightmapSize = COMPONENT_LIGHTMAP_SIZE; bytes += COMPONENT_LIGHTMAP_STRIDE; bitfield |= EaglercraftGPU.ATTRIB_LIGHTMAP; - }else { + } else { attribLightmapEnabled = false; attribLightmapIndex = -1; attribLightmapOffset = -1; @@ -183,15 +180,15 @@ public enum VertexFormat { attribLightmapNormalized = false; attribLightmapSize = -1; } - + attribCount = index; - attribStride = attribPositionStride = bytes; + attribStride = attribPositionStride = bytes; attribColorStride = color ? bytes : -1; attribTextureStride = texture ? bytes : -1; attribNormalStride = normal ? bytes : -1; attribLightmapStride = lightmap ? bytes : -1; eaglercraftAttribBits = bitfield; - + } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldRenderer.java index 30056597..90c58f93 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldRenderer.java @@ -1,13 +1,13 @@ package net.lax1dude.eaglercraft.v1_8.opengl; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import java.util.Arrays; import java.util.BitSet; import java.util.Comparator; import net.lax1dude.eaglercraft.v1_8.EagRuntime; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; +import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; import net.minecraft.client.renderer.GLAllocation; @@ -16,71 +16,188 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WorldRenderer { - + + public class State { + private final int[] stateRawBuffer; + private final VertexFormat stateVertexFormat; + + public State(int[] parArrayOfInt, VertexFormat parVertexFormat) { + this.stateRawBuffer = parArrayOfInt; + this.stateVertexFormat = parVertexFormat; + } + + public int[] getRawBuffer() { + return this.stateRawBuffer; + } + + public int getVertexCount() { + return this.stateRawBuffer.length / (this.stateVertexFormat.attribStride >> 2); + } + + public VertexFormat getVertexFormat() { + return this.stateVertexFormat; + } + } + + private static float func_181665_a(FloatBuffer parFloatBuffer, float parFloat1, float parFloat2, float parFloat3, + int parInt1, int parInt2) { + float f = parFloatBuffer.get(parInt2 + parInt1 * 0 + 0); + float f1 = parFloatBuffer.get(parInt2 + parInt1 * 0 + 1); + float f2 = parFloatBuffer.get(parInt2 + parInt1 * 0 + 2); + float f3 = parFloatBuffer.get(parInt2 + parInt1 * 1 + 0); + float f4 = parFloatBuffer.get(parInt2 + parInt1 * 1 + 1); + float f5 = parFloatBuffer.get(parInt2 + parInt1 * 1 + 2); + float f6 = parFloatBuffer.get(parInt2 + parInt1 * 2 + 0); + float f7 = parFloatBuffer.get(parInt2 + parInt1 * 2 + 1); + float f8 = parFloatBuffer.get(parInt2 + parInt1 * 2 + 2); + float f9 = parFloatBuffer.get(parInt2 + parInt1 * 3 + 0); + float f10 = parFloatBuffer.get(parInt2 + parInt1 * 3 + 1); + float f11 = parFloatBuffer.get(parInt2 + parInt1 * 3 + 2); + float f12 = (f + f3 + f6 + f9) * 0.25F - parFloat1; + float f13 = (f1 + f4 + f7 + f10) * 0.25F - parFloat2; + float f14 = (f2 + f5 + f8 + f11) * 0.25F - parFloat3; + return f12 * f12 + f13 * f13 + f14 * f14; + } + private boolean needsUpdate; private int drawMode; private double xOffset; private double yOffset; + private double zOffset; + private boolean isDrawing; - private VertexFormat vertexFormat; - private int vertexCount; private ByteBuffer byteBuffer; + private IntBuffer intBuffer; + private FloatBuffer floatBuffer; - + private boolean hasBeenFreed = false; + private final Vector3f tmpVec1 = new Vector3f(); + + private final Vector3f tmpVec2 = new Vector3f(); + + private final Vector3f tmpVec3 = new Vector3f(); + + private final Vector3f tmpVec4 = new Vector3f(); + + private final Vector3f tmpVec5 = new Vector3f(); + + private final Vector3f tmpVec6 = new Vector3f(); + public WorldRenderer(int bufferSizeIn) { this.byteBuffer = GLAllocation.createDirectByteBuffer(bufferSizeIn << 2); this.intBuffer = this.byteBuffer.asIntBuffer(); this.floatBuffer = this.byteBuffer.asFloatBuffer(); } - - public void free() { - if(!hasBeenFreed) { - hasBeenFreed = true; - EagRuntime.freeByteBuffer(byteBuffer); + + /** + * adds cached vertex data to the buffer + */ + public void addVertexData(int[] vertexData) { + this.grow(vertexData.length); + int p = this.intBuffer.position(); + this.intBuffer.position((this.vertexCount * this.vertexFormat.attribStride) >> 2); + this.intBuffer.put(vertexData); + this.intBuffer.position(p); + this.vertexCount += vertexData.length / (this.vertexFormat.attribStride >> 2); + } + + public void begin(int parInt1, VertexFormat parVertexFormat) { + if (this.isDrawing) { + throw new IllegalStateException("WorldRenderer already building you eagler!"); + } else { + this.isDrawing = true; + this.reset(); + this.drawMode = parInt1; + this.vertexFormat = parVertexFormat; + this.needsUpdate = false; + this.byteBuffer.limit(this.byteBuffer.capacity()); } } - + + /** + * sets color of current vertex + */ + public WorldRenderer color(float parFloat1, float parFloat2, float parFloat3, float parFloat4) { + return this.color((int) (parFloat1 * 255.0F), (int) (parFloat2 * 255.0F), (int) (parFloat3 * 255.0F), + (int) (parFloat4 * 255.0F)); + } + + /** + * sets color of current vertex + */ + public WorldRenderer color(int parInt1, int parInt2, int parInt3, int parInt4) { + if (this.needsUpdate) { + return this; + } else { + VertexFormat fmt = this.vertexFormat; + int i = this.vertexCount * fmt.attribStride + fmt.attribColorOffset; + this.byteBuffer.putInt(i, parInt1 | parInt2 << 8 | parInt3 << 16 | parInt4 << 24); + return this; + } + } + + /** + * increases the index of the current vertex by 1 + */ + public void endVertex() { + ++this.vertexCount; + this.grow(this.vertexFormat.attribStride >> 2); + } + public void finalize() { free(); } - private void grow(int parInt1) { - int pos = (this.vertexCount * this.vertexFormat.attribStride) >> 2; - int i = this.byteBuffer.capacity() >> 2; - if (parInt1 > (i - pos)) { - int k = (((pos + parInt1 + (parInt1 >> 1)) >> 16) + 1) << 16; - LogManager.getLogger() .warn("Needed to grow BufferBuilder buffer: Old size " + (i << 2) + - " bytes, new size " + (k << 2) + " bytes."); - ByteBuffer bytebuffer = GLAllocation.createDirectByteBuffer(k << 2); + public void finishDrawing() { + if (!this.isDrawing) { + throw new IllegalStateException("Not building!"); + } else { + this.isDrawing = false; this.byteBuffer.position(0); - bytebuffer.put(this.byteBuffer); - bytebuffer.rewind(); - EagRuntime.freeByteBuffer(this.byteBuffer); - this.byteBuffer = bytebuffer; - this.intBuffer = this.byteBuffer.asIntBuffer(); - this.floatBuffer = this.byteBuffer.asFloatBuffer(); + this.byteBuffer.limit(this.vertexCount * this.vertexFormat.attribStride); } } + public void free() { + if (!hasBeenFreed) { + hasBeenFreed = true; + EagRuntime.freeByteBuffer(byteBuffer); + } + } + + /** + * SLOW AND STUPID UPLOAD QUEUE SYSTEM, MUST BE REPLACED + */ + public WorldRenderer.State func_181672_a() { + this.intBuffer.position(0); + VertexFormat fmt = this.vertexFormat; + int i = (fmt.attribStride >> 2) * vertexCount; + this.intBuffer.limit(i); + int[] aint = new int[i]; + this.intBuffer.get(aint); + return new WorldRenderer.State(aint, fmt); + } + /** * MOST LIKELY USED TO SORT QUADS BACK TO FRONT */ @@ -139,77 +256,99 @@ public class WorldRenderer { } - /** - * SLOW AND STUPID UPLOAD QUEUE SYSTEM, MUST BE REPLACED - */ - public WorldRenderer.State func_181672_a() { - this.intBuffer.position(0); + public void genNormals(boolean b, int vertId) { VertexFormat fmt = this.vertexFormat; - int i = (fmt.attribStride >> 2) * vertexCount; - this.intBuffer.limit(i); - int[] aint = new int[i]; - this.intBuffer.get(aint); - return new WorldRenderer.State(aint, fmt); - } - - private static float func_181665_a(FloatBuffer parFloatBuffer, float parFloat1, float parFloat2, float parFloat3, - int parInt1, int parInt2) { - float f = parFloatBuffer.get(parInt2 + parInt1 * 0 + 0); - float f1 = parFloatBuffer.get(parInt2 + parInt1 * 0 + 1); - float f2 = parFloatBuffer.get(parInt2 + parInt1 * 0 + 2); - float f3 = parFloatBuffer.get(parInt2 + parInt1 * 1 + 0); - float f4 = parFloatBuffer.get(parInt2 + parInt1 * 1 + 1); - float f5 = parFloatBuffer.get(parInt2 + parInt1 * 1 + 2); - float f6 = parFloatBuffer.get(parInt2 + parInt1 * 2 + 0); - float f7 = parFloatBuffer.get(parInt2 + parInt1 * 2 + 1); - float f8 = parFloatBuffer.get(parInt2 + parInt1 * 2 + 2); - float f9 = parFloatBuffer.get(parInt2 + parInt1 * 3 + 0); - float f10 = parFloatBuffer.get(parInt2 + parInt1 * 3 + 1); - float f11 = parFloatBuffer.get(parInt2 + parInt1 * 3 + 2); - float f12 = (f + f3 + f6 + f9) * 0.25F - parFloat1; - float f13 = (f1 + f4 + f7 + f10) * 0.25F - parFloat2; - float f14 = (f2 + f5 + f8 + f11) * 0.25F - parFloat3; - return f12 * f12 + f13 * f13 + f14 * f14; - } - - /** - * SLOW AND STUPID COMPANION FUNCTION TO 'func_181672_a' - */ - public void setVertexState(WorldRenderer.State state) { - this.grow(state.getRawBuffer().length); - int p = intBuffer.position(); - this.intBuffer.position(0); - this.intBuffer.put(state.getRawBuffer()); - this.intBuffer.position(p); - this.vertexCount = state.getVertexCount(); - this.vertexFormat = state.getVertexFormat(); - } - - public void reset() { - this.vertexCount = 0; - this.byteBuffer.clear(); - this.intBuffer.clear(); - } - - public void begin(int parInt1, VertexFormat parVertexFormat) { - if (this.isDrawing) { - throw new IllegalStateException("WorldRenderer already building you eagler!"); - } else { - this.isDrawing = true; - this.reset(); - this.drawMode = parInt1; - this.vertexFormat = parVertexFormat; - this.needsUpdate = false; - this.byteBuffer.limit(this.byteBuffer.capacity()); + int i1 = fmt.attribStride; + int j1 = (this.vertexCount - 4) * i1; + tmpVec1.x = this.byteBuffer.getFloat(j1); + tmpVec1.y = this.byteBuffer.getFloat(j1 + 4); + tmpVec1.z = this.byteBuffer.getFloat(j1 + 8); + j1 += i1; + tmpVec2.x = this.byteBuffer.getFloat(j1); + tmpVec2.y = this.byteBuffer.getFloat(j1 + 4); + tmpVec2.z = this.byteBuffer.getFloat(j1 + 8); + j1 += i1 * 2; + tmpVec3.x = this.byteBuffer.getFloat(j1); + tmpVec3.y = this.byteBuffer.getFloat(j1 + 4); + tmpVec3.z = this.byteBuffer.getFloat(j1 + 8); + Vector3f.sub(tmpVec1, tmpVec2, tmpVec4); + Vector3f.sub(tmpVec3, tmpVec2, tmpVec5); + Vector3f.cross(tmpVec5, tmpVec4, tmpVec6); + float f = (float) Math.sqrt((double) (tmpVec6.x * tmpVec6.x + tmpVec6.y * tmpVec6.y + tmpVec6.z * tmpVec6.z)); + tmpVec6.x /= f; + tmpVec6.y /= f; + tmpVec6.z /= f; + int i = (byte) ((int) (tmpVec6.x * 127.0F)) & 255; + int j = (byte) ((int) (tmpVec6.y * 127.0F)) & 255; + int k = (byte) ((int) (tmpVec6.z * 127.0F)) & 255; + int l = i | j << 8 | k << 16 | vertId << 24; + int jj1 = (this.vertexCount - 4) * i1 + fmt.attribNormalOffset; + this.byteBuffer.putInt(jj1, l); + this.byteBuffer.putInt(jj1 + i1, l); + if (!b) { + this.byteBuffer.putInt(jj1 + i1 * 2, l); + } + this.byteBuffer.putInt(jj1 + i1 * 3, l); + if (b) { + j1 = (this.vertexCount - 2) * i1; + tmpVec1.x = this.byteBuffer.getFloat(j1); + tmpVec1.y = this.byteBuffer.getFloat(j1 + 4); + tmpVec1.z = this.byteBuffer.getFloat(j1 + 8); + Vector3f.sub(tmpVec2, tmpVec1, tmpVec4); + Vector3f.sub(tmpVec3, tmpVec1, tmpVec5); + Vector3f.cross(tmpVec5, tmpVec4, tmpVec6); + f = (float) Math.sqrt((double) (tmpVec6.x * tmpVec6.x + tmpVec6.y * tmpVec6.y + tmpVec6.z * tmpVec6.z)); + tmpVec6.x /= f; + tmpVec6.y /= f; + tmpVec6.z /= f; + i = (byte) ((int) (tmpVec6.x * 127.0F)) & 255; + j = (byte) ((int) (tmpVec6.y * 127.0F)) & 255; + k = (byte) ((int) (tmpVec6.z * 127.0F)) & 255; + l = i | j << 8 | k << 16 | vertId << 24; + this.byteBuffer.putInt(jj1 + i1 * 2, l); } } - public WorldRenderer tex(double parDouble1, double parDouble2) { - VertexFormat fmt = this.vertexFormat; - int i = this.vertexCount * fmt.attribStride + fmt.attribTextureOffset; - this.byteBuffer.putFloat(i, (float) parDouble1); - this.byteBuffer.putFloat(i + 4, (float) parDouble2); - return this; + public ByteBuffer getByteBuffer() { + return this.byteBuffer; + } + + /** + * gets the color index of a vertex parInt1 indicies before the current vertex + */ + private int getColorIndex(int parInt1) { + return ((this.vertexCount - parInt1) * this.vertexFormat.attribStride + + this.vertexFormat.attribColorOffset) >> 2; + } + + public int getDrawMode() { + return this.drawMode; + } + + public int getVertexCount() { + return this.vertexCount; + } + + public VertexFormat getVertexFormat() { + return this.vertexFormat; + } + + private void grow(int parInt1) { + int pos = (this.vertexCount * this.vertexFormat.attribStride) >> 2; + int i = this.byteBuffer.capacity() >> 2; + if (parInt1 > (i - pos)) { + int k = (((pos + parInt1 + (parInt1 >> 1)) >> 16) + 1) << 16; + LogManager.getLogger().warn("Needed to grow BufferBuilder buffer: Old size " + (i << 2) + + " bytes, new size " + (k << 2) + " bytes."); + ByteBuffer bytebuffer = GLAllocation.createDirectByteBuffer(k << 2); + this.byteBuffer.position(0); + bytebuffer.put(this.byteBuffer); + bytebuffer.rewind(); + EagRuntime.freeByteBuffer(this.byteBuffer); + this.byteBuffer = bytebuffer; + this.intBuffer = this.byteBuffer.asIntBuffer(); + this.floatBuffer = this.byteBuffer.asFloatBuffer(); + } } public WorldRenderer lightmap(int parInt1, int parInt2) { @@ -220,6 +359,36 @@ public class WorldRenderer { return this; } + /** + * Marks the current renderer data as dirty (makes it skip certain calls) + */ + public void markDirty() { + this.needsUpdate = true; + } + + /** + * set normal of current vertex + */ + public WorldRenderer normal(float parFloat1, float parFloat2, float parFloat3) { // TODO: crash with particles + VertexFormat fmt = this.vertexFormat; + int i = this.vertexCount * fmt.attribStride + fmt.attribNormalOffset; + this.byteBuffer.put(i, (byte) ((int) parFloat1 * 127 & 255)); + this.byteBuffer.put(i + 1, (byte) ((int) parFloat2 * 127 & 255)); + this.byteBuffer.put(i + 2, (byte) ((int) parFloat3 * 127 & 255)); + return this; + } + + /** + * sets position of current vertex + */ + public WorldRenderer pos(double parDouble1, double parDouble2, double parDouble3) { + int i = this.vertexCount * this.vertexFormat.attribStride; + this.byteBuffer.putFloat(i, (float) (parDouble1 + this.xOffset)); + this.byteBuffer.putFloat(i + 4, (float) (parDouble2 + this.yOffset)); + this.byteBuffer.putFloat(i + 8, (float) (parDouble3 + this.zOffset)); + return this; + } + /** * update lightmap color of the last 4 verticies, used in AO calculation */ @@ -234,29 +403,22 @@ public class WorldRenderer { } /** - * translates the last 4 verticies to the given position plus current offset + * sets color multiplier of a vertex parInt1 indicies before the current vertex */ - public void putPosition(double x, double y, double z) { - int i = this.vertexFormat.attribStride; - int j = (this.vertexCount - 4) * i; - - for (int k = 0; k < 4; ++k) { - int l = j + k * i; - int i1 = l + 4; - int j1 = i1 + 4; - this.byteBuffer.putFloat(l, (float) (x + this.xOffset) + this.byteBuffer.getFloat(l)); - this.byteBuffer.putFloat(i1, (float) (y + this.yOffset) + this.byteBuffer.getFloat(i1)); - this.byteBuffer.putFloat(j1, (float) (z + this.zOffset) + this.byteBuffer.getFloat(j1)); - } - + private void putColor(int argb, int parInt2) { + int i = this.getColorIndex(parInt2); + int j = argb >>> 16 & 255; + int k = argb >>> 8 & 255; + int l = argb & 255; + int i1 = argb >>> 24 & 255; + this.putColorRGBA(i, j, k, l, i1); } - /** - * gets the color index of a vertex parInt1 indicies before the current vertex - */ - private int getColorIndex(int parInt1) { - return ((this.vertexCount - parInt1) * this.vertexFormat.attribStride + - this.vertexFormat.attribColorOffset) >> 2; + public void putColor4(int argb) { + for (int i = 0; i < 4; ++i) { + this.putColor(argb, i + 1); + } + } /** @@ -276,18 +438,6 @@ public class WorldRenderer { } this.intBuffer.put(i, j); } - - /** - * sets color multiplier of a vertex parInt1 indicies before the current vertex - */ - private void putColor(int argb, int parInt2) { - int i = this.getColorIndex(parInt2); - int j = argb >>> 16 & 255; - int k = argb >>> 8 & 255; - int l = argb & 255; - int i1 = argb >>> 24 & 255; - this.putColorRGBA(i, j, k, l, i1); - } /** * sets color multiplier of a vertex parInt1 indicies before the current vertex @@ -300,6 +450,13 @@ public class WorldRenderer { this.putColorRGBA(i, j, k, l, 255); } + public void putColorRGB_F4(float red, float green, float blue) { + for (int i = 0; i < 4; ++i) { + this.putColorRGB_F(red, green, blue, i + 1); + } + + } + /** * sets color multiplier of a vertex parInt1 indicies before the current vertex */ @@ -307,66 +464,6 @@ public class WorldRenderer { this.intBuffer.put(index, parInt5 << 24 | parInt4 << 16 | parInt3 << 8 | red); } - /** - * Marks the current renderer data as dirty (makes it skip certain calls) - */ - public void markDirty() { - this.needsUpdate = true; - } - - /** - * sets color of current vertex - */ - public WorldRenderer color(float parFloat1, float parFloat2, float parFloat3, float parFloat4) { - return this.color((int) (parFloat1 * 255.0F), (int) (parFloat2 * 255.0F), (int) (parFloat3 * 255.0F), - (int) (parFloat4 * 255.0F)); - } - - /** - * sets color of current vertex - */ - public WorldRenderer color(int parInt1, int parInt2, int parInt3, int parInt4) { - if (this.needsUpdate) { - return this; - } else { - VertexFormat fmt = this.vertexFormat; - int i = this.vertexCount * fmt.attribStride + fmt.attribColorOffset; - this.byteBuffer.putInt(i, parInt1 | parInt2 << 8 | parInt3 << 16 | parInt4 << 24); - return this; - } - } - - /** - * adds cached vertex data to the buffer - */ - public void addVertexData(int[] vertexData) { - this.grow(vertexData.length); - int p = this.intBuffer.position(); - this.intBuffer.position((this.vertexCount * this.vertexFormat.attribStride) >> 2); - this.intBuffer.put(vertexData); - this.intBuffer.position(p); - this.vertexCount += vertexData.length / (this.vertexFormat.attribStride >> 2); - } - - /** - * increases the index of the current vertex by 1 - */ - public void endVertex() { - ++this.vertexCount; - this.grow(this.vertexFormat.attribStride >> 2); - } - - /** - * sets position of current vertex - */ - public WorldRenderer pos(double parDouble1, double parDouble2, double parDouble3) { - int i = this.vertexCount * this.vertexFormat.attribStride; - this.byteBuffer.putFloat(i, (float) (parDouble1 + this.xOffset)); - this.byteBuffer.putFloat(i + 4, (float) (parDouble2 + this.yOffset)); - this.byteBuffer.putFloat(i + 8, (float) (parDouble3 + this.zOffset)); - return this; - } - /** * sets the normal of the previous 4 verticies in the buffer */ @@ -388,7 +485,7 @@ public class WorldRenderer { int i = (byte) ((int) (x * 127.0F)) & 255; int j = (byte) ((int) (y * 127.0F)) & 255; int k = (byte) ((int) (z * 127.0F)) & 255; - int l = i | j << 8 | k << 16 | ((byte)id) << 24; + int l = i | j << 8 | k << 16 | ((byte) id) << 24; VertexFormat fmt = this.vertexFormat; int i1 = fmt.attribStride; int j1 = (this.vertexCount - 4) * i1 + fmt.attribNormalOffset; @@ -399,76 +496,27 @@ public class WorldRenderer { } /** - * set normal of current vertex + * translates the last 4 verticies to the given position plus current offset */ - public WorldRenderer normal(float parFloat1, float parFloat2, float parFloat3) { //TODO: crash with particles - VertexFormat fmt = this.vertexFormat; - int i = this.vertexCount * fmt.attribStride + fmt.attribNormalOffset; - this.byteBuffer.put(i, (byte) ((int) parFloat1 * 127 & 255)); - this.byteBuffer.put(i + 1, (byte) ((int) parFloat2 * 127 & 255)); - this.byteBuffer.put(i + 2, (byte) ((int) parFloat3 * 127 & 255)); - return this; + public void putPosition(double x, double y, double z) { + int i = this.vertexFormat.attribStride; + int j = (this.vertexCount - 4) * i; + + for (int k = 0; k < 4; ++k) { + int l = j + k * i; + int i1 = l + 4; + int j1 = i1 + 4; + this.byteBuffer.putFloat(l, (float) (x + this.xOffset) + this.byteBuffer.getFloat(l)); + this.byteBuffer.putFloat(i1, (float) (y + this.yOffset) + this.byteBuffer.getFloat(i1)); + this.byteBuffer.putFloat(j1, (float) (z + this.zOffset) + this.byteBuffer.getFloat(j1)); + } + } - private final Vector3f tmpVec1 = new Vector3f(); - private final Vector3f tmpVec2 = new Vector3f(); - private final Vector3f tmpVec3 = new Vector3f(); - private final Vector3f tmpVec4 = new Vector3f(); - private final Vector3f tmpVec5 = new Vector3f(); - private final Vector3f tmpVec6 = new Vector3f(); - - public void genNormals(boolean b, int vertId) { - VertexFormat fmt = this.vertexFormat; - int i1 = fmt.attribStride; - int j1 = (this.vertexCount - 4) * i1; - tmpVec1.x = this.byteBuffer.getFloat(j1); - tmpVec1.y = this.byteBuffer.getFloat(j1 + 4); - tmpVec1.z = this.byteBuffer.getFloat(j1 + 8); - j1 += i1; - tmpVec2.x = this.byteBuffer.getFloat(j1); - tmpVec2.y = this.byteBuffer.getFloat(j1 + 4); - tmpVec2.z = this.byteBuffer.getFloat(j1 + 8); - j1 += i1 * 2; - tmpVec3.x = this.byteBuffer.getFloat(j1); - tmpVec3.y = this.byteBuffer.getFloat(j1 + 4); - tmpVec3.z = this.byteBuffer.getFloat(j1 + 8); - Vector3f.sub(tmpVec1, tmpVec2, tmpVec4); - Vector3f.sub(tmpVec3, tmpVec2, tmpVec5); - Vector3f.cross(tmpVec5, tmpVec4, tmpVec6); - float f = (float) Math - .sqrt((double) (tmpVec6.x * tmpVec6.x + tmpVec6.y * tmpVec6.y + tmpVec6.z * tmpVec6.z)); - tmpVec6.x /= f; - tmpVec6.y /= f; - tmpVec6.z /= f; - int i = (byte) ((int) (tmpVec6.x * 127.0F)) & 255; - int j = (byte) ((int) (tmpVec6.y * 127.0F)) & 255; - int k = (byte) ((int) (tmpVec6.z * 127.0F)) & 255; - int l = i | j << 8 | k << 16 | vertId << 24; - int jj1 = (this.vertexCount - 4) * i1 + fmt.attribNormalOffset; - this.byteBuffer.putInt(jj1, l); - this.byteBuffer.putInt(jj1 + i1, l); - if(!b) { - this.byteBuffer.putInt(jj1 + i1 * 2, l); - } - this.byteBuffer.putInt(jj1 + i1 * 3, l); - if(b) { - j1 = (this.vertexCount - 2) * i1; - tmpVec1.x = this.byteBuffer.getFloat(j1); - tmpVec1.y = this.byteBuffer.getFloat(j1 + 4); - tmpVec1.z = this.byteBuffer.getFloat(j1 + 8); - Vector3f.sub(tmpVec2, tmpVec1, tmpVec4); - Vector3f.sub(tmpVec3, tmpVec1, tmpVec5); - Vector3f.cross(tmpVec5, tmpVec4, tmpVec6); - f = (float) Math.sqrt((double) (tmpVec6.x * tmpVec6.x + tmpVec6.y * tmpVec6.y + tmpVec6.z * tmpVec6.z)); - tmpVec6.x /= f; - tmpVec6.y /= f; - tmpVec6.z /= f; - i = (byte) ((int) (tmpVec6.x * 127.0F)) & 255; - j = (byte) ((int) (tmpVec6.y * 127.0F)) & 255; - k = (byte) ((int) (tmpVec6.z * 127.0F)) & 255; - l = i | j << 8 | k << 16 | vertId << 24; - this.byteBuffer.putInt(jj1 + i1 * 2, l); - } + public void reset() { + this.vertexCount = 0; + this.byteBuffer.clear(); + this.intBuffer.clear(); } /** @@ -480,65 +528,24 @@ public class WorldRenderer { this.zOffset = z; } - public void finishDrawing() { - if (!this.isDrawing) { - throw new IllegalStateException("Not building!"); - } else { - this.isDrawing = false; - this.byteBuffer.position(0); - this.byteBuffer.limit(this.vertexCount * this.vertexFormat.attribStride); - } + /** + * SLOW AND STUPID COMPANION FUNCTION TO 'func_181672_a' + */ + public void setVertexState(WorldRenderer.State state) { + this.grow(state.getRawBuffer().length); + int p = intBuffer.position(); + this.intBuffer.position(0); + this.intBuffer.put(state.getRawBuffer()); + this.intBuffer.position(p); + this.vertexCount = state.getVertexCount(); + this.vertexFormat = state.getVertexFormat(); } - public ByteBuffer getByteBuffer() { - return this.byteBuffer; - } - - public VertexFormat getVertexFormat() { - return this.vertexFormat; - } - - public int getVertexCount() { - return this.vertexCount; - } - - public int getDrawMode() { - return this.drawMode; - } - - public void putColor4(int argb) { - for (int i = 0; i < 4; ++i) { - this.putColor(argb, i + 1); - } - - } - - public void putColorRGB_F4(float red, float green, float blue) { - for (int i = 0; i < 4; ++i) { - this.putColorRGB_F(red, green, blue, i + 1); - } - - } - - public class State { - private final int[] stateRawBuffer; - private final VertexFormat stateVertexFormat; - - public State(int[] parArrayOfInt, VertexFormat parVertexFormat) { - this.stateRawBuffer = parArrayOfInt; - this.stateVertexFormat = parVertexFormat; - } - - public int[] getRawBuffer() { - return this.stateRawBuffer; - } - - public int getVertexCount() { - return this.stateRawBuffer.length / (this.stateVertexFormat.attribStride >> 2); - } - - public VertexFormat getVertexFormat() { - return this.stateVertexFormat; - } + public WorldRenderer tex(double parDouble1, double parDouble2) { + VertexFormat fmt = this.vertexFormat; + int i = this.vertexCount * fmt.attribStride + fmt.attribTextureOffset; + this.byteBuffer.putFloat(i, (float) parDouble1); + this.byteBuffer.putFloat(i + 4, (float) parDouble2); + return this; } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldVertexBufferUploader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldVertexBufferUploader.java index 18d3c292..70918bdd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldVertexBufferUploader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/WorldVertexBufferUploader.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; /** * Copyright (c) 2022 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,8 +25,7 @@ public class WorldVertexBufferUploader { VertexFormat fmt = parWorldRenderer.getVertexFormat(); ByteBuffer buf = parWorldRenderer.getByteBuffer(); buf.position(0).limit(cunt * fmt.attribStride); - EaglercraftGPU.renderBuffer(buf, fmt.eaglercraftAttribBits, - parWorldRenderer.getDrawMode(), cunt); + EaglercraftGPU.renderBuffer(buf, fmt.eaglercraftAttribBits, parWorldRenderer.getDrawMode(), cunt); parWorldRenderer.reset(); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/AbstractAcceleratedEffectRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/AbstractAcceleratedEffectRenderer.java index ff51e299..62c03da9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/AbstractAcceleratedEffectRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/AbstractAcceleratedEffectRenderer.java @@ -7,14 +7,15 @@ import net.minecraft.entity.Entity; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,27 +25,34 @@ public abstract class AbstractAcceleratedEffectRenderer implements IAcceleratedP public float partialTicks; @Override - public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, - int texSize, float particleSize, float r, float g, float b, float a) { - float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks - EntityFX.interpPosX); - float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks - EntityFX.interpPosY); - float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks - EntityFX.interpPosZ); + public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, int texSize, + float particleSize, float r, float g, float b, float a) { + float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks + - EntityFX.interpPosX); + float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks + - EntityFX.interpPosY); + float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks + - EntityFX.interpPosZ); drawParticle(xx, yy, zz, particleIndexX, particleIndexY, lightMapData, texSize, particleSize, r, g, b, a); } @Override - public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, - int texSize, float particleSize, int rgba) { - float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks - EntityFX.interpPosX); - float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks - EntityFX.interpPosY); - float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks - EntityFX.interpPosZ); + public void drawParticle(Entity entityIn, int particleIndexX, int particleIndexY, int lightMapData, int texSize, + float particleSize, int rgba) { + float xx = (float) (entityIn.prevPosX + (entityIn.posX - entityIn.prevPosX) * (double) partialTicks + - EntityFX.interpPosX); + float yy = (float) (entityIn.prevPosY + (entityIn.posY - entityIn.prevPosY) * (double) partialTicks + - EntityFX.interpPosY); + float zz = (float) (entityIn.prevPosZ + (entityIn.posZ - entityIn.prevPosZ) * (double) partialTicks + - EntityFX.interpPosZ); drawParticle(xx, yy, zz, particleIndexX, particleIndexY, lightMapData, texSize, particleSize, rgba); } @Override public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, int lightMapData, int texSize, float particleSize, float r, float g, float b, float a) { - int color = ((int)(a * 255.0f) << 24) | ((int)(r * 255.0f) << 16) | ((int)(g * 255.0f) << 8) | (int)(b * 255.0f); + int color = ((int) (a * 255.0f) << 24) | ((int) (r * 255.0f) << 16) | ((int) (g * 255.0f) << 8) + | (int) (b * 255.0f); drawParticle(posX, posY, posZ, particleIndexX, particleIndexY, lightMapData, texSize, particleSize, color); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ArrayListSerial.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ArrayListSerial.java index d0e83030..91d0ebad 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ArrayListSerial.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ArrayListSerial.java @@ -5,14 +5,15 @@ import java.util.ArrayList; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,13 +31,8 @@ public class ArrayListSerial extends ArrayList implements ListSerial { super(initialSize); } - public E set(int index, E element) { - ++modCountEagler; - return super.set(index, element); - } - - public int getEaglerSerial() { - return (modCount << 8) + modCountEagler; + public boolean eaglerCheck() { + return mark != getEaglerSerial(); } public void eaglerIncrSerial() { @@ -47,8 +43,13 @@ public class ArrayListSerial extends ArrayList implements ListSerial { mark = getEaglerSerial(); } - public boolean eaglerCheck() { - return mark != getEaglerSerial(); + public int getEaglerSerial() { + return (modCount << 8) + modCountEagler; + } + + public E set(int index, E element) { + ++modCountEagler; + return super.set(index, element); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BetterFrustum.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BetterFrustum.java index 94a0836d..67b3a2ba 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BetterFrustum.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BetterFrustum.java @@ -209,450 +209,27 @@ public class BetterFrustum { } /** - * Update the stored frustum planes of this - * {@link FrustumIntersection} with the given {@link Matrix4fc matrix}. - *

              - * Reference: - * Fast Extraction of Viewing Frustum Planes from the World-View-Projection - * Matrix + * Compute the signed distance from the given axis-aligned box to the + * plane. * - * @param m the {@link Matrix4fc matrix} to update this frustum - * culler's frustum planes from - * @return this + * @param minX the x-coordinate of the minimum corner + * @param minY the y-coordinate of the minimum corner + * @param minZ the z-coordinate of the minimum corner + * @param maxX the x-coordinate of the maximum corner + * @param maxY the y-coordinate of the maximum corner + * @param maxZ the z-coordinate of the maximum corner + * @param plane one of {@link #PLANE_NX}, {@link #PLANE_PX}, {@link #PLANE_NY}, + * {@link #PLANE_PY}, {@link #PLANE_NZ} and {@link #PLANE_PZ} + * @return the signed distance of the axis-aligned box to the plane */ - public BetterFrustum set(Matrix4f m) { - return set(m, true); + public float distanceToPlane(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, int plane) { + return planes[plane].x * (planes[plane].x < 0 ? maxX : minX) + + planes[plane].y * (planes[plane].y < 0 ? maxY : minY) + + planes[plane].z * (planes[plane].z < 0 ? maxZ : minZ) + planes[plane].w; } - /** - * Update the stored frustum planes of this - * {@link FrustumIntersection} with the given {@link Matrix4fc matrix} and allow - * to optimize the frustum plane extraction in the case when no intersection - * test is needed for spheres. - *

              - * Reference: - * Fast Extraction of Viewing Frustum Planes from the World-View-Projection - * Matrix - * - * @param m the {@link Matrix4fc matrix} to update - * this frustum culler's frustum planes - * from - * @param allowTestSpheres whether the methods - * {@link #testSphere(Vector3fc, float)}, - * {@link #testSphere(float, float, float, float)}, - * {@link #intersectSphere(Vector3fc, float)} or - * {@link #intersectSphere(float, float, float, float)} - * will be used. If no spheres need to be tested, then - * false should be used - * @return this - */ - public BetterFrustum set(Matrix4f m, boolean allowTestSpheres) { - float invl; - nxX = m.m03 + m.m00; - nxY = m.m13 + m.m10; - nxZ = m.m23 + m.m20; - nxW = m.m33 + m.m30; - if (allowTestSpheres) { - invl = 1.0f / (float)Math.sqrt(nxX * nxX + nxY * nxY + nxZ * nxZ); - nxX *= invl; - nxY *= invl; - nxZ *= invl; - nxW *= invl; - } - planes[0].set(nxX, nxY, nxZ, nxW); - pxX = m.m03 - m.m00; - pxY = m.m13 - m.m10; - pxZ = m.m23 - m.m20; - pxW = m.m33 - m.m30; - if (allowTestSpheres) { - invl = 1.0f / (float)Math.sqrt(pxX * pxX + pxY * pxY + pxZ * pxZ); - pxX *= invl; - pxY *= invl; - pxZ *= invl; - pxW *= invl; - } - planes[1].set(pxX, pxY, pxZ, pxW); - nyX = m.m03 + m.m01; - nyY = m.m13 + m.m11; - nyZ = m.m23 + m.m21; - nyW = m.m33 + m.m31; - if (allowTestSpheres) { - invl = 1.0f / (float)Math.sqrt(nyX * nyX + nyY * nyY + nyZ * nyZ); - nyX *= invl; - nyY *= invl; - nyZ *= invl; - nyW *= invl; - } - planes[2].set(nyX, nyY, nyZ, nyW); - pyX = m.m03 - m.m01; - pyY = m.m13 - m.m11; - pyZ = m.m23 - m.m21; - pyW = m.m33 - m.m31; - if (allowTestSpheres) { - invl = 1.0f / (float)Math.sqrt(pyX * pyX + pyY * pyY + pyZ * pyZ); - pyX *= invl; - pyY *= invl; - pyZ *= invl; - pyW *= invl; - } - planes[3].set(pyX, pyY, pyZ, pyW); - nzX = m.m03 + m.m02; - nzY = m.m13 + m.m12; - nzZ = m.m23 + m.m22; - nzW = m.m33 + m.m32; - if (allowTestSpheres) { - invl = 1.0f / (float)Math.sqrt(nzX * nzX + nzY * nzY + nzZ * nzZ); - nzX *= invl; - nzY *= invl; - nzZ *= invl; - nzW *= invl; - } - planes[4].set(nzX, nzY, nzZ, nzW); - pzX = m.m03 - m.m02; - pzY = m.m13 - m.m12; - pzZ = m.m23 - m.m22; - pzW = m.m33 - m.m32; - if (allowTestSpheres) { - invl = 1.0f / (float)Math.sqrt(pzX * pzX + pzY * pzY + pzZ * pzZ); - pzX *= invl; - pzY *= invl; - pzZ *= invl; - pzW *= invl; - } - planes[5].set(pzX, pzY, pzZ, pzW); - return this; - } - - /** - * Test whether the given point is within the frustum defined by - * this frustum culler. - * - * @param point the point to test - * @return true if the given point is inside the frustum; - * false otherwise - */ - public boolean testPoint(Vector3f point) { - return testPoint(point.x, point.y, point.z); - } - - /** - * Test whether the given point (x, y, z) is within the frustum - * defined by this frustum culler. - * - * @param x the x-coordinate of the point - * @param y the y-coordinate of the point - * @param z the z-coordinate of the point - * @return true if the given point is inside the frustum; - * false otherwise - */ - public boolean testPoint(float x, float y, float z) { - return nxX * x + nxY * y + nxZ * z + nxW >= 0 && pxX * x + pxY * y + pxZ * z + pxW >= 0 - && nyX * x + nyY * y + nyZ * z + nyW >= 0 && pyX * x + pyY * y + pyZ * z + pyW >= 0 - && nzX * x + nzY * y + nzZ * z + nzW >= 0 && pzX * x + pzY * y + pzZ * z + pzW >= 0; - } - - /** - * Test whether the given sphere is partly or completely within or outside of - * the frustum defined by this frustum culler. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for spheres that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param center the sphere's center - * @param radius the sphere's radius - * @return true if the given sphere is partly or completely inside - * the frustum; false otherwise - */ - public boolean testSphere(Vector3f center, float radius) { - return testSphere(center.x, center.y, center.z, radius); - } - - /** - * Test whether the given sphere is partly or completely within or outside of - * the frustum defined by this frustum culler. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for spheres that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param x the x-coordinate of the sphere's center - * @param y the y-coordinate of the sphere's center - * @param z the z-coordinate of the sphere's center - * @param r the sphere's radius - * @return true if the given sphere is partly or completely inside - * the frustum; false otherwise - */ - public boolean testSphere(float x, float y, float z, float r) { - return nxX * x + nxY * y + nxZ * z + nxW >= -r && pxX * x + pxY * y + pxZ * z + pxW >= -r - && nyX * x + nyY * y + nyZ * z + nyW >= -r && pyX * x + pyY * y + pyZ * z + pyW >= -r - && nzX * x + nzY * y + nzZ * z + nzW >= -r && pzX * x + pzY * y + pzZ * z + pzW >= -r; - } - - /** - * Determine whether the given sphere is partly or completely within or outside - * of the frustum defined by this frustum culler. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns {@link #INTERSECT} for spheres that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param center the sphere's center - * @param radius the sphere's radius - * @return {@link #INSIDE} if the given sphere is completely inside the frustum, - * or {@link #INTERSECT} if the sphere intersects the frustum, or - * {@link #OUTSIDE} if the sphere is outside of the frustum - */ - public int intersectSphere(Vector3f center, float radius) { - return intersectSphere(center.x, center.y, center.z, radius); - } - - /** - * Determine whether the given sphere is partly or completely within or outside - * of the frustum defined by this frustum culler. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns {@link #INTERSECT} for spheres that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param x the x-coordinate of the sphere's center - * @param y the y-coordinate of the sphere's center - * @param z the z-coordinate of the sphere's center - * @param r the sphere's radius - * @return {@link #INSIDE} if the given sphere is completely inside the frustum, - * or {@link #INTERSECT} if the sphere intersects the frustum, or - * {@link #OUTSIDE} if the sphere is outside of the frustum - */ - public int intersectSphere(float x, float y, float z, float r) { - boolean inside = true; - float dist; - dist = nxX * x + nxY * y + nxZ * z + nxW; - if (dist >= -r) { - inside &= dist >= r; - dist = pxX * x + pxY * y + pxZ * z + pxW; - if (dist >= -r) { - inside &= dist >= r; - dist = nyX * x + nyY * y + nyZ * z + nyW; - if (dist >= -r) { - inside &= dist >= r; - dist = pyX * x + pyY * y + pyZ * z + pyW; - if (dist >= -r) { - inside &= dist >= r; - dist = nzX * x + nzY * y + nzZ * z + nzW; - if (dist >= -r) { - inside &= dist >= r; - dist = pzX * x + pzY * y + pzZ * z + pzW; - if (dist >= -r) { - inside &= dist >= r; - return inside ? INSIDE : INTERSECT; - } - } - } - } - } - } - return OUTSIDE; - } - - /** - * Test whether the given axis-aligned box is partly or completely within or - * outside of the frustum defined by this frustum culler. The box - * is specified via its min and max corner - * coordinates. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for boxes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param min the minimum corner coordinates of the axis-aligned box - * @param max the maximum corner coordinates of the axis-aligned box - * @return true if the axis-aligned box is completely or partly - * inside of the frustum; false otherwise - */ - public boolean testAab(Vector3f min, Vector3f max) { - return testAab(min.x, min.y, min.z, max.x, max.y, max.z); - } - - /** - * Test whether the given axis-aligned box is partly or completely within or - * outside of the frustum defined by this frustum culler. The box - * is specified via its min and max corner coordinates. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for boxes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - *

              - * Reference: - * Efficient View - * Frustum Culling - * - * @param minX the x-coordinate of the minimum corner - * @param minY the y-coordinate of the minimum corner - * @param minZ the z-coordinate of the minimum corner - * @param maxX the x-coordinate of the maximum corner - * @param maxY the y-coordinate of the maximum corner - * @param maxZ the z-coordinate of the maximum corner - * @return true if the axis-aligned box is completely or partly - * inside of the frustum; false otherwise - */ - public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { - /* - * This is an implementation of the "2.4 Basic intersection test" of the - * mentioned site. It does not distinguish between partially inside and fully - * inside, though, so the test with the 'p' vertex is omitted. - */ - return nxX * (nxX < 0 ? minX : maxX) + nxY * (nxY < 0 ? minY : maxY) + nxZ * (nxZ < 0 ? minZ : maxZ) >= -nxW - && pxX * (pxX < 0 ? minX : maxX) + pxY * (pxY < 0 ? minY : maxY) + pxZ * (pxZ < 0 ? minZ : maxZ) >= -pxW - && nyX * (nyX < 0 ? minX : maxX) + nyY * (nyY < 0 ? minY : maxY) + nyZ * (nyZ < 0 ? minZ : maxZ) >= -nyW - && pyX * (pyX < 0 ? minX : maxX) + pyY * (pyY < 0 ? minY : maxY) + pyZ * (pyZ < 0 ? minZ : maxZ) >= -pyW - && nzX * (nzX < 0 ? minX : maxX) + nzY * (nzY < 0 ? minY : maxY) + nzZ * (nzZ < 0 ? minZ : maxZ) >= -nzW - && pzX * (pzX < 0 ? minX : maxX) + pzY * (pzY < 0 ? minY : maxY) - + pzZ * (pzZ < 0 ? minZ : maxZ) >= -pzW; - } - - /** - * Test whether the given XY-plane (at Z = 0) is partly or - * completely within or outside of the frustum defined by this - * frustum culler. The plane is specified via its min and - * max corner coordinates. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for planes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param min the minimum corner coordinates of the XY-plane - * @param max the maximum corner coordinates of the XY-plane - * @return true if the XY-plane is completely or partly inside of - * the frustum; false otherwise - */ - public boolean testPlaneXY(Vector2f min, Vector2f max) { - return testPlaneXY(min.x, min.y, max.x, max.y); - } - - /** - * Test whether the given XY-plane (at Z = 0) is partly or - * completely within or outside of the frustum defined by this - * frustum culler. The plane is specified via its min and max corner - * coordinates. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for planes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - *

              - * Reference: - * Efficient View - * Frustum Culling - * - * @param minX the x-coordinate of the minimum corner - * @param minY the y-coordinate of the minimum corner - * @param maxX the x-coordinate of the maximum corner - * @param maxY the y-coordinate of the maximum corner - * @return true if the XY-plane is completely or partly inside of - * the frustum; false otherwise - */ - public boolean testPlaneXY(float minX, float minY, float maxX, float maxY) { - /* - * This is an implementation of the "2.4 Basic intersection test" of the - * mentioned site. It does not distinguish between partially inside and fully - * inside, though, so the test with the 'p' vertex is omitted. - */ - return nxX * (nxX < 0 ? minX : maxX) + nxY * (nxY < 0 ? minY : maxY) >= -nxW - && pxX * (pxX < 0 ? minX : maxX) + pxY * (pxY < 0 ? minY : maxY) >= -pxW - && nyX * (nyX < 0 ? minX : maxX) + nyY * (nyY < 0 ? minY : maxY) >= -nyW - && pyX * (pyX < 0 ? minX : maxX) + pyY * (pyY < 0 ? minY : maxY) >= -pyW - && nzX * (nzX < 0 ? minX : maxX) + nzY * (nzY < 0 ? minY : maxY) >= -nzW - && pzX * (pzX < 0 ? minX : maxX) + pzY * (pzY < 0 ? minY : maxY) >= -pzW; - } - - /** - * Test whether the given XZ-plane (at Y = 0) is partly or - * completely within or outside of the frustum defined by this - * frustum culler. The plane is specified via its min and max corner - * coordinates. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns true for planes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - *

              - * Reference: - * Efficient View - * Frustum Culling - * - * @param minX the x-coordinate of the minimum corner - * @param minZ the z-coordinate of the minimum corner - * @param maxX the x-coordinate of the maximum corner - * @param maxZ the z-coordinate of the maximum corner - * @return true if the XZ-plane is completely or partly inside of - * the frustum; false otherwise - */ - public boolean testPlaneXZ(float minX, float minZ, float maxX, float maxZ) { - /* - * This is an implementation of the "2.4 Basic intersection test" of the - * mentioned site. It does not distinguish between partially inside and fully - * inside, though, so the test with the 'p' vertex is omitted. - */ - return nxX * (nxX < 0 ? minX : maxX) + nxZ * (nxZ < 0 ? minZ : maxZ) >= -nxW - && pxX * (pxX < 0 ? minX : maxX) + pxZ * (pxZ < 0 ? minZ : maxZ) >= -pxW - && nyX * (nyX < 0 ? minX : maxX) + nyZ * (nyZ < 0 ? minZ : maxZ) >= -nyW - && pyX * (pyX < 0 ? minX : maxX) + pyZ * (pyZ < 0 ? minZ : maxZ) >= -pyW - && nzX * (nzX < 0 ? minX : maxX) + nzZ * (nzZ < 0 ? minZ : maxZ) >= -nzW - && pzX * (pzX < 0 ? minX : maxX) + pzZ * (pzZ < 0 ? minZ : maxZ) >= -pzW; - } - - /** - * Determine whether the given axis-aligned box is partly or completely within - * or outside of the frustum defined by this frustum culler and, if - * the box is not inside this frustum, return the index of the plane that culled - * it. The box is specified via its min and max corner - * coordinates. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns {@link #INTERSECT} for boxes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param min the minimum corner coordinates of the axis-aligned box - * @param max the maximum corner coordinates of the axis-aligned box - * @return the index of the first plane that culled the box, if the box does not - * intersect the frustum; or {@link #INTERSECT} if the box intersects - * the frustum, or {@link #INSIDE} if the box is fully inside of the - * frustum. The plane index is one of {@link #PLANE_NX}, - * {@link #PLANE_PX}, {@link #PLANE_NY}, {@link #PLANE_PY}, - * {@link #PLANE_NZ} and {@link #PLANE_PZ} - */ - public int intersectAab(Vector3f min, Vector3f max) { - return intersectAab(min.x, min.y, min.z, max.x, max.y, max.z); + private float fma(float f1, float f2, float f3) { + return (f1 * f2) + f3; } /** @@ -732,64 +309,6 @@ public class BetterFrustum { return plane; } - /** - * Compute the signed distance from the given axis-aligned box to the - * plane. - * - * @param minX the x-coordinate of the minimum corner - * @param minY the y-coordinate of the minimum corner - * @param minZ the z-coordinate of the minimum corner - * @param maxX the x-coordinate of the maximum corner - * @param maxY the y-coordinate of the maximum corner - * @param maxZ the z-coordinate of the maximum corner - * @param plane one of {@link #PLANE_NX}, {@link #PLANE_PX}, {@link #PLANE_NY}, - * {@link #PLANE_PY}, {@link #PLANE_NZ} and {@link #PLANE_PZ} - * @return the signed distance of the axis-aligned box to the plane - */ - public float distanceToPlane(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, int plane) { - return planes[plane].x * (planes[plane].x < 0 ? maxX : minX) - + planes[plane].y * (planes[plane].y < 0 ? maxY : minY) - + planes[plane].z * (planes[plane].z < 0 ? maxZ : minZ) + planes[plane].w; - } - - /** - * Determine whether the given axis-aligned box is partly or completely within - * or outside of the frustum defined by this frustum culler and, if - * the box is not inside this frustum, return the index of the plane that culled - * it. The box is specified via its min and max corner - * coordinates. - *

              - * This method differs from {@link #intersectAab(Vector3fc, Vector3fc)} in that - * it allows to mask-off planes that should not be calculated. For example, in - * order to only test a box against the left frustum plane, use a mask of - * {@link #PLANE_MASK_NX}. Or in order to test all planes except the left - * plane, use a mask of (~0 ^ PLANE_MASK_NX). - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns {@link #INTERSECT} for boxes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param min the minimum corner coordinates of the axis-aligned box - * @param max the maximum corner coordinates of the axis-aligned box - * @param mask contains as bitset all the planes that should be tested. This - * value can be any combination of {@link #PLANE_MASK_NX}, - * {@link #PLANE_MASK_PX}, {@link #PLANE_MASK_NY}, - * {@link #PLANE_MASK_PY}, {@link #PLANE_MASK_NZ} and - * {@link #PLANE_MASK_PZ} - * @return the index of the first plane that culled the box, if the box does not - * intersect the frustum, or {@link #INTERSECT} if the box intersects - * the frustum, or {@link #INSIDE} if the box is fully inside of the - * frustum. The plane index is one of {@link #PLANE_NX}, - * {@link #PLANE_PX}, {@link #PLANE_NY}, {@link #PLANE_PY}, - * {@link #PLANE_NZ} and {@link #PLANE_PZ} - */ - public int intersectAab(Vector3f min, Vector3f max, int mask) { - return intersectAab(min.x, min.y, min.z, max.x, max.y, max.z, mask); - } - /** * Determine whether the given axis-aligned box is partly or completely within * or outside of the frustum defined by this frustum culler and, if @@ -881,57 +400,6 @@ public class BetterFrustum { return plane; } - /** - * Determine whether the given axis-aligned box is partly or completely within - * or outside of the frustum defined by this frustum culler and, if - * the box is not inside this frustum, return the index of the plane that culled - * it. The box is specified via its min and max corner - * coordinates. - *

              - * This method differs from {@link #intersectAab(Vector3fc, Vector3fc)} in that - * it allows to mask-off planes that should not be calculated. For example, in - * order to only test a box against the left frustum plane, use a mask of - * {@link #PLANE_MASK_NX}. Or in order to test all planes except the left - * plane, use a mask of (~0 ^ PLANE_MASK_NX). - *

              - * In addition, the startPlane denotes the first frustum plane to - * test the box against. To use this effectively means to store the plane that - * previously culled an axis-aligned box (as returned by - * intersectAab()) and in the next frame use the return value as - * the argument to the startPlane parameter of this method. The - * assumption is that the plane that culled the object previously will also cull - * it now (temporal coherency) and the culling computation is likely reduced in - * that case. - *

              - * The algorithm implemented by this method is conservative. This means that in - * certain circumstances a false positive can occur, when the method - * returns {@link #INTERSECT} for boxes that do not intersect the frustum. See - * iquilezles.org - * for an examination of this problem. - * - * @param min the minimum corner coordinates of the axis-aligned box - * @param max the maximum corner coordinates of the axis-aligned box - * @param mask contains as bitset all the planes that should be tested. - * This value can be any combination of - * {@link #PLANE_MASK_NX}, {@link #PLANE_MASK_PX}, - * {@link #PLANE_MASK_NY}, {@link #PLANE_MASK_PY}, - * {@link #PLANE_MASK_NZ} and {@link #PLANE_MASK_PZ} - * @param startPlane the first frustum plane to test the axis-aligned box - * against. It is one of {@link #PLANE_NX}, {@link #PLANE_PX}, - * {@link #PLANE_NY}, {@link #PLANE_PY}, {@link #PLANE_NZ} and - * {@link #PLANE_PZ} - * @return the index of the first plane that culled the box, if the box does not - * intersect the frustum, or {@link #INTERSECT} if the box intersects - * the frustum, or {@link #INSIDE} if the box is fully inside of the - * frustum. The plane index is one of {@link #PLANE_NX}, - * {@link #PLANE_PX}, {@link #PLANE_NY}, {@link #PLANE_PY}, - * {@link #PLANE_NZ} and {@link #PLANE_PZ} - */ - public int intersectAab(Vector3f min, Vector3f max, int mask, int startPlane) { - return intersectAab(min.x, min.y, min.z, max.x, max.y, max.z, mask, startPlane); - } - /** * Determine whether the given axis-aligned box is partly or completely within * or outside of the frustum defined by this frustum culler and, if @@ -1043,21 +511,369 @@ public class BetterFrustum { } /** - * Test whether the given line segment, defined by the end points a - * and b, is partly or completely within the frustum defined by - * this frustum culler. + * Determine whether the given axis-aligned box is partly or completely within + * or outside of the frustum defined by this frustum culler and, if + * the box is not inside this frustum, return the index of the plane that culled + * it. The box is specified via its min and max corner + * coordinates. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns {@link #INTERSECT} for boxes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. * - * @param a the line segment's first end point - * @param b the line segment's second end point - * @return true if the given line segment is partly or completely - * inside the frustum; false otherwise + * @param min the minimum corner coordinates of the axis-aligned box + * @param max the maximum corner coordinates of the axis-aligned box + * @return the index of the first plane that culled the box, if the box does not + * intersect the frustum; or {@link #INTERSECT} if the box intersects + * the frustum, or {@link #INSIDE} if the box is fully inside of the + * frustum. The plane index is one of {@link #PLANE_NX}, + * {@link #PLANE_PX}, {@link #PLANE_NY}, {@link #PLANE_PY}, + * {@link #PLANE_NZ} and {@link #PLANE_PZ} */ - public boolean testLineSegment(Vector3f a, Vector3f b) { - return testLineSegment(a.x, a.y, a.z, b.x, b.y, b.z); + public int intersectAab(Vector3f min, Vector3f max) { + return intersectAab(min.x, min.y, min.z, max.x, max.y, max.z); } - private float fma(float f1, float f2, float f3) { - return (f1 * f2) + f3; + /** + * Determine whether the given axis-aligned box is partly or completely within + * or outside of the frustum defined by this frustum culler and, if + * the box is not inside this frustum, return the index of the plane that culled + * it. The box is specified via its min and max corner + * coordinates. + *

              + * This method differs from {@link #intersectAab(Vector3fc, Vector3fc)} in that + * it allows to mask-off planes that should not be calculated. For example, in + * order to only test a box against the left frustum plane, use a mask of + * {@link #PLANE_MASK_NX}. Or in order to test all planes except the left + * plane, use a mask of (~0 ^ PLANE_MASK_NX). + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns {@link #INTERSECT} for boxes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param min the minimum corner coordinates of the axis-aligned box + * @param max the maximum corner coordinates of the axis-aligned box + * @param mask contains as bitset all the planes that should be tested. This + * value can be any combination of {@link #PLANE_MASK_NX}, + * {@link #PLANE_MASK_PX}, {@link #PLANE_MASK_NY}, + * {@link #PLANE_MASK_PY}, {@link #PLANE_MASK_NZ} and + * {@link #PLANE_MASK_PZ} + * @return the index of the first plane that culled the box, if the box does not + * intersect the frustum, or {@link #INTERSECT} if the box intersects + * the frustum, or {@link #INSIDE} if the box is fully inside of the + * frustum. The plane index is one of {@link #PLANE_NX}, + * {@link #PLANE_PX}, {@link #PLANE_NY}, {@link #PLANE_PY}, + * {@link #PLANE_NZ} and {@link #PLANE_PZ} + */ + public int intersectAab(Vector3f min, Vector3f max, int mask) { + return intersectAab(min.x, min.y, min.z, max.x, max.y, max.z, mask); + } + + /** + * Determine whether the given axis-aligned box is partly or completely within + * or outside of the frustum defined by this frustum culler and, if + * the box is not inside this frustum, return the index of the plane that culled + * it. The box is specified via its min and max corner + * coordinates. + *

              + * This method differs from {@link #intersectAab(Vector3fc, Vector3fc)} in that + * it allows to mask-off planes that should not be calculated. For example, in + * order to only test a box against the left frustum plane, use a mask of + * {@link #PLANE_MASK_NX}. Or in order to test all planes except the left + * plane, use a mask of (~0 ^ PLANE_MASK_NX). + *

              + * In addition, the startPlane denotes the first frustum plane to + * test the box against. To use this effectively means to store the plane that + * previously culled an axis-aligned box (as returned by + * intersectAab()) and in the next frame use the return value as + * the argument to the startPlane parameter of this method. The + * assumption is that the plane that culled the object previously will also cull + * it now (temporal coherency) and the culling computation is likely reduced in + * that case. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns {@link #INTERSECT} for boxes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param min the minimum corner coordinates of the axis-aligned box + * @param max the maximum corner coordinates of the axis-aligned box + * @param mask contains as bitset all the planes that should be tested. + * This value can be any combination of + * {@link #PLANE_MASK_NX}, {@link #PLANE_MASK_PX}, + * {@link #PLANE_MASK_NY}, {@link #PLANE_MASK_PY}, + * {@link #PLANE_MASK_NZ} and {@link #PLANE_MASK_PZ} + * @param startPlane the first frustum plane to test the axis-aligned box + * against. It is one of {@link #PLANE_NX}, {@link #PLANE_PX}, + * {@link #PLANE_NY}, {@link #PLANE_PY}, {@link #PLANE_NZ} and + * {@link #PLANE_PZ} + * @return the index of the first plane that culled the box, if the box does not + * intersect the frustum, or {@link #INTERSECT} if the box intersects + * the frustum, or {@link #INSIDE} if the box is fully inside of the + * frustum. The plane index is one of {@link #PLANE_NX}, + * {@link #PLANE_PX}, {@link #PLANE_NY}, {@link #PLANE_PY}, + * {@link #PLANE_NZ} and {@link #PLANE_PZ} + */ + public int intersectAab(Vector3f min, Vector3f max, int mask, int startPlane) { + return intersectAab(min.x, min.y, min.z, max.x, max.y, max.z, mask, startPlane); + } + + /** + * Determine whether the given sphere is partly or completely within or outside + * of the frustum defined by this frustum culler. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns {@link #INTERSECT} for spheres that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param x the x-coordinate of the sphere's center + * @param y the y-coordinate of the sphere's center + * @param z the z-coordinate of the sphere's center + * @param r the sphere's radius + * @return {@link #INSIDE} if the given sphere is completely inside the frustum, + * or {@link #INTERSECT} if the sphere intersects the frustum, or + * {@link #OUTSIDE} if the sphere is outside of the frustum + */ + public int intersectSphere(float x, float y, float z, float r) { + boolean inside = true; + float dist; + dist = nxX * x + nxY * y + nxZ * z + nxW; + if (dist >= -r) { + inside &= dist >= r; + dist = pxX * x + pxY * y + pxZ * z + pxW; + if (dist >= -r) { + inside &= dist >= r; + dist = nyX * x + nyY * y + nyZ * z + nyW; + if (dist >= -r) { + inside &= dist >= r; + dist = pyX * x + pyY * y + pyZ * z + pyW; + if (dist >= -r) { + inside &= dist >= r; + dist = nzX * x + nzY * y + nzZ * z + nzW; + if (dist >= -r) { + inside &= dist >= r; + dist = pzX * x + pzY * y + pzZ * z + pzW; + if (dist >= -r) { + inside &= dist >= r; + return inside ? INSIDE : INTERSECT; + } + } + } + } + } + } + return OUTSIDE; + } + + /** + * Determine whether the given sphere is partly or completely within or outside + * of the frustum defined by this frustum culler. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns {@link #INTERSECT} for spheres that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param center the sphere's center + * @param radius the sphere's radius + * @return {@link #INSIDE} if the given sphere is completely inside the frustum, + * or {@link #INTERSECT} if the sphere intersects the frustum, or + * {@link #OUTSIDE} if the sphere is outside of the frustum + */ + public int intersectSphere(Vector3f center, float radius) { + return intersectSphere(center.x, center.y, center.z, radius); + } + + /** + * Update the stored frustum planes of this + * {@link FrustumIntersection} with the given {@link Matrix4fc matrix}. + *

              + * Reference: + * Fast Extraction of Viewing Frustum Planes from the World-View-Projection + * Matrix + * + * @param m the {@link Matrix4fc matrix} to update this frustum + * culler's frustum planes from + * @return this + */ + public BetterFrustum set(Matrix4f m) { + return set(m, true); + } + + /** + * Update the stored frustum planes of this + * {@link FrustumIntersection} with the given {@link Matrix4fc matrix} and allow + * to optimize the frustum plane extraction in the case when no intersection + * test is needed for spheres. + *

              + * Reference: + * Fast Extraction of Viewing Frustum Planes from the World-View-Projection + * Matrix + * + * @param m the {@link Matrix4fc matrix} to update + * this frustum culler's frustum planes + * from + * @param allowTestSpheres whether the methods + * {@link #testSphere(Vector3fc, float)}, + * {@link #testSphere(float, float, float, float)}, + * {@link #intersectSphere(Vector3fc, float)} or + * {@link #intersectSphere(float, float, float, float)} + * will be used. If no spheres need to be tested, then + * false should be used + * @return this + */ + public BetterFrustum set(Matrix4f m, boolean allowTestSpheres) { + float invl; + nxX = m.m03 + m.m00; + nxY = m.m13 + m.m10; + nxZ = m.m23 + m.m20; + nxW = m.m33 + m.m30; + if (allowTestSpheres) { + invl = 1.0f / (float) Math.sqrt(nxX * nxX + nxY * nxY + nxZ * nxZ); + nxX *= invl; + nxY *= invl; + nxZ *= invl; + nxW *= invl; + } + planes[0].set(nxX, nxY, nxZ, nxW); + pxX = m.m03 - m.m00; + pxY = m.m13 - m.m10; + pxZ = m.m23 - m.m20; + pxW = m.m33 - m.m30; + if (allowTestSpheres) { + invl = 1.0f / (float) Math.sqrt(pxX * pxX + pxY * pxY + pxZ * pxZ); + pxX *= invl; + pxY *= invl; + pxZ *= invl; + pxW *= invl; + } + planes[1].set(pxX, pxY, pxZ, pxW); + nyX = m.m03 + m.m01; + nyY = m.m13 + m.m11; + nyZ = m.m23 + m.m21; + nyW = m.m33 + m.m31; + if (allowTestSpheres) { + invl = 1.0f / (float) Math.sqrt(nyX * nyX + nyY * nyY + nyZ * nyZ); + nyX *= invl; + nyY *= invl; + nyZ *= invl; + nyW *= invl; + } + planes[2].set(nyX, nyY, nyZ, nyW); + pyX = m.m03 - m.m01; + pyY = m.m13 - m.m11; + pyZ = m.m23 - m.m21; + pyW = m.m33 - m.m31; + if (allowTestSpheres) { + invl = 1.0f / (float) Math.sqrt(pyX * pyX + pyY * pyY + pyZ * pyZ); + pyX *= invl; + pyY *= invl; + pyZ *= invl; + pyW *= invl; + } + planes[3].set(pyX, pyY, pyZ, pyW); + nzX = m.m03 + m.m02; + nzY = m.m13 + m.m12; + nzZ = m.m23 + m.m22; + nzW = m.m33 + m.m32; + if (allowTestSpheres) { + invl = 1.0f / (float) Math.sqrt(nzX * nzX + nzY * nzY + nzZ * nzZ); + nzX *= invl; + nzY *= invl; + nzZ *= invl; + nzW *= invl; + } + planes[4].set(nzX, nzY, nzZ, nzW); + pzX = m.m03 - m.m02; + pzY = m.m13 - m.m12; + pzZ = m.m23 - m.m22; + pzW = m.m33 - m.m32; + if (allowTestSpheres) { + invl = 1.0f / (float) Math.sqrt(pzX * pzX + pzY * pzY + pzZ * pzZ); + pzX *= invl; + pzY *= invl; + pzZ *= invl; + pzW *= invl; + } + planes[5].set(pzX, pzY, pzZ, pzW); + return this; + } + + /** + * Test whether the given axis-aligned box is partly or completely within or + * outside of the frustum defined by this frustum culler. The box + * is specified via its min and max corner coordinates. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for boxes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + *

              + * Reference: + * Efficient View + * Frustum Culling + * + * @param minX the x-coordinate of the minimum corner + * @param minY the y-coordinate of the minimum corner + * @param minZ the z-coordinate of the minimum corner + * @param maxX the x-coordinate of the maximum corner + * @param maxY the y-coordinate of the maximum corner + * @param maxZ the z-coordinate of the maximum corner + * @return true if the axis-aligned box is completely or partly + * inside of the frustum; false otherwise + */ + public boolean testAab(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + /* + * This is an implementation of the "2.4 Basic intersection test" of the + * mentioned site. It does not distinguish between partially inside and fully + * inside, though, so the test with the 'p' vertex is omitted. + */ + return nxX * (nxX < 0 ? minX : maxX) + nxY * (nxY < 0 ? minY : maxY) + nxZ * (nxZ < 0 ? minZ : maxZ) >= -nxW + && pxX * (pxX < 0 ? minX : maxX) + pxY * (pxY < 0 ? minY : maxY) + pxZ * (pxZ < 0 ? minZ : maxZ) >= -pxW + && nyX * (nyX < 0 ? minX : maxX) + nyY * (nyY < 0 ? minY : maxY) + nyZ * (nyZ < 0 ? minZ : maxZ) >= -nyW + && pyX * (pyX < 0 ? minX : maxX) + pyY * (pyY < 0 ? minY : maxY) + pyZ * (pyZ < 0 ? minZ : maxZ) >= -pyW + && nzX * (nzX < 0 ? minX : maxX) + nzY * (nzY < 0 ? minY : maxY) + nzZ * (nzZ < 0 ? minZ : maxZ) >= -nzW + && pzX * (pzX < 0 ? minX : maxX) + pzY * (pzY < 0 ? minY : maxY) + + pzZ * (pzZ < 0 ? minZ : maxZ) >= -pzW; + } + + /** + * Test whether the given axis-aligned box is partly or completely within or + * outside of the frustum defined by this frustum culler. The box + * is specified via its min and max corner + * coordinates. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for boxes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param min the minimum corner coordinates of the axis-aligned box + * @param max the maximum corner coordinates of the axis-aligned box + * @return true if the axis-aligned box is completely or partly + * inside of the frustum; false otherwise + */ + public boolean testAab(Vector3f min, Vector3f max) { + return testAab(min.x, min.y, min.z, max.x, max.y, max.z); } /** @@ -1166,4 +982,188 @@ public class BetterFrustum { return da >= 0.0f || db >= 0.0f; } + /** + * Test whether the given line segment, defined by the end points a + * and b, is partly or completely within the frustum defined by + * this frustum culler. + * + * @param a the line segment's first end point + * @param b the line segment's second end point + * @return true if the given line segment is partly or completely + * inside the frustum; false otherwise + */ + public boolean testLineSegment(Vector3f a, Vector3f b) { + return testLineSegment(a.x, a.y, a.z, b.x, b.y, b.z); + } + + /** + * Test whether the given XY-plane (at Z = 0) is partly or + * completely within or outside of the frustum defined by this + * frustum culler. The plane is specified via its min and max corner + * coordinates. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for planes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + *

              + * Reference: + * Efficient View + * Frustum Culling + * + * @param minX the x-coordinate of the minimum corner + * @param minY the y-coordinate of the minimum corner + * @param maxX the x-coordinate of the maximum corner + * @param maxY the y-coordinate of the maximum corner + * @return true if the XY-plane is completely or partly inside of + * the frustum; false otherwise + */ + public boolean testPlaneXY(float minX, float minY, float maxX, float maxY) { + /* + * This is an implementation of the "2.4 Basic intersection test" of the + * mentioned site. It does not distinguish between partially inside and fully + * inside, though, so the test with the 'p' vertex is omitted. + */ + return nxX * (nxX < 0 ? minX : maxX) + nxY * (nxY < 0 ? minY : maxY) >= -nxW + && pxX * (pxX < 0 ? minX : maxX) + pxY * (pxY < 0 ? minY : maxY) >= -pxW + && nyX * (nyX < 0 ? minX : maxX) + nyY * (nyY < 0 ? minY : maxY) >= -nyW + && pyX * (pyX < 0 ? minX : maxX) + pyY * (pyY < 0 ? minY : maxY) >= -pyW + && nzX * (nzX < 0 ? minX : maxX) + nzY * (nzY < 0 ? minY : maxY) >= -nzW + && pzX * (pzX < 0 ? minX : maxX) + pzY * (pzY < 0 ? minY : maxY) >= -pzW; + } + + /** + * Test whether the given XY-plane (at Z = 0) is partly or + * completely within or outside of the frustum defined by this + * frustum culler. The plane is specified via its min and + * max corner coordinates. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for planes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param min the minimum corner coordinates of the XY-plane + * @param max the maximum corner coordinates of the XY-plane + * @return true if the XY-plane is completely or partly inside of + * the frustum; false otherwise + */ + public boolean testPlaneXY(Vector2f min, Vector2f max) { + return testPlaneXY(min.x, min.y, max.x, max.y); + } + + /** + * Test whether the given XZ-plane (at Y = 0) is partly or + * completely within or outside of the frustum defined by this + * frustum culler. The plane is specified via its min and max corner + * coordinates. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for planes that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + *

              + * Reference: + * Efficient View + * Frustum Culling + * + * @param minX the x-coordinate of the minimum corner + * @param minZ the z-coordinate of the minimum corner + * @param maxX the x-coordinate of the maximum corner + * @param maxZ the z-coordinate of the maximum corner + * @return true if the XZ-plane is completely or partly inside of + * the frustum; false otherwise + */ + public boolean testPlaneXZ(float minX, float minZ, float maxX, float maxZ) { + /* + * This is an implementation of the "2.4 Basic intersection test" of the + * mentioned site. It does not distinguish between partially inside and fully + * inside, though, so the test with the 'p' vertex is omitted. + */ + return nxX * (nxX < 0 ? minX : maxX) + nxZ * (nxZ < 0 ? minZ : maxZ) >= -nxW + && pxX * (pxX < 0 ? minX : maxX) + pxZ * (pxZ < 0 ? minZ : maxZ) >= -pxW + && nyX * (nyX < 0 ? minX : maxX) + nyZ * (nyZ < 0 ? minZ : maxZ) >= -nyW + && pyX * (pyX < 0 ? minX : maxX) + pyZ * (pyZ < 0 ? minZ : maxZ) >= -pyW + && nzX * (nzX < 0 ? minX : maxX) + nzZ * (nzZ < 0 ? minZ : maxZ) >= -nzW + && pzX * (pzX < 0 ? minX : maxX) + pzZ * (pzZ < 0 ? minZ : maxZ) >= -pzW; + } + + /** + * Test whether the given point (x, y, z) is within the frustum + * defined by this frustum culler. + * + * @param x the x-coordinate of the point + * @param y the y-coordinate of the point + * @param z the z-coordinate of the point + * @return true if the given point is inside the frustum; + * false otherwise + */ + public boolean testPoint(float x, float y, float z) { + return nxX * x + nxY * y + nxZ * z + nxW >= 0 && pxX * x + pxY * y + pxZ * z + pxW >= 0 + && nyX * x + nyY * y + nyZ * z + nyW >= 0 && pyX * x + pyY * y + pyZ * z + pyW >= 0 + && nzX * x + nzY * y + nzZ * z + nzW >= 0 && pzX * x + pzY * y + pzZ * z + pzW >= 0; + } + + /** + * Test whether the given point is within the frustum defined by + * this frustum culler. + * + * @param point the point to test + * @return true if the given point is inside the frustum; + * false otherwise + */ + public boolean testPoint(Vector3f point) { + return testPoint(point.x, point.y, point.z); + } + + /** + * Test whether the given sphere is partly or completely within or outside of + * the frustum defined by this frustum culler. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for spheres that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param x the x-coordinate of the sphere's center + * @param y the y-coordinate of the sphere's center + * @param z the z-coordinate of the sphere's center + * @param r the sphere's radius + * @return true if the given sphere is partly or completely inside + * the frustum; false otherwise + */ + public boolean testSphere(float x, float y, float z, float r) { + return nxX * x + nxY * y + nxZ * z + nxW >= -r && pxX * x + pxY * y + pxZ * z + pxW >= -r + && nyX * x + nyY * y + nyZ * z + nyW >= -r && pyX * x + pyY * y + pyZ * z + pyW >= -r + && nzX * x + nzY * y + nzZ * z + nzW >= -r && pzX * x + pzY * y + pzZ * z + pzW >= -r; + } + + /** + * Test whether the given sphere is partly or completely within or outside of + * the frustum defined by this frustum culler. + *

              + * The algorithm implemented by this method is conservative. This means that in + * certain circumstances a false positive can occur, when the method + * returns true for spheres that do not intersect the frustum. See + * iquilezles.org + * for an examination of this problem. + * + * @param center the sphere's center + * @param radius the sphere's radius + * @return true if the given sphere is partly or completely inside + * the frustum; false otherwise + */ + public boolean testSphere(Vector3f center, float radius) { + return testSphere(center.x, center.y, center.z, radius); + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BlockVertexIDs.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BlockVertexIDs.java index 2b5a2730..868e9f02 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BlockVertexIDs.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/BlockVertexIDs.java @@ -16,14 +16,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,7 +33,7 @@ public class BlockVertexIDs implements IResourceManagerReloadListener { private static final Logger logger = LogManager.getLogger("BlockVertexIDsCSV"); - public static final Map modelToID = new HashMap<>(); + public static final Map modelToID = new HashMap<>(); public static int builtin_water_still_vertex_id = 0; public static int builtin_water_flow_vertex_id = 0; @@ -46,23 +47,23 @@ public class BlockVertexIDs implements IResourceManagerReloadListener { modelToID.clear(); String line; boolean firstLine = true; - while((line = reader.readLine()) != null) { - if((line = line.trim()).length() > 0) { - if(firstLine) { + while ((line = reader.readLine()) != null) { + if ((line = line.trim()).length() > 0) { + if (firstLine) { firstLine = false; continue; } String[] split = line.split(","); - if(split.length == 2) { + if (split.length == 2) { try { int i = Integer.parseInt(split[1]); - if(i <= 0 || i > 254) { + if (i <= 0 || i > 254) { logger.error("Error: {}: Only IDs 1 to 254 are configurable!", split[0]); throw new NumberFormatException(); } i -= 127; modelToID.put(split[0], i); - switch(split[0]) { + switch (split[0]) { case "eagler:builtin/water_still_vertex_id": builtin_water_still_vertex_id = i; break; @@ -73,14 +74,14 @@ public class BlockVertexIDs implements IResourceManagerReloadListener { break; } continue; - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { } } logger.error("Skipping bad vertex id entry: {}", line); } } } - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Could not load list of vertex ids!"); logger.error(t); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/CloudRenderWorker.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/CloudRenderWorker.java index 05698c41..15e12736 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/CloudRenderWorker.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/CloudRenderWorker.java @@ -1,8 +1,45 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTextureLayer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage3D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix3x2fv; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4x3fv; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CONSTANT_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DST_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_CONSTANT_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RED; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE1; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_3D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_R; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT0; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_FRAMEBUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_R8; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; @@ -27,14 +64,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -100,6 +138,95 @@ public class CloudRenderWorker { static EaglercraftRandom rand = new EaglercraftRandom(); + static void bindParaboloid() { + GlStateManager.bindTexture(cloudNoiseSampleParaboloidTexture[3]); + } + + static boolean checkFrustum(Matrix3f mat) { + Vector3f tmp = tmpVector1; + tmp.x = -1.0f; + tmp.y = -1.0f; + tmp.z = 1.0f; + Matrix3f.transform(mat, tmp, tmp); + if (tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { + return true; + } + tmp.x = 1.0f; + tmp.y = -1.0f; + Matrix3f.transform(mat, tmp, tmp); + if (tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { + return true; + } + tmp.x = 1.0f; + tmp.y = 1.0f; + Matrix3f.transform(mat, tmp, tmp); + if (tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { + return true; + } + tmp.x = -1.0f; + tmp.y = 1.0f; + Matrix3f.transform(mat, tmp, tmp); + if (tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { + return true; + } + return false; + } + + static void destroy() { + if (cloudNoiseTexture != -1) { + GlStateManager.deleteTexture(cloudNoiseTexture); + cloudNoiseTexture = -1; + } + for (int i = 0; i < 4; ++i) { + if (cloudNoiseSampleParaboloidFramebuffer[i] != null) { + _wglDeleteFramebuffer(cloudNoiseSampleParaboloidFramebuffer[i]); + cloudNoiseSampleParaboloidFramebuffer[i] = null; + } + if (cloudNoiseSampleParaboloidTexture[i] != -1) { + GlStateManager.deleteTexture(cloudNoiseSampleParaboloidTexture[i]); + cloudNoiseSampleParaboloidTexture[i] = -1; + } + } + if (cloud3DSamplesTexture != -1) { + GlStateManager.deleteTexture(cloud3DSamplesTexture); + cloud3DSamplesTexture = -1; + } + if (cloud3DSamplesSlices != null) { + for (int i = 0; i < cloud3DSamplesSlices.length; ++i) { + _wglDeleteFramebuffer(cloud3DSamplesSlices[i]); + } + cloud3DSamplesSlices = null; + } + if (cloudSpecialShapeTexture != -1) { + GlStateManager.deleteTexture(cloudSpecialShapeTexture); + cloudSpecialShapeTexture = -1; + } + if (cloudOcclusionFramebuffer != null) { + _wglDeleteFramebuffer(cloudOcclusionFramebuffer); + cloudOcclusionFramebuffer = null; + } + if (cloudOcclusionTexture != -1) { + GlStateManager.deleteTexture(cloudOcclusionTexture); + cloudOcclusionTexture = -1; + } + if (shader_clouds_noise3d != null) { + shader_clouds_noise3d.destroy(); + shader_clouds_noise3d = null; + } + if (shader_clouds_shapes != null) { + shader_clouds_shapes.destroy(); + shader_clouds_shapes = null; + } + if (shader_clouds_sample != null) { + shader_clouds_sample.destroy(); + shader_clouds_sample = null; + } + if (shader_clouds_sun_occlusion != null) { + shader_clouds_sun_occlusion.destroy(); + shader_clouds_sun_occlusion = null; + } + } + static void initialize() { destroy(); @@ -126,7 +253,8 @@ public class CloudRenderWorker { ByteBuffer cloudNoiseDatBuffer = EagRuntime.allocateByteBuffer(cloudNoiseDat.length); cloudNoiseDatBuffer.put(cloudNoiseDat); cloudNoiseDatBuffer.flip(); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, cloudNoiseW, cloudNoiseH, 0, GL_RED, GL_UNSIGNED_BYTE, cloudNoiseDatBuffer); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, cloudNoiseW, cloudNoiseH, 0, GL_RED, GL_UNSIGNED_BYTE, + cloudNoiseDatBuffer); EagRuntime.freeByteBuffer(cloudNoiseDatBuffer); cloud3DSamplesTexture = GlStateManager.generateTexture(); @@ -140,14 +268,15 @@ public class CloudRenderWorker { cloud3DSamplesTextureSizeZ, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer) null); cloud3DSamplesSlices = new IFramebufferGL[cloud3DSamplesTextureSizeZ]; - for(int i = 0; i < cloud3DSamplesTextureSizeZ; ++i) { + for (int i = 0; i < cloud3DSamplesTextureSizeZ; ++i) { cloud3DSamplesSlices[i] = _wglCreateFramebuffer(); _wglBindFramebuffer(_GL_FRAMEBUFFER, cloud3DSamplesSlices[i]); - _wglFramebufferTextureLayer(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, EaglercraftGPU.getNativeTexture(cloud3DSamplesTexture), 0, i); + _wglFramebufferTextureLayer(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, + EaglercraftGPU.getNativeTexture(cloud3DSamplesTexture), 0, i); } GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 1.0f); - for(int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; ++i) { cloudNoiseSampleParaboloidFramebuffer[i] = _wglCreateFramebuffer(); _wglBindFramebuffer(_GL_FRAMEBUFFER, cloudNoiseSampleParaboloidFramebuffer[i]); cloudNoiseSampleParaboloidTexture[i] = GlStateManager.generateTexture(); @@ -156,8 +285,10 @@ public class CloudRenderWorker { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, i == 3 ? GL_LINEAR : GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, i == 3 ? GL_LINEAR : GL_NEAREST); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, cloudParaboloidTextureSize, cloudParaboloidTextureSize, GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(cloudNoiseSampleParaboloidTexture[i]), 0); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, cloudParaboloidTextureSize, + cloudParaboloidTextureSize, GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(cloudNoiseSampleParaboloidTexture[i]), 0); GlStateManager.clear(GL_COLOR_BUFFER_BIT); } @@ -168,11 +299,13 @@ public class CloudRenderWorker { _wglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); _wglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); _wglTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - byte[] cloudShapeTexture = EagRuntime.getRequiredResourceBytes("/assets/eagler/glsl/deferred/clouds_shapes.bmp"); + byte[] cloudShapeTexture = EagRuntime + .getRequiredResourceBytes("/assets/eagler/glsl/deferred/clouds_shapes.bmp"); cloudNoiseDatBuffer = EagRuntime.allocateByteBuffer(cloudShapeTexture.length); cloudNoiseDatBuffer.put(cloudShapeTexture); cloudNoiseDatBuffer.flip(); - _wglTexImage3D(GL_TEXTURE_3D, 0, _GL_R8, 32, 16, 24, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer) cloudNoiseDatBuffer); + _wglTexImage3D(GL_TEXTURE_3D, 0, _GL_R8, 32, 16, 24, 0, GL_RED, GL_UNSIGNED_BYTE, + (ByteBuffer) cloudNoiseDatBuffer); EagRuntime.freeByteBuffer(cloudNoiseDatBuffer); shader_clouds_noise3d = PipelineShaderCloudsNoise3D.compile(); @@ -192,8 +325,9 @@ public class CloudRenderWorker { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer)null); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(cloudOcclusionTexture), 0); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer) null); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(cloudOcclusionTexture), 0); } static void setPosition(float x, float y, float z) { @@ -202,17 +336,13 @@ public class CloudRenderWorker { renderViewZ = z; } - static void bindParaboloid() { - GlStateManager.bindTexture(cloudNoiseSampleParaboloidTexture[3]); - } - static void update() { long millis = EagRuntime.steadyTimeMillis(); - int cloudProgress = (int)(millis - cloudStartTimer); + int cloudProgress = (int) (millis - cloudStartTimer); int totalCloudSteps = 32 + 32 - 1; int currentCloudStep = cloudProgress * totalCloudSteps / cloudRenderPeriod; boolean b = false; - if(currentCloudStep > totalCloudSteps) { + if (currentCloudStep > totalCloudSteps) { currentCloudStep = totalCloudSteps; b = true; } @@ -222,12 +352,13 @@ public class CloudRenderWorker { WorldClient wc = Minecraft.getMinecraft().theWorld; float rain = wc.getRainStrength(0.0f); - if(cloudRenderProgress == 0) { + if (cloudRenderProgress == 0) { shader_clouds_noise3d.useProgram(); - _wglUniform2f(shader_clouds_noise3d.uniforms.u_textureSize2f, 1.0f / cloud3DSamplesTextureSizeX, 1.0f / cloud3DSamplesTextureSizeY); - float m = (float)((millis % 1200000l) * 0.00002); - _wglUniform3f(shader_clouds_noise3d.uniforms.u_cloudMovement3f, m, 0.0f, m);//2.213f, 0.0f, 2.213f); - + _wglUniform2f(shader_clouds_noise3d.uniforms.u_textureSize2f, 1.0f / cloud3DSamplesTextureSizeX, + 1.0f / cloud3DSamplesTextureSizeY); + float m = (float) ((millis % 1200000l) * 0.00002); + _wglUniform3f(shader_clouds_noise3d.uniforms.u_cloudMovement3f, m, 0.0f, m);// 2.213f, 0.0f, 2.213f); + tmpMatrix1.setIdentity(); tmpVector1.set(renderViewX * playerCoordsNoiseMapScale, 0.0f, renderViewZ * playerCoordsNoiseMapScale); Matrix4f.translate(tmpVector1, tmpMatrix1, tmpMatrix1); @@ -249,13 +380,14 @@ public class CloudRenderWorker { matrixCopyBuffer.put(tmpMatrix1.m32); matrixCopyBuffer.flip(); _wglUniformMatrix4x3fv(shader_clouds_noise3d.uniforms.u_sampleOffsetMatrix4f, false, matrixCopyBuffer); - + shader_clouds_sample.useProgram(); _wglUniform1f(shader_clouds_sample.uniforms.u_rainStrength1f, 0.0f); _wglUniform1f(shader_clouds_sample.uniforms.u_cloudTimer1f, 0.0f); _wglUniform3f(shader_clouds_sample.uniforms.u_cloudOffset3f, renderViewX, renderViewY, renderViewZ); Vector3f currentSunAngle = DeferredStateManager.currentSunLightAngle; - _wglUniform3f(shader_clouds_sample.uniforms.u_sunDirection3f, -currentSunAngle.x, -currentSunAngle.y, -currentSunAngle.z); + _wglUniform3f(shader_clouds_sample.uniforms.u_sunDirection3f, -currentSunAngle.x, -currentSunAngle.y, + -currentSunAngle.z); currentSunAngle = tmpVector1; currentSunAngle.set(DeferredStateManager.currentSunLightColor); float luma = currentSunAngle.x * 0.299f + currentSunAngle.y * 0.587f + currentSunAngle.z * 0.114f; @@ -267,35 +399,39 @@ public class CloudRenderWorker { cloudColorG += (currentSunAngle.y - cloudColorG) * 0.1f; cloudColorB += (currentSunAngle.z - cloudColorB) * 0.1f; _wglUniform3f(shader_clouds_sample.uniforms.u_sunColor3f, cloudColorR, cloudColorG, cloudColorB); - - float cloudDensityTimer = (float)((EagRuntime.steadyTimeMillis() % 10000000l) * 0.001); + + float cloudDensityTimer = (float) ((EagRuntime.steadyTimeMillis() % 10000000l) * 0.001); cloudDensityTimer += MathHelper.sin(cloudDensityTimer * 1.5f) * 1.5f; float x = cloudDensityTimer * 0.004f; - float f1 = MathHelper.sin(x + 0.322f) * 0.544f + MathHelper.sin(x * 4.5f + 1.843f) * 0.69f + MathHelper.sin(x * 3.4f + 0.8f) * 0.6f + MathHelper.sin(x * 6.1f + 1.72f) * 0.7f; + float f1 = MathHelper.sin(x + 0.322f) * 0.544f + MathHelper.sin(x * 4.5f + 1.843f) * 0.69f + + MathHelper.sin(x * 3.4f + 0.8f) * 0.6f + MathHelper.sin(x * 6.1f + 1.72f) * 0.7f; x = cloudDensityTimer * 0.002f; - float f2 = MathHelper.cos(x + 2.7f) + MathHelper.cos(x * 1.28f + 1.3f) * 0.4f + MathHelper.cos(x * 4.0f + 2.5f) * 0.3f + MathHelper.cos(x * 2.3f + 1.07f); + float f2 = MathHelper.cos(x + 2.7f) + MathHelper.cos(x * 1.28f + 1.3f) * 0.4f + + MathHelper.cos(x * 4.0f + 2.5f) * 0.3f + MathHelper.cos(x * 2.3f + 1.07f); float rain2 = rain + wc.getThunderStrength(0.0f); - _wglUniform4f(shader_clouds_sample.uniforms.u_densityModifier4f, 0.015f + f1 * 0.0021f * (1.0f - rain2 * 0.35f) + rain2 * 0.00023f, 0.0325f, -0.0172f + f2 * 0.00168f * (1.0f - rain2 * 0.35f) + rain * 0.0015f, 0.0f); + _wglUniform4f(shader_clouds_sample.uniforms.u_densityModifier4f, + 0.015f + f1 * 0.0021f * (1.0f - rain2 * 0.35f) + rain2 * 0.00023f, 0.0325f, + -0.0172f + f2 * 0.00168f * (1.0f - rain2 * 0.35f) + rain * 0.0015f, 0.0f); } - if(cloudRenderProgress < 32 && currentCloudStep > cloudRenderProgress) { + if (cloudRenderProgress < 32 && currentCloudStep > cloudRenderProgress) { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(cloudNoiseTexture); - + GlStateManager.viewport(0, 0, cloud3DSamplesTextureSizeX, cloud3DSamplesTextureSizeY); updateShape(); boolean shapeAllow = isDrawingCloudShapes; boolean shapeInit = false; - - for(int i = cloudRenderProgress, j = currentCloudStep < 32 ? currentCloudStep : 32; i < j; ++i) { + + for (int i = cloudRenderProgress, j = currentCloudStep < 32 ? currentCloudStep : 32; i < j; ++i) { int ccl = i * 2; boolean drawShape = false; - if(isDrawingCloudShapes && shapeAllow) { - if(ccl >= shapePosZ && ccl < shapePosZ + shapeSizeZ) { + if (isDrawingCloudShapes && shapeAllow) { + if (ccl >= shapePosZ && ccl < shapePosZ + shapeSizeZ) { drawShape = true; - if(!shapeInit) { + if (!shapeInit) { shapeInit = true; Matrix3f mat = tmpMatrix2; mat.setIdentity(); @@ -305,8 +441,8 @@ public class CloudRenderWorker { mat.m11 = mat.m00; mat = tmpMatrix3; mat.setIdentity(); - mat.m00 = (float)shapeSizeX * 0.5f; - mat.m11 = (float)shapeSizeY * 0.5f; + mat.m00 = (float) shapeSizeX * 0.5f; + mat.m11 = (float) shapeSizeY * 0.5f; Matrix3f.mul(tmpMatrix2, mat, tmpMatrix2); tmpMatrix2.m20 = shapePosX - renderViewX * playerCoordsNoiseMapScale * 128.0f; tmpMatrix2.m21 = shapePosY - renderViewZ * playerCoordsNoiseMapScale * 128.0f; @@ -317,10 +453,10 @@ public class CloudRenderWorker { mat = tmpMatrix2; mat.m20 -= 1.0f; mat.m21 -= 1.0f; - if(!checkFrustum(mat)) { + if (!checkFrustum(mat)) { drawShape = false; shapeAllow = false; - }else { + } else { matrixCopyBuffer.clear(); matrixCopyBuffer.put(mat.m00); matrixCopyBuffer.put(mat.m01); @@ -330,50 +466,55 @@ public class CloudRenderWorker { matrixCopyBuffer.put(mat.m21); matrixCopyBuffer.flip(); shader_clouds_shapes.useProgram(); - _wglUniformMatrix3x2fv(shader_clouds_shapes.uniforms.u_transformMatrix3x2f, false, matrixCopyBuffer); + _wglUniformMatrix3x2fv(shader_clouds_shapes.uniforms.u_transformMatrix3x2f, false, + matrixCopyBuffer); _wglUniform1f(shader_clouds_shapes.uniforms.u_textureLod1f, 0.0f); _wglUniform2f(shader_clouds_shapes.uniforms.u_sampleWeights2f, 0.35f, 0.55f); } } } } - + shader_clouds_noise3d.useProgram(); - + _wglBindFramebuffer(_GL_FRAMEBUFFER, cloud3DSamplesSlices[ccl]); - _wglUniform1f(shader_clouds_noise3d.uniforms.u_textureSlice1f, (float)(ccl / (float)cloud3DSamplesTextureSizeZ)); - + _wglUniform1f(shader_clouds_noise3d.uniforms.u_textureSlice1f, + (float) (ccl / (float) cloud3DSamplesTextureSizeZ)); + DrawUtils.drawStandardQuad2D(); - - if(drawShape) { + + if (drawShape) { GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_ONE, GL_SRC_ALPHA); shader_clouds_shapes.useProgram(); - _wglUniform1f(shader_clouds_shapes.uniforms.u_textureLevel1f, (float)(ccl - shapePosZ + 0.5f) / (float)shapeSizeZ); + _wglUniform1f(shader_clouds_shapes.uniforms.u_textureLevel1f, + (float) (ccl - shapePosZ + 0.5f) / (float) shapeSizeZ); GlStateManager.bindTexture3D(cloudSpecialShapeTexture); DrawUtils.drawStandardQuad2D(); GlStateManager.disableBlend(); shader_clouds_noise3d.useProgram(); GlStateManager.bindTexture(cloudNoiseTexture); } - + _wglBindFramebuffer(_GL_FRAMEBUFFER, cloud3DSamplesSlices[ccl + 1]); - _wglUniform1f(shader_clouds_noise3d.uniforms.u_textureSlice1f, (float)((ccl + 1) / (float)cloud3DSamplesTextureSizeZ)); - + _wglUniform1f(shader_clouds_noise3d.uniforms.u_textureSlice1f, + (float) ((ccl + 1) / (float) cloud3DSamplesTextureSizeZ)); + DrawUtils.drawStandardQuad2D(); - - if(drawShape && ccl + 1 < shapePosZ + shapeSizeZ) { + + if (drawShape && ccl + 1 < shapePosZ + shapeSizeZ) { GlStateManager.enableBlend(); shader_clouds_shapes.useProgram(); - _wglUniform1f(shader_clouds_shapes.uniforms.u_textureLevel1f, (float)((ccl + 1) - shapePosZ + 0.5f) / (float)shapeSizeZ); + _wglUniform1f(shader_clouds_shapes.uniforms.u_textureLevel1f, + (float) ((ccl + 1) - shapePosZ + 0.5f) / (float) shapeSizeZ); GlStateManager.bindTexture3D(cloudSpecialShapeTexture); DrawUtils.drawStandardQuad2D(); GlStateManager.disableBlend(); } } } - - if(currentCloudStep >= 32 && currentCloudStep > cloudRenderProgress) { + + if (currentCloudStep >= 32 && currentCloudStep > cloudRenderProgress) { _wglBindFramebuffer(_GL_FRAMEBUFFER, cloudNoiseSampleParaboloidFramebuffer[cloudRenderPhase]); GlStateManager.viewport(0, 0, cloudParaboloidTextureSize, cloudParaboloidTextureSize); @@ -382,61 +523,63 @@ public class CloudRenderWorker { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture3D(cloud3DSamplesTexture); shader_clouds_sample.useProgram(); - + GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL_DST_ALPHA, GL_ONE, GL_DST_ALPHA, GL_ZERO); - - for(int i = cloudRenderProgress > 32 ? cloudRenderProgress - 32 : 0, j = currentCloudStep - 31; i < j; ++i) { - if(i == 0) { + + for (int i = cloudRenderProgress > 32 ? cloudRenderProgress - 32 : 0, + j = currentCloudStep - 31; i < j; ++i) { + if (i == 0) { GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 1.0f); GlStateManager.clear(GL_COLOR_BUFFER_BIT); } - + _wglUniform1f(shader_clouds_sample.uniforms.u_sampleStep1f, i * 2); DrawUtils.drawStandardQuad2D(); - + _wglUniform1f(shader_clouds_sample.uniforms.u_sampleStep1f, i * 2 + 1); DrawUtils.drawStandardQuad2D(); } GlStateManager.disableBlend(); } - - if(b) { + + if (b) { cloudRenderProgress = 0; cloudStartTimer = EagRuntime.steadyTimeMillis(); cloudProgress = 0; cloudRenderPhase = (cloudRenderPhase + 1) % 3; - }else { + } else { cloudRenderProgress = currentCloudStep; } - + _wglBindFramebuffer(_GL_FRAMEBUFFER, cloudNoiseSampleParaboloidFramebuffer[3]); GlStateManager.viewport(0, 0, cloudParaboloidTextureSize, cloudParaboloidTextureSize); - - float fadeFactor = cloudProgress / (float)cloudRenderPeriod; - if(fadeFactor > 1.0f) fadeFactor = 1.0f; + + float fadeFactor = cloudProgress / (float) cloudRenderPeriod; + if (fadeFactor > 1.0f) + fadeFactor = 1.0f; GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(cloudNoiseSampleParaboloidTexture[(cloudRenderPhase + 1) % 3]); TextureCopyUtil.blitTexture(); - + GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); GlStateManager.setBlendConstants(0.0f, 0.0f, 0.0f, fadeFactor); GlStateManager.bindTexture(cloudNoiseSampleParaboloidTexture[(cloudRenderPhase + 2) % 3]); TextureCopyUtil.blitTexture(); GlStateManager.disableBlend(); - + _wglBindFramebuffer(_GL_FRAMEBUFFER, cloudOcclusionFramebuffer); GlStateManager.viewport(0, 0, 1, 1); - if(rain >= 1.0f) { + if (rain >= 1.0f) { GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); GlStateManager.clear(GL_COLOR_BUFFER_BIT); - }else if(DeferredStateManager.currentSunLightAngle.y < 0.0f) { + } else if (DeferredStateManager.currentSunLightAngle.y < 0.0f) { shader_clouds_sun_occlusion.useProgram(); GlStateManager.bindTexture(cloudNoiseSampleParaboloidTexture[3]); matrixCopyBuffer.clear(); - + tmpVector1.set(0.0f, 1.0f, 0.0f); Vector3f vec33 = tmpVector3; vec33.set(DeferredStateManager.currentSunLightAngle); @@ -445,165 +588,83 @@ public class CloudRenderWorker { vec33.z = -vec33.z; Vector3f.cross(tmpVector1, vec33, tmpVector1); Vector3f.cross(vec33, tmpVector1, tmpVector2); - + float rad = 0.1f; - + matrixCopyBuffer.put(tmpVector1.x * rad); matrixCopyBuffer.put(tmpVector2.x * rad); matrixCopyBuffer.put(vec33.x * rad); - + matrixCopyBuffer.put(tmpVector1.y * rad); matrixCopyBuffer.put(tmpVector2.y * rad); matrixCopyBuffer.put(vec33.y * rad); - + matrixCopyBuffer.put(tmpVector1.z * rad); matrixCopyBuffer.put(tmpVector2.z * rad); matrixCopyBuffer.put(vec33.z * rad); - + rad = 1.0f - rad; matrixCopyBuffer.put(vec33.x * rad); matrixCopyBuffer.put(vec33.y * rad); matrixCopyBuffer.put(vec33.z * rad); - + matrixCopyBuffer.flip(); _wglUniformMatrix4x3fv(shader_clouds_sun_occlusion.uniforms.u_sampleMatrix4x3f, false, matrixCopyBuffer); - - if(rain > 0.0f) { + + if (rain > 0.0f) { GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_CONSTANT_ALPHA, GL_ZERO); GlStateManager.setBlendConstants(0.0f, 0.0f, 0.0f, 1.0f - rain); DrawUtils.drawStandardQuad2D(); GlStateManager.disableBlend(); - }else { + } else { DrawUtils.drawStandardQuad2D(); } - }else { + } else { GlStateManager.clearColor(1.0f, 1.0f, 1.0f, 1.0f); GlStateManager.clear(GL_COLOR_BUFFER_BIT); } } - static void destroy() { - if(cloudNoiseTexture != -1) { - GlStateManager.deleteTexture(cloudNoiseTexture); - cloudNoiseTexture = -1; - } - for(int i = 0; i < 4; ++i) { - if(cloudNoiseSampleParaboloidFramebuffer[i] != null) { - _wglDeleteFramebuffer(cloudNoiseSampleParaboloidFramebuffer[i]); - cloudNoiseSampleParaboloidFramebuffer[i] = null; - } - if(cloudNoiseSampleParaboloidTexture[i] != -1) { - GlStateManager.deleteTexture(cloudNoiseSampleParaboloidTexture[i]); - cloudNoiseSampleParaboloidTexture[i] = -1; - } - } - if(cloud3DSamplesTexture != -1) { - GlStateManager.deleteTexture(cloud3DSamplesTexture); - cloud3DSamplesTexture = -1; - } - if(cloud3DSamplesSlices != null) { - for(int i = 0; i < cloud3DSamplesSlices.length; ++i) { - _wglDeleteFramebuffer(cloud3DSamplesSlices[i]); - } - cloud3DSamplesSlices = null; - } - if(cloudSpecialShapeTexture != -1) { - GlStateManager.deleteTexture(cloudSpecialShapeTexture); - cloudSpecialShapeTexture = -1; - } - if(cloudOcclusionFramebuffer != null) { - _wglDeleteFramebuffer(cloudOcclusionFramebuffer); - cloudOcclusionFramebuffer = null; - } - if(cloudOcclusionTexture != -1) { - GlStateManager.deleteTexture(cloudOcclusionTexture); - cloudOcclusionTexture = -1; - } - if(shader_clouds_noise3d != null) { - shader_clouds_noise3d.destroy(); - shader_clouds_noise3d = null; - } - if(shader_clouds_shapes != null) { - shader_clouds_shapes.destroy(); - shader_clouds_shapes = null; - } - if(shader_clouds_sample != null) { - shader_clouds_sample.destroy(); - shader_clouds_sample = null; - } - if(shader_clouds_sun_occlusion != null) { - shader_clouds_sun_occlusion.destroy(); - shader_clouds_sun_occlusion = null; - } - } - private static void updateShape() { long millis = EagRuntime.steadyTimeMillis(); - float dt = (float)((millis - shapeUpdateTimer) * 0.001); + float dt = (float) ((millis - shapeUpdateTimer) * 0.001); shapeUpdateTimer = millis; - if(millis > nextShapeAppearance) { + if (millis > nextShapeAppearance) { float playerCoordsNoiseMapScale = 0.02f * 128.0f; - if(!isDrawingCloudShapes) { + if (!isDrawingCloudShapes) { float shapeScaleBase = rand.nextFloat() * 3.0f + 2.0f; - shapeSizeX = (int)(32 * shapeScaleBase * (0.9f + rand.nextFloat() * 0.2f)); - shapeSizeY = (int)(16 * shapeScaleBase * (0.95f + rand.nextFloat() * 0.1f)); - shapeSizeZ = (int)(24 * shapeScaleBase * (0.48f + rand.nextFloat() * 0.04f)); + shapeSizeX = (int) (32 * shapeScaleBase * (0.9f + rand.nextFloat() * 0.2f)); + shapeSizeY = (int) (16 * shapeScaleBase * (0.95f + rand.nextFloat() * 0.1f)); + shapeSizeZ = (int) (24 * shapeScaleBase * (0.48f + rand.nextFloat() * 0.04f)); do { - shapePosX = (int)(cloud3DSamplesTextureSizeX * (rand.nextFloat() * 1.5f - 0.75f)); - shapePosY = (int)(cloud3DSamplesTextureSizeY * (rand.nextFloat() * 1.5f - 0.75f)); - }while(shapePosX > -192 && shapePosY > -192 && shapePosX < 192 && shapePosY < 192); + shapePosX = (int) (cloud3DSamplesTextureSizeX * (rand.nextFloat() * 1.5f - 0.75f)); + shapePosY = (int) (cloud3DSamplesTextureSizeY * (rand.nextFloat() * 1.5f - 0.75f)); + } while (shapePosX > -192 && shapePosY > -192 && shapePosX < 192 && shapePosY < 192); float l = -MathHelper.sqrt_float(shapePosX * shapePosX + shapePosY * shapePosY); - shapeRotate = (float)Math.atan2(shapePosY / l, shapePosX / l) / 0.0174532f; + shapeRotate = (float) Math.atan2(shapePosY / l, shapePosX / l) / 0.0174532f; shapeRotate += (rand.nextFloat() - 0.5f) * 90.0f; shapePosX += renderViewX * playerCoordsNoiseMapScale + cloud3DSamplesTextureSizeX * 0.5f; shapePosY += renderViewZ * playerCoordsNoiseMapScale + cloud3DSamplesTextureSizeY * 0.5f; - shapePosZ = (int)((cloud3DSamplesTextureSizeZ - shapeSizeZ) * (rand.nextFloat() * 0.5f + 0.25f)); + shapePosZ = (int) ((cloud3DSamplesTextureSizeZ - shapeSizeZ) * (rand.nextFloat() * 0.5f + 0.25f)); isDrawingCloudShapes = true; - }else { + } else { float dx = MathHelper.cos(-shapeRotate * 0.0174532f); float dy = MathHelper.sin(-shapeRotate * 0.0174532f); - shapePosX += (int)(dx * 10.0f * dt); - shapePosY -= (int)(dy * 10.0f * dt); - if(MathHelper.abs(shapePosX - renderViewX * playerCoordsNoiseMapScale - cloud3DSamplesTextureSizeX * 0.5f) > 300.0f || - MathHelper.abs(shapePosY - renderViewZ * playerCoordsNoiseMapScale - cloud3DSamplesTextureSizeY * 0.5f) > 300.0f) { + shapePosX += (int) (dx * 10.0f * dt); + shapePosY -= (int) (dy * 10.0f * dt); + if (MathHelper + .abs(shapePosX - renderViewX * playerCoordsNoiseMapScale + - cloud3DSamplesTextureSizeX * 0.5f) > 300.0f + || MathHelper.abs(shapePosY - renderViewZ * playerCoordsNoiseMapScale + - cloud3DSamplesTextureSizeY * 0.5f) > 300.0f) { nextShapeAppearance = millis + 300000l + rand.nextInt(1500000); isDrawingCloudShapes = false; } } - }else { + } else { isDrawingCloudShapes = false; } } - static boolean checkFrustum(Matrix3f mat) { - Vector3f tmp = tmpVector1; - tmp.x = -1.0f; - tmp.y = -1.0f; - tmp.z = 1.0f; - Matrix3f.transform(mat, tmp, tmp); - if(tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { - return true; - } - tmp.x = 1.0f; - tmp.y = -1.0f; - Matrix3f.transform(mat, tmp, tmp); - if(tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { - return true; - } - tmp.x = 1.0f; - tmp.y = 1.0f; - Matrix3f.transform(mat, tmp, tmp); - if(tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { - return true; - } - tmp.x = -1.0f; - tmp.y = 1.0f; - Matrix3f.transform(mat, tmp, tmp); - if(tmp.x >= -1.0f && tmp.x <= 1.0f && tmp.y >= -1.0f && tmp.y <= 1.0f) { - return true; - } - return false; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DebugFramebufferView.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DebugFramebufferView.java index 1a0913b7..15e51237 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DebugFramebufferView.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DebugFramebufferView.java @@ -1,5 +1,21 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE1; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COMPARE_REF_TO_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_TEXTURE_COMPARE_MODE; + import java.util.Arrays; import java.util.List; import java.util.function.Consumer; @@ -11,66 +27,63 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program.PipelineShaderG import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; - /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DebugFramebufferView { + private static class NoDataException extends RuntimeException { + } + public static boolean debugViewShown = false; private static long debugViewNameTimer = 0l; + private static int currentDebugView = 0; - public static final List views = Arrays.asList( - (new DebugFramebufferView("GBuffer: Diffuse Color", (pipeline) -> { + public static final List views = Arrays + .asList((new DebugFramebufferView("GBuffer: Diffuse Color", (pipeline) -> { pipeline.useDebugViewShader(0); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.gBufferDiffuseTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("GBuffer: Normal Vectors", (pipeline) -> { + })), (new DebugFramebufferView("GBuffer: Normal Vectors", (pipeline) -> { PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(1); - EaglerDeferredPipeline.uniformMatrixHelper(dbv.uniforms.u_inverseViewMatrix, DeferredStateManager.inverseViewMatrix); + EaglerDeferredPipeline.uniformMatrixHelper(dbv.uniforms.u_inverseViewMatrix, + DeferredStateManager.inverseViewMatrix); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.gBufferNormalsTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("GBuffer: Block/Sky Light Values", (pipeline) -> { + })), (new DebugFramebufferView("GBuffer: Block/Sky Light Values", (pipeline) -> { pipeline.useDebugViewShader(2); GlStateManager.setActiveTexture(GL_TEXTURE1); GlStateManager.bindTexture(pipeline.gBufferNormalsTexture); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.gBufferDiffuseTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("GBuffer: Material Params (1)", (pipeline) -> { + })), (new DebugFramebufferView("GBuffer: Material Params (1)", (pipeline) -> { pipeline.useDebugViewShader(0); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.gBufferMaterialTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("GBuffer: Material Params (2)", (pipeline) -> { + })), (new DebugFramebufferView("GBuffer: Material Params (2)", (pipeline) -> { pipeline.useDebugViewShader(3); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.gBufferMaterialTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("GBuffer: Depth Buffer", (pipeline) -> { + })), (new DebugFramebufferView("GBuffer: Depth Buffer", (pipeline) -> { float depthStart = 0.001f; float depthScale = 25.0f; PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(4); @@ -78,21 +91,23 @@ public class DebugFramebufferView { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.gBufferDepthTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Sun Shadow Depth: LOD 1", (pipeline) -> { - if(pipeline.config.is_rendering_shadowsSun_clamped < 1) throw new NoDataException(); + })), (new DebugFramebufferView("Sun Shadow Depth: LOD 1", (pipeline) -> { + if (pipeline.config.is_rendering_shadowsSun_clamped < 1) + throw new NoDataException(); PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(5); - _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 0.0f); + _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, + 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 0.0f); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.sunShadowDepthBuffer); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, GL_NONE); DrawUtils.drawStandardQuad2D(); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); - })), - (new DebugFramebufferView("Sun Shadow Color: LOD 1", (pipeline) -> { - if(pipeline.config.is_rendering_shadowsSun_clamped < 1 || !pipeline.config.is_rendering_shadowsColored) throw new NoDataException(); + })), (new DebugFramebufferView("Sun Shadow Color: LOD 1", (pipeline) -> { + if (pipeline.config.is_rendering_shadowsSun_clamped < 1 || !pipeline.config.is_rendering_shadowsColored) + throw new NoDataException(); PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(10); - _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 0.0f); + _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, + 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 0.0f); GlStateManager.setActiveTexture(GL_TEXTURE1); GlStateManager.bindTexture(pipeline.sunShadowColorBuffer); GlStateManager.setActiveTexture(GL_TEXTURE0); @@ -100,21 +115,23 @@ public class DebugFramebufferView { _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, GL_NONE); DrawUtils.drawStandardQuad2D(); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); - })), - (new DebugFramebufferView("Sun Shadow Depth: LOD 2", (pipeline) -> { - if(pipeline.config.is_rendering_shadowsSun_clamped < 2) throw new NoDataException(); + })), (new DebugFramebufferView("Sun Shadow Depth: LOD 2", (pipeline) -> { + if (pipeline.config.is_rendering_shadowsSun_clamped < 2) + throw new NoDataException(); PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(5); - _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 1.0f); + _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, + 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 1.0f); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.sunShadowDepthBuffer); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, GL_NONE); DrawUtils.drawStandardQuad2D(); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); - })), - (new DebugFramebufferView("Sun Shadow Color: LOD 2", (pipeline) -> { - if(pipeline.config.is_rendering_shadowsSun_clamped < 2 || !pipeline.config.is_rendering_shadowsColored) throw new NoDataException(); + })), (new DebugFramebufferView("Sun Shadow Color: LOD 2", (pipeline) -> { + if (pipeline.config.is_rendering_shadowsSun_clamped < 2 || !pipeline.config.is_rendering_shadowsColored) + throw new NoDataException(); PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(10); - _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 1.0f); + _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, + 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 1.0f); GlStateManager.setActiveTexture(GL_TEXTURE1); GlStateManager.bindTexture(pipeline.sunShadowColorBuffer); GlStateManager.setActiveTexture(GL_TEXTURE0); @@ -122,48 +139,46 @@ public class DebugFramebufferView { _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, GL_NONE); DrawUtils.drawStandardQuad2D(); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); - })), - (new DebugFramebufferView("Sun Shadow Depth: LOD 3", (pipeline) -> { - if(pipeline.config.is_rendering_shadowsSun_clamped < 3) throw new NoDataException(); + })), (new DebugFramebufferView("Sun Shadow Depth: LOD 3", (pipeline) -> { + if (pipeline.config.is_rendering_shadowsSun_clamped < 3) + throw new NoDataException(); PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(5); - _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 2.0f); + _wglUniform2f(dbv.uniforms.u_depthSliceStartEnd2f, + 1.0f / pipeline.config.is_rendering_shadowsSun_clamped, 2.0f); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.sunShadowDepthBuffer); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, GL_NONE); DrawUtils.drawStandardQuad2D(); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); - })), - (new DebugFramebufferView("GBuffer Shadow Values", (pipeline) -> { - if(pipeline.config.is_rendering_shadowsSun_clamped < 1) throw new NoDataException(); - if(pipeline.config.is_rendering_shadowsColored) { + })), (new DebugFramebufferView("GBuffer Shadow Values", (pipeline) -> { + if (pipeline.config.is_rendering_shadowsSun_clamped < 1) + throw new NoDataException(); + if (pipeline.config.is_rendering_shadowsColored) { pipeline.useDebugViewShader(0); - }else { + } else { pipeline.useDebugViewShader(6); } GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.sunLightingShadowTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Light Shafts Buffer", (pipeline) -> { - if(!pipeline.config.is_rendering_lightShafts) throw new NoDataException(); + })), (new DebugFramebufferView("Light Shafts Buffer", (pipeline) -> { + if (!pipeline.config.is_rendering_lightShafts) + throw new NoDataException(); pipeline.useDebugViewShader(6); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.lightShaftsTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Forward Render Mask", (pipeline) -> { + })), (new DebugFramebufferView("Forward Render Mask", (pipeline) -> { pipeline.useDebugViewShader(7); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.lightingHDRFramebufferColorTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Final HDR Color Buffer", (pipeline) -> { + })), (new DebugFramebufferView("Final HDR Color Buffer", (pipeline) -> { pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.lightingHDRFramebufferColorTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Final Depth Buffer", (pipeline) -> { + })), (new DebugFramebufferView("Final Depth Buffer", (pipeline) -> { float depthStart = 0.001f; float depthScale = 25.0f; PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(4); @@ -171,16 +186,16 @@ public class DebugFramebufferView { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.lightingHDRFramebufferDepthTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Last Frame Color Buffer", (pipeline) -> { - if(!pipeline.reprojectionEngineEnable && !pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Last Frame Color Buffer", (pipeline) -> { + if (!pipeline.reprojectionEngineEnable && !pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.lastFrameColorTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Last Frame Depth Buffer", (pipeline) -> { - if(!pipeline.reprojectionEngineEnable && !pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Last Frame Depth Buffer", (pipeline) -> { + if (!pipeline.reprojectionEngineEnable && !pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); float depthStart = 0.001f; float depthScale = 25.0f; PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(4); @@ -188,136 +203,131 @@ public class DebugFramebufferView { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.lastFrameDepthTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSAO: Raw GBuffer Samples", (pipeline) -> { - if(!pipeline.config.is_rendering_ssao) throw new NoDataException(); + })), (new DebugFramebufferView("SSAO: Raw GBuffer Samples", (pipeline) -> { + if (!pipeline.config.is_rendering_ssao) + throw new NoDataException(); pipeline.useDebugViewShader(6); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.ssaoGenerateTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSAO: Reprojected Samples", (pipeline) -> { - if(!pipeline.config.is_rendering_ssao) throw new NoDataException(); + })), (new DebugFramebufferView("SSAO: Reprojected Samples", (pipeline) -> { + if (!pipeline.config.is_rendering_ssao) + throw new NoDataException(); pipeline.useDebugViewShader(9); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionControlSSAOTexture[pipeline.reprojectionPhase]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSAO: History Buffer", (pipeline) -> { - if(!pipeline.config.is_rendering_ssao) throw new NoDataException(); + })), (new DebugFramebufferView("SSAO: History Buffer", (pipeline) -> { + if (!pipeline.config.is_rendering_ssao) + throw new NoDataException(); pipeline.useDebugViewShader(6); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionControlSSAOTexture[pipeline.reprojectionPhase]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSR: Reflection Buffer", (pipeline) -> { - if(!pipeline.config.is_rendering_raytracing) throw new NoDataException(); + })), (new DebugFramebufferView("SSR: Reflection Buffer", (pipeline) -> { + if (!pipeline.config.is_rendering_raytracing) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionSSRTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSR: Reflection Traces", (pipeline) -> { - if(!pipeline.config.is_rendering_raytracing) throw new NoDataException(); + })), (new DebugFramebufferView("SSR: Reflection Traces", (pipeline) -> { + if (!pipeline.config.is_rendering_raytracing) + throw new NoDataException(); pipeline.useDebugViewShader(11); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionSSRTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSR: Reflection Hit Vectors", (pipeline) -> { - if(!pipeline.config.is_rendering_raytracing) throw new NoDataException(); + })), (new DebugFramebufferView("SSR: Reflection Hit Vectors", (pipeline) -> { + if (!pipeline.config.is_rendering_raytracing) + throw new NoDataException(); pipeline.useDebugViewShader(12); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionSSRHitVector[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSR: Reflection Hit Mask", (pipeline) -> { - if(!pipeline.config.is_rendering_raytracing) throw new NoDataException(); + })), (new DebugFramebufferView("SSR: Reflection Hit Mask", (pipeline) -> { + if (!pipeline.config.is_rendering_raytracing) + throw new NoDataException(); pipeline.useDebugViewShader(13); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionSSRHitVector[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("SSR: History Buffer", (pipeline) -> { - if(!pipeline.config.is_rendering_raytracing) throw new NoDataException(); + })), (new DebugFramebufferView("SSR: History Buffer", (pipeline) -> { + if (!pipeline.config.is_rendering_raytracing) + throw new NoDataException(); pipeline.useDebugViewShader(11); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.reprojectionSSRHitVector[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Clouds 3D Noise Map", (pipeline) -> { + })), (new DebugFramebufferView("Clouds 3D Noise Map", (pipeline) -> { PipelineShaderGBufferDebugView dbg = pipeline.useDebugViewShader(18); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture3D(CloudRenderWorker.cloud3DSamplesTexture); - _wglUniform1f(_wglGetUniformLocation(dbg.program, "u_fuckU1f"), (float)((EagRuntime.steadyTimeMillis() % 5000l) / 5000.0)); + _wglUniform1f(_wglGetUniformLocation(dbg.program, "u_fuckU1f"), + (float) ((EagRuntime.steadyTimeMillis() % 5000l) / 5000.0)); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Clouds Back Buffer", (pipeline) -> { + })), (new DebugFramebufferView("Clouds Back Buffer", (pipeline) -> { pipeline.useDebugViewShader(0); GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(CloudRenderWorker.cloudNoiseSampleParaboloidTexture[CloudRenderWorker.cloudRenderPhase]); + GlStateManager.bindTexture( + CloudRenderWorker.cloudNoiseSampleParaboloidTexture[CloudRenderWorker.cloudRenderPhase]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Clouds Front Buffer", (pipeline) -> { + })), (new DebugFramebufferView("Clouds Front Buffer", (pipeline) -> { pipeline.useDebugViewShader(0); GlStateManager.setActiveTexture(GL_TEXTURE0); CloudRenderWorker.bindParaboloid(); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Cached Atmosphere Colors", (pipeline) -> { + })), (new DebugFramebufferView("Cached Atmosphere Colors", (pipeline) -> { pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.atmosphereHDRFramebufferColorTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Dual Paraboloid Map: Atmosphere", (pipeline) -> { + })), (new DebugFramebufferView("Dual Paraboloid Map: Atmosphere", (pipeline) -> { pipeline.useDebugViewShader(14); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.envMapAtmosphereTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Dual Paraboloid Map: Skybox", (pipeline) -> { + })), (new DebugFramebufferView("Dual Paraboloid Map: Skybox", (pipeline) -> { pipeline.useDebugViewShader(14); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.envMapSkyTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Dual Paraboloid Map: Terrain", (pipeline) -> { - if(!pipeline.config.is_rendering_useEnvMap) throw new NoDataException(); + })), (new DebugFramebufferView("Dual Paraboloid Map: Terrain", (pipeline) -> { + if (!pipeline.config.is_rendering_useEnvMap) + throw new NoDataException(); pipeline.useDebugViewShader(14); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.envMapColorTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Dual Paraboloid Map: Mask", (pipeline) -> { - if(!pipeline.config.is_rendering_useEnvMap) throw new NoDataException(); + })), (new DebugFramebufferView("Dual Paraboloid Map: Mask", (pipeline) -> { + if (!pipeline.config.is_rendering_useEnvMap) + throw new NoDataException(); pipeline.useDebugViewShader(15); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.envMapColorTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Skybox Irradiance Map", (pipeline) -> { + })), (new DebugFramebufferView("Skybox Irradiance Map", (pipeline) -> { pipeline.useDebugViewShader(14); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.skyIrradianceTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Atmosphere Irradiance Map", (pipeline) -> { + })), (new DebugFramebufferView("Atmosphere Irradiance Map", (pipeline) -> { pipeline.useDebugViewShader(14); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.atmosphereIrradianceTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: Surface Normals", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: Surface Normals", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(1); - EaglerDeferredPipeline.uniformMatrixHelper(dbv.uniforms.u_inverseViewMatrix, DeferredStateManager.inverseViewMatrix); + EaglerDeferredPipeline.uniformMatrixHelper(dbv.uniforms.u_inverseViewMatrix, + DeferredStateManager.inverseViewMatrix); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterMaskTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: Surface Depth", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: Surface Depth", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); float depthStart = 0.001f; float depthScale = 25.0f; PipelineShaderGBufferDebugView dbv = pipeline.useDebugViewShader(4); @@ -325,118 +335,111 @@ public class DebugFramebufferView { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterDepthBuffer); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: Distortion Map", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: Distortion Map", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(16); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterNormalMapTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: Refraction Buffer", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: Refraction Buffer", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterRefractionTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: SSR Reflect Buffer", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: SSR Reflect Buffer", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterControlReflectionTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: SSR Reflect Traces", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: SSR Reflect Traces", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(11); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterControlReflectionTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: SSR Reflect Hit Vectors", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: SSR Reflect Hit Vectors", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(12); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterControlHitVectorTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: SSR Reflect Hit Mask", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: SSR Reflect Hit Mask", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(13); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterControlHitVectorTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Water: SSR Reflect History", (pipeline) -> { - if(!pipeline.config.is_rendering_realisticWater) throw new NoDataException(); + })), (new DebugFramebufferView("Water: SSR Reflect History", (pipeline) -> { + if (!pipeline.config.is_rendering_realisticWater) + throw new NoDataException(); pipeline.useDebugViewShader(11); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.realisticWaterControlHitVectorTexture[1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Exposure Average -2", (pipeline) -> { + })), (new DebugFramebufferView("Exposure Average -2", (pipeline) -> { pipeline.useDebugViewShader(17); GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(pipeline.lumaAvgDownscaleTexture[pipeline.lumaAvgDownscaleFramebuffers.length - 2]); + GlStateManager.bindTexture( + pipeline.lumaAvgDownscaleTexture[pipeline.lumaAvgDownscaleFramebuffers.length - 2]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Exposure Average -1", (pipeline) -> { + })), (new DebugFramebufferView("Exposure Average -1", (pipeline) -> { pipeline.useDebugViewShader(17); GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(pipeline.lumaAvgDownscaleTexture[pipeline.lumaAvgDownscaleFramebuffers.length - 1]); + GlStateManager.bindTexture( + pipeline.lumaAvgDownscaleTexture[pipeline.lumaAvgDownscaleFramebuffers.length - 1]); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Dynamic Exposure Value", (pipeline) -> { + })), (new DebugFramebufferView("Dynamic Exposure Value", (pipeline) -> { pipeline.useDebugViewShader(17); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.exposureBlendTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Bloom Bright Pass", (pipeline) -> { - if(!pipeline.config.is_rendering_bloom) throw new NoDataException(); + })), (new DebugFramebufferView("Bloom Bright Pass", (pipeline) -> { + if (!pipeline.config.is_rendering_bloom) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.bloomBrightPassTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Bloom Horz. Blur", (pipeline) -> { - if(!pipeline.config.is_rendering_bloom) throw new NoDataException(); + })), (new DebugFramebufferView("Bloom Horz. Blur", (pipeline) -> { + if (!pipeline.config.is_rendering_bloom) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.bloomHBlurTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Bloom Vert. Blur", (pipeline) -> { - if(!pipeline.config.is_rendering_bloom) throw new NoDataException(); + })), (new DebugFramebufferView("Bloom Vert. Blur", (pipeline) -> { + if (!pipeline.config.is_rendering_bloom) + throw new NoDataException(); pipeline.useDebugViewShader(8); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.bloomVBlurTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Sun Occlusion: World", (pipeline) -> { + })), (new DebugFramebufferView("Sun Occlusion: World", (pipeline) -> { pipeline.useDebugViewShader(6); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(CloudRenderWorker.cloudOcclusionTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("Sun Occlusion: Screen", (pipeline) -> { + })), (new DebugFramebufferView("Sun Occlusion: Screen", (pipeline) -> { pipeline.useDebugViewShader(6); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.sunOcclusionValueTexture); DrawUtils.drawStandardQuad2D(); - })), - (new DebugFramebufferView("FXAA Luma Values", (pipeline) -> { - if(!pipeline.config.is_rendering_fxaa) throw new NoDataException(); + })), (new DebugFramebufferView("FXAA Luma Values", (pipeline) -> { + if (!pipeline.config.is_rendering_fxaa) + throw new NoDataException(); pipeline.useDebugViewShader(6); GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(pipeline.tonemapOutputTexture); DrawUtils.drawStandardQuad2D(); - })) - ); - - private static class NoDataException extends RuntimeException { - } + }))); public static void renderDebugView() { Minecraft mc = Minecraft.getMinecraft(); @@ -444,14 +447,14 @@ public class DebugFramebufferView { DebugFramebufferView view = views.get(currentDebugView); try { view.renderHandler.accept(EaglerDeferredPipeline.instance); - }catch(NoDataException ex) { + } catch (NoDataException ex) { GlStateManager.clearColor(0.0f, 0.0f, 0.1f, 0.0f); GlStateManager.clear(GL_COLOR_BUFFER_BIT); noData = true; } long millis = EagRuntime.steadyTimeMillis(); long elapsed = millis - debugViewNameTimer; - if(elapsed < 2000l || noData) { + if (elapsed < 2000l || noData) { GlStateManager.matrixMode(GL_PROJECTION); GlStateManager.pushMatrix(); GlStateManager.matrixMode(GL_MODELVIEW); @@ -461,8 +464,8 @@ public class DebugFramebufferView { GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int h = mc.scaledResolution.getScaledHeight() / 2; - - if(noData) { + + if (noData) { String noDataTxt = "No Data"; mc.entityRenderer.setupOverlayRendering(); int viewNameWidth = mc.fontRendererObj.getStringWidth(noDataTxt) * 2; @@ -472,29 +475,30 @@ public class DebugFramebufferView { mc.fontRendererObj.drawStringWithShadow(noDataTxt, 0, 0, 0xFFFFFFFF); GlStateManager.popMatrix(); } - - if(elapsed < 2000l) { - for(int i = 0; i < 9; ++i) { + + if (elapsed < 2000l) { + for (int i = 0; i < 9; ++i) { int i2 = currentDebugView - 4 + i; - if(i2 >= 0 && i2 < views.size()) { + if (i2 >= 0 && i2 < views.size()) { String str = views.get(i2).name; int j = mc.fontRendererObj.getStringWidth(str); float alphaF = ((i == 0 || i == 8) ? 0.25f : ((i == 1 || i == 7) ? 0.65f : 1.0f)); int x = 5; - if(elapsed > 1800l) { - x -= (int)(elapsed - 1800l); - alphaF *= (1.0f - (float)(elapsed - 1800l) / 190.0f); + if (elapsed > 1800l) { + x -= (int) (elapsed - 1800l); + alphaF *= (1.0f - (float) (elapsed - 1800l) / 190.0f); } int y = h + (i - 5) * 11; - Gui.drawRect(x, y, x + j + 2, y + 10, (int)(alphaF * 127.0f) << 24); - mc.fontRendererObj.drawStringWithShadow(str, x + 1, y + 1, (i == 4 ? 0xFFFF00 : 0xFFFFFF) | ((int)(alphaF * 255.0f) << 24)); + Gui.drawRect(x, y, x + j + 2, y + 10, (int) (alphaF * 127.0f) << 24); + mc.fontRendererObj.drawStringWithShadow(str, x + 1, y + 1, + (i == 4 ? 0xFFFF00 : 0xFFFFFF) | ((int) (alphaF * 255.0f) << 24)); } } mc.fontRendererObj.drawStringWithShadow("Use arrow keys to select framebuffers", 5, 23, 0xFFFFFF); mc.fontRendererObj.drawStringWithShadow("Press F+4 to exit", 5, 33, 0xFFFFFF); } - + GlStateManager.disableBlend(); GlStateManager.matrixMode(GL_PROJECTION); GlStateManager.popMatrix(); @@ -503,19 +507,22 @@ public class DebugFramebufferView { } } - public static void toggleDebugView() { - debugViewShown = !debugViewShown; - if(debugViewShown) { - debugViewNameTimer = EagRuntime.steadyTimeMillis(); - } - } - public static void switchView(int dir) { - if(!debugViewShown) return; + if (!debugViewShown) + return; debugViewNameTimer = EagRuntime.steadyTimeMillis(); currentDebugView += dir; - if(currentDebugView < 0) currentDebugView = views.size() - 1; - if(currentDebugView >= views.size()) currentDebugView = 0; + if (currentDebugView < 0) + currentDebugView = views.size() - 1; + if (currentDebugView >= views.size()) + currentDebugView = 0; + } + + public static void toggleDebugView() { + debugViewShown = !debugViewShown; + if (debugViewShown) { + debugViewNameTimer = EagRuntime.steadyTimeMillis(); + } } protected final String name; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DeferredStateManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DeferredStateManager.java index e55faddd..ac7d0b26 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DeferredStateManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DeferredStateManager.java @@ -1,5 +1,12 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; + +import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; import net.lax1dude.eaglercraft.v1_8.vector.Matrix4f; import net.lax1dude.eaglercraft.v1_8.vector.Vector3f; @@ -8,21 +15,18 @@ import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - -import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; - /** * Copyright (c) 2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -102,352 +106,117 @@ public class DeferredStateManager { public static boolean doCheckErrors = false; - public static final boolean isDeferredRenderer() { - return EaglerDeferredPipeline.instance != null; - } + static int fogLinearExp = 0; - public static final boolean isInDeferredPass() { - return EaglerDeferredPipeline.instance != null && GlStateManager.isExtensionPipeline(); - } + static float fogNear = 0.0f; - public static final boolean isInForwardPass() { - return enableForwardRender && !enableShadowRender; - } + static float fogFar = 100.0f; - public static final boolean isInParaboloidPass() { - return enableParaboloidRender; - } + static float fogDensity = 0.0f; - public static final boolean isRenderingRealisticWater() { - return EaglerDeferredPipeline.instance != null && EaglerDeferredPipeline.instance.config.is_rendering_realisticWater; - } + static float fogColorLightR = 1.0f; - public static final boolean isRenderingGlassHighlights() { - return EaglerDeferredPipeline.instance != null && EaglerDeferredPipeline.instance.config.is_rendering_useEnvMap; - } + static float fogColorLightG = 1.0f; - public static final void setDefaultMaterialConstants() { - materialConstantsRoughness = 0.5f; - materialConstantsMetalness = 0.02f; - materialConstantsEmission = 0.0f; - ++materialConstantsSerial; - } + static float fogColorLightB = 1.0f; - public static final void startUsingEnvMap() { - materialConstantsUseEnvMap = true; - } + static float fogColorLightA = 1.0f; - public static final void endUsingEnvMap() { - materialConstantsUseEnvMap = false; - } + static float fogColorDarkR = 1.0f; - public static final void reportForwardRenderObjectPosition(int centerX, int centerY, int centerZ) { - EaglerDeferredPipeline instance = EaglerDeferredPipeline.instance; - if(instance != null && enableForwardRender) { - EaglerDeferredConfig cfg = instance.config; - if(!cfg.is_rendering_dynamicLights || !cfg.shaderPackInfo.DYNAMIC_LIGHTS) { - return; - } - instance.bindLightSourceBucket(centerX, centerY, centerZ, 1); + static float fogColorDarkG = 1.0f; + + static float fogColorDarkB = 1.0f; + + static float fogColorDarkA = 1.0f; + + public static void checkGLError(String section) { + if (!doCheckErrors) { + return; + } + int i = EaglercraftGPU.glGetError(); + if (i != 0) { + EaglerDeferredPipeline.logger.error("########## GL ERROR ##########"); + EaglerDeferredPipeline.logger.error("@ {}", section); + do { + EaglerDeferredPipeline.logger.error("#{} - {}", i, EaglercraftGPU.gluErrorString(i)); + } while ((i = EaglercraftGPU.glGetError()) != 0); + EaglerDeferredPipeline.logger.error("##############################"); } } - public static final void reportForwardRenderObjectPosition2(float x, float y, float z) { - EaglerDeferredPipeline instance = EaglerDeferredPipeline.instance; - if(instance != null && enableForwardRender) { - EaglerDeferredConfig cfg = instance.config; - if(!cfg.is_rendering_dynamicLights || !cfg.shaderPackInfo.DYNAMIC_LIGHTS) { - return; - } - float posX = (float)((x + TileEntityRendererDispatcher.staticPlayerX) - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerX / 16.0) << 4)); - float posY = (float)((y + TileEntityRendererDispatcher.staticPlayerY) - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerY / 16.0) << 4)); - float posZ = (float)((z + TileEntityRendererDispatcher.staticPlayerZ) - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerZ / 16.0) << 4)); - instance.bindLightSourceBucket((int)posX, (int)posY, (int)posZ, 1); - } - } - - public static final void setHDRTranslucentPassBlendFunc() { - GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ZERO); - } - - public static final void enableMaterialTexture() { - enableMaterialMapTexture = true; - } - - public static final void disableMaterialTexture() { + public static final void disableAll() { enableMaterialMapTexture = false; - } - - public static final void enableForwardRender() { - enableForwardRender = true; - } - - public static final void disableForwardRender() { + materialConstantsUseEnvMap = false; enableForwardRender = false; - } - - public static final void enableParaboloidRender() { - enableParaboloidRender = true; - } - - public static final void disableParaboloidRender() { enableParaboloidRender = false; - } - - public static final void enableShadowRender() { - enableShadowRender = true; - } - - public static final void disableShadowRender() { enableShadowRender = false; - } - - public static final boolean isEnableShadowRender() { - return enableShadowRender; - } - - public static final void enableClipPlane() { - enableClipPlane = true; + enableClipPlane = false; + enableDrawWavingBlocks = false; + fogLinearExp = 0; + fogNear = 0.0f; + fogFar = 100.0f; + forwardCallbackHandler = null; } public static final void disableClipPlane() { enableClipPlane = false; } - public static final void setClipPlaneY(float yValue) { - clipPlaneY = yValue; - } - - public static final void enableDrawWavingBlocks() { - enableDrawWavingBlocks = true; - } - - public static final void disableDrawWavingBlocks() { - enableDrawWavingBlocks = false; - } - - public static final boolean isEnableDrawWavingBlocks() { - return enableDrawWavingBlocks; - } - - public static final void enableDrawRealisticWaterMask() { - enableDrawRealisticWaterMask = true; + public static final void disableDrawGlassHighlightsRender() { + enableDrawGlassHighlightsRender = false; } public static final void disableDrawRealisticWaterMask() { enableDrawRealisticWaterMask = false; } - public static final boolean isDrawRealisticWaterMask() { - return enableDrawRealisticWaterMask; - } - - public static final void enableDrawRealisticWaterRender() { - enableDrawRealisticWaterRender = true; - } - public static final void disableDrawRealisticWaterRender() { enableDrawRealisticWaterRender = false; } - public static final boolean isDrawRealisticWaterRender() { - return enableDrawRealisticWaterRender; + public static final void disableDrawWavingBlocks() { + enableDrawWavingBlocks = false; + } + + public static final void disableFog() { + fogLinearExp = 0; + } + + public static final void disableForwardRender() { + enableForwardRender = false; + } + + public static final void disableMaterialTexture() { + enableMaterialMapTexture = false; + } + + public static final void disableParaboloidRender() { + enableParaboloidRender = false; + } + + public static final void disableShadowRender() { + enableShadowRender = false; + } + + public static final void enableClipPlane() { + enableClipPlane = true; } public static final void enableDrawGlassHighlightsRender() { enableDrawGlassHighlightsRender = true; } - public static final void disableDrawGlassHighlightsRender() { - enableDrawGlassHighlightsRender = false; + public static final void enableDrawRealisticWaterMask() { + enableDrawRealisticWaterMask = true; } - public static final boolean isDrawGlassHighlightsRender() { - return enableDrawGlassHighlightsRender; + public static final void enableDrawRealisticWaterRender() { + enableDrawRealisticWaterRender = true; } - public static final void setWavingBlockOffset(float x, float y, float z) { - wavingBlockOffsetX = x; - wavingBlockOffsetY = y; - wavingBlockOffsetZ = z; - ++wavingBlockOffsetSerial; - } - - public static final void setWavingBlockParams(float x, float y, float z, float w) { - wavingBlockParamX = x; - wavingBlockParamY = y; - wavingBlockParamZ = z; - wavingBlockParamW = w; - ++wavingBlockParamSerial; - } - - public static final void setRoughnessConstant(float roughness) { - materialConstantsRoughness = roughness; - ++materialConstantsSerial; - } - - public static final void setMetalnessConstant(float metalness) { - materialConstantsMetalness = metalness; - ++materialConstantsSerial; - } - - public static final void setEmissionConstant(float emission) { - materialConstantsEmission = emission; - ++materialConstantsSerial; - } - - public static final void setBlockConstant(int blockId) { - constantBlock = blockId; - } - - public static final AxisAlignedBB getShadowMapBounds() { - return shadowMapBounds; - } - - public static final void setShadowMapBounds(AxisAlignedBB newShadowMapBounds) { - shadowMapBounds = newShadowMapBounds; - } - - public static final void loadGBufferViewMatrix() { - loadPassViewMatrix(); - viewMatrix.load(passViewMatrix); - inverseViewMatrix.load(passInverseViewMatrix); - viewMatrixSerial = passViewMatrixSerial; - } - - public static void loadGBufferProjectionMatrix() { - loadPassProjectionMatrix(); - projMatrix.load(passProjMatrix); - inverseProjMatrix.load(passInverseProjMatrix); - projMatrixSerial = passProjMatrixSerial; - } - - public static final void loadPassViewMatrix() { - GlStateManager.getFloat(GL_MODELVIEW_MATRIX, matrixCopyBuffer); - passViewMatrix.load(matrixCopyBuffer); - Matrix4f.invert(passViewMatrix, passInverseViewMatrix); - ++passViewMatrixSerial; - isShadowPassMatrixLoaded = false; - } - - public static void loadPassProjectionMatrix() { - GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); - passProjMatrix.load(matrixCopyBuffer); - Matrix4f.invert(passProjMatrix, passInverseProjMatrix); - ++passProjMatrixSerial; - } - - public static final void loadShadowPassViewMatrix() { - GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); - passViewMatrix.load(matrixCopyBuffer); - Matrix4f.invert(passViewMatrix, passInverseViewMatrix); - passProjMatrix.setIdentity(); - ++passViewMatrixSerial; - isShadowPassMatrixLoaded = true; - } - - public static final void setPassMatrixToGBuffer() { - passViewMatrix.load(viewMatrix); - passInverseViewMatrix.load(inverseViewMatrix); - passProjMatrix.load(projMatrix); - passInverseProjMatrix.load(inverseProjMatrix); - ++passViewMatrixSerial; - ++passProjMatrixSerial; - } - - public static void setCurrentSunAngle(Vector3f vec) { - currentSunAngle.set(vec); - if(vec.y > 0.05f) { - currentSunLightAngle.x = -vec.x; - currentSunLightAngle.y = -vec.y; - currentSunLightAngle.z = -vec.z; - }else { - currentSunLightAngle.set(vec); - } - } - - public static void setCurrentSunAngle(Vector4f vec) { - currentSunAngle.set(vec); - if(vec.y > 0.05f) { - currentSunLightAngle.x = -vec.x; - currentSunLightAngle.y = -vec.y; - currentSunLightAngle.z = -vec.z; - }else { - currentSunLightAngle.set(vec); - } - } - - public static final void loadSunShadowMatrixLOD0() { - GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); - sunShadowMatrix0.load(matrixCopyBuffer); - } - - public static final void loadSunShadowMatrixLOD1() { - GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); - sunShadowMatrix1.load(matrixCopyBuffer); - } - - public static final void loadSunShadowMatrixLOD2() { - GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); - sunShadowMatrix2.load(matrixCopyBuffer); - } - - public static final Matrix4f getSunShadowMatrixLOD0() { - return sunShadowMatrix0; - } - - public static final Matrix4f getSunShadowMatrixLOD1() { - return sunShadowMatrix1; - } - - public static final Matrix4f getSunShadowMatrixLOD2() { - return sunShadowMatrix2; - } - - public static final void setGBufferNearFarPlanes(float zNear, float zFar) { - gbufferNearPlane = zNear; - gbufferFarPlane = zFar; - } - - public static final void setWaterWindOffset(float sx, float sy, float fx, float fy) { - ++waterWindOffsetSerial; - u_waterWindOffset4f.x = sx; - u_waterWindOffset4f.y = sy; - u_waterWindOffset4f.z = fx; - u_waterWindOffset4f.w = fy; - } - - static int fogLinearExp = 0; - - static float fogNear = 0.0f; - static float fogFar = 100.0f; - - static float fogDensity = 0.0f; - - static float fogColorLightR = 1.0f; - static float fogColorLightG = 1.0f; - static float fogColorLightB = 1.0f; - static float fogColorLightA = 1.0f; - - static float fogColorDarkR = 1.0f; - static float fogColorDarkG = 1.0f; - static float fogColorDarkB = 1.0f; - static float fogColorDarkA = 1.0f; - - public static final void enableFogLinear(float near, float far, boolean atmosphere, float colorLightR, - float colorLightG, float colorLightB, float colorLightA, float colorDarkR, float colorDarkG, - float colorDarkB, float colorDarkA) { - fogLinearExp = atmosphere ? 5 : 1; - fogNear = near; - fogFar = far; - fogColorLightR = colorLightR; - fogColorLightG = colorLightG; - fogColorLightB = colorLightB; - fogColorLightA = colorLightA; - fogColorDarkR = colorDarkR; - fogColorDarkG = colorDarkG; - fogColorDarkB = colorDarkB; - fogColorDarkA = colorDarkA; + public static final void enableDrawWavingBlocks() { + enableDrawWavingBlocks = true; } public static final void enableFogExp(float density, boolean atmosphere, float colorLightR, float colorLightG, @@ -465,41 +234,287 @@ public class DeferredStateManager { fogColorDarkA = colorDarkA; } - public static final void disableFog() { - fogLinearExp = 0; + public static final void enableFogLinear(float near, float far, boolean atmosphere, float colorLightR, + float colorLightG, float colorLightB, float colorLightA, float colorDarkR, float colorDarkG, + float colorDarkB, float colorDarkA) { + fogLinearExp = atmosphere ? 5 : 1; + fogNear = near; + fogFar = far; + fogColorLightR = colorLightR; + fogColorLightG = colorLightG; + fogColorLightB = colorLightB; + fogColorLightA = colorLightA; + fogColorDarkR = colorDarkR; + fogColorDarkG = colorDarkG; + fogColorDarkB = colorDarkB; + fogColorDarkA = colorDarkA; } - public static final void disableAll() { - enableMaterialMapTexture = false; + public static final void enableForwardRender() { + enableForwardRender = true; + } + + public static final void enableMaterialTexture() { + enableMaterialMapTexture = true; + } + + public static final void enableParaboloidRender() { + enableParaboloidRender = true; + } + + public static final void enableShadowRender() { + enableShadowRender = true; + } + + public static final void endUsingEnvMap() { materialConstantsUseEnvMap = false; - enableForwardRender = false; - enableParaboloidRender = false; - enableShadowRender = false; - enableClipPlane = false; - enableDrawWavingBlocks = false; - fogLinearExp = 0; - fogNear = 0.0f; - fogFar = 100.0f; - forwardCallbackHandler = null; + } + + public static final AxisAlignedBB getShadowMapBounds() { + return shadowMapBounds; } public static float getSunHeight() { return -currentSunAngle.y; } - public static void checkGLError(String section) { - if(!doCheckErrors) { - return; - } - int i = EaglercraftGPU.glGetError(); - if(i != 0) { - EaglerDeferredPipeline.logger.error("########## GL ERROR ##########"); - EaglerDeferredPipeline.logger.error("@ {}", section); - do { - EaglerDeferredPipeline.logger.error("#{} - {}", i, EaglercraftGPU.gluErrorString(i)); - }while((i = EaglercraftGPU.glGetError()) != 0); - EaglerDeferredPipeline.logger.error("##############################"); + public static final Matrix4f getSunShadowMatrixLOD0() { + return sunShadowMatrix0; + } + + public static final Matrix4f getSunShadowMatrixLOD1() { + return sunShadowMatrix1; + } + + public static final Matrix4f getSunShadowMatrixLOD2() { + return sunShadowMatrix2; + } + + public static final boolean isDeferredRenderer() { + return EaglerDeferredPipeline.instance != null; + } + + public static final boolean isDrawGlassHighlightsRender() { + return enableDrawGlassHighlightsRender; + } + + public static final boolean isDrawRealisticWaterMask() { + return enableDrawRealisticWaterMask; + } + + public static final boolean isDrawRealisticWaterRender() { + return enableDrawRealisticWaterRender; + } + + public static final boolean isEnableDrawWavingBlocks() { + return enableDrawWavingBlocks; + } + + public static final boolean isEnableShadowRender() { + return enableShadowRender; + } + + public static final boolean isInDeferredPass() { + return EaglerDeferredPipeline.instance != null && GlStateManager.isExtensionPipeline(); + } + + public static final boolean isInForwardPass() { + return enableForwardRender && !enableShadowRender; + } + + public static final boolean isInParaboloidPass() { + return enableParaboloidRender; + } + + public static final boolean isRenderingGlassHighlights() { + return EaglerDeferredPipeline.instance != null && EaglerDeferredPipeline.instance.config.is_rendering_useEnvMap; + } + + public static final boolean isRenderingRealisticWater() { + return EaglerDeferredPipeline.instance != null + && EaglerDeferredPipeline.instance.config.is_rendering_realisticWater; + } + + public static void loadGBufferProjectionMatrix() { + loadPassProjectionMatrix(); + projMatrix.load(passProjMatrix); + inverseProjMatrix.load(passInverseProjMatrix); + projMatrixSerial = passProjMatrixSerial; + } + + public static final void loadGBufferViewMatrix() { + loadPassViewMatrix(); + viewMatrix.load(passViewMatrix); + inverseViewMatrix.load(passInverseViewMatrix); + viewMatrixSerial = passViewMatrixSerial; + } + + public static void loadPassProjectionMatrix() { + GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); + passProjMatrix.load(matrixCopyBuffer); + Matrix4f.invert(passProjMatrix, passInverseProjMatrix); + ++passProjMatrixSerial; + } + + public static final void loadPassViewMatrix() { + GlStateManager.getFloat(GL_MODELVIEW_MATRIX, matrixCopyBuffer); + passViewMatrix.load(matrixCopyBuffer); + Matrix4f.invert(passViewMatrix, passInverseViewMatrix); + ++passViewMatrixSerial; + isShadowPassMatrixLoaded = false; + } + + public static final void loadShadowPassViewMatrix() { + GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); + passViewMatrix.load(matrixCopyBuffer); + Matrix4f.invert(passViewMatrix, passInverseViewMatrix); + passProjMatrix.setIdentity(); + ++passViewMatrixSerial; + isShadowPassMatrixLoaded = true; + } + + public static final void loadSunShadowMatrixLOD0() { + GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); + sunShadowMatrix0.load(matrixCopyBuffer); + } + + public static final void loadSunShadowMatrixLOD1() { + GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); + sunShadowMatrix1.load(matrixCopyBuffer); + } + + public static final void loadSunShadowMatrixLOD2() { + GlStateManager.getFloat(GL_PROJECTION_MATRIX, matrixCopyBuffer); + sunShadowMatrix2.load(matrixCopyBuffer); + } + + public static final void reportForwardRenderObjectPosition(int centerX, int centerY, int centerZ) { + EaglerDeferredPipeline instance = EaglerDeferredPipeline.instance; + if (instance != null && enableForwardRender) { + EaglerDeferredConfig cfg = instance.config; + if (!cfg.is_rendering_dynamicLights || !cfg.shaderPackInfo.DYNAMIC_LIGHTS) { + return; + } + instance.bindLightSourceBucket(centerX, centerY, centerZ, 1); } } + public static final void reportForwardRenderObjectPosition2(float x, float y, float z) { + EaglerDeferredPipeline instance = EaglerDeferredPipeline.instance; + if (instance != null && enableForwardRender) { + EaglerDeferredConfig cfg = instance.config; + if (!cfg.is_rendering_dynamicLights || !cfg.shaderPackInfo.DYNAMIC_LIGHTS) { + return; + } + float posX = (float) ((x + TileEntityRendererDispatcher.staticPlayerX) + - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerX / 16.0) << 4)); + float posY = (float) ((y + TileEntityRendererDispatcher.staticPlayerY) + - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerY / 16.0) << 4)); + float posZ = (float) ((z + TileEntityRendererDispatcher.staticPlayerZ) + - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerZ / 16.0) << 4)); + instance.bindLightSourceBucket((int) posX, (int) posY, (int) posZ, 1); + } + } + + public static final void setBlockConstant(int blockId) { + constantBlock = blockId; + } + + public static final void setClipPlaneY(float yValue) { + clipPlaneY = yValue; + } + + public static void setCurrentSunAngle(Vector3f vec) { + currentSunAngle.set(vec); + if (vec.y > 0.05f) { + currentSunLightAngle.x = -vec.x; + currentSunLightAngle.y = -vec.y; + currentSunLightAngle.z = -vec.z; + } else { + currentSunLightAngle.set(vec); + } + } + + public static void setCurrentSunAngle(Vector4f vec) { + currentSunAngle.set(vec); + if (vec.y > 0.05f) { + currentSunLightAngle.x = -vec.x; + currentSunLightAngle.y = -vec.y; + currentSunLightAngle.z = -vec.z; + } else { + currentSunLightAngle.set(vec); + } + } + + public static final void setDefaultMaterialConstants() { + materialConstantsRoughness = 0.5f; + materialConstantsMetalness = 0.02f; + materialConstantsEmission = 0.0f; + ++materialConstantsSerial; + } + + public static final void setEmissionConstant(float emission) { + materialConstantsEmission = emission; + ++materialConstantsSerial; + } + + public static final void setGBufferNearFarPlanes(float zNear, float zFar) { + gbufferNearPlane = zNear; + gbufferFarPlane = zFar; + } + + public static final void setHDRTranslucentPassBlendFunc() { + GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ZERO); + } + + public static final void setMetalnessConstant(float metalness) { + materialConstantsMetalness = metalness; + ++materialConstantsSerial; + } + + public static final void setPassMatrixToGBuffer() { + passViewMatrix.load(viewMatrix); + passInverseViewMatrix.load(inverseViewMatrix); + passProjMatrix.load(projMatrix); + passInverseProjMatrix.load(inverseProjMatrix); + ++passViewMatrixSerial; + ++passProjMatrixSerial; + } + + public static final void setRoughnessConstant(float roughness) { + materialConstantsRoughness = roughness; + ++materialConstantsSerial; + } + + public static final void setShadowMapBounds(AxisAlignedBB newShadowMapBounds) { + shadowMapBounds = newShadowMapBounds; + } + + public static final void setWaterWindOffset(float sx, float sy, float fx, float fy) { + ++waterWindOffsetSerial; + u_waterWindOffset4f.x = sx; + u_waterWindOffset4f.y = sy; + u_waterWindOffset4f.z = fx; + u_waterWindOffset4f.w = fy; + } + + public static final void setWavingBlockOffset(float x, float y, float z) { + wavingBlockOffsetX = x; + wavingBlockOffsetY = y; + wavingBlockOffsetZ = z; + ++wavingBlockOffsetSerial; + } + + public static final void setWavingBlockParams(float x, float y, float z, float w) { + wavingBlockParamX = x; + wavingBlockParamY = y; + wavingBlockParamZ = z; + wavingBlockParamW = w; + ++wavingBlockParamSerial; + } + + public static final void startUsingEnvMap() { + materialConstantsUseEnvMap = true; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightInstance.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightInstance.java index a846bae8..6c5cf7b0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightInstance.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightInstance.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,6 +37,14 @@ class DynamicLightInstance { this.shadow = shadow; } + public void destroy() { + + } + + public float getRadiusInWorld() { + return radius; + } + public void updateLight(double posX, double posY, double posZ, float red, float green, float blue) { this.lastCacheHit = EagRuntime.steadyTimeMillis(); this.posX = posX; @@ -44,15 +53,7 @@ class DynamicLightInstance { this.red = red; this.green = green; this.blue = blue; - this.radius = (float)(Math.sqrt(red + green + blue) * 3.0 + 0.5); - } - - public void destroy() { - - } - - public float getRadiusInWorld() { - return radius; + this.radius = (float) (Math.sqrt(red + green + blue) * 3.0 + 0.5); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightManager.java index 5b91886f..38355f4b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/DynamicLightManager.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,11 +33,23 @@ public class DynamicLightManager { private static long lastTick = 0l; + static void destroyAll() { + Iterator itr = lightRenderers.values().iterator(); + while (itr.hasNext()) { + itr.next().destroy(); + } + lightRenderers.clear(); + } + + public static boolean isRenderingLights() { + return isRenderLightsPass; + } + public static void renderDynamicLight(String lightName, double posX, double posY, double posZ, float red, float green, float blue, boolean shadows) { - if(isRenderLightsPass) { + if (isRenderLightsPass) { DynamicLightInstance dl = lightRenderers.get(lightName); - if(dl == null) { + if (dl == null) { lightRenderers.put(lightName, dl = new DynamicLightInstance(lightName, shadows)); } dl.updateLight(posX, posY, posZ, red, green, blue); @@ -44,22 +57,18 @@ public class DynamicLightManager { } } - public static boolean isRenderingLights() { - return isRenderLightsPass; - } - public static void setIsRenderingLights(boolean b) { isRenderLightsPass = b; } static void updateTimers() { long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastTick > 1000l) { + if (millis - lastTick > 1000l) { lastTick = millis; Iterator itr = lightRenderers.values().iterator(); - while(itr.hasNext()) { + while (itr.hasNext()) { DynamicLightInstance dl = itr.next(); - if(millis - dl.lastCacheHit > renderTimeout) { + if (millis - dl.lastCacheHit > renderTimeout) { dl.destroy(); itr.remove(); } @@ -67,12 +76,4 @@ public class DynamicLightManager { } } - static void destroyAll() { - Iterator itr = lightRenderers.values().iterator(); - while(itr.hasNext()) { - itr.next().destroy(); - } - lightRenderers.clear(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredConfig.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredConfig.java index 08e5c03f..9b07d830 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredConfig.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredConfig.java @@ -16,21 +16,23 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerDeferredConfig { - public static final ResourceLocation shaderPackInfoFile = new ResourceLocation("eagler:glsl/deferred/shader_pack_info.json"); + public static final ResourceLocation shaderPackInfoFile = new ResourceLocation( + "eagler:glsl/deferred/shader_pack_info.json"); public ShaderPackInfo shaderPackInfo = null; @@ -66,7 +68,7 @@ public class EaglerDeferredConfig { public boolean is_rendering_fxaa = true; public void readOption(String key, String value) { - switch(key) { + switch (key) { case "shaders_deferred_wavingBlocks": wavingBlocks = value.equals("true"); break; @@ -114,30 +116,14 @@ public class EaglerDeferredConfig { } } - public void writeOptions(PrintWriter output) { - output.println("shaders_deferred_wavingBlocks:" + wavingBlocks); - output.println("shaders_deferred_dynamicLights:" + dynamicLights); - output.println("shaders_deferred_ssao:" + ssao); - output.println("shaders_deferred_shadowsSun:" + shadowsSun); - output.println("shaders_deferred_shadowsColored:" + shadowsColored); - output.println("shaders_deferred_shadowsSmoothed:" + shadowsSmoothed); - output.println("shaders_deferred_useEnvMap:" + useEnvMap); - output.println("shaders_deferred_realisticWater:" + realisticWater); - output.println("shaders_deferred_lightShafts:" + lightShafts); - output.println("shaders_deferred_raytracing:" + raytracing); - output.println("shaders_deferred_lensDistortion:" + lensDistortion); - output.println("shaders_deferred_lensFlares:" + lensFlares); - output.println("shaders_deferred_bloom:" + bloom); - output.println("shaders_deferred_fxaa:" + fxaa); - } - public void reloadShaderPackInfo(IResourceManager mgr) throws IOException { IResource res = mgr.getResource(shaderPackInfoFile); - try(InputStream is = res.getInputStream()) { + try (InputStream is = res.getInputStream()) { try { - JSONObject shaderInfoJSON = new JSONObject(new String(EaglerInputStream.inputStreamToBytes(is), StandardCharsets.UTF_8)); + JSONObject shaderInfoJSON = new JSONObject( + new String(EaglerInputStream.inputStreamToBytes(is), StandardCharsets.UTF_8)); shaderPackInfo = new ShaderPackInfo(shaderInfoJSON); - }catch(JSONException ex) { + } catch (JSONException ex) { throw new IOException("Invalid shader pack info json!", ex); } } @@ -160,4 +146,21 @@ public class EaglerDeferredConfig { is_rendering_fxaa = fxaa && shaderPackInfo.POST_FXAA; } + public void writeOptions(PrintWriter output) { + output.println("shaders_deferred_wavingBlocks:" + wavingBlocks); + output.println("shaders_deferred_dynamicLights:" + dynamicLights); + output.println("shaders_deferred_ssao:" + ssao); + output.println("shaders_deferred_shadowsSun:" + shadowsSun); + output.println("shaders_deferred_shadowsColored:" + shadowsColored); + output.println("shaders_deferred_shadowsSmoothed:" + shadowsSmoothed); + output.println("shaders_deferred_useEnvMap:" + useEnvMap); + output.println("shaders_deferred_realisticWater:" + realisticWater); + output.println("shaders_deferred_lightShafts:" + lightShafts); + output.println("shaders_deferred_raytracing:" + raytracing); + output.println("shaders_deferred_lensDistortion:" + lensDistortion); + output.println("shaders_deferred_lensFlares:" + lensFlares); + output.println("shaders_deferred_bloom:" + bloom); + output.println("shaders_deferred_fxaa:" + fxaa); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredPipeline.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredPipeline.java index 4e9b63f5..451cbd2e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredPipeline.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/EaglerDeferredPipeline.java @@ -1,5 +1,103 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBlitFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglClear; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglClearColor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglCreateFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteFramebuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglFramebufferTexture2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix2fv; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix3fv; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4x2fv; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ALWAYS; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_BACK; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CLAMP_TO_EDGE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_CONSTANT_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_COMPONENT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DYNAMIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRONT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LEQUAL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR_MIPMAP_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_CONSTANT_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_DST_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RED; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SMOOTH; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_COLOR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE1; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE10; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE11; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE2; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE3; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE4; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE5; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE6; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE7; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE9; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAX_LEVEL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_INT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ZERO; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT0; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT1; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COLOR_ATTACHMENT2; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_COMPARE_REF_TO_TEXTURE; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_DEPTH_ATTACHMENT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_DEPTH_COMPONENT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_DEPTH_COMPONENT24; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_DEPTH_COMPONENT32F; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_DRAW_FRAMEBUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_FRAMEBUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_R8; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_READ_FRAMEBUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_RG; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_RG8; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_TEXTURE_COMPARE_FUNC; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_TEXTURE_COMPARE_MODE; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_UNIFORM_BUFFER; + +import java.io.DataInputStream; +import java.io.IOException; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EagUtils; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; @@ -60,27 +158,18 @@ import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; - -import java.io.DataInputStream; -import java.io.IOException; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -101,176 +190,314 @@ public class EaglerDeferredPipeline { public static EaglerDeferredPipeline instance = null; public static boolean isSuspended = false; - public EaglerDeferredConfig config = null; - public GBufferPipelineCompiler deferredExtPipeline = new GBufferPipelineCompiler(); + private static final int[] SSRColorAttachments = new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1 }; + public static FloatBuffer matrixCopyBuffer = null; + public static final Matrix4f tmpMatrixViewProj = new Matrix4f(); + + public static final Matrix4f tmpMatrixViewReproject = new Matrix4f(); + public static final Matrix4f tmpMatrixViewProjReproject = new Matrix4f(); + + public static final Matrix4f tmpMatrixLastFrameViewReproject = new Matrix4f(); + public static final Matrix4f tmpMatrixLastFrameProj = new Matrix4f(); + public static final Matrix4f tmpMatrixLastFrameViewProjReproject = new Matrix4f(); + public static final Matrix4f tmpMatrixInverseViewProj = new Matrix4f(); + + public static final Matrix4f tmpMatrixInverseViewProjReproject = new Matrix4f(); + + public static final Matrix4f tmpShadowLOD0MatrixTexSpace = new Matrix4f(); + public static final Matrix4f tmpShadowLOD1MatrixTexSpace = new Matrix4f(); + public static final Matrix4f tmpShadowLOD2MatrixTexSpace = new Matrix4f(); + + public static final Vector3f vec3_05 = new Vector3f(0.5f, 0.5f, 0.5f); + public static final Vector3f vec3_2 = new Vector3f(2.0f, 2.0f, 2.0f); + + public static final Vector3f vec3_n1 = new Vector3f(-1.0f, -1.0f, -1.0f); + + public static final Matrix4f tmpClipToTexSpaceMatLeft = new Matrix4f().translate(vec3_05).scale(vec3_05); + + public static final Matrix4f tmpTexToClipSpaceMatRight = new Matrix4f().translate(vec3_n1).scale(vec3_2); + public static final Matrix4f tmpMatrix1 = new Matrix4f(); + + public static final Matrix4f tmpMatrix2 = new Matrix4f(); + public static final Matrix3f tmpMatrix3 = new Matrix3f(); + public static final Vector3f tmpVector1 = new Vector3f(); + + public static final Vector4f tmpVector2 = new Vector4f(); + public static final Vector3f tmpVector3 = new Vector3f(); + + public static final Vector3f tmpVector4 = new Vector3f(); + public static final int MAX_LIGHTS_PER_CHUNK = 12; + + public static final int LIGHTING_BUFFER_LENGTH = 32 * MAX_LIGHTS_PER_CHUNK + 16; + private static final ResourceLocation locationEndSkyPng = new ResourceLocation("textures/environment/end_sky.png"); + private static final Comparator comparatorLightRadius = (l1, l2) -> { + return l1.radius < l2.radius ? 1 : -1; + }; + + public static final String getReasonUnsupported() { + if (EaglercraftGPU.checkOpenGLESVersion() < 300) { + return I18n.format("shaders.gui.unsupported.reason.oldOpenGLVersion"); + } else if (!EaglercraftGPU.checkHasHDRFramebufferSupportWithFilter()) { + return I18n.format("shaders.gui.unsupported.reason.hdrFramebuffer"); + } else { + return null; + } + } + + public static final boolean isSupported() { + return EaglercraftGPU.checkOpenGLESVersion() >= 300 && EaglercraftGPU.checkHasHDRFramebufferSupportWithFilter(); + } + + public static final void renderSuspended() { + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + GlStateManager.globalEnableBlend(); + Minecraft mc = Minecraft.getMinecraft(); + GlStateManager.viewport(0, 0, mc.displayWidth, mc.displayHeight); + GlStateManager.clearColor(0.5f, 0.0f, 0.0f, 1.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.pushMatrix(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.pushMatrix(); + ScaledResolution scaledresolution = mc.scaledResolution; + int w = scaledresolution.getScaledWidth(); + mc.entityRenderer.setupOverlayRendering(); + GlStateManager.enableAlpha(); + GlStateManager.pushMatrix(); + String str = "Shaders Suspended"; + GlStateManager.translate((w - mc.fontRendererObj.getStringWidth(str) * 2) * 0.5f, 45.0f, 0.0f); + GlStateManager.scale(2.0f, 2.0f, 2.0f); + mc.fontRendererObj.drawStringWithShadow(str, 0, 0, 0xFFFFFF); + GlStateManager.popMatrix(); + GlStateManager.pushMatrix(); + str = "(check console)"; + GlStateManager.translate((w - mc.fontRendererObj.getStringWidth(str) * 1.5) * 0.5f, 80.0f, 0.0f); + GlStateManager.scale(1.5f, 1.5f, 1.5f); + mc.fontRendererObj.drawStringWithShadow(str, 0, 0, 0xFFFFFF); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.popMatrix(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.popMatrix(); + EagUtils.sleep(10l); + } + + public static void setLinear() { + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + } + + public static void setNearest() { + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + } + + /** + * source: + * https://github.com/JOML-CI/JOML/blob/main/src/main/java/org/joml/Intersectionf.java + */ + public static boolean testAabSphere(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, + float centerX, float centerY, float centerZ, float radius2) { + if (centerX < minX) { + float d = (centerX - minX); + radius2 -= d * d; + } else if (centerX > maxX) { + float d = (centerX - maxX); + radius2 -= d * d; + } + if (centerY < minY) { + float d = (centerY - minY); + radius2 -= d * d; + } else if (centerY > maxY) { + float d = (centerY - maxY); + radius2 -= d * d; + } + if (centerZ < minZ) { + float d = (centerZ - minZ); + radius2 -= d * d; + } else if (centerZ > maxZ) { + float d = (centerZ - maxZ); + radius2 -= d * d; + } + return radius2 >= 0.0f; + } + + static void uniformMatrixHelper(IUniformGL uniform, Matrix3f matrix) { + matrixCopyBuffer.clear(); + matrix.store(matrixCopyBuffer); + matrixCopyBuffer.flip(); + _wglUniformMatrix3fv(uniform, false, matrixCopyBuffer); + } + + static void uniformMatrixHelper(IUniformGL uniform, Matrix4f matrix) { + matrixCopyBuffer.clear(); + matrix.store(matrixCopyBuffer); + matrixCopyBuffer.flip(); + _wglUniformMatrix4fv(uniform, false, matrixCopyBuffer); + } + + public EaglerDeferredConfig config = null; + + public GBufferPipelineCompiler deferredExtPipeline = new GBufferPipelineCompiler(); public final Minecraft mc; public int currentWidth = -1; public int currentHeight = -1; - public double currentRenderX = 0.0; + public double currentRenderY = 0.0; + public double currentRenderZ = 0.0; public int currentRenderPosSerial = 0; - public IFramebufferGL gBufferFramebuffer = null; - public int gBufferDiffuseTexture = -1; + public int gBufferNormalsTexture = -1; + public int gBufferMaterialTexture = -1; - public IFramebufferGL gBufferQuarterFramebuffer = null; - public int gBufferQuarterDepthTexture = -1; + public int gBufferQuarterDepthTexture = -1; public int[] gBufferDrawBuffers = null; public int gBufferDepthTexture = -1; - public IFramebufferGL lastFrameGBufferFramebuffer = null; - public int lastFrameGBufferDepthTexture = -1; + public int lastFrameGBufferDepthTexture = -1; public IFramebufferGL lastFrameFramebuffer = null; public int lastFrameColorTexture = -1; public int lastFrameDepthTexture = -1; - public IFramebufferGL fogDepthCopyBuffer = null; + public int fogDepthCopyTexture = -1; public IFramebufferGL sunShadowFramebuffer = null; - public IFramebufferGL sunShadowColorFramebuffer = null; + public IFramebufferGL sunShadowColorFramebuffer = null; public int sunShadowDepthBuffer = -1; + public int sunShadowDepthBufferRes = -1; public int sunShadowColorBuffer = -1; public IFramebufferGL sunLightingShadowFramebuffer = null; public int sunLightingShadowTexture = -1; - public IFramebufferGL ssaoGenerateFramebuffer = null; - public int ssaoGenerateTexture = -1; + public int ssaoGenerateTexture = -1; private int reprojectionStartup = 0; public int ssaoNoiseTexture = -1; - public IFramebufferGL lightingHDRFramebuffer = null; public int lightingHDRFramebufferColorTexture = -1; + public int lightingHDRFramebufferDepthTexture = -1; - public IFramebufferGL handRenderFramebuffer = null; - public int handRenderFramebufferDepthTexture = -1; + public int handRenderFramebufferDepthTexture = -1; public IFramebufferGL[] reprojectionControlFramebuffer = new IFramebufferGL[] { null, null }; public int[] reprojectionControlDrawBuffers = new int[0]; public int[] reprojectionControlSSAOTexture = new int[] { -1, -1 }; - public int reprojectionPhase = 0; public IFramebufferGL[] reprojectionSSRFramebuffer = new IFramebufferGL[] { null, null }; public int[] reprojectionSSRTexture = new int[] { -1, -1 }; + public int[] reprojectionSSRHitVector = new int[] { -1, -1 }; public boolean reprojectionEngineEnable = false; - private static final int[] SSRColorAttachments = new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1 }; - public IFramebufferGL lightShaftsFramebuffer = null; public int lightShaftsTexture = -1; public IFramebufferGL atmosphereHDRFramebuffer = null; - public int atmosphereHDRFramebufferColorTexture = -1; + public int atmosphereHDRFramebufferColorTexture = -1; public IFramebufferGL envMapAtmosphereFramebuffer = null; public int envMapAtmosphereTexture = -1; - public IFramebufferGL envMapSkyFramebuffer = null; + public int envMapSkyTexture = -1; public IFramebufferGL envMapFramebuffer = null; public int envMapColorTexture = -1; public int envMapDepthTexture = -1; public int moonTextures = -1; - public int irradiancePhase = 0; - public IFramebufferGL atmosphereIrradianceFramebuffer = null; public int atmosphereIrradianceTexture = -1; public IFramebufferGL skyIrradianceFramebuffer = null; public int skyIrradianceTexture = -1; - public IFramebufferGL realisticWaterMaskFramebuffer = null; public int realisticWaterMaskTexture = -1; + public int realisticWaterDepthBuffer = -1; - public IFramebufferGL realisticWaterCombinedNormalsFramebuffer = null; - public int realisticWaterCombinedNormalsTexture = -1; + public int realisticWaterCombinedNormalsTexture = -1; public IFramebufferGL realisticWaterDisplacementMapFramebuffer = null; + public int realisticWaterDisplacementMapTexture = -1; public int realisticWaterNoiseMap = -1; public IFramebufferGL realisticWaterNormalMapFramebuffer = null; public int realisticWaterNormalMapTexture = -1; - public IFramebufferGL realisticWaterControlFramebuffer = null; public IFramebufferGL[] realisticWaterSSRFramebuffer = new IFramebufferGL[2]; public int[] realisticWaterControlReflectionTexture = new int[] { -1, -1 }; public int[] realisticWaterControlHitVectorTexture = new int[] { -1, -1 }; public int realisticWaterRefractionTexture = -1; - public IFramebufferGL[] lumaAvgDownscaleFramebuffers = null; public int[] lumaAvgDownscaleTexture = null; - public IFramebufferGL exposureBlendFramebuffer = null; public int exposureBlendTexture = -1; - public IFramebufferGL sunOcclusionValueFramebuffer = null; public int sunOcclusionValueTexture = -1; - public int dither8x8Texture = -1; - public IFramebufferGL bloomBrightPassFramebuffer = null; public int bloomBrightPassTextureW = -1; public int bloomBrightPassTextureH = -1; public int bloomBrightPassTexture = -1; - public IFramebufferGL bloomDownscaleAFramebuffer = null; public int bloomDownscaleATextureW = -1; public int bloomDownscaleATextureH = -1; public int bloomDownscaleATexture = -1; - public IFramebufferGL bloomDownscaleBFramebuffer = null; public int bloomDownscaleBTextureW = -1; public int bloomDownscaleBTextureH = -1; public int bloomDownscaleBTexture = -1; - public IFramebufferGL bloomHBlurFramebuffer = null; public int bloomBlurTextureW = -1; public int bloomBlurTextureH = -1; public int bloomHBlurTexture = -1; - public IFramebufferGL bloomVBlurFramebuffer = null; public int bloomVBlurTexture = -1; - public IFramebufferGL lensDistortFramebuffer = null; public int lensDistortTexture = -1; - public IFramebufferGL tonemapOutputFramebuffer = null; public int tonemapOutputTexture = -1; - public PipelineShaderSSAOGenerate shader_ssao_generate = null; private int reprojectionTexWidth = -1; + private int reprojectionTexHeight = -1; + public PipelineShaderGBufferCombine shader_deferred_combine = null; + public int brdfTexture = -1; + public PipelineShaderLightingSun shader_lighting_sun = null; public PipelineShaderShadowsSun shader_shadows_sun = null; + public PipelineShaderLightShaftsSample shader_light_shafts_sample = null; public PipelineShaderTonemap shader_post_tonemap = null; public PipelineShaderLensDistortion shader_post_lens_distort = null; public PipelineShaderPostExposureAvg shader_post_exposure_avg = null; public PipelineShaderPostExposureAvg shader_post_exposure_avg_luma = null; + public PipelineShaderPostExposureFinal shader_post_exposure_final = null; public PipelineShaderBloomBrightPass shader_post_bloom_bright = null; public PipelineShaderBloomBlurPass shader_post_bloom_blur = null; @@ -294,80 +521,54 @@ public class EaglerDeferredPipeline { public PipelineShaderHandDepthMask shader_hand_depth_mask = null; public PipelineShaderFXAA shader_post_fxaa = null; public SkyboxRenderer skybox = null; + public LightSourceMesh pointLightMesh = null; public final GBufferAcceleratedEffectRenderer gbufferEffectRenderer = new GBufferAcceleratedEffectRenderer(); public final ForwardAcceleratedEffectRenderer forwardEffectRenderer = new ForwardAcceleratedEffectRenderer(); - public final PipelineShaderGBufferDebugView[] shader_gbuffer_debug_view = new PipelineShaderGBufferDebugView[19]; - public final EaglercraftRandom random = new EaglercraftRandom(); - - public static FloatBuffer matrixCopyBuffer = null; - public IBufferGL buffer_worldLightingData; - private ByteBuffer worldLightingDataCopyBuffer; + private ByteBuffer worldLightingDataCopyBuffer; public IBufferGL buffer_chunkLightingData; + public IBufferGL buffer_chunkLightingDataZero; + private ByteBuffer chunkLightingDataCopyBuffer; + private boolean isChunkLightingEnabled = false; public ListSerial currentBoundLightSourceBucket; - public static final Matrix4f tmpMatrixViewProj = new Matrix4f(); - public static final Matrix4f tmpMatrixViewReproject = new Matrix4f(); - public static final Matrix4f tmpMatrixViewProjReproject = new Matrix4f(); - public static final Matrix4f tmpMatrixLastFrameViewReproject = new Matrix4f(); - public static final Matrix4f tmpMatrixLastFrameProj = new Matrix4f(); - public static final Matrix4f tmpMatrixLastFrameViewProjReproject = new Matrix4f(); - public static final Matrix4f tmpMatrixInverseViewProj = new Matrix4f(); - public static final Matrix4f tmpMatrixInverseViewProjReproject = new Matrix4f(); - public static final Matrix4f tmpShadowLOD0MatrixTexSpace = new Matrix4f(); - public static final Matrix4f tmpShadowLOD1MatrixTexSpace = new Matrix4f(); - public static final Matrix4f tmpShadowLOD2MatrixTexSpace = new Matrix4f(); - public static final Vector3f vec3_05 = new Vector3f(0.5f, 0.5f, 0.5f); - public static final Vector3f vec3_2 = new Vector3f(2.0f, 2.0f, 2.0f); - public static final Vector3f vec3_n1 = new Vector3f(-1.0f, -1.0f, -1.0f); - public static final Matrix4f tmpClipToTexSpaceMatLeft = new Matrix4f().translate(vec3_05).scale(vec3_05); - public static final Matrix4f tmpTexToClipSpaceMatRight = new Matrix4f().translate(vec3_n1).scale(vec3_2); - public static final Matrix4f tmpMatrix1 = new Matrix4f(); - public static final Matrix4f tmpMatrix2 = new Matrix4f(); - public static final Matrix3f tmpMatrix3 = new Matrix3f(); - public static final Vector3f tmpVector1 = new Vector3f(); - public static final Vector4f tmpVector2 = new Vector4f(); - public static final Vector3f tmpVector3 = new Vector3f(); - public static final Vector3f tmpVector4 = new Vector3f(); - public final ListSerial[] lightSourceBuckets; private final int[] lightSourceBucketSerials; private final int[] lightSourceRenderPosSerials; + public ListSerial currentLightSourceBucket; private int currentLightSourceBucketId = -1; private int lightingBufferSliceLength = -1; - public static final int MAX_LIGHTS_PER_CHUNK = 12; - public static final int LIGHTING_BUFFER_LENGTH = 32 * MAX_LIGHTS_PER_CHUNK + 16; - private int uniformBufferOffsetAlignment = -1; - - private int uboAlign(int offset) { - return MathHelper.ceiling_float_int((float)offset / (float)uniformBufferOffsetAlignment) * uniformBufferOffsetAlignment; - } - private final int lightSourceBucketsWidth; - private final int lightSourceBucketsHeight; + private final int lightSourceBucketsHeight; private double reprojectionOriginCoordinateX = 0.0; + private double reprojectionOriginCoordinateY = 0.0; + private double reprojectionOriginCoordinateZ = 0.0; private float reprojectionViewerOffsetX = 0.0f; + private float reprojectionViewerOffsetY = 0.0f; + private float reprojectionViewerOffsetZ = 0.0f; private double cloudRenderOriginCoordinateX = 0.0; + private double cloudRenderOriginCoordinateZ = 0.0; private float cloudRenderViewerOffsetX = 0.0f; + private float cloudRenderViewerOffsetZ = 0.0f; private long recalcAtmosphereTimer = 0l; @@ -378,7 +579,7 @@ public class EaglerDeferredPipeline { public EaglerDeferredPipeline(Minecraft mc) { this.mc = mc; - if(matrixCopyBuffer == null) { + if (matrixCopyBuffer == null) { matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); } this.lightSourceBucketsWidth = 5; @@ -387,964 +588,101 @@ public class EaglerDeferredPipeline { this.lightSourceBuckets = new ListSerial[cnt]; this.lightSourceBucketSerials = new int[cnt]; this.lightSourceRenderPosSerials = new int[cnt]; - for(int i = 0; i < cnt; ++i) { + for (int i = 0; i < cnt; ++i) { this.lightSourceBuckets[i] = new ArrayListSerial<>(16); this.lightSourceBucketSerials[i] = -1; this.lightSourceRenderPosSerials[i] = -1; } } - public void rebuild(EaglerDeferredConfig config) { - destroy(); - uniformBufferOffsetAlignment = EaglercraftGPU.getUniformBufferOffsetAlignment(); - DeferredStateManager.doCheckErrors = EagRuntime.getConfiguration().isCheckShaderGLErrors(); - DeferredStateManager.checkGLError("Pre: rebuild pipeline"); - this.config = config; - this.currentWidth = -1; - this.currentHeight = -1; - logger.info("Rebuilding pipeline..."); - - gBufferFramebuffer = _wglCreateFramebuffer(); - - _wglBindFramebuffer(_GL_FRAMEBUFFER, gBufferFramebuffer); - - gBufferDiffuseTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(gBufferDiffuseTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(gBufferDiffuseTexture), 0); - gBufferNormalsTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(gBufferNormalsTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(gBufferNormalsTexture), 0); - gBufferMaterialTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(gBufferMaterialTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(gBufferMaterialTexture), 0); - gBufferDrawBuffers = new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1, _GL_COLOR_ATTACHMENT2 }; - _wglDrawBuffers(gBufferDrawBuffers); - - gBufferDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(gBufferDepthTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(gBufferDepthTexture), 0); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: gbuffers"); - - boolean shadowsSun = config.is_rendering_shadowsSun_clamped > 0; - if(shadowsSun) { - sunShadowFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowFramebuffer); - sunShadowDepthBuffer = GlStateManager.generateTexture(); - GlStateManager.bindTexture(sunShadowDepthBuffer); - setNearest(); - _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_FUNC, GL_GREATER); - _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); - int lods = config.is_rendering_shadowsSun_clamped; - if(lods > 3) { - lods = 3; - } - sunShadowDepthBufferRes = 2048; - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT24, sunShadowDepthBufferRes, sunShadowDepthBufferRes * lods, 0, _GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, (ByteBuffer)null); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(sunShadowDepthBuffer), 0); - sunLightingShadowFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunLightingShadowFramebuffer); - sunLightingShadowTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(sunLightingShadowTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(sunLightingShadowTexture), 0); - if(config.is_rendering_shadowsColored) { - sunShadowColorFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowColorFramebuffer); - GlStateManager.bindTexture(sunShadowDepthBuffer); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(sunShadowDepthBuffer), 0); - sunShadowColorBuffer = GlStateManager.generateTexture(); - GlStateManager.bindTexture(sunShadowColorBuffer); - setNearest(); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, sunShadowDepthBufferRes, sunShadowDepthBufferRes * lods, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(sunShadowColorBuffer), 0); - } - - DeferredStateManager.checkGLError("Post: rebuild pipeline: shadowsSun"); - } - - reprojectionEngineEnable = config.is_rendering_ssao || config.is_rendering_raytracing; - if(reprojectionEngineEnable || config.is_rendering_realisticWater) { - lastFrameFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lastFrameFramebuffer); - lastFrameColorTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lastFrameColorTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lastFrameColorTexture), 0); - lastFrameDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lastFrameDepthTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lastFrameDepthTexture), 0); - lastFrameGBufferFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lastFrameGBufferFramebuffer); - lastFrameGBufferDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lastFrameGBufferDepthTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lastFrameGBufferDepthTexture), 0); - DeferredStateManager.checkGLError("Post: rebuild pipeline: lastFrame"); - } - - if(reprojectionEngineEnable) { - gBufferQuarterFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, gBufferQuarterFramebuffer); - gBufferQuarterDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(gBufferQuarterDepthTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(gBufferQuarterDepthTexture), 0); - reprojectionStartup = 0; - for(int i = 0; i < 2; ++i) { - reprojectionControlFramebuffer[i] = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionControlFramebuffer[i]); - if(config.is_rendering_ssao) { - reprojectionControlSSAOTexture[i] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(reprojectionControlSSAOTexture[i]); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(reprojectionControlSSAOTexture[i]), 0); - } - if(config.is_rendering_raytracing) { - reprojectionSSRTexture[i] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(reprojectionSSRTexture[0]); // yes this should be 0 - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, - config.is_rendering_ssao ? _GL_COLOR_ATTACHMENT1 : _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - EaglercraftGPU.getNativeTexture(reprojectionSSRTexture[0]), 0); - reprojectionSSRHitVector[i] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(reprojectionSSRHitVector[0]); // yes this should be 0 - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, - config.is_rendering_ssao ? _GL_COLOR_ATTACHMENT2 : _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, - EaglercraftGPU.getNativeTexture(reprojectionSSRHitVector[0]), 0); - reprojectionSSRFramebuffer[i] = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionSSRFramebuffer[i]); - _wglDrawBuffers(SSRColorAttachments); - GlStateManager.bindTexture(reprojectionSSRTexture[i]); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(reprojectionSSRTexture[i]), 0); - GlStateManager.bindTexture(reprojectionSSRHitVector[i]); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(reprojectionSSRHitVector[i]), 0); - } - } - shader_reproject_control = PipelineShaderReprojControl.compile(config.is_rendering_ssao, config.is_rendering_raytracing); - shader_reproject_control.loadUniforms(); - if(config.is_rendering_raytracing) { - shader_reproject_ssr = PipelineShaderReprojSSR.compile(); - shader_reproject_ssr.loadUniforms(); - } - reprojectionControlDrawBuffers = new int[(config.is_rendering_ssao ? 1 : 0) + (config.is_rendering_raytracing ? 2 : 0)]; - int i = 0; - if(config.is_rendering_ssao) { - reprojectionControlDrawBuffers[i] = _GL_COLOR_ATTACHMENT0; - ++i; - } - if(config.is_rendering_raytracing) { - reprojectionControlDrawBuffers[i] = _GL_COLOR_ATTACHMENT0 + i; - ++i; - reprojectionControlDrawBuffers[i] = _GL_COLOR_ATTACHMENT0 + i; - } - for(int j = 0; j < 2; ++j) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionControlFramebuffer[j]); - _wglDrawBuffers(reprojectionControlDrawBuffers); - } - DeferredStateManager.checkGLError("Post: rebuild pipeline: reprojectionEngineEnable"); - } - - if(config.is_rendering_ssao) { - ssaoGenerateFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, ssaoGenerateFramebuffer); - ssaoGenerateTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(ssaoGenerateTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(ssaoGenerateTexture), 0); - ssaoNoiseTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(ssaoNoiseTexture); - setNearest(); - int noiseTexSize = 64, noiseTexLen = 16384; - byte[] noiseTexDat = EagRuntime.getRequiredResourceBytes("assets/eagler/glsl/deferred/ssao_noise.bmp"); - if(noiseTexDat == null || noiseTexDat.length != noiseTexLen) { - noiseTexDat = new byte[noiseTexLen]; - for(int i = 0; i < 4096; ++i) { - noiseTexDat[(i << 2) + 2] = (byte)255; // dumb fallback - } - } - ByteBuffer noiseTextureBytes = EagRuntime.allocateByteBuffer(noiseTexLen); - noiseTextureBytes.put(noiseTexDat); - noiseTextureBytes.flip(); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, noiseTexSize, noiseTexSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, noiseTextureBytes); - EagRuntime.freeByteBuffer(noiseTextureBytes); - shader_ssao_generate = PipelineShaderSSAOGenerate.compile(); - shader_ssao_generate.loadUniforms(); - DeferredStateManager.checkGLError("Post: rebuild pipeline: SSAO"); - } - - lightingHDRFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - lightingHDRFramebufferColorTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lightingHDRFramebufferColorTexture), 0); - lightingHDRFramebufferDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lightingHDRFramebufferDepthTexture), 0); - - handRenderFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, handRenderFramebuffer); - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lightingHDRFramebufferColorTexture), 0); - handRenderFramebufferDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(handRenderFramebufferDepthTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(handRenderFramebufferDepthTexture), 0); - - shader_hand_depth_mask = PipelineShaderHandDepthMask.compile(); - shader_hand_depth_mask.loadUniforms(); - shader_deferred_combine = PipelineShaderGBufferCombine.compile(config.is_rendering_ssao, config.is_rendering_useEnvMap, config.is_rendering_raytracing); - shader_deferred_combine.loadUniforms(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: lightingHDRFramebuffer"); - - brdfTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(brdfTexture); - setLinear(); - int brdfLutW = 64, brdfLutH = 64, brdfLutLen = 8192; - byte[] brdfLutDat = EagRuntime.getRequiredResourceBytes("assets/eagler/glsl/deferred/brdf_lut.bmp"); - if(brdfLutDat == null || brdfLutDat.length != brdfLutLen) { - brdfLutDat = new byte[brdfLutLen]; - for(int i = 0; i < 4096; ++i) { - brdfLutDat[i << 1] = (byte)192; // dumb fallback - } - } - ByteBuffer brdfLutDatBuffer = EagRuntime.allocateByteBuffer(brdfLutDat.length); - brdfLutDatBuffer.put(brdfLutDat); - brdfLutDatBuffer.flip(); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_RG8, brdfLutW, brdfLutH, 0, _GL_RG, GL_UNSIGNED_BYTE, brdfLutDatBuffer); - EagRuntime.freeByteBuffer(brdfLutDatBuffer); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: brdfLut"); - - dither8x8Texture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(dither8x8Texture); - setNearest(); - ByteBuffer dither8x8DatBuffer = EagRuntime.allocateByteBuffer(ditherPattern.length); - dither8x8DatBuffer.put(ditherPattern); - dither8x8DatBuffer.flip(); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, 8, 8, 0, GL_RED, GL_UNSIGNED_BYTE, dither8x8DatBuffer); - EagRuntime.freeByteBuffer(dither8x8DatBuffer); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: dither8x8Texture"); - - shader_lighting_sun = PipelineShaderLightingSun.compile(shadowsSun ? config.is_rendering_shadowsSun_clamped : 0, - config.is_rendering_shadowsColored); - shader_lighting_sun.loadUniforms(); - if(shadowsSun) { - shader_shadows_sun = PipelineShaderShadowsSun.compile(config.is_rendering_shadowsSun_clamped, - config.is_rendering_shadowsSmoothed, config.is_rendering_shadowsColored); - shader_shadows_sun.loadUniforms(); - } - shader_post_tonemap = PipelineShaderTonemap.compile(); - shader_post_tonemap.loadUniforms(); - shader_post_fxaa = PipelineShaderFXAA.compile(); - shader_post_fxaa.loadUniforms(); - shader_post_exposure_avg = PipelineShaderPostExposureAvg.compile(false); - shader_post_exposure_avg.loadUniforms(); - shader_post_exposure_avg_luma = PipelineShaderPostExposureAvg.compile(true); - shader_post_exposure_avg_luma.loadUniforms(); - shader_post_exposure_final = PipelineShaderPostExposureFinal.compile(); - shader_post_exposure_final.loadUniforms(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: compile shaders 1"); - - if(config.is_rendering_lensFlares) { - sunOcclusionValueFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunOcclusionValueFramebuffer); - sunOcclusionValueTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(sunOcclusionValueTexture); - setNearest(); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer)null); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(sunOcclusionValueTexture), 0); - shader_lens_sun_occlusion = PipelineShaderLensSunOcclusion.compile(); - shader_lens_sun_occlusion.loadUniforms(); - DeferredStateManager.checkGLError("Post: rebuild pipeline: sunOcclusionValueFramebuffer"); - } - - if(config.is_rendering_lensDistortion) { - lensDistortFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lensDistortFramebuffer); - lensDistortTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lensDistortTexture); - setLinear(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lensDistortTexture), 0); - shader_post_lens_distort = PipelineShaderLensDistortion.compile(); - shader_post_lens_distort.loadUniforms(); - DeferredStateManager.checkGLError("Post: rebuild pipeline: lens distortion"); - } - - lastExposureUpdate = 0l; - - exposureBlendFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, exposureBlendFramebuffer); - exposureBlendTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(exposureBlendTexture); - setNearest(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 1, 1, GL_RED, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(exposureBlendTexture), 0); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: exposureBlendFramebuffer"); - - skybox = new SkyboxRenderer(new ResourceLocation("eagler:glsl/deferred/skybox.dat")); - try { - skybox.load(); - } catch (IOException e) { - throw new RuntimeException("Failed to load skybox!", e); - } - - pointLightMesh = new LightSourceMesh(new ResourceLocation("eagler:glsl/deferred/light_point_mesh.dat"), "light_point_mesh"); - try { - pointLightMesh.load(); - } catch (IOException e) { - throw new RuntimeException("Failed to load point light mesh!", e); - } - - DeferredStateManager.checkGLError("Post: rebuild pipeline: meshes"); - - atmosphereHDRFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, atmosphereHDRFramebuffer); - atmosphereHDRFramebufferColorTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(atmosphereHDRFramebufferColorTexture); - setNearest(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, skybox.getAtmosLUTWidth(), skybox.getAtmosLUTHeight(), GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(atmosphereHDRFramebufferColorTexture), 0); - - envMapAtmosphereFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapAtmosphereFramebuffer); - envMapAtmosphereTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(envMapAtmosphereTexture); - setLinear(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 128, 256, GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(envMapAtmosphereTexture), 0); - - envMapSkyFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapSkyFramebuffer); - envMapSkyTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(envMapSkyTexture); - setLinear(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 128, 256, GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(envMapSkyTexture), 0); - - irradiancePhase = 0; - - atmosphereIrradianceFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, atmosphereIrradianceFramebuffer); - atmosphereIrradianceTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(atmosphereIrradianceTexture); - setLinear(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 32, 64, GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(atmosphereIrradianceTexture), 0); - GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT); - - skyIrradianceFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, skyIrradianceFramebuffer); - skyIrradianceTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(skyIrradianceTexture); - setLinear(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 32, 64, GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(skyIrradianceTexture), 0); - GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: atmosphere"); - - moonTextures = GlStateManager.generateTexture(); - GlStateManager.bindTexture(moonTextures); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - ByteBuffer copyBuffer = EagRuntime.allocateByteBuffer(262144); - int mip = 0; - - try (DataInputStream dis = new DataInputStream(mc.getResourceManager() - .getResource(new ResourceLocation("eagler:glsl/deferred/eagler_moon.bmp")).getInputStream())) { - while(dis.read() == 'E') { - int w = dis.readShort(); - int h = dis.readShort(); - copyBuffer.clear(); - for(int i = 0, l = w * h * 4; i < l; ++i) { - copyBuffer.put((byte)dis.read()); - } - copyBuffer.flip(); - _wglTexImage2D(GL_TEXTURE_2D, mip++, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, copyBuffer); - } - }catch(IOException ex) { - throw new RuntimeException("Could not load \"eagler_moon.bmp\"!", ex); - }finally { - EagRuntime.freeByteBuffer(copyBuffer); - } - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mip - 1); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: moon"); - - CloudRenderWorker.initialize(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: clouds"); - - fogDepthCopyBuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, fogDepthCopyBuffer); - fogDepthCopyTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(fogDepthCopyTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(fogDepthCopyTexture), 0); - - shader_atmosphere_fog = PipelineShaderGBufferFog.compile(false, true, config.is_rendering_lightShafts); - shader_atmosphere_fog.loadUniforms(); - shader_colored_fog_linear = PipelineShaderGBufferFog.compile(true, false, false); - shader_colored_fog_linear.loadUniforms(); - shader_colored_fog_exp = PipelineShaderGBufferFog.compile(false, false, false); - shader_colored_fog_exp.loadUniforms(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: fog"); - - if(config.is_rendering_useEnvMap) { - envMapFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapFramebuffer); - envMapColorTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(envMapColorTexture); - setLinear(); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 128, 256, GL_RGBA, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(envMapColorTexture), 0); - envMapDepthTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(envMapDepthTexture); - setNearest(); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT24, 128, 256, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, (ByteBuffer)null); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(envMapDepthTexture), 0); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: env map"); - } - - if(config.is_rendering_realisticWater) { - realisticWaterMaskFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterMaskFramebuffer); - realisticWaterMaskTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterMaskTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterMaskTexture), 0); - realisticWaterDepthBuffer = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterDepthBuffer); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterDepthBuffer), 0); - realisticWaterCombinedNormalsFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterCombinedNormalsFramebuffer); - realisticWaterCombinedNormalsTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterCombinedNormalsTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterCombinedNormalsTexture), 0); - realisticWaterRefractionTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterRefractionTexture); - setNearest(); - realisticWaterControlFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterControlFramebuffer); - realisticWaterControlReflectionTexture[0] = GlStateManager.generateTexture(); - realisticWaterControlReflectionTexture[1] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterControlReflectionTexture[0]); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterControlReflectionTexture[0]), 0); - realisticWaterControlHitVectorTexture[0] = GlStateManager.generateTexture(); - realisticWaterControlHitVectorTexture[1] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterControlHitVectorTexture[0]); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterControlHitVectorTexture[0]), 0); - GlStateManager.bindTexture(realisticWaterRefractionTexture); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterRefractionTexture), 0); - _wglDrawBuffers(new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1, _GL_COLOR_ATTACHMENT2 }); - for(int i = 0; i < 2; ++i) { - realisticWaterSSRFramebuffer[i] = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterSSRFramebuffer[i]); - GlStateManager.bindTexture(realisticWaterControlReflectionTexture[i]); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterControlReflectionTexture[i]), 0); - GlStateManager.bindTexture(realisticWaterControlHitVectorTexture[i]); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterControlHitVectorTexture[i]), 0); - _wglDrawBuffers(new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1 }); - } - realisticWaterDisplacementMapFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterDisplacementMapFramebuffer); - realisticWaterDisplacementMapTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterDisplacementMapTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterDisplacementMapTexture), 0); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 256, 256, GL_RED, true); - realisticWaterNormalMapFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterNormalMapFramebuffer); - realisticWaterNormalMapTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterNormalMapTexture); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(realisticWaterNormalMapTexture), 0); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_RG8, 256, 256, 0, _GL_RG, GL_UNSIGNED_BYTE, (ByteBuffer)null); - realisticWaterNoiseMap = GlStateManager.generateTexture(); - GlStateManager.bindTexture(realisticWaterNoiseMap); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - String realistic_water_noise_filename = "assets/eagler/glsl/deferred/realistic_water_noise.bmp"; - byte[] bitmapBytes = EagRuntime.getRequiredResourceBytes(realistic_water_noise_filename); - try { - if(bitmapBytes.length != 32768) { - throw new IOException("File is length " + bitmapBytes.length + ", expected " + 32768); - } - }catch(Throwable t) { - throw new RuntimeException("File \"" + realistic_water_noise_filename + "\" could not be loaded!", t); - } - ByteBuffer buf = EagRuntime.allocateByteBuffer(32768); - buf.put(bitmapBytes); - buf.flip(); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_RG8, 128, 128, 0, _GL_RG, GL_UNSIGNED_BYTE, buf); - EagRuntime.freeByteBuffer(buf); - shader_realistic_water_control = PipelineShaderRealisticWaterControl.compile(); - shader_realistic_water_control.loadUniforms(); - shader_realistic_water_noise = PipelineShaderRealisticWaterNoise.compile(); - shader_realistic_water_noise.loadUniforms(); - shader_realistic_water_normals = PipelineShaderRealisticWaterNormalMap.compile(); - shader_realistic_water_normals.loadUniforms(); - _wglUniform2f(shader_realistic_water_normals.uniforms.u_sampleOffset2f, 0.00390625f, 0.00390625f); - if(!config.is_rendering_raytracing) { - shader_reproject_ssr = PipelineShaderReprojSSR.compile(); - shader_reproject_ssr.loadUniforms(); - } - - DeferredStateManager.checkGLError("Post: rebuild pipeline: realistic water"); - } - - if(config.is_rendering_fxaa) { - tonemapOutputFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, tonemapOutputFramebuffer); - tonemapOutputTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(tonemapOutputTexture); - setNearest(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(tonemapOutputTexture), 0); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: fxaa"); - } - - if(config.is_rendering_lensFlares) { - LensFlareMeshRenderer.initialize(); - DeferredStateManager.checkGLError("Post: rebuild pipeline: lensFlares"); - } - - recalcAtmosphereTimer = 0l; - - shader_skybox_atmosphere = PipelineShaderSkyboxAtmosphere.compile(); - shader_skybox_atmosphere.loadUniforms(); - - shader_skybox_render = PipelineShaderSkyboxRender.compile(false, true); - shader_skybox_render.loadUniforms(); - - shader_skybox_render_paraboloid = PipelineShaderSkyboxRender.compile(true, true); - shader_skybox_render_paraboloid.loadUniforms(); - - shader_skybox_render_paraboloid_noclouds = PipelineShaderSkyboxRender.compile(true, false); - shader_skybox_render_paraboloid_noclouds.loadUniforms(); - - shader_skybox_irradiance[0] = PipelineShaderSkyboxIrradiance.compile(0); - shader_skybox_irradiance[0].loadUniforms(); - - shader_skybox_irradiance[1] = PipelineShaderSkyboxIrradiance.compile(1); - shader_skybox_irradiance[1].loadUniforms(); - - shader_skybox_irradiance[2] = PipelineShaderSkyboxIrradiance.compile(2); - shader_skybox_irradiance[2].loadUniforms(); - - shader_moon_render = PipelineShaderMoonRender.compile(); - shader_moon_render.loadUniforms(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: skybox shaders"); - - if(config.is_rendering_lightShafts) { - lightShaftsFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightShaftsFramebuffer); - lightShaftsTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lightShaftsTexture); - setLinear(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(lightShaftsTexture), 0); - shader_light_shafts_sample = PipelineShaderLightShaftsSample.compile(config.is_rendering_shadowsSun_clamped); - shader_light_shafts_sample.loadUniforms(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: light shafts"); - } - - if(config.is_rendering_bloom) { - bloomBrightPassFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomBrightPassFramebuffer); - bloomBrightPassTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(bloomBrightPassTexture); - setNearest(); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(bloomBrightPassTexture), 0); - bloomDownscaleAFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleAFramebuffer); - bloomDownscaleATexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(bloomDownscaleATexture); - setLinear(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(bloomDownscaleATexture), 0); - bloomDownscaleBFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleBFramebuffer); - bloomDownscaleBTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(bloomDownscaleBTexture); - setLinear(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(bloomDownscaleBTexture), 0); - bloomHBlurFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomHBlurFramebuffer); - bloomHBlurTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(bloomHBlurTexture); - setNearest(); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(bloomHBlurTexture), 0); - bloomVBlurFramebuffer = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomVBlurFramebuffer); - bloomVBlurTexture = GlStateManager.generateTexture(); - GlStateManager.bindTexture(bloomVBlurTexture); - setLinear(); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, EaglercraftGPU.getNativeTexture(bloomVBlurTexture), 0); - shader_post_bloom_bright = PipelineShaderBloomBrightPass.compile(); - shader_post_bloom_bright.loadUniforms(); - shader_post_bloom_blur = PipelineShaderBloomBlurPass.compile(); - shader_post_bloom_blur.loadUniforms(); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: bloom"); - } - - gbufferEffectRenderer.initialize(); - forwardEffectRenderer.initialize(config.is_rendering_dynamicLights, config.is_rendering_shadowsSun_clamped); - - if(config.is_rendering_dynamicLights) { - shader_lighting_point = PipelineShaderLightingPoint.compile(false); - shader_lighting_point.loadUniforms(); - - lightingBufferSliceLength = uboAlign(LIGHTING_BUFFER_LENGTH); - - chunkLightingDataCopyBuffer = EagRuntime.allocateByteBuffer(LIGHTING_BUFFER_LENGTH); - for(int i = 0; i < LIGHTING_BUFFER_LENGTH; i += 4) { - chunkLightingDataCopyBuffer.putInt(0); - } - chunkLightingDataCopyBuffer.flip(); - - buffer_chunkLightingData = _wglGenBuffers(); - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); - int cnt = lightSourceBucketsWidth * lightSourceBucketsHeight * lightSourceBucketsWidth; - _wglBufferData(_GL_UNIFORM_BUFFER, cnt * lightingBufferSliceLength, GL_DYNAMIC_DRAW); - - buffer_chunkLightingDataZero = _wglGenBuffers(); - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); - _wglBufferData(_GL_UNIFORM_BUFFER, chunkLightingDataCopyBuffer, GL_STATIC_DRAW); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: dynamic lights"); - } - - buffer_worldLightingData = _wglGenBuffers(); - EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); - worldLightingDataCopyBuffer = EagRuntime.allocateByteBuffer(304); - for(int i = 0; i < 76; ++i) { - worldLightingDataCopyBuffer.putInt(0); - } - worldLightingDataCopyBuffer.flip(); - _wglBufferData(_GL_UNIFORM_BUFFER, worldLightingDataCopyBuffer, GL_DYNAMIC_DRAW); - - DeferredStateManager.checkGLError("Post: rebuild pipeline: world lighting data"); - - FixedFunctionPipeline.loadExtensionPipeline(deferredExtPipeline); - - if(!EaglercraftGPU.checkHDRFramebufferSupport(16)) { - logger.warn("16-bit HDR (floating point) framebuffers are not supported on this device, 32-bit framebuffers will be used instead which may slow the game down"); - } - - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - DeferredStateManager.checkGLError("Post: rebuild pipeline"); - } - - public void setRenderPosGlobal(double renderPosX, double renderPosY, double renderPosZ) { - if (renderPosX != currentRenderX || renderPosY != currentRenderY || renderPosZ != currentRenderZ - || currentRenderPosSerial == 0) { - currentRenderX = renderPosX; - currentRenderY = renderPosY; - currentRenderZ = renderPosZ; - ++currentRenderPosSerial; + public void addLightSourceToBucket(int cx, int cy, int cz, DynamicLightInstance dl) { + ListSerial lst = getLightSourceBucketRelativeChunkCoords(cx, cy, cz); + if (lst != null) { + lst.add(dl); } } - public void updateReprojectionCoordinates(double worldX, double worldY, double worldZ) { - double distX = worldX - reprojectionOriginCoordinateX; - double distY = worldY - reprojectionOriginCoordinateY; - double distZ = worldZ - reprojectionOriginCoordinateZ; - if(distX * distX + distY * distY + distZ * distZ > 48.0 * 48.0) { - reprojectionOriginCoordinateX = worldX; - reprojectionOriginCoordinateY = worldY; - reprojectionOriginCoordinateZ = worldZ; - reprojectionViewerOffsetX = 0.0f; - reprojectionViewerOffsetY = 0.0f; - reprojectionViewerOffsetZ = 0.0f; - reprojectionStartup = 0; - }else { - reprojectionViewerOffsetX = (float) distX; - reprojectionViewerOffsetY = (float) distY; - reprojectionViewerOffsetZ = (float) distZ; - } - distX = worldX - cloudRenderOriginCoordinateX; - distZ = worldZ - cloudRenderOriginCoordinateZ; - if(distX * distX + distZ * distZ > 256.0 * 256.0) { - cloudRenderOriginCoordinateX = worldX; - cloudRenderOriginCoordinateZ = worldZ; - cloudRenderViewerOffsetX = 0.0f; - cloudRenderViewerOffsetZ = 0.0f; - }else { - cloudRenderViewerOffsetX = (float) distX; - cloudRenderViewerOffsetZ = (float) distZ; - } - } - - public void setPartialTicks(float partialTicks_) { - partialTicks = partialTicks_; - } - - public float getPartialTicks() { - return partialTicks; - } - - public void resize(int w, int h) { - if(w == currentWidth && h == currentHeight) { + public void applyGBufferFog() { + DeferredStateManager.checkGLError("Pre: applyGBufferFog()"); + if (DeferredStateManager.fogLinearExp == 0) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); return; } - - DeferredStateManager.checkGLError("Pre: resize pipeline to " + w + " x " + h); - - GlStateManager.bindTexture(gBufferDiffuseTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - GlStateManager.bindTexture(gBufferNormalsTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - GlStateManager.bindTexture(gBufferMaterialTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - - GlStateManager.bindTexture(gBufferDepthTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - - DeferredStateManager.checkGLError("Post: resize pipeline: gbuffer"); - - if(config.is_rendering_shadowsSun_clamped > 0) { - GlStateManager.bindTexture(sunLightingShadowTexture); - if(config.is_rendering_shadowsColored) { - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - }else { - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer)null); - } - DeferredStateManager.checkGLError("Post: resize pipeline: sunLightingShadowTexture"); - } - - reprojectionStartup = 0; - reprojectionTexWidth = w >> 1; - reprojectionTexHeight = h >> 1; - - shader_deferred_combine.useProgram(); - _wglUniform2f(shader_deferred_combine.uniforms.u_halfResolutionPixelAlignment2f, (float)w / (reprojectionTexWidth << 1), (float)h / (reprojectionTexHeight << 1)); - - if(config.is_rendering_ssao) { - GlStateManager.bindTexture(ssaoGenerateTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, reprojectionTexWidth, reprojectionTexHeight, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer)null); - DeferredStateManager.checkGLError("Post: resize pipeline: ssao"); - } - - if(reprojectionEngineEnable || config.is_rendering_realisticWater) { - GlStateManager.bindTexture(lastFrameColorTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, GL_RGBA, true); - GlStateManager.bindTexture(lastFrameDepthTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, reprojectionTexWidth, reprojectionTexHeight, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - GlStateManager.bindTexture(lastFrameGBufferDepthTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - DeferredStateManager.checkGLError("Post: resize pipeline: lastFrame"); - } - - if(config.is_rendering_raytracing || config.is_rendering_realisticWater) { - shader_reproject_ssr.useProgram(); - _wglUniform4f(shader_reproject_ssr.uniforms.u_pixelAlignment4f, reprojectionTexWidth, reprojectionTexHeight, w, h); - } - - if(reprojectionEngineEnable) { - GlStateManager.bindTexture(gBufferQuarterDepthTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, reprojectionTexWidth, reprojectionTexHeight, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - - for(int i = 0; i < 2; ++i) { - if(config.is_rendering_ssao) { - GlStateManager.bindTexture(reprojectionControlSSAOTexture[i]); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, reprojectionTexWidth, reprojectionTexHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - } - if(config.is_rendering_raytracing) { - GlStateManager.bindTexture(reprojectionSSRTexture[i]); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, GL_RGBA, true); - GlStateManager.bindTexture(reprojectionSSRHitVector[i]); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, GL_RGBA, true); - } - } - - shader_reproject_control.useProgram(); - _wglUniform4f(shader_reproject_control.uniforms.u_pixelAlignment4f, reprojectionTexWidth, reprojectionTexHeight, w, h); - DeferredStateManager.checkGLError("Post: resize pipeline: reprojectionEngineEnable"); - } - - if(config.is_rendering_realisticWater) { - GlStateManager.bindTexture(realisticWaterMaskTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - GlStateManager.bindTexture(realisticWaterDepthBuffer); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - GlStateManager.bindTexture(realisticWaterCombinedNormalsTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - GlStateManager.bindTexture(realisticWaterRefractionTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, GL_RGBA, true); - for(int i = 0; i < 2; ++i) { - GlStateManager.bindTexture(realisticWaterControlReflectionTexture[i]); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, GL_RGBA, true); - GlStateManager.bindTexture(realisticWaterControlHitVectorTexture[i]); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, GL_RGBA, true); - } - - shader_realistic_water_control.useProgram(); - _wglUniform4f(shader_realistic_water_control.uniforms.u_pixelAlignment4f, reprojectionTexWidth, reprojectionTexHeight, w, h); - DeferredStateManager.checkGLError("Post: resize pipeline: realisticWater"); - } - - if(config.is_rendering_lightShafts) { + _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, lightingHDRFramebuffer); + _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, fogDepthCopyBuffer); + _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, + GL_NEAREST); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + if (config.is_rendering_lightShafts) { + GlStateManager.setActiveTexture(GL_TEXTURE4); GlStateManager.bindTexture(lightShaftsTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, reprojectionTexWidth, reprojectionTexHeight, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer)null); - DeferredStateManager.checkGLError("Post: resize pipeline: lightShafts"); } - - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, w, h, GL_RGBA, true); // USE RGBA! WebGL won't render to RGB16F - - GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - - GlStateManager.bindTexture(handRenderFramebufferDepthTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - - DeferredStateManager.checkGLError("Post: resize pipeline: lightingHDRFramebuffer"); - + GlStateManager.setActiveTexture(GL_TEXTURE3); + GlStateManager.bindTexture(skyIrradianceTexture); + GlStateManager.setActiveTexture(GL_TEXTURE2); GlStateManager.bindTexture(fogDepthCopyTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer)null); - - DeferredStateManager.checkGLError("Post: resize pipeline: fogDepthCopyTexture"); - - if(config.is_rendering_lensDistortion) { - GlStateManager.bindTexture(lensDistortTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - DeferredStateManager.checkGLError("Post: resize pipeline: lensDistortion"); + GlStateManager.setActiveTexture(GL_TEXTURE1); + GlStateManager.bindTexture(gBufferNormalsTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(gBufferDepthTexture); + tmpMatrix1.load(DeferredStateManager.inverseViewMatrix); + tmpMatrix1.m30 = tmpMatrix1.m31 = tmpMatrix1.m32 = 0.0f; + Matrix4f.mul(tmpMatrix1, DeferredStateManager.inverseProjMatrix, tmpMatrix1); + PipelineShaderGBufferFog fogShader; + switch (DeferredStateManager.fogLinearExp) { + case 1: + fogShader = shader_colored_fog_linear; + fogShader.useProgram(); + _wglUniform2f(fogShader.uniforms.u_linearFogParam2f, DeferredStateManager.fogNear, + DeferredStateManager.fogFar); + break; + case 2: + fogShader = shader_colored_fog_exp; + fogShader.useProgram(); + _wglUniform1f(fogShader.uniforms.u_expFogDensity1f, DeferredStateManager.fogDensity); + break; + case 6: + fogShader = shader_atmosphere_fog; + fogShader.useProgram(); + _wglUniform1f(fogShader.uniforms.u_expFogDensity1f, DeferredStateManager.fogDensity); + float mul = 0.05f * MathHelper.clamp_float(-1.0f - DeferredStateManager.getSunHeight() * 20.0f, 0.0f, 1.0f) + + 0.01f; + _wglUniform3f(fogShader.uniforms.u_sunColorAdd3f, DeferredStateManager.currentSunLightColor.x * mul, + DeferredStateManager.currentSunLightColor.y * mul, + DeferredStateManager.currentSunLightColor.z * mul); + break; + default: + throw new RuntimeException("Invalid fog type: " + DeferredStateManager.fogLinearExp); } - - if(config.is_rendering_fxaa) { - GlStateManager.bindTexture(tonemapOutputTexture); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer)null); - DeferredStateManager.checkGLError("Post: resize pipeline: fxaa"); - } - - if(config.is_rendering_bloom) { - int bloomStageW = w; - int bloomStageH = h; - GlStateManager.bindTexture(bloomBrightPassTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); - bloomBrightPassTextureW = bloomStageW; - bloomBrightPassTextureH = bloomStageH; - bloomDownscaleATextureW = bloomDownscaleATextureH = 0; - bloomDownscaleBTextureW = bloomDownscaleBTextureH = 0; - if(bloomStageW > 150 && bloomStageH > 85) { - setLinear(); - bloomStageW >>= 1; - bloomStageH >>= 1; - if(bloomStageW > 150 && bloomStageH > 85) { - GlStateManager.bindTexture(bloomDownscaleATexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); - bloomDownscaleATextureW = bloomStageW; - bloomDownscaleATextureH = bloomStageH; - bloomStageW >>= 1; - bloomStageH >>= 1; - if(bloomStageW > 150 && bloomStageH > 85) { - GlStateManager.bindTexture(bloomDownscaleBTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); - bloomDownscaleBTextureW = bloomStageW; - bloomDownscaleBTextureH = bloomStageH; - bloomStageW >>= 1; - bloomStageH >>= 1; - } - } - }else { - setNearest(); - } - GlStateManager.bindTexture(bloomHBlurTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); - GlStateManager.bindTexture(bloomVBlurTexture); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); - bloomBlurTextureW = bloomStageW; - bloomBlurTextureH = bloomStageH; - DeferredStateManager.checkGLError("Post: resize pipeline: bloom"); - } - - if(lumaAvgDownscaleFramebuffers != null) { - for(int i = 0; i < lumaAvgDownscaleFramebuffers.length; ++i) { - _wglDeleteFramebuffer(lumaAvgDownscaleFramebuffers[i]); - } - } - - if(lumaAvgDownscaleTexture != null) { - for(int i = 0; i < lumaAvgDownscaleTexture.length; ++i) { - GlStateManager.deleteTexture(lumaAvgDownscaleTexture[i]); - } - } - - int j = 0; - int k = h > w ? w : h; - while(k > 8) { - ++j; - k >>= 2; - } - - lumaAvgDownscaleFramebuffers = new IFramebufferGL[j]; - lumaAvgDownscaleTexture = new int[j]; - - int kw = w; - int kh = h; - int kw2, kh2; - for(int i = 0; i < j; ++i) { - kw2 = kw >> 2; - kh2 = kh >> 2; - lumaAvgDownscaleFramebuffers[i] = _wglCreateFramebuffer(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lumaAvgDownscaleFramebuffers[i]); - lumaAvgDownscaleTexture[i] = GlStateManager.generateTexture(); - GlStateManager.bindTexture(lumaAvgDownscaleTexture[i]); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, i == j - 1 ? GL_NEAREST : GL_LINEAR); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, i == j - 1 ? GL_NEAREST : GL_LINEAR); - EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, ((kw & 3) != 0) ? (kw2 + 1) : kw2, - ((kh & 3) != 0) ? (kh2 + 1) : kh2, GL_RED, true); - _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - EaglercraftGPU.getNativeTexture(lumaAvgDownscaleTexture[i]), 0); - kw = kw2; - kh = kh2; - } - - currentWidth = w; - currentHeight = h; - - DeferredStateManager.checkGLError("Post: resize pipeline: lumaAvg"); + uniformMatrixHelper(fogShader.uniforms.u_inverseViewProjMatrix4f, tmpMatrix1); + _wglUniform4f(fogShader.uniforms.u_fogColorLight4f, DeferredStateManager.fogColorLightR, + DeferredStateManager.fogColorLightG, DeferredStateManager.fogColorLightB, + DeferredStateManager.fogColorLightA); + _wglUniform4f(fogShader.uniforms.u_fogColorDark4f, DeferredStateManager.fogColorDarkR, + DeferredStateManager.fogColorDarkG, DeferredStateManager.fogColorDarkB, + DeferredStateManager.fogColorDarkA); + GlStateManager.disableDepth(); + GlStateManager.depthMask(false); + GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + DrawUtils.drawStandardQuad2D(); + GlStateManager.enableDepth(); + GlStateManager.depthMask(true); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + DeferredStateManager.checkGLError("Post: applyGBufferFog()"); } - public void loadViewMatrix() { - DeferredStateManager.loadGBufferViewMatrix(); - DeferredStateManager.loadGBufferProjectionMatrix(); + public void beginDrawColoredShadows() { + DeferredStateManager.checkGLError("Pre: beginDrawColoredShadows()"); + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowColorFramebuffer); + DeferredStateManager.enableForwardRender(); + GlStateManager.globalEnableBlend(); + GlStateManager.enableBlend(); + GlStateManager.depthMask(false); + GlStateManager.tryBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ZERO); + GlStateManager.enablePolygonOffset(); + GlStateManager.doPolygonOffset(0.25f, 1.0f); + GlStateManager.colorMask(true, true, true, true); + DeferredStateManager.checkGLError("Post: beginDrawColoredShadows()"); } public void beginDrawDeferred() { @@ -1352,6 +690,142 @@ public class EaglerDeferredPipeline { DynamicLightManager.lightRenderList.clear(); } + public void beginDrawEnvMap() { + DeferredStateManager.checkGLError("Pre: beginDrawEnvMap()"); + GlStateManager.enableDepth(); + GlStateManager.depthMask(true); + DeferredStateManager.enableForwardRender(); + DeferredStateManager.enableParaboloidRender(); + DeferredStateManager.disableFog(); + GlStateManager.enableExtensionPipeline(); + updateForwardRenderWorldLightingData(); + EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); + EaglercraftGPU.bindUniformBufferRange(0, buffer_worldLightingData, 0, worldLightingDataCopyBuffer.remaining()); + if (config.is_rendering_dynamicLights) { + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); + EaglercraftGPU.bindUniformBufferRange(1, buffer_chunkLightingData, 0, + chunkLightingDataCopyBuffer.capacity()); + } + GlStateManager.matrixMode(GL_PROJECTION); + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); + GlStateManager.matrixMode(GL_MODELVIEW); + GlStateManager.pushMatrix(); + GlStateManager.loadIdentity(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapFramebuffer); + GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + GlStateManager.setActiveTexture(GL_TEXTURE10); + GlStateManager.bindTexture(skyIrradianceTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + DeferredStateManager.checkGLError("Post: beginDrawEnvMap()"); + } + + public void beginDrawEnvMapBottom(float eyeHeight) { + DeferredStateManager.checkGLError("Pre: beginDrawEnvMapBottom()"); + GlStateManager.loadIdentity(); + tmpMatrix1.setIdentity(); + tmpMatrix1.m32 = -eyeHeight; + Matrix4f.mul(tmpMatrix1, DeferredStateManager.paraboloidBottomViewMatrix, tmpMatrix1); + GlStateManager.getModelViewReference().load(tmpMatrix1); + DeferredStateManager.passViewMatrix.load(tmpMatrix1); + Matrix4f.invert(DeferredStateManager.passViewMatrix, DeferredStateManager.passInverseViewMatrix); + ++DeferredStateManager.passViewMatrixSerial; + GlStateManager.viewport(0, 128, 128, 128); + DeferredStateManager.checkGLError("Post: beginDrawEnvMapBottom()"); + } + + public void beginDrawEnvMapSolid() { + DeferredStateManager.checkGLError("Pre: beginDrawEnvMapSolid()"); + GlStateManager.disableBlend(); + bindEnvMapBlockTexture(); + DeferredStateManager.checkGLError("Post: beginDrawEnvMapSolid()"); + } + + public void beginDrawEnvMapTop(float eyeHeight) { + DeferredStateManager.checkGLError("Pre: beginDrawEnvMapTop()"); + GlStateManager.loadIdentity(); + tmpMatrix1.setIdentity(); + tmpMatrix1.m32 = eyeHeight; + Matrix4f.mul(tmpMatrix1, DeferredStateManager.paraboloidTopViewMatrix, tmpMatrix1); + GlStateManager.getModelViewReference().load(tmpMatrix1); + DeferredStateManager.passProjMatrix.setIdentity(); + DeferredStateManager.passInverseProjMatrix.setIdentity(); + ++DeferredStateManager.passProjMatrixSerial; + DeferredStateManager.passViewMatrix.load(tmpMatrix1); + Matrix4f.invert(DeferredStateManager.passViewMatrix, DeferredStateManager.passInverseViewMatrix); + ++DeferredStateManager.passViewMatrixSerial; + GlStateManager.viewport(0, 0, 128, 128); + DeferredStateManager.checkGLError("Post: beginDrawEnvMapTop()"); + } + + public void beginDrawEnvMapTranslucent() { + DeferredStateManager.checkGLError("Pre: beginDrawEnvMapTranslucent()"); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); + bindEnvMapBlockTexture(); + DeferredStateManager.checkGLError("Post: beginDrawEnvMapTranslucent()"); + } + + public void beginDrawGlassHighlights() { + DeferredStateManager.checkGLError("Pre: beginDrawGlassHighlights()"); + DeferredStateManager.enableDrawGlassHighlightsRender(); + GlStateManager.depthMask(false); + GlStateManager.enablePolygonOffset(); + GlStateManager.doPolygonOffset(0.25f, 1.0f); + GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); + DeferredStateManager.checkGLError("Post: beginDrawGlassHighlights()"); + } + + public void beginDrawHandOverlay() { + DeferredStateManager.checkGLError("Pre: beginDrawHandOverlay()"); + _wglBindFramebuffer(_GL_FRAMEBUFFER, handRenderFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + GlStateManager.clearDepth(1.0f); + GlStateManager.depthMask(true); + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + GlStateManager.enableDepth(); + DeferredStateManager.setDefaultMaterialConstants(); + DeferredStateManager.checkGLError("Post: beginDrawHandOverlay()"); + } + + public void beginDrawHDRTranslucent() { + DeferredStateManager.checkGLError("Pre: beginDrawHDRTranslucent()"); + GlStateManager.enableDepth(); + GlStateManager.depthMask(true); + GlStateManager.enableAlpha(); + GlStateManager.alphaFunc(GL_GREATER, 0.1f); + GlStateManager.enableBlend(); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + DeferredStateManager.enableForwardRender(); + GlStateManager.enableExtensionPipeline(); + updateForwardRenderWorldLightingData(); + EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); + EaglercraftGPU.bindUniformBufferRange(0, buffer_worldLightingData, 0, worldLightingDataCopyBuffer.remaining()); + if (config.is_rendering_dynamicLights) { + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); + EaglercraftGPU.bindUniformBufferRange(1, buffer_chunkLightingData, 0, + chunkLightingDataCopyBuffer.capacity()); + } + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + DeferredStateManager.setPassMatrixToGBuffer(); + GlStateManager.setActiveTexture(GL_TEXTURE10); + GlStateManager.bindTexture(skyIrradianceTexture); + if (config.is_rendering_lightShafts) { + GlStateManager.setActiveTexture(GL_TEXTURE11); + GlStateManager.bindTexture(lightShaftsTexture); + } + if (config.is_rendering_useEnvMap) { + GlStateManager.setActiveTexture(GL_TEXTURE5); + GlStateManager.bindTexture(envMapColorTexture); + } + GlStateManager.setActiveTexture(GL_TEXTURE6); + GlStateManager.bindTexture(brdfTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + DeferredStateManager.checkGLError("Post: beginDrawHDRTranslucent()"); + } + public void beginDrawMainGBuffer() { DeferredStateManager.checkGLError("Pre: beginDrawMainGBuffer()"); resize(mc.displayWidth, mc.displayHeight); @@ -1367,6 +841,15 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("Post: beginDrawMainGBuffer()"); } + public void beginDrawMainGBufferDestroyProgress() { + DeferredStateManager.checkGLError("Pre: beginDrawMainGBufferDestroyProgress()"); + GlStateManager.disableExtensionPipeline(); + } + + public void beginDrawMainGBufferEntities() { + DeferredStateManager.checkGLError("Pre: beginDrawMainGBufferEntities()"); + } + public void beginDrawMainGBufferTerrain() { DeferredStateManager.checkGLError("Pre: beginDrawMainGBufferTerrain()"); TextureManager mgr = mc.getTextureManager(); @@ -1376,36 +859,16 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("Post: beginDrawMainGBufferTerrain()"); } - public void beginDrawMainGBufferEntities() { - DeferredStateManager.checkGLError("Pre: beginDrawMainGBufferEntities()"); - } - - public void beginDrawMainGBufferDestroyProgress() { - DeferredStateManager.checkGLError("Pre: beginDrawMainGBufferDestroyProgress()"); - GlStateManager.disableExtensionPipeline(); - } - - public void endDrawMainGBufferDestroyProgress() { - DeferredStateManager.checkGLError("Pre: endDrawMainGBufferDestroyProgress()"); - GlStateManager.enableExtensionPipeline(); - } - - public void endDrawMainGBuffer() { - DeferredStateManager.checkGLError("Pre: endDrawMainGBuffer()"); - _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); - DeferredStateManager.checkGLError("Post: endDrawMainGBuffer()"); - } - public void beginDrawMainShadowMap() { DeferredStateManager.checkGLError("Pre: beginDrawMainShadowMap()"); - if(config.is_rendering_shadowsColored) { + if (config.is_rendering_shadowsColored) { _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowColorFramebuffer); _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); GlStateManager.clearColor(1.0f, 1.0f, 1.0f, 1.0f); GlStateManager.clearDepth(1.0f); GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowFramebuffer); - }else { + } else { _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowFramebuffer); _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); GlStateManager.clearDepth(1.0f); @@ -1418,47 +881,225 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("Post: beginDrawMainShadowMap()"); } - public void endDrawMainShadowMap() { - DeferredStateManager.checkGLError("Pre: endDrawMainShadowMap()"); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - GlStateManager.cullFace(GL_BACK); - DeferredStateManager.disableShadowRender(); - GlStateManager.colorMask(true, true, true, true); - DeferredStateManager.checkGLError("Post: endDrawMainShadowMap()"); - } - public void beginDrawMainShadowMapLOD(int lod) { DeferredStateManager.checkGLError("Pre: beginDrawMainShadowMapLOD(" + lod + ")"); GlStateManager.viewport(0, sunShadowDepthBufferRes * lod, sunShadowDepthBufferRes, sunShadowDepthBufferRes); } - public void beginDrawColoredShadows() { - DeferredStateManager.checkGLError("Pre: beginDrawColoredShadows()"); - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowColorFramebuffer); - DeferredStateManager.enableForwardRender(); - GlStateManager.globalEnableBlend(); - GlStateManager.enableBlend(); - GlStateManager.depthMask(false); - GlStateManager.tryBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ZERO); - GlStateManager.enablePolygonOffset(); - GlStateManager.doPolygonOffset(0.25f, 1.0f); - GlStateManager.colorMask(true, true, true, true); - DeferredStateManager.checkGLError("Post: beginDrawColoredShadows()"); - } - - public void endDrawColoredShadows() { - DeferredStateManager.checkGLError("Pre: endDrawColoredShadows()"); - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowFramebuffer); - DeferredStateManager.disableForwardRender(); - GlStateManager.disableBlend(); - GlStateManager.globalDisableBlend(); + public void beginDrawRealisticWaterMask() { + DeferredStateManager.checkGLError("Pre: beginDrawRealisticWaterMask()"); + _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, gBufferFramebuffer); + _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, realisticWaterMaskFramebuffer); + _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, + GL_NEAREST); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterMaskFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT); + GlStateManager.enableDepth(); + GlStateManager.enableCull(); GlStateManager.depthMask(true); - GlStateManager.disablePolygonOffset(); - GlStateManager.colorMask(false, false, false, false); - DeferredStateManager.checkGLError("Post: endDrawColoredShadows()"); + DeferredStateManager.enableDrawRealisticWaterMask(); + GlStateManager.enableExtensionPipeline(); + DeferredStateManager.checkGLError("Post: beginDrawRealisticWaterMask()"); } - private static final ResourceLocation locationEndSkyPng = new ResourceLocation("textures/environment/end_sky.png"); + public void beginDrawRealisticWaterSurface() { + DeferredStateManager.checkGLError("Pre: beginDrawRealisticWaterSurface()"); + DeferredStateManager.enableDrawRealisticWaterRender(); + GlStateManager.setActiveTexture(GL_TEXTURE9); + GlStateManager.bindTexture(realisticWaterNormalMapTexture); + GlStateManager.setActiveTexture(GL_TEXTURE8); + GlStateManager.bindTexture(realisticWaterRefractionTexture); + GlStateManager.setActiveTexture(GL_TEXTURE7); + GlStateManager.bindTexture(realisticWaterControlReflectionTexture[1]); + GlStateManager.setActiveTexture(GL_TEXTURE5); + GlStateManager.bindTexture(envMapSkyTexture); + GlStateManager.setActiveTexture(GL_TEXTURE4); + if (config.is_rendering_shadowsSun_clamped > 0) { + GlStateManager.bindTexture(sunShadowDepthBuffer); + if (config.is_rendering_shadowsSmoothed) { + setLinear(); + } + } else { + GlStateManager.bindTexture(-1); + } + TextureManager mgr = mc.getTextureManager(); + GlStateManager.setActiveTexture(GL_TEXTURE3); + GlStateManager.bindTexture(MetalsLUT.getGLTexture()); + GlStateManager.setActiveTexture(GL_TEXTURE0); + mgr.bindTexture(TextureMap.locationBlocksTexture); + GlStateManager.enableCull(); + DeferredStateManager.checkGLError("Post: beginDrawRealisticWaterSurface()"); + } + + public void beginDrawTranslucentBlocks() { + DeferredStateManager.checkGLError("Pre: beginDrawTranslucentBlocks()"); + } + + public void beginDrawTranslucentEntities() { + DeferredStateManager.checkGLError("Pre: beginDrawTranslucentEntities()"); + GlStateManager.setActiveTexture(GL_TEXTURE4); + if (config.is_rendering_shadowsSun_clamped > 0) { + GlStateManager.bindTexture(sunShadowDepthBuffer); + if (config.is_rendering_shadowsSmoothed) { + setLinear(); + } + } else { + GlStateManager.bindTexture(-1); + } + TextureManager mgr = mc.getTextureManager(); + GlStateManager.setActiveTexture(GL_TEXTURE3); + GlStateManager.bindTexture(MetalsLUT.getGLTexture()); + GlStateManager.setActiveTexture(GL_TEXTURE0); + mgr.bindTexture(TextureMap.locationBlocksTexture); + GlStateManager.enableCull(); + DeferredStateManager.checkGLError("Post: beginDrawTranslucentEntities()"); + } + + private void bindEnvMapBlockTexture() { + DeferredStateManager.checkGLError("Pre: bindEnvMapBlockTexture()"); + GlStateManager.setActiveTexture(GL_TEXTURE4); + if (config.is_rendering_shadowsSun_clamped > 0) { + GlStateManager.bindTexture(sunShadowDepthBuffer); + } else { + GlStateManager.bindTexture(-1); + } + TextureManager mgr = mc.getTextureManager(); + GlStateManager.setActiveTexture(GL_TEXTURE10); + GlStateManager.bindTexture(skyIrradianceTexture); + GlStateManager.setActiveTexture(GL_TEXTURE3); + GlStateManager.bindTexture(MetalsLUT.getGLTexture()); + GlStateManager.setActiveTexture(GL_TEXTURE0); + mgr.bindTexture(TextureMap.locationBlocksTexture); + GlStateManager.enableCull(); + DeferredStateManager.checkGLError("Post: bindEnvMapBlockTexture()"); + } + + public void bindLightSourceBucket(int relativeBlockX, int relativeBlockY, int relativeBlockZ, int uboIndex) { + int hw = lightSourceBucketsWidth / 2; + int hh = lightSourceBucketsHeight / 2; + int bucketX = (relativeBlockX >> 4) + hw; + int bucketY = (relativeBlockY >> 4) + hh; + int bucketZ = (relativeBlockZ >> 4) + hw; + if (bucketX >= 0 && bucketY >= 0 && bucketZ >= 0 && bucketX < lightSourceBucketsWidth + && bucketY < lightSourceBucketsHeight && bucketZ < lightSourceBucketsWidth) { + currentLightSourceBucketId = bucketY * lightSourceBucketsWidth * lightSourceBucketsWidth + + bucketZ * lightSourceBucketsWidth + bucketX; + currentLightSourceBucket = lightSourceBuckets[currentLightSourceBucketId]; + int ser = currentLightSourceBucket.getEaglerSerial(); + int max = currentLightSourceBucket.size(); + if (max > 0) { + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); + int offset = currentLightSourceBucketId * lightingBufferSliceLength; + if (lightSourceBucketSerials[currentLightSourceBucketId] != ser + || lightSourceRenderPosSerials[currentLightSourceBucketId] != currentRenderPosSerial) { + lightSourceBucketSerials[currentLightSourceBucketId] = ser; + lightSourceRenderPosSerials[currentLightSourceBucketId] = currentRenderPosSerial; + if (max > MAX_LIGHTS_PER_CHUNK) { + max = MAX_LIGHTS_PER_CHUNK; + } + chunkLightingDataCopyBuffer.clear(); + chunkLightingDataCopyBuffer.putInt(max); + chunkLightingDataCopyBuffer.putInt(0); // padding + chunkLightingDataCopyBuffer.putInt(0); // padding + chunkLightingDataCopyBuffer.putInt(0); // padding + for (int i = 0; i < max; ++i) { + DynamicLightInstance dl = currentLightSourceBucket.get(i); + chunkLightingDataCopyBuffer.putFloat((float) (dl.posX - currentRenderX)); + chunkLightingDataCopyBuffer.putFloat((float) (dl.posY - currentRenderY)); + chunkLightingDataCopyBuffer.putFloat((float) (dl.posZ - currentRenderZ)); + chunkLightingDataCopyBuffer.putInt(0); // padding + chunkLightingDataCopyBuffer.putFloat(dl.red); + chunkLightingDataCopyBuffer.putFloat(dl.green); + chunkLightingDataCopyBuffer.putFloat(dl.blue); + chunkLightingDataCopyBuffer.putInt(0); // padding + } + chunkLightingDataCopyBuffer.flip(); + _wglBufferSubData(_GL_UNIFORM_BUFFER, offset, chunkLightingDataCopyBuffer); + } + EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingData, offset, + LIGHTING_BUFFER_LENGTH); + } else { + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); + EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingDataZero, 0, + LIGHTING_BUFFER_LENGTH); + } + } else { + currentLightSourceBucketId = -1; + currentLightSourceBucket = null; + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); + EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingDataZero, 0, LIGHTING_BUFFER_LENGTH); + } + } + + public void bucketLightSource(float x, float y, float z, DynamicLightInstance dl) { + int bucketX = MathHelper.floor_float(x / 16.0f); + int bucketY = MathHelper.floor_float(y / 16.0f); + int bucketZ = MathHelper.floor_float(z / 16.0f); + addLightSourceToBucket(bucketX, bucketY, bucketZ, dl); + int minX = bucketX, maxX = bucketX; + int minY = bucketY, maxY = bucketY; + int minZ = bucketZ, maxZ = bucketZ; + float lightLocalX = x - (bucketX << 4); + float lightLocalY = y - (bucketY << 4); + float lightLocalZ = z - (bucketZ << 4); + float radius = dl.radius; + boolean outOfBounds = false; + if (lightLocalX - radius < 0.0f) { + minX -= 1; + outOfBounds = true; + addLightSourceToBucket(bucketX - 1, bucketY, bucketZ, dl); + } + if (lightLocalY - radius < 0.0f) { + minY -= 1; + outOfBounds = true; + addLightSourceToBucket(bucketX, bucketY - 1, bucketZ, dl); + } + if (lightLocalZ - radius < 0.0f) { + minZ -= 1; + outOfBounds = true; + addLightSourceToBucket(bucketX, bucketY, bucketZ - 1, dl); + } + if (lightLocalX + radius >= 16.0f) { + maxX += 1; + outOfBounds = true; + addLightSourceToBucket(bucketX + 1, bucketY, bucketZ, dl); + } + if (lightLocalY + radius >= 16.0f) { + maxY += 1; + outOfBounds = true; + addLightSourceToBucket(bucketX, bucketY + 1, bucketZ, dl); + } + if (lightLocalZ + radius >= 16.0f) { + maxZ += 1; + outOfBounds = true; + addLightSourceToBucket(bucketX, bucketY, bucketZ + 1, dl); + } + if (!outOfBounds) { + return; + } + radius *= radius; + for (int yy = minY; yy <= maxY; ++yy) { + for (int zz = minZ; zz <= maxZ; ++zz) { + for (int xx = minX; xx <= maxX; ++xx) { + if ((xx == bucketX ? 1 : 0) + (yy == bucketY ? 1 : 0) + (zz == bucketZ ? 1 : 0) > 1) { + continue; + } + List lst = getLightSourceBucketRelativeChunkCoords(xx, yy, zz); + if (lst != null) { + int bucketBoundsX = xx << 4; + int bucketBoundsY = yy << 4; + int bucketBoundsZ = zz << 4; + if (testAabSphere(bucketBoundsX, bucketBoundsY, bucketBoundsZ, bucketBoundsX + 16, + bucketBoundsY + 16, bucketBoundsZ + 16, x, y, z, radius)) { + lst.add(dl); + } + } + } + } + } + } public void combineGBuffersAndIlluminate() { DeferredStateManager.checkGLError("Pre: combineGBuffersAndIlluminate()"); @@ -1489,13 +1130,16 @@ public class EaglerDeferredPipeline { Matrix4f.invert(tmpMatrixViewProj, tmpMatrixInverseViewProj); Entity renderViewEntity = mc.getRenderViewEntity(); - if(renderViewEntity == null) { + if (renderViewEntity == null) { renderViewEntity = mc.thePlayer; } - double entityPosX = renderViewEntity.prevPosX + (renderViewEntity.posX - renderViewEntity.prevPosX) * partialTicks; - double entityPosY = renderViewEntity.prevPosY + (renderViewEntity.posY - renderViewEntity.prevPosY) * partialTicks; - double entityPosZ = renderViewEntity.prevPosZ + (renderViewEntity.posZ - renderViewEntity.prevPosZ) * partialTicks; + double entityPosX = renderViewEntity.prevPosX + + (renderViewEntity.posX - renderViewEntity.prevPosX) * partialTicks; + double entityPosY = renderViewEntity.prevPosY + + (renderViewEntity.posY - renderViewEntity.prevPosY) * partialTicks; + double entityPosZ = renderViewEntity.prevPosZ + + (renderViewEntity.posZ - renderViewEntity.prevPosZ) * partialTicks; int entityChunkOriginX = MathHelper.floor_double(entityPosX / 16.0) << 4; int entityChunkOriginY = MathHelper.floor_double(entityPosY / 16.0) << 4; int entityChunkOriginZ = MathHelper.floor_double(entityPosZ / 16.0) << 4; @@ -1509,15 +1153,15 @@ public class EaglerDeferredPipeline { // ==================== UPDATE CLOUD RENDERER ===================== // - if(dim == 0) { - CloudRenderWorker.setPosition(cloudRenderViewerOffsetX, (float)entityPosY, cloudRenderViewerOffsetZ); + if (dim == 0) { + CloudRenderWorker.setPosition(cloudRenderViewerOffsetX, (float) entityPosY, cloudRenderViewerOffsetZ); CloudRenderWorker.update(); DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): UPDATE CLOUD RENDERER"); } - if(millis - recalcAtmosphereTimer > 100l) { + if (millis - recalcAtmosphereTimer > 100l) { - if(dim == 0) { + if (dim == 0) { // =============== CALCULATE ATMOSPHERE COLORS ================ // @@ -1527,8 +1171,10 @@ public class EaglerDeferredPipeline { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(skybox.getNormalsLUT()); GlStateManager.viewport(0, 0, skybox.getAtmosLUTWidth(), skybox.getAtmosLUTHeight()); - _wglUniform4f(shader_skybox_atmosphere.uniforms.u_sunDirectionIntensity4f, -currentSunAngle.x, -currentSunAngle.y, -currentSunAngle.z, 5.0f); - _wglUniform1f(shader_skybox_atmosphere.uniforms.u_altitude1f, Math.max((float)(entityPosY - 85.0), -20.0f)); + _wglUniform4f(shader_skybox_atmosphere.uniforms.u_sunDirectionIntensity4f, -currentSunAngle.x, + -currentSunAngle.y, -currentSunAngle.z, 5.0f); + _wglUniform1f(shader_skybox_atmosphere.uniforms.u_altitude1f, + Math.max((float) (entityPosY - 85.0), -20.0f)); Vector3f sunColorTmp = tmpVector3; sunColorTmp.set(DeferredStateManager.currentSunLightColor); float luma = sunColorTmp.x * 0.299f + sunColorTmp.y * 0.587f + sunColorTmp.z * 0.114f; @@ -1537,7 +1183,8 @@ public class EaglerDeferredPipeline { sunColorTmp.y = (sunColorTmp.y - luma) * sat + luma; sunColorTmp.z = (sunColorTmp.z - luma) * sat + luma; sunColorTmp.scale(0.3f - ff2 * 0.175f); - _wglUniform4f(shader_skybox_atmosphere.uniforms.u_blendColor4f, sunColorTmp.x * 0.05f, sunColorTmp.y * 0.05f, sunColorTmp.z * 0.05f, fff); + _wglUniform4f(shader_skybox_atmosphere.uniforms.u_blendColor4f, sunColorTmp.x * 0.05f, + sunColorTmp.y * 0.05f, sunColorTmp.z * 0.05f, fff); DrawUtils.drawStandardQuad2D(); @@ -1552,45 +1199,52 @@ public class EaglerDeferredPipeline { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(atmosphereHDRFramebufferColorTexture); shader_skybox_render_paraboloid.useProgram(); - uniformMatrixHelper(shader_skybox_render_paraboloid.uniforms.u_viewMatrix4f, DeferredStateManager.paraboloidTopViewMatrix); + uniformMatrixHelper(shader_skybox_render_paraboloid.uniforms.u_viewMatrix4f, + DeferredStateManager.paraboloidTopViewMatrix); _wglUniform1f(shader_skybox_render_paraboloid.uniforms.u_farPlane1f, 2.0f); if (mc.theWorld.getLastLightningBolt() > 0) { float f = 0.3f + fff; - _wglUniform4f(shader_skybox_render_paraboloid.uniforms.u_lightningColor4f, 0.02f * f, 0.02f * f, 0.02f * f, 1.0f - f * 0.25f); - }else { + _wglUniform4f(shader_skybox_render_paraboloid.uniforms.u_lightningColor4f, 0.02f * f, 0.02f * f, + 0.02f * f, 1.0f - f * 0.25f); + } else { _wglUniform4f(shader_skybox_render_paraboloid.uniforms.u_lightningColor4f, 0.0f, 0.0f, 0.0f, 1.0f); } skybox.drawTop(); GlStateManager.viewport(0, 128, 128, 128); - uniformMatrixHelper(shader_skybox_render_paraboloid.uniforms.u_viewMatrix4f, DeferredStateManager.paraboloidBottomViewMatrix); + uniformMatrixHelper(shader_skybox_render_paraboloid.uniforms.u_viewMatrix4f, + DeferredStateManager.paraboloidBottomViewMatrix); skybox.drawBottom(); DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): GENERATE SKY REFLECTION MAP"); - - if(irradiancePhase++ % 10 == 0) { + if (irradiancePhase++ % 10 == 0) { // =============== GENERATE ATMOSPHERE REFLECTION MAP ================ // _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapAtmosphereFramebuffer); GlStateManager.viewport(0, 0, 128, 128); shader_skybox_render_paraboloid_noclouds.useProgram(); - uniformMatrixHelper(shader_skybox_render_paraboloid_noclouds.uniforms.u_viewMatrix4f, DeferredStateManager.paraboloidTopViewMatrix); + uniformMatrixHelper(shader_skybox_render_paraboloid_noclouds.uniforms.u_viewMatrix4f, + DeferredStateManager.paraboloidTopViewMatrix); _wglUniform1f(shader_skybox_render_paraboloid_noclouds.uniforms.u_farPlane1f, 2.0f); if (mc.theWorld.getLastLightningBolt() > 0) { float f = 0.3f + fff; - _wglUniform4f(shader_skybox_render_paraboloid_noclouds.uniforms.u_lightningColor4f, 0.02f * f, 0.02f * f, 0.02f * f, 1.0f - f * 0.25f); - }else { - _wglUniform4f(shader_skybox_render_paraboloid_noclouds.uniforms.u_lightningColor4f, 0.0f, 0.0f, 0.0f, 1.0f); + _wglUniform4f(shader_skybox_render_paraboloid_noclouds.uniforms.u_lightningColor4f, 0.02f * f, + 0.02f * f, 0.02f * f, 1.0f - f * 0.25f); + } else { + _wglUniform4f(shader_skybox_render_paraboloid_noclouds.uniforms.u_lightningColor4f, 0.0f, 0.0f, + 0.0f, 1.0f); } skybox.drawTop(); GlStateManager.viewport(0, 128, 128, 128); - uniformMatrixHelper(shader_skybox_render_paraboloid_noclouds.uniforms.u_viewMatrix4f, DeferredStateManager.paraboloidBottomViewMatrix); + uniformMatrixHelper(shader_skybox_render_paraboloid_noclouds.uniforms.u_viewMatrix4f, + DeferredStateManager.paraboloidBottomViewMatrix); skybox.drawBottom(); - DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): GENERATE ATMOSPHERE REFLECTION MAP"); + DeferredStateManager + .checkGLError("combineGBuffersAndIlluminate(): GENERATE ATMOSPHERE REFLECTION MAP"); // =============== GENERATE ATMOSPHERE IRRADIANCE MAP ================ // @@ -1612,9 +1266,10 @@ public class EaglerDeferredPipeline { GlStateManager.disableBlend(); - DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): GENERATE ATMOSPHERE IRRADIANCE MAP"); + DeferredStateManager + .checkGLError("combineGBuffersAndIlluminate(): GENERATE ATMOSPHERE IRRADIANCE MAP"); - }else { + } else { // =============== GENERATE SKY IRRADIANCE MAP ================ // @@ -1638,7 +1293,7 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): GENERATE SKY IRRADIANCE MAP"); } - }else if(dim == -1) { + } else if (dim == -1) { // =============== NETHER SKY REFLECTION MAP ================ // @@ -1656,7 +1311,7 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): NETHER SKY IRRADIANCE MAP"); - }else if(dim == 1) { + } else if (dim == 1) { // =============== END SKY REFLECTION MAP ================ // @@ -1678,7 +1333,7 @@ public class EaglerDeferredPipeline { } - if(reprojectionEngineEnable) { + if (reprojectionEngineEnable) { // ============ DOWNSCALE DEPTH BUFFER, FOR PERFORMANCE =========== // @@ -1690,15 +1345,17 @@ public class EaglerDeferredPipeline { GlStateManager.bindTexture(gBufferDepthTexture); _wglDrawBuffers(GL_NONE); GlStateManager.viewport(0, 0, reprojectionTexWidth, reprojectionTexHeight); - TextureCopyUtil.alignPixelsTopLeft(reprojectionTexWidth << 1, reprojectionTexHeight << 1, reprojectionTexWidth, reprojectionTexHeight); + TextureCopyUtil.alignPixelsTopLeft(reprojectionTexWidth << 1, reprojectionTexHeight << 1, + reprojectionTexWidth, reprojectionTexHeight); TextureCopyUtil.blitTextureDepth(); GlStateManager.disableDepth(); GlStateManager.depthMask(false); GlStateManager.depthFunc(GL_LEQUAL); - DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): DOWNSCALE DEPTH BUFFER, FOR PERFORMANCE"); + DeferredStateManager + .checkGLError("combineGBuffersAndIlluminate(): DOWNSCALE DEPTH BUFFER, FOR PERFORMANCE"); - if(config.is_rendering_ssao) { + if (config.is_rendering_ssao) { // ====================== RUN SSAO ALGORITHM ====================== // @@ -1711,13 +1368,19 @@ public class EaglerDeferredPipeline { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(gBufferQuarterDepthTexture); shader_ssao_generate.useProgram(); - uniformMatrixHelper(shader_ssao_generate.uniforms.u_projectionMatrix4f, DeferredStateManager.projMatrix); - uniformMatrixHelper(shader_ssao_generate.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_ssao_generate.uniforms.u_projectionMatrix4f, + DeferredStateManager.projMatrix); + uniformMatrixHelper(shader_ssao_generate.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); matrixCopyBuffer.clear(); - matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); - matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); - matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); - matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); + matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); + matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); + matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); + matrixCopyBuffer.put(((random.nextFloat() * 25.0f - 12.5f) + + (random.nextBoolean() ? 1.0f : -1.0f) * (random.nextFloat() * 6.0f + 6.0f)) * 10.0f); matrixCopyBuffer.flip(); _wglUniformMatrix2fv(shader_ssao_generate.uniforms.u_randomizerDataMatrix2f, false, matrixCopyBuffer); @@ -1731,45 +1394,46 @@ public class EaglerDeferredPipeline { // ============== RUN REPROJECTION CONTROL SHADER ================ // GlStateManager.setActiveTexture(GL_TEXTURE8); - if(config.is_rendering_raytracing) { + if (config.is_rendering_raytracing) { GlStateManager.bindTexture(gBufferMaterialTexture); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE7); - GlStateManager.bindTexture(lastFrameGBufferDepthTexture); // may be full of garbage data, let's pretend it won't + GlStateManager.bindTexture(lastFrameGBufferDepthTexture); // may be full of garbage data, let's pretend it + // won't GlStateManager.setActiveTexture(GL_TEXTURE6); - if(config.is_rendering_raytracing) { + if (config.is_rendering_raytracing) { GlStateManager.bindTexture(lastFrameColorTexture); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE5); - if(config.is_rendering_raytracing) { + if (config.is_rendering_raytracing) { GlStateManager.bindTexture(reprojectionSSRHitVector[1]); // may be garbage data - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE4); - if(config.is_rendering_raytracing) { + if (config.is_rendering_raytracing) { GlStateManager.bindTexture(reprojectionSSRTexture[1]); // may be garbage data - }else { + } else { GlStateManager.bindTexture(-1); } - + GlStateManager.setActiveTexture(GL_TEXTURE3); GlStateManager.bindTexture(gBufferNormalsTexture); GlStateManager.setActiveTexture(GL_TEXTURE2); - if(config.is_rendering_ssao) { + if (config.is_rendering_ssao) { GlStateManager.bindTexture(reprojectionControlSSAOTexture[1 - reprojectionPhase]); // may be garbage - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE1); - if(config.is_rendering_ssao) { + if (config.is_rendering_ssao) { GlStateManager.bindTexture(ssaoGenerateTexture); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE0); @@ -1783,12 +1447,16 @@ public class EaglerDeferredPipeline { Matrix4f.mul(DeferredStateManager.viewMatrix, tmpMatrix1, tmpMatrixViewReproject); Matrix4f.mul(tmpMatrixViewProj, tmpMatrix1, tmpMatrixViewProjReproject); Matrix4f.invert(tmpMatrixViewProjReproject, tmpMatrixInverseViewProjReproject); - - uniformMatrixHelper(shader_reproject_control.uniforms.u_inverseViewProjMatrix4f, tmpMatrixInverseViewProjReproject); - uniformMatrixHelper(shader_reproject_control.uniforms.u_reprojectionMatrix4f, tmpMatrixLastFrameViewProjReproject); - if(config.is_rendering_raytracing) { - uniformMatrixHelper(shader_reproject_control.uniforms.u_projectionMatrix4f, DeferredStateManager.projMatrix); - uniformMatrixHelper(shader_reproject_control.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + + uniformMatrixHelper(shader_reproject_control.uniforms.u_inverseViewProjMatrix4f, + tmpMatrixInverseViewProjReproject); + uniformMatrixHelper(shader_reproject_control.uniforms.u_reprojectionMatrix4f, + tmpMatrixLastFrameViewProjReproject); + if (config.is_rendering_raytracing) { + uniformMatrixHelper(shader_reproject_control.uniforms.u_projectionMatrix4f, + DeferredStateManager.projMatrix); + uniformMatrixHelper(shader_reproject_control.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); Matrix4f.invert(tmpMatrixLastFrameProj, tmpMatrix1); uniformMatrixHelper(shader_reproject_control.uniforms.u_lastInverseProjMatrix4f, tmpMatrix1); Matrix4f.invert(tmpMatrixLastFrameViewReproject, tmpMatrix1); @@ -1799,14 +1467,15 @@ public class EaglerDeferredPipeline { uniformMatrixHelper(shader_reproject_control.uniforms.u_viewToPreviousProjMatrix4f, tmpMatrix1); } _wglUniform4f(shader_reproject_control.uniforms.u_nearFarPlane4f, DeferredStateManager.gbufferNearPlane, - DeferredStateManager.gbufferFarPlane, DeferredStateManager.gbufferNearPlane * DeferredStateManager.gbufferFarPlane * 2.0f, + DeferredStateManager.gbufferFarPlane, + DeferredStateManager.gbufferNearPlane * DeferredStateManager.gbufferFarPlane * 2.0f, DeferredStateManager.gbufferFarPlane - DeferredStateManager.gbufferNearPlane); DrawUtils.drawStandardQuad2D(); DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RUN REPROJECTION CONTROL SHADER"); - if(config.is_rendering_raytracing) { + if (config.is_rendering_raytracing) { // =========== RUN SCREENSPACE REFLECTIONS ALGORITHM ============= // @@ -1826,7 +1495,8 @@ public class EaglerDeferredPipeline { _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionSSRFramebuffer[1]); shader_reproject_ssr.useProgram(); - uniformMatrixHelper(shader_reproject_ssr.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_reproject_ssr.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); Matrix4f.mul(tmpMatrixLastFrameViewProjReproject, tmpMatrixInverseViewProjReproject, tmpMatrix1); Matrix4f.mul(tmpMatrix1, DeferredStateManager.projMatrix, tmpMatrix1); uniformMatrixHelper(shader_reproject_ssr.uniforms.u_lastProjectionMatrix4f, tmpMatrix1); @@ -1841,7 +1511,8 @@ public class EaglerDeferredPipeline { matrixCopyBuffer.put(tmpMatrix1.m32); matrixCopyBuffer.put(tmpMatrix1.m33); matrixCopyBuffer.flip(); - _wglUniformMatrix4x2fv(shader_reproject_ssr.uniforms.u_lastInverseProjMatrix4x2f, false, matrixCopyBuffer); + _wglUniformMatrix4x2fv(shader_reproject_ssr.uniforms.u_lastInverseProjMatrix4x2f, false, + matrixCopyBuffer); _wglUniform1f(shader_reproject_ssr.uniforms.u_sampleStep1f, 0.125f); DrawUtils.drawStandardQuad2D(); // sample 1 @@ -1878,11 +1549,12 @@ public class EaglerDeferredPipeline { DrawUtils.drawStandardQuad2D(); // sample 5 - DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RUN SCREENSPACE REFLECTIONS ALGORITHM"); + DeferredStateManager + .checkGLError("combineGBuffersAndIlluminate(): RUN SCREENSPACE REFLECTIONS ALGORITHM"); } } - if(config.is_rendering_shadowsSun_clamped > 0) { + if (config.is_rendering_shadowsSun_clamped > 0) { // ==================== RENDER SUNLIGHT SHADOWS ===================== // @@ -1890,16 +1562,17 @@ public class EaglerDeferredPipeline { GlStateManager.viewport(0, 0, currentWidth, currentHeight); shader_shadows_sun.useProgram(); - uniformMatrixHelper(shader_shadows_sun.uniforms.u_inverseViewMatrix4f, DeferredStateManager.inverseViewMatrix); + uniformMatrixHelper(shader_shadows_sun.uniforms.u_inverseViewMatrix4f, + DeferredStateManager.inverseViewMatrix); uniformMatrixHelper(shader_shadows_sun.uniforms.u_inverseViewProjMatrix4f, tmpMatrixInverseViewProj); - if(config.is_rendering_shadowsColored) { + if (config.is_rendering_shadowsColored) { GlStateManager.setActiveTexture(GL_TEXTURE3); GlStateManager.bindTexture(sunShadowColorBuffer); } GlStateManager.setActiveTexture(GL_TEXTURE2); GlStateManager.bindTexture(sunShadowDepthBuffer); - if(config.is_rendering_shadowsSmoothed) { + if (config.is_rendering_shadowsSmoothed) { setLinear(); } GlStateManager.setActiveTexture(GL_TEXTURE1); @@ -1908,20 +1581,24 @@ public class EaglerDeferredPipeline { GlStateManager.bindTexture(gBufferNormalsTexture); Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix0, tmpShadowLOD0MatrixTexSpace); uniformMatrixHelper(shader_shadows_sun.uniforms.u_sunShadowMatrixLOD04f, tmpShadowLOD0MatrixTexSpace); - if(config.is_rendering_shadowsSun_clamped > 1) { - Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix1, tmpShadowLOD1MatrixTexSpace); + if (config.is_rendering_shadowsSun_clamped > 1) { + Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix1, + tmpShadowLOD1MatrixTexSpace); uniformMatrixHelper(shader_shadows_sun.uniforms.u_sunShadowMatrixLOD14f, tmpShadowLOD1MatrixTexSpace); - if(config.is_rendering_shadowsSun_clamped > 2) { - Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix2, tmpShadowLOD2MatrixTexSpace); - uniformMatrixHelper(shader_shadows_sun.uniforms.u_sunShadowMatrixLOD24f, tmpShadowLOD2MatrixTexSpace); + if (config.is_rendering_shadowsSun_clamped > 2) { + Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix2, + tmpShadowLOD2MatrixTexSpace); + uniformMatrixHelper(shader_shadows_sun.uniforms.u_sunShadowMatrixLOD24f, + tmpShadowLOD2MatrixTexSpace); } } Vector3f currentSunShadowAngle = DeferredStateManager.currentSunLightAngle; - _wglUniform3f(shader_shadows_sun.uniforms.u_sunDirection3f, -currentSunShadowAngle.x, -currentSunShadowAngle.y, -currentSunShadowAngle.z); + _wglUniform3f(shader_shadows_sun.uniforms.u_sunDirection3f, -currentSunShadowAngle.x, + -currentSunShadowAngle.y, -currentSunShadowAngle.z); DrawUtils.drawStandardQuad2D(); - if(config.is_rendering_shadowsSmoothed) { + if (config.is_rendering_shadowsSmoothed) { GlStateManager.setActiveTexture(GL_TEXTURE2); setNearest(); GlStateManager.setActiveTexture(GL_TEXTURE0); @@ -1935,13 +1612,14 @@ public class EaglerDeferredPipeline { GlStateManager.viewport(0, 0, currentWidth, currentHeight); _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, gBufferFramebuffer); _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, lightingHDRFramebuffer); - _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, + GL_NEAREST); _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - if(dim == -1) { + if (dim == -1) { float f = 0.13f; GlStateManager.clearColor(0.57f * 0.57f * f, 0.38f * 0.38f * f, 0.20f * 0.20f * f, 0.0f); - }else { + } else { GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); } GlStateManager.clear(GL_COLOR_BUFFER_BIT); @@ -1957,21 +1635,21 @@ public class EaglerDeferredPipeline { GlStateManager.setActiveTexture(GL_TEXTURE7); GlStateManager.bindTexture(skyIrradianceTexture); GlStateManager.setActiveTexture(GL_TEXTURE6); - if(config.is_rendering_useEnvMap) { + if (config.is_rendering_useEnvMap) { GlStateManager.bindTexture(envMapColorTexture); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE5); - if(config.is_rendering_raytracing) { + if (config.is_rendering_raytracing) { GlStateManager.bindTexture(reprojectionSSRTexture[1]); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE4); - if(config.is_rendering_ssao) { + if (config.is_rendering_ssao) { GlStateManager.bindTexture(reprojectionControlSSAOTexture[reprojectionPhase]); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE3); @@ -1984,12 +1662,16 @@ public class EaglerDeferredPipeline { GlStateManager.bindTexture(gBufferDiffuseTexture); shader_deferred_combine.useProgram(); - uniformMatrixHelper(shader_deferred_combine.uniforms.u_inverseViewMatrix4f, DeferredStateManager.inverseViewMatrix); - uniformMatrixHelper(shader_deferred_combine.uniforms.u_inverseProjMatrix4f, DeferredStateManager.inverseProjMatrix); - _wglUniform3f(shader_deferred_combine.uniforms.u_sunDirection3f, DeferredStateManager.currentSunAngle.x, DeferredStateManager.currentSunAngle.y, DeferredStateManager.currentSunAngle.z); + uniformMatrixHelper(shader_deferred_combine.uniforms.u_inverseViewMatrix4f, + DeferredStateManager.inverseViewMatrix); + uniformMatrixHelper(shader_deferred_combine.uniforms.u_inverseProjMatrix4f, + DeferredStateManager.inverseProjMatrix); + _wglUniform3f(shader_deferred_combine.uniforms.u_sunDirection3f, DeferredStateManager.currentSunAngle.x, + DeferredStateManager.currentSunAngle.y, DeferredStateManager.currentSunAngle.z); float lightningBoost = mc.theWorld.getLastLightningBolt() > 0 ? 1.0f : 0.0f; lightningBoost *= 0.3f + fff; - _wglUniform1f(shader_deferred_combine.uniforms.u_skyLightFactor1f, getSkyBrightnessTimeParam() + lightningBoost); + _wglUniform1f(shader_deferred_combine.uniforms.u_skyLightFactor1f, + getSkyBrightnessTimeParam() + lightningBoost); DrawUtils.drawStandardQuad2D(); DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RENDER AMBIENT LIGHTING"); @@ -2001,77 +1683,85 @@ public class EaglerDeferredPipeline { // ==================== RENDER SUNLIGHT ===================== // - if(dim == 0) { + if (dim == 0) { shader_lighting_sun.useProgram(); - uniformMatrixHelper(shader_lighting_sun.uniforms.u_inverseViewMatrix4f, DeferredStateManager.inverseViewMatrix); - uniformMatrixHelper(shader_lighting_sun.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_lighting_sun.uniforms.u_inverseViewMatrix4f, + DeferredStateManager.inverseViewMatrix); + uniformMatrixHelper(shader_lighting_sun.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); GlStateManager.setActiveTexture(GL_TEXTURE5); GlStateManager.bindTexture(MetalsLUT.getGLTexture()); GlStateManager.setActiveTexture(GL_TEXTURE4); - if(config.is_rendering_shadowsSun_clamped > 0) { + if (config.is_rendering_shadowsSun_clamped > 0) { GlStateManager.bindTexture(sunLightingShadowTexture); - }else { + } else { GlStateManager.bindTexture(-1); } GlStateManager.setActiveTexture(GL_TEXTURE0); - + float ffff = getSkyBrightnessParam(); float[] sunRGB; - if(currentSunAngle.y < 0.05f) { - sunRGB = TemperaturesLUT.getColorTemperature((int)sunKelvin); + if (currentSunAngle.y < 0.05f) { + sunRGB = TemperaturesLUT.getColorTemperature((int) sunKelvin); Vector3f currentSunLightColor3f = DeferredStateManager.currentSunLightColor; // reuse variable currentSunLightColor3f.x = sunRGB[0] * 8.0f * (0.1f + ffff * 0.9f); currentSunLightColor3f.y = sunRGB[1] * 8.0f * (0.1f + ffff * 0.9f); currentSunLightColor3f.z = sunRGB[2] * 8.0f * (0.1f + ffff * 0.9f); - _wglUniform3f(shader_lighting_sun.uniforms.u_sunColor3f, sunRGB[0] * 4.0f * ffff, sunRGB[1] * 4.0f * ffff, sunRGB[2] * 4.0f * ffff); - }else { - sunRGB = TemperaturesLUT.getColorTemperature((int)(9000.0f + 2500.0f * currentSunAngle.y)); + _wglUniform3f(shader_lighting_sun.uniforms.u_sunColor3f, sunRGB[0] * 4.0f * ffff, + sunRGB[1] * 4.0f * ffff, sunRGB[2] * 4.0f * ffff); + } else { + sunRGB = TemperaturesLUT.getColorTemperature((int) (9000.0f + 2500.0f * currentSunAngle.y)); Vector3f currentSunLightColor3f = DeferredStateManager.currentSunLightColor; // reuse variable currentSunLightColor3f.x = sunRGB[0] * 0.3f * (0.2f + ffff * 0.8f); currentSunLightColor3f.y = sunRGB[1] * 0.3f * (0.2f + ffff * 0.8f); currentSunLightColor3f.z = sunRGB[2] * 0.3f * (0.2f + ffff * 0.8f); - _wglUniform3f(shader_lighting_sun.uniforms.u_sunColor3f, sunRGB[0] * 0.1f * (0.5f + ffff * 0.5f), sunRGB[1] * 0.1f * (0.5f + ffff * 0.5f), sunRGB[2] * 0.1f * (0.5f + ffff * 0.5f)); + _wglUniform3f(shader_lighting_sun.uniforms.u_sunColor3f, sunRGB[0] * 0.1f * (0.5f + ffff * 0.5f), + sunRGB[1] * 0.1f * (0.5f + ffff * 0.5f), sunRGB[2] * 0.1f * (0.5f + ffff * 0.5f)); } - - _wglUniform3f(shader_lighting_sun.uniforms.u_sunDirection3f, -DeferredStateManager.currentSunLightAngle.x, -DeferredStateManager.currentSunLightAngle.y, -DeferredStateManager.currentSunLightAngle.z); - + + _wglUniform3f(shader_lighting_sun.uniforms.u_sunDirection3f, -DeferredStateManager.currentSunLightAngle.x, + -DeferredStateManager.currentSunLightAngle.y, -DeferredStateManager.currentSunLightAngle.z); + DrawUtils.drawStandardQuad2D(); - + DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RENDER SUNLIGHT"); - }else { + } else { DeferredStateManager.currentSunLightColor.set(0.0f, 0.0f, 0.0f); } // ================== RENDER DYNAMIC LIGHTS =================== // - if(config.is_rendering_dynamicLights) { + if (config.is_rendering_dynamicLights) { shader_lighting_point.useProgram(); - uniformMatrixHelper(shader_lighting_point.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); - uniformMatrixHelper(shader_lighting_point.uniforms.u_inverseViewMatrix4f, DeferredStateManager.inverseViewMatrix); + uniformMatrixHelper(shader_lighting_point.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_lighting_point.uniforms.u_inverseViewMatrix4f, + DeferredStateManager.inverseViewMatrix); _wglUniform2f(shader_lighting_point.uniforms.u_viewportSize2f, 1.0f / currentWidth, 1.0f / currentHeight); Iterator itr = DynamicLightManager.lightRenderList.iterator(); AxisAlignedBB aabb = renderViewEntity.getEntityBoundingBox(); double eyeHeight = renderViewEntity.getEyeHeight(); - while(itr.hasNext()) { + while (itr.hasNext()) { DynamicLightInstance dl = itr.next(); - float lightPosX = (float)(dl.posX - entityPosX); - float lightPosY = (float)(dl.posY - entityPosY); - float lightPosZ = (float)(dl.posZ - entityPosZ); - float lightChunkPosX = (float)(dl.posX - entityChunkOriginX); - float lightChunkPosY = (float)(dl.posY - entityChunkOriginY); - float lightChunkPosZ = (float)(dl.posZ - entityChunkOriginZ); + float lightPosX = (float) (dl.posX - entityPosX); + float lightPosY = (float) (dl.posY - entityPosY); + float lightPosZ = (float) (dl.posZ - entityPosZ); + float lightChunkPosX = (float) (dl.posX - entityChunkOriginX); + float lightChunkPosY = (float) (dl.posY - entityChunkOriginY); + float lightChunkPosZ = (float) (dl.posZ - entityChunkOriginZ); bucketLightSource(lightChunkPosX, lightChunkPosY, lightChunkPosZ, dl); - if(dl.posX > aabb.minX - 0.25 && dl.posY > aabb.minY + eyeHeight - 0.25 && dl.posZ > aabb.minZ - 0.25 && - dl.posX < aabb.maxX + 0.25 && dl.posY < aabb.minY + eyeHeight + 0.25 && dl.posZ < aabb.maxZ + 0.25) { + if (dl.posX > aabb.minX - 0.25 && dl.posY > aabb.minY + eyeHeight - 0.25 && dl.posZ > aabb.minZ - 0.25 + && dl.posX < aabb.maxX + 0.25 && dl.posY < aabb.minY + eyeHeight + 0.25 + && dl.posZ < aabb.maxZ + 0.25) { tmpMatrix1.setIdentity(); uniformMatrixHelper(shader_lighting_point.uniforms.u_modelViewProjMatrix4f, tmpMatrix1); _wglUniform3f(shader_lighting_point.uniforms.u_lightColor3f, dl.red, dl.green, dl.blue); _wglUniform3f(shader_lighting_point.uniforms.u_lightPosition3f, lightPosX, lightPosY, lightPosZ); DrawUtils.drawStandardQuad3D(); - }else { + } else { float radius = dl.radius; tmpVector1.set(lightPosX, lightPosY, lightPosZ); - if(DeferredStateManager.currentGBufferFrustum.testSphere(tmpVector1, radius)) { + if (DeferredStateManager.currentGBufferFrustum.testSphere(tmpVector1, radius)) { tmpMatrix1.setIdentity(); Matrix4f.translate(tmpVector1, tmpMatrix1, tmpMatrix1); tmpVector1.set(radius, radius, radius); @@ -2079,7 +1769,8 @@ public class EaglerDeferredPipeline { Matrix4f.mul(tmpMatrixViewProj, tmpMatrix1, tmpMatrix1); uniformMatrixHelper(shader_lighting_point.uniforms.u_modelViewProjMatrix4f, tmpMatrix1); _wglUniform3f(shader_lighting_point.uniforms.u_lightColor3f, dl.red, dl.green, dl.blue); - _wglUniform3f(shader_lighting_point.uniforms.u_lightPosition3f, lightPosX, lightPosY, lightPosZ); + _wglUniform3f(shader_lighting_point.uniforms.u_lightPosition3f, lightPosX, lightPosY, + lightPosZ); pointLightMesh.drawMeshVAO(); } } @@ -2096,13 +1787,14 @@ public class EaglerDeferredPipeline { GlStateManager.disableBlend(); - if(reprojectionEngineEnable || config.is_rendering_realisticWater) { + if (reprojectionEngineEnable || config.is_rendering_realisticWater) { // =========== SAVE REPROJECTION DATA FOR NEXT FRAME ============= // _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, lightingHDRFramebuffer); _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, lastFrameGBufferFramebuffer); - _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, + GL_DEPTH_BUFFER_BIT, GL_NEAREST); DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): SAVE REPROJECTION DATA FOR NEXT FRAME"); } @@ -2111,7 +1803,7 @@ public class EaglerDeferredPipeline { // =================== RENDER SKYBOX MESH =================== // - if(dim == 0) { + if (dim == 0) { GlStateManager.enableDepth(); GlStateManager.setActiveTexture(GL_TEXTURE2); GlStateManager.bindTexture(CloudRenderWorker.cloudOcclusionTexture); @@ -2122,26 +1814,29 @@ public class EaglerDeferredPipeline { shader_skybox_render.useProgram(); uniformMatrixHelper(shader_skybox_render.uniforms.u_viewMatrix4f, DeferredStateManager.viewMatrix); uniformMatrixHelper(shader_skybox_render.uniforms.u_projMatrix4f, DeferredStateManager.projMatrix); - _wglUniform3f(shader_skybox_render.uniforms.u_sunDirection3f, -currentSunAngle.x, -currentSunAngle.y, -currentSunAngle.z); + _wglUniform3f(shader_skybox_render.uniforms.u_sunDirection3f, -currentSunAngle.x, -currentSunAngle.y, + -currentSunAngle.z); float mag = 25.0f; - float[] sunRGB2 = TemperaturesLUT.getColorTemperature((int)sunKelvin - 1000); - _wglUniform3f(shader_skybox_render.uniforms.u_sunColor3f, sunRGB2[0] * mag, sunRGB2[1] * mag, sunRGB2[2] * mag); + float[] sunRGB2 = TemperaturesLUT.getColorTemperature((int) sunKelvin - 1000); + _wglUniform3f(shader_skybox_render.uniforms.u_sunColor3f, sunRGB2[0] * mag, sunRGB2[1] * mag, + sunRGB2[2] * mag); if (mc.theWorld.getLastLightningBolt() > 0) { float f = 0.3f + fff; - _wglUniform4f(shader_skybox_render.uniforms.u_lightningColor4f, 0.02f * f, 0.02f * f, 0.02f * f, 1.0f - f * 0.25f); - }else { + _wglUniform4f(shader_skybox_render.uniforms.u_lightningColor4f, 0.02f * f, 0.02f * f, 0.02f * f, + 1.0f - f * 0.25f); + } else { _wglUniform4f(shader_skybox_render.uniforms.u_lightningColor4f, 0.0f, 0.0f, 0.0f, 1.0f); } skybox.drawFull(); - + DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RENDER SKYBOX MESH"); - }else if(dim == 1) { + } else if (dim == 1) { GlStateManager.enableDepth(); GlStateManager.setActiveTexture(GL_TEXTURE0); mc.getTextureManager().bindTexture(locationEndSkyPng); - if(shader_skybox_render_end == null) { + if (shader_skybox_render_end == null) { shader_skybox_render_end = PipelineShaderSkyboxRenderEnd.compile(); shader_skybox_render_end.loadUniforms(); } @@ -2156,7 +1851,7 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RENDER SKYBOX MESH"); } - if(dim == 0 && fff < 1.0f) { + if (dim == 0 && fff < 1.0f) { // ===================== RENDER MOON ====================== // @@ -2183,22 +1878,22 @@ public class EaglerDeferredPipeline { moonMatrix.m21 = tmpVector4.y; moonMatrix.m22 = tmpVector4.z; Matrix4f.mul(moonMatrix, tmpMatrix2, moonMatrix); - + GlStateManager.bindTexture(moonTextures); shader_moon_render.useProgram(); - + uniformMatrixHelper(shader_moon_render.uniforms.u_modelMatrix4f, moonMatrix); uniformMatrixHelper(shader_moon_render.uniforms.u_viewMatrix4f, DeferredStateManager.viewMatrix); uniformMatrixHelper(shader_moon_render.uniforms.u_projMatrix4f, DeferredStateManager.projMatrix); float fffff = 0.1f + MathHelper.clamp_float((-currentSunAngle.y + 0.1f) * 8.0f, 0.0f, 0.5f); _wglUniform3f(shader_moon_render.uniforms.u_moonColor3f, 1.4f * fffff, 1.2f * fffff, 1.0f * fffff); - - float f = (float)(Minecraft.getMinecraft().theWorld.getWorldTime() - 18000f) / 24000f / 4f * 3.14159f; + + float f = (float) (Minecraft.getMinecraft().theWorld.getWorldTime() - 18000f) / 24000f / 4f * 3.14159f; _wglUniform3f(shader_moon_render.uniforms.u_lightDir3f, MathHelper.sin(f), 0.0f, MathHelper.cos(f)); - + GlStateManager.enableBlend(); GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE, GL_ZERO, GL_ZERO); - + DrawUtils.drawStandardQuad2D(); DeferredStateManager.checkGLError("combineGBuffersAndIlluminate(): RENDER MOON"); @@ -2209,289 +1904,873 @@ public class EaglerDeferredPipeline { GlStateManager.disableBlend(); } - public void bindLightSourceBucket(int relativeBlockX, int relativeBlockY, int relativeBlockZ, int uboIndex) { - int hw = lightSourceBucketsWidth / 2; - int hh = lightSourceBucketsHeight / 2; - int bucketX = (relativeBlockX >> 4) + hw; - int bucketY = (relativeBlockY >> 4) + hh; - int bucketZ = (relativeBlockZ >> 4) + hw; - if(bucketX >= 0 && bucketY >= 0 && bucketZ >= 0 && bucketX < lightSourceBucketsWidth - && bucketY < lightSourceBucketsHeight && bucketZ < lightSourceBucketsWidth) { - currentLightSourceBucketId = bucketY * lightSourceBucketsWidth * lightSourceBucketsWidth - + bucketZ * lightSourceBucketsWidth + bucketX; - currentLightSourceBucket = lightSourceBuckets[currentLightSourceBucketId]; - int ser = currentLightSourceBucket.getEaglerSerial(); - int max = currentLightSourceBucket.size(); - if(max > 0) { - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); - int offset = currentLightSourceBucketId * lightingBufferSliceLength; - if (lightSourceBucketSerials[currentLightSourceBucketId] != ser - || lightSourceRenderPosSerials[currentLightSourceBucketId] != currentRenderPosSerial) { - lightSourceBucketSerials[currentLightSourceBucketId] = ser; - lightSourceRenderPosSerials[currentLightSourceBucketId] = currentRenderPosSerial; - if(max > MAX_LIGHTS_PER_CHUNK) { - max = MAX_LIGHTS_PER_CHUNK; - } - chunkLightingDataCopyBuffer.clear(); - chunkLightingDataCopyBuffer.putInt(max); - chunkLightingDataCopyBuffer.putInt(0); //padding - chunkLightingDataCopyBuffer.putInt(0); //padding - chunkLightingDataCopyBuffer.putInt(0); //padding - for(int i = 0; i < max; ++i) { - DynamicLightInstance dl = currentLightSourceBucket.get(i); - chunkLightingDataCopyBuffer.putFloat((float)(dl.posX - currentRenderX)); - chunkLightingDataCopyBuffer.putFloat((float)(dl.posY - currentRenderY)); - chunkLightingDataCopyBuffer.putFloat((float)(dl.posZ - currentRenderZ)); - chunkLightingDataCopyBuffer.putInt(0); //padding - chunkLightingDataCopyBuffer.putFloat(dl.red); - chunkLightingDataCopyBuffer.putFloat(dl.green); - chunkLightingDataCopyBuffer.putFloat(dl.blue); - chunkLightingDataCopyBuffer.putInt(0); //padding - } - chunkLightingDataCopyBuffer.flip(); - _wglBufferSubData(_GL_UNIFORM_BUFFER, offset, chunkLightingDataCopyBuffer); - } - EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingData, offset, LIGHTING_BUFFER_LENGTH); - }else { - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); - EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingDataZero, 0, LIGHTING_BUFFER_LENGTH); + public void destroy() { + DeferredStateManager.checkGLError("Pre: destroy()"); + if (gBufferFramebuffer != null) { + _wglDeleteFramebuffer(gBufferFramebuffer); + gBufferFramebuffer = null; + } + if (gBufferDiffuseTexture != -1) { + GlStateManager.bindTexture(gBufferDiffuseTexture); + gBufferDiffuseTexture = -1; + } + if (gBufferNormalsTexture != -1) { + GlStateManager.bindTexture(gBufferNormalsTexture); + gBufferNormalsTexture = -1; + } + if (gBufferMaterialTexture != -1) { + GlStateManager.bindTexture(gBufferMaterialTexture); + gBufferMaterialTexture = -1; + } + if (gBufferDepthTexture != -1) { + GlStateManager.bindTexture(gBufferDepthTexture); + gBufferDepthTexture = -1; + } + if (sunShadowFramebuffer != null) { + _wglDeleteFramebuffer(sunShadowFramebuffer); + sunShadowFramebuffer = null; + } + if (sunShadowDepthBuffer != -1) { + GlStateManager.deleteTexture(sunShadowDepthBuffer); + sunShadowDepthBuffer = -1; + } + if (sunLightingShadowFramebuffer != null) { + _wglDeleteFramebuffer(sunLightingShadowFramebuffer); + sunLightingShadowFramebuffer = null; + } + if (sunLightingShadowTexture != -1) { + GlStateManager.deleteTexture(sunLightingShadowTexture); + sunLightingShadowTexture = -1; + } + if (ssaoGenerateFramebuffer != null) { + _wglDeleteFramebuffer(ssaoGenerateFramebuffer); + ssaoGenerateFramebuffer = null; + } + if (ssaoGenerateTexture != -1) { + GlStateManager.deleteTexture(ssaoGenerateTexture); + ssaoGenerateTexture = -1; + reprojectionTexWidth = -1; + reprojectionTexHeight = -1; + } + if (shader_ssao_generate != null) { + shader_ssao_generate.destroy(); + shader_ssao_generate = null; + } + if (ssaoNoiseTexture != -1) { + GlStateManager.deleteTexture(ssaoNoiseTexture); + ssaoNoiseTexture = -1; + } + for (int i = 0; i < 2; ++i) { + if (reprojectionControlFramebuffer[i] != null) { + _wglDeleteFramebuffer(reprojectionControlFramebuffer[i]); + reprojectionControlFramebuffer[i] = null; } - }else { - currentLightSourceBucketId = -1; - currentLightSourceBucket = null; - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); - EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingDataZero, 0, LIGHTING_BUFFER_LENGTH); - } - } - - public ListSerial getLightSourceBucketRelativeChunkCoords(int cx, int cy, int cz) { - int hw = lightSourceBucketsWidth / 2; - int hh = lightSourceBucketsHeight / 2; - cx += hw; - cy += hh; - cz += hw; - if(cx < 0 || cx >= lightSourceBucketsWidth || cy < 0 || cy >= lightSourceBucketsHeight || cz < 0 - || cz >= lightSourceBucketsWidth) { - return null; - }else { - return lightSourceBuckets[cy * lightSourceBucketsWidth * lightSourceBucketsWidth - + cz * lightSourceBucketsWidth + cx]; - } - } - - public void addLightSourceToBucket(int cx, int cy, int cz, DynamicLightInstance dl) { - ListSerial lst = getLightSourceBucketRelativeChunkCoords(cx, cy, cz); - if(lst != null) { - lst.add(dl); - } - } - - public void bucketLightSource(float x, float y, float z, DynamicLightInstance dl) { - int bucketX = MathHelper.floor_float(x / 16.0f); - int bucketY = MathHelper.floor_float(y / 16.0f); - int bucketZ = MathHelper.floor_float(z / 16.0f); - addLightSourceToBucket(bucketX, bucketY, bucketZ, dl); - int minX = bucketX, maxX = bucketX; - int minY = bucketY, maxY = bucketY; - int minZ = bucketZ, maxZ = bucketZ; - float lightLocalX = x - (bucketX << 4); - float lightLocalY = y - (bucketY << 4); - float lightLocalZ = z - (bucketZ << 4); - float radius = dl.radius; - boolean outOfBounds = false; - if(lightLocalX - radius < 0.0f) { - minX -= 1; - outOfBounds = true; - addLightSourceToBucket(bucketX - 1, bucketY, bucketZ, dl); - } - if(lightLocalY - radius < 0.0f) { - minY -= 1; - outOfBounds = true; - addLightSourceToBucket(bucketX, bucketY - 1, bucketZ, dl); - } - if(lightLocalZ - radius < 0.0f) { - minZ -= 1; - outOfBounds = true; - addLightSourceToBucket(bucketX, bucketY, bucketZ - 1, dl); - } - if(lightLocalX + radius >= 16.0f) { - maxX += 1; - outOfBounds = true; - addLightSourceToBucket(bucketX + 1, bucketY, bucketZ, dl); - } - if(lightLocalY + radius >= 16.0f) { - maxY += 1; - outOfBounds = true; - addLightSourceToBucket(bucketX, bucketY + 1, bucketZ, dl); - } - if(lightLocalZ + radius >= 16.0f) { - maxZ += 1; - outOfBounds = true; - addLightSourceToBucket(bucketX, bucketY, bucketZ + 1, dl); - } - if(!outOfBounds) { - return; - } - radius *= radius; - for(int yy = minY; yy <= maxY; ++yy) { - for(int zz = minZ; zz <= maxZ; ++zz) { - for(int xx = minX; xx <= maxX; ++xx) { - if((xx == bucketX ? 1 : 0) + (yy == bucketY ? 1 : 0) + (zz == bucketZ ? 1 : 0) > 1) { - continue; - } - List lst = getLightSourceBucketRelativeChunkCoords(xx, yy, zz); - if(lst != null) { - int bucketBoundsX = xx << 4; - int bucketBoundsY = yy << 4; - int bucketBoundsZ = zz << 4; - if(testAabSphere(bucketBoundsX, bucketBoundsY, bucketBoundsZ, bucketBoundsX + 16, bucketBoundsY + 16, bucketBoundsZ + 16, x, y, z, radius)) { - lst.add(dl); - } - } - } + if (reprojectionControlSSAOTexture[i] != -1) { + GlStateManager.deleteTexture(reprojectionControlSSAOTexture[i]); + reprojectionControlSSAOTexture[i] = -1; + } + if (reprojectionSSRFramebuffer[i] != null) { + _wglDeleteFramebuffer(reprojectionSSRFramebuffer[i]); + reprojectionSSRFramebuffer[i] = null; + } + if (reprojectionSSRTexture[i] != -1) { + GlStateManager.deleteTexture(reprojectionSSRTexture[i]); + reprojectionSSRTexture[i] = -1; + } + if (reprojectionSSRHitVector[i] != -1) { + GlStateManager.deleteTexture(reprojectionSSRHitVector[i]); + reprojectionSSRHitVector[i] = -1; } } - } - - /** - * source: https://github.com/JOML-CI/JOML/blob/main/src/main/java/org/joml/Intersectionf.java - */ - public static boolean testAabSphere(float minX, float minY, float minZ, float maxX, float maxY, float maxZ, - float centerX, float centerY, float centerZ, float radius2) { - if (centerX < minX) { - float d = (centerX - minX); - radius2 -= d * d; - } else if (centerX > maxX) { - float d = (centerX - maxX); - radius2 -= d * d; + if (lastFrameFramebuffer != null) { + _wglDeleteFramebuffer(lastFrameFramebuffer); + lastFrameFramebuffer = null; } - if (centerY < minY) { - float d = (centerY - minY); - radius2 -= d * d; - } else if (centerY > maxY) { - float d = (centerY - maxY); - radius2 -= d * d; + if (lastFrameColorTexture != -1) { + GlStateManager.deleteTexture(lastFrameColorTexture); + lastFrameColorTexture = -1; } - if (centerZ < minZ) { - float d = (centerZ - minZ); - radius2 -= d * d; - } else if (centerZ > maxZ) { - float d = (centerZ - maxZ); - radius2 -= d * d; + if (lastFrameDepthTexture != -1) { + GlStateManager.deleteTexture(lastFrameDepthTexture); + lastFrameDepthTexture = -1; } - return radius2 >= 0.0f; - } - - private void truncateOverflowingLightBuffers() { - for(int i = 0; i < this.lightSourceBuckets.length; ++i) { - List lst = this.lightSourceBuckets[i]; - int k = lst.size(); - if(k > MAX_LIGHTS_PER_CHUNK) { - lst.sort(comparatorLightRadius); - for(int l = MAX_LIGHTS_PER_CHUNK - 1; l >= MAX_LIGHTS_PER_CHUNK; --l) { - lst.remove(l); - } + if (gBufferQuarterFramebuffer != null) { + _wglDeleteFramebuffer(gBufferQuarterFramebuffer); + gBufferQuarterFramebuffer = null; + } + if (gBufferQuarterDepthTexture != -1) { + GlStateManager.deleteTexture(gBufferQuarterDepthTexture); + gBufferQuarterDepthTexture = -1; + } + if (lastFrameGBufferFramebuffer != null) { + _wglDeleteFramebuffer(lastFrameGBufferFramebuffer); + lastFrameGBufferFramebuffer = null; + } + if (lastFrameGBufferDepthTexture != -1) { + GlStateManager.deleteTexture(lastFrameGBufferDepthTexture); + lastFrameGBufferDepthTexture = -1; + } + if (lightingHDRFramebuffer != null) { + _wglDeleteFramebuffer(lightingHDRFramebuffer); + lightingHDRFramebuffer = null; + } + if (lightingHDRFramebufferColorTexture != -1) { + GlStateManager.deleteTexture(lightingHDRFramebufferColorTexture); + lightingHDRFramebufferColorTexture = -1; + } + if (lightingHDRFramebufferDepthTexture != -1) { + GlStateManager.deleteTexture(lightingHDRFramebufferDepthTexture); + lightingHDRFramebufferDepthTexture = -1; + } + if (handRenderFramebuffer != null) { + _wglDeleteFramebuffer(handRenderFramebuffer); + handRenderFramebuffer = null; + } + if (handRenderFramebufferDepthTexture != -1) { + GlStateManager.deleteTexture(handRenderFramebufferDepthTexture); + handRenderFramebufferDepthTexture = -1; + } + if (atmosphereHDRFramebuffer != null) { + _wglDeleteFramebuffer(atmosphereHDRFramebuffer); + atmosphereHDRFramebuffer = null; + } + if (atmosphereHDRFramebufferColorTexture != -1) { + GlStateManager.deleteTexture(atmosphereHDRFramebufferColorTexture); + atmosphereHDRFramebufferColorTexture = -1; + } + if (envMapAtmosphereFramebuffer != null) { + _wglDeleteFramebuffer(envMapAtmosphereFramebuffer); + envMapAtmosphereFramebuffer = null; + } + if (envMapAtmosphereTexture != -1) { + GlStateManager.deleteTexture(envMapAtmosphereTexture); + envMapAtmosphereTexture = -1; + } + if (envMapSkyFramebuffer != null) { + _wglDeleteFramebuffer(envMapSkyFramebuffer); + envMapSkyFramebuffer = null; + } + if (envMapSkyTexture != -1) { + GlStateManager.deleteTexture(envMapSkyTexture); + envMapSkyTexture = -1; + } + if (moonTextures != -1) { + GlStateManager.deleteTexture(moonTextures); + moonTextures = -1; + } + if (envMapFramebuffer != null) { + _wglDeleteFramebuffer(envMapFramebuffer); + envMapFramebuffer = null; + } + if (envMapColorTexture != -1) { + GlStateManager.deleteTexture(envMapColorTexture); + envMapColorTexture = -1; + } + if (envMapDepthTexture != -1) { + GlStateManager.deleteTexture(envMapDepthTexture); + envMapDepthTexture = -1; + } + if (atmosphereIrradianceFramebuffer != null) { + _wglDeleteFramebuffer(atmosphereIrradianceFramebuffer); + atmosphereIrradianceFramebuffer = null; + } + if (atmosphereIrradianceTexture != -1) { + GlStateManager.deleteTexture(atmosphereIrradianceTexture); + atmosphereIrradianceTexture = -1; + } + if (skyIrradianceFramebuffer != null) { + _wglDeleteFramebuffer(skyIrradianceFramebuffer); + skyIrradianceFramebuffer = null; + } + if (skyIrradianceTexture != -1) { + GlStateManager.deleteTexture(skyIrradianceTexture); + skyIrradianceTexture = -1; + } + if (tonemapOutputFramebuffer != null) { + _wglDeleteFramebuffer(tonemapOutputFramebuffer); + tonemapOutputFramebuffer = null; + } + if (tonemapOutputTexture != -1) { + GlStateManager.deleteTexture(tonemapOutputTexture); + tonemapOutputTexture = -1; + } + if (lensDistortFramebuffer != null) { + _wglDeleteFramebuffer(lensDistortFramebuffer); + lensDistortFramebuffer = null; + } + if (lensDistortTexture != -1) { + GlStateManager.deleteTexture(lensDistortTexture); + lensDistortTexture = -1; + } + if (lumaAvgDownscaleFramebuffers != null) { + for (int i = 0; i < lumaAvgDownscaleFramebuffers.length; ++i) { + _wglDeleteFramebuffer(lumaAvgDownscaleFramebuffers[i]); + } + lumaAvgDownscaleFramebuffers = null; + } + if (lumaAvgDownscaleTexture != null) { + for (int i = 0; i < lumaAvgDownscaleTexture.length; ++i) { + GlStateManager.deleteTexture(lumaAvgDownscaleTexture[i]); + } + lumaAvgDownscaleTexture = null; + } + if (exposureBlendFramebuffer != null) { + _wglDeleteFramebuffer(exposureBlendFramebuffer); + exposureBlendFramebuffer = null; + } + if (exposureBlendTexture != -1) { + GlStateManager.deleteTexture(exposureBlendTexture); + exposureBlendTexture = -1; + } + if (bloomBrightPassFramebuffer != null) { + _wglDeleteFramebuffer(bloomBrightPassFramebuffer); + bloomBrightPassFramebuffer = null; + } + if (bloomBrightPassTexture != -1) { + GlStateManager.bindTexture(bloomBrightPassTexture); + bloomBrightPassTexture = -1; + } + if (bloomHBlurFramebuffer != null) { + _wglDeleteFramebuffer(bloomHBlurFramebuffer); + bloomHBlurFramebuffer = null; + } + if (bloomHBlurTexture != -1) { + GlStateManager.deleteTexture(bloomHBlurTexture); + bloomHBlurTexture = -1; + } + if (bloomVBlurFramebuffer != null) { + _wglDeleteFramebuffer(bloomVBlurFramebuffer); + bloomVBlurFramebuffer = null; + } + if (bloomVBlurTexture != -1) { + GlStateManager.deleteTexture(bloomVBlurTexture); + bloomVBlurTexture = -1; + } + if (bloomDownscaleAFramebuffer != null) { + _wglDeleteFramebuffer(bloomDownscaleAFramebuffer); + bloomDownscaleAFramebuffer = null; + } + if (bloomDownscaleATexture != -1) { + GlStateManager.deleteTexture(bloomDownscaleATexture); + bloomDownscaleATexture = -1; + } + if (bloomDownscaleBFramebuffer != null) { + _wglDeleteFramebuffer(bloomDownscaleBFramebuffer); + bloomDownscaleBFramebuffer = null; + } + if (bloomDownscaleBTexture != -1) { + GlStateManager.deleteTexture(bloomDownscaleBTexture); + bloomDownscaleBTexture = -1; + } + if (sunOcclusionValueFramebuffer != null) { + _wglDeleteFramebuffer(sunOcclusionValueFramebuffer); + sunOcclusionValueFramebuffer = null; + } + if (sunOcclusionValueTexture != -1) { + GlStateManager.deleteTexture(sunOcclusionValueTexture); + sunOcclusionValueTexture = -1; + } + if (dither8x8Texture != -1) { + GlStateManager.deleteTexture(dither8x8Texture); + dither8x8Texture = -1; + } + if (shader_deferred_combine != null) { + shader_deferred_combine.destroy(); + shader_deferred_combine = null; + } + if (shader_hand_depth_mask != null) { + shader_hand_depth_mask.destroy(); + shader_hand_depth_mask = null; + } + if (brdfTexture != -1) { + GlStateManager.deleteTexture(brdfTexture); + brdfTexture = -1; + } + if (shader_lighting_sun != null) { + shader_lighting_sun.destroy(); + shader_lighting_sun = null; + } + if (shader_shadows_sun != null) { + shader_shadows_sun.destroy(); + shader_shadows_sun = null; + } + if (shader_light_shafts_sample != null) { + shader_light_shafts_sample.destroy(); + shader_light_shafts_sample = null; + } + if (skybox != null) { + skybox.destroy(); + skybox = null; + } + if (pointLightMesh != null) { + pointLightMesh.destroy(); + pointLightMesh = null; + } + if (shader_skybox_atmosphere != null) { + shader_skybox_atmosphere.destroy(); + shader_skybox_atmosphere = null; + } + if (shader_skybox_render != null) { + shader_skybox_render.destroy(); + shader_skybox_render = null; + } + if (shader_lighting_point != null) { + shader_lighting_point.destroy(); + shader_lighting_point = null; + } + if (shader_post_lens_distort != null) { + shader_post_lens_distort.destroy(); + shader_post_lens_distort = null; + } + if (shader_post_tonemap != null) { + shader_post_tonemap.destroy(); + shader_post_tonemap = null; + } + if (shader_post_exposure_avg != null) { + shader_post_exposure_avg.destroy(); + shader_post_exposure_avg = null; + } + if (shader_post_exposure_avg_luma != null) { + shader_post_exposure_avg_luma.destroy(); + shader_post_exposure_avg_luma = null; + } + if (shader_post_exposure_final != null) { + shader_post_exposure_final.destroy(); + shader_post_exposure_final = null; + } + if (shader_post_bloom_bright != null) { + shader_post_bloom_bright.destroy(); + shader_post_bloom_bright = null; + } + if (shader_post_bloom_blur != null) { + shader_post_bloom_blur.destroy(); + shader_post_bloom_blur = null; + } + if (shader_lens_sun_occlusion != null) { + shader_lens_sun_occlusion.destroy(); + shader_lens_sun_occlusion = null; + } + if (shader_realistic_water_control != null) { + shader_realistic_water_control.destroy(); + shader_realistic_water_control = null; + } + if (shader_realistic_water_noise != null) { + shader_realistic_water_noise.destroy(); + shader_realistic_water_noise = null; + } + if (shader_realistic_water_normals != null) { + shader_realistic_water_normals.destroy(); + shader_realistic_water_normals = null; + } + if (shader_post_fxaa != null) { + shader_post_fxaa.destroy(); + shader_post_fxaa = null; + } + if (shader_skybox_render_paraboloid != null) { + shader_skybox_render_paraboloid.destroy(); + shader_skybox_render_paraboloid = null; + } + if (shader_skybox_render_paraboloid_noclouds != null) { + shader_skybox_render_paraboloid_noclouds.destroy(); + shader_skybox_render_paraboloid_noclouds = null; + } + if (shader_skybox_render_end != null) { + shader_skybox_render_end.destroy(); + shader_skybox_render_end = null; + } + for (int i = 0; i < 3; ++i) { + if (shader_skybox_irradiance[i] != null) { + shader_skybox_irradiance[i].destroy(); + shader_skybox_irradiance[i] = null; } } - } - - private static final Comparator comparatorLightRadius = (l1, l2) -> { - return l1.radius < l2.radius ? 1 : -1; - }; - - public void beginDrawEnvMap() { - DeferredStateManager.checkGLError("Pre: beginDrawEnvMap()"); - GlStateManager.enableDepth(); - GlStateManager.depthMask(true); - DeferredStateManager.enableForwardRender(); - DeferredStateManager.enableParaboloidRender(); - DeferredStateManager.disableFog(); - GlStateManager.enableExtensionPipeline(); - updateForwardRenderWorldLightingData(); - EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); - EaglercraftGPU.bindUniformBufferRange(0, buffer_worldLightingData, 0, worldLightingDataCopyBuffer.remaining()); - if(config.is_rendering_dynamicLights) { - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); - EaglercraftGPU.bindUniformBufferRange(1, buffer_chunkLightingData, 0, chunkLightingDataCopyBuffer.capacity()); + if (shader_colored_fog_linear != null) { + shader_colored_fog_linear.destroy(); + shader_colored_fog_linear = null; } - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.pushMatrix(); - GlStateManager.loadIdentity(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.pushMatrix(); - GlStateManager.loadIdentity(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapFramebuffer); - GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GlStateManager.setActiveTexture(GL_TEXTURE10); - GlStateManager.bindTexture(skyIrradianceTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); - DeferredStateManager.checkGLError("Post: beginDrawEnvMap()"); + if (shader_colored_fog_exp != null) { + shader_colored_fog_exp.destroy(); + shader_colored_fog_exp = null; + } + if (shader_atmosphere_fog != null) { + shader_atmosphere_fog.destroy(); + shader_atmosphere_fog = null; + } + if (shader_moon_render != null) { + shader_moon_render.destroy(); + shader_moon_render = null; + } + if (shader_reproject_control != null) { + shader_reproject_control.destroy(); + shader_reproject_control = null; + } + if (shader_reproject_ssr != null) { + shader_reproject_ssr.destroy(); + shader_reproject_ssr = null; + } + if (realisticWaterMaskFramebuffer != null) { + _wglDeleteFramebuffer(realisticWaterMaskFramebuffer); + realisticWaterMaskFramebuffer = null; + } + if (realisticWaterMaskTexture != -1) { + GlStateManager.deleteTexture(realisticWaterMaskTexture); + realisticWaterMaskTexture = -1; + } + if (realisticWaterDepthBuffer != -1) { + GlStateManager.deleteTexture(realisticWaterDepthBuffer); + realisticWaterDepthBuffer = -1; + } + if (realisticWaterCombinedNormalsFramebuffer != null) { + _wglDeleteFramebuffer(realisticWaterCombinedNormalsFramebuffer); + realisticWaterCombinedNormalsFramebuffer = null; + } + if (realisticWaterCombinedNormalsTexture != -1) { + GlStateManager.deleteTexture(realisticWaterCombinedNormalsTexture); + realisticWaterCombinedNormalsTexture = -1; + } + if (realisticWaterRefractionTexture != -1) { + GlStateManager.deleteTexture(realisticWaterRefractionTexture); + realisticWaterRefractionTexture = -1; + } + if (realisticWaterControlFramebuffer != null) { + _wglDeleteFramebuffer(realisticWaterControlFramebuffer); + realisticWaterControlFramebuffer = null; + } + for (int i = 0; i < 2; ++i) { + if (realisticWaterSSRFramebuffer[i] != null) { + _wglDeleteFramebuffer(realisticWaterSSRFramebuffer[i]); + realisticWaterSSRFramebuffer[i] = null; + } + if (realisticWaterControlReflectionTexture[i] != -1) { + GlStateManager.deleteTexture(realisticWaterControlReflectionTexture[i]); + realisticWaterControlReflectionTexture[i] = -1; + } + if (realisticWaterControlHitVectorTexture[i] != -1) { + GlStateManager.deleteTexture(realisticWaterControlHitVectorTexture[i]); + realisticWaterControlHitVectorTexture[i] = -1; + } + } + if (realisticWaterNormalMapFramebuffer != null) { + _wglDeleteFramebuffer(realisticWaterNormalMapFramebuffer); + realisticWaterNormalMapFramebuffer = null; + } + if (realisticWaterNormalMapTexture != -1) { + GlStateManager.deleteTexture(realisticWaterNormalMapTexture); + realisticWaterNormalMapTexture = -1; + } + if (realisticWaterDisplacementMapFramebuffer != null) { + _wglDeleteFramebuffer(realisticWaterDisplacementMapFramebuffer); + realisticWaterDisplacementMapFramebuffer = null; + } + if (realisticWaterDisplacementMapTexture != -1) { + GlStateManager.deleteTexture(realisticWaterDisplacementMapTexture); + realisticWaterDisplacementMapTexture = -1; + } + if (realisticWaterNoiseMap != -1) { + GlStateManager.deleteTexture(realisticWaterNoiseMap); + realisticWaterNoiseMap = -1; + } + if (buffer_chunkLightingData != null) { + _wglDeleteBuffers(buffer_chunkLightingData); + buffer_chunkLightingData = null; + } + if (buffer_chunkLightingDataZero != null) { + _wglDeleteBuffers(buffer_chunkLightingDataZero); + buffer_chunkLightingDataZero = null; + } + if (buffer_worldLightingData != null) { + _wglDeleteBuffers(buffer_worldLightingData); + buffer_worldLightingData = null; + } + if (worldLightingDataCopyBuffer != null) { + EagRuntime.freeByteBuffer(worldLightingDataCopyBuffer); + worldLightingDataCopyBuffer = null; + } + if (chunkLightingDataCopyBuffer != null) { + EagRuntime.freeByteBuffer(chunkLightingDataCopyBuffer); + chunkLightingDataCopyBuffer = null; + } + for (int i = 0; i < lightSourceBuckets.length; ++i) { + lightSourceBuckets[i].clear(); + lightSourceBucketSerials[i] = -1; + lightSourceRenderPosSerials[i] = -1; + } + currentLightSourceBucket = null; + currentLightSourceBucketId = -1; + currentBoundLightSourceBucket = null; + isChunkLightingEnabled = false; + for (int i = 0; i < shader_gbuffer_debug_view.length; ++i) { + if (shader_gbuffer_debug_view[i] != null) { + shader_gbuffer_debug_view[i].destroy(); + shader_gbuffer_debug_view[i] = null; + } + } + gbufferEffectRenderer.destroy(); + forwardEffectRenderer.destroy(); + DynamicLightManager.destroyAll(); + LensFlareMeshRenderer.destroy(); + CloudRenderWorker.destroy(); + FixedFunctionPipeline.loadExtensionPipeline(null); + DeferredStateManager.checkGLError("Post: destroy()"); } - public void beginDrawEnvMapTop(float eyeHeight) { - DeferredStateManager.checkGLError("Pre: beginDrawEnvMapTop()"); - GlStateManager.loadIdentity(); - tmpMatrix1.setIdentity(); - tmpMatrix1.m32 = eyeHeight; - Matrix4f.mul(tmpMatrix1, DeferredStateManager.paraboloidTopViewMatrix, tmpMatrix1); - GlStateManager.getModelViewReference().load(tmpMatrix1); - DeferredStateManager.passProjMatrix.setIdentity(); - DeferredStateManager.passInverseProjMatrix.setIdentity(); - ++DeferredStateManager.passProjMatrixSerial; - DeferredStateManager.passViewMatrix.load(tmpMatrix1); - Matrix4f.invert(DeferredStateManager.passViewMatrix, DeferredStateManager.passInverseViewMatrix); - ++DeferredStateManager.passViewMatrixSerial; - GlStateManager.viewport(0, 0, 128, 128); - DeferredStateManager.checkGLError("Post: beginDrawEnvMapTop()"); + private void drawDebugViewIfEnabled() { + if (DebugFramebufferView.debugViewShown) { + DebugFramebufferView.renderDebugView(); + } } - public void beginDrawEnvMapSolid() { - DeferredStateManager.checkGLError("Pre: beginDrawEnvMapSolid()"); + public void endDrawColoredShadows() { + DeferredStateManager.checkGLError("Pre: endDrawColoredShadows()"); + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowFramebuffer); + DeferredStateManager.disableForwardRender(); GlStateManager.disableBlend(); - bindEnvMapBlockTexture(); - DeferredStateManager.checkGLError("Post: beginDrawEnvMapSolid()"); + GlStateManager.globalDisableBlend(); + GlStateManager.depthMask(true); + GlStateManager.disablePolygonOffset(); + GlStateManager.colorMask(false, false, false, false); + DeferredStateManager.checkGLError("Post: endDrawColoredShadows()"); } - public void beginDrawEnvMapTranslucent() { - DeferredStateManager.checkGLError("Pre: beginDrawEnvMapTranslucent()"); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA, GL_ONE); - bindEnvMapBlockTexture(); - DeferredStateManager.checkGLError("Post: beginDrawEnvMapTranslucent()"); - } + public void endDrawDeferred() { + DeferredStateManager.checkGLError("Pre: endDrawDeferred()"); - private void bindEnvMapBlockTexture() { - DeferredStateManager.checkGLError("Pre: bindEnvMapBlockTexture()"); - GlStateManager.setActiveTexture(GL_TEXTURE4); - if(config.is_rendering_shadowsSun_clamped > 0) { - GlStateManager.bindTexture(sunShadowDepthBuffer); - }else { - GlStateManager.bindTexture(-1); + if (config.is_rendering_lensFlares && mc.theWorld.provider.getDimensionId() == 0 + && DeferredStateManager.currentSunAngle.y < 0.2f && mc.theWorld.getRainStrength(partialTicks) < 1.0f) { + + // =============== CALCULATE SUN COORDINATES ================ // + + tmpVector2.x = DeferredStateManager.currentSunAngle.x * 10.0f; + tmpVector2.y = DeferredStateManager.currentSunAngle.y * 10.0f; + tmpVector2.z = DeferredStateManager.currentSunAngle.z * 10.0f; + tmpVector2.w = 1.0f; + + Matrix4f.transform(tmpMatrixViewProj, tmpVector2, tmpVector2); + + tmpVector2.z /= tmpVector2.w; + float margin = 0.2f; + if (tmpVector2.z <= -1.0f) { + tmpVector2.x = DeferredStateManager.currentSunAngle.x * 10.0f; + tmpVector2.y = DeferredStateManager.currentSunAngle.y * 10.0f; + tmpVector2.z = DeferredStateManager.currentSunAngle.z * 10.0f; + tmpVector2.w = 0.0f; + Matrix4f.transform(tmpMatrixViewProj, tmpVector2, tmpVector2); + tmpVector2.x /= tmpVector2.w; + tmpVector2.y /= tmpVector2.w; + if (tmpVector2.x < 1.0f + margin && tmpVector2.x > -1.0f - margin && tmpVector2.y < 1.0f + margin + && tmpVector2.y > -1.0f - margin) { + + // ============ CALCULATE DEPTH SUN OCCLUSION ============ // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunOcclusionValueFramebuffer); + GlStateManager.viewport(0, 0, 1, 1); + + GlStateManager.setActiveTexture(GL_TEXTURE1); + GlStateManager.bindTexture(CloudRenderWorker.cloudOcclusionTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); + + float fov = 90.0f / mc.entityRenderer.getFOVModifier(partialTicks, true); + float radius = 0.05f * fov; + float aspectRatio = (float) currentHeight / (float) currentWidth; + + tmpMatrix3.setIdentity(); + tmpMatrix3.m00 = aspectRatio * radius; + tmpMatrix3.m11 = radius; + tmpMatrix3.m20 = tmpVector2.x * 0.5f + 0.5f; + tmpMatrix3.m21 = tmpVector2.y * 0.5f + 0.5f; + + shader_lens_sun_occlusion.useProgram(); + + uniformMatrixHelper(shader_lens_sun_occlusion.uniforms.u_sampleMatrix3f, tmpMatrix3); + + DrawUtils.drawStandardQuad2D(); + + DeferredStateManager.checkGLError("endDrawDeferred(): CALCULATE DEPTH SUN OCCLUSION"); + + // ============ RENDER SUN LENS FLARES MESHES ============ // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + + LensFlareMeshRenderer.drawLensFlares(tmpVector2.x, tmpVector2.y); + + DeferredStateManager.checkGLError("endDrawDeferred(): RENDER SUN LENS FLARES MESHES"); + } + } } - TextureManager mgr = mc.getTextureManager(); - GlStateManager.setActiveTexture(GL_TEXTURE10); - GlStateManager.bindTexture(skyIrradianceTexture); - GlStateManager.setActiveTexture(GL_TEXTURE3); - GlStateManager.bindTexture(MetalsLUT.getGLTexture()); - GlStateManager.setActiveTexture(GL_TEXTURE0); - mgr.bindTexture(TextureMap.locationBlocksTexture); - GlStateManager.enableCull(); - DeferredStateManager.checkGLError("Post: bindEnvMapBlockTexture()"); - } - public void beginDrawEnvMapBottom(float eyeHeight) { - DeferredStateManager.checkGLError("Pre: beginDrawEnvMapBottom()"); - GlStateManager.loadIdentity(); - tmpMatrix1.setIdentity(); - tmpMatrix1.m32 = -eyeHeight; - Matrix4f.mul(tmpMatrix1, DeferredStateManager.paraboloidBottomViewMatrix, tmpMatrix1); - GlStateManager.getModelViewReference().load(tmpMatrix1); - DeferredStateManager.passViewMatrix.load(tmpMatrix1); - Matrix4f.invert(DeferredStateManager.passViewMatrix, DeferredStateManager.passInverseViewMatrix); - ++DeferredStateManager.passViewMatrixSerial; - GlStateManager.viewport(0, 128, 128, 128); - DeferredStateManager.checkGLError("Post: beginDrawEnvMapBottom()"); + // ================ DOWNSCALE AND AVERAGE LUMA =============== // + + long millis = EagRuntime.steadyTimeMillis(); + if (millis - lastExposureUpdate > 33l) { + if (lumaAvgDownscaleFramebuffers.length == 0) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, exposureBlendFramebuffer); + GlStateManager.clearColor(1.0f, 1.0f, 1.0f, 1.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT); + } else { + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + setLinear(); + + int iw = currentWidth; + int ih = currentHeight; + int iw2 = 0, ih2 = 0, iw3 = 0, ih3 = 0; + for (int i = 0; i < lumaAvgDownscaleFramebuffers.length; ++i) { + iw2 = iw >> 2; + ih2 = ih >> 2; + // cheap way to round up: + iw3 = ((iw & 3) != 0) ? (iw2 + 1) : iw2; + ih3 = ((ih & 3) != 0) ? (ih2 + 1) : ih2; + _wglBindFramebuffer(_GL_FRAMEBUFFER, lumaAvgDownscaleFramebuffers[i]); + + if (i == 0) { + shader_post_exposure_avg_luma.useProgram(); + _wglUniform4f(shader_post_exposure_avg_luma.uniforms.u_sampleOffset4f, 1.0f / iw3, 1.0f / ih3, + 4.0f / iw, 4.0f / ih); + } else { + shader_post_exposure_avg.useProgram(); + GlStateManager.bindTexture(lumaAvgDownscaleTexture[i - 1]); + _wglUniform4f(shader_post_exposure_avg.uniforms.u_sampleOffset4f, 1.0f / iw3, 1.0f / ih3, + 4.0f / iw, 4.0f / ih); + } + + GlStateManager.viewport(0, 0, iw3, ih3); + + DrawUtils.drawStandardQuad2D(); + + iw = iw2; + ih = ih2; + } + + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + setNearest(); + + _wglBindFramebuffer(_GL_FRAMEBUFFER, exposureBlendFramebuffer); + GlStateManager.viewport(0, 0, 1, 1); + + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); + + GlStateManager.setBlendConstants(0.0f, 0.0f, 0.0f, + Math.min((float) ((millis - lastExposureUpdate) * 0.001), 1.0f)); + + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lumaAvgDownscaleTexture[lumaAvgDownscaleTexture.length - 1]); + + shader_post_exposure_final.useProgram(); + _wglUniform2f(shader_post_exposure_final.uniforms.u_inputSize2f, 1.0f / iw3, 1.0f / ih3); + + DrawUtils.drawStandardQuad2D(); + + GlStateManager.disableBlend(); + + lastExposureUpdate = millis; + } + + DeferredStateManager.checkGLError("endDrawDeferred(): DOWNSCALE AND AVERAGE LUMA"); + } + + if (config.is_rendering_bloom) { + + // ==================== BLOOM: BRIGHT PASS ==================== // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomBrightPassFramebuffer); + GlStateManager.viewport(0, 0, bloomBrightPassTextureW, bloomBrightPassTextureH); + boolean flag = bloomBrightPassTextureW != currentWidth || bloomBrightPassTextureH != currentHeight; + GlStateManager.setActiveTexture(GL_TEXTURE3); + GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); + GlStateManager.setActiveTexture(GL_TEXTURE2); + GlStateManager.bindTexture(gBufferMaterialTexture); + if (flag) { + setLinear(); + } + GlStateManager.setActiveTexture(GL_TEXTURE1); + GlStateManager.bindTexture(exposureBlendTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + if (flag) { + setLinear(); + } + shader_post_bloom_bright.useProgram(); + _wglUniform4f(shader_post_bloom_bright.uniforms.u_outputSize4f, bloomBrightPassTextureW, + bloomBrightPassTextureH, (flag ? 2.0f : 1.0f) / currentWidth, (flag ? 2.0f : 1.0f) / currentHeight); + DrawUtils.drawStandardQuad2D(); + if (flag) { + setNearest(); + GlStateManager.setActiveTexture(GL_TEXTURE2); + setNearest(); + GlStateManager.setActiveTexture(GL_TEXTURE0); + } + + DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: BRIGHT PASS"); + + // ==================== BLOOM: DOWNSCALE A ==================== // + + int bloomStageW = bloomBrightPassTextureW; + int bloomStageH = bloomBrightPassTextureH; + int texx = bloomBrightPassTexture; + if (bloomStageW > 300 && bloomStageH > 170) { + bloomStageW >>= 1; + bloomStageH >>= 1; + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleAFramebuffer); + GlStateManager.viewport(0, 0, bloomStageW, bloomStageH); + GlStateManager.bindTexture(texx); + texx = bloomDownscaleATexture; + TextureCopyUtil.alignPixels(bloomStageW, bloomStageH, 0.5f, 0.5f); + TextureCopyUtil.blitTexture(); + + DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: DOWNSCALE A"); + + if (bloomStageW > 300 && bloomStageH > 170) { + + // ==================== BLOOM: DOWNSCALE B ==================== // + + bloomStageW >>= 1; + bloomStageH >>= 1; + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleBFramebuffer); + GlStateManager.viewport(0, 0, bloomStageW, bloomStageH); + GlStateManager.bindTexture(texx); + texx = bloomDownscaleBTexture; + TextureCopyUtil.alignPixels(bloomStageW, bloomStageH, 0.5f, 0.5f); + TextureCopyUtil.blitTexture(); + + DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: DOWNSCALE B"); + } + } + + // ===================== BLOOM: HORZ BLUR ===================== // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomHBlurFramebuffer); + GlStateManager.viewport(0, 0, bloomBlurTextureW, bloomBlurTextureH); + flag = bloomBrightPassTextureW != bloomBlurTextureW || bloomBrightPassTextureH != bloomBlurTextureH; + GlStateManager.bindTexture(texx); + shader_post_bloom_blur.useProgram(); + _wglUniform2f(shader_post_bloom_blur.uniforms.u_sampleOffset2f, (flag ? 2.0f : 1.0f) / bloomStageW, 0.0f); + _wglUniform4f(shader_post_bloom_blur.uniforms.u_outputSize4f, bloomBlurTextureW, bloomBlurTextureH, + (flag ? 2.0f : 1.0f) / bloomStageW, (flag ? 2.0f : 1.0f) / bloomStageH); + DrawUtils.drawStandardQuad2D(); + + DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: HORZ BLUR"); + + // ===================== BLOOM: VERT BLUR ===================== // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomVBlurFramebuffer); + GlStateManager.bindTexture(bloomHBlurTexture); + shader_post_bloom_blur.useProgram(); + _wglUniform2f(shader_post_bloom_blur.uniforms.u_sampleOffset2f, 0.0f, 1.0f / bloomBlurTextureH); + _wglUniform4f(shader_post_bloom_blur.uniforms.u_outputSize4f, bloomBlurTextureW, bloomBlurTextureH, + 1.0f / bloomBlurTextureW, 1.0f / bloomBlurTextureH); + DrawUtils.drawStandardQuad2D(); + + DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: VERT BLUR"); + + // ======================== BLOOM: MIX ======================= // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + GlStateManager.bindTexture(bloomVBlurTexture); + GlStateManager.enableBlend(); + GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE, GL_ZERO, GL_ONE); + GlStateManager.setBlendConstants(0.0f, 0.0f, 0.0f, 0.15f); + TextureCopyUtil.blitTexture(); + GlStateManager.disableBlend(); + + DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: MIX"); + } + + // ==================== APPLY TONEMAPPING ==================== // + + float exposure = 1.0f; + + if (config.is_rendering_fxaa) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, tonemapOutputFramebuffer); + } else { + if (config.is_rendering_lensDistortion) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, lensDistortFramebuffer); + } else { + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + } + } + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + shader_post_tonemap.useProgram(); + GlStateManager.disableBlend(); + GlStateManager.setActiveTexture(GL_TEXTURE2); + GlStateManager.bindTexture(dither8x8Texture); + GlStateManager.setActiveTexture(GL_TEXTURE1); + GlStateManager.bindTexture(exposureBlendTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + _wglUniform3f(shader_post_tonemap.uniforms.u_exposure3f, exposure, exposure, exposure); + _wglUniform2f(shader_post_tonemap.uniforms.u_ditherScale2f, currentWidth / 8.0f, currentHeight / 8.0f); + DrawUtils.drawStandardQuad2D(); + GlStateManager.setActiveTexture(GL_TEXTURE2); + GlStateManager.bindTexture(-1); + GlStateManager.setActiveTexture(GL_TEXTURE0); + + DeferredStateManager.checkGLError("endDrawDeferred(): APPLY TONEMAPPING"); + + if (config.is_rendering_fxaa) { + + // ======================= APPLY FXAA ======================== // + + if (config.is_rendering_lensDistortion) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, lensDistortFramebuffer); + } else { + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + } + shader_post_fxaa.useProgram(); + GlStateManager.bindTexture(tonemapOutputTexture); + _wglUniform2f(shader_post_fxaa.uniforms.u_screenSize2f, 1.0f / currentWidth, 1.0f / currentHeight); + DrawUtils.drawStandardQuad2D(); + + DeferredStateManager.checkGLError("endDrawDeferred(): APPLY FXAA"); + } + + if (config.is_rendering_lensDistortion) { + + // ================= APPLY LENS DISTORTION ================== // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lensDistortTexture); + shader_post_lens_distort.useProgram(); + DrawUtils.drawStandardQuad2D(); + + DeferredStateManager.checkGLError("endDrawDeferred(): APPLY LENS DISTORTION"); + } + + // =========== BLIT WORLD DEPTH BUFFER TO OUTPUT ============= // + + if (EagRuntime.getPlatformType() == EnumPlatformType.DESKTOP) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + GlStateManager.enableDepth(); + GlStateManager.depthFunc(GL_ALWAYS); + GlStateManager.depthMask(true); + GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); + TextureCopyUtil.blitTextureDepth(); + GlStateManager.disableDepth(); + GlStateManager.depthFunc(GL_LEQUAL); + GlStateManager.depthMask(false); + } else { + _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, lightingHDRFramebuffer); + _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, null); + _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, + GL_DEPTH_BUFFER_BIT, GL_NEAREST); + } + + DeferredStateManager.checkGLError("endDrawDeferred(): BLIT WORLD DEPTH BUFFER TO OUTPUT"); + + // ================= OPTIONAL DEBUG OUTPUT =================== // + + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + drawDebugViewIfEnabled(); + + for (int i = 0; i < lightSourceBuckets.length; ++i) { + lightSourceBuckets[i].clear(); + } + + DeferredStateManager.checkGLError("endDrawDeferred(): OPTIONAL DEBUG OUTPUT"); } public void endDrawEnvMap() { @@ -2510,96 +2789,62 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("Post: endDrawEnvMap()"); } - private void updateForwardRenderWorldLightingData() { - worldLightingDataCopyBuffer.clear(); - worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunLightAngle.x); - worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunLightAngle.y); - worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunLightAngle.z); - worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunAngle.y); - float f = getSkyBrightnessParam(); - if(DeferredStateManager.currentSunAngle.y > 0.05f) { // moon: - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.x * 0.025f * f); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.y * 0.025f * f); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.z * 0.025f * f); - }else { - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.x * f); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.y * f); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.z * f); - } - float lightningBoost = mc.theWorld.getLastLightningBolt() > 0 ? 1.0f : 0.0f; - lightningBoost *= 0.3f + mc.theWorld.getRainStrength(partialTicks); - worldLightingDataCopyBuffer.putFloat(getSkyBrightnessTimeParam() + lightningBoost); - worldLightingDataCopyBuffer.putFloat((float)DeferredStateManager.fogLinearExp); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogDensity); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogNear); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogFar); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkR); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkG); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkB); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkA); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightR); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightG); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightB); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightA); - float mul = 0.05f * MathHelper.clamp_float(-1.0f - DeferredStateManager.getSunHeight() * 20.0f, 0.0f, 1.0f) + 0.01f; - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.x * mul); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.y * mul); - worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.z * mul); - worldLightingDataCopyBuffer.putInt(0); - worldLightingDataCopyBuffer.putFloat(1.0f); - worldLightingDataCopyBuffer.putFloat(1.0f); - worldLightingDataCopyBuffer.putFloat(1.0f); - worldLightingDataCopyBuffer.putFloat(1.0f); - if(config.is_rendering_shadowsSun_clamped > 0) { - tmpShadowLOD0MatrixTexSpace.store(worldLightingDataCopyBuffer); - if(config.is_rendering_shadowsSun_clamped > 1) { - tmpShadowLOD1MatrixTexSpace.store(worldLightingDataCopyBuffer); - if(config.is_rendering_shadowsSun_clamped > 2) { - tmpShadowLOD2MatrixTexSpace.store(worldLightingDataCopyBuffer); - } - } - } - worldLightingDataCopyBuffer.flip(); - EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); - _wglBufferSubData(_GL_UNIFORM_BUFFER, 0, worldLightingDataCopyBuffer); - } - - public void setForwardRenderLightFactors(float block, float sky, float sun, float dynamic) { - worldLightingDataCopyBuffer.clear(); - worldLightingDataCopyBuffer.putFloat(block); - worldLightingDataCopyBuffer.putFloat(sky); - worldLightingDataCopyBuffer.putFloat(sun); - worldLightingDataCopyBuffer.putFloat(dynamic); - worldLightingDataCopyBuffer.flip(); - EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); - _wglBufferSubData(_GL_UNIFORM_BUFFER, 96, worldLightingDataCopyBuffer); - } - - private float getSkyBrightnessParam() { - float fff = mc.theWorld.getRainStrength(partialTicks) * 0.9f; - fff += mc.theWorld.getThunderStrength(partialTicks) * 0.05f; - return 1.0f - fff; - } - - private float getSkyBrightnessTimeParam() { - return (2.0f + MathHelper.clamp_float(-DeferredStateManager.currentSunAngle.y * 8.0f, 0.0f, 1.5f)) * getSkyBrightnessParam(); - } - - public void beginDrawRealisticWaterMask() { - DeferredStateManager.checkGLError("Pre: beginDrawRealisticWaterMask()"); - _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, gBufferFramebuffer); - _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, realisticWaterMaskFramebuffer); - _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); - _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterMaskFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT); - GlStateManager.enableDepth(); - GlStateManager.enableCull(); + public void endDrawGlassHighlights() { + DeferredStateManager.checkGLError("Pre: endDrawGlassHighlights()"); + DeferredStateManager.disableDrawGlassHighlightsRender(); GlStateManager.depthMask(true); - DeferredStateManager.enableDrawRealisticWaterMask(); + GlStateManager.disablePolygonOffset(); + DeferredStateManager.setHDRTranslucentPassBlendFunc(); + DeferredStateManager.checkGLError("Post: endDrawGlassHighlights()"); + } + + public void endDrawHandOverlay() { + DeferredStateManager.checkGLError("Pre: endDrawHandOverlay()"); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + shader_hand_depth_mask.useProgram(); + _wglDrawBuffers(GL_NONE); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(handRenderFramebufferDepthTexture); + DrawUtils.drawStandardQuad2D(); + _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); + DeferredStateManager.checkGLError("Post: endDrawHandOverlay()"); + } + + public void endDrawHDRTranslucent() { + DeferredStateManager.checkGLError("Pre: endDrawHDRTranslucent()"); + DeferredStateManager.disableForwardRender(); + DeferredStateManager.disableFog(); + GlStateManager.disableFog(); + GlStateManager.disableDepth(); + GlStateManager.disableAlpha(); + GlStateManager.disableBlend(); + GlStateManager.disableExtensionPipeline(); + if (config.is_rendering_shadowsSun_clamped > 0 && config.is_rendering_shadowsSmoothed) { + GlStateManager.bindTexture(sunShadowDepthBuffer); + setNearest(); + } + DeferredStateManager.checkGLError("Post: endDrawHDRTranslucent()"); + } + + public void endDrawMainGBuffer() { + DeferredStateManager.checkGLError("Pre: endDrawMainGBuffer()"); + _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); + DeferredStateManager.checkGLError("Post: endDrawMainGBuffer()"); + } + + public void endDrawMainGBufferDestroyProgress() { + DeferredStateManager.checkGLError("Pre: endDrawMainGBufferDestroyProgress()"); GlStateManager.enableExtensionPipeline(); - DeferredStateManager.checkGLError("Post: beginDrawRealisticWaterMask()"); + } + + public void endDrawMainShadowMap() { + DeferredStateManager.checkGLError("Pre: endDrawMainShadowMap()"); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + GlStateManager.cullFace(GL_BACK); + DeferredStateManager.disableShadowRender(); + GlStateManager.colorMask(true, true, true, true); + DeferredStateManager.checkGLError("Post: endDrawMainShadowMap()"); } public void endDrawRealisticWaterMask() { @@ -2609,7 +2854,7 @@ public class EaglerDeferredPipeline { DeferredStateManager.disableDrawRealisticWaterMask(); GlStateManager.disableExtensionPipeline(); - if(config.is_rendering_lightShafts) { + if (config.is_rendering_lightShafts) { // ================== RENDER LIGHT SHAFTS =================== // @@ -2622,18 +2867,26 @@ public class EaglerDeferredPipeline { GlStateManager.setActiveTexture(GL_TEXTURE0); GlStateManager.bindTexture(realisticWaterDepthBuffer); shader_light_shafts_sample.useProgram(); - _wglUniform2f(shader_light_shafts_sample.uniforms.u_ditherScale2f, reprojectionTexWidth * 0.125f, reprojectionTexHeight * 0.125f); - uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_inverseViewProjMatrix4f, tmpMatrixInverseViewProj); - _wglUniform3f(shader_light_shafts_sample.uniforms.u_eyePosition3f, DeferredStateManager.inverseViewMatrix.m30, - DeferredStateManager.inverseViewMatrix.m31, DeferredStateManager.inverseViewMatrix.m32); + _wglUniform2f(shader_light_shafts_sample.uniforms.u_ditherScale2f, reprojectionTexWidth * 0.125f, + reprojectionTexHeight * 0.125f); + uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_inverseViewProjMatrix4f, + tmpMatrixInverseViewProj); + _wglUniform3f(shader_light_shafts_sample.uniforms.u_eyePosition3f, + DeferredStateManager.inverseViewMatrix.m30, DeferredStateManager.inverseViewMatrix.m31, + DeferredStateManager.inverseViewMatrix.m32); Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix0, tmpShadowLOD0MatrixTexSpace); - uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_sunShadowMatrixLOD04f, tmpShadowLOD0MatrixTexSpace); - if(config.is_rendering_shadowsSun_clamped > 1) { - Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix1, tmpShadowLOD1MatrixTexSpace); - uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_sunShadowMatrixLOD14f, tmpShadowLOD1MatrixTexSpace); - if(config.is_rendering_shadowsSun_clamped > 2) { - Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix2, tmpShadowLOD2MatrixTexSpace); - uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_sunShadowMatrixLOD24f, tmpShadowLOD2MatrixTexSpace); + uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_sunShadowMatrixLOD04f, + tmpShadowLOD0MatrixTexSpace); + if (config.is_rendering_shadowsSun_clamped > 1) { + Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix1, + tmpShadowLOD1MatrixTexSpace); + uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_sunShadowMatrixLOD14f, + tmpShadowLOD1MatrixTexSpace); + if (config.is_rendering_shadowsSun_clamped > 2) { + Matrix4f.mul(tmpClipToTexSpaceMatLeft, DeferredStateManager.sunShadowMatrix2, + tmpShadowLOD2MatrixTexSpace); + uniformMatrixHelper(shader_light_shafts_sample.uniforms.u_sunShadowMatrixLOD24f, + tmpShadowLOD2MatrixTexSpace); } } @@ -2697,7 +2950,7 @@ public class EaglerDeferredPipeline { GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); shader_realistic_water_control.useProgram(); - if(!reprojectionEngineEnable) { + if (!reprojectionEngineEnable) { tmpVector1.set(-reprojectionViewerOffsetX, -reprojectionViewerOffsetY, -reprojectionViewerOffsetZ); tmpMatrix1.setIdentity(); Matrix4f.translate(tmpVector1, tmpMatrix1, tmpMatrix1); @@ -2706,11 +2959,15 @@ public class EaglerDeferredPipeline { Matrix4f.invert(tmpMatrixViewProjReproject, tmpMatrixInverseViewProjReproject); } - uniformMatrixHelper(shader_realistic_water_control.uniforms.u_inverseViewProjMatrix4f, tmpMatrixInverseViewProjReproject); - uniformMatrixHelper(shader_realistic_water_control.uniforms.u_reprojectionMatrix4f, tmpMatrixLastFrameViewProjReproject); + uniformMatrixHelper(shader_realistic_water_control.uniforms.u_inverseViewProjMatrix4f, + tmpMatrixInverseViewProjReproject); + uniformMatrixHelper(shader_realistic_water_control.uniforms.u_reprojectionMatrix4f, + tmpMatrixLastFrameViewProjReproject); - uniformMatrixHelper(shader_realistic_water_control.uniforms.u_projectionMatrix4f, DeferredStateManager.projMatrix); - uniformMatrixHelper(shader_realistic_water_control.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_realistic_water_control.uniforms.u_projectionMatrix4f, + DeferredStateManager.projMatrix); + uniformMatrixHelper(shader_realistic_water_control.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); Matrix4f.invert(tmpMatrixLastFrameProj, tmpMatrix1); uniformMatrixHelper(shader_realistic_water_control.uniforms.u_lastInverseProjMatrix4f, tmpMatrix1); Matrix4f.invert(tmpMatrixLastFrameViewReproject, tmpMatrix1); @@ -2731,7 +2988,8 @@ public class EaglerDeferredPipeline { float fac = MathHelper.clamp_float(DeferredStateManager.currentSunAngle.y * -4.0f, 0.1f, 1.0f); _wglUniform4f(shader_realistic_water_control.uniforms.u_refractFogColor4f, fr * ff, fg * ff, fb * ff, fac); - uniformMatrixHelper(shader_realistic_water_control.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_realistic_water_control.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); DrawUtils.drawStandardQuad2D(); @@ -2755,7 +3013,8 @@ public class EaglerDeferredPipeline { _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterSSRFramebuffer[1]); shader_reproject_ssr.useProgram(); - uniformMatrixHelper(shader_reproject_ssr.uniforms.u_inverseProjectionMatrix4f, DeferredStateManager.inverseProjMatrix); + uniformMatrixHelper(shader_reproject_ssr.uniforms.u_inverseProjectionMatrix4f, + DeferredStateManager.inverseProjMatrix); Matrix4f.mul(tmpMatrixLastFrameViewProjReproject, tmpMatrixInverseViewProjReproject, tmpMatrix1); Matrix4f.mul(tmpMatrix1, DeferredStateManager.projMatrix, tmpMatrix1); uniformMatrixHelper(shader_reproject_ssr.uniforms.u_lastProjectionMatrix4f, tmpMatrix1); @@ -2818,7 +3077,7 @@ public class EaglerDeferredPipeline { GlStateManager.bindTexture(realisticWaterNoiseMap); shader_realistic_water_noise.useProgram(); - float waveTimer = (float)((EagRuntime.steadyTimeMillis() % 600000l) * 0.001); + float waveTimer = (float) ((EagRuntime.steadyTimeMillis() % 600000l) * 0.001); _wglUniform4f(shader_realistic_water_noise.uniforms.u_waveTimer4f, waveTimer, 0.0f, 0.0f, 0.0f); DrawUtils.drawStandardQuad2D(); @@ -2834,139 +3093,10 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("endDrawRealisticWaterMask(): GENERATE WAVE NORMAL MAP"); } - public void applyGBufferFog() { - DeferredStateManager.checkGLError("Pre: applyGBufferFog()"); - if(DeferredStateManager.fogLinearExp == 0) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - return; - } - _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, lightingHDRFramebuffer); - _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, fogDepthCopyBuffer); - _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - if(config.is_rendering_lightShafts) { - GlStateManager.setActiveTexture(GL_TEXTURE4); - GlStateManager.bindTexture(lightShaftsTexture); - } - GlStateManager.setActiveTexture(GL_TEXTURE3); - GlStateManager.bindTexture(skyIrradianceTexture); - GlStateManager.setActiveTexture(GL_TEXTURE2); - GlStateManager.bindTexture(fogDepthCopyTexture); - GlStateManager.setActiveTexture(GL_TEXTURE1); - GlStateManager.bindTexture(gBufferNormalsTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(gBufferDepthTexture); - tmpMatrix1.load(DeferredStateManager.inverseViewMatrix); - tmpMatrix1.m30 = tmpMatrix1.m31 = tmpMatrix1.m32 = 0.0f; - Matrix4f.mul(tmpMatrix1, DeferredStateManager.inverseProjMatrix, tmpMatrix1); - PipelineShaderGBufferFog fogShader; - switch(DeferredStateManager.fogLinearExp) { - case 1: - fogShader = shader_colored_fog_linear; - fogShader.useProgram(); - _wglUniform2f(fogShader.uniforms.u_linearFogParam2f, DeferredStateManager.fogNear, DeferredStateManager.fogFar); - break; - case 2: - fogShader = shader_colored_fog_exp; - fogShader.useProgram(); - _wglUniform1f(fogShader.uniforms.u_expFogDensity1f, DeferredStateManager.fogDensity); - break; - case 6: - fogShader = shader_atmosphere_fog; - fogShader.useProgram(); - _wglUniform1f(fogShader.uniforms.u_expFogDensity1f, DeferredStateManager.fogDensity); - float mul = 0.05f * MathHelper.clamp_float(-1.0f - DeferredStateManager.getSunHeight() * 20.0f, 0.0f, 1.0f) + 0.01f; - _wglUniform3f(fogShader.uniforms.u_sunColorAdd3f, DeferredStateManager.currentSunLightColor.x * mul, DeferredStateManager.currentSunLightColor.y * mul, DeferredStateManager.currentSunLightColor.z * mul); - break; - default: - throw new RuntimeException("Invalid fog type: " + DeferredStateManager.fogLinearExp); - } - uniformMatrixHelper(fogShader.uniforms.u_inverseViewProjMatrix4f, tmpMatrix1); - _wglUniform4f(fogShader.uniforms.u_fogColorLight4f, DeferredStateManager.fogColorLightR, - DeferredStateManager.fogColorLightG, DeferredStateManager.fogColorLightB, - DeferredStateManager.fogColorLightA); - _wglUniform4f(fogShader.uniforms.u_fogColorDark4f, DeferredStateManager.fogColorDarkR, - DeferredStateManager.fogColorDarkG, DeferredStateManager.fogColorDarkB, - DeferredStateManager.fogColorDarkA); - GlStateManager.disableDepth(); - GlStateManager.depthMask(false); - GlStateManager.tryBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); - DrawUtils.drawStandardQuad2D(); - GlStateManager.enableDepth(); - GlStateManager.depthMask(true); - DeferredStateManager.setHDRTranslucentPassBlendFunc(); - DeferredStateManager.checkGLError("Post: applyGBufferFog()"); - } - - public void beginDrawHDRTranslucent() { - DeferredStateManager.checkGLError("Pre: beginDrawHDRTranslucent()"); - GlStateManager.enableDepth(); - GlStateManager.depthMask(true); - GlStateManager.enableAlpha(); - GlStateManager.alphaFunc(GL_GREATER, 0.1f); - GlStateManager.enableBlend(); - DeferredStateManager.setHDRTranslucentPassBlendFunc(); - DeferredStateManager.enableForwardRender(); - GlStateManager.enableExtensionPipeline(); - updateForwardRenderWorldLightingData(); - EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); - EaglercraftGPU.bindUniformBufferRange(0, buffer_worldLightingData, 0, worldLightingDataCopyBuffer.remaining()); - if(config.is_rendering_dynamicLights) { - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); - EaglercraftGPU.bindUniformBufferRange(1, buffer_chunkLightingData, 0, chunkLightingDataCopyBuffer.capacity()); - } - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - DeferredStateManager.setPassMatrixToGBuffer(); - GlStateManager.setActiveTexture(GL_TEXTURE10); - GlStateManager.bindTexture(skyIrradianceTexture); - if(config.is_rendering_lightShafts) { - GlStateManager.setActiveTexture(GL_TEXTURE11); - GlStateManager.bindTexture(lightShaftsTexture); - } - if(config.is_rendering_useEnvMap) { - GlStateManager.setActiveTexture(GL_TEXTURE5); - GlStateManager.bindTexture(envMapColorTexture); - } - GlStateManager.setActiveTexture(GL_TEXTURE6); - GlStateManager.bindTexture(brdfTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); - DeferredStateManager.checkGLError("Post: beginDrawHDRTranslucent()"); - } - - public void beginDrawRealisticWaterSurface() { - DeferredStateManager.checkGLError("Pre: beginDrawRealisticWaterSurface()"); - DeferredStateManager.enableDrawRealisticWaterRender(); - GlStateManager.setActiveTexture(GL_TEXTURE9); - GlStateManager.bindTexture(realisticWaterNormalMapTexture); - GlStateManager.setActiveTexture(GL_TEXTURE8); - GlStateManager.bindTexture(realisticWaterRefractionTexture); - GlStateManager.setActiveTexture(GL_TEXTURE7); - GlStateManager.bindTexture(realisticWaterControlReflectionTexture[1]); - GlStateManager.setActiveTexture(GL_TEXTURE5); - GlStateManager.bindTexture(envMapSkyTexture); - GlStateManager.setActiveTexture(GL_TEXTURE4); - if(config.is_rendering_shadowsSun_clamped > 0) { - GlStateManager.bindTexture(sunShadowDepthBuffer); - if(config.is_rendering_shadowsSmoothed) { - setLinear(); - } - }else { - GlStateManager.bindTexture(-1); - } - TextureManager mgr = mc.getTextureManager(); - GlStateManager.setActiveTexture(GL_TEXTURE3); - GlStateManager.bindTexture(MetalsLUT.getGLTexture()); - GlStateManager.setActiveTexture(GL_TEXTURE0); - mgr.bindTexture(TextureMap.locationBlocksTexture); - GlStateManager.enableCull(); - DeferredStateManager.checkGLError("Post: beginDrawRealisticWaterSurface()"); - } - public void endDrawRealisticWaterSurface() { DeferredStateManager.checkGLError("Pre: endDrawRealisticWaterSurface()"); DeferredStateManager.disableDrawRealisticWaterRender(); - if(config.is_rendering_useEnvMap) { + if (config.is_rendering_useEnvMap) { GlStateManager.setActiveTexture(GL_TEXTURE5); GlStateManager.bindTexture(envMapColorTexture); GlStateManager.setActiveTexture(GL_TEXTURE0); @@ -2974,1016 +3104,773 @@ public class EaglerDeferredPipeline { DeferredStateManager.checkGLError("Post: endDrawRealisticWaterSurface()"); } - public void beginDrawTranslucentBlocks() { - DeferredStateManager.checkGLError("Pre: beginDrawTranslucentBlocks()"); - } - - public void beginDrawGlassHighlights() { - DeferredStateManager.checkGLError("Pre: beginDrawGlassHighlights()"); - DeferredStateManager.enableDrawGlassHighlightsRender(); - GlStateManager.depthMask(false); - GlStateManager.enablePolygonOffset(); - GlStateManager.doPolygonOffset(0.25f, 1.0f); - GlStateManager.tryBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); - DeferredStateManager.checkGLError("Post: beginDrawGlassHighlights()"); - } - - public void endDrawGlassHighlights() { - DeferredStateManager.checkGLError("Pre: endDrawGlassHighlights()"); - DeferredStateManager.disableDrawGlassHighlightsRender(); - GlStateManager.depthMask(true); - GlStateManager.disablePolygonOffset(); - DeferredStateManager.setHDRTranslucentPassBlendFunc(); - DeferredStateManager.checkGLError("Post: endDrawGlassHighlights()"); - } - - public void beginDrawTranslucentEntities() { - DeferredStateManager.checkGLError("Pre: beginDrawTranslucentEntities()"); - GlStateManager.setActiveTexture(GL_TEXTURE4); - if(config.is_rendering_shadowsSun_clamped > 0) { - GlStateManager.bindTexture(sunShadowDepthBuffer); - if(config.is_rendering_shadowsSmoothed) { - setLinear(); - } - }else { - GlStateManager.bindTexture(-1); + public ListSerial getLightSourceBucketRelativeChunkCoords(int cx, int cy, int cz) { + int hw = lightSourceBucketsWidth / 2; + int hh = lightSourceBucketsHeight / 2; + cx += hw; + cy += hh; + cz += hw; + if (cx < 0 || cx >= lightSourceBucketsWidth || cy < 0 || cy >= lightSourceBucketsHeight || cz < 0 + || cz >= lightSourceBucketsWidth) { + return null; + } else { + return lightSourceBuckets[cy * lightSourceBucketsWidth * lightSourceBucketsWidth + + cz * lightSourceBucketsWidth + cx]; } - TextureManager mgr = mc.getTextureManager(); - GlStateManager.setActiveTexture(GL_TEXTURE3); - GlStateManager.bindTexture(MetalsLUT.getGLTexture()); - GlStateManager.setActiveTexture(GL_TEXTURE0); - mgr.bindTexture(TextureMap.locationBlocksTexture); - GlStateManager.enableCull(); - DeferredStateManager.checkGLError("Post: beginDrawTranslucentEntities()"); } - public void saveReprojData() { - DeferredStateManager.checkGLError("Pre: saveReprojData()"); - if(reprojectionEngineEnable || config.is_rendering_realisticWater) { - - // =========== SAVE REPROJECTION DATA FOR NEXT FRAME ============= // - - tmpMatrixLastFrameProj.load(DeferredStateManager.projMatrix); - tmpMatrixLastFrameViewReproject.load(tmpMatrixViewReproject); - tmpMatrixLastFrameViewProjReproject.load(tmpMatrixViewProjReproject); - - GlStateManager.disableBlend(); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lastFrameFramebuffer); - GlStateManager.viewport(0, 0, reprojectionTexWidth, reprojectionTexHeight); - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); - TextureCopyUtil.alignPixelsTopLeft(reprojectionTexWidth << 1, reprojectionTexHeight << 1, reprojectionTexWidth, reprojectionTexHeight); - TextureCopyUtil.blitTexture(); - GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); - GlStateManager.enableDepth(); - GlStateManager.depthFunc(GL_ALWAYS); - GlStateManager.depthMask(true); - _wglDrawBuffers(GL_NONE); - TextureCopyUtil.alignPixelsTopLeft(reprojectionTexWidth << 1, reprojectionTexHeight << 1, reprojectionTexWidth, reprojectionTexHeight); - TextureCopyUtil.blitTextureDepth(); - GlStateManager.disableDepth(); - GlStateManager.depthMask(false); - GlStateManager.depthFunc(GL_LEQUAL); - _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); - - reprojectionPhase = (reprojectionPhase + 1) & 1; - ++reprojectionStartup; - - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - GlStateManager.enableBlend(); - } - DeferredStateManager.checkGLError("Post: saveReprojData()"); + public float getPartialTicks() { + return partialTicks; } - public void beginDrawHandOverlay() { - DeferredStateManager.checkGLError("Pre: beginDrawHandOverlay()"); - _wglBindFramebuffer(_GL_FRAMEBUFFER, handRenderFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - GlStateManager.clearDepth(1.0f); - GlStateManager.depthMask(true); - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - GlStateManager.enableDepth(); - DeferredStateManager.setDefaultMaterialConstants(); - DeferredStateManager.checkGLError("Post: beginDrawHandOverlay()"); + private float getSkyBrightnessParam() { + float fff = mc.theWorld.getRainStrength(partialTicks) * 0.9f; + fff += mc.theWorld.getThunderStrength(partialTicks) * 0.05f; + return 1.0f - fff; } - public void endDrawHandOverlay() { - DeferredStateManager.checkGLError("Pre: endDrawHandOverlay()"); - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - shader_hand_depth_mask.useProgram(); - _wglDrawBuffers(GL_NONE); - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(handRenderFramebufferDepthTexture); - DrawUtils.drawStandardQuad2D(); - _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); - DeferredStateManager.checkGLError("Post: endDrawHandOverlay()"); + private float getSkyBrightnessTimeParam() { + return (2.0f + MathHelper.clamp_float(-DeferredStateManager.currentSunAngle.y * 8.0f, 0.0f, 1.5f)) + * getSkyBrightnessParam(); } - public void endDrawHDRTranslucent() { - DeferredStateManager.checkGLError("Pre: endDrawHDRTranslucent()"); - DeferredStateManager.disableForwardRender(); - DeferredStateManager.disableFog(); - GlStateManager.disableFog(); - GlStateManager.disableDepth(); - GlStateManager.disableAlpha(); - GlStateManager.disableBlend(); - GlStateManager.disableExtensionPipeline(); - if(config.is_rendering_shadowsSun_clamped > 0 && config.is_rendering_shadowsSmoothed) { + public void loadViewMatrix() { + DeferredStateManager.loadGBufferViewMatrix(); + DeferredStateManager.loadGBufferProjectionMatrix(); + } + + public void rebuild(EaglerDeferredConfig config) { + destroy(); + uniformBufferOffsetAlignment = EaglercraftGPU.getUniformBufferOffsetAlignment(); + DeferredStateManager.doCheckErrors = EagRuntime.getConfiguration().isCheckShaderGLErrors(); + DeferredStateManager.checkGLError("Pre: rebuild pipeline"); + this.config = config; + this.currentWidth = -1; + this.currentHeight = -1; + logger.info("Rebuilding pipeline..."); + + gBufferFramebuffer = _wglCreateFramebuffer(); + + _wglBindFramebuffer(_GL_FRAMEBUFFER, gBufferFramebuffer); + + gBufferDiffuseTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(gBufferDiffuseTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(gBufferDiffuseTexture), 0); + gBufferNormalsTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(gBufferNormalsTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(gBufferNormalsTexture), 0); + gBufferMaterialTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(gBufferMaterialTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(gBufferMaterialTexture), 0); + gBufferDrawBuffers = new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1, _GL_COLOR_ATTACHMENT2 }; + _wglDrawBuffers(gBufferDrawBuffers); + + gBufferDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(gBufferDepthTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(gBufferDepthTexture), 0); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: gbuffers"); + + boolean shadowsSun = config.is_rendering_shadowsSun_clamped > 0; + if (shadowsSun) { + sunShadowFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowFramebuffer); + sunShadowDepthBuffer = GlStateManager.generateTexture(); GlStateManager.bindTexture(sunShadowDepthBuffer); setNearest(); + _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_FUNC, GL_GREATER); + _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); + int lods = config.is_rendering_shadowsSun_clamped; + if (lods > 3) { + lods = 3; + } + sunShadowDepthBufferRes = 2048; + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT24, sunShadowDepthBufferRes, + sunShadowDepthBufferRes * lods, 0, _GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, (ByteBuffer) null); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(sunShadowDepthBuffer), 0); + sunLightingShadowFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunLightingShadowFramebuffer); + sunLightingShadowTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(sunLightingShadowTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(sunLightingShadowTexture), 0); + if (config.is_rendering_shadowsColored) { + sunShadowColorFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunShadowColorFramebuffer); + GlStateManager.bindTexture(sunShadowDepthBuffer); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(sunShadowDepthBuffer), 0); + sunShadowColorBuffer = GlStateManager.generateTexture(); + GlStateManager.bindTexture(sunShadowColorBuffer); + setNearest(); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, sunShadowDepthBufferRes, sunShadowDepthBufferRes * lods, 0, + GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(sunShadowColorBuffer), 0); + } + + DeferredStateManager.checkGLError("Post: rebuild pipeline: shadowsSun"); } - DeferredStateManager.checkGLError("Post: endDrawHDRTranslucent()"); - } - public void endDrawDeferred() { - DeferredStateManager.checkGLError("Pre: endDrawDeferred()"); + reprojectionEngineEnable = config.is_rendering_ssao || config.is_rendering_raytracing; + if (reprojectionEngineEnable || config.is_rendering_realisticWater) { + lastFrameFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lastFrameFramebuffer); + lastFrameColorTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(lastFrameColorTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lastFrameColorTexture), 0); + lastFrameDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(lastFrameDepthTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lastFrameDepthTexture), 0); + lastFrameGBufferFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lastFrameGBufferFramebuffer); + lastFrameGBufferDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(lastFrameGBufferDepthTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lastFrameGBufferDepthTexture), 0); + DeferredStateManager.checkGLError("Post: rebuild pipeline: lastFrame"); + } - if(config.is_rendering_lensFlares && mc.theWorld.provider.getDimensionId() == 0 && - DeferredStateManager.currentSunAngle.y < 0.2f && mc.theWorld.getRainStrength(partialTicks) < 1.0f) { - - // =============== CALCULATE SUN COORDINATES ================ // - - tmpVector2.x = DeferredStateManager.currentSunAngle.x * 10.0f; - tmpVector2.y = DeferredStateManager.currentSunAngle.y * 10.0f; - tmpVector2.z = DeferredStateManager.currentSunAngle.z * 10.0f; - tmpVector2.w = 1.0f; - - Matrix4f.transform(tmpMatrixViewProj, tmpVector2, tmpVector2); - - tmpVector2.z /= tmpVector2.w; - float margin = 0.2f; - if (tmpVector2.z <= -1.0f) { - tmpVector2.x = DeferredStateManager.currentSunAngle.x * 10.0f; - tmpVector2.y = DeferredStateManager.currentSunAngle.y * 10.0f; - tmpVector2.z = DeferredStateManager.currentSunAngle.z * 10.0f; - tmpVector2.w = 0.0f; - Matrix4f.transform(tmpMatrixViewProj, tmpVector2, tmpVector2); - tmpVector2.x /= tmpVector2.w; - tmpVector2.y /= tmpVector2.w; - if (tmpVector2.x < 1.0f + margin && tmpVector2.x > -1.0f - margin && tmpVector2.y < 1.0f + margin - && tmpVector2.y > -1.0f - margin) { - - // ============ CALCULATE DEPTH SUN OCCLUSION ============ // - - _wglBindFramebuffer(_GL_FRAMEBUFFER, sunOcclusionValueFramebuffer); - GlStateManager.viewport(0, 0, 1, 1); - - GlStateManager.setActiveTexture(GL_TEXTURE1); - GlStateManager.bindTexture(CloudRenderWorker.cloudOcclusionTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); - - float fov = 90.0f / mc.entityRenderer.getFOVModifier(partialTicks, true); - float radius = 0.05f * fov; - float aspectRatio = (float)currentHeight / (float)currentWidth; - - tmpMatrix3.setIdentity(); - tmpMatrix3.m00 = aspectRatio * radius; - tmpMatrix3.m11 = radius; - tmpMatrix3.m20 = tmpVector2.x * 0.5f + 0.5f; - tmpMatrix3.m21 = tmpVector2.y * 0.5f + 0.5f; - - shader_lens_sun_occlusion.useProgram(); - - uniformMatrixHelper(shader_lens_sun_occlusion.uniforms.u_sampleMatrix3f, tmpMatrix3); - - DrawUtils.drawStandardQuad2D(); - - DeferredStateManager.checkGLError("endDrawDeferred(): CALCULATE DEPTH SUN OCCLUSION"); - - // ============ RENDER SUN LENS FLARES MESHES ============ // - - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - - LensFlareMeshRenderer.drawLensFlares(tmpVector2.x, tmpVector2.y); - - DeferredStateManager.checkGLError("endDrawDeferred(): RENDER SUN LENS FLARES MESHES"); + if (reprojectionEngineEnable) { + gBufferQuarterFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, gBufferQuarterFramebuffer); + gBufferQuarterDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(gBufferQuarterDepthTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(gBufferQuarterDepthTexture), 0); + reprojectionStartup = 0; + for (int i = 0; i < 2; ++i) { + reprojectionControlFramebuffer[i] = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionControlFramebuffer[i]); + if (config.is_rendering_ssao) { + reprojectionControlSSAOTexture[i] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(reprojectionControlSSAOTexture[i]); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(reprojectionControlSSAOTexture[i]), 0); + } + if (config.is_rendering_raytracing) { + reprojectionSSRTexture[i] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(reprojectionSSRTexture[0]); // yes this should be 0 + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, + config.is_rendering_ssao ? _GL_COLOR_ATTACHMENT1 : _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(reprojectionSSRTexture[0]), 0); + reprojectionSSRHitVector[i] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(reprojectionSSRHitVector[0]); // yes this should be 0 + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, + config.is_rendering_ssao ? _GL_COLOR_ATTACHMENT2 : _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(reprojectionSSRHitVector[0]), 0); + reprojectionSSRFramebuffer[i] = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionSSRFramebuffer[i]); + _wglDrawBuffers(SSRColorAttachments); + GlStateManager.bindTexture(reprojectionSSRTexture[i]); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(reprojectionSSRTexture[i]), 0); + GlStateManager.bindTexture(reprojectionSSRHitVector[i]); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(reprojectionSSRHitVector[i]), 0); } } + shader_reproject_control = PipelineShaderReprojControl.compile(config.is_rendering_ssao, + config.is_rendering_raytracing); + shader_reproject_control.loadUniforms(); + if (config.is_rendering_raytracing) { + shader_reproject_ssr = PipelineShaderReprojSSR.compile(); + shader_reproject_ssr.loadUniforms(); + } + reprojectionControlDrawBuffers = new int[(config.is_rendering_ssao ? 1 : 0) + + (config.is_rendering_raytracing ? 2 : 0)]; + int i = 0; + if (config.is_rendering_ssao) { + reprojectionControlDrawBuffers[i] = _GL_COLOR_ATTACHMENT0; + ++i; + } + if (config.is_rendering_raytracing) { + reprojectionControlDrawBuffers[i] = _GL_COLOR_ATTACHMENT0 + i; + ++i; + reprojectionControlDrawBuffers[i] = _GL_COLOR_ATTACHMENT0 + i; + } + for (int j = 0; j < 2; ++j) { + _wglBindFramebuffer(_GL_FRAMEBUFFER, reprojectionControlFramebuffer[j]); + _wglDrawBuffers(reprojectionControlDrawBuffers); + } + DeferredStateManager.checkGLError("Post: rebuild pipeline: reprojectionEngineEnable"); } - // ================ DOWNSCALE AND AVERAGE LUMA =============== // - - long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastExposureUpdate > 33l) { - if(lumaAvgDownscaleFramebuffers.length == 0) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, exposureBlendFramebuffer); - GlStateManager.clearColor(1.0f, 1.0f, 1.0f, 1.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT); - }else { - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - setLinear(); - - int iw = currentWidth; - int ih = currentHeight; - int iw2 = 0, ih2 = 0, iw3 = 0, ih3 = 0; - for(int i = 0; i < lumaAvgDownscaleFramebuffers.length; ++i) { - iw2 = iw >> 2; - ih2 = ih >> 2; - // cheap way to round up: - iw3 = ((iw & 3) != 0) ? (iw2 + 1) : iw2; - ih3 = ((ih & 3) != 0) ? (ih2 + 1) : ih2; - _wglBindFramebuffer(_GL_FRAMEBUFFER, lumaAvgDownscaleFramebuffers[i]); - - if(i == 0) { - shader_post_exposure_avg_luma.useProgram(); - _wglUniform4f(shader_post_exposure_avg_luma.uniforms.u_sampleOffset4f, 1.0f / iw3, 1.0f / ih3, 4.0f / iw, 4.0f / ih); - }else { - shader_post_exposure_avg.useProgram(); - GlStateManager.bindTexture(lumaAvgDownscaleTexture[i - 1]); - _wglUniform4f(shader_post_exposure_avg.uniforms.u_sampleOffset4f, 1.0f / iw3, 1.0f / ih3, 4.0f / iw, 4.0f / ih); - } - - GlStateManager.viewport(0, 0, iw3, ih3); - - DrawUtils.drawStandardQuad2D(); - - iw = iw2; - ih = ih2; - } - - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - setNearest(); - - _wglBindFramebuffer(_GL_FRAMEBUFFER, exposureBlendFramebuffer); - GlStateManager.viewport(0, 0, 1, 1); - - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_CONSTANT_ALPHA, GL_ONE_MINUS_CONSTANT_ALPHA); - - GlStateManager.setBlendConstants(0.0f, 0.0f, 0.0f, Math.min((float)((millis - lastExposureUpdate) * 0.001), 1.0f)); - - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(lumaAvgDownscaleTexture[lumaAvgDownscaleTexture.length - 1]); - - shader_post_exposure_final.useProgram(); - _wglUniform2f(shader_post_exposure_final.uniforms.u_inputSize2f, 1.0f / iw3, 1.0f / ih3); - - DrawUtils.drawStandardQuad2D(); - - GlStateManager.disableBlend(); - - lastExposureUpdate = millis; - } - - DeferredStateManager.checkGLError("endDrawDeferred(): DOWNSCALE AND AVERAGE LUMA"); - } - - if(config.is_rendering_bloom) { - - // ==================== BLOOM: BRIGHT PASS ==================== // - - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomBrightPassFramebuffer); - GlStateManager.viewport(0, 0, bloomBrightPassTextureW, bloomBrightPassTextureH); - boolean flag = bloomBrightPassTextureW != currentWidth || bloomBrightPassTextureH != currentHeight; - GlStateManager.setActiveTexture(GL_TEXTURE3); - GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); - GlStateManager.setActiveTexture(GL_TEXTURE2); - GlStateManager.bindTexture(gBufferMaterialTexture); - if(flag) { - setLinear(); - } - GlStateManager.setActiveTexture(GL_TEXTURE1); - GlStateManager.bindTexture(exposureBlendTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - if(flag) { - setLinear(); - } - shader_post_bloom_bright.useProgram(); - _wglUniform4f(shader_post_bloom_bright.uniforms.u_outputSize4f, bloomBrightPassTextureW, bloomBrightPassTextureH, (flag ? 2.0f : 1.0f) / currentWidth, (flag ? 2.0f : 1.0f) / currentHeight); - DrawUtils.drawStandardQuad2D(); - if(flag) { - setNearest(); - GlStateManager.setActiveTexture(GL_TEXTURE2); - setNearest(); - GlStateManager.setActiveTexture(GL_TEXTURE0); - } - - DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: BRIGHT PASS"); - - // ==================== BLOOM: DOWNSCALE A ==================== // - - int bloomStageW = bloomBrightPassTextureW; - int bloomStageH = bloomBrightPassTextureH; - int texx = bloomBrightPassTexture; - if(bloomStageW > 300 && bloomStageH > 170) { - bloomStageW >>= 1; - bloomStageH >>= 1; - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleAFramebuffer); - GlStateManager.viewport(0, 0, bloomStageW, bloomStageH); - GlStateManager.bindTexture(texx); - texx = bloomDownscaleATexture; - TextureCopyUtil.alignPixels(bloomStageW, bloomStageH, 0.5f, 0.5f); - TextureCopyUtil.blitTexture(); - - DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: DOWNSCALE A"); - - if(bloomStageW > 300 && bloomStageH > 170) { - - // ==================== BLOOM: DOWNSCALE B ==================== // - - bloomStageW >>= 1; - bloomStageH >>= 1; - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleBFramebuffer); - GlStateManager.viewport(0, 0, bloomStageW, bloomStageH); - GlStateManager.bindTexture(texx); - texx = bloomDownscaleBTexture; - TextureCopyUtil.alignPixels(bloomStageW, bloomStageH, 0.5f, 0.5f); - TextureCopyUtil.blitTexture(); - - DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: DOWNSCALE B"); + if (config.is_rendering_ssao) { + ssaoGenerateFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, ssaoGenerateFramebuffer); + ssaoGenerateTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(ssaoGenerateTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(ssaoGenerateTexture), 0); + ssaoNoiseTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(ssaoNoiseTexture); + setNearest(); + int noiseTexSize = 64, noiseTexLen = 16384; + byte[] noiseTexDat = EagRuntime.getRequiredResourceBytes("assets/eagler/glsl/deferred/ssao_noise.bmp"); + if (noiseTexDat == null || noiseTexDat.length != noiseTexLen) { + noiseTexDat = new byte[noiseTexLen]; + for (int i = 0; i < 4096; ++i) { + noiseTexDat[(i << 2) + 2] = (byte) 255; // dumb fallback } } - - // ===================== BLOOM: HORZ BLUR ===================== // - - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomHBlurFramebuffer); - GlStateManager.viewport(0, 0, bloomBlurTextureW, bloomBlurTextureH); - flag = bloomBrightPassTextureW != bloomBlurTextureW || bloomBrightPassTextureH != bloomBlurTextureH; - GlStateManager.bindTexture(texx); - shader_post_bloom_blur.useProgram(); - _wglUniform2f(shader_post_bloom_blur.uniforms.u_sampleOffset2f, (flag ? 2.0f : 1.0f) / bloomStageW, 0.0f); - _wglUniform4f(shader_post_bloom_blur.uniforms.u_outputSize4f, bloomBlurTextureW, bloomBlurTextureH, (flag ? 2.0f : 1.0f) / bloomStageW, (flag ? 2.0f : 1.0f) / bloomStageH); - DrawUtils.drawStandardQuad2D(); - - DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: HORZ BLUR"); - - // ===================== BLOOM: VERT BLUR ===================== // - - _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomVBlurFramebuffer); - GlStateManager.bindTexture(bloomHBlurTexture); - shader_post_bloom_blur.useProgram(); - _wglUniform2f(shader_post_bloom_blur.uniforms.u_sampleOffset2f, 0.0f, 1.0f / bloomBlurTextureH); - _wglUniform4f(shader_post_bloom_blur.uniforms.u_outputSize4f, bloomBlurTextureW, bloomBlurTextureH, 1.0f / bloomBlurTextureW, 1.0f / bloomBlurTextureH); - DrawUtils.drawStandardQuad2D(); - - DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: VERT BLUR"); - - // ======================== BLOOM: MIX ======================= // - - _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - GlStateManager.bindTexture(bloomVBlurTexture); - GlStateManager.enableBlend(); - GlStateManager.tryBlendFuncSeparate(GL_CONSTANT_ALPHA, GL_ONE, GL_ZERO, GL_ONE); - GlStateManager.setBlendConstants(0.0f, 0.0f, 0.0f, 0.15f); - TextureCopyUtil.blitTexture(); - GlStateManager.disableBlend(); - - DeferredStateManager.checkGLError("endDrawDeferred(): BLOOM: MIX"); + ByteBuffer noiseTextureBytes = EagRuntime.allocateByteBuffer(noiseTexLen); + noiseTextureBytes.put(noiseTexDat); + noiseTextureBytes.flip(); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, noiseTexSize, noiseTexSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, + noiseTextureBytes); + EagRuntime.freeByteBuffer(noiseTextureBytes); + shader_ssao_generate = PipelineShaderSSAOGenerate.compile(); + shader_ssao_generate.loadUniforms(); + DeferredStateManager.checkGLError("Post: rebuild pipeline: SSAO"); } - // ==================== APPLY TONEMAPPING ==================== // - - float exposure = 1.0f; - - if(config.is_rendering_fxaa) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, tonemapOutputFramebuffer); - }else { - if(config.is_rendering_lensDistortion) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, lensDistortFramebuffer); - }else { - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - } - } - GlStateManager.viewport(0, 0, currentWidth, currentHeight); - shader_post_tonemap.useProgram(); - GlStateManager.disableBlend(); - GlStateManager.setActiveTexture(GL_TEXTURE2); - GlStateManager.bindTexture(dither8x8Texture); - GlStateManager.setActiveTexture(GL_TEXTURE1); - GlStateManager.bindTexture(exposureBlendTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); + lightingHDRFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + lightingHDRFramebufferColorTexture = GlStateManager.generateTexture(); GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); - _wglUniform3f(shader_post_tonemap.uniforms.u_exposure3f, exposure, exposure, exposure); - _wglUniform2f(shader_post_tonemap.uniforms.u_ditherScale2f, currentWidth / 8.0f, currentHeight / 8.0f); - DrawUtils.drawStandardQuad2D(); - GlStateManager.setActiveTexture(GL_TEXTURE2); - GlStateManager.bindTexture(-1); - GlStateManager.setActiveTexture(GL_TEXTURE0); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lightingHDRFramebufferColorTexture), 0); + lightingHDRFramebufferDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lightingHDRFramebufferDepthTexture), 0); - DeferredStateManager.checkGLError("endDrawDeferred(): APPLY TONEMAPPING"); + handRenderFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, handRenderFramebuffer); + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lightingHDRFramebufferColorTexture), 0); + handRenderFramebufferDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(handRenderFramebufferDepthTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(handRenderFramebufferDepthTexture), 0); - if(config.is_rendering_fxaa) { - - // ======================= APPLY FXAA ======================== // + shader_hand_depth_mask = PipelineShaderHandDepthMask.compile(); + shader_hand_depth_mask.loadUniforms(); + shader_deferred_combine = PipelineShaderGBufferCombine.compile(config.is_rendering_ssao, + config.is_rendering_useEnvMap, config.is_rendering_raytracing); + shader_deferred_combine.loadUniforms(); - if(config.is_rendering_lensDistortion) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, lensDistortFramebuffer); - }else { - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + DeferredStateManager.checkGLError("Post: rebuild pipeline: lightingHDRFramebuffer"); + + brdfTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(brdfTexture); + setLinear(); + int brdfLutW = 64, brdfLutH = 64, brdfLutLen = 8192; + byte[] brdfLutDat = EagRuntime.getRequiredResourceBytes("assets/eagler/glsl/deferred/brdf_lut.bmp"); + if (brdfLutDat == null || brdfLutDat.length != brdfLutLen) { + brdfLutDat = new byte[brdfLutLen]; + for (int i = 0; i < 4096; ++i) { + brdfLutDat[i << 1] = (byte) 192; // dumb fallback } - shader_post_fxaa.useProgram(); - GlStateManager.bindTexture(tonemapOutputTexture); - _wglUniform2f(shader_post_fxaa.uniforms.u_screenSize2f, 1.0f / currentWidth, 1.0f / currentHeight); - DrawUtils.drawStandardQuad2D(); - - DeferredStateManager.checkGLError("endDrawDeferred(): APPLY FXAA"); } - - if(config.is_rendering_lensDistortion) { - - // ================= APPLY LENS DISTORTION ================== // + ByteBuffer brdfLutDatBuffer = EagRuntime.allocateByteBuffer(brdfLutDat.length); + brdfLutDatBuffer.put(brdfLutDat); + brdfLutDatBuffer.flip(); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_RG8, brdfLutW, brdfLutH, 0, _GL_RG, GL_UNSIGNED_BYTE, brdfLutDatBuffer); + EagRuntime.freeByteBuffer(brdfLutDatBuffer); - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - GlStateManager.setActiveTexture(GL_TEXTURE0); + DeferredStateManager.checkGLError("Post: rebuild pipeline: brdfLut"); + + dither8x8Texture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(dither8x8Texture); + setNearest(); + ByteBuffer dither8x8DatBuffer = EagRuntime.allocateByteBuffer(ditherPattern.length); + dither8x8DatBuffer.put(ditherPattern); + dither8x8DatBuffer.flip(); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, 8, 8, 0, GL_RED, GL_UNSIGNED_BYTE, dither8x8DatBuffer); + EagRuntime.freeByteBuffer(dither8x8DatBuffer); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: dither8x8Texture"); + + shader_lighting_sun = PipelineShaderLightingSun.compile(shadowsSun ? config.is_rendering_shadowsSun_clamped : 0, + config.is_rendering_shadowsColored); + shader_lighting_sun.loadUniforms(); + if (shadowsSun) { + shader_shadows_sun = PipelineShaderShadowsSun.compile(config.is_rendering_shadowsSun_clamped, + config.is_rendering_shadowsSmoothed, config.is_rendering_shadowsColored); + shader_shadows_sun.loadUniforms(); + } + shader_post_tonemap = PipelineShaderTonemap.compile(); + shader_post_tonemap.loadUniforms(); + shader_post_fxaa = PipelineShaderFXAA.compile(); + shader_post_fxaa.loadUniforms(); + shader_post_exposure_avg = PipelineShaderPostExposureAvg.compile(false); + shader_post_exposure_avg.loadUniforms(); + shader_post_exposure_avg_luma = PipelineShaderPostExposureAvg.compile(true); + shader_post_exposure_avg_luma.loadUniforms(); + shader_post_exposure_final = PipelineShaderPostExposureFinal.compile(); + shader_post_exposure_final.loadUniforms(); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: compile shaders 1"); + + if (config.is_rendering_lensFlares) { + sunOcclusionValueFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, sunOcclusionValueFramebuffer); + sunOcclusionValueTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(sunOcclusionValueTexture); + setNearest(); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer) null); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(sunOcclusionValueTexture), 0); + shader_lens_sun_occlusion = PipelineShaderLensSunOcclusion.compile(); + shader_lens_sun_occlusion.loadUniforms(); + DeferredStateManager.checkGLError("Post: rebuild pipeline: sunOcclusionValueFramebuffer"); + } + + if (config.is_rendering_lensDistortion) { + lensDistortFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lensDistortFramebuffer); + lensDistortTexture = GlStateManager.generateTexture(); GlStateManager.bindTexture(lensDistortTexture); - shader_post_lens_distort.useProgram(); - DrawUtils.drawStandardQuad2D(); - - DeferredStateManager.checkGLError("endDrawDeferred(): APPLY LENS DISTORTION"); - } - - // =========== BLIT WORLD DEPTH BUFFER TO OUTPUT ============= // - - if(EagRuntime.getPlatformType() == EnumPlatformType.DESKTOP) { - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - GlStateManager.enableDepth(); - GlStateManager.depthFunc(GL_ALWAYS); - GlStateManager.depthMask(true); - GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); - TextureCopyUtil.blitTextureDepth(); - GlStateManager.disableDepth(); - GlStateManager.depthFunc(GL_LEQUAL); - GlStateManager.depthMask(false); - }else { - _wglBindFramebuffer(_GL_READ_FRAMEBUFFER, lightingHDRFramebuffer); - _wglBindFramebuffer(_GL_DRAW_FRAMEBUFFER, null); - _wglBlitFramebuffer(0, 0, currentWidth, currentHeight, 0, 0, currentWidth, currentHeight, GL_DEPTH_BUFFER_BIT, GL_NEAREST); + setLinear(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lensDistortTexture), 0); + shader_post_lens_distort = PipelineShaderLensDistortion.compile(); + shader_post_lens_distort.loadUniforms(); + DeferredStateManager.checkGLError("Post: rebuild pipeline: lens distortion"); } - DeferredStateManager.checkGLError("endDrawDeferred(): BLIT WORLD DEPTH BUFFER TO OUTPUT"); + lastExposureUpdate = 0l; - // ================= OPTIONAL DEBUG OUTPUT =================== // + exposureBlendFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, exposureBlendFramebuffer); + exposureBlendTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(exposureBlendTexture); + setNearest(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 1, 1, GL_RED, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(exposureBlendTexture), 0); - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - drawDebugViewIfEnabled(); + DeferredStateManager.checkGLError("Post: rebuild pipeline: exposureBlendFramebuffer"); - for(int i = 0; i < lightSourceBuckets.length; ++i) { - lightSourceBuckets[i].clear(); + skybox = new SkyboxRenderer(new ResourceLocation("eagler:glsl/deferred/skybox.dat")); + try { + skybox.load(); + } catch (IOException e) { + throw new RuntimeException("Failed to load skybox!", e); } - DeferredStateManager.checkGLError("endDrawDeferred(): OPTIONAL DEBUG OUTPUT"); - } + pointLightMesh = new LightSourceMesh(new ResourceLocation("eagler:glsl/deferred/light_point_mesh.dat"), + "light_point_mesh"); + try { + pointLightMesh.load(); + } catch (IOException e) { + throw new RuntimeException("Failed to load point light mesh!", e); + } - static void uniformMatrixHelper(IUniformGL uniform, Matrix4f matrix) { - matrixCopyBuffer.clear(); - matrix.store(matrixCopyBuffer); - matrixCopyBuffer.flip(); - _wglUniformMatrix4fv(uniform, false, matrixCopyBuffer); - } + DeferredStateManager.checkGLError("Post: rebuild pipeline: meshes"); - static void uniformMatrixHelper(IUniformGL uniform, Matrix3f matrix) { - matrixCopyBuffer.clear(); - matrix.store(matrixCopyBuffer); - matrixCopyBuffer.flip(); - _wglUniformMatrix3fv(uniform, false, matrixCopyBuffer); - } + atmosphereHDRFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, atmosphereHDRFramebuffer); + atmosphereHDRFramebufferColorTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(atmosphereHDRFramebufferColorTexture); + setNearest(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, skybox.getAtmosLUTWidth(), + skybox.getAtmosLUTHeight(), GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(atmosphereHDRFramebufferColorTexture), 0); - public static void setNearest() { + envMapAtmosphereFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapAtmosphereFramebuffer); + envMapAtmosphereTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(envMapAtmosphereTexture); + setLinear(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 128, 256, GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(envMapAtmosphereTexture), 0); + + envMapSkyFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapSkyFramebuffer); + envMapSkyTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(envMapSkyTexture); + setLinear(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 128, 256, GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(envMapSkyTexture), 0); + + irradiancePhase = 0; + + atmosphereIrradianceFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, atmosphereIrradianceFramebuffer); + atmosphereIrradianceTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(atmosphereIrradianceTexture); + setLinear(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 32, 64, GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(atmosphereIrradianceTexture), 0); + GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT); + + skyIrradianceFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, skyIrradianceFramebuffer); + skyIrradianceTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(skyIrradianceTexture); + setLinear(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 32, 64, GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(skyIrradianceTexture), 0); + GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); + GlStateManager.clear(GL_COLOR_BUFFER_BIT); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: atmosphere"); + + moonTextures = GlStateManager.generateTexture(); + GlStateManager.bindTexture(moonTextures); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - } - - public static void setLinear() { - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - } + ByteBuffer copyBuffer = EagRuntime.allocateByteBuffer(262144); + int mip = 0; - public PipelineShaderGBufferDebugView useDebugViewShader(int idx) { - PipelineShaderGBufferDebugView dbgShader = shader_gbuffer_debug_view[idx]; - if(dbgShader == null) { - shader_gbuffer_debug_view[idx] = dbgShader = PipelineShaderGBufferDebugView.compile(idx); - dbgShader.loadUniforms(); + try (DataInputStream dis = new DataInputStream(mc.getResourceManager() + .getResource(new ResourceLocation("eagler:glsl/deferred/eagler_moon.bmp")).getInputStream())) { + while (dis.read() == 'E') { + int w = dis.readShort(); + int h = dis.readShort(); + copyBuffer.clear(); + for (int i = 0, l = w * h * 4; i < l; ++i) { + copyBuffer.put((byte) dis.read()); + } + copyBuffer.flip(); + _wglTexImage2D(GL_TEXTURE_2D, mip++, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, copyBuffer); + } + } catch (IOException ex) { + throw new RuntimeException("Could not load \"eagler_moon.bmp\"!", ex); + } finally { + EagRuntime.freeByteBuffer(copyBuffer); } - dbgShader.useProgram(); - return dbgShader; - } + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, mip - 1); - private void drawDebugViewIfEnabled() { - if(DebugFramebufferView.debugViewShown) { - DebugFramebufferView.renderDebugView(); - } - } + DeferredStateManager.checkGLError("Post: rebuild pipeline: moon"); - public void destroy() { - DeferredStateManager.checkGLError("Pre: destroy()"); - if(gBufferFramebuffer != null) { - _wglDeleteFramebuffer(gBufferFramebuffer); - gBufferFramebuffer = null; + CloudRenderWorker.initialize(); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: clouds"); + + fogDepthCopyBuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, fogDepthCopyBuffer); + fogDepthCopyTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(fogDepthCopyTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(fogDepthCopyTexture), 0); + + shader_atmosphere_fog = PipelineShaderGBufferFog.compile(false, true, config.is_rendering_lightShafts); + shader_atmosphere_fog.loadUniforms(); + shader_colored_fog_linear = PipelineShaderGBufferFog.compile(true, false, false); + shader_colored_fog_linear.loadUniforms(); + shader_colored_fog_exp = PipelineShaderGBufferFog.compile(false, false, false); + shader_colored_fog_exp.loadUniforms(); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: fog"); + + if (config.is_rendering_useEnvMap) { + envMapFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, envMapFramebuffer); + envMapColorTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(envMapColorTexture); + setLinear(); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 128, 256, GL_RGBA, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(envMapColorTexture), 0); + envMapDepthTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(envMapDepthTexture); + setNearest(); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT24, 128, 256, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, + (ByteBuffer) null); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(envMapDepthTexture), 0); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: env map"); } - if(gBufferDiffuseTexture != -1) { - GlStateManager.bindTexture(gBufferDiffuseTexture); - gBufferDiffuseTexture = -1; - } - if(gBufferNormalsTexture != -1) { - GlStateManager.bindTexture(gBufferNormalsTexture); - gBufferNormalsTexture = -1; - } - if(gBufferMaterialTexture != -1) { - GlStateManager.bindTexture(gBufferMaterialTexture); - gBufferMaterialTexture = -1; - } - if(gBufferDepthTexture != -1) { - GlStateManager.bindTexture(gBufferDepthTexture); - gBufferDepthTexture = -1; - } - if(sunShadowFramebuffer != null) { - _wglDeleteFramebuffer(sunShadowFramebuffer); - sunShadowFramebuffer = null; - } - if(sunShadowDepthBuffer != -1) { - GlStateManager.deleteTexture(sunShadowDepthBuffer); - sunShadowDepthBuffer = -1; - } - if(sunLightingShadowFramebuffer != null) { - _wglDeleteFramebuffer(sunLightingShadowFramebuffer); - sunLightingShadowFramebuffer = null; - } - if(sunLightingShadowTexture != -1) { - GlStateManager.deleteTexture(sunLightingShadowTexture); - sunLightingShadowTexture = -1; - } - if(ssaoGenerateFramebuffer != null) { - _wglDeleteFramebuffer(ssaoGenerateFramebuffer); - ssaoGenerateFramebuffer = null; - } - if(ssaoGenerateTexture != -1) { - GlStateManager.deleteTexture(ssaoGenerateTexture); - ssaoGenerateTexture = -1; - reprojectionTexWidth = -1; - reprojectionTexHeight = -1; - } - if(shader_ssao_generate != null) { - shader_ssao_generate.destroy(); - shader_ssao_generate = null; - } - if(ssaoNoiseTexture != -1) { - GlStateManager.deleteTexture(ssaoNoiseTexture); - ssaoNoiseTexture = -1; - } - for(int i = 0; i < 2; ++i) { - if(reprojectionControlFramebuffer[i] != null) { - _wglDeleteFramebuffer(reprojectionControlFramebuffer[i]); - reprojectionControlFramebuffer[i] = null; + + if (config.is_rendering_realisticWater) { + realisticWaterMaskFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterMaskFramebuffer); + realisticWaterMaskTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterMaskTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterMaskTexture), 0); + realisticWaterDepthBuffer = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterDepthBuffer); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterDepthBuffer), 0); + realisticWaterCombinedNormalsFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterCombinedNormalsFramebuffer); + realisticWaterCombinedNormalsTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterCombinedNormalsTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterCombinedNormalsTexture), 0); + realisticWaterRefractionTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterRefractionTexture); + setNearest(); + realisticWaterControlFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterControlFramebuffer); + realisticWaterControlReflectionTexture[0] = GlStateManager.generateTexture(); + realisticWaterControlReflectionTexture[1] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterControlReflectionTexture[0]); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterControlReflectionTexture[0]), 0); + realisticWaterControlHitVectorTexture[0] = GlStateManager.generateTexture(); + realisticWaterControlHitVectorTexture[1] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterControlHitVectorTexture[0]); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterControlHitVectorTexture[0]), 0); + GlStateManager.bindTexture(realisticWaterRefractionTexture); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterRefractionTexture), 0); + _wglDrawBuffers(new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1, _GL_COLOR_ATTACHMENT2 }); + for (int i = 0; i < 2; ++i) { + realisticWaterSSRFramebuffer[i] = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterSSRFramebuffer[i]); + GlStateManager.bindTexture(realisticWaterControlReflectionTexture[i]); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterControlReflectionTexture[i]), 0); + GlStateManager.bindTexture(realisticWaterControlHitVectorTexture[i]); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterControlHitVectorTexture[i]), 0); + _wglDrawBuffers(new int[] { _GL_COLOR_ATTACHMENT0, _GL_COLOR_ATTACHMENT1 }); } - if(reprojectionControlSSAOTexture[i] != -1) { - GlStateManager.deleteTexture(reprojectionControlSSAOTexture[i]); - reprojectionControlSSAOTexture[i] = -1; + realisticWaterDisplacementMapFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterDisplacementMapFramebuffer); + realisticWaterDisplacementMapTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterDisplacementMapTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterDisplacementMapTexture), 0); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 256, 256, GL_RED, true); + realisticWaterNormalMapFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, realisticWaterNormalMapFramebuffer); + realisticWaterNormalMapTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterNormalMapTexture); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(realisticWaterNormalMapTexture), 0); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_RG8, 256, 256, 0, _GL_RG, GL_UNSIGNED_BYTE, (ByteBuffer) null); + realisticWaterNoiseMap = GlStateManager.generateTexture(); + GlStateManager.bindTexture(realisticWaterNoiseMap); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + String realistic_water_noise_filename = "assets/eagler/glsl/deferred/realistic_water_noise.bmp"; + byte[] bitmapBytes = EagRuntime.getRequiredResourceBytes(realistic_water_noise_filename); + try { + if (bitmapBytes.length != 32768) { + throw new IOException("File is length " + bitmapBytes.length + ", expected " + 32768); + } + } catch (Throwable t) { + throw new RuntimeException("File \"" + realistic_water_noise_filename + "\" could not be loaded!", t); } - if(reprojectionSSRFramebuffer[i] != null) { - _wglDeleteFramebuffer(reprojectionSSRFramebuffer[i]); - reprojectionSSRFramebuffer[i] = null; - } - if(reprojectionSSRTexture[i] != -1) { - GlStateManager.deleteTexture(reprojectionSSRTexture[i]); - reprojectionSSRTexture[i] = -1; - } - if(reprojectionSSRHitVector[i] != -1) { - GlStateManager.deleteTexture(reprojectionSSRHitVector[i]); - reprojectionSSRHitVector[i] = -1; + ByteBuffer buf = EagRuntime.allocateByteBuffer(32768); + buf.put(bitmapBytes); + buf.flip(); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_RG8, 128, 128, 0, _GL_RG, GL_UNSIGNED_BYTE, buf); + EagRuntime.freeByteBuffer(buf); + shader_realistic_water_control = PipelineShaderRealisticWaterControl.compile(); + shader_realistic_water_control.loadUniforms(); + shader_realistic_water_noise = PipelineShaderRealisticWaterNoise.compile(); + shader_realistic_water_noise.loadUniforms(); + shader_realistic_water_normals = PipelineShaderRealisticWaterNormalMap.compile(); + shader_realistic_water_normals.loadUniforms(); + _wglUniform2f(shader_realistic_water_normals.uniforms.u_sampleOffset2f, 0.00390625f, 0.00390625f); + if (!config.is_rendering_raytracing) { + shader_reproject_ssr = PipelineShaderReprojSSR.compile(); + shader_reproject_ssr.loadUniforms(); } + + DeferredStateManager.checkGLError("Post: rebuild pipeline: realistic water"); } - if(lastFrameFramebuffer != null) { - _wglDeleteFramebuffer(lastFrameFramebuffer); - lastFrameFramebuffer = null; + + if (config.is_rendering_fxaa) { + tonemapOutputFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, tonemapOutputFramebuffer); + tonemapOutputTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(tonemapOutputTexture); + setNearest(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(tonemapOutputTexture), 0); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: fxaa"); } - if(lastFrameColorTexture != -1) { - GlStateManager.deleteTexture(lastFrameColorTexture); - lastFrameColorTexture = -1; + + if (config.is_rendering_lensFlares) { + LensFlareMeshRenderer.initialize(); + DeferredStateManager.checkGLError("Post: rebuild pipeline: lensFlares"); } - if(lastFrameDepthTexture != -1) { - GlStateManager.deleteTexture(lastFrameDepthTexture); - lastFrameDepthTexture = -1; + + recalcAtmosphereTimer = 0l; + + shader_skybox_atmosphere = PipelineShaderSkyboxAtmosphere.compile(); + shader_skybox_atmosphere.loadUniforms(); + + shader_skybox_render = PipelineShaderSkyboxRender.compile(false, true); + shader_skybox_render.loadUniforms(); + + shader_skybox_render_paraboloid = PipelineShaderSkyboxRender.compile(true, true); + shader_skybox_render_paraboloid.loadUniforms(); + + shader_skybox_render_paraboloid_noclouds = PipelineShaderSkyboxRender.compile(true, false); + shader_skybox_render_paraboloid_noclouds.loadUniforms(); + + shader_skybox_irradiance[0] = PipelineShaderSkyboxIrradiance.compile(0); + shader_skybox_irradiance[0].loadUniforms(); + + shader_skybox_irradiance[1] = PipelineShaderSkyboxIrradiance.compile(1); + shader_skybox_irradiance[1].loadUniforms(); + + shader_skybox_irradiance[2] = PipelineShaderSkyboxIrradiance.compile(2); + shader_skybox_irradiance[2].loadUniforms(); + + shader_moon_render = PipelineShaderMoonRender.compile(); + shader_moon_render.loadUniforms(); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: skybox shaders"); + + if (config.is_rendering_lightShafts) { + lightShaftsFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightShaftsFramebuffer); + lightShaftsTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(lightShaftsTexture); + setLinear(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lightShaftsTexture), 0); + shader_light_shafts_sample = PipelineShaderLightShaftsSample + .compile(config.is_rendering_shadowsSun_clamped); + shader_light_shafts_sample.loadUniforms(); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: light shafts"); } - if(gBufferQuarterFramebuffer != null) { - _wglDeleteFramebuffer(gBufferQuarterFramebuffer); - gBufferQuarterFramebuffer = null; - } - if(gBufferQuarterDepthTexture != -1) { - GlStateManager.deleteTexture(gBufferQuarterDepthTexture); - gBufferQuarterDepthTexture = -1; - } - if(lastFrameGBufferFramebuffer != null) { - _wglDeleteFramebuffer(lastFrameGBufferFramebuffer); - lastFrameGBufferFramebuffer = null; - } - if(lastFrameGBufferDepthTexture != -1) { - GlStateManager.deleteTexture(lastFrameGBufferDepthTexture); - lastFrameGBufferDepthTexture = -1; - } - if(lightingHDRFramebuffer != null) { - _wglDeleteFramebuffer(lightingHDRFramebuffer); - lightingHDRFramebuffer = null; - } - if(lightingHDRFramebufferColorTexture != -1) { - GlStateManager.deleteTexture(lightingHDRFramebufferColorTexture); - lightingHDRFramebufferColorTexture = -1; - } - if(lightingHDRFramebufferDepthTexture != -1) { - GlStateManager.deleteTexture(lightingHDRFramebufferDepthTexture); - lightingHDRFramebufferDepthTexture = -1; - } - if(handRenderFramebuffer != null) { - _wglDeleteFramebuffer(handRenderFramebuffer); - handRenderFramebuffer = null; - } - if(handRenderFramebufferDepthTexture != -1) { - GlStateManager.deleteTexture(handRenderFramebufferDepthTexture); - handRenderFramebufferDepthTexture = -1; - } - if(atmosphereHDRFramebuffer != null) { - _wglDeleteFramebuffer(atmosphereHDRFramebuffer); - atmosphereHDRFramebuffer = null; - } - if(atmosphereHDRFramebufferColorTexture != -1) { - GlStateManager.deleteTexture(atmosphereHDRFramebufferColorTexture); - atmosphereHDRFramebufferColorTexture = -1; - } - if(envMapAtmosphereFramebuffer != null) { - _wglDeleteFramebuffer(envMapAtmosphereFramebuffer); - envMapAtmosphereFramebuffer = null; - } - if(envMapAtmosphereTexture != -1) { - GlStateManager.deleteTexture(envMapAtmosphereTexture); - envMapAtmosphereTexture = -1; - } - if(envMapSkyFramebuffer != null) { - _wglDeleteFramebuffer(envMapSkyFramebuffer); - envMapSkyFramebuffer = null; - } - if(envMapSkyTexture != -1) { - GlStateManager.deleteTexture(envMapSkyTexture); - envMapSkyTexture = -1; - } - if(moonTextures != -1) { - GlStateManager.deleteTexture(moonTextures); - moonTextures = -1; - } - if(envMapFramebuffer != null) { - _wglDeleteFramebuffer(envMapFramebuffer); - envMapFramebuffer = null; - } - if(envMapColorTexture != -1) { - GlStateManager.deleteTexture(envMapColorTexture); - envMapColorTexture = -1; - } - if(envMapDepthTexture != -1) { - GlStateManager.deleteTexture(envMapDepthTexture); - envMapDepthTexture = -1; - } - if(atmosphereIrradianceFramebuffer != null) { - _wglDeleteFramebuffer(atmosphereIrradianceFramebuffer); - atmosphereIrradianceFramebuffer = null; - } - if(atmosphereIrradianceTexture != -1) { - GlStateManager.deleteTexture(atmosphereIrradianceTexture); - atmosphereIrradianceTexture = -1; - } - if(skyIrradianceFramebuffer != null) { - _wglDeleteFramebuffer(skyIrradianceFramebuffer); - skyIrradianceFramebuffer = null; - } - if(skyIrradianceTexture != -1) { - GlStateManager.deleteTexture(skyIrradianceTexture); - skyIrradianceTexture = -1; - } - if(tonemapOutputFramebuffer != null) { - _wglDeleteFramebuffer(tonemapOutputFramebuffer); - tonemapOutputFramebuffer = null; - } - if(tonemapOutputTexture != -1) { - GlStateManager.deleteTexture(tonemapOutputTexture); - tonemapOutputTexture = -1; - } - if(lensDistortFramebuffer != null) { - _wglDeleteFramebuffer(lensDistortFramebuffer); - lensDistortFramebuffer = null; - } - if(lensDistortTexture != -1) { - GlStateManager.deleteTexture(lensDistortTexture); - lensDistortTexture = -1; - } - if(lumaAvgDownscaleFramebuffers != null) { - for(int i = 0; i < lumaAvgDownscaleFramebuffers.length; ++i) { - _wglDeleteFramebuffer(lumaAvgDownscaleFramebuffers[i]); - } - lumaAvgDownscaleFramebuffers = null; - } - if(lumaAvgDownscaleTexture != null) { - for(int i = 0; i < lumaAvgDownscaleTexture.length; ++i) { - GlStateManager.deleteTexture(lumaAvgDownscaleTexture[i]); - } - lumaAvgDownscaleTexture = null; - } - if(exposureBlendFramebuffer != null) { - _wglDeleteFramebuffer(exposureBlendFramebuffer); - exposureBlendFramebuffer = null; - } - if(exposureBlendTexture != -1) { - GlStateManager.deleteTexture(exposureBlendTexture); - exposureBlendTexture = -1; - } - if(bloomBrightPassFramebuffer != null) { - _wglDeleteFramebuffer(bloomBrightPassFramebuffer); - bloomBrightPassFramebuffer = null; - } - if(bloomBrightPassTexture != -1) { + + if (config.is_rendering_bloom) { + bloomBrightPassFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomBrightPassFramebuffer); + bloomBrightPassTexture = GlStateManager.generateTexture(); GlStateManager.bindTexture(bloomBrightPassTexture); - bloomBrightPassTexture = -1; + setNearest(); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(bloomBrightPassTexture), 0); + bloomDownscaleAFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleAFramebuffer); + bloomDownscaleATexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(bloomDownscaleATexture); + setLinear(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(bloomDownscaleATexture), 0); + bloomDownscaleBFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomDownscaleBFramebuffer); + bloomDownscaleBTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(bloomDownscaleBTexture); + setLinear(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(bloomDownscaleBTexture), 0); + bloomHBlurFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomHBlurFramebuffer); + bloomHBlurTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(bloomHBlurTexture); + setNearest(); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(bloomHBlurTexture), 0); + bloomVBlurFramebuffer = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, bloomVBlurFramebuffer); + bloomVBlurTexture = GlStateManager.generateTexture(); + GlStateManager.bindTexture(bloomVBlurTexture); + setLinear(); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(bloomVBlurTexture), 0); + shader_post_bloom_bright = PipelineShaderBloomBrightPass.compile(); + shader_post_bloom_bright.loadUniforms(); + shader_post_bloom_blur = PipelineShaderBloomBlurPass.compile(); + shader_post_bloom_blur.loadUniforms(); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: bloom"); } - if(bloomHBlurFramebuffer != null) { - _wglDeleteFramebuffer(bloomHBlurFramebuffer); - bloomHBlurFramebuffer = null; - } - if(bloomHBlurTexture != -1) { - GlStateManager.deleteTexture(bloomHBlurTexture); - bloomHBlurTexture = -1; - } - if(bloomVBlurFramebuffer != null) { - _wglDeleteFramebuffer(bloomVBlurFramebuffer); - bloomVBlurFramebuffer = null; - } - if(bloomVBlurTexture != -1) { - GlStateManager.deleteTexture(bloomVBlurTexture); - bloomVBlurTexture = -1; - } - if(bloomDownscaleAFramebuffer != null) { - _wglDeleteFramebuffer(bloomDownscaleAFramebuffer); - bloomDownscaleAFramebuffer = null; - } - if(bloomDownscaleATexture != -1) { - GlStateManager.deleteTexture(bloomDownscaleATexture); - bloomDownscaleATexture = -1; - } - if(bloomDownscaleBFramebuffer != null) { - _wglDeleteFramebuffer(bloomDownscaleBFramebuffer); - bloomDownscaleBFramebuffer = null; - } - if(bloomDownscaleBTexture != -1) { - GlStateManager.deleteTexture(bloomDownscaleBTexture); - bloomDownscaleBTexture = -1; - } - if(sunOcclusionValueFramebuffer != null) { - _wglDeleteFramebuffer(sunOcclusionValueFramebuffer); - sunOcclusionValueFramebuffer = null; - } - if(sunOcclusionValueTexture != -1) { - GlStateManager.deleteTexture(sunOcclusionValueTexture); - sunOcclusionValueTexture = -1; - } - if(dither8x8Texture != -1) { - GlStateManager.deleteTexture(dither8x8Texture); - dither8x8Texture = -1; - } - if(shader_deferred_combine != null) { - shader_deferred_combine.destroy(); - shader_deferred_combine = null; - } - if(shader_hand_depth_mask != null) { - shader_hand_depth_mask.destroy(); - shader_hand_depth_mask = null; - } - if(brdfTexture != -1) { - GlStateManager.deleteTexture(brdfTexture); - brdfTexture = -1; - } - if(shader_lighting_sun != null) { - shader_lighting_sun.destroy(); - shader_lighting_sun = null; - } - if(shader_shadows_sun != null) { - shader_shadows_sun.destroy(); - shader_shadows_sun = null; - } - if(shader_light_shafts_sample != null) { - shader_light_shafts_sample.destroy(); - shader_light_shafts_sample = null; - } - if(skybox != null) { - skybox.destroy(); - skybox = null; - } - if(pointLightMesh != null) { - pointLightMesh.destroy(); - pointLightMesh = null; - } - if(shader_skybox_atmosphere != null) { - shader_skybox_atmosphere.destroy(); - shader_skybox_atmosphere = null; - } - if(shader_skybox_render != null) { - shader_skybox_render.destroy(); - shader_skybox_render = null; - } - if(shader_lighting_point != null) { - shader_lighting_point.destroy(); - shader_lighting_point = null; - } - if(shader_post_lens_distort != null) { - shader_post_lens_distort.destroy(); - shader_post_lens_distort = null; - } - if(shader_post_tonemap != null) { - shader_post_tonemap.destroy(); - shader_post_tonemap = null; - } - if(shader_post_exposure_avg != null) { - shader_post_exposure_avg.destroy(); - shader_post_exposure_avg = null; - } - if(shader_post_exposure_avg_luma != null) { - shader_post_exposure_avg_luma.destroy(); - shader_post_exposure_avg_luma = null; - } - if(shader_post_exposure_final != null) { - shader_post_exposure_final.destroy(); - shader_post_exposure_final = null; - } - if(shader_post_bloom_bright != null) { - shader_post_bloom_bright.destroy(); - shader_post_bloom_bright = null; - } - if(shader_post_bloom_blur != null) { - shader_post_bloom_blur.destroy(); - shader_post_bloom_blur = null; - } - if(shader_lens_sun_occlusion != null) { - shader_lens_sun_occlusion.destroy(); - shader_lens_sun_occlusion = null; - } - if(shader_realistic_water_control != null) { - shader_realistic_water_control.destroy(); - shader_realistic_water_control = null; - } - if(shader_realistic_water_noise != null) { - shader_realistic_water_noise.destroy(); - shader_realistic_water_noise = null; - } - if(shader_realistic_water_normals != null) { - shader_realistic_water_normals.destroy(); - shader_realistic_water_normals = null; - } - if(shader_post_fxaa != null) { - shader_post_fxaa.destroy(); - shader_post_fxaa = null; - } - if(shader_skybox_render_paraboloid != null) { - shader_skybox_render_paraboloid.destroy(); - shader_skybox_render_paraboloid = null; - } - if(shader_skybox_render_paraboloid_noclouds != null) { - shader_skybox_render_paraboloid_noclouds.destroy(); - shader_skybox_render_paraboloid_noclouds = null; - } - if(shader_skybox_render_end != null) { - shader_skybox_render_end.destroy(); - shader_skybox_render_end = null; - } - for(int i = 0; i < 3; ++i) { - if(shader_skybox_irradiance[i] != null) { - shader_skybox_irradiance[i].destroy(); - shader_skybox_irradiance[i] = null; + + gbufferEffectRenderer.initialize(); + forwardEffectRenderer.initialize(config.is_rendering_dynamicLights, config.is_rendering_shadowsSun_clamped); + + if (config.is_rendering_dynamicLights) { + shader_lighting_point = PipelineShaderLightingPoint.compile(false); + shader_lighting_point.loadUniforms(); + + lightingBufferSliceLength = uboAlign(LIGHTING_BUFFER_LENGTH); + + chunkLightingDataCopyBuffer = EagRuntime.allocateByteBuffer(LIGHTING_BUFFER_LENGTH); + for (int i = 0; i < LIGHTING_BUFFER_LENGTH; i += 4) { + chunkLightingDataCopyBuffer.putInt(0); } + chunkLightingDataCopyBuffer.flip(); + + buffer_chunkLightingData = _wglGenBuffers(); + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); + int cnt = lightSourceBucketsWidth * lightSourceBucketsHeight * lightSourceBucketsWidth; + _wglBufferData(_GL_UNIFORM_BUFFER, cnt * lightingBufferSliceLength, GL_DYNAMIC_DRAW); + + buffer_chunkLightingDataZero = _wglGenBuffers(); + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); + _wglBufferData(_GL_UNIFORM_BUFFER, chunkLightingDataCopyBuffer, GL_STATIC_DRAW); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: dynamic lights"); } - if(shader_colored_fog_linear != null) { - shader_colored_fog_linear.destroy(); - shader_colored_fog_linear = null; + + buffer_worldLightingData = _wglGenBuffers(); + EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); + worldLightingDataCopyBuffer = EagRuntime.allocateByteBuffer(304); + for (int i = 0; i < 76; ++i) { + worldLightingDataCopyBuffer.putInt(0); } - if(shader_colored_fog_exp != null) { - shader_colored_fog_exp.destroy(); - shader_colored_fog_exp = null; + worldLightingDataCopyBuffer.flip(); + _wglBufferData(_GL_UNIFORM_BUFFER, worldLightingDataCopyBuffer, GL_DYNAMIC_DRAW); + + DeferredStateManager.checkGLError("Post: rebuild pipeline: world lighting data"); + + FixedFunctionPipeline.loadExtensionPipeline(deferredExtPipeline); + + if (!EaglercraftGPU.checkHDRFramebufferSupport(16)) { + logger.warn( + "16-bit HDR (floating point) framebuffers are not supported on this device, 32-bit framebuffers will be used instead which may slow the game down"); } - if(shader_atmosphere_fog != null) { - shader_atmosphere_fog.destroy(); - shader_atmosphere_fog = null; - } - if(shader_moon_render != null) { - shader_moon_render.destroy(); - shader_moon_render = null; - } - if(shader_reproject_control != null) { - shader_reproject_control.destroy(); - shader_reproject_control = null; - } - if(shader_reproject_ssr != null) { - shader_reproject_ssr.destroy(); - shader_reproject_ssr = null; - } - if(realisticWaterMaskFramebuffer != null) { - _wglDeleteFramebuffer(realisticWaterMaskFramebuffer); - realisticWaterMaskFramebuffer = null; - } - if(realisticWaterMaskTexture != -1) { - GlStateManager.deleteTexture(realisticWaterMaskTexture); - realisticWaterMaskTexture = -1; - } - if(realisticWaterDepthBuffer != -1) { - GlStateManager.deleteTexture(realisticWaterDepthBuffer); - realisticWaterDepthBuffer = -1; - } - if(realisticWaterCombinedNormalsFramebuffer != null) { - _wglDeleteFramebuffer(realisticWaterCombinedNormalsFramebuffer); - realisticWaterCombinedNormalsFramebuffer = null; - } - if(realisticWaterCombinedNormalsTexture != -1) { - GlStateManager.deleteTexture(realisticWaterCombinedNormalsTexture); - realisticWaterCombinedNormalsTexture = -1; - } - if(realisticWaterRefractionTexture != -1) { - GlStateManager.deleteTexture(realisticWaterRefractionTexture); - realisticWaterRefractionTexture = -1; - } - if(realisticWaterControlFramebuffer != null) { - _wglDeleteFramebuffer(realisticWaterControlFramebuffer); - realisticWaterControlFramebuffer = null; - } - for(int i = 0; i < 2; ++i) { - if(realisticWaterSSRFramebuffer[i] != null) { - _wglDeleteFramebuffer(realisticWaterSSRFramebuffer[i]); - realisticWaterSSRFramebuffer[i] = null; - } - if(realisticWaterControlReflectionTexture[i] != -1) { - GlStateManager.deleteTexture(realisticWaterControlReflectionTexture[i]); - realisticWaterControlReflectionTexture[i] = -1; - } - if(realisticWaterControlHitVectorTexture[i] != -1) { - GlStateManager.deleteTexture(realisticWaterControlHitVectorTexture[i]); - realisticWaterControlHitVectorTexture[i] = -1; - } - } - if(realisticWaterNormalMapFramebuffer != null) { - _wglDeleteFramebuffer(realisticWaterNormalMapFramebuffer); - realisticWaterNormalMapFramebuffer = null; - } - if(realisticWaterNormalMapTexture != -1) { - GlStateManager.deleteTexture(realisticWaterNormalMapTexture); - realisticWaterNormalMapTexture = -1; - } - if(realisticWaterDisplacementMapFramebuffer != null) { - _wglDeleteFramebuffer(realisticWaterDisplacementMapFramebuffer); - realisticWaterDisplacementMapFramebuffer = null; - } - if(realisticWaterDisplacementMapTexture != -1) { - GlStateManager.deleteTexture(realisticWaterDisplacementMapTexture); - realisticWaterDisplacementMapTexture = -1; - } - if(realisticWaterNoiseMap != -1) { - GlStateManager.deleteTexture(realisticWaterNoiseMap); - realisticWaterNoiseMap = -1; - } - if(buffer_chunkLightingData != null) { - _wglDeleteBuffers(buffer_chunkLightingData); - buffer_chunkLightingData = null; - } - if(buffer_chunkLightingDataZero != null) { - _wglDeleteBuffers(buffer_chunkLightingDataZero); - buffer_chunkLightingDataZero = null; - } - if(buffer_worldLightingData != null) { - _wglDeleteBuffers(buffer_worldLightingData); - buffer_worldLightingData = null; - } - if(worldLightingDataCopyBuffer != null) { - EagRuntime.freeByteBuffer(worldLightingDataCopyBuffer); - worldLightingDataCopyBuffer = null; - } - if(chunkLightingDataCopyBuffer != null) { - EagRuntime.freeByteBuffer(chunkLightingDataCopyBuffer); - chunkLightingDataCopyBuffer = null; - } - for(int i = 0; i < lightSourceBuckets.length; ++i) { - lightSourceBuckets[i].clear(); - lightSourceBucketSerials[i] = -1; - lightSourceRenderPosSerials[i] = -1; - } - currentLightSourceBucket = null; - currentLightSourceBucketId = -1; - currentBoundLightSourceBucket = null; - isChunkLightingEnabled = false; - for(int i = 0; i < shader_gbuffer_debug_view.length; ++i) { - if(shader_gbuffer_debug_view[i] != null) { - shader_gbuffer_debug_view[i].destroy(); - shader_gbuffer_debug_view[i] = null; - } - } - gbufferEffectRenderer.destroy(); - forwardEffectRenderer.destroy(); - DynamicLightManager.destroyAll(); - LensFlareMeshRenderer.destroy(); - CloudRenderWorker.destroy(); - FixedFunctionPipeline.loadExtensionPipeline(null); - DeferredStateManager.checkGLError("Post: destroy()"); + + _wglBindFramebuffer(_GL_FRAMEBUFFER, null); + DeferredStateManager.checkGLError("Post: rebuild pipeline"); } public void resetContextStateAfterException() { @@ -4013,58 +3900,439 @@ public class EaglerDeferredPipeline { GlStateManager.loadIdentity(); GlStateManager.matrixMode(GL_MODELVIEW); GlStateManager.loadIdentity(); - if(config.is_rendering_shadowsSun_clamped > 0 && config.is_rendering_shadowsSmoothed) { + if (config.is_rendering_shadowsSun_clamped > 0 && config.is_rendering_shadowsSmoothed) { GlStateManager.bindTexture(sunShadowDepthBuffer); _wglTexParameteri(GL_TEXTURE_2D, _GL_TEXTURE_COMPARE_MODE, _GL_COMPARE_REF_TO_TEXTURE); setNearest(); } } - public static final boolean isSupported() { - return EaglercraftGPU.checkOpenGLESVersion() >= 300 && EaglercraftGPU.checkHasHDRFramebufferSupportWithFilter(); + public void resize(int w, int h) { + if (w == currentWidth && h == currentHeight) { + return; + } + + DeferredStateManager.checkGLError("Pre: resize pipeline to " + w + " x " + h); + + GlStateManager.bindTexture(gBufferDiffuseTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + GlStateManager.bindTexture(gBufferNormalsTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + GlStateManager.bindTexture(gBufferMaterialTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + + GlStateManager.bindTexture(gBufferDepthTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, + (ByteBuffer) null); + + DeferredStateManager.checkGLError("Post: resize pipeline: gbuffer"); + + if (config.is_rendering_shadowsSun_clamped > 0) { + GlStateManager.bindTexture(sunLightingShadowTexture); + if (config.is_rendering_shadowsColored) { + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + } else { + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, (ByteBuffer) null); + } + DeferredStateManager.checkGLError("Post: resize pipeline: sunLightingShadowTexture"); + } + + reprojectionStartup = 0; + reprojectionTexWidth = w >> 1; + reprojectionTexHeight = h >> 1; + + shader_deferred_combine.useProgram(); + _wglUniform2f(shader_deferred_combine.uniforms.u_halfResolutionPixelAlignment2f, + (float) w / (reprojectionTexWidth << 1), (float) h / (reprojectionTexHeight << 1)); + + if (config.is_rendering_ssao) { + GlStateManager.bindTexture(ssaoGenerateTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, reprojectionTexWidth, reprojectionTexHeight, 0, GL_RED, + GL_UNSIGNED_BYTE, (ByteBuffer) null); + DeferredStateManager.checkGLError("Post: resize pipeline: ssao"); + } + + if (reprojectionEngineEnable || config.is_rendering_realisticWater) { + GlStateManager.bindTexture(lastFrameColorTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, + GL_RGBA, true); + GlStateManager.bindTexture(lastFrameDepthTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, reprojectionTexWidth, reprojectionTexHeight, 0, + _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer) null); + GlStateManager.bindTexture(lastFrameGBufferDepthTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, + (ByteBuffer) null); + DeferredStateManager.checkGLError("Post: resize pipeline: lastFrame"); + } + + if (config.is_rendering_raytracing || config.is_rendering_realisticWater) { + shader_reproject_ssr.useProgram(); + _wglUniform4f(shader_reproject_ssr.uniforms.u_pixelAlignment4f, reprojectionTexWidth, reprojectionTexHeight, + w, h); + } + + if (reprojectionEngineEnable) { + GlStateManager.bindTexture(gBufferQuarterDepthTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, reprojectionTexWidth, reprojectionTexHeight, 0, + _GL_DEPTH_COMPONENT, GL_FLOAT, (ByteBuffer) null); + + for (int i = 0; i < 2; ++i) { + if (config.is_rendering_ssao) { + GlStateManager.bindTexture(reprojectionControlSSAOTexture[i]); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, reprojectionTexWidth, reprojectionTexHeight, 0, GL_RGBA, + GL_UNSIGNED_BYTE, (ByteBuffer) null); + } + if (config.is_rendering_raytracing) { + GlStateManager.bindTexture(reprojectionSSRTexture[i]); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, + reprojectionTexHeight, GL_RGBA, true); + GlStateManager.bindTexture(reprojectionSSRHitVector[i]); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, + reprojectionTexHeight, GL_RGBA, true); + } + } + + shader_reproject_control.useProgram(); + _wglUniform4f(shader_reproject_control.uniforms.u_pixelAlignment4f, reprojectionTexWidth, + reprojectionTexHeight, w, h); + DeferredStateManager.checkGLError("Post: resize pipeline: reprojectionEngineEnable"); + } + + if (config.is_rendering_realisticWater) { + GlStateManager.bindTexture(realisticWaterMaskTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + GlStateManager.bindTexture(realisticWaterDepthBuffer); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, + (ByteBuffer) null); + GlStateManager.bindTexture(realisticWaterCombinedNormalsTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + GlStateManager.bindTexture(realisticWaterRefractionTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, reprojectionTexHeight, + GL_RGBA, true); + for (int i = 0; i < 2; ++i) { + GlStateManager.bindTexture(realisticWaterControlReflectionTexture[i]); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, + reprojectionTexHeight, GL_RGBA, true); + GlStateManager.bindTexture(realisticWaterControlHitVectorTexture[i]); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, reprojectionTexWidth, + reprojectionTexHeight, GL_RGBA, true); + } + + shader_realistic_water_control.useProgram(); + _wglUniform4f(shader_realistic_water_control.uniforms.u_pixelAlignment4f, reprojectionTexWidth, + reprojectionTexHeight, w, h); + DeferredStateManager.checkGLError("Post: resize pipeline: realisticWater"); + } + + if (config.is_rendering_lightShafts) { + GlStateManager.bindTexture(lightShaftsTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_R8, reprojectionTexWidth, reprojectionTexHeight, 0, GL_RED, + GL_UNSIGNED_BYTE, (ByteBuffer) null); + DeferredStateManager.checkGLError("Post: resize pipeline: lightShafts"); + } + + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, w, h, GL_RGBA, true); // USE RGBA! WebGL won't + // render to RGB16F + + GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, + (ByteBuffer) null); + + GlStateManager.bindTexture(handRenderFramebufferDepthTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, + (ByteBuffer) null); + + DeferredStateManager.checkGLError("Post: resize pipeline: lightingHDRFramebuffer"); + + GlStateManager.bindTexture(fogDepthCopyTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, _GL_DEPTH_COMPONENT32F, w, h, 0, _GL_DEPTH_COMPONENT, GL_FLOAT, + (ByteBuffer) null); + + DeferredStateManager.checkGLError("Post: resize pipeline: fogDepthCopyTexture"); + + if (config.is_rendering_lensDistortion) { + GlStateManager.bindTexture(lensDistortTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + DeferredStateManager.checkGLError("Post: resize pipeline: lensDistortion"); + } + + if (config.is_rendering_fxaa) { + GlStateManager.bindTexture(tonemapOutputTexture); + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, (ByteBuffer) null); + DeferredStateManager.checkGLError("Post: resize pipeline: fxaa"); + } + + if (config.is_rendering_bloom) { + int bloomStageW = w; + int bloomStageH = h; + GlStateManager.bindTexture(bloomBrightPassTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); + bloomBrightPassTextureW = bloomStageW; + bloomBrightPassTextureH = bloomStageH; + bloomDownscaleATextureW = bloomDownscaleATextureH = 0; + bloomDownscaleBTextureW = bloomDownscaleBTextureH = 0; + if (bloomStageW > 150 && bloomStageH > 85) { + setLinear(); + bloomStageW >>= 1; + bloomStageH >>= 1; + if (bloomStageW > 150 && bloomStageH > 85) { + GlStateManager.bindTexture(bloomDownscaleATexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, + true); + bloomDownscaleATextureW = bloomStageW; + bloomDownscaleATextureH = bloomStageH; + bloomStageW >>= 1; + bloomStageH >>= 1; + if (bloomStageW > 150 && bloomStageH > 85) { + GlStateManager.bindTexture(bloomDownscaleBTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, + GL_RGBA, true); + bloomDownscaleBTextureW = bloomStageW; + bloomDownscaleBTextureH = bloomStageH; + bloomStageW >>= 1; + bloomStageH >>= 1; + } + } + } else { + setNearest(); + } + GlStateManager.bindTexture(bloomHBlurTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); + GlStateManager.bindTexture(bloomVBlurTexture); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, bloomStageW, bloomStageH, GL_RGBA, true); + bloomBlurTextureW = bloomStageW; + bloomBlurTextureH = bloomStageH; + DeferredStateManager.checkGLError("Post: resize pipeline: bloom"); + } + + if (lumaAvgDownscaleFramebuffers != null) { + for (int i = 0; i < lumaAvgDownscaleFramebuffers.length; ++i) { + _wglDeleteFramebuffer(lumaAvgDownscaleFramebuffers[i]); + } + } + + if (lumaAvgDownscaleTexture != null) { + for (int i = 0; i < lumaAvgDownscaleTexture.length; ++i) { + GlStateManager.deleteTexture(lumaAvgDownscaleTexture[i]); + } + } + + int j = 0; + int k = h > w ? w : h; + while (k > 8) { + ++j; + k >>= 2; + } + + lumaAvgDownscaleFramebuffers = new IFramebufferGL[j]; + lumaAvgDownscaleTexture = new int[j]; + + int kw = w; + int kh = h; + int kw2, kh2; + for (int i = 0; i < j; ++i) { + kw2 = kw >> 2; + kh2 = kh >> 2; + lumaAvgDownscaleFramebuffers[i] = _wglCreateFramebuffer(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lumaAvgDownscaleFramebuffers[i]); + lumaAvgDownscaleTexture[i] = GlStateManager.generateTexture(); + GlStateManager.bindTexture(lumaAvgDownscaleTexture[i]); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, i == j - 1 ? GL_NEAREST : GL_LINEAR); + _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, i == j - 1 ? GL_NEAREST : GL_LINEAR); + EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, ((kw & 3) != 0) ? (kw2 + 1) : kw2, + ((kh & 3) != 0) ? (kh2 + 1) : kh2, GL_RED, true); + _wglFramebufferTexture2D(_GL_FRAMEBUFFER, _GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, + EaglercraftGPU.getNativeTexture(lumaAvgDownscaleTexture[i]), 0); + kw = kw2; + kh = kh2; + } + + currentWidth = w; + currentHeight = h; + + DeferredStateManager.checkGLError("Post: resize pipeline: lumaAvg"); } - public static final String getReasonUnsupported() { - if(EaglercraftGPU.checkOpenGLESVersion() < 300) { - return I18n.format("shaders.gui.unsupported.reason.oldOpenGLVersion"); - }else if(!EaglercraftGPU.checkHasHDRFramebufferSupportWithFilter()) { - return I18n.format("shaders.gui.unsupported.reason.hdrFramebuffer"); - }else { - return null; + public void saveReprojData() { + DeferredStateManager.checkGLError("Pre: saveReprojData()"); + if (reprojectionEngineEnable || config.is_rendering_realisticWater) { + + // =========== SAVE REPROJECTION DATA FOR NEXT FRAME ============= // + + tmpMatrixLastFrameProj.load(DeferredStateManager.projMatrix); + tmpMatrixLastFrameViewReproject.load(tmpMatrixViewReproject); + tmpMatrixLastFrameViewProjReproject.load(tmpMatrixViewProjReproject); + + GlStateManager.disableBlend(); + _wglBindFramebuffer(_GL_FRAMEBUFFER, lastFrameFramebuffer); + GlStateManager.viewport(0, 0, reprojectionTexWidth, reprojectionTexHeight); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(lightingHDRFramebufferColorTexture); + _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); + TextureCopyUtil.alignPixelsTopLeft(reprojectionTexWidth << 1, reprojectionTexHeight << 1, + reprojectionTexWidth, reprojectionTexHeight); + TextureCopyUtil.blitTexture(); + GlStateManager.bindTexture(lightingHDRFramebufferDepthTexture); + GlStateManager.enableDepth(); + GlStateManager.depthFunc(GL_ALWAYS); + GlStateManager.depthMask(true); + _wglDrawBuffers(GL_NONE); + TextureCopyUtil.alignPixelsTopLeft(reprojectionTexWidth << 1, reprojectionTexHeight << 1, + reprojectionTexWidth, reprojectionTexHeight); + TextureCopyUtil.blitTextureDepth(); + GlStateManager.disableDepth(); + GlStateManager.depthMask(false); + GlStateManager.depthFunc(GL_LEQUAL); + _wglDrawBuffers(_GL_COLOR_ATTACHMENT0); + + reprojectionPhase = (reprojectionPhase + 1) & 1; + ++reprojectionStartup; + + _wglBindFramebuffer(_GL_FRAMEBUFFER, lightingHDRFramebuffer); + GlStateManager.viewport(0, 0, currentWidth, currentHeight); + GlStateManager.enableBlend(); + } + DeferredStateManager.checkGLError("Post: saveReprojData()"); + } + + public void setForwardRenderLightFactors(float block, float sky, float sun, float dynamic) { + worldLightingDataCopyBuffer.clear(); + worldLightingDataCopyBuffer.putFloat(block); + worldLightingDataCopyBuffer.putFloat(sky); + worldLightingDataCopyBuffer.putFloat(sun); + worldLightingDataCopyBuffer.putFloat(dynamic); + worldLightingDataCopyBuffer.flip(); + EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); + _wglBufferSubData(_GL_UNIFORM_BUFFER, 96, worldLightingDataCopyBuffer); + } + + public void setPartialTicks(float partialTicks_) { + partialTicks = partialTicks_; + } + + public void setRenderPosGlobal(double renderPosX, double renderPosY, double renderPosZ) { + if (renderPosX != currentRenderX || renderPosY != currentRenderY || renderPosZ != currentRenderZ + || currentRenderPosSerial == 0) { + currentRenderX = renderPosX; + currentRenderY = renderPosY; + currentRenderZ = renderPosZ; + ++currentRenderPosSerial; } } - public static final void renderSuspended() { - _wglBindFramebuffer(_GL_FRAMEBUFFER, null); - GlStateManager.globalEnableBlend(); - Minecraft mc = Minecraft.getMinecraft(); - GlStateManager.viewport(0, 0, mc.displayWidth, mc.displayHeight); - GlStateManager.clearColor(0.5f, 0.0f, 0.0f, 1.0f); - GlStateManager.clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.pushMatrix(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.pushMatrix(); - ScaledResolution scaledresolution = mc.scaledResolution; - int w = scaledresolution.getScaledWidth(); - mc.entityRenderer.setupOverlayRendering(); - GlStateManager.enableAlpha(); - GlStateManager.pushMatrix(); - String str = "Shaders Suspended"; - GlStateManager.translate((w - mc.fontRendererObj.getStringWidth(str) * 2) * 0.5f, 45.0f, 0.0f); - GlStateManager.scale(2.0f, 2.0f, 2.0f); - mc.fontRendererObj.drawStringWithShadow(str, 0, 0, 0xFFFFFF); - GlStateManager.popMatrix(); - GlStateManager.pushMatrix(); - str = "(check console)"; - GlStateManager.translate((w - mc.fontRendererObj.getStringWidth(str) * 1.5) * 0.5f, 80.0f, 0.0f); - GlStateManager.scale(1.5f, 1.5f, 1.5f); - mc.fontRendererObj.drawStringWithShadow(str, 0, 0, 0xFFFFFF); - GlStateManager.popMatrix(); - GlStateManager.matrixMode(GL_PROJECTION); - GlStateManager.popMatrix(); - GlStateManager.matrixMode(GL_MODELVIEW); - GlStateManager.popMatrix(); - EagUtils.sleep(10l); + private void truncateOverflowingLightBuffers() { + for (int i = 0; i < this.lightSourceBuckets.length; ++i) { + List lst = this.lightSourceBuckets[i]; + int k = lst.size(); + if (k > MAX_LIGHTS_PER_CHUNK) { + lst.sort(comparatorLightRadius); + for (int l = MAX_LIGHTS_PER_CHUNK - 1; l >= MAX_LIGHTS_PER_CHUNK; --l) { + lst.remove(l); + } + } + } + } + + private int uboAlign(int offset) { + return MathHelper.ceiling_float_int((float) offset / (float) uniformBufferOffsetAlignment) + * uniformBufferOffsetAlignment; + } + + private void updateForwardRenderWorldLightingData() { + worldLightingDataCopyBuffer.clear(); + worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunLightAngle.x); + worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunLightAngle.y); + worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunLightAngle.z); + worldLightingDataCopyBuffer.putFloat(-DeferredStateManager.currentSunAngle.y); + float f = getSkyBrightnessParam(); + if (DeferredStateManager.currentSunAngle.y > 0.05f) { // moon: + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.x * 0.025f * f); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.y * 0.025f * f); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.z * 0.025f * f); + } else { + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.x * f); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.y * f); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.z * f); + } + float lightningBoost = mc.theWorld.getLastLightningBolt() > 0 ? 1.0f : 0.0f; + lightningBoost *= 0.3f + mc.theWorld.getRainStrength(partialTicks); + worldLightingDataCopyBuffer.putFloat(getSkyBrightnessTimeParam() + lightningBoost); + worldLightingDataCopyBuffer.putFloat((float) DeferredStateManager.fogLinearExp); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogDensity); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogNear); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogFar); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkR); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkG); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkB); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorDarkA); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightR); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightG); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightB); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.fogColorLightA); + float mul = 0.05f * MathHelper.clamp_float(-1.0f - DeferredStateManager.getSunHeight() * 20.0f, 0.0f, 1.0f) + + 0.01f; + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.x * mul); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.y * mul); + worldLightingDataCopyBuffer.putFloat(DeferredStateManager.currentSunLightColor.z * mul); + worldLightingDataCopyBuffer.putInt(0); + worldLightingDataCopyBuffer.putFloat(1.0f); + worldLightingDataCopyBuffer.putFloat(1.0f); + worldLightingDataCopyBuffer.putFloat(1.0f); + worldLightingDataCopyBuffer.putFloat(1.0f); + if (config.is_rendering_shadowsSun_clamped > 0) { + tmpShadowLOD0MatrixTexSpace.store(worldLightingDataCopyBuffer); + if (config.is_rendering_shadowsSun_clamped > 1) { + tmpShadowLOD1MatrixTexSpace.store(worldLightingDataCopyBuffer); + if (config.is_rendering_shadowsSun_clamped > 2) { + tmpShadowLOD2MatrixTexSpace.store(worldLightingDataCopyBuffer); + } + } + } + worldLightingDataCopyBuffer.flip(); + EaglercraftGPU.bindGLUniformBuffer(buffer_worldLightingData); + _wglBufferSubData(_GL_UNIFORM_BUFFER, 0, worldLightingDataCopyBuffer); + } + + public void updateReprojectionCoordinates(double worldX, double worldY, double worldZ) { + double distX = worldX - reprojectionOriginCoordinateX; + double distY = worldY - reprojectionOriginCoordinateY; + double distZ = worldZ - reprojectionOriginCoordinateZ; + if (distX * distX + distY * distY + distZ * distZ > 48.0 * 48.0) { + reprojectionOriginCoordinateX = worldX; + reprojectionOriginCoordinateY = worldY; + reprojectionOriginCoordinateZ = worldZ; + reprojectionViewerOffsetX = 0.0f; + reprojectionViewerOffsetY = 0.0f; + reprojectionViewerOffsetZ = 0.0f; + reprojectionStartup = 0; + } else { + reprojectionViewerOffsetX = (float) distX; + reprojectionViewerOffsetY = (float) distY; + reprojectionViewerOffsetZ = (float) distZ; + } + distX = worldX - cloudRenderOriginCoordinateX; + distZ = worldZ - cloudRenderOriginCoordinateZ; + if (distX * distX + distZ * distZ > 256.0 * 256.0) { + cloudRenderOriginCoordinateX = worldX; + cloudRenderOriginCoordinateZ = worldZ; + cloudRenderViewerOffsetX = 0.0f; + cloudRenderViewerOffsetZ = 0.0f; + } else { + cloudRenderViewerOffsetX = (float) distX; + cloudRenderViewerOffsetZ = (float) distZ; + } + } + + public PipelineShaderGBufferDebugView useDebugViewShader(int idx) { + PipelineShaderGBufferDebugView dbgShader = shader_gbuffer_debug_view[idx]; + if (dbgShader == null) { + shader_gbuffer_debug_view[idx] = dbgShader = PipelineShaderGBufferDebugView.compile(idx); + dbgShader.loadUniforms(); + } + dbgShader.useProgram(); + return dbgShader; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ExtGLEnums.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ExtGLEnums.java index a66c5570..cb52b5d5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ExtGLEnums.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ExtGLEnums.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardAcceleratedEffectRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardAcceleratedEffectRenderer.java index 55710271..aa210862 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardAcceleratedEffectRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardAcceleratedEffectRenderer.java @@ -1,7 +1,26 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawArraysInstanced; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribDivisor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STREAM_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; @@ -20,14 +39,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,33 +56,144 @@ public class ForwardAcceleratedEffectRenderer extends AbstractAcceleratedEffectR private static final Logger logger = LogManager.getLogger("ForwardAcceleratedEffectRenderer"); - private ByteBuffer particleBuffer = null; - private int particleCount = 0; - private boolean particlesHasOverflowed = false; - private static final int BYTES_PER_PARTICLE = 24; private static final int PARTICLE_LIMIT = 5461; + private static final Matrix4f tmpMatrix = new Matrix4f(); + public static boolean isMaterialNormalTexture = false; + private ByteBuffer particleBuffer = null; + + private int particleCount = 0; + + private boolean particlesHasOverflowed = false; private PipelineShaderAccelParticleForward shaderProgram = null; private IBufferArrayGL vertexArray = null; + private IBufferGL vertexBuffer = null; private IBufferGL instancesBuffer = null; - - private static final Matrix4f tmpMatrix = new Matrix4f(); - private float f1; private float f2; private float f3; private float f4; + private float f5; - public static boolean isMaterialNormalTexture = false; + @Override + public void begin(float partialTicks) { + this.partialTicks = partialTicks; + + particleBuffer.clear(); + particleCount = 0; + particlesHasOverflowed = false; + + Entity et = Minecraft.getMinecraft().getRenderViewEntity(); + if (et != null) { + f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); + f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); + f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); + f4 = f1 * MathHelper.sin(et.rotationPitch * 0.017453292F); + f5 = MathHelper.cos(et.rotationPitch * 0.017453292F); + } + } + + public void destroy() { + if (particleBuffer != null) { + EagRuntime.freeByteBuffer(particleBuffer); + particleBuffer = null; + } + if (shaderProgram != null) { + shaderProgram.destroy(); + shaderProgram = null; + } + if (vertexArray != null) { + _wglDeleteVertexArrays(vertexArray); + vertexArray = null; + } + if (vertexBuffer != null) { + _wglDeleteBuffers(vertexBuffer); + vertexBuffer = null; + } + if (instancesBuffer != null) { + _wglDeleteBuffers(instancesBuffer); + instancesBuffer = null; + } + } + + @Override + public void draw(float texCoordWidth, float texCoordHeight) { + if (particleCount == 0) { + return; + } + + shaderProgram.useProgram(); + + _wglUniform3f(shaderProgram.uniforms.u_texCoordSize2f_particleSize1f, texCoordWidth, texCoordHeight, 0.0625f); + if (shaderProgram.uniforms.u_transformParam_1_2_5_f != null) { + _wglUniform3f(shaderProgram.uniforms.u_transformParam_1_2_5_f, f1, f5, f4); + _wglUniform2f(shaderProgram.uniforms.u_transformParam_3_4_f, f2, f3); + } else { + _wglUniform4f(shaderProgram.uniforms.u_transformParam_1_2_3_4_f, f1, f5, f2, f3); + _wglUniform1f(shaderProgram.uniforms.u_transformParam_5_f, f4); + } + if (isMaterialNormalTexture) { + _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 0.5f, 0.5f); + } else { + _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 1.0f, 0.0f); + } + + EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_modelViewMatrix4f, + DeferredStateManager.passViewMatrix); + EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_projectionMatrix4f, + DeferredStateManager.passProjMatrix); + EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_inverseViewMatrix4f, + DeferredStateManager.passInverseViewMatrix); + + EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); + EaglercraftGPU.bindGLBufferArray(vertexArray); + + int p = particleBuffer.position(); + int l = particleBuffer.limit(); + + particleBuffer.flip(); + _wglBufferSubData(GL_ARRAY_BUFFER, 0, particleBuffer); + + particleBuffer.position(p); + particleBuffer.limit(l); + + _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, particleCount); + } + + @Override + public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, + int lightMapData, int texSize, float particleSize, int rgba) { + if (particlesHasOverflowed) { + return; + } + if (particleCount >= PARTICLE_LIMIT) { + particlesHasOverflowed = true; + logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", + PARTICLE_LIMIT); + return; + } + ++particleCount; + ByteBuffer buf = particleBuffer; + buf.putFloat(posX); + buf.putFloat(posY); + buf.putFloat(posZ); + buf.putShort((short) particleIndexX); + buf.putShort((short) particleIndexY); + buf.put((byte) (lightMapData & 0xFF)); + buf.put((byte) ((lightMapData >> 16) & 0xFF)); + buf.put((byte) (particleSize * 16.0f)); + buf.put((byte) texSize); + buf.putInt(rgba); + } public void initialize(boolean dynamicLights, int sunShadows) { destroy(); - + shaderProgram = PipelineShaderAccelParticleForward.compile(dynamicLights, sunShadows); shaderProgram.loadUniforms(); @@ -73,10 +204,7 @@ public class ForwardAcceleratedEffectRenderer extends AbstractAcceleratedEffectR instancesBuffer = _wglGenBuffers(); FloatBuffer verts = EagRuntime.allocateFloatBuffer(12); - verts.put(new float[] { - -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, - -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f - }); + verts.put(new float[] { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f }); verts.flip(); EaglercraftGPU.bindGLBufferArray(vertexArray); @@ -114,111 +242,4 @@ public class ForwardAcceleratedEffectRenderer extends AbstractAcceleratedEffectR _wglVertexAttribDivisor(5, 1); } - - @Override - public void draw(float texCoordWidth, float texCoordHeight) { - if(particleCount == 0) { - return; - } - - shaderProgram.useProgram(); - - _wglUniform3f(shaderProgram.uniforms.u_texCoordSize2f_particleSize1f, texCoordWidth, texCoordHeight, 0.0625f); - if(shaderProgram.uniforms.u_transformParam_1_2_5_f != null) { - _wglUniform3f(shaderProgram.uniforms.u_transformParam_1_2_5_f, f1, f5, f4); - _wglUniform2f(shaderProgram.uniforms.u_transformParam_3_4_f, f2, f3); - }else { - _wglUniform4f(shaderProgram.uniforms.u_transformParam_1_2_3_4_f, f1, f5, f2, f3); - _wglUniform1f(shaderProgram.uniforms.u_transformParam_5_f, f4); - } - if(isMaterialNormalTexture) { - _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 0.5f, 0.5f); - }else { - _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 1.0f, 0.0f); - } - - EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_modelViewMatrix4f, DeferredStateManager.passViewMatrix); - EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_projectionMatrix4f, DeferredStateManager.passProjMatrix); - EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_inverseViewMatrix4f, DeferredStateManager.passInverseViewMatrix); - - EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); - EaglercraftGPU.bindGLBufferArray(vertexArray); - - int p = particleBuffer.position(); - int l = particleBuffer.limit(); - - particleBuffer.flip(); - _wglBufferSubData(GL_ARRAY_BUFFER, 0, particleBuffer); - - particleBuffer.position(p); - particleBuffer.limit(l); - - _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, particleCount); - } - - @Override - public void begin(float partialTicks) { - this.partialTicks = partialTicks; - - particleBuffer.clear(); - particleCount = 0; - particlesHasOverflowed = false; - - Entity et = Minecraft.getMinecraft().getRenderViewEntity(); - if(et != null) { - f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); - f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); - f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); - f4 = f1 * MathHelper.sin(et.rotationPitch * 0.017453292F); - f5 = MathHelper.cos(et.rotationPitch * 0.017453292F); - } - } - - @Override - public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, - int lightMapData, int texSize, float particleSize, int rgba) { - if(particlesHasOverflowed) { - return; - } - if(particleCount >= PARTICLE_LIMIT) { - particlesHasOverflowed = true; - logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", PARTICLE_LIMIT); - return; - } - ++particleCount; - ByteBuffer buf = particleBuffer; - buf.putFloat(posX); - buf.putFloat(posY); - buf.putFloat(posZ); - buf.putShort((short)particleIndexX); - buf.putShort((short)particleIndexY); - buf.put((byte)(lightMapData & 0xFF)); - buf.put((byte)((lightMapData >> 16) & 0xFF)); - buf.put((byte)(particleSize * 16.0f)); - buf.put((byte)texSize); - buf.putInt(rgba); - } - - public void destroy() { - if(particleBuffer != null) { - EagRuntime.freeByteBuffer(particleBuffer); - particleBuffer = null; - } - if(shaderProgram != null) { - shaderProgram.destroy(); - shaderProgram = null; - } - if(vertexArray != null) { - _wglDeleteVertexArrays(vertexArray); - vertexArray = null; - } - if(vertexBuffer != null) { - _wglDeleteBuffers(vertexBuffer); - vertexBuffer = null; - } - if(instancesBuffer != null) { - _wglDeleteBuffers(instancesBuffer); - instancesBuffer = null; - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardRenderCallbackHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardRenderCallbackHandler.java index 7dd380c0..ed450bc4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardRenderCallbackHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ForwardRenderCallbackHandler.java @@ -8,14 +8,15 @@ import java.util.List; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,10 +34,11 @@ public class ForwardRenderCallbackHandler { } public void sort(float x, float y, float z) { - if(renderPassList.size() == 0) return; + if (renderPassList.size() == 0) + return; ShadersRenderPassFuture rp; float dx, dy, dz; - for(int i = 0, l = renderPassList.size(); i < l; ++i) { + for (int i = 0, l = renderPassList.size(); i < l; ++i) { rp = renderPassList.get(i); dx = rp.getX() - x; dy = rp.getY() - y; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferAcceleratedEffectRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferAcceleratedEffectRenderer.java index 45655d18..c441d08a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferAcceleratedEffectRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferAcceleratedEffectRenderer.java @@ -1,7 +1,26 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawArraysInstanced; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribDivisor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STREAM_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; @@ -20,14 +39,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -36,33 +56,140 @@ public class GBufferAcceleratedEffectRenderer extends AbstractAcceleratedEffectR private static final Logger logger = LogManager.getLogger("GBufferAcceleratedEffectRenderer"); - private ByteBuffer particleBuffer = null; - private int particleCount = 0; - private boolean particlesHasOverflowed = false; - private static final int BYTES_PER_PARTICLE = 24; private static final int PARTICLE_LIMIT = 5461; + private static final Matrix4f tmpMatrix = new Matrix4f(); + public static boolean isMaterialNormalTexture = false; + private ByteBuffer particleBuffer = null; + + private int particleCount = 0; + + private boolean particlesHasOverflowed = false; private PipelineShaderAccelParticleGBuffer shaderProgram = null; private IBufferArrayGL vertexArray = null; + private IBufferGL vertexBuffer = null; private IBufferGL instancesBuffer = null; - - private static final Matrix4f tmpMatrix = new Matrix4f(); - private float f1; private float f2; private float f3; private float f4; + private float f5; - public static boolean isMaterialNormalTexture = false; + @Override + public void begin(float partialTicks) { + this.partialTicks = partialTicks; + + particleBuffer.clear(); + particleCount = 0; + particlesHasOverflowed = false; + + Entity et = Minecraft.getMinecraft().getRenderViewEntity(); + if (et != null) { + f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); + f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); + f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); + f4 = f1 * MathHelper.sin(et.rotationPitch * 0.017453292F); + f5 = MathHelper.cos(et.rotationPitch * 0.017453292F); + } + } + + public void destroy() { + if (particleBuffer != null) { + EagRuntime.freeByteBuffer(particleBuffer); + particleBuffer = null; + } + if (shaderProgram != null) { + shaderProgram.destroy(); + shaderProgram = null; + } + if (vertexArray != null) { + _wglDeleteVertexArrays(vertexArray); + vertexArray = null; + } + if (vertexBuffer != null) { + _wglDeleteBuffers(vertexBuffer); + vertexBuffer = null; + } + if (instancesBuffer != null) { + _wglDeleteBuffers(instancesBuffer); + instancesBuffer = null; + } + } + + @Override + public void draw(float texCoordWidth, float texCoordHeight) { + if (particleCount == 0) { + return; + } + + shaderProgram.useProgram(); + + _wglUniform3f(shaderProgram.uniforms.u_texCoordSize2f_particleSize1f, texCoordWidth, texCoordHeight, 0.0625f); + if (shaderProgram.uniforms.u_transformParam_1_2_5_f != null) { + _wglUniform3f(shaderProgram.uniforms.u_transformParam_1_2_5_f, f1, f5, f4); + _wglUniform2f(shaderProgram.uniforms.u_transformParam_3_4_f, f2, f3); + } else { + _wglUniform4f(shaderProgram.uniforms.u_transformParam_1_2_3_4_f, f1, f5, f2, f3); + _wglUniform1f(shaderProgram.uniforms.u_transformParam_5_f, f4); + } + if (isMaterialNormalTexture) { + _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 0.5f, 0.5f); + } else { + _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 1.0f, 0.0f); + } + + Matrix4f.mul(DeferredStateManager.passProjMatrix, DeferredStateManager.passViewMatrix, tmpMatrix); + EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_matrixTransform, tmpMatrix); + + EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); + EaglercraftGPU.bindGLBufferArray(vertexArray); + + int p = particleBuffer.position(); + int l = particleBuffer.limit(); + + particleBuffer.flip(); + _wglBufferSubData(GL_ARRAY_BUFFER, 0, particleBuffer); + + particleBuffer.position(p); + particleBuffer.limit(l); + + _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, particleCount); + } + + @Override + public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, + int lightMapData, int texSize, float particleSize, int rgba) { + if (particlesHasOverflowed) { + return; + } + if (particleCount >= PARTICLE_LIMIT) { + particlesHasOverflowed = true; + logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", + PARTICLE_LIMIT); + return; + } + ++particleCount; + ByteBuffer buf = particleBuffer; + buf.putFloat(posX); + buf.putFloat(posY); + buf.putFloat(posZ); + buf.putShort((short) particleIndexX); + buf.putShort((short) particleIndexY); + buf.put((byte) (lightMapData & 0xFF)); + buf.put((byte) ((lightMapData >> 16) & 0xFF)); + buf.put((byte) (particleSize * 16.0f)); + buf.put((byte) texSize); + buf.putInt(rgba); + } public void initialize() { destroy(); - + shaderProgram = PipelineShaderAccelParticleGBuffer.compile(); shaderProgram.loadUniforms(); @@ -73,10 +200,7 @@ public class GBufferAcceleratedEffectRenderer extends AbstractAcceleratedEffectR instancesBuffer = _wglGenBuffers(); FloatBuffer verts = EagRuntime.allocateFloatBuffer(12); - verts.put(new float[] { - -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, - -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f - }); + verts.put(new float[] { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f }); verts.flip(); EaglercraftGPU.bindGLBufferArray(vertexArray); @@ -114,110 +238,4 @@ public class GBufferAcceleratedEffectRenderer extends AbstractAcceleratedEffectR _wglVertexAttribDivisor(5, 1); } - - @Override - public void draw(float texCoordWidth, float texCoordHeight) { - if(particleCount == 0) { - return; - } - - shaderProgram.useProgram(); - - _wglUniform3f(shaderProgram.uniforms.u_texCoordSize2f_particleSize1f, texCoordWidth, texCoordHeight, 0.0625f); - if(shaderProgram.uniforms.u_transformParam_1_2_5_f != null) { - _wglUniform3f(shaderProgram.uniforms.u_transformParam_1_2_5_f, f1, f5, f4); - _wglUniform2f(shaderProgram.uniforms.u_transformParam_3_4_f, f2, f3); - }else { - _wglUniform4f(shaderProgram.uniforms.u_transformParam_1_2_3_4_f, f1, f5, f2, f3); - _wglUniform1f(shaderProgram.uniforms.u_transformParam_5_f, f4); - } - if(isMaterialNormalTexture) { - _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 0.5f, 0.5f); - }else { - _wglUniform2f(shaderProgram.uniforms.u_textureYScale2f, 1.0f, 0.0f); - } - - Matrix4f.mul(DeferredStateManager.passProjMatrix, DeferredStateManager.passViewMatrix, tmpMatrix); - EaglerDeferredPipeline.uniformMatrixHelper(shaderProgram.uniforms.u_matrixTransform, tmpMatrix); - - EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); - EaglercraftGPU.bindGLBufferArray(vertexArray); - - int p = particleBuffer.position(); - int l = particleBuffer.limit(); - - particleBuffer.flip(); - _wglBufferSubData(GL_ARRAY_BUFFER, 0, particleBuffer); - - particleBuffer.position(p); - particleBuffer.limit(l); - - _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, particleCount); - } - - @Override - public void begin(float partialTicks) { - this.partialTicks = partialTicks; - - particleBuffer.clear(); - particleCount = 0; - particlesHasOverflowed = false; - - Entity et = Minecraft.getMinecraft().getRenderViewEntity(); - if(et != null) { - f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); - f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); - f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); - f4 = f1 * MathHelper.sin(et.rotationPitch * 0.017453292F); - f5 = MathHelper.cos(et.rotationPitch * 0.017453292F); - } - } - - @Override - public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, - int lightMapData, int texSize, float particleSize, int rgba) { - if(particlesHasOverflowed) { - return; - } - if(particleCount >= PARTICLE_LIMIT) { - particlesHasOverflowed = true; - logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", PARTICLE_LIMIT); - return; - } - ++particleCount; - ByteBuffer buf = particleBuffer; - buf.putFloat(posX); - buf.putFloat(posY); - buf.putFloat(posZ); - buf.putShort((short)particleIndexX); - buf.putShort((short)particleIndexY); - buf.put((byte)(lightMapData & 0xFF)); - buf.put((byte)((lightMapData >> 16) & 0xFF)); - buf.put((byte)(particleSize * 16.0f)); - buf.put((byte)texSize); - buf.putInt(rgba); - } - - public void destroy() { - if(particleBuffer != null) { - EagRuntime.freeByteBuffer(particleBuffer); - particleBuffer = null; - } - if(shaderProgram != null) { - shaderProgram.destroy(); - shaderProgram = null; - } - if(vertexArray != null) { - _wglDeleteVertexArrays(vertexArray); - vertexArray = null; - } - if(vertexBuffer != null) { - _wglDeleteBuffers(vertexBuffer); - vertexBuffer = null; - } - if(instancesBuffer != null) { - _wglDeleteBuffers(instancesBuffer); - instancesBuffer = null; - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineCompiler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineCompiler.java index 4e257e47..9bbabe3b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineCompiler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineCompiler.java @@ -1,6 +1,9 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform4f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; @@ -21,14 +24,15 @@ import net.minecraft.client.renderer.GLAllocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,134 +54,13 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { private static FloatBuffer matrixCopyBuffer = null; private static final Matrix4f tmpMatrix = new Matrix4f(); - @Override - public String[] getShaderSource(int stateCoreBits, int stateExtBits, Object[] userPointer) { - if(matrixCopyBuffer == null) { - matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); - } - userPointer[0] = new GBufferPipelineProgramInstance(stateCoreBits, stateExtBits); - EaglerDeferredConfig conf = Minecraft.getMinecraft().gameSettings.deferredShaderConf; - StringBuilder macros = new StringBuilder(); - if((stateExtBits & STATE_SHADOW_RENDER) != 0) { - if((stateExtBits & STATE_CLIP_PLANE) != 0) { - macros.append("#define STATE_CLIP_PLANE\n"); - } - if((stateExtBits & STATE_WAVING_BLOCKS) != 0) { - macros.append("#define COMPILE_STATE_WAVING_BLOCKS\n"); - } - if((stateExtBits & STATE_FORWARD_RENDER) != 0) { - macros.append("#define COMPILE_COLORED_SHADOWS\n"); - } - logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), visualizeBits(stateExtBits)); - logger.info(" - {}", ShaderSource.deferred_shadow_vsh); - logger.info(" - {}", ShaderSource.deferred_shadow_fsh); - return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_shadow_vsh), - macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_shadow_fsh) }; - }else if((stateExtBits & STATE_REALISTIC_WATER_RENDER) != 0) { - if(conf.is_rendering_dynamicLights) { - macros.append("#define COMPILE_DYNAMIC_LIGHTS\n"); - } - if(conf.is_rendering_shadowsSun_clamped > 0) { - int lods = conf.is_rendering_shadowsSun_clamped - 1; - if(lods > 2) { - lods = 2; - } - macros.append("#define COMPILE_SUN_SHADOW_LOD" + lods + "\n"); - if(conf.is_rendering_shadowsSmoothed) { - macros.append("#define COMPILE_SUN_SHADOW_SMOOTH\n"); - } - } - if(conf.is_rendering_lightShafts) { - macros.append("#define COMPILE_FOG_LIGHT_SHAFTS\n"); - } - logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), visualizeBits(stateExtBits)); - logger.info(" - {}", ShaderSource.realistic_water_render_vsh); - logger.info(" - {}", ShaderSource.realistic_water_render_fsh); - return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.realistic_water_render_vsh), - macros.toString() + ShaderSource.getSourceFor(ShaderSource.realistic_water_render_fsh) }; - }else if((stateExtBits & STATE_GLASS_HIGHLIGHTS) != 0) { - if(conf.is_rendering_dynamicLights) { - macros.append("#define COMPILE_DYNAMIC_LIGHTS\n"); - } - if(conf.is_rendering_shadowsSun_clamped > 0) { - int lods = conf.is_rendering_shadowsSun_clamped - 1; - if(lods > 2) { - lods = 2; - } - macros.append("#define COMPILE_SUN_SHADOW_LOD" + lods + "\n"); - if(conf.is_rendering_shadowsSmoothed) { - macros.append("#define COMPILE_SUN_SHADOW_SMOOTH\n"); - } - } - logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), visualizeBits(stateExtBits)); - logger.info(" - {}", ShaderSource.forward_glass_highlights_vsh); - logger.info(" - {}", ShaderSource.forward_glass_highlights_fsh); - return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_glass_highlights_vsh), - macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_glass_highlights_fsh) }; - }else if((stateExtBits & (STATE_FORWARD_RENDER | STATE_PARABOLOID_RENDER)) != 0) { - if((stateExtBits & STATE_MATERIAL_TEXTURE) != 0) { - macros.append("#define COMPILE_NORMAL_MATERIAL_TEXTURE\n"); - } - if((stateExtBits & STATE_CLIP_PLANE) != 0) { - macros.append("#define STATE_CLIP_PLANE\n"); - } - if((stateExtBits & STATE_PARABOLOID_RENDER) != 0) { - macros.append("#define COMPILE_PARABOLOID\n"); - }else { - if(conf.is_rendering_useEnvMap) { - macros.append("#define COMPILE_PARABOLOID_ENV_MAP\n"); - } - } - if(conf.is_rendering_dynamicLights) { - macros.append("#define COMPILE_DYNAMIC_LIGHTS\n"); - } - if(conf.is_rendering_shadowsSun_clamped > 0) { - int lods = conf.is_rendering_shadowsSun_clamped - 1; - if(lods > 2) { - lods = 2; - } - macros.append("#define COMPILE_SUN_SHADOW_LOD" + lods + "\n"); - if(conf.is_rendering_shadowsSmoothed) { - macros.append("#define COMPILE_SUN_SHADOW_SMOOTH\n"); - } - } - if(conf.is_rendering_lightShafts) { - macros.append("#define COMPILE_FOG_LIGHT_SHAFTS\n"); - } - logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), visualizeBits(stateExtBits)); - logger.info(" - {}", ShaderSource.forward_core_vsh); - logger.info(" - {}", ShaderSource.forward_core_fsh); - return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_core_vsh), - macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_core_fsh) }; - }else if((stateExtBits & STATE_REALISTIC_WATER_MASK) != 0) { - logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), visualizeBits(stateExtBits)); - logger.info(" - {}", ShaderSource.realistic_water_mask_vsh); - logger.info(" - {}", ShaderSource.realistic_water_mask_fsh); - return new String[] { ShaderSource.getSourceFor(ShaderSource.realistic_water_mask_vsh), - ShaderSource.getSourceFor(ShaderSource.realistic_water_mask_fsh) }; - }else { - if((stateExtBits & STATE_MATERIAL_TEXTURE) != 0) { - macros.append("#define COMPILE_NORMAL_MATERIAL_TEXTURE\n"); - } - if((stateExtBits & STATE_CLIP_PLANE) != 0) { - macros.append("#define COMPILE_STATE_CLIP_PLANE\n"); - } - if((stateExtBits & STATE_WAVING_BLOCKS) != 0) { - macros.append("#define COMPILE_STATE_WAVING_BLOCKS\n"); - } - - logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), visualizeBits(stateExtBits)); - logger.info(" - {}", ShaderSource.deferred_core_vsh); - logger.info(" - {}", ShaderSource.deferred_core_gbuffer_fsh); - - return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_core_vsh), - macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_core_gbuffer_fsh) }; - } + private static String visualizeBits(int bits) { + return FixedFunctionPipeline.visualizeBits(bits); } @Override - public int getExtensionStatesCount() { - return 9; + public void destroyPipeline(IProgramGL shaderProgram, int stateCoreBits, int stateExtBits, Object[] userPointer) { + } @Override @@ -188,26 +71,165 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { | (DeferredStateManager.enableDrawWavingBlocks ? FixedFunctionShader.FixedFunctionState.STATE_ENABLE_LIGHTMAP : 0)) - : ((DeferredStateManager.enableDrawRealisticWaterMask) ? FixedFunctionShader.FixedFunctionState.STATE_ENABLE_LIGHTMAP + : ((DeferredStateManager.enableDrawRealisticWaterMask) + ? FixedFunctionShader.FixedFunctionState.STATE_ENABLE_LIGHTMAP : (DeferredStateManager.enableDrawRealisticWaterRender ? (FixedFunctionShader.FixedFunctionState.STATE_ENABLE_LIGHTMAP | FixedFunctionShader.FixedFunctionState.STATE_ENABLE_TEXTURE2D) - : (2943))); + : (2943))); } @Override public int getCurrentExtensionStateBits(int stateCoreBits) { return ((DeferredStateManager.enableMaterialMapTexture && !DeferredStateManager.enableShadowRender && !DeferredStateManager.enableDrawRealisticWaterMask - && !DeferredStateManager.enableDrawRealisticWaterRender) ? STATE_MATERIAL_TEXTURE : 0) | - (DeferredStateManager.enableForwardRender ? STATE_FORWARD_RENDER : 0) | - (DeferredStateManager.enableParaboloidRender ? STATE_PARABOLOID_RENDER : 0) | - (DeferredStateManager.enableShadowRender ? STATE_SHADOW_RENDER : 0) | - (DeferredStateManager.enableClipPlane ? STATE_CLIP_PLANE : 0) | - (DeferredStateManager.enableDrawWavingBlocks ? STATE_WAVING_BLOCKS : 0) | - (DeferredStateManager.enableDrawRealisticWaterMask ? STATE_REALISTIC_WATER_MASK : 0) | - (DeferredStateManager.enableDrawRealisticWaterRender ? STATE_REALISTIC_WATER_RENDER : 0) | - (DeferredStateManager.enableDrawGlassHighlightsRender ? STATE_GLASS_HIGHLIGHTS : 0); + && !DeferredStateManager.enableDrawRealisticWaterRender) ? STATE_MATERIAL_TEXTURE : 0) + | (DeferredStateManager.enableForwardRender ? STATE_FORWARD_RENDER : 0) + | (DeferredStateManager.enableParaboloidRender ? STATE_PARABOLOID_RENDER : 0) + | (DeferredStateManager.enableShadowRender ? STATE_SHADOW_RENDER : 0) + | (DeferredStateManager.enableClipPlane ? STATE_CLIP_PLANE : 0) + | (DeferredStateManager.enableDrawWavingBlocks ? STATE_WAVING_BLOCKS : 0) + | (DeferredStateManager.enableDrawRealisticWaterMask ? STATE_REALISTIC_WATER_MASK : 0) + | (DeferredStateManager.enableDrawRealisticWaterRender ? STATE_REALISTIC_WATER_RENDER : 0) + | (DeferredStateManager.enableDrawGlassHighlightsRender ? STATE_GLASS_HIGHLIGHTS : 0); + } + + @Override + public int getExtensionStatesCount() { + return 9; + } + + @Override + public String[] getShaderSource(int stateCoreBits, int stateExtBits, Object[] userPointer) { + if (matrixCopyBuffer == null) { + matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); + } + userPointer[0] = new GBufferPipelineProgramInstance(stateCoreBits, stateExtBits); + EaglerDeferredConfig conf = Minecraft.getMinecraft().gameSettings.deferredShaderConf; + StringBuilder macros = new StringBuilder(); + if ((stateExtBits & STATE_SHADOW_RENDER) != 0) { + if ((stateExtBits & STATE_CLIP_PLANE) != 0) { + macros.append("#define STATE_CLIP_PLANE\n"); + } + if ((stateExtBits & STATE_WAVING_BLOCKS) != 0) { + macros.append("#define COMPILE_STATE_WAVING_BLOCKS\n"); + } + if ((stateExtBits & STATE_FORWARD_RENDER) != 0) { + macros.append("#define COMPILE_COLORED_SHADOWS\n"); + } + logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), + visualizeBits(stateExtBits)); + logger.info(" - {}", ShaderSource.deferred_shadow_vsh); + logger.info(" - {}", ShaderSource.deferred_shadow_fsh); + return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_shadow_vsh), + macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_shadow_fsh) }; + } else if ((stateExtBits & STATE_REALISTIC_WATER_RENDER) != 0) { + if (conf.is_rendering_dynamicLights) { + macros.append("#define COMPILE_DYNAMIC_LIGHTS\n"); + } + if (conf.is_rendering_shadowsSun_clamped > 0) { + int lods = conf.is_rendering_shadowsSun_clamped - 1; + if (lods > 2) { + lods = 2; + } + macros.append("#define COMPILE_SUN_SHADOW_LOD" + lods + "\n"); + if (conf.is_rendering_shadowsSmoothed) { + macros.append("#define COMPILE_SUN_SHADOW_SMOOTH\n"); + } + } + if (conf.is_rendering_lightShafts) { + macros.append("#define COMPILE_FOG_LIGHT_SHAFTS\n"); + } + logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), + visualizeBits(stateExtBits)); + logger.info(" - {}", ShaderSource.realistic_water_render_vsh); + logger.info(" - {}", ShaderSource.realistic_water_render_fsh); + return new String[] { + macros.toString() + ShaderSource.getSourceFor(ShaderSource.realistic_water_render_vsh), + macros.toString() + ShaderSource.getSourceFor(ShaderSource.realistic_water_render_fsh) }; + } else if ((stateExtBits & STATE_GLASS_HIGHLIGHTS) != 0) { + if (conf.is_rendering_dynamicLights) { + macros.append("#define COMPILE_DYNAMIC_LIGHTS\n"); + } + if (conf.is_rendering_shadowsSun_clamped > 0) { + int lods = conf.is_rendering_shadowsSun_clamped - 1; + if (lods > 2) { + lods = 2; + } + macros.append("#define COMPILE_SUN_SHADOW_LOD" + lods + "\n"); + if (conf.is_rendering_shadowsSmoothed) { + macros.append("#define COMPILE_SUN_SHADOW_SMOOTH\n"); + } + } + logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), + visualizeBits(stateExtBits)); + logger.info(" - {}", ShaderSource.forward_glass_highlights_vsh); + logger.info(" - {}", ShaderSource.forward_glass_highlights_fsh); + return new String[] { + macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_glass_highlights_vsh), + macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_glass_highlights_fsh) }; + } else if ((stateExtBits & (STATE_FORWARD_RENDER | STATE_PARABOLOID_RENDER)) != 0) { + if ((stateExtBits & STATE_MATERIAL_TEXTURE) != 0) { + macros.append("#define COMPILE_NORMAL_MATERIAL_TEXTURE\n"); + } + if ((stateExtBits & STATE_CLIP_PLANE) != 0) { + macros.append("#define STATE_CLIP_PLANE\n"); + } + if ((stateExtBits & STATE_PARABOLOID_RENDER) != 0) { + macros.append("#define COMPILE_PARABOLOID\n"); + } else { + if (conf.is_rendering_useEnvMap) { + macros.append("#define COMPILE_PARABOLOID_ENV_MAP\n"); + } + } + if (conf.is_rendering_dynamicLights) { + macros.append("#define COMPILE_DYNAMIC_LIGHTS\n"); + } + if (conf.is_rendering_shadowsSun_clamped > 0) { + int lods = conf.is_rendering_shadowsSun_clamped - 1; + if (lods > 2) { + lods = 2; + } + macros.append("#define COMPILE_SUN_SHADOW_LOD" + lods + "\n"); + if (conf.is_rendering_shadowsSmoothed) { + macros.append("#define COMPILE_SUN_SHADOW_SMOOTH\n"); + } + } + if (conf.is_rendering_lightShafts) { + macros.append("#define COMPILE_FOG_LIGHT_SHAFTS\n"); + } + logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), + visualizeBits(stateExtBits)); + logger.info(" - {}", ShaderSource.forward_core_vsh); + logger.info(" - {}", ShaderSource.forward_core_fsh); + return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_core_vsh), + macros.toString() + ShaderSource.getSourceFor(ShaderSource.forward_core_fsh) }; + } else if ((stateExtBits & STATE_REALISTIC_WATER_MASK) != 0) { + logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), + visualizeBits(stateExtBits)); + logger.info(" - {}", ShaderSource.realistic_water_mask_vsh); + logger.info(" - {}", ShaderSource.realistic_water_mask_fsh); + return new String[] { ShaderSource.getSourceFor(ShaderSource.realistic_water_mask_vsh), + ShaderSource.getSourceFor(ShaderSource.realistic_water_mask_fsh) }; + } else { + if ((stateExtBits & STATE_MATERIAL_TEXTURE) != 0) { + macros.append("#define COMPILE_NORMAL_MATERIAL_TEXTURE\n"); + } + if ((stateExtBits & STATE_CLIP_PLANE) != 0) { + macros.append("#define COMPILE_STATE_CLIP_PLANE\n"); + } + if ((stateExtBits & STATE_WAVING_BLOCKS) != 0) { + macros.append("#define COMPILE_STATE_WAVING_BLOCKS\n"); + } + + logger.info("Compiling program for core state: {}, ext state: {}", visualizeBits(stateCoreBits), + visualizeBits(stateExtBits)); + logger.info(" - {}", ShaderSource.deferred_core_vsh); + logger.info(" - {}", ShaderSource.deferred_core_gbuffer_fsh); + + return new String[] { macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_core_vsh), + macros.toString() + ShaderSource.getSourceFor(ShaderSource.deferred_core_gbuffer_fsh) }; + } } @Override @@ -215,7 +237,7 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { Object[] userPointer) { EaglercraftGPU.bindGLShaderProgram(compiledProg); GBufferExtPipelineShader newShader = new GBufferExtPipelineShader(compiledProg, stateCoreBits, stateExtBits); - ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject = newShader; + ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject = newShader; newShader.loadUniforms(); } @@ -223,15 +245,15 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { public void updatePipeline(IProgramGL compiledProg, int stateCoreBits, int stateExtBits, Object[] userPointer) { int serial; GBufferExtPipelineShader.Uniforms uniforms = null; - if((stateExtBits & STATE_MATERIAL_TEXTURE) == 0) { - uniforms = ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject.uniforms; + if ((stateExtBits & STATE_MATERIAL_TEXTURE) == 0) { + uniforms = ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject.uniforms; serial = DeferredStateManager.materialConstantsSerial; - if(uniforms.materialConstantsSerial != serial) { + if (uniforms.materialConstantsSerial != serial) { uniforms.materialConstantsSerial = serial; float roughness = 1.0f - DeferredStateManager.materialConstantsRoughness; float metalness = DeferredStateManager.materialConstantsMetalness; float emission = DeferredStateManager.materialConstantsEmission; - if(uniforms.materialConstantsRoughness != roughness || uniforms.materialConstantsMetalness != metalness + if (uniforms.materialConstantsRoughness != roughness || uniforms.materialConstantsMetalness != metalness || uniforms.materialConstantsEmission != emission) { uniforms.materialConstantsRoughness = roughness; uniforms.materialConstantsMetalness = metalness; @@ -240,33 +262,33 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { } } } - if((stateCoreBits & FixedFunctionShader.FixedFunctionState.STATE_HAS_ATTRIB_NORMAL) == 0) { - if(uniforms == null) { - uniforms = ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject.uniforms; + if ((stateCoreBits & FixedFunctionShader.FixedFunctionState.STATE_HAS_ATTRIB_NORMAL) == 0) { + if (uniforms == null) { + uniforms = ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject.uniforms; } int blockId = DeferredStateManager.constantBlock; - if(uniforms.constantBlock != blockId) { + if (uniforms.constantBlock != blockId) { uniforms.constantBlock = blockId; _wglUniform1f(uniforms.u_blockConstant1f, (blockId - 127) * 0.007874f); } } - if((stateExtBits & STATE_CLIP_PLANE) != 0) { - if(uniforms == null) { - uniforms = ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject.uniforms; + if ((stateExtBits & STATE_CLIP_PLANE) != 0) { + if (uniforms == null) { + uniforms = ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject.uniforms; } float clipPlaneYState = DeferredStateManager.clipPlaneY; - if(uniforms.clipPlaneY != clipPlaneYState) { + if (uniforms.clipPlaneY != clipPlaneYState) { uniforms.clipPlaneY = clipPlaneYState; _wglUniform1f(uniforms.u_clipPlaneY1f, clipPlaneYState); } } - if((stateExtBits & STATE_WAVING_BLOCKS) != 0) { - if(uniforms == null) { - uniforms = ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject.uniforms; + if ((stateExtBits & STATE_WAVING_BLOCKS) != 0) { + if (uniforms == null) { + uniforms = ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject.uniforms; } serial = DeferredStateManager.passViewMatrixSerial; boolean modelDirty = false; - if(serial != uniforms.viewMatrixSerial) { + if (serial != uniforms.viewMatrixSerial) { uniforms.viewMatrixSerial = serial; matrixCopyBuffer.clear(); DeferredStateManager.passViewMatrix.store(matrixCopyBuffer); @@ -275,26 +297,27 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { modelDirty = true; } serial = GlStateManager.getModelViewSerial(); - if(uniforms.modelMatrixSerial != serial || modelDirty) { + if (uniforms.modelMatrixSerial != serial || modelDirty) { uniforms.modelMatrixSerial = serial; Matrix4f mat = GlStateManager.getModelViewReference(); matrixCopyBuffer.clear(); - if(!DeferredStateManager.isShadowPassMatrixLoaded) { + if (!DeferredStateManager.isShadowPassMatrixLoaded) { Matrix4f.mul(DeferredStateManager.passInverseViewMatrix, mat, tmpMatrix); tmpMatrix.store(matrixCopyBuffer); - }else { + } else { mat.store(matrixCopyBuffer); } matrixCopyBuffer.flip(); _wglUniformMatrix4fv(uniforms.u_modelMatrix4f, false, matrixCopyBuffer); } serial = DeferredStateManager.wavingBlockOffsetSerial; - if(serial != uniforms.wavingBlockOffsetSerial) { + if (serial != uniforms.wavingBlockOffsetSerial) { uniforms.wavingBlockOffsetSerial = serial; float x = DeferredStateManager.wavingBlockOffsetX; float y = DeferredStateManager.wavingBlockOffsetY; float z = DeferredStateManager.wavingBlockOffsetZ; - if(uniforms.wavingBlockOffsetX != x || uniforms.wavingBlockOffsetY != y || uniforms.wavingBlockOffsetZ != z) { + if (uniforms.wavingBlockOffsetX != x || uniforms.wavingBlockOffsetY != y + || uniforms.wavingBlockOffsetZ != z) { uniforms.wavingBlockOffsetX = x; uniforms.wavingBlockOffsetY = y; uniforms.wavingBlockOffsetZ = z; @@ -302,13 +325,14 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { } } serial = DeferredStateManager.wavingBlockParamSerial; - if(serial != uniforms.wavingBlockParamSerial) { + if (serial != uniforms.wavingBlockParamSerial) { uniforms.wavingBlockParamSerial = serial; float x = DeferredStateManager.wavingBlockParamX; float y = DeferredStateManager.wavingBlockParamY; float z = DeferredStateManager.wavingBlockParamZ; float w = DeferredStateManager.wavingBlockParamW; - if(uniforms.wavingBlockParamX != x || uniforms.wavingBlockParamY != y || uniforms.wavingBlockParamZ != z || uniforms.wavingBlockParamW != w) { + if (uniforms.wavingBlockParamX != x || uniforms.wavingBlockParamY != y + || uniforms.wavingBlockParamZ != z || uniforms.wavingBlockParamW != w) { uniforms.wavingBlockParamX = x; uniforms.wavingBlockParamY = y; uniforms.wavingBlockParamZ = z; @@ -317,28 +341,28 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { } } } - if((stateExtBits & STATE_FORWARD_RENDER) != 0) { - if(uniforms == null) { - uniforms = ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject.uniforms; + if ((stateExtBits & STATE_FORWARD_RENDER) != 0) { + if (uniforms == null) { + uniforms = ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject.uniforms; } serial = DeferredStateManager.passViewMatrixSerial; - if(serial != uniforms.inverseViewMatrixSerial) { + if (serial != uniforms.inverseViewMatrixSerial) { uniforms.inverseViewMatrixSerial = serial; matrixCopyBuffer.clear(); DeferredStateManager.passInverseViewMatrix.store(matrixCopyBuffer); matrixCopyBuffer.flip(); _wglUniformMatrix4fv(uniforms.u_inverseViewMatrix4f, false, matrixCopyBuffer); } - if((stateExtBits & STATE_PARABOLOID_RENDER) != 0) { - float farPlane = DeferredStateManager.gbufferFarPlane * 0.125f; //TODO - if(farPlane != uniforms.farPlane1f) { + if ((stateExtBits & STATE_PARABOLOID_RENDER) != 0) { + float farPlane = DeferredStateManager.gbufferFarPlane * 0.125f; // TODO + if (farPlane != uniforms.farPlane1f) { uniforms.farPlane1f = farPlane; _wglUniform1f(uniforms.u_farPlane1f, farPlane); } } - if((stateExtBits & STATE_REALISTIC_WATER_RENDER) != 0) { + if ((stateExtBits & STATE_REALISTIC_WATER_RENDER) != 0) { serial = DeferredStateManager.passViewMatrixSerial * 87917 + DeferredStateManager.passProjMatrixSerial; - if(serial != uniforms.modelViewProjMatrixAltSerial) { + if (serial != uniforms.modelViewProjMatrixAltSerial) { uniforms.modelViewProjMatrixAltSerial = serial; Matrix4f.mul(DeferredStateManager.passProjMatrix, DeferredStateManager.passViewMatrix, tmpMatrix); matrixCopyBuffer.clear(); @@ -347,18 +371,19 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { _wglUniformMatrix4fv(uniforms.u_modelViewProjMat4f_, false, matrixCopyBuffer); } serial = DeferredStateManager.waterWindOffsetSerial; - if(serial != uniforms.waterWindOffsetSerial) { + if (serial != uniforms.waterWindOffsetSerial) { uniforms.waterWindOffsetSerial = serial; Vector4f vec = DeferredStateManager.u_waterWindOffset4f; _wglUniform4f(uniforms.u_waterWindOffset4f, vec.x, vec.y, vec.z, vec.w); } serial = DeferredStateManager.wavingBlockOffsetSerial; - if(serial != uniforms.wavingBlockOffsetSerial) { + if (serial != uniforms.wavingBlockOffsetSerial) { uniforms.wavingBlockOffsetSerial = serial; float x = DeferredStateManager.wavingBlockOffsetX; float y = DeferredStateManager.wavingBlockOffsetY; float z = DeferredStateManager.wavingBlockOffsetZ; - if(uniforms.wavingBlockOffsetX != x || uniforms.wavingBlockOffsetY != y || uniforms.wavingBlockOffsetZ != z) { + if (uniforms.wavingBlockOffsetX != x || uniforms.wavingBlockOffsetY != y + || uniforms.wavingBlockOffsetZ != z) { uniforms.wavingBlockOffsetX = x; uniforms.wavingBlockOffsetY = y; uniforms.wavingBlockOffsetZ = z; @@ -366,26 +391,17 @@ public class GBufferPipelineCompiler implements IExtPipelineCompiler { } } } - }else if((stateExtBits & (STATE_SHADOW_RENDER | STATE_REALISTIC_WATER_MASK)) == 0) { - if(uniforms == null) { - uniforms = ((GBufferPipelineProgramInstance)userPointer[0]).shaderObject.uniforms; + } else if ((stateExtBits & (STATE_SHADOW_RENDER | STATE_REALISTIC_WATER_MASK)) == 0) { + if (uniforms == null) { + uniforms = ((GBufferPipelineProgramInstance) userPointer[0]).shaderObject.uniforms; } - if(uniforms.u_useEnvMap1f != null) { + if (uniforms.u_useEnvMap1f != null) { float use = DeferredStateManager.materialConstantsUseEnvMap ? 1.0f : 0.0f; - if(uniforms.materialConstantsUseEnvMap != use) { + if (uniforms.materialConstantsUseEnvMap != use) { uniforms.materialConstantsUseEnvMap = use; _wglUniform1f(uniforms.u_useEnvMap1f, use); } } } } - - @Override - public void destroyPipeline(IProgramGL shaderProgram, int stateCoreBits, int stateExtBits, Object[] userPointer) { - - } - - private static String visualizeBits(int bits) { - return FixedFunctionPipeline.visualizeBits(bits); - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineProgramInstance.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineProgramInstance.java index 24555dd3..19f02d9e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineProgramInstance.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/GBufferPipelineProgramInstance.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program.GBufferExtPipel /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LensFlareMeshRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LensFlareMeshRenderer.java index a49c1a8d..9d2ac364 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LensFlareMeshRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LensFlareMeshRenderer.java @@ -1,8 +1,43 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawArraysInstanced; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawElements; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglPixelStorei; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribDivisor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR_MIPMAP_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RED; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE0; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE1; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE2; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAX_LEVEL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNPACK_ALIGNMENT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_R8; import java.io.DataInputStream; import java.io.IOException; @@ -24,22 +59,25 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LensFlareMeshRenderer { - public static final ResourceLocation streaksTextureLocation = new ResourceLocation("eagler:glsl/deferred/lens_streaks.bmp"); - public static final ResourceLocation ghostsTextureLocation = new ResourceLocation("eagler:glsl/deferred/lens_ghosts.bmp"); + public static final ResourceLocation streaksTextureLocation = new ResourceLocation( + "eagler:glsl/deferred/lens_streaks.bmp"); + public static final ResourceLocation ghostsTextureLocation = new ResourceLocation( + "eagler:glsl/deferred/lens_ghosts.bmp"); public static final int ghostsSpriteCount = 4; static IBufferArrayGL streaksVertexArray = null; @@ -61,18 +99,120 @@ public class LensFlareMeshRenderer { static final Matrix3f tmpMat2 = new Matrix3f(); static final Vector3f tmpVec = new Vector3f(); + static void destroy() { + if (streaksVertexArray != null) { + _wglDeleteVertexArrays(streaksVertexArray); + streaksVertexArray = null; + } + if (streaksVertexBuffer != null) { + _wglDeleteBuffers(streaksVertexBuffer); + streaksVertexBuffer = null; + } + if (ghostsVertexArray != null) { + _wglDeleteVertexArrays(ghostsVertexArray); + ghostsVertexArray = null; + } + if (ghostsVertexBuffer != null) { + _wglDeleteBuffers(ghostsVertexBuffer); + ghostsVertexBuffer = null; + } + if (streaksTexture != -1) { + GlStateManager.deleteTexture(streaksTexture); + streaksTexture = -1; + } + if (ghostsTexture != -1) { + GlStateManager.deleteTexture(ghostsTexture); + ghostsTexture = -1; + } + if (streaksProgram != null) { + streaksProgram.destroy(); + streaksProgram = null; + } + if (ghostsProgram != null) { + ghostsProgram.destroy(); + ghostsProgram = null; + } + } + + static void drawLensFlares(float sunScreenX, float sunScreenY) { + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_ONE, GL_ONE); + + GlStateManager.setActiveTexture(GL_TEXTURE2); + GlStateManager.bindTexture(EaglerDeferredPipeline.instance.sunOcclusionValueTexture); + GlStateManager.setActiveTexture(GL_TEXTURE1); + GlStateManager.bindTexture(EaglerDeferredPipeline.instance.exposureBlendTexture); + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(streaksTexture); + + streaksProgram.useProgram(); + + Minecraft mc = Minecraft.getMinecraft(); + float aspectRatio = (float) mc.displayHeight / (float) mc.displayWidth; + + float fov = 90.0f / mc.entityRenderer.getFOVModifier(EaglerDeferredPipeline.instance.getPartialTicks(), true); + float size = 0.075f * fov * (1.0f + MathHelper.sqrt_float(sunScreenX * sunScreenX + sunScreenY * sunScreenY)); + + tmpMat.setIdentity(); + tmpMat.m00 = aspectRatio * 2.0f * size; + tmpMat.m11 = size; + tmpMat.m20 = sunScreenX; + tmpMat.m21 = sunScreenY; + + float rotation = sunScreenX * sunScreenX * Math.signum(sunScreenX) + + sunScreenY * sunScreenY * Math.signum(sunScreenY); + + tmpMat2.setIdentity(); + tmpMat2.m00 = MathHelper.cos(rotation); + tmpMat2.m01 = MathHelper.sin(rotation); + tmpMat2.m10 = -tmpMat2.m01; + tmpMat2.m11 = tmpMat2.m00; + Matrix3f.mul(tmpMat, tmpMat2, tmpMat); + + EaglerDeferredPipeline.uniformMatrixHelper(streaksProgram.uniforms.u_sunFlareMatrix3f, tmpMat); + + Vector3f v = DeferredStateManager.currentSunLightColor; + float mag = 1.0f + DeferredStateManager.currentSunAngle.y * 0.8f; + if (mag > 1.0f) { + mag = 1.0f - (mag - 1.0f) * 20.0f; + if (mag < 0.0f) { + mag = 0.0f; + } + } + mag = 0.003f * (1.0f + mag * mag * mag * 4.0f); + _wglUniform3f(streaksProgram.uniforms.u_flareColor3f, v.x * mag * 0.5f, v.y * mag * 0.5f, v.z * mag * 0.5f); + + EaglercraftGPU.bindGLBufferArray(streaksVertexArray); + _wglDrawElements(GL_TRIANGLES, streaksVertexCount + (streaksVertexCount >> 1), GL_UNSIGNED_SHORT, 0); + + ghostsProgram.useProgram(); + + GlStateManager.setActiveTexture(GL_TEXTURE0); + GlStateManager.bindTexture(ghostsTexture); + + _wglUniform3f(ghostsProgram.uniforms.u_flareColor3f, v.x * mag, v.y * mag, v.z * mag); + _wglUniform1f(ghostsProgram.uniforms.u_aspectRatio1f, aspectRatio); + _wglUniform2f(ghostsProgram.uniforms.u_sunPosition2f, sunScreenX, sunScreenY); + _wglUniform1f(ghostsProgram.uniforms.u_baseScale1f, fov); + + EaglercraftGPU.bindGLBufferArray(ghostsVertexArray); + _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, ghostsInstanceCount); + + GlStateManager.disableBlend(); + } + static void initialize() { destroy(); - + streaksProgram = PipelineShaderLensFlares.compileStreaks(); streaksProgram.loadUniforms(); - + ghostsProgram = PipelineShaderLensFlares.compileGhosts(); ghostsProgram.loadUniforms(); - + ByteBuffer copyBuffer = EagRuntime.allocateByteBuffer(16384); - for(int i = 0; i < 4; ++i) { + for (int i = 0; i < 4; ++i) { pushStreakQuad(copyBuffer, 0.0f, 0.0f, 1.0f, 10.0f, 0.0f, 0.0f, 1.0f, 1.0f, (i * 3.14159f / 4.0f)); pushStreakQuad(copyBuffer, 0.0f, 0.0f, 1.5f, 5.0f, 0.0f, 0.0f, 1.0f, 1.0f, ((i + 0.25f) * 3.14159f / 4.0f)); pushStreakQuad(copyBuffer, 0.0f, 0.0f, 0.5f, 7.0f, 0.0f, 0.0f, 1.0f, 1.0f, ((i + 0.5f) * 3.14159f / 4.0f)); @@ -160,7 +300,7 @@ public class LensFlareMeshRenderer { try (DataInputStream dis = new DataInputStream( Minecraft.getMinecraft().getResourceManager().getResource(streaksTextureLocation).getInputStream())) { loadFlareTexture(copyBuffer, dis); - }catch(IOException ex) { + } catch (IOException ex) { EagRuntime.freeByteBuffer(copyBuffer); throw new RuntimeException("Could not load: " + streaksTextureLocation, ex); } @@ -170,7 +310,7 @@ public class LensFlareMeshRenderer { try (DataInputStream dis = new DataInputStream( Minecraft.getMinecraft().getResourceManager().getResource(ghostsTextureLocation).getInputStream())) { loadFlareTexture(copyBuffer, dis); - }catch(IOException ex) { + } catch (IOException ex) { EagRuntime.freeByteBuffer(copyBuffer); throw new RuntimeException("Could not load: " + ghostsTextureLocation, ex); } @@ -185,12 +325,12 @@ public class LensFlareMeshRenderer { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); _wglPixelStorei(GL_UNPACK_ALIGNMENT, 1); int mip = 0; - while(dis.read() == 'E') { + while (dis.read() == 'E') { int w = dis.readShort(); int h = dis.readShort(); copyBuffer.clear(); - for(int i = 0, l = w * h; i < l; ++i) { - copyBuffer.put((byte)dis.read()); + for (int i = 0, l = w * h; i < l; ++i) { + copyBuffer.put((byte) dis.read()); } copyBuffer.flip(); _wglTexImage2D(GL_TEXTURE_2D, mip++, _GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, copyBuffer); @@ -199,6 +339,26 @@ public class LensFlareMeshRenderer { _wglPixelStorei(GL_UNPACK_ALIGNMENT, 4); } + static void pushGhostQuad(ByteBuffer copyBuffer, float offset, float scale, int sprite, float r, float g, float b, + float a) { + copyBuffer.putFloat(offset); + copyBuffer.putFloat(scale); + copyBuffer.putFloat(0.0f); + copyBuffer.putFloat((float) sprite / ghostsSpriteCount); + copyBuffer.putFloat(1.0f); + copyBuffer.putFloat(1.0f / ghostsSpriteCount); + copyBuffer.putFloat(r * a); + copyBuffer.putFloat(g * a); + copyBuffer.putFloat(b * a); + ++ghostsInstanceCount; + } + + static void pushGhostQuadAbberated(ByteBuffer copyBuffer, float offset, float scale, int sprite, float r, float g, + float b, float a) { + pushGhostQuad(copyBuffer, offset, scale, sprite, 0.0f, g, b, a); + pushGhostQuad(copyBuffer, offset + 0.005f, scale, sprite, r, 0.0f, 0.0f, a); + } + static void pushStreakQuad(ByteBuffer copyBuffer, float x, float y, float w, float h, float tx, float ty, float tw, float th, float rotation) { tmpMat.m00 = MathHelper.cos(rotation); @@ -207,164 +367,45 @@ public class LensFlareMeshRenderer { tmpMat.m11 = tmpMat.m00; tmpMat.m20 = x; tmpMat.m21 = y; - + tmpVec.x = -w; tmpVec.y = -h; tmpVec.z = 1.0f; Matrix3f.transform(tmpMat, tmpVec, tmpVec); - + copyBuffer.putFloat(tmpVec.x); copyBuffer.putFloat(tmpVec.y); copyBuffer.putFloat(tx); copyBuffer.putFloat(ty); - + tmpVec.x = w; tmpVec.y = -h; tmpVec.z = 1.0f; Matrix3f.transform(tmpMat, tmpVec, tmpVec); - + copyBuffer.putFloat(tmpVec.x); copyBuffer.putFloat(tmpVec.y); copyBuffer.putFloat(tx + tw); copyBuffer.putFloat(ty); - + tmpVec.x = w; tmpVec.y = h; tmpVec.z = 1.0f; Matrix3f.transform(tmpMat, tmpVec, tmpVec); - + copyBuffer.putFloat(tmpVec.x); copyBuffer.putFloat(tmpVec.y); copyBuffer.putFloat(tx + tw); copyBuffer.putFloat(ty + th); - + tmpVec.x = -w; tmpVec.y = h; tmpVec.z = 1.0f; Matrix3f.transform(tmpMat, tmpVec, tmpVec); - + copyBuffer.putFloat(tmpVec.x); copyBuffer.putFloat(tmpVec.y); copyBuffer.putFloat(tx); copyBuffer.putFloat(ty + th); } - - static void pushGhostQuadAbberated(ByteBuffer copyBuffer, float offset, float scale, int sprite, float r, float g, float b, float a) { - pushGhostQuad(copyBuffer, offset, scale, sprite, 0.0f, g, b, a); - pushGhostQuad(copyBuffer, offset + 0.005f, scale, sprite, r, 0.0f, 0.0f, a); - } - - static void pushGhostQuad(ByteBuffer copyBuffer, float offset, float scale, int sprite, float r, float g, float b, float a) { - copyBuffer.putFloat(offset); - copyBuffer.putFloat(scale); - copyBuffer.putFloat(0.0f); - copyBuffer.putFloat((float)sprite / ghostsSpriteCount); - copyBuffer.putFloat(1.0f); - copyBuffer.putFloat(1.0f / ghostsSpriteCount); - copyBuffer.putFloat(r * a); - copyBuffer.putFloat(g * a); - copyBuffer.putFloat(b * a); - ++ghostsInstanceCount; - } - - static void drawLensFlares(float sunScreenX, float sunScreenY) { - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_ONE, GL_ONE); - - GlStateManager.setActiveTexture(GL_TEXTURE2); - GlStateManager.bindTexture(EaglerDeferredPipeline.instance.sunOcclusionValueTexture); - GlStateManager.setActiveTexture(GL_TEXTURE1); - GlStateManager.bindTexture(EaglerDeferredPipeline.instance.exposureBlendTexture); - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(streaksTexture); - - streaksProgram.useProgram(); - - Minecraft mc = Minecraft.getMinecraft(); - float aspectRatio = (float)mc.displayHeight / (float)mc.displayWidth; - - float fov = 90.0f / mc.entityRenderer.getFOVModifier(EaglerDeferredPipeline.instance.getPartialTicks(), true); - float size = 0.075f * fov * (1.0f + MathHelper.sqrt_float(sunScreenX * sunScreenX + sunScreenY * sunScreenY)); - - tmpMat.setIdentity(); - tmpMat.m00 = aspectRatio * 2.0f * size; - tmpMat.m11 = size; - tmpMat.m20 = sunScreenX; - tmpMat.m21 = sunScreenY; - - float rotation = sunScreenX * sunScreenX * Math.signum(sunScreenX) + sunScreenY * sunScreenY * Math.signum(sunScreenY); - - tmpMat2.setIdentity(); - tmpMat2.m00 = MathHelper.cos(rotation); - tmpMat2.m01 = MathHelper.sin(rotation); - tmpMat2.m10 = -tmpMat2.m01; - tmpMat2.m11 = tmpMat2.m00; - Matrix3f.mul(tmpMat, tmpMat2, tmpMat); - - EaglerDeferredPipeline.uniformMatrixHelper(streaksProgram.uniforms.u_sunFlareMatrix3f, tmpMat); - - Vector3f v = DeferredStateManager.currentSunLightColor; - float mag = 1.0f + DeferredStateManager.currentSunAngle.y * 0.8f; - if(mag > 1.0f) { - mag = 1.0f - (mag - 1.0f) * 20.0f; - if(mag < 0.0f) { - mag = 0.0f; - } - } - mag = 0.003f * (1.0f + mag * mag * mag * 4.0f); - _wglUniform3f(streaksProgram.uniforms.u_flareColor3f, v.x * mag * 0.5f, v.y * mag * 0.5f, v.z * mag * 0.5f); - - EaglercraftGPU.bindGLBufferArray(streaksVertexArray); - _wglDrawElements(GL_TRIANGLES, streaksVertexCount + (streaksVertexCount >> 1), GL_UNSIGNED_SHORT, 0); - - ghostsProgram.useProgram(); - - GlStateManager.setActiveTexture(GL_TEXTURE0); - GlStateManager.bindTexture(ghostsTexture); - - _wglUniform3f(ghostsProgram.uniforms.u_flareColor3f, v.x * mag, v.y * mag, v.z * mag); - _wglUniform1f(ghostsProgram.uniforms.u_aspectRatio1f, aspectRatio); - _wglUniform2f(ghostsProgram.uniforms.u_sunPosition2f, sunScreenX, sunScreenY); - _wglUniform1f(ghostsProgram.uniforms.u_baseScale1f, fov); - - EaglercraftGPU.bindGLBufferArray(ghostsVertexArray); - _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, ghostsInstanceCount); - - GlStateManager.disableBlend(); - } - - static void destroy() { - if(streaksVertexArray != null) { - _wglDeleteVertexArrays(streaksVertexArray); - streaksVertexArray = null; - } - if(streaksVertexBuffer != null) { - _wglDeleteBuffers(streaksVertexBuffer); - streaksVertexBuffer = null; - } - if(ghostsVertexArray != null) { - _wglDeleteVertexArrays(ghostsVertexArray); - ghostsVertexArray = null; - } - if(ghostsVertexBuffer != null) { - _wglDeleteBuffers(ghostsVertexBuffer); - ghostsVertexBuffer = null; - } - if(streaksTexture != -1) { - GlStateManager.deleteTexture(streaksTexture); - streaksTexture = -1; - } - if(ghostsTexture != -1) { - GlStateManager.deleteTexture(ghostsTexture); - ghostsTexture = -1; - } - if(streaksProgram != null) { - streaksProgram.destroy(); - streaksProgram = null; - } - if(ghostsProgram != null) { - ghostsProgram.destroy(); - ghostsProgram = null; - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LightSourceMesh.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LightSourceMesh.java index bdcd2ed4..716e2186 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LightSourceMesh.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/LightSourceMesh.java @@ -1,8 +1,22 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindBuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawElements; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ELEMENT_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_INT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_HALF_FLOAT; import java.io.DataInputStream; import java.io.IOException; @@ -20,14 +34,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,37 +64,58 @@ public class LightSourceMesh { typeBytes = type.getBytes(StandardCharsets.UTF_8); } + public void destroy() { + if (meshVBO != null) { + _wglDeleteBuffers(meshVBO); + meshVBO = null; + } + if (meshIBO != null) { + _wglDeleteBuffers(meshIBO); + meshIBO = null; + } + if (meshVAO != null) { + _wglDeleteVertexArrays(meshVAO); + meshVAO = null; + } + } + + public void drawMeshVAO() { + EaglercraftGPU.bindGLBufferArray(meshVAO); + _wglDrawElements(GL_TRIANGLES, meshIndexCount, meshIndexType, 0); + } + public void load() throws IOException { destroy(); try (DataInputStream is = new DataInputStream( Minecraft.getMinecraft().getResourceManager().getResource(meshLocation).getInputStream())) { - if(is.read() != 0xEE || is.read() != 0xAA || is.read() != 0x66 || is.read() != '%') { + if (is.read() != 0xEE || is.read() != 0xAA || is.read() != 0x66 || is.read() != '%') { throw new IOException("Bad file type for: " + meshLocation.toString()); } byte[] bb = new byte[is.read()]; is.read(bb); - if(!Arrays.equals(bb, typeBytes)) { - throw new IOException("Bad file type \"" + new String(bb, StandardCharsets.UTF_8) + "\" for: " + meshLocation.toString()); + if (!Arrays.equals(bb, typeBytes)) { + throw new IOException("Bad file type \"" + new String(bb, StandardCharsets.UTF_8) + "\" for: " + + meshLocation.toString()); } - + int vboLength = is.readInt() * 6; byte[] readBuffer = new byte[vboLength]; is.read(readBuffer); - + ByteBuffer buf = EagRuntime.allocateByteBuffer(readBuffer.length); buf.put(readBuffer); buf.flip(); - + meshVBO = _wglGenBuffers(); EaglercraftGPU.bindGLArrayBuffer(meshVBO); _wglBufferData(GL_ARRAY_BUFFER, buf, GL_STATIC_DRAW); - + EagRuntime.freeByteBuffer(buf); - + int iboLength = meshIndexCount = is.readInt(); int iboType = is.read(); iboLength *= iboType; - switch(iboType) { + switch (iboType) { case 1: meshIndexType = GL_UNSIGNED_BYTE; break; @@ -92,46 +128,26 @@ public class LightSourceMesh { default: throw new IOException("Unsupported index buffer type: " + iboType); } - + readBuffer = new byte[iboLength]; is.read(readBuffer); - + buf = EagRuntime.allocateByteBuffer(readBuffer.length); buf.put(readBuffer); buf.flip(); - + meshVAO = _wglGenVertexArrays(); EaglercraftGPU.bindGLBufferArray(meshVAO); - + meshIBO = _wglGenBuffers(); _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, meshIBO); _wglBufferData(GL_ELEMENT_ARRAY_BUFFER, buf, GL_STATIC_DRAW); EagRuntime.freeByteBuffer(buf); - + EaglercraftGPU.bindGLArrayBuffer(meshVBO); - + _wglEnableVertexAttribArray(0); _wglVertexAttribPointer(0, 3, _GL_HALF_FLOAT, false, 6, 0); } } - - public void drawMeshVAO() { - EaglercraftGPU.bindGLBufferArray(meshVAO); - _wglDrawElements(GL_TRIANGLES, meshIndexCount, meshIndexType, 0); - } - - public void destroy() { - if(meshVBO != null) { - _wglDeleteBuffers(meshVBO); - meshVBO = null; - } - if(meshIBO != null) { - _wglDeleteBuffers(meshIBO); - meshIBO = null; - } - if(meshVAO != null) { - _wglDeleteVertexArrays(meshVAO); - meshVAO = null; - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ListSerial.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ListSerial.java index 7d19b521..8f92913a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ListSerial.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ListSerial.java @@ -5,26 +5,27 @@ import java.util.List; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface ListSerial extends List { - int getEaglerSerial(); + boolean eaglerCheck(); void eaglerIncrSerial(); void eaglerResetCheck(); - boolean eaglerCheck(); + int getEaglerSerial(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/NameTagRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/NameTagRenderer.java index 73703597..bb9d5a0c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/NameTagRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/NameTagRenderer.java @@ -5,14 +5,15 @@ import net.minecraft.entity.Entity; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,21 +25,13 @@ public class NameTagRenderer { public static int nameTagsCount = 0; static { - for(int i = 0; i < nameTagsThisFrame.length; ++i) { + for (int i = 0; i < nameTagsThisFrame.length; ++i) { nameTagsThisFrame[i] = new NameTagRenderer(); } } - public Entity entityIn; - public String str; - public double x; - public double y; - public double z; - public int maxDistance; - public double dst2; - public static void renderNameTag(Entity entityIn, String str, double x, double y, double z, int maxDistance) { - if(!doRenderNameTags || nameTagsCount >= nameTagsThisFrame.length) { + if (!doRenderNameTags || nameTagsCount >= nameTagsThisFrame.length) { return; } NameTagRenderer n = nameTagsThisFrame[nameTagsCount++]; @@ -51,4 +44,13 @@ public class NameTagRenderer { n.maxDistance = maxDistance; } + public Entity entityIn; + public String str; + public double x; + public double y; + public double z; + public int maxDistance; + + public double dst2; + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfo.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfo.java index 4837b044..bab25f15 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfo.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfo.java @@ -10,14 +10,15 @@ import org.json.JSONObject; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,10 +55,10 @@ public class ShaderPackInfo { apiVers = json.optInt("api_vers", -1); supportedFeatures = new HashSet<>(); JSONArray features = json.getJSONArray("features"); - if(features.length() == 0) { + if (features.length() == 0) { throw new JSONException("No supported features list has been defined for this shader pack!"); } - for(int i = 0, l = features.length(); i < l; ++i) { + for (int i = 0, l = features.length(); i < l; ++i) { supportedFeatures.add(features.getString(i)); } WAVING_BLOCKS = supportedFeatures.contains("WAVING_BLOCKS"); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfoReloadListener.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfoReloadListener.java index ba81c21a..509c564e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfoReloadListener.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShaderPackInfoReloadListener.java @@ -12,14 +12,15 @@ import net.minecraft.client.resources.IResourceManagerReloadListener; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,14 +34,14 @@ public class ShaderPackInfoReloadListener implements IResourceManagerReloadListe Minecraft mc = Minecraft.getMinecraft(); try { mc.gameSettings.deferredShaderConf.reloadShaderPackInfo(mcResourceManager); - }catch(IOException ex) { + } catch (IOException ex) { logger.info("Could not reload shader pack info!"); logger.info(ex); logger.info("Shaders have been disabled"); mc.gameSettings.shaders = false; } TextureMap tm = mc.getTextureMapBlocks(); - if(tm != null) { + if (tm != null) { mc.getTextureMapBlocks().setEnablePBREagler(mc.gameSettings.shaders); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShadersRenderPassFuture.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShadersRenderPassFuture.java index f5af571b..a8a56230 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShadersRenderPassFuture.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/ShadersRenderPassFuture.java @@ -6,14 +6,15 @@ import net.minecraft.entity.Entity; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,6 +30,30 @@ public abstract class ShadersRenderPassFuture { protected float z; protected float partialTicks; + private final float[] tmp = new float[1]; + + public ShadersRenderPassFuture(Entity e) { + this(e, EaglerDeferredPipeline.instance.getPartialTicks()); + } + + public ShadersRenderPassFuture(Entity e, float partialTicks) { + this.x = (float) ((e.posX - e.prevPosX) * partialTicks + e.prevPosX + - TileEntityRendererDispatcher.staticPlayerX); + this.y = (float) ((e.posY - e.prevPosY) * partialTicks + e.prevPosY + - TileEntityRendererDispatcher.staticPlayerY); + this.z = (float) ((e.posZ - e.prevPosZ) * partialTicks + e.prevPosZ + - TileEntityRendererDispatcher.staticPlayerZ); + } + + public ShadersRenderPassFuture(float x, float y, float z, float partialTicks) { + this.x = x; + this.y = y; + this.z = z; + this.partialTicks = partialTicks; + } + + public abstract void draw(PassType pass); + public float getX() { return x; } @@ -41,27 +66,6 @@ public abstract class ShadersRenderPassFuture { return z; } - public ShadersRenderPassFuture(float x, float y, float z, float partialTicks) { - this.x = x; - this.y = y; - this.z = z; - this.partialTicks = partialTicks; - } - - public ShadersRenderPassFuture(Entity e, float partialTicks) { - this.x = (float)((e.posX - e.prevPosX) * partialTicks + e.prevPosX - TileEntityRendererDispatcher.staticPlayerX); - this.y = (float)((e.posY - e.prevPosY) * partialTicks + e.prevPosY - TileEntityRendererDispatcher.staticPlayerY); - this.z = (float)((e.posZ - e.prevPosZ) * partialTicks + e.prevPosZ - TileEntityRendererDispatcher.staticPlayerZ); - } - - public ShadersRenderPassFuture(Entity e) { - this(e, EaglerDeferredPipeline.instance.getPartialTicks()); - } - - public abstract void draw(PassType pass); - - private final float[] tmp = new float[1]; - public float[] tmpValue() { return tmp; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/SkyboxRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/SkyboxRenderer.java index 6d862da7..cdade29f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/SkyboxRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/SkyboxRenderer.java @@ -1,8 +1,33 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBindBuffer; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawElements; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexImage2D; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ELEMENT_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA8; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_INT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_HALF_FLOAT; import java.io.DataInputStream; import java.io.IOException; @@ -21,14 +46,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -58,60 +84,109 @@ public class SkyboxRenderer { skyboxLocation = is; } + public void destroy() { + if (skyboxVBO != null) { + _wglDeleteBuffers(skyboxVBO); + skyboxVBO = null; + } + if (skyboxIBO != null) { + _wglDeleteBuffers(skyboxIBO); + skyboxVBO = null; + } + if (skyboxVAO != null) { + _wglDeleteVertexArrays(skyboxVAO); + skyboxVBO = null; + } + if (normalsLUT != -1) { + GlStateManager.deleteTexture(normalsLUT); + normalsLUT = -1; + } + } + + public void drawBottom() { + EaglercraftGPU.bindGLBufferArray(skyboxVAO); + _wglDrawElements(GL_TRIANGLES, skyboxBottomIndexCount, skyboxIndexType, + skyboxBottomIndexOffset * skyboxIndexStride); + } + + public void drawFull() { + EaglercraftGPU.bindGLBufferArray(skyboxVAO); + _wglDrawElements(GL_TRIANGLES, skyboxIndexCount, skyboxIndexType, 0); + } + + public void drawTop() { + EaglercraftGPU.bindGLBufferArray(skyboxVAO); + _wglDrawElements(GL_TRIANGLES, skyboxTopIndexCount, skyboxIndexType, skyboxTopIndexOffset * skyboxIndexStride); + } + + public int getAtmosLUTHeight() { + return atmosphereLUTHeight; + } + + public int getAtmosLUTWidth() { + return atmosphereLUTWidth; + } + + public int getNormalsLUT() { + return normalsLUT; + } + public void load() throws IOException { destroy(); try (DataInputStream is = new DataInputStream( Minecraft.getMinecraft().getResourceManager().getResource(skyboxLocation).getInputStream())) { - if(is.read() != 0xEE || is.read() != 0xAA || is.read() != 0x66 || is.read() != '%') { + if (is.read() != 0xEE || is.read() != 0xAA || is.read() != 0x66 || is.read() != '%') { throw new IOException("Bad file type for: " + skyboxLocation.toString()); } byte[] bb = new byte[is.read()]; is.read(bb); - if(!Arrays.equals(bb, new byte[] { 's', 'k', 'y', 'b', 'o', 'x' })) { - throw new IOException("Bad file type \"" + new String(bb, StandardCharsets.UTF_8) + "\" for: " + skyboxLocation.toString()); + if (!Arrays.equals(bb, new byte[] { 's', 'k', 'y', 'b', 'o', 'x' })) { + throw new IOException("Bad file type \"" + new String(bb, StandardCharsets.UTF_8) + "\" for: " + + skyboxLocation.toString()); } atmosphereLUTWidth = is.readUnsignedShort(); atmosphereLUTHeight = is.readUnsignedShort(); byte[] readBuffer = new byte[atmosphereLUTWidth * atmosphereLUTHeight * 4]; is.read(readBuffer); - + ByteBuffer buf = EagRuntime.allocateByteBuffer(readBuffer.length); buf.put(readBuffer); buf.flip(); - + normalsLUT = GlStateManager.generateTexture(); GlStateManager.bindTexture(normalsLUT); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, atmosphereLUTWidth, atmosphereLUTHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, buf); - + _wglTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, atmosphereLUTWidth, atmosphereLUTHeight, 0, GL_RGBA, + GL_UNSIGNED_BYTE, buf); + EagRuntime.freeByteBuffer(buf); skyboxTopIndexOffset = is.readInt(); skyboxTopIndexCount = is.readInt(); skyboxBottomIndexOffset = is.readInt(); skyboxBottomIndexCount = is.readInt(); - + int vboLength = is.readInt() * 8; readBuffer = new byte[vboLength]; is.read(readBuffer); - + buf = EagRuntime.allocateByteBuffer(readBuffer.length); buf.put(readBuffer); buf.flip(); - + skyboxVBO = _wglGenBuffers(); EaglercraftGPU.bindGLArrayBuffer(skyboxVBO); _wglBufferData(GL_ARRAY_BUFFER, buf, GL_STATIC_DRAW); - + EagRuntime.freeByteBuffer(buf); - + int iboLength = skyboxIndexCount = is.readInt(); int iboType = is.read(); iboLength *= iboType; - switch(iboType) { + switch (iboType) { case 1: skyboxIndexType = GL_UNSIGNED_BYTE; break; @@ -124,78 +199,32 @@ public class SkyboxRenderer { default: throw new IOException("Unsupported index buffer type: " + iboType); } - + skyboxIndexStride = iboType; - + readBuffer = new byte[iboLength]; is.read(readBuffer); - + buf = EagRuntime.allocateByteBuffer(readBuffer.length); buf.put(readBuffer); buf.flip(); - + skyboxVAO = _wglGenVertexArrays(); EaglercraftGPU.bindGLBufferArray(skyboxVAO); - + skyboxIBO = _wglGenBuffers(); _wglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skyboxIBO); _wglBufferData(GL_ELEMENT_ARRAY_BUFFER, buf, GL_STATIC_DRAW); EagRuntime.freeByteBuffer(buf); - + EaglercraftGPU.bindGLArrayBuffer(skyboxVBO); - + _wglEnableVertexAttribArray(0); _wglVertexAttribPointer(0, 3, _GL_HALF_FLOAT, false, 8, 0); - + _wglEnableVertexAttribArray(1); _wglVertexAttribPointer(1, 2, GL_UNSIGNED_BYTE, true, 8, 6); } } - public int getNormalsLUT() { - return normalsLUT; - } - - public int getAtmosLUTWidth() { - return atmosphereLUTWidth; - } - - public int getAtmosLUTHeight() { - return atmosphereLUTHeight; - } - - public void drawTop() { - EaglercraftGPU.bindGLBufferArray(skyboxVAO); - _wglDrawElements(GL_TRIANGLES, skyboxTopIndexCount, skyboxIndexType, skyboxTopIndexOffset * skyboxIndexStride); - } - - public void drawBottom() { - EaglercraftGPU.bindGLBufferArray(skyboxVAO); - _wglDrawElements(GL_TRIANGLES, skyboxBottomIndexCount, skyboxIndexType, skyboxBottomIndexOffset * skyboxIndexStride); - } - - public void drawFull() { - EaglercraftGPU.bindGLBufferArray(skyboxVAO); - _wglDrawElements(GL_TRIANGLES, skyboxIndexCount, skyboxIndexType, 0); - } - - public void destroy() { - if(skyboxVBO != null) { - _wglDeleteBuffers(skyboxVBO); - skyboxVBO = null; - } - if(skyboxIBO != null) { - _wglDeleteBuffers(skyboxIBO); - skyboxVBO = null; - } - if(skyboxVAO != null) { - _wglDeleteVertexArrays(skyboxVAO); - skyboxVBO = null; - } - if(normalsLUT != -1) { - GlStateManager.deleteTexture(normalsLUT); - normalsLUT = -1; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/VertexMarkerState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/VertexMarkerState.java index e2d86c70..503502e4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/VertexMarkerState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/VertexMarkerState.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfig.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfig.java index 6451750f..7b8b735c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfig.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfig.java @@ -15,14 +15,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,58 +45,31 @@ public class GuiShaderConfig extends GuiScreen { this.shaderStartState = Minecraft.getMinecraft().gameSettings.shaders; } - public void initGui() { - this.title = I18n.format("shaders.gui.title"); - this.buttonList.clear(); - this.buttonList.add(enableDisableButton = new GuiButton(0, width / 2 - 155, height - 30, 150, 20, I18n.format("shaders.gui.enable") - + ": " + (mc.gameSettings.shaders ? I18n.format("gui.yes") : I18n.format("gui.no")))); - this.buttonList.add(new GuiButton(1, width / 2 + 5, height - 30, 150, 20, I18n.format("gui.done"))); - if(listView == null) { - this.listView = new GuiShaderConfigList(this, mc); - }else { - this.listView.resize(); - } - } - protected void actionPerformed(GuiButton btn) { - if(btn.id == 0) { + if (btn.id == 0) { mc.gameSettings.shaders = !mc.gameSettings.shaders; listView.setAllDisabled(!mc.gameSettings.shaders); enableDisableButton.displayString = I18n.format("shaders.gui.enable") + ": " + (mc.gameSettings.shaders ? I18n.format("gui.yes") : I18n.format("gui.no")); - }else if(btn.id == 1) { + } else if (btn.id == 1) { mc.displayGuiScreen(parent); } } - public void onGuiClosed() { - if(shaderStartState != mc.gameSettings.shaders || listView.isDirty()) { - mc.gameSettings.saveOptions(); - if(shaderStartState != mc.gameSettings.shaders) { - mc.loadingScreen.eaglerShowRefreshResources(); - mc.refreshResources(); - }else { - logger.info("Reloading shaders..."); - try { - mc.gameSettings.deferredShaderConf.reloadShaderPackInfo(mc.getResourceManager()); - }catch(IOException ex) { - logger.info("Could not reload shader pack info!"); - logger.info(ex); - logger.info("Shaders have been disabled"); - mc.gameSettings.shaders = false; - mc.refreshResources(); - return; - } + public void drawScreen(int i, int j, float f) { + this.drawBackground(0); + listView.drawScreen(i, j, f); + drawCenteredString(this.fontRendererObj, title, this.width / 2, 15, 16777215); + super.drawScreen(i, j, f); + listView.postRender(i, j, f); + } - if(mc.gameSettings.shaders) { - ShaderSource.clearCache(); - } + FontRenderer getFontRenderer() { + return fontRendererObj; + } - if (mc.renderGlobal != null) { - mc.renderGlobal.loadRenderers(); - } - } - } + Minecraft getMinecraft() { + return mc; } public void handleMouseInput() throws IOException { @@ -108,6 +82,20 @@ public class GuiShaderConfig extends GuiScreen { listView.handleTouchInput(); } + public void initGui() { + this.title = I18n.format("shaders.gui.title"); + this.buttonList.clear(); + this.buttonList.add(enableDisableButton = new GuiButton(0, width / 2 - 155, height - 30, 150, 20, + I18n.format("shaders.gui.enable") + ": " + + (mc.gameSettings.shaders ? I18n.format("gui.yes") : I18n.format("gui.no")))); + this.buttonList.add(new GuiButton(1, width / 2 + 5, height - 30, 150, 20, I18n.format("gui.done"))); + if (listView == null) { + this.listView = new GuiShaderConfigList(this, mc); + } else { + this.listView.resize(); + } + } + protected void mouseClicked(int parInt1, int parInt2, int parInt3) { super.mouseClicked(parInt1, parInt2, parInt3); listView.mouseClicked(parInt1, parInt2, parInt3); @@ -118,23 +106,37 @@ public class GuiShaderConfig extends GuiScreen { listView.mouseReleased(i, j, k); } - public void drawScreen(int i, int j, float f) { - this.drawBackground(0); - listView.drawScreen(i, j, f); - drawCenteredString(this.fontRendererObj, title, this.width / 2, 15, 16777215); - super.drawScreen(i, j, f); - listView.postRender(i, j, f); + public void onGuiClosed() { + if (shaderStartState != mc.gameSettings.shaders || listView.isDirty()) { + mc.gameSettings.saveOptions(); + if (shaderStartState != mc.gameSettings.shaders) { + mc.loadingScreen.eaglerShowRefreshResources(); + mc.refreshResources(); + } else { + logger.info("Reloading shaders..."); + try { + mc.gameSettings.deferredShaderConf.reloadShaderPackInfo(mc.getResourceManager()); + } catch (IOException ex) { + logger.info("Could not reload shader pack info!"); + logger.info(ex); + logger.info("Shaders have been disabled"); + mc.gameSettings.shaders = false; + mc.refreshResources(); + return; + } + + if (mc.gameSettings.shaders) { + ShaderSource.clearCache(); + } + + if (mc.renderGlobal != null) { + mc.renderGlobal.loadRenderers(); + } + } + } } void renderTooltip(List txt, int x, int y) { drawHoveringText(txt, x, y); } - - FontRenderer getFontRenderer() { - return fontRendererObj; - } - - Minecraft getMinecraft() { - return mc; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfigList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfigList.java index 9d62b7f0..9b766231 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfigList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShaderConfigList.java @@ -17,476 +17,21 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiShaderConfigList extends GuiListExtended { - public static final ResourceLocation shaderPackIcon = new ResourceLocation("eagler:glsl/deferred/shader_pack_icon.png"); - - private final GuiShaderConfig screen; - - private final List list = new ArrayList<>(); - - private static abstract class ShaderOption { - - private final String label; - private final List desc; - - private ShaderOption(String label, List desc) { - this.label = label; - this.desc = desc; - } - - protected abstract String getDisplayValue(); - - protected abstract void toggleOption(GuiButton button, int dir); - - protected abstract boolean getDirty(); - - } - - private static List loadDescription(String key) { - List ret = new ArrayList<>(); - String msg; - int i = 0; - while(true) { - if((msg = I18n.format(key + '.' + i)).equals(key + '.' + i)) { - if(!I18n.format(key + '.' + (i + 1)).equals(key + '.' + (i + 1))) { - msg = ""; - }else { - break; - } - } - ret.add(msg); - ++i; - } - if(ret.size() == 0) { - ret.add("" + EnumChatFormatting.GRAY + EnumChatFormatting.ITALIC + "(no description found)"); - } - return ret; - } - - private static String loadShaderLbl(String key) { - return I18n.format("shaders.gui.option." + key + ".label"); - } - - private static List loadShaderDesc(String key) { - return loadDescription("shaders.gui.option." + key + ".desc"); - } - - private static String getColoredOnOff(boolean state, EnumChatFormatting on, EnumChatFormatting off) { - return state ? "" + on + I18n.format("options.on") : "" + off + I18n.format("options.off"); - } - - private void addAllOptions(List opts) { - for(int i = 0, l = opts.size(); i < l; ++i) { - ShaderOption opt1 = opts.get(i); - if(++i >= l) { - list.add(new ListEntryButtonRow(opt1, null, null)); - break; - } - ShaderOption opt2 = opts.get(i); - if(++i >= l) { - list.add(new ListEntryButtonRow(opt1, opt2, null)); - break; - } - list.add(new ListEntryButtonRow(opt1, opt2, opts.get(i))); - } - } - - public GuiShaderConfigList(GuiShaderConfig screen, Minecraft mcIn) { - super(mcIn, screen.width, screen.height, 32, screen.height - 40, 30); - this.screen = screen; - this.list.add(new ListEntryHeader("Current Shader Pack:")); - this.list.add(new ListEntryPackInfo()); - this.list.add(new ListEntrySpacing()); - this.list.add(new ListEntrySpacing()); - this.list.add(new ListEntryHeader(I18n.format("shaders.gui.headerTier1"))); - List opts = new ArrayList<>(); - EaglerDeferredConfig conf = mcIn.gameSettings.deferredShaderConf; - if(conf.shaderPackInfo.WAVING_BLOCKS) { - opts.add(new ShaderOption(loadShaderLbl("WAVING_BLOCKS"), loadShaderDesc("WAVING_BLOCKS")) { - private final boolean originalValue = conf.wavingBlocks; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.wavingBlocks, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.wavingBlocks = !conf.wavingBlocks; - } - @Override - protected boolean getDirty() { - return conf.wavingBlocks != originalValue; - } - }); - } - if(conf.shaderPackInfo.DYNAMIC_LIGHTS) { - opts.add(new ShaderOption(loadShaderLbl("DYNAMIC_LIGHTS"), loadShaderDesc("DYNAMIC_LIGHTS")) { - private final boolean originalValue = conf.dynamicLights; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.dynamicLights, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.dynamicLights = !conf.dynamicLights; - } - @Override - protected boolean getDirty() { - return conf.dynamicLights != originalValue; - } - }); - } - if(conf.shaderPackInfo.GLOBAL_AMBIENT_OCCLUSION) { - opts.add(new ShaderOption(loadShaderLbl("GLOBAL_AMBIENT_OCCLUSION"), loadShaderDesc("GLOBAL_AMBIENT_OCCLUSION")) { - private final boolean originalValue = conf.ssao; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.ssao, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.ssao = !conf.ssao; - } - @Override - protected boolean getDirty() { - return conf.ssao != originalValue; - } - }); - } - if(conf.shaderPackInfo.SHADOWS_SUN) { - opts.add(new ShaderOption(loadShaderLbl("SHADOWS_SUN"), loadShaderDesc("SHADOWS_SUN")) { - private final int originalValue = conf.shadowsSun; - @Override - protected String getDisplayValue() { - return conf.shadowsSun == 0 ? "" + EnumChatFormatting.RED + "0" : "" + EnumChatFormatting.YELLOW + (1 << (conf.shadowsSun + 3)); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.shadowsSun = (conf.shadowsSun + dir + 5) % 5; - } - @Override - protected boolean getDirty() { - return conf.shadowsSun != originalValue; - } - }); - } - if(conf.shaderPackInfo.REFLECTIONS_PARABOLOID) { - opts.add(new ShaderOption(loadShaderLbl("REFLECTIONS_PARABOLOID"), loadShaderDesc("REFLECTIONS_PARABOLOID")) { - private final boolean originalValue = conf.useEnvMap; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.useEnvMap, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.useEnvMap = !conf.useEnvMap; - } - @Override - protected boolean getDirty() { - return conf.useEnvMap != originalValue; - } - }); - } - if(conf.shaderPackInfo.POST_LENS_DISTORION) { - opts.add(new ShaderOption(loadShaderLbl("POST_LENS_DISTORION"), loadShaderDesc("POST_LENS_DISTORION")) { - private final boolean originalValue = conf.lensDistortion; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.lensDistortion, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.lensDistortion = !conf.lensDistortion; - } - @Override - protected boolean getDirty() { - return conf.lensDistortion != originalValue; - } - }); - } - if(conf.shaderPackInfo.POST_LENS_FLARES) { - opts.add(new ShaderOption(loadShaderLbl("POST_LENS_FLARES"), loadShaderDesc("POST_LENS_FLARES")) { - private final boolean originalValue = conf.lensFlares; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.lensFlares, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.lensFlares = !conf.lensFlares; - } - @Override - protected boolean getDirty() { - return conf.lensFlares != originalValue; - } - }); - } - if(conf.shaderPackInfo.POST_FXAA) { - opts.add(new ShaderOption(loadShaderLbl("POST_FXAA"), loadShaderDesc("POST_FXAA")) { - private final boolean originalValue = conf.fxaa; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.fxaa, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.fxaa = !conf.fxaa; - } - @Override - protected boolean getDirty() { - return conf.fxaa != originalValue; - } - }); - } - this.addAllOptions(opts); - opts.clear(); - this.list.add(new ListEntryHeader(I18n.format("shaders.gui.headerTier2"))); - if(conf.shaderPackInfo.SHADOWS_COLORED) { - opts.add(new ShaderOption(loadShaderLbl("SHADOWS_COLORED"), loadShaderDesc("SHADOWS_COLORED")) { - private final boolean originalValue = conf.shadowsColored; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.shadowsColored, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.shadowsColored = !conf.shadowsColored; - } - @Override - protected boolean getDirty() { - return conf.shadowsColored != originalValue; - } - }); - } - if(conf.shaderPackInfo.SHADOWS_SMOOTHED) { - opts.add(new ShaderOption(loadShaderLbl("SHADOWS_SMOOTHED"), loadShaderDesc("SHADOWS_SMOOTHED")) { - private final boolean originalValue = conf.shadowsSmoothed; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.shadowsSmoothed, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.shadowsSmoothed = !conf.shadowsSmoothed; - } - @Override - protected boolean getDirty() { - return conf.shadowsSmoothed != originalValue; - } - }); - } - if(conf.shaderPackInfo.REALISTIC_WATER) { - opts.add(new ShaderOption(loadShaderLbl("REALISTIC_WATER"), loadShaderDesc("REALISTIC_WATER")) { - private final boolean originalValue = conf.realisticWater; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.realisticWater, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.realisticWater = !conf.realisticWater; - } - @Override - protected boolean getDirty() { - return conf.realisticWater != originalValue; - } - }); - } - if(conf.shaderPackInfo.POST_BLOOM) { - opts.add(new ShaderOption(loadShaderLbl("POST_BLOOM"), loadShaderDesc("POST_BLOOM")) { - private final boolean originalValue = conf.bloom; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.bloom, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.bloom = !conf.bloom; - } - @Override - protected boolean getDirty() { - return conf.bloom != originalValue; - } - }); - } - if(conf.shaderPackInfo.LIGHT_SHAFTS) { - opts.add(new ShaderOption(loadShaderLbl("LIGHT_SHAFTS"), loadShaderDesc("LIGHT_SHAFTS")) { - private final boolean originalValue = conf.lightShafts; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.lightShafts, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.lightShafts = !conf.lightShafts; - } - @Override - protected boolean getDirty() { - return conf.lightShafts != originalValue; - } - }); - } - if(conf.shaderPackInfo.SCREEN_SPACE_REFLECTIONS) { - opts.add(new ShaderOption(loadShaderLbl("SCREEN_SPACE_REFLECTIONS"), loadShaderDesc("SCREEN_SPACE_REFLECTIONS")) { - private final boolean originalValue = conf.raytracing; - @Override - protected String getDisplayValue() { - return getColoredOnOff(conf.raytracing, EnumChatFormatting.GREEN, EnumChatFormatting.RED); - } - @Override - protected void toggleOption(GuiButton button, int dir) { - conf.raytracing = !conf.raytracing; - } - @Override - protected boolean getDirty() { - return conf.raytracing != originalValue; - } - }); - } - this.addAllOptions(opts); - setAllDisabled(!mcIn.gameSettings.shaders); - } - - public void setAllDisabled(boolean disable) { - for(int i = 0, l = list.size(); i < l; ++i) { - IGuiListEntry etr = list.get(i); - if(etr instanceof ListEntryButtonRow) { - ListEntryButtonRow etr2 = (ListEntryButtonRow)etr; - if(etr2.button1 != null) { - etr2.button1.enabled = !disable; - } - if(etr2.button2 != null) { - etr2.button2.enabled = !disable; - } - if(etr2.button3 != null) { - etr2.button3.enabled = !disable; - } - } - } - } - - @Override - public IGuiListEntry getListEntry(int var1) { - return list.get(var1); - } - - @Override - protected int getSize() { - return list.size(); - } - - @Override - public int getListWidth() { - return 225; - } - - private class ListEntryPackInfo implements IGuiListEntry { - - @Override - public void drawEntry(int entryID, int x, int y, int getListWidth, int var5, int var6, int var7, boolean var8) { - Minecraft mc = Minecraft.getMinecraft(); - ShaderPackInfo info = mc.gameSettings.deferredShaderConf.shaderPackInfo; - String packNameString = info.name; - int strWidth = mc.fontRendererObj.getStringWidth(packNameString) + 40; - if(strWidth < 210) { - strWidth = 210; - } - int x2 = strWidth > getListWidth * 2 ? x : x + (getListWidth - strWidth) / 2; - screen.drawString(mc.fontRendererObj, packNameString, x2 + 38, y + 3, 0xFFFFFF); - screen.drawString(mc.fontRendererObj, "Author: " + info.author, x2 + 38, y + 14, 0xBBBBBB); - screen.drawString(mc.fontRendererObj, "Version: " + info.vers, x2 + 38, y + 25, 0x888888); - List descLines = mc.fontRendererObj.listFormattedStringToWidth(info.desc, strWidth); - for(int i = 0, l = descLines.size(); i < l; ++i) { - screen.drawString(mc.fontRendererObj, descLines.get(i), x2, y + 43 + i * 9, 0xBBBBBB); - } - mc.getTextureManager().bindTexture(shaderPackIcon); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - Gui.drawModalRectWithCustomSizedTexture(x2, y + 2, 0, 0, 32, 32, 32, 32); - } - - @Override - public void setSelected(int var1, int var2, int var3) { - - } - - @Override - public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { - return false; - } - - @Override - public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { - - } - - } - - private class ListEntrySpacing implements IGuiListEntry { - - @Override - public void setSelected(int var1, int var2, int var3) { - - } - - @Override - public void drawEntry(int var1, int var2, int var3, int var4, int var5, int var6, int var7, boolean var8) { - - } - - @Override - public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { - return false; - } - - @Override - public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { - - } - - } - - private class ListEntryHeader implements IGuiListEntry { - - private final String text; - - private ListEntryHeader(String text) { - this.text = text; - } - - @Override - public void setSelected(int var1, int var2, int var3) { - - } - - @Override - public void drawEntry(int entryID, int x, int y, int getListWidth, int var5, int var6, int var7, boolean var8) { - screen.drawString(screen.getFontRenderer(), text, x, y + 10, 0xFFFFFF); - } - - @Override - public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { - return false; - } - - @Override - public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { - - } - - } - private class ListEntryButtonRow implements IGuiListEntry { private final ShaderOption opt1; @@ -501,48 +46,46 @@ public class GuiShaderConfigList extends GuiListExtended { this.opt1 = opt1; this.opt2 = opt2; this.opt3 = opt3; - if(this.opt1 != null) { + if (this.opt1 != null) { this.button1 = new GuiButton(0, 0, 0, 73, 20, this.opt1.label + ": " + this.opt1.getDisplayValue()); this.button1.fontScale = 0.78f - (this.opt1.label.length() * 0.01f); } - if(this.opt2 != null) { + if (this.opt2 != null) { this.button2 = new GuiButton(0, 0, 0, 73, 20, this.opt2.label + ": " + this.opt2.getDisplayValue()); this.button2.fontScale = 0.78f - (this.opt2.label.length() * 0.01f); } - if(this.opt3 != null) { + if (this.opt3 != null) { this.button3 = new GuiButton(0, 0, 0, 73, 20, this.opt3.label + ": " + this.opt3.getDisplayValue()); this.button3.fontScale = 0.78f - (this.opt3.label.length() * 0.01f); } } - @Override - public void setSelected(int var1, int var2, int var3) { - - } - @Override public void drawEntry(int entryID, int x, int y, int getListWidth, int var5, int var6, int var7, boolean var8) { - if(this.button1 != null) { + if (this.button1 != null) { this.button1.xPosition = x; this.button1.yPosition = y; this.button1.drawButton(mc, var6, var7); - if(this.button1.isMouseOver() && this.button1.yPosition + 10 < bottom && this.button1.yPosition + 10 > top) { + if (this.button1.isMouseOver() && this.button1.yPosition + 10 < bottom + && this.button1.yPosition + 10 > top) { renderTooltip(var6, var7 + 15, this.opt1.desc); } } - if(this.button2 != null) { + if (this.button2 != null) { this.button2.xPosition = x + 75; this.button2.yPosition = y; this.button2.drawButton(mc, var6, var7); - if(this.button2.isMouseOver() && this.button2.yPosition + 10 < bottom && this.button2.yPosition + 10 > top) { + if (this.button2.isMouseOver() && this.button2.yPosition + 10 < bottom + && this.button2.yPosition + 10 > top) { renderTooltip(var6, var7 + 15, this.opt2.desc); } } - if(this.button3 != null) { + if (this.button3 != null) { this.button3.xPosition = x + 150; this.button3.yPosition = y; this.button3.drawButton(mc, var6, var7); - if(this.button3.isMouseOver() && this.button3.yPosition + 10 < bottom && this.button3.yPosition + 10 > top) { + if (this.button3.isMouseOver() && this.button3.yPosition + 10 < bottom + && this.button3.yPosition + 10 > top) { renderTooltip(var6, var7 + 15, this.opt3.desc); } } @@ -550,30 +93,34 @@ public class GuiShaderConfigList extends GuiListExtended { @Override public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { - if(var4 != 0) return false; - if(this.button1 != null) { - if(this.button1.yPosition + 15 < bottom && this.button1.yPosition + 5 > top) { - if(this.button1.mousePressed(mc, var2, var3)) { + if (var4 != 0) + return false; + if (this.button1 != null) { + if (this.button1.yPosition + 15 < bottom && this.button1.yPosition + 5 > top) { + if (this.button1.mousePressed(mc, var2, var3)) { this.opt1.toggleOption(this.button1, var4 == 1 ? -1 : 1); - this.button1.displayString = (this.opt1.getDirty() ? "*" : "") + this.opt1.label + ": " + this.opt1.getDisplayValue(); + this.button1.displayString = (this.opt1.getDirty() ? "*" : "") + this.opt1.label + ": " + + this.opt1.getDisplayValue(); this.button1.playPressSound(mc.getSoundHandler()); } } } - if(this.button2 != null) { - if(this.button2.yPosition + 15 < bottom && this.button2.yPosition + 5 > top) { - if(this.button2.mousePressed(mc, var2, var3)) { + if (this.button2 != null) { + if (this.button2.yPosition + 15 < bottom && this.button2.yPosition + 5 > top) { + if (this.button2.mousePressed(mc, var2, var3)) { this.opt2.toggleOption(this.button2, var4 == 1 ? -1 : 1); - this.button2.displayString = (this.opt2.getDirty() ? "*" : "") + this.opt2.label + ": " + this.opt2.getDisplayValue(); + this.button2.displayString = (this.opt2.getDirty() ? "*" : "") + this.opt2.label + ": " + + this.opt2.getDisplayValue(); this.button2.playPressSound(mc.getSoundHandler()); } } } - if(this.button3 != null) { - if(this.button3.yPosition + 15 < bottom && this.button3.yPosition + 5 > top) { - if(this.button3.mousePressed(mc, var2, var3)) { + if (this.button3 != null) { + if (this.button3.yPosition + 15 < bottom && this.button3.yPosition + 5 > top) { + if (this.button3.mousePressed(mc, var2, var3)) { this.opt3.toggleOption(this.button3, var4 == 1 ? -1 : 1); - this.button3.displayString = (this.opt3.getDirty() ? "*" : "") + this.opt3.label + ": " + this.opt3.getDisplayValue(); + this.button3.displayString = (this.opt3.getDirty() ? "*" : "") + this.opt3.label + ": " + + this.opt3.getDisplayValue(); this.button3.playPressSound(mc.getSoundHandler()); } } @@ -583,17 +130,534 @@ public class GuiShaderConfigList extends GuiListExtended { @Override public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { - + } - + + @Override + public void setSelected(int var1, int var2, int var3) { + + } + } + private class ListEntryHeader implements IGuiListEntry { + + private final String text; + + private ListEntryHeader(String text) { + this.text = text; + } + + @Override + public void drawEntry(int entryID, int x, int y, int getListWidth, int var5, int var6, int var7, boolean var8) { + screen.drawString(screen.getFontRenderer(), text, x, y + 10, 0xFFFFFF); + } + + @Override + public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { + return false; + } + + @Override + public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { + + } + + @Override + public void setSelected(int var1, int var2, int var3) { + + } + + } + + private class ListEntryPackInfo implements IGuiListEntry { + + @Override + public void drawEntry(int entryID, int x, int y, int getListWidth, int var5, int var6, int var7, boolean var8) { + Minecraft mc = Minecraft.getMinecraft(); + ShaderPackInfo info = mc.gameSettings.deferredShaderConf.shaderPackInfo; + String packNameString = info.name; + int strWidth = mc.fontRendererObj.getStringWidth(packNameString) + 40; + if (strWidth < 210) { + strWidth = 210; + } + int x2 = strWidth > getListWidth * 2 ? x : x + (getListWidth - strWidth) / 2; + screen.drawString(mc.fontRendererObj, packNameString, x2 + 38, y + 3, 0xFFFFFF); + screen.drawString(mc.fontRendererObj, "Author: " + info.author, x2 + 38, y + 14, 0xBBBBBB); + screen.drawString(mc.fontRendererObj, "Version: " + info.vers, x2 + 38, y + 25, 0x888888); + List descLines = mc.fontRendererObj.listFormattedStringToWidth(info.desc, strWidth); + for (int i = 0, l = descLines.size(); i < l; ++i) { + screen.drawString(mc.fontRendererObj, descLines.get(i), x2, y + 43 + i * 9, 0xBBBBBB); + } + mc.getTextureManager().bindTexture(shaderPackIcon); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + Gui.drawModalRectWithCustomSizedTexture(x2, y + 2, 0, 0, 32, 32, 32, 32); + } + + @Override + public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { + return false; + } + + @Override + public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { + + } + + @Override + public void setSelected(int var1, int var2, int var3) { + + } + + } + + private class ListEntrySpacing implements IGuiListEntry { + + @Override + public void drawEntry(int var1, int var2, int var3, int var4, int var5, int var6, int var7, boolean var8) { + + } + + @Override + public boolean mousePressed(int var1, int var2, int var3, int var4, int var5, int var6) { + return false; + } + + @Override + public void mouseReleased(int var1, int var2, int var3, int var4, int var5, int var6) { + + } + + @Override + public void setSelected(int var1, int var2, int var3) { + + } + + } + + private static abstract class ShaderOption { + + private final String label; + private final List desc; + + private ShaderOption(String label, List desc) { + this.label = label; + this.desc = desc; + } + + protected abstract boolean getDirty(); + + protected abstract String getDisplayValue(); + + protected abstract void toggleOption(GuiButton button, int dir); + + } + + public static final ResourceLocation shaderPackIcon = new ResourceLocation( + "eagler:glsl/deferred/shader_pack_icon.png"); + + private static String getColoredOnOff(boolean state, EnumChatFormatting on, EnumChatFormatting off) { + return state ? "" + on + I18n.format("options.on") : "" + off + I18n.format("options.off"); + } + + private static List loadDescription(String key) { + List ret = new ArrayList<>(); + String msg; + int i = 0; + while (true) { + if ((msg = I18n.format(key + '.' + i)).equals(key + '.' + i)) { + if (!I18n.format(key + '.' + (i + 1)).equals(key + '.' + (i + 1))) { + msg = ""; + } else { + break; + } + } + ret.add(msg); + ++i; + } + if (ret.size() == 0) { + ret.add("" + EnumChatFormatting.GRAY + EnumChatFormatting.ITALIC + "(no description found)"); + } + return ret; + } + + private static List loadShaderDesc(String key) { + return loadDescription("shaders.gui.option." + key + ".desc"); + } + + private static String loadShaderLbl(String key) { + return I18n.format("shaders.gui.option." + key + ".label"); + } + + private final GuiShaderConfig screen; + + private final List list = new ArrayList<>(); + private List tooltipToShow = null; + private int tooltipToShowX = 0; + private int tooltipToShowY = 0; + public GuiShaderConfigList(GuiShaderConfig screen, Minecraft mcIn) { + super(mcIn, screen.width, screen.height, 32, screen.height - 40, 30); + this.screen = screen; + this.list.add(new ListEntryHeader("Current Shader Pack:")); + this.list.add(new ListEntryPackInfo()); + this.list.add(new ListEntrySpacing()); + this.list.add(new ListEntrySpacing()); + this.list.add(new ListEntryHeader(I18n.format("shaders.gui.headerTier1"))); + List opts = new ArrayList<>(); + EaglerDeferredConfig conf = mcIn.gameSettings.deferredShaderConf; + if (conf.shaderPackInfo.WAVING_BLOCKS) { + opts.add(new ShaderOption(loadShaderLbl("WAVING_BLOCKS"), loadShaderDesc("WAVING_BLOCKS")) { + private final boolean originalValue = conf.wavingBlocks; + + @Override + protected boolean getDirty() { + return conf.wavingBlocks != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.wavingBlocks, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.wavingBlocks = !conf.wavingBlocks; + } + }); + } + if (conf.shaderPackInfo.DYNAMIC_LIGHTS) { + opts.add(new ShaderOption(loadShaderLbl("DYNAMIC_LIGHTS"), loadShaderDesc("DYNAMIC_LIGHTS")) { + private final boolean originalValue = conf.dynamicLights; + + @Override + protected boolean getDirty() { + return conf.dynamicLights != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.dynamicLights, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.dynamicLights = !conf.dynamicLights; + } + }); + } + if (conf.shaderPackInfo.GLOBAL_AMBIENT_OCCLUSION) { + opts.add(new ShaderOption(loadShaderLbl("GLOBAL_AMBIENT_OCCLUSION"), + loadShaderDesc("GLOBAL_AMBIENT_OCCLUSION")) { + private final boolean originalValue = conf.ssao; + + @Override + protected boolean getDirty() { + return conf.ssao != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.ssao, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.ssao = !conf.ssao; + } + }); + } + if (conf.shaderPackInfo.SHADOWS_SUN) { + opts.add(new ShaderOption(loadShaderLbl("SHADOWS_SUN"), loadShaderDesc("SHADOWS_SUN")) { + private final int originalValue = conf.shadowsSun; + + @Override + protected boolean getDirty() { + return conf.shadowsSun != originalValue; + } + + @Override + protected String getDisplayValue() { + return conf.shadowsSun == 0 ? "" + EnumChatFormatting.RED + "0" + : "" + EnumChatFormatting.YELLOW + (1 << (conf.shadowsSun + 3)); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.shadowsSun = (conf.shadowsSun + dir + 5) % 5; + } + }); + } + if (conf.shaderPackInfo.REFLECTIONS_PARABOLOID) { + opts.add(new ShaderOption(loadShaderLbl("REFLECTIONS_PARABOLOID"), + loadShaderDesc("REFLECTIONS_PARABOLOID")) { + private final boolean originalValue = conf.useEnvMap; + + @Override + protected boolean getDirty() { + return conf.useEnvMap != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.useEnvMap, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.useEnvMap = !conf.useEnvMap; + } + }); + } + if (conf.shaderPackInfo.POST_LENS_DISTORION) { + opts.add(new ShaderOption(loadShaderLbl("POST_LENS_DISTORION"), loadShaderDesc("POST_LENS_DISTORION")) { + private final boolean originalValue = conf.lensDistortion; + + @Override + protected boolean getDirty() { + return conf.lensDistortion != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.lensDistortion, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.lensDistortion = !conf.lensDistortion; + } + }); + } + if (conf.shaderPackInfo.POST_LENS_FLARES) { + opts.add(new ShaderOption(loadShaderLbl("POST_LENS_FLARES"), loadShaderDesc("POST_LENS_FLARES")) { + private final boolean originalValue = conf.lensFlares; + + @Override + protected boolean getDirty() { + return conf.lensFlares != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.lensFlares, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.lensFlares = !conf.lensFlares; + } + }); + } + if (conf.shaderPackInfo.POST_FXAA) { + opts.add(new ShaderOption(loadShaderLbl("POST_FXAA"), loadShaderDesc("POST_FXAA")) { + private final boolean originalValue = conf.fxaa; + + @Override + protected boolean getDirty() { + return conf.fxaa != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.fxaa, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.fxaa = !conf.fxaa; + } + }); + } + this.addAllOptions(opts); + opts.clear(); + this.list.add(new ListEntryHeader(I18n.format("shaders.gui.headerTier2"))); + if (conf.shaderPackInfo.SHADOWS_COLORED) { + opts.add(new ShaderOption(loadShaderLbl("SHADOWS_COLORED"), loadShaderDesc("SHADOWS_COLORED")) { + private final boolean originalValue = conf.shadowsColored; + + @Override + protected boolean getDirty() { + return conf.shadowsColored != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.shadowsColored, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.shadowsColored = !conf.shadowsColored; + } + }); + } + if (conf.shaderPackInfo.SHADOWS_SMOOTHED) { + opts.add(new ShaderOption(loadShaderLbl("SHADOWS_SMOOTHED"), loadShaderDesc("SHADOWS_SMOOTHED")) { + private final boolean originalValue = conf.shadowsSmoothed; + + @Override + protected boolean getDirty() { + return conf.shadowsSmoothed != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.shadowsSmoothed, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.shadowsSmoothed = !conf.shadowsSmoothed; + } + }); + } + if (conf.shaderPackInfo.REALISTIC_WATER) { + opts.add(new ShaderOption(loadShaderLbl("REALISTIC_WATER"), loadShaderDesc("REALISTIC_WATER")) { + private final boolean originalValue = conf.realisticWater; + + @Override + protected boolean getDirty() { + return conf.realisticWater != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.realisticWater, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.realisticWater = !conf.realisticWater; + } + }); + } + if (conf.shaderPackInfo.POST_BLOOM) { + opts.add(new ShaderOption(loadShaderLbl("POST_BLOOM"), loadShaderDesc("POST_BLOOM")) { + private final boolean originalValue = conf.bloom; + + @Override + protected boolean getDirty() { + return conf.bloom != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.bloom, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.bloom = !conf.bloom; + } + }); + } + if (conf.shaderPackInfo.LIGHT_SHAFTS) { + opts.add(new ShaderOption(loadShaderLbl("LIGHT_SHAFTS"), loadShaderDesc("LIGHT_SHAFTS")) { + private final boolean originalValue = conf.lightShafts; + + @Override + protected boolean getDirty() { + return conf.lightShafts != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.lightShafts, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.lightShafts = !conf.lightShafts; + } + }); + } + if (conf.shaderPackInfo.SCREEN_SPACE_REFLECTIONS) { + opts.add(new ShaderOption(loadShaderLbl("SCREEN_SPACE_REFLECTIONS"), + loadShaderDesc("SCREEN_SPACE_REFLECTIONS")) { + private final boolean originalValue = conf.raytracing; + + @Override + protected boolean getDirty() { + return conf.raytracing != originalValue; + } + + @Override + protected String getDisplayValue() { + return getColoredOnOff(conf.raytracing, EnumChatFormatting.GREEN, EnumChatFormatting.RED); + } + + @Override + protected void toggleOption(GuiButton button, int dir) { + conf.raytracing = !conf.raytracing; + } + }); + } + this.addAllOptions(opts); + setAllDisabled(!mcIn.gameSettings.shaders); + } + + private void addAllOptions(List opts) { + for (int i = 0, l = opts.size(); i < l; ++i) { + ShaderOption opt1 = opts.get(i); + if (++i >= l) { + list.add(new ListEntryButtonRow(opt1, null, null)); + break; + } + ShaderOption opt2 = opts.get(i); + if (++i >= l) { + list.add(new ListEntryButtonRow(opt1, opt2, null)); + break; + } + list.add(new ListEntryButtonRow(opt1, opt2, opts.get(i))); + } + } + + @Override + public IGuiListEntry getListEntry(int var1) { + return list.get(var1); + } + + @Override + public int getListWidth() { + return 225; + } + + @Override + protected int getSize() { + return list.size(); + } + + public boolean isDirty() { + for (int i = 0, l = list.size(); i < l; ++i) { + IGuiListEntry etr = list.get(i); + if (etr instanceof ListEntryButtonRow) { + ListEntryButtonRow etr2 = (ListEntryButtonRow) etr; + if (etr2.opt1 != null) { + if (etr2.opt1.getDirty()) { + return true; + } + } + if (etr2.opt2 != null) { + if (etr2.opt2.getDirty()) { + return true; + } + } + if (etr2.opt3 != null) { + if (etr2.opt3.getDirty()) { + return true; + } + } + } + } + return false; + } + public void postRender(int mx, int my, float partialTicks) { - if(tooltipToShow != null) { + if (tooltipToShow != null) { screen.width *= 2; screen.height *= 2; GlStateManager.pushMatrix(); @@ -606,17 +670,13 @@ public class GuiShaderConfigList extends GuiListExtended { } } - private void renderTooltip(int x, int y, List msg) { - renderTooltip(x, y, 250, msg); - } - private void renderTooltip(int x, int y, int width, List msg) { List tooltipList = new ArrayList<>(msg.size() * 2); - for(int i = 0, l = msg.size(); i < l; ++i) { + for (int i = 0, l = msg.size(); i < l; ++i) { String s = msg.get(i); - if(s.length() > 0) { + if (s.length() > 0) { tooltipList.addAll(screen.getFontRenderer().listFormattedStringToWidth(s, width)); - }else { + } else { tooltipList.add(""); } } @@ -625,29 +685,8 @@ public class GuiShaderConfigList extends GuiListExtended { tooltipToShowY = y; } - public boolean isDirty() { - for(int i = 0, l = list.size(); i < l; ++i) { - IGuiListEntry etr = list.get(i); - if(etr instanceof ListEntryButtonRow) { - ListEntryButtonRow etr2 = (ListEntryButtonRow)etr; - if(etr2.opt1 != null) { - if(etr2.opt1.getDirty()) { - return true; - } - } - if(etr2.opt2 != null) { - if(etr2.opt2.getDirty()) { - return true; - } - } - if(etr2.opt3 != null) { - if(etr2.opt3.getDirty()) { - return true; - } - } - } - } - return false; + private void renderTooltip(int x, int y, List msg) { + renderTooltip(x, y, 250, msg); } public void resize() { @@ -657,4 +696,22 @@ public class GuiShaderConfigList extends GuiListExtended { bottom = screen.height - 40; } + public void setAllDisabled(boolean disable) { + for (int i = 0, l = list.size(); i < l; ++i) { + IGuiListEntry etr = list.get(i); + if (etr instanceof ListEntryButtonRow) { + ListEntryButtonRow etr2 = (ListEntryButtonRow) etr; + if (etr2.button1 != null) { + etr2.button1.enabled = !disable; + } + if (etr2.button2 != null) { + etr2.button2.enabled = !disable; + } + if (etr2.button3 != null) { + etr2.button3.enabled = !disable; + } + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShadersNotSupported.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShadersNotSupported.java index 321bb0a5..d4be1823 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShadersNotSupported.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/gui/GuiShadersNotSupported.java @@ -7,14 +7,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,22 +30,23 @@ public class GuiShadersNotSupported extends GuiScreen { this.reason = reason; } + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + mc.displayGuiScreen(parent); + } + } + + public void drawScreen(int i, int j, float var3) { + this.drawBackground(0); + drawCenteredString(fontRendererObj, I18n.format("shaders.gui.unsupported.title"), width / 2, height / 2 - 30, + 0xFFFFFF); + drawCenteredString(fontRendererObj, reason, width / 2, height / 2 - 10, 11184810); + super.drawScreen(i, j, var3); + } + public void initGui() { this.buttonList.clear(); this.buttonList.add(new GuiButton(0, width / 2 - 100, height / 2 + 10, I18n.format("gui.back"))); } - public void drawScreen(int i, int j, float var3) { - this.drawBackground(0); - drawCenteredString(fontRendererObj, I18n.format("shaders.gui.unsupported.title"), width / 2, height / 2 - 30, 0xFFFFFF); - drawCenteredString(fontRendererObj, reason, width / 2, height / 2 - 10, 11184810); - super.drawScreen(i, j, var3); - } - - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 0) { - mc.displayGuiScreen(parent); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/GBufferExtPipelineShader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/GBufferExtPipelineShader.java index 8fcea377..5e03f813 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/GBufferExtPipelineShader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/GBufferExtPipelineShader.java @@ -1,6 +1,9 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformBlockIndex; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformBlockBinding; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; @@ -8,29 +11,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GBufferExtPipelineShader extends ShaderProgram { - public final int coreState; - public final int extState; - - public GBufferExtPipelineShader(IProgramGL program, int coreState, int extState) { - super(program, new Uniforms()); - this.coreState = coreState; - this.extState = extState; - } - public static class Uniforms implements IProgramUniforms { public int materialConstantsSerial = -1; @@ -112,21 +107,31 @@ public class GBufferExtPipelineShader extends ShaderProgram { - public static PipelineShaderAccelParticleForward compile(boolean dynamicLights, int sunShadows) { - IShaderGL accelParticleVSH = ShaderCompiler.compileShader("accel_particle_forward", GL_VERTEX_SHADER, - ShaderSource.accel_particle_vsh, "COMPILE_FORWARD_VSH"); - IShaderGL accelParticleFSH = null; - try { - List lst = new ArrayList<>(2); - if(dynamicLights) { - lst.add("COMPILE_DYNAMIC_LIGHTS"); - } - if(sunShadows > 0) { - int lods = sunShadows - 1; - if(lods > 2) { - lods = 2; - } - lst.add("COMPILE_SUN_SHADOW_LOD" + lods); - } - accelParticleFSH = ShaderCompiler.compileShader("accel_particle_forward", GL_FRAGMENT_SHADER, - ShaderSource.accel_particle_forward_fsh, lst); - IProgramGL prog = ShaderCompiler.linkProgram("accel_particle_forward", accelParticleVSH, accelParticleFSH); - return new PipelineShaderAccelParticleForward(prog); - }finally { - if(accelParticleVSH != null) { - accelParticleVSH.free(); - } - if(accelParticleFSH != null) { - accelParticleFSH.free(); - } - } - } - - private PipelineShaderAccelParticleForward(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_modelViewMatrix4f = null; @@ -96,21 +67,55 @@ public class PipelineShaderAccelParticleForward extends ShaderProgram lst = new ArrayList<>(2); + if (dynamicLights) { + lst.add("COMPILE_DYNAMIC_LIGHTS"); + } + if (sunShadows > 0) { + int lods = sunShadows - 1; + if (lods > 2) { + lods = 2; + } + lst.add("COMPILE_SUN_SHADOW_LOD" + lods); + } + accelParticleFSH = ShaderCompiler.compileShader("accel_particle_forward", GL_FRAGMENT_SHADER, + ShaderSource.accel_particle_forward_fsh, lst); + IProgramGL prog = ShaderCompiler.linkProgram("accel_particle_forward", accelParticleVSH, accelParticleFSH); + return new PipelineShaderAccelParticleForward(prog); + } finally { + if (accelParticleVSH != null) { + accelParticleVSH.free(); + } + if (accelParticleFSH != null) { + accelParticleFSH.free(); + } + } + } + + private PipelineShaderAccelParticleForward(IProgramGL prog) { + super(prog, new Uniforms()); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderAccelParticleGBuffer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderAccelParticleGBuffer.java index 4618018a..2dc92c0e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderAccelParticleGBuffer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderAccelParticleGBuffer.java @@ -1,7 +1,9 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -10,43 +12,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderAccelParticleGBuffer extends ShaderProgram { - public static PipelineShaderAccelParticleGBuffer compile() { - IShaderGL accelParticleVSH = ShaderCompiler.compileShader("accel_particle_gbuffer", GL_VERTEX_SHADER, - ShaderSource.accel_particle_vsh, "COMPILE_GBUFFER_VSH"); - IShaderGL accelParticleFSH = null; - try { - accelParticleFSH = ShaderCompiler.compileShader("accel_particle_gbuffer", GL_FRAGMENT_SHADER, - ShaderSource.accel_particle_gbuffer_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("accel_particle_gbuffer", accelParticleVSH, accelParticleFSH); - return new PipelineShaderAccelParticleGBuffer(prog); - }finally { - if(accelParticleVSH != null) { - accelParticleVSH.free(); - } - if(accelParticleFSH != null) { - accelParticleFSH.free(); - } - } - } - - private PipelineShaderAccelParticleGBuffer(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_matrixTransform = null; @@ -75,4 +55,27 @@ public class PipelineShaderAccelParticleGBuffer extends ShaderProgram { - public static PipelineShaderBloomBlurPass compile() { - IShaderGL bloomBlurPass = ShaderCompiler.compileShader("post_bloom_blur", GL_FRAGMENT_SHADER, - ShaderSource.post_bloom_blur_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_bloom_blur", SharedPipelineShaders.deferred_local, bloomBlurPass); - return new PipelineShaderBloomBlurPass(prog); - }finally { - if(bloomBlurPass != null) { - bloomBlurPass.free(); - } - } - } - - private PipelineShaderBloomBlurPass(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_sampleOffset2f = null; @@ -58,4 +43,22 @@ public class PipelineShaderBloomBlurPass extends ShaderProgram { - public static PipelineShaderBloomBrightPass compile() throws ShaderException { - IShaderGL bloomBrightPass = ShaderCompiler.compileShader("post_bloom_bright", GL_FRAGMENT_SHADER, - ShaderSource.post_bloom_bright_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_bloom_bright", SharedPipelineShaders.deferred_local, bloomBrightPass); - return new PipelineShaderBloomBrightPass(prog); - }finally { - if(bloomBrightPass != null) { - bloomBrightPass.free(); - } - } - } - - private PipelineShaderBloomBrightPass(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_outputSize4f = null; @@ -59,4 +44,22 @@ public class PipelineShaderBloomBrightPass extends ShaderProgram { - public static PipelineShaderCloudsNoise3D compile() { - IShaderGL cloudsNoise3d = ShaderCompiler.compileShader("clouds_noise3d", GL_FRAGMENT_SHADER, - ShaderSource.clouds_noise3d_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("clouds_noise3d", SharedPipelineShaders.deferred_local, cloudsNoise3d); - return new PipelineShaderCloudsNoise3D(prog); - }finally { - if(cloudsNoise3d != null) { - cloudsNoise3d.free(); - } - } - } - - private PipelineShaderCloudsNoise3D(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_textureSlice1f = null; @@ -62,4 +47,22 @@ public class PipelineShaderCloudsNoise3D extends ShaderProgram { - public static PipelineShaderCloudsSample compile() { - IShaderGL cloudsSample = ShaderCompiler.compileShader("clouds_sample", GL_FRAGMENT_SHADER, - ShaderSource.clouds_sample_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("clouds_sample", SharedPipelineShaders.deferred_local, cloudsSample); - return new PipelineShaderCloudsSample(prog); - }finally { - if(cloudsSample != null) { - cloudsSample.free(); - } - } - } - - private PipelineShaderCloudsSample(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_rainStrength1f = null; @@ -69,4 +54,22 @@ public class PipelineShaderCloudsSample extends ShaderProgram { - public static PipelineShaderCloudsShapes compile() { - IShaderGL cloudsShapesVSH = ShaderCompiler.compileShader("clouds_shapes", GL_VERTEX_SHADER, - ShaderSource.clouds_shapes_vsh); - IShaderGL cloudsShapesFSH = null; - try { - cloudsShapesFSH = ShaderCompiler.compileShader("clouds_shapes", GL_FRAGMENT_SHADER, - ShaderSource.clouds_shapes_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("clouds_shapes", cloudsShapesVSH, cloudsShapesFSH); - return new PipelineShaderCloudsShapes(prog); - }finally { - if(cloudsShapesVSH != null) { - cloudsShapesVSH.free(); - } - if(cloudsShapesFSH != null) { - cloudsShapesFSH.free(); - } - } - } - - private PipelineShaderCloudsShapes(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_textureLevel1f = null; @@ -68,4 +48,27 @@ public class PipelineShaderCloudsShapes extends ShaderProgram { - public static PipelineShaderCloudsSunOcclusion compile() { - IShaderGL cloudsOcclusion = ShaderCompiler.compileShader("clouds_sun_occlusion", GL_FRAGMENT_SHADER, - ShaderSource.clouds_sun_occlusion_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("clouds_sun_occlusion", SharedPipelineShaders.deferred_local, cloudsOcclusion); - return new PipelineShaderCloudsSunOcclusion(prog); - }finally { - if(cloudsOcclusion != null) { - cloudsOcclusion.free(); - } - } - } - private PipelineShaderCloudsSunOcclusion(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_sampleMatrix4x3f = null; @@ -55,4 +41,22 @@ public class PipelineShaderCloudsSunOcclusion extends ShaderProgram { - public static PipelineShaderFXAA compile() throws ShaderException { - IShaderGL postFXAA = ShaderCompiler.compileShader("post_fxaa", GL_FRAGMENT_SHADER, - ShaderSource.post_fxaa_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_fxaa", SharedPipelineShaders.deferred_local, postFXAA); - return new PipelineShaderFXAA(prog); - }finally { - if(postFXAA != null) { - postFXAA.free(); - } - } - } - - private PipelineShaderFXAA(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_screenSize2f; @@ -56,4 +41,20 @@ public class PipelineShaderFXAA extends ShaderProgram { - public static PipelineShaderGBufferCombine compile(boolean ssao, boolean env, boolean ssr) throws ShaderException { - IShaderGL coreGBuffer = null; - List compileFlags = new ArrayList<>(2); - if(ssao) { - compileFlags.add("COMPILE_GLOBAL_AMBIENT_OCCLUSION"); - } - if(env) { - compileFlags.add("COMPILE_ENV_MAP_REFLECTIONS"); - } - if(ssr) { - compileFlags.add("COMPILE_SCREEN_SPACE_REFLECTIONS"); - } - coreGBuffer = ShaderCompiler.compileShader("deferred_combine", GL_FRAGMENT_SHADER, - ShaderSource.deferred_combine_fsh, compileFlags); - try { - IProgramGL prog = ShaderCompiler.linkProgram("deferred_combine", SharedPipelineShaders.deferred_local, coreGBuffer); - return new PipelineShaderGBufferCombine(prog, ssao, env, ssr); - }finally { - if(coreGBuffer != null) { - coreGBuffer.free(); - } - } - } - - private PipelineShaderGBufferCombine(IProgramGL program, boolean ssao, boolean env, boolean ssr) { - super(program, new Uniforms(ssao, env, ssr)); - } - public static class Uniforms implements IProgramUniforms { public final boolean ssao; @@ -95,4 +68,33 @@ public class PipelineShaderGBufferCombine extends ShaderProgram compileFlags = new ArrayList<>(2); + if (ssao) { + compileFlags.add("COMPILE_GLOBAL_AMBIENT_OCCLUSION"); + } + if (env) { + compileFlags.add("COMPILE_ENV_MAP_REFLECTIONS"); + } + if (ssr) { + compileFlags.add("COMPILE_SCREEN_SPACE_REFLECTIONS"); + } + coreGBuffer = ShaderCompiler.compileShader("deferred_combine", GL_FRAGMENT_SHADER, + ShaderSource.deferred_combine_fsh, compileFlags); + try { + IProgramGL prog = ShaderCompiler.linkProgram("deferred_combine", SharedPipelineShaders.deferred_local, + coreGBuffer); + return new PipelineShaderGBufferCombine(prog, ssao, env, ssr); + } finally { + if (coreGBuffer != null) { + coreGBuffer.free(); + } + } + } + + private PipelineShaderGBufferCombine(IProgramGL program, boolean ssao, boolean env, boolean ssr) { + super(program, new Uniforms(ssao, env, ssr)); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderGBufferDebugView.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderGBufferDebugView.java index 7037ccff..7db5c04b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderGBufferDebugView.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderGBufferDebugView.java @@ -1,46 +1,31 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; + import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderGBufferDebugView extends ShaderProgram { - public static PipelineShaderGBufferDebugView compile(int view) throws ShaderException { - IShaderGL debugView = ShaderCompiler.compileShader("gbuffer_debug_view", GL_FRAGMENT_SHADER, - ShaderSource.gbuffer_debug_view_fsh, ("DEBUG_VIEW_" + view)); - try { - IProgramGL prog = ShaderCompiler.linkProgram("gbuffer_debug_view", SharedPipelineShaders.deferred_local, debugView); - return new PipelineShaderGBufferDebugView(prog, view); - }finally { - if(debugView != null) { - debugView.free(); - } - } - } - - private PipelineShaderGBufferDebugView(IProgramGL prog, int mode) { - super(prog, new Uniforms(mode)); - } - public static class Uniforms implements IProgramUniforms { public final int mode; @@ -63,4 +48,22 @@ public class PipelineShaderGBufferDebugView extends ShaderProgram { - public static PipelineShaderGBufferFog compile(boolean linear, boolean atmosphere, boolean lightShafts) { - List macros = new ArrayList<>(3); - if(linear) { - macros.add("COMPILE_FOG_LINEAR"); - } - if(atmosphere) { - macros.add("COMPILE_FOG_ATMOSPHERE"); - } - if(lightShafts) { - macros.add("COMPILE_FOG_LIGHT_SHAFTS"); - } - IShaderGL deferredFog = ShaderCompiler.compileShader("deferred_fog", GL_FRAGMENT_SHADER, - ShaderSource.deferred_fog_fsh, macros); - try { - IProgramGL prog = ShaderCompiler.linkProgram("deferred_fog", SharedPipelineShaders.deferred_local, deferredFog); - return new PipelineShaderGBufferFog(prog); - }finally { - if(deferredFog != null) { - deferredFog.free(); - } - } - } - - private PipelineShaderGBufferFog(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_inverseViewProjMatrix4f = null; @@ -83,4 +58,32 @@ public class PipelineShaderGBufferFog extends ShaderProgram macros = new ArrayList<>(3); + if (linear) { + macros.add("COMPILE_FOG_LINEAR"); + } + if (atmosphere) { + macros.add("COMPILE_FOG_ATMOSPHERE"); + } + if (lightShafts) { + macros.add("COMPILE_FOG_LIGHT_SHAFTS"); + } + IShaderGL deferredFog = ShaderCompiler.compileShader("deferred_fog", GL_FRAGMENT_SHADER, + ShaderSource.deferred_fog_fsh, macros); + try { + IProgramGL prog = ShaderCompiler.linkProgram("deferred_fog", SharedPipelineShaders.deferred_local, + deferredFog); + return new PipelineShaderGBufferFog(prog); + } finally { + if (deferredFog != null) { + deferredFog.free(); + } + } + } + + private PipelineShaderGBufferFog(IProgramGL prog) { + super(prog, new Uniforms()); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderHandDepthMask.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderHandDepthMask.java index a7d6e22a..08854821 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderHandDepthMask.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderHandDepthMask.java @@ -1,7 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -9,37 +10,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderHandDepthMask extends ShaderProgram { - public static PipelineShaderHandDepthMask compile() { - IShaderGL handDepthMask = ShaderCompiler.compileShader("hand_depth_mask", GL_FRAGMENT_SHADER, - ShaderSource.hand_depth_mask_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("hand_depth_mask", SharedPipelineShaders.deferred_local, handDepthMask); - return new PipelineShaderHandDepthMask(prog); - }finally { - if(handDepthMask != null) { - handDepthMask.free(); - } - } - } - - private PipelineShaderHandDepthMask(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { private Uniforms() { @@ -52,4 +37,22 @@ public class PipelineShaderHandDepthMask extends ShaderProgram { - public static PipelineShaderLensDistortion compile() throws ShaderException { - IShaderGL lensDistort = ShaderCompiler.compileShader("post_lens_distort", GL_FRAGMENT_SHADER, - ShaderSource.post_lens_distort_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_lens_distort", SharedPipelineShaders.deferred_local, lensDistort); - return new PipelineShaderLensDistortion(prog); - }finally { - if(lensDistort != null) { - lensDistort.free(); - } - } - } - - private PipelineShaderLensDistortion(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { private Uniforms() { @@ -52,4 +37,22 @@ public class PipelineShaderLensDistortion extends ShaderProgram { - public static PipelineShaderLensFlares compileStreaks() { - IShaderGL vertexShader = ShaderCompiler.compileShader("post_lens_streaks", GL_VERTEX_SHADER, - ShaderSource.post_lens_streaks_vsh); - IShaderGL fragmentShader = null; - try { - fragmentShader = ShaderCompiler.compileShader("post_lens_streaks", GL_FRAGMENT_SHADER, - ShaderSource.post_lens_streaks_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("post_lens_streaks", vertexShader, fragmentShader); - return new PipelineShaderLensFlares(prog); - }finally { - if(vertexShader != null) { - vertexShader.free(); - } - if(fragmentShader != null) { - fragmentShader.free(); - } - } - } - - public static PipelineShaderLensFlares compileGhosts() { - IShaderGL vertexShader = ShaderCompiler.compileShader("post_lens_ghosts", GL_VERTEX_SHADER, - ShaderSource.post_lens_ghosts_vsh); - IShaderGL fragmentShader = null; - try { - fragmentShader = ShaderCompiler.compileShader("post_lens_ghosts", GL_FRAGMENT_SHADER, - ShaderSource.post_lens_ghosts_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("post_lens_ghosts", vertexShader, fragmentShader); - return new PipelineShaderLensFlares(prog); - }finally { - if(vertexShader != null) { - vertexShader.free(); - } - if(fragmentShader != null) { - fragmentShader.free(); - } - } - } - - private PipelineShaderLensFlares(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_sunFlareMatrix3f = null; @@ -88,4 +49,46 @@ public class PipelineShaderLensFlares extends ShaderProgram { - public static PipelineShaderLensSunOcclusion compile() throws ShaderException { - IShaderGL sunOcclusion = ShaderCompiler.compileShader("lens_sun_occlusion", GL_FRAGMENT_SHADER, - ShaderSource.lens_sun_occlusion_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("lens_sun_occlusion", SharedPipelineShaders.deferred_local, sunOcclusion); - return new PipelineShaderLensSunOcclusion(prog); - }finally { - if(sunOcclusion != null) { - sunOcclusion.free(); - } - } - } - - private PipelineShaderLensSunOcclusion(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_sampleMatrix3f = null; @@ -54,4 +39,22 @@ public class PipelineShaderLensSunOcclusion extends ShaderProgram { - public static PipelineShaderLightShaftsSample compile(int shadowsSun) { - if(shadowsSun == 0) { - throw new IllegalStateException("Enable shadows to compile this shader"); - } - int lods = shadowsSun - 1; - if(lods > 2) { - lods = 2; - } - IShaderGL lightShaftsSample = ShaderCompiler.compileShader("light_shafts_sample", GL_FRAGMENT_SHADER, - ShaderSource.light_shafts_sample_fsh, Arrays.asList("COMPILE_SUN_SHADOW_LOD" + lods)); - try { - IProgramGL prog = ShaderCompiler.linkProgram("light_shafts_sample", SharedPipelineShaders.deferred_local, lightShaftsSample); - return new PipelineShaderLightShaftsSample(prog); - }finally { - if(lightShaftsSample != null) { - lightShaftsSample.free(); - } - } - } - - private PipelineShaderLightShaftsSample(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_inverseViewProjMatrix4f = null; @@ -79,4 +57,29 @@ public class PipelineShaderLightShaftsSample extends ShaderProgram 2) { + lods = 2; + } + IShaderGL lightShaftsSample = ShaderCompiler.compileShader("light_shafts_sample", GL_FRAGMENT_SHADER, + ShaderSource.light_shafts_sample_fsh, Arrays.asList("COMPILE_SUN_SHADOW_LOD" + lods)); + try { + IProgramGL prog = ShaderCompiler.linkProgram("light_shafts_sample", SharedPipelineShaders.deferred_local, + lightShaftsSample); + return new PipelineShaderLightShaftsSample(prog); + } finally { + if (lightShaftsSample != null) { + lightShaftsSample.free(); + } + } + } + + private PipelineShaderLightShaftsSample(IProgramGL prog) { + super(prog, new Uniforms()); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingPoint.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingPoint.java index 8fc6aa10..1e0cf70c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingPoint.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingPoint.java @@ -1,7 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; import java.util.ArrayList; import java.util.List; @@ -13,42 +14,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderLightingPoint extends ShaderProgram { - public static PipelineShaderLightingPoint compile(boolean shadows) - throws ShaderException { - List compileFlags = new ArrayList<>(2); - if(shadows) { - compileFlags.add("COMPILE_PARABOLOID_SHADOW"); - } - IShaderGL lightingPoint = ShaderCompiler.compileShader("lighting_point", GL_FRAGMENT_SHADER, - ShaderSource.lighting_point_fsh, compileFlags); - try { - IProgramGL prog = ShaderCompiler.linkProgram("lighting_point", SharedPipelineShaders.lighting_mesh, lightingPoint); - return new PipelineShaderLightingPoint(prog, shadows); - }finally { - if(lightingPoint != null) { - lightingPoint.free(); - } - } - } - - private PipelineShaderLightingPoint(IProgramGL program, boolean shadows) { - super(program, new Uniforms(shadows)); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_viewportSize2f = null; @@ -81,4 +61,26 @@ public class PipelineShaderLightingPoint extends ShaderProgram compileFlags = new ArrayList<>(2); + if (shadows) { + compileFlags.add("COMPILE_PARABOLOID_SHADOW"); + } + IShaderGL lightingPoint = ShaderCompiler.compileShader("lighting_point", GL_FRAGMENT_SHADER, + ShaderSource.lighting_point_fsh, compileFlags); + try { + IProgramGL prog = ShaderCompiler.linkProgram("lighting_point", SharedPipelineShaders.lighting_mesh, + lightingPoint); + return new PipelineShaderLightingPoint(prog, shadows); + } finally { + if (lightingPoint != null) { + lightingPoint.free(); + } + } + } + + private PipelineShaderLightingPoint(IProgramGL program, boolean shadows) { + super(program, new Uniforms(shadows)); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingSun.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingSun.java index 9e725375..c4fb9887 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingSun.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderLightingSun.java @@ -1,7 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; import java.util.ArrayList; import java.util.List; @@ -13,45 +14,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderLightingSun extends ShaderProgram { - public static PipelineShaderLightingSun compile(int shadowsSun, boolean coloredShadows) throws ShaderException { - IShaderGL sunShader = null; - List compileFlags = new ArrayList<>(1); - if(shadowsSun > 0) { - compileFlags.add("COMPILE_SUN_SHADOW"); - } - if(coloredShadows) { - compileFlags.add("COMPILE_COLORED_SHADOW"); - } - sunShader = ShaderCompiler.compileShader("lighting_sun", GL_FRAGMENT_SHADER, - ShaderSource.lighting_sun_fsh, compileFlags); - try { - IProgramGL prog = ShaderCompiler.linkProgram("lighting_sun", SharedPipelineShaders.deferred_local, sunShader); - return new PipelineShaderLightingSun(prog, shadowsSun); - }finally { - if(sunShader != null) { - sunShader.free(); - } - } - } - - private PipelineShaderLightingSun(IProgramGL program, int shadowsSun) { - super(program, new Uniforms(shadowsSun)); - } - public static class Uniforms implements IProgramUniforms { public final int shadowsSun; @@ -80,4 +57,30 @@ public class PipelineShaderLightingSun extends ShaderProgram compileFlags = new ArrayList<>(1); + if (shadowsSun > 0) { + compileFlags.add("COMPILE_SUN_SHADOW"); + } + if (coloredShadows) { + compileFlags.add("COMPILE_COLORED_SHADOW"); + } + sunShader = ShaderCompiler.compileShader("lighting_sun", GL_FRAGMENT_SHADER, ShaderSource.lighting_sun_fsh, + compileFlags); + try { + IProgramGL prog = ShaderCompiler.linkProgram("lighting_sun", SharedPipelineShaders.deferred_local, + sunShader); + return new PipelineShaderLightingSun(prog, shadowsSun); + } finally { + if (sunShader != null) { + sunShader.free(); + } + } + } + + private PipelineShaderLightingSun(IProgramGL program, int shadowsSun) { + super(program, new Uniforms(shadowsSun)); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderMoonRender.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderMoonRender.java index f870f7fc..19e31e4e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderMoonRender.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderMoonRender.java @@ -1,52 +1,32 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; + import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderMoonRender extends ShaderProgram { - public static PipelineShaderMoonRender compile() { - IShaderGL moonRenderVSH = ShaderCompiler.compileShader("moon_render", GL_VERTEX_SHADER, - ShaderSource.moon_render_vsh); - IShaderGL moonRenderFSH = null; - try { - moonRenderFSH = ShaderCompiler.compileShader("moon_render", GL_FRAGMENT_SHADER, - ShaderSource.moon_render_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("moon_render", moonRenderVSH, moonRenderFSH); - return new PipelineShaderMoonRender(prog); - }finally { - if(moonRenderVSH != null) { - moonRenderVSH.free(); - } - if(moonRenderFSH != null) { - moonRenderFSH.free(); - } - } - } - - private PipelineShaderMoonRender(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_modelMatrix4f = null; @@ -71,4 +51,27 @@ public class PipelineShaderMoonRender extends ShaderProgram { - public static PipelineShaderPostExposureAvg compile(boolean luma) throws ShaderException { - List compileFlags = new ArrayList<>(1); - if(luma) { - compileFlags.add("CALCULATE_LUMINANCE"); - } - IShaderGL postExposureAvg = ShaderCompiler.compileShader("post_exposure_avg", GL_FRAGMENT_SHADER, - ShaderSource.post_exposure_avg_fsh, compileFlags); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_exposure_avg", SharedPipelineShaders.deferred_local, postExposureAvg); - return new PipelineShaderPostExposureAvg(prog); - }finally { - if(postExposureAvg != null) { - postExposureAvg.free(); - } - } - } - - private PipelineShaderPostExposureAvg(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_sampleOffset4f = null; @@ -60,7 +41,29 @@ public class PipelineShaderPostExposureAvg extends ShaderProgram compileFlags = new ArrayList<>(1); + if (luma) { + compileFlags.add("CALCULATE_LUMINANCE"); + } + IShaderGL postExposureAvg = ShaderCompiler.compileShader("post_exposure_avg", GL_FRAGMENT_SHADER, + ShaderSource.post_exposure_avg_fsh, compileFlags); + try { + IProgramGL prog = ShaderCompiler.linkProgram("post_exposure_avg", SharedPipelineShaders.deferred_local, + postExposureAvg); + return new PipelineShaderPostExposureAvg(prog); + } finally { + if (postExposureAvg != null) { + postExposureAvg.free(); + } + } + } + + private PipelineShaderPostExposureAvg(IProgramGL prog) { + super(prog, new Uniforms()); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderPostExposureFinal.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderPostExposureFinal.java index 494afe85..fddbd253 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderPostExposureFinal.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderPostExposureFinal.java @@ -1,7 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -10,37 +11,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderPostExposureFinal extends ShaderProgram { - public static PipelineShaderPostExposureFinal compile() throws ShaderException { - IShaderGL postExposureFinal = ShaderCompiler.compileShader("post_exposure_final", GL_FRAGMENT_SHADER, - ShaderSource.post_exposure_final_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_exposure_final", SharedPipelineShaders.deferred_local, postExposureFinal); - return new PipelineShaderPostExposureFinal(prog); - }finally { - if(postExposureFinal != null) { - postExposureFinal.free(); - } - } - } - - private PipelineShaderPostExposureFinal(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_inputSize2f = null; @@ -58,4 +43,22 @@ public class PipelineShaderPostExposureFinal extends ShaderProgram { - public static PipelineShaderRealisticWaterControl compile() throws ShaderException { - IShaderGL realisticWaterControl = ShaderCompiler.compileShader("realistic_water_control", GL_FRAGMENT_SHADER, - ShaderSource.realistic_water_control_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("realistic_water_control", SharedPipelineShaders.deferred_local, realisticWaterControl); - return new PipelineShaderRealisticWaterControl(prog); - }finally { - if(realisticWaterControl != null) { - realisticWaterControl.free(); - } - } - } - - public PipelineShaderRealisticWaterControl(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_inverseProjectionMatrix4f = null; @@ -81,4 +66,22 @@ public class PipelineShaderRealisticWaterControl extends ShaderProgram { - public static PipelineShaderRealisticWaterNoise compile() throws ShaderException { - IShaderGL realisticWaterNoise = ShaderCompiler.compileShader("realistic_water_noise", GL_FRAGMENT_SHADER, - ShaderSource.realistic_water_noise_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("realistic_water_noise", SharedPipelineShaders.deferred_local, realisticWaterNoise); - return new PipelineShaderRealisticWaterNoise(prog); - }finally { - if(realisticWaterNoise != null) { - realisticWaterNoise.free(); - } - } - } - - private PipelineShaderRealisticWaterNoise(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_waveTimer4f = null; @@ -53,4 +38,22 @@ public class PipelineShaderRealisticWaterNoise extends ShaderProgram { - - public static PipelineShaderRealisticWaterNormalMap compile() throws ShaderException { - IShaderGL realisticWaterNormals = ShaderCompiler.compileShader("realistic_water_normals", GL_FRAGMENT_SHADER, - ShaderSource.realistic_water_normals_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("realistic_water_normals", SharedPipelineShaders.deferred_local, realisticWaterNormals); - return new PipelineShaderRealisticWaterNormalMap(prog); - }finally { - if(realisticWaterNormals != null) { - realisticWaterNormals.free(); - } - } - } - - private PipelineShaderRealisticWaterNormalMap(IProgramGL prog) { - super(prog, new Uniforms()); - } +public class PipelineShaderRealisticWaterNormalMap + extends ShaderProgram { public static class Uniforms implements IProgramUniforms { @@ -53,4 +39,22 @@ public class PipelineShaderRealisticWaterNormalMap extends ShaderProgram { - public static PipelineShaderReprojControl compile(boolean ssao, boolean ssr) throws ShaderException { - List compileFlags = new ArrayList<>(2); - if(ssao) { - compileFlags.add("COMPILE_REPROJECT_SSAO"); - } - if(ssr) { - compileFlags.add("COMPILE_REPROJECT_SSR"); - } - IShaderGL reprojControl = ShaderCompiler.compileShader("reproj_control", GL_FRAGMENT_SHADER, - ShaderSource.reproject_control_fsh, compileFlags); - try { - IProgramGL prog = ShaderCompiler.linkProgram("reproj_control", SharedPipelineShaders.deferred_local, reprojControl); - return new PipelineShaderReprojControl(prog, ssao, ssr); - }finally { - if(reprojControl != null) { - reprojControl.free(); - } - } - } - - private PipelineShaderReprojControl(IProgramGL prog, boolean ssao, boolean ssr) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_inverseViewProjMatrix4f = null; @@ -87,4 +65,29 @@ public class PipelineShaderReprojControl extends ShaderProgram compileFlags = new ArrayList<>(2); + if (ssao) { + compileFlags.add("COMPILE_REPROJECT_SSAO"); + } + if (ssr) { + compileFlags.add("COMPILE_REPROJECT_SSR"); + } + IShaderGL reprojControl = ShaderCompiler.compileShader("reproj_control", GL_FRAGMENT_SHADER, + ShaderSource.reproject_control_fsh, compileFlags); + try { + IProgramGL prog = ShaderCompiler.linkProgram("reproj_control", SharedPipelineShaders.deferred_local, + reprojControl); + return new PipelineShaderReprojControl(prog, ssao, ssr); + } finally { + if (reprojControl != null) { + reprojControl.free(); + } + } + } + + private PipelineShaderReprojControl(IProgramGL prog, boolean ssao, boolean ssr) { + super(prog, new Uniforms()); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderReprojSSR.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderReprojSSR.java index 69fea206..b51dd2b8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderReprojSSR.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderReprojSSR.java @@ -1,7 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -10,37 +11,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderReprojSSR extends ShaderProgram { - public static PipelineShaderReprojSSR compile() throws ShaderException { - IShaderGL reprojSSR = ShaderCompiler.compileShader("reproj_ssr", GL_FRAGMENT_SHADER, - ShaderSource.reproject_ssr_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("reproj_ssr", SharedPipelineShaders.deferred_local, reprojSSR); - return new PipelineShaderReprojSSR(prog); - }finally { - if(reprojSSR != null) { - reprojSSR.free(); - } - } - } - - private PipelineShaderReprojSSR(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_lastProjectionMatrix4f; @@ -66,4 +51,21 @@ public class PipelineShaderReprojSSR extends ShaderProgram { - public static PipelineShaderSSAOGenerate compile() throws ShaderException { - IShaderGL ssaoGenerate = ShaderCompiler.compileShader("ssao_generate", GL_FRAGMENT_SHADER, - ShaderSource.ssao_generate_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("ssao_generate", SharedPipelineShaders.deferred_local, ssaoGenerate); - return new PipelineShaderSSAOGenerate(prog); - }finally { - if(ssaoGenerate != null) { - ssaoGenerate.free(); - } - } - } - - private PipelineShaderSSAOGenerate(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_projectionMatrix4f; @@ -59,4 +44,22 @@ public class PipelineShaderSSAOGenerate extends ShaderProgram { - public static PipelineShaderShadowsSun compile(int shadowsSun, boolean shadowsSunSmooth, boolean coloredShadows) - throws ShaderException { - IShaderGL shadowShader = null; - List compileFlags = new ArrayList<>(2); - if(shadowsSun == 0) { - throw new IllegalStateException("Enable shadows to compile this shader"); - } - int lods = shadowsSun - 1; - if(lods > 2) { - lods = 2; - } - compileFlags.add("COMPILE_SUN_SHADOW_LOD" + lods); - if(shadowsSunSmooth) { - compileFlags.add("COMPILE_SUN_SHADOW_SMOOTH"); - } - if(coloredShadows) { - compileFlags.add("COMPILE_COLORED_SHADOW"); - } - shadowShader = ShaderCompiler.compileShader("shadows_sun", GL_FRAGMENT_SHADER, - ShaderSource.shadows_sun_fsh, compileFlags); - try { - IProgramGL prog = ShaderCompiler.linkProgram("shadows_sun", SharedPipelineShaders.deferred_local, shadowShader); - return new PipelineShaderShadowsSun(prog, shadowsSun, shadowsSunSmooth); - }finally { - if(shadowShader != null) { - shadowShader.free(); - } - } - } - - private PipelineShaderShadowsSun(IProgramGL program, int shadowsSun, boolean shadowsSunSmooth) { - super(program, new Uniforms(shadowsSun, shadowsSunSmooth)); - } - public static class Uniforms implements IProgramUniforms { public final int shadowsSun; @@ -93,5 +61,39 @@ public class PipelineShaderShadowsSun extends ShaderProgram compileFlags = new ArrayList<>(2); + if (shadowsSun == 0) { + throw new IllegalStateException("Enable shadows to compile this shader"); + } + int lods = shadowsSun - 1; + if (lods > 2) { + lods = 2; + } + compileFlags.add("COMPILE_SUN_SHADOW_LOD" + lods); + if (shadowsSunSmooth) { + compileFlags.add("COMPILE_SUN_SHADOW_SMOOTH"); + } + if (coloredShadows) { + compileFlags.add("COMPILE_COLORED_SHADOW"); + } + shadowShader = ShaderCompiler.compileShader("shadows_sun", GL_FRAGMENT_SHADER, ShaderSource.shadows_sun_fsh, + compileFlags); + try { + IProgramGL prog = ShaderCompiler.linkProgram("shadows_sun", SharedPipelineShaders.deferred_local, + shadowShader); + return new PipelineShaderShadowsSun(prog, shadowsSun, shadowsSunSmooth); + } finally { + if (shadowShader != null) { + shadowShader.free(); + } + } + } + + private PipelineShaderShadowsSun(IProgramGL program, int shadowsSun, boolean shadowsSunSmooth) { + super(program, new Uniforms(shadowsSun, shadowsSunSmooth)); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxAtmosphere.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxAtmosphere.java index 45ca0717..dd765ba5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxAtmosphere.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxAtmosphere.java @@ -1,46 +1,31 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; + import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderSkyboxAtmosphere extends ShaderProgram { - public static PipelineShaderSkyboxAtmosphere compile() throws ShaderException { - IShaderGL skyboxAtmosphere = ShaderCompiler.compileShader("skybox_atmosphere", GL_FRAGMENT_SHADER, - ShaderSource.skybox_atmosphere_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("skybox_atmosphere", SharedPipelineShaders.deferred_local, skyboxAtmosphere); - return new PipelineShaderSkyboxAtmosphere(prog); - }finally { - if(skyboxAtmosphere != null) { - skyboxAtmosphere.free(); - } - } - } - - private PipelineShaderSkyboxAtmosphere(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_sunDirectionIntensity4f = null; @@ -56,4 +41,22 @@ public class PipelineShaderSkyboxAtmosphere extends ShaderProgram { - public static PipelineShaderSkyboxIrradiance compile(int phase) throws ShaderException { - IShaderGL skyboxIrradiance = ShaderCompiler.compileShader("skybox_irradiance", GL_FRAGMENT_SHADER, - ShaderSource.skybox_irradiance_fsh, Arrays.asList("PHASE_" + phase)); - try { - IProgramGL prog = ShaderCompiler.linkProgram("skybox_irradiance", SharedPipelineShaders.deferred_local, skyboxIrradiance); - return new PipelineShaderSkyboxIrradiance(prog); - }finally { - if(skyboxIrradiance != null) { - skyboxIrradiance.free(); - } - } - } - - private PipelineShaderSkyboxIrradiance(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { private Uniforms() { @@ -54,4 +39,22 @@ public class PipelineShaderSkyboxIrradiance extends ShaderProgram { - public static PipelineShaderSkyboxRender compile(boolean paraboloid, boolean clouds) throws ShaderException { - List compileFlags = new ArrayList<>(); - if(paraboloid) { - compileFlags.add("COMPILE_PARABOLOID_SKY"); - } - if(clouds) { - compileFlags.add("COMPILE_CLOUDS"); - } - IShaderGL vertexShader = ShaderCompiler.compileShader("skybox_render", GL_VERTEX_SHADER, - ShaderSource.skybox_render_vsh, compileFlags); - IShaderGL fragmentShader = null; - try { - fragmentShader = ShaderCompiler.compileShader("skybox_render", GL_FRAGMENT_SHADER, - ShaderSource.skybox_render_fsh, compileFlags); - IProgramGL prog = ShaderCompiler.linkProgram("skybox_render", vertexShader, fragmentShader); - return new PipelineShaderSkyboxRender(prog, paraboloid); - }finally { - if(vertexShader != null) { - vertexShader.free(); - } - if(fragmentShader != null) { - fragmentShader.free(); - } - } - } - - private PipelineShaderSkyboxRender(IProgramGL program, boolean paraboloid) { - super(program, new Uniforms(paraboloid)); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_viewMatrix4f = null; @@ -84,7 +57,37 @@ public class PipelineShaderSkyboxRender extends ShaderProgram compileFlags = new ArrayList<>(); + if (paraboloid) { + compileFlags.add("COMPILE_PARABOLOID_SKY"); + } + if (clouds) { + compileFlags.add("COMPILE_CLOUDS"); + } + IShaderGL vertexShader = ShaderCompiler.compileShader("skybox_render", GL_VERTEX_SHADER, + ShaderSource.skybox_render_vsh, compileFlags); + IShaderGL fragmentShader = null; + try { + fragmentShader = ShaderCompiler.compileShader("skybox_render", GL_FRAGMENT_SHADER, + ShaderSource.skybox_render_fsh, compileFlags); + IProgramGL prog = ShaderCompiler.linkProgram("skybox_render", vertexShader, fragmentShader); + return new PipelineShaderSkyboxRender(prog, paraboloid); + } finally { + if (vertexShader != null) { + vertexShader.free(); + } + if (fragmentShader != null) { + fragmentShader.free(); + } + } + } + + private PipelineShaderSkyboxRender(IProgramGL program, boolean paraboloid) { + super(program, new Uniforms(paraboloid)); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxRenderEnd.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxRenderEnd.java index 39c62f12..91a1a483 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxRenderEnd.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/PipelineShaderSkyboxRenderEnd.java @@ -1,7 +1,9 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -10,43 +12,21 @@ import net.lax1dude.eaglercraft.v1_8.internal.IUniformGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PipelineShaderSkyboxRenderEnd extends ShaderProgram { - public static PipelineShaderSkyboxRenderEnd compile() throws ShaderException { - IShaderGL vertexShader = ShaderCompiler.compileShader("skybox_render_end", GL_VERTEX_SHADER, - ShaderSource.skybox_render_end_vsh); - IShaderGL fragmentShader = null; - try { - fragmentShader = ShaderCompiler.compileShader("skybox_render_end", GL_FRAGMENT_SHADER, - ShaderSource.skybox_render_end_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("skybox_render_end", vertexShader, fragmentShader); - return new PipelineShaderSkyboxRenderEnd(prog); - }finally { - if(vertexShader != null) { - vertexShader.free(); - } - if(fragmentShader != null) { - fragmentShader.free(); - } - } - } - - private PipelineShaderSkyboxRenderEnd(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_viewMatrix4f = null; @@ -66,4 +46,27 @@ public class PipelineShaderSkyboxRenderEnd extends ShaderProgram { - public static PipelineShaderTonemap compile() throws ShaderException { - IShaderGL tonemapOperator = ShaderCompiler.compileShader("post_tonemap", GL_FRAGMENT_SHADER, - ShaderSource.post_tonemap_fsh); - try { - IProgramGL prog = ShaderCompiler.linkProgram("post_tonemap", SharedPipelineShaders.deferred_local, tonemapOperator); - return new PipelineShaderTonemap(prog); - }finally { - if(tonemapOperator != null) { - tonemapOperator.free(); - } - } - } - - private PipelineShaderTonemap(IProgramGL program) { - super(program, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_exposure3f; @@ -57,4 +42,22 @@ public class PipelineShaderTonemap extends ShaderProgram compileFlags) throws ShaderCompileException { + public static IShaderGL compileShader(String name, int stage, ResourceLocation filename, List compileFlags) + throws ShaderCompileException { return compileShader(name, stage, filename.toString(), ShaderSource.getSourceFor(filename), compileFlags); } - public static IShaderGL compileShader(String name, int stage, String filename, String source, List compileFlags) throws ShaderCompileException { + public static IShaderGL compileShader(String name, int stage, ResourceLocation filename, String... compileFlags) + throws ShaderCompileException { + return compileShader(name, stage, filename.toString(), ShaderSource.getSourceFor(filename), + Arrays.asList(compileFlags)); + } + + public static IShaderGL compileShader(String name, int stage, String filename, String source, + List compileFlags) throws ShaderCompileException { logger.info("Compiling Shader: " + filename); StringBuilder srcCat = new StringBuilder(); srcCat.append(GLSLHeader.getHeader()).append('\n'); - - if(compileFlags != null && compileFlags.size() > 0) { - for(int i = 0, l = compileFlags.size(); i < l; ++i) { + + if (compileFlags != null && compileFlags.size() > 0) { + for (int i = 0, l = compileFlags.size(); i < l; ++i) { srcCat.append("#define ").append(compileFlags.get(i)).append('\n'); } } - + IShaderGL ret = _wglCreateShader(stage); _wglShaderSource(ret, srcCat.append(source).toString()); _wglCompileShader(ret); - - if(_wglGetShaderi(ret, GL_COMPILE_STATUS) != GL_TRUE) { + + if (_wglGetShaderi(ret, GL_COMPILE_STATUS) != GL_TRUE) { logger.error("Failed to compile {} \"{}\" of program \"{}\"!", getStageName(stage), filename, name); String log = _wglGetShaderInfoLog(ret); - if(log != null) { + if (log != null) { String s2 = getStageNameV2(stage); String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { + for (int i = 0; i < lines.length; ++i) { logger.error("[{}] [{}] [{}] {}", name, s2, filename, lines[i]); } } _wglDeleteShader(ret); - throw new ShaderCompileException(name, stage, filename, "Compile status for " + getStageName(stage) + " \"" + filename + "\" of \"" + name + "\" is not GL_TRUE!"); + throw new ShaderCompileException(name, stage, filename, "Compile status for " + getStageName(stage) + " \"" + + filename + "\" of \"" + name + "\" is not GL_TRUE!"); } - + return ret; } - public static IProgramGL linkProgram(String name, IShaderGL vert, IShaderGL frag) throws ShaderLinkException { - IProgramGL ret = _wglCreateProgram(); - - _wglAttachShader(ret, vert); - _wglAttachShader(ret, frag); - _wglLinkProgram(ret); - _wglDetachShader(ret, vert); - _wglDetachShader(ret, frag); - - if(_wglGetProgrami(ret, GL_LINK_STATUS) != GL_TRUE) { - logger.error("Failed to link program \"{}\"!", name); - String log = _wglGetProgramInfoLog(ret); - if(log != null) { - String[] lines = log.split("(\\r\\n|\\r|\\n)"); - for(int i = 0; i < lines.length; ++i) { - logger.error("[{}] [LINK] {}", name, lines[i]); - } - } - _wglDeleteProgram(ret); - throw new ShaderLinkException(name, "Link status for program \"" + name + "\" is not GL_TRUE!"); - } - - return ret; + public static IShaderGL compileShader(String name, int stage, String filename, String source, + String... compileFlags) throws ShaderCompileException { + return compileShader(name, stage, filename, source, Arrays.asList(compileFlags)); } private static String getStageName(int stage) { - switch(stage) { + switch (stage) { case GL_VERTEX_SHADER: return "GL_VERTEX_SHADER"; case GL_FRAGMENT_SHADER: @@ -113,7 +111,7 @@ public class ShaderCompiler { } private static String getStageNameV2(int stage) { - switch(stage) { + switch (stage) { case GL_VERTEX_SHADER: return "VERT"; case GL_FRAGMENT_SHADER: @@ -122,4 +120,29 @@ public class ShaderCompiler { return "stage_" + stage; } } + + public static IProgramGL linkProgram(String name, IShaderGL vert, IShaderGL frag) throws ShaderLinkException { + IProgramGL ret = _wglCreateProgram(); + + _wglAttachShader(ret, vert); + _wglAttachShader(ret, frag); + _wglLinkProgram(ret); + _wglDetachShader(ret, vert); + _wglDetachShader(ret, frag); + + if (_wglGetProgrami(ret, GL_LINK_STATUS) != GL_TRUE) { + logger.error("Failed to link program \"{}\"!", name); + String log = _wglGetProgramInfoLog(ret); + if (log != null) { + String[] lines = log.split("(\\r\\n|\\r|\\n)"); + for (int i = 0; i < lines.length; ++i) { + logger.error("[{}] [LINK] {}", name, lines[i]); + } + } + _wglDeleteProgram(ret); + throw new ShaderLinkException(name, "Link status for program \"" + name + "\" is not GL_TRUE!"); + } + + return ret; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderException.java index f33ef8c8..8e2a83a7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderLinkException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderLinkException.java index 259566e9..8d4bfc25 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderLinkException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderLinkException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderProgram.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderProgram.java index acfc6255..4d00be30 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderProgram.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderProgram.java @@ -6,14 +6,15 @@ import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,8 +29,12 @@ public class ShaderProgram { this.uniforms = uniforms; } + public void destroy() { + program.free(); + } + public ShaderProgram loadUniforms() { - if(uniforms != null) { + if (uniforms != null) { EaglercraftGPU.bindGLShaderProgram(program); uniforms.loadUniforms(program); } @@ -40,8 +45,4 @@ public class ShaderProgram { EaglercraftGPU.bindGLShaderProgram(program); } - public void destroy() { - program.free(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderSource.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderSource.java index 17b21299..ee79bde4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderSource.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/ShaderSource.java @@ -18,14 +18,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,83 +35,145 @@ public class ShaderSource { private static final Logger logger = LogManager.getLogger("ShaderSource"); - public static final ResourceLocation accel_particle_vsh = new ResourceLocation("eagler:glsl/deferred/accel_particle.vsh"); - public static final ResourceLocation accel_particle_gbuffer_fsh = new ResourceLocation("eagler:glsl/deferred/accel_particle_gbuffer.fsh"); - public static final ResourceLocation accel_particle_forward_fsh = new ResourceLocation("eagler:glsl/deferred/accel_particle_forward.fsh"); - public static final ResourceLocation deferred_core_vsh = new ResourceLocation("eagler:glsl/deferred/deferred_core.vsh"); - public static final ResourceLocation deferred_core_gbuffer_fsh = new ResourceLocation("eagler:glsl/deferred/deferred_core_gbuffer.fsh"); - public static final ResourceLocation deferred_shadow_vsh = new ResourceLocation("eagler:glsl/deferred/deferred_shadow.vsh"); - public static final ResourceLocation deferred_shadow_fsh = new ResourceLocation("eagler:glsl/deferred/deferred_shadow.fsh"); - public static final ResourceLocation deferred_local_vsh = new ResourceLocation("eagler:glsl/deferred/deferred_local.vsh"); - public static final ResourceLocation deferred_combine_fsh = new ResourceLocation("eagler:glsl/deferred/deferred_combine.fsh"); - public static final ResourceLocation deferred_fog_fsh = new ResourceLocation("eagler:glsl/deferred/deferred_fog.fsh"); - public static final ResourceLocation forward_core_vsh = new ResourceLocation("eagler:glsl/deferred/forward_core.vsh"); - public static final ResourceLocation forward_core_fsh = new ResourceLocation("eagler:glsl/deferred/forward_core.fsh"); - public static final ResourceLocation forward_glass_highlights_vsh = new ResourceLocation("eagler:glsl/deferred/forward_glass_highlights.vsh"); - public static final ResourceLocation forward_glass_highlights_fsh = new ResourceLocation("eagler:glsl/deferred/forward_glass_highlights.fsh"); - public static final ResourceLocation realistic_water_mask_vsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_mask.vsh"); - public static final ResourceLocation realistic_water_mask_fsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_mask.fsh"); - public static final ResourceLocation realistic_water_render_vsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_render.vsh"); - public static final ResourceLocation realistic_water_render_fsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_render.fsh"); - public static final ResourceLocation realistic_water_control_fsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_control.fsh"); - public static final ResourceLocation realistic_water_normals_fsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_normals.fsh"); - public static final ResourceLocation realistic_water_noise_fsh = new ResourceLocation("eagler:glsl/deferred/realistic_water_noise.fsh"); - public static final ResourceLocation gbuffer_debug_view_fsh = new ResourceLocation("eagler:glsl/deferred/gbuffer_debug_view.fsh"); - public static final ResourceLocation ssao_generate_fsh = new ResourceLocation("eagler:glsl/deferred/ssao_generate.fsh"); - public static final ResourceLocation lighting_sun_fsh = new ResourceLocation("eagler:glsl/deferred/lighting_sun.fsh"); + public static final ResourceLocation accel_particle_vsh = new ResourceLocation( + "eagler:glsl/deferred/accel_particle.vsh"); + public static final ResourceLocation accel_particle_gbuffer_fsh = new ResourceLocation( + "eagler:glsl/deferred/accel_particle_gbuffer.fsh"); + public static final ResourceLocation accel_particle_forward_fsh = new ResourceLocation( + "eagler:glsl/deferred/accel_particle_forward.fsh"); + public static final ResourceLocation deferred_core_vsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_core.vsh"); + public static final ResourceLocation deferred_core_gbuffer_fsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_core_gbuffer.fsh"); + public static final ResourceLocation deferred_shadow_vsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_shadow.vsh"); + public static final ResourceLocation deferred_shadow_fsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_shadow.fsh"); + public static final ResourceLocation deferred_local_vsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_local.vsh"); + public static final ResourceLocation deferred_combine_fsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_combine.fsh"); + public static final ResourceLocation deferred_fog_fsh = new ResourceLocation( + "eagler:glsl/deferred/deferred_fog.fsh"); + public static final ResourceLocation forward_core_vsh = new ResourceLocation( + "eagler:glsl/deferred/forward_core.vsh"); + public static final ResourceLocation forward_core_fsh = new ResourceLocation( + "eagler:glsl/deferred/forward_core.fsh"); + public static final ResourceLocation forward_glass_highlights_vsh = new ResourceLocation( + "eagler:glsl/deferred/forward_glass_highlights.vsh"); + public static final ResourceLocation forward_glass_highlights_fsh = new ResourceLocation( + "eagler:glsl/deferred/forward_glass_highlights.fsh"); + public static final ResourceLocation realistic_water_mask_vsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_mask.vsh"); + public static final ResourceLocation realistic_water_mask_fsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_mask.fsh"); + public static final ResourceLocation realistic_water_render_vsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_render.vsh"); + public static final ResourceLocation realistic_water_render_fsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_render.fsh"); + public static final ResourceLocation realistic_water_control_fsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_control.fsh"); + public static final ResourceLocation realistic_water_normals_fsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_normals.fsh"); + public static final ResourceLocation realistic_water_noise_fsh = new ResourceLocation( + "eagler:glsl/deferred/realistic_water_noise.fsh"); + public static final ResourceLocation gbuffer_debug_view_fsh = new ResourceLocation( + "eagler:glsl/deferred/gbuffer_debug_view.fsh"); + public static final ResourceLocation ssao_generate_fsh = new ResourceLocation( + "eagler:glsl/deferred/ssao_generate.fsh"); + public static final ResourceLocation lighting_sun_fsh = new ResourceLocation( + "eagler:glsl/deferred/lighting_sun.fsh"); public static final ResourceLocation shadows_sun_fsh = new ResourceLocation("eagler:glsl/deferred/shadows_sun.fsh"); - public static final ResourceLocation light_shafts_sample_fsh = new ResourceLocation("eagler:glsl/deferred/light_shafts_sample.fsh"); - public static final ResourceLocation post_tonemap_fsh = new ResourceLocation("eagler:glsl/deferred/post_tonemap.fsh"); - public static final ResourceLocation post_bloom_bright_fsh = new ResourceLocation("eagler:glsl/deferred/post_bloom_bright.fsh"); - public static final ResourceLocation post_bloom_blur_fsh = new ResourceLocation("eagler:glsl/deferred/post_bloom_blur.fsh"); - public static final ResourceLocation post_lens_distort_fsh = new ResourceLocation("eagler:glsl/deferred/post_lens_distort.fsh"); - public static final ResourceLocation post_exposure_avg_fsh = new ResourceLocation("eagler:glsl/deferred/post_exposure_avg.fsh"); - public static final ResourceLocation post_exposure_final_fsh = new ResourceLocation("eagler:glsl/deferred/post_exposure_final.fsh"); - public static final ResourceLocation post_lens_streaks_vsh = new ResourceLocation("eagler:glsl/deferred/post_lens_streaks.vsh"); - public static final ResourceLocation post_lens_streaks_fsh = new ResourceLocation("eagler:glsl/deferred/post_lens_streaks.fsh"); - public static final ResourceLocation post_lens_ghosts_vsh = new ResourceLocation("eagler:glsl/deferred/post_lens_ghosts.vsh"); - public static final ResourceLocation post_lens_ghosts_fsh = new ResourceLocation("eagler:glsl/deferred/post_lens_ghosts.fsh"); - public static final ResourceLocation lens_sun_occlusion_fsh = new ResourceLocation("eagler:glsl/deferred/lens_sun_occlusion.fsh"); - public static final ResourceLocation skybox_atmosphere_fsh = new ResourceLocation("eagler:glsl/deferred/skybox_atmosphere.fsh"); - public static final ResourceLocation skybox_irradiance_fsh = new ResourceLocation("eagler:glsl/deferred/skybox_irradiance.fsh"); - public static final ResourceLocation skybox_render_vsh = new ResourceLocation("eagler:glsl/deferred/skybox_render.vsh"); - public static final ResourceLocation skybox_render_fsh = new ResourceLocation("eagler:glsl/deferred/skybox_render.fsh"); - public static final ResourceLocation skybox_render_end_vsh = new ResourceLocation("eagler:glsl/deferred/skybox_render_end.vsh"); - public static final ResourceLocation skybox_render_end_fsh = new ResourceLocation("eagler:glsl/deferred/skybox_render_end.fsh"); + public static final ResourceLocation light_shafts_sample_fsh = new ResourceLocation( + "eagler:glsl/deferred/light_shafts_sample.fsh"); + public static final ResourceLocation post_tonemap_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_tonemap.fsh"); + public static final ResourceLocation post_bloom_bright_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_bloom_bright.fsh"); + public static final ResourceLocation post_bloom_blur_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_bloom_blur.fsh"); + public static final ResourceLocation post_lens_distort_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_lens_distort.fsh"); + public static final ResourceLocation post_exposure_avg_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_exposure_avg.fsh"); + public static final ResourceLocation post_exposure_final_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_exposure_final.fsh"); + public static final ResourceLocation post_lens_streaks_vsh = new ResourceLocation( + "eagler:glsl/deferred/post_lens_streaks.vsh"); + public static final ResourceLocation post_lens_streaks_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_lens_streaks.fsh"); + public static final ResourceLocation post_lens_ghosts_vsh = new ResourceLocation( + "eagler:glsl/deferred/post_lens_ghosts.vsh"); + public static final ResourceLocation post_lens_ghosts_fsh = new ResourceLocation( + "eagler:glsl/deferred/post_lens_ghosts.fsh"); + public static final ResourceLocation lens_sun_occlusion_fsh = new ResourceLocation( + "eagler:glsl/deferred/lens_sun_occlusion.fsh"); + public static final ResourceLocation skybox_atmosphere_fsh = new ResourceLocation( + "eagler:glsl/deferred/skybox_atmosphere.fsh"); + public static final ResourceLocation skybox_irradiance_fsh = new ResourceLocation( + "eagler:glsl/deferred/skybox_irradiance.fsh"); + public static final ResourceLocation skybox_render_vsh = new ResourceLocation( + "eagler:glsl/deferred/skybox_render.vsh"); + public static final ResourceLocation skybox_render_fsh = new ResourceLocation( + "eagler:glsl/deferred/skybox_render.fsh"); + public static final ResourceLocation skybox_render_end_vsh = new ResourceLocation( + "eagler:glsl/deferred/skybox_render_end.vsh"); + public static final ResourceLocation skybox_render_end_fsh = new ResourceLocation( + "eagler:glsl/deferred/skybox_render_end.fsh"); public static final ResourceLocation moon_render_vsh = new ResourceLocation("eagler:glsl/deferred/moon_render.vsh"); public static final ResourceLocation moon_render_fsh = new ResourceLocation("eagler:glsl/deferred/moon_render.fsh"); - public static final ResourceLocation clouds_noise3d_fsh = new ResourceLocation("eagler:glsl/deferred/clouds_noise3d.fsh"); - public static final ResourceLocation clouds_shapes_fsh = new ResourceLocation("eagler:glsl/deferred/clouds_shapes.fsh"); - public static final ResourceLocation clouds_shapes_vsh = new ResourceLocation("eagler:glsl/deferred/clouds_shapes.vsh"); - public static final ResourceLocation clouds_sample_fsh = new ResourceLocation("eagler:glsl/deferred/clouds_sample.fsh"); - public static final ResourceLocation clouds_sun_occlusion_fsh = new ResourceLocation("eagler:glsl/deferred/clouds_sun_occlusion.fsh"); - public static final ResourceLocation clouds_color_fsh = new ResourceLocation("eagler:glsl/deferred/clouds_color.fsh"); - public static final ResourceLocation lighting_mesh_vsh = new ResourceLocation("eagler:glsl/deferred/lighting_mesh.vsh"); - public static final ResourceLocation lighting_point_fsh = new ResourceLocation("eagler:glsl/deferred/lighting_point.fsh"); - public static final ResourceLocation reproject_control_fsh = new ResourceLocation("eagler:glsl/deferred/reproject_control.fsh"); - public static final ResourceLocation reproject_ssr_fsh = new ResourceLocation("eagler:glsl/deferred/reproject_ssr.fsh"); + public static final ResourceLocation clouds_noise3d_fsh = new ResourceLocation( + "eagler:glsl/deferred/clouds_noise3d.fsh"); + public static final ResourceLocation clouds_shapes_fsh = new ResourceLocation( + "eagler:glsl/deferred/clouds_shapes.fsh"); + public static final ResourceLocation clouds_shapes_vsh = new ResourceLocation( + "eagler:glsl/deferred/clouds_shapes.vsh"); + public static final ResourceLocation clouds_sample_fsh = new ResourceLocation( + "eagler:glsl/deferred/clouds_sample.fsh"); + public static final ResourceLocation clouds_sun_occlusion_fsh = new ResourceLocation( + "eagler:glsl/deferred/clouds_sun_occlusion.fsh"); + public static final ResourceLocation clouds_color_fsh = new ResourceLocation( + "eagler:glsl/deferred/clouds_color.fsh"); + public static final ResourceLocation lighting_mesh_vsh = new ResourceLocation( + "eagler:glsl/deferred/lighting_mesh.vsh"); + public static final ResourceLocation lighting_point_fsh = new ResourceLocation( + "eagler:glsl/deferred/lighting_point.fsh"); + public static final ResourceLocation reproject_control_fsh = new ResourceLocation( + "eagler:glsl/deferred/reproject_control.fsh"); + public static final ResourceLocation reproject_ssr_fsh = new ResourceLocation( + "eagler:glsl/deferred/reproject_ssr.fsh"); public static final ResourceLocation post_fxaa_fsh = new ResourceLocation("eagler:glsl/deferred/post_fxaa.fsh"); - public static final ResourceLocation hand_depth_mask_fsh = new ResourceLocation("eagler:glsl/deferred/hand_depth_mask.fsh"); + public static final ResourceLocation hand_depth_mask_fsh = new ResourceLocation( + "eagler:glsl/deferred/hand_depth_mask.fsh"); - public static final ResourceLocation core_dynamiclights_vsh = new ResourceLocation("eagler:glsl/dynamiclights/core_dynamiclights.vsh"); - public static final ResourceLocation core_dynamiclights_fsh = new ResourceLocation("eagler:glsl/dynamiclights/core_dynamiclights.fsh"); - public static final ResourceLocation accel_particle_dynamiclights_vsh = new ResourceLocation("eagler:glsl/dynamiclights/accel_particle_dynamiclights.vsh"); - public static final ResourceLocation accel_particle_dynamiclights_fsh = new ResourceLocation("eagler:glsl/dynamiclights/accel_particle_dynamiclights.fsh"); + public static final ResourceLocation core_dynamiclights_vsh = new ResourceLocation( + "eagler:glsl/dynamiclights/core_dynamiclights.vsh"); + public static final ResourceLocation core_dynamiclights_fsh = new ResourceLocation( + "eagler:glsl/dynamiclights/core_dynamiclights.fsh"); + public static final ResourceLocation accel_particle_dynamiclights_vsh = new ResourceLocation( + "eagler:glsl/dynamiclights/accel_particle_dynamiclights.vsh"); + public static final ResourceLocation accel_particle_dynamiclights_fsh = new ResourceLocation( + "eagler:glsl/dynamiclights/accel_particle_dynamiclights.fsh"); private static final Map sourceCache = new HashMap<>(); private static boolean isHighP = false; + public static void clearCache() { + sourceCache.clear(); + logger.info("Cleared Cache"); + } + public static String getSourceFor(ResourceLocation path) { return getSourceFor(path, 0); } private static String getSourceFor(ResourceLocation path, int lineNumberOffset) { String str = sourceCache.get(path); - if(str == null) { + if (str == null) { try { str = loadSource(path, lineNumberOffset); - }catch(IOException ex) { + } catch (IOException ex) { str = ""; logger.error("Could not load shader source \"{}\"! {}", deferred_core_vsh, ex.toString()); logger.error("This may cause a NullPointerException when enabling certain features"); @@ -123,44 +186,52 @@ public class ShaderSource { private static String loadSource(ResourceLocation resourceLocation, int fileID) throws IOException { StringBuilder ret = new StringBuilder(); - try(InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(resourceLocation).getInputStream()) { + try (InputStream is = Minecraft.getMinecraft().getResourceManager().getResource(resourceLocation) + .getInputStream()) { int lineCounter = 1; BufferedReader lineReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); String line; - while((line = lineReader.readLine()) != null) { - if(line.startsWith("#line ")) { + while ((line = lineReader.readLine()) != null) { + if (line.startsWith("#line ")) { String[] split = line.split("\\s+", 3); try { lineCounter = Integer.parseInt(split[1]); - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { throw new IOException("Invalid preprocessor directive: " + line, ex); } ret.append("#line ").append(lineCounter).append(' ').append(fileID).append('\n'); - }else if(line.startsWith("#EAGLER ")) { + } else if (line.startsWith("#EAGLER ")) { StrTokenizer tokenizer = new StrTokenizer(line.substring(8)); tokenizer.setDelimiterChar(' '); tokenizer.setIgnoreEmptyTokens(true); tokenizer.setQuoteChar('\"'); - if(tokenizer.hasNext()) { + if (tokenizer.hasNext()) { String p1 = tokenizer.next(); - if(p1.equals("INCLUDE") && tokenizer.hasNext()) { + if (p1.equals("INCLUDE") && tokenizer.hasNext()) { String fileIDStr = tokenizer.next(); - if(tokenizer.hasNext() && fileIDStr.charAt(0) == '(' && fileIDStr.charAt(fileIDStr.length() - 1) == ')') { + if (tokenizer.hasNext() && fileIDStr.charAt(0) == '(' + && fileIDStr.charAt(fileIDStr.length() - 1) == ')') { String includePath = tokenizer.next(); - if(!tokenizer.hasNext()) { // ignore if there are extra arguments + if (!tokenizer.hasNext()) { // ignore if there are extra arguments int newFileId = -1; try { newFileId = Integer.parseInt(fileIDStr.substring(1, fileIDStr.length() - 1)); - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { } - if(newFileId != -1) { + if (newFileId != -1) { newFileId += fileID * 100; - ret.append('\n').append("////////////////////////////////////////////////////////////////////").append('\n'); + ret.append('\n').append( + "////////////////////////////////////////////////////////////////////") + .append('\n'); ret.append("//" + line).append('\n'); ret.append("#line 1 ").append(newFileId).append('\n'); - ret.append(getSourceFor(new ResourceLocation(includePath), newFileId)).append('\n'); - ret.append("////////////////////////////////////////////////////////////////////").append('\n'); - ret.append("#line ").append(lineCounter - 1).append(' ').append(fileID).append('\n').append('\n'); + ret.append(getSourceFor(new ResourceLocation(includePath), newFileId)) + .append('\n'); + ret.append( + "////////////////////////////////////////////////////////////////////") + .append('\n'); + ret.append("#line ").append(lineCounter - 1).append(' ').append(fileID) + .append('\n').append('\n'); ++lineCounter; continue; } @@ -170,9 +241,9 @@ public class ShaderSource { } logger.error("Skipping invalid preprocessor directive: " + line); ret.append("// [INVALID]: " + line).append('\n'); - }else if(isHighP && line.startsWith("precision")) { + } else if (isHighP && line.startsWith("precision")) { ret.append(line.replace("lowp", "highp").replace("mediump", "highp")).append('\n'); - }else { + } else { ret.append(line).append('\n'); } ++lineCounter; @@ -181,11 +252,6 @@ public class ShaderSource { return ret.toString(); } - public static void clearCache() { - sourceCache.clear(); - logger.info("Cleared Cache"); - } - public static void setHighP(boolean b) { isHighP = b; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/SharedPipelineShaders.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/SharedPipelineShaders.java index c2a902fc..4c0bc675 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/SharedPipelineShaders.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/program/SharedPipelineShaders.java @@ -1,20 +1,21 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program; -import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,21 +25,22 @@ public class SharedPipelineShaders { public static IShaderGL deferred_local = null; public static IShaderGL lighting_mesh = null; - public static void init() throws ShaderException { - free(); - deferred_local = ShaderCompiler.compileShader("deferred_local_vsh", GL_VERTEX_SHADER, ShaderSource.deferred_local_vsh); - lighting_mesh = ShaderCompiler.compileShader("lighting_mesh", GL_VERTEX_SHADER, ShaderSource.lighting_mesh_vsh); - } - public static void free() { - if(deferred_local != null) { + if (deferred_local != null) { deferred_local.free(); deferred_local = null; } - if(lighting_mesh != null) { + if (lighting_mesh != null) { lighting_mesh.free(); lighting_mesh = null; } } + public static void init() throws ShaderException { + free(); + deferred_local = ShaderCompiler.compileShader("deferred_local_vsh", GL_VERTEX_SHADER, + ShaderSource.deferred_local_vsh); + lighting_mesh = ShaderCompiler.compileShader("lighting_mesh", GL_VERTEX_SHADER, ShaderSource.lighting_mesh_vsh); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerBitwisePackedTexture.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerBitwisePackedTexture.java index 72bcf5f6..69a64123 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerBitwisePackedTexture.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerBitwisePackedTexture.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,23 +27,24 @@ public class EaglerBitwisePackedTexture { private static int getFromBits(int idxx, int bits, byte[] bytes) { int startByte = idxx >> 3; int endByte = (idxx + bits - 1) >> 3; - if(startByte == endByte) { - return (((int)bytes[startByte] & 0xff) >> (8 - (idxx & 7) - bits)) & ((1 << bits) - 1); - }else { - return (((((int)bytes[startByte] & 0xff) << 8) | ((int)bytes[endByte] & 0xff)) >> (16 - (idxx & 7) - bits)) & ((1 << bits) - 1); + if (startByte == endByte) { + return (((int) bytes[startByte] & 0xff) >> (8 - (idxx & 7) - bits)) & ((1 << bits) - 1); + } else { + return (((((int) bytes[startByte] & 0xff) << 8) | ((int) bytes[endByte] & 0xff)) >> (16 - (idxx & 7) + - bits)) & ((1 << bits) - 1); } } public static ImageData loadTexture(InputStream is, int alpha) throws IOException { - if(is.read() != '%' || is.read() != 'E' || is.read() != 'B' || is.read() != 'P') { + if (is.read() != '%' || is.read() != 'E' || is.read() != 'B' || is.read() != 'P') { throw new IOException("Not an EBP file!"); } int v = is.read(); - if(v != 1) { + if (v != 1) { throw new IOException("Unknown EBP version: " + v); } v = is.read(); - if(v != 3) { + if (v != 3) { throw new IOException("Invalid component count: " + v); } int w = is.read() | (is.read() << 8); @@ -50,27 +52,27 @@ public class EaglerBitwisePackedTexture { ImageData img = new ImageData(w, h, true); alpha <<= 24; v = is.read(); - if(v == 0) { - for(int i = 0, l = w * h; i < l; ++i) { + if (v == 0) { + for (int i = 0, l = w * h; i < l; ++i) { img.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | alpha; } - }else if(v == 1) { + } else if (v == 1) { int paletteSize = is.read(); int[] palette = new int[paletteSize + 1]; palette[0] = alpha; - for(int i = 0; i < paletteSize; ++i) { + for (int i = 0; i < paletteSize; ++i) { palette[i + 1] = is.read() | (is.read() << 8) | (is.read() << 16) | alpha; } int bpp = is.read(); byte[] readSet = new byte[is.read() | (is.read() << 8) | (is.read() << 16)]; is.read(readSet); - for(int i = 0, l = w * h; i < l; ++i) { + for (int i = 0, l = w * h; i < l; ++i) { img.pixels[i] = palette[getFromBits(i * bpp, bpp, readSet)]; } - }else { + } else { throw new IOException("Unknown EBP storage type: " + v); } - if(is.read() != ':' || is.read() != '>') { + if (is.read() != ':' || is.read() != '>') { throw new IOException("Invalid footer! (:>)"); } return img; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerTextureAtlasSpritePBR.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerTextureAtlasSpritePBR.java index a2074e2d..796d5041 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerTextureAtlasSpritePBR.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EaglerTextureAtlasSpritePBR.java @@ -25,14 +25,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,27 +42,134 @@ public class EaglerTextureAtlasSpritePBR extends EaglerTextureAtlasSprite { private static final Logger logger = LogManager.getLogger("EaglerTextureAtlasSpritePBR"); - protected List[] frameTextureDataPBR = new List[] { Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList() }; - protected TextureAnimationCache[] animationCachePBR = new TextureAnimationCache[3]; - - public boolean dontAnimateNormals = true; - public boolean dontAnimateMaterial = true; - public static EaglerTextureAtlasSpritePBR makeAtlasSprite(ResourceLocation spriteResourceLocation) { String s = spriteResourceLocation.toString(); return (EaglerTextureAtlasSpritePBR) (locationNameClock.equals(s) ? new TextureClockPBRImpl(s) : (locationNameCompass.equals(s) ? new TextureCompassPBRImpl(s) : new EaglerTextureAtlasSpritePBR(s))); } + protected List[] frameTextureDataPBR = new List[] { Lists.newArrayList(), Lists.newArrayList(), + Lists.newArrayList() }; + + protected TextureAnimationCache[] animationCachePBR = new TextureAnimationCache[3]; + public boolean dontAnimateNormals = true; + + public boolean dontAnimateMaterial = true; + public EaglerTextureAtlasSpritePBR(String spriteName) { super(spriteName); } - public void loadSpritePBR(ImageData[][] imageDatas, AnimationMetadataSection meta, - boolean dontAnimateNormals, boolean dontAnimateMaterial) { + protected void allocateFrameTextureData(int index) { + for (int j = 0; j < 3; ++j) { + if (this.frameTextureDataPBR[j].size() <= index) { + for (int i = this.frameTextureDataPBR[j].size(); i <= index; ++i) { + this.frameTextureDataPBR[j].add((int[][]) null); + } + } + } + } + + public void bakeAnimationCache() { + if (animationMetadata != null) { + for (int i = 0; i < 3; ++i) { + if (dontAnimateNormals && i == 1) + continue; + if (dontAnimateMaterial && i == 2) + continue; + int mipLevels = frameTextureDataPBR[i].get(0).length; + if (animationCachePBR[i] == null) { + animationCachePBR[i] = new TextureAnimationCache(width, height, mipLevels); + } + animationCachePBR[i].initialize(frameTextureDataPBR[i]); + } + } + } + + public void clearFramesTextureData() { + for (int i = 0; i < 3; ++i) { + this.frameTextureDataPBR[i].clear(); + if (this.animationCachePBR[i] != null) { + this.animationCachePBR[i].free(); + this.animationCachePBR[i] = null; + } + } + } + + public void generateMipmaps(int level) { + List[] arraylist = new List[] { Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList() }; + + for (int j = 0; j < 3; ++j) { + for (int i = 0; i < this.frameTextureDataPBR[j].size(); ++i) { + final int[][] aint = (int[][]) this.frameTextureDataPBR[j].get(i); + if (aint != null) { + try { + if (j == 0) { + arraylist[j].add(TextureUtil.generateMipmapData(level, this.width, aint)); + } else { + arraylist[j].add(PBRTextureMapUtils.generateMipmapDataIgnoreAlpha(level, this.width, aint)); + } + } catch (Throwable throwable) { + CrashReport crashreport = CrashReport.makeCrashReport(throwable, + "Generating mipmaps for frame (pbr)"); + CrashReportCategory crashreportcategory = crashreport.makeCategory("Frame being iterated"); + crashreportcategory.addCrashSection("PBR Layer", Integer.valueOf(j)); + crashreportcategory.addCrashSection("Frame index", Integer.valueOf(i)); + crashreportcategory.addCrashSectionCallable("Frame sizes", new Callable() { + public String call() throws Exception { + StringBuilder stringbuilder = new StringBuilder(); + + for (int k = 0; k < aint.length; ++k) { + if (stringbuilder.length() > 0) { + stringbuilder.append(", "); + } + + int[] aint1 = aint[k]; + stringbuilder.append(aint1 == null ? "null" : Integer.valueOf(aint1.length)); + } + + return stringbuilder.toString(); + } + }); + throw new ReportedException(crashreport); + } + } + } + } + + this.setFramesTextureDataPBR(arraylist); + this.bakeAnimationCache(); + } + + public int getFrameCount() { + return frameTextureDataPBR[0].size(); + } + + public int[][][] getFramePBRTextureData(int index) { + return new int[][][] { frameTextureDataPBR[0].get(index), frameTextureDataPBR[1].get(index), + frameTextureDataPBR[2].get(index) }; + } + + public int[][] getFrameTextureData(int index) { + return frameTextureDataPBR[0].get(index); + } + + public void loadSprite(ImageData[] images, AnimationMetadataSection meta) throws IOException { + Throwable t = new UnsupportedOperationException( + "Cannot call regular loadSprite in PBR mode, use loadSpritePBR"); + try { + throw t; + } catch (Throwable tt) { + logger.error(t); + } + } + + public void loadSpritePBR(ImageData[][] imageDatas, AnimationMetadataSection meta, boolean dontAnimateNormals, + boolean dontAnimateMaterial) { this.resetSprite(); - if(imageDatas.length != 3) { - throw new IllegalArgumentException("loadSpritePBR required an array of 3 different textures (" + imageDatas.length + " given)"); + if (imageDatas.length != 3) { + throw new IllegalArgumentException( + "loadSpritePBR required an array of 3 different textures (" + imageDatas.length + " given)"); } this.dontAnimateNormals = dontAnimateNormals; this.dontAnimateMaterial = dontAnimateMaterial; @@ -83,9 +191,10 @@ public class EaglerTextureAtlasSpritePBR extends EaglerTextureAtlasSprite { Integer.valueOf(bufferedimage.height), Integer.valueOf(i >> k), Integer.valueOf(j >> k) })); } - + aint[l][k] = new int[bufferedimage.width * bufferedimage.height]; - bufferedimage.getRGB(0, 0, bufferedimage.width, bufferedimage.height, aint[l][k], 0, bufferedimage.width); + bufferedimage.getRGB(0, 0, bufferedimage.width, bufferedimage.height, aint[l][k], 0, + bufferedimage.width); } } } @@ -135,94 +244,53 @@ public class EaglerTextureAtlasSpritePBR extends EaglerTextureAtlasSprite { } } - public int[][][] getFramePBRTextureData(int index) { - return new int[][][] { frameTextureDataPBR[0].get(index), - frameTextureDataPBR[1].get(index), - frameTextureDataPBR[2].get(index) }; + protected void resetSprite() { + this.animationMetadata = null; + this.setFramesTextureDataPBR(new List[] { Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList() }); + this.frameCounter = 0; + this.tickCounter = 0; + for (int i = 0; i < 3; ++i) { + if (this.animationCachePBR[i] != null) { + this.animationCachePBR[i].free(); + this.animationCachePBR[i] = null; + } + } } - public int[][] getFrameTextureData(int index) { - return frameTextureDataPBR[0].get(index); - } - - public int getFrameCount() { - return frameTextureDataPBR[0].size(); + public void setFramesTextureData(List newFramesTextureData) { + Throwable t = new UnsupportedOperationException( + "Cannot call regular setFramesTextureData in PBR mode, use setFramesTextureDataPBR"); + try { + throw t; + } catch (Throwable tt) { + logger.error(t); + } } public void setFramesTextureDataPBR(List[] newFramesTextureData) { frameTextureDataPBR = newFramesTextureData; } - protected void allocateFrameTextureData(int index) { - for(int j = 0; j < 3; ++j) { - if (this.frameTextureDataPBR[j].size() <= index) { - for (int i = this.frameTextureDataPBR[j].size(); i <= index; ++i) { - this.frameTextureDataPBR[j].add((int[][]) null); - } - } + public String toString() { + return "EaglerTextureAtlasSpritePBR{name=\'" + this.iconName + '\'' + ", frameCount=" + + this.framesTextureData.size() + ", rotated=" + this.rotated + ", x=" + this.originX + ", y=" + + this.originY + ", height=" + this.height + ", width=" + this.width + ", u0=" + this.minU + ", u1=" + + this.maxU + ", v0=" + this.minV + ", v1=" + this.maxV + '}'; + } + + public void updateAnimation(IFramebufferGL[] fb) { + Throwable t = new UnsupportedOperationException( + "Cannot call regular updateAnimation in PBR mode, use updateAnimationPBR"); + try { + throw t; + } catch (Throwable tt) { + logger.error(t); } } - public void generateMipmaps(int level) { - List[] arraylist = new List[] { Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList() }; - - for(int j = 0; j < 3; ++j) { - for (int i = 0; i < this.frameTextureDataPBR[j].size(); ++i) { - final int[][] aint = (int[][]) this.frameTextureDataPBR[j].get(i); - if (aint != null) { - try { - if(j == 0) { - arraylist[j].add(TextureUtil.generateMipmapData(level, this.width, aint)); - }else { - arraylist[j].add(PBRTextureMapUtils.generateMipmapDataIgnoreAlpha(level, this.width, aint)); - } - } catch (Throwable throwable) { - CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Generating mipmaps for frame (pbr)"); - CrashReportCategory crashreportcategory = crashreport.makeCategory("Frame being iterated"); - crashreportcategory.addCrashSection("PBR Layer", Integer.valueOf(j)); - crashreportcategory.addCrashSection("Frame index", Integer.valueOf(i)); - crashreportcategory.addCrashSectionCallable("Frame sizes", new Callable() { - public String call() throws Exception { - StringBuilder stringbuilder = new StringBuilder(); - - for (int k = 0; k < aint.length; ++k) { - if (stringbuilder.length() > 0) { - stringbuilder.append(", "); - } - - int[] aint1 = aint[k]; - stringbuilder.append(aint1 == null ? "null" : Integer.valueOf(aint1.length)); - } - - return stringbuilder.toString(); - } - }); - throw new ReportedException(crashreport); - } - } - } - } - - this.setFramesTextureDataPBR(arraylist); - this.bakeAnimationCache(); - } - - public void bakeAnimationCache() { - if(animationMetadata != null) { - for(int i = 0; i < 3; ++i) { - if(dontAnimateNormals && i == 1) continue; - if(dontAnimateMaterial && i == 2) continue; - int mipLevels = frameTextureDataPBR[i].get(0).length; - if(animationCachePBR[i] == null) { - animationCachePBR[i] = new TextureAnimationCache(width, height, mipLevels); - } - animationCachePBR[i].initialize(frameTextureDataPBR[i]); - } - } - } - - public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, int materialTexOffset) { - if(animationCachePBR[0] == null || (!dontAnimateNormals && animationCachePBR[1] == null) + public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, + int materialTexOffset) { + if (animationCachePBR[0] == null || (!dontAnimateNormals && animationCachePBR[1] == null) || (!dontAnimateMaterial && animationCachePBR[2] == null)) { throw new IllegalStateException("Animation cache for '" + this.iconName + "' was never baked!"); } @@ -235,79 +303,33 @@ public class EaglerTextureAtlasSpritePBR extends EaglerTextureAtlasSprite { this.tickCounter = 0; int k = this.animationMetadata.getFrameIndex(this.frameCounter); if (i != k && k >= 0 && k < this.frameTextureDataPBR[0].size()) { - animationCachePBR[0].copyFrameLevelsToTex2D(k, this.originX, this.originY, this.width, this.height, copyColorFramebuffer); - if(!dontAnimateNormals) animationCachePBR[1].copyFrameLevelsToTex2D(k, this.originX, this.originY, this.width, this.height, copyMaterialFramebuffer); - if(!dontAnimateMaterial) animationCachePBR[2].copyFrameLevelsToTex2D(k, this.originX, this.originY + materialTexOffset, this.width, this.height, copyMaterialFramebuffer); + animationCachePBR[0].copyFrameLevelsToTex2D(k, this.originX, this.originY, this.width, this.height, + copyColorFramebuffer); + if (!dontAnimateNormals) + animationCachePBR[1].copyFrameLevelsToTex2D(k, this.originX, this.originY, this.width, this.height, + copyMaterialFramebuffer); + if (!dontAnimateMaterial) + animationCachePBR[2].copyFrameLevelsToTex2D(k, this.originX, this.originY + materialTexOffset, + this.width, this.height, copyMaterialFramebuffer); } } else if (this.animationMetadata.isInterpolate()) { - float f = 1.0f - (float) this.tickCounter / (float) this.animationMetadata.getFrameTimeSingle(this.frameCounter); + float f = 1.0f + - (float) this.tickCounter / (float) this.animationMetadata.getFrameTimeSingle(this.frameCounter); int i = this.animationMetadata.getFrameIndex(this.frameCounter); int j = this.animationMetadata.getFrameCount() == 0 ? this.frameTextureDataPBR[0].size() : this.animationMetadata.getFrameCount(); int k = this.animationMetadata.getFrameIndex((this.frameCounter + 1) % j); if (i != k && k >= 0 && k < this.frameTextureDataPBR[0].size()) { - animationCachePBR[0].copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY, this.width, this.height, copyColorFramebuffer); - if(!dontAnimateNormals) animationCachePBR[1].copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY, this.width, this.height, copyMaterialFramebuffer); - if(!dontAnimateMaterial) animationCachePBR[2].copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY + materialTexOffset, this.width, this.height, copyMaterialFramebuffer); + animationCachePBR[0].copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY, this.width, + this.height, copyColorFramebuffer); + if (!dontAnimateNormals) + animationCachePBR[1].copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, this.originY, + this.width, this.height, copyMaterialFramebuffer); + if (!dontAnimateMaterial) + animationCachePBR[2].copyInterpolatedFrameLevelsToTex2D(i, k, f, this.originX, + this.originY + materialTexOffset, this.width, this.height, copyMaterialFramebuffer); } } } - public void clearFramesTextureData() { - for(int i = 0; i < 3; ++i) { - this.frameTextureDataPBR[i].clear(); - if(this.animationCachePBR[i] != null) { - this.animationCachePBR[i].free(); - this.animationCachePBR[i] = null; - } - } - } - - public void loadSprite(ImageData[] images, AnimationMetadataSection meta) throws IOException { - Throwable t = new UnsupportedOperationException("Cannot call regular loadSprite in PBR mode, use loadSpritePBR"); - try { - throw t; - }catch(Throwable tt) { - logger.error(t); - } - } - - public void setFramesTextureData(List newFramesTextureData) { - Throwable t = new UnsupportedOperationException("Cannot call regular setFramesTextureData in PBR mode, use setFramesTextureDataPBR"); - try { - throw t; - }catch(Throwable tt) { - logger.error(t); - } - } - - public void updateAnimation(IFramebufferGL[] fb) { - Throwable t = new UnsupportedOperationException("Cannot call regular updateAnimation in PBR mode, use updateAnimationPBR"); - try { - throw t; - }catch(Throwable tt) { - logger.error(t); - } - } - - protected void resetSprite() { - this.animationMetadata = null; - this.setFramesTextureDataPBR(new List[] { Lists.newArrayList(), Lists.newArrayList(), Lists.newArrayList() }); - this.frameCounter = 0; - this.tickCounter = 0; - for(int i = 0; i < 3; ++i) { - if(this.animationCachePBR[i] != null) { - this.animationCachePBR[i].free(); - this.animationCachePBR[i] = null; - } - } - } - - public String toString() { - return "EaglerTextureAtlasSpritePBR{name=\'" + this.iconName + '\'' + ", frameCount=" + this.framesTextureData.size() - + ", rotated=" + this.rotated + ", x=" + this.originX + ", y=" + this.originY + ", height=" - + this.height + ", width=" + this.width + ", u0=" + this.minU + ", u1=" + this.maxU + ", v0=" - + this.minV + ", v1=" + this.maxV + '}'; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EmissiveItems.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EmissiveItems.java index 8e9eb1e6..e8e7c785 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EmissiveItems.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/EmissiveItems.java @@ -18,14 +18,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,16 +35,16 @@ public class EmissiveItems implements IResourceManagerReloadListener { private static final Logger logger = LogManager.getLogger("EmissiveItemsCSV"); - private static final Map entries = new HashMap<>(); - - public static float[] getItemEmission(ItemStack itemStack) { - return getItemEmission(itemStack.getItem(), itemStack.getItemDamage()); - } + private static final Map entries = new HashMap<>(); public static float[] getItemEmission(Item item, int damage) { return entries.get(Item.itemRegistry.getNameForObject(item).toString() + "#" + damage); } + public static float[] getItemEmission(ItemStack itemStack) { + return getItemEmission(itemStack.getItem(), itemStack.getItemDamage()); + } + @Override public void onResourceManagerReload(IResourceManager var1) { try { @@ -53,14 +54,14 @@ public class EmissiveItems implements IResourceManagerReloadListener { entries.clear(); String line; boolean firstLine = true; - while((line = reader.readLine()) != null) { - if((line = line.trim()).length() > 0) { - if(firstLine) { + while ((line = reader.readLine()) != null) { + if ((line = line.trim()).length() > 0) { + if (firstLine) { firstLine = false; continue; } String[] split = line.split(","); - if(split.length == 6) { + if (split.length == 6) { try { int dmg = Integer.parseInt(split[1]); float r = Float.parseFloat(split[2]); @@ -72,14 +73,14 @@ public class EmissiveItems implements IResourceManagerReloadListener { b *= i; entries.put(split[0] + "#" + dmg, new float[] { r, g, b }); continue; - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { } } logger.error("Skipping bad emissive item entry: {}", line); } } } - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Could not load list of emissive items!"); logger.error(t); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/IEEE754.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/IEEE754.java index 345fd5fe..4291465b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/IEEE754.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/IEEE754.java @@ -2,7 +2,8 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.texture; public class IEEE754 { - // source: https://stackoverflow.com/questions/6162651/half-precision-floating-point-in-java + // source: + // https://stackoverflow.com/questions/6162651/half-precision-floating-point-in-java public static int encodeHalfFloat(float fval) { int fbits = Float.floatToIntBits(fval); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/MetalsLUT.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/MetalsLUT.java index 77e739d0..a1c1cef0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/MetalsLUT.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/MetalsLUT.java @@ -1,5 +1,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.texture; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglTexParameteri; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_REPEAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_RGBA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MAG_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_S; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_WRAP_T; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -17,20 +27,18 @@ import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; - /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,9 +50,9 @@ public class MetalsLUT implements IResourceManagerReloadListener { private static int glTexture = -1; public static int getGLTexture() { - if(glTexture == -1) { + if (glTexture == -1) { float[] lut = new float[128]; - for(int i = 0, j; i < 16; ++i) { + for (int i = 0, j; i < 16; ++i) { j = i << 3; lut[i] = 1.0f; lut[i + 1] = 1.0f; @@ -63,14 +71,14 @@ public class MetalsLUT implements IResourceManagerReloadListener { String line; int cnt = 0; boolean firstLine = true; - while((line = reader.readLine()) != null) { - if((line = line.trim()).length() > 0) { - if(firstLine) { + while ((line = reader.readLine()) != null) { + if ((line = line.trim()).length() > 0) { + if (firstLine) { firstLine = false; continue; } String[] split = line.split(","); - if(split.length == 8) { + if (split.length == 8) { try { int id = Integer.parseInt(split[1]); float nr = Float.parseFloat(split[2]); @@ -79,9 +87,9 @@ public class MetalsLUT implements IResourceManagerReloadListener { float kr = Float.parseFloat(split[5]); float kg = Float.parseFloat(split[6]); float kb = Float.parseFloat(split[7]); - if(id < 230 || id > 245) { + if (id < 230 || id > 245) { logger.error("Error, only metal IDs 230 to 245 are configurable!"); - }else { + } else { int i = (id - 230) << 3; lut[i] = nr; lut[i + 1] = ng; @@ -92,7 +100,7 @@ public class MetalsLUT implements IResourceManagerReloadListener { } ++cnt; continue; - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { } } logger.error("Skipping bad metal constant entry: {}", line); @@ -104,10 +112,10 @@ public class MetalsLUT implements IResourceManagerReloadListener { logger.error("Failed to load PBR metal lookup table!"); logger.error(e); } - if(EaglercraftGPU.checkHDRFramebufferSupport(16)) { + if (EaglercraftGPU.checkHDRFramebufferSupport(16)) { ByteBuffer pixels = EagRuntime.allocateByteBuffer(256); - for(int i = 0; i < 128; ++i) { - pixels.putShort((short)IEEE754.encodeHalfFloat(lut[i])); + for (int i = 0; i < 128; ++i) { + pixels.putShort((short) IEEE754.encodeHalfFloat(lut[i])); } pixels.flip(); glTexture = GlStateManager.generateTexture(); @@ -115,10 +123,10 @@ public class MetalsLUT implements IResourceManagerReloadListener { setupFiltering(); EaglercraftGPU.createFramebufferHDR16FTexture(GL_TEXTURE_2D, 0, 2, 16, GL_RGBA, pixels); EagRuntime.freeByteBuffer(pixels); - }else if(EaglercraftGPU.checkHDRFramebufferSupport(32)) { + } else if (EaglercraftGPU.checkHDRFramebufferSupport(32)) { logger.warn("16-bit HDR textures are not supported, using 32-bit fallback format"); ByteBuffer pixels = EagRuntime.allocateByteBuffer(512); - for(int i = 0; i < 128; ++i) { + for (int i = 0; i < 128; ++i) { pixels.putFloat(lut[i]); } pixels.flip(); @@ -127,25 +135,26 @@ public class MetalsLUT implements IResourceManagerReloadListener { setupFiltering(); EaglercraftGPU.createFramebufferHDR32FTexture(GL_TEXTURE_2D, 0, 2, 16, GL_RGBA, pixels); EagRuntime.freeByteBuffer(pixels); - }else { - throw new UnsupportedOperationException("HDR textures are unavailable, could not create PBR metal definition LUT!"); + } else { + throw new UnsupportedOperationException( + "HDR textures are unavailable, could not create PBR metal definition LUT!"); } } return glTexture; } - @Override - public void onResourceManagerReload(IResourceManager var1) { - if(glTexture != -1) { - GlStateManager.deleteTexture(glTexture); - glTexture = -1; - } - } - private static void setupFiltering() { _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); _wglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } + + @Override + public void onResourceManagerReload(IResourceManager var1) { + if (glTexture != -1) { + GlStateManager.deleteTexture(glTexture); + glTexture = -1; + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRMaterialConstants.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRMaterialConstants.java index 88fc72e6..c7aaea76 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRMaterialConstants.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRMaterialConstants.java @@ -17,14 +17,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,7 +35,7 @@ public class PBRMaterialConstants implements IResourceManagerReloadListener { public static final Logger logger = LogManager.getLogger("PBRMaterialConstants"); public final ResourceLocation resourceLocation; - public final Map spriteNameToMaterialConstants = new HashMap<>(); + public final Map spriteNameToMaterialConstants = new HashMap<>(); public int defaultMaterial = 0x00000A77; @@ -44,40 +45,41 @@ public class PBRMaterialConstants implements IResourceManagerReloadListener { @Override public void onResourceManagerReload(IResourceManager var1) { - try(InputStream is = var1.getResource(resourceLocation).getInputStream()) { + try (InputStream is = var1.getResource(resourceLocation).getInputStream()) { spriteNameToMaterialConstants.clear(); BufferedReader bf = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); String line; boolean firstLine = true; - while((line = bf.readLine()) != null) { - if((line = line.trim()).length() == 0) { + while ((line = bf.readLine()) != null) { + if ((line = line.trim()).length() == 0) { continue; } - if(firstLine) { + if (firstLine) { firstLine = false; continue; } String[] cols = line.split(","); - if(cols.length == 4) { + if (cols.length == 4) { try { - int value = Integer.parseInt(cols[1]) | (Integer.parseInt(cols[2]) << 8) | (Integer.parseInt(cols[3]) << 16); - if(cols[0].equals("default")) { + int value = Integer.parseInt(cols[1]) | (Integer.parseInt(cols[2]) << 8) + | (Integer.parseInt(cols[3]) << 16); + if (cols[0].equals("default")) { defaultMaterial = value; - }else { + } else { Integer v = spriteNameToMaterialConstants.get(cols[0]); - if(v == null) { + if (v == null) { spriteNameToMaterialConstants.put(cols[0], value); - }else if(v.intValue() != value) { + } else if (v.intValue() != value) { logger.warn("Inconsistent material definition for sprite \"{}\": {}", cols[0], line); } } continue; - }catch(NumberFormatException fmt) { + } catch (NumberFormatException fmt) { } } logger.error("Skipping bad material constant entry: {}", line); } - }catch(IOException ex) { + } catch (IOException ex) { logger.error("Could not load \"{}\"!", resourceLocation.toString()); logger.error(ex); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRTextureMapUtils.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRTextureMapUtils.java index e29938ff..8844ec64 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRTextureMapUtils.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/PBRTextureMapUtils.java @@ -13,14 +13,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,110 +30,19 @@ public class PBRTextureMapUtils { public static final ImageData defaultNormalsTexture = new ImageData(1, 1, new int[] { 0 }, true); - public static final PBRMaterialConstants blockMaterialConstants = new PBRMaterialConstants(new ResourceLocation("eagler:glsl/deferred/material_block_constants.csv")); + public static final PBRMaterialConstants blockMaterialConstants = new PBRMaterialConstants( + new ResourceLocation("eagler:glsl/deferred/material_block_constants.csv")); public static final Logger logger = LogManager.getLogger("PBRTextureMap"); - public static ImageData locateCompanionTexture(IResourceManager resMgr, IResource mainImage, String ext) { - ResourceLocation baseLocation = mainImage.getResourceLocation(); - String domain = baseLocation.getResourceDomain(); - String resourcePack = mainImage.getResourcePackName(); - String fname = baseLocation.getResourcePath(); - int idx = fname.lastIndexOf('.'); - if(idx != -1) { - fname = fname.substring(0, idx) + ext + fname.substring(idx); - }else { - fname += ext; - } - try { - List ress = resMgr.getAllResources(new ResourceLocation(domain, fname)); - for(int k = 0, l = ress.size(); k < l; ++k) { - IResource res = ress.get(k); - if(res.getResourcePackName().equals(resourcePack)) { - ImageData toRet = TextureUtil.readBufferedImage(res.getInputStream()); - if(ext.equals("_s")) { - for(int i = 0, j; i < toRet.pixels.length; ++i) { - // swap B and A, because labPBR support - int a = (toRet.pixels[i] >>> 24) & 0xFF; - if(a == 0xFF) a = 0; - toRet.pixels[i] = (toRet.pixels[i] & 0x0000FFFF) | Math.min(a << 18, 0xFF0000) | 0xFF000000; - } - } - return toRet; - } - } - }catch(Throwable t) { - } - if("Default".equals(resourcePack)) { - idx = fname.lastIndexOf('.'); - if(idx != -1) { - fname = fname.substring(0, idx); - } - try { - return TextureUtil.readBufferedImage(resMgr.getResource(new ResourceLocation("eagler:glsl/deferred/assets_pbr/" + fname + ".png")).getInputStream()); - }catch(Throwable t) { - } - try { - return EaglerBitwisePackedTexture.loadTextureSafe(resMgr.getResource(new ResourceLocation("eagler:glsl/deferred/assets_pbr/" + fname + ".ebp")).getInputStream(), 255); - }catch(Throwable t) { - // dead code because teavm - t.toString(); - } - } - return null; - } - - public static void unifySizes(int lvl, ImageData[]... imageSets) { - int resX = -1; - int resY = -1; - int iw, ih; - for(int i = 0; i < imageSets.length; ++i) { - iw = imageSets[i][lvl].width; - ih = imageSets[i][lvl].height; - if(iw != ih) { - } - if(iw > resX) { - resX = iw; - } - if(ih > resY) { - resY = ih; - } - } - if(resX == -1 || resY == -1) { - throw new IllegalArgumentException("No images were provided!"); - } - for(int i = 0; i < imageSets.length; ++i) { - ImageData in = imageSets[i][lvl]; - ImageData out = null; - if(in.width != resX || in.height != resY) { - out = new ImageData(resX, resY, true); - if(in.width == 1 && in.height == 1) { - int px = in.pixels[0]; - for(int j = 0; j < out.pixels.length; ++j) { - out.pixels[j] = px; - } - }else { - for(int y = 0; y < resY; ++y) { - for(int x = 0; x < resX; ++x) { - out.pixels[y * resX + x] = in.pixels[((y * in.height / resY)) * in.width + (x * in.width / resX)]; - } - } - } - } - if(out != null) { - imageSets[i][lvl] = out; - } - } - } - public static ImageData generateMaterialTextureFor(String iconName) { - if(iconName.startsWith("minecraft:")) { + if (iconName.startsWith("minecraft:")) { iconName = iconName.substring(10); } Integer in = blockMaterialConstants.spriteNameToMaterialConstants.get(iconName); - if(in == null) { + if (in == null) { return new ImageData(1, 1, new int[] { blockMaterialConstants.defaultMaterial }, true); - }else { + } else { return new ImageData(1, 1, new int[] { in.intValue() }, true); } } @@ -141,15 +51,15 @@ public class PBRTextureMapUtils { int[][] ret = new int[level + 1][]; ret[0] = aint[0]; if (level > 0) { - for(int i = 1; i <= level; ++i) { - if(aint[i] != null) { + for (int i = 1; i <= level; ++i) { + if (aint[i] != null) { ret[i] = aint[i]; - }else { + } else { int lvlW = width >> i, lvl2W = lvlW << 1; int len = lvlW * lvlW; ret[i] = new int[len]; int x, y, s1, s2, s3, s4, c1, c2, c3, c4; - for(int j = 0; j < len; ++j) { + for (int j = 0; j < len; ++j) { x = (j % len) << 1; y = (j / len) << 1; s1 = ret[i - 1][x + y * lvl2W]; @@ -168,4 +78,103 @@ public class PBRTextureMapUtils { return ret; } + public static ImageData locateCompanionTexture(IResourceManager resMgr, IResource mainImage, String ext) { + ResourceLocation baseLocation = mainImage.getResourceLocation(); + String domain = baseLocation.getResourceDomain(); + String resourcePack = mainImage.getResourcePackName(); + String fname = baseLocation.getResourcePath(); + int idx = fname.lastIndexOf('.'); + if (idx != -1) { + fname = fname.substring(0, idx) + ext + fname.substring(idx); + } else { + fname += ext; + } + try { + List ress = resMgr.getAllResources(new ResourceLocation(domain, fname)); + for (int k = 0, l = ress.size(); k < l; ++k) { + IResource res = ress.get(k); + if (res.getResourcePackName().equals(resourcePack)) { + ImageData toRet = TextureUtil.readBufferedImage(res.getInputStream()); + if (ext.equals("_s")) { + for (int i = 0, j; i < toRet.pixels.length; ++i) { + // swap B and A, because labPBR support + int a = (toRet.pixels[i] >>> 24) & 0xFF; + if (a == 0xFF) + a = 0; + toRet.pixels[i] = (toRet.pixels[i] & 0x0000FFFF) | Math.min(a << 18, 0xFF0000) | 0xFF000000; + } + } + return toRet; + } + } + } catch (Throwable t) { + } + if ("Default".equals(resourcePack)) { + idx = fname.lastIndexOf('.'); + if (idx != -1) { + fname = fname.substring(0, idx); + } + try { + return TextureUtil.readBufferedImage( + resMgr.getResource(new ResourceLocation("eagler:glsl/deferred/assets_pbr/" + fname + ".png")) + .getInputStream()); + } catch (Throwable t) { + } + try { + return EaglerBitwisePackedTexture.loadTextureSafe( + resMgr.getResource(new ResourceLocation("eagler:glsl/deferred/assets_pbr/" + fname + ".ebp")) + .getInputStream(), + 255); + } catch (Throwable t) { + // dead code because teavm + t.toString(); + } + } + return null; + } + + public static void unifySizes(int lvl, ImageData[]... imageSets) { + int resX = -1; + int resY = -1; + int iw, ih; + for (int i = 0; i < imageSets.length; ++i) { + iw = imageSets[i][lvl].width; + ih = imageSets[i][lvl].height; + if (iw != ih) { + } + if (iw > resX) { + resX = iw; + } + if (ih > resY) { + resY = ih; + } + } + if (resX == -1 || resY == -1) { + throw new IllegalArgumentException("No images were provided!"); + } + for (int i = 0; i < imageSets.length; ++i) { + ImageData in = imageSets[i][lvl]; + ImageData out = null; + if (in.width != resX || in.height != resY) { + out = new ImageData(resX, resY, true); + if (in.width == 1 && in.height == 1) { + int px = in.pixels[0]; + for (int j = 0; j < out.pixels.length; ++j) { + out.pixels[j] = px; + } + } else { + for (int y = 0; y < resY; ++y) { + for (int x = 0; x < resX; ++x) { + out.pixels[y * resX + x] = in.pixels[((y * in.height / resY)) * in.width + + (x * in.width / resX)]; + } + } + } + } + if (out != null) { + imageSets[i][lvl] = out; + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TemperaturesLUT.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TemperaturesLUT.java index 10c71389..3b251669 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TemperaturesLUT.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TemperaturesLUT.java @@ -13,14 +13,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,17 +32,37 @@ public class TemperaturesLUT implements IResourceManagerReloadListener { public static final float[][] colorTemperatureLUT = new float[390][3]; + public static float[] getColorTemperature(int kelvin) { + if (kelvin < 1000) + kelvin = 1000; + if (kelvin > 39000) + kelvin = 39000; + int k = ((kelvin - 100) / 100); + return colorTemperatureLUT[k]; + } + + public static void getColorTemperature(int kelvin, float[] ret) { + if (kelvin < 1000) + kelvin = 1000; + if (kelvin > 39000) + kelvin = 39000; + int k = ((kelvin - 100) / 100); + ret[0] = colorTemperatureLUT[k][0]; + ret[1] = colorTemperatureLUT[k][1]; + ret[2] = colorTemperatureLUT[k][2]; + } + @Override public void onResourceManagerReload(IResourceManager var1) { try { IResource res = var1.getResource(new ResourceLocation("eagler:glsl/deferred/temperatures.lut")); - try(InputStream is = res.getInputStream()) { - for(int i = 0; i < 390; ++i) { - colorTemperatureLUT[i][0] = ((int)is.read() & 0xFF) * 0.0039216f; + try (InputStream is = res.getInputStream()) { + for (int i = 0; i < 390; ++i) { + colorTemperatureLUT[i][0] = ((int) is.read() & 0xFF) * 0.0039216f; colorTemperatureLUT[i][0] *= colorTemperatureLUT[i][0]; - colorTemperatureLUT[i][1] = ((int)is.read() & 0xFF) * 0.0039216f; + colorTemperatureLUT[i][1] = ((int) is.read() & 0xFF) * 0.0039216f; colorTemperatureLUT[i][1] *= colorTemperatureLUT[i][1]; - colorTemperatureLUT[i][2] = ((int)is.read() & 0xFF) * 0.0039216f; + colorTemperatureLUT[i][2] = ((int) is.read() & 0xFF) * 0.0039216f; colorTemperatureLUT[i][2] *= colorTemperatureLUT[i][2]; } } @@ -51,20 +72,4 @@ public class TemperaturesLUT implements IResourceManagerReloadListener { } } - public static float[] getColorTemperature(int kelvin) { - if (kelvin < 1000) kelvin = 1000; - if (kelvin > 39000) kelvin = 39000; - int k = ((kelvin - 100) / 100); - return colorTemperatureLUT[k]; - } - - public static void getColorTemperature(int kelvin, float[] ret) { - if (kelvin < 1000) kelvin = 1000; - if (kelvin > 39000) kelvin = 39000; - int k = ((kelvin - 100) / 100); - ret[0] = colorTemperatureLUT[k][0]; - ret[1] = colorTemperatureLUT[k][1]; - ret[2] = colorTemperatureLUT[k][2]; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureClockPBRImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureClockPBRImpl.java index 620ad6d8..cb4988ec 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureClockPBRImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureClockPBRImpl.java @@ -7,14 +7,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,7 +28,8 @@ public class TextureClockPBRImpl extends EaglerTextureAtlasSpritePBR { super(spriteName); } - public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, int materialTexOffset) { + public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, + int materialTexOffset) { if (!this.frameTextureDataPBR[0].isEmpty()) { Minecraft minecraft = Minecraft.getMinecraft(); double d0 = 0.0; @@ -53,7 +55,8 @@ public class TextureClockPBRImpl extends EaglerTextureAtlasSpritePBR { this.smoothParam1 += this.smoothParam2; int i, frameCount = this.frameTextureDataPBR[0].size(); - for (i = (int) ((this.smoothParam1 + 1.0) * frameCount) % frameCount; i < 0; i = (i + frameCount) % frameCount) { + for (i = (int) ((this.smoothParam1 + 1.0) * frameCount) % frameCount; i < 0; i = (i + frameCount) + % frameCount) { ; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureCompassPBRImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureCompassPBRImpl.java index b4ac23a2..27986dcd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureCompassPBRImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/deferred/texture/TextureCompassPBRImpl.java @@ -9,14 +9,15 @@ import net.minecraft.world.World; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,13 +30,16 @@ public class TextureCompassPBRImpl extends EaglerTextureAtlasSpritePBR { super(spriteName); } - public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, int materialOffset) { + public void updateAnimationPBR(IFramebufferGL[] copyColorFramebuffer, IFramebufferGL[] copyMaterialFramebuffer, + int materialOffset) { Minecraft minecraft = Minecraft.getMinecraft(); if (minecraft.theWorld != null && minecraft.thePlayer != null) { this.updateCompassPBR(minecraft.theWorld, minecraft.thePlayer.posX, minecraft.thePlayer.posZ, - (double) minecraft.thePlayer.rotationYaw, false, copyColorFramebuffer, copyMaterialFramebuffer, materialOffset); + (double) minecraft.thePlayer.rotationYaw, false, copyColorFramebuffer, copyMaterialFramebuffer, + materialOffset); } else { - this.updateCompassPBR((World) null, 0.0, 0.0, 0.0, true, copyColorFramebuffer, copyMaterialFramebuffer, materialOffset); + this.updateCompassPBR((World) null, 0.0, 0.0, 0.0, true, copyColorFramebuffer, copyMaterialFramebuffer, + materialOffset); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightBucketLoader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightBucketLoader.java index 5a17d1f8..2f4b90f2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightBucketLoader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightBucketLoader.java @@ -1,8 +1,12 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DYNAMIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.ExtGLEnums._GL_UNIFORM_BUFFER; import java.util.Comparator; import java.util.List; @@ -19,41 +23,46 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DynamicLightBucketLoader { + public static final int MAX_LIGHTS_PER_CHUNK = 12; + public static final int LIGHTING_BUFFER_LENGTH = 16 * MAX_LIGHTS_PER_CHUNK + 16; + private static final Comparator comparatorLightRadius = (l1, l2) -> { + return l1.radius < l2.radius ? 1 : -1; + }; public IBufferGL buffer_chunkLightingData; + public IBufferGL buffer_chunkLightingDataZero; private ByteBuffer chunkLightingDataCopyBuffer; public ListSerial currentBoundLightSourceBucket; - public final ListSerial[] lightSourceBuckets; private final int[] lightSourceBucketsSerials; private final int[] lightSourceRenderPosSerials; + public ListSerial currentLightSourceBucket; private int currentLightSourceBucketId = -1; + private int lightingBufferSliceLength = -1; - - public static final int MAX_LIGHTS_PER_CHUNK = 12; - public static final int LIGHTING_BUFFER_LENGTH = 16 * MAX_LIGHTS_PER_CHUNK + 16; - private final int lightSourceBucketsWidth; - private final int lightSourceBucketsHeight; + private final int lightSourceBucketsHeight; private double currentRenderX = 0.0; private double currentRenderY = 0.0; private double currentRenderZ = 0.0; + private int currentRenderPosSerial = 0; public DynamicLightBucketLoader() { @@ -65,37 +74,10 @@ public class DynamicLightBucketLoader { this.lightSourceRenderPosSerials = new int[cnt]; } - public void initialize() { - destroy(); - - int alignment = EaglercraftGPU.getUniformBufferOffsetAlignment(); - lightingBufferSliceLength = MathHelper.ceiling_float_int((float)LIGHTING_BUFFER_LENGTH / (float)alignment) * alignment; - - chunkLightingDataCopyBuffer = EagRuntime.allocateByteBuffer(LIGHTING_BUFFER_LENGTH); - for(int i = 0; i < LIGHTING_BUFFER_LENGTH; i += 4) { - chunkLightingDataCopyBuffer.putInt(0); - } - chunkLightingDataCopyBuffer.flip(); - - buffer_chunkLightingData = _wglGenBuffers(); - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); - int cnt = lightSourceBucketsWidth * lightSourceBucketsHeight * lightSourceBucketsWidth; - _wglBufferData(_GL_UNIFORM_BUFFER, cnt * lightingBufferSliceLength, GL_DYNAMIC_DRAW); - - buffer_chunkLightingDataZero = _wglGenBuffers(); - EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); - _wglBufferData(_GL_UNIFORM_BUFFER, chunkLightingDataCopyBuffer, GL_STATIC_DRAW); - - for(int i = 0; i < this.lightSourceBuckets.length; ++i) { - this.lightSourceBuckets[i] = new ArrayListSerial<>(16); - this.lightSourceBucketsSerials[i] = -1; - this.lightSourceRenderPosSerials[i] = -1; - } - } - - public void clearBuckets() { - for(int i = 0; i < this.lightSourceBuckets.length; ++i) { - this.lightSourceBuckets[i].clear(); + public void addLightSourceToBucket(int cx, int cy, int cz, DynamicLightInstance dl) { + ListSerial lst = getLightSourceBucketRelativeChunkCoords(cx, cy, cz); + if (lst != null) { + lst.add(dl); } } @@ -105,44 +87,46 @@ public class DynamicLightBucketLoader { int bucketX = (relativeBlockX >> 4) + hw; int bucketY = (relativeBlockY >> 4) + hh; int bucketZ = (relativeBlockZ >> 4) + hw; - if(bucketX >= 0 && bucketY >= 0 && bucketZ >= 0 && bucketX < lightSourceBucketsWidth + if (bucketX >= 0 && bucketY >= 0 && bucketZ >= 0 && bucketX < lightSourceBucketsWidth && bucketY < lightSourceBucketsHeight && bucketZ < lightSourceBucketsWidth) { currentLightSourceBucketId = bucketY * lightSourceBucketsWidth * lightSourceBucketsWidth + bucketZ * lightSourceBucketsWidth + bucketX; currentLightSourceBucket = lightSourceBuckets[currentLightSourceBucketId]; int ser = currentLightSourceBucket.getEaglerSerial(); int max = currentLightSourceBucket.size(); - if(max > 0) { + if (max > 0) { EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); int offset = currentLightSourceBucketId * lightingBufferSliceLength; if (lightSourceBucketsSerials[currentLightSourceBucketId] != ser || lightSourceRenderPosSerials[currentLightSourceBucketId] != currentRenderPosSerial) { lightSourceBucketsSerials[currentLightSourceBucketId] = ser; lightSourceRenderPosSerials[currentLightSourceBucketId] = currentRenderPosSerial; - if(max > MAX_LIGHTS_PER_CHUNK) { + if (max > MAX_LIGHTS_PER_CHUNK) { max = MAX_LIGHTS_PER_CHUNK; } chunkLightingDataCopyBuffer.clear(); chunkLightingDataCopyBuffer.putInt(max); - chunkLightingDataCopyBuffer.putInt(0); //padding - chunkLightingDataCopyBuffer.putInt(0); //padding - chunkLightingDataCopyBuffer.putInt(0); //padding - for(int i = 0; i < max; ++i) { + chunkLightingDataCopyBuffer.putInt(0); // padding + chunkLightingDataCopyBuffer.putInt(0); // padding + chunkLightingDataCopyBuffer.putInt(0); // padding + for (int i = 0; i < max; ++i) { DynamicLightInstance dl = currentLightSourceBucket.get(i); - chunkLightingDataCopyBuffer.putFloat((float)(dl.posX - currentRenderX)); - chunkLightingDataCopyBuffer.putFloat((float)(dl.posY - currentRenderY)); - chunkLightingDataCopyBuffer.putFloat((float)(dl.posZ - currentRenderZ)); + chunkLightingDataCopyBuffer.putFloat((float) (dl.posX - currentRenderX)); + chunkLightingDataCopyBuffer.putFloat((float) (dl.posY - currentRenderY)); + chunkLightingDataCopyBuffer.putFloat((float) (dl.posZ - currentRenderZ)); chunkLightingDataCopyBuffer.putFloat(dl.radius); } chunkLightingDataCopyBuffer.flip(); _wglBufferSubData(_GL_UNIFORM_BUFFER, offset, chunkLightingDataCopyBuffer); } - EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingData, offset, LIGHTING_BUFFER_LENGTH); - }else { + EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingData, offset, + LIGHTING_BUFFER_LENGTH); + } else { EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); - EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingDataZero, 0, LIGHTING_BUFFER_LENGTH); + EaglercraftGPU.bindUniformBufferRange(uboIndex, buffer_chunkLightingDataZero, 0, + LIGHTING_BUFFER_LENGTH); } - }else { + } else { currentLightSourceBucketId = -1; currentLightSourceBucket = null; EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); @@ -150,28 +134,6 @@ public class DynamicLightBucketLoader { } } - public ListSerial getLightSourceBucketRelativeChunkCoords(int cx, int cy, int cz) { - int hw = lightSourceBucketsWidth / 2; - int hh = lightSourceBucketsHeight / 2; - cx += hw; - cy += hh; - cz += hw; - if(cx < 0 || cx >= lightSourceBucketsWidth || cy < 0 || cy >= lightSourceBucketsHeight || cz < 0 - || cz >= lightSourceBucketsWidth) { - return null; - }else { - return lightSourceBuckets[cy * lightSourceBucketsWidth * lightSourceBucketsWidth - + cz * lightSourceBucketsWidth + cx]; - } - } - - public void addLightSourceToBucket(int cx, int cy, int cz, DynamicLightInstance dl) { - ListSerial lst = getLightSourceBucketRelativeChunkCoords(cx, cy, cz); - if(lst != null) { - lst.add(dl); - } - } - public void bucketLightSource(float x, float y, float z, DynamicLightInstance dl) { int bucketX = MathHelper.floor_float(x / 16.0f); int bucketY = MathHelper.floor_float(y / 16.0f); @@ -185,48 +147,48 @@ public class DynamicLightBucketLoader { float lightLocalZ = z - (bucketZ << 4); float radius = dl.radius; boolean outOfBounds = false; - if(lightLocalX - radius < 0.0f) { + if (lightLocalX - radius < 0.0f) { minX -= 1; outOfBounds = true; addLightSourceToBucket(bucketX - 1, bucketY, bucketZ, dl); } - if(lightLocalY - radius < 0.0f) { + if (lightLocalY - radius < 0.0f) { minY -= 1; outOfBounds = true; addLightSourceToBucket(bucketX, bucketY - 1, bucketZ, dl); } - if(lightLocalZ - radius < 0.0f) { + if (lightLocalZ - radius < 0.0f) { minZ -= 1; outOfBounds = true; addLightSourceToBucket(bucketX, bucketY, bucketZ - 1, dl); } - if(lightLocalX + radius >= 16.0f) { + if (lightLocalX + radius >= 16.0f) { maxX += 1; outOfBounds = true; addLightSourceToBucket(bucketX + 1, bucketY, bucketZ, dl); } - if(lightLocalY + radius >= 16.0f) { + if (lightLocalY + radius >= 16.0f) { maxY += 1; outOfBounds = true; addLightSourceToBucket(bucketX, bucketY + 1, bucketZ, dl); } - if(lightLocalZ + radius >= 16.0f) { + if (lightLocalZ + radius >= 16.0f) { maxZ += 1; outOfBounds = true; addLightSourceToBucket(bucketX, bucketY, bucketZ + 1, dl); } - if(!outOfBounds) { + if (!outOfBounds) { return; } radius *= radius; - for(int yy = minY; yy <= maxY; ++yy) { - for(int zz = minZ; zz <= maxZ; ++zz) { - for(int xx = minX; xx <= maxX; ++xx) { - if((xx == bucketX ? 1 : 0) + (yy == bucketY ? 1 : 0) + (zz == bucketZ ? 1 : 0) > 1) { + for (int yy = minY; yy <= maxY; ++yy) { + for (int zz = minZ; zz <= maxZ; ++zz) { + for (int xx = minX; xx <= maxX; ++xx) { + if ((xx == bucketX ? 1 : 0) + (yy == bucketY ? 1 : 0) + (zz == bucketZ ? 1 : 0) > 1) { continue; } List lst = getLightSourceBucketRelativeChunkCoords(xx, yy, zz); - if(lst != null) { + if (lst != null) { int bucketBoundsX = xx << 4; int bucketBoundsY = yy << 4; int bucketBoundsZ = zz << 4; @@ -240,22 +202,77 @@ public class DynamicLightBucketLoader { } } - public void truncateOverflowingBuffers() { - for(int i = 0; i < lightSourceBuckets.length; ++i) { - List lst = lightSourceBuckets[i]; - int k = lst.size(); - if(k > MAX_LIGHTS_PER_CHUNK) { - lst.sort(comparatorLightRadius); - for(int l = MAX_LIGHTS_PER_CHUNK - 1; l >= MAX_LIGHTS_PER_CHUNK; --l) { - lst.remove(l); - } - } + public void clearBuckets() { + for (int i = 0; i < this.lightSourceBuckets.length; ++i) { + this.lightSourceBuckets[i].clear(); } } - private static final Comparator comparatorLightRadius = (l1, l2) -> { - return l1.radius < l2.radius ? 1 : -1; - }; + public void destroy() { + if (chunkLightingDataCopyBuffer != null) { + EagRuntime.freeByteBuffer(chunkLightingDataCopyBuffer); + chunkLightingDataCopyBuffer = null; + } + if (buffer_chunkLightingData != null) { + _wglDeleteBuffers(buffer_chunkLightingData); + buffer_chunkLightingData = null; + } + if (buffer_chunkLightingDataZero != null) { + _wglDeleteBuffers(buffer_chunkLightingDataZero); + buffer_chunkLightingDataZero = null; + } + for (int i = 0; i < lightSourceBuckets.length; ++i) { + lightSourceBuckets[i] = null; + lightSourceBucketsSerials[i] = -1; + lightSourceRenderPosSerials[i] = -1; + } + currentLightSourceBucket = null; + currentLightSourceBucketId = -1; + } + + public ListSerial getLightSourceBucketRelativeChunkCoords(int cx, int cy, int cz) { + int hw = lightSourceBucketsWidth / 2; + int hh = lightSourceBucketsHeight / 2; + cx += hw; + cy += hh; + cz += hw; + if (cx < 0 || cx >= lightSourceBucketsWidth || cy < 0 || cy >= lightSourceBucketsHeight || cz < 0 + || cz >= lightSourceBucketsWidth) { + return null; + } else { + return lightSourceBuckets[cy * lightSourceBucketsWidth * lightSourceBucketsWidth + + cz * lightSourceBucketsWidth + cx]; + } + } + + public void initialize() { + destroy(); + + int alignment = EaglercraftGPU.getUniformBufferOffsetAlignment(); + lightingBufferSliceLength = MathHelper.ceiling_float_int((float) LIGHTING_BUFFER_LENGTH / (float) alignment) + * alignment; + + chunkLightingDataCopyBuffer = EagRuntime.allocateByteBuffer(LIGHTING_BUFFER_LENGTH); + for (int i = 0; i < LIGHTING_BUFFER_LENGTH; i += 4) { + chunkLightingDataCopyBuffer.putInt(0); + } + chunkLightingDataCopyBuffer.flip(); + + buffer_chunkLightingData = _wglGenBuffers(); + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingData); + int cnt = lightSourceBucketsWidth * lightSourceBucketsHeight * lightSourceBucketsWidth; + _wglBufferData(_GL_UNIFORM_BUFFER, cnt * lightingBufferSliceLength, GL_DYNAMIC_DRAW); + + buffer_chunkLightingDataZero = _wglGenBuffers(); + EaglercraftGPU.bindGLUniformBuffer(buffer_chunkLightingDataZero); + _wglBufferData(_GL_UNIFORM_BUFFER, chunkLightingDataCopyBuffer, GL_STATIC_DRAW); + + for (int i = 0; i < this.lightSourceBuckets.length; ++i) { + this.lightSourceBuckets[i] = new ArrayListSerial<>(16); + this.lightSourceBucketsSerials[i] = -1; + this.lightSourceRenderPosSerials[i] = -1; + } + } public void setRenderPos(double currentRenderX, double currentRenderY, double currentRenderZ) { if (this.currentRenderX != currentRenderX || this.currentRenderY != currentRenderY @@ -267,25 +284,16 @@ public class DynamicLightBucketLoader { } } - public void destroy() { - if(chunkLightingDataCopyBuffer != null) { - EagRuntime.freeByteBuffer(chunkLightingDataCopyBuffer); - chunkLightingDataCopyBuffer = null; + public void truncateOverflowingBuffers() { + for (int i = 0; i < lightSourceBuckets.length; ++i) { + List lst = lightSourceBuckets[i]; + int k = lst.size(); + if (k > MAX_LIGHTS_PER_CHUNK) { + lst.sort(comparatorLightRadius); + for (int l = MAX_LIGHTS_PER_CHUNK - 1; l >= MAX_LIGHTS_PER_CHUNK; --l) { + lst.remove(l); + } + } } - if(buffer_chunkLightingData != null) { - _wglDeleteBuffers(buffer_chunkLightingData); - buffer_chunkLightingData = null; - } - if(buffer_chunkLightingDataZero != null) { - _wglDeleteBuffers(buffer_chunkLightingDataZero); - buffer_chunkLightingDataZero = null; - } - for(int i = 0; i < lightSourceBuckets.length; ++i) { - lightSourceBuckets[i] = null; - lightSourceBucketsSerials[i] = -1; - lightSourceRenderPosSerials[i] = -1; - } - currentLightSourceBucket = null; - currentLightSourceBucketId = -1; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightInstance.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightInstance.java index e6b388aa..f00b20ea 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightInstance.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightInstance.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,6 +26,10 @@ class DynamicLightInstance { public DynamicLightInstance() { } + public float getRadiusInWorld() { + return radius; + } + public void updateLight(double posX, double posY, double posZ, float radius) { this.posX = posX; this.posY = posY; @@ -32,8 +37,4 @@ class DynamicLightInstance { this.radius = radius; } - public float getRadiusInWorld() { - return radius; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsAcceleratedEffectRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsAcceleratedEffectRenderer.java index cc380163..a7722042 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsAcceleratedEffectRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsAcceleratedEffectRenderer.java @@ -1,7 +1,27 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglBufferSubData; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDeleteVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglDrawArraysInstanced; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglEnableVertexAttribArray; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenBuffers; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGenVertexArrays; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform2f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform3f; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribDivisor; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglVertexAttribPointer; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ARRAY_BUFFER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FLOAT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_MODELVIEW_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_PROJECTION_MATRIX; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STATIC_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_STREAM_DRAW; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TRIANGLES; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_BYTE; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_UNSIGNED_SHORT; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.IBufferArrayGL; @@ -23,14 +43,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,93 +60,75 @@ public class DynamicLightsAcceleratedEffectRenderer extends AbstractAcceleratedE private static final Logger logger = LogManager.getLogger("DynamicLightsAcceleratedEffectRenderer"); - private ByteBuffer particleBuffer = null; - private int particleCount = 0; - private boolean particlesHasOverflowed = false; - private static final int BYTES_PER_PARTICLE = 24; private static final int PARTICLE_LIMIT = 5461; + public static boolean isMaterialNormalTexture = false; + + private ByteBuffer particleBuffer = null; + private int particleCount = 0; + + private boolean particlesHasOverflowed = false; private DynamicLightsAccelParticleShader shaderProgram = null; - private IBufferArrayGL vertexArray = null; + private IBufferGL vertexBuffer = null; private IBufferGL instancesBuffer = null; - private float f1; private float f2; private float f3; private float f4; + private float f5; - public static boolean isMaterialNormalTexture = false; + @Override + public void begin(float partialTicks) { + this.partialTicks = partialTicks; - public void initialize() { - destroy(); + particleBuffer.clear(); + particleCount = 0; + particlesHasOverflowed = false; - if(DynamicLightsPipelineCompiler.matrixCopyBuffer == null) { - DynamicLightsPipelineCompiler.matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); + Entity et = Minecraft.getMinecraft().getRenderViewEntity(); + if (et != null) { + f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); + f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); + f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); + f4 = f1 * MathHelper.sin(et.rotationPitch * 0.017453292F); + f5 = MathHelper.cos(et.rotationPitch * 0.017453292F); } + } - shaderProgram = DynamicLightsAccelParticleShader.compile(); - shaderProgram.loadUniforms(); - - particleBuffer = EagRuntime.allocateByteBuffer(PARTICLE_LIMIT * BYTES_PER_PARTICLE); - - vertexArray = _wglGenVertexArrays(); - vertexBuffer = _wglGenBuffers(); - instancesBuffer = _wglGenBuffers(); - - FloatBuffer verts = EagRuntime.allocateFloatBuffer(12); - verts.put(new float[] { - -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, - -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f - }); - verts.flip(); - - EaglercraftGPU.bindGLBufferArray(vertexArray); - - EaglercraftGPU.bindGLArrayBuffer(vertexBuffer); - _wglBufferData(GL_ARRAY_BUFFER, verts, GL_STATIC_DRAW); - - EagRuntime.freeFloatBuffer(verts); - - _wglEnableVertexAttribArray(0); - _wglVertexAttribPointer(0, 2, GL_FLOAT, false, 8, 0); - _wglVertexAttribDivisor(0, 0); - - EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); - _wglBufferData(GL_ARRAY_BUFFER, particleBuffer.remaining(), GL_STREAM_DRAW); - - _wglEnableVertexAttribArray(1); - _wglVertexAttribPointer(1, 3, GL_FLOAT, false, 24, 0); - _wglVertexAttribDivisor(1, 1); - - _wglEnableVertexAttribArray(2); - _wglVertexAttribPointer(2, 2, GL_UNSIGNED_SHORT, false, 24, 12); - _wglVertexAttribDivisor(2, 1); - - _wglEnableVertexAttribArray(3); - _wglVertexAttribPointer(3, 2, GL_UNSIGNED_BYTE, true, 24, 16); - _wglVertexAttribDivisor(3, 1); - - _wglEnableVertexAttribArray(4); - _wglVertexAttribPointer(4, 2, GL_UNSIGNED_BYTE, false, 24, 18); - _wglVertexAttribDivisor(4, 1); - - _wglEnableVertexAttribArray(5); - _wglVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, true, 24, 20); - _wglVertexAttribDivisor(5, 1); - + public void destroy() { + if (particleBuffer != null) { + EagRuntime.freeByteBuffer(particleBuffer); + particleBuffer = null; + } + if (shaderProgram != null) { + shaderProgram.destroy(); + shaderProgram = null; + } + if (vertexArray != null) { + _wglDeleteVertexArrays(vertexArray); + vertexArray = null; + } + if (vertexBuffer != null) { + _wglDeleteBuffers(vertexBuffer); + vertexBuffer = null; + } + if (instancesBuffer != null) { + _wglDeleteBuffers(instancesBuffer); + instancesBuffer = null; + } } @Override public void draw(float texCoordWidth, float texCoordHeight) { - if(particleCount == 0) { + if (particleCount == 0) { return; } - + shaderProgram.useProgram(); _wglUniform3f(shaderProgram.uniforms.u_texCoordSize2f_particleSize1f, texCoordWidth, texCoordHeight, 0.0625f); @@ -162,33 +165,16 @@ public class DynamicLightsAcceleratedEffectRenderer extends AbstractAcceleratedE _wglDrawArraysInstanced(GL_TRIANGLES, 0, 6, particleCount); } - @Override - public void begin(float partialTicks) { - this.partialTicks = partialTicks; - - particleBuffer.clear(); - particleCount = 0; - particlesHasOverflowed = false; - - Entity et = Minecraft.getMinecraft().getRenderViewEntity(); - if(et != null) { - f1 = MathHelper.cos(et.rotationYaw * 0.017453292F); - f2 = MathHelper.sin(et.rotationYaw * 0.017453292F); - f3 = -f2 * MathHelper.sin(et.rotationPitch * 0.017453292F); - f4 = f1 * MathHelper.sin(et.rotationPitch * 0.017453292F); - f5 = MathHelper.cos(et.rotationPitch * 0.017453292F); - } - } - @Override public void drawParticle(float posX, float posY, float posZ, int particleIndexX, int particleIndexY, int lightMapData, int texSize, float particleSize, int rgba) { - if(particlesHasOverflowed) { + if (particlesHasOverflowed) { return; } - if(particleCount >= PARTICLE_LIMIT) { + if (particleCount >= PARTICLE_LIMIT) { particlesHasOverflowed = true; - logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", PARTICLE_LIMIT); + logger.error("Particle buffer has overflowed! Exceeded {} particles, no more particles will be rendered.", + PARTICLE_LIMIT); return; } ++particleCount; @@ -196,35 +182,68 @@ public class DynamicLightsAcceleratedEffectRenderer extends AbstractAcceleratedE buf.putFloat(posX); buf.putFloat(posY); buf.putFloat(posZ); - buf.putShort((short)particleIndexX); - buf.putShort((short)particleIndexY); - buf.put((byte)(lightMapData & 0xFF)); - buf.put((byte)((lightMapData >> 16) & 0xFF)); - buf.put((byte)(particleSize * 16.0f)); - buf.put((byte)texSize); + buf.putShort((short) particleIndexX); + buf.putShort((short) particleIndexY); + buf.put((byte) (lightMapData & 0xFF)); + buf.put((byte) ((lightMapData >> 16) & 0xFF)); + buf.put((byte) (particleSize * 16.0f)); + buf.put((byte) texSize); buf.putInt(rgba); } - public void destroy() { - if(particleBuffer != null) { - EagRuntime.freeByteBuffer(particleBuffer); - particleBuffer = null; - } - if(shaderProgram != null) { - shaderProgram.destroy(); - shaderProgram = null; - } - if(vertexArray != null) { - _wglDeleteVertexArrays(vertexArray); - vertexArray = null; - } - if(vertexBuffer != null) { - _wglDeleteBuffers(vertexBuffer); - vertexBuffer = null; - } - if(instancesBuffer != null) { - _wglDeleteBuffers(instancesBuffer); - instancesBuffer = null; + public void initialize() { + destroy(); + + if (DynamicLightsPipelineCompiler.matrixCopyBuffer == null) { + DynamicLightsPipelineCompiler.matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); } + + shaderProgram = DynamicLightsAccelParticleShader.compile(); + shaderProgram.loadUniforms(); + + particleBuffer = EagRuntime.allocateByteBuffer(PARTICLE_LIMIT * BYTES_PER_PARTICLE); + + vertexArray = _wglGenVertexArrays(); + vertexBuffer = _wglGenBuffers(); + instancesBuffer = _wglGenBuffers(); + + FloatBuffer verts = EagRuntime.allocateFloatBuffer(12); + verts.put(new float[] { -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f }); + verts.flip(); + + EaglercraftGPU.bindGLBufferArray(vertexArray); + + EaglercraftGPU.bindGLArrayBuffer(vertexBuffer); + _wglBufferData(GL_ARRAY_BUFFER, verts, GL_STATIC_DRAW); + + EagRuntime.freeFloatBuffer(verts); + + _wglEnableVertexAttribArray(0); + _wglVertexAttribPointer(0, 2, GL_FLOAT, false, 8, 0); + _wglVertexAttribDivisor(0, 0); + + EaglercraftGPU.bindGLArrayBuffer(instancesBuffer); + _wglBufferData(GL_ARRAY_BUFFER, particleBuffer.remaining(), GL_STREAM_DRAW); + + _wglEnableVertexAttribArray(1); + _wglVertexAttribPointer(1, 3, GL_FLOAT, false, 24, 0); + _wglVertexAttribDivisor(1, 1); + + _wglEnableVertexAttribArray(2); + _wglVertexAttribPointer(2, 2, GL_UNSIGNED_SHORT, false, 24, 12); + _wglVertexAttribDivisor(2, 1); + + _wglEnableVertexAttribArray(3); + _wglVertexAttribPointer(3, 2, GL_UNSIGNED_BYTE, true, 24, 16); + _wglVertexAttribDivisor(3, 1); + + _wglEnableVertexAttribArray(4); + _wglVertexAttribPointer(4, 2, GL_UNSIGNED_BYTE, false, 24, 18); + _wglVertexAttribDivisor(4, 1); + + _wglEnableVertexAttribArray(5); + _wglVertexAttribPointer(5, 4, GL_UNSIGNED_BYTE, true, 24, 20); + _wglVertexAttribDivisor(5, 1); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsPipelineCompiler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsPipelineCompiler.java index bb501c06..2d572696 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsPipelineCompiler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsPipelineCompiler.java @@ -1,6 +1,6 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformMatrix4fv; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; @@ -13,22 +13,21 @@ import net.minecraft.client.renderer.GLAllocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DynamicLightsPipelineCompiler implements IExtPipelineCompiler { - static FloatBuffer matrixCopyBuffer = null; - private static class PipelineInstance { private final int coreBits; @@ -43,26 +42,11 @@ public class DynamicLightsPipelineCompiler implements IExtPipelineCompiler { } - @Override - public String[] getShaderSource(int stateCoreBits, int stateExtBits, Object[] userPointer) { - if(matrixCopyBuffer == null) { - matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); - } - userPointer[0] = new PipelineInstance(stateCoreBits, stateExtBits); - return new String[] { - ShaderSource.getSourceFor(ShaderSource.core_dynamiclights_vsh), - ShaderSource.getSourceFor(ShaderSource.core_dynamiclights_fsh) - }; - } + static FloatBuffer matrixCopyBuffer = null; @Override - public int getExtensionStatesCount() { - return 0; - } + public void destroyPipeline(IProgramGL shaderProgram, int stateCoreBits, int stateExtBits, Object[] userPointer) { - @Override - public int getCurrentExtensionStateBits(int stateCoreBits) { - return 0; } @Override @@ -70,21 +54,41 @@ public class DynamicLightsPipelineCompiler implements IExtPipelineCompiler { return 0xFFFFFFFF; } + @Override + public int getCurrentExtensionStateBits(int stateCoreBits) { + return 0; + } + + @Override + public int getExtensionStatesCount() { + return 0; + } + + @Override + public String[] getShaderSource(int stateCoreBits, int stateExtBits, Object[] userPointer) { + if (matrixCopyBuffer == null) { + matrixCopyBuffer = GLAllocation.createDirectFloatBuffer(16); + } + userPointer[0] = new PipelineInstance(stateCoreBits, stateExtBits); + return new String[] { ShaderSource.getSourceFor(ShaderSource.core_dynamiclights_vsh), + ShaderSource.getSourceFor(ShaderSource.core_dynamiclights_fsh) }; + } + @Override public void initializeNewShader(IProgramGL compiledProg, int stateCoreBits, int stateExtBits, Object[] userPointer) { DynamicLightsExtPipelineShader newShader = new DynamicLightsExtPipelineShader(compiledProg, stateCoreBits); - ((PipelineInstance)userPointer[0]).shader = newShader; + ((PipelineInstance) userPointer[0]).shader = newShader; newShader.loadUniforms(); } @Override public void updatePipeline(IProgramGL compiledProg, int stateCoreBits, int stateExtBits, Object[] userPointer) { - if((stateCoreBits & FixedFunctionState.STATE_ENABLE_LIGHTMAP) != 0) { - DynamicLightsExtPipelineShader.Uniforms uniforms = ((PipelineInstance)userPointer[0]).shader.uniforms; - if(uniforms.u_inverseViewMatrix4f != null) { + if ((stateCoreBits & FixedFunctionState.STATE_ENABLE_LIGHTMAP) != 0) { + DynamicLightsExtPipelineShader.Uniforms uniforms = ((PipelineInstance) userPointer[0]).shader.uniforms; + if (uniforms.u_inverseViewMatrix4f != null) { int serial = DynamicLightsStateManager.inverseViewMatrixSerial; - if(uniforms.inverseViewMatrixSerial != serial) { + if (uniforms.inverseViewMatrixSerial != serial) { uniforms.inverseViewMatrixSerial = serial; FloatBuffer buf = matrixCopyBuffer; buf.clear(); @@ -96,9 +100,4 @@ public class DynamicLightsPipelineCompiler implements IExtPipelineCompiler { } } - @Override - public void destroyPipeline(IProgramGL shaderProgram, int stateCoreBits, int stateExtBits, Object[] userPointer) { - - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsStateManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsStateManager.java index bf47ed13..25ff4e2e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsStateManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/DynamicLightsStateManager.java @@ -17,14 +17,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -43,14 +44,70 @@ public class DynamicLightsStateManager { static int lastTotal = 0; private static long lastTick = 0l; + public static final void bindAcceleratedEffectRenderer(EffectRenderer renderer) { + renderer.acceleratedParticleRenderer = accelParticleRenderer; + } + + public static final void clearRenderList() { + if (instancePoolIndex > maxListLengthTracker) { + maxListLengthTracker = instancePoolIndex; + } + lightRenderList.clear(); + instancePoolIndex = 0; + } + + public static final void commitLightSourceBuckets(double renderPosX, double renderPosY, double renderPosZ) { + lastTotal = lightRenderList.size(); + if (bucketLoader != null) { + bucketLoader.clearBuckets(); + int entityChunkOriginX = MathHelper.floor_double(renderPosX / 16.0) << 4; + int entityChunkOriginY = MathHelper.floor_double(renderPosY / 16.0) << 4; + int entityChunkOriginZ = MathHelper.floor_double(renderPosZ / 16.0) << 4; + Iterator itr = lightRenderList.iterator(); + while (itr.hasNext()) { + DynamicLightInstance dl = itr.next(); + float lightChunkPosX = (float) (dl.posX - entityChunkOriginX); + float lightChunkPosY = (float) (dl.posY - entityChunkOriginY); + float lightChunkPosZ = (float) (dl.posZ - entityChunkOriginZ); + bucketLoader.bucketLightSource(lightChunkPosX, lightChunkPosY, lightChunkPosZ, dl); + } + bucketLoader.setRenderPos(renderPosX, renderPosY, renderPosZ); + bucketLoader.truncateOverflowingBuffers(); + } + updateTimers(); + clearRenderList(); + } + + public static final void destroyAll() { + lightInstancePool = new ArrayList<>(); + } + + public static final void disableDynamicLightsRender(boolean unloadPipeline) { + if (bucketLoader != null) { + bucketLoader.destroy(); + bucketLoader = null; + if (unloadPipeline) { + FixedFunctionPipeline.loadExtensionPipeline(null); + } + } + if (accelParticleRenderer != null) { + accelParticleRenderer.destroy(); + accelParticleRenderer = null; + } + destroyAll(); + lightRenderList.clear(); + instancePoolIndex = 0; + maxListLengthTracker = 0; + } + public static final void enableDynamicLightsRender() { - if(bucketLoader == null) { + if (bucketLoader == null) { bucketLoader = new DynamicLightBucketLoader(); bucketLoader.initialize(); bucketLoader.bindLightSourceBucket(-999, -999, -999, 0); FixedFunctionPipeline.loadExtensionPipeline(deferredExtPipeline); } - if(accelParticleRenderer == null) { + if (accelParticleRenderer == null) { accelParticleRenderer = new DynamicLightsAcceleratedEffectRenderer(); accelParticleRenderer.initialize(); } @@ -59,26 +116,8 @@ public class DynamicLightsStateManager { maxListLengthTracker = 0; } - public static final void bindAcceleratedEffectRenderer(EffectRenderer renderer) { - renderer.acceleratedParticleRenderer = accelParticleRenderer; - } - - public static final void disableDynamicLightsRender(boolean unloadPipeline) { - if(bucketLoader != null) { - bucketLoader.destroy(); - bucketLoader = null; - if(unloadPipeline) { - FixedFunctionPipeline.loadExtensionPipeline(null); - } - } - if(accelParticleRenderer != null) { - accelParticleRenderer.destroy(); - accelParticleRenderer = null; - } - destroyAll(); - lightRenderList.clear(); - instancePoolIndex = 0; - maxListLengthTracker = 0; + public static String getF3String() { + return "DynamicLightsTotal: " + lastTotal; } public static final boolean isDynamicLightsRender() { @@ -89,27 +128,16 @@ public class DynamicLightsStateManager { return GlStateManager.isExtensionPipeline() && bucketLoader != null; } - public static final void reportForwardRenderObjectPosition(int centerX, int centerY, int centerZ) { - if(bucketLoader != null) { - bucketLoader.bindLightSourceBucket(centerX, centerY, centerZ, 0); - } - } - - public static final void reportForwardRenderObjectPosition2(float x, float y, float z) { - if(bucketLoader != null) { - float posX = (float)((x + TileEntityRendererDispatcher.staticPlayerX) - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerX / 16.0) << 4)); - float posY = (float)((y + TileEntityRendererDispatcher.staticPlayerY) - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerY / 16.0) << 4)); - float posZ = (float)((z + TileEntityRendererDispatcher.staticPlayerZ) - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerZ / 16.0) << 4)); - bucketLoader.bindLightSourceBucket((int)posX, (int)posY, (int)posZ, 0); - } + public static boolean isSupported() { + return EaglercraftGPU.checkOpenGLESVersion() >= 300; } public static final void renderDynamicLight(String lightName, double posX, double posY, double posZ, float radius) { - if(bucketLoader != null) { + if (bucketLoader != null) { DynamicLightInstance dl; - if(instancePoolIndex < lightInstancePool.size()) { + if (instancePoolIndex < lightInstancePool.size()) { dl = lightInstancePool.get(instancePoolIndex); - }else { + } else { lightInstancePool.add(dl = new DynamicLightInstance()); } ++instancePoolIndex; @@ -118,34 +146,22 @@ public class DynamicLightsStateManager { } } - public static final void clearRenderList() { - if(instancePoolIndex > maxListLengthTracker) { - maxListLengthTracker = instancePoolIndex; + public static final void reportForwardRenderObjectPosition(int centerX, int centerY, int centerZ) { + if (bucketLoader != null) { + bucketLoader.bindLightSourceBucket(centerX, centerY, centerZ, 0); } - lightRenderList.clear(); - instancePoolIndex = 0; } - public static final void commitLightSourceBuckets(double renderPosX, double renderPosY, double renderPosZ) { - lastTotal = lightRenderList.size(); - if(bucketLoader != null) { - bucketLoader.clearBuckets(); - int entityChunkOriginX = MathHelper.floor_double(renderPosX / 16.0) << 4; - int entityChunkOriginY = MathHelper.floor_double(renderPosY / 16.0) << 4; - int entityChunkOriginZ = MathHelper.floor_double(renderPosZ / 16.0) << 4; - Iterator itr = lightRenderList.iterator(); - while(itr.hasNext()) { - DynamicLightInstance dl = itr.next(); - float lightChunkPosX = (float)(dl.posX - entityChunkOriginX); - float lightChunkPosY = (float)(dl.posY - entityChunkOriginY); - float lightChunkPosZ = (float)(dl.posZ - entityChunkOriginZ); - bucketLoader.bucketLightSource(lightChunkPosX, lightChunkPosY, lightChunkPosZ, dl); - } - bucketLoader.setRenderPos(renderPosX, renderPosY, renderPosZ); - bucketLoader.truncateOverflowingBuffers(); + public static final void reportForwardRenderObjectPosition2(float x, float y, float z) { + if (bucketLoader != null) { + float posX = (float) ((x + TileEntityRendererDispatcher.staticPlayerX) + - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerX / 16.0) << 4)); + float posY = (float) ((y + TileEntityRendererDispatcher.staticPlayerY) + - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerY / 16.0) << 4)); + float posZ = (float) ((z + TileEntityRendererDispatcher.staticPlayerZ) + - (MathHelper.floor_double(TileEntityRendererDispatcher.staticPlayerZ / 16.0) << 4)); + bucketLoader.bindLightSourceBucket((int) posX, (int) posY, (int) posZ, 0); } - updateTimers(); - clearRenderList(); } public static final void setupInverseViewMatrix() { @@ -155,11 +171,11 @@ public class DynamicLightsStateManager { private static final void updateTimers() { long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastTick > 5000l) { + if (millis - lastTick > 5000l) { lastTick = millis; - if(maxListLengthTracker < (lightInstancePool.size() >> 1)) { + if (maxListLengthTracker < (lightInstancePool.size() >> 1)) { List newPool = new ArrayList<>(Math.max(maxListLengthTracker, 16)); - for(int i = 0; i < maxListLengthTracker; ++i) { + for (int i = 0; i < maxListLengthTracker; ++i) { newPool.add(lightInstancePool.get(i)); } lightInstancePool = newPool; @@ -168,16 +184,4 @@ public class DynamicLightsStateManager { } } - public static final void destroyAll() { - lightInstancePool = new ArrayList<>(); - } - - public static String getF3String() { - return "DynamicLightsTotal: " + lastTotal; - } - - public static boolean isSupported() { - return EaglercraftGPU.checkOpenGLESVersion() >= 300; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/program/DynamicLightsAccelParticleShader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/program/DynamicLightsAccelParticleShader.java index ff16f556..49c93ee4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/program/DynamicLightsAccelParticleShader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/opengl/ext/dynamiclights/program/DynamicLightsAccelParticleShader.java @@ -1,7 +1,11 @@ package net.lax1dude.eaglercraft.v1_8.opengl.ext.dynamiclights.program; -import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL.*; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformBlockIndex; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglGetUniformLocation; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniform1i; +import static net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL._wglUniformBlockBinding; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_FRAGMENT_SHADER; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_VERTEX_SHADER; import net.lax1dude.eaglercraft.v1_8.internal.IProgramGL; import net.lax1dude.eaglercraft.v1_8.internal.IShaderGL; @@ -14,43 +18,21 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ext.deferred.program.ShaderSource; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class DynamicLightsAccelParticleShader extends ShaderProgram { - public static DynamicLightsAccelParticleShader compile() { - IShaderGL accelParticleVSH = ShaderCompiler.compileShader("accel_particle_dynamiclights", GL_VERTEX_SHADER, - ShaderSource.accel_particle_dynamiclights_vsh); - IShaderGL accelParticleFSH = null; - try { - accelParticleFSH = ShaderCompiler.compileShader("accel_particle_dynamiclights", GL_FRAGMENT_SHADER, - ShaderSource.accel_particle_dynamiclights_fsh); - IProgramGL prog = ShaderCompiler.linkProgram("accel_particle_dynamiclights", accelParticleVSH, accelParticleFSH); - return new DynamicLightsAccelParticleShader(prog); - }finally { - if(accelParticleVSH != null) { - accelParticleVSH.free(); - } - if(accelParticleFSH != null) { - accelParticleFSH.free(); - } - } - } - - private DynamicLightsAccelParticleShader(IProgramGL prog) { - super(prog, new Uniforms()); - } - public static class Uniforms implements IProgramUniforms { public IUniformGL u_color4f = null; @@ -78,14 +60,38 @@ public class DynamicLightsAccelParticleShader extends ShaderProgram { - public final int coreState; - - public DynamicLightsExtPipelineShader(IProgramGL program, int coreState) { - super(program, new Uniforms()); - this.coreState = coreState; - } - public static class Uniforms implements IProgramUniforms { public int u_chunkLightingDataBlockBinding = -1; @@ -45,14 +41,21 @@ public class DynamicLightsExtPipelineShader extends ShaderProgram[] bannedWords; - private static ProfanityFilter instance = null; - public static ProfanityFilter getInstance() { - if(instance == null) { - instance = new ProfanityFilter(); - } - return instance; - } - - private ProfanityFilter() { - logger.info("Loading profanity filter hash set..."); - List strs = EagRuntime.getResourceLines("profanity_filter.wlist"); - if(strs == null) { - throw new RuntimeException("File is missing: profanity_filter.wlist"); - } - long start = EagRuntime.steadyTimeMillis(); - Set[] sets = new Set[0]; - int j = 0; - for(String str : strs) { - if(nextDelimiter(str, 0) != -1) continue; - str = LookAlikeUnicodeConv.convertString(str); - int l = str.length(); - if(l == 0) continue; - if(sets.length < l) { - Set[] setsNew = new Set[l]; - System.arraycopy(sets, 0, setsNew, 0, sets.length); - sets = setsNew; - } - --l; - if(sets[l] == null) { - sets[l] = new HashSet(); - } - if(sets[l].add(str)) { - ++j; - } - } - bannedWords = sets; - logger.info("Processed {} entries after {}ms", j, (EagRuntime.steadyTimeMillis() - start)); - } - - public IChatComponent profanityFilterChatComponent(IChatComponent componentIn) { - if(componentIn == null) return null; - IChatComponent cmp = null; - //long start = System.nanoTime(); - try { - cmp = profanityFilterChatComponent0(componentIn); - }catch(Throwable t) { - logger.error("Profanity filter raised an exception on chat component!"); - logger.error(t); - } - //logger.info("Took: {}", ((System.nanoTime() - start) / 1000000.0)); - return cmp != null ? cmp : componentIn; - } - - protected IChatComponent profanityFilterChatComponent0(IChatComponent componentIn) { - if(componentIn instanceof ChatComponentStyle) { - boolean flag = false; - if(componentIn instanceof ChatComponentText) { - ChatComponentText comp = (ChatComponentText)componentIn; - String str = comp.getChatComponentText_TextValue(); - if(StringUtils.isEmpty(str) && componentIn.getSiblings().isEmpty()) { - return componentIn; - } - str = profanityFilterString0(str); - if(str != null) { - IChatComponent replacedComponent = new ChatComponentText(str); - replacedComponent.setChatStyle(comp.getChatStyleIfPresent()); - replacedComponent.getSiblings().addAll(componentIn.getSiblings()); - componentIn = replacedComponent; - flag = true; - } - }else if(componentIn instanceof ChatComponentTranslation) { - ChatComponentTranslation comp = (ChatComponentTranslation)componentIn; - IChatComponent replacedComponent = new ChatComponentTranslation(comp.getKey(), profanityFilterFormatArgs(comp.getFormatArgs())); - replacedComponent.setChatStyle(comp.getChatStyleIfPresent()); - replacedComponent.getSiblings().addAll(componentIn.getSiblings()); - componentIn = replacedComponent; - flag = true; - } - List siblings = componentIn.getSiblings(); - for(int i = 0, l = siblings.size(); i < l; ++i) { - IChatComponent cmp = profanityFilterChatComponent0(siblings.get(i)); - if(cmp != null) { - if(!flag) { - componentIn = shallowCopy(componentIn); - siblings = componentIn.getSiblings(); - flag = true; - } - siblings.set(i, cmp); - } - } - ChatStyle styleOpt = ((ChatComponentStyle)componentIn).getChatStyleIfPresent(); - if(styleOpt != null) { - HoverEvent hoverEvent = styleOpt.getChatHoverEvent(); - if(hoverEvent != null) { - HoverEvent filteredHoverEvent = profanityFilterHoverEvent(hoverEvent); - if(filteredHoverEvent != null) { - if(!flag) { - componentIn = shallowCopy(componentIn); - flag = true; - } - ChatStyle newStyle = styleOpt.createShallowCopy(); - newStyle.setChatHoverEvent(filteredHoverEvent); - componentIn.setChatStyle(newStyle); - } - } - } - return flag ? componentIn : null; - }else { - return null; - } - } - - private Object[] profanityFilterFormatArgs(Object[] formatArgs) { - Object[] ret = profanityFilterFormatArgs0(formatArgs); - return ret != null ? ret : formatArgs; - } - - private Object[] profanityFilterFormatArgs0(Object[] formatArgs) { - Object[] ret = null; - for(int i = 0; i < formatArgs.length; ++i) { - if(formatArgs[i] != null) { - String arg = formatArgs[i].toString(); - arg = profanityFilterString0(arg); - if(arg != null) { - if(ret == null) { - ret = new Object[formatArgs.length]; - System.arraycopy(formatArgs, 0, ret, 0, ret.length); - } - ret[i] = arg; - } - } - - } - return ret; - } - - protected HoverEvent profanityFilterHoverEvent(HoverEvent evtIn) { - if(evtIn.getAction() == HoverEvent.Action.SHOW_TEXT) { - IChatComponent filtered = evtIn.getValue(); - if(filtered != null) { - filtered = profanityFilterChatComponent0(filtered); - if(filtered != null) { - return new HoverEvent(evtIn.getAction(), filtered); - } - } - } - return null; - } - - private static IChatComponent shallowCopy(IChatComponent comp) { - if(comp instanceof ChatComponentStyle) { - if(comp instanceof ChatComponentText) { - ChatComponentText old = (ChatComponentText)comp; - IChatComponent ret = new ChatComponentText(old.getChatComponentText_TextValue()); - ret.setChatStyle(old.getChatStyleIfPresent()); - ret.getSiblings().addAll(comp.getSiblings()); - return ret; - }else if(comp instanceof ChatComponentTranslation) { - ChatComponentTranslation old = (ChatComponentTranslation)comp; - IChatComponent ret = new ChatComponentTranslation(old.getKey(), old.getFormatArgs()); - ret.setChatStyle(old.getChatStyleIfPresent()); - ret.getSiblings().addAll(comp.getSiblings()); - return ret; - }else if(comp instanceof ChatComponentScore) { - ChatComponentScore old = (ChatComponentScore)comp; - IChatComponent ret = new ChatComponentScore(old.getName(), old.getObjective()); - ret.setChatStyle(old.getChatStyleIfPresent()); - ret.getSiblings().addAll(comp.getSiblings()); - return ret; - }else if(comp instanceof ChatComponentSelector) { - ChatComponentSelector old = (ChatComponentSelector)comp; - IChatComponent ret = new ChatComponentSelector(old.getSelector()); - ret.setChatStyle(old.getChatStyleIfPresent()); - ret.getSiblings().addAll(comp.getSiblings()); - return ret; - } - } - return comp.createCopy(); - } - private static final char[] stars = new char[] { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' }; - public String profanityFilterString(String stringIn) { - if(stringIn == null) return null; - String str = null; - //long start = System.nanoTime(); - try { - str = profanityFilterString0(stringIn); - }catch(Throwable t) { - logger.error("Profanity filter raised an exception on string!"); - logger.error(t); - } - //logger.info("Took: {}", ((System.nanoTime() - start) / 1000000.0)); - return str != null ? str : stringIn; - } - - protected String profanityFilterString0(String stringIn) { - if(StringUtils.isAllBlank(stringIn)) { - return null; - } - int inLen = stringIn.length(); - boolean flag = false; - int i = 0, j; - int k = -1; - StringBuilder b = null; - String str; - List rangeList = new ArrayList(4); - int minCoverage = 40; - int pieceLen; - while((j = nextDelimiter(stringIn, i)) != -1) { - if(j - i > 2) { - if(b != null) { - str = LookAlikeUnicodeConv.convertString(stripColorCodes(b.toString())).toLowerCase(); - pieceLen = str.length(); - b = null; - //System.out.println("\"" + str + "\""); - rangeList.clear(); - if(isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { - flag = true; - for(int m = 0, n = rangeList.size(); m < n; ++m) { - stringIn = doStar(stringIn, k, i - 1, rangeList.get(m)); - } - } - k = -1; - } - str = LookAlikeUnicodeConv.convertString(stripColorCodes(stringIn.substring(i, j))).toLowerCase(); - pieceLen = str.length(); - //System.out.println("\"" + str + "\""); - rangeList.clear(); - if(isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { - flag = true; - for(int m = 0, n = rangeList.size(); m < n; ++m) { - stringIn = doStar(stringIn, i, j, rangeList.get(m)); - } - } - }else if(j - i > 0) { - if(b == null) { - k = i; - b = new StringBuilder(stringIn.substring(i, j)); - }else { - b.append(stringIn.substring(i, j)); - } - } - i = j + 1; - } - j = inLen; - if(j - i > 2) { - if(b != null) { - str = LookAlikeUnicodeConv.convertString(stripColorCodes(b.toString())).toLowerCase(); - pieceLen = str.length(); - b = null; - //System.out.println("\"" + str + "\""); - rangeList.clear(); - if(isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { - flag = true; - for(int m = 0, n = rangeList.size(); m < n; ++m) { - stringIn = doStar(stringIn, k, i - 1, rangeList.get(m)); - } - } - k = -1; - } - str = LookAlikeUnicodeConv.convertString(stripColorCodes(stringIn.substring(i, j))).toLowerCase(); - pieceLen = str.length(); - //System.out.println("\"" + str + "\""); - rangeList.clear(); - if(isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { - flag = true; - for(int m = 0, n = rangeList.size(); m < n; ++m) { - stringIn = doStar(stringIn, i, j, rangeList.get(m)); - } - } - }else if(j - i > 0) { - if(b == null) { - k = i; - b = new StringBuilder(stringIn.substring(i, j)); - }else { - b.append(stringIn.substring(i, j)); - } - } - if(b != null) { - str = LookAlikeUnicodeConv.convertString(stripColorCodes(b.toString())).toLowerCase(); - pieceLen = str.length(); - b = null; - //System.out.println("\"" + str + "\""); - rangeList.clear(); - if(isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { - flag = true; - for(int m = 0, n = rangeList.size(); m < n; ++m) { - stringIn = doStar(stringIn, k, stringIn.length(), rangeList.get(m)); - } - } - } - return flag ? stringIn : null; - } - - protected String doStar(String stringIn, int start, int end, int[] rangeReturn) { - int strlen = stringIn.length(); - start += rangeReturn[0]; - end -= rangeReturn[1]; - int len = end - start; - if(len <= 0 || start < 0 || end > strlen) { - logger.warn("Profanity filter attempted out of bounds substring @ strlen: {}, start: {}, end: {}, len: {}", strlen, start, end, len); - return stringIn; - } - StringBuilder fixed = new StringBuilder(stringIn.substring(0, start)); - fixed.append(stars, 0, MathHelper.clamp_int(len, 1, stars.length)); - fixed.append(stringIn, end, stringIn.length()); - return fixed.toString(); - } - protected static final int[] zeroZero = new int[2]; - protected boolean isBanned(String word, List rangeReturn) { - int l = word.length(); - if(l == 0) return false; - int i = bannedWords.length; - int k; - boolean flag = false; - for(int j = Math.min(l, i); j >= 3; --j) { - if(j == l) { - Set set = bannedWords[j - 1]; - //System.out.println(" - \"" + word + "\""); - if(set != null && set.contains(word)) { - rangeReturn.add(zeroZero); - return true; - } - }else { - Set set = bannedWords[j - 1]; - if(set != null) { - int m = l - j; - for(int n = 0; n <= m; ++n) { - if(overlaps(n, n + j, l, rangeReturn)) { - //System.out.println("Skipping overlap: " + n + " -> " + (n + j)); - continue; - } - String ss = word.substring(n, n + j); - //System.out.println(" - \"" + ss + "\""); - if(set.contains(ss)) { - rangeReturn.add(new int[] { n, m - n }); - flag = true; - } - } - } - } - } - return flag; - } - - protected static boolean overlaps(int min, int max, int fullLen, List rangeReturn) { - int[] ii; - int j, k; - for(int i = 0, l = rangeReturn.size(); i < l; ++i) { - ii = rangeReturn.get(i); - j = ii[0]; - k = fullLen - ii[1]; - if(min < k && j < max) { - return true; - } - } - return false; - } - protected static int evaluateCoverage(int fullLen, List rangeReturn) { int coverage = 0; int[] ii; - for(int i = 0, l = rangeReturn.size(); i < l; ++i) { + for (int i = 0, l = rangeReturn.size(); i < l; ++i) { ii = rangeReturn.get(i); coverage += fullLen - ii[0] - ii[1] - 1; } return coverage; } - protected static String stripColorCodes(String stringIn) { - int i = stringIn.indexOf('\u00a7'); - if(i != -1) { - int j = 0; - int l = stringIn.length(); - StringBuilder ret = new StringBuilder(l); - do { - if(i - j > 0) { - ret.append(stringIn, j, i); - } - j = i + 2; - }while(j < l && (i = stringIn.indexOf('\u00a7', j)) != -1); - if(l - j > 0) { - ret.append(stringIn, j, l); - } - return ret.toString(); - }else { - return stringIn; + public static ProfanityFilter getInstance() { + if (instance == null) { + instance = new ProfanityFilter(); } + return instance; + } + + private static boolean isDelimiter(char c) { + switch (c) { + case ' ': + case '.': + case ',': + case '_': + case '+': + case '-': + case '=': + case '|': + case '?': + case '!': + case '<': + case '>': + case '/': + case '\\': + case '\'': + case '\"': + case '@': + case '#': + case '%': + case '^': + case '&': + case '*': + case '(': + case ')': + case '{': + case '}': + case ':': + case ';': + case '`': + case '~': + case '\n': + case '\r': + case '\t': + case '\u00a0': + return true; + } + return false; } private static int nextDelimiter(String stringIn, int startIndex) { int len = stringIn.length(); - while(startIndex < len) { + while (startIndex < len) { char c = stringIn.charAt(startIndex); - switch(c) { + switch (c) { case ' ': case '.': case ',': @@ -490,45 +159,387 @@ public class ProfanityFilter { return -1; } - private static boolean isDelimiter(char c) { - switch(c) { - case ' ': - case '.': - case ',': - case '_': - case '+': - case '-': - case '=': - case '|': - case '?': - case '!': - case '<': - case '>': - case '/': - case '\\': - case '\'': - case '\"': - case '@': - case '#': - case '%': - case '^': - case '&': - case '*': - case '(': - case ')': - case '{': - case '}': - case ':': - case ';': - case '`': - case '~': - case '\n': - case '\r': - case '\t': - case '\u00a0': - return true; + protected static boolean overlaps(int min, int max, int fullLen, List rangeReturn) { + int[] ii; + int j, k; + for (int i = 0, l = rangeReturn.size(); i < l; ++i) { + ii = rangeReturn.get(i); + j = ii[0]; + k = fullLen - ii[1]; + if (min < k && j < max) { + return true; + } } return false; } + private static IChatComponent shallowCopy(IChatComponent comp) { + if (comp instanceof ChatComponentStyle) { + if (comp instanceof ChatComponentText) { + ChatComponentText old = (ChatComponentText) comp; + IChatComponent ret = new ChatComponentText(old.getChatComponentText_TextValue()); + ret.setChatStyle(old.getChatStyleIfPresent()); + ret.getSiblings().addAll(comp.getSiblings()); + return ret; + } else if (comp instanceof ChatComponentTranslation) { + ChatComponentTranslation old = (ChatComponentTranslation) comp; + IChatComponent ret = new ChatComponentTranslation(old.getKey(), old.getFormatArgs()); + ret.setChatStyle(old.getChatStyleIfPresent()); + ret.getSiblings().addAll(comp.getSiblings()); + return ret; + } else if (comp instanceof ChatComponentScore) { + ChatComponentScore old = (ChatComponentScore) comp; + IChatComponent ret = new ChatComponentScore(old.getName(), old.getObjective()); + ret.setChatStyle(old.getChatStyleIfPresent()); + ret.getSiblings().addAll(comp.getSiblings()); + return ret; + } else if (comp instanceof ChatComponentSelector) { + ChatComponentSelector old = (ChatComponentSelector) comp; + IChatComponent ret = new ChatComponentSelector(old.getSelector()); + ret.setChatStyle(old.getChatStyleIfPresent()); + ret.getSiblings().addAll(comp.getSiblings()); + return ret; + } + } + return comp.createCopy(); + } + + protected static String stripColorCodes(String stringIn) { + int i = stringIn.indexOf('\u00a7'); + if (i != -1) { + int j = 0; + int l = stringIn.length(); + StringBuilder ret = new StringBuilder(l); + do { + if (i - j > 0) { + ret.append(stringIn, j, i); + } + j = i + 2; + } while (j < l && (i = stringIn.indexOf('\u00a7', j)) != -1); + if (l - j > 0) { + ret.append(stringIn, j, l); + } + return ret.toString(); + } else { + return stringIn; + } + } + + protected final Set[] bannedWords; + + private ProfanityFilter() { + logger.info("Loading profanity filter hash set..."); + List strs = EagRuntime.getResourceLines("profanity_filter.wlist"); + if (strs == null) { + throw new RuntimeException("File is missing: profanity_filter.wlist"); + } + long start = EagRuntime.steadyTimeMillis(); + Set[] sets = new Set[0]; + int j = 0; + for (String str : strs) { + if (nextDelimiter(str, 0) != -1) + continue; + str = LookAlikeUnicodeConv.convertString(str); + int l = str.length(); + if (l == 0) + continue; + if (sets.length < l) { + Set[] setsNew = new Set[l]; + System.arraycopy(sets, 0, setsNew, 0, sets.length); + sets = setsNew; + } + --l; + if (sets[l] == null) { + sets[l] = new HashSet(); + } + if (sets[l].add(str)) { + ++j; + } + } + bannedWords = sets; + logger.info("Processed {} entries after {}ms", j, (EagRuntime.steadyTimeMillis() - start)); + } + + protected String doStar(String stringIn, int start, int end, int[] rangeReturn) { + int strlen = stringIn.length(); + start += rangeReturn[0]; + end -= rangeReturn[1]; + int len = end - start; + if (len <= 0 || start < 0 || end > strlen) { + logger.warn("Profanity filter attempted out of bounds substring @ strlen: {}, start: {}, end: {}, len: {}", + strlen, start, end, len); + return stringIn; + } + StringBuilder fixed = new StringBuilder(stringIn.substring(0, start)); + fixed.append(stars, 0, MathHelper.clamp_int(len, 1, stars.length)); + fixed.append(stringIn, end, stringIn.length()); + return fixed.toString(); + } + + protected boolean isBanned(String word, List rangeReturn) { + int l = word.length(); + if (l == 0) + return false; + int i = bannedWords.length; + int k; + boolean flag = false; + for (int j = Math.min(l, i); j >= 3; --j) { + if (j == l) { + Set set = bannedWords[j - 1]; + // System.out.println(" - \"" + word + "\""); + if (set != null && set.contains(word)) { + rangeReturn.add(zeroZero); + return true; + } + } else { + Set set = bannedWords[j - 1]; + if (set != null) { + int m = l - j; + for (int n = 0; n <= m; ++n) { + if (overlaps(n, n + j, l, rangeReturn)) { + // System.out.println("Skipping overlap: " + n + " -> " + (n + j)); + continue; + } + String ss = word.substring(n, n + j); + // System.out.println(" - \"" + ss + "\""); + if (set.contains(ss)) { + rangeReturn.add(new int[] { n, m - n }); + flag = true; + } + } + } + } + } + return flag; + } + + public IChatComponent profanityFilterChatComponent(IChatComponent componentIn) { + if (componentIn == null) + return null; + IChatComponent cmp = null; + // long start = System.nanoTime(); + try { + cmp = profanityFilterChatComponent0(componentIn); + } catch (Throwable t) { + logger.error("Profanity filter raised an exception on chat component!"); + logger.error(t); + } + // logger.info("Took: {}", ((System.nanoTime() - start) / 1000000.0)); + return cmp != null ? cmp : componentIn; + } + + protected IChatComponent profanityFilterChatComponent0(IChatComponent componentIn) { + if (componentIn instanceof ChatComponentStyle) { + boolean flag = false; + if (componentIn instanceof ChatComponentText) { + ChatComponentText comp = (ChatComponentText) componentIn; + String str = comp.getChatComponentText_TextValue(); + if (StringUtils.isEmpty(str) && componentIn.getSiblings().isEmpty()) { + return componentIn; + } + str = profanityFilterString0(str); + if (str != null) { + IChatComponent replacedComponent = new ChatComponentText(str); + replacedComponent.setChatStyle(comp.getChatStyleIfPresent()); + replacedComponent.getSiblings().addAll(componentIn.getSiblings()); + componentIn = replacedComponent; + flag = true; + } + } else if (componentIn instanceof ChatComponentTranslation) { + ChatComponentTranslation comp = (ChatComponentTranslation) componentIn; + IChatComponent replacedComponent = new ChatComponentTranslation(comp.getKey(), + profanityFilterFormatArgs(comp.getFormatArgs())); + replacedComponent.setChatStyle(comp.getChatStyleIfPresent()); + replacedComponent.getSiblings().addAll(componentIn.getSiblings()); + componentIn = replacedComponent; + flag = true; + } + List siblings = componentIn.getSiblings(); + for (int i = 0, l = siblings.size(); i < l; ++i) { + IChatComponent cmp = profanityFilterChatComponent0(siblings.get(i)); + if (cmp != null) { + if (!flag) { + componentIn = shallowCopy(componentIn); + siblings = componentIn.getSiblings(); + flag = true; + } + siblings.set(i, cmp); + } + } + ChatStyle styleOpt = ((ChatComponentStyle) componentIn).getChatStyleIfPresent(); + if (styleOpt != null) { + HoverEvent hoverEvent = styleOpt.getChatHoverEvent(); + if (hoverEvent != null) { + HoverEvent filteredHoverEvent = profanityFilterHoverEvent(hoverEvent); + if (filteredHoverEvent != null) { + if (!flag) { + componentIn = shallowCopy(componentIn); + flag = true; + } + ChatStyle newStyle = styleOpt.createShallowCopy(); + newStyle.setChatHoverEvent(filteredHoverEvent); + componentIn.setChatStyle(newStyle); + } + } + } + return flag ? componentIn : null; + } else { + return null; + } + } + + private Object[] profanityFilterFormatArgs(Object[] formatArgs) { + Object[] ret = profanityFilterFormatArgs0(formatArgs); + return ret != null ? ret : formatArgs; + } + + private Object[] profanityFilterFormatArgs0(Object[] formatArgs) { + Object[] ret = null; + for (int i = 0; i < formatArgs.length; ++i) { + if (formatArgs[i] != null) { + String arg = formatArgs[i].toString(); + arg = profanityFilterString0(arg); + if (arg != null) { + if (ret == null) { + ret = new Object[formatArgs.length]; + System.arraycopy(formatArgs, 0, ret, 0, ret.length); + } + ret[i] = arg; + } + } + + } + return ret; + } + + protected HoverEvent profanityFilterHoverEvent(HoverEvent evtIn) { + if (evtIn.getAction() == HoverEvent.Action.SHOW_TEXT) { + IChatComponent filtered = evtIn.getValue(); + if (filtered != null) { + filtered = profanityFilterChatComponent0(filtered); + if (filtered != null) { + return new HoverEvent(evtIn.getAction(), filtered); + } + } + } + return null; + } + + public String profanityFilterString(String stringIn) { + if (stringIn == null) + return null; + String str = null; + // long start = System.nanoTime(); + try { + str = profanityFilterString0(stringIn); + } catch (Throwable t) { + logger.error("Profanity filter raised an exception on string!"); + logger.error(t); + } + // logger.info("Took: {}", ((System.nanoTime() - start) / 1000000.0)); + return str != null ? str : stringIn; + } + + protected String profanityFilterString0(String stringIn) { + if (StringUtils.isAllBlank(stringIn)) { + return null; + } + int inLen = stringIn.length(); + boolean flag = false; + int i = 0, j; + int k = -1; + StringBuilder b = null; + String str; + List rangeList = new ArrayList(4); + int minCoverage = 40; + int pieceLen; + while ((j = nextDelimiter(stringIn, i)) != -1) { + if (j - i > 2) { + if (b != null) { + str = LookAlikeUnicodeConv.convertString(stripColorCodes(b.toString())).toLowerCase(); + pieceLen = str.length(); + b = null; + // System.out.println("\"" + str + "\""); + rangeList.clear(); + if (isBanned(str, rangeList) + && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { + flag = true; + for (int m = 0, n = rangeList.size(); m < n; ++m) { + stringIn = doStar(stringIn, k, i - 1, rangeList.get(m)); + } + } + k = -1; + } + str = LookAlikeUnicodeConv.convertString(stripColorCodes(stringIn.substring(i, j))).toLowerCase(); + pieceLen = str.length(); + // System.out.println("\"" + str + "\""); + rangeList.clear(); + if (isBanned(str, rangeList) + && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { + flag = true; + for (int m = 0, n = rangeList.size(); m < n; ++m) { + stringIn = doStar(stringIn, i, j, rangeList.get(m)); + } + } + } else if (j - i > 0) { + if (b == null) { + k = i; + b = new StringBuilder(stringIn.substring(i, j)); + } else { + b.append(stringIn.substring(i, j)); + } + } + i = j + 1; + } + j = inLen; + if (j - i > 2) { + if (b != null) { + str = LookAlikeUnicodeConv.convertString(stripColorCodes(b.toString())).toLowerCase(); + pieceLen = str.length(); + b = null; + // System.out.println("\"" + str + "\""); + rangeList.clear(); + if (isBanned(str, rangeList) + && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { + flag = true; + for (int m = 0, n = rangeList.size(); m < n; ++m) { + stringIn = doStar(stringIn, k, i - 1, rangeList.get(m)); + } + } + k = -1; + } + str = LookAlikeUnicodeConv.convertString(stripColorCodes(stringIn.substring(i, j))).toLowerCase(); + pieceLen = str.length(); + // System.out.println("\"" + str + "\""); + rangeList.clear(); + if (isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { + flag = true; + for (int m = 0, n = rangeList.size(); m < n; ++m) { + stringIn = doStar(stringIn, i, j, rangeList.get(m)); + } + } + } else if (j - i > 0) { + if (b == null) { + k = i; + b = new StringBuilder(stringIn.substring(i, j)); + } else { + b.append(stringIn.substring(i, j)); + } + } + if (b != null) { + str = LookAlikeUnicodeConv.convertString(stripColorCodes(b.toString())).toLowerCase(); + pieceLen = str.length(); + b = null; + // System.out.println("\"" + str + "\""); + rangeList.clear(); + if (isBanned(str, rangeList) && evaluateCoverage(pieceLen, rangeList) > (pieceLen * minCoverage / 100)) { + flag = true; + for (int m = 0, n = rangeList.size(); m < n; ++m) { + stringIn = doStar(stringIn, k, stringIn.length(), rangeList.get(m)); + } + } + } + return flag ? stringIn : null; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CapePackets.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CapePackets.java index af6327a8..8468c5cf 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CapePackets.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CapePackets.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.profile; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,11 +21,6 @@ public class CapePackets { public static final int PACKET_MY_CAPE_PRESET = 0x01; public static final int PACKET_MY_CAPE_CUSTOM = 0x02; - public static byte[] writeMyCapePreset(int capeId) { - return new byte[] { (byte) PACKET_MY_CAPE_PRESET, (byte) (capeId >>> 24), (byte) (capeId >>> 16), - (byte) (capeId >>> 8), (byte) (capeId & 0xFF) }; - } - public static byte[] writeMyCapeCustom(CustomCape customCape) { byte[] packet = new byte[1 + customCape.texture.length]; packet[0] = (byte) PACKET_MY_CAPE_CUSTOM; @@ -32,4 +28,9 @@ public class CapePackets { return packet; } + public static byte[] writeMyCapePreset(int capeId) { + return new byte[] { (byte) PACKET_MY_CAPE_PRESET, (byte) (capeId >>> 24), (byte) (capeId >>> 16), + (byte) (capeId >>> 8), (byte) (capeId & 0xFF) }; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomCape.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomCape.java index 12fac3de..04d08589 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomCape.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomCape.java @@ -6,27 +6,28 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CustomCape { - public final String name; - public final byte[] texture; - - private EaglerSkinTexture textureInstance; - private ResourceLocation resourceLocation; - private static int texId = 0; + public final String name; + + public final byte[] texture; + private EaglerSkinTexture textureInstance; + + private ResourceLocation resourceLocation; public CustomCape(String name, byte[] texture) { this.name = name; @@ -36,23 +37,23 @@ public class CustomCape { this.textureInstance = new EaglerSkinTexture(texture2, 32, 32); this.resourceLocation = null; } - - public void load() { - if(resourceLocation == null) { - resourceLocation = new ResourceLocation("eagler:capes/custom/tex_" + texId++); - Minecraft.getMinecraft().getTextureManager().loadTexture(resourceLocation, textureInstance); - } - } - - public ResourceLocation getResource() { - return resourceLocation; - } - + public void delete() { - if(resourceLocation != null) { + if (resourceLocation != null) { Minecraft.getMinecraft().getTextureManager().deleteTexture(resourceLocation); resourceLocation = null; } } + public ResourceLocation getResource() { + return resourceLocation; + } + + public void load() { + if (resourceLocation == null) { + resourceLocation = new ResourceLocation("eagler:capes/custom/tex_" + texId++); + Minecraft.getMinecraft().getTextureManager().loadTexture(resourceLocation, textureInstance); + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomSkin.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomSkin.java index 6a1ef71f..afd1e84a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomSkin.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/CustomSkin.java @@ -6,28 +6,29 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CustomSkin { + private static int texId = 0; public final String name; public final byte[] texture; + public SkinModel model; - private EaglerSkinTexture textureInstance; - private ResourceLocation resourceLocation; - private static int texId = 0; + private ResourceLocation resourceLocation; public CustomSkin(String name, byte[] texture, SkinModel model) { this.name = name; @@ -36,23 +37,23 @@ public class CustomSkin { this.textureInstance = new EaglerSkinTexture(texture, model.width, model.height); this.resourceLocation = null; } - - public void load() { - if(resourceLocation == null) { - resourceLocation = new ResourceLocation("eagler:skins/custom/tex_" + texId++); - Minecraft.getMinecraft().getTextureManager().loadTexture(resourceLocation, textureInstance); - } - } - - public ResourceLocation getResource() { - return resourceLocation; - } - + public void delete() { - if(resourceLocation != null) { + if (resourceLocation != null) { Minecraft.getMinecraft().getTextureManager().deleteTexture(resourceLocation); resourceLocation = null; } } + public ResourceLocation getResource() { + return resourceLocation; + } + + public void load() { + if (resourceLocation == null) { + resourceLocation = new ResourceLocation("eagler:skins/custom/tex_" + texId++); + Minecraft.getMinecraft().getTextureManager().loadTexture(resourceLocation, textureInstance); + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultCapes.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultCapes.java index 87437aef..40b09b87 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultCapes.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultCapes.java @@ -5,14 +5,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,36 +46,38 @@ public enum DefaultCapes { TIKTOK(23, "TikTok", new ResourceLocation("eagler:capes/23.tiktok.png")), PURPLE_HEART(24, "Purple Heart", new ResourceLocation("eagler:capes/24.purple_heart.png")), CHERRY_BLOSSOM(25, "Cherry Blossom", new ResourceLocation("eagler:capes/25.cherry_blossom.png")); - + public static final DefaultCapes[] defaultCapesMap = new DefaultCapes[26]; - + + static { + DefaultCapes[] capes = values(); + for (int i = 0; i < capes.length; ++i) { + defaultCapesMap[capes[i].id] = capes[i]; + } + } + + public static DefaultCapes getCapeFromId(int id) { + DefaultCapes e = null; + if (id >= 0 && id < defaultCapesMap.length) { + e = defaultCapesMap[id]; + } + if (e != null) { + return e; + } else { + return NO_CAPE; + } + } + public final int id; + public final String name; + public final ResourceLocation location; - + private DefaultCapes(int id, String name, ResourceLocation location) { this.id = id; this.name = name; this.location = location; } - - public static DefaultCapes getCapeFromId(int id) { - DefaultCapes e = null; - if(id >= 0 && id < defaultCapesMap.length) { - e = defaultCapesMap[id]; - } - if(e != null) { - return e; - }else { - return NO_CAPE; - } - } - - static { - DefaultCapes[] capes = values(); - for(int i = 0; i < capes.length; ++i) { - defaultCapesMap[capes[i].id] = capes[i]; - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultSkins.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultSkins.java index 8f88b241..cdde470c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultSkins.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/DefaultSkins.java @@ -5,14 +5,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,7 +36,8 @@ public enum DefaultSkins { PRISONER_ALEX(13, "Prisoner Alex", new ResourceLocation("eagler:skins/14.prisoner_alex.png"), SkinModel.ALEX), SCOTTISH_STEVE(14, "Scottish Steve", new ResourceLocation("eagler:skins/15.scottish_steve.png"), SkinModel.STEVE), SCOTTISH_ALEX(15, "Scottish Alex", new ResourceLocation("eagler:skins/16.scottish_alex.png"), SkinModel.ALEX), - DEVELOPER_STEVE(16, "Developer Steve", new ResourceLocation("eagler:skins/17.developer_steve.png"), SkinModel.STEVE), + DEVELOPER_STEVE(16, "Developer Steve", new ResourceLocation("eagler:skins/17.developer_steve.png"), + SkinModel.STEVE), DEVELOPER_ALEX(17, "Developer Alex", new ResourceLocation("eagler:skins/18.developer_alex.png"), SkinModel.ALEX), HEROBRINE(18, "Herobrine", new ResourceLocation("eagler:skins/19.herobrine.png"), SkinModel.ZOMBIE), NOTCH(19, "Notch", new ResourceLocation("eagler:skins/20.notch.png"), SkinModel.STEVE), @@ -44,42 +46,46 @@ public enum DefaultSkins { PIG(22, "Pig", new ResourceLocation("eagler:skins/23.pig.png"), SkinModel.STEVE), MOOSHROOM(23, "Mooshroom", new ResourceLocation("eagler:skins/24.mooshroom.png"), SkinModel.STEVE), LONG_ARMS(24, "Long Arms", new ResourceLocation("eagler:mesh/longarms.fallback.png"), SkinModel.LONG_ARMS), - WEIRD_CLIMBER_DUDE(25, "Weird Climber Dude", new ResourceLocation("eagler:mesh/weirdclimber.fallback.png"), SkinModel.WEIRD_CLIMBER_DUDE), - LAXATIVE_DUDE(26, "Laxative Dude", new ResourceLocation("eagler:mesh/laxativedude.fallback.png"), SkinModel.LAXATIVE_DUDE), + WEIRD_CLIMBER_DUDE(25, "Weird Climber Dude", new ResourceLocation("eagler:mesh/weirdclimber.fallback.png"), + SkinModel.WEIRD_CLIMBER_DUDE), + LAXATIVE_DUDE(26, "Laxative Dude", new ResourceLocation("eagler:mesh/laxativedude.fallback.png"), + SkinModel.LAXATIVE_DUDE), BABY_CHARLES(27, "Baby Charles", new ResourceLocation("eagler:mesh/charles.fallback.png"), SkinModel.BABY_CHARLES), BABY_WINSTON(28, "Baby Winston", new ResourceLocation("eagler:mesh/winston.fallback.png"), SkinModel.BABY_WINSTON); - + public static final DefaultSkins[] defaultSkinsMap = new DefaultSkins[29]; - + + static { + DefaultSkins[] skins = values(); + for (int i = 0; i < skins.length; ++i) { + defaultSkinsMap[skins[i].id] = skins[i]; + } + } + + public static DefaultSkins getSkinFromId(int id) { + DefaultSkins e = null; + if (id >= 0 && id < defaultSkinsMap.length) { + e = defaultSkinsMap[id]; + } + if (e != null) { + return e; + } else { + return DEFAULT_STEVE; + } + } + public final int id; public final String name; + public final ResourceLocation location; + public final SkinModel model; - + private DefaultSkins(int id, String name, ResourceLocation location, SkinModel model) { this.id = id; this.name = name; this.location = location; this.model = model; } - - public static DefaultSkins getSkinFromId(int id) { - DefaultSkins e = null; - if(id >= 0 && id < defaultSkinsMap.length) { - e = defaultSkinsMap[id]; - } - if(e != null) { - return e; - }else { - return DEFAULT_STEVE; - } - } - - static { - DefaultSkins[] skins = values(); - for(int i = 0; i < skins.length; ++i) { - defaultSkinsMap[skins[i].id] = skins[i]; - } - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerProfile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerProfile.java index d5edfaa0..6fcefdc0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerProfile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerProfile.java @@ -9,6 +9,7 @@ import net.lax1dude.eaglercraft.v1_8.EaglerInputStream; import net.lax1dude.eaglercraft.v1_8.EaglerOutputStream; import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.HString; import net.minecraft.client.Minecraft; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; @@ -18,14 +19,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,270 +35,59 @@ import net.minecraft.util.ResourceLocation; public class EaglerProfile { private static String username; - + public static int presetSkinId; public static int customSkinId; - + public static int presetCapeId; public static int customCapeId; public static boolean isServerSkinOverride = false; public static int overridePresetSkinId = -1; - public static final ResourceLocation overrideCustomSkinTexture = new ResourceLocation("eagler:skins/custom/tex_server_override"); + public static final ResourceLocation overrideCustomSkinTexture = new ResourceLocation( + "eagler:skins/custom/tex_server_override"); public static EaglerSkinTexture overrideCustomSkin = null; public static SkinModel overrideCustomSkinModel = SkinModel.STEVE; public static boolean isServerCapeOverride = false; public static int overridePresetCapeId = -1; - public static final ResourceLocation overrideCustomCapeTexture = new ResourceLocation("eagler:capes/custom/tex_server_override"); + public static final ResourceLocation overrideCustomCapeTexture = new ResourceLocation( + "eagler:capes/custom/tex_server_override"); public static EaglerSkinTexture overrideCustomCape = null; public static final List customSkins = new ArrayList<>(); public static final List customCapes = new ArrayList<>(); - + public static final EaglercraftRandom rand; - - public static ResourceLocation getActiveSkinResourceLocation() { - if(isServerSkinOverride) { - if(overridePresetSkinId == -1) { - return overrideCustomSkinTexture; - }else { - if(overridePresetSkinId >= 0 && overridePresetSkinId < DefaultSkins.defaultSkinsMap.length) { - return DefaultSkins.defaultSkinsMap[overridePresetSkinId].location; - }else { - return DefaultSkins.defaultSkinsMap[0].location; - } - } - } - if(presetSkinId == -1) { - if(customSkinId >= 0 && customSkinId < customSkins.size()) { - return customSkins.get(customSkinId).getResource(); - }else { - customSkinId = -1; - presetSkinId = 0; - return DefaultSkins.defaultSkinsMap[0].location; - } - }else { - if(presetSkinId >= 0 && presetSkinId < DefaultSkins.defaultSkinsMap.length) { - return DefaultSkins.defaultSkinsMap[presetSkinId].location; - }else { - presetSkinId = 0; - return DefaultSkins.defaultSkinsMap[0].location; - } - } - } - - public static SkinModel getActiveSkinModel() { - if(isServerSkinOverride) { - if(overridePresetSkinId == -1) { - return overrideCustomSkinModel; - }else { - if(overridePresetSkinId >= 0 && overridePresetSkinId < DefaultSkins.defaultSkinsMap.length) { - return DefaultSkins.defaultSkinsMap[overridePresetSkinId].model; - }else { - return DefaultSkins.defaultSkinsMap[0].model; - } - } - } - if(presetSkinId == -1) { - if(customSkinId >= 0 && customSkinId < customSkins.size()) { - return customSkins.get(customSkinId).model; - }else { - customSkinId = -1; - presetSkinId = 0; - return DefaultSkins.defaultSkinsMap[0].model; - } - }else { - if(presetSkinId >= 0 && presetSkinId < DefaultSkins.defaultSkinsMap.length) { - return DefaultSkins.defaultSkinsMap[presetSkinId].model; - }else { - presetSkinId = 0; - return DefaultSkins.defaultSkinsMap[0].model; - } - } - } - - public static ResourceLocation getActiveCapeResourceLocation() { - if(isServerCapeOverride) { - if(overridePresetCapeId == -1) { - return overrideCustomCapeTexture; - }else { - if(overridePresetCapeId >= 0 && overridePresetCapeId < DefaultCapes.defaultCapesMap.length) { - return DefaultCapes.defaultCapesMap[overridePresetCapeId].location; - }else { - return DefaultCapes.defaultCapesMap[0].location; - } - } - } - if(presetCapeId == -1) { - if(customCapeId >= 0 && customCapeId < customCapes.size()) { - return customCapes.get(customCapeId).getResource(); - }else { - customCapeId = -1; - presetCapeId = 0; - return DefaultCapes.defaultCapesMap[0].location; - } - }else { - if(presetCapeId >= 0 && presetCapeId < DefaultCapes.defaultCapesMap.length) { - return DefaultCapes.defaultCapesMap[presetCapeId].location; - }else { - presetCapeId = 0; - return DefaultCapes.defaultCapesMap[0].location; - } - } - } - public static EaglercraftUUID getPlayerUUID() { - return Minecraft.getMinecraft().getSession().getProfile().getId(); - } + static { + String[] defaultNames = new String[] { "Yeeish", "Yeeish", "Yee", "Yee", "Yeer", "Yeeler", "Eagler", "Eagl", + "Darver", "Darvler", "Vool", "Vigg", "Vigg", "Deev", "Yigg", "Yeeg" }; - public static String getName() { - return username; - } + rand = new EaglercraftRandom(); - public static void setName(String str) { - username = str; - Minecraft mc = Minecraft.getMinecraft(); - if(mc != null) { - mc.getSession().reset(); - } - } + do { + username = HString.format("%s%s%04d", defaultNames[rand.nextInt(defaultNames.length)], + defaultNames[rand.nextInt(defaultNames.length)], rand.nextInt(10000)); + } while (username.length() > 16); - public static byte[] getSkinPacket(int vers) { - if(presetSkinId == -1) { - if(customSkinId >= 0 && customSkinId < customSkins.size()) { - CustomSkin toSend = customSkins.get(customSkinId); - if(vers <= 3) { - return SkinPackets.writeMySkinCustomV3(toSend); - }else { - return SkinPackets.writeMySkinCustomV4(toSend); - } - }else { - customSkinId = -1; - presetSkinId = 0; - return SkinPackets.writeMySkinPreset(0); - } - }else { - if(presetSkinId >= 0 && presetSkinId < DefaultSkins.defaultSkinsMap.length) { - return SkinPackets.writeMySkinPreset(presetSkinId); - }else { - presetSkinId = 0; - return SkinPackets.writeMySkinPreset(0); - } - } - } + setName(username); - public static byte[] getCapePacket() { - if(presetCapeId == -1) { - if(customCapeId >= 0 && customCapeId < customCapes.size()) { - return CapePackets.writeMyCapeCustom(customCapes.get(customCapeId)); - }else { - customCapeId = -1; - presetCapeId = 0; - return CapePackets.writeMyCapePreset(0); - } - }else { - if(presetCapeId >= 0 && presetCapeId < DefaultCapes.defaultCapesMap.length) { - return CapePackets.writeMyCapePreset(presetCapeId); - }else { - presetCapeId = 0; - return CapePackets.writeMyCapePreset(0); - } - } - } + do { + presetSkinId = rand.nextInt(DefaultSkins.defaultSkinsMap.length); + } while (DefaultSkins.defaultSkinsMap[presetSkinId].model.highPoly != null); + customSkinId = -1; - public static void handleForceSkinPreset(int preset) { - isServerSkinOverride = true; - overridePresetSkinId = preset; - ServerSkinCache.needReloadClientSkin = true; - } + presetCapeId = 0; + customCapeId = -1; - public static void handleForceSkinCustom(int modelID, byte[] datav3) { - if(datav3.length != 16384) { - return; - } - isServerSkinOverride = true; - overridePresetSkinId = -1; - overrideCustomSkinModel = SkinModel.getModelFromId(modelID); - if(overrideCustomSkinModel.highPoly != null) { - overrideCustomSkinModel = SkinModel.STEVE; - } - if(overrideCustomSkin == null) { - overrideCustomSkin = new EaglerSkinTexture(datav3, 64, 64); - Minecraft.getMinecraft().getTextureManager().loadTexture(overrideCustomSkinTexture, overrideCustomSkin); - }else { - overrideCustomSkin.copyPixelsIn(datav3); - } - ServerSkinCache.needReloadClientSkin = true; - } - - public static void handleForceCapePreset(int preset) { - isServerCapeOverride = true; - overridePresetCapeId = preset; - ServerCapeCache.needReloadClientCape = true; - } - - public static void handleForceCapeCustom(byte[] custom) { - if(custom.length != 1173) { - return; - } - byte[] pixels32x32 = new byte[4096]; - SkinConverter.convertCape23x17RGBto32x32RGBA(custom, pixels32x32); - isServerCapeOverride = true; - overridePresetCapeId = -1; - if(overrideCustomCape == null) { - overrideCustomCape = new EaglerSkinTexture(pixels32x32, 32, 32); - Minecraft.getMinecraft().getTextureManager().loadTexture(overrideCustomCapeTexture, overrideCustomCape); - }else { - overrideCustomCape.copyPixelsIn(pixels32x32); - } - ServerCapeCache.needReloadClientCape = true; - } - - public static void clearServerSkinOverride() { - isServerSkinOverride = false; - isServerCapeOverride = false; - } - - private static boolean doesSkinExist(String name) { - for(int i = 0, l = customSkins.size(); i < l; ++i) { - if(customSkins.get(i).name.equalsIgnoreCase(name)) { - return true; - } - } - return false; - } - - private static boolean doesCapeExist(String name) { - for(int i = 0, l = customCapes.size(); i < l; ++i) { - if(customCapes.get(i).name.equalsIgnoreCase(name)) { - return true; - } - } - return false; - } - - public static int addCustomSkin(String fileName, byte[] rawSkin) { - if(doesSkinExist(fileName)) { - String newName; - int i = 2; - while(doesSkinExist(newName = fileName + " (" + i + ")")) { - ++i; - } - fileName = newName; - } - CustomSkin newSkin = new CustomSkin(fileName, rawSkin, SkinModel.STEVE); - newSkin.load(); - int r = customSkins.size(); - customSkins.add(newSkin); - return r; } public static int addCustomCape(String fileName, byte[] rawCape23x17RGB) { - if(doesCapeExist(fileName)) { + if (doesCapeExist(fileName)) { String newName; int i = 2; - while(doesCapeExist(newName = fileName + " (" + i + ")")) { + while (doesCapeExist(newName = fileName + " (" + i + ")")) { ++i; } fileName = newName; @@ -308,18 +99,251 @@ public class EaglerProfile { return r; } + public static int addCustomSkin(String fileName, byte[] rawSkin) { + if (doesSkinExist(fileName)) { + String newName; + int i = 2; + while (doesSkinExist(newName = fileName + " (" + i + ")")) { + ++i; + } + fileName = newName; + } + CustomSkin newSkin = new CustomSkin(fileName, rawSkin, SkinModel.STEVE); + newSkin.load(); + int r = customSkins.size(); + customSkins.add(newSkin); + return r; + } + + public static void clearCustomCapes() { + for (int i = 0, l = customCapes.size(); i < l; ++i) { + customCapes.get(i).delete(); + } + customCapes.clear(); + } + public static void clearCustomSkins() { - for(int i = 0, l = customSkins.size(); i < l; ++i) { + for (int i = 0, l = customSkins.size(); i < l; ++i) { customSkins.get(i).delete(); } customSkins.clear(); } - public static void clearCustomCapes() { - for(int i = 0, l = customCapes.size(); i < l; ++i) { - customCapes.get(i).delete(); + public static void clearServerSkinOverride() { + isServerSkinOverride = false; + isServerCapeOverride = false; + } + + private static boolean doesCapeExist(String name) { + for (int i = 0, l = customCapes.size(); i < l; ++i) { + if (customCapes.get(i).name.equalsIgnoreCase(name)) { + return true; + } } - customCapes.clear(); + return false; + } + + private static boolean doesSkinExist(String name) { + for (int i = 0, l = customSkins.size(); i < l; ++i) { + if (customSkins.get(i).name.equalsIgnoreCase(name)) { + return true; + } + } + return false; + } + + public static ResourceLocation getActiveCapeResourceLocation() { + if (isServerCapeOverride) { + if (overridePresetCapeId == -1) { + return overrideCustomCapeTexture; + } else { + if (overridePresetCapeId >= 0 && overridePresetCapeId < DefaultCapes.defaultCapesMap.length) { + return DefaultCapes.defaultCapesMap[overridePresetCapeId].location; + } else { + return DefaultCapes.defaultCapesMap[0].location; + } + } + } + if (presetCapeId == -1) { + if (customCapeId >= 0 && customCapeId < customCapes.size()) { + return customCapes.get(customCapeId).getResource(); + } else { + customCapeId = -1; + presetCapeId = 0; + return DefaultCapes.defaultCapesMap[0].location; + } + } else { + if (presetCapeId >= 0 && presetCapeId < DefaultCapes.defaultCapesMap.length) { + return DefaultCapes.defaultCapesMap[presetCapeId].location; + } else { + presetCapeId = 0; + return DefaultCapes.defaultCapesMap[0].location; + } + } + } + + public static SkinModel getActiveSkinModel() { + if (isServerSkinOverride) { + if (overridePresetSkinId == -1) { + return overrideCustomSkinModel; + } else { + if (overridePresetSkinId >= 0 && overridePresetSkinId < DefaultSkins.defaultSkinsMap.length) { + return DefaultSkins.defaultSkinsMap[overridePresetSkinId].model; + } else { + return DefaultSkins.defaultSkinsMap[0].model; + } + } + } + if (presetSkinId == -1) { + if (customSkinId >= 0 && customSkinId < customSkins.size()) { + return customSkins.get(customSkinId).model; + } else { + customSkinId = -1; + presetSkinId = 0; + return DefaultSkins.defaultSkinsMap[0].model; + } + } else { + if (presetSkinId >= 0 && presetSkinId < DefaultSkins.defaultSkinsMap.length) { + return DefaultSkins.defaultSkinsMap[presetSkinId].model; + } else { + presetSkinId = 0; + return DefaultSkins.defaultSkinsMap[0].model; + } + } + } + + public static ResourceLocation getActiveSkinResourceLocation() { + if (isServerSkinOverride) { + if (overridePresetSkinId == -1) { + return overrideCustomSkinTexture; + } else { + if (overridePresetSkinId >= 0 && overridePresetSkinId < DefaultSkins.defaultSkinsMap.length) { + return DefaultSkins.defaultSkinsMap[overridePresetSkinId].location; + } else { + return DefaultSkins.defaultSkinsMap[0].location; + } + } + } + if (presetSkinId == -1) { + if (customSkinId >= 0 && customSkinId < customSkins.size()) { + return customSkins.get(customSkinId).getResource(); + } else { + customSkinId = -1; + presetSkinId = 0; + return DefaultSkins.defaultSkinsMap[0].location; + } + } else { + if (presetSkinId >= 0 && presetSkinId < DefaultSkins.defaultSkinsMap.length) { + return DefaultSkins.defaultSkinsMap[presetSkinId].location; + } else { + presetSkinId = 0; + return DefaultSkins.defaultSkinsMap[0].location; + } + } + } + + public static byte[] getCapePacket() { + if (presetCapeId == -1) { + if (customCapeId >= 0 && customCapeId < customCapes.size()) { + return CapePackets.writeMyCapeCustom(customCapes.get(customCapeId)); + } else { + customCapeId = -1; + presetCapeId = 0; + return CapePackets.writeMyCapePreset(0); + } + } else { + if (presetCapeId >= 0 && presetCapeId < DefaultCapes.defaultCapesMap.length) { + return CapePackets.writeMyCapePreset(presetCapeId); + } else { + presetCapeId = 0; + return CapePackets.writeMyCapePreset(0); + } + } + } + + public static String getName() { + return username; + } + + public static EaglercraftUUID getPlayerUUID() { + return Minecraft.getMinecraft().getSession().getProfile().getId(); + } + + public static byte[] getSkinPacket(int vers) { + if (presetSkinId == -1) { + if (customSkinId >= 0 && customSkinId < customSkins.size()) { + CustomSkin toSend = customSkins.get(customSkinId); + if (vers <= 3) { + return SkinPackets.writeMySkinCustomV3(toSend); + } else { + return SkinPackets.writeMySkinCustomV4(toSend); + } + } else { + customSkinId = -1; + presetSkinId = 0; + return SkinPackets.writeMySkinPreset(0); + } + } else { + if (presetSkinId >= 0 && presetSkinId < DefaultSkins.defaultSkinsMap.length) { + return SkinPackets.writeMySkinPreset(presetSkinId); + } else { + presetSkinId = 0; + return SkinPackets.writeMySkinPreset(0); + } + } + } + + public static void handleForceCapeCustom(byte[] custom) { + if (custom.length != 1173) { + return; + } + byte[] pixels32x32 = new byte[4096]; + SkinConverter.convertCape23x17RGBto32x32RGBA(custom, pixels32x32); + isServerCapeOverride = true; + overridePresetCapeId = -1; + if (overrideCustomCape == null) { + overrideCustomCape = new EaglerSkinTexture(pixels32x32, 32, 32); + Minecraft.getMinecraft().getTextureManager().loadTexture(overrideCustomCapeTexture, overrideCustomCape); + } else { + overrideCustomCape.copyPixelsIn(pixels32x32); + } + ServerCapeCache.needReloadClientCape = true; + } + + public static void handleForceCapePreset(int preset) { + isServerCapeOverride = true; + overridePresetCapeId = preset; + ServerCapeCache.needReloadClientCape = true; + } + + public static void handleForceSkinCustom(int modelID, byte[] datav3) { + if (datav3.length != 16384) { + return; + } + isServerSkinOverride = true; + overridePresetSkinId = -1; + overrideCustomSkinModel = SkinModel.getModelFromId(modelID); + if (overrideCustomSkinModel.highPoly != null) { + overrideCustomSkinModel = SkinModel.STEVE; + } + if (overrideCustomSkin == null) { + overrideCustomSkin = new EaglerSkinTexture(datav3, 64, 64); + Minecraft.getMinecraft().getTextureManager().loadTexture(overrideCustomSkinTexture, overrideCustomSkin); + } else { + overrideCustomSkin.copyPixelsIn(datav3); + } + ServerSkinCache.needReloadClientSkin = true; + } + + public static void handleForceSkinPreset(int preset) { + isServerSkinOverride = true; + overridePresetSkinId = preset; + ServerSkinCache.needReloadClientSkin = true; + } + + public static boolean isDefaultUsername(String str) { + return str.toLowerCase() + .matches("^(yeeish|yee|yeer|yeeler|eagler|eagl|darver|darvler|vool|vigg|deev|yigg|yeeg){2}\\d{2,4}$"); } public static void read() { @@ -334,7 +358,7 @@ public class EaglerProfile { NBTTagCompound profile; try { profile = CompressedStreamTools.readCompressed(new EaglerInputStream(profileStorage)); - }catch(IOException ex) { + } catch (IOException ex) { return; } @@ -345,26 +369,29 @@ public class EaglerProfile { presetSkinId = profile.getInteger("presetSkin"); customSkinId = profile.getInteger("customSkin"); - if(profile.hasKey("presetCape", 99)) presetCapeId = profile.getInteger("presetCape"); - if(profile.hasKey("customCape", 99)) customCapeId = profile.getInteger("customCape"); + if (profile.hasKey("presetCape", 99)) + presetCapeId = profile.getInteger("presetCape"); + if (profile.hasKey("customCape", 99)) + customCapeId = profile.getInteger("customCape"); String loadUsername = profile.getString("username").trim(); - if(!loadUsername.isEmpty()) { + if (!loadUsername.isEmpty()) { username = loadUsername.replaceAll("[^A-Za-z0-9]", "_"); } clearCustomSkins(); NBTTagList skinsList = profile.getTagList("skins", 10); - for(int i = 0, l = skinsList.tagCount(); i < l; ++i) { + for (int i = 0, l = skinsList.tagCount(); i < l; ++i) { NBTTagCompound skin = skinsList.getCompoundTagAt(i); String skinName = skin.getString("name"); byte[] skinData = skin.getByteArray("data"); - if(skinData.length != 16384) continue; - for(int y = 20; y < 32; ++y) { - for(int x = 16; x < 40; ++x) { - skinData[(y << 8) | (x << 2)] = (byte)0xff; + if (skinData.length != 16384) + continue; + for (int y = 20; y < 32; ++y) { + for (int x = 16; x < 40; ++x) { + skinData[(y << 8) | (x << 2)] = (byte) 0xff; } } int skinModel = skin.getByte("model"); @@ -373,46 +400,62 @@ public class EaglerProfile { customSkins.add(newSkin); } - if(profile.hasKey("capes", 9)) { + if (profile.hasKey("capes", 9)) { clearCustomCapes(); NBTTagList capesList = profile.getTagList("capes", 10); - for(int i = 0, l = capesList.tagCount(); i < l; ++i) { + for (int i = 0, l = capesList.tagCount(); i < l; ++i) { NBTTagCompound cape = capesList.getCompoundTagAt(i); String capeName = cape.getString("name"); byte[] capeData = cape.getByteArray("data"); - if(capeData.length != 1173) continue; + if (capeData.length != 1173) + continue; CustomCape newCape = new CustomCape(capeName, capeData); newCape.load(); customCapes.add(newCape); } } - if(presetSkinId == -1) { - if(customSkinId < 0 || customSkinId >= customSkins.size()) { + if (presetSkinId == -1) { + if (customSkinId < 0 || customSkinId >= customSkins.size()) { presetSkinId = 0; customSkinId = -1; } - }else { + } else { customSkinId = -1; - if(presetSkinId < 0 || presetSkinId >= DefaultSkins.defaultSkinsMap.length) { + if (presetSkinId < 0 || presetSkinId >= DefaultSkins.defaultSkinsMap.length) { presetSkinId = 0; } } - if(presetCapeId == -1) { - if(customCapeId < 0 || customCapeId >= customCapes.size()) { + if (presetCapeId == -1) { + if (customCapeId < 0 || customCapeId >= customCapes.size()) { presetCapeId = 0; customCapeId = -1; } - }else { + } else { customCapeId = -1; - if(presetCapeId < 0 || presetCapeId >= DefaultCapes.defaultCapesMap.length) { + if (presetCapeId < 0 || presetCapeId >= DefaultCapes.defaultCapesMap.length) { presetCapeId = 0; } } } + public static void save() { + byte[] b = write(); + if (b != null) { + EagRuntime.setStorage("p", b); + } + } + + public static void setName(String str) { + username = str; + Minecraft mc = Minecraft.getMinecraft(); + if (mc != null) { + mc.getSession().reset(); + } + } + public static byte[] write() { NBTTagCompound profile = new NBTTagCompound(); profile.setInteger("presetSkin", presetSkinId); @@ -421,17 +464,17 @@ public class EaglerProfile { profile.setInteger("customCape", customCapeId); profile.setString("username", username); NBTTagList skinsList = new NBTTagList(); - for(int i = 0, l = customSkins.size(); i < l; ++i) { + for (int i = 0, l = customSkins.size(); i < l; ++i) { CustomSkin sk = customSkins.get(i); NBTTagCompound skin = new NBTTagCompound(); skin.setString("name", sk.name); skin.setByteArray("data", sk.texture); - skin.setByte("model", (byte)sk.model.id); + skin.setByte("model", (byte) sk.model.id); skinsList.appendTag(skin); } profile.setTag("skins", skinsList); NBTTagList capesList = new NBTTagList(); - for(int i = 0, l = customCapes.size(); i < l; ++i) { + for (int i = 0, l = customCapes.size(); i < l; ++i) { CustomCape cp = customCapes.get(i); NBTTagCompound cape = new NBTTagCompound(); cape.setString("name", cp.name); @@ -448,35 +491,4 @@ public class EaglerProfile { return bao.toByteArray(); } - public static void save() { - byte[] b = write(); - if(b != null) { - EagRuntime.setStorage("p", b); - } - } - - static { - String[] defaultNames = new String[] { - "Yeeish", "Yeeish", "Yee", "Yee", "Yeer", "Yeeler", "Eagler", "Eagl", - "Darver", "Darvler", "Vool", "Vigg", "Vigg", "Deev", "Yigg", "Yeeg" - }; - - rand = new EaglercraftRandom(); - - do { - username = defaultNames[rand.nextInt(defaultNames.length)] + defaultNames[rand.nextInt(defaultNames.length)] + (100 + rand.nextInt(900)); - }while(username.length() > 16); - - setName(username); - - do { - presetSkinId = rand.nextInt(DefaultSkins.defaultSkinsMap.length); - }while(DefaultSkins.defaultSkinsMap[presetSkinId].model.highPoly != null); - customSkinId = -1; - - presetCapeId = 0; - customCapeId = -1; - - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerSkinTexture.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerSkinTexture.java index 025a0149..a3a28ff3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerSkinTexture.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/EaglerSkinTexture.java @@ -11,47 +11,24 @@ import net.minecraft.client.resources.IResourceManager; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerSkinTexture implements ITextureObject { - private final int[] pixels; - private final int width; - private final int height; - - private int textureId = -1; - - public EaglerSkinTexture(int[] pixels, int width, int height) { - if(pixels.length != width * height) { - throw new IllegalArgumentException("Wrong data length " + pixels.length * 4 + " for " + width + "x" + height + " texture"); - } - this.pixels = pixels; - this.width = width; - this.height = height; - } - - public EaglerSkinTexture(byte[] pixels, int width, int height) { - if(pixels.length != width * height * 4) { - throw new IllegalArgumentException("Wrong data length " + pixels.length + " for " + width + "x" + height + " texture"); - } - this.pixels = convertToInt(pixels); - this.width = width; - this.height = height; - } - public static int[] convertToInt(byte[] pixels) { int[] p = new int[pixels.length >> 2]; - for(int i = 0, j; i < p.length; ++i) { + for (int i = 0, j; i < p.length; ++i) { j = i << 2; p[i] = (((int) pixels[j] & 0xFF) << 24) | (((int) pixels[j + 1] & 0xFF) << 16) | (((int) pixels[j + 2] & 0xFF) << 8) | ((int) pixels[j + 3] & 0xFF); @@ -59,26 +36,56 @@ public class EaglerSkinTexture implements ITextureObject { return p; } + private final int[] pixels; + private final int width; + + private final int height; + + private int textureId = -1; + + public EaglerSkinTexture(byte[] pixels, int width, int height) { + if (pixels.length != width * height * 4) { + throw new IllegalArgumentException( + "Wrong data length " + pixels.length + " for " + width + "x" + height + " texture"); + } + this.pixels = convertToInt(pixels); + this.width = width; + this.height = height; + } + + public EaglerSkinTexture(int[] pixels, int width, int height) { + if (pixels.length != width * height) { + throw new IllegalArgumentException( + "Wrong data length " + pixels.length * 4 + " for " + width + "x" + height + " texture"); + } + this.pixels = pixels; + this.width = width; + this.height = height; + } + public void copyPixelsIn(byte[] pixels) { copyPixelsIn(convertToInt(pixels)); } public void copyPixelsIn(int[] pixels) { - if(this.pixels.length != pixels.length) { - throw new IllegalArgumentException("Tried to copy " + pixels.length + " pixels into a " + this.pixels.length + " pixel texture"); + if (this.pixels.length != pixels.length) { + throw new IllegalArgumentException( + "Tried to copy " + pixels.length + " pixels into a " + this.pixels.length + " pixel texture"); } System.arraycopy(pixels, 0, this.pixels, 0, pixels.length); - if(textureId != -1) { - TextureUtil.uploadTextureImageSub(textureId, new ImageData(width, height, pixels, true), 0, 0, false, false); + if (textureId != -1) { + TextureUtil.uploadTextureImageSub(textureId, new ImageData(width, height, pixels, true), 0, 0, false, + false); } } - @Override - public void loadTexture(IResourceManager var1) throws IOException { - if(textureId == -1) { - textureId = GlStateManager.generateTexture(); - TextureUtil.uploadTextureImageAllocate(textureId, new ImageData(width, height, pixels, true), false, false); - } + public void free() { + GlStateManager.deleteTexture(textureId); + textureId = -1; + } + + public int[] getData() { + return pixels; } @Override @@ -86,31 +93,30 @@ public class EaglerSkinTexture implements ITextureObject { return textureId; } - @Override - public void setBlurMipmap(boolean var1, boolean var2) { - // no - } - - @Override - public void restoreLastBlurMipmap() { - // no - } - - public void free() { - GlStateManager.deleteTexture(textureId); - textureId = -1; + public int getHeight() { + return height; } public int getWidth() { return width; } - public int getHeight() { - return height; + @Override + public void loadTexture(IResourceManager var1) throws IOException { + if (textureId == -1) { + textureId = GlStateManager.generateTexture(); + TextureUtil.uploadTextureImageAllocate(textureId, new ImageData(width, height, pixels, true), false, false); + } } - public int[] getData() { - return pixels; + @Override + public void restoreLastBlurMipmap() { + // no + } + + @Override + public void setBlurMipmap(boolean var1, boolean var2) { + // no } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiAuthenticationScreen.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiAuthenticationScreen.java index bec4f424..b31872bd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiAuthenticationScreen.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiAuthenticationScreen.java @@ -13,14 +13,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,19 +41,19 @@ public class GuiAuthenticationScreen extends GuiScreen { this.retAfterAuthScreen = retAfterAuthScreen; this.parent = parent; String authRequired = HandshakePacketTypes.AUTHENTICATION_REQUIRED; - if(message.startsWith(authRequired)) { + if (message.startsWith(authRequired)) { message = message.substring(authRequired.length()).trim(); } - if(message.length() > 0 && message.charAt(0) == '[') { + if (message.length() > 0 && message.charAt(0) == '[') { int idx = message.indexOf(']', 1); - if(idx != -1) { + if (idx != -1) { String authType = message.substring(1, idx); int type = Integer.MAX_VALUE; try { type = Integer.parseInt(authType); - }catch(NumberFormatException ex) { + } catch (NumberFormatException ex) { } - if(type != Integer.MAX_VALUE) { + if (type != Integer.MAX_VALUE) { authTypeForWarning = type; message = message.substring(idx + 1).trim(); } @@ -61,36 +62,10 @@ public class GuiAuthenticationScreen extends GuiScreen { this.message = message; } - public void initGui() { - if(authTypeForWarning != Integer.MAX_VALUE) { - GuiScreen scr = ConnectionHandshake.displayAuthProtocolConfirm(authTypeForWarning, parent, this); - authTypeForWarning = Integer.MAX_VALUE; - if(scr != null) { - mc.displayGuiScreen(scr); - allowPlaintext = true; - return; - } - } - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.buttonList.add(continueButton = new GuiButton(1, this.width / 2 - 100, this.height / 4 + 80 + 12, - I18n.format("auth.continue", new Object[0]))); - continueButton.enabled = false; - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 80 + 37, - I18n.format("gui.cancel", new Object[0]))); - this.password = new GuiPasswordTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 40, 200, 20); // 116 - this.password.setFocused(true); - this.password.setCanLoseFocus(false); - } - - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 1) { + if (parGuiButton.id == 1) { this.mc.displayGuiScreen(new GuiConnecting(retAfterAuthScreen, password.getText())); - }else { + } else { this.mc.displayGuiScreen(parent); } } @@ -104,11 +79,39 @@ public class GuiAuthenticationScreen extends GuiScreen { super.drawScreen(i, j, var3); } + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + password.fireInputEvent(event, param); + } + + public void initGui() { + if (authTypeForWarning != Integer.MAX_VALUE) { + GuiScreen scr = ConnectionHandshake.displayAuthProtocolConfirm(authTypeForWarning, parent, this); + authTypeForWarning = Integer.MAX_VALUE; + if (scr != null) { + mc.displayGuiScreen(scr); + allowPlaintext = true; + return; + } + } + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.buttonList.add(continueButton = new GuiButton(1, this.width / 2 - 100, this.height / 4 + 80 + 12, + I18n.format("auth.continue", new Object[0]))); + continueButton.enabled = false; + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 80 + 37, + I18n.format("gui.cancel", new Object[0]))); + this.password = new GuiPasswordTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 40, + 200, 20); // 116 + this.password.setFocused(true); + this.password.setCanLoseFocus(false); + } + protected void keyTyped(char parChar1, int parInt1) { String pass = password.getText(); - if(parInt1 == KeyboardConstants.KEY_RETURN && pass.length() > 0) { + if (parInt1 == KeyboardConstants.KEY_RETURN && pass.length() > 0) { this.mc.displayGuiScreen(new GuiConnecting(retAfterAuthScreen, pass, allowPlaintext)); - }else { + } else { this.password.textboxKeyTyped(parChar1, parInt1); this.continueButton.enabled = password.getText().length() > 0; } @@ -119,14 +122,13 @@ public class GuiAuthenticationScreen extends GuiScreen { this.password.mouseClicked(parInt1, parInt2, parInt3); } + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + @Override public boolean showCopyPasteButtons() { return password.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - password.fireInputEvent(event, param); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiPasswordTextField.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiPasswordTextField.java index 26bc7f61..c6dd6a5b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiPasswordTextField.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiPasswordTextField.java @@ -6,20 +6,37 @@ import net.minecraft.client.gui.GuiTextField; /** * Copyright (c) 2023 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiPasswordTextField extends GuiTextField { + private static final char[] STARS = new char[] { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', + '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' }; + + public static String stars(int len) { + return new String(STARS, 0, len > STARS.length ? STARS.length : len); + } + public GuiPasswordTextField(int componentId, FontRenderer fontrendererObj, int x, int y, int par5Width, int par6Height) { super(componentId, fontrendererObj, x, y, par5Width, par6Height); @@ -39,20 +56,4 @@ public class GuiPasswordTextField extends GuiTextField { text = oldText; } - public static String stars(int len) { - return new String(STARS, 0, len > STARS.length ? STARS.length : len); - } - - private static final char[] STARS = new char[] { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', - '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' }; - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenDefaultUsernameNote.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenDefaultUsernameNote.java new file mode 100644 index 00000000..fdfc26b8 --- /dev/null +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenDefaultUsernameNote.java @@ -0,0 +1,69 @@ +package net.lax1dude.eaglercraft.v1_8.profile; + +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; + +/** + * Copyright (c) 2024 lax1dude. All Rights Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class GuiScreenDefaultUsernameNote extends GuiScreen { + + private final GuiScreen back; + private final GuiScreen cont; + + public GuiScreenDefaultUsernameNote(GuiScreen back, GuiScreen cont) { + this.back = back; + this.cont = cont; + } + + @Override + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + this.mc.displayGuiScreen(back); + } else if (parGuiButton.id == 1) { + this.mc.displayGuiScreen(cont); + } else if (parGuiButton.id == 2) { + this.mc.gameSettings.hideDefaultUsernameWarning = true; + this.mc.gameSettings.saveOptions(); + this.mc.displayGuiScreen(cont); + } + } + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, I18n.format("defaultUsernameDetected.title"), this.width / 2, 70, + 11184810); + this.drawCenteredString(fontRendererObj, I18n.format("defaultUsernameDetected.text0", EaglerProfile.getName()), + this.width / 2, 90, 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("defaultUsernameDetected.text1"), this.width / 2, 105, + 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("defaultUsernameDetected.text2"), this.width / 2, 120, + 16777215); + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 112, + I18n.format("defaultUsernameDetected.changeUsername"))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 142, + I18n.format("defaultUsernameDetected.continueAnyway"))); + this.buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 6 + 172, + I18n.format("defaultUsernameDetected.doNotShow"))); + } + +} diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditCape.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditCape.java index e4cee9f7..e50037b2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditCape.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditCape.java @@ -1,5 +1,7 @@ package net.lax1dude.eaglercraft.v1_8.profile; +import java.io.IOException; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.Mouse; @@ -15,27 +17,27 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -import java.io.IOException; - /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenEditCape extends GuiScreen { - private final GuiScreenEditProfile parent; + private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); + private final GuiScreenEditProfile parent; private boolean dropDownOpen = false; private String[] dropDownOptions; private int slotsVisible = 0; @@ -44,9 +46,8 @@ public class GuiScreenEditCape extends GuiScreen { private int skinsHeight = 0; private boolean dragging = false; private int mousex = 0; - private int mousey = 0; - private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); + private int mousey = 0; protected String screenTitle = "Edit Cape"; @@ -54,184 +55,14 @@ public class GuiScreenEditCape extends GuiScreen { this.parent = parent; } - public void initGui() { - Keyboard.enableRepeatEvents(true); - screenTitle = I18n.format("editCape.title"); - selectedSlot = EaglerProfile.presetCapeId == -1 ? EaglerProfile.customCapeId : (EaglerProfile.presetCapeId + EaglerProfile.customCapes.size()); - buttonList.add(new GuiButton(0, width / 2 - 100, height / 6 + 168, I18n.format("gui.done"))); - buttonList.add(new GuiButton(1, width / 2 - 21, height / 6 + 80, 71, 20, I18n.format("editCape.addCape"))); - buttonList.add(new GuiButton(2, width / 2 - 21 + 71, height / 6 + 80, 72, 20, I18n.format("editCape.clearCape"))); - updateOptions(); - } - - private void updateOptions() { - int numCustom = EaglerProfile.customCapes.size(); - String[] n = new String[numCustom + DefaultCapes.defaultCapesMap.length]; - for(int i = 0; i < numCustom; ++i) { - n[i] = EaglerProfile.customCapes.get(i).name; - } - int numDefault = DefaultCapes.defaultCapesMap.length; - for(int j = 0; j < numDefault; ++j) { - n[numCustom + j] = DefaultCapes.defaultCapesMap[j].name; - } - dropDownOptions = n; - } - - public void drawScreen(int mx, int my, float partialTicks) { - drawDefaultBackground(); - drawCenteredString(fontRendererObj, screenTitle, width / 2, 15, 16777215); - drawString(fontRendererObj, I18n.format("editCape.playerCape"), width / 2 - 20, height / 6 + 36, 10526880); - - mousex = mx; - mousey = my; - - int skinX = width / 2 - 120; - int skinY = height / 6 + 8; - int skinWidth = 80; - int skinHeight = 130; - - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xFFA0A0A0); - drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, 0xFF000015); - - int skid = selectedSlot - EaglerProfile.customCapes.size(); - if(skid < 0) { - skid = 0; - } - - if(dropDownOpen) { - super.drawScreen(0, 0, partialTicks); - }else { - super.drawScreen(mx, my, partialTicks); - } - - int numberOfCustomSkins = EaglerProfile.customSkins.size(); - int numberOfCustomCapes = EaglerProfile.customCapes.size(); - ResourceLocation skinTexture; - SkinModel model; - if(parent.selectedSlot < numberOfCustomSkins) { - CustomSkin customSkin = EaglerProfile.customSkins.get(parent.selectedSlot); - skinTexture = customSkin.getResource(); - model = customSkin.model; - }else { - DefaultSkins defaultSkin = DefaultSkins.getSkinFromId(parent.selectedSlot - numberOfCustomSkins); - skinTexture = defaultSkin.location; - model = defaultSkin.model; - } - - if(model.highPoly != null) { - drawCenteredString(fontRendererObj, I18n.format(this.mc.gameSettings.enableFNAWSkins ? "editProfile.disableFNAW" : "editProfile.enableFNAW"), width / 2, height / 6 + 150, 10526880); - } - - skinX = width / 2 - 20; - skinY = height / 6 + 52; - skinWidth = 140; - skinHeight = 22; - - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); - drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 21, skinY + skinHeight - 1, -16777216); - drawRect(skinX + skinWidth - 20, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); - - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - mc.getTextureManager().bindTexture(eaglerGui); - drawTexturedModalRect(skinX + skinWidth - 18, skinY + 3, 0, 0, 16, 16); - - drawString(fontRendererObj, dropDownOptions[selectedSlot], skinX + 5, skinY + 7, 14737632); - - skinX = width / 2 - 20; - skinY = height / 6 + 73; - skinWidth = 140; - skinHeight = (height - skinY - 10); - slotsVisible = (skinHeight / 10); - if(slotsVisible > dropDownOptions.length) slotsVisible = dropDownOptions.length; - skinHeight = slotsVisible * 10 + 7; - skinsHeight = skinHeight; - if(scrollPos == -1) { - scrollPos = selectedSlot - 2; - } - if(scrollPos > (dropDownOptions.length - slotsVisible)) { - scrollPos = (dropDownOptions.length - slotsVisible); - } - if(scrollPos < 0) { - scrollPos = 0; - } - if(dropDownOpen) { - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); - drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); - for(int i = 0; i < slotsVisible; i++) { - if(i + scrollPos < dropDownOptions.length) { - if(selectedSlot == i + scrollPos) { - drawRect(skinX + 1, skinY + i*10 + 4, skinX + skinWidth - 1, skinY + i*10 + 14, 0x77ffffff); - }else if(mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i*10 + 5) && my < (skinY + i*10 + 15)) { - drawRect(skinX + 1, skinY + i*10 + 4, skinX + skinWidth - 1, skinY + i*10 + 14, 0x55ffffff); - } - drawString(fontRendererObj, dropDownOptions[i + scrollPos], skinX + 5, skinY + 5 + i*10, 14737632); - } - } - int scrollerSize = skinHeight * slotsVisible / dropDownOptions.length; - int scrollerPos = skinHeight * scrollPos / dropDownOptions.length; - drawRect(skinX + skinWidth - 4, skinY + scrollerPos + 1, skinX + skinWidth - 1, skinY + scrollerPos + scrollerSize, 0xff888888); - } - - if(!EagRuntime.getConfiguration().isDemo()) { - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - String text = I18n.format("editProfile.importExport"); - - int w = mc.fontRendererObj.getStringWidth(text); - boolean hover = mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12; - if(hover) { - Mouse.showCursor(EnumCursorType.HAND); - } - - drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); - - GlStateManager.popMatrix(); - } - - int xx = width / 2 - 80; - int yy = height / 6 + 130; - - skinX = this.width / 2 - 120; - skinY = this.height / 6 + 8; - skinWidth = 80; - skinHeight = 130; - - ResourceLocation capeTexture; - if(selectedSlot < numberOfCustomCapes) { - capeTexture = EaglerProfile.customCapes.get(selectedSlot).getResource(); - }else { - capeTexture = DefaultCapes.getCapeFromId(selectedSlot - numberOfCustomCapes).location; - } - - SkinPreviewRenderer.renderPreview(xx, yy, mx, my, true, model, skinTexture, capeTexture); - } - - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - if(dropDownOpen) { - int var1 = Mouse.getEventDWheel(); - if(var1 < 0) { - scrollPos += 3; - } - if(var1 > 0) { - scrollPos -= 3; - if(scrollPos < 0) { - scrollPos = 0; - } - } - } - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(!dropDownOpen) { - if(par1GuiButton.id == 0) { + if (!dropDownOpen) { + if (par1GuiButton.id == 0) { safeProfile(); this.mc.displayGuiScreen((GuiScreen) parent); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { EagRuntime.displayFileChooser("image/png", "png"); - }else if(par1GuiButton.id == 2) { + } else if (par1GuiButton.id == 2) { EaglerProfile.clearCustomCapes(); safeProfile(); updateOptions(); @@ -240,100 +71,220 @@ public class GuiScreenEditCape extends GuiScreen { } } - public void updateScreen() { - if(EagRuntime.fileChooserHasResult()) { - FileChooserResult result = EagRuntime.getFileChooserResult(); - if(result != null) { - ImageData loadedCape = ImageData.loadImageFile(result.fileData, ImageData.getMimeFromType(result.fileName)); - if(loadedCape != null) { - if((loadedCape.width == 32 || loadedCape.width == 64) && loadedCape.height == 32) { - byte[] resized = new byte[1173]; - SkinConverter.convertCape32x32RGBAto23x17RGB(loadedCape, resized); - int k; - if((k = EaglerProfile.addCustomCape(result.fileName, resized)) != -1) { - selectedSlot = k; - updateOptions(); - safeProfile(); - } - }else { - EagRuntime.showPopup("The selected image '" + result.fileName + "' is not the right size!\nEaglercraft only supports 32x32 or 64x32 capes"); - } - }else { - EagRuntime.showPopup("The selected file '" + result.fileName + "' is not a supported format!"); - } - } + public void drawScreen(int mx, int my, float partialTicks) { + drawDefaultBackground(); + drawCenteredString(fontRendererObj, screenTitle, width / 2, 15, 16777215); + drawString(fontRendererObj, I18n.format("editCape.playerCape"), width / 2 - 20, height / 6 + 36, 10526880); + + mousex = mx; + mousey = my; + + int skinX = width / 2 - 120; + int skinY = height / 6 + 8; + int skinWidth = 80; + int skinHeight = 130; + + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xFFA0A0A0); + drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, 0xFF000015); + + int skid = selectedSlot - EaglerProfile.customCapes.size(); + if (skid < 0) { + skid = 0; } - if(dropDownOpen) { - if(PointerInputAbstraction.getVCursorButtonDown(0)) { - int skinX = width / 2 - 20; - int skinY = height / 6 + 73; - int skinWidth = 140; - if(mousex >= (skinX + skinWidth - 10) && mousex < (skinX + skinWidth) && mousey >= skinY && mousey < (skinY + skinsHeight)) { - dragging = true; + + if (dropDownOpen) { + super.drawScreen(0, 0, partialTicks); + } else { + super.drawScreen(mx, my, partialTicks); + } + + int numberOfCustomSkins = EaglerProfile.customSkins.size(); + int numberOfCustomCapes = EaglerProfile.customCapes.size(); + ResourceLocation skinTexture; + SkinModel model; + if (parent.selectedSlot < numberOfCustomSkins) { + CustomSkin customSkin = EaglerProfile.customSkins.get(parent.selectedSlot); + skinTexture = customSkin.getResource(); + model = customSkin.model; + } else { + DefaultSkins defaultSkin = DefaultSkins.getSkinFromId(parent.selectedSlot - numberOfCustomSkins); + skinTexture = defaultSkin.location; + model = defaultSkin.model; + } + + if (model.highPoly != null) { + drawCenteredString(fontRendererObj, I18n.format( + this.mc.gameSettings.enableFNAWSkins ? "editProfile.disableFNAW" : "editProfile.enableFNAW"), + width / 2, height / 6 + 150, 10526880); + } + + skinX = width / 2 - 20; + skinY = height / 6 + 52; + skinWidth = 140; + skinHeight = 22; + + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); + drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 21, skinY + skinHeight - 1, -16777216); + drawRect(skinX + skinWidth - 20, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); + + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + mc.getTextureManager().bindTexture(eaglerGui); + drawTexturedModalRect(skinX + skinWidth - 18, skinY + 3, 0, 0, 16, 16); + + drawString(fontRendererObj, dropDownOptions[selectedSlot], skinX + 5, skinY + 7, 14737632); + + skinX = width / 2 - 20; + skinY = height / 6 + 73; + skinWidth = 140; + skinHeight = (height - skinY - 10); + slotsVisible = (skinHeight / 10); + if (slotsVisible > dropDownOptions.length) + slotsVisible = dropDownOptions.length; + skinHeight = slotsVisible * 10 + 7; + skinsHeight = skinHeight; + if (scrollPos == -1) { + scrollPos = selectedSlot - 2; + } + if (scrollPos > (dropDownOptions.length - slotsVisible)) { + scrollPos = (dropDownOptions.length - slotsVisible); + } + if (scrollPos < 0) { + scrollPos = 0; + } + if (dropDownOpen) { + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); + drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); + for (int i = 0; i < slotsVisible; i++) { + if (i + scrollPos < dropDownOptions.length) { + if (selectedSlot == i + scrollPos) { + drawRect(skinX + 1, skinY + i * 10 + 4, skinX + skinWidth - 1, skinY + i * 10 + 14, 0x77ffffff); + } else if (mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i * 10 + 5) + && my < (skinY + i * 10 + 15)) { + drawRect(skinX + 1, skinY + i * 10 + 4, skinX + skinWidth - 1, skinY + i * 10 + 14, 0x55ffffff); + } + drawString(fontRendererObj, dropDownOptions[i + scrollPos], skinX + 5, skinY + 5 + i * 10, + 14737632); + } + } + int scrollerSize = skinHeight * slotsVisible / dropDownOptions.length; + int scrollerPos = skinHeight * scrollPos / dropDownOptions.length; + drawRect(skinX + skinWidth - 4, skinY + scrollerPos + 1, skinX + skinWidth - 1, + skinY + scrollerPos + scrollerSize, 0xff888888); + } + + if (!EagRuntime.getConfiguration().isDemo()) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + String text = I18n.format("editProfile.importExport"); + + int w = mc.fontRendererObj.getStringWidth(text); + boolean hover = mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12; + if (hover) { + Mouse.showCursor(EnumCursorType.HAND); + } + + drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); + + GlStateManager.popMatrix(); + } + + int xx = width / 2 - 80; + int yy = height / 6 + 130; + + skinX = this.width / 2 - 120; + skinY = this.height / 6 + 8; + skinWidth = 80; + skinHeight = 130; + + ResourceLocation capeTexture; + if (selectedSlot < numberOfCustomCapes) { + capeTexture = EaglerProfile.customCapes.get(selectedSlot).getResource(); + } else { + capeTexture = DefaultCapes.getCapeFromId(selectedSlot - numberOfCustomCapes).location; + } + + SkinPreviewRenderer.renderPreview(xx, yy, mx, my, true, model, skinTexture, capeTexture); + } + + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + if (dropDownOpen) { + int var1 = Mouse.getEventDWheel(); + if (var1 < 0) { + scrollPos += 3; + } + if (var1 > 0) { + scrollPos -= 3; + if (scrollPos < 0) { + scrollPos = 0; } - if(dragging) { - int scrollerSize = skinsHeight * slotsVisible / dropDownOptions.length; - scrollPos = (mousey - skinY - (scrollerSize / 2)) * dropDownOptions.length / skinsHeight; - } - }else { - dragging = false; } - }else { - dragging = false; } } - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); + public void initGui() { + Keyboard.enableRepeatEvents(true); + screenTitle = I18n.format("editCape.title"); + selectedSlot = EaglerProfile.presetCapeId == -1 ? EaglerProfile.customCapeId + : (EaglerProfile.presetCapeId + EaglerProfile.customCapes.size()); + buttonList.add(new GuiButton(0, width / 2 - 100, height / 6 + 168, I18n.format("gui.done"))); + buttonList.add(new GuiButton(1, width / 2 - 21, height / 6 + 80, 71, 20, I18n.format("editCape.addCape"))); + buttonList + .add(new GuiButton(2, width / 2 - 21 + 71, height / 6 + 80, 72, 20, I18n.format("editCape.clearCape"))); + updateOptions(); } protected void keyTyped(char c, int k) { - if(k == 200 && selectedSlot > 0) { + if (k == 200 && selectedSlot > 0) { --selectedSlot; scrollPos = selectedSlot - 2; } - if(k == 208 && selectedSlot < (dropDownOptions.length - 1)) { + if (k == 208 && selectedSlot < (dropDownOptions.length - 1)) { ++selectedSlot; scrollPos = selectedSlot - 2; } } - + protected void mouseClicked(int mx, int my, int button) { if (button == 0) { - if(!EagRuntime.getConfiguration().isDemo()) { + if (!EagRuntime.getConfiguration().isDemo()) { int w = mc.fontRendererObj.getStringWidth(I18n.format("editProfile.importExport")); - if(mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12) { + if (mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12) { safeProfile(); mc.displayGuiScreen(new GuiScreenImportExportProfile(parent)); - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); return; } } - + int skinX = width / 2 + 140 - 40; int skinY = height / 6 + 52; - - if(mx >= skinX && mx < (skinX + 20) && my >= skinY && my < (skinY + 22)) { + + if (mx >= skinX && mx < (skinX + 20) && my >= skinY && my < (skinY + 22)) { dropDownOpen = !dropDownOpen; return; } - + skinX = width / 2 - 20; skinY = height / 6 + 52; int skinWidth = 140; int skinHeight = skinsHeight; - - if(!(mx >= skinX && mx < (skinX + skinWidth) && my >= skinY && my < (skinY + skinHeight + 22))) { + + if (!(mx >= skinX && mx < (skinX + skinWidth) && my >= skinY && my < (skinY + skinHeight + 22))) { dragging = false; - if(dropDownOpen) { + if (dropDownOpen) { dropDownOpen = false; return; } - }else if(dropDownOpen && !dragging) { + } else if (dropDownOpen && !dragging) { skinY += 21; - for(int i = 0; i < slotsVisible; i++) { - if(i + scrollPos < dropDownOptions.length) { - if(mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i * 10 + 5) && my < (skinY + i * 10 + 15) && selectedSlot != i + scrollPos) { + for (int i = 0; i < slotsVisible; i++) { + if (i + scrollPos < dropDownOptions.length) { + if (mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i * 10 + 5) + && my < (skinY + i * 10 + 15) && selectedSlot != i + scrollPos) { selectedSlot = i + scrollPos; dropDownOpen = false; dragging = false; @@ -345,16 +296,79 @@ public class GuiScreenEditCape extends GuiScreen { } super.mouseClicked(mx, my, button); } - + + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + protected void safeProfile() { int customLen = EaglerProfile.customCapes.size(); - if(selectedSlot < customLen) { + if (selectedSlot < customLen) { EaglerProfile.presetCapeId = -1; EaglerProfile.customCapeId = selectedSlot; - }else { + } else { EaglerProfile.presetCapeId = selectedSlot - customLen; EaglerProfile.customCapeId = -1; } } + private void updateOptions() { + int numCustom = EaglerProfile.customCapes.size(); + String[] n = new String[numCustom + DefaultCapes.defaultCapesMap.length]; + for (int i = 0; i < numCustom; ++i) { + n[i] = EaglerProfile.customCapes.get(i).name; + } + int numDefault = DefaultCapes.defaultCapesMap.length; + for (int j = 0; j < numDefault; ++j) { + n[numCustom + j] = DefaultCapes.defaultCapesMap[j].name; + } + dropDownOptions = n; + } + + public void updateScreen() { + if (EagRuntime.fileChooserHasResult()) { + FileChooserResult result = EagRuntime.getFileChooserResult(); + if (result != null) { + ImageData loadedCape = ImageData.loadImageFile(result.fileData, + ImageData.getMimeFromType(result.fileName)); + if (loadedCape != null) { + if ((loadedCape.width == 32 || loadedCape.width == 64) && loadedCape.height == 32) { + byte[] resized = new byte[1173]; + SkinConverter.convertCape32x32RGBAto23x17RGB(loadedCape, resized); + int k; + if ((k = EaglerProfile.addCustomCape(result.fileName, resized)) != -1) { + selectedSlot = k; + updateOptions(); + safeProfile(); + } + } else { + EagRuntime.showPopup("The selected image '" + result.fileName + + "' is not the right size!\nEaglercraft only supports 32x32 or 64x32 capes"); + } + } else { + EagRuntime.showPopup("The selected file '" + result.fileName + "' is not a supported format!"); + } + } + } + if (dropDownOpen) { + if (PointerInputAbstraction.getVCursorButtonDown(0)) { + int skinX = width / 2 - 20; + int skinY = height / 6 + 73; + int skinWidth = 140; + if (mousex >= (skinX + skinWidth - 10) && mousex < (skinX + skinWidth) && mousey >= skinY + && mousey < (skinY + skinsHeight)) { + dragging = true; + } + if (dragging) { + int scrollerSize = skinsHeight * slotsVisible / dropDownOptions.length; + scrollPos = (mousey - skinY - (scrollerSize / 2)) * dropDownOptions.length / skinsHeight; + } + } else { + dragging = false; + } + } else { + dragging = false; + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditProfile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditProfile.java index 4910f395..f806b7ae 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditProfile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenEditProfile.java @@ -1,5 +1,11 @@ package net.lax1dude.eaglercraft.v1_8.profile; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_DEPTH_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; + +import java.io.IOException; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.Keyboard; import net.lax1dude.eaglercraft.v1_8.Mouse; @@ -17,30 +23,28 @@ import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - -import java.io.IOException; - /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenEditProfile extends GuiScreen { + private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); private final GuiScreen parent; - private GuiTextField usernameField; + private GuiTextField usernameField; private boolean dropDownOpen = false; private String[] dropDownOptions; private int slotsVisible = 0; @@ -49,276 +53,31 @@ public class GuiScreenEditProfile extends GuiScreen { private int skinsHeight = 0; private boolean dragging = false; private int mousex = 0; + private int mousey = 0; private boolean newSkinWaitSteveOrAlex = false; - private static final ResourceLocation eaglerGui = new ResourceLocation("eagler:gui/eagler_gui.png"); - protected String screenTitle = "Edit Profile"; public GuiScreenEditProfile(GuiScreen parent) { this.parent = parent; } - public void initGui() { - Keyboard.enableRepeatEvents(true); - screenTitle = I18n.format("editProfile.title"); - usernameField = new GuiTextField(0, fontRendererObj, width / 2 - 20 + 1, height / 6 + 24 + 1, 138, 20); - usernameField.setFocused(true); - usernameField.setText(EaglerProfile.getName()); - usernameField.setMaxStringLength(16); - selectedSlot = EaglerProfile.presetSkinId == -1 ? EaglerProfile.customSkinId : (EaglerProfile.presetSkinId + EaglerProfile.customSkins.size()); - buttonList.add(new GuiButton(0, width / 2 - 100, height / 6 + 168, I18n.format("gui.done"))); - buttonList.add(new GuiButton(1, width / 2 - 21, height / 6 + 110, 71, 20, I18n.format("editProfile.addSkin"))); - buttonList.add(new GuiButton(2, width / 2 - 21 + 71, height / 6 + 110, 72, 20, I18n.format("editProfile.clearSkin"))); - updateOptions(); - } - - private void updateOptions() { - DefaultSkins[] arr = DefaultSkins.defaultSkinsMap; - if(!EagRuntime.getConfiguration().isAllowFNAWSkins()) { - DefaultSkins[] arrNoFNAW = new DefaultSkins[arr.length - 5]; - System.arraycopy(arr, 0, arrNoFNAW, 0, arrNoFNAW.length); - arr = arrNoFNAW; - } - int numCustom = EaglerProfile.customSkins.size(); - String[] n = new String[numCustom + arr.length]; - for(int i = 0; i < numCustom; ++i) { - n[i] = EaglerProfile.customSkins.get(i).name; - } - int numDefault = arr.length; - for(int j = 0; j < numDefault; ++j) { - n[numCustom + j] = arr[j].name; - } - dropDownOptions = n; - } - - public void drawScreen(int mx, int my, float partialTicks) { - drawDefaultBackground(); - drawCenteredString(fontRendererObj, screenTitle, width / 2, 15, 16777215); - drawString(fontRendererObj, I18n.format("editProfile.username"), width / 2 - 20, height / 6 + 8, 10526880); - drawString(fontRendererObj, I18n.format("editProfile.playerSkin"), width / 2 - 20, height / 6 + 66, 10526880); - - mousex = mx; - mousey = my; - - int skinX = width / 2 - 120; - int skinY = height / 6 + 8; - int skinWidth = 80; - int skinHeight = 130; - - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xFFA0A0A0); - drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, 0xFF000015); - - GlStateManager.pushMatrix(); - GlStateManager.translate(skinX + 2, skinY - 9, 0.0f); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - - if(selectedSlot > dropDownOptions.length - 1) { - selectedSlot = 0; - } - - int numberOfCustomSkins = EaglerProfile.customSkins.size(); - int skid = selectedSlot - numberOfCustomSkins; - SkinModel selectedSkinModel = skid < 0 ? EaglerProfile.customSkins.get(selectedSlot).model : DefaultSkins.getSkinFromId(skid).model; - if(selectedSkinModel == SkinModel.STEVE || selectedSkinModel == SkinModel.ALEX || (selectedSkinModel.highPoly != null && !this.mc.gameSettings.enableFNAWSkins)) { - String capesText = I18n.format("editProfile.capes"); - int color = 10526880; - if(mx > skinX - 10 && my > skinY - 16 && mx < skinX + (fontRendererObj.getStringWidth(capesText) * 0.75f) + 10 && my < skinY + 7) { - color = 0xFFCCCC44; - Mouse.showCursor(EnumCursorType.HAND); - } - this.drawString(this.fontRendererObj, EnumChatFormatting.UNDERLINE + capesText, 0, 0, color); - } - - GlStateManager.popMatrix(); - - usernameField.drawTextBox(); - if(dropDownOpen || newSkinWaitSteveOrAlex) { - super.drawScreen(0, 0, partialTicks); - }else { - super.drawScreen(mx, my, partialTicks); - } - - if(selectedSkinModel.highPoly != null) { - drawCenteredString(fontRendererObj, I18n.format(this.mc.gameSettings.enableFNAWSkins ? "editProfile.disableFNAW" : "editProfile.enableFNAW"), width / 2, height / 6 + 150, 10526880); - } - - skinX = width / 2 - 20; - skinY = height / 6 + 82; - skinWidth = 140; - skinHeight = 22; - - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); - drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 21, skinY + skinHeight - 1, -16777216); - drawRect(skinX + skinWidth - 20, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); - - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - mc.getTextureManager().bindTexture(eaglerGui); - drawTexturedModalRect(skinX + skinWidth - 18, skinY + 3, 0, 0, 16, 16); - - drawString(fontRendererObj, dropDownOptions[selectedSlot], skinX + 5, skinY + 7, 14737632); - - skinX = width / 2 - 20; - skinY = height / 6 + 103; - skinWidth = 140; - skinHeight = (height - skinY - 10); - slotsVisible = (skinHeight / 10); - if(slotsVisible > dropDownOptions.length) slotsVisible = dropDownOptions.length; - skinHeight = slotsVisible * 10 + 7; - skinsHeight = skinHeight; - if(scrollPos == -1) { - scrollPos = selectedSlot - 2; - } - if(scrollPos > (dropDownOptions.length - slotsVisible)) { - scrollPos = (dropDownOptions.length - slotsVisible); - } - if(scrollPos < 0) { - scrollPos = 0; - } - if(dropDownOpen) { - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); - drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); - for(int i = 0; i < slotsVisible; i++) { - if(i + scrollPos < dropDownOptions.length) { - if(selectedSlot == i + scrollPos) { - drawRect(skinX + 1, skinY + i*10 + 4, skinX + skinWidth - 1, skinY + i*10 + 14, 0x77ffffff); - }else if(mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i*10 + 5) && my < (skinY + i*10 + 15)) { - drawRect(skinX + 1, skinY + i*10 + 4, skinX + skinWidth - 1, skinY + i*10 + 14, 0x55ffffff); - } - drawString(fontRendererObj, dropDownOptions[i + scrollPos], skinX + 5, skinY + 5 + i*10, 14737632); - } - } - int scrollerSize = skinHeight * slotsVisible / dropDownOptions.length; - int scrollerPos = skinHeight * scrollPos / dropDownOptions.length; - drawRect(skinX + skinWidth - 4, skinY + scrollerPos + 1, skinX + skinWidth - 1, skinY + scrollerPos + scrollerSize, 0xff888888); - } - - if(!EagRuntime.getConfiguration().isDemo()) { - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - String text = I18n.format("editProfile.importExport"); - - int w = mc.fontRendererObj.getStringWidth(text); - boolean hover = mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12; - if(hover) { - Mouse.showCursor(EnumCursorType.HAND); - } - - drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); - - GlStateManager.popMatrix(); - } - - int xx = width / 2 - 80; - int yy = height / 6 + 130; - - if(newSkinWaitSteveOrAlex && selectedSlot < numberOfCustomSkins) { - skinWidth = 70; - skinHeight = 120; - - CustomSkin newSkin = EaglerProfile.customSkins.get(selectedSlot); - - GlStateManager.clear(GL_DEPTH_BUFFER_BIT); - - skinX = width / 2 - 90; - skinY = height / 4; - xx = skinX + 35; - yy = skinY + 117; - - boolean mouseOver = mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight; - int cc = mouseOver ? 0xFFDDDD99 : 0xFF555555; - - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - drawRect(0, 0, width, height, 0xbb000000); - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xbb000000); - GlStateManager.disableBlend(); - - drawRect(skinX, skinY, skinX + 1, skinY + skinHeight, cc); - drawRect(skinX, skinY, skinX + skinWidth, skinY + 1, cc); - drawRect(skinX + skinWidth - 1, skinY, skinX + skinWidth, skinY + skinHeight, cc); - drawRect(skinX, skinY + skinHeight - 1, skinX + skinWidth, skinY + skinHeight, cc); - - if(mouseOver) { - drawCenteredString(fontRendererObj, "Steve", skinX + skinWidth / 2, skinY + skinHeight + 6, cc); - } - - SkinPreviewRenderer.renderPreview(xx, yy, mx, my, false, SkinModel.STEVE, newSkin.getResource(), - EaglerProfile.getActiveCapeResourceLocation()); - - skinX = width / 2 + 20; - skinY = height / 4; - xx = skinX + 35; - yy = skinY + 117; - - mouseOver = mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight; - cc = mouseOver ? 0xFFDDDD99 : 0xFF555555; - - GlStateManager.enableBlend(); - GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xbb000000); - GlStateManager.disableBlend(); - - drawRect(skinX, skinY, skinX + 1, skinY + skinHeight, cc); - drawRect(skinX, skinY, skinX + skinWidth, skinY + 1, cc); - drawRect(skinX + skinWidth - 1, skinY, skinX + skinWidth, skinY + skinHeight, cc); - drawRect(skinX, skinY + skinHeight - 1, skinX + skinWidth, skinY + skinHeight, cc); - - if(mouseOver) { - drawCenteredString(fontRendererObj, "Alex", skinX + skinWidth / 2, skinY + skinHeight + 8, cc); - } - - SkinPreviewRenderer.renderPreview(xx, yy, mx, my, false, SkinModel.ALEX, newSkin.getResource(), - EaglerProfile.getActiveCapeResourceLocation()); - }else { - skinX = this.width / 2 - 120; - skinY = this.height / 6 + 8; - skinWidth = 80; - skinHeight = 130; - - ResourceLocation texture; - if(skid < 0) { - texture = EaglerProfile.customSkins.get(selectedSlot).getResource(); - }else { - texture = DefaultSkins.getSkinFromId(skid).location; - } - - SkinPreviewRenderer.renderPreview(xx, yy, newSkinWaitSteveOrAlex ? width / 2 : mx, - newSkinWaitSteveOrAlex ? height / 2 : my, false, selectedSkinModel, texture, - EaglerProfile.getActiveCapeResourceLocation()); - } - - } - - public void handleMouseInput() throws IOException { - super.handleMouseInput(); - if(dropDownOpen) { - int var1 = Mouse.getEventDWheel(); - if(var1 < 0) { - scrollPos += 3; - } - if(var1 > 0) { - scrollPos -= 3; - if(scrollPos < 0) { - scrollPos = 0; - } - } - } - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(!dropDownOpen) { - if(par1GuiButton.id == 0) { + if (!dropDownOpen) { + if (par1GuiButton.id == 0) { safeProfile(); EaglerProfile.save(); - this.mc.displayGuiScreen((GuiScreen) parent); - }else if(par1GuiButton.id == 1) { + if (!this.mc.gameSettings.hideDefaultUsernameWarning + && EaglerProfile.isDefaultUsername(EaglerProfile.getName())) { + this.mc.displayGuiScreen(new GuiScreenDefaultUsernameNote(this, parent)); + } else { + this.mc.displayGuiScreen(parent); + } + } else if (par1GuiButton.id == 1) { EagRuntime.displayFileChooser("image/png", "png"); - }else if(par1GuiButton.id == 2) { + } else if (par1GuiButton.id == 2) { EaglerProfile.clearCustomSkins(); safeProfile(); EaglerProfile.save(); @@ -328,130 +87,312 @@ public class GuiScreenEditProfile extends GuiScreen { } } - public void updateScreen() { - usernameField.updateCursorCounter(); - if(EagRuntime.fileChooserHasResult()) { - FileChooserResult result = EagRuntime.getFileChooserResult(); - if(result != null) { - ImageData loadedSkin = ImageData.loadImageFile(result.fileData, ImageData.getMimeFromType(result.fileName)); - if(loadedSkin != null) { - boolean isLegacy = loadedSkin.width == 64 && loadedSkin.height == 32; - boolean isModern = loadedSkin.width == 64 && loadedSkin.height == 64; - if(isLegacy) { - ImageData newSkin = new ImageData(64, 64, true); - SkinConverter.convert64x32to64x64(loadedSkin, newSkin); - loadedSkin = newSkin; - isModern = true; - } - if(isModern) { - byte[] rawSkin = new byte[16384]; - for(int i = 0, j, k; i < 4096; ++i) { - j = i << 2; - k = loadedSkin.pixels[i]; - rawSkin[j] = (byte)(k >>> 24); - rawSkin[j + 1] = (byte)(k >>> 16); - rawSkin[j + 2] = (byte)(k >>> 8); - rawSkin[j + 3] = (byte)(k & 0xFF); - } - for(int y = 20; y < 32; ++y) { - for(int x = 16; x < 40; ++x) { - rawSkin[(y << 8) | (x << 2)] = (byte)0xff; - } - } - int k; - if((k = EaglerProfile.addCustomSkin(result.fileName, rawSkin)) != -1) { - selectedSlot = k; - newSkinWaitSteveOrAlex = true; - updateOptions(); - safeProfile(); - EaglerProfile.save(); - } - }else { - EagRuntime.showPopup("The selected image '" + result.fileName + "' is not the right size!\nEaglercraft only supports 64x32 or 64x64 skins"); - } - }else { - EagRuntime.showPopup("The selected file '" + result.fileName + "' is not a supported format!"); - } - } + public void drawScreen(int mx, int my, float partialTicks) { + drawDefaultBackground(); + drawCenteredString(fontRendererObj, screenTitle, width / 2, 15, 16777215); + drawString(fontRendererObj, I18n.format("editProfile.username"), width / 2 - 20, height / 6 + 8, 10526880); + drawString(fontRendererObj, I18n.format("editProfile.playerSkin"), width / 2 - 20, height / 6 + 66, 10526880); + + mousex = mx; + mousey = my; + + int skinX = width / 2 - 120; + int skinY = height / 6 + 8; + int skinWidth = 80; + int skinHeight = 130; + + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xFFA0A0A0); + drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, 0xFF000015); + + GlStateManager.pushMatrix(); + GlStateManager.translate(skinX + 2, skinY - 9, 0.0f); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + + if (selectedSlot > dropDownOptions.length - 1) { + selectedSlot = 0; } - if(dropDownOpen) { - if(PointerInputAbstraction.getVCursorButtonDown(0)) { - int skinX = width / 2 - 20; - int skinY = height / 6 + 103; - int skinWidth = 140; - if(mousex >= (skinX + skinWidth - 10) && mousex < (skinX + skinWidth) && mousey >= skinY && mousey < (skinY + skinsHeight)) { - dragging = true; - } - if(dragging) { - int scrollerSize = skinsHeight * slotsVisible / dropDownOptions.length; - scrollPos = (mousey - skinY - (scrollerSize / 2)) * dropDownOptions.length / skinsHeight; - } - }else { - dragging = false; + + int numberOfCustomSkins = EaglerProfile.customSkins.size(); + int skid = selectedSlot - numberOfCustomSkins; + SkinModel selectedSkinModel = skid < 0 ? EaglerProfile.customSkins.get(selectedSlot).model + : DefaultSkins.getSkinFromId(skid).model; + if (selectedSkinModel == SkinModel.STEVE || selectedSkinModel == SkinModel.ALEX + || (selectedSkinModel.highPoly != null && !this.mc.gameSettings.enableFNAWSkins)) { + String capesText = I18n.format("editProfile.capes"); + int color = 10526880; + if (mx > skinX - 10 && my > skinY - 16 + && mx < skinX + (fontRendererObj.getStringWidth(capesText) * 0.75f) + 10 && my < skinY + 7) { + color = 0xFFCCCC44; + Mouse.showCursor(EnumCursorType.HAND); + } + this.drawString(this.fontRendererObj, EnumChatFormatting.UNDERLINE + capesText, 0, 0, color); + } + + GlStateManager.popMatrix(); + + usernameField.drawTextBox(); + if (dropDownOpen || newSkinWaitSteveOrAlex) { + super.drawScreen(0, 0, partialTicks); + } else { + super.drawScreen(mx, my, partialTicks); + } + + if (selectedSkinModel.highPoly != null) { + drawCenteredString(fontRendererObj, I18n.format( + this.mc.gameSettings.enableFNAWSkins ? "editProfile.disableFNAW" : "editProfile.enableFNAW"), + width / 2, height / 6 + 150, 10526880); + } + + skinX = width / 2 - 20; + skinY = height / 6 + 82; + skinWidth = 140; + skinHeight = 22; + + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); + drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 21, skinY + skinHeight - 1, -16777216); + drawRect(skinX + skinWidth - 20, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); + + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + mc.getTextureManager().bindTexture(eaglerGui); + drawTexturedModalRect(skinX + skinWidth - 18, skinY + 3, 0, 0, 16, 16); + + drawString(fontRendererObj, dropDownOptions[selectedSlot], skinX + 5, skinY + 7, 14737632); + + skinX = width / 2 - 20; + skinY = height / 6 + 103; + skinWidth = 140; + skinHeight = (height - skinY - 10); + slotsVisible = (skinHeight / 10); + if (slotsVisible > dropDownOptions.length) + slotsVisible = dropDownOptions.length; + skinHeight = slotsVisible * 10 + 7; + skinsHeight = skinHeight; + if (scrollPos == -1) { + scrollPos = selectedSlot - 2; + } + if (scrollPos > (dropDownOptions.length - slotsVisible)) { + scrollPos = (dropDownOptions.length - slotsVisible); + } + if (scrollPos < 0) { + scrollPos = 0; + } + if (dropDownOpen) { + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, -6250336); + drawRect(skinX + 1, skinY + 1, skinX + skinWidth - 1, skinY + skinHeight - 1, -16777216); + for (int i = 0; i < slotsVisible; i++) { + if (i + scrollPos < dropDownOptions.length) { + if (selectedSlot == i + scrollPos) { + drawRect(skinX + 1, skinY + i * 10 + 4, skinX + skinWidth - 1, skinY + i * 10 + 14, 0x77ffffff); + } else if (mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i * 10 + 5) + && my < (skinY + i * 10 + 15)) { + drawRect(skinX + 1, skinY + i * 10 + 4, skinX + skinWidth - 1, skinY + i * 10 + 14, 0x55ffffff); + } + drawString(fontRendererObj, dropDownOptions[i + scrollPos], skinX + 5, skinY + 5 + i * 10, + 14737632); + } + } + int scrollerSize = skinHeight * slotsVisible / dropDownOptions.length; + int scrollerPos = skinHeight * scrollPos / dropDownOptions.length; + drawRect(skinX + skinWidth - 4, skinY + scrollerPos + 1, skinX + skinWidth - 1, + skinY + scrollerPos + scrollerSize, 0xff888888); + } + + if (!EagRuntime.getConfiguration().isDemo()) { + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + String text = I18n.format("editProfile.importExport"); + + int w = mc.fontRendererObj.getStringWidth(text); + boolean hover = mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12; + if (hover) { + Mouse.showCursor(EnumCursorType.HAND); + } + + drawString(mc.fontRendererObj, EnumChatFormatting.UNDERLINE + text, 5, 5, hover ? 0xFFEEEE22 : 0xFFCCCCCC); + + GlStateManager.popMatrix(); + } + + int xx = width / 2 - 80; + int yy = height / 6 + 130; + + if (newSkinWaitSteveOrAlex && selectedSlot < numberOfCustomSkins) { + skinWidth = 70; + skinHeight = 120; + + CustomSkin newSkin = EaglerProfile.customSkins.get(selectedSlot); + + GlStateManager.clear(GL_DEPTH_BUFFER_BIT); + + skinX = width / 2 - 90; + skinY = height / 4; + xx = skinX + 35; + yy = skinY + 117; + + boolean mouseOver = mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight; + int cc = mouseOver ? 0xFFDDDD99 : 0xFF555555; + + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + drawRect(0, 0, width, height, 0xbb000000); + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xbb000000); + GlStateManager.disableBlend(); + + drawRect(skinX, skinY, skinX + 1, skinY + skinHeight, cc); + drawRect(skinX, skinY, skinX + skinWidth, skinY + 1, cc); + drawRect(skinX + skinWidth - 1, skinY, skinX + skinWidth, skinY + skinHeight, cc); + drawRect(skinX, skinY + skinHeight - 1, skinX + skinWidth, skinY + skinHeight, cc); + + if (mouseOver) { + drawCenteredString(fontRendererObj, "Steve", skinX + skinWidth / 2, skinY + skinHeight + 6, cc); + } + + SkinPreviewRenderer.renderPreview(xx, yy, mx, my, false, SkinModel.STEVE, newSkin.getResource(), + EaglerProfile.getActiveCapeResourceLocation()); + + skinX = width / 2 + 20; + skinY = height / 4; + xx = skinX + 35; + yy = skinY + 117; + + mouseOver = mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight; + cc = mouseOver ? 0xFFDDDD99 : 0xFF555555; + + GlStateManager.enableBlend(); + GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + drawRect(skinX, skinY, skinX + skinWidth, skinY + skinHeight, 0xbb000000); + GlStateManager.disableBlend(); + + drawRect(skinX, skinY, skinX + 1, skinY + skinHeight, cc); + drawRect(skinX, skinY, skinX + skinWidth, skinY + 1, cc); + drawRect(skinX + skinWidth - 1, skinY, skinX + skinWidth, skinY + skinHeight, cc); + drawRect(skinX, skinY + skinHeight - 1, skinX + skinWidth, skinY + skinHeight, cc); + + if (mouseOver) { + drawCenteredString(fontRendererObj, "Alex", skinX + skinWidth / 2, skinY + skinHeight + 8, cc); + } + + SkinPreviewRenderer.renderPreview(xx, yy, mx, my, false, SkinModel.ALEX, newSkin.getResource(), + EaglerProfile.getActiveCapeResourceLocation()); + } else { + skinX = this.width / 2 - 120; + skinY = this.height / 6 + 8; + skinWidth = 80; + skinHeight = 130; + + ResourceLocation texture; + if (skid < 0) { + texture = EaglerProfile.customSkins.get(selectedSlot).getResource(); + } else { + texture = DefaultSkins.getSkinFromId(skid).location; + } + + SkinPreviewRenderer.renderPreview(xx, yy, newSkinWaitSteveOrAlex ? width / 2 : mx, + newSkinWaitSteveOrAlex ? height / 2 : my, false, selectedSkinModel, texture, + EaglerProfile.getActiveCapeResourceLocation()); + } + + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + usernameField.fireInputEvent(event, param); + } + + public void handleMouseInput() throws IOException { + super.handleMouseInput(); + if (dropDownOpen) { + int var1 = Mouse.getEventDWheel(); + if (var1 < 0) { + scrollPos += 3; + } + if (var1 > 0) { + scrollPos -= 3; + if (scrollPos < 0) { + scrollPos = 0; + } } - }else { - dragging = false; } } - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); + public void initGui() { + Keyboard.enableRepeatEvents(true); + screenTitle = I18n.format("editProfile.title"); + usernameField = new GuiTextField(0, fontRendererObj, width / 2 - 20 + 1, height / 6 + 24 + 1, 138, 20); + usernameField.setFocused(true); + usernameField.setText(EaglerProfile.getName()); + usernameField.setMaxStringLength(16); + selectedSlot = EaglerProfile.presetSkinId == -1 ? EaglerProfile.customSkinId + : (EaglerProfile.presetSkinId + EaglerProfile.customSkins.size()); + buttonList.add(new GuiButton(0, width / 2 - 100, height / 6 + 168, I18n.format("gui.done"))); + buttonList.add(new GuiButton(1, width / 2 - 21, height / 6 + 110, 71, 20, I18n.format("editProfile.addSkin"))); + buttonList.add( + new GuiButton(2, width / 2 - 21 + 71, height / 6 + 110, 72, 20, I18n.format("editProfile.clearSkin"))); + updateOptions(); } protected void keyTyped(char c, int k) { usernameField.textboxKeyTyped(c, k); - + String text = usernameField.getText(); - if(text.length() > 16) text = text.substring(0, 16); + if (text.length() > 16) + text = text.substring(0, 16); text = text.replaceAll("[^A-Za-z0-9]", "_"); usernameField.updateText(text); - - if(k == 200 && selectedSlot > 0) { + + if (k == 200 && selectedSlot > 0) { --selectedSlot; scrollPos = selectedSlot - 2; } - if(k == 208 && selectedSlot < (dropDownOptions.length - 1)) { + if (k == 208 && selectedSlot < (dropDownOptions.length - 1)) { ++selectedSlot; scrollPos = selectedSlot - 2; } } - + protected void mouseClicked(int mx, int my, int button) { usernameField.mouseClicked(mx, my, button); if (button == 0) { - if(!EagRuntime.getConfiguration().isDemo()) { + if (!EagRuntime.getConfiguration().isDemo()) { int w = mc.fontRendererObj.getStringWidth(I18n.format("editProfile.importExport")); - if(mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12) { + if (mx > 1 && my > 1 && mx < (w * 3 / 4) + 7 && my < 12) { safeProfile(); EaglerProfile.save(); mc.displayGuiScreen(new GuiScreenImportExportProfile(this)); - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); return; } } - + int skinX, skinY; int skid = selectedSlot - EaglerProfile.customSkins.size(); - SkinModel selectedSkinModel = skid < 0 ? EaglerProfile.customSkins.get(selectedSlot).model : DefaultSkins.getSkinFromId(skid).model; - if(selectedSkinModel == SkinModel.STEVE || selectedSkinModel == SkinModel.ALEX || (selectedSkinModel.highPoly != null && !this.mc.gameSettings.enableFNAWSkins)) { + SkinModel selectedSkinModel = skid < 0 ? EaglerProfile.customSkins.get(selectedSlot).model + : DefaultSkins.getSkinFromId(skid).model; + if (selectedSkinModel == SkinModel.STEVE || selectedSkinModel == SkinModel.ALEX + || (selectedSkinModel.highPoly != null && !this.mc.gameSettings.enableFNAWSkins)) { skinX = this.width / 2 - 120; skinY = this.height / 6 + 8; String capesText = I18n.format("editProfile.capes"); - if(mx > skinX - 10 && my > skinY - 16 && mx < skinX + (fontRendererObj.getStringWidth(capesText) * 0.75f) + 10 && my < skinY + 7) { + if (mx > skinX - 10 && my > skinY - 16 + && mx < skinX + (fontRendererObj.getStringWidth(capesText) * 0.75f) + 10 && my < skinY + 7) { safeProfile(); this.mc.displayGuiScreen(new GuiScreenEditCape(this)); - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); return; } } - - if(newSkinWaitSteveOrAlex) { + + if (newSkinWaitSteveOrAlex) { skinX = width / 2 - 90; skinY = height / 4; int skinWidth = 70; int skinHeight = 120; - if(mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight) { - if(selectedSlot < EaglerProfile.customSkins.size()) { + if (mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight) { + if (selectedSlot < EaglerProfile.customSkins.size()) { newSkinWaitSteveOrAlex = false; EaglerProfile.customSkins.get(selectedSlot).model = SkinModel.STEVE; safeProfile(); @@ -460,21 +401,21 @@ public class GuiScreenEditProfile extends GuiScreen { } skinX = width / 2 + 20; skinY = height / 4; - if(mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight) { - if(selectedSlot < EaglerProfile.customSkins.size()) { + if (mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight) { + if (selectedSlot < EaglerProfile.customSkins.size()) { EaglerProfile.customSkins.get(selectedSlot).model = SkinModel.ALEX; newSkinWaitSteveOrAlex = false; safeProfile(); } } return; - }else if(selectedSlot < EaglerProfile.customSkins.size()) { + } else if (selectedSlot < EaglerProfile.customSkins.size()) { skinX = width / 2 - 120; skinY = height / 6 + 18; int skinWidth = 80; int skinHeight = 120; - if(mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight) { - if(selectedSlot < EaglerProfile.customSkins.size()) { + if (mx >= skinX && my >= skinY && mx < skinX + skinWidth && my < skinY + skinHeight) { + if (selectedSlot < EaglerProfile.customSkins.size()) { newSkinWaitSteveOrAlex = true; return; } @@ -482,28 +423,29 @@ public class GuiScreenEditProfile extends GuiScreen { } skinX = width / 2 + 140 - 40; skinY = height / 6 + 82; - - if(mx >= skinX && mx < (skinX + 20) && my >= skinY && my < (skinY + 22)) { + + if (mx >= skinX && mx < (skinX + 20) && my >= skinY && my < (skinY + 22)) { dropDownOpen = !dropDownOpen; return; } - + skinX = width / 2 - 20; skinY = height / 6 + 82; int skinWidth = 140; int skinHeight = skinsHeight; - - if(!(mx >= skinX && mx < (skinX + skinWidth) && my >= skinY && my < (skinY + skinHeight + 22))) { + + if (!(mx >= skinX && mx < (skinX + skinWidth) && my >= skinY && my < (skinY + skinHeight + 22))) { dragging = false; - if(dropDownOpen) { + if (dropDownOpen) { dropDownOpen = false; return; } - }else if(dropDownOpen && !dragging) { + } else if (dropDownOpen && !dragging) { skinY += 21; - for(int i = 0; i < slotsVisible; i++) { - if(i + scrollPos < dropDownOptions.length) { - if(mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i * 10 + 5) && my < (skinY + i * 10 + 15)) { + for (int i = 0; i < slotsVisible; i++) { + if (i + scrollPos < dropDownOptions.length) { + if (mx >= skinX && mx < (skinX + skinWidth - 10) && my >= (skinY + i * 10 + 5) + && my < (skinY + i * 10 + 15)) { selectedSlot = i + scrollPos; dropDownOpen = false; dragging = false; @@ -515,21 +457,25 @@ public class GuiScreenEditProfile extends GuiScreen { } super.mouseClicked(mx, my, button); } - + + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + } + protected void safeProfile() { int customLen = EaglerProfile.customSkins.size(); - if(selectedSlot < customLen) { + if (selectedSlot < customLen) { EaglerProfile.presetSkinId = -1; EaglerProfile.customSkinId = selectedSlot; - }else { + } else { EaglerProfile.presetSkinId = selectedSlot - customLen; EaglerProfile.customSkinId = -1; } String name = usernameField.getText().trim(); - while(name.length() < 3) { + while (name.length() < 3) { name = name + "_"; } - if(name.length() > 16) { + if (name.length() > 16) { name = name.substring(0, 16); } EaglerProfile.setName(name); @@ -540,9 +486,92 @@ public class GuiScreenEditProfile extends GuiScreen { return usernameField.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - usernameField.fireInputEvent(event, param); + private void updateOptions() { + DefaultSkins[] arr = DefaultSkins.defaultSkinsMap; + if (!EagRuntime.getConfiguration().isAllowFNAWSkins()) { + DefaultSkins[] arrNoFNAW = new DefaultSkins[arr.length - 5]; + System.arraycopy(arr, 0, arrNoFNAW, 0, arrNoFNAW.length); + arr = arrNoFNAW; + } + int numCustom = EaglerProfile.customSkins.size(); + String[] n = new String[numCustom + arr.length]; + for (int i = 0; i < numCustom; ++i) { + n[i] = EaglerProfile.customSkins.get(i).name; + } + int numDefault = arr.length; + for (int j = 0; j < numDefault; ++j) { + n[numCustom + j] = arr[j].name; + } + dropDownOptions = n; + } + + public void updateScreen() { + usernameField.updateCursorCounter(); + if (EagRuntime.fileChooserHasResult()) { + FileChooserResult result = EagRuntime.getFileChooserResult(); + if (result != null) { + ImageData loadedSkin = ImageData.loadImageFile(result.fileData, + ImageData.getMimeFromType(result.fileName)); + if (loadedSkin != null) { + boolean isLegacy = loadedSkin.width == 64 && loadedSkin.height == 32; + boolean isModern = loadedSkin.width == 64 && loadedSkin.height == 64; + if (isLegacy) { + ImageData newSkin = new ImageData(64, 64, true); + SkinConverter.convert64x32to64x64(loadedSkin, newSkin); + loadedSkin = newSkin; + isModern = true; + } + if (isModern) { + byte[] rawSkin = new byte[16384]; + for (int i = 0, j, k; i < 4096; ++i) { + j = i << 2; + k = loadedSkin.pixels[i]; + rawSkin[j] = (byte) (k >>> 24); + rawSkin[j + 1] = (byte) (k >>> 16); + rawSkin[j + 2] = (byte) (k >>> 8); + rawSkin[j + 3] = (byte) (k & 0xFF); + } + for (int y = 20; y < 32; ++y) { + for (int x = 16; x < 40; ++x) { + rawSkin[(y << 8) | (x << 2)] = (byte) 0xff; + } + } + int k; + if ((k = EaglerProfile.addCustomSkin(result.fileName, rawSkin)) != -1) { + selectedSlot = k; + newSkinWaitSteveOrAlex = true; + updateOptions(); + safeProfile(); + EaglerProfile.save(); + } + } else { + EagRuntime.showPopup("The selected image '" + result.fileName + + "' is not the right size!\nEaglercraft only supports 64x32 or 64x64 skins"); + } + } else { + EagRuntime.showPopup("The selected file '" + result.fileName + "' is not a supported format!"); + } + } + } + if (dropDownOpen) { + if (PointerInputAbstraction.getVCursorButtonDown(0)) { + int skinX = width / 2 - 20; + int skinY = height / 6 + 103; + int skinWidth = 140; + if (mousex >= (skinX + skinWidth - 10) && mousex < (skinX + skinWidth) && mousey >= skinY + && mousey < (skinY + skinsHeight)) { + dragging = true; + } + if (dragging) { + int scrollerSize = skinsHeight * slotsVisible / dropDownOptions.length; + scrollPos = (mousey - skinY - (scrollerSize / 2)) * dropDownOptions.length / skinsHeight; + } + } else { + dragging = false; + } + } else { + dragging = false; + } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenExportProfile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenExportProfile.java index e2fd9d0f..fd63ca01 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenExportProfile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenExportProfile.java @@ -12,14 +12,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,50 +42,67 @@ public class GuiScreenExportProfile extends GuiScreen { this.back = back; } - public void initGui() { - this.buttonList.add(exportProfile = new GuiButton(2, this.width / 2 - 100, this.height / 4, I18n.format("settingsBackup.export.option.profile") + " " + I18n.format(doExportProfile ? "gui.yes" : "gui.no"))); - this.buttonList.add(exportSettings = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 25, I18n.format("settingsBackup.export.option.settings") + " " + I18n.format(doExportSettings ? "gui.yes" : "gui.no"))); - this.buttonList.add(exportServers = new GuiButton(4, this.width / 2 - 100, this.height / 4 + 50, I18n.format("settingsBackup.export.option.servers") + " " + I18n.format(doExportServers ? "gui.yes" : "gui.no"))); - this.buttonList.add(exportResourcePacks = new GuiButton(5, this.width / 2 - 100, this.height / 4 + 75, I18n.format("settingsBackup.export.option.resourcePacks") + " " + I18n.format(doExportResourcePacks ? "gui.yes" : "gui.no"))); - exportResourcePacks.enabled = EaglerFolderResourcePack.isSupported(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 115, I18n.format("settingsBackup.export.option.export"))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 140, I18n.format("gui.cancel"))); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - if(!doExportProfile && !doExportSettings && !doExportServers && !doExportResourcePacks) { + if (par1GuiButton.id == 0) { + if (!doExportProfile && !doExportSettings && !doExportServers && !doExportResourcePacks) { mc.displayGuiScreen(back); - }else { - mc.loadingScreen.eaglerShow(I18n.format("settingsBackup.exporting.1"), I18n.format("settingsBackup.exporting.2")); + } else { + mc.loadingScreen.eaglerShow(I18n.format("settingsBackup.exporting.1"), + I18n.format("settingsBackup.exporting.2")); try { - ProfileExporter.exportProfileAndSettings(doExportProfile, doExportSettings, doExportServers, doExportResourcePacks); + ProfileExporter.exportProfileAndSettings(doExportProfile, doExportSettings, doExportServers, + doExportResourcePacks); mc.displayGuiScreen(back); } catch (IOException e) { EagRuntime.debugPrintStackTrace(e); - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("settingsBackup.exporting.failed.1", "settingsBackup.exporting.failed.2", back)); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("settingsBackup.exporting.failed.1", + "settingsBackup.exporting.failed.2", back)); } } - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { mc.displayGuiScreen(back); - }else if(par1GuiButton.id == 2) { + } else if (par1GuiButton.id == 2) { doExportProfile = !doExportProfile; - exportProfile.displayString = I18n.format("settingsBackup.export.option.profile") + " " + I18n.format(doExportProfile ? "gui.yes" : "gui.no"); - }else if(par1GuiButton.id == 3) { + exportProfile.displayString = I18n.format("settingsBackup.export.option.profile") + " " + + I18n.format(doExportProfile ? "gui.yes" : "gui.no"); + } else if (par1GuiButton.id == 3) { doExportSettings = !doExportSettings; - exportSettings.displayString = I18n.format("settingsBackup.export.option.settings") + " " + I18n.format(doExportSettings ? "gui.yes" : "gui.no"); - }else if(par1GuiButton.id == 4) { + exportSettings.displayString = I18n.format("settingsBackup.export.option.settings") + " " + + I18n.format(doExportSettings ? "gui.yes" : "gui.no"); + } else if (par1GuiButton.id == 4) { doExportServers = !doExportServers; - exportServers.displayString = I18n.format("settingsBackup.export.option.servers") + " " + I18n.format(doExportServers ? "gui.yes" : "gui.no"); - }else if(par1GuiButton.id == 5) { + exportServers.displayString = I18n.format("settingsBackup.export.option.servers") + " " + + I18n.format(doExportServers ? "gui.yes" : "gui.no"); + } else if (par1GuiButton.id == 5) { doExportResourcePacks = !doExportResourcePacks; - exportResourcePacks.displayString = I18n.format("settingsBackup.export.option.resourcePacks") + " " + I18n.format(doExportResourcePacks ? "gui.yes" : "gui.no"); + exportResourcePacks.displayString = I18n.format("settingsBackup.export.option.resourcePacks") + " " + + I18n.format(doExportResourcePacks ? "gui.yes" : "gui.no"); } } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("settingsBackup.export.title"), this.width / 2, this.height / 4 - 25, 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("settingsBackup.export.title"), this.width / 2, + this.height / 4 - 25, 16777215); super.drawScreen(par1, par2, par3); } + + public void initGui() { + this.buttonList.add(exportProfile = new GuiButton(2, this.width / 2 - 100, this.height / 4, + I18n.format("settingsBackup.export.option.profile") + " " + + I18n.format(doExportProfile ? "gui.yes" : "gui.no"))); + this.buttonList.add(exportSettings = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 25, + I18n.format("settingsBackup.export.option.settings") + " " + + I18n.format(doExportSettings ? "gui.yes" : "gui.no"))); + this.buttonList.add(exportServers = new GuiButton(4, this.width / 2 - 100, this.height / 4 + 50, + I18n.format("settingsBackup.export.option.servers") + " " + + I18n.format(doExportServers ? "gui.yes" : "gui.no"))); + this.buttonList.add(exportResourcePacks = new GuiButton(5, this.width / 2 - 100, this.height / 4 + 75, + I18n.format("settingsBackup.export.option.resourcePacks") + " " + + I18n.format(doExportResourcePacks ? "gui.yes" : "gui.no"))); + exportResourcePacks.enabled = EaglerFolderResourcePack.isSupported(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 115, + I18n.format("settingsBackup.export.option.export"))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 140, I18n.format("gui.cancel"))); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportExportProfile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportExportProfile.java index eed4aae6..b1a8abf9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportExportProfile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportExportProfile.java @@ -12,14 +12,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,50 +34,54 @@ public class GuiScreenImportExportProfile extends GuiScreen { this.back = back; } - public void initGui() { - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 40, I18n.format("settingsBackup.importExport.import"))); - this.buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 4 + 65, I18n.format("settingsBackup.importExport.export"))); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 130, I18n.format("gui.cancel"))); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { mc.displayGuiScreen(back); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { waitingForFile = true; EagRuntime.displayFileChooser(null, "epk"); - }else if(par1GuiButton.id == 2) { + } else if (par1GuiButton.id == 2) { mc.displayGuiScreen(new GuiScreenExportProfile(back)); } } - public void updateScreen() { - if(waitingForFile && EagRuntime.fileChooserHasResult()) { - waitingForFile = false; - FileChooserResult result = EagRuntime.getFileChooserResult(); - if(result != null) { - mc.loadingScreen.eaglerShow(I18n.format("settingsBackup.importing.1"), "settingsBackup.importing.2"); - ProfileImporter importer = new ProfileImporter(result.fileData); - try { - importer.readHeader(); - mc.displayGuiScreen(new GuiScreenImportProfile(importer, back)); - }catch(IOException ex) { - try { - importer.close(); - } catch (IOException e) { - } - EagRuntime.debugPrintStackTrace(ex); - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("settingsBackup.importing.failed.1", "settingsBackup.importing.failed.2", back)); - } - } - } - } - public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); - - this.drawCenteredString(this.fontRendererObj, I18n.format("settingsBackup.importExport.title"), this.width / 2, this.height / 4, 16777215); - + + this.drawCenteredString(this.fontRendererObj, I18n.format("settingsBackup.importExport.title"), this.width / 2, + this.height / 4, 16777215); + super.drawScreen(par1, par2, par3); } + + public void initGui() { + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 40, + I18n.format("settingsBackup.importExport.import"))); + this.buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 4 + 65, + I18n.format("settingsBackup.importExport.export"))); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 130, I18n.format("gui.cancel"))); + } + + public void updateScreen() { + if (waitingForFile && EagRuntime.fileChooserHasResult()) { + waitingForFile = false; + FileChooserResult result = EagRuntime.getFileChooserResult(); + if (result != null) { + mc.loadingScreen.eaglerShow(I18n.format("settingsBackup.importing.1"), "settingsBackup.importing.2"); + ProfileImporter importer = new ProfileImporter(result.fileData); + try { + importer.readHeader(); + mc.displayGuiScreen(new GuiScreenImportProfile(importer, back)); + } catch (IOException ex) { + try { + importer.close(); + } catch (IOException e) { + } + EagRuntime.debugPrintStackTrace(ex); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("settingsBackup.importing.failed.1", + "settingsBackup.importing.failed.2", back)); + } + } + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportProfile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportProfile.java index a08dc915..14c65955 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportProfile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/GuiScreenImportProfile.java @@ -14,14 +14,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,16 +50,80 @@ public class GuiScreenImportProfile extends GuiScreen { this.doImportResourcePacks = importer.hasResourcePacks(); } + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + if (!doImportProfile && !doImportSettings && !doImportServers && !doImportResourcePacks) { + mc.displayGuiScreen(back); + } else { + mc.loadingScreen.eaglerShow(I18n.format("settingsBackup.importing.1"), + I18n.format("settingsBackup.importing.2")); + try { + List list1 = new ArrayList<>(mc.gameSettings.resourcePacks); + List list2 = new ArrayList<>(mc.gameSettings.field_183018_l); + importer.importProfileAndSettings(doImportProfile, doImportSettings, doImportServers, + doImportResourcePacks); + boolean resourcePacksChanged = !mc.gameSettings.resourcePacks.equals(list1) + || !mc.gameSettings.field_183018_l.equals(list2); + if (resourcePacksChanged || (doImportResourcePacks && (list1.size() > 0 || list2.size() > 0))) { + mc.loadingScreen.eaglerShow(I18n.format("resourcePack.load.refreshing"), + I18n.format("resourcePack.load.pleaseWait")); + mc.getResourcePackRepository().reconstruct(mc.gameSettings); + mc.refreshResources(); + } + mc.displayGuiScreen(back); + } catch (IOException e) { + EagRuntime.debugPrintStackTrace(e); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("settingsBackup.importing.failed.1", + "settingsBackup.importing.failed.2", back)); + } + } + } else if (par1GuiButton.id == 1) { + mc.displayGuiScreen(back); + } else if (par1GuiButton.id == 2) { + doImportProfile = !doImportProfile; + importProfile.displayString = I18n.format("settingsBackup.import.option.profile") + " " + + I18n.format(doImportProfile ? "gui.yes" : "gui.no"); + } else if (par1GuiButton.id == 3) { + doImportSettings = !doImportSettings; + importSettings.displayString = I18n.format("settingsBackup.import.option.settings") + " " + + I18n.format(doImportSettings ? "gui.yes" : "gui.no"); + } else if (par1GuiButton.id == 4) { + doImportServers = !doImportServers; + importServers.displayString = I18n.format("settingsBackup.import.option.servers") + " " + + I18n.format(doImportServers ? "gui.yes" : "gui.no"); + } else if (par1GuiButton.id == 5) { + doImportResourcePacks = !doImportResourcePacks; + importResourcePacks.displayString = I18n.format("settingsBackup.import.option.resourcePacks") + " " + + I18n.format(doImportResourcePacks ? "gui.yes" : "gui.no"); + } + } + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("settingsBackup.import.title"), this.width / 2, + this.height / 4 - 25, 16777215); + super.drawScreen(par1, par2, par3); + } + public void initGui() { - this.buttonList.add(importProfile = new GuiButton(2, this.width / 2 - 100, this.height / 4, I18n.format("settingsBackup.import.option.profile") + " " + I18n.format(doImportProfile ? "gui.yes" : "gui.no"))); + this.buttonList.add(importProfile = new GuiButton(2, this.width / 2 - 100, this.height / 4, + I18n.format("settingsBackup.import.option.profile") + " " + + I18n.format(doImportProfile ? "gui.yes" : "gui.no"))); importProfile.enabled = importer.hasProfile(); - this.buttonList.add(importSettings = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 25, I18n.format("settingsBackup.import.option.settings") + " " + I18n.format(doImportSettings ? "gui.yes" : "gui.no"))); + this.buttonList.add(importSettings = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 25, + I18n.format("settingsBackup.import.option.settings") + " " + + I18n.format(doImportSettings ? "gui.yes" : "gui.no"))); importSettings.enabled = importer.hasProfile(); - this.buttonList.add(importServers = new GuiButton(4, this.width / 2 - 100, this.height / 4 + 50, I18n.format("settingsBackup.import.option.servers") + " " + I18n.format(doImportServers ? "gui.yes" : "gui.no"))); + this.buttonList.add(importServers = new GuiButton(4, this.width / 2 - 100, this.height / 4 + 50, + I18n.format("settingsBackup.import.option.servers") + " " + + I18n.format(doImportServers ? "gui.yes" : "gui.no"))); importServers.enabled = importer.hasServers(); - this.buttonList.add(importResourcePacks = new GuiButton(5, this.width / 2 - 100, this.height / 4 + 75, I18n.format("settingsBackup.import.option.resourcePacks") + " " + I18n.format(doImportResourcePacks ? "gui.yes" : "gui.no"))); + this.buttonList.add(importResourcePacks = new GuiButton(5, this.width / 2 - 100, this.height / 4 + 75, + I18n.format("settingsBackup.import.option.resourcePacks") + " " + + I18n.format(doImportResourcePacks ? "gui.yes" : "gui.no"))); importResourcePacks.enabled = importer.hasResourcePacks() && EaglerFolderResourcePack.isSupported(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 115, I18n.format("settingsBackup.import.option.import"))); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 115, + I18n.format("settingsBackup.import.option.import"))); this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 140, I18n.format("gui.cancel"))); } @@ -69,50 +134,4 @@ public class GuiScreenImportProfile extends GuiScreen { } catch (IOException e) { } } - - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - if(!doImportProfile && !doImportSettings && !doImportServers && !doImportResourcePacks) { - mc.displayGuiScreen(back); - }else { - mc.loadingScreen.eaglerShow(I18n.format("settingsBackup.importing.1"), I18n.format("settingsBackup.importing.2")); - try { - List list1 = new ArrayList<>(mc.gameSettings.resourcePacks); - List list2 = new ArrayList<>(mc.gameSettings.field_183018_l); - importer.importProfileAndSettings(doImportProfile, doImportSettings, doImportServers, doImportResourcePacks); - boolean resourcePacksChanged = !mc.gameSettings.resourcePacks.equals(list1) || !mc.gameSettings.field_183018_l.equals(list2); - if(resourcePacksChanged || (doImportResourcePacks && (list1.size() > 0 || list2.size() > 0))) { - mc.loadingScreen.eaglerShow(I18n.format("resourcePack.load.refreshing"), - I18n.format("resourcePack.load.pleaseWait")); - mc.getResourcePackRepository().reconstruct(mc.gameSettings); - mc.refreshResources(); - } - mc.displayGuiScreen(back); - } catch (IOException e) { - EagRuntime.debugPrintStackTrace(e); - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("settingsBackup.importing.failed.1", "settingsBackup.importing.failed.2", back)); - } - } - }else if(par1GuiButton.id == 1) { - mc.displayGuiScreen(back); - }else if(par1GuiButton.id == 2) { - doImportProfile = !doImportProfile; - importProfile.displayString = I18n.format("settingsBackup.import.option.profile") + " " + I18n.format(doImportProfile ? "gui.yes" : "gui.no"); - }else if(par1GuiButton.id == 3) { - doImportSettings = !doImportSettings; - importSettings.displayString = I18n.format("settingsBackup.import.option.settings") + " " + I18n.format(doImportSettings ? "gui.yes" : "gui.no"); - }else if(par1GuiButton.id == 4) { - doImportServers = !doImportServers; - importServers.displayString = I18n.format("settingsBackup.import.option.servers") + " " + I18n.format(doImportServers ? "gui.yes" : "gui.no"); - }else if(par1GuiButton.id == 5) { - doImportResourcePacks = !doImportResourcePacks; - importResourcePacks.displayString = I18n.format("settingsBackup.import.option.resourcePacks") + " " + I18n.format(doImportResourcePacks ? "gui.yes" : "gui.no"); - } - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("settingsBackup.import.title"), this.width / 2, this.height / 4 - 25, 16777215); - super.drawScreen(par1, par2, par3); - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/HighPolySkin.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/HighPolySkin.java index f53a1e4c..525fd9d1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/HighPolySkin.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/HighPolySkin.java @@ -5,87 +5,46 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum HighPolySkin { - LONG_ARMS( - new ResourceLocation("eagler:mesh/longarms.png"), - new ResourceLocation("eagler:mesh/longarms0.mdl"), - null, + LONG_ARMS(new ResourceLocation("eagler:mesh/longarms.png"), new ResourceLocation("eagler:mesh/longarms0.mdl"), null, new ResourceLocation("eagler:mesh/longarms2.mdl"), - new ResourceLocation[] { - new ResourceLocation("eagler:mesh/longarms1.mdl") - }, - new float[] { - 1.325f - }, - 0.0f, - new ResourceLocation("eagler:mesh/longarms.fallback.png") - ), - - WEIRD_CLIMBER_DUDE( - new ResourceLocation("eagler:mesh/weirdclimber.png"), - new ResourceLocation("eagler:mesh/weirdclimber0.mdl"), - null, + new ResourceLocation[] { new ResourceLocation("eagler:mesh/longarms1.mdl") }, new float[] { 1.325f }, 0.0f, + new ResourceLocation("eagler:mesh/longarms.fallback.png")), + + WEIRD_CLIMBER_DUDE(new ResourceLocation("eagler:mesh/weirdclimber.png"), + new ResourceLocation("eagler:mesh/weirdclimber0.mdl"), null, new ResourceLocation("eagler:mesh/weirdclimber2.mdl"), - new ResourceLocation[] { - new ResourceLocation("eagler:mesh/weirdclimber1.mdl") - }, - new float[] { - 2.62f - }, - -90.0f, - new ResourceLocation("eagler:mesh/weirdclimber.fallback.png") - ), - - LAXATIVE_DUDE( - new ResourceLocation("eagler:mesh/laxativedude.png"), - new ResourceLocation("eagler:mesh/laxativedude0.mdl"), - null, + new ResourceLocation[] { new ResourceLocation("eagler:mesh/weirdclimber1.mdl") }, new float[] { 2.62f }, + -90.0f, new ResourceLocation("eagler:mesh/weirdclimber.fallback.png")), + + LAXATIVE_DUDE(new ResourceLocation("eagler:mesh/laxativedude.png"), + new ResourceLocation("eagler:mesh/laxativedude0.mdl"), null, new ResourceLocation("eagler:mesh/laxativedude3.mdl"), - new ResourceLocation[] { - new ResourceLocation("eagler:mesh/laxativedude1.mdl"), - new ResourceLocation("eagler:mesh/laxativedude2.mdl") - }, - new float[] { - 2.04f - }, - 0.0f, - new ResourceLocation("eagler:mesh/laxativedude.fallback.png") - ), - - BABY_CHARLES( - new ResourceLocation("eagler:mesh/charles.png"), - new ResourceLocation("eagler:mesh/charles0.mdl"), - new ResourceLocation("eagler:mesh/charles1.mdl"), - new ResourceLocation("eagler:mesh/charles2.mdl"), - new ResourceLocation[] {}, - new float[] {}, - 0.0f, - new ResourceLocation("eagler:mesh/charles.fallback.png") - ), - - BABY_WINSTON( - new ResourceLocation("eagler:mesh/winston.png"), - new ResourceLocation("eagler:mesh/winston0.mdl"), - null, - new ResourceLocation("eagler:mesh/winston1.mdl"), - new ResourceLocation[] {}, - new float[] {}, - 0.0f, - new ResourceLocation("eagler:mesh/winston.fallback.png") - ); + new ResourceLocation[] { new ResourceLocation("eagler:mesh/laxativedude1.mdl"), + new ResourceLocation("eagler:mesh/laxativedude2.mdl") }, + new float[] { 2.04f }, 0.0f, new ResourceLocation("eagler:mesh/laxativedude.fallback.png")), + + BABY_CHARLES(new ResourceLocation("eagler:mesh/charles.png"), new ResourceLocation("eagler:mesh/charles0.mdl"), + new ResourceLocation("eagler:mesh/charles1.mdl"), new ResourceLocation("eagler:mesh/charles2.mdl"), + new ResourceLocation[] {}, new float[] {}, 0.0f, new ResourceLocation("eagler:mesh/charles.fallback.png")), + + BABY_WINSTON(new ResourceLocation("eagler:mesh/winston.png"), new ResourceLocation("eagler:mesh/winston0.mdl"), + null, new ResourceLocation("eagler:mesh/winston1.mdl"), new ResourceLocation[] {}, new float[] {}, 0.0f, + new ResourceLocation("eagler:mesh/winston.fallback.png")); public static float highPolyScale = 0.5f; @@ -97,9 +56,10 @@ public enum HighPolySkin { public final float[] limbsOffset; public final float limbsInitialRotation; public final ResourceLocation fallbackTexture; - - HighPolySkin(ResourceLocation texture, ResourceLocation bodyModel, ResourceLocation headModel, ResourceLocation eyesModel, - ResourceLocation[] limbsModel, float[] limbsOffset, float limbsInitialRotation, ResourceLocation fallbackTexture) { + + HighPolySkin(ResourceLocation texture, ResourceLocation bodyModel, ResourceLocation headModel, + ResourceLocation eyesModel, ResourceLocation[] limbsModel, float[] limbsOffset, float limbsInitialRotation, + ResourceLocation fallbackTexture) { this.texture = texture; this.bodyModel = bodyModel; this.headModel = headModel; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileExporter.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileExporter.java index 01e527c9..8b700496 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileExporter.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileExporter.java @@ -1,5 +1,8 @@ package net.lax1dude.eaglercraft.v1_8.profile; +import static net.lax1dude.eaglercraft.v1_8.sp.server.export.EPKCompiler.writeInt; +import static net.lax1dude.eaglercraft.v1_8.sp.server.export.EPKCompiler.writeLong; + import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; @@ -21,19 +24,18 @@ import net.lax1dude.eaglercraft.v1_8.update.UpdateService; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ServerList; -import static net.lax1dude.eaglercraft.v1_8.sp.server.export.EPKCompiler.*; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,18 +44,38 @@ public class ProfileExporter { private static final Logger logger = LogManager.getLogger("ProfileExporter"); + private static void exportFileToEPK(String name, byte[] contents, OutputStream os) throws IOException { + CRC32 checkSum = new CRC32(); + checkSum.update(contents); + long sum = checkSum.getValue(); + + os.write(new byte[] { (byte) 70, (byte) 73, (byte) 76, (byte) 69 }); // FILE + + byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); + os.write(nameBytes.length); + os.write(nameBytes); + writeInt(contents.length + 5, os); + writeInt((int) sum, os); + + os.write(contents); + os.write(':'); + os.write('>'); + } + public static void exportProfileAndSettings(boolean doExportProfile, boolean doExportSettings, boolean doExportServers, boolean doExportResourcePacks) throws IOException { doExportResourcePacks &= EaglerFolderResourcePack.isSupported(); EaglerOutputStream osb = new EaglerOutputStream(); - osb.write(new byte[]{(byte)69,(byte)65,(byte)71,(byte)80,(byte)75,(byte)71,(byte)36,(byte)36}); // EAGPKG$$ - osb.write(new byte[]{(byte)6,(byte)118,(byte)101,(byte)114,(byte)50,(byte)46,(byte)48}); // 6 + ver2.0 + osb.write( + new byte[] { (byte) 69, (byte) 65, (byte) 71, (byte) 80, (byte) 75, (byte) 71, (byte) 36, (byte) 36 }); // EAGPKG$$ + osb.write(new byte[] { (byte) 6, (byte) 118, (byte) 101, (byte) 114, (byte) 50, (byte) 46, (byte) 48 }); // 6 + + // ver2.0 Date d = new Date(); - + byte[] filename = "profile.epk".getBytes(StandardCharsets.UTF_8); osb.write(filename.length); osb.write(filename); - + byte[] comment = ("\n\n # Eaglercraft profile backup - \"" + EaglerProfile.getName() + "\"" + "\n # Contains: " + (doExportProfile ? "profile " : "") + (doExportSettings ? "settings " : "") + (doExportServers ? "servers " : "") + (doExportResourcePacks ? "resourcePacks" : "") + "\n\n") @@ -62,133 +84,120 @@ public class ProfileExporter { osb.write((comment.length >>> 8) & 255); osb.write(comment.length & 255); osb.write(comment); - + writeLong(d.getTime(), osb); - + int lengthIntegerOffset = osb.size(); - osb.write(new byte[]{(byte)255,(byte)255,(byte)255,(byte)255}); // this will be replaced with the file count - + osb.write(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 }); // this will be replaced with the file + // count + osb.write('G'); int fileCount = 2; - try(OutputStream os = EaglerZLIB.newGZIPOutputStream(osb)) { - os.write(new byte[]{(byte)72,(byte)69,(byte)65,(byte)68}); // HEAD - os.write(new byte[]{(byte)9,(byte)102,(byte)105,(byte)108,(byte)101,(byte)45,(byte)116,(byte)121, - (byte)112,(byte)101}); // 9 + file-type - os.write(new byte[]{(byte)0,(byte)0,(byte)0,(byte)14,(byte)101,(byte)112,(byte)107,(byte)47,(byte)112,(byte)114,(byte)111, - (byte)102,(byte)105,(byte)108,(byte)101,(byte)49,(byte)56,(byte)56}); // 14 + epk/profile188 + try (OutputStream os = EaglerZLIB.newGZIPOutputStream(osb)) { + os.write(new byte[] { (byte) 72, (byte) 69, (byte) 65, (byte) 68 }); // HEAD + os.write(new byte[] { (byte) 9, (byte) 102, (byte) 105, (byte) 108, (byte) 101, (byte) 45, (byte) 116, + (byte) 121, (byte) 112, (byte) 101 }); // 9 + file-type + os.write(new byte[] { (byte) 0, (byte) 0, (byte) 0, (byte) 14, (byte) 101, (byte) 112, (byte) 107, + (byte) 47, (byte) 112, (byte) 114, (byte) 111, (byte) 102, (byte) 105, (byte) 108, (byte) 101, + (byte) 49, (byte) 56, (byte) 56 }); // 14 + epk/profile188 os.write('>'); - - os.write(new byte[]{(byte)72,(byte)69,(byte)65,(byte)68}); // HEAD - os.write(new byte[]{(byte)12,(byte)102,(byte)105,(byte)108,(byte)101,(byte)45,(byte)101,(byte)120, - (byte)112,(byte)111,(byte)114,(byte)116,(byte)115,(byte)0,(byte)0,(byte)0,(byte)1}); // 12 + file-exports + 1 - os.write((doExportProfile ? 1 : 0) | (doExportSettings ? 2 : 0) | (doExportServers ? 4 : 0) | (doExportResourcePacks ? 8 : 0)); + + os.write(new byte[] { (byte) 72, (byte) 69, (byte) 65, (byte) 68 }); // HEAD + os.write(new byte[] { (byte) 12, (byte) 102, (byte) 105, (byte) 108, (byte) 101, (byte) 45, (byte) 101, + (byte) 120, (byte) 112, (byte) 111, (byte) 114, (byte) 116, (byte) 115, (byte) 0, (byte) 0, + (byte) 0, (byte) 1 }); // 12 + file-exports + 1 + os.write((doExportProfile ? 1 : 0) | (doExportSettings ? 2 : 0) | (doExportServers ? 4 : 0) + | (doExportResourcePacks ? 8 : 0)); os.write('>'); - - - if(doExportProfile) { + + if (doExportProfile) { byte[] profileData = EaglerProfile.write(); - if(profileData == null) { + if (profileData == null) { throw new IOException("Could not write profile data!"); } exportFileToEPK("_eaglercraftX.p", profileData, os); ++fileCount; } - - if(doExportSettings) { + + if (doExportSettings) { logger.info("Exporting game settings..."); byte[] gameSettings = Minecraft.getMinecraft().gameSettings.writeOptions(); - if(gameSettings == null) { + if (gameSettings == null) { throw new IOException("Could not write game settings!"); } exportFileToEPK("_eaglercraftX.g", gameSettings, os); ++fileCount; logger.info("Exporting relay settings..."); byte[] relays = RelayManager.relayManager.write(); - if(relays == null) { + if (relays == null) { throw new IOException("Could not write relay settings!"); } exportFileToEPK("_eaglercraftX.r", relays, os); ++fileCount; } - - if(doExportServers) { + + if (doExportServers) { logger.info("Exporting server list..."); byte[] servers = ServerList.getServerList().writeServerList(); - if(servers == null) { + if (servers == null) { throw new IOException("Could not write server list!"); } exportFileToEPK("_eaglercraftX.s", servers, os); ++fileCount; } - + logger.info("Exporting certificates..."); UpdateCertificate cert = UpdateService.getClientCertificate(); - if(cert != null) { + if (cert != null) { exportFileToEPK("certs/main.cert", cert.rawCertData, os); ++fileCount; } Collection updatesExport = UpdateService.getAvailableUpdates(); int cc = 0; - for(UpdateCertificate cert2 : updatesExport) { + for (UpdateCertificate cert2 : updatesExport) { exportFileToEPK("certs/c" + (cc++) + ".cert", cert2.rawCertData, os); ++fileCount; } - - if(doExportResourcePacks) { + + if (doExportResourcePacks) { logger.info("Exporting resource packs..."); - byte[] packManifest = (new VFile2(EaglerFolderResourcePack.RESOURCE_PACKS + "/manifest.json")).getAllBytes(); - if(packManifest != null) { + byte[] packManifest = (new VFile2(EaglerFolderResourcePack.RESOURCE_PACKS + "/manifest.json")) + .getAllBytes(); + if (packManifest != null) { exportFileToEPK(EaglerFolderResourcePack.RESOURCE_PACKS + "/manifest.json", packManifest, os); ++fileCount; VFile2 baseDir = new VFile2(EaglerFolderResourcePack.RESOURCE_PACKS); List files = baseDir.listFiles(true); logger.info("({} files to export)", files.size()); - for(int i = 0, l = files.size(); i < l; ++i) { + for (int i = 0, l = files.size(); i < l; ++i) { VFile2 f = files.get(i); - if(f.getPath().equals(EaglerFolderResourcePack.RESOURCE_PACKS + "/manifest.json")) { + if (f.getPath().equals(EaglerFolderResourcePack.RESOURCE_PACKS + "/manifest.json")) { continue; } exportFileToEPK(f.getPath(), f.getAllBytes(), os); ++fileCount; - if(i > 0 && i % 100 == 0) { + if (i > 0 && i % 100 == 0) { logger.info("Exported {} files", i); } } } } - - os.write(new byte[]{(byte)69,(byte)78,(byte)68,(byte)36}); // END$ + + os.write(new byte[] { (byte) 69, (byte) 78, (byte) 68, (byte) 36 }); // END$ } - - osb.write(new byte[]{(byte)58,(byte)58,(byte)58,(byte)89,(byte)69,(byte)69,(byte)58,(byte)62}); // :::YEE:> - + + osb.write( + new byte[] { (byte) 58, (byte) 58, (byte) 58, (byte) 89, (byte) 69, (byte) 69, (byte) 58, (byte) 62 }); // :::YEE:> + byte[] ret = osb.toByteArray(); - ret[lengthIntegerOffset] = (byte)((fileCount >>> 24) & 0xFF); - ret[lengthIntegerOffset + 1] = (byte)((fileCount >>> 16) & 0xFF); - ret[lengthIntegerOffset + 2] = (byte)((fileCount >>> 8) & 0xFF); - ret[lengthIntegerOffset + 3] = (byte)(fileCount & 0xFF); - + ret[lengthIntegerOffset] = (byte) ((fileCount >>> 24) & 0xFF); + ret[lengthIntegerOffset + 1] = (byte) ((fileCount >>> 16) & 0xFF); + ret[lengthIntegerOffset + 2] = (byte) ((fileCount >>> 8) & 0xFF); + ret[lengthIntegerOffset + 3] = (byte) (fileCount & 0xFF); + logger.info("Export complete!"); - + EagRuntime.downloadFileWithName(EaglerProfile.getName() + "-backup.epk", ret); } - - private static void exportFileToEPK(String name, byte[] contents, OutputStream os) throws IOException { - CRC32 checkSum = new CRC32(); - checkSum.update(contents); - long sum = checkSum.getValue(); - - os.write(new byte[]{(byte)70,(byte)73,(byte)76,(byte)69}); // FILE - - byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); - os.write(nameBytes.length); - os.write(nameBytes); - writeInt(contents.length + 5, os); - writeInt((int)sum, os); - - os.write(contents); - os.write(':'); - os.write('>'); - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileImporter.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileImporter.java index 4758b1c2..1cb0d71e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileImporter.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ProfileImporter.java @@ -18,14 +18,15 @@ import net.minecraft.client.multiplayer.ServerList; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,101 +46,86 @@ public class ProfileImporter implements Closeable { this.data = data; } - public void readHeader() throws IOException { - logger.info("Reading EPK file header..."); - epkDecompiler = new EPKDecompiler(data); - - FileEntry etr = epkDecompiler.readFile(); - if (etr == null || !etr.type.equals("HEAD") || !etr.name.equals("file-type") - || !EPKDecompiler.readASCII(etr.data).equals("epk/profile188")) { - throw new IOException("EPK file is not a profile backup!"); - } - - etr = epkDecompiler.readFile(); - if (etr == null || !etr.type.equals("HEAD") || !etr.name.equals("file-exports") || etr.data.length != 1) { - throw new IOException("EPK file is not a profile backup!"); - } - - headerHasProfile = (etr.data[0] & 1) != 0; - headerHasSettings = (etr.data[0] & 2) != 0; - headerHasServers = (etr.data[0] & 4) != 0; - headerHasResourcePacks = (etr.data[0] & 8) != 0; + @Override + public void close() throws IOException { + epkDecompiler.close(); } public boolean hasProfile() { return headerHasProfile; } - public boolean hasSettings() { - return headerHasSettings; + public boolean hasResourcePacks() { + return headerHasResourcePacks; } public boolean hasServers() { return headerHasServers; } - public boolean hasResourcePacks() { - return headerHasResourcePacks; + public boolean hasSettings() { + return headerHasSettings; } /** * Note: this function is sensitive to the order file appear in the EPK */ - public void importProfileAndSettings(boolean doImportProfile, boolean doImportSettings, - boolean doImportServers, boolean doImportResourcePacks) throws IOException { + public void importProfileAndSettings(boolean doImportProfile, boolean doImportSettings, boolean doImportServers, + boolean doImportResourcePacks) throws IOException { doImportProfile &= headerHasProfile; doImportSettings &= headerHasSettings; doImportServers &= headerHasServers; doImportResourcePacks &= headerHasResourcePacks && EaglerFolderResourcePack.isSupported(); FileEntry etr; - vigg: while((etr = epkDecompiler.readFile()) != null) { - if(etr.type.equals("FILE")) { - switch(etr.name) { + vigg: while ((etr = epkDecompiler.readFile()) != null) { + if (etr.type.equals("FILE")) { + switch (etr.name) { case "_eaglercraftX.p": - if(doImportProfile) { + if (doImportProfile) { logger.info("Importing profile..."); EaglerProfile.read(etr.data); EagRuntime.setStorage("p", etr.data); } break; case "_eaglercraftX.g": - if(doImportSettings) { + if (doImportSettings) { logger.info("Importing settings..."); Minecraft.getMinecraft().gameSettings.loadOptions(etr.data); EagRuntime.setStorage("g", etr.data); } break; case "_eaglercraftX.r": - if(doImportSettings) { + if (doImportSettings) { logger.info("Importing relays..."); RelayManager.relayManager.load(etr.data); EagRuntime.setStorage("r", etr.data); } break; case "_eaglercraftX.s": - if(doImportServers) { + if (doImportServers) { logger.info("Importing servers..."); ServerList.getServerList().loadServerList(etr.data); EagRuntime.setStorage("s", etr.data); } break; default: - if(etr.name.startsWith("certs/")) { + if (etr.name.startsWith("certs/")) { UpdateService.addCertificateToSet(etr.data); - }else if(etr.name.startsWith(EaglerFolderResourcePack.RESOURCE_PACKS + "/")) { - if(doImportResourcePacks) { + } else if (etr.name.startsWith(EaglerFolderResourcePack.RESOURCE_PACKS + "/")) { + if (doImportResourcePacks) { logger.info("Deleting old resource packs..."); - (new VFile2(EaglerFolderResourcePack.RESOURCE_PACKS)).listFiles(true).forEach(VFile2::delete); + (new VFile2(EaglerFolderResourcePack.RESOURCE_PACKS)).listFiles(true) + .forEach(VFile2::delete); logger.info("Importing resource packs..."); int counter = 0; do { - if(etr.name.startsWith(EaglerFolderResourcePack.RESOURCE_PACKS + "/")) { + if (etr.name.startsWith(EaglerFolderResourcePack.RESOURCE_PACKS + "/")) { (new VFile2(etr.name)).setAllBytes(etr.data); - if(++counter % 100 == 0) { + if (++counter % 100 == 0) { logger.info("Imported {} files", counter); } } - }while((etr = epkDecompiler.readFile()) != null); + } while ((etr = epkDecompiler.readFile()) != null); } break vigg; } @@ -150,8 +136,24 @@ public class ProfileImporter implements Closeable { logger.info("Import complete!"); } - @Override - public void close() throws IOException { - epkDecompiler.close(); + public void readHeader() throws IOException { + logger.info("Reading EPK file header..."); + epkDecompiler = new EPKDecompiler(data); + + FileEntry etr = epkDecompiler.readFile(); + if (etr == null || !etr.type.equals("HEAD") || !etr.name.equals("file-type") + || !EPKDecompiler.readASCII(etr.data).equals("epk/profile188")) { + throw new IOException("EPK file is not a profile backup!"); + } + + etr = epkDecompiler.readFile(); + if (etr == null || !etr.type.equals("HEAD") || !etr.name.equals("file-exports") || etr.data.length != 1) { + throw new IOException("EPK file is not a profile backup!"); + } + + headerHasProfile = (etr.data[0] & 1) != 0; + headerHasSettings = (etr.data[0] & 2) != 0; + headerHasServers = (etr.data[0] & 4) != 0; + headerHasResourcePacks = (etr.data[0] & 8) != 0; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/RenderHighPoly.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/RenderHighPoly.java index 176c9907..c5981c96 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/RenderHighPoly.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/RenderHighPoly.java @@ -1,6 +1,6 @@ package net.lax1dude.eaglercraft.v1_8.profile; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; @@ -28,14 +28,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,51 +45,51 @@ public class RenderHighPoly extends RenderPlayer { private static final Logger logger = LogManager.getLogger("RenderHighPoly"); + private static final Matrix4f tmpMatrix = new Matrix4f(); + public RenderHighPoly(RenderManager renderManager, ModelBase fallbackModel, float fallbackScale) { super(renderManager, fallbackModel, fallbackScale); } - private static final Matrix4f tmpMatrix = new Matrix4f(); - public void doRender(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2, float f, float f1) { if (!abstractclientplayer.isUser() || this.renderManager.livingPlayer == abstractclientplayer) { double nameY = d1; HighPolySkin highPolySkin = abstractclientplayer.getEaglerSkinModel().highPoly; - - if(highPolySkin == null) { + + if (highPolySkin == null) { super.doRender(abstractclientplayer, d0, d1, d2, f, f1); return; - }else if(highPolySkin == HighPolySkin.LAXATIVE_DUDE) { + } else if (highPolySkin == HighPolySkin.LAXATIVE_DUDE) { nameY += 0.1; - }else if(highPolySkin == HighPolySkin.BABY_WINSTON) { + } else if (highPolySkin == HighPolySkin.BABY_WINSTON) { nameY -= 1.0; } - + GlStateManager.pushMatrix(); GlStateManager.disableCull(); - + try { Minecraft mc = Minecraft.getMinecraft(); - float f2 = this.interpolateRotation(abstractclientplayer.prevRenderYawOffset, abstractclientplayer.renderYawOffset, - f1); - float f3 = this.interpolateRotation(abstractclientplayer.prevRotationYawHead, abstractclientplayer.rotationYawHead, - f1); + float f2 = this.interpolateRotation(abstractclientplayer.prevRenderYawOffset, + abstractclientplayer.renderYawOffset, f1); + float f3 = this.interpolateRotation(abstractclientplayer.prevRotationYawHead, + abstractclientplayer.rotationYawHead, f1); float f4 = f3 - f2; if (abstractclientplayer.isRiding() && abstractclientplayer.ridingEntity instanceof EntityLivingBase) { EntityLivingBase entitylivingbase1 = (EntityLivingBase) abstractclientplayer.ridingEntity; - f2 = this.interpolateRotation(entitylivingbase1.prevRenderYawOffset, entitylivingbase1.renderYawOffset, - f1); + f2 = this.interpolateRotation(entitylivingbase1.prevRenderYawOffset, + entitylivingbase1.renderYawOffset, f1); f4 = f3 - f2; float f5 = MathHelper.wrapAngleTo180_float(f4); if (f5 < -85.0F) { f5 = -85.0F; } - + if (f5 >= 85.0F) { f5 = 85.0F; } - + f2 = f3 - f5; if (f5 * f5 > 2500.0F) { f2 += f5 * 0.2F; @@ -101,301 +102,326 @@ public class RenderHighPoly extends RenderPlayer { GlStateManager.enableRescaleNormal(); this.preRenderCallback(abstractclientplayer, f1); float f6 = 0.0625F; - GlStateManager.scale(HighPolySkin.highPolyScale, HighPolySkin.highPolyScale, HighPolySkin.highPolyScale); + GlStateManager.scale(HighPolySkin.highPolyScale, HighPolySkin.highPolyScale, + HighPolySkin.highPolyScale); mc.getTextureManager().bindTexture(highPolySkin.texture); - - if(abstractclientplayer.isPlayerSleeping()) { - if(highPolySkin == HighPolySkin.LAXATIVE_DUDE || highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { + + if (abstractclientplayer.isPlayerSleeping()) { + if (highPolySkin == HighPolySkin.LAXATIVE_DUDE || highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { GlStateManager.translate(0.0f, -3.7f, 0.0f); - }else if(highPolySkin == HighPolySkin.BABY_WINSTON) { + } else if (highPolySkin == HighPolySkin.BABY_WINSTON) { GlStateManager.translate(0.0f, -2.4f, 0.0f); - }else { + } else { GlStateManager.translate(0.0f, -3.0f, 0.0f); } } - - float var15 = abstractclientplayer.prevLimbSwingAmount + (abstractclientplayer.limbSwingAmount - abstractclientplayer.prevLimbSwingAmount) * f1; + + float var15 = abstractclientplayer.prevLimbSwingAmount + + (abstractclientplayer.limbSwingAmount - abstractclientplayer.prevLimbSwingAmount) * f1; float var16 = abstractclientplayer.limbSwing - abstractclientplayer.limbSwingAmount * (1.0F - f1); - - if(highPolySkin == HighPolySkin.LONG_ARMS) { + + if (highPolySkin == HighPolySkin.LONG_ARMS) { GlStateManager.rotate(MathHelper.sin(var16) * 20f * var15, 0.0f, 1.0f, 0.0f); GlStateManager.rotate(MathHelper.cos(var16) * 7f * var15, 0.0f, 0.0f, 1.0f); - }else if(highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { + } else if (highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { GlStateManager.rotate(MathHelper.sin(var16) * 7f * var15, 0.0f, 1.0f, 0.0f); GlStateManager.rotate(MathHelper.cos(var16) * 3f * var15, 0.0f, 0.0f, 1.0f); GlStateManager.rotate(-f3, 0.0f, 1.0f, 0.0f); - float xd = (float)(abstractclientplayer.posX - abstractclientplayer.prevPosX); + float xd = (float) (abstractclientplayer.posX - abstractclientplayer.prevPosX); GlStateManager.rotate(xd * 70.0f * var15, 0.0f, 0.0f, 1.0f); - float zd = (float)(abstractclientplayer.posZ - abstractclientplayer.prevPosZ); + float zd = (float) (abstractclientplayer.posZ - abstractclientplayer.prevPosZ); GlStateManager.rotate(zd * 70.0f * var15, 1.0f, 0.0f, 0.0f); GlStateManager.rotate(f3, 0.0f, 1.0f, 0.0f); - }else if(highPolySkin == HighPolySkin.LAXATIVE_DUDE) { + } else if (highPolySkin == HighPolySkin.LAXATIVE_DUDE) { GlStateManager.rotate(-f3, 0.0f, 1.0f, 0.0f); - float xd = (float)(abstractclientplayer.posX - abstractclientplayer.prevPosX); + float xd = (float) (abstractclientplayer.posX - abstractclientplayer.prevPosX); GlStateManager.rotate(-xd * 40.0f * var15, 0.0f, 0.0f, 1.0f); - float zd = (float)(abstractclientplayer.posZ - abstractclientplayer.prevPosZ); + float zd = (float) (abstractclientplayer.posZ - abstractclientplayer.prevPosZ); GlStateManager.rotate(-zd * 40.0f * var15, 1.0f, 0.0f, 0.0f); GlStateManager.rotate(f3, 0.0f, 1.0f, 0.0f); - }else if(highPolySkin == HighPolySkin.BABY_WINSTON) { + } else if (highPolySkin == HighPolySkin.BABY_WINSTON) { GlStateManager.translate(0.0f, (MathHelper.cos(f10 % 100000.0f) + 1.0f) * var15 * 0.2f, 0.0f); GlStateManager.rotate(MathHelper.sin(var16) * 5f * var15, 0.0f, 1.0f, 0.0f); GlStateManager.rotate(MathHelper.cos(var16) * 5f * var15, 0.0f, 0.0f, 1.0f); } - + if (abstractclientplayer.hurtTime > 0 || abstractclientplayer.deathTime > 0) { GlStateManager.color(1.2f, 0.8F, 0.8F, 1.0F); } - - if(DeferredStateManager.isInDeferredPass()) { + + if (DeferredStateManager.isInDeferredPass()) { DeferredStateManager.setDefaultMaterialConstants(); DeferredStateManager.setRoughnessConstant(0.5f); DeferredStateManager.setMetalnessConstant(0.05f); } - - if(highPolySkin.bodyModel != null) { + + if (highPolySkin.bodyModel != null) { EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(highPolySkin.bodyModel)); } float jumpFactor = 0.0f; - - if(highPolySkin.headModel != null) { - if(highPolySkin == HighPolySkin.BABY_CHARLES) { + + if (highPolySkin.headModel != null) { + if (highPolySkin == HighPolySkin.BABY_CHARLES) { long millis = EagRuntime.steadyTimeMillis(); - float partialTicks = (float) ((millis - abstractclientplayer.eaglerHighPolyAnimationTick) * 0.02); - //long l50 = millis / 50l * 50l; - //boolean runTick = par1EntityPlayer.eaglerHighPolyAnimationTick < l50 && millis >= l50; + float partialTicks = (float) ((millis - abstractclientplayer.eaglerHighPolyAnimationTick) + * 0.02); + // long l50 = millis / 50l * 50l; + // boolean runTick = par1EntityPlayer.eaglerHighPolyAnimationTick < l50 && + // millis >= l50; abstractclientplayer.eaglerHighPolyAnimationTick = millis; - - if(partialTicks < 0.0f) { + + if (partialTicks < 0.0f) { partialTicks = 0.0f; } - if(partialTicks > 1.0f) { + if (partialTicks > 1.0f) { partialTicks = 1.0f; } - - float jumpFac = (float)(abstractclientplayer.posY - abstractclientplayer.prevPosY); - if(jumpFac < 0.0f && !abstractclientplayer.isCollidedVertically) { + + float jumpFac = (float) (abstractclientplayer.posY - abstractclientplayer.prevPosY); + if (jumpFac < 0.0f && !abstractclientplayer.isCollidedVertically) { jumpFac = -jumpFac; jumpFac *= 0.1f; } jumpFac -= 0.05f; - if(jumpFac > 0.1f && !abstractclientplayer.isCollidedVertically) { + if (jumpFac > 0.1f && !abstractclientplayer.isCollidedVertically) { jumpFac = 0.1f; - }else if(jumpFac < 0.0f) { + } else if (jumpFac < 0.0f) { jumpFac = 0.0f; - }else if(jumpFac > 0.1f && abstractclientplayer.isCollidedVertically) { + } else if (jumpFac > 0.1f && abstractclientplayer.isCollidedVertically) { jumpFac = 0.1f; - }else if(jumpFac > 0.4f) { + } else if (jumpFac > 0.4f) { jumpFac = 0.4f; } jumpFac *= 10.0f; - - abstractclientplayer.eaglerHighPolyAnimationFloat3 += (jumpFac / (jumpFac + 1.0f)) * 6.0f * partialTicks; - - if(Float.isInfinite(abstractclientplayer.eaglerHighPolyAnimationFloat3)) { + + abstractclientplayer.eaglerHighPolyAnimationFloat3 += (jumpFac / (jumpFac + 1.0f)) * 6.0f + * partialTicks; + + if (Float.isInfinite(abstractclientplayer.eaglerHighPolyAnimationFloat3)) { abstractclientplayer.eaglerHighPolyAnimationFloat3 = 1.0f; - }else if(abstractclientplayer.eaglerHighPolyAnimationFloat3 > 1.0f) { + } else if (abstractclientplayer.eaglerHighPolyAnimationFloat3 > 1.0f) { abstractclientplayer.eaglerHighPolyAnimationFloat3 = 1.0f; - }else if(abstractclientplayer.eaglerHighPolyAnimationFloat3 < -1.0f) { + } else if (abstractclientplayer.eaglerHighPolyAnimationFloat3 < -1.0f) { abstractclientplayer.eaglerHighPolyAnimationFloat3 = -1.0f; } - - abstractclientplayer.eaglerHighPolyAnimationFloat2 += abstractclientplayer.eaglerHighPolyAnimationFloat3 * partialTicks; - + + abstractclientplayer.eaglerHighPolyAnimationFloat2 += abstractclientplayer.eaglerHighPolyAnimationFloat3 + * partialTicks; + abstractclientplayer.eaglerHighPolyAnimationFloat5 += partialTicks; - while(abstractclientplayer.eaglerHighPolyAnimationFloat5 > 0.05f) { + while (abstractclientplayer.eaglerHighPolyAnimationFloat5 > 0.05f) { abstractclientplayer.eaglerHighPolyAnimationFloat5 -= 0.05f; abstractclientplayer.eaglerHighPolyAnimationFloat3 *= 0.99f; abstractclientplayer.eaglerHighPolyAnimationFloat2 *= 0.9f; } - - jumpFactor = abstractclientplayer.eaglerHighPolyAnimationFloat2; //(abstractclientplayer.eaglerHighPolyAnimationFloat1 - abstractclientplayer.eaglerHighPolyAnimationFloat2) * partialTicks + abstractclientplayer.eaglerHighPolyAnimationFloat2; + + jumpFactor = abstractclientplayer.eaglerHighPolyAnimationFloat2; // (abstractclientplayer.eaglerHighPolyAnimationFloat1 + // - + // abstractclientplayer.eaglerHighPolyAnimationFloat2) + // * partialTicks + + // abstractclientplayer.eaglerHighPolyAnimationFloat2; jumpFactor -= 0.12f; - if(jumpFactor < 0.0f) { + if (jumpFactor < 0.0f) { jumpFactor = 0.0f; } jumpFactor = jumpFactor / (jumpFactor + 2.0f); - if(jumpFactor > 1.0f) { + if (jumpFactor > 1.0f) { jumpFactor = 1.0f; } } - if(jumpFactor > 0.0f) { + if (jumpFactor > 0.0f) { GlStateManager.pushMatrix(); GlStateManager.translate(0.0f, jumpFactor * 3.0f, 0.0f); } - + EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(highPolySkin.headModel)); - - if(jumpFactor > 0.0f) { + + if (jumpFactor > 0.0f) { GlStateManager.popMatrix(); } } - - if(highPolySkin.limbsModel != null && highPolySkin.limbsModel.length > 0) { - for(int i = 0; i < highPolySkin.limbsModel.length; ++i) { + + if (highPolySkin.limbsModel != null && highPolySkin.limbsModel.length > 0) { + for (int i = 0; i < highPolySkin.limbsModel.length; ++i) { DeferredStateManager.setRoughnessConstant(0.023f); DeferredStateManager.setMetalnessConstant(0.902f); float offset = 0.0f; - if(highPolySkin.limbsOffset != null) { - if(highPolySkin.limbsOffset.length == 1) { + if (highPolySkin.limbsOffset != null) { + if (highPolySkin.limbsOffset.length == 1) { offset = highPolySkin.limbsOffset[0]; - }else { + } else { offset = highPolySkin.limbsOffset[i]; } } - + GlStateManager.pushMatrix(); - - if(offset != 0.0f || highPolySkin.limbsInitialRotation != 0.0f) { - if(offset != 0.0f) { + + if (offset != 0.0f || highPolySkin.limbsInitialRotation != 0.0f) { + if (offset != 0.0f) { GlStateManager.translate(0.0f, offset, 0.0f); } - if(highPolySkin.limbsInitialRotation != 0.0f) { + if (highPolySkin.limbsInitialRotation != 0.0f) { GlStateManager.rotate(highPolySkin.limbsInitialRotation, 1.0f, 0.0f, 0.0f); } } - - if(highPolySkin == HighPolySkin.LONG_ARMS) { - if(abstractclientplayer.isSwingInProgress) { - float var17 = MathHelper.cos(-abstractclientplayer.getSwingProgress(f1) * (float)Math.PI * 2.0f - 1.2f) - 0.362f; + + if (highPolySkin == HighPolySkin.LONG_ARMS) { + if (abstractclientplayer.isSwingInProgress) { + float var17 = MathHelper + .cos(-abstractclientplayer.getSwingProgress(f1) * (float) Math.PI * 2.0f - 1.2f) + - 0.362f; var17 *= var17; GlStateManager.rotate(-var17 * 20.0f, 1.0f, 0.0f, 0.0f); } - }else if(highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { - if(abstractclientplayer.isSwingInProgress) { - float var17 = MathHelper.cos(-abstractclientplayer.getSwingProgress(f1) * (float)Math.PI * 2.0f - 1.2f) - 0.362f; + } else if (highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { + if (abstractclientplayer.isSwingInProgress) { + float var17 = MathHelper + .cos(-abstractclientplayer.getSwingProgress(f1) * (float) Math.PI * 2.0f - 1.2f) + - 0.362f; var17 *= var17; GlStateManager.rotate(var17 * 60.0f, 1.0f, 0.0f, 0.0f); } GlStateManager.rotate(40.0f * var15, 1.0f, 0.0f, 0.0f); - }else if(highPolySkin == HighPolySkin.LAXATIVE_DUDE) { + } else if (highPolySkin == HighPolySkin.LAXATIVE_DUDE) { float fff = (i == 0) ? 1.0f : -1.0f; float swing = (MathHelper.cos(f10 % 100000.0f) * fff + 0.2f) * var15; float swing2 = (MathHelper.cos(f10 % 100000.0f) * fff * 0.5f + 0.0f) * var15; GlStateManager.rotate(swing * 25.0f, 1.0f, 0.0f, 0.0f); - if(abstractclientplayer.isSwingInProgress) { - float var17 = MathHelper.cos(-abstractclientplayer.getSwingProgress(f1) * (float)Math.PI * 2.0f - 1.2f) - 0.362f; + if (abstractclientplayer.isSwingInProgress) { + float var17 = MathHelper + .cos(-abstractclientplayer.getSwingProgress(f1) * (float) Math.PI * 2.0f - 1.2f) + - 0.362f; var17 *= var17; GlStateManager.rotate(-var17 * 25.0f, 1.0f, 0.0f, 0.0f); } - + // shear matrix tmpMatrix.setIdentity(); tmpMatrix.m21 = swing2; tmpMatrix.m23 = swing2 * -0.2f; GlStateManager.multMatrix(tmpMatrix); } - - if(i != 0) { + + if (i != 0) { mc.getTextureManager().bindTexture(highPolySkin.texture); if (abstractclientplayer.hurtTime > 0 || abstractclientplayer.deathTime > 0) { GlStateManager.color(1.2f, 0.8F, 0.8F, 1.0F); - }else { + } else { GlStateManager.color(1.0f, 1.0F, 1.0F, 1.0F); } } EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(highPolySkin.limbsModel[i])); - - if(i == 0) { + + if (i == 0) { GlStateManager.pushMatrix(); - + GlStateManager.translate(-0.287f, 0.05f, 0.0f); - - if(highPolySkin == HighPolySkin.LONG_ARMS) { + + if (highPolySkin == HighPolySkin.LONG_ARMS) { GlStateManager.translate(1.72f, 2.05f, -0.24f); ItemStack stk = abstractclientplayer.getHeldItem(); - if(stk != null) { + if (stk != null) { Item itm = stk.getItem(); - if(itm != null) { - if(itm == Items.bow) { + if (itm != null) { + if (itm == Items.bow) { GlStateManager.translate(-0.22f, 0.8f, 0.6f); GlStateManager.rotate(-90.0f, 1.0f, 0.0f, 0.0f); - }else if(itm instanceof ItemBlock && !((ItemBlock)itm).getBlock().isNormalCube()) { + } else if (itm instanceof ItemBlock + && !((ItemBlock) itm).getBlock().isNormalCube()) { GlStateManager.translate(0.0f, -0.1f, 0.13f); - }else if(!itm.isFull3D()) { + } else if (!itm.isFull3D()) { GlStateManager.translate(-0.08f, -0.1f, 0.16f); } } } - }else if(highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { + } else if (highPolySkin == HighPolySkin.WEIRD_CLIMBER_DUDE) { GlStateManager.translate(-0.029f, 1.2f, -3f); GlStateManager.rotate(-5.0f, 0.0f, 1.0f, 0.0f); float var17 = -1.2f * var15; - if(abstractclientplayer.isSwingInProgress) { - float vvar17 = MathHelper.cos(-abstractclientplayer.getSwingProgress(f1) * (float)Math.PI * 2.0f - 1.2f) - 0.362f; + if (abstractclientplayer.isSwingInProgress) { + float vvar17 = MathHelper.cos( + -abstractclientplayer.getSwingProgress(f1) * (float) Math.PI * 2.0f - 1.2f) + - 0.362f; var17 = vvar17 < var17 ? vvar17 : var17; } GlStateManager.translate(-0.02f * var17, 0.42f * var17, var17 * 0.35f); GlStateManager.rotate(var17 * 30.0f, 1.0f, 0.0f, 0.0f); GlStateManager.rotate(110.0f, 1.0f, 0.0f, 0.0f); ItemStack stk = abstractclientplayer.getHeldItem(); - if(stk != null) { + if (stk != null) { Item itm = stk.getItem(); - if(itm != null) { - if(itm == Items.bow) { + if (itm != null) { + if (itm == Items.bow) { GlStateManager.translate(-0.18f, 1.0f, 0.4f); GlStateManager.rotate(-95.0f, 1.0f, 0.0f, 0.0f); - }else if(itm instanceof ItemBlock && !((ItemBlock)itm).getBlock().isNormalCube()) { + } else if (itm instanceof ItemBlock + && !((ItemBlock) itm).getBlock().isNormalCube()) { GlStateManager.translate(0.0f, -0.1f, 0.13f); - }else if(!itm.isFull3D()) { + } else if (!itm.isFull3D()) { GlStateManager.translate(-0.08f, -0.1f, 0.16f); } } } - }else if(highPolySkin == HighPolySkin.LAXATIVE_DUDE) { + } else if (highPolySkin == HighPolySkin.LAXATIVE_DUDE) { GlStateManager.translate(1.291f, 2.44f, -2.18f); GlStateManager.rotate(95.0f, 1.0f, 0.0f, 0.0f); ItemStack stk = abstractclientplayer.getHeldItem(); - if(stk != null) { + if (stk != null) { Item itm = stk.getItem(); - if(itm != null) { - if(itm == Items.bow) { + if (itm != null) { + if (itm == Items.bow) { GlStateManager.translate(-0.65f, 1.3f, -0.1f); GlStateManager.rotate(180.0f, 0.0f, 0.0f, 1.0f); GlStateManager.rotate(20.0f, 1.0f, 0.0f, 0.0f); - }else if(itm instanceof ItemBlock && !((ItemBlock)itm).getBlock().isNormalCube()) { + } else if (itm instanceof ItemBlock + && !((ItemBlock) itm).getBlock().isNormalCube()) { GlStateManager.translate(0.0f, -0.35f, 0.4f); - }else if(!itm.isFull3D()) { + } else if (!itm.isFull3D()) { GlStateManager.translate(-0.1f, -0.1f, 0.16f); } } } } - + DeferredStateManager.setDefaultMaterialConstants(); renderHeldItem(abstractclientplayer, f1); GlStateManager.popMatrix(); } - + GlStateManager.popMatrix(); } } - - if(highPolySkin.eyesModel != null && !DeferredStateManager.isEnableShadowRender()) { + + if (highPolySkin.eyesModel != null && !DeferredStateManager.isEnableShadowRender()) { float ff = 0.00416f; int brightness = abstractclientplayer.getBrightnessForRender(0.0f); float blockLight = (brightness % 65536) * ff; float skyLight = (brightness / 65536) * ff; - float sunCurve = (float)((abstractclientplayer.worldObj.getWorldTime() + 4000l) % 24000) / 24000.0f; - sunCurve = MathHelper.clamp_float(9.8f - MathHelper.abs(sunCurve * 5.0f + sunCurve * sunCurve * 45.0f - 14.3f) * 0.7f, 0.0f, 1.0f); + float sunCurve = (float) ((abstractclientplayer.worldObj.getWorldTime() + 4000l) % 24000) + / 24000.0f; + sunCurve = MathHelper.clamp_float( + 9.8f - MathHelper.abs(sunCurve * 5.0f + sunCurve * sunCurve * 45.0f - 14.3f) * 0.7f, 0.0f, + 1.0f); skyLight = skyLight * (sunCurve * 0.85f + 0.15f); blockLight = blockLight * (sunCurve * 0.3f + 0.7f); float eyeBrightness = blockLight; - if(skyLight > eyeBrightness) { + if (skyLight > eyeBrightness) { eyeBrightness = skyLight; } eyeBrightness += blockLight * 0.2f; eyeBrightness = 1.0f - eyeBrightness; eyeBrightness = MathHelper.clamp_float(eyeBrightness * 1.9f - 1.0f, 0.0f, 1.0f); - if(eyeBrightness > 0.1f) { - if(DeferredStateManager.isInDeferredPass()) { + if (eyeBrightness > 0.1f) { + if (DeferredStateManager.isInDeferredPass()) { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); DeferredStateManager.setDefaultMaterialConstants(); DeferredStateManager.setEmissionConstant(eyeBrightness); - }else { + } else { GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_ONE, GL_ONE); - GlStateManager.color(eyeBrightness * 7.0f, eyeBrightness * 7.0f, eyeBrightness * 7.0f, 1.0f); - if(jumpFactor > 0.0f) { + GlStateManager.color(eyeBrightness * 7.0f, eyeBrightness * 7.0f, eyeBrightness * 7.0f, + 1.0f); + if (jumpFactor > 0.0f) { GlStateManager.pushMatrix(); GlStateManager.translate(0.0f, jumpFactor * 3.0f, 0.0f); } @@ -403,22 +429,22 @@ public class RenderHighPoly extends RenderPlayer { GlStateManager.disableTexture2D(); GlStateManager.disableLighting(); GlStateManager.enableCull(); - + EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(highPolySkin.eyesModel)); - + GlStateManager.enableTexture2D(); GlStateManager.enableLighting(); GlStateManager.disableCull(); - if(jumpFactor > 0.0f) { + if (jumpFactor > 0.0f) { GlStateManager.popMatrix(); } GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - if(!DeferredStateManager.isInDeferredPass()) { + if (!DeferredStateManager.isInDeferredPass()) { GlStateManager.disableBlend(); } } } - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Couldn\'t render entity"); logger.error(t); } @@ -433,14 +459,6 @@ public class RenderHighPoly extends RenderPlayer { } } - public void renderRightArm(AbstractClientPlayer clientPlayer) { - - } - - public void renderLeftArm(AbstractClientPlayer clientPlayer) { - - } - protected void renderHeldItem(AbstractClientPlayer clientPlayer, float partialTicks) { ItemStack itemstack = clientPlayer.getHeldItem(); if (itemstack != null) { @@ -470,6 +488,10 @@ public class RenderHighPoly extends RenderPlayer { } } + public void renderLeftArm(AbstractClientPlayer clientPlayer) { + + } + public void renderLivingAt(AbstractClientPlayer abstractclientplayer, double d0, double d1, double d2) { if (abstractclientplayer.isEntityAlive() && abstractclientplayer.isPlayerSleeping()) { super.renderLivingAt(abstractclientplayer, d0 - (double) abstractclientplayer.renderOffsetX, @@ -478,4 +500,8 @@ public class RenderHighPoly extends RenderPlayer { super.renderLivingAt(abstractclientplayer, d0, d1, d2); } } + + public void renderRightArm(AbstractClientPlayer clientPlayer) { + + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerCapeCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerCapeCache.java index ffad6327..ae8e3eff 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerCapeCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerCapeCache.java @@ -16,37 +16,54 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerCapeCache { - private static final Logger logger = LogManager.getLogger("ServerCapeCache"); + protected static class CacheCustomCape { + + protected final EaglerSkinTexture textureInstance; + protected final ResourceLocation resourceLocation; + + protected CacheCustomCape(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation) { + this.textureInstance = textureInstance; + this.resourceLocation = resourceLocation; + } + + } public class CapeCacheEntry { - + protected final boolean isPresetCape; protected final int presetCapeId; protected final CacheCustomCape customCape; - + protected long lastCacheHit = EagRuntime.steadyTimeMillis(); - + protected CapeCacheEntry(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation) { this.isPresetCape = false; this.presetCapeId = -1; this.customCape = new CacheCustomCape(textureInstance, resourceLocation); ServerCapeCache.this.textureManager.loadTexture(resourceLocation, textureInstance); } - + + protected CapeCacheEntry(int presetSkinId) { + this.isPresetCape = true; + this.presetCapeId = presetSkinId; + this.customCape = null; + } + /** * Use only for the constant for the client player */ @@ -55,112 +72,58 @@ public class ServerCapeCache { this.presetCapeId = -1; this.customCape = new CacheCustomCape(null, resourceLocation); } - - protected CapeCacheEntry(int presetSkinId) { - this.isPresetCape = true; - this.presetCapeId = presetSkinId; - this.customCape = null; - } - - public ResourceLocation getResourceLocation() { - if(isPresetCape) { - return DefaultCapes.getCapeFromId(presetCapeId).location; - }else { - if(customCape != null) { - return customCape.resourceLocation; - }else { - return null; - } - } - } - + protected void free() { - if(!isPresetCape && customCape.resourceLocation != null) { + if (!isPresetCape && customCape.resourceLocation != null) { ServerCapeCache.this.textureManager.deleteTexture(customCape.resourceLocation); } } - } - - protected static class CacheCustomCape { - - protected final EaglerSkinTexture textureInstance; - protected final ResourceLocation resourceLocation; - - protected CacheCustomCape(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation) { - this.textureInstance = textureInstance; - this.resourceLocation = resourceLocation; + public ResourceLocation getResourceLocation() { + if (isPresetCape) { + return DefaultCapes.getCapeFromId(presetCapeId).location; + } else { + if (customCape != null) { + return customCape.resourceLocation; + } else { + return null; + } + } } } + private static final Logger logger = LogManager.getLogger("ServerCapeCache"); + + private static int texId = 0; + public static boolean needReloadClientCape = false; private final CapeCacheEntry defaultCacheEntry = new CapeCacheEntry(0); private final Map capesCache = new HashMap<>(); + private final Map waitingCapes = new HashMap<>(); private final Map evictedCapes = new HashMap<>(); private final NetHandlerPlayClient netHandler; protected final TextureManager textureManager; - + private final EaglercraftUUID clientPlayerId; private CapeCacheEntry clientPlayerCacheEntry; - private long lastFlush = EagRuntime.steadyTimeMillis(); + private long lastFlushReq = EagRuntime.steadyTimeMillis(); private long lastFlushEvict = EagRuntime.steadyTimeMillis(); - private static int texId = 0; - public static boolean needReloadClientCape = false; - public ServerCapeCache(NetHandlerPlayClient netHandler, TextureManager textureManager) { this.netHandler = netHandler; this.textureManager = textureManager; this.clientPlayerId = EaglerProfile.getPlayerUUID(); reloadClientPlayerCape(); } - - public void reloadClientPlayerCape() { - needReloadClientCape = false; - this.clientPlayerCacheEntry = new CapeCacheEntry(EaglerProfile.getActiveCapeResourceLocation()); - } - - public CapeCacheEntry getClientPlayerCape() { - return clientPlayerCacheEntry; - } - - public CapeCacheEntry getCape(EaglercraftUUID player) { - if(player.equals(clientPlayerId)) { - return clientPlayerCacheEntry; - } - CapeCacheEntry etr = capesCache.get(player); - if(etr == null) { - if(!waitingCapes.containsKey(player) && !evictedCapes.containsKey(player)) { - waitingCapes.put(player, EagRuntime.steadyTimeMillis()); - netHandler.sendEaglerMessage(new CPacketGetOtherCapeEAG(player.msb, player.lsb)); - } - return defaultCacheEntry; - }else { - etr.lastCacheHit = EagRuntime.steadyTimeMillis(); - return etr; - } - } - - public void cacheCapePreset(EaglercraftUUID player, int presetId) { - if(waitingCapes.remove(player) != null) { - CapeCacheEntry etr = capesCache.remove(player); - if(etr != null) { - etr.free(); - } - capesCache.put(player, new CapeCacheEntry(presetId)); - }else { - logger.error("Unsolicited cape response recieved for \"{}\"! (preset {})", player, presetId); - } - } public void cacheCapeCustom(EaglercraftUUID player, byte[] pixels) { - if(waitingCapes.remove(player) != null) { + if (waitingCapes.remove(player) != null) { CapeCacheEntry etr = capesCache.remove(player); - if(etr != null) { + if (etr != null) { etr.free(); } byte[] pixels32x32 = new byte[4096]; @@ -168,62 +131,32 @@ public class ServerCapeCache { try { etr = new CapeCacheEntry(new EaglerSkinTexture(pixels32x32, 32, 32), new ResourceLocation("eagler:capes/multiplayer/tex_" + texId++)); - }catch(Throwable t) { + } catch (Throwable t) { etr = new CapeCacheEntry(0); logger.error("Could not process custom skin packet for \"{}\"!", player); logger.error(t); } capesCache.put(player, etr); - }else { + } else { logger.error("Unsolicited skin response recieved for \"{}\"!", player); } } - public void flush() { - long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastFlushReq > 5000l) { - lastFlushReq = millis; - if(!waitingCapes.isEmpty()) { - Iterator waitingItr = waitingCapes.values().iterator(); - while(waitingItr.hasNext()) { - if(millis - waitingItr.next().longValue() > 30000l) { - waitingItr.remove(); - } - } + public void cacheCapePreset(EaglercraftUUID player, int presetId) { + if (waitingCapes.remove(player) != null) { + CapeCacheEntry etr = capesCache.remove(player); + if (etr != null) { + etr.free(); } - } - if(millis - lastFlushEvict > 1000l) { - lastFlushEvict = millis; - if(!evictedCapes.isEmpty()) { - Iterator evictItr = evictedCapes.values().iterator(); - while(evictItr.hasNext()) { - if(millis - evictItr.next().longValue() > 3000l) { - evictItr.remove(); - } - } - } - } - if(millis - lastFlush > 60000l) { - lastFlush = millis; - if(!capesCache.isEmpty()) { - Iterator entryItr = capesCache.values().iterator(); - while(entryItr.hasNext()) { - CapeCacheEntry etr = entryItr.next(); - if(millis - etr.lastCacheHit > 900000l) { // 15 minutes - entryItr.remove(); - etr.free(); - } - } - } - } - if(needReloadClientCape) { - reloadClientPlayerCape(); + capesCache.put(player, new CapeCacheEntry(presetId)); + } else { + logger.error("Unsolicited cape response recieved for \"{}\"! (preset {})", player, presetId); } } public void destroy() { Iterator entryItr = capesCache.values().iterator(); - while(entryItr.hasNext()) { + while (entryItr.hasNext()) { entryItr.next().free(); } capesCache.clear(); @@ -234,16 +167,84 @@ public class ServerCapeCache { public void evictCape(EaglercraftUUID uuid) { evictedCapes.put(uuid, Long.valueOf(EagRuntime.steadyTimeMillis())); CapeCacheEntry etr = capesCache.remove(uuid); - if(etr != null) { + if (etr != null) { etr.free(); } } + public void flush() { + long millis = EagRuntime.steadyTimeMillis(); + if (millis - lastFlushReq > 5000l) { + lastFlushReq = millis; + if (!waitingCapes.isEmpty()) { + Iterator waitingItr = waitingCapes.values().iterator(); + while (waitingItr.hasNext()) { + if (millis - waitingItr.next().longValue() > 30000l) { + waitingItr.remove(); + } + } + } + } + if (millis - lastFlushEvict > 1000l) { + lastFlushEvict = millis; + if (!evictedCapes.isEmpty()) { + Iterator evictItr = evictedCapes.values().iterator(); + while (evictItr.hasNext()) { + if (millis - evictItr.next().longValue() > 3000l) { + evictItr.remove(); + } + } + } + } + if (millis - lastFlush > 60000l) { + lastFlush = millis; + if (!capesCache.isEmpty()) { + Iterator entryItr = capesCache.values().iterator(); + while (entryItr.hasNext()) { + CapeCacheEntry etr = entryItr.next(); + if (millis - etr.lastCacheHit > 900000l) { // 15 minutes + entryItr.remove(); + etr.free(); + } + } + } + } + if (needReloadClientCape) { + reloadClientPlayerCape(); + } + } + + public CapeCacheEntry getCape(EaglercraftUUID player) { + if (player.equals(clientPlayerId)) { + return clientPlayerCacheEntry; + } + CapeCacheEntry etr = capesCache.get(player); + if (etr == null) { + if (!waitingCapes.containsKey(player) && !evictedCapes.containsKey(player)) { + waitingCapes.put(player, EagRuntime.steadyTimeMillis()); + netHandler.sendEaglerMessage(new CPacketGetOtherCapeEAG(player.msb, player.lsb)); + } + return defaultCacheEntry; + } else { + etr.lastCacheHit = EagRuntime.steadyTimeMillis(); + return etr; + } + } + + public CapeCacheEntry getClientPlayerCape() { + return clientPlayerCacheEntry; + } + public void handleInvalidate(EaglercraftUUID uuid) { CapeCacheEntry etr = capesCache.remove(uuid); - if(etr != null) { + if (etr != null) { etr.free(); } } + public void reloadClientPlayerCape() { + needReloadClientCape = false; + this.clientPlayerCacheEntry = new CapeCacheEntry(EaglerProfile.getActiveCapeResourceLocation()); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerSkinCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerSkinCache.java index f11cf4ba..8d523d46 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerSkinCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/ServerSkinCache.java @@ -19,37 +19,58 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerSkinCache { - private static final Logger logger = LogManager.getLogger("ServerSkinCache"); + protected static class CacheCustomSkin { + + protected final EaglerSkinTexture textureInstance; + protected final ResourceLocation resourceLocation; + protected final SkinModel model; + + protected CacheCustomSkin(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation, + SkinModel model) { + this.textureInstance = textureInstance; + this.resourceLocation = resourceLocation; + this.model = model; + } + + } public class SkinCacheEntry { - + protected final boolean isPresetSkin; protected final int presetSkinId; protected final CacheCustomSkin customSkin; - + protected long lastCacheHit = EagRuntime.steadyTimeMillis(); - - protected SkinCacheEntry(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation, SkinModel model) { + + protected SkinCacheEntry(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation, + SkinModel model) { this.isPresetSkin = false; this.presetSkinId = -1; this.customSkin = new CacheCustomSkin(textureInstance, resourceLocation, model); ServerSkinCache.this.textureManager.loadTexture(resourceLocation, textureInstance); } - + + protected SkinCacheEntry(int presetSkinId) { + this.isPresetSkin = true; + this.presetSkinId = presetSkinId; + this.customSkin = null; + } + /** * Use only for the constant for the client player */ @@ -58,64 +79,44 @@ public class ServerSkinCache { this.presetSkinId = -1; this.customSkin = new CacheCustomSkin(null, resourceLocation, model); } - - protected SkinCacheEntry(int presetSkinId) { - this.isPresetSkin = true; - this.presetSkinId = presetSkinId; - this.customSkin = null; - } - - public ResourceLocation getResourceLocation() { - if(isPresetSkin) { - return DefaultSkins.getSkinFromId(presetSkinId).location; - }else { - if(customSkin != null) { - return customSkin.resourceLocation; - }else { - return DefaultSkins.DEFAULT_STEVE.location; - } - } - } - - public SkinModel getSkinModel() { - if(isPresetSkin) { - return DefaultSkins.getSkinFromId(presetSkinId).model; - }else { - if(customSkin != null) { - return customSkin.model; - }else { - return DefaultSkins.DEFAULT_STEVE.model; - } - } - } - + protected void free() { - if(!isPresetSkin) { + if (!isPresetSkin) { ServerSkinCache.this.textureManager.deleteTexture(customSkin.resourceLocation); } } - } + public ResourceLocation getResourceLocation() { + if (isPresetSkin) { + return DefaultSkins.getSkinFromId(presetSkinId).location; + } else { + if (customSkin != null) { + return customSkin.resourceLocation; + } else { + return DefaultSkins.DEFAULT_STEVE.location; + } + } + } - protected static class CacheCustomSkin { - - protected final EaglerSkinTexture textureInstance; - protected final ResourceLocation resourceLocation; - protected final SkinModel model; - - protected CacheCustomSkin(EaglerSkinTexture textureInstance, ResourceLocation resourceLocation, SkinModel model) { - this.textureInstance = textureInstance; - this.resourceLocation = resourceLocation; - this.model = model; + public SkinModel getSkinModel() { + if (isPresetSkin) { + return DefaultSkins.getSkinFromId(presetSkinId).model; + } else { + if (customSkin != null) { + return customSkin.model; + } else { + return DefaultSkins.DEFAULT_STEVE.model; + } + } } } protected static class WaitingSkin { - + protected final long timeout; protected final SkinModel model; - + protected WaitingSkin(long timeout, SkinModel model) { this.timeout = timeout; this.model = model; @@ -123,25 +124,27 @@ public class ServerSkinCache { } + private static final Logger logger = LogManager.getLogger("ServerSkinCache"); + + private static int texId = 0; + public static boolean needReloadClientSkin = false; private final SkinCacheEntry defaultCacheEntry = new SkinCacheEntry(0); private final SkinCacheEntry defaultSlimCacheEntry = new SkinCacheEntry(1); private final Map skinsCache = new HashMap<>(); + private final Map waitingSkins = new HashMap<>(); private final Map evictedSkins = new HashMap<>(); private final NetHandlerPlayClient netHandler; protected final TextureManager textureManager; - + private final EaglercraftUUID clientPlayerId; private SkinCacheEntry clientPlayerCacheEntry; - private long lastFlush = EagRuntime.steadyTimeMillis(); + private long lastFlushReq = EagRuntime.steadyTimeMillis(); private long lastFlushEvict = EagRuntime.steadyTimeMillis(); - private static int texId = 0; - public static boolean needReloadClientSkin = false; - public ServerSkinCache(NetHandlerPlayClient netHandler, TextureManager textureManager) { this.netHandler = netHandler; this.textureManager = textureManager; @@ -149,68 +152,171 @@ public class ServerSkinCache { reloadClientPlayerSkin(); } - public void reloadClientPlayerSkin() { - needReloadClientSkin = false; - this.clientPlayerCacheEntry = new SkinCacheEntry(EaglerProfile.getActiveSkinResourceLocation(), EaglerProfile.getActiveSkinModel()); + private SkinCacheEntry _getSkin(EaglercraftUUID player) { + SkinCacheEntry etr = skinsCache.get(player); + if (etr == null) { + if (!waitingSkins.containsKey(player) && !evictedSkins.containsKey(player)) { + waitingSkins.put(player, new WaitingSkin(EagRuntime.steadyTimeMillis(), null)); + netHandler.sendEaglerMessage(new CPacketGetOtherSkinEAG(player.msb, player.lsb)); + } + return defaultCacheEntry; + } else { + etr.lastCacheHit = EagRuntime.steadyTimeMillis(); + return etr; + } + } + + public void cacheSkinCustom(EaglercraftUUID player, byte[] pixels, SkinModel model) { + WaitingSkin waitingSkin; + if ((waitingSkin = waitingSkins.remove(player)) != null) { + SkinCacheEntry etr = skinsCache.remove(player); + if (etr != null) { + etr.free(); + } + if (waitingSkin.model != null) { + model = waitingSkin.model; + } else if (model == null) { + model = (player.hashCode() & 1) != 0 ? SkinModel.ALEX : SkinModel.STEVE; + } + try { + etr = new SkinCacheEntry(new EaglerSkinTexture(pixels, model.width, model.height), + new ResourceLocation("eagler:skins/multiplayer/tex_" + texId++), model); + } catch (Throwable t) { + etr = new SkinCacheEntry(0); + logger.error("Could not process custom skin packet for \"{}\"!", player); + logger.error(t); + } + skinsCache.put(player, etr); + } else { + logger.error("Unsolicited skin response recieved for \"{}\"! (custom {}x{})", player, model.width, + model.height); + } + } + + public void cacheSkinPreset(EaglercraftUUID player, int presetId) { + if (waitingSkins.remove(player) != null) { + SkinCacheEntry etr = skinsCache.remove(player); + if (etr != null) { + etr.free(); + } + skinsCache.put(player, new SkinCacheEntry(presetId)); + } else { + logger.error("Unsolicited skin response recieved for \"{}\"! (preset {})", player, presetId); + } + } + + public void destroy() { + Iterator entryItr = skinsCache.values().iterator(); + while (entryItr.hasNext()) { + entryItr.next().free(); + } + skinsCache.clear(); + waitingSkins.clear(); + evictedSkins.clear(); + } + + public void evictSkin(EaglercraftUUID uuid) { + evictedSkins.put(uuid, Long.valueOf(EagRuntime.steadyTimeMillis())); + SkinCacheEntry etr = skinsCache.remove(uuid); + if (etr != null) { + etr.free(); + } + } + + public void flush() { + long millis = EagRuntime.steadyTimeMillis(); + if (millis - lastFlushReq > 5000l) { + lastFlushReq = millis; + if (!waitingSkins.isEmpty()) { + Iterator waitingItr = waitingSkins.values().iterator(); + while (waitingItr.hasNext()) { + if (millis - waitingItr.next().timeout > 20000l) { + waitingItr.remove(); + } + } + } + } + if (millis - lastFlushEvict > 1000l) { + lastFlushEvict = millis; + if (!evictedSkins.isEmpty()) { + Iterator evictItr = evictedSkins.values().iterator(); + while (evictItr.hasNext()) { + if (millis - evictItr.next().longValue() > 3000l) { + evictItr.remove(); + } + } + } + } + if (millis - lastFlush > 60000l) { + lastFlush = millis; + if (!skinsCache.isEmpty()) { + Iterator entryItr = skinsCache.values().iterator(); + while (entryItr.hasNext()) { + SkinCacheEntry etr = entryItr.next(); + if (millis - etr.lastCacheHit > 900000l) { // 15 minutes + entryItr.remove(); + etr.free(); + } + } + } + } + if (needReloadClientSkin) { + reloadClientPlayerSkin(); + } } public SkinCacheEntry getClientPlayerSkin() { return clientPlayerCacheEntry; } - public SkinCacheEntry getSkin(GameProfile player) { - EaglercraftUUID uuid = player.getId(); - if(uuid != null && uuid.equals(clientPlayerId)) { - return clientPlayerCacheEntry; - } - TexturesProperty props = player.getTextures(); - if(props.eaglerPlayer || props.skin == null) { - if(uuid != null) { - return _getSkin(uuid); - }else { - if("slim".equalsIgnoreCase(props.model)) { - return defaultSlimCacheEntry; - }else { - return defaultCacheEntry; - } - } - }else { - return getSkin(props.skin, SkinModel.getModelFromId(props.model)); + public SkinModel getRequestedSkinType(EaglercraftUUID waiting) { + WaitingSkin waitingSkin; + if ((waitingSkin = waitingSkins.get(waiting)) != null) { + return waitingSkin.model; + } else { + return null; } } public SkinCacheEntry getSkin(EaglercraftUUID player) { - if(player.equals(clientPlayerId)) { + if (player.equals(clientPlayerId)) { return clientPlayerCacheEntry; } return _getSkin(player); } - private SkinCacheEntry _getSkin(EaglercraftUUID player) { - SkinCacheEntry etr = skinsCache.get(player); - if(etr == null) { - if(!waitingSkins.containsKey(player) && !evictedSkins.containsKey(player)) { - waitingSkins.put(player, new WaitingSkin(EagRuntime.steadyTimeMillis(), null)); - netHandler.sendEaglerMessage(new CPacketGetOtherSkinEAG(player.msb, player.lsb)); + public SkinCacheEntry getSkin(GameProfile player) { + EaglercraftUUID uuid = player.getId(); + if (uuid != null && uuid.equals(clientPlayerId)) { + return clientPlayerCacheEntry; + } + TexturesProperty props = player.getTextures(); + if (props.eaglerPlayer || props.skin == null) { + if (uuid != null) { + return _getSkin(uuid); + } else { + if ("slim".equalsIgnoreCase(props.model)) { + return defaultSlimCacheEntry; + } else { + return defaultCacheEntry; + } } - return defaultCacheEntry; - }else { - etr.lastCacheHit = EagRuntime.steadyTimeMillis(); - return etr; + } else { + return getSkin(props.skin, SkinModel.getModelFromId(props.model)); } } public SkinCacheEntry getSkin(String url, SkinModel skinModelResponse) { - if(url.length() > 0xFFFF) { + if (url.length() > 0xFFFF) { return skinModelResponse == SkinModel.ALEX ? defaultSlimCacheEntry : defaultCacheEntry; } EaglercraftUUID generatedUUID = SkinPackets.createEaglerURLSkinUUID(url); SkinCacheEntry etr = skinsCache.get(generatedUUID); - if(etr != null) { + if (etr != null) { etr.lastCacheHit = EagRuntime.steadyTimeMillis(); return etr; - }else { - if(!waitingSkins.containsKey(generatedUUID) && !evictedSkins.containsKey(generatedUUID)) { + } else { + if (!waitingSkins.containsKey(generatedUUID) && !evictedSkins.containsKey(generatedUUID)) { waitingSkins.put(generatedUUID, new WaitingSkin(EagRuntime.steadyTimeMillis(), skinModelResponse)); netHandler.sendEaglerMessage(new CPacketGetSkinByURLEAG(generatedUUID.msb, generatedUUID.lsb, url)); } @@ -218,118 +324,17 @@ public class ServerSkinCache { return skinModelResponse == SkinModel.ALEX ? defaultSlimCacheEntry : defaultCacheEntry; } - public void cacheSkinPreset(EaglercraftUUID player, int presetId) { - if(waitingSkins.remove(player) != null) { - SkinCacheEntry etr = skinsCache.remove(player); - if(etr != null) { - etr.free(); - } - skinsCache.put(player, new SkinCacheEntry(presetId)); - }else { - logger.error("Unsolicited skin response recieved for \"{}\"! (preset {})", player, presetId); - } - } - - public void cacheSkinCustom(EaglercraftUUID player, byte[] pixels, SkinModel model) { - WaitingSkin waitingSkin; - if((waitingSkin = waitingSkins.remove(player)) != null) { - SkinCacheEntry etr = skinsCache.remove(player); - if(etr != null) { - etr.free(); - } - if(waitingSkin.model != null) { - model = waitingSkin.model; - }else if(model == null) { - model = (player.hashCode() & 1) != 0 ? SkinModel.ALEX : SkinModel.STEVE; - } - try { - etr = new SkinCacheEntry(new EaglerSkinTexture(pixels, model.width, model.height), - new ResourceLocation("eagler:skins/multiplayer/tex_" + texId++), model); - }catch(Throwable t) { - etr = new SkinCacheEntry(0); - logger.error("Could not process custom skin packet for \"{}\"!", player); - logger.error(t); - } - skinsCache.put(player, etr); - }else { - logger.error("Unsolicited skin response recieved for \"{}\"! (custom {}x{})", player, model.width, model.height); - } - } - - public SkinModel getRequestedSkinType(EaglercraftUUID waiting) { - WaitingSkin waitingSkin; - if((waitingSkin = waitingSkins.get(waiting)) != null) { - return waitingSkin.model; - }else { - return null; - } - } - - public void flush() { - long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastFlushReq > 5000l) { - lastFlushReq = millis; - if(!waitingSkins.isEmpty()) { - Iterator waitingItr = waitingSkins.values().iterator(); - while(waitingItr.hasNext()) { - if(millis - waitingItr.next().timeout > 20000l) { - waitingItr.remove(); - } - } - } - } - if(millis - lastFlushEvict > 1000l) { - lastFlushEvict = millis; - if(!evictedSkins.isEmpty()) { - Iterator evictItr = evictedSkins.values().iterator(); - while(evictItr.hasNext()) { - if(millis - evictItr.next().longValue() > 3000l) { - evictItr.remove(); - } - } - } - } - if(millis - lastFlush > 60000l) { - lastFlush = millis; - if(!skinsCache.isEmpty()) { - Iterator entryItr = skinsCache.values().iterator(); - while(entryItr.hasNext()) { - SkinCacheEntry etr = entryItr.next(); - if(millis - etr.lastCacheHit > 900000l) { // 15 minutes - entryItr.remove(); - etr.free(); - } - } - } - } - if(needReloadClientSkin) { - reloadClientPlayerSkin(); - } - } - - public void destroy() { - Iterator entryItr = skinsCache.values().iterator(); - while(entryItr.hasNext()) { - entryItr.next().free(); - } - skinsCache.clear(); - waitingSkins.clear(); - evictedSkins.clear(); - } - - public void evictSkin(EaglercraftUUID uuid) { - evictedSkins.put(uuid, Long.valueOf(EagRuntime.steadyTimeMillis())); + public void handleInvalidate(EaglercraftUUID uuid) { SkinCacheEntry etr = skinsCache.remove(uuid); - if(etr != null) { + if (etr != null) { etr.free(); } } - public void handleInvalidate(EaglercraftUUID uuid) { - SkinCacheEntry etr = skinsCache.remove(uuid); - if(etr != null) { - etr.free(); - } + public void reloadClientPlayerSkin() { + needReloadClientSkin = false; + this.clientPlayerCacheEntry = new SkinCacheEntry(EaglerProfile.getActiveSkinResourceLocation(), + EaglerProfile.getActiveSkinModel()); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinConverter.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinConverter.java index 8e7a627b..55d75b2c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinConverter.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinConverter.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.opengl.ImageData; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,74 +36,65 @@ public class SkinConverter { copyRawPixels(skinIn.pixels, skinOut.pixels, 48, 52, 44, 64, 52, 20, 56, 32, 64, 64); } - public static void convertCape32x32RGBAto23x17RGB(ImageData skinIn, byte[] skinOut) { - int i, j; - for(int y = 0; y < 17; ++y) { - for(int x = 0; x < 22; ++x) { - i = (y * 23 + x) * 3; - j = skinIn.pixels[y * skinIn.width + x]; - if((j & 0xFF000000) != 0) { - skinOut[i] = (byte)(j >>> 16); - skinOut[i + 1] = (byte)(j >>> 8); - skinOut[i + 2] = (byte)(j & 0xFF); - }else { - skinOut[i] = skinOut[i + 1] = skinOut[i + 2] = 0; - } - } - } - for(int y = 0; y < 11; ++y) { - i = ((y + 6) * 23 + 22) * 3; - j = skinIn.pixels[(y + 11) * skinIn.width + 22]; - if((j & 0xFF000000) != 0) { - skinOut[i] = (byte)(j >>> 16); - skinOut[i + 1] = (byte)(j >>> 8); - skinOut[i + 2] = (byte)(j & 0xFF); - }else { - skinOut[i] = skinOut[i + 1] = skinOut[i + 2] = 0; - } - } - } - public static void convertCape23x17RGBto32x32RGBA(byte[] skinIn, byte[] skinOut) { int i, j; - for(int y = 0; y < 17; ++y) { - for(int x = 0; x < 22; ++x) { + for (int y = 0; y < 17; ++y) { + for (int x = 0; x < 22; ++x) { i = (y * 32 + x) << 2; j = (y * 23 + x) * 3; - skinOut[i] = (byte)0xFF; + skinOut[i] = (byte) 0xFF; skinOut[i + 1] = skinIn[j]; skinOut[i + 2] = skinIn[j + 1]; skinOut[i + 3] = skinIn[j + 2]; } } - for(int y = 0; y < 11; ++y) { + for (int y = 0; y < 11; ++y) { i = ((y + 11) * 32 + 22) << 2; j = ((y + 6) * 23 + 22) * 3; - skinOut[i] = (byte)0xFF; + skinOut[i] = (byte) 0xFF; skinOut[i + 1] = skinIn[j]; skinOut[i + 2] = skinIn[j + 1]; skinOut[i + 3] = skinIn[j + 2]; } } - private static void copyRawPixels(int[] imageIn, int[] imageOut, int dx1, int dy1, int dx2, int dy2, int sx1, - int sy1, int sx2, int sy2, int imgSrcWidth, int imgDstWidth) { - if(dx1 > dx2) { - copyRawPixels(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, imgSrcWidth, imgDstWidth, true); - } else { - copyRawPixels(imageIn, imageOut, sx1, sy1, dx1, dy1, sx2 - sx1, sy2 - sy1, imgSrcWidth, imgDstWidth, false); + public static void convertCape32x32RGBAto23x17RGB(ImageData skinIn, byte[] skinOut) { + int i, j; + for (int y = 0; y < 17; ++y) { + for (int x = 0; x < 22; ++x) { + i = (y * 23 + x) * 3; + j = skinIn.pixels[y * skinIn.width + x]; + if ((j & 0xFF000000) != 0) { + skinOut[i] = (byte) (j >>> 16); + skinOut[i + 1] = (byte) (j >>> 8); + skinOut[i + 2] = (byte) (j & 0xFF); + } else { + skinOut[i] = skinOut[i + 1] = skinOut[i + 2] = 0; + } + } + } + for (int y = 0; y < 11; ++y) { + i = ((y + 6) * 23 + 22) * 3; + j = skinIn.pixels[(y + 11) * skinIn.width + 22]; + if ((j & 0xFF000000) != 0) { + skinOut[i] = (byte) (j >>> 16); + skinOut[i + 1] = (byte) (j >>> 8); + skinOut[i + 2] = (byte) (j & 0xFF); + } else { + skinOut[i] = skinOut[i + 1] = skinOut[i + 2] = 0; + } } } private static void copyRawPixels(int[] imageIn, int[] imageOut, int srcX, int srcY, int dstX, int dstY, int width, int height, int imgSrcWidth, int imgDstWidth, boolean flip) { int i, j; - for(int y = 0; y < height; ++y) { - for(int x = 0; x < width; ++x) { + for (int y = 0; y < height; ++y) { + for (int x = 0; x < width; ++x) { i = imageIn[(srcY + y) * imgSrcWidth + srcX + x]; - if(flip) { + if (flip) { j = (dstY + y) * imgDstWidth + dstX + width - x - 1; - }else { + } else { j = (dstY + y) * imgDstWidth + dstX + x; } imageOut[j] = i; @@ -110,4 +102,13 @@ public class SkinConverter { } } + private static void copyRawPixels(int[] imageIn, int[] imageOut, int dx1, int dy1, int dx2, int dy2, int sx1, + int sy1, int sx2, int sy2, int imgSrcWidth, int imgDstWidth) { + if (dx1 > dx2) { + copyRawPixels(imageIn, imageOut, sx1, sy1, dx2, dy1, sx2 - sx1, sy2 - sy1, imgSrcWidth, imgDstWidth, true); + } else { + copyRawPixels(imageIn, imageOut, sx1, sy1, dx1, dy1, sx2 - sx1, sy2 - sy1, imgSrcWidth, imgDstWidth, false); + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinModel.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinModel.java index 541c51e9..95e91773 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinModel.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinModel.java @@ -6,14 +6,15 @@ import java.util.Map; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,26 +24,48 @@ public enum SkinModel { LONG_ARMS(3, HighPolySkin.LONG_ARMS), WEIRD_CLIMBER_DUDE(4, HighPolySkin.WEIRD_CLIMBER_DUDE), LAXATIVE_DUDE(5, HighPolySkin.LAXATIVE_DUDE), BABY_CHARLES(6, HighPolySkin.BABY_CHARLES), BABY_WINSTON(7, HighPolySkin.BABY_WINSTON); - - public final int id; - public final int width; - public final int height; - public final String profileSkinType; - public final boolean sanitize; - public final HighPolySkin highPoly; - + public static final SkinModel[] skinModels = new SkinModel[8]; private static final Map skinModelsByName = new HashMap<>(); - - private SkinModel(int id, int w, int h, String profileSkinType, boolean sanitize) { - this.id = id; - this.width = w; - this.height = h; - this.profileSkinType = profileSkinType; - this.sanitize = sanitize; - this.highPoly = null; + static { + SkinModel[] arr = values(); + for (int i = 0; i < arr.length; ++i) { + skinModels[arr[i].id] = arr[i]; + skinModelsByName.put(arr[i].profileSkinType, arr[i]); + } } - + + public static SkinModel getModelFromId(int id) { + SkinModel s = null; + if (id >= 0 && id < skinModels.length) { + s = skinModels[id]; + } + if (s != null) { + return s; + } else { + return STEVE; + } + } + + public static SkinModel getModelFromId(String str) { + SkinModel mdl = skinModelsByName.get(str.toLowerCase()); + if (mdl == null) { + return skinModels[0]; + } + return mdl; + } + + public final int id; + + public final int width; + public final int height; + + public final String profileSkinType; + + public final boolean sanitize; + + public final HighPolySkin highPoly; + private SkinModel(int id, HighPolySkin highPoly) { this.id = id; this.width = 256; @@ -52,32 +75,13 @@ public enum SkinModel { this.highPoly = highPoly; } - public static SkinModel getModelFromId(String str) { - SkinModel mdl = skinModelsByName.get(str.toLowerCase()); - if(mdl == null) { - return skinModels[0]; - } - return mdl; - } - - public static SkinModel getModelFromId(int id) { - SkinModel s = null; - if(id >= 0 && id < skinModels.length) { - s = skinModels[id]; - } - if(s != null) { - return s; - }else { - return STEVE; - } - } - - static { - SkinModel[] arr = values(); - for(int i = 0; i < arr.length; ++i) { - skinModels[arr[i].id] = arr[i]; - skinModelsByName.put(arr[i].profileSkinType, arr[i]); - } + private SkinModel(int id, int w, int h, String profileSkinType, boolean sanitize) { + this.id = id; + this.width = w; + this.height = h; + this.profileSkinType = profileSkinType; + this.sanitize = sanitize; + this.highPoly = null; } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPackets.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPackets.java index b91d7013..ed27f173 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPackets.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPackets.java @@ -7,14 +7,15 @@ import net.lax1dude.eaglercraft.v1_8.crypto.MD5Digest; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,9 +25,17 @@ public class SkinPackets { public static final int PACKET_MY_SKIN_PRESET = 0x01; public static final int PACKET_MY_SKIN_CUSTOM = 0x02; - public static byte[] writeMySkinPreset(int skinId) { - return new byte[] { (byte) PACKET_MY_SKIN_PRESET, (byte) (skinId >>> 24), (byte) (skinId >>> 16), - (byte) (skinId >>> 8), (byte) (skinId & 0xFF) }; + public static EaglercraftUUID createEaglerURLSkinUUID(String skinUrl) { + MD5Digest dg = new MD5Digest(); + byte[] bytes = ArrayUtils.asciiString("EaglercraftSkinURL:" + skinUrl); + dg.update(bytes, 0, bytes.length); + byte[] md5Bytes = new byte[16]; + dg.doFinal(md5Bytes, 0); + md5Bytes[6] &= 0x0f; + md5Bytes[6] |= 0x30; + md5Bytes[8] &= 0x3f; + md5Bytes[8] |= 0x80; + return new EaglercraftUUID(md5Bytes); } public static byte[] writeMySkinCustomV3(CustomSkin customSkin) { @@ -42,27 +51,19 @@ public class SkinPackets { packet[0] = (byte) PACKET_MY_SKIN_CUSTOM; packet[1] = (byte) customSkin.model.id; byte[] v3data = customSkin.texture; - for(int i = 0, j, k; i < 4096; ++i) { + for (int i = 0, j, k; i < 4096; ++i) { j = i << 2; k = i * 3 + 2; packet[k] = v3data[j + 1]; packet[k + 1] = v3data[j + 2]; - packet[k + 2] = (byte)((v3data[j + 3] >>> 1) | (v3data[j] & 0x80)); + packet[k + 2] = (byte) ((v3data[j + 3] >>> 1) | (v3data[j] & 0x80)); } return packet; } - public static EaglercraftUUID createEaglerURLSkinUUID(String skinUrl){ - MD5Digest dg = new MD5Digest(); - byte[] bytes = ArrayUtils.asciiString("EaglercraftSkinURL:" + skinUrl); - dg.update(bytes, 0, bytes.length); - byte[] md5Bytes = new byte[16]; - dg.doFinal(md5Bytes, 0); - md5Bytes[6] &= 0x0f; - md5Bytes[6] |= 0x30; - md5Bytes[8] &= 0x3f; - md5Bytes[8] |= 0x80; - return new EaglercraftUUID(md5Bytes); + public static byte[] writeMySkinPreset(int skinId) { + return new byte[] { (byte) PACKET_MY_SKIN_PRESET, (byte) (skinId >>> 24), (byte) (skinId >>> 16), + (byte) (skinId >>> 8), (byte) (skinId & 0xFF) }; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPreviewRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPreviewRenderer.java index 999c396a..98995b15 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPreviewRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/profile/SkinPreviewRenderer.java @@ -14,14 +14,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,7 +32,7 @@ public class SkinPreviewRenderer { private static ModelPlayer playerModelSteve = null; private static ModelPlayer playerModelAlex = null; private static ModelZombie playerModelZombie = null; - + public static void initialize() { playerModelSteve = new ModelPlayer(0.0f, false); playerModelSteve.isChild = false; @@ -41,13 +42,73 @@ public class SkinPreviewRenderer { playerModelZombie.isChild = false; } - public static void renderPreview(int x, int y, int mx, int my, SkinModel skinModel) { - renderPreview(x, y, mx, my, false, skinModel, null, null); + private static void renderHighPoly(int x, int y, int mx, int my, HighPolySkin msh) { + GlStateManager.enableTexture2D(); + GlStateManager.disableBlend(); + GlStateManager.disableCull(); + GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); + + GlStateManager.pushMatrix(); + GlStateManager.translate(x, y - 80.0f, 100.0f); + GlStateManager.scale(50.0f, 50.0f, 50.0f); + GlStateManager.rotate(180.0f, 1.0f, 0.0f, 0.0f); + GlStateManager.scale(1.0f, -1.0f, 1.0f); + + RenderHelper.enableGUIStandardItemLighting(); + + GlStateManager.translate(0.0f, 1.0f, 0.0f); + GlStateManager.rotate(((y - my) * -0.06f), 1.0f, 0.0f, 0.0f); + GlStateManager.rotate(((x - mx) * 0.06f), 0.0f, 1.0f, 0.0f); + GlStateManager.rotate(180.0f, 0.0f, 0.0f, 1.0f); + GlStateManager.translate(0.0f, -0.6f, 0.0f); + + GlStateManager.scale(HighPolySkin.highPolyScale, HighPolySkin.highPolyScale, HighPolySkin.highPolyScale); + Minecraft.getMinecraft().getTextureManager().bindTexture(msh.texture); + + if (msh.bodyModel != null) { + EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(msh.bodyModel)); + } + + if (msh.headModel != null) { + EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(msh.headModel)); + } + + if (msh.limbsModel != null && msh.limbsModel.length > 0) { + for (int i = 0; i < msh.limbsModel.length; ++i) { + float offset = 0.0f; + if (msh.limbsOffset != null) { + if (msh.limbsOffset.length == 1) { + offset = msh.limbsOffset[0]; + } else { + offset = msh.limbsOffset[i]; + } + } + if (offset != 0.0f || msh.limbsInitialRotation != 0.0f) { + GlStateManager.pushMatrix(); + if (offset != 0.0f) { + GlStateManager.translate(0.0f, offset, 0.0f); + } + if (msh.limbsInitialRotation != 0.0f) { + GlStateManager.rotate(msh.limbsInitialRotation, 1.0f, 0.0f, 0.0f); + } + } + + EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(msh.limbsModel[i])); + + if (offset != 0.0f || msh.limbsInitialRotation != 0.0f) { + GlStateManager.popMatrix(); + } + } + } + + GlStateManager.popMatrix(); + GlStateManager.disableLighting(); } - public static void renderPreview(int x, int y, int mx, int my, boolean capeMode, SkinModel skinModel, ResourceLocation skinTexture, ResourceLocation capeTexture) { + public static void renderPreview(int x, int y, int mx, int my, boolean capeMode, SkinModel skinModel, + ResourceLocation skinTexture, ResourceLocation capeTexture) { ModelBiped model; - switch(skinModel) { + switch (skinModel) { case STEVE: default: model = playerModelSteve; @@ -63,119 +124,61 @@ public class SkinPreviewRenderer { case LAXATIVE_DUDE: case BABY_CHARLES: case BABY_WINSTON: - if(skinModel.highPoly != null && Minecraft.getMinecraft().gameSettings.enableFNAWSkins) { + if (skinModel.highPoly != null && Minecraft.getMinecraft().gameSettings.enableFNAWSkins) { renderHighPoly(x, y, mx, my, skinModel.highPoly); return; } model = playerModelSteve; break; } - + GlStateManager.enableTexture2D(); GlStateManager.disableBlend(); GlStateManager.disableCull(); GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - + GlStateManager.pushMatrix(); GlStateManager.translate(x, y - 80.0f, 100.0f); GlStateManager.scale(50.0f, 50.0f, 50.0f); GlStateManager.rotate(180.0f, 1.0f, 0.0f, 0.0f); GlStateManager.scale(1.0f, -1.0f, 1.0f); - + RenderHelper.enableGUIStandardItemLighting(); - + GlStateManager.translate(0.0f, 1.0f, 0.0f); - if(capeMode) { + if (capeMode) { GlStateManager.rotate(140.0f, 0.0f, 1.0f, 0.0f); mx = x - (x - mx) - 20; GlStateManager.rotate(((y - my) * -0.02f), 1.0f, 0.0f, 0.0f); - }else { + } else { GlStateManager.rotate(((y - my) * -0.06f), 1.0f, 0.0f, 0.0f); } GlStateManager.rotate(((x - mx) * 0.06f), 0.0f, 1.0f, 0.0f); GlStateManager.translate(0.0f, -1.0f, 0.0f); - - if(skinTexture != null) { + + if (skinTexture != null) { Minecraft.getMinecraft().getTextureManager().bindTexture(skinTexture); } - - model.render(null, 0.0f, 0.0f, (float)(EagRuntime.steadyTimeMillis() % 2000000) / 50f, ((x - mx) * 0.06f), ((y - my) * -0.1f), 0.0625f); - - if(capeTexture != null && model instanceof ModelPlayer) { + + model.render(null, 0.0f, 0.0f, (float) (EagRuntime.steadyTimeMillis() % 2000000) / 50f, ((x - mx) * 0.06f), + ((y - my) * -0.1f), 0.0625f); + + if (capeTexture != null && model instanceof ModelPlayer) { Minecraft.getMinecraft().getTextureManager().bindTexture(capeTexture); GlStateManager.pushMatrix(); GlStateManager.translate(0.0F, 0.0F, 0.125F); GlStateManager.rotate(6.0F, 1.0F, 0.0F, 0.0F); GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F); - ((ModelPlayer)model).renderCape(0.0625f); + ((ModelPlayer) model).renderCape(0.0625f); GlStateManager.popMatrix(); } - + GlStateManager.popMatrix(); GlStateManager.disableLighting(); } - private static void renderHighPoly(int x, int y, int mx, int my, HighPolySkin msh) { - GlStateManager.enableTexture2D(); - GlStateManager.disableBlend(); - GlStateManager.disableCull(); - GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); - - GlStateManager.pushMatrix(); - GlStateManager.translate(x, y - 80.0f, 100.0f); - GlStateManager.scale(50.0f, 50.0f, 50.0f); - GlStateManager.rotate(180.0f, 1.0f, 0.0f, 0.0f); - GlStateManager.scale(1.0f, -1.0f, 1.0f); - - RenderHelper.enableGUIStandardItemLighting(); - - GlStateManager.translate(0.0f, 1.0f, 0.0f); - GlStateManager.rotate(((y - my) * -0.06f), 1.0f, 0.0f, 0.0f); - GlStateManager.rotate(((x - mx) * 0.06f), 0.0f, 1.0f, 0.0f); - GlStateManager.rotate(180.0f, 0.0f, 0.0f, 1.0f); - GlStateManager.translate(0.0f, -0.6f, 0.0f); - - GlStateManager.scale(HighPolySkin.highPolyScale, HighPolySkin.highPolyScale, HighPolySkin.highPolyScale); - Minecraft.getMinecraft().getTextureManager().bindTexture(msh.texture); - - if(msh.bodyModel != null) { - EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(msh.bodyModel)); - } - - if(msh.headModel != null) { - EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(msh.headModel)); - } - - if(msh.limbsModel != null && msh.limbsModel.length > 0) { - for(int i = 0; i < msh.limbsModel.length; ++i) { - float offset = 0.0f; - if(msh.limbsOffset != null) { - if(msh.limbsOffset.length == 1) { - offset = msh.limbsOffset[0]; - }else { - offset = msh.limbsOffset[i]; - } - } - if(offset != 0.0f || msh.limbsInitialRotation != 0.0f) { - GlStateManager.pushMatrix(); - if(offset != 0.0f) { - GlStateManager.translate(0.0f, offset, 0.0f); - } - if(msh.limbsInitialRotation != 0.0f) { - GlStateManager.rotate(msh.limbsInitialRotation, 1.0f, 0.0f, 0.0f); - } - } - - EaglercraftGPU.drawHighPoly(EaglerMeshLoader.getEaglerMesh(msh.limbsModel[i])); - - if(offset != 0.0f || msh.limbsInitialRotation != 0.0f) { - GlStateManager.popMatrix(); - } - } - } - - GlStateManager.popMatrix(); - GlStateManager.disableLighting(); + public static void renderPreview(int x, int y, int mx, int my, SkinModel skinModel) { + renderPreview(x, y, mx, my, false, skinModel, null, null); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/EnumScreenRecordingCodec.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/EnumScreenRecordingCodec.java index 3c1b4d95..e24bb678 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/EnumScreenRecordingCodec.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/EnumScreenRecordingCodec.java @@ -3,117 +3,122 @@ package net.lax1dude.eaglercraft.v1_8.recording; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum EnumScreenRecordingCodec { - CODEC_MP4_H264_GENERIC_AAC("MP4 (video: H.264 Default, audio: AAC LC)", "mp4", "video/mp4", "avc1", "mp4a.40.2", false), + CODEC_MP4_H264_GENERIC_AAC("MP4 (video: H.264 Default, audio: AAC LC)", "mp4", "video/mp4", "avc1", "mp4a.40.2", + false), CODEC_MP4_H264_GENERIC_OPUS("MP4 (video: H.264 Default, audio: Opus)", "mp4", "video/mp4", "avc1", "opus", false), - CODEC_MP4_H264_L40_AAC("MP4 (video: H.264 CBP L4.0, audio: AAC LC)", "mp4", "video/mp4", "avc1.424028", "mp4a.40.2", true), - CODEC_MP4_H264_L40_OPUS("MP4 (video: H.264 CBP L4.0, audio: Opus)", "mp4", "video/mp4", "avc1.424028", "opus", true), - CODEC_MP4_H264_L42_AAC("MP4 (video: H.264 CBP L4.2, audio: AAC LC)", "mp4", "video/mp4", "avc1.42402A", "mp4a.40.2", true), - CODEC_MP4_H264_L42_OPUS("MP4 (video: H.264 CBP L4.2, audio: Opus)", "mp4", "video/mp4", "avc1.42402A", "opus", true), - CODEC_MP4_H264_L50_AAC("MP4 (video: H.264 CBP L5.0, audio: AAC LC)", "mp4", "video/mp4", "avc1.424032", "mp4a.40.2", true), - CODEC_MP4_H264_L50_OPUS("MP4 (video: H.264 CBP L5.0, audio: Opus)", "mp4", "video/mp4", "avc1.424032", "opus", true), - CODEC_MP4_H264_L52_AAC("MP4 (video: H.264 CBP L5.2, audio: AAC LC)", "mp4", "video/mp4", "avc1.424034", "mp4a.40.2", true), - CODEC_MP4_H264_L52_OPUS("MP4 (video: H.264 CBP L5.2, audio: Opus)", "mp4", "video/mp4", "avc1.424034", "opus", true), + CODEC_MP4_H264_L40_AAC("MP4 (video: H.264 CBP L4.0, audio: AAC LC)", "mp4", "video/mp4", "avc1.424028", "mp4a.40.2", + true), + CODEC_MP4_H264_L40_OPUS("MP4 (video: H.264 CBP L4.0, audio: Opus)", "mp4", "video/mp4", "avc1.424028", "opus", + true), + CODEC_MP4_H264_L42_AAC("MP4 (video: H.264 CBP L4.2, audio: AAC LC)", "mp4", "video/mp4", "avc1.42402A", "mp4a.40.2", + true), + CODEC_MP4_H264_L42_OPUS("MP4 (video: H.264 CBP L4.2, audio: Opus)", "mp4", "video/mp4", "avc1.42402A", "opus", + true), + CODEC_MP4_H264_L50_AAC("MP4 (video: H.264 CBP L5.0, audio: AAC LC)", "mp4", "video/mp4", "avc1.424032", "mp4a.40.2", + true), + CODEC_MP4_H264_L50_OPUS("MP4 (video: H.264 CBP L5.0, audio: Opus)", "mp4", "video/mp4", "avc1.424032", "opus", + true), + CODEC_MP4_H264_L52_AAC("MP4 (video: H.264 CBP L5.2, audio: AAC LC)", "mp4", "video/mp4", "avc1.424034", "mp4a.40.2", + true), + CODEC_MP4_H264_L52_OPUS("MP4 (video: H.264 CBP L5.2, audio: Opus)", "mp4", "video/mp4", "avc1.424034", "opus", + true), CODEC_MP4_VP9_GENERIC_AAC("MP4 (video: VP9 Default, audio: AAC LC)", "mp4", "video/mp4", "vp9", "mp4a.40.2", false), CODEC_MP4_VP9_GENERIC_OPUS("MP4 (video: VP9 Default, audio: Opus)", "mp4", "video/mp4", "vp9", "opus", false), - CODEC_MP4_VP9_L40_AAC("MP4 (video: VP9 8-bit L4.0, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.40.08", "mp4a.40.2", true), - CODEC_MP4_VP9_L40_OPUS("MP4 (video: VP9 8-bit L4.0, audio: Opus)", "mp4", "video/mp4", "vp9.00.40.08", "opus", true), - CODEC_MP4_VP9_L41_AAC("MP4 (video: VP9 8-bit L4.1, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.41.08", "mp4a.40.2", true), - CODEC_MP4_VP9_L41_OPUS("MP4 (video: VP9 8-bit L4.1, audio: Opus)", "mp4", "video/mp4", "vp9.00.41.08", "opus", true), - CODEC_MP4_VP9_L50_AAC("MP4 (video: VP9 8-bit L5.0, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.50.08", "mp4a.40.2", true), - CODEC_MP4_VP9_L50_OPUS("MP4 (video: VP9 8-bit L5.0, audio: Opus)", "mp4", "video/mp4", "vp9.00.50.08", "opus", true), - CODEC_MP4_VP9_L51_AAC("MP4 (video: VP9 8-bit L5.1, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.51.08", "mp4a.40.2", true), - CODEC_MP4_VP9_L51_OPUS("MP4 (video: VP9 8-bit L5.1, audio: Opus)", "mp4", "video/mp4", "vp9.00.51.08", "opus", true), + CODEC_MP4_VP9_L40_AAC("MP4 (video: VP9 8-bit L4.0, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.40.08", "mp4a.40.2", + true), + CODEC_MP4_VP9_L40_OPUS("MP4 (video: VP9 8-bit L4.0, audio: Opus)", "mp4", "video/mp4", "vp9.00.40.08", "opus", + true), + CODEC_MP4_VP9_L41_AAC("MP4 (video: VP9 8-bit L4.1, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.41.08", "mp4a.40.2", + true), + CODEC_MP4_VP9_L41_OPUS("MP4 (video: VP9 8-bit L4.1, audio: Opus)", "mp4", "video/mp4", "vp9.00.41.08", "opus", + true), + CODEC_MP4_VP9_L50_AAC("MP4 (video: VP9 8-bit L5.0, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.50.08", "mp4a.40.2", + true), + CODEC_MP4_VP9_L50_OPUS("MP4 (video: VP9 8-bit L5.0, audio: Opus)", "mp4", "video/mp4", "vp9.00.50.08", "opus", + true), + CODEC_MP4_VP9_L51_AAC("MP4 (video: VP9 8-bit L5.1, audio: AAC LC)", "mp4", "video/mp4", "vp9.00.51.08", "mp4a.40.2", + true), + CODEC_MP4_VP9_L51_OPUS("MP4 (video: VP9 8-bit L5.1, audio: Opus)", "mp4", "video/mp4", "vp9.00.51.08", "opus", + true), CODEC_MP4_GENERIC("MP4 (Default Codecs)", "mp4", "video/mp4", null, null, false), - CODEC_WEBM_H264_GENERIC_OPUS("WEBM (video: H.264 Default, audio: Opus)", "webm", "video/webm", "avc1", "opus", false), - CODEC_WEBM_H264_GENERIC_VORBIS("WEBM (video: H.264 Default, audio: Vorbis)", "webm", "video/webm", "avc1", "vorbis", false), - CODEC_WEBM_H264_L40_OPUS("WEBM (video: H.264 CBP L4.0, audio: Opus)", "webm", "video/webm", "avc1.424028", "opus", true), - CODEC_WEBM_H264_L40_VORBIS("WEBM (video: H.264 CBP L4.0, audio: Vorbis)", "webm", "video/webm", "avc1.424028", "vorbis", true), - CODEC_WEBM_H264_L42_OPUS("WEBM (video: H.264 CBP L4.2, audio: Opus)", "webm", "video/webm", "avc1.42402A", "opus", true), - CODEC_WEBM_H264_L42_VORBIS("WEBM (video: H.264 CBP L4.2, audio: Vorbis)", "webm", "video/webm", "avc1.42402A", "vorbis", true), - CODEC_WEBM_H264_L50_OPUS("WEBM (video: H.264 CBP L5.0, audio: Opus)", "webm", "video/webm", "avc1.424032", "opus", true), - CODEC_WEBM_H264_L50_VORBIS("WEBM (video: H.264 CBP L5.0, audio: Vorbis)", "webm", "video/webm", "avc1.424032", "vorbis", true), - CODEC_WEBM_H264_L52_OPUS("WEBM (video: H.264 CBP L5.2, audio: Opus)", "webm", "video/webm", "avc1.424034", "opus", true), - CODEC_WEBM_H264_L52_VORBIS("WEBM (video: H.264 CBP L5.2, audio: Vorbis)", "webm", "video/webm", "avc1.424034", "vorbis", true), + CODEC_WEBM_H264_GENERIC_OPUS("WEBM (video: H.264 Default, audio: Opus)", "webm", "video/webm", "avc1", "opus", + false), + CODEC_WEBM_H264_GENERIC_VORBIS("WEBM (video: H.264 Default, audio: Vorbis)", "webm", "video/webm", "avc1", "vorbis", + false), + CODEC_WEBM_H264_L40_OPUS("WEBM (video: H.264 CBP L4.0, audio: Opus)", "webm", "video/webm", "avc1.424028", "opus", + true), + CODEC_WEBM_H264_L40_VORBIS("WEBM (video: H.264 CBP L4.0, audio: Vorbis)", "webm", "video/webm", "avc1.424028", + "vorbis", true), + CODEC_WEBM_H264_L42_OPUS("WEBM (video: H.264 CBP L4.2, audio: Opus)", "webm", "video/webm", "avc1.42402A", "opus", + true), + CODEC_WEBM_H264_L42_VORBIS("WEBM (video: H.264 CBP L4.2, audio: Vorbis)", "webm", "video/webm", "avc1.42402A", + "vorbis", true), + CODEC_WEBM_H264_L50_OPUS("WEBM (video: H.264 CBP L5.0, audio: Opus)", "webm", "video/webm", "avc1.424032", "opus", + true), + CODEC_WEBM_H264_L50_VORBIS("WEBM (video: H.264 CBP L5.0, audio: Vorbis)", "webm", "video/webm", "avc1.424032", + "vorbis", true), + CODEC_WEBM_H264_L52_OPUS("WEBM (video: H.264 CBP L5.2, audio: Opus)", "webm", "video/webm", "avc1.424034", "opus", + true), + CODEC_WEBM_H264_L52_VORBIS("WEBM (video: H.264 CBP L5.2, audio: Vorbis)", "webm", "video/webm", "avc1.424034", + "vorbis", true), CODEC_WEBM_VP9_GENERIC_OPUS("WEBM (video: VP9 Default, audio: Opus)", "webm", "video/webm", "vp9", "opus", false), - CODEC_WEBM_VP9_GENERIC_VORBIS("WEBM (video: VP9 Default, audio: Vorbis)", "webm", "video/webm", "vp9", "vorbis", false), - CODEC_WEBM_VP9_L40_OPUS("WEBM (video: VP9 8-bit L4.0, audio: Opus)", "webm", "video/webm", "vp9.00.40.08", "opus", true), - CODEC_WEBM_VP9_L40_VORBIS("WEBM (video: VP9 8-bit L4.0, audio: Vorbis)", "webm", "video/webm", "vp9.00.40.08", "vorbis", true), - CODEC_WEBM_VP9_L41_OPUS("WEBM (video: VP9 8-bit L4.1, audio: Opus)", "webm", "video/webm", "vp9.00.41.08", "opus", true), - CODEC_WEBM_VP9_L41_VORBIS("WEBM (video: VP9 8-bit L4.1, audio: Vorbis)", "webm", "video/webm", "vp9.00.41.08", "vorbis", true), - CODEC_WEBM_VP9_L50_OPUS("WEBM (video: VP9 8-bit L5.0, audio: Opus)", "webm", "video/webm", "vp9.00.50.08", "opus", true), - CODEC_WEBM_VP9_L50_VORBIS("WEBM (video: VP9 8-bit L5.0, audio: Vorbis)", "webm", "video/webm", "vp9.00.50.08", "vorbis", true), - CODEC_WEBM_VP9_L51_OPUS("WEBM (video: VP9 8-bit L5.1, audio: Opus)", "webm", "video/webm", "vp9.00.51.08", "opus", true), - CODEC_WEBM_VP9_L51_VORBIS("WEBM (video: VP9 8-bit L5.1, audio: Vorbis)", "webm", "video/webm", "vp9.00.51.08", "vorbis", true), + CODEC_WEBM_VP9_GENERIC_VORBIS("WEBM (video: VP9 Default, audio: Vorbis)", "webm", "video/webm", "vp9", "vorbis", + false), + CODEC_WEBM_VP9_L40_OPUS("WEBM (video: VP9 8-bit L4.0, audio: Opus)", "webm", "video/webm", "vp9.00.40.08", "opus", + true), + CODEC_WEBM_VP9_L40_VORBIS("WEBM (video: VP9 8-bit L4.0, audio: Vorbis)", "webm", "video/webm", "vp9.00.40.08", + "vorbis", true), + CODEC_WEBM_VP9_L41_OPUS("WEBM (video: VP9 8-bit L4.1, audio: Opus)", "webm", "video/webm", "vp9.00.41.08", "opus", + true), + CODEC_WEBM_VP9_L41_VORBIS("WEBM (video: VP9 8-bit L4.1, audio: Vorbis)", "webm", "video/webm", "vp9.00.41.08", + "vorbis", true), + CODEC_WEBM_VP9_L50_OPUS("WEBM (video: VP9 8-bit L5.0, audio: Opus)", "webm", "video/webm", "vp9.00.50.08", "opus", + true), + CODEC_WEBM_VP9_L50_VORBIS("WEBM (video: VP9 8-bit L5.0, audio: Vorbis)", "webm", "video/webm", "vp9.00.50.08", + "vorbis", true), + CODEC_WEBM_VP9_L51_OPUS("WEBM (video: VP9 8-bit L5.1, audio: Opus)", "webm", "video/webm", "vp9.00.51.08", "opus", + true), + CODEC_WEBM_VP9_L51_VORBIS("WEBM (video: VP9 8-bit L5.1, audio: Vorbis)", "webm", "video/webm", "vp9.00.51.08", + "vorbis", true), CODEC_WEBM_VP8_GENERIC_OPUS("WEBM (video: VP8 Default, audio: Opus)", "webm", "video/webm", "vp8", "opus", false), - CODEC_WEBM_VP8_GENERIC_VORBIS("WEBM (video: VP8 Default, audio: Vorbis)", "webm", "video/webm", "vp8", "vorbis", false), + CODEC_WEBM_VP8_GENERIC_VORBIS("WEBM (video: VP8 Default, audio: Vorbis)", "webm", "video/webm", "vp8", "vorbis", + false), CODEC_WEBM_GENERIC("WEBM (Default Codecs)", "webm", "video/webm", null, null, false); public static final EnumScreenRecordingCodec[] preferred_codec_order = new EnumScreenRecordingCodec[] { - CODEC_MP4_H264_GENERIC_AAC, - CODEC_MP4_H264_L52_AAC, - CODEC_MP4_H264_L50_AAC, - CODEC_MP4_H264_L42_AAC, - CODEC_MP4_H264_L40_AAC, - CODEC_MP4_H264_GENERIC_OPUS, - CODEC_MP4_H264_L40_OPUS, - CODEC_MP4_H264_L42_OPUS, - CODEC_MP4_H264_L50_OPUS, - CODEC_MP4_H264_L52_OPUS, - CODEC_WEBM_H264_GENERIC_OPUS, - CODEC_WEBM_H264_L52_OPUS, - CODEC_WEBM_H264_L50_OPUS, - CODEC_WEBM_H264_L42_OPUS, - CODEC_WEBM_H264_L40_OPUS, - CODEC_WEBM_H264_GENERIC_VORBIS, - CODEC_WEBM_H264_L52_VORBIS, - CODEC_WEBM_H264_L50_VORBIS, - CODEC_WEBM_H264_L42_VORBIS, - CODEC_WEBM_H264_L40_VORBIS, - CODEC_MP4_VP9_GENERIC_AAC, - CODEC_MP4_VP9_L51_AAC, - CODEC_MP4_VP9_L50_AAC, - CODEC_MP4_VP9_L41_AAC, - CODEC_MP4_VP9_L40_AAC, - CODEC_MP4_VP9_GENERIC_OPUS, - CODEC_MP4_VP9_L51_OPUS, - CODEC_MP4_VP9_L50_OPUS, - CODEC_MP4_VP9_L41_OPUS, - CODEC_MP4_VP9_L40_OPUS, - CODEC_WEBM_VP9_GENERIC_OPUS, - CODEC_WEBM_VP9_L51_OPUS, - CODEC_WEBM_VP9_L50_OPUS, - CODEC_WEBM_VP9_L41_OPUS, - CODEC_WEBM_VP9_L40_OPUS, - CODEC_WEBM_VP9_GENERIC_VORBIS, - CODEC_WEBM_VP9_L51_VORBIS, - CODEC_WEBM_VP9_L50_VORBIS, - CODEC_WEBM_VP9_L41_VORBIS, - CODEC_WEBM_VP9_L40_VORBIS, - CODEC_WEBM_VP8_GENERIC_OPUS, - CODEC_WEBM_VP8_GENERIC_VORBIS, - CODEC_MP4_GENERIC, - CODEC_WEBM_GENERIC - }; + CODEC_MP4_H264_GENERIC_AAC, CODEC_MP4_H264_L52_AAC, CODEC_MP4_H264_L50_AAC, CODEC_MP4_H264_L42_AAC, + CODEC_MP4_H264_L40_AAC, CODEC_MP4_H264_GENERIC_OPUS, CODEC_MP4_H264_L40_OPUS, CODEC_MP4_H264_L42_OPUS, + CODEC_MP4_H264_L50_OPUS, CODEC_MP4_H264_L52_OPUS, CODEC_WEBM_H264_GENERIC_OPUS, CODEC_WEBM_H264_L52_OPUS, + CODEC_WEBM_H264_L50_OPUS, CODEC_WEBM_H264_L42_OPUS, CODEC_WEBM_H264_L40_OPUS, + CODEC_WEBM_H264_GENERIC_VORBIS, CODEC_WEBM_H264_L52_VORBIS, CODEC_WEBM_H264_L50_VORBIS, + CODEC_WEBM_H264_L42_VORBIS, CODEC_WEBM_H264_L40_VORBIS, CODEC_MP4_VP9_GENERIC_AAC, CODEC_MP4_VP9_L51_AAC, + CODEC_MP4_VP9_L50_AAC, CODEC_MP4_VP9_L41_AAC, CODEC_MP4_VP9_L40_AAC, CODEC_MP4_VP9_GENERIC_OPUS, + CODEC_MP4_VP9_L51_OPUS, CODEC_MP4_VP9_L50_OPUS, CODEC_MP4_VP9_L41_OPUS, CODEC_MP4_VP9_L40_OPUS, + CODEC_WEBM_VP9_GENERIC_OPUS, CODEC_WEBM_VP9_L51_OPUS, CODEC_WEBM_VP9_L50_OPUS, CODEC_WEBM_VP9_L41_OPUS, + CODEC_WEBM_VP9_L40_OPUS, CODEC_WEBM_VP9_GENERIC_VORBIS, CODEC_WEBM_VP9_L51_VORBIS, + CODEC_WEBM_VP9_L50_VORBIS, CODEC_WEBM_VP9_L41_VORBIS, CODEC_WEBM_VP9_L40_VORBIS, + CODEC_WEBM_VP8_GENERIC_OPUS, CODEC_WEBM_VP8_GENERIC_VORBIS, CODEC_MP4_GENERIC, CODEC_WEBM_GENERIC }; public final String name; public final String fileExt; @@ -122,29 +127,30 @@ public enum EnumScreenRecordingCodec { public final String audioCodec; public final boolean advanced; public final String mimeType; - - private EnumScreenRecordingCodec(String name, String fileExt, String container, String videoCodec, String audioCodec, boolean advanced) { + + private EnumScreenRecordingCodec(String name, String fileExt, String container, String videoCodec, + String audioCodec, boolean advanced) { this.name = name; this.fileExt = fileExt; this.container = container; this.videoCodec = videoCodec; this.audioCodec = audioCodec; this.advanced = advanced; - if(videoCodec != null || audioCodec != null) { + if (videoCodec != null || audioCodec != null) { StringBuilder mimeBuilder = new StringBuilder(container); mimeBuilder.append(";codecs=\""); - if(videoCodec != null) { + if (videoCodec != null) { mimeBuilder.append(videoCodec); - if(audioCodec != null) { + if (audioCodec != null) { mimeBuilder.append(','); } } - if(audioCodec != null) { + if (audioCodec != null) { mimeBuilder.append(audioCodec); } mimeBuilder.append("\""); this.mimeType = mimeBuilder.toString(); - }else { + } else { this.mimeType = container; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingNote.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingNote.java index 1dc251a5..d3cd5bb1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingNote.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingNote.java @@ -7,46 +7,50 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenRecordingNote extends GuiScreen { - private GuiScreen cont; - public static boolean hasShown = false; + private GuiScreen cont; + public GuiScreenRecordingNote(GuiScreen cont) { this.cont = cont; } + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + hasShown = true; + this.mc.displayGuiScreen(cont); + } + } + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, I18n.format("options.recordingNote.title"), this.width / 2, 70, + 11184810); + this.drawCenteredString(fontRendererObj, I18n.format("options.recordingNote.text0"), this.width / 2, 90, + 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("options.recordingNote.text1"), this.width / 2, 102, + 16777215); + super.drawScreen(par1, par2, par3); + } + public void initGui() { this.buttonList.clear(); this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 108, I18n.format("gui.done"))); } - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, I18n.format("options.recordingNote.title"), this.width / 2, 70, 11184810); - this.drawCenteredString(fontRendererObj, I18n.format("options.recordingNote.text0"), this.width / 2, 90, 16777215); - this.drawCenteredString(fontRendererObj, I18n.format("options.recordingNote.text1"), this.width / 2, 102, 16777215); - super.drawScreen(par1, par2, par3); - } - - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - hasShown = true; - this.mc.displayGuiScreen(cont); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingSettings.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingSettings.java index 096a2de0..48d2be3a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingSettings.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenRecordingSettings.java @@ -15,14 +15,15 @@ import net.minecraft.util.MathHelper; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -47,113 +48,29 @@ public class GuiScreenRecordingSettings extends GuiScreen { this.parent = parent; } - public void initGui() { - buttonList.clear(); - buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 168, I18n.format("gui.done"))); - buttonList.add(codecButton = new GuiButton(1, this.width / 2 + 65, this.height / 6 - 2, 75, 20, I18n.format("options.screenRecording.codecButton"))); - boolean isRecording = ScreenRecordingController.isRecording(); - buttonList.add(recordButton = new GuiButton(2, this.width / 2 + 15, this.height / 6 + 28, 125, 20, - I18n.format(isRecording ? "options.screenRecording.stop" : "options.screenRecording.start"))); - buttonList.add(videoResolutionSlider = new GuiSlider2(3, this.width / 2 - 155, this.height / 6 + 64, 150, 20, (mc.gameSettings.screenRecordResolution - 1) / 3.999f, 1.0f) { - @Override - protected String updateDisplayString() { - int i = (int)(sliderValue * 3.999f); - return I18n.format("options.screenRecording.videoResolution") + ": x" + HString.format("%.2f", 1.0f / (int)Math.pow(2.0, i)); - } - @Override - protected void onChange() { - mc.gameSettings.screenRecordResolution = 1 + (int)(sliderValue * 3.999f); - dirty = true; - } - }); - buttonList.add(videoFrameRateSlider = new GuiSlider2(4, this.width / 2 + 5, this.height / 6 + 64, 150, 20, (Math.max(mc.gameSettings.screenRecordFPS, 9) - 9) / 51.999f, 1.0f) { - @Override - protected String updateDisplayString() { - int i = (int)(sliderValue * 51.999f); - return I18n.format("options.screenRecording.videoFPS") + ": " + (i <= 0 ? I18n.format("options.screenRecording.onVSync") : 9 + i); - } - @Override - protected void onChange() { - int i = (int)(sliderValue * 51.999f); - mc.gameSettings.screenRecordFPS = i <= 0 ? -1 : 9 + i; - dirty = true; - } - }); - buttonList.add(videoBitrateSlider = new GuiSlider2(5, this.width / 2 - 155, this.height / 6 + 98, 150, 20, MathHelper.sqrt_float(MathHelper.clamp_float((mc.gameSettings.screenRecordVideoBitrate - 250) / 19750.999f, 0.0f, 1.0f)), 1.0f) { - @Override - protected String updateDisplayString() { - return I18n.format("options.screenRecording.videoBitrate") + ": " + (250 + (int)(sliderValue * sliderValue * 19750.999f)) + "kbps"; - } - @Override - protected void onChange() { - mc.gameSettings.screenRecordVideoBitrate = 250 + (int)(sliderValue * sliderValue * 19750.999f); - dirty = true; - } - }); - buttonList.add(audioBitrateSlider = new GuiSlider2(6, this.width / 2 + 5, this.height / 6 + 98, 150, 20, MathHelper.sqrt_float(MathHelper.clamp_float((mc.gameSettings.screenRecordAudioBitrate - 24) / 232.999f, 0.0f, 1.0f)), 1.0f) { - @Override - protected String updateDisplayString() { - return I18n.format("options.screenRecording.audioBitrate") + ": " + (24 + (int)(sliderValue * sliderValue * 232.999f)) + "kbps"; - } - @Override - protected void onChange() { - mc.gameSettings.screenRecordAudioBitrate = 24 + (int)(sliderValue * sliderValue * 232.999f); - dirty = true; - } - }); - buttonList.add(gameVolumeSlider = new GuiSlider2(7, this.width / 2 - 155, this.height / 6 + 130, 150, 20, mc.gameSettings.screenRecordGameVolume, 1.0f) { - @Override - protected String updateDisplayString() { - return I18n.format("options.screenRecording.gameVolume") + ": " + (int)(sliderValue * 100.999f) + "%"; - } - @Override - protected void onChange() { - mc.gameSettings.screenRecordGameVolume = sliderValue; - ScreenRecordingController.setGameVolume(sliderValue); - dirty = true; - } - }); - buttonList.add(microphoneVolumeSlider = new GuiSlider2(8, this.width / 2 + 5, this.height / 6 + 130, 150, 20, mc.gameSettings.screenRecordMicVolume, 1.0f) { - @Override - protected String updateDisplayString() { - return I18n.format("options.screenRecording.microphoneVolume") + ": " + (int)(sliderValue * 100.999f) + "%"; - } - @Override - protected void onChange() { - mc.gameSettings.screenRecordMicVolume = sliderValue; - ScreenRecordingController.setMicrophoneVolume(sliderValue); - dirty = true; - } - }); - codecButton.enabled = !isRecording; - videoResolutionSlider.enabled = !isRecording; - videoFrameRateSlider.enabled = !isRecording; - audioBitrateSlider.enabled = !isRecording; - videoBitrateSlider.enabled = !isRecording; - microphoneVolumeSlider.enabled = !ScreenRecordingController.isMicVolumeLocked(); - } - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 0) { - if(dirty) { + if (parGuiButton.id == 0) { + if (dirty) { mc.gameSettings.saveOptions(); dirty = false; } mc.displayGuiScreen(parent); - }else if(parGuiButton.id == 1) { + } else if (parGuiButton.id == 1) { mc.displayGuiScreen(new GuiScreenSelectCodec(this, mc.gameSettings.screenRecordCodec)); - }else if(parGuiButton.id == 2) { - if(!ScreenRecordingController.isRecording()) { + } else if (parGuiButton.id == 2) { + if (!ScreenRecordingController.isRecording()) { try { - ScreenRecordingController.startRecording(new ScreenRecordParameters(mc.gameSettings.screenRecordCodec, - mc.gameSettings.screenRecordResolution, mc.gameSettings.screenRecordVideoBitrate, - mc.gameSettings.screenRecordAudioBitrate, mc.gameSettings.screenRecordFPS)); - }catch(Throwable t) { + ScreenRecordingController + .startRecording(new ScreenRecordParameters(mc.gameSettings.screenRecordCodec, + mc.gameSettings.screenRecordResolution, mc.gameSettings.screenRecordVideoBitrate, + mc.gameSettings.screenRecordAudioBitrate, mc.gameSettings.screenRecordFPS)); + } catch (Throwable t) { logger.error("Failed to begin screen recording!"); logger.error(t); - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("options.screenRecording.failed", t.toString(), parent)); + mc.displayGuiScreen( + new GuiScreenGenericErrorMessage("options.screenRecording.failed", t.toString(), parent)); } - }else { + } else { ScreenRecordingController.endRecording(); } } @@ -162,14 +79,14 @@ public class GuiScreenRecordingSettings extends GuiScreen { public void drawScreen(int i, int j, float var3) { drawDefaultBackground(); drawCenteredString(fontRendererObj, I18n.format("options.screenRecording.title"), this.width / 2, 15, 16777215); - if(mc.gameSettings.screenRecordCodec == null) { + if (mc.gameSettings.screenRecordCodec == null) { mc.gameSettings.screenRecordCodec = ScreenRecordingController.getDefaultCodec(); } - + String codecString = mc.gameSettings.screenRecordCodec.name; int codecStringWidth = fontRendererObj.getStringWidth(codecString); drawString(fontRendererObj, codecString, this.width / 2 + 60 - codecStringWidth, this.height / 6 + 4, 0xFFFFFF); - + boolean isRecording = ScreenRecordingController.isRecording(); codecButton.enabled = !isRecording; videoResolutionSlider.enabled = !isRecording; @@ -177,25 +94,136 @@ public class GuiScreenRecordingSettings extends GuiScreen { audioBitrateSlider.enabled = !isRecording; videoBitrateSlider.enabled = !isRecording; microphoneVolumeSlider.enabled = !ScreenRecordingController.isMicVolumeLocked(); - recordButton.displayString = I18n.format(isRecording ? "options.screenRecording.stop" : "options.screenRecording.start"); + recordButton.displayString = I18n + .format(isRecording ? "options.screenRecording.stop" : "options.screenRecording.start"); String statusString = I18n.format("options.screenRecording.status", - (isRecording ? EnumChatFormatting.GREEN : EnumChatFormatting.RED) + I18n.format(isRecording ? "options.screenRecording.status.1" : "options.screenRecording.status.0")); + (isRecording ? EnumChatFormatting.GREEN : EnumChatFormatting.RED) + I18n + .format(isRecording ? "options.screenRecording.status.1" : "options.screenRecording.status.0")); int statusStringWidth = fontRendererObj.getStringWidth(statusString); - drawString(fontRendererObj, statusString, this.width / 2 + 10 - statusStringWidth, this.height / 6 + 34, 0xFFFFFF); - + drawString(fontRendererObj, statusString, this.width / 2 + 10 - statusStringWidth, this.height / 6 + 34, + 0xFFFFFF); + super.drawScreen(i, j, var3); } protected void handleCodecCallback(EnumScreenRecordingCodec codec) { EnumScreenRecordingCodec oldCodec = mc.gameSettings.screenRecordCodec; - if(ScreenRecordingController.codecs.contains(codec)) { + if (ScreenRecordingController.codecs.contains(codec)) { mc.gameSettings.screenRecordCodec = codec; - }else { + } else { mc.gameSettings.screenRecordCodec = ScreenRecordingController.getDefaultCodec(); } - if(oldCodec != mc.gameSettings.screenRecordCodec) { + if (oldCodec != mc.gameSettings.screenRecordCodec) { dirty = true; } } + public void initGui() { + buttonList.clear(); + buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 168, I18n.format("gui.done"))); + buttonList.add(codecButton = new GuiButton(1, this.width / 2 + 65, this.height / 6 - 2, 75, 20, + I18n.format("options.screenRecording.codecButton"))); + boolean isRecording = ScreenRecordingController.isRecording(); + buttonList.add(recordButton = new GuiButton(2, this.width / 2 + 15, this.height / 6 + 28, 125, 20, + I18n.format(isRecording ? "options.screenRecording.stop" : "options.screenRecording.start"))); + buttonList.add(videoResolutionSlider = new GuiSlider2(3, this.width / 2 - 155, this.height / 6 + 64, 150, 20, + (mc.gameSettings.screenRecordResolution - 1) / 3.999f, 1.0f) { + @Override + protected void onChange() { + mc.gameSettings.screenRecordResolution = 1 + (int) (sliderValue * 3.999f); + dirty = true; + } + + @Override + protected String updateDisplayString() { + int i = (int) (sliderValue * 3.999f); + return I18n.format("options.screenRecording.videoResolution") + ": x" + + HString.format("%.2f", 1.0f / (int) Math.pow(2.0, i)); + } + }); + buttonList.add(videoFrameRateSlider = new GuiSlider2(4, this.width / 2 + 5, this.height / 6 + 64, 150, 20, + (Math.max(mc.gameSettings.screenRecordFPS, 9) - 9) / 51.999f, 1.0f) { + @Override + protected void onChange() { + int i = (int) (sliderValue * 51.999f); + mc.gameSettings.screenRecordFPS = i <= 0 ? -1 : 9 + i; + dirty = true; + } + + @Override + protected String updateDisplayString() { + int i = (int) (sliderValue * 51.999f); + return I18n.format("options.screenRecording.videoFPS") + ": " + + (i <= 0 ? I18n.format("options.screenRecording.onVSync") : 9 + i); + } + }); + buttonList.add(videoBitrateSlider = new GuiSlider2(5, this.width / 2 - 155, this.height / 6 + 98, 150, 20, + MathHelper.sqrt_float(MathHelper + .clamp_float((mc.gameSettings.screenRecordVideoBitrate - 250) / 19750.999f, 0.0f, 1.0f)), + 1.0f) { + @Override + protected void onChange() { + mc.gameSettings.screenRecordVideoBitrate = 250 + (int) (sliderValue * sliderValue * 19750.999f); + dirty = true; + } + + @Override + protected String updateDisplayString() { + return I18n.format("options.screenRecording.videoBitrate") + ": " + + (250 + (int) (sliderValue * sliderValue * 19750.999f)) + "kbps"; + } + }); + buttonList.add(audioBitrateSlider = new GuiSlider2(6, this.width / 2 + 5, this.height / 6 + 98, 150, 20, + MathHelper.sqrt_float( + MathHelper.clamp_float((mc.gameSettings.screenRecordAudioBitrate - 24) / 232.999f, 0.0f, 1.0f)), + 1.0f) { + @Override + protected void onChange() { + mc.gameSettings.screenRecordAudioBitrate = 24 + (int) (sliderValue * sliderValue * 232.999f); + dirty = true; + } + + @Override + protected String updateDisplayString() { + return I18n.format("options.screenRecording.audioBitrate") + ": " + + (24 + (int) (sliderValue * sliderValue * 232.999f)) + "kbps"; + } + }); + buttonList.add(gameVolumeSlider = new GuiSlider2(7, this.width / 2 - 155, this.height / 6 + 130, 150, 20, + mc.gameSettings.screenRecordGameVolume, 1.0f) { + @Override + protected void onChange() { + mc.gameSettings.screenRecordGameVolume = sliderValue; + ScreenRecordingController.setGameVolume(sliderValue); + dirty = true; + } + + @Override + protected String updateDisplayString() { + return I18n.format("options.screenRecording.gameVolume") + ": " + (int) (sliderValue * 100.999f) + "%"; + } + }); + buttonList.add(microphoneVolumeSlider = new GuiSlider2(8, this.width / 2 + 5, this.height / 6 + 130, 150, 20, + mc.gameSettings.screenRecordMicVolume, 1.0f) { + @Override + protected void onChange() { + mc.gameSettings.screenRecordMicVolume = sliderValue; + ScreenRecordingController.setMicrophoneVolume(sliderValue); + dirty = true; + } + + @Override + protected String updateDisplayString() { + return I18n.format("options.screenRecording.microphoneVolume") + ": " + (int) (sliderValue * 100.999f) + + "%"; + } + }); + codecButton.enabled = !isRecording; + videoResolutionSlider.enabled = !isRecording; + videoFrameRateSlider.enabled = !isRecording; + audioBitrateSlider.enabled = !isRecording; + videoBitrateSlider.enabled = !isRecording; + microphoneVolumeSlider.enabled = !ScreenRecordingController.isMicVolumeLocked(); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenSelectCodec.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenSelectCodec.java index 3b6cfaa8..34d17882 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenSelectCodec.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiScreenSelectCodec.java @@ -11,26 +11,32 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenSelectCodec extends GuiScreen { + static Minecraft getMC(GuiScreenSelectCodec screen) { + return screen.mc; + } + protected final GuiScreenRecordingSettings parent; protected List codecs; protected int selectedCodec; protected GuiSlotSelectCodec slots; protected GuiButton showAllButton; protected boolean showAll; + protected EnumScreenRecordingCodec codec; public GuiScreenSelectCodec(GuiScreenRecordingSettings parent, EnumScreenRecordingCodec codec) { @@ -38,23 +44,13 @@ public class GuiScreenSelectCodec extends GuiScreen { this.codec = codec; } - public void initGui() { - showAll = codec.advanced; - codecs = showAll ? ScreenRecordingController.advancedCodecsOrdered : ScreenRecordingController.simpleCodecsOrdered; - selectedCodec = codecs.indexOf(codec); - buttonList.clear(); - buttonList.add(showAllButton = new GuiButton(0, this.width / 2 - 154, this.height - 38, 150, 20, - I18n.format("options.recordingCodec.showAdvancedCodecs", I18n.format(showAll ? "gui.yes" : "gui.no")))); - buttonList.add(new GuiButton(1, this.width / 2 + 4, this.height - 38, 150, 20, I18n.format("gui.done"))); - slots = new GuiSlotSelectCodec(this, 32, height - 45); - } - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 0) { + if (parGuiButton.id == 0) { changeStateShowAll(!showAll); - showAllButton.displayString = I18n.format("options.recordingCodec.showAdvancedCodecs", I18n.format(showAll ? "gui.yes" : "gui.no")); - }else if(parGuiButton.id == 1) { - if(selectedCodec >= 0 && selectedCodec < codecs.size()) { + showAllButton.displayString = I18n.format("options.recordingCodec.showAdvancedCodecs", + I18n.format(showAll ? "gui.yes" : "gui.no")); + } else if (parGuiButton.id == 1) { + if (selectedCodec >= 0 && selectedCodec < codecs.size()) { parent.handleCodecCallback(codecs.get(selectedCodec)); } mc.displayGuiScreen(parent); @@ -62,16 +58,20 @@ public class GuiScreenSelectCodec extends GuiScreen { } protected void changeStateShowAll(boolean newShowAll) { - if(newShowAll == showAll) return; - EnumScreenRecordingCodec oldCodec = codecs.get(selectedCodec >= 0 && selectedCodec < codecs.size() ? selectedCodec : 0); - codecs = newShowAll ? ScreenRecordingController.advancedCodecsOrdered : ScreenRecordingController.simpleCodecsOrdered; + if (newShowAll == showAll) + return; + EnumScreenRecordingCodec oldCodec = codecs + .get(selectedCodec >= 0 && selectedCodec < codecs.size() ? selectedCodec : 0); + codecs = newShowAll ? ScreenRecordingController.advancedCodecsOrdered + : ScreenRecordingController.simpleCodecsOrdered; showAll = newShowAll; selectedCodec = codecs.indexOf(oldCodec); } public void drawScreen(int i, int j, float var3) { slots.drawScreen(i, j, var3); - this.drawCenteredString(this.fontRendererObj, I18n.format("options.recordingCodec.title"), this.width / 2, 16, 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("options.recordingCodec.title"), this.width / 2, 16, + 16777215); super.drawScreen(i, j, var3); } @@ -85,8 +85,16 @@ public class GuiScreenSelectCodec extends GuiScreen { slots.handleTouchInput(); } - static Minecraft getMC(GuiScreenSelectCodec screen) { - return screen.mc; + public void initGui() { + showAll = codec.advanced; + codecs = showAll ? ScreenRecordingController.advancedCodecsOrdered + : ScreenRecordingController.simpleCodecsOrdered; + selectedCodec = codecs.indexOf(codec); + buttonList.clear(); + buttonList.add(showAllButton = new GuiButton(0, this.width / 2 - 154, this.height - 38, 150, 20, + I18n.format("options.recordingCodec.showAdvancedCodecs", I18n.format(showAll ? "gui.yes" : "gui.no")))); + buttonList.add(new GuiButton(1, this.width / 2 + 4, this.height - 38, 150, 20, I18n.format("gui.done"))); + slots = new GuiSlotSelectCodec(this, 32, height - 45); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiSlotSelectCodec.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiSlotSelectCodec.java index 4521968d..3e411cc6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiSlotSelectCodec.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/GuiSlotSelectCodec.java @@ -5,14 +5,15 @@ import net.minecraft.client.gui.GuiSlot; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,32 +28,32 @@ public class GuiSlotSelectCodec extends GuiSlot { } @Override - protected int getSize() { - return screen.codecs.size(); + protected void drawBackground() { + screen.drawDefaultBackground(); + } + + @Override + protected void drawSlot(int id, int xx, int yy, int width, int height, int ii) { + if (id < screen.codecs.size()) { + this.screen.drawString(mc.fontRendererObj, screen.codecs.get(id).name, xx + 4, yy + 3, 0xFFFFFF); + } } @Override protected void elementClicked(int var1, boolean var2, int var3, int var4) { - if(var1 < screen.codecs.size()) { + if (var1 < screen.codecs.size()) { screen.selectedCodec = var1; } } + @Override + protected int getSize() { + return screen.codecs.size(); + } + @Override protected boolean isSelected(int var1) { return screen.selectedCodec == var1; } - @Override - protected void drawBackground() { - screen.drawDefaultBackground(); - } - - @Override - protected void drawSlot(int id, int xx, int yy, int width, int height, int ii) { - if(id < screen.codecs.size()) { - this.screen.drawString(mc.fontRendererObj, screen.codecs.get(id).name, xx + 4, yy + 3, 0xFFFFFF); - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/ScreenRecordingController.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/ScreenRecordingController.java index 869b7dea..3a00b059 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/ScreenRecordingController.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/recording/ScreenRecordingController.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.internal.ScreenRecordParameters; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,17 +38,26 @@ public class ScreenRecordingController { public static final Set codecs = new HashSet<>(); private static boolean supported = false; + public static void endRecording() { + PlatformScreenRecord.endRecording(); + } + + public static EnumScreenRecordingCodec getDefaultCodec() { + return simpleCodecsOrdered.isEmpty() ? (advancedCodecsOrdered.isEmpty() ? null : advancedCodecsOrdered.get(0)) + : simpleCodecsOrdered.get(0); + } + public static void initialize() { simpleCodecsOrdered.clear(); advancedCodecsOrdered.clear(); codecs.clear(); supported = PlatformScreenRecord.isSupported(); - if(supported) { + if (supported) { EnumScreenRecordingCodec[] codecsOrdered = EnumScreenRecordingCodec.preferred_codec_order; - for(int i = 0; i < codecsOrdered.length; ++i) { + for (int i = 0; i < codecsOrdered.length; ++i) { EnumScreenRecordingCodec codec = codecsOrdered[i]; - if(PlatformScreenRecord.isCodecSupported(codec)) { - if(!codec.advanced) { + if (PlatformScreenRecord.isCodecSupported(codec)) { + if (!codec.advanced) { simpleCodecsOrdered.add(codec); } advancedCodecsOrdered.add(codec); @@ -55,15 +65,27 @@ public class ScreenRecordingController { } } } - if(codecs.isEmpty()) { + if (codecs.isEmpty()) { supported = false; } } + public static boolean isMicVolumeLocked() { + return PlatformScreenRecord.isMicVolumeLocked(); + } + + public static boolean isRecording() { + return PlatformScreenRecord.isRecording(); + } + public static boolean isSupported() { return supported; } + public static boolean isVSyncLocked() { + return PlatformScreenRecord.isVSyncLocked(); + } + public static void setGameVolume(float volume) { PlatformScreenRecord.setGameVolume(volume); } @@ -76,24 +98,4 @@ public class ScreenRecordingController { PlatformScreenRecord.startRecording(params); } - public static void endRecording() { - PlatformScreenRecord.endRecording(); - } - - public static boolean isRecording() { - return PlatformScreenRecord.isRecording(); - } - - public static boolean isMicVolumeLocked() { - return PlatformScreenRecord.isMicVolumeLocked(); - } - - public static boolean isVSyncLocked() { - return PlatformScreenRecord.isVSyncLocked(); - } - - public static EnumScreenRecordingCodec getDefaultCodec() { - return simpleCodecsOrdered.isEmpty() ? (advancedCodecsOrdered.isEmpty() ? null : advancedCodecsOrdered.get(0)) : simpleCodecsOrdered.get(0); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/AddressResolver.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/AddressResolver.java index de5b34de..fd29b09a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/AddressResolver.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/AddressResolver.java @@ -7,57 +7,58 @@ import net.minecraft.client.multiplayer.ServerData; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class AddressResolver { + public static ServerAddress resolveAddressFromURI(String input) { + String uri = resolveURI(input); + String lc = input.toLowerCase(); + if (lc.startsWith("ws://")) { + input = input.substring(5); + } else if (lc.startsWith("wss://")) { + input = input.substring(6); + } + int port = EagRuntime.requireSSL() ? 443 : 80; + int i = input.indexOf('/'); + if (i != -1) { + input = input.substring(0, i); + } + i = input.lastIndexOf(':'); + if (i != -1) { + try { + port = Integer.parseInt(input.substring(i + 1)); + } catch (Throwable t) { + } + } + return new ServerAddress(uri, port); + } + public static String resolveURI(ServerData input) { return resolveURI(input.serverIP); } - + public static String resolveURI(String input) { String lc = input.toLowerCase(); - if(!lc.startsWith("ws://") && !lc.startsWith("wss://")) { - if(EagRuntime.requireSSL()) { + if (!lc.startsWith("ws://") && !lc.startsWith("wss://")) { + if (EagRuntime.requireSSL()) { input = "wss://" + input; - }else { + } else { input = "ws://" + input; } } return input; } - public static ServerAddress resolveAddressFromURI(String input) { - String uri = resolveURI(input); - String lc = input.toLowerCase(); - if(lc.startsWith("ws://")) { - input = input.substring(5); - }else if(lc.startsWith("wss://")) { - input = input.substring(6); - } - int port = EagRuntime.requireSSL() ? 443: 80; - int i = input.indexOf('/'); - if(i != -1) { - input = input.substring(0, i); - } - i = input.lastIndexOf(':'); - if(i != -1) { - try { - port = Integer.parseInt(input.substring(i + 1)); - }catch(Throwable t) { - } - } - return new ServerAddress(uri, port); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/CompressionNotSupportedException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/CompressionNotSupportedException.java index 95471d32..06c31986 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/CompressionNotSupportedException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/CompressionNotSupportedException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.socket; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -18,9 +19,9 @@ package net.lax1dude.eaglercraft.v1_8.socket; public class CompressionNotSupportedException extends UnsupportedOperationException { public CompressionNotSupportedException() { - super("Compression is not supported by Eaglercraft, set " + - "'network-compression-threshold=-1' in server.properties to " + - "allow Eaglercraft connections to this server"); + super("Compression is not supported by Eaglercraft, set " + + "'network-compression-threshold=-1' in server.properties to " + + "allow Eaglercraft connections to this server"); } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ConnectionHandshake.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ConnectionHandshake.java index d1ca8978..f1b1ed24 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ConnectionHandshake.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ConnectionHandshake.java @@ -36,14 +36,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,27 +56,17 @@ public class ConnectionHandshake { private static final int protocolV2 = 2; private static final int protocolV3 = 3; private static final int protocolV4 = 4; - + private static final Logger logger = LogManager.getLogger(); public static String pluginVersion = null; public static String pluginBrand = null; public static int protocolVersion = -1; - - public static byte[] getSPHandshakeProtocolData() { - try { - EaglerOutputStream bao = new EaglerOutputStream(); - DataOutputStream d = new DataOutputStream(bao); - d.writeShort(3); // supported eagler protocols count - d.writeShort(protocolV2); // client supports v2 - d.writeShort(protocolV3); // client supports v3 - d.writeShort(protocolV4); // client supports v4 - return bao.toByteArray(); - }catch(IOException ex) { - throw new RuntimeException(ex); - } - } - + + private static final byte[] HEX = new byte[] { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', + (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', + (byte) 'e', (byte) 'f' }; + public static boolean attemptHandshake(Minecraft mc, IWebSocketClient client, GuiConnecting connecting, GuiScreen ret, String password, boolean allowPlaintext, boolean enableCookies, byte[] cookieData) { try { @@ -86,273 +77,281 @@ public class ConnectionHandshake { protocolVersion = -1; EaglerOutputStream bao = new EaglerOutputStream(); DataOutputStream d = new DataOutputStream(bao); - + d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_VERSION); - + d.writeByte(2); // legacy protocol version - + d.write(getSPHandshakeProtocolData()); // write supported eagler protocol versions d.writeShort(1); // supported game protocols count d.writeShort(47); // client supports 1.8 protocol - + String clientBrand = EaglercraftVersion.projectForkName; d.writeByte(clientBrand.length()); d.writeBytes(clientBrand); - + String clientVers = EaglercraftVersion.projectOriginVersion; d.writeByte(clientVers.length()); d.writeBytes(clientVers); - + d.writeBoolean(password != null); - + String username = mc.getSession().getProfile().getName(); d.writeByte(username.length()); d.writeBytes(username); - + client.send(bao.toByteArray()); - + byte[] read = awaitNextPacket(client, baseTimeout); - if(read == null) { + if (read == null) { logger.error("Read timed out while waiting for server protocol response!"); return false; } - + DataInputStream di = new DataInputStream(new EaglerInputStream(read)); - + int type = di.read(); - if(type == HandshakePacketTypes.PROTOCOL_VERSION_MISMATCH) { - + if (type == HandshakePacketTypes.PROTOCOL_VERSION_MISMATCH) { + StringBuilder protocols = new StringBuilder(); int c = di.readShort(); - for(int i = 0; i < c; ++i) { - if(i > 0) { + for (int i = 0; i < c; ++i) { + if (i > 0) { protocols.append(", "); } protocols.append("v").append(di.readShort()); } - + StringBuilder games = new StringBuilder(); c = di.readShort(); - for(int i = 0; i < c; ++i) { - if(i > 0) { + for (int i = 0; i < c; ++i) { + if (i > 0) { games.append(", "); } games.append("mc").append(di.readShort()); } - + logger.info("Incompatible client: v2/v3/v4 & mc47"); logger.info("Server supports: {}", protocols); logger.info("Server supports: {}", games); - + int msgLen = di.read(); byte[] dat = new byte[msgLen]; di.read(dat); String msg = new String(dat, StandardCharsets.UTF_8); - + mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", new ChatComponentText(msg))); - + return false; - }else if(type == HandshakePacketTypes.PROTOCOL_SERVER_VERSION) { + } else if (type == HandshakePacketTypes.PROTOCOL_SERVER_VERSION) { protocolVersion = di.readShort(); - - if(protocolVersion != protocolV2 && protocolVersion != protocolV3 && protocolVersion != protocolV4) { + + if (protocolVersion != protocolV2 && protocolVersion != protocolV3 && protocolVersion != protocolV4) { logger.info("Incompatible server version: {}", protocolVersion); - mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", new ChatComponentText(protocolVersion < protocolV2 ? "Outdated Server" : "Outdated Client"))); + mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", new ChatComponentText( + protocolVersion < protocolV2 ? "Outdated Server" : "Outdated Client"))); return false; } - + int gameVers = di.readShort(); - if(gameVers != 47) { + if (gameVers != 47) { logger.info("Incompatible minecraft protocol version: {}", gameVers); - mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", new ChatComponentText("This server does not support 1.8!"))); + mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", + new ChatComponentText("This server does not support 1.8!"))); return false; } - + logger.info("Server protocol: {}", protocolVersion); - + int msgLen = di.read(); byte[] dat = new byte[msgLen]; di.read(dat); pluginBrand = ArrayUtils.asciiString(dat); - + msgLen = di.read(); dat = new byte[msgLen]; di.read(dat); pluginVersion = ArrayUtils.asciiString(dat); - + logger.info("Server version: {}", pluginVersion); logger.info("Server brand: {}", pluginBrand); - + int authType = di.read(); - int saltLength = (int)di.readShort() & 0xFFFF; - + int saltLength = (int) di.readShort() & 0xFFFF; + byte[] salt = new byte[saltLength]; di.read(salt); - + bao.reset(); d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_REQUEST_LOGIN); - + d.writeByte(username.length()); d.writeBytes(username); - + String requestedServer = "default"; d.writeByte(requestedServer.length()); d.writeBytes(requestedServer); - - if(authType != 0 && password != null && password.length() > 0) { - if(authType == HandshakePacketTypes.AUTH_METHOD_PLAINTEXT) { - if(allowPlaintext) { + + if (authType != 0 && password != null && password.length() > 0) { + if (authType == HandshakePacketTypes.AUTH_METHOD_PLAINTEXT) { + if (allowPlaintext) { logger.warn("Server is using insecure plaintext authentication"); d.writeByte(password.length() << 1); d.writeChars(password); - }else { - logger.error("Plaintext authentication was attempted but no user confirmation has been given to proceed"); + } else { + logger.error( + "Plaintext authentication was attempted but no user confirmation has been given to proceed"); mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", - new ChatComponentText(EnumChatFormatting.RED + "Plaintext authentication was attempted but no user confirmation has been given to proceed"))); + new ChatComponentText(EnumChatFormatting.RED + + "Plaintext authentication was attempted but no user confirmation has been given to proceed"))); return false; } - }else if(authType == HandshakePacketTypes.AUTH_METHOD_EAGLER_SHA256) { + } else if (authType == HandshakePacketTypes.AUTH_METHOD_EAGLER_SHA256) { SHA256Digest digest = new SHA256Digest(); - + int passLen = password.length(); - - digest.update((byte)((passLen >>> 8) & 0xFF)); - digest.update((byte)(passLen & 0xFF)); - - for(int i = 0; i < passLen; ++i) { + + digest.update((byte) ((passLen >>> 8) & 0xFF)); + digest.update((byte) (passLen & 0xFF)); + + for (int i = 0; i < passLen; ++i) { char codePoint = password.charAt(i); - digest.update((byte)((codePoint >>> 8) & 0xFF)); - digest.update((byte)(codePoint & 0xFF)); + digest.update((byte) ((codePoint >>> 8) & 0xFF)); + digest.update((byte) (codePoint & 0xFF)); } - + digest.update(HandshakePacketTypes.EAGLER_SHA256_SALT_SAVE, 0, 32); - + byte[] hashed = new byte[32]; digest.doFinal(hashed, 0); - + digest.reset(); - + digest.update(hashed, 0, 32); digest.update(salt, 0, 32); digest.update(HandshakePacketTypes.EAGLER_SHA256_SALT_BASE, 0, 32); - + digest.doFinal(hashed, 0); - + digest.reset(); - + digest.update(hashed, 0, 32); digest.update(salt, 32, 32); digest.update(HandshakePacketTypes.EAGLER_SHA256_SALT_BASE, 0, 32); - + digest.doFinal(hashed, 0); - + d.writeByte(32); d.write(hashed); - }else if(authType == HandshakePacketTypes.AUTH_METHOD_AUTHME_SHA256) { + } else if (authType == HandshakePacketTypes.AUTH_METHOD_AUTHME_SHA256) { SHA256Digest digest = new SHA256Digest(); - + byte[] passwd = password.getBytes(StandardCharsets.UTF_8); digest.update(passwd, 0, passwd.length); - + byte[] hashed = new byte[32]; digest.doFinal(hashed, 0); - + byte[] toHexAndSalt = new byte[64]; - for(int i = 0; i < 32; ++i) { + for (int i = 0; i < 32; ++i) { toHexAndSalt[i << 1] = HEX[(hashed[i] >> 4) & 0xF]; toHexAndSalt[(i << 1) + 1] = HEX[hashed[i] & 0xF]; } - + digest.reset(); digest.update(toHexAndSalt, 0, 64); digest.update(salt, 0, salt.length); - + digest.doFinal(hashed, 0); - - for(int i = 0; i < 32; ++i) { + + for (int i = 0; i < 32; ++i) { toHexAndSalt[i << 1] = HEX[(hashed[i] >> 4) & 0xF]; toHexAndSalt[(i << 1) + 1] = HEX[hashed[i] & 0xF]; } d.writeByte(64); d.write(toHexAndSalt); - }else { + } else { logger.error("Unsupported authentication type: {}", authType); - mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", - new ChatComponentText(EnumChatFormatting.RED + "Unsupported authentication type: " + authType + "\n\n" + EnumChatFormatting.GRAY + "(Use a newer version of the client)"))); + mc.displayGuiScreen( + new GuiDisconnected(ret, "connect.failed", + new ChatComponentText(EnumChatFormatting.RED + + "Unsupported authentication type: " + authType + "\n\n" + + EnumChatFormatting.GRAY + "(Use a newer version of the client)"))); return false; } - }else { + } else { d.writeByte(0); } - if(protocolVersion >= protocolV4) { + if (protocolVersion >= protocolV4) { d.writeBoolean(enableCookies); - if(enableCookies && cookieData != null) { + if (enableCookies && cookieData != null) { d.writeByte(cookieData.length); d.write(cookieData); - }else { + } else { d.writeByte(0); } } - + client.send(bao.toByteArray()); - + read = awaitNextPacket(client, baseTimeout); - if(read == null) { + if (read == null) { logger.error("Read timed out while waiting for login negotiation response!"); return false; } - + di = new DataInputStream(new EaglerInputStream(read)); type = di.read(); - if(type == HandshakePacketTypes.PROTOCOL_SERVER_ALLOW_LOGIN) { + if (type == HandshakePacketTypes.PROTOCOL_SERVER_ALLOW_LOGIN) { msgLen = di.read(); dat = new byte[msgLen]; di.read(dat); - + String serverUsername = ArrayUtils.asciiString(dat); - - Minecraft.getMinecraft().getSession().update(serverUsername, new EaglercraftUUID(di.readLong(), di.readLong())); - - Map profileDataToSend = new HashMap<>(); - - if(protocolVersion >= 4) { + + Minecraft.getMinecraft().getSession().update(serverUsername, + new EaglercraftUUID(di.readLong(), di.readLong())); + + Map profileDataToSend = new HashMap<>(); + + if (protocolVersion >= 4) { bao.reset(); d.writeLong(EaglercraftVersion.clientBrandUUID.msb); d.writeLong(EaglercraftVersion.clientBrandUUID.lsb); profileDataToSend.put("brand_uuid_v1", bao.toByteArray()); } - + byte[] packetSkin = EaglerProfile.getSkinPacket(protocolVersion); - if(packetSkin.length > 0xFFFF) { + if (packetSkin.length > 0xFFFF) { throw new IOException("Skin packet is too long: " + packetSkin.length); } profileDataToSend.put(protocolVersion >= 4 ? "skin_v2" : "skin_v1", packetSkin); - + byte[] packetCape = EaglerProfile.getCapePacket(); - if(packetCape.length > 0xFFFF) { + if (packetCape.length > 0xFFFF) { throw new IOException("Cape packet is too long: " + packetCape.length); } profileDataToSend.put("cape_v1", packetCape); - + byte[] packetSignatureData = UpdateService.getClientSignatureData(); - if(packetSignatureData != null) { + if (packetSignatureData != null) { profileDataToSend.put("update_cert_v1", packetSignatureData); } - - if(protocolVersion >= 4) { - List> toSend = new ArrayList<>(profileDataToSend.entrySet()); - while(!toSend.isEmpty()) { + + if (protocolVersion >= 4) { + List> toSend = new ArrayList<>(profileDataToSend.entrySet()); + while (!toSend.isEmpty()) { int sendLen = 2; bao.reset(); d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_PROFILE_DATA); d.writeByte(0); // will be replaced int packetCount = 0; - while(!toSend.isEmpty() && packetCount < 255) { - Entry etr = toSend.get(toSend.size() - 1); + while (!toSend.isEmpty() && packetCount < 255) { + Entry etr = toSend.get(toSend.size() - 1); int i = 3 + etr.getKey().length() + etr.getValue().length; - if(sendLen + i < 0xFF00) { + if (sendLen + i < 0xFF00) { String profileDataType = etr.getKey(); d.writeByte(profileDataType.length()); d.writeBytes(profileDataType); @@ -361,16 +360,16 @@ public class ConnectionHandshake { d.write(data); toSend.remove(toSend.size() - 1); ++packetCount; - }else { + } else { break; } } byte[] send = bao.toByteArray(); - send[1] = (byte)packetCount; + send[1] = (byte) packetCount; client.send(send); } - }else { - for(Entry etr : profileDataToSend.entrySet()) { + } else { + for (Entry etr : profileDataToSend.entrySet()) { bao.reset(); d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_PROFILE_DATA); String profileDataType = etr.getKey(); @@ -382,125 +381,139 @@ public class ConnectionHandshake { client.send(bao.toByteArray()); } } - + bao.reset(); d.writeByte(HandshakePacketTypes.PROTOCOL_CLIENT_FINISH_LOGIN); client.send(bao.toByteArray()); - + read = awaitNextPacket(client, baseTimeout); - if(read == null) { + if (read == null) { logger.error("Read timed out while waiting for login confirmation response!"); return false; } - + di = new DataInputStream(new EaglerInputStream(read)); type = di.read(); - if(type == HandshakePacketTypes.PROTOCOL_SERVER_FINISH_LOGIN) { + if (type == HandshakePacketTypes.PROTOCOL_SERVER_FINISH_LOGIN) { return true; - }else if(type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) { + } else if (type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) { showError(mc, client, connecting, ret, di, protocolVersion == protocolV2); return false; - }else { + } else { return false; } - }else if(type == HandshakePacketTypes.PROTOCOL_SERVER_DENY_LOGIN) { - if(protocolVersion == protocolV2) { + } else if (type == HandshakePacketTypes.PROTOCOL_SERVER_DENY_LOGIN) { + if (protocolVersion == protocolV2) { msgLen = di.read(); - }else { + } else { msgLen = di.readUnsignedShort(); } dat = new byte[msgLen]; di.read(dat); String errStr = new String(dat, StandardCharsets.UTF_8); - mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", IChatComponent.Serializer.jsonToComponent(errStr))); + mc.displayGuiScreen(new GuiDisconnected(ret, "connect.failed", + IChatComponent.Serializer.jsonToComponent(errStr))); return false; - }else if(type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) { + } else if (type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) { showError(mc, client, connecting, ret, di, protocolVersion == protocolV2); return false; - }else { + } else { return false; } - }else if(type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) { + } else if (type == HandshakePacketTypes.PROTOCOL_SERVER_ERROR) { showError(mc, client, connecting, ret, di, true); return false; - }else { + } else { return false; } - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Exception in handshake"); logger.error(t); return false; } - + } - + private static byte[] awaitNextPacket(IWebSocketClient client, long timeout) { long millis = EagRuntime.steadyTimeMillis(); IWebSocketFrame b; - while((b = client.getNextBinaryFrame()) == null) { - if(client.getState().isClosed()) { + while ((b = client.getNextBinaryFrame()) == null) { + if (client.getState().isClosed()) { return null; } try { Thread.sleep(50l); } catch (InterruptedException e) { } - if(EagRuntime.steadyTimeMillis() - millis > timeout) { + if (EagRuntime.steadyTimeMillis() - millis > timeout) { client.close(); return null; } } return b.getByteArray(); } - - private static void showError(Minecraft mc, IWebSocketClient client, GuiConnecting connecting, GuiScreen scr, DataInputStream err, boolean v2) throws IOException { + + public static GuiScreen displayAuthProtocolConfirm(int protocol, GuiScreen no, GuiScreen yes) { + if (protocol == HandshakePacketTypes.AUTH_METHOD_PLAINTEXT) { + return new GuiHandshakeApprove("plaintext", no, yes); + } else if (protocol != HandshakePacketTypes.AUTH_METHOD_EAGLER_SHA256 + && protocol != HandshakePacketTypes.AUTH_METHOD_AUTHME_SHA256) { + return new GuiHandshakeApprove("unsupportedAuth", no); + } else { + return null; + } + } + + public static byte[] getSPHandshakeProtocolData() { + try { + EaglerOutputStream bao = new EaglerOutputStream(); + DataOutputStream d = new DataOutputStream(bao); + d.writeShort(3); // supported eagler protocols count + d.writeShort(protocolV2); // client supports v2 + d.writeShort(protocolV3); // client supports v3 + d.writeShort(protocolV4); // client supports v4 + return bao.toByteArray(); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + private static void showError(Minecraft mc, IWebSocketClient client, GuiConnecting connecting, GuiScreen scr, + DataInputStream err, boolean v2) throws IOException { int errorCode = err.read(); int msgLen = v2 ? err.read() : err.readUnsignedShort(); - + // workaround for bug in EaglerXBungee 1.2.7 and below - if(msgLen == 0) { - if(v2) { - if(err.available() == 256) { + if (msgLen == 0) { + if (v2) { + if (err.available() == 256) { msgLen = 256; } - }else { - if(err.available() == 65536) { + } else { + if (err.available() == 65536) { msgLen = 65536; } } } - + byte[] dat = new byte[msgLen]; err.read(dat); String errStr = new String(dat, StandardCharsets.UTF_8); logger.info("Server Error Code {}: {}", errorCode, errStr); - if(errorCode == HandshakePacketTypes.SERVER_ERROR_RATELIMIT_BLOCKED) { + if (errorCode == HandshakePacketTypes.SERVER_ERROR_RATELIMIT_BLOCKED) { RateLimitTracker.registerBlock(client.getCurrentURI()); mc.displayGuiScreen(GuiDisconnected.createRateLimitKick(scr)); - }else if(errorCode == HandshakePacketTypes.SERVER_ERROR_RATELIMIT_LOCKED) { + } else if (errorCode == HandshakePacketTypes.SERVER_ERROR_RATELIMIT_LOCKED) { RateLimitTracker.registerLockOut(client.getCurrentURI()); mc.displayGuiScreen(GuiDisconnected.createRateLimitKick(scr)); - }else if(errorCode == HandshakePacketTypes.SERVER_ERROR_CUSTOM_MESSAGE) { - mc.displayGuiScreen(new GuiDisconnected(scr, "connect.failed", IChatComponent.Serializer.jsonToComponent(errStr))); - }else if(connecting != null && errorCode == HandshakePacketTypes.SERVER_ERROR_AUTHENTICATION_REQUIRED) { + } else if (errorCode == HandshakePacketTypes.SERVER_ERROR_CUSTOM_MESSAGE) { + mc.displayGuiScreen( + new GuiDisconnected(scr, "connect.failed", IChatComponent.Serializer.jsonToComponent(errStr))); + } else if (connecting != null && errorCode == HandshakePacketTypes.SERVER_ERROR_AUTHENTICATION_REQUIRED) { mc.displayGuiScreen(new GuiAuthenticationScreen(connecting, scr, errStr)); - }else { - mc.displayGuiScreen(new GuiDisconnected(scr, "connect.failed", new ChatComponentText("Server Error Code " + errorCode + "\n" + errStr))); + } else { + mc.displayGuiScreen(new GuiDisconnected(scr, "connect.failed", + new ChatComponentText("Server Error Code " + errorCode + "\n" + errStr))); } } - - public static GuiScreen displayAuthProtocolConfirm(int protocol, GuiScreen no, GuiScreen yes) { - if(protocol == HandshakePacketTypes.AUTH_METHOD_PLAINTEXT) { - return new GuiHandshakeApprove("plaintext", no, yes); - }else if(protocol != HandshakePacketTypes.AUTH_METHOD_EAGLER_SHA256 && protocol != HandshakePacketTypes.AUTH_METHOD_AUTHME_SHA256) { - return new GuiHandshakeApprove("unsupportedAuth", no); - }else { - return null; - } - } - - private static final byte[] HEX = new byte[] { - (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', - (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' - }; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EaglercraftNetworkManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EaglercraftNetworkManager.java index 86959d94..55945493 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EaglercraftNetworkManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EaglercraftNetworkManager.java @@ -15,98 +15,99 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public abstract class EaglercraftNetworkManager { - + + public static final Logger logger = LogManager.getLogger("NetworkManager"); protected final String address; protected INetHandler nethandler = null; protected EnumConnectionState packetState = EnumConnectionState.HANDSHAKING; protected final PacketBuffer temporaryBuffer; + protected int debugPacketCounter = 0; - protected String pluginBrand = null; + protected String pluginVersion = null; - - public static final Logger logger = LogManager.getLogger("NetworkManager"); + + protected boolean clientDisconnected = false; public EaglercraftNetworkManager(String address) { this.address = address; this.temporaryBuffer = new PacketBuffer(Unpooled.buffer(0x1FFFF)); } - - public void setPluginInfo(String pluginBrand, String pluginVersion) { - this.pluginBrand = pluginBrand; - this.pluginVersion = pluginVersion; - } - - public String getPluginBrand() { - return pluginBrand; - } - - public String getPluginVersion() { - return pluginVersion; - } - + + public abstract boolean checkDisconnected(); + + public abstract void closeChannel(IChatComponent reason); + public abstract void connect(); - - public abstract EnumEaglerConnectionState getConnectStatus(); - + + protected void doClientDisconnect(IChatComponent msg) { + if (!clientDisconnected) { + clientDisconnected = true; + if (nethandler != null) { + this.nethandler.onDisconnect(msg); + } + } + } + public String getAddress() { return address; } - - public abstract void closeChannel(IChatComponent reason); - - public void setConnectionState(EnumConnectionState state) { - packetState = state; - } - - public abstract void processReceivedPackets() throws IOException; - public abstract void sendPacket(Packet pkt); - - public void setNetHandler(INetHandler nethandler) { - this.nethandler = nethandler; - } - - public boolean isLocalChannel() { - return false; - } - - public boolean isChannelOpen() { - return getConnectStatus() == EnumEaglerConnectionState.CONNECTED; - } + public abstract EnumEaglerConnectionState getConnectStatus(); public boolean getIsencrypted() { return false; } + public String getPluginBrand() { + return pluginBrand; + } + + public String getPluginVersion() { + return pluginVersion; + } + + public boolean isChannelOpen() { + return getConnectStatus() == EnumEaglerConnectionState.CONNECTED; + } + + public boolean isLocalChannel() { + return false; + } + + public abstract void processReceivedPackets() throws IOException; + + public abstract void sendPacket(Packet pkt); + public void setCompressionTreshold(int compressionTreshold) { throw new CompressionNotSupportedException(); } - public abstract boolean checkDisconnected(); - - protected boolean clientDisconnected = false; - - protected void doClientDisconnect(IChatComponent msg) { - if(!clientDisconnected) { - clientDisconnected = true; - if(nethandler != null) { - this.nethandler.onDisconnect(msg); - } - } + public void setConnectionState(EnumConnectionState state) { + packetState = state; } - + + public void setNetHandler(INetHandler nethandler) { + this.nethandler = nethandler; + } + + public void setPluginInfo(String pluginBrand, String pluginVersion) { + this.pluginBrand = pluginBrand; + this.pluginVersion = pluginVersion; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EncryptionNotSupportedException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EncryptionNotSupportedException.java index dfec35e3..1031955e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EncryptionNotSupportedException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/EncryptionNotSupportedException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.socket; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -18,9 +19,8 @@ package net.lax1dude.eaglercraft.v1_8.socket; public class EncryptionNotSupportedException extends UnsupportedOperationException { public EncryptionNotSupportedException() { - super("Encryption is not supported by Eaglercraft, set " + - "online-mode=false' in server.properties to " + - "allow Eaglercraft connections to this server"); + super("Encryption is not supported by Eaglercraft, set " + "online-mode=false' in server.properties to " + + "allow Eaglercraft connections to this server"); } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/GuiHandshakeApprove.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/GuiHandshakeApprove.java index 19882b92..32e20f77 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/GuiHandshakeApprove.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/GuiHandshakeApprove.java @@ -10,14 +10,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,14 +34,43 @@ public class GuiHandshakeApprove extends GuiScreen { protected int bodyY; + public GuiHandshakeApprove(String message, GuiScreen back) { + this(message, back, null); + } + public GuiHandshakeApprove(String message, GuiScreen no, GuiScreen yes) { this.message = message; this.no = no; this.yes = yes; } - public GuiHandshakeApprove(String message, GuiScreen back) { - this(message, back, null); + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + mc.displayGuiScreen(no); + } else if (parGuiButton.id == 1) { + mc.displayGuiScreen(yes); + } + } + + public void drawScreen(int xx, int yy, float partialTicks) { + drawBackground(0); + drawCenteredString(fontRendererObj, titleString, width / 2, bodyY, 16777215); + for (int i = 0, l = bodyLines.size(); i < l; ++i) { + String s = bodyLines.get(i); + if (s.length() > 0) { + drawCenteredString(fontRendererObj, s, width / 2, bodyY + 20 + i * 10, 16777215); + } + } + super.drawScreen(xx, yy, partialTicks); + } + + private String getI18nOrNull(String key) { + String ret = I18n.format(key); + if (key.equals(ret)) { + return null; + } else { + return ret; + } } public void initGui() { @@ -49,16 +79,16 @@ public class GuiHandshakeApprove extends GuiScreen { bodyLines = new ArrayList<>(); int i = 0; boolean wasNull = true; - while(true) { + while (true) { String line = getI18nOrNull("handshakeApprove." + message + ".body." + (i++)); - if(line == null) { - if(wasNull) { + if (line == null) { + if (wasNull) { break; - }else { + } else { bodyLines.add(""); wasNull = true; } - }else { + } else { bodyLines.add(line); wasNull = false; } @@ -66,41 +96,12 @@ public class GuiHandshakeApprove extends GuiScreen { int totalHeight = 10 + 10 + bodyLines.size() * 10 + 10 + 20; bodyY = (height - totalHeight) / 2 - 15; int buttonY = bodyY + totalHeight - 20; - if(yes != null) { + if (yes != null) { this.buttonList.add(new GuiButton(0, width / 2 + 3, buttonY, 100, 20, I18n.format("gui.no"))); this.buttonList.add(new GuiButton(1, width / 2 - 103, buttonY, 100, 20, I18n.format("gui.yes"))); - }else { + } else { this.buttonList.add(new GuiButton(0, width / 2 - 100, buttonY, 200, 20, I18n.format("gui.back"))); } } - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 0) { - mc.displayGuiScreen(no); - }else if(parGuiButton.id == 1) { - mc.displayGuiScreen(yes); - } - } - - public void drawScreen(int xx, int yy, float partialTicks) { - drawBackground(0); - drawCenteredString(fontRendererObj, titleString, width / 2, bodyY, 16777215); - for(int i = 0, l = bodyLines.size(); i < l; ++i) { - String s = bodyLines.get(i); - if(s.length() > 0) { - drawCenteredString(fontRendererObj, s, width / 2, bodyY + 20 + i * 10, 16777215); - } - } - super.drawScreen(xx, yy, partialTicks); - } - - private String getI18nOrNull(String key) { - String ret = I18n.format(key); - if(key.equals(ret)) { - return null; - }else { - return ret; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/HandshakePacketTypes.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/HandshakePacketTypes.java index a5ee6fb8..c7fe0fef 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/HandshakePacketTypes.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/HandshakePacketTypes.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.socket; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/RateLimitTracker.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/RateLimitTracker.java index 97786ca3..9a94b092 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/RateLimitTracker.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/RateLimitTracker.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,17 +50,17 @@ public class RateLimitTracker { public static void tick() { long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastTickUpdate > 5000l) { + if (millis - lastTickUpdate > 5000l) { lastTickUpdate = millis; Iterator blocksItr = blocks.values().iterator(); - while(blocksItr.hasNext()) { - if(millis - blocksItr.next().longValue() > 900000l) { + while (blocksItr.hasNext()) { + if (millis - blocksItr.next().longValue() > 900000l) { blocksItr.remove(); } } blocksItr = lockout.values().iterator(); - while(blocksItr.hasNext()) { - if(millis - blocksItr.next().longValue() > 900000l) { + while (blocksItr.hasNext()) { + if (millis - blocksItr.next().longValue() > 900000l) { blocksItr.remove(); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryDispatch.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryDispatch.java index bfff0c4b..b211b31a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryDispatch.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryDispatch.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2022-2023 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryImpl.java index 19c37156..3289d4bd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/ServerQueryImpl.java @@ -18,14 +18,15 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -54,104 +55,42 @@ class ServerQueryImpl implements IServerQuery { } @Override - public void update() { - if(!hasSentAccept && websocketClient.getState() == EnumEaglerConnectionState.CONNECTED) { - hasSentAccept = true; - websocketClient.send("Accept: " + accept); + public int binaryResponsesAvailable() { + synchronized (queryResponsesBytes) { + return queryResponsesBytes.size(); } - List lst = websocketClient.getNextFrames(); - if(lst != null) { - for(int i = 0, l = lst.size(); i < l; ++i) { - IWebSocketFrame frame = lst.get(i); - alive = true; - if(pingTimer == -1) { - pingTimer = PlatformRuntime.steadyTimeMillis() - pingStart; - if(pingTimer < 1) { - pingTimer = 1; - } - } - if(frame.isString()) { - String str = frame.getString(); - if(str.equalsIgnoreCase("BLOCKED")) { - logger.error("Reached full IP ratelimit for {}!", uri); - rateLimit = EnumServerRateLimit.BLOCKED; - return; - } - if(str.equalsIgnoreCase("LOCKED")) { - logger.error("Reached full IP ratelimit lockout for {}!", uri); - rateLimit = EnumServerRateLimit.LOCKED_OUT; - return; - } - try { - JSONObject obj = new JSONObject(str); - if("blocked".equalsIgnoreCase(obj.optString("type", null))) { - logger.error("Reached query ratelimit for {}!", uri); - rateLimit = EnumServerRateLimit.BLOCKED; - }else if("locked".equalsIgnoreCase(obj.optString("type", null))) { - logger.error("Reached query ratelimit lockout for {}!", uri); - rateLimit = EnumServerRateLimit.LOCKED_OUT; - }else { - queryResponses.add(new QueryResponse(obj, pingTimer)); - } - }catch(Throwable t) { - logger.error("Exception thrown parsing websocket query response from \"" + uri + "\"!"); - logger.error(t); - } - }else { - queryResponsesBytes.add(frame.getByteArray()); - } - } - } - if(websocketClient.isClosed()) { + } + + @Override + public void close() { + if (open) { open = false; + websocketClient.close(); } } @Override - public void send(String str) { - if(websocketClient.getState() == EnumEaglerConnectionState.CONNECTED) { - websocketClient.send(str); - } - } - - @Override - public void send(byte[] bytes) { - if(websocketClient.getState() == EnumEaglerConnectionState.CONNECTED) { - websocketClient.send(bytes); - } - } - - @Override - public int responsesAvailable() { - synchronized(queryResponses) { - return queryResponses.size(); - } - } - - @Override - public QueryResponse getResponse() { - synchronized(queryResponses) { - if(queryResponses.size() > 0) { - return queryResponses.remove(0); - }else { + public byte[] getBinaryResponse() { + synchronized (queryResponsesBytes) { + if (queryResponsesBytes.size() > 0) { + return queryResponsesBytes.remove(0); + } else { return null; } } } @Override - public int binaryResponsesAvailable() { - synchronized(queryResponsesBytes) { - return queryResponsesBytes.size(); - } + public EnumServerRateLimit getRateLimit() { + return rateLimit; } @Override - public byte[] getBinaryResponse() { - synchronized(queryResponsesBytes) { - if(queryResponsesBytes.size() > 0) { - return queryResponsesBytes.remove(0); - }else { + public QueryResponse getResponse() { + synchronized (queryResponses) { + if (queryResponses.size() > 0) { + return queryResponses.remove(0); + } else { return null; } } @@ -164,16 +103,78 @@ class ServerQueryImpl implements IServerQuery { } @Override - public void close() { - if(open) { - open = false; - websocketClient.close(); + public int responsesAvailable() { + synchronized (queryResponses) { + return queryResponses.size(); } } @Override - public EnumServerRateLimit getRateLimit() { - return rateLimit; + public void send(byte[] bytes) { + if (websocketClient.getState() == EnumEaglerConnectionState.CONNECTED) { + websocketClient.send(bytes); + } + } + + @Override + public void send(String str) { + if (websocketClient.getState() == EnumEaglerConnectionState.CONNECTED) { + websocketClient.send(str); + } + } + + @Override + public void update() { + if (!hasSentAccept && websocketClient.getState() == EnumEaglerConnectionState.CONNECTED) { + hasSentAccept = true; + websocketClient.send("Accept: " + accept); + } + List lst = websocketClient.getNextFrames(); + if (lst != null) { + for (int i = 0, l = lst.size(); i < l; ++i) { + IWebSocketFrame frame = lst.get(i); + alive = true; + if (pingTimer == -1) { + pingTimer = PlatformRuntime.steadyTimeMillis() - pingStart; + if (pingTimer < 1) { + pingTimer = 1; + } + } + if (frame.isString()) { + String str = frame.getString(); + if (str.equalsIgnoreCase("BLOCKED")) { + logger.error("Reached full IP ratelimit for {}!", uri); + rateLimit = EnumServerRateLimit.BLOCKED; + return; + } + if (str.equalsIgnoreCase("LOCKED")) { + logger.error("Reached full IP ratelimit lockout for {}!", uri); + rateLimit = EnumServerRateLimit.LOCKED_OUT; + return; + } + try { + JSONObject obj = new JSONObject(str); + if ("blocked".equalsIgnoreCase(obj.optString("type", null))) { + logger.error("Reached query ratelimit for {}!", uri); + rateLimit = EnumServerRateLimit.BLOCKED; + } else if ("locked".equalsIgnoreCase(obj.optString("type", null))) { + logger.error("Reached query ratelimit lockout for {}!", uri); + rateLimit = EnumServerRateLimit.LOCKED_OUT; + } else { + queryResponses.add(new QueryResponse(obj, pingTimer)); + } + } catch (Throwable t) { + logger.error("Exception thrown parsing websocket query response from \"" + uri + "\"!"); + logger.error(t); + } + } else { + queryResponsesBytes.add(frame.getByteArray()); + } + } + } + if (websocketClient.isClosed()) { + open = false; + } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/WebSocketNetworkManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/WebSocketNetworkManager.java index fb251f6f..a7e4e0ca 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/WebSocketNetworkManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/WebSocketNetworkManager.java @@ -17,14 +17,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,6 +39,27 @@ public class WebSocketNetworkManager extends EaglercraftNetworkManager { this.webSocketClient = webSocketClient; } + public boolean checkDisconnected() { + if (webSocketClient.isClosed()) { + try { + processReceivedPackets(); // catch kick message + } catch (IOException e) { + } + doClientDisconnect(new ChatComponentTranslation("disconnect.endOfStream")); + return true; + } else { + return false; + } + } + + public void closeChannel(IChatComponent reason) { + webSocketClient.close(); + if (nethandler != null) { + nethandler.onDisconnect(reason); + } + clientDisconnected = true; + } + public void connect() { } @@ -45,27 +67,21 @@ public class WebSocketNetworkManager extends EaglercraftNetworkManager { return webSocketClient.getState(); } - public void closeChannel(IChatComponent reason) { - webSocketClient.close(); - if(nethandler != null) { - nethandler.onDisconnect(reason); - } - clientDisconnected = true; - } - public void processReceivedPackets() throws IOException { - if(nethandler == null) return; - if(webSocketClient.availableStringFrames() > 0) { - logger.warn("discarding {} string frames recieved on a binary connection", webSocketClient.availableStringFrames()); + if (nethandler == null) + return; + if (webSocketClient.availableStringFrames() > 0) { + logger.warn("discarding {} string frames recieved on a binary connection", + webSocketClient.availableStringFrames()); webSocketClient.clearStringFrames(); } List pkts = webSocketClient.getNextBinaryFrames(); - if(pkts == null) { + if (pkts == null) { return; } - for(int i = 0, l = pkts.size(); i < l; ++i) { + for (int i = 0, l = pkts.size(); i < l; ++i) { IWebSocketFrame next = pkts.get(i); ++debugPacketCounter; try { @@ -74,79 +90,69 @@ public class WebSocketNetworkManager extends EaglercraftNetworkManager { nettyBuffer.writerIndex(asByteArray.length); PacketBuffer input = new PacketBuffer(nettyBuffer); int pktId = input.readVarIntFromBuffer(); - + Packet pkt; try { pkt = packetState.getPacket(EnumPacketDirection.CLIENTBOUND, pktId); - }catch(IllegalAccessException | InstantiationException ex) { + } catch (IllegalAccessException | InstantiationException ex) { throw new IOException("Recieved a packet with type " + pktId + " which is invalid!"); } - - if(pkt == null) { - throw new IOException("Recieved packet type " + pktId + " which is undefined in state " + packetState); + + if (pkt == null) { + throw new IOException( + "Recieved packet type " + pktId + " which is undefined in state " + packetState); } - + try { pkt.readPacketData(input); - }catch(Throwable t) { + } catch (Throwable t) { throw new IOException("Failed to read packet type '" + pkt.getClass().getSimpleName() + "'", t); } - + try { pkt.processPacket(nethandler); - }catch(Throwable t) { - logger.error("Failed to process {}! It'll be skipped for debug purposes.", pkt.getClass().getSimpleName()); + } catch (Throwable t) { + logger.error("Failed to process {}! It'll be skipped for debug purposes.", + pkt.getClass().getSimpleName()); logger.error(t); } - - }catch(Throwable t) { - logger.error("Failed to process websocket frame {}! It'll be skipped for debug purposes.", debugPacketCounter); + + } catch (Throwable t) { + logger.error("Failed to process websocket frame {}! It'll be skipped for debug purposes.", + debugPacketCounter); logger.error(t); } } } public void sendPacket(Packet pkt) { - if(!isChannelOpen()) { + if (!isChannelOpen()) { logger.error("Packet was sent on a closed connection: {}", pkt.getClass().getSimpleName()); return; } - + int i; try { i = packetState.getPacketId(EnumPacketDirection.SERVERBOUND, pkt); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Incorrect packet for state: {}", pkt.getClass().getSimpleName()); return; } - + temporaryBuffer.clear(); temporaryBuffer.writeVarIntToBuffer(i); try { pkt.writePacketData(temporaryBuffer); - }catch(IOException ex) { + } catch (IOException ex) { logger.error("Failed to write packet {}!", pkt.getClass().getSimpleName()); return; } - + int len = temporaryBuffer.writerIndex(); byte[] bytes = new byte[len]; temporaryBuffer.getBytes(0, bytes); - + webSocketClient.send(bytes); } - public boolean checkDisconnected() { - if(webSocketClient.isClosed()) { - try { - processReceivedPackets(); // catch kick message - } catch (IOException e) { - } - doClientDisconnect(new ChatComponentTranslation("disconnect.endOfStream")); - return true; - }else { - return false; - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV3MessageHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV3MessageHandler.java index 039c8646..7b3a9a45 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV3MessageHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV3MessageHandler.java @@ -6,7 +6,18 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.profile.SkinModel; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessageHandler; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketEnableFNAWSkinsEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapeCustomEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapePresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinPresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalAllowedEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDisconnectPeerEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalGlobalEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalICEEAG; import net.lax1dude.eaglercraft.v1_8.update.UpdateService; import net.lax1dude.eaglercraft.v1_8.voice.VoiceClientController; import net.minecraft.client.Minecraft; @@ -15,14 +26,15 @@ import net.minecraft.client.network.NetHandlerPlayClient; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -55,15 +67,15 @@ public class ClientV3MessageHandler implements GameMessageHandler { public void handleServer(SPacketOtherSkinCustomV3EAG packet) { EaglercraftUUID responseUUID = new EaglercraftUUID(packet.uuidMost, packet.uuidLeast); SkinModel modelId; - if(packet.modelID == (byte)0xFF) { + if (packet.modelID == (byte) 0xFF) { modelId = this.netHandler.getSkinCache().getRequestedSkinType(responseUUID); - }else { + } else { modelId = SkinModel.getModelFromId(packet.modelID & 0x7F); - if((packet.modelID & 0x80) != 0 && modelId.sanitize) { + if ((packet.modelID & 0x80) != 0 && modelId.sanitize) { modelId = SkinModel.STEVE; } } - if(modelId.highPoly != null) { + if (modelId.highPoly != null) { modelId = SkinModel.STEVE; } this.netHandler.getSkinCache().cacheSkinCustom(responseUUID, packet.customSkin, modelId); @@ -108,8 +120,8 @@ public class ClientV3MessageHandler implements GameMessageHandler { public void handleServer(SPacketVoiceSignalDisconnectPeerEAG packet) { if (VoiceClientController.isClientSupported()) { - VoiceClientController.handleVoiceSignalPacketTypeDisconnect( - new EaglercraftUUID(packet.uuidMost, packet.uuidLeast)); + VoiceClientController + .handleVoiceSignalPacketTypeDisconnect(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast)); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV4MessageHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV4MessageHandler.java index eb52fbe8..2c57efce 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV4MessageHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/ClientV4MessageHandler.java @@ -10,7 +10,35 @@ import net.lax1dude.eaglercraft.v1_8.cookie.ServerCookieDataStore; import net.lax1dude.eaglercraft.v1_8.profile.EaglerProfile; import net.lax1dude.eaglercraft.v1_8.profile.SkinModel; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessageHandler; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketCustomizePauseMenuV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketEnableFNAWSkinsEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientCapeCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientCapePresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinPresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketInvalidatePlayerCacheV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifBadgeHideV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifBadgeShowV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifIconsRegisterV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifIconsReleaseV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapeCustomEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapePresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherPlayerClientUUIDV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinPresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketRedirectClientV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketServerInfoDataChunkV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketSetServerCookieV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUnforceClientV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalAllowedEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectAnnounceV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDisconnectPeerEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalGlobalEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketWebViewMessageV4EAG; import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.SkinPacketVersionCache; import net.lax1dude.eaglercraft.v1_8.update.UpdateService; import net.lax1dude.eaglercraft.v1_8.voice.VoiceClientController; @@ -22,14 +50,15 @@ import net.minecraft.client.network.NetHandlerPlayClient; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,6 +71,10 @@ public class ClientV4MessageHandler implements GameMessageHandler { this.netHandler = netHandler; } + public void handleServer(SPacketCustomizePauseMenuV4EAG packet) { + PauseMenuCustomizeState.loadPacket(packet); + } + public void handleServer(SPacketEnableFNAWSkinsEAG packet) { netHandler.currentFNAWSkinAllowedState = packet.enableSkins; netHandler.currentFNAWSkinForcedState = packet.force; @@ -49,6 +82,52 @@ public class ClientV4MessageHandler implements GameMessageHandler { || (netHandler.currentFNAWSkinAllowedState && Minecraft.getMinecraft().gameSettings.enableFNAWSkins)); } + public void handleServer(SPacketForceClientCapeCustomV4EAG packet) { + EaglerProfile.handleForceCapeCustom(packet.customCape); + } + + public void handleServer(SPacketForceClientCapePresetV4EAG packet) { + EaglerProfile.handleForceCapePreset(packet.presetCape); + } + + public void handleServer(SPacketForceClientSkinCustomV4EAG packet) { + EaglerProfile.handleForceSkinCustom(packet.modelID, SkinPacketVersionCache.convertToV3Raw(packet.customSkin)); + } + + public void handleServer(SPacketForceClientSkinPresetV4EAG packet) { + EaglerProfile.handleForceSkinPreset(packet.presetSkin); + } + + public void handleServer(SPacketInvalidatePlayerCacheV4EAG packet) { + if (packet.players != null && packet.players.size() > 0) { + for (SPacketInvalidatePlayerCacheV4EAG.InvalidateRequest req : packet.players) { + EaglercraftUUID uuid = new EaglercraftUUID(req.uuidMost, req.uuidLeast); + if (req.invalidateSkin) { + this.netHandler.getSkinCache().handleInvalidate(uuid); + } + if (req.invalidateCape) { + this.netHandler.getCapeCache().handleInvalidate(uuid); + } + } + } + } + + public void handleServer(SPacketNotifBadgeHideV4EAG packet) { + netHandler.getNotifManager().processPacketHideBadge(packet); + } + + public void handleServer(SPacketNotifBadgeShowV4EAG packet) { + netHandler.getNotifManager().processPacketShowBadge(packet); + } + + public void handleServer(SPacketNotifIconsRegisterV4EAG packet) { + netHandler.getNotifManager().processPacketAddIcons(packet); + } + + public void handleServer(SPacketNotifIconsReleaseV4EAG packet) { + netHandler.getNotifManager().processPacketRemIcons(packet); + } + public void handleServer(SPacketOtherCapeCustomEAG packet) { netHandler.getCapeCache().cacheCapeCustom(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.customCape); @@ -59,25 +138,62 @@ public class ClientV4MessageHandler implements GameMessageHandler { packet.presetCape); } + public void handleServer(SPacketOtherPlayerClientUUIDV4EAG packet) { + ClientUUIDLoadingCache.handleResponse(packet.requestId, + new EaglercraftUUID(packet.clientUUIDMost, packet.clientUUIDLeast)); + } + public void handleServer(SPacketOtherSkinCustomV4EAG packet) { EaglercraftUUID responseUUID = new EaglercraftUUID(packet.uuidMost, packet.uuidLeast); SkinModel modelId; - if(packet.modelID == (byte)0xFF) { + if (packet.modelID == (byte) 0xFF) { modelId = this.netHandler.getSkinCache().getRequestedSkinType(responseUUID); - }else { + } else { modelId = SkinModel.getModelFromId(packet.modelID & 0x7F); - if((packet.modelID & 0x80) != 0 && modelId.sanitize) { + if ((packet.modelID & 0x80) != 0 && modelId.sanitize) { modelId = SkinModel.STEVE; } } - if(modelId.highPoly != null) { + if (modelId.highPoly != null) { modelId = SkinModel.STEVE; } - this.netHandler.getSkinCache().cacheSkinCustom(responseUUID, SkinPacketVersionCache.convertToV3Raw(packet.customSkin), modelId); + this.netHandler.getSkinCache().cacheSkinCustom(responseUUID, + SkinPacketVersionCache.convertToV3Raw(packet.customSkin), modelId); } public void handleServer(SPacketOtherSkinPresetEAG packet) { - this.netHandler.getSkinCache().cacheSkinPreset(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.presetSkin); + this.netHandler.getSkinCache().cacheSkinPreset(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + packet.presetSkin); + } + + public void handleServer(SPacketRedirectClientV4EAG packet) { + Minecraft.getMinecraft().handleReconnectPacket(packet.redirectURI); + } + + public void handleServer(SPacketServerInfoDataChunkV4EAG packet) { + ServerInfoCache.handleChunk(packet); + } + + public void handleServer(SPacketSetServerCookieV4EAG packet) { + if (!netHandler.isClientInEaglerSingleplayerOrLAN() + && Minecraft.getMinecraft().getCurrentServerData().enableCookies) { + ServerCookieDataStore.saveCookie(netHandler.getNetworkManager().getAddress(), packet.expires, packet.data, + packet.revokeQuerySupported, packet.saveCookieToDisk); + } + } + + public void handleServer(SPacketUnforceClientV4EAG packet) { + if (packet.resetSkin) { + EaglerProfile.isServerSkinOverride = false; + } + if (packet.resetCape) { + EaglerProfile.isServerCapeOverride = false; + } + if (packet.resetFNAW) { + netHandler.currentFNAWSkinForcedState = false; + Minecraft.getMinecraft().getRenderManager().setEnableFNAWSkins( + netHandler.currentFNAWSkinAllowedState && Minecraft.getMinecraft().gameSettings.enableFNAWSkins); + } } public void handleServer(SPacketUpdateCertEAG packet) { @@ -92,15 +208,17 @@ public class ClientV4MessageHandler implements GameMessageHandler { } } - public void handleServer(SPacketVoiceSignalConnectV4EAG packet) { + public void handleServer(SPacketVoiceSignalConnectAnnounceV4EAG packet) { if (VoiceClientController.isClientSupported()) { - VoiceClientController.handleVoiceSignalPacketTypeConnect(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.offer); + VoiceClientController + .handleVoiceSignalPacketTypeConnectAnnounce(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast)); } } - public void handleServer(SPacketVoiceSignalConnectAnnounceV4EAG packet) { + public void handleServer(SPacketVoiceSignalConnectV4EAG packet) { if (VoiceClientController.isClientSupported()) { - VoiceClientController.handleVoiceSignalPacketTypeConnectAnnounce(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast)); + VoiceClientController.handleVoiceSignalPacketTypeConnect( + new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.offer); } } @@ -114,7 +232,8 @@ public class ClientV4MessageHandler implements GameMessageHandler { public void handleServer(SPacketVoiceSignalDisconnectPeerEAG packet) { if (VoiceClientController.isClientSupported()) { - VoiceClientController.handleVoiceSignalPacketTypeDisconnect(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast)); + VoiceClientController + .handleVoiceSignalPacketTypeDisconnect(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast)); } } @@ -132,91 +251,8 @@ public class ClientV4MessageHandler implements GameMessageHandler { } } - public void handleServer(SPacketForceClientSkinPresetV4EAG packet) { - EaglerProfile.handleForceSkinPreset(packet.presetSkin); - } - - public void handleServer(SPacketForceClientSkinCustomV4EAG packet) { - EaglerProfile.handleForceSkinCustom(packet.modelID, SkinPacketVersionCache.convertToV3Raw(packet.customSkin)); - } - - public void handleServer(SPacketSetServerCookieV4EAG packet) { - if(!netHandler.isClientInEaglerSingleplayerOrLAN() && Minecraft.getMinecraft().getCurrentServerData().enableCookies) { - ServerCookieDataStore.saveCookie(netHandler.getNetworkManager().getAddress(), packet.expires, packet.data, - packet.revokeQuerySupported, packet.saveCookieToDisk); - } - } - - public void handleServer(SPacketRedirectClientV4EAG packet) { - Minecraft.getMinecraft().handleReconnectPacket(packet.redirectURI); - } - - public void handleServer(SPacketOtherPlayerClientUUIDV4EAG packet) { - ClientUUIDLoadingCache.handleResponse(packet.requestId, new EaglercraftUUID(packet.clientUUIDMost, packet.clientUUIDLeast)); - } - - public void handleServer(SPacketForceClientCapePresetV4EAG packet) { - EaglerProfile.handleForceCapePreset(packet.presetCape); - } - - public void handleServer(SPacketForceClientCapeCustomV4EAG packet) { - EaglerProfile.handleForceCapeCustom(packet.customCape); - } - - public void handleServer(SPacketInvalidatePlayerCacheV4EAG packet) { - if(packet.players != null && packet.players.size() > 0) { - for(SPacketInvalidatePlayerCacheV4EAG.InvalidateRequest req : packet.players) { - EaglercraftUUID uuid = new EaglercraftUUID(req.uuidMost, req.uuidLeast); - if(req.invalidateSkin) { - this.netHandler.getSkinCache().handleInvalidate(uuid); - } - if(req.invalidateCape) { - this.netHandler.getCapeCache().handleInvalidate(uuid); - } - } - } - } - - public void handleServer(SPacketUnforceClientV4EAG packet) { - if(packet.resetSkin) { - EaglerProfile.isServerSkinOverride = false; - } - if(packet.resetCape) { - EaglerProfile.isServerCapeOverride = false; - } - if(packet.resetFNAW) { - netHandler.currentFNAWSkinForcedState = false; - Minecraft.getMinecraft().getRenderManager().setEnableFNAWSkins( - netHandler.currentFNAWSkinAllowedState && Minecraft.getMinecraft().gameSettings.enableFNAWSkins); - } - } - - public void handleServer(SPacketCustomizePauseMenuV4EAG packet) { - PauseMenuCustomizeState.loadPacket(packet); - } - - public void handleServer(SPacketServerInfoDataChunkV4EAG packet) { - ServerInfoCache.handleChunk(packet); - } - public void handleServer(SPacketWebViewMessageV4EAG packet) { WebViewOverlayController.handleMessagePacket(packet); } - public void handleServer(SPacketNotifIconsRegisterV4EAG packet) { - netHandler.getNotifManager().processPacketAddIcons(packet); - } - - public void handleServer(SPacketNotifIconsReleaseV4EAG packet) { - netHandler.getNotifManager().processPacketRemIcons(packet); - } - - public void handleServer(SPacketNotifBadgeShowV4EAG packet) { - netHandler.getNotifManager().processPacketShowBadge(packet); - } - - public void handleServer(SPacketNotifBadgeHideV4EAG packet) { - netHandler.getNotifManager().processPacketHideBadge(packet); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/GameProtocolMessageController.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/GameProtocolMessageController.java index dc4176ea..38489de6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/GameProtocolMessageController.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/GameProtocolMessageController.java @@ -22,14 +22,15 @@ import net.minecraft.network.PacketBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,143 +39,8 @@ public class GameProtocolMessageController { private static final Logger logger = LogManager.getLogger("GameProtocolMessageController"); - public final GamePluginMessageProtocol protocol; - public final int sendDirection; - public final int receiveDirection; - private final PacketBufferInputWrapper inputStream = new PacketBufferInputWrapper(null); - private final PacketBufferOutputWrapper outputStream = new PacketBufferOutputWrapper(null); - private final GameMessageHandler handler; - private final IPluginMessageSendFunction sendFunction; - private final List sendQueueV4; - private final boolean noDelay; - - public GameProtocolMessageController(GamePluginMessageProtocol protocol, int sendDirection, GameMessageHandler handler, - IPluginMessageSendFunction sendCallback) { - this.protocol = protocol; - this.sendDirection = sendDirection; - this.receiveDirection = GamePluginMessageConstants.oppositeDirection(sendDirection); - this.handler = handler; - this.sendFunction = sendCallback; - this.noDelay = protocol.ver < 4 || EagRuntime.getConfiguration().isEaglerNoDelay(); - this.sendQueueV4 = !noDelay ? new LinkedList<>() : null; - } - - public boolean handlePacket(String channel, PacketBuffer data) throws IOException { - GameMessagePacket pkt; - if(protocol.ver >= 4 && data.readableBytes() > 0 && data.getByte(data.readerIndex()) == (byte) 0xFF - && channel.equals(GamePluginMessageConstants.V4_CHANNEL)) { - data.readByte(); - inputStream.buffer = data; - int count = inputStream.readVarInt(); - for(int i = 0, j, k; i < count; ++i) { - j = data.readVarIntFromBuffer(); - k = data.readerIndex() + j; - if(j > data.readableBytes()) { - throw new IOException("Packet fragment is too long: " + j + " > " + data.readableBytes()); - } - pkt = protocol.readPacket(channel, receiveDirection, inputStream); - if(pkt != null) { - try { - pkt.handlePacket(handler); - }catch(Throwable t) { - logger.error("Failed to handle packet {} in direction {} using handler {}!", pkt.getClass().getSimpleName(), - GamePluginMessageConstants.getDirectionString(receiveDirection), handler); - logger.error(t); - } - }else { - logger.warn("Could not read packet fragment {} of {}, unknown packet", count, i); - } - if(data.readerIndex() != k) { - logger.warn("Packet fragment {} was the wrong length: {} != {}", - (pkt != null ? pkt.getClass().getSimpleName() : "unknown"), j + data.readerIndex() - k, j); - data.readerIndex(k); - } - } - if(data.readableBytes() > 0) { - logger.warn("Leftover data after reading multi-packet! ({} bytes)", data.readableBytes()); - } - inputStream.buffer = null; - return true; - } - inputStream.buffer = data; - pkt = protocol.readPacket(channel, receiveDirection, inputStream); - if(pkt != null && inputStream.available() > 0) { - logger.warn("Leftover data after reading packet {}! ({} bytes)", pkt.getClass().getSimpleName(), inputStream.available()); - } - inputStream.buffer = null; - if(pkt != null) { - try { - pkt.handlePacket(handler); - }catch(Throwable t) { - logger.error("Failed to handle packet {} in direction {} using handler {}!", pkt.getClass().getSimpleName(), - GamePluginMessageConstants.getDirectionString(receiveDirection), handler); - logger.error(t); - } - return true; - }else { - return false; - } - } - - public void sendPacket(GameMessagePacket packet) throws IOException { - int len = packet.length() + 1; - PacketBuffer buf = new PacketBuffer(len != 0 ? Unpooled.buffer(len) : Unpooled.buffer(64)); - outputStream.buffer = buf; - String chan = protocol.writePacket(sendDirection, outputStream, packet); - outputStream.buffer = null; - int j = buf.writerIndex(); - if(len != 0 && j != len && j + 1 != len) { - logger.warn("Packet {} was expected to be {} bytes but was serialized to {} bytes!", - packet.getClass().getSimpleName(), len, j); - } - if(sendQueueV4 != null && chan.equals(GamePluginMessageConstants.V4_CHANNEL)) { - sendQueueV4.add(buf); - }else { - sendFunction.sendPluginMessage(chan, buf); - } - } - - public void flush() { - if(sendQueueV4 != null) { - int queueLen = sendQueueV4.size(); - PacketBuffer pkt; - if(queueLen == 0) { - return; - }else if(queueLen == 1) { - pkt = sendQueueV4.remove(0); - sendFunction.sendPluginMessage(GamePluginMessageConstants.V4_CHANNEL, pkt); - }else { - int i, j, sendCount = 0, totalLen = 0; - PacketBuffer sendBuffer; - while(sendQueueV4.size() > 0) { - do { - i = sendQueueV4.get(sendCount++).readableBytes(); - totalLen += GamePacketOutputBuffer.getVarIntSize(i) + i; - }while(totalLen < 32760 && sendCount < sendQueueV4.size()); - if(totalLen >= 32760) { - --sendCount; - } - if(sendCount <= 1) { - pkt = sendQueueV4.remove(0); - sendFunction.sendPluginMessage(GamePluginMessageConstants.V4_CHANNEL, pkt); - continue; - } - sendBuffer = new PacketBuffer(Unpooled.buffer(1 + totalLen + GamePacketOutputBuffer.getVarIntSize(sendCount))); - sendBuffer.writeByte(0xFF); - sendBuffer.writeVarIntToBuffer(sendCount); - for(j = 0; j < sendCount; ++j) { - pkt = sendQueueV4.remove(0); - sendBuffer.writeVarIntToBuffer(pkt.readableBytes()); - sendBuffer.writeBytes(pkt); - } - sendFunction.sendPluginMessage(GamePluginMessageConstants.V4_CHANNEL, sendBuffer); - } - } - } - } - public static GameMessageHandler createClientHandler(int protocolVersion, NetHandlerPlayClient netHandler) { - switch(protocolVersion) { + switch (protocolVersion) { case 2: case 3: return new ClientV3MessageHandler(netHandler); @@ -186,7 +52,7 @@ public class GameProtocolMessageController { } public static GameMessageHandler createServerHandler(int protocolVersion, NetHandlerPlayServer netHandler) { - switch(protocolVersion) { + switch (protocolVersion) { case 2: case 3: return new ServerV3MessageHandler(netHandler); @@ -196,4 +62,145 @@ public class GameProtocolMessageController { throw new IllegalArgumentException("Unknown protocol verison: " + protocolVersion); } } + + public final GamePluginMessageProtocol protocol; + public final int sendDirection; + public final int receiveDirection; + private final PacketBufferInputWrapper inputStream = new PacketBufferInputWrapper(null); + private final PacketBufferOutputWrapper outputStream = new PacketBufferOutputWrapper(null); + private final GameMessageHandler handler; + private final IPluginMessageSendFunction sendFunction; + + private final List sendQueueV4; + + private final boolean noDelay; + + public GameProtocolMessageController(GamePluginMessageProtocol protocol, int sendDirection, + GameMessageHandler handler, IPluginMessageSendFunction sendCallback) { + this.protocol = protocol; + this.sendDirection = sendDirection; + this.receiveDirection = GamePluginMessageConstants.oppositeDirection(sendDirection); + this.handler = handler; + this.sendFunction = sendCallback; + this.noDelay = protocol.ver < 4 || EagRuntime.getConfiguration().isEaglerNoDelay(); + this.sendQueueV4 = !noDelay ? new LinkedList<>() : null; + } + + public void flush() { + if (sendQueueV4 != null) { + int queueLen = sendQueueV4.size(); + PacketBuffer pkt; + if (queueLen == 0) { + return; + } else if (queueLen == 1) { + pkt = sendQueueV4.remove(0); + sendFunction.sendPluginMessage(GamePluginMessageConstants.V4_CHANNEL, pkt); + } else { + int i, j, sendCount = 0, totalLen = 0; + PacketBuffer sendBuffer; + while (sendQueueV4.size() > 0) { + do { + i = sendQueueV4.get(sendCount++).readableBytes(); + totalLen += GamePacketOutputBuffer.getVarIntSize(i) + i; + } while (totalLen < 32760 && sendCount < sendQueueV4.size()); + if (totalLen >= 32760) { + --sendCount; + } + if (sendCount <= 1) { + pkt = sendQueueV4.remove(0); + sendFunction.sendPluginMessage(GamePluginMessageConstants.V4_CHANNEL, pkt); + continue; + } + sendBuffer = new PacketBuffer( + Unpooled.buffer(1 + totalLen + GamePacketOutputBuffer.getVarIntSize(sendCount))); + sendBuffer.writeByte(0xFF); + sendBuffer.writeVarIntToBuffer(sendCount); + for (j = 0; j < sendCount; ++j) { + pkt = sendQueueV4.remove(0); + sendBuffer.writeVarIntToBuffer(pkt.readableBytes()); + sendBuffer.writeBytes(pkt); + } + sendFunction.sendPluginMessage(GamePluginMessageConstants.V4_CHANNEL, sendBuffer); + } + } + } + } + + public boolean handlePacket(String channel, PacketBuffer data) throws IOException { + GameMessagePacket pkt; + if (protocol.ver >= 4 && data.readableBytes() > 0 && data.getByte(data.readerIndex()) == (byte) 0xFF + && channel.equals(GamePluginMessageConstants.V4_CHANNEL)) { + data.readByte(); + inputStream.buffer = data; + int count = inputStream.readVarInt(); + for (int i = 0, j, k; i < count; ++i) { + j = data.readVarIntFromBuffer(); + k = data.readerIndex() + j; + if (j > data.readableBytes()) { + throw new IOException("Packet fragment is too long: " + j + " > " + data.readableBytes()); + } + pkt = protocol.readPacket(channel, receiveDirection, inputStream); + if (pkt != null) { + try { + pkt.handlePacket(handler); + } catch (Throwable t) { + logger.error("Failed to handle packet {} in direction {} using handler {}!", + pkt.getClass().getSimpleName(), + GamePluginMessageConstants.getDirectionString(receiveDirection), handler); + logger.error(t); + } + } else { + logger.warn("Could not read packet fragment {} of {}, unknown packet", count, i); + } + if (data.readerIndex() != k) { + logger.warn("Packet fragment {} was the wrong length: {} != {}", + (pkt != null ? pkt.getClass().getSimpleName() : "unknown"), j + data.readerIndex() - k, j); + data.readerIndex(k); + } + } + if (data.readableBytes() > 0) { + logger.warn("Leftover data after reading multi-packet! ({} bytes)", data.readableBytes()); + } + inputStream.buffer = null; + return true; + } + inputStream.buffer = data; + pkt = protocol.readPacket(channel, receiveDirection, inputStream); + if (pkt != null && inputStream.available() > 0) { + logger.warn("Leftover data after reading packet {}! ({} bytes)", pkt.getClass().getSimpleName(), + inputStream.available()); + } + inputStream.buffer = null; + if (pkt != null) { + try { + pkt.handlePacket(handler); + } catch (Throwable t) { + logger.error("Failed to handle packet {} in direction {} using handler {}!", + pkt.getClass().getSimpleName(), GamePluginMessageConstants.getDirectionString(receiveDirection), + handler); + logger.error(t); + } + return true; + } else { + return false; + } + } + + public void sendPacket(GameMessagePacket packet) throws IOException { + int len = packet.length() + 1; + PacketBuffer buf = new PacketBuffer(len != 0 ? Unpooled.buffer(len) : Unpooled.buffer(64)); + outputStream.buffer = buf; + String chan = protocol.writePacket(sendDirection, outputStream, packet); + outputStream.buffer = null; + int j = buf.writerIndex(); + if (len != 0 && j != len && j + 1 != len) { + logger.warn("Packet {} was expected to be {} bytes but was serialized to {} bytes!", + packet.getClass().getSimpleName(), len, j); + } + if (sendQueueV4 != null && chan.equals(GamePluginMessageConstants.V4_CHANNEL)) { + sendQueueV4.add(buf); + } else { + sendFunction.sendPluginMessage(chan, buf); + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/IPluginMessageSendFunction.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/IPluginMessageSendFunction.java index e4fbbf7b..c5204ae2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/IPluginMessageSendFunction.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/IPluginMessageSendFunction.java @@ -5,14 +5,15 @@ import net.minecraft.network.PacketBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferInputWrapper.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferInputWrapper.java index 1566bb7e..d914ac02 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferInputWrapper.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferInputWrapper.java @@ -12,14 +12,15 @@ import net.minecraft.network.PacketBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,47 +33,20 @@ public class PacketBufferInputWrapper implements GamePacketInputBuffer { this.buffer = buffer; } + @Override + public int available() throws IOException { + return buffer.readableBytes(); + } + public PacketBuffer getBuffer() { return buffer; } - public void setBuffer(PacketBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void readFully(byte[] b) throws IOException { - try { - buffer.readBytes(b); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public void readFully(byte[] b, int off, int len) throws IOException { - try { - buffer.readBytes(b, off, len); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public int skipBytes(int n) throws IOException { - int r = buffer.readableBytes(); - if(n > r) { - n = r; - } - buffer.readerIndex(buffer.readerIndex() + n); - return n; - } - @Override public boolean readBoolean() throws IOException { try { return buffer.readBoolean(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } @@ -81,34 +55,16 @@ public class PacketBufferInputWrapper implements GamePacketInputBuffer { public byte readByte() throws IOException { try { return buffer.readByte(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } @Override - public int readUnsignedByte() throws IOException { + public byte[] readByteArrayMC() throws IOException { try { - return buffer.readUnsignedByte(); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public short readShort() throws IOException { - try { - return buffer.readShort(); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public int readUnsignedShort() throws IOException { - try { - return buffer.readUnsignedShort(); - }catch(IndexOutOfBoundsException ex) { + return buffer.readByteArray(); + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } @@ -117,34 +73,7 @@ public class PacketBufferInputWrapper implements GamePacketInputBuffer { public char readChar() throws IOException { try { return buffer.readChar(); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public int readInt() throws IOException { - try { - return buffer.readInt(); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public long readLong() throws IOException { - try { - return buffer.readLong(); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public float readFloat() throws IOException { - try { - return buffer.readFloat(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } @@ -153,7 +82,43 @@ public class PacketBufferInputWrapper implements GamePacketInputBuffer { public double readDouble() throws IOException { try { return buffer.readDouble(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public float readFloat() throws IOException { + try { + return buffer.readFloat(); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public void readFully(byte[] b) throws IOException { + try { + buffer.readBytes(b); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public void readFully(byte[] b, int off, int len) throws IOException { + try { + buffer.readBytes(b, off, len); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public int readInt() throws IOException { + try { + return buffer.readInt(); + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } @@ -164,23 +129,82 @@ public class PacketBufferInputWrapper implements GamePacketInputBuffer { } @Override - public String readUTF() throws IOException { - return DataInputStream.readUTF(this); + public long readLong() throws IOException { + try { + return buffer.readLong(); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } } @Override - public void skipAllBytes(int n) throws IOException { - if(buffer.readableBytes() < n) { + public short readShort() throws IOException { + try { + return buffer.readShort(); + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } - buffer.readerIndex(buffer.readerIndex() + n); + } + + @Override + public String readStringEaglerASCII16() throws IOException { + int len = readUnsignedShort(); + char[] ret = new char[len]; + for (int i = 0; i < len; ++i) { + ret[i] = (char) readByte(); + } + return new String(ret); + } + + @Override + public String readStringEaglerASCII8() throws IOException { + int len = readUnsignedByte(); + char[] ret = new char[len]; + for (int i = 0; i < len; ++i) { + ret[i] = (char) readByte(); + } + return new String(ret); + } + + @Override + public String readStringMC(int maxLen) throws IOException { + try { + return buffer.readStringFromBuffer(maxLen); + } catch (DecoderException ex) { + throw new IOException(ex.getMessage()); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public int readUnsignedByte() throws IOException { + try { + return buffer.readUnsignedByte(); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public int readUnsignedShort() throws IOException { + try { + return buffer.readUnsignedShort(); + } catch (IndexOutOfBoundsException ex) { + throw new EOFException(); + } + } + + @Override + public String readUTF() throws IOException { + return DataInputStream.readUTF(this); } @Override public int readVarInt() throws IOException { try { return buffer.readVarIntFromBuffer(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } @@ -189,107 +213,85 @@ public class PacketBufferInputWrapper implements GamePacketInputBuffer { public long readVarLong() throws IOException { try { return buffer.readVarLong(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } + public void setBuffer(PacketBuffer buffer) { + this.buffer = buffer; + } + @Override - public String readStringMC(int maxLen) throws IOException { - try { - return buffer.readStringFromBuffer(maxLen); - }catch(DecoderException ex) { - throw new IOException(ex.getMessage()); - }catch(IndexOutOfBoundsException ex) { + public void skipAllBytes(int n) throws IOException { + if (buffer.readableBytes() < n) { throw new EOFException(); } + buffer.readerIndex(buffer.readerIndex() + n); } @Override - public String readStringEaglerASCII8() throws IOException { - int len = readUnsignedByte(); - char[] ret = new char[len]; - for(int i = 0; i < len; ++i) { - ret[i] = (char)readByte(); + public int skipBytes(int n) throws IOException { + int r = buffer.readableBytes(); + if (n > r) { + n = r; } - return new String(ret); - } - - @Override - public String readStringEaglerASCII16() throws IOException { - int len = readUnsignedShort(); - char[] ret = new char[len]; - for(int i = 0; i < len; ++i) { - ret[i] = (char)readByte(); - } - return new String(ret); - } - - @Override - public byte[] readByteArrayMC() throws IOException { - try { - return buffer.readByteArray(); - }catch(IndexOutOfBoundsException ex) { - throw new EOFException(); - } - } - - @Override - public int available() throws IOException { - return buffer.readableBytes(); + buffer.readerIndex(buffer.readerIndex() + n); + return n; } @Override public InputStream stream() { return new InputStream() { - @Override - public int read() throws IOException { - if(buffer.readableBytes() > 0) { - return buffer.readUnsignedShort(); - }else { - return -1; - } - } - - @Override - public int read(byte b[], int off, int len) throws IOException { - int avail = buffer.readableBytes(); - if(avail == 0) return -1; - len = avail > len ? avail : len; - buffer.readBytes(b, off, len); - return len; - } - - @Override - public long skip(long n) throws IOException { - return PacketBufferInputWrapper.this.skipBytes((int)n); - } - @Override public int available() throws IOException { return buffer.readableBytes(); } - @Override - public boolean markSupported() { - return true; - } - @Override public synchronized void mark(int readlimit) { buffer.markReaderIndex(); } @Override - public synchronized void reset() throws IOException { + public boolean markSupported() { + return true; + } + + @Override + public int read() throws IOException { + if (buffer.readableBytes() > 0) { + return buffer.readUnsignedShort(); + } else { + return -1; + } + } + + @Override + public int read(byte b[], int off, int len) throws IOException { + int avail = buffer.readableBytes(); + if (avail == 0) + return -1; + len = avail > len ? avail : len; + buffer.readBytes(b, off, len); + return len; + } + + @Override + public synchronized void reset() throws IOException { try { buffer.resetReaderIndex(); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new EOFException(); } } + @Override + public long skip(long n) throws IOException { + return PacketBufferInputWrapper.this.skipBytes((int) n); + } + }; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferOutputWrapper.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferOutputWrapper.java index 67e17cc0..23567178 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferOutputWrapper.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/client/PacketBufferOutputWrapper.java @@ -9,175 +9,21 @@ import net.minecraft.network.PacketBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PacketBufferOutputWrapper implements GamePacketOutputBuffer { - protected PacketBuffer buffer; - - public PacketBufferOutputWrapper(PacketBuffer buffer) { - this.buffer = buffer; - } - - public PacketBuffer getBuffer() { - return buffer; - } - - public void setBuffer(PacketBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void write(int b) throws IOException { - try { - buffer.writeByte(b); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void write(byte[] b) throws IOException { - try { - buffer.writeBytes(b); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void write(byte[] b, int off, int len) throws IOException { - try { - buffer.writeBytes(b, off, len); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeBoolean(boolean v) throws IOException { - try { - buffer.writeBoolean(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeByte(int v) throws IOException { - try { - buffer.writeByte(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeShort(int v) throws IOException { - try { - buffer.writeShort(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeChar(int v) throws IOException { - try { - buffer.writeChar(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeInt(int v) throws IOException { - try { - buffer.writeInt(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeLong(long v) throws IOException { - try { - buffer.writeLong(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeFloat(float v) throws IOException { - try { - buffer.writeFloat(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeDouble(double v) throws IOException { - try { - buffer.writeDouble(v); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeBytes(String s) throws IOException { - try { - int l = s.length(); - for(int i = 0; i < l; ++i) { - buffer.writeByte((int)s.charAt(i)); - } - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeChars(String s) throws IOException { - try { - int l = s.length(); - for(int i = 0; i < l; ++i) { - buffer.writeChar(s.charAt(i)); - } - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public final void writeUTF(String str) throws IOException { - long utfCount = countUTFBytes(str); - if (utfCount > 65535) { - throw new IOException("String is longer than 65535 bytes when encoded as UTF8!"); - } - byte[] arr = new byte[(int) utfCount + 2]; - int offset = 2; - arr[0] = (byte)(((int)utfCount >>> 8) & 0xFF); - arr[1] = (byte)((int)utfCount & 0xFF); - offset = writeUTFBytesToBuffer(str, arr, offset); - try { - buffer.writeBytes(arr, 0, offset); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - private static long countUTFBytes(String str) { int utfCount = 0; int length = str.length(); @@ -212,69 +58,86 @@ public class PacketBufferOutputWrapper implements GamePacketOutputBuffer { return offset; } - @Override - public void writeVarInt(int i) throws IOException { - try { - buffer.writeVarIntToBuffer(i); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } + protected PacketBuffer buffer; + + public PacketBufferOutputWrapper(PacketBuffer buffer) { + this.buffer = buffer; + } + + public PacketBuffer getBuffer() { + return buffer; + } + + public void setBuffer(PacketBuffer buffer) { + this.buffer = buffer; } @Override - public void writeVarLong(long i) throws IOException { - try { - buffer.writeVarLong(i); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } + public OutputStream stream() { + return new OutputStream() { - @Override - public void writeStringMC(String str) throws IOException { - try { - buffer.writeString(str); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } - } - - @Override - public void writeStringEaglerASCII8(String str) throws IOException { - int len = str.length(); - if(len > 255) { - throw new IOException("String is longer than 255 chars! (" + len + ")"); - } - try { - buffer.writeByte(len); - for(int i = 0, j; i < len; ++i) { - j = (int)str.charAt(i); - if(j > 255) { - j = (int)'?'; + @Override + public void write(byte b[], int off, int len) throws IOException { + try { + buffer.writeBytes(b, off, len); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); } - buffer.writeByte(j); } - }catch(IndexOutOfBoundsException ex) { + + @Override + public void write(int b) throws IOException { + try { + buffer.writeByte(b); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + }; + } + + @Override + public void write(byte[] b) throws IOException { + try { + buffer.writeBytes(b); + } catch (IndexOutOfBoundsException ex) { throw new IOException("Packet buffer overflowed!"); } } @Override - public void writeStringEaglerASCII16(String str) throws IOException { - int len = str.length(); - if(len > 65535) { - throw new IOException("String is longer than 65535 chars! (" + len + ")"); - } + public void write(byte[] b, int off, int len) throws IOException { try { - buffer.writeShort(len); - for(int i = 0, j; i < len; ++i) { - j = (int)str.charAt(i); - if(j > 255) { - j = (int)'?'; - } - buffer.writeByte(j); - } - }catch(IndexOutOfBoundsException ex) { + buffer.writeBytes(b, off, len); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void write(int b) throws IOException { + try { + buffer.writeByte(b); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeBoolean(boolean v) throws IOException { + try { + buffer.writeBoolean(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeByte(int v) throws IOException { + try { + buffer.writeByte(v); + } catch (IndexOutOfBoundsException ex) { throw new IOException("Packet buffer overflowed!"); } } @@ -283,34 +146,172 @@ public class PacketBufferOutputWrapper implements GamePacketOutputBuffer { public void writeByteArrayMC(byte[] bytes) throws IOException { try { buffer.writeByteArray(bytes); - }catch(IndexOutOfBoundsException ex) { + } catch (IndexOutOfBoundsException ex) { throw new IOException("Packet buffer overflowed!"); } } @Override - public OutputStream stream() { - return new OutputStream() { - - @Override - public void write(int b) throws IOException { - try { - buffer.writeByte(b); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } + public void writeBytes(String s) throws IOException { + try { + int l = s.length(); + for (int i = 0; i < l; ++i) { + buffer.writeByte((int) s.charAt(i)); } + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } - @Override - public void write(byte b[], int off, int len) throws IOException { - try { - buffer.writeBytes(b, off, len); - }catch(IndexOutOfBoundsException ex) { - throw new IOException("Packet buffer overflowed!"); - } + @Override + public void writeChar(int v) throws IOException { + try { + buffer.writeChar(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeChars(String s) throws IOException { + try { + int l = s.length(); + for (int i = 0; i < l; ++i) { + buffer.writeChar(s.charAt(i)); } + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } - }; + @Override + public void writeDouble(double v) throws IOException { + try { + buffer.writeDouble(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeFloat(float v) throws IOException { + try { + buffer.writeFloat(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeInt(int v) throws IOException { + try { + buffer.writeInt(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeLong(long v) throws IOException { + try { + buffer.writeLong(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeShort(int v) throws IOException { + try { + buffer.writeShort(v); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeStringEaglerASCII16(String str) throws IOException { + int len = str.length(); + if (len > 65535) { + throw new IOException("String is longer than 65535 chars! (" + len + ")"); + } + try { + buffer.writeShort(len); + for (int i = 0, j; i < len; ++i) { + j = (int) str.charAt(i); + if (j > 255) { + j = (int) '?'; + } + buffer.writeByte(j); + } + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeStringEaglerASCII8(String str) throws IOException { + int len = str.length(); + if (len > 255) { + throw new IOException("String is longer than 255 chars! (" + len + ")"); + } + try { + buffer.writeByte(len); + for (int i = 0, j; i < len; ++i) { + j = (int) str.charAt(i); + if (j > 255) { + j = (int) '?'; + } + buffer.writeByte(j); + } + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeStringMC(String str) throws IOException { + try { + buffer.writeString(str); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public final void writeUTF(String str) throws IOException { + long utfCount = countUTFBytes(str); + if (utfCount > 65535) { + throw new IOException("String is longer than 65535 bytes when encoded as UTF8!"); + } + byte[] arr = new byte[(int) utfCount + 2]; + int offset = 2; + arr[0] = (byte) (((int) utfCount >>> 8) & 0xFF); + arr[1] = (byte) ((int) utfCount & 0xFF); + offset = writeUTFBytesToBuffer(str, arr, offset); + try { + buffer.writeBytes(arr, 0, offset); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeVarInt(int i) throws IOException { + try { + buffer.writeVarIntToBuffer(i); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } + } + + @Override + public void writeVarLong(long i) throws IOException { + try { + buffer.writeVarLong(i); + } catch (IndexOutOfBoundsException ex) { + throw new IOException("Packet buffer overflowed!"); + } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/IntegratedServerState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/IntegratedServerState.java index f6444aec..3f6e47af 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/IntegratedServerState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/IntegratedServerState.java @@ -1,18 +1,29 @@ package net.lax1dude.eaglercraft.v1_8.sp; -import net.lax1dude.eaglercraft.v1_8.sp.ipc.*; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket00StartServer; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket01StopServer; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket03DeleteWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket06RenameWorldNBT; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket07ImportWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0BPause; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket12FileWrite; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket13FileCopyMove; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket18ClearPlayers; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket19Autosave; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketFFProcessKeepAlive; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,58 +52,95 @@ public class IntegratedServerState { public static final int WORLD_FILE_MOVE = 18; public static final int WORLD_FILE_COPY = 19; public static final int WORLD_CLEAR_PLAYERS = 20; - - public static String getStateName(int i) { - switch(i) { - case WORLD_WORKER_NOT_RUNNING: return "WORLD_WORKER_NOT_RUNNING"; - case WORLD_WORKER_BOOTING: return "WORLD_WORKER_BOOTING"; - case WORLD_NONE: return "WORLD_NONE"; - case WORLD_LOADING: return "WORLD_LOADING"; - case WORLD_LOADED: return "WORLD_LOADED"; - case WORLD_UNLOADING: return "WORLD_UNLOADING"; - case WORLD_DELETING: return "WORLD_DELETING"; - case WORLD_RENAMING: return "WORLD_RENAMING"; - case WORLD_DUPLICATING: return "WORLD_DUPLICATING"; - case WORLD_PAUSED: return "WORLD_PAUSED"; - case WORLD_LISTING: return "WORLD_LISTING"; - case WORLD_SAVING: return "WORLD_SAVING"; - case WORLD_IMPORTING: return "WORLD_IMPORTING"; - case WORLD_EXPORTING: return "WORLD_EXPORTING"; - case WORLD_GET_NBT: return "WORLD_GET_NBT"; - case WORLD_LIST_FILE: return "WORLD_LIST_FILE"; - case WORLD_FILE_READ: return "WORLD_FILE_READ"; - case WORLD_FILE_WRITE: return "WORLD_FILE_WRITE"; - case WORLD_FILE_MOVE: return "WORLD_FILE_MOVE"; - case WORLD_FILE_COPY: return "WORLD_FILE_COPY"; - case WORLD_CLEAR_PLAYERS: return "WORLD_CLEAR_PLAYERS"; - default: return "INVALID"; - } - } - - public static boolean isACKValidInState(int ack, int state) { - switch(ack) { - case 0xFF: return state == WORLD_WORKER_BOOTING; - case IPCPacketFFProcessKeepAlive.EXITED: return true; - case IPCPacketFFProcessKeepAlive.FAILURE: return true; - case IPCPacket01StopServer.ID: return true; - case IPCPacket00StartServer.ID: return state == WORLD_LOADING; - case IPCPacket03DeleteWorld.ID: return state == WORLD_DELETING; - case IPCPacket06RenameWorldNBT.ID: return (state == WORLD_DUPLICATING || state == WORLD_RENAMING); - case IPCPacket07ImportWorld.ID: return state == WORLD_IMPORTING; - case IPCPacket0BPause.ID: - case IPCPacket19Autosave.ID: return (state == WORLD_SAVING || state == WORLD_PAUSED || state == WORLD_LOADED || state == WORLD_UNLOADING); - case IPCPacket12FileWrite.ID: return state == WORLD_FILE_WRITE; - case IPCPacket13FileCopyMove.ID: return (state == WORLD_FILE_MOVE || state == WORLD_FILE_COPY); - case IPCPacket18ClearPlayers.ID: return state == WORLD_CLEAR_PLAYERS; - default: return false; - } - } - + public static void assertState(int ack, int state) { - if(!isACKValidInState(ack, state)) { - String msg = "Recieved ACK " + ack + " while the client state was " + state + " '" + getStateName(state) + "'"; + if (!isACKValidInState(ack, state)) { + String msg = "Recieved ACK " + ack + " while the client state was " + state + " '" + getStateName(state) + + "'"; throw new IllegalStateException(msg); } } + public static String getStateName(int i) { + switch (i) { + case WORLD_WORKER_NOT_RUNNING: + return "WORLD_WORKER_NOT_RUNNING"; + case WORLD_WORKER_BOOTING: + return "WORLD_WORKER_BOOTING"; + case WORLD_NONE: + return "WORLD_NONE"; + case WORLD_LOADING: + return "WORLD_LOADING"; + case WORLD_LOADED: + return "WORLD_LOADED"; + case WORLD_UNLOADING: + return "WORLD_UNLOADING"; + case WORLD_DELETING: + return "WORLD_DELETING"; + case WORLD_RENAMING: + return "WORLD_RENAMING"; + case WORLD_DUPLICATING: + return "WORLD_DUPLICATING"; + case WORLD_PAUSED: + return "WORLD_PAUSED"; + case WORLD_LISTING: + return "WORLD_LISTING"; + case WORLD_SAVING: + return "WORLD_SAVING"; + case WORLD_IMPORTING: + return "WORLD_IMPORTING"; + case WORLD_EXPORTING: + return "WORLD_EXPORTING"; + case WORLD_GET_NBT: + return "WORLD_GET_NBT"; + case WORLD_LIST_FILE: + return "WORLD_LIST_FILE"; + case WORLD_FILE_READ: + return "WORLD_FILE_READ"; + case WORLD_FILE_WRITE: + return "WORLD_FILE_WRITE"; + case WORLD_FILE_MOVE: + return "WORLD_FILE_MOVE"; + case WORLD_FILE_COPY: + return "WORLD_FILE_COPY"; + case WORLD_CLEAR_PLAYERS: + return "WORLD_CLEAR_PLAYERS"; + default: + return "INVALID"; + } + } + + public static boolean isACKValidInState(int ack, int state) { + switch (ack) { + case 0xFF: + return state == WORLD_WORKER_BOOTING; + case IPCPacketFFProcessKeepAlive.EXITED: + return true; + case IPCPacketFFProcessKeepAlive.FAILURE: + return true; + case IPCPacket01StopServer.ID: + return true; + case IPCPacket00StartServer.ID: + return state == WORLD_LOADING; + case IPCPacket03DeleteWorld.ID: + return state == WORLD_DELETING; + case IPCPacket06RenameWorldNBT.ID: + return (state == WORLD_DUPLICATING || state == WORLD_RENAMING); + case IPCPacket07ImportWorld.ID: + return state == WORLD_IMPORTING; + case IPCPacket0BPause.ID: + case IPCPacket19Autosave.ID: + return (state == WORLD_SAVING || state == WORLD_PAUSED || state == WORLD_LOADED + || state == WORLD_UNLOADING); + case IPCPacket12FileWrite.ID: + return state == WORLD_FILE_WRITE; + case IPCPacket13FileCopyMove.ID: + return (state == WORLD_FILE_MOVE || state == WORLD_FILE_COPY); + case IPCPacket18ClearPlayers.ID: + return state == WORLD_CLEAR_PLAYERS; + default: + return false; + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerSaveHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerSaveHandler.java index ed749286..bdfdfaa6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerSaveHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerSaveHandler.java @@ -6,14 +6,15 @@ import net.minecraft.world.storage.WorldInfo; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerServerController.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerServerController.java index 4f8c30a1..a197bc49 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerServerController.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SingleplayerServerController.java @@ -9,19 +9,44 @@ import java.util.List; import java.util.Map; import java.util.Set; -import net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC; - import org.apache.commons.lang3.StringUtils; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.EnumEaglerConnectionState; import net.lax1dude.eaglercraft.v1_8.internal.IPCPacketData; import net.lax1dude.eaglercraft.v1_8.internal.PlatformApplication; +import net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.profile.EaglerProfile; import net.lax1dude.eaglercraft.v1_8.sp.internal.ClientPlatformSingleplayer; -import net.lax1dude.eaglercraft.v1_8.sp.ipc.*; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket00StartServer; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket01StopServer; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket02InitWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket03DeleteWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket05RequestData; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket06RenameWorldNBT; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket07ImportWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket09RequestResponse; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0ASetWorldDifficulty; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0BPause; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0CPlayerChannel; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0DProgressUpdate; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0EListWorlds; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket12FileWrite; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket13FileCopyMove; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket14StringList; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket15Crashed; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket16NBTList; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket17ConfigureLAN; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket18ClearPlayers; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket19Autosave; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1ALoggerMessage; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1BEnableLogging; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1CIssueDetected; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketBase; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketFFProcessKeepAlive; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketManager; import net.lax1dude.eaglercraft.v1_8.sp.lan.LANServerController; import net.lax1dude.eaglercraft.v1_8.sp.socket.ClientIntegratedServerNetworkManager; import net.minecraft.client.Minecraft; @@ -37,14 +62,15 @@ import net.minecraft.world.storage.WorldInfo; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -70,152 +96,101 @@ public class SingleplayerServerController implements ISaveFormat { private static boolean isPaused = false; private static List integratedServerTPS = new ArrayList<>(); private static long integratedServerLastTPSUpdate = 0; - public static final ClientIntegratedServerNetworkManager localPlayerNetworkManager = new ClientIntegratedServerNetworkManager(PLAYER_CHANNEL); + public static final ClientIntegratedServerNetworkManager localPlayerNetworkManager = new ClientIntegratedServerNetworkManager( + PLAYER_CHANNEL); private static final List openLANChannels = new ArrayList<>(); private static final IPCPacketManager packetManagerInstance = new IPCPacketManager(); - private SingleplayerServerController() { - } + private static boolean callFailed = false; - public static void startIntegratedServerWorker(boolean forceSingleThread) { - if(statusState == IntegratedServerState.WORLD_WORKER_NOT_RUNNING) { - exceptions.clear(); - issuesDetected.clear(); - statusState = IntegratedServerState.WORLD_WORKER_BOOTING; - loggingState = true; - boolean singleThreadSupport = ClientPlatformSingleplayer.isSingleThreadModeSupported(); - if(!singleThreadSupport && forceSingleThread) { - throw new UnsupportedOperationException("Single thread mode is not supported!"); - } - if(forceSingleThread || !singleThreadSupport) { - ClientPlatformSingleplayer.startIntegratedServer(forceSingleThread); - }else { - try { - ClientPlatformSingleplayer.startIntegratedServer(forceSingleThread); - }catch(Throwable t) { - logger.error("Failed to start integrated server worker"); - logger.error(t); - logger.error("Attempting to use single thread mode"); - exceptions.clear(); - issuesDetected.clear(); - statusState = IntegratedServerState.WORLD_WORKER_BOOTING; - loggingState = true; - ClientPlatformSingleplayer.startIntegratedServer(true); - } - } + private static byte[] exportResponse = null; + + public static void autoSave() { + if (!isPaused) { + statusState = IntegratedServerState.WORLD_SAVING; + sendIPCPacket(new IPCPacket19Autosave()); } } - public static boolean isIssueDetected(int issue) { - return issuesDetected.contains(issue); + public static boolean canKillWorker() { + return ClientPlatformSingleplayer.canKillWorker(); } - public static boolean isIntegratedServerWorkerStarted() { - return statusState != IntegratedServerState.WORLD_WORKER_NOT_RUNNING && statusState != IntegratedServerState.WORLD_WORKER_BOOTING; + public static void clearPlayerData(String worldName) { + ensureReady(); + statusState = IntegratedServerState.WORLD_CLEAR_PLAYERS; + sendIPCPacket(new IPCPacket18ClearPlayers(worldName)); } - public static boolean isIntegratedServerWorkerAlive() { - return statusState != IntegratedServerState.WORLD_WORKER_NOT_RUNNING; + public static void clearTPS() { + integratedServerTPS.clear(); + integratedServerLastTPSUpdate = 0l; } - public static boolean isRunningSingleThreadMode() { - return ClientPlatformSingleplayer.isRunningSingleThreadMode(); - } - - public static boolean isReady() { - return statusState == IntegratedServerState.WORLD_NONE; - } - - public static boolean isWorldNotLoaded() { - return statusState == IntegratedServerState.WORLD_NONE || statusState == IntegratedServerState.WORLD_WORKER_NOT_RUNNING || - statusState == IntegratedServerState.WORLD_WORKER_BOOTING; - } - - public static boolean isWorldRunning() { - return statusState == IntegratedServerState.WORLD_LOADED || statusState == IntegratedServerState.WORLD_PAUSED || - statusState == IntegratedServerState.WORLD_LOADING || statusState == IntegratedServerState.WORLD_SAVING; - } - - public static boolean isWorldReady() { - return statusState == IntegratedServerState.WORLD_LOADED || statusState == IntegratedServerState.WORLD_PAUSED || - statusState == IntegratedServerState.WORLD_SAVING; - } - - public static int getStatusState() { - return statusState; - } - - public static boolean isChannelOpen(String ch) { - return openLANChannels.contains(ch); - } - - public static boolean isChannelNameAllowed(String ch) { - return !IPC_CHANNEL.equals(ch) && !PLAYER_CHANNEL.equals(ch); - } - - public static void openPlayerChannel(String ch) { - if(openLANChannels.contains(ch)) { - logger.error("Tried to open channel that already exists: \"{}\"", ch); - } else if (!isChannelNameAllowed(ch)) { - logger.error("Tried to open disallowed channel name: \"{}\"", ch); - }else { - openLANChannels.add(ch); - sendIPCPacket(new IPCPacket0CPlayerChannel(ch, true)); - PlatformWebRTC.serverLANCreatePeer(ch); - } - } - - public static void closePlayerChannel(String ch) { - if(!openLANChannels.remove(ch)) { - logger.error("Tried to close channel that doesn't exist: \"{}\"", ch); - }else { - sendIPCPacket(new IPCPacket0CPlayerChannel(ch, false)); - PlatformWebRTC.serverLANDisconnectPeer(ch); - } - } - - public static void openLocalPlayerChannel() { - localPlayerNetworkManager.isPlayerChannelOpen = true; - sendIPCPacket(new IPCPacket0CPlayerChannel(PLAYER_CHANNEL, true)); - } - public static void closeLocalPlayerChannel() { localPlayerNetworkManager.isPlayerChannelOpen = false; sendIPCPacket(new IPCPacket0CPlayerChannel(PLAYER_CHANNEL, false)); } - + + public static void closePlayerChannel(String ch) { + if (!openLANChannels.remove(ch)) { + logger.error("Tried to close channel that doesn't exist: \"{}\"", ch); + } else { + sendIPCPacket(new IPCPacket0CPlayerChannel(ch, false)); + PlatformWebRTC.serverLANDisconnectPeer(ch); + } + } + + public static void configureLAN(net.minecraft.world.WorldSettings.GameType enumGameType, boolean allowCommands) { + sendIPCPacket(new IPCPacket17ConfigureLAN(enumGameType.getID(), allowCommands, + LANServerController.currentICEServers)); + } + + public static boolean didLastCallFail() { + boolean c = callFailed; + callFailed = false; + return c; + } + + public static void duplicateWorld(String var1, String var2) { + sendIPCPacket(new IPCPacket06RenameWorldNBT(var1, var2, true)); + statusState = IntegratedServerState.WORLD_DUPLICATING; + } + private static void ensureReady() { - if(!isReady()) { - String msg = "Server is in state " + statusState + " '" + IntegratedServerState.getStateName(statusState) + "' which is not the 'WORLD_NONE' state for the requested IPC operation"; + if (!isReady()) { + String msg = "Server is in state " + statusState + " '" + IntegratedServerState.getStateName(statusState) + + "' which is not the 'WORLD_NONE' state for the requested IPC operation"; throw new IllegalStateException(msg); } } - + private static void ensureWorldReady() { - if(!isWorldReady()) { - String msg = "Server is in state " + statusState + " '" + IntegratedServerState.getStateName(statusState) + "' which is not the 'WORLD_LOADED' state for the requested IPC operation"; + if (!isWorldReady()) { + String msg = "Server is in state " + statusState + " '" + IntegratedServerState.getStateName(statusState) + + "' which is not the 'WORLD_LOADED' state for the requested IPC operation"; throw new IllegalStateException(msg); } } - public static void launchEaglercraftServer(String folderName, int difficulty, int viewDistance, WorldSettings settings) { + public static void exportWorld(String name, int format) { ensureReady(); - clearTPS(); - if(settings != null) { - sendIPCPacket(new IPCPacket02InitWorld(folderName, settings.getGameType().getID(), - settings.getTerrainType().getWorldTypeID(), settings.getWorldName(), settings.getSeed(), - settings.areCommandsAllowed(), settings.isMapFeaturesEnabled(), settings.isBonusChestEnabled(), - settings.getHardcoreEnabled())); + statusState = IntegratedServerState.WORLD_EXPORTING; + if (format == IPCPacket05RequestData.REQUEST_LEVEL_EAG) { + name = name + (new String(new char[] { (char) 253, (char) 233, (char) 233 })) + EaglerProfile.getName(); } - statusState = IntegratedServerState.WORLD_LOADING; - worldStatusProgress = 0.0f; - sendIPCPacket(new IPCPacket00StartServer(folderName, EaglerProfile.getName(), difficulty, viewDistance, EagRuntime.getConfiguration().isDemo())); + sendIPCPacket(new IPCPacket05RequestData(name, (byte) format)); } - public static void clearTPS() { - integratedServerTPS.clear(); - integratedServerLastTPSUpdate = 0l; + public static byte[] getExportResponse() { + byte[] dat = exportResponse; + exportResponse = null; + return dat; + } + + public static int getStatusState() { + return statusState; } public static List getTPS() { @@ -226,209 +201,135 @@ public class SingleplayerServerController implements ISaveFormat { return EagRuntime.steadyTimeMillis() - integratedServerLastTPSUpdate; } - public static boolean hangupEaglercraftServer() { - LANServerController.closeLAN(); - if(isWorldRunning()) { - logger.error("Shutting down integrated server due to unexpected client hangup, this is a memleak"); - statusState = IntegratedServerState.WORLD_UNLOADING; - sendIPCPacket(new IPCPacket01StopServer()); - return true; - }else { - return false; - } - } - - public static boolean shutdownEaglercraftServer() { - LANServerController.closeLAN(); - if(isWorldRunning()) { - logger.info("Shutting down integrated server"); - statusState = IntegratedServerState.WORLD_UNLOADING; - sendIPCPacket(new IPCPacket01StopServer()); - return true; - }else { - return false; - } - } - - public static void autoSave() { - if(!isPaused) { - statusState = IntegratedServerState.WORLD_SAVING; - sendIPCPacket(new IPCPacket19Autosave()); - } - } - - public static void setPaused(boolean pause) { - if(statusState != IntegratedServerState.WORLD_LOADED && statusState != IntegratedServerState.WORLD_PAUSED && statusState != IntegratedServerState.WORLD_SAVING) { - return; - } - if(isPaused != pause) { - sendIPCPacket(new IPCPacket0BPause(pause)); - isPaused = pause; - } - } - - public static void runTick() { - List pktList = ClientPlatformSingleplayer.recieveAllPacket(); - if(pktList != null) { - IPCPacketData packetData; - for(int i = 0, l = pktList.size(); i < l; ++i) { - packetData = pktList.get(i); - if(packetData.channel.equals(SingleplayerServerController.IPC_CHANNEL)) { - IPCPacketBase ipc; - try { - ipc = packetManagerInstance.IPCDeserialize(packetData.contents); - }catch(IOException ex) { - throw new RuntimeException("Failed to deserialize IPC packet", ex); - } - handleIPCPacket(ipc); - }else if(packetData.channel.equals(SingleplayerServerController.PLAYER_CHANNEL)) { - if(localPlayerNetworkManager.getConnectStatus() != EnumEaglerConnectionState.CLOSED) { - localPlayerNetworkManager.addRecievedPacket(packetData.contents); - }else { - logger.warn("Recieved {} byte packet on closed local player connection", packetData.contents.length); - } - }else { - PlatformWebRTC.serverLANWritePacket(packetData.channel, packetData.contents); - } - } - } - - boolean logWindowState = PlatformApplication.isShowingDebugConsole(); - if(loggingState != logWindowState) { - loggingState = logWindowState; - sendIPCPacket(new IPCPacket1BEnableLogging(logWindowState)); - } - - if(ClientPlatformSingleplayer.isRunningSingleThreadMode()) { - ClientPlatformSingleplayer.updateSingleThreadMode(); - } - - LANServerController.updateLANServer(); - } - private static void handleIPCPacket(IPCPacketBase ipc) { - switch(ipc.id()) { + switch (ipc.id()) { case IPCPacketFFProcessKeepAlive.ID: { - IPCPacketFFProcessKeepAlive pkt = (IPCPacketFFProcessKeepAlive)ipc; + IPCPacketFFProcessKeepAlive pkt = (IPCPacketFFProcessKeepAlive) ipc; IntegratedServerState.assertState(pkt.ack, statusState); - switch(pkt.ack) { - case 0xFF: - logger.info("Integrated server signaled a successful boot"); - sendIPCPacket(new IPCPacket14StringList(IPCPacket14StringList.LOCALE, StringTranslate.dump())); - statusState = IntegratedServerState.WORLD_NONE; - break; - case IPCPacket00StartServer.ID: - statusState = IntegratedServerState.WORLD_LOADED; - isPaused = false; - break; - case IPCPacket0BPause.ID: - case IPCPacket19Autosave.ID: - if(statusState != IntegratedServerState.WORLD_UNLOADING) { - statusState = isPaused ? IntegratedServerState.WORLD_PAUSED : IntegratedServerState.WORLD_LOADED; - } - break; - case IPCPacketFFProcessKeepAlive.FAILURE: - logger.error("Server signaled 'FAILURE' response in state '{}'", IntegratedServerState.getStateName(statusState)); - statusState = IntegratedServerState.WORLD_NONE; - callFailed = true; - break; - case IPCPacket01StopServer.ID: - LANServerController.closeLAN(); - localPlayerNetworkManager.isPlayerChannelOpen = false; - statusState = IntegratedServerState.WORLD_NONE; - break; - case IPCPacket06RenameWorldNBT.ID: - statusState = IntegratedServerState.WORLD_NONE; - break; - case IPCPacket03DeleteWorld.ID: - case IPCPacket07ImportWorld.ID: - case IPCPacket12FileWrite.ID: - case IPCPacket13FileCopyMove.ID: - case IPCPacket18ClearPlayers.ID: - statusState = IntegratedServerState.WORLD_NONE; - break; - case IPCPacketFFProcessKeepAlive.EXITED: - logger.error("Server signaled 'EXITED' response in state '{}'", IntegratedServerState.getStateName(statusState)); - if(ClientPlatformSingleplayer.canKillWorker()) { - ClientPlatformSingleplayer.killWorker(); - } - LANServerController.closeLAN(); - localPlayerNetworkManager.isPlayerChannelOpen = false; - statusState = IntegratedServerState.WORLD_WORKER_NOT_RUNNING; - callFailed = true; - break; - default: - logger.error("IPC acknowledge packet type 0x{} was not handled", Integer.toHexString(pkt.ack)); - break; + switch (pkt.ack) { + case 0xFF: + logger.info("Integrated server signaled a successful boot"); + sendIPCPacket(new IPCPacket14StringList(IPCPacket14StringList.LOCALE, StringTranslate.dump())); + statusState = IntegratedServerState.WORLD_NONE; + break; + case IPCPacket00StartServer.ID: + statusState = IntegratedServerState.WORLD_LOADED; + isPaused = false; + break; + case IPCPacket0BPause.ID: + case IPCPacket19Autosave.ID: + if (statusState != IntegratedServerState.WORLD_UNLOADING) { + statusState = isPaused ? IntegratedServerState.WORLD_PAUSED : IntegratedServerState.WORLD_LOADED; + } + break; + case IPCPacketFFProcessKeepAlive.FAILURE: + logger.error("Server signaled 'FAILURE' response in state '{}'", + IntegratedServerState.getStateName(statusState)); + statusState = IntegratedServerState.WORLD_NONE; + callFailed = true; + break; + case IPCPacket01StopServer.ID: + LANServerController.closeLAN(); + localPlayerNetworkManager.isPlayerChannelOpen = false; + statusState = IntegratedServerState.WORLD_NONE; + break; + case IPCPacket06RenameWorldNBT.ID: + statusState = IntegratedServerState.WORLD_NONE; + break; + case IPCPacket03DeleteWorld.ID: + case IPCPacket07ImportWorld.ID: + case IPCPacket12FileWrite.ID: + case IPCPacket13FileCopyMove.ID: + case IPCPacket18ClearPlayers.ID: + statusState = IntegratedServerState.WORLD_NONE; + break; + case IPCPacketFFProcessKeepAlive.EXITED: + logger.error("Server signaled 'EXITED' response in state '{}'", + IntegratedServerState.getStateName(statusState)); + if (ClientPlatformSingleplayer.canKillWorker()) { + ClientPlatformSingleplayer.killWorker(); + } + LANServerController.closeLAN(); + localPlayerNetworkManager.isPlayerChannelOpen = false; + statusState = IntegratedServerState.WORLD_WORKER_NOT_RUNNING; + callFailed = true; + break; + default: + logger.error("IPC acknowledge packet type 0x{} was not handled", Integer.toHexString(pkt.ack)); + break; } break; } case IPCPacket09RequestResponse.ID: { - IPCPacket09RequestResponse pkt = (IPCPacket09RequestResponse)ipc; - if(statusState == IntegratedServerState.WORLD_EXPORTING) { + IPCPacket09RequestResponse pkt = (IPCPacket09RequestResponse) ipc; + if (statusState == IntegratedServerState.WORLD_EXPORTING) { statusState = IntegratedServerState.WORLD_NONE; exportResponse = pkt.response; - }else { - logger.error("IPCPacket09RequestResponse was recieved but statusState was '{}' instead of 'WORLD_EXPORTING'", IntegratedServerState.getStateName(statusState)); + } else { + logger.error( + "IPCPacket09RequestResponse was recieved but statusState was '{}' instead of 'WORLD_EXPORTING'", + IntegratedServerState.getStateName(statusState)); } break; } case IPCPacket0DProgressUpdate.ID: { - IPCPacket0DProgressUpdate pkt = (IPCPacket0DProgressUpdate)ipc; + IPCPacket0DProgressUpdate pkt = (IPCPacket0DProgressUpdate) ipc; worldStatusString = pkt.updateMessage; worldStatusProgress = pkt.updateProgress; break; } case IPCPacket15Crashed.ID: { - exceptions.add((IPCPacket15Crashed)ipc); - if(exceptions.size() > 64) { + exceptions.add((IPCPacket15Crashed) ipc); + if (exceptions.size() > 64) { exceptions.remove(0); } break; } case IPCPacket16NBTList.ID: { - IPCPacket16NBTList pkt = (IPCPacket16NBTList)ipc; - if(pkt.opCode == IPCPacket16NBTList.WORLD_LIST && statusState == IntegratedServerState.WORLD_LISTING) { + IPCPacket16NBTList pkt = (IPCPacket16NBTList) ipc; + if (pkt.opCode == IPCPacket16NBTList.WORLD_LIST && statusState == IntegratedServerState.WORLD_LISTING) { statusState = IntegratedServerState.WORLD_NONE; saveListNBT.clear(); saveListNBT.addAll(pkt.nbtTagList); loadSaveComparators(); - }else { - logger.error("IPC packet type 0x{} class '{}' contained invalid opCode {} in state {} '{}'", Integer.toHexString(ipc.id()), ipc.getClass().getSimpleName(), pkt.opCode, statusState, IntegratedServerState.getStateName(statusState)); + } else { + logger.error("IPC packet type 0x{} class '{}' contained invalid opCode {} in state {} '{}'", + Integer.toHexString(ipc.id()), ipc.getClass().getSimpleName(), pkt.opCode, statusState, + IntegratedServerState.getStateName(statusState)); } break; } case IPCPacket0CPlayerChannel.ID: { - IPCPacket0CPlayerChannel pkt = (IPCPacket0CPlayerChannel)ipc; - if(!pkt.open) { - if(pkt.channel.equals(PLAYER_CHANNEL)) { + IPCPacket0CPlayerChannel pkt = (IPCPacket0CPlayerChannel) ipc; + if (!pkt.open) { + if (pkt.channel.equals(PLAYER_CHANNEL)) { LANServerController.closeLAN(); localPlayerNetworkManager.isPlayerChannelOpen = false; logger.error("Local player channel was closed"); - }else { + } else { PlatformWebRTC.serverLANDisconnectPeer(pkt.channel); } } break; } case IPCPacket14StringList.ID: { - IPCPacket14StringList pkt = (IPCPacket14StringList)ipc; - if(pkt.opCode == IPCPacket14StringList.SERVER_TPS) { + IPCPacket14StringList pkt = (IPCPacket14StringList) ipc; + if (pkt.opCode == IPCPacket14StringList.SERVER_TPS) { integratedServerTPS.clear(); integratedServerTPS.addAll(pkt.stringList); integratedServerLastTPSUpdate = EagRuntime.steadyTimeMillis(); - }else { + } else { logger.warn("Strange string list type {} recieved!", pkt.opCode); } break; } case IPCPacket1ALoggerMessage.ID: { - IPCPacket1ALoggerMessage pkt = (IPCPacket1ALoggerMessage)ipc; + IPCPacket1ALoggerMessage pkt = (IPCPacket1ALoggerMessage) ipc; PlatformApplication.addLogMessage(pkt.logMessage, pkt.isError); break; } case IPCPacket1CIssueDetected.ID: { - IPCPacket1CIssueDetected pkt = (IPCPacket1CIssueDetected)ipc; + IPCPacket1CIssueDetected pkt = (IPCPacket1CIssueDetected) ipc; issuesDetected.add(pkt.issueID); break; } @@ -437,83 +338,104 @@ public class SingleplayerServerController implements ISaveFormat { } } - public static void sendIPCPacket(IPCPacketBase ipc) { - byte[] pkt; - try { - pkt = packetManagerInstance.IPCSerialize(ipc); - }catch (IOException ex) { - throw new RuntimeException("Failed to serialize IPC packet", ex); + public static boolean hangupEaglercraftServer() { + LANServerController.closeLAN(); + if (isWorldRunning()) { + logger.error("Shutting down integrated server due to unexpected client hangup, this is a memleak"); + statusState = IntegratedServerState.WORLD_UNLOADING; + sendIPCPacket(new IPCPacket01StopServer()); + return true; + } else { + return false; } - ClientPlatformSingleplayer.sendPacket(new IPCPacketData(IPC_CHANNEL, pkt)); - } - - - private static boolean callFailed = false; - - public static boolean didLastCallFail() { - boolean c = callFailed; - callFailed = false; - return c; } public static void importWorld(String name, byte[] data, int format, byte gameRules) { ensureReady(); statusState = IntegratedServerState.WORLD_IMPORTING; - sendIPCPacket(new IPCPacket07ImportWorld(name, data, (byte)format, gameRules)); + sendIPCPacket(new IPCPacket07ImportWorld(name, data, (byte) format, gameRules)); } - - public static void exportWorld(String name, int format) { + + public static boolean isChannelNameAllowed(String ch) { + return !IPC_CHANNEL.equals(ch) && !PLAYER_CHANNEL.equals(ch); + } + + public static boolean isChannelOpen(String ch) { + return openLANChannels.contains(ch); + } + + public static boolean isClientInEaglerSingleplayerOrLAN() { + Minecraft mc = Minecraft.getMinecraft(); + return mc != null && mc.thePlayer != null && mc.thePlayer.sendQueue.isClientInEaglerSingleplayerOrLAN(); + } + + public static boolean isIntegratedServerWorkerAlive() { + return statusState != IntegratedServerState.WORLD_WORKER_NOT_RUNNING; + } + + public static boolean isIntegratedServerWorkerStarted() { + return statusState != IntegratedServerState.WORLD_WORKER_NOT_RUNNING + && statusState != IntegratedServerState.WORLD_WORKER_BOOTING; + } + + public static boolean isIssueDetected(int issue) { + return issuesDetected.contains(issue); + } + + public static boolean isReady() { + return statusState == IntegratedServerState.WORLD_NONE; + } + + public static boolean isRunningSingleThreadMode() { + return ClientPlatformSingleplayer.isRunningSingleThreadMode(); + } + + public static boolean isWorldNotLoaded() { + return statusState == IntegratedServerState.WORLD_NONE + || statusState == IntegratedServerState.WORLD_WORKER_NOT_RUNNING + || statusState == IntegratedServerState.WORLD_WORKER_BOOTING; + } + + public static boolean isWorldReady() { + return statusState == IntegratedServerState.WORLD_LOADED || statusState == IntegratedServerState.WORLD_PAUSED + || statusState == IntegratedServerState.WORLD_SAVING; + } + + public static boolean isWorldRunning() { + return statusState == IntegratedServerState.WORLD_LOADED || statusState == IntegratedServerState.WORLD_PAUSED + || statusState == IntegratedServerState.WORLD_LOADING + || statusState == IntegratedServerState.WORLD_SAVING; + } + + public static void killWorker() { + statusState = IntegratedServerState.WORLD_WORKER_NOT_RUNNING; + ClientPlatformSingleplayer.killWorker(); + LANServerController.closeLAN(); + } + + public static void launchEaglercraftServer(String folderName, int difficulty, int viewDistance, + WorldSettings settings) { ensureReady(); - statusState = IntegratedServerState.WORLD_EXPORTING; - if(format == IPCPacket05RequestData.REQUEST_LEVEL_EAG) { - name = name + (new String(new char[] { (char)253, (char)233, (char)233 })) + EaglerProfile.getName(); + clearTPS(); + if (settings != null) { + sendIPCPacket(new IPCPacket02InitWorld(folderName, settings.getGameType().getID(), + settings.getTerrainType().getWorldTypeID(), settings.getWorldName(), settings.getSeed(), + settings.areCommandsAllowed(), settings.isMapFeaturesEnabled(), settings.isBonusChestEnabled(), + settings.getHardcoreEnabled())); } - sendIPCPacket(new IPCPacket05RequestData(name, (byte)format)); - } - - private static byte[] exportResponse = null; - - public static byte[] getExportResponse() { - byte[] dat = exportResponse; - exportResponse = null; - return dat; - } - - public static String worldStatusString() { - return worldStatusString; - } - - public static float worldStatusProgress() { - return worldStatusProgress; - } - - public static IPCPacket15Crashed worldStatusError() { - return exceptions.size() > 0 ? exceptions.remove(0) : null; - } - - public static IPCPacket15Crashed[] worldStatusErrors() { - int l = exceptions.size(); - if(l == 0) { - return null; - } - IPCPacket15Crashed[] pkts = exceptions.toArray(new IPCPacket15Crashed[l]); - exceptions.clear(); - return pkts; - } - - public static void clearPlayerData(String worldName) { - ensureReady(); - statusState = IntegratedServerState.WORLD_CLEAR_PLAYERS; - sendIPCPacket(new IPCPacket18ClearPlayers(worldName)); + statusState = IntegratedServerState.WORLD_LOADING; + worldStatusProgress = 0.0f; + sendIPCPacket(new IPCPacket00StartServer(folderName, EaglerProfile.getName(), difficulty, viewDistance, + EagRuntime.getConfiguration().isDemo())); } private static void loadSaveComparators() { saveListMap.clear(); saveListCache.clear(); - for(int j = 0, l = saveListNBT.size(); j < l; ++j) { + for (int j = 0, l = saveListNBT.size(); j < l; ++j) { NBTTagCompound nbt = saveListNBT.get(j); String folderName = nbt.getString("folderNameEagler"); - if(!StringUtils.isEmpty(folderName)) { + if (!StringUtils.isEmpty(folderName)) { WorldInfo worldinfo = new WorldInfo(nbt.getCompoundTag("Data")); saveListMap.put(folderName, worldinfo); String s1 = worldinfo.getWorldName(); @@ -529,34 +451,169 @@ public class SingleplayerServerController implements ISaveFormat { } } - @Override - public String getName() { - return "eaglercraft"; + public static void openLocalPlayerChannel() { + localPlayerNetworkManager.isPlayerChannelOpen = true; + sendIPCPacket(new IPCPacket0CPlayerChannel(PLAYER_CHANNEL, true)); + } + + public static void openPlayerChannel(String ch) { + if (openLANChannels.contains(ch)) { + logger.error("Tried to open channel that already exists: \"{}\"", ch); + } else if (!isChannelNameAllowed(ch)) { + logger.error("Tried to open disallowed channel name: \"{}\"", ch); + } else { + openLANChannels.add(ch); + sendIPCPacket(new IPCPacket0CPlayerChannel(ch, true)); + PlatformWebRTC.serverLANCreatePeer(ch); + } + } + + public static void runTick() { + List pktList = ClientPlatformSingleplayer.recieveAllPacket(); + if (pktList != null) { + IPCPacketData packetData; + for (int i = 0, l = pktList.size(); i < l; ++i) { + packetData = pktList.get(i); + if (packetData.channel.equals(SingleplayerServerController.IPC_CHANNEL)) { + IPCPacketBase ipc; + try { + ipc = packetManagerInstance.IPCDeserialize(packetData.contents); + } catch (IOException ex) { + throw new RuntimeException("Failed to deserialize IPC packet", ex); + } + handleIPCPacket(ipc); + } else if (packetData.channel.equals(SingleplayerServerController.PLAYER_CHANNEL)) { + if (localPlayerNetworkManager.getConnectStatus() != EnumEaglerConnectionState.CLOSED) { + localPlayerNetworkManager.addRecievedPacket(packetData.contents); + } else { + logger.warn("Recieved {} byte packet on closed local player connection", + packetData.contents.length); + } + } else { + PlatformWebRTC.serverLANWritePacket(packetData.channel, packetData.contents); + } + } + } + + boolean logWindowState = PlatformApplication.isShowingDebugConsole(); + if (loggingState != logWindowState) { + loggingState = logWindowState; + sendIPCPacket(new IPCPacket1BEnableLogging(logWindowState)); + } + + if (ClientPlatformSingleplayer.isRunningSingleThreadMode()) { + ClientPlatformSingleplayer.updateSingleThreadMode(); + } + + LANServerController.updateLANServer(); + } + + public static void sendIPCPacket(IPCPacketBase ipc) { + byte[] pkt; + try { + pkt = packetManagerInstance.IPCSerialize(ipc); + } catch (IOException ex) { + throw new RuntimeException("Failed to serialize IPC packet", ex); + } + ClientPlatformSingleplayer.sendPacket(new IPCPacketData(IPC_CHANNEL, pkt)); + } + + public static void setDifficulty(int difficultyId) { + if (isWorldRunning()) { + sendIPCPacket(new IPCPacket0ASetWorldDifficulty((byte) difficultyId)); + } + } + + public static void setPaused(boolean pause) { + if (statusState != IntegratedServerState.WORLD_LOADED && statusState != IntegratedServerState.WORLD_PAUSED + && statusState != IntegratedServerState.WORLD_SAVING) { + return; + } + if (isPaused != pause) { + sendIPCPacket(new IPCPacket0BPause(pause)); + isPaused = pause; + } + } + + public static boolean shutdownEaglercraftServer() { + LANServerController.closeLAN(); + if (isWorldRunning()) { + logger.info("Shutting down integrated server"); + statusState = IntegratedServerState.WORLD_UNLOADING; + sendIPCPacket(new IPCPacket01StopServer()); + return true; + } else { + return false; + } + } + + public static void startIntegratedServerWorker(boolean forceSingleThread) { + if (statusState == IntegratedServerState.WORLD_WORKER_NOT_RUNNING) { + exceptions.clear(); + issuesDetected.clear(); + statusState = IntegratedServerState.WORLD_WORKER_BOOTING; + loggingState = true; + boolean singleThreadSupport = ClientPlatformSingleplayer.isSingleThreadModeSupported(); + if (!singleThreadSupport && forceSingleThread) { + throw new UnsupportedOperationException("Single thread mode is not supported!"); + } + if (forceSingleThread || !singleThreadSupport) { + ClientPlatformSingleplayer.startIntegratedServer(forceSingleThread); + } else { + try { + ClientPlatformSingleplayer.startIntegratedServer(forceSingleThread); + } catch (Throwable t) { + logger.error("Failed to start integrated server worker"); + logger.error(t); + logger.error("Attempting to use single thread mode"); + exceptions.clear(); + issuesDetected.clear(); + statusState = IntegratedServerState.WORLD_WORKER_BOOTING; + loggingState = true; + ClientPlatformSingleplayer.startIntegratedServer(true); + } + } + } + } + + public static void updateLocale(List dump) { + if (statusState != IntegratedServerState.WORLD_WORKER_NOT_RUNNING) { + sendIPCPacket(new IPCPacket14StringList(IPCPacket14StringList.LOCALE, dump)); + } + } + + public static IPCPacket15Crashed worldStatusError() { + return exceptions.size() > 0 ? exceptions.remove(0) : null; + } + + public static IPCPacket15Crashed[] worldStatusErrors() { + int l = exceptions.size(); + if (l == 0) { + return null; + } + IPCPacket15Crashed[] pkts = exceptions.toArray(new IPCPacket15Crashed[l]); + exceptions.clear(); + return pkts; + } + + public static float worldStatusProgress() { + return worldStatusProgress; + } + + public static String worldStatusString() { + return worldStatusString; + } + + private SingleplayerServerController() { } @Override - public ISaveHandler getSaveLoader(String var1, boolean var2) { - return new SingleplayerSaveHandler(saveListMap.get(var1)); + public boolean canLoadWorld(String var1) { + return saveListMap.containsKey(var1); } @Override - public List getSaveList() { - return saveListCache; - } - - @Override - public void flushCache() { - sendIPCPacket(new IPCPacket0EListWorlds()); - statusState = IntegratedServerState.WORLD_LISTING; - } - - @Override - public WorldInfo getWorldInfo(String var1) { - return saveListMap.get(var1); - } - - @Override - public boolean func_154335_d(String var1) { + public boolean convertMapFormat(String var1, IProgressUpdate var2) { return false; } @@ -568,15 +625,9 @@ public class SingleplayerServerController implements ISaveFormat { } @Override - public boolean renameWorld(String var1, String var2) { - sendIPCPacket(new IPCPacket06RenameWorldNBT(var1, var2, false)); - statusState = IntegratedServerState.WORLD_RENAMING; - return true; - } - - public static void duplicateWorld(String var1, String var2) { - sendIPCPacket(new IPCPacket06RenameWorldNBT(var1, var2, true)); - statusState = IntegratedServerState.WORLD_DUPLICATING; + public void flushCache() { + sendIPCPacket(new IPCPacket0EListWorlds()); + statusState = IntegratedServerState.WORLD_LISTING; } @Override @@ -584,49 +635,40 @@ public class SingleplayerServerController implements ISaveFormat { return false; } + @Override + public boolean func_154335_d(String var1) { + return false; + } + + @Override + public String getName() { + return "eaglercraft"; + } + + @Override + public List getSaveList() { + return saveListCache; + } + + @Override + public ISaveHandler getSaveLoader(String var1, boolean var2) { + return new SingleplayerSaveHandler(saveListMap.get(var1)); + } + + @Override + public WorldInfo getWorldInfo(String var1) { + return saveListMap.get(var1); + } + @Override public boolean isOldMapFormat(String var1) { return false; } @Override - public boolean convertMapFormat(String var1, IProgressUpdate var2) { - return false; - } - - @Override - public boolean canLoadWorld(String var1) { - return saveListMap.containsKey(var1); - } - - public static boolean canKillWorker() { - return ClientPlatformSingleplayer.canKillWorker(); - } - - public static void killWorker() { - statusState = IntegratedServerState.WORLD_WORKER_NOT_RUNNING; - ClientPlatformSingleplayer.killWorker(); - LANServerController.closeLAN(); - } - - public static void updateLocale(List dump) { - if(statusState != IntegratedServerState.WORLD_WORKER_NOT_RUNNING) { - sendIPCPacket(new IPCPacket14StringList(IPCPacket14StringList.LOCALE, dump)); - } - } - - public static void setDifficulty(int difficultyId) { - if(isWorldRunning()) { - sendIPCPacket(new IPCPacket0ASetWorldDifficulty((byte)difficultyId)); - } - } - - public static void configureLAN(net.minecraft.world.WorldSettings.GameType enumGameType, boolean allowCommands) { - sendIPCPacket(new IPCPacket17ConfigureLAN(enumGameType.getID(), allowCommands, LANServerController.currentICEServers)); - } - - public static boolean isClientInEaglerSingleplayerOrLAN() { - Minecraft mc = Minecraft.getMinecraft(); - return mc != null && mc.thePlayer != null && mc.thePlayer.sendQueue.isClientInEaglerSingleplayerOrLAN(); + public boolean renameWorld(String var1, String var2) { + sendIPCPacket(new IPCPacket06RenameWorldNBT(var1, var2, false)); + statusState = IntegratedServerState.WORLD_RENAMING; + return true; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SkullCommand.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SkullCommand.java index 1d2aa1d0..6250b98b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SkullCommand.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/SkullCommand.java @@ -10,14 +10,15 @@ import net.minecraft.util.ChatComponentTranslation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,29 +38,31 @@ public class SkullCommand { } public void tick() { - if(waitingForSelection && EagRuntime.fileChooserHasResult()) { + if (waitingForSelection && EagRuntime.fileChooserHasResult()) { waitingForSelection = false; FileChooserResult fr = EagRuntime.getFileChooserResult(); - if(fr == null || mc.thePlayer == null || mc.thePlayer.sendQueue == null) { + if (fr == null || mc.thePlayer == null || mc.thePlayer.sendQueue == null) { return; } ImageData loaded = ImageData.loadImageFile(fr.fileData, ImageData.getMimeFromType(fr.fileName)); - if(loaded == null) { - mc.ingameGUI.getChatGUI().printChatMessage(new ChatComponentTranslation("command.skull.error.invalid.format")); + if (loaded == null) { + mc.ingameGUI.getChatGUI() + .printChatMessage(new ChatComponentTranslation("command.skull.error.invalid.format")); return; } - if(loaded.width != 64 || loaded.height > 64) { - mc.ingameGUI.getChatGUI().printChatMessage(new ChatComponentTranslation("command.skull.error.invalid.skin", loaded.width, loaded.height)); + if (loaded.width != 64 || loaded.height > 64) { + mc.ingameGUI.getChatGUI().printChatMessage( + new ChatComponentTranslation("command.skull.error.invalid.skin", loaded.width, loaded.height)); return; } byte[] rawSkin = new byte[loaded.pixels.length << 2]; - for(int i = 0, j, k; i < 4096; ++i) { + for (int i = 0, j, k; i < 4096; ++i) { j = i << 2; k = loaded.pixels[i]; - rawSkin[j] = (byte)(k >>> 24); - rawSkin[j + 1] = (byte)(k >>> 16); - rawSkin[j + 2] = (byte)(k >>> 8); - rawSkin[j + 3] = (byte)(k & 0xFF); + rawSkin[j] = (byte) (k >>> 24); + rawSkin[j + 1] = (byte) (k >>> 16); + rawSkin[j + 2] = (byte) (k >>> 8); + rawSkin[j + 3] = (byte) (k & 0xFF); } mc.thePlayer.sendQueue.sendEaglerMessage(new CPacketInstallSkinSPEAG(rawSkin)); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/WorkerStartupFailedException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/WorkerStartupFailedException.java index ca86bca0..fa71e68c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/WorkerStartupFailedException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/WorkerStartupFailedException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.sp; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/CrashScreen.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/CrashScreen.java index 5792faf7..259bfbd8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/CrashScreen.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/CrashScreen.java @@ -5,26 +5,27 @@ import net.lax1dude.eaglercraft.v1_8.sp.internal.ClientPlatformSingleplayer; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class CrashScreen { - public static void showCrashReportOverlay(String report, int x, int y, int w, int h) { - ClientPlatformSingleplayer.showCrashReportOverlay(report, x, y, w, h); - } - public static void hideCrashReportOverlay() { ClientPlatformSingleplayer.hideCrashReportOverlay(); } + public static void showCrashReportOverlay(String report, int x, int y, int w, int h) { + ClientPlatformSingleplayer.showCrashReportOverlay(report, x, y, w, h); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiNetworkSettingsButton.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiNetworkSettingsButton.java index 276b5531..c622310e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiNetworkSettingsButton.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiNetworkSettingsButton.java @@ -15,14 +15,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -46,7 +47,7 @@ public class GuiNetworkSettingsButton extends Gui { int w = mc.fontRendererObj.getStringWidth(text); boolean hover = xx > 1 && yy > 1 && xx < (w * 3 / 4) + 7 && yy < 12; - if(hover) { + if (hover) { Mouse.showCursor(EnumCursorType.HAND); } @@ -57,13 +58,14 @@ public class GuiNetworkSettingsButton extends Gui { public void mouseClicked(int xx, int yy, int btn) { int w = mc.fontRendererObj.getStringWidth(text); - if(xx > 2 && yy > 2 && xx < (w * 3 / 4) + 5 && yy < 12) { - if(LANServerController.supported()) { + if (xx > 2 && yy > 2 && xx < (w * 3 / 4) + 5 && yy < 12) { + if (LANServerController.supported()) { mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenRelay(screen))); - }else { + } else { mc.displayGuiScreen(new GuiScreenLANNotSupported(screen)); } - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenAddRelay.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenAddRelay.java index 8bba2619..8802c780 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenAddRelay.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenAddRelay.java @@ -12,14 +12,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,42 +36,6 @@ public class GuiScreenAddRelay extends GuiScreen { this.parentGui = par1GuiScreen; } - /** - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - this.serverName.updateCursorCounter(); - this.serverAddress.updateCursorCounter(); - } - - /** - * Adds the buttons (and other controls) to the screen in question. - */ - public void initGui() { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.parentGui.addNewName = RelayManager.relayManager.makeNewRelayName(); - this.parentGui.addNewAddr = ""; - this.parentGui.addNewPrimary = RelayManager.relayManager.count() == 0; - int sslOff = EagRuntime.requireSSL() ? 36 : 0; - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12 + sslOff, I18n.format("addRelay.add"))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12 + sslOff, I18n.format("gui.cancel"))); - this.buttonList.add(new GuiButton(2, this.width / 2 - 100, 142, I18n.format("addRelay.primary") + ": " + (this.parentGui.addNewPrimary ? I18n.format("gui.yes") : I18n.format("gui.no")))); - this.serverName = new GuiTextField(3, this.fontRendererObj, this.width / 2 - 100, 106, 200, 20); - this.serverAddress = new GuiTextField(4, this.fontRendererObj, this.width / 2 - 100, 66, 200, 20); - this.serverAddress.setMaxStringLength(128); - this.serverAddress.setFocused(true); - ((GuiButton) this.buttonList.get(0)).enabled = this.serverAddress.getText().length() > 0 && this.serverAddress.getText().split(":").length > 0 && this.serverName.getText().length() > 0; - this.serverName.setText(this.parentGui.addNewName); - } - - /** - * Called when the screen is unloaded. Used to disable keyboard repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - /** * Fired when a control is clicked. This is the equivalent of * ActionListener.actionPerformed(ActionEvent e). @@ -85,11 +50,66 @@ public class GuiScreenAddRelay extends GuiScreen { this.parentGui.confirmClicked(true, 0); } else if (par1GuiButton.id == 2) { this.parentGui.addNewPrimary = !this.parentGui.addNewPrimary; - ((GuiButton) this.buttonList.get(2)).displayString = I18n.format("addRelay.primary") + ": " + (this.parentGui.addNewPrimary ? I18n.format("gui.yes") : I18n.format("gui.no")); + ((GuiButton) this.buttonList.get(2)).displayString = I18n.format("addRelay.primary") + ": " + + (this.parentGui.addNewPrimary ? I18n.format("gui.yes") : I18n.format("gui.no")); } } } + public boolean blockPTTKey() { + return this.serverName.isFocused() || this.serverAddress.isFocused(); + } + + /** + * Draws the screen and all the components in it. + */ + public void drawScreen(int par1, int par2, float par3) { + this.drawBackground(0); + this.drawCenteredString(this.fontRendererObj, I18n.format("addRelay.title"), this.width / 2, 17, 16777215); + this.drawString(this.fontRendererObj, I18n.format("addRelay.address"), this.width / 2 - 100, 53, 10526880); + this.drawString(this.fontRendererObj, I18n.format("addRelay.name"), this.width / 2 - 100, 94, 10526880); + if (EagRuntime.requireSSL()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn1"), this.width / 2, 169, + 0xccccff); + this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn2"), this.width / 2, 181, + 0xccccff); + } + this.serverName.drawTextBox(); + this.serverAddress.drawTextBox(); + super.drawScreen(par1, par2, par3); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + this.serverName.fireInputEvent(event, param); + this.serverAddress.fireInputEvent(event, param); + } + + /** + * Adds the buttons (and other controls) to the screen in question. + */ + public void initGui() { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.parentGui.addNewName = RelayManager.relayManager.makeNewRelayName(); + this.parentGui.addNewAddr = ""; + this.parentGui.addNewPrimary = RelayManager.relayManager.count() == 0; + int sslOff = EagRuntime.requireSSL() ? 36 : 0; + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12 + sslOff, + I18n.format("addRelay.add"))); + this.buttonList.add( + new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12 + sslOff, I18n.format("gui.cancel"))); + this.buttonList.add(new GuiButton(2, this.width / 2 - 100, 142, I18n.format("addRelay.primary") + ": " + + (this.parentGui.addNewPrimary ? I18n.format("gui.yes") : I18n.format("gui.no")))); + this.serverName = new GuiTextField(3, this.fontRendererObj, this.width / 2 - 100, 106, 200, 20); + this.serverAddress = new GuiTextField(4, this.fontRendererObj, this.width / 2 - 100, 66, 200, 20); + this.serverAddress.setMaxStringLength(128); + this.serverAddress.setFocused(true); + ((GuiButton) this.buttonList.get(0)).enabled = this.serverAddress.getText().length() > 0 + && this.serverAddress.getText().split(":").length > 0 && this.serverName.getText().length() > 0; + this.serverName.setText(this.parentGui.addNewName); + } + /** * Fired when a key is typed. This is the equivalent of * KeyListener.keyTyped(KeyEvent e). @@ -112,7 +132,8 @@ public class GuiScreenAddRelay extends GuiScreen { this.actionPerformed((GuiButton) this.buttonList.get(0)); } - ((GuiButton) this.buttonList.get(0)).enabled = this.serverAddress.getText().length() > 0 && this.serverAddress.getText().split(":").length > 0 && this.serverName.getText().length() > 0; + ((GuiButton) this.buttonList.get(0)).enabled = this.serverAddress.getText().length() > 0 + && this.serverAddress.getText().split(":").length > 0 && this.serverName.getText().length() > 0; } /** @@ -125,24 +146,10 @@ public class GuiScreenAddRelay extends GuiScreen { } /** - * Draws the screen and all the components in it. + * Called when the screen is unloaded. Used to disable keyboard repeat events */ - public void drawScreen(int par1, int par2, float par3) { - this.drawBackground(0); - this.drawCenteredString(this.fontRendererObj, I18n.format("addRelay.title"), this.width / 2, 17, 16777215); - this.drawString(this.fontRendererObj, I18n.format("addRelay.address"), this.width / 2 - 100, 53, 10526880); - this.drawString(this.fontRendererObj, I18n.format("addRelay.name"), this.width / 2 - 100, 94, 10526880); - if(EagRuntime.requireSSL()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn1"), this.width / 2, 169, 0xccccff); - this.drawCenteredString(this.fontRendererObj, I18n.format("addServer.SSLWarn2"), this.width / 2, 181, 0xccccff); - } - this.serverName.drawTextBox(); - this.serverAddress.drawTextBox(); - super.drawScreen(par1, par2, par3); - } - - public boolean blockPTTKey() { - return this.serverName.isFocused() || this.serverAddress.isFocused(); + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); } @Override @@ -150,10 +157,12 @@ public class GuiScreenAddRelay extends GuiScreen { return this.serverName.isFocused() || this.serverAddress.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - this.serverName.fireInputEvent(event, param); - this.serverAddress.fireInputEvent(event, param); + /** + * Called from the main game loop to update the screen. + */ + public void updateScreen() { + this.serverName.updateCursorCounter(); + this.serverAddress.updateCursorCounter(); } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenBackupWorldSelection.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenBackupWorldSelection.java index 5c3904ca..7a900897 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenBackupWorldSelection.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenBackupWorldSelection.java @@ -17,14 +17,15 @@ import net.minecraft.world.storage.WorldInfo; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,9 +42,9 @@ public class GuiScreenBackupWorldSelection extends GuiScreen { private long worldSeed; private boolean oldRNG; private NBTTagCompound levelDat; - + private String worldName; - + public GuiScreenBackupWorldSelection(GuiScreen selectWorld, String worldName, NBTTagCompound levelDat) { this.selectWorld = selectWorld; this.worldName = worldName; @@ -51,89 +52,106 @@ public class GuiScreenBackupWorldSelection extends GuiScreen { this.worldSeed = levelDat.getCompoundTag("Data").getLong("RandomSeed"); this.oldRNG = levelDat.getCompoundTag("Data").getInteger("eaglerVersionSerial") == 0; } - - public void initGui() { - this.buttonList.add(worldRecreate = new GuiButton(1, this.width / 2 - 100, this.height / 5 + 5, I18n.format("singleplayer.backup.recreate"))); - this.buttonList.add(worldDuplicate = new GuiButton(2, this.width / 2 - 100, this.height / 5 + 30, I18n.format("singleplayer.backup.duplicate"))); - this.buttonList.add(worldExport = new GuiButton(3, this.width / 2 - 100, this.height / 5 + 80, I18n.format("singleplayer.backup.export"))); - this.buttonList.add(worldConvert = new GuiButton(4, this.width / 2 - 100, this.height / 5 + 105, I18n.format("singleplayer.backup.vanilla"))); - this.buttonList.add(worldBackup = new GuiButton(5, this.width / 2 - 100, this.height / 5 + 136, I18n.format("singleplayer.backup.clearPlayerData"))); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 155, I18n.format("gui.cancel"))); - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.title", worldName), this.width / 2, this.height / 5 - 35, 16777215); - if(oldRNG) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.seed") + " " + worldSeed + " " + EnumChatFormatting.RED + "(pre-u34)", this.width / 2, this.height / 5 + 62, 0xAAAAFF); - }else { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.seed") + " " + worldSeed, this.width / 2, this.height / 5 + 62, 0xAAAAFF); - } - - int toolTipColor = 0xDDDDAA; - if(worldRecreate.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.recreate.tooltip"), this.width / 2, this.height / 5 - 12, toolTipColor); - }else if(worldDuplicate.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.duplicate.tooltip"), this.width / 2, this.height / 5 - 12, toolTipColor); - }else if(worldExport.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.export.tooltip"), this.width / 2, this.height / 5 - 12, toolTipColor); - }else if(worldConvert.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.vanilla.tooltip"), this.width / 2, this.height / 5 - 12, toolTipColor); - }else if(worldBackup.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.clearPlayerData.tooltip"), this.width / 2, this.height / 5 - 12, toolTipColor); - } - - super.drawScreen(par1, par2, par3); - } protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { this.mc.displayGuiScreen(selectWorld); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { GuiCreateWorld cw = new GuiCreateWorld(selectWorld); WorldInfo inf = new WorldInfo(this.levelDat.getCompoundTag("Data")); cw.func_146318_a(inf); - if(inf.isOldEaglercraftRandom()) { + if (inf.isOldEaglercraftRandom()) { this.mc.displayGuiScreen(new GuiScreenOldSeedWarning(cw)); - }else { + } else { this.mc.displayGuiScreen(cw); } - }else if(par1GuiButton.id == 2) { + } else if (par1GuiButton.id == 2) { this.mc.displayGuiScreen(new GuiRenameWorld(this.selectWorld, this.worldName, true)); - }else if(par1GuiButton.id == 3) { + } else if (par1GuiButton.id == 3) { SingleplayerServerController.exportWorld(worldName, IPCPacket05RequestData.REQUEST_LEVEL_EAG); - this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(selectWorld, "singleplayer.busy.exporting.1", "singleplayer.failed.exporting.1", () -> { - byte[] b = SingleplayerServerController.getExportResponse(); - if(b != null) { - EagRuntime.downloadFileWithName(worldName + ".epk", b); - return true; - } - return false; - })); - }else if(par1GuiButton.id == 4) { + this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(selectWorld, "singleplayer.busy.exporting.1", + "singleplayer.failed.exporting.1", () -> { + byte[] b = SingleplayerServerController.getExportResponse(); + if (b != null) { + EagRuntime.downloadFileWithName(worldName + ".epk", b); + return true; + } + return false; + })); + } else if (par1GuiButton.id == 4) { SingleplayerServerController.exportWorld(worldName, IPCPacket05RequestData.REQUEST_LEVEL_MCA); - this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(selectWorld, "singleplayer.busy.exporting.2", "singleplayer.failed.exporting.2", () -> { - byte[] b = SingleplayerServerController.getExportResponse(); - if(b != null) { - EagRuntime.downloadFileWithName(worldName + ".zip", b); - return true; - } - return false; - })); - }else if(par1GuiButton.id == 5) { + this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(selectWorld, "singleplayer.busy.exporting.2", + "singleplayer.failed.exporting.2", () -> { + byte[] b = SingleplayerServerController.getExportResponse(); + if (b != null) { + EagRuntime.downloadFileWithName(worldName + ".zip", b); + return true; + } + return false; + })); + } else if (par1GuiButton.id == 5) { this.mc.displayGuiScreen(new GuiYesNo(this, I18n.format("singleplayer.backup.clearPlayerData.warning1"), - I18n.format("singleplayer.backup.clearPlayerData.warning2", worldName, EaglerProfile.getName()), 0)); + I18n.format("singleplayer.backup.clearPlayerData.warning2", worldName, EaglerProfile.getName()), + 0)); } } - + public void confirmClicked(boolean par1, int par2) { - if(par1) { + if (par1) { SingleplayerServerController.clearPlayerData(worldName); - this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(this, "singleplayer.busy.clearplayers", "singleplayer.failed.clearplayers", SingleplayerServerController::isReady)); - }else { + this.mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(this, "singleplayer.busy.clearplayers", + "singleplayer.failed.clearplayers", SingleplayerServerController::isReady)); + } else { mc.displayGuiScreen(this); } } + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.title", worldName), + this.width / 2, this.height / 5 - 35, 16777215); + if (oldRNG) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.seed") + " " + worldSeed + + " " + EnumChatFormatting.RED + "(pre-u34)", this.width / 2, this.height / 5 + 62, 0xAAAAFF); + } else { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.seed") + " " + worldSeed, + this.width / 2, this.height / 5 + 62, 0xAAAAFF); + } + + int toolTipColor = 0xDDDDAA; + if (worldRecreate.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.recreate.tooltip"), + this.width / 2, this.height / 5 - 12, toolTipColor); + } else if (worldDuplicate.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.duplicate.tooltip"), + this.width / 2, this.height / 5 - 12, toolTipColor); + } else if (worldExport.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.export.tooltip"), + this.width / 2, this.height / 5 - 12, toolTipColor); + } else if (worldConvert.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.vanilla.tooltip"), + this.width / 2, this.height / 5 - 12, toolTipColor); + } else if (worldBackup.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.backup.clearPlayerData.tooltip"), + this.width / 2, this.height / 5 - 12, toolTipColor); + } + + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + this.buttonList.add(worldRecreate = new GuiButton(1, this.width / 2 - 100, this.height / 5 + 5, + I18n.format("singleplayer.backup.recreate"))); + this.buttonList.add(worldDuplicate = new GuiButton(2, this.width / 2 - 100, this.height / 5 + 30, + I18n.format("singleplayer.backup.duplicate"))); + this.buttonList.add(worldExport = new GuiButton(3, this.width / 2 - 100, this.height / 5 + 80, + I18n.format("singleplayer.backup.export"))); + this.buttonList.add(worldConvert = new GuiButton(4, this.width / 2 - 100, this.height / 5 + 105, + I18n.format("singleplayer.backup.vanilla"))); + this.buttonList.add(worldBackup = new GuiButton(5, this.width / 2 - 100, this.height / 5 + 136, + I18n.format("singleplayer.backup.clearPlayerData"))); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 155, I18n.format("gui.cancel"))); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenChangeRelayTimeout.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenChangeRelayTimeout.java index 74271dae..2bde8d67 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenChangeRelayTimeout.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenChangeRelayTimeout.java @@ -8,14 +8,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,34 +31,12 @@ public class GuiScreenChangeRelayTimeout extends GuiScreen { this.parent = parent; } - public void initGui() { - title = I18n.format("networkSettings.relayTimeoutTitle"); - buttonList.clear(); - buttonList.add(new GuiButton(0, width / 2 - 100, height / 3 + 55, I18n.format("gui.done"))); - buttonList.add(new GuiButton(1, width / 2 - 100, height / 3 + 85, I18n.format("gui.cancel"))); - slider = new GuiSlider2(0, width / 2 - 100, height / 3 + 10, 200, 20, (mc.gameSettings.relayTimeout - 1) / 14.0f, 1.0f) { - public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { - if(super.mousePressed(par1Minecraft, par2, par3)) { - this.displayString = "" + (int)((sliderValue * 14.0f) + 1.0f) + "s"; - return true; - }else { - return false; - } - } - public void mouseDragged(Minecraft par1Minecraft, int par2, int par3) { - super.mouseDragged(par1Minecraft, par2, par3); - this.displayString = "" + (int)((sliderValue * 14.0f) + 1.0f) + "s"; - } - }; - slider.displayString = "" + mc.gameSettings.relayTimeout + "s"; - } - public void actionPerformed(GuiButton btn) { - if(btn.id == 0) { - mc.gameSettings.relayTimeout = (int)((slider.sliderValue * 14.0f) + 1.0f); + if (btn.id == 0) { + mc.gameSettings.relayTimeout = (int) ((slider.sliderValue * 14.0f) + 1.0f); mc.gameSettings.saveOptions(); mc.displayGuiScreen(parent); - }else if(btn.id == 1) { + } else if (btn.id == 1) { mc.displayGuiScreen(parent); } } @@ -69,13 +48,37 @@ public class GuiScreenChangeRelayTimeout extends GuiScreen { super.drawScreen(par1, par2, par3); } + public void initGui() { + title = I18n.format("networkSettings.relayTimeoutTitle"); + buttonList.clear(); + buttonList.add(new GuiButton(0, width / 2 - 100, height / 3 + 55, I18n.format("gui.done"))); + buttonList.add(new GuiButton(1, width / 2 - 100, height / 3 + 85, I18n.format("gui.cancel"))); + slider = new GuiSlider2(0, width / 2 - 100, height / 3 + 10, 200, 20, + (mc.gameSettings.relayTimeout - 1) / 14.0f, 1.0f) { + public void mouseDragged(Minecraft par1Minecraft, int par2, int par3) { + super.mouseDragged(par1Minecraft, par2, par3); + this.displayString = "" + (int) ((sliderValue * 14.0f) + 1.0f) + "s"; + } + + public boolean mousePressed(Minecraft par1Minecraft, int par2, int par3) { + if (super.mousePressed(par1Minecraft, par2, par3)) { + this.displayString = "" + (int) ((sliderValue * 14.0f) + 1.0f) + "s"; + return true; + } else { + return false; + } + } + }; + slider.displayString = "" + mc.gameSettings.relayTimeout + "s"; + } + public void mouseClicked(int mx, int my, int button) { slider.mousePressed(mc, mx, my); super.mouseClicked(mx, my, button); } public void mouseReleased(int par1, int par2, int par3) { - if(par3 == 0) { + if (par3 == 0) { slider.mouseReleased(par1, par2); } super.mouseReleased(par1, par2, par3); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenConnectOption.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenConnectOption.java index aee6c5eb..bb26263f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenConnectOption.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenConnectOption.java @@ -10,14 +10,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,26 +36,17 @@ public class GuiScreenConnectOption extends GuiScreen { this.relaysButton = new GuiNetworkSettingsButton(this); } - public void initGui() { - title = I18n.format("selectServer.direct"); - prompt = I18n.format("directConnect.prompt"); - buttonList.clear(); - buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 - 60 + 90, I18n.format("directConnect.serverJoin"))); - buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 4 - 60 + 115, I18n.format("directConnect.lanWorld"))); - buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 - 60 + 155, I18n.format("gui.cancel"))); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { guiScreen.cancelDirectConnect(); mc.displayGuiScreen(guiScreen); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { mc.displayGuiScreen(new GuiScreenServerList(guiScreen, guiScreen.getSelectedServer())); - }else if(par1GuiButton.id == 2) { - if(LANServerController.supported()) { + } else if (par1GuiButton.id == 2) { + if (LANServerController.supported()) { guiScreen.cancelDirectConnect(); mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenLANConnect(guiScreen))); - }else { + } else { mc.displayGuiScreen(new GuiScreenLANNotSupported(this)); } } @@ -68,6 +60,17 @@ public class GuiScreenConnectOption extends GuiScreen { relaysButton.drawScreen(par1, par2); } + public void initGui() { + title = I18n.format("selectServer.direct"); + prompt = I18n.format("directConnect.prompt"); + buttonList.clear(); + buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 - 60 + 90, + I18n.format("directConnect.serverJoin"))); + buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 4 - 60 + 115, + I18n.format("directConnect.lanWorld"))); + buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 - 60 + 155, I18n.format("gui.cancel"))); + } + protected void mouseClicked(int par1, int par2, int par3) { relaysButton.mouseClicked(par1, par2, par3); super.mouseClicked(par1, par2, par3); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenCreateWorldSelection.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenCreateWorldSelection.java index 80ef57e3..4b44e7ce 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenCreateWorldSelection.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenCreateWorldSelection.java @@ -10,14 +10,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -30,57 +31,65 @@ public class GuiScreenCreateWorldSelection extends GuiScreen { private GuiButton worldVanilla = null; private boolean isImportingEPK = false; private boolean isImportingMCA = false; - + public GuiScreenCreateWorldSelection(GuiScreen mainmenu) { this.mainmenu = mainmenu; } - - public void initGui() { - this.buttonList.add(worldCreate = new GuiButton(1, this.width / 2 - 100, this.height / 4 + 40, I18n.format("singleplayer.create.create"))); - this.buttonList.add(worldImport = new GuiButton(2, this.width / 2 - 100, this.height / 4 + 65, I18n.format("singleplayer.create.import"))); - this.buttonList.add(worldVanilla = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 90, I18n.format("singleplayer.create.vanilla"))); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 130, I18n.format("gui.cancel"))); - } - - public void updateScreen() { - if(EagRuntime.fileChooserHasResult() && (isImportingEPK || isImportingMCA)) { - FileChooserResult fr = EagRuntime.getFileChooserResult(); - if(fr != null) { - this.mc.displayGuiScreen(new GuiScreenNameWorldImport(mainmenu, fr, isImportingEPK ? 0 : (isImportingMCA ? 1 : -1))); - } - isImportingEPK = isImportingMCA = false; - } - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.title"), this.width / 2, this.height / 4, 16777215); - - int toolTipColor = 0xDDDDAA; - if(worldCreate.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.create.tooltip"), this.width / 2, this.height / 4 + 20, toolTipColor); - }else if(worldImport.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.import.tooltip"), this.width / 2, this.height / 4 + 20, toolTipColor); - }else if(worldVanilla.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.vanilla.tooltip"), this.width / 2, this.height / 4 + 20, toolTipColor); - } - - super.drawScreen(par1, par2, par3); - } protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { this.mc.displayGuiScreen(mainmenu); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { this.mc.displayGuiScreen(new GuiCreateWorld(mainmenu)); - }else if(par1GuiButton.id == 2) { + } else if (par1GuiButton.id == 2) { isImportingEPK = true; EagRuntime.displayFileChooser(null, "epk"); - }else if(par1GuiButton.id == 3) { + } else if (par1GuiButton.id == 3) { isImportingMCA = true; EagRuntime.displayFileChooser(null, "zip"); } } + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.title"), this.width / 2, + this.height / 4, 16777215); + + int toolTipColor = 0xDDDDAA; + if (worldCreate.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.create.tooltip"), + this.width / 2, this.height / 4 + 20, toolTipColor); + } else if (worldImport.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.import.tooltip"), + this.width / 2, this.height / 4 + 20, toolTipColor); + } else if (worldVanilla.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.create.vanilla.tooltip"), + this.width / 2, this.height / 4 + 20, toolTipColor); + } + + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + this.buttonList.add(worldCreate = new GuiButton(1, this.width / 2 - 100, this.height / 4 + 40, + I18n.format("singleplayer.create.create"))); + this.buttonList.add(worldImport = new GuiButton(2, this.width / 2 - 100, this.height / 4 + 65, + I18n.format("singleplayer.create.import"))); + this.buttonList.add(worldVanilla = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 90, + I18n.format("singleplayer.create.vanilla"))); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 130, I18n.format("gui.cancel"))); + } + + public void updateScreen() { + if (EagRuntime.fileChooserHasResult() && (isImportingEPK || isImportingMCA)) { + FileChooserResult fr = EagRuntime.getFileChooserResult(); + if (fr != null) { + this.mc.displayGuiScreen( + new GuiScreenNameWorldImport(mainmenu, fr, isImportingEPK ? 0 : (isImportingMCA ? 1 : -1))); + } + isImportingEPK = isImportingMCA = false; + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerFailed.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerFailed.java index 09e04d1d..fa20adf6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerFailed.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerFailed.java @@ -6,14 +6,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerStartup.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerStartup.java index f5418127..02aa6fd4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerStartup.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoIntegratedServerStartup.java @@ -6,31 +6,30 @@ import net.lax1dude.eaglercraft.v1_8.sp.WorkerStartupFailedException; import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket15Crashed; import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1CIssueDetected; import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiMainMenu; import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.gui.GuiSelectWorld; import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenDemoIntegratedServerStartup extends GuiScreen { + private static final String[] dotDotDot = new String[] { "", ".", "..", "..." }; private final GuiScreen contScreen; private final boolean singleThread; - private static final String[] dotDotDot = new String[] { "", ".", "..", "..." }; private int counter = 0; @@ -46,32 +45,56 @@ public class GuiScreenDemoIntegratedServerStartup extends GuiScreen { this.singleThread = singleThread; } + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + SingleplayerServerController.killWorker(); + mc.displayGuiScreen(new GuiScreenDemoIntegratedServerStartup(contScreen, true)); + } + } + + public boolean canCloseGui() { + return false; + } + + public void drawScreen(int i, int j, float f) { + this.drawBackground(0); + String txt = I18n.format("singleplayer.integratedStartup"); + int w = this.fontRendererObj.getStringWidth(txt); + this.drawString(this.fontRendererObj, txt + dotDotDot[(int) ((EagRuntime.steadyTimeMillis() / 300L) % 4L)], + (this.width - w) / 2, this.height / 2 - 50, 16777215); + super.drawScreen(i, j, f); + } + public void initGui() { this.buttonList.clear(); - this.buttonList.add(cancelButton = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, I18n.format("singleplayer.busy.killTask"))); + this.buttonList.add(cancelButton = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, + I18n.format("singleplayer.busy.killTask"))); cancelButton.visible = false; } public void updateScreen() { ++counter; - if(counter == 2) { + if (counter == 2) { try { SingleplayerServerController.startIntegratedServerWorker(singleThread); - }catch(WorkerStartupFailedException ex) { - mc.displayGuiScreen(new GuiScreenIntegratedServerFailed(ex.getMessage(), new GuiScreenDemoIntegratedServerFailed())); + } catch (WorkerStartupFailedException ex) { + mc.displayGuiScreen(new GuiScreenIntegratedServerFailed(ex.getMessage(), + new GuiScreenDemoIntegratedServerFailed())); return; } - }else if(counter > 2) { - if(counter > 100 && SingleplayerServerController.canKillWorker() && !singleThread) { + } else if (counter > 2) { + if (counter > 100 && SingleplayerServerController.canKillWorker() && !singleThread) { cancelButton.visible = true; } IPCPacket15Crashed[] crashReport = SingleplayerServerController.worldStatusErrors(); - if(crashReport != null) { - mc.displayGuiScreen(GuiScreenIntegratedServerBusy.createException(new GuiScreenDemoIntegratedServerFailed(), "singleplayer.failed.notStarted", crashReport)); - }else if(SingleplayerServerController.isIntegratedServerWorkerStarted()) { + if (crashReport != null) { + mc.displayGuiScreen(GuiScreenIntegratedServerBusy.createException( + new GuiScreenDemoIntegratedServerFailed(), "singleplayer.failed.notStarted", crashReport)); + } else if (SingleplayerServerController.isIntegratedServerWorkerStarted()) { GuiScreen cont = contScreen; - if(SingleplayerServerController.isRunningSingleThreadMode()) { - cont = new GuiScreenIntegratedServerFailed("singleplayer.failed.singleThreadWarning.1", "singleplayer.failed.singleThreadWarning.2", cont); + if (SingleplayerServerController.isRunningSingleThreadMode()) { + cont = new GuiScreenIntegratedServerFailed("singleplayer.failed.singleThreadWarning.1", + "singleplayer.failed.singleThreadWarning.2", cont); } else if (!EagRuntime.getConfiguration().isRamdiskMode() && SingleplayerServerController.isIssueDetected(IPCPacket1CIssueDetected.ISSUE_RAMDISK_MODE) && SingleplayerServerController.canKillWorker()) { @@ -82,23 +105,4 @@ public class GuiScreenDemoIntegratedServerStartup extends GuiScreen { } } - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 0) { - SingleplayerServerController.killWorker(); - mc.displayGuiScreen(new GuiScreenDemoIntegratedServerStartup(contScreen, true)); - } - } - - public void drawScreen(int i, int j, float f) { - this.drawBackground(0); - String txt = I18n.format("singleplayer.integratedStartup"); - int w = this.fontRendererObj.getStringWidth(txt); - this.drawString(this.fontRendererObj, txt + dotDotDot[(int)((EagRuntime.steadyTimeMillis() / 300L) % 4L)], (this.width - w) / 2, this.height / 2 - 50, 16777215); - super.drawScreen(i, j, f); - } - - public boolean canCloseGui() { - return false; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoPlayWorldSelection.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoPlayWorldSelection.java index 042e8e29..92d7e3c4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoPlayWorldSelection.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenDemoPlayWorldSelection.java @@ -9,14 +9,15 @@ import net.minecraft.world.demo.DemoWorldServer; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,46 +27,51 @@ public class GuiScreenDemoPlayWorldSelection extends GuiScreen { private GuiScreen mainmenu; private GuiButton playWorld = null; private GuiButton joinWorld = null; - + public GuiScreenDemoPlayWorldSelection(GuiScreen mainmenu) { this.mainmenu = mainmenu; } - - public void initGui() { - this.buttonList.add(playWorld = new GuiButton(1, this.width / 2 - 100, this.height / 4 + 40, I18n.format("singleplayer.demo.create.create"))); - this.buttonList.add(joinWorld = new GuiButton(2, this.width / 2 - 100, this.height / 4 + 65, I18n.format("singleplayer.demo.create.join"))); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 130, I18n.format("gui.cancel"))); - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.demo.create.title"), this.width / 2, this.height / 4, 16777215); - - int toolTipColor = 0xDDDDAA; - if(playWorld.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.demo.create.create.tooltip"), this.width / 2, this.height / 4 + 20, toolTipColor); - }else if(joinWorld.isMouseOver()) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.demo.create.join.tooltip"), this.width / 2, this.height / 4 + 20, toolTipColor); - } - - super.drawScreen(par1, par2, par3); - } protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { this.mc.displayGuiScreen(mainmenu); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { this.mc.gameSettings.hasCreatedDemoWorld = true; this.mc.gameSettings.saveOptions(); this.mc.launchIntegratedServer("Demo World", "Demo World", DemoWorldServer.demoWorldSettings); - }else if(par1GuiButton.id == 2) { - if(LANServerController.supported()) { + } else if (par1GuiButton.id == 2) { + if (LANServerController.supported()) { this.mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenLANConnect(mainmenu))); - }else { + } else { this.mc.displayGuiScreen(new GuiScreenLANNotSupported(mainmenu)); } } } + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.demo.create.title"), this.width / 2, + this.height / 4, 16777215); + + int toolTipColor = 0xDDDDAA; + if (playWorld.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.demo.create.create.tooltip"), + this.width / 2, this.height / 4 + 20, toolTipColor); + } else if (joinWorld.isMouseOver()) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.demo.create.join.tooltip"), + this.width / 2, this.height / 4 + 20, toolTipColor); + } + + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + this.buttonList.add(playWorld = new GuiButton(1, this.width / 2 - 100, this.height / 4 + 40, + I18n.format("singleplayer.demo.create.create"))); + this.buttonList.add(joinWorld = new GuiButton(2, this.width / 2 - 100, this.height / 4 + 65, + I18n.format("singleplayer.demo.create.join"))); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 130, I18n.format("gui.cancel"))); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerBusy.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerBusy.java index effd5153..63a96d7d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerBusy.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerBusy.java @@ -15,69 +15,73 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenIntegratedServerBusy extends GuiScreen { + private static final Runnable defaultTerminateAction = () -> { + if (SingleplayerServerController.canKillWorker()) { + SingleplayerServerController.killWorker(); + Minecraft.getMinecraft().displayGuiScreen( + new GuiScreenIntegratedServerFailed("singleplayer.failed.killed", new GuiMainMenu())); + } else { + EagRuntime.showPopup("Cannot kill worker tasks on desktop runtime!"); + } + }; + private static final BiConsumer defaultExceptionAction = (t, u) -> { + GuiScreenIntegratedServerBusy tt = (GuiScreenIntegratedServerBusy) t; + Minecraft.getMinecraft().displayGuiScreen(createException(tt.menu, tt.failMessage, u)); + }; + + public static GuiScreen createException(GuiScreen ok, String msg, IPCPacket15Crashed[] exceptions) { + ok = new GuiScreenIntegratedServerFailed(msg, ok); + if (exceptions != null) { + for (int i = exceptions.length - 1; i >= 0; --i) { + ok = new GuiScreenIntegratedServerCrashed(ok, exceptions[i].crashReport); + } + } + return ok; + } + public final GuiScreen menu; private GuiButton killTask; public final String failMessage; private BooleanSupplier checkTaskComplete; private Runnable taskKill; private String lastStatus; + private String currentStatus; + private BiConsumer onException; + private int areYouSure; - + private long startStartTime; - - private static final Runnable defaultTerminateAction = () -> { - if(SingleplayerServerController.canKillWorker()) { - SingleplayerServerController.killWorker(); - Minecraft.getMinecraft().displayGuiScreen(new GuiScreenIntegratedServerFailed("singleplayer.failed.killed", new GuiMainMenu())); - }else { - EagRuntime.showPopup("Cannot kill worker tasks on desktop runtime!"); - } - }; - - public static GuiScreen createException(GuiScreen ok, String msg, IPCPacket15Crashed[] exceptions) { - ok = new GuiScreenIntegratedServerFailed(msg, ok); - if(exceptions != null) { - for(int i = exceptions.length - 1; i >= 0; --i) { - ok = new GuiScreenIntegratedServerCrashed(ok, exceptions[i].crashReport); - } - } - return ok; - } - - private static final BiConsumer defaultExceptionAction = (t, u) -> { - GuiScreenIntegratedServerBusy tt = (GuiScreenIntegratedServerBusy) t; - Minecraft.getMinecraft().displayGuiScreen(createException(tt.menu, tt.failMessage, u)); - }; - - public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, BooleanSupplier checkTaskComplete) { + + public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, + BooleanSupplier checkTaskComplete) { this(menu, progressMessage, failMessage, checkTaskComplete, defaultExceptionAction, defaultTerminateAction); } - - public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, BooleanSupplier checkTaskComplete, BiConsumer exceptionAction) { + + public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, + BooleanSupplier checkTaskComplete, BiConsumer exceptionAction) { this(menu, progressMessage, failMessage, checkTaskComplete, exceptionAction, defaultTerminateAction); } - - public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, BooleanSupplier checkTaskComplete, Runnable onTerminate) { - this(menu, progressMessage, failMessage, checkTaskComplete, defaultExceptionAction, onTerminate); - } - - public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, BooleanSupplier checkTaskComplete, BiConsumer onException, Runnable onTerminate) { + + public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, + BooleanSupplier checkTaskComplete, BiConsumer onException, + Runnable onTerminate) { this.menu = menu; this.failMessage = failMessage; this.checkTaskComplete = checkTaskComplete; @@ -86,86 +90,99 @@ public class GuiScreenIntegratedServerBusy extends GuiScreen { this.lastStatus = SingleplayerServerController.worldStatusString(); this.currentStatus = progressMessage; } - - public void initGui() { - if(startStartTime == 0) this.startStartTime = EagRuntime.steadyTimeMillis(); - areYouSure = 0; - this.buttonList.add(killTask = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, I18n.format("singleplayer.busy.killTask"))); - killTask.enabled = false; - } - - public boolean doesGuiPauseGame() { - return false; - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - int top = this.height / 3; - - long millis = EagRuntime.steadyTimeMillis(); - - String str = I18n.format(currentStatus); - - long dots = (millis / 500l) % 4l; - this.drawString(fontRendererObj, str + (dots > 0 ? "." : "") + (dots > 1 ? "." : "") + (dots > 2 ? "." : ""), (this.width - this.fontRendererObj.getStringWidth(str)) / 2, top + 10, 0xFFFFFF); - - if(areYouSure > 0) { - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.busy.cancelWarning"), this.width / 2, top + 25, 0xFF8888); - }else { - float prog = SingleplayerServerController.worldStatusProgress(); - if(this.currentStatus.equals(this.lastStatus) && prog > 0.01f) { - this.drawCenteredString(fontRendererObj, (prog > 1.0f ? ("(" + (prog > 1000000.0f ? "" + (int)(prog / 1000000.0f) + "MB" : - (prog > 1000.0f ? "" + (int)(prog / 1000.0f) + "kB" : "" + (int)prog + "B")) + ")") : "" + (int)(prog * 100.0f) + "%"), this.width / 2, top + 25, 0xFFFFFF); - }else { - long elapsed = (millis - startStartTime) / 1000l; - if(elapsed > 3) { - this.drawCenteredString(fontRendererObj, "(" + elapsed + "s)", this.width / 2, top + 25, 0xFFFFFF); - } - } - } - - super.drawScreen(par1, par2, par3); - } - - public void updateScreen() { - long millis = EagRuntime.steadyTimeMillis(); - if(millis - startStartTime > 6000l && SingleplayerServerController.canKillWorker()) { - killTask.enabled = true; - } - if(SingleplayerServerController.didLastCallFail() || !SingleplayerServerController.isIntegratedServerWorkerAlive()) { - onException.accept(this, SingleplayerServerController.worldStatusErrors()); - return; - } - if(checkTaskComplete.getAsBoolean()) { - this.mc.displayGuiScreen(menu); - } - String str = SingleplayerServerController.worldStatusString(); - if(!lastStatus.equals(str)) { - lastStatus = str; - currentStatus = str; - } - killTask.displayString = I18n.format(areYouSure > 0 ? "singleplayer.busy.confirmCancel" : "singleplayer.busy.killTask"); - if(areYouSure > 0) { - --areYouSure; - } + + public GuiScreenIntegratedServerBusy(GuiScreen menu, String progressMessage, String failMessage, + BooleanSupplier checkTaskComplete, Runnable onTerminate) { + this(menu, progressMessage, failMessage, checkTaskComplete, defaultExceptionAction, onTerminate); } protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - if(areYouSure <= 0) { + if (par1GuiButton.id == 0) { + if (areYouSure <= 0) { areYouSure = 80; - }else if(areYouSure <= 65) { + } else if (areYouSure <= 65) { taskKill.run(); } } } - public boolean shouldHangupIntegratedServer() { - return false; - } - public boolean canCloseGui() { return false; } + public boolean doesGuiPauseGame() { + return false; + } + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + int top = this.height / 3; + + long millis = EagRuntime.steadyTimeMillis(); + + String str = I18n.format(currentStatus); + + long dots = (millis / 500l) % 4l; + this.drawString(fontRendererObj, str + (dots > 0 ? "." : "") + (dots > 1 ? "." : "") + (dots > 2 ? "." : ""), + (this.width - this.fontRendererObj.getStringWidth(str)) / 2, top + 10, 0xFFFFFF); + + if (areYouSure > 0) { + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.busy.cancelWarning"), this.width / 2, + top + 25, 0xFF8888); + } else { + float prog = SingleplayerServerController.worldStatusProgress(); + if (this.currentStatus.equals(this.lastStatus) && prog > 0.01f) { + this.drawCenteredString(fontRendererObj, (prog > 1.0f + ? ("(" + (prog > 1000000.0f ? "" + (int) (prog / 1000000.0f) + "MB" + : (prog > 1000.0f ? "" + (int) (prog / 1000.0f) + "kB" : "" + (int) prog + "B")) + ")") + : "" + (int) (prog * 100.0f) + "%"), this.width / 2, top + 25, 0xFFFFFF); + } else { + long elapsed = (millis - startStartTime) / 1000l; + if (elapsed > 3) { + this.drawCenteredString(fontRendererObj, "(" + elapsed + "s)", this.width / 2, top + 25, 0xFFFFFF); + } + } + } + + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + if (startStartTime == 0) + this.startStartTime = EagRuntime.steadyTimeMillis(); + areYouSure = 0; + this.buttonList.add(killTask = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, + I18n.format("singleplayer.busy.killTask"))); + killTask.enabled = false; + } + + public boolean shouldHangupIntegratedServer() { + return false; + } + + public void updateScreen() { + long millis = EagRuntime.steadyTimeMillis(); + if (millis - startStartTime > 6000l && SingleplayerServerController.canKillWorker()) { + killTask.enabled = true; + } + if (SingleplayerServerController.didLastCallFail() + || !SingleplayerServerController.isIntegratedServerWorkerAlive()) { + onException.accept(this, SingleplayerServerController.worldStatusErrors()); + return; + } + if (checkTaskComplete.getAsBoolean()) { + this.mc.displayGuiScreen(menu); + } + String str = SingleplayerServerController.worldStatusString(); + if (!lastStatus.equals(str)) { + lastStatus = str; + currentStatus = str; + } + killTask.displayString = I18n + .format(areYouSure > 0 ? "singleplayer.busy.confirmCancel" : "singleplayer.busy.killTask"); + if (areYouSure > 0) { + --areYouSure; + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerCrashed.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerCrashed.java index aba74974..c40429ad 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerCrashed.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerCrashed.java @@ -7,14 +7,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,31 +29,34 @@ public class GuiScreenIntegratedServerCrashed extends GuiScreen { this.mainmenu = mainmenu; this.crashReport = crashReport; } - - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height - 50, I18n.format("singleplayer.crashed.continue"))); - int i = mc.scaledResolution.getScaleFactor(); - CrashScreen.showCrashReportOverlay(crashReport, 90 * i, 60 * i, (width - 180) * i, (height - 130) * i); + + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + this.mc.displayGuiScreen(mainmenu); + } } - - public void onGuiClosed() { - CrashScreen.hideCrashReportOverlay(); - } - + public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.crashed.title"), this.width / 2, 25, 0xFFAAAA); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.crashed.checkConsole"), this.width / 2, 40, 0xBBBBBB); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.crashed.title"), this.width / 2, 25, + 0xFFAAAA); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.crashed.checkConsole"), this.width / 2, 40, + 0xBBBBBB); super.drawScreen(par1, par2, par3); } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - this.mc.displayGuiScreen(mainmenu); - } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add( + new GuiButton(0, this.width / 2 - 100, this.height - 50, I18n.format("singleplayer.crashed.continue"))); + int i = mc.scaledResolution.getScaleFactor(); + CrashScreen.showCrashReportOverlay(crashReport, 90 * i, 60 * i, (width - 180) * i, (height - 130) * i); } - + + public void onGuiClosed() { + CrashScreen.hideCrashReportOverlay(); + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerFailed.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerFailed.java index aba653c0..d44846b0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerFailed.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerFailed.java @@ -10,14 +10,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,23 +29,26 @@ public class GuiScreenIntegratedServerFailed extends GuiScreen { private String str2; private GuiScreen cont; - public GuiScreenIntegratedServerFailed(String str1, String str2, GuiScreen cont) { - this.str1 = I18n.format(str1); - this.str2 = I18n.format(str2); - this.cont = cont; - } - public GuiScreenIntegratedServerFailed(String str2, GuiScreen cont) { this.str1 = I18n.format("singleplayer.failed.title"); this.str2 = I18n.format(str2); this.cont = cont; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("singleplayer.crashed.continue"))); - if(!ClientPlatformSingleplayer.isRunningSingleThreadMode() && ClientPlatformSingleplayer.isSingleThreadModeSupported()) { - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 126, I18n.format("singleplayer.crashed.singleThreadCont"))); + public GuiScreenIntegratedServerFailed(String str1, String str2, GuiScreen cont) { + this.str1 = I18n.format(str1); + this.str2 = I18n.format(str2); + this.cont = cont; + } + + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + this.mc.displayGuiScreen(cont); + } else if (par1GuiButton.id == 1) { + if (SingleplayerServerController.canKillWorker()) { + SingleplayerServerController.killWorker(); + } + this.mc.displayGuiScreen(new GuiScreenIntegratedServerStartup(new GuiMainMenu(), true)); } } @@ -55,14 +59,14 @@ public class GuiScreenIntegratedServerFailed extends GuiScreen { super.drawScreen(par1, par2, par3); } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - this.mc.displayGuiScreen(cont); - }else if(par1GuiButton.id == 1) { - if(SingleplayerServerController.canKillWorker()) { - SingleplayerServerController.killWorker(); - } - this.mc.displayGuiScreen(new GuiScreenIntegratedServerStartup(new GuiMainMenu(), true)); + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, + I18n.format("singleplayer.crashed.continue"))); + if (!ClientPlatformSingleplayer.isRunningSingleThreadMode() + && ClientPlatformSingleplayer.isSingleThreadModeSupported()) { + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 126, + I18n.format("singleplayer.crashed.singleThreadCont"))); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerStartup.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerStartup.java index 13ddcf05..098053ca 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerStartup.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenIntegratedServerStartup.java @@ -14,23 +14,24 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenIntegratedServerStartup extends GuiScreen { + private static final String[] dotDotDot = new String[] { "", ".", "..", "..." }; private final GuiScreen backScreen; private final boolean singleThread; - private static final String[] dotDotDot = new String[] { "", ".", "..", "..." }; private int counter = 0; @@ -46,32 +47,55 @@ public class GuiScreenIntegratedServerStartup extends GuiScreen { this.singleThread = singleThread; } + protected void actionPerformed(GuiButton parGuiButton) { + if (parGuiButton.id == 0) { + SingleplayerServerController.killWorker(); + mc.displayGuiScreen(new GuiScreenIntegratedServerStartup(new GuiMainMenu(), true)); + } + } + + public boolean canCloseGui() { + return false; + } + + public void drawScreen(int i, int j, float f) { + this.drawBackground(0); + String txt = I18n.format("singleplayer.integratedStartup"); + int w = this.fontRendererObj.getStringWidth(txt); + this.drawString(this.fontRendererObj, txt + dotDotDot[(int) ((EagRuntime.steadyTimeMillis() / 300L) % 4L)], + (this.width - w) / 2, this.height / 2 - 50, 16777215); + super.drawScreen(i, j, f); + } + public void initGui() { this.buttonList.clear(); - this.buttonList.add(cancelButton = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, I18n.format("singleplayer.busy.killTask"))); + this.buttonList.add(cancelButton = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, + I18n.format("singleplayer.busy.killTask"))); cancelButton.visible = false; } public void updateScreen() { ++counter; - if(counter == 2) { + if (counter == 2) { try { SingleplayerServerController.startIntegratedServerWorker(singleThread); - }catch(WorkerStartupFailedException ex) { + } catch (WorkerStartupFailedException ex) { mc.displayGuiScreen(new GuiScreenIntegratedServerFailed(ex.getMessage(), new GuiMainMenu())); return; } - }else if(counter > 2) { - if(counter > 100 && SingleplayerServerController.canKillWorker() && !singleThread) { + } else if (counter > 2) { + if (counter > 100 && SingleplayerServerController.canKillWorker() && !singleThread) { cancelButton.visible = true; } IPCPacket15Crashed[] crashReport = SingleplayerServerController.worldStatusErrors(); - if(crashReport != null) { - mc.displayGuiScreen(GuiScreenIntegratedServerBusy.createException(new GuiMainMenu(), "singleplayer.failed.notStarted", crashReport)); - }else if(SingleplayerServerController.isIntegratedServerWorkerStarted()) { + if (crashReport != null) { + mc.displayGuiScreen(GuiScreenIntegratedServerBusy.createException(new GuiMainMenu(), + "singleplayer.failed.notStarted", crashReport)); + } else if (SingleplayerServerController.isIntegratedServerWorkerStarted()) { GuiScreen cont = new GuiSelectWorld(backScreen); - if(SingleplayerServerController.isRunningSingleThreadMode()) { - cont = new GuiScreenIntegratedServerFailed("singleplayer.failed.singleThreadWarning.1", "singleplayer.failed.singleThreadWarning.2", cont); + if (SingleplayerServerController.isRunningSingleThreadMode()) { + cont = new GuiScreenIntegratedServerFailed("singleplayer.failed.singleThreadWarning.1", + "singleplayer.failed.singleThreadWarning.2", cont); } else if (!EagRuntime.getConfiguration().isRamdiskMode() && SingleplayerServerController.isIssueDetected(IPCPacket1CIssueDetected.ISSUE_RAMDISK_MODE) && SingleplayerServerController.canKillWorker()) { @@ -82,23 +106,4 @@ public class GuiScreenIntegratedServerStartup extends GuiScreen { } } - protected void actionPerformed(GuiButton parGuiButton) { - if(parGuiButton.id == 0) { - SingleplayerServerController.killWorker(); - mc.displayGuiScreen(new GuiScreenIntegratedServerStartup(new GuiMainMenu(), true)); - } - } - - public void drawScreen(int i, int j, float f) { - this.drawBackground(0); - String txt = I18n.format("singleplayer.integratedStartup"); - int w = this.fontRendererObj.getStringWidth(txt); - this.drawString(this.fontRendererObj, txt + dotDotDot[(int)((EagRuntime.steadyTimeMillis() / 300L) % 4L)], (this.width - w) / 2, this.height / 2 - 50, 16777215); - super.drawScreen(i, j, f); - } - - public boolean canCloseGui() { - return false; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnect.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnect.java index 7853f459..0385a4ec 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnect.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnect.java @@ -10,48 +10,75 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenLANConnect extends GuiScreen { + private static String lastCode = ""; private final GuiScreen parent; private GuiTextField codeTextField; - private final GuiNetworkSettingsButton relaysButton; - private static String lastCode = ""; + private final GuiNetworkSettingsButton relaysButton; public GuiScreenLANConnect(GuiScreen parent) { this.parent = parent; this.relaysButton = new GuiNetworkSettingsButton(this); } + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 1) { + mc.displayGuiScreen(parent); + } else if (par1GuiButton.id == 0) { + mc.displayGuiScreen(new GuiScreenLANConnecting(parent, this.codeTextField.getText().trim())); + } + } + + public void drawScreen(int xx, int yy, float pt) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("selectServer.direct"), this.width / 2, + this.height / 4 - 60 + 20, 16777215); + this.drawString(this.fontRendererObj, I18n.format("directConnect.lanWorldCode"), this.width / 2 - 100, + this.height / 4 + 12, 10526880); + this.drawCenteredString(this.fontRendererObj, I18n.format("directConnect.networkSettingsNote"), this.width / 2, + this.height / 4 + 63, 10526880); + this.drawCenteredString(this.fontRendererObj, I18n.format("directConnect.ipGrabNote"), this.width / 2, + this.height / 4 + 77, 10526880); + this.codeTextField.drawTextBox(); + super.drawScreen(xx, yy, pt); + this.relaysButton.drawScreen(xx, yy); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + codeTextField.fireInputEvent(event, param); + } + public void initGui() { Keyboard.enableRepeatEvents(true); this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, I18n.format("directConnect.lanWorldJoin"))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, I18n.format("gui.cancel"))); - this.codeTextField = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 27, 200, 20); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, + I18n.format("directConnect.lanWorldJoin"))); + this.buttonList + .add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, I18n.format("gui.cancel"))); + this.codeTextField = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 27, 200, + 20); this.codeTextField.setMaxStringLength(48); this.codeTextField.setFocused(true); this.codeTextField.setText(lastCode); this.buttonList.get(0).enabled = this.codeTextField.getText().trim().length() > 0; } - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - lastCode = this.codeTextField.getText().trim(); - } - protected void keyTyped(char par1, int par2) { if (this.codeTextField.textboxKeyTyped(par1, par2)) { ((GuiButton) this.buttonList.get(0)).enabled = this.codeTextField.getText().trim().length() > 0; @@ -60,33 +87,15 @@ public class GuiScreenLANConnect extends GuiScreen { } } - public void updateScreen() { - this.codeTextField.updateCursorCounter(); - } - protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); this.codeTextField.mouseClicked(par1, par2, par3); this.relaysButton.mouseClicked(par1, par2, par3); } - public void drawScreen(int xx, int yy, float pt) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("selectServer.direct"), this.width / 2, this.height / 4 - 60 + 20, 16777215); - this.drawString(this.fontRendererObj, I18n.format("directConnect.lanWorldCode"), this.width / 2 - 100, this.height / 4 + 12, 10526880); - this.drawCenteredString(this.fontRendererObj, I18n.format("directConnect.networkSettingsNote"), this.width / 2, this.height / 4 + 63, 10526880); - this.drawCenteredString(this.fontRendererObj, I18n.format("directConnect.ipGrabNote"), this.width / 2, this.height / 4 + 77, 10526880); - this.codeTextField.drawTextBox(); - super.drawScreen(xx, yy, pt); - this.relaysButton.drawScreen(xx, yy); - } - - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 1) { - mc.displayGuiScreen(parent); - }else if(par1GuiButton.id == 0) { - mc.displayGuiScreen(new GuiScreenLANConnecting(parent, this.codeTextField.getText().trim())); - } + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); + lastCode = this.codeTextField.getText().trim(); } @Override @@ -94,9 +103,8 @@ public class GuiScreenLANConnect extends GuiScreen { return codeTextField.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - codeTextField.fireInputEvent(event, param); + public void updateScreen() { + this.codeTextField.updateCursorCounter(); } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnecting.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnecting.java index 26e4cba1..eee87d58 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnecting.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANConnecting.java @@ -1,5 +1,7 @@ package net.lax1dude.eaglercraft.v1_8.sp.gui; +import java.io.IOException; + import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; import net.lax1dude.eaglercraft.v1_8.internal.PlatformWebRTC; import net.lax1dude.eaglercraft.v1_8.profile.EaglerProfile; @@ -19,19 +21,18 @@ import net.minecraft.network.EnumConnectionState; import net.minecraft.network.login.client.C00PacketLoginStart; import net.minecraft.util.ChatComponentText; -import java.io.IOException; - /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,58 +62,49 @@ public class GuiScreenLANConnecting extends GuiScreen { Minecraft.getMinecraft().setServerData(new ServerData("Shared World", "shared:" + relay.address, false)); } + public boolean canCloseGui() { + return false; + } + public boolean doesGuiPauseGame() { return false; } - public void updateScreen() { - if(networkManager != null) { - if (networkManager.isChannelOpen()) { - try { - networkManager.processReceivedPackets(); - } catch (IOException ex) { - } - } else { - if (networkManager.checkDisconnected()) { - this.mc.getSession().reset(); - if (mc.currentScreen == this) { - mc.loadWorld(null); - mc.displayGuiScreen(new GuiDisconnected(parent, "connect.failed", new ChatComponentText("LAN Connection Refused"))); - } - } - } - } - } - public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); - if(completed) { + if (completed) { String message = I18n.format("connect.authorizing"); - this.drawString(fontRendererObj, message, (this.width - this.fontRendererObj.getStringWidth(message)) / 2, this.height / 3 + 10, 0xFFFFFF); - }else { + this.drawString(fontRendererObj, message, (this.width - this.fontRendererObj.getStringWidth(message)) / 2, + this.height / 3 + 10, 0xFFFFFF); + } else { LoadingScreenRenderer ls = mc.loadingScreen; String message = I18n.format("lanServer.pleaseWait"); - this.drawString(fontRendererObj, message, (this.width - this.fontRendererObj.getStringWidth(message)) / 2, this.height / 3 + 10, 0xFFFFFF); + this.drawString(fontRendererObj, message, (this.width - this.fontRendererObj.getStringWidth(message)) / 2, + this.height / 3 + 10, 0xFFFFFF); PlatformWebRTC.startRTCLANClient(); - if(++renderCount > 1) { + if (++renderCount > 1) { RelayServerSocket sock; - if(relay == null) { - sock = RelayManager.relayManager.getWorkingRelay((str) -> ls.resetProgressAndMessage("Connecting: " + str), 0x02, code); - }else { + if (relay == null) { + sock = RelayManager.relayManager + .getWorkingRelay((str) -> ls.resetProgressAndMessage("Connecting: " + str), 0x02, code); + } else { sock = RelayManager.relayManager.connectHandshake(relay, 0x02, code); } - if(sock == null) { - this.mc.displayGuiScreen(new GuiScreenNoRelays(parent, I18n.format("noRelay.worldNotFound1").replace("$code$", code), - I18n.format("noRelay.worldNotFound2").replace("$code$", code), I18n.format("noRelay.worldNotFound3"))); + if (sock == null) { + this.mc.displayGuiScreen( + new GuiScreenNoRelays(parent, I18n.format("noRelay.worldNotFound1").replace("$code$", code), + I18n.format("noRelay.worldNotFound2").replace("$code$", code), + I18n.format("noRelay.worldNotFound3"))); return; } networkManager = LANClientNetworkManager.connectToWorld(sock, code, sock.getURI()); - if(networkManager == null) { - this.mc.displayGuiScreen(new GuiDisconnected(parent, "connect.failed", new ChatComponentText(I18n.format("noRelay.worldFail").replace("$code$", code)))); + if (networkManager == null) { + this.mc.displayGuiScreen(new GuiDisconnected(parent, "connect.failed", + new ChatComponentText(I18n.format("noRelay.worldFail").replace("$code$", code)))); return; } @@ -129,8 +121,24 @@ public class GuiScreenLANConnecting extends GuiScreen { } } - public boolean canCloseGui() { - return false; + public void updateScreen() { + if (networkManager != null) { + if (networkManager.isChannelOpen()) { + try { + networkManager.processReceivedPackets(); + } catch (IOException ex) { + } + } else { + if (networkManager.checkDisconnected()) { + this.mc.getSession().reset(); + if (mc.currentScreen == this) { + mc.loadWorld(null); + mc.displayGuiScreen(new GuiDisconnected(parent, "connect.failed", + new ChatComponentText("LAN Connection Refused"))); + } + } + } + } } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANInfo.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANInfo.java index 8890ec3f..a64de6b1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANInfo.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANInfo.java @@ -7,52 +7,59 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenLANInfo extends GuiScreen { + private static boolean hasShown = false; + + public static GuiScreen showLANInfoScreen(GuiScreen cont) { + if (!hasShown) { + hasShown = true; + return new GuiScreenLANInfo(cont); + } else { + return cont; + } + } + private GuiScreen parent; public GuiScreenLANInfo(GuiScreen parent) { this.parent = parent; } + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + mc.displayGuiScreen(parent); + } + } + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format("lanInfo.title"), this.width / 2, + this.height / 4 - 60 + 20, 16777215); + this.fontRendererObj + .drawSplitString( + I18n.format("lanInfo.desc.0") + "\n\n\n" + + I18n.format("lanInfo.desc.1", I18n.format("menu.multiplayer"), + I18n.format("menu.openToLan")), + this.width / 2 - 100, this.height / 4 - 60 + 60, 200, -6250336); + super.drawScreen(par1, par2, par3); + } + public void initGui() { buttonList.clear(); buttonList.add(new GuiButton(0, this.width / 2 - 100, height / 6 + 168, I18n.format("gui.continue"))); } - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("lanInfo.title"), this.width / 2, this.height / 4 - 60 + 20, 16777215); - this.fontRendererObj.drawSplitString(I18n.format("lanInfo.desc.0") + "\n\n\n" + I18n.format("lanInfo.desc.1", I18n.format("menu.multiplayer"), I18n.format("menu.openToLan")), this.width / 2 - 100, this.height / 4 - 60 + 60, 200, -6250336); - super.drawScreen(par1, par2, par3); - } - - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - mc.displayGuiScreen(parent); - } - } - - private static boolean hasShown = false; - - public static GuiScreen showLANInfoScreen(GuiScreen cont) { - if(!hasShown) { - hasShown = true; - return new GuiScreenLANInfo(cont); - }else { - return cont; - } - } - } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANNotSupported.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANNotSupported.java index 1d1fc598..72eec992 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANNotSupported.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenLANNotSupported.java @@ -7,14 +7,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,22 +28,25 @@ public class GuiScreenLANNotSupported extends GuiScreen { this.cont = cont; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("singleplayer.crashed.continue"))); - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.notSupported.title"), this.width / 2, 70, 11184810); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.notSupported.desc"), this.width / 2, 90, 16777215); - super.drawScreen(par1, par2, par3); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { this.mc.displayGuiScreen(cont); } } + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.notSupported.title"), this.width / 2, 70, + 11184810); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.notSupported.desc"), this.width / 2, 90, + 16777215); + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, + I18n.format("singleplayer.crashed.continue"))); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNameWorldImport.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNameWorldImport.java index ff8c54d6..e632c375 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNameWorldImport.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNameWorldImport.java @@ -14,14 +14,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,49 +46,11 @@ public class GuiScreenNameWorldImport extends GuiScreen { this.importFormat = format; this.world = world; this.name = world.fileName; - if(name.length() > 4 && (name.endsWith(".epk") || name.endsWith(".zip"))) { + if (name.length() > 4 && (name.endsWith(".epk") || name.endsWith(".zip"))) { name = name.substring(0, name.length() - 4); } } - /** - * Called from the main game loop to update the screen. - */ - public void updateScreen() { - if(!timeToImport) { - this.theGuiTextField.updateCursorCounter(); - } - if(definetlyTimeToImport && !isImporting) { - isImporting = true; - SingleplayerServerController.importWorld(GuiCreateWorld.func_146317_a(mc.getSaveLoader(), this.theGuiTextField.getText().trim()), world.fileData, importFormat, (byte) ((loadSpawnChunks ? 2 : 0) | (enhancedGameRules ? 1 : 0))); - mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(parentGuiScreen, "singleplayer.busy.importing." + (importFormat + 1), "singleplayer.failed.importing." + (importFormat + 1), SingleplayerServerController::isReady)); - } - } - - /** - * Adds the buttons (and other controls) to the screen in question. - */ - public void initGui() { - if(!timeToImport) { - Keyboard.enableRepeatEvents(true); - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, I18n.format("singleplayer.import.continue"))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, I18n.format("gui.cancel"))); - this.theGuiTextField = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 3, 200, 20); - this.theGuiTextField.setFocused(true); - this.theGuiTextField.setText(name); - this.buttonList.add(loadSpawnChunksBtn = new GuiButton(2, this.width / 2 - 100, this.height / 4 + 24 + 12, I18n.format("singleplayer.import.loadSpawnChunks", loadSpawnChunks ? I18n.format("gui.yes") : I18n.format("gui.no")))); - this.buttonList.add(enhancedGameRulesBtn = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 48 + 12, I18n.format("singleplayer.import.enhancedGameRules", enhancedGameRules ? I18n.format("gui.yes") : I18n.format("gui.no")))); - } - } - - /** - * Called when the screen is unloaded. Used to disable keyboard repeat events - */ - public void onGuiClosed() { - Keyboard.enableRepeatEvents(false); - } - /** * Fired when a control is clicked. This is the equivalent of * ActionListener.actionPerformed(ActionEvent e). @@ -102,14 +65,69 @@ public class GuiScreenNameWorldImport extends GuiScreen { timeToImport = true; } else if (par1GuiButton.id == 2) { loadSpawnChunks = !loadSpawnChunks; - loadSpawnChunksBtn.displayString = I18n.format("singleplayer.import.loadSpawnChunks", loadSpawnChunks ? I18n.format("gui.yes") : I18n.format("gui.no")); + loadSpawnChunksBtn.displayString = I18n.format("singleplayer.import.loadSpawnChunks", + loadSpawnChunks ? I18n.format("gui.yes") : I18n.format("gui.no")); } else if (par1GuiButton.id == 3) { enhancedGameRules = !enhancedGameRules; - enhancedGameRulesBtn.displayString = I18n.format("singleplayer.import.enhancedGameRules", enhancedGameRules ? I18n.format("gui.yes") : I18n.format("gui.no")); + enhancedGameRulesBtn.displayString = I18n.format("singleplayer.import.enhancedGameRules", + enhancedGameRules ? I18n.format("gui.yes") : I18n.format("gui.no")); } } } + /** + * Draws the screen and all the components in it. + */ + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + if (!timeToImport) { + this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.import.title"), this.width / 2, + this.height / 4 - 60 + 20, 16777215); + this.drawString(this.fontRendererObj, I18n.format("singleplayer.import.enterName"), this.width / 2 - 100, + this.height / 4 - 60 + 50, 10526880); + this.drawCenteredString(this.fontRendererObj, I18n.format("createWorld.seedNote"), this.width / 2, + this.height / 4 + 90, -6250336); + this.theGuiTextField.drawTextBox(); + } else { + definetlyTimeToImport = true; + long dots = (EagRuntime.steadyTimeMillis() / 500l) % 4l; + String str = I18n.format("singleplayer.import.reading", world.fileName); + this.drawString(fontRendererObj, + str + (dots > 0 ? "." : "") + (dots > 1 ? "." : "") + (dots > 2 ? "." : ""), + (this.width - this.fontRendererObj.getStringWidth(str)) / 2, this.height / 3 + 10, 0xFFFFFF); + } + super.drawScreen(par1, par2, par3); + } + + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + theGuiTextField.fireInputEvent(event, param); + } + + /** + * Adds the buttons (and other controls) to the screen in question. + */ + public void initGui() { + if (!timeToImport) { + Keyboard.enableRepeatEvents(true); + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 + 96 + 12, + I18n.format("singleplayer.import.continue"))); + this.buttonList + .add(new GuiButton(1, this.width / 2 - 100, this.height / 4 + 120 + 12, I18n.format("gui.cancel"))); + this.theGuiTextField = new GuiTextField(2, this.fontRendererObj, this.width / 2 - 100, this.height / 4 + 3, + 200, 20); + this.theGuiTextField.setFocused(true); + this.theGuiTextField.setText(name); + this.buttonList.add(loadSpawnChunksBtn = new GuiButton(2, this.width / 2 - 100, this.height / 4 + 24 + 12, + I18n.format("singleplayer.import.loadSpawnChunks", + loadSpawnChunks ? I18n.format("gui.yes") : I18n.format("gui.no")))); + this.buttonList.add(enhancedGameRulesBtn = new GuiButton(3, this.width / 2 - 100, this.height / 4 + 48 + 12, + I18n.format("singleplayer.import.enhancedGameRules", + enhancedGameRules ? I18n.format("gui.yes") : I18n.format("gui.no")))); + } + } + /** * Fired when a key is typed. This is the equivalent of * KeyListener.keyTyped(KeyEvent e). @@ -128,28 +146,16 @@ public class GuiScreenNameWorldImport extends GuiScreen { */ protected void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); - if(!timeToImport) { + if (!timeToImport) { this.theGuiTextField.mouseClicked(par1, par2, par3); } } /** - * Draws the screen and all the components in it. + * Called when the screen is unloaded. Used to disable keyboard repeat events */ - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - if(!timeToImport) { - this.drawCenteredString(this.fontRendererObj, I18n.format("singleplayer.import.title"), this.width / 2, this.height / 4 - 60 + 20, 16777215); - this.drawString(this.fontRendererObj, I18n.format("singleplayer.import.enterName"), this.width / 2 - 100, this.height / 4 - 60 + 50, 10526880); - this.drawCenteredString(this.fontRendererObj, I18n.format("createWorld.seedNote"), this.width / 2, this.height / 4 + 90, -6250336); - this.theGuiTextField.drawTextBox(); - }else { - definetlyTimeToImport = true; - long dots = (EagRuntime.steadyTimeMillis() / 500l) % 4l; - String str = I18n.format("singleplayer.import.reading", world.fileName); - this.drawString(fontRendererObj, str + (dots > 0 ? "." : "") + (dots > 1 ? "." : "") + (dots > 2 ? "." : ""), (this.width - this.fontRendererObj.getStringWidth(str)) / 2, this.height / 3 + 10, 0xFFFFFF); - } - super.drawScreen(par1, par2, par3); + public void onGuiClosed() { + Keyboard.enableRepeatEvents(false); } @Override @@ -157,9 +163,22 @@ public class GuiScreenNameWorldImport extends GuiScreen { return theGuiTextField.isFocused(); } - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - theGuiTextField.fireInputEvent(event, param); + /** + * Called from the main game loop to update the screen. + */ + public void updateScreen() { + if (!timeToImport) { + this.theGuiTextField.updateCursorCounter(); + } + if (definetlyTimeToImport && !isImporting) { + isImporting = true; + SingleplayerServerController.importWorld( + GuiCreateWorld.func_146317_a(mc.getSaveLoader(), this.theGuiTextField.getText().trim()), + world.fileData, importFormat, (byte) ((loadSpawnChunks ? 2 : 0) | (enhancedGameRules ? 1 : 0))); + mc.displayGuiScreen(new GuiScreenIntegratedServerBusy(parentGuiScreen, + "singleplayer.busy.importing." + (importFormat + 1), + "singleplayer.failed.importing." + (importFormat + 1), SingleplayerServerController::isReady)); + } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNoRelays.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNoRelays.java index d4402d24..9efa9625 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNoRelays.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenNoRelays.java @@ -7,14 +7,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,30 +41,34 @@ public class GuiScreenNoRelays extends GuiScreen { this.title3 = title3; } - public void initGui() { - buttonList.clear(); - buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 - 60 + 145, I18n.format("gui.cancel"))); - buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 - 60 + 115, I18n.format("directConnect.lanWorldRelay"))); - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format(title1), this.width / 2, this.height / 4 - 60 + 70, 16777215); - if(title2 != null) { - this.drawCenteredString(this.fontRendererObj, I18n.format(title2), this.width / 2, this.height / 4 - 60 + 80, 0xCCCCCC); - } - if(title3 != null) { - this.drawCenteredString(this.fontRendererObj, I18n.format(title3), this.width / 2, this.height / 4 - 60 + 90, 0xCCCCCC); - } - super.drawScreen(par1, par2, par3); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { mc.displayGuiScreen(parent); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { mc.displayGuiScreen(GuiScreenLANInfo.showLANInfoScreen(new GuiScreenRelay(parent))); } } + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(this.fontRendererObj, I18n.format(title1), this.width / 2, this.height / 4 - 60 + 70, + 16777215); + if (title2 != null) { + this.drawCenteredString(this.fontRendererObj, I18n.format(title2), this.width / 2, + this.height / 4 - 60 + 80, 0xCCCCCC); + } + if (title3 != null) { + this.drawCenteredString(this.fontRendererObj, I18n.format(title3), this.width / 2, + this.height / 4 - 60 + 90, 0xCCCCCC); + } + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + buttonList.clear(); + buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 4 - 60 + 145, I18n.format("gui.cancel"))); + buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 4 - 60 + 115, + I18n.format("directConnect.lanWorldRelay"))); + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenOldSeedWarning.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenOldSeedWarning.java index c13e4aa4..12c36a89 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenOldSeedWarning.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenOldSeedWarning.java @@ -7,14 +7,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,22 +28,26 @@ public class GuiScreenOldSeedWarning extends GuiScreen { this.cont = cont; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, I18n.format("singleplayer.oldseedwarning.ok"))); + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + this.mc.displayGuiScreen(cont); + } } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.oldseedwarning.title"), this.width / 2, 70, 11184810); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.oldseedwarning.msg1"), this.width / 2, 90, 16777215); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.oldseedwarning.msg2"), this.width / 2, 105, 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.oldseedwarning.title"), this.width / 2, 70, + 11184810); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.oldseedwarning.msg1"), this.width / 2, 90, + 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.oldseedwarning.msg2"), this.width / 2, 105, + 16777215); super.drawScreen(par1, par2, par3); } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - this.mc.displayGuiScreen(cont); - } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 96, + I18n.format("singleplayer.oldseedwarning.ok"))); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRAMDiskModeDetected.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRAMDiskModeDetected.java index 732f88d6..884c2b75 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRAMDiskModeDetected.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRAMDiskModeDetected.java @@ -9,14 +9,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,27 +30,32 @@ public class GuiScreenRAMDiskModeDetected extends GuiScreen { this.cont = cont; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 106, I18n.format("singleplayer.ramdiskdetected.continue"))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 136, I18n.format("singleplayer.ramdiskdetected.singleThreadCont"))); - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.ramdiskdetected.title"), this.width / 2, 70, 11184810); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.ramdiskdetected.text0"), this.width / 2, 90, 16777215); - this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.ramdiskdetected.text1"), this.width / 2, 105, 16777215); - super.drawScreen(par1, par2, par3); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { + if (par1GuiButton.id == 0) { this.mc.displayGuiScreen(cont); - }else if(par1GuiButton.id == 1) { + } else if (par1GuiButton.id == 1) { SingleplayerServerController.killWorker(); mc.displayGuiScreen(new GuiScreenIntegratedServerStartup(new GuiMainMenu(), true)); } } + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.ramdiskdetected.title"), this.width / 2, 70, + 11184810); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.ramdiskdetected.text0"), this.width / 2, 90, + 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("singleplayer.ramdiskdetected.text1"), this.width / 2, 105, + 16777215); + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 106, + I18n.format("singleplayer.ramdiskdetected.continue"))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 136, + I18n.format("singleplayer.ramdiskdetected.singleThreadCont"))); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRelay.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRelay.java index 8f10ec17..c7662798 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRelay.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenRelay.java @@ -1,5 +1,7 @@ package net.lax1dude.eaglercraft.v1_8.sp.gui; +import java.io.IOException; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.Mouse; import net.lax1dude.eaglercraft.v1_8.internal.EnumCursorType; @@ -8,128 +10,127 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayManager; import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayServer; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; -import net.minecraft.client.gui.*; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.gui.GuiYesNo; +import net.minecraft.client.gui.GuiYesNoCallback; import net.minecraft.client.resources.I18n; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; -import java.io.IOException; - /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiScreenRelay extends GuiScreen implements GuiYesNoCallback { + static Minecraft getMinecraft(GuiScreenRelay screen) { + return screen.mc; + } + private final GuiScreen screen; private GuiSlotRelay slots; private boolean hasPinged; private boolean addingNew = false; private boolean deleting = false; - int selected; + int selected; private GuiButton deleteRelay; + private GuiButton setPrimary; private String tooltipString = null; private long lastRefresh = 0l; + private int mx = 0; + + private int my = 0; + + String addNewName; + + String addNewAddr; + + boolean addNewPrimary; + public GuiScreenRelay(GuiScreen screen) { this.screen = screen; } - public void initGui() { - selected = -1; - buttonList.clear(); - buttonList.add(new GuiButton(0, this.width / 2 + 54, this.height - 28, 100, 20, I18n.format("gui.done"))); - buttonList.add(new GuiButton(1, this.width / 2 - 154, this.height - 52, 100, 20, I18n.format("networkSettings.add"))); - buttonList.add(deleteRelay = new GuiButton(2, this.width / 2 - 50, this.height - 52, 100, 20, I18n.format("networkSettings.delete"))); - buttonList.add(setPrimary = new GuiButton(3, this.width / 2 + 54, this.height - 52, 100, 20, I18n.format("networkSettings.default"))); - buttonList.add(new GuiButton(4, this.width / 2 - 50, this.height - 28, 100, 20, I18n.format("networkSettings.refresh"))); - buttonList.add(new GuiButton(5, this.width / 2 - 154, this.height - 28, 100, 20, I18n.format("networkSettings.loadDefaults"))); - buttonList.add(new GuiButton(6, this.width - 100, 0, 100, 20, I18n.format("networkSettings.downloadRelay"))); - updateButtons(); - this.slots = new GuiSlotRelay(this); - if(!hasPinged) { - hasPinged = true; - slots.relayManager.ping(); - } - } - - void updateButtons() { - if(selected < 0) { - deleteRelay.enabled = false; - setPrimary.enabled = false; - }else { - deleteRelay.enabled = true; - setPrimary.enabled = true; - } - } - public void actionPerformed(GuiButton btn) { - if(btn.id == 0) { + if (btn.id == 0) { RelayManager.relayManager.save(); mc.displayGuiScreen(screen); - } else if(btn.id == 1) { + } else if (btn.id == 1) { addingNew = true; mc.displayGuiScreen(new GuiScreenAddRelay(this)); - } else if(btn.id == 2) { - if(selected >= 0) { + } else if (btn.id == 2) { + if (selected >= 0) { RelayServer srv = RelayManager.relayManager.get(selected); - mc.displayGuiScreen(new GuiYesNo(this, I18n.format("networkSettings.delete"), I18n.format("addRelay.removeText1") + - EnumChatFormatting.GRAY + " '" + srv.comment + "' (" + srv.address + ")", selected)); + mc.displayGuiScreen( + new GuiYesNo( + this, I18n.format("networkSettings.delete"), I18n.format("addRelay.removeText1") + + EnumChatFormatting.GRAY + " '" + srv.comment + "' (" + srv.address + ")", + selected)); deleting = true; } - } else if(btn.id == 3) { - if(selected >= 0) { + } else if (btn.id == 3) { + if (selected >= 0) { slots.relayManager.setPrimary(selected); selected = 0; } - } else if(btn.id == 4) { + } else if (btn.id == 4) { long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastRefresh > 700l) { + if (millis - lastRefresh > 700l) { lastRefresh = millis; slots.relayManager.ping(); } lastRefresh += 60l; - } else if(btn.id == 5) { + } else if (btn.id == 5) { slots.relayManager.loadDefaults(); long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastRefresh > 700l) { + if (millis - lastRefresh > 700l) { lastRefresh = millis; slots.relayManager.ping(); } lastRefresh += 60l; - } else if(btn.id == 6) { - EagRuntime.downloadFileWithName("EaglerSPRelay.zip", EagRuntime.getRequiredResourceBytes("relay_download.zip")); + } else if (btn.id == 6) { + EagRuntime.downloadFileWithName("EaglerSPRelay.zip", + EagRuntime.getRequiredResourceBytes("relay_download.zip")); } } - public void updateScreen() { - slots.relayManager.update(); - } - - private int mx = 0; - private int my = 0; - - int getFrameMouseX() { - return mx; - } - - int getFrameMouseY() { - return my; + public void confirmClicked(boolean par1, int par2) { + if (par1) { + if (addingNew) { + RelayManager.relayManager.addNew(addNewAddr, addNewName, addNewPrimary); + addNewAddr = null; + addNewName = null; + addNewPrimary = false; + selected = -1; + updateButtons(); + } else if (deleting) { + RelayManager.relayManager.remove(par2); + selected = -1; + updateButtons(); + } + } + addingNew = false; + deleting = false; + this.mc.displayGuiScreen(this); } public void drawScreen(int par1, int par2, float par3) { @@ -137,7 +138,7 @@ public class GuiScreenRelay extends GuiScreen implements GuiYesNoCallback { my = par2; slots.drawScreen(par1, par2, par3); - if(tooltipString != null) { + if (tooltipString != null) { int ww = mc.fontRendererObj.getStringWidth(tooltipString); Gui.drawRect(par1 + 1, par2 - 14, par1 + ww + 7, par2 - 2, 0xC0000000); screen.drawString(mc.fontRendererObj, tooltipString, par1 + 4, par2 - 12, 0xFF999999); @@ -156,57 +157,22 @@ public class GuiScreenRelay extends GuiScreen implements GuiYesNoCallback { str = EnumChatFormatting.UNDERLINE + I18n.format("networkSettings.relayTimeoutChange"); int w2 = fontRendererObj.getStringWidth(str); boolean b = par1 > w + 5 && par1 < w + 7 + w2 * 3 / 4 && par2 > 3 && par2 < 11; - if(b) Mouse.showCursor(EnumCursorType.HAND); - this.drawString(fontRendererObj, EnumChatFormatting.UNDERLINE + I18n.format("networkSettings.relayTimeoutChange"), 0, 0, b ? 0xCCCCCC : 0x999999); + if (b) + Mouse.showCursor(EnumCursorType.HAND); + this.drawString(fontRendererObj, + EnumChatFormatting.UNDERLINE + I18n.format("networkSettings.relayTimeoutChange"), 0, 0, + b ? 0xCCCCCC : 0x999999); GlStateManager.popMatrix(); super.drawScreen(par1, par2, par3); } - protected void mouseClicked(int par1, int par2, int par3) { - super.mouseClicked(par1, par2, par3); - if(par3 == 0) { - String str = I18n.format("networkSettings.relayTimeout") + " " + mc.gameSettings.relayTimeout; - int w = fontRendererObj.getStringWidth(str); - str = I18n.format("networkSettings.relayTimeoutChange"); - int w2 = fontRendererObj.getStringWidth(str); - if(par1 > w + 5 && par1 < w + 7 + w2 * 3 / 4 && par2 > 3 && par2 < 11) { - this.mc.displayGuiScreen(new GuiScreenChangeRelayTimeout(this)); - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - } - } + int getFrameMouseX() { + return mx; } - void setToolTip(String str) { - tooltipString = str; - } - - String addNewName; - String addNewAddr; - boolean addNewPrimary; - - public void confirmClicked(boolean par1, int par2) { - if(par1) { - if(addingNew) { - RelayManager.relayManager.addNew(addNewAddr, addNewName, addNewPrimary); - addNewAddr = null; - addNewName = null; - addNewPrimary = false; - selected = -1; - updateButtons(); - }else if(deleting) { - RelayManager.relayManager.remove(par2); - selected = -1; - updateButtons(); - } - } - addingNew = false; - deleting = false; - this.mc.displayGuiScreen(this); - } - - static Minecraft getMinecraft(GuiScreenRelay screen) { - return screen.mc; + int getFrameMouseY() { + return my; } @Override @@ -221,4 +187,60 @@ public class GuiScreenRelay extends GuiScreen implements GuiYesNoCallback { this.slots.handleTouchInput(); } + public void initGui() { + selected = -1; + buttonList.clear(); + buttonList.add(new GuiButton(0, this.width / 2 + 54, this.height - 28, 100, 20, I18n.format("gui.done"))); + buttonList.add( + new GuiButton(1, this.width / 2 - 154, this.height - 52, 100, 20, I18n.format("networkSettings.add"))); + buttonList.add(deleteRelay = new GuiButton(2, this.width / 2 - 50, this.height - 52, 100, 20, + I18n.format("networkSettings.delete"))); + buttonList.add(setPrimary = new GuiButton(3, this.width / 2 + 54, this.height - 52, 100, 20, + I18n.format("networkSettings.default"))); + buttonList.add(new GuiButton(4, this.width / 2 - 50, this.height - 28, 100, 20, + I18n.format("networkSettings.refresh"))); + buttonList.add(new GuiButton(5, this.width / 2 - 154, this.height - 28, 100, 20, + I18n.format("networkSettings.loadDefaults"))); + buttonList.add(new GuiButton(6, this.width - 100, 0, 100, 20, I18n.format("networkSettings.downloadRelay"))); + updateButtons(); + this.slots = new GuiSlotRelay(this); + if (!hasPinged) { + hasPinged = true; + slots.relayManager.ping(); + } + } + + protected void mouseClicked(int par1, int par2, int par3) { + super.mouseClicked(par1, par2, par3); + if (par3 == 0) { + String str = I18n.format("networkSettings.relayTimeout") + " " + mc.gameSettings.relayTimeout; + int w = fontRendererObj.getStringWidth(str); + str = I18n.format("networkSettings.relayTimeoutChange"); + int w2 = fontRendererObj.getStringWidth(str); + if (par1 > w + 5 && par1 < w + 7 + w2 * 3 / 4 && par2 > 3 && par2 < 11) { + this.mc.displayGuiScreen(new GuiScreenChangeRelayTimeout(this)); + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } + } + } + + void setToolTip(String str) { + tooltipString = str; + } + + void updateButtons() { + if (selected < 0) { + deleteRelay.enabled = false; + setPrimary.enabled = false; + } else { + deleteRelay.enabled = true; + setPrimary.enabled = true; + } + } + + public void updateScreen() { + slots.relayManager.update(); + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenSingleplayerConnecting.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenSingleplayerConnecting.java index 89f8d6f4..be867987 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenSingleplayerConnecting.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiScreenSingleplayerConnecting.java @@ -21,14 +21,15 @@ import net.minecraft.util.ChatComponentText; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,43 +41,64 @@ public class GuiScreenSingleplayerConnecting extends GuiScreen { private GuiButton killTask; private ClientIntegratedServerNetworkManager networkManager = null; private int timer = 0; - + private long startStartTime; private boolean hasOpened = false; - + public GuiScreenSingleplayerConnecting(GuiScreen menu, String message) { this.menu = menu; this.message = message; } - - public void initGui() { - if(startStartTime == 0) this.startStartTime = EagRuntime.steadyTimeMillis(); - this.buttonList.add(killTask = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, I18n.format("singleplayer.busy.killTask"))); - killTask.enabled = false; - } - - public void drawScreen(int par1, int par2, float par3) { - this.drawDefaultBackground(); - float f = 2.0f; - int top = this.height / 3; - - long millis = EagRuntime.steadyTimeMillis(); - - long dots = (millis / 500l) % 4l; - this.drawString(fontRendererObj, message + (dots > 0 ? "." : "") + (dots > 1 ? "." : "") + (dots > 2 ? "." : ""), (this.width - this.fontRendererObj.getStringWidth(message)) / 2, top + 10, 0xFFFFFF); - - long elapsed = (millis - startStartTime) / 1000l; - if(elapsed > 3) { - this.drawCenteredString(fontRendererObj, "(" + elapsed + "s)", this.width / 2, top + 25, 0xFFFFFF); + + protected void actionPerformed(GuiButton par1GuiButton) { + if (par1GuiButton.id == 0) { + SingleplayerServerController.killWorker(); + this.mc.loadWorld((WorldClient) null); + this.mc.getSession().reset(); + this.mc.displayGuiScreen(menu); } - - super.drawScreen(par1, par2, par3); + } + + public boolean canCloseGui() { + return false; } public boolean doesGuiPauseGame() { return false; } - + + public void drawScreen(int par1, int par2, float par3) { + this.drawDefaultBackground(); + float f = 2.0f; + int top = this.height / 3; + + long millis = EagRuntime.steadyTimeMillis(); + + long dots = (millis / 500l) % 4l; + this.drawString(fontRendererObj, + message + (dots > 0 ? "." : "") + (dots > 1 ? "." : "") + (dots > 2 ? "." : ""), + (this.width - this.fontRendererObj.getStringWidth(message)) / 2, top + 10, 0xFFFFFF); + + long elapsed = (millis - startStartTime) / 1000l; + if (elapsed > 3) { + this.drawCenteredString(fontRendererObj, "(" + elapsed + "s)", this.width / 2, top + 25, 0xFFFFFF); + } + + super.drawScreen(par1, par2, par3); + } + + public void initGui() { + if (startStartTime == 0) + this.startStartTime = EagRuntime.steadyTimeMillis(); + this.buttonList.add(killTask = new GuiButton(0, this.width / 2 - 100, this.height / 3 + 50, + I18n.format("singleplayer.busy.killTask"))); + killTask.enabled = false; + } + + public boolean shouldHangupIntegratedServer() { + return false; + } + public void updateScreen() { ++timer; if (timer > 1) { @@ -90,7 +112,8 @@ public class GuiScreenSingleplayerConnecting extends GuiScreen { this.mc.getSession().setLAN(); this.mc.clearTitles(); this.networkManager.setConnectionState(EnumConnectionState.LOGIN); - this.networkManager.setNetHandler(new NetHandlerSingleplayerLogin(this.networkManager, this.mc, this.menu)); + this.networkManager.setNetHandler( + new NetHandlerSingleplayerLogin(this.networkManager, this.mc, this.menu)); this.networkManager.sendPacket(new C00PacketLoginStart(this.mc.getSession().getProfile(), EaglerProfile.getSkinPacket(3), EaglerProfile.getCapePacket(), ConnectionHandshake.getSPHandshakeProtocolData(), EaglercraftVersion.clientBrandUUID)); @@ -104,34 +127,18 @@ public class GuiScreenSingleplayerConnecting extends GuiScreen { this.mc.getSession().reset(); if (mc.currentScreen == this) { mc.loadWorld(null); - mc.displayGuiScreen(new GuiDisconnected(menu, "connect.failed", new ChatComponentText("Worker Connection Refused"))); + mc.displayGuiScreen(new GuiDisconnected(menu, "connect.failed", + new ChatComponentText("Worker Connection Refused"))); } } } } } - + long millis = EagRuntime.steadyTimeMillis(); - if(millis - startStartTime > 6000l && SingleplayerServerController.canKillWorker()) { + if (millis - startStartTime > 6000l && SingleplayerServerController.canKillWorker()) { killTask.enabled = true; } } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - SingleplayerServerController.killWorker(); - this.mc.loadWorld((WorldClient)null); - this.mc.getSession().reset(); - this.mc.displayGuiScreen(menu); - } - } - - public boolean shouldHangupIntegratedServer() { - return false; - } - - public boolean canCloseGui() { - return false; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiShareToLan.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiShareToLan.java index 107013f4..648dbcf8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiShareToLan.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiShareToLan.java @@ -15,14 +15,15 @@ import net.minecraft.world.WorldSettings; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -60,54 +61,6 @@ public class GuiShareToLan extends GuiScreen { this.gameMode = gameMode; } - /** - * Adds the buttons (and other controls) to the screen in question. - */ - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(101, this.width / 2 - 155, this.height - 28, 140, 20, - I18n.format("lanServer.start"))); - this.buttonList.add(new GuiButton(102, this.width / 2 + 5, this.height - 28, 140, 20, - I18n.format("gui.cancel"))); - this.buttonList.add(this.buttonGameMode = new GuiButton(104, this.width / 2 - 155, 135, 140, 20, - I18n.format("selectWorld.gameMode"))); - this.buttonList.add(this.buttonAllowCommandsToggle = new GuiButton(103, this.width / 2 + 5, 135, 140, 20, - I18n.format("selectWorld.allowCommands"))); - this.buttonGameMode.enabled = this.buttonAllowCommandsToggle.enabled = !mc.isDemo(); - this.buttonList.add(this.buttonHiddenToggle = new GuiButton(105, this.width / 2 - 75, 165, 140, 20, - I18n.format("lanServer.hidden"))); - this.codeTextField = new GuiTextField(0, this.fontRendererObj, this.width / 2 - 100, 80, 200, 20); - this.codeTextField.setText(mc.thePlayer.getName() + "'s World"); - this.codeTextField.setFocused(true); - this.codeTextField.setMaxStringLength(252); - this.func_74088_g(); - } - - private void func_74088_g() { - this.buttonGameMode.displayString = I18n.format("selectWorld.gameMode") + ": " - + I18n.format("selectWorld.gameMode." + this.gameMode); - this.buttonAllowCommandsToggle.displayString = I18n.format("selectWorld.allowCommands") - + " "; - this.buttonHiddenToggle.displayString = I18n.format("lanServer.hidden") - + " "; - - if (this.allowCommands) { - this.buttonAllowCommandsToggle.displayString = this.buttonAllowCommandsToggle.displayString - + I18n.format("options.on"); - } else { - this.buttonAllowCommandsToggle.displayString = this.buttonAllowCommandsToggle.displayString - + I18n.format("options.off"); - } - - if (this.hiddenToggle) { - this.buttonHiddenToggle.displayString = this.buttonHiddenToggle.displayString - + I18n.format("options.on"); - } else { - this.buttonHiddenToggle.displayString = this.buttonHiddenToggle.displayString - + I18n.format("options.off"); - } - } - /** * Fired when a control is clicked. This is the equivalent of * ActionListener.actionPerformed(ActionEvent e). @@ -116,7 +69,7 @@ public class GuiShareToLan extends GuiScreen { if (par1GuiButton.id == 102) { this.mc.displayGuiScreen(this.parentScreen); } else if (par1GuiButton.id == 104) { - if(!mc.isDemo()) { + if (!mc.isDemo()) { if (this.gameMode.equals("survival")) { this.gameMode = "creative"; } else if (this.gameMode.equals("creative")) { @@ -126,11 +79,11 @@ public class GuiShareToLan extends GuiScreen { } else { this.gameMode = "survival"; } - + this.func_74088_g(); } } else if (par1GuiButton.id == 103) { - if(!mc.isDemo()) { + if (!mc.isDemo()) { this.allowCommands = !this.allowCommands; this.func_74088_g(); } @@ -153,7 +106,8 @@ public class GuiShareToLan extends GuiScreen { LoadingScreenRenderer ls = mc.loadingScreen; String code = LANServerController.shareToLAN(ls::resetProgressAndMessage, worldName, hiddenToggle); if (code != null) { - SingleplayerServerController.configureLAN(WorldSettings.GameType.getByName(this.gameMode), this.allowCommands); + SingleplayerServerController.configureLAN(WorldSettings.GameType.getByName(this.gameMode), + this.allowCommands); this.mc.ingameGUI.getChatGUI().printChatMessage(new ChatComponentText(I18n.format("lanServer.opened") .replace("$relay$", LANServerController.getCurrentURI()).replace("$code$", code))); } else { @@ -162,33 +116,89 @@ public class GuiShareToLan extends GuiScreen { } } + public boolean blockPTTKey() { + return this.codeTextField.isFocused(); + } + /** * Draws the screen and all the components in it. */ public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); - this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.title"), this.width / 2, - 35, 16777215); - this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.worldName"), this.width / 2, - 62, 16777215); - this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.otherPlayers"), - this.width / 2, 112, 16777215); - this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.ipGrabNote"), - this.width / 2, 195, 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.title"), this.width / 2, 35, 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.worldName"), this.width / 2, 62, 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.otherPlayers"), this.width / 2, 112, + 16777215); + this.drawCenteredString(this.fontRendererObj, I18n.format("lanServer.ipGrabNote"), this.width / 2, 195, + 16777215); super.drawScreen(par1, par2, par3); this.relaysButton.drawScreen(par1, par2); this.codeTextField.drawTextBox(); } + @Override + public void fireInputEvent(EnumInputEvent event, String param) { + this.codeTextField.fireInputEvent(event, param); + } + + private void func_74088_g() { + this.buttonGameMode.displayString = I18n.format("selectWorld.gameMode") + ": " + + I18n.format("selectWorld.gameMode." + this.gameMode); + this.buttonAllowCommandsToggle.displayString = I18n.format("selectWorld.allowCommands") + " "; + this.buttonHiddenToggle.displayString = I18n.format("lanServer.hidden") + " "; + + if (this.allowCommands) { + this.buttonAllowCommandsToggle.displayString = this.buttonAllowCommandsToggle.displayString + + I18n.format("options.on"); + } else { + this.buttonAllowCommandsToggle.displayString = this.buttonAllowCommandsToggle.displayString + + I18n.format("options.off"); + } + + if (this.hiddenToggle) { + this.buttonHiddenToggle.displayString = this.buttonHiddenToggle.displayString + I18n.format("options.on"); + } else { + this.buttonHiddenToggle.displayString = this.buttonHiddenToggle.displayString + I18n.format("options.off"); + } + } + + /** + * Adds the buttons (and other controls) to the screen in question. + */ + public void initGui() { + this.buttonList.clear(); + this.buttonList.add( + new GuiButton(101, this.width / 2 - 155, this.height - 28, 140, 20, I18n.format("lanServer.start"))); + this.buttonList + .add(new GuiButton(102, this.width / 2 + 5, this.height - 28, 140, 20, I18n.format("gui.cancel"))); + this.buttonList.add(this.buttonGameMode = new GuiButton(104, this.width / 2 - 155, 135, 140, 20, + I18n.format("selectWorld.gameMode"))); + this.buttonList.add(this.buttonAllowCommandsToggle = new GuiButton(103, this.width / 2 + 5, 135, 140, 20, + I18n.format("selectWorld.allowCommands"))); + this.buttonGameMode.enabled = this.buttonAllowCommandsToggle.enabled = !mc.isDemo(); + this.buttonList.add(this.buttonHiddenToggle = new GuiButton(105, this.width / 2 - 75, 165, 140, 20, + I18n.format("lanServer.hidden"))); + this.codeTextField = new GuiTextField(0, this.fontRendererObj, this.width / 2 - 100, 80, 200, 20); + this.codeTextField.setText(mc.thePlayer.getName() + "'s World"); + this.codeTextField.setFocused(true); + this.codeTextField.setMaxStringLength(252); + this.func_74088_g(); + } + + protected void keyTyped(char c, int k) { + super.keyTyped(c, k); + this.codeTextField.textboxKeyTyped(c, k); + } + public void mouseClicked(int par1, int par2, int par3) { super.mouseClicked(par1, par2, par3); this.relaysButton.mouseClicked(par1, par2, par3); this.codeTextField.mouseClicked(par1, par2, par3); } - protected void keyTyped(char c, int k) { - super.keyTyped(c, k); - this.codeTextField.textboxKeyTyped(c, k); + @Override + public boolean showCopyPasteButtons() { + return this.codeTextField.isFocused(); } public void updateScreen() { @@ -196,18 +206,4 @@ public class GuiShareToLan extends GuiScreen { this.codeTextField.updateCursorCounter(); } - public boolean blockPTTKey() { - return this.codeTextField.isFocused(); - } - - @Override - public boolean showCopyPasteButtons() { - return this.codeTextField.isFocused(); - } - - @Override - public void fireInputEvent(EnumInputEvent event, String param) { - this.codeTextField.fireInputEvent(event, param); - } - } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlider2.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlider2.java index cba3519f..fbdda6ea 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlider2.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlider2.java @@ -7,14 +7,15 @@ import net.minecraft.client.gui.GuiButton; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,6 +43,10 @@ public class GuiSlider2 extends GuiButton { return 0; } + public boolean isSliderTouchEvents() { + return true; + } + /** * Fired when the mouse button is dragged. Equivalent of * MouseListener.mouseDragged(MouseEvent e). @@ -60,17 +65,19 @@ public class GuiSlider2 extends GuiButton { this.sliderValue = 1.0F; } - if(oldValue != sliderValue) { + if (oldValue != sliderValue) { onChange(); } this.displayString = updateDisplayString(); } - if(this.enabled) { + if (this.enabled) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); - this.drawTexturedModalRect(this.xPosition + (int) (this.sliderValue * (float) (this.width - 8)), this.yPosition, 0, 66, 4, 20); - this.drawTexturedModalRect(this.xPosition + (int) (this.sliderValue * (float) (this.width - 8)) + 4, this.yPosition, 196, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int) (this.sliderValue * (float) (this.width - 8)), + this.yPosition, 0, 66, 4, 20); + this.drawTexturedModalRect(this.xPosition + (int) (this.sliderValue * (float) (this.width - 8)) + 4, + this.yPosition, 196, 66, 4, 20); } } } @@ -92,7 +99,7 @@ public class GuiSlider2 extends GuiButton { this.sliderValue = 1.0F; } - if(oldValue != sliderValue) { + if (oldValue != sliderValue) { onChange(); } @@ -112,16 +119,12 @@ public class GuiSlider2 extends GuiButton { this.dragging = false; } - protected String updateDisplayString() { - return (int)(this.sliderValue * this.sliderMax * 100.0F) + "%"; - } - protected void onChange() { - + } - public boolean isSliderTouchEvents() { - return true; + protected String updateDisplayString() { + return (int) (this.sliderValue * this.sliderMax * 100.0F) + "%"; } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlotRelay.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlotRelay.java index f9eee32c..32900c56 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlotRelay.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/gui/GuiSlotRelay.java @@ -12,14 +12,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,22 +38,6 @@ class GuiSlotRelay extends GuiSlot { this.relayManager = RelayManager.relayManager; } - @Override - protected int getSize() { - return relayManager.count(); - } - - @Override - protected void elementClicked(int var1, boolean var2, int var3, int var4) { - screen.selected = var1; - screen.updateButtons(); - } - - @Override - protected boolean isSelected(int var1) { - return screen.selected == var1; - } - @Override protected void drawBackground() { screen.drawDefaultBackground(); @@ -60,7 +45,7 @@ class GuiSlotRelay extends GuiSlot { @Override protected void drawSlot(int id, int xx, int yy, int width, int height, int ii) { - if(id < relayManager.count()) { + if (id < relayManager.count()) { this.mc.getTextureManager().bindTexture(Gui.icons); RelayServer srv = relayManager.get(id); String comment = srv.comment; @@ -69,31 +54,31 @@ class GuiSlotRelay extends GuiSlot { String str = null; int h = 12; long ping = srv.getPing(); - if(ping == 0l) { + if (ping == 0l) { var16 = 5; str = "No Connection"; - }else if(ping < 0l) { + } else if (ping < 0l) { var15 = 1; var16 = (int) (Minecraft.getSystemTime() / 100L + (long) (id * 2) & 7L); if (var16 > 4) { var16 = 8 - var16; } str = "Polling..."; - }else { + } else { RelayQuery.VersionMismatch vm = srv.getPingCompatible(); - if(!vm.isCompatible()) { + if (!vm.isCompatible()) { var16 = 5; - switch(vm) { - case CLIENT_OUTDATED: - str = "Outdated Client!"; - break; - case RELAY_OUTDATED: - str = "Outdated Relay!"; - break; - default: - case UNKNOWN: - str = "Incompatible Relay!"; - break; + switch (vm) { + case CLIENT_OUTDATED: + str = "Outdated Client!"; + break; + case RELAY_OUTDATED: + str = "Outdated Relay!"; + break; + default: + case UNKNOWN: + str = "Incompatible Relay!"; + break; } GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); GlStateManager.pushMatrix(); @@ -102,9 +87,9 @@ class GuiSlotRelay extends GuiSlot { screen.drawTexturedModalRect(0, 0, 0, 144, 16, 16); GlStateManager.popMatrix(); h += 10; - }else { + } else { String pingComment = srv.getPingComment().trim(); - if(pingComment.length() > 0) { + if (pingComment.length() > 0) { comment = pingComment; } str = "" + ping + "ms"; @@ -124,7 +109,7 @@ class GuiSlotRelay extends GuiSlot { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); screen.drawTexturedModalRect(xx + 205, yy, 0 + var15 * 10, 176 + var16 * 8, 10, 8); - if(srv.isPrimary()) { + if (srv.isPrimary()) { GlStateManager.pushMatrix(); GlStateManager.translate(xx + 4, yy + 5, 0.0f); GlStateManager.scale(0.8f, 0.8f, 0.8f); @@ -136,15 +121,31 @@ class GuiSlotRelay extends GuiSlot { screen.drawString(mc.fontRendererObj, comment, xx + 22, yy + 2, 0xFFFFFFFF); screen.drawString(mc.fontRendererObj, srv.address, xx + 22, yy + 12, 0xFF999999); - if(str != null) { + if (str != null) { int mx = screen.getFrameMouseX(); int my = screen.getFrameMouseY(); int rx = xx + 202; - if(mx > rx && mx < rx + 13 && my > yy - 1 && my < yy + h) { + if (mx > rx && mx < rx + 13 && my > yy - 1 && my < yy + h) { screen.setToolTip(str); } } } } + @Override + protected void elementClicked(int var1, boolean var2, int var3, int var4) { + screen.selected = var1; + screen.updateButtons(); + } + + @Override + protected int getSize() { + return relayManager.count(); + } + + @Override + protected boolean isSelected(int var1) { + return screen.selected == var1; + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCInputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCInputStream.java index 1022033d..150ab01a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCInputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCInputStream.java @@ -6,32 +6,52 @@ import java.io.InputStream; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCInputStream extends InputStream { - + private byte[] currentBuffer = null; private int idx = 0; private int markIDX = 0; private String errorName = null; - + public void feedBuffer(byte[] b) { currentBuffer = b; idx = 0; errorName = null; markIDX = 0; } - + + public byte[] getLeftover() { + if (currentBuffer.length - idx <= 0) { + return null; + } + + byte[] buf = new byte[currentBuffer.length - idx]; + System.arraycopy(currentBuffer, idx, buf, 0, currentBuffer.length - idx); + + return buf; + } + + public int getLeftoverCount() { + return currentBuffer.length - idx; + } + + public void markIndex() { + markIDX = idx; + } + public void nameBuffer(String str) { errorName = str; } @@ -39,46 +59,32 @@ public class IPCInputStream extends InputStream { @Override public int read() throws IOException { try { - return ((int)currentBuffer[idx++]) & 0xFF; - }catch(ArrayIndexOutOfBoundsException a) { - throw new IOException("IPCInputStream buffer underflow" + (errorName == null ? "," : (" (while deserializing '" + errorName + "')")) + " no bytes remaining", a); + return ((int) currentBuffer[idx++]) & 0xFF; + } catch (ArrayIndexOutOfBoundsException a) { + throw new IOException("IPCInputStream buffer underflow" + + (errorName == null ? "," : (" (while deserializing '" + errorName + "')")) + + " no bytes remaining", a); } } - + @Override public int read(byte b[], int off, int len) throws IOException { - if(idx + len > currentBuffer.length) { - throw new IOException("IPCInputStream buffer underflow" + (errorName == null ? "," : (" (while deserializing '" + errorName + "')")) + " tried to read " + len + " when there are only " + (currentBuffer.length - idx) + " bytes remaining", new ArrayIndexOutOfBoundsException(idx + len - 1)); + if (idx + len > currentBuffer.length) { + throw new IOException("IPCInputStream buffer underflow" + + (errorName == null ? "," : (" (while deserializing '" + errorName + "')")) + " tried to read " + + len + " when there are only " + (currentBuffer.length - idx) + " bytes remaining", + new ArrayIndexOutOfBoundsException(idx + len - 1)); } - if(off + len > b.length) { + if (off + len > b.length) { throw new ArrayIndexOutOfBoundsException(off + len - 1); } System.arraycopy(currentBuffer, idx, b, off, len); idx += len; return len; } - - public void markIndex() { - markIDX = idx; - } - + public void rewindIndex() { idx = markIDX; } - - public byte[] getLeftover() { - if(currentBuffer.length - idx <= 0) { - return null; - } - - byte[] buf = new byte[currentBuffer.length - idx]; - System.arraycopy(currentBuffer, idx, buf, 0, currentBuffer.length - idx); - - return buf; - } - - public int getLeftoverCount() { - return currentBuffer.length - idx; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCOutputStream.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCOutputStream.java index e5aa8fdd..e3d322a5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCOutputStream.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCOutputStream.java @@ -6,14 +6,15 @@ import java.io.OutputStream; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,46 +25,48 @@ public class IPCOutputStream extends OutputStream { private byte[] currentBuffer = null; private int idx = 0; private int originalSize = 0; - + public void feedBuffer(byte[] buf, String clazzName) { currentBuffer = buf; idx = 0; originalSize = buf.length; className = clazzName; } - - public byte[] returnBuffer() { - if(className != null && currentBuffer.length != originalSize) { - System.err.println("WARNING: Packet '" + className + "' was supposed to be " + originalSize + " bytes but buffer has grown by " + (currentBuffer.length - originalSize) + " to " + currentBuffer.length + " bytes"); - } - return currentBuffer; - } - + void growBuffer(int i) { int ii = currentBuffer.length; int iii = i - ii; - if(iii > 0) { + if (iii > 0) { byte[] n = new byte[i]; System.arraycopy(currentBuffer, 0, n, 0, ii); currentBuffer = n; } } - @Override - public void write(int b) throws IOException { - if(idx >= currentBuffer.length) { - growBuffer(idx + 1); + public byte[] returnBuffer() { + if (className != null && currentBuffer.length != originalSize) { + System.err.println("WARNING: Packet '" + className + "' was supposed to be " + originalSize + + " bytes but buffer has grown by " + (currentBuffer.length - originalSize) + " to " + + currentBuffer.length + " bytes"); } - currentBuffer[idx++] = (byte) b; + return currentBuffer; } - + @Override public void write(byte b[], int off, int len) throws IOException { - if(idx + len > currentBuffer.length) { + if (idx + len > currentBuffer.length) { growBuffer(idx + len); } System.arraycopy(b, off, currentBuffer, idx, len); idx += len; } + @Override + public void write(int b) throws IOException { + if (idx >= currentBuffer.length) { + growBuffer(idx + 1); + } + currentBuffer[idx++] = (byte) b; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket00StartServer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket00StartServer.java index a8d4f98c..30a0523b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket00StartServer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket00StartServer.java @@ -7,20 +7,21 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket00StartServer implements IPCPacketBase { - + public static final int ID = 0x00; public String worldName; @@ -28,11 +29,12 @@ public class IPCPacket00StartServer implements IPCPacketBase { public int initialDifficulty; public int initialViewDistance; public boolean demoMode; - + public IPCPacket00StartServer() { } - - public IPCPacket00StartServer(String worldName, String ownerName, int initialDifficulty, int initialViewDistance, boolean demoMode) { + + public IPCPacket00StartServer(String worldName, String ownerName, int initialDifficulty, int initialViewDistance, + boolean demoMode) { this.worldName = worldName; this.ownerName = ownerName; this.initialDifficulty = initialDifficulty; @@ -49,6 +51,11 @@ public class IPCPacket00StartServer implements IPCPacketBase { demoMode = bin.readBoolean(); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(worldName); @@ -58,11 +65,6 @@ public class IPCPacket00StartServer implements IPCPacketBase { bin.writeBoolean(demoMode); } - @Override - public int id() { - return ID; - } - @Override public int size() { return IPCPacketBase.strLen(worldName) + IPCPacketBase.strLen(ownerName) + 3; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket01StopServer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket01StopServer.java index 08640156..353c91a3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket01StopServer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket01StopServer.java @@ -7,22 +7,23 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket01StopServer implements IPCPacketBase { - + public static final int ID = 0x01; - + public IPCPacket01StopServer() { } @@ -31,12 +32,12 @@ public class IPCPacket01StopServer implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket02InitWorld.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket02InitWorld.java index d7817c15..f771ed75 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket02InitWorld.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket02InitWorld.java @@ -7,20 +7,21 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket02InitWorld implements IPCPacketBase { - + public static final int ID = 0x02; public String worldName; @@ -32,14 +33,15 @@ public class IPCPacket02InitWorld implements IPCPacketBase { public boolean structures; public boolean bonusChest; public boolean hardcore; - + public IPCPacket02InitWorld() { } - - public IPCPacket02InitWorld(String worldName, int gamemode, int worldType, String worldArgs, long seed, boolean cheats, boolean structures, boolean bonusChest, boolean hardcore) { + + public IPCPacket02InitWorld(String worldName, int gamemode, int worldType, String worldArgs, long seed, + boolean cheats, boolean structures, boolean bonusChest, boolean hardcore) { this.worldName = worldName; - this.gamemode = (byte)gamemode; - this.worldType = (byte)worldType; + this.gamemode = (byte) gamemode; + this.worldType = (byte) worldType; this.worldArgs = worldArgs; this.seed = seed; this.cheats = cheats; @@ -61,6 +63,11 @@ public class IPCPacket02InitWorld implements IPCPacketBase { hardcore = bin.readBoolean(); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(worldName); @@ -74,11 +81,6 @@ public class IPCPacket02InitWorld implements IPCPacketBase { bin.writeBoolean(hardcore); } - @Override - public int id() { - return ID; - } - @Override public int size() { return IPCPacketBase.strLen(worldName) + 1 + 1 + IPCPacketBase.strLen(worldArgs) + 8 + 4; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket03DeleteWorld.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket03DeleteWorld.java index 30aeec83..b9a31d54 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket03DeleteWorld.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket03DeleteWorld.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket03DeleteWorld implements IPCPacketBase { - + public static final int ID = 0x03; public String worldName; - + public IPCPacket03DeleteWorld() { } - + public IPCPacket03DeleteWorld(String worldName) { this.worldName = worldName; } @@ -38,13 +39,13 @@ public class IPCPacket03DeleteWorld implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(worldName); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(worldName); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket04RenameWorld.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket04RenameWorld.java index c403798a..aebcea4b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket04RenameWorld.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket04RenameWorld.java @@ -7,30 +7,31 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket04RenameWorld implements IPCPacketBase { - + public static final int ID = 0x04; public String worldOldName; public String worldNewName; public String displayName; public boolean copy; - + public IPCPacket04RenameWorld() { } - + public IPCPacket04RenameWorld(String worldOldName, String worldNewName, String displayName, boolean copy) { this.worldOldName = worldOldName; this.worldNewName = worldNewName; @@ -46,6 +47,11 @@ public class IPCPacket04RenameWorld implements IPCPacketBase { copy = bin.readBoolean(); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(worldOldName); @@ -54,14 +60,10 @@ public class IPCPacket04RenameWorld implements IPCPacketBase { bin.writeBoolean(copy); } - @Override - public int id() { - return ID; - } - @Override public int size() { - return IPCPacketBase.strLen(worldOldName) + IPCPacketBase.strLen(worldNewName) + IPCPacketBase.strLen(displayName) + 1; + return IPCPacketBase.strLen(worldOldName) + IPCPacketBase.strLen(worldNewName) + + IPCPacketBase.strLen(displayName) + 1; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket05RequestData.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket05RequestData.java index a809f784..496ab355 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket05RequestData.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket05RequestData.java @@ -7,20 +7,21 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket05RequestData implements IPCPacketBase { - + public static final int ID = 0x05; public static final byte REQUEST_LEVEL_DAT = 0x00; @@ -29,10 +30,10 @@ public class IPCPacket05RequestData implements IPCPacketBase { public String worldName; public byte request; - + public IPCPacket05RequestData() { } - + public IPCPacket05RequestData(String worldName, byte request) { this.worldName = worldName; this.request = request; @@ -45,14 +46,14 @@ public class IPCPacket05RequestData implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(worldName); - bin.writeByte(request); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(worldName); + bin.writeByte(request); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket06RenameWorldNBT.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket06RenameWorldNBT.java index ed9e577b..718ea529 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket06RenameWorldNBT.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket06RenameWorldNBT.java @@ -7,29 +7,30 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket06RenameWorldNBT implements IPCPacketBase { - + public static final int ID = 0x06; public String worldName; public String displayName; public boolean duplicate; - + public IPCPacket06RenameWorldNBT() { } - + public IPCPacket06RenameWorldNBT(String worldName, String displayName, boolean duplicate) { this.worldName = worldName; this.displayName = displayName; @@ -43,6 +44,11 @@ public class IPCPacket06RenameWorldNBT implements IPCPacketBase { this.duplicate = bin.readBoolean(); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(worldName); @@ -50,11 +56,6 @@ public class IPCPacket06RenameWorldNBT implements IPCPacketBase { bin.writeBoolean(duplicate); } - @Override - public int id() { - return ID; - } - @Override public int size() { return IPCPacketBase.strLen(worldName) + IPCPacketBase.strLen(displayName) + 1; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket07ImportWorld.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket07ImportWorld.java index 9ddf8ed5..e3cceadd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket07ImportWorld.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket07ImportWorld.java @@ -7,33 +7,34 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket07ImportWorld implements IPCPacketBase { - - public static final int ID = 0x07; - public byte gameRules; + public static final int ID = 0x07; + public static final byte WORLD_FORMAT_EAG = 0x00; + + public static final byte WORLD_FORMAT_MCA = 0x01; + public byte gameRules; public String worldName; + public byte[] worldData; public byte worldFormat; - - public static final byte WORLD_FORMAT_EAG = 0x00; - public static final byte WORLD_FORMAT_MCA = 0x01; - + public IPCPacket07ImportWorld() { } - + public IPCPacket07ImportWorld(String worldName, byte[] worldData, byte worldFormat, byte gameRules) { this.worldName = worldName; this.worldData = worldData; @@ -50,6 +51,11 @@ public class IPCPacket07ImportWorld implements IPCPacketBase { bin.readFully(worldData); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(worldName); @@ -59,11 +65,6 @@ public class IPCPacket07ImportWorld implements IPCPacketBase { bin.write(worldData); } - @Override - public int id() { - return ID; - } - @Override public int size() { return IPCPacketBase.strLen(worldName) + worldData.length + 6; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket09RequestResponse.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket09RequestResponse.java index 23968a94..83fa6e46 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket09RequestResponse.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket09RequestResponse.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket09RequestResponse implements IPCPacketBase { - + public static final int ID = 0x09; public byte[] response; - + public IPCPacket09RequestResponse() { } - + public IPCPacket09RequestResponse(byte[] dat) { this.response = dat; } @@ -39,14 +40,14 @@ public class IPCPacket09RequestResponse implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeInt(response.length); - bin.write(response); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeInt(response.length); + bin.write(response); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0ASetWorldDifficulty.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0ASetWorldDifficulty.java index 4b29f09b..182a4363 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0ASetWorldDifficulty.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0ASetWorldDifficulty.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket0ASetWorldDifficulty implements IPCPacketBase { - + public static final int ID = 0x0A; - + public byte difficulty; - + public IPCPacket0ASetWorldDifficulty() { } - + public IPCPacket0ASetWorldDifficulty(byte difficulty) { this.difficulty = difficulty; } @@ -38,13 +39,13 @@ public class IPCPacket0ASetWorldDifficulty implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeByte(difficulty); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeByte(difficulty); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0BPause.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0BPause.java index c11bd2ba..58f0c154 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0BPause.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0BPause.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket0BPause implements IPCPacketBase { - + public static final int ID = 0x0B; public boolean pause; - + public IPCPacket0BPause() { } - + public IPCPacket0BPause(boolean pause) { this.pause = pause; } @@ -38,13 +39,13 @@ public class IPCPacket0BPause implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeBoolean(pause); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeBoolean(pause); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0CPlayerChannel.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0CPlayerChannel.java index 803ea1df..e1f835bd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0CPlayerChannel.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0CPlayerChannel.java @@ -7,28 +7,29 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket0CPlayerChannel implements IPCPacketBase { - + public static final int ID = 0x0C; public String channel; public boolean open; - + public IPCPacket0CPlayerChannel() { } - + public IPCPacket0CPlayerChannel(String channel, boolean open) { this.channel = channel; this.open = open; @@ -41,14 +42,14 @@ public class IPCPacket0CPlayerChannel implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(channel); - bin.writeBoolean(open); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(channel); + bin.writeBoolean(open); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0DProgressUpdate.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0DProgressUpdate.java index b78ae705..528a5877 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0DProgressUpdate.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0DProgressUpdate.java @@ -7,28 +7,29 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket0DProgressUpdate implements IPCPacketBase { - + public static final int ID = 0x0D; public String updateMessage; public float updateProgress; - + public IPCPacket0DProgressUpdate() { } - + public IPCPacket0DProgressUpdate(String updateMessage, float updateProgress) { this.updateMessage = updateMessage == null ? "" : updateMessage; this.updateProgress = updateProgress; @@ -41,14 +42,14 @@ public class IPCPacket0DProgressUpdate implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(updateMessage); - bin.writeFloat(updateProgress); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(updateMessage); + bin.writeFloat(updateProgress); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0EListWorlds.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0EListWorlds.java index 1649ad99..a3231af8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0EListWorlds.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0EListWorlds.java @@ -7,22 +7,23 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket0EListWorlds implements IPCPacketBase { - + public static final int ID = 0x0E; - + public IPCPacket0EListWorlds() { } @@ -31,12 +32,12 @@ public class IPCPacket0EListWorlds implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0FListFiles.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0FListFiles.java index 099c89e2..3e934af2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0FListFiles.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket0FListFiles.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket0FListFiles implements IPCPacketBase { - + public static final int ID = 0x0F; public String path; - + public IPCPacket0FListFiles() { } - + public IPCPacket0FListFiles(String path) { this.path = path; } @@ -38,13 +39,13 @@ public class IPCPacket0FListFiles implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(path); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(path); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket10FileRead.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket10FileRead.java index 73955627..37f5b8d0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket10FileRead.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket10FileRead.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket10FileRead implements IPCPacketBase { - + public static final int ID = 0x10; public String file; - + public IPCPacket10FileRead() { } - + public IPCPacket10FileRead(String file) { this.file = file; } @@ -38,13 +39,13 @@ public class IPCPacket10FileRead implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(file); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(file); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket12FileWrite.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket12FileWrite.java index 14451969..e0625df2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket12FileWrite.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket12FileWrite.java @@ -7,28 +7,29 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket12FileWrite implements IPCPacketBase { - + public static final int ID = 0x12; public String path; public byte[] data; - + public IPCPacket12FileWrite() { } - + public IPCPacket12FileWrite(String path, byte[] data) { this.path = path; this.data = data; @@ -39,6 +40,11 @@ public class IPCPacket12FileWrite implements IPCPacketBase { path = bin.readUTF(); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(path); @@ -46,11 +52,6 @@ public class IPCPacket12FileWrite implements IPCPacketBase { bin.write(data); } - @Override - public int id() { - return ID; - } - @Override public int size() { return IPCPacketBase.strLen(path) + 4 + data.length; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket13FileCopyMove.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket13FileCopyMove.java index 7a1296af..9e5dea02 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket13FileCopyMove.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket13FileCopyMove.java @@ -7,29 +7,30 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket13FileCopyMove implements IPCPacketBase { - + public static final int ID = 0x13; public String fileOldName; public String fileNewName; public boolean copy; - + public IPCPacket13FileCopyMove() { } - + public IPCPacket13FileCopyMove(String fileOldName, String fileNewName, boolean copy) { this.fileOldName = fileOldName; this.fileNewName = fileNewName; @@ -43,6 +44,11 @@ public class IPCPacket13FileCopyMove implements IPCPacketBase { copy = bin.readBoolean(); } + @Override + public int id() { + return ID; + } + @Override public void serialize(DataOutput bin) throws IOException { bin.writeUTF(fileOldName); @@ -50,11 +56,6 @@ public class IPCPacket13FileCopyMove implements IPCPacketBase { bin.writeBoolean(copy); } - @Override - public int id() { - return ID; - } - @Override public int size() { return IPCPacketBase.strLen(fileOldName) + IPCPacketBase.strLen(fileNewName) + 1; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket14StringList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket14StringList.java index 90d3df6c..83cc415f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket14StringList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket14StringList.java @@ -9,20 +9,21 @@ import java.util.List; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket14StringList implements IPCPacketBase { - + public static final int ID = 0x14; public static final int FILE_LIST = 0x0; @@ -32,27 +33,27 @@ public class IPCPacket14StringList implements IPCPacketBase { public int opCode; public final List stringList; - + public IPCPacket14StringList() { stringList = new ArrayList<>(); } - - public IPCPacket14StringList(int opcode, String[] list) { - stringList = new ArrayList<>(list.length); - for(int i = 0; i < list.length; ++i) { - String s = list[i].trim(); - if(s.length() > 0) { + + public IPCPacket14StringList(int opcode, List list) { + stringList = new ArrayList<>(list.size()); + for (int i = 0, l = list.size(); i < l; ++i) { + String s = list.get(i).trim(); + if (s.length() > 0) { stringList.add(s); } } this.opCode = opcode; } - - public IPCPacket14StringList(int opcode, List list) { - stringList = new ArrayList<>(list.size()); - for(int i = 0, l = list.size(); i < l; ++i) { - String s = list.get(i).trim(); - if(s.length() > 0) { + + public IPCPacket14StringList(int opcode, String[] list) { + stringList = new ArrayList<>(list.length); + for (int i = 0; i < list.length; ++i) { + String s = list[i].trim(); + if (s.length() > 0) { stringList.add(s); } } @@ -64,30 +65,30 @@ public class IPCPacket14StringList implements IPCPacketBase { stringList.clear(); opCode = bin.readByte(); int len = bin.readInt(); - for(int i = 0; i < len; ++i) { + for (int i = 0; i < len; ++i) { stringList.add(bin.readUTF()); } } - @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeByte(opCode); - int l = stringList.size(); - bin.writeInt(l); - for(int i = 0; i < l; ++i) { - bin.writeUTF(stringList.get(i)); - } - } - @Override public int id() { return ID; } + @Override + public void serialize(DataOutput bin) throws IOException { + bin.writeByte(opCode); + int l = stringList.size(); + bin.writeInt(l); + for (int i = 0; i < l; ++i) { + bin.writeUTF(stringList.get(i)); + } + } + @Override public int size() { int len = 5; - for(int i = 0, l = stringList.size(); i < l; ++i) { + for (int i = 0, l = stringList.size(); i < l; ++i) { len += IPCPacketBase.strLen(stringList.get(i)); } return len; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket15Crashed.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket15Crashed.java index 08334551..bf46078f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket15Crashed.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket15Crashed.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket15Crashed implements IPCPacketBase { - + public static final int ID = 0x15; - + public String crashReport; - + public IPCPacket15Crashed() { } - + public IPCPacket15Crashed(String crashReport) { this.crashReport = crashReport; } @@ -38,13 +39,13 @@ public class IPCPacket15Crashed implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(crashReport); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(crashReport); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket16NBTList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket16NBTList.java index d065a082..0b5c5b32 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket16NBTList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket16NBTList.java @@ -17,14 +17,15 @@ import net.minecraft.nbt.NBTTagCompound; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,77 +33,77 @@ import net.minecraft.nbt.NBTTagCompound; public class IPCPacket16NBTList implements IPCPacketBase { public static final int ID = 0x16; - + public static final int WORLD_LIST = 0x0; public int opCode; public final List tagList; public final List nbtTagList; - + public IPCPacket16NBTList() { tagList = new LinkedList<>(); nbtTagList = new LinkedList<>(); } - - public IPCPacket16NBTList(int opcode, NBTTagCompound[] list) { - this(opcode, Arrays.asList(list)); - } - + public IPCPacket16NBTList(int opcode, List list) { tagList = new LinkedList<>(); nbtTagList = list; - for(int i = 0, size = list.size(); i < size; ++i) { + for (int i = 0, size = list.size(); i < size; ++i) { NBTTagCompound tag = list.get(i); try { EaglerOutputStream bao = new EaglerOutputStream(); CompressedStreamTools.write(tag, new DataOutputStream(bao)); tagList.add(bao.toByteArray()); - }catch(IOException e) { + } catch (IOException e) { System.err.println("Failed to write tag '" + tag.getId() + "' (#" + i + ") in IPCPacket16NBTList"); } } opCode = opcode; } + public IPCPacket16NBTList(int opcode, NBTTagCompound[] list) { + this(opcode, Arrays.asList(list)); + } + @Override public void deserialize(DataInput bin) throws IOException { tagList.clear(); nbtTagList.clear(); opCode = bin.readInt(); int count = bin.readInt(); - for(int i = 0; i < count; ++i) { + for (int i = 0; i < count; ++i) { byte[] toRead = new byte[bin.readInt()]; bin.readFully(toRead); tagList.add(toRead); try { nbtTagList.add(CompressedStreamTools.read(new DataInputStream(new EaglerInputStream(toRead)))); - }catch(IOException e) { + } catch (IOException e) { System.err.println("Failed to read tag #" + i + " in IPCPacket16NBTList"); } } } - @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeInt(opCode); - int l = tagList.size(); - bin.writeInt(l); - for(int i = 0; i < l; ++i) { - byte[] str = tagList.get(i); - bin.writeInt(str.length); - bin.write(str); - } - } - @Override public int id() { return ID; } + @Override + public void serialize(DataOutput bin) throws IOException { + bin.writeInt(opCode); + int l = tagList.size(); + bin.writeInt(l); + for (int i = 0; i < l; ++i) { + byte[] str = tagList.get(i); + bin.writeInt(str.length); + bin.write(str); + } + } + @Override public int size() { int len = 8; - for(int i = 0, l = tagList.size(); i < l; ++i) { + for (int i = 0, l = tagList.size(); i < l; ++i) { len += 4; len += tagList.get(i).length; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket17ConfigureLAN.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket17ConfigureLAN.java index 21167e54..f5adb370 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket17ConfigureLAN.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket17ConfigureLAN.java @@ -9,30 +9,31 @@ import java.util.List; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket17ConfigureLAN implements IPCPacketBase { - + public static final int ID = 0x17; - + public int gamemode; public boolean cheats; public final List iceServers; - + public IPCPacket17ConfigureLAN() { iceServers = new ArrayList<>(); } - + public IPCPacket17ConfigureLAN(int gamemode, boolean cheats, List iceServers) { this.gamemode = gamemode; this.cheats = cheats; @@ -45,30 +46,30 @@ public class IPCPacket17ConfigureLAN implements IPCPacketBase { cheats = bin.readBoolean(); iceServers.clear(); int iceCount = bin.readUnsignedByte(); - for(int i = 0; i < iceCount; ++i) { + for (int i = 0; i < iceCount; ++i) { iceServers.add(bin.readUTF()); } } - @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeByte(gamemode); - bin.writeBoolean(cheats); - bin.writeByte(iceServers.size()); - for(int i = 0, l = iceServers.size(); i < l; ++i) { - bin.writeUTF(iceServers.get(i)); - } - } - @Override public int id() { return ID; } + @Override + public void serialize(DataOutput bin) throws IOException { + bin.writeByte(gamemode); + bin.writeBoolean(cheats); + bin.writeByte(iceServers.size()); + for (int i = 0, l = iceServers.size(); i < l; ++i) { + bin.writeUTF(iceServers.get(i)); + } + } + @Override public int size() { int s = 0; - for(int i = 0, l = iceServers.size(); i < l; ++i) { + for (int i = 0, l = iceServers.size(); i < l; ++i) { s += 2; s += iceServers.get(i).length(); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket18ClearPlayers.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket18ClearPlayers.java index 81a396b7..0f389c8a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket18ClearPlayers.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket18ClearPlayers.java @@ -7,30 +7,31 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket18ClearPlayers implements IPCPacketBase { - + public static final int ID = 0x18; - + public String worldName = null; - + + public IPCPacket18ClearPlayers() { + } + public IPCPacket18ClearPlayers(String worldName) { this.worldName = worldName; } - - public IPCPacket18ClearPlayers() { - } @Override public void deserialize(DataInput bin) throws IOException { @@ -38,13 +39,13 @@ public class IPCPacket18ClearPlayers implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(worldName); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(worldName); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket19Autosave.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket19Autosave.java index 20841cb5..b192285c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket19Autosave.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket19Autosave.java @@ -7,22 +7,23 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket19Autosave implements IPCPacketBase { - + public static final int ID = 0x19; - + public IPCPacket19Autosave() { } @@ -31,12 +32,12 @@ public class IPCPacket19Autosave implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1ALoggerMessage.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1ALoggerMessage.java index 7404478f..a071018a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1ALoggerMessage.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1ALoggerMessage.java @@ -7,38 +7,39 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket1ALoggerMessage implements IPCPacketBase { - + public static final int ID = 0x1A; public String logMessage; public boolean isError; - + public IPCPacket1ALoggerMessage() { } - - public IPCPacket1ALoggerMessage(String logMessage, boolean isError) { - this.logMessage = logMessage; - this.isError = isError; - } - + public IPCPacket1ALoggerMessage(String logMessage) { this.logMessage = logMessage; this.isError = false; } + public IPCPacket1ALoggerMessage(String logMessage, boolean isError) { + this.logMessage = logMessage; + this.isError = isError; + } + @Override public void deserialize(DataInput bin) throws IOException { this.logMessage = bin.readUTF(); @@ -46,14 +47,14 @@ public class IPCPacket1ALoggerMessage implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeUTF(this.logMessage); - bin.writeBoolean(this.isError); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeUTF(this.logMessage); + bin.writeBoolean(this.isError); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1BEnableLogging.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1BEnableLogging.java index a3e5afd1..ef51e7fd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1BEnableLogging.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1BEnableLogging.java @@ -7,27 +7,28 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacket1BEnableLogging implements IPCPacketBase { - + public static final int ID = 0x1B; public boolean enable; - + public IPCPacket1BEnableLogging() { } - + public IPCPacket1BEnableLogging(boolean enable) { this.enable = enable; } @@ -38,13 +39,13 @@ public class IPCPacket1BEnableLogging implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeBoolean(enable); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeBoolean(enable); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1CIssueDetected.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1CIssueDetected.java index 51a5e962..38bdfa4c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1CIssueDetected.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacket1CIssueDetected.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,13 +41,13 @@ public class IPCPacket1CIssueDetected implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeByte(issueID); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeByte(issueID); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketBase.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketBase.java index 48e6dbf4..67c8489c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketBase.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketBase.java @@ -7,30 +7,26 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IPCPacketBase { - public void deserialize(DataInput bin) throws IOException; - public void serialize(DataOutput bin) throws IOException; - public int id(); - public int size(); - public static int strLen(String s) { int strlen = s.length(); int utflen = 2; int c; - + for (int i = 0; i < strlen; ++i) { c = s.charAt(i); if ((c >= 0x0001) && (c <= 0x007F)) { @@ -41,8 +37,16 @@ public interface IPCPacketBase { utflen += 2; } } - + return utflen; } - + + public void deserialize(DataInput bin) throws IOException; + + public int id(); + + public void serialize(DataOutput bin) throws IOException; + + public int size(); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketFFProcessKeepAlive.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketFFProcessKeepAlive.java index 5553bd3d..a4f4e7e5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketFFProcessKeepAlive.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketFFProcessKeepAlive.java @@ -7,31 +7,32 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacketFFProcessKeepAlive implements IPCPacketBase { - + public static final int ID = 0xFF; public static final int KEEPALIVE = 0; public static final int FAILURE = 0xFE; public static final int EXITED = 0xFC; - + public int ack; - + public IPCPacketFFProcessKeepAlive() { } - + public IPCPacketFFProcessKeepAlive(int ack) { this.ack = ack; } @@ -42,13 +43,13 @@ public class IPCPacketFFProcessKeepAlive implements IPCPacketBase { } @Override - public void serialize(DataOutput bin) throws IOException { - bin.writeByte(ack); + public int id() { + return ID; } @Override - public int id() { - return ID; + public void serialize(DataOutput bin) throws IOException { + bin.writeByte(ack); } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketManager.java index 6363efa2..6728fda6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/ipc/IPCPacketManager.java @@ -9,28 +9,23 @@ import java.util.function.Supplier; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IPCPacketManager { - + public static final HashMap> mappings = new HashMap<>(); - public final IPCInputStream IPC_INPUT_STREAM = new IPCInputStream(); - public final IPCOutputStream IPC_OUTPUT_STREAM = new IPCOutputStream(); - - public final DataInputStream IPC_DATA_INPUT_STREAM = new DataInputStream(IPC_INPUT_STREAM); - public final DataOutputStream IPC_DATA_OUTPUT_STREAM = new DataOutputStream(IPC_OUTPUT_STREAM); - static { mappings.put(IPCPacket00StartServer.ID, IPCPacket00StartServer::new); mappings.put(IPCPacket01StopServer.ID, IPCPacket01StopServer::new); @@ -60,38 +55,45 @@ public class IPCPacketManager { mappings.put(IPCPacket1CIssueDetected.ID, IPCPacket1CIssueDetected::new); mappings.put(IPCPacketFFProcessKeepAlive.ID, IPCPacketFFProcessKeepAlive::new); } - + public final IPCInputStream IPC_INPUT_STREAM = new IPCInputStream(); + + public final IPCOutputStream IPC_OUTPUT_STREAM = new IPCOutputStream(); + public final DataInputStream IPC_DATA_INPUT_STREAM = new DataInputStream(IPC_INPUT_STREAM); + + public final DataOutputStream IPC_DATA_OUTPUT_STREAM = new DataOutputStream(IPC_OUTPUT_STREAM); + + public IPCPacketBase IPCDeserialize(byte[] pkt) throws IOException { + + IPC_INPUT_STREAM.feedBuffer(pkt); + int i = IPC_INPUT_STREAM.read(); + + Supplier pk = mappings.get(Integer.valueOf(i)); + if (pk == null) { + throw new IOException("Packet type 0x" + Integer.toHexString(i) + " doesn't exist"); + } + + IPCPacketBase p = pk.get(); + + IPC_INPUT_STREAM.nameBuffer(p.getClass().getSimpleName()); + + p.deserialize(IPC_DATA_INPUT_STREAM); + + int lo = IPC_INPUT_STREAM.getLeftoverCount(); + if (lo > 0) { + System.err.println("Packet type 0x" + Integer.toHexString(i) + " class '" + p.getClass().getSimpleName() + + "' was size " + (pkt.length - 1) + " but only " + (pkt.length - 1 - lo) + " bytes were read"); + } + + return p; + } + public byte[] IPCSerialize(IPCPacketBase pkt) throws IOException { - + IPC_OUTPUT_STREAM.feedBuffer(new byte[pkt.size() + 1], pkt.getClass().getSimpleName()); IPC_OUTPUT_STREAM.write(pkt.id()); pkt.serialize(IPC_DATA_OUTPUT_STREAM); - + return IPC_OUTPUT_STREAM.returnBuffer(); } - - public IPCPacketBase IPCDeserialize(byte[] pkt) throws IOException { - - IPC_INPUT_STREAM.feedBuffer(pkt); - int i = IPC_INPUT_STREAM.read(); - - Supplier pk = mappings.get(Integer.valueOf(i)); - if(pk == null) { - throw new IOException("Packet type 0x" + Integer.toHexString(i) + " doesn't exist"); - } - - IPCPacketBase p = pk.get(); - - IPC_INPUT_STREAM.nameBuffer(p.getClass().getSimpleName()); - - p.deserialize(IPC_DATA_INPUT_STREAM); - - int lo = IPC_INPUT_STREAM.getLeftoverCount(); - if(lo > 0) { - System.err.println("Packet type 0x" + Integer.toHexString(i) + " class '" + p.getClass().getSimpleName() + "' was size " + (pkt.length - 1) + " but only " + (pkt.length - 1 - lo) + " bytes were read"); - } - - return p; - } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientNetworkManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientNetworkManager.java index 15a1054b..8b95779f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientNetworkManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientNetworkManager.java @@ -1,5 +1,10 @@ package net.lax1dude.eaglercraft.v1_8.sp.lan; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EagUtils; import net.lax1dude.eaglercraft.v1_8.EaglerInputStream; @@ -13,29 +18,32 @@ import net.lax1dude.eaglercraft.v1_8.netty.ByteBuf; import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.socket.EaglercraftNetworkManager; import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayServerSocket; -import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.*; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket00Handshake; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket01ICEServers; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket03ICECandidate; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket04Description; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket05ClientSuccess; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket06ClientFailure; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacketFFErrorCode; import net.minecraft.network.EnumPacketDirection; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.IChatComponent; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,13 +56,195 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { public static final int fragmentSize = 0xFF00; - private static final String[] initStateNames = new String[] { "PRE", "INIT", "SENT_ICE_CANDIDATE", "SENT_DESCRIPTION" }; + private static final String[] initStateNames = new String[] { "PRE", "INIT", "SENT_ICE_CANDIDATE", + "SENT_DESCRIPTION" }; + + public static LANClientNetworkManager connectToWorld(RelayServerSocket sock, String displayCode, + String displayRelay) { + PlatformWebRTC.clearLANClientState(); + int connectState = PRE; + RelayPacket pkt; + mainLoop: while (!sock.isClosed()) { + PlatformWebRTC.runScheduledTasks(); + sock.update(); + if ((pkt = sock.readPacket()) != null) { + if (pkt instanceof RelayPacket00Handshake) { + if (connectState == PRE) { + + // %%%%%% Process IPacket00Handshake %%%%%% + + logger.info("Relay [{}|{}] recieved handshake, client id: {}", displayRelay, displayCode, + ((RelayPacket00Handshake) pkt).connectionCode); + connectState = INIT; + + } else { + sock.close(); + logger.error("Relay [{}|{}] unexpected packet: IPacket00Handshake in state {}", displayRelay, + displayCode, initStateNames[connectState]); + return null; + } + } else if (pkt instanceof RelayPacket01ICEServers) { + if (connectState == INIT) { + + // %%%%%% Process IPacket01ICEServers %%%%%% + + RelayPacket01ICEServers ipkt = (RelayPacket01ICEServers) pkt; + + // print servers + logger.info("Relay [{}|{}] provided ICE servers:", displayRelay, displayCode); + List servers = new ArrayList<>(); + for (RelayPacket01ICEServers.RelayServer srv : ipkt.servers) { + logger.info("Relay [{}|{}] {}: {}", displayRelay, displayCode, srv.type.name(), + srv.address); + servers.add(srv.getICEString()); + } + + // process + PlatformWebRTC.clientLANSetICEServersAndConnect(servers.toArray(new String[servers.size()])); + + // await result + long lm = EagRuntime.steadyTimeMillis(); + do { + PlatformWebRTC.runScheduledTasks(); + String c = PlatformWebRTC.clientLANAwaitDescription(); + if (c != null) { + logger.info("Relay [{}|{}] client sent description", displayRelay, displayCode); + + // 'this.descriptionHandler' was called, send result: + sock.writePacket(new RelayPacket04Description("", c)); + + connectState = SENT_DESCRIPTION; + continue mainLoop; + } + EagUtils.sleep(20l); + } while (EagRuntime.steadyTimeMillis() - lm < 5000l); + + // no description was sent + sock.close(); + logger.error("Relay [{}|{}] client provide description timeout", displayRelay, displayCode); + return null; + + } else { + sock.close(); + logger.error("Relay [{}|{}] unexpected packet: IPacket01ICEServers in state {}", displayRelay, + displayCode, initStateNames[connectState]); + return null; + } + } else if (pkt instanceof RelayPacket03ICECandidate) { + if (connectState == SENT_ICE_CANDIDATE) { + + // %%%%%% Process IPacket03ICECandidate %%%%%% + + RelayPacket03ICECandidate ipkt = (RelayPacket03ICECandidate) pkt; + + // process + logger.info("Relay [{}|{}] recieved server ICE candidate", displayRelay, displayCode); + PlatformWebRTC.clientLANSetICECandidate(ipkt.getCandidateString()); + + // await result + long lm = EagRuntime.steadyTimeMillis(); + do { + PlatformWebRTC.runScheduledTasks(); + if (PlatformWebRTC.clientLANAwaitChannel()) { + logger.info("Relay [{}|{}] client opened data channel", displayRelay, displayCode); + + // 'this.remoteDataChannelHandler' was called, success + sock.writePacket(new RelayPacket05ClientSuccess(ipkt.peerId)); + sock.close(); + return new LANClientNetworkManager(displayCode, displayRelay); + + } + EagUtils.sleep(20l); + } while (EagRuntime.steadyTimeMillis() - lm < 5000l); + + // no channel was opened + sock.writePacket(new RelayPacket06ClientFailure(ipkt.peerId)); + sock.close(); + logger.error("Relay [{}|{}] client open data channel timeout", displayRelay, displayCode); + return null; + + } else { + sock.close(); + logger.error("Relay [{}|{}] unexpected packet: IPacket03ICECandidate in state {}", displayRelay, + displayCode, initStateNames[connectState]); + return null; + } + } else if (pkt instanceof RelayPacket04Description) { + if (connectState == SENT_DESCRIPTION) { + + // %%%%%% Process IPacket04Description %%%%%% + + RelayPacket04Description ipkt = (RelayPacket04Description) pkt; + + // process + logger.info("Relay [{}|{}] recieved server description", displayRelay, displayCode); + PlatformWebRTC.clientLANSetDescription(ipkt.getDescriptionString()); + + // await result + long lm = EagRuntime.steadyTimeMillis(); + do { + PlatformWebRTC.runScheduledTasks(); + String c = PlatformWebRTC.clientLANAwaitICECandidate(); + if (c != null) { + logger.info("Relay [{}|{}] client sent ICE candidate", displayRelay, displayCode); + + // 'this.iceCandidateHandler' was called, send result: + sock.writePacket(new RelayPacket03ICECandidate("", c)); + + connectState = SENT_ICE_CANDIDATE; + continue mainLoop; + } + EagUtils.sleep(20l); + } while (EagRuntime.steadyTimeMillis() - lm < 5000l); + + // no ice candidates were sent + sock.close(); + logger.error("Relay [{}|{}] client provide ICE candidate timeout", displayRelay, displayCode); + return null; + + } else { + sock.close(); + logger.error("Relay [{}|{}] unexpected packet: IPacket04Description in state {}", displayRelay, + displayCode, initStateNames[connectState]); + return null; + } + } else if (pkt instanceof RelayPacketFFErrorCode) { + + // %%%%%% Process IPacketFFErrorCode %%%%%% + + RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; + logger.error("Relay [{}|{}] connection failed: {}({}): {}", displayRelay, displayCode, + RelayPacketFFErrorCode.code2string(ipkt.code), ipkt.code, ipkt.desc); + Throwable t; + while ((t = sock.getException()) != null) { + logger.error(t); + } + sock.close(); + return null; + + } else { + + // %%%%%% Unexpected Packet %%%%%% + + logger.error("Relay [{}|{}] unexpected packet: {}", displayRelay, displayCode, + pkt.getClass().getSimpleName()); + sock.close(); + return null; + } + } + EagUtils.sleep(20l); + } + return null; + } public final String displayCode; + public final String displayRelay; private boolean firstPacket = true; + private List fragmentedPacket = new ArrayList<>(); + private LANClientNetworkManager(String displayCode, String displayRelay) { super(""); this.displayCode = displayCode; @@ -62,6 +252,30 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { this.nethandler = null; } + @Override + public boolean checkDisconnected() { + if (PlatformWebRTC.clientLANClosed()) { + clientDisconnected = false; + try { + processReceivedPackets(); // catch kick message + } catch (IOException e) { + } + doClientDisconnect(new ChatComponentTranslation("disconnect.endOfStream")); + } + return clientDisconnected; + } + + @Override + public void closeChannel(IChatComponent reason) { + if (!PlatformWebRTC.clientLANClosed()) { + PlatformWebRTC.clientLANCloseConnection(); + } + if (nethandler != null) { + nethandler.onDisconnect(reason); + } + clientDisconnected = true; + } + @Override public void connect() { fragmentedPacket.clear(); @@ -73,222 +287,6 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { return clientDisconnected ? EnumEaglerConnectionState.CLOSED : EnumEaglerConnectionState.CONNECTED; } - public static LANClientNetworkManager connectToWorld(RelayServerSocket sock, String displayCode, String displayRelay) { - PlatformWebRTC.clearLANClientState(); - int connectState = PRE; - RelayPacket pkt; - mainLoop: while(!sock.isClosed()) { - PlatformWebRTC.runScheduledTasks(); - sock.update(); - if((pkt = sock.readPacket()) != null) { - if(pkt instanceof RelayPacket00Handshake) { - if(connectState == PRE) { - - // %%%%%% Process IPacket00Handshake %%%%%% - - logger.info("Relay [{}|{}] recieved handshake, client id: {}", displayRelay, displayCode, ((RelayPacket00Handshake)pkt).connectionCode); - connectState = INIT; - - }else { - sock.close(); - logger.error("Relay [{}|{}] unexpected packet: IPacket00Handshake in state {}", displayRelay, displayCode, initStateNames[connectState]); - return null; - } - }else if(pkt instanceof RelayPacket01ICEServers) { - if(connectState == INIT) { - - // %%%%%% Process IPacket01ICEServers %%%%%% - - RelayPacket01ICEServers ipkt = (RelayPacket01ICEServers) pkt; - - // print servers - logger.info("Relay [{}|{}] provided ICE servers:", displayRelay, displayCode); - List servers = new ArrayList<>(); - for(RelayPacket01ICEServers.RelayServer srv : ipkt.servers) { - logger.info("Relay [{}|{}] {}: {}", displayRelay, displayCode, srv.type.name(), srv.address); - servers.add(srv.getICEString()); - } - - // process - PlatformWebRTC.clientLANSetICEServersAndConnect(servers.toArray(new String[servers.size()])); - - // await result - long lm = EagRuntime.steadyTimeMillis(); - do { - PlatformWebRTC.runScheduledTasks(); - String c = PlatformWebRTC.clientLANAwaitDescription(); - if(c != null) { - logger.info("Relay [{}|{}] client sent description", displayRelay, displayCode); - - // 'this.descriptionHandler' was called, send result: - sock.writePacket(new RelayPacket04Description("", c)); - - connectState = SENT_DESCRIPTION; - continue mainLoop; - } - EagUtils.sleep(20l); - }while(EagRuntime.steadyTimeMillis() - lm < 5000l); - - // no description was sent - sock.close(); - logger.error("Relay [{}|{}] client provide description timeout", displayRelay, displayCode); - return null; - - }else { - sock.close(); - logger.error("Relay [{}|{}] unexpected packet: IPacket01ICEServers in state {}", displayRelay, displayCode, initStateNames[connectState]); - return null; - } - }else if(pkt instanceof RelayPacket03ICECandidate) { - if(connectState == SENT_ICE_CANDIDATE) { - - // %%%%%% Process IPacket03ICECandidate %%%%%% - - RelayPacket03ICECandidate ipkt = (RelayPacket03ICECandidate) pkt; - - // process - logger.info("Relay [{}|{}] recieved server ICE candidate", displayRelay, displayCode); - PlatformWebRTC.clientLANSetICECandidate(ipkt.getCandidateString()); - - // await result - long lm = EagRuntime.steadyTimeMillis(); - do { - PlatformWebRTC.runScheduledTasks(); - if(PlatformWebRTC.clientLANAwaitChannel()) { - logger.info("Relay [{}|{}] client opened data channel", displayRelay, displayCode); - - // 'this.remoteDataChannelHandler' was called, success - sock.writePacket(new RelayPacket05ClientSuccess(ipkt.peerId)); - sock.close(); - return new LANClientNetworkManager(displayCode, displayRelay); - - } - EagUtils.sleep(20l); - }while(EagRuntime.steadyTimeMillis() - lm < 5000l); - - // no channel was opened - sock.writePacket(new RelayPacket06ClientFailure(ipkt.peerId)); - sock.close(); - logger.error("Relay [{}|{}] client open data channel timeout", displayRelay, displayCode); - return null; - - }else { - sock.close(); - logger.error("Relay [{}|{}] unexpected packet: IPacket03ICECandidate in state {}", displayRelay, displayCode, initStateNames[connectState]); - return null; - } - }else if(pkt instanceof RelayPacket04Description) { - if(connectState == SENT_DESCRIPTION) { - - // %%%%%% Process IPacket04Description %%%%%% - - RelayPacket04Description ipkt = (RelayPacket04Description) pkt; - - // process - logger.info("Relay [{}|{}] recieved server description", displayRelay, displayCode); - PlatformWebRTC.clientLANSetDescription(ipkt.getDescriptionString()); - - // await result - long lm = EagRuntime.steadyTimeMillis(); - do { - PlatformWebRTC.runScheduledTasks(); - String c = PlatformWebRTC.clientLANAwaitICECandidate(); - if(c != null) { - logger.info("Relay [{}|{}] client sent ICE candidate", displayRelay, displayCode); - - // 'this.iceCandidateHandler' was called, send result: - sock.writePacket(new RelayPacket03ICECandidate("", c)); - - connectState = SENT_ICE_CANDIDATE; - continue mainLoop; - } - EagUtils.sleep(20l); - }while(EagRuntime.steadyTimeMillis() - lm < 5000l); - - // no ice candidates were sent - sock.close(); - logger.error("Relay [{}|{}] client provide ICE candidate timeout", displayRelay, displayCode); - return null; - - }else { - sock.close(); - logger.error("Relay [{}|{}] unexpected packet: IPacket04Description in state {}", displayRelay, displayCode, initStateNames[connectState]); - return null; - } - }else if(pkt instanceof RelayPacketFFErrorCode) { - - // %%%%%% Process IPacketFFErrorCode %%%%%% - - RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; - logger.error("Relay [{}|{}] connection failed: {}({}): {}", displayRelay, displayCode, RelayPacketFFErrorCode.code2string(ipkt.code), ipkt.code, ipkt.desc); - Throwable t; - while((t = sock.getException()) != null) { - logger.error(t); - } - sock.close(); - return null; - - }else { - - // %%%%%% Unexpected Packet %%%%%% - - logger.error("Relay [{}|{}] unexpected packet: {}", displayRelay, displayCode, pkt.getClass().getSimpleName()); - sock.close(); - return null; - } - } - EagUtils.sleep(20l); - } - return null; - } - - @Override - public void sendPacket(Packet pkt) { - if(!isChannelOpen()) { - logger.error("Packet was sent on a closed connection: {}", pkt.getClass().getSimpleName()); - return; - } - - int i; - try { - i = packetState.getPacketId(EnumPacketDirection.SERVERBOUND, pkt); - }catch(Throwable t) { - logger.error("Incorrect packet for state: {}", pkt.getClass().getSimpleName()); - return; - } - - temporaryBuffer.clear(); - temporaryBuffer.writeVarIntToBuffer(i); - try { - pkt.writePacketData(temporaryBuffer); - }catch(IOException ex) { - logger.error("Failed to write packet {}!", pkt.getClass().getSimpleName()); - return; - } - - int len = temporaryBuffer.readableBytes(); - int fragmentSizeN1 = fragmentSize - 1; - if(len > fragmentSizeN1) { - do { - int readLen = len > fragmentSizeN1 ? fragmentSizeN1 : len; - byte[] frag = new byte[readLen + 1]; - temporaryBuffer.readBytes(frag, 1, readLen); - frag[0] = temporaryBuffer.readableBytes() == 0 ? (byte)0 : (byte)1; - PlatformWebRTC.clientLANSendPacket(frag); - }while((len = temporaryBuffer.readableBytes()) > 0); - }else { - byte[] bytes = new byte[len + 1]; - bytes[0] = 0; - temporaryBuffer.readBytes(bytes, 1, len); - PlatformWebRTC.clientLANSendPacket(bytes); - } - } - - @Override - public boolean isLocalChannel() { - return true; - } - @Override public boolean isChannelOpen() { if (PlatformWebRTC.clientLANClosed()) { @@ -297,34 +295,37 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { return !clientDisconnected; } - private List fragmentedPacket = new ArrayList<>(); + @Override + public boolean isLocalChannel() { + return true; + } @Override public void processReceivedPackets() throws IOException { - if(this.nethandler != null) { + if (this.nethandler != null) { List packets = PlatformWebRTC.clientLANReadAllPacket(); - if(packets == null) { + if (packets == null) { return; } - for(int k = 0, l = packets.size(); k < l; ++k) { + for (int k = 0, l = packets.size(); k < l; ++k) { byte[] data = packets.get(k); byte[] fullData; boolean compressed = false; if (data[0] == 0 || data[0] == 2) { - if(fragmentedPacket.isEmpty()) { + if (fragmentedPacket.isEmpty()) { fullData = new byte[data.length - 1]; System.arraycopy(data, 1, fullData, 0, fullData.length); - }else { + } else { fragmentedPacket.add(data); int len = 0; int fragCount = fragmentedPacket.size(); - for(int i = 0; i < fragCount; ++i) { + for (int i = 0; i < fragCount; ++i) { len += fragmentedPacket.get(i).length - 1; } fullData = new byte[len]; len = 0; - for(int i = 0; i < fragCount; ++i) { + for (int i = 0; i < fragCount; ++i) { byte[] f = fragmentedPacket.get(i); System.arraycopy(f, 1, fullData, len, f.length - 1); len += f.length - 1; @@ -336,19 +337,19 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { fragmentedPacket.add(data); continue; } else { - logger.error("Recieved {} byte fragment of unknown type: {}", data.length, ((int)data[0] & 0xFF)); + logger.error("Recieved {} byte fragment of unknown type: {}", data.length, ((int) data[0] & 0xFF)); continue; } - if(compressed) { - if(fullData.length < 4) { + if (compressed) { + if (fullData.length < 4) { throw new IOException("Recieved invalid " + fullData.length + " byte compressed packet"); } EaglerInputStream bi = new EaglerInputStream(fullData); int i = (bi.read() << 24) | (bi.read() << 16) | (bi.read() << 8) | bi.read(); fullData = new byte[i]; int r; - try(InputStream inflaterInputStream = EaglerZLIB.newInflaterInputStream(bi)) { + try (InputStream inflaterInputStream = EaglerZLIB.newInflaterInputStream(bi)) { r = IOUtils.readFully(inflaterInputStream, fullData); } if (i != r) { @@ -356,9 +357,10 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { } } - if(firstPacket) { + if (firstPacket) { // 1.5 kick packet - if(fullData.length == 31 && fullData[0] == (byte)0xFF && fullData[1] == (byte)0x00 && fullData[2] == (byte)0x0E) { + if (fullData.length == 31 && fullData[0] == (byte) 0xFF && fullData[1] == (byte) 0x00 + && fullData[2] == (byte) 0x0E) { logger.error("Detected a 1.5 LAN server!"); this.closeChannel(new ChatComponentTranslation("singleplayer.outdatedLANServerKick")); firstPacket = false; @@ -375,24 +377,26 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { Packet pkt; try { pkt = packetState.getPacket(EnumPacketDirection.CLIENTBOUND, pktId); - }catch(IllegalAccessException | InstantiationException ex) { + } catch (IllegalAccessException | InstantiationException ex) { throw new IOException("Recieved a packet with type " + pktId + " which is invalid!"); } - if(pkt == null) { - throw new IOException("Recieved packet type " + pktId + " which is undefined in state " + packetState); + if (pkt == null) { + throw new IOException( + "Recieved packet type " + pktId + " which is undefined in state " + packetState); } try { pkt.readPacketData(input); - }catch(Throwable t) { + } catch (Throwable t) { throw new IOException("Failed to read packet type '" + pkt.getClass().getSimpleName() + "'", t); } try { pkt.processPacket(nethandler); - }catch(Throwable t) { - logger.error("Failed to process {}! It'll be skipped for debug purposes.", pkt.getClass().getSimpleName()); + } catch (Throwable t) { + logger.error("Failed to process {}! It'll be skipped for debug purposes.", + pkt.getClass().getSimpleName()); logger.error(t); } } @@ -400,27 +404,45 @@ public class LANClientNetworkManager extends EaglercraftNetworkManager { } @Override - public void closeChannel(IChatComponent reason) { - if(!PlatformWebRTC.clientLANClosed()) { - PlatformWebRTC.clientLANCloseConnection(); + public void sendPacket(Packet pkt) { + if (!isChannelOpen()) { + logger.error("Packet was sent on a closed connection: {}", pkt.getClass().getSimpleName()); + return; } - if(nethandler != null) { - nethandler.onDisconnect(reason); - } - clientDisconnected = true; - } - @Override - public boolean checkDisconnected() { - if(PlatformWebRTC.clientLANClosed()) { - clientDisconnected = false; - try { - processReceivedPackets(); // catch kick message - } catch (IOException e) { - } - doClientDisconnect(new ChatComponentTranslation("disconnect.endOfStream")); + int i; + try { + i = packetState.getPacketId(EnumPacketDirection.SERVERBOUND, pkt); + } catch (Throwable t) { + logger.error("Incorrect packet for state: {}", pkt.getClass().getSimpleName()); + return; + } + + temporaryBuffer.clear(); + temporaryBuffer.writeVarIntToBuffer(i); + try { + pkt.writePacketData(temporaryBuffer); + } catch (IOException ex) { + logger.error("Failed to write packet {}!", pkt.getClass().getSimpleName()); + return; + } + + int len = temporaryBuffer.readableBytes(); + int fragmentSizeN1 = fragmentSize - 1; + if (len > fragmentSizeN1) { + do { + int readLen = len > fragmentSizeN1 ? fragmentSizeN1 : len; + byte[] frag = new byte[readLen + 1]; + temporaryBuffer.readBytes(frag, 1, readLen); + frag[0] = temporaryBuffer.readableBytes() == 0 ? (byte) 0 : (byte) 1; + PlatformWebRTC.clientLANSendPacket(frag); + } while ((len = temporaryBuffer.readableBytes()) > 0); + } else { + byte[] bytes = new byte[len + 1]; + bytes[0] = 0; + temporaryBuffer.readBytes(bytes, 1, len); + PlatformWebRTC.clientLANSendPacket(bytes); } - return clientDisconnected; } } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientPeer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientPeer.java index 817bc4cf..44c07e14 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientPeer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANClientPeer.java @@ -17,14 +17,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket04Description; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -45,126 +46,9 @@ class LANClientPeer { PlatformWebRTC.serverLANCreatePeer(clientId); } - protected void handleICECandidates(String candidates) { - if(state == SENT_DESCRIPTION) { - PlatformWebRTC.serverLANPeerICECandidates(clientId, candidates); - long millis = EagRuntime.steadyTimeMillis(); - do { - LANPeerEvent evt; - if((evt = PlatformWebRTC.serverLANGetEvent(clientId)) != null) { - if(evt instanceof LANPeerEvent.LANPeerICECandidateEvent) { - LANServerController.lanRelaySocket.writePacket(new RelayPacket03ICECandidate(clientId, ((LANPeerEvent.LANPeerICECandidateEvent)evt).candidates)); - state = SENT_ICE_CANDIDATE; - return; - }else if(evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { - logger.error("LAN client '{}' disconnected while waiting for server ICE candidates", clientId); - }else { - logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); - } - disconnect(); - return; - } - EagUtils.sleep(20l); - }while(EagRuntime.steadyTimeMillis() - millis < 5000l); - logger.error("Getting server ICE candidates for '{}' timed out!", clientId); - disconnect(); - }else { - logger.error("Relay [{}] unexpected IPacket03ICECandidate for '{}'", LANServerController.lanRelaySocket.getURI(), clientId); - } - } - - protected void handleDescription(String description) { - if(state == PRE) { - PlatformWebRTC.serverLANPeerDescription(clientId, description); - long millis = EagRuntime.steadyTimeMillis(); - do { - LANPeerEvent evt; - if((evt = PlatformWebRTC.serverLANGetEvent(clientId)) != null) { - if(evt instanceof LANPeerEvent.LANPeerDescriptionEvent) { - LANServerController.lanRelaySocket.writePacket(new RelayPacket04Description(clientId, ((LANPeerEvent.LANPeerDescriptionEvent)evt).description)); - state = SENT_DESCRIPTION; - return; - }else if(evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { - logger.error("LAN client '{}' disconnected while waiting for server description", clientId); - }else { - logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); - } - disconnect(); - return; - } - EagUtils.sleep(20l); - }while(EagRuntime.steadyTimeMillis() - millis < 5000l); - logger.error("Getting server description for '{}' timed out!", clientId); - disconnect(); - }else { - logger.error("Relay [{}] unexpected IPacket04Description for '{}'", LANServerController.lanRelaySocket.getURI(), clientId); - } - } - - protected void handleSuccess() { - if(state == SENT_ICE_CANDIDATE) { - long millis = EagRuntime.steadyTimeMillis(); - do { - LANPeerEvent evt; - while((evt = PlatformWebRTC.serverLANGetEvent(clientId)) != null && evt instanceof LANPeerEvent.LANPeerICECandidateEvent) { - // skip ice candidates - } - if(evt != null) { - if(evt instanceof LANPeerEvent.LANPeerDataChannelEvent) { - SingleplayerServerController.openPlayerChannel(clientId); - state = CONNECTED; - return; - }else if(evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { - logger.error("LAN client '{}' disconnected while waiting for connection", clientId); - }else { - logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); - } - disconnect(); - return; - } - EagUtils.sleep(20l); - }while(EagRuntime.steadyTimeMillis() - millis < 5000l); - logger.error("Getting server description for '{}' timed out!", clientId); - disconnect(); - }else { - logger.error("Relay [{}] unexpected IPacket05ClientSuccess for '{}'", LANServerController.lanRelaySocket.getURI(), clientId); - } - } - - protected void handleFailure() { - if(state == SENT_ICE_CANDIDATE) { - logger.error("Client '{}' failed to connect", clientId); - disconnect(); - }else { - logger.error("Relay [{}] unexpected IPacket06ClientFailure for '{}'", LANServerController.lanRelaySocket.getURI(), clientId); - } - } - - protected void update() { - if(state == CONNECTED) { - List l = PlatformWebRTC.serverLANGetAllEvent(clientId); - if(l == null) { - return; - } - Iterator itr = l.iterator(); - while(state == CONNECTED && itr.hasNext()) { - LANPeerEvent evt = itr.next(); - if(evt instanceof LANPeerEvent.LANPeerPacketEvent) { - ClientPlatformSingleplayer.sendPacket(new IPCPacketData(clientId, ((LANPeerEvent.LANPeerPacketEvent)evt).payload)); - }else if(evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { - logger.info("LAN client '{}' disconnected", clientId); - disconnect(); - }else { - logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); - disconnect(); - } - } - } - } - protected void disconnect() { - if(!dead) { - if(state == CONNECTED) { + if (!dead) { + if (state == CONNECTED) { SingleplayerServerController.closePlayerChannel(clientId); } state = CLOSED; @@ -173,4 +57,129 @@ class LANClientPeer { } } + protected void handleDescription(String description) { + if (state == PRE) { + PlatformWebRTC.serverLANPeerDescription(clientId, description); + long millis = EagRuntime.steadyTimeMillis(); + do { + LANPeerEvent evt; + if ((evt = PlatformWebRTC.serverLANGetEvent(clientId)) != null) { + if (evt instanceof LANPeerEvent.LANPeerDescriptionEvent) { + LANServerController.lanRelaySocket.writePacket(new RelayPacket04Description(clientId, + ((LANPeerEvent.LANPeerDescriptionEvent) evt).description)); + state = SENT_DESCRIPTION; + return; + } else if (evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { + logger.error("LAN client '{}' disconnected while waiting for server description", clientId); + } else { + logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); + } + disconnect(); + return; + } + EagUtils.sleep(20l); + } while (EagRuntime.steadyTimeMillis() - millis < 5000l); + logger.error("Getting server description for '{}' timed out!", clientId); + disconnect(); + } else { + logger.error("Relay [{}] unexpected IPacket04Description for '{}'", + LANServerController.lanRelaySocket.getURI(), clientId); + } + } + + protected void handleFailure() { + if (state == SENT_ICE_CANDIDATE) { + logger.error("Client '{}' failed to connect", clientId); + disconnect(); + } else { + logger.error("Relay [{}] unexpected IPacket06ClientFailure for '{}'", + LANServerController.lanRelaySocket.getURI(), clientId); + } + } + + protected void handleICECandidates(String candidates) { + if (state == SENT_DESCRIPTION) { + PlatformWebRTC.serverLANPeerICECandidates(clientId, candidates); + long millis = EagRuntime.steadyTimeMillis(); + do { + LANPeerEvent evt; + if ((evt = PlatformWebRTC.serverLANGetEvent(clientId)) != null) { + if (evt instanceof LANPeerEvent.LANPeerICECandidateEvent) { + LANServerController.lanRelaySocket.writePacket(new RelayPacket03ICECandidate(clientId, + ((LANPeerEvent.LANPeerICECandidateEvent) evt).candidates)); + state = SENT_ICE_CANDIDATE; + return; + } else if (evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { + logger.error("LAN client '{}' disconnected while waiting for server ICE candidates", clientId); + } else { + logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); + } + disconnect(); + return; + } + EagUtils.sleep(20l); + } while (EagRuntime.steadyTimeMillis() - millis < 5000l); + logger.error("Getting server ICE candidates for '{}' timed out!", clientId); + disconnect(); + } else { + logger.error("Relay [{}] unexpected IPacket03ICECandidate for '{}'", + LANServerController.lanRelaySocket.getURI(), clientId); + } + } + + protected void handleSuccess() { + if (state == SENT_ICE_CANDIDATE) { + long millis = EagRuntime.steadyTimeMillis(); + do { + LANPeerEvent evt; + while ((evt = PlatformWebRTC.serverLANGetEvent(clientId)) != null + && evt instanceof LANPeerEvent.LANPeerICECandidateEvent) { + // skip ice candidates + } + if (evt != null) { + if (evt instanceof LANPeerEvent.LANPeerDataChannelEvent) { + SingleplayerServerController.openPlayerChannel(clientId); + state = CONNECTED; + return; + } else if (evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { + logger.error("LAN client '{}' disconnected while waiting for connection", clientId); + } else { + logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); + } + disconnect(); + return; + } + EagUtils.sleep(20l); + } while (EagRuntime.steadyTimeMillis() - millis < 5000l); + logger.error("Getting server description for '{}' timed out!", clientId); + disconnect(); + } else { + logger.error("Relay [{}] unexpected IPacket05ClientSuccess for '{}'", + LANServerController.lanRelaySocket.getURI(), clientId); + } + } + + protected void update() { + if (state == CONNECTED) { + List l = PlatformWebRTC.serverLANGetAllEvent(clientId); + if (l == null) { + return; + } + Iterator itr = l.iterator(); + while (state == CONNECTED && itr.hasNext()) { + LANPeerEvent evt = itr.next(); + if (evt instanceof LANPeerEvent.LANPeerPacketEvent) { + ClientPlatformSingleplayer + .sendPacket(new IPCPacketData(clientId, ((LANPeerEvent.LANPeerPacketEvent) evt).payload)); + } else if (evt instanceof LANPeerEvent.LANPeerDisconnectEvent) { + logger.info("LAN client '{}' disconnected", clientId); + disconnect(); + } else { + logger.error("LAN client '{}' had an accident: {}", clientId, evt.getClass().getSimpleName()); + disconnect(); + } + } + } + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANPeerEvent.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANPeerEvent.java index 1485ed72..6559dbc0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANPeerEvent.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANPeerEvent.java @@ -3,44 +3,41 @@ package net.lax1dude.eaglercraft.v1_8.sp.lan; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface LANPeerEvent { - String getPeerId(); - - public static class LANPeerICECandidateEvent implements LANPeerEvent { - + public static class LANPeerDataChannelEvent implements LANPeerEvent { + public final String clientId; - public final String candidates; - - public LANPeerICECandidateEvent(String clientId, String candidates) { + + public LANPeerDataChannelEvent(String clientId) { this.clientId = clientId; - this.candidates = candidates; } @Override public String getPeerId() { return clientId; } - + } - + public static class LANPeerDescriptionEvent implements LANPeerEvent { - + public final String clientId; public final String description; - + public LANPeerDescriptionEvent(String clientId, String description) { this.clientId = clientId; this.description = description; @@ -50,14 +47,14 @@ public interface LANPeerEvent { public String getPeerId() { return clientId; } - + } - - public static class LANPeerDataChannelEvent implements LANPeerEvent { - + + public static class LANPeerDisconnectEvent implements LANPeerEvent { + public final String clientId; - - public LANPeerDataChannelEvent(String clientId) { + + public LANPeerDisconnectEvent(String clientId) { this.clientId = clientId; } @@ -65,14 +62,31 @@ public interface LANPeerEvent { public String getPeerId() { return clientId; } - + } - + + public static class LANPeerICECandidateEvent implements LANPeerEvent { + + public final String clientId; + public final String candidates; + + public LANPeerICECandidateEvent(String clientId, String candidates) { + this.clientId = clientId; + this.candidates = candidates; + } + + @Override + public String getPeerId() { + return clientId; + } + + } + public static class LANPeerPacketEvent implements LANPeerEvent { - + public final String clientId; public final byte[] payload; - + public LANPeerPacketEvent(String clientId, byte[] payload) { this.clientId = clientId; this.payload = payload; @@ -82,22 +96,9 @@ public interface LANPeerEvent { public String getPeerId() { return clientId; } - - } - - public static class LANPeerDisconnectEvent implements LANPeerEvent { - - public final String clientId; - - public LANPeerDisconnectEvent(String clientId) { - this.clientId = clientId; - } - @Override - public String getPeerId() { - return clientId; - } - } - + + String getPeerId(); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerController.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerController.java index c743baf0..480a82bf 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerController.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerController.java @@ -14,19 +14,28 @@ import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayManager; import net.lax1dude.eaglercraft.v1_8.sp.relay.RelayServerSocket; -import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.*; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket00Handshake; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket01ICEServers; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket02NewClient; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket03ICECandidate; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket04Description; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket05ClientSuccess; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket06ClientFailure; +import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacketFFErrorCode; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,60 +50,14 @@ public class LANServerController { private static String currentCode = null; - public static String shareToLAN(Consumer progressCallback, String worldName, boolean worldHidden) { - currentCode = null; - RelayServerSocket sock = RelayManager.relayManager.getWorkingRelay((str) -> progressCallback.accept("Connecting: " + str), - RelayManager.preferredRelayVersion, worldName + (worldHidden ? ";1" : ";0")); - if(sock == null) { - lanRelaySocket = null; - return null; - }else { - progressCallback.accept("Opening: " + sock.getURI()); - RelayPacket00Handshake hs = (RelayPacket00Handshake)sock.readPacket(); - lanRelaySocket = sock; - String code = hs.connectionCode; - logger.info("Relay [{}] connected as 'server', code: {}", sock.getURI(), code); - progressCallback.accept("Opened '" + code + "' on " + sock.getURI()); - long millis = EagRuntime.steadyTimeMillis(); - do { - sock.update(); - if(sock.isClosed()) { - logger.info("Relay [{}] connection lost", sock.getURI()); - lanRelaySocket = null; - return null; - } - RelayPacket pkt = sock.readPacket(); - if(pkt != null) { - if(pkt instanceof RelayPacket01ICEServers) { - RelayPacket01ICEServers ipkt = (RelayPacket01ICEServers)pkt; - logger.info("Relay [{}] provided ICE servers:", sock.getURI()); - currentICEServers.clear(); - for(net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket01ICEServers.RelayServer srv : ipkt.servers) { - logger.info("Relay [{}] {}: {}", sock.getURI(), srv.type.name(), srv.address); - currentICEServers.add(srv.getICEString()); - } - PlatformWebRTC.serverLANInitializeServer(currentICEServers.toArray(new String[currentICEServers.size()])); - return currentCode = code; - }else { - logger.error("Relay [{}] unexpected packet: {}", sock.getURI(), pkt.getClass().getSimpleName()); - closeLAN(); - return null; - } - } - EagUtils.sleep(50l); - }while(EagRuntime.steadyTimeMillis() - millis < 1000l); - logger.info("Relay [{}] relay provide ICE servers timeout", sock.getURI()); - closeLAN(); - return null; + private static final Map clients = new HashMap<>(); + + public static void cleanupLAN() { + Iterator itr = clients.values().iterator(); + while (itr.hasNext()) { + itr.next().disconnect(); } - } - - public static String getCurrentURI() { - return lanRelaySocket == null ? "" : lanRelaySocket.getURI(); - } - - public static String getCurrentCode() { - return currentCode == null ? "" : currentCode; + clients.clear(); } public static void closeLAN() { @@ -106,19 +69,19 @@ public class LANServerController { } public static void closeLANNoKick() { - if(lanRelaySocket != null) { + if (lanRelaySocket != null) { lanRelaySocket.close(); lanRelaySocket = null; currentCode = null; } } - public static void cleanupLAN() { - Iterator itr = clients.values().iterator(); - while(itr.hasNext()) { - itr.next().disconnect(); - } - clients.clear(); + public static String getCurrentCode() { + return currentCode == null ? "" : currentCode; + } + + public static String getCurrentURI() { + return lanRelaySocket == null ? "" : lanRelaySocket.getURI(); } public static boolean hasPeers() { @@ -133,79 +96,134 @@ public class LANServerController { return lanRelaySocket != null; } - private static final Map clients = new HashMap<>(); - - public static void updateLANServer() { - if(lanRelaySocket != null) { - lanRelaySocket.update(); - RelayPacket pkt; - while((pkt = lanRelaySocket.readPacket()) != null) { - if(pkt instanceof RelayPacket02NewClient) { - RelayPacket02NewClient ipkt = (RelayPacket02NewClient) pkt; - if(clients.containsKey(ipkt.clientId)) { - logger.error("Relay [{}] relay provided duplicate client '{}'", lanRelaySocket.getURI(), ipkt.clientId); - }else { - clients.put(ipkt.clientId, new LANClientPeer(ipkt.clientId)); - } - }else if(pkt instanceof RelayPacket03ICECandidate) { - RelayPacket03ICECandidate ipkt = (RelayPacket03ICECandidate) pkt; - LANClientPeer c = clients.get(ipkt.peerId); - if(c != null) { - c.handleICECandidates(ipkt.getCandidateString()); - }else { - logger.error("Relay [{}] relay sent IPacket03ICECandidate for unknown client '{}'", lanRelaySocket.getURI(), ipkt.peerId); - } - }else if(pkt instanceof RelayPacket04Description) { - RelayPacket04Description ipkt = (RelayPacket04Description) pkt; - LANClientPeer c = clients.get(ipkt.peerId); - if(c != null) { - c.handleDescription(ipkt.getDescriptionString()); - }else { - logger.error("Relay [{}] relay sent IPacket04Description for unknown client '{}'", lanRelaySocket.getURI(), ipkt.peerId); - } - }else if(pkt instanceof RelayPacket05ClientSuccess) { - RelayPacket05ClientSuccess ipkt = (RelayPacket05ClientSuccess) pkt; - LANClientPeer c = clients.get(ipkt.clientId); - if(c != null) { - c.handleSuccess(); - }else { - logger.error("Relay [{}] relay sent IPacket05ClientSuccess for unknown client '{}'", lanRelaySocket.getURI(), ipkt.clientId); - } - }else if(pkt instanceof RelayPacket06ClientFailure) { - RelayPacket06ClientFailure ipkt = (RelayPacket06ClientFailure) pkt; - LANClientPeer c = clients.get(ipkt.clientId); - if(c != null) { - c.handleFailure(); - }else { - logger.error("Relay [{}] relay sent IPacket06ClientFailure for unknown client '{}'", lanRelaySocket.getURI(), ipkt.clientId); - } - }else if(pkt instanceof RelayPacketFFErrorCode) { - RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; - logger.error("Relay [{}] error code thrown: {}({}): {}", lanRelaySocket.getURI(), RelayPacketFFErrorCode.code2string(ipkt.code), ipkt.code, ipkt.desc); - Throwable t; - while((t = lanRelaySocket.getException()) != null) { - logger.error(t); - } - }else { - logger.error("Relay [{}] unexpected packet: {}", lanRelaySocket.getURI(), pkt.getClass().getSimpleName()); + public static String shareToLAN(Consumer progressCallback, String worldName, boolean worldHidden) { + currentCode = null; + RelayServerSocket sock = RelayManager.relayManager.getWorkingRelay( + (str) -> progressCallback.accept("Connecting: " + str), RelayManager.preferredRelayVersion, + worldName + (worldHidden ? ";1" : ";0")); + if (sock == null) { + lanRelaySocket = null; + return null; + } else { + progressCallback.accept("Opening: " + sock.getURI()); + RelayPacket00Handshake hs = (RelayPacket00Handshake) sock.readPacket(); + lanRelaySocket = sock; + String code = hs.connectionCode; + logger.info("Relay [{}] connected as 'server', code: {}", sock.getURI(), code); + progressCallback.accept("Opened '" + code + "' on " + sock.getURI()); + long millis = EagRuntime.steadyTimeMillis(); + do { + sock.update(); + if (sock.isClosed()) { + logger.info("Relay [{}] connection lost", sock.getURI()); + lanRelaySocket = null; + return null; } - lanRelaySocket.update(); - } - if(lanRelaySocket.isClosed()) { - lanRelaySocket = null; - } - } - Iterator itr = clients.values().iterator(); - while(itr.hasNext()) { - LANClientPeer cl = itr.next(); - cl.update(); - if(cl.dead) { - itr.remove(); - } + RelayPacket pkt = sock.readPacket(); + if (pkt != null) { + if (pkt instanceof RelayPacket01ICEServers) { + RelayPacket01ICEServers ipkt = (RelayPacket01ICEServers) pkt; + logger.info("Relay [{}] provided ICE servers:", sock.getURI()); + currentICEServers.clear(); + for (net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket01ICEServers.RelayServer srv : ipkt.servers) { + logger.info("Relay [{}] {}: {}", sock.getURI(), srv.type.name(), srv.address); + currentICEServers.add(srv.getICEString()); + } + PlatformWebRTC.serverLANInitializeServer( + currentICEServers.toArray(new String[currentICEServers.size()])); + return currentCode = code; + } else { + logger.error("Relay [{}] unexpected packet: {}", sock.getURI(), pkt.getClass().getSimpleName()); + closeLAN(); + return null; + } + } + EagUtils.sleep(50l); + } while (EagRuntime.steadyTimeMillis() - millis < 1000l); + logger.info("Relay [{}] relay provide ICE servers timeout", sock.getURI()); + closeLAN(); + return null; } } public static boolean supported() { return PlatformWebRTC.supported(); } + + public static void updateLANServer() { + if (lanRelaySocket != null) { + lanRelaySocket.update(); + RelayPacket pkt; + while ((pkt = lanRelaySocket.readPacket()) != null) { + if (pkt instanceof RelayPacket02NewClient) { + RelayPacket02NewClient ipkt = (RelayPacket02NewClient) pkt; + if (clients.containsKey(ipkt.clientId)) { + logger.error("Relay [{}] relay provided duplicate client '{}'", lanRelaySocket.getURI(), + ipkt.clientId); + } else { + clients.put(ipkt.clientId, new LANClientPeer(ipkt.clientId)); + } + } else if (pkt instanceof RelayPacket03ICECandidate) { + RelayPacket03ICECandidate ipkt = (RelayPacket03ICECandidate) pkt; + LANClientPeer c = clients.get(ipkt.peerId); + if (c != null) { + c.handleICECandidates(ipkt.getCandidateString()); + } else { + logger.error("Relay [{}] relay sent IPacket03ICECandidate for unknown client '{}'", + lanRelaySocket.getURI(), ipkt.peerId); + } + } else if (pkt instanceof RelayPacket04Description) { + RelayPacket04Description ipkt = (RelayPacket04Description) pkt; + LANClientPeer c = clients.get(ipkt.peerId); + if (c != null) { + c.handleDescription(ipkt.getDescriptionString()); + } else { + logger.error("Relay [{}] relay sent IPacket04Description for unknown client '{}'", + lanRelaySocket.getURI(), ipkt.peerId); + } + } else if (pkt instanceof RelayPacket05ClientSuccess) { + RelayPacket05ClientSuccess ipkt = (RelayPacket05ClientSuccess) pkt; + LANClientPeer c = clients.get(ipkt.clientId); + if (c != null) { + c.handleSuccess(); + } else { + logger.error("Relay [{}] relay sent IPacket05ClientSuccess for unknown client '{}'", + lanRelaySocket.getURI(), ipkt.clientId); + } + } else if (pkt instanceof RelayPacket06ClientFailure) { + RelayPacket06ClientFailure ipkt = (RelayPacket06ClientFailure) pkt; + LANClientPeer c = clients.get(ipkt.clientId); + if (c != null) { + c.handleFailure(); + } else { + logger.error("Relay [{}] relay sent IPacket06ClientFailure for unknown client '{}'", + lanRelaySocket.getURI(), ipkt.clientId); + } + } else if (pkt instanceof RelayPacketFFErrorCode) { + RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; + logger.error("Relay [{}] error code thrown: {}({}): {}", lanRelaySocket.getURI(), + RelayPacketFFErrorCode.code2string(ipkt.code), ipkt.code, ipkt.desc); + Throwable t; + while ((t = lanRelaySocket.getException()) != null) { + logger.error(t); + } + } else { + logger.error("Relay [{}] unexpected packet: {}", lanRelaySocket.getURI(), + pkt.getClass().getSimpleName()); + } + lanRelaySocket.update(); + } + if (lanRelaySocket.isClosed()) { + lanRelaySocket = null; + } + } + Iterator itr = clients.values().iterator(); + while (itr.hasNext()) { + LANClientPeer cl = itr.next(); + cl.update(); + if (cl.dead) { + itr.remove(); + } + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerList.java index d396f6ee..17194aef 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/lan/LANServerList.java @@ -19,71 +19,127 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket07LocalWorlds; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class LANServerList { - + + public class LanServer { + + private String lanServerMotd; + private RelayServer lanServerRelay; + private String lanServerCode; + + protected boolean flagged = true; + + protected LanServer(String lanServerMotd, RelayServer lanServerRelay, String lanServerCode) { + this.lanServerMotd = lanServerMotd; + this.lanServerRelay = lanServerRelay; + this.lanServerCode = lanServerCode; + } + + public String getLanServerCode() { + return lanServerCode; + } + + public String getLanServerMotd() { + return lanServerMotd; + } + + public RelayServer getLanServerRelay() { + return lanServerRelay; + } + + } + private final List lanServersList = new LinkedList<>(); private final Map lanServersQueryList = new LinkedHashMap<>(); + private final Set deadURIs = new HashSet<>(); - private long lastRefresh = 0l; + private int refreshCounter = 0; - + + public int countServers() { + return lanServersList.size(); + } + + public void forceRefresh() { + deadURIs.clear(); + refreshCounter = 0; + refresh(); + } + + public LanServer getServer(int idx) { + return lanServersList.get(idx); + } + + private void refresh() { + lastRefresh = EagRuntime.steadyTimeMillis(); + if (PlatformWebRTC.supported()) { + for (int i = 0, l = RelayManager.relayManager.count(); i < l; ++i) { + RelayServer srv = RelayManager.relayManager.get(i); + if (!lanServersQueryList.containsKey(srv.address) && !deadURIs.contains(srv.address)) { + lanServersQueryList.put(srv.address, PlatformWebRTC.openRelayWorldsQuery(srv.address)); + } + } + } + } + public boolean update() { long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastRefresh > 20000l) { - if(++refreshCounter < 10) { + if (millis - lastRefresh > 20000l) { + if (++refreshCounter < 10) { refresh(); - }else { + } else { lastRefresh = millis; } - }else { + } else { boolean changed = false; - Iterator> itr = lanServersQueryList.entrySet().iterator(); - while(itr.hasNext()) { - Entry etr = itr.next(); + Iterator> itr = lanServersQueryList.entrySet().iterator(); + while (itr.hasNext()) { + Entry etr = itr.next(); String uri = etr.getKey(); RelayWorldsQuery q = etr.getValue(); q.update(); - if(!q.isQueryOpen()) { + if (!q.isQueryOpen()) { itr.remove(); - if(q.isQueryFailed()) { + if (q.isQueryFailed()) { deadURIs.add(uri); Iterator itr2 = lanServersList.iterator(); - while(itr2.hasNext()) { - if(itr2.next().lanServerRelay.address.equals(uri)) { + while (itr2.hasNext()) { + if (itr2.next().lanServerRelay.address.equals(uri)) { itr2.remove(); changed = true; } } - }else { + } else { RelayServer rl = RelayManager.relayManager.getByURI(uri); Iterator itr2 = lanServersList.iterator(); - while(itr2.hasNext()) { + while (itr2.hasNext()) { LanServer l = itr2.next(); - if(l.lanServerRelay.address.equals(uri)) { + if (l.lanServerRelay.address.equals(uri)) { l.flagged = false; } } - if(rl != null) { + if (rl != null) { Iterator itr3 = q.getWorlds().iterator(); - yee: while(itr3.hasNext()) { + yee: while (itr3.hasNext()) { RelayPacket07LocalWorlds.LocalWorld l = itr3.next(); itr2 = lanServersList.iterator(); - while(itr2.hasNext()) { + while (itr2.hasNext()) { LanServer l2 = itr2.next(); - if(l2.lanServerRelay.address.equals(uri) && l2.lanServerCode.equals(l.worldCode)) { + if (l2.lanServerRelay.address.equals(uri) && l2.lanServerCode.equals(l.worldCode)) { l2.lanServerMotd = l.worldName; l2.flagged = true; continue yee; @@ -94,10 +150,10 @@ public class LANServerList { } } itr2 = lanServersList.iterator(); - while(itr2.hasNext()) { + while (itr2.hasNext()) { LanServer l = itr2.next(); - if(l.lanServerRelay.address.equals(uri)) { - if(!l.flagged) { + if (l.lanServerRelay.address.equals(uri)) { + if (!l.flagged) { itr2.remove(); changed = true; } @@ -110,59 +166,5 @@ public class LANServerList { } return false; } - - public void forceRefresh() { - deadURIs.clear(); - refreshCounter = 0; - refresh(); - } - private void refresh() { - lastRefresh = EagRuntime.steadyTimeMillis(); - if(PlatformWebRTC.supported()) { - for(int i = 0, l = RelayManager.relayManager.count(); i < l; ++i) { - RelayServer srv = RelayManager.relayManager.get(i); - if(!lanServersQueryList.containsKey(srv.address) && !deadURIs.contains(srv.address)) { - lanServersQueryList.put(srv.address, PlatformWebRTC.openRelayWorldsQuery(srv.address)); - } - } - } - } - - public LanServer getServer(int idx) { - return lanServersList.get(idx); - } - - public int countServers() { - return lanServersList.size(); - } - - public class LanServer { - - private String lanServerMotd; - private RelayServer lanServerRelay; - private String lanServerCode; - - protected boolean flagged = true; - - protected LanServer(String lanServerMotd, RelayServer lanServerRelay, String lanServerCode) { - this.lanServerMotd = lanServerMotd; - this.lanServerRelay = lanServerRelay; - this.lanServerCode = lanServerCode; - } - - public String getLanServerMotd() { - return lanServerMotd; - } - - public RelayServer getLanServerRelay() { - return lanServerRelay; - } - - public String getLanServerCode() { - return lanServerCode; - } - - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayEntry.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayEntry.java index 0094056e..637ee863 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayEntry.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayEntry.java @@ -3,28 +3,29 @@ package net.lax1dude.eaglercraft.v1_8.sp.relay; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayEntry { - + public final String address; public final String comment; public final boolean primary; - + public RelayEntry(String address, String comment, boolean primary) { this.address = address; this.comment = comment; this.primary = primary; } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayLoggerImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayLoggerImpl.java index c9344cc5..d470ef03 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayLoggerImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayLoggerImpl.java @@ -6,14 +6,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.IRelayLogger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,16 +32,6 @@ public class RelayLoggerImpl implements IRelayLogger { impl.debug(msg, args); } - @Override - public void info(String msg, Object... args) { - impl.debug(msg, args); - } - - @Override - public void warn(String msg, Object... args) { - impl.warn(msg, args); - } - @Override public void error(String msg, Object... args) { impl.error(msg, args); @@ -51,4 +42,14 @@ public class RelayLoggerImpl implements IRelayLogger { impl.error(th); } + @Override + public void info(String msg, Object... args) { + impl.debug(msg, args); + } + + @Override + public void warn(String msg, Object... args) { + impl.warn(msg, args); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayManager.java index 937d5803..ecf6a319 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayManager.java @@ -24,14 +24,15 @@ import net.minecraft.nbt.NBTTagList; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,40 +43,98 @@ public class RelayManager { public static final RelayManager relayManager = new RelayManager(); public static final int preferredRelayVersion = 1; - + private final List relays = new ArrayList<>(); private long lastPingThrough = 0l; - public void load(byte[] relayConfig) { - NBTTagCompound relays = null; - if(relayConfig != null) { - try { - relays = CompressedStreamTools.readCompressed(new EaglerInputStream(relayConfig)); - } catch (IOException ex) { - } + private final List brokenServers = new LinkedList<>(); + + public void add(String addr, String comment, boolean primary) { + lastPingThrough = 0l; + int i = relays.size(); + relays.add(new RelayServer(addr, comment, false)); + if (primary) { + setPrimary0(i); } - if(relays != null && relays.hasKey("relays", 9)) { - load(relays.getTagList("relays", 10)); - if(!relays.getBoolean("f")) { - fixBullshit(); - } - }else { - sort(); // loads defaults - save(); + save(); + } + + public void addNew(String addr, String comment, boolean primary) { + lastPingThrough = 0l; + int i = relays.size(); + int j = primary || i == 0 ? 0 : 1; + RelayServer newServer = new RelayServer(addr, comment, false); + relays.add(j, newServer); + newServer.ping(); + if (primary) { + setPrimary0(j); } + save(); + } + + public void close() { + for (int i = 0, l = relays.size(); i < l; ++i) { + relays.get(i).close(); + } + } + + public RelayServerSocket connectHandshake(RelayServer relay, int type, String code) { + RelayServerSocket sock = relay.openSocket(); + while (!sock.isClosed()) { + sock.update(); + if (sock.isOpen()) { + sock.writePacket(new RelayPacket00Handshake(type, preferredRelayVersion, code)); + while (!sock.isClosed()) { + sock.update(); + RelayPacket pkt = sock.nextPacket(); + if (pkt != null) { + if (pkt instanceof RelayPacket00Handshake) { + return sock; + } else if (pkt instanceof RelayPacketFFErrorCode) { + RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; + logger.error("Relay [{}] failed: {}({}): {}", relay.address, + RelayPacketFFErrorCode.code2string(ipkt.code), ipkt.code, ipkt.desc); + Throwable t; + while ((t = sock.getException()) != null) { + logger.error(t); + } + sock.close(); + return null; + } else { + logger.error("Relay [{}] unexpected packet: {}", relay.address, + pkt.getClass().getSimpleName()); + sock.close(); + return null; + } + } + EagUtils.sleep(20l); + } + } + EagUtils.sleep(20l); + } + logger.error("Relay [{}] connection failed!", relay.address); + Throwable t; + while ((t = sock.getException()) != null) { + logger.error(t); + } + return null; + } + + public int count() { + return relays.size(); } // versions pre-u24 always have "relay.deev.is" as primary due to a glitch // this function is intended to randomize the list if that is detected private void fixBullshit() { - if(!relays.isEmpty()) { - for(int i = 0, l = relays.size(); i < l; ++i) { + if (!relays.isEmpty()) { + for (int i = 0, l = relays.size(); i < l; ++i) { RelayServer rs = relays.get(i); - if(rs.address.equalsIgnoreCase("wss://relay.deev.is/") && !rs.isPrimary()) { + if (rs.address.equalsIgnoreCase("wss://relay.deev.is/") && !rs.isPrimary()) { return; } } - for(int i = 0, l = relays.size(); i < l; ++i) { + for (int i = 0, l = relays.size(); i < l; ++i) { relays.get(i).setPrimary(false); } relays.get(ThreadLocalRandom.current().nextInt(relays.size())).setPrimary(true); @@ -84,17 +143,129 @@ public class RelayManager { } } + public RelayServer get(int idx) { + return relays.get(idx); + } + + public RelayServer getByURI(String uri) { + Iterator itr = relays.iterator(); + while (itr.hasNext()) { + RelayServer rl = itr.next(); + if (rl.address.equals(uri)) { + return rl; + } + } + return null; + } + + public RelayServer getPrimary() { + if (!relays.isEmpty()) { + for (int i = 0, l = relays.size(); i < l; ++i) { + RelayServer srv = relays.get(i); + if (srv.isPrimary()) { + return srv; + } + } + sort(); + save(); + return getPrimary(); + } else { + return null; + } + } + + private RelayServerSocket getWorkingCodeRelayActive(Consumer progressCallback, int type, String code) { + if (!relays.isEmpty()) { + for (int i = 0, l = relays.size(); i < l; ++i) { + RelayServer srv = relays.get(i); + if (!brokenServers.contains(srv)) { + progressCallback.accept(srv.address); + RelayServerSocket sock = connectHandshake(srv, type, code); + if (sock != null) { + if (!sock.isFailed()) { + return sock; + } + } else { + brokenServers.add(srv); + } + } + } + return null; + } else { + return null; + } + } + + public RelayServerSocket getWorkingRelay(Consumer progressCallback, int type, String code) { + brokenServers.clear(); + if (!relays.isEmpty()) { + long millis = EagRuntime.steadyTimeMillis(); + if (millis - lastPingThrough < 10000l) { + RelayServer relay = getPrimary(); + if (relay.getPing() > 0l && relay.getPingCompatible().isCompatible()) { + progressCallback.accept(relay.address); + RelayServerSocket sock = connectHandshake(relay, type, code); + if (sock != null) { + if (!sock.isFailed()) { + return sock; + } + } else { + brokenServers.add(relay); + } + } + for (int i = 0, l = relays.size(); i < l; ++i) { + RelayServer relayEtr = relays.get(i); + if (relayEtr != relay) { + if (relayEtr.getPing() > 0l && relayEtr.getPingCompatible().isCompatible()) { + progressCallback.accept(relayEtr.address); + RelayServerSocket sock = connectHandshake(relayEtr, type, code); + if (sock != null) { + if (!sock.isFailed()) { + return sock; + } + } else { + brokenServers.add(relayEtr); + } + } + } + } + } + return getWorkingCodeRelayActive(progressCallback, type, code); + } else { + return null; + } + } + + public void load(byte[] relayConfig) { + NBTTagCompound relays = null; + if (relayConfig != null) { + try { + relays = CompressedStreamTools.readCompressed(new EaglerInputStream(relayConfig)); + } catch (IOException ex) { + } + } + if (relays != null && relays.hasKey("relays", 9)) { + load(relays.getTagList("relays", 10)); + if (!relays.getBoolean("f")) { + fixBullshit(); + } + } else { + sort(); // loads defaults + save(); + } + } + private void load(NBTTagList relayConfig) { relays.clear(); - if(relayConfig != null && relayConfig.tagCount() > 0) { + if (relayConfig != null && relayConfig.tagCount() > 0) { boolean gotAPrimary = false; - for(int i = 0, l = relayConfig.tagCount(); i < l; ++i) { + for (int i = 0, l = relayConfig.tagCount(); i < l; ++i) { NBTTagCompound relay = relayConfig.getCompoundTagAt(i); boolean p = relay.getBoolean("primary"); - if(p) { - if(gotAPrimary) { + if (p) { + if (gotAPrimary) { p = false; - }else { + } else { gotAPrimary = true; } } @@ -103,21 +274,132 @@ public class RelayManager { } sort(); } - + + public void loadDefaults() { + List defaultRelays = EagRuntime.getConfiguration().getRelays(); + eee: for (int i = 0, l = defaultRelays.size(); i < l; ++i) { + RelayEntry etr = defaultRelays.get(i); + for (int j = 0, l2 = relays.size(); j < l2; ++j) { + if (relays.get(j).address.equalsIgnoreCase(etr.address)) { + continue eee; + } + } + relays.add(new RelayServer(etr)); + } + sort(); + } + + public String makeNewRelayName() { + String str = "Relay Server #" + (relays.size() + 1); + for (int i = relays.size() + 2, l = relays.size() + 50; i < l; ++i) { + if (str.equalsIgnoreCase("Relay Server #" + i)) { + str = "Relay Server #" + (i + 1); + } + } + eee: while (true) { + for (int i = 0, l = relays.size(); i < l; ++i) { + if (str.equalsIgnoreCase(relays.get(i).comment)) { + str = str + "_"; + continue eee; + } + } + break; + } + return str; + } + + public void ping() { + lastPingThrough = EagRuntime.steadyTimeMillis(); + for (int i = 0, l = relays.size(); i < l; ++i) { + relays.get(i).ping(); + } + } + + public void remove(int idx) { + RelayServer srv = relays.remove(idx); + srv.close(); + sort(); + save(); + } + public void save() { - if(relays.isEmpty()) { + if (relays.isEmpty()) { return; } byte[] data = write(); - if(data != null) { + if (data != null) { EagRuntime.setStorage("r", data); } } - + + public void setPrimary(int idx) { + setPrimary0(idx); + save(); + } + + private void setPrimary0(int idx) { + if (idx >= 0 && idx < relays.size()) { + for (int i = 0, l = relays.size(); i < l; ++i) { + RelayServer srv = relays.get(i); + if (srv.isPrimary()) { + srv.setPrimary(false); + } + } + RelayServer pr = relays.remove(idx); + pr.setPrimary(true); + relays.add(0, pr); + } + } + + private void sort() { + if (relays.isEmpty()) { + List defaultRelays = EagRuntime.getConfiguration().getRelays(); + for (int i = 0, l = defaultRelays.size(); i < l; ++i) { + relays.add(new RelayServer(defaultRelays.get(i))); + } + } + if (relays.isEmpty()) { + return; + } + int j = -1; + for (int i = 0, l = relays.size(); i < l; ++i) { + if (relays.get(i).isPrimary()) { + if (j == -1) { + j = i; + } else { + relays.get(i).setPrimary(false); + } + } + } + if (j == -1) { + boolean found = false; + for (int i = 0, l = relays.size(); i < l; ++i) { + RelayServer srv = relays.get(i); + if (srv.getPing() > 0l) { + found = true; + srv.setPrimary(true); + break; + } + } + if (!found) { + relays.get(0).setPrimary(true); + } + } else { + RelayServer srv = relays.remove(j); + relays.add(0, srv); + } + } + + public void update() { + for (int i = 0, l = relays.size(); i < l; ++i) { + relays.get(i).update(); + } + } + public byte[] write() { try { NBTTagList lst = new NBTTagList(); - for(int i = 0, l = relays.size(); i < l; ++i) { + for (int i = 0, l = relays.size(); i < l; ++i) { RelayServer srv = relays.get(i); NBTTagCompound etr = new NBTTagCompound(); etr.setString("addr", srv.address); @@ -139,284 +421,5 @@ public class RelayManager { return null; } } - - private void sort() { - if(relays.isEmpty()) { - List defaultRelays = EagRuntime.getConfiguration().getRelays(); - for(int i = 0, l = defaultRelays.size(); i < l; ++i) { - relays.add(new RelayServer(defaultRelays.get(i))); - } - } - if(relays.isEmpty()) { - return; - } - int j = -1; - for(int i = 0, l = relays.size(); i < l; ++i) { - if(relays.get(i).isPrimary()) { - if(j == -1) { - j = i; - }else { - relays.get(i).setPrimary(false); - } - } - } - if(j == -1) { - boolean found = false; - for(int i = 0, l = relays.size(); i < l; ++i) { - RelayServer srv = relays.get(i); - if(srv.getPing() > 0l) { - found = true; - srv.setPrimary(true); - break; - } - } - if(!found) { - relays.get(0).setPrimary(true); - } - }else { - RelayServer srv = relays.remove(j); - relays.add(0, srv); - } - } - - public void ping() { - lastPingThrough = EagRuntime.steadyTimeMillis(); - for(int i = 0, l = relays.size(); i < l; ++i) { - relays.get(i).ping(); - } - } - - public void update() { - for(int i = 0, l = relays.size(); i < l; ++i) { - relays.get(i).update(); - } - } - - public void close() { - for(int i = 0, l = relays.size(); i < l; ++i) { - relays.get(i).close(); - } - } - - public int count() { - return relays.size(); - } - - public RelayServer get(int idx) { - return relays.get(idx); - } - - public void add(String addr, String comment, boolean primary) { - lastPingThrough = 0l; - int i = relays.size(); - relays.add(new RelayServer(addr, comment, false)); - if(primary) { - setPrimary0(i); - } - save(); - } - - public void addNew(String addr, String comment, boolean primary) { - lastPingThrough = 0l; - int i = relays.size(); - int j = primary || i == 0 ? 0 : 1; - RelayServer newServer = new RelayServer(addr, comment, false); - relays.add(j, newServer); - newServer.ping(); - if(primary) { - setPrimary0(j); - } - save(); - } - - public void setPrimary(int idx) { - setPrimary0(idx); - save(); - } - private void setPrimary0(int idx) { - if(idx >= 0 && idx < relays.size()) { - for(int i = 0, l = relays.size(); i < l; ++i) { - RelayServer srv = relays.get(i); - if(srv.isPrimary()) { - srv.setPrimary(false); - } - } - RelayServer pr = relays.remove(idx); - pr.setPrimary(true); - relays.add(0, pr); - } - } - - public void remove(int idx) { - RelayServer srv = relays.remove(idx); - srv.close(); - sort(); - save(); - } - - public RelayServer getPrimary() { - if(!relays.isEmpty()) { - for(int i = 0, l = relays.size(); i < l; ++i) { - RelayServer srv = relays.get(i); - if(srv.isPrimary()) { - return srv; - } - } - sort(); - save(); - return getPrimary(); - }else { - return null; - } - } - - public RelayServerSocket connectHandshake(RelayServer relay, int type, String code) { - RelayServerSocket sock = relay.openSocket(); - while(!sock.isClosed()) { - sock.update(); - if(sock.isOpen()) { - sock.writePacket(new RelayPacket00Handshake(type, preferredRelayVersion, code)); - while(!sock.isClosed()) { - sock.update(); - RelayPacket pkt = sock.nextPacket(); - if(pkt != null) { - if(pkt instanceof RelayPacket00Handshake) { - return sock; - }else if(pkt instanceof RelayPacketFFErrorCode) { - RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; - logger.error("Relay [{}] failed: {}({}): {}", relay.address, RelayPacketFFErrorCode.code2string(ipkt.code), ipkt.code, ipkt.desc); - Throwable t; - while((t = sock.getException()) != null) { - logger.error(t); - } - sock.close(); - return null; - }else { - logger.error("Relay [{}] unexpected packet: {}", relay.address, pkt.getClass().getSimpleName()); - sock.close(); - return null; - } - } - EagUtils.sleep(20l); - } - } - EagUtils.sleep(20l); - } - logger.error("Relay [{}] connection failed!", relay.address); - Throwable t; - while((t = sock.getException()) != null) { - logger.error(t); - } - return null; - } - - private final List brokenServers = new LinkedList<>(); - - public RelayServerSocket getWorkingRelay(Consumer progressCallback, int type, String code) { - brokenServers.clear(); - if(!relays.isEmpty()) { - long millis = EagRuntime.steadyTimeMillis(); - if(millis - lastPingThrough < 10000l) { - RelayServer relay = getPrimary(); - if(relay.getPing() > 0l && relay.getPingCompatible().isCompatible()) { - progressCallback.accept(relay.address); - RelayServerSocket sock = connectHandshake(relay, type, code); - if(sock != null) { - if(!sock.isFailed()) { - return sock; - } - }else { - brokenServers.add(relay); - } - } - for(int i = 0, l = relays.size(); i < l; ++i) { - RelayServer relayEtr = relays.get(i); - if(relayEtr != relay) { - if(relayEtr.getPing() > 0l && relayEtr.getPingCompatible().isCompatible()) { - progressCallback.accept(relayEtr.address); - RelayServerSocket sock = connectHandshake(relayEtr, type, code); - if(sock != null) { - if(!sock.isFailed()) { - return sock; - } - }else { - brokenServers.add(relayEtr); - } - } - } - } - } - return getWorkingCodeRelayActive(progressCallback, type, code); - }else { - return null; - } - } - - private RelayServerSocket getWorkingCodeRelayActive(Consumer progressCallback, int type, String code) { - if(!relays.isEmpty()) { - for(int i = 0, l = relays.size(); i < l; ++i) { - RelayServer srv = relays.get(i); - if(!brokenServers.contains(srv)) { - progressCallback.accept(srv.address); - RelayServerSocket sock = connectHandshake(srv, type, code); - if(sock != null) { - if(!sock.isFailed()) { - return sock; - } - }else { - brokenServers.add(srv); - } - } - } - return null; - }else { - return null; - } - } - - public void loadDefaults() { - List defaultRelays = EagRuntime.getConfiguration().getRelays(); - eee: for(int i = 0, l = defaultRelays.size(); i < l; ++i) { - RelayEntry etr = defaultRelays.get(i); - for(int j = 0, l2 = relays.size(); j < l2; ++j) { - if(relays.get(j).address.equalsIgnoreCase(etr.address)) { - continue eee; - } - } - relays.add(new RelayServer(etr)); - } - sort(); - } - - public String makeNewRelayName() { - String str = "Relay Server #" + (relays.size() + 1); - for(int i = relays.size() + 2, l = relays.size() + 50; i < l; ++i) { - if(str.equalsIgnoreCase("Relay Server #" + i)) { - str = "Relay Server #" + (i + 1); - } - } - eee: while(true) { - for(int i = 0, l = relays.size(); i < l; ++i) { - if(str.equalsIgnoreCase(relays.get(i).comment)) { - str = str + "_"; - continue eee; - } - } - break; - } - return str; - } - - public RelayServer getByURI(String uri) { - Iterator itr = relays.iterator(); - while(itr.hasNext()) { - RelayServer rl = itr.next(); - if(rl.address.equals(uri)) { - return rl; - } - } - return null; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQuery.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQuery.java index 05e24a2f..e9de2b28 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQuery.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQuery.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.sp.relay; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,22 +24,30 @@ public interface RelayQuery { enum VersionMismatch { COMPATIBLE, CLIENT_OUTDATED, RELAY_OUTDATED, UNKNOWN; + public boolean isCompatible() { return this == COMPATIBLE; } } - void update(); - boolean isQueryOpen(); - boolean isQueryFailed(); - RateLimit isQueryRateLimit(); void close(); - - int getVersion(); - String getComment(); + String getBrand(); - long getPing(); + + String getComment(); VersionMismatch getCompatible(); + long getPing(); + + int getVersion(); + + boolean isQueryFailed(); + + boolean isQueryOpen(); + + RateLimit isQueryRateLimit(); + + void update(); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryImpl.java index 09c28da5..cc5f18c1 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryImpl.java @@ -22,14 +22,15 @@ import net.lax1dude.eaglercraft.v1_8.update.UpdateService; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -65,48 +66,98 @@ public class RelayQueryImpl implements RelayQuery { try { connectionOpenedAt = EagRuntime.steadyTimeMillis(); s = PlatformNetworking.openWebSocketUnsafe(uri); - }catch(Throwable t) { + } catch (Throwable t) { connectionOpenedAt = 0l; sock = null; failed = true; return; } sock = s; - + + } + + @Override + public void close() { + if (sock != null) { + sock.close(); + } + } + + @Override + public String getBrand() { + return brand; + } + + @Override + public String getComment() { + return comment; + } + + @Override + public VersionMismatch getCompatible() { + return versError; + } + + @Override + public long getPing() { + return connectionPingTimer < 1 ? 1 : connectionPingTimer; + } + + @Override + public int getVersion() { + return vers; + } + + @Override + public boolean isQueryFailed() { + return failed || sock == null || sock.getState() == EnumEaglerConnectionState.FAILED; + } + + @Override + public boolean isQueryOpen() { + return sock != null && !sock.isClosed(); + } + + @Override + public RateLimit isQueryRateLimit() { + return rateLimitStatus; } @Override public void update() { - if(sock == null) return; - if(sock.availableStringFrames() > 0) { - logger.warn("[{}] discarding {} string frames recieved on a binary connection", uri, sock.availableStringFrames()); + if (sock == null) + return; + if (sock.availableStringFrames() > 0) { + logger.warn("[{}] discarding {} string frames recieved on a binary connection", uri, + sock.availableStringFrames()); sock.clearStringFrames(); } List frames = sock.getNextBinaryFrames(); - if(frames != null) { - for(int i = 0, l = frames.size(); i < l; ++i) { + if (frames != null) { + for (int i = 0, l = frames.size(); i < l; ++i) { hasRecievedAnyData = true; byte[] arr = frames.get(i).getByteArray(); - if(arr.length == 2 && arr[0] == (byte)0xFC) { - if(arr[1] == (byte)0x00 || arr[1] == (byte)0x01) { + if (arr.length == 2 && arr[0] == (byte) 0xFC) { + if (arr[1] == (byte) 0x00 || arr[1] == (byte) 0x01) { rateLimitStatus = RateLimit.BLOCKED; RelayServerRateLimitTracker.setLimited(RelayQueryImpl.this.uri); - }else if(arr[1] == (byte)0x02) { + } else if (arr[1] == (byte) 0x02) { rateLimitStatus = RateLimit.NOW_LOCKED; RelayServerRateLimitTracker.setLimitedLocked(RelayQueryImpl.this.uri); - }else { + } else { rateLimitStatus = RateLimit.LOCKED; RelayServerRateLimitTracker.setLocked(RelayQueryImpl.this.uri); } failed = true; sock.close(); - }else { + } else { try { - RelayPacket pkt = RelayPacket.readPacket(new DataInputStream(new EaglerInputStream(arr)), loggerImpl); - if(pkt instanceof RelayPacket69Pong) { - RelayPacket69Pong ipkt = (RelayPacket69Pong)pkt; + RelayPacket pkt = RelayPacket.readPacket(new DataInputStream(new EaglerInputStream(arr)), + loggerImpl); + if (pkt instanceof RelayPacket69Pong) { + RelayPacket69Pong ipkt = (RelayPacket69Pong) pkt; versError = VersionMismatch.COMPATIBLE; - if(connectionPingTimer == -1) { + if (connectionPingTimer == -1) { connectionPingTimer = frames.get(i).getTimestamp() - connectionPingStart; } vers = ipkt.protcolVersion; @@ -115,21 +166,21 @@ public class RelayQueryImpl implements RelayQuery { failed = false; sock.close(); return; - }else if(pkt instanceof RelayPacket70SpecialUpdate) { - RelayPacket70SpecialUpdate ipkt = (RelayPacket70SpecialUpdate)pkt; - if(ipkt.operation == RelayPacket70SpecialUpdate.OPERATION_UPDATE_CERTIFICATE) { + } else if (pkt instanceof RelayPacket70SpecialUpdate) { + RelayPacket70SpecialUpdate ipkt = (RelayPacket70SpecialUpdate) pkt; + if (ipkt.operation == RelayPacket70SpecialUpdate.OPERATION_UPDATE_CERTIFICATE) { UpdateService.addCertificateToSet(ipkt.updatePacket); } - }else if(pkt instanceof RelayPacketFFErrorCode) { - RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode)pkt; - if(ipkt.code == RelayPacketFFErrorCode.TYPE_PROTOCOL_VERSION) { + } else if (pkt instanceof RelayPacketFFErrorCode) { + RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; + if (ipkt.code == RelayPacketFFErrorCode.TYPE_PROTOCOL_VERSION) { String s1 = ipkt.desc.toLowerCase(); - if(s1.contains("outdated client") || s1.contains("client outdated")) { + if (s1.contains("outdated client") || s1.contains("client outdated")) { versError = VersionMismatch.CLIENT_OUTDATED; - }else if(s1.contains("outdated server") || s1.contains("server outdated") || - s1.contains("outdated relay") || s1.contains("server relay")) { + } else if (s1.contains("outdated server") || s1.contains("server outdated") + || s1.contains("outdated relay") || s1.contains("server relay")) { versError = VersionMismatch.RELAY_OUTDATED; - }else { + } else { versError = VersionMismatch.UNKNOWN; } } @@ -137,7 +188,7 @@ public class RelayQueryImpl implements RelayQuery { failed = true; sock.close(); return; - }else { + } else { throw new IOException("Unexpected packet '" + pkt.getClass().getSimpleName() + "'"); } } catch (IOException e) { @@ -150,11 +201,12 @@ public class RelayQueryImpl implements RelayQuery { } } } - if(sock.isOpen() && !hasSentHandshake) { + if (sock.isOpen() && !hasSentHandshake) { hasSentHandshake = true; try { connectionPingStart = EagRuntime.steadyTimeMillis(); - sock.send(RelayPacket.writePacket(new RelayPacket00Handshake(0x03, RelayManager.preferredRelayVersion, ""), loggerImpl)); + sock.send(RelayPacket.writePacket( + new RelayPacket00Handshake(0x03, RelayManager.preferredRelayVersion, ""), loggerImpl)); } catch (IOException e) { logger.error("Failed to write handshake: {}", e.toString()); logger.error(e); @@ -162,64 +214,17 @@ public class RelayQueryImpl implements RelayQuery { failed = true; } } - if(sock.isClosed()) { - if(!hasRecievedAnyData) { + if (sock.isClosed()) { + if (!hasRecievedAnyData) { failed = true; rateLimitStatus = RelayServerRateLimitTracker.isLimitedLong(uri); } } - if(EagRuntime.steadyTimeMillis() - connectionOpenedAt > 10000l) { + if (EagRuntime.steadyTimeMillis() - connectionOpenedAt > 10000l) { logger.error("Terminating connection that was open for too long: {}", uri); sock.close(); failed = true; } } - @Override - public boolean isQueryOpen() { - return sock != null && !sock.isClosed(); - } - - @Override - public boolean isQueryFailed() { - return failed || sock == null || sock.getState() == EnumEaglerConnectionState.FAILED; - } - - @Override - public RateLimit isQueryRateLimit() { - return rateLimitStatus; - } - - @Override - public void close() { - if(sock != null) { - sock.close(); - } - } - - @Override - public int getVersion() { - return vers; - } - - @Override - public String getComment() { - return comment; - } - - @Override - public String getBrand() { - return brand; - } - - @Override - public long getPing() { - return connectionPingTimer < 1 ? 1 : connectionPingTimer; - } - - @Override - public VersionMismatch getCompatible() { - return versError; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryRateLimitDummy.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryRateLimitDummy.java index 059d0837..a5c19881 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryRateLimitDummy.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayQueryRateLimitDummy.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.sp.relay; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,48 +24,18 @@ public class RelayQueryRateLimitDummy implements RelayQuery { this.type = type; } - @Override - public void update() { - - } - - @Override - public boolean isQueryOpen() { - return false; - } - - @Override - public boolean isQueryFailed() { - return true; - } - - @Override - public RateLimit isQueryRateLimit() { - return type; - } - @Override public void close() { } - @Override - public int getVersion() { - return RelayManager.preferredRelayVersion; - } - - @Override - public String getComment() { - return "this query was rate limited"; - } - @Override public String getBrand() { return "lax1dude"; } @Override - public long getPing() { - return 0l; + public String getComment() { + return "this query was rate limited"; } @Override @@ -72,4 +43,34 @@ public class RelayQueryRateLimitDummy implements RelayQuery { return VersionMismatch.COMPATIBLE; } + @Override + public long getPing() { + return 0l; + } + + @Override + public int getVersion() { + return RelayManager.preferredRelayVersion; + } + + @Override + public boolean isQueryFailed() { + return true; + } + + @Override + public boolean isQueryOpen() { + return false; + } + + @Override + public RateLimit isQueryRateLimit() { + return type; + } + + @Override + public void update() { + + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServer.java index 4ccf839a..758dc60e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServer.java @@ -9,24 +9,25 @@ import net.minecraft.client.Minecraft; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayServer { - + public final String address; public final String comment; private boolean primary; - + private RelayQuery query = null; private int queriedVersion = -1; private String queriedComment; @@ -36,58 +37,62 @@ public class RelayServer { private long workingPing = 0l; public long lastPing = 0l; + public RelayServer(RelayEntry etr) { + this(etr.address, etr.comment, etr.primary); + } + public RelayServer(String address, String comment, boolean primary) { this.address = address; this.comment = comment; this.primary = primary; } - - public RelayServer(RelayEntry etr) { - this(etr.address, etr.comment, etr.primary); - } - - public boolean isPrimary() { - return primary; - } - - public void setPrimary(boolean primaryee) { - primary = primaryee; + + public void close() { + if (query != null && query.isQueryOpen()) { + query.close(); + query = null; + queriedVersion = -1; + queriedComment = null; + queriedVendor = null; + queriedCompatible = VersionMismatch.UNKNOWN; + ping = 0l; + } } public long getPing() { return ping; } - public long getWorkingPing() { - return workingPing; - } - - public int getPingVersion() { - return queriedVersion; - } - public String getPingComment() { return queriedComment == null ? "" : queriedComment; } - - public String getPingVendor() { - return queriedVendor == null ? "" : queriedVendor; - } - + public VersionMismatch getPingCompatible() { return queriedCompatible; } - - public void pingBlocking() { - ping(); - while(getPing() < 0l) { - EagUtils.sleep(250l); - update(); - } + + public String getPingVendor() { + return queriedVendor == null ? "" : queriedVendor; } - + + public int getPingVersion() { + return queriedVersion; + } + + public long getWorkingPing() { + return workingPing; + } + + public boolean isPrimary() { + return primary; + } + + public RelayServerSocket openSocket() { + return PlatformWebRTC.openRelayConnection(address, Minecraft.getMinecraft().gameSettings.relayTimeout * 1000); + } + public void ping() { - if(PlatformWebRTC.supported()) { + if (PlatformWebRTC.supported()) { close(); query = PlatformWebRTC.openRelayQuery(address); queriedVersion = -1; @@ -95,7 +100,7 @@ public class RelayServer { queriedVendor = null; queriedCompatible = VersionMismatch.UNKNOWN; ping = -1l; - }else { + } else { query = null; queriedVersion = 1; queriedComment = "LAN NOT SUPPORTED"; @@ -104,18 +109,30 @@ public class RelayServer { ping = -1l; } } - + + public void pingBlocking() { + ping(); + while (getPing() < 0l) { + EagUtils.sleep(250l); + update(); + } + } + + public void setPrimary(boolean primaryee) { + primary = primaryee; + } + public void update() { - if(query != null) { + if (query != null) { query.update(); - if(!query.isQueryOpen()) { - if(query.isQueryFailed()) { + if (!query.isQueryOpen()) { + if (query.isQueryFailed()) { queriedVersion = -1; queriedComment = null; queriedVendor = null; queriedCompatible = VersionMismatch.UNKNOWN; ping = 0l; - }else { + } else { queriedVersion = query.getVersion(); queriedComment = query.getComment(); queriedVendor = query.getBrand(); @@ -128,21 +145,5 @@ public class RelayServer { } } } - - public void close() { - if(query != null && query.isQueryOpen()) { - query.close(); - query = null; - queriedVersion = -1; - queriedComment = null; - queriedVendor = null; - queriedCompatible = VersionMismatch.UNKNOWN; - ping = 0l; - } - } - - public RelayServerSocket openSocket() { - return PlatformWebRTC.openRelayConnection(address, Minecraft.getMinecraft().gameSettings.relayTimeout * 1000); - } - + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerRateLimitTracker.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerRateLimitTracker.java index e7b34d65..2bf4baaf 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerRateLimitTracker.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerRateLimitTracker.java @@ -8,91 +8,92 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayServerRateLimitTracker { - private static final Map relayQueryLimited = new HashMap<>(); - private static final Map relayQueryLocked = new HashMap<>(); + private static final Map relayQueryLimited = new HashMap<>(); + private static final Map relayQueryLocked = new HashMap<>(); - public static void setLimited(String str) { - synchronized(relayQueryLimited) { - relayQueryLimited.put(str, EagRuntime.steadyTimeMillis()); + public static RelayQuery.RateLimit isLimited(String str) { + long now = EagRuntime.steadyTimeMillis(); + synchronized (relayQueryLocked) { + Long l = relayQueryLocked.get(str); + if (l != null && now - l.longValue() < 60000l) { + return RelayQuery.RateLimit.LOCKED; + } } + synchronized (relayQueryLimited) { + Long l = relayQueryLimited.get(str); + if (l != null && now - l.longValue() < 10000l) { + return RelayQuery.RateLimit.BLOCKED; + } + } + return RelayQuery.RateLimit.NONE; } - public static void setLocked(String str) { - synchronized(relayQueryLocked) { - relayQueryLocked.put(str, EagRuntime.steadyTimeMillis()); + public static RelayQuery.RateLimit isLimitedEver(String str) { + synchronized (relayQueryLocked) { + if (relayQueryLocked.containsKey(str)) { + return RelayQuery.RateLimit.LOCKED; + } + } + synchronized (relayQueryLimited) { + if (relayQueryLimited.containsKey(str)) { + return RelayQuery.RateLimit.BLOCKED; + } + } + return RelayQuery.RateLimit.NONE; + } + + public static RelayQuery.RateLimit isLimitedLong(String str) { + long now = EagRuntime.steadyTimeMillis(); + synchronized (relayQueryLocked) { + Long l = relayQueryLocked.get(str); + if (l != null && now - l.longValue() < 400000l) { + return RelayQuery.RateLimit.LOCKED; + } + } + synchronized (relayQueryLimited) { + Long l = relayQueryLimited.get(str); + if (l != null && now - l.longValue() < 900000l) { + return RelayQuery.RateLimit.BLOCKED; + } + } + return RelayQuery.RateLimit.NONE; + } + + public static void setLimited(String str) { + synchronized (relayQueryLimited) { + relayQueryLimited.put(str, EagRuntime.steadyTimeMillis()); } } public static void setLimitedLocked(String str) { long now = EagRuntime.steadyTimeMillis(); - synchronized(relayQueryLimited) { + synchronized (relayQueryLimited) { relayQueryLimited.put(str, now); } - synchronized(relayQueryLocked) { + synchronized (relayQueryLocked) { relayQueryLocked.put(str, now); } } - public static RelayQuery.RateLimit isLimited(String str) { - long now = EagRuntime.steadyTimeMillis(); - synchronized(relayQueryLocked) { - Long l = relayQueryLocked.get(str); - if(l != null && now - l.longValue() < 60000l) { - return RelayQuery.RateLimit.LOCKED; - } + public static void setLocked(String str) { + synchronized (relayQueryLocked) { + relayQueryLocked.put(str, EagRuntime.steadyTimeMillis()); } - synchronized(relayQueryLimited) { - Long l = relayQueryLimited.get(str); - if(l != null && now - l.longValue() < 10000l) { - return RelayQuery.RateLimit.BLOCKED; - } - } - return RelayQuery.RateLimit.NONE; - } - - public static RelayQuery.RateLimit isLimitedLong(String str) { - long now = EagRuntime.steadyTimeMillis(); - synchronized(relayQueryLocked) { - Long l = relayQueryLocked.get(str); - if(l != null && now - l.longValue() < 400000l) { - return RelayQuery.RateLimit.LOCKED; - } - } - synchronized(relayQueryLimited) { - Long l = relayQueryLimited.get(str); - if(l != null && now - l.longValue() < 900000l) { - return RelayQuery.RateLimit.BLOCKED; - } - } - return RelayQuery.RateLimit.NONE; - } - - public static RelayQuery.RateLimit isLimitedEver(String str) { - synchronized(relayQueryLocked) { - if(relayQueryLocked.containsKey(str)) { - return RelayQuery.RateLimit.LOCKED; - } - } - synchronized(relayQueryLimited) { - if(relayQueryLimited.containsKey(str)) { - return RelayQuery.RateLimit.BLOCKED; - } - } - return RelayQuery.RateLimit.NONE; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocket.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocket.java index e5fdbf02..a4a32eb3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocket.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocket.java @@ -5,35 +5,41 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface RelayServerSocket { - void update(); - boolean isOpen(); - boolean isClosed(); void close(); - - boolean isFailed(); + Throwable getException(); - - void writePacket(RelayPacket pkt); - - RelayPacket readPacket(); - RelayPacket nextPacket(); - + RelayQuery.RateLimit getRatelimitHistory(); - + String getURI(); - + + boolean isClosed(); + + boolean isFailed(); + + boolean isOpen(); + + RelayPacket nextPacket(); + + RelayPacket readPacket(); + + void update(); + + void writePacket(RelayPacket pkt); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketImpl.java index 05885f48..fd7f65de 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketImpl.java @@ -19,14 +19,15 @@ import net.lax1dude.eaglercraft.v1_8.update.UpdateService; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -50,7 +51,7 @@ public class RelayServerSocketImpl implements RelayServerSocket { IWebSocketClient s; try { s = PlatformNetworking.openWebSocketUnsafe(uri); - }catch(Throwable t) { + } catch (Throwable t) { exceptions.add(t); sock = null; failed = true; @@ -59,103 +60,18 @@ public class RelayServerSocketImpl implements RelayServerSocket { sock = s; } - @Override - public void update() { - if(sock == null) return; - if(sock.availableStringFrames() > 0) { - logger.warn("[{}] discarding {} string frames recieved on a binary connection", uri, sock.availableStringFrames()); - sock.clearStringFrames(); - } - List frames = sock.getNextBinaryFrames(); - if(frames != null) { - for(int i = 0, l = frames.size(); i < l; ++i) { - hasRecievedAnyData = true; - try { - RelayPacket pkt = RelayPacket.readPacket(new DataInputStream(frames.get(i).getInputStream()), loggerImpl); - if(pkt instanceof RelayPacket70SpecialUpdate) { - RelayPacket70SpecialUpdate ipkt = (RelayPacket70SpecialUpdate)pkt; - if(ipkt.operation == RelayPacket70SpecialUpdate.OPERATION_UPDATE_CERTIFICATE) { - UpdateService.addCertificateToSet(ipkt.updatePacket); - } - }else { - packets.add(pkt); - } - } catch (IOException e) { - exceptions.add(e); - logger.error("[{}] Relay Socket Error: {}", uri, e.toString()); - EagRuntime.debugPrintStackTrace(e); - failed = true; - sock.close(); - return; - } - } - } - if(sock.isClosed()) { - if (!hasRecievedAnyData) { - failed = true; - } - } - } - - @Override - public boolean isOpen() { - return sock != null && sock.isOpen(); - } - - @Override - public boolean isClosed() { - return sock == null || sock.isClosed(); - } - @Override public void close() { - if(sock != null) { + if (sock != null) { sock.close(); } } - @Override - public boolean isFailed() { - return failed || sock == null || sock.getState() == EnumEaglerConnectionState.FAILED; - } - @Override public Throwable getException() { - if(!exceptions.isEmpty()) { + if (!exceptions.isEmpty()) { return exceptions.remove(0); - }else { - return null; - } - } - - @Override - public void writePacket(RelayPacket pkt) { - if(sock != null) { - try { - sock.send(RelayPacket.writePacket(pkt, loggerImpl)); - } catch (Throwable e) { - logger.error("Relay connection error: {}", e.toString()); - EagRuntime.debugPrintStackTrace(e); - exceptions.add(e); - sock.close(); - } - } - } - - @Override - public RelayPacket readPacket() { - if(!packets.isEmpty()) { - return packets.remove(0); - }else { - return null; - } - } - - @Override - public RelayPacket nextPacket() { - if(!packets.isEmpty()) { - return packets.get(0); - }else { + } else { return null; } } @@ -170,4 +86,92 @@ public class RelayServerSocketImpl implements RelayServerSocket { return uri; } + @Override + public boolean isClosed() { + return sock == null || sock.isClosed(); + } + + @Override + public boolean isFailed() { + return failed || sock == null || sock.getState() == EnumEaglerConnectionState.FAILED; + } + + @Override + public boolean isOpen() { + return sock != null && sock.isOpen(); + } + + @Override + public RelayPacket nextPacket() { + if (!packets.isEmpty()) { + return packets.get(0); + } else { + return null; + } + } + + @Override + public RelayPacket readPacket() { + if (!packets.isEmpty()) { + return packets.remove(0); + } else { + return null; + } + } + + @Override + public void update() { + if (sock == null) + return; + if (sock.availableStringFrames() > 0) { + logger.warn("[{}] discarding {} string frames recieved on a binary connection", uri, + sock.availableStringFrames()); + sock.clearStringFrames(); + } + List frames = sock.getNextBinaryFrames(); + if (frames != null) { + for (int i = 0, l = frames.size(); i < l; ++i) { + hasRecievedAnyData = true; + try { + RelayPacket pkt = RelayPacket.readPacket(new DataInputStream(frames.get(i).getInputStream()), + loggerImpl); + if (pkt instanceof RelayPacket70SpecialUpdate) { + RelayPacket70SpecialUpdate ipkt = (RelayPacket70SpecialUpdate) pkt; + if (ipkt.operation == RelayPacket70SpecialUpdate.OPERATION_UPDATE_CERTIFICATE) { + UpdateService.addCertificateToSet(ipkt.updatePacket); + } + } else { + packets.add(pkt); + } + } catch (IOException e) { + exceptions.add(e); + logger.error("[{}] Relay Socket Error: {}", uri, e.toString()); + EagRuntime.debugPrintStackTrace(e); + failed = true; + sock.close(); + return; + } + } + } + if (sock.isClosed()) { + if (!hasRecievedAnyData) { + failed = true; + } + } + } + + @Override + public void writePacket(RelayPacket pkt) { + if (sock != null) { + try { + sock.send(RelayPacket.writePacket(pkt, loggerImpl)); + } catch (Throwable e) { + logger.error("Relay connection error: {}", e.toString()); + EagRuntime.debugPrintStackTrace(e); + exceptions.add(e); + sock.close(); + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketRateLimitDummy.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketRateLimitDummy.java index e00aa10e..afc30a1b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketRateLimitDummy.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayServerSocketRateLimitDummy.java @@ -5,14 +5,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -25,48 +26,15 @@ public class RelayServerSocketRateLimitDummy implements RelayServerSocket { this.limit = limit; } - @Override - public void update() { - } - - @Override - public boolean isOpen() { - return false; - } - - @Override - public boolean isClosed() { - return true; - } - @Override public void close() { } - @Override - public boolean isFailed() { - return true; - } - @Override public Throwable getException() { return null; } - @Override - public void writePacket(RelayPacket pkt) { - } - - @Override - public RelayPacket readPacket() { - return null; - } - - @Override - public RelayPacket nextPacket() { - return null; - } - @Override public RelayQuery.RateLimit getRatelimitHistory() { return limit; @@ -77,4 +45,37 @@ public class RelayServerSocketRateLimitDummy implements RelayServerSocket { return ""; } + @Override + public boolean isClosed() { + return true; + } + + @Override + public boolean isFailed() { + return true; + } + + @Override + public boolean isOpen() { + return false; + } + + @Override + public RelayPacket nextPacket() { + return null; + } + + @Override + public RelayPacket readPacket() { + return null; + } + + @Override + public void update() { + } + + @Override + public void writePacket(RelayPacket pkt) { + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQuery.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQuery.java index ae461fc8..e8c83feb 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQuery.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQuery.java @@ -8,28 +8,33 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket07LocalWorlds; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface RelayWorldsQuery { - void update(); - boolean isQueryOpen(); - boolean isQueryFailed(); - RelayQuery.RateLimit isQueryRateLimit(); void close(); - - List getWorlds(); - + VersionMismatch getCompatible(); - + + List getWorlds(); + + boolean isQueryFailed(); + + boolean isQueryOpen(); + + RelayQuery.RateLimit isQueryRateLimit(); + + void update(); + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryImpl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryImpl.java index d8a68cb4..687141b7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryImpl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryImpl.java @@ -23,14 +23,15 @@ import net.lax1dude.eaglercraft.v1_8.update.UpdateService; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -61,7 +62,7 @@ public class RelayWorldsQueryImpl implements RelayWorldsQuery { try { openedAt = EagRuntime.steadyTimeMillis(); s = PlatformNetworking.openWebSocketUnsafe(uri); - }catch(Throwable t) { + } catch (Throwable t) { sock = null; failed = true; return; @@ -69,54 +70,89 @@ public class RelayWorldsQueryImpl implements RelayWorldsQuery { sock = s; } + @Override + public void close() { + if (sock != null) { + sock.close(); + } + } + + @Override + public RelayQuery.VersionMismatch getCompatible() { + return versError; + } + + @Override + public List getWorlds() { + return worlds; + } + + @Override + public boolean isQueryFailed() { + return failed || sock == null || sock.getState() == EnumEaglerConnectionState.FAILED; + } + + @Override + public boolean isQueryOpen() { + return sock != null && !sock.isClosed(); + } + + @Override + public RelayQuery.RateLimit isQueryRateLimit() { + return rateLimitStatus; + } + @Override public void update() { - if(sock == null) return; - if(sock.availableStringFrames() > 0) { - logger.warn("[{}] discarding {} string frames recieved on a binary connection", uri, sock.availableStringFrames()); + if (sock == null) + return; + if (sock.availableStringFrames() > 0) { + logger.warn("[{}] discarding {} string frames recieved on a binary connection", uri, + sock.availableStringFrames()); sock.clearStringFrames(); } List frames = sock.getNextBinaryFrames(); - if(frames != null) { - for(int i = 0, l = frames.size(); i < l; ++i) { + if (frames != null) { + for (int i = 0, l = frames.size(); i < l; ++i) { hasRecievedAnyData = true; byte[] arr = frames.get(i).getByteArray(); - if(arr.length == 2 && arr[0] == (byte)0xFC) { - if(arr[1] == (byte)0x00 || arr[1] == (byte)0x01) { + if (arr.length == 2 && arr[0] == (byte) 0xFC) { + if (arr[1] == (byte) 0x00 || arr[1] == (byte) 0x01) { rateLimitStatus = RateLimit.BLOCKED; RelayServerRateLimitTracker.setLimited(RelayWorldsQueryImpl.this.uri); - }else if(arr[1] == (byte)0x02) { + } else if (arr[1] == (byte) 0x02) { rateLimitStatus = RateLimit.NOW_LOCKED; RelayServerRateLimitTracker.setLimitedLocked(RelayWorldsQueryImpl.this.uri); - }else { + } else { rateLimitStatus = RateLimit.LOCKED; RelayServerRateLimitTracker.setLocked(RelayWorldsQueryImpl.this.uri); } failed = true; sock.close(); - }else { + } else { try { - RelayPacket pkt = RelayPacket.readPacket(new DataInputStream(new EaglerInputStream(arr)), loggerImpl); - if(pkt instanceof RelayPacket07LocalWorlds) { - worlds = ((RelayPacket07LocalWorlds)pkt).worldsList; + RelayPacket pkt = RelayPacket.readPacket(new DataInputStream(new EaglerInputStream(arr)), + loggerImpl); + if (pkt instanceof RelayPacket07LocalWorlds) { + worlds = ((RelayPacket07LocalWorlds) pkt).worldsList; sock.close(); failed = false; return; - }else if(pkt instanceof RelayPacket70SpecialUpdate) { - RelayPacket70SpecialUpdate ipkt = (RelayPacket70SpecialUpdate)pkt; - if(ipkt.operation == RelayPacket70SpecialUpdate.OPERATION_UPDATE_CERTIFICATE) { + } else if (pkt instanceof RelayPacket70SpecialUpdate) { + RelayPacket70SpecialUpdate ipkt = (RelayPacket70SpecialUpdate) pkt; + if (ipkt.operation == RelayPacket70SpecialUpdate.OPERATION_UPDATE_CERTIFICATE) { UpdateService.addCertificateToSet(ipkt.updatePacket); } - }else if(pkt instanceof RelayPacketFFErrorCode) { - RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode)pkt; - if(ipkt.code == RelayPacketFFErrorCode.TYPE_PROTOCOL_VERSION) { + } else if (pkt instanceof RelayPacketFFErrorCode) { + RelayPacketFFErrorCode ipkt = (RelayPacketFFErrorCode) pkt; + if (ipkt.code == RelayPacketFFErrorCode.TYPE_PROTOCOL_VERSION) { String s1 = ipkt.desc.toLowerCase(); - if(s1.contains("outdated client") || s1.contains("client outdated")) { + if (s1.contains("outdated client") || s1.contains("client outdated")) { versError = RelayQuery.VersionMismatch.CLIENT_OUTDATED; - }else if(s1.contains("outdated server") || s1.contains("server outdated") || - s1.contains("outdated relay") || s1.contains("server relay")) { + } else if (s1.contains("outdated server") || s1.contains("server outdated") + || s1.contains("outdated relay") || s1.contains("server relay")) { versError = RelayQuery.VersionMismatch.RELAY_OUTDATED; - }else { + } else { versError = RelayQuery.VersionMismatch.UNKNOWN; } } @@ -124,7 +160,7 @@ public class RelayWorldsQueryImpl implements RelayWorldsQuery { failed = true; sock.close(); return; - }else { + } else { throw new IOException("Unexpected packet '" + pkt.getClass().getSimpleName() + "'"); } } catch (IOException e) { @@ -137,10 +173,11 @@ public class RelayWorldsQueryImpl implements RelayWorldsQuery { } } } - if(sock.isOpen() && !hasSentHandshake) { + if (sock.isOpen() && !hasSentHandshake) { hasSentHandshake = true; try { - sock.send(RelayPacket.writePacket(new RelayPacket00Handshake(0x04, RelayManager.preferredRelayVersion, ""), loggerImpl)); + sock.send(RelayPacket.writePacket( + new RelayPacket00Handshake(0x04, RelayManager.preferredRelayVersion, ""), loggerImpl)); } catch (IOException e) { logger.error("Failed to write handshake: {}", e.toString()); logger.error(e); @@ -148,13 +185,13 @@ public class RelayWorldsQueryImpl implements RelayWorldsQuery { failed = true; } } - if(sock.isClosed()) { - if(!hasRecievedAnyData) { + if (sock.isClosed()) { + if (!hasRecievedAnyData) { failed = true; rateLimitStatus = RelayServerRateLimitTracker.isLimitedLong(uri); } - }else { - if(EagRuntime.steadyTimeMillis() - openedAt > 10000l) { + } else { + if (EagRuntime.steadyTimeMillis() - openedAt > 10000l) { logger.error("Terminating connection that was open for too long: {}", uri); sock.close(); failed = true; @@ -162,36 +199,4 @@ public class RelayWorldsQueryImpl implements RelayWorldsQuery { } } - @Override - public boolean isQueryOpen() { - return sock != null && !sock.isClosed(); - } - - @Override - public boolean isQueryFailed() { - return failed || sock == null || sock.getState() == EnumEaglerConnectionState.FAILED; - } - - @Override - public RelayQuery.RateLimit isQueryRateLimit() { - return rateLimitStatus; - } - - @Override - public void close() { - if(sock != null) { - sock.close(); - } - } - - @Override - public List getWorlds() { - return worlds; - } - - @Override - public RelayQuery.VersionMismatch getCompatible() { - return versError; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryRateLimitDummy.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryRateLimitDummy.java index 2915c825..9a3326a2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryRateLimitDummy.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/relay/RelayWorldsQueryRateLimitDummy.java @@ -8,14 +8,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.relay.pkt.RelayPacket07LocalWorlds; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -28,37 +29,37 @@ public class RelayWorldsQueryRateLimitDummy implements RelayWorldsQuery { this.rateLimit = rateLimit; } - @Override - public void update() { - } - - @Override - public boolean isQueryOpen() { - return false; - } - - @Override - public boolean isQueryFailed() { - return true; - } - - @Override - public RelayQuery.RateLimit isQueryRateLimit() { - return rateLimit; - } - @Override public void close() { } + @Override + public RelayQuery.VersionMismatch getCompatible() { + return RelayQuery.VersionMismatch.COMPATIBLE; + } + @Override public List getWorlds() { return new ArrayList<>(0); } @Override - public RelayQuery.VersionMismatch getCompatible() { - return RelayQuery.VersionMismatch.COMPATIBLE; + public boolean isQueryFailed() { + return true; + } + + @Override + public boolean isQueryOpen() { + return false; + } + + @Override + public RelayQuery.RateLimit isQueryRateLimit() { + return rateLimit; + } + + @Override + public void update() { } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/ClientCommandDummy.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/ClientCommandDummy.java index ef861b89..31439a60 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/ClientCommandDummy.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/ClientCommandDummy.java @@ -8,14 +8,15 @@ import net.minecraft.util.ChatComponentTranslation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -38,13 +39,13 @@ public class ClientCommandDummy extends CommandBase { } @Override - public int getRequiredPermissionLevel() { - return permissionLevel; + public String getCommandUsage(ICommandSender var1) { + return commandUsage; } @Override - public String getCommandUsage(ICommandSender var1) { - return commandUsage; + public int getRequiredPermissionLevel() { + return permissionLevel; } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerChunkLoader.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerChunkLoader.java index 11bd903e..60a554ad 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerChunkLoader.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerChunkLoader.java @@ -7,25 +7,26 @@ import java.io.OutputStream; import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.ChunkCoordIntPair; import net.minecraft.world.MinecraftException; import net.minecraft.world.World; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.storage.AnvilChunkLoader; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,19 +36,6 @@ public class EaglerChunkLoader extends AnvilChunkLoader { private static final String hex = "0123456789ABCDEF"; private static final Logger logger = LogManager.getLogger("EaglerChunkLoader"); - public static String getChunkPath(int x, int z) { - int unsignedX = x + 1900000; - int unsignedZ = z + 1900000; - - char[] path = new char[12]; - for(int i = 5; i >= 0; --i) { - path[i] = hex.charAt((unsignedX >>> (i << 2)) & 0xF); - path[i + 6] = hex.charAt((unsignedZ >>> (i << 2)) & 0xF); - } - - return new String(path); - } - public static ChunkCoordIntPair getChunkCoords(String filename) { String strX = filename.substring(0, 6); String strZ = filename.substring(6); @@ -55,7 +43,7 @@ public class EaglerChunkLoader extends AnvilChunkLoader { int retX = 0; int retZ = 0; - for(int i = 0; i < 6; ++i) { + for (int i = 0; i < 6; ++i) { retX |= hex.indexOf(strX.charAt(i)) << (i << 2); retZ |= hex.indexOf(strZ.charAt(i)) << (i << 2); } @@ -63,26 +51,44 @@ public class EaglerChunkLoader extends AnvilChunkLoader { return new ChunkCoordIntPair(retX - 1900000, retZ - 1900000); } + public static String getChunkPath(int x, int z) { + int unsignedX = x + 1900000; + int unsignedZ = z + 1900000; + + char[] path = new char[12]; + for (int i = 5; i >= 0; --i) { + path[i] = hex.charAt((unsignedX >>> (i << 2)) & 0xF); + path[i + 6] = hex.charAt((unsignedZ >>> (i << 2)) & 0xF); + } + + return new String(path); + } + public final VFile2 chunkDirectory; public EaglerChunkLoader(VFile2 chunkDirectory) { this.chunkDirectory = chunkDirectory; } + @Override + public void chunkTick() { + // ? + } + @Override public Chunk loadChunk(World var1, int var2, int var3) throws IOException { VFile2 file = WorldsDB.newVFile(chunkDirectory, getChunkPath(var2, var3) + ".dat"); - if(!file.exists()) { + if (!file.exists()) { return null; } try { NBTTagCompound nbt; - try(InputStream is = file.getInputStream()) { + try (InputStream is = file.getInputStream()) { nbt = CompressedStreamTools.readCompressed(is); } return checkedReadChunkFromNBT(var1, var2, var3, nbt); - }catch(Throwable t) { - + } catch (Throwable t) { + } return null; } @@ -94,7 +100,7 @@ public class EaglerChunkLoader extends AnvilChunkLoader { NBTTagCompound fileData = new NBTTagCompound(); fileData.setTag("Level", chunkData); VFile2 file = WorldsDB.newVFile(chunkDirectory, getChunkPath(var2.xPosition, var2.zPosition) + ".dat"); - try(OutputStream os = file.getOutputStream()) { + try (OutputStream os = file.getOutputStream()) { CompressedStreamTools.writeCompressed(fileData, os); } } @@ -104,11 +110,6 @@ public class EaglerChunkLoader extends AnvilChunkLoader { // ? } - @Override - public void chunkTick() { - // ? - } - @Override public void saveExtraData() { // ? diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerIntegratedServerWorker.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerIntegratedServerWorker.java index 0aad61cb..0e722fbc 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerIntegratedServerWorker.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerIntegratedServerWorker.java @@ -17,7 +17,37 @@ import net.lax1dude.eaglercraft.v1_8.log4j.ILogRedirector; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.sp.SingleplayerServerController; -import net.lax1dude.eaglercraft.v1_8.sp.ipc.*; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket00StartServer; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket01StopServer; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket02InitWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket03DeleteWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket05RequestData; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket06RenameWorldNBT; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket07ImportWorld; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket09RequestResponse; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0ASetWorldDifficulty; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0BPause; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0CPlayerChannel; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0DProgressUpdate; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket0EListWorlds; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket14StringList; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket15Crashed; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket16NBTList; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket17ConfigureLAN; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket18ClearPlayers; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket19Autosave; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1ALoggerMessage; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1BEnableLogging; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacket1CIssueDetected; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketBase; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketFFProcessKeepAlive; +import net.lax1dude.eaglercraft.v1_8.sp.ipc.IPCPacketManager; +import net.lax1dude.eaglercraft.v1_8.sp.server.export.WorldConverterEPK; +import net.lax1dude.eaglercraft.v1_8.sp.server.export.WorldConverterMCA; +import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplayer; +import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; +import net.minecraft.nbt.CompressedStreamTools; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.EnumConnectionState; import net.minecraft.server.network.NetHandlerLoginServer; import net.minecraft.util.ChatComponentText; @@ -27,24 +57,19 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldSettings.GameType; import net.minecraft.world.WorldType; -import net.lax1dude.eaglercraft.v1_8.sp.server.export.WorldConverterEPK; -import net.lax1dude.eaglercraft.v1_8.sp.server.export.WorldConverterMCA; -import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplayer; -import net.lax1dude.eaglercraft.v1_8.sp.server.socket.IntegratedServerPlayerNetworkManager; -import net.minecraft.nbt.CompressedStreamTools; -import net.minecraft.nbt.NBTTagCompound; /** * Copyright (c) 2023-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -62,352 +87,14 @@ public class EaglerIntegratedServerWorker { private static final IPCPacketManager packetManagerInstance = new IPCPacketManager(); - private static void processAsyncMessageQueue() { - List pktList = ServerPlatformSingleplayer.recieveAllPacket(); - if(pktList != null) { - IPCPacketData packetData; - for(int i = 0, l = pktList.size(); i < l; ++i) { - packetData = pktList.get(i); - if(packetData.channel.equals(SingleplayerServerController.IPC_CHANNEL)) { - IPCPacketBase ipc; - try { - ipc = packetManagerInstance.IPCDeserialize(packetData.contents); - }catch(IOException ex) { - throw new RuntimeException("Failed to deserialize IPC packet", ex); - } - handleIPCPacket(ipc); - }else { - IntegratedServerPlayerNetworkManager netHandler = openChannels.get(packetData.channel); - if(netHandler != null) { - netHandler.addRecievedPacket(packetData.contents); - }else { - logger.error("Recieved packet on channel that does not exist: \"{}\"", packetData.channel); - } - } - } - } - } - - public static void tick() { - List ocs = new ArrayList<>(openChannels.values()); - for(int i = 0, l = ocs.size(); i < l; ++i) { - ocs.get(i).tick(); - } - } - - public static EaglerMinecraftServer getServer() { - return currentProcess; - } - - public static boolean getChannelExists(String channel) { - return openChannels.containsKey(channel); - } - public static void closeChannel(String channel) { IntegratedServerPlayerNetworkManager netmanager = openChannels.remove(channel); - if(netmanager != null) { + if (netmanager != null) { netmanager.closeChannel(new ChatComponentText("End of stream")); sendIPCPacket(new IPCPacket0CPlayerChannel(channel, false)); } } - private static void startPlayerConnnection(String channel) { - if(openChannels.containsKey(channel)) { - logger.error("Tried opening player channel that already exists: {}", channel); - return; - } - if(currentProcess == null) { - logger.error("Tried opening player channel while server is stopped: {}", channel); - return; - } - IntegratedServerPlayerNetworkManager networkmanager = new IntegratedServerPlayerNetworkManager(channel); - networkmanager.setConnectionState(EnumConnectionState.LOGIN); - networkmanager.setNetHandler(new NetHandlerLoginServer(currentProcess, networkmanager)); - openChannels.put(channel, networkmanager); - } - - private static void handleIPCPacket(IPCPacketBase ipc) { - int id = ipc.id(); - try { - switch(id) { - case IPCPacket00StartServer.ID: { - IPCPacket00StartServer pkt = (IPCPacket00StartServer)ipc; - - if(!isServerStopped()) { - currentProcess.stopServer(); - } - - currentProcess = new EaglerMinecraftServer(pkt.worldName, pkt.ownerName, pkt.initialViewDistance, newWorldSettings, pkt.demoMode); - currentProcess.setBaseServerProperties(EnumDifficulty.getDifficultyEnum(pkt.initialDifficulty), newWorldSettings == null ? GameType.SURVIVAL : newWorldSettings.getGameType()); - currentProcess.startServer(); - - String[] worlds = EaglerSaveFormat.worldsList.getAllLines(); - if(worlds == null || (worlds.length == 1 && worlds[0].trim().length() <= 0)) { - worlds = null; - } - if(worlds == null) { - EaglerSaveFormat.worldsList.setAllChars(pkt.worldName); - }else { - boolean found = false; - for(int i = 0; i < worlds.length; ++i) { - if(worlds[i].equals(pkt.worldName)) { - found = true; - break; - } - } - if(!found) { - String[] s = new String[worlds.length + 1]; - s[0] = pkt.worldName; - System.arraycopy(worlds, 0, s, 1, worlds.length); - EaglerSaveFormat.worldsList.setAllChars(String.join("\n", s)); - } - } - - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket00StartServer.ID)); - break; - } - case IPCPacket01StopServer.ID: { - if(currentProcess != null) { - currentProcess.stopServer(); - currentProcess = null; - } - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket01StopServer.ID)); - break; - } - case IPCPacket02InitWorld.ID: { - tryStopServer(); - IPCPacket02InitWorld pkt = (IPCPacket02InitWorld)ipc; - newWorldSettings = new WorldSettings(pkt.seed, GameType.getByID(pkt.gamemode), pkt.structures, - pkt.hardcore, WorldType.worldTypes[pkt.worldType]); - newWorldSettings.setWorldName(pkt.worldArgs); // "setWorldName" is actually for setting generator arguments, MCP fucked up - if(pkt.bonusChest) { - newWorldSettings.enableBonusChest(); - } - if(pkt.cheats) { - newWorldSettings.enableCommands(); - } - break; - } - case IPCPacket03DeleteWorld.ID: { - tryStopServer(); - IPCPacket03DeleteWorld pkt = (IPCPacket03DeleteWorld)ipc; - if(!saveFormat.deleteWorldDirectory(pkt.worldName)) { - sendTaskFailed(); - break; - } - String[] worldsTxt = EaglerSaveFormat.worldsList.getAllLines(); - if(worldsTxt != null) { - List newWorlds = new ArrayList<>(); - for(int i = 0; i < worldsTxt.length; ++i) { - String str = worldsTxt[i]; - if(!str.equalsIgnoreCase(pkt.worldName)) { - newWorlds.add(str); - } - } - EaglerSaveFormat.worldsList.setAllChars(String.join("\n", newWorlds)); - } - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket03DeleteWorld.ID)); - break; - } - case IPCPacket05RequestData.ID: { - tryStopServer(); - IPCPacket05RequestData pkt = (IPCPacket05RequestData)ipc; - if(pkt.request == IPCPacket05RequestData.REQUEST_LEVEL_EAG) { - sendIPCPacket(new IPCPacket09RequestResponse(WorldConverterEPK.exportWorld(pkt.worldName))); - }else if(pkt.request == IPCPacket05RequestData.REQUEST_LEVEL_MCA) { - sendIPCPacket(new IPCPacket09RequestResponse(WorldConverterMCA.exportWorld(pkt.worldName))); - }else { - logger.error("Unknown IPCPacket05RequestData type {}", ((int)pkt.request & 0xFF)); - sendTaskFailed(); - } - break; - } - case IPCPacket06RenameWorldNBT.ID: { - tryStopServer(); - IPCPacket06RenameWorldNBT pkt = (IPCPacket06RenameWorldNBT)ipc; - boolean b = false; - if(pkt.duplicate) { - b = saveFormat.duplicateWorld(pkt.worldName, pkt.displayName); - }else { - b = saveFormat.renameWorld(pkt.worldName, pkt.displayName); - } - if(!b) { - sendTaskFailed(); - break; - } - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket06RenameWorldNBT.ID)); - break; - } - case IPCPacket07ImportWorld.ID: { - tryStopServer(); - IPCPacket07ImportWorld pkt = (IPCPacket07ImportWorld)ipc; - try { - if(pkt.worldFormat == IPCPacket07ImportWorld.WORLD_FORMAT_EAG) { - WorldConverterEPK.importWorld(pkt.worldData, pkt.worldName); - }else if(pkt.worldFormat == IPCPacket07ImportWorld.WORLD_FORMAT_MCA) { - WorldConverterMCA.importWorld(pkt.worldData, pkt.worldName, pkt.gameRules); - }else { - throw new IOException("Client requested an unsupported export format!"); - } - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket07ImportWorld.ID)); - }catch(IOException ex) { - sendIPCPacket(new IPCPacket15Crashed("COULD NOT IMPORT WORLD \"" + pkt.worldName + "\"!!!\n\n" + EagRuntime.getStackTrace(ex) + "\n\nFile is probably corrupt, try a different world")); - sendTaskFailed(); - } - break; - } - case IPCPacket0ASetWorldDifficulty.ID: { - IPCPacket0ASetWorldDifficulty pkt = (IPCPacket0ASetWorldDifficulty)ipc; - if(!isServerStopped()) { - if(pkt.difficulty == (byte)-1) { - currentProcess.setDifficultyLockedForAllWorlds(true); - }else { - currentProcess.setDifficultyForAllWorlds(EnumDifficulty.getDifficultyEnum(pkt.difficulty)); - } - }else { - logger.warn("Client tried to set difficulty while server was stopped"); - } - break; - } - case IPCPacket0BPause.ID: { - IPCPacket0BPause pkt = (IPCPacket0BPause)ipc; - if(!isServerStopped()) { - currentProcess.setPaused(pkt.pause); - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket0BPause.ID)); - }else { - logger.error("Client tried to {} while server was stopped", pkt.pause ? "pause" : "unpause"); - sendTaskFailed(); - } - break; - } - case IPCPacket0CPlayerChannel.ID: { - IPCPacket0CPlayerChannel pkt = (IPCPacket0CPlayerChannel)ipc; - if(!isServerStopped()) { - if(pkt.open) { - startPlayerConnnection(pkt.channel); - }else { - closeChannel(pkt.channel); - } - }else { - logger.error("Client tried to {} channel server was stopped", pkt.open ? "open" : "close"); - } - break; - } - case IPCPacket0EListWorlds.ID: { - IPCPacket0EListWorlds pkt = (IPCPacket0EListWorlds)ipc; - if(!isServerStopped()) { - logger.error("Client tried to list worlds while server was running"); - sendTaskFailed(); - }else { - String[] worlds = EaglerSaveFormat.worldsList.getAllLines(); - if(worlds == null) { - sendIPCPacket(new IPCPacket16NBTList(IPCPacket16NBTList.WORLD_LIST, new LinkedList<>())); - break; - } - LinkedHashSet updatedList = new LinkedHashSet<>(); - LinkedList sendListNBT = new LinkedList<>(); - boolean rewrite = false; - for(int i = 0; i < worlds.length; ++i) { - String w = worlds[i].trim(); - if(w.length() > 0) { - VFile2 vf = WorldsDB.newVFile(EaglerSaveFormat.worldsFolder, w, "level.dat"); - if(!vf.exists()) { - vf = WorldsDB.newVFile(EaglerSaveFormat.worldsFolder, w, "level.dat_old"); - } - if(vf.exists()) { - try(InputStream dat = vf.getInputStream()) { - if(updatedList.add(w)) { - NBTTagCompound worldDatNBT = CompressedStreamTools.readCompressed(dat); - worldDatNBT.setString("folderNameEagler", w); - sendListNBT.add(worldDatNBT); - }else { - rewrite = true; - } - continue; - }catch(IOException e) { - // shit fuck - } - } - rewrite = true; - logger.error("World level.dat for '{}' was not found, attempting to delete", w); - if(!saveFormat.deleteWorldDirectory(w)) { - logger.error("Failed to delete '{}'! It will be removed from the worlds list anyway", w); - } - }else { - rewrite = true; - } - } - if(rewrite) { - EaglerSaveFormat.worldsList.setAllChars(String.join("\n", updatedList)); - } - sendIPCPacket(new IPCPacket16NBTList(IPCPacket16NBTList.WORLD_LIST, sendListNBT)); - } - break; - } - case IPCPacket14StringList.ID: { - IPCPacket14StringList pkt = (IPCPacket14StringList)ipc; - switch(pkt.opCode) { - case IPCPacket14StringList.LOCALE: - StringTranslate.initServer(pkt.stringList); - break; - //case IPCPacket14StringList.STAT_GUID: - // AchievementMap.init(pkt.stringList); - // AchievementList.init(); - // break; - default: - logger.error("Strange string list 0x{} with length{} recieved", Integer.toHexString(pkt.opCode), pkt.stringList.size()); - break; - } - break; - } - case IPCPacket17ConfigureLAN.ID: { - - IPCPacket17ConfigureLAN pkt = (IPCPacket17ConfigureLAN)ipc; - if(!pkt.iceServers.isEmpty() && ServerPlatformSingleplayer.getClientConfigAdapter().isAllowVoiceClient()) { - currentProcess.enableVoice(pkt.iceServers.toArray(new String[pkt.iceServers.size()])); - } - currentProcess.getConfigurationManager().configureLAN(pkt.gamemode, pkt.cheats); // don't use iceServers - - break; - } - case IPCPacket18ClearPlayers.ID: { - if(!isServerStopped()) { - logger.error("Client tried to clear players while server was running"); - sendTaskFailed(); - }else { - saveFormat.clearPlayers(((IPCPacket18ClearPlayers)ipc).worldName); - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket18ClearPlayers.ID)); - } - break; - } - case IPCPacket19Autosave.ID: { - if(!isServerStopped()) { - currentProcess.getConfigurationManager().saveAllPlayerData(); - currentProcess.saveAllWorlds(false); - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket19Autosave.ID)); - }else { - logger.error("Client tried to autosave while server was stopped"); - sendTaskFailed(); - } - break; - } - case IPCPacket1BEnableLogging.ID: { - enableLoggingRedirector(((IPCPacket1BEnableLogging)ipc).enable); - break; - } - default: - logger.error("IPC packet type 0x{} class \"{}\" was not handled", Integer.toHexString(id), ipc.getClass().getSimpleName()); - sendTaskFailed(); - break; - } - }catch(Throwable t) { - logger.error("IPC packet type 0x{} class \"{}\" was not processed correctly", Integer.toHexString(id), ipc.getClass().getSimpleName()); - logger.error(t); - sendIPCPacket(new IPCPacket15Crashed("IPC packet type 0x" + Integer.toHexString(id) + " class \"" + ipc.getClass().getSimpleName() + "\" was not processed correctly!\n\n" + EagRuntime.getStackTrace(t))); - sendTaskFailed(); - } - } - public static void enableLoggingRedirector(boolean en) { LogManager.logRedirector = en ? new ILogRedirector() { @Override @@ -417,93 +104,413 @@ public class EaglerIntegratedServerWorker { } : null; } - public static void sendLogMessagePacket(String txt, boolean err) { - sendIPCPacket(new IPCPacket1ALoggerMessage(txt, err)); + public static boolean getChannelExists(String channel) { + return openChannels.containsKey(channel); } - public static void sendIPCPacket(IPCPacketBase ipc) { - byte[] pkt; + public static EaglerMinecraftServer getServer() { + return currentProcess; + } + + private static void handleIPCPacket(IPCPacketBase ipc) { + int id = ipc.id(); try { - pkt = packetManagerInstance.IPCSerialize(ipc); - }catch (IOException ex) { - throw new RuntimeException("Failed to serialize IPC packet", ex); + switch (id) { + case IPCPacket00StartServer.ID: { + IPCPacket00StartServer pkt = (IPCPacket00StartServer) ipc; + + if (!isServerStopped()) { + currentProcess.stopServer(); + } + + currentProcess = new EaglerMinecraftServer(pkt.worldName, pkt.ownerName, pkt.initialViewDistance, + newWorldSettings, pkt.demoMode); + currentProcess.setBaseServerProperties(EnumDifficulty.getDifficultyEnum(pkt.initialDifficulty), + newWorldSettings == null ? GameType.SURVIVAL : newWorldSettings.getGameType()); + currentProcess.startServer(); + + String[] worlds = EaglerSaveFormat.worldsList.getAllLines(); + if (worlds == null || (worlds.length == 1 && worlds[0].trim().length() <= 0)) { + worlds = null; + } + if (worlds == null) { + EaglerSaveFormat.worldsList.setAllChars(pkt.worldName); + } else { + boolean found = false; + for (int i = 0; i < worlds.length; ++i) { + if (worlds[i].equals(pkt.worldName)) { + found = true; + break; + } + } + if (!found) { + String[] s = new String[worlds.length + 1]; + s[0] = pkt.worldName; + System.arraycopy(worlds, 0, s, 1, worlds.length); + EaglerSaveFormat.worldsList.setAllChars(String.join("\n", s)); + } + } + + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket00StartServer.ID)); + break; + } + case IPCPacket01StopServer.ID: { + if (currentProcess != null) { + currentProcess.stopServer(); + currentProcess = null; + } + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket01StopServer.ID)); + break; + } + case IPCPacket02InitWorld.ID: { + tryStopServer(); + IPCPacket02InitWorld pkt = (IPCPacket02InitWorld) ipc; + newWorldSettings = new WorldSettings(pkt.seed, GameType.getByID(pkt.gamemode), pkt.structures, + pkt.hardcore, WorldType.worldTypes[pkt.worldType]); + newWorldSettings.setWorldName(pkt.worldArgs); // "setWorldName" is actually for setting generator + // arguments, MCP fucked up + if (pkt.bonusChest) { + newWorldSettings.enableBonusChest(); + } + if (pkt.cheats) { + newWorldSettings.enableCommands(); + } + break; + } + case IPCPacket03DeleteWorld.ID: { + tryStopServer(); + IPCPacket03DeleteWorld pkt = (IPCPacket03DeleteWorld) ipc; + if (!saveFormat.deleteWorldDirectory(pkt.worldName)) { + sendTaskFailed(); + break; + } + String[] worldsTxt = EaglerSaveFormat.worldsList.getAllLines(); + if (worldsTxt != null) { + List newWorlds = new ArrayList<>(); + for (int i = 0; i < worldsTxt.length; ++i) { + String str = worldsTxt[i]; + if (!str.equalsIgnoreCase(pkt.worldName)) { + newWorlds.add(str); + } + } + EaglerSaveFormat.worldsList.setAllChars(String.join("\n", newWorlds)); + } + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket03DeleteWorld.ID)); + break; + } + case IPCPacket05RequestData.ID: { + tryStopServer(); + IPCPacket05RequestData pkt = (IPCPacket05RequestData) ipc; + if (pkt.request == IPCPacket05RequestData.REQUEST_LEVEL_EAG) { + sendIPCPacket(new IPCPacket09RequestResponse(WorldConverterEPK.exportWorld(pkt.worldName))); + } else if (pkt.request == IPCPacket05RequestData.REQUEST_LEVEL_MCA) { + sendIPCPacket(new IPCPacket09RequestResponse(WorldConverterMCA.exportWorld(pkt.worldName))); + } else { + logger.error("Unknown IPCPacket05RequestData type {}", ((int) pkt.request & 0xFF)); + sendTaskFailed(); + } + break; + } + case IPCPacket06RenameWorldNBT.ID: { + tryStopServer(); + IPCPacket06RenameWorldNBT pkt = (IPCPacket06RenameWorldNBT) ipc; + boolean b = false; + if (pkt.duplicate) { + b = saveFormat.duplicateWorld(pkt.worldName, pkt.displayName); + } else { + b = saveFormat.renameWorld(pkt.worldName, pkt.displayName); + } + if (!b) { + sendTaskFailed(); + break; + } + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket06RenameWorldNBT.ID)); + break; + } + case IPCPacket07ImportWorld.ID: { + tryStopServer(); + IPCPacket07ImportWorld pkt = (IPCPacket07ImportWorld) ipc; + try { + if (pkt.worldFormat == IPCPacket07ImportWorld.WORLD_FORMAT_EAG) { + WorldConverterEPK.importWorld(pkt.worldData, pkt.worldName); + } else if (pkt.worldFormat == IPCPacket07ImportWorld.WORLD_FORMAT_MCA) { + WorldConverterMCA.importWorld(pkt.worldData, pkt.worldName, pkt.gameRules); + } else { + throw new IOException("Client requested an unsupported export format!"); + } + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket07ImportWorld.ID)); + } catch (IOException ex) { + sendIPCPacket(new IPCPacket15Crashed("COULD NOT IMPORT WORLD \"" + pkt.worldName + "\"!!!\n\n" + + EagRuntime.getStackTrace(ex) + "\n\nFile is probably corrupt, try a different world")); + sendTaskFailed(); + } + break; + } + case IPCPacket0ASetWorldDifficulty.ID: { + IPCPacket0ASetWorldDifficulty pkt = (IPCPacket0ASetWorldDifficulty) ipc; + if (!isServerStopped()) { + if (pkt.difficulty == (byte) -1) { + currentProcess.setDifficultyLockedForAllWorlds(true); + } else { + currentProcess.setDifficultyForAllWorlds(EnumDifficulty.getDifficultyEnum(pkt.difficulty)); + } + } else { + logger.warn("Client tried to set difficulty while server was stopped"); + } + break; + } + case IPCPacket0BPause.ID: { + IPCPacket0BPause pkt = (IPCPacket0BPause) ipc; + if (!isServerStopped()) { + currentProcess.setPaused(pkt.pause); + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket0BPause.ID)); + } else { + logger.error("Client tried to {} while server was stopped", pkt.pause ? "pause" : "unpause"); + sendTaskFailed(); + } + break; + } + case IPCPacket0CPlayerChannel.ID: { + IPCPacket0CPlayerChannel pkt = (IPCPacket0CPlayerChannel) ipc; + if (!isServerStopped()) { + if (pkt.open) { + startPlayerConnnection(pkt.channel); + } else { + closeChannel(pkt.channel); + } + } else { + logger.error("Client tried to {} channel server was stopped", pkt.open ? "open" : "close"); + } + break; + } + case IPCPacket0EListWorlds.ID: { + IPCPacket0EListWorlds pkt = (IPCPacket0EListWorlds) ipc; + if (!isServerStopped()) { + logger.error("Client tried to list worlds while server was running"); + sendTaskFailed(); + } else { + String[] worlds = EaglerSaveFormat.worldsList.getAllLines(); + if (worlds == null) { + sendIPCPacket(new IPCPacket16NBTList(IPCPacket16NBTList.WORLD_LIST, new LinkedList<>())); + break; + } + LinkedHashSet updatedList = new LinkedHashSet<>(); + LinkedList sendListNBT = new LinkedList<>(); + boolean rewrite = false; + for (int i = 0; i < worlds.length; ++i) { + String w = worlds[i].trim(); + if (w.length() > 0) { + VFile2 vf = WorldsDB.newVFile(EaglerSaveFormat.worldsFolder, w, "level.dat"); + if (!vf.exists()) { + vf = WorldsDB.newVFile(EaglerSaveFormat.worldsFolder, w, "level.dat_old"); + } + if (vf.exists()) { + try (InputStream dat = vf.getInputStream()) { + if (updatedList.add(w)) { + NBTTagCompound worldDatNBT = CompressedStreamTools.readCompressed(dat); + worldDatNBT.setString("folderNameEagler", w); + sendListNBT.add(worldDatNBT); + } else { + rewrite = true; + } + continue; + } catch (IOException e) { + // shit fuck + } + } + rewrite = true; + logger.error("World level.dat for '{}' was not found, attempting to delete", w); + if (!saveFormat.deleteWorldDirectory(w)) { + logger.error("Failed to delete '{}'! It will be removed from the worlds list anyway", + w); + } + } else { + rewrite = true; + } + } + if (rewrite) { + EaglerSaveFormat.worldsList.setAllChars(String.join("\n", updatedList)); + } + sendIPCPacket(new IPCPacket16NBTList(IPCPacket16NBTList.WORLD_LIST, sendListNBT)); + } + break; + } + case IPCPacket14StringList.ID: { + IPCPacket14StringList pkt = (IPCPacket14StringList) ipc; + switch (pkt.opCode) { + case IPCPacket14StringList.LOCALE: + StringTranslate.initServer(pkt.stringList); + break; + // case IPCPacket14StringList.STAT_GUID: + // AchievementMap.init(pkt.stringList); + // AchievementList.init(); + // break; + default: + logger.error("Strange string list 0x{} with length{} recieved", Integer.toHexString(pkt.opCode), + pkt.stringList.size()); + break; + } + break; + } + case IPCPacket17ConfigureLAN.ID: { + + IPCPacket17ConfigureLAN pkt = (IPCPacket17ConfigureLAN) ipc; + if (!pkt.iceServers.isEmpty() + && ServerPlatformSingleplayer.getClientConfigAdapter().isAllowVoiceClient()) { + currentProcess.enableVoice(pkt.iceServers.toArray(new String[pkt.iceServers.size()])); + } + currentProcess.getConfigurationManager().configureLAN(pkt.gamemode, pkt.cheats); // don't use iceServers + + break; + } + case IPCPacket18ClearPlayers.ID: { + if (!isServerStopped()) { + logger.error("Client tried to clear players while server was running"); + sendTaskFailed(); + } else { + saveFormat.clearPlayers(((IPCPacket18ClearPlayers) ipc).worldName); + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket18ClearPlayers.ID)); + } + break; + } + case IPCPacket19Autosave.ID: { + if (!isServerStopped()) { + currentProcess.getConfigurationManager().saveAllPlayerData(); + currentProcess.saveAllWorlds(false); + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket19Autosave.ID)); + } else { + logger.error("Client tried to autosave while server was stopped"); + sendTaskFailed(); + } + break; + } + case IPCPacket1BEnableLogging.ID: { + enableLoggingRedirector(((IPCPacket1BEnableLogging) ipc).enable); + break; + } + default: + logger.error("IPC packet type 0x{} class \"{}\" was not handled", Integer.toHexString(id), + ipc.getClass().getSimpleName()); + sendTaskFailed(); + break; + } + } catch (Throwable t) { + logger.error("IPC packet type 0x{} class \"{}\" was not processed correctly", Integer.toHexString(id), + ipc.getClass().getSimpleName()); + logger.error(t); + sendIPCPacket(new IPCPacket15Crashed( + "IPC packet type 0x" + Integer.toHexString(id) + " class \"" + ipc.getClass().getSimpleName() + + "\" was not processed correctly!\n\n" + EagRuntime.getStackTrace(t))); + sendTaskFailed(); } - ServerPlatformSingleplayer.sendPacket(new IPCPacketData(SingleplayerServerController.IPC_CHANNEL, pkt)); - } - - public static void reportTPS(List texts) { - sendIPCPacket(new IPCPacket14StringList(IPCPacket14StringList.SERVER_TPS, texts)); - } - - public static void sendTaskFailed() { - sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacketFFProcessKeepAlive.FAILURE)); - } - - public static void sendProgress(String updateMessage, float updateProgress) { - sendIPCPacket(new IPCPacket0DProgressUpdate(updateMessage, updateProgress)); } private static boolean isServerStopped() { return currentProcess == null || !currentProcess.isServerRunning(); } - private static void tryStopServer() { - if(!isServerStopped()) { - currentProcess.stopServer(); - } - currentProcess = null; - } - private static void mainLoop(boolean singleThreadMode) { processAsyncMessageQueue(); - - if(currentProcess != null) { - if(currentProcess.isServerRunning()) { + + if (currentProcess != null) { + if (currentProcess.isServerRunning()) { currentProcess.mainLoop(singleThreadMode); } - if(!currentProcess.isServerRunning()) { + if (!currentProcess.isServerRunning()) { currentProcess.stopServer(); currentProcess = null; sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacket01StopServer.ID)); } - }else { - if(!singleThreadMode) { + } else { + if (!singleThreadMode) { EagUtils.sleep(50l); } } } + private static void processAsyncMessageQueue() { + List pktList = ServerPlatformSingleplayer.recieveAllPacket(); + if (pktList != null) { + IPCPacketData packetData; + for (int i = 0, l = pktList.size(); i < l; ++i) { + packetData = pktList.get(i); + if (packetData.channel.equals(SingleplayerServerController.IPC_CHANNEL)) { + IPCPacketBase ipc; + try { + ipc = packetManagerInstance.IPCDeserialize(packetData.contents); + } catch (IOException ex) { + throw new RuntimeException("Failed to deserialize IPC packet", ex); + } + handleIPCPacket(ipc); + } else { + IntegratedServerPlayerNetworkManager netHandler = openChannels.get(packetData.channel); + if (netHandler != null) { + netHandler.addRecievedPacket(packetData.contents); + } else { + logger.error("Recieved packet on channel that does not exist: \"{}\"", packetData.channel); + } + } + } + } + } + + public static void reportTPS(List texts) { + sendIPCPacket(new IPCPacket14StringList(IPCPacket14StringList.SERVER_TPS, texts)); + } + + public static void sendIPCPacket(IPCPacketBase ipc) { + byte[] pkt; + try { + pkt = packetManagerInstance.IPCSerialize(ipc); + } catch (IOException ex) { + throw new RuntimeException("Failed to serialize IPC packet", ex); + } + ServerPlatformSingleplayer.sendPacket(new IPCPacketData(SingleplayerServerController.IPC_CHANNEL, pkt)); + } + + public static void sendLogMessagePacket(String txt, boolean err) { + sendIPCPacket(new IPCPacket1ALoggerMessage(txt, err)); + } + + public static void sendProgress(String updateMessage, float updateProgress) { + sendIPCPacket(new IPCPacket0DProgressUpdate(updateMessage, updateProgress)); + } + + public static void sendTaskFailed() { + sendIPCPacket(new IPCPacketFFProcessKeepAlive(IPCPacketFFProcessKeepAlive.FAILURE)); + } + public static void serverMain() { try { currentProcess = null; logger.info("Starting EaglercraftX integrated server worker..."); - - if(ServerPlatformSingleplayer.getWorldsDatabase().isRamdisk()) { + + if (ServerPlatformSingleplayer.getWorldsDatabase().isRamdisk()) { sendIPCPacket(new IPCPacket1CIssueDetected(IPCPacket1CIssueDetected.ISSUE_RAMDISK_MODE)); } - + // signal thread startup successful sendIPCPacket(new IPCPacketFFProcessKeepAlive(0xFF)); - - while(true) { + + while (true) { mainLoop(false); ServerPlatformSingleplayer.immediateContinue(); } - }catch(Throwable tt) { - if(tt instanceof ReportedException) { - String fullReport = ((ReportedException)tt).getCrashReport().getCompleteReport(); + } catch (Throwable tt) { + if (tt instanceof ReportedException) { + String fullReport = ((ReportedException) tt).getCrashReport().getCompleteReport(); logger.error(fullReport); sendIPCPacket(new IPCPacket15Crashed(fullReport)); - }else { + } else { logger.error("Server process encountered a fatal error!"); logger.error(tt); sendIPCPacket(new IPCPacket15Crashed("SERVER PROCESS EXITED!\n\n" + EagRuntime.getStackTrace(tt))); } - }finally { - if(!isServerStopped()) { + } finally { + if (!isServerStopped()) { try { currentProcess.stopServer(); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Encountered exception while stopping server!"); logger.error(t); } @@ -515,7 +522,7 @@ public class EaglerIntegratedServerWorker { public static void singleThreadMain() { logger.info("Starting EaglercraftX integrated server worker..."); - if(ServerPlatformSingleplayer.getWorldsDatabase().isRamdisk()) { + if (ServerPlatformSingleplayer.getWorldsDatabase().isRamdisk()) { sendIPCPacket(new IPCPacket1CIssueDetected(IPCPacket1CIssueDetected.ISSUE_RAMDISK_MODE)); } sendIPCPacket(new IPCPacketFFProcessKeepAlive(0xFF)); @@ -525,4 +532,33 @@ public class EaglerIntegratedServerWorker { mainLoop(true); } + private static void startPlayerConnnection(String channel) { + if (openChannels.containsKey(channel)) { + logger.error("Tried opening player channel that already exists: {}", channel); + return; + } + if (currentProcess == null) { + logger.error("Tried opening player channel while server is stopped: {}", channel); + return; + } + IntegratedServerPlayerNetworkManager networkmanager = new IntegratedServerPlayerNetworkManager(channel); + networkmanager.setConnectionState(EnumConnectionState.LOGIN); + networkmanager.setNetHandler(new NetHandlerLoginServer(currentProcess, networkmanager)); + openChannels.put(channel, networkmanager); + } + + public static void tick() { + List ocs = new ArrayList<>(openChannels.values()); + for (int i = 0, l = ocs.size(); i < l; ++i) { + ocs.get(i).tick(); + } + } + + private static void tryStopServer() { + if (!isServerStopped()) { + currentProcess.stopServer(); + } + currentProcess = null; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerMinecraftServer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerMinecraftServer.java index 7f995361..bc2421c2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerMinecraftServer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerMinecraftServer.java @@ -9,6 +9,9 @@ import com.google.common.collect.Lists; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; +import net.lax1dude.eaglercraft.v1_8.sp.server.skins.IntegratedCapeService; +import net.lax1dude.eaglercraft.v1_8.sp.server.skins.IntegratedSkinService; +import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Bootstrap; @@ -17,21 +20,19 @@ import net.minecraft.world.EnumDifficulty; import net.minecraft.world.WorldServer; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldSettings.GameType; -import net.lax1dude.eaglercraft.v1_8.sp.server.skins.IntegratedCapeService; -import net.lax1dude.eaglercraft.v1_8.sp.server.skins.IntegratedSkinService; -import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; /** * Copyright (c) 2023-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,17 +43,6 @@ public class EaglerMinecraftServer extends MinecraftServer { public static final VFile2 savesDir = WorldsDB.newVFile("worlds"); - protected EnumDifficulty difficulty; - protected GameType gamemode; - protected WorldSettings newWorldSettings; - protected boolean paused; - protected EaglerSaveHandler saveHandler; - protected IntegratedSkinService skinService; - protected IntegratedCapeService capeService; - protected IntegratedVoiceService voiceService; - - private long lastTPSUpdate = 0l; - public static int counterTicksPerSecond = 0; public static int counterChunkRead = 0; public static int counterChunkGenerate = 0; @@ -60,13 +50,84 @@ public class EaglerMinecraftServer extends MinecraftServer { public static int counterTileUpdate = 0; public static int counterLightUpdate = 0; + private static int countChunksLoaded(WorldServer[] worlds) { + int i = 0; + for (int j = 0; j < worlds.length; ++j) { + if (worlds[j] != null) { + i += worlds[j].theChunkProviderServer.getLoadedChunkCount(); + } + } + return i; + } + + private static int countChunksTotal(WorldServer[] worlds) { + int i = 0; + for (int j = 0; j < worlds.length; ++j) { + if (worlds[j] != null) { + List players = worlds[j].playerEntities; + for (int l = 0, n = players.size(); l < n; ++l) { + i += ((EntityPlayerMP) players.get(l)).loadedChunks.size(); + } + i += worlds[j].theChunkProviderServer.getLoadedChunkCount(); + } + } + return i; + } + + private static int countEntities(WorldServer[] worlds) { + int i = 0; + for (int j = 0; j < worlds.length; ++j) { + if (worlds[j] != null) { + i += worlds[j].loadedEntityList.size(); + } + } + return i; + } + + private static int countPlayerEntities(WorldServer[] worlds) { + int i = 0; + for (int j = 0; j < worlds.length; ++j) { + if (worlds[j] != null) { + i += worlds[j].playerEntities.size(); + } + } + return i; + } + + private static int countTileEntities(WorldServer[] worlds) { + int i = 0; + for (int j = 0; j < worlds.length; ++j) { + if (worlds[j] != null) { + i += worlds[j].loadedTileEntityList.size(); + } + } + return i; + } + + protected EnumDifficulty difficulty; + protected GameType gamemode; + protected WorldSettings newWorldSettings; + protected boolean paused; + + protected EaglerSaveHandler saveHandler; + + protected IntegratedSkinService skinService; + + protected IntegratedCapeService capeService; + + protected IntegratedVoiceService voiceService; + + private long lastTPSUpdate = 0l; + private final List scheduledTasks = new LinkedList<>(); - public EaglerMinecraftServer(String world, String owner, int viewDistance, WorldSettings currentWorldSettings, boolean demo) { + public EaglerMinecraftServer(String world, String owner, int viewDistance, WorldSettings currentWorldSettings, + boolean demo) { super(world); Bootstrap.register(); this.saveHandler = new EaglerSaveHandler(savesDir, world); - this.skinService = new IntegratedSkinService(WorldsDB.newVFile(saveHandler.getWorldDirectory(), "eagler/skulls")); + this.skinService = new IntegratedSkinService( + WorldsDB.newVFile(saveHandler.getWorldDirectory(), "eagler/skulls")); this.capeService = new IntegratedCapeService(); this.voiceService = null; this.setServerOwner(owner); @@ -79,51 +140,15 @@ public class EaglerMinecraftServer extends MinecraftServer { this.paused = false; } - public IntegratedSkinService getSkinService() { - return skinService; - } - - public IntegratedCapeService getCapeService() { - return capeService; - } - - public IntegratedVoiceService getVoiceService() { - return voiceService; - } - - public void enableVoice(String[] iceServers) { - if(iceServers != null) { - if(voiceService != null) { - voiceService.changeICEServers(iceServers); - }else { - voiceService = new IntegratedVoiceService(iceServers); - for(EntityPlayerMP player : getConfigurationManager().func_181057_v()) { - voiceService.handlePlayerLoggedIn(player); - } - } - } - } - - public void setBaseServerProperties(EnumDifficulty difficulty, GameType gamemode) { - this.difficulty = difficulty; - this.gamemode = gamemode; - this.setCanSpawnAnimals(true); - this.setCanSpawnNPCs(true); - this.setAllowPvp(true); - this.setAllowFlight(true); - } - @Override public void addScheduledTask(Runnable var1) { scheduledTasks.add(var1); } @Override - protected boolean startServer() throws IOException { - logger.info("Starting integrated eaglercraft server version 1.8.8"); - this.loadAllWorlds(saveHandler, this.getWorldName(), newWorldSettings); - serverRunning = true; - return true; + public boolean canStructuresSpawn() { + return worldServers != null ? worldServers[0].getWorldInfo().isMapFeaturesEnabled() + : newWorldSettings.isMapFeaturesEnabled(); } public void deleteWorldAndStopServer() { @@ -132,16 +157,92 @@ public class EaglerMinecraftServer extends MinecraftServer { EaglerIntegratedServerWorker.saveFormat.deleteWorldDirectory(getFolderName()); } + public void enableVoice(String[] iceServers) { + if (iceServers != null) { + if (voiceService != null) { + voiceService.changeICEServers(iceServers); + } else { + voiceService = new IntegratedVoiceService(iceServers); + for (EntityPlayerMP player : getConfigurationManager().func_181057_v()) { + voiceService.handlePlayerLoggedIn(player); + } + } + } + } + + @Override + public boolean func_181034_q() { + return true; + } + + @Override + public boolean func_181035_ah() { + return false; + } + + @Override + public boolean func_183002_r() { + return true; + } + + public IntegratedCapeService getCapeService() { + return capeService; + } + + @Override + public EnumDifficulty getDifficulty() { + return difficulty; + } + + @Override + public GameType getGameType() { + return worldServers != null ? worldServers[0].getWorldInfo().getGameType() : newWorldSettings.getGameType(); + } + + @Override + public int getOpPermissionLevel() { + return 4; + } + + public boolean getPaused() { + return paused; + } + + public IntegratedSkinService getSkinService() { + return skinService; + } + + public IntegratedVoiceService getVoiceService() { + return voiceService; + } + + @Override + public boolean isCommandBlockEnabled() { + return true; + } + + @Override + public boolean isDedicatedServer() { + return false; + } + + @Override + public boolean isHardcore() { + return worldServers != null ? worldServers[0].getWorldInfo().isHardcoreModeEnabled() + : newWorldSettings.getHardcoreEnabled(); + } + public void mainLoop(boolean singleThreadMode) { long k = getCurrentTimeMillis(); this.sendTPSToClient(k); - if(paused && this.playersOnline.size() <= 1) { + if (paused && this.playersOnline.size() <= 1) { currentTime = k; return; } long j = k - this.currentTime; - if (j > (singleThreadMode ? 500L : 2000L) && this.currentTime - this.timeOfLastWarning >= (singleThreadMode ? 5000L : 15000L)) { + if (j > (singleThreadMode ? 500L : 2000L) + && this.currentTime - this.timeOfLastWarning >= (singleThreadMode ? 5000L : 15000L)) { logger.warn( "Can\'t keep up! Did the system time change, or is the server overloaded? Running {}ms behind, skipping {} tick(s)", new Object[] { Long.valueOf(j), Long.valueOf(j / 50L) }); @@ -169,24 +270,17 @@ public class EaglerMinecraftServer extends MinecraftServer { } } - public void updateTimeLightAndEntities() { - this.skinService.flushCache(); - super.updateTimeLightAndEntities(); - } - protected void sendTPSToClient(long millis) { - if(millis - lastTPSUpdate > 1000l) { + if (millis - lastTPSUpdate > 1000l) { lastTPSUpdate = millis; - if(serverRunning && this.worldServers != null) { - List lst = Lists.newArrayList( - "TPS: " + counterTicksPerSecond + "/20", + if (serverRunning && this.worldServers != null) { + List lst = Lists.newArrayList("TPS: " + counterTicksPerSecond + "/20", "Chunks: " + countChunksLoaded(this.worldServers) + "/" + countChunksTotal(this.worldServers), "Entities: " + countEntities(this.worldServers) + "+" + countTileEntities(this.worldServers), "R: " + counterChunkRead + ", G: " + counterChunkGenerate + ", W: " + counterChunkWrite, - "TU: " + counterTileUpdate + ", LU: " + counterLightUpdate - ); + "TU: " + counterTileUpdate + ", LU: " + counterLightUpdate); int players = countPlayerEntities(this.worldServers); - if(players > 1) { + if (players > 1) { lst.add("Players: " + players); } counterTicksPerSecond = counterChunkRead = counterChunkGenerate = 0; @@ -196,124 +290,38 @@ public class EaglerMinecraftServer extends MinecraftServer { } } - private static int countChunksLoaded(WorldServer[] worlds) { - int i = 0; - for(int j = 0; j < worlds.length; ++j) { - if(worlds[j] != null) { - i += worlds[j].theChunkProviderServer.getLoadedChunkCount(); - } - } - return i; - } - - private static int countChunksTotal(WorldServer[] worlds) { - int i = 0; - for(int j = 0; j < worlds.length; ++j) { - if(worlds[j] != null) { - List players = worlds[j].playerEntities; - for(int l = 0, n = players.size(); l < n; ++l) { - i += ((EntityPlayerMP)players.get(l)).loadedChunks.size(); - } - i += worlds[j].theChunkProviderServer.getLoadedChunkCount(); - } - } - return i; - } - - private static int countEntities(WorldServer[] worlds) { - int i = 0; - for(int j = 0; j < worlds.length; ++j) { - if(worlds[j] != null) { - i += worlds[j].loadedEntityList.size(); - } - } - return i; - } - - private static int countTileEntities(WorldServer[] worlds) { - int i = 0; - for(int j = 0; j < worlds.length; ++j) { - if(worlds[j] != null) { - i += worlds[j].loadedTileEntityList.size(); - } - } - return i; - } - - private static int countPlayerEntities(WorldServer[] worlds) { - int i = 0; - for(int j = 0; j < worlds.length; ++j) { - if(worlds[j] != null) { - i += worlds[j].playerEntities.size(); - } - } - return i; + public void setBaseServerProperties(EnumDifficulty difficulty, GameType gamemode) { + this.difficulty = difficulty; + this.gamemode = gamemode; + this.setCanSpawnAnimals(true); + this.setCanSpawnNPCs(true); + this.setAllowPvp(true); + this.setAllowFlight(true); } public void setPaused(boolean p) { paused = p; - if(!p) { + if (!p) { currentTime = EagRuntime.steadyTimeMillis(); } } - - public boolean getPaused() { - return paused; - } - - @Override - public boolean canStructuresSpawn() { - return worldServers != null ? worldServers[0].getWorldInfo().isMapFeaturesEnabled() : newWorldSettings.isMapFeaturesEnabled(); - } - - @Override - public GameType getGameType() { - return worldServers != null ? worldServers[0].getWorldInfo().getGameType() : newWorldSettings.getGameType(); - } - - @Override - public EnumDifficulty getDifficulty() { - return difficulty; - } - - @Override - public boolean isHardcore() { - return worldServers != null ? worldServers[0].getWorldInfo().isHardcoreModeEnabled() : newWorldSettings.getHardcoreEnabled(); - } - - @Override - public int getOpPermissionLevel() { - return 4; - } - - @Override - public boolean func_181034_q() { - return true; - } - - @Override - public boolean func_183002_r() { - return true; - } - - @Override - public boolean isDedicatedServer() { - return false; - } - - @Override - public boolean func_181035_ah() { - return false; - } - - @Override - public boolean isCommandBlockEnabled() { - return true; - } @Override public String shareToLAN(GameType var1, boolean var2) { return null; } + @Override + protected boolean startServer() throws IOException { + logger.info("Starting integrated eaglercraft server version 1.8.8"); + this.loadAllWorlds(saveHandler, this.getWorldName(), newWorldSettings); + serverRunning = true; + return true; + } + + public void updateTimeLightAndEntities() { + this.skinService.flushCache(); + super.updateTimeLightAndEntities(); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerPlayerList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerPlayerList.java index 525110bb..74ae027f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerPlayerList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerPlayerList.java @@ -1,27 +1,28 @@ package net.lax1dude.eaglercraft.v1_8.sp.server; import net.minecraft.entity.player.EntityPlayerMP; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.ServerConfigurationManager; -import net.minecraft.nbt.NBTTagCompound; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerPlayerList extends ServerConfigurationManager { - + private NBTTagCompound hostPlayerNBT = null; public EaglerPlayerList(MinecraftServer par1MinecraftServer, int viewDistance) { @@ -29,6 +30,17 @@ public class EaglerPlayerList extends ServerConfigurationManager { this.viewDistance = viewDistance; } + public NBTTagCompound getHostPlayerData() { + return this.hostPlayerNBT; + } + + public void playerLoggedOut(EntityPlayerMP playerIn) { + super.playerLoggedOut(playerIn); + EaglerMinecraftServer svr = (EaglerMinecraftServer) getServerInstance(); + svr.skinService.unregisterPlayer(playerIn.getUniqueID()); + svr.capeService.unregisterPlayer(playerIn.getUniqueID()); + } + protected void writePlayerData(EntityPlayerMP par1EntityPlayerMP) { if (par1EntityPlayerMP.getName().equals(this.getServerInstance().getServerOwner())) { this.hostPlayerNBT = new NBTTagCompound(); @@ -36,15 +48,4 @@ public class EaglerPlayerList extends ServerConfigurationManager { } super.writePlayerData(par1EntityPlayerMP); } - - public NBTTagCompound getHostPlayerData() { - return this.hostPlayerNBT; - } - - public void playerLoggedOut(EntityPlayerMP playerIn) { - super.playerLoggedOut(playerIn); - EaglerMinecraftServer svr = (EaglerMinecraftServer)getServerInstance(); - svr.skinService.unregisterPlayer(playerIn.getUniqueID()); - svr.capeService.unregisterPlayer(playerIn.getUniqueID()); - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveFormat.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveFormat.java index 4fb29bdb..64c31390 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveFormat.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveFormat.java @@ -16,57 +16,27 @@ import net.minecraft.world.storage.WorldInfo; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EaglerSaveFormat extends SaveFormatOld { - public EaglerSaveFormat(VFile2 parFile) { - super(parFile); - } - public static final VFile2 worldsList = WorldsDB.newVFile("worlds_list.txt"); + public static final VFile2 worldsFolder = WorldsDB.newVFile("worlds"); - public String getName() { - return "eagler"; - } - - public ISaveHandler getSaveLoader(String s, boolean flag) { - return new EaglerSaveHandler(this.savesDirectory, s); - } - - public List getSaveList() { - ArrayList arraylist = Lists.newArrayList(); - if(worldsList.exists()) { - String[] lines = worldsList.getAllLines(); - for (int i = 0; i < lines.length; ++i) { - String s = lines[i]; - WorldInfo worldinfo = this.getWorldInfo(s); - if (worldinfo != null - && (worldinfo.getSaveVersion() == 19132 || worldinfo.getSaveVersion() == 19133)) { - boolean flag = worldinfo.getSaveVersion() != this.getSaveVersion(); - String s1 = worldinfo.getWorldName(); - if (StringUtils.isEmpty(s1)) { - s1 = s; - } - - arraylist.add(new SaveFormatComparator(s, s1, worldinfo.getLastTimePlayed(), 0l, - worldinfo.getGameType(), flag, worldinfo.isHardcoreModeEnabled(), - worldinfo.areCommandsAllowed(), null)); - } - } - } - return arraylist; + public EaglerSaveFormat(VFile2 parFile) { + super(parFile); } public void clearPlayers(String worldFolder) { @@ -74,14 +44,11 @@ public class EaglerSaveFormat extends SaveFormatOld { deleteFiles(file1.listFiles(true), null); } - protected int getSaveVersion() { - return 19133; // why notch? - } - public boolean duplicateWorld(String worldFolder, String displayName) { String newFolderName = displayName.replaceAll("[\\./\"]", "_"); VFile2 newFolder = WorldsDB.newVFile(savesDirectory, newFolderName); - while((WorldsDB.newVFile(newFolder, "level.dat")).exists() || (WorldsDB.newVFile(newFolder, "level.dat_old")).exists()) { + while ((WorldsDB.newVFile(newFolder, "level.dat")).exists() + || (WorldsDB.newVFile(newFolder, "level.dat_old")).exists()) { newFolderName += "_"; newFolder = WorldsDB.newVFile(savesDirectory, newFolderName); } @@ -91,7 +58,7 @@ public class EaglerSaveFormat extends SaveFormatOld { int lastUpdate = 0; final VFile2 finalNewFolder = newFolder; List vfl = oldFolder.listFiles(true); - for(int i = 0, l = vfl.size(); i < l; ++i) { + for (int i = 0, l = vfl.size(); i < l; ++i) { VFile2 vf = vfl.get(i); String fileNameRelative = vf.getPath().substring(oldPath.length() + 1); totalSize += VFile2.copyFile(vf, WorldsDB.newVFile(finalNewFolder, fileNameRelative)); @@ -101,9 +68,9 @@ public class EaglerSaveFormat extends SaveFormatOld { } } String[] worldsTxt = worldsList.getAllLines(); - if(worldsTxt == null || worldsTxt.length <= 0) { + if (worldsTxt == null || worldsTxt.length <= 0) { worldsTxt = new String[] { newFolderName }; - }else { + } else { String[] tmp = worldsTxt; worldsTxt = new String[worldsTxt.length + 1]; System.arraycopy(tmp, 0, worldsTxt, 0, tmp.length); @@ -112,4 +79,39 @@ public class EaglerSaveFormat extends SaveFormatOld { worldsList.setAllChars(String.join("\n", worldsTxt)); return renameWorld(newFolderName, displayName); } + + public String getName() { + return "eagler"; + } + + public List getSaveList() { + ArrayList arraylist = Lists.newArrayList(); + if (worldsList.exists()) { + String[] lines = worldsList.getAllLines(); + for (int i = 0; i < lines.length; ++i) { + String s = lines[i]; + WorldInfo worldinfo = this.getWorldInfo(s); + if (worldinfo != null && (worldinfo.getSaveVersion() == 19132 || worldinfo.getSaveVersion() == 19133)) { + boolean flag = worldinfo.getSaveVersion() != this.getSaveVersion(); + String s1 = worldinfo.getWorldName(); + if (StringUtils.isEmpty(s1)) { + s1 = s; + } + + arraylist.add( + new SaveFormatComparator(s, s1, worldinfo.getLastTimePlayed(), 0l, worldinfo.getGameType(), + flag, worldinfo.isHardcoreModeEnabled(), worldinfo.areCommandsAllowed(), null)); + } + } + } + return arraylist; + } + + public ISaveHandler getSaveLoader(String s, boolean flag) { + return new EaglerSaveHandler(this.savesDirectory, s); + } + + protected int getSaveVersion() { + return 19133; // why notch? + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveHandler.java index dae1b7ec..badadb70 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/EaglerSaveHandler.java @@ -1,23 +1,24 @@ package net.lax1dude.eaglercraft.v1_8.sp.server; import net.lax1dude.eaglercraft.v1_8.internal.vfs2.VFile2; +import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldProvider; import net.minecraft.world.chunk.storage.IChunkLoader; import net.minecraft.world.storage.SaveHandler; import net.minecraft.world.storage.WorldInfo; -import net.minecraft.nbt.NBTTagCompound; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/WorldsDB.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/WorldsDB.java index 401c3fd9..a9a9269c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/WorldsDB.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/WorldsDB.java @@ -9,14 +9,15 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplay /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKCompiler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKCompiler.java index e20eb498..391d869a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKCompiler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKCompiler.java @@ -13,24 +13,45 @@ import net.lax1dude.eaglercraft.v1_8.EaglerZLIB; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class EPKCompiler { + public static void writeInt(int i, OutputStream os) throws IOException { + os.write((i >>> 24) & 0xFF); + os.write((i >>> 16) & 0xFF); + os.write((i >>> 8) & 0xFF); + os.write(i & 0xFF); + } + + public static void writeLong(long i, OutputStream os) throws IOException { + os.write((int) ((i >>> 56l) & 0xFFl)); + os.write((int) ((i >>> 48l) & 0xFFl)); + os.write((int) ((i >>> 40l) & 0xFFl)); + os.write((int) ((i >>> 32l) & 0xFFl)); + os.write((int) ((i >>> 24l) & 0xFFl)); + os.write((int) ((i >>> 16l) & 0xFFl)); + os.write((int) ((i >>> 8l) & 0xFFl)); + os.write((int) (i & 0xFFl)); + } + private final EaglerOutputStream os; private final OutputStream dos; private final CRC32 checkSum = new CRC32(); + private int lengthIntegerOffset = 0; + private int totalFileCount = 0; public EPKCompiler(String name, String owner, String type) { @@ -40,145 +61,132 @@ public class EPKCompiler { public EPKCompiler(String name, String owner, String type, boolean gzip, boolean world, String commentStr) { os = new EaglerOutputStream(0x200000); try { - - os.write(new byte[]{(byte)69,(byte)65,(byte)71,(byte)80,(byte)75,(byte)71,(byte)36,(byte)36}); // EAGPKG$$ - os.write(new byte[]{(byte)6,(byte)118,(byte)101,(byte)114,(byte)50,(byte)46,(byte)48}); // 6 + ver2.0 + + os.write(new byte[] { (byte) 69, (byte) 65, (byte) 71, (byte) 80, (byte) 75, (byte) 71, (byte) 36, + (byte) 36 }); // EAGPKG$$ + os.write(new byte[] { (byte) 6, (byte) 118, (byte) 101, (byte) 114, (byte) 50, (byte) 46, (byte) 48 }); // 6 + // + + // ver2.0 Date d = new Date(); - + byte[] filename = (name + ".epk").getBytes(StandardCharsets.UTF_8); os.write(filename.length); os.write(filename); - - byte[] comment = (world ? ("\n\n # Eagler EPK v2.0 (c) " - + (new SimpleDateFormat("yyyy")).format(d) + " " + owner - + "\n # export: on " + (new SimpleDateFormat("MM/dd/yyyy")).format(d) - + " at " + (new SimpleDateFormat("hh:mm:ss aa")).format(d) - + "\n\n # world name: " + name + "\n\n") : commentStr).getBytes(StandardCharsets.UTF_8); + + byte[] comment = (world + ? ("\n\n # Eagler EPK v2.0 (c) " + (new SimpleDateFormat("yyyy")).format(d) + " " + owner + + "\n # export: on " + (new SimpleDateFormat("MM/dd/yyyy")).format(d) + " at " + + (new SimpleDateFormat("hh:mm:ss aa")).format(d) + "\n\n # world name: " + name + "\n\n") + : commentStr).getBytes(StandardCharsets.UTF_8); os.write((comment.length >>> 8) & 255); os.write(comment.length & 255); os.write(comment); - + writeLong(d.getTime(), os); - + lengthIntegerOffset = os.size(); - os.write(new byte[]{(byte)255,(byte)255,(byte)255,(byte)255}); // this will be replaced with the file count - - if(gzip) { + os.write(new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255 }); // this will be replaced with the + // file count + + if (gzip) { os.write('G'); // compression type: gzip dos = EaglerZLIB.newGZIPOutputStream(os); - }else { + } else { os.write('0'); // compression type: none dos = os; } - - dos.write(new byte[]{(byte)72,(byte)69,(byte)65,(byte)68}); // HEAD - dos.write(new byte[]{(byte)9,(byte)102,(byte)105,(byte)108,(byte)101,(byte)45,(byte)116,(byte)121, - (byte)112,(byte)101}); // 9 + file-type - + + dos.write(new byte[] { (byte) 72, (byte) 69, (byte) 65, (byte) 68 }); // HEAD + dos.write(new byte[] { (byte) 9, (byte) 102, (byte) 105, (byte) 108, (byte) 101, (byte) 45, (byte) 116, + (byte) 121, (byte) 112, (byte) 101 }); // 9 + file-type + byte[] typeBytes = type.getBytes(StandardCharsets.UTF_8); writeInt(typeBytes.length, dos); dos.write(typeBytes); // write type dos.write('>'); - + ++totalFileCount; - - if(world) { - dos.write(new byte[]{(byte)72,(byte)69,(byte)65,(byte)68}); // HEAD - dos.write(new byte[]{(byte)10,(byte)119,(byte)111,(byte)114,(byte)108,(byte)100,(byte)45,(byte)110, - (byte)97,(byte)109,(byte)101}); // 10 + world-name - + + if (world) { + dos.write(new byte[] { (byte) 72, (byte) 69, (byte) 65, (byte) 68 }); // HEAD + dos.write(new byte[] { (byte) 10, (byte) 119, (byte) 111, (byte) 114, (byte) 108, (byte) 100, (byte) 45, + (byte) 110, (byte) 97, (byte) 109, (byte) 101 }); // 10 + world-name + byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); writeInt(nameBytes.length, dos); dos.write(nameBytes); // write name dos.write('>'); - + ++totalFileCount; } - - if(world && owner != null) { - dos.write(new byte[]{(byte)72,(byte)69,(byte)65,(byte)68}); // HEAD - dos.write(new byte[]{(byte)11,(byte)119,(byte)111,(byte)114,(byte)108,(byte)100,(byte)45,(byte)111, - (byte)119,(byte)110,(byte)101,(byte)114}); // 11 + world-owner - + + if (world && owner != null) { + dos.write(new byte[] { (byte) 72, (byte) 69, (byte) 65, (byte) 68 }); // HEAD + dos.write(new byte[] { (byte) 11, (byte) 119, (byte) 111, (byte) 114, (byte) 108, (byte) 100, (byte) 45, + (byte) 111, (byte) 119, (byte) 110, (byte) 101, (byte) 114 }); // 11 + world-owner + byte[] ownerBytes = owner.getBytes(StandardCharsets.UTF_8); writeInt(ownerBytes.length, dos); dos.write(ownerBytes); // write owner dos.write('>'); - + ++totalFileCount; } - - }catch(IOException ex) { + + } catch (IOException ex) { throw new RuntimeException("This happened somehow", ex); } } - + public void append(String name, byte[] dat) { try { - + checkSum.reset(); checkSum.update(dat, 0, dat.length); long sum = checkSum.getValue(); - - dos.write(new byte[]{(byte)70,(byte)73,(byte)76,(byte)69}); // FILE - + + dos.write(new byte[] { (byte) 70, (byte) 73, (byte) 76, (byte) 69 }); // FILE + byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); dos.write(nameBytes.length); dos.write(nameBytes); - + writeInt(dat.length + 5, dos); - writeInt((int)sum, dos); - + writeInt((int) sum, dos); + dos.write(dat); - + dos.write(':'); dos.write('>'); - + ++totalFileCount; - - }catch(IOException ex) { + + } catch (IOException ex) { throw new RuntimeException("This happened somehow", ex); } } - + public byte[] complete() { try { - dos.write(new byte[]{(byte)69,(byte)78,(byte)68,(byte)36}); // END$ + dos.write(new byte[] { (byte) 69, (byte) 78, (byte) 68, (byte) 36 }); // END$ dos.close(); - - os.write(new byte[]{(byte)58,(byte)58,(byte)58,(byte)89,(byte)69,(byte)69,(byte)58,(byte)62}); // :::YEE:> - + + os.write(new byte[] { (byte) 58, (byte) 58, (byte) 58, (byte) 89, (byte) 69, (byte) 69, (byte) 58, + (byte) 62 }); // :::YEE:> + byte[] ret = os.toByteArray(); - ret[lengthIntegerOffset] = (byte)(totalFileCount >>> 24); - ret[lengthIntegerOffset + 1] = (byte)(totalFileCount >>> 16); - ret[lengthIntegerOffset + 2] = (byte)(totalFileCount >>> 8); - ret[lengthIntegerOffset + 3] = (byte)(totalFileCount & 0xFF); - + ret[lengthIntegerOffset] = (byte) (totalFileCount >>> 24); + ret[lengthIntegerOffset + 1] = (byte) (totalFileCount >>> 16); + ret[lengthIntegerOffset + 2] = (byte) (totalFileCount >>> 8); + ret[lengthIntegerOffset + 3] = (byte) (totalFileCount & 0xFF); + return ret; - - }catch(IOException ex) { + + } catch (IOException ex) { throw new RuntimeException("This happened somehow", ex); } } - - public static void writeInt(int i, OutputStream os) throws IOException { - os.write((i >>> 24) & 0xFF); - os.write((i >>> 16) & 0xFF); - os.write((i >>> 8) & 0xFF); - os.write(i & 0xFF); - } - - public static void writeLong(long i, OutputStream os) throws IOException { - os.write((int)((i >>> 56l) & 0xFFl)); - os.write((int)((i >>> 48l) & 0xFFl)); - os.write((int)((i >>> 40l) & 0xFFl)); - os.write((int)((i >>> 32l) & 0xFFl)); - os.write((int)((i >>> 24l) & 0xFFl)); - os.write((int)((i >>> 16l) & 0xFFl)); - os.write((int)((i >>> 8l) & 0xFFl)); - os.write((int)(i & 0xFFl)); - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKDecompiler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKDecompiler.java index fb07f6d1..4c1349cc 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKDecompiler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/EPKDecompiler.java @@ -13,14 +13,15 @@ import net.lax1dude.eaglercraft.v1_8.IOUtils; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,50 +32,81 @@ public class EPKDecompiler implements Closeable { public final String type; public final String name; public final byte[] data; + protected FileEntry(String type, String name, byte[] data) { this.type = type; this.name = name; this.data = data; } } - + + public static final int loadInt(InputStream is) throws IOException { + return (is.read() << 24) | (is.read() << 16) | (is.read() << 8) | is.read(); + } + + public static final int loadShort(InputStream is) throws IOException { + return (is.read() << 8) | is.read(); + } + + public static final String readASCII(byte[] bytesIn) throws IOException { + char[] charIn = new char[bytesIn.length]; + for (int i = 0; i < bytesIn.length; ++i) { + charIn[i] = (char) ((int) bytesIn[i] & 0xFF); + } + return new String(charIn); + } + + public static final String readASCII(InputStream bytesIn) throws IOException { + int len = bytesIn.read(); + char[] charIn = new char[len]; + for (int i = 0; i < len; ++i) { + charIn[i] = (char) (bytesIn.read() & 0xFF); + } + return new String(charIn); + } + private ByteArrayInputStream in2; + private InputStream zis; + private CRC32 crc32; + private int numFiles; + private boolean isFinished = false; - + public EPKDecompiler(byte[] data) throws IOException { in2 = new ByteArrayInputStream(data); - + byte[] header = new byte[8]; IOUtils.readFully(in2, header); - - if(Arrays.equals(header, new byte[]{(byte)69,(byte)65,(byte)71,(byte)80,(byte)75,(byte)71,(byte)36,(byte)36})) { - byte[] endCode = new byte[] { (byte)':', (byte)':', (byte)':', (byte)'Y', - (byte)'E', (byte)'E', (byte)':', (byte)'>' }; - for(int i = 0; i < 8; ++i) { - if(data[data.length - 8 + i] != endCode[i]) { + + if (Arrays.equals(header, new byte[] { (byte) 69, (byte) 65, (byte) 71, (byte) 80, (byte) 75, (byte) 71, + (byte) 36, (byte) 36 })) { + byte[] endCode = new byte[] { (byte) ':', (byte) ':', (byte) ':', (byte) 'Y', (byte) 'E', (byte) 'E', + (byte) ':', (byte) '>' }; + for (int i = 0; i < 8; ++i) { + if (data[data.length - 8 + i] != endCode[i]) { throw new IOException("EPK file is missing EOF code (:::YEE:>)"); } } in2 = new ByteArrayInputStream(data, 8, data.length - 16); InputStream is = in2; - + String vers = readASCII(is); - if(!vers.startsWith("ver2.")) { + if (!vers.startsWith("ver2.")) { throw new IOException("Unknown or invalid EPK version: " + vers); } IOUtils.skipFully(is, is.read()); // skip filename IOUtils.skipFully(is, loadShort(is)); // skip comment IOUtils.skipFully(is, 8); // skip millis date - + numFiles = loadInt(is); - - char compressionType = (char)is.read(); - - switch(compressionType) { + + char compressionType = (char) is.read(); + + switch (compressionType) { case 'G': zis = EaglerZLIB.newGZIPInputStream(is); break; @@ -87,96 +119,15 @@ public class EPKDecompiler implements Closeable { default: throw new IOException("Invalid or unsupported EPK compression: " + compressionType); } - + crc32 = new CRC32(); - }else if(Arrays.equals(header, new byte[]{(byte)69,(byte)65,(byte)71,(byte)80,(byte)75,(byte)71,(byte)33,(byte)33})) { + } else if (Arrays.equals(header, new byte[] { (byte) 69, (byte) 65, (byte) 71, (byte) 80, (byte) 75, (byte) 71, + (byte) 33, (byte) 33 })) { throw new IOException("FILE IS AN UNSUPPORTED LEGACY FORMAT!"); - }else { + } else { throw new IOException("FILE IS NOT AN EPK FILE!"); } - - } - public FileEntry readFile() throws IOException { - if(isFinished) { - return null; - } - - byte[] typeBytes = new byte[4]; - IOUtils.readFully(zis, typeBytes); - String type = readASCII(typeBytes); - - if(numFiles == 0) { - if(!"END$".equals(type)) { - throw new IOException("EPK file is missing END code (END$)"); - } - isFinished = true; - return null; - }else { - if("END$".equals(type)) { - throw new IOException("Unexpected END when there are still " + numFiles + " files remaining"); - }else { - String name = readASCII(zis); - int len = loadInt(zis); - byte[] data; - - if("FILE".equals(type)) { - if(len < 5) { - throw new IOException("File '" + name + "' is incomplete (no crc)"); - } - - int loadedCrc = loadInt(zis); - - data = new byte[len - 5]; - IOUtils.readFully(zis, data); - - crc32.reset(); - crc32.update(data, 0, data.length); - if((int)crc32.getValue() != loadedCrc) { - throw new IOException("File '" + name + "' has an invalid checksum"); - } - - if(zis.read() != ':') { - throw new IOException("File '" + name + "' is incomplete"); - } - }else { - data = new byte[len]; - IOUtils.readFully(zis, data); - } - - if(zis.read() != '>') { - throw new IOException("Object '" + name + "' is incomplete"); - } - - --numFiles; - return new FileEntry(type, name, data); - } - } - } - - public static final int loadShort(InputStream is) throws IOException { - return (is.read() << 8) | is.read(); - } - - public static final int loadInt(InputStream is) throws IOException { - return (is.read() << 24) | (is.read() << 16) | (is.read() << 8) | is.read(); - } - - public static final String readASCII(byte[] bytesIn) throws IOException { - char[] charIn = new char[bytesIn.length]; - for(int i = 0; i < bytesIn.length; ++i) { - charIn[i] = (char)((int)bytesIn[i] & 0xFF); - } - return new String(charIn); - } - - public static final String readASCII(InputStream bytesIn) throws IOException { - int len = bytesIn.read(); - char[] charIn = new char[len]; - for(int i = 0; i < len; ++i) { - charIn[i] = (char)(bytesIn.read() & 0xFF); - } - return new String(charIn); } @Override @@ -184,4 +135,61 @@ public class EPKDecompiler implements Closeable { zis.close(); } + public FileEntry readFile() throws IOException { + if (isFinished) { + return null; + } + + byte[] typeBytes = new byte[4]; + IOUtils.readFully(zis, typeBytes); + String type = readASCII(typeBytes); + + if (numFiles == 0) { + if (!"END$".equals(type)) { + throw new IOException("EPK file is missing END code (END$)"); + } + isFinished = true; + return null; + } else { + if ("END$".equals(type)) { + throw new IOException("Unexpected END when there are still " + numFiles + " files remaining"); + } else { + String name = readASCII(zis); + int len = loadInt(zis); + byte[] data; + + if ("FILE".equals(type)) { + if (len < 5) { + throw new IOException("File '" + name + "' is incomplete (no crc)"); + } + + int loadedCrc = loadInt(zis); + + data = new byte[len - 5]; + IOUtils.readFully(zis, data); + + crc32.reset(); + crc32.update(data, 0, data.length); + if ((int) crc32.getValue() != loadedCrc) { + throw new IOException("File '" + name + "' has an invalid checksum"); + } + + if (zis.read() != ':') { + throw new IOException("File '" + name + "' is incomplete"); + } + } else { + data = new byte[len]; + IOUtils.readFully(zis, data); + } + + if (zis.read() != '>') { + throw new IOException("Object '" + name + "' is incomplete"); + } + + --numFiles; + return new FileEntry(type, name, data); + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/RandomAccessMemoryFile.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/RandomAccessMemoryFile.java index d0052ccf..3a47f1f9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/RandomAccessMemoryFile.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/RandomAccessMemoryFile.java @@ -8,14 +8,15 @@ import java.io.IOException; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,6 +33,16 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { this.pos = 0; } + public byte[] getByteArray() { + byte[] b = new byte[length]; + System.arraycopy(buffer, 0, b, 0, length); + return b; + } + + public int getLength() { + return length; + } + private void grow(int newMaxSize) { if (length < newMaxSize) { if (buffer.length < newMaxSize) { @@ -43,16 +54,32 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { } } - public byte[] getByteArray() { - byte[] b = new byte[length]; - System.arraycopy(buffer, 0, b, 0, length); - return b; - } - public int read() throws IOException { return (pos < length) ? (buffer[pos++] & 0xff) : -1; } + public int read(byte b[]) throws IOException { + return readBytes(b, 0, b.length); + } + + public int read(byte b[], int off, int len) throws IOException { + return readBytes(b, off, len); + } + + public final boolean readBoolean() throws IOException { + int ch = this.read(); + if (ch < 0) + throw new EOFException(); + return (ch != 0); + } + + public final byte readByte() throws IOException { + int ch = this.read(); + if (ch < 0) + throw new EOFException(); + return (byte) (ch); + } + private int readBytes(byte b[], int off, int len) throws IOException { if (pos >= length) { return -1; @@ -70,12 +97,20 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { return len; } - public int read(byte b[], int off, int len) throws IOException { - return readBytes(b, off, len); + public final char readChar() throws IOException { + int ch1 = this.read(); + int ch2 = this.read(); + if ((ch1 | ch2) < 0) + throw new EOFException(); + return (char) ((ch1 << 8) + (ch2 << 0)); } - public int read(byte b[]) throws IOException { - return readBytes(b, 0, b.length); + public final double readDouble() throws IOException { + return Double.longBitsToDouble(readLong()); + } + + public final float readFloat() throws IOException { + return Float.intBitsToFloat(readInt()); } public final void readFully(byte b[]) throws IOException { @@ -92,98 +127,6 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { } while (n < len); } - public int skipBytes(int n) throws IOException { - int newpos; - - if (n <= 0) { - return 0; - } - newpos = pos + n; - if (newpos > length) { - newpos = length; - } - seek(newpos); - - return (int) (newpos - pos); - } - - public void write(int b) throws IOException { - grow(pos + 1); - buffer[pos] = (byte) b; - pos += 1; - } - - private void writeBytes(byte b[], int off, int len) throws IOException { - grow(pos + len); - System.arraycopy(b, off, buffer, pos, len); - pos += len; - } - - public void write(byte b[]) throws IOException { - writeBytes(b, 0, b.length); - } - - public void write(byte b[], int off, int len) throws IOException { - writeBytes(b, off, len); - } - - public void seek(int pos) { - this.pos = pos; - } - - public int getLength() { - return length; - } - - public void setLength(int newLength) { - grow(newLength); - } - - public final boolean readBoolean() throws IOException { - int ch = this.read(); - if (ch < 0) - throw new EOFException(); - return (ch != 0); - } - - public final byte readByte() throws IOException { - int ch = this.read(); - if (ch < 0) - throw new EOFException(); - return (byte) (ch); - } - - public final int readUnsignedByte() throws IOException { - int ch = this.read(); - if (ch < 0) - throw new EOFException(); - return ch; - } - - public final short readShort() throws IOException { - int ch1 = this.read(); - int ch2 = this.read(); - if ((ch1 | ch2) < 0) - throw new EOFException(); - return (short) ((ch1 << 8) + (ch2 << 0)); - } - - public final int readUnsignedShort() throws IOException { - int ch1 = this.read(); - int ch2 = this.read(); - if ((ch1 | ch2) < 0) - throw new EOFException(); - return (ch1 << 8) + (ch2 << 0); - } - - public final char readChar() throws IOException { - int ch1 = this.read(); - int ch2 = this.read(); - if ((ch1 | ch2) < 0) - throw new EOFException(); - return (char) ((ch1 << 8) + (ch2 << 0)); - } - public final int readInt() throws IOException { int ch1 = this.read(); int ch2 = this.read(); @@ -194,18 +137,6 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0)); } - public final long readLong() throws IOException { - return ((long) (readInt()) << 32) + (readInt() & 0xFFFFFFFFL); - } - - public final float readFloat() throws IOException { - return Float.intBitsToFloat(readInt()); - } - - public final double readDouble() throws IOException { - return Double.longBitsToDouble(readLong()); - } - public final String readLine() throws IOException { StringBuilder input = new StringBuilder(); int c = -1; @@ -236,10 +167,74 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { return input.toString(); } + public final long readLong() throws IOException { + return ((long) (readInt()) << 32) + (readInt() & 0xFFFFFFFFL); + } + + public final short readShort() throws IOException { + int ch1 = this.read(); + int ch2 = this.read(); + if ((ch1 | ch2) < 0) + throw new EOFException(); + return (short) ((ch1 << 8) + (ch2 << 0)); + } + + public final int readUnsignedByte() throws IOException { + int ch = this.read(); + if (ch < 0) + throw new EOFException(); + return ch; + } + + public final int readUnsignedShort() throws IOException { + int ch1 = this.read(); + int ch2 = this.read(); + if ((ch1 | ch2) < 0) + throw new EOFException(); + return (ch1 << 8) + (ch2 << 0); + } + public final String readUTF() throws IOException { throw new IOException("TODO"); } + public void seek(int pos) { + this.pos = pos; + } + + public void setLength(int newLength) { + grow(newLength); + } + + public int skipBytes(int n) throws IOException { + int newpos; + + if (n <= 0) { + return 0; + } + newpos = pos + n; + if (newpos > length) { + newpos = length; + } + seek(newpos); + + return (int) (newpos - pos); + } + + public void write(byte b[]) throws IOException { + writeBytes(b, 0, b.length); + } + + public void write(byte b[], int off, int len) throws IOException { + writeBytes(b, off, len); + } + + public void write(int b) throws IOException { + grow(pos + 1); + buffer[pos] = (byte) b; + pos += 1; + } + public final void writeBoolean(boolean v) throws IOException { write(v ? 1 : 0); } @@ -248,9 +243,17 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { write(v); } - public final void writeShort(int v) throws IOException { - write((v >>> 8) & 0xFF); - write((v >>> 0) & 0xFF); + private void writeBytes(byte b[], int off, int len) throws IOException { + grow(pos + len); + System.arraycopy(b, off, buffer, pos, len); + pos += len; + } + + public final void writeBytes(String s) throws IOException { + int len = s.length(); + byte[] b = new byte[len]; + s.getBytes(0, len, b, 0); + writeBytes(b, 0, len); } public final void writeChar(int v) throws IOException { @@ -258,6 +261,27 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { write((v >>> 0) & 0xFF); } + public final void writeChars(String s) throws IOException { + int clen = s.length(); + int blen = 2 * clen; + byte[] b = new byte[blen]; + char[] c = new char[clen]; + s.getChars(0, clen, c, 0); + for (int i = 0, j = 0; i < clen; i++) { + b[j++] = (byte) (c[i] >>> 8); + b[j++] = (byte) (c[i] >>> 0); + } + writeBytes(b, 0, blen); + } + + public final void writeDouble(double v) throws IOException { + writeLong(Double.doubleToLongBits(v)); + } + + public final void writeFloat(float v) throws IOException { + writeInt(Float.floatToIntBits(v)); + } + public final void writeInt(int v) throws IOException { write((v >>> 24) & 0xFF); write((v >>> 16) & 0xFF); @@ -276,32 +300,9 @@ public class RandomAccessMemoryFile implements DataInput, DataOutput { write((int) (v >>> 0) & 0xFF); } - public final void writeFloat(float v) throws IOException { - writeInt(Float.floatToIntBits(v)); - } - - public final void writeDouble(double v) throws IOException { - writeLong(Double.doubleToLongBits(v)); - } - - public final void writeBytes(String s) throws IOException { - int len = s.length(); - byte[] b = new byte[len]; - s.getBytes(0, len, b, 0); - writeBytes(b, 0, len); - } - - public final void writeChars(String s) throws IOException { - int clen = s.length(); - int blen = 2 * clen; - byte[] b = new byte[blen]; - char[] c = new char[clen]; - s.getChars(0, clen, c, 0); - for (int i = 0, j = 0; i < clen; i++) { - b[j++] = (byte) (c[i] >>> 8); - b[j++] = (byte) (c[i] >>> 0); - } - writeBytes(b, 0, blen); + public final void writeShort(int v) throws IOException { + write((v >>> 8) & 0xFF); + write((v >>> 0) & 0xFF); } public final void writeUTF(String str) throws IOException { diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterEPK.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterEPK.java index 524de859..a3b4f11b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterEPK.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterEPK.java @@ -18,14 +18,15 @@ import net.minecraft.world.storage.WorldInfo; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,82 +35,17 @@ public class WorldConverterEPK { private static final Logger logger = LogManager.getLogger("WorldConverterEPK"); - public static void importWorld(byte[] archiveContents, String newName) throws IOException { - logger.info("Importing world \"{}\" from EPK", newName); - String folderName = newName.replaceAll("[\\./\"]", "_"); - VFile2 worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); - while(WorldsDB.newVFile(worldDir, "level.dat").exists() || WorldsDB.newVFile(worldDir, "level.dat_old").exists()) { - folderName += "_"; - worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); - } - try(EPKDecompiler dc = new EPKDecompiler(archiveContents)) { - EPKDecompiler.FileEntry f = null; - int lastProgUpdate = 0; - int prog = 0; - String hasReadType = null; - boolean has152Format = false; - int cnt = 0; - while((f = dc.readFile()) != null) { - byte[] b = f.data; - if(hasReadType == null) { - if (f.type.equals("HEAD") && f.name.equals("file-type") - && ((hasReadType = EPKDecompiler.readASCII(f.data)).equals("epk/world188") - || (has152Format = hasReadType.equals("epk/world152")))) { - if(has152Format) { - logger.warn("World type detected as 1.5.2, it will be converted to 1.8.8 format"); - } - continue; - }else { - throw new IOException("file does not contain a singleplayer 1.5.2 or 1.8.8 world!"); - } - } - if(f.type.equals("FILE")) { - if(f.name.equals("level.dat") || f.name.equals("level.dat_old")) { - NBTTagCompound worldDatNBT = CompressedStreamTools.readCompressed(new EaglerInputStream(b)); - worldDatNBT.getCompoundTag("Data").setString("LevelName", newName); - worldDatNBT.getCompoundTag("Data").setLong("LastPlayed", System.currentTimeMillis()); - if(has152Format) { - WorldInfo.initEaglerVersion(worldDatNBT.getCompoundTag("Data")); - } - EaglerOutputStream tmp = new EaglerOutputStream(); - CompressedStreamTools.writeCompressed(worldDatNBT, tmp); - b = tmp.toByteArray(); - } - VFile2 ff = WorldsDB.newVFile(worldDir, f.name); - ff.setAllBytes(b); - prog += b.length; - ++cnt; - if(prog - lastProgUpdate > 25000) { - lastProgUpdate = prog; - logger.info("Extracted {} files, {} bytes from EPK...", cnt, prog); - EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.importing.1", prog); - } - } - } - } - logger.info("EPK was successfully extracted into directory \"{}\"", worldDir.getPath()); - String[] worldsTxt = EaglerSaveFormat.worldsList.getAllLines(); - if(worldsTxt == null || worldsTxt.length <= 0 || (worldsTxt.length == 1 && worldsTxt[0].trim().length() <= 0)) { - worldsTxt = new String[] { folderName }; - }else { - String[] tmp = worldsTxt; - worldsTxt = new String[worldsTxt.length + 1]; - System.arraycopy(tmp, 0, worldsTxt, 0, tmp.length); - worldsTxt[worldsTxt.length - 1] = folderName; - } - EaglerSaveFormat.worldsList.setAllChars(String.join("\n", worldsTxt)); - } - public static byte[] exportWorld(String worldName) { String realWorldName = worldName; String worldOwner = "UNKNOWN"; - String splitter = new String(new char[] { (char)253, (char)233, (char)233 }); - if(worldName.contains(splitter)) { + String splitter = new String(new char[] { (char) 253, (char) 233, (char) 233 }); + if (worldName.contains(splitter)) { int i = worldName.lastIndexOf(splitter); worldOwner = worldName.substring(i + 3); realWorldName = worldName.substring(0, i); } - VFile2 worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(realWorldName, false).getWorldDirectory(); + VFile2 worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(realWorldName, false) + .getWorldDirectory(); logger.info("Exporting world directory \"{}\" as EPK", worldDir.getPath()); final int[] bytesWritten = new int[1]; final int[] filesWritten = new int[1]; @@ -117,7 +53,7 @@ public class WorldConverterEPK { EPKCompiler c = new EPKCompiler(realWorldName, worldOwner, "epk/world188"); String pfx = worldDir.getPath(); List filesList = worldDir.listFiles(true); - for(int i = 0, l = filesList.size(); i < l; ++i) { + for (int i = 0, l = filesList.size(); i < l; ++i) { VFile2 vf = filesList.get(i); ++filesWritten[0]; byte[] b = vf.getAllBytes(); @@ -134,4 +70,72 @@ public class WorldConverterEPK { return r; } + public static void importWorld(byte[] archiveContents, String newName) throws IOException { + logger.info("Importing world \"{}\" from EPK", newName); + String folderName = newName.replaceAll("[\\./\"]", "_"); + VFile2 worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); + while (WorldsDB.newVFile(worldDir, "level.dat").exists() + || WorldsDB.newVFile(worldDir, "level.dat_old").exists()) { + folderName += "_"; + worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); + } + try (EPKDecompiler dc = new EPKDecompiler(archiveContents)) { + EPKDecompiler.FileEntry f = null; + int lastProgUpdate = 0; + int prog = 0; + String hasReadType = null; + boolean has152Format = false; + int cnt = 0; + while ((f = dc.readFile()) != null) { + byte[] b = f.data; + if (hasReadType == null) { + if (f.type.equals("HEAD") && f.name.equals("file-type") + && ((hasReadType = EPKDecompiler.readASCII(f.data)).equals("epk/world188") + || (has152Format = hasReadType.equals("epk/world152")))) { + if (has152Format) { + logger.warn("World type detected as 1.5.2, it will be converted to 1.8.8 format"); + } + continue; + } else { + throw new IOException("file does not contain a singleplayer 1.5.2 or 1.8.8 world!"); + } + } + if (f.type.equals("FILE")) { + if (f.name.equals("level.dat") || f.name.equals("level.dat_old")) { + NBTTagCompound worldDatNBT = CompressedStreamTools.readCompressed(new EaglerInputStream(b)); + worldDatNBT.getCompoundTag("Data").setString("LevelName", newName); + worldDatNBT.getCompoundTag("Data").setLong("LastPlayed", System.currentTimeMillis()); + if (has152Format) { + WorldInfo.initEaglerVersion(worldDatNBT.getCompoundTag("Data")); + } + EaglerOutputStream tmp = new EaglerOutputStream(); + CompressedStreamTools.writeCompressed(worldDatNBT, tmp); + b = tmp.toByteArray(); + } + VFile2 ff = WorldsDB.newVFile(worldDir, f.name); + ff.setAllBytes(b); + prog += b.length; + ++cnt; + if (prog - lastProgUpdate > 25000) { + lastProgUpdate = prog; + logger.info("Extracted {} files, {} bytes from EPK...", cnt, prog); + EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.importing.1", prog); + } + } + } + } + logger.info("EPK was successfully extracted into directory \"{}\"", worldDir.getPath()); + String[] worldsTxt = EaglerSaveFormat.worldsList.getAllLines(); + if (worldsTxt == null || worldsTxt.length <= 0 + || (worldsTxt.length == 1 && worldsTxt[0].trim().length() <= 0)) { + worldsTxt = new String[] { folderName }; + } else { + String[] tmp = worldsTxt; + worldsTxt = new String[worldsTxt.length + 1]; + System.arraycopy(tmp, 0, worldsTxt, 0, tmp.length); + worldsTxt[worldsTxt.length - 1] = folderName; + } + EaglerSaveFormat.worldsList.setAllChars(String.join("\n", worldsTxt)); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterMCA.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterMCA.java index 7e5bfa5e..2caf9e20 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterMCA.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/export/WorldConverterMCA.java @@ -20,22 +20,23 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerChunkLoader; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerIntegratedServerWorker; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerSaveFormat; import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; -import net.minecraft.world.chunk.storage.RegionFile; -import net.minecraft.world.storage.WorldInfo; import net.minecraft.nbt.CompressedStreamTools; import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.world.chunk.storage.RegionFile; +import net.minecraft.world.storage.WorldInfo; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,53 +45,193 @@ public class WorldConverterMCA { private static final Logger logger = LogManager.getLogger("WorldConverterMCA"); + public static byte[] exportWorld(String folderName) throws IOException { + EaglerOutputStream bao = new EaglerOutputStream(); + VFile2 worldFolder; + try (ZipOutputStream zos = new ZipOutputStream(bao)) { + zos.setComment("contains backup of world '" + folderName + "'"); + worldFolder = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); + logger.info("Exporting world directory \"{}\" as MCA", worldFolder.getPath()); + VFile2 vf = WorldsDB.newVFile(worldFolder, "level.dat"); + byte[] b; + int lastProgUpdate = 0; + int prog = 0; + boolean safe = false; + if (vf.exists()) { + zos.putNextEntry(new ZipEntry(folderName + "/level.dat")); + b = vf.getAllBytes(); + zos.write(b); + prog += b.length; + safe = true; + } + vf = WorldsDB.newVFile(worldFolder, "level.dat_old"); + if (vf.exists()) { + zos.putNextEntry(new ZipEntry(folderName + "/level.dat_old")); + b = vf.getAllBytes(); + zos.write(b); + prog += b.length; + safe = true; + } + if (prog - lastProgUpdate > 25000) { + lastProgUpdate = prog; + EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); + } + String[] srcFolderNames = new String[] { "level0", "level-1", "level1" }; + String[] dstFolderNames = new String[] { "/region/", "/DIM-1/region/", "/DIM1/region/" }; + List fileList; + for (int i = 0; i < 3; ++i) { + vf = WorldsDB.newVFile(worldFolder, srcFolderNames[i]); + fileList = vf.listFiles(true); + String regionFolder = folderName + dstFolderNames[i]; + logger.info("Converting chunks in \"{}\" as MCA to \"{}\"...", vf.getPath(), regionFolder); + Map regionFiles = new HashMap<>(); + for (int k = 0, l = fileList.size(); k < l; ++k) { + VFile2 chunkFile = fileList.get(k); + NBTTagCompound chunkNBT; + NBTTagCompound chunkLevel; + try { + b = chunkFile.getAllBytes(); + chunkNBT = CompressedStreamTools.readCompressed(new EaglerInputStream(b)); + if (!chunkNBT.hasKey("Level", 10)) { + throw new IOException("Chunk is missing level data!"); + } + chunkLevel = chunkNBT.getCompoundTag("Level"); + } catch (IOException t) { + logger.error("Could not read chunk: {}", chunkFile.getPath()); + logger.error(t); + continue; + } + int chunkX = chunkLevel.getInteger("xPos"); + int chunkZ = chunkLevel.getInteger("zPos"); + String regionFileName = "r." + (chunkX >> 5) + "." + (chunkZ >> 5) + ".mca"; + RegionFile rf = regionFiles.get(regionFileName); + if (rf == null) { + rf = new RegionFile(new RandomAccessMemoryFile(new byte[65536], 0)); + regionFiles.put(regionFileName, rf); + } + try (DataOutputStream dos = rf.getChunkDataOutputStream(chunkX & 31, chunkZ & 31)) { + CompressedStreamTools.write(chunkNBT, dos); + } catch (IOException t) { + logger.error("Could not write chunk to {}: {}", regionFileName, chunkFile.getPath()); + logger.error(t); + continue; + } + prog += b.length; + if (prog - lastProgUpdate > 25000) { + lastProgUpdate = prog; + EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); + } + } + if (regionFiles.isEmpty()) { + logger.info("No region files were generated"); + continue; + } + for (Entry etr : regionFiles.entrySet()) { + String regionPath = regionFolder + etr.getKey(); + logger.info("Writing region file: {}", regionPath); + zos.putNextEntry(new ZipEntry(regionPath)); + zos.write(etr.getValue().getFile().getByteArray()); + } + } + logger.info("Copying extra world data..."); + fileList = WorldsDB.newVFile(worldFolder, "data").listFiles(false); + for (int k = 0, l = fileList.size(); k < l; ++k) { + VFile2 dataFile = fileList.get(k); + zos.putNextEntry(new ZipEntry(folderName + "/data/" + dataFile.getName())); + b = dataFile.getAllBytes(); + zos.write(b); + prog += b.length; + if (prog - lastProgUpdate > 25000) { + lastProgUpdate = prog; + EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); + } + } + fileList = WorldsDB.newVFile(worldFolder, "players").listFiles(false); + for (int k = 0, l = fileList.size(); k < l; ++k) { + VFile2 dataFile = fileList.get(k); + zos.putNextEntry(new ZipEntry(folderName + "/players/" + dataFile.getName())); + b = dataFile.getAllBytes(); + zos.write(b); + prog += b.length; + if (prog - lastProgUpdate > 25000) { + lastProgUpdate = prog; + EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); + } + } + fileList = WorldsDB.newVFile(worldFolder, "eagler/skulls").listFiles(false); + for (int k = 0, l = fileList.size(); k < l; ++k) { + VFile2 dataFile = fileList.get(k); + zos.putNextEntry(new ZipEntry(folderName + "/eagler/skulls/" + dataFile.getName())); + b = dataFile.getAllBytes(); + zos.write(b); + prog += b.length; + if (prog - lastProgUpdate > 25000) { + lastProgUpdate = prog; + EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); + } + } + } + logger.info("World directory \"{}\" was successfully exported as MCA", worldFolder.getPath()); + return bao.toByteArray(); + } + public static void importWorld(byte[] archiveContents, String newName, byte gameRules) throws IOException { logger.info("Importing world \"{}\" from MCA", newName); String folderName = newName.replaceAll("[\\./\"]", "_"); VFile2 worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); - while(WorldsDB.newVFile(worldDir, "level.dat").exists() || WorldsDB.newVFile(worldDir, "level.dat_old").exists()) { + while (WorldsDB.newVFile(worldDir, "level.dat").exists() + || WorldsDB.newVFile(worldDir, "level.dat_old").exists()) { folderName += "_"; worldDir = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); } List fileNames = new ArrayList<>(); - try(ZipInputStream zis = new ZipInputStream(new EaglerInputStream(archiveContents))) { + try (ZipInputStream zis = new ZipInputStream(new EaglerInputStream(archiveContents))) { ZipEntry folderNameFile = null; - while((folderNameFile = zis.getNextEntry()) != null) { - if (folderNameFile.getName().contains("__MACOSX/")) continue; - if (folderNameFile.isDirectory()) continue; + while ((folderNameFile = zis.getNextEntry()) != null) { + if (folderNameFile.getName().contains("__MACOSX/")) + continue; + if (folderNameFile.isDirectory()) + continue; String lowerName = folderNameFile.getName().toLowerCase(); - if (!(lowerName.endsWith(".dat") || lowerName.endsWith(".dat_old") || lowerName.endsWith(".mca") || lowerName.endsWith(".mcr"))) continue; + if (!(lowerName.endsWith(".dat") || lowerName.endsWith(".dat_old") || lowerName.endsWith(".mca") + || lowerName.endsWith(".mcr"))) + continue; fileNames.add(folderNameFile.getName().toCharArray()); } } final int[] i = new int[] { 0 }; - while(fileNames.get(0).length > i[0] && fileNames.stream().allMatch(w -> w[i[0]] == fileNames.get(0)[i[0]])) i[0]++; + while (fileNames.get(0).length > i[0] && fileNames.stream().allMatch(w -> w[i[0]] == fileNames.get(0)[i[0]])) + i[0]++; int folderPrefixOffset = i[0]; - try(ZipInputStream zis = new ZipInputStream(new EaglerInputStream(archiveContents))) { + try (ZipInputStream zis = new ZipInputStream(new EaglerInputStream(archiveContents))) { ZipEntry f = null; int lastProgUpdate = 0; int prog = 0; byte[] bb = new byte[16384]; while ((f = zis.getNextEntry()) != null) { - if (f.getName().contains("__MACOSX/")) continue; - if (f.isDirectory()) continue; + if (f.getName().contains("__MACOSX/")) + continue; + if (f.isDirectory()) + continue; String lowerName = f.getName().toLowerCase(); - if (!(lowerName.endsWith(".dat") || lowerName.endsWith(".dat_old") || lowerName.endsWith(".mca") || lowerName.endsWith(".mcr") || lowerName.endsWith(".bmp"))) continue; + if (!(lowerName.endsWith(".dat") || lowerName.endsWith(".dat_old") || lowerName.endsWith(".mca") + || lowerName.endsWith(".mcr") || lowerName.endsWith(".bmp"))) + continue; byte[] b; - int sz = (int)f.getSize(); - if(sz >= 0) { + int sz = (int) f.getSize(); + if (sz >= 0) { b = new byte[sz]; int j = 0, k; - while(j < b.length && (k = zis.read(b, j, b.length - j)) != -1) { + while (j < b.length && (k = zis.read(b, j, b.length - j)) != -1) { j += k; } - }else { + } else { b = EaglerInputStream.inputStreamToBytes(zis); } String fileName = f.getName().substring(folderPrefixOffset); if (fileName.equals("level.dat") || fileName.equals("level.dat_old")) { NBTTagCompound worldDatNBT = CompressedStreamTools.readCompressed(new EaglerInputStream(b)); - + NBTTagCompound gameRulesNBT = worldDatNBT.getCompoundTag("Data").getCompoundTag("GameRules"); gameRulesNBT.setString("loadSpawnChunks", (gameRules & 2) != 0 ? "true" : "false"); String s = (gameRules & 1) != 0 ? "true" : "false"; @@ -109,30 +250,33 @@ public class WorldConverterMCA { VFile2 ff = WorldsDB.newVFile(worldDir, fileName); ff.setAllBytes(b); prog += b.length; - } else if ((fileName.endsWith(".mcr") || fileName.endsWith(".mca")) && (fileName.startsWith("region/") || fileName.startsWith("DIM1/region/") || fileName.startsWith("DIM-1/region/"))) { - VFile2 chunkFolder = WorldsDB.newVFile(worldDir, fileName.startsWith("DIM1") ? "level1" : (fileName.startsWith("DIM-1") ? "level-1" : "level0")); + } else if ((fileName.endsWith(".mcr") || fileName.endsWith(".mca")) && (fileName.startsWith("region/") + || fileName.startsWith("DIM1/region/") || fileName.startsWith("DIM-1/region/"))) { + VFile2 chunkFolder = WorldsDB.newVFile(worldDir, fileName.startsWith("DIM1") ? "level1" + : (fileName.startsWith("DIM-1") ? "level-1" : "level0")); RegionFile mca = new RegionFile(new RandomAccessMemoryFile(b, b.length)); int loadChunksCount = 0; - for(int j = 0; j < 32; ++j) { - for(int k = 0; k < 32; ++k) { - if(mca.isChunkSaved(j, k)) { + for (int j = 0; j < 32; ++j) { + for (int k = 0; k < 32; ++k) { + if (mca.isChunkSaved(j, k)) { NBTTagCompound chunkNBT; NBTTagCompound chunkLevel; try { chunkNBT = CompressedStreamTools.read(mca.getChunkDataInputStream(j, k)); - if(!chunkNBT.hasKey("Level", 10)) { + if (!chunkNBT.hasKey("Level", 10)) { throw new IOException("Chunk is missing level data!"); } chunkLevel = chunkNBT.getCompoundTag("Level"); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("{}: Could not read chunk: {}, {}", fileName, j, k); logger.error(t); continue; } int chunkX = chunkLevel.getInteger("xPos"); int chunkZ = chunkLevel.getInteger("zPos"); - VFile2 chunkOut = WorldsDB.newVFile(chunkFolder, EaglerChunkLoader.getChunkPath(chunkX, chunkZ) + ".dat"); - if(chunkOut.exists()) { + VFile2 chunkOut = WorldsDB.newVFile(chunkFolder, + EaglerChunkLoader.getChunkPath(chunkX, chunkZ) + ".dat"); + if (chunkOut.exists()) { logger.error("{}: Chunk already exists: {}", fileName, chunkOut.getPath()); continue; } @@ -151,8 +295,9 @@ public class WorldConverterMCA { } logger.info("{}: Imported {} chunks successfully ({} bytes)", fileName, loadChunksCount, prog); } else if (fileName.startsWith("playerdata/") || fileName.startsWith("stats/")) { - //TODO: LAN player inventories - } else if (fileName.startsWith("data/") || fileName.startsWith("players/") || fileName.startsWith("eagler/skulls/")) { + // TODO: LAN player inventories + } else if (fileName.startsWith("data/") || fileName.startsWith("players/") + || fileName.startsWith("eagler/skulls/")) { VFile2 ff = WorldsDB.newVFile(worldDir, fileName); ff.setAllBytes(b); prog += b.length; @@ -167,9 +312,10 @@ public class WorldConverterMCA { } logger.info("MCA was successfully extracted into directory \"{}\"", worldDir.getPath()); String[] worldsTxt = EaglerSaveFormat.worldsList.getAllLines(); - if(worldsTxt == null || worldsTxt.length <= 0 || (worldsTxt.length == 1 && worldsTxt[0].trim().length() <= 0)) { + if (worldsTxt == null || worldsTxt.length <= 0 + || (worldsTxt.length == 1 && worldsTxt[0].trim().length() <= 0)) { worldsTxt = new String[] { folderName }; - }else { + } else { String[] tmp = worldsTxt; worldsTxt = new String[worldsTxt.length + 1]; System.arraycopy(tmp, 0, worldsTxt, 0, tmp.length); @@ -178,134 +324,4 @@ public class WorldConverterMCA { EaglerSaveFormat.worldsList.setAllChars(String.join("\n", worldsTxt)); } - public static byte[] exportWorld(String folderName) throws IOException { - EaglerOutputStream bao = new EaglerOutputStream(); - VFile2 worldFolder; - try(ZipOutputStream zos = new ZipOutputStream(bao)) { - zos.setComment("contains backup of world '" + folderName + "'"); - worldFolder = EaglerIntegratedServerWorker.saveFormat.getSaveLoader(folderName, false).getWorldDirectory(); - logger.info("Exporting world directory \"{}\" as MCA", worldFolder.getPath()); - VFile2 vf = WorldsDB.newVFile(worldFolder, "level.dat"); - byte[] b; - int lastProgUpdate = 0; - int prog = 0; - boolean safe = false; - if(vf.exists()) { - zos.putNextEntry(new ZipEntry(folderName + "/level.dat")); - b = vf.getAllBytes(); - zos.write(b); - prog += b.length; - safe = true; - } - vf = WorldsDB.newVFile(worldFolder, "level.dat_old"); - if(vf.exists()) { - zos.putNextEntry(new ZipEntry(folderName + "/level.dat_old")); - b = vf.getAllBytes(); - zos.write(b); - prog += b.length; - safe = true; - } - if (prog - lastProgUpdate > 25000) { - lastProgUpdate = prog; - EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); - } - String[] srcFolderNames = new String[] { "level0", "level-1", "level1" }; - String[] dstFolderNames = new String[] { "/region/", "/DIM-1/region/", "/DIM1/region/" }; - List fileList; - for(int i = 0; i < 3; ++i) { - vf = WorldsDB.newVFile(worldFolder, srcFolderNames[i]); - fileList = vf.listFiles(true); - String regionFolder = folderName + dstFolderNames[i]; - logger.info("Converting chunks in \"{}\" as MCA to \"{}\"...", vf.getPath(), regionFolder); - Map regionFiles = new HashMap<>(); - for(int k = 0, l = fileList.size(); k < l; ++k) { - VFile2 chunkFile = fileList.get(k); - NBTTagCompound chunkNBT; - NBTTagCompound chunkLevel; - try { - b = chunkFile.getAllBytes(); - chunkNBT = CompressedStreamTools.readCompressed(new EaglerInputStream(b)); - if(!chunkNBT.hasKey("Level", 10)) { - throw new IOException("Chunk is missing level data!"); - } - chunkLevel = chunkNBT.getCompoundTag("Level"); - }catch(IOException t) { - logger.error("Could not read chunk: {}", chunkFile.getPath()); - logger.error(t); - continue; - } - int chunkX = chunkLevel.getInteger("xPos"); - int chunkZ = chunkLevel.getInteger("zPos"); - String regionFileName = "r." + (chunkX >> 5) + "." + (chunkZ >> 5) + ".mca"; - RegionFile rf = regionFiles.get(regionFileName); - if(rf == null) { - rf = new RegionFile(new RandomAccessMemoryFile(new byte[65536], 0)); - regionFiles.put(regionFileName, rf); - } - try(DataOutputStream dos = rf.getChunkDataOutputStream(chunkX & 31, chunkZ & 31)) { - CompressedStreamTools.write(chunkNBT, dos); - }catch(IOException t) { - logger.error("Could not write chunk to {}: {}", regionFileName, chunkFile.getPath()); - logger.error(t); - continue; - } - prog += b.length; - if (prog - lastProgUpdate > 25000) { - lastProgUpdate = prog; - EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); - } - } - if(regionFiles.isEmpty()) { - logger.info("No region files were generated"); - continue; - } - for(Entry etr : regionFiles.entrySet()) { - String regionPath = regionFolder + etr.getKey(); - logger.info("Writing region file: {}", regionPath); - zos.putNextEntry(new ZipEntry(regionPath)); - zos.write(etr.getValue().getFile().getByteArray()); - } - } - logger.info("Copying extra world data..."); - fileList = WorldsDB.newVFile(worldFolder, "data").listFiles(false); - for(int k = 0, l = fileList.size(); k < l; ++k) { - VFile2 dataFile = fileList.get(k); - zos.putNextEntry(new ZipEntry(folderName + "/data/" + dataFile.getName())); - b = dataFile.getAllBytes(); - zos.write(b); - prog += b.length; - if (prog - lastProgUpdate > 25000) { - lastProgUpdate = prog; - EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); - } - } - fileList = WorldsDB.newVFile(worldFolder, "players").listFiles(false); - for(int k = 0, l = fileList.size(); k < l; ++k) { - VFile2 dataFile = fileList.get(k); - zos.putNextEntry(new ZipEntry(folderName + "/players/" + dataFile.getName())); - b = dataFile.getAllBytes(); - zos.write(b); - prog += b.length; - if (prog - lastProgUpdate > 25000) { - lastProgUpdate = prog; - EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); - } - } - fileList = WorldsDB.newVFile(worldFolder, "eagler/skulls").listFiles(false); - for(int k = 0, l = fileList.size(); k < l; ++k) { - VFile2 dataFile = fileList.get(k); - zos.putNextEntry(new ZipEntry(folderName + "/eagler/skulls/" + dataFile.getName())); - b = dataFile.getAllBytes(); - zos.write(b); - prog += b.length; - if (prog - lastProgUpdate > 25000) { - lastProgUpdate = prog; - EaglerIntegratedServerWorker.sendProgress("singleplayer.busy.exporting.2", prog); - } - } - } - logger.info("World directory \"{}\" was successfully exported as MCA", worldFolder.getPath()); - return bao.toByteArray(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/CustomSkullData.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/CustomSkullData.java index b37a5562..9852e1b4 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/CustomSkullData.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/CustomSkullData.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.SkinPacketVersionCache /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,7 +32,7 @@ public class CustomSkullData { public CustomSkullData(String skinURL, byte[] skinData) { this.skinURL = skinURL; this.lastHit = EagRuntime.steadyTimeMillis(); - if(skinData.length != 16384) { + if (skinData.length != 16384) { byte[] fixed = new byte[16384]; System.arraycopy(skinData, 0, fixed, 0, skinData.length > fixed.length ? fixed.length : skinData.length); skinData = fixed; @@ -40,11 +41,12 @@ public class CustomSkullData { } public byte[] getFullSkin() { - return ((SPacketOtherSkinCustomV3EAG)skinData.getV3()).customSkin; + return ((SPacketOtherSkinCustomV3EAG) skinData.getV3()).customSkin; } public GameMessagePacket getSkinPacket(EaglercraftUUID uuid, GamePluginMessageProtocol protocol) { - return SkinPacketVersionCache.rewriteUUID(skinData.get(protocol), uuid.getMostSignificantBits(), uuid.getLeastSignificantBits()); + return SkinPacketVersionCache.rewriteUUID(skinData.get(protocol), uuid.getMostSignificantBits(), + uuid.getLeastSignificantBits()); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapePackets.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapePackets.java index 6df2b5c3..b2cfaa0c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapePackets.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapePackets.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCape /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,21 +28,23 @@ public class IntegratedCapePackets { public static final int PACKET_MY_CAPE_PRESET = 0x01; public static final int PACKET_MY_CAPE_CUSTOM = 0x02; - public static void registerEaglerPlayer(EaglercraftUUID clientUUID, byte[] bs, IntegratedCapeService capeService) throws IOException { - if(bs.length == 0) { + public static void registerEaglerPlayer(EaglercraftUUID clientUUID, byte[] bs, IntegratedCapeService capeService) + throws IOException { + if (bs.length == 0) { throw new IOException("Zero-length packet recieved"); } GameMessagePacket generatedPacket; - int packetType = (int)bs[0] & 0xFF; - switch(packetType) { + int packetType = (int) bs[0] & 0xFF; + switch (packetType) { case PACKET_MY_CAPE_PRESET: - if(bs.length != 5) { + if (bs.length != 5) { throw new IOException("Invalid length " + bs.length + " for preset cape packet"); } - generatedPacket = new SPacketOtherCapePresetEAG(clientUUID.msb, clientUUID.lsb, (bs[1] << 24) | (bs[2] << 16) | (bs[3] << 8) | (bs[4] & 0xFF)); + generatedPacket = new SPacketOtherCapePresetEAG(clientUUID.msb, clientUUID.lsb, + (bs[1] << 24) | (bs[2] << 16) | (bs[3] << 8) | (bs[4] & 0xFF)); break; case PACKET_MY_CAPE_CUSTOM: - if(bs.length != 1174) { + if (bs.length != 1174) { throw new IOException("Invalid length " + bs.length + " for custom cape packet"); } byte[] capePixels = new byte[bs.length - 1]; @@ -55,7 +58,8 @@ public class IntegratedCapePackets { } public static void registerEaglerPlayerFallback(EaglercraftUUID clientUUID, IntegratedCapeService capeService) { - capeService.registerEaglercraftPlayer(clientUUID, new SPacketOtherCapePresetEAG(clientUUID.msb, clientUUID.lsb, 0)); + capeService.registerEaglercraftPlayer(clientUUID, + new SPacketOtherCapePresetEAG(clientUUID.msb, clientUUID.lsb, 0)); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapeService.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapeService.java index 7e17e673..46c71e2f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapeService.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedCapeService.java @@ -14,14 +14,15 @@ import net.minecraft.entity.player.EntityPlayerMP; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,6 +35,14 @@ public class IntegratedCapeService { private final Map capesCache = new HashMap<>(); + public void processGetOtherCape(EaglercraftUUID searchUUID, EntityPlayerMP sender) { + GameMessagePacket maybeCape = capesCache.get(searchUUID); + if (maybeCape == null) { + maybeCape = new SPacketOtherCapePresetEAG(searchUUID.msb, searchUUID.lsb, 0); + } + sender.playerNetServerHandler.sendEaglerMessage(maybeCape); + } + public void processLoginPacket(byte[] packetData, EntityPlayerMP sender) { try { IntegratedCapePackets.registerEaglerPlayer(sender.getUniqueID(), packetData, this); @@ -48,16 +57,8 @@ public class IntegratedCapeService { capesCache.put(playerUUID, capePacket); } - public void processGetOtherCape(EaglercraftUUID searchUUID, EntityPlayerMP sender) { - GameMessagePacket maybeCape = capesCache.get(searchUUID); - if(maybeCape == null) { - maybeCape = new SPacketOtherCapePresetEAG(searchUUID.msb, searchUUID.lsb, 0); - } - sender.playerNetServerHandler.sendEaglerMessage(maybeCape); - } - public void unregisterPlayer(EaglercraftUUID playerUUID) { - synchronized(capesCache) { + synchronized (capesCache) { capesCache.remove(playerUUID); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinPackets.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinPackets.java index 67da9f9d..b4e52e31 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinPackets.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinPackets.java @@ -4,20 +4,23 @@ import java.io.IOException; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinPresetEAG; import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.SkinPacketVersionCache; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,88 +29,15 @@ public class IntegratedSkinPackets { public static final int PACKET_MY_SKIN_PRESET = 0x01; public static final int PACKET_MY_SKIN_CUSTOM = 0x02; - - public static void registerEaglerPlayer(EaglercraftUUID clientUUID, byte[] bs, IntegratedSkinService skinService, - int protocolVers) throws IOException { - if(bs.length == 0) { - throw new IOException("Zero-length packet recieved"); - } - GameMessagePacket generatedPacketV3 = null; - GameMessagePacket generatedPacketV4 = null; - int skinModel = -1; - int packetType = (int)bs[0] & 0xFF; - switch(packetType) { - case PACKET_MY_SKIN_PRESET: - if(bs.length != 5) { - throw new IOException("Invalid length " + bs.length + " for preset skin packet"); - } - generatedPacketV3 = generatedPacketV4 = new SPacketOtherSkinPresetEAG(clientUUID.msb, clientUUID.lsb, - (bs[1] << 24) | (bs[2] << 16) | (bs[3] << 8) | (bs[4] & 0xFF)); - break; - case PACKET_MY_SKIN_CUSTOM: - if(protocolVers <= 3) { - byte[] pixels = new byte[16384]; - if(bs.length != 2 + pixels.length) { - throw new IOException("Invalid length " + bs.length + " for custom skin packet"); - } - setAlphaForChestV3(pixels); - System.arraycopy(bs, 2, pixels, 0, pixels.length); - generatedPacketV3 = new SPacketOtherSkinCustomV3EAG(clientUUID.msb, clientUUID.lsb, (skinModel = (int)bs[1] & 0xFF), pixels); - }else { - byte[] pixels = new byte[12288]; - if(bs.length != 2 + pixels.length) { - throw new IOException("Invalid length " + bs.length + " for custom skin packet"); - } - setAlphaForChestV4(pixels); - System.arraycopy(bs, 2, pixels, 0, pixels.length); - generatedPacketV4 = new SPacketOtherSkinCustomV4EAG(clientUUID.msb, clientUUID.lsb, (skinModel = (int)bs[1] & 0xFF), pixels); - } - break; - default: - throw new IOException("Unknown skin packet type: " + packetType); - } - skinService.processPacketPlayerSkin(clientUUID, new SkinPacketVersionCache(generatedPacketV3, generatedPacketV4), skinModel); - } - - public static void registerEaglerPlayerFallback(EaglercraftUUID clientUUID, IntegratedSkinService skinService) throws IOException { - int skinModel = (clientUUID.hashCode() & 1) != 0 ? 1 : 0; - skinService.processPacketPlayerSkin(clientUUID, SkinPacketVersionCache.createPreset(clientUUID.msb, clientUUID.lsb, skinModel), skinModel); - } - - public static void setAlphaForChestV3(byte[] skin64x64) { - if(skin64x64.length != 16384) { - throw new IllegalArgumentException("Skin is not 64x64!"); - } - for(int y = 20; y < 32; ++y) { - for(int x = 16; x < 40; ++x) { - skin64x64[(y << 8) | (x << 2)] = (byte)0xFF; - } - } - } - - public static void setAlphaForChestV4(byte[] skin64x64) { - if(skin64x64.length != 12288) { - throw new IllegalArgumentException("Skin is not 64x64!"); - } - for(int y = 20; y < 32; ++y) { - for(int x = 16; x < 40; ++x) { - skin64x64[((y << 6) | x) * 3] |= 0x80; - } - } - } - - public static SPacketOtherSkinPresetEAG makePresetResponse(EaglercraftUUID uuid) { - return new SPacketOtherSkinPresetEAG(uuid.msb, uuid.lsb, (uuid.hashCode() & 1) != 0 ? 1 : 0); - } - + public static byte[] asciiString(String string) { byte[] str = new byte[string.length()]; - for(int i = 0; i < str.length; ++i) { - str[i] = (byte)string.charAt(i); + for (int i = 0; i < str.length; ++i) { + str[i] = (byte) string.charAt(i); } return str; } - + public static EaglercraftUUID createEaglerURLSkinUUID(String skinUrl) { return EaglercraftUUID.nameUUIDFromBytes(asciiString("EaglercraftSkinURL:" + skinUrl)); } @@ -116,4 +46,82 @@ public class IntegratedSkinPackets { return "slim".equalsIgnoreCase(modelName) ? 1 : 0; } + public static SPacketOtherSkinPresetEAG makePresetResponse(EaglercraftUUID uuid) { + return new SPacketOtherSkinPresetEAG(uuid.msb, uuid.lsb, (uuid.hashCode() & 1) != 0 ? 1 : 0); + } + + public static void registerEaglerPlayer(EaglercraftUUID clientUUID, byte[] bs, IntegratedSkinService skinService, + int protocolVers) throws IOException { + if (bs.length == 0) { + throw new IOException("Zero-length packet recieved"); + } + GameMessagePacket generatedPacketV3 = null; + GameMessagePacket generatedPacketV4 = null; + int skinModel = -1; + int packetType = (int) bs[0] & 0xFF; + switch (packetType) { + case PACKET_MY_SKIN_PRESET: + if (bs.length != 5) { + throw new IOException("Invalid length " + bs.length + " for preset skin packet"); + } + generatedPacketV3 = generatedPacketV4 = new SPacketOtherSkinPresetEAG(clientUUID.msb, clientUUID.lsb, + (bs[1] << 24) | (bs[2] << 16) | (bs[3] << 8) | (bs[4] & 0xFF)); + break; + case PACKET_MY_SKIN_CUSTOM: + if (protocolVers <= 3) { + byte[] pixels = new byte[16384]; + if (bs.length != 2 + pixels.length) { + throw new IOException("Invalid length " + bs.length + " for custom skin packet"); + } + setAlphaForChestV3(pixels); + System.arraycopy(bs, 2, pixels, 0, pixels.length); + generatedPacketV3 = new SPacketOtherSkinCustomV3EAG(clientUUID.msb, clientUUID.lsb, + (skinModel = (int) bs[1] & 0xFF), pixels); + } else { + byte[] pixels = new byte[12288]; + if (bs.length != 2 + pixels.length) { + throw new IOException("Invalid length " + bs.length + " for custom skin packet"); + } + setAlphaForChestV4(pixels); + System.arraycopy(bs, 2, pixels, 0, pixels.length); + generatedPacketV4 = new SPacketOtherSkinCustomV4EAG(clientUUID.msb, clientUUID.lsb, + (skinModel = (int) bs[1] & 0xFF), pixels); + } + break; + default: + throw new IOException("Unknown skin packet type: " + packetType); + } + skinService.processPacketPlayerSkin(clientUUID, + new SkinPacketVersionCache(generatedPacketV3, generatedPacketV4), skinModel); + } + + public static void registerEaglerPlayerFallback(EaglercraftUUID clientUUID, IntegratedSkinService skinService) + throws IOException { + int skinModel = (clientUUID.hashCode() & 1) != 0 ? 1 : 0; + skinService.processPacketPlayerSkin(clientUUID, + SkinPacketVersionCache.createPreset(clientUUID.msb, clientUUID.lsb, skinModel), skinModel); + } + + public static void setAlphaForChestV3(byte[] skin64x64) { + if (skin64x64.length != 16384) { + throw new IllegalArgumentException("Skin is not 64x64!"); + } + for (int y = 20; y < 32; ++y) { + for (int x = 16; x < 40; ++x) { + skin64x64[(y << 8) | (x << 2)] = (byte) 0xFF; + } + } + } + + public static void setAlphaForChestV4(byte[] skin64x64) { + if (skin64x64.length != 12288) { + throw new IllegalArgumentException("Skin is not 64x64!"); + } + for (int y = 20; y < 32; ++y) { + for (int x = 16; x < 40; ++x) { + skin64x64[((y << 6) | x) * 3] |= 0x80; + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinService.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinService.java index 0aa1ce1c..1806ae0a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinService.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/skins/IntegratedSkinService.java @@ -20,23 +20,24 @@ import net.lax1dude.eaglercraft.v1_8.sp.server.WorldsDB; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; -import net.minecraft.util.ChatComponentTranslation; -import net.minecraft.util.EnumChatFormatting; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.nbt.NBTTagString; +import net.minecraft.util.ChatComponentTranslation; +import net.minecraft.util.EnumChatFormatting; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -48,11 +49,11 @@ public class IntegratedSkinService { public static final byte[] skullNotFoundTexture = new byte[4096]; static { - for(int y = 0; y < 16; ++y) { - for(int x = 0; x < 64; ++x) { + for (int y = 0; y < 16; ++y) { + for (int x = 0; x < 64; ++x) { int i = (y << 8) | (x << 2); - byte j = ((x + y) & 1) == 1 ? (byte)255 : 0; - skullNotFoundTexture[i] = (byte)255; + byte j = ((x + y) & 1) == 1 ? (byte) 255 : 0; + skullNotFoundTexture[i] = (byte) 255; skullNotFoundTexture[i + 1] = j; skullNotFoundTexture[i + 2] = 0; skullNotFoundTexture[i + 3] = j; @@ -60,10 +61,12 @@ public class IntegratedSkinService { } } - public final VFile2 skullsDirectory; + private static final String hex = "0123456789abcdef"; - public final Map playerSkins = new HashMap<>(); - public final Map customSkulls = new HashMap<>(); + public final VFile2 skullsDirectory; + public final Map playerSkins = new HashMap<>(); + + public final Map customSkulls = new HashMap<>(); private long lastFlush = 0l; @@ -71,6 +74,50 @@ public class IntegratedSkinService { this.skullsDirectory = skullsDirectory; } + public void flushCache() { + long cur = EagRuntime.steadyTimeMillis(); + if (cur - lastFlush > 300000l) { + lastFlush = cur; + Iterator customSkullsItr = customSkulls.values().iterator(); + while (customSkullsItr.hasNext()) { + if (cur - customSkullsItr.next().lastHit > 900000l) { + customSkullsItr.remove(); + } + } + } + } + + public String installNewSkull(byte[] skullData) { + // set to 16384 to save a full 64x64 skin + if (skullData.length > 4096) { + byte[] tmp = skullData; + skullData = new byte[4096]; + System.arraycopy(tmp, 0, skullData, 0, 4096); + } + SHA1Digest sha = new SHA1Digest(); + sha.update(skullData, 0, skullData.length); + byte[] hash = new byte[20]; + sha.doFinal(hash, 0); + char[] hashText = new char[40]; + for (int i = 0; i < 20; ++i) { + hashText[i << 1] = hex.charAt((hash[i] & 0xF0) >> 4); + hashText[(i << 1) + 1] = hex.charAt(hash[i] & 0x0F); + } + String str = "skin-" + new String(hashText) + ".bmp"; + customSkulls.put(str, new CustomSkullData(str, skullData)); + WorldsDB.newVFile(skullsDirectory, str).setAllBytes(skullData); + return str; + } + + private CustomSkullData loadCustomSkull(String urlStr) { + byte[] data = WorldsDB.newVFile(skullsDirectory, urlStr).getAllBytes(); + if (data == null) { + return new CustomSkullData(urlStr, skullNotFoundTexture); + } else { + return new CustomSkullData(urlStr, data); + } + } + public void processLoginPacket(byte[] packetData, EntityPlayerMP sender, int protocolVers) { try { IntegratedSkinPackets.registerEaglerPlayer(sender.getUniqueID(), packetData, this, protocolVers); @@ -84,9 +131,9 @@ public class IntegratedSkinService { public void processPacketGetOtherSkin(EaglercraftUUID searchUUID, EntityPlayerMP sender) { SkinPacketVersionCache playerSkin = playerSkins.get(searchUUID); GameMessagePacket toSend = null; - if(playerSkin != null) { + if (playerSkin != null) { toSend = playerSkin.get(sender.playerNetServerHandler.getEaglerMessageProtocol()); - }else { + } else { toSend = IntegratedSkinPackets.makePresetResponse(searchUUID); } sender.playerNetServerHandler.sendEaglerMessage(toSend); @@ -95,17 +142,17 @@ public class IntegratedSkinService { public void processPacketGetOtherSkin(EaglercraftUUID searchUUID, String urlStr, EntityPlayerMP sender) { urlStr = urlStr.toLowerCase(); GameMessagePacket playerSkin; - if(!urlStr.startsWith("eagler://")) { + if (!urlStr.startsWith("eagler://")) { playerSkin = new SPacketOtherSkinPresetEAG(searchUUID.msb, searchUUID.lsb, 0); - }else { + } else { urlStr = urlStr.substring(9); - if(urlStr.contains(VFile2.pathSeperator)) { + if (urlStr.contains(VFile2.pathSeperator)) { playerSkin = new SPacketOtherSkinPresetEAG(searchUUID.msb, searchUUID.lsb, 0); - }else { + } else { CustomSkullData sk = customSkulls.get(urlStr); - if(sk == null) { + if (sk == null) { customSkulls.put(urlStr, sk = loadCustomSkull(urlStr)); - }else { + } else { sk.lastHit = EagRuntime.steadyTimeMillis(); } playerSkin = sk.getSkinPacket(searchUUID, sender.playerNetServerHandler.getEaglerMessageProtocol()); @@ -114,16 +161,8 @@ public class IntegratedSkinService { sender.playerNetServerHandler.sendEaglerMessage(playerSkin); } - public void processPacketPlayerSkin(EaglercraftUUID clientUUID, SkinPacketVersionCache generatedPacket, int skinModel) { - playerSkins.put(clientUUID, generatedPacket); - } - - public void unregisterPlayer(EaglercraftUUID clientUUID) { - playerSkins.remove(clientUUID); - } - public void processPacketInstallNewSkin(byte[] skullData, EntityPlayerMP sender) { - if(!sender.canCommandSenderUseCommand(2, "give")) { + if (!sender.canCommandSenderUseCommand(2, "give")) { ChatComponentTranslation cc = new ChatComponentTranslation("command.skull.nopermission"); cc.getChatStyle().setColor(EnumChatFormatting.RED); sender.addChatMessage(cc); @@ -133,12 +172,15 @@ public class IntegratedSkinService { NBTTagCompound rootTagCompound = new NBTTagCompound(); NBTTagCompound ownerTagCompound = new NBTTagCompound(); ownerTagCompound.setString("Name", "Eagler"); - ownerTagCompound.setString("Id", EaglercraftUUID.nameUUIDFromBytes((("EaglerSkullUUID:" + fileName).getBytes(StandardCharsets.UTF_8))).toString()); + ownerTagCompound.setString("Id", EaglercraftUUID + .nameUUIDFromBytes((("EaglerSkullUUID:" + fileName).getBytes(StandardCharsets.UTF_8))).toString()); NBTTagCompound propertiesTagCompound = new NBTTagCompound(); NBTTagList texturesTagList = new NBTTagList(); NBTTagCompound texturesTagCompound = new NBTTagCompound(); - String texturesProp = "{\"textures\":{\"SKIN\":{\"url\":\"" + fileName + "\",\"metadata\":{\"model\":\"default\"}}}}"; - texturesTagCompound.setString("Value", Base64.encodeBase64String(texturesProp.getBytes(StandardCharsets.UTF_8))); + String texturesProp = "{\"textures\":{\"SKIN\":{\"url\":\"" + fileName + + "\",\"metadata\":{\"model\":\"default\"}}}}"; + texturesTagCompound.setString("Value", + Base64.encodeBase64String(texturesProp.getBytes(StandardCharsets.UTF_8))); texturesTagList.appendTag(texturesTagCompound); propertiesTagCompound.setTag("textures", texturesTagList); ownerTagCompound.setTag("Properties", propertiesTagCompound); @@ -146,7 +188,8 @@ public class IntegratedSkinService { NBTTagCompound displayTagCompound = new NBTTagCompound(); displayTagCompound.setString("Name", EnumChatFormatting.RESET + "Custom Eaglercraft Skull"); NBTTagList loreList = new NBTTagList(); - loreList.appendTag(new NBTTagString(EnumChatFormatting.GRAY + (fileName.length() > 24 ? (fileName.substring(0, 22) + "...") : fileName))); + loreList.appendTag(new NBTTagString( + EnumChatFormatting.GRAY + (fileName.length() > 24 ? (fileName.substring(0, 22) + "...") : fileName))); displayTagCompound.setTag("Lore", loreList); rootTagCompound.setTag("display", displayTagCompound); ItemStack stack = new ItemStack(Items.skull, 1, 3); @@ -154,56 +197,18 @@ public class IntegratedSkinService { boolean flag = sender.inventory.addItemStackToInventory(stack); if (flag) { sender.worldObj.playSoundAtEntity(sender, "random.pop", 0.2F, - ((sender.getRNG().nextFloat() - sender.getRNG().nextFloat()) * 0.7F + 1.0F) - * 2.0F); + ((sender.getRNG().nextFloat() - sender.getRNG().nextFloat()) * 0.7F + 1.0F) * 2.0F); sender.inventoryContainer.detectAndSendChanges(); } sender.addChatMessage(new ChatComponentTranslation("command.skull.feedback", fileName)); } - private static final String hex = "0123456789abcdef"; - - public String installNewSkull(byte[] skullData) { - // set to 16384 to save a full 64x64 skin - if(skullData.length > 4096) { - byte[] tmp = skullData; - skullData = new byte[4096]; - System.arraycopy(tmp, 0, skullData, 0, 4096); - } - SHA1Digest sha = new SHA1Digest(); - sha.update(skullData, 0, skullData.length); - byte[] hash = new byte[20]; - sha.doFinal(hash, 0); - char[] hashText = new char[40]; - for(int i = 0; i < 20; ++i) { - hashText[i << 1] = hex.charAt((hash[i] & 0xF0) >> 4); - hashText[(i << 1) + 1] = hex.charAt(hash[i] & 0x0F); - } - String str = "skin-" + new String(hashText) + ".bmp"; - customSkulls.put(str, new CustomSkullData(str, skullData)); - WorldsDB.newVFile(skullsDirectory, str).setAllBytes(skullData); - return str; + public void processPacketPlayerSkin(EaglercraftUUID clientUUID, SkinPacketVersionCache generatedPacket, + int skinModel) { + playerSkins.put(clientUUID, generatedPacket); } - private CustomSkullData loadCustomSkull(String urlStr) { - byte[] data = WorldsDB.newVFile(skullsDirectory, urlStr).getAllBytes(); - if(data == null) { - return new CustomSkullData(urlStr, skullNotFoundTexture); - }else { - return new CustomSkullData(urlStr, data); - } - } - - public void flushCache() { - long cur = EagRuntime.steadyTimeMillis(); - if(cur - lastFlush > 300000l) { - lastFlush = cur; - Iterator customSkullsItr = customSkulls.values().iterator(); - while(customSkullsItr.hasNext()) { - if(cur - customSkullsItr.next().lastHit > 900000l) { - customSkullsItr.remove(); - } - } - } + public void unregisterPlayer(EaglercraftUUID clientUUID) { + playerSkins.remove(clientUUID); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/IntegratedServerPlayerNetworkManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/IntegratedServerPlayerNetworkManager.java index 419c69b6..bad35950 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/IntegratedServerPlayerNetworkManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/IntegratedServerPlayerNetworkManager.java @@ -17,6 +17,7 @@ import net.lax1dude.eaglercraft.v1_8.netty.Unpooled; import net.lax1dude.eaglercraft.v1_8.socket.CompressionNotSupportedException; import net.lax1dude.eaglercraft.v1_8.sp.SingleplayerServerController; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerIntegratedServerWorker; +import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplayer; import net.minecraft.network.EnumConnectionState; import net.minecraft.network.EnumPacketDirection; import net.minecraft.network.INetHandler; @@ -25,96 +26,105 @@ import net.minecraft.network.PacketBuffer; import net.minecraft.util.ChatComponentText; import net.minecraft.util.IChatComponent; import net.minecraft.util.ITickable; -import net.lax1dude.eaglercraft.v1_8.sp.server.internal.ServerPlatformSingleplayer; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IntegratedServerPlayerNetworkManager { + private static PacketBuffer temporaryBuffer; + private static EaglerOutputStream temporaryOutputStream; + public static final int fragmentSize = 0xFF00; + public static final int compressionThreshold = 1024; + public static final Logger logger = LogManager.getLogger("NetworkManager"); private INetHandler nethandler = null; public final String playerChannel; private EnumConnectionState packetState = EnumConnectionState.HANDSHAKING; - private static PacketBuffer temporaryBuffer; - private static EaglerOutputStream temporaryOutputStream; private int debugPacketCounter = 0; - private byte[][] recievedPacketBuffer = new byte[16384][]; - private int recievedPacketBufferCounter = 0; - private final boolean enableSendCompression; + private byte[][] recievedPacketBuffer = new byte[16384][]; + + private int recievedPacketBufferCounter = 0; + + private final boolean enableSendCompression; private boolean firstPacket = true; private List fragmentedPacket = new ArrayList<>(); - public static final int fragmentSize = 0xFF00; - public static final int compressionThreshold = 1024; - - public static final Logger logger = LogManager.getLogger("NetworkManager"); - public IntegratedServerPlayerNetworkManager(String playerChannel) { - if(temporaryBuffer == null) { + if (temporaryBuffer == null) { temporaryBuffer = new PacketBuffer(Unpooled.buffer(0x1FFFF)); } this.playerChannel = playerChannel; this.enableSendCompression = !SingleplayerServerController.PLAYER_CHANNEL.equals(playerChannel); - if(this.enableSendCompression) { - if(temporaryOutputStream == null) { + if (this.enableSendCompression) { + if (temporaryOutputStream == null) { temporaryOutputStream = new EaglerOutputStream(16386); } } } - - public void connect() { - fragmentedPacket.clear(); - firstPacket = true; - } - - public EnumEaglerConnectionState getConnectStatus() { - return EaglerIntegratedServerWorker.getChannelExists(playerChannel) ? EnumEaglerConnectionState.CONNECTED : EnumEaglerConnectionState.CLOSED; - } - - public void closeChannel(IChatComponent reason) { - EaglerIntegratedServerWorker.closeChannel(playerChannel); - if(nethandler != null) { - nethandler.onDisconnect(reason); - } - } - - public void setConnectionState(EnumConnectionState state) { - packetState = state; - } public void addRecievedPacket(byte[] next) { - if(recievedPacketBufferCounter < recievedPacketBuffer.length - 1) { + if (recievedPacketBufferCounter < recievedPacketBuffer.length - 1) { recievedPacketBuffer[recievedPacketBufferCounter++] = next; - }else { + } else { logger.error("Dropping packets on recievedPacketBuffer for channel \"{}\"! (overflow)", playerChannel); } } - public void processReceivedPackets() { - if(nethandler == null) return; + public void closeChannel(IChatComponent reason) { + EaglerIntegratedServerWorker.closeChannel(playerChannel); + if (nethandler != null) { + nethandler.onDisconnect(reason); + } + } - - for(int i = 0; i < recievedPacketBufferCounter; ++i) { + public void connect() { + fragmentedPacket.clear(); + firstPacket = true; + } + + public EnumEaglerConnectionState getConnectStatus() { + return EaglerIntegratedServerWorker.getChannelExists(playerChannel) ? EnumEaglerConnectionState.CONNECTED + : EnumEaglerConnectionState.CLOSED; + } + + public boolean getIsencrypted() { + return false; + } + + public boolean isChannelOpen() { + return getConnectStatus() == EnumEaglerConnectionState.CONNECTED; + } + + public boolean isLocalChannel() { + return false; + } + + public void processReceivedPackets() { + if (nethandler == null) + return; + + for (int i = 0; i < recievedPacketBufferCounter; ++i) { byte[] data = recievedPacketBuffer[i]; byte[] fullData; - if(enableSendCompression) { - if(firstPacket) { - if(data.length > 2 && data[0] == (byte)0x02 && data[1] == (byte)0x3D) { + if (enableSendCompression) { + if (firstPacket) { + if (data.length > 2 && data[0] == (byte) 0x02 && data[1] == (byte) 0x3D) { EaglerOutputStream kickPacketBAO = new EaglerOutputStream(); try { DataOutputStream kickDAO = new DataOutputStream(kickPacketBAO); @@ -123,14 +133,16 @@ public class IntegratedServerPlayerNetworkManager { String msg = "This is an EaglercraftX 1.8 LAN world!"; kickDAO.write(0x00); kickDAO.write(msg.length()); - for(int j = 0, l = msg.length(); j < l; ++j) { + for (int j = 0, l = msg.length(); j < l; ++j) { kickDAO.writeChar(msg.charAt(j)); } - }catch(IOException ex) { + } catch (IOException ex) { throw new RuntimeException(ex); } - ServerPlatformSingleplayer.sendPacket(new IPCPacketData(playerChannel, kickPacketBAO.toByteArray())); - closeChannel(new ChatComponentText("Recieved unsuppoorted connection from an Eaglercraft 1.5.2 client!")); + ServerPlatformSingleplayer + .sendPacket(new IPCPacketData(playerChannel, kickPacketBAO.toByteArray())); + closeChannel(new ChatComponentText( + "Recieved unsuppoorted connection from an Eaglercraft 1.5.2 client!")); firstPacket = false; recievedPacketBufferCounter = 0; return; @@ -138,19 +150,19 @@ public class IntegratedServerPlayerNetworkManager { firstPacket = false; } if (data[0] == 0) { - if(fragmentedPacket.isEmpty()) { + if (fragmentedPacket.isEmpty()) { fullData = new byte[data.length - 1]; System.arraycopy(data, 1, fullData, 0, fullData.length); - }else { + } else { fragmentedPacket.add(data); int len = 0; int fragCount = fragmentedPacket.size(); - for(int j = 0; j < fragCount; ++j) { + for (int j = 0; j < fragCount; ++j) { len += fragmentedPacket.get(j).length - 1; } fullData = new byte[len]; len = 0; - for(int j = 0; j < fragCount; ++j) { + for (int j = 0; j < fragCount; ++j) { byte[] f = fragmentedPacket.get(j); System.arraycopy(f, 1, fullData, len, f.length - 1); len += f.length - 1; @@ -161,14 +173,14 @@ public class IntegratedServerPlayerNetworkManager { fragmentedPacket.add(data); continue; } else { - logger.error("Recieved {} byte fragment of unknown type: {}", data.length, ((int)data[0] & 0xFF)); + logger.error("Recieved {} byte fragment of unknown type: {}", data.length, ((int) data[0] & 0xFF)); continue; } - - }else { + + } else { fullData = data; } - + recievedPacketBuffer[i] = null; ++debugPacketCounter; try { @@ -176,33 +188,36 @@ public class IntegratedServerPlayerNetworkManager { nettyBuffer.writerIndex(fullData.length); PacketBuffer input = new PacketBuffer(nettyBuffer); int pktId = input.readVarIntFromBuffer(); - + Packet pkt; try { pkt = packetState.getPacket(EnumPacketDirection.SERVERBOUND, pktId); - }catch(IllegalAccessException | InstantiationException ex) { + } catch (IllegalAccessException | InstantiationException ex) { throw new IOException("Recieved a packet with type " + pktId + " which is invalid!"); } - if(pkt == null) { - throw new IOException("Recieved packet type " + pktId + " which is undefined in state " + packetState); + if (pkt == null) { + throw new IOException( + "Recieved packet type " + pktId + " which is undefined in state " + packetState); } try { pkt.readPacketData(input); - }catch(Throwable t) { + } catch (Throwable t) { throw new IOException("Failed to read packet type '" + pkt.getClass().getSimpleName() + "'", t); } - + try { pkt.processPacket(nethandler); - }catch(Throwable t) { - logger.error("Failed to process {}! It'll be skipped for debug purposes.", pkt.getClass().getSimpleName()); + } catch (Throwable t) { + logger.error("Failed to process {}! It'll be skipped for debug purposes.", + pkt.getClass().getSimpleName()); logger.error(t); } - - }catch(Throwable t) { - logger.error("Failed to process socket frame {}! It'll be skipped for debug purposes.", debugPacketCounter); + + } catch (Throwable t) { + logger.error("Failed to process socket frame {}! It'll be skipped for debug purposes.", + debugPacketCounter); logger.error(t); } } @@ -210,30 +225,30 @@ public class IntegratedServerPlayerNetworkManager { } public void sendPacket(Packet pkt) { - if(!isChannelOpen()) { + if (!isChannelOpen()) { return; } - + int i; try { i = packetState.getPacketId(EnumPacketDirection.CLIENTBOUND, pkt); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Incorrect packet for state: {}", pkt.getClass().getSimpleName()); return; } - + temporaryBuffer.clear(); temporaryBuffer.writeVarIntToBuffer(i); try { pkt.writePacketData(temporaryBuffer); - }catch(IOException ex) { + } catch (IOException ex) { logger.error("Failed to write packet {}!", pkt.getClass().getSimpleName()); return; } - + int len = temporaryBuffer.readableBytes(); - if(enableSendCompression) { - if(len > compressionThreshold) { + if (enableSendCompression) { + if (len > compressionThreshold) { temporaryOutputStream.reset(); byte[] compressedData; try { @@ -242,73 +257,67 @@ public class IntegratedServerPlayerNetworkManager { temporaryOutputStream.write((len >>> 16) & 0xFF); temporaryOutputStream.write((len >>> 8) & 0xFF); temporaryOutputStream.write(len & 0xFF); - try(OutputStream os = EaglerZLIB.newDeflaterOutputStream(temporaryOutputStream)) { + try (OutputStream os = EaglerZLIB.newDeflaterOutputStream(temporaryOutputStream)) { temporaryBuffer.readBytes(os, len); } compressedData = temporaryOutputStream.toByteArray(); - }catch(IOException ex) { + } catch (IOException ex) { logger.error("Failed to compress packet {}!", pkt.getClass().getSimpleName()); return; } - if(compressedData.length > fragmentSize) { + if (compressedData.length > fragmentSize) { int fragmentSizeN1 = fragmentSize - 1; for (int j = 1; j < compressedData.length; j += fragmentSizeN1) { - byte[] fragData = new byte[((j + fragmentSizeN1 > (compressedData.length - 1)) ? ((compressedData.length - 1) % fragmentSizeN1) : fragmentSizeN1) + 1]; + byte[] fragData = new byte[((j + fragmentSizeN1 > (compressedData.length - 1)) + ? ((compressedData.length - 1) % fragmentSizeN1) + : fragmentSizeN1) + 1]; System.arraycopy(compressedData, j, fragData, 1, fragData.length - 1); fragData[0] = (j + fragmentSizeN1 < compressedData.length) ? (byte) 1 : (byte) 2; ServerPlatformSingleplayer.sendPacket(new IPCPacketData(playerChannel, fragData)); } - }else { + } else { ServerPlatformSingleplayer.sendPacket(new IPCPacketData(playerChannel, compressedData)); } - }else { + } else { int fragmentSizeN1 = fragmentSize - 1; - if(len > fragmentSizeN1) { + if (len > fragmentSizeN1) { do { int readLen = len > fragmentSizeN1 ? fragmentSizeN1 : len; byte[] frag = new byte[readLen + 1]; temporaryBuffer.readBytes(frag, 1, readLen); - frag[0] = temporaryBuffer.readableBytes() == 0 ? (byte)0 : (byte)1; + frag[0] = temporaryBuffer.readableBytes() == 0 ? (byte) 0 : (byte) 1; ServerPlatformSingleplayer.sendPacket(new IPCPacketData(playerChannel, frag)); - }while((len = temporaryBuffer.readableBytes()) > 0); - }else { + } while ((len = temporaryBuffer.readableBytes()) > 0); + } else { byte[] bytes = new byte[len + 1]; bytes[0] = 0; temporaryBuffer.readBytes(bytes, 1, len); ServerPlatformSingleplayer.sendPacket(new IPCPacketData(playerChannel, bytes)); } } - }else { + } else { byte[] bytes = new byte[len]; temporaryBuffer.readBytes(bytes, 0, len); ServerPlatformSingleplayer.sendPacket(new IPCPacketData(playerChannel, bytes)); } } - - public void setNetHandler(INetHandler nethandler) { - this.nethandler = nethandler; - } - - public boolean isLocalChannel() { - return false; - } - - public boolean isChannelOpen() { - return getConnectStatus() == EnumEaglerConnectionState.CONNECTED; - } - - public boolean getIsencrypted() { - return false; - } public void setCompressionTreshold(int compressionTreshold) { throw new CompressionNotSupportedException(); } + public void setConnectionState(EnumConnectionState state) { + packetState = state; + } + + public void setNetHandler(INetHandler nethandler) { + this.nethandler = nethandler; + } + public void tick() { processReceivedPackets(); - if(nethandler instanceof ITickable) { - ((ITickable)nethandler).update(); + if (nethandler instanceof ITickable) { + ((ITickable) nethandler).update(); } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/NetHandlerHandshakeEagler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/NetHandlerHandshakeEagler.java index 29764cc0..b7a1a7a6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/NetHandlerHandshakeEagler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/NetHandlerHandshakeEagler.java @@ -9,14 +9,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,14 +27,15 @@ public class NetHandlerHandshakeEagler implements INetHandlerHandshakeServer { private final EaglerMinecraftServer mcServer; private final IntegratedServerPlayerNetworkManager networkManager; - public NetHandlerHandshakeEagler(EaglerMinecraftServer parMinecraftServer, IntegratedServerPlayerNetworkManager parNetworkManager) { + public NetHandlerHandshakeEagler(EaglerMinecraftServer parMinecraftServer, + IntegratedServerPlayerNetworkManager parNetworkManager) { this.mcServer = parMinecraftServer; this.networkManager = parNetworkManager; } @Override public void onDisconnect(IChatComponent var1) { - + } @Override diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV3MessageHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV3MessageHandler.java index cc6cf034..2341d07a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV3MessageHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV3MessageHandler.java @@ -2,7 +2,15 @@ package net.lax1dude.eaglercraft.v1_8.sp.server.socket.protocol; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessageHandler; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherCapeEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherSkinEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetSkinByURLEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketInstallSkinSPEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalConnectEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalRequestEAG; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; import net.minecraft.network.NetHandlerPlayServer; @@ -10,14 +18,15 @@ import net.minecraft.network.NetHandlerPlayServer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,19 +38,22 @@ public class ServerV3MessageHandler implements GameMessageHandler { public ServerV3MessageHandler(NetHandlerPlayServer netHandler) { this.netHandler = netHandler; - this.server = (EaglerMinecraftServer)netHandler.serverController; + this.server = (EaglerMinecraftServer) netHandler.serverController; } public void handleClient(CPacketGetOtherCapeEAG packet) { - server.getCapeService().processGetOtherCape(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + server.getCapeService().processGetOtherCape(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); } public void handleClient(CPacketGetOtherSkinEAG packet) { - server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); } public void handleClient(CPacketGetSkinByURLEAG packet) { - server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.url, netHandler.playerEntity); + server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + packet.url, netHandler.playerEntity); } public void handleClient(CPacketInstallSkinSPEAG packet) { @@ -50,24 +62,26 @@ public class ServerV3MessageHandler implements GameMessageHandler { public void handleClient(CPacketVoiceSignalConnectEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { + if (voiceSvc != null) { voiceSvc.handleVoiceSignalPacketTypeConnect(netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalDescEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeDesc(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.desc, netHandler.playerEntity); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeDesc(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + packet.desc, netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalDisconnectV3EAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - if(packet.isPeerType) { - voiceSvc.handleVoiceSignalPacketTypeDisconnectPeer(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); - }else { + if (voiceSvc != null) { + if (packet.isPeerType) { + voiceSvc.handleVoiceSignalPacketTypeDisconnectPeer( + new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + } else { voiceSvc.handleVoiceSignalPacketTypeDisconnect(netHandler.playerEntity); } } @@ -75,15 +89,17 @@ public class ServerV3MessageHandler implements GameMessageHandler { public void handleClient(CPacketVoiceSignalICEEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeICE(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.ice, netHandler.playerEntity); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeICE(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.ice, + netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalRequestEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeRequest(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeRequest(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV4MessageHandler.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV4MessageHandler.java index a8f993f8..7361094f 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV4MessageHandler.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/socket/protocol/ServerV4MessageHandler.java @@ -2,7 +2,17 @@ package net.lax1dude.eaglercraft.v1_8.sp.server.socket.protocol; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessageHandler; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherCapeEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherClientUUIDV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherSkinEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetSkinByURLEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketInstallSkinSPEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalConnectEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectPeerV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalRequestEAG; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherPlayerClientUUIDV4EAG; import net.lax1dude.eaglercraft.v1_8.sp.server.EaglerMinecraftServer; import net.lax1dude.eaglercraft.v1_8.sp.server.voice.IntegratedVoiceService; @@ -12,14 +22,15 @@ import net.minecraft.network.NetHandlerPlayServer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -31,19 +42,33 @@ public class ServerV4MessageHandler implements GameMessageHandler { public ServerV4MessageHandler(NetHandlerPlayServer netHandler) { this.netHandler = netHandler; - this.server = (EaglerMinecraftServer)netHandler.serverController; + this.server = (EaglerMinecraftServer) netHandler.serverController; } public void handleClient(CPacketGetOtherCapeEAG packet) { - server.getCapeService().processGetOtherCape(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + server.getCapeService().processGetOtherCape(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); + } + + public void handleClient(CPacketGetOtherClientUUIDV4EAG packet) { + EntityPlayerMP player = server.getConfigurationManager() + .getPlayerByUUID(new EaglercraftUUID(packet.playerUUIDMost, packet.playerUUIDLeast)); + if (player != null && player.clientBrandUUID != null) { + netHandler.sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(packet.requestId, + player.clientBrandUUID.msb, player.clientBrandUUID.lsb)); + } else { + netHandler.sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(packet.requestId, 0l, 0l)); + } } public void handleClient(CPacketGetOtherSkinEAG packet) { - server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); } public void handleClient(CPacketGetSkinByURLEAG packet) { - server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.url, netHandler.playerEntity); + server.getSkinService().processPacketGetOtherSkin(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + packet.url, netHandler.playerEntity); } public void handleClient(CPacketInstallSkinSPEAG packet) { @@ -52,52 +77,47 @@ public class ServerV4MessageHandler implements GameMessageHandler { public void handleClient(CPacketVoiceSignalConnectEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { + if (voiceSvc != null) { voiceSvc.handleVoiceSignalPacketTypeConnect(netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalDescEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeDesc(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.desc, netHandler.playerEntity); - } - } - - public void handleClient(CPacketVoiceSignalDisconnectV4EAG packet) { - IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeDisconnect(netHandler.playerEntity); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeDesc(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + packet.desc, netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalDisconnectPeerV4EAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeDisconnectPeer(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeDisconnectPeer(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); + } + } + + public void handleClient(CPacketVoiceSignalDisconnectV4EAG packet) { + IntegratedVoiceService voiceSvc = server.getVoiceService(); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeDisconnect(netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalICEEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeICE(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.ice, netHandler.playerEntity); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeICE(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), packet.ice, + netHandler.playerEntity); } } public void handleClient(CPacketVoiceSignalRequestEAG packet) { IntegratedVoiceService voiceSvc = server.getVoiceService(); - if(voiceSvc != null) { - voiceSvc.handleVoiceSignalPacketTypeRequest(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), netHandler.playerEntity); - } - } - - public void handleClient(CPacketGetOtherClientUUIDV4EAG packet) { - EntityPlayerMP player = server.getConfigurationManager().getPlayerByUUID(new EaglercraftUUID(packet.playerUUIDMost, packet.playerUUIDLeast)); - if(player != null && player.clientBrandUUID != null) { - netHandler.sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(packet.requestId, player.clientBrandUUID.msb, player.clientBrandUUID.lsb)); - }else { - netHandler.sendEaglerMessage(new SPacketOtherPlayerClientUUIDV4EAG(packet.requestId, 0l, 0l)); + if (voiceSvc != null) { + voiceSvc.handleVoiceSignalPacketTypeRequest(new EaglercraftUUID(packet.uuidMost, packet.uuidLeast), + netHandler.playerEntity); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/voice/IntegratedVoiceService.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/voice/IntegratedVoiceService.java index f6a802ac..7b29cba5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/voice/IntegratedVoiceService.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/server/voice/IntegratedVoiceService.java @@ -12,51 +12,46 @@ import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalAllowedEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDisconnectPeerEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalGlobalEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalICEEAG; import net.lax1dude.eaglercraft.v1_8.voice.ExpiringSet; import net.minecraft.entity.player.EntityPlayerMP; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class IntegratedVoiceService { - public static final Logger logger = LogManager.getLogger("IntegratedVoiceService"); - - private GameMessagePacket iceServersPacket; - - private final Map voicePlayers = new HashMap<>(); - private final Map> voiceRequests = new HashMap<>(); - private final Set voicePairs = new HashSet<>(); - - public IntegratedVoiceService(String[] iceServers) { - iceServersPacket = new SPacketVoiceSignalAllowedEAG(true, iceServers); - } - - public void changeICEServers(String[] iceServers) { - iceServersPacket = new SPacketVoiceSignalAllowedEAG(true, iceServers); - } - private static class VoicePair { private final EaglercraftUUID uuid1; private final EaglercraftUUID uuid2; - @Override - public int hashCode() { - return uuid1.hashCode() ^ uuid2.hashCode(); + private VoicePair(EaglercraftUUID uuid1, EaglercraftUUID uuid2) { + this.uuid1 = uuid1; + this.uuid2 = uuid2; + } + + private boolean anyEquals(EaglercraftUUID uuid) { + return uuid1.equals(uuid) || uuid2.equals(uuid); } @Override @@ -72,14 +67,26 @@ public class IntegratedVoiceService { || (uuid1.equals(other.uuid2) && uuid2.equals(other.uuid1)); } - private VoicePair(EaglercraftUUID uuid1, EaglercraftUUID uuid2) { - this.uuid1 = uuid1; - this.uuid2 = uuid2; + @Override + public int hashCode() { + return uuid1.hashCode() ^ uuid2.hashCode(); } + } - private boolean anyEquals(EaglercraftUUID uuid) { - return uuid1.equals(uuid) || uuid2.equals(uuid); - } + public static final Logger logger = LogManager.getLogger("IntegratedVoiceService"); + + private GameMessagePacket iceServersPacket; + private final Map voicePlayers = new HashMap<>(); + private final Map> voiceRequests = new HashMap<>(); + + private final Set voicePairs = new HashSet<>(); + + public IntegratedVoiceService(String[] iceServers) { + iceServersPacket = new SPacketVoiceSignalAllowedEAG(true, iceServers); + } + + public void changeICEServers(String[] iceServers) { + iceServersPacket = new SPacketVoiceSignalAllowedEAG(true, iceServers); } public void handlePlayerLoggedIn(EntityPlayerMP player) { @@ -90,54 +97,6 @@ public class IntegratedVoiceService { removeUser(player.getUniqueID()); } - public void handleVoiceSignalPacketTypeRequest(EaglercraftUUID player, EntityPlayerMP sender) { - EaglercraftUUID senderUUID = sender.getUniqueID(); - if (senderUUID.equals(player)) - return; // prevent duplicates - if (!voicePlayers.containsKey(senderUUID)) - return; - EntityPlayerMP targetPlayerCon = voicePlayers.get(player); - if (targetPlayerCon == null) - return; - VoicePair newPair = new VoicePair(player, senderUUID); - if (voicePairs.contains(newPair)) - return; // already paired - ExpiringSet senderRequestSet = voiceRequests.get(senderUUID); - if (senderRequestSet == null) { - voiceRequests.put(senderUUID, senderRequestSet = new ExpiringSet<>(2000)); - } - if (!senderRequestSet.add(player)) { - return; - } - - // check if other has requested earlier - ExpiringSet theSet; - if ((theSet = voiceRequests.get(player)) != null && theSet.contains(senderUUID)) { - theSet.remove(senderUUID); - if (theSet.isEmpty()) - voiceRequests.remove(player); - senderRequestSet.remove(player); - if (senderRequestSet.isEmpty()) - voiceRequests.remove(senderUUID); - // send each other add data - voicePairs.add(newPair); - if(targetPlayerCon.playerNetServerHandler.getEaglerMessageProtocol().ver <= 3) { - targetPlayerCon.playerNetServerHandler - .sendEaglerMessage(new SPacketVoiceSignalConnectV3EAG(senderUUID.msb, senderUUID.lsb, false, false)); - }else { - targetPlayerCon.playerNetServerHandler - .sendEaglerMessage(new SPacketVoiceSignalConnectV4EAG(senderUUID.msb, senderUUID.lsb, false)); - } - if(sender.playerNetServerHandler.getEaglerMessageProtocol().ver <= 3) { - sender.playerNetServerHandler - .sendEaglerMessage(new SPacketVoiceSignalConnectV3EAG(player.msb, player.lsb, false, true)); - }else { - sender.playerNetServerHandler - .sendEaglerMessage(new SPacketVoiceSignalConnectV4EAG(player.msb, player.lsb, true)); - } - } - } - public void handleVoiceSignalPacketTypeConnect(EntityPlayerMP sender) { if (voicePlayers.containsKey(sender.getUniqueID())) { return; @@ -148,7 +107,7 @@ public class IntegratedVoiceService { return; } Collection userDatas = new ArrayList<>(voicePlayers.size()); - for(EntityPlayerMP player : voicePlayers.values()) { + for (EntityPlayerMP player : voicePlayers.values()) { EaglercraftUUID uuid = player.getUniqueID(); userDatas.add(new SPacketVoiceSignalGlobalEAG.UserData(uuid.msb, uuid.lsb, player.getName())); } @@ -158,15 +117,6 @@ public class IntegratedVoiceService { } } - public void handleVoiceSignalPacketTypeICE(EaglercraftUUID player, byte[] str, EntityPlayerMP sender) { - EaglercraftUUID uuid = sender.getUniqueID(); - VoicePair pair = new VoicePair(player, uuid); - EntityPlayerMP pass = voicePairs.contains(pair) ? voicePlayers.get(player) : null; - if (pass != null) { - pass.playerNetServerHandler.sendEaglerMessage(new SPacketVoiceSignalICEEAG(uuid.msb, uuid.lsb, str)); - } - } - public void handleVoiceSignalPacketTypeDesc(EaglercraftUUID player, byte[] str, EntityPlayerMP sender) { EaglercraftUUID uuid = sender.getUniqueID(); VoicePair pair = new VoicePair(player, uuid); @@ -197,9 +147,68 @@ public class IntegratedVoiceService { pairsItr.remove(); EntityPlayerMP conn = voicePlayers.get(target); if (conn != null) { - conn.playerNetServerHandler.sendEaglerMessage(new SPacketVoiceSignalDisconnectPeerEAG(player.msb, player.lsb)); + conn.playerNetServerHandler + .sendEaglerMessage(new SPacketVoiceSignalDisconnectPeerEAG(player.msb, player.lsb)); } - sender.playerNetServerHandler.sendEaglerMessage(new SPacketVoiceSignalDisconnectPeerEAG(target.msb, target.lsb)); + sender.playerNetServerHandler + .sendEaglerMessage(new SPacketVoiceSignalDisconnectPeerEAG(target.msb, target.lsb)); + } + } + } + + public void handleVoiceSignalPacketTypeICE(EaglercraftUUID player, byte[] str, EntityPlayerMP sender) { + EaglercraftUUID uuid = sender.getUniqueID(); + VoicePair pair = new VoicePair(player, uuid); + EntityPlayerMP pass = voicePairs.contains(pair) ? voicePlayers.get(player) : null; + if (pass != null) { + pass.playerNetServerHandler.sendEaglerMessage(new SPacketVoiceSignalICEEAG(uuid.msb, uuid.lsb, str)); + } + } + + public void handleVoiceSignalPacketTypeRequest(EaglercraftUUID player, EntityPlayerMP sender) { + EaglercraftUUID senderUUID = sender.getUniqueID(); + if (senderUUID.equals(player)) + return; // prevent duplicates + if (!voicePlayers.containsKey(senderUUID)) + return; + EntityPlayerMP targetPlayerCon = voicePlayers.get(player); + if (targetPlayerCon == null) + return; + VoicePair newPair = new VoicePair(player, senderUUID); + if (voicePairs.contains(newPair)) + return; // already paired + ExpiringSet senderRequestSet = voiceRequests.get(senderUUID); + if (senderRequestSet == null) { + voiceRequests.put(senderUUID, senderRequestSet = new ExpiringSet<>(2000)); + } + if (!senderRequestSet.add(player)) { + return; + } + + // check if other has requested earlier + ExpiringSet theSet; + if ((theSet = voiceRequests.get(player)) != null && theSet.contains(senderUUID)) { + theSet.remove(senderUUID); + if (theSet.isEmpty()) + voiceRequests.remove(player); + senderRequestSet.remove(player); + if (senderRequestSet.isEmpty()) + voiceRequests.remove(senderUUID); + // send each other add data + voicePairs.add(newPair); + if (targetPlayerCon.playerNetServerHandler.getEaglerMessageProtocol().ver <= 3) { + targetPlayerCon.playerNetServerHandler.sendEaglerMessage( + new SPacketVoiceSignalConnectV3EAG(senderUUID.msb, senderUUID.lsb, false, false)); + } else { + targetPlayerCon.playerNetServerHandler + .sendEaglerMessage(new SPacketVoiceSignalConnectV4EAG(senderUUID.msb, senderUUID.lsb, false)); + } + if (sender.playerNetServerHandler.getEaglerMessageProtocol().ver <= 3) { + sender.playerNetServerHandler + .sendEaglerMessage(new SPacketVoiceSignalConnectV3EAG(player.msb, player.lsb, false, true)); + } else { + sender.playerNetServerHandler + .sendEaglerMessage(new SPacketVoiceSignalConnectV4EAG(player.msb, player.lsb, true)); } } } @@ -211,7 +220,7 @@ public class IntegratedVoiceService { voiceRequests.remove(user); if (voicePlayers.size() > 0) { Collection userDatas = new ArrayList<>(voicePlayers.size()); - for(EntityPlayerMP player : voicePlayers.values()) { + for (EntityPlayerMP player : voicePlayers.values()) { EaglercraftUUID uuid = player.getUniqueID(); userDatas.add(new SPacketVoiceSignalGlobalEAG.UserData(uuid.msb, uuid.lsb, player.getName())); } @@ -234,7 +243,8 @@ public class IntegratedVoiceService { if (voicePlayers.size() > 0) { EntityPlayerMP conn = voicePlayers.get(target); if (conn != null) { - conn.playerNetServerHandler.sendEaglerMessage(new SPacketVoiceSignalDisconnectPeerEAG(user.msb, user.lsb)); + conn.playerNetServerHandler + .sendEaglerMessage(new SPacketVoiceSignalDisconnectPeerEAG(user.msb, user.lsb)); } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/ClientIntegratedServerNetworkManager.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/ClientIntegratedServerNetworkManager.java index f6ac239f..2e49d7bd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/ClientIntegratedServerNetworkManager.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/ClientIntegratedServerNetworkManager.java @@ -19,14 +19,15 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2023-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -42,6 +43,47 @@ public class ClientIntegratedServerNetworkManager extends EaglercraftNetworkMana super(channel); } + public void addRecievedPacket(byte[] next) { + if (recievedPacketBufferCounter < recievedPacketBuffer.length - 1) { + recievedPacketBuffer[recievedPacketBufferCounter++] = next; + } else { + logger.error("Dropping packets on recievedPacketBuffer for channel \"{}\"! (overflow)", address); + } + } + + @Override + public boolean checkDisconnected() { + if (!isPlayerChannelOpen) { + try { + processReceivedPackets(); // catch kick message + } catch (IOException e) { + } + clearRecieveQueue(); + doClientDisconnect(new ChatComponentTranslation("disconnect.endOfStream")); + return true; + } else { + return false; + } + } + + public void clearRecieveQueue() { + for (int i = 0; i < recievedPacketBufferCounter; ++i) { + recievedPacketBuffer[i] = null; + } + recievedPacketBufferCounter = 0; + } + + @Override + public void closeChannel(IChatComponent reason) { + LANServerController.closeLAN(); + SingleplayerServerController.closeLocalPlayerChannel(); + if (nethandler != null) { + nethandler.onDisconnect(reason); + } + clearRecieveQueue(); + clientDisconnected = true; + } + @Override public void connect() { clearRecieveQueue(); @@ -54,29 +96,16 @@ public class ClientIntegratedServerNetworkManager extends EaglercraftNetworkMana } @Override - public void closeChannel(IChatComponent reason) { - LANServerController.closeLAN(); - SingleplayerServerController.closeLocalPlayerChannel(); - if(nethandler != null) { - nethandler.onDisconnect(reason); - } - clearRecieveQueue(); - clientDisconnected = true; - } - - public void addRecievedPacket(byte[] next) { - if(recievedPacketBufferCounter < recievedPacketBuffer.length - 1) { - recievedPacketBuffer[recievedPacketBufferCounter++] = next; - }else { - logger.error("Dropping packets on recievedPacketBuffer for channel \"{}\"! (overflow)", address); - } + public boolean isLocalChannel() { + return true; } @Override public void processReceivedPackets() throws IOException { - if(nethandler == null) return; + if (nethandler == null) + return; - for(int i = 0; i < recievedPacketBufferCounter; ++i) { + for (int i = 0; i < recievedPacketBufferCounter; ++i) { byte[] next = recievedPacketBuffer[i]; recievedPacketBuffer[i] = null; ++debugPacketCounter; @@ -85,33 +114,36 @@ public class ClientIntegratedServerNetworkManager extends EaglercraftNetworkMana nettyBuffer.writerIndex(next.length); PacketBuffer input = new PacketBuffer(nettyBuffer); int pktId = input.readVarIntFromBuffer(); - + Packet pkt; try { pkt = packetState.getPacket(EnumPacketDirection.CLIENTBOUND, pktId); - }catch(IllegalAccessException | InstantiationException ex) { + } catch (IllegalAccessException | InstantiationException ex) { throw new IOException("Recieved a packet with type " + pktId + " which is invalid!"); } - - if(pkt == null) { - throw new IOException("Recieved packet type " + pktId + " which is undefined in state " + packetState); + + if (pkt == null) { + throw new IOException( + "Recieved packet type " + pktId + " which is undefined in state " + packetState); } - + try { pkt.readPacketData(input); - }catch(Throwable t) { + } catch (Throwable t) { throw new IOException("Failed to read packet type '" + pkt.getClass().getSimpleName() + "'", t); } - + try { pkt.processPacket(nethandler); - }catch(Throwable t) { - logger.error("Failed to process {}! It'll be skipped for debug purposes.", pkt.getClass().getSimpleName()); + } catch (Throwable t) { + logger.error("Failed to process {}! It'll be skipped for debug purposes.", + pkt.getClass().getSimpleName()); logger.error(t); } - - }catch(Throwable t) { - logger.error("Failed to process socket frame {}! It'll be skipped for debug purposes.", debugPacketCounter); + + } catch (Throwable t) { + logger.error("Failed to process socket frame {}! It'll be skipped for debug purposes.", + debugPacketCounter); logger.error(t); } } @@ -120,59 +152,32 @@ public class ClientIntegratedServerNetworkManager extends EaglercraftNetworkMana @Override public void sendPacket(Packet pkt) { - if(!isChannelOpen()) { + if (!isChannelOpen()) { logger.error("Packet was sent on a closed connection: {}", pkt.getClass().getSimpleName()); return; } - + int i; try { i = packetState.getPacketId(EnumPacketDirection.SERVERBOUND, pkt); - }catch(Throwable t) { + } catch (Throwable t) { logger.error("Incorrect packet for state: {}", pkt.getClass().getSimpleName()); return; } - + temporaryBuffer.clear(); temporaryBuffer.writeVarIntToBuffer(i); try { pkt.writePacketData(temporaryBuffer); - }catch(IOException ex) { + } catch (IOException ex) { logger.error("Failed to write packet {}!", pkt.getClass().getSimpleName()); return; } - + int len = temporaryBuffer.writerIndex(); byte[] bytes = new byte[len]; temporaryBuffer.getBytes(0, bytes); - + ClientPlatformSingleplayer.sendPacket(new IPCPacketData(address, bytes)); } - - @Override - public boolean checkDisconnected() { - if(!isPlayerChannelOpen) { - try { - processReceivedPackets(); // catch kick message - } catch (IOException e) { - } - clearRecieveQueue(); - doClientDisconnect(new ChatComponentTranslation("disconnect.endOfStream")); - return true; - }else { - return false; - } - } - - @Override - public boolean isLocalChannel() { - return true; - } - - public void clearRecieveQueue() { - for(int i = 0; i < recievedPacketBufferCounter; ++i) { - recievedPacketBuffer[i] = null; - } - recievedPacketBufferCounter = 0; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/NetHandlerSingleplayerLogin.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/NetHandlerSingleplayerLogin.java index 5736b45c..5ac787ea 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/NetHandlerSingleplayerLogin.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/sp/socket/NetHandlerSingleplayerLogin.java @@ -26,64 +26,34 @@ import net.minecraft.util.IChatComponent; /** * Copyright (c) 2023-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class NetHandlerSingleplayerLogin implements INetHandlerLoginClient { + private static final Logger logger = LogManager.getLogger("NetHandlerSingleplayerLogin"); private final Minecraft mc; private final GuiScreen previousGuiScreen; + private final EaglercraftNetworkManager networkManager; - private static final Logger logger = LogManager.getLogger("NetHandlerSingleplayerLogin"); - - public NetHandlerSingleplayerLogin(EaglercraftNetworkManager parNetworkManager, Minecraft mcIn, GuiScreen parGuiScreen) { + public NetHandlerSingleplayerLogin(EaglercraftNetworkManager parNetworkManager, Minecraft mcIn, + GuiScreen parGuiScreen) { this.networkManager = parNetworkManager; this.mc = mcIn; this.previousGuiScreen = parGuiScreen; } - @Override - public void onDisconnect(IChatComponent var1) { - this.mc.displayGuiScreen(new GuiDisconnected(this.previousGuiScreen, "connect.failed", var1)); - } - - @Override - public void handleEncryptionRequest(S01PacketEncryptionRequest var1) { - - } - - @Override - public void handleLoginSuccess(S02PacketLoginSuccess var1) { - this.networkManager.setConnectionState(EnumConnectionState.PLAY); - int p = var1.getSelectedProtocol(); - GamePluginMessageProtocol mp = GamePluginMessageProtocol.getByVersion(p); - if(mp == null) { - this.networkManager.closeChannel(new ChatComponentText("Unknown protocol selected: " + p)); - return; - } - logger.info("Server is using protocol: {}", p); - NetHandlerPlayClient netHandler = new NetHandlerPlayClient(this.mc, this.previousGuiScreen, this.networkManager, var1.getProfile()); - netHandler.setEaglerMessageController( - new GameProtocolMessageController(mp, GamePluginMessageConstants.CLIENT_TO_SERVER, - GameProtocolMessageController.createClientHandler(p, netHandler), - (ch, msg) -> netHandler.addToSendQueue(new C17PacketCustomPayload(ch, msg)))); - this.networkManager.setNetHandler(netHandler); - byte[] b = UpdateService.getClientSignatureData(); - if(b != null) { - this.networkManager.sendPacket(new C17PacketCustomPayload("EAG|MyUpdCert-1.8", new PacketBuffer(Unpooled.buffer(b, b.length).writerIndex(b.length)))); - } - } - @Override public void handleDisconnect(S00PacketDisconnect var1) { networkManager.closeChannel(var1.func_149603_c()); @@ -91,7 +61,41 @@ public class NetHandlerSingleplayerLogin implements INetHandlerLoginClient { @Override public void handleEnableCompression(S03PacketEnableCompression var1) { - + + } + + @Override + public void handleEncryptionRequest(S01PacketEncryptionRequest var1) { + + } + + @Override + public void handleLoginSuccess(S02PacketLoginSuccess var1) { + this.networkManager.setConnectionState(EnumConnectionState.PLAY); + int p = var1.getSelectedProtocol(); + GamePluginMessageProtocol mp = GamePluginMessageProtocol.getByVersion(p); + if (mp == null) { + this.networkManager.closeChannel(new ChatComponentText("Unknown protocol selected: " + p)); + return; + } + logger.info("Server is using protocol: {}", p); + NetHandlerPlayClient netHandler = new NetHandlerPlayClient(this.mc, this.previousGuiScreen, this.networkManager, + var1.getProfile()); + netHandler.setEaglerMessageController( + new GameProtocolMessageController(mp, GamePluginMessageConstants.CLIENT_TO_SERVER, + GameProtocolMessageController.createClientHandler(p, netHandler), + (ch, msg) -> netHandler.addToSendQueue(new C17PacketCustomPayload(ch, msg)))); + this.networkManager.setNetHandler(netHandler); + byte[] b = UpdateService.getClientSignatureData(); + if (b != null) { + this.networkManager.sendPacket(new C17PacketCustomPayload("EAG|MyUpdCert-1.8", + new PacketBuffer(Unpooled.buffer(b, b.length).writerIndex(b.length)))); + } + } + + @Override + public void onDisconnect(IChatComponent var1) { + this.mc.displayGuiScreen(new GuiDisconnected(this.previousGuiScreen, "connect.failed", var1)); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControl.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControl.java index f86a9c45..ea1f1bed 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControl.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControl.java @@ -13,65 +13,60 @@ import net.minecraft.client.settings.GameSettings; /** * Copyright (c) 2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum EnumTouchControl { - + DPAD_UP(EnumTouchControlPos.BOTTOM_LEFT, 60, 109, 44, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 56, 0, 22, 22, 2); }), - - + DPAD_LEFT(EnumTouchControlPos.BOTTOM_LEFT, 11, 60, 44, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 56, 22, 22, 22, 2); }), - - + DPAD_RIGHT(EnumTouchControlPos.BOTTOM_LEFT, 109, 60, 44, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 56, 66, 22, 22, 2); }), - - + DPAD_DOWN(EnumTouchControlPos.BOTTOM_LEFT, 60, 11, 44, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 56, 44, 22, 22, 2); }), - - + DPAD_UP_LEFT(EnumTouchControlPos.BOTTOM_LEFT, 16, 112, 36, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, 0, 18, 18, 2); }), - - + DPAD_UP_RIGHT(EnumTouchControlPos.BOTTOM_LEFT, 112, 112, 36, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, 18, 18, 18, 2); }), - - + JUMP(EnumTouchControlPos.BOTTOM_RIGHT, 64, 64, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { - if(TouchControls.isSneakToggled) { + if (!TouchControls.isPressed(enumIn)) { + if (TouchControls.isSneakToggled) { TouchControls.resetSneakInvalidate(); } } @@ -80,29 +75,28 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, 90, 18, 18, 2); }), - - + SNEAK(EnumTouchControlPos.BOTTOM_LEFT, 64, 64, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { enumIn.invalid = true; TouchControls.isSneakToggled = !TouchControls.isSneakToggled; } }, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); - TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, TouchControls.isSneakToggled ? 126 : 108, 18, 18, 2); + TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, TouchControls.isSneakToggled ? 126 : 108, 18, 18, + 2); }), - - + BACK(EnumTouchControlPos.TOP, -18, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { - if(Touch.isDeviceKeyboardOpenMAYBE()) { + if (!TouchControls.isPressed(enumIn)) { + if (Touch.isDeviceKeyboardOpenMAYBE()) { Touch.closeDeviceKeyboard(); - }else { + } else { Minecraft mc = Minecraft.getMinecraft(); - if(mc.thePlayer != null) { + if (mc.thePlayer != null) { mc.setIngameFocus(); - }else if(mc.currentScreen != null && !(mc.currentScreen instanceof GuiMainMenu)) { + } else if (mc.currentScreen != null && !(mc.currentScreen instanceof GuiMainMenu)) { mc.displayGuiScreen(null); } } @@ -112,24 +106,21 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 0, 36, 18, 18, 2); }), - - + BACK_DISABLED(EnumTouchControlPos.TOP, -18, 0, 36, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 0, 54, 18, 18, 2); }), - - + KEYBOARD(EnumTouchControlPos.TOP, 18, 0, 36, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 0, 72, 18, 18, 2); }), - - + PAUSE(EnumTouchControlPos.TOP, -18, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { Minecraft mc = Minecraft.getMinecraft(); mc.displayInGameMenu(); } @@ -138,10 +129,9 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 0, 0, 18, 18, 2); }), - - + CHAT(EnumTouchControlPos.TOP, 18, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { Minecraft mc = Minecraft.getMinecraft(); mc.displayGuiScreen(new GuiChat()); } @@ -150,10 +140,9 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 0, 18, 18, 18, 2); }), - - + F3(EnumTouchControlPos.TOP, 144, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { Minecraft mc = Minecraft.getMinecraft(); GameSettings gameSettings = mc.gameSettings; gameSettings.showDebugInfo = !gameSettings.showDebugInfo; @@ -163,10 +152,9 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 218, 220, 18, 18, 2); }), - - + F5(EnumTouchControlPos.TOP, 90, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { Minecraft mc = Minecraft.getMinecraft(); mc.togglePerspective(); } @@ -175,12 +163,11 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 218, 184, 18, 18, 2); }), - - + PASTE(EnumTouchControlPos.TOP, 144, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { GuiScreen screen = Minecraft.getMinecraft().currentScreen; - if(screen != null) { + if (screen != null) { screen.fireInputEvent(EnumInputEvent.CLIPBOARD_PASTE, null); } } @@ -189,12 +176,11 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 218, 148, 18, 18, 2); }), - - + COPY(EnumTouchControlPos.TOP, 90, 0, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { GuiScreen screen = Minecraft.getMinecraft().currentScreen; - if(screen != null) { + if (screen != null) { screen.fireInputEvent(EnumInputEvent.CLIPBOARD_COPY, null); } } @@ -203,10 +189,9 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 218, 166, 18, 18, 2); }), - - + PICK(EnumTouchControlPos.BOTTOM_RIGHT, 62, 125, 40, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { Minecraft.getMinecraft().middleClickMouse(); } }, (enumIn, x, y, pressed, mc, res) -> { @@ -214,10 +199,9 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 36, 20, 20, 20, 2); }), - - + FLY(EnumTouchControlPos.BOTTOM_LEFT, 16, 16, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { TouchControls.resetSneak(); EntityPlayerSP player = Minecraft.getMinecraft().thePlayer; player.jump(); @@ -228,24 +212,21 @@ public enum EnumTouchControl { int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, 72, 18, 18, 2); }), - - + FLY_UP(EnumTouchControlPos.BOTTOM_RIGHT, 12, 120, 36, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, 36, 18, 18, 2); }), - - + FLY_DOWN(EnumTouchControlPos.BOTTOM_RIGHT, 12, 75, 36, null, (enumIn, x, y, pressed, mc, res) -> { mc.getTextureManager().bindTexture(TouchOverlayRenderer.spriteSheet); int[] pos = enumIn.getLocation(res, TouchOverlayRenderer._fuck); TouchOverlayRenderer.drawTexturedModalRect(pos[0], pos[1], 18, 54, 18, 18, 2); }), - - + FLY_END(EnumTouchControlPos.BOTTOM_RIGHT, 64, 64, 36, (enumIn, x, y) -> { - if(!TouchControls.isPressed(enumIn)) { + if (!TouchControls.isPressed(enumIn)) { Minecraft.getMinecraft().thePlayer.capabilities.isFlying = false; } }, (enumIn, x, y, pressed, mc, res) -> { @@ -262,98 +243,13 @@ public enum EnumTouchControl { void call(EnumTouchControl enumIn, int x, int y, boolean pressed, Minecraft mc, ScaledResolution res); } - protected final EnumTouchControlPos pos; - protected final int offX; - protected final int offY; - protected final int size; - protected final TouchAction action; - protected final TouchRender render; - - protected boolean visible = true; - protected boolean invalid = true; - public static final EnumTouchControl[] _VALUES = values(); - - EnumTouchControl(EnumTouchControlPos pos, int offX, int offY, int size, TouchAction action, TouchRender render) { - this.pos = pos; - this.offX = offX; - this.offY = offY; - this.size = size; - this.action = action; - this.render = render; - } - - public int[] getLocation(ScaledResolution scaledResolution, int[] loc) { - if(loc == null) { - loc = new int[2]; - } - int sz = size; - switch (pos) { - case TOP_LEFT: - loc[0] = offX; - loc[1] = offY; - break; - case TOP: - loc[0] = offX + (scaledResolution.getScaledWidth() - sz) / 2; - loc[1] = offY; - break; - case TOP_RIGHT: - loc[0] = -offX + (scaledResolution.getScaledWidth() - sz); - loc[1] = offY; - break; - case LEFT: - loc[0] = offX; - loc[1] = offY + (scaledResolution.getScaledHeight() - sz) / 2; - break; - case RIGHT: - loc[0] = -offX + (scaledResolution.getScaledWidth() - sz); - loc[1] = offY + (scaledResolution.getScaledHeight() - sz) / 2; - break; - case BOTTOM_LEFT: - loc[0] = offX; - loc[1] = -offY + (scaledResolution.getScaledHeight() - sz); - break; - case BOTTOM: - loc[0] = offX + (scaledResolution.getScaledWidth() - sz) / 2; - loc[1] = -offY + (scaledResolution.getScaledHeight() - sz); - break; - case BOTTOM_RIGHT: - loc[0] = -offX + (scaledResolution.getScaledWidth() - sz); - loc[1] = -offY + (scaledResolution.getScaledHeight() - sz); - break; - } - return loc; - } - - public void setVisible(TouchOverlayRenderer renderer, boolean vis) { - if(visible != vis) { - visible = vis; - invalid = true; - if(vis) { - renderer.invalidate(); - }else { - renderer.invalidateDeep(); - } - } - } - - public int getSize() { - return size; - } - - public TouchAction getAction() { - return action; - } - - public TouchRender getRender() { - return render; - } - protected static EnumTouchLayoutState currentLayout = null; public static void setLayoutState(TouchOverlayRenderer renderer, EnumTouchLayoutState layout) { - if(layout == currentLayout) return; - switch(layout) { + if (layout == currentLayout) + return; + switch (layout) { case IN_GUI: DPAD_UP.setVisible(renderer, false); DPAD_LEFT.setVisible(renderer, false); @@ -576,4 +472,92 @@ public enum EnumTouchControl { currentLayout = layout; } + protected final EnumTouchControlPos pos; + protected final int offX; + protected final int offY; + + protected final int size; + protected final TouchAction action; + + protected final TouchRender render; + + protected boolean visible = true; + + protected boolean invalid = true; + + EnumTouchControl(EnumTouchControlPos pos, int offX, int offY, int size, TouchAction action, TouchRender render) { + this.pos = pos; + this.offX = offX; + this.offY = offY; + this.size = size; + this.action = action; + this.render = render; + } + + public TouchAction getAction() { + return action; + } + + public int[] getLocation(ScaledResolution scaledResolution, int[] loc) { + if (loc == null) { + loc = new int[2]; + } + int sz = size; + switch (pos) { + case TOP_LEFT: + loc[0] = offX; + loc[1] = offY; + break; + case TOP: + loc[0] = offX + (scaledResolution.getScaledWidth() - sz) / 2; + loc[1] = offY; + break; + case TOP_RIGHT: + loc[0] = -offX + (scaledResolution.getScaledWidth() - sz); + loc[1] = offY; + break; + case LEFT: + loc[0] = offX; + loc[1] = offY + (scaledResolution.getScaledHeight() - sz) / 2; + break; + case RIGHT: + loc[0] = -offX + (scaledResolution.getScaledWidth() - sz); + loc[1] = offY + (scaledResolution.getScaledHeight() - sz) / 2; + break; + case BOTTOM_LEFT: + loc[0] = offX; + loc[1] = -offY + (scaledResolution.getScaledHeight() - sz); + break; + case BOTTOM: + loc[0] = offX + (scaledResolution.getScaledWidth() - sz) / 2; + loc[1] = -offY + (scaledResolution.getScaledHeight() - sz); + break; + case BOTTOM_RIGHT: + loc[0] = -offX + (scaledResolution.getScaledWidth() - sz); + loc[1] = -offY + (scaledResolution.getScaledHeight() - sz); + break; + } + return loc; + } + + public TouchRender getRender() { + return render; + } + + public int getSize() { + return size; + } + + public void setVisible(TouchOverlayRenderer renderer, boolean vis) { + if (visible != vis) { + visible = vis; + invalid = true; + if (vis) { + renderer.invalidate(); + } else { + renderer.invalidateDeep(); + } + } + } + } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControlPos.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControlPos.java index fa10bd87..64bc8777 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControlPos.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchControlPos.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.touch_gui; /** * Copyright (c) 2024 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchLayoutState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchLayoutState.java index 55601f14..0f228637 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchLayoutState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/EnumTouchLayoutState.java @@ -3,26 +3,20 @@ package net.lax1dude.eaglercraft.v1_8.touch_gui; /** * Copyright (c) 2024 lax1due. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum EnumTouchLayoutState { - IN_GUI, - IN_GUI_TYPING, - IN_GUI_NO_BACK, - IN_GAME, - IN_GAME_WALK, - IN_GAME_CAN_FLY, - IN_GAME_WALK_CAN_FLY, - IN_GAME_FLYING, + IN_GUI, IN_GUI_TYPING, IN_GUI_NO_BACK, IN_GAME, IN_GAME_WALK, IN_GAME_CAN_FLY, IN_GAME_WALK_CAN_FLY, IN_GAME_FLYING, IN_GAME_WALK_FLYING; } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControlInput.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControlInput.java index 03d01059..d39b151e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControlInput.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControlInput.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.touch_gui; /** * Copyright (c) 2024 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -19,6 +20,7 @@ public class TouchControlInput { public int x; public int y; public final EnumTouchControl control; + public TouchControlInput(int x, int y, EnumTouchControl control) { this.x = x; this.y = y; diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControls.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControls.java index aa1b59cf..ae39e0e3 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControls.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchControls.java @@ -1,23 +1,27 @@ package net.lax1dude.eaglercraft.v1_8.touch_gui; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + import net.lax1dude.eaglercraft.v1_8.Touch; import net.lax1dude.eaglercraft.v1_8.touch_gui.EnumTouchControl.TouchAction; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; -import java.util.*; - /** * Copyright (c) 2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,48 +33,27 @@ public class TouchControls { protected static boolean isSneakToggled = false; - public static void update(boolean screenTouched) { - Minecraft mc = Minecraft.getMinecraft(); - int h = mc.displayHeight; - final ScaledResolution sr = mc.scaledResolution; - int fac = sr.getScaleFactor(); - if(screenTouched) { - int touchPoints = Touch.touchPointCount(); - int[] loc; - for(int i = 0; i < touchPoints; ++i) { - int x = Touch.touchPointX(i); - int y = h - Touch.touchPointY(i) - 1; - int uid = Touch.touchPointUID(i); - TouchControlInput input = touchControls.get(uid); - if(input != null) { - EnumTouchControl ctrl = input.control; - loc = ctrl.getLocation(sr, TouchOverlayRenderer._fuck); - loc[0] *= fac; - loc[1] *= fac; - int size = ctrl.getSize() * fac; - if (x >= loc[0] && y >= loc[1] && x < loc[0] + size && y < loc[1] + size) { - continue; - } - EnumTouchControl[] en = EnumTouchControl._VALUES; - for (int j = 0; j < en.length; ++j) { - EnumTouchControl control = en[j]; - if(!control.visible) continue; - loc = control.getLocation(sr, TouchOverlayRenderer._fuck); - loc[0] *= fac; - loc[1] *= fac; - size = control.getSize() * fac; - if (x >= loc[0] && y >= loc[1] && x < loc[0] + size && y < loc[1] + size) { - touchControls.put(uid, new TouchControlInput(x / fac, y / fac, control)); - break; - } - } + public static boolean getSneakToggled() { + return isSneakToggled; + } + + public static void handleInput() { + if (!touchControls.isEmpty()) { + Set newPressed = EnumSet.noneOf(EnumTouchControl.class); + TouchOverlayRenderer renderer = Minecraft.getMinecraft().touchOverlayRenderer; + for (TouchControlInput input : touchControls.values()) { + TouchAction action = input.control.getAction(); + if (action != null) { + action.call(input.control, input.x, input.y); } + if (input.control.invalid) { + renderer.invalidate(); + } + newPressed.add(input.control); } - mc.ingameGUI.updateTouchEagler(mc.currentScreen == null); - }else { - touchControls.clear(); + touchControlPressed = newPressed; + } else { touchControlPressed.clear(); - mc.ingameGUI.updateTouchEagler(false); } } @@ -78,53 +61,23 @@ public class TouchControls { Minecraft mc = Minecraft.getMinecraft(); pointY = mc.displayHeight - pointY - 1; EnumTouchControl control = overlappingControl0(pointX, pointY, mc.scaledResolution); - if(control != null) { + if (control != null) { int fac = mc.scaledResolution.getScaleFactor(); touchControls.put(uid, new TouchControlInput(pointX / fac, pointY / fac, control)); return true; - }else { - return mc.currentScreen == null && Minecraft.getMinecraft().ingameGUI.handleTouchBeginEagler(uid, pointX, pointY); + } else { + return mc.currentScreen == null + && Minecraft.getMinecraft().ingameGUI.handleTouchBeginEagler(uid, pointX, pointY); } } public static boolean handleTouchEnd(int uid, int pointX, int pointY) { - if(touchControls.remove(uid) != null) { + if (touchControls.remove(uid) != null) { return true; - }else { + } else { Minecraft mc = Minecraft.getMinecraft(); - return mc.currentScreen == null && mc.ingameGUI.handleTouchEndEagler(uid, pointX, mc.displayHeight - pointY - 1); - } - } - - public static void resetSneak() { - isSneakToggled = false; - } - - public static void resetSneakInvalidate() { - if(isSneakToggled) { - isSneakToggled = false; - EnumTouchControl.SNEAK.invalid = true; - Minecraft.getMinecraft().touchOverlayRenderer.invalidate(); - } - } - - public static void handleInput() { - if(!touchControls.isEmpty()) { - Set newPressed = EnumSet.noneOf(EnumTouchControl.class); - TouchOverlayRenderer renderer = Minecraft.getMinecraft().touchOverlayRenderer; - for (TouchControlInput input : touchControls.values()) { - TouchAction action = input.control.getAction(); - if(action != null) { - action.call(input.control, input.x, input.y); - } - if(input.control.invalid) { - renderer.invalidate(); - } - newPressed.add(input.control); - } - touchControlPressed = newPressed; - }else { - touchControlPressed.clear(); + return mc.currentScreen == null + && mc.ingameGUI.handleTouchEndEagler(uid, pointX, mc.displayHeight - pointY - 1); } } @@ -132,10 +85,6 @@ public class TouchControls { return touchControlPressed.contains(control); } - public static boolean getSneakToggled() { - return isSneakToggled; - } - public static EnumTouchControl overlappingControl(int tx, int ty) { Minecraft mc = Minecraft.getMinecraft(); ty = mc.displayHeight - ty - 1; @@ -149,7 +98,8 @@ public class TouchControls { int size; for (int j = 0; j < en.length; ++j) { EnumTouchControl control = en[j]; - if(!control.visible) continue; + if (!control.visible) + continue; loc = control.getLocation(sr, TouchOverlayRenderer._fuck); loc[0] *= fac; loc[1] *= fac; @@ -161,4 +111,62 @@ public class TouchControls { return null; } + public static void resetSneak() { + isSneakToggled = false; + } + + public static void resetSneakInvalidate() { + if (isSneakToggled) { + isSneakToggled = false; + EnumTouchControl.SNEAK.invalid = true; + Minecraft.getMinecraft().touchOverlayRenderer.invalidate(); + } + } + + public static void update(boolean screenTouched) { + Minecraft mc = Minecraft.getMinecraft(); + int h = mc.displayHeight; + final ScaledResolution sr = mc.scaledResolution; + int fac = sr.getScaleFactor(); + if (screenTouched) { + int touchPoints = Touch.touchPointCount(); + int[] loc; + for (int i = 0; i < touchPoints; ++i) { + int x = Touch.touchPointX(i); + int y = h - Touch.touchPointY(i) - 1; + int uid = Touch.touchPointUID(i); + TouchControlInput input = touchControls.get(uid); + if (input != null) { + EnumTouchControl ctrl = input.control; + loc = ctrl.getLocation(sr, TouchOverlayRenderer._fuck); + loc[0] *= fac; + loc[1] *= fac; + int size = ctrl.getSize() * fac; + if (x >= loc[0] && y >= loc[1] && x < loc[0] + size && y < loc[1] + size) { + continue; + } + EnumTouchControl[] en = EnumTouchControl._VALUES; + for (int j = 0; j < en.length; ++j) { + EnumTouchControl control = en[j]; + if (!control.visible) + continue; + loc = control.getLocation(sr, TouchOverlayRenderer._fuck); + loc[0] *= fac; + loc[1] *= fac; + size = control.getSize() * fac; + if (x >= loc[0] && y >= loc[1] && x < loc[0] + size && y < loc[1] + size) { + touchControls.put(uid, new TouchControlInput(x / fac, y / fac, control)); + break; + } + } + } + } + mc.ingameGUI.updateTouchEagler(mc.currentScreen == null); + } else { + touchControls.clear(); + touchControlPressed.clear(); + mc.ingameGUI.updateTouchEagler(false); + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchOverlayRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchOverlayRenderer.java index 040f28ac..4c56f85e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchOverlayRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/touch_gui/TouchOverlayRenderer.java @@ -1,5 +1,13 @@ package net.lax1dude.eaglercraft.v1_8.touch_gui; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_COLOR_BUFFER_BIT; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; + +import java.util.Set; + +import com.google.common.collect.Sets; + import net.lax1dude.eaglercraft.v1_8.PointerInputAbstraction; import net.lax1dude.eaglercraft.v1_8.Touch; import net.lax1dude.eaglercraft.v1_8.opengl.GameOverlayFramebuffer; @@ -13,23 +21,18 @@ import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; - -import java.util.Set; - -import com.google.common.collect.Sets; - /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -40,11 +43,30 @@ public class TouchOverlayRenderer { static final int[] _fuck = new int[2]; + protected static void drawTexturedModalRect(float xCoord, float yCoord, int minU, int minV, int maxU, int maxV, + int scaleFac) { + float f = 0.00390625F; + float f1 = 0.00390625F; + Tessellator tessellator = Tessellator.getInstance(); + WorldRenderer worldrenderer = tessellator.getWorldRenderer(); + worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); + worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) maxV * scaleFac), 0.0) + .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); + worldrenderer.pos((double) (xCoord + (float) maxU * scaleFac), (double) (yCoord + (float) maxV * scaleFac), 0.0) + .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); + worldrenderer.pos((double) (xCoord + (float) maxU * scaleFac), (double) (yCoord + 0.0F), 0.0) + .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + 0) * f1)).endVertex(); + worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + 0.0F), 0.0) + .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + 0) * f1)).endVertex(); + tessellator.draw(); + } + private GameOverlayFramebuffer overlayFramebuffer; private final Minecraft mc; private boolean invalid = false; private boolean invalidDeep = false; private int currentWidth = -1; + private int currentHeight = -1; public TouchOverlayRenderer(Minecraft mc) { @@ -54,6 +76,30 @@ public class TouchOverlayRenderer { EnumTouchControl.setLayoutState(this, EnumTouchLayoutState.IN_GUI); } + private EnumTouchLayoutState hashLayoutState() { + if (mc.currentScreen != null) { + return mc.currentScreen.showCopyPasteButtons() ? EnumTouchLayoutState.IN_GUI_TYPING + : (mc.currentScreen.canCloseGui() ? EnumTouchLayoutState.IN_GUI + : EnumTouchLayoutState.IN_GUI_NO_BACK); + } + EntityPlayerSP player = mc.thePlayer; + if (player != null) { + if (player.capabilities.isFlying) { + return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK_FLYING + : EnumTouchLayoutState.IN_GAME_FLYING; + } else { + if (player.capabilities.allowFlying) { + return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK_CAN_FLY + : EnumTouchLayoutState.IN_GAME_CAN_FLY; + } else { + return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK : EnumTouchLayoutState.IN_GAME; + } + } + } else { + return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK : EnumTouchLayoutState.IN_GAME; + } + } + public void invalidate() { invalid = true; } @@ -64,18 +110,18 @@ public class TouchOverlayRenderer { } public void render(int w, int h, ScaledResolution scaledResolution) { - if(PointerInputAbstraction.isTouchMode()) { + if (PointerInputAbstraction.isTouchMode()) { render0(w, h, scaledResolution); - if(EnumTouchControl.KEYBOARD.visible) { + if (EnumTouchControl.KEYBOARD.visible) { int[] pos = EnumTouchControl.KEYBOARD.getLocation(scaledResolution, _fuck); int scale = scaledResolution.getScaleFactor(); int size = EnumTouchControl.KEYBOARD.size * scale; Touch.touchSetOpenKeyboardZone(pos[0] * scale, (scaledResolution.getScaledHeight() - pos[1] - 1) * scale - size, size, size); - }else { + } else { Touch.touchSetOpenKeyboardZone(0, 0, 0, 0); } - }else { + } else { Touch.touchSetOpenKeyboardZone(0, 0, 0, 0); } } @@ -84,7 +130,7 @@ public class TouchOverlayRenderer { EnumTouchControl.setLayoutState(this, hashLayoutState()); int sw = scaledResolution.getScaledWidth(); int sh = scaledResolution.getScaledHeight(); - if(currentWidth != sw || currentHeight != sh) { + if (currentWidth != sw || currentHeight != sh) { invalidateDeep(); } GlStateManager.disableDepth(); @@ -92,11 +138,11 @@ public class TouchOverlayRenderer { GlStateManager.disableLighting(); GlStateManager.enableAlpha(); GlStateManager.depthMask(false); - if(invalid) { + if (invalid) { GlStateManager.pushMatrix(); invalidDeep |= overlayFramebuffer.beginRender(sw, sh); GlStateManager.viewport(0, 0, sw, sh); - if(invalidDeep) { + if (invalidDeep) { currentWidth = sw; currentHeight = sh; GlStateManager.clearColor(0.0f, 0.0f, 0.0f, 0.0f); @@ -107,8 +153,8 @@ public class TouchOverlayRenderer { controls.remove(input.control); } for (EnumTouchControl control : controls) { - if(invalidDeep || control.invalid) { - if(control.visible) { + if (invalidDeep || control.invalid) { + if (control.visible) { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); control.getRender().call(control, 0, 0, false, mc, scaledResolution); } @@ -117,8 +163,8 @@ public class TouchOverlayRenderer { } for (TouchControlInput input : TouchControls.touchControls.values()) { EnumTouchControl control = input.control; - if(invalidDeep || control.invalid) { - if(control.visible) { + if (invalidDeep || control.invalid) { + if (control.visible) { GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); control.getRender().call(control, input.x, input.y, true, mc, scaledResolution); } @@ -149,49 +195,10 @@ public class TouchOverlayRenderer { GlStateManager.depthMask(true); } - private EnumTouchLayoutState hashLayoutState() { - if(mc.currentScreen != null) { - return mc.currentScreen.showCopyPasteButtons() ? EnumTouchLayoutState.IN_GUI_TYPING - : (mc.currentScreen.canCloseGui() ? EnumTouchLayoutState.IN_GUI - : EnumTouchLayoutState.IN_GUI_NO_BACK); - } - EntityPlayerSP player = mc.thePlayer; - if(player != null) { - if(player.capabilities.isFlying) { - return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK_FLYING : EnumTouchLayoutState.IN_GAME_FLYING; - }else { - if(player.capabilities.allowFlying) { - return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK_CAN_FLY : EnumTouchLayoutState.IN_GAME_CAN_FLY; - }else { - return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK : EnumTouchLayoutState.IN_GAME; - } - } - }else { - return showDiagButtons() ? EnumTouchLayoutState.IN_GAME_WALK : EnumTouchLayoutState.IN_GAME; - } - } - private boolean showDiagButtons() { return TouchControls.isPressed(EnumTouchControl.DPAD_UP) || TouchControls.isPressed(EnumTouchControl.DPAD_UP_LEFT) || TouchControls.isPressed(EnumTouchControl.DPAD_UP_RIGHT); } - protected static void drawTexturedModalRect(float xCoord, float yCoord, int minU, int minV, int maxU, int maxV, int scaleFac) { - float f = 0.00390625F; - float f1 = 0.00390625F; - Tessellator tessellator = Tessellator.getInstance(); - WorldRenderer worldrenderer = tessellator.getWorldRenderer(); - worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + (float) maxV * scaleFac), 0.0) - .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); - worldrenderer.pos((double) (xCoord + (float) maxU * scaleFac), (double) (yCoord + (float) maxV * scaleFac), 0.0) - .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + maxV) * f1)).endVertex(); - worldrenderer.pos((double) (xCoord + (float) maxU * scaleFac), (double) (yCoord + 0.0F), 0.0) - .tex((double) ((float) (minU + maxU) * f), (double) ((float) (minV + 0) * f1)).endVertex(); - worldrenderer.pos((double) (xCoord + 0.0F), (double) (yCoord + 0.0F), 0.0) - .tex((double) ((float) (minU + 0) * f), (double) ((float) (minV + 0) * f1)).endVertex(); - tessellator.draw(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/CertificateInvalidException.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/CertificateInvalidException.java index acb3c250..e4ae1c10 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/CertificateInvalidException.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/CertificateInvalidException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.update; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -20,14 +21,14 @@ public class CertificateInvalidException extends RuntimeException { public CertificateInvalidException() { } - public CertificateInvalidException(String message, Throwable cause) { - super(message, cause); - } - public CertificateInvalidException(String message) { super(message); } + public CertificateInvalidException(String message, Throwable cause) { + super(message, cause); + } + public CertificateInvalidException(Throwable cause) { super(cause); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateCheckerOverlay.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateCheckerOverlay.java index 4379bae1..bb08f7de 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateCheckerOverlay.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateCheckerOverlay.java @@ -1,33 +1,37 @@ package net.lax1dude.eaglercraft.v1_8.update; -import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; -import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; -import net.lax1dude.eaglercraft.v1_8.sp.lan.LANServerController; -import net.minecraft.util.EnumChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Gui; -import net.minecraft.client.gui.GuiButton; -import net.minecraft.client.gui.GuiScreen; -import net.minecraft.client.resources.I18n; -import net.minecraft.util.ResourceLocation; - -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; import java.util.List; import org.apache.commons.lang3.StringUtils; +import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; +import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; +import net.lax1dude.eaglercraft.v1_8.sp.lan.LANServerController; +import net.minecraft.client.Minecraft; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.gui.GuiButton; +import net.minecraft.client.gui.GuiScreen; +import net.minecraft.client.resources.I18n; +import net.minecraft.util.EnumChatFormatting; +import net.minecraft.util.ResourceLocation; + /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,73 +60,61 @@ public class GuiUpdateCheckerOverlay extends Gui { this.backScreen = screen; } - public void setResolution(Minecraft mc, int w, int h) { - if(!UpdateService.supported()) { - return; - } - this.mc = mc; - this.width = w; - this.height = h; - checkForUpdatesButton = new GuiButton(0, 0, 0, 150, 20, I18n.format("update.button") + " " + I18n.format(mc.gameSettings.enableUpdateSvc ? "gui.yes" : "gui.no")); - startDownloadButton = new GuiButton(1, 1, 0, 115, 20, I18n.format("update.startDownload")); - viewAllUpdatesButton = new GuiButton(2, 1, 0, 115, 20, I18n.format("update.viewAll", 0)); - dismissUpdatesButton = new GuiButton(3, 1, 0, 115, 20, I18n.format("update.dismiss")); - } - public void drawScreen(int mx, int my, float partialTicks) { - if(!UpdateService.supported()) { + if (!UpdateService.supported()) { return; } UpdateProgressStruct progressState = UpdateService.getUpdatingStatus(); - if(progressState.isBusy) { + if (progressState.isBusy) { drawScreenBusy(mx, my, partialTicks, progressState); return; } - + checkForUpdatesButton.visible = isIngame; startDownloadButton.visible = false; viewAllUpdatesButton.visible = false; dismissUpdatesButton.visible = false; totalHeightOffset = 0; - + int i = UpdateService.getAvailableUpdates().size(); boolean shownSP = i > 0 || !mc.isSingleplayer() || LANServerController.isHostingLAN(); checkForUpdatesButton.visible &= shownSP; - - if(mc.gameSettings.enableUpdateSvc) { + + if (mc.gameSettings.enableUpdateSvc) { String str; UpdateCertificate cert = UpdateService.getLatestUpdateFound(); - if(cert != null) { + if (cert != null) { startDownloadButton.visible = true; viewAllUpdatesButton.visible = true; dismissUpdatesButton.visible = true; viewAllUpdatesButton.displayString = I18n.format("update.viewAll", i); str = I18n.format("update.found"); mc.fontRendererObj.drawStringWithShadow(str, 3, 22, 0xFFFFAA); - + int embedY = 35; int embedWidth = 115; - int embedWidth2 = (int)(embedWidth / 0.75f); - - List lst = cert.bundleVersionComment.length() == 0 ? null : mc.fontRendererObj.listFormattedStringToWidth(cert.bundleVersionComment, embedWidth2 - 14); - + int embedWidth2 = (int) (embedWidth / 0.75f); + + List lst = cert.bundleVersionComment.length() == 0 ? null + : mc.fontRendererObj.listFormattedStringToWidth(cert.bundleVersionComment, embedWidth2 - 14); + int embedHeight = 44; - if(lst != null) { + if (lst != null) { embedHeight += 3 + lst.size() * 6; } - + GlStateManager.pushMatrix(); GlStateManager.translate(1.0f, embedY, 0.0f); GlStateManager.scale(0.75f, 0.75f, 0.75f); - - int embedHeight2 = (int)(embedHeight / 0.75f); - + + int embedHeight2 = (int) (embedHeight / 0.75f); + drawGradientRect(1, 1, embedWidth2 - 1, embedHeight2 - 1, 0xFFFFFFAA, 0xFFFFFFAA); drawGradientRect(0, 1, embedWidth2, 2, 0xFF000000, 0xFF000000); drawGradientRect(0, embedHeight2 - 1, embedWidth2, embedHeight2, 0xFF000000, 0xFF000000); drawGradientRect(0, 1, 1, embedHeight2 - 1, 0xFF000000, 0xFF000000); drawGradientRect(embedWidth2 - 1, 1, embedWidth2, embedHeight2 - 1, 0xFF000000, 0xFF000000); - + mc.getTextureManager().bindTexture(eaglerIcons); GlStateManager.pushMatrix(); GlStateManager.scale(0.3f, 0.3f, 0.3f); @@ -131,34 +123,37 @@ public class GuiUpdateCheckerOverlay extends Gui { drawTexturedModalRect(25, 25, 156, 0, 100, 100); EaglercraftGPU.glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); GlStateManager.popMatrix(); - + mc.fontRendererObj.drawString(EnumChatFormatting.UNDERLINE + cert.bundleDisplayName, 45, 11, 0x000000); - mc.fontRendererObj.drawString(I18n.format("update.update") + " " + EnumChatFormatting.DARK_RED + cert.bundleDisplayVersion, 45, 25, 0x000000); - - if(lst != null) { - for(int j = 0, l = lst.size(); j < l; ++j) { + mc.fontRendererObj.drawString( + I18n.format("update.update") + " " + EnumChatFormatting.DARK_RED + cert.bundleDisplayVersion, + 45, 25, 0x000000); + + if (lst != null) { + for (int j = 0, l = lst.size(); j < l; ++j) { mc.fontRendererObj.drawString(lst.get(j), 5, 42 + j * 8, 0x000000); } } - - mc.fontRendererObj.drawString(I18n.format("update.author") + " " + cert.bundleAuthorName, 5, 44 + (lst == null ? 0 : (3 + lst.size() * 8)), 0x777777); - + + mc.fontRendererObj.drawString(I18n.format("update.author") + " " + cert.bundleAuthorName, 5, + 44 + (lst == null ? 0 : (3 + lst.size() * 8)), 0x777777); + startDownloadButton.yPosition = embedHeight + embedY + 5; viewAllUpdatesButton.yPosition = startDownloadButton.yPosition + 22; dismissUpdatesButton.yPosition = viewAllUpdatesButton.yPosition + 22; totalHeightOffset = dismissUpdatesButton.yPosition + 20; - + GlStateManager.popMatrix(); - }else if(isIngame) { - if(shownSP) { + } else if (isIngame) { + if (shownSP) { str = I18n.format("update.noneNew"); mc.fontRendererObj.drawString(str, 3, 22, 0xDDDDDD); - if(i > 0) { + if (i > 0) { viewAllUpdatesButton.yPosition = 40; viewAllUpdatesButton.visible = true; viewAllUpdatesButton.displayString = I18n.format("update.viewAll", i); totalHeightOffset = 60; - }else { + } else { totalHeightOffset = 32; } } @@ -172,7 +167,7 @@ public class GuiUpdateCheckerOverlay extends Gui { } public void drawScreenBusy(int mx, int my, float partialTicks, UpdateProgressStruct progressState) { - if(!UpdateService.supported()) { + if (!UpdateService.supported()) { return; } checkForUpdatesButton.visible = false; @@ -185,12 +180,12 @@ public class GuiUpdateCheckerOverlay extends Gui { mc.fontRendererObj.drawStringWithShadow(str, 2, 2, 0xFFFFAA); GlStateManager.translate(0.0f, 14.0f, 0.0f); GlStateManager.scale(0.75f, 0.75f, 0.75f); - if(!StringUtils.isAllBlank(progressState.statusString1)) { + if (!StringUtils.isAllBlank(progressState.statusString1)) { str = progressState.statusString1; mc.fontRendererObj.drawStringWithShadow(str, 3, 0, 0xFFFFFF); } int cc = isIngame ? 0xBBBBBB : 0xFFFFFF; - if(!StringUtils.isAllBlank(progressState.statusString2)) { + if (!StringUtils.isAllBlank(progressState.statusString2)) { str = progressState.statusString2; mc.fontRendererObj.drawStringWithShadow(str, 3, 11, cc); } @@ -199,63 +194,79 @@ public class GuiUpdateCheckerOverlay extends Gui { int progX2 = 135; int progY2 = 32; float prog = progressState.progressBar; - if(prog >= 0.0f) { + if (prog >= 0.0f) { int bk = 0xFFBBBBBB; int fg = 0xFFDD0000; - drawGradientRect(progX1 + 1, progY1 + 1, progX1 + (int)((progX2 - progX1 - 1) * prog), progY2 - 1, fg, fg); - drawGradientRect(progX1 + (int)((progX2 - progX1 - 1) * prog), progY1 + 1, progX2 - 1, progY2 - 1, bk, bk); + drawGradientRect(progX1 + 1, progY1 + 1, progX1 + (int) ((progX2 - progX1 - 1) * prog), progY2 - 1, fg, fg); + drawGradientRect(progX1 + (int) ((progX2 - progX1 - 1) * prog), progY1 + 1, progX2 - 1, progY2 - 1, bk, bk); drawGradientRect(progX1, progY1, progX2, progY1 + 1, 0xFF000000, 0xFF000000); drawGradientRect(progX1, progY2 - 1, progX2, progY2, 0xFF000000, 0xFF000000); drawGradientRect(progX1, progY1 + 1, progX1 + 1, progY2 - 1, 0xFF000000, 0xFF000000); drawGradientRect(progX2 - 1, progY1 + 1, progX2, progY2 - 1, 0xFF000000, 0xFF000000); } totalHeightOffset = 32; - if(!StringUtils.isAllBlank(progressState.statusString3)) { + if (!StringUtils.isAllBlank(progressState.statusString3)) { GlStateManager.translate(0.0f, progY2 + 2, 0.0f); GlStateManager.scale(0.66f, 0.66f, 0.66f); str = progressState.statusString3; - List wrappedURL = mc.fontRendererObj.listFormattedStringToWidth(str, (int)((progX2 - progX1) * 1.5f)); - for(int i = 0, l = wrappedURL.size(); i < l; ++i) { + List wrappedURL = mc.fontRendererObj.listFormattedStringToWidth(str, + (int) ((progX2 - progX1) * 1.5f)); + for (int i = 0, l = wrappedURL.size(); i < l; ++i) { str = wrappedURL.get(i); mc.fontRendererObj.drawStringWithShadow(str, 5, i * 11, cc); } - totalHeightOffset += (int)(wrappedURL.size() * 5.5f); + totalHeightOffset += (int) (wrappedURL.size() * 5.5f); } GlStateManager.popMatrix(); } + public int getSharedWorldInfoYOffset() { + return totalHeightOffset; + } + public void mouseClicked(int mx, int my, int btn) { - if(!UpdateService.supported()) { + if (!UpdateService.supported()) { return; } if (btn == 0) { - if(checkForUpdatesButton.mousePressed(mc, mx, my)) { + if (checkForUpdatesButton.mousePressed(mc, mx, my)) { mc.gameSettings.enableUpdateSvc = !mc.gameSettings.enableUpdateSvc; mc.gameSettings.saveOptions(); - checkForUpdatesButton.displayString = I18n.format("update.button") + " " + I18n.format(mc.gameSettings.enableUpdateSvc ? "gui.yes" : "gui.no"); + checkForUpdatesButton.displayString = I18n.format("update.button") + " " + + I18n.format(mc.gameSettings.enableUpdateSvc ? "gui.yes" : "gui.no"); } - if(startDownloadButton.mousePressed(mc, mx, my)) { - if(!UpdateService.getUpdatingStatus().isBusy) { + if (startDownloadButton.mousePressed(mc, mx, my)) { + if (!UpdateService.getUpdatingStatus().isBusy) { UpdateCertificate cert = UpdateService.getLatestUpdateFound(); - if(cert != null) { + if (cert != null) { UpdateService.startClientUpdateFrom(cert); } } } - if(viewAllUpdatesButton.mousePressed(mc, mx, my)) { + if (viewAllUpdatesButton.mousePressed(mc, mx, my)) { mc.displayGuiScreen(new GuiUpdateVersionList(backScreen)); } - if(dismissUpdatesButton.mousePressed(mc, mx, my)) { + if (dismissUpdatesButton.mousePressed(mc, mx, my)) { UpdateCertificate cert = UpdateService.getLatestUpdateFound(); - if(cert != null) { + if (cert != null) { UpdateService.dismiss(cert); } } } } - public int getSharedWorldInfoYOffset() { - return totalHeightOffset; + public void setResolution(Minecraft mc, int w, int h) { + if (!UpdateService.supported()) { + return; + } + this.mc = mc; + this.width = w; + this.height = h; + checkForUpdatesButton = new GuiButton(0, 0, 0, 150, 20, I18n.format("update.button") + " " + + I18n.format(mc.gameSettings.enableUpdateSvc ? "gui.yes" : "gui.no")); + startDownloadButton = new GuiButton(1, 1, 0, 115, 20, I18n.format("update.startDownload")); + viewAllUpdatesButton = new GuiButton(2, 1, 0, 115, 20, I18n.format("update.viewAll", 0)); + dismissUpdatesButton = new GuiButton(3, 1, 0, 115, 20, I18n.format("update.dismiss")); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateDownloadSuccess.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateDownloadSuccess.java index 00a79a86..c3544d74 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateDownloadSuccess.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateDownloadSuccess.java @@ -7,14 +7,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,21 +30,14 @@ public class GuiUpdateDownloadSuccess extends GuiScreen { this.updateData = updateData; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 56, I18n.format("updateSuccess.downloadOffline"))); - this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 86, I18n.format("updateSuccess.installToBootMenu"))); - this.buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 6 + 130, I18n.format("gui.cancel"))); - } - public void actionPerformed(GuiButton btn) { - if(btn.id == 0) { + if (btn.id == 0) { this.mc.loadingScreen.eaglerShow(I18n.format("updateSuccess.downloading"), null); UpdateService.quine(updateData.clientSignature, updateData.clientBundle); this.mc.displayGuiScreen(parent); - }else if(btn.id == 1) { + } else if (btn.id == 1) { this.mc.displayGuiScreen(new GuiUpdateInstallOptions(this, parent, updateData)); - }else if(btn.id == 2) { + } else if (btn.id == 2) { this.mc.displayGuiScreen(parent); } } @@ -57,4 +51,13 @@ public class GuiUpdateDownloadSuccess extends GuiScreen { super.drawScreen(par1, par2, par3); } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 56, + I18n.format("updateSuccess.downloadOffline"))); + this.buttonList.add(new GuiButton(1, this.width / 2 - 100, this.height / 6 + 86, + I18n.format("updateSuccess.installToBootMenu"))); + this.buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 6 + 130, I18n.format("gui.cancel"))); + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateInstallOptions.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateInstallOptions.java index 444e25b3..565dd554 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateInstallOptions.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateInstallOptions.java @@ -9,14 +9,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,35 +40,26 @@ public class GuiUpdateInstallOptions extends GuiScreen { enableCountdown = makeDefault; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(makeDefaultBtn = new GuiButton(0, this.width / 2 - 100, this.height / 6 + 46, - I18n.format("updateInstall.setDefault") + ": " + I18n.format(makeDefault ? "gui.yes" : "gui.no"))); - this.buttonList.add(enableCountdownBtn = new GuiButton(1, this.width / 2 - 100, this.height / 6 + 76, - I18n.format("updateInstall.setCountdown") + ": " - + I18n.format(enableCountdown ? "gui.yes" : "gui.no"))); - this.buttonList.add(new GuiButton(2, this.width / 2 - 100, this.height / 6 + 110, I18n.format("updateInstall.install"))); - this.buttonList.add(new GuiButton(3, this.width / 2 - 100, this.height / 6 + 140, I18n.format("gui.cancel"))); - - } - public void actionPerformed(GuiButton btn) { - if(btn.id == 0) { + if (btn.id == 0) { makeDefault = !makeDefault; - makeDefaultBtn.displayString = I18n.format("updateInstall.setDefault") + ": " + I18n.format(makeDefault ? "gui.yes" : "gui.no"); - }else if(btn.id == 1) { + makeDefaultBtn.displayString = I18n.format("updateInstall.setDefault") + ": " + + I18n.format(makeDefault ? "gui.yes" : "gui.no"); + } else if (btn.id == 1) { enableCountdown = !enableCountdown; - enableCountdownBtn.displayString = I18n.format("updateInstall.setCountdown") + ": " + I18n.format(enableCountdown ? "gui.yes" : "gui.no"); - }else if(btn.id == 2) { + enableCountdownBtn.displayString = I18n.format("updateInstall.setCountdown") + ": " + + I18n.format(enableCountdown ? "gui.yes" : "gui.no"); + } else if (btn.id == 2) { mc.loadingScreen.eaglerShow(I18n.format("updateSuccess.installing"), null); try { - UpdateService.installSignedClient(updateData.clientSignature, updateData.clientBundle, makeDefault, enableCountdown); - }catch(Throwable t) { + UpdateService.installSignedClient(updateData.clientSignature, updateData.clientBundle, makeDefault, + enableCountdown); + } catch (Throwable t) { mc.displayGuiScreen(new GuiScreenGenericErrorMessage("installFailed.title", t.toString(), onDone)); return; } mc.displayGuiScreen(onDone); - }else if(btn.id == 3) { + } else if (btn.id == 3) { mc.displayGuiScreen(parent); } } @@ -81,4 +73,17 @@ public class GuiUpdateInstallOptions extends GuiScreen { super.drawScreen(mx, my, partialTicks); } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(makeDefaultBtn = new GuiButton(0, this.width / 2 - 100, this.height / 6 + 46, + I18n.format("updateInstall.setDefault") + ": " + I18n.format(makeDefault ? "gui.yes" : "gui.no"))); + this.buttonList.add(enableCountdownBtn = new GuiButton(1, this.width / 2 - 100, this.height / 6 + 76, + I18n.format("updateInstall.setCountdown") + ": " + + I18n.format(enableCountdown ? "gui.yes" : "gui.no"))); + this.buttonList.add( + new GuiButton(2, this.width / 2 - 100, this.height / 6 + 110, I18n.format("updateInstall.install"))); + this.buttonList.add(new GuiButton(3, this.width / 2 - 100, this.height / 6 + 140, I18n.format("gui.cancel"))); + + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionList.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionList.java index b965e909..0aa75ce0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionList.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionList.java @@ -11,54 +11,42 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiUpdateVersionList extends GuiScreen { + static Minecraft getMinecraft(GuiUpdateVersionList screen) { + return screen.mc; + } + final GuiScreen back; GuiUpdateVersionSlot slots; int selected; GuiButton downloadButton; int mx = 0; int my = 0; + String tooltip = null; public GuiUpdateVersionList(GuiScreen back) { this.back = back; } - public void initGui() { - selected = -1; - buttonList.clear(); - buttonList.add(new GuiButton(0, this.width / 2 + 54, this.height - 28, 100, 20, I18n.format("gui.done"))); - buttonList.add(downloadButton = new GuiButton(1, this.width / 2 - 50, this.height - 28, 100, 20, I18n.format("updateList.download"))); - buttonList.add(new GuiButton(2, this.width / 2 - 154, this.height - 28, 100, 20, I18n.format("updateList.refresh"))); - slots = new GuiUpdateVersionSlot(this); - updateButtons(); - } - - void updateButtons() { - downloadButton.enabled = selected != -1; - } - - static Minecraft getMinecraft(GuiUpdateVersionList screen) { - return screen.mc; - } - public void actionPerformed(GuiButton btn) { - switch(btn.id) { + switch (btn.id) { case 1: - if(selected != -1) { + if (selected != -1) { UpdateService.startClientUpdateFrom(slots.certList.get(selected)); } case 0: @@ -77,10 +65,12 @@ public class GuiUpdateVersionList extends GuiScreen { my = par2; slots.drawScreen(par1, par2, par3); this.drawCenteredString(fontRendererObj, I18n.format("updateList.title"), this.width / 2, 16, 16777215); - this.drawCenteredString(fontRendererObj, I18n.format("updateList.note.0"), this.width / 2, this.height - 55, 0x888888); - this.drawCenteredString(fontRendererObj, I18n.format("updateList.note.1"), this.width / 2, this.height - 45, 0x888888); + this.drawCenteredString(fontRendererObj, I18n.format("updateList.note.0"), this.width / 2, this.height - 55, + 0x888888); + this.drawCenteredString(fontRendererObj, I18n.format("updateList.note.1"), this.width / 2, this.height - 45, + 0x888888); super.drawScreen(par1, par2, par3); - if(tooltip != null) { + if (tooltip != null) { drawHoveringText(mc.fontRendererObj.listFormattedStringToWidth(tooltip, 180), par1, par2); GlStateManager.disableLighting(); tooltip = null; @@ -99,4 +89,20 @@ public class GuiUpdateVersionList extends GuiScreen { slots.handleTouchInput(); } + public void initGui() { + selected = -1; + buttonList.clear(); + buttonList.add(new GuiButton(0, this.width / 2 + 54, this.height - 28, 100, 20, I18n.format("gui.done"))); + buttonList.add(downloadButton = new GuiButton(1, this.width / 2 - 50, this.height - 28, 100, 20, + I18n.format("updateList.download"))); + buttonList.add( + new GuiButton(2, this.width / 2 - 154, this.height - 28, 100, 20, I18n.format("updateList.refresh"))); + slots = new GuiUpdateVersionSlot(this); + updateButtons(); + } + + void updateButtons() { + downloadButton.enabled = selected != -1; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionSlot.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionSlot.java index 37a2d499..4cb4f898 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionSlot.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/GuiUpdateVersionSlot.java @@ -1,6 +1,9 @@ package net.lax1dude.eaglercraft.v1_8.update; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_LINEAR; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_NEAREST; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_2D; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_TEXTURE_MIN_FILTER; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -11,21 +14,22 @@ import java.util.List; import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; import net.lax1dude.eaglercraft.v1_8.opengl.EaglercraftGPU; import net.lax1dude.eaglercraft.v1_8.opengl.GlStateManager; -import net.minecraft.util.EnumChatFormatting; import net.minecraft.client.gui.GuiSlot; +import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,6 +38,11 @@ public class GuiUpdateVersionSlot extends GuiSlot { private static final ResourceLocation eaglerGuiTex = new ResourceLocation("eagler:gui/eagler_gui.png"); + public static final SimpleDateFormat dateFmt = new SimpleDateFormat("M/dd/yyyy"); + + private static final char[] hexChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', + 'D', 'E', 'F' }; + final List certList = new ArrayList<>(); final GuiUpdateVersionList screen; @@ -44,53 +53,14 @@ public class GuiUpdateVersionSlot extends GuiSlot { this.refresh(); } - public void refresh() { - certList.clear(); - Collection certs = UpdateService.getAvailableUpdates(); - synchronized(certs) { - certList.addAll(certs); - } - certList.sort((c1, c2) -> { - if(c1.bundleVersionInteger > c2.bundleVersionInteger) { - return -1; - }else if(c1.bundleVersionInteger == c2.bundleVersionInteger) { - if(c1.sigTimestamp > c2.sigTimestamp) { - return -1; - }else if(c1.sigTimestamp == c2.sigTimestamp) { - return 0; - } - } - return 1; - }); - } - - @Override - protected int getSize() { - return certList.size(); - } - - @Override - protected void elementClicked(int var1, boolean var2, int var3, int var4) { - screen.selected = var1; - screen.updateButtons(); - } - - @Override - protected boolean isSelected(int var1) { - return var1 == screen.selected; - } - @Override protected void drawBackground() { screen.drawBackground(0); } - public static final SimpleDateFormat dateFmt = new SimpleDateFormat("M/dd/yyyy"); - private static final char[] hexChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; - @Override protected void drawSlot(int id, int xx, int yy, int width, int height, int ii) { - if(id < certList.size()) { + if (id < certList.size()) { this.mc.getTextureManager().bindTexture(eaglerGuiTex); GlStateManager.pushMatrix(); GlStateManager.translate(xx, yy, 0.0f); @@ -112,18 +82,20 @@ public class GuiUpdateVersionSlot extends GuiSlot { : (cert.bundleVersionInteger < EaglercraftVersion.updateBundlePackageVersionInt ? EnumChatFormatting.RED : EnumChatFormatting.YELLOW)) - + cert.bundleDisplayVersion + EnumChatFormatting.DARK_GRAY + " " - + cert.bundleVersionInteger + " " + EnumChatFormatting.GRAY - + dateFmt.format(new Date(cert.sigTimestamp)) + EnumChatFormatting.WHITE + " " + (cert.bundleDataLength / 1024) + " kB", + + cert.bundleDisplayVersion + EnumChatFormatting.DARK_GRAY + " " + cert.bundleVersionInteger + + " " + EnumChatFormatting.GRAY + dateFmt.format(new Date(cert.sigTimestamp)) + + EnumChatFormatting.WHITE + " " + (cert.bundleDataLength / 1024) + " kB", 2, 2, 0xFFFFFF); - List strs = (List)mc.fontRendererObj.listFormattedStringToWidth(cert.bundleVersionComment, (int)((getListWidth() - iconSize - 6) * 1.25f)); - if(strs.size() > 0) { + List strs = (List) mc.fontRendererObj.listFormattedStringToWidth(cert.bundleVersionComment, + (int) ((getListWidth() - iconSize - 6) * 1.25f)); + if (strs.size() > 0) { screen.drawString(mc.fontRendererObj, strs.get(0), 2, 13, 0x888888); } - if(strs.size() > 1) { + if (strs.size() > 1) { screen.drawString(mc.fontRendererObj, strs.get(1), 2, 24, 0x888888); } - if(strs.size() > 2 && screen.mx > xx + iconSize && screen.my > yy + 8 && screen.mx < xx + getListWidth() - 5 && screen.my < yy + 25) { + if (strs.size() > 2 && screen.mx > xx + iconSize && screen.my > yy + 8 + && screen.mx < xx + getListWidth() - 5 && screen.my < yy + 25) { screen.tooltip = cert.bundleVersionComment; } char[] hexStr1 = new char[] { hexChars[(cert.bundleDataHash[0] >>> 4) & 0xF], @@ -142,8 +114,44 @@ public class GuiUpdateVersionSlot extends GuiSlot { } } + @Override + protected void elementClicked(int var1, boolean var2, int var3, int var4) { + screen.selected = var1; + screen.updateButtons(); + } + @Override public int getListWidth() { return 250; } + + @Override + protected int getSize() { + return certList.size(); + } + + @Override + protected boolean isSelected(int var1) { + return var1 == screen.selected; + } + + public void refresh() { + certList.clear(); + Collection certs = UpdateService.getAvailableUpdates(); + synchronized (certs) { + certList.addAll(certs); + } + certList.sort((c1, c2) -> { + if (c1.bundleVersionInteger > c2.bundleVersionInteger) { + return -1; + } else if (c1.bundleVersionInteger == c2.bundleVersionInteger) { + if (c1.sigTimestamp > c2.sigTimestamp) { + return -1; + } else if (c1.sigTimestamp == c2.sigTimestamp) { + return 0; + } + } + return 1; + }); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/RelayUpdateChecker.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/RelayUpdateChecker.java index f5746807..fb5d2e43 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/RelayUpdateChecker.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/RelayUpdateChecker.java @@ -19,14 +19,15 @@ import net.minecraft.client.Minecraft; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,16 +35,16 @@ import net.minecraft.client.Minecraft; public class RelayUpdateChecker { private static class RelayEntry { - + private final String uri; private boolean queued; private boolean handshake; private RelayServerSocket currentSocket; - + private RelayEntry(String uri) { this.uri = uri; } - + } private static final List relaysList = new ArrayList<>(); @@ -55,17 +56,28 @@ public class RelayUpdateChecker { private static final String magic = "~!REQUEST_UPDATE_CERT"; + private static void connect(RelayEntry socket) { + try { + socket.handshake = false; + socket.currentSocket = PlatformWebRTC.openRelayConnection(socket.uri, 10000); + if (socket.currentSocket.isClosed()) { + socket.currentSocket = null; + } + } catch (Throwable t) { + } + } + public static void runTick() { - if(!EagRuntime.getConfiguration().isCheckRelaysForUpdates()) { + if (!EagRuntime.getConfiguration().isCheckRelaysForUpdates()) { return; } - if(!hasInit) { + if (!hasInit) { hasInit = true; - for(net.lax1dude.eaglercraft.v1_8.sp.relay.RelayEntry etr : EagRuntime.getConfiguration().getRelays()) { + for (net.lax1dude.eaglercraft.v1_8.sp.relay.RelayEntry etr : EagRuntime.getConfiguration().getRelays()) { relaysList.add(new RelayEntry(etr.address)); } byte[] b = PlatformApplication.getLocalStorage("lastRelayUpdate", false); - if(b != null) { + if (b != null) { try { lastUpdateCheck = (new DataInputStream(new EaglerInputStream(b))).readLong(); } catch (IOException e) { @@ -87,56 +99,46 @@ public class RelayUpdateChecker { relaysList.get(i).queued = true; } } - for(int i = 0, l = relaysList.size(); i < l; ++i) { + for (int i = 0, l = relaysList.size(); i < l; ++i) { RelayEntry etr = relaysList.get(i); - if(etr.currentSocket != null) { + if (etr.currentSocket != null) { updateRelay(etr); - if(etr.currentSocket != null) { + if (etr.currentSocket != null) { return; } } } - for(int i = 0, l = relaysList.size(); i < l; ++i) { + for (int i = 0, l = relaysList.size(); i < l; ++i) { RelayEntry etr = relaysList.get(i); - if(etr.queued) { + if (etr.queued) { etr.queued = false; connect(etr); - if(etr.currentSocket != null) { + if (etr.currentSocket != null) { return; } } } } - private static void connect(RelayEntry socket) { - try { - socket.handshake = false; - socket.currentSocket = PlatformWebRTC.openRelayConnection(socket.uri, 10000); - if(socket.currentSocket.isClosed()) { - socket.currentSocket = null; - } - }catch(Throwable t) { - } - } - private static void updateRelay(RelayEntry socket) { try { socket.currentSocket.update(); - if(socket.currentSocket.isClosed()) { + if (socket.currentSocket.isClosed()) { socket.currentSocket = null; - }else if(socket.currentSocket.isOpen()) { - if(!socket.handshake) { + } else if (socket.currentSocket.isOpen()) { + if (!socket.handshake) { socket.handshake = true; - socket.currentSocket.writePacket(new RelayPacket00Handshake(0x02, RelayManager.preferredRelayVersion, magic)); - }else { + socket.currentSocket + .writePacket(new RelayPacket00Handshake(0x02, RelayManager.preferredRelayVersion, magic)); + } else { // close immediately - if(socket.currentSocket.nextPacket() != null) { + if (socket.currentSocket.nextPacket() != null) { socket.currentSocket.close(); socket.currentSocket = null; } } } - }catch(Throwable t) { + } catch (Throwable t) { } } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateCertificate.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateCertificate.java index a78f786d..f7b1c933 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateCertificate.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateCertificate.java @@ -19,14 +19,15 @@ import net.lax1dude.eaglercraft.v1_8.crypto.SHA256Digest; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,16 +38,12 @@ public class UpdateCertificate { public final String type; public final String addr; + private DLSource(String type, String addr) { this.type = type; this.addr = addr; } - @Override - public int hashCode() { - return Objects.hash(addr, type); - } - @Override public boolean equals(Object obj) { if (this == obj) @@ -59,78 +56,74 @@ public class UpdateCertificate { return Objects.equals(addr, other.addr) && Objects.equals(type, other.type); } + @Override + public int hashCode() { + return Objects.hash(addr, type); + } + } - public final byte[] rawCertData; - - public final int sigVersion; - public final long sigTimestamp; - - public final int bundleDataLength; - public final byte[] bundleDataHash; - - public final String bundlePackageName; - public final String bundleDisplayName; - public final String bundleAuthorName; - public final int bundleVersionInteger; - public final String bundleDisplayVersion; - public final String bundleVersionComment; - - public final DLSource[] bundleDataSources; - - public static UpdateCertificate parseAndVerifyCertificate(byte[] certData) throws IOException, CertificateInvalidException { + public static UpdateCertificate parseAndVerifyCertificate(byte[] certData) + throws IOException, CertificateInvalidException { InputStream is = new EaglerInputStream(certData); - if(is.read() != 'E' || is.read() != 'A' || is.read() != 'G' || is.read() != 'S' || is.read() != 'I' || is.read() != 'G') { + if (is.read() != 'E' || is.read() != 'A' || is.read() != 'G' || is.read() != 'S' || is.read() != 'I' + || is.read() != 'G') { throw new IOException("Data is not a certificate!"); } - + int vers = is.read() << 8; vers |= is.read(); - if(vers != 1) { + if (vers != 1) { throw new IOException("Invalid certificate version: " + vers); } - + byte[] rsa2048sum = new byte[256]; IOUtils.readFully(is, rsa2048sum); - - byte[] rsa2048sumDec = (new BigInteger(rsa2048sum)).modPow(new BigInteger("65537"), EaglercraftVersion.updateSignatureModulus).toByteArray(); - - if(rsa2048sumDec.length > 256) { + + byte[] rsa2048sumDec = (new BigInteger(rsa2048sum)) + .modPow(new BigInteger("65537"), EaglercraftVersion.updateSignatureModulus).toByteArray(); + + if (rsa2048sumDec.length > 256) { throw new IOException("Invalid decrypted hash length: " + rsa2048sum.length); } - - if(rsa2048sumDec.length < 256) { + + if (rsa2048sumDec.length < 256) { byte[] tmp = rsa2048sumDec; rsa2048sumDec = new byte[256]; System.arraycopy(tmp, 0, rsa2048sumDec, 256 - tmp.length, tmp.length); } - + int payloadLen = is.read() << 8; payloadLen |= is.read(); - + byte[] signaturePayload = new byte[payloadLen]; IOUtils.readFully(is, signaturePayload); - + SHA256Digest sha256 = new SHA256Digest(); sha256.update(new byte[] { (byte) 170, (byte) 191, (byte) 203, (byte) 188, (byte) 47, (byte) 37, (byte) 17, (byte) 187, (byte) 169, (byte) 225, (byte) 247, (byte) 193, (byte) 100, (byte) 101, (byte) 233, (byte) 106, (byte) 80, (byte) 204, (byte) 192, (byte) 140, (byte) 19, (byte) 18, (byte) 165, (byte) 252, - (byte) 138, (byte) 187, (byte) 229, (byte) 148, (byte) 118, (byte) 208, (byte) 179, (byte) 233 }, 0, 32); + (byte) 138, (byte) 187, (byte) 229, (byte) 148, (byte) 118, (byte) 208, (byte) 179, (byte) 233 }, 0, + 32); sha256.update(signaturePayload, 0, signaturePayload.length); byte[] hash2048 = new byte[256]; sha256.doFinal(hash2048, 0); sha256.reset(); - sha256.update(new byte[] { (byte) 95, (byte) 222, (byte) 208, (byte) 153, (byte) 171, (byte) 133, (byte) 7, - (byte) 88, (byte) 111, (byte) 87, (byte) 37, (byte) 104, (byte) 98, (byte) 115, (byte) 185, (byte) 153, - (byte) 206, (byte) 188, (byte) 143, (byte) 18, (byte) 247, (byte) 28, (byte) 130, (byte) 87, (byte) 56, - (byte) 223, (byte) 45, (byte) 192, (byte) 108, (byte) 166, (byte) 254, (byte) 19 }, 0, 32); + sha256.update( + new byte[] { (byte) 95, (byte) 222, (byte) 208, (byte) 153, (byte) 171, (byte) 133, (byte) 7, (byte) 88, + (byte) 111, (byte) 87, (byte) 37, (byte) 104, (byte) 98, (byte) 115, (byte) 185, (byte) 153, + (byte) 206, (byte) 188, (byte) 143, (byte) 18, (byte) 247, (byte) 28, (byte) 130, (byte) 87, + (byte) 56, (byte) 223, (byte) 45, (byte) 192, (byte) 108, (byte) 166, (byte) 254, (byte) 19 }, + 0, 32); sha256.update(signaturePayload, 0, signaturePayload.length); sha256.doFinal(hash2048, 32); sha256.reset(); - sha256.update(new byte[] { (byte) 101, (byte) 245, (byte) 91, (byte) 125, (byte) 50, (byte) 79, (byte) 71, - (byte) 52, (byte) 244, (byte) 249, (byte) 84, (byte) 5, (byte) 139, (byte) 21, (byte) 13, (byte) 200, - (byte) 75, (byte) 0, (byte) 103, (byte) 1, (byte) 14, (byte) 159, (byte) 199, (byte) 194, (byte) 56, - (byte) 161, (byte) 63, (byte) 248, (byte) 90, (byte) 134, (byte) 96, (byte) 160 }, 0, 32); + sha256.update( + new byte[] { (byte) 101, (byte) 245, (byte) 91, (byte) 125, (byte) 50, (byte) 79, (byte) 71, (byte) 52, + (byte) 244, (byte) 249, (byte) 84, (byte) 5, (byte) 139, (byte) 21, (byte) 13, (byte) 200, + (byte) 75, (byte) 0, (byte) 103, (byte) 1, (byte) 14, (byte) 159, (byte) 199, (byte) 194, + (byte) 56, (byte) 161, (byte) 63, (byte) 248, (byte) 90, (byte) 134, (byte) 96, (byte) 160 }, + 0, 32); sha256.update(signaturePayload, 0, signaturePayload.length); sha256.doFinal(hash2048, 64); sha256.reset(); @@ -140,26 +133,43 @@ public class UpdateCertificate { (byte) 88, (byte) 215, (byte) 216, (byte) 253, (byte) 235, (byte) 7, (byte) 60 }, 0, 32); sha256.update(signaturePayload, 0, signaturePayload.length); sha256.doFinal(hash2048, 96); - - hash2048[0] = (byte)((signaturePayload.length >>> 8) & 0xFF); - hash2048[1] = (byte)(signaturePayload.length & 0xFF); - - if(!Arrays.equals(hash2048, rsa2048sumDec)) { + + hash2048[0] = (byte) ((signaturePayload.length >>> 8) & 0xFF); + hash2048[1] = (byte) (signaturePayload.length & 0xFF); + + if (!Arrays.equals(hash2048, rsa2048sumDec)) { throw new CertificateInvalidException("SHA256 checksum of signature payload is invalid!"); } - + UpdateCertificate cert; - try(InputStream gis = EaglerZLIB.newGZIPInputStream(new EaglerInputStream(signaturePayload))) { + try (InputStream gis = EaglerZLIB.newGZIPInputStream(new EaglerInputStream(signaturePayload))) { cert = new UpdateCertificate(certData, gis, vers); } - - if(System.currentTimeMillis() < cert.sigTimestamp) { + + if (System.currentTimeMillis() < cert.sigTimestamp) { throw new CertificateInvalidException("Update certificate timestamp is from the future!?"); } - + return cert; } + public final byte[] rawCertData; + public final int sigVersion; + + public final long sigTimestamp; + public final int bundleDataLength; + + public final byte[] bundleDataHash; + public final String bundlePackageName; + public final String bundleDisplayName; + public final String bundleAuthorName; + public final int bundleVersionInteger; + public final String bundleDisplayVersion; + + public final String bundleVersionComment; + + public final DLSource[] bundleDataSources; + private UpdateCertificate(byte[] certData, InputStream is, int sigVers) throws IOException { this.rawCertData = certData; this.sigVersion = sigVers; @@ -177,35 +187,12 @@ public class UpdateCertificate { IOUtils.skipFully(dis, dis.read()); int sourceCount = dis.readInt(); this.bundleDataSources = new DLSource[sourceCount]; - for(int i = 0; i < sourceCount; ++i) { + for (int i = 0; i < sourceCount; ++i) { IOUtils.skipFully(dis, 4); bundleDataSources[i] = new DLSource(dis.readUTF(), dis.readUTF()); } } - public boolean isBundleDataValid(byte[] bundleData) { - if(bundleData.length != bundleDataLength) { - return false; - } - SHA256Digest sha256 = new SHA256Digest(); - sha256.update(bundleData, 0, bundleData.length); - byte[] out = new byte[32]; - sha256.doFinal(out, 0); - return Arrays.equals(out, bundleDataHash); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(bundleDataHash); - result = prime * result + Arrays.hashCode(bundleDataSources); - result = prime * result - + Objects.hash(bundleAuthorName, bundleDataLength, bundleDisplayName, bundleDisplayVersion, - bundlePackageName, bundleVersionComment, bundleVersionInteger, sigTimestamp, sigVersion); - return result; - } - @Override public boolean equals(Object obj) { if (this == obj) @@ -226,11 +213,34 @@ public class UpdateCertificate { && sigVersion == other.sigVersion; } - public ListMultimap getSourceMultimap() { - ListMultimap ret = ListMultimapBuilder.hashKeys().arrayListValues().build(); - for(int i = 0; i < bundleDataSources.length; ++i) { + public ListMultimap getSourceMultimap() { + ListMultimap ret = ListMultimapBuilder.hashKeys().arrayListValues().build(); + for (int i = 0; i < bundleDataSources.length; ++i) { ret.put(bundleDataSources[i].type, bundleDataSources[i].addr); } return ret; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(bundleDataHash); + result = prime * result + Arrays.hashCode(bundleDataSources); + result = prime * result + + Objects.hash(bundleAuthorName, bundleDataLength, bundleDisplayName, bundleDisplayVersion, + bundlePackageName, bundleVersionComment, bundleVersionInteger, sigTimestamp, sigVersion); + return result; + } + + public boolean isBundleDataValid(byte[] bundleData) { + if (bundleData.length != bundleDataLength) { + return false; + } + SHA256Digest sha256 = new SHA256Digest(); + sha256.update(bundleData, 0, bundleData.length); + byte[] out = new byte[32]; + sha256.doFinal(out, 0); + return Arrays.equals(out, bundleDataHash); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateDataObj.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateDataObj.java index e039d16b..8a69d6f2 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateDataObj.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateDataObj.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.update; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateProgressStruct.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateProgressStruct.java index 73f9014e..c13f0cb7 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateProgressStruct.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateProgressStruct.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.update; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateResultObj.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateResultObj.java index 238d8183..9d1fc000 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateResultObj.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateResultObj.java @@ -3,21 +3,31 @@ package net.lax1dude.eaglercraft.v1_8.update; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class UpdateResultObj { + public static UpdateResultObj createFailure(String dataObj) { + return new UpdateResultObj(false, dataObj); + } + + public static UpdateResultObj createSuccess(UpdateDataObj dataObj) { + return new UpdateResultObj(true, dataObj); + } + private final boolean success; + private final Object dataObj; private UpdateResultObj(boolean success, Object dataObj) { @@ -25,24 +35,16 @@ public class UpdateResultObj { this.dataObj = dataObj; } - public static UpdateResultObj createSuccess(UpdateDataObj dataObj) { - return new UpdateResultObj(true, dataObj); + public String getFailure() { + return (String) dataObj; } - public static UpdateResultObj createFailure(String dataObj) { - return new UpdateResultObj(false, dataObj); + public UpdateDataObj getSuccess() { + return (UpdateDataObj) dataObj; } public boolean isSuccess() { return success; } - public UpdateDataObj getSuccess() { - return (UpdateDataObj)dataObj; - } - - public String getFailure() { - return (String)dataObj; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateService.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateService.java index 0e7216d6..dc16e62d 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateService.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/update/UpdateService.java @@ -17,30 +17,21 @@ import net.lax1dude.eaglercraft.v1_8.log4j.Logger; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class UpdateService { - private static final Logger logger = LogManager.getLogger("UpdateService"); - - private static UpdateCertificate myUpdateCert = null; - private static boolean isBundleDataValid = false; - - private static UpdateCertificate latestUpdateFound = null; - private static final Set availableUpdates = new HashSet<>(); - private static final Set fastUpdateKnownCheckSet = new HashSet<>(); - private static final Set dismissedUpdates = new HashSet<>(); - private static class RawKnownCertHolder { private final byte[] data; @@ -53,70 +44,25 @@ public class UpdateService { this.age = EagRuntime.steadyTimeMillis(); } + public boolean equals(Object o) { + return o != null && (o == this + || ((o instanceof RawKnownCertHolder) && Arrays.equals(((RawKnownCertHolder) o).data, data))); + } + public int hashCode() { return hashcode; } - - public boolean equals(Object o) { - return o != null && (o == this || ((o instanceof RawKnownCertHolder) && Arrays.equals(((RawKnownCertHolder)o).data, data))); - } } - public static boolean supported() { - return EaglercraftVersion.enableUpdateService && EagRuntime.getConfiguration().allowUpdateSvc() && PlatformUpdateSvc.supported(); - } + private static final Logger logger = LogManager.getLogger("UpdateService"); + private static UpdateCertificate myUpdateCert = null; - public static void initialize() { - if(!supported()) { - logger.info("Update service is not supported on this client"); - return; - } - PlatformUpdateSvc.initialize(); - if(PlatformUpdateSvc.getClientSignatureData() != null) { - logger.info("Testing client update certificate..."); - try { - myUpdateCert = UpdateCertificate.parseAndVerifyCertificate(PlatformUpdateSvc.getClientSignatureData()); - if(!EaglercraftVersion.updateBundlePackageName.equalsIgnoreCase(myUpdateCert.bundlePackageName)) { - throw new CertificateInvalidException("Certificate package name does not match current client package name!"); - } - if(EaglercraftVersion.updateBundlePackageVersionInt != myUpdateCert.bundleVersionInteger) { - throw new CertificateInvalidException("Certificate client version does not match current client version!"); - } - }catch(Throwable t) { - myUpdateCert = null; - logger.error("Client update certificate is invalid!"); - logger.error(t); - } - if(myUpdateCert != null && PlatformUpdateSvc.getClientBundleData() != null) { - isBundleDataValid = myUpdateCert.isBundleDataValid(PlatformUpdateSvc.getClientBundleData()); - if(!isBundleDataValid) { - logger.error("Client checksum does not match certificate! \"Download Offline\" button will download a fresh client"); - } - } - } - byte[] latestUpdate = PlatformApplication.getLocalStorage(EaglercraftVersion.updateLatestLocalStorageKey, false); - if(latestUpdate != null) { - addCertificateToSet(latestUpdate, false); - } - } + private static boolean isBundleDataValid = false; + private static UpdateCertificate latestUpdateFound = null; + private static final Set availableUpdates = new HashSet<>(); + private static final Set fastUpdateKnownCheckSet = new HashSet<>(); - public static byte[] getClientSignatureData() { - if(myUpdateCert != null) { - return PlatformUpdateSvc.getClientSignatureData(); - } - return null; - } - - public static byte[] getClientBundleData() { - if(isBundleDataValid) { - return PlatformUpdateSvc.getClientBundleData(); - } - return null; - } - - public static UpdateCertificate getClientCertificate() { - return myUpdateCert; - } + private static final Set dismissedUpdates = new HashSet<>(); public static void addCertificateToSet(byte[] certificateData) { addCertificateToSet(certificateData, true); @@ -124,14 +70,16 @@ public class UpdateService { private static void addCertificateToSet(byte[] certificateData, boolean saveLatest) { if (EagRuntime.getConfiguration().allowUpdateDL()) { - synchronized(availableUpdates) { + synchronized (availableUpdates) { try { - if(certificateData.length > 32767) { - throw new CertificateInvalidException("Certificate is too large! (" + certificateData.length + " bytes)"); + if (certificateData.length > 32767) { + throw new CertificateInvalidException( + "Certificate is too large! (" + certificateData.length + " bytes)"); } - if(!fastUpdateKnownCheckSet.add(new RawKnownCertHolder(certificateData))) { + if (!fastUpdateKnownCheckSet.add(new RawKnownCertHolder(certificateData))) { if (EagRuntime.getConfiguration().isLogInvalidCerts()) { - logger.info("Ignoring {} byte certificate that has already been processed", certificateData.length); + logger.info("Ignoring {} byte certificate that has already been processed", + certificateData.length); } freeMemory(); return; @@ -139,8 +87,9 @@ public class UpdateService { UpdateCertificate cert = UpdateCertificate.parseAndVerifyCertificate(certificateData); if (EaglercraftVersion.updateBundlePackageName.equalsIgnoreCase(cert.bundlePackageName)) { if (myUpdateCert == null || !Arrays.equals(cert.bundleDataHash, myUpdateCert.bundleDataHash)) { - if(availableUpdates.add(cert)) { - logger.info("Found new update: {} - {}", cert.bundleDisplayName, cert.bundleDisplayVersion); + if (availableUpdates.add(cert)) { + logger.info("Found new update: {} - {}", cert.bundleDisplayName, + cert.bundleDisplayVersion); if (cert.bundleVersionInteger > EaglercraftVersion.updateBundlePackageVersionInt && (latestUpdateFound == null || cert.bundleVersionInteger > latestUpdateFound.bundleVersionInteger @@ -149,12 +98,13 @@ public class UpdateService { && !dismissedUpdates.contains(cert)) { latestUpdateFound = cert; if (saveLatest) { - PlatformApplication.setLocalStorage(EaglercraftVersion.updateLatestLocalStorageKey, - certificateData, false); + PlatformApplication.setLocalStorage( + EaglercraftVersion.updateLatestLocalStorageKey, certificateData, false); } } - }else if(EagRuntime.getConfiguration().isLogInvalidCerts()) { - logger.info("Ignoring already indexed update: {} - {}", cert.bundleDisplayName, cert.bundleDisplayVersion); + } else if (EagRuntime.getConfiguration().isLogInvalidCerts()) { + logger.info("Ignoring already indexed update: {} - {}", cert.bundleDisplayName, + cert.bundleDisplayVersion); } } } else { @@ -166,7 +116,8 @@ public class UpdateService { } } catch (Throwable t) { if (EagRuntime.getConfiguration().isLogInvalidCerts()) { - logger.error("Invalid update certificate recieved! The certificate may be from a different client"); + logger.error( + "Invalid update certificate recieved! The certificate may be from a different client"); logger.error(t); } } @@ -174,27 +125,96 @@ public class UpdateService { } } + public static void dismiss(UpdateCertificate cert) { + if (latestUpdateFound == cert) { + latestUpdateFound = null; + } + dismissedUpdates.add(cert); + } + private static void freeMemory() { - if(fastUpdateKnownCheckSet.size() > 127) { + if (fastUpdateKnownCheckSet.size() > 127) { List lst = new ArrayList<>(fastUpdateKnownCheckSet); fastUpdateKnownCheckSet.clear(); - lst.sort((c1, c2) -> { return (int)(c2.age - c1.age); }); - for(int i = 0; i < 64; ++i) { + lst.sort((c1, c2) -> { + return (int) (c2.age - c1.age); + }); + for (int i = 0; i < 64; ++i) { fastUpdateKnownCheckSet.add(lst.get(i)); } } } - public static void startClientUpdateFrom(UpdateCertificate clientUpdate) { - PlatformUpdateSvc.startClientUpdateFrom(clientUpdate); + public static Collection getAvailableUpdates() { + return availableUpdates; + } + + public static byte[] getClientBundleData() { + if (isBundleDataValid) { + return PlatformUpdateSvc.getClientBundleData(); + } + return null; + } + + public static UpdateCertificate getClientCertificate() { + return myUpdateCert; + } + + public static byte[] getClientSignatureData() { + if (myUpdateCert != null) { + return PlatformUpdateSvc.getClientSignatureData(); + } + return null; + } + + public static UpdateCertificate getLatestUpdateFound() { + return latestUpdateFound; + } + + public static UpdateResultObj getUpdateResult() { + return PlatformUpdateSvc.getUpdateResult(); } public static UpdateProgressStruct getUpdatingStatus() { return PlatformUpdateSvc.getUpdatingStatus(); } - public static UpdateResultObj getUpdateResult() { - return PlatformUpdateSvc.getUpdateResult(); + public static void initialize() { + if (!supported()) { + logger.info("Update service is not supported on this client"); + return; + } + PlatformUpdateSvc.initialize(); + if (PlatformUpdateSvc.getClientSignatureData() != null) { + logger.info("Testing client update certificate..."); + try { + myUpdateCert = UpdateCertificate.parseAndVerifyCertificate(PlatformUpdateSvc.getClientSignatureData()); + if (!EaglercraftVersion.updateBundlePackageName.equalsIgnoreCase(myUpdateCert.bundlePackageName)) { + throw new CertificateInvalidException( + "Certificate package name does not match current client package name!"); + } + if (EaglercraftVersion.updateBundlePackageVersionInt != myUpdateCert.bundleVersionInteger) { + throw new CertificateInvalidException( + "Certificate client version does not match current client version!"); + } + } catch (Throwable t) { + myUpdateCert = null; + logger.error("Client update certificate is invalid!"); + logger.error(t); + } + if (myUpdateCert != null && PlatformUpdateSvc.getClientBundleData() != null) { + isBundleDataValid = myUpdateCert.isBundleDataValid(PlatformUpdateSvc.getClientBundleData()); + if (!isBundleDataValid) { + logger.error( + "Client checksum does not match certificate! \"Download Offline\" button will download a fresh client"); + } + } + } + byte[] latestUpdate = PlatformApplication.getLocalStorage(EaglercraftVersion.updateLatestLocalStorageKey, + false); + if (latestUpdate != null) { + addCertificateToSet(latestUpdate, false); + } } public static void installSignedClient(UpdateCertificate clientCert, byte[] clientPayload, boolean setDefault, @@ -202,28 +222,13 @@ public class UpdateService { PlatformUpdateSvc.installSignedClient(clientCert, clientPayload, setDefault, setTimeout); } - public static UpdateCertificate getLatestUpdateFound() { - return latestUpdateFound; - } - - public static Collection getAvailableUpdates() { - return availableUpdates; - } - - public static void dismiss(UpdateCertificate cert) { - if(latestUpdateFound == cert) { - latestUpdateFound = null; - } - dismissedUpdates.add(cert); - } - public static void quine() { - if(myUpdateCert != null) { + if (myUpdateCert != null) { byte[] data = getClientBundleData(); - if(data != null) { + if (data != null) { logger.info("Generating signed offline download..."); PlatformUpdateSvc.quine(myUpdateCert, data); - }else { + } else { logger.error("Client checksum does not match certificate! Downloading a fresh client..."); PlatformUpdateSvc.startClientUpdateFrom(myUpdateCert); } @@ -238,4 +243,13 @@ public class UpdateService { return EagRuntime.getConfiguration().getDownloadOfflineButtonLink() == null && (myUpdateCert == null || (getClientBundleData() == null && PlatformUpdateSvc.getUpdatingStatus().isBusy)); } + + public static void startClientUpdateFrom(UpdateCertificate clientUpdate) { + PlatformUpdateSvc.startClientUpdateFrom(clientUpdate); + } + + public static boolean supported() { + return EaglercraftVersion.enableUpdateService && EagRuntime.getConfiguration().allowUpdateSvc() + && PlatformUpdateSvc.supported(); + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix.java index 2b76f6b3..8c14e28c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -40,8 +41,7 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * matrix unless otherwise stated. * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public abstract class Matrix implements Serializable { @@ -53,19 +53,17 @@ public abstract class Matrix implements Serializable { } /** - * Set this matrix to be the identity matrix. - * @return this + * @return the determinant of the matrix */ - public abstract Matrix setIdentity(); - + public abstract float determinant(); /** * Invert this matrix + * * @return this */ public abstract Matrix invert(); - /** * Load from a float buffer. The buffer stores the matrix in column major * (OpenGL) order. @@ -75,7 +73,6 @@ public abstract class Matrix implements Serializable { */ public abstract Matrix load(FloatBuffer buf); - /** * Load from a float buffer. The buffer stores the matrix in row major * (mathematical) order. @@ -85,50 +82,50 @@ public abstract class Matrix implements Serializable { */ public abstract Matrix loadTranspose(FloatBuffer buf); - /** * Negate this matrix + * * @return this */ public abstract Matrix negate(); + /** + * Set this matrix to be the identity matrix. + * + * @return this + */ + public abstract Matrix setIdentity(); /** - * Store this matrix in a float buffer. The matrix is stored in column - * major (openGL) order. + * Set this matrix to 0. + * + * @return this + */ + public abstract Matrix setZero(); + + /** + * Store this matrix in a float buffer. The matrix is stored in column major + * (openGL) order. + * * @param buf The buffer to store this matrix in * @return this */ public abstract Matrix store(FloatBuffer buf); - /** - * Store this matrix in a float buffer. The matrix is stored in row - * major (maths) order. + * Store this matrix in a float buffer. The matrix is stored in row major + * (maths) order. + * * @param buf The buffer to store this matrix in * @return this */ public abstract Matrix storeTranspose(FloatBuffer buf); - /** * Transpose this matrix + * * @return this */ public abstract Matrix transpose(); - - /** - * Set this matrix to 0. - * @return this - */ - public abstract Matrix setZero(); - - - /** - * @return the determinant of the matrix - */ - public abstract float determinant(); - - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix2f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix2f.java index 34c61751..70aed683 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix2f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix2f.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -39,42 +40,68 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * Holds a 2x2 matrix * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public class Matrix2f extends Matrix implements Serializable { private static final long serialVersionUID = 1L; - public float m00, m01, m10, m11; - /** - * Constructor for Matrix2f. The matrix is initialised to the identity. + * Add two matrices together and place the result in a third matrix. + * + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix */ - public Matrix2f() { - setIdentity(); + public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + dest.m00 = left.m00 + right.m00; + dest.m01 = left.m01 + right.m01; + dest.m10 = left.m10 + right.m10; + dest.m11 = left.m11 + right.m11; + + return dest; } /** - * Constructor + * Invert the source matrix and place the result in the destination matrix. + * + * @param src The source matrix to be inverted + * @param dest The destination matrix or null if a new matrix is to be created + * @return The inverted matrix, or null if source can't be reverted. */ - public Matrix2f(Matrix2f src) { - load(src); - } + public static Matrix2f invert(Matrix2f src, Matrix2f dest) { + /* + * inv(A) = 1/det(A) * adj(A); + */ - /** - * Load from another matrix - * @param src The source matrix - * @return this - */ - public Matrix2f load(Matrix2f src) { - return load(src, this); + float determinant = src.determinant(); + if (determinant != 0) { + if (dest == null) + dest = new Matrix2f(); + float determinant_inv = 1f / determinant; + float t00 = src.m11 * determinant_inv; + float t01 = -src.m01 * determinant_inv; + float t11 = src.m00 * determinant_inv; + float t10 = -src.m10 * determinant_inv; + + dest.m00 = t00; + dest.m01 = t01; + dest.m10 = t10; + dest.m11 = t11; + return dest; + } else + return null; } /** * Copy the source matrix to the destination matrix. - * @param src The source matrix + * + * @param src The source matrix * @param dest The destination matrix, or null if a new one should be created. * @return The copied matrix */ @@ -90,111 +117,12 @@ public class Matrix2f extends Matrix implements Serializable { return dest; } - /** - * Load from a float buffer. The buffer stores the matrix in column major - * (OpenGL) order. - * - * @param buf A float buffer to read from - * @return this - */ - public Matrix load(FloatBuffer buf) { - - m00 = buf.get(); - m01 = buf.get(); - m10 = buf.get(); - m11 = buf.get(); - - return this; - } - - /** - * Load from a float buffer. The buffer stores the matrix in row major - * (mathematical) order. - * - * @param buf A float buffer to read from - * @return this - */ - public Matrix loadTranspose(FloatBuffer buf) { - - m00 = buf.get(); - m10 = buf.get(); - m01 = buf.get(); - m11 = buf.get(); - - return this; - } - - /** - * Store this matrix in a float buffer. The matrix is stored in column - * major (openGL) order. - * @param buf The buffer to store this matrix in - */ - public Matrix store(FloatBuffer buf) { - buf.put(m00); - buf.put(m01); - buf.put(m10); - buf.put(m11); - return this; - } - - /** - * Store this matrix in a float buffer. The matrix is stored in row - * major (maths) order. - * @param buf The buffer to store this matrix in - */ - public Matrix storeTranspose(FloatBuffer buf) { - buf.put(m00); - buf.put(m10); - buf.put(m01); - buf.put(m11); - return this; - } - - - - /** - * Add two matrices together and place the result in a third matrix. - * @param left The left source matrix - * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created - * @return the destination matrix - */ - public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) { - if (dest == null) - dest = new Matrix2f(); - - dest.m00 = left.m00 + right.m00; - dest.m01 = left.m01 + right.m01; - dest.m10 = left.m10 + right.m10; - dest.m11 = left.m11 + right.m11; - - return dest; - } - - /** - * Subtract the right matrix from the left and place the result in a third matrix. - * @param left The left source matrix - * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created - * @return the destination matrix - */ - public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) { - if (dest == null) - dest = new Matrix2f(); - - dest.m00 = left.m00 - right.m00; - dest.m01 = left.m01 - right.m01; - dest.m10 = left.m10 - right.m10; - dest.m11 = left.m11 - right.m11; - - return dest; - } - /** * Multiply the right matrix by the left and place the result in a third matrix. - * @param left The left source matrix + * + * @param left The left source matrix * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created + * @param dest The destination matrix, or null if a new one is to be created * @return the destination matrix */ public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest) { @@ -214,131 +142,10 @@ public class Matrix2f extends Matrix implements Serializable { return dest; } - /** - * Transform a Vector by a matrix and return the result in a destination - * vector. - * @param left The left matrix - * @param right The right vector - * @param dest The destination vector, or null if a new one is to be created - * @return the destination vector - */ - public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) { - if (dest == null) - dest = new Vector2f(); - - float x = left.m00 * right.x + left.m10 * right.y; - float y = left.m01 * right.x + left.m11 * right.y; - - dest.x = x; - dest.y = y; - - return dest; - } - - /** - * Transpose this matrix - * @return this - */ - public Matrix transpose() { - return transpose(this); - } - - /** - * Transpose this matrix and place the result in another matrix. - * @param dest The destination matrix or null if a new matrix is to be created - * @return the transposed matrix - */ - public Matrix2f transpose(Matrix2f dest) { - return transpose(this, dest); - } - - /** - * Transpose the source matrix and place the result in the destination matrix. - * @param src The source matrix or null if a new matrix is to be created - * @param dest The destination matrix or null if a new matrix is to be created - * @return the transposed matrix - */ - public static Matrix2f transpose(Matrix2f src, Matrix2f dest) { - if (dest == null) - dest = new Matrix2f(); - - float m01 = src.m10; - float m10 = src.m01; - - dest.m01 = m01; - dest.m10 = m10; - - return dest; - } - - /** - * Invert this matrix - * @return this if successful, null otherwise - */ - public Matrix invert() { - return invert(this, this); - } - - /** - * Invert the source matrix and place the result in the destination matrix. - * @param src The source matrix to be inverted - * @param dest The destination matrix or null if a new matrix is to be created - * @return The inverted matrix, or null if source can't be reverted. - */ - public static Matrix2f invert(Matrix2f src, Matrix2f dest) { - /* - *inv(A) = 1/det(A) * adj(A); - */ - - float determinant = src.determinant(); - if (determinant != 0) { - if (dest == null) - dest = new Matrix2f(); - float determinant_inv = 1f/determinant; - float t00 = src.m11*determinant_inv; - float t01 = -src.m01*determinant_inv; - float t11 = src.m00*determinant_inv; - float t10 = -src.m10*determinant_inv; - - dest.m00 = t00; - dest.m01 = t01; - dest.m10 = t10; - dest.m11 = t11; - return dest; - } else - return null; - } - - /** - * Returns a string representation of this matrix - */ - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append(m00).append(' ').append(m10).append(' ').append('\n'); - buf.append(m01).append(' ').append(m11).append(' ').append('\n'); - return buf.toString(); - } - - /** - * Negate this matrix - * @return this - */ - public Matrix negate() { - return negate(this); - } - - /** - * Negate this matrix and stash the result in another matrix. - * @param dest The destination matrix, or null if a new matrix is to be created - * @return the negated matrix - */ - public Matrix2f negate(Matrix2f dest) { - return negate(this, dest); - } - /** * Negate the source matrix and stash the result in the destination matrix. - * @param src The source matrix to be negated + * + * @param src The source matrix to be negated * @param dest The destination matrix, or null if a new matrix is to be created * @return the negated matrix */ @@ -354,16 +161,9 @@ public class Matrix2f extends Matrix implements Serializable { return dest; } - /** - * Set this matrix to be the identity matrix. - * @return this - */ - public Matrix setIdentity() { - return setIdentity(this); - } - /** * Set the source matrix to be the identity matrix. + * * @param src The matrix to set to the identity. * @return The source matrix */ @@ -375,14 +175,6 @@ public class Matrix2f extends Matrix implements Serializable { return src; } - /** - * Set this matrix to 0. - * @return this - */ - public Matrix setZero() { - return setZero(this); - } - public static Matrix2f setZero(Matrix2f src) { src.m00 = 0.0f; src.m01 = 0.0f; @@ -391,10 +183,237 @@ public class Matrix2f extends Matrix implements Serializable { return src; } - /* (non-Javadoc) + /** + * Subtract the right matrix from the left and place the result in a third + * matrix. + * + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + dest.m00 = left.m00 - right.m00; + dest.m01 = left.m01 - right.m01; + dest.m10 = left.m10 - right.m10; + dest.m11 = left.m11 - right.m11; + + return dest; + } + + /** + * Transform a Vector by a matrix and return the result in a destination vector. + * + * @param left The left matrix + * @param right The right vector + * @param dest The destination vector, or null if a new one is to be created + * @return the destination vector + */ + public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) { + if (dest == null) + dest = new Vector2f(); + + float x = left.m00 * right.x + left.m10 * right.y; + float y = left.m01 * right.x + left.m11 * right.y; + + dest.x = x; + dest.y = y; + + return dest; + } + + /** + * Transpose the source matrix and place the result in the destination matrix. + * + * @param src The source matrix or null if a new matrix is to be created + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public static Matrix2f transpose(Matrix2f src, Matrix2f dest) { + if (dest == null) + dest = new Matrix2f(); + + float m01 = src.m10; + float m10 = src.m01; + + dest.m01 = m01; + dest.m10 = m10; + + return dest; + } + + public float m00, m01, m10, m11; + + /** + * Constructor for Matrix2f. The matrix is initialised to the identity. + */ + public Matrix2f() { + setIdentity(); + } + + /** + * Constructor + */ + public Matrix2f(Matrix2f src) { + load(src); + } + + /* + * (non-Javadoc) + * * @see org.lwjgl.vector.Matrix#determinant() */ public float determinant() { - return m00 * m11 - m01*m10; + return m00 * m11 - m01 * m10; + } + + /** + * Invert this matrix + * + * @return this if successful, null otherwise + */ + public Matrix invert() { + return invert(this, this); + } + + /** + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix load(FloatBuffer buf) { + + m00 = buf.get(); + m01 = buf.get(); + m10 = buf.get(); + m11 = buf.get(); + + return this; + } + + /** + * Load from another matrix + * + * @param src The source matrix + * @return this + */ + public Matrix2f load(Matrix2f src) { + return load(src, this); + } + + /** + * Load from a float buffer. The buffer stores the matrix in row major + * (mathematical) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix loadTranspose(FloatBuffer buf) { + + m00 = buf.get(); + m10 = buf.get(); + m01 = buf.get(); + m11 = buf.get(); + + return this; + } + + /** + * Negate this matrix + * + * @return this + */ + public Matrix negate() { + return negate(this); + } + + /** + * Negate this matrix and stash the result in another matrix. + * + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public Matrix2f negate(Matrix2f dest) { + return negate(this, dest); + } + + /** + * Set this matrix to be the identity matrix. + * + * @return this + */ + public Matrix setIdentity() { + return setIdentity(this); + } + + /** + * Set this matrix to 0. + * + * @return this + */ + public Matrix setZero() { + return setZero(this); + } + + /** + * Store this matrix in a float buffer. The matrix is stored in column major + * (openGL) order. + * + * @param buf The buffer to store this matrix in + */ + public Matrix store(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m10); + buf.put(m11); + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in row major + * (maths) order. + * + * @param buf The buffer to store this matrix in + */ + public Matrix storeTranspose(FloatBuffer buf) { + buf.put(m00); + buf.put(m10); + buf.put(m01); + buf.put(m11); + return this; + } + + /** + * Returns a string representation of this matrix + */ + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(m00).append(' ').append(m10).append(' ').append('\n'); + buf.append(m01).append(' ').append(m11).append(' ').append('\n'); + return buf.toString(); + } + + /** + * Transpose this matrix + * + * @return this + */ + public Matrix transpose() { + return transpose(this); + } + + /** + * Transpose this matrix and place the result in another matrix. + * + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public Matrix2f transpose(Matrix2f dest) { + return transpose(this, dest); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix3f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix3f.java index 08d4e601..e80e2c4b 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix3f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix3f.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -39,44 +40,94 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * Holds a 3x3 matrix. * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public class Matrix3f extends Matrix implements Serializable { private static final long serialVersionUID = 1L; - public float m00, - m01, - m02, - m10, - m11, - m12, - m20, - m21, - m22; - /** - * Constructor for Matrix3f. Matrix is initialised to the identity. + * Add two matrices together and place the result in a third matrix. + * + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix */ - public Matrix3f() { - super(); - setIdentity(); + public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = left.m00 + right.m00; + dest.m01 = left.m01 + right.m01; + dest.m02 = left.m02 + right.m02; + dest.m10 = left.m10 + right.m10; + dest.m11 = left.m11 + right.m11; + dest.m12 = left.m12 + right.m12; + dest.m20 = left.m20 + right.m20; + dest.m21 = left.m21 + right.m21; + dest.m22 = left.m22 + right.m22; + + return dest; + } + + public static boolean equal(Matrix3f a, Matrix3f b) { + return a.m00 == b.m00 && a.m01 == b.m01 && a.m02 == b.m02 && a.m10 == b.m10 && a.m11 == b.m11 && a.m12 == b.m12 + && a.m20 == b.m20 && a.m21 == b.m21 && a.m22 == b.m22; } /** - * Load from another matrix - * @param src The source matrix - * @return this + * Invert the source matrix and put the result into the destination matrix + * + * @param src The source matrix to be inverted + * @param dest The destination matrix, or null if a new one is to be created + * @return The inverted matrix if successful, null otherwise */ - public Matrix3f load(Matrix3f src) { - return load(src, this); + public static Matrix3f invert(Matrix3f src, Matrix3f dest) { + float determinant = src.determinant(); + + if (determinant != 0) { + if (dest == null) + dest = new Matrix3f(); + /* + * do it the ordinary way + * + * inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix) + * + * m00 m01 m02 m10 m11 m12 m20 m21 m22 + */ + float determinant_inv = 1f / determinant; + + // get the conjugate matrix + float t00 = src.m11 * src.m22 - src.m12 * src.m21; + float t01 = -src.m10 * src.m22 + src.m12 * src.m20; + float t02 = src.m10 * src.m21 - src.m11 * src.m20; + float t10 = -src.m01 * src.m22 + src.m02 * src.m21; + float t11 = src.m00 * src.m22 - src.m02 * src.m20; + float t12 = -src.m00 * src.m21 + src.m01 * src.m20; + float t20 = src.m01 * src.m12 - src.m02 * src.m11; + float t21 = -src.m00 * src.m12 + src.m02 * src.m10; + float t22 = src.m00 * src.m11 - src.m01 * src.m10; + + dest.m00 = t00 * determinant_inv; + dest.m11 = t11 * determinant_inv; + dest.m22 = t22 * determinant_inv; + dest.m01 = t10 * determinant_inv; + dest.m10 = t01 * determinant_inv; + dest.m20 = t02 * determinant_inv; + dest.m02 = t20 * determinant_inv; + dest.m12 = t21 * determinant_inv; + dest.m21 = t12 * determinant_inv; + return dest; + } else + return null; } /** * Copy source matrix to destination matrix - * @param src The source matrix + * + * @param src The source matrix * @param dest The destination matrix, or null of a new matrix is to be created * @return The copied matrix */ @@ -97,6 +148,214 @@ public class Matrix3f extends Matrix implements Serializable { return dest; } + /** + * Multiply the right matrix by the left and place the result in a third matrix. + * + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + float m00 = left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02; + float m01 = left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02; + float m02 = left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02; + float m10 = left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12; + float m11 = left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12; + float m12 = left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12; + float m20 = left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22; + float m21 = left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22; + float m22 = left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22; + + dest.m00 = m00; + dest.m01 = m01; + dest.m02 = m02; + dest.m10 = m10; + dest.m11 = m11; + dest.m12 = m12; + dest.m20 = m20; + dest.m21 = m21; + dest.m22 = m22; + + return dest; + } + + /** + * Negate the source matrix and place the result in the destination matrix. + * + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public static Matrix3f negate(Matrix3f src, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = -src.m00; + dest.m01 = -src.m02; + dest.m02 = -src.m01; + dest.m10 = -src.m10; + dest.m11 = -src.m12; + dest.m12 = -src.m11; + dest.m20 = -src.m20; + dest.m21 = -src.m22; + dest.m22 = -src.m21; + return dest; + } + + /** + * Set the matrix to be the identity matrix. + * + * @param m The matrix to be set to the identity + * @return m + */ + public static Matrix3f setIdentity(Matrix3f m) { + m.m00 = 1.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m10 = 0.0f; + m.m11 = 1.0f; + m.m12 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 1.0f; + return m; + } + + /** + * Set the matrix matrix to 0. + * + * @param m The matrix to be set to 0 + * @return m + */ + public static Matrix3f setZero(Matrix3f m) { + m.m00 = 0.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m10 = 0.0f; + m.m11 = 0.0f; + m.m12 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 0.0f; + return m; + } + + /** + * Subtract the right matrix from the left and place the result in a third + * matrix. + * + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + + dest.m00 = left.m00 - right.m00; + dest.m01 = left.m01 - right.m01; + dest.m02 = left.m02 - right.m02; + dest.m10 = left.m10 - right.m10; + dest.m11 = left.m11 - right.m11; + dest.m12 = left.m12 - right.m12; + dest.m20 = left.m20 - right.m20; + dest.m21 = left.m21 - right.m21; + dest.m22 = left.m22 - right.m22; + + return dest; + } + + /** + * Transform a Vector by a matrix and return the result in a destination vector. + * + * @param left The left matrix + * @param right The right vector + * @param dest The destination vector, or null if a new one is to be created + * @return the destination vector + */ + public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) { + if (dest == null) + dest = new Vector3f(); + + float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z; + float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z; + float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z; + + dest.x = x; + dest.y = y; + dest.z = z; + + return dest; + } + + /** + * Transpose the source matrix and place the result into the destination matrix + * + * @param src The source matrix to be transposed + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public static Matrix3f transpose(Matrix3f src, Matrix3f dest) { + if (dest == null) + dest = new Matrix3f(); + float m00 = src.m00; + float m01 = src.m10; + float m02 = src.m20; + float m10 = src.m01; + float m11 = src.m11; + float m12 = src.m21; + float m20 = src.m02; + float m21 = src.m12; + float m22 = src.m22; + + dest.m00 = m00; + dest.m01 = m01; + dest.m02 = m02; + dest.m10 = m10; + dest.m11 = m11; + dest.m12 = m12; + dest.m20 = m20; + dest.m21 = m21; + dest.m22 = m22; + return dest; + } + + public float m00, m01, m02, m10, m11, m12, m20, m21, m22; + + /** + * Constructor for Matrix3f. Matrix is initialised to the identity. + */ + public Matrix3f() { + super(); + setIdentity(); + } + + /** + * @return the determinant of the matrix + */ + public float determinant() { + float f = m00 * (m11 * m22 - m12 * m21) + m01 * (m12 * m20 - m10 * m22) + m02 * (m10 * m21 - m11 * m20); + return f; + } + + public boolean equals(Object m) { + return (m instanceof Matrix3f) && equal(this, (Matrix3f) m); + } + + /** + * Invert this matrix + * + * @return this if successful, null otherwise + */ + public Matrix invert() { + return invert(this, this); + } + /** * Load from a float buffer. The buffer stores the matrix in column major * (OpenGL) order. @@ -120,8 +379,18 @@ public class Matrix3f extends Matrix implements Serializable { } /** - * Load from a float buffer. The buffer stores the matrix in row major - * (maths) order. + * Load from another matrix + * + * @param src The source matrix + * @return this + */ + public Matrix3f load(Matrix3f src) { + return load(src, this); + } + + /** + * Load from a float buffer. The buffer stores the matrix in row major (maths) + * order. * * @param buf A float buffer to read from * @return this @@ -142,23 +411,42 @@ public class Matrix3f extends Matrix implements Serializable { } /** - * Store this matrix in a float buffer. The matrix is stored in column - * major (openGL) order. - * @param buf The buffer to store this matrix in + * Negate this matrix + * + * @return this */ - public Matrix store(FloatBuffer buf) { - buf.put(m00); - buf.put(m01); - buf.put(m02); - buf.put(m10); - buf.put(m11); - buf.put(m12); - buf.put(m20); - buf.put(m21); - buf.put(m22); - return this; + public Matrix negate() { + return negate(this); } - + + /** + * Negate this matrix and place the result in a destination matrix. + * + * @param dest The destination matrix, or null if a new matrix is to be created + * @return the negated matrix + */ + public Matrix3f negate(Matrix3f dest) { + return negate(this, dest); + } + + /** + * Set this matrix to be the identity matrix. + * + * @return this + */ + public Matrix setIdentity() { + return setIdentity(this); + } + + /** + * Set this matrix to 0. + * + * @return this + */ + public Matrix setZero() { + return setZero(this); + } + public Matrix store(float[] buf) { buf[0] = m00; buf[1] = m01; @@ -173,8 +461,28 @@ public class Matrix3f extends Matrix implements Serializable { } /** - * Store this matrix in a float buffer. The matrix is stored in row - * major (maths) order. + * Store this matrix in a float buffer. The matrix is stored in column major + * (openGL) order. + * + * @param buf The buffer to store this matrix in + */ + public Matrix store(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m02); + buf.put(m10); + buf.put(m11); + buf.put(m12); + buf.put(m20); + buf.put(m21); + buf.put(m22); + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in row major + * (maths) order. + * * @param buf The buffer to store this matrix in */ public Matrix storeTranspose(FloatBuffer buf) { @@ -190,179 +498,6 @@ public class Matrix3f extends Matrix implements Serializable { return this; } - /** - * Add two matrices together and place the result in a third matrix. - * @param left The left source matrix - * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created - * @return the destination matrix - */ - public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) { - if (dest == null) - dest = new Matrix3f(); - - dest.m00 = left.m00 + right.m00; - dest.m01 = left.m01 + right.m01; - dest.m02 = left.m02 + right.m02; - dest.m10 = left.m10 + right.m10; - dest.m11 = left.m11 + right.m11; - dest.m12 = left.m12 + right.m12; - dest.m20 = left.m20 + right.m20; - dest.m21 = left.m21 + right.m21; - dest.m22 = left.m22 + right.m22; - - return dest; - } - - /** - * Subtract the right matrix from the left and place the result in a third matrix. - * @param left The left source matrix - * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created - * @return the destination matrix - */ - public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) { - if (dest == null) - dest = new Matrix3f(); - - dest.m00 = left.m00 - right.m00; - dest.m01 = left.m01 - right.m01; - dest.m02 = left.m02 - right.m02; - dest.m10 = left.m10 - right.m10; - dest.m11 = left.m11 - right.m11; - dest.m12 = left.m12 - right.m12; - dest.m20 = left.m20 - right.m20; - dest.m21 = left.m21 - right.m21; - dest.m22 = left.m22 - right.m22; - - return dest; - } - - /** - * Multiply the right matrix by the left and place the result in a third matrix. - * @param left The left source matrix - * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created - * @return the destination matrix - */ - public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) { - if (dest == null) - dest = new Matrix3f(); - - float m00 = - left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02; - float m01 = - left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02; - float m02 = - left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02; - float m10 = - left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12; - float m11 = - left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12; - float m12 = - left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12; - float m20 = - left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22; - float m21 = - left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22; - float m22 = - left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22; - - dest.m00 = m00; - dest.m01 = m01; - dest.m02 = m02; - dest.m10 = m10; - dest.m11 = m11; - dest.m12 = m12; - dest.m20 = m20; - dest.m21 = m21; - dest.m22 = m22; - - return dest; - } - - /** - * Transform a Vector by a matrix and return the result in a destination - * vector. - * @param left The left matrix - * @param right The right vector - * @param dest The destination vector, or null if a new one is to be created - * @return the destination vector - */ - public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) { - if (dest == null) - dest = new Vector3f(); - - float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z; - float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z; - float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z; - - dest.x = x; - dest.y = y; - dest.z = z; - - return dest; - } - - /** - * Transpose this matrix - * @return this - */ - public Matrix transpose() { - return transpose(this, this); - } - - /** - * Transpose this matrix and place the result in another matrix - * @param dest The destination matrix or null if a new matrix is to be created - * @return the transposed matrix - */ - public Matrix3f transpose(Matrix3f dest) { - return transpose(this, dest); - } - - /** - * Transpose the source matrix and place the result into the destination matrix - * @param src The source matrix to be transposed - * @param dest The destination matrix or null if a new matrix is to be created - * @return the transposed matrix - */ - public static Matrix3f transpose(Matrix3f src, Matrix3f dest) { - if (dest == null) - dest = new Matrix3f(); - float m00 = src.m00; - float m01 = src.m10; - float m02 = src.m20; - float m10 = src.m01; - float m11 = src.m11; - float m12 = src.m21; - float m20 = src.m02; - float m21 = src.m12; - float m22 = src.m22; - - dest.m00 = m00; - dest.m01 = m01; - dest.m02 = m02; - dest.m10 = m10; - dest.m11 = m11; - dest.m12 = m12; - dest.m20 = m20; - dest.m21 = m21; - dest.m22 = m22; - return dest; - } - - /** - * @return the determinant of the matrix - */ - public float determinant() { - float f = - m00 * (m11 * m22 - m12 * m21) - + m01 * (m12 * m20 - m10 * m22) - + m02 * (m10 * m21 - m11 * m20); - return f; - } - /** * Returns a string representation of this matrix */ @@ -375,165 +510,21 @@ public class Matrix3f extends Matrix implements Serializable { } /** - * Invert this matrix - * @return this if successful, null otherwise - */ - public Matrix invert() { - return invert(this, this); - } - - /** - * Invert the source matrix and put the result into the destination matrix - * @param src The source matrix to be inverted - * @param dest The destination matrix, or null if a new one is to be created - * @return The inverted matrix if successful, null otherwise - */ - public static Matrix3f invert(Matrix3f src, Matrix3f dest) { - float determinant = src.determinant(); - - if (determinant != 0) { - if (dest == null) - dest = new Matrix3f(); - /* do it the ordinary way - * - * inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix) - * - * m00 m01 m02 - * m10 m11 m12 - * m20 m21 m22 - */ - float determinant_inv = 1f/determinant; - - // get the conjugate matrix - float t00 = src.m11 * src.m22 - src.m12* src.m21; - float t01 = - src.m10 * src.m22 + src.m12 * src.m20; - float t02 = src.m10 * src.m21 - src.m11 * src.m20; - float t10 = - src.m01 * src.m22 + src.m02 * src.m21; - float t11 = src.m00 * src.m22 - src.m02 * src.m20; - float t12 = - src.m00 * src.m21 + src.m01 * src.m20; - float t20 = src.m01 * src.m12 - src.m02 * src.m11; - float t21 = -src.m00 * src.m12 + src.m02 * src.m10; - float t22 = src.m00 * src.m11 - src.m01 * src.m10; - - dest.m00 = t00*determinant_inv; - dest.m11 = t11*determinant_inv; - dest.m22 = t22*determinant_inv; - dest.m01 = t10*determinant_inv; - dest.m10 = t01*determinant_inv; - dest.m20 = t02*determinant_inv; - dest.m02 = t20*determinant_inv; - dest.m12 = t21*determinant_inv; - dest.m21 = t12*determinant_inv; - return dest; - } else - return null; - } - - - /** - * Negate this matrix + * Transpose this matrix + * * @return this */ - public Matrix negate() { - return negate(this); + public Matrix transpose() { + return transpose(this, this); } /** - * Negate this matrix and place the result in a destination matrix. - * @param dest The destination matrix, or null if a new matrix is to be created - * @return the negated matrix + * Transpose this matrix and place the result in another matrix + * + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix */ - public Matrix3f negate(Matrix3f dest) { - return negate(this, dest); - } - - /** - * Negate the source matrix and place the result in the destination matrix. - * @param src The source matrix - * @param dest The destination matrix, or null if a new matrix is to be created - * @return the negated matrix - */ - public static Matrix3f negate(Matrix3f src, Matrix3f dest) { - if (dest == null) - dest = new Matrix3f(); - - dest.m00 = -src.m00; - dest.m01 = -src.m02; - dest.m02 = -src.m01; - dest.m10 = -src.m10; - dest.m11 = -src.m12; - dest.m12 = -src.m11; - dest.m20 = -src.m20; - dest.m21 = -src.m22; - dest.m22 = -src.m21; - return dest; - } - - /** - * Set this matrix to be the identity matrix. - * @return this - */ - public Matrix setIdentity() { - return setIdentity(this); - } - - /** - * Set the matrix to be the identity matrix. - * @param m The matrix to be set to the identity - * @return m - */ - public static Matrix3f setIdentity(Matrix3f m) { - m.m00 = 1.0f; - m.m01 = 0.0f; - m.m02 = 0.0f; - m.m10 = 0.0f; - m.m11 = 1.0f; - m.m12 = 0.0f; - m.m20 = 0.0f; - m.m21 = 0.0f; - m.m22 = 1.0f; - return m; - } - - /** - * Set this matrix to 0. - * @return this - */ - public Matrix setZero() { - return setZero(this); - } - - /** - * Set the matrix matrix to 0. - * @param m The matrix to be set to 0 - * @return m - */ - public static Matrix3f setZero(Matrix3f m) { - m.m00 = 0.0f; - m.m01 = 0.0f; - m.m02 = 0.0f; - m.m10 = 0.0f; - m.m11 = 0.0f; - m.m12 = 0.0f; - m.m20 = 0.0f; - m.m21 = 0.0f; - m.m22 = 0.0f; - return m; - } - - public boolean equals(Object m) { - return (m instanceof Matrix3f) && equal(this, (Matrix3f)m); - } - - public static boolean equal(Matrix3f a, Matrix3f b) { - return a.m00 == b.m00 && - a.m01 == b.m01 && - a.m02 == b.m02 && - a.m10 == b.m10 && - a.m11 == b.m11 && - a.m12 == b.m12 && - a.m20 == b.m20 && - a.m21 == b.m21 && - a.m22 == b.m22; + public Matrix3f transpose(Matrix3f dest) { + return transpose(this, dest); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix4f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix4f.java index e493bcc6..9415abcd 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix4f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Matrix4f.java @@ -44,342 +44,12 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; public class Matrix4f extends Matrix implements Serializable { private static final long serialVersionUID = 1L; - public float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33; - - /** - * Construct a new matrix, initialized to the identity. - */ - public Matrix4f() { - super(); - setIdentity(); - } - - public Matrix4f(final Matrix4f src) { - super(); - load(src); - } - - /** - * Returns a string representation of this matrix - */ - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append(m30).append('\n'); - buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append(m31).append('\n'); - buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append(m32).append('\n'); - buf.append(m03).append(' ').append(m13).append(' ').append(m23).append(' ').append(m33).append('\n'); - return buf.toString(); - } - - /** - * Set this matrix to be the identity matrix. - * @return this - */ - public Matrix setIdentity() { - return setIdentity(this); - } - - /** - * Set the given matrix to be the identity matrix. - * @param m The matrix to set to the identity - * @return m - */ - public static Matrix4f setIdentity(Matrix4f m) { - m.m00 = 1.0f; - m.m01 = 0.0f; - m.m02 = 0.0f; - m.m03 = 0.0f; - m.m10 = 0.0f; - m.m11 = 1.0f; - m.m12 = 0.0f; - m.m13 = 0.0f; - m.m20 = 0.0f; - m.m21 = 0.0f; - m.m22 = 1.0f; - m.m23 = 0.0f; - m.m30 = 0.0f; - m.m31 = 0.0f; - m.m32 = 0.0f; - m.m33 = 1.0f; - - return m; - } - - /** - * Set this matrix to 0. - * @return this - */ - public Matrix setZero() { - return setZero(this); - } - - /** - * Set the given matrix to 0. - * @param m The matrix to set to 0 - * @return m - */ - public static Matrix4f setZero(Matrix4f m) { - m.m00 = 0.0f; - m.m01 = 0.0f; - m.m02 = 0.0f; - m.m03 = 0.0f; - m.m10 = 0.0f; - m.m11 = 0.0f; - m.m12 = 0.0f; - m.m13 = 0.0f; - m.m20 = 0.0f; - m.m21 = 0.0f; - m.m22 = 0.0f; - m.m23 = 0.0f; - m.m30 = 0.0f; - m.m31 = 0.0f; - m.m32 = 0.0f; - m.m33 = 0.0f; - - return m; - } - - /** - * Load from another matrix4f - * @param src The source matrix - * @return this - */ - public Matrix4f load(Matrix4f src) { - return load(src, this); - } - - /** - * Copy the source matrix to the destination matrix - * @param src The source matrix - * @param dest The destination matrix, or null of a new one is to be created - * @return The copied matrix - */ - public static Matrix4f load(Matrix4f src, Matrix4f dest) { - if (dest == null) - dest = new Matrix4f(); - dest.m00 = src.m00; - dest.m01 = src.m01; - dest.m02 = src.m02; - dest.m03 = src.m03; - dest.m10 = src.m10; - dest.m11 = src.m11; - dest.m12 = src.m12; - dest.m13 = src.m13; - dest.m20 = src.m20; - dest.m21 = src.m21; - dest.m22 = src.m22; - dest.m23 = src.m23; - dest.m30 = src.m30; - dest.m31 = src.m31; - dest.m32 = src.m32; - dest.m33 = src.m33; - - return dest; - } - - /** - * Load from a float buffer. The buffer stores the matrix in column major - * (OpenGL) order. - * - * @param buf A float buffer to read from - * @return this - */ - public Matrix load(FloatBuffer buf) { - - m00 = buf.get(); - m01 = buf.get(); - m02 = buf.get(); - m03 = buf.get(); - m10 = buf.get(); - m11 = buf.get(); - m12 = buf.get(); - m13 = buf.get(); - m20 = buf.get(); - m21 = buf.get(); - m22 = buf.get(); - m23 = buf.get(); - m30 = buf.get(); - m31 = buf.get(); - m32 = buf.get(); - m33 = buf.get(); - - return this; - } - - /** - * Load from a float buffer. The buffer stores the matrix in column major - * (OpenGL) order. - * - * @param buf A float array to read from - * @return this - */ - public Matrix load(float[] buf) { - - m00 = buf[0]; - m01 = buf[1]; - m02 = buf[2]; - m03 = buf[3]; - m10 = buf[4]; - m11 = buf[5]; - m12 = buf[6]; - m13 = buf[7]; - m20 = buf[8]; - m21 = buf[9]; - m22 = buf[10]; - m23 = buf[11]; - m30 = buf[12]; - m31 = buf[13]; - m32 = buf[14]; - m33 = buf[15]; - - return this; - } - - /** - * Load from a float buffer. The buffer stores the matrix in row major - * (maths) order. - * - * @param buf A float buffer to read from - * @return this - */ - public Matrix loadTranspose(FloatBuffer buf) { - - m00 = buf.get(); - m10 = buf.get(); - m20 = buf.get(); - m30 = buf.get(); - m01 = buf.get(); - m11 = buf.get(); - m21 = buf.get(); - m31 = buf.get(); - m02 = buf.get(); - m12 = buf.get(); - m22 = buf.get(); - m32 = buf.get(); - m03 = buf.get(); - m13 = buf.get(); - m23 = buf.get(); - m33 = buf.get(); - - return this; - } - - /** - * Store this matrix in a float buffer. The matrix is stored in column - * major (openGL) order. - * @param buf The buffer to store this matrix in - */ - public Matrix store(FloatBuffer buf) { - buf.put(m00); - buf.put(m01); - buf.put(m02); - buf.put(m03); - buf.put(m10); - buf.put(m11); - buf.put(m12); - buf.put(m13); - buf.put(m20); - buf.put(m21); - buf.put(m22); - buf.put(m23); - buf.put(m30); - buf.put(m31); - buf.put(m32); - buf.put(m33); - return this; - } - - /** - * eagler - */ - public Matrix store(ByteBuffer buf) { - buf.putFloat(m00); - buf.putFloat(m01); - buf.putFloat(m02); - buf.putFloat(m03); - buf.putFloat(m10); - buf.putFloat(m11); - buf.putFloat(m12); - buf.putFloat(m13); - buf.putFloat(m20); - buf.putFloat(m21); - buf.putFloat(m22); - buf.putFloat(m23); - buf.putFloat(m30); - buf.putFloat(m31); - buf.putFloat(m32); - buf.putFloat(m33); - return this; - } - - public Matrix store(float[] buf) { - buf[0] = m00; - buf[1] = m01; - buf[2] = m02; - buf[3] = m03; - buf[4] = m10; - buf[5] = m11; - buf[6] = m12; - buf[7] = m13; - buf[8] = m20; - buf[9] = m21; - buf[10] = m22; - buf[11] = m23; - buf[12] = m30; - buf[13] = m31; - buf[14] = m32; - buf[15] = m33; - return this; - } - - /** - * Store this matrix in a float buffer. The matrix is stored in row - * major (maths) order. - * @param buf The buffer to store this matrix in - */ - public Matrix storeTranspose(FloatBuffer buf) { - buf.put(m00); - buf.put(m10); - buf.put(m20); - buf.put(m30); - buf.put(m01); - buf.put(m11); - buf.put(m21); - buf.put(m31); - buf.put(m02); - buf.put(m12); - buf.put(m22); - buf.put(m32); - buf.put(m03); - buf.put(m13); - buf.put(m23); - buf.put(m33); - return this; - } - - /** - * Store the rotation portion of this matrix in a float buffer. The matrix is stored in column - * major (openGL) order. - * @param buf The buffer to store this matrix in - */ - public Matrix store3f(FloatBuffer buf) { - buf.put(m00); - buf.put(m01); - buf.put(m02); - buf.put(m10); - buf.put(m11); - buf.put(m12); - buf.put(m20); - buf.put(m21); - buf.put(m22); - return this; - } - /** * Add two matrices together and place the result in a third matrix. - * @param left The left source matrix + * + * @param left The left source matrix * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created + * @param dest The destination matrix, or null if a new one is to be created * @return the destination matrix */ public static Matrix4f add(Matrix4f left, Matrix4f right, Matrix4f dest) { @@ -407,41 +77,127 @@ public class Matrix4f extends Matrix implements Serializable { } /** - * Subtract the right matrix from the left and place the result in a third matrix. - * @param left The left source matrix - * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created - * @return the destination matrix + * Calculate the determinant of a 3x3 matrix + * + * @return result */ - public static Matrix4f sub(Matrix4f left, Matrix4f right, Matrix4f dest) { + + private static float determinant3x3(float t00, float t01, float t02, float t10, float t11, float t12, float t20, + float t21, float t22) { + return t00 * (t11 * t22 - t12 * t21) + t01 * (t12 * t20 - t10 * t22) + t02 * (t10 * t21 - t11 * t20); + } + + public static boolean equal(Matrix4f a, Matrix4f b) { + return a.m00 == b.m00 && a.m01 == b.m01 && a.m02 == b.m02 && a.m03 == b.m03 && a.m10 == b.m10 && a.m11 == b.m11 + && a.m12 == b.m12 && a.m13 == b.m13 && a.m20 == b.m20 && a.m21 == b.m21 && a.m22 == b.m22 + && a.m23 == b.m23 && a.m30 == b.m30 && a.m31 == b.m31 && a.m32 == b.m32 && a.m33 == b.m33; + } + + /** + * Invert the source matrix and put the result in the destination + * + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return The inverted matrix if successful, null otherwise + */ + public static Matrix4f invert(Matrix4f src, Matrix4f dest) { + float determinant = src.determinant(); + + if (determinant != 0) { + /* + * m00 m01 m02 m03 m10 m11 m12 m13 m20 m21 m22 m23 m30 m31 m32 m33 + */ + if (dest == null) + dest = new Matrix4f(); + float determinant_inv = 1f / determinant; + + // first row + float t00 = determinant3x3(src.m11, src.m12, src.m13, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33); + float t01 = -determinant3x3(src.m10, src.m12, src.m13, src.m20, src.m22, src.m23, src.m30, src.m32, + src.m33); + float t02 = determinant3x3(src.m10, src.m11, src.m13, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33); + float t03 = -determinant3x3(src.m10, src.m11, src.m12, src.m20, src.m21, src.m22, src.m30, src.m31, + src.m32); + // second row + float t10 = -determinant3x3(src.m01, src.m02, src.m03, src.m21, src.m22, src.m23, src.m31, src.m32, + src.m33); + float t11 = determinant3x3(src.m00, src.m02, src.m03, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33); + float t12 = -determinant3x3(src.m00, src.m01, src.m03, src.m20, src.m21, src.m23, src.m30, src.m31, + src.m33); + float t13 = determinant3x3(src.m00, src.m01, src.m02, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32); + // third row + float t20 = determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m31, src.m32, src.m33); + float t21 = -determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m30, src.m32, + src.m33); + float t22 = determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m30, src.m31, src.m33); + float t23 = -determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m30, src.m31, + src.m32); + // fourth row + float t30 = -determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m21, src.m22, + src.m23); + float t31 = determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m20, src.m22, src.m23); + float t32 = -determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m20, src.m21, + src.m23); + float t33 = determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m20, src.m21, src.m22); + + // transpose and divide by the determinant + dest.m00 = t00 * determinant_inv; + dest.m11 = t11 * determinant_inv; + dest.m22 = t22 * determinant_inv; + dest.m33 = t33 * determinant_inv; + dest.m01 = t10 * determinant_inv; + dest.m10 = t01 * determinant_inv; + dest.m20 = t02 * determinant_inv; + dest.m02 = t20 * determinant_inv; + dest.m12 = t21 * determinant_inv; + dest.m21 = t12 * determinant_inv; + dest.m03 = t30 * determinant_inv; + dest.m30 = t03 * determinant_inv; + dest.m13 = t31 * determinant_inv; + dest.m31 = t13 * determinant_inv; + dest.m32 = t23 * determinant_inv; + dest.m23 = t32 * determinant_inv; + return dest; + } else + return null; + } + + /** + * Copy the source matrix to the destination matrix + * + * @param src The source matrix + * @param dest The destination matrix, or null of a new one is to be created + * @return The copied matrix + */ + public static Matrix4f load(Matrix4f src, Matrix4f dest) { if (dest == null) dest = new Matrix4f(); - - dest.m00 = left.m00 - right.m00; - dest.m01 = left.m01 - right.m01; - dest.m02 = left.m02 - right.m02; - dest.m03 = left.m03 - right.m03; - dest.m10 = left.m10 - right.m10; - dest.m11 = left.m11 - right.m11; - dest.m12 = left.m12 - right.m12; - dest.m13 = left.m13 - right.m13; - dest.m20 = left.m20 - right.m20; - dest.m21 = left.m21 - right.m21; - dest.m22 = left.m22 - right.m22; - dest.m23 = left.m23 - right.m23; - dest.m30 = left.m30 - right.m30; - dest.m31 = left.m31 - right.m31; - dest.m32 = left.m32 - right.m32; - dest.m33 = left.m33 - right.m33; + dest.m00 = src.m00; + dest.m01 = src.m01; + dest.m02 = src.m02; + dest.m03 = src.m03; + dest.m10 = src.m10; + dest.m11 = src.m11; + dest.m12 = src.m12; + dest.m13 = src.m13; + dest.m20 = src.m20; + dest.m21 = src.m21; + dest.m22 = src.m22; + dest.m23 = src.m23; + dest.m30 = src.m30; + dest.m31 = src.m31; + dest.m32 = src.m32; + dest.m33 = src.m33; return dest; } /** * Multiply the right matrix by the left and place the result in a third matrix. - * @param left The left source matrix + * + * @param left The left source matrix * @param right The right source matrix - * @param dest The destination matrix, or null if a new one is to be created + * @param dest The destination matrix, or null if a new one is to be created * @return the destination matrix */ public static Matrix4f mul(Matrix4f left, Matrix4f right, Matrix4f dest) { @@ -486,118 +242,45 @@ public class Matrix4f extends Matrix implements Serializable { } /** - * Transform a Vector by a matrix and return the result in a destination - * vector. - * @param left The left matrix - * @param right The right vector - * @param dest The destination vector, or null if a new one is to be created - * @return the destination vector - */ - public static Vector4f transform(Matrix4f left, Vector4f right, Vector4f dest) { - if (dest == null) - dest = new Vector4f(); - - float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z + left.m30 * right.w; - float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z + left.m31 * right.w; - float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z + left.m32 * right.w; - float w = left.m03 * right.x + left.m13 * right.y + left.m23 * right.z + left.m33 * right.w; - - dest.x = x; - dest.y = y; - dest.z = z; - dest.w = w; - - return dest; - } - - /** - * Transpose this matrix - * @return this - */ - public Matrix transpose() { - return transpose(this); - } - - /** - * Translate this matrix - * @param vec The vector to translate by - * @return this - */ - public Matrix4f translate(Vector2f vec) { - return translate(vec, this); - } - - /** - * Translate this matrix - * @param vec The vector to translate by - * @return this - */ - public Matrix4f translate(Vector3f vec) { - return translate(vec, this); - } - - /** - * Scales this matrix - * @param vec The vector to scale by - * @return this - */ - public Matrix4f scale(Vector3f vec) { - return scale(vec, this, this); - } - - /** - * Scales the source matrix and put the result in the destination matrix - * @param vec The vector to scale by - * @param src The source matrix + * Negate this matrix and place the result in a destination matrix. + * + * @param src The source matrix * @param dest The destination matrix, or null if a new matrix is to be created - * @return The scaled matrix + * @return The negated matrix */ - public static Matrix4f scale(Vector3f vec, Matrix4f src, Matrix4f dest) { + public static Matrix4f negate(Matrix4f src, Matrix4f dest) { if (dest == null) dest = new Matrix4f(); - dest.m00 = src.m00 * vec.x; - dest.m01 = src.m01 * vec.x; - dest.m02 = src.m02 * vec.x; - dest.m03 = src.m03 * vec.x; - dest.m10 = src.m10 * vec.y; - dest.m11 = src.m11 * vec.y; - dest.m12 = src.m12 * vec.y; - dest.m13 = src.m13 * vec.y; - dest.m20 = src.m20 * vec.z; - dest.m21 = src.m21 * vec.z; - dest.m22 = src.m22 * vec.z; - dest.m23 = src.m23 * vec.z; + + dest.m00 = -src.m00; + dest.m01 = -src.m01; + dest.m02 = -src.m02; + dest.m03 = -src.m03; + dest.m10 = -src.m10; + dest.m11 = -src.m11; + dest.m12 = -src.m12; + dest.m13 = -src.m13; + dest.m20 = -src.m20; + dest.m21 = -src.m21; + dest.m22 = -src.m22; + dest.m23 = -src.m23; + dest.m30 = -src.m30; + dest.m31 = -src.m31; + dest.m32 = -src.m32; + dest.m33 = -src.m33; + return dest; } /** - * Rotates the matrix around the given axis the specified angle + * Rotates the source matrix around the given axis the specified angle and put + * the result in the destination matrix. + * * @param angle the angle, in radians. - * @param axis The vector representing the rotation axis. Must be normalized. - * @return this - */ - public Matrix4f rotate(float angle, Vector3f axis) { - return rotate(angle, axis, this); - } - - /** - * Rotates the matrix around the given axis the specified angle - * @param angle the angle, in radians. - * @param axis The vector representing the rotation axis. Must be normalized. - * @param dest The matrix to put the result, or null if a new matrix is to be created - * @return The rotated matrix - */ - public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { - return rotate(angle, axis, this, dest); - } - - /** - * Rotates the source matrix around the given axis the specified angle and - * put the result in the destination matrix. - * @param angle the angle, in radians. - * @param axis The vector representing the rotation axis. Must be normalized. - * @param src The matrix to rotate - * @param dest The matrix to put the result, or null if a new matrix is to be created + * @param axis The vector representing the rotation axis. Must be normalized. + * @param src The matrix to rotate + * @param dest The matrix to put the result, or null if a new matrix is to be + * created * @return The rotated matrix */ public static Matrix4f rotate(float angle, Vector3f axis, Matrix4f src, Matrix4f dest) { @@ -606,24 +289,24 @@ public class Matrix4f extends Matrix implements Serializable { float c = (float) Math.cos(angle); float s = (float) Math.sin(angle); float oneminusc = 1.0f - c; - float xy = axis.x*axis.y; - float yz = axis.y*axis.z; - float xz = axis.x*axis.z; - float xs = axis.x*s; - float ys = axis.y*s; - float zs = axis.z*s; + float xy = axis.x * axis.y; + float yz = axis.y * axis.z; + float xz = axis.x * axis.z; + float xs = axis.x * s; + float ys = axis.y * s; + float zs = axis.z * s; - float f00 = axis.x*axis.x*oneminusc+c; - float f01 = xy*oneminusc+zs; - float f02 = xz*oneminusc-ys; + float f00 = axis.x * axis.x * oneminusc + c; + float f01 = xy * oneminusc + zs; + float f02 = xz * oneminusc - ys; // n[3] not used - float f10 = xy*oneminusc-zs; - float f11 = axis.y*axis.y*oneminusc+c; - float f12 = yz*oneminusc+xs; + float f10 = xy * oneminusc - zs; + float f11 = axis.y * axis.y * oneminusc + c; + float f12 = yz * oneminusc + xs; // n[7] not used - float f20 = xz*oneminusc+ys; - float f21 = yz*oneminusc-xs; - float f22 = axis.z*axis.z*oneminusc+c; + float f20 = xz * oneminusc + ys; + float f21 = yz * oneminusc - xs; + float f22 = axis.z * axis.z * oneminusc + c; float t00 = src.m00 * f00 + src.m10 * f01 + src.m20 * f02; float t01 = src.m01 * f00 + src.m11 * f01 + src.m21 * f02; @@ -649,48 +332,148 @@ public class Matrix4f extends Matrix implements Serializable { } /** - * Translate this matrix and stash the result in another matrix - * @param vec The vector to translate by - * @param dest The destination matrix or null if a new matrix is to be created - * @return the translated matrix + * Scales the source matrix and put the result in the destination matrix + * + * @param vec The vector to scale by + * @param src The source matrix + * @param dest The destination matrix, or null if a new matrix is to be created + * @return The scaled matrix */ - public Matrix4f translate(Vector3f vec, Matrix4f dest) { - return translate(vec, this, dest); + public static Matrix4f scale(Vector3f vec, Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + dest.m00 = src.m00 * vec.x; + dest.m01 = src.m01 * vec.x; + dest.m02 = src.m02 * vec.x; + dest.m03 = src.m03 * vec.x; + dest.m10 = src.m10 * vec.y; + dest.m11 = src.m11 * vec.y; + dest.m12 = src.m12 * vec.y; + dest.m13 = src.m13 * vec.y; + dest.m20 = src.m20 * vec.z; + dest.m21 = src.m21 * vec.z; + dest.m22 = src.m22 * vec.z; + dest.m23 = src.m23 * vec.z; + return dest; } /** - * Translate the source matrix and stash the result in the destination matrix - * @param vec The vector to translate by - * @param src The source matrix - * @param dest The destination matrix or null if a new matrix is to be created - * @return The translated matrix + * Set the given matrix to be the identity matrix. + * + * @param m The matrix to set to the identity + * @return m */ - public static Matrix4f translate(Vector3f vec, Matrix4f src, Matrix4f dest) { + public static Matrix4f setIdentity(Matrix4f m) { + m.m00 = 1.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m03 = 0.0f; + m.m10 = 0.0f; + m.m11 = 1.0f; + m.m12 = 0.0f; + m.m13 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 1.0f; + m.m23 = 0.0f; + m.m30 = 0.0f; + m.m31 = 0.0f; + m.m32 = 0.0f; + m.m33 = 1.0f; + + return m; + } + + /** + * Set the given matrix to 0. + * + * @param m The matrix to set to 0 + * @return m + */ + public static Matrix4f setZero(Matrix4f m) { + m.m00 = 0.0f; + m.m01 = 0.0f; + m.m02 = 0.0f; + m.m03 = 0.0f; + m.m10 = 0.0f; + m.m11 = 0.0f; + m.m12 = 0.0f; + m.m13 = 0.0f; + m.m20 = 0.0f; + m.m21 = 0.0f; + m.m22 = 0.0f; + m.m23 = 0.0f; + m.m30 = 0.0f; + m.m31 = 0.0f; + m.m32 = 0.0f; + m.m33 = 0.0f; + + return m; + } + + /** + * Subtract the right matrix from the left and place the result in a third + * matrix. + * + * @param left The left source matrix + * @param right The right source matrix + * @param dest The destination matrix, or null if a new one is to be created + * @return the destination matrix + */ + public static Matrix4f sub(Matrix4f left, Matrix4f right, Matrix4f dest) { if (dest == null) dest = new Matrix4f(); - dest.m30 += src.m00 * vec.x + src.m10 * vec.y + src.m20 * vec.z; - dest.m31 += src.m01 * vec.x + src.m11 * vec.y + src.m21 * vec.z; - dest.m32 += src.m02 * vec.x + src.m12 * vec.y + src.m22 * vec.z; - dest.m33 += src.m03 * vec.x + src.m13 * vec.y + src.m23 * vec.z; + dest.m00 = left.m00 - right.m00; + dest.m01 = left.m01 - right.m01; + dest.m02 = left.m02 - right.m02; + dest.m03 = left.m03 - right.m03; + dest.m10 = left.m10 - right.m10; + dest.m11 = left.m11 - right.m11; + dest.m12 = left.m12 - right.m12; + dest.m13 = left.m13 - right.m13; + dest.m20 = left.m20 - right.m20; + dest.m21 = left.m21 - right.m21; + dest.m22 = left.m22 - right.m22; + dest.m23 = left.m23 - right.m23; + dest.m30 = left.m30 - right.m30; + dest.m31 = left.m31 - right.m31; + dest.m32 = left.m32 - right.m32; + dest.m33 = left.m33 - right.m33; return dest; } /** - * Translate this matrix and stash the result in another matrix - * @param vec The vector to translate by - * @param dest The destination matrix or null if a new matrix is to be created - * @return the translated matrix + * Transform a Vector by a matrix and return the result in a destination vector. + * + * @param left The left matrix + * @param right The right vector + * @param dest The destination vector, or null if a new one is to be created + * @return the destination vector */ - public Matrix4f translate(Vector2f vec, Matrix4f dest) { - return translate(vec, this, dest); + public static Vector4f transform(Matrix4f left, Vector4f right, Vector4f dest) { + if (dest == null) + dest = new Vector4f(); + + float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z + left.m30 * right.w; + float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z + left.m31 * right.w; + float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z + left.m32 * right.w; + float w = left.m03 * right.x + left.m13 * right.y + left.m23 * right.z + left.m33 * right.w; + + dest.x = x; + dest.y = y; + dest.z = z; + dest.w = w; + + return dest; } /** * Translate the source matrix and stash the result in the destination matrix - * @param vec The vector to translate by - * @param src The source matrix + * + * @param vec The vector to translate by + * @param src The source matrix * @param dest The destination matrix or null if a new matrix is to be created * @return The translated matrix */ @@ -707,23 +490,35 @@ public class Matrix4f extends Matrix implements Serializable { } /** - * Transpose this matrix and place the result in another matrix + * Translate the source matrix and stash the result in the destination matrix + * + * @param vec The vector to translate by + * @param src The source matrix * @param dest The destination matrix or null if a new matrix is to be created - * @return the transposed matrix + * @return The translated matrix */ - public Matrix4f transpose(Matrix4f dest) { - return transpose(this, dest); + public static Matrix4f translate(Vector3f vec, Matrix4f src, Matrix4f dest) { + if (dest == null) + dest = new Matrix4f(); + + dest.m30 += src.m00 * vec.x + src.m10 * vec.y + src.m20 * vec.z; + dest.m31 += src.m01 * vec.x + src.m11 * vec.y + src.m21 * vec.z; + dest.m32 += src.m02 * vec.x + src.m12 * vec.y + src.m22 * vec.z; + dest.m33 += src.m03 * vec.x + src.m13 * vec.y + src.m23 * vec.z; + + return dest; } /** * Transpose the source matrix and place the result in the destination matrix - * @param src The source matrix + * + * @param src The source matrix * @param dest The destination matrix or null if a new matrix is to be created * @return the transposed matrix */ public static Matrix4f transpose(Matrix4f src, Matrix4f dest) { if (dest == null) - dest = new Matrix4f(); + dest = new Matrix4f(); float m00 = src.m00; float m01 = src.m10; float m02 = src.m20; @@ -761,50 +556,43 @@ public class Matrix4f extends Matrix implements Serializable { return dest; } + public float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33; + + /** + * Construct a new matrix, initialized to the identity. + */ + public Matrix4f() { + super(); + setIdentity(); + } + + public Matrix4f(final Matrix4f src) { + super(); + load(src); + } + /** * @return the determinant of the matrix */ public float determinant() { - float f = - m00 - * ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32) - - m13 * m22 * m31 - - m11 * m23 * m32 - - m12 * m21 * m33); - f -= m01 - * ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32) - - m13 * m22 * m30 - - m10 * m23 * m32 + float f = m00 * ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32) - m13 * m22 * m31 - m11 * m23 * m32 + - m12 * m21 * m33); + f -= m01 * ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32) - m13 * m22 * m30 - m10 * m23 * m32 - m12 * m20 * m33); - f += m02 - * ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31) - - m13 * m21 * m30 - - m10 * m23 * m31 + f += m02 * ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31) - m13 * m21 * m30 - m10 * m23 * m31 - m11 * m20 * m33); - f -= m03 - * ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31) - - m12 * m21 * m30 - - m10 * m22 * m31 + f -= m03 * ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31) - m12 * m21 * m30 - m10 * m22 * m31 - m11 * m20 * m32); return f; } - /** - * Calculate the determinant of a 3x3 matrix - * @return result - */ - - private static float determinant3x3(float t00, float t01, float t02, - float t10, float t11, float t12, - float t20, float t21, float t22) - { - return t00 * (t11 * t22 - t12 * t21) - + t01 * (t12 * t20 - t10 * t22) - + t02 * (t10 * t21 - t11 * t20); + public boolean equals(Object m) { + return (m instanceof Matrix4f) && equal(this, (Matrix4f) m); } /** * Invert this matrix + * * @return this if successful, null otherwise */ public Matrix invert() { @@ -812,70 +600,105 @@ public class Matrix4f extends Matrix implements Serializable { } /** - * Invert the source matrix and put the result in the destination - * @param src The source matrix - * @param dest The destination matrix, or null if a new matrix is to be created - * @return The inverted matrix if successful, null otherwise + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float array to read from + * @return this */ - public static Matrix4f invert(Matrix4f src, Matrix4f dest) { - float determinant = src.determinant(); + public Matrix load(float[] buf) { - if (determinant != 0) { - /* - * m00 m01 m02 m03 - * m10 m11 m12 m13 - * m20 m21 m22 m23 - * m30 m31 m32 m33 - */ - if (dest == null) - dest = new Matrix4f(); - float determinant_inv = 1f/determinant; + m00 = buf[0]; + m01 = buf[1]; + m02 = buf[2]; + m03 = buf[3]; + m10 = buf[4]; + m11 = buf[5]; + m12 = buf[6]; + m13 = buf[7]; + m20 = buf[8]; + m21 = buf[9]; + m22 = buf[10]; + m23 = buf[11]; + m30 = buf[12]; + m31 = buf[13]; + m32 = buf[14]; + m33 = buf[15]; - // first row - float t00 = determinant3x3(src.m11, src.m12, src.m13, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33); - float t01 = -determinant3x3(src.m10, src.m12, src.m13, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33); - float t02 = determinant3x3(src.m10, src.m11, src.m13, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33); - float t03 = -determinant3x3(src.m10, src.m11, src.m12, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32); - // second row - float t10 = -determinant3x3(src.m01, src.m02, src.m03, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33); - float t11 = determinant3x3(src.m00, src.m02, src.m03, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33); - float t12 = -determinant3x3(src.m00, src.m01, src.m03, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33); - float t13 = determinant3x3(src.m00, src.m01, src.m02, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32); - // third row - float t20 = determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m31, src.m32, src.m33); - float t21 = -determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m30, src.m32, src.m33); - float t22 = determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m30, src.m31, src.m33); - float t23 = -determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m30, src.m31, src.m32); - // fourth row - float t30 = -determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m21, src.m22, src.m23); - float t31 = determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m20, src.m22, src.m23); - float t32 = -determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m20, src.m21, src.m23); - float t33 = determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m20, src.m21, src.m22); + return this; + } - // transpose and divide by the determinant - dest.m00 = t00*determinant_inv; - dest.m11 = t11*determinant_inv; - dest.m22 = t22*determinant_inv; - dest.m33 = t33*determinant_inv; - dest.m01 = t10*determinant_inv; - dest.m10 = t01*determinant_inv; - dest.m20 = t02*determinant_inv; - dest.m02 = t20*determinant_inv; - dest.m12 = t21*determinant_inv; - dest.m21 = t12*determinant_inv; - dest.m03 = t30*determinant_inv; - dest.m30 = t03*determinant_inv; - dest.m13 = t31*determinant_inv; - dest.m31 = t13*determinant_inv; - dest.m32 = t23*determinant_inv; - dest.m23 = t32*determinant_inv; - return dest; - } else - return null; + /** + * Load from a float buffer. The buffer stores the matrix in column major + * (OpenGL) order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix load(FloatBuffer buf) { + + m00 = buf.get(); + m01 = buf.get(); + m02 = buf.get(); + m03 = buf.get(); + m10 = buf.get(); + m11 = buf.get(); + m12 = buf.get(); + m13 = buf.get(); + m20 = buf.get(); + m21 = buf.get(); + m22 = buf.get(); + m23 = buf.get(); + m30 = buf.get(); + m31 = buf.get(); + m32 = buf.get(); + m33 = buf.get(); + + return this; + } + + /** + * Load from another matrix4f + * + * @param src The source matrix + * @return this + */ + public Matrix4f load(Matrix4f src) { + return load(src, this); + } + + /** + * Load from a float buffer. The buffer stores the matrix in row major (maths) + * order. + * + * @param buf A float buffer to read from + * @return this + */ + public Matrix loadTranspose(FloatBuffer buf) { + + m00 = buf.get(); + m10 = buf.get(); + m20 = buf.get(); + m30 = buf.get(); + m01 = buf.get(); + m11 = buf.get(); + m21 = buf.get(); + m31 = buf.get(); + m02 = buf.get(); + m12 = buf.get(); + m22 = buf.get(); + m32 = buf.get(); + m03 = buf.get(); + m13 = buf.get(); + m23 = buf.get(); + m33 = buf.get(); + + return this; } /** * Negate this matrix + * * @return this */ public Matrix negate() { @@ -884,6 +707,7 @@ public class Matrix4f extends Matrix implements Serializable { /** * Negate this matrix and place the result in a destination matrix. + * * @param dest The destination matrix, or null if a new matrix is to be created * @return the negated matrix */ @@ -892,55 +716,241 @@ public class Matrix4f extends Matrix implements Serializable { } /** - * Negate this matrix and place the result in a destination matrix. - * @param src The source matrix - * @param dest The destination matrix, or null if a new matrix is to be created - * @return The negated matrix + * Rotates the matrix around the given axis the specified angle + * + * @param angle the angle, in radians. + * @param axis The vector representing the rotation axis. Must be normalized. + * @return this */ - public static Matrix4f negate(Matrix4f src, Matrix4f dest) { - if (dest == null) - dest = new Matrix4f(); - - dest.m00 = -src.m00; - dest.m01 = -src.m01; - dest.m02 = -src.m02; - dest.m03 = -src.m03; - dest.m10 = -src.m10; - dest.m11 = -src.m11; - dest.m12 = -src.m12; - dest.m13 = -src.m13; - dest.m20 = -src.m20; - dest.m21 = -src.m21; - dest.m22 = -src.m22; - dest.m23 = -src.m23; - dest.m30 = -src.m30; - dest.m31 = -src.m31; - dest.m32 = -src.m32; - dest.m33 = -src.m33; - - return dest; + public Matrix4f rotate(float angle, Vector3f axis) { + return rotate(angle, axis, this); } - - public boolean equals(Object m) { - return (m instanceof Matrix4f) && equal(this, (Matrix4f)m); + + /** + * Rotates the matrix around the given axis the specified angle + * + * @param angle the angle, in radians. + * @param axis The vector representing the rotation axis. Must be normalized. + * @param dest The matrix to put the result, or null if a new matrix is to be + * created + * @return The rotated matrix + */ + public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) { + return rotate(angle, axis, this, dest); } - - public static boolean equal(Matrix4f a, Matrix4f b) { - return a.m00 == b.m00 && - a.m01 == b.m01 && - a.m02 == b.m02 && - a.m03 == b.m03 && - a.m10 == b.m10 && - a.m11 == b.m11 && - a.m12 == b.m12 && - a.m13 == b.m13 && - a.m20 == b.m20 && - a.m21 == b.m21 && - a.m22 == b.m22 && - a.m23 == b.m23 && - a.m30 == b.m30 && - a.m31 == b.m31 && - a.m32 == b.m32 && - a.m33 == b.m33; + + /** + * Scales this matrix + * + * @param vec The vector to scale by + * @return this + */ + public Matrix4f scale(Vector3f vec) { + return scale(vec, this, this); + } + + /** + * Set this matrix to be the identity matrix. + * + * @return this + */ + public Matrix setIdentity() { + return setIdentity(this); + } + + /** + * Set this matrix to 0. + * + * @return this + */ + public Matrix setZero() { + return setZero(this); + } + + /** + * eagler + */ + public Matrix store(ByteBuffer buf) { + buf.putFloat(m00); + buf.putFloat(m01); + buf.putFloat(m02); + buf.putFloat(m03); + buf.putFloat(m10); + buf.putFloat(m11); + buf.putFloat(m12); + buf.putFloat(m13); + buf.putFloat(m20); + buf.putFloat(m21); + buf.putFloat(m22); + buf.putFloat(m23); + buf.putFloat(m30); + buf.putFloat(m31); + buf.putFloat(m32); + buf.putFloat(m33); + return this; + } + + public Matrix store(float[] buf) { + buf[0] = m00; + buf[1] = m01; + buf[2] = m02; + buf[3] = m03; + buf[4] = m10; + buf[5] = m11; + buf[6] = m12; + buf[7] = m13; + buf[8] = m20; + buf[9] = m21; + buf[10] = m22; + buf[11] = m23; + buf[12] = m30; + buf[13] = m31; + buf[14] = m32; + buf[15] = m33; + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in column major + * (openGL) order. + * + * @param buf The buffer to store this matrix in + */ + public Matrix store(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m02); + buf.put(m03); + buf.put(m10); + buf.put(m11); + buf.put(m12); + buf.put(m13); + buf.put(m20); + buf.put(m21); + buf.put(m22); + buf.put(m23); + buf.put(m30); + buf.put(m31); + buf.put(m32); + buf.put(m33); + return this; + } + + /** + * Store the rotation portion of this matrix in a float buffer. The matrix is + * stored in column major (openGL) order. + * + * @param buf The buffer to store this matrix in + */ + public Matrix store3f(FloatBuffer buf) { + buf.put(m00); + buf.put(m01); + buf.put(m02); + buf.put(m10); + buf.put(m11); + buf.put(m12); + buf.put(m20); + buf.put(m21); + buf.put(m22); + return this; + } + + /** + * Store this matrix in a float buffer. The matrix is stored in row major + * (maths) order. + * + * @param buf The buffer to store this matrix in + */ + public Matrix storeTranspose(FloatBuffer buf) { + buf.put(m00); + buf.put(m10); + buf.put(m20); + buf.put(m30); + buf.put(m01); + buf.put(m11); + buf.put(m21); + buf.put(m31); + buf.put(m02); + buf.put(m12); + buf.put(m22); + buf.put(m32); + buf.put(m03); + buf.put(m13); + buf.put(m23); + buf.put(m33); + return this; + } + + /** + * Returns a string representation of this matrix + */ + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append(m30).append('\n'); + buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append(m31).append('\n'); + buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append(m32).append('\n'); + buf.append(m03).append(' ').append(m13).append(' ').append(m23).append(' ').append(m33).append('\n'); + return buf.toString(); + } + + /** + * Translate this matrix + * + * @param vec The vector to translate by + * @return this + */ + public Matrix4f translate(Vector2f vec) { + return translate(vec, this); + } + + /** + * Translate this matrix and stash the result in another matrix + * + * @param vec The vector to translate by + * @param dest The destination matrix or null if a new matrix is to be created + * @return the translated matrix + */ + public Matrix4f translate(Vector2f vec, Matrix4f dest) { + return translate(vec, this, dest); + } + + /** + * Translate this matrix + * + * @param vec The vector to translate by + * @return this + */ + public Matrix4f translate(Vector3f vec) { + return translate(vec, this); + } + + /** + * Translate this matrix and stash the result in another matrix + * + * @param vec The vector to translate by + * @param dest The destination matrix or null if a new matrix is to be created + * @return the translated matrix + */ + public Matrix4f translate(Vector3f vec, Matrix4f dest) { + return translate(vec, this, dest); + } + + /** + * Transpose this matrix + * + * @return this + */ + public Matrix transpose() { + return transpose(this); + } + + /** + * Transpose this matrix and place the result in another matrix + * + * @param dest The destination matrix or null if a new matrix is to be created + * @return the transposed matrix + */ + public Matrix4f transpose(Matrix4f dest) { + return transpose(this, dest); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Quaternion.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Quaternion.java index 3697b4f7..9dbc4ed9 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Quaternion.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Quaternion.java @@ -45,6 +45,156 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; public class Quaternion extends Vector implements ReadableVector4f { private static final long serialVersionUID = 1L; + /** + * The dot product of two quaternions + * + * @param left The LHS quat + * @param right The RHS quat + * @return left dot right + */ + public static float dot(Quaternion left, Quaternion right) { + return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; + } + + /** + * Sets the value of this quaternion to the quaternion product of quaternions + * left and right (this = left * right). Note that this is safe for aliasing + * (e.g. this can be left or right). + * + * @param left the first quaternion + * @param right the second quaternion + */ + public static Quaternion mul(Quaternion left, Quaternion right, Quaternion dest) { + if (dest == null) + dest = new Quaternion(); + dest.set(left.x * right.w + left.w * right.x + left.y * right.z - left.z * right.y, + left.y * right.w + left.w * right.y + left.z * right.x - left.x * right.z, + left.z * right.w + left.w * right.z + left.x * right.y - left.y * right.x, + left.w * right.w - left.x * right.x - left.y * right.y - left.z * right.z); + return dest; + } + + /** + * + * Multiplies quaternion left by the inverse of quaternion right and places the + * value into this quaternion. The value of both argument quaternions is + * preservered (this = left * right^-1). + * + * @param left the left quaternion + * @param right the right quaternion + */ + public static Quaternion mulInverse(Quaternion left, Quaternion right, Quaternion dest) { + float n = right.lengthSquared(); + // zero-div may occur. + n = (n == 0.0 ? n : 1 / n); + // store on stack once for aliasing-safty + if (dest == null) + dest = new Quaternion(); + dest.set((left.x * right.w - left.w * right.x - left.y * right.z + left.z * right.y) * n, + (left.y * right.w - left.w * right.y - left.z * right.x + left.x * right.z) * n, + (left.z * right.w - left.w * right.z - left.x * right.y + left.y * right.x) * n, + (left.w * right.w + left.x * right.x + left.y * right.y + left.z * right.z) * n); + + return dest; + } + + /** + * Calculate the conjugate of this quaternion and put it into the given one + * + * @param src The source quaternion + * @param dest The quaternion which should be set to the conjugate of this + * quaternion + */ + public static Quaternion negate(Quaternion src, Quaternion dest) { + if (dest == null) + dest = new Quaternion(); + + dest.x = -src.x; + dest.y = -src.y; + dest.z = -src.z; + dest.w = src.w; + + return dest; + } + + /** + * Normalise the source quaternion and place the result in another quaternion. + * + * @param src The source quaternion + * @param dest The destination quaternion, or null if a new quaternion is to be + * created + * @return The normalised quaternion + */ + public static Quaternion normalise(Quaternion src, Quaternion dest) { + float inv_l = 1f / src.length(); + + if (dest == null) + dest = new Quaternion(); + + dest.set(src.x * inv_l, src.y * inv_l, src.z * inv_l, src.w * inv_l); + + return dest; + } + + /** + * Scale the source quaternion by scale and put the result in the destination + * + * @param scale The amount to scale by + * @param src The source quaternion + * @param dest The destination quaternion, or null if a new quaternion is to be + * created + * @return The scaled quaternion + */ + public static Quaternion scale(float scale, Quaternion src, Quaternion dest) { + if (dest == null) + dest = new Quaternion(); + dest.x = src.x * scale; + dest.y = src.y * scale; + dest.z = src.z * scale; + dest.w = src.w * scale; + return dest; + } + + /** + * Sets the value of the source quaternion using the rotational component of the + * passed matrix. + * + * @param m The source matrix + * @param q The destination quaternion, or null if a new quaternion is to be + * created + * @return q + */ + public static Quaternion setFromMatrix(Matrix3f m, Quaternion q) { + return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, m.m21, m.m22); + } + + /** + * Sets the value of the source quaternion using the rotational component of the + * passed matrix. + * + * @param m The source matrix + * @param q The destination quaternion, or null if a new quaternion is to be + * created + * @return q + */ + public static Quaternion setFromMatrix(Matrix4f m, Quaternion q) { + return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, m.m21, m.m22); + } + + /** + * Set the given quaternion to the multiplication identity. + * + * @param q The quaternion + * @return q + */ + public static Quaternion setIdentity(Quaternion q) { + q.x = 0; + q.y = 0; + q.z = 0; + q.w = 1; + return q; + } + public float x, y, z, w; /** @@ -55,6 +205,14 @@ public class Quaternion extends Vector implements ReadableVector4f { setIdentity(); } + /** + * C'tor + * + */ + public Quaternion(float x, float y, float z, float w) { + set(x, y, z, w); + } + /** * C'tor * @@ -64,12 +222,93 @@ public class Quaternion extends Vector implements ReadableVector4f { set(src); } - /** - * C'tor + /* + * (Overrides) * + * @see org.lwjgl.vector.ReadableVector3f#getW() */ - public Quaternion(float x, float y, float z, float w) { - set(x, y, z, w); + public float getW() { + return w; + } + + /** + * @return x + */ + public final float getX() { + return x; + } + + /** + * @return y + */ + public final float getY() { + return y; + } + + /* + * (Overrides) + * + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getZ() { + return z; + } + + /** + * @return the length squared of the quaternion + */ + public float lengthSquared() { + return x * x + y * y + z * z + w * w; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.Vector#load(java.nio.FloatBuffer) + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + z = buf.get(); + w = buf.get(); + return this; + } + + /** + * Calculate the conjugate of this quaternion + */ + public Vector negate() { + return negate(this, this); + } + + /** + * Calculate the conjugate of this quaternion and put it into the given one + * + * @param dest The quaternion which should be set to the conjugate of this + * quaternion + */ + public Quaternion negate(Quaternion dest) { + return negate(this, dest); + } + + /** + * Normalise this quaternion and place the result in another quaternion. + * + * @param dest The destination quaternion, or null if a new quaternion is to be + * created + * @return the normalised quaternion + */ + public Quaternion normalise(Quaternion dest) { + return normalise(this, dest); + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + return scale(scale, this, this); } /* @@ -96,8 +335,7 @@ public class Quaternion extends Vector implements ReadableVector4f { /* * (non-Javadoc) * - * @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, - * float) + * @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float) */ public void set(float x, float y, float z, float w) { this.x = x; @@ -109,8 +347,7 @@ public class Quaternion extends Vector implements ReadableVector4f { /** * Load from another Vector4f * - * @param src - * The source vector + * @param src The source vector * @return this */ public Quaternion set(ReadableVector4f src) { @@ -121,303 +358,11 @@ public class Quaternion extends Vector implements ReadableVector4f { return this; } - /** - * Set this quaternion to the multiplication identity. - * @return this - */ - public Quaternion setIdentity() { - return setIdentity(this); - } - - /** - * Set the given quaternion to the multiplication identity. - * @param q The quaternion - * @return q - */ - public static Quaternion setIdentity(Quaternion q) { - q.x = 0; - q.y = 0; - q.z = 0; - q.w = 1; - return q; - } - - /** - * @return the length squared of the quaternion - */ - public float lengthSquared() { - return x * x + y * y + z * z + w * w; - } - - /** - * Normalise the source quaternion and place the result in another quaternion. - * - * @param src - * The source quaternion - * @param dest - * The destination quaternion, or null if a new quaternion is to be - * created - * @return The normalised quaternion - */ - public static Quaternion normalise(Quaternion src, Quaternion dest) { - float inv_l = 1f/src.length(); - - if (dest == null) - dest = new Quaternion(); - - dest.set(src.x * inv_l, src.y * inv_l, src.z * inv_l, src.w * inv_l); - - return dest; - } - - /** - * Normalise this quaternion and place the result in another quaternion. - * - * @param dest - * The destination quaternion, or null if a new quaternion is to be - * created - * @return the normalised quaternion - */ - public Quaternion normalise(Quaternion dest) { - return normalise(this, dest); - } - - /** - * The dot product of two quaternions - * - * @param left - * The LHS quat - * @param right - * The RHS quat - * @return left dot right - */ - public static float dot(Quaternion left, Quaternion right) { - return left.x * right.x + left.y * right.y + left.z * right.z + left.w - * right.w; - } - - /** - * Calculate the conjugate of this quaternion and put it into the given one - * - * @param dest - * The quaternion which should be set to the conjugate of this - * quaternion - */ - public Quaternion negate(Quaternion dest) { - return negate(this, dest); - } - - /** - * Calculate the conjugate of this quaternion and put it into the given one - * - * @param src - * The source quaternion - * @param dest - * The quaternion which should be set to the conjugate of this - * quaternion - */ - public static Quaternion negate(Quaternion src, Quaternion dest) { - if (dest == null) - dest = new Quaternion(); - - dest.x = -src.x; - dest.y = -src.y; - dest.z = -src.z; - dest.w = src.w; - - return dest; - } - - /** - * Calculate the conjugate of this quaternion - */ - public Vector negate() { - return negate(this, this); - } - - /* (non-Javadoc) - * @see org.lwjgl.util.vector.Vector#load(java.nio.FloatBuffer) - */ - public Vector load(FloatBuffer buf) { - x = buf.get(); - y = buf.get(); - z = buf.get(); - w = buf.get(); - return this; - } - - /* - * (non-Javadoc) - * - * @see org.lwjgl.vector.Vector#scale(float) - */ - public Vector scale(float scale) { - return scale(scale, this, this); - } - - /** - * Scale the source quaternion by scale and put the result in the destination - * @param scale The amount to scale by - * @param src The source quaternion - * @param dest The destination quaternion, or null if a new quaternion is to be created - * @return The scaled quaternion - */ - public static Quaternion scale(float scale, Quaternion src, Quaternion dest) { - if (dest == null) - dest = new Quaternion(); - dest.x = src.x * scale; - dest.y = src.y * scale; - dest.z = src.z * scale; - dest.w = src.w * scale; - return dest; - } - - /* (non-Javadoc) - * @see org.lwjgl.util.vector.ReadableVector#store(java.nio.FloatBuffer) - */ - public Vector store(FloatBuffer buf) { - buf.put(x); - buf.put(y); - buf.put(z); - buf.put(w); - - return this; - } - - /** - * @return x - */ - public final float getX() { - return x; - } - - /** - * @return y - */ - public final float getY() { - return y; - } - - /** - * Set X - * - * @param x - */ - public final void setX(float x) { - this.x = x; - } - - /** - * Set Y - * - * @param y - */ - public final void setY(float y) { - this.y = y; - } - - /** - * Set Z - * - * @param z - */ - public void setZ(float z) { - this.z = z; - } - - /* - * (Overrides) - * - * @see org.lwjgl.vector.ReadableVector3f#getZ() - */ - public float getZ() { - return z; - } - - /** - * Set W - * - * @param w - */ - public void setW(float w) { - this.w = w; - } - - /* - * (Overrides) - * - * @see org.lwjgl.vector.ReadableVector3f#getW() - */ - public float getW() { - return w; - } - - public String toString() { - return "Quaternion: " + x + " " + y + " " + z + " " + w; - } - - /** - * Sets the value of this quaternion to the quaternion product of - * quaternions left and right (this = left * right). Note that this is safe - * for aliasing (e.g. this can be left or right). - * - * @param left - * the first quaternion - * @param right - * the second quaternion - */ - public static Quaternion mul(Quaternion left, Quaternion right, - Quaternion dest) { - if (dest == null) - dest = new Quaternion(); - dest.set(left.x * right.w + left.w * right.x + left.y * right.z - - left.z * right.y, left.y * right.w + left.w * right.y - + left.z * right.x - left.x * right.z, left.z * right.w - + left.w * right.z + left.x * right.y - left.y * right.x, - left.w * right.w - left.x * right.x - left.y * right.y - - left.z * right.z); - return dest; - } - - /** - * - * Multiplies quaternion left by the inverse of quaternion right and places - * the value into this quaternion. The value of both argument quaternions is - * preservered (this = left * right^-1). - * - * @param left - * the left quaternion - * @param right - * the right quaternion - */ - public static Quaternion mulInverse(Quaternion left, Quaternion right, - Quaternion dest) { - float n = right.lengthSquared(); - // zero-div may occur. - n = (n == 0.0 ? n : 1 / n); - // store on stack once for aliasing-safty - if (dest == null) - dest = new Quaternion(); - dest - .set((left.x * right.w - left.w * right.x - left.y - * right.z + left.z * right.y) - * n, (left.y * right.w - left.w * right.y - left.z - * right.x + left.x * right.z) - * n, (left.z * right.w - left.w * right.z - left.x - * right.y + left.y * right.x) - * n, (left.w * right.w + left.x * right.x + left.y - * right.y + left.z * right.z) - * n); - - return dest; - } - /** * Sets the value of this quaternion to the equivalent rotation of the * Axis-Angle argument. * - * @param a1 - * the axis-angle: (x,y,z) is the axis and w is the angle + * @param a1 the axis-angle: (x,y,z) is the axis and w is the angle */ public final void setFromAxisAngle(Vector4f a1) { x = a1.x; @@ -432,64 +377,11 @@ public class Quaternion extends Vector implements ReadableVector4f { w = (float) Math.cos(0.5 * a1.w); } - /** - * Sets the value of this quaternion using the rotational component of the - * passed matrix. - * - * @param m - * The matrix - * @return this - */ - public final Quaternion setFromMatrix(Matrix4f m) { - return setFromMatrix(m, this); - } - - /** - * Sets the value of the source quaternion using the rotational component of the - * passed matrix. - * - * @param m - * The source matrix - * @param q - * The destination quaternion, or null if a new quaternion is to be created - * @return q - */ - public static Quaternion setFromMatrix(Matrix4f m, Quaternion q) { - return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, - m.m21, m.m22); - } - - /** - * Sets the value of this quaternion using the rotational component of the - * passed matrix. - * - * @param m - * The source matrix - */ - public final Quaternion setFromMatrix(Matrix3f m) { - return setFromMatrix(m, this); - } - - /** - * Sets the value of the source quaternion using the rotational component of the - * passed matrix. - * - * @param m - * The source matrix - * @param q - * The destination quaternion, or null if a new quaternion is to be created - * @return q - */ - public static Quaternion setFromMatrix(Matrix3f m, Quaternion q) { - return q.setFromMat(m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, - m.m21, m.m22); - } - /** * Private method to perform the matrix-to-quaternion conversion */ - private Quaternion setFromMat(float m00, float m01, float m02, float m10, - float m11, float m12, float m20, float m21, float m22) { + private Quaternion setFromMat(float m00, float m01, float m02, float m10, float m11, float m12, float m20, + float m21, float m22) { float s; float tr = m00 + m11 + m22; @@ -527,4 +419,88 @@ public class Quaternion extends Vector implements ReadableVector4f { } return this; } + + /** + * Sets the value of this quaternion using the rotational component of the + * passed matrix. + * + * @param m The source matrix + */ + public final Quaternion setFromMatrix(Matrix3f m) { + return setFromMatrix(m, this); + } + + /** + * Sets the value of this quaternion using the rotational component of the + * passed matrix. + * + * @param m The matrix + * @return this + */ + public final Quaternion setFromMatrix(Matrix4f m) { + return setFromMatrix(m, this); + } + + /** + * Set this quaternion to the multiplication identity. + * + * @return this + */ + public Quaternion setIdentity() { + return setIdentity(this); + } + + /** + * Set W + * + * @param w + */ + public void setW(float w) { + this.w = w; + } + + /** + * Set X + * + * @param x + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Set Y + * + * @param y + */ + public final void setY(float y) { + this.y = y; + } + + /** + * Set Z + * + * @param z + */ + public void setZ(float z) { + this.z = z; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.ReadableVector#store(java.nio.FloatBuffer) + */ + public Vector store(FloatBuffer buf) { + buf.put(x); + buf.put(y); + buf.put(z); + buf.put(w); + + return this; + } + + public String toString() { + return "Quaternion: " + x + " " + y + " " + z + " " + w; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector.java index 912185ad..92d4f493 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector.java @@ -41,12 +41,15 @@ public interface ReadableVector { * @return the length of the vector */ float length(); + /** * @return the length squared of the vector */ float lengthSquared(); + /** * Store this vector in a FloatBuffer + * * @param buf The buffer to store it in, at the current position * @return this */ diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector2f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector2f.java index 16f7aa72..579bf7ab 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector2f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/ReadableVector2f.java @@ -39,6 +39,7 @@ public interface ReadableVector2f extends ReadableVector { * @return x */ float getX(); + /** * @return y */ diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector.java index 86611a77..e41a527e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -39,8 +40,7 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * Base class for vectors. * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public abstract class Vector implements Serializable, ReadableVector { @@ -58,7 +58,6 @@ public abstract class Vector implements Serializable, ReadableVector { return (float) Math.sqrt(lengthSquared()); } - /** * @return the length squared of the vector */ @@ -66,6 +65,7 @@ public abstract class Vector implements Serializable, ReadableVector { /** * Load this vector from a FloatBuffer + * * @param buf The buffer to load it from, at the current position * @return this */ @@ -73,13 +73,14 @@ public abstract class Vector implements Serializable, ReadableVector { /** * Negate a vector + * * @return this */ public abstract Vector negate(); - /** * Normalise this vector + * * @return this */ public final Vector normalise() { @@ -91,22 +92,20 @@ public abstract class Vector implements Serializable, ReadableVector { throw new IllegalStateException("Zero length vector"); } - - /** - * Store this vector in a FloatBuffer - * @param buf The buffer to store it in, at the current position - * @return this - */ - public abstract Vector store(FloatBuffer buf); - - /** * Scale this vector + * * @param scale The scale factor * @return this */ public abstract Vector scale(float scale); - + /** + * Store this vector in a FloatBuffer + * + * @param buf The buffer to store it in, at the current position + * @return this + */ + public abstract Vector store(FloatBuffer buf); } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector2f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector2f.java index 3eb32df9..ca7e4aed 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector2f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector2f.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -39,14 +40,76 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * Holds a 2-tuple vector. * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public class Vector2f extends Vector implements Serializable, ReadableVector2f, WritableVector2f { private static final long serialVersionUID = 1L; + /** + * Add a vector to another vector and place the result in a destination vector. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return the sum of left and right in dest + */ + public static Vector2f add(Vector2f left, Vector2f right, Vector2f dest) { + if (dest == null) + return new Vector2f(left.x + right.x, left.y + right.y); + else { + dest.set(left.x + right.x, left.y + right.y); + return dest; + } + } + + /** + * Calculate the angle between two vectors, in radians + * + * @param a A vector + * @param b The other vector + * @return the angle between the two vectors, in radians + */ + public static float angle(Vector2f a, Vector2f b) { + float dls = dot(a, b) / (a.length() * b.length()); + if (dls < -1f) + dls = -1f; + else if (dls > 1.0f) + dls = 1.0f; + return (float) Math.acos(dls); + } + + /** + * The dot product of two vectors is calculated as v1.x * v2.x + v1.y * v2.y + + * v1.z * v2.z + * + * @param left The LHS vector + * @param right The RHS vector + * @return left dot right + */ + public static float dot(Vector2f left, Vector2f right) { + return left.x * right.x + left.y * right.y; + } + + /** + * Subtract a vector from another vector and place the result in a destination + * vector. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return left minus right in dest + */ + public static Vector2f sub(Vector2f left, Vector2f right, Vector2f dest) { + if (dest == null) + return new Vector2f(left.x - right.x, left.y - right.y); + else { + dest.set(left.x - right.x, left.y - right.y); + return dest; + } + } + public float x, y; /** @@ -59,202 +122,30 @@ public class Vector2f extends Vector implements Serializable, ReadableVector2f, /** * Constructor. */ - public Vector2f(ReadableVector2f src) { - set(src); + public Vector2f(float x, float y) { + set(x, y); } /** * Constructor. */ - public Vector2f(float x, float y) { - set(x, y); + public Vector2f(ReadableVector2f src) { + set(src); } - /* (non-Javadoc) - * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) - */ - public void set(float x, float y) { - this.x = x; - this.y = y; - } + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vector2f other = (Vector2f) obj; - /** - * Load from another Vector2f - * @param src The source vector - * @return this - */ - public Vector2f set(ReadableVector2f src) { - x = src.getX(); - y = src.getY(); - return this; - } + if (x == other.x && y == other.y) + return true; - /** - * @return the length squared of the vector - */ - public float lengthSquared() { - return x * x + y * y; - } - - /** - * Translate a vector - * @param x The translation in x - * @param y the translation in y - * @return this - */ - public Vector2f translate(float x, float y) { - this.x += x; - this.y += y; - return this; - } - - /** - * Negate a vector - * @return this - */ - public Vector negate() { - x = -x; - y = -y; - return this; - } - - /** - * Negate a vector and place the result in a destination vector. - * @param dest The destination vector or null if a new vector is to be created - * @return the negated vector - */ - public Vector2f negate(Vector2f dest) { - if (dest == null) - dest = new Vector2f(); - dest.x = -x; - dest.y = -y; - return dest; - } - - - /** - * Normalise this vector and place the result in another vector. - * @param dest The destination vector, or null if a new vector is to be created - * @return the normalised vector - */ - public Vector2f normalise(Vector2f dest) { - float l = length(); - - if (dest == null) - dest = new Vector2f(x / l, y / l); - else - dest.set(x / l, y / l); - - return dest; - } - - /** - * The dot product of two vectors is calculated as - * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z - * @param left The LHS vector - * @param right The RHS vector - * @return left dot right - */ - public static float dot(Vector2f left, Vector2f right) { - return left.x * right.x + left.y * right.y; - } - - - - /** - * Calculate the angle between two vectors, in radians - * @param a A vector - * @param b The other vector - * @return the angle between the two vectors, in radians - */ - public static float angle(Vector2f a, Vector2f b) { - float dls = dot(a, b) / (a.length() * b.length()); - if (dls < -1f) - dls = -1f; - else if (dls > 1.0f) - dls = 1.0f; - return (float)Math.acos(dls); - } - - /** - * Add a vector to another vector and place the result in a destination - * vector. - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination vector, or null if a new vector is to be created - * @return the sum of left and right in dest - */ - public static Vector2f add(Vector2f left, Vector2f right, Vector2f dest) { - if (dest == null) - return new Vector2f(left.x + right.x, left.y + right.y); - else { - dest.set(left.x + right.x, left.y + right.y); - return dest; - } - } - - /** - * Subtract a vector from another vector and place the result in a destination - * vector. - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination vector, or null if a new vector is to be created - * @return left minus right in dest - */ - public static Vector2f sub(Vector2f left, Vector2f right, Vector2f dest) { - if (dest == null) - return new Vector2f(left.x - right.x, left.y - right.y); - else { - dest.set(left.x - right.x, left.y - right.y); - return dest; - } - } - - /** - * Store this vector in a FloatBuffer - * @param buf The buffer to store it in, at the current position - * @return this - */ - public Vector store(FloatBuffer buf) { - buf.put(x); - buf.put(y); - return this; - } - - /** - * Load this vector from a FloatBuffer - * @param buf The buffer to load it from, at the current position - * @return this - */ - public Vector load(FloatBuffer buf) { - x = buf.get(); - y = buf.get(); - return this; - } - - /* (non-Javadoc) - * @see org.lwjgl.vector.Vector#scale(float) - */ - public Vector scale(float scale) { - - x *= scale; - y *= scale; - - return this; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuilder sb = new StringBuilder(64); - - sb.append("Vector2f["); - sb.append(x); - sb.append(", "); - sb.append(y); - sb.append(']'); - return sb.toString(); + return false; } /** @@ -271,8 +162,105 @@ public class Vector2f extends Vector implements Serializable, ReadableVector2f, return y; } + /** + * @return the length squared of the vector + */ + public float lengthSquared() { + return x * x + y * y; + } + + /** + * Load this vector from a FloatBuffer + * + * @param buf The buffer to load it from, at the current position + * @return this + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + return this; + } + + /** + * Negate a vector + * + * @return this + */ + public Vector negate() { + x = -x; + y = -y; + return this; + } + + /** + * Negate a vector and place the result in a destination vector. + * + * @param dest The destination vector or null if a new vector is to be created + * @return the negated vector + */ + public Vector2f negate(Vector2f dest) { + if (dest == null) + dest = new Vector2f(); + dest.x = -x; + dest.y = -y; + return dest; + } + + /** + * Normalise this vector and place the result in another vector. + * + * @param dest The destination vector, or null if a new vector is to be created + * @return the normalised vector + */ + public Vector2f normalise(Vector2f dest) { + float l = length(); + + if (dest == null) + dest = new Vector2f(x / l, y / l); + else + dest.set(x / l, y / l); + + return dest; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + + x *= scale; + y *= scale; + + return this; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /** + * Load from another Vector2f + * + * @param src The source vector + * @return this + */ + public Vector2f set(ReadableVector2f src) { + x = src.getX(); + y = src.getY(); + return this; + } + /** * Set X + * * @param x */ public final void setX(float x) { @@ -281,21 +269,52 @@ public class Vector2f extends Vector implements Serializable, ReadableVector2f, /** * Set Y + * * @param y */ public final void setY(float y) { this.y = y; - } - - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Vector2f other = (Vector2f)obj; - - if (x == other.x && y == other.y) return true; - - return false; } - + + /** + * Store this vector in a FloatBuffer + * + * @param buf The buffer to store it in, at the current position + * @return this + */ + public Vector store(FloatBuffer buf) { + buf.put(x); + buf.put(y); + return this; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuilder sb = new StringBuilder(64); + + sb.append("Vector2f["); + sb.append(x); + sb.append(", "); + sb.append(y); + sb.append(']'); + return sb.toString(); + } + + /** + * Translate a vector + * + * @param x The translation in x + * @param y the translation in y + * @return this + */ + public Vector2f translate(float x, float y) { + this.x += x; + this.y += y; + return this; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector3f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector3f.java index 55d41052..979655ea 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector3f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector3f.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -39,14 +40,95 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * Holds a 3-tuple vector. * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public class Vector3f extends Vector implements Serializable, ReadableVector3f, WritableVector3f { private static final long serialVersionUID = 1L; + /** + * Add a vector to another vector and place the result in a destination vector. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return the sum of left and right in dest + */ + public static Vector3f add(Vector3f left, Vector3f right, Vector3f dest) { + if (dest == null) + return new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z); + else { + dest.set(left.x + right.x, left.y + right.y, left.z + right.z); + return dest; + } + } + + /** + * Calculate the angle between two vectors, in radians + * + * @param a A vector + * @param b The other vector + * @return the angle between the two vectors, in radians + */ + public static float angle(Vector3f a, Vector3f b) { + float dls = dot(a, b) / (a.length() * b.length()); + if (dls < -1f) + dls = -1f; + else if (dls > 1.0f) + dls = 1.0f; + return (float) Math.acos(dls); + } + + /** + * The cross product of two vectors. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination result, or null if a new vector is to be created + * @return left cross right + */ + public static Vector3f cross(Vector3f left, Vector3f right, Vector3f dest) { + + if (dest == null) + dest = new Vector3f(); + + dest.set(left.y * right.z - left.z * right.y, right.x * left.z - right.z * left.x, + left.x * right.y - left.y * right.x); + + return dest; + } + + /** + * The dot product of two vectors is calculated as v1.x * v2.x + v1.y * v2.y + + * v1.z * v2.z + * + * @param left The LHS vector + * @param right The RHS vector + * @return left dot right + */ + public static float dot(Vector3f left, Vector3f right) { + return left.x * right.x + left.y * right.y + left.z * right.z; + } + + /** + * Subtract a vector from another vector and place the result in a destination + * vector. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return left minus right in dest + */ + public static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest) { + if (dest == null) + return new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z); + else { + dest.set(left.x - right.x, left.y - right.y, left.z - right.z); + return dest; + } + } + public float x, y, z; /** @@ -59,245 +141,30 @@ public class Vector3f extends Vector implements Serializable, ReadableVector3f, /** * Constructor */ - public Vector3f(ReadableVector3f src) { - set(src); + public Vector3f(float x, float y, float z) { + set(x, y, z); } /** * Constructor */ - public Vector3f(float x, float y, float z) { - set(x, y, z); + public Vector3f(ReadableVector3f src) { + set(src); } - /* (non-Javadoc) - * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) - */ - public void set(float x, float y) { - this.x = x; - this.y = y; - } + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vector3f other = (Vector3f) obj; - /* (non-Javadoc) - * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) - */ - public void set(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } + if (x == other.x && y == other.y && z == other.z) + return true; - /** - * Load from another Vector3f - * @param src The source vector - * @return this - */ - public Vector3f set(ReadableVector3f src) { - x = src.getX(); - y = src.getY(); - z = src.getZ(); - return this; - } - - /** - * @return the length squared of the vector - */ - public float lengthSquared() { - return x * x + y * y + z * z; - } - - /** - * Translate a vector - * @param x The translation in x - * @param y the translation in y - * @return this - */ - public Vector3f translate(float x, float y, float z) { - this.x += x; - this.y += y; - this.z += z; - return this; - } - - /** - * Add a vector to another vector and place the result in a destination - * vector. - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination vector, or null if a new vector is to be created - * @return the sum of left and right in dest - */ - public static Vector3f add(Vector3f left, Vector3f right, Vector3f dest) { - if (dest == null) - return new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z); - else { - dest.set(left.x + right.x, left.y + right.y, left.z + right.z); - return dest; - } - } - - /** - * Subtract a vector from another vector and place the result in a destination - * vector. - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination vector, or null if a new vector is to be created - * @return left minus right in dest - */ - public static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest) { - if (dest == null) - return new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z); - else { - dest.set(left.x - right.x, left.y - right.y, left.z - right.z); - return dest; - } - } - - /** - * The cross product of two vectors. - * - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination result, or null if a new vector is to be created - * @return left cross right - */ - public static Vector3f cross( - Vector3f left, - Vector3f right, - Vector3f dest) - { - - if (dest == null) - dest = new Vector3f(); - - dest.set( - left.y * right.z - left.z * right.y, - right.x * left.z - right.z * left.x, - left.x * right.y - left.y * right.x - ); - - return dest; - } - - - - /** - * Negate a vector - * @return this - */ - public Vector negate() { - x = -x; - y = -y; - z = -z; - return this; - } - - /** - * Negate a vector and place the result in a destination vector. - * @param dest The destination vector or null if a new vector is to be created - * @return the negated vector - */ - public Vector3f negate(Vector3f dest) { - if (dest == null) - dest = new Vector3f(); - dest.x = -x; - dest.y = -y; - dest.z = -z; - return dest; - } - - - /** - * Normalise this vector and place the result in another vector. - * @param dest The destination vector, or null if a new vector is to be created - * @return the normalised vector - */ - public Vector3f normalise(Vector3f dest) { - float l = length(); - - if (dest == null) - dest = new Vector3f(x / l, y / l, z / l); - else - dest.set(x / l, y / l, z / l); - - return dest; - } - - /** - * The dot product of two vectors is calculated as - * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z - * @param left The LHS vector - * @param right The RHS vector - * @return left dot right - */ - public static float dot(Vector3f left, Vector3f right) { - return left.x * right.x + left.y * right.y + left.z * right.z; - } - - /** - * Calculate the angle between two vectors, in radians - * @param a A vector - * @param b The other vector - * @return the angle between the two vectors, in radians - */ - public static float angle(Vector3f a, Vector3f b) { - float dls = dot(a, b) / (a.length() * b.length()); - if (dls < -1f) - dls = -1f; - else if (dls > 1.0f) - dls = 1.0f; - return (float)Math.acos(dls); - } - - /* (non-Javadoc) - * @see org.lwjgl.vector.Vector#load(FloatBuffer) - */ - public Vector load(FloatBuffer buf) { - x = buf.get(); - y = buf.get(); - z = buf.get(); - return this; - } - - /* (non-Javadoc) - * @see org.lwjgl.vector.Vector#scale(float) - */ - public Vector scale(float scale) { - - x *= scale; - y *= scale; - z *= scale; - - return this; - - } - - /* (non-Javadoc) - * @see org.lwjgl.vector.Vector#store(FloatBuffer) - */ - public Vector store(FloatBuffer buf) { - - buf.put(x); - buf.put(y); - buf.put(z); - - return this; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuilder sb = new StringBuilder(64); - - sb.append("Vector3f["); - sb.append(x); - sb.append(", "); - sb.append(y); - sb.append(", "); - sb.append(z); - sb.append(']'); - return sb.toString(); + return false; } /** @@ -314,8 +181,130 @@ public class Vector3f extends Vector implements Serializable, ReadableVector3f, return y; } + /* + * (Overrides) + * + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getZ() { + return z; + } + + /** + * @return the length squared of the vector + */ + public float lengthSquared() { + return x * x + y * y + z * z; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#load(FloatBuffer) + */ + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + z = buf.get(); + return this; + } + + /** + * Negate a vector + * + * @return this + */ + public Vector negate() { + x = -x; + y = -y; + z = -z; + return this; + } + + /** + * Negate a vector and place the result in a destination vector. + * + * @param dest The destination vector or null if a new vector is to be created + * @return the negated vector + */ + public Vector3f negate(Vector3f dest) { + if (dest == null) + dest = new Vector3f(); + dest.x = -x; + dest.y = -y; + dest.z = -z; + return dest; + } + + /** + * Normalise this vector and place the result in another vector. + * + * @param dest The destination vector, or null if a new vector is to be created + * @return the normalised vector + */ + public Vector3f normalise(Vector3f dest) { + float l = length(); + + if (dest == null) + dest = new Vector3f(x / l, y / l, z / l); + else + dest.set(x / l, y / l, z / l); + + return dest; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#scale(float) + */ + public Vector scale(float scale) { + + x *= scale; + y *= scale; + z *= scale; + + return this; + + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) + */ + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /** + * Load from another Vector3f + * + * @param src The source vector + * @return this + */ + public Vector3f set(ReadableVector3f src) { + x = src.getX(); + y = src.getY(); + z = src.getZ(); + return this; + } + /** * Set X + * * @param x */ public final void setX(float x) { @@ -324,6 +313,7 @@ public class Vector3f extends Vector implements Serializable, ReadableVector3f, /** * Set Y + * * @param y */ public final void setY(float y) { @@ -332,27 +322,56 @@ public class Vector3f extends Vector implements Serializable, ReadableVector3f, /** * Set Z + * * @param z */ public void setZ(float z) { this.z = z; } - /* (Overrides) - * @see org.lwjgl.vector.ReadableVector3f#getZ() + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#store(FloatBuffer) */ - public float getZ() { - return z; + public Vector store(FloatBuffer buf) { + + buf.put(x); + buf.put(y); + buf.put(z); + + return this; } - - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Vector3f other = (Vector3f)obj; - - if (x == other.x && y == other.y && z == other.z) return true; - - return false; + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuilder sb = new StringBuilder(64); + + sb.append("Vector3f["); + sb.append(x); + sb.append(", "); + sb.append(y); + sb.append(", "); + sb.append(z); + sb.append(']'); + return sb.toString(); + } + + /** + * Translate a vector + * + * @param x The translation in x + * @param y the translation in y + * @return this + */ + public Vector3f translate(float x, float y, float z) { + this.x += x; + this.y += y; + this.z += z; + return this; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector4f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector4f.java index 3b05d6d6..f1dc6f73 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector4f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/Vector4f.java @@ -32,6 +32,7 @@ package net.lax1dude.eaglercraft.v1_8.vector; import java.io.Serializable; + import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; /** @@ -39,14 +40,76 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; * Holds a 4-tuple vector. * * @author cix_foo - * @version $Revision$ - * $Id$ + * @version $Revision$ $Id$ */ public class Vector4f extends Vector implements Serializable, ReadableVector4f, WritableVector4f { private static final long serialVersionUID = 1L; + /** + * Add a vector to another vector and place the result in a destination vector. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return the sum of left and right in dest + */ + public static Vector4f add(Vector4f left, Vector4f right, Vector4f dest) { + if (dest == null) + return new Vector4f(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); + else { + dest.set(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); + return dest; + } + } + + /** + * Calculate the angle between two vectors, in radians + * + * @param a A vector + * @param b The other vector + * @return the angle between the two vectors, in radians + */ + public static float angle(Vector4f a, Vector4f b) { + float dls = dot(a, b) / (a.length() * b.length()); + if (dls < -1f) + dls = -1f; + else if (dls > 1.0f) + dls = 1.0f; + return (float) Math.acos(dls); + } + + /** + * The dot product of two vectors is calculated as v1.x * v2.x + v1.y * v2.y + + * v1.z * v2.z + v1.w * v2.w + * + * @param left The LHS vector + * @param right The RHS vector + * @return left dot right + */ + public static float dot(Vector4f left, Vector4f right) { + return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; + } + + /** + * Subtract a vector from another vector and place the result in a destination + * vector. + * + * @param left The LHS vector + * @param right The RHS vector + * @param dest The destination vector, or null if a new vector is to be created + * @return left minus right in dest + */ + public static Vector4f sub(Vector4f left, Vector4f right, Vector4f dest) { + if (dest == null) + return new Vector4f(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); + else { + dest.set(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); + return dest; + } + } + public float x, y, z, w; /** @@ -59,55 +122,62 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, /** * Constructor */ - public Vector4f(ReadableVector4f src) { - set(src); + public Vector4f(float x, float y, float z, float w) { + set(x, y, z, w); } /** * Constructor */ - public Vector4f(float x, float y, float z, float w) { - set(x, y, z, w); + public Vector4f(ReadableVector4f src) { + set(src); } - /* (non-Javadoc) - * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) - */ - public void set(float x, float y) { - this.x = x; - this.y = y; + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vector4f other = (Vector4f) obj; + + if (x == other.x && y == other.y && z == other.z && w == other.w) + return true; + + return false; } - /* (non-Javadoc) - * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) + /* + * (Overrides) + * + * @see org.lwjgl.vector.ReadableVector3f#getZ() */ - public void set(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - } - - /* (non-Javadoc) - * @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float) - */ - public void set(float x, float y, float z, float w) { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + public float getW() { + return w; } /** - * Load from another Vector4f - * @param src The source vector - * @return this + * @return x */ - public Vector4f set(ReadableVector4f src) { - x = src.getX(); - y = src.getY(); - z = src.getZ(); - w = src.getW(); - return this; + public final float getX() { + return x; + } + + /** + * @return y + */ + public final float getY() { + return y; + } + + /* + * (Overrides) + * + * @see org.lwjgl.vector.ReadableVector3f#getZ() + */ + public float getZ() { + return z; } /** @@ -117,57 +187,22 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, return x * x + y * y + z * z + w * w; } - /** - * Translate a vector - * @param x The translation in x - * @param y the translation in y - * @return this + /* + * (non-Javadoc) + * + * @see org.lwjgl.vector.Vector#load(FloatBuffer) */ - public Vector4f translate(float x, float y, float z, float w) { - this.x += x; - this.y += y; - this.z += z; - this.w += w; + public Vector load(FloatBuffer buf) { + x = buf.get(); + y = buf.get(); + z = buf.get(); + w = buf.get(); return this; } - /** - * Add a vector to another vector and place the result in a destination - * vector. - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination vector, or null if a new vector is to be created - * @return the sum of left and right in dest - */ - public static Vector4f add(Vector4f left, Vector4f right, Vector4f dest) { - if (dest == null) - return new Vector4f(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); - else { - dest.set(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); - return dest; - } - } - - /** - * Subtract a vector from another vector and place the result in a destination - * vector. - * @param left The LHS vector - * @param right The RHS vector - * @param dest The destination vector, or null if a new vector is to be created - * @return left minus right in dest - */ - public static Vector4f sub(Vector4f left, Vector4f right, Vector4f dest) { - if (dest == null) - return new Vector4f(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); - else { - dest.set(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); - return dest; - } - } - - /** * Negate a vector + * * @return this */ public Vector negate() { @@ -180,6 +215,7 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, /** * Negate a vector and place the result in a destination vector. + * * @param dest The destination vector or null if a new vector is to be created * @return the negated vector */ @@ -193,9 +229,9 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, return dest; } - /** * Normalise this vector and place the result in another vector. + * * @param dest The destination vector, or null if a new vector is to be created * @return the normalised vector */ @@ -210,44 +246,9 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, return dest; } - /** - * The dot product of two vectors is calculated as - * v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w - * @param left The LHS vector - * @param right The RHS vector - * @return left dot right - */ - public static float dot(Vector4f left, Vector4f right) { - return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w; - } - - /** - * Calculate the angle between two vectors, in radians - * @param a A vector - * @param b The other vector - * @return the angle between the two vectors, in radians - */ - public static float angle(Vector4f a, Vector4f b) { - float dls = dot(a, b) / (a.length() * b.length()); - if (dls < -1f) - dls = -1f; - else if (dls > 1.0f) - dls = 1.0f; - return (float)Math.acos(dls); - } - - /* (non-Javadoc) - * @see org.lwjgl.vector.Vector#load(FloatBuffer) - */ - public Vector load(FloatBuffer buf) { - x = buf.get(); - y = buf.get(); - z = buf.get(); - w = buf.get(); - return this; - } - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.lwjgl.vector.Vector#scale(float) */ public Vector scale(float scale) { @@ -258,7 +259,92 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, return this; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector2f#set(float, float) + */ + public void set(float x, float y) { + this.x = x; + this.y = y; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float) + */ + public void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + + /* + * (non-Javadoc) + * + * @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float) + */ + public void set(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + /** + * Load from another Vector4f + * + * @param src The source vector + * @return this + */ + public Vector4f set(ReadableVector4f src) { + x = src.getX(); + y = src.getY(); + z = src.getZ(); + w = src.getW(); + return this; + } + + /** + * Set W + * + * @param w + */ + public void setW(float w) { + this.w = w; + } + + /** + * Set X + * + * @param x + */ + public final void setX(float x) { + this.x = x; + } + + /** + * Set Y + * + * @param y + */ + public final void setY(float y) { + this.y = y; + } + + /** + * Set Z + * + * @param z + */ + public void setZ(float z) { + this.z = z; + } + + /* + * (non-Javadoc) + * * @see org.lwjgl.vector.Vector#store(FloatBuffer) */ public Vector store(FloatBuffer buf) { @@ -276,74 +362,17 @@ public class Vector4f extends Vector implements Serializable, ReadableVector4f, } /** - * @return x + * Translate a vector + * + * @param x The translation in x + * @param y the translation in y + * @return this */ - public final float getX() { - return x; - } - - /** - * @return y - */ - public final float getY() { - return y; - } - - /** - * Set X - * @param x - */ - public final void setX(float x) { - this.x = x; - } - - /** - * Set Y - * @param y - */ - public final void setY(float y) { - this.y = y; - } - - /** - * Set Z - * @param z - */ - public void setZ(float z) { - this.z = z; - } - - - /* (Overrides) - * @see org.lwjgl.vector.ReadableVector3f#getZ() - */ - public float getZ() { - return z; - } - - /** - * Set W - * @param w - */ - public void setW(float w) { - this.w = w; - } - - /* (Overrides) - * @see org.lwjgl.vector.ReadableVector3f#getZ() - */ - public float getW() { - return w; - } - - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Vector4f other = (Vector4f)obj; - - if (x == other.x && y == other.y && z == other.z && w == other.w) return true; - - return false; + public Vector4f translate(float x, float y, float z, float w) { + this.x += x; + this.y += y; + this.z += z; + this.w += w; + return this; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector2f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector2f.java index a140996d..27376e50 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector2f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector2f.java @@ -33,29 +33,32 @@ package net.lax1dude.eaglercraft.v1_8.vector; /** * Writable interface to Vector2fs + * * @author $author$ - * @version $revision$ - * $Id$ + * @version $revision$ $Id$ */ public interface WritableVector2f { + /** + * Set the X,Y values + * + * @param x + * @param y + */ + void set(float x, float y); + /** * Set the X value + * * @param x */ void setX(float x); /** * Set the Y value + * * @param y */ void setY(float y); - /** - * Set the X,Y values - * @param x - * @param y - */ - void set(float x, float y); - } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector3f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector3f.java index d27284f4..3c4f8d27 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector3f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector3f.java @@ -33,24 +33,26 @@ package net.lax1dude.eaglercraft.v1_8.vector; /** * Writable interface to Vector3fs + * * @author $author$ - * @version $revision$ - * $Id$ + * @version $revision$ $Id$ */ public interface WritableVector3f extends WritableVector2f { + /** + * Set the X,Y,Z values + * + * @param x + * @param y + * @param z + */ + void set(float x, float y, float z); + /** * Set the Z value + * * @param z */ void setZ(float z); - /** - * Set the X,Y,Z values - * @param x - * @param y - * @param z - */ - void set(float x, float y, float z); - } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector4f.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector4f.java index 20be4c75..d8835573 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector4f.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/vector/WritableVector4f.java @@ -33,25 +33,27 @@ package net.lax1dude.eaglercraft.v1_8.vector; /** * Writable interface to Vector4fs + * * @author $author$ - * @version $revision$ - * $Id$ + * @version $revision$ $Id$ */ public interface WritableVector4f extends WritableVector3f { + /** + * Set the X,Y,Z,W values + * + * @param x + * @param y + * @param z + * @param w + */ + void set(float x, float y, float z, float w); + /** * Set the W value + * * @param w */ void setW(float w); - /** - * Set the X,Y,Z,W values - * @param x - * @param y - * @param z - * @param w - */ - void set(float x, float y, float z, float w); - } \ No newline at end of file diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelPeerState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelPeerState.java index 0b1ff097..c7948603 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelPeerState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelPeerState.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.voice; /** * Copyright (c) 2024 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelReadyState.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelReadyState.java index c470876a..d12f7e13 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelReadyState.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelReadyState.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.voice; /** * Copyright (c) 2024 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelStatus.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelStatus.java index 8a6d737d..43cd91fa 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelStatus.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelStatus.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.voice; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelType.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelType.java index d035edb9..2807a8e8 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelType.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/EnumVoiceChannelType.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.voice; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/ExpiringSet.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/ExpiringSet.java index a3228f67..5c1fc939 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/ExpiringSet.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/ExpiringSet.java @@ -10,77 +10,82 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; /** * Copyright (c) 2022 ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ExpiringSet extends HashSet { - private final long expiration; - private final ExpiringEvent event; + public interface ExpiringEvent { + void onExpiration(T item); + } - private final Map timestamps = new HashMap<>(); + private final long expiration; - public ExpiringSet(long expiration) { - this.expiration = expiration; - this.event = null; - } + private final ExpiringEvent event; - public ExpiringSet(long expiration, ExpiringEvent event) { - this.expiration = expiration; - this.event = event; - } + private final Map timestamps = new HashMap<>(); - public interface ExpiringEvent { - void onExpiration(T item); - } + public ExpiringSet(long expiration) { + this.expiration = expiration; + this.event = null; + } - public void checkForExpirations() { - Iterator iterator = this.timestamps.keySet().iterator(); - long now = EagRuntime.steadyTimeMillis(); - while (iterator.hasNext()) { - T element = iterator.next(); - if (super.contains(element)) { - if (this.timestamps.get(element) + this.expiration < now) { - if (this.event != null) this.event.onExpiration(element); - iterator.remove(); - super.remove(element); - } - } else { - iterator.remove(); - super.remove(element); - } - } - } + public ExpiringSet(long expiration, ExpiringEvent event) { + this.expiration = expiration; + this.event = event; + } - public boolean add(T o) { - checkForExpirations(); - boolean success = super.add(o); - if (success) timestamps.put(o, EagRuntime.steadyTimeMillis()); - return success; - } + public boolean add(T o) { + checkForExpirations(); + boolean success = super.add(o); + if (success) + timestamps.put(o, EagRuntime.steadyTimeMillis()); + return success; + } - public boolean remove(Object o) { - checkForExpirations(); - boolean success = super.remove(o); - if (success) timestamps.remove(o); - return success; - } + public void checkForExpirations() { + Iterator iterator = this.timestamps.keySet().iterator(); + long now = EagRuntime.steadyTimeMillis(); + while (iterator.hasNext()) { + T element = iterator.next(); + if (super.contains(element)) { + if (this.timestamps.get(element) + this.expiration < now) { + if (this.event != null) + this.event.onExpiration(element); + iterator.remove(); + super.remove(element); + } + } else { + iterator.remove(); + super.remove(element); + } + } + } - public void clear() { - this.timestamps.clear(); - super.clear(); - } + public void clear() { + this.timestamps.clear(); + super.clear(); + } - public boolean contains(Object o) { - checkForExpirations(); - return super.contains(o); - } + public boolean contains(Object o) { + checkForExpirations(); + return super.contains(o); + } + + public boolean remove(Object o) { + checkForExpirations(); + boolean success = super.remove(o); + if (success) + timestamps.remove(o); + return success; + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceMenu.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceMenu.java index caa72908..62a0d8f0 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceMenu.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceMenu.java @@ -1,6 +1,7 @@ package net.lax1dude.eaglercraft.v1_8.voice; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_ONE_MINUS_SRC_ALPHA; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_SRC_ALPHA; import java.util.List; import java.util.Set; @@ -25,14 +26,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,48 +46,83 @@ public class GuiVoiceMenu extends Gui { private static final ResourceLocation voiceGuiIcons = new ResourceLocation("eagler:gui/eagler_gui.png"); - protected final GuiScreen parent; + protected static boolean showingCompatWarning = false; + protected static boolean showCompatWarning = true; + protected static boolean showingTrackingWarning = false; + protected static boolean showTrackingWarning = true; + protected static EnumVoiceChannelType continueChannel = null; + + public static int attenuate(int cin, float f) { + return attenuate(cin, f, f, f, 1.0f); + } + + public static int attenuate(int cin, float r, float g, float b, float a) { + float var10 = (float) (cin >>> 24 & 255) / 255.0F; + float var6 = (float) (cin >>> 16 & 255) / 255.0F; + float var7 = (float) (cin >>> 8 & 255) / 255.0F; + float var8 = (float) (cin & 255) / 255.0F; + var10 *= a; + var6 *= r; + var7 *= g; + var8 *= b; + if (var10 > 1.0f) { + var10 = 1.0f; + } + if (var6 > 1.0f) { + var6 = 1.0f; + } + if (var7 > 1.0f) { + var7 = 1.0f; + } + if (var8 > 1.0f) { + var8 = 1.0f; + } + return (((int) (var10 * 255.0f) << 24) | ((int) (var6 * 255.0f) << 16) | ((int) (var7 * 255.0f) << 8) + | (int) (var8 * 255.0f)); + } + + protected final GuiScreen parent; protected Minecraft mc; + protected FontRenderer fontRendererObj; protected int width; protected int height; - protected int voiceButtonOFFposX; + protected int voiceButtonOFFposY; protected int voiceButtonOFFposW; protected int voiceButtonOFFposH; - protected int voiceButtonRADIUSposX; + protected int voiceButtonRADIUSposY; protected int voiceButtonRADIUSposW; protected int voiceButtonRADIUSposH; - protected int voiceButtonGLOBALposX; + protected int voiceButtonGLOBALposY; protected int voiceButtonGLOBALposW; protected int voiceButtonGLOBALposH; - protected int voiceScreenButtonOFFposX; + protected int voiceScreenButtonOFFposY; protected int voiceScreenButtonOFFposW; protected int voiceScreenButtonOFFposH; - protected int voiceScreenButtonRADIUSposX; + protected int voiceScreenButtonRADIUSposY; protected int voiceScreenButtonRADIUSposW; protected int voiceScreenButtonRADIUSposH; - protected int voiceScreenButtonGLOBALposX; + protected int voiceScreenButtonGLOBALposY; protected int voiceScreenButtonGLOBALposW; protected int voiceScreenButtonGLOBALposH; - protected int voiceScreenButtonChangeRadiusposX; + protected int voiceScreenButtonChangeRadiusposY; protected int voiceScreenButtonChangeRadiusposW; protected int voiceScreenButtonChangeRadiusposH; - protected int voiceScreenVolumeIndicatorX; protected int voiceScreenVolumeIndicatorY; protected int voiceScreenVolumeIndicatorW; @@ -95,117 +132,184 @@ public class GuiVoiceMenu extends Gui { protected boolean showSliderVolume = false; protected boolean showPTTKeyConfig = false; protected int showNewPTTKey = 0; + protected GuiSlider2 sliderBlocks = null; protected GuiSlider2 sliderListenVolume = null; - protected GuiSlider2 sliderSpeakVolume = null; + protected GuiSlider2 sliderSpeakVolume = null; protected GuiButton applyRadiusButton = null; + protected GuiButton applyVolumeButton = null; + protected GuiButton noticeContinueButton = null; + protected GuiButton noticeCancelButton = null; - protected static boolean showingCompatWarning = false; - protected static boolean showCompatWarning = true; - - protected static boolean showingTrackingWarning = false; - protected static boolean showTrackingWarning = true; - - protected static EnumVoiceChannelType continueChannel = null; - public GuiVoiceMenu(GuiScreen parent) { this.parent = parent; } - - public void setResolution(Minecraft mc, int w, int h) { - this.mc = mc; - this.fontRendererObj = mc.fontRendererObj; - this.width = w; - this.height = h; - initGui(); - } - - public void initGui() { - this.sliderBlocks = new GuiSlider2(-1, (width - 150) / 2, height / 3 + 20, 150, 20, (VoiceClientController.getVoiceProximity() - 5) / 17.0f, 1.0f) { - protected String updateDisplayString() { - return (int)((sliderValue * 17.0f) + 5.0f) + " Blocks"; + + private void actionPerformed(GuiButton btn) { + if (btn.id == 2) { + showSliderBlocks = false; + VoiceClientController.setVoiceProximity( + mc.gameSettings.voiceListenRadius = (int) ((sliderBlocks.sliderValue * 17.0f) + 5.0f)); + mc.gameSettings.saveOptions(); + } else if (btn.id == 3) { + showSliderVolume = false; + VoiceClientController + .setVoiceListenVolume(mc.gameSettings.voiceListenVolume = sliderListenVolume.sliderValue); + VoiceClientController.setVoiceSpeakVolume(mc.gameSettings.voiceSpeakVolume = sliderSpeakVolume.sliderValue); + mc.gameSettings.saveOptions(); + } else if (btn.id == 4) { + showPTTKeyConfig = false; + mc.gameSettings.saveOptions(); + } else if (btn.id == 5) { + if (showingCompatWarning) { + showingCompatWarning = false; + showCompatWarning = false; + if (showTrackingWarning) { + showingTrackingWarning = true; + } else { + VoiceClientController.setVoiceChannel(continueChannel); + } + } else if (showingTrackingWarning) { + showingTrackingWarning = false; + showTrackingWarning = false; + VoiceClientController.setVoiceChannel(continueChannel); } - }; - sliderBlocks.displayString = "" + VoiceClientController.getVoiceProximity() + " Blocks"; - this.sliderListenVolume = new GuiSlider2(-1, (width - 150) / 2, height / 3 + 10, 150, 20, VoiceClientController.getVoiceListenVolume(), 1.0f); - this.sliderSpeakVolume = new GuiSlider2(-1, (width - 150) / 2, height / 3 + 56, 150, 20, VoiceClientController.getVoiceSpeakVolume(), 1.0f); - - applyRadiusButton = new GuiButton(2, (width - 150) / 2, height / 3 + 49, 150, 20, I18n.format("voice.apply")); - applyVolumeButton = new GuiButton(3, (width - 150) / 2, height / 3 + 90, 150, 20, I18n.format("voice.apply")); - noticeContinueButton = new GuiButton(5, (width - 150) / 2, height / 3 + 60, 150, 20, I18n.format("voice.unsupportedWarning10")); - noticeCancelButton = new GuiButton(6, (width - 150) / 2, height / 3 + 90, 150, 20, I18n.format("voice.unsupportedWarning11")); - applyRadiusButton.visible = applyVolumeButton.visible = noticeContinueButton.visible = noticeCancelButton.visible = false; + } else if (btn.id == 6) { + if (showingTrackingWarning) { + showingTrackingWarning = false; + VoiceClientController.setVoiceChannel(EnumVoiceChannelType.NONE); + } + } } - + private void drawButtons(int mx, int my, float partialTicks) { applyRadiusButton.drawButton(mc, mx, my); applyVolumeButton.drawButton(mc, mx, my); noticeContinueButton.drawButton(mc, mx, my); noticeCancelButton.drawButton(mc, mx, my); } - + + private void drawNotice(String title, boolean showCancel, String... lines) { + + int widthAccum = 0; + + for (int i = 0; i < lines.length; ++i) { + int w = fontRendererObj.getStringWidth(lines[i]); + if (widthAccum < w) { + widthAccum = w; + } + } + + int margin = 15; + + int x = (width - widthAccum) / 2; + int y = (height - lines.length * 10 - 60 - margin) / 2; + + drawRect(x - margin - 1, y - margin - 1, x + widthAccum + margin + 1, y + lines.length * 10 + 49 + margin, + 0xFFCCCCCC); + drawRect(x - margin, y - margin, x + widthAccum + margin, y + lines.length * 10 + 48 + margin, 0xFF111111); + + drawCenteredString(fontRendererObj, EnumChatFormatting.BOLD + title, width / 2, y, 0xFF7766); + + for (int i = 0; i < lines.length; ++i) { + drawString(fontRendererObj, lines[i], x, y + i * 10 + 18, 0xDDAAAA); + } + + if (!showCancel) { + noticeContinueButton.width = 150; + noticeContinueButton.xPosition = (width - 150) / 2; + noticeContinueButton.yPosition = y + lines.length * 10 + 29; + } else { + noticeContinueButton.width = widthAccum / 2 - 10; + noticeContinueButton.xPosition = (width - widthAccum) / 2 + widthAccum / 2 + 3; + noticeContinueButton.yPosition = y + lines.length * 10 + 28; + noticeCancelButton.width = widthAccum / 2 - 10; + noticeCancelButton.xPosition = (width - widthAccum) / 2 + 4; + noticeCancelButton.yPosition = y + lines.length * 10 + 28; + } + + } + + private void drawOutline(int x, int y, int w, int h, int color) { + drawRect(x, y, x + w, y + 1, color); + drawRect(x + w - 1, y + 1, x + w, y + h - 1, color); + drawRect(x, y + h - 1, x + w, y + h, color); + drawRect(x, y + 1, x + 1, y + h - 1, color); + } + public void drawScreen(int mx, int my, float partialTicks) { String txt = I18n.format("voice.title"); drawString(fontRendererObj, txt, width - 5 - fontRendererObj.getStringWidth(txt), 5, 0xFFCC22); - + applyRadiusButton.visible = showSliderBlocks; applyVolumeButton.visible = showSliderVolume; - - if(showSliderBlocks || showSliderVolume || showPTTKeyConfig) { - + + if (showSliderBlocks || showSliderVolume || showPTTKeyConfig) { + drawRect(0, 0, this.width, this.height, 0xB0101010); - - if(showSliderBlocks) { - - drawRect(width / 2 - 86, height / 4 - 1, this.width / 2 + 86, height / 3 + 64 + height / 16, 0xFFDDDDDD); - drawRect(width / 2 - 85, height / 4 + 0, this.width / 2 + 85, height / 3 + 63 + height / 16, 0xFF333333); - - drawCenteredString(this.fontRendererObj, I18n.format("voice.radiusTitle"), this.width / 2, height / 4 + 9, 16777215); - drawString(this.fontRendererObj, I18n.format("voice.radiusLabel"), (this.width - 150) / 2 + 3, height / 3 + 6, 0xCCCCCC); + + if (showSliderBlocks) { + + drawRect(width / 2 - 86, height / 4 - 1, this.width / 2 + 86, height / 3 + 64 + height / 16, + 0xFFDDDDDD); + drawRect(width / 2 - 85, height / 4 + 0, this.width / 2 + 85, height / 3 + 63 + height / 16, + 0xFF333333); + + drawCenteredString(this.fontRendererObj, I18n.format("voice.radiusTitle"), this.width / 2, + height / 4 + 9, 16777215); + drawString(this.fontRendererObj, I18n.format("voice.radiusLabel"), (this.width - 150) / 2 + 3, + height / 3 + 6, 0xCCCCCC); sliderBlocks.drawButton(mc, mx, my); - - }else if(showSliderVolume) { - - drawRect(width / 2 - 86, height / 4 - 11, this.width / 2 + 86, height / 3 + 104 + height / 16, 0xFFDDDDDD); - drawRect(width / 2 - 85, height / 4 - 10, this.width / 2 + 85, height / 3 + 103 + height / 16, 0xFF333333); - - drawCenteredString(this.fontRendererObj, I18n.format("voice.volumeTitle"), this.width / 2, height / 4 - 1, 16777215); - drawString(this.fontRendererObj, I18n.format("voice.volumeListen"), (this.width - 150) / 2 + 3, height / 3 - 4, 0xCCCCCC); + + } else if (showSliderVolume) { + + drawRect(width / 2 - 86, height / 4 - 11, this.width / 2 + 86, height / 3 + 104 + height / 16, + 0xFFDDDDDD); + drawRect(width / 2 - 85, height / 4 - 10, this.width / 2 + 85, height / 3 + 103 + height / 16, + 0xFF333333); + + drawCenteredString(this.fontRendererObj, I18n.format("voice.volumeTitle"), this.width / 2, + height / 4 - 1, 16777215); + drawString(this.fontRendererObj, I18n.format("voice.volumeListen"), (this.width - 150) / 2 + 3, + height / 3 - 4, 0xCCCCCC); sliderListenVolume.drawButton(mc, mx, my); - - drawString(this.fontRendererObj, I18n.format("voice.volumeSpeak"), (this.width - 150) / 2 + 3, height / 3 + 42, 0xCCCCCC); + + drawString(this.fontRendererObj, I18n.format("voice.volumeSpeak"), (this.width - 150) / 2 + 3, + height / 3 + 42, 0xCCCCCC); sliderSpeakVolume.drawButton(mc, mx, my); - - }else if(showPTTKeyConfig) { - + + } else if (showPTTKeyConfig) { + drawRect(width / 2 - 86, height / 3 - 10, this.width / 2 + 86, height / 3 + 35, 0xFFDDDDDD); drawRect(width / 2 - 85, height / 3 - 9, this.width / 2 + 85, height / 3 + 34, 0xFF333333); - - if(showNewPTTKey > 0) { + + if (showNewPTTKey > 0) { GlStateManager.pushMatrix(); GlStateManager.translate(this.width / 2, height / 3 + 5, 0.0f); GlStateManager.scale(2.0f, 2.0f, 2.0f); - drawCenteredString(this.fontRendererObj, Keyboard.getKeyName(mc.gameSettings.voicePTTKey), 0, 0, 0xFFCC11); + drawCenteredString(this.fontRendererObj, Keyboard.getKeyName(mc.gameSettings.voicePTTKey), 0, 0, + 0xFFCC11); GlStateManager.popMatrix(); - }else { - drawCenteredString(this.fontRendererObj, I18n.format("voice.pttChangeDesc"), this.width / 2, height / 3 + 8, 16777215); + } else { + drawCenteredString(this.fontRendererObj, I18n.format("voice.pttChangeDesc"), this.width / 2, + height / 3 + 8, 16777215); } } - + drawButtons(mx, my, partialTicks); throw new AbortedException(); } - + GlStateManager.pushMatrix(); - + GlStateManager.translate(width - 6, 15, 0.0f); GlStateManager.scale(0.75f, 0.75f, 0.75f); - - if(!VoiceClientController.isClientSupported()) { + + if (!VoiceClientController.isClientSupported()) { txt = I18n.format("voice.titleVoiceUnavailable"); drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 6, 0xFF7777); txt = I18n.format("voice.titleVoiceBrowserError"); @@ -213,8 +317,8 @@ public class GuiVoiceMenu extends Gui { GlStateManager.popMatrix(); return; } - - if(!VoiceClientController.isServerSupported()) { + + if (!VoiceClientController.isServerSupported()) { txt = I18n.format("voice.titleNoVoice"); drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 5, 0xFF7777); GlStateManager.popMatrix(); @@ -223,29 +327,33 @@ public class GuiVoiceMenu extends Gui { int xo = 0; // this feature is optional - //if(VoiceClientController.voiceRelayed()) { - // txt = I18n.format("voice.warning1"); - // drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 8, 0xBB9999); - // txt = I18n.format("voice.warning2"); - // drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 18, 0xBB9999); - // txt = I18n.format("voice.warning3"); - // drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 28, 0xBB9999); - // xo = 43; - // GlStateManager.translate(0.0f, xo, 0.0f); - //} - + // if(VoiceClientController.voiceRelayed()) { + // txt = I18n.format("voice.warning1"); + // drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 8, + // 0xBB9999); + // txt = I18n.format("voice.warning2"); + // drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 18, + // 0xBB9999); + // txt = I18n.format("voice.warning3"); + // drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 28, + // 0xBB9999); + // xo = 43; + // GlStateManager.translate(0.0f, xo, 0.0f); + // } + EnumVoiceChannelStatus status = VoiceClientController.getVoiceStatus(); EnumVoiceChannelType channel = VoiceClientController.getVoiceChannel(); - + boolean flag = false; - - if(channel == EnumVoiceChannelType.NONE) { + + if (channel == EnumVoiceChannelType.NONE) { flag = true; - }else { - if(status == EnumVoiceChannelStatus.CONNECTED) { - - if(channel == EnumVoiceChannelType.PROXIMITY) { - txt = I18n.format("voice.connectedRadius").replace("$radius$", "" + VoiceClientController.getVoiceProximity()).replace("$f$", ""); + } else { + if (status == EnumVoiceChannelStatus.CONNECTED) { + + if (channel == EnumVoiceChannelType.PROXIMITY) { + txt = I18n.format("voice.connectedRadius") + .replace("$radius$", "" + VoiceClientController.getVoiceProximity()).replace("$f$", ""); int w = fontRendererObj.getStringWidth(txt); int xx = width - 5 - (w * 3 / 4); int yy = 15 + (xo * 3 / 4); @@ -253,63 +361,65 @@ public class GuiVoiceMenu extends Gui { voiceScreenButtonChangeRadiusposY = yy; voiceScreenButtonChangeRadiusposW = width - 3 - xx; voiceScreenButtonChangeRadiusposH = 12; - if(mx >= xx && my >= yy && mx < xx + voiceScreenButtonChangeRadiusposW && my < yy + 12) { - txt = I18n.format("voice.connectedRadius").replace("$radius$", "" + VoiceClientController.getVoiceProximity()) + if (mx >= xx && my >= yy && mx < xx + voiceScreenButtonChangeRadiusposW && my < yy + 12) { + txt = I18n.format("voice.connectedRadius") + .replace("$radius$", "" + VoiceClientController.getVoiceProximity()) .replace("$f$", "" + EnumChatFormatting.UNDERLINE) + EnumChatFormatting.RESET; } - }else { + } else { txt = I18n.format("voice.connectedGlobal"); } - + voiceScreenVolumeIndicatorX = width - 15 - (104 * 3 / 4); voiceScreenVolumeIndicatorY = 15 + (xo * 3 / 4) + 30; voiceScreenVolumeIndicatorW = width - voiceScreenVolumeIndicatorX - 4; voiceScreenVolumeIndicatorH = 23; - + drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 5, 0x66DD66); drawRect(-90, 42, 2, 52, 0xFFAAAAAA); drawRect(-89, 43, 1, 51, 0xFF222222); - + float vol = VoiceClientController.getVoiceListenVolume(); - drawRect(-89, 43, -89 + (int)(vol * 90), 51, 0xFF993322); - - for(float f = 0.07f; f < vol; f += 0.08f) { - int ww = (int)(f * 90); + drawRect(-89, 43, -89 + (int) (vol * 90), 51, 0xFF993322); + + for (float f = 0.07f; f < vol; f += 0.08f) { + int ww = (int) (f * 90); drawRect(-89 + ww, 43, -89 + ww + 1, 51, 0xFF999999); } drawRect(-90, 57, 2, 67, 0xFFAAAAAA); drawRect(-89, 58, 1, 66, 0xFF222222); - + vol = VoiceClientController.getVoiceSpeakVolume(); - drawRect(-89, 58, -89 + (int)(vol * 90), 66, 0xFF993322); - - for(float f = 0.07f; f < vol; f += 0.08f) { - int ww = (int)(f * 90); + drawRect(-89, 58, -89 + (int) (vol * 90), 66, 0xFF993322); + + for (float f = 0.07f; f < vol; f += 0.08f) { + int ww = (int) (f * 90); drawRect(-89 + ww, 58, -89 + ww + 1, 66, 0xFF999999); } - + mc.getTextureManager().bindTexture(voiceGuiIcons); GlStateManager.color(0.7f, 0.7f, 0.7f, 1.0f); - + GlStateManager.pushMatrix(); GlStateManager.translate(-104.0f, 41.5f, 0.0f); GlStateManager.scale(0.7f, 0.7f, 0.7f); drawTexturedModalRect(0, 0, 64, 144, 16, 16); GlStateManager.popMatrix(); - + GlStateManager.pushMatrix(); GlStateManager.translate(-104.0f, 56.5f, 0.0f); GlStateManager.scale(0.7f, 0.7f, 0.7f); - if((mc.currentScreen == null || !mc.currentScreen.blockPTTKey()) && Keyboard.isKeyDown(mc.gameSettings.voicePTTKey)) { + if ((mc.currentScreen == null || !mc.currentScreen.blockPTTKey()) + && Keyboard.isKeyDown(mc.gameSettings.voicePTTKey)) { GlStateManager.color(0.9f, 0.4f, 0.4f, 1.0f); drawTexturedModalRect(0, 0, 64, 64, 16, 16); - }else { + } else { drawTexturedModalRect(0, 0, 64, 32, 16, 16); } GlStateManager.popMatrix(); - + txt = I18n.format("voice.ptt", Keyboard.getKeyName(mc.gameSettings.voicePTTKey)); drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt) - 10, 76, 0x66DD66); @@ -320,9 +430,9 @@ public class GuiVoiceMenu extends Gui { GlStateManager.scale(0.35f, 0.35f, 0.35f); drawTexturedModalRect(0, 0, 32, 224, 32, 32); GlStateManager.popMatrix(); - + txt = I18n.format("voice.playersListening"); - + GlStateManager.pushMatrix(); GlStateManager.translate(0.0f, 98.0f, 0.0f); GlStateManager.scale(1.2f, 1.2f, 1.2f); @@ -330,70 +440,73 @@ public class GuiVoiceMenu extends Gui { GlStateManager.popMatrix(); List playersToRender = VoiceClientController.getVoiceRecent(); - - if(playersToRender.size() > 0) { + + if (playersToRender.size() > 0) { EaglercraftUUID uuid; Set playersSpeaking = VoiceClientController.getVoiceSpeaking(); Set playersMuted = VoiceClientController.getVoiceMuted(); - for(int i = 0, l = playersToRender.size(); i < l; ++i) { + for (int i = 0, l = playersToRender.size(); i < l; ++i) { uuid = playersToRender.get(i); txt = VoiceClientController.getVoiceUsername(uuid); - + boolean muted = playersMuted.contains(uuid); boolean speaking = !muted && playersSpeaking.contains(uuid); - + int mhy = voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH + 33 + i * 9; - boolean hovered = mx >= voiceScreenVolumeIndicatorX - 3 && my >= mhy && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + 2 && my < mhy + 9; + boolean hovered = mx >= voiceScreenVolumeIndicatorX - 3 && my >= mhy + && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + 2 && my < mhy + 9; float cm = hovered ? 1.5f : 1.0f; mc.getTextureManager().bindTexture(voiceGuiIcons); GlStateManager.pushMatrix(); GlStateManager.translate(-100.0f, 115.0f + i * 12.0f, 0.0f); GlStateManager.scale(0.78f, 0.78f, 0.78f); - - if(muted) { + + if (muted) { GlStateManager.color(1.0f * cm, 0.2f * cm, 0.2f * cm, 1.0f); drawTexturedModalRect(0, 0, 64, 208, 16, 16); - }else if(speaking) { + } else if (speaking) { GlStateManager.color(1.0f * cm, 1.0f * cm, 1.0f * cm, 1.0f); drawTexturedModalRect(0, 0, 64, 176, 16, 16); - }else { + } else { GlStateManager.color(0.65f * cm, 0.65f * cm, 0.65f * cm, 1.0f); drawTexturedModalRect(0, 0, 64, 144, 16, 16); } - + GlStateManager.popMatrix(); - if(muted) { + if (muted) { drawString(fontRendererObj, txt, -84, 117 + i * 12, attenuate(0xCC4444, cm)); - }else if(speaking) { + } else if (speaking) { drawString(fontRendererObj, txt, -84, 117 + i * 12, attenuate(0xCCCCCC, cm)); - }else { + } else { drawString(fontRendererObj, txt, -84, 117 + i * 12, attenuate(0x999999, cm)); } - + } - }else { + } else { txt = "(none)"; drawString(fontRendererObj, txt, -fontRendererObj.getStringWidth(txt), 112, 0xAAAAAA); } - - }else if(status == EnumVoiceChannelStatus.CONNECTING) { - float fadeTimer = MathHelper.sin((float)((EagRuntime.steadyTimeMillis() % 700l) * 0.0014d) * 3.14159f) * 0.35f + 0.3f; + + } else if (status == EnumVoiceChannelStatus.CONNECTING) { + float fadeTimer = MathHelper.sin((float) ((EagRuntime.steadyTimeMillis() % 700l) * 0.0014d) * 3.14159f) + * 0.35f + 0.3f; txt = I18n.format("voice.connecting"); GlStateManager.enableBlend(); GlStateManager.blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 5, (0xFFDD77 | ((int)(Math.pow(fadeTimer, 1.0d / 2.2d) * 255.0f) << 24))); + drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 5, + (0xFFDD77 | ((int) (Math.pow(fadeTimer, 1.0d / 2.2d) * 255.0f) << 24))); GlStateManager.disableBlend(); - }else if(status == EnumVoiceChannelStatus.UNAVAILABLE) { + } else if (status == EnumVoiceChannelStatus.UNAVAILABLE) { txt = I18n.format("voice.unavailable"); drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 5, 0xFF3333); - }else { + } else { flag = true; } } - - if(flag) { + + if (flag) { txt = I18n.format("voice.notConnected"); drawString(fontRendererObj, txt, 1 - fontRendererObj.getStringWidth(txt), 5, 0xBB9999); } @@ -405,7 +518,7 @@ public class GuiVoiceMenu extends Gui { int OFFwidth = fontRendererObj.getStringWidth(OFFstring); int RADIUSwidth = fontRendererObj.getStringWidth(RADIUSstring); int GLOBALwidth = fontRendererObj.getStringWidth(GLOBALstring); - + voiceButtonOFFposX = 0 - OFFwidth - 8 - RADIUSwidth - 8 - GLOBALwidth; voiceButtonOFFposY = 20; voiceButtonOFFposW = OFFwidth + 5; @@ -435,182 +548,125 @@ public class GuiVoiceMenu extends Gui { voiceScreenButtonGLOBALposY = 15 + (voiceButtonGLOBALposY + xo) * 3 / 4; voiceScreenButtonGLOBALposW = voiceButtonGLOBALposW * 3 / 4; voiceScreenButtonGLOBALposH = voiceButtonGLOBALposH * 3 / 4; - - if(channel == EnumVoiceChannelType.NONE) { + + if (channel == EnumVoiceChannelType.NONE) { drawOutline(voiceButtonOFFposX, voiceButtonOFFposY, voiceButtonOFFposW, voiceButtonOFFposH, 0xFFCCCCCC); drawRect(voiceButtonOFFposX + 1, voiceButtonOFFposY + 1, voiceButtonOFFposX + voiceButtonOFFposW - 2, voiceButtonOFFposY + voiceButtonOFFposH - 1, 0xFF222222); - }else if(mx >= voiceScreenButtonOFFposX && my >= voiceScreenButtonOFFposY && mx < voiceScreenButtonOFFposX + - voiceScreenButtonOFFposW && my < voiceScreenButtonOFFposY + voiceScreenButtonOFFposH) { + } else if (mx >= voiceScreenButtonOFFposX && my >= voiceScreenButtonOFFposY + && mx < voiceScreenButtonOFFposX + voiceScreenButtonOFFposW + && my < voiceScreenButtonOFFposY + voiceScreenButtonOFFposH) { drawOutline(voiceButtonOFFposX, voiceButtonOFFposY, voiceButtonOFFposW, voiceButtonOFFposH, 0xFF777777); } - if(channel == EnumVoiceChannelType.PROXIMITY) { - drawOutline(voiceButtonRADIUSposX, voiceButtonRADIUSposY, voiceButtonRADIUSposW, voiceButtonRADIUSposH, 0xFFCCCCCC); - drawRect(voiceButtonRADIUSposX + 1, voiceButtonRADIUSposY + 1, voiceButtonRADIUSposX + voiceButtonRADIUSposW - 2, + if (channel == EnumVoiceChannelType.PROXIMITY) { + drawOutline(voiceButtonRADIUSposX, voiceButtonRADIUSposY, voiceButtonRADIUSposW, voiceButtonRADIUSposH, + 0xFFCCCCCC); + drawRect(voiceButtonRADIUSposX + 1, voiceButtonRADIUSposY + 1, + voiceButtonRADIUSposX + voiceButtonRADIUSposW - 2, voiceButtonRADIUSposY + voiceButtonRADIUSposH - 1, 0xFF222222); - }else if(mx >= voiceScreenButtonRADIUSposX && my >= voiceScreenButtonRADIUSposY && mx < voiceScreenButtonRADIUSposX + - voiceScreenButtonRADIUSposW && my < voiceScreenButtonRADIUSposY + voiceScreenButtonRADIUSposH) { - drawOutline(voiceButtonRADIUSposX, voiceButtonRADIUSposY, voiceButtonRADIUSposW, voiceButtonRADIUSposH, 0xFF777777); + } else if (mx >= voiceScreenButtonRADIUSposX && my >= voiceScreenButtonRADIUSposY + && mx < voiceScreenButtonRADIUSposX + voiceScreenButtonRADIUSposW + && my < voiceScreenButtonRADIUSposY + voiceScreenButtonRADIUSposH) { + drawOutline(voiceButtonRADIUSposX, voiceButtonRADIUSposY, voiceButtonRADIUSposW, voiceButtonRADIUSposH, + 0xFF777777); } - if(channel == EnumVoiceChannelType.GLOBAL) { - drawOutline(voiceButtonGLOBALposX, voiceButtonGLOBALposY, voiceButtonGLOBALposW, voiceButtonGLOBALposH, 0xFFCCCCCC); - drawRect(voiceButtonGLOBALposX + 1, voiceButtonGLOBALposY + 1, voiceButtonGLOBALposX + voiceButtonGLOBALposW - 2, + if (channel == EnumVoiceChannelType.GLOBAL) { + drawOutline(voiceButtonGLOBALposX, voiceButtonGLOBALposY, voiceButtonGLOBALposW, voiceButtonGLOBALposH, + 0xFFCCCCCC); + drawRect(voiceButtonGLOBALposX + 1, voiceButtonGLOBALposY + 1, + voiceButtonGLOBALposX + voiceButtonGLOBALposW - 2, voiceButtonGLOBALposY + voiceButtonGLOBALposH - 1, 0xFF222222); - }else if(mx >= voiceScreenButtonGLOBALposX && my >= voiceScreenButtonGLOBALposY && mx < voiceScreenButtonGLOBALposX + - voiceScreenButtonGLOBALposW && my < voiceScreenButtonGLOBALposY + voiceScreenButtonGLOBALposH) { - drawOutline(voiceButtonGLOBALposX, voiceButtonGLOBALposY, voiceButtonGLOBALposW, voiceButtonGLOBALposH, 0xFF777777); + } else if (mx >= voiceScreenButtonGLOBALposX && my >= voiceScreenButtonGLOBALposY + && mx < voiceScreenButtonGLOBALposX + voiceScreenButtonGLOBALposW + && my < voiceScreenButtonGLOBALposY + voiceScreenButtonGLOBALposH) { + drawOutline(voiceButtonGLOBALposX, voiceButtonGLOBALposY, voiceButtonGLOBALposW, voiceButtonGLOBALposH, + 0xFF777777); } - int enabledColor = (status == EnumVoiceChannelStatus.CONNECTED || channel == EnumVoiceChannelType.NONE) ? 0x66DD66 : 0xDDCC66; + int enabledColor = (status == EnumVoiceChannelStatus.CONNECTED || channel == EnumVoiceChannelType.NONE) + ? 0x66DD66 + : 0xDDCC66; int disabledColor = 0xDD4444; - - if(channel != EnumVoiceChannelType.NONE && status == EnumVoiceChannelStatus.UNAVAILABLE) { + + if (channel != EnumVoiceChannelType.NONE && status == EnumVoiceChannelStatus.UNAVAILABLE) { enabledColor = disabledColor; } - - drawString(fontRendererObj, OFFstring, 3 - OFFwidth - 8 - RADIUSwidth - 8 - GLOBALwidth, 24, channel == EnumVoiceChannelType.NONE ? enabledColor : disabledColor); - drawString(fontRendererObj, RADIUSstring, 3 - RADIUSwidth - 8 - GLOBALwidth, 24, channel == EnumVoiceChannelType.PROXIMITY ? enabledColor : disabledColor); - drawString(fontRendererObj, GLOBALstring, 3 - GLOBALwidth, 24, channel == EnumVoiceChannelType.GLOBAL ? enabledColor : disabledColor); - + + drawString(fontRendererObj, OFFstring, 3 - OFFwidth - 8 - RADIUSwidth - 8 - GLOBALwidth, 24, + channel == EnumVoiceChannelType.NONE ? enabledColor : disabledColor); + drawString(fontRendererObj, RADIUSstring, 3 - RADIUSwidth - 8 - GLOBALwidth, 24, + channel == EnumVoiceChannelType.PROXIMITY ? enabledColor : disabledColor); + drawString(fontRendererObj, GLOBALstring, 3 - GLOBALwidth, 24, + channel == EnumVoiceChannelType.GLOBAL ? enabledColor : disabledColor); + GlStateManager.popMatrix(); - - if(showingCompatWarning) { - - drawNotice(I18n.format("voice.unsupportedWarning1"), false, I18n.format("voice.unsupportedWarning2"), I18n.format("voice.unsupportedWarning3"), - "", I18n.format("voice.unsupportedWarning4"), I18n.format("voice.unsupportedWarning5"), I18n.format("voice.unsupportedWarning6"), - I18n.format("voice.unsupportedWarning7"), "", I18n.format("voice.unsupportedWarning8"), I18n.format("voice.unsupportedWarning9")); - + + if (showingCompatWarning) { + + drawNotice(I18n.format("voice.unsupportedWarning1"), false, I18n.format("voice.unsupportedWarning2"), + I18n.format("voice.unsupportedWarning3"), "", I18n.format("voice.unsupportedWarning4"), + I18n.format("voice.unsupportedWarning5"), I18n.format("voice.unsupportedWarning6"), + I18n.format("voice.unsupportedWarning7"), "", I18n.format("voice.unsupportedWarning8"), + I18n.format("voice.unsupportedWarning9")); + noticeContinueButton.visible = true; noticeCancelButton.visible = false; - }else if(showingTrackingWarning) { - - drawNotice(I18n.format("voice.ipGrabWarning1"), true, I18n.format("voice.ipGrabWarning2"), I18n.format("voice.ipGrabWarning3"), - I18n.format("voice.ipGrabWarning4"), "", I18n.format("voice.ipGrabWarning5"), I18n.format("voice.ipGrabWarning6"), + } else if (showingTrackingWarning) { + + drawNotice(I18n.format("voice.ipGrabWarning1"), true, I18n.format("voice.ipGrabWarning2"), + I18n.format("voice.ipGrabWarning3"), I18n.format("voice.ipGrabWarning4"), "", + I18n.format("voice.ipGrabWarning5"), I18n.format("voice.ipGrabWarning6"), I18n.format("voice.ipGrabWarning7")); - + noticeContinueButton.visible = true; noticeCancelButton.visible = true; - }else { + } else { noticeContinueButton.visible = false; noticeCancelButton.visible = false; } - + drawButtons(mx, my, partialTicks); - if(showingCompatWarning || showingTrackingWarning) { + if (showingCompatWarning || showingTrackingWarning) { throw new AbortedException(); } } - - private void drawNotice(String title, boolean showCancel, String... lines) { - - int widthAccum = 0; - - for(int i = 0; i < lines.length; ++i) { - int w = fontRendererObj.getStringWidth(lines[i]); - if(widthAccum < w) { - widthAccum = w; - } - } - - int margin = 15; - - int x = (width - widthAccum) / 2; - int y = (height - lines.length * 10 - 60 - margin) / 2; - drawRect(x - margin - 1, y - margin - 1, x + widthAccum + margin + 1, - y + lines.length * 10 + 49 + margin, 0xFFCCCCCC); - drawRect(x - margin, y - margin, x + widthAccum + margin, - y + lines.length * 10 + 48 + margin, 0xFF111111); - - drawCenteredString(fontRendererObj, EnumChatFormatting.BOLD + title, width / 2, y, 0xFF7766); - - for(int i = 0; i < lines.length; ++i) { - drawString(fontRendererObj, lines[i], x, y + i * 10 + 18, 0xDDAAAA); - } - - if(!showCancel) { - noticeContinueButton.width = 150; - noticeContinueButton.xPosition = (width - 150) / 2; - noticeContinueButton.yPosition = y + lines.length * 10 + 29; - }else { - noticeContinueButton.width = widthAccum / 2 - 10; - noticeContinueButton.xPosition = (width - widthAccum) / 2 + widthAccum / 2 + 3; - noticeContinueButton.yPosition = y + lines.length * 10 + 28; - noticeCancelButton.width = widthAccum / 2 - 10; - noticeCancelButton.xPosition = (width - widthAccum) / 2 + 4; - noticeCancelButton.yPosition = y + lines.length * 10 + 28; - } - - } - - public static int attenuate(int cin, float f) { - return attenuate(cin, f, f, f, 1.0f); - } - - public static int attenuate(int cin, float r, float g, float b, float a) { - float var10 = (float) (cin >>> 24 & 255) / 255.0F; - float var6 = (float) (cin >>> 16 & 255) / 255.0F; - float var7 = (float) (cin >>> 8 & 255) / 255.0F; - float var8 = (float) (cin & 255) / 255.0F; - var10 *= a; - var6 *= r; - var7 *= g; - var8 *= b; - if(var10 > 1.0f) { - var10 = 1.0f; - } - if(var6 > 1.0f) { - var6 = 1.0f; - } - if(var7 > 1.0f) { - var7 = 1.0f; - } - if(var8 > 1.0f) { - var8 = 1.0f; - } - return (((int)(var10 * 255.0f) << 24) | ((int)(var6 * 255.0f) << 16) | ((int)(var7 * 255.0f) << 8) | (int)(var8 * 255.0f)); - } - - private void drawOutline(int x, int y, int w, int h, int color) { - drawRect(x, y, x + w, y + 1, color); - drawRect(x + w - 1, y + 1, x + w, y + h - 1, color); - drawRect(x, y + h - 1, x + w, y + h, color); - drawRect(x, y + 1, x + 1, y + h - 1, color); - } - - public void mouseReleased(int par1, int par2, int par3) { - if(par3 != 0 && par3 != 12345) return; - boolean touchMode = PointerInputAbstraction.isTouchMode(); - if(!touchMode || par3 == 0) { - applyRadiusButton.mouseReleased(par1, par2); - applyVolumeButton.mouseReleased(par1, par2); - noticeContinueButton.mouseReleased(par1, par2); - noticeCancelButton.mouseReleased(par1, par2); - } - if(showSliderBlocks || showSliderVolume) { - if(showSliderBlocks) { - if(!touchMode || par3 == 12345) { - sliderBlocks.mouseReleased(par1, par2); - } - }else if(showSliderVolume) { - if(!touchMode || par3 == 12345) { - sliderListenVolume.mouseReleased(par1, par2); - sliderSpeakVolume.mouseReleased(par1, par2); - } + public void initGui() { + this.sliderBlocks = new GuiSlider2(-1, (width - 150) / 2, height / 3 + 20, 150, 20, + (VoiceClientController.getVoiceProximity() - 5) / 17.0f, 1.0f) { + protected String updateDisplayString() { + return (int) ((sliderValue * 17.0f) + 5.0f) + " Blocks"; } - throw new AbortedException(); - } + }; + sliderBlocks.displayString = "" + VoiceClientController.getVoiceProximity() + " Blocks"; + this.sliderListenVolume = new GuiSlider2(-1, (width - 150) / 2, height / 3 + 10, 150, 20, + VoiceClientController.getVoiceListenVolume(), 1.0f); + this.sliderSpeakVolume = new GuiSlider2(-1, (width - 150) / 2, height / 3 + 56, 150, 20, + VoiceClientController.getVoiceSpeakVolume(), 1.0f); + + applyRadiusButton = new GuiButton(2, (width - 150) / 2, height / 3 + 49, 150, 20, I18n.format("voice.apply")); + applyVolumeButton = new GuiButton(3, (width - 150) / 2, height / 3 + 90, 150, 20, I18n.format("voice.apply")); + noticeContinueButton = new GuiButton(5, (width - 150) / 2, height / 3 + 60, 150, 20, + I18n.format("voice.unsupportedWarning10")); + noticeCancelButton = new GuiButton(6, (width - 150) / 2, height / 3 + 90, 150, 20, + I18n.format("voice.unsupportedWarning11")); + applyRadiusButton.visible = applyVolumeButton.visible = noticeContinueButton.visible = noticeCancelButton.visible = false; } - + + public boolean isBlockingInput() { + return showSliderBlocks || showSliderVolume || showPTTKeyConfig || showingCompatWarning + || showingTrackingWarning; + } + public void keyTyped(char par1, int par2) { - if(showSliderBlocks || showSliderVolume || showPTTKeyConfig) { - if(showPTTKeyConfig) { - if(par2 == 1) { + if (showSliderBlocks || showSliderVolume || showPTTKeyConfig) { + if (showPTTKeyConfig) { + if (par2 == 1) { showPTTKeyConfig = false; - }else { + } else { mc.gameSettings.voicePTTKey = par2; showNewPTTKey = 10; } @@ -618,98 +674,121 @@ public class GuiVoiceMenu extends Gui { throw new AbortedException(); } } - + public void mouseClicked(int mx, int my, int button) { - if(button != 0 && button != 12345) return; + if (button != 0 && button != 12345) + return; boolean touchMode = PointerInputAbstraction.isTouchMode(); - if(showSliderBlocks || showSliderVolume || showPTTKeyConfig || showingCompatWarning || showingTrackingWarning) { - if(showSliderBlocks) { - if(!touchMode || button == 12345) { + if (showSliderBlocks || showSliderVolume || showPTTKeyConfig || showingCompatWarning + || showingTrackingWarning) { + if (showSliderBlocks) { + if (!touchMode || button == 12345) { sliderBlocks.mousePressed(mc, mx, my); } - }else if(showSliderVolume) { - if(!touchMode || button == 12345) { + } else if (showSliderVolume) { + if (!touchMode || button == 12345) { sliderListenVolume.mousePressed(mc, mx, my); sliderSpeakVolume.mousePressed(mc, mx, my); } } - if((!touchMode || button == 0) && applyRadiusButton.mousePressed(mc, mx, my)) actionPerformed(applyRadiusButton); - if((!touchMode || button == 0) && applyVolumeButton.mousePressed(mc, mx, my)) actionPerformed(applyVolumeButton); - if((!touchMode || button == 0) && noticeContinueButton.mousePressed(mc, mx, my)) actionPerformed(noticeContinueButton); - if((!touchMode || button == 0) && noticeCancelButton.mousePressed(mc, mx, my)) actionPerformed(noticeCancelButton); + if ((!touchMode || button == 0) && applyRadiusButton.mousePressed(mc, mx, my)) + actionPerformed(applyRadiusButton); + if ((!touchMode || button == 0) && applyVolumeButton.mousePressed(mc, mx, my)) + actionPerformed(applyVolumeButton); + if ((!touchMode || button == 0) && noticeContinueButton.mousePressed(mc, mx, my)) + actionPerformed(noticeContinueButton); + if ((!touchMode || button == 0) && noticeCancelButton.mousePressed(mc, mx, my)) + actionPerformed(noticeCancelButton); throw new AbortedException(); } - + EnumVoiceChannelStatus status = VoiceClientController.getVoiceStatus(); EnumVoiceChannelType channel = VoiceClientController.getVoiceChannel(); - - if(button == 0) { - if(VoiceClientController.isSupported()) { - if(mx >= voiceScreenButtonOFFposX && my >= voiceScreenButtonOFFposY && mx < voiceScreenButtonOFFposX + - voiceScreenButtonOFFposW && my < voiceScreenButtonOFFposY + voiceScreenButtonOFFposH) { + + if (button == 0) { + if (VoiceClientController.isSupported()) { + if (mx >= voiceScreenButtonOFFposX && my >= voiceScreenButtonOFFposY + && mx < voiceScreenButtonOFFposX + voiceScreenButtonOFFposW + && my < voiceScreenButtonOFFposY + voiceScreenButtonOFFposH) { VoiceClientController.setVoiceChannel(EnumVoiceChannelType.NONE); - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - }else if(mx >= voiceScreenButtonRADIUSposX && my >= voiceScreenButtonRADIUSposY && mx < voiceScreenButtonRADIUSposX + - voiceScreenButtonRADIUSposW && my < voiceScreenButtonRADIUSposY + voiceScreenButtonRADIUSposH) { - - if(showCompatWarning) { + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } else if (mx >= voiceScreenButtonRADIUSposX && my >= voiceScreenButtonRADIUSposY + && mx < voiceScreenButtonRADIUSposX + voiceScreenButtonRADIUSposW + && my < voiceScreenButtonRADIUSposY + voiceScreenButtonRADIUSposH) { + + if (showCompatWarning) { continueChannel = EnumVoiceChannelType.PROXIMITY; showingCompatWarning = true; - }else if(showTrackingWarning) { + } else if (showTrackingWarning) { continueChannel = EnumVoiceChannelType.PROXIMITY; showingTrackingWarning = true; - }else { + } else { VoiceClientController.setVoiceChannel(EnumVoiceChannelType.PROXIMITY); } - - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - - }else if(mx >= voiceScreenButtonGLOBALposX && my >= voiceScreenButtonGLOBALposY && mx < voiceScreenButtonGLOBALposX + - voiceScreenButtonGLOBALposW && my < voiceScreenButtonGLOBALposY + voiceScreenButtonGLOBALposH) { - - if(showCompatWarning) { + + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + + } else if (mx >= voiceScreenButtonGLOBALposX && my >= voiceScreenButtonGLOBALposY + && mx < voiceScreenButtonGLOBALposX + voiceScreenButtonGLOBALposW + && my < voiceScreenButtonGLOBALposY + voiceScreenButtonGLOBALposH) { + + if (showCompatWarning) { continueChannel = EnumVoiceChannelType.GLOBAL; showingCompatWarning = true; - }else if(showTrackingWarning) { + } else if (showTrackingWarning) { continueChannel = EnumVoiceChannelType.GLOBAL; showingTrackingWarning = true; - }else { + } else { VoiceClientController.setVoiceChannel(EnumVoiceChannelType.GLOBAL); } - - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - }else if(channel == EnumVoiceChannelType.PROXIMITY && status == EnumVoiceChannelStatus.CONNECTED && mx >= voiceScreenButtonChangeRadiusposX && - my >= voiceScreenButtonChangeRadiusposY && mx < voiceScreenButtonChangeRadiusposX + voiceScreenButtonChangeRadiusposW && - my < voiceScreenButtonChangeRadiusposY + voiceScreenButtonChangeRadiusposH) { + + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } else if (channel == EnumVoiceChannelType.PROXIMITY && status == EnumVoiceChannelStatus.CONNECTED + && mx >= voiceScreenButtonChangeRadiusposX && my >= voiceScreenButtonChangeRadiusposY + && mx < voiceScreenButtonChangeRadiusposX + voiceScreenButtonChangeRadiusposW + && my < voiceScreenButtonChangeRadiusposY + voiceScreenButtonChangeRadiusposH) { showSliderBlocks = true; sliderBlocks.sliderValue = (VoiceClientController.getVoiceProximity() - 5) / 17.0f; - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - }else if(status == EnumVoiceChannelStatus.CONNECTED && channel != EnumVoiceChannelType.NONE && mx >= voiceScreenVolumeIndicatorX && - my >= voiceScreenVolumeIndicatorY && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW && - my < voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH) { + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } else if (status == EnumVoiceChannelStatus.CONNECTED && channel != EnumVoiceChannelType.NONE + && mx >= voiceScreenVolumeIndicatorX && my >= voiceScreenVolumeIndicatorY + && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + && my < voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH) { showSliderVolume = true; sliderListenVolume.sliderValue = VoiceClientController.getVoiceListenVolume(); sliderSpeakVolume.sliderValue = VoiceClientController.getVoiceSpeakVolume(); - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - }else if(status == EnumVoiceChannelStatus.CONNECTED && channel != EnumVoiceChannelType.NONE && mx >= voiceScreenVolumeIndicatorX - 1 && - my >= voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH + 2 && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + 2 && - my < voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH + 12) { + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } else if (status == EnumVoiceChannelStatus.CONNECTED && channel != EnumVoiceChannelType.NONE + && mx >= voiceScreenVolumeIndicatorX - 1 + && my >= voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH + 2 + && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + 2 + && my < voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH + 12) { showPTTKeyConfig = true; - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); - }else if(status == EnumVoiceChannelStatus.CONNECTED) { + this.mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + } else if (status == EnumVoiceChannelStatus.CONNECTED) { List playersToRender = VoiceClientController.getVoiceRecent(); - if(playersToRender.size() > 0) { + if (playersToRender.size() > 0) { Set playersMuted = VoiceClientController.getVoiceMuted(); - for(int i = 0, l = playersToRender.size(); i < l; ++i) { + for (int i = 0, l = playersToRender.size(); i < l; ++i) { EaglercraftUUID uuid = playersToRender.get(i); String txt = VoiceClientController.getVoiceUsername(uuid); boolean muted = playersMuted.contains(uuid); int mhy = voiceScreenVolumeIndicatorY + voiceScreenVolumeIndicatorH + 33 + i * 9; - if(mx >= voiceScreenVolumeIndicatorX - 3 && my >= mhy && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + 2 && my < mhy + 9) { + if (mx >= voiceScreenVolumeIndicatorX - 3 && my >= mhy + && mx < voiceScreenVolumeIndicatorX + voiceScreenVolumeIndicatorW + 2 + && my < mhy + 9) { VoiceClientController.setVoiceMuted(uuid, !muted); - this.mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + this.mc.getSoundHandler().playSound( + PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); break; } } @@ -717,56 +796,50 @@ public class GuiVoiceMenu extends Gui { } } } - + } - - private void actionPerformed(GuiButton btn) { - if(btn.id == 2) { - showSliderBlocks = false; - VoiceClientController.setVoiceProximity(mc.gameSettings.voiceListenRadius = (int)((sliderBlocks.sliderValue * 17.0f) + 5.0f)); - mc.gameSettings.saveOptions(); - }else if(btn.id == 3) { - showSliderVolume = false; - VoiceClientController.setVoiceListenVolume(mc.gameSettings.voiceListenVolume = sliderListenVolume.sliderValue); - VoiceClientController.setVoiceSpeakVolume(mc.gameSettings.voiceSpeakVolume = sliderSpeakVolume.sliderValue); - mc.gameSettings.saveOptions(); - }else if(btn.id == 4) { - showPTTKeyConfig = false; - mc.gameSettings.saveOptions(); - }else if(btn.id == 5) { - if(showingCompatWarning) { - showingCompatWarning = false; - showCompatWarning = false; - if(showTrackingWarning) { - showingTrackingWarning = true; - }else { - VoiceClientController.setVoiceChannel(continueChannel); + + public void mouseReleased(int par1, int par2, int par3) { + if (par3 != 0 && par3 != 12345) + return; + boolean touchMode = PointerInputAbstraction.isTouchMode(); + if (!touchMode || par3 == 0) { + applyRadiusButton.mouseReleased(par1, par2); + applyVolumeButton.mouseReleased(par1, par2); + noticeContinueButton.mouseReleased(par1, par2); + noticeCancelButton.mouseReleased(par1, par2); + } + if (showSliderBlocks || showSliderVolume) { + if (showSliderBlocks) { + if (!touchMode || par3 == 12345) { + sliderBlocks.mouseReleased(par1, par2); + } + } else if (showSliderVolume) { + if (!touchMode || par3 == 12345) { + sliderListenVolume.mouseReleased(par1, par2); + sliderSpeakVolume.mouseReleased(par1, par2); } - }else if(showingTrackingWarning) { - showingTrackingWarning = false; - showTrackingWarning = false; - VoiceClientController.setVoiceChannel(continueChannel); - } - }else if(btn.id == 6) { - if(showingTrackingWarning) { - showingTrackingWarning = false; - VoiceClientController.setVoiceChannel(EnumVoiceChannelType.NONE); } + throw new AbortedException(); } } - + + public void setResolution(Minecraft mc, int w, int h) { + this.mc = mc; + this.fontRendererObj = mc.fontRendererObj; + this.width = w; + this.height = h; + initGui(); + } + public void updateScreen() { - if(showNewPTTKey > 0) { + if (showNewPTTKey > 0) { --showNewPTTKey; - if(showNewPTTKey == 0) { + if (showNewPTTKey == 0) { showPTTKeyConfig = false; mc.gameSettings.saveOptions(); } } } - public boolean isBlockingInput() { - return showSliderBlocks || showSliderVolume || showPTTKeyConfig || showingCompatWarning || showingTrackingWarning; - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceOverlay.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceOverlay.java index b6534cb6..97f7ac2a 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceOverlay.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/GuiVoiceOverlay.java @@ -19,88 +19,86 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class GuiVoiceOverlay extends Gui { + private static final ResourceLocation voiceGuiIcons = new ResourceLocation("eagler:gui/eagler_gui.png"); public final Minecraft mc; public int width; + public int height; - + private long pttTimer = 0l; - + public GuiVoiceOverlay(Minecraft mc) { this.mc = mc; } - - public void setResolution(int w, int h) { - this.width = w; - this.height = h; - } - - private static final ResourceLocation voiceGuiIcons = new ResourceLocation("eagler:gui/eagler_gui.png"); public void drawOverlay() { - if(mc.theWorld != null && VoiceClientController.getVoiceStatus() == EnumVoiceChannelStatus.CONNECTED && VoiceClientController.getVoiceChannel() != EnumVoiceChannelType.NONE && - !(mc.currentScreen != null && (mc.currentScreen instanceof GuiIngameMenu))) { - - if(mc.currentScreen != null && mc.currentScreen.doesGuiPauseGame()) { + if (mc.theWorld != null && VoiceClientController.getVoiceStatus() == EnumVoiceChannelStatus.CONNECTED + && VoiceClientController.getVoiceChannel() != EnumVoiceChannelType.NONE + && !(mc.currentScreen != null && (mc.currentScreen instanceof GuiIngameMenu))) { + + if (mc.currentScreen != null && mc.currentScreen.doesGuiPauseGame()) { return; } - + GlStateManager.disableLighting(); GlStateManager.disableBlend(); GlStateManager.enableAlpha(); GlStateManager.alphaFunc(GL_GREATER, 0.1F); GlStateManager.pushMatrix(); - - if(mc.currentScreen == null || (mc.currentScreen instanceof GuiChat)) { + + if (mc.currentScreen == null || (mc.currentScreen instanceof GuiChat)) { GlStateManager.translate(width / 2 + 77, height - 56, 0.0f); - if(mc.thePlayer == null || mc.thePlayer.capabilities.isCreativeMode) { + if (mc.thePlayer == null || mc.thePlayer.capabilities.isCreativeMode) { GlStateManager.translate(0.0f, 16.0f, 0.0f); } - }else { + } else { GlStateManager.translate(width / 2 + 10, 4, 0.0f); } GlStateManager.scale(0.75f, 0.75f, 0.75f); - + String txxt = "press '" + Keyboard.getKeyName(mc.gameSettings.voicePTTKey) + "'"; drawString(mc.fontRendererObj, txxt, -3 - mc.fontRendererObj.getStringWidth(txxt), 9, 0xDDDDDD); GlStateManager.scale(0.66f, 0.66f, 0.66f); - + mc.getTextureManager().bindTexture(voiceGuiIcons); - - if((mc.currentScreen == null || !mc.currentScreen.blockPTTKey()) && Keyboard.isKeyDown(mc.gameSettings.voicePTTKey)) { + + if ((mc.currentScreen == null || !mc.currentScreen.blockPTTKey()) + && Keyboard.isKeyDown(mc.gameSettings.voicePTTKey)) { long millis = EagRuntime.steadyTimeMillis(); - if(pttTimer == 0l) { + if (pttTimer == 0l) { pttTimer = millis; } GlStateManager.color(0.2f, 0.2f, 0.2f, 1.0f); drawTexturedModalRect(0, 0, 0, 64, 32, 32); GlStateManager.translate(-1.5f, -1.5f, 0.0f); - if(millis - pttTimer < 1050l) { - if((millis - pttTimer) % 300l < 150l) { + if (millis - pttTimer < 1050l) { + if ((millis - pttTimer) % 300l < 150l) { GlStateManager.color(0.9f, 0.2f, 0.2f, 1.0f); - }else { + } else { GlStateManager.color(0.9f, 0.7f, 0.7f, 1.0f); } - }else { + } else { GlStateManager.color(0.9f, 0.3f, 0.3f, 1.0f); } drawTexturedModalRect(0, 0, 0, 64, 32, 32); - }else { + } else { pttTimer = 0l; GlStateManager.color(0.2f, 0.2f, 0.2f, 1.0f); drawTexturedModalRect(0, 0, 0, 32, 32, 32); @@ -110,55 +108,55 @@ public class GuiVoiceOverlay extends Gui { GlStateManager.translate(-0.5f, -0.5f, 0.0f); drawTexturedModalRect(0, 0, 0, 32, 32, 32); } - + GlStateManager.popMatrix(); - - if(VoiceClientController.getVoiceChannel() == EnumVoiceChannelType.PROXIMITY) { + + if (VoiceClientController.getVoiceChannel() == EnumVoiceChannelType.PROXIMITY) { Set listeners = VoiceClientController.getVoiceListening(); - if(listeners.size() > 0) { + if (listeners.size() > 0) { Set speakers = VoiceClientController.getVoiceSpeaking(); Set muted = VoiceClientController.getVoiceMuted(); - + List listenerList = new ArrayList<>(); listenerList.addAll(listeners); listenerList.removeAll(muted); - - while(listenerList.size() > 5) { + + while (listenerList.size() > 5) { boolean flag = false; - for(int i = 0, l = listenerList.size(); i < l; ++i) { - if(!speakers.contains(listenerList.get(i))) { + for (int i = 0, l = listenerList.size(); i < l; ++i) { + if (!speakers.contains(listenerList.get(i))) { listenerList.remove(i); flag = true; break; } } - if(!flag) { + if (!flag) { break; } } - + int more = listenerList.size() - 5; - + int ww = width; int hh = height; - - if(mc.currentScreen != null && (mc.currentScreen instanceof GuiChat)) { + + if (mc.currentScreen != null && (mc.currentScreen instanceof GuiChat)) { hh -= 15; } - + List listenerListStr = new ArrayList<>(Math.min(5, listenerList.size())); - + int left = 50; - for(int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { + for (int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { String txt = VoiceClientController.getVoiceUsername(listenerList.get(i)); listenerListStr.add(txt); int j = mc.fontRendererObj.getStringWidth(txt) + 4; - if(j > left) { + if (j > left) { left = j; } } - - if(more > 0) { + + if (more > 0) { GlStateManager.pushMatrix(); GlStateManager.translate(ww - left + 3, hh - 10, left); GlStateManager.scale(0.75f, 0.75f, 0.75f); @@ -166,63 +164,64 @@ public class GuiVoiceOverlay extends Gui { GlStateManager.popMatrix(); hh -= 9; } - - for(int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { + + for (int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { boolean speaking = speakers.contains(listenerList.get(i)); float speakf = speaking ? 1.0f : 0.75f; - - drawString(mc.fontRendererObj, listenerListStr.get(i), ww - left, hh - 13 - i * 11, speaking ? 0xEEEEEE : 0xBBBBBB); - + + drawString(mc.fontRendererObj, listenerListStr.get(i), ww - left, hh - 13 - i * 11, + speaking ? 0xEEEEEE : 0xBBBBBB); + mc.getTextureManager().bindTexture(voiceGuiIcons); - + GlStateManager.pushMatrix(); GlStateManager.translate(ww - left - 14, hh - 14 - i * 11, 0.0f); - + GlStateManager.scale(0.75f, 0.75f, 0.75f); GlStateManager.color(speakf * 0.2f, speakf * 0.2f, speakf * 0.2f, 1.0f); drawTexturedModalRect(0, 0, 64, speaking ? 176 : 208, 16, 16); GlStateManager.translate(0.25f, 0.25f, 0.0f); drawTexturedModalRect(0, 0, 64, speaking ? 176 : 208, 16, 16); - + GlStateManager.translate(-1.25f, -1.25f, 0.0f); GlStateManager.color(speakf, speakf, speakf, 1.0f); drawTexturedModalRect(0, 0, 64, speaking ? 176 : 208, 16, 16); - + GlStateManager.popMatrix(); - + } - + } - }else if(VoiceClientController.getVoiceChannel() == EnumVoiceChannelType.GLOBAL) { + } else if (VoiceClientController.getVoiceChannel() == EnumVoiceChannelType.GLOBAL) { Set speakers = VoiceClientController.getVoiceSpeaking(); Set muted = VoiceClientController.getVoiceMuted(); - + List listenerList = new ArrayList<>(); listenerList.addAll(speakers); listenerList.removeAll(muted); - + int more = listenerList.size() - 5; - + int ww = width; int hh = height; - - if(mc.currentScreen != null && (mc.currentScreen instanceof GuiChat)) { + + if (mc.currentScreen != null && (mc.currentScreen instanceof GuiChat)) { hh -= 15; } - + List listenerListStr = new ArrayList<>(Math.min(5, listenerList.size())); - + int left = 50; - for(int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { + for (int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { String txt = VoiceClientController.getVoiceUsername(listenerList.get(i)); listenerListStr.add(txt); int j = mc.fontRendererObj.getStringWidth(txt) + 4; - if(j > left) { + if (j > left) { left = j; } } - - if(more > 0) { + + if (more > 0) { GlStateManager.pushMatrix(); GlStateManager.translate(ww - left + 3, hh - 10, left); GlStateManager.scale(0.75f, 0.75f, 0.75f); @@ -230,30 +229,35 @@ public class GuiVoiceOverlay extends Gui { GlStateManager.popMatrix(); hh -= 9; } - - for(int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { + + for (int i = 0, l = listenerList.size(); i < l && i < 5; ++i) { drawString(mc.fontRendererObj, listenerListStr.get(i), ww - left, hh - 13 - i * 11, 0xEEEEEE); - + mc.getTextureManager().bindTexture(voiceGuiIcons); - + GlStateManager.pushMatrix(); GlStateManager.translate(ww - left - 14, hh - 14 - i * 11, 0.0f); - + GlStateManager.scale(0.75f, 0.75f, 0.75f); GlStateManager.color(0.2f, 0.2f, 0.2f, 1.0f); drawTexturedModalRect(0, 0, 64, 176, 16, 16); GlStateManager.translate(0.25f, 0.25f, 0.0f); drawTexturedModalRect(0, 0, 64, 176, 16, 16); - + GlStateManager.translate(-1.25f, -1.25f, 0.0f); GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f); drawTexturedModalRect(0, 0, 64, 176, 16, 16); - + GlStateManager.popMatrix(); - + } } } } + public void setResolution(int w, int h) { + this.width = w; + this.height = h; + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceClientController.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceClientController.java index 4e177ad1..33605815 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceClientController.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceClientController.java @@ -18,7 +18,13 @@ import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; import net.lax1dude.eaglercraft.v1_8.profile.EaglerProfile; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalConnectEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectPeerV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalRequestEAG; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalGlobalEAG; import net.minecraft.client.Minecraft; import net.minecraft.entity.player.EntityPlayer; @@ -26,14 +32,15 @@ import net.minecraft.entity.player.EntityPlayer; /** * Copyright (c) 2022-2024 lax1dude, ayunami2000. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -57,54 +64,93 @@ public class VoiceClientController { }); private static final Map uuidToNameLookup = new HashMap<>(256); - public static boolean isSupported() { - return isClientSupported() && isServerSupported(); - } - private static boolean checked = false; - public static boolean isClientSupported() { - if (!checked) { - checked = true; - clientSupport = EagRuntime.getConfiguration().isAllowVoiceClient() && PlatformVoiceClient.isSupported(); - } - return clientSupport; - } + private static boolean talkStatus = false; - public static boolean isServerSupported() { - return serverSupport; - } + private static int proximity = 16; - public static void initializeVoiceClient(Consumer signalSendCallbackIn, int proto) { - packetSendCallback = signalSendCallbackIn; - protocolVersion = proto; - uuidToNameLookup.clear(); - if (getVoiceChannel() != EnumVoiceChannelType.NONE) sendInitialVoice(); - } + private static float volumeListen = 0.5f; - public static void handleVoiceSignalPacketTypeGlobal(EaglercraftUUID[] voicePlayers, String[] voiceNames) { - uuidToNameLookup.clear(); - for (int i = 0; i < voicePlayers.length; i++) { - if(voiceNames != null) { - uuidToNameLookup.put(voicePlayers[i], voiceNames[i]); - } - sendPacketRequestIfNeeded(voicePlayers[i]); + private static float volumeSpeak = 0.5f; + + private static final Set listeningSet = new HashSet<>(); + + private static final Set speakingSet = new HashSet<>(); + + private static final Set mutedSet = new HashSet<>(); + + public static void activateVoice(boolean talk) { + if (talkStatus != talk) { + PlatformVoiceClient.activateVoice(talk); + talkStatus = talk; } } - public static void handleVoiceSignalPacketTypeGlobalNew(Collection voicePlayers) { - uuidToNameLookup.clear(); - for (SPacketVoiceSignalGlobalEAG.UserData player : voicePlayers) { - EaglercraftUUID uuid = new EaglercraftUUID(player.uuidMost, player.uuidLeast); - if(player.username != null) { - uuidToNameLookup.put(uuid, player.username); - } + public static final boolean addNearbyPlayer(EaglercraftUUID uuid) { + recentlyNearbyPlayers.remove(uuid); + if (nearbyPlayers.add(uuid)) { sendPacketRequestIfNeeded(uuid); + return true; } + return false; + } + + public static final void cleanupNearbyPlayers(HashSet existingPlayers) { + nearbyPlayers.stream().filter(ud -> !existingPlayers.contains(ud)).collect(Collectors.toSet()) + .forEach(VoiceClientController::removeNearbyPlayer); + } + + public static EnumVoiceChannelType getVoiceChannel() { + return voiceChannel; + } + + public static Set getVoiceListening() { + return listeningSet; + } + + public static float getVoiceListenVolume() { + return volumeListen; + } + + public static Set getVoiceMuted() { + return mutedSet; + } + + public static int getVoiceProximity() { + return proximity; + } + + public static List getVoiceRecent() { + return new ArrayList<>(listeningSet); + } + + public static Set getVoiceSpeaking() { + return speakingSet; + } + + public static float getVoiceSpeakVolume() { + return volumeSpeak; + } + + public static EnumVoiceChannelStatus getVoiceStatus() { + return (!isClientSupported() || !isServerSupported()) ? EnumVoiceChannelStatus.UNAVAILABLE + : (PlatformVoiceClient.getReadyState() != EnumVoiceChannelReadyState.DEVICE_INITIALIZED + ? EnumVoiceChannelStatus.CONNECTING + : (voicePeerErrored() ? EnumVoiceChannelStatus.UNAVAILABLE : EnumVoiceChannelStatus.CONNECTED)); + } + + public static String getVoiceUsername(EaglercraftUUID uuid) { + if (uuid == null) { + return "null"; + } + String ret = uuidToNameLookup.get(uuid); + return ret == null ? uuid.toString() : ret; } public static void handleServerDisconnect() { - if(!isClientSupported()) return; + if (!isClientSupported()) + return; serverSupport = false; uuidToNameLookup.clear(); for (EaglercraftUUID uuid : nearbyPlayers) { @@ -125,10 +171,10 @@ public class VoiceClientController { public static void handleVoiceSignalPacketTypeAllowed(boolean voiceAvailableStat, String[] servs) { serverSupport = voiceAvailableStat; PlatformVoiceClient.setICEServers(servs); - if(isSupported()) { + if (isSupported()) { EnumVoiceChannelType ch = getVoiceChannel(); - setVoiceChannel(EnumVoiceChannelType.NONE); - setVoiceChannel(ch); + setVoiceChannel(EnumVoiceChannelType.NONE); + setVoiceChannel(ch); } } @@ -140,75 +186,128 @@ public class VoiceClientController { sendPacketRequest(user); } + public static void handleVoiceSignalPacketTypeDescription(EaglercraftUUID user, String desc) { + PlatformVoiceClient.signalDescription(user, desc); + } + public static void handleVoiceSignalPacketTypeDisconnect(EaglercraftUUID user) { PlatformVoiceClient.signalDisconnect(user, true); } + public static void handleVoiceSignalPacketTypeGlobal(EaglercraftUUID[] voicePlayers, String[] voiceNames) { + uuidToNameLookup.clear(); + for (int i = 0; i < voicePlayers.length; i++) { + if (voiceNames != null) { + uuidToNameLookup.put(voicePlayers[i], voiceNames[i]); + } + sendPacketRequestIfNeeded(voicePlayers[i]); + } + } + + public static void handleVoiceSignalPacketTypeGlobalNew( + Collection voicePlayers) { + uuidToNameLookup.clear(); + for (SPacketVoiceSignalGlobalEAG.UserData player : voicePlayers) { + EaglercraftUUID uuid = new EaglercraftUUID(player.uuidMost, player.uuidLeast); + if (player.username != null) { + uuidToNameLookup.put(uuid, player.username); + } + sendPacketRequestIfNeeded(uuid); + } + } + public static void handleVoiceSignalPacketTypeICECandidate(EaglercraftUUID user, String ice) { PlatformVoiceClient.signalICECandidate(user, ice); } - public static void handleVoiceSignalPacketTypeDescription(EaglercraftUUID user, String desc) { - PlatformVoiceClient.signalDescription(user, desc); + public static void initializeVoiceClient(Consumer signalSendCallbackIn, int proto) { + packetSendCallback = signalSendCallbackIn; + protocolVersion = proto; + uuidToNameLookup.clear(); + if (getVoiceChannel() != EnumVoiceChannelType.NONE) + sendInitialVoice(); } - public static void tickVoiceClient(Minecraft mc) { - if(!isClientSupported()) return; - recentlyNearbyPlayers.checkForExpirations(); - speakingSet.clear(); - PlatformVoiceClient.tickVoiceClient(); - - if (getVoiceChannel() != EnumVoiceChannelType.NONE && (getVoiceStatus() == EnumVoiceChannelStatus.CONNECTING || getVoiceStatus() == EnumVoiceChannelStatus.CONNECTED)) { - activateVoice((mc.currentScreen == null || !mc.currentScreen.blockPTTKey()) && Keyboard.isKeyDown(mc.gameSettings.voicePTTKey)); - - if (mc.theWorld != null && mc.thePlayer != null) { - HashSet seenPlayers = new HashSet<>(); - for (EntityPlayer player : mc.theWorld.playerEntities) { - if (player == mc.thePlayer) continue; - if (getVoiceChannel() == EnumVoiceChannelType.PROXIMITY) updateVoicePosition(player.getUniqueID(), player.posX, player.posY + player.getEyeHeight(), player.posZ); - int prox = 22; - // cube - if (Math.abs(mc.thePlayer.posX - player.posX) <= prox && Math.abs(mc.thePlayer.posY - player.posY) <= prox && Math.abs(mc.thePlayer.posZ - player.posZ) <= prox) { - if (!uuidToNameLookup.containsKey(player.getUniqueID())) { - uuidToNameLookup.put(player.getUniqueID(), player.getName()); - } - if (addNearbyPlayer(player.getUniqueID())) { - seenPlayers.add(player.getUniqueID()); - } - } - } - cleanupNearbyPlayers(seenPlayers); - } + public static boolean isClientSupported() { + if (!checked) { + checked = true; + clientSupport = EagRuntime.getConfiguration().isAllowVoiceClient() && PlatformVoiceClient.isSupported(); } + return clientSupport; } - public static final boolean addNearbyPlayer(EaglercraftUUID uuid) { - recentlyNearbyPlayers.remove(uuid); - if (nearbyPlayers.add(uuid)) { - sendPacketRequestIfNeeded(uuid); - return true; - } - return false; + public static boolean isServerSupported() { + return serverSupport; + } + + public static boolean isSupported() { + return isClientSupported() && isServerSupported(); } public static final void removeNearbyPlayer(EaglercraftUUID uuid) { if (nearbyPlayers.remove(uuid)) { - if (getVoiceStatus() == EnumVoiceChannelStatus.DISCONNECTED || getVoiceStatus() == EnumVoiceChannelStatus.UNAVAILABLE) return; - if (voiceChannel == EnumVoiceChannelType.PROXIMITY) recentlyNearbyPlayers.add(uuid); + if (getVoiceStatus() == EnumVoiceChannelStatus.DISCONNECTED + || getVoiceStatus() == EnumVoiceChannelStatus.UNAVAILABLE) + return; + if (voiceChannel == EnumVoiceChannelType.PROXIMITY) + recentlyNearbyPlayers.add(uuid); } } - public static final void cleanupNearbyPlayers(HashSet existingPlayers) { - nearbyPlayers.stream().filter(ud -> !existingPlayers.contains(ud)).collect(Collectors.toSet()).forEach(VoiceClientController::removeNearbyPlayer); + public static void sendInitialVoice() { + sendPacketConnect(); + for (EaglercraftUUID uuid : nearbyPlayers) { + sendPacketRequest(uuid); + } } - public static final void updateVoicePosition(EaglercraftUUID uuid, double x, double y, double z) { - PlatformVoiceClient.updateVoicePosition(uuid, x, y, z); + public static void sendPacketConnect() { + packetSendCallback.accept(new CPacketVoiceSignalConnectEAG()); + } + + public static void sendPacketDesc(EaglercraftUUID peerId, String desc) { + packetSendCallback.accept(new CPacketVoiceSignalDescEAG(peerId.msb, peerId.lsb, desc)); + } + + public static void sendPacketDisconnect() { + if (protocolVersion <= 3) { + packetSendCallback.accept(new CPacketVoiceSignalDisconnectV3EAG()); + } else { + packetSendCallback.accept(new CPacketVoiceSignalDisconnectV4EAG()); + } + } + + public static void sendPacketDisconnectPeer(EaglercraftUUID peerId) { + if (protocolVersion <= 3) { + packetSendCallback.accept(new CPacketVoiceSignalDisconnectV3EAG(true, peerId.msb, peerId.lsb)); + } else { + packetSendCallback.accept(new CPacketVoiceSignalDisconnectPeerV4EAG(peerId.msb, peerId.lsb)); + } + } + + public static void sendPacketICE(EaglercraftUUID peerId, String candidate) { + packetSendCallback.accept(new CPacketVoiceSignalICEEAG(peerId.msb, peerId.lsb, candidate)); + } + + public static void sendPacketRequest(EaglercraftUUID peerId) { + packetSendCallback.accept(new CPacketVoiceSignalRequestEAG(peerId.msb, peerId.lsb)); + } + + private static void sendPacketRequestIfNeeded(EaglercraftUUID uuid) { + if (getVoiceStatus() == EnumVoiceChannelStatus.DISCONNECTED + || getVoiceStatus() == EnumVoiceChannelStatus.UNAVAILABLE) + return; + if (uuid.equals(EaglerProfile.getPlayerUUID())) + return; + if (!getVoiceListening().contains(uuid)) + sendPacketRequest(uuid); } public static void setVoiceChannel(EnumVoiceChannelType channel) { - if (voiceChannel == channel) return; - if (channel != EnumVoiceChannelType.NONE) PlatformVoiceClient.initializeDevices(); + if (voiceChannel == channel) + return; + if (channel != EnumVoiceChannelType.NONE) + PlatformVoiceClient.initializeDevices(); PlatformVoiceClient.resetPeerStates(); if (channel == EnumVoiceChannelType.NONE) { for (EaglercraftUUID uuid : nearbyPlayers) { @@ -235,7 +334,7 @@ public class VoiceClientController { nearbyPlayers.clear(); recentlyNearbyPlayers.clear(); sendPacketDisconnect(); - } else if(voiceChannel == EnumVoiceChannelType.GLOBAL) { + } else if (voiceChannel == EnumVoiceChannelType.GLOBAL) { Set antiConcurrentModificationUUIDs = new HashSet<>(listeningSet); antiConcurrentModificationUUIDs.removeAll(nearbyPlayers); antiConcurrentModificationUUIDs.removeAll(recentlyNearbyPlayers); @@ -250,82 +349,11 @@ public class VoiceClientController { } } - public static void sendInitialVoice() { - sendPacketConnect(); - for (EaglercraftUUID uuid : nearbyPlayers) { - sendPacketRequest(uuid); - } - } - - public static EnumVoiceChannelType getVoiceChannel() { - return voiceChannel; - } - - private static boolean voicePeerErrored() { - return PlatformVoiceClient.getPeerState() == EnumVoiceChannelPeerState.FAILED || PlatformVoiceClient.getPeerStateConnect() == EnumVoiceChannelPeerState.FAILED || PlatformVoiceClient.getPeerStateInitial() == EnumVoiceChannelPeerState.FAILED || PlatformVoiceClient.getPeerStateDesc() == EnumVoiceChannelPeerState.FAILED || PlatformVoiceClient.getPeerStateIce() == EnumVoiceChannelPeerState.FAILED; - } - public static EnumVoiceChannelStatus getVoiceStatus() { - return (!isClientSupported() || !isServerSupported()) ? EnumVoiceChannelStatus.UNAVAILABLE : - (PlatformVoiceClient.getReadyState() != EnumVoiceChannelReadyState.DEVICE_INITIALIZED ? - EnumVoiceChannelStatus.CONNECTING : (voicePeerErrored() ? EnumVoiceChannelStatus.UNAVAILABLE : EnumVoiceChannelStatus.CONNECTED)); - } - - private static boolean talkStatus = false; - - public static void activateVoice(boolean talk) { - if (talkStatus != talk) { - PlatformVoiceClient.activateVoice(talk); - talkStatus = talk; - } - } - - private static int proximity = 16; - - public static void setVoiceProximity(int prox) { - PlatformVoiceClient.setVoiceProximity(prox); - proximity = prox; - } - - public static int getVoiceProximity() { - return proximity; - } - - private static float volumeListen = 0.5f; - public static void setVoiceListenVolume(float f) { PlatformVoiceClient.setVoiceListenVolume(f); volumeListen = f; } - public static float getVoiceListenVolume() { - return volumeListen; - } - - private static float volumeSpeak = 0.5f; - - public static void setVoiceSpeakVolume(float f) { - if (volumeSpeak != f) { - PlatformVoiceClient.setMicVolume(f); - } - volumeSpeak = f; - } - - public static float getVoiceSpeakVolume() { - return volumeSpeak; - } - - private static final Set listeningSet = new HashSet<>(); - private static final Set speakingSet = new HashSet<>(); - private static final Set mutedSet = new HashSet<>(); - - public static Set getVoiceListening() { - return listeningSet; - } - - public static Set getVoiceSpeaking() { - return speakingSet; - } - public static void setVoiceMuted(EaglercraftUUID uuid, boolean mute) { PlatformVoiceClient.mutePeer(uuid, mute); if (mute) { @@ -335,57 +363,65 @@ public class VoiceClientController { } } - public static Set getVoiceMuted() { - return mutedSet; + public static void setVoiceProximity(int prox) { + PlatformVoiceClient.setVoiceProximity(prox); + proximity = prox; } - public static List getVoiceRecent() { - return new ArrayList<>(listeningSet); - } - - public static String getVoiceUsername(EaglercraftUUID uuid) { - if(uuid == null) { - return "null"; + public static void setVoiceSpeakVolume(float f) { + if (volumeSpeak != f) { + PlatformVoiceClient.setMicVolume(f); } - String ret = uuidToNameLookup.get(uuid); - return ret == null ? uuid.toString() : ret; + volumeSpeak = f; } - public static void sendPacketICE(EaglercraftUUID peerId, String candidate) { - packetSendCallback.accept(new CPacketVoiceSignalICEEAG(peerId.msb, peerId.lsb, candidate)); - } + public static void tickVoiceClient(Minecraft mc) { + if (!isClientSupported()) + return; + recentlyNearbyPlayers.checkForExpirations(); + speakingSet.clear(); + PlatformVoiceClient.tickVoiceClient(); - public static void sendPacketDesc(EaglercraftUUID peerId, String desc) { - packetSendCallback.accept(new CPacketVoiceSignalDescEAG(peerId.msb, peerId.lsb, desc)); - } + if (getVoiceChannel() != EnumVoiceChannelType.NONE && (getVoiceStatus() == EnumVoiceChannelStatus.CONNECTING + || getVoiceStatus() == EnumVoiceChannelStatus.CONNECTED)) { + activateVoice((mc.currentScreen == null || !mc.currentScreen.blockPTTKey()) + && Keyboard.isKeyDown(mc.gameSettings.voicePTTKey)); - public static void sendPacketDisconnect() { - if(protocolVersion <= 3) { - packetSendCallback.accept(new CPacketVoiceSignalDisconnectV3EAG()); - }else { - packetSendCallback.accept(new CPacketVoiceSignalDisconnectV4EAG()); + if (mc.theWorld != null && mc.thePlayer != null) { + HashSet seenPlayers = new HashSet<>(); + for (EntityPlayer player : mc.theWorld.playerEntities) { + if (player == mc.thePlayer) + continue; + if (getVoiceChannel() == EnumVoiceChannelType.PROXIMITY) + updateVoicePosition(player.getUniqueID(), player.posX, player.posY + player.getEyeHeight(), + player.posZ); + int prox = 22; + // cube + if (Math.abs(mc.thePlayer.posX - player.posX) <= prox + && Math.abs(mc.thePlayer.posY - player.posY) <= prox + && Math.abs(mc.thePlayer.posZ - player.posZ) <= prox) { + if (!uuidToNameLookup.containsKey(player.getUniqueID())) { + uuidToNameLookup.put(player.getUniqueID(), player.getName()); + } + if (addNearbyPlayer(player.getUniqueID())) { + seenPlayers.add(player.getUniqueID()); + } + } + } + cleanupNearbyPlayers(seenPlayers); + } } } - public static void sendPacketDisconnectPeer(EaglercraftUUID peerId) { - if(protocolVersion <= 3) { - packetSendCallback.accept(new CPacketVoiceSignalDisconnectV3EAG(true, peerId.msb, peerId.lsb)); - }else { - packetSendCallback.accept(new CPacketVoiceSignalDisconnectPeerV4EAG(peerId.msb, peerId.lsb)); - } + public static final void updateVoicePosition(EaglercraftUUID uuid, double x, double y, double z) { + PlatformVoiceClient.updateVoicePosition(uuid, x, y, z); } - public static void sendPacketConnect() { - packetSendCallback.accept(new CPacketVoiceSignalConnectEAG()); - } - - public static void sendPacketRequest(EaglercraftUUID peerId) { - packetSendCallback.accept(new CPacketVoiceSignalRequestEAG(peerId.msb, peerId.lsb)); - } - - private static void sendPacketRequestIfNeeded(EaglercraftUUID uuid) { - if (getVoiceStatus() == EnumVoiceChannelStatus.DISCONNECTED || getVoiceStatus() == EnumVoiceChannelStatus.UNAVAILABLE) return; - if(uuid.equals(EaglerProfile.getPlayerUUID())) return; - if (!getVoiceListening().contains(uuid)) sendPacketRequest(uuid); + private static boolean voicePeerErrored() { + return PlatformVoiceClient.getPeerState() == EnumVoiceChannelPeerState.FAILED + || PlatformVoiceClient.getPeerStateConnect() == EnumVoiceChannelPeerState.FAILED + || PlatformVoiceClient.getPeerStateInitial() == EnumVoiceChannelPeerState.FAILED + || PlatformVoiceClient.getPeerStateDesc() == EnumVoiceChannelPeerState.FAILED + || PlatformVoiceClient.getPeerStateIce() == EnumVoiceChannelPeerState.FAILED; } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceTagRenderer.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceTagRenderer.java index b04bf214..6dc807b5 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceTagRenderer.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/voice/VoiceTagRenderer.java @@ -1,6 +1,6 @@ package net.lax1dude.eaglercraft.v1_8.voice; -import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.*; +import static net.lax1dude.eaglercraft.v1_8.opengl.RealOpenGLEnums.GL_GREATER; import java.util.HashSet; import java.util.Set; @@ -17,14 +17,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,10 +36,14 @@ public class VoiceTagRenderer { private static final Set voiceTagsDrawnThisFrame = new HashSet<>(); + public static void clearTagsDrawnSet() { + voiceTagsDrawnThisFrame.clear(); + } + public static void renderVoiceNameTag(Minecraft mc, EntityOtherPlayerMP player, int offset) { EaglercraftUUID uuid = player.getUniqueID(); boolean mute = VoiceClientController.getVoiceMuted().contains(uuid); - if((mute || VoiceClientController.getVoiceSpeaking().contains(uuid)) && voiceTagsDrawnThisFrame.add(uuid)) { + if ((mute || VoiceClientController.getVoiceSpeaking().contains(uuid)) && voiceTagsDrawnThisFrame.add(uuid)) { GlStateManager.disableLighting(); GlStateManager.disableTexture2D(); GlStateManager.enableAlpha(); @@ -73,34 +78,44 @@ public class VoiceTagRenderer { float var7 = 0.00390625F; float var8 = 0.00390625F; - if(mute) { + if (mute) { GlStateManager.color(0.9F, 0.3F, 0.3F, 0.125F); - }else { + } else { GlStateManager.color(1.0F, 1.0F, 1.0F, 0.125F); } worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(0, 1.0, 0).tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)).endVertex(); - worldrenderer.pos(1.0, 1.0, 0).tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)).endVertex(); - worldrenderer.pos(1.0, 0, 0).tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)).endVertex(); - worldrenderer.pos(0, 0, 0).tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)).endVertex(); + worldrenderer.pos(0, 1.0, 0) + .tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)).endVertex(); + worldrenderer.pos(1.0, 1.0, 0) + .tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)) + .endVertex(); + worldrenderer.pos(1.0, 0, 0) + .tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)).endVertex(); + worldrenderer.pos(0, 0, 0).tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)) + .endVertex(); tessellator.draw(); GlStateManager.alphaFunc(GL_GREATER, 0.1f); GlStateManager.enableDepth(); GlStateManager.depthMask(true); - if(mute) { + if (mute) { GlStateManager.color(0.9F, 0.3F, 0.3F, 1.0F); - }else { + } else { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); } worldrenderer.begin(7, DefaultVertexFormats.POSITION_TEX); - worldrenderer.pos(0, 1.0, 0).tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)).endVertex(); - worldrenderer.pos(1.0, 1.0, 0).tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)).endVertex(); - worldrenderer.pos(1.0, 0, 0).tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)).endVertex(); - worldrenderer.pos(0, 0, 0).tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)).endVertex(); + worldrenderer.pos(0, 1.0, 0) + .tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)).endVertex(); + worldrenderer.pos(1.0, 1.0, 0) + .tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 32 - 0.2f) * var8)) + .endVertex(); + worldrenderer.pos(1.0, 0, 0) + .tex((double) ((float) (u + 32 - 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)).endVertex(); + worldrenderer.pos(0, 0, 0).tex((double) ((float) (u + 0.2f) * var7), (double) ((float) (v + 0.2f) * var8)) + .endVertex(); tessellator.draw(); GlStateManager.enableLighting(); @@ -111,8 +126,4 @@ public class VoiceTagRenderer { } } - public static void clearTagsDrawnSet() { - voiceTagsDrawnThisFrame.clear(); - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenPhishingWaring.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenPhishingWaring.java index e96895fa..629371a6 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenPhishingWaring.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenPhishingWaring.java @@ -11,14 +11,15 @@ import net.minecraft.util.ResourceLocation; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,52 +38,9 @@ public class GuiScreenPhishingWaring extends GuiScreen { this.cont = cont; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 134, I18n.format("webviewPhishingWaring.continue"))); - } - - public void drawScreen(int mx, int my, float pt) { - this.drawDefaultBackground(); - this.drawCenteredString(fontRendererObj, EnumChatFormatting.BOLD + I18n.format("webviewPhishingWaring.title"), this.width / 2, 70, 0xFF4444); - this.drawCenteredString(fontRendererObj, I18n.format("webviewPhishingWaring.text0"), this.width / 2, 90, 16777215); - this.drawCenteredString(fontRendererObj, I18n.format("webviewPhishingWaring.text1"), this.width / 2, 102, 16777215); - this.drawCenteredString(fontRendererObj, I18n.format("webviewPhishingWaring.text2"), this.width / 2, 114, 16777215); - - String dontShowAgain = I18n.format("webviewPhishingWaring.dontShowAgain"); - int w = fontRendererObj.getStringWidth(dontShowAgain) + 20; - int ww = (this.width - w) / 2; - this.drawString(fontRendererObj, dontShowAgain, ww + 20, 137, 0xCCCCCC); - - mouseOverCheck = ww < mx && ww + 17 > mx && 133 < my && 150 > my; - - if(mouseOverCheck) { - GlStateManager.color(0.7f, 0.7f, 1.0f, 1.0f); - }else { - GlStateManager.color(0.6f, 0.6f, 0.6f, 1.0f); - } - - mc.getTextureManager().bindTexture(beaconGuiTexture); - - GlStateManager.pushMatrix(); - GlStateManager.scale(0.75f, 0.75f, 0.75f); - drawTexturedModalRect(ww * 4 / 3, 133 * 4 / 3, 22, 219, 22, 22); - GlStateManager.popMatrix(); - - if(hasCheckedBox) { - GlStateManager.pushMatrix(); - GlStateManager.color(1.1f, 1.1f, 1.1f, 1.0f); - GlStateManager.translate(0.5f, 0.5f, 0.0f); - drawTexturedModalRect(ww, 133, 90, 222, 16, 16); - GlStateManager.popMatrix(); - } - - super.drawScreen(mx, my, pt); - } - protected void actionPerformed(GuiButton par1GuiButton) { - if(par1GuiButton.id == 0) { - if(hasCheckedBox && !mc.gameSettings.hasHiddenPhishWarning) { + if (par1GuiButton.id == 0) { + if (hasCheckedBox && !mc.gameSettings.hasHiddenPhishWarning) { mc.gameSettings.hasHiddenPhishWarning = true; mc.gameSettings.saveOptions(); } @@ -91,11 +49,60 @@ public class GuiScreenPhishingWaring extends GuiScreen { } } + public void drawScreen(int mx, int my, float pt) { + this.drawDefaultBackground(); + this.drawCenteredString(fontRendererObj, EnumChatFormatting.BOLD + I18n.format("webviewPhishingWaring.title"), + this.width / 2, 70, 0xFF4444); + this.drawCenteredString(fontRendererObj, I18n.format("webviewPhishingWaring.text0"), this.width / 2, 90, + 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("webviewPhishingWaring.text1"), this.width / 2, 102, + 16777215); + this.drawCenteredString(fontRendererObj, I18n.format("webviewPhishingWaring.text2"), this.width / 2, 114, + 16777215); + + String dontShowAgain = I18n.format("webviewPhishingWaring.dontShowAgain"); + int w = fontRendererObj.getStringWidth(dontShowAgain) + 20; + int ww = (this.width - w) / 2; + this.drawString(fontRendererObj, dontShowAgain, ww + 20, 137, 0xCCCCCC); + + mouseOverCheck = ww < mx && ww + 17 > mx && 133 < my && 150 > my; + + if (mouseOverCheck) { + GlStateManager.color(0.7f, 0.7f, 1.0f, 1.0f); + } else { + GlStateManager.color(0.6f, 0.6f, 0.6f, 1.0f); + } + + mc.getTextureManager().bindTexture(beaconGuiTexture); + + GlStateManager.pushMatrix(); + GlStateManager.scale(0.75f, 0.75f, 0.75f); + drawTexturedModalRect(ww * 4 / 3, 133 * 4 / 3, 22, 219, 22, 22); + GlStateManager.popMatrix(); + + if (hasCheckedBox) { + GlStateManager.pushMatrix(); + GlStateManager.color(1.1f, 1.1f, 1.1f, 1.0f); + GlStateManager.translate(0.5f, 0.5f, 0.0f); + drawTexturedModalRect(ww, 133, 90, 222, 16, 16); + GlStateManager.popMatrix(); + } + + super.drawScreen(mx, my, pt); + } + + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 134, + I18n.format("webviewPhishingWaring.continue"))); + } + @Override protected void mouseClicked(int mx, int my, int btn) { - if(btn == 0 && mouseOverCheck) { + if (btn == 0 && mouseOverCheck) { hasCheckedBox = !hasCheckedBox; - mc.getSoundHandler().playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); + mc.getSoundHandler() + .playSound(PositionedSoundRecord.create(new ResourceLocation("gui.button.press"), 1.0F)); return; } super.mouseClicked(mx, my, btn); diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenRecieveServerInfo.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenRecieveServerInfo.java index 995a35c0..d4897125 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenRecieveServerInfo.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenRecieveServerInfo.java @@ -25,14 +25,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,20 +53,23 @@ public class GuiScreenRecieveServerInfo extends GuiScreen { this.expectHash = expectHash; } - public void initGui() { - this.buttonList.clear(); - this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 106, I18n.format("gui.cancel"))); + public void actionPerformed(GuiButton button) { + if (button.id == 0) { + mc.displayGuiScreen(parent); + } } public void drawScreen(int par1, int par2, float par3) { this.drawDefaultBackground(); this.drawCenteredString(fontRendererObj, I18n.format("recieveServerInfo.title"), this.width / 2, 70, 11184810); this.drawCenteredString(fontRendererObj, I18n.format(statusString), this.width / 2, 90, 16777215); - if(Arrays.equals(ServerInfoCache.chunkRecieveHash, expectHash) && ServerInfoCache.chunkFinalSize > 0) { + if (Arrays.equals(ServerInfoCache.chunkRecieveHash, expectHash) && ServerInfoCache.chunkFinalSize > 0) { int progress = ServerInfoCache.chunkCurrentSize * 100 / ServerInfoCache.chunkFinalSize; - if(progress < 0) progress = 0; - if(progress > 100) progress = 100; - if(ServerInfoCache.hasLastChunk) { + if (progress < 0) + progress = 0; + if (progress > 100) + progress = 100; + if (ServerInfoCache.hasLastChunk) { progress = 100; } Tessellator tessellator = Tessellator.getInstance(); @@ -78,50 +82,54 @@ public class GuiScreenRecieveServerInfo extends GuiScreen { worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR); worldrenderer.pos((double) i1, (double) j1, 0.0D).color(128, 128, 128, 255).endVertex(); worldrenderer.pos((double) i1, (double) (j1 + b1), 0.0D).color(128, 128, 128, 255).endVertex(); - worldrenderer.pos((double) (i1 + b0), (double) (j1 + b1), 0.0D).color(128, 128, 128, 255) - .endVertex(); + worldrenderer.pos((double) (i1 + b0), (double) (j1 + b1), 0.0D).color(128, 128, 128, 255).endVertex(); worldrenderer.pos((double) (i1 + b0), (double) j1, 0.0D).color(128, 128, 128, 255).endVertex(); worldrenderer.pos((double) i1, (double) j1, 0.0D).color(128, 255, 128, 255).endVertex(); worldrenderer.pos((double) i1, (double) (j1 + b1), 0.0D).color(128, 255, 128, 255).endVertex(); - worldrenderer.pos((double) (i1 + progress), (double) (j1 + b1), 0.0D).color(128, 255, 128, 255) - .endVertex(); - worldrenderer.pos((double) (i1 + progress), (double) j1, 0.0D).color(128, 255, 128, 255) - .endVertex(); + worldrenderer.pos((double) (i1 + progress), (double) (j1 + b1), 0.0D).color(128, 255, 128, 255).endVertex(); + worldrenderer.pos((double) (i1 + progress), (double) j1, 0.0D).color(128, 255, 128, 255).endVertex(); tessellator.draw(); GlStateManager.enableTexture2D(); } super.drawScreen(par1, par2, par3); } - public void actionPerformed(GuiButton button) { - if(button.id == 0) { - mc.displayGuiScreen(parent); - } + public void initGui() { + this.buttonList.clear(); + this.buttonList.add(new GuiButton(0, this.width / 2 - 100, this.height / 6 + 106, I18n.format("gui.cancel"))); + } + + protected boolean isPartOfPauseMenu() { + return true; } public void updateScreen() { - if(mc.thePlayer == null) { + if (mc.thePlayer == null) { mc.displayGuiScreen(parent); return; } ++timer; - if(timer == 1) { + if (timer == 1) { byte[] data = ServerInfoCache.loadFromCache(expectHash); - if(data != null) { - mc.displayGuiScreen(GuiScreenServerInfo.createForCurrentState(parent, data, WebViewOptions.getEmbedOriginUUID(expectHash))); - }else { + if (data != null) { + mc.displayGuiScreen(GuiScreenServerInfo.createForCurrentState(parent, data, + WebViewOptions.getEmbedOriginUUID(expectHash))); + } else { byte[] b = mc.thePlayer.sendQueue.cachedServerInfoData; - if(b != null) { - if(b.length == 0) { - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", "serverInfoFailure.desc", parent)); - }else { + if (b != null) { + if (b.length == 0) { + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", + "serverInfoFailure.desc", parent)); + } else { ServerInfoCache.storeInCache(expectHash, b); - mc.displayGuiScreen(GuiScreenServerInfo.createForCurrentState(parent, b, WebViewOptions.getEmbedOriginUUID(expectHash))); + mc.displayGuiScreen(GuiScreenServerInfo.createForCurrentState(parent, b, + WebViewOptions.getEmbedOriginUUID(expectHash))); } - }else { + } else { statusString = "recieveServerInfo.contactingServer"; - if(!mc.thePlayer.sendQueue.hasRequestedServerInfo) { - if(!ServerInfoCache.hasLastChunk || !Arrays.equals(ServerInfoCache.chunkRecieveHash, expectHash)) { + if (!mc.thePlayer.sendQueue.hasRequestedServerInfo) { + if (!ServerInfoCache.hasLastChunk + || !Arrays.equals(ServerInfoCache.chunkRecieveHash, expectHash)) { ServerInfoCache.clearDownload(); mc.thePlayer.sendQueue.sendEaglerMessage(new CPacketRequestServerInfoV4EAG(expectHash)); mc.thePlayer.sendQueue.hasRequestedServerInfo = true; @@ -129,75 +137,80 @@ public class GuiScreenRecieveServerInfo extends GuiScreen { } } } - }else if(timer > 1) { - if(Arrays.equals(ServerInfoCache.chunkRecieveHash, expectHash)) { - if(ServerInfoCache.hasLastChunk) { + } else if (timer > 1) { + if (Arrays.equals(ServerInfoCache.chunkRecieveHash, expectHash)) { + if (ServerInfoCache.hasLastChunk) { statusString = "recieveServerInfo.decompressing"; ++timer2; - if(timer2 == 2) { + if (timer2 == 2) { byte[] finalData = new byte[ServerInfoCache.chunkCurrentSize]; int i = 0; - for(byte[] b : ServerInfoCache.chunkRecieveBuffer) { + for (byte[] b : ServerInfoCache.chunkRecieveBuffer) { System.arraycopy(b, 0, finalData, i, b.length); i += b.length; } - if(i != ServerInfoCache.chunkCurrentSize) { + if (i != ServerInfoCache.chunkCurrentSize) { logger.error("An unknown error occured!"); mc.thePlayer.sendQueue.cachedServerInfoData = new byte[0]; - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", "serverInfoFailure.desc", parent)); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", + "serverInfoFailure.desc", parent)); return; } ServerInfoCache.clearDownload(); try { EaglerInputStream bis = new EaglerInputStream(finalData); int finalSize = (new DataInputStream(bis)).readInt(); - if(finalSize < 0) { + if (finalSize < 0) { logger.error("The response data was corrupt, decompressed size is negative!"); mc.thePlayer.sendQueue.cachedServerInfoData = new byte[0]; - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", "serverInfoFailure.desc", parent)); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", + "serverInfoFailure.desc", parent)); return; } - if(finalSize > ServerInfoCache.CACHE_MAX_SIZE * 2) { - logger.error("Failed to decompress/verify server info response! Size is massive, {} " + finalSize + " bytes reported!"); + if (finalSize > ServerInfoCache.CACHE_MAX_SIZE * 2) { + logger.error("Failed to decompress/verify server info response! Size is massive, {} " + + finalSize + " bytes reported!"); logger.error("Aborting decompression. Rejoin the server to try again."); mc.thePlayer.sendQueue.cachedServerInfoData = new byte[0]; - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", "serverInfoFailure.desc", parent)); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", + "serverInfoFailure.desc", parent)); return; } byte[] decompressed = new byte[finalSize]; - try(InputStream is = EaglerZLIB.newGZIPInputStream(bis)) { + try (InputStream is = EaglerZLIB.newGZIPInputStream(bis)) { IOUtils.readFully(is, decompressed); } SHA1Digest digest = new SHA1Digest(); digest.update(decompressed, 0, decompressed.length); byte[] csum = new byte[20]; digest.doFinal(csum, 0); - if(Arrays.equals(csum, expectHash)) { + if (Arrays.equals(csum, expectHash)) { ServerInfoCache.storeInCache(csum, decompressed); mc.thePlayer.sendQueue.cachedServerInfoData = decompressed; - mc.displayGuiScreen(GuiScreenServerInfo.createForCurrentState(parent, decompressed, WebViewOptions.getEmbedOriginUUID(expectHash))); - }else { - logger.error("The data recieved from the server did not have the correct SHA1 checksum! Rejoin the server to try again."); + mc.displayGuiScreen(GuiScreenServerInfo.createForCurrentState(parent, decompressed, + WebViewOptions.getEmbedOriginUUID(expectHash))); + } else { + logger.error( + "The data recieved from the server did not have the correct SHA1 checksum! Rejoin the server to try again."); mc.thePlayer.sendQueue.cachedServerInfoData = new byte[0]; - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", "serverInfoFailure.desc", parent)); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", + "serverInfoFailure.desc", parent)); } - }catch(IOException ex) { - logger.error("Failed to decompress/verify server info response! Rejoin the server to try again."); + } catch (IOException ex) { + logger.error( + "Failed to decompress/verify server info response! Rejoin the server to try again."); logger.error(ex); mc.thePlayer.sendQueue.cachedServerInfoData = new byte[0]; - mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", "serverInfoFailure.desc", parent)); + mc.displayGuiScreen(new GuiScreenGenericErrorMessage("serverInfoFailure.title", + "serverInfoFailure.desc", parent)); } } - }else { + } else { statusString = "recieveServerInfo.recievingData"; } - }else { + } else { statusString = "recieveServerInfo.contactingServer"; } } } - - protected boolean isPartOfPauseMenu() { - return true; - } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfo.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfo.java index b2a3e6bb..b3501100 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfo.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfo.java @@ -18,14 +18,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,45 +35,11 @@ public class GuiScreenServerInfo extends GuiScreen { private static final Logger logger = LogManager.getLogger("GuiScreenServerInfo"); - private final GuiScreen parent; - private final WebViewOptions opts; - private boolean isShowing = false; - - public GuiScreenServerInfo(GuiScreen parent, WebViewOptions opts) { - this.parent = parent; - this.opts = opts; - } - - public static GuiScreen createForCurrentState(GuiScreen parent, String url) { - URI urlObj; - try { - urlObj = new URI(url); - }catch(URISyntaxException ex) { - logger.error("Refusing to iframe an invalid URL: {}", url); - logger.error(ex); - return new GuiScreenGenericErrorMessage("webviewInvalidURL.title", "webviewInvalidURL.desc", parent); - } - return createForCurrentState(parent, urlObj); - } - - public static GuiScreen createForCurrentState(GuiScreen parent, URI url) { + public static GuiScreen createForCurrentState(GuiScreen parent, byte[] blob, + EaglercraftUUID permissionsOriginUUID) { boolean support = WebViewOverlayController.supported(); boolean fallbackSupport = WebViewOverlayController.fallbackSupported(); - if(!support && !fallbackSupport) { - return new GuiScreenGenericErrorMessage("webviewNotSupported.title", "webviewNotSupported.desc", parent); - } - WebViewOptions opts = new WebViewOptions(); - opts.contentMode = EnumWebViewContentMode.URL_BASED; - opts.url = url; - setupState(opts); - opts.permissionsOriginUUID = WebViewOptions.getURLOriginUUID(url); - return support ? new GuiScreenServerInfo(parent, opts) : new GuiScreenServerInfoDesktop(parent, opts); - } - - public static GuiScreen createForCurrentState(GuiScreen parent, byte[] blob, EaglercraftUUID permissionsOriginUUID) { - boolean support = WebViewOverlayController.supported(); - boolean fallbackSupport = WebViewOverlayController.fallbackSupported(); - if(!support && !fallbackSupport) { + if (!support && !fallbackSupport) { return new GuiScreenGenericErrorMessage("webviewNotSupported.title", "webviewNotSupported.desc", parent); } WebViewOptions opts = new WebViewOptions(); @@ -83,34 +50,55 @@ public class GuiScreenServerInfo extends GuiScreen { return support ? new GuiScreenServerInfo(parent, opts) : new GuiScreenServerInfoDesktop(parent, opts); } + public static GuiScreen createForCurrentState(GuiScreen parent, String url) { + URI urlObj; + try { + urlObj = new URI(url); + } catch (URISyntaxException ex) { + logger.error("Refusing to iframe an invalid URL: {}", url); + logger.error(ex); + return new GuiScreenGenericErrorMessage("webviewInvalidURL.title", "webviewInvalidURL.desc", parent); + } + return createForCurrentState(parent, urlObj); + } + + public static GuiScreen createForCurrentState(GuiScreen parent, URI url) { + boolean support = WebViewOverlayController.supported(); + boolean fallbackSupport = WebViewOverlayController.fallbackSupported(); + if (!support && !fallbackSupport) { + return new GuiScreenGenericErrorMessage("webviewNotSupported.title", "webviewNotSupported.desc", parent); + } + WebViewOptions opts = new WebViewOptions(); + opts.contentMode = EnumWebViewContentMode.URL_BASED; + opts.url = url; + setupState(opts); + opts.permissionsOriginUUID = WebViewOptions.getURLOriginUUID(url); + return support ? new GuiScreenServerInfo(parent, opts) : new GuiScreenServerInfoDesktop(parent, opts); + } + public static void setupState(WebViewOptions opts) { - opts.scriptEnabled = (PauseMenuCustomizeState.serverInfoEmbedPerms & PauseMenuCustomizeState.SERVER_INFO_EMBED_PERMS_JAVASCRIPT) != 0; - opts.strictCSPEnable = (PauseMenuCustomizeState.serverInfoEmbedPerms & PauseMenuCustomizeState.SERVER_INFO_EMBED_PERMS_STRICT_CSP) != 0; - opts.serverMessageAPIEnabled = (PauseMenuCustomizeState.serverInfoEmbedPerms & PauseMenuCustomizeState.SERVER_INFO_EMBED_PERMS_MESSAGE_API) != 0; + opts.scriptEnabled = (PauseMenuCustomizeState.serverInfoEmbedPerms + & PauseMenuCustomizeState.SERVER_INFO_EMBED_PERMS_JAVASCRIPT) != 0; + opts.strictCSPEnable = (PauseMenuCustomizeState.serverInfoEmbedPerms + & PauseMenuCustomizeState.SERVER_INFO_EMBED_PERMS_STRICT_CSP) != 0; + opts.serverMessageAPIEnabled = (PauseMenuCustomizeState.serverInfoEmbedPerms + & PauseMenuCustomizeState.SERVER_INFO_EMBED_PERMS_MESSAGE_API) != 0; opts.fallbackTitle = PauseMenuCustomizeState.serverInfoEmbedTitle; } - public void initGui() { - ScaledResolution res = mc.scaledResolution; - if(!isShowing) { - isShowing = true; - WebViewOverlayController.beginShowingSmart(opts, res, 30, 30, width - 60, height - 60); - }else { - WebViewOverlayController.resizeSmart(res, 30, 30, width - 60, height - 60); - } - buttonList.clear(); - buttonList.add(new GuiButton(0, (width - 200) / 2, height - 25, I18n.format("gui.done"))); - } + private final GuiScreen parent; - public void onGuiClosed() { - if(isShowing) { - isShowing = false; - WebViewOverlayController.endShowing(); - } + private final WebViewOptions opts; + + private boolean isShowing = false; + + public GuiScreenServerInfo(GuiScreen parent, WebViewOptions opts) { + this.parent = parent; + this.opts = opts; } public void actionPerformed(GuiButton btn) { - if(btn.id == 0) { + if (btn.id == 0) { mc.displayGuiScreen(parent); } } @@ -122,7 +110,26 @@ public class GuiScreenServerInfo extends GuiScreen { super.drawScreen(mx, my, pt); } + public void initGui() { + ScaledResolution res = mc.scaledResolution; + if (!isShowing) { + isShowing = true; + WebViewOverlayController.beginShowingSmart(opts, res, 30, 30, width - 60, height - 60); + } else { + WebViewOverlayController.resizeSmart(res, 30, 30, width - 60, height - 60); + } + buttonList.clear(); + buttonList.add(new GuiButton(0, (width - 200) / 2, height - 25, I18n.format("gui.done"))); + } + protected boolean isPartOfPauseMenu() { return true; } + + public void onGuiClosed() { + if (isShowing) { + isShowing = false; + WebViewOverlayController.endShowing(); + } + } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfoDesktop.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfoDesktop.java index 19f0b2d3..7f447b73 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfoDesktop.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/GuiScreenServerInfoDesktop.java @@ -10,14 +10,15 @@ import net.minecraft.client.resources.I18n; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,43 +38,17 @@ public class GuiScreenServerInfoDesktop extends GuiScreen { this.opts = opts; } - public void initGui() { - buttonList.clear(); - buttonList.add(btnOpen = new GuiButton(0, (width - 200) / 2, height / 6 + 110, I18n.format("fallbackWebViewScreen.openButton"))); - btnOpen.enabled = false; - buttonList.add(new GuiButton(1, (width - 200) / 2, height / 6 + 140, I18n.format("fallbackWebViewScreen.exitButton"))); - } - - public void updateScreen() { - ++timer; - if(timer == 2) { - WebViewOverlayController.endFallbackServer(); - WebViewOverlayController.launchFallback(opts); - }else if(timer > 2) { - if(WebViewOverlayController.fallbackRunning()) { - btnOpen.enabled = WebViewOverlayController.getFallbackURL() != null; - hasStarted = true; - }else { - btnOpen.enabled = false; - } - } - } - public void actionPerformed(GuiButton button) { - if(button.id == 0) { + if (button.id == 0) { String link = WebViewOverlayController.getFallbackURL(); - if(link != null) { + if (link != null) { EagRuntime.openLink(link); } - }else if(button.id == 1) { + } else if (button.id == 1) { mc.displayGuiScreen(parent); } } - public void onGuiClosed() { - WebViewOverlayController.endFallbackServer(); - } - public void drawScreen(int mx, int my, float pt) { drawDefaultBackground(); drawCenteredString(fontRendererObj, PauseMenuCustomizeState.serverInfoEmbedTitle, this.width / 2, 70, 16777215); @@ -85,8 +60,36 @@ public class GuiScreenServerInfoDesktop extends GuiScreen { super.drawScreen(mx, my, pt); } + public void initGui() { + buttonList.clear(); + buttonList.add(btnOpen = new GuiButton(0, (width - 200) / 2, height / 6 + 110, + I18n.format("fallbackWebViewScreen.openButton"))); + btnOpen.enabled = false; + buttonList.add( + new GuiButton(1, (width - 200) / 2, height / 6 + 140, I18n.format("fallbackWebViewScreen.exitButton"))); + } + protected boolean isPartOfPauseMenu() { return true; } + public void onGuiClosed() { + WebViewOverlayController.endFallbackServer(); + } + + public void updateScreen() { + ++timer; + if (timer == 2) { + WebViewOverlayController.endFallbackServer(); + WebViewOverlayController.launchFallback(opts); + } else if (timer > 2) { + if (WebViewOverlayController.fallbackRunning()) { + btnOpen.enabled = WebViewOverlayController.getFallbackURL() != null; + hasStarted = true; + } else { + btnOpen.enabled = false; + } + } + } + } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/PermissionsCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/PermissionsCache.java index bcd5e6ac..ba749c0c 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/PermissionsCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/PermissionsCache.java @@ -8,14 +8,15 @@ import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,15 +35,22 @@ public class PermissionsCache { } - private static final Map javaScriptAllowed = new HashMap<>(); + private static final Map javaScriptAllowed = new HashMap<>(); + + public static void clearJavaScriptAllowed(EaglercraftUUID uuid) { + synchronized (javaScriptAllowed) { + if (uuid != null) + javaScriptAllowed.remove(uuid); + } + } public static Permission getJavaScriptAllowed(EaglercraftUUID uuid, int flags) { - synchronized(javaScriptAllowed) { - if(uuid == null) { + synchronized (javaScriptAllowed) { + if (uuid == null) { return null; } Permission p = javaScriptAllowed.get(uuid); - if(p == null) { + if (p == null) { return null; } return (p.perm | flags) != p.perm ? null : p; @@ -50,14 +58,9 @@ public class PermissionsCache { } public static void setJavaScriptAllowed(EaglercraftUUID uuid, int flags, boolean allowed) { - synchronized(javaScriptAllowed) { - if(uuid != null) javaScriptAllowed.put(uuid, new Permission(flags, allowed)); - } - } - - public static void clearJavaScriptAllowed(EaglercraftUUID uuid) { - synchronized(javaScriptAllowed) { - if(uuid != null) javaScriptAllowed.remove(uuid); + synchronized (javaScriptAllowed) { + if (uuid != null) + javaScriptAllowed.put(uuid, new Permission(flags, allowed)); } } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/ServerInfoCache.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/ServerInfoCache.java index 2faa3562..c3f73f4e 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/ServerInfoCache.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/ServerInfoCache.java @@ -13,25 +13,21 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketServerInf /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class ServerInfoCache { - public static final int CACHE_MAX_SIZE = 0x200000; // 2 MB - - private static final Map cache = new HashMap<>(); - private static int cacheSize = 0; - private static class CacheEntry { private final byte[] data; @@ -46,14 +42,28 @@ public class ServerInfoCache { } + public static final int CACHE_MAX_SIZE = 0x200000; // 2 MB + private static final Map cache = new HashMap<>(); + + private static int cacheSize = 0; + protected static final List chunkRecieveBuffer = new LinkedList<>(); protected static byte[] chunkRecieveHash = null; protected static int chunkCurrentSize = 0; protected static int chunkFinalSize = 0; protected static boolean hasLastChunk = false; + public static void clearDownload() { + chunkRecieveBuffer.clear(); + hasLastChunk = false; + chunkRecieveHash = null; + chunkCurrentSize = 0; + chunkFinalSize = 0; + } + public static void handleChunk(SPacketServerInfoDataChunkV4EAG chunk) { - //System.out.println("p: " + chunk.seqId + " " + chunk.finalSize + " " + Base64.encodeBase64String(chunk.finalHash) + " " + chunk.lastChunk); + // System.out.println("p: " + chunk.seqId + " " + chunk.finalSize + " " + + // Base64.encodeBase64String(chunk.finalHash) + " " + chunk.lastChunk); if (chunkRecieveHash == null || hasLastChunk || !Arrays.equals(chunk.finalHash, chunkRecieveHash) || chunk.seqId != chunkRecieveBuffer.size()) { chunkRecieveBuffer.clear(); @@ -61,7 +71,7 @@ public class ServerInfoCache { chunkRecieveHash = null; chunkCurrentSize = 0; chunkFinalSize = 0; - if(chunk.seqId != 0) { + if (chunk.seqId != 0) { return; } chunkRecieveHash = chunk.finalHash; @@ -72,33 +82,46 @@ public class ServerInfoCache { hasLastChunk = chunk.lastChunk; } - public static void clearDownload() { - chunkRecieveBuffer.clear(); - hasLastChunk = false; - chunkRecieveHash = null; - chunkCurrentSize = 0; - chunkFinalSize = 0; - } - public static byte[] loadFromCache(byte[] hash) { - if(hash == null || hash.length != 20) { + if (hash == null || hash.length != 20) { return null; } CacheEntry etr = cache.get(new HashKey(hash)); - if(etr != null) { + if (etr != null) { etr.lastHit = EagRuntime.steadyTimeMillis(); return etr.data; - }else { + } else { return null; } } + private static void shrink(int toAdd) { + if (toAdd > CACHE_MAX_SIZE) { + cache.clear(); + cacheSize = 0; + return; + } + while (!cache.isEmpty() && cacheSize + toAdd > CACHE_MAX_SIZE) { + CacheEntry oldest = null; + for (CacheEntry e : cache.values()) { + if (oldest == null || e.lastHit < oldest.lastHit) { + oldest = e; + } + } + if (cache.remove(oldest.hash) != null) { + cacheSize -= oldest.data.length; + } else { + break; // wtf? + } + } + } + public static void storeInCache(byte[] hash, byte[] data) { - if(hash == null || hash.length != 20 || data == null) { + if (hash == null || hash.length != 20 || data == null) { return; } HashKey hashObj = new HashKey(hash); - if(cache.containsKey(hashObj)) { + if (cache.containsKey(hashObj)) { return; } shrink(data.length); @@ -106,25 +129,4 @@ public class ServerInfoCache { cacheSize += data.length; } - private static void shrink(int toAdd) { - if(toAdd > CACHE_MAX_SIZE) { - cache.clear(); - cacheSize = 0; - return; - } - while(!cache.isEmpty() && cacheSize + toAdd > CACHE_MAX_SIZE) { - CacheEntry oldest = null; - for(CacheEntry e : cache.values()) { - if(oldest == null || e.lastHit < oldest.lastHit) { - oldest = e; - } - } - if(cache.remove(oldest.hash) != null) { - cacheSize -= oldest.data.length; - }else { - break; //wtf? - } - } - } - } diff --git a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/WebViewOverlayController.java b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/WebViewOverlayController.java index 3c6e4d75..121a6c43 100644 --- a/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/WebViewOverlayController.java +++ b/src/main/java/net/lax1dude/eaglercraft/v1_8/webview/WebViewOverlayController.java @@ -9,84 +9,85 @@ import net.minecraft.client.gui.ScaledResolution; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class WebViewOverlayController { - public static boolean supported() { - return PlatformWebView.supported(); - } - - public static boolean isShowing() { - return PlatformWebView.isShowing(); + public static interface IPacketSendCallback { + boolean sendPacket(GameMessagePacket packet); } public static void beginShowing(WebViewOptions options, int x, int y, int w, int h) { PlatformWebView.beginShowing(options, x, y, w, h); } - public static void resize(int x, int y, int w, int h) { - PlatformWebView.resize(x, y, w, h); - } - public static void beginShowingSmart(WebViewOptions options, ScaledResolution res, int x, int y, int w, int h) { int fac = res.getScaleFactor(); PlatformWebView.beginShowing(options, x * fac, y * fac, w * fac, h * fac); } - public static void resizeSmart(ScaledResolution res, int x, int y, int w, int h) { - int fac = res.getScaleFactor(); - PlatformWebView.resize(x * fac, y * fac, w * fac, h * fac); + public static void endFallbackServer() { + PlatformWebView.endFallbackServer(); } public static void endShowing() { PlatformWebView.endShowing(); } - public static boolean fallbackSupported() { - return PlatformWebView.fallbackSupported(); - } - - public static void launchFallback(WebViewOptions options) { - PlatformWebView.launchFallback(options); - } - public static boolean fallbackRunning() { return PlatformWebView.fallbackRunning(); } + public static boolean fallbackSupported() { + return PlatformWebView.fallbackSupported(); + } + public static String getFallbackURL() { return PlatformWebView.getFallbackURL(); } - public static void endFallbackServer() { - PlatformWebView.endFallbackServer(); - } - public static void handleMessagePacket(SPacketWebViewMessageV4EAG packet) { PlatformWebView.handleMessageFromServer(packet); } - public static interface IPacketSendCallback { - boolean sendPacket(GameMessagePacket packet); + public static boolean isShowing() { + return PlatformWebView.isShowing(); } - public static void setPacketSendCallback(IPacketSendCallback callback) { - PlatformWebView.setPacketSendCallback(callback); + public static void launchFallback(WebViewOptions options) { + PlatformWebView.launchFallback(options); + } + + public static void resize(int x, int y, int w, int h) { + PlatformWebView.resize(x, y, w, h); + } + + public static void resizeSmart(ScaledResolution res, int x, int y, int w, int h) { + int fac = res.getScaleFactor(); + PlatformWebView.resize(x * fac, y * fac, w * fac, h * fac); } public static void runTick() { PlatformWebView.runTick(); } + public static void setPacketSendCallback(IPacketSendCallback callback) { + PlatformWebView.setPacketSendCallback(callback); + } + + public static boolean supported() { + return PlatformWebView.supported(); + } + } diff --git a/src/main/java/org/apache/commons/lang3/AnnotationUtils.java b/src/main/java/org/apache/commons/lang3/AnnotationUtils.java index 00dc093c..8243e192 100644 --- a/src/main/java/org/apache/commons/lang3/AnnotationUtils.java +++ b/src/main/java/org/apache/commons/lang3/AnnotationUtils.java @@ -74,14 +74,6 @@ public class AnnotationUtils { setArrayEnd("]"); } - /** - * {@inheritDoc} - */ - @Override - protected String getShortClassName(final Class cls) { - return cls.getSimpleName(); - } - /** * {@inheritDoc} */ @@ -93,20 +85,107 @@ public class AnnotationUtils { super.appendDetail(buffer, fieldName, value); } + /** + * {@inheritDoc} + */ + @Override + protected String getShortClassName(final Class cls) { + return cls.getSimpleName(); + } + }; /** - *

              - * {@code AnnotationUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used statically. - *

              + * Helper method for comparing two arrays of annotations. * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              + * @param a1 the first array + * @param a2 the second array + * @return a flag whether these arrays are equal */ - public AnnotationUtils() { + private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) { + if (a1.length != a2.length) { + return false; + } + for (int i = 0; i < a1.length; i++) { + if (!equals(a1[i], a2[i])) { + return false; + } + } + return true; + } + + /** + * Helper method for comparing two objects of an array type. + * + * @param componentType the component type of the array + * @param o1 the first object + * @param o2 the second object + * @return a flag whether these objects are equal + */ + private static boolean arrayMemberEquals(final Class componentType, final Object o1, final Object o2) { + if (componentType.isAnnotation()) { + return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2); + } + if (componentType.equals(Byte.TYPE)) { + return Arrays.equals((byte[]) o1, (byte[]) o2); + } + if (componentType.equals(Short.TYPE)) { + return Arrays.equals((short[]) o1, (short[]) o2); + } + if (componentType.equals(Integer.TYPE)) { + return Arrays.equals((int[]) o1, (int[]) o2); + } + if (componentType.equals(Character.TYPE)) { + return Arrays.equals((char[]) o1, (char[]) o2); + } + if (componentType.equals(Long.TYPE)) { + return Arrays.equals((long[]) o1, (long[]) o2); + } + if (componentType.equals(Float.TYPE)) { + return Arrays.equals((float[]) o1, (float[]) o2); + } + if (componentType.equals(Double.TYPE)) { + return Arrays.equals((double[]) o1, (double[]) o2); + } + if (componentType.equals(Boolean.TYPE)) { + return Arrays.equals((boolean[]) o1, (boolean[]) o2); + } + return Arrays.equals((Object[]) o1, (Object[]) o2); + } + + /** + * Helper method for generating a hash code for an array. + * + * @param componentType the component type of the array + * @param o the array + * @return a hash code for the specified array + */ + private static int arrayMemberHash(final Class componentType, final Object o) { + if (componentType.equals(Byte.TYPE)) { + return Arrays.hashCode((byte[]) o); + } + if (componentType.equals(Short.TYPE)) { + return Arrays.hashCode((short[]) o); + } + if (componentType.equals(Integer.TYPE)) { + return Arrays.hashCode((int[]) o); + } + if (componentType.equals(Character.TYPE)) { + return Arrays.hashCode((char[]) o); + } + if (componentType.equals(Long.TYPE)) { + return Arrays.hashCode((long[]) o); + } + if (componentType.equals(Float.TYPE)) { + return Arrays.hashCode((float[]) o); + } + if (componentType.equals(Double.TYPE)) { + return Arrays.hashCode((double[]) o); + } + if (componentType.equals(Boolean.TYPE)) { + return Arrays.hashCode((boolean[]) o); + } + return Arrays.hashCode((Object[]) o); } // ----------------------------------------------------------------------- @@ -186,30 +265,23 @@ public class AnnotationUtils { return result; } + // besides modularity, this has the advantage of autoboxing primitives: /** - *

              - * Generate a string representation of an Annotation, as suggested by - * {@link Annotation#toString()}. - *

              + * Helper method for generating a hash code for a member of an annotation. * - * @param a the annotation of which a string representation is desired - * @return the standard string representation of an annotation, not {@code null} + * @param name the name of the member + * @param value the value of the member + * @return a hash code for this member */ - public static String toString(final Annotation a) { - final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE); - for (final Method m : a.annotationType().getDeclaredMethods()) { - if (m.getParameterTypes().length > 0) { - continue; // wtf? - } - try { - builder.append(m.getName(), m.invoke(a)); - } catch (final RuntimeException ex) { - throw ex; - } catch (final Exception ex) { - throw new RuntimeException(ex); - } + private static int hashMember(final String name, final Object value) { + final int part1 = name.hashCode() * 127; + if (value.getClass().isArray()) { + return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value); } - return builder.build(); + if (value instanceof Annotation) { + return part1 ^ hashCode((Annotation) value); + } + return part1 ^ value.hashCode(); } /** @@ -238,25 +310,6 @@ public class AnnotationUtils { || Class.class.equals(type); } - // besides modularity, this has the advantage of autoboxing primitives: - /** - * Helper method for generating a hash code for a member of an annotation. - * - * @param name the name of the member - * @param value the value of the member - * @return a hash code for this member - */ - private static int hashMember(final String name, final Object value) { - final int part1 = name.hashCode() * 127; - if (value.getClass().isArray()) { - return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value); - } - if (value instanceof Annotation) { - return part1 ^ hashCode((Annotation) value); - } - return part1 ^ value.hashCode(); - } - /** * Helper method for checking whether two objects of the given type are equal. * This method is used to compare the parameters of two annotation instances. @@ -283,95 +336,42 @@ public class AnnotationUtils { } /** - * Helper method for comparing two objects of an array type. + *

              + * Generate a string representation of an Annotation, as suggested by + * {@link Annotation#toString()}. + *

              * - * @param componentType the component type of the array - * @param o1 the first object - * @param o2 the second object - * @return a flag whether these objects are equal + * @param a the annotation of which a string representation is desired + * @return the standard string representation of an annotation, not {@code null} */ - private static boolean arrayMemberEquals(final Class componentType, final Object o1, final Object o2) { - if (componentType.isAnnotation()) { - return annotationArrayMemberEquals((Annotation[]) o1, (Annotation[]) o2); - } - if (componentType.equals(Byte.TYPE)) { - return Arrays.equals((byte[]) o1, (byte[]) o2); - } - if (componentType.equals(Short.TYPE)) { - return Arrays.equals((short[]) o1, (short[]) o2); - } - if (componentType.equals(Integer.TYPE)) { - return Arrays.equals((int[]) o1, (int[]) o2); - } - if (componentType.equals(Character.TYPE)) { - return Arrays.equals((char[]) o1, (char[]) o2); - } - if (componentType.equals(Long.TYPE)) { - return Arrays.equals((long[]) o1, (long[]) o2); - } - if (componentType.equals(Float.TYPE)) { - return Arrays.equals((float[]) o1, (float[]) o2); - } - if (componentType.equals(Double.TYPE)) { - return Arrays.equals((double[]) o1, (double[]) o2); - } - if (componentType.equals(Boolean.TYPE)) { - return Arrays.equals((boolean[]) o1, (boolean[]) o2); - } - return Arrays.equals((Object[]) o1, (Object[]) o2); - } - - /** - * Helper method for comparing two arrays of annotations. - * - * @param a1 the first array - * @param a2 the second array - * @return a flag whether these arrays are equal - */ - private static boolean annotationArrayMemberEquals(final Annotation[] a1, final Annotation[] a2) { - if (a1.length != a2.length) { - return false; - } - for (int i = 0; i < a1.length; i++) { - if (!equals(a1[i], a2[i])) { - return false; + public static String toString(final Annotation a) { + final ToStringBuilder builder = new ToStringBuilder(a, TO_STRING_STYLE); + for (final Method m : a.annotationType().getDeclaredMethods()) { + if (m.getParameterTypes().length > 0) { + continue; // wtf? + } + try { + builder.append(m.getName(), m.invoke(a)); + } catch (final RuntimeException ex) { + throw ex; + } catch (final Exception ex) { + throw new RuntimeException(ex); } } - return true; + return builder.build(); } /** - * Helper method for generating a hash code for an array. + *

              + * {@code AnnotationUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used statically. + *

              * - * @param componentType the component type of the array - * @param o the array - * @return a hash code for the specified array + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              */ - private static int arrayMemberHash(final Class componentType, final Object o) { - if (componentType.equals(Byte.TYPE)) { - return Arrays.hashCode((byte[]) o); - } - if (componentType.equals(Short.TYPE)) { - return Arrays.hashCode((short[]) o); - } - if (componentType.equals(Integer.TYPE)) { - return Arrays.hashCode((int[]) o); - } - if (componentType.equals(Character.TYPE)) { - return Arrays.hashCode((char[]) o); - } - if (componentType.equals(Long.TYPE)) { - return Arrays.hashCode((long[]) o); - } - if (componentType.equals(Float.TYPE)) { - return Arrays.hashCode((float[]) o); - } - if (componentType.equals(Double.TYPE)) { - return Arrays.hashCode((double[]) o); - } - if (componentType.equals(Boolean.TYPE)) { - return Arrays.hashCode((boolean[]) o); - } - return Arrays.hashCode((Object[]) o); + public AnnotationUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/ArchUtils.java b/src/main/java/org/apache/commons/lang3/ArchUtils.java index 82c9b4f3..8caa0df7 100644 --- a/src/main/java/org/apache/commons/lang3/ArchUtils.java +++ b/src/main/java/org/apache/commons/lang3/ArchUtils.java @@ -41,45 +41,6 @@ public class ArchUtils { init(); } - private static void init() { - init_X86_32Bit(); - init_X86_64Bit(); - init_IA64_32Bit(); - init_IA64_64Bit(); - init_PPC_32Bit(); - init_PPC_64Bit(); - } - - private static void init_X86_32Bit() { - final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.X86); - addProcessors(processor, "x86", "i386", "i486", "i586", "i686", "pentium"); - } - - private static void init_X86_64Bit() { - final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.X86); - addProcessors(processor, "x86_64", "amd64", "em64t", "universal"); - } - - private static void init_IA64_32Bit() { - final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.IA_64); - addProcessors(processor, "ia64_32", "ia64n"); - } - - private static void init_IA64_64Bit() { - final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.IA_64); - addProcessors(processor, "ia64", "ia64w"); - } - - private static void init_PPC_32Bit() { - final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.PPC); - addProcessors(processor, "ppc", "power", "powerpc", "power_pc", "power_rs"); - } - - private static void init_PPC_64Bit() { - final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.PPC); - addProcessors(processor, "ppc64", "power64", "powerpc64", "power_pc64", "power_rs64"); - } - /** * Adds the given {@link Processor} with the given key {@link String} to the * map. @@ -132,4 +93,43 @@ public class ArchUtils { return ARCH_TO_PROCESSOR.get(value); } + private static void init() { + init_X86_32Bit(); + init_X86_64Bit(); + init_IA64_32Bit(); + init_IA64_64Bit(); + init_PPC_32Bit(); + init_PPC_64Bit(); + } + + private static void init_IA64_32Bit() { + final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.IA_64); + addProcessors(processor, "ia64_32", "ia64n"); + } + + private static void init_IA64_64Bit() { + final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.IA_64); + addProcessors(processor, "ia64", "ia64w"); + } + + private static void init_PPC_32Bit() { + final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.PPC); + addProcessors(processor, "ppc", "power", "powerpc", "power_pc", "power_rs"); + } + + private static void init_PPC_64Bit() { + final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.PPC); + addProcessors(processor, "ppc64", "power64", "powerpc64", "power_pc64", "power_rs64"); + } + + private static void init_X86_32Bit() { + final Processor processor = new Processor(Processor.Arch.BIT_32, Processor.Type.X86); + addProcessors(processor, "x86", "i386", "i486", "i586", "i686", "pentium"); + } + + private static void init_X86_64Bit() { + final Processor processor = new Processor(Processor.Arch.BIT_64, Processor.Type.X86); + addProcessors(processor, "x86_64", "amd64", "em64t", "universal"); + } + } diff --git a/src/main/java/org/apache/commons/lang3/BitField.java b/src/main/java/org/apache/commons/lang3/BitField.java index 12bd4cf2..188bacad 100644 --- a/src/main/java/org/apache/commons/lang3/BitField.java +++ b/src/main/java/org/apache/commons/lang3/BitField.java @@ -99,41 +99,42 @@ public class BitField { /** *

              - * Obtains the value for the specified BitField, appropriately shifted right. + * Clears the bits. *

              * - *

              - * Many users of a BitField will want to treat the specified bits as an int - * value, and will not want to be aware that the value is stored as a BitField - * (and so shifted left so many bits). - *

              - * - * @see #setValue(int,int) * @param holder the int data containing the bits we're interested in - * @return the selected bits, shifted right appropriately + * @return the value of holder with the specified bits cleared (set to + * {@code 0}) */ - public int getValue(final int holder) { - return getRawValue(holder) >> _shift_count; + public int clear(final int holder) { + return holder & ~_mask; } /** *

              - * Obtains the value for the specified BitField, appropriately shifted right, as - * a short. + * Clears the bits. *

              * - *

              - * Many users of a BitField will want to treat the specified bits as an int - * value, and will not want to be aware that the value is stored as a BitField - * (and so shifted left so many bits). - *

              + * @param holder the byte data containing the bits we're interested in * - * @see #setShortValue(short,short) - * @param holder the short data containing the bits we're interested in - * @return the selected bits, shifted right appropriately + * @return the value of holder with the specified bits cleared (set to + * {@code 0}) */ - public short getShortValue(final short holder) { - return (short) getValue(holder); + public byte clearByte(final byte holder) { + return (byte) clear(holder); + } + + /** + *

              + * Clears the bits. + *

              + * + * @param holder the short data containing the bits we're interested in + * @return the value of holder with the specified bits cleared (set to + * {@code 0}) + */ + public short clearShort(final short holder) { + return (short) clear(holder); } /** @@ -162,20 +163,41 @@ public class BitField { /** *

              - * Returns whether the field is set or not. + * Obtains the value for the specified BitField, appropriately shifted right, as + * a short. *

              * *

              - * This is most commonly used for a single-bit field, which is often used to - * represent a boolean value; the results of using it for a multi-bit field is - * to determine whether *any* of its bits are set. + * Many users of a BitField will want to treat the specified bits as an int + * value, and will not want to be aware that the value is stored as a BitField + * (and so shifted left so many bits). *

              * - * @param holder the int data containing the bits we're interested in - * @return {@code true} if any of the bits are set, else {@code false} + * @see #setShortValue(short,short) + * @param holder the short data containing the bits we're interested in + * @return the selected bits, shifted right appropriately */ - public boolean isSet(final int holder) { - return (holder & _mask) != 0; + public short getShortValue(final short holder) { + return (short) getValue(holder); + } + + /** + *

              + * Obtains the value for the specified BitField, appropriately shifted right. + *

              + * + *

              + * Many users of a BitField will want to treat the specified bits as an int + * value, and will not want to be aware that the value is stored as a BitField + * (and so shifted left so many bits). + *

              + * + * @see #setValue(int,int) + * @param holder the int data containing the bits we're interested in + * @return the selected bits, shifted right appropriately + */ + public int getValue(final int holder) { + return getRawValue(holder) >> _shift_count; } /** @@ -197,72 +219,20 @@ public class BitField { /** *

              - * Replaces the bits with new values. + * Returns whether the field is set or not. *

              * - * @see #getValue(int) - * @param holder the int data containing the bits we're interested in - * @param value the new value for the specified bits - * @return the value of holder with the bits from the value parameter replacing - * the old bits - */ - public int setValue(final int holder, final int value) { - return (holder & ~_mask) | ((value << _shift_count) & _mask); - } - - /** *

              - * Replaces the bits with new values. - *

              - * - * @see #getShortValue(short) - * @param holder the short data containing the bits we're interested in - * @param value the new value for the specified bits - * @return the value of holder with the bits from the value parameter replacing - * the old bits - */ - public short setShortValue(final short holder, final short value) { - return (short) setValue(holder, value); - } - - /** - *

              - * Clears the bits. + * This is most commonly used for a single-bit field, which is often used to + * represent a boolean value; the results of using it for a multi-bit field is + * to determine whether *any* of its bits are set. *

              * * @param holder the int data containing the bits we're interested in - * @return the value of holder with the specified bits cleared (set to - * {@code 0}) + * @return {@code true} if any of the bits are set, else {@code false} */ - public int clear(final int holder) { - return holder & ~_mask; - } - - /** - *

              - * Clears the bits. - *

              - * - * @param holder the short data containing the bits we're interested in - * @return the value of holder with the specified bits cleared (set to - * {@code 0}) - */ - public short clearShort(final short holder) { - return (short) clear(holder); - } - - /** - *

              - * Clears the bits. - *

              - * - * @param holder the byte data containing the bits we're interested in - * - * @return the value of holder with the specified bits cleared (set to - * {@code 0}) - */ - public byte clearByte(final byte holder) { - return (byte) clear(holder); + public boolean isSet(final int holder) { + return (holder & _mask) != 0; } /** @@ -279,14 +249,15 @@ public class BitField { /** *

              - * Sets the bits. + * Sets a boolean BitField. *

              * - * @param holder the short data containing the bits we're interested in - * @return the value of holder with the specified bits set to {@code 1} + * @param holder the int data containing the bits we're interested in + * @param flag indicating whether to set or clear the bits + * @return the value of holder with the specified bits set or cleared */ - public short setShort(final short holder) { - return (short) set(holder); + public int setBoolean(final int holder, final boolean flag) { + return flag ? set(holder) : clear(holder); } /** @@ -307,12 +278,24 @@ public class BitField { * Sets a boolean BitField. *

              * - * @param holder the int data containing the bits we're interested in + * @param holder the byte data containing the bits we're interested in * @param flag indicating whether to set or clear the bits * @return the value of holder with the specified bits set or cleared */ - public int setBoolean(final int holder, final boolean flag) { - return flag ? set(holder) : clear(holder); + public byte setByteBoolean(final byte holder, final boolean flag) { + return flag ? setByte(holder) : clearByte(holder); + } + + /** + *

              + * Sets the bits. + *

              + * + * @param holder the short data containing the bits we're interested in + * @return the value of holder with the specified bits set to {@code 1} + */ + public short setShort(final short holder) { + return (short) set(holder); } /** @@ -330,15 +313,32 @@ public class BitField { /** *

              - * Sets a boolean BitField. + * Replaces the bits with new values. *

              * - * @param holder the byte data containing the bits we're interested in - * @param flag indicating whether to set or clear the bits - * @return the value of holder with the specified bits set or cleared + * @see #getShortValue(short) + * @param holder the short data containing the bits we're interested in + * @param value the new value for the specified bits + * @return the value of holder with the bits from the value parameter replacing + * the old bits */ - public byte setByteBoolean(final byte holder, final boolean flag) { - return flag ? setByte(holder) : clearByte(holder); + public short setShortValue(final short holder, final short value) { + return (short) setValue(holder, value); + } + + /** + *

              + * Replaces the bits with new values. + *

              + * + * @see #getValue(int) + * @param holder the int data containing the bits we're interested in + * @param value the new value for the specified bits + * @return the value of holder with the bits from the value parameter replacing + * the old bits + */ + public int setValue(final int holder, final int value) { + return (holder & ~_mask) | ((value << _shift_count) & _mask); } } diff --git a/src/main/java/org/apache/commons/lang3/CharRange.java b/src/main/java/org/apache/commons/lang3/CharRange.java index 49cfc197..735c8996 100644 --- a/src/main/java/org/apache/commons/lang3/CharRange.java +++ b/src/main/java/org/apache/commons/lang3/CharRange.java @@ -39,26 +39,199 @@ import java.util.NoSuchElementException; // to depend on Range. final class CharRange implements Iterable, Serializable { + /** + * Character {@link Iterator}. + *

              + * #NotThreadSafe# + *

              + */ + private static class CharacterIterator implements Iterator { + /** The current character */ + private char current; + + private final CharRange range; + private boolean hasNext; + + /** + * Constructs a new iterator for the character range. + * + * @param r The character range + */ + private CharacterIterator(final CharRange r) { + range = r; + hasNext = true; + + if (range.negated) { + if (range.start == 0) { + if (range.end == Character.MAX_VALUE) { + // This range is an empty set + hasNext = false; + } else { + current = (char) (range.end + 1); + } + } else { + current = 0; + } + } else { + current = range.start; + } + } + + /** + * Has the iterator not reached the end character yet? + * + * @return {@code true} if the iterator has yet to reach the character date + */ + @Override + public boolean hasNext() { + return hasNext; + } + + /** + * Returns the next character in the iteration + * + * @return {@code Character} for the next character + */ + @Override + public Character next() { + if (!hasNext) { + throw new NoSuchElementException(); + } + final char cur = current; + prepareNext(); + return Character.valueOf(cur); + } + + /** + * Prepares the next character in the range. + */ + private void prepareNext() { + if (range.negated) { + if (current == Character.MAX_VALUE) { + hasNext = false; + } else if (current + 1 == range.start) { + if (range.end == Character.MAX_VALUE) { + hasNext = false; + } else { + current = (char) (range.end + 1); + } + } else { + current = (char) (current + 1); + } + } else if (current < range.end) { + current = (char) (current + 1); + } else { + hasNext = false; + } + } + + /** + * Always throws UnsupportedOperationException. + * + * @throws UnsupportedOperationException Always thrown. + * @see java.util.Iterator#remove() + */ + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } + /** * Required for serialization support. Lang version 2.0. * * @see java.io.Serializable */ private static final long serialVersionUID = 8270183163158333422L; + /** Empty array. */ + static final CharRange[] EMPTY_ARRAY = new CharRange[0]; + + /** + *

              + * Constructs a {@code CharRange} over a single character. + *

              + * + * @param ch only character in this range + * @return the new CharRange object + * @since 2.5 + */ + public static CharRange is(final char ch) { + return new CharRange(ch, ch, false); + } + + /** + *

              + * Constructs a {@code CharRange} over a set of characters. + *

              + * + *

              + * If start and end are in the wrong order, they are reversed. Thus {@code a-e} + * is the same as {@code e-a}. + *

              + * + * @param start first character, inclusive, in this range + * @param end last character, inclusive, in this range + * @return the new CharRange object + * @since 2.5 + */ + public static CharRange isIn(final char start, final char end) { + return new CharRange(start, end, false); + } + + /** + *

              + * Constructs a negated {@code CharRange} over a single character. + *

              + * + *

              + * A negated range includes everything except that defined by the single + * character. + *

              + * + * @param ch only character in this range + * @return the new CharRange object + * @since 2.5 + */ + public static CharRange isNot(final char ch) { + return new CharRange(ch, ch, true); + } + + /** + *

              + * Constructs a negated {@code CharRange} over a set of characters. + *

              + * + *

              + * A negated range includes everything except that defined by the start and end + * characters. + *

              + * + *

              + * If start and end are in the wrong order, they are reversed. Thus {@code a-e} + * is the same as {@code e-a}. + *

              + * + * @param start first character, inclusive, in this range + * @param end last character, inclusive, in this range + * @return the new CharRange object + * @since 2.5 + */ + public static CharRange isNotIn(final char start, final char end) { + return new CharRange(start, end, true); + } /** The first character, inclusive, in the range. */ private final char start; + /** The last character, inclusive, in the range. */ private final char end; + /** True if the range is everything except the characters specified. */ private final boolean negated; /** Cached toString. */ private transient String iToString; - /** Empty array. */ - static final CharRange[] EMPTY_ARRAY = new CharRange[0]; - /** *

              * Constructs a {@code CharRange} over a set of characters, optionally negating @@ -91,120 +264,6 @@ final class CharRange implements Iterable, Serializable { this.negated = negated; } - /** - *

              - * Constructs a {@code CharRange} over a single character. - *

              - * - * @param ch only character in this range - * @return the new CharRange object - * @since 2.5 - */ - public static CharRange is(final char ch) { - return new CharRange(ch, ch, false); - } - - /** - *

              - * Constructs a negated {@code CharRange} over a single character. - *

              - * - *

              - * A negated range includes everything except that defined by the single - * character. - *

              - * - * @param ch only character in this range - * @return the new CharRange object - * @since 2.5 - */ - public static CharRange isNot(final char ch) { - return new CharRange(ch, ch, true); - } - - /** - *

              - * Constructs a {@code CharRange} over a set of characters. - *

              - * - *

              - * If start and end are in the wrong order, they are reversed. Thus {@code a-e} - * is the same as {@code e-a}. - *

              - * - * @param start first character, inclusive, in this range - * @param end last character, inclusive, in this range - * @return the new CharRange object - * @since 2.5 - */ - public static CharRange isIn(final char start, final char end) { - return new CharRange(start, end, false); - } - - /** - *

              - * Constructs a negated {@code CharRange} over a set of characters. - *

              - * - *

              - * A negated range includes everything except that defined by the start and end - * characters. - *

              - * - *

              - * If start and end are in the wrong order, they are reversed. Thus {@code a-e} - * is the same as {@code e-a}. - *

              - * - * @param start first character, inclusive, in this range - * @param end last character, inclusive, in this range - * @return the new CharRange object - * @since 2.5 - */ - public static CharRange isNotIn(final char start, final char end) { - return new CharRange(start, end, true); - } - - // Accessors - // ----------------------------------------------------------------------- - /** - *

              - * Gets the start character for this character range. - *

              - * - * @return the start char (inclusive) - */ - public char getStart() { - return this.start; - } - - /** - *

              - * Gets the end character for this character range. - *

              - * - * @return the end char (inclusive) - */ - public char getEnd() { - return this.end; - } - - /** - *

              - * Is this {@code CharRange} negated. - *

              - * - *

              - * A negated range includes everything except that defined by the start and end - * characters. - *

              - * - * @return {@code true} if negated - */ - public boolean isNegated() { - return negated; - } - // Contains // ----------------------------------------------------------------------- /** @@ -265,6 +324,30 @@ final class CharRange implements Iterable, Serializable { return start == other.start && end == other.end && negated == other.negated; } + /** + *

              + * Gets the end character for this character range. + *

              + * + * @return the end char (inclusive) + */ + public char getEnd() { + return this.end; + } + + // Accessors + // ----------------------------------------------------------------------- + /** + *

              + * Gets the start character for this character range. + *

              + * + * @return the start char (inclusive) + */ + public char getStart() { + return this.start; + } + /** *

              * Gets a hashCode compatible with the equals method. @@ -277,6 +360,42 @@ final class CharRange implements Iterable, Serializable { return 83 + start + 7 * end + (negated ? 1 : 0); } + /** + *

              + * Is this {@code CharRange} negated. + *

              + * + *

              + * A negated range includes everything except that defined by the start and end + * characters. + *

              + * + * @return {@code true} if negated + */ + public boolean isNegated() { + return negated; + } + + // Expansions + // ----------------------------------------------------------------------- + /** + *

              + * Returns an iterator which can be used to walk through the characters + * described by this range. + *

              + * + *

              + * #NotThreadSafe# the iterator is not thread-safe + *

              + * + * @return an iterator to the chars represented by this range + * @since 2.5 + */ + @Override + public Iterator iterator() { + return new CharacterIterator(this); + } + /** *

              * Gets a string representation of the character range. @@ -300,122 +419,4 @@ final class CharRange implements Iterable, Serializable { } return iToString; } - - // Expansions - // ----------------------------------------------------------------------- - /** - *

              - * Returns an iterator which can be used to walk through the characters - * described by this range. - *

              - * - *

              - * #NotThreadSafe# the iterator is not thread-safe - *

              - * - * @return an iterator to the chars represented by this range - * @since 2.5 - */ - @Override - public Iterator iterator() { - return new CharacterIterator(this); - } - - /** - * Character {@link Iterator}. - *

              - * #NotThreadSafe# - *

              - */ - private static class CharacterIterator implements Iterator { - /** The current character */ - private char current; - - private final CharRange range; - private boolean hasNext; - - /** - * Constructs a new iterator for the character range. - * - * @param r The character range - */ - private CharacterIterator(final CharRange r) { - range = r; - hasNext = true; - - if (range.negated) { - if (range.start == 0) { - if (range.end == Character.MAX_VALUE) { - // This range is an empty set - hasNext = false; - } else { - current = (char) (range.end + 1); - } - } else { - current = 0; - } - } else { - current = range.start; - } - } - - /** - * Prepares the next character in the range. - */ - private void prepareNext() { - if (range.negated) { - if (current == Character.MAX_VALUE) { - hasNext = false; - } else if (current + 1 == range.start) { - if (range.end == Character.MAX_VALUE) { - hasNext = false; - } else { - current = (char) (range.end + 1); - } - } else { - current = (char) (current + 1); - } - } else if (current < range.end) { - current = (char) (current + 1); - } else { - hasNext = false; - } - } - - /** - * Has the iterator not reached the end character yet? - * - * @return {@code true} if the iterator has yet to reach the character date - */ - @Override - public boolean hasNext() { - return hasNext; - } - - /** - * Returns the next character in the iteration - * - * @return {@code Character} for the next character - */ - @Override - public Character next() { - if (!hasNext) { - throw new NoSuchElementException(); - } - final char cur = current; - prepareNext(); - return Character.valueOf(cur); - } - - /** - * Always throws UnsupportedOperationException. - * - * @throws UnsupportedOperationException Always thrown. - * @see java.util.Iterator#remove() - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - } } diff --git a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java index d8767d92..8bbfd377 100644 --- a/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharSequenceUtils.java @@ -28,43 +28,45 @@ public class CharSequenceUtils { private static final int NOT_FOUND = -1; - /** - *

              - * {@code CharSequenceUtils} instances should NOT be constructed in standard - * programming. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public CharSequenceUtils() { + static final int TO_STRING_LIMIT = 16; + + private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, final int len2, + final int start1) { + for (int i = 1, j = len2 - 1; i <= j; i++, j--) { + if (cs.charAt(start1 + i) != searchChar.charAt(i) || cs.charAt(start1 + j) != searchChar.charAt(j)) { + return false; + } + } + return true; } - // ----------------------------------------------------------------------- /** - *

              - * Returns a new {@code CharSequence} that is a subsequence of this sequence - * starting with the {@code char} value at the specified index. - *

              + * Used by the indexOf(CharSequence methods) as a green implementation of + * indexOf. * - *

              - * This provides the {@code CharSequence} equivalent to - * {@link String#substring(int)}. The length (in {@code char}) of the returned - * sequence is {@code length() - start}, so if {@code start == end} then an - * empty sequence is returned. - *

              - * - * @param cs the specified subsequence, null returns null - * @param start the start index, inclusive, valid - * @return a new subsequence, may be null - * @throws IndexOutOfBoundsException if {@code start} is negative or if - * {@code start} is greater than - * {@code length()} + * @param cs the {@code CharSequence} to be processed + * @param searchChar the {@code CharSequence} to be searched for + * @param start the start index + * @return the index where the search sequence was found */ - public static CharSequence subSequence(final CharSequence cs, final int start) { - return cs == null ? null : cs.subSequence(start, cs.length()); + static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) { + if (cs instanceof String) { + return ((String) cs).indexOf(searchChar.toString(), start); + } else if (cs instanceof StringBuilder) { + return ((StringBuilder) cs).indexOf(searchChar.toString(), start); + } else if (cs instanceof StringBuffer) { + return ((StringBuffer) cs).indexOf(searchChar.toString(), start); + } + return cs.toString().indexOf(searchChar.toString(), start); +// if (cs instanceof String && searchChar instanceof String) { +// // TODO: Do we assume searchChar is usually relatively small; +// // If so then calling toString() on it is better than reverting to +// // the green implementation in the else block +// return ((String) cs).indexOf((String) searchChar, start); +// } else { +// // TODO: Implement rather than convert to String +// return cs.toString().indexOf(searchChar.toString(), start); +// } } // ----------------------------------------------------------------------- @@ -138,106 +140,6 @@ public class CharSequenceUtils { return NOT_FOUND; } - /** - * Used by the indexOf(CharSequence methods) as a green implementation of - * indexOf. - * - * @param cs the {@code CharSequence} to be processed - * @param searchChar the {@code CharSequence} to be searched for - * @param start the start index - * @return the index where the search sequence was found - */ - static int indexOf(final CharSequence cs, final CharSequence searchChar, final int start) { - if (cs instanceof String) { - return ((String) cs).indexOf(searchChar.toString(), start); - } else if (cs instanceof StringBuilder) { - return ((StringBuilder) cs).indexOf(searchChar.toString(), start); - } else if (cs instanceof StringBuffer) { - return ((StringBuffer) cs).indexOf(searchChar.toString(), start); - } - return cs.toString().indexOf(searchChar.toString(), start); -// if (cs instanceof String && searchChar instanceof String) { -// // TODO: Do we assume searchChar is usually relatively small; -// // If so then calling toString() on it is better than reverting to -// // the green implementation in the else block -// return ((String) cs).indexOf((String) searchChar, start); -// } else { -// // TODO: Implement rather than convert to String -// return cs.toString().indexOf(searchChar.toString(), start); -// } - } - - /** - * Returns the index within {@code cs} of the last occurrence of the specified - * character, searching backward starting at the specified index. For values of - * {@code searchChar} in the range from 0 to 0xFFFF (inclusive), the index - * returned is the largest value k such that:
              - * - *
              -	 * (this.charAt(k) == searchChar) && (k <= start)
              -	 * 
              - * - *
              is true. For other values of {@code searchChar}, it is the - * largest value k such that:
              - * - *
              -	 * (this.codePointAt(k) == searchChar) && (k <= start)
              -	 * 
              - * - *
              is true. In either case, if no such character occurs in - * {@code cs} at or before position {@code start}, then {@code -1} is returned. - * - *

              - * All indices are specified in {@code char} values (Unicode code units). - * - * @param cs the {@code CharSequence} to be processed - * @param searchChar the char to be searched for - * @param start the start index, negative returns -1, beyond length starts - * at end - * @return the index where the search char was found, -1 if not found - * @since 3.6 updated to behave more like {@code String} - */ - static int lastIndexOf(final CharSequence cs, final int searchChar, int start) { - if (cs instanceof String) { - return ((String) cs).lastIndexOf(searchChar, start); - } - final int sz = cs.length(); - if (start < 0) { - return NOT_FOUND; - } - if (start >= sz) { - start = sz - 1; - } - if (searchChar < Character.MIN_SUPPLEMENTARY_CODE_POINT) { - for (int i = start; i >= 0; --i) { - if (cs.charAt(i) == searchChar) { - return i; - } - } - return NOT_FOUND; - } - // supplementary characters (LANG1300) - // NOTE - we must do a forward traversal for this to avoid duplicating code - // points - if (searchChar <= Character.MAX_CODE_POINT) { - final char[] chars = Character.toChars(searchChar); - // make sure it's not the last index - if (start == sz - 1) { - return NOT_FOUND; - } - for (int i = start; i >= 0; i--) { - final char high = cs.charAt(i); - final char low = cs.charAt(i + 1); - if (chars[0] == high && chars[1] == low) { - return i; - } - } - } - return NOT_FOUND; - } - - static final int TO_STRING_LIMIT = 16; - /** * Used by the lastIndexOf(CharSequence methods) as a green implementation of * lastIndexOf @@ -310,36 +212,73 @@ public class CharSequenceUtils { } } - private static boolean checkLaterThan1(final CharSequence cs, final CharSequence searchChar, final int len2, - final int start1) { - for (int i = 1, j = len2 - 1; i <= j; i++, j--) { - if (cs.charAt(start1 + i) != searchChar.charAt(i) || cs.charAt(start1 + j) != searchChar.charAt(j)) { - return false; + /** + * Returns the index within {@code cs} of the last occurrence of the specified + * character, searching backward starting at the specified index. For values of + * {@code searchChar} in the range from 0 to 0xFFFF (inclusive), the index + * returned is the largest value k such that:

              + * + *
              +	 * (this.charAt(k) == searchChar) && (k <= start)
              +	 * 
              + * + *
              is true. For other values of {@code searchChar}, it is the + * largest value k such that:
              + * + *
              +	 * (this.codePointAt(k) == searchChar) && (k <= start)
              +	 * 
              + * + *
              is true. In either case, if no such character occurs in + * {@code cs} at or before position {@code start}, then {@code -1} is returned. + * + *

              + * All indices are specified in {@code char} values (Unicode code units). + * + * @param cs the {@code CharSequence} to be processed + * @param searchChar the char to be searched for + * @param start the start index, negative returns -1, beyond length starts + * at end + * @return the index where the search char was found, -1 if not found + * @since 3.6 updated to behave more like {@code String} + */ + static int lastIndexOf(final CharSequence cs, final int searchChar, int start) { + if (cs instanceof String) { + return ((String) cs).lastIndexOf(searchChar, start); + } + final int sz = cs.length(); + if (start < 0) { + return NOT_FOUND; + } + if (start >= sz) { + start = sz - 1; + } + if (searchChar < Character.MIN_SUPPLEMENTARY_CODE_POINT) { + for (int i = start; i >= 0; --i) { + if (cs.charAt(i) == searchChar) { + return i; + } + } + return NOT_FOUND; + } + // supplementary characters (LANG1300) + // NOTE - we must do a forward traversal for this to avoid duplicating code + // points + if (searchChar <= Character.MAX_CODE_POINT) { + final char[] chars = Character.toChars(searchChar); + // make sure it's not the last index + if (start == sz - 1) { + return NOT_FOUND; + } + for (int i = start; i >= 0; i--) { + final char high = cs.charAt(i); + final char low = cs.charAt(i + 1); + if (chars[0] == high && chars[1] == low) { + return i; + } } } - return true; - } - - /** - * Converts the given CharSequence to a char[]. - * - * @param source the {@code CharSequence} to be processed. - * @return the resulting char array, never null. - * @since 3.11 - */ - public static char[] toCharArray(final CharSequence source) { - final int len = StringUtils.length(source); - if (len == 0) { - return new char[0]; - } - if (source instanceof String) { - return ((String) source).toCharArray(); - } - final char[] array = new char[len]; - for (int i = 0; i < len; i++) { - array[i] = source.charAt(i); - } - return array; + return NOT_FOUND; } /** @@ -399,4 +338,65 @@ public class CharSequenceUtils { return true; } + + // ----------------------------------------------------------------------- + /** + *

              + * Returns a new {@code CharSequence} that is a subsequence of this sequence + * starting with the {@code char} value at the specified index. + *

              + * + *

              + * This provides the {@code CharSequence} equivalent to + * {@link String#substring(int)}. The length (in {@code char}) of the returned + * sequence is {@code length() - start}, so if {@code start == end} then an + * empty sequence is returned. + *

              + * + * @param cs the specified subsequence, null returns null + * @param start the start index, inclusive, valid + * @return a new subsequence, may be null + * @throws IndexOutOfBoundsException if {@code start} is negative or if + * {@code start} is greater than + * {@code length()} + */ + public static CharSequence subSequence(final CharSequence cs, final int start) { + return cs == null ? null : cs.subSequence(start, cs.length()); + } + + /** + * Converts the given CharSequence to a char[]. + * + * @param source the {@code CharSequence} to be processed. + * @return the resulting char array, never null. + * @since 3.11 + */ + public static char[] toCharArray(final CharSequence source) { + final int len = StringUtils.length(source); + if (len == 0) { + return new char[0]; + } + if (source instanceof String) { + return ((String) source).toCharArray(); + } + final char[] array = new char[len]; + for (int i = 0; i < len; i++) { + array[i] = source.charAt(i); + } + return array; + } + + /** + *

              + * {@code CharSequenceUtils} instances should NOT be constructed in standard + * programming. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              + */ + public CharSequenceUtils() { + } } diff --git a/src/main/java/org/apache/commons/lang3/CharSet.java b/src/main/java/org/apache/commons/lang3/CharSet.java index 04a9ca91..5cab1113 100644 --- a/src/main/java/org/apache/commons/lang3/CharSet.java +++ b/src/main/java/org/apache/commons/lang3/CharSet.java @@ -100,9 +100,6 @@ public class CharSet implements Serializable { COMMON.put("0-9", ASCII_NUMERIC); } - /** The set of CharRange objects. */ - private final Set set = Collections.synchronizedSet(new HashSet<>()); - // ----------------------------------------------------------------------- /** *

              @@ -194,6 +191,9 @@ public class CharSet implements Serializable { return new CharSet(setStrs); } + /** The set of CharRange objects. */ + private final Set set = Collections.synchronizedSet(new HashSet<>()); + // ----------------------------------------------------------------------- /** *

              @@ -247,21 +247,6 @@ public class CharSet implements Serializable { } } - // ----------------------------------------------------------------------- - /** - *

              - * Gets the internal set as an array of CharRange objects. - *

              - * - * @return an array of immutable CharRange objects - * @since 2.0 - */ -// NOTE: This is no longer public as CharRange is no longer a public class. -// It may be replaced when CharSet moves to Range. - /* public */ CharRange[] getCharRanges() { - return set.toArray(CharRange.EMPTY_ARRAY); - } - // ----------------------------------------------------------------------- /** *

              @@ -311,6 +296,21 @@ public class CharSet implements Serializable { return set.equals(other.set); } + // ----------------------------------------------------------------------- + /** + *

              + * Gets the internal set as an array of CharRange objects. + *

              + * + * @return an array of immutable CharRange objects + * @since 2.0 + */ +// NOTE: This is no longer public as CharRange is no longer a public class. +// It may be replaced when CharSet moves to Range. + /* public */ CharRange[] getCharRanges() { + return set.toArray(CharRange.EMPTY_ARRAY); + } + /** *

              * Gets a hash code compatible with the equals method. diff --git a/src/main/java/org/apache/commons/lang3/CharUtils.java b/src/main/java/org/apache/commons/lang3/CharUtils.java index 93180cb4..dc4933d9 100644 --- a/src/main/java/org/apache/commons/lang3/CharUtils.java +++ b/src/main/java/org/apache/commons/lang3/CharUtils.java @@ -75,71 +75,187 @@ public class CharUtils { /** *

              - * {@code CharUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * {@code CharUtils.toString('c');}. + * Compares two {@code char} values numerically. This is the same functionality + * as provided in Java 7. *

              * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              + * @param x the first {@code char} to compare + * @param y the second {@code char} to compare + * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if + * {@code x < y}; and a value greater than {@code 0} if {@code x > y} + * @since 3.4 */ - public CharUtils() { + public static int compare(final char x, final char y) { + return x - y; } - // ----------------------------------------------------------------------- + // -------------------------------------------------------------------------- /** *

              - * Converts the character to a Character. - *

              - * - *

              - * For ASCII 7 bit characters, this uses a cache that will return the same - * Character object each time. + * Checks whether the character is ASCII 7 bit. *

              * *
              -	 *   CharUtils.toCharacterObject(' ')  = ' '
              -	 *   CharUtils.toCharacterObject('A')  = 'A'
              +	 *   CharUtils.isAscii('a')  = true
              +	 *   CharUtils.isAscii('A')  = true
              +	 *   CharUtils.isAscii('3')  = true
              +	 *   CharUtils.isAscii('-')  = true
              +	 *   CharUtils.isAscii('\n') = true
              +	 *   CharUtils.isAscii('©') = false
               	 * 
              * - * @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches - * chars 0 through 127. - * @param ch the character to convert - * @return a Character of the specified character + * @param ch the character to check + * @return true if less than 128 */ - @Deprecated - public static Character toCharacterObject(final char ch) { - return Character.valueOf(ch); + public static boolean isAscii(final char ch) { + return ch < 128; } /** *

              - * Converts the String to a Character using the first character, returning null - * for empty Strings. - *

              - * - *

              - * For ASCII 7 bit characters, this uses a cache that will return the same - * Character object each time. + * Checks whether the character is ASCII 7 bit alphabetic. *

              * *
              -	 *   CharUtils.toCharacterObject(null) = null
              -	 *   CharUtils.toCharacterObject("")   = null
              -	 *   CharUtils.toCharacterObject("A")  = 'A'
              -	 *   CharUtils.toCharacterObject("BA") = 'B'
              +	 *   CharUtils.isAsciiAlpha('a')  = true
              +	 *   CharUtils.isAsciiAlpha('A')  = true
              +	 *   CharUtils.isAsciiAlpha('3')  = false
              +	 *   CharUtils.isAsciiAlpha('-')  = false
              +	 *   CharUtils.isAsciiAlpha('\n') = false
              +	 *   CharUtils.isAsciiAlpha('©') = false
               	 * 
              * - * @param str the character to convert - * @return the Character value of the first letter of the String + * @param ch the character to check + * @return true if between 65 and 90 or 97 and 122 inclusive */ - public static Character toCharacterObject(final String str) { - if (StringUtils.isEmpty(str)) { - return null; - } - return Character.valueOf(str.charAt(0)); + public static boolean isAsciiAlpha(final char ch) { + return isAsciiAlphaUpper(ch) || isAsciiAlphaLower(ch); + } + + /** + *

              + * Checks whether the character is ASCII 7 bit alphabetic lower case. + *

              + * + *
              +	 *   CharUtils.isAsciiAlphaLower('a')  = true
              +	 *   CharUtils.isAsciiAlphaLower('A')  = false
              +	 *   CharUtils.isAsciiAlphaLower('3')  = false
              +	 *   CharUtils.isAsciiAlphaLower('-')  = false
              +	 *   CharUtils.isAsciiAlphaLower('\n') = false
              +	 *   CharUtils.isAsciiAlphaLower('©') = false
              +	 * 
              + * + * @param ch the character to check + * @return true if between 97 and 122 inclusive + */ + public static boolean isAsciiAlphaLower(final char ch) { + return ch >= 'a' && ch <= 'z'; + } + + /** + *

              + * Checks whether the character is ASCII 7 bit numeric. + *

              + * + *
              +	 *   CharUtils.isAsciiAlphanumeric('a')  = true
              +	 *   CharUtils.isAsciiAlphanumeric('A')  = true
              +	 *   CharUtils.isAsciiAlphanumeric('3')  = true
              +	 *   CharUtils.isAsciiAlphanumeric('-')  = false
              +	 *   CharUtils.isAsciiAlphanumeric('\n') = false
              +	 *   CharUtils.isAsciiAlphanumeric('©') = false
              +	 * 
              + * + * @param ch the character to check + * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive + */ + public static boolean isAsciiAlphanumeric(final char ch) { + return isAsciiAlpha(ch) || isAsciiNumeric(ch); + } + + /** + *

              + * Checks whether the character is ASCII 7 bit alphabetic upper case. + *

              + * + *
              +	 *   CharUtils.isAsciiAlphaUpper('a')  = false
              +	 *   CharUtils.isAsciiAlphaUpper('A')  = true
              +	 *   CharUtils.isAsciiAlphaUpper('3')  = false
              +	 *   CharUtils.isAsciiAlphaUpper('-')  = false
              +	 *   CharUtils.isAsciiAlphaUpper('\n') = false
              +	 *   CharUtils.isAsciiAlphaUpper('©') = false
              +	 * 
              + * + * @param ch the character to check + * @return true if between 65 and 90 inclusive + */ + public static boolean isAsciiAlphaUpper(final char ch) { + return ch >= 'A' && ch <= 'Z'; + } + + /** + *

              + * Checks whether the character is ASCII 7 bit control. + *

              + * + *
              +	 *   CharUtils.isAsciiControl('a')  = false
              +	 *   CharUtils.isAsciiControl('A')  = false
              +	 *   CharUtils.isAsciiControl('3')  = false
              +	 *   CharUtils.isAsciiControl('-')  = false
              +	 *   CharUtils.isAsciiControl('\n') = true
              +	 *   CharUtils.isAsciiControl('©') = false
              +	 * 
              + * + * @param ch the character to check + * @return true if less than 32 or equals 127 + */ + public static boolean isAsciiControl(final char ch) { + return ch < 32 || ch == 127; + } + + /** + *

              + * Checks whether the character is ASCII 7 bit numeric. + *

              + * + *
              +	 *   CharUtils.isAsciiNumeric('a')  = false
              +	 *   CharUtils.isAsciiNumeric('A')  = false
              +	 *   CharUtils.isAsciiNumeric('3')  = true
              +	 *   CharUtils.isAsciiNumeric('-')  = false
              +	 *   CharUtils.isAsciiNumeric('\n') = false
              +	 *   CharUtils.isAsciiNumeric('©') = false
              +	 * 
              + * + * @param ch the character to check + * @return true if between 48 and 57 inclusive + */ + public static boolean isAsciiNumeric(final char ch) { + return ch >= '0' && ch <= '9'; + } + + /** + *

              + * Checks whether the character is ASCII 7 bit printable. + *

              + * + *
              +	 *   CharUtils.isAsciiPrintable('a')  = true
              +	 *   CharUtils.isAsciiPrintable('A')  = true
              +	 *   CharUtils.isAsciiPrintable('3')  = true
              +	 *   CharUtils.isAsciiPrintable('-')  = true
              +	 *   CharUtils.isAsciiPrintable('\n') = false
              +	 *   CharUtils.isAsciiPrintable('©') = false
              +	 * 
              + * + * @param ch the character to check + * @return true if between 32 and 126 inclusive + */ + public static boolean isAsciiPrintable(final char ch) { + return ch >= 32 && ch < 127; } // ----------------------------------------------------------------------- @@ -234,6 +350,60 @@ public class CharUtils { return str.charAt(0); } + // ----------------------------------------------------------------------- + /** + *

              + * Converts the character to a Character. + *

              + * + *

              + * For ASCII 7 bit characters, this uses a cache that will return the same + * Character object each time. + *

              + * + *
              +	 *   CharUtils.toCharacterObject(' ')  = ' '
              +	 *   CharUtils.toCharacterObject('A')  = 'A'
              +	 * 
              + * + * @deprecated Java 5 introduced {@link Character#valueOf(char)} which caches + * chars 0 through 127. + * @param ch the character to convert + * @return a Character of the specified character + */ + @Deprecated + public static Character toCharacterObject(final char ch) { + return Character.valueOf(ch); + } + + /** + *

              + * Converts the String to a Character using the first character, returning null + * for empty Strings. + *

              + * + *

              + * For ASCII 7 bit characters, this uses a cache that will return the same + * Character object each time. + *

              + * + *
              +	 *   CharUtils.toCharacterObject(null) = null
              +	 *   CharUtils.toCharacterObject("")   = null
              +	 *   CharUtils.toCharacterObject("A")  = 'A'
              +	 *   CharUtils.toCharacterObject("BA") = 'B'
              +	 * 
              + * + * @param str the character to convert + * @return the Character value of the first letter of the String + */ + public static Character toCharacterObject(final String str) { + if (StringUtils.isEmpty(str)) { + return null; + } + return Character.valueOf(str.charAt(0)); + } + // ----------------------------------------------------------------------- /** *

              @@ -448,188 +618,18 @@ public class CharUtils { return unicodeEscaped(ch.charValue()); } - // -------------------------------------------------------------------------- /** *

              - * Checks whether the character is ASCII 7 bit. + * {@code CharUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used as + * {@code CharUtils.toString('c');}. *

              * - *
              -	 *   CharUtils.isAscii('a')  = true
              -	 *   CharUtils.isAscii('A')  = true
              -	 *   CharUtils.isAscii('3')  = true
              -	 *   CharUtils.isAscii('-')  = true
              -	 *   CharUtils.isAscii('\n') = true
              -	 *   CharUtils.isAscii('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if less than 128 - */ - public static boolean isAscii(final char ch) { - return ch < 128; - } - - /** *

              - * Checks whether the character is ASCII 7 bit printable. + * This constructor is public to permit tools that require a JavaBean instance + * to operate. *

              - * - *
              -	 *   CharUtils.isAsciiPrintable('a')  = true
              -	 *   CharUtils.isAsciiPrintable('A')  = true
              -	 *   CharUtils.isAsciiPrintable('3')  = true
              -	 *   CharUtils.isAsciiPrintable('-')  = true
              -	 *   CharUtils.isAsciiPrintable('\n') = false
              -	 *   CharUtils.isAsciiPrintable('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if between 32 and 126 inclusive */ - public static boolean isAsciiPrintable(final char ch) { - return ch >= 32 && ch < 127; - } - - /** - *

              - * Checks whether the character is ASCII 7 bit control. - *

              - * - *
              -	 *   CharUtils.isAsciiControl('a')  = false
              -	 *   CharUtils.isAsciiControl('A')  = false
              -	 *   CharUtils.isAsciiControl('3')  = false
              -	 *   CharUtils.isAsciiControl('-')  = false
              -	 *   CharUtils.isAsciiControl('\n') = true
              -	 *   CharUtils.isAsciiControl('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if less than 32 or equals 127 - */ - public static boolean isAsciiControl(final char ch) { - return ch < 32 || ch == 127; - } - - /** - *

              - * Checks whether the character is ASCII 7 bit alphabetic. - *

              - * - *
              -	 *   CharUtils.isAsciiAlpha('a')  = true
              -	 *   CharUtils.isAsciiAlpha('A')  = true
              -	 *   CharUtils.isAsciiAlpha('3')  = false
              -	 *   CharUtils.isAsciiAlpha('-')  = false
              -	 *   CharUtils.isAsciiAlpha('\n') = false
              -	 *   CharUtils.isAsciiAlpha('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if between 65 and 90 or 97 and 122 inclusive - */ - public static boolean isAsciiAlpha(final char ch) { - return isAsciiAlphaUpper(ch) || isAsciiAlphaLower(ch); - } - - /** - *

              - * Checks whether the character is ASCII 7 bit alphabetic upper case. - *

              - * - *
              -	 *   CharUtils.isAsciiAlphaUpper('a')  = false
              -	 *   CharUtils.isAsciiAlphaUpper('A')  = true
              -	 *   CharUtils.isAsciiAlphaUpper('3')  = false
              -	 *   CharUtils.isAsciiAlphaUpper('-')  = false
              -	 *   CharUtils.isAsciiAlphaUpper('\n') = false
              -	 *   CharUtils.isAsciiAlphaUpper('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if between 65 and 90 inclusive - */ - public static boolean isAsciiAlphaUpper(final char ch) { - return ch >= 'A' && ch <= 'Z'; - } - - /** - *

              - * Checks whether the character is ASCII 7 bit alphabetic lower case. - *

              - * - *
              -	 *   CharUtils.isAsciiAlphaLower('a')  = true
              -	 *   CharUtils.isAsciiAlphaLower('A')  = false
              -	 *   CharUtils.isAsciiAlphaLower('3')  = false
              -	 *   CharUtils.isAsciiAlphaLower('-')  = false
              -	 *   CharUtils.isAsciiAlphaLower('\n') = false
              -	 *   CharUtils.isAsciiAlphaLower('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if between 97 and 122 inclusive - */ - public static boolean isAsciiAlphaLower(final char ch) { - return ch >= 'a' && ch <= 'z'; - } - - /** - *

              - * Checks whether the character is ASCII 7 bit numeric. - *

              - * - *
              -	 *   CharUtils.isAsciiNumeric('a')  = false
              -	 *   CharUtils.isAsciiNumeric('A')  = false
              -	 *   CharUtils.isAsciiNumeric('3')  = true
              -	 *   CharUtils.isAsciiNumeric('-')  = false
              -	 *   CharUtils.isAsciiNumeric('\n') = false
              -	 *   CharUtils.isAsciiNumeric('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if between 48 and 57 inclusive - */ - public static boolean isAsciiNumeric(final char ch) { - return ch >= '0' && ch <= '9'; - } - - /** - *

              - * Checks whether the character is ASCII 7 bit numeric. - *

              - * - *
              -	 *   CharUtils.isAsciiAlphanumeric('a')  = true
              -	 *   CharUtils.isAsciiAlphanumeric('A')  = true
              -	 *   CharUtils.isAsciiAlphanumeric('3')  = true
              -	 *   CharUtils.isAsciiAlphanumeric('-')  = false
              -	 *   CharUtils.isAsciiAlphanumeric('\n') = false
              -	 *   CharUtils.isAsciiAlphanumeric('©') = false
              -	 * 
              - * - * @param ch the character to check - * @return true if between 48 and 57 or 65 and 90 or 97 and 122 inclusive - */ - public static boolean isAsciiAlphanumeric(final char ch) { - return isAsciiAlpha(ch) || isAsciiNumeric(ch); - } - - /** - *

              - * Compares two {@code char} values numerically. This is the same functionality - * as provided in Java 7. - *

              - * - * @param x the first {@code char} to compare - * @param y the second {@code char} to compare - * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if - * {@code x < y}; and a value greater than {@code 0} if {@code x > y} - * @since 3.4 - */ - public static int compare(final char x, final char y) { - return x - y; + public CharUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/ClassPathUtils.java b/src/main/java/org/apache/commons/lang3/ClassPathUtils.java index ccee09d0..5c0bb26b 100644 --- a/src/main/java/org/apache/commons/lang3/ClassPathUtils.java +++ b/src/main/java/org/apache/commons/lang3/ClassPathUtils.java @@ -28,21 +28,6 @@ package org.apache.commons.lang3; //@Immutable public class ClassPathUtils { - /** - *

              - * {@code ClassPathUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * {@code ClassPathUtils.toFullyQualifiedName(MyClass.class, "MyClass.properties");}. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public ClassPathUtils() { - } - /** * Returns the fully qualified name for the resource with name * {@code resourceName} relative to the given context. @@ -155,4 +140,19 @@ public class ClassPathUtils { return context.getName().replace('.', '/') + "/" + resourceName; } + /** + *

              + * {@code ClassPathUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used as + * {@code ClassPathUtils.toFullyQualifiedName(MyClass.class, "MyClass.properties");}. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              + */ + public ClassPathUtils() { + } + } diff --git a/src/main/java/org/apache/commons/lang3/Conversion.java b/src/main/java/org/apache/commons/lang3/Conversion.java index 30965383..c315ffd7 100644 --- a/src/main/java/org/apache/commons/lang3/Conversion.java +++ b/src/main/java/org/apache/commons/lang3/Conversion.java @@ -86,200 +86,107 @@ public class Conversion { /** *

              - * Converts a hexadecimal digit into an int using the default (Lsb0) bit - * ordering. + * Converts the first 4 bits of a binary (represented as boolean array) in big + * endian Msb0 bit ordering to a hexadecimal digit. *

              *

              - * '1' is converted to 1 + * (1, 0, 0, 0) is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + * 0, 1, 0, 0) is converted to '4' *

              * - * @param hexDigit the hexadecimal digit to convert - * @return an int equals to {@code hexDigit} - * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal - * digit + * @param src the binary to convert + * @return a hexadecimal digit representing the selected bits + * @throws IllegalArgumentException if {@code src} is empty + * @throws NullPointerException if {@code src} is {@code null} */ - public static int hexDigitToInt(final char hexDigit) { - final int digit = Character.digit(hexDigit, 16); - if (digit < 0) { - throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); - } - return digit; + public static char binaryBeMsb0ToHexDigit(final boolean[] src) { + return binaryBeMsb0ToHexDigit(src, 0); } /** *

              - * Converts a hexadecimal digit into an int using the Msb0 bit ordering. + * Converts a binary (represented as boolean array) in big endian Msb0 bit + * ordering to a hexadecimal digit. *

              *

              - * '1' is converted to 8 + * (1, 0, 0, 0) with srcPos = 0 is converted as follow: '8' (1, 0, 0, 0, 0, 0, + * 0, 0, 0, 0, 0, 1, 0, 1, 0, 0) with srcPos = 2 is converted to '5' *

              * - * @param hexDigit the hexadecimal digit to convert - * @return an int equals to {@code hexDigit} - * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal - * digit + * @param src the binary to convert + * @param srcPos the position of the lsb to start the conversion + * @return a hexadecimal digit representing the selected bits + * @throws IllegalArgumentException if {@code src} is empty + * @throws NullPointerException if {@code src} is {@code null} */ - public static int hexDigitMsb0ToInt(final char hexDigit) { - switch (hexDigit) { - case '0': - return 0x0; - case '1': - return 0x8; - case '2': - return 0x4; - case '3': - return 0xC; - case '4': - return 0x2; - case '5': - return 0xA; - case '6': - return 0x6; - case '7': - return 0xE; - case '8': - return 0x1; - case '9': - return 0x9; - case 'a':// fall through - case 'A': - return 0x5; - case 'b':// fall through - case 'B': - return 0xD; - case 'c':// fall through - case 'C': - return 0x3; - case 'd':// fall through - case 'D': - return 0xB; - case 'e':// fall through - case 'E': - return 0x7; - case 'f':// fall through - case 'F': - return 0xF; - default: - throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + public static char binaryBeMsb0ToHexDigit(boolean[] src, int srcPos) { + if (src.length == 0) { + throw new IllegalArgumentException("Cannot convert an empty array."); } + final int beSrcPos = src.length - 1 - srcPos; + final int srcLen = Math.min(4, beSrcPos + 1); + final boolean[] paddedSrc = new boolean[4]; + System.arraycopy(src, beSrcPos + 1 - srcLen, paddedSrc, 4 - srcLen, srcLen); + src = paddedSrc; + srcPos = 0; + if (src[srcPos]) { + if (src.length > srcPos + 1 && src[srcPos + 1]) { + if (src.length > srcPos + 2 && src[srcPos + 2]) { + return src.length > srcPos + 3 && src[srcPos + 3] ? 'f' : 'e'; + } + return src.length > srcPos + 3 && src[srcPos + 3] ? 'd' : 'c'; + } + if (src.length > srcPos + 2 && src[srcPos + 2]) { + return src.length > srcPos + 3 && src[srcPos + 3] ? 'b' : 'a'; + } + return src.length > srcPos + 3 && src[srcPos + 3] ? '9' : '8'; + } + if (src.length > srcPos + 1 && src[srcPos + 1]) { + if (src.length > srcPos + 2 && src[srcPos + 2]) { + return src.length > srcPos + 3 && src[srcPos + 3] ? '7' : '6'; + } + return src.length > srcPos + 3 && src[srcPos + 3] ? '5' : '4'; + } + if (src.length > srcPos + 2 && src[srcPos + 2]) { + return src.length > srcPos + 3 && src[srcPos + 3] ? '3' : '2'; + } + return src.length > srcPos + 3 && src[srcPos + 3] ? '1' : '0'; } /** *

              - * Converts a hexadecimal digit into binary (represented as boolean array) using - * the default (Lsb0) bit ordering. - *

              - *

              - * '1' is converted as follow: (1, 0, 0, 0) + * Converts binary (represented as boolean array) into a byte using the default + * (little endian, Lsb0) byte and bit ordering. *

              * - * @param hexDigit the hexadecimal digit to convert - * @return a boolean array with the binary representation of {@code hexDigit} - * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal - * digit + * @param src the binary to convert + * @param srcPos the position in {@code src}, in boolean unit, from where to + * start the conversion + * @param dstInit initial value of the destination byte + * @param dstPos the position of the lsb, in bits, in the result byte + * @param nBools the number of booleans to convert + * @return a byte containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 8} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBools > src.length} */ - public static boolean[] hexDigitToBinary(final char hexDigit) { - switch (hexDigit) { - case '0': - return FFFF.clone(); - case '1': - return TFFF.clone(); - case '2': - return FTFF.clone(); - case '3': - return TTFF.clone(); - case '4': - return FFTF.clone(); - case '5': - return TFTF.clone(); - case '6': - return FTTF.clone(); - case '7': - return TTTF.clone(); - case '8': - return FFFT.clone(); - case '9': - return TFFT.clone(); - case 'a':// fall through - case 'A': - return FTFT.clone(); - case 'b':// fall through - case 'B': - return TTFT.clone(); - case 'c':// fall through - case 'C': - return FFTT.clone(); - case 'd':// fall through - case 'D': - return TFTT.clone(); - case 'e':// fall through - case 'E': - return FTTT.clone(); - case 'f':// fall through - case 'F': - return TTTT.clone(); - default: - throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + public static byte binaryToByte(final boolean[] src, final int srcPos, final byte dstInit, final int dstPos, + final int nBools) { + if (src.length == 0 && srcPos == 0 || 0 == nBools) { + return dstInit; } - } - - /** - *

              - * Converts a hexadecimal digit into binary (represented as boolean array) using - * the Msb0 bit ordering. - *

              - *

              - * '1' is converted as follow: (0, 0, 0, 1) - *

              - * - * @param hexDigit the hexadecimal digit to convert - * @return a boolean array with the binary representation of {@code hexDigit} - * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal - * digit - */ - public static boolean[] hexDigitMsb0ToBinary(final char hexDigit) { - switch (hexDigit) { - case '0': - return FFFF.clone(); - case '1': - return FFFT.clone(); - case '2': - return FFTF.clone(); - case '3': - return FFTT.clone(); - case '4': - return FTFF.clone(); - case '5': - return FTFT.clone(); - case '6': - return FTTF.clone(); - case '7': - return FTTT.clone(); - case '8': - return TFFF.clone(); - case '9': - return TFFT.clone(); - case 'a':// fall through - case 'A': - return TFTF.clone(); - case 'b':// fall through - case 'B': - return TFTT.clone(); - case 'c':// fall through - case 'C': - return TTFF.clone(); - case 'd':// fall through - case 'D': - return TTFT.clone(); - case 'e':// fall through - case 'E': - return TTTF.clone(); - case 'f':// fall through - case 'F': - return TTTT.clone(); - default: - throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + if (nBools - 1 + dstPos >= 8) { + throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 8"); } + byte out = dstInit; + for (int i = 0; i < nBools; i++) { + final int shift = i + dstPos; + final int bits = (src[i + srcPos] ? 1 : 0) << shift; + final int mask = 0x1 << shift; + out = (byte) ((out & ~mask) | bits); + } + return out; } /** @@ -414,71 +321,785 @@ public class Conversion { /** *

              - * Converts the first 4 bits of a binary (represented as boolean array) in big - * endian Msb0 bit ordering to a hexadecimal digit. - *

              - *

              - * (1, 0, 0, 0) is converted as follow: '8' (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - * 0, 1, 0, 0) is converted to '4' + * Converts binary (represented as boolean array) into an int using the default + * (little endian, Lsb0) byte and bit ordering. *

              * - * @param src the binary to convert - * @return a hexadecimal digit representing the selected bits - * @throws IllegalArgumentException if {@code src} is empty - * @throws NullPointerException if {@code src} is {@code null} + * @param src the binary to convert + * @param srcPos the position in {@code src}, in boolean unit, from where to + * start the conversion + * @param dstInit initial value of the destination int + * @param dstPos the position of the lsb, in bits, in the result int + * @param nBools the number of booleans to convert + * @return an int containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 32} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBools > src.length} */ - public static char binaryBeMsb0ToHexDigit(final boolean[] src) { - return binaryBeMsb0ToHexDigit(src, 0); + public static int binaryToInt(final boolean[] src, final int srcPos, final int dstInit, final int dstPos, + final int nBools) { + if (src.length == 0 && srcPos == 0 || 0 == nBools) { + return dstInit; + } + if (nBools - 1 + dstPos >= 32) { + throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 32"); + } + int out = dstInit; + for (int i = 0; i < nBools; i++) { + final int shift = i + dstPos; + final int bits = (src[i + srcPos] ? 1 : 0) << shift; + final int mask = 0x1 << shift; + out = (out & ~mask) | bits; + } + return out; } /** *

              - * Converts a binary (represented as boolean array) in big endian Msb0 bit - * ordering to a hexadecimal digit. - *

              - *

              - * (1, 0, 0, 0) with srcPos = 0 is converted as follow: '8' (1, 0, 0, 0, 0, 0, - * 0, 0, 0, 0, 0, 1, 0, 1, 0, 0) with srcPos = 2 is converted to '5' + * Converts binary (represented as boolean array) into a long using the default + * (little endian, Lsb0) byte and bit ordering. *

              * - * @param src the binary to convert - * @param srcPos the position of the lsb to start the conversion - * @return a hexadecimal digit representing the selected bits - * @throws IllegalArgumentException if {@code src} is empty - * @throws NullPointerException if {@code src} is {@code null} + * @param src the binary to convert + * @param srcPos the position in {@code src}, in boolean unit, from where to + * start the conversion + * @param dstInit initial value of the destination long + * @param dstPos the position of the lsb, in bits, in the result long + * @param nBools the number of booleans to convert + * @return a long containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 64} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBools > src.length} */ - public static char binaryBeMsb0ToHexDigit(boolean[] src, int srcPos) { - if (src.length == 0) { - throw new IllegalArgumentException("Cannot convert an empty array."); + public static long binaryToLong(final boolean[] src, final int srcPos, final long dstInit, final int dstPos, + final int nBools) { + if (src.length == 0 && srcPos == 0 || 0 == nBools) { + return dstInit; } - final int beSrcPos = src.length - 1 - srcPos; - final int srcLen = Math.min(4, beSrcPos + 1); - final boolean[] paddedSrc = new boolean[4]; - System.arraycopy(src, beSrcPos + 1 - srcLen, paddedSrc, 4 - srcLen, srcLen); - src = paddedSrc; - srcPos = 0; - if (src[srcPos]) { - if (src.length > srcPos + 1 && src[srcPos + 1]) { - if (src.length > srcPos + 2 && src[srcPos + 2]) { - return src.length > srcPos + 3 && src[srcPos + 3] ? 'f' : 'e'; - } - return src.length > srcPos + 3 && src[srcPos + 3] ? 'd' : 'c'; + if (nBools - 1 + dstPos >= 64) { + throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 64"); + } + long out = dstInit; + for (int i = 0; i < nBools; i++) { + final int shift = i + dstPos; + final long bits = (src[i + srcPos] ? 1L : 0) << shift; + final long mask = 0x1L << shift; + out = (out & ~mask) | bits; + } + return out; + } + + /** + *

              + * Converts binary (represented as boolean array) into a short using the default + * (little endian, Lsb0) byte and bit ordering. + *

              + * + * @param src the binary to convert + * @param srcPos the position in {@code src}, in boolean unit, from where to + * start the conversion + * @param dstInit initial value of the destination short + * @param dstPos the position of the lsb, in bits, in the result short + * @param nBools the number of booleans to convert + * @return a short containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 16} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBools > src.length} + */ + public static short binaryToShort(final boolean[] src, final int srcPos, final short dstInit, final int dstPos, + final int nBools) { + if (src.length == 0 && srcPos == 0 || 0 == nBools) { + return dstInit; + } + if (nBools - 1 + dstPos >= 16) { + throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 16"); + } + short out = dstInit; + for (int i = 0; i < nBools; i++) { + final int shift = i + dstPos; + final int bits = (src[i + srcPos] ? 1 : 0) << shift; + final int mask = 0x1 << shift; + out = (short) ((out & ~mask) | bits); + } + return out; + } + + /** + *

              + * Converts an array of byte into an int using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the byte array to convert + * @param srcPos the position in {@code src}, in byte unit, from where to start + * the conversion + * @param dstInit initial value of the destination int + * @param dstPos the position of the lsb, in bits, in the result int + * @param nBytes the number of bytes to convert + * @return an int containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 32} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBytes > src.length} + */ + public static int byteArrayToInt(final byte[] src, final int srcPos, final int dstInit, final int dstPos, + final int nBytes) { + if (src.length == 0 && srcPos == 0 || 0 == nBytes) { + return dstInit; + } + if ((nBytes - 1) * 8 + dstPos >= 32) { + throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 32"); + } + int out = dstInit; + for (int i = 0; i < nBytes; i++) { + final int shift = i * 8 + dstPos; + final int bits = (0xff & src[i + srcPos]) << shift; + final int mask = 0xff << shift; + out = (out & ~mask) | bits; + } + return out; + } + + /** + *

              + * Converts an array of byte into a long using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the byte array to convert + * @param srcPos the position in {@code src}, in byte unit, from where to start + * the conversion + * @param dstInit initial value of the destination long + * @param dstPos the position of the lsb, in bits, in the result long + * @param nBytes the number of bytes to convert + * @return a long containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 64} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBytes > src.length} + */ + public static long byteArrayToLong(final byte[] src, final int srcPos, final long dstInit, final int dstPos, + final int nBytes) { + if (src.length == 0 && srcPos == 0 || 0 == nBytes) { + return dstInit; + } + if ((nBytes - 1) * 8 + dstPos >= 64) { + throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 64"); + } + long out = dstInit; + for (int i = 0; i < nBytes; i++) { + final int shift = i * 8 + dstPos; + final long bits = (0xffL & src[i + srcPos]) << shift; + final long mask = 0xffL << shift; + out = (out & ~mask) | bits; + } + return out; + } + + /** + *

              + * Converts an array of byte into a short using the default (little endian, + * Lsb0) byte and bit ordering. + *

              + * + * @param src the byte array to convert + * @param srcPos the position in {@code src}, in byte unit, from where to start + * the conversion + * @param dstInit initial value of the destination short + * @param dstPos the position of the lsb, in bits, in the result short + * @param nBytes the number of bytes to convert + * @return a short containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 16} + * @throws ArrayIndexOutOfBoundsException if + * {@code srcPos + nBytes > src.length} + */ + public static short byteArrayToShort(final byte[] src, final int srcPos, final short dstInit, final int dstPos, + final int nBytes) { + if (src.length == 0 && srcPos == 0 || 0 == nBytes) { + return dstInit; + } + if ((nBytes - 1) * 8 + dstPos >= 16) { + throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 16"); + } + short out = dstInit; + for (int i = 0; i < nBytes; i++) { + final int shift = i * 8 + dstPos; + final int bits = (0xff & src[i + srcPos]) << shift; + final int mask = 0xff << shift; + out = (short) ((out & ~mask) | bits); + } + return out; + } + + /** + *

              + * Converts bytes from an array into a UUID using the default (little endian, + * Lsb0) byte and bit ordering. + *

              + * + * @param src the byte array to convert + * @param srcPos the position in {@code src} where to copy the result from + * @return a UUID + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if array does not contain at least 16 bytes + * beginning with {@code srcPos} + */ + public static EaglercraftUUID byteArrayToUuid(final byte[] src, final int srcPos) { + if (src.length - srcPos < 16) { + throw new IllegalArgumentException("Need at least 16 bytes for UUID"); + } + return new EaglercraftUUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(src, srcPos + 8, 0, 0, 8)); + } + + /** + *

              + * Converts a byte into an array of boolean using the default (little endian, + * Lsb0) byte and bit ordering. + *

              + * + * @param src the byte to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dst the destination array + * @param dstPos the position in {@code dst} where to copy the result + * @param nBools the number of booleans to copy to {@code dst}, must be smaller + * or equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws NullPointerException if {@code dst} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 8} + * @throws ArrayIndexOutOfBoundsException if + * {@code dstPos + nBools > dst.length} + */ + public static boolean[] byteToBinary(final byte src, final int srcPos, final boolean[] dst, final int dstPos, + final int nBools) { + if (0 == nBools) { + return dst; + } + if (nBools - 1 + srcPos >= 8) { + throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 8"); + } + for (int i = 0; i < nBools; i++) { + final int shift = i + srcPos; + dst[dstPos + i] = (0x1 & (src >> shift)) != 0; + } + return dst; + } + + /** + *

              + * Converts a byte into an array of Char using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the byte to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dstInit the initial value for the result String + * @param dstPos the position in {@code dst} where to copy the result + * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or + * equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 8} + * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos} + */ + public static String byteToHex(final byte src, final int srcPos, final String dstInit, final int dstPos, + final int nHexs) { + if (0 == nHexs) { + return dstInit; + } + if ((nHexs - 1) * 4 + srcPos >= 8) { + throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 8"); + } + final StringBuilder sb = new StringBuilder(dstInit); + int append = sb.length(); + for (int i = 0; i < nHexs; i++) { + final int shift = i * 4 + srcPos; + final int bits = 0xF & (src >> shift); + if (dstPos + i == append) { + ++append; + sb.append(intToHexDigit(bits)); + } else { + sb.setCharAt(dstPos + i, intToHexDigit(bits)); } - if (src.length > srcPos + 2 && src[srcPos + 2]) { - return src.length > srcPos + 3 && src[srcPos + 3] ? 'b' : 'a'; + } + return sb.toString(); + } + + /** + *

              + * Converts a hexadecimal digit into binary (represented as boolean array) using + * the Msb0 bit ordering. + *

              + *

              + * '1' is converted as follow: (0, 0, 0, 1) + *

              + * + * @param hexDigit the hexadecimal digit to convert + * @return a boolean array with the binary representation of {@code hexDigit} + * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal + * digit + */ + public static boolean[] hexDigitMsb0ToBinary(final char hexDigit) { + switch (hexDigit) { + case '0': + return FFFF.clone(); + case '1': + return FFFT.clone(); + case '2': + return FFTF.clone(); + case '3': + return FFTT.clone(); + case '4': + return FTFF.clone(); + case '5': + return FTFT.clone(); + case '6': + return FTTF.clone(); + case '7': + return FTTT.clone(); + case '8': + return TFFF.clone(); + case '9': + return TFFT.clone(); + case 'a':// fall through + case 'A': + return TFTF.clone(); + case 'b':// fall through + case 'B': + return TFTT.clone(); + case 'c':// fall through + case 'C': + return TTFF.clone(); + case 'd':// fall through + case 'D': + return TTFT.clone(); + case 'e':// fall through + case 'E': + return TTTF.clone(); + case 'f':// fall through + case 'F': + return TTTT.clone(); + default: + throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + } + } + + /** + *

              + * Converts a hexadecimal digit into an int using the Msb0 bit ordering. + *

              + *

              + * '1' is converted to 8 + *

              + * + * @param hexDigit the hexadecimal digit to convert + * @return an int equals to {@code hexDigit} + * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal + * digit + */ + public static int hexDigitMsb0ToInt(final char hexDigit) { + switch (hexDigit) { + case '0': + return 0x0; + case '1': + return 0x8; + case '2': + return 0x4; + case '3': + return 0xC; + case '4': + return 0x2; + case '5': + return 0xA; + case '6': + return 0x6; + case '7': + return 0xE; + case '8': + return 0x1; + case '9': + return 0x9; + case 'a':// fall through + case 'A': + return 0x5; + case 'b':// fall through + case 'B': + return 0xD; + case 'c':// fall through + case 'C': + return 0x3; + case 'd':// fall through + case 'D': + return 0xB; + case 'e':// fall through + case 'E': + return 0x7; + case 'f':// fall through + case 'F': + return 0xF; + default: + throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + } + } + + /** + *

              + * Converts a hexadecimal digit into binary (represented as boolean array) using + * the default (Lsb0) bit ordering. + *

              + *

              + * '1' is converted as follow: (1, 0, 0, 0) + *

              + * + * @param hexDigit the hexadecimal digit to convert + * @return a boolean array with the binary representation of {@code hexDigit} + * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal + * digit + */ + public static boolean[] hexDigitToBinary(final char hexDigit) { + switch (hexDigit) { + case '0': + return FFFF.clone(); + case '1': + return TFFF.clone(); + case '2': + return FTFF.clone(); + case '3': + return TTFF.clone(); + case '4': + return FFTF.clone(); + case '5': + return TFTF.clone(); + case '6': + return FTTF.clone(); + case '7': + return TTTF.clone(); + case '8': + return FFFT.clone(); + case '9': + return TFFT.clone(); + case 'a':// fall through + case 'A': + return FTFT.clone(); + case 'b':// fall through + case 'B': + return TTFT.clone(); + case 'c':// fall through + case 'C': + return FFTT.clone(); + case 'd':// fall through + case 'D': + return TFTT.clone(); + case 'e':// fall through + case 'E': + return FTTT.clone(); + case 'f':// fall through + case 'F': + return TTTT.clone(); + default: + throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + } + } + + /** + *

              + * Converts a hexadecimal digit into an int using the default (Lsb0) bit + * ordering. + *

              + *

              + * '1' is converted to 1 + *

              + * + * @param hexDigit the hexadecimal digit to convert + * @return an int equals to {@code hexDigit} + * @throws IllegalArgumentException if {@code hexDigit} is not a hexadecimal + * digit + */ + public static int hexDigitToInt(final char hexDigit) { + final int digit = Character.digit(hexDigit, 16); + if (digit < 0) { + throw new IllegalArgumentException("Cannot interpret '" + hexDigit + "' as a hexadecimal digit"); + } + return digit; + } + + /** + *

              + * Converts an array of Char into a byte using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the hex string to convert + * @param srcPos the position in {@code src}, in Char unit, from where to start + * the conversion + * @param dstInit initial value of the destination byte + * @param dstPos the position of the lsb, in bits, in the result byte + * @param nHex the number of Chars to convert + * @return a byte containing the selected bits + * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 8} + */ + public static byte hexToByte(final String src, final int srcPos, final byte dstInit, final int dstPos, + final int nHex) { + if (0 == nHex) { + return dstInit; + } + if ((nHex - 1) * 4 + dstPos >= 8) { + throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 8"); + } + byte out = dstInit; + for (int i = 0; i < nHex; i++) { + final int shift = i * 4 + dstPos; + final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; + final int mask = 0xf << shift; + out = (byte) ((out & ~mask) | bits); + } + return out; + } + + /** + *

              + * Converts an array of Char into an int using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the hex string to convert + * @param srcPos the position in {@code src}, in Char unit, from where to start + * the conversion + * @param dstInit initial value of the destination int + * @param dstPos the position of the lsb, in bits, in the result int + * @param nHex the number of Chars to convert + * @return an int containing the selected bits + * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 32} + */ + public static int hexToInt(final String src, final int srcPos, final int dstInit, final int dstPos, + final int nHex) { + if (0 == nHex) { + return dstInit; + } + if ((nHex - 1) * 4 + dstPos >= 32) { + throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 32"); + } + int out = dstInit; + for (int i = 0; i < nHex; i++) { + final int shift = i * 4 + dstPos; + final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; + final int mask = 0xf << shift; + out = (out & ~mask) | bits; + } + return out; + } + + /** + *

              + * Converts an array of Char into a long using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the hex string to convert + * @param srcPos the position in {@code src}, in Char unit, from where to start + * the conversion + * @param dstInit initial value of the destination long + * @param dstPos the position of the lsb, in bits, in the result long + * @param nHex the number of Chars to convert + * @return a long containing the selected bits + * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 64} + */ + public static long hexToLong(final String src, final int srcPos, final long dstInit, final int dstPos, + final int nHex) { + if (0 == nHex) { + return dstInit; + } + if ((nHex - 1) * 4 + dstPos >= 64) { + throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 64"); + } + long out = dstInit; + for (int i = 0; i < nHex; i++) { + final int shift = i * 4 + dstPos; + final long bits = (0xfL & hexDigitToInt(src.charAt(i + srcPos))) << shift; + final long mask = 0xfL << shift; + out = (out & ~mask) | bits; + } + return out; + } + + /** + *

              + * Converts an array of Char into a short using the default (little endian, + * Lsb0) byte and bit ordering. + *

              + * + * @param src the hex string to convert + * @param srcPos the position in {@code src}, in Char unit, from where to start + * the conversion + * @param dstInit initial value of the destination short + * @param dstPos the position of the lsb, in bits, in the result short + * @param nHex the number of Chars to convert + * @return a short containing the selected bits + * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 16} + */ + public static short hexToShort(final String src, final int srcPos, final short dstInit, final int dstPos, + final int nHex) { + if (0 == nHex) { + return dstInit; + } + if ((nHex - 1) * 4 + dstPos >= 16) { + throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 16"); + } + short out = dstInit; + for (int i = 0; i < nHex; i++) { + final int shift = i * 4 + dstPos; + final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; + final int mask = 0xf << shift; + out = (short) ((out & ~mask) | bits); + } + return out; + } + + /** + *

              + * Converts an array of int into a long using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the int array to convert + * @param srcPos the position in {@code src}, in int unit, from where to start + * the conversion + * @param dstInit initial value of the destination long + * @param dstPos the position of the lsb, in bits, in the result long + * @param nInts the number of ints to convert + * @return a long containing the selected bits + * @throws IllegalArgumentException if {@code (nInts-1)*32+dstPos >= 64} + * @throws NullPointerException if {@code src} is {@code null} + * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nInts > src.length} + */ + public static long intArrayToLong(final int[] src, final int srcPos, final long dstInit, final int dstPos, + final int nInts) { + if (src.length == 0 && srcPos == 0 || 0 == nInts) { + return dstInit; + } + if ((nInts - 1) * 32 + dstPos >= 64) { + throw new IllegalArgumentException("(nInts-1)*32+dstPos is greater or equal to than 64"); + } + long out = dstInit; + for (int i = 0; i < nInts; i++) { + final int shift = i * 32 + dstPos; + final long bits = (0xffffffffL & src[i + srcPos]) << shift; + final long mask = 0xffffffffL << shift; + out = (out & ~mask) | bits; + } + return out; + } + + /** + *

              + * Converts an int into an array of boolean using the default (little endian, + * Lsb0) byte and bit ordering. + *

              + * + * @param src the int to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dst the destination array + * @param dstPos the position in {@code dst} where to copy the result + * @param nBools the number of booleans to copy to {@code dst}, must be smaller + * or equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws NullPointerException if {@code dst} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 32} + * @throws ArrayIndexOutOfBoundsException if + * {@code dstPos + nBools > dst.length} + */ + public static boolean[] intToBinary(final int src, final int srcPos, final boolean[] dst, final int dstPos, + final int nBools) { + if (0 == nBools) { + return dst; + } + if (nBools - 1 + srcPos >= 32) { + throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 32"); + } + for (int i = 0; i < nBools; i++) { + final int shift = i + srcPos; + dst[dstPos + i] = (0x1 & (src >> shift)) != 0; + } + return dst; + } + + /** + *

              + * Converts an int into an array of byte using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the int to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dst the destination array + * @param dstPos the position in {@code dst} where to copy the result + * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or + * equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws NullPointerException if {@code dst} is {@code null} + * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 32} + * @throws ArrayIndexOutOfBoundsException if + * {@code dstPos + nBytes > dst.length} + */ + public static byte[] intToByteArray(final int src, final int srcPos, final byte[] dst, final int dstPos, + final int nBytes) { + if (0 == nBytes) { + return dst; + } + if ((nBytes - 1) * 8 + srcPos >= 32) { + throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 32"); + } + for (int i = 0; i < nBytes; i++) { + final int shift = i * 8 + srcPos; + dst[dstPos + i] = (byte) (0xff & (src >> shift)); + } + return dst; + } + + /** + *

              + * Converts an int into an array of Char using the default (little endian, Lsb0) + * byte and bit ordering. + *

              + * + * @param src the int to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dstInit the initial value for the result String + * @param dstPos the position in {@code dst} where to copy the result + * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or + * equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 32} + * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos} + */ + public static String intToHex(final int src, final int srcPos, final String dstInit, final int dstPos, + final int nHexs) { + if (0 == nHexs) { + return dstInit; + } + if ((nHexs - 1) * 4 + srcPos >= 32) { + throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 32"); + } + final StringBuilder sb = new StringBuilder(dstInit); + int append = sb.length(); + for (int i = 0; i < nHexs; i++) { + final int shift = i * 4 + srcPos; + final int bits = 0xF & (src >> shift); + if (dstPos + i == append) { + ++append; + sb.append(intToHexDigit(bits)); + } else { + sb.setCharAt(dstPos + i, intToHexDigit(bits)); } - return src.length > srcPos + 3 && src[srcPos + 3] ? '9' : '8'; } - if (src.length > srcPos + 1 && src[srcPos + 1]) { - if (src.length > srcPos + 2 && src[srcPos + 2]) { - return src.length > srcPos + 3 && src[srcPos + 3] ? '7' : '6'; - } - return src.length > srcPos + 3 && src[srcPos + 3] ? '5' : '4'; - } - if (src.length > srcPos + 2 && src[srcPos + 2]) { - return src.length > srcPos + 3 && src[srcPos + 3] ? '3' : '2'; - } - return src.length > srcPos + 3 && src[srcPos + 3] ? '1' : '0'; + return sb.toString(); } /** @@ -567,493 +1188,144 @@ public class Conversion { /** *

              - * Converts an array of int into a long using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the int array to convert - * @param srcPos the position in {@code src}, in int unit, from where to start - * the conversion - * @param dstInit initial value of the destination long - * @param dstPos the position of the lsb, in bits, in the result long - * @param nInts the number of ints to convert - * @return a long containing the selected bits - * @throws IllegalArgumentException if {@code (nInts-1)*32+dstPos >= 64} - * @throws NullPointerException if {@code src} is {@code null} - * @throws ArrayIndexOutOfBoundsException if {@code srcPos + nInts > src.length} - */ - public static long intArrayToLong(final int[] src, final int srcPos, final long dstInit, final int dstPos, - final int nInts) { - if (src.length == 0 && srcPos == 0 || 0 == nInts) { - return dstInit; - } - if ((nInts - 1) * 32 + dstPos >= 64) { - throw new IllegalArgumentException("(nInts-1)*32+dstPos is greater or equal to than 64"); - } - long out = dstInit; - for (int i = 0; i < nInts; i++) { - final int shift = i * 32 + dstPos; - final long bits = (0xffffffffL & src[i + srcPos]) << shift; - final long mask = 0xffffffffL << shift; - out = (out & ~mask) | bits; - } - return out; - } - - /** - *

              - * Converts an array of short into a long using the default (little endian, + * Converts an int into an array of short using the default (little endian, * Lsb0) byte and bit ordering. *

              * - * @param src the short array to convert - * @param srcPos the position in {@code src}, in short unit, from where to - * start the conversion - * @param dstInit initial value of the destination long - * @param dstPos the position of the lsb, in bits, in the result long - * @param nShorts the number of shorts to convert - * @return a long containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 64} + * @param src the int to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dst the destination array + * @param dstPos the position in {@code dst} where to copy the result + * @param nShorts the number of shorts to copy to {@code dst}, must be smaller + * or equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws NullPointerException if {@code dst} is {@code null} + * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 32} * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nShorts > src.length} + * {@code dstPos + nShorts > dst.length} */ - public static long shortArrayToLong(final short[] src, final int srcPos, final long dstInit, final int dstPos, + public static short[] intToShortArray(final int src, final int srcPos, final short[] dst, final int dstPos, final int nShorts) { - if (src.length == 0 && srcPos == 0 || 0 == nShorts) { - return dstInit; + if (0 == nShorts) { + return dst; } - if ((nShorts - 1) * 16 + dstPos >= 64) { - throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 64"); + if ((nShorts - 1) * 16 + srcPos >= 32) { + throw new IllegalArgumentException("(nShorts-1)*16+srcPos is greater or equal to than 32"); } - long out = dstInit; for (int i = 0; i < nShorts; i++) { - final int shift = i * 16 + dstPos; - final long bits = (0xffffL & src[i + srcPos]) << shift; - final long mask = 0xffffL << shift; - out = (out & ~mask) | bits; + final int shift = i * 16 + srcPos; + dst[dstPos + i] = (short) (0xffff & (src >> shift)); } - return out; + return dst; } /** *

              - * Converts an array of short into an int using the default (little endian, + * Converts a long into an array of boolean using the default (little endian, * Lsb0) byte and bit ordering. *

              * - * @param src the short array to convert - * @param srcPos the position in {@code src}, in short unit, from where to - * start the conversion - * @param dstInit initial value of the destination int - * @param dstPos the position of the lsb, in bits, in the result int - * @param nShorts the number of shorts to convert - * @return an int containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 32} + * @param src the long to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dst the destination array + * @param dstPos the position in {@code dst} where to copy the result + * @param nBools the number of booleans to copy to {@code dst}, must be smaller + * or equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws NullPointerException if {@code dst} is {@code null} + * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 64} * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nShorts > src.length} + * {@code dstPos + nBools > dst.length} */ - public static int shortArrayToInt(final short[] src, final int srcPos, final int dstInit, final int dstPos, - final int nShorts) { - if (src.length == 0 && srcPos == 0 || 0 == nShorts) { - return dstInit; + public static boolean[] longToBinary(final long src, final int srcPos, final boolean[] dst, final int dstPos, + final int nBools) { + if (0 == nBools) { + return dst; } - if ((nShorts - 1) * 16 + dstPos >= 32) { - throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 32"); + if (nBools - 1 + srcPos >= 64) { + throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 64"); } - int out = dstInit; - for (int i = 0; i < nShorts; i++) { - final int shift = i * 16 + dstPos; - final int bits = (0xffff & src[i + srcPos]) << shift; - final int mask = 0xffff << shift; - out = (out & ~mask) | bits; + for (int i = 0; i < nBools; i++) { + final int shift = i + srcPos; + dst[dstPos + i] = (0x1 & (src >> shift)) != 0; } - return out; + return dst; } /** *

              - * Converts an array of byte into a long using the default (little endian, Lsb0) + * Converts a long into an array of byte using the default (little endian, Lsb0) * byte and bit ordering. *

              * - * @param src the byte array to convert - * @param srcPos the position in {@code src}, in byte unit, from where to start - * the conversion - * @param dstInit initial value of the destination long - * @param dstPos the position of the lsb, in bits, in the result long - * @param nBytes the number of bytes to convert - * @return a long containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 64} + * @param src the long to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dst the destination array + * @param dstPos the position in {@code dst} where to copy the result + * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or + * equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws NullPointerException if {@code dst} is {@code null} + * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 64} * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBytes > src.length} + * {@code dstPos + nBytes > dst.length} */ - public static long byteArrayToLong(final byte[] src, final int srcPos, final long dstInit, final int dstPos, + public static byte[] longToByteArray(final long src, final int srcPos, final byte[] dst, final int dstPos, final int nBytes) { - if (src.length == 0 && srcPos == 0 || 0 == nBytes) { - return dstInit; + if (0 == nBytes) { + return dst; } - if ((nBytes - 1) * 8 + dstPos >= 64) { - throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 64"); + if ((nBytes - 1) * 8 + srcPos >= 64) { + throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 64"); } - long out = dstInit; for (int i = 0; i < nBytes; i++) { - final int shift = i * 8 + dstPos; - final long bits = (0xffL & src[i + srcPos]) << shift; - final long mask = 0xffL << shift; - out = (out & ~mask) | bits; + final int shift = i * 8 + srcPos; + dst[dstPos + i] = (byte) (0xff & (src >> shift)); } - return out; + return dst; } /** *

              - * Converts an array of byte into an int using the default (little endian, Lsb0) + * Converts a long into an array of Char using the default (little endian, Lsb0) * byte and bit ordering. *

              * - * @param src the byte array to convert - * @param srcPos the position in {@code src}, in byte unit, from where to start - * the conversion - * @param dstInit initial value of the destination int - * @param dstPos the position of the lsb, in bits, in the result int - * @param nBytes the number of bytes to convert - * @return an int containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 32} - * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBytes > src.length} + * @param src the long to convert + * @param srcPos the position in {@code src}, in bits, from where to start the + * conversion + * @param dstInit the initial value for the result String + * @param dstPos the position in {@code dst} where to copy the result + * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or + * equal to the width of the input (from srcPos to msb) + * @return {@code dst} + * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 64} + * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos} */ - public static int byteArrayToInt(final byte[] src, final int srcPos, final int dstInit, final int dstPos, - final int nBytes) { - if (src.length == 0 && srcPos == 0 || 0 == nBytes) { + public static String longToHex(final long src, final int srcPos, final String dstInit, final int dstPos, + final int nHexs) { + if (0 == nHexs) { return dstInit; } - if ((nBytes - 1) * 8 + dstPos >= 32) { - throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 32"); + if ((nHexs - 1) * 4 + srcPos >= 64) { + throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 64"); } - int out = dstInit; - for (int i = 0; i < nBytes; i++) { - final int shift = i * 8 + dstPos; - final int bits = (0xff & src[i + srcPos]) << shift; - final int mask = 0xff << shift; - out = (out & ~mask) | bits; + final StringBuilder sb = new StringBuilder(dstInit); + int append = sb.length(); + for (int i = 0; i < nHexs; i++) { + final int shift = i * 4 + srcPos; + final int bits = (int) (0xF & (src >> shift)); + if (dstPos + i == append) { + ++append; + sb.append(intToHexDigit(bits)); + } else { + sb.setCharAt(dstPos + i, intToHexDigit(bits)); + } } - return out; - } - - /** - *

              - * Converts an array of byte into a short using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the byte array to convert - * @param srcPos the position in {@code src}, in byte unit, from where to start - * the conversion - * @param dstInit initial value of the destination short - * @param dstPos the position of the lsb, in bits, in the result short - * @param nBytes the number of bytes to convert - * @return a short containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code (nBytes-1)*8+dstPos >= 16} - * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBytes > src.length} - */ - public static short byteArrayToShort(final byte[] src, final int srcPos, final short dstInit, final int dstPos, - final int nBytes) { - if (src.length == 0 && srcPos == 0 || 0 == nBytes) { - return dstInit; - } - if ((nBytes - 1) * 8 + dstPos >= 16) { - throw new IllegalArgumentException("(nBytes-1)*8+dstPos is greater or equal to than 16"); - } - short out = dstInit; - for (int i = 0; i < nBytes; i++) { - final int shift = i * 8 + dstPos; - final int bits = (0xff & src[i + srcPos]) << shift; - final int mask = 0xff << shift; - out = (short) ((out & ~mask) | bits); - } - return out; - } - - /** - *

              - * Converts an array of Char into a long using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the hex string to convert - * @param srcPos the position in {@code src}, in Char unit, from where to start - * the conversion - * @param dstInit initial value of the destination long - * @param dstPos the position of the lsb, in bits, in the result long - * @param nHex the number of Chars to convert - * @return a long containing the selected bits - * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 64} - */ - public static long hexToLong(final String src, final int srcPos, final long dstInit, final int dstPos, - final int nHex) { - if (0 == nHex) { - return dstInit; - } - if ((nHex - 1) * 4 + dstPos >= 64) { - throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 64"); - } - long out = dstInit; - for (int i = 0; i < nHex; i++) { - final int shift = i * 4 + dstPos; - final long bits = (0xfL & hexDigitToInt(src.charAt(i + srcPos))) << shift; - final long mask = 0xfL << shift; - out = (out & ~mask) | bits; - } - return out; - } - - /** - *

              - * Converts an array of Char into an int using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the hex string to convert - * @param srcPos the position in {@code src}, in Char unit, from where to start - * the conversion - * @param dstInit initial value of the destination int - * @param dstPos the position of the lsb, in bits, in the result int - * @param nHex the number of Chars to convert - * @return an int containing the selected bits - * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 32} - */ - public static int hexToInt(final String src, final int srcPos, final int dstInit, final int dstPos, - final int nHex) { - if (0 == nHex) { - return dstInit; - } - if ((nHex - 1) * 4 + dstPos >= 32) { - throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 32"); - } - int out = dstInit; - for (int i = 0; i < nHex; i++) { - final int shift = i * 4 + dstPos; - final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; - final int mask = 0xf << shift; - out = (out & ~mask) | bits; - } - return out; - } - - /** - *

              - * Converts an array of Char into a short using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the hex string to convert - * @param srcPos the position in {@code src}, in Char unit, from where to start - * the conversion - * @param dstInit initial value of the destination short - * @param dstPos the position of the lsb, in bits, in the result short - * @param nHex the number of Chars to convert - * @return a short containing the selected bits - * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 16} - */ - public static short hexToShort(final String src, final int srcPos, final short dstInit, final int dstPos, - final int nHex) { - if (0 == nHex) { - return dstInit; - } - if ((nHex - 1) * 4 + dstPos >= 16) { - throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 16"); - } - short out = dstInit; - for (int i = 0; i < nHex; i++) { - final int shift = i * 4 + dstPos; - final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; - final int mask = 0xf << shift; - out = (short) ((out & ~mask) | bits); - } - return out; - } - - /** - *

              - * Converts an array of Char into a byte using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the hex string to convert - * @param srcPos the position in {@code src}, in Char unit, from where to start - * the conversion - * @param dstInit initial value of the destination byte - * @param dstPos the position of the lsb, in bits, in the result byte - * @param nHex the number of Chars to convert - * @return a byte containing the selected bits - * @throws IllegalArgumentException if {@code (nHexs-1)*4+dstPos >= 8} - */ - public static byte hexToByte(final String src, final int srcPos, final byte dstInit, final int dstPos, - final int nHex) { - if (0 == nHex) { - return dstInit; - } - if ((nHex - 1) * 4 + dstPos >= 8) { - throw new IllegalArgumentException("(nHexs-1)*4+dstPos is greater or equal to than 8"); - } - byte out = dstInit; - for (int i = 0; i < nHex; i++) { - final int shift = i * 4 + dstPos; - final int bits = (0xf & hexDigitToInt(src.charAt(i + srcPos))) << shift; - final int mask = 0xf << shift; - out = (byte) ((out & ~mask) | bits); - } - return out; - } - - /** - *

              - * Converts binary (represented as boolean array) into a long using the default - * (little endian, Lsb0) byte and bit ordering. - *

              - * - * @param src the binary to convert - * @param srcPos the position in {@code src}, in boolean unit, from where to - * start the conversion - * @param dstInit initial value of the destination long - * @param dstPos the position of the lsb, in bits, in the result long - * @param nBools the number of booleans to convert - * @return a long containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 64} - * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBools > src.length} - */ - public static long binaryToLong(final boolean[] src, final int srcPos, final long dstInit, final int dstPos, - final int nBools) { - if (src.length == 0 && srcPos == 0 || 0 == nBools) { - return dstInit; - } - if (nBools - 1 + dstPos >= 64) { - throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 64"); - } - long out = dstInit; - for (int i = 0; i < nBools; i++) { - final int shift = i + dstPos; - final long bits = (src[i + srcPos] ? 1L : 0) << shift; - final long mask = 0x1L << shift; - out = (out & ~mask) | bits; - } - return out; - } - - /** - *

              - * Converts binary (represented as boolean array) into an int using the default - * (little endian, Lsb0) byte and bit ordering. - *

              - * - * @param src the binary to convert - * @param srcPos the position in {@code src}, in boolean unit, from where to - * start the conversion - * @param dstInit initial value of the destination int - * @param dstPos the position of the lsb, in bits, in the result int - * @param nBools the number of booleans to convert - * @return an int containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 32} - * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBools > src.length} - */ - public static int binaryToInt(final boolean[] src, final int srcPos, final int dstInit, final int dstPos, - final int nBools) { - if (src.length == 0 && srcPos == 0 || 0 == nBools) { - return dstInit; - } - if (nBools - 1 + dstPos >= 32) { - throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 32"); - } - int out = dstInit; - for (int i = 0; i < nBools; i++) { - final int shift = i + dstPos; - final int bits = (src[i + srcPos] ? 1 : 0) << shift; - final int mask = 0x1 << shift; - out = (out & ~mask) | bits; - } - return out; - } - - /** - *

              - * Converts binary (represented as boolean array) into a short using the default - * (little endian, Lsb0) byte and bit ordering. - *

              - * - * @param src the binary to convert - * @param srcPos the position in {@code src}, in boolean unit, from where to - * start the conversion - * @param dstInit initial value of the destination short - * @param dstPos the position of the lsb, in bits, in the result short - * @param nBools the number of booleans to convert - * @return a short containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 16} - * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBools > src.length} - */ - public static short binaryToShort(final boolean[] src, final int srcPos, final short dstInit, final int dstPos, - final int nBools) { - if (src.length == 0 && srcPos == 0 || 0 == nBools) { - return dstInit; - } - if (nBools - 1 + dstPos >= 16) { - throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 16"); - } - short out = dstInit; - for (int i = 0; i < nBools; i++) { - final int shift = i + dstPos; - final int bits = (src[i + srcPos] ? 1 : 0) << shift; - final int mask = 0x1 << shift; - out = (short) ((out & ~mask) | bits); - } - return out; - } - - /** - *

              - * Converts binary (represented as boolean array) into a byte using the default - * (little endian, Lsb0) byte and bit ordering. - *

              - * - * @param src the binary to convert - * @param srcPos the position in {@code src}, in boolean unit, from where to - * start the conversion - * @param dstInit initial value of the destination byte - * @param dstPos the position of the lsb, in bits, in the result byte - * @param nBools the number of booleans to convert - * @return a byte containing the selected bits - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+dstPos >= 8} - * @throws ArrayIndexOutOfBoundsException if - * {@code srcPos + nBools > src.length} - */ - public static byte binaryToByte(final boolean[] src, final int srcPos, final byte dstInit, final int dstPos, - final int nBools) { - if (src.length == 0 && srcPos == 0 || 0 == nBools) { - return dstInit; - } - if (nBools - 1 + dstPos >= 8) { - throw new IllegalArgumentException("nBools-1+dstPos is greater or equal to than 8"); - } - byte out = dstInit; - for (int i = 0; i < nBools; i++) { - final int shift = i + dstPos; - final int bits = (src[i + srcPos] ? 1 : 0) << shift; - final int mask = 0x1 << shift; - out = (byte) ((out & ~mask) | bits); - } - return out; + return sb.toString(); } /** @@ -1126,102 +1398,107 @@ public class Conversion { /** *

              - * Converts an int into an array of short using the default (little endian, + * Converts an array of short into an int using the default (little endian, * Lsb0) byte and bit ordering. *

              * - * @param src the int to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dst the destination array - * @param dstPos the position in {@code dst} where to copy the result - * @param nShorts the number of shorts to copy to {@code dst}, must be smaller - * or equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code (nShorts-1)*16+srcPos >= 32} + * @param src the short array to convert + * @param srcPos the position in {@code src}, in short unit, from where to + * start the conversion + * @param dstInit initial value of the destination int + * @param dstPos the position of the lsb, in bits, in the result int + * @param nShorts the number of shorts to convert + * @return an int containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 32} * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nShorts > dst.length} + * {@code srcPos + nShorts > src.length} */ - public static short[] intToShortArray(final int src, final int srcPos, final short[] dst, final int dstPos, + public static int shortArrayToInt(final short[] src, final int srcPos, final int dstInit, final int dstPos, final int nShorts) { - if (0 == nShorts) { - return dst; + if (src.length == 0 && srcPos == 0 || 0 == nShorts) { + return dstInit; } - if ((nShorts - 1) * 16 + srcPos >= 32) { - throw new IllegalArgumentException("(nShorts-1)*16+srcPos is greater or equal to than 32"); + if ((nShorts - 1) * 16 + dstPos >= 32) { + throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 32"); } + int out = dstInit; for (int i = 0; i < nShorts; i++) { - final int shift = i * 16 + srcPos; - dst[dstPos + i] = (short) (0xffff & (src >> shift)); + final int shift = i * 16 + dstPos; + final int bits = (0xffff & src[i + srcPos]) << shift; + final int mask = 0xffff << shift; + out = (out & ~mask) | bits; } - return dst; + return out; } /** *

              - * Converts a long into an array of byte using the default (little endian, Lsb0) - * byte and bit ordering. + * Converts an array of short into a long using the default (little endian, + * Lsb0) byte and bit ordering. *

              * - * @param src the long to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dst the destination array - * @param dstPos the position in {@code dst} where to copy the result - * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or - * equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 64} + * @param src the short array to convert + * @param srcPos the position in {@code src}, in short unit, from where to + * start the conversion + * @param dstInit initial value of the destination long + * @param dstPos the position of the lsb, in bits, in the result long + * @param nShorts the number of shorts to convert + * @return a long containing the selected bits + * @throws NullPointerException if {@code src} is {@code null} + * @throws IllegalArgumentException if {@code (nShorts-1)*16+dstPos >= 64} * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nBytes > dst.length} + * {@code srcPos + nShorts > src.length} */ - public static byte[] longToByteArray(final long src, final int srcPos, final byte[] dst, final int dstPos, - final int nBytes) { - if (0 == nBytes) { - return dst; + public static long shortArrayToLong(final short[] src, final int srcPos, final long dstInit, final int dstPos, + final int nShorts) { + if (src.length == 0 && srcPos == 0 || 0 == nShorts) { + return dstInit; } - if ((nBytes - 1) * 8 + srcPos >= 64) { - throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 64"); + if ((nShorts - 1) * 16 + dstPos >= 64) { + throw new IllegalArgumentException("(nShorts-1)*16+dstPos is greater or equal to than 64"); } - for (int i = 0; i < nBytes; i++) { - final int shift = i * 8 + srcPos; - dst[dstPos + i] = (byte) (0xff & (src >> shift)); + long out = dstInit; + for (int i = 0; i < nShorts; i++) { + final int shift = i * 16 + dstPos; + final long bits = (0xffffL & src[i + srcPos]) << shift; + final long mask = 0xffffL << shift; + out = (out & ~mask) | bits; } - return dst; + return out; } /** *

              - * Converts an int into an array of byte using the default (little endian, Lsb0) - * byte and bit ordering. + * Converts a short into an array of boolean using the default (little endian, + * Lsb0) byte and bit ordering. *

              * - * @param src the int to convert + * @param src the short to convert * @param srcPos the position in {@code src}, in bits, from where to start the * conversion * @param dst the destination array * @param dstPos the position in {@code dst} where to copy the result - * @param nBytes the number of bytes to copy to {@code dst}, must be smaller or - * equal to the width of the input (from srcPos to msb) + * @param nBools the number of booleans to copy to {@code dst}, must be smaller + * or equal to the width of the input (from srcPos to msb) * @return {@code dst} * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code (nBytes-1)*8+srcPos >= 32} + * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 16} * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nBytes > dst.length} + * {@code dstPos + nBools > dst.length} */ - public static byte[] intToByteArray(final int src, final int srcPos, final byte[] dst, final int dstPos, - final int nBytes) { - if (0 == nBytes) { + public static boolean[] shortToBinary(final short src, final int srcPos, final boolean[] dst, final int dstPos, + final int nBools) { + if (0 == nBools) { return dst; } - if ((nBytes - 1) * 8 + srcPos >= 32) { - throw new IllegalArgumentException("(nBytes-1)*8+srcPos is greater or equal to than 32"); + if (nBools - 1 + srcPos >= 16) { + throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 16"); } - for (int i = 0; i < nBytes; i++) { - final int shift = i * 8 + srcPos; - dst[dstPos + i] = (byte) (0xff & (src >> shift)); + assert (nBools - 1) < 16 - srcPos; + for (int i = 0; i < nBools; i++) { + final int shift = i + srcPos; + dst[dstPos + i] = (0x1 & (src >> shift)) != 0; } return dst; } @@ -1260,86 +1537,6 @@ public class Conversion { return dst; } - /** - *

              - * Converts a long into an array of Char using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the long to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dstInit the initial value for the result String - * @param dstPos the position in {@code dst} where to copy the result - * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or - * equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 64} - * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos} - */ - public static String longToHex(final long src, final int srcPos, final String dstInit, final int dstPos, - final int nHexs) { - if (0 == nHexs) { - return dstInit; - } - if ((nHexs - 1) * 4 + srcPos >= 64) { - throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 64"); - } - final StringBuilder sb = new StringBuilder(dstInit); - int append = sb.length(); - for (int i = 0; i < nHexs; i++) { - final int shift = i * 4 + srcPos; - final int bits = (int) (0xF & (src >> shift)); - if (dstPos + i == append) { - ++append; - sb.append(intToHexDigit(bits)); - } else { - sb.setCharAt(dstPos + i, intToHexDigit(bits)); - } - } - return sb.toString(); - } - - /** - *

              - * Converts an int into an array of Char using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the int to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dstInit the initial value for the result String - * @param dstPos the position in {@code dst} where to copy the result - * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or - * equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 32} - * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos} - */ - public static String intToHex(final int src, final int srcPos, final String dstInit, final int dstPos, - final int nHexs) { - if (0 == nHexs) { - return dstInit; - } - if ((nHexs - 1) * 4 + srcPos >= 32) { - throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 32"); - } - final StringBuilder sb = new StringBuilder(dstInit); - int append = sb.length(); - for (int i = 0; i < nHexs; i++) { - final int shift = i * 4 + srcPos; - final int bits = 0xF & (src >> shift); - if (dstPos + i == append) { - ++append; - sb.append(intToHexDigit(bits)); - } else { - sb.setCharAt(dstPos + i, intToHexDigit(bits)); - } - } - return sb.toString(); - } - /** *

              * Converts a short into an array of Char using the default (little endian, @@ -1380,183 +1577,6 @@ public class Conversion { return sb.toString(); } - /** - *

              - * Converts a byte into an array of Char using the default (little endian, Lsb0) - * byte and bit ordering. - *

              - * - * @param src the byte to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dstInit the initial value for the result String - * @param dstPos the position in {@code dst} where to copy the result - * @param nHexs the number of Chars to copy to {@code dst}, must be smaller or - * equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws IllegalArgumentException if {@code (nHexs-1)*4+srcPos >= 8} - * @throws StringIndexOutOfBoundsException if {@code dst.init.length() < dstPos} - */ - public static String byteToHex(final byte src, final int srcPos, final String dstInit, final int dstPos, - final int nHexs) { - if (0 == nHexs) { - return dstInit; - } - if ((nHexs - 1) * 4 + srcPos >= 8) { - throw new IllegalArgumentException("(nHexs-1)*4+srcPos is greater or equal to than 8"); - } - final StringBuilder sb = new StringBuilder(dstInit); - int append = sb.length(); - for (int i = 0; i < nHexs; i++) { - final int shift = i * 4 + srcPos; - final int bits = 0xF & (src >> shift); - if (dstPos + i == append) { - ++append; - sb.append(intToHexDigit(bits)); - } else { - sb.setCharAt(dstPos + i, intToHexDigit(bits)); - } - } - return sb.toString(); - } - - /** - *

              - * Converts a long into an array of boolean using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the long to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dst the destination array - * @param dstPos the position in {@code dst} where to copy the result - * @param nBools the number of booleans to copy to {@code dst}, must be smaller - * or equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 64} - * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nBools > dst.length} - */ - public static boolean[] longToBinary(final long src, final int srcPos, final boolean[] dst, final int dstPos, - final int nBools) { - if (0 == nBools) { - return dst; - } - if (nBools - 1 + srcPos >= 64) { - throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 64"); - } - for (int i = 0; i < nBools; i++) { - final int shift = i + srcPos; - dst[dstPos + i] = (0x1 & (src >> shift)) != 0; - } - return dst; - } - - /** - *

              - * Converts an int into an array of boolean using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the int to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dst the destination array - * @param dstPos the position in {@code dst} where to copy the result - * @param nBools the number of booleans to copy to {@code dst}, must be smaller - * or equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 32} - * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nBools > dst.length} - */ - public static boolean[] intToBinary(final int src, final int srcPos, final boolean[] dst, final int dstPos, - final int nBools) { - if (0 == nBools) { - return dst; - } - if (nBools - 1 + srcPos >= 32) { - throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 32"); - } - for (int i = 0; i < nBools; i++) { - final int shift = i + srcPos; - dst[dstPos + i] = (0x1 & (src >> shift)) != 0; - } - return dst; - } - - /** - *

              - * Converts a short into an array of boolean using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the short to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dst the destination array - * @param dstPos the position in {@code dst} where to copy the result - * @param nBools the number of booleans to copy to {@code dst}, must be smaller - * or equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 16} - * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nBools > dst.length} - */ - public static boolean[] shortToBinary(final short src, final int srcPos, final boolean[] dst, final int dstPos, - final int nBools) { - if (0 == nBools) { - return dst; - } - if (nBools - 1 + srcPos >= 16) { - throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 16"); - } - assert (nBools - 1) < 16 - srcPos; - for (int i = 0; i < nBools; i++) { - final int shift = i + srcPos; - dst[dstPos + i] = (0x1 & (src >> shift)) != 0; - } - return dst; - } - - /** - *

              - * Converts a byte into an array of boolean using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the byte to convert - * @param srcPos the position in {@code src}, in bits, from where to start the - * conversion - * @param dst the destination array - * @param dstPos the position in {@code dst} where to copy the result - * @param nBools the number of booleans to copy to {@code dst}, must be smaller - * or equal to the width of the input (from srcPos to msb) - * @return {@code dst} - * @throws NullPointerException if {@code dst} is {@code null} - * @throws IllegalArgumentException if {@code nBools-1+srcPos >= 8} - * @throws ArrayIndexOutOfBoundsException if - * {@code dstPos + nBools > dst.length} - */ - public static boolean[] byteToBinary(final byte src, final int srcPos, final boolean[] dst, final int dstPos, - final int nBools) { - if (0 == nBools) { - return dst; - } - if (nBools - 1 + srcPos >= 8) { - throw new IllegalArgumentException("nBools-1+srcPos is greater or equal to than 8"); - } - for (int i = 0; i < nBools; i++) { - final int shift = i + srcPos; - dst[dstPos + i] = (0x1 & (src >> shift)) != 0; - } - return dst; - } - /** *

              * Converts UUID into an array of byte using the default (little endian, Lsb0) @@ -1574,7 +1594,8 @@ public class Conversion { * @throws ArrayIndexOutOfBoundsException if * {@code dstPos + nBytes > dst.length} */ - public static byte[] uuidToByteArray(final EaglercraftUUID src, final byte[] dst, final int dstPos, final int nBytes) { + public static byte[] uuidToByteArray(final EaglercraftUUID src, final byte[] dst, final int dstPos, + final int nBytes) { if (0 == nBytes) { return dst; } @@ -1587,24 +1608,4 @@ public class Conversion { } return dst; } - - /** - *

              - * Converts bytes from an array into a UUID using the default (little endian, - * Lsb0) byte and bit ordering. - *

              - * - * @param src the byte array to convert - * @param srcPos the position in {@code src} where to copy the result from - * @return a UUID - * @throws NullPointerException if {@code src} is {@code null} - * @throws IllegalArgumentException if array does not contain at least 16 bytes - * beginning with {@code srcPos} - */ - public static EaglercraftUUID byteArrayToUuid(final byte[] src, final int srcPos) { - if (src.length - srcPos < 16) { - throw new IllegalArgumentException("Need at least 16 bytes for UUID"); - } - return new EaglercraftUUID(byteArrayToLong(src, srcPos, 0, 0, 8), byteArrayToLong(src, srcPos + 8, 0, 0, 8)); - } } diff --git a/src/main/java/org/apache/commons/lang3/Functions.java b/src/main/java/org/apache/commons/lang3/Functions.java index 97a70e82..fc395cc7 100644 --- a/src/main/java/org/apache/commons/lang3/Functions.java +++ b/src/main/java/org/apache/commons/lang3/Functions.java @@ -62,7 +62,7 @@ import org.apache.commons.lang3.function.FailableBooleanSupplier; * *
                * {@code
              - *   Functions.accept((m) -> m.invoke(o,args));
              + * Functions.accept((m) -> m.invoke(o, args));
                * }
                * 
              * diff --git a/src/main/java/org/apache/commons/lang3/JavaVersion.java b/src/main/java/org/apache/commons/lang3/JavaVersion.java index 39a16100..f7b4cf07 100644 --- a/src/main/java/org/apache/commons/lang3/JavaVersion.java +++ b/src/main/java/org/apache/commons/lang3/JavaVersion.java @@ -152,79 +152,6 @@ public enum JavaVersion { */ JAVA_RECENT(maxVersion(), Float.toString(maxVersion())); - /** - * The float value. - */ - private final float value; - - /** - * The standard name. - */ - private final String name; - - /** - * Constructor. - * - * @param value the float value - * @param name the standard name, not null - */ - JavaVersion(final float value, final String name) { - this.value = value; - this.name = name; - } - - // ----------------------------------------------------------------------- - /** - *

              - * Whether this version of Java is at least the version of Java passed in. - *

              - * - *

              - * For example:
              - * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)} - *

              - * - * @param requiredVersion the version to check against, not null - * @return true if this version is equal to or greater than the specified - * version - */ - public boolean atLeast(final JavaVersion requiredVersion) { - return this.value >= requiredVersion.value; - } - - // ----------------------------------------------------------------------- - /** - *

              - * Whether this version of Java is at most the version of Java passed in. - *

              - * - *

              - * For example:
              - * {@code myVersion.atMost(JavaVersion.JAVA_1_4)} - *

              - * - * @param requiredVersion the version to check against, not null - * @return true if this version is equal to or greater than the specified - * version - * @since 3.9 - */ - public boolean atMost(final JavaVersion requiredVersion) { - return this.value <= requiredVersion.value; - } - - /** - * Transforms the given string with a Java version number to the corresponding - * constant of this enumeration class. This method is used internally. - * - * @param nom the Java version as string - * @return the corresponding enumeration constant or null if the version - * is unknown - */ - // helper for static importing - static JavaVersion getJavaVersion(final String nom) { - return get(nom); - } - /** * Transforms the given string with a Java version number to the corresponding * constant of this enumeration class. This method is used internally. @@ -289,21 +216,17 @@ public enum JavaVersion { } } - // ----------------------------------------------------------------------- /** - *

              - * The string value is overridden to return the standard name. - *

              + * Transforms the given string with a Java version number to the corresponding + * constant of this enumeration class. This method is used internally. * - *

              - * For example, {@code "1.5"}. - *

              - * - * @return the name, not null + * @param nom the Java version as string + * @return the corresponding enumeration constant or null if the version + * is unknown */ - @Override - public String toString() { - return name; + // helper for static importing + static JavaVersion getJavaVersion(final String nom) { + return get(nom); } /** @@ -340,4 +263,81 @@ public enum JavaVersion { } return defaultReturnValue; } + + /** + * The float value. + */ + private final float value; + + /** + * The standard name. + */ + private final String name; + + /** + * Constructor. + * + * @param value the float value + * @param name the standard name, not null + */ + JavaVersion(final float value, final String name) { + this.value = value; + this.name = name; + } + + // ----------------------------------------------------------------------- + /** + *

              + * Whether this version of Java is at least the version of Java passed in. + *

              + * + *

              + * For example:
              + * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)} + *

              + * + * @param requiredVersion the version to check against, not null + * @return true if this version is equal to or greater than the specified + * version + */ + public boolean atLeast(final JavaVersion requiredVersion) { + return this.value >= requiredVersion.value; + } + + // ----------------------------------------------------------------------- + /** + *

              + * Whether this version of Java is at most the version of Java passed in. + *

              + * + *

              + * For example:
              + * {@code myVersion.atMost(JavaVersion.JAVA_1_4)} + *

              + * + * @param requiredVersion the version to check against, not null + * @return true if this version is equal to or greater than the specified + * version + * @since 3.9 + */ + public boolean atMost(final JavaVersion requiredVersion) { + return this.value <= requiredVersion.value; + } + + // ----------------------------------------------------------------------- + /** + *

              + * The string value is overridden to return the standard name. + *

              + * + *

              + * For example, {@code "1.5"}. + *

              + * + * @return the name, not null + */ + @Override + public String toString() { + return name; + } } diff --git a/src/main/java/org/apache/commons/lang3/NotImplementedException.java b/src/main/java/org/apache/commons/lang3/NotImplementedException.java index 58c82f6d..ec4154e5 100644 --- a/src/main/java/org/apache/commons/lang3/NotImplementedException.java +++ b/src/main/java/org/apache/commons/lang3/NotImplementedException.java @@ -72,11 +72,14 @@ public class NotImplementedException extends UnsupportedOperationException { /** * Constructs a NotImplementedException. * - * @param cause cause of the exception + * @param message description of the exception + * @param code code indicating a resource for more information regarding the + * lack of implementation * @since 3.2 */ - public NotImplementedException(final Throwable cause) { - this(cause, null); + public NotImplementedException(final String message, final String code) { + super(message); + this.code = code; } /** @@ -94,15 +97,26 @@ public class NotImplementedException extends UnsupportedOperationException { * Constructs a NotImplementedException. * * @param message description of the exception + * @param cause cause of the exception * @param code code indicating a resource for more information regarding the * lack of implementation * @since 3.2 */ - public NotImplementedException(final String message, final String code) { - super(message); + public NotImplementedException(final String message, final Throwable cause, final String code) { + super(message, cause); this.code = code; } + /** + * Constructs a NotImplementedException. + * + * @param cause cause of the exception + * @since 3.2 + */ + public NotImplementedException(final Throwable cause) { + this(cause, null); + } + /** * Constructs a NotImplementedException. * @@ -116,20 +130,6 @@ public class NotImplementedException extends UnsupportedOperationException { this.code = code; } - /** - * Constructs a NotImplementedException. - * - * @param message description of the exception - * @param cause cause of the exception - * @param code code indicating a resource for more information regarding the - * lack of implementation - * @since 3.2 - */ - public NotImplementedException(final String message, final Throwable cause, final String code) { - super(message, cause); - this.code = code; - } - /** * Obtain the not implemented code. This is an unformatted piece of text * intended to point to further information regarding the lack of diff --git a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java index 4baad6d4..9959d71c 100644 --- a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java +++ b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java @@ -24,8 +24,8 @@ import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; *

              * *

              - * Caveat: Instances of {@link EaglercraftRandom}, upon which the implementation of this - * class relies, are not cryptographically secure. + * Caveat: Instances of {@link EaglercraftRandom}, upon which the + * implementation of this class relies, are not cryptographically secure. *

              * *

              @@ -68,21 +68,6 @@ public class RandomStringUtils { */ private static final EaglercraftRandom RANDOM = new EaglercraftRandom(); - /** - *

              - * {@code RandomStringUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * {@code RandomStringUtils.random(5);}. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public RandomStringUtils() { - } - // Random // ----------------------------------------------------------------------- /** @@ -101,240 +86,6 @@ public class RandomStringUtils { return random(count, false, false); } - /** - *

              - * Creates a random string whose length is the number of characters specified. - *

              - * - *

              - * Characters will be chosen from the set of characters whose ASCII value is - * between {@code 32} and {@code 126} (inclusive). - *

              - * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAscii(final int count) { - return random(count, 32, 127, false, false); - } - - /** - *

              - * Creates a random string whose length is between the inclusive minimum and the - * exclusive maximum. - *

              - * - *

              - * Characters will be chosen from the set of characters whose ASCII value is - * between {@code 32} and {@code 126} (inclusive). - *

              - * - * @param minLengthInclusive the inclusive minimum length of the string to - * generate - * @param maxLengthExclusive the exclusive maximum length of the string to - * generate - * @return the random string - * @since 3.5 - */ - public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) { - return randomAscii(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); - } - - /** - *

              - * Creates a random string whose length is the number of characters specified. - *

              - * - *

              - * Characters will be chosen from the set of Latin alphabetic characters (a-z, - * A-Z). - *

              - * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphabetic(final int count) { - return random(count, true, false); - } - - /** - *

              - * Creates a random string whose length is between the inclusive minimum and the - * exclusive maximum. - *

              - * - *

              - * Characters will be chosen from the set of Latin alphabetic characters (a-z, - * A-Z). - *

              - * - * @param minLengthInclusive the inclusive minimum length of the string to - * generate - * @param maxLengthExclusive the exclusive maximum length of the string to - * generate - * @return the random string - * @since 3.5 - */ - public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) { - return randomAlphabetic(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); - } - - /** - *

              - * Creates a random string whose length is the number of characters specified. - *

              - * - *

              - * Characters will be chosen from the set of Latin alphabetic characters (a-z, - * A-Z) and the digits 0-9. - *

              - * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphanumeric(final int count) { - return random(count, true, true); - } - - /** - *

              - * Creates a random string whose length is between the inclusive minimum and the - * exclusive maximum. - *

              - * - *

              - * Characters will be chosen from the set of Latin alphabetic characters (a-z, - * A-Z) and the digits 0-9. - *

              - * - * @param minLengthInclusive the inclusive minimum length of the string to - * generate - * @param maxLengthExclusive the exclusive maximum length of the string to - * generate - * @return the random string - * @since 3.5 - */ - public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) { - return randomAlphanumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); - } - - /** - *

              - * Creates a random string whose length is the number of characters specified. - *

              - * - *

              - * Characters will be chosen from the set of characters which match the POSIX - * [:graph:] regular expression character class. This class contains all visible - * ASCII characters (i.e. anything except spaces and control characters). - *

              - * - * @param count the length of random string to create - * @return the random string - * @since 3.5 - */ - public static String randomGraph(final int count) { - return random(count, 33, 126, false, false); - } - - /** - *

              - * Creates a random string whose length is between the inclusive minimum and the - * exclusive maximum. - *

              - * - *

              - * Characters will be chosen from the set of \p{Graph} characters. - *

              - * - * @param minLengthInclusive the inclusive minimum length of the string to - * generate - * @param maxLengthExclusive the exclusive maximum length of the string to - * generate - * @return the random string - * @since 3.5 - */ - public static String randomGraph(final int minLengthInclusive, final int maxLengthExclusive) { - return randomGraph(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); - } - - /** - *

              - * Creates a random string whose length is the number of characters specified. - *

              - * - *

              - * Characters will be chosen from the set of numeric characters. - *

              - * - * @param count the length of random string to create - * @return the random string - */ - public static String randomNumeric(final int count) { - return random(count, false, true); - } - - /** - *

              - * Creates a random string whose length is between the inclusive minimum and the - * exclusive maximum. - *

              - * - *

              - * Characters will be chosen from the set of \p{Digit} characters. - *

              - * - * @param minLengthInclusive the inclusive minimum length of the string to - * generate - * @param maxLengthExclusive the exclusive maximum length of the string to - * generate - * @return the random string - * @since 3.5 - */ - public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) { - return randomNumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); - } - - /** - *

              - * Creates a random string whose length is the number of characters specified. - *

              - * - *

              - * Characters will be chosen from the set of characters which match the POSIX - * [:print:] regular expression character class. This class includes all visible - * ASCII characters and spaces (i.e. anything except control characters). - *

              - * - * @param count the length of random string to create - * @return the random string - * @since 3.5 - */ - public static String randomPrint(final int count) { - return random(count, 32, 126, false, false); - } - - /** - *

              - * Creates a random string whose length is between the inclusive minimum and the - * exclusive maximum. - *

              - * - *

              - * Characters will be chosen from the set of \p{Print} characters. - *

              - * - * @param minLengthInclusive the inclusive minimum length of the string to - * generate - * @param maxLengthExclusive the exclusive maximum length of the string to - * generate - * @return the random string - * @since 3.5 - */ - public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) { - return randomPrint(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); - } - /** *

              * Creates a random string whose length is the number of characters specified. @@ -356,6 +107,28 @@ public class RandomStringUtils { return random(count, 0, 0, letters, numbers); } + /** + *

              + * Creates a random string whose length is the number of characters specified. + *

              + * + *

              + * Characters will be chosen from the set of characters specified. + *

              + * + * @param count the length of random string to create + * @param chars the character array containing the set of characters to use, may + * be null + * @return the random string + * @throws IllegalArgumentException if {@code count} < 0. + */ + public static String random(final int count, final char... chars) { + if (chars == null) { + return random(count, 0, 0, false, false, null, RANDOM); + } + return random(count, 0, chars.length, false, false, chars, RANDOM); + } + /** *

              * Creates a random string whose length is the number of characters specified. @@ -388,9 +161,9 @@ public class RandomStringUtils { * *

              * This method has exactly the same semantics as - * {@link #random(int,int,int,boolean,boolean,char[],EaglercraftRandom)}, but instead of - * using an externally supplied source of randomness, it uses the internal - * static {@link EaglercraftRandom} instance. + * {@link #random(int,int,int,boolean,boolean,char[],EaglercraftRandom)}, but + * instead of using an externally supplied source of randomness, it uses the + * internal static {@link EaglercraftRandom} instance. *

              * * @param count the length of random string to create @@ -429,10 +202,10 @@ public class RandomStringUtils { *

              * *

              - * This method accepts a user-supplied {@link EaglercraftRandom} instance to use as a - * source of randomness. By seeding a single {@link EaglercraftRandom} instance with a - * fixed seed and using it for each call, the same random sequence of strings - * can be generated repeatedly and predictably. + * This method accepts a user-supplied {@link EaglercraftRandom} instance to use + * as a source of randomness. By seeding a single {@link EaglercraftRandom} + * instance with a fixed seed and using it for each call, the same random + * sequence of strings can be generated repeatedly and predictably. *

              * * @param count the length of random string to create @@ -558,20 +331,247 @@ public class RandomStringUtils { *

              * *

              - * Characters will be chosen from the set of characters specified. + * Characters will be chosen from the set of Latin alphabetic characters (a-z, + * A-Z). *

              * * @param count the length of random string to create - * @param chars the character array containing the set of characters to use, may - * be null * @return the random string - * @throws IllegalArgumentException if {@code count} < 0. */ - public static String random(final int count, final char... chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, 0, chars.length, false, false, chars, RANDOM); + public static String randomAlphabetic(final int count) { + return random(count, true, false); + } + + /** + *

              + * Creates a random string whose length is between the inclusive minimum and the + * exclusive maximum. + *

              + * + *

              + * Characters will be chosen from the set of Latin alphabetic characters (a-z, + * A-Z). + *

              + * + * @param minLengthInclusive the inclusive minimum length of the string to + * generate + * @param maxLengthExclusive the exclusive maximum length of the string to + * generate + * @return the random string + * @since 3.5 + */ + public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) { + return randomAlphabetic(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); + } + + /** + *

              + * Creates a random string whose length is the number of characters specified. + *

              + * + *

              + * Characters will be chosen from the set of Latin alphabetic characters (a-z, + * A-Z) and the digits 0-9. + *

              + * + * @param count the length of random string to create + * @return the random string + */ + public static String randomAlphanumeric(final int count) { + return random(count, true, true); + } + + /** + *

              + * Creates a random string whose length is between the inclusive minimum and the + * exclusive maximum. + *

              + * + *

              + * Characters will be chosen from the set of Latin alphabetic characters (a-z, + * A-Z) and the digits 0-9. + *

              + * + * @param minLengthInclusive the inclusive minimum length of the string to + * generate + * @param maxLengthExclusive the exclusive maximum length of the string to + * generate + * @return the random string + * @since 3.5 + */ + public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) { + return randomAlphanumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); + } + + /** + *

              + * Creates a random string whose length is the number of characters specified. + *

              + * + *

              + * Characters will be chosen from the set of characters whose ASCII value is + * between {@code 32} and {@code 126} (inclusive). + *

              + * + * @param count the length of random string to create + * @return the random string + */ + public static String randomAscii(final int count) { + return random(count, 32, 127, false, false); + } + + /** + *

              + * Creates a random string whose length is between the inclusive minimum and the + * exclusive maximum. + *

              + * + *

              + * Characters will be chosen from the set of characters whose ASCII value is + * between {@code 32} and {@code 126} (inclusive). + *

              + * + * @param minLengthInclusive the inclusive minimum length of the string to + * generate + * @param maxLengthExclusive the exclusive maximum length of the string to + * generate + * @return the random string + * @since 3.5 + */ + public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) { + return randomAscii(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); + } + + /** + *

              + * Creates a random string whose length is the number of characters specified. + *

              + * + *

              + * Characters will be chosen from the set of characters which match the POSIX + * [:graph:] regular expression character class. This class contains all visible + * ASCII characters (i.e. anything except spaces and control characters). + *

              + * + * @param count the length of random string to create + * @return the random string + * @since 3.5 + */ + public static String randomGraph(final int count) { + return random(count, 33, 126, false, false); + } + + /** + *

              + * Creates a random string whose length is between the inclusive minimum and the + * exclusive maximum. + *

              + * + *

              + * Characters will be chosen from the set of \p{Graph} characters. + *

              + * + * @param minLengthInclusive the inclusive minimum length of the string to + * generate + * @param maxLengthExclusive the exclusive maximum length of the string to + * generate + * @return the random string + * @since 3.5 + */ + public static String randomGraph(final int minLengthInclusive, final int maxLengthExclusive) { + return randomGraph(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); + } + + /** + *

              + * Creates a random string whose length is the number of characters specified. + *

              + * + *

              + * Characters will be chosen from the set of numeric characters. + *

              + * + * @param count the length of random string to create + * @return the random string + */ + public static String randomNumeric(final int count) { + return random(count, false, true); + } + + /** + *

              + * Creates a random string whose length is between the inclusive minimum and the + * exclusive maximum. + *

              + * + *

              + * Characters will be chosen from the set of \p{Digit} characters. + *

              + * + * @param minLengthInclusive the inclusive minimum length of the string to + * generate + * @param maxLengthExclusive the exclusive maximum length of the string to + * generate + * @return the random string + * @since 3.5 + */ + public static String randomNumeric(final int minLengthInclusive, final int maxLengthExclusive) { + return randomNumeric(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); + } + + /** + *

              + * Creates a random string whose length is the number of characters specified. + *

              + * + *

              + * Characters will be chosen from the set of characters which match the POSIX + * [:print:] regular expression character class. This class includes all visible + * ASCII characters and spaces (i.e. anything except control characters). + *

              + * + * @param count the length of random string to create + * @return the random string + * @since 3.5 + */ + public static String randomPrint(final int count) { + return random(count, 32, 126, false, false); + } + + /** + *

              + * Creates a random string whose length is between the inclusive minimum and the + * exclusive maximum. + *

              + * + *

              + * Characters will be chosen from the set of \p{Print} characters. + *

              + * + * @param minLengthInclusive the inclusive minimum length of the string to + * generate + * @param maxLengthExclusive the exclusive maximum length of the string to + * generate + * @return the random string + * @since 3.5 + */ + public static String randomPrint(final int minLengthInclusive, final int maxLengthExclusive) { + return randomPrint(RandomUtils.nextInt(minLengthInclusive, maxLengthExclusive)); + } + + /** + *

              + * {@code RandomStringUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used as + * {@code RandomStringUtils.random(5);}. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              + */ + public RandomStringUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/RandomUtils.java b/src/main/java/org/apache/commons/lang3/RandomUtils.java index 00a2733a..2fafc640 100644 --- a/src/main/java/org/apache/commons/lang3/RandomUtils.java +++ b/src/main/java/org/apache/commons/lang3/RandomUtils.java @@ -20,11 +20,13 @@ import net.lax1dude.eaglercraft.v1_8.EaglercraftRandom; /** *

              - * Utility library that supplements the standard {@link EaglercraftRandom} class. + * Utility library that supplements the standard {@link EaglercraftRandom} + * class. *

              * *

              - * Caveat: Instances of {@link EaglercraftRandom} are not cryptographically secure. + * Caveat: Instances of {@link EaglercraftRandom} are not cryptographically + * secure. *

              * *

              @@ -45,21 +47,6 @@ public class RandomUtils { */ private static final EaglercraftRandom RANDOM = new EaglercraftRandom(); - /** - *

              - * {@code RandomUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * {@code RandomUtils.nextBytes(5);}. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public RandomUtils() { - } - /** *

              * Returns a random boolean value @@ -89,6 +76,91 @@ public class RandomUtils { return result; } + /** + *

              + * Returns a random double within 0 - Double.MAX_VALUE + *

              + * + * @return the random double + * @see #nextDouble(double, double) + * @since 3.5 + */ + public static double nextDouble() { + return nextDouble(0, Double.MAX_VALUE); + } + + /** + *

              + * Returns a random double within the specified range. + *

              + * + * @param startInclusive the smallest value that can be returned, must be + * non-negative + * @param endExclusive the upper bound (not included) + * @throws IllegalArgumentException if {@code startInclusive > endExclusive} or + * if {@code startInclusive} is negative + * @return the random double + */ + public static double nextDouble(final double startInclusive, final double endExclusive) { + Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value."); + Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); + + if (startInclusive == endExclusive) { + return startInclusive; + } + + return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextDouble()); + } + + /** + *

              + * Returns a random float within 0 - Float.MAX_VALUE + *

              + * + * @return the random float + * @see #nextFloat(float, float) + * @since 3.5 + */ + public static float nextFloat() { + return nextFloat(0, Float.MAX_VALUE); + } + + /** + *

              + * Returns a random float within the specified range. + *

              + * + * @param startInclusive the smallest value that can be returned, must be + * non-negative + * @param endExclusive the upper bound (not included) + * @throws IllegalArgumentException if {@code startInclusive > endExclusive} or + * if {@code startInclusive} is negative + * @return the random float + */ + public static float nextFloat(final float startInclusive, final float endExclusive) { + Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value."); + Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); + + if (startInclusive == endExclusive) { + return startInclusive; + } + + return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextFloat()); + } + + /** + *

              + * Returns a random int within 0 - Integer.MAX_VALUE + *

              + * + * @return the random integer + * @see #nextInt(int, int) + * @since 3.5 + */ + public static int nextInt() { + return nextInt(0, Integer.MAX_VALUE); + } + /** *

              * Returns a random integer within the specified range. @@ -112,42 +184,6 @@ public class RandomUtils { return startInclusive + RANDOM.nextInt(endExclusive - startInclusive); } - /** - *

              - * Returns a random int within 0 - Integer.MAX_VALUE - *

              - * - * @return the random integer - * @see #nextInt(int, int) - * @since 3.5 - */ - public static int nextInt() { - return nextInt(0, Integer.MAX_VALUE); - } - - /** - *

              - * Returns a random long within the specified range. - *

              - * - * @param startInclusive the smallest value that can be returned, must be - * non-negative - * @param endExclusive the upper bound (not included) - * @throws IllegalArgumentException if {@code startInclusive > endExclusive} or - * if {@code startInclusive} is negative - * @return the random long - */ - public static long nextLong(final long startInclusive, final long endExclusive) { - Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value."); - Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); - - if (startInclusive == endExclusive) { - return startInclusive; - } - - return startInclusive + nextLong(endExclusive - startInclusive); - } - /** *

              * Returns a random long within 0 - Long.MAX_VALUE @@ -183,7 +219,7 @@ public class RandomUtils { /** *

              - * Returns a random double within the specified range. + * Returns a random long within the specified range. *

              * * @param startInclusive the smallest value that can be returned, must be @@ -191,9 +227,9 @@ public class RandomUtils { * @param endExclusive the upper bound (not included) * @throws IllegalArgumentException if {@code startInclusive > endExclusive} or * if {@code startInclusive} is negative - * @return the random double + * @return the random long */ - public static double nextDouble(final double startInclusive, final double endExclusive) { + public static long nextLong(final long startInclusive, final long endExclusive) { Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value."); Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); @@ -201,55 +237,21 @@ public class RandomUtils { return startInclusive; } - return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextDouble()); + return startInclusive + nextLong(endExclusive - startInclusive); } /** *

              - * Returns a random double within 0 - Double.MAX_VALUE + * {@code RandomUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used as + * {@code RandomUtils.nextBytes(5);}. *

              * - * @return the random double - * @see #nextDouble(double, double) - * @since 3.5 - */ - public static double nextDouble() { - return nextDouble(0, Double.MAX_VALUE); - } - - /** *

              - * Returns a random float within the specified range. + * This constructor is public to permit tools that require a JavaBean instance + * to operate. *

              - * - * @param startInclusive the smallest value that can be returned, must be - * non-negative - * @param endExclusive the upper bound (not included) - * @throws IllegalArgumentException if {@code startInclusive > endExclusive} or - * if {@code startInclusive} is negative - * @return the random float */ - public static float nextFloat(final float startInclusive, final float endExclusive) { - Validate.isTrue(endExclusive >= startInclusive, "Start value must be smaller or equal to end value."); - Validate.isTrue(startInclusive >= 0, "Both range values must be non-negative."); - - if (startInclusive == endExclusive) { - return startInclusive; - } - - return startInclusive + ((endExclusive - startInclusive) * RANDOM.nextFloat()); - } - - /** - *

              - * Returns a random float within 0 - Float.MAX_VALUE - *

              - * - * @return the random float - * @see #nextFloat(float, float) - * @since 3.5 - */ - public static float nextFloat() { - return nextFloat(0, Float.MAX_VALUE); + public RandomUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/Range.java b/src/main/java/org/apache/commons/lang3/Range.java index 757bb3ed..5014362f 100644 --- a/src/main/java/org/apache/commons/lang3/Range.java +++ b/src/main/java/org/apache/commons/lang3/Range.java @@ -312,6 +312,42 @@ public final class Range implements Serializable { } } + /** + *

              + * Fits the given element into this range by returning the given element or, if + * out of bounds, the range minimum if below, or the range maximum if above. + *

              + * + *
              +	 * Range<Integer> range = Range.between(16, 64);
              +	 * range.fit(-9) -->  16
              +	 * range.fit(0)  -->  16
              +	 * range.fit(15) -->  16
              +	 * range.fit(16) -->  16
              +	 * range.fit(17) -->  17
              +	 * ...
              +	 * range.fit(63) -->  63
              +	 * range.fit(64) -->  64
              +	 * range.fit(99) -->  64
              +	 * 
              + * + * @param element the element to check for, not null + * @return the minimum, the element, or the maximum depending on the element's + * location relative to the range + * @since 3.10 + */ + public T fit(final T element) { + // Comparable API says throw NPE on null + Validate.notNull(element, "element"); + if (isAfter(element)) { + return minimum; + } else if (isBefore(element)) { + return maximum; + } else { + return element; + } + } + /** *

              * Gets the comparator being used to determine if objects are within the range. @@ -537,42 +573,6 @@ public final class Range implements Serializable { return comparator.compare(element, minimum) == 0; } - /** - *

              - * Fits the given element into this range by returning the given element or, if - * out of bounds, the range minimum if below, or the range maximum if above. - *

              - * - *
              -	 * Range<Integer> range = Range.between(16, 64);
              -	 * range.fit(-9) -->  16
              -	 * range.fit(0)  -->  16
              -	 * range.fit(15) -->  16
              -	 * range.fit(16) -->  16
              -	 * range.fit(17) -->  17
              -	 * ...
              -	 * range.fit(63) -->  63
              -	 * range.fit(64) -->  64
              -	 * range.fit(99) -->  64
              -	 * 
              - * - * @param element the element to check for, not null - * @return the minimum, the element, or the maximum depending on the element's - * location relative to the range - * @since 3.10 - */ - public T fit(final T element) { - // Comparable API says throw NPE on null - Validate.notNull(element, "element"); - if (isAfter(element)) { - return minimum; - } else if (isBefore(element)) { - return maximum; - } else { - return element; - } - } - /** *

              * Gets the range as a {@code String}. diff --git a/src/main/java/org/apache/commons/lang3/SerializationException.java b/src/main/java/org/apache/commons/lang3/SerializationException.java index e31e3b69..92b39b07 100644 --- a/src/main/java/org/apache/commons/lang3/SerializationException.java +++ b/src/main/java/org/apache/commons/lang3/SerializationException.java @@ -61,19 +61,6 @@ public class SerializationException extends RuntimeException { super(msg); } - /** - *

              - * Constructs a new {@code SerializationException} with specified nested - * {@code Throwable}. - *

              - * - * @param cause The {@code Exception} or {@code Error} that caused this - * exception to be thrown. - */ - public SerializationException(final Throwable cause) { - super(cause); - } - /** *

              * Constructs a new {@code SerializationException} with specified detail message @@ -88,4 +75,17 @@ public class SerializationException extends RuntimeException { super(msg, cause); } + /** + *

              + * Constructs a new {@code SerializationException} with specified nested + * {@code Throwable}. + *

              + * + * @param cause The {@code Exception} or {@code Error} that caused this + * exception to be thrown. + */ + public SerializationException(final Throwable cause) { + super(cause); + } + } diff --git a/src/main/java/org/apache/commons/lang3/Streams.java b/src/main/java/org/apache/commons/lang3/Streams.java index 47d8d0d8..c54378f6 100644 --- a/src/main/java/org/apache/commons/lang3/Streams.java +++ b/src/main/java/org/apache/commons/lang3/Streams.java @@ -71,6 +71,60 @@ import org.apache.commons.lang3.Functions.FailablePredicate; @Deprecated public class Streams { + /** + * A Collector type for arrays. + * + * @param The array type. + * @deprecated Use + * {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}. + */ + @Deprecated + public static class ArrayCollector implements Collector, O[]> { + private static final Set characteristics = Collections.emptySet(); + private final Class elementType; + + /** + * Constructs a new instance for the given element type. + * + * @param elementType The element type. + */ + public ArrayCollector(final Class elementType) { + this.elementType = elementType; + } + + @Override + public BiConsumer, O> accumulator() { + return List::add; + } + + @Override + public Set characteristics() { + return characteristics; + } + + @Override + public BinaryOperator> combiner() { + return (left, right) -> { + left.addAll(right); + return left; + }; + } + + @Override + public Function, O[]> finisher() { + return list -> { + @SuppressWarnings("unchecked") + final O[] array = (O[]) Array.newInstance(elementType, list.size()); + return list.toArray(array); + }; + } + + @Override + public Supplier> supplier() { + return ArrayList::new; + } + } + /** * A reduced, and simplified version of a {@link Stream} with failable method * signatures. @@ -94,55 +148,58 @@ public class Streams { this.stream = stream; } + /** + * Returns whether all elements of this stream match the provided predicate. May + * not evaluate the predicate on all elements if not necessary for determining + * the result. If the stream is empty then {@code true} is returned and the + * predicate is not evaluated. + * + *

              + * This is a short-circuiting terminal operation. + * + * Note This method evaluates the universal quantification of the + * predicate over the elements of the stream (for all x P(x)). If the stream is + * empty, the quantification is said to be vacuously satisfied and is + * always {@code true} (regardless of P(x)). + * + * @param predicate A non-interfering, stateless predicate to apply to elements + * of this stream + * @return {@code true} If either all elements of the stream match the provided + * predicate or the stream is empty, otherwise {@code false}. + */ + public boolean allMatch(final FailablePredicate predicate) { + assertNotTerminated(); + return stream().allMatch(Functions.asPredicate(predicate)); + } + + /** + * Returns whether any elements of this stream match the provided predicate. May + * not evaluate the predicate on all elements if not necessary for determining + * the result. If the stream is empty then {@code false} is returned and the + * predicate is not evaluated. + * + *

              + * This is a short-circuiting terminal operation. + * + * Note This method evaluates the existential quantification of the + * predicate over the elements of the stream (for some x P(x)). + * + * @param predicate A non-interfering, stateless predicate to apply to elements + * of this stream + * @return {@code true} if any elements of the stream match the provided + * predicate, otherwise {@code false} + */ + public boolean anyMatch(final FailablePredicate predicate) { + assertNotTerminated(); + return stream().anyMatch(Functions.asPredicate(predicate)); + } + protected void assertNotTerminated() { if (terminated) { throw new IllegalStateException("This stream is already terminated."); } } - protected void makeTerminated() { - assertNotTerminated(); - terminated = true; - } - - /** - * Returns a FailableStream consisting of the elements of this stream that match - * the given FailablePredicate. - * - *

              - * This is an intermediate operation. - * - * @param predicate a non-interfering, stateless predicate to apply to each - * element to determine if it should be included. - * @return the new stream - */ - public FailableStream filter(final FailablePredicate predicate) { - assertNotTerminated(); - stream = stream.filter(Functions.asPredicate(predicate)); - return this; - } - - /** - * Performs an action for each element of this stream. - * - *

              - * This is a terminal operation. - * - *

              - * The behavior of this operation is explicitly nondeterministic. For parallel - * stream pipelines, this operation does not guarantee to respect the - * encounter order of the stream, as doing so would sacrifice the benefit of - * parallelism. For any given element, the action may be performed at whatever - * time and in whatever thread the library chooses. If the action accesses - * shared state, it is responsible for providing the required synchronization. - * - * @param action a non-interfering action to perform on the elements - */ - public void forEach(final FailableConsumer action) { - makeTerminated(); - stream().forEach(Functions.asConsumer(action)); - } - /** * Performs a mutable reduction operation on the elements of this stream using a * {@code Collector}. A {@code Collector} encapsulates the functions used as @@ -273,6 +330,65 @@ public class Streams { return stream().collect(pupplier, accumulator, combiner); } + /** + * Returns a FailableStream consisting of the elements of this stream that match + * the given FailablePredicate. + * + *

              + * This is an intermediate operation. + * + * @param predicate a non-interfering, stateless predicate to apply to each + * element to determine if it should be included. + * @return the new stream + */ + public FailableStream filter(final FailablePredicate predicate) { + assertNotTerminated(); + stream = stream.filter(Functions.asPredicate(predicate)); + return this; + } + + /** + * Performs an action for each element of this stream. + * + *

              + * This is a terminal operation. + * + *

              + * The behavior of this operation is explicitly nondeterministic. For parallel + * stream pipelines, this operation does not guarantee to respect the + * encounter order of the stream, as doing so would sacrifice the benefit of + * parallelism. For any given element, the action may be performed at whatever + * time and in whatever thread the library chooses. If the action accesses + * shared state, it is responsible for providing the required synchronization. + * + * @param action a non-interfering action to perform on the elements + */ + public void forEach(final FailableConsumer action) { + makeTerminated(); + stream().forEach(Functions.asConsumer(action)); + } + + protected void makeTerminated() { + assertNotTerminated(); + terminated = true; + } + + /** + * Returns a stream consisting of the results of applying the given function to + * the elements of this stream. + * + *

              + * This is an intermediate operation. + * + * @param The element type of the new stream + * @param mapper A non-interfering, stateless function to apply to each element + * @return the new stream + */ + public FailableStream map(final FailableFunction mapper) { + assertNotTerminated(); + return new FailableStream<>(stream.map(Functions.asFunction(mapper))); + } + /** * Performs a reduction on the elements of this stream, using the provided * identity value and an associative accumulation function, and returns the @@ -333,22 +449,6 @@ public class Streams { return stream().reduce(identity, accumulator); } - /** - * Returns a stream consisting of the results of applying the given function to - * the elements of this stream. - * - *

              - * This is an intermediate operation. - * - * @param The element type of the new stream - * @param mapper A non-interfering, stateless function to apply to each element - * @return the new stream - */ - public FailableStream map(final FailableFunction mapper) { - assertNotTerminated(); - return new FailableStream<>(stream.map(Functions.asFunction(mapper))); - } - /** * Converts the FailableStream into an equivalent stream. * @@ -358,97 +458,6 @@ public class Streams { public Stream stream() { return stream; } - - /** - * Returns whether all elements of this stream match the provided predicate. May - * not evaluate the predicate on all elements if not necessary for determining - * the result. If the stream is empty then {@code true} is returned and the - * predicate is not evaluated. - * - *

              - * This is a short-circuiting terminal operation. - * - * Note This method evaluates the universal quantification of the - * predicate over the elements of the stream (for all x P(x)). If the stream is - * empty, the quantification is said to be vacuously satisfied and is - * always {@code true} (regardless of P(x)). - * - * @param predicate A non-interfering, stateless predicate to apply to elements - * of this stream - * @return {@code true} If either all elements of the stream match the provided - * predicate or the stream is empty, otherwise {@code false}. - */ - public boolean allMatch(final FailablePredicate predicate) { - assertNotTerminated(); - return stream().allMatch(Functions.asPredicate(predicate)); - } - - /** - * Returns whether any elements of this stream match the provided predicate. May - * not evaluate the predicate on all elements if not necessary for determining - * the result. If the stream is empty then {@code false} is returned and the - * predicate is not evaluated. - * - *

              - * This is a short-circuiting terminal operation. - * - * Note This method evaluates the existential quantification of the - * predicate over the elements of the stream (for some x P(x)). - * - * @param predicate A non-interfering, stateless predicate to apply to elements - * of this stream - * @return {@code true} if any elements of the stream match the provided - * predicate, otherwise {@code false} - */ - public boolean anyMatch(final FailablePredicate predicate) { - assertNotTerminated(); - return stream().anyMatch(Functions.asPredicate(predicate)); - } - } - - /** - * Converts the given {@link Stream stream} into a {@link FailableStream}. This - * is basically a simplified, reduced version of the {@link Stream} class, with - * the same underlying element stream, except that failable objects, like - * {@link FailablePredicate}, {@link FailableFunction}, or - * {@link FailableConsumer} may be applied, instead of {@link Predicate}, - * {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet - * like this: - * - *

              -	 * final List<O> list;
              -	 * final Method m;
              -	 * final Function<O, String> mapper = (o) -> {
              -	 * 	try {
              -	 * 		return (String) m.invoke(o);
              -	 * 	} catch (Throwable t) {
              -	 * 		throw Functions.rethrow(t);
              -	 * 	}
              -	 * };
              -	 * final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
              -	 * 
              - * - * as follows: - * - *
              -	 * final List<O> list;
              -	 * final Method m;
              -	 * final List<String> strList = Functions.stream(list.stream()).map((o) -> (String) m.invoke(o))
              -	 * 		.collect(Collectors.toList());
              -	 * 
              - * - * While the second version may not be quite as efficient (because it - * depends on the creation of additional, intermediate objects, of type - * FailableStream), it is much more concise, and readable, and meets the spirit - * of Lambdas better than the first version. - * - * @param The streams element type. - * @param stream The stream, which is being converted. - * @return The {@link FailableStream}, which has been created by converting the - * stream. - */ - public static FailableStream stream(final Stream stream) { - return new FailableStream<>(stream); } /** @@ -497,57 +506,48 @@ public class Streams { } /** - * A Collector type for arrays. - * - * @param The array type. - * @deprecated Use - * {@link org.apache.commons.lang3.stream.Streams.ArrayCollector}. + * Converts the given {@link Stream stream} into a {@link FailableStream}. This + * is basically a simplified, reduced version of the {@link Stream} class, with + * the same underlying element stream, except that failable objects, like + * {@link FailablePredicate}, {@link FailableFunction}, or + * {@link FailableConsumer} may be applied, instead of {@link Predicate}, + * {@link Function}, or {@link Consumer}. The idea is to rewrite a code snippet + * like this: + * + *
              +	 * final List<O> list;
              +	 * final Method m;
              +	 * final Function<O, String> mapper = (o) -> {
              +	 * 	try {
              +	 * 		return (String) m.invoke(o);
              +	 * 	} catch (Throwable t) {
              +	 * 		throw Functions.rethrow(t);
              +	 * 	}
              +	 * };
              +	 * final List<String> strList = list.stream().map(mapper).collect(Collectors.toList());
              +	 * 
              + * + * as follows: + * + *
              +	 * final List<O> list;
              +	 * final Method m;
              +	 * final List<String> strList = Functions.stream(list.stream()).map((o) -> (String) m.invoke(o))
              +	 * 		.collect(Collectors.toList());
              +	 * 
              + * + * While the second version may not be quite as efficient (because it + * depends on the creation of additional, intermediate objects, of type + * FailableStream), it is much more concise, and readable, and meets the spirit + * of Lambdas better than the first version. + * + * @param The streams element type. + * @param stream The stream, which is being converted. + * @return The {@link FailableStream}, which has been created by converting the + * stream. */ - @Deprecated - public static class ArrayCollector implements Collector, O[]> { - private static final Set characteristics = Collections.emptySet(); - private final Class elementType; - - /** - * Constructs a new instance for the given element type. - * - * @param elementType The element type. - */ - public ArrayCollector(final Class elementType) { - this.elementType = elementType; - } - - @Override - public Supplier> supplier() { - return ArrayList::new; - } - - @Override - public BiConsumer, O> accumulator() { - return List::add; - } - - @Override - public BinaryOperator> combiner() { - return (left, right) -> { - left.addAll(right); - return left; - }; - } - - @Override - public Function, O[]> finisher() { - return list -> { - @SuppressWarnings("unchecked") - final O[] array = (O[]) Array.newInstance(elementType, list.size()); - return list.toArray(array); - }; - } - - @Override - public Set characteristics() { - return characteristics; - } + public static FailableStream stream(final Stream stream) { + return new FailableStream<>(stream); } /** diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index 5acabc92..6f972bd6 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -31,10 +31,10 @@ import java.util.StringJoiner; import java.util.function.Supplier; import java.util.regex.Pattern; -import net.lax1dude.eaglercraft.v1_8.HString; - import org.apache.commons.lang3.function.ToBooleanBiFunction; +import net.lax1dude.eaglercraft.v1_8.HString; + /** *

              * Operations on {@link java.lang.String} that are {@code null} safe. diff --git a/src/main/java/org/apache/commons/lang3/SystemUtils.java b/src/main/java/org/apache/commons/lang3/SystemUtils.java index 4651c5fb..142c6fbe 100644 --- a/src/main/java/org/apache/commons/lang3/SystemUtils.java +++ b/src/main/java/org/apache/commons/lang3/SystemUtils.java @@ -16,6 +16,8 @@ */ package org.apache.commons.lang3; +import java.io.File; + /** *

              * Helpers for {@code java.lang.System}. diff --git a/src/main/java/org/apache/commons/lang3/Validate.java b/src/main/java/org/apache/commons/lang3/Validate.java index 136f9d6a..f7b39a2e 100644 --- a/src/main/java/org/apache/commons/lang3/Validate.java +++ b/src/main/java/org/apache/commons/lang3/Validate.java @@ -79,1190 +79,41 @@ public class Validate { private static final String DEFAULT_IS_INSTANCE_OF_EX_MESSAGE = "Expected type: %s, actual: %s"; /** - * Constructor. This class should not normally be instantiated. + * Validate that the specified primitive value falls between the two exclusive + * values specified; otherwise, throws an exception. + * + *

              +	 * Validate.exclusiveBetween(0.1, 2.1, 1.1);
              +	 * 
              + * + * @param start the exclusive start value + * @param end the exclusive end value + * @param value the value to validate + * @throws IllegalArgumentException if the value falls out of the boundaries + * + * @since 3.3 */ - public Validate() { + @SuppressWarnings("boxing") + public static void exclusiveBetween(final double start, final double end, final double value) { + // TODO when breaking BC, consider returning value + if (value <= start || value >= end) { + throw new IllegalArgumentException(HString.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); + } } // isTrue // --------------------------------------------------------------------------------- /** - *

              - * Validate that the argument condition is {@code true}; otherwise throwing an - * exception with the specified message. This method is useful when validating - * according to an arbitrary boolean expression, such as validating a primitive - * number or using your own custom validation expression. - *

              - * - *
              -	 * Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);
              -	 * 
              - * - *

              - * For performance reasons, the long value is passed as a separate parameter and - * appended to the exception message only in the case of an error. - *

              - * - * @param expression the boolean expression to check - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param value the value to append to the message when invalid - * @throws IllegalArgumentException if expression is {@code false} - * @see #isTrue(boolean) - * @see #isTrue(boolean, String, double) - * @see #isTrue(boolean, String, Object...) - */ - public static void isTrue(final boolean expression, final String message, final long value) { - if (!expression) { - throw new IllegalArgumentException(HString.format(message, Long.valueOf(value))); - } - } - - /** - *

              - * Validate that the argument condition is {@code true}; otherwise throwing an - * exception with the specified message. This method is useful when validating - * according to an arbitrary boolean expression, such as validating a primitive - * number or using your own custom validation expression. - *

              - * - *
              -	 * Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);
              -	 * 
              - * - *

              - * For performance reasons, the double value is passed as a separate parameter - * and appended to the exception message only in the case of an error. - *

              - * - * @param expression the boolean expression to check - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param value the value to append to the message when invalid - * @throws IllegalArgumentException if expression is {@code false} - * @see #isTrue(boolean) - * @see #isTrue(boolean, String, long) - * @see #isTrue(boolean, String, Object...) - */ - public static void isTrue(final boolean expression, final String message, final double value) { - if (!expression) { - throw new IllegalArgumentException(HString.format(message, Double.valueOf(value))); - } - } - - /** - *

              - * Validate that the argument condition is {@code true}; otherwise throwing an - * exception with the specified message. This method is useful when validating - * according to an arbitrary boolean expression, such as validating a primitive - * number or using your own custom validation expression. - *

              - * - *
              -	 * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
              -	 * Validate.isTrue(myObject.isOk(), "The object is not okay");
              -	 * 
              - * - * @param expression the boolean expression to check - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param values the optional values for the formatted exception message, - * null array not recommended - * @throws IllegalArgumentException if expression is {@code false} - * @see #isTrue(boolean) - * @see #isTrue(boolean, String, long) - * @see #isTrue(boolean, String, double) - */ - public static void isTrue(final boolean expression, final String message, final Object... values) { - if (!expression) { - throw new IllegalArgumentException(HString.format(message, values)); - } - } - - /** - *

              - * Validate that the argument condition is {@code true}; otherwise throwing an - * exception. This method is useful when validating according to an arbitrary - * boolean expression, such as validating a primitive number or using your own - * custom validation expression. - *

              - * - *
              -	 * Validate.isTrue(i > 0);
              -	 * Validate.isTrue(myObject.isOk());
              -	 * 
              - * - *

              - * The message of the exception is "The validated expression is - * false". - *

              - * - * @param expression the boolean expression to check - * @throws IllegalArgumentException if expression is {@code false} - * @see #isTrue(boolean, String, long) - * @see #isTrue(boolean, String, double) - * @see #isTrue(boolean, String, Object...) - */ - public static void isTrue(final boolean expression) { - if (!expression) { - throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE); - } - } - - // notNull - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument is not {@code null}; otherwise throwing - * an exception. - * - *

              -	 * Validate.notNull(myObject, "The object must not be null");
              -	 * 
              - * - *

              - * The message of the exception is "The validated object is null". - *

              - * - * @param the object type - * @param object the object to check - * @return the validated object (never {@code null} for method chaining) - * @throws NullPointerException if the object is {@code null} - * @see #notNull(Object, String, Object...) - */ - public static T notNull(final T object) { - return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE); - } - - /** - *

              - * Validate that the specified argument is not {@code null}; otherwise throwing - * an exception with the specified message. - * - *

              -	 * Validate.notNull(myObject, "The object must not be null");
              -	 * 
              - * - * @param the object type - * @param object the object to check - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message - * @return the validated object (never {@code null} for method chaining) - * @throws NullPointerException if the object is {@code null} - * @see #notNull(Object) - */ - public static T notNull(final T object, final String message, final Object... values) { - return JDKBackports.javaUtilObject_requireNonNull(object, () -> HString.format(message, values)); - } - - // notEmpty array - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument array is neither {@code null} nor a - * length of zero (no elements); otherwise throwing an exception with the - * specified message. - * - *

              -	 * Validate.notEmpty(myArray, "The array must not be empty");
              -	 * 
              - * - * @param the array type - * @param array the array to check, validated not null by this method - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated array (never {@code null} method for chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IllegalArgumentException if the array is empty - * @see #notEmpty(Object[]) - */ - public static T[] notEmpty(final T[] array, final String message, final Object... values) { - JDKBackports.javaUtilObject_requireNonNull(array, () -> HString.format(message, values)); - if (array.length == 0) { - throw new IllegalArgumentException(HString.format(message, values)); - } - return array; - } - - /** - *

              - * Validate that the specified argument array is neither {@code null} nor a - * length of zero (no elements); otherwise throwing an exception. - * - *

              -	 * Validate.notEmpty(myArray);
              -	 * 
              - * - *

              - * The message in the exception is "The validated array is empty". - * - * @param the array type - * @param array the array to check, validated not null by this method - * @return the validated array (never {@code null} method for chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IllegalArgumentException if the array is empty - * @see #notEmpty(Object[], String, Object...) - */ - public static T[] notEmpty(final T[] array) { - return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE); - } - - // notEmpty collection - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument collection is neither {@code null} nor a - * size of zero (no elements); otherwise throwing an exception with the - * specified message. - * - *

              -	 * Validate.notEmpty(myCollection, "The collection must not be empty");
              -	 * 
              - * - * @param the collection type - * @param collection the collection to check, validated not null by this method - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param values the optional values for the formatted exception message, - * null array not recommended - * @return the validated collection (never {@code null} method for chaining) - * @throws NullPointerException if the collection is {@code null} - * @throws IllegalArgumentException if the collection is empty - * @see #notEmpty(Object[]) - */ - public static > T notEmpty(final T collection, final String message, - final Object... values) { - JDKBackports.javaUtilObject_requireNonNull(collection, () -> HString.format(message, values)); - if (collection.isEmpty()) { - throw new IllegalArgumentException(HString.format(message, values)); - } - return collection; - } - - /** - *

              - * Validate that the specified argument collection is neither {@code null} nor a - * size of zero (no elements); otherwise throwing an exception. - * - *

              -	 * Validate.notEmpty(myCollection);
              -	 * 
              - * - *

              - * The message in the exception is "The validated collection is - * empty". - *

              - * - * @param the collection type - * @param collection the collection to check, validated not null by this method - * @return the validated collection (never {@code null} method for chaining) - * @throws NullPointerException if the collection is {@code null} - * @throws IllegalArgumentException if the collection is empty - * @see #notEmpty(Collection, String, Object...) - */ - public static > T notEmpty(final T collection) { - return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE); - } - - // notEmpty map - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument map is neither {@code null} nor a size - * of zero (no elements); otherwise throwing an exception with the specified - * message. - * - *

              -	 * Validate.notEmpty(myMap, "The map must not be empty");
              -	 * 
              - * - * @param the map type - * @param map the map to check, validated not null by this method - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated map (never {@code null} method for chaining) - * @throws NullPointerException if the map is {@code null} - * @throws IllegalArgumentException if the map is empty - * @see #notEmpty(Object[]) - */ - public static > T notEmpty(final T map, final String message, final Object... values) { - JDKBackports.javaUtilObject_requireNonNull(map, () -> HString.format(message, values)); - if (map.isEmpty()) { - throw new IllegalArgumentException(HString.format(message, values)); - } - return map; - } - - /** - *

              - * Validate that the specified argument map is neither {@code null} nor a size - * of zero (no elements); otherwise throwing an exception. - * - *

              -	 * Validate.notEmpty(myMap);
              -	 * 
              - * - *

              - * The message in the exception is "The validated map is empty". - *

              - * - * @param the map type - * @param map the map to check, validated not null by this method - * @return the validated map (never {@code null} method for chaining) - * @throws NullPointerException if the map is {@code null} - * @throws IllegalArgumentException if the map is empty - * @see #notEmpty(Map, String, Object...) - */ - public static > T notEmpty(final T map) { - return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE); - } - - // notEmpty string - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument character sequence is neither - * {@code null} nor a length of zero (no characters); otherwise throwing an - * exception with the specified message. - * - *

              -	 * Validate.notEmpty(myString, "The string must not be empty");
              -	 * 
              - * - * @param the character sequence type - * @param chars the character sequence to check, validated not null by this - * method - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated character sequence (never {@code null} method for - * chaining) - * @throws NullPointerException if the character sequence is {@code null} - * @throws IllegalArgumentException if the character sequence is empty - * @see #notEmpty(CharSequence) - */ - public static T notEmpty(final T chars, final String message, final Object... values) { - JDKBackports.javaUtilObject_requireNonNull(chars, () -> HString.format(message, values)); - if (chars.length() == 0) { - throw new IllegalArgumentException(HString.format(message, values)); - } - return chars; - } - - /** - *

              - * Validate that the specified argument character sequence is neither - * {@code null} nor a length of zero (no characters); otherwise throwing an - * exception with the specified message. - * - *

              -	 * Validate.notEmpty(myString);
              -	 * 
              - * - *

              - * The message in the exception is "The validated character sequence is - * empty". - *

              - * - * @param the character sequence type - * @param chars the character sequence to check, validated not null by this - * method - * @return the validated character sequence (never {@code null} method for - * chaining) - * @throws NullPointerException if the character sequence is {@code null} - * @throws IllegalArgumentException if the character sequence is empty - * @see #notEmpty(CharSequence, String, Object...) - */ - public static T notEmpty(final T chars) { - return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE); - } - - // notBlank string - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument character sequence is neither - * {@code null}, a length of zero (no characters), empty nor whitespace; - * otherwise throwing an exception with the specified message. - * - *

              -	 * Validate.notBlank(myString, "The string must not be blank");
              -	 * 
              - * - * @param the character sequence type - * @param chars the character sequence to check, validated not null by this - * method - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated character sequence (never {@code null} method for - * chaining) - * @throws NullPointerException if the character sequence is {@code null} - * @throws IllegalArgumentException if the character sequence is blank - * @see #notBlank(CharSequence) - * - * @since 3.0 - */ - public static T notBlank(final T chars, final String message, final Object... values) { - JDKBackports.javaUtilObject_requireNonNull(chars, () -> HString.format(message, values)); - if (StringUtils.isBlank(chars)) { - throw new IllegalArgumentException(HString.format(message, values)); - } - return chars; - } - - /** - *

              - * Validate that the specified argument character sequence is neither - * {@code null}, a length of zero (no characters), empty nor whitespace; - * otherwise throwing an exception. - * - *

              -	 * Validate.notBlank(myString);
              -	 * 
              - * - *

              - * The message in the exception is "The validated character sequence is - * blank". - *

              - * - * @param the character sequence type - * @param chars the character sequence to check, validated not null by this - * method - * @return the validated character sequence (never {@code null} method for - * chaining) - * @throws NullPointerException if the character sequence is {@code null} - * @throws IllegalArgumentException if the character sequence is blank - * @see #notBlank(CharSequence, String, Object...) - * - * @since 3.0 - */ - public static T notBlank(final T chars) { - return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE); - } - - // noNullElements array - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument array is neither {@code null} nor - * contains any elements that are {@code null}; otherwise throwing an exception - * with the specified message. - * - *

              -	 * Validate.noNullElements(myArray, "The array contain null at position %d");
              -	 * 
              - * - *

              - * If the array is {@code null}, then the message in the exception is "The - * validated object is null". - *

              - * - *

              - * If the array has a {@code null} element, then the iteration index of the - * invalid element is appended to the {@code values} argument. - *

              - * - * @param the array type - * @param array the array to check, validated not null by this method - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated array (never {@code null} method for chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IllegalArgumentException if an element is {@code null} - * @see #noNullElements(Object[]) - */ - public static T[] noNullElements(final T[] array, final String message, final Object... values) { - notNull(array); - for (int i = 0; i < array.length; i++) { - if (array[i] == null) { - final Object[] values2 = new Object[values.length + 1]; - System.arraycopy(values, 0, values2, 0, values.length); - values2[values.length - 1] = i; - throw new IllegalArgumentException(HString.format(message, values2)); - } - } - return array; - } - - /** - *

              - * Validate that the specified argument array is neither {@code null} nor - * contains any elements that are {@code null}; otherwise throwing an exception. - *

              - * - *
              -	 * Validate.noNullElements(myArray);
              -	 * 
              - * - *

              - * If the array is {@code null}, then the message in the exception is "The - * validated object is null". - *

              - * - *

              - * If the array has a {@code null} element, then the message in the exception is - * "The validated array contains null element at index: " followed by - * the index. - *

              - * - * @param the array type - * @param array the array to check, validated not null by this method - * @return the validated array (never {@code null} method for chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IllegalArgumentException if an element is {@code null} - * @see #noNullElements(Object[], String, Object...) - */ - public static T[] noNullElements(final T[] array) { - return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE); - } - - // noNullElements iterable - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument iterable is neither {@code null} nor - * contains any elements that are {@code null}; otherwise throwing an exception - * with the specified message. - * - *

              -	 * Validate.noNullElements(myCollection, "The collection contains null at position %d");
              -	 * 
              - * - *

              - * If the iterable is {@code null}, then the message in the exception is - * "The validated object is null". - *

              - * - *

              - * If the iterable has a {@code null} element, then the iteration index of the - * invalid element is appended to the {@code values} argument. - *

              - * - * @param the iterable type - * @param iterable the iterable to check, validated not null by this method - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated iterable (never {@code null} method for chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IllegalArgumentException if an element is {@code null} - * @see #noNullElements(Iterable) - */ - public static > T noNullElements(final T iterable, final String message, - final Object... values) { - notNull(iterable); - int i = 0; - for (final Iterator it = iterable.iterator(); it.hasNext(); i++) { - if (it.next() == null) { - final Object[] values2 = new Object[values.length + 1]; - System.arraycopy(values, 0, values2, 0, values.length); - values2[values.length - 1] = i; - throw new IllegalArgumentException(HString.format(message, values2)); - } - } - return iterable; - } - - /** - *

              - * Validate that the specified argument iterable is neither {@code null} nor - * contains any elements that are {@code null}; otherwise throwing an exception. - * - *

              -	 * Validate.noNullElements(myCollection);
              -	 * 
              - * - *

              - * If the iterable is {@code null}, then the message in the exception is - * "The validated object is null". - *

              - * - *

              - * If the array has a {@code null} element, then the message in the exception is - * "The validated iterable contains null element at index: " followed - * by the index. - *

              - * - * @param the iterable type - * @param iterable the iterable to check, validated not null by this method - * @return the validated iterable (never {@code null} method for chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IllegalArgumentException if an element is {@code null} - * @see #noNullElements(Iterable, String, Object...) - */ - public static > T noNullElements(final T iterable) { - return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE); - } - - // validIndex array - // --------------------------------------------------------------------------------- - - /** - *

              - * Validates that the index is within the bounds of the argument array; - * otherwise throwing an exception with the specified message. - *

              - * - *
              -	 * Validate.validIndex(myArray, 2, "The array index is invalid: ");
              -	 * 
              - * - *

              - * If the array is {@code null}, then the message of the exception is "The - * validated object is null". - *

              - * - * @param the array type - * @param array the array to check, validated not null by this method - * @param index the index to check - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated array (never {@code null} for method chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IndexOutOfBoundsException if the index is invalid - * @see #validIndex(Object[], int) - * - * @since 3.0 - */ - public static T[] validIndex(final T[] array, final int index, final String message, final Object... values) { - notNull(array); - if (index < 0 || index >= array.length) { - throw new IndexOutOfBoundsException(HString.format(message, values)); - } - return array; - } - - /** - *

              - * Validates that the index is within the bounds of the argument array; - * otherwise throwing an exception. - *

              - * - *
              -	 * Validate.validIndex(myArray, 2);
              -	 * 
              - * - *

              - * If the array is {@code null}, then the message of the exception is "The - * validated object is null". - *

              - * - *

              - * If the index is invalid, then the message of the exception is "The - * validated array index is invalid: " followed by the index. - *

              - * - * @param the array type - * @param array the array to check, validated not null by this method - * @param index the index to check - * @return the validated array (never {@code null} for method chaining) - * @throws NullPointerException if the array is {@code null} - * @throws IndexOutOfBoundsException if the index is invalid - * @see #validIndex(Object[], int, String, Object...) - * - * @since 3.0 - */ - public static T[] validIndex(final T[] array, final int index) { - return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); - } - - // validIndex collection - // --------------------------------------------------------------------------------- - - /** - *

              - * Validates that the index is within the bounds of the argument collection; - * otherwise throwing an exception with the specified message. - *

              - * - *
              -	 * Validate.validIndex(myCollection, 2, "The collection index is invalid: ");
              -	 * 
              - * - *

              - * If the collection is {@code null}, then the message of the exception is - * "The validated object is null". - *

              - * - * @param the collection type - * @param collection the collection to check, validated not null by this method - * @param index the index to check - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param values the optional values for the formatted exception message, - * null array not recommended - * @return the validated collection (never {@code null} for chaining) - * @throws NullPointerException if the collection is {@code null} - * @throws IndexOutOfBoundsException if the index is invalid - * @see #validIndex(Collection, int) - * - * @since 3.0 - */ - public static > T validIndex(final T collection, final int index, final String message, - final Object... values) { - notNull(collection); - if (index < 0 || index >= collection.size()) { - throw new IndexOutOfBoundsException(HString.format(message, values)); - } - return collection; - } - - /** - *

              - * Validates that the index is within the bounds of the argument collection; - * otherwise throwing an exception. - *

              - * - *
              -	 * Validate.validIndex(myCollection, 2);
              -	 * 
              - * - *

              - * If the index is invalid, then the message of the exception is "The - * validated collection index is invalid: " followed by the index. - *

              - * - * @param the collection type - * @param collection the collection to check, validated not null by this method - * @param index the index to check - * @return the validated collection (never {@code null} for method chaining) - * @throws NullPointerException if the collection is {@code null} - * @throws IndexOutOfBoundsException if the index is invalid - * @see #validIndex(Collection, int, String, Object...) - * - * @since 3.0 - */ - public static > T validIndex(final T collection, final int index) { - return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index)); - } - - // validIndex string - // --------------------------------------------------------------------------------- - - /** - *

              - * Validates that the index is within the bounds of the argument character - * sequence; otherwise throwing an exception with the specified message. - *

              - * - *
              -	 * Validate.validIndex(myStr, 2, "The string index is invalid: ");
              -	 * 
              - * - *

              - * If the character sequence is {@code null}, then the message of the exception - * is "The validated object is null". - *

              - * - * @param the character sequence type - * @param chars the character sequence to check, validated not null by this - * method - * @param index the index to check - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @return the validated character sequence (never {@code null} for method - * chaining) - * @throws NullPointerException if the character sequence is {@code null} - * @throws IndexOutOfBoundsException if the index is invalid - * @see #validIndex(CharSequence, int) - * - * @since 3.0 - */ - public static T validIndex(final T chars, final int index, final String message, - final Object... values) { - notNull(chars); - if (index < 0 || index >= chars.length()) { - throw new IndexOutOfBoundsException(HString.format(message, values)); - } - return chars; - } - - /** - *

              - * Validates that the index is within the bounds of the argument character - * sequence; otherwise throwing an exception. - *

              - * - *
              -	 * Validate.validIndex(myStr, 2);
              -	 * 
              - * - *

              - * If the character sequence is {@code null}, then the message of the exception - * is "The validated object is null". - *

              - * - *

              - * If the index is invalid, then the message of the exception is "The - * validated character sequence index is invalid: " followed by the index. - *

              - * - * @param the character sequence type - * @param chars the character sequence to check, validated not null by this - * method - * @param index the index to check - * @return the validated character sequence (never {@code null} for method - * chaining) - * @throws NullPointerException if the character sequence is {@code null} - * @throws IndexOutOfBoundsException if the index is invalid - * @see #validIndex(CharSequence, int, String, Object...) - * - * @since 3.0 - */ - public static T validIndex(final T chars, final int index) { - return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index)); - } - - // validState - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the stateful condition is {@code true}; otherwise throwing an - * exception. This method is useful when validating according to an arbitrary - * boolean expression, such as validating a primitive number or using your own - * custom validation expression. - *

              - * - *
              -	 * Validate.validState(field > 0);
              -	 * Validate.validState(this.isOk());
              -	 * 
              - * - *

              - * The message of the exception is "The validated state is false". - *

              - * - * @param expression the boolean expression to check - * @throws IllegalStateException if expression is {@code false} - * @see #validState(boolean, String, Object...) - * - * @since 3.0 - */ - public static void validState(final boolean expression) { - if (!expression) { - throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE); - } - } - - /** - *

              - * Validate that the stateful condition is {@code true}; otherwise throwing an - * exception with the specified message. This method is useful when validating - * according to an arbitrary boolean expression, such as validating a primitive - * number or using your own custom validation expression. - *

              - * - *
              -	 * Validate.validState(this.isOk(), "The state is not OK: %s", myObject);
              -	 * 
              - * - * @param expression the boolean expression to check - * @param message the {@link String#format(String, Object...)} exception - * message if invalid, not null - * @param values the optional values for the formatted exception message, - * null array not recommended - * @throws IllegalStateException if expression is {@code false} - * @see #validState(boolean) - * - * @since 3.0 - */ - public static void validState(final boolean expression, final String message, final Object... values) { - if (!expression) { - throw new IllegalStateException(HString.format(message, values)); - } - } - - // matchesPattern - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument character sequence matches the specified - * regular expression pattern; otherwise throwing an exception. - *

              - * - *
              -	 * Validate.matchesPattern("hi", "[a-z]*");
              -	 * 
              - * - *

              - * The syntax of the pattern is the one used in the {@link Pattern} class. - *

              - * - * @param input the character sequence to validate, not null - * @param pattern the regular expression pattern, not null - * @throws IllegalArgumentException if the character sequence does not match the - * pattern - * @see #matchesPattern(CharSequence, String, String, Object...) - * - * @since 3.0 - */ - public static void matchesPattern(final CharSequence input, final String pattern) { - // TODO when breaking BC, consider returning input - if (!Pattern.matches(pattern, input)) { - throw new IllegalArgumentException(HString.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern)); - } - } - - /** - *

              - * Validate that the specified argument character sequence matches the specified - * regular expression pattern; otherwise throwing an exception with the - * specified message. - *

              - * - *
              -	 * Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");
              -	 * 
              - * - *

              - * The syntax of the pattern is the one used in the {@link Pattern} class. - *

              - * - * @param input the character sequence to validate, not null - * @param pattern the regular expression pattern, not null - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @throws IllegalArgumentException if the character sequence does not match the - * pattern - * @see #matchesPattern(CharSequence, String) - * - * @since 3.0 - */ - public static void matchesPattern(final CharSequence input, final String pattern, final String message, - final Object... values) { - // TODO when breaking BC, consider returning input - if (!Pattern.matches(pattern, input)) { - throw new IllegalArgumentException(HString.format(message, values)); - } - } - - // notNaN - // --------------------------------------------------------------------------------- - - /** - *

              - * Validates that the specified argument is not {@code NaN}; otherwise throwing - * an exception. - *

              - * - *
              -	 * Validate.notNaN(myDouble);
              -	 * 
              - * - *

              - * The message of the exception is "The validated value is not a - * number". - *

              - * - * @param value the value to validate - * @throws IllegalArgumentException if the value is not a number - * @see #notNaN(double, java.lang.String, java.lang.Object...) - * - * @since 3.5 - */ - public static void notNaN(final double value) { - notNaN(value, DEFAULT_NOT_NAN_EX_MESSAGE); - } - - /** - *

              - * Validates that the specified argument is not {@code NaN}; otherwise throwing - * an exception with the specified message. - *

              - * - *
              -	 * Validate.notNaN(myDouble, "The value must be a number");
              -	 * 
              - * - * @param value the value to validate - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message - * @throws IllegalArgumentException if the value is not a number - * @see #notNaN(double) - * - * @since 3.5 - */ - public static void notNaN(final double value, final String message, final Object... values) { - if (Double.isNaN(value)) { - throw new IllegalArgumentException(HString.format(message, values)); - } - } - - // finite - // --------------------------------------------------------------------------------- - - /** - *

              - * Validates that the specified argument is not infinite or {@code NaN}; - * otherwise throwing an exception. - *

              - * - *
              -	 * Validate.finite(myDouble);
              -	 * 
              - * - *

              - * The message of the exception is "The value is invalid: %f". - *

              - * - * @param value the value to validate - * @throws IllegalArgumentException if the value is infinite or {@code NaN} - * @see #finite(double, java.lang.String, java.lang.Object...) - * - * @since 3.5 - */ - public static void finite(final double value) { - finite(value, DEFAULT_FINITE_EX_MESSAGE, value); - } - - /** - *

              - * Validates that the specified argument is not infinite or {@code NaN}; - * otherwise throwing an exception with the specified message. - *

              - * - *
              -	 * Validate.finite(myDouble, "The argument must contain a numeric value");
              -	 * 
              - * - * @param value the value to validate - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message - * @throws IllegalArgumentException if the value is infinite or {@code NaN} - * @see #finite(double) - * - * @since 3.5 - */ - public static void finite(final double value, final String message, final Object... values) { - if (Double.isNaN(value) || Double.isInfinite(value)) { - throw new IllegalArgumentException(HString.format(message, values)); - } - } - - // inclusiveBetween - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument object fall between the two inclusive - * values specified; otherwise, throws an exception. - *

              - * - *
              -	 * Validate.inclusiveBetween(0, 2, 1);
              -	 * 
              - * - * @param the type of the argument object - * @param start the inclusive start value, not null - * @param end the inclusive end value, not null - * @param value the object to validate, not null - * @throws IllegalArgumentException if the value falls outside the boundaries - * @see #inclusiveBetween(Object, Object, Comparable, String, Object...) - * - * @since 3.0 - */ - public static void inclusiveBetween(final T start, final T end, final Comparable value) { - // TODO when breaking BC, consider returning value - if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { - throw new IllegalArgumentException(HString.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); - } - } - - /** - *

              - * Validate that the specified argument object fall between the two inclusive - * values specified; otherwise, throws an exception with the specified message. - *

              - * - *
              -	 * Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");
              -	 * 
              - * - * @param the type of the argument object - * @param start the inclusive start value, not null - * @param end the inclusive end value, not null - * @param value the object to validate, not null - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @throws IllegalArgumentException if the value falls outside the boundaries - * @see #inclusiveBetween(Object, Object, Comparable) - * - * @since 3.0 - */ - public static void inclusiveBetween(final T start, final T end, final Comparable value, final String message, - final Object... values) { - // TODO when breaking BC, consider returning value - if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { - throw new IllegalArgumentException(HString.format(message, values)); - } - } - - /** - * Validate that the specified primitive value falls between the two inclusive - * values specified; otherwise, throws an exception. - * - *
              -	 * Validate.inclusiveBetween(0, 2, 1);
              -	 * 
              - * - * @param start the inclusive start value - * @param end the inclusive end value - * @param value the value to validate - * @throws IllegalArgumentException if the value falls outside the boundaries - * (inclusive) - * - * @since 3.3 - */ - @SuppressWarnings("boxing") - public static void inclusiveBetween(final long start, final long end, final long value) { - // TODO when breaking BC, consider returning value - if (value < start || value > end) { - throw new IllegalArgumentException(HString.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); - } - } - - /** - * Validate that the specified primitive value falls between the two inclusive + * Validate that the specified primitive value falls between the two exclusive * values specified; otherwise, throws an exception with the specified message. * *
              -	 * Validate.inclusiveBetween(0, 2, 1, "Not in range");
              +	 * Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");
               	 * 
              * - * @param start the inclusive start value - * @param end the inclusive end value + * @param start the exclusive start value + * @param end the exclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * @@ -1270,122 +121,14 @@ public class Validate { * * @since 3.3 */ - public static void inclusiveBetween(final long start, final long end, final long value, final String message) { - // TODO when breaking BC, consider returning value - if (value < start || value > end) { - throw new IllegalArgumentException(message); - } - } - - /** - * Validate that the specified primitive value falls between the two inclusive - * values specified; otherwise, throws an exception. - * - *
              -	 * Validate.inclusiveBetween(0.1, 2.1, 1.1);
              -	 * 
              - * - * @param start the inclusive start value - * @param end the inclusive end value - * @param value the value to validate - * @throws IllegalArgumentException if the value falls outside the boundaries - * (inclusive) - * - * @since 3.3 - */ - @SuppressWarnings("boxing") - public static void inclusiveBetween(final double start, final double end, final double value) { - // TODO when breaking BC, consider returning value - if (value < start || value > end) { - throw new IllegalArgumentException(HString.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); - } - } - - /** - * Validate that the specified primitive value falls between the two inclusive - * values specified; otherwise, throws an exception with the specified message. - * - *
              -	 * Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");
              -	 * 
              - * - * @param start the inclusive start value - * @param end the inclusive end value - * @param value the value to validate - * @param message the exception message if invalid, not null - * - * @throws IllegalArgumentException if the value falls outside the boundaries - * - * @since 3.3 - */ - public static void inclusiveBetween(final double start, final double end, final double value, + public static void exclusiveBetween(final double start, final double end, final double value, final String message) { // TODO when breaking BC, consider returning value - if (value < start || value > end) { + if (value <= start || value >= end) { throw new IllegalArgumentException(message); } } - // exclusiveBetween - // --------------------------------------------------------------------------------- - - /** - *

              - * Validate that the specified argument object fall between the two exclusive - * values specified; otherwise, throws an exception. - *

              - * - *
              -	 * Validate.exclusiveBetween(0, 2, 1);
              -	 * 
              - * - * @param the type of the argument object - * @param start the exclusive start value, not null - * @param end the exclusive end value, not null - * @param value the object to validate, not null - * @throws IllegalArgumentException if the value falls outside the boundaries - * @see #exclusiveBetween(Object, Object, Comparable, String, Object...) - * - * @since 3.0 - */ - public static void exclusiveBetween(final T start, final T end, final Comparable value) { - // TODO when breaking BC, consider returning value - if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { - throw new IllegalArgumentException(HString.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); - } - } - - /** - *

              - * Validate that the specified argument object fall between the two exclusive - * values specified; otherwise, throws an exception with the specified message. - *

              - * - *
              -	 * Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");
              -	 * 
              - * - * @param the type of the argument object - * @param start the exclusive start value, not null - * @param end the exclusive end value, not null - * @param value the object to validate, not null - * @param message the {@link String#format(String, Object...)} exception message - * if invalid, not null - * @param values the optional values for the formatted exception message, null - * array not recommended - * @throws IllegalArgumentException if the value falls outside the boundaries - * @see #exclusiveBetween(Object, Object, Comparable) - * - * @since 3.0 - */ - public static void exclusiveBetween(final T start, final T end, final Comparable value, final String message, - final Object... values) { - // TODO when breaking BC, consider returning value - if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { - throw new IllegalArgumentException(HString.format(message, values)); - } - } - /** * Validate that the specified primitive value falls between the two exclusive * values specified; otherwise, throws an exception. @@ -1434,38 +177,154 @@ public class Validate { } /** - * Validate that the specified primitive value falls between the two exclusive + *

              + * Validate that the specified argument object fall between the two exclusive * values specified; otherwise, throws an exception. + *

              * *
              -	 * Validate.exclusiveBetween(0.1, 2.1, 1.1);
              +	 * Validate.exclusiveBetween(0, 2, 1);
               	 * 
              * - * @param start the exclusive start value - * @param end the exclusive end value - * @param value the value to validate - * @throws IllegalArgumentException if the value falls out of the boundaries + * @param the type of the argument object + * @param start the exclusive start value, not null + * @param end the exclusive end value, not null + * @param value the object to validate, not null + * @throws IllegalArgumentException if the value falls outside the boundaries + * @see #exclusiveBetween(Object, Object, Comparable, String, Object...) * - * @since 3.3 + * @since 3.0 */ - @SuppressWarnings("boxing") - public static void exclusiveBetween(final double start, final double end, final double value) { + public static void exclusiveBetween(final T start, final T end, final Comparable value) { // TODO when breaking BC, consider returning value - if (value <= start || value >= end) { + if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { throw new IllegalArgumentException(HString.format(DEFAULT_EXCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); } } + // notNull + // --------------------------------------------------------------------------------- + /** - * Validate that the specified primitive value falls between the two exclusive + *

              + * Validate that the specified argument object fall between the two exclusive + * values specified; otherwise, throws an exception with the specified message. + *

              + * + *
              +	 * Validate.exclusiveBetween(0, 2, 1, "Not in boundaries");
              +	 * 
              + * + * @param the type of the argument object + * @param start the exclusive start value, not null + * @param end the exclusive end value, not null + * @param value the object to validate, not null + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @throws IllegalArgumentException if the value falls outside the boundaries + * @see #exclusiveBetween(Object, Object, Comparable) + * + * @since 3.0 + */ + public static void exclusiveBetween(final T start, final T end, final Comparable value, final String message, + final Object... values) { + // TODO when breaking BC, consider returning value + if (value.compareTo(start) <= 0 || value.compareTo(end) >= 0) { + throw new IllegalArgumentException(HString.format(message, values)); + } + } + + /** + *

              + * Validates that the specified argument is not infinite or {@code NaN}; + * otherwise throwing an exception. + *

              + * + *
              +	 * Validate.finite(myDouble);
              +	 * 
              + * + *

              + * The message of the exception is "The value is invalid: %f". + *

              + * + * @param value the value to validate + * @throws IllegalArgumentException if the value is infinite or {@code NaN} + * @see #finite(double, java.lang.String, java.lang.Object...) + * + * @since 3.5 + */ + public static void finite(final double value) { + finite(value, DEFAULT_FINITE_EX_MESSAGE, value); + } + + // notEmpty array + // --------------------------------------------------------------------------------- + + /** + *

              + * Validates that the specified argument is not infinite or {@code NaN}; + * otherwise throwing an exception with the specified message. + *

              + * + *
              +	 * Validate.finite(myDouble, "The argument must contain a numeric value");
              +	 * 
              + * + * @param value the value to validate + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message + * @throws IllegalArgumentException if the value is infinite or {@code NaN} + * @see #finite(double) + * + * @since 3.5 + */ + public static void finite(final double value, final String message, final Object... values) { + if (Double.isNaN(value) || Double.isInfinite(value)) { + throw new IllegalArgumentException(HString.format(message, values)); + } + } + + /** + * Validate that the specified primitive value falls between the two inclusive + * values specified; otherwise, throws an exception. + * + *
              +	 * Validate.inclusiveBetween(0.1, 2.1, 1.1);
              +	 * 
              + * + * @param start the inclusive start value + * @param end the inclusive end value + * @param value the value to validate + * @throws IllegalArgumentException if the value falls outside the boundaries + * (inclusive) + * + * @since 3.3 + */ + @SuppressWarnings("boxing") + public static void inclusiveBetween(final double start, final double end, final double value) { + // TODO when breaking BC, consider returning value + if (value < start || value > end) { + throw new IllegalArgumentException(HString.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); + } + } + + // notEmpty collection + // --------------------------------------------------------------------------------- + + /** + * Validate that the specified primitive value falls between the two inclusive * values specified; otherwise, throws an exception with the specified message. * *
              -	 * Validate.exclusiveBetween(0.1, 2.1, 1.1, "Not in range");
              +	 * Validate.inclusiveBetween(0.1, 2.1, 1.1, "Not in range");
               	 * 
              * - * @param start the exclusive start value - * @param end the exclusive end value + * @param start the inclusive start value + * @param end the inclusive end value * @param value the value to validate * @param message the exception message if invalid, not null * @@ -1473,82 +332,125 @@ public class Validate { * * @since 3.3 */ - public static void exclusiveBetween(final double start, final double end, final double value, + public static void inclusiveBetween(final double start, final double end, final double value, final String message) { // TODO when breaking BC, consider returning value - if (value <= start || value >= end) { + if (value < start || value > end) { throw new IllegalArgumentException(message); } } - // isInstanceOf + /** + * Validate that the specified primitive value falls between the two inclusive + * values specified; otherwise, throws an exception. + * + *
              +	 * Validate.inclusiveBetween(0, 2, 1);
              +	 * 
              + * + * @param start the inclusive start value + * @param end the inclusive end value + * @param value the value to validate + * @throws IllegalArgumentException if the value falls outside the boundaries + * (inclusive) + * + * @since 3.3 + */ + @SuppressWarnings("boxing") + public static void inclusiveBetween(final long start, final long end, final long value) { + // TODO when breaking BC, consider returning value + if (value < start || value > end) { + throw new IllegalArgumentException(HString.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); + } + } + + // notEmpty map // --------------------------------------------------------------------------------- /** - * Validates that the argument is an instance of the specified class, if not - * throws an exception. - * - *

              - * This method is useful when validating according to an arbitrary class - *

              + * Validate that the specified primitive value falls between the two inclusive + * values specified; otherwise, throws an exception with the specified message. * *
              -	 * Validate.isInstanceOf(OkClass.class, object);
              +	 * Validate.inclusiveBetween(0, 2, 1, "Not in range");
               	 * 
              * - *

              - * The message of the exception is "Expected type: {type}, actual: - * {obj_type}" - *

              + * @param start the inclusive start value + * @param end the inclusive end value + * @param value the value to validate + * @param message the exception message if invalid, not null * - * @param type the class the object must be validated against, not null - * @param obj the object to check, null throws an exception - * @throws IllegalArgumentException if argument is not of specified class - * @see #isInstanceOf(Class, Object, String, Object...) + * @throws IllegalArgumentException if the value falls outside the boundaries * - * @since 3.0 + * @since 3.3 */ - public static void isInstanceOf(final Class type, final Object obj) { - // TODO when breaking BC, consider returning obj - if (!type.isInstance(obj)) { - throw new IllegalArgumentException(HString.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), - obj == null ? "null" : obj.getClass().getName())); + public static void inclusiveBetween(final long start, final long end, final long value, final String message) { + // TODO when breaking BC, consider returning value + if (value < start || value > end) { + throw new IllegalArgumentException(message); } } /** *

              - * Validate that the argument is an instance of the specified class; otherwise - * throwing an exception with the specified message. This method is useful when - * validating according to an arbitrary class + * Validate that the specified argument object fall between the two inclusive + * values specified; otherwise, throws an exception. *

              * *
              -	 * Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s", object.getClass().getName());
              +	 * Validate.inclusiveBetween(0, 2, 1);
               	 * 
              * - * @param type the class the object must be validated against, not null - * @param obj the object to check, null throws an exception + * @param the type of the argument object + * @param start the inclusive start value, not null + * @param end the inclusive end value, not null + * @param value the object to validate, not null + * @throws IllegalArgumentException if the value falls outside the boundaries + * @see #inclusiveBetween(Object, Object, Comparable, String, Object...) + * + * @since 3.0 + */ + public static void inclusiveBetween(final T start, final T end, final Comparable value) { + // TODO when breaking BC, consider returning value + if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { + throw new IllegalArgumentException(HString.format(DEFAULT_INCLUSIVE_BETWEEN_EX_MESSAGE, value, start, end)); + } + } + + // notEmpty string + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument object fall between the two inclusive + * values specified; otherwise, throws an exception with the specified message. + *

              + * + *
              +	 * Validate.inclusiveBetween(0, 2, 1, "Not in boundaries");
              +	 * 
              + * + * @param the type of the argument object + * @param start the inclusive start value, not null + * @param end the inclusive end value, not null + * @param value the object to validate, not null * @param message the {@link String#format(String, Object...)} exception message * if invalid, not null * @param values the optional values for the formatted exception message, null * array not recommended - * @throws IllegalArgumentException if argument is not of specified class - * @see #isInstanceOf(Class, Object) + * @throws IllegalArgumentException if the value falls outside the boundaries + * @see #inclusiveBetween(Object, Object, Comparable) * * @since 3.0 */ - public static void isInstanceOf(final Class type, final Object obj, final String message, + public static void inclusiveBetween(final T start, final T end, final Comparable value, final String message, final Object... values) { - // TODO when breaking BC, consider returning obj - if (!type.isInstance(obj)) { + // TODO when breaking BC, consider returning value + if (value.compareTo(start) < 0 || value.compareTo(end) > 0) { throw new IllegalArgumentException(HString.format(message, values)); } } - // isAssignableFrom - // --------------------------------------------------------------------------------- - /** * Validates that the argument can be converted to the specified class, if not, * throws an exception. @@ -1582,6 +484,9 @@ public class Validate { } } + // notBlank string + // --------------------------------------------------------------------------------- + /** * Validates that the argument can be converted to the specified class, if not * throws an exception. @@ -1617,4 +522,1099 @@ public class Validate { throw new IllegalArgumentException(HString.format(message, values)); } } + + /** + * Validates that the argument is an instance of the specified class, if not + * throws an exception. + * + *

              + * This method is useful when validating according to an arbitrary class + *

              + * + *
              +	 * Validate.isInstanceOf(OkClass.class, object);
              +	 * 
              + * + *

              + * The message of the exception is "Expected type: {type}, actual: + * {obj_type}" + *

              + * + * @param type the class the object must be validated against, not null + * @param obj the object to check, null throws an exception + * @throws IllegalArgumentException if argument is not of specified class + * @see #isInstanceOf(Class, Object, String, Object...) + * + * @since 3.0 + */ + public static void isInstanceOf(final Class type, final Object obj) { + // TODO when breaking BC, consider returning obj + if (!type.isInstance(obj)) { + throw new IllegalArgumentException(HString.format(DEFAULT_IS_INSTANCE_OF_EX_MESSAGE, type.getName(), + obj == null ? "null" : obj.getClass().getName())); + } + } + + // noNullElements array + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the argument is an instance of the specified class; otherwise + * throwing an exception with the specified message. This method is useful when + * validating according to an arbitrary class + *

              + * + *
              +	 * Validate.isInstanceOf(OkClass.class, object, "Wrong class, object is of class %s", object.getClass().getName());
              +	 * 
              + * + * @param type the class the object must be validated against, not null + * @param obj the object to check, null throws an exception + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @throws IllegalArgumentException if argument is not of specified class + * @see #isInstanceOf(Class, Object) + * + * @since 3.0 + */ + public static void isInstanceOf(final Class type, final Object obj, final String message, + final Object... values) { + // TODO when breaking BC, consider returning obj + if (!type.isInstance(obj)) { + throw new IllegalArgumentException(HString.format(message, values)); + } + } + + /** + *

              + * Validate that the argument condition is {@code true}; otherwise throwing an + * exception. This method is useful when validating according to an arbitrary + * boolean expression, such as validating a primitive number or using your own + * custom validation expression. + *

              + * + *
              +	 * Validate.isTrue(i > 0);
              +	 * Validate.isTrue(myObject.isOk());
              +	 * 
              + * + *

              + * The message of the exception is "The validated expression is + * false". + *

              + * + * @param expression the boolean expression to check + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, double) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(final boolean expression) { + if (!expression) { + throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE); + } + } + + // noNullElements iterable + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the argument condition is {@code true}; otherwise throwing an + * exception with the specified message. This method is useful when validating + * according to an arbitrary boolean expression, such as validating a primitive + * number or using your own custom validation expression. + *

              + * + *
              +	 * Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);
              +	 * 
              + * + *

              + * For performance reasons, the double value is passed as a separate parameter + * and appended to the exception message only in the case of an error. + *

              + * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(final boolean expression, final String message, final double value) { + if (!expression) { + throw new IllegalArgumentException(HString.format(message, Double.valueOf(value))); + } + } + + /** + *

              + * Validate that the argument condition is {@code true}; otherwise throwing an + * exception with the specified message. This method is useful when validating + * according to an arbitrary boolean expression, such as validating a primitive + * number or using your own custom validation expression. + *

              + * + *
              +	 * Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);
              +	 * 
              + * + *

              + * For performance reasons, the long value is passed as a separate parameter and + * appended to the exception message only in the case of an error. + *

              + * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param value the value to append to the message when invalid + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, double) + * @see #isTrue(boolean, String, Object...) + */ + public static void isTrue(final boolean expression, final String message, final long value) { + if (!expression) { + throw new IllegalArgumentException(HString.format(message, Long.valueOf(value))); + } + } + + // validIndex array + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the argument condition is {@code true}; otherwise throwing an + * exception with the specified message. This method is useful when validating + * according to an arbitrary boolean expression, such as validating a primitive + * number or using your own custom validation expression. + *

              + * + *
              +	 * Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
              +	 * Validate.isTrue(myObject.isOk(), "The object is not okay");
              +	 * 
              + * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param values the optional values for the formatted exception message, + * null array not recommended + * @throws IllegalArgumentException if expression is {@code false} + * @see #isTrue(boolean) + * @see #isTrue(boolean, String, long) + * @see #isTrue(boolean, String, double) + */ + public static void isTrue(final boolean expression, final String message, final Object... values) { + if (!expression) { + throw new IllegalArgumentException(HString.format(message, values)); + } + } + + /** + *

              + * Validate that the specified argument character sequence matches the specified + * regular expression pattern; otherwise throwing an exception. + *

              + * + *
              +	 * Validate.matchesPattern("hi", "[a-z]*");
              +	 * 
              + * + *

              + * The syntax of the pattern is the one used in the {@link Pattern} class. + *

              + * + * @param input the character sequence to validate, not null + * @param pattern the regular expression pattern, not null + * @throws IllegalArgumentException if the character sequence does not match the + * pattern + * @see #matchesPattern(CharSequence, String, String, Object...) + * + * @since 3.0 + */ + public static void matchesPattern(final CharSequence input, final String pattern) { + // TODO when breaking BC, consider returning input + if (!Pattern.matches(pattern, input)) { + throw new IllegalArgumentException(HString.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern)); + } + } + + // validIndex collection + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument character sequence matches the specified + * regular expression pattern; otherwise throwing an exception with the + * specified message. + *

              + * + *
              +	 * Validate.matchesPattern("hi", "[a-z]*", "%s does not match %s", "hi" "[a-z]*");
              +	 * 
              + * + *

              + * The syntax of the pattern is the one used in the {@link Pattern} class. + *

              + * + * @param input the character sequence to validate, not null + * @param pattern the regular expression pattern, not null + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @throws IllegalArgumentException if the character sequence does not match the + * pattern + * @see #matchesPattern(CharSequence, String) + * + * @since 3.0 + */ + public static void matchesPattern(final CharSequence input, final String pattern, final String message, + final Object... values) { + // TODO when breaking BC, consider returning input + if (!Pattern.matches(pattern, input)) { + throw new IllegalArgumentException(HString.format(message, values)); + } + } + + /** + *

              + * Validate that the specified argument iterable is neither {@code null} nor + * contains any elements that are {@code null}; otherwise throwing an exception. + * + *

              +	 * Validate.noNullElements(myCollection);
              +	 * 
              + * + *

              + * If the iterable is {@code null}, then the message in the exception is + * "The validated object is null". + *

              + * + *

              + * If the array has a {@code null} element, then the message in the exception is + * "The validated iterable contains null element at index: " followed + * by the index. + *

              + * + * @param the iterable type + * @param iterable the iterable to check, validated not null by this method + * @return the validated iterable (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Iterable, String, Object...) + */ + public static > T noNullElements(final T iterable) { + return noNullElements(iterable, DEFAULT_NO_NULL_ELEMENTS_COLLECTION_EX_MESSAGE); + } + + // validIndex string + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument iterable is neither {@code null} nor + * contains any elements that are {@code null}; otherwise throwing an exception + * with the specified message. + * + *

              +	 * Validate.noNullElements(myCollection, "The collection contains null at position %d");
              +	 * 
              + * + *

              + * If the iterable is {@code null}, then the message in the exception is + * "The validated object is null". + *

              + * + *

              + * If the iterable has a {@code null} element, then the iteration index of the + * invalid element is appended to the {@code values} argument. + *

              + * + * @param the iterable type + * @param iterable the iterable to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated iterable (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Iterable) + */ + public static > T noNullElements(final T iterable, final String message, + final Object... values) { + notNull(iterable); + int i = 0; + for (final Iterator it = iterable.iterator(); it.hasNext(); i++) { + if (it.next() == null) { + final Object[] values2 = new Object[values.length + 1]; + System.arraycopy(values, 0, values2, 0, values.length); + values2[values.length - 1] = i; + throw new IllegalArgumentException(HString.format(message, values2)); + } + } + return iterable; + } + + /** + *

              + * Validate that the specified argument array is neither {@code null} nor + * contains any elements that are {@code null}; otherwise throwing an exception. + *

              + * + *
              +	 * Validate.noNullElements(myArray);
              +	 * 
              + * + *

              + * If the array is {@code null}, then the message in the exception is "The + * validated object is null". + *

              + * + *

              + * If the array has a {@code null} element, then the message in the exception is + * "The validated array contains null element at index: " followed by + * the index. + *

              + * + * @param the array type + * @param array the array to check, validated not null by this method + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Object[], String, Object...) + */ + public static T[] noNullElements(final T[] array) { + return noNullElements(array, DEFAULT_NO_NULL_ELEMENTS_ARRAY_EX_MESSAGE); + } + + // validState + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument array is neither {@code null} nor + * contains any elements that are {@code null}; otherwise throwing an exception + * with the specified message. + * + *

              +	 * Validate.noNullElements(myArray, "The array contain null at position %d");
              +	 * 
              + * + *

              + * If the array is {@code null}, then the message in the exception is "The + * validated object is null". + *

              + * + *

              + * If the array has a {@code null} element, then the iteration index of the + * invalid element is appended to the {@code values} argument. + *

              + * + * @param the array type + * @param array the array to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if an element is {@code null} + * @see #noNullElements(Object[]) + */ + public static T[] noNullElements(final T[] array, final String message, final Object... values) { + notNull(array); + for (int i = 0; i < array.length; i++) { + if (array[i] == null) { + final Object[] values2 = new Object[values.length + 1]; + System.arraycopy(values, 0, values2, 0, values.length); + values2[values.length - 1] = i; + throw new IllegalArgumentException(HString.format(message, values2)); + } + } + return array; + } + + /** + *

              + * Validate that the specified argument character sequence is neither + * {@code null}, a length of zero (no characters), empty nor whitespace; + * otherwise throwing an exception. + * + *

              +	 * Validate.notBlank(myString);
              +	 * 
              + * + *

              + * The message in the exception is "The validated character sequence is + * blank". + *

              + * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this + * method + * @return the validated character sequence (never {@code null} method for + * chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is blank + * @see #notBlank(CharSequence, String, Object...) + * + * @since 3.0 + */ + public static T notBlank(final T chars) { + return notBlank(chars, DEFAULT_NOT_BLANK_EX_MESSAGE); + } + + // matchesPattern + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument character sequence is neither + * {@code null}, a length of zero (no characters), empty nor whitespace; + * otherwise throwing an exception with the specified message. + * + *

              +	 * Validate.notBlank(myString, "The string must not be blank");
              +	 * 
              + * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this + * method + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated character sequence (never {@code null} method for + * chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is blank + * @see #notBlank(CharSequence) + * + * @since 3.0 + */ + public static T notBlank(final T chars, final String message, final Object... values) { + JDKBackports.javaUtilObject_requireNonNull(chars, () -> HString.format(message, values)); + if (StringUtils.isBlank(chars)) { + throw new IllegalArgumentException(HString.format(message, values)); + } + return chars; + } + + /** + *

              + * Validate that the specified argument collection is neither {@code null} nor a + * size of zero (no elements); otherwise throwing an exception. + * + *

              +	 * Validate.notEmpty(myCollection);
              +	 * 
              + * + *

              + * The message in the exception is "The validated collection is + * empty". + *

              + * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @return the validated collection (never {@code null} method for chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IllegalArgumentException if the collection is empty + * @see #notEmpty(Collection, String, Object...) + */ + public static > T notEmpty(final T collection) { + return notEmpty(collection, DEFAULT_NOT_EMPTY_COLLECTION_EX_MESSAGE); + } + + // notNaN + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument map is neither {@code null} nor a size + * of zero (no elements); otherwise throwing an exception. + * + *

              +	 * Validate.notEmpty(myMap);
              +	 * 
              + * + *

              + * The message in the exception is "The validated map is empty". + *

              + * + * @param the map type + * @param map the map to check, validated not null by this method + * @return the validated map (never {@code null} method for chaining) + * @throws NullPointerException if the map is {@code null} + * @throws IllegalArgumentException if the map is empty + * @see #notEmpty(Map, String, Object...) + */ + public static > T notEmpty(final T map) { + return notEmpty(map, DEFAULT_NOT_EMPTY_MAP_EX_MESSAGE); + } + + /** + *

              + * Validate that the specified argument character sequence is neither + * {@code null} nor a length of zero (no characters); otherwise throwing an + * exception with the specified message. + * + *

              +	 * Validate.notEmpty(myString);
              +	 * 
              + * + *

              + * The message in the exception is "The validated character sequence is + * empty". + *

              + * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this + * method + * @return the validated character sequence (never {@code null} method for + * chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is empty + * @see #notEmpty(CharSequence, String, Object...) + */ + public static T notEmpty(final T chars) { + return notEmpty(chars, DEFAULT_NOT_EMPTY_CHAR_SEQUENCE_EX_MESSAGE); + } + + // finite + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument collection is neither {@code null} nor a + * size of zero (no elements); otherwise throwing an exception with the + * specified message. + * + *

              +	 * Validate.notEmpty(myCollection, "The collection must not be empty");
              +	 * 
              + * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param values the optional values for the formatted exception message, + * null array not recommended + * @return the validated collection (never {@code null} method for chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IllegalArgumentException if the collection is empty + * @see #notEmpty(Object[]) + */ + public static > T notEmpty(final T collection, final String message, + final Object... values) { + JDKBackports.javaUtilObject_requireNonNull(collection, () -> HString.format(message, values)); + if (collection.isEmpty()) { + throw new IllegalArgumentException(HString.format(message, values)); + } + return collection; + } + + /** + *

              + * Validate that the specified argument map is neither {@code null} nor a size + * of zero (no elements); otherwise throwing an exception with the specified + * message. + * + *

              +	 * Validate.notEmpty(myMap, "The map must not be empty");
              +	 * 
              + * + * @param the map type + * @param map the map to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated map (never {@code null} method for chaining) + * @throws NullPointerException if the map is {@code null} + * @throws IllegalArgumentException if the map is empty + * @see #notEmpty(Object[]) + */ + public static > T notEmpty(final T map, final String message, final Object... values) { + JDKBackports.javaUtilObject_requireNonNull(map, () -> HString.format(message, values)); + if (map.isEmpty()) { + throw new IllegalArgumentException(HString.format(message, values)); + } + return map; + } + + // inclusiveBetween + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument character sequence is neither + * {@code null} nor a length of zero (no characters); otherwise throwing an + * exception with the specified message. + * + *

              +	 * Validate.notEmpty(myString, "The string must not be empty");
              +	 * 
              + * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this + * method + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated character sequence (never {@code null} method for + * chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IllegalArgumentException if the character sequence is empty + * @see #notEmpty(CharSequence) + */ + public static T notEmpty(final T chars, final String message, final Object... values) { + JDKBackports.javaUtilObject_requireNonNull(chars, () -> HString.format(message, values)); + if (chars.length() == 0) { + throw new IllegalArgumentException(HString.format(message, values)); + } + return chars; + } + + /** + *

              + * Validate that the specified argument array is neither {@code null} nor a + * length of zero (no elements); otherwise throwing an exception. + * + *

              +	 * Validate.notEmpty(myArray);
              +	 * 
              + * + *

              + * The message in the exception is "The validated array is empty". + * + * @param the array type + * @param array the array to check, validated not null by this method + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if the array is empty + * @see #notEmpty(Object[], String, Object...) + */ + public static T[] notEmpty(final T[] array) { + return notEmpty(array, DEFAULT_NOT_EMPTY_ARRAY_EX_MESSAGE); + } + + /** + *

              + * Validate that the specified argument array is neither {@code null} nor a + * length of zero (no elements); otherwise throwing an exception with the + * specified message. + * + *

              +	 * Validate.notEmpty(myArray, "The array must not be empty");
              +	 * 
              + * + * @param the array type + * @param array the array to check, validated not null by this method + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated array (never {@code null} method for chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IllegalArgumentException if the array is empty + * @see #notEmpty(Object[]) + */ + public static T[] notEmpty(final T[] array, final String message, final Object... values) { + JDKBackports.javaUtilObject_requireNonNull(array, () -> HString.format(message, values)); + if (array.length == 0) { + throw new IllegalArgumentException(HString.format(message, values)); + } + return array; + } + + /** + *

              + * Validates that the specified argument is not {@code NaN}; otherwise throwing + * an exception. + *

              + * + *
              +	 * Validate.notNaN(myDouble);
              +	 * 
              + * + *

              + * The message of the exception is "The validated value is not a + * number". + *

              + * + * @param value the value to validate + * @throws IllegalArgumentException if the value is not a number + * @see #notNaN(double, java.lang.String, java.lang.Object...) + * + * @since 3.5 + */ + public static void notNaN(final double value) { + notNaN(value, DEFAULT_NOT_NAN_EX_MESSAGE); + } + + /** + *

              + * Validates that the specified argument is not {@code NaN}; otherwise throwing + * an exception with the specified message. + *

              + * + *
              +	 * Validate.notNaN(myDouble, "The value must be a number");
              +	 * 
              + * + * @param value the value to validate + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message + * @throws IllegalArgumentException if the value is not a number + * @see #notNaN(double) + * + * @since 3.5 + */ + public static void notNaN(final double value, final String message, final Object... values) { + if (Double.isNaN(value)) { + throw new IllegalArgumentException(HString.format(message, values)); + } + } + + /** + *

              + * Validate that the specified argument is not {@code null}; otherwise throwing + * an exception. + * + *

              +	 * Validate.notNull(myObject, "The object must not be null");
              +	 * 
              + * + *

              + * The message of the exception is "The validated object is null". + *

              + * + * @param the object type + * @param object the object to check + * @return the validated object (never {@code null} for method chaining) + * @throws NullPointerException if the object is {@code null} + * @see #notNull(Object, String, Object...) + */ + public static T notNull(final T object) { + return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE); + } + + // exclusiveBetween + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the specified argument is not {@code null}; otherwise throwing + * an exception with the specified message. + * + *

              +	 * Validate.notNull(myObject, "The object must not be null");
              +	 * 
              + * + * @param the object type + * @param object the object to check + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message + * @return the validated object (never {@code null} for method chaining) + * @throws NullPointerException if the object is {@code null} + * @see #notNull(Object) + */ + public static T notNull(final T object, final String message, final Object... values) { + return JDKBackports.javaUtilObject_requireNonNull(object, () -> HString.format(message, values)); + } + + /** + *

              + * Validates that the index is within the bounds of the argument collection; + * otherwise throwing an exception. + *

              + * + *
              +	 * Validate.validIndex(myCollection, 2);
              +	 * 
              + * + *

              + * If the index is invalid, then the message of the exception is "The + * validated collection index is invalid: " followed by the index. + *

              + * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @param index the index to check + * @return the validated collection (never {@code null} for method chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Collection, int, String, Object...) + * + * @since 3.0 + */ + public static > T validIndex(final T collection, final int index) { + return validIndex(collection, index, DEFAULT_VALID_INDEX_COLLECTION_EX_MESSAGE, Integer.valueOf(index)); + } + + /** + *

              + * Validates that the index is within the bounds of the argument character + * sequence; otherwise throwing an exception. + *

              + * + *
              +	 * Validate.validIndex(myStr, 2);
              +	 * 
              + * + *

              + * If the character sequence is {@code null}, then the message of the exception + * is "The validated object is null". + *

              + * + *

              + * If the index is invalid, then the message of the exception is "The + * validated character sequence index is invalid: " followed by the index. + *

              + * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this + * method + * @param index the index to check + * @return the validated character sequence (never {@code null} for method + * chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(CharSequence, int, String, Object...) + * + * @since 3.0 + */ + public static T validIndex(final T chars, final int index) { + return validIndex(chars, index, DEFAULT_VALID_INDEX_CHAR_SEQUENCE_EX_MESSAGE, Integer.valueOf(index)); + } + + /** + *

              + * Validates that the index is within the bounds of the argument collection; + * otherwise throwing an exception with the specified message. + *

              + * + *
              +	 * Validate.validIndex(myCollection, 2, "The collection index is invalid: ");
              +	 * 
              + * + *

              + * If the collection is {@code null}, then the message of the exception is + * "The validated object is null". + *

              + * + * @param the collection type + * @param collection the collection to check, validated not null by this method + * @param index the index to check + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param values the optional values for the formatted exception message, + * null array not recommended + * @return the validated collection (never {@code null} for chaining) + * @throws NullPointerException if the collection is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Collection, int) + * + * @since 3.0 + */ + public static > T validIndex(final T collection, final int index, final String message, + final Object... values) { + notNull(collection); + if (index < 0 || index >= collection.size()) { + throw new IndexOutOfBoundsException(HString.format(message, values)); + } + return collection; + } + + /** + *

              + * Validates that the index is within the bounds of the argument character + * sequence; otherwise throwing an exception with the specified message. + *

              + * + *
              +	 * Validate.validIndex(myStr, 2, "The string index is invalid: ");
              +	 * 
              + * + *

              + * If the character sequence is {@code null}, then the message of the exception + * is "The validated object is null". + *

              + * + * @param the character sequence type + * @param chars the character sequence to check, validated not null by this + * method + * @param index the index to check + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated character sequence (never {@code null} for method + * chaining) + * @throws NullPointerException if the character sequence is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(CharSequence, int) + * + * @since 3.0 + */ + public static T validIndex(final T chars, final int index, final String message, + final Object... values) { + notNull(chars); + if (index < 0 || index >= chars.length()) { + throw new IndexOutOfBoundsException(HString.format(message, values)); + } + return chars; + } + + /** + *

              + * Validates that the index is within the bounds of the argument array; + * otherwise throwing an exception. + *

              + * + *
              +	 * Validate.validIndex(myArray, 2);
              +	 * 
              + * + *

              + * If the array is {@code null}, then the message of the exception is "The + * validated object is null". + *

              + * + *

              + * If the index is invalid, then the message of the exception is "The + * validated array index is invalid: " followed by the index. + *

              + * + * @param the array type + * @param array the array to check, validated not null by this method + * @param index the index to check + * @return the validated array (never {@code null} for method chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Object[], int, String, Object...) + * + * @since 3.0 + */ + public static T[] validIndex(final T[] array, final int index) { + return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); + } + + // isInstanceOf + // --------------------------------------------------------------------------------- + + /** + *

              + * Validates that the index is within the bounds of the argument array; + * otherwise throwing an exception with the specified message. + *

              + * + *
              +	 * Validate.validIndex(myArray, 2, "The array index is invalid: ");
              +	 * 
              + * + *

              + * If the array is {@code null}, then the message of the exception is "The + * validated object is null". + *

              + * + * @param the array type + * @param array the array to check, validated not null by this method + * @param index the index to check + * @param message the {@link String#format(String, Object...)} exception message + * if invalid, not null + * @param values the optional values for the formatted exception message, null + * array not recommended + * @return the validated array (never {@code null} for method chaining) + * @throws NullPointerException if the array is {@code null} + * @throws IndexOutOfBoundsException if the index is invalid + * @see #validIndex(Object[], int) + * + * @since 3.0 + */ + public static T[] validIndex(final T[] array, final int index, final String message, final Object... values) { + notNull(array); + if (index < 0 || index >= array.length) { + throw new IndexOutOfBoundsException(HString.format(message, values)); + } + return array; + } + + /** + *

              + * Validate that the stateful condition is {@code true}; otherwise throwing an + * exception. This method is useful when validating according to an arbitrary + * boolean expression, such as validating a primitive number or using your own + * custom validation expression. + *

              + * + *
              +	 * Validate.validState(field > 0);
              +	 * Validate.validState(this.isOk());
              +	 * 
              + * + *

              + * The message of the exception is "The validated state is false". + *

              + * + * @param expression the boolean expression to check + * @throws IllegalStateException if expression is {@code false} + * @see #validState(boolean, String, Object...) + * + * @since 3.0 + */ + public static void validState(final boolean expression) { + if (!expression) { + throw new IllegalStateException(DEFAULT_VALID_STATE_EX_MESSAGE); + } + } + + // isAssignableFrom + // --------------------------------------------------------------------------------- + + /** + *

              + * Validate that the stateful condition is {@code true}; otherwise throwing an + * exception with the specified message. This method is useful when validating + * according to an arbitrary boolean expression, such as validating a primitive + * number or using your own custom validation expression. + *

              + * + *
              +	 * Validate.validState(this.isOk(), "The state is not OK: %s", myObject);
              +	 * 
              + * + * @param expression the boolean expression to check + * @param message the {@link String#format(String, Object...)} exception + * message if invalid, not null + * @param values the optional values for the formatted exception message, + * null array not recommended + * @throws IllegalStateException if expression is {@code false} + * @see #validState(boolean) + * + * @since 3.0 + */ + public static void validState(final boolean expression, final String message, final Object... values) { + if (!expression) { + throw new IllegalStateException(HString.format(message, values)); + } + } + + /** + * Constructor. This class should not normally be instantiated. + */ + public Validate() { + } } diff --git a/src/main/java/org/apache/commons/lang3/arch/Processor.java b/src/main/java/org/apache/commons/lang3/arch/Processor.java index 148a9dfe..523ed24a 100644 --- a/src/main/java/org/apache/commons/lang3/arch/Processor.java +++ b/src/main/java/org/apache/commons/lang3/arch/Processor.java @@ -159,16 +159,6 @@ public class Processor { return Arch.BIT_64 == arch; } - /** - * Checks if {@link Processor} is type of x86. - * - * @return {@code true}, if {@link Processor} is {@link Type#X86}, else - * {@code false}. - */ - public boolean isX86() { - return Type.X86 == type; - } - /** * Checks if {@link Processor} is type of Intel Itanium. * @@ -189,4 +179,14 @@ public class Processor { return Type.PPC == type; } + /** + * Checks if {@link Processor} is type of x86. + * + * @return {@code true}, if {@link Processor} is {@link Type#X86}, else + * {@code false}. + */ + public boolean isX86() { + return Type.X86 == type; + } + } diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java b/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java index 2a5b6f1f..8e6e6bc5 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringBuilder.java @@ -1058,6 +1058,21 @@ public class ToStringBuilder implements Builder { return this; } + /** + * Returns the String that was build as an object representation. The default + * implementation utilizes the {@link #toString()} implementation. + * + * @return the String {@code toString} + * + * @see #toString() + * + * @since 3.0 + */ + @Override + public String build() { + return toString(); + } + /** *

              * Returns the {@code Object} being output. @@ -1070,6 +1085,8 @@ public class ToStringBuilder implements Builder { return object; } + // ---------------------------------------------------------------------------- + /** *

              * Gets the {@code StringBuffer} being populated. @@ -1081,8 +1098,6 @@ public class ToStringBuilder implements Builder { return buffer; } - // ---------------------------------------------------------------------------- - /** *

              * Gets the {@code ToStringStyle} being used. @@ -1120,19 +1135,4 @@ public class ToStringBuilder implements Builder { } return this.getStringBuffer().toString(); } - - /** - * Returns the String that was build as an object representation. The default - * implementation utilizes the {@link #toString()} implementation. - * - * @return the String {@code toString} - * - * @see #toString() - * - * @since 3.0 - */ - @Override - public String build() { - return toString(); - } } diff --git a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java index 1c88f7fb..d8cbb34d 100644 --- a/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java +++ b/src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java @@ -73,6 +73,573 @@ import org.apache.commons.lang3.StringUtils; @SuppressWarnings("deprecation") // StringEscapeUtils public abstract class ToStringStyle implements Serializable { + /** + *

              + * Default {@code ToStringStyle}. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + *

              + */ + private static final class DefaultToStringStyle extends ToStringStyle { + + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 1L; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + DefaultToStringStyle() { + } + + /** + *

              + * Ensure {@code Singleton} after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return DEFAULT_STYLE; + } + + } + + /** + *

              + * {@code ToStringStyle} that outputs with JSON format. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + *

              + * + * @since 3.4 + * @see json.org + */ + private static final class JsonToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + private static final String FIELD_NAME_QUOTE = "\""; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + JsonToStringStyle() { + this.setUseClassName(false); + this.setUseIdentityHashCode(false); + + this.setContentStart("{"); + this.setContentEnd("}"); + + this.setArrayStart("["); + this.setArrayEnd("]"); + + this.setFieldSeparator(","); + this.setFieldNameValueSeparator(":"); + + this.setNullText("null"); + + this.setSummaryObjectStartText("\"<"); + this.setSummaryObjectEndText(">\""); + + this.setSizeStartText("\"\""); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final boolean[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final byte[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final char[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final double[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final float[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final int[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final long[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final Object value, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, value, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final Object[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + public void append(final StringBuffer buffer, final String fieldName, final short[] array, + final Boolean fullDetail) { + + if (fieldName == null) { + throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); + } + if (!isFullDetail(fullDetail)) { + throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); + } + + super.append(buffer, fieldName, array, fullDetail); + } + + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final char value) { + appendValueAsString(buffer, String.valueOf(value)); + } + + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { + if (coll != null && !coll.isEmpty()) { + buffer.append(getArrayStart()); + int i = 0; + for (final Object item : coll) { + appendDetail(buffer, fieldName, i++, item); + } + buffer.append(getArrayEnd()); + return; + } + + buffer.append(coll); + } + + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map map) { + if (map != null && !map.isEmpty()) { + buffer.append(getContentStart()); + + boolean firstItem = true; + for (final Entry entry : map.entrySet()) { + final String keyStr = Objects.toString(entry.getKey(), null); + if (keyStr != null) { + if (firstItem) { + firstItem = false; + } else { + appendFieldEnd(buffer, keyStr); + } + appendFieldStart(buffer, keyStr); + final Object value = entry.getValue(); + if (value == null) { + appendNullText(buffer, keyStr); + } else { + appendInternal(buffer, keyStr, value, true); + } + } + } + + buffer.append(getContentEnd()); + return; + } + + buffer.append(map); + } + + @Override + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) { + + if (value == null) { + appendNullText(buffer, fieldName); + return; + } + + if (value instanceof String || value instanceof Character) { + appendValueAsString(buffer, value.toString()); + return; + } + + if (value instanceof Number || value instanceof Boolean) { + buffer.append(value); + return; + } + + final String valueAsString = value.toString(); + if (isJsonObject(valueAsString) || isJsonArray(valueAsString)) { + buffer.append(value); + return; + } + + appendDetail(buffer, fieldName, valueAsString); + } + + @Override + protected void appendFieldStart(final StringBuffer buffer, final String fieldName) { + throw new UnsupportedOperationException("Not supported in TeaVM"); + /* + * if (fieldName == null) { throw new UnsupportedOperationException( + * "Field names are mandatory when using JsonToStringStyle"); } + * + * super.appendFieldStart(buffer, FIELD_NAME_QUOTE + + * StringEscapeUtils.escapeJson(fieldName) + FIELD_NAME_QUOTE); + */ + } + + /** + * Appends the given String enclosed in double-quotes to the given StringBuffer. + * + * @param buffer the StringBuffer to append the value to. + * @param value the value to append. + */ + private void appendValueAsString(final StringBuffer buffer, final String value) { + // buffer.append('"').append(StringEscapeUtils.escapeJson(value)).append('"'); + throw new UnsupportedOperationException("Not supported in TeaVM"); + } + + private boolean isJsonArray(final String valueAsString) { + return valueAsString.startsWith(getArrayStart()) && valueAsString.endsWith(getArrayEnd()); + } + + private boolean isJsonObject(final String valueAsString) { + return valueAsString.startsWith(getContentStart()) && valueAsString.endsWith(getContentEnd()); + } + + /** + *

              + * Ensure {@code Singleton} after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return JSON_STYLE; + } + + } + + /** + *

              + * {@code ToStringStyle} that outputs on multiple lines. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + *

              + */ + private static final class MultiLineToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + MultiLineToStringStyle() { + this.setContentStart("["); + this.setFieldSeparator(System.lineSeparator() + " "); + this.setFieldSeparatorAtStart(true); + this.setContentEnd(System.lineSeparator() + "]"); + } + + /** + *

              + * Ensure {@code Singleton} after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return MULTI_LINE_STYLE; + } + + } + + /** + *

              + * {@code ToStringStyle} that does not print out the classname and identity hash + * code but prints content start and field names. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + *

              + */ + private static final class NoClassNameToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + NoClassNameToStringStyle() { + this.setUseClassName(false); + this.setUseIdentityHashCode(false); + } + + /** + *

              + * Ensure {@code Singleton} after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return NO_CLASS_NAME_STYLE; + } + + } + + /** + *

              + * {@code ToStringStyle} that does not print out the field names. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + */ + private static final class NoFieldNameToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + NoFieldNameToStringStyle() { + this.setUseFieldNames(false); + } + + /** + *

              + * Ensure {@code Singleton} after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return NO_FIELD_NAMES_STYLE; + } + + } + + /** + *

              + * {@code ToStringStyle} that prints out the short class name and no identity + * hashcode. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + *

              + */ + private static final class ShortPrefixToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + ShortPrefixToStringStyle() { + this.setUseShortClassName(true); + this.setUseIdentityHashCode(false); + } + + /** + *

              + * Ensure Singleton after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return SHORT_PREFIX_STYLE; + } + + } + + /** + *

              + * {@code ToStringStyle} that does not print out the classname, identity + * hashcode, content start or field name. + *

              + * + *

              + * This is an inner class rather than using {@code StandardToStringStyle} to + * ensure its immutability. + *

              + */ + private static final class SimpleToStringStyle extends ToStringStyle { + + private static final long serialVersionUID = 1L; + + /** + *

              + * Constructor. + *

              + * + *

              + * Use the static constant rather than instantiating. + *

              + */ + SimpleToStringStyle() { + this.setUseClassName(false); + this.setUseIdentityHashCode(false); + this.setUseFieldNames(false); + this.setContentStart(StringUtils.EMPTY); + this.setContentEnd(StringUtils.EMPTY); + } + + /** + *

              + * Ensure Singleton after serialization. + *

              + * + * @return the singleton + */ + private Object readResolve() { + return SIMPLE_STYLE; + } + + } + /** * Serialization version ID. */ @@ -314,11 +881,15 @@ public abstract class ToStringStyle implements Serializable { */ private boolean arrayContentDetail = true; + // ---------------------------------------------------------------------------- + /** * The array end {@code '}'}. */ private String arrayEnd = "}"; + // ---------------------------------------------------------------------------- + /** * The value to use when fullDetail is {@code null}, the default value is * {@code true}. @@ -345,13 +916,13 @@ public abstract class ToStringStyle implements Serializable { */ private String summaryObjectStartText = "<"; + // ---------------------------------------------------------------------------- + /** * The summary object text start {@code '>'}. */ private String summaryObjectEndText = ">"; - // ---------------------------------------------------------------------------- - /** *

              * Constructor. @@ -360,111 +931,316 @@ public abstract class ToStringStyle implements Serializable { protected ToStringStyle() { } + /** + *

              + * Append to the {@code toString} a {@code boolean} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final boolean value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code boolean} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final boolean[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code byte} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final byte value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code byte} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the {@code toString} + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final byte[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code char} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final char value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + // ---------------------------------------------------------------------------- /** *

              - * Append to the {@code toString} the superclass toString. - *

              - *

              - * NOTE: It assumes that the toString has been created from the same - * ToStringStyle. + * Append to the {@code toString} a {@code char} array. *

              * - *

              - * A {@code null} {@code superToString} is ignored. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param superToString the {@code super.toString()} - * @since 2.0 + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the {@code toString} + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides */ - public void appendSuper(final StringBuffer buffer, final String superToString) { - appendToString(buffer, superToString); + public void append(final StringBuffer buffer, final String fieldName, final char[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); } /** *

              - * Append to the {@code toString} another toString. - *

              - *

              - * NOTE: It assumes that the toString has been created from the same - * ToStringStyle. + * Append to the {@code toString} a {@code double} value. *

              * - *

              - * A {@code null} {@code toString} is ignored. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param toString the additional {@code toString} - * @since 2.0 + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} */ - public void appendToString(final StringBuffer buffer, final String toString) { - if (toString != null) { - final int pos1 = toString.indexOf(contentStart) + contentStart.length(); - final int pos2 = toString.lastIndexOf(contentEnd); - if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) { - if (fieldSeparatorAtStart) { - removeLastFieldSeparator(buffer); - } - buffer.append(toString, pos1, pos2); - appendFieldSeparator(buffer); - } - } - } - - /** - *

              - * Append to the {@code toString} the start of data indicator. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param object the {@code Object} to build a {@code toString} for - */ - public void appendStart(final StringBuffer buffer, final Object object) { - if (object != null) { - appendClassName(buffer, object); - appendIdentityHashCode(buffer, object); - appendContentStart(buffer); - if (fieldSeparatorAtStart) { - appendFieldSeparator(buffer); - } - } - } - - /** - *

              - * Append to the {@code toString} the end of data indicator. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param object the {@code Object} to build a {@code toString} for. - */ - public void appendEnd(final StringBuffer buffer, final Object object) { - if (!this.fieldSeparatorAtEnd) { - removeLastFieldSeparator(buffer); - } - appendContentEnd(buffer); - unregister(object); - } - - /** - *

              - * Remove the last field separator from the buffer. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @since 2.0 - */ - protected void removeLastFieldSeparator(final StringBuffer buffer) { - if (StringUtils.endsWith(buffer, fieldSeparator)) { - buffer.setLength(buffer.length() - fieldSeparator.length()); - } + public void append(final StringBuffer buffer, final String fieldName, final double value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); } // ---------------------------------------------------------------------------- + /** + *

              + * Append to the {@code toString} a {@code double} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final double[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code float} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final float value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code float} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final float[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} an {@code int} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final int value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} an {@code int} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the {@code toString} + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final int[] array, final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code long} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final long value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code long} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the {@code toString} + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final long[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + /** *

              * Append to the {@code toString} an {@code Object} value, printing the full @@ -491,6 +1267,575 @@ public abstract class ToStringStyle implements Serializable { appendFieldEnd(buffer, fieldName); } + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} an {@code Object} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the toString + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final Object[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} a {@code short} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param value the value to add to the {@code toString} + */ + public void append(final StringBuffer buffer, final String fieldName, final short value) { + appendFieldStart(buffer, fieldName); + appendDetail(buffer, fieldName, value); + appendFieldEnd(buffer, fieldName); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code short} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + * @param array the array to add to the {@code toString} + * @param fullDetail {@code true} for detail, {@code false} for summary info, + * {@code null} for style decides + */ + public void append(final StringBuffer buffer, final String fieldName, final short[] array, + final Boolean fullDetail) { + appendFieldStart(buffer, fieldName); + + if (array == null) { + appendNullText(buffer, fieldName); + + } else if (isFullDetail(fullDetail)) { + appendDetail(buffer, fieldName, array); + + } else { + appendSummary(buffer, fieldName, array); + } + + appendFieldEnd(buffer, fieldName); + } + + /** + *

              + * Append to the {@code toString} the class name. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param object the {@code Object} whose name to output + */ + protected void appendClassName(final StringBuffer buffer, final Object object) { + if (useClassName && object != null) { + register(object); + if (useShortClassName) { + buffer.append(getShortClassName(object.getClass())); + } else { + buffer.append(object.getClass().getName()); + } + } + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} the content end. + *

              + * + * @param buffer the {@code StringBuffer} to populate + */ + protected void appendContentEnd(final StringBuffer buffer) { + buffer.append(contentEnd); + } + + /** + *

              + * Append to the {@code toString} the content start. + *

              + * + * @param buffer the {@code StringBuffer} to populate + */ + protected void appendContentStart(final StringBuffer buffer) { + buffer.append(contentStart); + } + + /** + *

              + * Append to the {@code toString} an {@code Object} value that has been detected + * to participate in a cycle. This implementation will print the standard string + * value of the value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString}, not {@code null} + * + * @since 2.2 + */ + protected void appendCyclicObject(final StringBuffer buffer, final String fieldName, final Object value) { + ObjectUtils.identityToString(buffer, value); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code boolean} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of a {@code boolean} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

              + * Append to the {@code toString} a {@code byte} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of a {@code byte} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code char} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final char value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of a {@code char} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final char[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

              + * Append to the {@code toString} a {@code Collection}. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param coll the {@code Collection} to add to the {@code toString}, not + * {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { + buffer.append(coll); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code double} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final double value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of a {@code double} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final double[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

              + * Append to the {@code toString} a {@code float} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final float value) { + buffer.append(value); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} the detail of a {@code float} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final float[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

              + * Append to the {@code toString} an {@code int} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final int value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of an {@code Object} array item. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param i the array item index to add + * @param item the array item to add + * @since 3.11 + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final int i, final Object item) { + if (i > 0) { + buffer.append(arraySeparator); + } + if (item == null) { + appendNullText(buffer, fieldName); + } else { + appendInternal(buffer, fieldName, item, arrayContentDetail); + } + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} the detail of an {@code int} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final int[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

              + * Append to the {@code toString} a {@code long} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final long value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of a {@code long} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final long[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code Map}. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param map the {@code Map} to add to the {@code toString}, not + * {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map map) { + buffer.append(map); + } + + /** + *

              + * Append to the {@code toString} an {@code Object} value, printing the full + * detail of the {@code Object}. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of an {@code Object} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + final Object item = array[i]; + appendDetail(buffer, fieldName, i, item); + } + buffer.append(arrayEnd); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} a {@code short} value. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param value the value to add to the {@code toString} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final short value) { + buffer.append(value); + } + + /** + *

              + * Append to the {@code toString} the detail of a {@code short} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendDetail(final StringBuffer buffer, final String fieldName, final short[] array) { + buffer.append(arrayStart); + for (int i = 0; i < array.length; i++) { + if (i > 0) { + buffer.append(arraySeparator); + } + appendDetail(buffer, fieldName, array[i]); + } + buffer.append(arrayEnd); + } + + /** + *

              + * Append to the {@code toString} the end of data indicator. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param object the {@code Object} to build a {@code toString} for. + */ + public void appendEnd(final StringBuffer buffer, final Object object) { + if (!this.fieldSeparatorAtEnd) { + removeLastFieldSeparator(buffer); + } + appendContentEnd(buffer); + unregister(object); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} the field end. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + */ + protected void appendFieldEnd(final StringBuffer buffer, final String fieldName) { + appendFieldSeparator(buffer); + } + + /** + *

              + * Append to the {@code toString} the field separator. + *

              + * + * @param buffer the {@code StringBuffer} to populate + */ + protected void appendFieldSeparator(final StringBuffer buffer) { + buffer.append(fieldSeparator); + } + + /** + *

              + * Append to the {@code toString} the field start. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name + */ + protected void appendFieldStart(final StringBuffer buffer, final String fieldName) { + if (useFieldNames && fieldName != null) { + buffer.append(fieldName); + buffer.append(fieldNameValueSeparator); + } + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append the {@link System#identityHashCode(java.lang.Object)}. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param object the {@code Object} whose id to output + */ + protected void appendIdentityHashCode(final StringBuffer buffer, final Object object) { + if (this.isUseIdentityHashCode() && object != null) { + register(object); + buffer.append('@'); + buffer.append(Integer.toHexString(System.identityHashCode(object))); + } + } + /** *

              * Append to the {@code toString} an {@code Object}, correctly interpreting its @@ -617,61 +1962,130 @@ public abstract class ToStringStyle implements Serializable { /** *

              - * Append to the {@code toString} an {@code Object} value that has been detected - * to participate in a cycle. This implementation will print the standard string - * value of the value. + * Append to the {@code toString} an indicator for {@code null}. + *

              + * + *

              + * The default indicator is {@code '<null>'}. *

              * * @param buffer the {@code StringBuffer} to populate * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString}, not {@code null} - * - * @since 2.2 */ - protected void appendCyclicObject(final StringBuffer buffer, final String fieldName, final Object value) { - ObjectUtils.identityToString(buffer, value); + protected void appendNullText(final StringBuffer buffer, final String fieldName) { + buffer.append(nullText); + } + + // ---------------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} the start of data indicator. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param object the {@code Object} to build a {@code toString} for + */ + public void appendStart(final StringBuffer buffer, final Object object) { + if (object != null) { + appendClassName(buffer, object); + appendIdentityHashCode(buffer, object); + appendContentStart(buffer); + if (fieldSeparatorAtStart) { + appendFieldSeparator(buffer); + } + } } /** *

              - * Append to the {@code toString} an {@code Object} value, printing the full - * detail of the {@code Object}. + * Append to the {@code toString} a summary of a {@code boolean} array. *

              * * @param buffer the {@code StringBuffer} to populate * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString}, not {@code null} + * @param array the array to add to the {@code toString}, not {@code null} */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) { - buffer.append(value); + protected void appendSummary(final StringBuffer buffer, final String fieldName, final boolean[] array) { + appendSummarySize(buffer, fieldName, array.length); } /** *

              - * Append to the {@code toString} a {@code Collection}. + * Append to the {@code toString} a summary of a {@code byte} array. *

              * * @param buffer the {@code StringBuffer} to populate * @param fieldName the field name, typically not used as already appended - * @param coll the {@code Collection} to add to the {@code toString}, not - * {@code null} + * @param array the array to add to the {@code toString}, not {@code null} */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { - buffer.append(coll); + protected void appendSummary(final StringBuffer buffer, final String fieldName, final byte[] array) { + appendSummarySize(buffer, fieldName, array.length); } /** *

              - * Append to the {@code toString} a {@code Map}. + * Append to the {@code toString} a summary of a {@code char} array. *

              * * @param buffer the {@code StringBuffer} to populate * @param fieldName the field name, typically not used as already appended - * @param map the {@code Map} to add to the {@code toString}, not - * {@code null} + * @param array the array to add to the {@code toString}, not {@code null} */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map map) { - buffer.append(map); + protected void appendSummary(final StringBuffer buffer, final String fieldName, final char[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + /** + *

              + * Append to the {@code toString} a summary of a {@code double} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendSummary(final StringBuffer buffer, final String fieldName, final double[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + /** + *

              + * Append to the {@code toString} a summary of a {@code float} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendSummary(final StringBuffer buffer, final String fieldName, final float[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + /** + *

              + * Append to the {@code toString} a summary of an {@code int} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendSummary(final StringBuffer buffer, final String fieldName, final int[] array) { + appendSummarySize(buffer, fieldName, array.length); + } + + /** + *

              + * Append to the {@code toString} a summary of a {@code long} array. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} + */ + protected void appendSummary(final StringBuffer buffer, final String fieldName, final long[] array) { + appendSummarySize(buffer, fieldName, array.length); } /** @@ -690,336 +2104,6 @@ public abstract class ToStringStyle implements Serializable { buffer.append(summaryObjectEndText); } - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code long} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final long value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code long} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final long value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} an {@code int} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final int value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} an {@code int} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final int value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code short} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final short value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code short} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final short value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code byte} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final byte value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code byte} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code char} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final char value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code char} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final char value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code double} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final double value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code double} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final double value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code float} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final float value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code float} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final float value) { - buffer.append(value); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code boolean} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param value the value to add to the {@code toString} - */ - public void append(final StringBuffer buffer, final String fieldName, final boolean value) { - appendFieldStart(buffer, fieldName); - appendDetail(buffer, fieldName, value); - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} a {@code boolean} value. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param value the value to add to the {@code toString} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean value) { - buffer.append(value); - } - - /** - *

              - * Append to the {@code toString} an {@code Object} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the toString - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final Object[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} the detail of an {@code Object} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - final Object item = array[i]; - appendDetail(buffer, fieldName, i, item); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} the detail of an {@code Object} array item. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param i the array item index to add - * @param item the array item to add - * @since 3.11 - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final int i, final Object item) { - if (i > 0) { - buffer.append(arraySeparator); - } - if (item == null) { - appendNullText(buffer, fieldName); - } else { - appendInternal(buffer, fieldName, item, arrayContentDetail); - } - } - - /** - *

              - * Append to the {@code toString} the detail of an array type. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - * @since 2.0 - */ - protected void reflectionAppendArrayDetail(final StringBuffer buffer, final String fieldName, final Object array) { - buffer.append(arrayStart); - final int length = Array.getLength(array); - for (int i = 0; i < length; i++) { - final Object item = Array.get(array, i); - appendDetail(buffer, fieldName, i, item); - } - buffer.append(arrayEnd); - } - /** *

              * Append to the {@code toString} a summary of an {@code Object} array. @@ -1033,181 +2117,6 @@ public abstract class ToStringStyle implements Serializable { appendSummarySize(buffer, fieldName, array.length); } - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code long} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the {@code toString} - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final long[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code long} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final long[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of a {@code long} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final long[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} an {@code int} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the {@code toString} - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final int[] array, final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of an {@code int} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final int[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of an {@code int} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final int[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code short} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the {@code toString} - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final short[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code short} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final short[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - /** *

              * Append to the {@code toString} a summary of a {@code short} array. @@ -1221,433 +2130,10 @@ public abstract class ToStringStyle implements Serializable { appendSummarySize(buffer, fieldName, array.length); } - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code byte} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the {@code toString} - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final byte[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code byte} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final byte[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of a {@code byte} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final byte[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code char} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the {@code toString} - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final char[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code char} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final char[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of a {@code char} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final char[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code double} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the toString - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final double[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code double} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final double[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of a {@code double} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final double[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code float} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the toString - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final float[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code float} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final float[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of a {@code float} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final float[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} a {@code boolean} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - * @param array the array to add to the toString - * @param fullDetail {@code true} for detail, {@code false} for summary info, - * {@code null} for style decides - */ - public void append(final StringBuffer buffer, final String fieldName, final boolean[] array, - final Boolean fullDetail) { - appendFieldStart(buffer, fieldName); - - if (array == null) { - appendNullText(buffer, fieldName); - - } else if (isFullDetail(fullDetail)) { - appendDetail(buffer, fieldName, array); - - } else { - appendSummary(buffer, fieldName, array); - } - - appendFieldEnd(buffer, fieldName); - } - - /** - *

              - * Append to the {@code toString} the detail of a {@code boolean} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendDetail(final StringBuffer buffer, final String fieldName, final boolean[] array) { - buffer.append(arrayStart); - for (int i = 0; i < array.length; i++) { - if (i > 0) { - buffer.append(arraySeparator); - } - appendDetail(buffer, fieldName, array[i]); - } - buffer.append(arrayEnd); - } - - /** - *

              - * Append to the {@code toString} a summary of a {@code boolean} array. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - * @param array the array to add to the {@code toString}, not {@code null} - */ - protected void appendSummary(final StringBuffer buffer, final String fieldName, final boolean[] array) { - appendSummarySize(buffer, fieldName, array.length); - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * Append to the {@code toString} the class name. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param object the {@code Object} whose name to output - */ - protected void appendClassName(final StringBuffer buffer, final Object object) { - if (useClassName && object != null) { - register(object); - if (useShortClassName) { - buffer.append(getShortClassName(object.getClass())); - } else { - buffer.append(object.getClass().getName()); - } - } - } - - /** - *

              - * Append the {@link System#identityHashCode(java.lang.Object)}. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param object the {@code Object} whose id to output - */ - protected void appendIdentityHashCode(final StringBuffer buffer, final Object object) { - if (this.isUseIdentityHashCode() && object != null) { - register(object); - buffer.append('@'); - buffer.append(Integer.toHexString(System.identityHashCode(object))); - } - } - - /** - *

              - * Append to the {@code toString} the content start. - *

              - * - * @param buffer the {@code StringBuffer} to populate - */ - protected void appendContentStart(final StringBuffer buffer) { - buffer.append(contentStart); - } - - /** - *

              - * Append to the {@code toString} the content end. - *

              - * - * @param buffer the {@code StringBuffer} to populate - */ - protected void appendContentEnd(final StringBuffer buffer) { - buffer.append(contentEnd); - } - - /** - *

              - * Append to the {@code toString} an indicator for {@code null}. - *

              - * - *

              - * The default indicator is {@code '<null>'}. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - */ - protected void appendNullText(final StringBuffer buffer, final String fieldName) { - buffer.append(nullText); - } - - /** - *

              - * Append to the {@code toString} the field separator. - *

              - * - * @param buffer the {@code StringBuffer} to populate - */ - protected void appendFieldSeparator(final StringBuffer buffer) { - buffer.append(fieldSeparator); - } - - /** - *

              - * Append to the {@code toString} the field start. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name - */ - protected void appendFieldStart(final StringBuffer buffer, final String fieldName) { - if (useFieldNames && fieldName != null) { - buffer.append(fieldName); - buffer.append(fieldNameValueSeparator); - } - } - - /** - *

              - * Append to the {@code toString} the field end. - *

              - * - * @param buffer the {@code StringBuffer} to populate - * @param fieldName the field name, typically not used as already appended - */ - protected void appendFieldEnd(final StringBuffer buffer, final String fieldName) { - appendFieldSeparator(buffer); - } + // Setters and getters for the customizable parts of the style + // These methods are not expected to be overridden, except to make public + // (They are not public so that immutable subclasses can be written) + // --------------------------------------------------------------------- /** *

              @@ -1677,6 +2163,291 @@ public abstract class ToStringStyle implements Serializable { buffer.append(sizeEndText); } + /** + *

              + * Append to the {@code toString} the superclass toString. + *

              + *

              + * NOTE: It assumes that the toString has been created from the same + * ToStringStyle. + *

              + * + *

              + * A {@code null} {@code superToString} is ignored. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param superToString the {@code super.toString()} + * @since 2.0 + */ + public void appendSuper(final StringBuffer buffer, final String superToString) { + appendToString(buffer, superToString); + } + + // --------------------------------------------------------------------- + + /** + *

              + * Append to the {@code toString} another toString. + *

              + *

              + * NOTE: It assumes that the toString has been created from the same + * ToStringStyle. + *

              + * + *

              + * A {@code null} {@code toString} is ignored. + *

              + * + * @param buffer the {@code StringBuffer} to populate + * @param toString the additional {@code toString} + * @since 2.0 + */ + public void appendToString(final StringBuffer buffer, final String toString) { + if (toString != null) { + final int pos1 = toString.indexOf(contentStart) + contentStart.length(); + final int pos2 = toString.lastIndexOf(contentEnd); + if (pos1 != pos2 && pos1 >= 0 && pos2 >= 0) { + if (fieldSeparatorAtStart) { + removeLastFieldSeparator(buffer); + } + buffer.append(toString, pos1, pos2); + appendFieldSeparator(buffer); + } + } + } + + /** + *

              + * Gets the array end text. + *

              + * + * @return the current array end text + */ + protected String getArrayEnd() { + return arrayEnd; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets the array separator text. + *

              + * + * @return the current array separator text + */ + protected String getArraySeparator() { + return arraySeparator; + } + + /** + *

              + * Gets the array start text. + *

              + * + * @return the current array start text + */ + protected String getArrayStart() { + return arrayStart; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets the content end text. + *

              + * + * @return the current content end text + */ + protected String getContentEnd() { + return contentEnd; + } + + /** + *

              + * Gets the content start text. + *

              + * + * @return the current content start text + */ + protected String getContentStart() { + return contentStart; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets the field name value separator text. + *

              + * + * @return the current field name value separator text + */ + protected String getFieldNameValueSeparator() { + return fieldNameValueSeparator; + } + + /** + *

              + * Gets the field separator text. + *

              + * + * @return the current field separator text + */ + protected String getFieldSeparator() { + return fieldSeparator; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets the text to output when {@code null} found. + *

              + * + * @return the current text to output when null found + */ + protected String getNullText() { + return nullText; + } + + /** + *

              + * Gets the short class name for a class. + *

              + * + *

              + * The short class name is the classname excluding the package name. + *

              + * + * @param cls the {@code Class} to get the short name of + * @return the short name + */ + protected String getShortClassName(final Class cls) { + return cls.getSimpleName(); + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets the end text to output when a {@code Collection}, {@code Map} or array + * size is output. + *

              + * + *

              + * This is output after the size value. + *

              + * + * @return the current end of size text + */ + protected String getSizeEndText() { + return sizeEndText; + } + + /** + *

              + * Gets the start text to output when a {@code Collection}, {@code Map} or array + * size is output. + *

              + * + *

              + * This is output before the size value. + *

              + * + * @return the current start of size text + */ + protected String getSizeStartText() { + return sizeStartText; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets the end text to output when an {@code Object} is output in summary mode. + *

              + * + *

              + * This is output after the size value. + *

              + * + * @return the current end of summary text + */ + protected String getSummaryObjectEndText() { + return summaryObjectEndText; + } + + /** + *

              + * Gets the start text to output when an {@code Object} is output in summary + * mode. + *

              + * + *

              + * This is output before the size value. + *

              + * + * @return the current start of summary text + */ + protected String getSummaryObjectStartText() { + return summaryObjectStartText; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets whether to output array content detail. + *

              + * + * @return the current array content detail setting + */ + protected boolean isArrayContentDetail() { + return arrayContentDetail; + } + + /** + *

              + * Gets whether to use full detail when the caller doesn't specify. + *

              + * + * @return the current defaultFullDetail flag + */ + protected boolean isDefaultFullDetail() { + return defaultFullDetail; + } + + // --------------------------------------------------------------------- + + /** + *

              + * Gets whether the field separator should be added at the end of each buffer. + *

              + * + * @return fieldSeparatorAtEnd flag + * @since 2.0 + */ + protected boolean isFieldSeparatorAtEnd() { + return fieldSeparatorAtEnd; + } + + /** + *

              + * Gets whether the field separator should be added at the start of each buffer. + *

              + * + * @return the fieldSeparatorAtStart flag + * @since 2.0 + */ + protected boolean isFieldSeparatorAtStart() { + return fieldSeparatorAtStart; + } + + // --------------------------------------------------------------------- + /** *

              * Is this field to be output in full detail. @@ -1700,27 +2471,6 @@ public abstract class ToStringStyle implements Serializable { return fullDetailRequest.booleanValue(); } - /** - *

              - * Gets the short class name for a class. - *

              - * - *

              - * The short class name is the classname excluding the package name. - *

              - * - * @param cls the {@code Class} to get the short name of - * @return the short name - */ - protected String getShortClassName(final Class cls) { - return cls.getSimpleName(); - } - - // Setters and getters for the customizable parts of the style - // These methods are not expected to be overridden, except to make public - // (They are not public so that immutable subclasses can be written) - // --------------------------------------------------------------------- - /** *

              * Gets whether to use the class name. @@ -1732,15 +2482,28 @@ public abstract class ToStringStyle implements Serializable { return useClassName; } + // --------------------------------------------------------------------- + /** *

              - * Sets whether to use the class name. + * Gets whether to use the field names passed in. *

              * - * @param useClassName the new useClassName flag + * @return the current useFieldNames flag */ - protected void setUseClassName(final boolean useClassName) { - this.useClassName = useClassName; + protected boolean isUseFieldNames() { + return useFieldNames; + } + + /** + *

              + * Gets whether to use the identity hash code. + *

              + * + * @return the current useIdentityHashCode flag + */ + protected boolean isUseIdentityHashCode() { + return useIdentityHashCode; } // --------------------------------------------------------------------- @@ -1759,99 +2522,38 @@ public abstract class ToStringStyle implements Serializable { /** *

              - * Sets whether to output short or long class names. + * Append to the {@code toString} the detail of an array type. *

              * - * @param useShortClassName the new useShortClassName flag + * @param buffer the {@code StringBuffer} to populate + * @param fieldName the field name, typically not used as already appended + * @param array the array to add to the {@code toString}, not {@code null} * @since 2.0 */ - protected void setUseShortClassName(final boolean useShortClassName) { - this.useShortClassName = useShortClassName; + protected void reflectionAppendArrayDetail(final StringBuffer buffer, final String fieldName, final Object array) { + buffer.append(arrayStart); + final int length = Array.getLength(array); + for (int i = 0; i < length; i++) { + final Object item = Array.get(array, i); + appendDetail(buffer, fieldName, i, item); + } + buffer.append(arrayEnd); } // --------------------------------------------------------------------- /** *

              - * Gets whether to use the identity hash code. + * Remove the last field separator from the buffer. *

              * - * @return the current useIdentityHashCode flag + * @param buffer the {@code StringBuffer} to populate + * @since 2.0 */ - protected boolean isUseIdentityHashCode() { - return useIdentityHashCode; - } - - /** - *

              - * Sets whether to use the identity hash code. - *

              - * - * @param useIdentityHashCode the new useIdentityHashCode flag - */ - protected void setUseIdentityHashCode(final boolean useIdentityHashCode) { - this.useIdentityHashCode = useIdentityHashCode; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets whether to use the field names passed in. - *

              - * - * @return the current useFieldNames flag - */ - protected boolean isUseFieldNames() { - return useFieldNames; - } - - /** - *

              - * Sets whether to use the field names passed in. - *

              - * - * @param useFieldNames the new useFieldNames flag - */ - protected void setUseFieldNames(final boolean useFieldNames) { - this.useFieldNames = useFieldNames; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets whether to use full detail when the caller doesn't specify. - *

              - * - * @return the current defaultFullDetail flag - */ - protected boolean isDefaultFullDetail() { - return defaultFullDetail; - } - - /** - *

              - * Sets whether to use full detail when the caller doesn't specify. - *

              - * - * @param defaultFullDetail the new defaultFullDetail flag - */ - protected void setDefaultFullDetail(final boolean defaultFullDetail) { - this.defaultFullDetail = defaultFullDetail; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets whether to output array content detail. - *

              - * - * @return the current array content detail setting - */ - protected boolean isArrayContentDetail() { - return arrayContentDetail; + protected void removeLastFieldSeparator(final StringBuffer buffer) { + if (StringUtils.endsWith(buffer, fieldSeparator)) { + buffer.setLength(buffer.length() - fieldSeparator.length()); + } } /** @@ -1867,48 +2569,6 @@ public abstract class ToStringStyle implements Serializable { // --------------------------------------------------------------------- - /** - *

              - * Gets the array start text. - *

              - * - * @return the current array start text - */ - protected String getArrayStart() { - return arrayStart; - } - - /** - *

              - * Sets the array start text. - *

              - * - *

              - * {@code null} is accepted, but will be converted to an empty String. - *

              - * - * @param arrayStart the new array start text - */ - protected void setArrayStart(String arrayStart) { - if (arrayStart == null) { - arrayStart = StringUtils.EMPTY; - } - this.arrayStart = arrayStart; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets the array end text. - *

              - * - * @return the current array end text - */ - protected String getArrayEnd() { - return arrayEnd; - } - /** *

              * Sets the array end text. @@ -1927,19 +2587,6 @@ public abstract class ToStringStyle implements Serializable { this.arrayEnd = arrayEnd; } - // --------------------------------------------------------------------- - - /** - *

              - * Gets the array separator text. - *

              - * - * @return the current array separator text - */ - protected String getArraySeparator() { - return arraySeparator; - } - /** *

              * Sets the array separator text. @@ -1962,44 +2609,20 @@ public abstract class ToStringStyle implements Serializable { /** *

              - * Gets the content start text. - *

              - * - * @return the current content start text - */ - protected String getContentStart() { - return contentStart; - } - - /** - *

              - * Sets the content start text. + * Sets the array start text. *

              * *

              * {@code null} is accepted, but will be converted to an empty String. *

              * - * @param contentStart the new content start text + * @param arrayStart the new array start text */ - protected void setContentStart(String contentStart) { - if (contentStart == null) { - contentStart = StringUtils.EMPTY; + protected void setArrayStart(String arrayStart) { + if (arrayStart == null) { + arrayStart = StringUtils.EMPTY; } - this.contentStart = contentStart; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets the content end text. - *

              - * - * @return the current content end text - */ - protected String getContentEnd() { - return contentEnd; + this.arrayStart = arrayStart; } /** @@ -2024,15 +2647,35 @@ public abstract class ToStringStyle implements Serializable { /** *

              - * Gets the field name value separator text. + * Sets the content start text. *

              * - * @return the current field name value separator text + *

              + * {@code null} is accepted, but will be converted to an empty String. + *

              + * + * @param contentStart the new content start text */ - protected String getFieldNameValueSeparator() { - return fieldNameValueSeparator; + protected void setContentStart(String contentStart) { + if (contentStart == null) { + contentStart = StringUtils.EMPTY; + } + this.contentStart = contentStart; } + /** + *

              + * Sets whether to use full detail when the caller doesn't specify. + *

              + * + * @param defaultFullDetail the new defaultFullDetail flag + */ + protected void setDefaultFullDetail(final boolean defaultFullDetail) { + this.defaultFullDetail = defaultFullDetail; + } + + // --------------------------------------------------------------------- + /** *

              * Sets the field name value separator text. @@ -2051,19 +2694,6 @@ public abstract class ToStringStyle implements Serializable { this.fieldNameValueSeparator = fieldNameValueSeparator; } - // --------------------------------------------------------------------- - - /** - *

              - * Gets the field separator text. - *

              - * - * @return the current field separator text - */ - protected String getFieldSeparator() { - return fieldSeparator; - } - /** *

              * Sets the field separator text. @@ -2086,14 +2716,14 @@ public abstract class ToStringStyle implements Serializable { /** *

              - * Gets whether the field separator should be added at the start of each buffer. + * Sets whether the field separator should be added at the end of each buffer. *

              * - * @return the fieldSeparatorAtStart flag + * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag * @since 2.0 */ - protected boolean isFieldSeparatorAtStart() { - return fieldSeparatorAtStart; + protected void setFieldSeparatorAtEnd(final boolean fieldSeparatorAtEnd) { + this.fieldSeparatorAtEnd = fieldSeparatorAtEnd; } /** @@ -2110,43 +2740,6 @@ public abstract class ToStringStyle implements Serializable { // --------------------------------------------------------------------- - /** - *

              - * Gets whether the field separator should be added at the end of each buffer. - *

              - * - * @return fieldSeparatorAtEnd flag - * @since 2.0 - */ - protected boolean isFieldSeparatorAtEnd() { - return fieldSeparatorAtEnd; - } - - /** - *

              - * Sets whether the field separator should be added at the end of each buffer. - *

              - * - * @param fieldSeparatorAtEnd the fieldSeparatorAtEnd flag - * @since 2.0 - */ - protected void setFieldSeparatorAtEnd(final boolean fieldSeparatorAtEnd) { - this.fieldSeparatorAtEnd = fieldSeparatorAtEnd; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets the text to output when {@code null} found. - *

              - * - * @return the current text to output when null found - */ - protected String getNullText() { - return nullText; - } - /** *

              * Sets the text to output when {@code null} found. @@ -2165,65 +2758,6 @@ public abstract class ToStringStyle implements Serializable { this.nullText = nullText; } - // --------------------------------------------------------------------- - - /** - *

              - * Gets the start text to output when a {@code Collection}, {@code Map} or array - * size is output. - *

              - * - *

              - * This is output before the size value. - *

              - * - * @return the current start of size text - */ - protected String getSizeStartText() { - return sizeStartText; - } - - /** - *

              - * Sets the start text to output when a {@code Collection}, {@code Map} or array - * size is output. - *

              - * - *

              - * This is output before the size value. - *

              - * - *

              - * {@code null} is accepted, but will be converted to an empty String. - *

              - * - * @param sizeStartText the new start of size text - */ - protected void setSizeStartText(String sizeStartText) { - if (sizeStartText == null) { - sizeStartText = StringUtils.EMPTY; - } - this.sizeStartText = sizeStartText; - } - - // --------------------------------------------------------------------- - - /** - *

              - * Gets the end text to output when a {@code Collection}, {@code Map} or array - * size is output. - *

              - * - *

              - * This is output after the size value. - *

              - * - * @return the current end of size text - */ - protected String getSizeEndText() { - return sizeEndText; - } - /** *

              * Sets the end text to output when a {@code Collection}, {@code Map} or array @@ -2247,28 +2781,12 @@ public abstract class ToStringStyle implements Serializable { this.sizeEndText = sizeEndText; } - // --------------------------------------------------------------------- + // ---------------------------------------------------------------------------- /** *

              - * Gets the start text to output when an {@code Object} is output in summary - * mode. - *

              - * - *

              - * This is output before the size value. - *

              - * - * @return the current start of summary text - */ - protected String getSummaryObjectStartText() { - return summaryObjectStartText; - } - - /** - *

              - * Sets the start text to output when an {@code Object} is output in summary - * mode. + * Sets the start text to output when a {@code Collection}, {@code Map} or array + * size is output. *

              * *

              @@ -2279,31 +2797,16 @@ public abstract class ToStringStyle implements Serializable { * {@code null} is accepted, but will be converted to an empty String. *

              * - * @param summaryObjectStartText the new start of summary text + * @param sizeStartText the new start of size text */ - protected void setSummaryObjectStartText(String summaryObjectStartText) { - if (summaryObjectStartText == null) { - summaryObjectStartText = StringUtils.EMPTY; + protected void setSizeStartText(String sizeStartText) { + if (sizeStartText == null) { + sizeStartText = StringUtils.EMPTY; } - this.summaryObjectStartText = summaryObjectStartText; + this.sizeStartText = sizeStartText; } - // --------------------------------------------------------------------- - - /** - *

              - * Gets the end text to output when an {@code Object} is output in summary mode. - *

              - * - *

              - * This is output after the size value. - *

              - * - * @return the current end of summary text - */ - protected String getSummaryObjectEndText() { - return summaryObjectEndText; - } + // ---------------------------------------------------------------------------- /** *

              @@ -2331,580 +2834,77 @@ public abstract class ToStringStyle implements Serializable { /** *

              - * Default {@code ToStringStyle}. + * Sets the start text to output when an {@code Object} is output in summary + * mode. *

              * *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. + * This is output before the size value. *

              + * + *

              + * {@code null} is accepted, but will be converted to an empty String. + *

              + * + * @param summaryObjectStartText the new start of summary text */ - private static final class DefaultToStringStyle extends ToStringStyle { - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1L; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - DefaultToStringStyle() { + protected void setSummaryObjectStartText(String summaryObjectStartText) { + if (summaryObjectStartText == null) { + summaryObjectStartText = StringUtils.EMPTY; } - - /** - *

              - * Ensure {@code Singleton} after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return DEFAULT_STYLE; - } - + this.summaryObjectStartText = summaryObjectStartText; } // ---------------------------------------------------------------------------- /** *

              - * {@code ToStringStyle} that does not print out the field names. + * Sets whether to use the class name. *

              * - *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. + * @param useClassName the new useClassName flag */ - private static final class NoFieldNameToStringStyle extends ToStringStyle { - - private static final long serialVersionUID = 1L; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - NoFieldNameToStringStyle() { - this.setUseFieldNames(false); - } - - /** - *

              - * Ensure {@code Singleton} after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return NO_FIELD_NAMES_STYLE; - } - + protected void setUseClassName(final boolean useClassName) { + this.useClassName = useClassName; } // ---------------------------------------------------------------------------- /** *

              - * {@code ToStringStyle} that prints out the short class name and no identity - * hashcode. + * Sets whether to use the field names passed in. *

              * - *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. - *

              + * @param useFieldNames the new useFieldNames flag */ - private static final class ShortPrefixToStringStyle extends ToStringStyle { - - private static final long serialVersionUID = 1L; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - ShortPrefixToStringStyle() { - this.setUseShortClassName(true); - this.setUseIdentityHashCode(false); - } - - /** - *

              - * Ensure Singleton after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return SHORT_PREFIX_STYLE; - } - + protected void setUseFieldNames(final boolean useFieldNames) { + this.useFieldNames = useFieldNames; } // ---------------------------------------------------------------------------- /** *

              - * {@code ToStringStyle} that does not print out the classname, identity - * hashcode, content start or field name. + * Sets whether to use the identity hash code. *

              * - *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. - *

              + * @param useIdentityHashCode the new useIdentityHashCode flag */ - private static final class SimpleToStringStyle extends ToStringStyle { - - private static final long serialVersionUID = 1L; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - SimpleToStringStyle() { - this.setUseClassName(false); - this.setUseIdentityHashCode(false); - this.setUseFieldNames(false); - this.setContentStart(StringUtils.EMPTY); - this.setContentEnd(StringUtils.EMPTY); - } - - /** - *

              - * Ensure Singleton after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return SIMPLE_STYLE; - } - + protected void setUseIdentityHashCode(final boolean useIdentityHashCode) { + this.useIdentityHashCode = useIdentityHashCode; } // ---------------------------------------------------------------------------- /** *

              - * {@code ToStringStyle} that outputs on multiple lines. + * Sets whether to output short or long class names. *

              * - *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. - *

              + * @param useShortClassName the new useShortClassName flag + * @since 2.0 */ - private static final class MultiLineToStringStyle extends ToStringStyle { - - private static final long serialVersionUID = 1L; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - MultiLineToStringStyle() { - this.setContentStart("["); - this.setFieldSeparator(System.lineSeparator() + " "); - this.setFieldSeparatorAtStart(true); - this.setContentEnd(System.lineSeparator() + "]"); - } - - /** - *

              - * Ensure {@code Singleton} after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return MULTI_LINE_STYLE; - } - - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * {@code ToStringStyle} that does not print out the classname and identity hash - * code but prints content start and field names. - *

              - * - *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. - *

              - */ - private static final class NoClassNameToStringStyle extends ToStringStyle { - - private static final long serialVersionUID = 1L; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - NoClassNameToStringStyle() { - this.setUseClassName(false); - this.setUseIdentityHashCode(false); - } - - /** - *

              - * Ensure {@code Singleton} after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return NO_CLASS_NAME_STYLE; - } - - } - - // ---------------------------------------------------------------------------- - - /** - *

              - * {@code ToStringStyle} that outputs with JSON format. - *

              - * - *

              - * This is an inner class rather than using {@code StandardToStringStyle} to - * ensure its immutability. - *

              - * - * @since 3.4 - * @see json.org - */ - private static final class JsonToStringStyle extends ToStringStyle { - - private static final long serialVersionUID = 1L; - - private static final String FIELD_NAME_QUOTE = "\""; - - /** - *

              - * Constructor. - *

              - * - *

              - * Use the static constant rather than instantiating. - *

              - */ - JsonToStringStyle() { - this.setUseClassName(false); - this.setUseIdentityHashCode(false); - - this.setContentStart("{"); - this.setContentEnd("}"); - - this.setArrayStart("["); - this.setArrayEnd("]"); - - this.setFieldSeparator(","); - this.setFieldNameValueSeparator(":"); - - this.setNullText("null"); - - this.setSummaryObjectStartText("\"<"); - this.setSummaryObjectEndText(">\""); - - this.setSizeStartText("\"\""); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final Object[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final long[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final int[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final short[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final byte[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final char[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final double[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final float[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final boolean[] array, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, array, fullDetail); - } - - @Override - public void append(final StringBuffer buffer, final String fieldName, final Object value, - final Boolean fullDetail) { - - if (fieldName == null) { - throw new UnsupportedOperationException("Field names are mandatory when using JsonToStringStyle"); - } - if (!isFullDetail(fullDetail)) { - throw new UnsupportedOperationException("FullDetail must be true when using JsonToStringStyle"); - } - - super.append(buffer, fieldName, value, fullDetail); - } - - @Override - protected void appendDetail(final StringBuffer buffer, final String fieldName, final char value) { - appendValueAsString(buffer, String.valueOf(value)); - } - - @Override - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Object value) { - - if (value == null) { - appendNullText(buffer, fieldName); - return; - } - - if (value instanceof String || value instanceof Character) { - appendValueAsString(buffer, value.toString()); - return; - } - - if (value instanceof Number || value instanceof Boolean) { - buffer.append(value); - return; - } - - final String valueAsString = value.toString(); - if (isJsonObject(valueAsString) || isJsonArray(valueAsString)) { - buffer.append(value); - return; - } - - appendDetail(buffer, fieldName, valueAsString); - } - - @Override - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection coll) { - if (coll != null && !coll.isEmpty()) { - buffer.append(getArrayStart()); - int i = 0; - for (final Object item : coll) { - appendDetail(buffer, fieldName, i++, item); - } - buffer.append(getArrayEnd()); - return; - } - - buffer.append(coll); - } - - @Override - protected void appendDetail(final StringBuffer buffer, final String fieldName, final Map map) { - if (map != null && !map.isEmpty()) { - buffer.append(getContentStart()); - - boolean firstItem = true; - for (final Entry entry : map.entrySet()) { - final String keyStr = Objects.toString(entry.getKey(), null); - if (keyStr != null) { - if (firstItem) { - firstItem = false; - } else { - appendFieldEnd(buffer, keyStr); - } - appendFieldStart(buffer, keyStr); - final Object value = entry.getValue(); - if (value == null) { - appendNullText(buffer, keyStr); - } else { - appendInternal(buffer, keyStr, value, true); - } - } - } - - buffer.append(getContentEnd()); - return; - } - - buffer.append(map); - } - - private boolean isJsonArray(final String valueAsString) { - return valueAsString.startsWith(getArrayStart()) && valueAsString.endsWith(getArrayEnd()); - } - - private boolean isJsonObject(final String valueAsString) { - return valueAsString.startsWith(getContentStart()) && valueAsString.endsWith(getContentEnd()); - } - - /** - * Appends the given String enclosed in double-quotes to the given StringBuffer. - * - * @param buffer the StringBuffer to append the value to. - * @param value the value to append. - */ - private void appendValueAsString(final StringBuffer buffer, final String value) { - // buffer.append('"').append(StringEscapeUtils.escapeJson(value)).append('"'); - throw new UnsupportedOperationException("Not supported in TeaVM"); - } - - @Override - protected void appendFieldStart(final StringBuffer buffer, final String fieldName) { - throw new UnsupportedOperationException("Not supported in TeaVM"); - /* - * if (fieldName == null) { throw new UnsupportedOperationException( - * "Field names are mandatory when using JsonToStringStyle"); } - * - * super.appendFieldStart(buffer, FIELD_NAME_QUOTE + - * StringEscapeUtils.escapeJson(fieldName) + FIELD_NAME_QUOTE); - */ - } - - /** - *

              - * Ensure {@code Singleton} after serialization. - *

              - * - * @return the singleton - */ - private Object readResolve() { - return JSON_STYLE; - } - + protected void setUseShortClassName(final boolean useShortClassName) { + this.useShortClassName = useShortClassName; } } diff --git a/src/main/java/org/apache/commons/lang3/exception/CloneFailedException.java b/src/main/java/org/apache/commons/lang3/exception/CloneFailedException.java index 64c4fefc..2222b71c 100644 --- a/src/main/java/org/apache/commons/lang3/exception/CloneFailedException.java +++ b/src/main/java/org/apache/commons/lang3/exception/CloneFailedException.java @@ -38,15 +38,6 @@ public class CloneFailedException extends RuntimeException { super(message); } - /** - * Constructs a CloneFailedException. - * - * @param cause cause of the exception - */ - public CloneFailedException(final Throwable cause) { - super(cause); - } - /** * Constructs a CloneFailedException. * @@ -56,4 +47,13 @@ public class CloneFailedException extends RuntimeException { public CloneFailedException(final String message, final Throwable cause) { super(message, cause); } + + /** + * Constructs a CloneFailedException. + * + * @param cause cause of the exception + */ + public CloneFailedException(final Throwable cause) { + super(cause); + } } diff --git a/src/main/java/org/apache/commons/lang3/function/TriFunction.java b/src/main/java/org/apache/commons/lang3/function/TriFunction.java index 45c34706..1e1dc831 100644 --- a/src/main/java/org/apache/commons/lang3/function/TriFunction.java +++ b/src/main/java/org/apache/commons/lang3/function/TriFunction.java @@ -39,16 +39,6 @@ import java.util.function.Function; @FunctionalInterface public interface TriFunction { - /** - * Applies this function to the given arguments. - * - * @param t the first function argument - * @param u the second function argument - * @param v the third function argument - * @return the function result - */ - R apply(T t, U u, V v); - /** * Returns a composed function that first applies this function to its input, * and then applies the {@code after} function to the result. If evaluation of @@ -66,4 +56,14 @@ public interface TriFunction { Objects.requireNonNull(after); return (final T t, final U u, final V v) -> after.apply(apply(t, u, v)); } + + /** + * Applies this function to the given arguments. + * + * @param t the first function argument + * @param u the second function argument + * @param v the third function argument + * @return the function result + */ + R apply(T t, U u, V v); } diff --git a/src/main/java/org/apache/commons/lang3/math/Fraction.java b/src/main/java/org/apache/commons/lang3/math/Fraction.java index f40bdb72..b643c1b6 100644 --- a/src/main/java/org/apache/commons/lang3/math/Fraction.java +++ b/src/main/java/org/apache/commons/lang3/math/Fraction.java @@ -98,38 +98,86 @@ public final class Fraction extends Number implements Comparable { public static final Fraction FOUR_FIFTHS = new Fraction(4, 5); /** - * The numerator number part of the fraction (the three in three sevenths). + * Add two integers, checking for overflow. + * + * @param x an addend + * @param y an addend + * @return the sum {@code x+y} + * @throws ArithmeticException if the result can not be represented as an int */ - private final int numerator; - /** - * The denominator number part of the fraction (the seven in three sevenths). - */ - private final int denominator; - - /** - * Cached output hashCode (class is immutable). - */ - private transient int hashCode; - /** - * Cached output toString (class is immutable). - */ - private transient String toString; - /** - * Cached output toProperString (class is immutable). - */ - private transient String toProperString; + private static int addAndCheck(final int x, final int y) { + final long s = (long) x + (long) y; + if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { + throw new ArithmeticException("overflow: add"); + } + return (int) s; + } /** *

              - * Constructs a {@code Fraction} instance with the 2 parts of a fraction Y/Z. + * Creates a {@code Fraction} instance from a {@code double} value. *

              * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' + *

              + * This method uses the + * continued + * fraction algorithm, computing a maximum of 25 convergents and bounding + * the denominator by 10,000. + *

              + * + * @param value the double value to convert + * @return a new fraction instance that is close to the value + * @throws ArithmeticException if {@code |value| > Integer.MAX_VALUE} or + * {@code value = NaN} + * @throws ArithmeticException if the calculated denominator is {@code zero} + * @throws ArithmeticException if the algorithm does not converge */ - private Fraction(final int numerator, final int denominator) { - this.numerator = numerator; - this.denominator = denominator; + public static Fraction getFraction(double value) { + final int sign = value < 0 ? -1 : 1; + value = Math.abs(value); + if (value > Integer.MAX_VALUE || Double.isNaN(value)) { + throw new ArithmeticException("The value must not be greater than Integer.MAX_VALUE or NaN"); + } + final int wholeNumber = (int) value; + value -= wholeNumber; + + int numer0 = 0; // the pre-previous + int denom0 = 1; // the pre-previous + int numer1 = 1; // the previous + int denom1 = 0; // the previous + int numer2 = 0; // the current, setup in calculation + int denom2 = 0; // the current, setup in calculation + int a1 = (int) value; + int a2 = 0; + double x1 = 1; + double x2 = 0; + double y1 = value - a1; + double y2 = 0; + double delta1, delta2 = Double.MAX_VALUE; + double fraction; + int i = 1; + do { + delta1 = delta2; + a2 = (int) (x1 / y1); + x2 = y1; + y2 = x1 - a2 * y1; + numer2 = a1 * numer1 + numer0; + denom2 = a1 * denom1 + denom0; + fraction = (double) numer2 / (double) denom2; + delta2 = Math.abs(value - fraction); + a1 = a2; + x1 = x2; + y1 = y2; + numer0 = numer1; + denom0 = denom1; + numer1 = numer2; + denom1 = denom2; + i++; + } while (delta1 > delta2 && denom2 <= 10000 && denom2 > 0 && i < 25); + if (i == 25) { + throw new ArithmeticException("Unable to convert double to fraction"); + } + return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0); } /** @@ -206,119 +254,6 @@ public final class Fraction extends Number implements Comparable { return new Fraction((int) numeratorValue, denominator); } - /** - *

              - * Creates a reduced {@code Fraction} instance with the 2 parts of a fraction - * Y/Z. - *

              - * - *

              - * For example, if the input parameters represent 2/4, then the created fraction - * will be 1/2. - *

              - * - *

              - * Any negative signs are resolved to be on the numerator. - *

              - * - * @param numerator the numerator, for example the three in 'three sevenths' - * @param denominator the denominator, for example the seven in 'three sevenths' - * @return a new fraction instance, with the numerator and denominator reduced - * @throws ArithmeticException if the denominator is {@code zero} - */ - public static Fraction getReducedFraction(int numerator, int denominator) { - if (denominator == 0) { - throw new ArithmeticException("The denominator must not be zero"); - } - if (numerator == 0) { - return ZERO; // normalize zero. - } - // allow 2^k/-2^31 as a valid fraction (where k>0) - if (denominator == Integer.MIN_VALUE && (numerator & 1) == 0) { - numerator /= 2; - denominator /= 2; - } - if (denominator < 0) { - if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: can't negate"); - } - numerator = -numerator; - denominator = -denominator; - } - // simplify fraction. - final int gcd = greatestCommonDivisor(numerator, denominator); - numerator /= gcd; - denominator /= gcd; - return new Fraction(numerator, denominator); - } - - /** - *

              - * Creates a {@code Fraction} instance from a {@code double} value. - *

              - * - *

              - * This method uses the - * continued - * fraction algorithm, computing a maximum of 25 convergents and bounding - * the denominator by 10,000. - *

              - * - * @param value the double value to convert - * @return a new fraction instance that is close to the value - * @throws ArithmeticException if {@code |value| > Integer.MAX_VALUE} or - * {@code value = NaN} - * @throws ArithmeticException if the calculated denominator is {@code zero} - * @throws ArithmeticException if the algorithm does not converge - */ - public static Fraction getFraction(double value) { - final int sign = value < 0 ? -1 : 1; - value = Math.abs(value); - if (value > Integer.MAX_VALUE || Double.isNaN(value)) { - throw new ArithmeticException("The value must not be greater than Integer.MAX_VALUE or NaN"); - } - final int wholeNumber = (int) value; - value -= wholeNumber; - - int numer0 = 0; // the pre-previous - int denom0 = 1; // the pre-previous - int numer1 = 1; // the previous - int denom1 = 0; // the previous - int numer2 = 0; // the current, setup in calculation - int denom2 = 0; // the current, setup in calculation - int a1 = (int) value; - int a2 = 0; - double x1 = 1; - double x2 = 0; - double y1 = value - a1; - double y2 = 0; - double delta1, delta2 = Double.MAX_VALUE; - double fraction; - int i = 1; - do { - delta1 = delta2; - a2 = (int) (x1 / y1); - x2 = y1; - y2 = x1 - a2 * y1; - numer2 = a1 * numer1 + numer0; - denom2 = a1 * denom1 + denom0; - fraction = (double) numer2 / (double) denom2; - delta2 = Math.abs(value - fraction); - a1 = a2; - x1 = x2; - y1 = y2; - numer0 = numer1; - denom0 = denom1; - numer1 = numer2; - denom1 = denom2; - i++; - } while (delta1 > delta2 && denom2 <= 10000 && denom2 > 0 && i < 25); - if (i == 25) { - throw new ArithmeticException("Unable to convert double to fraction"); - } - return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0); - } - /** *

              * Creates a Fraction from a {@code String}. @@ -376,259 +311,50 @@ public final class Fraction extends Number implements Comparable { return getFraction(numer, denom); } - // Accessors - // ------------------------------------------------------------------- - /** *

              - * Gets the numerator part of the fraction. + * Creates a reduced {@code Fraction} instance with the 2 parts of a fraction + * Y/Z. *

              * *

              - * This method may return a value greater than the denominator, an improper - * fraction, such as the seven in 7/4. + * For example, if the input parameters represent 2/4, then the created fraction + * will be 1/2. *

              * - * @return the numerator fraction part + *

              + * Any negative signs are resolved to be on the numerator. + *

              + * + * @param numerator the numerator, for example the three in 'three sevenths' + * @param denominator the denominator, for example the seven in 'three sevenths' + * @return a new fraction instance, with the numerator and denominator reduced + * @throws ArithmeticException if the denominator is {@code zero} */ - public int getNumerator() { - return numerator; - } - - /** - *

              - * Gets the denominator part of the fraction. - *

              - * - * @return the denominator fraction part - */ - public int getDenominator() { - return denominator; - } - - /** - *

              - * Gets the proper numerator, always positive. - *

              - * - *

              - * An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This - * method returns the 3 from the proper fraction. - *

              - * - *

              - * If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so - * this method returns the positive proper numerator, 3. - *

              - * - * @return the numerator fraction part of a proper fraction, always positive - */ - public int getProperNumerator() { - return Math.abs(numerator % denominator); - } - - /** - *

              - * Gets the proper whole part of the fraction. - *

              - * - *

              - * An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This - * method returns the 1 from the proper fraction. - *

              - * - *

              - * If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so - * this method returns the positive whole part -1. - *

              - * - * @return the whole fraction part of a proper fraction, that includes the sign - */ - public int getProperWhole() { - return numerator / denominator; - } - - // Number methods - // ------------------------------------------------------------------- - - /** - *

              - * Gets the fraction as an {@code int}. This returns the whole number part of - * the fraction. - *

              - * - * @return the whole number fraction part - */ - @Override - public int intValue() { - return numerator / denominator; - } - - /** - *

              - * Gets the fraction as a {@code long}. This returns the whole number part of - * the fraction. - *

              - * - * @return the whole number fraction part - */ - @Override - public long longValue() { - return (long) numerator / denominator; - } - - /** - *

              - * Gets the fraction as a {@code float}. This calculates the fraction as the - * numerator divided by denominator. - *

              - * - * @return the fraction as a {@code float} - */ - @Override - public float floatValue() { - return (float) numerator / (float) denominator; - } - - /** - *

              - * Gets the fraction as a {@code double}. This calculates the fraction as the - * numerator divided by denominator. - *

              - * - * @return the fraction as a {@code double} - */ - @Override - public double doubleValue() { - return (double) numerator / (double) denominator; - } - - // Calculations - // ------------------------------------------------------------------- - - /** - *

              - * Reduce the fraction to the smallest values for the numerator and denominator, - * returning the result. - *

              - * - *

              - * For example, if this fraction represents 2/4, then the result will be 1/2. - *

              - * - * @return a new reduced fraction instance, or this if no simplification - * possible - */ - public Fraction reduce() { + public static Fraction getReducedFraction(int numerator, int denominator) { + if (denominator == 0) { + throw new ArithmeticException("The denominator must not be zero"); + } if (numerator == 0) { - return equals(ZERO) ? this : ZERO; + return ZERO; // normalize zero. } - final int gcd = greatestCommonDivisor(Math.abs(numerator), denominator); - if (gcd == 1) { - return this; + // allow 2^k/-2^31 as a valid fraction (where k>0) + if (denominator == Integer.MIN_VALUE && (numerator & 1) == 0) { + numerator /= 2; + denominator /= 2; } - return getFraction(numerator / gcd, denominator / gcd); - } - - /** - *

              - * Gets a fraction that is the inverse (1/fraction) of this one. - *

              - * - *

              - * The returned fraction is not reduced. - *

              - * - * @return a new fraction instance with the numerator and denominator inverted. - * @throws ArithmeticException if the fraction represents zero. - */ - public Fraction invert() { - if (numerator == 0) { - throw new ArithmeticException("Unable to invert zero."); - } - if (numerator == Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: can't negate numerator"); - } - if (numerator < 0) { - return new Fraction(-denominator, -numerator); - } - return new Fraction(denominator, numerator); - } - - /** - *

              - * Gets a fraction that is the negative (-fraction) of this one. - *

              - * - *

              - * The returned fraction is not reduced. - *

              - * - * @return a new fraction instance with the opposite signed numerator - */ - public Fraction negate() { - // the positive range is one smaller than the negative range of an int. - if (numerator == Integer.MIN_VALUE) { - throw new ArithmeticException("overflow: too large to negate"); - } - return new Fraction(-numerator, denominator); - } - - /** - *

              - * Gets a fraction that is the positive equivalent of this one. - *

              - *

              - * More precisely: {@code (fraction >= 0 ? this : -fraction)} - *

              - * - *

              - * The returned fraction is not reduced. - *

              - * - * @return {@code this} if it is positive, or a new positive fraction instance - * with the opposite signed numerator - */ - public Fraction abs() { - if (numerator >= 0) { - return this; - } - return negate(); - } - - /** - *

              - * Gets a fraction that is raised to the passed in power. - *

              - * - *

              - * The returned fraction is in reduced form. - *

              - * - * @param power the power to raise the fraction to - * @return {@code this} if the power is one, {@code ONE} if the power is zero - * (even if the fraction equals ZERO) or a new fraction instance raised - * to the appropriate power - * @throws ArithmeticException if the resulting numerator or denominator exceeds - * {@code Integer.MAX_VALUE} - */ - public Fraction pow(final int power) { - if (power == 1) { - return this; - } else if (power == 0) { - return ONE; - } else if (power < 0) { - if (power == Integer.MIN_VALUE) { // MIN_VALUE can't be negated. - return this.invert().pow(2).pow(-(power / 2)); + if (denominator < 0) { + if (numerator == Integer.MIN_VALUE || denominator == Integer.MIN_VALUE) { + throw new ArithmeticException("overflow: can't negate"); } - return this.invert().pow(-power); - } else { - final Fraction f = this.multiplyBy(this); - if (power % 2 == 0) { // if even... - return f.pow(power / 2); - } - return f.pow(power / 2).multiplyBy(this); + numerator = -numerator; + denominator = -denominator; } + // simplify fraction. + final int gcd = greatestCommonDivisor(numerator, denominator); + numerator /= gcd; + denominator /= gcd; + return new Fraction(numerator, denominator); } /** @@ -699,9 +425,6 @@ public final class Fraction extends Number implements Comparable { return -u * (1 << k); // gcd is u*2^k } - // Arithmetic - // ------------------------------------------------------------------- - /** * Multiply two integers, checking for overflow. * @@ -735,22 +458,6 @@ public final class Fraction extends Number implements Comparable { return (int) m; } - /** - * Add two integers, checking for overflow. - * - * @param x an addend - * @param y an addend - * @return the sum {@code x+y} - * @throws ArithmeticException if the result can not be represented as an int - */ - private static int addAndCheck(final int x, final int y) { - final long s = (long) x + (long) y; - if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { - throw new ArithmeticException("overflow: add"); - } - return (int) s; - } - /** * Subtract two integers, checking for overflow. * @@ -767,6 +474,72 @@ public final class Fraction extends Number implements Comparable { return (int) s; } + /** + * The numerator number part of the fraction (the three in three sevenths). + */ + private final int numerator; + + // Accessors + // ------------------------------------------------------------------- + + /** + * The denominator number part of the fraction (the seven in three sevenths). + */ + private final int denominator; + + /** + * Cached output hashCode (class is immutable). + */ + private transient int hashCode; + + /** + * Cached output toString (class is immutable). + */ + private transient String toString; + + /** + * Cached output toProperString (class is immutable). + */ + private transient String toProperString; + + // Number methods + // ------------------------------------------------------------------- + + /** + *

              + * Constructs a {@code Fraction} instance with the 2 parts of a fraction Y/Z. + *

              + * + * @param numerator the numerator, for example the three in 'three sevenths' + * @param denominator the denominator, for example the seven in 'three sevenths' + */ + private Fraction(final int numerator, final int denominator) { + this.numerator = numerator; + this.denominator = denominator; + } + + /** + *

              + * Gets a fraction that is the positive equivalent of this one. + *

              + *

              + * More precisely: {@code (fraction >= 0 ? this : -fraction)} + *

              + * + *

              + * The returned fraction is not reduced. + *

              + * + * @return {@code this} if it is positive, or a new positive fraction instance + * with the opposite signed numerator + */ + public Fraction abs() { + if (numerator >= 0) { + return this; + } + return negate(); + } + /** *

              * Adds the value of this fraction to another, returning the result in reduced @@ -783,22 +556,6 @@ public final class Fraction extends Number implements Comparable { return addSub(fraction, true /* add */); } - /** - *

              - * Subtracts the value of another fraction from the value of this one, returning - * the result in reduced form. - *

              - * - * @param fraction the fraction to subtract, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws IllegalArgumentException if the fraction is {@code null} - * @throws ArithmeticException if the resulting numerator or denominator - * cannot be represented in an {@code int}. - */ - public Fraction subtract(final Fraction fraction) { - return addSub(fraction, false /* subtract */); - } - /** * Implement add and subtract using algorithm described in Knuth 4.5.1. * @@ -847,95 +604,9 @@ public final class Fraction extends Number implements Comparable { return new Fraction(w.intValue(), mulPosAndCheck(denominator / d1, fraction.denominator / d2)); } - /** - *

              - * Multiplies the value of this fraction by another, returning the result in - * reduced form. - *

              - * - * @param fraction the fraction to multiply by, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullPointerException if the fraction is {@code null} - * @throws ArithmeticException if the resulting numerator or denominator - * exceeds {@code Integer.MAX_VALUE} - */ - public Fraction multiplyBy(final Fraction fraction) { - Validate.notNull(fraction, "fraction"); - if (numerator == 0 || fraction.numerator == 0) { - return ZERO; - } - // knuth 4.5.1 - // make sure we don't overflow unless the result *must* overflow. - final int d1 = greatestCommonDivisor(numerator, fraction.denominator); - final int d2 = greatestCommonDivisor(fraction.numerator, denominator); - return getReducedFraction(mulAndCheck(numerator / d1, fraction.numerator / d2), - mulPosAndCheck(denominator / d2, fraction.denominator / d1)); - } - - /** - *

              - * Divide the value of this fraction by another. - *

              - * - * @param fraction the fraction to divide by, must not be {@code null} - * @return a {@code Fraction} instance with the resulting values - * @throws NullPointerException if the fraction is {@code null} - * @throws ArithmeticException if the fraction to divide by is zero - * @throws ArithmeticException if the resulting numerator or denominator - * exceeds {@code Integer.MAX_VALUE} - */ - public Fraction divideBy(final Fraction fraction) { - Validate.notNull(fraction, "fraction"); - if (fraction.numerator == 0) { - throw new ArithmeticException("The fraction to divide by must not be zero"); - } - return multiplyBy(fraction.invert()); - } - - // Basics + // Calculations // ------------------------------------------------------------------- - /** - *

              - * Compares this fraction to another object to test if they are equal. - *

              - * . - * - *

              - * To be equal, both values must be equal. Thus 2/4 is not equal to 1/2. - *

              - * - * @param obj the reference object with which to compare - * @return {@code true} if this object is equal - */ - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Fraction)) { - return false; - } - final Fraction other = (Fraction) obj; - return getNumerator() == other.getNumerator() && getDenominator() == other.getDenominator(); - } - - /** - *

              - * Gets a hashCode for the fraction. - *

              - * - * @return a hash code value for this object - */ - @Override - public int hashCode() { - if (hashCode == 0) { - // hash code update should be atomic. - hashCode = 37 * (37 * 17 + getNumerator()) + getDenominator(); - } - return hashCode; - } - /** *

              * Compares this object to another based on size. @@ -968,20 +639,334 @@ public final class Fraction extends Number implements Comparable { /** *

              - * Gets the fraction as a {@code String}. + * Divide the value of this fraction by another. + *

              + * + * @param fraction the fraction to divide by, must not be {@code null} + * @return a {@code Fraction} instance with the resulting values + * @throws NullPointerException if the fraction is {@code null} + * @throws ArithmeticException if the fraction to divide by is zero + * @throws ArithmeticException if the resulting numerator or denominator + * exceeds {@code Integer.MAX_VALUE} + */ + public Fraction divideBy(final Fraction fraction) { + Validate.notNull(fraction, "fraction"); + if (fraction.numerator == 0) { + throw new ArithmeticException("The fraction to divide by must not be zero"); + } + return multiplyBy(fraction.invert()); + } + + /** + *

              + * Gets the fraction as a {@code double}. This calculates the fraction as the + * numerator divided by denominator. + *

              + * + * @return the fraction as a {@code double} + */ + @Override + public double doubleValue() { + return (double) numerator / (double) denominator; + } + + /** + *

              + * Compares this fraction to another object to test if they are equal. + *

              + * . + * + *

              + * To be equal, both values must be equal. Thus 2/4 is not equal to 1/2. + *

              + * + * @param obj the reference object with which to compare + * @return {@code true} if this object is equal + */ + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof Fraction)) { + return false; + } + final Fraction other = (Fraction) obj; + return getNumerator() == other.getNumerator() && getDenominator() == other.getDenominator(); + } + + /** + *

              + * Gets the fraction as a {@code float}. This calculates the fraction as the + * numerator divided by denominator. + *

              + * + * @return the fraction as a {@code float} + */ + @Override + public float floatValue() { + return (float) numerator / (float) denominator; + } + + /** + *

              + * Gets the denominator part of the fraction. + *

              + * + * @return the denominator fraction part + */ + public int getDenominator() { + return denominator; + } + + // Arithmetic + // ------------------------------------------------------------------- + + /** + *

              + * Gets the numerator part of the fraction. *

              * *

              - * The format used is 'numerator/denominator' always. + * This method may return a value greater than the denominator, an improper + * fraction, such as the seven in 7/4. + *

              * - * @return a {@code String} form of the fraction + * @return the numerator fraction part + */ + public int getNumerator() { + return numerator; + } + + /** + *

              + * Gets the proper numerator, always positive. + *

              + * + *

              + * An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This + * method returns the 3 from the proper fraction. + *

              + * + *

              + * If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so + * this method returns the positive proper numerator, 3. + *

              + * + * @return the numerator fraction part of a proper fraction, always positive + */ + public int getProperNumerator() { + return Math.abs(numerator % denominator); + } + + /** + *

              + * Gets the proper whole part of the fraction. + *

              + * + *

              + * An improper fraction 7/4 can be resolved into a proper one, 1 3/4. This + * method returns the 1 from the proper fraction. + *

              + * + *

              + * If the fraction is negative such as -7/4, it can be resolved into -1 3/4, so + * this method returns the positive whole part -1. + *

              + * + * @return the whole fraction part of a proper fraction, that includes the sign + */ + public int getProperWhole() { + return numerator / denominator; + } + + /** + *

              + * Gets a hashCode for the fraction. + *

              + * + * @return a hash code value for this object */ @Override - public String toString() { - if (toString == null) { - toString = getNumerator() + "/" + getDenominator(); + public int hashCode() { + if (hashCode == 0) { + // hash code update should be atomic. + hashCode = 37 * (37 * 17 + getNumerator()) + getDenominator(); } - return toString; + return hashCode; + } + + /** + *

              + * Gets the fraction as an {@code int}. This returns the whole number part of + * the fraction. + *

              + * + * @return the whole number fraction part + */ + @Override + public int intValue() { + return numerator / denominator; + } + + /** + *

              + * Gets a fraction that is the inverse (1/fraction) of this one. + *

              + * + *

              + * The returned fraction is not reduced. + *

              + * + * @return a new fraction instance with the numerator and denominator inverted. + * @throws ArithmeticException if the fraction represents zero. + */ + public Fraction invert() { + if (numerator == 0) { + throw new ArithmeticException("Unable to invert zero."); + } + if (numerator == Integer.MIN_VALUE) { + throw new ArithmeticException("overflow: can't negate numerator"); + } + if (numerator < 0) { + return new Fraction(-denominator, -numerator); + } + return new Fraction(denominator, numerator); + } + + /** + *

              + * Gets the fraction as a {@code long}. This returns the whole number part of + * the fraction. + *

              + * + * @return the whole number fraction part + */ + @Override + public long longValue() { + return (long) numerator / denominator; + } + + /** + *

              + * Multiplies the value of this fraction by another, returning the result in + * reduced form. + *

              + * + * @param fraction the fraction to multiply by, must not be {@code null} + * @return a {@code Fraction} instance with the resulting values + * @throws NullPointerException if the fraction is {@code null} + * @throws ArithmeticException if the resulting numerator or denominator + * exceeds {@code Integer.MAX_VALUE} + */ + public Fraction multiplyBy(final Fraction fraction) { + Validate.notNull(fraction, "fraction"); + if (numerator == 0 || fraction.numerator == 0) { + return ZERO; + } + // knuth 4.5.1 + // make sure we don't overflow unless the result *must* overflow. + final int d1 = greatestCommonDivisor(numerator, fraction.denominator); + final int d2 = greatestCommonDivisor(fraction.numerator, denominator); + return getReducedFraction(mulAndCheck(numerator / d1, fraction.numerator / d2), + mulPosAndCheck(denominator / d2, fraction.denominator / d1)); + } + + /** + *

              + * Gets a fraction that is the negative (-fraction) of this one. + *

              + * + *

              + * The returned fraction is not reduced. + *

              + * + * @return a new fraction instance with the opposite signed numerator + */ + public Fraction negate() { + // the positive range is one smaller than the negative range of an int. + if (numerator == Integer.MIN_VALUE) { + throw new ArithmeticException("overflow: too large to negate"); + } + return new Fraction(-numerator, denominator); + } + + // Basics + // ------------------------------------------------------------------- + + /** + *

              + * Gets a fraction that is raised to the passed in power. + *

              + * + *

              + * The returned fraction is in reduced form. + *

              + * + * @param power the power to raise the fraction to + * @return {@code this} if the power is one, {@code ONE} if the power is zero + * (even if the fraction equals ZERO) or a new fraction instance raised + * to the appropriate power + * @throws ArithmeticException if the resulting numerator or denominator exceeds + * {@code Integer.MAX_VALUE} + */ + public Fraction pow(final int power) { + if (power == 1) { + return this; + } else if (power == 0) { + return ONE; + } else if (power < 0) { + if (power == Integer.MIN_VALUE) { // MIN_VALUE can't be negated. + return this.invert().pow(2).pow(-(power / 2)); + } + return this.invert().pow(-power); + } else { + final Fraction f = this.multiplyBy(this); + if (power % 2 == 0) { // if even... + return f.pow(power / 2); + } + return f.pow(power / 2).multiplyBy(this); + } + } + + /** + *

              + * Reduce the fraction to the smallest values for the numerator and denominator, + * returning the result. + *

              + * + *

              + * For example, if this fraction represents 2/4, then the result will be 1/2. + *

              + * + * @return a new reduced fraction instance, or this if no simplification + * possible + */ + public Fraction reduce() { + if (numerator == 0) { + return equals(ZERO) ? this : ZERO; + } + final int gcd = greatestCommonDivisor(Math.abs(numerator), denominator); + if (gcd == 1) { + return this; + } + return getFraction(numerator / gcd, denominator / gcd); + } + + /** + *

              + * Subtracts the value of another fraction from the value of this one, returning + * the result in reduced form. + *

              + * + * @param fraction the fraction to subtract, must not be {@code null} + * @return a {@code Fraction} instance with the resulting values + * @throws IllegalArgumentException if the fraction is {@code null} + * @throws ArithmeticException if the resulting numerator or denominator + * cannot be represented in an {@code int}. + */ + public Fraction subtract(final Fraction fraction) { + return addSub(fraction, false /* subtract */); } /** @@ -1022,4 +1007,22 @@ public final class Fraction extends Number implements Comparable { } return toProperString; } + + /** + *

              + * Gets the fraction as a {@code String}. + *

              + * + *

              + * The format used is 'numerator/denominator' always. + * + * @return a {@code String} form of the fraction + */ + @Override + public String toString() { + if (toString == null) { + toString = getNumerator() + "/" + getDenominator(); + } + return toString; + } } diff --git a/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java b/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java index cb29cf67..39495f20 100644 --- a/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/IEEE754rUtils.java @@ -32,136 +32,6 @@ import org.apache.commons.lang3.Validate; */ public class IEEE754rUtils { - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws NullPointerException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from min(double[]) to min(double...) - */ - public static double min(final double... array) { - Validate.notNull(array, "array"); - Validate.isTrue(array.length != 0, "Array cannot be empty."); - - // Finds and returns min - double min = array[0]; - for (int i = 1; i < array.length; i++) { - min = min(array[i], min); - } - - return min; - } - - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws NullPointerException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from min(float[]) to min(float...) - */ - public static float min(final float... array) { - Validate.notNull(array, "array"); - Validate.isTrue(array.length != 0, "Array cannot be empty."); - - // Finds and returns min - float min = array[0]; - for (int i = 1; i < array.length; i++) { - min = min(array[i], min); - } - - return min; - } - - /** - *

              - * Gets the minimum of three {@code double} values. - *

              - * - *

              - * NaN is only returned if all numbers are NaN as per IEEE-754r. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static double min(final double a, final double b, final double c) { - return min(min(a, b), c); - } - - /** - *

              - * Gets the minimum of two {@code double} values. - *

              - * - *

              - * NaN is only returned if all numbers are NaN as per IEEE-754r. - *

              - * - * @param a value 1 - * @param b value 2 - * @return the smallest of the values - */ - public static double min(final double a, final double b) { - if (Double.isNaN(a)) { - return b; - } else if (Double.isNaN(b)) { - return a; - } else { - return Math.min(a, b); - } - } - - /** - *

              - * Gets the minimum of three {@code float} values. - *

              - * - *

              - * NaN is only returned if all numbers are NaN as per IEEE-754r. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static float min(final float a, final float b, final float c) { - return min(min(a, b), c); - } - - /** - *

              - * Gets the minimum of two {@code float} values. - *

              - * - *

              - * NaN is only returned if all numbers are NaN as per IEEE-754r. - *

              - * - * @param a value 1 - * @param b value 2 - * @return the smallest of the values - */ - public static float min(final float a, final float b) { - if (Float.isNaN(a)) { - return b; - } else if (Float.isNaN(b)) { - return a; - } else { - return Math.min(a, b); - } - } - /** *

              * Returns the maximum value in an array. @@ -186,6 +56,47 @@ public class IEEE754rUtils { return max; } + /** + *

              + * Gets the maximum of two {@code double} values. + *

              + * + *

              + * NaN is only returned if all numbers are NaN as per IEEE-754r. + *

              + * + * @param a value 1 + * @param b value 2 + * @return the largest of the values + */ + public static double max(final double a, final double b) { + if (Double.isNaN(a)) { + return b; + } else if (Double.isNaN(b)) { + return a; + } else { + return Math.max(a, b); + } + } + + /** + *

              + * Gets the maximum of three {@code double} values. + *

              + * + *

              + * NaN is only returned if all numbers are NaN as per IEEE-754r. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static double max(final double a, final double b, final double c) { + return max(max(a, b), c); + } + /** *

              * Returns the maximum value in an array. @@ -212,25 +123,7 @@ public class IEEE754rUtils { /** *

              - * Gets the maximum of three {@code double} values. - *

              - * - *

              - * NaN is only returned if all numbers are NaN as per IEEE-754r. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static double max(final double a, final double b, final double c) { - return max(max(a, b), c); - } - - /** - *

              - * Gets the maximum of two {@code double} values. + * Gets the maximum of two {@code float} values. *

              * *

              @@ -241,10 +134,10 @@ public class IEEE754rUtils { * @param b value 2 * @return the largest of the values */ - public static double max(final double a, final double b) { - if (Double.isNaN(a)) { + public static float max(final float a, final float b) { + if (Float.isNaN(a)) { return b; - } else if (Double.isNaN(b)) { + } else if (Float.isNaN(b)) { return a; } else { return Math.max(a, b); @@ -271,7 +164,31 @@ public class IEEE754rUtils { /** *

              - * Gets the maximum of two {@code float} values. + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws NullPointerException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + Validate.notNull(array, "array"); + Validate.isTrue(array.length != 0, "Array cannot be empty."); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + min = min(array[i], min); + } + + return min; + } + + /** + *

              + * Gets the minimum of two {@code double} values. *

              * *

              @@ -280,16 +197,99 @@ public class IEEE754rUtils { * * @param a value 1 * @param b value 2 - * @return the largest of the values + * @return the smallest of the values */ - public static float max(final float a, final float b) { + public static double min(final double a, final double b) { + if (Double.isNaN(a)) { + return b; + } else if (Double.isNaN(b)) { + return a; + } else { + return Math.min(a, b); + } + } + + /** + *

              + * Gets the minimum of three {@code double} values. + *

              + * + *

              + * NaN is only returned if all numbers are NaN as per IEEE-754r. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static double min(final double a, final double b, final double c) { + return min(min(a, b), c); + } + + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws NullPointerException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + Validate.notNull(array, "array"); + Validate.isTrue(array.length != 0, "Array cannot be empty."); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + min = min(array[i], min); + } + + return min; + } + + /** + *

              + * Gets the minimum of two {@code float} values. + *

              + * + *

              + * NaN is only returned if all numbers are NaN as per IEEE-754r. + *

              + * + * @param a value 1 + * @param b value 2 + * @return the smallest of the values + */ + public static float min(final float a, final float b) { if (Float.isNaN(a)) { return b; } else if (Float.isNaN(b)) { return a; } else { - return Math.max(a, b); + return Math.min(a, b); } } + /** + *

              + * Gets the minimum of three {@code float} values. + *

              + * + *

              + * NaN is only returned if all numbers are NaN as per IEEE-754r. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static float min(final float a, final float b, final float c) { + return min(min(a, b), c); + } + } diff --git a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java index 1c49c50d..822fdba4 100644 --- a/src/main/java/org/apache/commons/lang3/math/NumberUtils.java +++ b/src/main/java/org/apache/commons/lang3/math/NumberUtils.java @@ -88,601 +88,228 @@ public class NumberUtils { /** *

              - * {@code NumberUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * {@code NumberUtils.toInt("6");}. + * Compares two {@code byte} values numerically. This is the same functionality + * as provided in Java 7. + *

              + * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} to compare + * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if + * {@code x < y}; and a value greater than {@code 0} if {@code x > y} + * @since 3.4 + */ + public static int compare(final byte x, final byte y) { + return x - y; + } + + /** + *

              + * Compares two {@code int} values numerically. This is the same functionality + * as provided in Java 7. + *

              + * + * @param x the first {@code int} to compare + * @param y the second {@code int} to compare + * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if + * {@code x < y}; and a value greater than {@code 0} if {@code x > y} + * @since 3.4 + */ + public static int compare(final int x, final int y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

              + * Compares to {@code long} values numerically. This is the same functionality + * as provided in Java 7. + *

              + * + * @param x the first {@code long} to compare + * @param y the second {@code long} to compare + * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if + * {@code x < y}; and a value greater than {@code 0} if {@code x > y} + * @since 3.4 + */ + public static int compare(final long x, final long y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

              + * Compares to {@code short} values numerically. This is the same functionality + * as provided in Java 7. + *

              + * + * @param x the first {@code short} to compare + * @param y the second {@code short} to compare + * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if + * {@code x < y}; and a value greater than {@code 0} if {@code x > y} + * @since 3.4 + */ + public static int compare(final short x, final short y) { + if (x == y) { + return 0; + } + return x < y ? -1 : 1; + } + + /** + *

              + * Convert a {@code String} to a {@code BigDecimal}. *

              * *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. + * Returns {@code null} if the string is {@code null}. *

              + * + * @param str a {@code String} to convert, may be null + * @return converted {@code BigDecimal} (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted */ - public NumberUtils() { + public static BigDecimal createBigDecimal(final String str) { + if (str == null) { + return null; + } + // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException + if (StringUtils.isBlank(str)) { + throw new NumberFormatException("A blank string is not a valid number"); + } + return new BigDecimal(str); + } + + /** + *

              + * Convert a {@code String} to a {@code BigInteger}; since 3.2 it handles hex + * (0x or #) and octal (0) notations. + *

              + * + *

              + * Returns {@code null} if the string is {@code null}. + *

              + * + * @param str a {@code String} to convert, may be null + * @return converted {@code BigInteger} (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static BigInteger createBigInteger(final String str) { + if (str == null) { + return null; + } + int pos = 0; // offset within string + int radix = 10; + boolean negate = false; // need to negate later? + if (str.startsWith("-")) { + negate = true; + pos = 1; + } + if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex + radix = 16; + pos += 2; + } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) + radix = 16; + pos++; + } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional + // digits + radix = 8; + pos++; + } // default is to treat as decimal + + final BigInteger value = new BigInteger(str.substring(pos), radix); + return negate ? value.negate() : value; + } + + /** + *

              + * Convert a {@code String} to a {@code Double}. + *

              + * + *

              + * Returns {@code null} if the string is {@code null}. + *

              + * + * @param str a {@code String} to convert, may be null + * @return converted {@code Double} (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted + */ + public static Double createDouble(final String str) { + if (str == null) { + return null; + } + return Double.valueOf(str); } // ----------------------------------------------------------------------- /** *

              - * Convert a {@code String} to an {@code int}, returning {@code zero} if the - * conversion fails. + * Convert a {@code String} to a {@code Float}. *

              * *

              - * If the string is {@code null}, {@code zero} is returned. + * Returns {@code null} if the string is {@code null}. *

              * - *
              -	 *   NumberUtils.toInt(null) = 0
              -	 *   NumberUtils.toInt("")   = 0
              -	 *   NumberUtils.toInt("1")  = 1
              -	 * 
              - * - * @param str the string to convert, may be null - * @return the int represented by the string, or {@code zero} if conversion - * fails - * @since 2.1 + * @param str a {@code String} to convert, may be null + * @return converted {@code Float} (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted */ - public static int toInt(final String str) { - return toInt(str, 0); - } - - /** - *

              - * Convert a {@code String} to an {@code int}, returning a default value if the - * conversion fails. - *

              - * - *

              - * If the string is {@code null}, the default value is returned. - *

              - * - *
              -	 *   NumberUtils.toInt(null, 1) = 1
              -	 *   NumberUtils.toInt("", 1)   = 1
              -	 *   NumberUtils.toInt("1", 0)  = 1
              -	 * 
              - * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the int represented by the string, or the default if conversion fails - * @since 2.1 - */ - public static int toInt(final String str, final int defaultValue) { + public static Float createFloat(final String str) { if (str == null) { - return defaultValue; - } - try { - return Integer.parseInt(str); - } catch (final NumberFormatException nfe) { - return defaultValue; + return null; } + return Float.valueOf(str); } /** *

              - * Convert a {@code String} to a {@code long}, returning {@code zero} if the - * conversion fails. + * Convert a {@code String} to a {@code Integer}, handling hex (0xhhhh) and + * octal (0dddd) notations. N.B. a leading zero means octal; spaces are not + * trimmed. *

              * *

              - * If the string is {@code null}, {@code zero} is returned. + * Returns {@code null} if the string is {@code null}. *

              * - *
              -	 *   NumberUtils.toLong(null) = 0L
              -	 *   NumberUtils.toLong("")   = 0L
              -	 *   NumberUtils.toLong("1")  = 1L
              -	 * 
              - * - * @param str the string to convert, may be null - * @return the long represented by the string, or {@code 0} if conversion fails - * @since 2.1 + * @param str a {@code String} to convert, may be null + * @return converted {@code Integer} (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted */ - public static long toLong(final String str) { - return toLong(str, 0L); - } - - /** - *

              - * Convert a {@code String} to a {@code long}, returning a default value if the - * conversion fails. - *

              - * - *

              - * If the string is {@code null}, the default value is returned. - *

              - * - *
              -	 *   NumberUtils.toLong(null, 1L) = 1L
              -	 *   NumberUtils.toLong("", 1L)   = 1L
              -	 *   NumberUtils.toLong("1", 0L)  = 1L
              -	 * 
              - * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the long represented by the string, or the default if conversion - * fails - * @since 2.1 - */ - public static long toLong(final String str, final long defaultValue) { + public static Integer createInteger(final String str) { if (str == null) { - return defaultValue; - } - try { - return Long.parseLong(str); - } catch (final NumberFormatException nfe) { - return defaultValue; + return null; } + // decode() handles 0xAABD and 0777 (hex and octal) as well. + return Integer.decode(str); } /** *

              - * Convert a {@code String} to a {@code float}, returning {@code 0.0f} if the - * conversion fails. + * Convert a {@code String} to a {@code Long}; since 3.1 it handles hex (0Xhhhh) + * and octal (0ddd) notations. N.B. a leading zero means octal; spaces are not + * trimmed. *

              * *

              - * If the string {@code str} is {@code null}, {@code 0.0f} is returned. + * Returns {@code null} if the string is {@code null}. *

              * - *
              -	 *   NumberUtils.toFloat(null)   = 0.0f
              -	 *   NumberUtils.toFloat("")     = 0.0f
              -	 *   NumberUtils.toFloat("1.5")  = 1.5f
              -	 * 
              - * - * @param str the string to convert, may be {@code null} - * @return the float represented by the string, or {@code 0.0f} if conversion - * fails - * @since 2.1 + * @param str a {@code String} to convert, may be null + * @return converted {@code Long} (or null if the input is null) + * @throws NumberFormatException if the value cannot be converted */ - public static float toFloat(final String str) { - return toFloat(str, 0.0f); - } - - /** - *

              - * Convert a {@code String} to a {@code float}, returning a default value if the - * conversion fails. - *

              - * - *

              - * If the string {@code str} is {@code null}, the default value is returned. - *

              - * - *
              -	 *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
              -	 *   NumberUtils.toFloat("", 1.1f)     = 1.1f
              -	 *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
              -	 * 
              - * - * @param str the string to convert, may be {@code null} - * @param defaultValue the default value - * @return the float represented by the string, or defaultValue if conversion - * fails - * @since 2.1 - */ - public static float toFloat(final String str, final float defaultValue) { + public static Long createLong(final String str) { if (str == null) { - return defaultValue; - } - try { - return Float.parseFloat(str); - } catch (final NumberFormatException nfe) { - return defaultValue; + return null; } + return Long.decode(str); } - /** - *

              - * Convert a {@code String} to a {@code double}, returning {@code 0.0d} if the - * conversion fails. - *

              - * - *

              - * If the string {@code str} is {@code null}, {@code 0.0d} is returned. - *

              - * - *
              -	 *   NumberUtils.toDouble(null)   = 0.0d
              -	 *   NumberUtils.toDouble("")     = 0.0d
              -	 *   NumberUtils.toDouble("1.5")  = 1.5d
              -	 * 
              - * - * @param str the string to convert, may be {@code null} - * @return the double represented by the string, or {@code 0.0d} if conversion - * fails - * @since 2.1 - */ - public static double toDouble(final String str) { - return toDouble(str, 0.0d); - } - - /** - *

              - * Convert a {@code String} to a {@code double}, returning a default value if - * the conversion fails. - *

              - * - *

              - * If the string {@code str} is {@code null}, the default value is returned. - *

              - * - *
              -	 *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
              -	 *   NumberUtils.toDouble("", 1.1d)     = 1.1d
              -	 *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
              -	 * 
              - * - * @param str the string to convert, may be {@code null} - * @param defaultValue the default value - * @return the double represented by the string, or defaultValue if conversion - * fails - * @since 2.1 - */ - public static double toDouble(final String str, final double defaultValue) { - if (str == null) { - return defaultValue; - } - try { - return Double.parseDouble(str); - } catch (final NumberFormatException nfe) { - return defaultValue; - } - } - - /** - *

              - * Convert a {@code BigDecimal} to a {@code double}. - *

              - * - *

              - * If the {@code BigDecimal} {@code value} is {@code null}, then the specified - * default value is returned. - *

              - * - *
              -	 *   NumberUtils.toDouble(null)                     = 0.0d
              -	 *   NumberUtils.toDouble(BigDecimal.valudOf(8.5d)) = 8.5d
              -	 * 
              - * - * @param value the {@code BigDecimal} to convert, may be {@code null}. - * @return the double represented by the {@code BigDecimal} or {@code 0.0d} if - * the {@code BigDecimal} is {@code null}. - * @since 3.8 - */ - public static double toDouble(final BigDecimal value) { - return toDouble(value, 0.0d); - } - - /** - *

              - * Convert a {@code BigDecimal} to a {@code double}. - *

              - * - *

              - * If the {@code BigDecimal} {@code value} is {@code null}, then the specified - * default value is returned. - *

              - * - *
              -	 *   NumberUtils.toDouble(null, 1.1d)                     = 1.1d
              -	 *   NumberUtils.toDouble(BigDecimal.valudOf(8.5d), 1.1d) = 8.5d
              -	 * 
              - * - * @param value the {@code BigDecimal} to convert, may be {@code null}. - * @param defaultValue the default value - * @return the double represented by the {@code BigDecimal} or the defaultValue - * if the {@code BigDecimal} is {@code null}. - * @since 3.8 - */ - public static double toDouble(final BigDecimal value, final double defaultValue) { - return value == null ? defaultValue : value.doubleValue(); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Convert a {@code String} to a {@code byte}, returning {@code zero} if the - * conversion fails. - *

              - * - *

              - * If the string is {@code null}, {@code zero} is returned. - *

              - * - *
              -	 *   NumberUtils.toByte(null) = 0
              -	 *   NumberUtils.toByte("")   = 0
              -	 *   NumberUtils.toByte("1")  = 1
              -	 * 
              - * - * @param str the string to convert, may be null - * @return the byte represented by the string, or {@code zero} if conversion - * fails - * @since 2.5 - */ - public static byte toByte(final String str) { - return toByte(str, (byte) 0); - } - - /** - *

              - * Convert a {@code String} to a {@code byte}, returning a default value if the - * conversion fails. - *

              - * - *

              - * If the string is {@code null}, the default value is returned. - *

              - * - *
              -	 *   NumberUtils.toByte(null, 1) = 1
              -	 *   NumberUtils.toByte("", 1)   = 1
              -	 *   NumberUtils.toByte("1", 0)  = 1
              -	 * 
              - * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the byte represented by the string, or the default if conversion - * fails - * @since 2.5 - */ - public static byte toByte(final String str, final byte defaultValue) { - if (str == null) { - return defaultValue; - } - try { - return Byte.parseByte(str); - } catch (final NumberFormatException nfe) { - return defaultValue; - } - } - - /** - *

              - * Convert a {@code String} to a {@code short}, returning {@code zero} if the - * conversion fails. - *

              - * - *

              - * If the string is {@code null}, {@code zero} is returned. - *

              - * - *
              -	 *   NumberUtils.toShort(null) = 0
              -	 *   NumberUtils.toShort("")   = 0
              -	 *   NumberUtils.toShort("1")  = 1
              -	 * 
              - * - * @param str the string to convert, may be null - * @return the short represented by the string, or {@code zero} if conversion - * fails - * @since 2.5 - */ - public static short toShort(final String str) { - return toShort(str, (short) 0); - } - - /** - *

              - * Convert a {@code String} to an {@code short}, returning a default value if - * the conversion fails. - *

              - * - *

              - * If the string is {@code null}, the default value is returned. - *

              - * - *
              -	 *   NumberUtils.toShort(null, 1) = 1
              -	 *   NumberUtils.toShort("", 1)   = 1
              -	 *   NumberUtils.toShort("1", 0)  = 1
              -	 * 
              - * - * @param str the string to convert, may be null - * @param defaultValue the default value - * @return the short represented by the string, or the default if conversion - * fails - * @since 2.5 - */ - public static short toShort(final String str, final short defaultValue) { - if (str == null) { - return defaultValue; - } - try { - return Short.parseShort(str); - } catch (final NumberFormatException nfe) { - return defaultValue; - } - } - - /** - * Convert a {@code BigDecimal} to a {@code BigDecimal} with a scale of two that - * has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied - * {@code value} is null, then {@code BigDecimal.ZERO} is returned. - * - *

              - * Note, the scale of a {@code BigDecimal} is the number of digits to the right - * of the decimal point. - *

              - * - * @param value the {@code BigDecimal} to convert, may be null. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final BigDecimal value) { - return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); - } - - /** - * Convert a {@code BigDecimal} to a {@code BigDecimal} whose scale is the - * specified value with a {@code RoundingMode} applied. If the input - * {@code value} is {@code null}, we simply return {@code BigDecimal.ZERO}. - * - * @param value the {@code BigDecimal} to convert, may be null. - * @param scale the number of digits to the right of the decimal point. - * @param roundingMode a rounding behavior for numerical operations capable of - * discarding precision. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final BigDecimal value, final int scale, - final RoundingMode roundingMode) { - if (value == null) { - return BigDecimal.ZERO; - } - return value.setScale(scale, (roundingMode == null) ? RoundingMode.HALF_EVEN : roundingMode); - } - - /** - * Convert a {@code Float} to a {@code BigDecimal} with a scale of two that has - * been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied - * {@code value} is null, then {@code BigDecimal.ZERO} is returned. - * - *

              - * Note, the scale of a {@code BigDecimal} is the number of digits to the right - * of the decimal point. - *

              - * - * @param value the {@code Float} to convert, may be null. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final Float value) { - return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); - } - - /** - * Convert a {@code Float} to a {@code BigDecimal} whose scale is the specified - * value with a {@code RoundingMode} applied. If the input {@code value} is - * {@code null}, we simply return {@code BigDecimal.ZERO}. - * - * @param value the {@code Float} to convert, may be null. - * @param scale the number of digits to the right of the decimal point. - * @param roundingMode a rounding behavior for numerical operations capable of - * discarding precision. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final Float value, final int scale, final RoundingMode roundingMode) { - if (value == null) { - return BigDecimal.ZERO; - } - return toScaledBigDecimal(BigDecimal.valueOf(value), scale, roundingMode); - } - - /** - * Convert a {@code Double} to a {@code BigDecimal} with a scale of two that has - * been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied - * {@code value} is null, then {@code BigDecimal.ZERO} is returned. - * - *

              - * Note, the scale of a {@code BigDecimal} is the number of digits to the right - * of the decimal point. - *

              - * - * @param value the {@code Double} to convert, may be null. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final Double value) { - return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); - } - - /** - * Convert a {@code Double} to a {@code BigDecimal} whose scale is the specified - * value with a {@code RoundingMode} applied. If the input {@code value} is - * {@code null}, we simply return {@code BigDecimal.ZERO}. - * - * @param value the {@code Double} to convert, may be null. - * @param scale the number of digits to the right of the decimal point. - * @param roundingMode a rounding behavior for numerical operations capable of - * discarding precision. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final Double value, final int scale, final RoundingMode roundingMode) { - if (value == null) { - return BigDecimal.ZERO; - } - return toScaledBigDecimal(BigDecimal.valueOf(value), scale, roundingMode); - } - - /** - * Convert a {@code String} to a {@code BigDecimal} with a scale of two that has - * been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied - * {@code value} is null, then {@code BigDecimal.ZERO} is returned. - * - *

              - * Note, the scale of a {@code BigDecimal} is the number of digits to the right - * of the decimal point. - *

              - * - * @param value the {@code String} to convert, may be null. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final String value) { - return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); - } - - /** - * Convert a {@code String} to a {@code BigDecimal} whose scale is the specified - * value with a {@code RoundingMode} applied. If the input {@code value} is - * {@code null}, we simply return {@code BigDecimal.ZERO}. - * - * @param value the {@code String} to convert, may be null. - * @param scale the number of digits to the right of the decimal point. - * @param roundingMode a rounding behavior for numerical operations capable of - * discarding precision. - * @return the scaled, with appropriate rounding, {@code BigDecimal}. - * @since 3.8 - */ - public static BigDecimal toScaledBigDecimal(final String value, final int scale, final RoundingMode roundingMode) { - if (value == null) { - return BigDecimal.ZERO; - } - return toScaledBigDecimal(createBigDecimal(value), scale, roundingMode); - } - - // ----------------------------------------------------------------------- - // must handle Long, Float, Integer, Float, Short, - // BigDecimal, BigInteger and Byte - // useful methods: - // Byte.decode(String) - // Byte.valueOf(String, int radix) - // Byte.valueOf(String) - // Double.valueOf(String) - // Float.valueOf(String) - // Float.valueOf(String) - // Integer.valueOf(String, int radix) - // Integer.valueOf(String) - // Integer.decode(String) - // Integer.getInteger(String) - // Integer.getInteger(String, int val) - // Integer.getInteger(String, Integer val) - // Integer.valueOf(String) - // Double.valueOf(String) - // new Byte(String) - // Long.valueOf(String) - // Long.getLong(String) - // Long.getLong(String, int) - // Long.getLong(String, Integer) - // Long.valueOf(String, int) - // Long.valueOf(String) - // Short.valueOf(String) - // Short.decode(String) - // Short.valueOf(String, int) - // Short.valueOf(String) - // new BigDecimal(String) - // new BigInteger(String) - // new BigInteger(String, int radix) - // Possible inputs: - // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd - // plus minus everything. Prolly more. A lot are not separable. - /** *

              * Turns a string value into a java.lang.Number. @@ -955,805 +582,6 @@ public class NumberUtils { return !str.isEmpty(); } - // ----------------------------------------------------------------------- - /** - *

              - * Convert a {@code String} to a {@code Float}. - *

              - * - *

              - * Returns {@code null} if the string is {@code null}. - *

              - * - * @param str a {@code String} to convert, may be null - * @return converted {@code Float} (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static Float createFloat(final String str) { - if (str == null) { - return null; - } - return Float.valueOf(str); - } - - /** - *

              - * Convert a {@code String} to a {@code Double}. - *

              - * - *

              - * Returns {@code null} if the string is {@code null}. - *

              - * - * @param str a {@code String} to convert, may be null - * @return converted {@code Double} (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static Double createDouble(final String str) { - if (str == null) { - return null; - } - return Double.valueOf(str); - } - - /** - *

              - * Convert a {@code String} to a {@code Integer}, handling hex (0xhhhh) and - * octal (0dddd) notations. N.B. a leading zero means octal; spaces are not - * trimmed. - *

              - * - *

              - * Returns {@code null} if the string is {@code null}. - *

              - * - * @param str a {@code String} to convert, may be null - * @return converted {@code Integer} (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static Integer createInteger(final String str) { - if (str == null) { - return null; - } - // decode() handles 0xAABD and 0777 (hex and octal) as well. - return Integer.decode(str); - } - - /** - *

              - * Convert a {@code String} to a {@code Long}; since 3.1 it handles hex (0Xhhhh) - * and octal (0ddd) notations. N.B. a leading zero means octal; spaces are not - * trimmed. - *

              - * - *

              - * Returns {@code null} if the string is {@code null}. - *

              - * - * @param str a {@code String} to convert, may be null - * @return converted {@code Long} (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static Long createLong(final String str) { - if (str == null) { - return null; - } - return Long.decode(str); - } - - /** - *

              - * Convert a {@code String} to a {@code BigInteger}; since 3.2 it handles hex - * (0x or #) and octal (0) notations. - *

              - * - *

              - * Returns {@code null} if the string is {@code null}. - *

              - * - * @param str a {@code String} to convert, may be null - * @return converted {@code BigInteger} (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static BigInteger createBigInteger(final String str) { - if (str == null) { - return null; - } - int pos = 0; // offset within string - int radix = 10; - boolean negate = false; // need to negate later? - if (str.startsWith("-")) { - negate = true; - pos = 1; - } - if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex - radix = 16; - pos += 2; - } else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer) - radix = 16; - pos++; - } else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional - // digits - radix = 8; - pos++; - } // default is to treat as decimal - - final BigInteger value = new BigInteger(str.substring(pos), radix); - return negate ? value.negate() : value; - } - - /** - *

              - * Convert a {@code String} to a {@code BigDecimal}. - *

              - * - *

              - * Returns {@code null} if the string is {@code null}. - *

              - * - * @param str a {@code String} to convert, may be null - * @return converted {@code BigDecimal} (or null if the input is null) - * @throws NumberFormatException if the value cannot be converted - */ - public static BigDecimal createBigDecimal(final String str) { - if (str == null) { - return null; - } - // handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException - if (StringUtils.isBlank(str)) { - throw new NumberFormatException("A blank string is not a valid number"); - } - return new BigDecimal(str); - } - - // Min in array - // -------------------------------------------------------------------- - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from min(long[]) to min(long...) - */ - public static long min(final long... array) { - // Validates input - validateArray(array); - - // Finds and returns min - long min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from min(int[]) to min(int...) - */ - public static int min(final int... array) { - // Validates input - validateArray(array); - - // Finds and returns min - int min = array[0]; - for (int j = 1; j < array.length; j++) { - if (array[j] < min) { - min = array[j]; - } - } - - return min; - } - - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from min(short[]) to min(short...) - */ - public static short min(final short... array) { - // Validates input - validateArray(array); - - // Finds and returns min - short min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from min(byte[]) to min(byte...) - */ - public static byte min(final byte... array) { - // Validates input - validateArray(array); - - // Finds and returns min - byte min = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method - * that handles NaN differently - * @since 3.4 Changed signature from min(double[]) to min(double...) - */ - public static double min(final double... array) { - // Validates input - validateArray(array); - - // Finds and returns min - double min = array[0]; - for (int i = 1; i < array.length; i++) { - if (Double.isNaN(array[i])) { - return Double.NaN; - } - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - /** - *

              - * Returns the minimum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the minimum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method - * that handles NaN differently - * @since 3.4 Changed signature from min(float[]) to min(float...) - */ - public static float min(final float... array) { - // Validates input - validateArray(array); - - // Finds and returns min - float min = array[0]; - for (int i = 1; i < array.length; i++) { - if (Float.isNaN(array[i])) { - return Float.NaN; - } - if (array[i] < min) { - min = array[i]; - } - } - - return min; - } - - // Max in array - // -------------------------------------------------------------------- - /** - *

              - * Returns the maximum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the maximum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from max(long[]) to max(long...) - */ - public static long max(final long... array) { - // Validates input - validateArray(array); - - // Finds and returns max - long max = array[0]; - for (int j = 1; j < array.length; j++) { - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - *

              - * Returns the maximum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the maximum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from max(int[]) to max(int...) - */ - public static int max(final int... array) { - // Validates input - validateArray(array); - - // Finds and returns max - int max = array[0]; - for (int j = 1; j < array.length; j++) { - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - *

              - * Returns the maximum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the maximum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from max(short[]) to max(short...) - */ - public static short max(final short... array) { - // Validates input - validateArray(array); - - // Finds and returns max - short max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - - return max; - } - - /** - *

              - * Returns the maximum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the maximum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @since 3.4 Changed signature from max(byte[]) to max(byte...) - */ - public static byte max(final byte... array) { - // Validates input - validateArray(array); - - // Finds and returns max - byte max = array[0]; - for (int i = 1; i < array.length; i++) { - if (array[i] > max) { - max = array[i]; - } - } - - return max; - } - - /** - *

              - * Returns the maximum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the maximum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method - * that handles NaN differently - * @since 3.4 Changed signature from max(double[]) to max(double...) - */ - public static double max(final double... array) { - // Validates input - validateArray(array); - - // Finds and returns max - double max = array[0]; - for (int j = 1; j < array.length; j++) { - if (Double.isNaN(array[j])) { - return Double.NaN; - } - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - *

              - * Returns the maximum value in an array. - *

              - * - * @param array an array, must not be null or empty - * @return the maximum value in the array - * @throws IllegalArgumentException if {@code array} is {@code null} - * @throws IllegalArgumentException if {@code array} is empty - * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method - * that handles NaN differently - * @since 3.4 Changed signature from max(float[]) to max(float...) - */ - public static float max(final float... array) { - // Validates input - validateArray(array); - - // Finds and returns max - float max = array[0]; - for (int j = 1; j < array.length; j++) { - if (Float.isNaN(array[j])) { - return Float.NaN; - } - if (array[j] > max) { - max = array[j]; - } - } - - return max; - } - - /** - * Checks if the specified array is neither null nor empty. - * - * @param array the array to check - * @throws IllegalArgumentException if {@code array} is either {@code null} or - * empty - */ - private static void validateArray(final Object array) { - Validate.notNull(array, "array"); - Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); - } - - // 3 param min - // ----------------------------------------------------------------------- - /** - *

              - * Gets the minimum of three {@code long} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static long min(long a, final long b, final long c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the minimum of three {@code int} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static int min(int a, final int b, final int c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the minimum of three {@code short} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static short min(short a, final short b, final short c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the minimum of three {@code byte} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - */ - public static byte min(byte a, final byte b, final byte c) { - if (b < a) { - a = b; - } - if (c < a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the minimum of three {@code double} values. - *

              - * - *

              - * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - * @see IEEE754rUtils#min(double, double, double) for a version of this method - * that handles NaN differently - */ - public static double min(final double a, final double b, final double c) { - return Math.min(Math.min(a, b), c); - } - - /** - *

              - * Gets the minimum of three {@code float} values. - *

              - * - *

              - * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the smallest of the values - * @see IEEE754rUtils#min(float, float, float) for a version of this method that - * handles NaN differently - */ - public static float min(final float a, final float b, final float c) { - return Math.min(Math.min(a, b), c); - } - - // 3 param max - // ----------------------------------------------------------------------- - /** - *

              - * Gets the maximum of three {@code long} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static long max(long a, final long b, final long c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the maximum of three {@code int} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static int max(int a, final int b, final int c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the maximum of three {@code short} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static short max(short a, final short b, final short c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the maximum of three {@code byte} values. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - */ - public static byte max(byte a, final byte b, final byte c) { - if (b > a) { - a = b; - } - if (c > a) { - a = c; - } - return a; - } - - /** - *

              - * Gets the maximum of three {@code double} values. - *

              - * - *

              - * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - * @see IEEE754rUtils#max(double, double, double) for a version of this method - * that handles NaN differently - */ - public static double max(final double a, final double b, final double c) { - return Math.max(Math.max(a, b), c); - } - - /** - *

              - * Gets the maximum of three {@code float} values. - *

              - * - *

              - * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. - *

              - * - * @param a value 1 - * @param b value 2 - * @param c value 3 - * @return the largest of the values - * @see IEEE754rUtils#max(float, float, float) for a version of this method that - * handles NaN differently - */ - public static float max(final float a, final float b, final float c) { - return Math.max(Math.max(a, b), c); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Checks whether the {@code String} contains only digit characters. - *

              - * - *

              - * {@code Null} and empty String will return {@code false}. - *

              - * - * @param str the {@code String} to check - * @return {@code true} if str contains only Unicode numeric - */ - public static boolean isDigits(final String str) { - return StringUtils.isNumeric(str); - } - - /** - *

              - * Checks whether the String a valid Java number. - *

              - * - *

              - * Valid numbers include hexadecimal marked with the {@code 0x} or {@code 0X} - * qualifier, octal numbers, scientific notation and numbers marked with a type - * qualifier (e.g. 123L). - *

              - * - *

              - * Non-hexadecimal strings beginning with a leading zero are treated as octal - * values. Thus the string {@code 09} will return {@code false}, since {@code 9} - * is not a valid octal value. However, numbers beginning with {@code 0.} are - * treated as decimal. - *

              - * - *

              - * {@code null} and empty/blank {@code String} will return {@code false}. - *

              - * - *

              - * Note, {@link #createNumber(String)} should return a number for every input - * resulting in {@code true}. - *

              - * - * @param str the {@code String} to check - * @return {@code true} if the string is a correctly formatted number - * @since 3.3 the code supports hex {@code 0Xhhh} an octal {@code 0ddd} - * validation - * @deprecated This feature will be removed in Lang 4.0, use - * {@link NumberUtils#isCreatable(String)} instead - */ - @Deprecated - public static boolean isNumber(final String str) { - return isCreatable(str); - } - /** *

              * Checks whether the String a valid Java number. @@ -1893,6 +721,62 @@ public class NumberUtils { return !allowSigns && foundDigit; } + // ----------------------------------------------------------------------- + /** + *

              + * Checks whether the {@code String} contains only digit characters. + *

              + * + *

              + * {@code Null} and empty String will return {@code false}. + *

              + * + * @param str the {@code String} to check + * @return {@code true} if str contains only Unicode numeric + */ + public static boolean isDigits(final String str) { + return StringUtils.isNumeric(str); + } + + /** + *

              + * Checks whether the String a valid Java number. + *

              + * + *

              + * Valid numbers include hexadecimal marked with the {@code 0x} or {@code 0X} + * qualifier, octal numbers, scientific notation and numbers marked with a type + * qualifier (e.g. 123L). + *

              + * + *

              + * Non-hexadecimal strings beginning with a leading zero are treated as octal + * values. Thus the string {@code 09} will return {@code false}, since {@code 9} + * is not a valid octal value. However, numbers beginning with {@code 0.} are + * treated as decimal. + *

              + * + *

              + * {@code null} and empty/blank {@code String} will return {@code false}. + *

              + * + *

              + * Note, {@link #createNumber(String)} should return a number for every input + * resulting in {@code true}. + *

              + * + * @param str the {@code String} to check + * @return {@code true} if the string is a correctly formatted number + * @since 3.3 the code supports hex {@code 0Xhhh} an octal {@code 0ddd} + * validation + * @deprecated This feature will be removed in Lang 4.0, use + * {@link NumberUtils#isCreatable(String)} instead + */ + @Deprecated + public static boolean isNumber(final String str) { + return isCreatable(str); + } + /** *

              * Checks whether the given String is a parsable number. @@ -1935,6 +819,1180 @@ public class NumberUtils { return withDecimalsParsing(str, 0); } + /** + *

              + * Returns the maximum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from max(byte[]) to max(byte...) + */ + public static byte max(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns max + byte max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

              + * Gets the maximum of three {@code byte} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static byte max(byte a, final byte b, final byte c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

              + * Returns the maximum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @see IEEE754rUtils#max(double[]) IEEE754rUtils for a version of this method + * that handles NaN differently + * @since 3.4 Changed signature from max(double[]) to max(double...) + */ + public static double max(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns max + double max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Double.isNaN(array[j])) { + return Double.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

              + * Gets the maximum of three {@code double} values. + *

              + * + *

              + * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(double, double, double) for a version of this method + * that handles NaN differently + */ + public static double max(final double a, final double b, final double c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

              + * Returns the maximum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @see IEEE754rUtils#max(float[]) IEEE754rUtils for a version of this method + * that handles NaN differently + * @since 3.4 Changed signature from max(float[]) to max(float...) + */ + public static float max(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns max + float max = array[0]; + for (int j = 1; j < array.length; j++) { + if (Float.isNaN(array[j])) { + return Float.NaN; + } + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + // ----------------------------------------------------------------------- + // must handle Long, Float, Integer, Float, Short, + // BigDecimal, BigInteger and Byte + // useful methods: + // Byte.decode(String) + // Byte.valueOf(String, int radix) + // Byte.valueOf(String) + // Double.valueOf(String) + // Float.valueOf(String) + // Float.valueOf(String) + // Integer.valueOf(String, int radix) + // Integer.valueOf(String) + // Integer.decode(String) + // Integer.getInteger(String) + // Integer.getInteger(String, int val) + // Integer.getInteger(String, Integer val) + // Integer.valueOf(String) + // Double.valueOf(String) + // new Byte(String) + // Long.valueOf(String) + // Long.getLong(String) + // Long.getLong(String, int) + // Long.getLong(String, Integer) + // Long.valueOf(String, int) + // Long.valueOf(String) + // Short.valueOf(String) + // Short.decode(String) + // Short.valueOf(String, int) + // Short.valueOf(String) + // new BigDecimal(String) + // new BigInteger(String) + // new BigInteger(String, int radix) + // Possible inputs: + // 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd + // plus minus everything. Prolly more. A lot are not separable. + + /** + *

              + * Gets the maximum of three {@code float} values. + *

              + * + *

              + * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + * @see IEEE754rUtils#max(float, float, float) for a version of this method that + * handles NaN differently + */ + public static float max(final float a, final float b, final float c) { + return Math.max(Math.max(a, b), c); + } + + /** + *

              + * Returns the maximum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from max(int[]) to max(int...) + */ + public static int max(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns max + int max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + /** + *

              + * Gets the maximum of three {@code int} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static int max(int a, final int b, final int c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + // Max in array + // -------------------------------------------------------------------- + /** + *

              + * Returns the maximum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from max(long[]) to max(long...) + */ + public static long max(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns max + long max = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] > max) { + max = array[j]; + } + } + + return max; + } + + // 3 param max + // ----------------------------------------------------------------------- + /** + *

              + * Gets the maximum of three {@code long} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static long max(long a, final long b, final long c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

              + * Returns the maximum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the maximum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from max(short[]) to max(short...) + */ + public static short max(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns max + short max = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] > max) { + max = array[i]; + } + } + + return max; + } + + /** + *

              + * Gets the maximum of three {@code short} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the largest of the values + */ + public static short max(short a, final short b, final short c) { + if (b > a) { + a = b; + } + if (c > a) { + a = c; + } + return a; + } + + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from min(byte[]) to min(byte...) + */ + public static byte min(final byte... array) { + // Validates input + validateArray(array); + + // Finds and returns min + byte min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

              + * Gets the minimum of three {@code byte} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static byte min(byte a, final byte b, final byte c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @see IEEE754rUtils#min(double[]) IEEE754rUtils for a version of this method + * that handles NaN differently + * @since 3.4 Changed signature from min(double[]) to min(double...) + */ + public static double min(final double... array) { + // Validates input + validateArray(array); + + // Finds and returns min + double min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Double.isNaN(array[i])) { + return Double.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

              + * Gets the minimum of three {@code double} values. + *

              + * + *

              + * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(double, double, double) for a version of this method + * that handles NaN differently + */ + public static double min(final double a, final double b, final double c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @see IEEE754rUtils#min(float[]) IEEE754rUtils for a version of this method + * that handles NaN differently + * @since 3.4 Changed signature from min(float[]) to min(float...) + */ + public static float min(final float... array) { + // Validates input + validateArray(array); + + // Finds and returns min + float min = array[0]; + for (int i = 1; i < array.length; i++) { + if (Float.isNaN(array[i])) { + return Float.NaN; + } + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

              + * Gets the minimum of three {@code float} values. + *

              + * + *

              + * If any value is {@code NaN}, {@code NaN} is returned. Infinity is handled. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + * @see IEEE754rUtils#min(float, float, float) for a version of this method that + * handles NaN differently + */ + public static float min(final float a, final float b, final float c) { + return Math.min(Math.min(a, b), c); + } + + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from min(int[]) to min(int...) + */ + public static int min(final int... array) { + // Validates input + validateArray(array); + + // Finds and returns min + int min = array[0]; + for (int j = 1; j < array.length; j++) { + if (array[j] < min) { + min = array[j]; + } + } + + return min; + } + + /** + *

              + * Gets the minimum of three {@code int} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static int min(int a, final int b, final int c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + // Min in array + // -------------------------------------------------------------------- + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from min(long[]) to min(long...) + */ + public static long min(final long... array) { + // Validates input + validateArray(array); + + // Finds and returns min + long min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + // 3 param min + // ----------------------------------------------------------------------- + /** + *

              + * Gets the minimum of three {@code long} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static long min(long a, final long b, final long c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + /** + *

              + * Returns the minimum value in an array. + *

              + * + * @param array an array, must not be null or empty + * @return the minimum value in the array + * @throws IllegalArgumentException if {@code array} is {@code null} + * @throws IllegalArgumentException if {@code array} is empty + * @since 3.4 Changed signature from min(short[]) to min(short...) + */ + public static short min(final short... array) { + // Validates input + validateArray(array); + + // Finds and returns min + short min = array[0]; + for (int i = 1; i < array.length; i++) { + if (array[i] < min) { + min = array[i]; + } + } + + return min; + } + + /** + *

              + * Gets the minimum of three {@code short} values. + *

              + * + * @param a value 1 + * @param b value 2 + * @param c value 3 + * @return the smallest of the values + */ + public static short min(short a, final short b, final short c) { + if (b < a) { + a = b; + } + if (c < a) { + a = c; + } + return a; + } + + // ----------------------------------------------------------------------- + /** + *

              + * Convert a {@code String} to a {@code byte}, returning {@code zero} if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, {@code zero} is returned. + *

              + * + *
              +	 *   NumberUtils.toByte(null) = 0
              +	 *   NumberUtils.toByte("")   = 0
              +	 *   NumberUtils.toByte("1")  = 1
              +	 * 
              + * + * @param str the string to convert, may be null + * @return the byte represented by the string, or {@code zero} if conversion + * fails + * @since 2.5 + */ + public static byte toByte(final String str) { + return toByte(str, (byte) 0); + } + + /** + *

              + * Convert a {@code String} to a {@code byte}, returning a default value if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, the default value is returned. + *

              + * + *
              +	 *   NumberUtils.toByte(null, 1) = 1
              +	 *   NumberUtils.toByte("", 1)   = 1
              +	 *   NumberUtils.toByte("1", 0)  = 1
              +	 * 
              + * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the byte represented by the string, or the default if conversion + * fails + * @since 2.5 + */ + public static byte toByte(final String str, final byte defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Byte.parseByte(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

              + * Convert a {@code BigDecimal} to a {@code double}. + *

              + * + *

              + * If the {@code BigDecimal} {@code value} is {@code null}, then the specified + * default value is returned. + *

              + * + *
              +	 *   NumberUtils.toDouble(null)                     = 0.0d
              +	 *   NumberUtils.toDouble(BigDecimal.valudOf(8.5d)) = 8.5d
              +	 * 
              + * + * @param value the {@code BigDecimal} to convert, may be {@code null}. + * @return the double represented by the {@code BigDecimal} or {@code 0.0d} if + * the {@code BigDecimal} is {@code null}. + * @since 3.8 + */ + public static double toDouble(final BigDecimal value) { + return toDouble(value, 0.0d); + } + + /** + *

              + * Convert a {@code BigDecimal} to a {@code double}. + *

              + * + *

              + * If the {@code BigDecimal} {@code value} is {@code null}, then the specified + * default value is returned. + *

              + * + *
              +	 *   NumberUtils.toDouble(null, 1.1d)                     = 1.1d
              +	 *   NumberUtils.toDouble(BigDecimal.valudOf(8.5d), 1.1d) = 8.5d
              +	 * 
              + * + * @param value the {@code BigDecimal} to convert, may be {@code null}. + * @param defaultValue the default value + * @return the double represented by the {@code BigDecimal} or the defaultValue + * if the {@code BigDecimal} is {@code null}. + * @since 3.8 + */ + public static double toDouble(final BigDecimal value, final double defaultValue) { + return value == null ? defaultValue : value.doubleValue(); + } + + /** + *

              + * Convert a {@code String} to a {@code double}, returning {@code 0.0d} if the + * conversion fails. + *

              + * + *

              + * If the string {@code str} is {@code null}, {@code 0.0d} is returned. + *

              + * + *
              +	 *   NumberUtils.toDouble(null)   = 0.0d
              +	 *   NumberUtils.toDouble("")     = 0.0d
              +	 *   NumberUtils.toDouble("1.5")  = 1.5d
              +	 * 
              + * + * @param str the string to convert, may be {@code null} + * @return the double represented by the string, or {@code 0.0d} if conversion + * fails + * @since 2.1 + */ + public static double toDouble(final String str) { + return toDouble(str, 0.0d); + } + + /** + *

              + * Convert a {@code String} to a {@code double}, returning a default value if + * the conversion fails. + *

              + * + *

              + * If the string {@code str} is {@code null}, the default value is returned. + *

              + * + *
              +	 *   NumberUtils.toDouble(null, 1.1d)   = 1.1d
              +	 *   NumberUtils.toDouble("", 1.1d)     = 1.1d
              +	 *   NumberUtils.toDouble("1.5", 0.0d)  = 1.5d
              +	 * 
              + * + * @param str the string to convert, may be {@code null} + * @param defaultValue the default value + * @return the double represented by the string, or defaultValue if conversion + * fails + * @since 2.1 + */ + public static double toDouble(final String str, final double defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Double.parseDouble(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

              + * Convert a {@code String} to a {@code float}, returning {@code 0.0f} if the + * conversion fails. + *

              + * + *

              + * If the string {@code str} is {@code null}, {@code 0.0f} is returned. + *

              + * + *
              +	 *   NumberUtils.toFloat(null)   = 0.0f
              +	 *   NumberUtils.toFloat("")     = 0.0f
              +	 *   NumberUtils.toFloat("1.5")  = 1.5f
              +	 * 
              + * + * @param str the string to convert, may be {@code null} + * @return the float represented by the string, or {@code 0.0f} if conversion + * fails + * @since 2.1 + */ + public static float toFloat(final String str) { + return toFloat(str, 0.0f); + } + + /** + *

              + * Convert a {@code String} to a {@code float}, returning a default value if the + * conversion fails. + *

              + * + *

              + * If the string {@code str} is {@code null}, the default value is returned. + *

              + * + *
              +	 *   NumberUtils.toFloat(null, 1.1f)   = 1.0f
              +	 *   NumberUtils.toFloat("", 1.1f)     = 1.1f
              +	 *   NumberUtils.toFloat("1.5", 0.0f)  = 1.5f
              +	 * 
              + * + * @param str the string to convert, may be {@code null} + * @param defaultValue the default value + * @return the float represented by the string, or defaultValue if conversion + * fails + * @since 2.1 + */ + public static float toFloat(final String str, final float defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Float.parseFloat(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + // ----------------------------------------------------------------------- + /** + *

              + * Convert a {@code String} to an {@code int}, returning {@code zero} if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, {@code zero} is returned. + *

              + * + *
              +	 *   NumberUtils.toInt(null) = 0
              +	 *   NumberUtils.toInt("")   = 0
              +	 *   NumberUtils.toInt("1")  = 1
              +	 * 
              + * + * @param str the string to convert, may be null + * @return the int represented by the string, or {@code zero} if conversion + * fails + * @since 2.1 + */ + public static int toInt(final String str) { + return toInt(str, 0); + } + + /** + *

              + * Convert a {@code String} to an {@code int}, returning a default value if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, the default value is returned. + *

              + * + *
              +	 *   NumberUtils.toInt(null, 1) = 1
              +	 *   NumberUtils.toInt("", 1)   = 1
              +	 *   NumberUtils.toInt("1", 0)  = 1
              +	 * 
              + * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the int represented by the string, or the default if conversion fails + * @since 2.1 + */ + public static int toInt(final String str, final int defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Integer.parseInt(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + *

              + * Convert a {@code String} to a {@code long}, returning {@code zero} if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, {@code zero} is returned. + *

              + * + *
              +	 *   NumberUtils.toLong(null) = 0L
              +	 *   NumberUtils.toLong("")   = 0L
              +	 *   NumberUtils.toLong("1")  = 1L
              +	 * 
              + * + * @param str the string to convert, may be null + * @return the long represented by the string, or {@code 0} if conversion fails + * @since 2.1 + */ + public static long toLong(final String str) { + return toLong(str, 0L); + } + + /** + *

              + * Convert a {@code String} to a {@code long}, returning a default value if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, the default value is returned. + *

              + * + *
              +	 *   NumberUtils.toLong(null, 1L) = 1L
              +	 *   NumberUtils.toLong("", 1L)   = 1L
              +	 *   NumberUtils.toLong("1", 0L)  = 1L
              +	 * 
              + * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the long represented by the string, or the default if conversion + * fails + * @since 2.1 + */ + public static long toLong(final String str, final long defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Long.parseLong(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + * Convert a {@code BigDecimal} to a {@code BigDecimal} with a scale of two that + * has been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied + * {@code value} is null, then {@code BigDecimal.ZERO} is returned. + * + *

              + * Note, the scale of a {@code BigDecimal} is the number of digits to the right + * of the decimal point. + *

              + * + * @param value the {@code BigDecimal} to convert, may be null. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final BigDecimal value) { + return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); + } + + /** + * Convert a {@code BigDecimal} to a {@code BigDecimal} whose scale is the + * specified value with a {@code RoundingMode} applied. If the input + * {@code value} is {@code null}, we simply return {@code BigDecimal.ZERO}. + * + * @param value the {@code BigDecimal} to convert, may be null. + * @param scale the number of digits to the right of the decimal point. + * @param roundingMode a rounding behavior for numerical operations capable of + * discarding precision. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final BigDecimal value, final int scale, + final RoundingMode roundingMode) { + if (value == null) { + return BigDecimal.ZERO; + } + return value.setScale(scale, (roundingMode == null) ? RoundingMode.HALF_EVEN : roundingMode); + } + + /** + * Convert a {@code Double} to a {@code BigDecimal} with a scale of two that has + * been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied + * {@code value} is null, then {@code BigDecimal.ZERO} is returned. + * + *

              + * Note, the scale of a {@code BigDecimal} is the number of digits to the right + * of the decimal point. + *

              + * + * @param value the {@code Double} to convert, may be null. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final Double value) { + return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); + } + + /** + * Convert a {@code Double} to a {@code BigDecimal} whose scale is the specified + * value with a {@code RoundingMode} applied. If the input {@code value} is + * {@code null}, we simply return {@code BigDecimal.ZERO}. + * + * @param value the {@code Double} to convert, may be null. + * @param scale the number of digits to the right of the decimal point. + * @param roundingMode a rounding behavior for numerical operations capable of + * discarding precision. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final Double value, final int scale, final RoundingMode roundingMode) { + if (value == null) { + return BigDecimal.ZERO; + } + return toScaledBigDecimal(BigDecimal.valueOf(value), scale, roundingMode); + } + + /** + * Convert a {@code Float} to a {@code BigDecimal} with a scale of two that has + * been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied + * {@code value} is null, then {@code BigDecimal.ZERO} is returned. + * + *

              + * Note, the scale of a {@code BigDecimal} is the number of digits to the right + * of the decimal point. + *

              + * + * @param value the {@code Float} to convert, may be null. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final Float value) { + return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); + } + + /** + * Convert a {@code Float} to a {@code BigDecimal} whose scale is the specified + * value with a {@code RoundingMode} applied. If the input {@code value} is + * {@code null}, we simply return {@code BigDecimal.ZERO}. + * + * @param value the {@code Float} to convert, may be null. + * @param scale the number of digits to the right of the decimal point. + * @param roundingMode a rounding behavior for numerical operations capable of + * discarding precision. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final Float value, final int scale, final RoundingMode roundingMode) { + if (value == null) { + return BigDecimal.ZERO; + } + return toScaledBigDecimal(BigDecimal.valueOf(value), scale, roundingMode); + } + + /** + * Convert a {@code String} to a {@code BigDecimal} with a scale of two that has + * been rounded using {@code RoundingMode.HALF_EVEN}. If the supplied + * {@code value} is null, then {@code BigDecimal.ZERO} is returned. + * + *

              + * Note, the scale of a {@code BigDecimal} is the number of digits to the right + * of the decimal point. + *

              + * + * @param value the {@code String} to convert, may be null. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final String value) { + return toScaledBigDecimal(value, INTEGER_TWO, RoundingMode.HALF_EVEN); + } + + /** + * Convert a {@code String} to a {@code BigDecimal} whose scale is the specified + * value with a {@code RoundingMode} applied. If the input {@code value} is + * {@code null}, we simply return {@code BigDecimal.ZERO}. + * + * @param value the {@code String} to convert, may be null. + * @param scale the number of digits to the right of the decimal point. + * @param roundingMode a rounding behavior for numerical operations capable of + * discarding precision. + * @return the scaled, with appropriate rounding, {@code BigDecimal}. + * @since 3.8 + */ + public static BigDecimal toScaledBigDecimal(final String value, final int scale, final RoundingMode roundingMode) { + if (value == null) { + return BigDecimal.ZERO; + } + return toScaledBigDecimal(createBigDecimal(value), scale, roundingMode); + } + + /** + *

              + * Convert a {@code String} to a {@code short}, returning {@code zero} if the + * conversion fails. + *

              + * + *

              + * If the string is {@code null}, {@code zero} is returned. + *

              + * + *
              +	 *   NumberUtils.toShort(null) = 0
              +	 *   NumberUtils.toShort("")   = 0
              +	 *   NumberUtils.toShort("1")  = 1
              +	 * 
              + * + * @param str the string to convert, may be null + * @return the short represented by the string, or {@code zero} if conversion + * fails + * @since 2.5 + */ + public static short toShort(final String str) { + return toShort(str, (short) 0); + } + + /** + *

              + * Convert a {@code String} to an {@code short}, returning a default value if + * the conversion fails. + *

              + * + *

              + * If the string is {@code null}, the default value is returned. + *

              + * + *
              +	 *   NumberUtils.toShort(null, 1) = 1
              +	 *   NumberUtils.toShort("", 1)   = 1
              +	 *   NumberUtils.toShort("1", 0)  = 1
              +	 * 
              + * + * @param str the string to convert, may be null + * @param defaultValue the default value + * @return the short represented by the string, or the default if conversion + * fails + * @since 2.5 + */ + public static short toShort(final String str, final short defaultValue) { + if (str == null) { + return defaultValue; + } + try { + return Short.parseShort(str); + } catch (final NumberFormatException nfe) { + return defaultValue; + } + } + + /** + * Checks if the specified array is neither null nor empty. + * + * @param array the array to check + * @throws IllegalArgumentException if {@code array} is either {@code null} or + * empty + */ + private static void validateArray(final Object array) { + Validate.notNull(array, "array"); + Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty."); + } + private static boolean withDecimalsParsing(final String str, final int beginIdx) { int decimalPoints = 0; for (int i = beginIdx; i < str.length(); i++) { @@ -1954,74 +2012,16 @@ public class NumberUtils { /** *

              - * Compares two {@code int} values numerically. This is the same functionality - * as provided in Java 7. + * {@code NumberUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used as + * {@code NumberUtils.toInt("6");}. *

              * - * @param x the first {@code int} to compare - * @param y the second {@code int} to compare - * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if - * {@code x < y}; and a value greater than {@code 0} if {@code x > y} - * @since 3.4 - */ - public static int compare(final int x, final int y) { - if (x == y) { - return 0; - } - return x < y ? -1 : 1; - } - - /** *

              - * Compares to {@code long} values numerically. This is the same functionality - * as provided in Java 7. + * This constructor is public to permit tools that require a JavaBean instance + * to operate. *

              - * - * @param x the first {@code long} to compare - * @param y the second {@code long} to compare - * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if - * {@code x < y}; and a value greater than {@code 0} if {@code x > y} - * @since 3.4 */ - public static int compare(final long x, final long y) { - if (x == y) { - return 0; - } - return x < y ? -1 : 1; - } - - /** - *

              - * Compares to {@code short} values numerically. This is the same functionality - * as provided in Java 7. - *

              - * - * @param x the first {@code short} to compare - * @param y the second {@code short} to compare - * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if - * {@code x < y}; and a value greater than {@code 0} if {@code x > y} - * @since 3.4 - */ - public static int compare(final short x, final short y) { - if (x == y) { - return 0; - } - return x < y ? -1 : 1; - } - - /** - *

              - * Compares two {@code byte} values numerically. This is the same functionality - * as provided in Java 7. - *

              - * - * @param x the first {@code byte} to compare - * @param y the second {@code byte} to compare - * @return the value {@code 0} if {@code x == y}; a value less than {@code 0} if - * {@code x < y}; and a value greater than {@code 0} if {@code x > y} - * @since 3.4 - */ - public static int compare(final byte x, final byte y) { - return x - y; + public NumberUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableBoolean.java b/src/main/java/org/apache/commons/lang3/mutable/MutableBoolean.java index 95301ffc..3be10057 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableBoolean.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableBoolean.java @@ -67,6 +67,46 @@ public class MutableBoolean implements Mutable, Serializable, Comparabl this.value = value.booleanValue(); } + // ----------------------------------------------------------------------- + /** + * Returns the value of this MutableBoolean as a boolean. + * + * @return the boolean value represented by this object. + */ + public boolean booleanValue() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this mutable to another in ascending order. + * + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater where + * false is less than true + */ + @Override + public int compareTo(final MutableBoolean other) { + return BooleanUtils.compare(this.value, other.value); + } + + // ----------------------------------------------------------------------- + /** + * Compares this object to the specified object. The result is {@code true} if + * and only if the argument is not {@code null} and is an {@code MutableBoolean} + * object that contains the same {@code boolean} value as this object. + * + * @param obj the object to compare with, null returns false + * @return {@code true} if the objects are the same; {@code false} otherwise. + */ + @Override + public boolean equals(final Object obj) { + if (obj instanceof MutableBoolean) { + return value == ((MutableBoolean) obj).booleanValue(); + } + return false; + } + // ----------------------------------------------------------------------- /** * Gets the value as a Boolean instance. @@ -79,12 +119,35 @@ public class MutableBoolean implements Mutable, Serializable, Comparabl } /** - * Sets the value. + * Returns a suitable hash code for this mutable. * - * @param value the value to set + * @return the hash code returned by {@code Boolean.TRUE} or + * {@code Boolean.FALSE} */ - public void setValue(final boolean value) { - this.value = value; + @Override + public int hashCode() { + return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode(); + } + + /** + * Checks if the current value is {@code false}. + * + * @return {@code true} if the current value is {@code false} + * @since 2.5 + */ + public boolean isFalse() { + return !value; + } + + // ----------------------------------------------------------------------- + /** + * Checks if the current value is {@code true}. + * + * @return {@code true} if the current value is {@code true} + * @since 2.5 + */ + public boolean isTrue() { + return value; } /** @@ -105,6 +168,15 @@ public class MutableBoolean implements Mutable, Serializable, Comparabl this.value = true; } + /** + * Sets the value. + * + * @param value the value to set + */ + public void setValue(final boolean value) { + this.value = value; + } + /** * Sets the value from any Boolean instance. * @@ -116,37 +188,6 @@ public class MutableBoolean implements Mutable, Serializable, Comparabl this.value = value.booleanValue(); } - // ----------------------------------------------------------------------- - /** - * Checks if the current value is {@code true}. - * - * @return {@code true} if the current value is {@code true} - * @since 2.5 - */ - public boolean isTrue() { - return value; - } - - /** - * Checks if the current value is {@code false}. - * - * @return {@code true} if the current value is {@code false} - * @since 2.5 - */ - public boolean isFalse() { - return !value; - } - - // ----------------------------------------------------------------------- - /** - * Returns the value of this MutableBoolean as a boolean. - * - * @return the boolean value represented by this object. - */ - public boolean booleanValue() { - return value; - } - // ----------------------------------------------------------------------- /** * Gets this mutable as an instance of Boolean. @@ -158,47 +199,6 @@ public class MutableBoolean implements Mutable, Serializable, Comparabl return Boolean.valueOf(booleanValue()); } - // ----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is {@code true} if - * and only if the argument is not {@code null} and is an {@code MutableBoolean} - * object that contains the same {@code boolean} value as this object. - * - * @param obj the object to compare with, null returns false - * @return {@code true} if the objects are the same; {@code false} otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof MutableBoolean) { - return value == ((MutableBoolean) obj).booleanValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return the hash code returned by {@code Boolean.TRUE} or - * {@code Boolean.FALSE} - */ - @Override - public int hashCode() { - return value ? Boolean.TRUE.hashCode() : Boolean.FALSE.hashCode(); - } - - // ----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater where - * false is less than true - */ - @Override - public int compareTo(final MutableBoolean other) { - return BooleanUtils.compare(this.value, other.value); - } - // ----------------------------------------------------------------------- /** * Returns the String value of this mutable. diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableByte.java b/src/main/java/org/apache/commons/lang3/mutable/MutableByte.java index 0244b466..71edf032 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableByte.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableByte.java @@ -75,110 +75,6 @@ public class MutableByte extends Number implements Comparable, Muta this.value = Byte.parseByte(value); } - // ----------------------------------------------------------------------- - /** - * Gets the value as a Byte instance. - * - * @return the value as a Byte, never null - */ - @Override - public Byte getValue() { - return Byte.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(final byte value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - @Override - public void setValue(final Number value) { - this.value = value.byteValue(); - } - - // ----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since 2.2 - */ - public void increment() { - value++; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the increment operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was incremented - * @since 3.5 - */ - public byte getAndIncrement() { - final byte last = value; - value++; - return last; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately after the increment operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is incremented - * @since 3.5 - */ - public byte incrementAndGet() { - value++; - return value; - } - - /** - * Decrements the value. - * - * @since 2.2 - */ - public void decrement() { - value--; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the decrement operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was decremented - * @since 3.5 - */ - public byte getAndDecrement() { - final byte last = value; - value--; - return last; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately after the decrement operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is decremented - * @since 3.5 - */ - public byte decrementAndGet() { - value--; - return value; - } - // ----------------------------------------------------------------------- /** * Adds a value to the value of this instance. @@ -201,27 +97,6 @@ public class MutableByte extends Number implements Comparable, Muta this.value += operand.byteValue(); } - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since 2.2 - */ - public void subtract(final byte operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since 2.2 - */ - public void subtract(final Number operand) { - this.value -= operand.byteValue(); - } - /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately after the addition operation. @@ -251,6 +126,92 @@ public class MutableByte extends Number implements Comparable, Muta return value; } + // ----------------------------------------------------------------------- + // shortValue relies on Number implementation + /** + * Returns the value of this MutableByte as a byte. + * + * @return the numeric value represented by this object after conversion to type + * byte. + */ + @Override + public byte byteValue() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this mutable to another in ascending order. + * + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater + */ + @Override + public int compareTo(final MutableByte other) { + return NumberUtils.compare(this.value, other.value); + } + + /** + * Decrements the value. + * + * @since 2.2 + */ + public void decrement() { + value--; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately after the decrement operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is decremented + * @since 3.5 + */ + public byte decrementAndGet() { + value--; + return value; + } + + /** + * Returns the value of this MutableByte as a double. + * + * @return the numeric value represented by this object after conversion to type + * double. + */ + @Override + public double doubleValue() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this object to the specified object. The result is {@code true} if + * and only if the argument is not {@code null} and is a {@code MutableByte} + * object that contains the same {@code byte} value as this object. + * + * @param obj the object to compare with, null returns false + * @return {@code true} if the objects are the same; {@code false} otherwise. + */ + @Override + public boolean equals(final Object obj) { + if (obj instanceof MutableByte) { + return value == ((MutableByte) obj).byteValue(); + } + return false; + } + + /** + * Returns the value of this MutableByte as a float. + * + * @return the numeric value represented by this object after conversion to type + * float. + */ + @Override + public float floatValue() { + return value; + } + /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately prior to the addition @@ -284,16 +245,75 @@ public class MutableByte extends Number implements Comparable, Muta return last; } - // ----------------------------------------------------------------------- - // shortValue relies on Number implementation /** - * Returns the value of this MutableByte as a byte. + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the decrement operation. + * This method is not thread safe. * - * @return the numeric value represented by this object after conversion to type - * byte. + * @return the value associated with the instance before it was decremented + * @since 3.5 + */ + public byte getAndDecrement() { + final byte last = value; + value--; + return last; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the increment operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was incremented + * @since 3.5 + */ + public byte getAndIncrement() { + final byte last = value; + value++; + return last; + } + + // ----------------------------------------------------------------------- + /** + * Gets the value as a Byte instance. + * + * @return the value as a Byte, never null */ @Override - public byte byteValue() { + public Byte getValue() { + return Byte.valueOf(this.value); + } + + /** + * Returns a suitable hash code for this mutable. + * + * @return a suitable hash code + */ + @Override + public int hashCode() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Increments the value. + * + * @since 2.2 + */ + public void increment() { + value++; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately after the increment operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is incremented + * @since 3.5 + */ + public byte incrementAndGet() { + value++; return value; } @@ -320,25 +340,44 @@ public class MutableByte extends Number implements Comparable, Muta } /** - * Returns the value of this MutableByte as a float. + * Sets the value. * - * @return the numeric value represented by this object after conversion to type - * float. + * @param value the value to set */ - @Override - public float floatValue() { - return value; + public void setValue(final byte value) { + this.value = value; } /** - * Returns the value of this MutableByte as a double. + * Sets the value from any Number instance. * - * @return the numeric value represented by this object after conversion to type - * double. + * @param value the value to set, not null + * @throws NullPointerException if the object is null */ @Override - public double doubleValue() { - return value; + public void setValue(final Number value) { + this.value = value.byteValue(); + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @since 2.2 + */ + public void subtract(final byte operand) { + this.value -= operand; + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @throws NullPointerException if the object is null + * @since 2.2 + */ + public void subtract(final Number operand) { + this.value -= operand.byteValue(); } // ----------------------------------------------------------------------- @@ -351,45 +390,6 @@ public class MutableByte extends Number implements Comparable, Muta return Byte.valueOf(byteValue()); } - // ----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is {@code true} if - * and only if the argument is not {@code null} and is a {@code MutableByte} - * object that contains the same {@code byte} value as this object. - * - * @param obj the object to compare with, null returns false - * @return {@code true} if the objects are the same; {@code false} otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof MutableByte) { - return value == ((MutableByte) obj).byteValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return value; - } - - // ----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - @Override - public int compareTo(final MutableByte other) { - return NumberUtils.compare(this.value, other.value); - } - // ----------------------------------------------------------------------- /** * Returns the String value of this mutable. diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java b/src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java index 1754e360..c17d2579 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableDouble.java @@ -73,129 +73,6 @@ public class MutableDouble extends Number implements Comparable, this.value = Double.parseDouble(value); } - // ----------------------------------------------------------------------- - /** - * Gets the value as a Double instance. - * - * @return the value as a Double, never null - */ - @Override - public Double getValue() { - return Double.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(final double value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - @Override - public void setValue(final Number value) { - this.value = value.doubleValue(); - } - - // ----------------------------------------------------------------------- - /** - * Checks whether the double value is the special NaN value. - * - * @return true if NaN - */ - public boolean isNaN() { - return Double.isNaN(value); - } - - /** - * Checks whether the double value is infinite. - * - * @return true if infinite - */ - public boolean isInfinite() { - return Double.isInfinite(value); - } - - // ----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since 2.2 - */ - public void increment() { - value++; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the increment operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was incremented - * @since 3.5 - */ - public double getAndIncrement() { - final double last = value; - value++; - return last; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately after the increment operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is incremented - * @since 3.5 - */ - public double incrementAndGet() { - value++; - return value; - } - - /** - * Decrements the value. - * - * @since 2.2 - */ - public void decrement() { - value--; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the decrement operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was decremented - * @since 3.5 - */ - public double getAndDecrement() { - final double last = value; - value--; - return last; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately after the decrement operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is decremented - * @since 3.5 - */ - public double decrementAndGet() { - value--; - return value; - } - // ----------------------------------------------------------------------- /** * Adds a value to the value of this instance. @@ -218,27 +95,6 @@ public class MutableDouble extends Number implements Comparable, this.value += operand.doubleValue(); } - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since 2.2 - */ - public void subtract(final double operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since 2.2 - */ - public void subtract(final Number operand) { - this.value -= operand.doubleValue(); - } - /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately after the addition operation. @@ -268,72 +124,38 @@ public class MutableDouble extends Number implements Comparable, return value; } - /** - * Increments this instance's value by {@code operand}; this method returns the - * value associated with the instance immediately prior to the addition - * operation. This method is not thread safe. - * - * @param operand the quantity to add, not null - * @return the value associated with this instance immediately before the - * operand was added - * @since 3.5 - */ - public double getAndAdd(final double operand) { - final double last = value; - this.value += operand; - return last; - } - - /** - * Increments this instance's value by {@code operand}; this method returns the - * value associated with the instance immediately prior to the addition - * operation. This method is not thread safe. - * - * @param operand the quantity to add, not null - * @throws NullPointerException if {@code operand} is null - * @return the value associated with this instance immediately before the - * operand was added - * @since 3.5 - */ - public double getAndAdd(final Number operand) { - final double last = value; - this.value += operand.doubleValue(); - return last; - } - // ----------------------------------------------------------------------- - // shortValue and byteValue rely on Number implementation /** - * Returns the value of this MutableDouble as an int. + * Compares this mutable to another in ascending order. * - * @return the numeric value represented by this object after conversion to type - * int. + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater */ @Override - public int intValue() { - return (int) value; + public int compareTo(final MutableDouble other) { + return Double.compare(this.value, other.value); } /** - * Returns the value of this MutableDouble as a long. + * Decrements the value. * - * @return the numeric value represented by this object after conversion to type - * long. + * @since 2.2 */ - @Override - public long longValue() { - return (long) value; + public void decrement() { + value--; } /** - * Returns the value of this MutableDouble as a float. + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately after the decrement operation. This + * method is not thread safe. * - * @return the numeric value represented by this object after conversion to type - * float. + * @return the value associated with the instance after it is decremented + * @since 3.5 */ - @Override - public float floatValue() { - return (float) value; + public double decrementAndGet() { + value--; + return value; } /** @@ -347,16 +169,6 @@ public class MutableDouble extends Number implements Comparable, return value; } - // ----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Double. - * - * @return a Double instance containing the value from this mutable, never null - */ - public Double toDouble() { - return Double.valueOf(doubleValue()); - } - // ----------------------------------------------------------------------- /** * Compares this object against the specified object. The result is {@code true} @@ -397,6 +209,89 @@ public class MutableDouble extends Number implements Comparable, && Double.doubleToLongBits(((MutableDouble) obj).value) == Double.doubleToLongBits(value); } + /** + * Returns the value of this MutableDouble as a float. + * + * @return the numeric value represented by this object after conversion to type + * float. + */ + @Override + public float floatValue() { + return (float) value; + } + + /** + * Increments this instance's value by {@code operand}; this method returns the + * value associated with the instance immediately prior to the addition + * operation. This method is not thread safe. + * + * @param operand the quantity to add, not null + * @return the value associated with this instance immediately before the + * operand was added + * @since 3.5 + */ + public double getAndAdd(final double operand) { + final double last = value; + this.value += operand; + return last; + } + + /** + * Increments this instance's value by {@code operand}; this method returns the + * value associated with the instance immediately prior to the addition + * operation. This method is not thread safe. + * + * @param operand the quantity to add, not null + * @throws NullPointerException if {@code operand} is null + * @return the value associated with this instance immediately before the + * operand was added + * @since 3.5 + */ + public double getAndAdd(final Number operand) { + final double last = value; + this.value += operand.doubleValue(); + return last; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the decrement operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was decremented + * @since 3.5 + */ + public double getAndDecrement() { + final double last = value; + value--; + return last; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the increment operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was incremented + * @since 3.5 + */ + public double getAndIncrement() { + final double last = value; + value++; + return last; + } + + // ----------------------------------------------------------------------- + /** + * Gets the value as a Double instance. + * + * @return the value as a Double, never null + */ + @Override + public Double getValue() { + return Double.valueOf(this.value); + } + /** * Returns a suitable hash code for this mutable. * @@ -410,14 +305,119 @@ public class MutableDouble extends Number implements Comparable, // ----------------------------------------------------------------------- /** - * Compares this mutable to another in ascending order. + * Increments the value. * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater + * @since 2.2 + */ + public void increment() { + value++; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately after the increment operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is incremented + * @since 3.5 + */ + public double incrementAndGet() { + value++; + return value; + } + + // ----------------------------------------------------------------------- + // shortValue and byteValue rely on Number implementation + /** + * Returns the value of this MutableDouble as an int. + * + * @return the numeric value represented by this object after conversion to type + * int. */ @Override - public int compareTo(final MutableDouble other) { - return Double.compare(this.value, other.value); + public int intValue() { + return (int) value; + } + + /** + * Checks whether the double value is infinite. + * + * @return true if infinite + */ + public boolean isInfinite() { + return Double.isInfinite(value); + } + + // ----------------------------------------------------------------------- + /** + * Checks whether the double value is the special NaN value. + * + * @return true if NaN + */ + public boolean isNaN() { + return Double.isNaN(value); + } + + /** + * Returns the value of this MutableDouble as a long. + * + * @return the numeric value represented by this object after conversion to type + * long. + */ + @Override + public long longValue() { + return (long) value; + } + + /** + * Sets the value. + * + * @param value the value to set + */ + public void setValue(final double value) { + this.value = value; + } + + /** + * Sets the value from any Number instance. + * + * @param value the value to set, not null + * @throws NullPointerException if the object is null + */ + @Override + public void setValue(final Number value) { + this.value = value.doubleValue(); + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @since 2.2 + */ + public void subtract(final double operand) { + this.value -= operand; + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @throws NullPointerException if the object is null + * @since 2.2 + */ + public void subtract(final Number operand) { + this.value -= operand.doubleValue(); + } + + // ----------------------------------------------------------------------- + /** + * Gets this mutable as an instance of Double. + * + * @return a Double instance containing the value from this mutable, never null + */ + public Double toDouble() { + return Double.valueOf(doubleValue()); } // ----------------------------------------------------------------------- diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableFloat.java b/src/main/java/org/apache/commons/lang3/mutable/MutableFloat.java index 7315a595..810c91e3 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableFloat.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableFloat.java @@ -73,129 +73,6 @@ public class MutableFloat extends Number implements Comparable, Mu this.value = Float.parseFloat(value); } - // ----------------------------------------------------------------------- - /** - * Gets the value as a Float instance. - * - * @return the value as a Float, never null - */ - @Override - public Float getValue() { - return Float.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(final float value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - @Override - public void setValue(final Number value) { - this.value = value.floatValue(); - } - - // ----------------------------------------------------------------------- - /** - * Checks whether the float value is the special NaN value. - * - * @return true if NaN - */ - public boolean isNaN() { - return Float.isNaN(value); - } - - /** - * Checks whether the float value is infinite. - * - * @return true if infinite - */ - public boolean isInfinite() { - return Float.isInfinite(value); - } - - // ----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since 2.2 - */ - public void increment() { - value++; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the increment operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was incremented - * @since 3.5 - */ - public float getAndIncrement() { - final float last = value; - value++; - return last; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately after the increment operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is incremented - * @since 3.5 - */ - public float incrementAndGet() { - value++; - return value; - } - - /** - * Decrements the value. - * - * @since 2.2 - */ - public void decrement() { - value--; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the decrement operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was decremented - * @since 3.5 - */ - public float getAndDecrement() { - final float last = value; - value--; - return last; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately after the decrement operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is decremented - * @since 3.5 - */ - public float decrementAndGet() { - value--; - return value; - } - // ----------------------------------------------------------------------- /** * Adds a value to the value of this instance. @@ -218,27 +95,6 @@ public class MutableFloat extends Number implements Comparable, Mu this.value += operand.floatValue(); } - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract - * @since 2.2 - */ - public void subtract(final float operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since 2.2 - */ - public void subtract(final Number operand) { - this.value -= operand.floatValue(); - } - /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately after the addition operation. @@ -268,71 +124,37 @@ public class MutableFloat extends Number implements Comparable, Mu return value; } - /** - * Increments this instance's value by {@code operand}; this method returns the - * value associated with the instance immediately prior to the addition - * operation. This method is not thread safe. - * - * @param operand the quantity to add, not null - * @return the value associated with this instance immediately before the - * operand was added - * @since 3.5 - */ - public float getAndAdd(final float operand) { - final float last = value; - this.value += operand; - return last; - } - - /** - * Increments this instance's value by {@code operand}; this method returns the - * value associated with the instance immediately prior to the addition - * operation. This method is not thread safe. - * - * @param operand the quantity to add, not null - * @throws NullPointerException if {@code operand} is null - * @return the value associated with this instance immediately before the - * operand was added - * @since 3.5 - */ - public float getAndAdd(final Number operand) { - final float last = value; - this.value += operand.floatValue(); - return last; - } - // ----------------------------------------------------------------------- - // shortValue and byteValue rely on Number implementation /** - * Returns the value of this MutableFloat as an int. + * Compares this mutable to another in ascending order. * - * @return the numeric value represented by this object after conversion to type - * int. + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater */ @Override - public int intValue() { - return (int) value; + public int compareTo(final MutableFloat other) { + return Float.compare(this.value, other.value); } /** - * Returns the value of this MutableFloat as a long. + * Decrements the value. * - * @return the numeric value represented by this object after conversion to type - * long. + * @since 2.2 */ - @Override - public long longValue() { - return (long) value; + public void decrement() { + value--; } /** - * Returns the value of this MutableFloat as a float. + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately after the decrement operation. This + * method is not thread safe. * - * @return the numeric value represented by this object after conversion to type - * float. + * @return the value associated with the instance after it is decremented + * @since 3.5 */ - @Override - public float floatValue() { + public float decrementAndGet() { + value--; return value; } @@ -347,16 +169,6 @@ public class MutableFloat extends Number implements Comparable, Mu return value; } - // ----------------------------------------------------------------------- - /** - * Gets this mutable as an instance of Float. - * - * @return a Float instance containing the value from this mutable, never null - */ - public Float toFloat() { - return Float.valueOf(floatValue()); - } - // ----------------------------------------------------------------------- /** * Compares this object against some other object. The result is {@code true} if @@ -398,6 +210,89 @@ public class MutableFloat extends Number implements Comparable, Mu && Float.floatToIntBits(((MutableFloat) obj).value) == Float.floatToIntBits(value); } + /** + * Returns the value of this MutableFloat as a float. + * + * @return the numeric value represented by this object after conversion to type + * float. + */ + @Override + public float floatValue() { + return value; + } + + /** + * Increments this instance's value by {@code operand}; this method returns the + * value associated with the instance immediately prior to the addition + * operation. This method is not thread safe. + * + * @param operand the quantity to add, not null + * @return the value associated with this instance immediately before the + * operand was added + * @since 3.5 + */ + public float getAndAdd(final float operand) { + final float last = value; + this.value += operand; + return last; + } + + /** + * Increments this instance's value by {@code operand}; this method returns the + * value associated with the instance immediately prior to the addition + * operation. This method is not thread safe. + * + * @param operand the quantity to add, not null + * @throws NullPointerException if {@code operand} is null + * @return the value associated with this instance immediately before the + * operand was added + * @since 3.5 + */ + public float getAndAdd(final Number operand) { + final float last = value; + this.value += operand.floatValue(); + return last; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the decrement operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was decremented + * @since 3.5 + */ + public float getAndDecrement() { + final float last = value; + value--; + return last; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the increment operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was incremented + * @since 3.5 + */ + public float getAndIncrement() { + final float last = value; + value++; + return last; + } + + // ----------------------------------------------------------------------- + /** + * Gets the value as a Float instance. + * + * @return the value as a Float, never null + */ + @Override + public Float getValue() { + return Float.valueOf(this.value); + } + /** * Returns a suitable hash code for this mutable. * @@ -410,14 +305,119 @@ public class MutableFloat extends Number implements Comparable, Mu // ----------------------------------------------------------------------- /** - * Compares this mutable to another in ascending order. + * Increments the value. * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater + * @since 2.2 + */ + public void increment() { + value++; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately after the increment operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is incremented + * @since 3.5 + */ + public float incrementAndGet() { + value++; + return value; + } + + // ----------------------------------------------------------------------- + // shortValue and byteValue rely on Number implementation + /** + * Returns the value of this MutableFloat as an int. + * + * @return the numeric value represented by this object after conversion to type + * int. */ @Override - public int compareTo(final MutableFloat other) { - return Float.compare(this.value, other.value); + public int intValue() { + return (int) value; + } + + /** + * Checks whether the float value is infinite. + * + * @return true if infinite + */ + public boolean isInfinite() { + return Float.isInfinite(value); + } + + // ----------------------------------------------------------------------- + /** + * Checks whether the float value is the special NaN value. + * + * @return true if NaN + */ + public boolean isNaN() { + return Float.isNaN(value); + } + + /** + * Returns the value of this MutableFloat as a long. + * + * @return the numeric value represented by this object after conversion to type + * long. + */ + @Override + public long longValue() { + return (long) value; + } + + /** + * Sets the value. + * + * @param value the value to set + */ + public void setValue(final float value) { + this.value = value; + } + + /** + * Sets the value from any Number instance. + * + * @param value the value to set, not null + * @throws NullPointerException if the object is null + */ + @Override + public void setValue(final Number value) { + this.value = value.floatValue(); + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract + * @since 2.2 + */ + public void subtract(final float operand) { + this.value -= operand; + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @throws NullPointerException if the object is null + * @since 2.2 + */ + public void subtract(final Number operand) { + this.value -= operand.floatValue(); + } + + // ----------------------------------------------------------------------- + /** + * Gets this mutable as an instance of Float. + * + * @return a Float instance containing the value from this mutable, never null + */ + public Float toFloat() { + return Float.valueOf(floatValue()); } // ----------------------------------------------------------------------- diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableInt.java b/src/main/java/org/apache/commons/lang3/mutable/MutableInt.java index 90c2d8b2..f11003c6 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableInt.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableInt.java @@ -75,110 +75,6 @@ public class MutableInt extends Number implements Comparable, Mutabl this.value = Integer.parseInt(value); } - // ----------------------------------------------------------------------- - /** - * Gets the value as a Integer instance. - * - * @return the value as a Integer, never null - */ - @Override - public Integer getValue() { - return Integer.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(final int value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - @Override - public void setValue(final Number value) { - this.value = value.intValue(); - } - - // ----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since 2.2 - */ - public void increment() { - value++; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the increment operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was incremented - * @since 3.5 - */ - public int getAndIncrement() { - final int last = value; - value++; - return last; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately after the increment operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is incremented - * @since 3.5 - */ - public int incrementAndGet() { - value++; - return value; - } - - /** - * Decrements the value. - * - * @since 2.2 - */ - public void decrement() { - value--; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the decrement operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was decremented - * @since 3.5 - */ - public int getAndDecrement() { - final int last = value; - value--; - return last; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately after the decrement operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is decremented - * @since 3.5 - */ - public int decrementAndGet() { - value--; - return value; - } - // ----------------------------------------------------------------------- /** * Adds a value to the value of this instance. @@ -201,27 +97,6 @@ public class MutableInt extends Number implements Comparable, Mutabl this.value += operand.intValue(); } - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since 2.2 - */ - public void subtract(final int operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since 2.2 - */ - public void subtract(final Number operand) { - this.value -= operand.intValue(); - } - /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately after the addition operation. @@ -251,6 +126,79 @@ public class MutableInt extends Number implements Comparable, Mutabl return value; } + // ----------------------------------------------------------------------- + /** + * Compares this mutable to another in ascending order. + * + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater + */ + @Override + public int compareTo(final MutableInt other) { + return NumberUtils.compare(this.value, other.value); + } + + /** + * Decrements the value. + * + * @since 2.2 + */ + public void decrement() { + value--; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately after the decrement operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is decremented + * @since 3.5 + */ + public int decrementAndGet() { + value--; + return value; + } + + /** + * Returns the value of this MutableInt as a double. + * + * @return the numeric value represented by this object after conversion to type + * double. + */ + @Override + public double doubleValue() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this object to the specified object. The result is {@code true} if + * and only if the argument is not {@code null} and is a {@code MutableInt} + * object that contains the same {@code int} value as this object. + * + * @param obj the object to compare with, null returns false + * @return {@code true} if the objects are the same; {@code false} otherwise. + */ + @Override + public boolean equals(final Object obj) { + if (obj instanceof MutableInt) { + return value == ((MutableInt) obj).intValue(); + } + return false; + } + + /** + * Returns the value of this MutableInt as a float. + * + * @return the numeric value represented by this object after conversion to type + * float. + */ + @Override + public float floatValue() { + return value; + } + /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately prior to the addition @@ -284,6 +232,78 @@ public class MutableInt extends Number implements Comparable, Mutabl return last; } + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the decrement operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was decremented + * @since 3.5 + */ + public int getAndDecrement() { + final int last = value; + value--; + return last; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the increment operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was incremented + * @since 3.5 + */ + public int getAndIncrement() { + final int last = value; + value++; + return last; + } + + // ----------------------------------------------------------------------- + /** + * Gets the value as a Integer instance. + * + * @return the value as a Integer, never null + */ + @Override + public Integer getValue() { + return Integer.valueOf(this.value); + } + + /** + * Returns a suitable hash code for this mutable. + * + * @return a suitable hash code + */ + @Override + public int hashCode() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Increments the value. + * + * @since 2.2 + */ + public void increment() { + value++; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately after the increment operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is incremented + * @since 3.5 + */ + public int incrementAndGet() { + value++; + return value; + } + // ----------------------------------------------------------------------- // shortValue and byteValue rely on Number implementation /** @@ -309,25 +329,44 @@ public class MutableInt extends Number implements Comparable, Mutabl } /** - * Returns the value of this MutableInt as a float. + * Sets the value. * - * @return the numeric value represented by this object after conversion to type - * float. + * @param value the value to set */ - @Override - public float floatValue() { - return value; + public void setValue(final int value) { + this.value = value; } /** - * Returns the value of this MutableInt as a double. + * Sets the value from any Number instance. * - * @return the numeric value represented by this object after conversion to type - * double. + * @param value the value to set, not null + * @throws NullPointerException if the object is null */ @Override - public double doubleValue() { - return value; + public void setValue(final Number value) { + this.value = value.intValue(); + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @since 2.2 + */ + public void subtract(final int operand) { + this.value -= operand; + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @throws NullPointerException if the object is null + * @since 2.2 + */ + public void subtract(final Number operand) { + this.value -= operand.intValue(); } // ----------------------------------------------------------------------- @@ -340,45 +379,6 @@ public class MutableInt extends Number implements Comparable, Mutabl return Integer.valueOf(intValue()); } - // ----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is {@code true} if - * and only if the argument is not {@code null} and is a {@code MutableInt} - * object that contains the same {@code int} value as this object. - * - * @param obj the object to compare with, null returns false - * @return {@code true} if the objects are the same; {@code false} otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof MutableInt) { - return value == ((MutableInt) obj).intValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return value; - } - - // ----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - @Override - public int compareTo(final MutableInt other) { - return NumberUtils.compare(this.value, other.value); - } - // ----------------------------------------------------------------------- /** * Returns the String value of this mutable. diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableLong.java b/src/main/java/org/apache/commons/lang3/mutable/MutableLong.java index 7b8ae315..96e9f233 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableLong.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableLong.java @@ -75,110 +75,6 @@ public class MutableLong extends Number implements Comparable, Muta this.value = Long.parseLong(value); } - // ----------------------------------------------------------------------- - /** - * Gets the value as a Long instance. - * - * @return the value as a Long, never null - */ - @Override - public Long getValue() { - return Long.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(final long value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - @Override - public void setValue(final Number value) { - this.value = value.longValue(); - } - - // ----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since 2.2 - */ - public void increment() { - value++; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the increment operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was incremented - * @since 3.5 - */ - public long getAndIncrement() { - final long last = value; - value++; - return last; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately after the increment operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is incremented - * @since 3.5 - */ - public long incrementAndGet() { - value++; - return value; - } - - /** - * Decrements the value. - * - * @since 2.2 - */ - public void decrement() { - value--; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the decrement operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was decremented - * @since 3.5 - */ - public long getAndDecrement() { - final long last = value; - value--; - return last; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately after the decrement operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is decremented - * @since 3.5 - */ - public long decrementAndGet() { - value--; - return value; - } - // ----------------------------------------------------------------------- /** * Adds a value to the value of this instance. @@ -201,27 +97,6 @@ public class MutableLong extends Number implements Comparable, Muta this.value += operand.longValue(); } - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @since 2.2 - */ - public void subtract(final long operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since 2.2 - */ - public void subtract(final Number operand) { - this.value -= operand.longValue(); - } - /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately after the addition operation. @@ -251,6 +126,79 @@ public class MutableLong extends Number implements Comparable, Muta return value; } + // ----------------------------------------------------------------------- + /** + * Compares this mutable to another in ascending order. + * + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater + */ + @Override + public int compareTo(final MutableLong other) { + return NumberUtils.compare(this.value, other.value); + } + + /** + * Decrements the value. + * + * @since 2.2 + */ + public void decrement() { + value--; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately after the decrement operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is decremented + * @since 3.5 + */ + public long decrementAndGet() { + value--; + return value; + } + + /** + * Returns the value of this MutableLong as a double. + * + * @return the numeric value represented by this object after conversion to type + * double. + */ + @Override + public double doubleValue() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this object to the specified object. The result is {@code true} if + * and only if the argument is not {@code null} and is a {@code MutableLong} + * object that contains the same {@code long} value as this object. + * + * @param obj the object to compare with, null returns false + * @return {@code true} if the objects are the same; {@code false} otherwise. + */ + @Override + public boolean equals(final Object obj) { + if (obj instanceof MutableLong) { + return value == ((MutableLong) obj).longValue(); + } + return false; + } + + /** + * Returns the value of this MutableLong as a float. + * + * @return the numeric value represented by this object after conversion to type + * float. + */ + @Override + public float floatValue() { + return value; + } + /** * Increments this instance's value by {@code operand}; this method returns the * value associated with the instance immediately prior to the addition @@ -284,6 +232,78 @@ public class MutableLong extends Number implements Comparable, Muta return last; } + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the decrement operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was decremented + * @since 3.5 + */ + public long getAndDecrement() { + final long last = value; + value--; + return last; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the increment operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was incremented + * @since 3.5 + */ + public long getAndIncrement() { + final long last = value; + value++; + return last; + } + + // ----------------------------------------------------------------------- + /** + * Gets the value as a Long instance. + * + * @return the value as a Long, never null + */ + @Override + public Long getValue() { + return Long.valueOf(this.value); + } + + /** + * Returns a suitable hash code for this mutable. + * + * @return a suitable hash code + */ + @Override + public int hashCode() { + return (int) (value ^ (value >>> 32)); + } + + // ----------------------------------------------------------------------- + /** + * Increments the value. + * + * @since 2.2 + */ + public void increment() { + value++; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately after the increment operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is incremented + * @since 3.5 + */ + public long incrementAndGet() { + value++; + return value; + } + // ----------------------------------------------------------------------- // shortValue and byteValue rely on Number implementation /** @@ -309,25 +329,44 @@ public class MutableLong extends Number implements Comparable, Muta } /** - * Returns the value of this MutableLong as a float. + * Sets the value. * - * @return the numeric value represented by this object after conversion to type - * float. + * @param value the value to set */ - @Override - public float floatValue() { - return value; + public void setValue(final long value) { + this.value = value; } /** - * Returns the value of this MutableLong as a double. + * Sets the value from any Number instance. * - * @return the numeric value represented by this object after conversion to type - * double. + * @param value the value to set, not null + * @throws NullPointerException if the object is null */ @Override - public double doubleValue() { - return value; + public void setValue(final Number value) { + this.value = value.longValue(); + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @since 2.2 + */ + public void subtract(final long operand) { + this.value -= operand; + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @throws NullPointerException if the object is null + * @since 2.2 + */ + public void subtract(final Number operand) { + this.value -= operand.longValue(); } // ----------------------------------------------------------------------- @@ -340,45 +379,6 @@ public class MutableLong extends Number implements Comparable, Muta return Long.valueOf(longValue()); } - // ----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is {@code true} if - * and only if the argument is not {@code null} and is a {@code MutableLong} - * object that contains the same {@code long} value as this object. - * - * @param obj the object to compare with, null returns false - * @return {@code true} if the objects are the same; {@code false} otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof MutableLong) { - return value == ((MutableLong) obj).longValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return (int) (value ^ (value >>> 32)); - } - - // ----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - @Override - public int compareTo(final MutableLong other) { - return NumberUtils.compare(this.value, other.value); - } - // ----------------------------------------------------------------------- /** * Returns the String value of this mutable. diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableObject.java b/src/main/java/org/apache/commons/lang3/mutable/MutableObject.java index 08f8f42b..ebba17da 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableObject.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableObject.java @@ -52,27 +52,6 @@ public class MutableObject implements Mutable, Serializable { this.value = value; } - // ----------------------------------------------------------------------- - /** - * Gets the value. - * - * @return the value, may be null - */ - @Override - public T getValue() { - return this.value; - } - - /** - * Sets the value. - * - * @param value the value to set - */ - @Override - public void setValue(final T value) { - this.value = value; - } - // ----------------------------------------------------------------------- /** *

              @@ -101,6 +80,17 @@ public class MutableObject implements Mutable, Serializable { return false; } + // ----------------------------------------------------------------------- + /** + * Gets the value. + * + * @return the value, may be null + */ + @Override + public T getValue() { + return this.value; + } + /** * Returns the value's hash code or {@code 0} if the value is {@code null}. * @@ -111,6 +101,16 @@ public class MutableObject implements Mutable, Serializable { return value == null ? 0 : value.hashCode(); } + /** + * Sets the value. + * + * @param value the value to set + */ + @Override + public void setValue(final T value) { + this.value = value; + } + // ----------------------------------------------------------------------- /** * Returns the String value of this mutable. diff --git a/src/main/java/org/apache/commons/lang3/mutable/MutableShort.java b/src/main/java/org/apache/commons/lang3/mutable/MutableShort.java index 9ccf0b64..bdef87ef 100644 --- a/src/main/java/org/apache/commons/lang3/mutable/MutableShort.java +++ b/src/main/java/org/apache/commons/lang3/mutable/MutableShort.java @@ -45,15 +45,6 @@ public class MutableShort extends Number implements Comparable, Mu public MutableShort() { } - /** - * Constructs a new MutableShort with the specified value. - * - * @param value the initial value to store - */ - public MutableShort(final short value) { - this.value = value; - } - /** * Constructs a new MutableShort with the specified value. * @@ -64,6 +55,15 @@ public class MutableShort extends Number implements Comparable, Mu this.value = value.shortValue(); } + /** + * Constructs a new MutableShort with the specified value. + * + * @param value the initial value to store + */ + public MutableShort(final short value) { + this.value = value; + } + /** * Constructs a new MutableShort parsing the given string. * @@ -75,121 +75,6 @@ public class MutableShort extends Number implements Comparable, Mu this.value = Short.parseShort(value); } - // ----------------------------------------------------------------------- - /** - * Gets the value as a Short instance. - * - * @return the value as a Short, never null - */ - @Override - public Short getValue() { - return Short.valueOf(this.value); - } - - /** - * Sets the value. - * - * @param value the value to set - */ - public void setValue(final short value) { - this.value = value; - } - - /** - * Sets the value from any Number instance. - * - * @param value the value to set, not null - * @throws NullPointerException if the object is null - */ - @Override - public void setValue(final Number value) { - this.value = value.shortValue(); - } - - // ----------------------------------------------------------------------- - /** - * Increments the value. - * - * @since 2.2 - */ - public void increment() { - value++; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the increment operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was incremented - * @since 3.5 - */ - public short getAndIncrement() { - final short last = value; - value++; - return last; - } - - /** - * Increments this instance's value by 1; this method returns the value - * associated with the instance immediately after the increment operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is incremented - * @since 3.5 - */ - public short incrementAndGet() { - value++; - return value; - } - - /** - * Decrements the value. - * - * @since 2.2 - */ - public void decrement() { - value--; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately prior to the decrement operation. - * This method is not thread safe. - * - * @return the value associated with the instance before it was decremented - * @since 3.5 - */ - public short getAndDecrement() { - final short last = value; - value--; - return last; - } - - /** - * Decrements this instance's value by 1; this method returns the value - * associated with the instance immediately after the decrement operation. This - * method is not thread safe. - * - * @return the value associated with the instance after it is decremented - * @since 3.5 - */ - public short decrementAndGet() { - value--; - return value; - } - - // ----------------------------------------------------------------------- - /** - * Adds a value to the value of this instance. - * - * @param operand the value to add, not null - * @since 2.2 - */ - public void add(final short operand) { - this.value += operand; - } - /** * Adds a value to the value of this instance. * @@ -201,39 +86,15 @@ public class MutableShort extends Number implements Comparable, Mu this.value += operand.shortValue(); } + // ----------------------------------------------------------------------- /** - * Subtracts a value from the value of this instance. + * Adds a value to the value of this instance. * - * @param operand the value to subtract, not null + * @param operand the value to add, not null * @since 2.2 */ - public void subtract(final short operand) { - this.value -= operand; - } - - /** - * Subtracts a value from the value of this instance. - * - * @param operand the value to subtract, not null - * @throws NullPointerException if the object is null - * @since 2.2 - */ - public void subtract(final Number operand) { - this.value -= operand.shortValue(); - } - - /** - * Increments this instance's value by {@code operand}; this method returns the - * value associated with the instance immediately after the addition operation. - * This method is not thread safe. - * - * @param operand the quantity to add, not null - * @return the value associated with this instance after adding the operand - * @since 3.5 - */ - public short addAndGet(final short operand) { + public void add(final short operand) { this.value += operand; - return value; } /** @@ -253,18 +114,89 @@ public class MutableShort extends Number implements Comparable, Mu /** * Increments this instance's value by {@code operand}; this method returns the - * value associated with the instance immediately prior to the addition - * operation. This method is not thread safe. + * value associated with the instance immediately after the addition operation. + * This method is not thread safe. * * @param operand the quantity to add, not null - * @return the value associated with this instance immediately before the - * operand was added + * @return the value associated with this instance after adding the operand * @since 3.5 */ - public short getAndAdd(final short operand) { - final short last = value; + public short addAndGet(final short operand) { this.value += operand; - return last; + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this mutable to another in ascending order. + * + * @param other the other mutable to compare to, not null + * @return negative if this is less, zero if equal, positive if greater + */ + @Override + public int compareTo(final MutableShort other) { + return NumberUtils.compare(this.value, other.value); + } + + /** + * Decrements the value. + * + * @since 2.2 + */ + public void decrement() { + value--; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately after the decrement operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is decremented + * @since 3.5 + */ + public short decrementAndGet() { + value--; + return value; + } + + /** + * Returns the value of this MutableShort as a double. + * + * @return the numeric value represented by this object after conversion to type + * double. + */ + @Override + public double doubleValue() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Compares this object to the specified object. The result is {@code true} if + * and only if the argument is not {@code null} and is a {@code MutableShort} + * object that contains the same {@code short} value as this object. + * + * @param obj the object to compare with, null returns false + * @return {@code true} if the objects are the same; {@code false} otherwise. + */ + @Override + public boolean equals(final Object obj) { + if (obj instanceof MutableShort) { + return value == ((MutableShort) obj).shortValue(); + } + return false; + } + + /** + * Returns the value of this MutableShort as a float. + * + * @return the numeric value represented by this object after conversion to type + * float. + */ + @Override + public float floatValue() { + return value; } /** @@ -284,16 +216,91 @@ public class MutableShort extends Number implements Comparable, Mu return last; } - // ----------------------------------------------------------------------- - // byteValue relies on Number implementation /** - * Returns the value of this MutableShort as a short. + * Increments this instance's value by {@code operand}; this method returns the + * value associated with the instance immediately prior to the addition + * operation. This method is not thread safe. * - * @return the numeric value represented by this object after conversion to type - * short. + * @param operand the quantity to add, not null + * @return the value associated with this instance immediately before the + * operand was added + * @since 3.5 + */ + public short getAndAdd(final short operand) { + final short last = value; + this.value += operand; + return last; + } + + /** + * Decrements this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the decrement operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was decremented + * @since 3.5 + */ + public short getAndDecrement() { + final short last = value; + value--; + return last; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately prior to the increment operation. + * This method is not thread safe. + * + * @return the value associated with the instance before it was incremented + * @since 3.5 + */ + public short getAndIncrement() { + final short last = value; + value++; + return last; + } + + // ----------------------------------------------------------------------- + /** + * Gets the value as a Short instance. + * + * @return the value as a Short, never null */ @Override - public short shortValue() { + public Short getValue() { + return Short.valueOf(this.value); + } + + /** + * Returns a suitable hash code for this mutable. + * + * @return a suitable hash code + */ + @Override + public int hashCode() { + return value; + } + + // ----------------------------------------------------------------------- + /** + * Increments the value. + * + * @since 2.2 + */ + public void increment() { + value++; + } + + /** + * Increments this instance's value by 1; this method returns the value + * associated with the instance immediately after the increment operation. This + * method is not thread safe. + * + * @return the value associated with the instance after it is incremented + * @since 3.5 + */ + public short incrementAndGet() { + value++; return value; } @@ -320,25 +327,57 @@ public class MutableShort extends Number implements Comparable, Mu } /** - * Returns the value of this MutableShort as a float. + * Sets the value from any Number instance. * - * @return the numeric value represented by this object after conversion to type - * float. + * @param value the value to set, not null + * @throws NullPointerException if the object is null */ @Override - public float floatValue() { + public void setValue(final Number value) { + this.value = value.shortValue(); + } + + /** + * Sets the value. + * + * @param value the value to set + */ + public void setValue(final short value) { + this.value = value; + } + + // ----------------------------------------------------------------------- + // byteValue relies on Number implementation + /** + * Returns the value of this MutableShort as a short. + * + * @return the numeric value represented by this object after conversion to type + * short. + */ + @Override + public short shortValue() { return value; } /** - * Returns the value of this MutableShort as a double. + * Subtracts a value from the value of this instance. * - * @return the numeric value represented by this object after conversion to type - * double. + * @param operand the value to subtract, not null + * @throws NullPointerException if the object is null + * @since 2.2 */ - @Override - public double doubleValue() { - return value; + public void subtract(final Number operand) { + this.value -= operand.shortValue(); + } + + /** + * Subtracts a value from the value of this instance. + * + * @param operand the value to subtract, not null + * @since 2.2 + */ + public void subtract(final short operand) { + this.value -= operand; } // ----------------------------------------------------------------------- @@ -351,45 +390,6 @@ public class MutableShort extends Number implements Comparable, Mu return Short.valueOf(shortValue()); } - // ----------------------------------------------------------------------- - /** - * Compares this object to the specified object. The result is {@code true} if - * and only if the argument is not {@code null} and is a {@code MutableShort} - * object that contains the same {@code short} value as this object. - * - * @param obj the object to compare with, null returns false - * @return {@code true} if the objects are the same; {@code false} otherwise. - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof MutableShort) { - return value == ((MutableShort) obj).shortValue(); - } - return false; - } - - /** - * Returns a suitable hash code for this mutable. - * - * @return a suitable hash code - */ - @Override - public int hashCode() { - return value; - } - - // ----------------------------------------------------------------------- - /** - * Compares this mutable to another in ascending order. - * - * @param other the other mutable to compare to, not null - * @return negative if this is less, zero if equal, positive if greater - */ - @Override - public int compareTo(final MutableShort other) { - return NumberUtils.compare(this.value, other.value); - } - // ----------------------------------------------------------------------- /** * Returns the String value of this mutable. diff --git a/src/main/java/org/apache/commons/lang3/text/CompositeFormat.java b/src/main/java/org/apache/commons/lang3/text/CompositeFormat.java index 112967bb..f4eedea3 100644 --- a/src/main/java/org/apache/commons/lang3/text/CompositeFormat.java +++ b/src/main/java/org/apache/commons/lang3/text/CompositeFormat.java @@ -27,8 +27,8 @@ import java.text.ParsePosition; * stored in a database another way. * * @!deprecated as of 3.6, use commons-text - * CompositeFormat instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/CompositeFormat.html"> + * CompositeFormat instead */ //@Deprecated public class CompositeFormat extends Format { @@ -71,6 +71,24 @@ public class CompositeFormat extends Format { return formatter.format(obj, toAppendTo, pos); } + /** + * Provides access to the parser Format implementation. + * + * @return formatter Format implementation + */ + public Format getFormatter() { + return this.formatter; + } + + /** + * Provides access to the parser Format implementation. + * + * @return parser Format implementation + */ + public Format getParser() { + return this.parser; + } + /** * Uses the parser Format instance. * @@ -86,24 +104,6 @@ public class CompositeFormat extends Format { return parser.parseObject(source, pos); } - /** - * Provides access to the parser Format implementation. - * - * @return parser Format implementation - */ - public Format getParser() { - return this.parser; - } - - /** - * Provides access to the parser Format implementation. - * - * @return formatter Format implementation - */ - public Format getFormatter() { - return this.formatter; - } - /** * Utility method to parse and then reformat a String. * diff --git a/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java b/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java index ee90728d..8024a404 100644 --- a/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java +++ b/src/main/java/org/apache/commons/lang3/text/ExtendedMessageFormat.java @@ -72,8 +72,8 @@ import org.apache.commons.lang3.Validate; * * @since 2.4 * @!deprecated as of 3.6, use commons-text - * ExtendedMessageFormat instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/ExtendedMessageFormat.html"> + * ExtendedMessageFormat instead */ //@Deprecated public class ExtendedMessageFormat extends MessageFormat { @@ -110,17 +110,6 @@ public class ExtendedMessageFormat extends MessageFormat { this(pattern, locale, null); } - /** - * Create a new ExtendedMessageFormat for the default locale. - * - * @param pattern the pattern to use, not null - * @param registry the registry of format factories, may be null - * @throws IllegalArgumentException in case of a bad pattern. - */ - public ExtendedMessageFormat(final String pattern, final Map registry) { - this(pattern, Locale.getDefault(), registry); - } - /** * Create a new ExtendedMessageFormat. * @@ -138,11 +127,45 @@ public class ExtendedMessageFormat extends MessageFormat { } /** - * {@inheritDoc} + * Create a new ExtendedMessageFormat for the default locale. + * + * @param pattern the pattern to use, not null + * @param registry the registry of format factories, may be null + * @throws IllegalArgumentException in case of a bad pattern. */ - @Override - public String toPattern() { - return toPattern; + public ExtendedMessageFormat(final String pattern, final Map registry) { + this(pattern, Locale.getDefault(), registry); + } + + /** + * Consume a quoted string, adding it to {@code appendTo} if specified. + * + * @param pattern pattern to parse + * @param pos current parse position + * @param appendTo optional StringBuilder to append + * @return {@code appendTo} + */ + private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, + final StringBuilder appendTo) { + assert pattern.toCharArray()[pos.getIndex()] == QUOTE : "Quoted string must start with quote character"; + + // handle quote character at the beginning of the string + if (appendTo != null) { + appendTo.append(QUOTE); + } + next(pos); + + final int start = pos.getIndex(); + final char[] c = pattern.toCharArray(); + final int lastHold = start; + for (int i = pos.getIndex(); i < pattern.length(); i++) { + if (c[pos.getIndex()] == QUOTE) { + next(pos); + return appendTo == null ? null : appendTo.append(c, lastHold, pos.getIndex() - lastHold); + } + next(pos); + } + throw new IllegalArgumentException("Unterminated quoted string at position " + start); } /** @@ -215,6 +238,238 @@ public class ExtendedMessageFormat extends MessageFormat { } } + /** + * Learn whether the specified Collection contains non-null elements. + * + * @param coll to check + * @return {@code true} if some Object was found, {@code false} otherwise. + */ + private boolean containsElements(final Collection coll) { + if (coll == null || coll.isEmpty()) { + return false; + } + for (final Object name : coll) { + if (name != null) { + return true; + } + } + return false; + } + + /** + * Check if this extended message format is equal to another object. + * + * @param obj the object to compare to + * @return true if this object equals the other, otherwise false + */ + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (obj == null) { + return false; + } + if (!super.equals(obj)) { + return false; + } + if (ObjectUtils.notEqual(getClass(), obj.getClass())) { + return false; + } + final ExtendedMessageFormat rhs = (ExtendedMessageFormat) obj; + if (ObjectUtils.notEqual(toPattern, rhs.toPattern)) { + return false; + } + return !ObjectUtils.notEqual(registry, rhs.registry); + } + + /** + * Gets a custom format from a format description. + * + * @param desc String + * @return Format + */ + private Format getFormat(final String desc) { + if (registry != null) { + String name = desc; + String args = null; + final int i = desc.indexOf(START_FMT); + if (i > 0) { + name = desc.substring(0, i).trim(); + args = desc.substring(i + 1).trim(); + } + final FormatFactory factory = registry.get(name); + if (factory != null) { + return factory.getFormat(name, args, getLocale()); + } + } + return null; + } + + /** + * Consume quoted string only + * + * @param pattern pattern to parse + * @param pos current parse position + */ + private void getQuotedString(final String pattern, final ParsePosition pos) { + appendQuotedString(pattern, pos, null); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + int result = super.hashCode(); + result = HASH_SEED * result + Objects.hashCode(registry); + result = HASH_SEED * result + Objects.hashCode(toPattern); + return result; + } + + /** + * Insert formats back into the pattern for toPattern() support. + * + * @param pattern source + * @param customPatterns The custom patterns to re-insert, if any + * @return full pattern + */ + private String insertFormats(final String pattern, final ArrayList customPatterns) { + if (!containsElements(customPatterns)) { + return pattern; + } + final StringBuilder sb = new StringBuilder(pattern.length() * 2); + final ParsePosition pos = new ParsePosition(0); + int fe = -1; + int depth = 0; + while (pos.getIndex() < pattern.length()) { + final char c = pattern.charAt(pos.getIndex()); + switch (c) { + case QUOTE: + appendQuotedString(pattern, pos, sb); + break; + case START_FE: + depth++; + sb.append(START_FE).append(readArgumentIndex(pattern, next(pos))); + // do not look for custom patterns when they are embedded, e.g. in a choice + if (depth == 1) { + fe++; + final String customPattern = customPatterns.get(fe); + if (customPattern != null) { + sb.append(START_FMT).append(customPattern); + } + } + break; + case END_FE: + depth--; + //$FALL-THROUGH$ + default: + sb.append(c); + next(pos); + } + } + return sb.toString(); + } + + /** + * Convenience method to advance parse position by 1 + * + * @param pos ParsePosition + * @return {@code pos} + */ + private ParsePosition next(final ParsePosition pos) { + pos.setIndex(pos.getIndex() + 1); + return pos; + } + + /** + * Parse the format component of a format element. + * + * @param pattern string to parse + * @param pos current parse position + * @return Format description String + */ + private String parseFormatDescription(final String pattern, final ParsePosition pos) { + final int start = pos.getIndex(); + seekNonWs(pattern, pos); + final int text = pos.getIndex(); + int depth = 1; + for (; pos.getIndex() < pattern.length(); next(pos)) { + switch (pattern.charAt(pos.getIndex())) { + case START_FE: + depth++; + break; + case END_FE: + depth--; + if (depth == 0) { + return pattern.substring(text, pos.getIndex()); + } + break; + case QUOTE: + getQuotedString(pattern, pos); + break; + default: + break; + } + } + throw new IllegalArgumentException("Unterminated format element at position " + start); + } + + /** + * Read the argument index from the current format element + * + * @param pattern pattern to parse + * @param pos current parse position + * @return argument index + */ + private int readArgumentIndex(final String pattern, final ParsePosition pos) { + final int start = pos.getIndex(); + seekNonWs(pattern, pos); + final StringBuilder result = new StringBuilder(); + boolean error = false; + for (; !error && pos.getIndex() < pattern.length(); next(pos)) { + char c = pattern.charAt(pos.getIndex()); + if (Character.isWhitespace(c)) { + seekNonWs(pattern, pos); + c = pattern.charAt(pos.getIndex()); + if (c != START_FMT && c != END_FE) { + error = true; + continue; + } + } + if ((c == START_FMT || c == END_FE) && result.length() > 0) { + try { + return Integer.parseInt(result.toString()); + } catch (final NumberFormatException e) { // NOPMD + // we've already ensured only digits, so unless something + // outlandishly large was specified we should be okay. + } + } + error = !Character.isDigit(c); + result.append(c); + } + if (error) { + throw new IllegalArgumentException("Invalid format argument index at position " + start + ": " + + pattern.substring(start, pos.getIndex())); + } + throw new IllegalArgumentException("Unterminated format element at position " + start); + } + + /** + * Consume whitespace from the current parse position. + * + * @param pattern String to read + * @param pos current position + */ + private void seekNonWs(final String pattern, final ParsePosition pos) { + int len = 0; + final char[] buffer = pattern.toCharArray(); + do { + len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex()); + pos.setIndex(pos.getIndex() + len); + } while (len > 0 && pos.getIndex() < pattern.length()); + } + /** * Throws UnsupportedOperationException - see class Javadoc for details. * @@ -265,266 +520,11 @@ public class ExtendedMessageFormat extends MessageFormat { throw new UnsupportedOperationException(); } - /** - * Check if this extended message format is equal to another object. - * - * @param obj the object to compare to - * @return true if this object equals the other, otherwise false - */ - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (obj == null) { - return false; - } - if (!super.equals(obj)) { - return false; - } - if (ObjectUtils.notEqual(getClass(), obj.getClass())) { - return false; - } - final ExtendedMessageFormat rhs = (ExtendedMessageFormat) obj; - if (ObjectUtils.notEqual(toPattern, rhs.toPattern)) { - return false; - } - return !ObjectUtils.notEqual(registry, rhs.registry); - } - /** * {@inheritDoc} */ @Override - public int hashCode() { - int result = super.hashCode(); - result = HASH_SEED * result + Objects.hashCode(registry); - result = HASH_SEED * result + Objects.hashCode(toPattern); - return result; - } - - /** - * Gets a custom format from a format description. - * - * @param desc String - * @return Format - */ - private Format getFormat(final String desc) { - if (registry != null) { - String name = desc; - String args = null; - final int i = desc.indexOf(START_FMT); - if (i > 0) { - name = desc.substring(0, i).trim(); - args = desc.substring(i + 1).trim(); - } - final FormatFactory factory = registry.get(name); - if (factory != null) { - return factory.getFormat(name, args, getLocale()); - } - } - return null; - } - - /** - * Read the argument index from the current format element - * - * @param pattern pattern to parse - * @param pos current parse position - * @return argument index - */ - private int readArgumentIndex(final String pattern, final ParsePosition pos) { - final int start = pos.getIndex(); - seekNonWs(pattern, pos); - final StringBuilder result = new StringBuilder(); - boolean error = false; - for (; !error && pos.getIndex() < pattern.length(); next(pos)) { - char c = pattern.charAt(pos.getIndex()); - if (Character.isWhitespace(c)) { - seekNonWs(pattern, pos); - c = pattern.charAt(pos.getIndex()); - if (c != START_FMT && c != END_FE) { - error = true; - continue; - } - } - if ((c == START_FMT || c == END_FE) && result.length() > 0) { - try { - return Integer.parseInt(result.toString()); - } catch (final NumberFormatException e) { // NOPMD - // we've already ensured only digits, so unless something - // outlandishly large was specified we should be okay. - } - } - error = !Character.isDigit(c); - result.append(c); - } - if (error) { - throw new IllegalArgumentException("Invalid format argument index at position " + start + ": " - + pattern.substring(start, pos.getIndex())); - } - throw new IllegalArgumentException("Unterminated format element at position " + start); - } - - /** - * Parse the format component of a format element. - * - * @param pattern string to parse - * @param pos current parse position - * @return Format description String - */ - private String parseFormatDescription(final String pattern, final ParsePosition pos) { - final int start = pos.getIndex(); - seekNonWs(pattern, pos); - final int text = pos.getIndex(); - int depth = 1; - for (; pos.getIndex() < pattern.length(); next(pos)) { - switch (pattern.charAt(pos.getIndex())) { - case START_FE: - depth++; - break; - case END_FE: - depth--; - if (depth == 0) { - return pattern.substring(text, pos.getIndex()); - } - break; - case QUOTE: - getQuotedString(pattern, pos); - break; - default: - break; - } - } - throw new IllegalArgumentException("Unterminated format element at position " + start); - } - - /** - * Insert formats back into the pattern for toPattern() support. - * - * @param pattern source - * @param customPatterns The custom patterns to re-insert, if any - * @return full pattern - */ - private String insertFormats(final String pattern, final ArrayList customPatterns) { - if (!containsElements(customPatterns)) { - return pattern; - } - final StringBuilder sb = new StringBuilder(pattern.length() * 2); - final ParsePosition pos = new ParsePosition(0); - int fe = -1; - int depth = 0; - while (pos.getIndex() < pattern.length()) { - final char c = pattern.charAt(pos.getIndex()); - switch (c) { - case QUOTE: - appendQuotedString(pattern, pos, sb); - break; - case START_FE: - depth++; - sb.append(START_FE).append(readArgumentIndex(pattern, next(pos))); - // do not look for custom patterns when they are embedded, e.g. in a choice - if (depth == 1) { - fe++; - final String customPattern = customPatterns.get(fe); - if (customPattern != null) { - sb.append(START_FMT).append(customPattern); - } - } - break; - case END_FE: - depth--; - //$FALL-THROUGH$ - default: - sb.append(c); - next(pos); - } - } - return sb.toString(); - } - - /** - * Consume whitespace from the current parse position. - * - * @param pattern String to read - * @param pos current position - */ - private void seekNonWs(final String pattern, final ParsePosition pos) { - int len = 0; - final char[] buffer = pattern.toCharArray(); - do { - len = StrMatcher.splitMatcher().isMatch(buffer, pos.getIndex()); - pos.setIndex(pos.getIndex() + len); - } while (len > 0 && pos.getIndex() < pattern.length()); - } - - /** - * Convenience method to advance parse position by 1 - * - * @param pos ParsePosition - * @return {@code pos} - */ - private ParsePosition next(final ParsePosition pos) { - pos.setIndex(pos.getIndex() + 1); - return pos; - } - - /** - * Consume a quoted string, adding it to {@code appendTo} if specified. - * - * @param pattern pattern to parse - * @param pos current parse position - * @param appendTo optional StringBuilder to append - * @return {@code appendTo} - */ - private StringBuilder appendQuotedString(final String pattern, final ParsePosition pos, - final StringBuilder appendTo) { - assert pattern.toCharArray()[pos.getIndex()] == QUOTE : "Quoted string must start with quote character"; - - // handle quote character at the beginning of the string - if (appendTo != null) { - appendTo.append(QUOTE); - } - next(pos); - - final int start = pos.getIndex(); - final char[] c = pattern.toCharArray(); - final int lastHold = start; - for (int i = pos.getIndex(); i < pattern.length(); i++) { - if (c[pos.getIndex()] == QUOTE) { - next(pos); - return appendTo == null ? null : appendTo.append(c, lastHold, pos.getIndex() - lastHold); - } - next(pos); - } - throw new IllegalArgumentException("Unterminated quoted string at position " + start); - } - - /** - * Consume quoted string only - * - * @param pattern pattern to parse - * @param pos current parse position - */ - private void getQuotedString(final String pattern, final ParsePosition pos) { - appendQuotedString(pattern, pos, null); - } - - /** - * Learn whether the specified Collection contains non-null elements. - * - * @param coll to check - * @return {@code true} if some Object was found, {@code false} otherwise. - */ - private boolean containsElements(final Collection coll) { - if (coll == null || coll.isEmpty()) { - return false; - } - for (final Object name : coll) { - if (name != null) { - return true; - } - } - return false; + public String toPattern() { + return toPattern; } } diff --git a/src/main/java/org/apache/commons/lang3/text/FormatFactory.java b/src/main/java/org/apache/commons/lang3/text/FormatFactory.java index 86e7933f..c9e52ed0 100644 --- a/src/main/java/org/apache/commons/lang3/text/FormatFactory.java +++ b/src/main/java/org/apache/commons/lang3/text/FormatFactory.java @@ -24,8 +24,8 @@ import java.util.Locale; * * @since 2.4 * @!deprecated as of 3.6, use commons-text - * FormatFactory instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/FormatFactory.html"> + * FormatFactory instead */ //@Deprecated public interface FormatFactory { diff --git a/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java b/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java index fd8fe4d7..738b22b0 100644 --- a/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java +++ b/src/main/java/org/apache/commons/lang3/text/FormattableUtils.java @@ -40,8 +40,8 @@ import net.lax1dude.eaglercraft.v1_8.HString; * * @since 3.0 * @!deprecated as of 3.6, use commons-text - * FormattableUtils instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/FormattableUtils.html"> + * FormattableUtils instead */ //@Deprecated public class FormattableUtils { @@ -51,32 +51,6 @@ public class FormattableUtils { */ private static final String SIMPLEST_FORMAT = "%s"; - /** - *

              - * {@code FormattableUtils} instances should NOT be constructed in standard - * programming. Instead, the methods of the class should be invoked statically. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public FormattableUtils() { - } - - // ----------------------------------------------------------------------- - /** - * Gets the default formatted representation of the specified - * {@code Formattable}. - * - * @param formattable the instance to convert to a string, not null - * @return the resulting string, not null - */ - public static String toString(final Formattable formattable) { - return HString.format(SIMPLEST_FORMAT, formattable); - } - /** * Handles the common {@code Formattable} operations of truncate-pad-append, * with no ellipsis on precision overflow, and padding width underflow with @@ -111,24 +85,6 @@ public class FormattableUtils { return append(seq, formatter, flags, width, precision, padChar, null); } - /** - * Handles the common {@link Formattable} operations of truncate-pad-append, - * padding width underflow with spaces. - * - * @param seq the string to handle, not null - * @param formatter the destination formatter, not null - * @param flags the flags for formatting, see {@code Formattable} - * @param width the width of the output, see {@code Formattable} - * @param precision the precision of the output, see {@code Formattable} - * @param ellipsis the ellipsis to use when precision dictates truncation, null - * or empty causes a hard truncation - * @return the {@code formatter} instance, not null - */ - public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width, - final int precision, final CharSequence ellipsis) { - return append(seq, formatter, flags, width, precision, ' ', ellipsis); - } - /** * Handles the common {@link Formattable} operations of truncate-pad-append. * @@ -159,4 +115,48 @@ public class FormattableUtils { return formatter; } + /** + * Handles the common {@link Formattable} operations of truncate-pad-append, + * padding width underflow with spaces. + * + * @param seq the string to handle, not null + * @param formatter the destination formatter, not null + * @param flags the flags for formatting, see {@code Formattable} + * @param width the width of the output, see {@code Formattable} + * @param precision the precision of the output, see {@code Formattable} + * @param ellipsis the ellipsis to use when precision dictates truncation, null + * or empty causes a hard truncation + * @return the {@code formatter} instance, not null + */ + public static Formatter append(final CharSequence seq, final Formatter formatter, final int flags, final int width, + final int precision, final CharSequence ellipsis) { + return append(seq, formatter, flags, width, precision, ' ', ellipsis); + } + + // ----------------------------------------------------------------------- + /** + * Gets the default formatted representation of the specified + * {@code Formattable}. + * + * @param formattable the instance to convert to a string, not null + * @return the resulting string, not null + */ + public static String toString(final Formattable formattable) { + return HString.format(SIMPLEST_FORMAT, formattable); + } + + /** + *

              + * {@code FormattableUtils} instances should NOT be constructed in standard + * programming. Instead, the methods of the class should be invoked statically. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              + */ + public FormattableUtils() { + } + } diff --git a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java index 6fd0a5bb..8e7fdc7f 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrBuilder.java +++ b/src/main/java/org/apache/commons/lang3/text/StrBuilder.java @@ -25,12 +25,12 @@ import java.util.Iterator; import java.util.List; import java.util.Objects; -import net.lax1dude.eaglercraft.v1_8.HString; - import org.apache.commons.lang3.CharUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.Builder; +import net.lax1dude.eaglercraft.v1_8.HString; + /** * Builds a string from constituent parts providing a more flexible and powerful * API than StringBuffer. @@ -78,30 +78,207 @@ import org.apache.commons.lang3.builder.Builder; * * @since 2.2 * @!deprecated as of 3.6, use commons-text - * TextStringBuilder instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/TextStringBuilder.html"> + * TextStringBuilder instead */ //@Deprecated public class StrBuilder implements CharSequence, Appendable, Serializable, Builder { + // ----------------------------------------------------------------------- + /** + * Inner class to allow StrBuilder to operate as a reader. + */ + class StrBuilderReader extends Reader { + /** The current stream position. */ + private int pos; + /** The last mark position. */ + private int mark; + + /** + * Default constructor. + */ + StrBuilderReader() { + } + + /** {@inheritDoc} */ + @Override + public void close() { + // do nothing + } + + /** {@inheritDoc} */ + @Override + public void mark(final int readAheadLimit) { + mark = pos; + } + + /** {@inheritDoc} */ + @Override + public boolean markSupported() { + return true; + } + + /** {@inheritDoc} */ + @Override + public int read() { + if (ready() == false) { + return -1; + } + return StrBuilder.this.charAt(pos++); + } + + /** {@inheritDoc} */ + @Override + public int read(final char[] b, final int off, int len) { + if (off < 0 || len < 0 || off > b.length || (off + len) > b.length || (off + len) < 0) { + throw new IndexOutOfBoundsException(); + } + if (len == 0) { + return 0; + } + if (pos >= StrBuilder.this.size()) { + return -1; + } + if (pos + len > size()) { + len = StrBuilder.this.size() - pos; + } + StrBuilder.this.getChars(pos, pos + len, b, off); + pos += len; + return len; + } + + /** {@inheritDoc} */ + @Override + public boolean ready() { + return pos < StrBuilder.this.size(); + } + + /** {@inheritDoc} */ + @Override + public void reset() { + pos = mark; + } + + /** {@inheritDoc} */ + @Override + public long skip(long n) { + if (pos + n > StrBuilder.this.size()) { + n = StrBuilder.this.size() - pos; + } + if (n < 0) { + return 0; + } + pos += n; + return n; + } + } + + // ----------------------------------------------------------------------- + /** + * Inner class to allow StrBuilder to operate as a tokenizer. + */ + class StrBuilderTokenizer extends StrTokenizer { + + /** + * Default constructor. + */ + StrBuilderTokenizer() { + } + + /** {@inheritDoc} */ + @Override + public String getContent() { + final String str = super.getContent(); + if (str == null) { + return StrBuilder.this.toString(); + } + return str; + } + + /** {@inheritDoc} */ + @Override + protected List tokenize(final char[] chars, final int offset, final int count) { + if (chars == null) { + return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size()); + } + return super.tokenize(chars, offset, count); + } + } + + // ----------------------------------------------------------------------- + /** + * Inner class to allow StrBuilder to operate as a writer. + */ + class StrBuilderWriter extends Writer { + + /** + * Default constructor. + */ + StrBuilderWriter() { + } + + /** {@inheritDoc} */ + @Override + public void close() { + // do nothing + } + + /** {@inheritDoc} */ + @Override + public void flush() { + // do nothing + } + + /** {@inheritDoc} */ + @Override + public void write(final char[] cbuf) { + StrBuilder.this.append(cbuf); + } + + /** {@inheritDoc} */ + @Override + public void write(final char[] cbuf, final int off, final int len) { + StrBuilder.this.append(cbuf, off, len); + } + + /** {@inheritDoc} */ + @Override + public void write(final int c) { + StrBuilder.this.append((char) c); + } + + /** {@inheritDoc} */ + @Override + public void write(final String str) { + StrBuilder.this.append(str); + } + + /** {@inheritDoc} */ + @Override + public void write(final String str, final int off, final int len) { + StrBuilder.this.append(str, off, len); + } + } + /** * The extra capacity for new builders. */ static final int CAPACITY = 32; - /** * Required for serialization support. * * @see java.io.Serializable */ private static final long serialVersionUID = 7628716375283629643L; - /** Internal data storage. */ protected char[] buffer; // TODO make private? + /** Current size of the buffer. */ protected int size; // TODO make private? + /** The new line. */ private String newLine; + /** The null text. */ private String nullText; @@ -141,400 +318,148 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build } } - // ----------------------------------------------------------------------- /** - * Gets the text to be appended when a new line is added. + * Appends a boolean value to the string builder. * - * @return the new line text, null means use system default - */ - public String getNewLineText() { - return newLine; - } - - /** - * Sets the text to be appended when a new line is added. - * - * @param newLine the new line text, null means use system default + * @param value the value to append * @return this, to enable chaining */ - public StrBuilder setNewLineText(final String newLine) { - this.newLine = newLine; - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets the text to be appended when null is added. - * - * @return the null text, null means no append - */ - public String getNullText() { - return nullText; - } - - /** - * Sets the text to be appended when null is added. - * - * @param nullText the null text, null means no append - * @return this, to enable chaining - */ - public StrBuilder setNullText(String nullText) { - if (nullText != null && nullText.isEmpty()) { - nullText = null; - } - this.nullText = nullText; - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets the length of the string builder. - * - * @return the length - */ - @Override - public int length() { - return size; - } - - /** - * Updates the length of the builder by either dropping the last characters or - * adding filler of Unicode zero. - * - * @param length the length to set to, must be zero or positive - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the length is negative - */ - public StrBuilder setLength(final int length) { - if (length < 0) { - throw new StringIndexOutOfBoundsException(length); - } - if (length < size) { - size = length; - } else if (length > size) { - ensureCapacity(length); - final int oldEnd = size; - final int newEnd = length; - size = length; - for (int i = oldEnd; i < newEnd; i++) { - buffer[i] = CharUtils.NUL; - } - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets the current size of the internal character array buffer. - * - * @return the capacity - */ - public int capacity() { - return buffer.length; - } - - /** - * Checks the capacity and ensures that it is at least the size specified. - * - * @param capacity the capacity to ensure - * @return this, to enable chaining - */ - public StrBuilder ensureCapacity(final int capacity) { - if (capacity > buffer.length) { - final char[] old = buffer; - buffer = new char[capacity * 2]; - System.arraycopy(old, 0, buffer, 0, size); - } - return this; - } - - /** - * Minimizes the capacity to the actual length of the string. - * - * @return this, to enable chaining - */ - public StrBuilder minimizeCapacity() { - if (buffer.length > length()) { - final char[] old = buffer; - buffer = new char[length()]; - System.arraycopy(old, 0, buffer, 0, size); - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets the length of the string builder. - *

              - * This method is the same as {@link #length()} and is provided to match the API - * of Collections. - * - * @return the length - */ - public int size() { - return size; - } - - /** - * Checks is the string builder is empty (convenience Collections API style - * method). - *

              - * This method is the same as checking {@link #length()} and is provided to - * match the API of Collections. - * - * @return {@code true} if the size is {@code 0}. - */ - public boolean isEmpty() { - return size == 0; - } - - /** - * Checks is the string builder is not empty (convenience Collections API style - * method). - *

              - * This method is the same as checking {@link #length()} and is provided to - * match the API of Collections. - * - * @return {@code true} if the size is greater than {@code 0}. - * @since 3.12.0 - */ - public boolean isNotEmpty() { - return size > 0; - } - - /** - * Clears the string builder (convenience Collections API style method). - *

              - * This method does not reduce the size of the internal character buffer. To do - * that, call {@code clear()} followed by {@link #minimizeCapacity()}. - *

              - * This method is the same as {@link #setLength(int)} called with zero and is - * provided to match the API of Collections. - * - * @return this, to enable chaining - */ - public StrBuilder clear() { - size = 0; - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets the character at the specified index. - * - * @see #setCharAt(int, char) - * @see #deleteCharAt(int) - * @param index the index to retrieve, must be valid - * @return the character at the index - * @throws IndexOutOfBoundsException if the index is invalid - */ - @Override - public char charAt(final int index) { - if (index < 0 || index >= length()) { - throw new StringIndexOutOfBoundsException(index); - } - return buffer[index]; - } - - /** - * Sets the character at the specified index. - * - * @see #charAt(int) - * @see #deleteCharAt(int) - * @param index the index to set - * @param ch the new character - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder setCharAt(final int index, final char ch) { - if (index < 0 || index >= length()) { - throw new StringIndexOutOfBoundsException(index); - } - buffer[index] = ch; - return this; - } - - /** - * Deletes the character at the specified index. - * - * @see #charAt(int) - * @see #setCharAt(int, char) - * @param index the index to delete - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder deleteCharAt(final int index) { - if (index < 0 || index >= size) { - throw new StringIndexOutOfBoundsException(index); - } - deleteImpl(index, index + 1, 1); - return this; - } - - // ----------------------------------------------------------------------- - /** - * Copies the builder's character array into a new character array. - * - * @return a new array that represents the contents of the builder - */ - public char[] toCharArray() { - if (size == 0) { - return new char[0]; - } - final char[] chars = new char[size]; - System.arraycopy(buffer, 0, chars, 0, size); - return chars; - } - - /** - * Copies part of the builder's character array into a new character array. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except that if too - * large it is treated as end of string - * @return a new array that holds part of the contents of the builder - * @throws IndexOutOfBoundsException if startIndex is invalid, or if endIndex is - * invalid (but endIndex greater than size is - * valid) - */ - public char[] toCharArray(final int startIndex, int endIndex) { - endIndex = validateRange(startIndex, endIndex); - final int len = endIndex - startIndex; - if (len == 0) { - return new char[0]; - } - final char[] chars = new char[len]; - System.arraycopy(buffer, startIndex, chars, 0, len); - return chars; - } - - /** - * Copies the character array into the specified array. - * - * @param destination the destination array, null will cause an array to be - * created - * @return the input array, unless that was null or too small - */ - public char[] getChars(char[] destination) { - final int len = length(); - if (destination == null || destination.length < len) { - destination = new char[len]; - } - System.arraycopy(buffer, 0, destination, 0, len); - return destination; - } - - /** - * Copies the character array into the specified array. - * - * @param startIndex first index to copy, inclusive, must be valid - * @param endIndex last index, exclusive, must be valid - * @param destination the destination array, must not be null or too small - * @param destinationIndex the index to start copying in destination - * @throws NullPointerException if the array is null - * @throws IndexOutOfBoundsException if any index is invalid - */ - public void getChars(final int startIndex, final int endIndex, final char[] destination, - final int destinationIndex) { - if (startIndex < 0) { - throw new StringIndexOutOfBoundsException(startIndex); - } - if (endIndex < 0 || endIndex > length()) { - throw new StringIndexOutOfBoundsException(endIndex); - } - if (startIndex > endIndex) { - throw new StringIndexOutOfBoundsException("end < start"); - } - System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex); - } - - // ----------------------------------------------------------------------- - /** - * If possible, reads chars from the provided {@link Readable} directly into - * underlying character buffer without making extra copies. - * - * @param readable object to read from - * @return the number of characters read - * @throws IOException if an I/O error occurs. - * - * @since 3.4 - * @see #appendTo(Appendable) - */ - public int readFrom(final Readable readable) throws IOException { - final int oldSize = size; - if (readable instanceof Reader) { - final Reader r = (Reader) readable; - ensureCapacity(size + 1); - int read; - while ((read = r.read(buffer, size, buffer.length - size)) != -1) { - size += read; - ensureCapacity(size + 1); - } - } else if (readable instanceof CharBuffer) { - final CharBuffer cb = (CharBuffer) readable; - final int remaining = cb.remaining(); - ensureCapacity(size + remaining); - cb.get(buffer, size, remaining); - size += remaining; + public StrBuilder append(final boolean value) { + if (value) { + ensureCapacity(size + 4); + buffer[size++] = 't'; + buffer[size++] = 'r'; + buffer[size++] = 'u'; + buffer[size++] = 'e'; } else { - while (true) { - ensureCapacity(size + 1); - final CharBuffer buf = CharBuffer.wrap(buffer, size, buffer.length - size); - final int read = readable.read(buf); - if (read == -1) { - break; - } - size += read; - } + ensureCapacity(size + 5); + buffer[size++] = 'f'; + buffer[size++] = 'a'; + buffer[size++] = 'l'; + buffer[size++] = 's'; + buffer[size++] = 'e'; } - return size - oldSize; + return this; } - // ----------------------------------------------------------------------- /** - * Appends the new line string to this string builder. - *

              - * The new line string can be altered using {@link #setNewLineText(String)}. - * This might be used to force the output to always use Unix line endings even - * when on Windows. + * Appends a char value to the string builder. * + * @param ch the value to append * @return this, to enable chaining + * @since 3.0 */ - public StrBuilder appendNewLine() { - if (newLine == null) { - append(System.lineSeparator()); - return this; - } - return append(newLine); + @Override + public StrBuilder append(final char ch) { + final int len = length(); + ensureCapacity(len + 1); + buffer[size++] = ch; + return this; } /** - * Appends the text representing {@code null} to this string builder. - * - * @return this, to enable chaining - */ - public StrBuilder appendNull() { - if (nullText == null) { - return this; - } - return append(nullText); - } - - /** - * Appends an object to this string builder. Appending null will call + * Appends a char array to the string builder. Appending null will call * {@link #appendNull()}. * - * @param obj the object to append + * @param chars the char array to append * @return this, to enable chaining */ - public StrBuilder append(final Object obj) { - if (obj == null) { + public StrBuilder append(final char[] chars) { + if (chars == null) { return appendNull(); } - if (obj instanceof CharSequence) { - return append((CharSequence) obj); + final int strLen = chars.length; + if (strLen > 0) { + final int len = length(); + ensureCapacity(len + strLen); + System.arraycopy(chars, 0, buffer, len, strLen); + size += strLen; } - return append(obj.toString()); + return this; + } + + /** + * Appends a char array to the string builder. Appending null will call + * {@link #appendNull()}. + * + * @param chars the char array to append + * @param startIndex the start index, inclusive, must be valid + * @param length the length to append, must be valid + * @return this, to enable chaining + */ + public StrBuilder append(final char[] chars, final int startIndex, final int length) { + if (chars == null) { + return appendNull(); + } + if (startIndex < 0 || startIndex > chars.length) { + throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length); + } + if (length < 0 || (startIndex + length) > chars.length) { + throw new StringIndexOutOfBoundsException("Invalid length: " + length); + } + if (length > 0) { + final int len = length(); + ensureCapacity(len + length); + System.arraycopy(chars, startIndex, buffer, len, length); + size += length; + } + return this; + } + + /** + * Appends the contents of a char buffer to this string builder. Appending null + * will call {@link #appendNull()}. + * + * @param buf the char buffer to append + * @return this, to enable chaining + * @since 3.4 + */ + public StrBuilder append(final CharBuffer buf) { + if (buf == null) { + return appendNull(); + } + if (buf.hasArray()) { + final int length = buf.remaining(); + final int len = length(); + ensureCapacity(len + length); + System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), buffer, len, length); + size += length; + } else { + append(buf.toString()); + } + return this; + } + + /** + * Appends the contents of a char buffer to this string builder. Appending null + * will call {@link #appendNull()}. + * + * @param buf the char buffer to append + * @param startIndex the start index, inclusive, must be valid + * @param length the length to append, must be valid + * @return this, to enable chaining + * @since 3.4 + */ + public StrBuilder append(final CharBuffer buf, final int startIndex, final int length) { + if (buf == null) { + return appendNull(); + } + if (buf.hasArray()) { + final int totalLength = buf.remaining(); + if (startIndex < 0 || startIndex > totalLength) { + throw new StringIndexOutOfBoundsException("startIndex must be valid"); + } + if (length < 0 || (startIndex + length) > totalLength) { + throw new StringIndexOutOfBoundsException("length must be valid"); + } + final int len = length(); + ensureCapacity(len + length); + System.arraycopy(buf.array(), buf.arrayOffset() + buf.position() + startIndex, buffer, len, length); + size += length; + } else { + append(buf.toString(), startIndex, length); + } + return this; } /** @@ -583,6 +508,112 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return append(seq.toString(), startIndex, length); } + /** + * Appends a double value to the string builder using {@code String.valueOf}. + * + * @param value the value to append + * @return this, to enable chaining + */ + public StrBuilder append(final double value) { + return append(String.valueOf(value)); + } + + /** + * Appends a float value to the string builder using {@code String.valueOf}. + * + * @param value the value to append + * @return this, to enable chaining + */ + public StrBuilder append(final float value) { + return append(String.valueOf(value)); + } + + /** + * Appends an int value to the string builder using {@code String.valueOf}. + * + * @param value the value to append + * @return this, to enable chaining + */ + public StrBuilder append(final int value) { + return append(String.valueOf(value)); + } + + /** + * Appends a long value to the string builder using {@code String.valueOf}. + * + * @param value the value to append + * @return this, to enable chaining + */ + public StrBuilder append(final long value) { + return append(String.valueOf(value)); + } + + /** + * Appends an object to this string builder. Appending null will call + * {@link #appendNull()}. + * + * @param obj the object to append + * @return this, to enable chaining + */ + public StrBuilder append(final Object obj) { + if (obj == null) { + return appendNull(); + } + if (obj instanceof CharSequence) { + return append((CharSequence) obj); + } + return append(obj.toString()); + } + + /** + * Appends another string builder to this string builder. Appending null will + * call {@link #appendNull()}. + * + * @param str the string builder to append + * @return this, to enable chaining + */ + public StrBuilder append(final StrBuilder str) { + if (str == null) { + return appendNull(); + } + final int strLen = str.length(); + if (strLen > 0) { + final int len = length(); + ensureCapacity(len + strLen); + System.arraycopy(str.buffer, 0, buffer, len, strLen); + size += strLen; + } + return this; + } + + /** + * Appends part of a string builder to this string builder. Appending null will + * call {@link #appendNull()}. + * + * @param str the string to append + * @param startIndex the start index, inclusive, must be valid + * @param length the length to append, must be valid + * @return this, to enable chaining + */ + public StrBuilder append(final StrBuilder str, final int startIndex, final int length) { + if (str == null) { + return appendNull(); + } + if (startIndex < 0 || startIndex > str.length()) { + throw new StringIndexOutOfBoundsException("startIndex must be valid"); + } + if (length < 0 || (startIndex + length) > str.length()) { + throw new StringIndexOutOfBoundsException("length must be valid"); + } + if (length > 0) { + final int len = length(); + ensureCapacity(len + length); + str.getChars(startIndex, startIndex + length, buffer, len); + size += length; + } + return this; + } + /** * Appends a string to this string builder. Appending null will call * {@link #appendNull()}. @@ -645,62 +676,6 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return append(HString.format(format, objs)); } - /** - * Appends the contents of a char buffer to this string builder. Appending null - * will call {@link #appendNull()}. - * - * @param buf the char buffer to append - * @return this, to enable chaining - * @since 3.4 - */ - public StrBuilder append(final CharBuffer buf) { - if (buf == null) { - return appendNull(); - } - if (buf.hasArray()) { - final int length = buf.remaining(); - final int len = length(); - ensureCapacity(len + length); - System.arraycopy(buf.array(), buf.arrayOffset() + buf.position(), buffer, len, length); - size += length; - } else { - append(buf.toString()); - } - return this; - } - - /** - * Appends the contents of a char buffer to this string builder. Appending null - * will call {@link #appendNull()}. - * - * @param buf the char buffer to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 3.4 - */ - public StrBuilder append(final CharBuffer buf, final int startIndex, final int length) { - if (buf == null) { - return appendNull(); - } - if (buf.hasArray()) { - final int totalLength = buf.remaining(); - if (startIndex < 0 || startIndex > totalLength) { - throw new StringIndexOutOfBoundsException("startIndex must be valid"); - } - if (length < 0 || (startIndex + length) > totalLength) { - throw new StringIndexOutOfBoundsException("length must be valid"); - } - final int len = length(); - ensureCapacity(len + length); - System.arraycopy(buf.array(), buf.arrayOffset() + buf.position() + startIndex, buffer, len, length); - size += length; - } else { - append(buf.toString(), startIndex, length); - } - return this; - } - /** * Appends a string buffer to this string builder. Appending null will call * {@link #appendNull()}. @@ -802,180 +777,256 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build } /** - * Appends another string builder to this string builder. Appending null will - * call {@link #appendNull()}. + * Appends each item in an iterable to the builder without any separators. + * Appending a null iterable will have no effect. Each object is appended using + * {@link #append(Object)}. * - * @param str the string builder to append + * @param iterable the iterable to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final StrBuilder str) { - if (str == null) { - return appendNull(); - } - final int strLen = str.length(); - if (strLen > 0) { - final int len = length(); - ensureCapacity(len + strLen); - System.arraycopy(str.buffer, 0, buffer, len, strLen); - size += strLen; + public StrBuilder appendAll(final Iterable iterable) { + if (iterable != null) { + for (final Object o : iterable) { + append(o); + } } return this; } /** - * Appends part of a string builder to this string builder. Appending null will - * call {@link #appendNull()}. + * Appends each item in an iterator to the builder without any separators. + * Appending a null iterator will have no effect. Each object is appended using + * {@link #append(Object)}. * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid + * @param it the iterator to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final StrBuilder str, final int startIndex, final int length) { - if (str == null) { - return appendNull(); + public StrBuilder appendAll(final Iterator it) { + if (it != null) { + while (it.hasNext()) { + append(it.next()); + } } - if (startIndex < 0 || startIndex > str.length()) { - throw new StringIndexOutOfBoundsException("startIndex must be valid"); - } - if (length < 0 || (startIndex + length) > str.length()) { - throw new StringIndexOutOfBoundsException("length must be valid"); - } - if (length > 0) { - final int len = length(); - ensureCapacity(len + length); - str.getChars(startIndex, startIndex + length, buffer, len); - size += length; + return this; + } + + // ----------------------------------------------------------------------- + /** + * Appends each item in an array to the builder without any separators. + * Appending a null array will have no effect. Each object is appended using + * {@link #append(Object)}. + * + * @param the element type + * @param array the array to append + * @return this, to enable chaining + * @since 2.3 + */ + public StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array) { + /* + * @SuppressWarnings used to hide warning about vararg usage. We cannot + * use @SafeVarargs, since this method is not final. Using @SuppressWarnings is + * fine, because it isn't inherited by subclasses, so each subclass must vouch + * for itself whether its use of 'array' is safe. + */ + if (array.length > 0) { + for (final Object element : array) { + append(element); + } } return this; } /** - * Appends a char array to the string builder. Appending null will call - * {@link #appendNull()}. + * Appends an object to the builder padding on the left to a fixed width. The + * {@code String.valueOf} of the {@code int} value is used. If the formatted + * value is larger than the length, the left hand side is lost. + * + * @param value the value to append + * @param width the fixed field width, zero or negative has no effect + * @param padChar the pad character to use + * @return this, to enable chaining + */ + public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) { + return appendFixedWidthPadLeft(String.valueOf(value), width, padChar); + } + + // ----------------------------------------------------------------------- + /** + * Appends an object to the builder padding on the left to a fixed width. The + * {@code toString} of the object is used. If the object is larger than the + * length, the left hand side is lost. If the object is null, the null text + * value is used. + * + * @param obj the object to append, null uses null text + * @param width the fixed field width, zero or negative has no effect + * @param padChar the pad character to use + * @return this, to enable chaining + */ + public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) { + if (width > 0) { + ensureCapacity(size + width); + String str = (obj == null ? getNullText() : obj.toString()); + if (str == null) { + str = StringUtils.EMPTY; + } + final int strLen = str.length(); + if (strLen >= width) { + str.getChars(strLen - width, strLen, buffer, size); + } else { + final int padLen = width - strLen; + for (int i = 0; i < padLen; i++) { + buffer[size + i] = padChar; + } + str.getChars(0, strLen, buffer, size + padLen); + } + size += width; + } + return this; + } + + /** + * Appends an object to the builder padding on the right to a fixed length. The + * {@code String.valueOf} of the {@code int} value is used. If the object is + * larger than the length, the right hand side is lost. + * + * @param value the value to append + * @param width the fixed field width, zero or negative has no effect + * @param padChar the pad character to use + * @return this, to enable chaining + */ + public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) { + return appendFixedWidthPadRight(String.valueOf(value), width, padChar); + } + + /** + * Appends an object to the builder padding on the right to a fixed length. The + * {@code toString} of the object is used. If the object is larger than the + * length, the right hand side is lost. If the object is null, null text value + * is used. + * + * @param obj the object to append, null uses null text + * @param width the fixed field width, zero or negative has no effect + * @param padChar the pad character to use + * @return this, to enable chaining + */ + public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) { + if (width > 0) { + ensureCapacity(size + width); + String str = (obj == null ? getNullText() : obj.toString()); + if (str == null) { + str = StringUtils.EMPTY; + } + final int strLen = str.length(); + if (strLen >= width) { + str.getChars(0, width, buffer, size); + } else { + final int padLen = width - strLen; + str.getChars(0, strLen, buffer, size); + for (int i = 0; i < padLen; i++) { + buffer[size + strLen + i] = padChar; + } + } + size += width; + } + return this; + } + + /** + * Appends a boolean value followed by a new line to the string builder. + * + * @param value the value to append + * @return this, to enable chaining + * @since 2.3 + */ + public StrBuilder appendln(final boolean value) { + return append(value).appendNewLine(); + } + + /** + * Appends a char value followed by a new line to the string builder. + * + * @param ch the value to append + * @return this, to enable chaining + * @since 2.3 + */ + public StrBuilder appendln(final char ch) { + return append(ch).appendNewLine(); + } + + /** + * Appends a char array followed by a new line to the string builder. Appending + * null will call {@link #appendNull()}. * * @param chars the char array to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final char[] chars) { - if (chars == null) { - return appendNull(); - } - final int strLen = chars.length; - if (strLen > 0) { - final int len = length(); - ensureCapacity(len + strLen); - System.arraycopy(chars, 0, buffer, len, strLen); - size += strLen; - } - return this; + public StrBuilder appendln(final char[] chars) { + return append(chars).appendNewLine(); } /** - * Appends a char array to the string builder. Appending null will call - * {@link #appendNull()}. + * Appends a char array followed by a new line to the string builder. Appending + * null will call {@link #appendNull()}. * * @param chars the char array to append * @param startIndex the start index, inclusive, must be valid * @param length the length to append, must be valid * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final char[] chars, final int startIndex, final int length) { - if (chars == null) { - return appendNull(); - } - if (startIndex < 0 || startIndex > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid startIndex: " + length); - } - if (length < 0 || (startIndex + length) > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid length: " + length); - } - if (length > 0) { - final int len = length(); - ensureCapacity(len + length); - System.arraycopy(chars, startIndex, buffer, len, length); - size += length; - } - return this; + public StrBuilder appendln(final char[] chars, final int startIndex, final int length) { + return append(chars, startIndex, length).appendNewLine(); } /** - * Appends a boolean value to the string builder. + * Appends a double value followed by a new line to the string builder using + * {@code String.valueOf}. * * @param value the value to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final boolean value) { - if (value) { - ensureCapacity(size + 4); - buffer[size++] = 't'; - buffer[size++] = 'r'; - buffer[size++] = 'u'; - buffer[size++] = 'e'; - } else { - ensureCapacity(size + 5); - buffer[size++] = 'f'; - buffer[size++] = 'a'; - buffer[size++] = 'l'; - buffer[size++] = 's'; - buffer[size++] = 'e'; - } - return this; + public StrBuilder appendln(final double value) { + return append(value).appendNewLine(); } /** - * Appends a char value to the string builder. - * - * @param ch the value to append - * @return this, to enable chaining - * @since 3.0 - */ - @Override - public StrBuilder append(final char ch) { - final int len = length(); - ensureCapacity(len + 1); - buffer[size++] = ch; - return this; - } - - /** - * Appends an int value to the string builder using {@code String.valueOf}. + * Appends a float value followed by a new line to the string builder using + * {@code String.valueOf}. * * @param value the value to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final int value) { - return append(String.valueOf(value)); + public StrBuilder appendln(final float value) { + return append(value).appendNewLine(); } /** - * Appends a long value to the string builder using {@code String.valueOf}. + * Appends an int value followed by a new line to the string builder using + * {@code String.valueOf}. * * @param value the value to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final long value) { - return append(String.valueOf(value)); + public StrBuilder appendln(final int value) { + return append(value).appendNewLine(); } /** - * Appends a float value to the string builder using {@code String.valueOf}. + * Appends a long value followed by a new line to the string builder using + * {@code String.valueOf}. * * @param value the value to append * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder append(final float value) { - return append(String.valueOf(value)); - } - - /** - * Appends a double value to the string builder using {@code String.valueOf}. - * - * @param value the value to append - * @return this, to enable chaining - */ - public StrBuilder append(final double value) { - return append(String.valueOf(value)); + public StrBuilder appendln(final long value) { + return append(value).appendNewLine(); } // ----------------------------------------------------------------------- @@ -991,6 +1042,32 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return append(obj).appendNewLine(); } + /** + * Appends another string builder followed by a new line to this string builder. + * Appending null will call {@link #appendNull()}. + * + * @param str the string builder to append + * @return this, to enable chaining + * @since 2.3 + */ + public StrBuilder appendln(final StrBuilder str) { + return append(str).appendNewLine(); + } + + /** + * Appends part of a string builder followed by a new line to this string + * builder. Appending null will call {@link #appendNull()}. + * + * @param str the string to append + * @param startIndex the start index, inclusive, must be valid + * @param length the length to append, must be valid + * @return this, to enable chaining + * @since 2.3 + */ + public StrBuilder appendln(final StrBuilder str, final int startIndex, final int length) { + return append(str, startIndex, length).appendNewLine(); + } + /** * Appends a string followed by a new line to this string builder. Appending * null will call {@link #appendNull()}. @@ -1042,6 +1119,20 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return append(str).appendNewLine(); } + /** + * Appends part of a string buffer followed by a new line to this string + * builder. Appending null will call {@link #appendNull()}. + * + * @param str the string to append + * @param startIndex the start index, inclusive, must be valid + * @param length the length to append, must be valid + * @return this, to enable chaining + * @since 2.3 + */ + public StrBuilder appendln(final StringBuffer str, final int startIndex, final int length) { + return append(str, startIndex, length).appendNewLine(); + } + /** * Appends a string builder followed by a new line to this string builder. * Appending null will call {@link #appendNull()}. @@ -1068,332 +1159,50 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return append(str, startIndex, length).appendNewLine(); } - /** - * Appends part of a string buffer followed by a new line to this string - * builder. Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final StringBuffer str, final int startIndex, final int length) { - return append(str, startIndex, length).appendNewLine(); - } - - /** - * Appends another string builder followed by a new line to this string builder. - * Appending null will call {@link #appendNull()}. - * - * @param str the string builder to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final StrBuilder str) { - return append(str).appendNewLine(); - } - - /** - * Appends part of a string builder followed by a new line to this string - * builder. Appending null will call {@link #appendNull()}. - * - * @param str the string to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final StrBuilder str, final int startIndex, final int length) { - return append(str, startIndex, length).appendNewLine(); - } - - /** - * Appends a char array followed by a new line to the string builder. Appending - * null will call {@link #appendNull()}. - * - * @param chars the char array to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final char[] chars) { - return append(chars).appendNewLine(); - } - - /** - * Appends a char array followed by a new line to the string builder. Appending - * null will call {@link #appendNull()}. - * - * @param chars the char array to append - * @param startIndex the start index, inclusive, must be valid - * @param length the length to append, must be valid - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final char[] chars, final int startIndex, final int length) { - return append(chars, startIndex, length).appendNewLine(); - } - - /** - * Appends a boolean value followed by a new line to the string builder. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final boolean value) { - return append(value).appendNewLine(); - } - - /** - * Appends a char value followed by a new line to the string builder. - * - * @param ch the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final char ch) { - return append(ch).appendNewLine(); - } - - /** - * Appends an int value followed by a new line to the string builder using - * {@code String.valueOf}. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final int value) { - return append(value).appendNewLine(); - } - - /** - * Appends a long value followed by a new line to the string builder using - * {@code String.valueOf}. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final long value) { - return append(value).appendNewLine(); - } - - /** - * Appends a float value followed by a new line to the string builder using - * {@code String.valueOf}. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final float value) { - return append(value).appendNewLine(); - } - - /** - * Appends a double value followed by a new line to the string builder using - * {@code String.valueOf}. - * - * @param value the value to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendln(final double value) { - return append(value).appendNewLine(); - } - // ----------------------------------------------------------------------- /** - * Appends each item in an array to the builder without any separators. - * Appending a null array will have no effect. Each object is appended using - * {@link #append(Object)}. - * - * @param the element type - * @param array the array to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendAll(@SuppressWarnings("unchecked") final T... array) { - /* - * @SuppressWarnings used to hide warning about vararg usage. We cannot - * use @SafeVarargs, since this method is not final. Using @SuppressWarnings is - * fine, because it isn't inherited by subclasses, so each subclass must vouch - * for itself whether its use of 'array' is safe. - */ - if (array.length > 0) { - for (final Object element : array) { - append(element); - } - } - return this; - } - - /** - * Appends each item in an iterable to the builder without any separators. - * Appending a null iterable will have no effect. Each object is appended using - * {@link #append(Object)}. - * - * @param iterable the iterable to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendAll(final Iterable iterable) { - if (iterable != null) { - for (final Object o : iterable) { - append(o); - } - } - return this; - } - - /** - * Appends each item in an iterator to the builder without any separators. - * Appending a null iterator will have no effect. Each object is appended using - * {@link #append(Object)}. - * - * @param it the iterator to append - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendAll(final Iterator it) { - if (it != null) { - while (it.hasNext()) { - append(it.next()); - } - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Appends an array placing separators between each value, but not before the - * first or after the last. Appending a null array will have no effect. Each - * object is appended using {@link #append(Object)}. - * - * @param array the array to append - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - */ - public StrBuilder appendWithSeparators(final Object[] array, final String separator) { - if (array != null && array.length > 0) { - final String sep = Objects.toString(separator, ""); - append(array[0]); - for (int i = 1; i < array.length; i++) { - append(sep); - append(array[i]); - } - } - return this; - } - - /** - * Appends an iterable placing separators between each value, but not before the - * first or after the last. Appending a null iterable will have no effect. Each - * object is appended using {@link #append(Object)}. - * - * @param iterable the iterable to append - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - */ - public StrBuilder appendWithSeparators(final Iterable iterable, final String separator) { - if (iterable != null) { - final String sep = Objects.toString(separator, ""); - final Iterator it = iterable.iterator(); - while (it.hasNext()) { - append(it.next()); - if (it.hasNext()) { - append(sep); - } - } - } - return this; - } - - /** - * Appends an iterator placing separators between each value, but not before the - * first or after the last. Appending a null iterator will have no effect. Each - * object is appended using {@link #append(Object)}. - * - * @param it the iterator to append - * @param separator the separator to use, null means no separator - * @return this, to enable chaining - */ - public StrBuilder appendWithSeparators(final Iterator it, final String separator) { - if (it != null) { - final String sep = Objects.toString(separator, ""); - while (it.hasNext()) { - append(it.next()); - if (it.hasNext()) { - append(sep); - } - } - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Appends a separator if the builder is currently non-empty. Appending a null - * separator will have no effect. The separator is appended using - * {@link #append(String)}. + * Appends the new line string to this string builder. *

              - * This method is useful for adding a separator each time around the loop except - * the first. - * - *

              -	 * for (Iterator it = list.iterator(); it.hasNext();) {
              -	 * 	appendSeparator(",");
              -	 * 	append(it.next());
              -	 * }
              -	 * 
              - * - * Note that for this simple example, you should use - * {@link #appendWithSeparators(Iterable, String)}. + * The new line string can be altered using {@link #setNewLineText(String)}. + * This might be used to force the output to always use Unix line endings even + * when on Windows. * - * @param separator the separator to use, null means no separator * @return this, to enable chaining - * @since 2.3 */ - public StrBuilder appendSeparator(final String separator) { - return appendSeparator(separator, null); + public StrBuilder appendNewLine() { + if (newLine == null) { + append(System.lineSeparator()); + return this; + } + return append(newLine); } /** - * Appends one of both separators to the StrBuilder. If the builder is currently - * empty it will append the defaultIfEmpty-separator Otherwise it will append - * the standard-separator + * Appends the text representing {@code null} to this string builder. * - * Appending a null separator will have no effect. The separator is appended - * using {@link #append(String)}. - *

              - * This method is for example useful for constructing queries - * - *

              -	 * StrBuilder whereClause = new StrBuilder();
              -	 * if (searchCommand.getPriority() != null) {
              -	 *  whereClause.appendSeparator(" and", " where");
              -	 *  whereClause.append(" priority = ?")
              -	 * }
              -	 * if (searchCommand.getComponent() != null) {
              -	 *  whereClause.appendSeparator(" and", " where");
              -	 *  whereClause.append(" component = ?")
              -	 * }
              -	 * selectClause.append(whereClause)
              -	 * 
              - * - * @param standard the separator if builder is not empty, null means no - * separator - * @param defaultIfEmpty the separator if builder is empty, null means no - * separator * @return this, to enable chaining - * @since 2.5 */ - public StrBuilder appendSeparator(final String standard, final String defaultIfEmpty) { - final String str = isEmpty() ? defaultIfEmpty : standard; - if (str != null) { - append(str); + public StrBuilder appendNull() { + if (nullText == null) { + return this; + } + return append(nullText); + } + + // ----------------------------------------------------------------------- + /** + * Appends the pad character to the builder the specified number of times. + * + * @param length the length to append, negative means no append + * @param padChar the character to append + * @return this, to enable chaining + */ + public StrBuilder appendPadding(final int length, final char padChar) { + if (length >= 0) { + ensureCapacity(size + length); + for (int i = 0; i < length; i++) { + buffer[size++] = padChar; + } } return this; } @@ -1447,37 +1256,6 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return this; } - /** - * Appends a separator to the builder if the loop index is greater than zero. - * Appending a null separator will have no effect. The separator is appended - * using {@link #append(String)}. - *

              - * This method is useful for adding a separator each time around the loop except - * the first. - *

              - * - *
              -	 * for (int i = 0; i < list.size(); i++) {
              -	 * 	appendSeparator(",", i);
              -	 * 	append(list.get(i));
              -	 * }
              -	 * 
              - * - * Note that for this simple example, you should use - * {@link #appendWithSeparators(Iterable, String)}. - * - * @param separator the separator to use, null means no separator - * @param loopIndex the loop index - * @return this, to enable chaining - * @since 2.3 - */ - public StrBuilder appendSeparator(final String separator, final int loopIndex) { - if (separator != null && loopIndex > 0) { - append(separator); - } - return this; - } - /** * Appends a separator to the builder if the loop index is greater than zero. * The separator is appended using {@link #append(char)}. @@ -1510,325 +1288,377 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build // ----------------------------------------------------------------------- /** - * Appends the pad character to the builder the specified number of times. + * Appends a separator if the builder is currently non-empty. Appending a null + * separator will have no effect. The separator is appended using + * {@link #append(String)}. + *

              + * This method is useful for adding a separator each time around the loop except + * the first. + * + *

              +	 * for (Iterator it = list.iterator(); it.hasNext();) {
              +	 * 	appendSeparator(",");
              +	 * 	append(it.next());
              +	 * }
              +	 * 
              + * + * Note that for this simple example, you should use + * {@link #appendWithSeparators(Iterable, String)}. * - * @param length the length to append, negative means no append - * @param padChar the character to append + * @param separator the separator to use, null means no separator * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder appendPadding(final int length, final char padChar) { - if (length >= 0) { - ensureCapacity(size + length); - for (int i = 0; i < length; i++) { - buffer[size++] = padChar; - } - } - return this; + public StrBuilder appendSeparator(final String separator) { + return appendSeparator(separator, null); } - // ----------------------------------------------------------------------- /** - * Appends an object to the builder padding on the left to a fixed width. The - * {@code toString} of the object is used. If the object is larger than the - * length, the left hand side is lost. If the object is null, the null text - * value is used. + * Appends a separator to the builder if the loop index is greater than zero. + * Appending a null separator will have no effect. The separator is appended + * using {@link #append(String)}. + *

              + * This method is useful for adding a separator each time around the loop except + * the first. + *

              + * + *
              +	 * for (int i = 0; i < list.size(); i++) {
              +	 * 	appendSeparator(",", i);
              +	 * 	append(list.get(i));
              +	 * }
              +	 * 
              + * + * Note that for this simple example, you should use + * {@link #appendWithSeparators(Iterable, String)}. * - * @param obj the object to append, null uses null text - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use + * @param separator the separator to use, null means no separator + * @param loopIndex the loop index * @return this, to enable chaining + * @since 2.3 */ - public StrBuilder appendFixedWidthPadLeft(final Object obj, final int width, final char padChar) { - if (width > 0) { - ensureCapacity(size + width); - String str = (obj == null ? getNullText() : obj.toString()); - if (str == null) { - str = StringUtils.EMPTY; - } - final int strLen = str.length(); - if (strLen >= width) { - str.getChars(strLen - width, strLen, buffer, size); - } else { - final int padLen = width - strLen; - for (int i = 0; i < padLen; i++) { - buffer[size + i] = padChar; - } - str.getChars(0, strLen, buffer, size + padLen); - } - size += width; + public StrBuilder appendSeparator(final String separator, final int loopIndex) { + if (separator != null && loopIndex > 0) { + append(separator); } return this; } /** - * Appends an object to the builder padding on the left to a fixed width. The - * {@code String.valueOf} of the {@code int} value is used. If the formatted - * value is larger than the length, the left hand side is lost. + * Appends one of both separators to the StrBuilder. If the builder is currently + * empty it will append the defaultIfEmpty-separator Otherwise it will append + * the standard-separator * - * @param value the value to append - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use - * @return this, to enable chaining - */ - public StrBuilder appendFixedWidthPadLeft(final int value, final int width, final char padChar) { - return appendFixedWidthPadLeft(String.valueOf(value), width, padChar); - } - - /** - * Appends an object to the builder padding on the right to a fixed length. The - * {@code toString} of the object is used. If the object is larger than the - * length, the right hand side is lost. If the object is null, null text value - * is used. + * Appending a null separator will have no effect. The separator is appended + * using {@link #append(String)}. + *

              + * This method is for example useful for constructing queries + * + *

              +	 * StrBuilder whereClause = new StrBuilder();
              +	 * if (searchCommand.getPriority() != null) {
              +	 *  whereClause.appendSeparator(" and", " where");
              +	 *  whereClause.append(" priority = ?")
              +	 * }
              +	 * if (searchCommand.getComponent() != null) {
              +	 *  whereClause.appendSeparator(" and", " where");
              +	 *  whereClause.append(" component = ?")
              +	 * }
              +	 * selectClause.append(whereClause)
              +	 * 
              * - * @param obj the object to append, null uses null text - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use + * @param standard the separator if builder is not empty, null means no + * separator + * @param defaultIfEmpty the separator if builder is empty, null means no + * separator * @return this, to enable chaining + * @since 2.5 */ - public StrBuilder appendFixedWidthPadRight(final Object obj, final int width, final char padChar) { - if (width > 0) { - ensureCapacity(size + width); - String str = (obj == null ? getNullText() : obj.toString()); - if (str == null) { - str = StringUtils.EMPTY; - } - final int strLen = str.length(); - if (strLen >= width) { - str.getChars(0, width, buffer, size); - } else { - final int padLen = width - strLen; - str.getChars(0, strLen, buffer, size); - for (int i = 0; i < padLen; i++) { - buffer[size + strLen + i] = padChar; - } - } - size += width; - } - return this; - } - - /** - * Appends an object to the builder padding on the right to a fixed length. The - * {@code String.valueOf} of the {@code int} value is used. If the object is - * larger than the length, the right hand side is lost. - * - * @param value the value to append - * @param width the fixed field width, zero or negative has no effect - * @param padChar the pad character to use - * @return this, to enable chaining - */ - public StrBuilder appendFixedWidthPadRight(final int value, final int width, final char padChar) { - return appendFixedWidthPadRight(String.valueOf(value), width, padChar); - } - - // ----------------------------------------------------------------------- - /** - * Inserts the string representation of an object into this builder. Inserting - * null will use the stored null text value. - * - * @param index the index to add at, must be valid - * @param obj the object to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, final Object obj) { - if (obj == null) { - return insert(index, nullText); - } - return insert(index, obj.toString()); - } - - /** - * Inserts the string into this builder. Inserting null will use the stored null - * text value. - * - * @param index the index to add at, must be valid - * @param str the string to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, String str) { - validateIndex(index); - if (str == null) { - str = nullText; - } + public StrBuilder appendSeparator(final String standard, final String defaultIfEmpty) { + final String str = isEmpty() ? defaultIfEmpty : standard; if (str != null) { - final int strLen = str.length(); - if (strLen > 0) { - final int newSize = size + strLen; - ensureCapacity(newSize); - System.arraycopy(buffer, index, buffer, index + strLen, size - index); - size = newSize; - str.getChars(0, strLen, buffer, index); + append(str); + } + return this; + } + + /** + * Appends current contents of this {@code StrBuilder} to the provided + * {@link Appendable}. + *

              + * This method tries to avoid doing any extra copies of contents. + * + * @param appendable the appendable to append data to + * @throws IOException if an I/O error occurs + * + * @since 3.4 + * @see #readFrom(Readable) + */ + public void appendTo(final Appendable appendable) throws IOException { + if (appendable instanceof Writer) { + ((Writer) appendable).write(buffer, 0, size); + } else if (appendable instanceof StringBuilder) { + ((StringBuilder) appendable).append(buffer, 0, size); + } else if (appendable instanceof StringBuffer) { + ((StringBuffer) appendable).append(buffer, 0, size); + } else if (appendable instanceof CharBuffer) { + ((CharBuffer) appendable).put(buffer, 0, size); + } else { + appendable.append(this); + } + } + + /** + * Appends an iterable placing separators between each value, but not before the + * first or after the last. Appending a null iterable will have no effect. Each + * object is appended using {@link #append(Object)}. + * + * @param iterable the iterable to append + * @param separator the separator to use, null means no separator + * @return this, to enable chaining + */ + public StrBuilder appendWithSeparators(final Iterable iterable, final String separator) { + if (iterable != null) { + final String sep = Objects.toString(separator, ""); + final Iterator it = iterable.iterator(); + while (it.hasNext()) { + append(it.next()); + if (it.hasNext()) { + append(sep); + } } } return this; } /** - * Inserts the character array into this builder. Inserting null will use the - * stored null text value. + * Appends an iterator placing separators between each value, but not before the + * first or after the last. Appending a null iterator will have no effect. Each + * object is appended using {@link #append(Object)}. * - * @param index the index to add at, must be valid - * @param chars the char array to insert + * @param it the iterator to append + * @param separator the separator to use, null means no separator * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid */ - public StrBuilder insert(final int index, final char[] chars) { - validateIndex(index); - if (chars == null) { - return insert(index, nullText); - } - final int len = chars.length; - if (len > 0) { - ensureCapacity(size + len); - System.arraycopy(buffer, index, buffer, index + len, size - index); - System.arraycopy(chars, 0, buffer, index, len); - size += len; + public StrBuilder appendWithSeparators(final Iterator it, final String separator) { + if (it != null) { + final String sep = Objects.toString(separator, ""); + while (it.hasNext()) { + append(it.next()); + if (it.hasNext()) { + append(sep); + } + } } return this; } - /** - * Inserts part of the character array into this builder. Inserting null will - * use the stored null text value. - * - * @param index the index to add at, must be valid - * @param chars the char array to insert - * @param offset the offset into the character array to start at, must be valid - * @param length the length of the character array part to copy, must be - * positive - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if any index is invalid - */ - public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) { - validateIndex(index); - if (chars == null) { - return insert(index, nullText); - } - if (offset < 0 || offset > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid offset: " + offset); - } - if (length < 0 || offset + length > chars.length) { - throw new StringIndexOutOfBoundsException("Invalid length: " + length); - } - if (length > 0) { - ensureCapacity(size + length); - System.arraycopy(buffer, index, buffer, index + length, size - index); - System.arraycopy(chars, offset, buffer, index, length); - size += length; - } - return this; - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(int index, final boolean value) { - validateIndex(index); - if (value) { - ensureCapacity(size + 4); - System.arraycopy(buffer, index, buffer, index + 4, size - index); - buffer[index++] = 't'; - buffer[index++] = 'r'; - buffer[index++] = 'u'; - buffer[index] = 'e'; - size += 4; - } else { - ensureCapacity(size + 5); - System.arraycopy(buffer, index, buffer, index + 5, size - index); - buffer[index++] = 'f'; - buffer[index++] = 'a'; - buffer[index++] = 'l'; - buffer[index++] = 's'; - buffer[index] = 'e'; - size += 5; - } - return this; - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, final char value) { - validateIndex(index); - ensureCapacity(size + 1); - System.arraycopy(buffer, index, buffer, index + 1, size - index); - buffer[index] = value; - size++; - return this; - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, final int value) { - return insert(index, String.valueOf(value)); - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, final long value) { - return insert(index, String.valueOf(value)); - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, final float value) { - return insert(index, String.valueOf(value)); - } - - /** - * Inserts the value into this builder. - * - * @param index the index to add at, must be valid - * @param value the value to insert - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder insert(final int index, final double value) { - return insert(index, String.valueOf(value)); - } - // ----------------------------------------------------------------------- /** - * Internal method to delete a range without validation. + * Appends an array placing separators between each value, but not before the + * first or after the last. Appending a null array will have no effect. Each + * object is appended using {@link #append(Object)}. * - * @param startIndex the start index, must be valid - * @param endIndex the end index (exclusive), must be valid - * @param len the length, must be valid - * @throws IndexOutOfBoundsException if any index is invalid + * @param array the array to append + * @param separator the separator to use, null means no separator + * @return this, to enable chaining */ - private void deleteImpl(final int startIndex, final int endIndex, final int len) { - System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex); - size -= len; + public StrBuilder appendWithSeparators(final Object[] array, final String separator) { + if (array != null && array.length > 0) { + final String sep = Objects.toString(separator, ""); + append(array[0]); + for (int i = 1; i < array.length; i++) { + append(sep); + append(array[i]); + } + } + return this; + } + + // ----------------------------------------------------------------------- + /** + * Gets the contents of this builder as a Reader. + *

              + * This method allows the contents of the builder to be read using any standard + * method that expects a Reader. + *

              + * To use, simply create a {@code StrBuilder}, populate it with data, call + * {@code asReader}, and then read away. + *

              + * The internal character array is shared between the builder and the reader. + * This allows you to append to the builder after creating the reader, and the + * changes will be picked up. Note however, that no synchronization occurs, so + * you must perform all operations with the builder and the reader in one + * thread. + *

              + * The returned reader supports marking, and ignores the flush method. + * + * @return a reader that reads from this builder + */ + public Reader asReader() { + return new StrBuilderReader(); + } + + // ----------------------------------------------------------------------- + /** + * Creates a tokenizer that can tokenize the contents of this builder. + *

              + * This method allows the contents of this builder to be tokenized. The + * tokenizer will be setup by default to tokenize on space, tab, newline and + * formfeed (as per StringTokenizer). These values can be changed on the + * tokenizer class, before retrieving the tokens. + *

              + * The returned tokenizer is linked to this builder. You may intermix calls to + * the builder and tokenizer within certain limits, however there is no + * synchronization. Once the tokenizer has been used once, it must be + * {@link StrTokenizer#reset() reset} to pickup the latest changes in the + * builder. For example: + * + *

              +	 * StrBuilder b = new StrBuilder();
              +	 * b.append("a b ");
              +	 * StrTokenizer t = b.asTokenizer();
              +	 * String[] tokens1 = t.getTokenArray(); // returns a,b
              +	 * b.append("c d ");
              +	 * String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
              +	 * t.reset(); // reset causes builder changes to be picked up
              +	 * String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
              +	 * 
              + * + * In addition to simply intermixing appends and tokenization, you can also call + * the set methods on the tokenizer to alter how it tokenizes. Just remember to + * call reset when you want to pickup builder changes. + *

              + * Calling {@link StrTokenizer#reset(String)} or + * {@link StrTokenizer#reset(char[])} with a non-null value will break the link + * with the builder. + * + * @return a tokenizer that is linked to this builder + */ + public StrTokenizer asTokenizer() { + return new StrBuilderTokenizer(); + } + + // ----------------------------------------------------------------------- + /** + * Gets this builder as a Writer that can be written to. + *

              + * This method allows you to populate the contents of the builder using any + * standard method that takes a Writer. + *

              + * To use, simply create a {@code StrBuilder}, call {@code asWriter}, and + * populate away. The data is available at any time using the methods of the + * {@code StrBuilder}. + *

              + * The internal character array is shared between the builder and the writer. + * This allows you to intermix calls that append to the builder and write using + * the writer and the changes will be occur correctly. Note however, that no + * synchronization occurs, so you must perform all operations with the builder + * and the writer in one thread. + *

              + * The returned writer ignores the close and flush methods. + * + * @return a writer that populates this builder + */ + public Writer asWriter() { + return new StrBuilderWriter(); + } + + /** + * Implement the {@link Builder} interface. + * + * @return the builder as a String + * @since 3.2 + * @see #toString() + */ + @Override + public String build() { + return toString(); + } + + // ----------------------------------------------------------------------- + /** + * Gets the current size of the internal character array buffer. + * + * @return the capacity + */ + public int capacity() { + return buffer.length; + } + + // ----------------------------------------------------------------------- + /** + * Gets the character at the specified index. + * + * @see #setCharAt(int, char) + * @see #deleteCharAt(int) + * @param index the index to retrieve, must be valid + * @return the character at the index + * @throws IndexOutOfBoundsException if the index is invalid + */ + @Override + public char charAt(final int index) { + if (index < 0 || index >= length()) { + throw new StringIndexOutOfBoundsException(index); + } + return buffer[index]; + } + + /** + * Clears the string builder (convenience Collections API style method). + *

              + * This method does not reduce the size of the internal character buffer. To do + * that, call {@code clear()} followed by {@link #minimizeCapacity()}. + *

              + * This method is the same as {@link #setLength(int)} called with zero and is + * provided to match the API of Collections. + * + * @return this, to enable chaining + */ + public StrBuilder clear() { + size = 0; + return this; + } + + // ----------------------------------------------------------------------- + /** + * Checks if the string builder contains the specified char. + * + * @param ch the character to find + * @return true if the builder contains the character + */ + public boolean contains(final char ch) { + final char[] thisBuf = buffer; + for (int i = 0; i < this.size; i++) { + if (thisBuf[i] == ch) { + return true; + } + } + return false; + } + + /** + * Checks if the string builder contains the specified string. + * + * @param str the string to find + * @return true if the builder contains the string + */ + public boolean contains(final String str) { + return indexOf(str, 0) >= 0; + } + + /** + * Checks if the string builder contains a string matched using the specified + * matcher. + *

              + * Matchers can be used to perform advanced searching behavior. For example you + * could write a matcher to search for the character 'a' followed by a number. + * + * @param matcher the matcher to use, null returns -1 + * @return true if the matcher finds a match in the builder + */ + public boolean contains(final StrMatcher matcher) { + return indexOf(matcher, 0) >= 0; } /** @@ -1873,22 +1703,6 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return this; } - /** - * Deletes the character wherever it occurs in the builder. - * - * @param ch the character to delete - * @return this, to enable chaining - */ - public StrBuilder deleteFirst(final char ch) { - for (int i = 0; i < size; i++) { - if (buffer[i] == ch) { - deleteImpl(i, i + 1, 1); - break; - } - } - return this; - } - // ----------------------------------------------------------------------- /** * Deletes the string wherever it occurs in the builder. @@ -1908,6 +1722,54 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return this; } + // ----------------------------------------------------------------------- + /** + * Deletes all parts of the builder that the matcher matches. + *

              + * Matchers can be used to perform advanced deletion behavior. For example you + * could write a matcher to delete all occurrences where the character 'a' is + * followed by a number. + * + * @param matcher the matcher to use to find the deletion, null causes no action + * @return this, to enable chaining + */ + public StrBuilder deleteAll(final StrMatcher matcher) { + return replace(matcher, null, 0, size, -1); + } + + /** + * Deletes the character at the specified index. + * + * @see #charAt(int) + * @see #setCharAt(int, char) + * @param index the index to delete + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder deleteCharAt(final int index) { + if (index < 0 || index >= size) { + throw new StringIndexOutOfBoundsException(index); + } + deleteImpl(index, index + 1, 1); + return this; + } + + /** + * Deletes the character wherever it occurs in the builder. + * + * @param ch the character to delete + * @return this, to enable chaining + */ + public StrBuilder deleteFirst(final char ch) { + for (int i = 0; i < size; i++) { + if (buffer[i] == ch) { + deleteImpl(i, i + 1, 1); + break; + } + } + return this; + } + /** * Deletes the string wherever it occurs in the builder. * @@ -1925,21 +1787,6 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return this; } - // ----------------------------------------------------------------------- - /** - * Deletes all parts of the builder that the matcher matches. - *

              - * Matchers can be used to perform advanced deletion behavior. For example you - * could write a matcher to delete all occurrences where the character 'a' is - * followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no action - * @return this, to enable chaining - */ - public StrBuilder deleteAll(final StrMatcher matcher) { - return replace(matcher, null, 0, size, -1); - } - /** * Deletes the first match within the builder using the specified matcher. *

              @@ -1960,292 +1807,12 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build * * @param startIndex the start index, must be valid * @param endIndex the end index (exclusive), must be valid - * @param removeLen the length to remove (endIndex - startIndex), must be valid - * @param insertStr the string to replace with, null means delete range - * @param insertLen the length of the insert string, must be valid + * @param len the length, must be valid * @throws IndexOutOfBoundsException if any index is invalid */ - private void replaceImpl(final int startIndex, final int endIndex, final int removeLen, final String insertStr, - final int insertLen) { - final int newSize = size - removeLen + insertLen; - if (insertLen != removeLen) { - ensureCapacity(newSize); - System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex); - size = newSize; - } - if (insertLen > 0) { - insertStr.getChars(0, insertLen, buffer, startIndex); - } - } - - /** - * Replaces a portion of the string builder with another string. The length of - * the inserted string does not have to match the removed length. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except that if too - * large it is treated as end of string - * @param replaceStr the string to replace with, null means delete range - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if the index is invalid - */ - public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) { - endIndex = validateRange(startIndex, endIndex); - final int insertLen = (replaceStr == null ? 0 : replaceStr.length()); - replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen); - return this; - } - - // ----------------------------------------------------------------------- - /** - * Replaces the search character with the replace character throughout the - * builder. - * - * @param search the search character - * @param replace the replace character - * @return this, to enable chaining - */ - public StrBuilder replaceAll(final char search, final char replace) { - if (search != replace) { - for (int i = 0; i < size; i++) { - if (buffer[i] == search) { - buffer[i] = replace; - } - } - } - return this; - } - - /** - * Replaces the first instance of the search character with the replace - * character in the builder. - * - * @param search the search character - * @param replace the replace character - * @return this, to enable chaining - */ - public StrBuilder replaceFirst(final char search, final char replace) { - if (search != replace) { - for (int i = 0; i < size; i++) { - if (buffer[i] == search) { - buffer[i] = replace; - break; - } - } - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Replaces the search string with the replace string throughout the builder. - * - * @param searchStr the search string, null causes no action to occur - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceAll(final String searchStr, final String replaceStr) { - final int searchLen = (searchStr == null ? 0 : searchStr.length()); - if (searchLen > 0) { - final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); - int index = indexOf(searchStr, 0); - while (index >= 0) { - replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); - index = indexOf(searchStr, index + replaceLen); - } - } - return this; - } - - /** - * Replaces the first instance of the search string with the replace string. - * - * @param searchStr the search string, null causes no action to occur - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceFirst(final String searchStr, final String replaceStr) { - final int searchLen = (searchStr == null ? 0 : searchStr.length()); - if (searchLen > 0) { - final int index = indexOf(searchStr, 0); - if (index >= 0) { - final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); - replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); - } - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Replaces all matches within the builder with the replace string. - *

              - * Matchers can be used to perform advanced replace behavior. For example you - * could write a matcher to replace all occurrences where the character 'a' is - * followed by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no - * action - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) { - return replace(matcher, replaceStr, 0, size, -1); - } - - /** - * Replaces the first match within the builder with the replace string. - *

              - * Matchers can be used to perform advanced replace behavior. For example you - * could write a matcher to replace where the character 'a' is followed by a - * number. - * - * @param matcher the matcher to use to find the deletion, null causes no - * action - * @param replaceStr the replace string, null is equivalent to an empty string - * @return this, to enable chaining - */ - public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) { - return replace(matcher, replaceStr, 0, size, 1); - } - - // ----------------------------------------------------------------------- - /** - * Advanced search and replaces within the builder using a matcher. - *

              - * Matchers can be used to perform advanced behavior. For example you could - * write a matcher to delete all occurrences where the character 'a' is followed - * by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no - * action - * @param replaceStr the string to replace the match with, null is a delete - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except that if - * too large it is treated as end of string - * @param replaceCount the number of times to replace, -1 for replace all - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if start index is invalid - */ - public StrBuilder replace(final StrMatcher matcher, final String replaceStr, final int startIndex, int endIndex, - final int replaceCount) { - endIndex = validateRange(startIndex, endIndex); - return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount); - } - - /** - * Replaces within the builder using a matcher. - *

              - * Matchers can be used to perform advanced behavior. For example you could - * write a matcher to delete all occurrences where the character 'a' is followed - * by a number. - * - * @param matcher the matcher to use to find the deletion, null causes no - * action - * @param replaceStr the string to replace the match with, null is a delete - * @param from the start index, must be valid - * @param to the end index (exclusive), must be valid - * @param replaceCount the number of times to replace, -1 for replace all - * @return this, to enable chaining - * @throws IndexOutOfBoundsException if any index is invalid - */ - private StrBuilder replaceImpl(final StrMatcher matcher, final String replaceStr, final int from, int to, - int replaceCount) { - if (matcher == null || size == 0) { - return this; - } - final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); - for (int i = from; i < to && replaceCount != 0; i++) { - final char[] buf = buffer; - final int removeLen = matcher.isMatch(buf, i, from, to); - if (removeLen > 0) { - replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen); - to = to - removeLen + replaceLen; - i = i + replaceLen - 1; - if (replaceCount > 0) { - replaceCount--; - } - } - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Reverses the string builder placing each character in the opposite index. - * - * @return this, to enable chaining - */ - public StrBuilder reverse() { - if (size == 0) { - return this; - } - - final int half = size / 2; - final char[] buf = buffer; - for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++, rightIdx--) { - final char swap = buf[leftIdx]; - buf[leftIdx] = buf[rightIdx]; - buf[rightIdx] = swap; - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Trims the builder by removing characters less than or equal to a space from - * the beginning and end. - * - * @return this, to enable chaining - */ - public StrBuilder trim() { - if (size == 0) { - return this; - } - int len = size; - final char[] buf = buffer; - int pos = 0; - while (pos < len && buf[pos] <= ' ') { - pos++; - } - while (pos < len && buf[len - 1] <= ' ') { - len--; - } - if (len < size) { - delete(len, size); - } - if (pos > 0) { - delete(0, pos); - } - return this; - } - - // ----------------------------------------------------------------------- - /** - * Checks whether this builder starts with the specified string. - *

              - * Note that this method handles null input quietly, unlike String. - * - * @param str the string to search for, null returns false - * @return true if the builder starts with the string - */ - public boolean startsWith(final String str) { - if (str == null) { - return false; - } - final int len = str.length(); - if (len == 0) { - return true; - } - if (len > size) { - return false; - } - for (int i = 0; i < len; i++) { - if (buffer[i] != str.charAt(i)) { - return false; - } - } - return true; + private void deleteImpl(final int startIndex, final int endIndex, final int len) { + System.arraycopy(buffer, endIndex, buffer, startIndex, size - endIndex); + size -= len; } /** @@ -2276,167 +1843,159 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return true; } - // ----------------------------------------------------------------------- /** - * {@inheritDoc} - * - * @since 3.0 + * Checks the capacity and ensures that it is at least the size specified. + * + * @param capacity the capacity to ensure + * @return this, to enable chaining + */ + public StrBuilder ensureCapacity(final int capacity) { + if (capacity > buffer.length) { + final char[] old = buffer; + buffer = new char[capacity * 2]; + System.arraycopy(old, 0, buffer, 0, size); + } + return this; + } + + /** + * Checks the contents of this builder against another to see if they contain + * the same character content. + * + * @param obj the object to check, null returns false + * @return true if the builders contain the same characters in the same order */ @Override - public CharSequence subSequence(final int startIndex, final int endIndex) { + public boolean equals(final Object obj) { + return obj instanceof StrBuilder && equals((StrBuilder) obj); + } + + /** + * Checks the contents of this builder against another to see if they contain + * the same character content. + * + * @param other the object to check, null returns false + * @return true if the builders contain the same characters in the same order + */ + public boolean equals(final StrBuilder other) { + if (this == other) { + return true; + } + if (other == null) { + return false; + } + if (this.size != other.size) { + return false; + } + final char[] thisBuf = this.buffer; + final char[] otherBuf = other.buffer; + for (int i = size - 1; i >= 0; i--) { + if (thisBuf[i] != otherBuf[i]) { + return false; + } + } + return true; + } + + /** + * Checks the contents of this builder against another to see if they contain + * the same character content ignoring case. + * + * @param other the object to check, null returns false + * @return true if the builders contain the same characters in the same order + */ + public boolean equalsIgnoreCase(final StrBuilder other) { + if (this == other) { + return true; + } + if (this.size != other.size) { + return false; + } + final char[] thisBuf = this.buffer; + final char[] otherBuf = other.buffer; + for (int i = size - 1; i >= 0; i--) { + final char c1 = thisBuf[i]; + final char c2 = otherBuf[i]; + if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) { + return false; + } + } + return true; + } + + /** + * Copies the character array into the specified array. + * + * @param destination the destination array, null will cause an array to be + * created + * @return the input array, unless that was null or too small + */ + public char[] getChars(char[] destination) { + final int len = length(); + if (destination == null || destination.length < len) { + destination = new char[len]; + } + System.arraycopy(buffer, 0, destination, 0, len); + return destination; + } + + /** + * Copies the character array into the specified array. + * + * @param startIndex first index to copy, inclusive, must be valid + * @param endIndex last index, exclusive, must be valid + * @param destination the destination array, must not be null or too small + * @param destinationIndex the index to start copying in destination + * @throws NullPointerException if the array is null + * @throws IndexOutOfBoundsException if any index is invalid + */ + public void getChars(final int startIndex, final int endIndex, final char[] destination, + final int destinationIndex) { if (startIndex < 0) { throw new StringIndexOutOfBoundsException(startIndex); } - if (endIndex > size) { + if (endIndex < 0 || endIndex > length()) { throw new StringIndexOutOfBoundsException(endIndex); } if (startIndex > endIndex) { - throw new StringIndexOutOfBoundsException(endIndex - startIndex); + throw new StringIndexOutOfBoundsException("end < start"); } - return substring(startIndex, endIndex); - } - - /** - * Extracts a portion of this string builder as a string. - * - * @param start the start index, inclusive, must be valid - * @return the new string - * @throws IndexOutOfBoundsException if the index is invalid - */ - public String substring(final int start) { - return substring(start, size); - } - - /** - * Extracts a portion of this string builder as a string. - *

              - * Note: This method treats an endIndex greater than the length of the builder - * as equal to the length of the builder, and continues without error, unlike - * StringBuffer or String. - * - * @param startIndex the start index, inclusive, must be valid - * @param endIndex the end index, exclusive, must be valid except that if too - * large it is treated as end of string - * @return the new string - * @throws IndexOutOfBoundsException if the index is invalid - */ - public String substring(final int startIndex, int endIndex) { - endIndex = validateRange(startIndex, endIndex); - return new String(buffer, startIndex, endIndex - startIndex); - } - - /** - * Extracts the leftmost characters from the string builder without throwing an - * exception. - *

              - * This method extracts the left {@code length} characters from the builder. If - * this many characters are not available, the whole builder is returned. Thus - * the returned string may be shorter than the length requested. - * - * @param length the number of characters to extract, negative returns empty - * string - * @return the new string - */ - public String leftString(final int length) { - if (length <= 0) { - return StringUtils.EMPTY; - } else if (length >= size) { - return new String(buffer, 0, size); - } else { - return new String(buffer, 0, length); - } - } - - /** - * Extracts the rightmost characters from the string builder without throwing an - * exception. - *

              - * This method extracts the right {@code length} characters from the builder. If - * this many characters are not available, the whole builder is returned. Thus - * the returned string may be shorter than the length requested. - * - * @param length the number of characters to extract, negative returns empty - * string - * @return the new string - */ - public String rightString(final int length) { - if (length <= 0) { - return StringUtils.EMPTY; - } else if (length >= size) { - return new String(buffer, 0, size); - } else { - return new String(buffer, size - length, length); - } - } - - /** - * Extracts some characters from the middle of the string builder without - * throwing an exception. - *

              - * This method extracts {@code length} characters from the builder at the - * specified index. If the index is negative it is treated as zero. If the index - * is greater than the builder size, it is treated as the builder size. If the - * length is negative, the empty string is returned. If insufficient characters - * are available in the builder, as much as possible is returned. Thus the - * returned string may be shorter than the length requested. - * - * @param index the index to start at, negative means zero - * @param length the number of characters to extract, negative returns empty - * string - * @return the new string - */ - public String midString(int index, final int length) { - if (index < 0) { - index = 0; - } - if (length <= 0 || index >= size) { - return StringUtils.EMPTY; - } - if (size <= index + length) { - return new String(buffer, index, size - index); - } - return new String(buffer, index, length); + System.arraycopy(buffer, startIndex, destination, destinationIndex, endIndex - startIndex); } // ----------------------------------------------------------------------- /** - * Checks if the string builder contains the specified char. + * Gets the text to be appended when a new line is added. * - * @param ch the character to find - * @return true if the builder contains the character + * @return the new line text, null means use system default */ - public boolean contains(final char ch) { - final char[] thisBuf = buffer; - for (int i = 0; i < this.size; i++) { - if (thisBuf[i] == ch) { - return true; - } + public String getNewLineText() { + return newLine; + } + + // ----------------------------------------------------------------------- + /** + * Gets the text to be appended when null is added. + * + * @return the null text, null means no append + */ + public String getNullText() { + return nullText; + } + + /** + * Gets a suitable hash code for this builder. + * + * @return a hash code + */ + @Override + public int hashCode() { + final char[] buf = buffer; + int hash = 0; + for (int i = size - 1; i >= 0; i--) { + hash = 31 * hash + buf[i]; } - return false; - } - - /** - * Checks if the string builder contains the specified string. - * - * @param str the string to find - * @return true if the builder contains the string - */ - public boolean contains(final String str) { - return indexOf(str, 0) >= 0; - } - - /** - * Checks if the string builder contains a string matched using the specified - * matcher. - *

              - * Matchers can be used to perform advanced searching behavior. For example you - * could write a matcher to search for the character 'a' followed by a number. - * - * @param matcher the matcher to use, null returns -1 - * @return true if the matcher finds a match in the builder - */ - public boolean contains(final StrMatcher matcher) { - return indexOf(matcher, 0) >= 0; + return hash; } // ----------------------------------------------------------------------- @@ -2565,6 +2124,229 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return -1; } + /** + * Inserts the value into this builder. + * + * @param index the index to add at, must be valid + * @param value the value to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(int index, final boolean value) { + validateIndex(index); + if (value) { + ensureCapacity(size + 4); + System.arraycopy(buffer, index, buffer, index + 4, size - index); + buffer[index++] = 't'; + buffer[index++] = 'r'; + buffer[index++] = 'u'; + buffer[index] = 'e'; + size += 4; + } else { + ensureCapacity(size + 5); + System.arraycopy(buffer, index, buffer, index + 5, size - index); + buffer[index++] = 'f'; + buffer[index++] = 'a'; + buffer[index++] = 'l'; + buffer[index++] = 's'; + buffer[index] = 'e'; + size += 5; + } + return this; + } + + /** + * Inserts the value into this builder. + * + * @param index the index to add at, must be valid + * @param value the value to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final char value) { + validateIndex(index); + ensureCapacity(size + 1); + System.arraycopy(buffer, index, buffer, index + 1, size - index); + buffer[index] = value; + size++; + return this; + } + + /** + * Inserts the character array into this builder. Inserting null will use the + * stored null text value. + * + * @param index the index to add at, must be valid + * @param chars the char array to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final char[] chars) { + validateIndex(index); + if (chars == null) { + return insert(index, nullText); + } + final int len = chars.length; + if (len > 0) { + ensureCapacity(size + len); + System.arraycopy(buffer, index, buffer, index + len, size - index); + System.arraycopy(chars, 0, buffer, index, len); + size += len; + } + return this; + } + + /** + * Inserts part of the character array into this builder. Inserting null will + * use the stored null text value. + * + * @param index the index to add at, must be valid + * @param chars the char array to insert + * @param offset the offset into the character array to start at, must be valid + * @param length the length of the character array part to copy, must be + * positive + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if any index is invalid + */ + public StrBuilder insert(final int index, final char[] chars, final int offset, final int length) { + validateIndex(index); + if (chars == null) { + return insert(index, nullText); + } + if (offset < 0 || offset > chars.length) { + throw new StringIndexOutOfBoundsException("Invalid offset: " + offset); + } + if (length < 0 || offset + length > chars.length) { + throw new StringIndexOutOfBoundsException("Invalid length: " + length); + } + if (length > 0) { + ensureCapacity(size + length); + System.arraycopy(buffer, index, buffer, index + length, size - index); + System.arraycopy(chars, offset, buffer, index, length); + size += length; + } + return this; + } + + /** + * Inserts the value into this builder. + * + * @param index the index to add at, must be valid + * @param value the value to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final double value) { + return insert(index, String.valueOf(value)); + } + + /** + * Inserts the value into this builder. + * + * @param index the index to add at, must be valid + * @param value the value to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final float value) { + return insert(index, String.valueOf(value)); + } + + /** + * Inserts the value into this builder. + * + * @param index the index to add at, must be valid + * @param value the value to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final int value) { + return insert(index, String.valueOf(value)); + } + + /** + * Inserts the value into this builder. + * + * @param index the index to add at, must be valid + * @param value the value to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final long value) { + return insert(index, String.valueOf(value)); + } + + // ----------------------------------------------------------------------- + /** + * Inserts the string representation of an object into this builder. Inserting + * null will use the stored null text value. + * + * @param index the index to add at, must be valid + * @param obj the object to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, final Object obj) { + if (obj == null) { + return insert(index, nullText); + } + return insert(index, obj.toString()); + } + + /** + * Inserts the string into this builder. Inserting null will use the stored null + * text value. + * + * @param index the index to add at, must be valid + * @param str the string to insert + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder insert(final int index, String str) { + validateIndex(index); + if (str == null) { + str = nullText; + } + if (str != null) { + final int strLen = str.length(); + if (strLen > 0) { + final int newSize = size + strLen; + ensureCapacity(newSize); + System.arraycopy(buffer, index, buffer, index + strLen, size - index); + size = newSize; + str.getChars(0, strLen, buffer, index); + } + } + return this; + } + + /** + * Checks is the string builder is empty (convenience Collections API style + * method). + *

              + * This method is the same as checking {@link #length()} and is provided to + * match the API of Collections. + * + * @return {@code true} if the size is {@code 0}. + */ + public boolean isEmpty() { + return size == 0; + } + + /** + * Checks is the string builder is not empty (convenience Collections API style + * method). + *

              + * This method is the same as checking {@link #length()} and is provided to + * match the API of Collections. + * + * @return {@code true} if the size is greater than {@code 0}. + * @since 3.12.0 + */ + public boolean isNotEmpty() { + return size > 0; + } + // ----------------------------------------------------------------------- /** * Searches the string builder to find the last reference to the specified char. @@ -2686,199 +2468,577 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return -1; } - // ----------------------------------------------------------------------- /** - * Creates a tokenizer that can tokenize the contents of this builder. + * Extracts the leftmost characters from the string builder without throwing an + * exception. *

              - * This method allows the contents of this builder to be tokenized. The - * tokenizer will be setup by default to tokenize on space, tab, newline and - * formfeed (as per StringTokenizer). These values can be changed on the - * tokenizer class, before retrieving the tokens. - *

              - * The returned tokenizer is linked to this builder. You may intermix calls to - * the builder and tokenizer within certain limits, however there is no - * synchronization. Once the tokenizer has been used once, it must be - * {@link StrTokenizer#reset() reset} to pickup the latest changes in the - * builder. For example: - * - *

              -	 * StrBuilder b = new StrBuilder();
              -	 * b.append("a b ");
              -	 * StrTokenizer t = b.asTokenizer();
              -	 * String[] tokens1 = t.getTokenArray(); // returns a,b
              -	 * b.append("c d ");
              -	 * String[] tokens2 = t.getTokenArray(); // returns a,b (c and d ignored)
              -	 * t.reset(); // reset causes builder changes to be picked up
              -	 * String[] tokens3 = t.getTokenArray(); // returns a,b,c,d
              -	 * 
              - * - * In addition to simply intermixing appends and tokenization, you can also call - * the set methods on the tokenizer to alter how it tokenizes. Just remember to - * call reset when you want to pickup builder changes. - *

              - * Calling {@link StrTokenizer#reset(String)} or - * {@link StrTokenizer#reset(char[])} with a non-null value will break the link - * with the builder. + * This method extracts the left {@code length} characters from the builder. If + * this many characters are not available, the whole builder is returned. Thus + * the returned string may be shorter than the length requested. * - * @return a tokenizer that is linked to this builder + * @param length the number of characters to extract, negative returns empty + * string + * @return the new string */ - public StrTokenizer asTokenizer() { - return new StrBuilderTokenizer(); + public String leftString(final int length) { + if (length <= 0) { + return StringUtils.EMPTY; + } else if (length >= size) { + return new String(buffer, 0, size); + } else { + return new String(buffer, 0, length); + } } // ----------------------------------------------------------------------- /** - * Gets the contents of this builder as a Reader. - *

              - * This method allows the contents of the builder to be read using any standard - * method that expects a Reader. - *

              - * To use, simply create a {@code StrBuilder}, populate it with data, call - * {@code asReader}, and then read away. - *

              - * The internal character array is shared between the builder and the reader. - * This allows you to append to the builder after creating the reader, and the - * changes will be picked up. Note however, that no synchronization occurs, so - * you must perform all operations with the builder and the reader in one - * thread. - *

              - * The returned reader supports marking, and ignores the flush method. + * Gets the length of the string builder. * - * @return a reader that reads from this builder + * @return the length */ - public Reader asReader() { - return new StrBuilderReader(); + @Override + public int length() { + return size; + } + + /** + * Extracts some characters from the middle of the string builder without + * throwing an exception. + *

              + * This method extracts {@code length} characters from the builder at the + * specified index. If the index is negative it is treated as zero. If the index + * is greater than the builder size, it is treated as the builder size. If the + * length is negative, the empty string is returned. If insufficient characters + * are available in the builder, as much as possible is returned. Thus the + * returned string may be shorter than the length requested. + * + * @param index the index to start at, negative means zero + * @param length the number of characters to extract, negative returns empty + * string + * @return the new string + */ + public String midString(int index, final int length) { + if (index < 0) { + index = 0; + } + if (length <= 0 || index >= size) { + return StringUtils.EMPTY; + } + if (size <= index + length) { + return new String(buffer, index, size - index); + } + return new String(buffer, index, length); + } + + /** + * Minimizes the capacity to the actual length of the string. + * + * @return this, to enable chaining + */ + public StrBuilder minimizeCapacity() { + if (buffer.length > length()) { + final char[] old = buffer; + buffer = new char[length()]; + System.arraycopy(old, 0, buffer, 0, size); + } + return this; } // ----------------------------------------------------------------------- /** - * Gets this builder as a Writer that can be written to. - *

              - * This method allows you to populate the contents of the builder using any - * standard method that takes a Writer. - *

              - * To use, simply create a {@code StrBuilder}, call {@code asWriter}, and - * populate away. The data is available at any time using the methods of the - * {@code StrBuilder}. - *

              - * The internal character array is shared between the builder and the writer. - * This allows you to intermix calls that append to the builder and write using - * the writer and the changes will be occur correctly. Note however, that no - * synchronization occurs, so you must perform all operations with the builder - * and the writer in one thread. - *

              - * The returned writer ignores the close and flush methods. + * If possible, reads chars from the provided {@link Readable} directly into + * underlying character buffer without making extra copies. * - * @return a writer that populates this builder - */ - public Writer asWriter() { - return new StrBuilderWriter(); - } - - /** - * Appends current contents of this {@code StrBuilder} to the provided - * {@link Appendable}. - *

              - * This method tries to avoid doing any extra copies of contents. - * - * @param appendable the appendable to append data to - * @throws IOException if an I/O error occurs + * @param readable object to read from + * @return the number of characters read + * @throws IOException if an I/O error occurs. * * @since 3.4 - * @see #readFrom(Readable) + * @see #appendTo(Appendable) */ - public void appendTo(final Appendable appendable) throws IOException { - if (appendable instanceof Writer) { - ((Writer) appendable).write(buffer, 0, size); - } else if (appendable instanceof StringBuilder) { - ((StringBuilder) appendable).append(buffer, 0, size); - } else if (appendable instanceof StringBuffer) { - ((StringBuffer) appendable).append(buffer, 0, size); - } else if (appendable instanceof CharBuffer) { - ((CharBuffer) appendable).put(buffer, 0, size); + public int readFrom(final Readable readable) throws IOException { + final int oldSize = size; + if (readable instanceof Reader) { + final Reader r = (Reader) readable; + ensureCapacity(size + 1); + int read; + while ((read = r.read(buffer, size, buffer.length - size)) != -1) { + size += read; + ensureCapacity(size + 1); + } + } else if (readable instanceof CharBuffer) { + final CharBuffer cb = (CharBuffer) readable; + final int remaining = cb.remaining(); + ensureCapacity(size + remaining); + cb.get(buffer, size, remaining); + size += remaining; } else { - appendable.append(this); - } - } - - /** - * Checks the contents of this builder against another to see if they contain - * the same character content ignoring case. - * - * @param other the object to check, null returns false - * @return true if the builders contain the same characters in the same order - */ - public boolean equalsIgnoreCase(final StrBuilder other) { - if (this == other) { - return true; - } - if (this.size != other.size) { - return false; - } - final char[] thisBuf = this.buffer; - final char[] otherBuf = other.buffer; - for (int i = size - 1; i >= 0; i--) { - final char c1 = thisBuf[i]; - final char c2 = otherBuf[i]; - if (c1 != c2 && Character.toUpperCase(c1) != Character.toUpperCase(c2)) { - return false; + while (true) { + ensureCapacity(size + 1); + final CharBuffer buf = CharBuffer.wrap(buffer, size, buffer.length - size); + final int read = readable.read(buf); + if (read == -1) { + break; + } + size += read; } } - return true; + return size - oldSize; } /** - * Checks the contents of this builder against another to see if they contain - * the same character content. + * Replaces a portion of the string builder with another string. The length of + * the inserted string does not have to match the removed length. * - * @param other the object to check, null returns false - * @return true if the builders contain the same characters in the same order + * @param startIndex the start index, inclusive, must be valid + * @param endIndex the end index, exclusive, must be valid except that if too + * large it is treated as end of string + * @param replaceStr the string to replace with, null means delete range + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid */ - public boolean equals(final StrBuilder other) { - if (this == other) { - return true; - } - if (other == null) { - return false; - } - if (this.size != other.size) { - return false; - } - final char[] thisBuf = this.buffer; - final char[] otherBuf = other.buffer; - for (int i = size - 1; i >= 0; i--) { - if (thisBuf[i] != otherBuf[i]) { - return false; + public StrBuilder replace(final int startIndex, int endIndex, final String replaceStr) { + endIndex = validateRange(startIndex, endIndex); + final int insertLen = (replaceStr == null ? 0 : replaceStr.length()); + replaceImpl(startIndex, endIndex, endIndex - startIndex, replaceStr, insertLen); + return this; + } + + // ----------------------------------------------------------------------- + /** + * Advanced search and replaces within the builder using a matcher. + *

              + * Matchers can be used to perform advanced behavior. For example you could + * write a matcher to delete all occurrences where the character 'a' is followed + * by a number. + * + * @param matcher the matcher to use to find the deletion, null causes no + * action + * @param replaceStr the string to replace the match with, null is a delete + * @param startIndex the start index, inclusive, must be valid + * @param endIndex the end index, exclusive, must be valid except that if + * too large it is treated as end of string + * @param replaceCount the number of times to replace, -1 for replace all + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if start index is invalid + */ + public StrBuilder replace(final StrMatcher matcher, final String replaceStr, final int startIndex, int endIndex, + final int replaceCount) { + endIndex = validateRange(startIndex, endIndex); + return replaceImpl(matcher, replaceStr, startIndex, endIndex, replaceCount); + } + + // ----------------------------------------------------------------------- + /** + * Replaces the search character with the replace character throughout the + * builder. + * + * @param search the search character + * @param replace the replace character + * @return this, to enable chaining + */ + public StrBuilder replaceAll(final char search, final char replace) { + if (search != replace) { + for (int i = 0; i < size; i++) { + if (buffer[i] == search) { + buffer[i] = replace; + } } } - return true; + return this; + } + + // ----------------------------------------------------------------------- + /** + * Replaces the search string with the replace string throughout the builder. + * + * @param searchStr the search string, null causes no action to occur + * @param replaceStr the replace string, null is equivalent to an empty string + * @return this, to enable chaining + */ + public StrBuilder replaceAll(final String searchStr, final String replaceStr) { + final int searchLen = (searchStr == null ? 0 : searchStr.length()); + if (searchLen > 0) { + final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); + int index = indexOf(searchStr, 0); + while (index >= 0) { + replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); + index = indexOf(searchStr, index + replaceLen); + } + } + return this; + } + + // ----------------------------------------------------------------------- + /** + * Replaces all matches within the builder with the replace string. + *

              + * Matchers can be used to perform advanced replace behavior. For example you + * could write a matcher to replace all occurrences where the character 'a' is + * followed by a number. + * + * @param matcher the matcher to use to find the deletion, null causes no + * action + * @param replaceStr the replace string, null is equivalent to an empty string + * @return this, to enable chaining + */ + public StrBuilder replaceAll(final StrMatcher matcher, final String replaceStr) { + return replace(matcher, replaceStr, 0, size, -1); } /** - * Checks the contents of this builder against another to see if they contain - * the same character content. + * Replaces the first instance of the search character with the replace + * character in the builder. * - * @param obj the object to check, null returns false - * @return true if the builders contain the same characters in the same order + * @param search the search character + * @param replace the replace character + * @return this, to enable chaining */ - @Override - public boolean equals(final Object obj) { - return obj instanceof StrBuilder && equals((StrBuilder) obj); + public StrBuilder replaceFirst(final char search, final char replace) { + if (search != replace) { + for (int i = 0; i < size; i++) { + if (buffer[i] == search) { + buffer[i] = replace; + break; + } + } + } + return this; } /** - * Gets a suitable hash code for this builder. + * Replaces the first instance of the search string with the replace string. * - * @return a hash code + * @param searchStr the search string, null causes no action to occur + * @param replaceStr the replace string, null is equivalent to an empty string + * @return this, to enable chaining */ - @Override - public int hashCode() { + public StrBuilder replaceFirst(final String searchStr, final String replaceStr) { + final int searchLen = (searchStr == null ? 0 : searchStr.length()); + if (searchLen > 0) { + final int index = indexOf(searchStr, 0); + if (index >= 0) { + final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); + replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen); + } + } + return this; + } + + /** + * Replaces the first match within the builder with the replace string. + *

              + * Matchers can be used to perform advanced replace behavior. For example you + * could write a matcher to replace where the character 'a' is followed by a + * number. + * + * @param matcher the matcher to use to find the deletion, null causes no + * action + * @param replaceStr the replace string, null is equivalent to an empty string + * @return this, to enable chaining + */ + public StrBuilder replaceFirst(final StrMatcher matcher, final String replaceStr) { + return replace(matcher, replaceStr, 0, size, 1); + } + + // ----------------------------------------------------------------------- + /** + * Internal method to delete a range without validation. + * + * @param startIndex the start index, must be valid + * @param endIndex the end index (exclusive), must be valid + * @param removeLen the length to remove (endIndex - startIndex), must be valid + * @param insertStr the string to replace with, null means delete range + * @param insertLen the length of the insert string, must be valid + * @throws IndexOutOfBoundsException if any index is invalid + */ + private void replaceImpl(final int startIndex, final int endIndex, final int removeLen, final String insertStr, + final int insertLen) { + final int newSize = size - removeLen + insertLen; + if (insertLen != removeLen) { + ensureCapacity(newSize); + System.arraycopy(buffer, endIndex, buffer, startIndex + insertLen, size - endIndex); + size = newSize; + } + if (insertLen > 0) { + insertStr.getChars(0, insertLen, buffer, startIndex); + } + } + + /** + * Replaces within the builder using a matcher. + *

              + * Matchers can be used to perform advanced behavior. For example you could + * write a matcher to delete all occurrences where the character 'a' is followed + * by a number. + * + * @param matcher the matcher to use to find the deletion, null causes no + * action + * @param replaceStr the string to replace the match with, null is a delete + * @param from the start index, must be valid + * @param to the end index (exclusive), must be valid + * @param replaceCount the number of times to replace, -1 for replace all + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if any index is invalid + */ + private StrBuilder replaceImpl(final StrMatcher matcher, final String replaceStr, final int from, int to, + int replaceCount) { + if (matcher == null || size == 0) { + return this; + } + final int replaceLen = (replaceStr == null ? 0 : replaceStr.length()); + for (int i = from; i < to && replaceCount != 0; i++) { + final char[] buf = buffer; + final int removeLen = matcher.isMatch(buf, i, from, to); + if (removeLen > 0) { + replaceImpl(i, i + removeLen, removeLen, replaceStr, replaceLen); + to = to - removeLen + replaceLen; + i = i + replaceLen - 1; + if (replaceCount > 0) { + replaceCount--; + } + } + } + return this; + } + + // ----------------------------------------------------------------------- + /** + * Reverses the string builder placing each character in the opposite index. + * + * @return this, to enable chaining + */ + public StrBuilder reverse() { + if (size == 0) { + return this; + } + + final int half = size / 2; final char[] buf = buffer; - int hash = 0; - for (int i = size - 1; i >= 0; i--) { - hash = 31 * hash + buf[i]; + for (int leftIdx = 0, rightIdx = size - 1; leftIdx < half; leftIdx++, rightIdx--) { + final char swap = buf[leftIdx]; + buf[leftIdx] = buf[rightIdx]; + buf[rightIdx] = swap; } - return hash; + return this; + } + + /** + * Extracts the rightmost characters from the string builder without throwing an + * exception. + *

              + * This method extracts the right {@code length} characters from the builder. If + * this many characters are not available, the whole builder is returned. Thus + * the returned string may be shorter than the length requested. + * + * @param length the number of characters to extract, negative returns empty + * string + * @return the new string + */ + public String rightString(final int length) { + if (length <= 0) { + return StringUtils.EMPTY; + } else if (length >= size) { + return new String(buffer, 0, size); + } else { + return new String(buffer, size - length, length); + } + } + + /** + * Sets the character at the specified index. + * + * @see #charAt(int) + * @see #deleteCharAt(int) + * @param index the index to set + * @param ch the new character + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the index is invalid + */ + public StrBuilder setCharAt(final int index, final char ch) { + if (index < 0 || index >= length()) { + throw new StringIndexOutOfBoundsException(index); + } + buffer[index] = ch; + return this; + } + + /** + * Updates the length of the builder by either dropping the last characters or + * adding filler of Unicode zero. + * + * @param length the length to set to, must be zero or positive + * @return this, to enable chaining + * @throws IndexOutOfBoundsException if the length is negative + */ + public StrBuilder setLength(final int length) { + if (length < 0) { + throw new StringIndexOutOfBoundsException(length); + } + if (length < size) { + size = length; + } else if (length > size) { + ensureCapacity(length); + final int oldEnd = size; + final int newEnd = length; + size = length; + for (int i = oldEnd; i < newEnd; i++) { + buffer[i] = CharUtils.NUL; + } + } + return this; + } + + /** + * Sets the text to be appended when a new line is added. + * + * @param newLine the new line text, null means use system default + * @return this, to enable chaining + */ + public StrBuilder setNewLineText(final String newLine) { + this.newLine = newLine; + return this; + } + + /** + * Sets the text to be appended when null is added. + * + * @param nullText the null text, null means no append + * @return this, to enable chaining + */ + public StrBuilder setNullText(String nullText) { + if (nullText != null && nullText.isEmpty()) { + nullText = null; + } + this.nullText = nullText; + return this; + } + + // ----------------------------------------------------------------------- + /** + * Gets the length of the string builder. + *

              + * This method is the same as {@link #length()} and is provided to match the API + * of Collections. + * + * @return the length + */ + public int size() { + return size; + } + + // ----------------------------------------------------------------------- + /** + * Checks whether this builder starts with the specified string. + *

              + * Note that this method handles null input quietly, unlike String. + * + * @param str the string to search for, null returns false + * @return true if the builder starts with the string + */ + public boolean startsWith(final String str) { + if (str == null) { + return false; + } + final int len = str.length(); + if (len == 0) { + return true; + } + if (len > size) { + return false; + } + for (int i = 0; i < len; i++) { + if (buffer[i] != str.charAt(i)) { + return false; + } + } + return true; + } + + // ----------------------------------------------------------------------- + /** + * {@inheritDoc} + * + * @since 3.0 + */ + @Override + public CharSequence subSequence(final int startIndex, final int endIndex) { + if (startIndex < 0) { + throw new StringIndexOutOfBoundsException(startIndex); + } + if (endIndex > size) { + throw new StringIndexOutOfBoundsException(endIndex); + } + if (startIndex > endIndex) { + throw new StringIndexOutOfBoundsException(endIndex - startIndex); + } + return substring(startIndex, endIndex); + } + + /** + * Extracts a portion of this string builder as a string. + * + * @param start the start index, inclusive, must be valid + * @return the new string + * @throws IndexOutOfBoundsException if the index is invalid + */ + public String substring(final int start) { + return substring(start, size); + } + + /** + * Extracts a portion of this string builder as a string. + *

              + * Note: This method treats an endIndex greater than the length of the builder + * as equal to the length of the builder, and continues without error, unlike + * StringBuffer or String. + * + * @param startIndex the start index, inclusive, must be valid + * @param endIndex the end index, exclusive, must be valid except that if too + * large it is treated as end of string + * @return the new string + * @throws IndexOutOfBoundsException if the index is invalid + */ + public String substring(final int startIndex, int endIndex) { + endIndex = validateRange(startIndex, endIndex); + return new String(buffer, startIndex, endIndex - startIndex); + } + + // ----------------------------------------------------------------------- + /** + * Copies the builder's character array into a new character array. + * + * @return a new array that represents the contents of the builder + */ + public char[] toCharArray() { + if (size == 0) { + return new char[0]; + } + final char[] chars = new char[size]; + System.arraycopy(buffer, 0, chars, 0, size); + return chars; + } + + /** + * Copies part of the builder's character array into a new character array. + * + * @param startIndex the start index, inclusive, must be valid + * @param endIndex the end index, exclusive, must be valid except that if too + * large it is treated as end of string + * @return a new array that holds part of the contents of the builder + * @throws IndexOutOfBoundsException if startIndex is invalid, or if endIndex is + * invalid (but endIndex greater than size is + * valid) + */ + public char[] toCharArray(final int startIndex, int endIndex) { + endIndex = validateRange(startIndex, endIndex); + final int len = endIndex - startIndex; + if (len == 0) { + return new char[0]; + } + final char[] chars = new char[len]; + System.arraycopy(buffer, startIndex, chars, 0, len); + return chars; } // ----------------------------------------------------------------------- @@ -2917,16 +3077,45 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return new StringBuilder(size).append(buffer, 0, size); } + // ----------------------------------------------------------------------- /** - * Implement the {@link Builder} interface. - * - * @return the builder as a String - * @since 3.2 - * @see #toString() + * Trims the builder by removing characters less than or equal to a space from + * the beginning and end. + * + * @return this, to enable chaining */ - @Override - public String build() { - return toString(); + public StrBuilder trim() { + if (size == 0) { + return this; + } + int len = size; + final char[] buf = buffer; + int pos = 0; + while (pos < len && buf[pos] <= ' ') { + pos++; + } + while (pos < len && buf[len - 1] <= ' ') { + len--; + } + if (len < size) { + delete(len, size); + } + if (pos > 0) { + delete(0, pos); + } + return this; + } + + /** + * Validates parameters defining a single index in the builder. + * + * @param index the index, must be valid + * @throws IndexOutOfBoundsException if the index is invalid + */ + protected void validateIndex(final int index) { + if (index < 0 || index > size) { + throw new StringIndexOutOfBoundsException(index); + } } // ----------------------------------------------------------------------- @@ -2952,192 +3141,4 @@ public class StrBuilder implements CharSequence, Appendable, Serializable, Build return endIndex; } - /** - * Validates parameters defining a single index in the builder. - * - * @param index the index, must be valid - * @throws IndexOutOfBoundsException if the index is invalid - */ - protected void validateIndex(final int index) { - if (index < 0 || index > size) { - throw new StringIndexOutOfBoundsException(index); - } - } - - // ----------------------------------------------------------------------- - /** - * Inner class to allow StrBuilder to operate as a tokenizer. - */ - class StrBuilderTokenizer extends StrTokenizer { - - /** - * Default constructor. - */ - StrBuilderTokenizer() { - } - - /** {@inheritDoc} */ - @Override - protected List tokenize(final char[] chars, final int offset, final int count) { - if (chars == null) { - return super.tokenize(StrBuilder.this.buffer, 0, StrBuilder.this.size()); - } - return super.tokenize(chars, offset, count); - } - - /** {@inheritDoc} */ - @Override - public String getContent() { - final String str = super.getContent(); - if (str == null) { - return StrBuilder.this.toString(); - } - return str; - } - } - - // ----------------------------------------------------------------------- - /** - * Inner class to allow StrBuilder to operate as a reader. - */ - class StrBuilderReader extends Reader { - /** The current stream position. */ - private int pos; - /** The last mark position. */ - private int mark; - - /** - * Default constructor. - */ - StrBuilderReader() { - } - - /** {@inheritDoc} */ - @Override - public void close() { - // do nothing - } - - /** {@inheritDoc} */ - @Override - public int read() { - if (ready() == false) { - return -1; - } - return StrBuilder.this.charAt(pos++); - } - - /** {@inheritDoc} */ - @Override - public int read(final char[] b, final int off, int len) { - if (off < 0 || len < 0 || off > b.length || (off + len) > b.length || (off + len) < 0) { - throw new IndexOutOfBoundsException(); - } - if (len == 0) { - return 0; - } - if (pos >= StrBuilder.this.size()) { - return -1; - } - if (pos + len > size()) { - len = StrBuilder.this.size() - pos; - } - StrBuilder.this.getChars(pos, pos + len, b, off); - pos += len; - return len; - } - - /** {@inheritDoc} */ - @Override - public long skip(long n) { - if (pos + n > StrBuilder.this.size()) { - n = StrBuilder.this.size() - pos; - } - if (n < 0) { - return 0; - } - pos += n; - return n; - } - - /** {@inheritDoc} */ - @Override - public boolean ready() { - return pos < StrBuilder.this.size(); - } - - /** {@inheritDoc} */ - @Override - public boolean markSupported() { - return true; - } - - /** {@inheritDoc} */ - @Override - public void mark(final int readAheadLimit) { - mark = pos; - } - - /** {@inheritDoc} */ - @Override - public void reset() { - pos = mark; - } - } - - // ----------------------------------------------------------------------- - /** - * Inner class to allow StrBuilder to operate as a writer. - */ - class StrBuilderWriter extends Writer { - - /** - * Default constructor. - */ - StrBuilderWriter() { - } - - /** {@inheritDoc} */ - @Override - public void close() { - // do nothing - } - - /** {@inheritDoc} */ - @Override - public void flush() { - // do nothing - } - - /** {@inheritDoc} */ - @Override - public void write(final int c) { - StrBuilder.this.append((char) c); - } - - /** {@inheritDoc} */ - @Override - public void write(final char[] cbuf) { - StrBuilder.this.append(cbuf); - } - - /** {@inheritDoc} */ - @Override - public void write(final char[] cbuf, final int off, final int len) { - StrBuilder.this.append(cbuf, off, len); - } - - /** {@inheritDoc} */ - @Override - public void write(final String str) { - StrBuilder.this.append(str); - } - - /** {@inheritDoc} */ - @Override - public void write(final String str, final int off, final int len) { - StrBuilder.this.append(str, off, len); - } - } - } diff --git a/src/main/java/org/apache/commons/lang3/text/StrLookup.java b/src/main/java/org/apache/commons/lang3/text/StrLookup.java index fa69ba26..d389c3cc 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrLookup.java +++ b/src/main/java/org/apache/commons/lang3/text/StrLookup.java @@ -34,95 +34,12 @@ import java.util.Map; * @param Unused. * @since 2.2 * @!deprecated as of 3.6, use commons-text - * StringLookupFactory instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/lookup/StringLookupFactory.html"> + * StringLookupFactory instead */ //@Deprecated public abstract class StrLookup { - /** - * Lookup that always returns null. - */ - private static final StrLookup NONE_LOOKUP = new MapStrLookup<>(null); - - /** - * Lookup based on system properties. - */ - private static final StrLookup SYSTEM_PROPERTIES_LOOKUP = new SystemPropertiesStrLookup(); - - // ----------------------------------------------------------------------- - /** - * Returns a lookup which always returns null. - * - * @return a lookup that always returns null, not null - */ - public static StrLookup noneLookup() { - return NONE_LOOKUP; - } - - /** - * Returns a new lookup which uses a copy of the current - * {@link System#getProperties() System properties}. - *

              - * If a security manager blocked access to system properties, then null will be - * returned from every lookup. - *

              - * If a null key is used, this lookup will throw a NullPointerException. - * - * @return a lookup using system properties, not null - */ - public static StrLookup systemPropertiesLookup() { - return SYSTEM_PROPERTIES_LOOKUP; - } - - /** - * Returns a lookup which looks up values using a map. - *

              - * If the map is null, then null will be returned from every lookup. The map - * result object is converted to a string using toString(). - * - * @param the type of the values supported by the lookup - * @param map the map of keys to values, may be null - * @return a lookup using the map, not null - */ - public static StrLookup mapLookup(final Map map) { - return new MapStrLookup<>(map); - } - - // ----------------------------------------------------------------------- - /** - * Constructor. - */ - protected StrLookup() { - } - - /** - * Looks up a String key to a String value. - *

              - * The internal implementation may use any mechanism to return the value. The - * simplest implementation is to use a Map. However, virtually any - * implementation is possible. - *

              - * For example, it would be possible to implement a lookup that used the key as - * a primary key, and looked up the value on demand from the database Or, a - * numeric based implementation could be created that treats the key as an - * integer, increments the value and return the result as a string - converting - * 1 to 2, 15 to 16 etc. - *

              - * The {@link #lookup(String)} method always returns a String, regardless of the - * underlying data, by converting it as necessary. For example: - * - *

              -	 * Map<String, Object> map = new HashMap<String, Object>();
              -	 * map.put("number", Integer.valueOf(2));
              -	 * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
              -	 * 
              - * - * @param key the key to be looked up, may be null - * @return the matching value, null if no match - */ - public abstract String lookup(String key); - // ----------------------------------------------------------------------- /** * Lookup implementation that uses a Map. @@ -183,4 +100,87 @@ public abstract class StrLookup { return null; } } + + /** + * Lookup that always returns null. + */ + private static final StrLookup NONE_LOOKUP = new MapStrLookup<>(null); + + /** + * Lookup based on system properties. + */ + private static final StrLookup SYSTEM_PROPERTIES_LOOKUP = new SystemPropertiesStrLookup(); + + /** + * Returns a lookup which looks up values using a map. + *

              + * If the map is null, then null will be returned from every lookup. The map + * result object is converted to a string using toString(). + * + * @param the type of the values supported by the lookup + * @param map the map of keys to values, may be null + * @return a lookup using the map, not null + */ + public static StrLookup mapLookup(final Map map) { + return new MapStrLookup<>(map); + } + + // ----------------------------------------------------------------------- + /** + * Returns a lookup which always returns null. + * + * @return a lookup that always returns null, not null + */ + public static StrLookup noneLookup() { + return NONE_LOOKUP; + } + + /** + * Returns a new lookup which uses a copy of the current + * {@link System#getProperties() System properties}. + *

              + * If a security manager blocked access to system properties, then null will be + * returned from every lookup. + *

              + * If a null key is used, this lookup will throw a NullPointerException. + * + * @return a lookup using system properties, not null + */ + public static StrLookup systemPropertiesLookup() { + return SYSTEM_PROPERTIES_LOOKUP; + } + + // ----------------------------------------------------------------------- + /** + * Constructor. + */ + protected StrLookup() { + } + + /** + * Looks up a String key to a String value. + *

              + * The internal implementation may use any mechanism to return the value. The + * simplest implementation is to use a Map. However, virtually any + * implementation is possible. + *

              + * For example, it would be possible to implement a lookup that used the key as + * a primary key, and looked up the value on demand from the database Or, a + * numeric based implementation could be created that treats the key as an + * integer, increments the value and return the result as a string - converting + * 1 to 2, 15 to 16 etc. + *

              + * The {@link #lookup(String)} method always returns a String, regardless of the + * underlying data, by converting it as necessary. For example: + * + *

              +	 * Map<String, Object> map = new HashMap<String, Object>();
              +	 * map.put("number", Integer.valueOf(2));
              +	 * assertEquals("2", StrLookup.mapLookup(map).lookup("number"));
              +	 * 
              + * + * @param key the key to be looked up, may be null + * @return the matching value, null if no match + */ + public abstract String lookup(String key); } diff --git a/src/main/java/org/apache/commons/lang3/text/StrMatcher.java b/src/main/java/org/apache/commons/lang3/text/StrMatcher.java index 80661d53..47aadeb1 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrMatcher.java +++ b/src/main/java/org/apache/commons/lang3/text/StrMatcher.java @@ -30,245 +30,42 @@ import org.apache.commons.lang3.StringUtils; * * @since 2.2 * @!deprecated as of 3.6, use commons-text - * StringMatcherFactory instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/matcher/StringMatcherFactory.html"> + * StringMatcherFactory instead */ //@Deprecated public abstract class StrMatcher { - /** - * Matches the comma character. - */ - private static final StrMatcher COMMA_MATCHER = new CharMatcher(','); - /** - * Matches the tab character. - */ - private static final StrMatcher TAB_MATCHER = new CharMatcher('\t'); - /** - * Matches the space character. - */ - private static final StrMatcher SPACE_MATCHER = new CharMatcher(' '); - /** - * Matches the same characters as StringTokenizer, namely space, tab, newline, - * formfeed. - */ - private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray()); - /** - * Matches the String trim() whitespace characters. - */ - private static final StrMatcher TRIM_MATCHER = new TrimMatcher(); - /** - * Matches the double quote character. - */ - private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\''); - /** - * Matches the double quote character. - */ - private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"'); - /** - * Matches the single or double quote character. - */ - private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray()); - /** - * Matches no characters. - */ - private static final StrMatcher NONE_MATCHER = new NoMatcher(); - - // ----------------------------------------------------------------------- - - /** - * Returns a matcher which matches the comma character. - * - * @return a matcher for a comma - */ - public static StrMatcher commaMatcher() { - return COMMA_MATCHER; - } - - /** - * Returns a matcher which matches the tab character. - * - * @return a matcher for a tab - */ - public static StrMatcher tabMatcher() { - return TAB_MATCHER; - } - - /** - * Returns a matcher which matches the space character. - * - * @return a matcher for a space - */ - public static StrMatcher spaceMatcher() { - return SPACE_MATCHER; - } - - /** - * Matches the same characters as StringTokenizer, namely space, tab, newline - * and formfeed. - * - * @return the split matcher - */ - public static StrMatcher splitMatcher() { - return SPLIT_MATCHER; - } - - /** - * Matches the String trim() whitespace characters. - * - * @return the trim matcher - */ - public static StrMatcher trimMatcher() { - return TRIM_MATCHER; - } - - /** - * Returns a matcher which matches the single quote character. - * - * @return a matcher for a single quote - */ - public static StrMatcher singleQuoteMatcher() { - return SINGLE_QUOTE_MATCHER; - } - - /** - * Returns a matcher which matches the double quote character. - * - * @return a matcher for a double quote - */ - public static StrMatcher doubleQuoteMatcher() { - return DOUBLE_QUOTE_MATCHER; - } - - /** - * Returns a matcher which matches the single or double quote character. - * - * @return a matcher for a single or double quote - */ - public static StrMatcher quoteMatcher() { - return QUOTE_MATCHER; - } - - /** - * Matches no characters. - * - * @return a matcher that matches nothing - */ - public static StrMatcher noneMatcher() { - return NONE_MATCHER; - } - - /** - * Constructor that creates a matcher from a character. - * - * @param ch the character to match, must not be null - * @return a new Matcher for the given char - */ - public static StrMatcher charMatcher(final char ch) { - return new CharMatcher(ch); - } - - /** - * Constructor that creates a matcher from a set of characters. - * - * @param chars the characters to match, null or empty matches nothing - * @return a new matcher for the given char[] - */ - public static StrMatcher charSetMatcher(final char... chars) { - if (chars == null || chars.length == 0) { - return NONE_MATCHER; - } - if (chars.length == 1) { - return new CharMatcher(chars[0]); - } - return new CharSetMatcher(chars); - } - - /** - * Constructor that creates a matcher from a string representing a set of - * characters. - * - * @param chars the characters to match, null or empty matches nothing - * @return a new Matcher for the given characters - */ - public static StrMatcher charSetMatcher(final String chars) { - if (StringUtils.isEmpty(chars)) { - return NONE_MATCHER; - } - if (chars.length() == 1) { - return new CharMatcher(chars.charAt(0)); - } - return new CharSetMatcher(chars.toCharArray()); - } - - /** - * Constructor that creates a matcher from a string. - * - * @param str the string to match, null or empty matches nothing - * @return a new Matcher for the given String - */ - public static StrMatcher stringMatcher(final String str) { - if (StringUtils.isEmpty(str)) { - return NONE_MATCHER; - } - return new StringMatcher(str); - } - // ----------------------------------------------------------------------- /** - * Constructor. + * Class used to define a character for matching purposes. */ - protected StrMatcher() { - } + static final class CharMatcher extends StrMatcher { + /** The character to match. */ + private final char ch; - /** - * Returns the number of matching characters, zero for no match. - *

              - * This method is called to check for a match. The parameter {@code pos} - * represents the current position to be checked in the string {@code buffer} (a - * character array which must not be changed). The API guarantees that - * {@code pos} is a valid index for {@code buffer}. - *

              - * The character array may be larger than the active area to be matched. Only - * values in the buffer between the specified indices may be accessed. - *

              - * The matching code may check one character or many. It may check characters - * preceding {@code pos} as well as those after, so long as no checks exceed the - * bounds specified. - *

              - * It must return zero for no match, or a positive number if a match was found. - * The number indicates the number of characters that matched. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index (exclusive) of the active buffer, valid for - * buffer - * @return the number of matching characters, zero for no match - */ - public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd); + /** + * Constructor that creates a matcher that matches a single character. + * + * @param ch the character to match + */ + CharMatcher(final char ch) { + this.ch = ch; + } - /** - * Returns the number of matching characters, zero for no match. - *

              - * This method is called to check for a match. The parameter {@code pos} - * represents the current position to be checked in the string {@code buffer} (a - * character array which must not be changed). The API guarantees that - * {@code pos} is a valid index for {@code buffer}. - *

              - * The matching code may check one character or many. It may check characters - * preceding {@code pos} as well as those after. - *

              - * It must return zero for no match, or a positive number if a match was found. - * The number indicates the number of characters that matched. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @return the number of matching characters, zero for no match - * @since 2.4 - */ - public int isMatch(final char[] buffer, final int pos) { - return isMatch(buffer, pos, 0, buffer.length); + /** + * Returns whether or not the given character matches. + * + * @param buffer the text content to match against, do not change + * @param pos the starting position for the match, valid for buffer + * @param bufferStart the first active index in the buffer, valid for buffer + * @param bufferEnd the end index of the active buffer, valid for buffer + * @return the number of matching characters, zero for no match + */ + @Override + public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) { + return ch == buffer[pos] ? 1 : 0; + } } // ----------------------------------------------------------------------- @@ -305,23 +102,18 @@ public abstract class StrMatcher { // ----------------------------------------------------------------------- /** - * Class used to define a character for matching purposes. + * Class used to match no characters. */ - static final class CharMatcher extends StrMatcher { - /** The character to match. */ - private final char ch; + static final class NoMatcher extends StrMatcher { /** - * Constructor that creates a matcher that matches a single character. - * - * @param ch the character to match + * Constructs a new instance of {@code NoMatcher}. */ - CharMatcher(final char ch) { - this.ch = ch; + NoMatcher() { } /** - * Returns whether or not the given character matches. + * Always returns {@code false}. * * @param buffer the text content to match against, do not change * @param pos the starting position for the match, valid for buffer @@ -331,7 +123,7 @@ public abstract class StrMatcher { */ @Override public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) { - return ch == buffer[pos] ? 1 : 0; + return 0; } } @@ -382,33 +174,6 @@ public abstract class StrMatcher { } - // ----------------------------------------------------------------------- - /** - * Class used to match no characters. - */ - static final class NoMatcher extends StrMatcher { - - /** - * Constructs a new instance of {@code NoMatcher}. - */ - NoMatcher() { - } - - /** - * Always returns {@code false}. - * - * @param buffer the text content to match against, do not change - * @param pos the starting position for the match, valid for buffer - * @param bufferStart the first active index in the buffer, valid for buffer - * @param bufferEnd the end index of the active buffer, valid for buffer - * @return the number of matching characters, zero for no match - */ - @Override - public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) { - return 0; - } - } - // ----------------------------------------------------------------------- /** * Class used to match whitespace as per trim(). @@ -436,4 +201,244 @@ public abstract class StrMatcher { } } + /** + * Matches the comma character. + */ + private static final StrMatcher COMMA_MATCHER = new CharMatcher(','); + /** + * Matches the tab character. + */ + private static final StrMatcher TAB_MATCHER = new CharMatcher('\t'); + /** + * Matches the space character. + */ + private static final StrMatcher SPACE_MATCHER = new CharMatcher(' '); + /** + * Matches the same characters as StringTokenizer, namely space, tab, newline, + * formfeed. + */ + private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray()); + + // ----------------------------------------------------------------------- + + /** + * Matches the String trim() whitespace characters. + */ + private static final StrMatcher TRIM_MATCHER = new TrimMatcher(); + + /** + * Matches the double quote character. + */ + private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\''); + + /** + * Matches the double quote character. + */ + private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"'); + + /** + * Matches the single or double quote character. + */ + private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray()); + + /** + * Matches no characters. + */ + private static final StrMatcher NONE_MATCHER = new NoMatcher(); + + /** + * Constructor that creates a matcher from a character. + * + * @param ch the character to match, must not be null + * @return a new Matcher for the given char + */ + public static StrMatcher charMatcher(final char ch) { + return new CharMatcher(ch); + } + + /** + * Constructor that creates a matcher from a set of characters. + * + * @param chars the characters to match, null or empty matches nothing + * @return a new matcher for the given char[] + */ + public static StrMatcher charSetMatcher(final char... chars) { + if (chars == null || chars.length == 0) { + return NONE_MATCHER; + } + if (chars.length == 1) { + return new CharMatcher(chars[0]); + } + return new CharSetMatcher(chars); + } + + /** + * Constructor that creates a matcher from a string representing a set of + * characters. + * + * @param chars the characters to match, null or empty matches nothing + * @return a new Matcher for the given characters + */ + public static StrMatcher charSetMatcher(final String chars) { + if (StringUtils.isEmpty(chars)) { + return NONE_MATCHER; + } + if (chars.length() == 1) { + return new CharMatcher(chars.charAt(0)); + } + return new CharSetMatcher(chars.toCharArray()); + } + + /** + * Returns a matcher which matches the comma character. + * + * @return a matcher for a comma + */ + public static StrMatcher commaMatcher() { + return COMMA_MATCHER; + } + + /** + * Returns a matcher which matches the double quote character. + * + * @return a matcher for a double quote + */ + public static StrMatcher doubleQuoteMatcher() { + return DOUBLE_QUOTE_MATCHER; + } + + /** + * Matches no characters. + * + * @return a matcher that matches nothing + */ + public static StrMatcher noneMatcher() { + return NONE_MATCHER; + } + + /** + * Returns a matcher which matches the single or double quote character. + * + * @return a matcher for a single or double quote + */ + public static StrMatcher quoteMatcher() { + return QUOTE_MATCHER; + } + + /** + * Returns a matcher which matches the single quote character. + * + * @return a matcher for a single quote + */ + public static StrMatcher singleQuoteMatcher() { + return SINGLE_QUOTE_MATCHER; + } + + /** + * Returns a matcher which matches the space character. + * + * @return a matcher for a space + */ + public static StrMatcher spaceMatcher() { + return SPACE_MATCHER; + } + + /** + * Matches the same characters as StringTokenizer, namely space, tab, newline + * and formfeed. + * + * @return the split matcher + */ + public static StrMatcher splitMatcher() { + return SPLIT_MATCHER; + } + + /** + * Constructor that creates a matcher from a string. + * + * @param str the string to match, null or empty matches nothing + * @return a new Matcher for the given String + */ + public static StrMatcher stringMatcher(final String str) { + if (StringUtils.isEmpty(str)) { + return NONE_MATCHER; + } + return new StringMatcher(str); + } + + /** + * Returns a matcher which matches the tab character. + * + * @return a matcher for a tab + */ + public static StrMatcher tabMatcher() { + return TAB_MATCHER; + } + + /** + * Matches the String trim() whitespace characters. + * + * @return the trim matcher + */ + public static StrMatcher trimMatcher() { + return TRIM_MATCHER; + } + + // ----------------------------------------------------------------------- + /** + * Constructor. + */ + protected StrMatcher() { + } + + /** + * Returns the number of matching characters, zero for no match. + *

              + * This method is called to check for a match. The parameter {@code pos} + * represents the current position to be checked in the string {@code buffer} (a + * character array which must not be changed). The API guarantees that + * {@code pos} is a valid index for {@code buffer}. + *

              + * The matching code may check one character or many. It may check characters + * preceding {@code pos} as well as those after. + *

              + * It must return zero for no match, or a positive number if a match was found. + * The number indicates the number of characters that matched. + * + * @param buffer the text content to match against, do not change + * @param pos the starting position for the match, valid for buffer + * @return the number of matching characters, zero for no match + * @since 2.4 + */ + public int isMatch(final char[] buffer, final int pos) { + return isMatch(buffer, pos, 0, buffer.length); + } + + /** + * Returns the number of matching characters, zero for no match. + *

              + * This method is called to check for a match. The parameter {@code pos} + * represents the current position to be checked in the string {@code buffer} (a + * character array which must not be changed). The API guarantees that + * {@code pos} is a valid index for {@code buffer}. + *

              + * The character array may be larger than the active area to be matched. Only + * values in the buffer between the specified indices may be accessed. + *

              + * The matching code may check one character or many. It may check characters + * preceding {@code pos} as well as those after, so long as no checks exceed the + * bounds specified. + *

              + * It must return zero for no match, or a positive number if a match was found. + * The number indicates the number of characters that matched. + * + * @param buffer the text content to match against, do not change + * @param pos the starting position for the match, valid for buffer + * @param bufferStart the first active index in the buffer, valid for buffer + * @param bufferEnd the end index (exclusive) of the active buffer, valid for + * buffer + * @return the number of matching characters, zero for no match + */ + public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd); + } diff --git a/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java b/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java index eb8a943b..6328957b 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java +++ b/src/main/java/org/apache/commons/lang3/text/StrSubstitutor.java @@ -144,8 +144,8 @@ import org.apache.commons.lang3.StringUtils; * * @since 2.2 * @!deprecated as of 3.6, use commons-text - * StringSubstitutor instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html"> + * StringSubstitutor instead */ //@Deprecated public class StrSubstitutor { @@ -169,35 +169,6 @@ public class StrSubstitutor { */ public static final StrMatcher DEFAULT_VALUE_DELIMITER = StrMatcher.stringMatcher(":-"); - /** - * Stores the escape character. - */ - private char escapeChar; - /** - * Stores the variable prefix. - */ - private StrMatcher prefixMatcher; - /** - * Stores the variable suffix. - */ - private StrMatcher suffixMatcher; - /** - * Stores the default variable value delimiter - */ - private StrMatcher valueDelimiterMatcher; - /** - * Variable resolution is delegated to an implementor of VariableResolver. - */ - private StrLookup variableResolver; - /** - * The flag whether substitution in variable names is enabled. - */ - private boolean enableSubstitutionInVariables; - /** - * Whether escapes should be preserved. Default is false; - */ - private boolean preserveEscapes; - // ----------------------------------------------------------------------- /** * Replaces all the occurrences of variables in the given source object with @@ -267,6 +238,39 @@ public class StrSubstitutor { return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source); } + /** + * Stores the escape character. + */ + private char escapeChar; + /** + * Stores the variable prefix. + */ + private StrMatcher prefixMatcher; + /** + * Stores the variable suffix. + */ + private StrMatcher suffixMatcher; + + /** + * Stores the default variable value delimiter + */ + private StrMatcher valueDelimiterMatcher; + + /** + * Variable resolution is delegated to an implementor of VariableResolver. + */ + private StrLookup variableResolver; + + /** + * The flag whether substitution in variable names is enabled. + */ + private boolean enableSubstitutionInVariables; + + /** + * Whether escapes should be preserved. Default is false; + */ + private boolean preserveEscapes; + // ----------------------------------------------------------------------- /** * Creates a new instance with defaults for variable prefix and suffix and the @@ -415,46 +419,116 @@ public class StrSubstitutor { this.setValueDelimiterMatcher(valueDelimiterMatcher); } + /** + * Checks if the specified variable is already in the stack (list) of variables. + * + * @param varName the variable name to check + * @param priorVariables the list of prior variables + */ + private void checkCyclicSubstitution(final String varName, final List priorVariables) { + if (priorVariables.contains(varName) == false) { + return; + } + final StrBuilder buf = new StrBuilder(256); + buf.append("Infinite loop in property interpolation of "); + buf.append(priorVariables.remove(0)); + buf.append(": "); + buf.appendWithSeparators(priorVariables, "->"); + throw new IllegalStateException(buf.toString()); + } + + // Escape // ----------------------------------------------------------------------- /** - * Replaces all the occurrences of variables with their matching values from the - * resolver using the given source string as a template. + * Returns the escape character. * - * @param source the string to replace in, null returns null - * @return the result of the replace operation + * @return the character used for escaping variable references */ - public String replace(final String source) { - if (source == null) { - return null; - } - final StrBuilder buf = new StrBuilder(source); - if (substitute(buf, 0, source.length()) == false) { - return source; - } - return buf.toString(); + public char getEscapeChar() { + return this.escapeChar; + } + + // Variable Default Value Delimiter + // ----------------------------------------------------------------------- + /** + * Gets the variable default value delimiter matcher currently in use. + *

              + * The variable default value delimiter is the character or characters that + * delimit the variable name and the variable default value. This delimiter is + * expressed in terms of a matcher allowing advanced variable default value + * delimiter matches. + *

              + * If it returns null, then the variable default value resolution is disabled. + * + * @return the variable default value delimiter matcher in use, may be null + * @since 3.2 + */ + public StrMatcher getValueDelimiterMatcher() { + return valueDelimiterMatcher; + } + + // Prefix + // ----------------------------------------------------------------------- + /** + * Gets the variable prefix matcher currently in use. + *

              + * The variable prefix is the character or characters that identify the start of + * a variable. This prefix is expressed in terms of a matcher allowing advanced + * prefix matches. + * + * @return the prefix matcher in use + */ + public StrMatcher getVariablePrefixMatcher() { + return prefixMatcher; + } + + // Resolver + // ----------------------------------------------------------------------- + /** + * Gets the VariableResolver that is used to lookup variables. + * + * @return the VariableResolver + */ + public StrLookup getVariableResolver() { + return this.variableResolver; + } + + // Suffix + // ----------------------------------------------------------------------- + /** + * Gets the variable suffix matcher currently in use. + *

              + * The variable suffix is the character or characters that identify the end of a + * variable. This suffix is expressed in terms of a matcher allowing advanced + * suffix matches. + * + * @return the suffix matcher in use + */ + public StrMatcher getVariableSuffixMatcher() { + return suffixMatcher; + } + + // Substitution support in variable names + // ----------------------------------------------------------------------- + /** + * Returns a flag whether substitution is done in variable names. + * + * @return the substitution in variable names flag + * @since 3.0 + */ + public boolean isEnableSubstitutionInVariables() { + return enableSubstitutionInVariables; } /** - * Replaces all the occurrences of variables with their matching values from the - * resolver using the given source string as a template. - *

              - * Only the specified portion of the string will be processed. The rest of the - * string is not processed, and is not returned. + * Returns the flag controlling whether escapes are preserved during + * substitution. * - * @param source the string to replace in, null returns null - * @param offset the start offset within the array, must be valid - * @param length the length within the array to be processed, must be valid - * @return the result of the replace operation + * @return the preserve escape flag + * @since 3.5 */ - public String replace(final String source, final int offset, final int length) { - if (source == null) { - return null; - } - final StrBuilder buf = new StrBuilder(length).append(source, offset, length); - if (substitute(buf, 0, length) == false) { - return source.substring(offset, offset + length); - } - return buf.toString(); + public boolean isPreserveEscapes() { + return preserveEscapes; } // ----------------------------------------------------------------------- @@ -499,46 +573,6 @@ public class StrSubstitutor { return buf.toString(); } - // ----------------------------------------------------------------------- - /** - * Replaces all the occurrences of variables with their matching values from the - * resolver using the given source buffer as a template. The buffer is not - * altered by this method. - * - * @param source the buffer to use as a template, not changed, null returns null - * @return the result of the replace operation - */ - public String replace(final StringBuffer source) { - if (source == null) { - return null; - } - final StrBuilder buf = new StrBuilder(source.length()).append(source); - substitute(buf, 0, buf.length()); - return buf.toString(); - } - - /** - * Replaces all the occurrences of variables with their matching values from the - * resolver using the given source buffer as a template. The buffer is not - * altered by this method. - *

              - * Only the specified portion of the buffer will be processed. The rest of the - * buffer is not processed, and is not returned. - * - * @param source the buffer to use as a template, not changed, null returns null - * @param offset the start offset within the array, must be valid - * @param length the length within the array to be processed, must be valid - * @return the result of the replace operation - */ - public String replace(final StringBuffer source, final int offset, final int length) { - if (source == null) { - return null; - } - final StrBuilder buf = new StrBuilder(length).append(source, offset, length); - substitute(buf, 0, length); - return buf.toString(); - } - /** * Replaces all the occurrences of variables with their matching values from the * resolver using the given source as a template. The source is not altered by @@ -578,6 +612,24 @@ public class StrSubstitutor { return buf.toString(); } + // ----------------------------------------------------------------------- + /** + * Replaces all the occurrences of variables in the given source object with + * their matching values from the resolver. The input source object is converted + * to a string using {@code toString} and is not altered. + * + * @param source the source to replace in, null returns null + * @return the result of the replace operation + */ + public String replace(final Object source) { + if (source == null) { + return null; + } + final StrBuilder buf = new StrBuilder().append(source); + substitute(buf, 0, buf.length()); + return buf.toString(); + } + // ----------------------------------------------------------------------- /** * Replaces all the occurrences of variables with their matching values from the @@ -622,22 +674,120 @@ public class StrSubstitutor { // ----------------------------------------------------------------------- /** - * Replaces all the occurrences of variables in the given source object with - * their matching values from the resolver. The input source object is converted - * to a string using {@code toString} and is not altered. + * Replaces all the occurrences of variables with their matching values from the + * resolver using the given source string as a template. * - * @param source the source to replace in, null returns null + * @param source the string to replace in, null returns null * @return the result of the replace operation */ - public String replace(final Object source) { + public String replace(final String source) { if (source == null) { return null; } - final StrBuilder buf = new StrBuilder().append(source); + final StrBuilder buf = new StrBuilder(source); + if (substitute(buf, 0, source.length()) == false) { + return source; + } + return buf.toString(); + } + + /** + * Replaces all the occurrences of variables with their matching values from the + * resolver using the given source string as a template. + *

              + * Only the specified portion of the string will be processed. The rest of the + * string is not processed, and is not returned. + * + * @param source the string to replace in, null returns null + * @param offset the start offset within the array, must be valid + * @param length the length within the array to be processed, must be valid + * @return the result of the replace operation + */ + public String replace(final String source, final int offset, final int length) { + if (source == null) { + return null; + } + final StrBuilder buf = new StrBuilder(length).append(source, offset, length); + if (substitute(buf, 0, length) == false) { + return source.substring(offset, offset + length); + } + return buf.toString(); + } + + // ----------------------------------------------------------------------- + /** + * Replaces all the occurrences of variables with their matching values from the + * resolver using the given source buffer as a template. The buffer is not + * altered by this method. + * + * @param source the buffer to use as a template, not changed, null returns null + * @return the result of the replace operation + */ + public String replace(final StringBuffer source) { + if (source == null) { + return null; + } + final StrBuilder buf = new StrBuilder(source.length()).append(source); substitute(buf, 0, buf.length()); return buf.toString(); } + /** + * Replaces all the occurrences of variables with their matching values from the + * resolver using the given source buffer as a template. The buffer is not + * altered by this method. + *

              + * Only the specified portion of the buffer will be processed. The rest of the + * buffer is not processed, and is not returned. + * + * @param source the buffer to use as a template, not changed, null returns null + * @param offset the start offset within the array, must be valid + * @param length the length within the array to be processed, must be valid + * @return the result of the replace operation + */ + public String replace(final StringBuffer source, final int offset, final int length) { + if (source == null) { + return null; + } + final StrBuilder buf = new StrBuilder(length).append(source, offset, length); + substitute(buf, 0, length); + return buf.toString(); + } + + // ----------------------------------------------------------------------- + /** + * Replaces all the occurrences of variables within the given source builder + * with their matching values from the resolver. + * + * @param source the builder to replace in, updated, null returns zero + * @return true if altered + */ + public boolean replaceIn(final StrBuilder source) { + if (source == null) { + return false; + } + return substitute(source, 0, source.length()); + } + + /** + * Replaces all the occurrences of variables within the given source builder + * with their matching values from the resolver. + *

              + * Only the specified portion of the builder will be processed. The rest of the + * builder is not processed, but it is not deleted. + * + * @param source the builder to replace in, null returns zero + * @param offset the start offset within the array, must be valid + * @param length the length within the builder to be processed, must be valid + * @return true if altered + */ + public boolean replaceIn(final StrBuilder source, final int offset, final int length) { + if (source == null) { + return false; + } + return substitute(source, offset, length); + } + // ----------------------------------------------------------------------- /** * Replaces all the occurrences of variables within the given source buffer with @@ -722,38 +872,236 @@ public class StrSubstitutor { return true; } - // ----------------------------------------------------------------------- /** - * Replaces all the occurrences of variables within the given source builder - * with their matching values from the resolver. + * Internal method that resolves the value of a variable. + *

              + * Most users of this class do not need to call this method. This method is + * called automatically by the substitution process. + *

              + * Writers of subclasses can override this method if they need to alter how each + * substitution occurs. The method is passed the variable's name and must return + * the corresponding value. This implementation uses the + * {@link #getVariableResolver()} with the variable's name as the key. * - * @param source the builder to replace in, updated, null returns zero - * @return true if altered + * @param variableName the name of the variable, not null + * @param buf the buffer where the substitution is occurring, not null + * @param startPos the start position of the variable including the prefix, + * valid + * @param endPos the end position of the variable including the suffix, + * valid + * @return the variable's value or null if the variable is unknown */ - public boolean replaceIn(final StrBuilder source) { - if (source == null) { - return false; + protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos, + final int endPos) { + final StrLookup resolver = getVariableResolver(); + if (resolver == null) { + return null; } - return substitute(source, 0, source.length()); + return resolver.lookup(variableName); } /** - * Replaces all the occurrences of variables within the given source builder - * with their matching values from the resolver. - *

              - * Only the specified portion of the builder will be processed. The rest of the - * builder is not processed, but it is not deleted. + * Sets a flag whether substitution is done in variable names. If set to + * true, the names of variables can contain other variables which are + * processed first before the original variable is evaluated, e.g. + * {@code ${jre-${java.version}}}. The default value is false. * - * @param source the builder to replace in, null returns zero - * @param offset the start offset within the array, must be valid - * @param length the length within the builder to be processed, must be valid - * @return true if altered + * @param enableSubstitutionInVariables the new value of the flag + * @since 3.0 */ - public boolean replaceIn(final StrBuilder source, final int offset, final int length) { - if (source == null) { - return false; + public void setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) { + this.enableSubstitutionInVariables = enableSubstitutionInVariables; + } + + /** + * Sets the escape character. If this character is placed before a variable + * reference in the source text, this variable will be ignored. + * + * @param escapeCharacter the escape character (0 for disabling escaping) + */ + public void setEscapeChar(final char escapeCharacter) { + this.escapeChar = escapeCharacter; + } + + /** + * Sets a flag controlling whether escapes are preserved during substitution. If + * set to true, the escape character is retained during substitution + * (e.g. {@code $${this-is-escaped}} remains {@code $${this-is-escaped}}). If + * set to false, the escape character is removed during substitution + * (e.g. {@code $${this-is-escaped}} becomes {@code ${this-is-escaped}}). The + * default value is false + * + * @param preserveEscapes true if escapes are to be preserved + * @since 3.5 + */ + public void setPreserveEscapes(final boolean preserveEscapes) { + this.preserveEscapes = preserveEscapes; + } + + /** + * Sets the variable default value delimiter to use. + *

              + * The variable default value delimiter is the character or characters that + * delimit the variable name and the variable default value. This method allows + * a single character variable default value delimiter to be easily set. + * + * @param valueDelimiter the variable default value delimiter character to use + * @return this, to enable chaining + * @since 3.2 + */ + public StrSubstitutor setValueDelimiter(final char valueDelimiter) { + return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter)); + } + + /** + * Sets the variable default value delimiter to use. + *

              + * The variable default value delimiter is the character or characters that + * delimit the variable name and the variable default value. This method allows + * a string variable default value delimiter to be easily set. + *

              + * If the {@code valueDelimiter} is null or empty string, then the variable + * default value resolution becomes disabled. + * + * @param valueDelimiter the variable default value delimiter string to use, may + * be null or empty + * @return this, to enable chaining + * @since 3.2 + */ + public StrSubstitutor setValueDelimiter(final String valueDelimiter) { + if (StringUtils.isEmpty(valueDelimiter)) { + setValueDelimiterMatcher(null); + return this; } - return substitute(source, offset, length); + return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter)); + } + + /** + * Sets the variable default value delimiter matcher to use. + *

              + * The variable default value delimiter is the character or characters that + * delimit the variable name and the variable default value. This delimiter is + * expressed in terms of a matcher allowing advanced variable default value + * delimiter matches. + *

              + * If the {@code valueDelimiterMatcher} is null, then the variable default value + * resolution becomes disabled. + * + * @param valueDelimiterMatcher variable default value delimiter matcher to use, + * may be null + * @return this, to enable chaining + * @since 3.2 + */ + public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) { + this.valueDelimiterMatcher = valueDelimiterMatcher; + return this; + } + + /** + * Sets the variable prefix to use. + *

              + * The variable prefix is the character or characters that identify the start of + * a variable. This method allows a single character prefix to be easily set. + * + * @param prefix the prefix character to use + * @return this, to enable chaining + */ + public StrSubstitutor setVariablePrefix(final char prefix) { + return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix)); + } + + /** + * Sets the variable prefix to use. + *

              + * The variable prefix is the character or characters that identify the start of + * a variable. This method allows a string prefix to be easily set. + * + * @param prefix the prefix for variables, not null + * @return this, to enable chaining + * @throws IllegalArgumentException if the prefix is null + */ + public StrSubstitutor setVariablePrefix(final String prefix) { + if (prefix == null) { + throw new IllegalArgumentException("Variable prefix must not be null."); + } + return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix)); + } + + /** + * Sets the variable prefix matcher currently in use. + *

              + * The variable prefix is the character or characters that identify the start of + * a variable. This prefix is expressed in terms of a matcher allowing advanced + * prefix matches. + * + * @param prefixMatcher the prefix matcher to use, null ignored + * @return this, to enable chaining + * @throws IllegalArgumentException if the prefix matcher is null + */ + public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) { + if (prefixMatcher == null) { + throw new IllegalArgumentException("Variable prefix matcher must not be null."); + } + this.prefixMatcher = prefixMatcher; + return this; + } + + /** + * Sets the VariableResolver that is used to lookup variables. + * + * @param variableResolver the VariableResolver + */ + public void setVariableResolver(final StrLookup variableResolver) { + this.variableResolver = variableResolver; + } + + /** + * Sets the variable suffix to use. + *

              + * The variable suffix is the character or characters that identify the end of a + * variable. This method allows a single character suffix to be easily set. + * + * @param suffix the suffix character to use + * @return this, to enable chaining + */ + public StrSubstitutor setVariableSuffix(final char suffix) { + return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix)); + } + + /** + * Sets the variable suffix to use. + *

              + * The variable suffix is the character or characters that identify the end of a + * variable. This method allows a string suffix to be easily set. + * + * @param suffix the suffix for variables, not null + * @return this, to enable chaining + * @throws IllegalArgumentException if the suffix is null + */ + public StrSubstitutor setVariableSuffix(final String suffix) { + if (suffix == null) { + throw new IllegalArgumentException("Variable suffix must not be null."); + } + return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix)); + } + + /** + * Sets the variable suffix matcher currently in use. + *

              + * The variable suffix is the character or characters that identify the end of a + * variable. This suffix is expressed in terms of a matcher allowing advanced + * suffix matches. + * + * @param suffixMatcher the suffix matcher to use, null ignored + * @return this, to enable chaining + * @throws IllegalArgumentException if the suffix matcher is null + */ + public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) { + if (suffixMatcher == null) { + throw new IllegalArgumentException("Variable suffix matcher must not be null."); + } + this.suffixMatcher = suffixMatcher; + return this; } // ----------------------------------------------------------------------- @@ -915,348 +1263,4 @@ public class StrSubstitutor { } return lengthChange; } - - /** - * Checks if the specified variable is already in the stack (list) of variables. - * - * @param varName the variable name to check - * @param priorVariables the list of prior variables - */ - private void checkCyclicSubstitution(final String varName, final List priorVariables) { - if (priorVariables.contains(varName) == false) { - return; - } - final StrBuilder buf = new StrBuilder(256); - buf.append("Infinite loop in property interpolation of "); - buf.append(priorVariables.remove(0)); - buf.append(": "); - buf.appendWithSeparators(priorVariables, "->"); - throw new IllegalStateException(buf.toString()); - } - - /** - * Internal method that resolves the value of a variable. - *

              - * Most users of this class do not need to call this method. This method is - * called automatically by the substitution process. - *

              - * Writers of subclasses can override this method if they need to alter how each - * substitution occurs. The method is passed the variable's name and must return - * the corresponding value. This implementation uses the - * {@link #getVariableResolver()} with the variable's name as the key. - * - * @param variableName the name of the variable, not null - * @param buf the buffer where the substitution is occurring, not null - * @param startPos the start position of the variable including the prefix, - * valid - * @param endPos the end position of the variable including the suffix, - * valid - * @return the variable's value or null if the variable is unknown - */ - protected String resolveVariable(final String variableName, final StrBuilder buf, final int startPos, - final int endPos) { - final StrLookup resolver = getVariableResolver(); - if (resolver == null) { - return null; - } - return resolver.lookup(variableName); - } - - // Escape - // ----------------------------------------------------------------------- - /** - * Returns the escape character. - * - * @return the character used for escaping variable references - */ - public char getEscapeChar() { - return this.escapeChar; - } - - /** - * Sets the escape character. If this character is placed before a variable - * reference in the source text, this variable will be ignored. - * - * @param escapeCharacter the escape character (0 for disabling escaping) - */ - public void setEscapeChar(final char escapeCharacter) { - this.escapeChar = escapeCharacter; - } - - // Prefix - // ----------------------------------------------------------------------- - /** - * Gets the variable prefix matcher currently in use. - *

              - * The variable prefix is the character or characters that identify the start of - * a variable. This prefix is expressed in terms of a matcher allowing advanced - * prefix matches. - * - * @return the prefix matcher in use - */ - public StrMatcher getVariablePrefixMatcher() { - return prefixMatcher; - } - - /** - * Sets the variable prefix matcher currently in use. - *

              - * The variable prefix is the character or characters that identify the start of - * a variable. This prefix is expressed in terms of a matcher allowing advanced - * prefix matches. - * - * @param prefixMatcher the prefix matcher to use, null ignored - * @return this, to enable chaining - * @throws IllegalArgumentException if the prefix matcher is null - */ - public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) { - if (prefixMatcher == null) { - throw new IllegalArgumentException("Variable prefix matcher must not be null."); - } - this.prefixMatcher = prefixMatcher; - return this; - } - - /** - * Sets the variable prefix to use. - *

              - * The variable prefix is the character or characters that identify the start of - * a variable. This method allows a single character prefix to be easily set. - * - * @param prefix the prefix character to use - * @return this, to enable chaining - */ - public StrSubstitutor setVariablePrefix(final char prefix) { - return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix)); - } - - /** - * Sets the variable prefix to use. - *

              - * The variable prefix is the character or characters that identify the start of - * a variable. This method allows a string prefix to be easily set. - * - * @param prefix the prefix for variables, not null - * @return this, to enable chaining - * @throws IllegalArgumentException if the prefix is null - */ - public StrSubstitutor setVariablePrefix(final String prefix) { - if (prefix == null) { - throw new IllegalArgumentException("Variable prefix must not be null."); - } - return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix)); - } - - // Suffix - // ----------------------------------------------------------------------- - /** - * Gets the variable suffix matcher currently in use. - *

              - * The variable suffix is the character or characters that identify the end of a - * variable. This suffix is expressed in terms of a matcher allowing advanced - * suffix matches. - * - * @return the suffix matcher in use - */ - public StrMatcher getVariableSuffixMatcher() { - return suffixMatcher; - } - - /** - * Sets the variable suffix matcher currently in use. - *

              - * The variable suffix is the character or characters that identify the end of a - * variable. This suffix is expressed in terms of a matcher allowing advanced - * suffix matches. - * - * @param suffixMatcher the suffix matcher to use, null ignored - * @return this, to enable chaining - * @throws IllegalArgumentException if the suffix matcher is null - */ - public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) { - if (suffixMatcher == null) { - throw new IllegalArgumentException("Variable suffix matcher must not be null."); - } - this.suffixMatcher = suffixMatcher; - return this; - } - - /** - * Sets the variable suffix to use. - *

              - * The variable suffix is the character or characters that identify the end of a - * variable. This method allows a single character suffix to be easily set. - * - * @param suffix the suffix character to use - * @return this, to enable chaining - */ - public StrSubstitutor setVariableSuffix(final char suffix) { - return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix)); - } - - /** - * Sets the variable suffix to use. - *

              - * The variable suffix is the character or characters that identify the end of a - * variable. This method allows a string suffix to be easily set. - * - * @param suffix the suffix for variables, not null - * @return this, to enable chaining - * @throws IllegalArgumentException if the suffix is null - */ - public StrSubstitutor setVariableSuffix(final String suffix) { - if (suffix == null) { - throw new IllegalArgumentException("Variable suffix must not be null."); - } - return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix)); - } - - // Variable Default Value Delimiter - // ----------------------------------------------------------------------- - /** - * Gets the variable default value delimiter matcher currently in use. - *

              - * The variable default value delimiter is the character or characters that - * delimit the variable name and the variable default value. This delimiter is - * expressed in terms of a matcher allowing advanced variable default value - * delimiter matches. - *

              - * If it returns null, then the variable default value resolution is disabled. - * - * @return the variable default value delimiter matcher in use, may be null - * @since 3.2 - */ - public StrMatcher getValueDelimiterMatcher() { - return valueDelimiterMatcher; - } - - /** - * Sets the variable default value delimiter matcher to use. - *

              - * The variable default value delimiter is the character or characters that - * delimit the variable name and the variable default value. This delimiter is - * expressed in terms of a matcher allowing advanced variable default value - * delimiter matches. - *

              - * If the {@code valueDelimiterMatcher} is null, then the variable default value - * resolution becomes disabled. - * - * @param valueDelimiterMatcher variable default value delimiter matcher to use, - * may be null - * @return this, to enable chaining - * @since 3.2 - */ - public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) { - this.valueDelimiterMatcher = valueDelimiterMatcher; - return this; - } - - /** - * Sets the variable default value delimiter to use. - *

              - * The variable default value delimiter is the character or characters that - * delimit the variable name and the variable default value. This method allows - * a single character variable default value delimiter to be easily set. - * - * @param valueDelimiter the variable default value delimiter character to use - * @return this, to enable chaining - * @since 3.2 - */ - public StrSubstitutor setValueDelimiter(final char valueDelimiter) { - return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter)); - } - - /** - * Sets the variable default value delimiter to use. - *

              - * The variable default value delimiter is the character or characters that - * delimit the variable name and the variable default value. This method allows - * a string variable default value delimiter to be easily set. - *

              - * If the {@code valueDelimiter} is null or empty string, then the variable - * default value resolution becomes disabled. - * - * @param valueDelimiter the variable default value delimiter string to use, may - * be null or empty - * @return this, to enable chaining - * @since 3.2 - */ - public StrSubstitutor setValueDelimiter(final String valueDelimiter) { - if (StringUtils.isEmpty(valueDelimiter)) { - setValueDelimiterMatcher(null); - return this; - } - return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter)); - } - - // Resolver - // ----------------------------------------------------------------------- - /** - * Gets the VariableResolver that is used to lookup variables. - * - * @return the VariableResolver - */ - public StrLookup getVariableResolver() { - return this.variableResolver; - } - - /** - * Sets the VariableResolver that is used to lookup variables. - * - * @param variableResolver the VariableResolver - */ - public void setVariableResolver(final StrLookup variableResolver) { - this.variableResolver = variableResolver; - } - - // Substitution support in variable names - // ----------------------------------------------------------------------- - /** - * Returns a flag whether substitution is done in variable names. - * - * @return the substitution in variable names flag - * @since 3.0 - */ - public boolean isEnableSubstitutionInVariables() { - return enableSubstitutionInVariables; - } - - /** - * Sets a flag whether substitution is done in variable names. If set to - * true, the names of variables can contain other variables which are - * processed first before the original variable is evaluated, e.g. - * {@code ${jre-${java.version}}}. The default value is false. - * - * @param enableSubstitutionInVariables the new value of the flag - * @since 3.0 - */ - public void setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) { - this.enableSubstitutionInVariables = enableSubstitutionInVariables; - } - - /** - * Returns the flag controlling whether escapes are preserved during - * substitution. - * - * @return the preserve escape flag - * @since 3.5 - */ - public boolean isPreserveEscapes() { - return preserveEscapes; - } - - /** - * Sets a flag controlling whether escapes are preserved during substitution. If - * set to true, the escape character is retained during substitution - * (e.g. {@code $${this-is-escaped}} remains {@code $${this-is-escaped}}). If - * set to false, the escape character is removed during substitution - * (e.g. {@code $${this-is-escaped}} becomes {@code ${this-is-escaped}}). The - * default value is false - * - * @param preserveEscapes true if escapes are to be preserved - * @since 3.5 - */ - public void setPreserveEscapes(final boolean preserveEscapes) { - this.preserveEscapes = preserveEscapes; - } } diff --git a/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java b/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java index 2f116bd4..2a8835a5 100644 --- a/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java +++ b/src/main/java/org/apache/commons/lang3/text/StrTokenizer.java @@ -95,8 +95,8 @@ import org.apache.commons.lang3.StringUtils; * * @since 2.2 * @!deprecated as of 3.6, use commons-text - * StringTokenizer instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringTokenizer.html"> + * StringTokenizer instead */ //@Deprecated public class StrTokenizer implements ListIterator, Cloneable { @@ -121,29 +121,6 @@ public class StrTokenizer implements ListIterator, Cloneable { TSV_TOKENIZER_PROTOTYPE.setIgnoreEmptyTokens(false); } - /** The text to work on. */ - private char[] chars; - /** The parsed tokens */ - private String[] tokens; - /** The current iteration position */ - private int tokenPos; - - /** The delimiter matcher */ - private StrMatcher delimMatcher = StrMatcher.splitMatcher(); - /** The quote matcher */ - private StrMatcher quoteMatcher = StrMatcher.noneMatcher(); - /** The ignored matcher */ - private StrMatcher ignoredMatcher = StrMatcher.noneMatcher(); - /** The trimmer matcher */ - private StrMatcher trimmerMatcher = StrMatcher.noneMatcher(); - - /** Whether to return empty tokens as null */ - private boolean emptyAsNull; - /** Whether to ignore empty tokens */ - private boolean ignoreEmptyTokens = true; - - // ----------------------------------------------------------------------- - /** * Returns a clone of {@code CSV_TOKENIZER_PROTOTYPE}. * @@ -176,7 +153,7 @@ public class StrTokenizer implements ListIterator, Cloneable { * @param input the text to parse * @return a new tokenizer instance which parses Comma Separated Value strings */ - public static StrTokenizer getCSVInstance(final String input) { + public static StrTokenizer getCSVInstance(final char[] input) { final StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; @@ -191,7 +168,7 @@ public class StrTokenizer implements ListIterator, Cloneable { * @param input the text to parse * @return a new tokenizer instance which parses Comma Separated Value strings */ - public static StrTokenizer getCSVInstance(final char[] input) { + public static StrTokenizer getCSVInstance(final String input) { final StrTokenizer tok = getCSVClone(); tok.reset(input); return tok; @@ -227,7 +204,7 @@ public class StrTokenizer implements ListIterator, Cloneable { * @param input the string to parse * @return a new tokenizer instance which parses Tab Separated Value strings. */ - public static StrTokenizer getTSVInstance(final String input) { + public static StrTokenizer getTSVInstance(final char[] input) { final StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; @@ -241,12 +218,41 @@ public class StrTokenizer implements ListIterator, Cloneable { * @param input the string to parse * @return a new tokenizer instance which parses Tab Separated Value strings. */ - public static StrTokenizer getTSVInstance(final char[] input) { + public static StrTokenizer getTSVInstance(final String input) { final StrTokenizer tok = getTSVClone(); tok.reset(input); return tok; } + /** The text to work on. */ + private char[] chars; + + // ----------------------------------------------------------------------- + + /** The parsed tokens */ + private String[] tokens; + + /** The current iteration position */ + private int tokenPos; + + /** The delimiter matcher */ + private StrMatcher delimMatcher = StrMatcher.splitMatcher(); + + /** The quote matcher */ + private StrMatcher quoteMatcher = StrMatcher.noneMatcher(); + + /** The ignored matcher */ + private StrMatcher ignoredMatcher = StrMatcher.noneMatcher(); + + /** The trimmer matcher */ + private StrMatcher trimmerMatcher = StrMatcher.noneMatcher(); + + /** Whether to return empty tokens as null */ + private boolean emptyAsNull; + + /** Whether to ignore empty tokens */ + private boolean ignoreEmptyTokens = true; + // ----------------------------------------------------------------------- /** * Constructs a tokenizer splitting on space, tab, newline and formfeed as per @@ -258,6 +264,75 @@ public class StrTokenizer implements ListIterator, Cloneable { this.chars = null; } + /** + * Constructs a tokenizer splitting on space, tab, newline and formfeed as per + * StringTokenizer. + * + * @param input the string which is to be parsed, not cloned + */ + public StrTokenizer(final char[] input) { + this.chars = new String(input).toCharArray(); + } + + /** + * Constructs a tokenizer splitting on the specified character. + * + * @param input the string which is to be parsed, not cloned + * @param delim the field delimiter character + */ + public StrTokenizer(final char[] input, final char delim) { + this(input); + setDelimiterChar(delim); + } + + /** + * Constructs a tokenizer splitting on the specified delimiter character and + * handling quotes using the specified quote character. + * + * @param input the string which is to be parsed, not cloned + * @param delim the field delimiter character + * @param quote the field quoted string character + */ + public StrTokenizer(final char[] input, final char delim, final char quote) { + this(input, delim); + setQuoteChar(quote); + } + + /** + * Constructs a tokenizer splitting on the specified string. + * + * @param input the string which is to be parsed, not cloned + * @param delim the field delimiter string + */ + public StrTokenizer(final char[] input, final String delim) { + this(input); + setDelimiterString(delim); + } + + /** + * Constructs a tokenizer splitting using the specified delimiter matcher. + * + * @param input the string which is to be parsed, not cloned + * @param delim the field delimiter matcher + */ + public StrTokenizer(final char[] input, final StrMatcher delim) { + this(input); + setDelimiterMatcher(delim); + } + + /** + * Constructs a tokenizer splitting using the specified delimiter matcher and + * handling quotes using the specified quote matcher. + * + * @param input the string which is to be parsed, not cloned + * @param delim the field delimiter character + * @param quote the field quoted string character + */ + public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) { + this(input, delim); + setQuoteMatcher(quote); + } + /** * Constructs a tokenizer splitting on space, tab, newline and formfeed as per * StringTokenizer. @@ -283,6 +358,19 @@ public class StrTokenizer implements ListIterator, Cloneable { setDelimiterChar(delim); } + /** + * Constructs a tokenizer splitting on the specified delimiter character and + * handling quotes using the specified quote character. + * + * @param input the string which is to be parsed + * @param delim the field delimiter character + * @param quote the field quoted string character + */ + public StrTokenizer(final String input, final char delim, final char quote) { + this(input, delim); + setQuoteChar(quote); + } + /** * Constructs a tokenizer splitting on the specified delimiter string. * @@ -305,19 +393,6 @@ public class StrTokenizer implements ListIterator, Cloneable { setDelimiterMatcher(delim); } - /** - * Constructs a tokenizer splitting on the specified delimiter character and - * handling quotes using the specified quote character. - * - * @param input the string which is to be parsed - * @param delim the field delimiter character - * @param quote the field quoted string character - */ - public StrTokenizer(final String input, final char delim, final char quote) { - this(input, delim); - setQuoteChar(quote); - } - /** * Constructs a tokenizer splitting using the specified delimiter matcher and * handling quotes using the specified quote matcher. @@ -332,110 +407,136 @@ public class StrTokenizer implements ListIterator, Cloneable { } /** - * Constructs a tokenizer splitting on space, tab, newline and formfeed as per - * StringTokenizer. - * - * @param input the string which is to be parsed, not cloned + * Unsupported ListIterator operation. + * + * @param obj this parameter ignored. + * @throws UnsupportedOperationException always */ - public StrTokenizer(final char[] input) { - this.chars = new String(input).toCharArray(); + @Override + public void add(final String obj) { + throw new UnsupportedOperationException("add() is unsupported"); } /** - * Constructs a tokenizer splitting on the specified character. + * Adds a token to a list, paying attention to the parameters we've set. * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter character + * @param list the list to add to + * @param tok the token to add */ - public StrTokenizer(final char[] input, final char delim) { - this(input); - setDelimiterChar(delim); + private void addToken(final List list, String tok) { + if (StringUtils.isEmpty(tok)) { + if (isIgnoreEmptyTokens()) { + return; + } + if (isEmptyTokenAsNull()) { + tok = null; + } + } + list.add(tok); } - /** - * Constructs a tokenizer splitting on the specified string. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter string - */ - public StrTokenizer(final char[] input, final String delim) { - this(input); - setDelimiterString(delim); - } - - /** - * Constructs a tokenizer splitting using the specified delimiter matcher. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter matcher - */ - public StrTokenizer(final char[] input, final StrMatcher delim) { - this(input); - setDelimiterMatcher(delim); - } - - /** - * Constructs a tokenizer splitting on the specified delimiter character and - * handling quotes using the specified quote character. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter character - * @param quote the field quoted string character - */ - public StrTokenizer(final char[] input, final char delim, final char quote) { - this(input, delim); - setQuoteChar(quote); - } - - /** - * Constructs a tokenizer splitting using the specified delimiter matcher and - * handling quotes using the specified quote matcher. - * - * @param input the string which is to be parsed, not cloned - * @param delim the field delimiter character - * @param quote the field quoted string character - */ - public StrTokenizer(final char[] input, final StrMatcher delim, final StrMatcher quote) { - this(input, delim); - setQuoteMatcher(quote); - } - - // API + // Implementation // ----------------------------------------------------------------------- /** - * Gets the number of tokens found in the String. - * - * @return the number of matched tokens + * Checks if tokenization has been done, and if not then do it. */ - public int size() { - checkTokenized(); - return tokens.length; + private void checkTokenized() { + if (tokens == null) { + if (chars == null) { + // still call tokenize as subclass may do some work + final List split = tokenize(null, 0, 0); + tokens = split.toArray(new String[0]); + } else { + final List split = tokenize(chars, 0, chars.length); + tokens = split.toArray(new String[0]); + } + } + } + + // ----------------------------------------------------------------------- + /** + * Creates a new instance of this Tokenizer. The new instance is reset so that + * it will be at the start of the token list. If a + * {@link CloneNotSupportedException} is caught, return {@code null}. + * + * @return a new instance of this Tokenizer which has been reset. + */ + @Override + public Object clone() { + try { + return cloneReset(); + } catch (final CloneNotSupportedException ex) { + return null; + } } /** - * Gets the next token from the String. Equivalent to {@link #next()} except it - * returns null rather than throwing {@link NoSuchElementException} when no - * tokens remain. + * Creates a new instance of this Tokenizer. The new instance is reset so that + * it will be at the start of the token list. * - * @return the next sequential token, or null when no more tokens are found + * @return a new instance of this Tokenizer which has been reset. + * @throws CloneNotSupportedException if there is a problem cloning */ - public String nextToken() { - if (hasNext()) { - return tokens[tokenPos++]; + Object cloneReset() throws CloneNotSupportedException { + // this method exists to enable 100% test coverage + final StrTokenizer cloned = (StrTokenizer) super.clone(); + if (cloned.chars != null) { + cloned.chars = cloned.chars.clone(); } - return null; + cloned.reset(); + return cloned; } + // ----------------------------------------------------------------------- /** - * Gets the previous token from the String. + * Gets the String content that the tokenizer is parsing. * - * @return the previous sequential token, or null when no more tokens are found + * @return the string content being parsed */ - public String previousToken() { - if (hasPrevious()) { - return tokens[--tokenPos]; + public String getContent() { + if (chars == null) { + return null; } - return null; + return new String(chars); + } + + // Delimiter + // ----------------------------------------------------------------------- + /** + * Gets the field delimiter matcher. + * + * @return the delimiter matcher in use + */ + public StrMatcher getDelimiterMatcher() { + return this.delimMatcher; + } + + // Ignored + // ----------------------------------------------------------------------- + /** + * Gets the ignored character matcher. + *

              + * These characters are ignored when parsing the String, unless they are within + * a quoted region. The default value is not to ignore anything. + * + * @return the ignored matcher in use + */ + public StrMatcher getIgnoredMatcher() { + return ignoredMatcher; + } + + // Quote + // ----------------------------------------------------------------------- + /** + * Gets the quote matcher currently in use. + *

              + * The quote character is used to wrap data between the tokens. This enables + * delimiters to be entered as data. The default value is '"' (double quote). + * + * @return the quote matcher in use + */ + public StrMatcher getQuoteMatcher() { + return quoteMatcher; } /** @@ -460,49 +561,18 @@ public class StrTokenizer implements ListIterator, Cloneable { return list; } + // Trimmer + // ----------------------------------------------------------------------- /** - * Resets this tokenizer, forgetting all parsing and iteration already - * completed. + * Gets the trimmer character matcher. *

              - * This method allows the same tokenizer to be reused for the same String. + * These characters are trimmed off on each side of the delimiter until the + * token or quote is found. The default value is not to trim anything. * - * @return this, to enable chaining + * @return the trimmer matcher in use */ - public StrTokenizer reset() { - tokenPos = 0; - tokens = null; - return this; - } - - /** - * Reset this tokenizer, giving it a new input string to parse. In this manner - * you can re-use a tokenizer with the same settings on multiple input lines. - * - * @param input the new string to tokenize, null sets no text to parse - * @return this, to enable chaining - */ - public StrTokenizer reset(final String input) { - reset(); - if (input != null) { - this.chars = input.toCharArray(); - } else { - this.chars = null; - } - return this; - } - - /** - * Reset this tokenizer, giving it a new input string to parse. In this manner - * you can re-use a tokenizer with the same settings on multiple input lines. - * - * @param input the new character array to tokenize, not cloned, null sets no - * text to parse - * @return this, to enable chaining - */ - public StrTokenizer reset(final char[] input) { - reset(); - this.chars = new String(input).toCharArray(); - return this; + public StrMatcher getTrimmerMatcher() { + return trimmerMatcher; } // ListIterator @@ -518,6 +588,60 @@ public class StrTokenizer implements ListIterator, Cloneable { return tokenPos < tokens.length; } + /** + * Checks whether there are any previous tokens that can be iterated to. + * + * @return true if there are previous tokens + */ + @Override + public boolean hasPrevious() { + checkTokenized(); + return tokenPos > 0; + } + + // ----------------------------------------------------------------------- + /** + * Gets whether the tokenizer currently returns empty tokens as null. The + * default for this property is false. + * + * @return true if empty tokens are returned as null + */ + public boolean isEmptyTokenAsNull() { + return this.emptyAsNull; + } + + // ----------------------------------------------------------------------- + /** + * Gets whether the tokenizer currently ignores empty tokens. The default for + * this property is true. + * + * @return true if empty tokens are not returned + */ + public boolean isIgnoreEmptyTokens() { + return ignoreEmptyTokens; + } + + /** + * Checks if the characters at the index specified match the quote already + * matched in readNextToken(). + * + * @param srcChars the character array being tokenized + * @param pos the position to check for a quote + * @param len the length of the character array being tokenized + * @param quoteStart the start position of the matched quote, 0 if no quoting + * @param quoteLen the length of the matched quote, 0 if no quoting + * @return true if a quote is matched + */ + private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart, + final int quoteLen) { + for (int i = 0; i < quoteLen; i++) { + if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) { + return false; + } + } + return true; + } + /** * Gets the next token. * @@ -543,14 +667,17 @@ public class StrTokenizer implements ListIterator, Cloneable { } /** - * Checks whether there are any previous tokens that can be iterated to. + * Gets the next token from the String. Equivalent to {@link #next()} except it + * returns null rather than throwing {@link NoSuchElementException} when no + * tokens remain. * - * @return true if there are previous tokens + * @return the next sequential token, or null when no more tokens are found */ - @Override - public boolean hasPrevious() { - checkTokenized(); - return tokenPos > 0; + public String nextToken() { + if (hasNext()) { + return tokens[tokenPos++]; + } + return null; } /** @@ -577,113 +704,15 @@ public class StrTokenizer implements ListIterator, Cloneable { } /** - * Unsupported ListIterator operation. + * Gets the previous token from the String. * - * @throws UnsupportedOperationException always + * @return the previous sequential token, or null when no more tokens are found */ - @Override - public void remove() { - throw new UnsupportedOperationException("remove() is unsupported"); - } - - /** - * Unsupported ListIterator operation. - * - * @param obj this parameter ignored. - * @throws UnsupportedOperationException always - */ - @Override - public void set(final String obj) { - throw new UnsupportedOperationException("set() is unsupported"); - } - - /** - * Unsupported ListIterator operation. - * - * @param obj this parameter ignored. - * @throws UnsupportedOperationException always - */ - @Override - public void add(final String obj) { - throw new UnsupportedOperationException("add() is unsupported"); - } - - // Implementation - // ----------------------------------------------------------------------- - /** - * Checks if tokenization has been done, and if not then do it. - */ - private void checkTokenized() { - if (tokens == null) { - if (chars == null) { - // still call tokenize as subclass may do some work - final List split = tokenize(null, 0, 0); - tokens = split.toArray(new String[0]); - } else { - final List split = tokenize(chars, 0, chars.length); - tokens = split.toArray(new String[0]); - } + public String previousToken() { + if (hasPrevious()) { + return tokens[--tokenPos]; } - } - - /** - * Internal method to performs the tokenization. - *

              - * Most users of this class do not need to call this method. This method will be - * called automatically by other (public) methods when required. - *

              - * This method exists to allow subclasses to add code before or after the - * tokenization. For example, a subclass could alter the character array, offset - * or count to be parsed, or call the tokenizer multiple times on multiple - * strings. It is also be possible to filter the results. - *

              - * {@code StrTokenizer} will always pass a zero offset and a count equal to the - * length of the array to this method, however a subclass may pass other values, - * or even an entirely different array. - * - * @param srcChars the character array being tokenized, may be null - * @param offset the start position within the character array, must be valid - * @param count the number of characters to tokenize, must be valid - * @return the modifiable list of String tokens, unmodifiable if null array or - * zero count - */ - protected List tokenize(final char[] srcChars, final int offset, final int count) { - if (srcChars == null || count == 0) { - return Collections.emptyList(); - } - final StrBuilder buf = new StrBuilder(); - final List tokenList = new ArrayList<>(); - int pos = offset; - - // loop around the entire buffer - while (pos >= 0 && pos < count) { - // find next token - pos = readNextToken(srcChars, pos, count, buf, tokenList); - - // handle case where end of string is a delimiter - if (pos >= count) { - addToken(tokenList, StringUtils.EMPTY); - } - } - return tokenList; - } - - /** - * Adds a token to a list, paying attention to the parameters we've set. - * - * @param list the list to add to - * @param tok the token to add - */ - private void addToken(final List list, String tok) { - if (StringUtils.isEmpty(tok)) { - if (isIgnoreEmptyTokens()) { - return; - } - if (isEmptyTokenAsNull()) { - tok = null; - } - } - list.add(tok); + return null; } /** @@ -832,35 +861,79 @@ public class StrTokenizer implements ListIterator, Cloneable { } /** - * Checks if the characters at the index specified match the quote already - * matched in readNextToken(). + * Unsupported ListIterator operation. * - * @param srcChars the character array being tokenized - * @param pos the position to check for a quote - * @param len the length of the character array being tokenized - * @param quoteStart the start position of the matched quote, 0 if no quoting - * @param quoteLen the length of the matched quote, 0 if no quoting - * @return true if a quote is matched + * @throws UnsupportedOperationException always */ - private boolean isQuote(final char[] srcChars, final int pos, final int len, final int quoteStart, - final int quoteLen) { - for (int i = 0; i < quoteLen; i++) { - if (pos + i >= len || srcChars[pos + i] != srcChars[quoteStart + i]) { - return false; - } - } - return true; + @Override + public void remove() { + throw new UnsupportedOperationException("remove() is unsupported"); } - // Delimiter - // ----------------------------------------------------------------------- /** - * Gets the field delimiter matcher. + * Resets this tokenizer, forgetting all parsing and iteration already + * completed. + *

              + * This method allows the same tokenizer to be reused for the same String. * - * @return the delimiter matcher in use + * @return this, to enable chaining */ - public StrMatcher getDelimiterMatcher() { - return this.delimMatcher; + public StrTokenizer reset() { + tokenPos = 0; + tokens = null; + return this; + } + + /** + * Reset this tokenizer, giving it a new input string to parse. In this manner + * you can re-use a tokenizer with the same settings on multiple input lines. + * + * @param input the new character array to tokenize, not cloned, null sets no + * text to parse + * @return this, to enable chaining + */ + public StrTokenizer reset(final char[] input) { + reset(); + this.chars = new String(input).toCharArray(); + return this; + } + + /** + * Reset this tokenizer, giving it a new input string to parse. In this manner + * you can re-use a tokenizer with the same settings on multiple input lines. + * + * @param input the new string to tokenize, null sets no text to parse + * @return this, to enable chaining + */ + public StrTokenizer reset(final String input) { + reset(); + if (input != null) { + this.chars = input.toCharArray(); + } else { + this.chars = null; + } + return this; + } + + /** + * Unsupported ListIterator operation. + * + * @param obj this parameter ignored. + * @throws UnsupportedOperationException always + */ + @Override + public void set(final String obj) { + throw new UnsupportedOperationException("set() is unsupported"); + } + + /** + * Sets the field delimiter character. + * + * @param delim the delimiter character to use + * @return this, to enable chaining + */ + public StrTokenizer setDelimiterChar(final char delim) { + return setDelimiterMatcher(StrMatcher.charMatcher(delim)); } /** @@ -880,16 +953,6 @@ public class StrTokenizer implements ListIterator, Cloneable { return this; } - /** - * Sets the field delimiter character. - * - * @param delim the delimiter character to use - * @return this, to enable chaining - */ - public StrTokenizer setDelimiterChar(final char delim) { - return setDelimiterMatcher(StrMatcher.charMatcher(delim)); - } - /** * Sets the field delimiter string. * @@ -900,61 +963,29 @@ public class StrTokenizer implements ListIterator, Cloneable { return setDelimiterMatcher(StrMatcher.stringMatcher(delim)); } - // Quote - // ----------------------------------------------------------------------- /** - * Gets the quote matcher currently in use. - *

              - * The quote character is used to wrap data between the tokens. This enables - * delimiters to be entered as data. The default value is '"' (double quote). + * Sets whether the tokenizer should return empty tokens as null. The default + * for this property is false. * - * @return the quote matcher in use - */ - public StrMatcher getQuoteMatcher() { - return quoteMatcher; - } - - /** - * Set the quote matcher to use. - *

              - * The quote character is used to wrap data between the tokens. This enables - * delimiters to be entered as data. - * - * @param quote the quote matcher to use, null ignored + * @param emptyAsNull whether empty tokens are returned as null * @return this, to enable chaining */ - public StrTokenizer setQuoteMatcher(final StrMatcher quote) { - if (quote != null) { - this.quoteMatcher = quote; - } + public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) { + this.emptyAsNull = emptyAsNull; return this; } /** - * Sets the quote character to use. + * Set the character to ignore. *

              - * The quote character is used to wrap data between the tokens. This enables - * delimiters to be entered as data. + * This character is ignored when parsing the String, unless it is within a + * quoted region. * - * @param quote the quote character to use + * @param ignored the ignored character to use * @return this, to enable chaining */ - public StrTokenizer setQuoteChar(final char quote) { - return setQuoteMatcher(StrMatcher.charMatcher(quote)); - } - - // Ignored - // ----------------------------------------------------------------------- - /** - * Gets the ignored character matcher. - *

              - * These characters are ignored when parsing the String, unless they are within - * a quoted region. The default value is not to ignore anything. - * - * @return the ignored matcher in use - */ - public StrMatcher getIgnoredMatcher() { - return ignoredMatcher; + public StrTokenizer setIgnoredChar(final char ignored) { + return setIgnoredMatcher(StrMatcher.charMatcher(ignored)); } /** @@ -974,30 +1005,44 @@ public class StrTokenizer implements ListIterator, Cloneable { } /** - * Set the character to ignore. - *

              - * This character is ignored when parsing the String, unless it is within a - * quoted region. + * Sets whether the tokenizer should ignore and not return empty tokens. The + * default for this property is true. * - * @param ignored the ignored character to use + * @param ignoreEmptyTokens whether empty tokens are not returned * @return this, to enable chaining */ - public StrTokenizer setIgnoredChar(final char ignored) { - return setIgnoredMatcher(StrMatcher.charMatcher(ignored)); + public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) { + this.ignoreEmptyTokens = ignoreEmptyTokens; + return this; } - // Trimmer - // ----------------------------------------------------------------------- /** - * Gets the trimmer character matcher. + * Sets the quote character to use. *

              - * These characters are trimmed off on each side of the delimiter until the - * token or quote is found. The default value is not to trim anything. + * The quote character is used to wrap data between the tokens. This enables + * delimiters to be entered as data. * - * @return the trimmer matcher in use + * @param quote the quote character to use + * @return this, to enable chaining */ - public StrMatcher getTrimmerMatcher() { - return trimmerMatcher; + public StrTokenizer setQuoteChar(final char quote) { + return setQuoteMatcher(StrMatcher.charMatcher(quote)); + } + + /** + * Set the quote matcher to use. + *

              + * The quote character is used to wrap data between the tokens. This enables + * delimiters to be entered as data. + * + * @param quote the quote matcher to use, null ignored + * @return this, to enable chaining + */ + public StrTokenizer setQuoteMatcher(final StrMatcher quote) { + if (quote != null) { + this.quoteMatcher = quote; + } + return this; } /** @@ -1016,97 +1061,58 @@ public class StrTokenizer implements ListIterator, Cloneable { return this; } + // API // ----------------------------------------------------------------------- /** - * Gets whether the tokenizer currently returns empty tokens as null. The - * default for this property is false. + * Gets the number of tokens found in the String. * - * @return true if empty tokens are returned as null + * @return the number of matched tokens */ - public boolean isEmptyTokenAsNull() { - return this.emptyAsNull; + public int size() { + checkTokenized(); + return tokens.length; } /** - * Sets whether the tokenizer should return empty tokens as null. The default - * for this property is false. + * Internal method to performs the tokenization. + *

              + * Most users of this class do not need to call this method. This method will be + * called automatically by other (public) methods when required. + *

              + * This method exists to allow subclasses to add code before or after the + * tokenization. For example, a subclass could alter the character array, offset + * or count to be parsed, or call the tokenizer multiple times on multiple + * strings. It is also be possible to filter the results. + *

              + * {@code StrTokenizer} will always pass a zero offset and a count equal to the + * length of the array to this method, however a subclass may pass other values, + * or even an entirely different array. * - * @param emptyAsNull whether empty tokens are returned as null - * @return this, to enable chaining + * @param srcChars the character array being tokenized, may be null + * @param offset the start position within the character array, must be valid + * @param count the number of characters to tokenize, must be valid + * @return the modifiable list of String tokens, unmodifiable if null array or + * zero count */ - public StrTokenizer setEmptyTokenAsNull(final boolean emptyAsNull) { - this.emptyAsNull = emptyAsNull; - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets whether the tokenizer currently ignores empty tokens. The default for - * this property is true. - * - * @return true if empty tokens are not returned - */ - public boolean isIgnoreEmptyTokens() { - return ignoreEmptyTokens; - } - - /** - * Sets whether the tokenizer should ignore and not return empty tokens. The - * default for this property is true. - * - * @param ignoreEmptyTokens whether empty tokens are not returned - * @return this, to enable chaining - */ - public StrTokenizer setIgnoreEmptyTokens(final boolean ignoreEmptyTokens) { - this.ignoreEmptyTokens = ignoreEmptyTokens; - return this; - } - - // ----------------------------------------------------------------------- - /** - * Gets the String content that the tokenizer is parsing. - * - * @return the string content being parsed - */ - public String getContent() { - if (chars == null) { - return null; + protected List tokenize(final char[] srcChars, final int offset, final int count) { + if (srcChars == null || count == 0) { + return Collections.emptyList(); } - return new String(chars); - } + final StrBuilder buf = new StrBuilder(); + final List tokenList = new ArrayList<>(); + int pos = offset; - // ----------------------------------------------------------------------- - /** - * Creates a new instance of this Tokenizer. The new instance is reset so that - * it will be at the start of the token list. If a - * {@link CloneNotSupportedException} is caught, return {@code null}. - * - * @return a new instance of this Tokenizer which has been reset. - */ - @Override - public Object clone() { - try { - return cloneReset(); - } catch (final CloneNotSupportedException ex) { - return null; - } - } + // loop around the entire buffer + while (pos >= 0 && pos < count) { + // find next token + pos = readNextToken(srcChars, pos, count, buf, tokenList); - /** - * Creates a new instance of this Tokenizer. The new instance is reset so that - * it will be at the start of the token list. - * - * @return a new instance of this Tokenizer which has been reset. - * @throws CloneNotSupportedException if there is a problem cloning - */ - Object cloneReset() throws CloneNotSupportedException { - // this method exists to enable 100% test coverage - final StrTokenizer cloned = (StrTokenizer) super.clone(); - if (cloned.chars != null) { - cloned.chars = cloned.chars.clone(); + // handle case where end of string is a delimiter + if (pos >= count) { + addToken(tokenList, StringUtils.EMPTY); + } } - cloned.reset(); - return cloned; + return tokenList; } // ----------------------------------------------------------------------- diff --git a/src/main/java/org/apache/commons/lang3/text/WordUtils.java b/src/main/java/org/apache/commons/lang3/text/WordUtils.java index 68a30a71..115c68cf 100644 --- a/src/main/java/org/apache/commons/lang3/text/WordUtils.java +++ b/src/main/java/org/apache/commons/lang3/text/WordUtils.java @@ -34,25 +34,444 @@ import org.apache.commons.lang3.StringUtils; * * @since 2.0 * @!deprecated as of 3.6, use commons-text - * WordUtils instead + * "https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/WordUtils.html"> + * WordUtils instead */ //@Deprecated public class WordUtils { + // Capitalizing + // ----------------------------------------------------------------------- /** *

              - * {@code WordUtils} instances should NOT be constructed in standard - * programming. Instead, the class should be used as - * {@code WordUtils.wrap("foo bar", 20);}. + * Capitalizes all the whitespace separated words in a String. Only the first + * character of each word is changed. To convert the rest of each word to + * lowercase at the same time, use {@link #capitalizeFully(String)}. *

              * *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. + * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} + * input String returns {@code null}. Capitalization uses the Unicode title + * case, normally equivalent to upper case. *

              + * + *
              +	 * WordUtils.capitalize(null)        = null
              +	 * WordUtils.capitalize("")          = ""
              +	 * WordUtils.capitalize("i am FINE") = "I Am FINE"
              +	 * 
              + * + * @param str the String to capitalize, may be null + * @return capitalized String, {@code null} if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) */ - public WordUtils() { + public static String capitalize(final String str) { + return capitalize(str, null); + } + + /** + *

              + * Capitalizes all the delimiter separated words in a String. Only the first + * character of each word is changed. To convert the rest of each word to + * lowercase at the same time, use {@link #capitalizeFully(String, char[])}. + *

              + * + *

              + * The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized. + *

              + * + *

              + * A {@code null} input String returns {@code null}. Capitalization uses the + * Unicode title case, normally equivalent to upper case. + *

              + * + *
              +	 * WordUtils.capitalize(null, *)            = null
              +	 * WordUtils.capitalize("", *)              = ""
              +	 * WordUtils.capitalize(*, new char[0])     = *
              +	 * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
              +	 * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
              +	 * 
              + * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means + * whitespace + * @return capitalized String, {@code null} if null String input + * @see #uncapitalize(String) + * @see #capitalizeFully(String) + * @since 2.1 + */ + public static String capitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean capitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + capitalizeNext = true; + } else if (capitalizeNext) { + buffer[i] = Character.toTitleCase(ch); + capitalizeNext = false; + } + } + return new String(buffer); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Converts all the whitespace separated words in a String into capitalized + * words, that is each word is made up of a titlecase character and then a + * series of lowercase characters. + *

              + * + *

              + * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} + * input String returns {@code null}. Capitalization uses the Unicode title + * case, normally equivalent to upper case. + *

              + * + *
              +	 * WordUtils.capitalizeFully(null)        = null
              +	 * WordUtils.capitalizeFully("")          = ""
              +	 * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
              +	 * 
              + * + * @param str the String to capitalize, may be null + * @return capitalized String, {@code null} if null String input + */ + public static String capitalizeFully(final String str) { + return capitalizeFully(str, null); + } + + /** + *

              + * Converts all the delimiter separated words in a String into capitalized + * words, that is each word is made up of a titlecase character and then a + * series of lowercase characters. + *

              + * + *

              + * The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be capitalized. + *

              + * + *

              + * A {@code null} input String returns {@code null}. Capitalization uses the + * Unicode title case, normally equivalent to upper case. + *

              + * + *
              +	 * WordUtils.capitalizeFully(null, *)            = null
              +	 * WordUtils.capitalizeFully("", *)              = ""
              +	 * WordUtils.capitalizeFully(*, null)            = *
              +	 * WordUtils.capitalizeFully(*, new char[0])     = *
              +	 * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
              +	 * 
              + * + * @param str the String to capitalize, may be null + * @param delimiters set of characters to determine capitalization, null means + * whitespace + * @return capitalized String, {@code null} if null String input + * @since 2.1 + */ + public static String capitalizeFully(String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + str = str.toLowerCase(); + return capitalize(str, delimiters); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Checks if the String contains all words in the given array. + *

              + * + *

              + * A {@code null} String will return {@code false}. A {@code null}, zero length + * search array or if one element of array is null will return {@code false}. + *

              + * + *
              +	 * WordUtils.containsAllWords(null, *)            = false
              +	 * WordUtils.containsAllWords("", *)              = false
              +	 * WordUtils.containsAllWords(*, null)            = false
              +	 * WordUtils.containsAllWords(*, [])              = false
              +	 * WordUtils.containsAllWords("abcd", "ab", "cd") = false
              +	 * WordUtils.containsAllWords("abc def", "def", "abc") = true
              +	 * 
              + * + * + * @param word The CharSequence to check, may be null + * @param words The array of String words to search for, may be null + * @return {@code true} if all search words are found, {@code false} otherwise + * @since 3.5 + */ + public static boolean containsAllWords(final CharSequence word, final CharSequence... words) { + if (StringUtils.isEmpty(word) || words.length == 0) { + return false; + } + for (final CharSequence w : words) { + if (StringUtils.isBlank(w)) { + return false; + } + final Pattern p = Pattern.compile(".*\\b" + w + "\\b.*"); + if (!p.matcher(word).matches()) { + return false; + } + } + return true; + } + + // ----------------------------------------------------------------------- + /** + *

              + * Extracts the initial characters from each word in the String. + *

              + * + *

              + * All first characters after whitespace are returned as a new string. Their + * case is not changed. + *

              + * + *

              + * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} + * input String returns {@code null}. + *

              + * + *
              +	 * WordUtils.initials(null)             = null
              +	 * WordUtils.initials("")               = ""
              +	 * WordUtils.initials("Ben John Lee")   = "BJL"
              +	 * WordUtils.initials("Ben J.Lee")      = "BJ"
              +	 * 
              + * + * @param str the String to get initials from, may be null + * @return String of initial letters, {@code null} if null String input + * @see #initials(String,char[]) + * @since 2.2 + */ + public static String initials(final String str) { + return initials(str, null); + } + + /** + *

              + * Extracts the initial characters from each word in the String. + *

              + * + *

              + * All first characters after the defined delimiters are returned as a new + * string. Their case is not changed. + *

              + * + *

              + * If the delimiters array is null, then Whitespace is used. Whitespace is + * defined by {@link Character#isWhitespace(char)}. A {@code null} input String + * returns {@code null}. An empty delimiter array returns an empty String. + *

              + * + *
              +	 * WordUtils.initials(null, *)                = null
              +	 * WordUtils.initials("", *)                  = ""
              +	 * WordUtils.initials("Ben John Lee", null)   = "BJL"
              +	 * WordUtils.initials("Ben J.Lee", null)      = "BJ"
              +	 * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
              +	 * WordUtils.initials(*, new char[0])         = ""
              +	 * 
              + * + * @param str the String to get initials from, may be null + * @param delimiters set of characters to determine words, null means whitespace + * @return String of initial characters, {@code null} if null String input + * @see #initials(String) + * @since 2.2 + */ + public static String initials(final String str, final char... delimiters) { + if (StringUtils.isEmpty(str)) { + return str; + } + if (delimiters != null && delimiters.length == 0) { + return StringUtils.EMPTY; + } + final int strLen = str.length(); + final char[] buf = new char[strLen / 2 + 1]; + int count = 0; + boolean lastWasGap = true; + for (int i = 0; i < strLen; i++) { + final char ch = str.charAt(i); + + if (isDelimiter(ch, delimiters)) { + lastWasGap = true; + } else if (lastWasGap) { + buf[count++] = ch; + lastWasGap = false; + } else { + continue; // ignore ch + } + } + return new String(buf, 0, count); + } + + // ----------------------------------------------------------------------- + /** + * Is the character a delimiter. + * + * @param ch the character to check + * @param delimiters the delimiters + * @return true if it is a delimiter + */ + private static boolean isDelimiter(final char ch, final char[] delimiters) { + if (delimiters == null) { + return Character.isWhitespace(ch); + } + for (final char delimiter : delimiters) { + if (ch == delimiter) { + return true; + } + } + return false; + } + + // ----------------------------------------------------------------------- + /** + *

              + * Swaps the case of a String using a word based algorithm. + *

              + * + *
                + *
              • Upper case character converts to Lower case
              • + *
              • Title case character converts to Lower case
              • + *
              • Lower case character after Whitespace or at start converts to Title + * case
              • + *
              • Other Lower case character converts to Upper case
              • + *
              + * + *

              + * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} + * input String returns {@code null}. + *

              + * + *
              +	 * StringUtils.swapCase(null)                 = null
              +	 * StringUtils.swapCase("")                   = ""
              +	 * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
              +	 * 
              + * + * @param str the String to swap case, may be null + * @return the changed String, {@code null} if null String input + */ + public static String swapCase(final String str) { + if (StringUtils.isEmpty(str)) { + return str; + } + final char[] buffer = str.toCharArray(); + + boolean whitespace = true; + + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (Character.isUpperCase(ch) || Character.isTitleCase(ch)) { + buffer[i] = Character.toLowerCase(ch); + whitespace = false; + } else if (Character.isLowerCase(ch)) { + if (whitespace) { + buffer[i] = Character.toTitleCase(ch); + whitespace = false; + } else { + buffer[i] = Character.toUpperCase(ch); + } + } else { + whitespace = Character.isWhitespace(ch); + } + } + return new String(buffer); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Uncapitalizes all the whitespace separated words in a String. Only the first + * character of each word is changed. + *

              + * + *

              + * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} + * input String returns {@code null}. + *

              + * + *
              +	 * WordUtils.uncapitalize(null)        = null
              +	 * WordUtils.uncapitalize("")          = ""
              +	 * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
              +	 * 
              + * + * @param str the String to uncapitalize, may be null + * @return uncapitalized String, {@code null} if null String input + * @see #capitalize(String) + */ + public static String uncapitalize(final String str) { + return uncapitalize(str, null); + } + + /** + *

              + * Uncapitalizes all the whitespace separated words in a String. Only the first + * character of each word is changed. + *

              + * + *

              + * The delimiters represent a set of characters understood to separate words. + * The first string character and the first non-delimiter character after a + * delimiter will be uncapitalized. + *

              + * + *

              + * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} + * input String returns {@code null}. + *

              + * + *
              +	 * WordUtils.uncapitalize(null, *)            = null
              +	 * WordUtils.uncapitalize("", *)              = ""
              +	 * WordUtils.uncapitalize(*, null)            = *
              +	 * WordUtils.uncapitalize(*, new char[0])     = *
              +	 * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
              +	 * 
              + * + * @param str the String to uncapitalize, may be null + * @param delimiters set of characters to determine uncapitalization, null means + * whitespace + * @return uncapitalized String, {@code null} if null String input + * @see #capitalize(String) + * @since 2.1 + */ + public static String uncapitalize(final String str, final char... delimiters) { + final int delimLen = delimiters == null ? -1 : delimiters.length; + if (StringUtils.isEmpty(str) || delimLen == 0) { + return str; + } + final char[] buffer = str.toCharArray(); + boolean uncapitalizeNext = true; + for (int i = 0; i < buffer.length; i++) { + final char ch = buffer[i]; + if (isDelimiter(ch, delimiters)) { + uncapitalizeNext = true; + } else if (uncapitalizeNext) { + buffer[i] = Character.toLowerCase(ch); + uncapitalizeNext = false; + } + } + return new String(buffer); } // Wrapping @@ -396,438 +815,19 @@ public class WordUtils { return wrappedLine.toString(); } - // Capitalizing - // ----------------------------------------------------------------------- /** *

              - * Capitalizes all the whitespace separated words in a String. Only the first - * character of each word is changed. To convert the rest of each word to - * lowercase at the same time, use {@link #capitalizeFully(String)}. + * {@code WordUtils} instances should NOT be constructed in standard + * programming. Instead, the class should be used as + * {@code WordUtils.wrap("foo bar", 20);}. *

              * *

              - * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} - * input String returns {@code null}. Capitalization uses the Unicode title - * case, normally equivalent to upper case. + * This constructor is public to permit tools that require a JavaBean instance + * to operate. *

              - * - *
              -	 * WordUtils.capitalize(null)        = null
              -	 * WordUtils.capitalize("")          = ""
              -	 * WordUtils.capitalize("i am FINE") = "I Am FINE"
              -	 * 
              - * - * @param str the String to capitalize, may be null - * @return capitalized String, {@code null} if null String input - * @see #uncapitalize(String) - * @see #capitalizeFully(String) */ - public static String capitalize(final String str) { - return capitalize(str, null); - } - - /** - *

              - * Capitalizes all the delimiter separated words in a String. Only the first - * character of each word is changed. To convert the rest of each word to - * lowercase at the same time, use {@link #capitalizeFully(String, char[])}. - *

              - * - *

              - * The delimiters represent a set of characters understood to separate words. - * The first string character and the first non-delimiter character after a - * delimiter will be capitalized. - *

              - * - *

              - * A {@code null} input String returns {@code null}. Capitalization uses the - * Unicode title case, normally equivalent to upper case. - *

              - * - *
              -	 * WordUtils.capitalize(null, *)            = null
              -	 * WordUtils.capitalize("", *)              = ""
              -	 * WordUtils.capitalize(*, new char[0])     = *
              -	 * WordUtils.capitalize("i am fine", null)  = "I Am Fine"
              -	 * WordUtils.capitalize("i aM.fine", {'.'}) = "I aM.Fine"
              -	 * 
              - * - * @param str the String to capitalize, may be null - * @param delimiters set of characters to determine capitalization, null means - * whitespace - * @return capitalized String, {@code null} if null String input - * @see #uncapitalize(String) - * @see #capitalizeFully(String) - * @since 2.1 - */ - public static String capitalize(final String str, final char... delimiters) { - final int delimLen = delimiters == null ? -1 : delimiters.length; - if (StringUtils.isEmpty(str) || delimLen == 0) { - return str; - } - final char[] buffer = str.toCharArray(); - boolean capitalizeNext = true; - for (int i = 0; i < buffer.length; i++) { - final char ch = buffer[i]; - if (isDelimiter(ch, delimiters)) { - capitalizeNext = true; - } else if (capitalizeNext) { - buffer[i] = Character.toTitleCase(ch); - capitalizeNext = false; - } - } - return new String(buffer); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Converts all the whitespace separated words in a String into capitalized - * words, that is each word is made up of a titlecase character and then a - * series of lowercase characters. - *

              - * - *

              - * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} - * input String returns {@code null}. Capitalization uses the Unicode title - * case, normally equivalent to upper case. - *

              - * - *
              -	 * WordUtils.capitalizeFully(null)        = null
              -	 * WordUtils.capitalizeFully("")          = ""
              -	 * WordUtils.capitalizeFully("i am FINE") = "I Am Fine"
              -	 * 
              - * - * @param str the String to capitalize, may be null - * @return capitalized String, {@code null} if null String input - */ - public static String capitalizeFully(final String str) { - return capitalizeFully(str, null); - } - - /** - *

              - * Converts all the delimiter separated words in a String into capitalized - * words, that is each word is made up of a titlecase character and then a - * series of lowercase characters. - *

              - * - *

              - * The delimiters represent a set of characters understood to separate words. - * The first string character and the first non-delimiter character after a - * delimiter will be capitalized. - *

              - * - *

              - * A {@code null} input String returns {@code null}. Capitalization uses the - * Unicode title case, normally equivalent to upper case. - *

              - * - *
              -	 * WordUtils.capitalizeFully(null, *)            = null
              -	 * WordUtils.capitalizeFully("", *)              = ""
              -	 * WordUtils.capitalizeFully(*, null)            = *
              -	 * WordUtils.capitalizeFully(*, new char[0])     = *
              -	 * WordUtils.capitalizeFully("i aM.fine", {'.'}) = "I am.Fine"
              -	 * 
              - * - * @param str the String to capitalize, may be null - * @param delimiters set of characters to determine capitalization, null means - * whitespace - * @return capitalized String, {@code null} if null String input - * @since 2.1 - */ - public static String capitalizeFully(String str, final char... delimiters) { - final int delimLen = delimiters == null ? -1 : delimiters.length; - if (StringUtils.isEmpty(str) || delimLen == 0) { - return str; - } - str = str.toLowerCase(); - return capitalize(str, delimiters); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Uncapitalizes all the whitespace separated words in a String. Only the first - * character of each word is changed. - *

              - * - *

              - * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} - * input String returns {@code null}. - *

              - * - *
              -	 * WordUtils.uncapitalize(null)        = null
              -	 * WordUtils.uncapitalize("")          = ""
              -	 * WordUtils.uncapitalize("I Am FINE") = "i am fINE"
              -	 * 
              - * - * @param str the String to uncapitalize, may be null - * @return uncapitalized String, {@code null} if null String input - * @see #capitalize(String) - */ - public static String uncapitalize(final String str) { - return uncapitalize(str, null); - } - - /** - *

              - * Uncapitalizes all the whitespace separated words in a String. Only the first - * character of each word is changed. - *

              - * - *

              - * The delimiters represent a set of characters understood to separate words. - * The first string character and the first non-delimiter character after a - * delimiter will be uncapitalized. - *

              - * - *

              - * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} - * input String returns {@code null}. - *

              - * - *
              -	 * WordUtils.uncapitalize(null, *)            = null
              -	 * WordUtils.uncapitalize("", *)              = ""
              -	 * WordUtils.uncapitalize(*, null)            = *
              -	 * WordUtils.uncapitalize(*, new char[0])     = *
              -	 * WordUtils.uncapitalize("I AM.FINE", {'.'}) = "i AM.fINE"
              -	 * 
              - * - * @param str the String to uncapitalize, may be null - * @param delimiters set of characters to determine uncapitalization, null means - * whitespace - * @return uncapitalized String, {@code null} if null String input - * @see #capitalize(String) - * @since 2.1 - */ - public static String uncapitalize(final String str, final char... delimiters) { - final int delimLen = delimiters == null ? -1 : delimiters.length; - if (StringUtils.isEmpty(str) || delimLen == 0) { - return str; - } - final char[] buffer = str.toCharArray(); - boolean uncapitalizeNext = true; - for (int i = 0; i < buffer.length; i++) { - final char ch = buffer[i]; - if (isDelimiter(ch, delimiters)) { - uncapitalizeNext = true; - } else if (uncapitalizeNext) { - buffer[i] = Character.toLowerCase(ch); - uncapitalizeNext = false; - } - } - return new String(buffer); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Swaps the case of a String using a word based algorithm. - *

              - * - *
                - *
              • Upper case character converts to Lower case
              • - *
              • Title case character converts to Lower case
              • - *
              • Lower case character after Whitespace or at start converts to Title - * case
              • - *
              • Other Lower case character converts to Upper case
              • - *
              - * - *

              - * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} - * input String returns {@code null}. - *

              - * - *
              -	 * StringUtils.swapCase(null)                 = null
              -	 * StringUtils.swapCase("")                   = ""
              -	 * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
              -	 * 
              - * - * @param str the String to swap case, may be null - * @return the changed String, {@code null} if null String input - */ - public static String swapCase(final String str) { - if (StringUtils.isEmpty(str)) { - return str; - } - final char[] buffer = str.toCharArray(); - - boolean whitespace = true; - - for (int i = 0; i < buffer.length; i++) { - final char ch = buffer[i]; - if (Character.isUpperCase(ch) || Character.isTitleCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - whitespace = false; - } else if (Character.isLowerCase(ch)) { - if (whitespace) { - buffer[i] = Character.toTitleCase(ch); - whitespace = false; - } else { - buffer[i] = Character.toUpperCase(ch); - } - } else { - whitespace = Character.isWhitespace(ch); - } - } - return new String(buffer); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Extracts the initial characters from each word in the String. - *

              - * - *

              - * All first characters after whitespace are returned as a new string. Their - * case is not changed. - *

              - * - *

              - * Whitespace is defined by {@link Character#isWhitespace(char)}. A {@code null} - * input String returns {@code null}. - *

              - * - *
              -	 * WordUtils.initials(null)             = null
              -	 * WordUtils.initials("")               = ""
              -	 * WordUtils.initials("Ben John Lee")   = "BJL"
              -	 * WordUtils.initials("Ben J.Lee")      = "BJ"
              -	 * 
              - * - * @param str the String to get initials from, may be null - * @return String of initial letters, {@code null} if null String input - * @see #initials(String,char[]) - * @since 2.2 - */ - public static String initials(final String str) { - return initials(str, null); - } - - /** - *

              - * Extracts the initial characters from each word in the String. - *

              - * - *

              - * All first characters after the defined delimiters are returned as a new - * string. Their case is not changed. - *

              - * - *

              - * If the delimiters array is null, then Whitespace is used. Whitespace is - * defined by {@link Character#isWhitespace(char)}. A {@code null} input String - * returns {@code null}. An empty delimiter array returns an empty String. - *

              - * - *
              -	 * WordUtils.initials(null, *)                = null
              -	 * WordUtils.initials("", *)                  = ""
              -	 * WordUtils.initials("Ben John Lee", null)   = "BJL"
              -	 * WordUtils.initials("Ben J.Lee", null)      = "BJ"
              -	 * WordUtils.initials("Ben J.Lee", [' ','.']) = "BJL"
              -	 * WordUtils.initials(*, new char[0])         = ""
              -	 * 
              - * - * @param str the String to get initials from, may be null - * @param delimiters set of characters to determine words, null means whitespace - * @return String of initial characters, {@code null} if null String input - * @see #initials(String) - * @since 2.2 - */ - public static String initials(final String str, final char... delimiters) { - if (StringUtils.isEmpty(str)) { - return str; - } - if (delimiters != null && delimiters.length == 0) { - return StringUtils.EMPTY; - } - final int strLen = str.length(); - final char[] buf = new char[strLen / 2 + 1]; - int count = 0; - boolean lastWasGap = true; - for (int i = 0; i < strLen; i++) { - final char ch = str.charAt(i); - - if (isDelimiter(ch, delimiters)) { - lastWasGap = true; - } else if (lastWasGap) { - buf[count++] = ch; - lastWasGap = false; - } else { - continue; // ignore ch - } - } - return new String(buf, 0, count); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Checks if the String contains all words in the given array. - *

              - * - *

              - * A {@code null} String will return {@code false}. A {@code null}, zero length - * search array or if one element of array is null will return {@code false}. - *

              - * - *
              -	 * WordUtils.containsAllWords(null, *)            = false
              -	 * WordUtils.containsAllWords("", *)              = false
              -	 * WordUtils.containsAllWords(*, null)            = false
              -	 * WordUtils.containsAllWords(*, [])              = false
              -	 * WordUtils.containsAllWords("abcd", "ab", "cd") = false
              -	 * WordUtils.containsAllWords("abc def", "def", "abc") = true
              -	 * 
              - * - * - * @param word The CharSequence to check, may be null - * @param words The array of String words to search for, may be null - * @return {@code true} if all search words are found, {@code false} otherwise - * @since 3.5 - */ - public static boolean containsAllWords(final CharSequence word, final CharSequence... words) { - if (StringUtils.isEmpty(word) || words.length == 0) { - return false; - } - for (final CharSequence w : words) { - if (StringUtils.isBlank(w)) { - return false; - } - final Pattern p = Pattern.compile(".*\\b" + w + "\\b.*"); - if (!p.matcher(word).matches()) { - return false; - } - } - return true; - } - - // ----------------------------------------------------------------------- - /** - * Is the character a delimiter. - * - * @param ch the character to check - * @param delimiters the delimiters - * @return true if it is a delimiter - */ - private static boolean isDelimiter(final char ch, final char[] delimiters) { - if (delimiters == null) { - return Character.isWhitespace(ch); - } - for (final char delimiter : delimiters) { - if (ch == delimiter) { - return true; - } - } - return false; + public WordUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java b/src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java index 820753bc..3c567da4 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateFormatUtils.java @@ -199,100 +199,6 @@ public class DateFormatUtils { public static final FastDateFormat SMTP_DATETIME_FORMAT = FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); - // ----------------------------------------------------------------------- - /** - *

              - * DateFormatUtils instances should NOT be constructed in standard programming. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public DateFormatUtils() { - } - - /** - *

              - * Formats a date/time into a specific pattern using the UTC time zone. - *

              - * - * @param millis the date to format expressed in milliseconds - * @param pattern the pattern to use to format the date, not null - * @return the formatted date - */ - public static String formatUTC(final long millis, final String pattern) { - return format(new Date(millis), pattern, UTC_TIME_ZONE, null); - } - - /** - *

              - * Formats a date/time into a specific pattern using the UTC time zone. - *

              - * - * @param date the date to format, not null - * @param pattern the pattern to use to format the date, not null - * @return the formatted date - */ - public static String formatUTC(final Date date, final String pattern) { - return format(date, pattern, UTC_TIME_ZONE, null); - } - - /** - *

              - * Formats a date/time into a specific pattern using the UTC time zone. - *

              - * - * @param millis the date to format expressed in milliseconds - * @param pattern the pattern to use to format the date, not null - * @param locale the locale to use, may be {@code null} - * @return the formatted date - */ - public static String formatUTC(final long millis, final String pattern, final Locale locale) { - return format(new Date(millis), pattern, UTC_TIME_ZONE, locale); - } - - /** - *

              - * Formats a date/time into a specific pattern using the UTC time zone. - *

              - * - * @param date the date to format, not null - * @param pattern the pattern to use to format the date, not null - * @param locale the locale to use, may be {@code null} - * @return the formatted date - */ - public static String formatUTC(final Date date, final String pattern, final Locale locale) { - return format(date, pattern, UTC_TIME_ZONE, locale); - } - - /** - *

              - * Formats a date/time into a specific pattern. - *

              - * - * @param millis the date to format expressed in milliseconds - * @param pattern the pattern to use to format the date, not null - * @return the formatted date - */ - public static String format(final long millis, final String pattern) { - return format(new Date(millis), pattern, null, null); - } - - /** - *

              - * Formats a date/time into a specific pattern. - *

              - * - * @param date the date to format, not null - * @param pattern the pattern to use to format the date, not null - * @return the formatted date - */ - public static String format(final Date date, final String pattern) { - return format(date, pattern, null, null); - } - /** *

              * Formats a calendar into a specific pattern. @@ -308,78 +214,6 @@ public class DateFormatUtils { return format(calendar, pattern, null, null); } - /** - *

              - * Formats a date/time into a specific pattern in a time zone. - *

              - * - * @param millis the time expressed in milliseconds - * @param pattern the pattern to use to format the date, not null - * @param timeZone the time zone to use, may be {@code null} - * @return the formatted date - */ - public static String format(final long millis, final String pattern, final TimeZone timeZone) { - return format(new Date(millis), pattern, timeZone, null); - } - - /** - *

              - * Formats a date/time into a specific pattern in a time zone. - *

              - * - * @param date the date to format, not null - * @param pattern the pattern to use to format the date, not null - * @param timeZone the time zone to use, may be {@code null} - * @return the formatted date - */ - public static String format(final Date date, final String pattern, final TimeZone timeZone) { - return format(date, pattern, timeZone, null); - } - - /** - *

              - * Formats a calendar into a specific pattern in a time zone. - *

              - * - * @param calendar the calendar to format, not null - * @param pattern the pattern to use to format the calendar, not null - * @param timeZone the time zone to use, may be {@code null} - * @return the formatted calendar - * @see FastDateFormat#format(Calendar) - * @since 2.4 - */ - public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone) { - return format(calendar, pattern, timeZone, null); - } - - /** - *

              - * Formats a date/time into a specific pattern in a locale. - *

              - * - * @param millis the date to format expressed in milliseconds - * @param pattern the pattern to use to format the date, not null - * @param locale the locale to use, may be {@code null} - * @return the formatted date - */ - public static String format(final long millis, final String pattern, final Locale locale) { - return format(new Date(millis), pattern, null, locale); - } - - /** - *

              - * Formats a date/time into a specific pattern in a locale. - *

              - * - * @param date the date to format, not null - * @param pattern the pattern to use to format the date, not null - * @param locale the locale to use, may be {@code null} - * @return the formatted date - */ - public static String format(final Date date, final String pattern, final Locale locale) { - return format(date, pattern, null, locale); - } - /** *

              * Formats a calendar into a specific pattern in a locale. @@ -398,33 +232,18 @@ public class DateFormatUtils { /** *

              - * Formats a date/time into a specific pattern in a time zone and locale. + * Formats a calendar into a specific pattern in a time zone. *

              * - * @param millis the date to format expressed in milliseconds - * @param pattern the pattern to use to format the date, not null + * @param calendar the calendar to format, not null + * @param pattern the pattern to use to format the calendar, not null * @param timeZone the time zone to use, may be {@code null} - * @param locale the locale to use, may be {@code null} - * @return the formatted date + * @return the formatted calendar + * @see FastDateFormat#format(Calendar) + * @since 2.4 */ - public static String format(final long millis, final String pattern, final TimeZone timeZone, final Locale locale) { - return format(new Date(millis), pattern, timeZone, locale); - } - - /** - *

              - * Formats a date/time into a specific pattern in a time zone and locale. - *

              - * - * @param date the date to format, not null - * @param pattern the pattern to use to format the date, not null, not null - * @param timeZone the time zone to use, may be {@code null} - * @param locale the locale to use, may be {@code null} - * @return the formatted date - */ - public static String format(final Date date, final String pattern, final TimeZone timeZone, final Locale locale) { - final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); - return df.format(date); + public static String format(final Calendar calendar, final String pattern, final TimeZone timeZone) { + return format(calendar, pattern, timeZone, null); } /** @@ -446,4 +265,185 @@ public class DateFormatUtils { return df.format(calendar); } + /** + *

              + * Formats a date/time into a specific pattern. + *

              + * + * @param date the date to format, not null + * @param pattern the pattern to use to format the date, not null + * @return the formatted date + */ + public static String format(final Date date, final String pattern) { + return format(date, pattern, null, null); + } + + /** + *

              + * Formats a date/time into a specific pattern in a locale. + *

              + * + * @param date the date to format, not null + * @param pattern the pattern to use to format the date, not null + * @param locale the locale to use, may be {@code null} + * @return the formatted date + */ + public static String format(final Date date, final String pattern, final Locale locale) { + return format(date, pattern, null, locale); + } + + /** + *

              + * Formats a date/time into a specific pattern in a time zone. + *

              + * + * @param date the date to format, not null + * @param pattern the pattern to use to format the date, not null + * @param timeZone the time zone to use, may be {@code null} + * @return the formatted date + */ + public static String format(final Date date, final String pattern, final TimeZone timeZone) { + return format(date, pattern, timeZone, null); + } + + /** + *

              + * Formats a date/time into a specific pattern in a time zone and locale. + *

              + * + * @param date the date to format, not null + * @param pattern the pattern to use to format the date, not null, not null + * @param timeZone the time zone to use, may be {@code null} + * @param locale the locale to use, may be {@code null} + * @return the formatted date + */ + public static String format(final Date date, final String pattern, final TimeZone timeZone, final Locale locale) { + final FastDateFormat df = FastDateFormat.getInstance(pattern, timeZone, locale); + return df.format(date); + } + + /** + *

              + * Formats a date/time into a specific pattern. + *

              + * + * @param millis the date to format expressed in milliseconds + * @param pattern the pattern to use to format the date, not null + * @return the formatted date + */ + public static String format(final long millis, final String pattern) { + return format(new Date(millis), pattern, null, null); + } + + /** + *

              + * Formats a date/time into a specific pattern in a locale. + *

              + * + * @param millis the date to format expressed in milliseconds + * @param pattern the pattern to use to format the date, not null + * @param locale the locale to use, may be {@code null} + * @return the formatted date + */ + public static String format(final long millis, final String pattern, final Locale locale) { + return format(new Date(millis), pattern, null, locale); + } + + /** + *

              + * Formats a date/time into a specific pattern in a time zone. + *

              + * + * @param millis the time expressed in milliseconds + * @param pattern the pattern to use to format the date, not null + * @param timeZone the time zone to use, may be {@code null} + * @return the formatted date + */ + public static String format(final long millis, final String pattern, final TimeZone timeZone) { + return format(new Date(millis), pattern, timeZone, null); + } + + /** + *

              + * Formats a date/time into a specific pattern in a time zone and locale. + *

              + * + * @param millis the date to format expressed in milliseconds + * @param pattern the pattern to use to format the date, not null + * @param timeZone the time zone to use, may be {@code null} + * @param locale the locale to use, may be {@code null} + * @return the formatted date + */ + public static String format(final long millis, final String pattern, final TimeZone timeZone, final Locale locale) { + return format(new Date(millis), pattern, timeZone, locale); + } + + /** + *

              + * Formats a date/time into a specific pattern using the UTC time zone. + *

              + * + * @param date the date to format, not null + * @param pattern the pattern to use to format the date, not null + * @return the formatted date + */ + public static String formatUTC(final Date date, final String pattern) { + return format(date, pattern, UTC_TIME_ZONE, null); + } + + /** + *

              + * Formats a date/time into a specific pattern using the UTC time zone. + *

              + * + * @param date the date to format, not null + * @param pattern the pattern to use to format the date, not null + * @param locale the locale to use, may be {@code null} + * @return the formatted date + */ + public static String formatUTC(final Date date, final String pattern, final Locale locale) { + return format(date, pattern, UTC_TIME_ZONE, locale); + } + + /** + *

              + * Formats a date/time into a specific pattern using the UTC time zone. + *

              + * + * @param millis the date to format expressed in milliseconds + * @param pattern the pattern to use to format the date, not null + * @return the formatted date + */ + public static String formatUTC(final long millis, final String pattern) { + return format(new Date(millis), pattern, UTC_TIME_ZONE, null); + } + + /** + *

              + * Formats a date/time into a specific pattern using the UTC time zone. + *

              + * + * @param millis the date to format expressed in milliseconds + * @param pattern the pattern to use to format the date, not null + * @param locale the locale to use, may be {@code null} + * @return the formatted date + */ + public static String formatUTC(final long millis, final String pattern, final Locale locale) { + return format(new Date(millis), pattern, UTC_TIME_ZONE, locale); + } + + // ----------------------------------------------------------------------- + /** + *

              + * DateFormatUtils instances should NOT be constructed in standard programming. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              + */ + public DateFormatUtils() { + } + } diff --git a/src/main/java/org/apache/commons/lang3/time/DateParser.java b/src/main/java/org/apache/commons/lang3/time/DateParser.java index 303f7c10..b448a255 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateParser.java +++ b/src/main/java/org/apache/commons/lang3/time/DateParser.java @@ -35,6 +35,40 @@ import java.util.TimeZone; */ public interface DateParser { + /** + *

              + * Gets the locale used by this parser. + *

              + * + * @return the locale + */ + Locale getLocale(); + + // Accessors + // ----------------------------------------------------------------------- + /** + *

              + * Gets the pattern used by this parser. + *

              + * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + String getPattern(); + + /** + *

              + * Gets the time zone used by this parser. + *

              + * + *

              + * The default {@link TimeZone} used to create a {@link Date} when the + * {@link TimeZone} is not specified by the format pattern. + *

              + * + * @return the time zone + */ + TimeZone getTimeZone(); + /** * Equivalent to DateFormat.parse(String). * @@ -82,40 +116,6 @@ public interface DateParser { */ boolean parse(String source, ParsePosition pos, Calendar calendar); - // Accessors - // ----------------------------------------------------------------------- - /** - *

              - * Gets the pattern used by this parser. - *

              - * - * @return the pattern, {@link java.text.SimpleDateFormat} compatible - */ - String getPattern(); - - /** - *

              - * Gets the time zone used by this parser. - *

              - * - *

              - * The default {@link TimeZone} used to create a {@link Date} when the - * {@link TimeZone} is not specified by the format pattern. - *

              - * - * @return the time zone - */ - TimeZone getTimeZone(); - - /** - *

              - * Gets the locale used by this parser. - *

              - * - * @return the locale - */ - Locale getLocale(); - /** * Parses text from a string to produce a Date. * diff --git a/src/main/java/org/apache/commons/lang3/time/DatePrinter.java b/src/main/java/org/apache/commons/lang3/time/DatePrinter.java index 47a17a80..66044fc6 100644 --- a/src/main/java/org/apache/commons/lang3/time/DatePrinter.java +++ b/src/main/java/org/apache/commons/lang3/time/DatePrinter.java @@ -34,27 +34,6 @@ import java.util.TimeZone; */ public interface DatePrinter { - /** - *

              - * Formats a millisecond {@code long} value. - *

              - * - * @param millis the millisecond value to format - * @return the formatted string - * @since 2.1 - */ - String format(long millis); - - /** - *

              - * Formats a {@code Date} object using a {@code GregorianCalendar}. - *

              - * - * @param date the date to format - * @return the formatted string - */ - String format(Date date); - /** *

              * Formats a {@code Calendar} object. @@ -70,31 +49,20 @@ public interface DatePrinter { /** *

              - * Formats a millisecond {@code long} value into the supplied - * {@code StringBuffer}. + * Formats a {@code Calendar} object into the supplied {@code Appendable}. *

              + * The TimeZone set on the Calendar is only used to adjust the time offset. The + * TimeZone specified during the construction of the Parser will determine the + * TimeZone used in the formatted string. * - * @param millis the millisecond value to format - * @param buf the buffer to format into + * @param calendar the calendar to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or + * StringBuffer. * @return the specified string buffer - * @deprecated Use {{@link #format(long, Appendable)}. + * @since 3.5 */ - @Deprecated - StringBuffer format(long millis, StringBuffer buf); - - /** - *

              - * Formats a {@code Date} object into the supplied {@code StringBuffer} using a - * {@code GregorianCalendar}. - *

              - * - * @param date the date to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Date, Appendable)}. - */ - @Deprecated - StringBuffer format(Date date, StringBuffer buf); + B format(Calendar calendar, B buf); /** *

              @@ -114,18 +82,13 @@ public interface DatePrinter { /** *

              - * Formats a millisecond {@code long} value into the supplied - * {@code Appendable}. + * Formats a {@code Date} object using a {@code GregorianCalendar}. *

              * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or - * StringBuffer. - * @return the specified string buffer - * @since 3.5 + * @param date the date to format + * @return the formatted string */ - B format(long millis, B buf); + String format(Date date); /** *

              @@ -143,20 +106,80 @@ public interface DatePrinter { /** *

              - * Formats a {@code Calendar} object into the supplied {@code Appendable}. + * Formats a {@code Date} object into the supplied {@code StringBuffer} using a + * {@code GregorianCalendar}. *

              - * The TimeZone set on the Calendar is only used to adjust the time offset. The - * TimeZone specified during the construction of the Parser will determine the - * TimeZone used in the formatted string. * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or - * StringBuffer. + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Date, Appendable)}. + */ + @Deprecated + StringBuffer format(Date date, StringBuffer buf); + + /** + *

              + * Formats a millisecond {@code long} value. + *

              + * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + String format(long millis); + + /** + *

              + * Formats a millisecond {@code long} value into the supplied + * {@code Appendable}. + *

              + * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or + * StringBuffer. * @return the specified string buffer * @since 3.5 */ - B format(Calendar calendar, B buf); + B format(long millis, B buf); + + /** + *

              + * Formats a millisecond {@code long} value into the supplied + * {@code StringBuffer}. + *

              + * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(long, Appendable)}. + */ + @Deprecated + StringBuffer format(long millis, StringBuffer buf); + + /** + *

              + * Formats a {@code Date}, {@code Calendar} or {@code Long} (milliseconds) + * object. + *

              + * + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + * @see java.text.DateFormat#format(Object, StringBuffer, FieldPosition) + */ + StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); + + /** + *

              + * Gets the locale used by this printer. + *

              + * + * @return the locale + */ + Locale getLocale(); // Accessors // ----------------------------------------------------------------------- @@ -181,27 +204,4 @@ public interface DatePrinter { * @return the time zone */ TimeZone getTimeZone(); - - /** - *

              - * Gets the locale used by this printer. - *

              - * - * @return the locale - */ - Locale getLocale(); - - /** - *

              - * Formats a {@code Date}, {@code Calendar} or {@code Long} (milliseconds) - * object. - *

              - * - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - * @see java.text.DateFormat#format(Object, StringBuffer, FieldPosition) - */ - StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos); } diff --git a/src/main/java/org/apache/commons/lang3/time/DateUtils.java b/src/main/java/org/apache/commons/lang3/time/DateUtils.java index 47906f41..38427293 100644 --- a/src/main/java/org/apache/commons/lang3/time/DateUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DateUtils.java @@ -57,66 +57,63 @@ import org.apache.commons.lang3.Validate; */ public class DateUtils { + // ----------------------------------------------------------------------- /** - * Number of milliseconds in a standard second. - * - * @since 2.1 + *

              + * Date iterator. + *

              */ - public static final long MILLIS_PER_SECOND = 1000; - /** - * Number of milliseconds in a standard minute. - * - * @since 2.1 - */ - public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; - /** - * Number of milliseconds in a standard hour. - * - * @since 2.1 - */ - public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; - /** - * Number of milliseconds in a standard day. - * - * @since 2.1 - */ - public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; + static class DateIterator implements Iterator { + private final Calendar endFinal; + private final Calendar spot; - /** - * This is half a month, so this represents whether a date is in the top or - * bottom half of the month. - */ - public static final int SEMI_MONTH = 1001; + /** + * Constructs a DateIterator that ranges from one date to another. + * + * @param startFinal start date (inclusive) + * @param endFinal end date (inclusive) + */ + DateIterator(final Calendar startFinal, final Calendar endFinal) { + this.endFinal = endFinal; + spot = startFinal; + spot.add(Calendar.DATE, -1); + } - private static final int[][] fields = { { Calendar.MILLISECOND }, { Calendar.SECOND }, { Calendar.MINUTE }, - { Calendar.HOUR_OF_DAY, Calendar.HOUR }, { Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM - /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */ - }, { Calendar.MONTH, SEMI_MONTH }, { Calendar.YEAR }, { Calendar.ERA } }; + /** + * Has the iterator not reached the end date yet? + * + * @return {@code true} if the iterator has yet to reach the end date + */ + @Override + public boolean hasNext() { + return spot.before(endFinal); + } - /** - * A week range, starting on Sunday. - */ - public static final int RANGE_WEEK_SUNDAY = 1; - /** - * A week range, starting on Monday. - */ - public static final int RANGE_WEEK_MONDAY = 2; - /** - * A week range, starting on the day focused. - */ - public static final int RANGE_WEEK_RELATIVE = 3; - /** - * A week range, centered around the day focused. - */ - public static final int RANGE_WEEK_CENTER = 4; - /** - * A month range, the week starting on Sunday. - */ - public static final int RANGE_MONTH_SUNDAY = 5; - /** - * A month range, the week starting on Monday. - */ - public static final int RANGE_MONTH_MONDAY = 6; + /** + * Returns the next calendar in the iteration + * + * @return Object calendar for the next date + */ + @Override + public Calendar next() { + if (spot.equals(endFinal)) { + throw new NoSuchElementException(); + } + spot.add(Calendar.DATE, 1); + return (Calendar) spot.clone(); + } + + /** + * Always throws UnsupportedOperationException. + * + * @throws UnsupportedOperationException Always thrown. + * @see java.util.Iterator#remove() + */ + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } /** * Calendar modification types. @@ -139,349 +136,85 @@ public class DateUtils { } /** - *

              - * {@code DateUtils} instances should NOT be constructed in standard - * programming. Instead, the static methods on the class should be used, such as - * {@code DateUtils.parseDate(str);}. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              - */ - public DateUtils() { - } - - // ----------------------------------------------------------------------- - /** - *

              - * Checks if two date objects are on the same day ignoring time. - *

              - * - *

              - * 28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. 28 Mar 2002 13:45 - * and 12 Mar 2002 13:45 would return false. - *

              - * - * @param date1 the first date, not altered, not null - * @param date2 the second date, not altered, not null - * @return true if they represent the same day - * @throws IllegalArgumentException if either date is {@code null} + * Number of milliseconds in a standard second. + * * @since 2.1 */ - public static boolean isSameDay(final Date date1, final Date date2) { - if (date1 == null || date2 == null) { - throw nullDateIllegalArgumentException(); - } - final Calendar cal1 = Calendar.getInstance(); - cal1.setTime(date1); - final Calendar cal2 = Calendar.getInstance(); - cal2.setTime(date2); - return isSameDay(cal1, cal2); - } - + public static final long MILLIS_PER_SECOND = 1000; /** - *

              - * Checks if two calendar objects are on the same day ignoring time. - *

              - * - *

              - * 28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. 28 Mar 2002 13:45 - * and 12 Mar 2002 13:45 would return false. - *

              - * - * @param cal1 the first calendar, not altered, not null - * @param cal2 the second calendar, not altered, not null - * @return true if they represent the same day - * @throws IllegalArgumentException if either calendar is {@code null} + * Number of milliseconds in a standard minute. + * * @since 2.1 */ - public static boolean isSameDay(final Calendar cal1, final Calendar cal2) { - if (cal1 == null || cal2 == null) { - throw nullDateIllegalArgumentException(); - } - return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) - && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); - } + public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND; - // ----------------------------------------------------------------------- /** - *

              - * Checks if two date objects represent the same instant in time. - *

              - * - *

              - * This method compares the long millisecond time of the two objects. - *

              - * - * @param date1 the first date, not altered, not null - * @param date2 the second date, not altered, not null - * @return true if they represent the same millisecond instant - * @throws IllegalArgumentException if either date is {@code null} + * Number of milliseconds in a standard hour. + * * @since 2.1 */ - public static boolean isSameInstant(final Date date1, final Date date2) { - if (date1 == null || date2 == null) { - throw nullDateIllegalArgumentException(); - } - return date1.getTime() == date2.getTime(); - } + public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE; /** - *

              - * Checks if two calendar objects represent the same instant in time. - *

              - * - *

              - * This method compares the long millisecond time of the two objects. - *

              - * - * @param cal1 the first calendar, not altered, not null - * @param cal2 the second calendar, not altered, not null - * @return true if they represent the same millisecond instant - * @throws IllegalArgumentException if either date is {@code null} + * Number of milliseconds in a standard day. + * * @since 2.1 */ - public static boolean isSameInstant(final Calendar cal1, final Calendar cal2) { - if (cal1 == null || cal2 == null) { - throw nullDateIllegalArgumentException(); - } - return cal1.getTime().getTime() == cal2.getTime().getTime(); - } + public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR; + + /** + * This is half a month, so this represents whether a date is in the top or + * bottom half of the month. + */ + public static final int SEMI_MONTH = 1001; + private static final int[][] fields = { { Calendar.MILLISECOND }, { Calendar.SECOND }, { Calendar.MINUTE }, + { Calendar.HOUR_OF_DAY, Calendar.HOUR }, { Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM + /* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */ + }, { Calendar.MONTH, SEMI_MONTH }, { Calendar.YEAR }, { Calendar.ERA } }; + /** + * A week range, starting on Sunday. + */ + public static final int RANGE_WEEK_SUNDAY = 1; + /** + * A week range, starting on Monday. + */ + public static final int RANGE_WEEK_MONDAY = 2; + /** + * A week range, starting on the day focused. + */ + public static final int RANGE_WEEK_RELATIVE = 3; + /** + * A week range, centered around the day focused. + */ + public static final int RANGE_WEEK_CENTER = 4; + + /** + * A month range, the week starting on Sunday. + */ + public static final int RANGE_MONTH_SUNDAY = 5; + + /** + * A month range, the week starting on Monday. + */ + public static final int RANGE_MONTH_MONDAY = 6; // ----------------------------------------------------------------------- /** - *

              - * Checks if two calendar objects represent the same local time. - *

              + * Adds to a date returning a new object. The original {@code Date} is + * unchanged. * - *

              - * This method compares the values of the fields of the two objects. In - * addition, both calendars must be the same of the same type. - *

              - * - * @param cal1 the first calendar, not altered, not null - * @param cal2 the second calendar, not altered, not null - * @return true if they represent the same millisecond instant - * @throws IllegalArgumentException if either date is {@code null} - * @since 2.1 - */ - public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2) { - if (cal1 == null || cal2 == null) { - throw nullDateIllegalArgumentException(); - } - return cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) - && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) - && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) - && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) - && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) - && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) - && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass(); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Parses a string representing a date by trying a variety of different parsers. - *

              - * - *

              - * The parse will try each parse pattern in turn. A parse is only deemed - * successful if it parses the whole of the input string. If no parse patterns - * match, a ParseException is thrown. - *

              - * The parser will be lenient toward the parsed date. - * - * @param str the date to parse, not null - * @param parsePatterns the date format patterns to use, see SimpleDateFormat, - * not null - * @return the parsed date - * @throws IllegalArgumentException if the date string or pattern array is null - * @throws ParseException if none of the date patterns were suitable - * (or there were none) - */ - public static Date parseDate(final String str, final String... parsePatterns) throws ParseException { - return parseDate(str, null, parsePatterns); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Parses a string representing a date by trying a variety of different parsers, - * using the default date format symbols for the given locale. - *

              - * - *

              - * The parse will try each parse pattern in turn. A parse is only deemed - * successful if it parses the whole of the input string. If no parse patterns - * match, a ParseException is thrown. - *

              - * The parser will be lenient toward the parsed date. - * - * @param str the date to parse, not null - * @param locale the locale whose date format symbols should be used. If - * {@code null}, the system locale is used (as per - * {@link #parseDate(String, String...)}). - * @param parsePatterns the date format patterns to use, see SimpleDateFormat, - * not null - * @return the parsed date - * @throws IllegalArgumentException if the date string or pattern array is null - * @throws ParseException if none of the date patterns were suitable - * (or there were none) - * @since 3.2 - */ - public static Date parseDate(final String str, final Locale locale, final String... parsePatterns) - throws ParseException { - return parseDateWithLeniency(str, locale, parsePatterns, true); - } - - // ----------------------------------------------------------------------- - /** - *

              - * Parses a string representing a date by trying a variety of different parsers. - *

              - * - *

              - * The parse will try each parse pattern in turn. A parse is only deemed - * successful if it parses the whole of the input string. If no parse patterns - * match, a ParseException is thrown. - *

              - * The parser parses strictly - it does not allow for dates such as "February - * 942, 1996". - * - * @param str the date to parse, not null - * @param parsePatterns the date format patterns to use, see SimpleDateFormat, - * not null - * @return the parsed date - * @throws IllegalArgumentException if the date string or pattern array is null - * @throws ParseException if none of the date patterns were suitable - * @since 2.5 - */ - public static Date parseDateStrictly(final String str, final String... parsePatterns) throws ParseException { - return parseDateStrictly(str, null, parsePatterns); - } - - /** - *

              - * Parses a string representing a date by trying a variety of different parsers, - * using the default date format symbols for the given locale.. - *

              - * - *

              - * The parse will try each parse pattern in turn. A parse is only deemed - * successful if it parses the whole of the input string. If no parse patterns - * match, a ParseException is thrown. - *

              - * The parser parses strictly - it does not allow for dates such as "February - * 942, 1996". - * - * @param str the date to parse, not null - * @param locale the locale whose date format symbols should be used. If - * {@code null}, the system locale is used (as per - * {@link #parseDateStrictly(String, String...)}). - * @param parsePatterns the date format patterns to use, see SimpleDateFormat, - * not null - * @return the parsed date - * @throws IllegalArgumentException if the date string or pattern array is null - * @throws ParseException if none of the date patterns were suitable - * @since 3.2 - */ - public static Date parseDateStrictly(final String str, final Locale locale, final String... parsePatterns) - throws ParseException { - return parseDateWithLeniency(str, locale, parsePatterns, false); - } - - /** - *

              - * Parses a string representing a date by trying a variety of different parsers. - *

              - * - *

              - * The parse will try each parse pattern in turn. A parse is only deemed - * successful if it parses the whole of the input string. If no parse patterns - * match, a ParseException is thrown. - *

              - * - * @param str the date to parse, not null - * @param locale the locale to use when interpreting the pattern, can be - * null in which case the default system locale is used - * @param parsePatterns the date format patterns to use, see SimpleDateFormat, - * not null - * @param lenient Specify whether or not date/time parsing is to be - * lenient. - * @return the parsed date - * @throws IllegalArgumentException if the date string or pattern array is null - * @throws ParseException if none of the date patterns were suitable - * @see java.util.Calendar#isLenient() - */ - private static Date parseDateWithLeniency(final String str, final Locale locale, final String[] parsePatterns, - final boolean lenient) throws ParseException { - if (str == null || parsePatterns == null) { - throw new IllegalArgumentException("Date and Patterns must not be null"); - } - - final TimeZone tz = TimeZone.getDefault(); - final Locale lcl = LocaleUtils.toLocale(locale); - final ParsePosition pos = new ParsePosition(0); - final Calendar calendar = Calendar.getInstance(tz, lcl); - calendar.setLenient(lenient); - - for (final String parsePattern : parsePatterns) { - final FastDateParser fdp = new FastDateParser(parsePattern, tz, lcl); - calendar.clear(); - try { - if (fdp.parse(str, pos, calendar) && pos.getIndex() == str.length()) { - return calendar.getTime(); - } - } catch (final IllegalArgumentException ignore) { - // leniency is preventing calendar from being set - } - pos.setIndex(0); - } - throw new ParseException("Unable to parse the date: " + str, -1); - } - - // ----------------------------------------------------------------------- - /** - * Adds a number of years to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to add, may be negative + * @param date the date, not null + * @param calendarField the calendar field to add to + * @param amount the amount to add, may be negative * @return the new {@code Date} with the amount added - * @throws IllegalArgumentException if the date is null + * @throws NullPointerException if the date is null */ - public static Date addYears(final Date date, final int amount) { - return add(date, Calendar.YEAR, amount); - } - - // ----------------------------------------------------------------------- - /** - * Adds a number of months to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to add, may be negative - * @return the new {@code Date} with the amount added - * @throws IllegalArgumentException if the date is null - */ - public static Date addMonths(final Date date, final int amount) { - return add(date, Calendar.MONTH, amount); - } - - // ----------------------------------------------------------------------- - /** - * Adds a number of weeks to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to add, may be negative - * @return the new {@code Date} with the amount added - * @throws IllegalArgumentException if the date is null - */ - public static Date addWeeks(final Date date, final int amount) { - return add(date, Calendar.WEEK_OF_YEAR, amount); + private static Date add(final Date date, final int calendarField, final int amount) { + validateDateNotNull(date); + final Calendar c = Calendar.getInstance(); + c.setTime(date); + c.add(calendarField, amount); + return c.getTime(); } // ----------------------------------------------------------------------- @@ -512,6 +245,20 @@ public class DateUtils { return add(date, Calendar.HOUR_OF_DAY, amount); } + // ----------------------------------------------------------------------- + /** + * Adds a number of milliseconds to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to add, may be negative + * @return the new {@code Date} with the amount added + * @throws IllegalArgumentException if the date is null + */ + public static Date addMilliseconds(final Date date, final int amount) { + return add(date, Calendar.MILLISECOND, amount); + } + // ----------------------------------------------------------------------- /** * Adds a number of minutes to a date returning a new object. The original @@ -526,6 +273,20 @@ public class DateUtils { return add(date, Calendar.MINUTE, amount); } + // ----------------------------------------------------------------------- + /** + * Adds a number of months to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to add, may be negative + * @return the new {@code Date} with the amount added + * @throws IllegalArgumentException if the date is null + */ + public static Date addMonths(final Date date, final int amount) { + return add(date, Calendar.MONTH, amount); + } + // ----------------------------------------------------------------------- /** * Adds a number of seconds to a date returning a new object. The original @@ -542,7 +303,7 @@ public class DateUtils { // ----------------------------------------------------------------------- /** - * Adds a number of milliseconds to a date returning a new object. The original + * Adds a number of weeks to a date returning a new object. The original * {@code Date} is unchanged. * * @param date the date, not null @@ -550,396 +311,50 @@ public class DateUtils { * @return the new {@code Date} with the amount added * @throws IllegalArgumentException if the date is null */ - public static Date addMilliseconds(final Date date, final int amount) { - return add(date, Calendar.MILLISECOND, amount); + public static Date addWeeks(final Date date, final int amount) { + return add(date, Calendar.WEEK_OF_YEAR, amount); } // ----------------------------------------------------------------------- /** - * Adds to a date returning a new object. The original {@code Date} is - * unchanged. + * Adds a number of years to a date returning a new object. The original + * {@code Date} is unchanged. * - * @param date the date, not null - * @param calendarField the calendar field to add to - * @param amount the amount to add, may be negative + * @param date the date, not null + * @param amount the amount to add, may be negative * @return the new {@code Date} with the amount added - * @throws NullPointerException if the date is null - */ - private static Date add(final Date date, final int calendarField, final int amount) { - validateDateNotNull(date); - final Calendar c = Calendar.getInstance(); - c.setTime(date); - c.add(calendarField, amount); - return c.getTime(); - } - - // ----------------------------------------------------------------------- - /** - * Sets the years field to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value * @throws IllegalArgumentException if the date is null - * @since 2.4 */ - public static Date setYears(final Date date, final int amount) { - return set(date, Calendar.YEAR, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the months field to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - public static Date setMonths(final Date date, final int amount) { - return set(date, Calendar.MONTH, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the day of month field to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - public static Date setDays(final Date date, final int amount) { - return set(date, Calendar.DAY_OF_MONTH, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the hours field to a date returning a new object. Hours range from 0-23. - * The original {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - public static Date setHours(final Date date, final int amount) { - return set(date, Calendar.HOUR_OF_DAY, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the minute field to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - public static Date setMinutes(final Date date, final int amount) { - return set(date, Calendar.MINUTE, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the seconds field to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - public static Date setSeconds(final Date date, final int amount) { - return set(date, Calendar.SECOND, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the milliseconds field to a date returning a new object. The original - * {@code Date} is unchanged. - * - * @param date the date, not null - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - public static Date setMilliseconds(final Date date, final int amount) { - return set(date, Calendar.MILLISECOND, amount); - } - - // ----------------------------------------------------------------------- - /** - * Sets the specified field to a date returning a new object. This does not use - * a lenient calendar. The original {@code Date} is unchanged. - * - * @param date the date, not null - * @param calendarField the {@code Calendar} field to set the amount to - * @param amount the amount to set - * @return a new {@code Date} set with the specified value - * @throws IllegalArgumentException if the date is null - * @since 2.4 - */ - private static Date set(final Date date, final int calendarField, final int amount) { - validateDateNotNull(date); - // getInstance() returns a new object, so this method is thread safe. - final Calendar c = Calendar.getInstance(); - c.setLenient(false); - c.setTime(date); - c.set(calendarField, amount); - return c.getTime(); - } - - // ----------------------------------------------------------------------- - /** - * Converts a {@code Date} into a {@code Calendar}. - * - * @param date the date to convert to a Calendar - * @return the created Calendar - * @throws NullPointerException if null is passed in - * @since 3.0 - */ - public static Calendar toCalendar(final Date date) { - final Calendar c = Calendar.getInstance(); - c.setTime(date); - return c; - } - - // ----------------------------------------------------------------------- - /** - * Converts a {@code Date} of a given {@code TimeZone} into a {@code Calendar} - * - * @param date the date to convert to a Calendar - * @param tz the time zone of the {@code date} - * @return the created Calendar - * @throws NullPointerException if {@code date} or {@code tz} is null - */ - public static Calendar toCalendar(final Date date, final TimeZone tz) { - final Calendar c = Calendar.getInstance(tz); - c.setTime(date); - return c; - } - - // ----------------------------------------------------------------------- - /** - *

              - * Rounds a date, leaving the field specified as the most significant field. - *

              - * - *

              - * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this - * was passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was - * passed with MONTH, it would return 1 April 2002 0:00:00.000. - *

              - * - *

              - * For a date in a time zone that handles the change to daylight saving time, - * rounding to Calendar.HOUR_OF_DAY will behave as follows. Suppose daylight - * saving time begins at 02:00 on March 30. Rounding a date that crosses this - * time would produce the following values: - *

              - *
                - *
              • March 30, 2003 01:10 rounds to March 30, 2003 01:00
              • - *
              • March 30, 2003 01:40 rounds to March 30, 2003 03:00
              • - *
              • March 30, 2003 02:10 rounds to March 30, 2003 03:00
              • - *
              • March 30, 2003 02:40 rounds to March 30, 2003 04:00
              • - *
              - * - * @param date the date to work with, not null - * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different rounded date, not null - * @throws ArithmeticException if the year is over 280 million - */ - public static Date round(final Date date, final int field) { - validateDateNotNull(date); - final Calendar gval = Calendar.getInstance(); - gval.setTime(date); - modify(gval, field, ModifyType.ROUND); - return gval.getTime(); + public static Date addYears(final Date date, final int amount) { + return add(date, Calendar.YEAR, amount); } /** *

              - * Rounds a date, leaving the field specified as the most significant field. - *

              - * - *

              - * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this - * was passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was - * passed with MONTH, it would return 1 April 2002 0:00:00.000. - *

              - * - *

              - * For a date in a time zone that handles the change to daylight saving time, - * rounding to Calendar.HOUR_OF_DAY will behave as follows. Suppose daylight - * saving time begins at 02:00 on March 30. Rounding a date that crosses this - * time would produce the following values: - *

              - *
                - *
              • March 30, 2003 01:10 rounds to March 30, 2003 01:00
              • - *
              • March 30, 2003 01:40 rounds to March 30, 2003 03:00
              • - *
              • March 30, 2003 02:10 rounds to March 30, 2003 03:00
              • - *
              • March 30, 2003 02:40 rounds to March 30, 2003 04:00
              • - *
              - * - * @param date the date to work with, not null - * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different rounded date, not null - * @throws NullPointerException if the date is {@code null} - * @throws ArithmeticException if the year is over 280 million - */ - public static Calendar round(final Calendar date, final int field) { - if (date == null) { - throw nullDateIllegalArgumentException(); - } - final Calendar rounded = (Calendar) date.clone(); - modify(rounded, field, ModifyType.ROUND); - return rounded; - } - - private static IllegalArgumentException nullDateIllegalArgumentException() { - return new IllegalArgumentException("The date must not be null"); - } - - /** - *

              - * Rounds a date, leaving the field specified as the most significant field. - *

              - * - *

              - * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this - * was passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was - * passed with MONTH, it would return 1 April 2002 0:00:00.000. - *

              - * - *

              - * For a date in a time zone that handles the change to daylight saving time, - * rounding to Calendar.HOUR_OF_DAY will behave as follows. Suppose daylight - * saving time begins at 02:00 on March 30. Rounding a date that crosses this - * time would produce the following values: - *

              - *
                - *
              • March 30, 2003 01:10 rounds to March 30, 2003 01:00
              • - *
              • March 30, 2003 01:40 rounds to March 30, 2003 03:00
              • - *
              • March 30, 2003 02:10 rounds to March 30, 2003 03:00
              • - *
              • March 30, 2003 02:40 rounds to March 30, 2003 04:00
              • - *
              - * - * @param date the date to work with, either {@code Date} or {@code Calendar}, - * not null - * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different rounded date, not null - * @throws NullPointerException if the date is {@code null} - * @throws ClassCastException if the object type is not a {@code Date} or - * {@code Calendar} - * @throws ArithmeticException if the year is over 280 million - */ - public static Date round(final Object date, final int field) { - if (date == null) { - throw nullDateIllegalArgumentException(); - } - if (date instanceof Date) { - return round((Date) date, field); - } else if (date instanceof Calendar) { - return round((Calendar) date, field).getTime(); - } else { - throw new ClassCastException("Could not round " + date); - } - } - - // ----------------------------------------------------------------------- - /** - *

              - * Truncates a date, leaving the field specified as the most significant field. + * Gets a date ceiling, leaving the field specified as the most significant + * field. *

              * *

              * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you - * passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was - * passed with MONTH, it would return 1 Mar 2002 0:00:00.000. + * passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was + * passed with MONTH, it would return 1 Apr 2002 0:00:00.000. *

              * * @param date the date to work with, not null * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different truncated date, not null + * @return the different ceil date, not null * @throws NullPointerException if the date is {@code null} * @throws ArithmeticException if the year is over 280 million + * @since 2.5 */ - public static Date truncate(final Date date, final int field) { - validateDateNotNull(date); - final Calendar gval = Calendar.getInstance(); - gval.setTime(date); - modify(gval, field, ModifyType.TRUNCATE); - return gval.getTime(); - } - - /** - *

              - * Truncates a date, leaving the field specified as the most significant field. - *

              - * - *

              - * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you - * passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was - * passed with MONTH, it would return 1 Mar 2002 0:00:00.000. - *

              - * - * @param date the date to work with, not null - * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different truncated date, not null - * @throws NullPointerException if the date is {@code null} - * @throws ArithmeticException if the year is over 280 million - */ - public static Calendar truncate(final Calendar date, final int field) { + public static Calendar ceiling(final Calendar date, final int field) { if (date == null) { throw nullDateIllegalArgumentException(); } - final Calendar truncated = (Calendar) date.clone(); - modify(truncated, field, ModifyType.TRUNCATE); - return truncated; - } - - /** - *

              - * Truncates a date, leaving the field specified as the most significant field. - *

              - * - *

              - * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you - * passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was - * passed with MONTH, it would return 1 Mar 2002 0:00:00.000. - *

              - * - * @param date the date to work with, either {@code Date} or {@code Calendar}, - * not null - * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different truncated date, not null - * @throws NullPointerException if the date is {@code null} - * @throws ClassCastException if the object type is not a {@code Date} or - * {@code Calendar} - * @throws ArithmeticException if the year is over 280 million - */ - public static Date truncate(final Object date, final int field) { - if (date == null) { - throw nullDateIllegalArgumentException(); - } - if (date instanceof Date) { - return truncate((Date) date, field); - } else if (date instanceof Calendar) { - return truncate((Calendar) date, field).getTime(); - } else { - throw new ClassCastException("Could not truncate " + date); - } + final Calendar ceiled = (Calendar) date.clone(); + modify(ceiled, field, ModifyType.CEILING); + return ceiled; } // ----------------------------------------------------------------------- @@ -970,34 +385,6 @@ public class DateUtils { return gval.getTime(); } - /** - *

              - * Gets a date ceiling, leaving the field specified as the most significant - * field. - *

              - * - *

              - * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you - * passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was - * passed with MONTH, it would return 1 Apr 2002 0:00:00.000. - *

              - * - * @param date the date to work with, not null - * @param field the field from {@code Calendar} or {@code SEMI_MONTH} - * @return the different ceil date, not null - * @throws NullPointerException if the date is {@code null} - * @throws ArithmeticException if the year is over 280 million - * @since 2.5 - */ - public static Calendar ceiling(final Calendar date, final int field) { - if (date == null) { - throw nullDateIllegalArgumentException(); - } - final Calendar ceiled = (Calendar) date.clone(); - modify(ceiled, field, ModifyType.CEILING); - return ceiled; - } - /** *

              * Gets a date ceiling, leaving the field specified as the most significant @@ -1033,6 +420,833 @@ public class DateUtils { } } + /** + * Gets a Calendar fragment for any unit. + * + * @param calendar the calendar to work with, not null + * @param fragment the Calendar field part of calendar to calculate + * @param unit the time unit + * @return number of units within the fragment of the calendar + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + private static long getFragment(final Calendar calendar, final int fragment, final TimeUnit unit) { + if (calendar == null) { + throw nullDateIllegalArgumentException(); + } + + long result = 0; + + final int offset = (unit == TimeUnit.DAYS) ? 0 : 1; + + // Fragments bigger than a day require a breakdown to days + switch (fragment) { + case Calendar.YEAR: + result += unit.convert(calendar.get(Calendar.DAY_OF_YEAR) - offset, TimeUnit.DAYS); + break; + case Calendar.MONTH: + result += unit.convert(calendar.get(Calendar.DAY_OF_MONTH) - offset, TimeUnit.DAYS); + break; + default: + break; + } + + switch (fragment) { + // Number of days already calculated for these cases + case Calendar.YEAR: + case Calendar.MONTH: + + // The rest of the valid cases + case Calendar.DAY_OF_YEAR: + case Calendar.DATE: + result += unit.convert(calendar.get(Calendar.HOUR_OF_DAY), TimeUnit.HOURS); + //$FALL-THROUGH$ + case Calendar.HOUR_OF_DAY: + result += unit.convert(calendar.get(Calendar.MINUTE), TimeUnit.MINUTES); + //$FALL-THROUGH$ + case Calendar.MINUTE: + result += unit.convert(calendar.get(Calendar.SECOND), TimeUnit.SECONDS); + //$FALL-THROUGH$ + case Calendar.SECOND: + result += unit.convert(calendar.get(Calendar.MILLISECOND), TimeUnit.MILLISECONDS); + break; + case Calendar.MILLISECOND: + break; // never useful + default: + throw new IllegalArgumentException("The fragment " + fragment + " is not supported"); + } + return result; + } + + /** + * Gets a Date fragment for any unit. + * + * @param date the date to work with, not null + * @param fragment the Calendar field part of date to calculate + * @param unit the time unit + * @return number of units within the fragment of the date + * @throws NullPointerException if the date is {@code null} + * @throws IllegalArgumentException if fragment is not supported + * @since 2.4 + */ + private static long getFragment(final Date date, final int fragment, final TimeUnit unit) { + validateDateNotNull(date); + final Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + return getFragment(calendar, fragment, unit); + } + + /** + *

              + * Returns the number of days within the fragment. All datefields greater than + * the fragment will be ignored. + *

              + * + *

              + * Asking the days of any date will only return the number of days of the + * current month (resulting in a number between 1 and 31). This method will + * retrieve the number of days for any fragment. For example, if you want to + * calculate the number of days past this year, your fragment is Calendar.YEAR. + * The result will be all days of the past month(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a DAY field will return + * 0. + *

              + * + *
                + *
              • January 28, 2008 with Calendar.MONTH as fragment will return 28 + * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
              • + *
              • February 28, 2008 with Calendar.MONTH as fragment will return 28 + * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
              • + *
              • January 28, 2008 with Calendar.YEAR as fragment will return 28 + * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
              • + *
              • February 28, 2008 with Calendar.YEAR as fragment will return 59 + * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
              • + *
              • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 (a + * millisecond cannot be split in days)
              • + *
              + * + * @param calendar the calendar to work with, not null + * @param fragment the {@code Calendar} field part of calendar to calculate + * @return number of days within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInDays(final Calendar calendar, final int fragment) { + return getFragment(calendar, fragment, TimeUnit.DAYS); + } + + /** + *

              + * Returns the number of days within the fragment. All datefields greater than + * the fragment will be ignored. + *

              + * + *

              + * Asking the days of any date will only return the number of days of the + * current month (resulting in a number between 1 and 31). This method will + * retrieve the number of days for any fragment. For example, if you want to + * calculate the number of days past this year, your fragment is Calendar.YEAR. + * The result will be all days of the past month(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a DAY field will return + * 0. + *

              + * + *
                + *
              • January 28, 2008 with Calendar.MONTH as fragment will return 28 + * (equivalent to deprecated date.getDay())
              • + *
              • February 28, 2008 with Calendar.MONTH as fragment will return 28 + * (equivalent to deprecated date.getDay())
              • + *
              • January 28, 2008 with Calendar.YEAR as fragment will return 28
              • + *
              • February 28, 2008 with Calendar.YEAR as fragment will return 59
              • + *
              • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 (a + * millisecond cannot be split in days)
              • + *
              + * + * @param date the date to work with, not null + * @param fragment the {@code Calendar} field part of date to calculate + * @return number of days within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInDays(final Date date, final int fragment) { + return getFragment(date, fragment, TimeUnit.DAYS); + } + + /** + *

              + * Returns the number of hours within the fragment. All datefields greater than + * the fragment will be ignored. + *

              + * + *

              + * Asking the hours of any date will only return the number of hours of the + * current day (resulting in a number between 0 and 23). This method will + * retrieve the number of hours for any fragment. For example, if you want to + * calculate the number of hours past this month, your fragment is + * Calendar.MONTH. The result will be all hours of the past day(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a HOUR field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will + * return 7 (equivalent to calendar.get(Calendar.HOUR_OF_DAY))
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will + * return 7 (equivalent to calendar.get(Calendar.HOUR_OF_DAY))
              • + *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 7
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 127 (5*24 + 7)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in hours)
              • + *
              + * + * @param calendar the calendar to work with, not null + * @param fragment the {@code Calendar} field part of calendar to calculate + * @return number of hours within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInHours(final Calendar calendar, final int fragment) { + return getFragment(calendar, fragment, TimeUnit.HOURS); + } + + /** + *

              + * Returns the number of hours within the fragment. All datefields greater than + * the fragment will be ignored. + *

              + * + *

              + * Asking the hours of any date will only return the number of hours of the + * current day (resulting in a number between 0 and 23). This method will + * retrieve the number of hours for any fragment. For example, if you want to + * calculate the number of hours past this month, your fragment is + * Calendar.MONTH. The result will be all hours of the past day(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a HOUR field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will + * return 7 (equivalent to deprecated date.getHours())
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will + * return 7 (equivalent to deprecated date.getHours())
              • + *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 7
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 127 (5*24 + 7)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in hours)
              • + *
              + * + * @param date the date to work with, not null + * @param fragment the {@code Calendar} field part of date to calculate + * @return number of hours within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInHours(final Date date, final int fragment) { + return getFragment(date, fragment, TimeUnit.HOURS); + } + + /** + *

              + * Returns the number of milliseconds within the fragment. All datefields + * greater than the fragment will be ignored. + *

              + * + *

              + * Asking the milliseconds of any date will only return the number of + * milliseconds of the current second (resulting in a number between 0 and 999). + * This method will retrieve the number of milliseconds for any fragment. For + * example, if you want to calculate the number of seconds past today, your + * fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will be all + * seconds of the past hour(s), minutes(s) and second(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a MILLISECOND field + * will return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return + * 538 (equivalent to calendar.get(Calendar.MILLISECOND))
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return + * 538 (equivalent to calendar.get(Calendar.MILLISECOND))
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return + * 10538 (10*1000 + 538)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in milliseconds)
              • + *
              + * + * @param calendar the calendar to work with, not null + * @param fragment the {@code Calendar} field part of calendar to calculate + * @return number of milliseconds within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment) { + return getFragment(calendar, fragment, TimeUnit.MILLISECONDS); + } + + /** + *

              + * Returns the number of milliseconds within the fragment. All datefields + * greater than the fragment will be ignored. + *

              + * + *

              + * Asking the milliseconds of any date will only return the number of + * milliseconds of the current second (resulting in a number between 0 and 999). + * This method will retrieve the number of milliseconds for any fragment. For + * example, if you want to calculate the number of milliseconds past today, your + * fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will be all + * milliseconds of the past hour(s), minutes(s) and second(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a SECOND field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return + * 538
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return + * 538
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return + * 10538 (10*1000 + 538)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in milliseconds)
              • + *
              + * + * @param date the date to work with, not null + * @param fragment the {@code Calendar} field part of date to calculate + * @return number of milliseconds within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInMilliseconds(final Date date, final int fragment) { + return getFragment(date, fragment, TimeUnit.MILLISECONDS); + } + + /** + *

              + * Returns the number of minutes within the fragment. All datefields greater + * than the fragment will be ignored. + *

              + * + *

              + * Asking the minutes of any date will only return the number of minutes of the + * current hour (resulting in a number between 0 and 59). This method will + * retrieve the number of minutes for any fragment. For example, if you want to + * calculate the number of minutes past this month, your fragment is + * Calendar.MONTH. The result will be all minutes of the past day(s) and + * hour(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a MINUTE field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will + * return 15 (equivalent to calendar.get(Calendar.MINUTES))
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will + * return 15 (equivalent to calendar.get(Calendar.MINUTES))
              • + *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 15
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 435 (7*60 + 15)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in minutes)
              • + *
              + * + * @param calendar the calendar to work with, not null + * @param fragment the {@code Calendar} field part of calendar to calculate + * @return number of minutes within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInMinutes(final Calendar calendar, final int fragment) { + return getFragment(calendar, fragment, TimeUnit.MINUTES); + } + + /** + *

              + * Returns the number of minutes within the fragment. All datefields greater + * than the fragment will be ignored. + *

              + * + *

              + * Asking the minutes of any date will only return the number of minutes of the + * current hour (resulting in a number between 0 and 59). This method will + * retrieve the number of minutes for any fragment. For example, if you want to + * calculate the number of minutes past this month, your fragment is + * Calendar.MONTH. The result will be all minutes of the past day(s) and + * hour(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a MINUTE field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will + * return 15 (equivalent to deprecated date.getMinutes())
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will + * return 15 (equivalent to deprecated date.getMinutes())
              • + *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 15
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return + * 435 (7*60 + 15)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in minutes)
              • + *
              + * + * @param date the date to work with, not null + * @param fragment the {@code Calendar} field part of date to calculate + * @return number of minutes within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInMinutes(final Date date, final int fragment) { + return getFragment(date, fragment, TimeUnit.MINUTES); + } + + /** + *

              + * Returns the number of seconds within the fragment. All datefields greater + * than the fragment will be ignored. + *

              + * + *

              + * Asking the seconds of any date will only return the number of seconds of the + * current minute (resulting in a number between 0 and 59). This method will + * retrieve the number of seconds for any fragment. For example, if you want to + * calculate the number of seconds past today, your fragment is Calendar.DATE or + * Calendar.DAY_OF_YEAR. The result will be all seconds of the past hour(s) and + * minutes(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a SECOND field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return + * 10 (equivalent to calendar.get(Calendar.SECOND))
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return + * 10 (equivalent to calendar.get(Calendar.SECOND))
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will + * return 26110 (7*3600 + 15*60 + 10)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in seconds)
              • + *
              + * + * @param calendar the calendar to work with, not null + * @param fragment the {@code Calendar} field part of calendar to calculate + * @return number of seconds within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInSeconds(final Calendar calendar, final int fragment) { + return getFragment(calendar, fragment, TimeUnit.SECONDS); + } + + /** + *

              + * Returns the number of seconds within the fragment. All datefields greater + * than the fragment will be ignored. + *

              + * + *

              + * Asking the seconds of any date will only return the number of seconds of the + * current minute (resulting in a number between 0 and 59). This method will + * retrieve the number of seconds for any fragment. For example, if you want to + * calculate the number of seconds past today, your fragment is Calendar.DATE or + * Calendar.DAY_OF_YEAR. The result will be all seconds of the past hour(s) and + * minutes(s). + *

              + * + *

              + * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR + * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and + * Calendar.MILLISECOND A fragment less than or equal to a SECOND field will + * return 0. + *

              + * + *
                + *
              • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return + * 10 (equivalent to deprecated date.getSeconds())
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return + * 10 (equivalent to deprecated date.getSeconds())
              • + *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will + * return 26110 (7*3600 + 15*60 + 10)
              • + *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will + * return 0 (a millisecond cannot be split in seconds)
              • + *
              + * + * @param date the date to work with, not null + * @param fragment the {@code Calendar} field part of date to calculate + * @return number of seconds within the fragment of date + * @throws IllegalArgumentException if the date is {@code null} or fragment is + * not supported + * @since 2.4 + */ + public static long getFragmentInSeconds(final Date date, final int fragment) { + return getFragment(date, fragment, TimeUnit.SECONDS); + } + + /** + *

              + * Checks if two calendar objects are on the same day ignoring time. + *

              + * + *

              + * 28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. 28 Mar 2002 13:45 + * and 12 Mar 2002 13:45 would return false. + *

              + * + * @param cal1 the first calendar, not altered, not null + * @param cal2 the second calendar, not altered, not null + * @return true if they represent the same day + * @throws IllegalArgumentException if either calendar is {@code null} + * @since 2.1 + */ + public static boolean isSameDay(final Calendar cal1, final Calendar cal2) { + if (cal1 == null || cal2 == null) { + throw nullDateIllegalArgumentException(); + } + return cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) + && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Checks if two date objects are on the same day ignoring time. + *

              + * + *

              + * 28 Mar 2002 13:45 and 28 Mar 2002 06:01 would return true. 28 Mar 2002 13:45 + * and 12 Mar 2002 13:45 would return false. + *

              + * + * @param date1 the first date, not altered, not null + * @param date2 the second date, not altered, not null + * @return true if they represent the same day + * @throws IllegalArgumentException if either date is {@code null} + * @since 2.1 + */ + public static boolean isSameDay(final Date date1, final Date date2) { + if (date1 == null || date2 == null) { + throw nullDateIllegalArgumentException(); + } + final Calendar cal1 = Calendar.getInstance(); + cal1.setTime(date1); + final Calendar cal2 = Calendar.getInstance(); + cal2.setTime(date2); + return isSameDay(cal1, cal2); + } + + /** + *

              + * Checks if two calendar objects represent the same instant in time. + *

              + * + *

              + * This method compares the long millisecond time of the two objects. + *

              + * + * @param cal1 the first calendar, not altered, not null + * @param cal2 the second calendar, not altered, not null + * @return true if they represent the same millisecond instant + * @throws IllegalArgumentException if either date is {@code null} + * @since 2.1 + */ + public static boolean isSameInstant(final Calendar cal1, final Calendar cal2) { + if (cal1 == null || cal2 == null) { + throw nullDateIllegalArgumentException(); + } + return cal1.getTime().getTime() == cal2.getTime().getTime(); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Checks if two date objects represent the same instant in time. + *

              + * + *

              + * This method compares the long millisecond time of the two objects. + *

              + * + * @param date1 the first date, not altered, not null + * @param date2 the second date, not altered, not null + * @return true if they represent the same millisecond instant + * @throws IllegalArgumentException if either date is {@code null} + * @since 2.1 + */ + public static boolean isSameInstant(final Date date1, final Date date2) { + if (date1 == null || date2 == null) { + throw nullDateIllegalArgumentException(); + } + return date1.getTime() == date2.getTime(); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Checks if two calendar objects represent the same local time. + *

              + * + *

              + * This method compares the values of the fields of the two objects. In + * addition, both calendars must be the same of the same type. + *

              + * + * @param cal1 the first calendar, not altered, not null + * @param cal2 the second calendar, not altered, not null + * @return true if they represent the same millisecond instant + * @throws IllegalArgumentException if either date is {@code null} + * @since 2.1 + */ + public static boolean isSameLocalTime(final Calendar cal1, final Calendar cal2) { + if (cal1 == null || cal2 == null) { + throw nullDateIllegalArgumentException(); + } + return cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) + && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) + && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) + && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) + && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) + && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) + && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass(); + } + + /** + *

              + * Constructs an {@code Iterator} over each day in a date range defined by a + * focus date and range style. + *

              + * + *

              + * For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} + * will return an {@code Iterator} that starts with Sunday, June 30, 2002 and + * ends with Saturday, August 3, 2002, returning a Calendar instance for each + * intermediate day. + *

              + * + *

              + * This method provides an iterator that returns Calendar objects. The days are + * progressed using {@link Calendar#add(int, int)}. + *

              + * + * @param focus the date to work with, not null + * @param rangeStyle the style constant to use. Must be one of + * {@link DateUtils#RANGE_MONTH_SUNDAY}, + * {@link DateUtils#RANGE_MONTH_MONDAY}, + * {@link DateUtils#RANGE_WEEK_SUNDAY}, + * {@link DateUtils#RANGE_WEEK_MONDAY}, + * {@link DateUtils#RANGE_WEEK_RELATIVE}, + * {@link DateUtils#RANGE_WEEK_CENTER} + * @return the date iterator, not null + * @throws IllegalArgumentException if the date is {@code null} + * @throws IllegalArgumentException if the rangeStyle is invalid + */ + public static Iterator iterator(final Calendar focus, final int rangeStyle) { + if (focus == null) { + throw nullDateIllegalArgumentException(); + } + Calendar start = null; + Calendar end = null; + int startCutoff = Calendar.SUNDAY; + int endCutoff = Calendar.SATURDAY; + switch (rangeStyle) { + case RANGE_MONTH_SUNDAY: + case RANGE_MONTH_MONDAY: + // Set start to the first of the month + start = truncate(focus, Calendar.MONTH); + // Set end to the last of the month + end = (Calendar) start.clone(); + end.add(Calendar.MONTH, 1); + end.add(Calendar.DATE, -1); + // Loop start back to the previous sunday or monday + if (rangeStyle == RANGE_MONTH_MONDAY) { + startCutoff = Calendar.MONDAY; + endCutoff = Calendar.SUNDAY; + } + break; + case RANGE_WEEK_SUNDAY: + case RANGE_WEEK_MONDAY: + case RANGE_WEEK_RELATIVE: + case RANGE_WEEK_CENTER: + // Set start and end to the current date + start = truncate(focus, Calendar.DATE); + end = truncate(focus, Calendar.DATE); + switch (rangeStyle) { + case RANGE_WEEK_SUNDAY: + // already set by default + break; + case RANGE_WEEK_MONDAY: + startCutoff = Calendar.MONDAY; + endCutoff = Calendar.SUNDAY; + break; + case RANGE_WEEK_RELATIVE: + startCutoff = focus.get(Calendar.DAY_OF_WEEK); + endCutoff = startCutoff - 1; + break; + case RANGE_WEEK_CENTER: + startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3; + endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3; + break; + default: + break; + } + break; + default: + throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid."); + } + if (startCutoff < Calendar.SUNDAY) { + startCutoff += 7; + } + if (startCutoff > Calendar.SATURDAY) { + startCutoff -= 7; + } + if (endCutoff < Calendar.SUNDAY) { + endCutoff += 7; + } + if (endCutoff > Calendar.SATURDAY) { + endCutoff -= 7; + } + while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) { + start.add(Calendar.DATE, -1); + } + while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) { + end.add(Calendar.DATE, 1); + } + return new DateIterator(start, end); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Constructs an {@code Iterator} over each day in a date range defined by a + * focus date and range style. + *

              + * + *

              + * For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} + * will return an {@code Iterator} that starts with Sunday, June 30, 2002 and + * ends with Saturday, August 3, 2002, returning a Calendar instance for each + * intermediate day. + *

              + * + *

              + * This method provides an iterator that returns Calendar objects. The days are + * progressed using {@link Calendar#add(int, int)}. + *

              + * + * @param focus the date to work with, not null + * @param rangeStyle the style constant to use. Must be one of + * {@link DateUtils#RANGE_MONTH_SUNDAY}, + * {@link DateUtils#RANGE_MONTH_MONDAY}, + * {@link DateUtils#RANGE_WEEK_SUNDAY}, + * {@link DateUtils#RANGE_WEEK_MONDAY}, + * {@link DateUtils#RANGE_WEEK_RELATIVE}, + * {@link DateUtils#RANGE_WEEK_CENTER} + * @return the date iterator, not null, not null + * @throws NullPointerException if the date is {@code null} + * @throws IllegalArgumentException if the rangeStyle is invalid + */ + public static Iterator iterator(final Date focus, final int rangeStyle) { + validateDateNotNull(focus); + final Calendar gval = Calendar.getInstance(); + gval.setTime(focus); + return iterator(gval, rangeStyle); + } + + /** + *

              + * Constructs an {@code Iterator} over each day in a date range defined by a + * focus date and range style. + *

              + * + *

              + * For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} + * will return an {@code Iterator} that starts with Sunday, June 30, 2002 and + * ends with Saturday, August 3, 2002, returning a Calendar instance for each + * intermediate day. + *

              + * + * @param focus the date to work with, either {@code Date} or + * {@code Calendar}, not null + * @param rangeStyle the style constant to use. Must be one of the range styles + * listed for the {@link #iterator(Calendar, int)} method. + * @return the date iterator, not null + * @throws IllegalArgumentException if the date is {@code null} + * @throws ClassCastException if the object type is not a {@code Date} or + * {@code Calendar} + */ + public static Iterator iterator(final Object focus, final int rangeStyle) { + if (focus == null) { + throw nullDateIllegalArgumentException(); + } + if (focus instanceof Date) { + return iterator((Date) focus, rangeStyle); + } else if (focus instanceof Calendar) { + return iterator((Calendar) focus, rangeStyle); + } else { + throw new ClassCastException("Could not iterate based on " + focus); + } + } + // ----------------------------------------------------------------------- /** *

              @@ -1186,738 +1400,535 @@ public class DateUtils { } + private static IllegalArgumentException nullDateIllegalArgumentException() { + return new IllegalArgumentException("The date must not be null"); + } + // ----------------------------------------------------------------------- /** *

              - * Constructs an {@code Iterator} over each day in a date range defined by a - * focus date and range style. + * Parses a string representing a date by trying a variety of different parsers, + * using the default date format symbols for the given locale. *

              * *

              - * For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} - * will return an {@code Iterator} that starts with Sunday, June 30, 2002 and - * ends with Saturday, August 3, 2002, returning a Calendar instance for each - * intermediate day. + * The parse will try each parse pattern in turn. A parse is only deemed + * successful if it parses the whole of the input string. If no parse patterns + * match, a ParseException is thrown. *

              + * The parser will be lenient toward the parsed date. * - *

              - * This method provides an iterator that returns Calendar objects. The days are - * progressed using {@link Calendar#add(int, int)}. - *

              - * - * @param focus the date to work with, not null - * @param rangeStyle the style constant to use. Must be one of - * {@link DateUtils#RANGE_MONTH_SUNDAY}, - * {@link DateUtils#RANGE_MONTH_MONDAY}, - * {@link DateUtils#RANGE_WEEK_SUNDAY}, - * {@link DateUtils#RANGE_WEEK_MONDAY}, - * {@link DateUtils#RANGE_WEEK_RELATIVE}, - * {@link DateUtils#RANGE_WEEK_CENTER} - * @return the date iterator, not null, not null - * @throws NullPointerException if the date is {@code null} - * @throws IllegalArgumentException if the rangeStyle is invalid + * @param str the date to parse, not null + * @param locale the locale whose date format symbols should be used. If + * {@code null}, the system locale is used (as per + * {@link #parseDate(String, String...)}). + * @param parsePatterns the date format patterns to use, see SimpleDateFormat, + * not null + * @return the parsed date + * @throws IllegalArgumentException if the date string or pattern array is null + * @throws ParseException if none of the date patterns were suitable + * (or there were none) + * @since 3.2 */ - public static Iterator iterator(final Date focus, final int rangeStyle) { - validateDateNotNull(focus); - final Calendar gval = Calendar.getInstance(); - gval.setTime(focus); - return iterator(gval, rangeStyle); + public static Date parseDate(final String str, final Locale locale, final String... parsePatterns) + throws ParseException { + return parseDateWithLeniency(str, locale, parsePatterns, true); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Parses a string representing a date by trying a variety of different parsers. + *

              + * + *

              + * The parse will try each parse pattern in turn. A parse is only deemed + * successful if it parses the whole of the input string. If no parse patterns + * match, a ParseException is thrown. + *

              + * The parser will be lenient toward the parsed date. + * + * @param str the date to parse, not null + * @param parsePatterns the date format patterns to use, see SimpleDateFormat, + * not null + * @return the parsed date + * @throws IllegalArgumentException if the date string or pattern array is null + * @throws ParseException if none of the date patterns were suitable + * (or there were none) + */ + public static Date parseDate(final String str, final String... parsePatterns) throws ParseException { + return parseDate(str, null, parsePatterns); } /** *

              - * Constructs an {@code Iterator} over each day in a date range defined by a - * focus date and range style. + * Parses a string representing a date by trying a variety of different parsers, + * using the default date format symbols for the given locale.. *

              * *

              - * For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} - * will return an {@code Iterator} that starts with Sunday, June 30, 2002 and - * ends with Saturday, August 3, 2002, returning a Calendar instance for each - * intermediate day. + * The parse will try each parse pattern in turn. A parse is only deemed + * successful if it parses the whole of the input string. If no parse patterns + * match, a ParseException is thrown. *

              + * The parser parses strictly - it does not allow for dates such as "February + * 942, 1996". * - *

              - * This method provides an iterator that returns Calendar objects. The days are - * progressed using {@link Calendar#add(int, int)}. - *

              - * - * @param focus the date to work with, not null - * @param rangeStyle the style constant to use. Must be one of - * {@link DateUtils#RANGE_MONTH_SUNDAY}, - * {@link DateUtils#RANGE_MONTH_MONDAY}, - * {@link DateUtils#RANGE_WEEK_SUNDAY}, - * {@link DateUtils#RANGE_WEEK_MONDAY}, - * {@link DateUtils#RANGE_WEEK_RELATIVE}, - * {@link DateUtils#RANGE_WEEK_CENTER} - * @return the date iterator, not null - * @throws IllegalArgumentException if the date is {@code null} - * @throws IllegalArgumentException if the rangeStyle is invalid + * @param str the date to parse, not null + * @param locale the locale whose date format symbols should be used. If + * {@code null}, the system locale is used (as per + * {@link #parseDateStrictly(String, String...)}). + * @param parsePatterns the date format patterns to use, see SimpleDateFormat, + * not null + * @return the parsed date + * @throws IllegalArgumentException if the date string or pattern array is null + * @throws ParseException if none of the date patterns were suitable + * @since 3.2 */ - public static Iterator iterator(final Calendar focus, final int rangeStyle) { - if (focus == null) { + public static Date parseDateStrictly(final String str, final Locale locale, final String... parsePatterns) + throws ParseException { + return parseDateWithLeniency(str, locale, parsePatterns, false); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Parses a string representing a date by trying a variety of different parsers. + *

              + * + *

              + * The parse will try each parse pattern in turn. A parse is only deemed + * successful if it parses the whole of the input string. If no parse patterns + * match, a ParseException is thrown. + *

              + * The parser parses strictly - it does not allow for dates such as "February + * 942, 1996". + * + * @param str the date to parse, not null + * @param parsePatterns the date format patterns to use, see SimpleDateFormat, + * not null + * @return the parsed date + * @throws IllegalArgumentException if the date string or pattern array is null + * @throws ParseException if none of the date patterns were suitable + * @since 2.5 + */ + public static Date parseDateStrictly(final String str, final String... parsePatterns) throws ParseException { + return parseDateStrictly(str, null, parsePatterns); + } + + /** + *

              + * Parses a string representing a date by trying a variety of different parsers. + *

              + * + *

              + * The parse will try each parse pattern in turn. A parse is only deemed + * successful if it parses the whole of the input string. If no parse patterns + * match, a ParseException is thrown. + *

              + * + * @param str the date to parse, not null + * @param locale the locale to use when interpreting the pattern, can be + * null in which case the default system locale is used + * @param parsePatterns the date format patterns to use, see SimpleDateFormat, + * not null + * @param lenient Specify whether or not date/time parsing is to be + * lenient. + * @return the parsed date + * @throws IllegalArgumentException if the date string or pattern array is null + * @throws ParseException if none of the date patterns were suitable + * @see java.util.Calendar#isLenient() + */ + private static Date parseDateWithLeniency(final String str, final Locale locale, final String[] parsePatterns, + final boolean lenient) throws ParseException { + if (str == null || parsePatterns == null) { + throw new IllegalArgumentException("Date and Patterns must not be null"); + } + + final TimeZone tz = TimeZone.getDefault(); + final Locale lcl = LocaleUtils.toLocale(locale); + final ParsePosition pos = new ParsePosition(0); + final Calendar calendar = Calendar.getInstance(tz, lcl); + calendar.setLenient(lenient); + + for (final String parsePattern : parsePatterns) { + final FastDateParser fdp = new FastDateParser(parsePattern, tz, lcl); + calendar.clear(); + try { + if (fdp.parse(str, pos, calendar) && pos.getIndex() == str.length()) { + return calendar.getTime(); + } + } catch (final IllegalArgumentException ignore) { + // leniency is preventing calendar from being set + } + pos.setIndex(0); + } + throw new ParseException("Unable to parse the date: " + str, -1); + } + + /** + *

              + * Rounds a date, leaving the field specified as the most significant field. + *

              + * + *

              + * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this + * was passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was + * passed with MONTH, it would return 1 April 2002 0:00:00.000. + *

              + * + *

              + * For a date in a time zone that handles the change to daylight saving time, + * rounding to Calendar.HOUR_OF_DAY will behave as follows. Suppose daylight + * saving time begins at 02:00 on March 30. Rounding a date that crosses this + * time would produce the following values: + *

              + *
                + *
              • March 30, 2003 01:10 rounds to March 30, 2003 01:00
              • + *
              • March 30, 2003 01:40 rounds to March 30, 2003 03:00
              • + *
              • March 30, 2003 02:10 rounds to March 30, 2003 03:00
              • + *
              • March 30, 2003 02:40 rounds to March 30, 2003 04:00
              • + *
              + * + * @param date the date to work with, not null + * @param field the field from {@code Calendar} or {@code SEMI_MONTH} + * @return the different rounded date, not null + * @throws NullPointerException if the date is {@code null} + * @throws ArithmeticException if the year is over 280 million + */ + public static Calendar round(final Calendar date, final int field) { + if (date == null) { throw nullDateIllegalArgumentException(); } - Calendar start = null; - Calendar end = null; - int startCutoff = Calendar.SUNDAY; - int endCutoff = Calendar.SATURDAY; - switch (rangeStyle) { - case RANGE_MONTH_SUNDAY: - case RANGE_MONTH_MONDAY: - // Set start to the first of the month - start = truncate(focus, Calendar.MONTH); - // Set end to the last of the month - end = (Calendar) start.clone(); - end.add(Calendar.MONTH, 1); - end.add(Calendar.DATE, -1); - // Loop start back to the previous sunday or monday - if (rangeStyle == RANGE_MONTH_MONDAY) { - startCutoff = Calendar.MONDAY; - endCutoff = Calendar.SUNDAY; - } - break; - case RANGE_WEEK_SUNDAY: - case RANGE_WEEK_MONDAY: - case RANGE_WEEK_RELATIVE: - case RANGE_WEEK_CENTER: - // Set start and end to the current date - start = truncate(focus, Calendar.DATE); - end = truncate(focus, Calendar.DATE); - switch (rangeStyle) { - case RANGE_WEEK_SUNDAY: - // already set by default - break; - case RANGE_WEEK_MONDAY: - startCutoff = Calendar.MONDAY; - endCutoff = Calendar.SUNDAY; - break; - case RANGE_WEEK_RELATIVE: - startCutoff = focus.get(Calendar.DAY_OF_WEEK); - endCutoff = startCutoff - 1; - break; - case RANGE_WEEK_CENTER: - startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3; - endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3; - break; - default: - break; - } - break; - default: - throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid."); - } - if (startCutoff < Calendar.SUNDAY) { - startCutoff += 7; - } - if (startCutoff > Calendar.SATURDAY) { - startCutoff -= 7; - } - if (endCutoff < Calendar.SUNDAY) { - endCutoff += 7; - } - if (endCutoff > Calendar.SATURDAY) { - endCutoff -= 7; - } - while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) { - start.add(Calendar.DATE, -1); - } - while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) { - end.add(Calendar.DATE, 1); - } - return new DateIterator(start, end); + final Calendar rounded = (Calendar) date.clone(); + modify(rounded, field, ModifyType.ROUND); + return rounded; } + // ----------------------------------------------------------------------- /** *

              - * Constructs an {@code Iterator} over each day in a date range defined by a - * focus date and range style. + * Rounds a date, leaving the field specified as the most significant field. *

              * *

              - * For instance, passing Thursday, July 4, 2002 and a {@code RANGE_MONTH_SUNDAY} - * will return an {@code Iterator} that starts with Sunday, June 30, 2002 and - * ends with Saturday, August 3, 2002, returning a Calendar instance for each - * intermediate day. - *

              - * - * @param focus the date to work with, either {@code Date} or - * {@code Calendar}, not null - * @param rangeStyle the style constant to use. Must be one of the range styles - * listed for the {@link #iterator(Calendar, int)} method. - * @return the date iterator, not null - * @throws IllegalArgumentException if the date is {@code null} - * @throws ClassCastException if the object type is not a {@code Date} or - * {@code Calendar} - */ - public static Iterator iterator(final Object focus, final int rangeStyle) { - if (focus == null) { - throw nullDateIllegalArgumentException(); - } - if (focus instanceof Date) { - return iterator((Date) focus, rangeStyle); - } else if (focus instanceof Calendar) { - return iterator((Calendar) focus, rangeStyle); - } else { - throw new ClassCastException("Could not iterate based on " + focus); - } - } - - /** - *

              - * Returns the number of milliseconds within the fragment. All datefields - * greater than the fragment will be ignored. + * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this + * was passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was + * passed with MONTH, it would return 1 April 2002 0:00:00.000. *

              * *

              - * Asking the milliseconds of any date will only return the number of - * milliseconds of the current second (resulting in a number between 0 and 999). - * This method will retrieve the number of milliseconds for any fragment. For - * example, if you want to calculate the number of milliseconds past today, your - * fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will be all - * milliseconds of the past hour(s), minutes(s) and second(s). + * For a date in a time zone that handles the change to daylight saving time, + * rounding to Calendar.HOUR_OF_DAY will behave as follows. Suppose daylight + * saving time begins at 02:00 on March 30. Rounding a date that crosses this + * time would produce the following values: *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a SECOND field will - * return 0. - *

              - * *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return - * 538
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return - * 538
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return - * 10538 (10*1000 + 538)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in milliseconds)
              • + *
              • March 30, 2003 01:10 rounds to March 30, 2003 01:00
              • + *
              • March 30, 2003 01:40 rounds to March 30, 2003 03:00
              • + *
              • March 30, 2003 02:10 rounds to March 30, 2003 03:00
              • + *
              • March 30, 2003 02:40 rounds to March 30, 2003 04:00
              • *
              * - * @param date the date to work with, not null - * @param fragment the {@code Calendar} field part of date to calculate - * @return number of milliseconds within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 + * @param date the date to work with, not null + * @param field the field from {@code Calendar} or {@code SEMI_MONTH} + * @return the different rounded date, not null + * @throws ArithmeticException if the year is over 280 million */ - public static long getFragmentInMilliseconds(final Date date, final int fragment) { - return getFragment(date, fragment, TimeUnit.MILLISECONDS); - } - - /** - *

              - * Returns the number of seconds within the fragment. All datefields greater - * than the fragment will be ignored. - *

              - * - *

              - * Asking the seconds of any date will only return the number of seconds of the - * current minute (resulting in a number between 0 and 59). This method will - * retrieve the number of seconds for any fragment. For example, if you want to - * calculate the number of seconds past today, your fragment is Calendar.DATE or - * Calendar.DAY_OF_YEAR. The result will be all seconds of the past hour(s) and - * minutes(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a SECOND field will - * return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return - * 10 (equivalent to deprecated date.getSeconds())
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return - * 10 (equivalent to deprecated date.getSeconds())
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will - * return 26110 (7*3600 + 15*60 + 10)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in seconds)
              • - *
              - * - * @param date the date to work with, not null - * @param fragment the {@code Calendar} field part of date to calculate - * @return number of seconds within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInSeconds(final Date date, final int fragment) { - return getFragment(date, fragment, TimeUnit.SECONDS); - } - - /** - *

              - * Returns the number of minutes within the fragment. All datefields greater - * than the fragment will be ignored. - *

              - * - *

              - * Asking the minutes of any date will only return the number of minutes of the - * current hour (resulting in a number between 0 and 59). This method will - * retrieve the number of minutes for any fragment. For example, if you want to - * calculate the number of minutes past this month, your fragment is - * Calendar.MONTH. The result will be all minutes of the past day(s) and - * hour(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a MINUTE field will - * return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will - * return 15 (equivalent to deprecated date.getMinutes())
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will - * return 15 (equivalent to deprecated date.getMinutes())
              • - *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 15
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 435 (7*60 + 15)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in minutes)
              • - *
              - * - * @param date the date to work with, not null - * @param fragment the {@code Calendar} field part of date to calculate - * @return number of minutes within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInMinutes(final Date date, final int fragment) { - return getFragment(date, fragment, TimeUnit.MINUTES); - } - - /** - *

              - * Returns the number of hours within the fragment. All datefields greater than - * the fragment will be ignored. - *

              - * - *

              - * Asking the hours of any date will only return the number of hours of the - * current day (resulting in a number between 0 and 23). This method will - * retrieve the number of hours for any fragment. For example, if you want to - * calculate the number of hours past this month, your fragment is - * Calendar.MONTH. The result will be all hours of the past day(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a HOUR field will - * return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will - * return 7 (equivalent to deprecated date.getHours())
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will - * return 7 (equivalent to deprecated date.getHours())
              • - *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 7
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 127 (5*24 + 7)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in hours)
              • - *
              - * - * @param date the date to work with, not null - * @param fragment the {@code Calendar} field part of date to calculate - * @return number of hours within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInHours(final Date date, final int fragment) { - return getFragment(date, fragment, TimeUnit.HOURS); - } - - /** - *

              - * Returns the number of days within the fragment. All datefields greater than - * the fragment will be ignored. - *

              - * - *

              - * Asking the days of any date will only return the number of days of the - * current month (resulting in a number between 1 and 31). This method will - * retrieve the number of days for any fragment. For example, if you want to - * calculate the number of days past this year, your fragment is Calendar.YEAR. - * The result will be all days of the past month(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a DAY field will return - * 0. - *

              - * - *
                - *
              • January 28, 2008 with Calendar.MONTH as fragment will return 28 - * (equivalent to deprecated date.getDay())
              • - *
              • February 28, 2008 with Calendar.MONTH as fragment will return 28 - * (equivalent to deprecated date.getDay())
              • - *
              • January 28, 2008 with Calendar.YEAR as fragment will return 28
              • - *
              • February 28, 2008 with Calendar.YEAR as fragment will return 59
              • - *
              • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 (a - * millisecond cannot be split in days)
              • - *
              - * - * @param date the date to work with, not null - * @param fragment the {@code Calendar} field part of date to calculate - * @return number of days within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInDays(final Date date, final int fragment) { - return getFragment(date, fragment, TimeUnit.DAYS); - } - - /** - *

              - * Returns the number of milliseconds within the fragment. All datefields - * greater than the fragment will be ignored. - *

              - * - *

              - * Asking the milliseconds of any date will only return the number of - * milliseconds of the current second (resulting in a number between 0 and 999). - * This method will retrieve the number of milliseconds for any fragment. For - * example, if you want to calculate the number of seconds past today, your - * fragment is Calendar.DATE or Calendar.DAY_OF_YEAR. The result will be all - * seconds of the past hour(s), minutes(s) and second(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a MILLISECOND field - * will return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.SECOND as fragment will return - * 538 (equivalent to calendar.get(Calendar.MILLISECOND))
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.SECOND as fragment will return - * 538 (equivalent to calendar.get(Calendar.MILLISECOND))
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return - * 10538 (10*1000 + 538)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in milliseconds)
              • - *
              - * - * @param calendar the calendar to work with, not null - * @param fragment the {@code Calendar} field part of calendar to calculate - * @return number of milliseconds within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInMilliseconds(final Calendar calendar, final int fragment) { - return getFragment(calendar, fragment, TimeUnit.MILLISECONDS); - } - - /** - *

              - * Returns the number of seconds within the fragment. All datefields greater - * than the fragment will be ignored. - *

              - * - *

              - * Asking the seconds of any date will only return the number of seconds of the - * current minute (resulting in a number between 0 and 59). This method will - * retrieve the number of seconds for any fragment. For example, if you want to - * calculate the number of seconds past today, your fragment is Calendar.DATE or - * Calendar.DAY_OF_YEAR. The result will be all seconds of the past hour(s) and - * minutes(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a SECOND field will - * return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return - * 10 (equivalent to calendar.get(Calendar.SECOND))
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MINUTE as fragment will return - * 10 (equivalent to calendar.get(Calendar.SECOND))
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will - * return 26110 (7*3600 + 15*60 + 10)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in seconds)
              • - *
              - * - * @param calendar the calendar to work with, not null - * @param fragment the {@code Calendar} field part of calendar to calculate - * @return number of seconds within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInSeconds(final Calendar calendar, final int fragment) { - return getFragment(calendar, fragment, TimeUnit.SECONDS); - } - - /** - *

              - * Returns the number of minutes within the fragment. All datefields greater - * than the fragment will be ignored. - *

              - * - *

              - * Asking the minutes of any date will only return the number of minutes of the - * current hour (resulting in a number between 0 and 59). This method will - * retrieve the number of minutes for any fragment. For example, if you want to - * calculate the number of minutes past this month, your fragment is - * Calendar.MONTH. The result will be all minutes of the past day(s) and - * hour(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a MINUTE field will - * return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will - * return 15 (equivalent to calendar.get(Calendar.MINUTES))
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.HOUR_OF_DAY as fragment will - * return 15 (equivalent to calendar.get(Calendar.MINUTES))
              • - *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 15
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 435 (7*60 + 15)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in minutes)
              • - *
              - * - * @param calendar the calendar to work with, not null - * @param fragment the {@code Calendar} field part of calendar to calculate - * @return number of minutes within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInMinutes(final Calendar calendar, final int fragment) { - return getFragment(calendar, fragment, TimeUnit.MINUTES); - } - - /** - *

              - * Returns the number of hours within the fragment. All datefields greater than - * the fragment will be ignored. - *

              - * - *

              - * Asking the hours of any date will only return the number of hours of the - * current day (resulting in a number between 0 and 23). This method will - * retrieve the number of hours for any fragment. For example, if you want to - * calculate the number of hours past this month, your fragment is - * Calendar.MONTH. The result will be all hours of the past day(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a HOUR field will - * return 0. - *

              - * - *
                - *
              • January 1, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will - * return 7 (equivalent to calendar.get(Calendar.HOUR_OF_DAY))
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.DAY_OF_YEAR as fragment will - * return 7 (equivalent to calendar.get(Calendar.HOUR_OF_DAY))
              • - *
              • January 1, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 7
              • - *
              • January 6, 2008 7:15:10.538 with Calendar.MONTH as fragment will return - * 127 (5*24 + 7)
              • - *
              • January 16, 2008 7:15:10.538 with Calendar.MILLISECOND as fragment will - * return 0 (a millisecond cannot be split in hours)
              • - *
              - * - * @param calendar the calendar to work with, not null - * @param fragment the {@code Calendar} field part of calendar to calculate - * @return number of hours within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInHours(final Calendar calendar, final int fragment) { - return getFragment(calendar, fragment, TimeUnit.HOURS); - } - - /** - *

              - * Returns the number of days within the fragment. All datefields greater than - * the fragment will be ignored. - *

              - * - *

              - * Asking the days of any date will only return the number of days of the - * current month (resulting in a number between 1 and 31). This method will - * retrieve the number of days for any fragment. For example, if you want to - * calculate the number of days past this year, your fragment is Calendar.YEAR. - * The result will be all days of the past month(s). - *

              - * - *

              - * Valid fragments are: Calendar.YEAR, Calendar.MONTH, both Calendar.DAY_OF_YEAR - * and Calendar.DATE, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND and - * Calendar.MILLISECOND A fragment less than or equal to a DAY field will return - * 0. - *

              - * - *
                - *
              • January 28, 2008 with Calendar.MONTH as fragment will return 28 - * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
              • - *
              • February 28, 2008 with Calendar.MONTH as fragment will return 28 - * (equivalent to calendar.get(Calendar.DAY_OF_MONTH))
              • - *
              • January 28, 2008 with Calendar.YEAR as fragment will return 28 - * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
              • - *
              • February 28, 2008 with Calendar.YEAR as fragment will return 59 - * (equivalent to calendar.get(Calendar.DAY_OF_YEAR))
              • - *
              • January 28, 2008 with Calendar.MILLISECOND as fragment will return 0 (a - * millisecond cannot be split in days)
              • - *
              - * - * @param calendar the calendar to work with, not null - * @param fragment the {@code Calendar} field part of calendar to calculate - * @return number of days within the fragment of date - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 - */ - public static long getFragmentInDays(final Calendar calendar, final int fragment) { - return getFragment(calendar, fragment, TimeUnit.DAYS); - } - - /** - * Gets a Date fragment for any unit. - * - * @param date the date to work with, not null - * @param fragment the Calendar field part of date to calculate - * @param unit the time unit - * @return number of units within the fragment of the date - * @throws NullPointerException if the date is {@code null} - * @throws IllegalArgumentException if fragment is not supported - * @since 2.4 - */ - private static long getFragment(final Date date, final int fragment, final TimeUnit unit) { + public static Date round(final Date date, final int field) { validateDateNotNull(date); - final Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - return getFragment(calendar, fragment, unit); + final Calendar gval = Calendar.getInstance(); + gval.setTime(date); + modify(gval, field, ModifyType.ROUND); + return gval.getTime(); } /** - * Gets a Calendar fragment for any unit. + *

              + * Rounds a date, leaving the field specified as the most significant field. + *

              * - * @param calendar the calendar to work with, not null - * @param fragment the Calendar field part of calendar to calculate - * @param unit the time unit - * @return number of units within the fragment of the calendar - * @throws IllegalArgumentException if the date is {@code null} or fragment is - * not supported - * @since 2.4 + *

              + * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if this + * was passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was + * passed with MONTH, it would return 1 April 2002 0:00:00.000. + *

              + * + *

              + * For a date in a time zone that handles the change to daylight saving time, + * rounding to Calendar.HOUR_OF_DAY will behave as follows. Suppose daylight + * saving time begins at 02:00 on March 30. Rounding a date that crosses this + * time would produce the following values: + *

              + *
                + *
              • March 30, 2003 01:10 rounds to March 30, 2003 01:00
              • + *
              • March 30, 2003 01:40 rounds to March 30, 2003 03:00
              • + *
              • March 30, 2003 02:10 rounds to March 30, 2003 03:00
              • + *
              • March 30, 2003 02:40 rounds to March 30, 2003 04:00
              • + *
              + * + * @param date the date to work with, either {@code Date} or {@code Calendar}, + * not null + * @param field the field from {@code Calendar} or {@code SEMI_MONTH} + * @return the different rounded date, not null + * @throws NullPointerException if the date is {@code null} + * @throws ClassCastException if the object type is not a {@code Date} or + * {@code Calendar} + * @throws ArithmeticException if the year is over 280 million */ - private static long getFragment(final Calendar calendar, final int fragment, final TimeUnit unit) { - if (calendar == null) { + public static Date round(final Object date, final int field) { + if (date == null) { throw nullDateIllegalArgumentException(); } - - long result = 0; - - final int offset = (unit == TimeUnit.DAYS) ? 0 : 1; - - // Fragments bigger than a day require a breakdown to days - switch (fragment) { - case Calendar.YEAR: - result += unit.convert(calendar.get(Calendar.DAY_OF_YEAR) - offset, TimeUnit.DAYS); - break; - case Calendar.MONTH: - result += unit.convert(calendar.get(Calendar.DAY_OF_MONTH) - offset, TimeUnit.DAYS); - break; - default: - break; + if (date instanceof Date) { + return round((Date) date, field); + } else if (date instanceof Calendar) { + return round((Calendar) date, field).getTime(); + } else { + throw new ClassCastException("Could not round " + date); } + } - switch (fragment) { - // Number of days already calculated for these cases - case Calendar.YEAR: - case Calendar.MONTH: + // ----------------------------------------------------------------------- + /** + * Sets the specified field to a date returning a new object. This does not use + * a lenient calendar. The original {@code Date} is unchanged. + * + * @param date the date, not null + * @param calendarField the {@code Calendar} field to set the amount to + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + private static Date set(final Date date, final int calendarField, final int amount) { + validateDateNotNull(date); + // getInstance() returns a new object, so this method is thread safe. + final Calendar c = Calendar.getInstance(); + c.setLenient(false); + c.setTime(date); + c.set(calendarField, amount); + return c.getTime(); + } - // The rest of the valid cases - case Calendar.DAY_OF_YEAR: - case Calendar.DATE: - result += unit.convert(calendar.get(Calendar.HOUR_OF_DAY), TimeUnit.HOURS); - //$FALL-THROUGH$ - case Calendar.HOUR_OF_DAY: - result += unit.convert(calendar.get(Calendar.MINUTE), TimeUnit.MINUTES); - //$FALL-THROUGH$ - case Calendar.MINUTE: - result += unit.convert(calendar.get(Calendar.SECOND), TimeUnit.SECONDS); - //$FALL-THROUGH$ - case Calendar.SECOND: - result += unit.convert(calendar.get(Calendar.MILLISECOND), TimeUnit.MILLISECONDS); - break; - case Calendar.MILLISECOND: - break; // never useful - default: - throw new IllegalArgumentException("The fragment " + fragment + " is not supported"); - } - return result; + // ----------------------------------------------------------------------- + /** + * Sets the day of month field to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setDays(final Date date, final int amount) { + return set(date, Calendar.DAY_OF_MONTH, amount); + } + + // ----------------------------------------------------------------------- + /** + * Sets the hours field to a date returning a new object. Hours range from 0-23. + * The original {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setHours(final Date date, final int amount) { + return set(date, Calendar.HOUR_OF_DAY, amount); + } + + // ----------------------------------------------------------------------- + /** + * Sets the milliseconds field to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setMilliseconds(final Date date, final int amount) { + return set(date, Calendar.MILLISECOND, amount); + } + + // ----------------------------------------------------------------------- + /** + * Sets the minute field to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setMinutes(final Date date, final int amount) { + return set(date, Calendar.MINUTE, amount); + } + + // ----------------------------------------------------------------------- + /** + * Sets the months field to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setMonths(final Date date, final int amount) { + return set(date, Calendar.MONTH, amount); + } + + // ----------------------------------------------------------------------- + /** + * Sets the seconds field to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setSeconds(final Date date, final int amount) { + return set(date, Calendar.SECOND, amount); + } + + // ----------------------------------------------------------------------- + /** + * Sets the years field to a date returning a new object. The original + * {@code Date} is unchanged. + * + * @param date the date, not null + * @param amount the amount to set + * @return a new {@code Date} set with the specified value + * @throws IllegalArgumentException if the date is null + * @since 2.4 + */ + public static Date setYears(final Date date, final int amount) { + return set(date, Calendar.YEAR, amount); + } + + // ----------------------------------------------------------------------- + /** + * Converts a {@code Date} into a {@code Calendar}. + * + * @param date the date to convert to a Calendar + * @return the created Calendar + * @throws NullPointerException if null is passed in + * @since 3.0 + */ + public static Calendar toCalendar(final Date date) { + final Calendar c = Calendar.getInstance(); + c.setTime(date); + return c; + } + + // ----------------------------------------------------------------------- + /** + * Converts a {@code Date} of a given {@code TimeZone} into a {@code Calendar} + * + * @param date the date to convert to a Calendar + * @param tz the time zone of the {@code date} + * @return the created Calendar + * @throws NullPointerException if {@code date} or {@code tz} is null + */ + public static Calendar toCalendar(final Date date, final TimeZone tz) { + final Calendar c = Calendar.getInstance(tz); + c.setTime(date); + return c; } /** - * Determines if two calendars are equal up to no more than the specified most - * significant field. + *

              + * Truncates a date, leaving the field specified as the most significant field. + *

              * - * @param cal1 the first calendar, not {@code null} - * @param cal2 the second calendar, not {@code null} - * @param field the field from {@code Calendar} - * @return {@code true} if equal; otherwise {@code false} - * @throws IllegalArgumentException if any argument is {@code null} - * @see #truncate(Calendar, int) - * @see #truncatedEquals(Date, Date, int) - * @since 3.0 + *

              + * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you + * passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was + * passed with MONTH, it would return 1 Mar 2002 0:00:00.000. + *

              + * + * @param date the date to work with, not null + * @param field the field from {@code Calendar} or {@code SEMI_MONTH} + * @return the different truncated date, not null + * @throws NullPointerException if the date is {@code null} + * @throws ArithmeticException if the year is over 280 million */ - public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field) { - return truncatedCompareTo(cal1, cal2, field) == 0; + public static Calendar truncate(final Calendar date, final int field) { + if (date == null) { + throw nullDateIllegalArgumentException(); + } + final Calendar truncated = (Calendar) date.clone(); + modify(truncated, field, ModifyType.TRUNCATE); + return truncated; + } + + // ----------------------------------------------------------------------- + /** + *

              + * Truncates a date, leaving the field specified as the most significant field. + *

              + * + *

              + * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you + * passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was + * passed with MONTH, it would return 1 Mar 2002 0:00:00.000. + *

              + * + * @param date the date to work with, not null + * @param field the field from {@code Calendar} or {@code SEMI_MONTH} + * @return the different truncated date, not null + * @throws NullPointerException if the date is {@code null} + * @throws ArithmeticException if the year is over 280 million + */ + public static Date truncate(final Date date, final int field) { + validateDateNotNull(date); + final Calendar gval = Calendar.getInstance(); + gval.setTime(date); + modify(gval, field, ModifyType.TRUNCATE); + return gval.getTime(); } /** - * Determines if two dates are equal up to no more than the specified most - * significant field. + *

              + * Truncates a date, leaving the field specified as the most significant field. + *

              * - * @param date1 the first date, not {@code null} - * @param date2 the second date, not {@code null} - * @param field the field from {@code Calendar} - * @return {@code true} if equal; otherwise {@code false} - * @throws IllegalArgumentException if any argument is {@code null} - * @see #truncate(Date, int) - * @see #truncatedEquals(Calendar, Calendar, int) - * @since 3.0 + *

              + * For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you + * passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was + * passed with MONTH, it would return 1 Mar 2002 0:00:00.000. + *

              + * + * @param date the date to work with, either {@code Date} or {@code Calendar}, + * not null + * @param field the field from {@code Calendar} or {@code SEMI_MONTH} + * @return the different truncated date, not null + * @throws NullPointerException if the date is {@code null} + * @throws ClassCastException if the object type is not a {@code Date} or + * {@code Calendar} + * @throws ArithmeticException if the year is over 280 million */ - public static boolean truncatedEquals(final Date date1, final Date date2, final int field) { - return truncatedCompareTo(date1, date2, field) == 0; + public static Date truncate(final Object date, final int field) { + if (date == null) { + throw nullDateIllegalArgumentException(); + } + if (date instanceof Date) { + return truncate((Date) date, field); + } else if (date instanceof Calendar) { + return truncate((Calendar) date, field).getTime(); + } else { + throw new ClassCastException("Could not truncate " + date); + } } /** @@ -1960,66 +1971,57 @@ public class DateUtils { return truncatedDate1.compareTo(truncatedDate2); } + /** + * Determines if two calendars are equal up to no more than the specified most + * significant field. + * + * @param cal1 the first calendar, not {@code null} + * @param cal2 the second calendar, not {@code null} + * @param field the field from {@code Calendar} + * @return {@code true} if equal; otherwise {@code false} + * @throws IllegalArgumentException if any argument is {@code null} + * @see #truncate(Calendar, int) + * @see #truncatedEquals(Date, Date, int) + * @since 3.0 + */ + public static boolean truncatedEquals(final Calendar cal1, final Calendar cal2, final int field) { + return truncatedCompareTo(cal1, cal2, field) == 0; + } + + /** + * Determines if two dates are equal up to no more than the specified most + * significant field. + * + * @param date1 the first date, not {@code null} + * @param date2 the second date, not {@code null} + * @param field the field from {@code Calendar} + * @return {@code true} if equal; otherwise {@code false} + * @throws IllegalArgumentException if any argument is {@code null} + * @see #truncate(Date, int) + * @see #truncatedEquals(Calendar, Calendar, int) + * @since 3.0 + */ + public static boolean truncatedEquals(final Date date1, final Date date2, final int field) { + return truncatedCompareTo(date1, date2, field) == 0; + } + private static void validateDateNotNull(final Date date) { Validate.notNull(date, "date"); } - // ----------------------------------------------------------------------- /** *

              - * Date iterator. + * {@code DateUtils} instances should NOT be constructed in standard + * programming. Instead, the static methods on the class should be used, such as + * {@code DateUtils.parseDate(str);}. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. *

              */ - static class DateIterator implements Iterator { - private final Calendar endFinal; - private final Calendar spot; - - /** - * Constructs a DateIterator that ranges from one date to another. - * - * @param startFinal start date (inclusive) - * @param endFinal end date (inclusive) - */ - DateIterator(final Calendar startFinal, final Calendar endFinal) { - this.endFinal = endFinal; - spot = startFinal; - spot.add(Calendar.DATE, -1); - } - - /** - * Has the iterator not reached the end date yet? - * - * @return {@code true} if the iterator has yet to reach the end date - */ - @Override - public boolean hasNext() { - return spot.before(endFinal); - } - - /** - * Returns the next calendar in the iteration - * - * @return Object calendar for the next date - */ - @Override - public Calendar next() { - if (spot.equals(endFinal)) { - throw new NoSuchElementException(); - } - spot.add(Calendar.DATE, 1); - return (Calendar) spot.clone(); - } - - /** - * Always throws UnsupportedOperationException. - * - * @throws UnsupportedOperationException Always thrown. - * @see java.util.Iterator#remove() - */ - @Override - public void remove() { - throw new UnsupportedOperationException(); - } + public DateUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java b/src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java index 072e093e..a1727f3c 100644 --- a/src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java +++ b/src/main/java/org/apache/commons/lang3/time/DurationFormatUtils.java @@ -82,17 +82,126 @@ import org.apache.commons.lang3.Validate; public class DurationFormatUtils { /** - *

              - * DurationFormatUtils instances should NOT be constructed in standard - * programming. - *

              - * - *

              - * This constructor is public to permit tools that require a JavaBean instance - * to operate. - *

              + * Element that is parsed from the format pattern. */ - public DurationFormatUtils() { + static class Token { + + /** Empty array. */ + private static final Token[] EMPTY_ARRAY = new Token[0]; + + /** + * Helper method to determine if a set of tokens contain a value + * + * @param tokens set to look in + * @param value to look for + * @return boolean {@code true} if contained + */ + static boolean containsTokenWithValue(final Token[] tokens, final Object value) { + for (final Token token : tokens) { + if (token.getValue() == value) { + return true; + } + } + return false; + } + + private final Object value; + private int count; + + /** + * Wraps a token around a value. A value would be something like a 'Y'. + * + * @param value to wrap + */ + Token(final Object value) { + this.value = value; + this.count = 1; + } + + /** + * Wraps a token around a repeated number of a value, for example it would store + * 'yyyy' as a value for y and a count of 4. + * + * @param value to wrap + * @param count to wrap + */ + Token(final Object value, final int count) { + this.value = value; + this.count = count; + } + + /** + * Supports equality of this Token to another Token. + * + * @param obj2 Object to consider equality of + * @return boolean {@code true} if equal + */ + @Override + public boolean equals(final Object obj2) { + if (obj2 instanceof Token) { + final Token tok2 = (Token) obj2; + if (this.value.getClass() != tok2.value.getClass()) { + return false; + } + if (this.count != tok2.count) { + return false; + } + if (this.value instanceof StringBuilder) { + return this.value.toString().equals(tok2.value.toString()); + } else if (this.value instanceof Number) { + return this.value.equals(tok2.value); + } else { + return this.value == tok2.value; + } + } + return false; + } + + /** + * Gets the current number of values represented + * + * @return int number of values represented + */ + int getCount() { + return count; + } + + /** + * Gets the particular value this token represents. + * + * @return Object value + */ + Object getValue() { + return value; + } + + /** + * Returns a hash code for the token equal to the hash code for the token's + * value. Thus 'TT' and 'TTTT' will have the same hash code. + * + * @return The hash code for the token + */ + @Override + public int hashCode() { + return this.value.hashCode(); + } + + /** + * Adds another one of the value + */ + void increment() { + count++; + } + + /** + * Represents this token as a String. + * + * @return String representation of the token + */ + @Override + public String toString() { + return StringUtils.repeat(this.value.toString(), this.count); + } } /** @@ -106,44 +215,76 @@ public class DurationFormatUtils { */ public static final String ISO_EXTENDED_FORMAT_PATTERN = "'P'yyyy'Y'M'M'd'DT'H'H'm'M's.SSS'S'"; + static final String y = "y"; + + static final String M = "M"; + + static final String d = "d"; + + static final String H = "H"; + + static final String m = "m"; + + static final String s = "s"; + + static final String S = "S"; + // ----------------------------------------------------------------------- /** *

              - * Formats the time gap as a string. + * The internal method to do the formatting. *

              * - *

              - * The format used is ISO 8601-like: {@code HH:mm:ss.SSS}. - *

              - * - * @param durationMillis the duration to format - * @return the formatted duration, not null - * @throws java.lang.IllegalArgumentException if durationMillis is negative + * @param tokens the tokens + * @param years the number of years + * @param months the number of months + * @param days the number of days + * @param hours the number of hours + * @param minutes the number of minutes + * @param seconds the number of seconds + * @param milliseconds the number of millis + * @param padWithZeros whether to pad + * @return the formatted string */ - public static String formatDurationHMS(final long durationMillis) { - return formatDuration(durationMillis, "HH:mm:ss.SSS"); - } - - /** - *

              - * Formats the time gap as a string. - *

              - * - *

              - * The format used is the ISO 8601 period format. - *

              - * - *

              - * This method formats durations using the days and lower fields of the ISO - * format pattern, such as P7D6TH5M4.321S. - *

              - * - * @param durationMillis the duration to format - * @return the formatted duration, not null - * @throws java.lang.IllegalArgumentException if durationMillis is negative - */ - public static String formatDurationISO(final long durationMillis) { - return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false); + static String format(final Token[] tokens, final long years, final long months, final long days, final long hours, + final long minutes, final long seconds, final long milliseconds, final boolean padWithZeros) { + final StringBuilder buffer = new StringBuilder(); + boolean lastOutputSeconds = false; + for (final Token token : tokens) { + final Object value = token.getValue(); + final int count = token.getCount(); + if (value instanceof StringBuilder) { + buffer.append(value.toString()); + } else if (value.equals(y)) { + buffer.append(paddedValue(years, padWithZeros, count)); + lastOutputSeconds = false; + } else if (value.equals(M)) { + buffer.append(paddedValue(months, padWithZeros, count)); + lastOutputSeconds = false; + } else if (value.equals(d)) { + buffer.append(paddedValue(days, padWithZeros, count)); + lastOutputSeconds = false; + } else if (value.equals(H)) { + buffer.append(paddedValue(hours, padWithZeros, count)); + lastOutputSeconds = false; + } else if (value.equals(m)) { + buffer.append(paddedValue(minutes, padWithZeros, count)); + lastOutputSeconds = false; + } else if (value.equals(s)) { + buffer.append(paddedValue(seconds, padWithZeros, count)); + lastOutputSeconds = true; + } else if (value.equals(S)) { + if (lastOutputSeconds) { + // ensure at least 3 digits are displayed even if padding is not selected + final int width = padWithZeros ? Math.max(3, count) : 3; + buffer.append(paddedValue(milliseconds, true, width)); + } else { + buffer.append(paddedValue(milliseconds, padWithZeros, count)); + } + lastOutputSeconds = false; + } + } + return buffer.toString(); } /** @@ -214,6 +355,46 @@ public class DurationFormatUtils { return format(tokens, 0, 0, days, hours, minutes, seconds, milliseconds, padWithZeros); } + // ----------------------------------------------------------------------- + /** + *

              + * Formats the time gap as a string. + *

              + * + *

              + * The format used is ISO 8601-like: {@code HH:mm:ss.SSS}. + *

              + * + * @param durationMillis the duration to format + * @return the formatted duration, not null + * @throws java.lang.IllegalArgumentException if durationMillis is negative + */ + public static String formatDurationHMS(final long durationMillis) { + return formatDuration(durationMillis, "HH:mm:ss.SSS"); + } + + /** + *

              + * Formats the time gap as a string. + *

              + * + *

              + * The format used is the ISO 8601 period format. + *

              + * + *

              + * This method formats durations using the days and lower fields of the ISO + * format pattern, such as P7D6TH5M4.321S. + *

              + * + * @param durationMillis the duration to format + * @return the formatted duration, not null + * @throws java.lang.IllegalArgumentException if durationMillis is negative + */ + public static String formatDurationISO(final long durationMillis) { + return formatDuration(durationMillis, ISO_EXTENDED_FORMAT_PATTERN, false); + } + /** *

              * Formats an elapsed time into a pluralization correct string. @@ -282,26 +463,6 @@ public class DurationFormatUtils { return duration.trim(); } - // ----------------------------------------------------------------------- - /** - *

              - * Formats the time gap as a string. - *

              - * - *

              - * The format used is the ISO 8601 period format. - *

              - * - * @param startMillis the start of the duration to format - * @param endMillis the end of the duration to format - * @return the formatted duration, not null - * @throws java.lang.IllegalArgumentException if startMillis is greater than - * endMillis - */ - public static String formatPeriodISO(final long startMillis, final long endMillis) { - return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault()); - } - /** *

              * Formats the time gap as a string, using the specified format. Padding the @@ -481,85 +642,23 @@ public class DurationFormatUtils { // ----------------------------------------------------------------------- /** *

              - * The internal method to do the formatting. + * Formats the time gap as a string. *

              * - * @param tokens the tokens - * @param years the number of years - * @param months the number of months - * @param days the number of days - * @param hours the number of hours - * @param minutes the number of minutes - * @param seconds the number of seconds - * @param milliseconds the number of millis - * @param padWithZeros whether to pad - * @return the formatted string - */ - static String format(final Token[] tokens, final long years, final long months, final long days, final long hours, - final long minutes, final long seconds, final long milliseconds, final boolean padWithZeros) { - final StringBuilder buffer = new StringBuilder(); - boolean lastOutputSeconds = false; - for (final Token token : tokens) { - final Object value = token.getValue(); - final int count = token.getCount(); - if (value instanceof StringBuilder) { - buffer.append(value.toString()); - } else if (value.equals(y)) { - buffer.append(paddedValue(years, padWithZeros, count)); - lastOutputSeconds = false; - } else if (value.equals(M)) { - buffer.append(paddedValue(months, padWithZeros, count)); - lastOutputSeconds = false; - } else if (value.equals(d)) { - buffer.append(paddedValue(days, padWithZeros, count)); - lastOutputSeconds = false; - } else if (value.equals(H)) { - buffer.append(paddedValue(hours, padWithZeros, count)); - lastOutputSeconds = false; - } else if (value.equals(m)) { - buffer.append(paddedValue(minutes, padWithZeros, count)); - lastOutputSeconds = false; - } else if (value.equals(s)) { - buffer.append(paddedValue(seconds, padWithZeros, count)); - lastOutputSeconds = true; - } else if (value.equals(S)) { - if (lastOutputSeconds) { - // ensure at least 3 digits are displayed even if padding is not selected - final int width = padWithZeros ? Math.max(3, count) : 3; - buffer.append(paddedValue(milliseconds, true, width)); - } else { - buffer.append(paddedValue(milliseconds, padWithZeros, count)); - } - lastOutputSeconds = false; - } - } - return buffer.toString(); - } - - /** *

              - * Converts a {@code long} to a {@code String} with optional zero padding. + * The format used is the ISO 8601 period format. *

              * - * @param value the value to convert - * @param padWithZeros whether to pad with zeroes - * @param count the size to pad to (ignored if {@code padWithZeros} is - * false) - * @return the string result + * @param startMillis the start of the duration to format + * @param endMillis the end of the duration to format + * @return the formatted duration, not null + * @throws java.lang.IllegalArgumentException if startMillis is greater than + * endMillis */ - private static String paddedValue(final long value, final boolean padWithZeros, final int count) { - final String longString = Long.toString(value); - return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString; + public static String formatPeriodISO(final long startMillis, final long endMillis) { + return formatPeriod(startMillis, endMillis, ISO_EXTENDED_FORMAT_PATTERN, false, TimeZone.getDefault()); } - static final String y = "y"; - static final String M = "M"; - static final String d = "d"; - static final String H = "H"; - static final String m = "m"; - static final String s = "s"; - static final String S = "S"; - /** * Parses a classic date format string into Tokens * @@ -640,126 +739,33 @@ public class DurationFormatUtils { } /** - * Element that is parsed from the format pattern. + *

              + * Converts a {@code long} to a {@code String} with optional zero padding. + *

              + * + * @param value the value to convert + * @param padWithZeros whether to pad with zeroes + * @param count the size to pad to (ignored if {@code padWithZeros} is + * false) + * @return the string result */ - static class Token { + private static String paddedValue(final long value, final boolean padWithZeros, final int count) { + final String longString = Long.toString(value); + return padWithZeros ? StringUtils.leftPad(longString, count, '0') : longString; + } - /** Empty array. */ - private static final Token[] EMPTY_ARRAY = new Token[0]; - - /** - * Helper method to determine if a set of tokens contain a value - * - * @param tokens set to look in - * @param value to look for - * @return boolean {@code true} if contained - */ - static boolean containsTokenWithValue(final Token[] tokens, final Object value) { - for (final Token token : tokens) { - if (token.getValue() == value) { - return true; - } - } - return false; - } - - private final Object value; - private int count; - - /** - * Wraps a token around a value. A value would be something like a 'Y'. - * - * @param value to wrap - */ - Token(final Object value) { - this.value = value; - this.count = 1; - } - - /** - * Wraps a token around a repeated number of a value, for example it would store - * 'yyyy' as a value for y and a count of 4. - * - * @param value to wrap - * @param count to wrap - */ - Token(final Object value, final int count) { - this.value = value; - this.count = count; - } - - /** - * Adds another one of the value - */ - void increment() { - count++; - } - - /** - * Gets the current number of values represented - * - * @return int number of values represented - */ - int getCount() { - return count; - } - - /** - * Gets the particular value this token represents. - * - * @return Object value - */ - Object getValue() { - return value; - } - - /** - * Supports equality of this Token to another Token. - * - * @param obj2 Object to consider equality of - * @return boolean {@code true} if equal - */ - @Override - public boolean equals(final Object obj2) { - if (obj2 instanceof Token) { - final Token tok2 = (Token) obj2; - if (this.value.getClass() != tok2.value.getClass()) { - return false; - } - if (this.count != tok2.count) { - return false; - } - if (this.value instanceof StringBuilder) { - return this.value.toString().equals(tok2.value.toString()); - } else if (this.value instanceof Number) { - return this.value.equals(tok2.value); - } else { - return this.value == tok2.value; - } - } - return false; - } - - /** - * Returns a hash code for the token equal to the hash code for the token's - * value. Thus 'TT' and 'TTTT' will have the same hash code. - * - * @return The hash code for the token - */ - @Override - public int hashCode() { - return this.value.hashCode(); - } - - /** - * Represents this token as a String. - * - * @return String representation of the token - */ - @Override - public String toString() { - return StringUtils.repeat(this.value.toString(), this.count); - } + /** + *

              + * DurationFormatUtils instances should NOT be constructed in standard + * programming. + *

              + * + *

              + * This constructor is public to permit tools that require a JavaBean instance + * to operate. + *

              + */ + public DurationFormatUtils() { } } diff --git a/src/main/java/org/apache/commons/lang3/time/FastDateFormat.java b/src/main/java/org/apache/commons/lang3/time/FastDateFormat.java index 74cd84a8..b4a9d77c 100644 --- a/src/main/java/org/apache/commons/lang3/time/FastDateFormat.java +++ b/src/main/java/org/apache/commons/lang3/time/FastDateFormat.java @@ -124,77 +124,6 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { } }; - private final FastDatePrinter printer; - private final FastDateParser parser; - - // ----------------------------------------------------------------------- - /** - *

              - * Gets a formatter instance using the default pattern in the default locale. - *

              - * - * @return a date/time formatter - */ - public static FastDateFormat getInstance() { - return cache.getInstance(); - } - - /** - *

              - * Gets a formatter instance using the specified pattern in the default locale. - *

              - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(final String pattern) { - return cache.getInstance(pattern, null, null); - } - - /** - *

              - * Gets a formatter instance using the specified pattern and time zone. - *

              - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone optional time zone, overrides time zone of formatted date - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone) { - return cache.getInstance(pattern, timeZone, null); - } - - /** - *

              - * Gets a formatter instance using the specified pattern and locale. - *

              - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param locale optional locale, overrides system locale - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid - */ - public static FastDateFormat getInstance(final String pattern, final Locale locale) { - return cache.getInstance(pattern, null, locale); - } - - /** - *

              - * Gets a formatter instance using the specified pattern, time zone and locale. - *

              - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone optional time zone, overrides time zone of formatted date - * @param locale optional locale, overrides system locale - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid or {@code null} - */ - public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) { - return cache.getInstance(pattern, timeZone, locale); - } - // ----------------------------------------------------------------------- /** *

              @@ -259,70 +188,6 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { return cache.getDateInstance(style, timeZone, locale); } - // ----------------------------------------------------------------------- - /** - *

              - * Gets a time formatter instance using the specified style in the default time - * zone and locale. - *

              - * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time pattern defined - * @since 2.1 - */ - public static FastDateFormat getTimeInstance(final int style) { - return cache.getTimeInstance(style, null, null); - } - - /** - *

              - * Gets a time formatter instance using the specified style and locale in the - * default time zone. - *

              - * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @param locale optional locale, overrides system locale - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time pattern defined - * @since 2.1 - */ - public static FastDateFormat getTimeInstance(final int style, final Locale locale) { - return cache.getTimeInstance(style, null, locale); - } - - /** - *

              - * Gets a time formatter instance using the specified style and time zone in the - * default locale. - *

              - * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of formatted time - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time pattern defined - * @since 2.1 - */ - public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone) { - return cache.getTimeInstance(style, timeZone, null); - } - - /** - *

              - * Gets a time formatter instance using the specified style, time zone and - * locale. - *

              - * - * @param style time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of formatted time - * @param locale optional locale, overrides system locale - * @return a localized standard time formatter - * @throws IllegalArgumentException if the Locale has no time pattern defined - */ - public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) { - return cache.getTimeInstance(style, timeZone, locale); - } - // ----------------------------------------------------------------------- /** *

              @@ -397,6 +262,142 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { return cache.getDateTimeInstance(dateStyle, timeStyle, timeZone, locale); } + // ----------------------------------------------------------------------- + /** + *

              + * Gets a formatter instance using the default pattern in the default locale. + *

              + * + * @return a date/time formatter + */ + public static FastDateFormat getInstance() { + return cache.getInstance(); + } + + /** + *

              + * Gets a formatter instance using the specified pattern in the default locale. + *

              + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern) { + return cache.getInstance(pattern, null, null); + } + + /** + *

              + * Gets a formatter instance using the specified pattern and locale. + *

              + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param locale optional locale, overrides system locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern, final Locale locale) { + return cache.getInstance(pattern, null, locale); + } + + /** + *

              + * Gets a formatter instance using the specified pattern and time zone. + *

              + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone optional time zone, overrides time zone of formatted date + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid + */ + public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone) { + return cache.getInstance(pattern, timeZone, null); + } + + /** + *

              + * Gets a formatter instance using the specified pattern, time zone and locale. + *

              + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern + * @param timeZone optional time zone, overrides time zone of formatted date + * @param locale optional locale, overrides system locale + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid or {@code null} + */ + public static FastDateFormat getInstance(final String pattern, final TimeZone timeZone, final Locale locale) { + return cache.getInstance(pattern, timeZone, locale); + } + + // ----------------------------------------------------------------------- + /** + *

              + * Gets a time formatter instance using the specified style in the default time + * zone and locale. + *

              + * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style) { + return cache.getTimeInstance(style, null, null); + } + + /** + *

              + * Gets a time formatter instance using the specified style and locale in the + * default time zone. + *

              + * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param locale optional locale, overrides system locale + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style, final Locale locale) { + return cache.getTimeInstance(style, null, locale); + } + + /** + *

              + * Gets a time formatter instance using the specified style and time zone in the + * default locale. + *

              + * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of formatted time + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time pattern defined + * @since 2.1 + */ + public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone) { + return cache.getTimeInstance(style, timeZone, null); + } + + /** + *

              + * Gets a time formatter instance using the specified style, time zone and + * locale. + *

              + * + * @param style time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of formatted time + * @param locale optional locale, overrides system locale + * @return a localized standard time formatter + * @throws IllegalArgumentException if the Locale has no time pattern defined + */ + public static FastDateFormat getTimeInstance(final int style, final TimeZone timeZone, final Locale locale) { + return cache.getTimeInstance(style, timeZone, locale); + } + + private final FastDatePrinter printer; + + private final FastDateParser parser; + // Constructor // ----------------------------------------------------------------------- /** @@ -434,6 +435,182 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { parser = new FastDateParser(pattern, timeZone, locale, centuryStart); } + /** + *

              + * Performs the formatting by applying the rules to the specified calendar. + *

              + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {@link #format(Calendar, Appendable)} + */ + @Deprecated + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + return printer.applyRules(calendar, buf); + } + + // Basics + // ----------------------------------------------------------------------- + /** + *

              + * Compares two objects for equality. + *

              + * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateFormat)) { + return false; + } + final FastDateFormat other = (FastDateFormat) obj; + // no need to check parser, as it has same invariants as printer + return printer.equals(other.printer); + } + + /** + *

              + * Formats a {@code Calendar} object. + *

              + * + * @param calendar the calendar to format + * @return the formatted string + */ + @Override + public String format(final Calendar calendar) { + return printer.format(calendar); + } + + /** + *

              + * Formats a {@code Calendar} object into the supplied {@code StringBuffer}. + *

              + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 3.5 + */ + @Override + public B format(final Calendar calendar, final B buf) { + return printer.format(calendar, buf); + } + + /** + *

              + * Formats a {@code Calendar} object into the supplied {@code StringBuffer}. + *

              + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Calendar, Appendable)}. + */ + @Deprecated + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + return printer.format(calendar, buf); + } + + /** + *

              + * Formats a {@code Date} object using a {@code GregorianCalendar}. + *

              + * + * @param date the date to format + * @return the formatted string + */ + @Override + public String format(final Date date) { + return printer.format(date); + } + + /** + *

              + * Formats a {@code Date} object into the supplied {@code StringBuffer} using a + * {@code GregorianCalendar}. + *

              + * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 3.5 + */ + @Override + public B format(final Date date, final B buf) { + return printer.format(date, buf); + } + + /** + *

              + * Formats a {@code Date} object into the supplied {@code StringBuffer} using a + * {@code GregorianCalendar}. + *

              + * + * @param date the date to format + * @param buf the buffer to format into + * @return the specified string buffer + * @deprecated Use {{@link #format(Date, Appendable)}. + */ + @Deprecated + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + return printer.format(date, buf); + } + + /** + *

              + * Formats a millisecond {@code long} value. + *

              + * + * @param millis the millisecond value to format + * @return the formatted string + * @since 2.1 + */ + @Override + public String format(final long millis) { + return printer.format(millis); + } + + /** + *

              + * Formats a millisecond {@code long} value into the supplied + * {@code StringBuffer}. + *

              + * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 3.5 + */ + @Override + public B format(final long millis, final B buf) { + return printer.format(millis, buf); + } + + // Parsing + // ----------------------------------------------------------------------- + + /** + *

              + * Formats a millisecond {@code long} value into the supplied + * {@code StringBuffer}. + *

              + * + * @param millis the millisecond value to format + * @param buf the buffer to format into + * @return the specified string buffer + * @since 2.1 + * @deprecated Use {{@link #format(long, Appendable)}. + */ + @Deprecated + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + return printer.format(millis, buf); + } + // Format methods // ----------------------------------------------------------------------- /** @@ -456,144 +633,74 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { /** *

              - * Formats a millisecond {@code long} value. + * Gets the locale used by this formatter. *

              * - * @param millis the millisecond value to format - * @return the formatted string - * @since 2.1 + * @return the locale */ @Override - public String format(final long millis) { - return printer.format(millis); + public Locale getLocale() { + return printer.getLocale(); } /** *

              - * Formats a {@code Date} object using a {@code GregorianCalendar}. + * Gets an estimate for the maximum string length that the formatter will + * produce. *

              * - * @param date the date to format - * @return the formatted string - */ - @Override - public String format(final Date date) { - return printer.format(date); - } - - /** *

              - * Formats a {@code Calendar} object. + * The actual formatted length will almost always be less than or equal to this + * amount. *

              * - * @param calendar the calendar to format - * @return the formatted string + * @return the maximum formatted length */ - @Override - public String format(final Calendar calendar) { - return printer.format(calendar); + public int getMaxLengthEstimate() { + return printer.getMaxLengthEstimate(); } - /** - *

              - * Formats a millisecond {@code long} value into the supplied - * {@code StringBuffer}. - *

              - * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 2.1 - * @deprecated Use {{@link #format(long, Appendable)}. - */ - @Deprecated - @Override - public StringBuffer format(final long millis, final StringBuffer buf) { - return printer.format(millis, buf); - } - - /** - *

              - * Formats a {@code Date} object into the supplied {@code StringBuffer} using a - * {@code GregorianCalendar}. - *

              - * - * @param date the date to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Date, Appendable)}. - */ - @Deprecated - @Override - public StringBuffer format(final Date date, final StringBuffer buf) { - return printer.format(date, buf); - } - - /** - *

              - * Formats a {@code Calendar} object into the supplied {@code StringBuffer}. - *

              - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {{@link #format(Calendar, Appendable)}. - */ - @Deprecated - @Override - public StringBuffer format(final Calendar calendar, final StringBuffer buf) { - return printer.format(calendar, buf); - } - - /** - *

              - * Formats a millisecond {@code long} value into the supplied - * {@code StringBuffer}. - *

              - * - * @param millis the millisecond value to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 3.5 - */ - @Override - public B format(final long millis, final B buf) { - return printer.format(millis, buf); - } - - /** - *

              - * Formats a {@code Date} object into the supplied {@code StringBuffer} using a - * {@code GregorianCalendar}. - *

              - * - * @param date the date to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 3.5 - */ - @Override - public B format(final Date date, final B buf) { - return printer.format(date, buf); - } - - /** - *

              - * Formats a {@code Calendar} object into the supplied {@code StringBuffer}. - *

              - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @since 3.5 - */ - @Override - public B format(final Calendar calendar, final B buf) { - return printer.format(calendar, buf); - } - - // Parsing + // Accessors // ----------------------------------------------------------------------- + /** + *

              + * Gets the pattern used by this formatter. + *

              + * + * @return the pattern, {@link java.text.SimpleDateFormat} compatible + */ + @Override + public String getPattern() { + return printer.getPattern(); + } + + /** + *

              + * Gets the time zone used by this formatter. + *

              + * + *

              + * This zone is always used for {@code Date} formatting. + *

              + * + * @return the time zone + */ + @Override + public TimeZone getTimeZone() { + return printer.getTimeZone(); + } + + /** + *

              + * Returns a hash code compatible with equals. + *

              + * + * @return a hash code compatible with equals + */ + @Override + public int hashCode() { + return printer.hashCode(); + } /* * (non-Javadoc) @@ -636,97 +743,6 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { return parser.parseObject(source, pos); } - // Accessors - // ----------------------------------------------------------------------- - /** - *

              - * Gets the pattern used by this formatter. - *

              - * - * @return the pattern, {@link java.text.SimpleDateFormat} compatible - */ - @Override - public String getPattern() { - return printer.getPattern(); - } - - /** - *

              - * Gets the time zone used by this formatter. - *

              - * - *

              - * This zone is always used for {@code Date} formatting. - *

              - * - * @return the time zone - */ - @Override - public TimeZone getTimeZone() { - return printer.getTimeZone(); - } - - /** - *

              - * Gets the locale used by this formatter. - *

              - * - * @return the locale - */ - @Override - public Locale getLocale() { - return printer.getLocale(); - } - - /** - *

              - * Gets an estimate for the maximum string length that the formatter will - * produce. - *

              - * - *

              - * The actual formatted length will almost always be less than or equal to this - * amount. - *

              - * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return printer.getMaxLengthEstimate(); - } - - // Basics - // ----------------------------------------------------------------------- - /** - *

              - * Compares two objects for equality. - *

              - * - * @param obj the object to compare to - * @return {@code true} if equal - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof FastDateFormat)) { - return false; - } - final FastDateFormat other = (FastDateFormat) obj; - // no need to check parser, as it has same invariants as printer - return printer.equals(other.printer); - } - - /** - *

              - * Returns a hash code compatible with equals. - *

              - * - * @return a hash code compatible with equals - */ - @Override - public int hashCode() { - return printer.hashCode(); - } - /** *

              * Gets a debugging string version of this formatter. @@ -739,19 +755,4 @@ public class FastDateFormat extends Format implements DateParser, DatePrinter { return "FastDateFormat[" + printer.getPattern() + "," + printer.getLocale() + "," + printer.getTimeZone().getID() + "]"; } - - /** - *

              - * Performs the formatting by applying the rules to the specified calendar. - *

              - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * @deprecated Use {@link #format(Calendar, Appendable)} - */ - @Deprecated - protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { - return printer.applyRules(calendar, buf); - } } diff --git a/src/main/java/org/apache/commons/lang3/time/FastDateParser.java b/src/main/java/org/apache/commons/lang3/time/FastDateParser.java index 1feb2b45..f91d75ef 100644 --- a/src/main/java/org/apache/commons/lang3/time/FastDateParser.java +++ b/src/main/java/org/apache/commons/lang3/time/FastDateParser.java @@ -87,108 +87,317 @@ import org.apache.commons.lang3.LocaleUtils; public class FastDateParser implements DateParser, Serializable { /** - * Required for serialization support. - * - * @see java.io.Serializable + * A strategy that handles a text field in the parsing pattern */ - private static final long serialVersionUID = 3L; + private static class CaseInsensitiveTextStrategy extends PatternStrategy { + private final int field; + final Locale locale; + private final Map lKeyValues; - static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP"); + /** + * Constructs a Strategy that parses a Text field + * + * @param field The Calendar field + * @param definingCalendar The Calendar to use + * @param locale The Locale to use + */ + CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) { + this.field = field; + this.locale = LocaleUtils.toLocale(locale); - // defining fields - private final String pattern; - private final TimeZone timeZone; - private final Locale locale; - private final int century; - private final int startYear; - - // derived fields - private transient List patterns; - - // comparator used to sort regex alternatives - // alternatives should be ordered longer first, and shorter last. ('february' - // before 'feb') - // all entries must be lowercase by locale. - private static final Comparator LONGER_FIRST_LOWERCASE = Comparator.reverseOrder(); - - /** - *

              - * Constructs a new FastDateParser. - *

              - * - * Use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} or another - * variation of the factory methods of {@link FastDateFormat} to get a cached - * FastDateParser instance. - * - * @param pattern non-null {@link java.text.SimpleDateFormat} compatible - * pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale - */ - protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) { - this(pattern, timeZone, locale, null); - } - - /** - *

              - * Constructs a new FastDateParser. - *

              - * - * @param pattern non-null {@link java.text.SimpleDateFormat} compatible - * pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale - * @param centuryStart The start of the century for 2 digit year parsing - * - * @since 3.5 - */ - protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, - final Date centuryStart) { - this.pattern = pattern; - this.timeZone = timeZone; - this.locale = LocaleUtils.toLocale(locale); - - final Calendar definingCalendar = Calendar.getInstance(timeZone, this.locale); - - final int centuryStartYear; - if (centuryStart != null) { - definingCalendar.setTime(centuryStart); - centuryStartYear = definingCalendar.get(Calendar.YEAR); - } else if (this.locale.equals(JAPANESE_IMPERIAL)) { - centuryStartYear = 0; - } else { - // from 80 years ago to 20 years from now - definingCalendar.setTime(new Date()); - centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80; + final StringBuilder regex = new StringBuilder(); + regex.append("((?iu)"); + lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex); + regex.setLength(regex.length() - 1); + regex.append(")"); + createPattern(regex); } - century = centuryStartYear / 100 * 100; - startYear = centuryStartYear - century; - init(definingCalendar); - } - - /** - * Initializes derived fields from defining fields. This is called from - * constructor and from readObject (de-serialization) - * - * @param definingCalendar the {@link java.util.Calendar} instance used to - * initialize this FastDateParser - */ - private void init(final Calendar definingCalendar) { - patterns = new ArrayList<>(); - - final StrategyParser fm = new StrategyParser(definingCalendar); - for (;;) { - final StrategyAndWidth field = fm.getNextStrategy(); - if (field == null) { - break; + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) { + final String lowerCase = value.toLowerCase(locale); + Integer iVal = lKeyValues.get(lowerCase); + if (iVal == null) { + // match missing the optional trailing period + iVal = lKeyValues.get(lowerCase + '.'); } - patterns.add(field); + calendar.set(field, iVal.intValue()); + } + + /** + * Converts this instance to a handy debug string. + * + * @since 3.12.0 + */ + @Override + public String toString() { + return "CaseInsensitiveTextStrategy [field=" + field + ", locale=" + locale + ", lKeyValues=" + lKeyValues + + ", pattern=" + pattern + "]"; } } - // helper classes to parse the format string - // ----------------------------------------------------------------------- + /** + * A strategy that copies the static or quoted field in the parsing pattern + */ + private static class CopyQuotedStrategy extends Strategy { + + private final String formatField; + + /** + * Constructs a Strategy that ensures the formatField has literal text + * + * @param formatField The literal text to match + */ + CopyQuotedStrategy(final String formatField) { + this.formatField = formatField; + } + + /** + * {@inheritDoc} + */ + @Override + boolean isNumber() { + return false; + } + + @Override + boolean parse(final FastDateParser parser, final Calendar calendar, final String source, + final ParsePosition pos, final int maxWidth) { + for (int idx = 0; idx < formatField.length(); ++idx) { + final int sIdx = idx + pos.getIndex(); + if (sIdx == source.length()) { + pos.setErrorIndex(sIdx); + return false; + } + if (formatField.charAt(idx) != source.charAt(sIdx)) { + pos.setErrorIndex(sIdx); + return false; + } + } + pos.setIndex(formatField.length() + pos.getIndex()); + return true; + } + + /** + * Converts this instance to a handy debug string. + * + * @since 3.12.0 + */ + @Override + public String toString() { + return "CopyQuotedStrategy [formatField=" + formatField + "]"; + } + } + + private static class ISO8601TimeZoneStrategy extends PatternStrategy { + // Z, +hh, -hh, +hhmm, -hhmm, +hh:mm or -hh:mm + + private static final Strategy ISO_8601_1_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}))"); + + private static final Strategy ISO_8601_2_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}\\d{2}))"); + + private static final Strategy ISO_8601_3_STRATEGY = new ISO8601TimeZoneStrategy( + "(Z|(?:[+-]\\d{2}(?::)\\d{2}))"); + + /** + * Factory method for ISO8601TimeZoneStrategies. + * + * @param tokenLen a token indicating the length of the TimeZone String to be + * formatted. + * @return a ISO8601TimeZoneStrategy that can format TimeZone String of length + * {@code tokenLen}. If no such strategy exists, an + * IllegalArgumentException will be thrown. + */ + static Strategy getStrategy(final int tokenLen) { + switch (tokenLen) { + case 1: + return ISO_8601_1_STRATEGY; + case 2: + return ISO_8601_2_STRATEGY; + case 3: + return ISO_8601_3_STRATEGY; + default: + throw new IllegalArgumentException("invalid number of X"); + } + } + + /** + * Constructs a Strategy that parses a TimeZone + * + * @param pattern The Pattern + */ + ISO8601TimeZoneStrategy(final String pattern) { + createPattern(pattern); + } + + /** + * {@inheritDoc} + */ + @Override + void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) { + calendar.setTimeZone(FastTimeZone.getGmtTimeZone(value)); + } + } + + /** + * A strategy that handles a number field in the parsing pattern + */ + private static class NumberStrategy extends Strategy { + + private final int field; + + /** + * Constructs a Strategy that parses a Number field + * + * @param field The Calendar field + */ + NumberStrategy(final int field) { + this.field = field; + } + + /** + * {@inheritDoc} + */ + @Override + boolean isNumber() { + return true; + } + + /** + * Make any modifications to parsed integer + * + * @param parser The parser + * @param iValue The parsed integer + * @return The modified value + */ + int modify(final FastDateParser parser, final int iValue) { + return iValue; + } + + @Override + boolean parse(final FastDateParser parser, final Calendar calendar, final String source, + final ParsePosition pos, final int maxWidth) { + int idx = pos.getIndex(); + int last = source.length(); + + if (maxWidth == 0) { + // if no maxWidth, strip leading white space + for (; idx < last; ++idx) { + final char c = source.charAt(idx); + if (!Character.isWhitespace(c)) { + break; + } + } + pos.setIndex(idx); + } else { + final int end = idx + maxWidth; + if (last > end) { + last = end; + } + } + + for (; idx < last; ++idx) { + final char c = source.charAt(idx); + if (!Character.isDigit(c)) { + break; + } + } + + if (pos.getIndex() == idx) { + pos.setErrorIndex(idx); + return false; + } + + final int value = Integer.parseInt(source.substring(pos.getIndex(), idx)); + pos.setIndex(idx); + + calendar.set(field, modify(parser, value)); + return true; + } + + /** + * Converts this instance to a handy debug string. + * + * @since 3.12.0 + */ + @Override + public String toString() { + return "NumberStrategy [field=" + field + "]"; + } + } + + /** + * A strategy to parse a single field from the parsing pattern + */ + private abstract static class PatternStrategy extends Strategy { + + Pattern pattern; + + void createPattern(final String regex) { + this.pattern = Pattern.compile(regex); + } + + void createPattern(final StringBuilder regex) { + createPattern(regex.toString()); + } + + /** + * Is this field a number? The default implementation returns false. + * + * @return true, if field is a number + */ + @Override + boolean isNumber() { + return false; + } + + @Override + boolean parse(final FastDateParser parser, final Calendar calendar, final String source, + final ParsePosition pos, final int maxWidth) { + final Matcher matcher = pattern.matcher(source.substring(pos.getIndex())); + if (!matcher.lookingAt()) { + pos.setErrorIndex(pos.getIndex()); + return false; + } + pos.setIndex(pos.getIndex() + matcher.end(1)); + setCalendar(parser, calendar, matcher.group(1)); + return true; + } + + abstract void setCalendar(FastDateParser parser, Calendar calendar, String value); + + /** + * Converts this instance to a handy debug string. + * + * @since 3.12.0 + */ + @Override + public String toString() { + return getClass().getSimpleName() + " [pattern=" + pattern + "]"; + } + + } + + /** + * A strategy to parse a single field from the parsing pattern + */ + private abstract static class Strategy { + + /** + * Is this field a number? The default implementation returns false. + * + * @return true, if field is a number + */ + boolean isNumber() { + return false; + } + + abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos, + int maxWidth); + } /** * Holds strategy and field width @@ -278,657 +487,10 @@ public class FastDateParser implements DateParser, Serializable { } } - private static boolean isFormatLetter(final char c) { - return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; - } - - // Accessors - // ----------------------------------------------------------------------- - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DateParser#getPattern() - */ - @Override - public String getPattern() { - return pattern; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DateParser#getTimeZone() - */ - @Override - public TimeZone getTimeZone() { - return timeZone; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DateParser#getLocale() - */ - @Override - public Locale getLocale() { - return locale; - } - - // Basics - // ----------------------------------------------------------------------- - /** - *

              - * Compares another object for equality with this object. - *

              - * - * @param obj the object to compare to - * @return {@code true}if equal to this instance - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof FastDateParser)) { - return false; - } - final FastDateParser other = (FastDateParser) obj; - return pattern.equals(other.pattern) && timeZone.equals(other.timeZone) && locale.equals(other.locale); - } - - /** - *

              - * Returns a hash code compatible with equals. - *

              - * - * @return a hash code compatible with equals - */ - @Override - public int hashCode() { - return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); - } - - /** - *

              - * Gets a string version of this formatter. - *

              - * - * @return a debugging string - */ - @Override - public String toString() { - return "FastDateParser[" + pattern + ", " + locale + ", " + timeZone.getID() + "]"; - } - - /** - * Converts all state of this instance to a String handy for debugging. - * - * @return a string. - * @since 3.12.0 - */ - public String toStringAll() { - return "FastDateParser [pattern=" + pattern + ", timeZone=" + timeZone + ", locale=" + locale + ", century=" - + century + ", startYear=" + startYear + ", patterns=" + patterns + "]"; - } - - // Serializing - /** - * Creates the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - - final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); - init(definingCalendar); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String) - */ - @Override - public Object parseObject(final String source) throws ParseException { - return parse(source); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String) - */ - @Override - public Date parse(final String source) throws ParseException { - final ParsePosition pp = new ParsePosition(0); - final Date date = parse(source, pp); - if (date == null) { - // Add a note re supported date range - if (locale.equals(JAPANESE_IMPERIAL)) { - throw new ParseException("(The " + locale + " locale does not support dates before 1868 AD)\n" - + "Unparseable date: \"" + source, pp.getErrorIndex()); - } - throw new ParseException("Unparseable date: " + source, pp.getErrorIndex()); - } - return date; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, - * java.text.ParsePosition) - */ - @Override - public Object parseObject(final String source, final ParsePosition pos) { - return parse(source, pos); - } - - /** - * This implementation updates the ParsePosition if the parse succeeds. However, - * it sets the error index to the position before the failed field unlike the - * method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)} which - * sets the error index to after the failed field. - *

              - * To determine if the parse has succeeded, the caller must check if the current - * parse position given by {@link ParsePosition#getIndex()} has been updated. If - * the input buffer has been fully parsed, then the index will point to just - * after the end of the input buffer. - * - * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, - * java.text.ParsePosition) - */ - @Override - public Date parse(final String source, final ParsePosition pos) { - // timing tests indicate getting new instance is 19% faster than cloning - final Calendar cal = Calendar.getInstance(timeZone, locale); - cal.clear(); - - return parse(source, pos, cal) ? cal.getTime() : null; - } - - /** - * Parses a formatted date string according to the format. Updates the Calendar - * with parsed fields. Upon success, the ParsePosition index is updated to - * indicate how much of the source text was consumed. Not all source text needs - * to be consumed. Upon parse failure, ParsePosition error index is updated to - * the offset of the source text which does not match the supplied format. - * - * @param source The text to parse. - * @param pos On input, the position in the source to start parsing, on - * output, updated position. - * @param calendar The calendar into which to set parsed fields. - * @return true, if source has been parsed (pos parsePosition is updated); - * otherwise false (and pos errorIndex is updated) - * @throws IllegalArgumentException when Calendar has been set to be not - * lenient, and a parsed field is out of range. - */ - @Override - public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { - final ListIterator lt = patterns.listIterator(); - while (lt.hasNext()) { - final StrategyAndWidth strategyAndWidth = lt.next(); - final int maxWidth = strategyAndWidth.getMaxWidth(lt); - if (!strategyAndWidth.strategy.parse(this, calendar, source, pos, maxWidth)) { - return false; - } - } - return true; - } - - // Support for strategies - // ----------------------------------------------------------------------- - - private static StringBuilder simpleQuote(final StringBuilder sb, final String value) { - for (int i = 0; i < value.length(); ++i) { - final char c = value.charAt(i); - switch (c) { - case '\\': - case '^': - case '$': - case '.': - case '|': - case '?': - case '*': - case '+': - case '(': - case ')': - case '[': - case '{': - sb.append('\\'); - default: - sb.append(c); - } - } - if (sb.charAt(sb.length() - 1) == '.') { - // trailing '.' is optional - sb.append('?'); - } - return sb; - } - - /** - * Gets the short and long values displayed for a field - * - * @param calendar The calendar to obtain the short and long values - * @param locale The locale of display names - * @param field The field of interest - * @param regex The regular expression to build - * @return The map of string display names to field values - */ - private static Map appendDisplayNames(final Calendar calendar, Locale locale, final int field, - final StringBuilder regex) { - final Map values = new HashMap<>(); - locale = LocaleUtils.toLocale(locale); - final Map displayNames = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale); - final TreeSet sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); - for (final Map.Entry displayName : displayNames.entrySet()) { - final String key = displayName.getKey().toLowerCase(locale); - if (sorted.add(key)) { - values.put(key, displayName.getValue()); - } - } - for (final String symbol : sorted) { - simpleQuote(regex, symbol).append('|'); - } - return values; - } - - /** - * Adjusts dates to be within appropriate century - * - * @param twoDigitYear The year to adjust - * @return A value between centuryStart(inclusive) to - * centuryStart+100(exclusive) - */ - private int adjustYear(final int twoDigitYear) { - final int trial = century + twoDigitYear; - return twoDigitYear >= startYear ? trial : trial + 100; - } - - /** - * A strategy to parse a single field from the parsing pattern - */ - private abstract static class Strategy { - - /** - * Is this field a number? The default implementation returns false. - * - * @return true, if field is a number - */ - boolean isNumber() { - return false; - } - - abstract boolean parse(FastDateParser parser, Calendar calendar, String source, ParsePosition pos, - int maxWidth); - } - - /** - * A strategy to parse a single field from the parsing pattern - */ - private abstract static class PatternStrategy extends Strategy { - - Pattern pattern; - - void createPattern(final StringBuilder regex) { - createPattern(regex.toString()); - } - - void createPattern(final String regex) { - this.pattern = Pattern.compile(regex); - } - - /** - * Is this field a number? The default implementation returns false. - * - * @return true, if field is a number - */ - @Override - boolean isNumber() { - return false; - } - - @Override - boolean parse(final FastDateParser parser, final Calendar calendar, final String source, - final ParsePosition pos, final int maxWidth) { - final Matcher matcher = pattern.matcher(source.substring(pos.getIndex())); - if (!matcher.lookingAt()) { - pos.setErrorIndex(pos.getIndex()); - return false; - } - pos.setIndex(pos.getIndex() + matcher.end(1)); - setCalendar(parser, calendar, matcher.group(1)); - return true; - } - - abstract void setCalendar(FastDateParser parser, Calendar calendar, String value); - - /** - * Converts this instance to a handy debug string. - * - * @since 3.12.0 - */ - @Override - public String toString() { - return getClass().getSimpleName() + " [pattern=" + pattern + "]"; - } - - } - - /** - * Gets a Strategy given a field from a SimpleDateFormat pattern - * - * @param f A sub-sequence of the SimpleDateFormat pattern - * @param definingCalendar The calendar to obtain the short and long values - * @return The Strategy that will handle parsing for the field - */ - private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) { - switch (f) { - default: - throw new IllegalArgumentException("Format '" + f + "' not supported"); - case 'D': - return DAY_OF_YEAR_STRATEGY; - case 'E': - return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); - case 'F': - return DAY_OF_WEEK_IN_MONTH_STRATEGY; - case 'G': - return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); - case 'H': // Hour in day (0-23) - return HOUR_OF_DAY_STRATEGY; - case 'K': // Hour in am/pm (0-11) - return HOUR_STRATEGY; - case 'M': - return width >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY; - case 'S': - return MILLISECOND_STRATEGY; - case 'W': - return WEEK_OF_MONTH_STRATEGY; - case 'a': - return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); - case 'd': - return DAY_OF_MONTH_STRATEGY; - case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 - return HOUR12_STRATEGY; - case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0 - return HOUR24_OF_DAY_STRATEGY; - case 'm': - return MINUTE_STRATEGY; - case 's': - return SECOND_STRATEGY; - case 'u': - return DAY_OF_WEEK_STRATEGY; - case 'w': - return WEEK_OF_YEAR_STRATEGY; - case 'y': - case 'Y': - return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY; - case 'X': - return ISO8601TimeZoneStrategy.getStrategy(width); - case 'Z': - if (width == 2) { - return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY; - } - //$FALL-THROUGH$ - case 'z': - return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); - } - } - - @SuppressWarnings("unchecked") // OK because we are creating an array with no entries - private static final Map[] caches = new Map[Calendar.FIELD_COUNT]; - - /** - * Gets a cache of Strategies for a particular field - * - * @param field The Calendar field - * @return a cache of Locale to Strategy - */ - private static Map getCache(final int field) { - synchronized (caches) { - if (caches[field] == null) { - caches[field] = new HashMap<>(3); - } - return caches[field]; - } - } - - /** - * Constructs a Strategy that parses a Text field - * - * @param field The Calendar field - * @param definingCalendar The calendar to obtain the short and long values - * @return a TextStrategy for the field and Locale - */ - private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) { - final Map cache = getCache(field); - Strategy strategy = cache.get(locale); - if (strategy == null) { - strategy = field == Calendar.ZONE_OFFSET ? new TimeZoneStrategy(locale) - : new CaseInsensitiveTextStrategy(field, definingCalendar, locale); - final Strategy inCache = cache.putIfAbsent(locale, strategy); - if (inCache != null) { - return inCache; - } - } - return strategy; - } - - /** - * A strategy that copies the static or quoted field in the parsing pattern - */ - private static class CopyQuotedStrategy extends Strategy { - - private final String formatField; - - /** - * Constructs a Strategy that ensures the formatField has literal text - * - * @param formatField The literal text to match - */ - CopyQuotedStrategy(final String formatField) { - this.formatField = formatField; - } - - /** - * {@inheritDoc} - */ - @Override - boolean isNumber() { - return false; - } - - @Override - boolean parse(final FastDateParser parser, final Calendar calendar, final String source, - final ParsePosition pos, final int maxWidth) { - for (int idx = 0; idx < formatField.length(); ++idx) { - final int sIdx = idx + pos.getIndex(); - if (sIdx == source.length()) { - pos.setErrorIndex(sIdx); - return false; - } - if (formatField.charAt(idx) != source.charAt(sIdx)) { - pos.setErrorIndex(sIdx); - return false; - } - } - pos.setIndex(formatField.length() + pos.getIndex()); - return true; - } - - /** - * Converts this instance to a handy debug string. - * - * @since 3.12.0 - */ - @Override - public String toString() { - return "CopyQuotedStrategy [formatField=" + formatField + "]"; - } - } - - /** - * A strategy that handles a text field in the parsing pattern - */ - private static class CaseInsensitiveTextStrategy extends PatternStrategy { - private final int field; - final Locale locale; - private final Map lKeyValues; - - /** - * Constructs a Strategy that parses a Text field - * - * @param field The Calendar field - * @param definingCalendar The Calendar to use - * @param locale The Locale to use - */ - CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) { - this.field = field; - this.locale = LocaleUtils.toLocale(locale); - - final StringBuilder regex = new StringBuilder(); - regex.append("((?iu)"); - lKeyValues = appendDisplayNames(definingCalendar, locale, field, regex); - regex.setLength(regex.length() - 1); - regex.append(")"); - createPattern(regex); - } - - /** - * {@inheritDoc} - */ - @Override - void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) { - final String lowerCase = value.toLowerCase(locale); - Integer iVal = lKeyValues.get(lowerCase); - if (iVal == null) { - // match missing the optional trailing period - iVal = lKeyValues.get(lowerCase + '.'); - } - calendar.set(field, iVal.intValue()); - } - - /** - * Converts this instance to a handy debug string. - * - * @since 3.12.0 - */ - @Override - public String toString() { - return "CaseInsensitiveTextStrategy [field=" + field + ", locale=" + locale + ", lKeyValues=" + lKeyValues - + ", pattern=" + pattern + "]"; - } - } - - /** - * A strategy that handles a number field in the parsing pattern - */ - private static class NumberStrategy extends Strategy { - - private final int field; - - /** - * Constructs a Strategy that parses a Number field - * - * @param field The Calendar field - */ - NumberStrategy(final int field) { - this.field = field; - } - - /** - * {@inheritDoc} - */ - @Override - boolean isNumber() { - return true; - } - - @Override - boolean parse(final FastDateParser parser, final Calendar calendar, final String source, - final ParsePosition pos, final int maxWidth) { - int idx = pos.getIndex(); - int last = source.length(); - - if (maxWidth == 0) { - // if no maxWidth, strip leading white space - for (; idx < last; ++idx) { - final char c = source.charAt(idx); - if (!Character.isWhitespace(c)) { - break; - } - } - pos.setIndex(idx); - } else { - final int end = idx + maxWidth; - if (last > end) { - last = end; - } - } - - for (; idx < last; ++idx) { - final char c = source.charAt(idx); - if (!Character.isDigit(c)) { - break; - } - } - - if (pos.getIndex() == idx) { - pos.setErrorIndex(idx); - return false; - } - - final int value = Integer.parseInt(source.substring(pos.getIndex(), idx)); - pos.setIndex(idx); - - calendar.set(field, modify(parser, value)); - return true; - } - - /** - * Make any modifications to parsed integer - * - * @param parser The parser - * @param iValue The parsed integer - * @return The modified value - */ - int modify(final FastDateParser parser, final int iValue) { - return iValue; - } - - /** - * Converts this instance to a handy debug string. - * - * @since 3.12.0 - */ - @Override - public String toString() { - return "NumberStrategy [field=" + field + "]"; - } - } - - private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) { - /** - * {@inheritDoc} - */ - @Override - int modify(final FastDateParser parser, final int iValue) { - return iValue < 100 ? parser.adjustYear(iValue) : iValue; - } - }; - /** * A strategy that handles a time zone field in the parsing pattern */ static class TimeZoneStrategy extends PatternStrategy { - private static final String RFC_822_TIME_ZONE = "[+-]\\d{4}"; - private static final String GMT_OPTION = TimeZones.GMT_ID + "[+-]\\d{1,2}:\\d{2}"; - - private final Locale locale; - private final Map tzNames = new HashMap<>(); - private static class TzInfo { final TimeZone zone; final int dstOffset; @@ -939,11 +501,18 @@ public class FastDateParser implements DateParser, Serializable { } } + private static final String RFC_822_TIME_ZONE = "[+-]\\d{4}"; + + private static final String GMT_OPTION = TimeZones.GMT_ID + "[+-]\\d{1,2}:\\d{2}"; /** * Index of zone id */ private static final int ID = 0; + private final Locale locale; + + private final Map tzNames = new HashMap<>(); + /** * Constructs a Strategy that parses a TimeZone * @@ -1032,53 +601,36 @@ public class FastDateParser implements DateParser, Serializable { } - private static class ISO8601TimeZoneStrategy extends PatternStrategy { - // Z, +hh, -hh, +hhmm, -hhmm, +hh:mm or -hh:mm + /** + * Required for serialization support. + * + * @see java.io.Serializable + */ + private static final long serialVersionUID = 3L; - /** - * Constructs a Strategy that parses a TimeZone - * - * @param pattern The Pattern - */ - ISO8601TimeZoneStrategy(final String pattern) { - createPattern(pattern); - } + static final Locale JAPANESE_IMPERIAL = new Locale("ja", "JP", "JP"); + // comparator used to sort regex alternatives + // alternatives should be ordered longer first, and shorter last. ('february' + // before 'feb') + // all entries must be lowercase by locale. + private static final Comparator LONGER_FIRST_LOWERCASE = Comparator.reverseOrder(); + + // helper classes to parse the format string + // ----------------------------------------------------------------------- + + @SuppressWarnings("unchecked") // OK because we are creating an array with no entries + private static final Map[] caches = new Map[Calendar.FIELD_COUNT]; + + private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) { /** * {@inheritDoc} */ @Override - void setCalendar(final FastDateParser parser, final Calendar calendar, final String value) { - calendar.setTimeZone(FastTimeZone.getGmtTimeZone(value)); + int modify(final FastDateParser parser, final int iValue) { + return iValue < 100 ? parser.adjustYear(iValue) : iValue; } - - private static final Strategy ISO_8601_1_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}))"); - private static final Strategy ISO_8601_2_STRATEGY = new ISO8601TimeZoneStrategy("(Z|(?:[+-]\\d{2}\\d{2}))"); - private static final Strategy ISO_8601_3_STRATEGY = new ISO8601TimeZoneStrategy( - "(Z|(?:[+-]\\d{2}(?::)\\d{2}))"); - - /** - * Factory method for ISO8601TimeZoneStrategies. - * - * @param tokenLen a token indicating the length of the TimeZone String to be - * formatted. - * @return a ISO8601TimeZoneStrategy that can format TimeZone String of length - * {@code tokenLen}. If no such strategy exists, an - * IllegalArgumentException will be thrown. - */ - static Strategy getStrategy(final int tokenLen) { - switch (tokenLen) { - case 1: - return ISO_8601_1_STRATEGY; - case 2: - return ISO_8601_2_STRATEGY; - case 3: - return ISO_8601_3_STRATEGY; - default: - throw new IllegalArgumentException("invalid number of X"); - } - } - } + }; private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) { @Override @@ -1088,10 +640,15 @@ public class FastDateParser implements DateParser, Serializable { }; private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR); + private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR); + private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH); + private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR); + private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH); + private static final Strategy DAY_OF_WEEK_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK) { @Override int modify(final FastDateParser parser, final int iValue) { @@ -1100,7 +657,9 @@ public class FastDateParser implements DateParser, Serializable { }; private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH); + private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY); + private static final Strategy HOUR24_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) { @Override int modify(final FastDateParser parser, final int iValue) { @@ -1116,7 +675,465 @@ public class FastDateParser implements DateParser, Serializable { }; private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR); + private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE); + private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND); + + // Support for strategies + // ----------------------------------------------------------------------- + private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND); + + /** + * Gets the short and long values displayed for a field + * + * @param calendar The calendar to obtain the short and long values + * @param locale The locale of display names + * @param field The field of interest + * @param regex The regular expression to build + * @return The map of string display names to field values + */ + private static Map appendDisplayNames(final Calendar calendar, Locale locale, final int field, + final StringBuilder regex) { + final Map values = new HashMap<>(); + locale = LocaleUtils.toLocale(locale); + final Map displayNames = calendar.getDisplayNames(field, Calendar.ALL_STYLES, locale); + final TreeSet sorted = new TreeSet<>(LONGER_FIRST_LOWERCASE); + for (final Map.Entry displayName : displayNames.entrySet()) { + final String key = displayName.getKey().toLowerCase(locale); + if (sorted.add(key)) { + values.put(key, displayName.getValue()); + } + } + for (final String symbol : sorted) { + simpleQuote(regex, symbol).append('|'); + } + return values; + } + + /** + * Gets a cache of Strategies for a particular field + * + * @param field The Calendar field + * @return a cache of Locale to Strategy + */ + private static Map getCache(final int field) { + synchronized (caches) { + if (caches[field] == null) { + caches[field] = new HashMap<>(3); + } + return caches[field]; + } + } + + private static boolean isFormatLetter(final char c) { + return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z'; + } + + private static StringBuilder simpleQuote(final StringBuilder sb, final String value) { + for (int i = 0; i < value.length(); ++i) { + final char c = value.charAt(i); + switch (c) { + case '\\': + case '^': + case '$': + case '.': + case '|': + case '?': + case '*': + case '+': + case '(': + case ')': + case '[': + case '{': + sb.append('\\'); + default: + sb.append(c); + } + } + if (sb.charAt(sb.length() - 1) == '.') { + // trailing '.' is optional + sb.append('?'); + } + return sb; + } + + // defining fields + private final String pattern; + + private final TimeZone timeZone; + + private final Locale locale; + + private final int century; + + private final int startYear; + + // derived fields + private transient List patterns; + + /** + *

              + * Constructs a new FastDateParser. + *

              + * + * Use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} or another + * variation of the factory methods of {@link FastDateFormat} to get a cached + * FastDateParser instance. + * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) { + this(pattern, timeZone, locale, null); + } + + /** + *

              + * Constructs a new FastDateParser. + *

              + * + * @param pattern non-null {@link java.text.SimpleDateFormat} compatible + * pattern + * @param timeZone non-null time zone to use + * @param locale non-null locale + * @param centuryStart The start of the century for 2 digit year parsing + * + * @since 3.5 + */ + protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, + final Date centuryStart) { + this.pattern = pattern; + this.timeZone = timeZone; + this.locale = LocaleUtils.toLocale(locale); + + final Calendar definingCalendar = Calendar.getInstance(timeZone, this.locale); + + final int centuryStartYear; + if (centuryStart != null) { + definingCalendar.setTime(centuryStart); + centuryStartYear = definingCalendar.get(Calendar.YEAR); + } else if (this.locale.equals(JAPANESE_IMPERIAL)) { + centuryStartYear = 0; + } else { + // from 80 years ago to 20 years from now + definingCalendar.setTime(new Date()); + centuryStartYear = definingCalendar.get(Calendar.YEAR) - 80; + } + century = centuryStartYear / 100 * 100; + startYear = centuryStartYear - century; + + init(definingCalendar); + } + + /** + * Adjusts dates to be within appropriate century + * + * @param twoDigitYear The year to adjust + * @return A value between centuryStart(inclusive) to + * centuryStart+100(exclusive) + */ + private int adjustYear(final int twoDigitYear) { + final int trial = century + twoDigitYear; + return twoDigitYear >= startYear ? trial : trial + 100; + } + + // Basics + // ----------------------------------------------------------------------- + /** + *

              + * Compares another object for equality with this object. + *

              + * + * @param obj the object to compare to + * @return {@code true}if equal to this instance + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDateParser)) { + return false; + } + final FastDateParser other = (FastDateParser) obj; + return pattern.equals(other.pattern) && timeZone.equals(other.timeZone) && locale.equals(other.locale); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DateParser#getLocale() + */ + @Override + public Locale getLocale() { + return locale; + } + + /** + * Constructs a Strategy that parses a Text field + * + * @param field The Calendar field + * @param definingCalendar The calendar to obtain the short and long values + * @return a TextStrategy for the field and Locale + */ + private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) { + final Map cache = getCache(field); + Strategy strategy = cache.get(locale); + if (strategy == null) { + strategy = field == Calendar.ZONE_OFFSET ? new TimeZoneStrategy(locale) + : new CaseInsensitiveTextStrategy(field, definingCalendar, locale); + final Strategy inCache = cache.putIfAbsent(locale, strategy); + if (inCache != null) { + return inCache; + } + } + return strategy; + } + + // Accessors + // ----------------------------------------------------------------------- + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DateParser#getPattern() + */ + @Override + public String getPattern() { + return pattern; + } + + /** + * Gets a Strategy given a field from a SimpleDateFormat pattern + * + * @param f A sub-sequence of the SimpleDateFormat pattern + * @param definingCalendar The calendar to obtain the short and long values + * @return The Strategy that will handle parsing for the field + */ + private Strategy getStrategy(final char f, final int width, final Calendar definingCalendar) { + switch (f) { + default: + throw new IllegalArgumentException("Format '" + f + "' not supported"); + case 'D': + return DAY_OF_YEAR_STRATEGY; + case 'E': + return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar); + case 'F': + return DAY_OF_WEEK_IN_MONTH_STRATEGY; + case 'G': + return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar); + case 'H': // Hour in day (0-23) + return HOUR_OF_DAY_STRATEGY; + case 'K': // Hour in am/pm (0-11) + return HOUR_STRATEGY; + case 'M': + return width >= 3 ? getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) : NUMBER_MONTH_STRATEGY; + case 'S': + return MILLISECOND_STRATEGY; + case 'W': + return WEEK_OF_MONTH_STRATEGY; + case 'a': + return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar); + case 'd': + return DAY_OF_MONTH_STRATEGY; + case 'h': // Hour in am/pm (1-12), i.e. midday/midnight is 12, not 0 + return HOUR12_STRATEGY; + case 'k': // Hour in day (1-24), i.e. midnight is 24, not 0 + return HOUR24_OF_DAY_STRATEGY; + case 'm': + return MINUTE_STRATEGY; + case 's': + return SECOND_STRATEGY; + case 'u': + return DAY_OF_WEEK_STRATEGY; + case 'w': + return WEEK_OF_YEAR_STRATEGY; + case 'y': + case 'Y': + return width > 2 ? LITERAL_YEAR_STRATEGY : ABBREVIATED_YEAR_STRATEGY; + case 'X': + return ISO8601TimeZoneStrategy.getStrategy(width); + case 'Z': + if (width == 2) { + return ISO8601TimeZoneStrategy.ISO_8601_3_STRATEGY; + } + //$FALL-THROUGH$ + case 'z': + return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DateParser#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return timeZone; + } + + /** + *

              + * Returns a hash code compatible with equals. + *

              + * + * @return a hash code compatible with equals + */ + @Override + public int hashCode() { + return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode()); + } + + /** + * Initializes derived fields from defining fields. This is called from + * constructor and from readObject (de-serialization) + * + * @param definingCalendar the {@link java.util.Calendar} instance used to + * initialize this FastDateParser + */ + private void init(final Calendar definingCalendar) { + patterns = new ArrayList<>(); + + final StrategyParser fm = new StrategyParser(definingCalendar); + for (;;) { + final StrategyAndWidth field = fm.getNextStrategy(); + if (field == null) { + break; + } + patterns.add(field); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String) + */ + @Override + public Date parse(final String source) throws ParseException { + final ParsePosition pp = new ParsePosition(0); + final Date date = parse(source, pp); + if (date == null) { + // Add a note re supported date range + if (locale.equals(JAPANESE_IMPERIAL)) { + throw new ParseException("(The " + locale + " locale does not support dates before 1868 AD)\n" + + "Unparseable date: \"" + source, pp.getErrorIndex()); + } + throw new ParseException("Unparseable date: " + source, pp.getErrorIndex()); + } + return date; + } + + /** + * This implementation updates the ParsePosition if the parse succeeds. However, + * it sets the error index to the position before the failed field unlike the + * method {@link java.text.SimpleDateFormat#parse(String, ParsePosition)} which + * sets the error index to after the failed field. + *

              + * To determine if the parse has succeeded, the caller must check if the current + * parse position given by {@link ParsePosition#getIndex()} has been updated. If + * the input buffer has been fully parsed, then the index will point to just + * after the end of the input buffer. + * + * @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, + * java.text.ParsePosition) + */ + @Override + public Date parse(final String source, final ParsePosition pos) { + // timing tests indicate getting new instance is 19% faster than cloning + final Calendar cal = Calendar.getInstance(timeZone, locale); + cal.clear(); + + return parse(source, pos, cal) ? cal.getTime() : null; + } + + /** + * Parses a formatted date string according to the format. Updates the Calendar + * with parsed fields. Upon success, the ParsePosition index is updated to + * indicate how much of the source text was consumed. Not all source text needs + * to be consumed. Upon parse failure, ParsePosition error index is updated to + * the offset of the source text which does not match the supplied format. + * + * @param source The text to parse. + * @param pos On input, the position in the source to start parsing, on + * output, updated position. + * @param calendar The calendar into which to set parsed fields. + * @return true, if source has been parsed (pos parsePosition is updated); + * otherwise false (and pos errorIndex is updated) + * @throws IllegalArgumentException when Calendar has been set to be not + * lenient, and a parsed field is out of range. + */ + @Override + public boolean parse(final String source, final ParsePosition pos, final Calendar calendar) { + final ListIterator lt = patterns.listIterator(); + while (lt.hasNext()) { + final StrategyAndWidth strategyAndWidth = lt.next(); + final int maxWidth = strategyAndWidth.getMaxWidth(lt); + if (!strategyAndWidth.strategy.parse(this, calendar, source, pos, maxWidth)) { + return false; + } + } + return true; + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String) + */ + @Override + public Object parseObject(final String source) throws ParseException { + return parse(source); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, + * java.text.ParsePosition) + */ + @Override + public Object parseObject(final String source, final ParsePosition pos) { + return parse(source, pos); + } + + // Serializing + /** + * Creates the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + + final Calendar definingCalendar = Calendar.getInstance(timeZone, locale); + init(definingCalendar); + } + + /** + *

              + * Gets a string version of this formatter. + *

              + * + * @return a debugging string + */ + @Override + public String toString() { + return "FastDateParser[" + pattern + ", " + locale + ", " + timeZone.getID() + "]"; + } + + /** + * Converts all state of this instance to a String handy for debugging. + * + * @return a string. + * @since 3.12.0 + */ + public String toStringAll() { + return "FastDateParser [pattern=" + pattern + ", timeZone=" + timeZone + ", locale=" + locale + ", century=" + + century + ", startYear=" + startYear + ", patterns=" + patterns + "]"; + } } diff --git a/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java b/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java index 335584df..35a46d7f 100644 --- a/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java +++ b/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java @@ -106,6 +106,835 @@ public class FastDatePrinter implements DatePrinter, Serializable { // taking the value and adding (mathematically) the ASCII value for '0'. // So, don't change this code! It works and is very fast. + /** + *

              + * Inner class to output a constant single character. + *

              + */ + private static class CharacterLiteral implements Rule { + private final char mValue; + + /** + * Constructs a new instance of {@code CharacterLiteral} to hold the specified + * value. + * + * @param value the character literal + */ + CharacterLiteral(final char value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + buffer.append(mValue); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 1; + } + } + + /** + *

              + * Inner class to output the numeric day in week. + *

              + */ + private static class DayInWeekField implements NumberRule { + private final NumberRule mRule; + + DayInWeekField(final NumberRule rule) { + mRule = rule; + } + + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + final int value = calendar.get(Calendar.DAY_OF_WEEK); + mRule.appendTo(buffer, value == Calendar.SUNDAY ? 7 : value - 1); + } + + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + } + + /** + *

              + * Inner class to output a time zone as a number {@code +/-HHMM} or + * {@code +/-HH:MM}. + *

              + */ + private static class Iso8601_Rule implements Rule { + + // Sign TwoDigitHours or Z + static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); + // Sign TwoDigitHours Minutes or Z + static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); + // Sign TwoDigitHours : Minutes or Z + static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); + + /** + * Factory method for Iso8601_Rules. + * + * @param tokenLen a token indicating the length of the TimeZone String to be + * formatted. + * @return a Iso8601_Rule that can format TimeZone String of length + * {@code tokenLen}. If no such rule exists, an IllegalArgumentException + * will be thrown. + */ + static Iso8601_Rule getRule(final int tokenLen) { + switch (tokenLen) { + case 1: + return ISO8601_HOURS; + case 2: + return ISO8601_HOURS_MINUTES; + case 3: + return ISO8601_HOURS_COLON_MINUTES; + default: + throw new IllegalArgumentException("invalid number of X"); + } + } + + final int length; + + /** + * Constructs an instance of {@code Iso8601_Rule} with the specified properties. + * + * @param length The number of characters in output (unless Z is output) + */ + Iso8601_Rule(final int length) { + this.length = length; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + if (offset == 0) { + buffer.append("Z"); + return; + } + + if (offset < 0) { + buffer.append('-'); + offset = -offset; + } else { + buffer.append('+'); + } + + final int hours = offset / (60 * 60 * 1000); + appendDigits(buffer, hours); + + if (length < 5) { + return; + } + + if (length == 6) { + buffer.append(':'); + } + + final int minutes = offset / (60 * 1000) - 60 * hours; + appendDigits(buffer, minutes); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return length; + } + } + + /** + *

              + * Inner class defining a numeric rule. + *

              + */ + private interface NumberRule extends Rule { + /** + * Appends the specified value to the output buffer based on the rule + * implementation. + * + * @param buffer the output buffer + * @param value the value to be appended + * @throws IOException if an I/O error occurs. + */ + void appendTo(Appendable buffer, int value) throws IOException; + } + + /** + *

              + * Inner class to output a padded number. + *

              + */ + private static class PaddedNumberField implements NumberRule { + private final int mField; + private final int mSize; + + /** + * Constructs an instance of {@code PaddedNumberField}. + * + * @param field the field + * @param size size of the output field + */ + PaddedNumberField(final int field, final int size) { + if (size < 3) { + // Should use UnpaddedNumberField or TwoDigitNumberField. + throw new IllegalArgumentException(); + } + mField = field; + mSize = size; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + appendFullDigits(buffer, value, mSize); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mSize; + } + } + + // Rules + // ----------------------------------------------------------------------- + /** + *

              + * Inner class defining a rule. + *

              + */ + private interface Rule { + /** + * Appends the value of the specified calendar to the output buffer based on the + * rule implementation. + * + * @param buf the output buffer + * @param calendar calendar to be appended + * @throws IOException if an I/O error occurs. + */ + void appendTo(Appendable buf, Calendar calendar) throws IOException; + + /** + * Returns the estimated length of the result. + * + * @return the estimated length + */ + int estimateLength(); + } + + /** + *

              + * Inner class to output a constant string. + *

              + */ + private static class StringLiteral implements Rule { + private final String mValue; + + /** + * Constructs a new instance of {@code StringLiteral} to hold the specified + * value. + * + * @param value the string literal + */ + StringLiteral(final String value) { + mValue = value; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + buffer.append(mValue); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mValue.length(); + } + } + + /** + *

              + * Inner class to output one of a set of values. + *

              + */ + private static class TextField implements Rule { + private final int mField; + private final String[] mValues; + + /** + * Constructs an instance of {@code TextField} with the specified field and + * values. + * + * @param field the field + * @param values the field values + */ + TextField(final int field, final String[] values) { + mField = field; + mValues = values; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + buffer.append(mValues[calendar.get(mField)]); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + int max = 0; + for (int i = mValues.length; --i >= 0;) { + final int len = mValues[i].length(); + if (len > max) { + max = len; + } + } + return max; + } + } + + // ---------------------------------------------------------------------- + /** + *

              + * Inner class that acts as a compound key for time zone names. + *

              + */ + private static class TimeZoneDisplayKey { + private final TimeZone mTimeZone; + private final int mStyle; + private final Locale mLocale; + + /** + * Constructs an instance of {@code TimeZoneDisplayKey} with the specified + * properties. + * + * @param timeZone the time zone + * @param daylight adjust the style for daylight saving time if {@code true} + * @param style the time zone style + * @param locale the time zone locale + */ + TimeZoneDisplayKey(final TimeZone timeZone, final boolean daylight, final int style, final Locale locale) { + mTimeZone = timeZone; + if (daylight) { + mStyle = style | 0x80000000; + } else { + mStyle = style; + } + mLocale = LocaleUtils.toLocale(locale); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof TimeZoneDisplayKey) { + final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; + return mTimeZone.equals(other.mTimeZone) && mStyle == other.mStyle && mLocale.equals(other.mLocale); + } + return false; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return (mStyle * 31 + mLocale.hashCode()) * 31 + mTimeZone.hashCode(); + } + } + + /** + *

              + * Inner class to output a time zone name. + *

              + */ + private static class TimeZoneNameRule implements Rule { + private final Locale mLocale; + private final int mStyle; + private final String mStandard; + private final String mDaylight; + + /** + * Constructs an instance of {@code TimeZoneNameRule} with the specified + * properties. + * + * @param timeZone the time zone + * @param locale the locale + * @param style the style + */ + TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { + mLocale = LocaleUtils.toLocale(locale); + mStyle = style; + + mStandard = getTimeZoneDisplay(timeZone, false, style, locale); + mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + final TimeZone zone = calendar.getTimeZone(); + if (calendar.get(Calendar.DST_OFFSET) == 0) { + buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); + } else { + buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); + } + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + // We have no access to the Calendar object that will be passed to + // appendTo so base estimate on the TimeZone passed to the + // constructor + return Math.max(mStandard.length(), mDaylight.length()); + } + } + + /** + *

              + * Inner class to output a time zone as a number {@code +/-HHMM} or + * {@code +/-HH:MM}. + *

              + */ + private static class TimeZoneNumberRule implements Rule { + static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); + static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); + + final boolean mColon; + + /** + * Constructs an instance of {@code TimeZoneNumberRule} with the specified + * properties. + * + * @param colon add colon between HH and MM in the output if {@code true} + */ + TimeZoneNumberRule(final boolean colon) { + mColon = colon; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + + int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); + + if (offset < 0) { + buffer.append('-'); + offset = -offset; + } else { + buffer.append('+'); + } + + final int hours = offset / (60 * 60 * 1000); + appendDigits(buffer, hours); + + if (mColon) { + buffer.append(':'); + } + + final int minutes = offset / (60 * 1000) - 60 * hours; + appendDigits(buffer, minutes); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 5; + } + } + + /** + *

              + * Inner class to output the twelve hour field. + *

              + */ + private static class TwelveHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwelveHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwelveHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + int value = calendar.get(Calendar.HOUR); + if (value == 0) { + value = calendar.getLeastMaximum(Calendar.HOUR) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + } + + /** + *

              + * Inner class to output the twenty four hour field. + *

              + */ + private static class TwentyFourHourField implements NumberRule { + private final NumberRule mRule; + + /** + * Constructs an instance of {@code TwentyFourHourField} with the specified + * {@code NumberRule}. + * + * @param rule the rule + */ + TwentyFourHourField(final NumberRule rule) { + mRule = rule; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + int value = calendar.get(Calendar.HOUR_OF_DAY); + if (value == 0) { + value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; + } + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + } + + /** + *

              + * Inner class to output a two digit month. + *

              + */ + private static class TwoDigitMonthField implements NumberRule { + static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); + + /** + * Constructs an instance of {@code TwoDigitMonthField}. + */ + TwoDigitMonthField() { + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + appendDigits(buffer, value); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + } + + /** + *

              + * Inner class to output a two digit number. + *

              + */ + private static class TwoDigitNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code TwoDigitNumberField} with the specified + * field. + * + * @param field the field + */ + TwoDigitNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + if (value < 100) { + appendDigits(buffer, value); + } else { + appendFullDigits(buffer, value, 2); + } + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + } + + /** + *

              + * Inner class to output a two digit year. + *

              + */ + private static class TwoDigitYearField implements NumberRule { + static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); + + /** + * Constructs an instance of {@code TwoDigitYearField}. + */ + TwoDigitYearField() { + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(Calendar.YEAR) % 100); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + appendDigits(buffer, value % 100); + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + } + + /** + *

              + * Inner class to output an unpadded month. + *

              + */ + private static class UnpaddedMonthField implements NumberRule { + static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); + + /** + * Constructs an instance of {@code UnpaddedMonthField}. + * + */ + UnpaddedMonthField() { + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(Calendar.MONTH) + 1); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + if (value < 10) { + buffer.append((char) (value + '0')); + } else { + appendDigits(buffer, value); + } + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 2; + } + } + + /** + *

              + * Inner class to output an unpadded number. + *

              + */ + private static class UnpaddedNumberField implements NumberRule { + private final int mField; + + /** + * Constructs an instance of {@code UnpadedNumberField} with the specified + * field. + * + * @param field the field + */ + UnpaddedNumberField(final int field) { + mField = field; + } + + /** + * {@inheritDoc} + */ + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + appendTo(buffer, calendar.get(mField)); + } + + /** + * {@inheritDoc} + */ + @Override + public final void appendTo(final Appendable buffer, final int value) throws IOException { + if (value < 10) { + buffer.append((char) (value + '0')); + } else if (value < 100) { + appendDigits(buffer, value); + } else { + appendFullDigits(buffer, value, 1); + } + } + + /** + * {@inheritDoc} + */ + @Override + public int estimateLength() { + return 4; + } + } + + /** + *

              + * Inner class to output the numeric day in week. + *

              + */ + private static class WeekYear implements NumberRule { + private final NumberRule mRule; + + WeekYear(final NumberRule rule) { + mRule = rule; + } + + @Override + public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { + mRule.appendTo(buffer, calendar.getWeekYear()); + } + + @Override + public void appendTo(final Appendable buffer, final int value) throws IOException { + mRule.appendTo(buffer, value); + } + + @Override + public int estimateLength() { + return mRule.estimateLength(); + } + } + /** Empty array. */ private static final Rule[] EMPTY_RULE_ARRAY = new Rule[0]; @@ -120,35 +949,156 @@ public class FastDatePrinter implements DatePrinter, Serializable { * FULL locale dependent date or time style. */ public static final int FULL = DateFormat.FULL; + /** * LONG locale dependent date or time style. */ public static final int LONG = DateFormat.LONG; + /** * MEDIUM locale dependent date or time style. */ public static final int MEDIUM = DateFormat.MEDIUM; + /** * SHORT locale dependent date or time style. */ public static final int SHORT = DateFormat.SHORT; + private static final int MAX_DIGITS = 10; // log10(Integer.MAX_VALUE) ~= 9.3 + + private static final Map cTimeZoneDisplayCache = new HashMap<>(7); + + /** + * Appends two digits to the given buffer. + * + * @param buffer the buffer to append to. + * @param value the value to append digits from. + */ + private static void appendDigits(final Appendable buffer, final int value) throws IOException { + buffer.append((char) (value / 10 + '0')); + buffer.append((char) (value % 10 + '0')); + } + + /** + * Appends all digits to the given buffer. + * + * @param buffer the buffer to append to. + * @param value the value to append digits from. + */ + private static void appendFullDigits(final Appendable buffer, int value, int minFieldWidth) throws IOException { + // specialized paths for 1 to 4 digits -> avoid the memory allocation from the + // temporary work array + // see LANG-1248 + if (value < 10000) { + // less memory allocation path works for four digits or less + + int nDigits = 4; + if (value < 1000) { + --nDigits; + if (value < 100) { + --nDigits; + if (value < 10) { + --nDigits; + } + } + } + // left zero pad + for (int i = minFieldWidth - nDigits; i > 0; --i) { + buffer.append('0'); + } + + switch (nDigits) { + case 4: + buffer.append((char) (value / 1000 + '0')); + value %= 1000; + case 3: + if (value >= 100) { + buffer.append((char) (value / 100 + '0')); + value %= 100; + } else { + buffer.append('0'); + } + case 2: + if (value >= 10) { + buffer.append((char) (value / 10 + '0')); + value %= 10; + } else { + buffer.append('0'); + } + case 1: + buffer.append((char) (value + '0')); + } + } else { + // more memory allocation path works for any digits + + // build up decimal representation in reverse + final char[] work = new char[MAX_DIGITS]; + int digit = 0; + while (value != 0) { + work[digit++] = (char) (value % 10 + '0'); + value = value / 10; + } + + // pad with zeros + while (digit < minFieldWidth) { + buffer.append('0'); + --minFieldWidth; + } + + // reverse + while (--digit >= 0) { + buffer.append(work[digit]); + } + } + } + + /** + *

              + * Gets the time zone display name, using a cache for performance. + *

              + * + * @param tz the zone to query + * @param daylight true if daylight savings + * @param style the style to use {@code TimeZone.LONG} or + * {@code TimeZone.SHORT} + * @param locale the locale to use + * @return the textual name of the time zone + */ + static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { + final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); + String value = cTimeZoneDisplayCache.get(key); + if (value == null) { + // This is a very slow call, so cache the results. + value = tz.getDisplayName(daylight, style, locale); + final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); + if (prior != null) { + value = prior; + } + } + return value; + } + /** * The pattern. */ private final String mPattern; + /** * The time zone. */ private final TimeZone mTimeZone; + /** * The locale. */ private final Locale mLocale; + /** * The parsed rules. */ private transient Rule[] mRules; + /** * The estimated maximum length. */ @@ -177,6 +1127,301 @@ public class FastDatePrinter implements DatePrinter, Serializable { init(); } + /** + *

              + * Performs the formatting by applying the rules to the specified calendar. + *

              + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @param the Appendable class type, usually StringBuilder or + * StringBuffer. + * @return the specified string buffer + */ + private B applyRules(final Calendar calendar, final B buf) { + try { + for (final Rule rule : mRules) { + rule.appendTo(buf, calendar); + } + } catch (final IOException ioe) { + throw new RuntimeException("Unexpected throwable", ioe); + } + return buf; + } + + /** + * Performs the formatting by applying the rules to the specified calendar. + * + * @param calendar the calendar to format + * @param buf the buffer to format into + * @return the specified string buffer + * + * @deprecated use {@link #format(Calendar)} or + * {@link #format(Calendar, Appendable)} + */ + @Deprecated + protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { + return (StringBuffer) applyRules(calendar, (Appendable) buf); + } + + /** + * Creates a String representation of the given Calendar by applying the rules + * of this printer to it. + * + * @param c the Calender to apply the rules to. + * @return a String representation of the given Calendar. + */ + private String applyRulesToString(final Calendar c) { + return applyRules(c, new StringBuilder(mMaxLengthEstimate)).toString(); + } + + // Basics + // ----------------------------------------------------------------------- + /** + *

              + * Compares two objects for equality. + *

              + * + * @param obj the object to compare to + * @return {@code true} if equal + */ + @Override + public boolean equals(final Object obj) { + if (!(obj instanceof FastDatePrinter)) { + return false; + } + final FastDatePrinter other = (FastDatePrinter) obj; + return mPattern.equals(other.mPattern) && mTimeZone.equals(other.mTimeZone) && mLocale.equals(other.mLocale); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) + */ + @Override + public String format(final Calendar calendar) { + return format(calendar, new StringBuilder(mMaxLengthEstimate)).toString(); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, + * java.lang.Appendable) + */ + @Override + public B format(Calendar calendar, final B buf) { + // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter + // to be ignored + if (!calendar.getTimeZone().equals(mTimeZone)) { + calendar = (Calendar) calendar.clone(); + calendar.setTimeZone(mTimeZone); + } + return applyRules(calendar, buf); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, + * java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final Calendar calendar, final StringBuffer buf) { + // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter + // to be ignored + return format(calendar.getTime(), buf); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) + */ + @Override + public String format(final Date date) { + final Calendar c = newCalendar(); + c.setTime(date); + return applyRulesToString(c); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, + * java.lang.Appendable) + */ + @Override + public B format(final Date date, final B buf) { + final Calendar c = newCalendar(); + c.setTime(date); + return applyRules(c, buf); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, + * java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final Date date, final StringBuffer buf) { + final Calendar c = newCalendar(); + c.setTime(date); + return (StringBuffer) applyRules(c, (Appendable) buf); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(long) + */ + @Override + public String format(final long millis) { + final Calendar c = newCalendar(); + c.setTimeInMillis(millis); + return applyRulesToString(c); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(long, + * java.lang.Appendable) + */ + @Override + public B format(final long millis, final B buf) { + final Calendar c = newCalendar(); + c.setTimeInMillis(millis); + return applyRules(c, buf); + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#format(long, + * java.lang.StringBuffer) + */ + @Override + public StringBuffer format(final long millis, final StringBuffer buf) { + final Calendar c = newCalendar(); + c.setTimeInMillis(millis); + return (StringBuffer) applyRules(c, (Appendable) buf); + } + + /** + *

              + * Formats a {@code Date}, {@code Calendar} or {@code Long} (milliseconds) + * object. + *

              + * + * @since 3.5 + * @param obj the object to format + * @return The formatted value. + */ + String format(final Object obj) { + if (obj instanceof Date) { + return format((Date) obj); + } else if (obj instanceof Calendar) { + return format((Calendar) obj); + } else if (obj instanceof Long) { + return format(((Long) obj).longValue()); + } else { + throw new IllegalArgumentException("Unknown class: " + (obj == null ? "" : obj.getClass().getName())); + } + } + + // Format methods + // ----------------------------------------------------------------------- + /** + *

              + * Formats a {@code Date}, {@code Calendar} or {@code Long} (milliseconds) + * object. + *

              + * + * @deprecated Use {{@link #format(Date)}, {{@link #format(Calendar)}, + * {{@link #format(long)}, or {{@link #format(Object)} + * @param obj the object to format + * @param toAppendTo the buffer to append to + * @param pos the position - ignored + * @return the buffer passed in + */ + @Deprecated + @Override + public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { + if (obj instanceof Date) { + return format((Date) obj, toAppendTo); + } else if (obj instanceof Calendar) { + return format((Calendar) obj, toAppendTo); + } else if (obj instanceof Long) { + return format(((Long) obj).longValue(), toAppendTo); + } else { + throw new IllegalArgumentException("Unknown class: " + (obj == null ? "" : obj.getClass().getName())); + } + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#getLocale() + */ + @Override + public Locale getLocale() { + return mLocale; + } + + /** + *

              + * Gets an estimate for the maximum string length that the formatter will + * produce. + *

              + * + *

              + * The actual formatted length will almost always be less than or equal to this + * amount. + *

              + * + * @return the maximum formatted length + */ + public int getMaxLengthEstimate() { + return mMaxLengthEstimate; + } + + // Accessors + // ----------------------------------------------------------------------- + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#getPattern() + */ + @Override + public String getPattern() { + return mPattern; + } + + /* + * (non-Javadoc) + * + * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() + */ + @Override + public TimeZone getTimeZone() { + return mTimeZone; + } + + /** + *

              + * Returns a hash code compatible with equals. + *

              + * + * @return a hash code compatible with equals + */ + @Override + public int hashCode() { + return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); + } + /** *

              * Initializes the instance for first use. @@ -194,6 +1439,17 @@ public class FastDatePrinter implements DatePrinter, Serializable { mMaxLengthEstimate = len; } + // ----------------------------------------------------------------------- + + /** + * Creation method for new calender instances. + * + * @return a new Calendar instance. + */ + private Calendar newCalendar() { + return Calendar.getInstance(mTimeZone, mLocale); + } + // Parse the pattern // ----------------------------------------------------------------------- /** @@ -399,6 +1655,21 @@ public class FastDatePrinter implements DatePrinter, Serializable { return buf.toString(); } + // Serializing + // ----------------------------------------------------------------------- + /** + * Create the object after serialization. This implementation reinitializes the + * transient properties. + * + * @param in ObjectInputStream from which the object is being deserialized. + * @throws IOException if there is an IO issue. + * @throws ClassNotFoundException if a class cannot be found. + */ + private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + init(); + } + /** *

              * Gets an appropriate rule for the padding required. @@ -419,310 +1690,6 @@ public class FastDatePrinter implements DatePrinter, Serializable { } } - // Format methods - // ----------------------------------------------------------------------- - /** - *

              - * Formats a {@code Date}, {@code Calendar} or {@code Long} (milliseconds) - * object. - *

              - * - * @deprecated Use {{@link #format(Date)}, {{@link #format(Calendar)}, - * {{@link #format(long)}, or {{@link #format(Object)} - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - */ - @Deprecated - @Override - public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { - if (obj instanceof Date) { - return format((Date) obj, toAppendTo); - } else if (obj instanceof Calendar) { - return format((Calendar) obj, toAppendTo); - } else if (obj instanceof Long) { - return format(((Long) obj).longValue(), toAppendTo); - } else { - throw new IllegalArgumentException("Unknown class: " + (obj == null ? "" : obj.getClass().getName())); - } - } - - /** - *

              - * Formats a {@code Date}, {@code Calendar} or {@code Long} (milliseconds) - * object. - *

              - * - * @since 3.5 - * @param obj the object to format - * @return The formatted value. - */ - String format(final Object obj) { - if (obj instanceof Date) { - return format((Date) obj); - } else if (obj instanceof Calendar) { - return format((Calendar) obj); - } else if (obj instanceof Long) { - return format(((Long) obj).longValue()); - } else { - throw new IllegalArgumentException("Unknown class: " + (obj == null ? "" : obj.getClass().getName())); - } - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(long) - */ - @Override - public String format(final long millis) { - final Calendar c = newCalendar(); - c.setTimeInMillis(millis); - return applyRulesToString(c); - } - - /** - * Creates a String representation of the given Calendar by applying the rules - * of this printer to it. - * - * @param c the Calender to apply the rules to. - * @return a String representation of the given Calendar. - */ - private String applyRulesToString(final Calendar c) { - return applyRules(c, new StringBuilder(mMaxLengthEstimate)).toString(); - } - - /** - * Creation method for new calender instances. - * - * @return a new Calendar instance. - */ - private Calendar newCalendar() { - return Calendar.getInstance(mTimeZone, mLocale); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) - */ - @Override - public String format(final Date date) { - final Calendar c = newCalendar(); - c.setTime(date); - return applyRulesToString(c); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) - */ - @Override - public String format(final Calendar calendar) { - return format(calendar, new StringBuilder(mMaxLengthEstimate)).toString(); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(long, - * java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final long millis, final StringBuffer buf) { - final Calendar c = newCalendar(); - c.setTimeInMillis(millis); - return (StringBuffer) applyRules(c, (Appendable) buf); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, - * java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Date date, final StringBuffer buf) { - final Calendar c = newCalendar(); - c.setTime(date); - return (StringBuffer) applyRules(c, (Appendable) buf); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, - * java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Calendar calendar, final StringBuffer buf) { - // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter - // to be ignored - return format(calendar.getTime(), buf); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(long, - * java.lang.Appendable) - */ - @Override - public B format(final long millis, final B buf) { - final Calendar c = newCalendar(); - c.setTimeInMillis(millis); - return applyRules(c, buf); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, - * java.lang.Appendable) - */ - @Override - public B format(final Date date, final B buf) { - final Calendar c = newCalendar(); - c.setTime(date); - return applyRules(c, buf); - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, - * java.lang.Appendable) - */ - @Override - public B format(Calendar calendar, final B buf) { - // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter - // to be ignored - if (!calendar.getTimeZone().equals(mTimeZone)) { - calendar = (Calendar) calendar.clone(); - calendar.setTimeZone(mTimeZone); - } - return applyRules(calendar, buf); - } - - /** - * Performs the formatting by applying the rules to the specified calendar. - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - * - * @deprecated use {@link #format(Calendar)} or - * {@link #format(Calendar, Appendable)} - */ - @Deprecated - protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { - return (StringBuffer) applyRules(calendar, (Appendable) buf); - } - - /** - *

              - * Performs the formatting by applying the rules to the specified calendar. - *

              - * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @param the Appendable class type, usually StringBuilder or - * StringBuffer. - * @return the specified string buffer - */ - private B applyRules(final Calendar calendar, final B buf) { - try { - for (final Rule rule : mRules) { - rule.appendTo(buf, calendar); - } - } catch (final IOException ioe) { - throw new RuntimeException("Unexpected throwable", ioe); - } - return buf; - } - - // Accessors - // ----------------------------------------------------------------------- - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#getPattern() - */ - @Override - public String getPattern() { - return mPattern; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() - */ - @Override - public TimeZone getTimeZone() { - return mTimeZone; - } - - /* - * (non-Javadoc) - * - * @see org.apache.commons.lang3.time.DatePrinter#getLocale() - */ - @Override - public Locale getLocale() { - return mLocale; - } - - /** - *

              - * Gets an estimate for the maximum string length that the formatter will - * produce. - *

              - * - *

              - * The actual formatted length will almost always be less than or equal to this - * amount. - *

              - * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return mMaxLengthEstimate; - } - - // Basics - // ----------------------------------------------------------------------- - /** - *

              - * Compares two objects for equality. - *

              - * - * @param obj the object to compare to - * @return {@code true} if equal - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof FastDatePrinter)) { - return false; - } - final FastDatePrinter other = (FastDatePrinter) obj; - return mPattern.equals(other.mPattern) && mTimeZone.equals(other.mTimeZone) && mLocale.equals(other.mLocale); - } - - /** - *

              - * Returns a hash code compatible with equals. - *

              - * - * @return a hash code compatible with equals - */ - @Override - public int hashCode() { - return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); - } - /** *

              * Gets a debugging string version of this formatter. @@ -734,964 +1701,4 @@ public class FastDatePrinter implements DatePrinter, Serializable { public String toString() { return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; } - - // Serializing - // ----------------------------------------------------------------------- - /** - * Create the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - init(); - } - - /** - * Appends two digits to the given buffer. - * - * @param buffer the buffer to append to. - * @param value the value to append digits from. - */ - private static void appendDigits(final Appendable buffer, final int value) throws IOException { - buffer.append((char) (value / 10 + '0')); - buffer.append((char) (value % 10 + '0')); - } - - private static final int MAX_DIGITS = 10; // log10(Integer.MAX_VALUE) ~= 9.3 - - /** - * Appends all digits to the given buffer. - * - * @param buffer the buffer to append to. - * @param value the value to append digits from. - */ - private static void appendFullDigits(final Appendable buffer, int value, int minFieldWidth) throws IOException { - // specialized paths for 1 to 4 digits -> avoid the memory allocation from the - // temporary work array - // see LANG-1248 - if (value < 10000) { - // less memory allocation path works for four digits or less - - int nDigits = 4; - if (value < 1000) { - --nDigits; - if (value < 100) { - --nDigits; - if (value < 10) { - --nDigits; - } - } - } - // left zero pad - for (int i = minFieldWidth - nDigits; i > 0; --i) { - buffer.append('0'); - } - - switch (nDigits) { - case 4: - buffer.append((char) (value / 1000 + '0')); - value %= 1000; - case 3: - if (value >= 100) { - buffer.append((char) (value / 100 + '0')); - value %= 100; - } else { - buffer.append('0'); - } - case 2: - if (value >= 10) { - buffer.append((char) (value / 10 + '0')); - value %= 10; - } else { - buffer.append('0'); - } - case 1: - buffer.append((char) (value + '0')); - } - } else { - // more memory allocation path works for any digits - - // build up decimal representation in reverse - final char[] work = new char[MAX_DIGITS]; - int digit = 0; - while (value != 0) { - work[digit++] = (char) (value % 10 + '0'); - value = value / 10; - } - - // pad with zeros - while (digit < minFieldWidth) { - buffer.append('0'); - --minFieldWidth; - } - - // reverse - while (--digit >= 0) { - buffer.append(work[digit]); - } - } - } - - // Rules - // ----------------------------------------------------------------------- - /** - *

              - * Inner class defining a rule. - *

              - */ - private interface Rule { - /** - * Returns the estimated length of the result. - * - * @return the estimated length - */ - int estimateLength(); - - /** - * Appends the value of the specified calendar to the output buffer based on the - * rule implementation. - * - * @param buf the output buffer - * @param calendar calendar to be appended - * @throws IOException if an I/O error occurs. - */ - void appendTo(Appendable buf, Calendar calendar) throws IOException; - } - - /** - *

              - * Inner class defining a numeric rule. - *

              - */ - private interface NumberRule extends Rule { - /** - * Appends the specified value to the output buffer based on the rule - * implementation. - * - * @param buffer the output buffer - * @param value the value to be appended - * @throws IOException if an I/O error occurs. - */ - void appendTo(Appendable buffer, int value) throws IOException; - } - - /** - *

              - * Inner class to output a constant single character. - *

              - */ - private static class CharacterLiteral implements Rule { - private final char mValue; - - /** - * Constructs a new instance of {@code CharacterLiteral} to hold the specified - * value. - * - * @param value the character literal - */ - CharacterLiteral(final char value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 1; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - buffer.append(mValue); - } - } - - /** - *

              - * Inner class to output a constant string. - *

              - */ - private static class StringLiteral implements Rule { - private final String mValue; - - /** - * Constructs a new instance of {@code StringLiteral} to hold the specified - * value. - * - * @param value the string literal - */ - StringLiteral(final String value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mValue.length(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - buffer.append(mValue); - } - } - - /** - *

              - * Inner class to output one of a set of values. - *

              - */ - private static class TextField implements Rule { - private final int mField; - private final String[] mValues; - - /** - * Constructs an instance of {@code TextField} with the specified field and - * values. - * - * @param field the field - * @param values the field values - */ - TextField(final int field, final String[] values) { - mField = field; - mValues = values; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - int max = 0; - for (int i = mValues.length; --i >= 0;) { - final int len = mValues[i].length(); - if (len > max) { - max = len; - } - } - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - buffer.append(mValues[calendar.get(mField)]); - } - } - - /** - *

              - * Inner class to output an unpadded number. - *

              - */ - private static class UnpaddedNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code UnpadedNumberField} with the specified - * field. - * - * @param field the field - */ - UnpaddedNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 4; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - if (value < 10) { - buffer.append((char) (value + '0')); - } else if (value < 100) { - appendDigits(buffer, value); - } else { - appendFullDigits(buffer, value, 1); - } - } - } - - /** - *

              - * Inner class to output an unpadded month. - *

              - */ - private static class UnpaddedMonthField implements NumberRule { - static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); - - /** - * Constructs an instance of {@code UnpaddedMonthField}. - * - */ - UnpaddedMonthField() { - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - if (value < 10) { - buffer.append((char) (value + '0')); - } else { - appendDigits(buffer, value); - } - } - } - - /** - *

              - * Inner class to output a padded number. - *

              - */ - private static class PaddedNumberField implements NumberRule { - private final int mField; - private final int mSize; - - /** - * Constructs an instance of {@code PaddedNumberField}. - * - * @param field the field - * @param size size of the output field - */ - PaddedNumberField(final int field, final int size) { - if (size < 3) { - // Should use UnpaddedNumberField or TwoDigitNumberField. - throw new IllegalArgumentException(); - } - mField = field; - mSize = size; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mSize; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - appendFullDigits(buffer, value, mSize); - } - } - - /** - *

              - * Inner class to output a two digit number. - *

              - */ - private static class TwoDigitNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code TwoDigitNumberField} with the specified - * field. - * - * @param field the field - */ - TwoDigitNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - if (value < 100) { - appendDigits(buffer, value); - } else { - appendFullDigits(buffer, value, 2); - } - } - } - - /** - *

              - * Inner class to output a two digit year. - *

              - */ - private static class TwoDigitYearField implements NumberRule { - static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); - - /** - * Constructs an instance of {@code TwoDigitYearField}. - */ - TwoDigitYearField() { - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(Calendar.YEAR) % 100); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - appendDigits(buffer, value % 100); - } - } - - /** - *

              - * Inner class to output a two digit month. - *

              - */ - private static class TwoDigitMonthField implements NumberRule { - static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); - - /** - * Constructs an instance of {@code TwoDigitMonthField}. - */ - TwoDigitMonthField() { - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final Appendable buffer, final int value) throws IOException { - appendDigits(buffer, value); - } - } - - /** - *

              - * Inner class to output the twelve hour field. - *

              - */ - private static class TwelveHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwelveHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwelveHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - int value = calendar.get(Calendar.HOUR); - if (value == 0) { - value = calendar.getLeastMaximum(Calendar.HOUR) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - /** - *

              - * Inner class to output the twenty four hour field. - *

              - */ - private static class TwentyFourHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwentyFourHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwentyFourHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - int value = calendar.get(Calendar.HOUR_OF_DAY); - if (value == 0) { - value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - /** - *

              - * Inner class to output the numeric day in week. - *

              - */ - private static class DayInWeekField implements NumberRule { - private final NumberRule mRule; - - DayInWeekField(final NumberRule rule) { - mRule = rule; - } - - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - final int value = calendar.get(Calendar.DAY_OF_WEEK); - mRule.appendTo(buffer, value == Calendar.SUNDAY ? 7 : value - 1); - } - - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - /** - *

              - * Inner class to output the numeric day in week. - *

              - */ - private static class WeekYear implements NumberRule { - private final NumberRule mRule; - - WeekYear(final NumberRule rule) { - mRule = rule; - } - - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - mRule.appendTo(buffer, calendar.getWeekYear()); - } - - @Override - public void appendTo(final Appendable buffer, final int value) throws IOException { - mRule.appendTo(buffer, value); - } - } - - // ----------------------------------------------------------------------- - - private static final Map cTimeZoneDisplayCache = new HashMap<>(7); - - /** - *

              - * Gets the time zone display name, using a cache for performance. - *

              - * - * @param tz the zone to query - * @param daylight true if daylight savings - * @param style the style to use {@code TimeZone.LONG} or - * {@code TimeZone.SHORT} - * @param locale the locale to use - * @return the textual name of the time zone - */ - static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { - final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); - String value = cTimeZoneDisplayCache.get(key); - if (value == null) { - // This is a very slow call, so cache the results. - value = tz.getDisplayName(daylight, style, locale); - final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); - if (prior != null) { - value = prior; - } - } - return value; - } - - /** - *

              - * Inner class to output a time zone name. - *

              - */ - private static class TimeZoneNameRule implements Rule { - private final Locale mLocale; - private final int mStyle; - private final String mStandard; - private final String mDaylight; - - /** - * Constructs an instance of {@code TimeZoneNameRule} with the specified - * properties. - * - * @param timeZone the time zone - * @param locale the locale - * @param style the style - */ - TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { - mLocale = LocaleUtils.toLocale(locale); - mStyle = style; - - mStandard = getTimeZoneDisplay(timeZone, false, style, locale); - mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - // We have no access to the Calendar object that will be passed to - // appendTo so base estimate on the TimeZone passed to the - // constructor - return Math.max(mStandard.length(), mDaylight.length()); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - final TimeZone zone = calendar.getTimeZone(); - if (calendar.get(Calendar.DST_OFFSET) == 0) { - buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); - } else { - buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); - } - } - } - - /** - *

              - * Inner class to output a time zone as a number {@code +/-HHMM} or - * {@code +/-HH:MM}. - *

              - */ - private static class TimeZoneNumberRule implements Rule { - static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); - static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); - - final boolean mColon; - - /** - * Constructs an instance of {@code TimeZoneNumberRule} with the specified - * properties. - * - * @param colon add colon between HH and MM in the output if {@code true} - */ - TimeZoneNumberRule(final boolean colon) { - mColon = colon; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 5; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (mColon) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - /** - *

              - * Inner class to output a time zone as a number {@code +/-HHMM} or - * {@code +/-HH:MM}. - *

              - */ - private static class Iso8601_Rule implements Rule { - - // Sign TwoDigitHours or Z - static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); - // Sign TwoDigitHours Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); - // Sign TwoDigitHours : Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); - - /** - * Factory method for Iso8601_Rules. - * - * @param tokenLen a token indicating the length of the TimeZone String to be - * formatted. - * @return a Iso8601_Rule that can format TimeZone String of length - * {@code tokenLen}. If no such rule exists, an IllegalArgumentException - * will be thrown. - */ - static Iso8601_Rule getRule(final int tokenLen) { - switch (tokenLen) { - case 1: - return ISO8601_HOURS; - case 2: - return ISO8601_HOURS_MINUTES; - case 3: - return ISO8601_HOURS_COLON_MINUTES; - default: - throw new IllegalArgumentException("invalid number of X"); - } - } - - final int length; - - /** - * Constructs an instance of {@code Iso8601_Rule} with the specified properties. - * - * @param length The number of characters in output (unless Z is output) - */ - Iso8601_Rule(final int length) { - this.length = length; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return length; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - if (offset == 0) { - buffer.append("Z"); - return; - } - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (length < 5) { - return; - } - - if (length == 6) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - // ---------------------------------------------------------------------- - /** - *

              - * Inner class that acts as a compound key for time zone names. - *

              - */ - private static class TimeZoneDisplayKey { - private final TimeZone mTimeZone; - private final int mStyle; - private final Locale mLocale; - - /** - * Constructs an instance of {@code TimeZoneDisplayKey} with the specified - * properties. - * - * @param timeZone the time zone - * @param daylight adjust the style for daylight saving time if {@code true} - * @param style the time zone style - * @param locale the time zone locale - */ - TimeZoneDisplayKey(final TimeZone timeZone, final boolean daylight, final int style, final Locale locale) { - mTimeZone = timeZone; - if (daylight) { - mStyle = style | 0x80000000; - } else { - mStyle = style; - } - mLocale = LocaleUtils.toLocale(locale); - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return (mStyle * 31 + mLocale.hashCode()) * 31 + mTimeZone.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof TimeZoneDisplayKey) { - final TimeZoneDisplayKey other = (TimeZoneDisplayKey) obj; - return mTimeZone.equals(other.mTimeZone) && mStyle == other.mStyle && mLocale.equals(other.mLocale); - } - return false; - } - } } diff --git a/src/main/java/org/apache/commons/lang3/time/FormatCache.java b/src/main/java/org/apache/commons/lang3/time/FormatCache.java index 9f1a0ef4..9282054e 100644 --- a/src/main/java/org/apache/commons/lang3/time/FormatCache.java +++ b/src/main/java/org/apache/commons/lang3/time/FormatCache.java @@ -36,147 +36,61 @@ import org.apache.commons.lang3.Validate; // TODO: Before making public move from getDateTimeInstance(Integer, ...) to int; or some other approach. abstract class FormatCache { + /** + * Helper class to hold multi-part Map keys as arrays. + */ + private static final class ArrayKey { + + private static int computeHashCode(final Object[] keys) { + final int prime = 31; + int result = 1; + result = prime * result + Arrays.hashCode(keys); + return result; + } + + private final Object[] keys; + private final int hashCode; + + /** + * Constructs an instance of {@code MultipartKey} to hold the specified objects. + * + * @param keys the set of objects that make up the key. Each key may be null. + */ + ArrayKey(final Object... keys) { + this.keys = keys; + this.hashCode = computeHashCode(keys); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + final ArrayKey other = (ArrayKey) obj; + return Arrays.deepEquals(keys, other.keys); + } + + @Override + public int hashCode() { + return hashCode; + } + + } + /** * No date or no time. Used in same parameters as DateFormat.SHORT or * DateFormat.LONG */ static final int NONE = -1; - private final Map cInstanceCache = new HashMap<>(7); - private static final Map cDateTimeInstanceCache = new HashMap<>(7); - /** - * Gets a formatter instance using the default pattern in the default time zone - * and locale. - * - * @return a date/time formatter - */ - public F getInstance() { - return getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TimeZone.getDefault(), Locale.getDefault()); - } - - /** - * Gets a formatter instance using the specified pattern, time zone and locale. - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, - * non-null - * @param timeZone the time zone, null means use the default TimeZone - * @param locale the locale, null means use the default Locale - * @return a pattern based date/time formatter - * @throws NullPointerException if pattern is {@code null} - * @throws IllegalArgumentException if pattern is invalid - */ - public F getInstance(final String pattern, TimeZone timeZone, Locale locale) { - Validate.notNull(pattern, "pattern"); - if (timeZone == null) { - timeZone = TimeZone.getDefault(); - } - locale = LocaleUtils.toLocale(locale); - final ArrayKey key = new ArrayKey(pattern, timeZone, locale); - F format = cInstanceCache.get(key); - if (format == null) { - format = createInstance(pattern, timeZone, locale); - final F previousValue = cInstanceCache.putIfAbsent(key, format); - if (previousValue != null) { - // another thread snuck in and did the same work - // we should return the instance that is in ConcurrentMap - format = previousValue; - } - } - return format; - } - - /** - * Create a format instance using the specified pattern, time zone and locale. - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this - * will not be null. - * @param timeZone time zone, this will not be null. - * @param locale locale, this will not be null. - * @return a pattern based date/time formatter - * @throws IllegalArgumentException if pattern is invalid or {@code null} - */ - protected abstract F createInstance(String pattern, TimeZone timeZone, Locale locale); - - /** - * Gets a date/time formatter instance using the specified style, time zone and - * locale. - * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no - * date in format - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no - * time in format - * @param timeZone optional time zone, overrides time zone of formatted date, - * null means use default Locale - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time pattern - * defined - */ - // This must remain private, see LANG-884 - private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, - Locale locale) { - locale = LocaleUtils.toLocale(locale); - final String pattern = getPatternForStyle(dateStyle, timeStyle, locale); - return getInstance(pattern, timeZone, locale); - } - - /** - * Gets a date/time formatter instance using the specified style, time zone and - * locale. - * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of formatted date, - * null means use default Locale - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time pattern - * defined - */ - // package protected, for access from FastDateFormat; do not make public or - // protected - F getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone, final Locale locale) { - return getDateTimeInstance(Integer.valueOf(dateStyle), Integer.valueOf(timeStyle), timeZone, locale); - } - - /** - * Gets a date formatter instance using the specified style, time zone and - * locale. - * - * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of formatted date, - * null means use default Locale - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time pattern - * defined - */ - // package protected, for access from FastDateFormat; do not make public or - // protected - F getDateInstance(final int dateStyle, final TimeZone timeZone, final Locale locale) { - return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale); - } - - /** - * Gets a time formatter instance using the specified style, time zone and - * locale. - * - * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT - * @param timeZone optional time zone, overrides time zone of formatted date, - * null means use default Locale - * @param locale optional locale, overrides system locale - * @return a localized standard date/time formatter - * @throws IllegalArgumentException if the Locale has no date/time pattern - * defined - */ - // package protected, for access from FastDateFormat; do not make public or - // protected - F getTimeInstance(final int timeStyle, final TimeZone timeZone, final Locale locale) { - return getDateTimeInstance(null, Integer.valueOf(timeStyle), timeZone, locale); - } - /** * Gets a date/time format for the specified styles and locale. * @@ -220,51 +134,137 @@ abstract class FormatCache { return pattern; } + private final Map cInstanceCache = new HashMap<>(7); + /** - * Helper class to hold multi-part Map keys as arrays. + * Create a format instance using the specified pattern, time zone and locale. + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, this + * will not be null. + * @param timeZone time zone, this will not be null. + * @param locale locale, this will not be null. + * @return a pattern based date/time formatter + * @throws IllegalArgumentException if pattern is invalid or {@code null} */ - private static final class ArrayKey { + protected abstract F createInstance(String pattern, TimeZone timeZone, Locale locale); - private static int computeHashCode(final Object[] keys) { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(keys); - return result; + /** + * Gets a date formatter instance using the specified style, time zone and + * locale. + * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of formatted date, + * null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time pattern + * defined + */ + // package protected, for access from FastDateFormat; do not make public or + // protected + F getDateInstance(final int dateStyle, final TimeZone timeZone, final Locale locale) { + return getDateTimeInstance(Integer.valueOf(dateStyle), null, timeZone, locale); + } + + /** + * Gets a date/time formatter instance using the specified style, time zone and + * locale. + * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of formatted date, + * null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time pattern + * defined + */ + // package protected, for access from FastDateFormat; do not make public or + // protected + F getDateTimeInstance(final int dateStyle, final int timeStyle, final TimeZone timeZone, final Locale locale) { + return getDateTimeInstance(Integer.valueOf(dateStyle), Integer.valueOf(timeStyle), timeZone, locale); + } + + /** + * Gets a date/time formatter instance using the specified style, time zone and + * locale. + * + * @param dateStyle date style: FULL, LONG, MEDIUM, or SHORT, null indicates no + * date in format + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT, null indicates no + * time in format + * @param timeZone optional time zone, overrides time zone of formatted date, + * null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time pattern + * defined + */ + // This must remain private, see LANG-884 + private F getDateTimeInstance(final Integer dateStyle, final Integer timeStyle, final TimeZone timeZone, + Locale locale) { + locale = LocaleUtils.toLocale(locale); + final String pattern = getPatternForStyle(dateStyle, timeStyle, locale); + return getInstance(pattern, timeZone, locale); + } + + /** + * Gets a formatter instance using the default pattern in the default time zone + * and locale. + * + * @return a date/time formatter + */ + public F getInstance() { + return getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, TimeZone.getDefault(), Locale.getDefault()); + } + + /** + * Gets a formatter instance using the specified pattern, time zone and locale. + * + * @param pattern {@link java.text.SimpleDateFormat} compatible pattern, + * non-null + * @param timeZone the time zone, null means use the default TimeZone + * @param locale the locale, null means use the default Locale + * @return a pattern based date/time formatter + * @throws NullPointerException if pattern is {@code null} + * @throws IllegalArgumentException if pattern is invalid + */ + public F getInstance(final String pattern, TimeZone timeZone, Locale locale) { + Validate.notNull(pattern, "pattern"); + if (timeZone == null) { + timeZone = TimeZone.getDefault(); } - - private final Object[] keys; - private final int hashCode; - - /** - * Constructs an instance of {@code MultipartKey} to hold the specified objects. - * - * @param keys the set of objects that make up the key. Each key may be null. - */ - ArrayKey(final Object... keys) { - this.keys = keys; - this.hashCode = computeHashCode(keys); - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; + locale = LocaleUtils.toLocale(locale); + final ArrayKey key = new ArrayKey(pattern, timeZone, locale); + F format = cInstanceCache.get(key); + if (format == null) { + format = createInstance(pattern, timeZone, locale); + final F previousValue = cInstanceCache.putIfAbsent(key, format); + if (previousValue != null) { + // another thread snuck in and did the same work + // we should return the instance that is in ConcurrentMap + format = previousValue; } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final ArrayKey other = (ArrayKey) obj; - return Arrays.deepEquals(keys, other.keys); } + return format; + } + /** + * Gets a time formatter instance using the specified style, time zone and + * locale. + * + * @param timeStyle time style: FULL, LONG, MEDIUM, or SHORT + * @param timeZone optional time zone, overrides time zone of formatted date, + * null means use default Locale + * @param locale optional locale, overrides system locale + * @return a localized standard date/time formatter + * @throws IllegalArgumentException if the Locale has no date/time pattern + * defined + */ + // package protected, for access from FastDateFormat; do not make public or + // protected + F getTimeInstance(final int timeStyle, final TimeZone timeZone, final Locale locale) { + return getDateTimeInstance(null, Integer.valueOf(timeStyle), timeZone, locale); } } diff --git a/src/main/java/org/apache/commons/lang3/time/GmtTimeZone.java b/src/main/java/org/apache/commons/lang3/time/GmtTimeZone.java index ef4ec987..4c528387 100644 --- a/src/main/java/org/apache/commons/lang3/time/GmtTimeZone.java +++ b/src/main/java/org/apache/commons/lang3/time/GmtTimeZone.java @@ -33,7 +33,12 @@ class GmtTimeZone extends TimeZone { // Serializable! static final long serialVersionUID = 1L; + private static StringBuilder twoDigits(final StringBuilder sb, final int n) { + return sb.append((char) ('0' + (n / 10))).append((char) ('0' + (n % 10))); + } + private final int offset; + private final String zoneId; GmtTimeZone(final boolean negate, final int hours, final int minutes) { @@ -50,8 +55,17 @@ class GmtTimeZone extends TimeZone { } - private static StringBuilder twoDigits(final StringBuilder sb, final int n) { - return sb.append((char) ('0' + (n / 10))).append((char) ('0' + (n % 10))); + @Override + public boolean equals(final Object other) { + if (!(other instanceof GmtTimeZone)) { + return false; + } + return zoneId == ((GmtTimeZone) other).zoneId; + } + + @Override + public String getID() { + return zoneId; } @Override @@ -60,46 +74,33 @@ class GmtTimeZone extends TimeZone { return offset; } - @Override - public void setRawOffset(final int offsetMillis) { - throw new UnsupportedOperationException(); - } - @Override public int getRawOffset() { return offset; } - @Override - public String getID() { - return zoneId; - } - - @Override - public boolean useDaylightTime() { - return false; - } - - @Override - public boolean inDaylightTime(final Date date) { - return false; - } - - @Override - public String toString() { - return "[GmtTimeZone id=\"" + zoneId + "\",offset=" + offset + ']'; - } - @Override public int hashCode() { return offset; } @Override - public boolean equals(final Object other) { - if (!(other instanceof GmtTimeZone)) { - return false; - } - return zoneId == ((GmtTimeZone) other).zoneId; + public boolean inDaylightTime(final Date date) { + return false; + } + + @Override + public void setRawOffset(final int offsetMillis) { + throw new UnsupportedOperationException(); + } + + @Override + public String toString() { + return "[GmtTimeZone id=\"" + zoneId + "\",offset=" + offset + ']'; + } + + @Override + public boolean useDaylightTime() { + return false; } } diff --git a/src/main/java/org/apache/commons/lang3/time/TimeZones.java b/src/main/java/org/apache/commons/lang3/time/TimeZones.java index 688d6fa5..2ddf5192 100644 --- a/src/main/java/org/apache/commons/lang3/time/TimeZones.java +++ b/src/main/java/org/apache/commons/lang3/time/TimeZones.java @@ -24,13 +24,13 @@ package org.apache.commons.lang3.time; */ public class TimeZones { - // do not instantiate - private TimeZones() { - } - /** * A public version of {@link java.util.TimeZone}'s package private * {@code GMT_ID} field. */ public static final String GMT_ID = "GMT"; + + // do not instantiate + private TimeZones() { + } } diff --git a/src/main/java/org/json/JSONArray.java b/src/main/java/org/json/JSONArray.java index f86075e6..231165e4 100644 --- a/src/main/java/org/json/JSONArray.java +++ b/src/main/java/org/json/JSONArray.java @@ -16,7 +16,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; - /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The @@ -53,8 +52,8 @@ import java.util.Map; *
            • Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, and * if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and - * if they are not the reserved words true, false, or + * { } [ ] / \ : , # and if they do not look like numbers and if + * they are not the reserved words true, false, or * null.
            • * * @@ -63,1915 +62,1756 @@ import java.util.Map; */ public class JSONArray implements Iterable { - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * - * @param x - * A JSONTokener - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(JSONTokener x) throws JSONException { - this(); - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - - char nextChar = x.nextClean(); - if (nextChar == 0) { - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - } - if (nextChar != ']') { - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch (x.nextClean()) { - case 0: - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - case ',': - nextChar = x.nextClean(); - if (nextChar == 0) { - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - } - if (nextChar == ']') { - return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - } - - /** - * Construct a JSONArray from a source JSON text. - * - * @param source - * A string that begins with [ (left - * bracket) and ends with ] - *  (right bracket). - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(String source) throws JSONException { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONArray from a Collection. - * - * @param collection - * A Collection. - */ - public JSONArray(Collection collection) { - this(collection, 0, new JSONParserConfiguration()); - } - - /** - * Construct a JSONArray from a Collection. - * - * @param collection - * A Collection. - * @param jsonParserConfiguration - * Configuration object for the JSON parser - */ - public JSONArray(Collection collection, JSONParserConfiguration jsonParserConfiguration) { - this(collection, 0, jsonParserConfiguration); - } - - /** - * Construct a JSONArray from a collection with recursion depth. - * - * @param collection - * A Collection. - * @param recursionDepth - * Variable for tracking the count of nested object creations. - * @param jsonParserConfiguration - * Configuration object for the JSON parser - */ - JSONArray(Collection collection, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - if (recursionDepth > jsonParserConfiguration.getMaxNestingDepth()) { - throw new JSONException("JSONArray has reached recursion depth limit of " + jsonParserConfiguration.getMaxNestingDepth()); - } - if (collection == null) { - this.myArrayList = new ArrayList(); - } else { - this.myArrayList = new ArrayList(collection.size()); - this.addAll(collection, true, recursionDepth, jsonParserConfiguration); - } - } - - /** - * Construct a JSONArray from an Iterable. This is a shallow copy. - * - * @param iter - * A Iterable collection. - */ - public JSONArray(Iterable iter) { - this(); - if (iter == null) { - return; - } - this.addAll(iter, true); - } - - /** - * Construct a JSONArray from another JSONArray. This is a shallow copy. - * - * @param array - * A array. - */ - public JSONArray(JSONArray array) { - if (array == null) { - this.myArrayList = new ArrayList(); - } else { - // shallow copy directly the internal array lists as any wrapping - // should have been done already in the original JSONArray - this.myArrayList = new ArrayList(array.myArrayList); - } - } - - /** - * Construct a JSONArray from an array. - * - * @param array - * Array. If the parameter passed is null, or not an array, an - * exception will be thrown. - * - * @throws JSONException - * If not an array or if an array value is non-finite number. - * @throws NullPointerException - * Thrown if the array parameter is null. - */ - public JSONArray(Object array) throws JSONException { - this(); - if (!array.getClass().isArray()) { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); - } - this.addAll(array, true, 0); - } - - /** - * Construct a JSONArray with the specified initial capacity. - * - * @param initialCapacity - * the initial capacity of the JSONArray. - * @throws JSONException - * If the initial capacity is negative. - */ - public JSONArray(int initialCapacity) throws JSONException { - if (initialCapacity < 0) { - throw new JSONException( - "JSONArray initial capacity cannot be negative."); - } - this.myArrayList = new ArrayList(initialCapacity); - } - - @Override - public Iterator iterator() { - return this.myArrayList.iterator(); - } - - /** - * Get the object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value. - * @throws JSONException - * If there is no value for the index. - */ - public Object get(int index) throws JSONException { - Object object = this.opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - /** - * Get the boolean value associated with an index. The string values "true" - * and "false" are converted to boolean. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - * @throws JSONException - * If there is no value for the index or if the value is not - * convertible to boolean. - */ - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if (object.equals(Boolean.FALSE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { - return true; - } - throw wrongValueFormatException(index, "boolean", object, null); - } - - /** - * Get the double value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public double getDouble(int index) throws JSONException { - final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).doubleValue(); - } - try { - return Double.parseDouble(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(index, "double", object, e); - } - } - - /** - * Get the float value associated with a key. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public float getFloat(int index) throws JSONException { - final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).floatValue(); - } - try { - return Float.parseFloat(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(index, "float", object, e); - } - } - - /** - * Get the Number value associated with a key. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public Number getNumber(int index) throws JSONException { - Object object = this.get(index); - try { - if (object instanceof Number) { - return (Number)object; - } - return JSONObject.stringToNumber(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(index, "number", object, e); - } - } - - /** - * Get the enum value associated with an index. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, int index) throws JSONException { - E val = optEnum(clazz, index); - if(val==null) { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw wrongValueFormatException(index, "enum of type " - + JSONObject.quote(clazz.getSimpleName()), opt(index), null); - } - return val; - } - - /** - * Get the BigDecimal value associated with an index. If the value is float - * or double, the {@link BigDecimal#BigDecimal(double)} constructor - * will be used. See notes on the constructor for conversion issues that - * may arise. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigDecimal. - */ - public BigDecimal getBigDecimal (int index) throws JSONException { - Object object = this.get(index); - BigDecimal val = JSONObject.objectToBigDecimal(object, null); - if(val == null) { - throw wrongValueFormatException(index, "BigDecimal", object, null); - } - return val; - } - - /** - * Get the BigInteger value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigInteger. - */ - public BigInteger getBigInteger (int index) throws JSONException { - Object object = this.get(index); - BigInteger val = JSONObject.objectToBigInteger(object, null); - if(val == null) { - throw wrongValueFormatException(index, "BigInteger", object, null); - } - return val; - } - - /** - * Get the int value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value is not a number. - */ - public int getInt(int index) throws JSONException { - final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).intValue(); - } - try { - return Integer.parseInt(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(index, "int", object, e); - } - } - - /** - * Get the JSONArray associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONArray value. - * @throws JSONException - * If there is no value for the index. or if the value is not a - * JSONArray - */ - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw wrongValueFormatException(index, "JSONArray", object, null); - } - - /** - * Get the JSONObject associated with an index. - * - * @param index - * subscript - * @return A JSONObject value. - * @throws JSONException - * If there is no value for the index or if the value is not a - * JSONObject - */ - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw wrongValueFormatException(index, "JSONObject", object, null); - } - - /** - * Get the long value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public long getLong(int index) throws JSONException { - final Object object = this.get(index); - if(object instanceof Number) { - return ((Number)object).longValue(); - } - try { - return Long.parseLong(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(index, "long", object, e); - } - } - - /** - * Get the string associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A string value. - * @throws JSONException - * If there is no string value for the index. - */ - public String getString(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof String) { - return (String) object; - } - throw wrongValueFormatException(index, "String", object, null); - } - - /** - * Determine if the value is null. - * - * @param index - * The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. - */ - public boolean isNull(int index) { - return JSONObject.NULL.equals(this.opt(index)); - } - - /** - * Make a string from the contents of this JSONArray. The - * separator string is inserted between each element. Warning: - * This method assumes that the data structure is acyclical. - * - * @param separator - * A string that will be inserted between the elements. - * @return a string. - * @throws JSONException - * If the array contains an invalid number. - */ - public String join(String separator) throws JSONException { - int len = this.length(); - if (len == 0) { - return ""; - } - - StringBuilder sb = new StringBuilder( - JSONObject.valueToString(this.myArrayList.get(0))); - - for (int i = 1; i < len; i++) { - sb.append(separator) - .append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return this.myArrayList.size(); - } - - /** - * Removes all of the elements from this JSONArray. - * The JSONArray will be empty after this call returns. - */ - public void clear() { - this.myArrayList.clear(); - } - - /** - * Get the optional object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. If not, null is returned. - * @return An object value, or null if there is no object at that index. - */ - public Object opt(int index) { - return (index < 0 || index >= this.length()) ? null : this.myArrayList - .get(index); - } - - /** - * Get the optional boolean value associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) { - return this.optBoolean(index, false); - } - - /** - * Get the optional boolean value associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. - * @return The truth. - */ - public boolean optBoolean(int index, boolean defaultValue) { - try { - return this.getBoolean(index); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get the optional Boolean object associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - */ - public Boolean optBooleanObject(int index) { - return this.optBooleanObject(index, false); - } - - /** - * Get the optional Boolean object associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. - * @return The truth. - */ - public Boolean optBooleanObject(int index, Boolean defaultValue) { - try { - return this.getBoolean(index); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) { - return this.optDouble(index, Double.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - final double doubleValue = val.doubleValue(); - // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { - // return defaultValue; - // } - return doubleValue; - } - - /** - * Get the optional Double object associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The object. - */ - public Double optDoubleObject(int index) { - return this.optDoubleObject(index, Double.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default object. - * @return The object. - */ - public Double optDoubleObject(int index, Double defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - final Double doubleValue = val.doubleValue(); - // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { - // return defaultValue; - // } - return doubleValue; - } - - /** - * Get the optional float value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public float optFloat(int index) { - return this.optFloat(index, Float.NaN); - } - - /** - * Get the optional float value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default value. - * @return The value. - */ - public float optFloat(int index, float defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - final float floatValue = val.floatValue(); - // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { - // return floatValue; - // } - return floatValue; - } - - /** - * Get the optional Float object associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The object. - */ - public Float optFloatObject(int index) { - return this.optFloatObject(index, Float.NaN); - } - - /** - * Get the optional Float object associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default object. - * @return The object. - */ - public Float optFloatObject(int index, Float defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - final Float floatValue = val.floatValue(); - // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { - // return floatValue; - // } - return floatValue; - } - - /** - * Get the optional int value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) { - return this.optInt(index, 0); - } - - /** - * Get the optional int value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public int optInt(int index, int defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * Get the optional Integer object associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The object. - */ - public Integer optIntegerObject(int index) { - return this.optIntegerObject(index, 0); - } - - /** - * Get the optional Integer object associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default object. - * @return The object. - */ - public Integer optIntegerObject(int index, Integer defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location or null if not found - */ - public > E optEnum(Class clazz, int index) { - return this.optEnum(clazz, index, null); - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default in case the value is not found - * @return The enum value at the index location or defaultValue if - * the value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, int index, E defaultValue) { - try { - Object val = this.opt(index); - if (JSONObject.NULL.equals(val)) { - return defaultValue; - } - if (clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } catch (IllegalArgumentException e) { - return defaultValue; - } catch (NullPointerException e) { - return defaultValue; - } - } - - /** - * Get the optional BigInteger value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public BigInteger optBigInteger(int index, BigInteger defaultValue) { - Object val = this.opt(index); - return JSONObject.objectToBigInteger(val, defaultValue); - } - - /** - * Get the optional BigDecimal value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. If the value - * is float or double, the {@link BigDecimal#BigDecimal(double)} - * constructor will be used. See notes on the constructor for conversion - * issues that may arise. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { - Object val = this.opt(index); - return JSONObject.objectToBigDecimal(val, defaultValue); - } - - /** - * Get the optional JSONArray associated with an index. Null is returned if - * there is no value at that index or if the value is not a JSONArray. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONArray value. - */ - public JSONArray optJSONArray(int index) { - return this.optJSONArray(index, null); - } - - /** - * Get the optional JSONArray associated with an index. The defaultValue is returned if - * there is no value at that index or if the value is not a JSONArray. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default. - * @return A JSONArray value. - */ - public JSONArray optJSONArray(int index, JSONArray defaultValue) { - Object object = this.opt(index); - return object instanceof JSONArray ? (JSONArray) object : defaultValue; - } - - /** - * Get the optional JSONObject associated with an index. Null is returned if - * there is no value at that index or if the value is not a JSONObject. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) { - return this.optJSONObject(index, null); - } - - /** - * Get the optional JSONObject associated with an index. The defaultValue is returned if - * there is no value at that index or if the value is not a JSONObject. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index, JSONObject defaultValue) { - Object object = this.opt(index); - return object instanceof JSONObject ? (JSONObject) object : defaultValue; - } - - /** - * Get the optional long value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) { - return this.optLong(index, 0); - } - - /** - * Get the optional long value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public long optLong(int index, long defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.longValue(); - } - - /** - * Get the optional Long object associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The object. - */ - public Long optLongObject(int index) { - return this.optLongObject(index, 0L); - } - - /** - * Get the optional Long object associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default object. - * @return The object. - */ - public Long optLongObject(int index, Long defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.longValue(); - } - - /** - * Get an optional {@link Number} value associated with a key, or null - * if there is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object which is the value. - */ - public Number optNumber(int index) { - return this.optNumber(index, null); - } - - /** - * Get an optional {@link Number} value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public Number optNumber(int index, Number defaultValue) { - Object val = this.opt(index); - if (JSONObject.NULL.equals(val)) { - return defaultValue; - } - if (val instanceof Number){ - return (Number) val; - } - - if (val instanceof String) { - try { - return JSONObject.stringToNumber((String) val); - } catch (Exception e) { - return defaultValue; - } - } - return defaultValue; - } - - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value is not a - * string and is not null, then it is converted to a string. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) { - return this.optString(index, ""); - } - - /** - * Get the optional string associated with an index. The defaultValue is - * returned if the key is not found. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return A String value. - */ - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) ? defaultValue : object - .toString(); - } - - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value - * A boolean value. - * @return this. - */ - public JSONArray put(boolean value) { - return this.put(value ? Boolean.TRUE : Boolean.FALSE); - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - */ - public JSONArray put(Collection value) { - return this.put(new JSONArray(value)); - } - - /** - * Append a double value. This increases the array's length by one. - * - * @param value - * A double value. - * @return this. - * @throws JSONException - * if the value is not finite. - */ - public JSONArray put(double value) throws JSONException { - return this.put(Double.valueOf(value)); - } - - /** - * Append a float value. This increases the array's length by one. - * - * @param value - * A float value. - * @return this. - * @throws JSONException - * if the value is not finite. - */ - public JSONArray put(float value) throws JSONException { - return this.put(Float.valueOf(value)); - } - - /** - * Append an int value. This increases the array's length by one. - * - * @param value - * An int value. - * @return this. - */ - public JSONArray put(int value) { - return this.put(Integer.valueOf(value)); - } - - /** - * Append an long value. This increases the array's length by one. - * - * @param value - * A long value. - * @return this. - */ - public JSONArray put(long value) { - return this.put(Long.valueOf(value)); - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject which - * is produced from a Map. - * - * @param value - * A Map value. - * @return this. - * @throws JSONException - * If a value in the map is non-finite number. - * @throws NullPointerException - * If a key in the map is null - */ - public JSONArray put(Map value) { - return this.put(new JSONObject(value)); - } - - /** - * Append an object value. This increases the array's length by one. - * - * @param value - * An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is non-finite number. - */ - public JSONArray put(Object value) { - JSONObject.testValidity(value); - this.myArrayList.add(value); - return this; - } - - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * A boolean value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, boolean value) throws JSONException { - return this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param index - * The subscript. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. - */ - public JSONArray put(int index, Collection value) throws JSONException { - return this.put(index, new JSONArray(value)); - } - - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A double value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. - */ - public JSONArray put(int index, double value) throws JSONException { - return this.put(index, Double.valueOf(value)); - } - - /** - * Put or replace a float value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A float value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. - */ - public JSONArray put(int index, float value) throws JSONException { - return this.put(index, Float.valueOf(value)); - } - - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * An int value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException { - return this.put(index, Integer.valueOf(value)); - } - - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A long value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException { - return this.put(index, Long.valueOf(value)); - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject that - * is produced from a Map. - * - * @param index - * The subscript. - * @param value - * The Map value. - * @return - * reference to self - * @throws JSONException - * If the index is negative or if the value is an invalid - * number. - * @throws NullPointerException - * If a key in the map is null - */ - public JSONArray put(int index, Map value) throws JSONException { - this.put(index, new JSONObject(value, new JSONParserConfiguration())); - return this; - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject that - * is produced from a Map. - * - * @param index - * The subscript - * @param value - * The Map value. - * @param jsonParserConfiguration - * Configuration object for the JSON parser - * @return reference to self - * @throws JSONException - * If the index is negative or if the value is an invalid - * number. - */ - public JSONArray put(int index, Map value, JSONParserConfiguration jsonParserConfiguration) throws JSONException { - this.put(index, new JSONObject(value, jsonParserConfiguration)); - return this; - } - - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the index is negative or if the value is an invalid - * number. - */ - public JSONArray put(int index, Object value) throws JSONException { - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < this.length()) { - JSONObject.testValidity(value); - this.myArrayList.set(index, value); - return this; - } - if(index == this.length()){ - // simple append - return this.put(value); - } - // if we are inserting past the length, we want to grow the array all at once - // instead of incrementally. - this.myArrayList.ensureCapacity(index + 1); - while (index != this.length()) { - // we don't need to test validity of NULL objects - this.myArrayList.add(JSONObject.NULL); - } - return this.put(value); - } - - /** - * Put a collection's elements in to the JSONArray. - * - * @param collection - * A Collection. - * @return this. - */ - public JSONArray putAll(Collection collection) { - this.addAll(collection, false); - return this; - } - - /** - * Put an Iterable's elements in to the JSONArray. - * - * @param iter - * An Iterable. - * @return this. - */ - public JSONArray putAll(Iterable iter) { - this.addAll(iter, false); - return this; - } - - /** - * Put a JSONArray's elements in to the JSONArray. - * - * @param array - * A JSONArray. - * @return this. - */ - public JSONArray putAll(JSONArray array) { - // directly copy the elements from the source array to this one - // as all wrapping should have been done already in the source. - this.myArrayList.addAll(array.myArrayList); - return this; - } - - /** - * Put an array's elements in to the JSONArray. - * - * @param array - * Array. If the parameter passed is null, or not an array or Iterable, an - * exception will be thrown. - * @return this. - * - * @throws JSONException - * If not an array, JSONArray, Iterable or if an value is non-finite number. - * @throws NullPointerException - * Thrown if the array parameter is null. - */ - public JSONArray putAll(Object array) throws JSONException { - this.addAll(array, false); - return this; - } - - /** - * Creates a JSONPointer using an initialization string and tries to - * match it to an item within this JSONArray. For example, given a - * JSONArray initialized with this document: - *
              -     * [
              -     *     {"b":"c"}
              -     * ]
              -     * 
              - * and this JSONPointer string: - *
              -     * "/0/b"
              -     * 
              - * Then this method will return the String "c" - * A JSONPointerException may be thrown from code called by this method. - * - * @param jsonPointer string that can be used to create a JSONPointer - * @return the item matched by the JSONPointer, otherwise null - */ - public Object query(String jsonPointer) { - return query(new JSONPointer(jsonPointer)); - } - - /** - * Uses a user initialized JSONPointer and tries to - * match it to an item within this JSONArray. For example, given a - * JSONArray initialized with this document: - *
              -     * [
              -     *     {"b":"c"}
              -     * ]
              -     * 
              - * and this JSONPointer: - *
              -     * "/0/b"
              -     * 
              - * Then this method will return the String "c" - * A JSONPointerException may be thrown from code called by this method. - * - * @param jsonPointer string that can be used to create a JSONPointer - * @return the item matched by the JSONPointer, otherwise null - */ - public Object query(JSONPointer jsonPointer) { - return jsonPointer.queryFrom(this); - } - - /** - * Queries and returns a value from this object using {@code jsonPointer}, or - * returns null if the query fails due to a missing key. - * - * @param jsonPointer the string representation of the JSON pointer - * @return the queried value or {@code null} - * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax - */ - public Object optQuery(String jsonPointer) { - return optQuery(new JSONPointer(jsonPointer)); - } - - /** - * Queries and returns a value from this object using {@code jsonPointer}, or - * returns null if the query fails due to a missing key. - * - * @param jsonPointer The JSON pointer - * @return the queried value or {@code null} - * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax - */ - public Object optQuery(JSONPointer jsonPointer) { - try { - return jsonPointer.queryFrom(this); - } catch (JSONPointerException e) { - return null; - } - } - - /** - * Remove an index and close the hole. - * - * @param index - * The index of the element to be removed. - * @return The value that was associated with the index, or null if there - * was no value. - */ - public Object remove(int index) { - return index >= 0 && index < this.length() - ? this.myArrayList.remove(index) - : null; - } - - /** - * Determine if two JSONArrays are similar. - * They must contain similar sequences. - * - * @param other The other JSONArray - * @return true if they are equal - */ - public boolean similar(Object other) { - if (!(other instanceof JSONArray)) { - return false; - } - int len = this.length(); - if (len != ((JSONArray)other).length()) { - return false; - } - for (int i = 0; i < len; i += 1) { - Object valueThis = this.myArrayList.get(i); - Object valueOther = ((JSONArray)other).myArrayList.get(i); - if(valueThis == valueOther) { - continue; - } - if(valueThis == null) { - return false; - } - if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof Number && valueOther instanceof Number) { - if (!JSONObject.isNumberSimilar((Number)valueThis, (Number)valueOther)) { - return false; - } - } else if (valueThis instanceof JSONString && valueOther instanceof JSONString) { - if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } - - /** - * Produce a JSONObject by combining a JSONArray of names with the values of - * this JSONArray. - * - * @param names - * A JSONArray containing a list of key strings. These will be - * paired with the values. - * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException - * If any of the names are null. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.isEmpty() || this.isEmpty()) { - return null; - } - JSONObject jo = new JSONObject(names.length()); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - /** - * Make a JSON text of this JSONArray. For compactness, no unnecessary - * whitespace is added. If it is not possible to produce a syntactically - * correct JSON text then null will be returned instead. This could occur if - * the array contains an invalid number. - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * - * @return a printable, displayable, transmittable representation of the - * array. - */ - @Override - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return null; - } - } - - /** - * Make a pretty-printed JSON text of this JSONArray. - * - *

              If

               {@code indentFactor > 0}
              and the {@link JSONArray} has only - * one element, then the array will be output on a single line: - *
              {@code [1]}
              - * - *

              If an array has 2 or more elements, then it will be output across - * multiple lines:

              {@code
              -     * [
              -     * 1,
              -     * "value 2",
              -     * 3
              -     * ]
              -     * }
              - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, transmittable representation of the - * object, beginning with [ (left - * bracket) and ending with ] - *  (right bracket). - * @throws JSONException if a called function fails - */ - @SuppressWarnings("resource") - public String toString(int indentFactor) throws JSONException { - StringWriter sw = new StringWriter(); - return this.write(sw, indentFactor, 0).toString(); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * @param writer the writer object - * @return The writer. - * @throws JSONException if a called function fails - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. - * - *

              If

              {@code indentFactor > 0}
              and the {@link JSONArray} has only - * one element, then the array will be output on a single line: - *
              {@code [1]}
              - * - *

              If an array has 2 or more elements, then it will be output across - * multiple lines:

              {@code
              -     * [
              -     * 1,
              -     * "value 2",
              -     * 3
              -     * ]
              -     * }
              - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * - * @param writer - * Writes the serialized JSON - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @param indent - * The indentation of the top level. - * @return The writer. - * @throws JSONException if a called function fails or unable to write - */ - @SuppressWarnings("resource") - public Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean needsComma = false; - int length = this.length(); - writer.write('['); - - if (length == 1) { - try { - JSONObject.writeValue(writer, this.myArrayList.get(0), - indentFactor, indent); - } catch (Exception e) { - throw new JSONException("Unable to write JSONArray value at index: 0", e); - } - } else if (length != 0) { - final int newIndent = indent + indentFactor; - - for (int i = 0; i < length; i += 1) { - if (needsComma) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, newIndent); - try { - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newIndent); - } catch (Exception e) { - throw new JSONException("Unable to write JSONArray value at index: " + i, e); - } - needsComma = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch (IOException e) { - throw new JSONException(e); - } - } - - /** - * Returns a java.util.List containing all of the elements in this array. - * If an element in the array is a JSONArray or JSONObject it will also - * be converted to a List and a Map respectively. - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * @return a java.util.List containing the elements of this array - */ - public List toList() { - List results = new ArrayList(this.myArrayList.size()); - for (Object element : this.myArrayList) { - if (element == null || JSONObject.NULL.equals(element)) { - results.add(null); - } else if (element instanceof JSONArray) { - results.add(((JSONArray) element).toList()); - } else if (element instanceof JSONObject) { - results.add(((JSONObject) element).toMap()); - } else { - results.add(element); - } - } - return results; - } - - /** - * Check if JSONArray is empty. - * - * @return true if JSONArray is empty, otherwise false. - */ - public boolean isEmpty() { - return this.myArrayList.isEmpty(); - } - - /** - * Add a collection's elements to the JSONArray. - * - * @param collection - * A Collection. - * @param wrap - * {@code true} to call {@link JSONObject#wrap(Object)} for each item, - * {@code false} to add the items directly - * @param recursionDepth - * Variable for tracking the count of nested object creations. - */ - private void addAll(Collection collection, boolean wrap, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - this.myArrayList.ensureCapacity(this.myArrayList.size() + collection.size()); - if (wrap) { - for (Object o: collection){ - this.put(JSONObject.wrap(o, recursionDepth + 1, jsonParserConfiguration)); - } - } else { - for (Object o: collection){ - this.put(o); - } - } - } - - /** - * Add an Iterable's elements to the JSONArray. - * - * @param iter - * An Iterable. - * @param wrap - * {@code true} to call {@link JSONObject#wrap(Object)} for each item, - * {@code false} to add the items directly - */ - private void addAll(Iterable iter, boolean wrap) { - if (wrap) { - for (Object o: iter){ - this.put(JSONObject.wrap(o)); - } - } else { - for (Object o: iter){ - this.put(o); - } - } - } - - /** - * Add an array's elements to the JSONArray. - * - * @param array - * Array. If the parameter passed is null, or not an array, - * JSONArray, Collection, or Iterable, an exception will be - * thrown. - * @param wrap - * {@code true} to call {@link JSONObject#wrap(Object)} for each item, - * {@code false} to add the items directly - * @throws JSONException - * If not an array or if an array value is non-finite number. - */ - private void addAll(Object array, boolean wrap) throws JSONException { - this.addAll(array, wrap, 0); - } - - /** - * Add an array's elements to the JSONArray. - * - * @param array - * Array. If the parameter passed is null, or not an array, - * JSONArray, Collection, or Iterable, an exception will be - * thrown. - * @param wrap - * {@code true} to call {@link JSONObject#wrap(Object)} for each item, - * {@code false} to add the items directly - * @param recursionDepth - * Variable for tracking the count of nested object creations. - */ - private void addAll(Object array, boolean wrap, int recursionDepth) { - addAll(array, wrap, recursionDepth, new JSONParserConfiguration()); - } - /** - * Add an array's elements to the JSONArray. - *` - * @param array - * Array. If the parameter passed is null, or not an array, - * JSONArray, Collection, or Iterable, an exception will be - * thrown. - * @param wrap - * {@code true} to call {@link JSONObject#wrap(Object)} for each item, - * {@code false} to add the items directly - * @param recursionDepth - * Variable for tracking the count of nested object creations. - * @param jsonParserConfiguration - * Variable to pass parser custom configuration for json parsing. - * @throws JSONException - * If not an array or if an array value is non-finite number. - * @throws NullPointerException - * Thrown if the array parameter is null. - */ - private void addAll(Object array, boolean wrap, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) throws JSONException { - if (array.getClass().isArray()) { - int length = Array.getLength(array); - this.myArrayList.ensureCapacity(this.myArrayList.size() + length); - if (wrap) { - for (int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i), recursionDepth + 1, jsonParserConfiguration)); - } - } else { - for (int i = 0; i < length; i += 1) { - this.put(Array.get(array, i)); - } - } - } else if (array instanceof JSONArray) { - // use the built in array list `addAll` as all object - // wrapping should have been completed in the original - // JSONArray - this.myArrayList.addAll(((JSONArray)array).myArrayList); - } else if (array instanceof Collection) { - this.addAll((Collection)array, wrap, recursionDepth); - } else if (array instanceof Iterable) { - this.addAll((Iterable)array, wrap); - } else { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); - } - } - - /** - * Create a new JSONException in a common format for incorrect conversions. - * @param idx index of the item - * @param valueType the type of value being coerced to - * @param cause optional cause of the coercion failure - * @return JSONException that can be thrown. - */ - private static JSONException wrongValueFormatException( - int idx, - String valueType, - Object value, - Throwable cause) { - if(value == null) { - return new JSONException( - "JSONArray[" + idx + "] is not a " + valueType + " (null)." - , cause); - } - // don't try to toString collections or known object types that could be large. - if(value instanceof Map || value instanceof Iterable || value instanceof JSONObject) { - return new JSONException( - "JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + ")." - , cause); - } - return new JSONException( - "JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")." - , cause); - } + /** + * Create a new JSONException in a common format for incorrect conversions. + * + * @param idx index of the item + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException(int idx, String valueType, Object value, Throwable cause) { + if (value == null) { + return new JSONException("JSONArray[" + idx + "] is not a " + valueType + " (null).", cause); + } + // don't try to toString collections or known object types that could be large. + if (value instanceof Map || value instanceof Iterable || value instanceof JSONObject) { + return new JSONException("JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + ").", + cause); + } + return new JSONException( + "JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ").", cause); + } + + /** + * The arrayList where the JSONArray's properties are kept. + */ + private final ArrayList myArrayList; + + /** + * Construct an empty JSONArray. + */ + public JSONArray() { + this.myArrayList = new ArrayList(); + } + + /** + * Construct a JSONArray from a Collection. + * + * @param collection A Collection. + */ + public JSONArray(Collection collection) { + this(collection, 0, new JSONParserConfiguration()); + } + + /** + * Construct a JSONArray from a collection with recursion depth. + * + * @param collection A Collection. + * @param recursionDepth Variable for tracking the count of nested + * object creations. + * @param jsonParserConfiguration Configuration object for the JSON parser + */ + JSONArray(Collection collection, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { + if (recursionDepth > jsonParserConfiguration.getMaxNestingDepth()) { + throw new JSONException( + "JSONArray has reached recursion depth limit of " + jsonParserConfiguration.getMaxNestingDepth()); + } + if (collection == null) { + this.myArrayList = new ArrayList(); + } else { + this.myArrayList = new ArrayList(collection.size()); + this.addAll(collection, true, recursionDepth, jsonParserConfiguration); + } + } + + /** + * Construct a JSONArray from a Collection. + * + * @param collection A Collection. + * @param jsonParserConfiguration Configuration object for the JSON parser + */ + public JSONArray(Collection collection, JSONParserConfiguration jsonParserConfiguration) { + this(collection, 0, jsonParserConfiguration); + } + + /** + * Construct a JSONArray with the specified initial capacity. + * + * @param initialCapacity the initial capacity of the JSONArray. + * @throws JSONException If the initial capacity is negative. + */ + public JSONArray(int initialCapacity) throws JSONException { + if (initialCapacity < 0) { + throw new JSONException("JSONArray initial capacity cannot be negative."); + } + this.myArrayList = new ArrayList(initialCapacity); + } + + /** + * Construct a JSONArray from an Iterable. This is a shallow copy. + * + * @param iter A Iterable collection. + */ + public JSONArray(Iterable iter) { + this(); + if (iter == null) { + return; + } + this.addAll(iter, true); + } + + /** + * Construct a JSONArray from another JSONArray. This is a shallow copy. + * + * @param array A array. + */ + public JSONArray(JSONArray array) { + if (array == null) { + this.myArrayList = new ArrayList(); + } else { + // shallow copy directly the internal array lists as any wrapping + // should have been done already in the original JSONArray + this.myArrayList = new ArrayList(array.myArrayList); + } + } + + /** + * Construct a JSONArray from a JSONTokener. + * + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + public JSONArray(JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + + char nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw x.syntaxError("Expected a ',' or ']'"); + } + if (nextChar != ']') { + x.back(); + for (;;) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case 0: + // array is unclosed. No ']' found, instead EOF + throw x.syntaxError("Expected a ',' or ']'"); + case ',': + nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw x.syntaxError("Expected a ',' or ']'"); + } + if (nextChar == ']') { + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } + + /** + * Construct a JSONArray from an array. + * + * @param array Array. If the parameter passed is null, or not an array, an + * exception will be thrown. + * + * @throws JSONException If not an array or if an array value is + * non-finite number. + * @throws NullPointerException Thrown if the array parameter is null. + */ + public JSONArray(Object array) throws JSONException { + this(); + if (!array.getClass().isArray()) { + throw new JSONException("JSONArray initial value should be a string or collection or array."); + } + this.addAll(array, true, 0); + } + + /** + * Construct a JSONArray from a source JSON text. + * + * @param source A string that begins with [ (left + * bracket) and ends with ] + *  (right bracket). + * @throws JSONException If there is a syntax error. + */ + public JSONArray(String source) throws JSONException { + this(new JSONTokener(source)); + } + + /** + * Add a collection's elements to the JSONArray. + * + * @param collection A Collection. + * @param wrap {@code true} to call {@link JSONObject#wrap(Object)} + * for each item, {@code false} to add the items directly + * @param recursionDepth Variable for tracking the count of nested object + * creations. + */ + private void addAll(Collection collection, boolean wrap, int recursionDepth, + JSONParserConfiguration jsonParserConfiguration) { + this.myArrayList.ensureCapacity(this.myArrayList.size() + collection.size()); + if (wrap) { + for (Object o : collection) { + this.put(JSONObject.wrap(o, recursionDepth + 1, jsonParserConfiguration)); + } + } else { + for (Object o : collection) { + this.put(o); + } + } + } + + /** + * Add an Iterable's elements to the JSONArray. + * + * @param iter An Iterable. + * @param wrap {@code true} to call {@link JSONObject#wrap(Object)} for each + * item, {@code false} to add the items directly + */ + private void addAll(Iterable iter, boolean wrap) { + if (wrap) { + for (Object o : iter) { + this.put(JSONObject.wrap(o)); + } + } else { + for (Object o : iter) { + this.put(o); + } + } + } + + /** + * Add an array's elements to the JSONArray. + * + * @param array Array. If the parameter passed is null, or not an array, + * JSONArray, Collection, or Iterable, an exception will be thrown. + * @param wrap {@code true} to call {@link JSONObject#wrap(Object)} for each + * item, {@code false} to add the items directly + * @throws JSONException If not an array or if an array value is non-finite + * number. + */ + private void addAll(Object array, boolean wrap) throws JSONException { + this.addAll(array, wrap, 0); + } + + /** + * Add an array's elements to the JSONArray. + * + * @param array Array. If the parameter passed is null, or not an + * array, JSONArray, Collection, or Iterable, an exception + * will be thrown. + * @param wrap {@code true} to call {@link JSONObject#wrap(Object)} + * for each item, {@code false} to add the items directly + * @param recursionDepth Variable for tracking the count of nested object + * creations. + */ + private void addAll(Object array, boolean wrap, int recursionDepth) { + addAll(array, wrap, recursionDepth, new JSONParserConfiguration()); + } + + /** + * Add an array's elements to the JSONArray. ` + * + * @param array Array. If the parameter passed is null, or not + * an array, JSONArray, Collection, or Iterable, + * an exception will be thrown. + * @param wrap {@code true} to call + * {@link JSONObject#wrap(Object)} for each item, + * {@code false} to add the items directly + * @param recursionDepth Variable for tracking the count of nested + * object creations. + * @param jsonParserConfiguration Variable to pass parser custom configuration + * for json parsing. + * @throws JSONException If not an array or if an array value is + * non-finite number. + * @throws NullPointerException Thrown if the array parameter is null. + */ + private void addAll(Object array, boolean wrap, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) + throws JSONException { + if (array.getClass().isArray()) { + int length = Array.getLength(array); + this.myArrayList.ensureCapacity(this.myArrayList.size() + length); + if (wrap) { + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i), recursionDepth + 1, jsonParserConfiguration)); + } + } else { + for (int i = 0; i < length; i += 1) { + this.put(Array.get(array, i)); + } + } + } else if (array instanceof JSONArray) { + // use the built in array list `addAll` as all object + // wrapping should have been completed in the original + // JSONArray + this.myArrayList.addAll(((JSONArray) array).myArrayList); + } else if (array instanceof Collection) { + this.addAll((Collection) array, wrap, recursionDepth); + } else if (array instanceof Iterable) { + this.addAll((Iterable) array, wrap); + } else { + throw new JSONException("JSONArray initial value should be a string or collection or array."); + } + } + + /** + * Removes all of the elements from this JSONArray. The JSONArray will be empty + * after this call returns. + */ + public void clear() { + this.myArrayList.clear(); + } + + /** + * Get the object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return An object value. + * @throws JSONException If there is no value for the index. + */ + public Object get(int index) throws JSONException { + Object object = this.opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + /** + * Get the BigDecimal value associated with an index. If the value is float or + * double, the {@link BigDecimal#BigDecimal(double)} constructor will be used. + * See notes on the constructor for conversion issues that may arise. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be + * converted to a BigDecimal. + */ + public BigDecimal getBigDecimal(int index) throws JSONException { + Object object = this.get(index); + BigDecimal val = JSONObject.objectToBigDecimal(object, null); + if (val == null) { + throw wrongValueFormatException(index, "BigDecimal", object, null); + } + return val; + } + + /** + * Get the BigInteger value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be + * converted to a BigInteger. + */ + public BigInteger getBigInteger(int index) throws JSONException { + Object object = this.get(index); + BigInteger val = JSONObject.objectToBigInteger(object, null); + if (val == null) { + throw wrongValueFormatException(index, "BigInteger", object, null); + } + return val; + } + + /** + * Get the boolean value associated with an index. The string values "true" and + * "false" are converted to boolean. + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + * @throws JSONException If there is no value for the index or if the value is + * not convertible to boolean. + */ + public boolean getBoolean(int index) throws JSONException { + Object object = this.get(index); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) + || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw wrongValueFormatException(index, "boolean", object, null); + } + + /** + * Get the double value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be + * converted to a number. + */ + public double getDouble(int index) throws JSONException { + final Object object = this.get(index); + if (object instanceof Number) { + return ((Number) object).doubleValue(); + } + try { + return Double.parseDouble(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "double", object, e); + } + } + + /** + * Get the enum value associated with an index. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @return The enum value at the index location + * @throws JSONException if the key is not found or if the value cannot be + * converted to an enum. + */ + public > E getEnum(Class clazz, int index) throws JSONException { + E val = optEnum(clazz, index); + if (val == null) { + // JSONException should really take a throwable argument. + // If it did, I would re-implement this with the Enum.valueOf + // method and place any thrown exception in the JSONException + throw wrongValueFormatException(index, "enum of type " + JSONObject.quote(clazz.getSimpleName()), + opt(index), null); + } + return val; + } + + /** + * Get the float value associated with a key. + * + * @param index The index must be between 0 and length() - 1. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public float getFloat(int index) throws JSONException { + final Object object = this.get(index); + if (object instanceof Number) { + return ((Number) object).floatValue(); + } + try { + return Float.parseFloat(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "float", object, e); + } + } + + /** + * Get the int value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value is not a + * number. + */ + public int getInt(int index) throws JSONException { + final Object object = this.get(index); + if (object instanceof Number) { + return ((Number) object).intValue(); + } + try { + return Integer.parseInt(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "int", object, e); + } + } + + /** + * Get the JSONArray associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + * @throws JSONException If there is no value for the index. or if the value is + * not a JSONArray + */ + public JSONArray getJSONArray(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw wrongValueFormatException(index, "JSONArray", object, null); + } + + /** + * Get the JSONObject associated with an index. + * + * @param index subscript + * @return A JSONObject value. + * @throws JSONException If there is no value for the index or if the value is + * not a JSONObject + */ + public JSONObject getJSONObject(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw wrongValueFormatException(index, "JSONObject", object, null); + } + + /** + * Get the long value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be + * converted to a number. + */ + public long getLong(int index) throws JSONException { + final Object object = this.get(index); + if (object instanceof Number) { + return ((Number) object).longValue(); + } + try { + return Long.parseLong(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "long", object, e); + } + } + + /** + * Get the Number value associated with a key. + * + * @param index The index must be between 0 and length() - 1. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public Number getNumber(int index) throws JSONException { + Object object = this.get(index); + try { + if (object instanceof Number) { + return (Number) object; + } + return JSONObject.stringToNumber(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(index, "number", object, e); + } + } + + /** + * Get the string associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return A string value. + * @throws JSONException If there is no string value for the index. + */ + public String getString(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof String) { + return (String) object; + } + throw wrongValueFormatException(index, "String", object, null); + } + + /** + * Check if JSONArray is empty. + * + * @return true if JSONArray is empty, otherwise false. + */ + public boolean isEmpty() { + return this.myArrayList.isEmpty(); + } + + /** + * Determine if the value is null. + * + * @param index The index must be between 0 and length() - 1. + * @return true if the value at the index is null, or if there is + * no value. + */ + public boolean isNull(int index) { + return JSONObject.NULL.equals(this.opt(index)); + } + + @Override + public Iterator iterator() { + return this.myArrayList.iterator(); + } + + /** + * Make a string from the contents of this JSONArray. The separator + * string is inserted between each element. Warning: This method assumes that + * the data structure is acyclical. + * + * @param separator A string that will be inserted between the elements. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join(String separator) throws JSONException { + int len = this.length(); + if (len == 0) { + return ""; + } + + StringBuilder sb = new StringBuilder(JSONObject.valueToString(this.myArrayList.get(0))); + + for (int i = 1; i < len; i++) { + sb.append(separator).append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length() { + return this.myArrayList.size(); + } + + /** + * Get the optional object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. If not, null is + * returned. + * @return An object value, or null if there is no object at that index. + */ + public Object opt(int index) { + return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); + } + + /** + * Get the optional BigDecimal value associated with an index. The defaultValue + * is returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. If the value is float or double, + * the {@link BigDecimal#BigDecimal(double)} constructor will be used. See notes + * on the constructor for conversion issues that may arise. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { + Object val = this.opt(index); + return JSONObject.objectToBigDecimal(val, defaultValue); + } + + /** + * Get the optional BigInteger value associated with an index. The defaultValue + * is returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public BigInteger optBigInteger(int index, BigInteger defaultValue) { + Object val = this.opt(index); + return JSONObject.objectToBigInteger(val, defaultValue); + } + + /** + * Get the optional boolean value associated with an index. It returns false if + * there is no value at that index, or if the value is not Boolean.TRUE or the + * String "true". + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + */ + public boolean optBoolean(int index) { + return this.optBoolean(index, false); + } + + /** + * Get the optional boolean value associated with an index. It returns the + * defaultValue if there is no value at that index or if it is not a Boolean or + * the String "true" or "false" (case insensitive). + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. + */ + public boolean optBoolean(int index, boolean defaultValue) { + try { + return this.getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get the optional Boolean object associated with an index. It returns false if + * there is no value at that index, or if the value is not Boolean.TRUE or the + * String "true". + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + */ + public Boolean optBooleanObject(int index) { + return this.optBooleanObject(index, false); + } + + /** + * Get the optional Boolean object associated with an index. It returns the + * defaultValue if there is no value at that index or if it is not a Boolean or + * the String "true" or "false" (case insensitive). + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. + */ + public Boolean optBooleanObject(int index, Boolean defaultValue) { + try { + return this.getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get the optional double value associated with an index. NaN is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public double optDouble(int index) { + return this.optDouble(index, Double.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default value. + * @return The value. + */ + public double optDouble(int index, double defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + final double doubleValue = val.doubleValue(); + // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { + // return defaultValue; + // } + return doubleValue; + } + + /** + * Get the optional Double object associated with an index. NaN is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The object. + */ + public Double optDoubleObject(int index) { + return this.optDoubleObject(index, Double.NaN); + } + + /** + * Get the optional double value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default object. + * @return The object. + */ + public Double optDoubleObject(int index, Double defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + final Double doubleValue = val.doubleValue(); + // if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) { + // return defaultValue; + // } + return doubleValue; + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @return The enum value at the index location or null if not found + */ + public > E optEnum(Class clazz, int index) { + return this.optEnum(clazz, index, null); + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default in case the value is not found + * @return The enum value at the index location or defaultValue if the value is + * not found or cannot be assigned to clazz + */ + public > E optEnum(Class clazz, int index, E defaultValue) { + try { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (clazz.isAssignableFrom(val.getClass())) { + // we just checked it! + @SuppressWarnings("unchecked") + E myE = (E) val; + return myE; + } + return Enum.valueOf(clazz, val.toString()); + } catch (IllegalArgumentException e) { + return defaultValue; + } catch (NullPointerException e) { + return defaultValue; + } + } + + /** + * Get the optional float value associated with an index. NaN is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public float optFloat(int index) { + return this.optFloat(index, Float.NaN); + } + + /** + * Get the optional float value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default value. + * @return The value. + */ + public float optFloat(int index, float defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + final float floatValue = val.floatValue(); + // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { + // return floatValue; + // } + return floatValue; + } + + /** + * Get the optional Float object associated with an index. NaN is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The object. + */ + public Float optFloatObject(int index) { + return this.optFloatObject(index, Float.NaN); + } + + /** + * Get the optional Float object associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default object. + * @return The object. + */ + public Float optFloatObject(int index, Float defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + final Float floatValue = val.floatValue(); + // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { + // return floatValue; + // } + return floatValue; + } + + /** + * Get the optional int value associated with an index. Zero is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public int optInt(int index) { + return this.optInt(index, 0); + } + + /** + * Get the optional int value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public int optInt(int index, int defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + return val.intValue(); + } + + /** + * Get the optional Integer object associated with an index. Zero is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The object. + */ + public Integer optIntegerObject(int index) { + return this.optIntegerObject(index, 0); + } + + /** + * Get the optional Integer object associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default object. + * @return The object. + */ + public Integer optIntegerObject(int index, Integer defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + return val.intValue(); + } + + /** + * Get the optional JSONArray associated with an index. Null is returned if + * there is no value at that index or if the value is not a JSONArray. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + */ + public JSONArray optJSONArray(int index) { + return this.optJSONArray(index, null); + } + + /** + * Get the optional JSONArray associated with an index. The defaultValue is + * returned if there is no value at that index or if the value is not a + * JSONArray. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default. + * @return A JSONArray value. + */ + public JSONArray optJSONArray(int index, JSONArray defaultValue) { + Object object = this.opt(index); + return object instanceof JSONArray ? (JSONArray) object : defaultValue; + } + + /** + * Get the optional JSONObject associated with an index. Null is returned if + * there is no value at that index or if the value is not a JSONObject. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONObject value. + */ + public JSONObject optJSONObject(int index) { + return this.optJSONObject(index, null); + } + + /** + * Get the optional JSONObject associated with an index. The defaultValue is + * returned if there is no value at that index or if the value is not a + * JSONObject. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default. + * @return A JSONObject value. + */ + public JSONObject optJSONObject(int index, JSONObject defaultValue) { + Object object = this.opt(index); + return object instanceof JSONObject ? (JSONObject) object : defaultValue; + } + + /** + * Get the optional long value associated with an index. Zero is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public long optLong(int index) { + return this.optLong(index, 0); + } + + /** + * Get the optional long value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public long optLong(int index, long defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + return val.longValue(); + } + + /** + * Get the optional Long object associated with an index. Zero is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The object. + */ + public Long optLongObject(int index) { + return this.optLongObject(index, 0L); + } + + /** + * Get the optional Long object associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default object. + * @return The object. + */ + public Long optLongObject(int index, Long defaultValue) { + final Number val = this.optNumber(index, null); + if (val == null) { + return defaultValue; + } + return val.longValue(); + } + + /** + * Get an optional {@link Number} value associated with a key, or + * null if there is no such key or if the value is not a number. If + * the value is a string, an attempt will be made to evaluate it as a number + * ({@link BigDecimal}). This method would be used in cases where type coercion + * of the number value is unwanted. + * + * @param index The index must be between 0 and length() - 1. + * @return An object which is the value. + */ + public Number optNumber(int index) { + return this.optNumber(index, null); + } + + /** + * Get an optional {@link Number} value associated with a key, or the default if + * there is no such key or if the value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number + * ({@link BigDecimal}). This method would be used in cases where type coercion + * of the number value is unwanted. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Number optNumber(int index, Number defaultValue) { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number) { + return (Number) val; + } + + if (val instanceof String) { + try { + return JSONObject.stringToNumber((String) val); + } catch (Exception e) { + return defaultValue; + } + } + return defaultValue; + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer The JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(JSONPointer jsonPointer) { + try { + return jsonPointer.queryFrom(this); + } catch (JSONPointerException e) { + return null; + } + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer the string representation of the JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(String jsonPointer) { + return optQuery(new JSONPointer(jsonPointer)); + } + + /** + * Get the optional string value associated with an index. It returns an empty + * string if there is no value at that index. If the value is not a string and + * is not null, then it is converted to a string. + * + * @param index The index must be between 0 and length() - 1. + * @return A String value. + */ + public String optString(int index) { + return this.optString(index, ""); + } + + /** + * Get the optional string associated with an index. The defaultValue is + * returned if the key is not found. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return A String value. + */ + public String optString(int index, String defaultValue) { + Object object = this.opt(index); + return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); + } + + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public JSONArray put(boolean value) { + return this.put(value ? Boolean.TRUE : Boolean.FALSE); + } + + /** + * Put a value in the JSONArray, where the value will be a JSONArray which is + * produced from a Collection. + * + * @param value A Collection value. + * @return this. + * @throws JSONException If the value is non-finite number. + */ + public JSONArray put(Collection value) { + return this.put(new JSONArray(value)); + } + + /** + * Append a double value. This increases the array's length by one. + * + * @param value A double value. + * @return this. + * @throws JSONException if the value is not finite. + */ + public JSONArray put(double value) throws JSONException { + return this.put(Double.valueOf(value)); + } + + /** + * Append a float value. This increases the array's length by one. + * + * @param value A float value. + * @return this. + * @throws JSONException if the value is not finite. + */ + public JSONArray put(float value) throws JSONException { + return this.put(Float.valueOf(value)); + } + + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public JSONArray put(int value) { + return this.put(Integer.valueOf(value)); + } + + /** + * Put or replace a boolean value in the JSONArray. If the index is greater than + * the length of the JSONArray, then null elements will be added as necessary to + * pad it out. + * + * @param index The subscript. + * @param value A boolean value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, boolean value) throws JSONException { + return this.put(index, value ? Boolean.TRUE : Boolean.FALSE); + } + + /** + * Put a value in the JSONArray, where the value will be a JSONArray which is + * produced from a Collection. + * + * @param index The subscript. + * @param value A Collection value. + * @return this. + * @throws JSONException If the index is negative or if the value is non-finite. + */ + public JSONArray put(int index, Collection value) throws JSONException { + return this.put(index, new JSONArray(value)); + } + + /** + * Put or replace a double value. If the index is greater than the length of the + * JSONArray, then null elements will be added as necessary to pad it out. + * + * @param index The subscript. + * @param value A double value. + * @return this. + * @throws JSONException If the index is negative or if the value is non-finite. + */ + public JSONArray put(int index, double value) throws JSONException { + return this.put(index, Double.valueOf(value)); + } + + /** + * Put or replace a float value. If the index is greater than the length of the + * JSONArray, then null elements will be added as necessary to pad it out. + * + * @param index The subscript. + * @param value A float value. + * @return this. + * @throws JSONException If the index is negative or if the value is non-finite. + */ + public JSONArray put(int index, float value) throws JSONException { + return this.put(index, Float.valueOf(value)); + } + + /** + * Put or replace an int value. If the index is greater than the length of the + * JSONArray, then null elements will be added as necessary to pad it out. + * + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, int value) throws JSONException { + return this.put(index, Integer.valueOf(value)); + } + + /** + * Put or replace a long value. If the index is greater than the length of the + * JSONArray, then null elements will be added as necessary to pad it out. + * + * @param index The subscript. + * @param value A long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, long value) throws JSONException { + return this.put(index, Long.valueOf(value)); + } + + /** + * Put a value in the JSONArray, where the value will be a JSONObject that is + * produced from a Map. + * + * @param index The subscript. + * @param value The Map value. + * @return reference to self + * @throws JSONException If the index is negative or if the value is an + * invalid number. + * @throws NullPointerException If a key in the map is null + */ + public JSONArray put(int index, Map value) throws JSONException { + this.put(index, new JSONObject(value, new JSONParserConfiguration())); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a JSONObject that is + * produced from a Map. + * + * @param index The subscript + * @param value The Map value. + * @param jsonParserConfiguration Configuration object for the JSON parser + * @return reference to self + * @throws JSONException If the index is negative or if the value is an invalid + * number. + */ + public JSONArray put(int index, Map value, JSONParserConfiguration jsonParserConfiguration) + throws JSONException { + this.put(index, new JSONObject(value, jsonParserConfiguration)); + return this; + } + + /** + * Put or replace an object value in the JSONArray. If the index is greater than + * the length of the JSONArray, then null elements will be added as necessary to + * pad it out. + * + * @param index The subscript. + * @param value The value to put into the array. The value should be a Boolean, + * Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + * @throws JSONException If the index is negative or if the value is an invalid + * number. + */ + public JSONArray put(int index, Object value) throws JSONException { + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < this.length()) { + JSONObject.testValidity(value); + this.myArrayList.set(index, value); + return this; + } + if (index == this.length()) { + // simple append + return this.put(value); + } + // if we are inserting past the length, we want to grow the array all at once + // instead of incrementally. + this.myArrayList.ensureCapacity(index + 1); + while (index != this.length()) { + // we don't need to test validity of NULL objects + this.myArrayList.add(JSONObject.NULL); + } + return this.put(value); + } + + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public JSONArray put(long value) { + return this.put(Long.valueOf(value)); + } + + /** + * Put a value in the JSONArray, where the value will be a JSONObject which is + * produced from a Map. + * + * @param value A Map value. + * @return this. + * @throws JSONException If a value in the map is non-finite number. + * @throws NullPointerException If a key in the map is null + */ + public JSONArray put(Map value) { + return this.put(new JSONObject(value)); + } + + /** + * Append an object value. This increases the array's length by one. + * + * @param value An object value. The value should be a Boolean, Double, Integer, + * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL + * object. + * @return this. + * @throws JSONException If the value is non-finite number. + */ + public JSONArray put(Object value) { + JSONObject.testValidity(value); + this.myArrayList.add(value); + return this; + } + + /** + * Put a collection's elements in to the JSONArray. + * + * @param collection A Collection. + * @return this. + */ + public JSONArray putAll(Collection collection) { + this.addAll(collection, false); + return this; + } + + /** + * Put an Iterable's elements in to the JSONArray. + * + * @param iter An Iterable. + * @return this. + */ + public JSONArray putAll(Iterable iter) { + this.addAll(iter, false); + return this; + } + + /** + * Put a JSONArray's elements in to the JSONArray. + * + * @param array A JSONArray. + * @return this. + */ + public JSONArray putAll(JSONArray array) { + // directly copy the elements from the source array to this one + // as all wrapping should have been done already in the source. + this.myArrayList.addAll(array.myArrayList); + return this; + } + + /** + * Put an array's elements in to the JSONArray. + * + * @param array Array. If the parameter passed is null, or not an array or + * Iterable, an exception will be thrown. + * @return this. + * + * @throws JSONException If not an array, JSONArray, Iterable or if an + * value is non-finite number. + * @throws NullPointerException Thrown if the array parameter is null. + */ + public JSONArray putAll(Object array) throws JSONException { + this.addAll(array, false); + return this; + } + + /** + * Uses a user initialized JSONPointer and tries to match it to an item within + * this JSONArray. For example, given a JSONArray initialized with this + * document: + * + *
              +	 * [
              +	 *     {"b":"c"}
              +	 * ]
              +	 * 
              + * + * and this JSONPointer: + * + *
              +	 * "/0/b"
              +	 * 
              + * + * Then this method will return the String "c" A JSONPointerException may be + * thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(JSONPointer jsonPointer) { + return jsonPointer.queryFrom(this); + } + + /** + * Creates a JSONPointer using an initialization string and tries to match it to + * an item within this JSONArray. For example, given a JSONArray initialized + * with this document: + * + *
              +	 * [
              +	 *     {"b":"c"}
              +	 * ]
              +	 * 
              + * + * and this JSONPointer string: + * + *
              +	 * "/0/b"
              +	 * 
              + * + * Then this method will return the String "c" A JSONPointerException may be + * thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(String jsonPointer) { + return query(new JSONPointer(jsonPointer)); + } + + /** + * Remove an index and close the hole. + * + * @param index The index of the element to be removed. + * @return The value that was associated with the index, or null if there was no + * value. + */ + public Object remove(int index) { + return index >= 0 && index < this.length() ? this.myArrayList.remove(index) : null; + } + + /** + * Determine if two JSONArrays are similar. They must contain similar sequences. + * + * @param other The other JSONArray + * @return true if they are equal + */ + public boolean similar(Object other) { + if (!(other instanceof JSONArray)) { + return false; + } + int len = this.length(); + if (len != ((JSONArray) other).length()) { + return false; + } + for (int i = 0; i < len; i += 1) { + Object valueThis = this.myArrayList.get(i); + Object valueOther = ((JSONArray) other).myArrayList.get(i); + if (valueThis == valueOther) { + continue; + } + if (valueThis == null) { + return false; + } + if (valueThis instanceof JSONObject) { + if (!((JSONObject) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof Number && valueOther instanceof Number) { + if (!JSONObject.isNumberSimilar((Number) valueThis, (Number) valueOther)) { + return false; + } + } else if (valueThis instanceof JSONString && valueOther instanceof JSONString) { + if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) { + return false; + } + } else if (!valueThis.equals(valueOther)) { + return false; + } + } + return true; + } + + /** + * Produce a JSONObject by combining a JSONArray of names with the values of + * this JSONArray. + * + * @param names A JSONArray containing a list of key strings. These will be + * paired with the values. + * @return A JSONObject, or null if there are no names or if this JSONArray has + * no values. + * @throws JSONException If any of the names are null. + */ + public JSONObject toJSONObject(JSONArray names) throws JSONException { + if (names == null || names.isEmpty() || this.isEmpty()) { + return null; + } + JSONObject jo = new JSONObject(names.length()); + for (int i = 0; i < names.length(); i += 1) { + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } + + /** + * Returns a java.util.List containing all of the elements in this array. If an + * element in the array is a JSONArray or JSONObject it will also be converted + * to a List and a Map respectively. + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @return a java.util.List containing the elements of this array + */ + public List toList() { + List results = new ArrayList(this.myArrayList.size()); + for (Object element : this.myArrayList) { + if (element == null || JSONObject.NULL.equals(element)) { + results.add(null); + } else if (element instanceof JSONArray) { + results.add(((JSONArray) element).toList()); + } else if (element instanceof JSONObject) { + results.add(((JSONObject) element).toMap()); + } else { + results.add(element); + } + } + return results; + } + + /** + * Make a JSON text of this JSONArray. For compactness, no unnecessary + * whitespace is added. If it is not possible to produce a syntactically correct + * JSON text then null will be returned instead. This could occur if the array + * contains an invalid number. + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable representation of the array. + */ + @Override + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + /** + * Make a pretty-printed JSON text of this JSONArray. + * + *

              + * If + * + *

               {@code
              +	 * indentFactor > 0
              +	 * }
              + * + * and the {@link JSONArray} has only one element, then the array will be output + * on a single line: + * + *
              {@code [1]}
              + * + *

              + * If an array has 2 or more elements, then it will be output across multiple + * lines: + * + *

              {@code
              +	 * [
              +	 * 1,
              +	 * "value 2",
              +	 * 3
              +	 * ]
              +	 * }
              + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of indentation. + * @return a printable, displayable, transmittable representation of the object, + * beginning with [ (left bracket) and + * ending with ]  (right bracket). + * @throws JSONException if a called function fails + */ + @SuppressWarnings("resource") + public String toString(int indentFactor) throws JSONException { + StringWriter sw = new StringWriter(); + return this.write(sw, indentFactor, 0).toString(); + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param writer the writer object + * @return The writer. + * @throws JSONException if a called function fails + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. + * + *

              + * If + * + *

              {@code
              +	 * indentFactor > 0
              +	 * }
              + * + * and the {@link JSONArray} has only one element, then the array will be output + * on a single line: + * + *
              {@code [1]}
              + * + *

              + * If an array has 2 or more elements, then it will be output across multiple + * lines: + * + *

              {@code
              +	 * [
              +	 * 1,
              +	 * "value 2",
              +	 * 3
              +	 * ]
              +	 * }
              + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param writer Writes the serialized JSON + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indentation of the top level. + * @return The writer. + * @throws JSONException if a called function fails or unable to write + */ + @SuppressWarnings("resource") + public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { + try { + boolean needsComma = false; + int length = this.length(); + writer.write('['); + + if (length == 1) { + try { + JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONArray value at index: 0", e); + } + } else if (length != 0) { + final int newIndent = indent + indentFactor; + + for (int i = 0; i < length; i += 1) { + if (needsComma) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, newIndent); + try { + JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newIndent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONArray value at index: " + i, e); + } + needsComma = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, indent); + } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); + } + } } diff --git a/src/main/java/org/json/JSONException.java b/src/main/java/org/json/JSONException.java index 02c29f3f..4dcefbe5 100644 --- a/src/main/java/org/json/JSONException.java +++ b/src/main/java/org/json/JSONException.java @@ -11,39 +11,35 @@ Public Domain. * @version 2015-12-09 */ public class JSONException extends RuntimeException { - /** Serialization ID */ - private static final long serialVersionUID = 0; + /** Serialization ID */ + private static final long serialVersionUID = 0; - /** - * Constructs a JSONException with an explanatory message. - * - * @param message - * Detail about the reason for the exception. - */ - public JSONException(final String message) { - super(message); - } + /** + * Constructs a JSONException with an explanatory message. + * + * @param message Detail about the reason for the exception. + */ + public JSONException(final String message) { + super(message); + } - /** - * Constructs a JSONException with an explanatory message and cause. - * - * @param message - * Detail about the reason for the exception. - * @param cause - * The cause. - */ - public JSONException(final String message, final Throwable cause) { - super(message, cause); - } + /** + * Constructs a JSONException with an explanatory message and cause. + * + * @param message Detail about the reason for the exception. + * @param cause The cause. + */ + public JSONException(final String message, final Throwable cause) { + super(message, cause); + } - /** - * Constructs a new JSONException with the specified cause. - * - * @param cause - * The cause. - */ - public JSONException(final Throwable cause) { - super(cause.getMessage(), cause); - } + /** + * Constructs a new JSONException with the specified cause. + * + * @param cause The cause. + */ + public JSONException(final Throwable cause) { + super(cause.getMessage(), cause); + } } diff --git a/src/main/java/org/json/JSONObject.java b/src/main/java/org/json/JSONObject.java index 6494f934..270622c7 100644 --- a/src/main/java/org/json/JSONObject.java +++ b/src/main/java/org/json/JSONObject.java @@ -32,32 +32,29 @@ import java.util.regex.Pattern; * A JSONObject is an unordered collection of name/value pairs. Its external * form is a string wrapped in curly braces with colons between the names and * values, and commas between the values and names. The internal form is an - * object having get and opt methods for accessing - * the values by name, and put methods for adding or replacing - * values by name. The values can be any of these types: Boolean, + * object having get and opt methods for accessing the + * values by name, and put methods for adding or replacing values + * by name. The values can be any of these types: Boolean, * JSONArray, JSONObject, Number, - * String, or the JSONObject.NULL object. A - * JSONObject constructor can be used to convert an external form JSON text - * into an internal form whose values can be retrieved with the - * get and opt methods, or to convert values into a - * JSON text using the put and toString methods. A - * get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. + * String, or the JSONObject.NULL object. A JSONObject + * constructor can be used to convert an external form JSON text into an + * internal form whose values can be retrieved with the get and + * opt methods, or to convert values into a JSON text using the + * put and toString methods. A get method + * returns a value if one can be found, and throws an exception if one cannot be + * found. An opt method returns a default value instead of throwing + * an exception, and so is useful for obtaining optional values. *

              * The generic get() and opt() methods return an * object, which you can cast or query for type. There are also typed * get and opt methods that do type checking and type - * coercion for you. The opt methods differ from the get methods in that they - * do not throw. Instead, they return a specified value, such as null. + * coercion for you. The opt methods differ from the get methods in that they do + * not throw. Instead, they return a specified value, such as null. *

              - * The put methods add or replace values in an object. For - * example, + * The put methods add or replace values in an object. For example, * *

              - * myString = new JSONObject()
              - *         .put("JSON", "Hello, World!").toString();
              + * myString = new JSONObject().put("JSON", "Hello, World!").toString();
                * 
              * * produces the string {"JSON": "Hello, World"}. @@ -70,2914 +67,2768 @@ import java.util.regex.Pattern; * before the closing brace. *
            • Strings may be quoted with ' (single * quote).
            • - *
            • Strings do not need to be quoted at all if they do not begin with a - * quote or single quote, and if they do not contain leading or trailing - * spaces, and if they do not contain any of these characters: - * { } [ ] / \ : , # and if they do not look like numbers and - * if they are not the reserved words true, false, - * or null.
            • + *
            • Strings do not need to be quoted at all if they do not begin with a quote + * or single quote, and if they do not contain leading or trailing spaces, and + * if they do not contain any of these characters: + * { } [ ] / \ : , # and if they do not look like numbers and if + * they are not the reserved words true, false, or + * null.
            • * * * @author JSON.org * @version 2016-08-15 */ public class JSONObject { - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null { + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst + * Java's null is equivalent to the value that JavaScript calls undefined. + */ + private static final class Null { - /** - * There is only intended to be a single instance of the NULL object, - * so the clone method returns itself. - * - * @return NULL. - */ - @Override - protected final Object clone() { - return this; - } + /** + * There is only intended to be a single instance of the NULL object, so the + * clone method returns itself. + * + * @return NULL. + */ + @Override + protected final Object clone() { + return this; + } - /** - * A Null object is equal to the null value and to itself. - * - * @param object - * An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object or - * null. - */ - @Override - @SuppressWarnings("lgtm[java/unchecked-cast-in-equals]") - public boolean equals(Object object) { - return object == null || object == this; - } - /** - * A Null object is equal to the null value and to itself. - * - * @return always returns 0. - */ - @Override - public int hashCode() { - return 0; - } + /** + * A Null object is equal to the null value and to itself. + * + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object or null. + */ + @Override + @SuppressWarnings("lgtm[java/unchecked-cast-in-equals]") + public boolean equals(Object object) { + return object == null || object == this; + } - /** - * Get the "null" string value. - * - * @return The string "null". - */ - @Override - public String toString() { - return "null"; - } - } + /** + * A Null object is equal to the null value and to itself. + * + * @return always returns 0. + */ + @Override + public int hashCode() { + return 0; + } - /** - * Regular Expression Pattern that matches JSON Numbers. This is primarily used for - * output to guarantee that we are always writing valid JSON. - */ - static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"); + /** + * Get the "null" string value. + * + * @return The string "null". + */ + @Override + public String toString() { + return "null"; + } + } - /** - * The map where the JSONObject's properties are kept. - */ - private final Map map; + /** + * Regular Expression Pattern that matches JSON Numbers. This is primarily used + * for output to guarantee that we are always writing valid JSON. + */ + static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"); - /** - * Retrieves the type of the underlying Map in this class. - * - * @return The class object representing the type of the underlying Map. - */ - public Class getMapType() { - return map.getClass(); - } + /** + * It is sometimes more convenient and less ambiguous to have a + * NULL object than to use Java's null value. + * JSONObject.NULL.equals(null) returns true. + * JSONObject.NULL.toString() returns "null". + */ + public static final Object NULL = new Null(); - /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); + /** + * Produce a string from a double. The string "null" will be returned if the + * number is not finite. + * + * @param d A double. + * @return A String. + */ + public static String doubleToString(double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - // HashMap is used on purpose to ensure that elements are unordered by - // the specification. - // JSON tends to be a portable transfer format to allows the container - // implementations to rearrange their items for a faster element - // retrieval based on associative access. - // Therefore, an implementation mustn't rely on the order of the item. - this.map = new HashMap(); - } +// Shave off trailing zeros and decimal point, if possible. - /** - * Construct a JSONObject from a subset of another JSONObject. An array of - * strings is used to identify the keys that should be copied. Missing keys - * are ignored. - * - * @param jo - * A JSONObject. - * @param names - * An array of strings. - */ - public JSONObject(JSONObject jo, String ... names) { - this(names.length); - for (int i = 0; i < names.length; i += 1) { - try { - this.putOnce(names[i], jo.opt(names[i])); - } catch (Exception ignore) { - } - } - } + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } - /** - * Construct a JSONObject from a JSONTokener. - * - * @param x - * A JSONTokener object containing the source string. - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; + /** + * Searches the class hierarchy to see if the method or it's super + * implementations and interfaces has the annotation. + * + * @param type of the annotation + * + * @param m method to check + * @param annotationClass annotation to look for + * @return the {@link Annotation} if the annotation exists on the current method + * or one of its super class definitions + */ + private static A getAnnotation(final Method m, final Class annotationClass) { + // if we have invalid data the result is null + if (m == null || annotationClass == null) { + return null; + } - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - c = x.nextClean(); - switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - key = x.nextSimpleValue(c).toString(); - } + if (m.isAnnotationPresent(annotationClass)) { + return m.getAnnotation(annotationClass); + } - // The key is followed by ':'. + // if we've already reached the Object class, return null; + Class c = m.getDeclaringClass(); + if (c.getSuperclass() == null) { + return null; + } - c = x.nextClean(); - if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } + // check directly implemented interfaces for the method being checked + for (Class i : c.getInterfaces()) { + try { + Method im = i.getMethod(m.getName(), m.getParameterTypes()); + return getAnnotation(im, annotationClass); + } catch (final SecurityException ex) { + continue; + } catch (final NoSuchMethodException ex) { + continue; + } + } - // Use syntaxError(..) to include error location + // If the superclass is Object, no annotations will be found any more + if (c.getSuperclass().equals(Object.class)) + return null; - if (key != null) { - // Check if key exists - if (this.opt(key) != null) { - // key already exists - throw x.syntaxError("Duplicate key \"" + key + "\""); - } - // Only add value if non-null - Object value = x.nextValue(); - if (value!=null) { - this.put(key, value); - } - } + try { + return getAnnotation(c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), annotationClass); + } catch (final SecurityException ex) { + return null; + } catch (final NoSuchMethodException ex) { + return null; + } + } - // Pairs are separated by ','. + /** + * Searches the class hierarchy to see if the method or it's super + * implementations and interfaces has the annotation. Returns the depth of the + * annotation in the hierarchy. + * + * @param m method to check + * @param annotationClass annotation to look for + * @return Depth of the annotation or -1 if the annotation is not on the method. + */ + private static int getAnnotationDepth(final Method m, final Class annotationClass) { + // if we have invalid data the result is -1 + if (m == null || annotationClass == null) { + return -1; + } - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { - return; - } - if (x.end()) { - throw x.syntaxError("A JSONObject text must end with '}'"); - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } + if (m.isAnnotationPresent(annotationClass)) { + return 1; + } - /** - * Construct a JSONObject from a Map. - * - * @param m - * A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - * If a value in the map is non-finite number. - * @throws NullPointerException - * If a key in the map is null - */ - public JSONObject(Map m) { - this(m, 0, new JSONParserConfiguration()); - } + // if we've already reached the Object class, return -1; + Class c = m.getDeclaringClass(); + if (c.getSuperclass() == null) { + return -1; + } - /** - * Construct a JSONObject from a Map with custom json parse configurations. - * - * @param m - * A map object that can be used to initialize the contents of - * the JSONObject. - * @param jsonParserConfiguration - * Variable to pass parser custom configuration for json parsing. - */ - public JSONObject(Map m, JSONParserConfiguration jsonParserConfiguration) { - this(m, 0, jsonParserConfiguration); - } + // check directly implemented interfaces for the method being checked + for (Class i : c.getInterfaces()) { + try { + Method im = i.getMethod(m.getName(), m.getParameterTypes()); + int d = getAnnotationDepth(im, annotationClass); + if (d > 0) { + // since the annotation was on the interface, add 1 + return d + 1; + } + } catch (final SecurityException ex) { + continue; + } catch (final NoSuchMethodException ex) { + continue; + } + } - /** - * Construct a JSONObject from a map with recursion depth. - * - */ - private JSONObject(Map m, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - if (recursionDepth > jsonParserConfiguration.getMaxNestingDepth()) { - throw new JSONException("JSONObject has reached recursion depth limit of " + jsonParserConfiguration.getMaxNestingDepth()); - } - if (m == null) { - this.map = new HashMap(); - } else { - this.map = new HashMap(m.size()); - for (final Entry e : m.entrySet()) { - if(e.getKey() == null) { - throw new NullPointerException("Null key."); - } - final Object value = e.getValue(); - if (value != null) { - testValidity(value); - this.map.put(String.valueOf(e.getKey()), wrap(value, recursionDepth + 1, jsonParserConfiguration)); - } - } - } - } + // If the superclass is Object, no annotations will be found any more + if (c.getSuperclass().equals(Object.class)) + return -1; - /** - * Construct a JSONObject from an Object using bean getters. It reflects on - * all of the public methods of the object. For each of the methods with no - * parameters and a name starting with "get" or - * "is" followed by an uppercase letter, the method is invoked, - * and a key and the value returned from the getter method are put into the - * new JSONObject. - *

              - * The key is formed by removing the "get" or "is" - * prefix. If the second remaining character is not upper case, then the - * first character is converted to lower case. - *

              - * Methods that are static, return void, - * have parameters, or are "bridge" methods, are ignored. - *

              - * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is - * "Larry Fine", then the JSONObject will contain - * "name": "Larry Fine". - *

              - * The {@link JSONPropertyName} annotation can be used on a bean getter to - * override key name used in the JSONObject. For example, using the object - * above with the getName method, if we annotated it with: - *

              -     * @JSONPropertyName("FullName")
              -     * public String getName() { return this.name; }
              -     * 
              - * The resulting JSON object would contain "FullName": "Larry Fine" - *

              - * Similarly, the {@link JSONPropertyName} annotation can be used on non- - * get and is methods. We can also override key - * name used in the JSONObject as seen below even though the field would normally - * be ignored: - *

              -     * @JSONPropertyName("FullName")
              -     * public String fullName() { return this.name; }
              -     * 
              - * The resulting JSON object would contain "FullName": "Larry Fine" - *

              - * The {@link JSONPropertyIgnore} annotation can be used to force the bean property - * to not be serialized into JSON. If both {@link JSONPropertyIgnore} and - * {@link JSONPropertyName} are defined on the same method, a depth comparison is - * performed and the one closest to the concrete class being serialized is used. - * If both annotations are at the same level, then the {@link JSONPropertyIgnore} - * annotation takes precedent and the field is not serialized. - * For example, the following declaration would prevent the getName - * method from being serialized: - *

              -     * @JSONPropertyName("FullName")
              -     * @JSONPropertyIgnore
              -     * public String getName() { return this.name; }
              -     * 
              - * - * @param bean - * An object that has getter methods that should be used to make - * a JSONObject. - * @throws JSONException - * If a getter returned a non-finite number. - */ - public JSONObject(Object bean) { - this(); - this.populateMap(bean); - } + try { + int d = getAnnotationDepth(c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), + annotationClass); + if (d > 0) { + // since the annotation was on the superclass, add 1 + return d + 1; + } + return -1; + } catch (final SecurityException ex) { + return -1; + } catch (final NoSuchMethodException ex) { + return -1; + } + } - private JSONObject(Object bean, Set objectsRecord) { - this(); - this.populateMap(bean, objectsRecord); - } + private static String getKeyNameFromMethod(Method method) { + final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class); + if (ignoreDepth > 0) { + final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class); + if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) { + // the hierarchy asked to ignore, and the nearest name override + // was higher or non-existent + return null; + } + } + JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class); + if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) { + return annotation.value(); + } + String key; + final String name = method.getName(); + if (name.startsWith("get") && name.length() > 3) { + key = name.substring(3); + } else if (name.startsWith("is") && name.length() > 2) { + key = name.substring(2); + } else { + return null; + } + // if the first letter in the key is not uppercase, then skip. + // This is to maintain backwards compatibility before PR406 + // (https://github.com/stleary/JSON-java/pull/406/) + if (key.length() == 0 || Character.isLowerCase(key.charAt(0))) { + return null; + } + if (key.length() == 1) { + key = key.toLowerCase(Locale.ROOT); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1); + } + return key; + } - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings from - * the names array, and the values will be the field values associated with - * those keys in the object. If a key is not found or not visible, then it - * will not be copied into the new JSONObject. - * - * @param object - * An object that has fields that should be used to make a - * JSONObject. - * @param names - * An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String ... names) { - this(names.length); - Class c = object.getClass(); - for (int i = 0; i < names.length; i += 1) { - String name = names[i]; - try { - this.putOpt(name, c.getField(name).get(object)); - } catch (Exception ignore) { - } - } - } + /** + * Get an array of field names from a JSONObject. + * + * @param jo JSON object + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(JSONObject jo) { + if (jo.isEmpty()) { + return null; + } + return jo.keySet().toArray(new String[jo.length()]); + } - /** - * Construct a JSONObject from a source JSON text string. This is the most - * commonly used JSONObject constructor. - * - * @param source - * A string beginning with { (left - * brace) and ending with } - *  (right brace). - * @exception JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } + /** + * Get an array of public field names from an Object. + * + * @param object object to read + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(Object object) { + if (object == null) { + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0) { + return null; + } + String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } - /** - * Construct a JSONObject from a ResourceBundle. - * - * @param baseName - * The ResourceBundle base name. - * @param locale - * The Locale to load the ResourceBundle for. - * @throws JSONException - * If any JSONExceptions are detected. - */ - public JSONObject(String baseName, Locale locale) throws JSONException { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, - Thread.currentThread().getContextClassLoader()); + static final void indent(Writer writer, int indent) throws IOException { + for (int i = 0; i < indent; i += 1) { + writer.write(' '); + } + } + + /** + * Tests if the value should be tried as a decimal. It makes no test if there + * are actual digits. + * + * @param val value to test + * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false + * otherwise. + */ + protected static boolean isDecimalNotation(final String val) { + return val.indexOf('.') > -1 || val.indexOf('e') > -1 || val.indexOf('E') > -1 || "-0".equals(val); + } + + /** + * Compares two numbers to see if they are similar. + * + * If either of the numbers are Double or Float instances, then they are checked + * to have a finite value. If either value is not finite (NaN or + * ±infinity), then this function will always return false. If both numbers + * are finite, they are first checked to be the same type and implement + * {@link Comparable}. If they do, then the actual + * {@link Comparable#compareTo(Object)} is called. If they are not the same + * type, or don't implement Comparable, then they are converted to + * {@link BigDecimal}s. Finally the BigDecimal values are compared using + * {@link BigDecimal#compareTo(BigDecimal)}. + * + * @param l the Left value to compare. Can not be null. + * @param r the right value to compare. Can not be null. + * @return true if the numbers are similar, false otherwise. + */ + static boolean isNumberSimilar(Number l, Number r) { + if (!numberIsFinite(l) || !numberIsFinite(r)) { + // non-finite numbers are never similar + return false; + } + + // if the classes are the same and implement Comparable + // then use the built in compare first. + if (l.getClass().equals(r.getClass()) && l instanceof Comparable) { + @SuppressWarnings({ "rawtypes", "unchecked" }) + int compareTo = ((Comparable) l).compareTo(r); + return compareTo == 0; + } + + // BigDecimal should be able to handle all of our number types that we support + // through + // documentation. Convert to BigDecimal first, then use the Compare method to + // decide equality. + final BigDecimal lBigDecimal = objectToBigDecimal(l, null, false); + final BigDecimal rBigDecimal = objectToBigDecimal(r, null, false); + if (lBigDecimal == null || rBigDecimal == null) { + return false; + } + return lBigDecimal.compareTo(rBigDecimal) == 0; + } + + private static boolean isValidMethodName(String name) { + return !"getClass".equals(name) && !"getDeclaringClass".equals(name); + } + + private static boolean numberIsFinite(Number n) { + if (n instanceof Double && (((Double) n).isInfinite() || ((Double) n).isNaN())) { + return false; + } else if (n instanceof Float && (((Float) n).isInfinite() || ((Float) n).isNaN())) { + return false; + } + return true; + } + + /** + * Produce a string from a Number. + * + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + public static String numberToString(Number number) throws JSONException { + if (number == null) { + throw new JSONException("Null pointer"); + } + testValidity(number); + + // Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * @param val value to convert + * @param defaultValue default value to return is the conversion doesn't work or + * is null. + * @return BigDecimal conversion of the original value, or the defaultValue if + * unable to convert. + */ + static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) { + return objectToBigDecimal(val, defaultValue, true); + } + + /** + * @param val value to convert + * @param defaultValue default value to return is the conversion doesn't work or + * is null. + * @param exact When true, then {@link Double} and + * {@link Float} values will be converted exactly. When + * false, they will be converted to + * {@link String} values before converting to + * {@link BigDecimal}. + * @return BigDecimal conversion of the original value, or the defaultValue if + * unable to convert. + */ + static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue, boolean exact) { + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigDecimal) { + return (BigDecimal) val; + } + if (val instanceof BigInteger) { + return new BigDecimal((BigInteger) val); + } + if (val instanceof Double || val instanceof Float) { + if (!numberIsFinite((Number) val)) { + return defaultValue; + } + if (exact) { + return new BigDecimal(((Number) val).doubleValue()); + } + // use the string constructor so that we maintain "nice" values for doubles and + // floats + // the double constructor will translate doubles to "exact" values instead of + // the likely + // intended representation + return new BigDecimal(val.toString()); + } + if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte) { + return new BigDecimal(((Number) val).longValue()); + } + // don't check if it's a string in case of unchecked Number subclasses + try { + return new BigDecimal(val.toString()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * @param val value to convert + * @param defaultValue default value to return is the conversion doesn't work or + * is null. + * @return BigInteger conversion of the original value, or the defaultValue if + * unable to convert. + */ + static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigInteger) { + return (BigInteger) val; + } + if (val instanceof BigDecimal) { + return ((BigDecimal) val).toBigInteger(); + } + if (val instanceof Double || val instanceof Float) { + if (!numberIsFinite((Number) val)) { + return defaultValue; + } + return new BigDecimal(((Number) val).doubleValue()).toBigInteger(); + } + if (val instanceof Long || val instanceof Integer || val instanceof Short || val instanceof Byte) { + return BigInteger.valueOf(((Number) val).longValue()); + } + // don't check if it's a string in case of unchecked Number subclasses + try { + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + final String valStr = val.toString(); + if (isDecimalNotation(valStr)) { + return new BigDecimal(valStr).toBigInteger(); + } + return new BigInteger(valStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Produce a string in double quotes with backslash sequences in all the right + * places. A backslash will be inserted within </, producing <\/, allowing + * JSON text to be delivered in HTML. In JSON text, a string cannot contain a + * control character or an unescaped quote or backslash. + * + * @param string A String + * @return A String correctly formatted for insertion in a JSON text. + */ + @SuppressWarnings("resource") + public static String quote(String string) { + StringWriter sw = new StringWriter(); + try { + return quote(string, sw).toString(); + } catch (IOException ignored) { + // will never happen - we are writing to a string writer + return ""; + } + } + + /** + * Quotes a string and appends the result to a given Writer. + * + * @param string The input string to be quoted. + * @param w The Writer to which the quoted string will be appended. + * @return The same Writer instance after appending the quoted string. + * @throws IOException If an I/O error occurs while writing to the Writer. + */ + public static Writer quote(String string, Writer w) throws IOException { + if (string == null || string.isEmpty()) { + w.write("\"\""); + return w; + } + + char b; + char c = 0; + String hhhh; + int i; + int len = string.length(); + + w.write('"'); + for (i = 0; i < len; i += 1) { + b = c; + c = string.charAt(i); + switch (c) { + case '\\': + case '"': + w.write('\\'); + w.write(c); + break; + case '/': + if (b == '<') { + w.write('\\'); + } + w.write(c); + break; + case '\b': + w.write("\\b"); + break; + case '\t': + w.write("\\t"); + break; + case '\n': + w.write("\\n"); + break; + case '\f': + w.write("\\f"); + break; + case '\r': + w.write("\\r"); + break; + default: + if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + w.write("\\u"); + hhhh = Integer.toHexString(c); + w.write("0000", 0, 4 - hhhh.length()); + w.write(hhhh); + } else { + w.write(c); + } + } + } + w.write('"'); + return w; + } + + /** + * Create a new JSONException in a common format for recursive object + * definition. + * + * @param key name of the key + * @return JSONException that can be thrown. + */ + private static JSONException recursivelyDefinedObjectException(String key) { + return new JSONException("JavaBean object contains recursively defined member variable of key " + quote(key)); + } + + /** + * For a prospective number, remove the leading zeros + * + * @param value prospective number + * @return number without leading zeros + */ + private static String removeLeadingZerosOfNumber(String value) { + if (value.equals("-")) { + return value; + } + boolean negativeFirstChar = (value.charAt(0) == '-'); + int counter = negativeFirstChar ? 1 : 0; + while (counter < value.length()) { + if (value.charAt(counter) != '0') { + if (negativeFirstChar) { + return "-".concat(value.substring(counter)); + } + return value.substring(counter); + } + ++counter; + } + if (negativeFirstChar) { + return "-0"; + } + return "0"; + } + + /** + * Converts a string to a number using the narrowest possible type. Possible + * returns for this function are BigDecimal, Double, BigInteger, Long, and + * Integer. When a Double is returned, it should always be a valid Double and + * not NaN or +-infinity. + * + * @param val value to convert + * @return Number representation of the value. + * @throws NumberFormatException thrown if the value is not a valid number. A + * public caller should catch this and wrap it in + * a {@link JSONException} if applicable. + */ + protected static Number stringToNumber(final String val) throws NumberFormatException { + char initial = val.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + // decimal representation + if (isDecimalNotation(val)) { + // Use a BigDecimal all the time so we keep the original + // representation. BigDecimal doesn't support -0.0, ensure we + // keep that by forcing a decimal. + try { + BigDecimal bd = new BigDecimal(val); + if (initial == '-' && BigDecimal.ZERO.compareTo(bd) == 0) { + return Double.valueOf(-0.0); + } + return bd; + } catch (NumberFormatException retryAsDouble) { + // this is to support "Hex Floats" like this: 0x1.0P-1074 + try { + Double d = Double.valueOf(val); + if (d.isNaN() || d.isInfinite()) { + throw new NumberFormatException("val [" + val + "] is not a valid number."); + } + return d; + } catch (NumberFormatException ignore) { + throw new NumberFormatException("val [" + val + "] is not a valid number."); + } + } + } + // block items like 00 01 etc. Java number parsers treat these as Octal. + if (initial == '0' && val.length() > 1) { + char at1 = val.charAt(1); + if (at1 >= '0' && at1 <= '9') { + throw new NumberFormatException("val [" + val + "] is not a valid number."); + } + } else if (initial == '-' && val.length() > 2) { + char at1 = val.charAt(1); + char at2 = val.charAt(2); + if (at1 == '0' && at2 >= '0' && at2 <= '9') { + throw new NumberFormatException("val [" + val + "] is not a valid number."); + } + } + // integer representation. + // This will narrow any values to the smallest reasonable Object representation + // (Integer, Long, or BigInteger) + + // BigInteger down conversion: We use a similar bitLength compare as + // BigInteger#intValueExact uses. Increases GC, but objects hold + // only what they need. i.e. Less runtime overhead if the value is + // long lived. + BigInteger bi = new BigInteger(val); + if (bi.bitLength() <= 31) { + return Integer.valueOf(bi.intValue()); + } + if (bi.bitLength() <= 63) { + return Long.valueOf(bi.longValue()); + } + return bi; + } + throw new NumberFormatException("val [" + val + "] is not a valid number."); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string can't + * be converted, return the string. + * + * @param string A String. can not be null. + * @return A simple JSON value. + * @throws NullPointerException Thrown if the string is null. + */ + // Changes to this method must be copied to the corresponding method in + // the XML class to keep full support for Android + public static Object stringToValue(String string) { + if ("".equals(string)) { + return string; + } + + // check JSON key words true/false/null + if ("true".equalsIgnoreCase(string)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(string)) { + return Boolean.FALSE; + } + if ("null".equalsIgnoreCase(string)) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. If a number cannot be produced, + * then the value will just be a string. + */ + + char initial = string.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + try { + return stringToNumber(string); + } catch (Exception ignore) { + } + } + return string; + } + + /** + * Throw an exception if the object is a NaN or infinite number. + * + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + public static void testValidity(Object o) throws JSONException { + if (o instanceof Number && !numberIsFinite((Number) o)) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } + + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce the + * JSON text. The method is required to produce a strictly conforming text. If + * the object does not contain a toJSONString method (which is the most common + * case), then a text will be produced by other means. If the value is an array + * or Collection, then a JSONArray will be made from it and its toJSONString + * method will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the value's + * toString method will be called, and the result will be quoted. + * + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @return a printable, displayable, transmittable representation of the object, + * beginning with { (left brace) and + * ending with } (right brace). + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + // moves the implementation to JSONWriter as: + // 1. It makes more sense to be part of the writer class + // 2. For Android support this method is not available. By implementing it in + // the Writer + // Android users can use the writer with the built in Android JSONObject + // implementation. + return JSONWriter.valueToString(value); + } + + /** + * Wrap an object, if necessary. If the object is null, return the + * NULL object. If it is an array or collection, wrap it in a JSONArray. If it + * is a map, wrap it in a JSONObject. If it is a standard property (Double, + * String, et al) then it is already wrapped. Otherwise, if it comes from one of + * the java packages, turn it into a string. And if it doesn't, try to wrap it + * in a JSONObject. If the wrapping fails, then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + public static Object wrap(Object object) { + return wrap(object, null); + } + + /** + * Wrap an object, if necessary. If the object is null, return the + * NULL object. If it is an array or collection, wrap it in a JSONArray. If it + * is a map, wrap it in a JSONObject. If it is a standard property (Double, + * String, et al) then it is already wrapped. Otherwise, if it comes from one of + * the java packages, turn it into a string. And if it doesn't, try to wrap it + * in a JSONObject. If the wrapping fails, then null is returned. + * + * @param object The object to wrap + * @param recursionDepth Variable for tracking the count of nested + * object creations. + * @param jsonParserConfiguration Variable to pass parser custom configuration + * for json parsing. + * @return The wrapped value + */ + static Object wrap(Object object, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { + return wrap(object, null, recursionDepth, jsonParserConfiguration); + } + + private static Object wrap(Object object, Set objectsRecord) { + return wrap(object, objectsRecord, 0, new JSONParserConfiguration()); + } + + private static Object wrap(Object object, Set objectsRecord, int recursionDepth, + JSONParserConfiguration jsonParserConfiguration) { + try { + if (NULL.equals(object)) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) + || object instanceof JSONString || object instanceof Byte || object instanceof Character + || object instanceof Short || object instanceof Integer || object instanceof Long + || object instanceof Boolean || object instanceof Float || object instanceof Double + || object instanceof String || object instanceof BigInteger || object instanceof BigDecimal + || object instanceof Enum) { + return object; + } + + if (object instanceof Collection) { + Collection coll = (Collection) object; + return new JSONArray(coll, recursionDepth, jsonParserConfiguration); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + Map map = (Map) object; + return new JSONObject(map, recursionDepth, jsonParserConfiguration); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") + || object.getClass().getClassLoader() == null) { + return object.toString(); + } + if (objectsRecord != null) { + return new JSONObject(object, objectsRecord); + } + return new JSONObject(object); + } catch (JSONException exception) { + throw exception; + } catch (Exception exception) { + return null; + } + } + + @SuppressWarnings("resource") + static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) + throws JSONException, IOException { + if (value == null || value.equals(null)) { + writer.write("null"); + } else if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + } else if (value instanceof Number) { + // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary + final String numberAsString = numberToString((Number) value); + if (NUMBER_PATTERN.matcher(numberAsString).matches()) { + writer.write(numberAsString); + } else { + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + quote(numberAsString, writer); + } + } else if (value instanceof Boolean) { + writer.write(value.toString()); + } else if (value instanceof Enum) { + writer.write(quote(((Enum) value).name())); + } else if (value instanceof JSONObject) { + ((JSONObject) value).write(writer, indentFactor, indent); + } else if (value instanceof JSONArray) { + ((JSONArray) value).write(writer, indentFactor, indent); + } else if (value instanceof Map) { + Map map = (Map) value; + new JSONObject(map).write(writer, indentFactor, indent); + } else if (value instanceof Collection) { + Collection coll = (Collection) value; + new JSONArray(coll).write(writer, indentFactor, indent); + } else if (value.getClass().isArray()) { + new JSONArray(value).write(writer, indentFactor, indent); + } else { + quote(value.toString(), writer); + } + return writer; + } + + /** + * Create a new JSONException in a common format for incorrect conversions. + * + * @param key name of the key + * @param valueType the type of value being coerced to + * @param cause optional cause of the coercion failure + * @return JSONException that can be thrown. + */ + private static JSONException wrongValueFormatException(String key, String valueType, Object value, + Throwable cause) { + if (value == null) { + + return new JSONException("JSONObject[" + quote(key) + "] is not a " + valueType + " (null).", cause); + } + // don't try to toString collections or known object types that could be large. + if (value instanceof Map || value instanceof Iterable || value instanceof JSONObject) { + return new JSONException( + "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + ").", cause); + } + return new JSONException( + "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ").", + cause); + } + + /** + * The map where the JSONObject's properties are kept. + */ + private final Map map; + + /** + * Construct an empty JSONObject. + */ + public JSONObject() { + // HashMap is used on purpose to ensure that elements are unordered by + // the specification. + // JSON tends to be a portable transfer format to allows the container + // implementations to rearrange their items for a faster element + // retrieval based on associative access. + // Therefore, an implementation mustn't rely on the order of the item. + this.map = new HashMap(); + } + + /** + * Constructor to specify an initial capacity of the internal map. Useful for + * library internal calls where we know, or at least can best guess, how big + * this JSONObject will be. + * + * @param initialCapacity initial capacity of the internal map. + */ + protected JSONObject(int initialCapacity) { + this.map = new HashMap(initialCapacity); + } + + /** + * Construct a JSONObject from a subset of another JSONObject. An array of + * strings is used to identify the keys that should be copied. Missing keys are + * ignored. + * + * @param jo A JSONObject. + * @param names An array of strings. + */ + public JSONObject(JSONObject jo, String... names) { + this(names.length); + for (int i = 0; i < names.length; i += 1) { + try { + this.putOnce(names[i], jo.opt(names[i])); + } catch (Exception ignore) { + } + } + } + + /** + * Construct a JSONObject from a JSONTokener. + * + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. + */ + public JSONObject(JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (;;) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + key = x.nextSimpleValue(c).toString(); + } + + // The key is followed by ':'. + + c = x.nextClean(); + if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + + // Use syntaxError(..) to include error location + + if (key != null) { + // Check if key exists + if (this.opt(key) != null) { + // key already exists + throw x.syntaxError("Duplicate key \"" + key + "\""); + } + // Only add value if non-null + Object value = x.nextValue(); + if (value != null) { + this.put(key, value); + } + } + + // Pairs are separated by ','. + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + if (x.end()) { + throw x.syntaxError("A JSONObject text must end with '}'"); + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + /** + * Construct a JSONObject from a Map. + * + * @param m A map object that can be used to initialize the contents of the + * JSONObject. + * @throws JSONException If a value in the map is non-finite number. + * @throws NullPointerException If a key in the map is null + */ + public JSONObject(Map m) { + this(m, 0, new JSONParserConfiguration()); + } + + /** + * Construct a JSONObject from a map with recursion depth. + * + */ + private JSONObject(Map m, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { + if (recursionDepth > jsonParserConfiguration.getMaxNestingDepth()) { + throw new JSONException( + "JSONObject has reached recursion depth limit of " + jsonParserConfiguration.getMaxNestingDepth()); + } + if (m == null) { + this.map = new HashMap(); + } else { + this.map = new HashMap(m.size()); + for (final Entry e : m.entrySet()) { + if (e.getKey() == null) { + throw new NullPointerException("Null key."); + } + final Object value = e.getValue(); + if (value != null) { + testValidity(value); + this.map.put(String.valueOf(e.getKey()), wrap(value, recursionDepth + 1, jsonParserConfiguration)); + } + } + } + } + + /** + * Construct a JSONObject from a Map with custom json parse configurations. + * + * @param m A map object that can be used to initialize + * the contents of the JSONObject. + * @param jsonParserConfiguration Variable to pass parser custom configuration + * for json parsing. + */ + public JSONObject(Map m, JSONParserConfiguration jsonParserConfiguration) { + this(m, 0, jsonParserConfiguration); + } + + /** + * Construct a JSONObject from an Object using bean getters. It reflects on all + * of the public methods of the object. For each of the methods with no + * parameters and a name starting with "get" or "is" + * followed by an uppercase letter, the method is invoked, and a key and the + * value returned from the getter method are put into the new JSONObject. + *

              + * The key is formed by removing the "get" or "is" + * prefix. If the second remaining character is not upper case, then the first + * character is converted to lower case. + *

              + * Methods that are static, return void, have + * parameters, or are "bridge" methods, are ignored. + *

              + * For example, if an object has a method named "getName", and if + * the result of calling object.getName() is + * "Larry Fine", then the JSONObject will contain + * "name": "Larry Fine". + *

              + * The {@link JSONPropertyName} annotation can be used on a bean getter to + * override key name used in the JSONObject. For example, using the object above + * with the getName method, if we annotated it with: + * + *

              +	 * @JSONPropertyName("FullName")
              +	 * public String getName() {
              +	 * 	return this.name;
              +	 * }
              +	 * 
              + * + * The resulting JSON object would contain "FullName": "Larry Fine" + *

              + * Similarly, the {@link JSONPropertyName} annotation can be used on non- + * get and is methods. We can also override key name + * used in the JSONObject as seen below even though the field would normally be + * ignored: + * + *

              +	 * @JSONPropertyName("FullName")
              +	 * public String fullName() {
              +	 * 	return this.name;
              +	 * }
              +	 * 
              + * + * The resulting JSON object would contain "FullName": "Larry Fine" + *

              + * The {@link JSONPropertyIgnore} annotation can be used to force the bean + * property to not be serialized into JSON. If both {@link JSONPropertyIgnore} + * and {@link JSONPropertyName} are defined on the same method, a depth + * comparison is performed and the one closest to the concrete class being + * serialized is used. If both annotations are at the same level, then the + * {@link JSONPropertyIgnore} annotation takes precedent and the field is not + * serialized. For example, the following declaration would prevent the + * getName method from being serialized: + * + *

              +	 * @JSONPropertyName("FullName")
              +	 * @JSONPropertyIgnore
              +	 * public String getName() {
              +	 * 	return this.name;
              +	 * }
              +	 * 
              + * + * @param bean An object that has getter methods that should be used to make a + * JSONObject. + * @throws JSONException If a getter returned a non-finite number. + */ + public JSONObject(Object bean) { + this(); + this.populateMap(bean); + } + + private JSONObject(Object bean, Set objectsRecord) { + this(); + this.populateMap(bean, objectsRecord); + } + + /** + * Construct a JSONObject from an Object, using reflection to find the public + * members. The resulting JSONObject's keys will be the strings from the names + * array, and the values will be the field values associated with those keys in + * the object. If a key is not found or not visible, then it will not be copied + * into the new JSONObject. + * + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. + */ + public JSONObject(Object object, String... names) { + this(names.length); + Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + String name = names[i]; + try { + this.putOpt(name, c.getField(name).get(object)); + } catch (Exception ignore) { + } + } + } + + /** + * Construct a JSONObject from a source JSON text string. This is the most + * commonly used JSONObject constructor. + * + * @param source A string beginning with { (left + * brace) and ending with } + *  (right brace). + * @exception JSONException If there is a syntax error in the source string or a + * duplicated key. + */ + public JSONObject(String source) throws JSONException { + this(new JSONTokener(source)); + } + + /** + * Construct a JSONObject from a ResourceBundle. + * + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. + */ + public JSONObject(String baseName, Locale locale) throws JSONException { + this(); + ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, + Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. - Enumeration keys = bundle.getKeys(); - while (keys.hasMoreElements()) { - Object key = keys.nextElement(); - if (key != null) { + Enumeration keys = bundle.getKeys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (key != null) { // Go through the path, ensuring that there is a nested JSONObject for each // segment except the last. Add the value using the last segment's name into // the deepest nested JSONObject. - String[] path = ((String) key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for (int i = 0; i < last; i += 1) { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if (nextTarget == null) { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String) key)); - } - } - } - - /** - * Constructor to specify an initial capacity of the internal map. Useful for library - * internal calls where we know, or at least can best guess, how big this JSONObject - * will be. - * - * @param initialCapacity initial capacity of the internal map. - */ - protected JSONObject(int initialCapacity){ - this.map = new HashMap(initialCapacity); - } - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a JSONArray - * is stored under the key to hold all of the accumulated values. If there - * is already a JSONArray, then the new value is appended to it. In - * contrast, the put method replaces the previous value. - * - * If only one value is accumulated that is not a JSONArray, then the result - * will be the same as using put. But if multiple values are accumulated, - * then the result will be like append. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject accumulate(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, - value instanceof JSONArray ? new JSONArray().put(value) - : value); - } else if (object instanceof JSONArray) { - ((JSONArray) object).put(value); - } else { - this.put(key, new JSONArray().put(object).put(value)); - } - return this; - } - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is non-finite number or if the current value associated with - * the key is not a JSONArray. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { - this.put(key, ((JSONArray) object).put(value)); - } else { - throw wrongValueFormatException(key, "JSONArray", null, null); - } - return this; - } - - /** - * Produce a string from a double. The string "null" will be returned if the - * number is not finite. - * - * @param d - * A double. - * @return A String. - */ - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - -// Shave off trailing zeros and decimal point, if possible. - - String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 - && string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get the value object associated with a key. - * - * @param key - * A key string. - * @return The object associated with the key. - * @throws JSONException - * if the key is not found. - */ - public Object get(String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } - return object; - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, String key) throws JSONException { - E val = optEnum(clazz, key); - if(val==null) { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), opt(key), null); - } - return val; - } - - /** - * Get the boolean value associated with a key. - * - * @param key - * A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or - * "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - if (object.equals(Boolean.FALSE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) - || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { - return true; - } - throw wrongValueFormatException(key, "Boolean", object, null); - } - - /** - * Get the BigInteger value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot - * be converted to BigInteger. - */ - public BigInteger getBigInteger(String key) throws JSONException { - Object object = this.get(key); - BigInteger ret = objectToBigInteger(object, null); - if (ret != null) { - return ret; - } - throw wrongValueFormatException(key, "BigInteger", object, null); - } - - /** - * Get the BigDecimal value associated with a key. If the value is float or - * double, the {@link BigDecimal#BigDecimal(double)} constructor will - * be used. See notes on the constructor for conversion issues that may - * arise. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value - * cannot be converted to BigDecimal. - */ - public BigDecimal getBigDecimal(String key) throws JSONException { - Object object = this.get(key); - BigDecimal ret = objectToBigDecimal(object, null); - if (ret != null) { - return ret; - } - throw wrongValueFormatException(key, "BigDecimal", object, null); - } - - /** - * Get the double value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).doubleValue(); - } - try { - return Double.parseDouble(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "double", object, e); - } - } - - /** - * Get the float value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public float getFloat(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).floatValue(); - } - try { - return Float.parseFloat(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "float", object, e); - } - } - - /** - * Get the Number value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public Number getNumber(String key) throws JSONException { - Object object = this.get(key); - try { - if (object instanceof Number) { - return (Number)object; - } - return stringToNumber(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "number", object, e); - } - } - - /** - * Get the int value associated with a key. - * - * @param key - * A key string. - * @return The integer value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an integer. - */ - public int getInt(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).intValue(); - } - try { - return Integer.parseInt(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "int", object, e); - } - } - - /** - * Get the JSONArray value associated with a key. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw wrongValueFormatException(key, "JSONArray", object, null); - } - - /** - * Get the JSONObject value associated with a key. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw wrongValueFormatException(key, "JSONObject", object, null); - } - - /** - * Get the long value associated with a key. - * - * @param key - * A key string. - * @return The long value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to a long. - */ - public long getLong(String key) throws JSONException { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).longValue(); - } - try { - return Long.parseLong(object.toString()); - } catch (Exception e) { - throw wrongValueFormatException(key, "long", object, e); - } - } - - /** - * Get an array of field names from a JSONObject. - * - * @param jo - * JSON object - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) { - if (jo.isEmpty()) { - return null; - } - return jo.keySet().toArray(new String[jo.length()]); - } - - /** - * Get an array of public field names from an Object. - * - * @param object - * object to read - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - /** - * Get the string associated with a key. - * - * @param key - * A key string. - * @return A string which is the value. - * @throws JSONException - * if there is no string value for the key. - */ - public String getString(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof String) { - return (String) object; - } - throw wrongValueFormatException(key, "string", object, null); - } - - /** - * Determine if the JSONObject contains a specific key. - * - * @param key - * A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1 (Integer). If there is such a property, and if it is - * an Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it. - * No overflow bounds checking is performed, so callers should initialize the key - * prior to this call with an appropriate type that can handle the maximum expected - * value. - * - * @param key - * A key string. - * @return this. - * @throws JSONException - * If there is already a property with this name that is not an - * Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); - if (value == null) { - this.put(key, 1); - } else if (value instanceof Integer) { - this.put(key, ((Integer) value).intValue() + 1); - } else if (value instanceof Long) { - this.put(key, ((Long) value).longValue() + 1L); - } else if (value instanceof BigInteger) { - this.put(key, ((BigInteger)value).add(BigInteger.ONE)); - } else if (value instanceof Float) { - this.put(key, ((Float) value).floatValue() + 1.0f); - } else if (value instanceof Double) { - this.put(key, ((Double) value).doubleValue() + 1.0d); - } else if (value instanceof BigDecimal) { - this.put(key, ((BigDecimal)value).add(BigDecimal.ONE)); - } else { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - /** - * Determine if the value associated with the key is null or if there is no - * value. - * - * @param key - * A key string. - * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(this.opt(key)); - } - - /** - * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also - * modify the JSONObject. Use with caution. - * - * @see Set#iterator() - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.keySet().iterator(); - } - - /** - * Get a set of keys of the JSONObject. Modifying this key Set will also modify the - * JSONObject. Use with caution. - * - * @see Map#keySet() - * - * @return A keySet. - */ - public Set keySet() { - return this.map.keySet(); - } - - /** - * Get a set of entries of the JSONObject. These are raw values and may not - * match what is returned by the JSONObject get* and opt* functions. Modifying - * the returned EntrySet or the Entry objects contained therein will modify the - * backing JSONObject. This does not return a clone or a read-only view. - * - * Use with caution. - * - * @see Map#entrySet() - * - * @return An Entry Set - */ - protected Set> entrySet() { - return this.map.entrySet(); - } - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - /** - * Removes all of the elements from this JSONObject. - * The JSONObject will be empty after this call returns. - */ - public void clear() { - this.map.clear(); - } - - /** - * Check if JSONObject is empty. - * - * @return true if JSONObject is empty, otherwise false. - */ - public boolean isEmpty() { - return this.map.isEmpty(); - } - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - if(this.map.isEmpty()) { - return null; - } - return new JSONArray(this.map.keySet()); - } - - /** - * Produce a string from a Number. - * - * @param number - * A Number - * @return A String. - * @throws JSONException - * If n is a non-finite number. - */ - public static String numberToString(Number number) throws JSONException { - if (number == null) { - throw new JSONException("Null pointer"); - } - testValidity(number); - - // Shave off trailing zeros and decimal point, if possible. - - String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 - && string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get an optional value associated with a key. - * - * @param key - * A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key or null if not found - */ - public > E optEnum(Class clazz, String key) { - return this.optEnum(clazz, key, null); - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @param defaultValue - * The default in case the value is not found - * @return The enum value associated with the key or defaultValue - * if the value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, String key, E defaultValue) { - try { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } catch (IllegalArgumentException e) { - return defaultValue; - } catch (NullPointerException e) { - return defaultValue; - } - } - - /** - * Get an optional boolean associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key - * A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - - /** - * Get an optional boolean associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof Boolean){ - return ((Boolean) val).booleanValue(); - } - try { - // we'll use the get anyway because it does string conversion. - return this.getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional boolean object associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key - * A key string. - * @return The truth. - */ - public Boolean optBooleanObject(String key) { - return this.optBooleanObject(key, false); - } - - /** - * Get an optional boolean object associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return The truth. - */ - public Boolean optBooleanObject(String key, Boolean defaultValue) { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof Boolean){ - return ((Boolean) val).booleanValue(); - } - try { - // we'll use the get anyway because it does string conversion. - return this.getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional BigDecimal associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. If the value - * is float or double, then the {@link BigDecimal#BigDecimal(double)} - * constructor will be used. See notes on the constructor for conversion - * issues that may arise. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { - Object val = this.opt(key); - return objectToBigDecimal(val, defaultValue); - } - - /** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @return BigDecimal conversion of the original value, or the defaultValue if unable - * to convert. - */ - static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) { - return objectToBigDecimal(val, defaultValue, true); - } - - /** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @param exact When true, then {@link Double} and {@link Float} values will be converted exactly. - * When false, they will be converted to {@link String} values before converting to {@link BigDecimal}. - * @return BigDecimal conversion of the original value, or the defaultValue if unable - * to convert. - */ - static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue, boolean exact) { - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigDecimal){ - return (BigDecimal) val; - } - if (val instanceof BigInteger){ - return new BigDecimal((BigInteger) val); - } - if (val instanceof Double || val instanceof Float){ - if (!numberIsFinite((Number)val)) { - return defaultValue; - } - if (exact) { - return new BigDecimal(((Number)val).doubleValue()); - } - // use the string constructor so that we maintain "nice" values for doubles and floats - // the double constructor will translate doubles to "exact" values instead of the likely - // intended representation - return new BigDecimal(val.toString()); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return new BigDecimal(((Number) val).longValue()); - } - // don't check if it's a string in case of unchecked Number subclasses - try { - return new BigDecimal(val.toString()); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional BigInteger associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) { - Object val = this.opt(key); - return objectToBigInteger(val, defaultValue); - } - - /** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @return BigInteger conversion of the original value, or the defaultValue if unable - * to convert. - */ - static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigInteger){ - return (BigInteger) val; - } - if (val instanceof BigDecimal){ - return ((BigDecimal) val).toBigInteger(); - } - if (val instanceof Double || val instanceof Float){ - if (!numberIsFinite((Number)val)) { - return defaultValue; - } - return new BigDecimal(((Number) val).doubleValue()).toBigInteger(); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return BigInteger.valueOf(((Number) val).longValue()); - } - // don't check if it's a string in case of unchecked Number subclasses - try { - // the other opt functions handle implicit conversions, i.e. - // jo.put("double",1.1d); - // jo.optInt("double"); -- will return 1, not an error - // this conversion to BigDecimal then to BigInteger is to maintain - // that type cast support that may truncate the decimal. - final String valStr = val.toString(); - if(isDecimalNotation(valStr)) { - return new BigDecimal(valStr).toBigInteger(); - } - return new BigInteger(valStr); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - /** - * Get an optional double associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - return val.doubleValue(); - } - - /** - * Get an optional Double object associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public Double optDoubleObject(String key) { - return this.optDoubleObject(key, Double.NaN); - } - - /** - * Get an optional Double object associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public Double optDoubleObject(String key, Double defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - return val.doubleValue(); - } - - /** - * Get the optional float value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param key - * A key string. - * @return The value. - */ - public float optFloat(String key) { - return this.optFloat(key, Float.NaN); - } - - /** - * Get the optional float value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param key - * A key string. - * @param defaultValue - * The default value. - * @return The value. - */ - public float optFloat(String key, float defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - final float floatValue = val.floatValue(); - // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { - // return defaultValue; - // } - return floatValue; - } - - /** - * Get the optional Float object associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param key - * A key string. - * @return The object. - */ - public Float optFloatObject(String key) { - return this.optFloatObject(key, Float.NaN); - } - - /** - * Get the optional Float object associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param key - * A key string. - * @param defaultValue - * The default object. - * @return The object. - */ - public Float optFloatObject(String key, Float defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - final Float floatValue = val.floatValue(); - // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { - // return defaultValue; - // } - return floatValue; - } - - /** - * Get an optional int value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return this.optInt(key, 0); - } - - /** - * Get an optional int value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * Get an optional Integer object associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public Integer optIntegerObject(String key) { - return this.optIntegerObject(key, 0); - } - - /** - * Get an optional Integer object associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public Integer optIntegerObject(String key, Integer defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * Get an optional JSONArray associated with a key. It returns null if there - * is no such key, or if its value is not a JSONArray. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - return this.optJSONArray(key, null); - } - - /** - * Get an optional JSONArray associated with a key, or the default if there - * is no such key, or if its value is not a JSONArray. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key, JSONArray defaultValue) { - Object object = this.opt(key); - return object instanceof JSONArray ? (JSONArray) object : defaultValue; - } - - /** - * Get an optional JSONObject associated with a key. It returns null if - * there is no such key, or if its value is not a JSONObject. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { return this.optJSONObject(key, null); } - - /** - * Get an optional JSONObject associated with a key, or the default if there - * is no such key or if the value is not a JSONObject. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An JSONObject which is the value. - */ - public JSONObject optJSONObject(String key, JSONObject defaultValue) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : defaultValue; - } - - /** - * Get an optional long value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return this.optLong(key, 0); - } - - /** - * Get an optional long value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - - return val.longValue(); - } - - /** - * Get an optional Long object associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public Long optLongObject(String key) { - return this.optLongObject(key, 0L); - } - - /** - * Get an optional Long object associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public Long optLongObject(String key, Long defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - - return val.longValue(); - } - - /** - * Get an optional {@link Number} value associated with a key, or null - * if there is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public Number optNumber(String key) { - return this.optNumber(key, null); - } - - /** - * Get an optional {@link Number} value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. This method - * would be used in cases where type coercion of the number value is unwanted. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public Number optNumber(String key, Number defaultValue) { - Object val = this.opt(key); - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof Number){ - return (Number) val; - } - - try { - return stringToNumber(val.toString()); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * Get an optional string associated with a key. It returns an empty string - * if there is no such key. If the value is not a string and is not null, - * then it is converted to a string. - * - * @param key - * A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return this.optString(key, ""); - } - - /** - * Get an optional string associated with a key. It returns the defaultValue - * if there is no such key. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - /** - * Populates the internal map of the JSONObject with the bean properties. The - * bean can not be recursive. - * - * @see JSONObject#JSONObject(Object) - * - * @param bean - * the bean - * @throws JSONException - * If a getter returned a non-finite number. - */ - private void populateMap(Object bean) { - populateMap(bean, Collections.newSetFromMap(new IdentityHashMap())); - } - - private void populateMap(Object bean, Set objectsRecord) { - Class klass = bean.getClass(); - - // If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for (final Method method : methods) { - final int modifiers = method.getModifiers(); - if (Modifier.isPublic(modifiers) - && !Modifier.isStatic(modifiers) - && method.getParameterTypes().length == 0 - && !method.isBridge() - && method.getReturnType() != Void.TYPE - && isValidMethodName(method.getName())) { - final String key = getKeyNameFromMethod(method); - if (key != null && !key.isEmpty()) { - try { - final Object result = method.invoke(bean); - if (result != null) { - // check cyclic dependency and throw error if needed - // the wrap and populateMap combination method is - // itself DFS recursive - if (objectsRecord.contains(result)) { - throw recursivelyDefinedObjectException(key); - } - - objectsRecord.add(result); - - testValidity(result); - this.map.put(key, wrap(result, objectsRecord)); - - objectsRecord.remove(result); - - // we don't use the result anywhere outside of wrap - // if it's a resource we should be sure to close it - // after calling toString - if (result instanceof Closeable) { - try { - ((Closeable) result).close(); - } catch (IOException ignore) { - } - } - } - } catch (IllegalAccessException ignore) { - } catch (IllegalArgumentException ignore) { - } catch (InvocationTargetException ignore) { - } - } - } - } - } - - private static boolean isValidMethodName(String name) { - return !"getClass".equals(name) && !"getDeclaringClass".equals(name); - } - - private static String getKeyNameFromMethod(Method method) { - final int ignoreDepth = getAnnotationDepth(method, JSONPropertyIgnore.class); - if (ignoreDepth > 0) { - final int forcedNameDepth = getAnnotationDepth(method, JSONPropertyName.class); - if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) { - // the hierarchy asked to ignore, and the nearest name override - // was higher or non-existent - return null; - } - } - JSONPropertyName annotation = getAnnotation(method, JSONPropertyName.class); - if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) { - return annotation.value(); - } - String key; - final String name = method.getName(); - if (name.startsWith("get") && name.length() > 3) { - key = name.substring(3); - } else if (name.startsWith("is") && name.length() > 2) { - key = name.substring(2); - } else { - return null; - } - // if the first letter in the key is not uppercase, then skip. - // This is to maintain backwards compatibility before PR406 - // (https://github.com/stleary/JSON-java/pull/406/) - if (key.length() == 0 || Character.isLowerCase(key.charAt(0))) { - return null; - } - if (key.length() == 1) { - key = key.toLowerCase(Locale.ROOT); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1); - } - return key; - } - - /** - * Searches the class hierarchy to see if the method or it's super - * implementations and interfaces has the annotation. - * - * @param - * type of the annotation - * - * @param m - * method to check - * @param annotationClass - * annotation to look for - * @return the {@link Annotation} if the annotation exists on the current method - * or one of its super class definitions - */ - private static A getAnnotation(final Method m, final Class annotationClass) { - // if we have invalid data the result is null - if (m == null || annotationClass == null) { - return null; - } - - if (m.isAnnotationPresent(annotationClass)) { - return m.getAnnotation(annotationClass); - } - - // if we've already reached the Object class, return null; - Class c = m.getDeclaringClass(); - if (c.getSuperclass() == null) { - return null; - } - - // check directly implemented interfaces for the method being checked - for (Class i : c.getInterfaces()) { - try { - Method im = i.getMethod(m.getName(), m.getParameterTypes()); - return getAnnotation(im, annotationClass); - } catch (final SecurityException ex) { - continue; - } catch (final NoSuchMethodException ex) { - continue; - } - } - - //If the superclass is Object, no annotations will be found any more - if (c.getSuperclass().equals(Object.class)) - return null; - - try { - return getAnnotation( - c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), - annotationClass); - } catch (final SecurityException ex) { - return null; - } catch (final NoSuchMethodException ex) { - return null; - } - } - - /** - * Searches the class hierarchy to see if the method or it's super - * implementations and interfaces has the annotation. Returns the depth of the - * annotation in the hierarchy. - * - * @param m - * method to check - * @param annotationClass - * annotation to look for - * @return Depth of the annotation or -1 if the annotation is not on the method. - */ - private static int getAnnotationDepth(final Method m, final Class annotationClass) { - // if we have invalid data the result is -1 - if (m == null || annotationClass == null) { - return -1; - } - - if (m.isAnnotationPresent(annotationClass)) { - return 1; - } - - // if we've already reached the Object class, return -1; - Class c = m.getDeclaringClass(); - if (c.getSuperclass() == null) { - return -1; - } - - // check directly implemented interfaces for the method being checked - for (Class i : c.getInterfaces()) { - try { - Method im = i.getMethod(m.getName(), m.getParameterTypes()); - int d = getAnnotationDepth(im, annotationClass); - if (d > 0) { - // since the annotation was on the interface, add 1 - return d + 1; - } - } catch (final SecurityException ex) { - continue; - } catch (final NoSuchMethodException ex) { - continue; - } - } - - //If the superclass is Object, no annotations will be found any more - if (c.getSuperclass().equals(Object.class)) - return -1; - - try { - int d = getAnnotationDepth( - c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), - annotationClass); - if (d > 0) { - // since the annotation was on the superclass, add 1 - return d + 1; - } - return -1; - } catch (final SecurityException ex) { - return -1; - } catch (final NoSuchMethodException ex) { - return -1; - } - } - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A boolean which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * - * @param key - * A key string. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, Collection value) throws JSONException { - return this.put(key, new JSONArray(value)); - } - - /** - * Put a key/double pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A double which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, double value) throws JSONException { - return this.put(key, Double.valueOf(value)); - } - - /** - * Put a key/float pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A float which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, float value) throws JSONException { - return this.put(key, Float.valueOf(value)); - } - - /** - * Put a key/int pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * An int which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - return this.put(key, Integer.valueOf(value)); - } - - /** - * Put a key/long pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A long which is the value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - return this.put(key, Long.valueOf(value)); - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * - * @param key - * A key string. - * @param value - * A Map value. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, Map value) throws JSONException { - return this.put(key, new JSONObject(value)); - } - - /** - * Put a key/value pair in the JSONObject. If the value is null, then the - * key will be removed from the JSONObject if it is present. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new NullPointerException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null, and only if there is not already a member with that - * name. - * - * @param key - * key to insert into - * @param value - * value to insert - * @return this. - * @throws JSONException - * if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - return this.put(key, value); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - return this.put(key, value); - } - return this; - } - - /** - * Creates a JSONPointer using an initialization string and tries to - * match it to an item within this JSONObject. For example, given a - * JSONObject initialized with this document: - *
              -     * {
              -     *     "a":{"b":"c"}
              -     * }
              -     * 
              - * and this JSONPointer string: - *
              -     * "/a/b"
              -     * 
              - * Then this method will return the String "c". - * A JSONPointerException may be thrown from code called by this method. - * - * @param jsonPointer string that can be used to create a JSONPointer - * @return the item matched by the JSONPointer, otherwise null - */ - public Object query(String jsonPointer) { - return query(new JSONPointer(jsonPointer)); - } - /** - * Uses a user initialized JSONPointer and tries to - * match it to an item within this JSONObject. For example, given a - * JSONObject initialized with this document: - *
              -     * {
              -     *     "a":{"b":"c"}
              -     * }
              -     * 
              - * and this JSONPointer: - *
              -     * "/a/b"
              -     * 
              - * Then this method will return the String "c". - * A JSONPointerException may be thrown from code called by this method. - * - * @param jsonPointer string that can be used to create a JSONPointer - * @return the item matched by the JSONPointer, otherwise null - */ - public Object query(JSONPointer jsonPointer) { - return jsonPointer.queryFrom(this); - } - - /** - * Queries and returns a value from this object using {@code jsonPointer}, or - * returns null if the query fails due to a missing key. - * - * @param jsonPointer the string representation of the JSON pointer - * @return the queried value or {@code null} - * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax - */ - public Object optQuery(String jsonPointer) { - return optQuery(new JSONPointer(jsonPointer)); - } - - /** - * Queries and returns a value from this object using {@code jsonPointer}, or - * returns null if the query fails due to a missing key. - * - * @param jsonPointer The JSON pointer - * @return the queried value or {@code null} - * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax - */ - public Object optQuery(JSONPointer jsonPointer) { - try { - return jsonPointer.queryFrom(this); - } catch (JSONPointerException e) { - return null; - } - } - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within </, producing - * <\/, allowing JSON text to be delivered in HTML. In JSON text, a - * string cannot contain a control character or an unescaped quote or - * backslash. - * - * @param string - * A String - * @return A String correctly formatted for insertion in a JSON text. - */ - @SuppressWarnings("resource") - public static String quote(String string) { - StringWriter sw = new StringWriter(); - try { - return quote(string, sw).toString(); - } catch (IOException ignored) { - // will never happen - we are writing to a string writer - return ""; - } - } - - /** - * Quotes a string and appends the result to a given Writer. - * - * @param string The input string to be quoted. - * @param w The Writer to which the quoted string will be appended. - * @return The same Writer instance after appending the quoted string. - * @throws IOException If an I/O error occurs while writing to the Writer. - */ - public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.isEmpty()) { - w.write("\"\""); - return w; - } - - char b; - char c = 0; - String hhhh; - int i; - int len = string.length(); - - w.write('"'); - for (i = 0; i < len; i += 1) { - b = c; - c = string.charAt(i); - switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { - w.write('\\'); - } - w.write(c); - break; - case '\b': - w.write("\\b"); - break; - case '\t': - w.write("\\t"); - break; - case '\n': - w.write("\\n"); - break; - case '\f': - w.write("\\f"); - break; - case '\r': - w.write("\\r"); - break; - default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - w.write("\\u"); - hhhh = Integer.toHexString(c); - w.write("0000", 0, 4 - hhhh.length()); - w.write(hhhh); - } else { - w.write(c); - } - } - } - w.write('"'); - return w; - } - - /** - * Remove a name and its value, if present. - * - * @param key - * The name to be removed. - * @return The value that was associated with the name, or null if there was - * no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Determine if two JSONObjects are similar. - * They must contain the same set of names which must be associated with - * similar values. - * - * @param other The other JSONObject - * @return true if they are equal - */ - public boolean similar(Object other) { - try { - if (!(other instanceof JSONObject)) { - return false; - } - if (!this.keySet().equals(((JSONObject)other).keySet())) { - return false; - } - for (final Entry entry : this.entrySet()) { - String name = entry.getKey(); - Object valueThis = entry.getValue(); - Object valueOther = ((JSONObject)other).get(name); - if(valueThis == valueOther) { - continue; - } - if(valueThis == null) { - return false; - } - if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof Number && valueOther instanceof Number) { - if (!isNumberSimilar((Number)valueThis, (Number)valueOther)) { - return false; - } - } else if (valueThis instanceof JSONString && valueOther instanceof JSONString) { - if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; - } - } - return true; - } catch (Throwable exception) { - return false; - } - } - - /** - * Compares two numbers to see if they are similar. - * - * If either of the numbers are Double or Float instances, then they are checked to have - * a finite value. If either value is not finite (NaN or ±infinity), then this - * function will always return false. If both numbers are finite, they are first checked - * to be the same type and implement {@link Comparable}. If they do, then the actual - * {@link Comparable#compareTo(Object)} is called. If they are not the same type, or don't - * implement Comparable, then they are converted to {@link BigDecimal}s. Finally the - * BigDecimal values are compared using {@link BigDecimal#compareTo(BigDecimal)}. - * - * @param l the Left value to compare. Can not be null. - * @param r the right value to compare. Can not be null. - * @return true if the numbers are similar, false otherwise. - */ - static boolean isNumberSimilar(Number l, Number r) { - if (!numberIsFinite(l) || !numberIsFinite(r)) { - // non-finite numbers are never similar - return false; - } - - // if the classes are the same and implement Comparable - // then use the built in compare first. - if(l.getClass().equals(r.getClass()) && l instanceof Comparable) { - @SuppressWarnings({ "rawtypes", "unchecked" }) - int compareTo = ((Comparable)l).compareTo(r); - return compareTo==0; - } - - // BigDecimal should be able to handle all of our number types that we support through - // documentation. Convert to BigDecimal first, then use the Compare method to - // decide equality. - final BigDecimal lBigDecimal = objectToBigDecimal(l, null, false); - final BigDecimal rBigDecimal = objectToBigDecimal(r, null, false); - if (lBigDecimal == null || rBigDecimal == null) { - return false; - } - return lBigDecimal.compareTo(rBigDecimal) == 0; - } - - private static boolean numberIsFinite(Number n) { - if (n instanceof Double && (((Double) n).isInfinite() || ((Double) n).isNaN())) { - return false; - } else if (n instanceof Float && (((Float) n).isInfinite() || ((Float) n).isNaN())) { - return false; - } - return true; - } - - /** - * Tests if the value should be tried as a decimal. It makes no test if there are actual digits. - * - * @param val value to test - * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise. - */ - protected static boolean isDecimalNotation(final String val) { - return val.indexOf('.') > -1 || val.indexOf('e') > -1 - || val.indexOf('E') > -1 || "-0".equals(val); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * - * @param string - * A String. can not be null. - * @return A simple JSON value. - * @throws NullPointerException - * Thrown if the string is null. - */ - // Changes to this method must be copied to the corresponding method in - // the XML class to keep full support for Android - public static Object stringToValue(String string) { - if ("".equals(string)) { - return string; - } - - // check JSON key words true/false/null - if ("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if ("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if ("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. If a number cannot be - * produced, then the value will just be a string. - */ - - char initial = string.charAt(0); - if ((initial >= '0' && initial <= '9') || initial == '-') { - try { - return stringToNumber(string); - } catch (Exception ignore) { - } - } - return string; - } - - /** - * Converts a string to a number using the narrowest possible type. Possible - * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer. - * When a Double is returned, it should always be a valid Double and not NaN or +-infinity. - * - * @param val value to convert - * @return Number representation of the value. - * @throws NumberFormatException thrown if the value is not a valid number. A public - * caller should catch this and wrap it in a {@link JSONException} if applicable. - */ - protected static Number stringToNumber(final String val) throws NumberFormatException { - char initial = val.charAt(0); - if ((initial >= '0' && initial <= '9') || initial == '-') { - // decimal representation - if (isDecimalNotation(val)) { - // Use a BigDecimal all the time so we keep the original - // representation. BigDecimal doesn't support -0.0, ensure we - // keep that by forcing a decimal. - try { - BigDecimal bd = new BigDecimal(val); - if(initial == '-' && BigDecimal.ZERO.compareTo(bd)==0) { - return Double.valueOf(-0.0); - } - return bd; - } catch (NumberFormatException retryAsDouble) { - // this is to support "Hex Floats" like this: 0x1.0P-1074 - try { - Double d = Double.valueOf(val); - if(d.isNaN() || d.isInfinite()) { - throw new NumberFormatException("val ["+val+"] is not a valid number."); - } - return d; - } catch (NumberFormatException ignore) { - throw new NumberFormatException("val ["+val+"] is not a valid number."); - } - } - } - // block items like 00 01 etc. Java number parsers treat these as Octal. - if(initial == '0' && val.length() > 1) { - char at1 = val.charAt(1); - if(at1 >= '0' && at1 <= '9') { - throw new NumberFormatException("val ["+val+"] is not a valid number."); - } - } else if (initial == '-' && val.length() > 2) { - char at1 = val.charAt(1); - char at2 = val.charAt(2); - if(at1 == '0' && at2 >= '0' && at2 <= '9') { - throw new NumberFormatException("val ["+val+"] is not a valid number."); - } - } - // integer representation. - // This will narrow any values to the smallest reasonable Object representation - // (Integer, Long, or BigInteger) - - // BigInteger down conversion: We use a similar bitLength compare as - // BigInteger#intValueExact uses. Increases GC, but objects hold - // only what they need. i.e. Less runtime overhead if the value is - // long lived. - BigInteger bi = new BigInteger(val); - if(bi.bitLength() <= 31){ - return Integer.valueOf(bi.intValue()); - } - if(bi.bitLength() <= 63){ - return Long.valueOf(bi.longValue()); - } - return bi; - } - throw new NumberFormatException("val ["+val+"] is not a valid number."); - } - - /** - * Throw an exception if the object is a NaN or infinite number. - * - * @param o - * The object to test. - * @throws JSONException - * If o is a non-finite number. - */ - public static void testValidity(Object o) throws JSONException { - if (o instanceof Number && !numberIsFinite((Number) o)) { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * - * @param names - * A JSONArray containing a list of key strings. This determines - * the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException - * If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.isEmpty()) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace is - * added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - */ - @Override - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return null; - } - } - - /** - * Make a pretty-printed JSON text of this JSONObject. - * - *

              If

              {@code indentFactor > 0}
              and the {@link JSONObject} - * has only one key, then the object will be output on a single line: - *
              {@code {"key": 1}}
              - * - *

              If an object has 2 or more keys, then it will be output across - * multiple lines:

              {@code {
              -     *  "key1": 1,
              -     *  "key2": "value 2",
              -     *  "key3": 3
              -     * }}
              - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the object contains an invalid number. - */ - @SuppressWarnings("resource") - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); - return this.write(w, indentFactor, 0).toString(); - } - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce the - * JSON text. The method is required to produce a strictly conforming text. - * If the object does not contain a toJSONString method (which is the most - * common case), then a text will be produced by other means. If the value - * is an array or Collection, then a JSONArray will be made from it and its - * toJSONString method will be called. If the value is a MAP, then a - * JSONObject will be made from it and its toJSONString method will be - * called. Otherwise, the value's toString method will be called, and the - * result will be quoted. - * - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * @param value - * The value to be serialized. - * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - // moves the implementation to JSONWriter as: - // 1. It makes more sense to be part of the writer class - // 2. For Android support this method is not available. By implementing it in the Writer - // Android users can use the writer with the built in Android JSONObject implementation. - return JSONWriter.valueToString(value); - } - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If it is - * a map, wrap it in a JSONObject. If it is a standard property (Double, - * String, et al) then it is already wrapped. Otherwise, if it comes from - * one of the java packages, turn it into a string. And if it doesn't, try - * to wrap it in a JSONObject. If the wrapping fails, then null is returned. - * - * @param object - * The object to wrap - * @return The wrapped value - */ - public static Object wrap(Object object) { - return wrap(object, null); - } - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If it is - * a map, wrap it in a JSONObject. If it is a standard property (Double, - * String, et al) then it is already wrapped. Otherwise, if it comes from - * one of the java packages, turn it into a string. And if it doesn't, try - * to wrap it in a JSONObject. If the wrapping fails, then null is returned. - * - * @param object - * The object to wrap - * @param recursionDepth - * Variable for tracking the count of nested object creations. - * @param jsonParserConfiguration - * Variable to pass parser custom configuration for json parsing. - * @return The wrapped value - */ - static Object wrap(Object object, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - return wrap(object, null, recursionDepth, jsonParserConfiguration); - } - - private static Object wrap(Object object, Set objectsRecord) { - return wrap(object, objectsRecord, 0, new JSONParserConfiguration()); - } - - private static Object wrap(Object object, Set objectsRecord, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - try { - if (NULL.equals(object)) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray - || NULL.equals(object) || object instanceof JSONString - || object instanceof Byte || object instanceof Character - || object instanceof Short || object instanceof Integer - || object instanceof Long || object instanceof Boolean - || object instanceof Float || object instanceof Double - || object instanceof String || object instanceof BigInteger - || object instanceof BigDecimal || object instanceof Enum) { - return object; - } - - if (object instanceof Collection) { - Collection coll = (Collection) object; - return new JSONArray(coll, recursionDepth, jsonParserConfiguration); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - Map map = (Map) object; - return new JSONObject(map, recursionDepth, jsonParserConfiguration); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null ? objectPackage - .getName() : ""; - if (objectPackageName.startsWith("java.") - || objectPackageName.startsWith("javax.") - || object.getClass().getClassLoader() == null) { - return object.toString(); - } - if (objectsRecord != null) { - return new JSONObject(object, objectsRecord); - } - return new JSONObject(object); - } - catch (JSONException exception) { - throw exception; - } catch (Exception exception) { - return null; - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * @param writer the writer object - * @return The writer. - * @throws JSONException if a called function has an error - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - @SuppressWarnings("resource") - static final Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { - if (value == null || value.equals(null)) { - writer.write("null"); - } else if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else if (value instanceof Number) { - // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary - final String numberAsString = numberToString((Number) value); - if(NUMBER_PATTERN.matcher(numberAsString).matches()) { - writer.write(numberAsString); - } else { - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - quote(numberAsString, writer); - } - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof Enum) { - writer.write(quote(((Enum)value).name())); - } else if (value instanceof JSONObject) { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { - Map map = (Map) value; - new JSONObject(map).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { - Collection coll = (Collection) value; - new JSONArray(coll).write(writer, indentFactor, indent); - } else if (value.getClass().isArray()) { - new JSONArray(value).write(writer, indentFactor, indent); - } else { - quote(value.toString(), writer); - } - return writer; - } - - static final void indent(Writer writer, int indent) throws IOException { - for (int i = 0; i < indent; i += 1) { - writer.write(' '); - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. - * - *

              If

              {@code indentFactor > 0}
              and the {@link JSONObject} - * has only one key, then the object will be output on a single line: - *
              {@code {"key": 1}}
              - * - *

              If an object has 2 or more keys, then it will be output across - * multiple lines:

              {@code {
              -     *  "key1": 1,
              -     *  "key2": "value 2",
              -     *  "key3": 3
              -     * }}
              - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * - * @param writer - * Writes the serialized JSON - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @param indent - * The indentation of the top level. - * @return The writer. - * @throws JSONException if a called function has an error or a write error - * occurs - */ - @SuppressWarnings("resource") - public Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean needsComma = false; - final int length = this.length(); - writer.write('{'); - - if (length == 1) { - final Entry entry = this.entrySet().iterator().next(); - final String key = entry.getKey(); - writer.write(quote(key)); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - try{ - writeValue(writer, entry.getValue(), indentFactor, indent); - } catch (Exception e) { - throw new JSONException("Unable to write JSONObject value for key: " + key, e); - } - } else if (length != 0) { - final int newIndent = indent + indentFactor; - for (final Entry entry : this.entrySet()) { - if (needsComma) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, newIndent); - final String key = entry.getKey(); - writer.write(quote(key)); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - try { - writeValue(writer, entry.getValue(), indentFactor, newIndent); - } catch (Exception e) { - throw new JSONException("Unable to write JSONObject value for key: " + key, e); - } - needsComma = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, indent); - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } - - /** - * Returns a java.util.Map containing all of the entries in this object. - * If an entry in the object is a JSONArray or JSONObject it will also - * be converted. - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * @return a java.util.Map containing the entries of this object - */ - public Map toMap() { - Map results = new HashMap(); - for (Entry entry : this.entrySet()) { - Object value; - if (entry.getValue() == null || NULL.equals(entry.getValue())) { - value = null; - } else if (entry.getValue() instanceof JSONObject) { - value = ((JSONObject) entry.getValue()).toMap(); - } else if (entry.getValue() instanceof JSONArray) { - value = ((JSONArray) entry.getValue()).toList(); - } else { - value = entry.getValue(); - } - results.put(entry.getKey(), value); - } - return results; - } - - /** - * Create a new JSONException in a common format for incorrect conversions. - * @param key name of the key - * @param valueType the type of value being coerced to - * @param cause optional cause of the coercion failure - * @return JSONException that can be thrown. - */ - private static JSONException wrongValueFormatException( - String key, - String valueType, - Object value, - Throwable cause) { - if(value == null) { - - return new JSONException( - "JSONObject[" + quote(key) + "] is not a " + valueType + " (null)." - , cause); - } - // don't try to toString collections or known object types that could be large. - if(value instanceof Map || value instanceof Iterable || value instanceof JSONObject) { - return new JSONException( - "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + ")." - , cause); - } - return new JSONException( - "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")." - , cause); - } - - /** - * Create a new JSONException in a common format for recursive object definition. - * @param key name of the key - * @return JSONException that can be thrown. - */ - private static JSONException recursivelyDefinedObjectException(String key) { - return new JSONException( - "JavaBean object contains recursively defined member variable of key " + quote(key) - ); - } - - /** - * For a prospective number, remove the leading zeros - * @param value prospective number - * @return number without leading zeros - */ - private static String removeLeadingZerosOfNumber(String value){ - if (value.equals("-")){return value;} - boolean negativeFirstChar = (value.charAt(0) == '-'); - int counter = negativeFirstChar ? 1:0; - while (counter < value.length()){ - if (value.charAt(counter) != '0'){ - if (negativeFirstChar) {return "-".concat(value.substring(counter));} - return value.substring(counter); - } - ++counter; - } - if (negativeFirstChar) {return "-0";} - return "0"; - } + String[] path = ((String) key).split("\\."); + int last = path.length - 1; + JSONObject target = this; + for (int i = 0; i < last; i += 1) { + String segment = path[i]; + JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null) { + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String) key)); + } + } + } + + /** + * Accumulate values under a key. It is similar to the put method except that if + * there is already an object stored under the key then a JSONArray is stored + * under the key to hold all of the accumulated values. If there is already a + * JSONArray, then the new value is appended to it. In contrast, the put method + * replaces the previous value. + * + * If only one value is accumulated that is not a JSONArray, then the result + * will be the same as using put. But if multiple values are accumulated, then + * the result will be like append. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject accumulate(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } else if (object instanceof JSONArray) { + ((JSONArray) object).put(value); + } else { + this.put(key, new JSONArray().put(object).put(value)); + } + return this; + } + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already associated + * with a JSONArray, then the value parameter is appended to it. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is non-finite number or if the + * current value associated with the key is not a + * JSONArray. + * @throws NullPointerException If the key is null. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + this.put(key, ((JSONArray) object).put(value)); + } else { + throw wrongValueFormatException(key, "JSONArray", null, null); + } + return this; + } + + /** + * Removes all of the elements from this JSONObject. The JSONObject will be + * empty after this call returns. + */ + public void clear() { + this.map.clear(); + } + + /** + * Get a set of entries of the JSONObject. These are raw values and may not + * match what is returned by the JSONObject get* and opt* functions. Modifying + * the returned EntrySet or the Entry objects contained therein will modify the + * backing JSONObject. This does not return a clone or a read-only view. + * + * Use with caution. + * + * @see Map#entrySet() + * + * @return An Entry Set + */ + protected Set> entrySet() { + return this.map.entrySet(); + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = this.opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + /** + * Get the BigDecimal value associated with a key. If the value is float or + * double, the {@link BigDecimal#BigDecimal(double)} constructor will be used. + * See notes on the constructor for conversion issues that may arise. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value cannot be + * converted to BigDecimal. + */ + public BigDecimal getBigDecimal(String key) throws JSONException { + Object object = this.get(key); + BigDecimal ret = objectToBigDecimal(object, null); + if (ret != null) { + return ret; + } + throw wrongValueFormatException(key, "BigDecimal", object, null); + } + + /** + * Get the BigInteger value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value cannot be + * converted to BigInteger. + */ + public BigInteger getBigInteger(String key) throws JSONException { + Object object = this.get(key); + BigInteger ret = objectToBigInteger(object, null); + if (ret != null) { + return ret; + } + throw wrongValueFormatException(key, "BigInteger", object, null); + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or + * "false". + */ + public boolean getBoolean(String key) throws JSONException { + Object object = this.get(key); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) + || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw wrongValueFormatException(key, "Boolean", object, null); + } + + /** + * Get the double value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public double getDouble(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).doubleValue(); + } + try { + return Double.parseDouble(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "double", object, e); + } + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key + * @throws JSONException if the key is not found or if the value cannot be + * converted to an enum. + */ + public > E getEnum(Class clazz, String key) throws JSONException { + E val = optEnum(clazz, key); + if (val == null) { + // JSONException should really take a throwable argument. + // If it did, I would re-implement this with the Enum.valueOf + // method and place any thrown exception in the JSONException + throw wrongValueFormatException(key, "enum of type " + quote(clazz.getSimpleName()), opt(key), null); + } + return val; + } + + /** + * Get the float value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public float getFloat(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).floatValue(); + } + try { + return Float.parseFloat(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "float", object, e); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot be + * converted to an integer. + */ + public int getInt(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).intValue(); + } + try { + return Integer.parseInt(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "int", object, e); + } + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or if the value is not a + * JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw wrongValueFormatException(key, "JSONArray", object, null); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or if the value is not a + * JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw wrongValueFormatException(key, "JSONObject", object, null); + } + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot be + * converted to a long. + */ + public long getLong(String key) throws JSONException { + final Object object = this.get(key); + if (object instanceof Number) { + return ((Number) object).longValue(); + } + try { + return Long.parseLong(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "long", object, e); + } + } + + /** + * Retrieves the type of the underlying Map in this class. + * + * @return The class object representing the type of the underlying Map. + */ + public Class getMapType() { + return map.getClass(); + } + + /** + * Get the Number value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public Number getNumber(String key) throws JSONException { + Object object = this.get(key); + try { + if (object instanceof Number) { + return (Number) object; + } + return stringToNumber(object.toString()); + } catch (Exception e) { + throw wrongValueFormatException(key, "number", object, e); + } + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if there is no string value for the key. + */ + public String getString(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof String) { + return (String) object; + } + throw wrongValueFormatException(key, "string", object, null); + } + + /** + * Determine if the JSONObject contains a specific key. + * + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key) { + return this.map.containsKey(key); + } + + /** + * Increment a property of a JSONObject. If there is no such property, create + * one with a value of 1 (Integer). If there is such a property, and if it is an + * Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it. + * No overflow bounds checking is performed, so callers should initialize the + * key prior to this call with an appropriate type that can handle the maximum + * expected value. + * + * @param key A key string. + * @return this. + * @throws JSONException If there is already a property with this name that is + * not an Integer, Long, Double, or Float. + */ + public JSONObject increment(String key) throws JSONException { + Object value = this.opt(key); + if (value == null) { + this.put(key, 1); + } else if (value instanceof Integer) { + this.put(key, ((Integer) value).intValue() + 1); + } else if (value instanceof Long) { + this.put(key, ((Long) value).longValue() + 1L); + } else if (value instanceof BigInteger) { + this.put(key, ((BigInteger) value).add(BigInteger.ONE)); + } else if (value instanceof Float) { + this.put(key, ((Float) value).floatValue() + 1.0f); + } else if (value instanceof Double) { + this.put(key, ((Double) value).doubleValue() + 1.0d); + } else if (value instanceof BigDecimal) { + this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); + } else { + throw new JSONException("Unable to increment [" + quote(key) + "]."); + } + return this; + } + + /** + * Check if JSONObject is empty. + * + * @return true if JSONObject is empty, otherwise false. + */ + public boolean isEmpty() { + return this.map.isEmpty(); + } + + /** + * Determine if the value associated with the key is null or if + * there is no value. + * + * @param key A key string. + * @return true if there is no value associated with the key or if the value is + * the JSONObject.NULL object. + */ + public boolean isNull(String key) { + return JSONObject.NULL.equals(this.opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. Modifying this key Set will + * also modify the JSONObject. Use with caution. + * + * @see Set#iterator() + * + * @return An iterator of the keys. + */ + public Iterator keys() { + return this.keySet().iterator(); + } + + /** + * Get a set of keys of the JSONObject. Modifying this key Set will also modify + * the JSONObject. Use with caution. + * + * @see Map#keySet() + * + * @return A keySet. + */ + public Set keySet() { + return this.map.keySet(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + /** + * Produce a JSONArray containing the names of the elements of this JSONObject. + * + * @return A JSONArray containing the key strings, or null if the JSONObject is + * empty. + */ + public JSONArray names() { + if (this.map.isEmpty()) { + return null; + } + return new JSONArray(this.map.keySet()); + } + + /** + * Get an optional value associated with a key. + * + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key) { + return key == null ? null : this.map.get(key); + } + + /** + * Get an optional BigDecimal associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. If the value is + * float or double, then the {@link BigDecimal#BigDecimal(double)} constructor + * will be used. See notes on the constructor for conversion issues that may + * arise. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { + Object val = this.opt(key); + return objectToBigDecimal(val, defaultValue); + } + + /** + * Get an optional BigInteger associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigInteger optBigInteger(String key, BigInteger defaultValue) { + Object val = this.opt(key); + return objectToBigInteger(val, defaultValue); + } + + /** + * Get an optional boolean associated with a key. It returns false if there is + * no such key, or if the value is not Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key) { + return this.optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. It returns the defaultValue if + * there is no such key, or if it is not a Boolean or the String "true" or + * "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Boolean) { + return ((Boolean) val).booleanValue(); + } + try { + // we'll use the get anyway because it does string conversion. + return this.getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional boolean object associated with a key. It returns false if + * there is no such key, or if the value is not Boolean.TRUE or the String + * "true". + * + * @param key A key string. + * @return The truth. + */ + public Boolean optBooleanObject(String key) { + return this.optBooleanObject(key, false); + } + + /** + * Get an optional boolean object associated with a key. It returns the + * defaultValue if there is no such key, or if it is not a Boolean or the String + * "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public Boolean optBooleanObject(String key, Boolean defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Boolean) { + return ((Boolean) val).booleanValue(); + } + try { + // we'll use the get anyway because it does string conversion. + return this.getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional double associated with a key, or NaN if there is no such key + * or if its value is not a number. If the value is a string, an attempt will be + * made to evaluate it as a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return this.optDouble(key, Double.NaN); + } + + /** + * Get an optional double associated with a key, or the defaultValue if there is + * no such key or if its value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue) { + Number val = this.optNumber(key); + if (val == null) { + return defaultValue; + } + return val.doubleValue(); + } + + /** + * Get an optional Double object associated with a key, or NaN if there is no + * such key or if its value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public Double optDoubleObject(String key) { + return this.optDoubleObject(key, Double.NaN); + } + + /** + * Get an optional Double object associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Double optDoubleObject(String key, Double defaultValue) { + Number val = this.optNumber(key); + if (val == null) { + return defaultValue; + } + return val.doubleValue(); + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key or null if not found + */ + public > E optEnum(Class clazz, String key) { + return this.optEnum(clazz, key, null); + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @param defaultValue The default in case the value is not found + * @return The enum value associated with the key or defaultValue if the value + * is not found or cannot be assigned to clazz + */ + public > E optEnum(Class clazz, String key, E defaultValue) { + try { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (clazz.isAssignableFrom(val.getClass())) { + // we just checked it! + @SuppressWarnings("unchecked") + E myE = (E) val; + return myE; + } + return Enum.valueOf(clazz, val.toString()); + } catch (IllegalArgumentException e) { + return defaultValue; + } catch (NullPointerException e) { + return defaultValue; + } + } + + /** + * Get the optional float value associated with an index. NaN is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param key A key string. + * @return The value. + */ + public float optFloat(String key) { + return this.optFloat(key, Float.NaN); + } + + /** + * Get the optional float value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param key A key string. + * @param defaultValue The default value. + * @return The value. + */ + public float optFloat(String key, float defaultValue) { + Number val = this.optNumber(key); + if (val == null) { + return defaultValue; + } + final float floatValue = val.floatValue(); + // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { + // return defaultValue; + // } + return floatValue; + } + + /** + * Get the optional Float object associated with an index. NaN is returned if + * there is no value for the index, or if the value is not a number and cannot + * be converted to a number. + * + * @param key A key string. + * @return The object. + */ + public Float optFloatObject(String key) { + return this.optFloatObject(key, Float.NaN); + } + + /** + * Get the optional Float object associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a number + * and cannot be converted to a number. + * + * @param key A key string. + * @param defaultValue The default object. + * @return The object. + */ + public Float optFloatObject(String key, Float defaultValue) { + Number val = this.optNumber(key); + if (val == null) { + return defaultValue; + } + final Float floatValue = val.floatValue(); + // if (Float.isNaN(floatValue) || Float.isInfinite(floatValue)) { + // return defaultValue; + // } + return floatValue; + } + + /** + * Get an optional int value associated with a key, or zero if there is no such + * key or if the value is not a number. If the value is a string, an attempt + * will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key) { + return this.optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, or the default if there is + * no such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue) { + final Number val = this.optNumber(key, null); + if (val == null) { + return defaultValue; + } + return val.intValue(); + } + + /** + * Get an optional Integer object associated with a key, or zero if there is no + * such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public Integer optIntegerObject(String key) { + return this.optIntegerObject(key, 0); + } + + /** + * Get an optional Integer object associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Integer optIntegerObject(String key, Integer defaultValue) { + final Number val = this.optNumber(key, null); + if (val == null) { + return defaultValue; + } + return val.intValue(); + } + + /** + * Get an optional JSONArray associated with a key. It returns null if there is + * no such key, or if its value is not a JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key) { + return this.optJSONArray(key, null); + } + + /** + * Get an optional JSONArray associated with a key, or the default if there is + * no such key, or if its value is not a JSONArray. + * + * @param key A key string. + * @param defaultValue The default. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key, JSONArray defaultValue) { + Object object = this.opt(key); + return object instanceof JSONArray ? (JSONArray) object : defaultValue; + } + + /** + * Get an optional JSONObject associated with a key. It returns null if there is + * no such key, or if its value is not a JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject(String key) { + return this.optJSONObject(key, null); + } + + /** + * Get an optional JSONObject associated with a key, or the default if there is + * no such key or if the value is not a JSONObject. + * + * @param key A key string. + * @param defaultValue The default. + * @return An JSONObject which is the value. + */ + public JSONObject optJSONObject(String key, JSONObject defaultValue) { + Object object = this.opt(key); + return object instanceof JSONObject ? (JSONObject) object : defaultValue; + } + + /** + * Get an optional long value associated with a key, or zero if there is no such + * key or if the value is not a number. If the value is a string, an attempt + * will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key) { + return this.optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, or the default if there is + * no such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue) { + final Number val = this.optNumber(key, null); + if (val == null) { + return defaultValue; + } + + return val.longValue(); + } + + /** + * Get an optional Long object associated with a key, or zero if there is no + * such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public Long optLongObject(String key) { + return this.optLongObject(key, 0L); + } + + /** + * Get an optional Long object associated with a key, or the default if there is + * no such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Long optLongObject(String key, Long defaultValue) { + final Number val = this.optNumber(key, null); + if (val == null) { + return defaultValue; + } + + return val.longValue(); + } + + /** + * Get an optional {@link Number} value associated with a key, or + * null if there is no such key or if the value is not a number. If + * the value is a string, an attempt will be made to evaluate it as a number + * ({@link BigDecimal}). This method would be used in cases where type coercion + * of the number value is unwanted. + * + * @param key A key string. + * @return An object which is the value. + */ + public Number optNumber(String key) { + return this.optNumber(key, null); + } + + /** + * Get an optional {@link Number} value associated with a key, or the default if + * there is no such key or if the value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. This method would + * be used in cases where type coercion of the number value is unwanted. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public Number optNumber(String key, Number defaultValue) { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof Number) { + return (Number) val; + } + + try { + return stringToNumber(val.toString()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer The JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(JSONPointer jsonPointer) { + try { + return jsonPointer.queryFrom(this); + } catch (JSONPointerException e) { + return null; + } + } + + /** + * Queries and returns a value from this object using {@code jsonPointer}, or + * returns null if the query fails due to a missing key. + * + * @param jsonPointer the string representation of the JSON pointer + * @return the queried value or {@code null} + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax + */ + public Object optQuery(String jsonPointer) { + return optQuery(new JSONPointer(jsonPointer)); + } + + /** + * Get an optional string associated with a key. It returns an empty string if + * there is no such key. If the value is not a string and is not null, then it + * is converted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key) { + return this.optString(key, ""); + } + + /** + * Get an optional string associated with a key. It returns the defaultValue if + * there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue) { + Object object = this.opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + /** + * Populates the internal map of the JSONObject with the bean properties. The + * bean can not be recursive. + * + * @see JSONObject#JSONObject(Object) + * + * @param bean the bean + * @throws JSONException If a getter returned a non-finite number. + */ + private void populateMap(Object bean) { + populateMap(bean, Collections.newSetFromMap(new IdentityHashMap())); + } + + private void populateMap(Object bean, Set objectsRecord) { + Class klass = bean.getClass(); + + // If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); + for (final Method method : methods) { + final int modifiers = method.getModifiers(); + if (Modifier.isPublic(modifiers) && !Modifier.isStatic(modifiers) && method.getParameterTypes().length == 0 + && !method.isBridge() && method.getReturnType() != Void.TYPE + && isValidMethodName(method.getName())) { + final String key = getKeyNameFromMethod(method); + if (key != null && !key.isEmpty()) { + try { + final Object result = method.invoke(bean); + if (result != null) { + // check cyclic dependency and throw error if needed + // the wrap and populateMap combination method is + // itself DFS recursive + if (objectsRecord.contains(result)) { + throw recursivelyDefinedObjectException(key); + } + + objectsRecord.add(result); + + testValidity(result); + this.map.put(key, wrap(result, objectsRecord)); + + objectsRecord.remove(result); + + // we don't use the result anywhere outside of wrap + // if it's a resource we should be sure to close it + // after calling toString + if (result instanceof Closeable) { + try { + ((Closeable) result).close(); + } catch (IOException ignore) { + } + } + } + } catch (IllegalAccessException ignore) { + } catch (IllegalArgumentException ignore) { + } catch (InvocationTargetException ignore) { + } + } + } + } + } + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException { + return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a JSONArray + * which is produced from a Collection. + * + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, Collection value) throws JSONException { + return this.put(key, new JSONArray(value)); + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, double value) throws JSONException { + return this.put(key, Double.valueOf(value)); + } + + /** + * Put a key/float pair in the JSONObject. + * + * @param key A key string. + * @param value A float which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, float value) throws JSONException { + return this.put(key, Float.valueOf(value)); + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException { + return this.put(key, Integer.valueOf(value)); + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException { + return this.put(key, Long.valueOf(value)); + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a JSONObject + * which is produced from a Map. + * + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, Map value) throws JSONException { + return this.put(key, new JSONObject(value)); + } + + /** + * Put a key/value pair in the JSONObject. If the value is null, + * then the key will be removed from the JSONObject if it is present. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException { + if (key == null) { + throw new NullPointerException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + this.remove(key); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value are + * both non-null, and only if there is not already a member with that name. + * + * @param key key to insert into + * @param value value to insert + * @return this. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException { + if (key != null && value != null) { + if (this.opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + return this.put(key, value); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value are + * both non-null. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException { + if (key != null && value != null) { + return this.put(key, value); + } + return this; + } + + /** + * Uses a user initialized JSONPointer and tries to match it to an item within + * this JSONObject. For example, given a JSONObject initialized with this + * document: + * + *
              +	 * {
              +	 *     "a":{"b":"c"}
              +	 * }
              +	 * 
              + * + * and this JSONPointer: + * + *
              +	 * "/a/b"
              +	 * 
              + * + * Then this method will return the String "c". A JSONPointerException may be + * thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(JSONPointer jsonPointer) { + return jsonPointer.queryFrom(this); + } + + /** + * Creates a JSONPointer using an initialization string and tries to match it to + * an item within this JSONObject. For example, given a JSONObject initialized + * with this document: + * + *
              +	 * {
              +	 *     "a":{"b":"c"}
              +	 * }
              +	 * 
              + * + * and this JSONPointer string: + * + *
              +	 * "/a/b"
              +	 * 
              + * + * Then this method will return the String "c". A JSONPointerException may be + * thrown from code called by this method. + * + * @param jsonPointer string that can be used to create a JSONPointer + * @return the item matched by the JSONPointer, otherwise null + */ + public Object query(String jsonPointer) { + return query(new JSONPointer(jsonPointer)); + } + + /** + * Remove a name and its value, if present. + * + * @param key The name to be removed. + * @return The value that was associated with the name, or null if there was no + * value. + */ + public Object remove(String key) { + return this.map.remove(key); + } + + /** + * Determine if two JSONObjects are similar. They must contain the same set of + * names which must be associated with similar values. + * + * @param other The other JSONObject + * @return true if they are equal + */ + public boolean similar(Object other) { + try { + if (!(other instanceof JSONObject)) { + return false; + } + if (!this.keySet().equals(((JSONObject) other).keySet())) { + return false; + } + for (final Entry entry : this.entrySet()) { + String name = entry.getKey(); + Object valueThis = entry.getValue(); + Object valueOther = ((JSONObject) other).get(name); + if (valueThis == valueOther) { + continue; + } + if (valueThis == null) { + return false; + } + if (valueThis instanceof JSONObject) { + if (!((JSONObject) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof Number && valueOther instanceof Number) { + if (!isNumberSimilar((Number) valueThis, (Number) valueOther)) { + return false; + } + } else if (valueThis instanceof JSONString && valueOther instanceof JSONString) { + if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) { + return false; + } + } else if (!valueThis.equals(valueOther)) { + return false; + } + } + return true; + } catch (Throwable exception) { + return false; + } + } + + /** + * Produce a JSONArray containing the values of the members of this JSONObject. + * + * @param names A JSONArray containing a list of key strings. This determines + * the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray(JSONArray names) throws JSONException { + if (names == null || names.isEmpty()) { + return null; + } + JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Returns a java.util.Map containing all of the entries in this object. If an + * entry in the object is a JSONArray or JSONObject it will also be converted. + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @return a java.util.Map containing the entries of this object + */ + public Map toMap() { + Map results = new HashMap(); + for (Entry entry : this.entrySet()) { + Object value; + if (entry.getValue() == null || NULL.equals(entry.getValue())) { + value = null; + } else if (entry.getValue() instanceof JSONObject) { + value = ((JSONObject) entry.getValue()).toMap(); + } else if (entry.getValue() instanceof JSONArray) { + value = ((JSONArray) entry.getValue()).toList(); + } else { + value = entry.getValue(); + } + results.put(entry.getKey(), value); + } + return results; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace is added. + * If this would not result in a syntactically correct JSON text, then null will + * be returned instead. + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable representation of + * the object, beginning with { (left + * brace) and ending with } (right + * brace). + */ + @Override + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + /** + * Make a pretty-printed JSON text of this JSONObject. + * + *

              + * If + * + *

              {@code
              +	 * indentFactor > 0
              +	 * }
              + * + * and the {@link JSONObject} has only one key, then the object will be output + * on a single line: + * + *
              {@code {"key": 1}}
              + * + *

              + * If an object has 2 or more keys, then it will be output across multiple + * lines: + * + *

              {@code {
              +	 *  "key1": 1,
              +	 *  "key2": "value 2",
              +	 *  "key3": 3
              +	 * }}
              + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of indentation. + * @return a printable, displayable, portable, transmittable representation of + * the object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the object contains an invalid number. + */ + @SuppressWarnings("resource") + public String toString(int indentFactor) throws JSONException { + StringWriter w = new StringWriter(); + return this.write(w, indentFactor, 0).toString(); + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. For + * compactness, no whitespace is added. + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param writer the writer object + * @return The writer. + * @throws JSONException if a called function has an error + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. + * + *

              + * If + * + *

              {@code
              +	 * indentFactor > 0
              +	 * }
              + * + * and the {@link JSONObject} has only one key, then the object will be output + * on a single line: + * + *
              {@code {"key": 1}}
              + * + *

              + * If an object has 2 or more keys, then it will be output across multiple + * lines: + * + *

              {@code {
              +	 *  "key1": 1,
              +	 *  "key2": "value 2",
              +	 *  "key3": 3
              +	 * }}
              + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param writer Writes the serialized JSON + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indentation of the top level. + * @return The writer. + * @throws JSONException if a called function has an error or a write error + * occurs + */ + @SuppressWarnings("resource") + public Writer write(Writer writer, int indentFactor, int indent) throws JSONException { + try { + boolean needsComma = false; + final int length = this.length(); + writer.write('{'); + + if (length == 1) { + final Entry entry = this.entrySet().iterator().next(); + final String key = entry.getKey(); + writer.write(quote(key)); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + try { + writeValue(writer, entry.getValue(), indentFactor, indent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONObject value for key: " + key, e); + } + } else if (length != 0) { + final int newIndent = indent + indentFactor; + for (final Entry entry : this.entrySet()) { + if (needsComma) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, newIndent); + final String key = entry.getKey(); + writer.write(quote(key)); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + try { + writeValue(writer, entry.getValue(), indentFactor, newIndent); + } catch (Exception e) { + throw new JSONException("Unable to write JSONObject value for key: " + key, e); + } + needsComma = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, indent); + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } } diff --git a/src/main/java/org/json/JSONParserConfiguration.java b/src/main/java/org/json/JSONParserConfiguration.java index f95e2442..04c33859 100644 --- a/src/main/java/org/json/JSONParserConfiguration.java +++ b/src/main/java/org/json/JSONParserConfiguration.java @@ -5,22 +5,22 @@ package org.json; */ public class JSONParserConfiguration extends ParserConfiguration { - /** - * Configuration with the default values. - */ - public JSONParserConfiguration() { - super(); - } + /** + * Configuration with the default values. + */ + public JSONParserConfiguration() { + super(); + } - @Override - protected JSONParserConfiguration clone() { - return new JSONParserConfiguration(); - } + @Override + protected JSONParserConfiguration clone() { + return new JSONParserConfiguration(); + } - @SuppressWarnings("unchecked") - @Override - public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) { - return super.withMaxNestingDepth(maxNestingDepth); - } + @SuppressWarnings("unchecked") + @Override + public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) { + return super.withMaxNestingDepth(maxNestingDepth); + } } diff --git a/src/main/java/org/json/JSONPointer.java b/src/main/java/org/json/JSONPointer.java index 3553b063..77364017 100644 --- a/src/main/java/org/json/JSONPointer.java +++ b/src/main/java/org/json/JSONPointer.java @@ -19,269 +19,285 @@ Public Domain. * * In a nutshell, JSONPointer allows the user to navigate into a JSON document * using strings, and retrieve targeted objects, like a simple form of XPATH. - * Path segments are separated by the '/' char, which signifies the root of - * the document when it appears as the first char of the string. Array - * elements are navigated using ordinals, counting from 0. JSONPointer strings - * may be extended to any arbitrary number of segments. If the navigation - * is successful, the matched item is returned. A matched item may be a - * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building - * fails, an appropriate exception is thrown. If the navigation fails to find - * a match, a JSONPointerException is thrown. + * Path segments are separated by the '/' char, which signifies the root of the + * document when it appears as the first char of the string. Array elements are + * navigated using ordinals, counting from 0. JSONPointer strings may be + * extended to any arbitrary number of segments. If the navigation is + * successful, the matched item is returned. A matched item may be a JSONObject, + * a JSONArray, or a JSON value. If the JSONPointer string building fails, an + * appropriate exception is thrown. If the navigation fails to find a match, a + * JSONPointerException is thrown. * * @author JSON.org * @version 2016-05-14 */ public class JSONPointer { - // used for URL encoding and decoding - private static final String ENCODING = "utf-8"; + /** + * This class allows the user to build a JSONPointer in steps, using exactly one + * segment in each step. + */ + public static class Builder { - /** - * This class allows the user to build a JSONPointer in steps, using - * exactly one segment in each step. - */ - public static class Builder { + // Segments for the eventual JSONPointer string + private final List refTokens = new ArrayList(); - /** - * Constructs a new Builder object. - */ - public Builder() { - } + /** + * Constructs a new Builder object. + */ + public Builder() { + } - // Segments for the eventual JSONPointer string - private final List refTokens = new ArrayList(); + /** + * Adds an integer to the reference token list. Although not necessarily, mostly + * this token will denote an array index. + * + * @param arrayIndex the array index to be added to the token list + * @return {@code this} + */ + public Builder append(int arrayIndex) { + this.refTokens.add(String.valueOf(arrayIndex)); + return this; + } - /** - * Creates a {@code JSONPointer} instance using the tokens previously set using the - * {@link #append(String)} method calls. - * @return a JSONPointer object - */ - public JSONPointer build() { - return new JSONPointer(this.refTokens); - } + /** + * Adds an arbitrary token to the list of reference tokens. It can be any + * non-null value. + * + * Unlike in the case of JSON string or URI fragment representation of JSON + * pointers, the argument of this method MUST NOT be escaped. If you want to + * query the property called {@code "a~b"} then you should simply pass the + * {@code "a~b"} string as-is, there is no need to escape it as {@code "a~0b"}. + * + * @param token the new token to be appended to the list + * @return {@code this} + * @throws NullPointerException if {@code token} is null + */ + public Builder append(String token) { + if (token == null) { + throw new NullPointerException("token cannot be null"); + } + this.refTokens.add(token); + return this; + } - /** - * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. - * - * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the - * argument of this method MUST NOT be escaped. If you want to query the property called - * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no - * need to escape it as {@code "a~0b"}. - * - * @param token the new token to be appended to the list - * @return {@code this} - * @throws NullPointerException if {@code token} is null - */ - public Builder append(String token) { - if (token == null) { - throw new NullPointerException("token cannot be null"); - } - this.refTokens.add(token); - return this; - } + /** + * Creates a {@code JSONPointer} instance using the tokens previously set using + * the {@link #append(String)} method calls. + * + * @return a JSONPointer object + */ + public JSONPointer build() { + return new JSONPointer(this.refTokens); + } + } - /** - * Adds an integer to the reference token list. Although not necessarily, mostly this token will - * denote an array index. - * - * @param arrayIndex the array index to be added to the token list - * @return {@code this} - */ - public Builder append(int arrayIndex) { - this.refTokens.add(String.valueOf(arrayIndex)); - return this; - } - } + // used for URL encoding and decoding + private static final String ENCODING = "utf-8"; - /** - * Static factory method for {@link Builder}. Example usage: - * - *

              
              -     * JSONPointer pointer = JSONPointer.builder()
              -     *       .append("obj")
              -     *       .append("other~key").append("another/key")
              -     *       .append("\"")
              -     *       .append(0)
              -     *       .build();
              -     * 
              - * - * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained - * {@link Builder#append(String)} calls. - */ - public static Builder builder() { - return new Builder(); - } + /** + * Static factory method for {@link Builder}. Example usage: + * + *
              +	 * 
              +	 * JSONPointer pointer = JSONPointer.builder()
              +	 *       .append("obj")
              +	 *       .append("other~key").append("another/key")
              +	 *       .append("\"")
              +	 *       .append(0)
              +	 *       .build();
              +	 * 
              +	 * 
              + * + * @return a builder instance which can be used to construct a + * {@code JSONPointer} instance by chained + * {@link Builder#append(String)} calls. + */ + public static Builder builder() { + return new Builder(); + } - // Segments for the JSONPointer string - private final List refTokens; + /** + * Escapes path segment values to an unambiguous form. The escape char to be + * inserted is '~'. The chars to be escaped are ~, which maps to ~0, and /, + * which maps to ~1. + * + * @param token the JSONPointer segment value to be escaped + * @return the escaped value for the token + * + * @see rfc6901 section + * 3 + */ + private static String escape(String token) { + return token.replace("~", "~0").replace("/", "~1"); + } - /** - * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to - * evaluate the same JSON Pointer on different JSON documents then it is recommended - * to keep the {@code JSONPointer} instances due to performance considerations. - * - * @param pointer the JSON String or URI Fragment representation of the JSON pointer. - * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer - */ - public JSONPointer(final String pointer) { - if (pointer == null) { - throw new NullPointerException("pointer cannot be null"); - } - if (pointer.isEmpty() || pointer.equals("#")) { - this.refTokens = Collections.emptyList(); - return; - } - String refs; - if (pointer.startsWith("#/")) { - refs = pointer.substring(2); - try { - refs = URLDecoder.decode(refs, ENCODING); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } else if (pointer.startsWith("/")) { - refs = pointer.substring(1); - } else { - throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); - } - this.refTokens = new ArrayList(); - int slashIdx = -1; - int prevSlashIdx = 0; - do { - prevSlashIdx = slashIdx + 1; - slashIdx = refs.indexOf('/', prevSlashIdx); - if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { - // found 2 slashes in a row ( obj//next ) - // or single slash at the end of a string ( obj/test/ ) - this.refTokens.add(""); - } else if (slashIdx >= 0) { - final String token = refs.substring(prevSlashIdx, slashIdx); - this.refTokens.add(unescape(token)); - } else { - // last item after separator, or no separator at all. - final String token = refs.substring(prevSlashIdx); - this.refTokens.add(unescape(token)); - } - } while (slashIdx >= 0); - // using split does not take into account consecutive separators or "ending nulls" - //for (String token : refs.split("/")) { - // this.refTokens.add(unescape(token)); - //} - } - - /** - * Constructs a new JSONPointer instance with the provided list of reference tokens. - * - * @param refTokens A list of strings representing the reference tokens for the JSON Pointer. - * Each token identifies a step in the path to the targeted value. - */ - public JSONPointer(List refTokens) { - this.refTokens = new ArrayList(refTokens); - } - - /** - * @see rfc6901 section 3 - */ - private static String unescape(String token) { - return token.replace("~1", "/").replace("~0", "~"); - } - - /** - * Evaluates this JSON Pointer on the given {@code document}. The {@code document} - * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty - * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the - * returned value will be {@code document} itself. - * - * @param document the JSON document which should be the subject of querying. - * @return the result of the evaluation - * @throws JSONPointerException if an error occurs during evaluation - */ - public Object queryFrom(Object document) throws JSONPointerException { - if (this.refTokens.isEmpty()) { - return document; - } - Object current = document; - for (String token : this.refTokens) { - if (current instanceof JSONObject) { - current = ((JSONObject) current).opt(unescape(token)); - } else if (current instanceof JSONArray) { - current = readByIndexToken(current, token); - } else { - throw new JSONPointerException(format( - "value [%s] is not an array or object therefore its key %s cannot be resolved", current, - token)); - } - } - return current; - } - - /** - * Matches a JSONArray element by ordinal position - * @param current the JSONArray to be evaluated - * @param indexToken the array index in string form - * @return the matched object. If no matching item is found a - * @throws JSONPointerException is thrown if the index is out of bounds - */ - private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { - try { - int index = Integer.parseInt(indexToken); - JSONArray currentArr = (JSONArray) current; - if (index >= currentArr.length()) { - throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", indexToken, - Integer.valueOf(currentArr.length()))); - } - try { + /** + * Matches a JSONArray element by ordinal position + * + * @param current the JSONArray to be evaluated + * @param indexToken the array index in string form + * @return the matched object. If no matching item is found a + * @throws JSONPointerException is thrown if the index is out of bounds + */ + private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { + try { + int index = Integer.parseInt(indexToken); + JSONArray currentArr = (JSONArray) current; + if (index >= currentArr.length()) { + throw new JSONPointerException(format("index %s is out of bounds - the array has %d elements", + indexToken, Integer.valueOf(currentArr.length()))); + } + try { return currentArr.get(index); } catch (JSONException e) { throw new JSONPointerException("Error reading value at index position " + index, e); } - } catch (NumberFormatException e) { - throw new JSONPointerException(format("%s is not an array index", indexToken), e); - } - } + } catch (NumberFormatException e) { + throw new JSONPointerException(format("%s is not an array index", indexToken), e); + } + } - /** - * Returns a string representing the JSONPointer path value using string - * representation - */ - @Override - public String toString() { - StringBuilder rval = new StringBuilder(""); - for (String token: this.refTokens) { - rval.append('/').append(escape(token)); - } - return rval.toString(); - } + /** + * @see rfc6901 section + * 3 + */ + private static String unescape(String token) { + return token.replace("~1", "/").replace("~0", "~"); + } - /** - * Escapes path segment values to an unambiguous form. - * The escape char to be inserted is '~'. The chars to be escaped - * are ~, which maps to ~0, and /, which maps to ~1. - * @param token the JSONPointer segment value to be escaped - * @return the escaped value for the token - * - * @see rfc6901 section 3 - */ - private static String escape(String token) { - return token.replace("~", "~0") - .replace("/", "~1"); - } + // Segments for the JSONPointer string + private final List refTokens; + + /** + * Constructs a new JSONPointer instance with the provided list of reference + * tokens. + * + * @param refTokens A list of strings representing the reference tokens for the + * JSON Pointer. Each token identifies a step in the path to + * the targeted value. + */ + public JSONPointer(List refTokens) { + this.refTokens = new ArrayList(refTokens); + } + + /** + * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to + * evaluate the same JSON Pointer on different JSON documents then it is + * recommended to keep the {@code JSONPointer} instances due to performance + * considerations. + * + * @param pointer the JSON String or URI Fragment representation of the JSON + * pointer. + * @throws IllegalArgumentException if {@code pointer} is not a valid JSON + * pointer + */ + public JSONPointer(final String pointer) { + if (pointer == null) { + throw new NullPointerException("pointer cannot be null"); + } + if (pointer.isEmpty() || pointer.equals("#")) { + this.refTokens = Collections.emptyList(); + return; + } + String refs; + if (pointer.startsWith("#/")) { + refs = pointer.substring(2); + try { + refs = URLDecoder.decode(refs, ENCODING); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } else if (pointer.startsWith("/")) { + refs = pointer.substring(1); + } else { + throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); + } + this.refTokens = new ArrayList(); + int slashIdx = -1; + int prevSlashIdx = 0; + do { + prevSlashIdx = slashIdx + 1; + slashIdx = refs.indexOf('/', prevSlashIdx); + if (prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { + // found 2 slashes in a row ( obj//next ) + // or single slash at the end of a string ( obj/test/ ) + this.refTokens.add(""); + } else if (slashIdx >= 0) { + final String token = refs.substring(prevSlashIdx, slashIdx); + this.refTokens.add(unescape(token)); + } else { + // last item after separator, or no separator at all. + final String token = refs.substring(prevSlashIdx); + this.refTokens.add(unescape(token)); + } + } while (slashIdx >= 0); + // using split does not take into account consecutive separators or "ending + // nulls" + // for (String token : refs.split("/")) { + // this.refTokens.add(unescape(token)); + // } + } + + /** + * Evaluates this JSON Pointer on the given {@code document}. The + * {@code document} is usually a {@link JSONObject} or a {@link JSONArray} + * instance, but the empty JSON Pointer ({@code ""}) can be evaluated on any + * JSON values and in such case the returned value will be {@code document} + * itself. + * + * @param document the JSON document which should be the subject of querying. + * @return the result of the evaluation + * @throws JSONPointerException if an error occurs during evaluation + */ + public Object queryFrom(Object document) throws JSONPointerException { + if (this.refTokens.isEmpty()) { + return document; + } + Object current = document; + for (String token : this.refTokens) { + if (current instanceof JSONObject) { + current = ((JSONObject) current).opt(unescape(token)); + } else if (current instanceof JSONArray) { + current = readByIndexToken(current, token); + } else { + throw new JSONPointerException( + format("value [%s] is not an array or object therefore its key %s cannot be resolved", current, + token)); + } + } + return current; + } + + /** + * Returns a string representing the JSONPointer path value using string + * representation + */ + @Override + public String toString() { + StringBuilder rval = new StringBuilder(""); + for (String token : this.refTokens) { + rval.append('/').append(escape(token)); + } + return rval.toString(); + } + + /** + * Returns a string representing the JSONPointer path value using URI fragment + * identifier representation + * + * @return a uri fragment string + */ + public String toURIFragment() { + try { + StringBuilder rval = new StringBuilder("#"); + for (String token : this.refTokens) { + rval.append('/').append(URLEncoder.encode(token, ENCODING)); + } + return rval.toString(); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } - /** - * Returns a string representing the JSONPointer path value using URI - * fragment identifier representation - * @return a uri fragment string - */ - public String toURIFragment() { - try { - StringBuilder rval = new StringBuilder("#"); - for (String token : this.refTokens) { - rval.append('/').append(URLEncoder.encode(token, ENCODING)); - } - return rval.toString(); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - } diff --git a/src/main/java/org/json/JSONPointerException.java b/src/main/java/org/json/JSONPointerException.java index dc5a25ad..fffcd981 100644 --- a/src/main/java/org/json/JSONPointerException.java +++ b/src/main/java/org/json/JSONPointerException.java @@ -12,25 +12,26 @@ Public Domain. * @version 2016-05-13 */ public class JSONPointerException extends JSONException { - private static final long serialVersionUID = 8872944667561856751L; + private static final long serialVersionUID = 8872944667561856751L; - /** - * Constructs a new JSONPointerException with the specified error message. - * - * @param message The detail message describing the reason for the exception. - */ - public JSONPointerException(String message) { - super(message); - } + /** + * Constructs a new JSONPointerException with the specified error message. + * + * @param message The detail message describing the reason for the exception. + */ + public JSONPointerException(String message) { + super(message); + } - /** - * Constructs a new JSONPointerException with the specified error message and cause. - * - * @param message The detail message describing the reason for the exception. - * @param cause The cause of the exception. - */ - public JSONPointerException(String message, Throwable cause) { - super(message, cause); - } + /** + * Constructs a new JSONPointerException with the specified error message and + * cause. + * + * @param message The detail message describing the reason for the exception. + * @param cause The cause of the exception. + */ + public JSONPointerException(String message, Throwable cause) { + super(message, cause); + } } diff --git a/src/main/java/org/json/JSONPropertyIgnore.java b/src/main/java/org/json/JSONPropertyIgnore.java index d3a5bc5a..7930b7ff 100644 --- a/src/main/java/org/json/JSONPropertyIgnore.java +++ b/src/main/java/org/json/JSONPropertyIgnore.java @@ -12,12 +12,13 @@ import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Use this annotation on a getter method to override the Bean name - * parser for Bean -> JSONObject mapping. If this annotation is - * present at any level in the class hierarchy, then the method will - * not be serialized from the bean into the JSONObject. + * Use this annotation on a getter method to override the Bean name parser for + * Bean -> JSONObject mapping. If this annotation is present at any level in + * the class hierarchy, then the method will not be serialized from the bean + * into the JSONObject. */ @Documented @Retention(RUNTIME) -@Target({METHOD}) -public @interface JSONPropertyIgnore { } +@Target({ METHOD }) +public @interface JSONPropertyIgnore { +} diff --git a/src/main/java/org/json/JSONPropertyName.java b/src/main/java/org/json/JSONPropertyName.java index 0e4123f3..bb38e815 100644 --- a/src/main/java/org/json/JSONPropertyName.java +++ b/src/main/java/org/json/JSONPropertyName.java @@ -12,17 +12,18 @@ import java.lang.annotation.Retention; import java.lang.annotation.Target; /** - * Use this annotation on a getter method to override the Bean name - * parser for Bean -> JSONObject mapping. A value set to empty string "" + * Use this annotation on a getter method to override the Bean name parser for + * Bean -> JSONObject mapping. A value set to empty string "" * will have the Bean parser fall back to the default field name processing. */ @Documented @Retention(RUNTIME) -@Target({METHOD}) +@Target({ METHOD }) public @interface JSONPropertyName { - /** - * The value of the JSON property. - * @return The name of the property as to be used in the JSON Object. - */ - String value(); + /** + * The value of the JSON property. + * + * @return The name of the property as to be used in the JSON Object. + */ + String value(); } diff --git a/src/main/java/org/json/JSONString.java b/src/main/java/org/json/JSONString.java index ee82720a..ba65aed0 100644 --- a/src/main/java/org/json/JSONString.java +++ b/src/main/java/org/json/JSONString.java @@ -7,18 +7,17 @@ Public Domain. /** * The JSONString interface allows a toJSONString() * method so that a class can change the behavior of - * JSONObject.toString(), JSONArray.toString(), - * and JSONWriter.value(Object). The + * JSONObject.toString(), JSONArray.toString(), and + * JSONWriter.value(Object). The * toJSONString method will be used instead of the default behavior * of using the Object's toString() method and quoting the result. */ public interface JSONString { - /** - * The toJSONString method allows a class to produce its own JSON - * serialization. - * - * @return A strictly syntactically correct JSON text. - */ - public String toJSONString(); + /** + * The toJSONString method allows a class to produce its own JSON + * serialization. + * + * @return A strictly syntactically correct JSON text. + */ + public String toJSONString(); } - diff --git a/src/main/java/org/json/JSONStringer.java b/src/main/java/org/json/JSONStringer.java index 2f6cf9ed..04ab6db4 100644 --- a/src/main/java/org/json/JSONStringer.java +++ b/src/main/java/org/json/JSONStringer.java @@ -7,53 +7,57 @@ Public Domain. import java.io.StringWriter; /** - * JSONStringer provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of + * JSONStringer provides a quick and convenient way of producing JSON text. The + * texts produced strictly conform to JSON syntax rules. No whitespace is added, + * so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. *

              * A JSONStringer instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting cascade style. For example,

              - * myString = new JSONStringer()
              - *     .object()
              - *         .key("JSON")
              - *         .value("Hello, World!")
              - *     .endObject()
              - *     .toString();
              which produces the string
              - * {"JSON":"Hello, World!"}
              + * values to the text, and a key method for adding keys before + * values in objects. There are array and endArray + * methods that make and bound array values, and object and + * endObject methods which make and bound object values. All of + * these methods return the JSONWriter instance, permitting cascade style. For + * example, + * + *
              + * myString = new JSONStringer().object().key("JSON").value("Hello, World!").endObject().toString();
              + * 
              + * + * which produces the string + * + *
              + * {"JSON":"Hello, World!"}
              + * 
              *

              * The first method called must be array or object. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 200 levels deep. *

              * This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2015-12-09 */ public class JSONStringer extends JSONWriter { - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() { - super(new StringWriter()); - } + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer() { + super(new StringWriter()); + } - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * @return The JSON text. - */ - @Override - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } + /** + * Return the JSON text. This method is used to obtain the product of the + * JSONStringer instance. It will return null if there was a + * problem in the construction of the JSON text (such as the calls to + * array were not properly balanced with calls to + * endArray). + * + * @return The JSON text. + */ + @Override + public String toString() { + return this.mode == 'd' ? this.writer.toString() : null; + } } diff --git a/src/main/java/org/json/JSONTokener.java b/src/main/java/org/json/JSONTokener.java index 0bc6dfb6..13b74744 100644 --- a/src/main/java/org/json/JSONTokener.java +++ b/src/main/java/org/json/JSONTokener.java @@ -1,6 +1,11 @@ package org.json; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; import java.nio.charset.Charset; /* @@ -9,530 +14,529 @@ Public Domain. /** * A JSONTokener takes a source string and extracts characters and tokens from - * it. It is used by the JSONObject and JSONArray constructors to parse - * JSON source strings. + * it. It is used by the JSONObject and JSONArray constructors to parse JSON + * source strings. + * * @author JSON.org * @version 2014-05-03 */ public class JSONTokener { - /** current read character position on the current line. */ - private long character; - /** flag to indicate if the end of the input has been found. */ - private boolean eof; - /** current read index of the input. */ - private long index; - /** current line of the input. */ - private long line; - /** previous character read from the input. */ - private char previous; - /** Reader for the input. */ - private final Reader reader; - /** flag to indicate that a previous character was requested. */ - private boolean usePrevious; - /** the number of characters read in the previous line. */ - private long characterPreviousLine; + /** + * Get the hex value of a character (base16). + * + * @param c A character between '0' and '9' or between 'A' and 'F' or between + * 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. + */ + public static int dehexchar(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f') { + return c - ('a' - 10); + } + return -1; + } + /** current read character position on the current line. */ + private long character; + /** flag to indicate if the end of the input has been found. */ + private boolean eof; + /** current read index of the input. */ + private long index; + /** current line of the input. */ + private long line; + /** previous character read from the input. */ + private char previous; + /** Reader for the input. */ + private final Reader reader; + /** flag to indicate that a previous character was requested. */ + private boolean usePrevious; - /** - * Construct a JSONTokener from a Reader. The caller must close the Reader. - * - * @param reader A reader. - */ - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.characterPreviousLine = 0; - this.line = 1; - } + /** the number of characters read in the previous line. */ + private long characterPreviousLine; + /** + * Construct a JSONTokener from an InputStream. The caller must close the input + * stream. + * + * @param inputStream The source. + */ + public JSONTokener(InputStream inputStream) { + this(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); + } - /** - * Construct a JSONTokener from an InputStream. The caller must close the input stream. - * @param inputStream The source. - */ - public JSONTokener(InputStream inputStream) { - this(new InputStreamReader(inputStream, Charset.forName("UTF-8"))); - } + /** + * Construct a JSONTokener from a Reader. The caller must close the Reader. + * + * @param reader A reader. + */ + public JSONTokener(Reader reader) { + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.characterPreviousLine = 0; + this.line = 1; + } + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener(String s) { + this(new StringReader(s)); + } - /** - * Construct a JSONTokener from a string. - * - * @param s A source string. - */ - public JSONTokener(String s) { - this(new StringReader(s)); - } + /** + * Back up one character. This provides a sort of lookahead capability, so that + * you can test for a digit or letter before attempting to parse the next number + * or identifier. + * + * @throws JSONException Thrown if trying to step back more than 1 step or if + * already at the start of the string + */ + public void back() throws JSONException { + if (this.usePrevious || this.index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.decrementIndexes(); + this.usePrevious = true; + this.eof = false; + } + /** + * Closes the underlying reader, releasing any resources associated with it. + * + * @throws IOException If an I/O error occurs while closing the reader. + */ + public void close() throws IOException { + if (reader != null) { + reader.close(); + } + } - /** - * Back up one character. This provides a sort of lookahead capability, - * so that you can test for a digit or letter before attempting to parse - * the next number or identifier. - * @throws JSONException Thrown if trying to step back more than 1 step - * or if already at the start of the string - */ - public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.decrementIndexes(); - this.usePrevious = true; - this.eof = false; - } + /** + * Decrements the indexes for the {@link #back()} method based on the previous + * character read. + */ + private void decrementIndexes() { + this.index--; + if (this.previous == '\r' || this.previous == '\n') { + this.line--; + this.character = this.characterPreviousLine; + } else if (this.character > 0) { + this.character--; + } + } - /** - * Decrements the indexes for the {@link #back()} method based on the previous character read. - */ - private void decrementIndexes() { - this.index--; - if(this.previous=='\r' || this.previous == '\n') { - this.line--; - this.character=this.characterPreviousLine ; - } else if(this.character > 0){ - this.character--; - } - } + /** + * Checks if the end of the input has been reached. + * + * @return true if at the end of the file and we didn't step back + */ + public boolean end() { + return this.eof && !this.usePrevious; + } - /** - * Get the hex value of a character (base16). - * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. - */ - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - if (c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if (c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } + /** + * Get the last character read from the input or '\0' if nothing has been read + * yet. + * + * @return the last character read from the input. + */ + protected char getPrevious() { + return this.previous; + } - /** - * Checks if the end of the input has been reached. - * - * @return true if at the end of the file and we didn't step back - */ - public boolean end() { - return this.eof && !this.usePrevious; - } + /** + * Increments the internal indexes according to the previous character read and + * the character passed as the current character. + * + * @param c the current character read. + */ + private void incrementIndexes(int c) { + if (c > 0) { + this.index++; + if (c == '\r') { + this.line++; + this.characterPreviousLine = this.character; + this.character = 0; + } else if (c == '\n') { + if (this.previous != '\r') { + this.line++; + this.characterPreviousLine = this.character; + } + this.character = 0; + } else { + this.character++; + } + } + } + /** + * Determine if the source string still contains characters that next() can + * consume. + * + * @return true if not yet at the end of the source. + * @throws JSONException thrown if there is an error stepping forward or + * backward while checking for more data. + */ + public boolean more() throws JSONException { + if (this.usePrevious) { + return true; + } + try { + this.reader.mark(1); + } catch (IOException e) { + throw new JSONException("Unable to preserve stream position", e); + } + try { + // -1 is EOF, but next() can not consume the null character '\0' + if (this.reader.read() <= 0) { + this.eof = true; + return false; + } + this.reader.reset(); + } catch (IOException e) { + throw new JSONException("Unable to read the next character from the stream", e); + } + return true; + } - /** - * Determine if the source string still contains characters that next() - * can consume. - * @return true if not yet at the end of the source. - * @throws JSONException thrown if there is an error stepping forward - * or backward while checking for more data. - */ - public boolean more() throws JSONException { - if(this.usePrevious) { - return true; - } - try { - this.reader.mark(1); - } catch (IOException e) { - throw new JSONException("Unable to preserve stream position", e); - } - try { - // -1 is EOF, but next() can not consume the null character '\0' - if(this.reader.read() <= 0) { - this.eof = true; - return false; - } - this.reader.reset(); - } catch (IOException e) { - throw new JSONException("Unable to read the next character from the stream", e); - } - return true; - } + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + * @throws JSONException Thrown if there is an error reading the source string. + */ + public char next() throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (IOException exception) { + throw new JSONException(exception); + } + } + if (c <= 0) { // End of stream + this.eof = true; + return 0; + } + this.incrementIndexes(c); + this.previous = (char) c; + return this.previous; + } + /** + * Consume the next character, and check that it matches a specified character. + * + * @param c The character to match. + * @return The character. + * @throws JSONException if the character does not match. + */ + public char next(char c) throws JSONException { + char n = this.next(); + if (n != c) { + if (n > 0) { + throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); + } + throw this.syntaxError("Expected '" + c + "' and instead saw ''"); + } + return n; + } - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - * @throws JSONException Thrown if there is an error reading the source string. - */ - public char next() throws JSONException { - int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch (IOException exception) { - throw new JSONException(exception); - } - } - if (c <= 0) { // End of stream - this.eof = true; - return 0; - } - this.incrementIndexes(c); - this.previous = (char) c; - return this.previous; - } + /** + * Get the next n characters. + * + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not n characters + * remaining in the source string. + */ + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } - /** - * Get the last character read from the input or '\0' if nothing has been read yet. - * @return the last character read from the input. - */ - protected char getPrevious() { return this.previous;} + char[] chars = new char[n]; + int pos = 0; - /** - * Increments the internal indexes according to the previous character - * read and the character passed as the current character. - * @param c the current character read. - */ - private void incrementIndexes(int c) { - if(c > 0) { - this.index++; - if(c=='\r') { - this.line++; - this.characterPreviousLine = this.character; - this.character=0; - }else if (c=='\n') { - if(this.previous != '\r') { - this.line++; - this.characterPreviousLine = this.character; - } - this.character=0; - } else { - this.character++; - } - } - } + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } - /** - * Consume the next character, and check that it matches a specified - * character. - * @param c The character to match. - * @return The character. - * @throws JSONException if the character does not match. - */ - public char next(char c) throws JSONException { - char n = this.next(); - if (n != c) { - if(n > 0) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); - } - throw this.syntaxError("Expected '" + c + "' and instead saw ''"); - } - return n; - } + /** + * Get the next char in the string, skipping whitespace. + * + * @throws JSONException Thrown if there is an error reading the source string. + * @return A character, or 0 if there are no more characters. + */ + public char nextClean() throws JSONException { + for (;;) { + char c = this.next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + Object nextSimpleValue(char c) { + String string; - /** - * Get the next n characters. - * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. - */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } + switch (c) { + case '"': + case '\'': + return this.nextString(c); + } - char[] chars = new char[n]; - int pos = 0; + /* + * Handle unquoted text. This could be the values true, false, or null, or it + * can be a number. An implementation (such as this one) is allowed to also + * accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a formatting + * character. + */ - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } + StringBuilder sb = new StringBuilder(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = this.next(); + } + if (!this.eof) { + this.back(); + } + string = sb.toString().trim(); + if ("".equals(string)) { + throw this.syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } - /** - * Get the next char in the string, skipping whitespace. - * @throws JSONException Thrown if there is an error reading the source string. - * @return A character, or 0 if there are no more characters. - */ - public char nextClean() throws JSONException { - for (;;) { - char c = this.next(); - if (c == 0 || c > ' ') { - return c; - } - } - } + /** + * Return the characters up to the next close quote character. Backslash + * processing is done. The formal JSON format does not allow strings in single + * quotes, but an implementation is allowed to accept them. + * + * @param quote The quoting character, either " (double + * quote) or ' (single + * quote). + * @return A String. + * @throws JSONException Unterminated string. + */ + public String nextString(char quote) throws JSONException { + char c; + StringBuilder sb = new StringBuilder(); + for (;;) { + c = this.next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); + case '\\': + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + try { + sb.append((char) Integer.parseInt(this.next(4), 16)); + } catch (NumberFormatException e) { + throw this.syntaxError("Illegal escape.", e); + } + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + /** + * Get the text up but not including the specified character or the end of line, + * whichever comes first. + * + * @param delimiter A delimiter character. + * @return A string. + * @throws JSONException Thrown if there is an error while searching for the + * delimiter + */ + public String nextTo(char delimiter) throws JSONException { + StringBuilder sb = new StringBuilder(); + for (;;) { + char c = this.next(); + if (c == delimiter || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } - /** - * Return the characters up to the next close quote character. - * Backslash processing is done. The formal JSON format does not - * allow strings in single quotes, but an implementation is allowed to - * accept them. - * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. - * @throws JSONException Unterminated string. - */ - public String nextString(char quote) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (;;) { - c = this.next(); - switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - try { - sb.append((char)Integer.parseInt(this.next(4), 16)); - } catch (NumberFormatException e) { - throw this.syntaxError("Illegal escape.", e); - } - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } + /** + * Get the text up but not including one of the specified delimiter characters + * or the end of line, whichever comes first. + * + * @param delimiters A set of delimiter characters. + * @return A string, trimmed. + * @throws JSONException Thrown if there is an error while searching for the + * delimiter + */ + public String nextTo(String delimiters) throws JSONException { + char c; + StringBuilder sb = new StringBuilder(); + for (;;) { + c = this.next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + /** + * Get the next value. The value can be a Boolean, Double, Integer, JSONArray, + * JSONObject, Long, or String, or the JSONObject.NULL object. + * + * @throws JSONException If syntax error. + * + * @return An object. + */ + public Object nextValue() throws JSONException { + char c = this.nextClean(); + switch (c) { + case '{': + this.back(); + try { + return new JSONObject(this); + } catch (StackOverflowError e) { + throw new JSONException("JSON Array or Object depth too large to process.", e); + } + case '[': + this.back(); + try { + return new JSONArray(this); + } catch (StackOverflowError e) { + throw new JSONException("JSON Array or Object depth too large to process.", e); + } + } + return nextSimpleValue(c); + } - /** - * Get the text up but not including the specified character or the - * end of line, whichever comes first. - * @param delimiter A delimiter character. - * @return A string. - * @throws JSONException Thrown if there is an error while searching - * for the delimiter - */ - public String nextTo(char delimiter) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (;;) { - char c = this.next(); - if (c == delimiter || c == 0 || c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } + /** + * Skip characters until the next character is the requested character. If the + * requested character is not found, no characters are skipped. + * + * @param to A character to skip to. + * @return The requested character, or zero if the requested character is not + * found. + * @throws JSONException Thrown if there is an error while searching for the to + * character + */ + public char skipTo(char to) throws JSONException { + char c; + try { + long startIndex = this.index; + long startCharacter = this.character; + long startLine = this.line; + this.reader.mark(1000000); + do { + c = this.next(); + if (c == 0) { + // in some readers, reset() may throw an exception if + // the remaining portion of the input is greater than + // the mark size (1,000,000 above). + this.reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return 0; + } + } while (c != to); + this.reader.mark(1); + } catch (IOException exception) { + throw new JSONException(exception); + } + this.back(); + return c; + } + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message) { + return new JSONException(message + this.toString()); + } - /** - * Get the text up but not including one of the specified delimiter - * characters or the end of line, whichever comes first. - * @param delimiters A set of delimiter characters. - * @return A string, trimmed. - * @throws JSONException Thrown if there is an error while searching - * for the delimiter - */ - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (;;) { - c = this.next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @param causedBy The throwable that caused the error. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message, Throwable causedBy) { + return new JSONException(message + this.toString(), causedBy); + } - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. - * - * @return An object. - */ - public Object nextValue() throws JSONException { - char c = this.nextClean(); - switch (c) { - case '{': - this.back(); - try { - return new JSONObject(this); - } catch (StackOverflowError e) { - throw new JSONException("JSON Array or Object depth too large to process.", e); - } - case '[': - this.back(); - try { - return new JSONArray(this); - } catch (StackOverflowError e) { - throw new JSONException("JSON Array or Object depth too large to process.", e); - } - } - return nextSimpleValue(c); - } - - Object nextSimpleValue(char c) { - String string; - - switch (c) { - case '"': - case '\'': - return this.nextString(c); - } - - /* - * Handle unquoted text. This could be the values true, false, or - * null, or it can be a number. An implementation (such as this one) - * is allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuilder sb = new StringBuilder(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = this.next(); - } - if (!this.eof) { - this.back(); - } - - string = sb.toString().trim(); - if ("".equals(string)) { - throw this.syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - - /** - * Skip characters until the next character is the requested character. - * If the requested character is not found, no characters are skipped. - * @param to A character to skip to. - * @return The requested character, or zero if the requested character - * is not found. - * @throws JSONException Thrown if there is an error while searching - * for the to character - */ - public char skipTo(char to) throws JSONException { - char c; - try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do { - c = this.next(); - if (c == 0) { - // in some readers, reset() may throw an exception if - // the remaining portion of the input is greater than - // the mark size (1,000,000 above). - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return 0; - } - } while (c != to); - this.reader.mark(1); - } catch (IOException exception) { - throw new JSONException(exception); - } - this.back(); - return c; - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) { - return new JSONException(message + this.toString()); - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @param causedBy The throwable that caused the error. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message, Throwable causedBy) { - return new JSONException(message + this.toString(), causedBy); - } - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - @Override - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; - } - - /** - * Closes the underlying reader, releasing any resources associated with it. - * - * @throws IOException If an I/O error occurs while closing the reader. - */ - public void close() throws IOException { - if(reader!=null){ - reader.close(); - } - } + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + @Override + public String toString() { + return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; + } } diff --git a/src/main/java/org/json/JSONWriter.java b/src/main/java/org/json/JSONWriter.java index 11f4a5c7..8df044a1 100644 --- a/src/main/java/org/json/JSONWriter.java +++ b/src/main/java/org/json/JSONWriter.java @@ -9,386 +9,385 @@ Public Domain. */ /** - * JSONWriter provides a quick and convenient way of producing JSON text. - * The texts produced strictly conform to JSON syntax rules. No whitespace is - * added, so the results are ready for transmission or storage. Each instance of + * JSONWriter provides a quick and convenient way of producing JSON text. The + * texts produced strictly conform to JSON syntax rules. No whitespace is added, + * so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. *

              * A JSONWriter instance provides a value method for appending - * values to the - * text, and a key - * method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and - * object and endObject methods which make and bound - * object values. All of these methods return the JSONWriter instance, - * permitting a cascade style. For example,

              - * new JSONWriter(myWriter)
              - *     .object()
              - *         .key("JSON")
              - *         .value("Hello, World!")
              - *     .endObject();
              which writes
              - * {"JSON":"Hello, World!"}
              + * values to the text, and a key method for adding keys before + * values in objects. There are array and endArray + * methods that make and bound array values, and object and + * endObject methods which make and bound object values. All of + * these methods return the JSONWriter instance, permitting a cascade style. For + * example, + * + *
              + * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
              + * 
              + * + * which writes + * + *
              + * {"JSON":"Hello, World!"}
              + * 
              *

              * The first method called must be array or object. * There are no methods for adding commas or colons. JSONWriter adds them for * you. Objects and arrays can be nested up to 200 levels deep. *

              * This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2016-08-08 */ public class JSONWriter { - private static final int maxdepth = 200; + private static final int maxdepth = 200; - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce the + * JSON text. The method is required to produce a strictly conforming text. If + * the object does not contain a toJSONString method (which is the most common + * case), then a text will be produced by other means. If the value is an array + * or Collection, then a JSONArray will be made from it and its toJSONString + * method will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the value's + * toString method will be called, and the result will be quoted. + * + *

              + * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @return a printable, displayable, transmittable representation of the object, + * beginning with { (left brace) and + * ending with } (right brace). + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + String object; + try { + object = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (object != null) { + return object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number) { + // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex + final String numberAsString = JSONObject.numberToString((Number) value); + if (JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { + // Close enough to a JSON number that we will return it unquoted + return numberAsString; + } + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + return JSONObject.quote(numberAsString); + } + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + Map map = (Map) value; + return new JSONObject(map).toString(); + } + if (value instanceof Collection) { + Collection coll = (Collection) value; + return new JSONArray(coll).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + if (value instanceof Enum) { + return JSONObject.quote(((Enum) value).name()); + } + return JSONObject.quote(value.toString()); + } - /** - * The current mode. Values: - * 'a' (array), - * 'd' (done), - * 'i' (initial), - * 'k' (key), - * 'o' (object). - */ - protected char mode; + /** + * The comma flag determines if a comma should be output before the next value. + */ + private boolean comma; - /** - * The object/array stack. - */ - private final JSONObject stack[]; + /** + * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' (key), + * 'o' (object). + */ + protected char mode; - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; + /** + * The object/array stack. + */ + private final JSONObject stack[]; - /** - * The writer that will receive the output. - */ - protected Appendable writer; + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - * @param w an appendable object - */ - public JSONWriter(Appendable w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } + /** + * The writer that will receive the output. + */ + protected Appendable writer; - /** - * Append a value. - * @param string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.append(','); - } - this.writer.append(string); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } + /** + * Make a fresh JSONWriter. It can be used to build one JSON text. + * + * @param w an appendable object + */ + public JSONWriter(Appendable w) { + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } + /** + * Append a value. + * + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.append(','); + } + this.writer.append(string); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } - /** - * End something. - * @param m Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char m, char c) throws JSONException { - if (this.mode != m) { - throw new JSONException(m == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(m); - try { - this.writer.append(c); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - this.comma = true; - return this; - } + /** + * Begin appending a new array. All values until the balancing + * endArray will be appended to this array. The + * endArray method must be called to mark the array's end. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is started + * in the wrong place (for example as a key or after the + * end of the outermost array or object). + */ + public JSONWriter array() throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } - /** - * End an array. This method most be called to balance calls to - * array. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } + /** + * End something. + * + * @param m Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char m, char c) throws JSONException { + if (this.mode != m) { + throw new JSONException(m == 'a' ? "Misplaced endArray." : "Misplaced endObject."); + } + this.pop(m); + try { + this.writer.append(c); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + this.comma = true; + return this; + } - /** - * End an object. This method most be called to balance calls to - * object. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } + /** + * End an array. This method most be called to balance calls to + * array. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException { + return this.end('a', ']'); + } - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * @param string A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - JSONObject topObject = this.stack[this.top - 1]; - // don't use the built in putOnce method to maintain Android support - if(topObject.has(string)) { + /** + * End an object. This method most be called to balance calls to + * object. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException { + return this.end('k', '}'); + } + + /** + * Append a key. The key will be associated with the next value. In an object, + * every value must be preceded by a key. + * + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys do not + * belong in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + JSONObject topObject = this.stack[this.top - 1]; + // don't use the built in putOnce method to maintain Android support + if (topObject.has(string)) { throw new JSONException("Duplicate key \"" + string + "\""); } - topObject.put(string, true); - if (this.comma) { - this.writer.append(','); - } - this.writer.append(JSONObject.quote(string)); - this.writer.append(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } + topObject.put(string, true); + if (this.comma) { + this.writer.append(','); + } + this.writer.append(JSONObject.quote(string)); + this.writer.append(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } + /** + * Begin appending a new object. All keys and values until the balancing + * endObject will be appended to this object. The + * endObject method must be called to mark the object's end. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is started + * in the wrong place (for example as a key or after the + * end of the outermost array or object). + */ + public JSONWriter object() throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); + } - } + /** + * Pop an array or object scope. + * + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; + } + /** + * Push an array or object scope. + * + * @param jo The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } + /** + * Append either the value true or the value false. + * + * @param b A boolean. + * @return this + * @throws JSONException if a called function has an error + */ + public JSONWriter value(boolean b) throws JSONException { + return this.append(b ? "true" : "false"); + } - /** - * Push an array or object scope. - * @param jo The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } + /** + * Append a double value. + * + * @param d A double. + * @return this + * @throws JSONException If the number is not finite. + */ + public JSONWriter value(double d) throws JSONException { + return this.value(Double.valueOf(d)); + } - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce the - * JSON text. The method is required to produce a strictly conforming text. - * If the object does not contain a toJSONString method (which is the most - * common case), then a text will be produced by other means. If the value - * is an array or Collection, then a JSONArray will be made from it and its - * toJSONString method will be called. If the value is a MAP, then a - * JSONObject will be made from it and its toJSONString method will be - * called. Otherwise, the value's toString method will be called, and the - * result will be quoted. - * - *

              - * Warning: This method assumes that the data structure is acyclical. - * - * @param value - * The value to be serialized. - * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - String object; - try { - object = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (object != null) { - return object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if (value instanceof Number) { - // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex - final String numberAsString = JSONObject.numberToString((Number) value); - if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { - // Close enough to a JSON number that we will return it unquoted - return numberAsString; - } - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - return JSONObject.quote(numberAsString); - } - if (value instanceof Boolean || value instanceof JSONObject - || value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - Map map = (Map) value; - return new JSONObject(map).toString(); - } - if (value instanceof Collection) { - Collection coll = (Collection) value; - return new JSONArray(coll).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - if(value instanceof Enum){ - return JSONObject.quote(((Enum)value).name()); - } - return JSONObject.quote(value.toString()); - } + /** + * Append a long value. + * + * @param l A long. + * @return this + * @throws JSONException if a called function has an error + */ + public JSONWriter value(long l) throws JSONException { + return this.append(Long.toString(l)); + } - /** - * Append either the value true or the value - * false. - * @param b A boolean. - * @return this - * @throws JSONException if a called function has an error - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * @param d A double. - * @return this - * @throws JSONException If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(Double.valueOf(d)); - } - - /** - * Append a long value. - * @param l A long. - * @return this - * @throws JSONException if a called function has an error - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - - /** - * Append an object value. - * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(valueToString(object)); - } + /** + * Append an object value. + * + * @param object The object to append. It can be null, or a Boolean, Number, + * String, JSONObject, or JSONArray, or an object that implements + * JSONString. + * @return this + * @throws JSONException If the value is out of sequence. + */ + public JSONWriter value(Object object) throws JSONException { + return this.append(valueToString(object)); + } } diff --git a/src/main/java/org/json/ParserConfiguration.java b/src/main/java/org/json/ParserConfiguration.java index 5cdc10d8..84d090b4 100644 --- a/src/main/java/org/json/ParserConfiguration.java +++ b/src/main/java/org/json/ParserConfiguration.java @@ -6,121 +6,128 @@ Public Domain. /** * Configuration base object for parsers. The configuration is immutable. */ -@SuppressWarnings({""}) +@SuppressWarnings({ "" }) public class ParserConfiguration { - /** - * Used to indicate there's no defined limit to the maximum nesting depth when parsing a document. - */ - public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1; + /** + * Used to indicate there's no defined limit to the maximum nesting depth when + * parsing a document. + */ + public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1; - /** - * The default maximum nesting depth when parsing a document. - */ - public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; + /** + * The default maximum nesting depth when parsing a document. + */ + public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; - /** - * Specifies if values should be kept as strings (true), or if - * they should try to be guessed into JSON values (numeric, boolean, string) - */ - protected boolean keepStrings; + /** + * Specifies if values should be kept as strings (true), or if they + * should try to be guessed into JSON values (numeric, boolean, string) + */ + protected boolean keepStrings; - /** - * The maximum nesting depth when parsing a document. - */ - protected int maxNestingDepth; + /** + * The maximum nesting depth when parsing a document. + */ + protected int maxNestingDepth; - /** - * Constructs a new ParserConfiguration with default settings. - */ - public ParserConfiguration() { - this.keepStrings = false; - this.maxNestingDepth = DEFAULT_MAXIMUM_NESTING_DEPTH; - } + /** + * Constructs a new ParserConfiguration with default settings. + */ + public ParserConfiguration() { + this.keepStrings = false; + this.maxNestingDepth = DEFAULT_MAXIMUM_NESTING_DEPTH; + } - /** - * Constructs a new ParserConfiguration with the specified settings. - * - * @param keepStrings A boolean indicating whether to preserve strings during parsing. - * @param maxNestingDepth An integer representing the maximum allowed nesting depth. - */ - protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) { - this.keepStrings = keepStrings; - this.maxNestingDepth = maxNestingDepth; - } + /** + * Constructs a new ParserConfiguration with the specified settings. + * + * @param keepStrings A boolean indicating whether to preserve strings + * during parsing. + * @param maxNestingDepth An integer representing the maximum allowed nesting + * depth. + */ + protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) { + this.keepStrings = keepStrings; + this.maxNestingDepth = maxNestingDepth; + } - /** - * Provides a new instance of the same configuration. - */ - @Override - protected ParserConfiguration clone() { - // future modifications to this method should always ensure a "deep" - // clone in the case of collections. i.e. if a Map is added as a configuration - // item, a new map instance should be created and if possible each value in the - // map should be cloned as well. If the values of the map are known to also - // be immutable, then a shallow clone of the map is acceptable. - return new ParserConfiguration( - this.keepStrings, - this.maxNestingDepth - ); - } + /** + * Provides a new instance of the same configuration. + */ + @Override + protected ParserConfiguration clone() { + // future modifications to this method should always ensure a "deep" + // clone in the case of collections. i.e. if a Map is added as a configuration + // item, a new map instance should be created and if possible each value in the + // map should be cloned as well. If the values of the map are known to also + // be immutable, then a shallow clone of the map is acceptable. + return new ParserConfiguration(this.keepStrings, this.maxNestingDepth); + } - /** - * When parsing the XML into JSONML, specifies if values should be kept as strings (true), or if - * they should try to be guessed into JSON values (numeric, boolean, string) - * - * @return The keepStrings configuration value. - */ - public boolean isKeepStrings() { - return this.keepStrings; - } + /** + * The maximum nesting depth that the parser will descend before throwing an + * exception when parsing the XML into JSONML. + * + * @return the maximum nesting depth set for this configuration + */ + public int getMaxNestingDepth() { + return maxNestingDepth; + } - /** - * When parsing the XML into JSONML, specifies if values should be kept as strings (true), or if - * they should try to be guessed into JSON values (numeric, boolean, string) - * - * @param newVal - * new value to use for the keepStrings configuration option. - * @param the type of the configuration object - * - * @return The existing configuration will not be modified. A new configuration is returned. - */ - @SuppressWarnings("unchecked") - public T withKeepStrings(final boolean newVal) { - T newConfig = (T)this.clone(); - newConfig.keepStrings = newVal; - return newConfig; - } + /** + * When parsing the XML into JSONML, specifies if values should be kept as + * strings (true), or if they should try to be guessed into JSON + * values (numeric, boolean, string) + * + * @return The keepStrings configuration value. + */ + public boolean isKeepStrings() { + return this.keepStrings; + } - /** - * The maximum nesting depth that the parser will descend before throwing an exception - * when parsing the XML into JSONML. - * @return the maximum nesting depth set for this configuration - */ - public int getMaxNestingDepth() { - return maxNestingDepth; - } + /** + * When parsing the XML into JSONML, specifies if values should be kept as + * strings (true), or if they should try to be guessed into JSON + * values (numeric, boolean, string) + * + * @param newVal new value to use for the keepStrings configuration + * option. + * @param the type of the configuration object + * + * @return The existing configuration will not be modified. A new configuration + * is returned. + */ + @SuppressWarnings("unchecked") + public T withKeepStrings(final boolean newVal) { + T newConfig = (T) this.clone(); + newConfig.keepStrings = newVal; + return newConfig; + } - /** - * Defines the maximum nesting depth that the parser will descend before throwing an exception - * when parsing the XML into JSONML. The default max nesting depth is 512, which means the parser - * will throw a JsonException if the maximum depth is reached. - * Using any negative value as a parameter is equivalent to setting no limit to the nesting depth, - * which means the parses will go as deep as the maximum call stack size allows. - * @param maxNestingDepth the maximum nesting depth allowed to the XML parser - * @param the type of the configuration object - * - * @return The existing configuration will not be modified. A new configuration is returned. - */ - @SuppressWarnings("unchecked") - public T withMaxNestingDepth(int maxNestingDepth) { - T newConfig = (T)this.clone(); + /** + * Defines the maximum nesting depth that the parser will descend before + * throwing an exception when parsing the XML into JSONML. The default max + * nesting depth is 512, which means the parser will throw a JsonException if + * the maximum depth is reached. Using any negative value as a parameter is + * equivalent to setting no limit to the nesting depth, which means the parses + * will go as deep as the maximum call stack size allows. + * + * @param maxNestingDepth the maximum nesting depth allowed to the XML parser + * @param the type of the configuration object + * + * @return The existing configuration will not be modified. A new configuration + * is returned. + */ + @SuppressWarnings("unchecked") + public T withMaxNestingDepth(int maxNestingDepth) { + T newConfig = (T) this.clone(); - if (maxNestingDepth > UNDEFINED_MAXIMUM_NESTING_DEPTH) { - newConfig.maxNestingDepth = maxNestingDepth; - } else { - newConfig.maxNestingDepth = UNDEFINED_MAXIMUM_NESTING_DEPTH; - } + if (maxNestingDepth > UNDEFINED_MAXIMUM_NESTING_DEPTH) { + newConfig.maxNestingDepth = maxNestingDepth; + } else { + newConfig.maxNestingDepth = UNDEFINED_MAXIMUM_NESTING_DEPTH; + } - return newConfig; - } + return newConfig; + } } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketInputBuffer.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketInputBuffer.java index 57c40d1d..8c8a0719 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketInputBuffer.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketInputBuffer.java @@ -7,35 +7,36 @@ import java.io.InputStream; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface GamePacketInputBuffer extends DataInput { - void skipAllBytes(int n) throws IOException; + int available() throws IOException; + + byte[] readByteArrayMC() throws IOException; + + String readStringEaglerASCII16() throws IOException; + + String readStringEaglerASCII8() throws IOException; + + String readStringMC(int maxLen) throws IOException; int readVarInt() throws IOException; long readVarLong() throws IOException; - String readStringMC(int maxLen) throws IOException; - - String readStringEaglerASCII8() throws IOException; - - String readStringEaglerASCII16() throws IOException; - - byte[] readByteArrayMC() throws IOException; - - int available() throws IOException; + void skipAllBytes(int n) throws IOException; InputStream stream(); diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketOutputBuffer.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketOutputBuffer.java index bf193736..0d2d37b9 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketOutputBuffer.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePacketOutputBuffer.java @@ -7,33 +7,24 @@ import java.io.OutputStream; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface GamePacketOutputBuffer extends DataOutput { - void writeVarInt(int i) throws IOException; - - void writeVarLong(long i) throws IOException; - - void writeStringMC(String str) throws IOException; - - void writeStringEaglerASCII8(String str) throws IOException; - - void writeStringEaglerASCII16(String str) throws IOException; - - void writeByteArrayMC(byte[] bytes) throws IOException; - - OutputStream stream(); + public static int getArrayMCSize(int len) { + return getVarIntSize(len) + len; + } public static int getVarIntSize(int input) { for (int i = 1; i < 5; ++i) { @@ -55,7 +46,17 @@ public interface GamePacketOutputBuffer extends DataOutput { return 9; } - public static int getArrayMCSize(int len) { - return getVarIntSize(len) + len; - } + OutputStream stream(); + + void writeByteArrayMC(byte[] bytes) throws IOException; + + void writeStringEaglerASCII16(String str) throws IOException; + + void writeStringEaglerASCII8(String str) throws IOException; + + void writeStringMC(String str) throws IOException; + + void writeVarInt(int i) throws IOException; + + void writeVarLong(long i) throws IOException; } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageConstants.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageConstants.java index ca54621c..05bdbad0 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageConstants.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageConstants.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.socket.protocol; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,7 +30,7 @@ public class GamePluginMessageConstants { public static final int SERVER_TO_CLIENT = 1; public static String getDirectionString(int dir) { - switch(dir) { + switch (dir) { case CLIENT_TO_SERVER: return "CLIENT_TO_SERVER"; case SERVER_TO_CLIENT: @@ -40,7 +41,7 @@ public class GamePluginMessageConstants { } public static int oppositeDirection(int dir) { - switch(dir) { + switch (dir) { case CLIENT_TO_SERVER: return SERVER_TO_CLIENT; case SERVER_TO_CLIENT: diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageProtocol.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageProtocol.java index 6de32a7a..0b8e1f1a 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageProtocol.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/GamePluginMessageProtocol.java @@ -1,10 +1,13 @@ package net.lax1dude.eaglercraft.v1_8.socket.protocol; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.*; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; - -import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.*; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.CLIENT_TO_SERVER; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.SERVER_TO_CLIENT; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.V3_CAPE_CHANNEL; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.V3_FNAW_EN_CHANNEL; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.V3_SKIN_CHANNEL; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.V3_UPDATE_CHANNEL; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.V3_VOICE_CHANNEL; +import static net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageConstants.V4_CHANNEL; import java.io.IOException; import java.util.ArrayList; @@ -15,24 +18,72 @@ import java.util.List; import java.util.Map; import java.util.Set; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherCapeEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherClientUUIDV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherSkinEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetSkinByURLEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketInstallSkinSPEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketRequestServerInfoV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalConnectEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectPeerV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalRequestEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketWebViewMessageEnV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketWebViewMessageV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketCustomizePauseMenuV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketEnableFNAWSkinsEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientCapeCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientCapePresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinPresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketInvalidatePlayerCacheV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifBadgeHideV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifBadgeShowV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifIconsRegisterV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifIconsReleaseV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapeCustomEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapePresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherPlayerClientUUIDV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinPresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketRedirectClientV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketServerInfoDataChunkV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketSetServerCookieV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUnforceClientV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalAllowedEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectAnnounceV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDisconnectPeerEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalGlobalEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketWebViewMessageV4EAG; + /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public enum GamePluginMessageProtocol { - V3(3, - define(V3_SKIN_CHANNEL, 0x03, CLIENT_TO_SERVER, CPacketGetOtherSkinEAG.class), + V3(3, define(V3_SKIN_CHANNEL, 0x03, CLIENT_TO_SERVER, CPacketGetOtherSkinEAG.class), define(V3_SKIN_CHANNEL, 0x04, SERVER_TO_CLIENT, SPacketOtherSkinPresetEAG.class), define(V3_SKIN_CHANNEL, 0x05, SERVER_TO_CLIENT, SPacketOtherSkinCustomV3EAG.class), define(V3_SKIN_CHANNEL, 0x06, CLIENT_TO_SERVER, CPacketGetSkinByURLEAG.class), @@ -52,9 +103,8 @@ public enum GamePluginMessageProtocol { define(V3_VOICE_CHANNEL, 0x04, SERVER_TO_CLIENT, SPacketVoiceSignalDescEAG.class), define(V3_VOICE_CHANNEL, 0x05, SERVER_TO_CLIENT, SPacketVoiceSignalGlobalEAG.class), define(V3_UPDATE_CHANNEL, -1, SERVER_TO_CLIENT, SPacketUpdateCertEAG.class), - define(V3_FNAW_EN_CHANNEL, -1, SERVER_TO_CLIENT, SPacketEnableFNAWSkinsEAG.class) - ), V4(4, - define(V4_CHANNEL, 0x01, CLIENT_TO_SERVER, CPacketGetOtherSkinEAG.class), + define(V3_FNAW_EN_CHANNEL, -1, SERVER_TO_CLIENT, SPacketEnableFNAWSkinsEAG.class)), + V4(4, define(V4_CHANNEL, 0x01, CLIENT_TO_SERVER, CPacketGetOtherSkinEAG.class), define(V4_CHANNEL, 0x02, SERVER_TO_CLIENT, SPacketOtherSkinPresetEAG.class), define(V4_CHANNEL, 0x03, SERVER_TO_CLIENT, SPacketOtherSkinCustomV4EAG.class), define(V4_CHANNEL, 0x04, CLIENT_TO_SERVER, CPacketGetSkinByURLEAG.class), @@ -96,32 +146,80 @@ public enum GamePluginMessageProtocol { define(V4_CHANNEL, 0x28, SERVER_TO_CLIENT, SPacketNotifIconsRegisterV4EAG.class), define(V4_CHANNEL, 0x29, SERVER_TO_CLIENT, SPacketNotifIconsReleaseV4EAG.class), define(V4_CHANNEL, 0x2A, SERVER_TO_CLIENT, SPacketNotifBadgeShowV4EAG.class), - define(V4_CHANNEL, 0x2B, SERVER_TO_CLIENT, SPacketNotifBadgeHideV4EAG.class) - ); + define(V4_CHANNEL, 0x2B, SERVER_TO_CLIENT, SPacketNotifBadgeHideV4EAG.class)); + + private static class PacketDef { + + private final String channel; + private final int id; + private final int dir; + private final Class clazz; + + private PacketDef(String channel, int id, int dir, Class clazz) { + this.channel = channel; + this.id = id; + this.dir = dir; + this.clazz = clazz; + } + + } + + private static final GamePluginMessageProtocol[] PROTOCOLS_MAP = new GamePluginMessageProtocol[5]; + private static final Set allChannels = new HashSet<>(); + static { + GamePluginMessageProtocol[] _values = values(); + PROTOCOLS_MAP[2] = V3; + for (int i = 0; i < _values.length; ++i) { + GamePluginMessageProtocol protocol = _values[i]; + PROTOCOLS_MAP[protocol.ver] = protocol; + allChannels.addAll(protocol.channelMap[CLIENT_TO_SERVER].keySet()); + allChannels.addAll(protocol.channelMap[SERVER_TO_CLIENT].keySet()); + } + for (int i = 0; i < _values.length; ++i) { + GamePluginMessageProtocol protocol = _values[i]; + protocol.notChannelMap.addAll(allChannels); + protocol.notChannelMap.removeAll(protocol.channelMap[CLIENT_TO_SERVER].keySet()); + protocol.notChannelMap.removeAll(protocol.channelMap[SERVER_TO_CLIENT].keySet()); + } + } + + private static PacketDef define(String channel, int id, int dir, Class clazz) { + return new PacketDef(channel, id, dir, clazz); + } + + public static Set getAllChannels() { + return allChannels; + } + + public static GamePluginMessageProtocol getByVersion(int ver) { + if (ver < 0 || ver > PROTOCOLS_MAP.length) { + return null; + } + return PROTOCOLS_MAP[ver]; + } public final int ver; private final Map[] channelMap; - private final Map, PacketDef>[] classMap; - private final Set notChannelMap = new HashSet<>(); // populated in clinit - private static final GamePluginMessageProtocol[] PROTOCOLS_MAP = new GamePluginMessageProtocol[5]; - private static final Set allChannels = new HashSet<>(); + private final Map, PacketDef>[] classMap; + + private final Set notChannelMap = new HashSet<>(); // populated in clinit private GamePluginMessageProtocol(int versionInt, PacketDef... packets) { ver = versionInt; channelMap = new Map[] { new HashMap<>(), new HashMap<>() }; classMap = new Map[] { new HashMap<>(), new HashMap<>() }; - for(int i = 0; i < packets.length; ++i) { + for (int i = 0; i < packets.length; ++i) { PacketDef pkt = packets[i]; classMap[pkt.dir].put(pkt.clazz, pkt); - if(pkt.id == -1) { + if (pkt.id == -1) { channelMap[pkt.dir].put(pkt.channel, pkt); - }else { - PacketDef[] map = (PacketDef[])channelMap[pkt.dir].get(pkt.channel); - if(map == null || map.length <= pkt.id) { + } else { + PacketDef[] map = (PacketDef[]) channelMap[pkt.dir].get(pkt.channel); + if (map == null || map.length <= pkt.id) { PacketDef[] newMap = new PacketDef[((pkt.id + 1) & 0xF0) + 0x0F]; - if(map != null) { + if (map != null) { System.arraycopy(map, 0, newMap, 0, map.length); } map = newMap; @@ -132,99 +230,53 @@ public enum GamePluginMessageProtocol { } } - private static PacketDef define(String channel, int id, int dir, Class clazz) { - return new PacketDef(channel, id, dir, clazz); - } - - private static class PacketDef { - - private final String channel; - private final int id; - private final int dir; - private final Class clazz; - - private PacketDef(String channel, int id, int dir, Class clazz) { - this.channel = channel; - this.id = id; - this.dir = dir; - this.clazz = clazz; - } - - } - - public GameMessagePacket readPacket(String channel, int direction, GamePacketInputBuffer buffer) throws IOException { - Object obj = channelMap[direction].get(channel); - if(obj == null) { - return null; - } - PacketDef toRead; - if(obj instanceof PacketDef) { - toRead = (PacketDef)obj; - }else { - int pktId = buffer.readUnsignedByte(); - PacketDef[] pkts = (PacketDef[])obj; - if(pktId < 0 || pktId >= pkts.length || (toRead = pkts[pktId]) == null) { - throw new IOException("[" + channel + "] Unknown packet ID: " + pktId); - } - } - GameMessagePacket ret; - try { - ret = toRead.clazz.newInstance(); - }catch(Throwable t) { - throw new RuntimeException("Reflection failed to call packet constructor! (Is it defined?)", t); - } - ret.readPacket(buffer); - return ret; - } - - public String writePacket(int direction, GamePacketOutputBuffer stream, GameMessagePacket packet) throws IOException { - Class clazz = packet.getClass(); - PacketDef def = classMap[direction].get(clazz); - if(def == null) { - throw new IOException("Unknown packet type or wrong direction: " + clazz); - } - if(def.id != -1) { - stream.writeByte(def.id); - } - packet.writePacket(stream); - return def.channel; - } - public List filterProtocols(Collection data) { List ret = new ArrayList<>(data.size()); - for(String str : data) { - if(!notChannelMap.contains(str)) { + for (String str : data) { + if (!notChannelMap.contains(str)) { ret.add(str); } } return ret; } - public static GamePluginMessageProtocol getByVersion(int ver) { - if(ver < 0 || ver > PROTOCOLS_MAP.length) { + public GameMessagePacket readPacket(String channel, int direction, GamePacketInputBuffer buffer) + throws IOException { + Object obj = channelMap[direction].get(channel); + if (obj == null) { return null; } - return PROTOCOLS_MAP[ver]; + PacketDef toRead; + if (obj instanceof PacketDef) { + toRead = (PacketDef) obj; + } else { + int pktId = buffer.readUnsignedByte(); + PacketDef[] pkts = (PacketDef[]) obj; + if (pktId < 0 || pktId >= pkts.length || (toRead = pkts[pktId]) == null) { + throw new IOException("[" + channel + "] Unknown packet ID: " + pktId); + } + } + GameMessagePacket ret; + try { + ret = toRead.clazz.newInstance(); + } catch (Throwable t) { + throw new RuntimeException("Reflection failed to call packet constructor! (Is it defined?)", t); + } + ret.readPacket(buffer); + return ret; } - public static Set getAllChannels() { - return allChannels; - } - - static { - GamePluginMessageProtocol[] _values = values(); - PROTOCOLS_MAP[2] = V3; - for(int i = 0; i < _values.length; ++i) { - GamePluginMessageProtocol protocol = _values[i]; - PROTOCOLS_MAP[protocol.ver] = protocol; - allChannels.addAll(protocol.channelMap[CLIENT_TO_SERVER].keySet()); - allChannels.addAll(protocol.channelMap[SERVER_TO_CLIENT].keySet()); + public String writePacket(int direction, GamePacketOutputBuffer stream, GameMessagePacket packet) + throws IOException { + Class clazz = packet.getClass(); + PacketDef def = classMap[direction].get(clazz); + if (def == null) { + throw new IOException("Unknown packet type or wrong direction: " + clazz); } - for(int i = 0; i < _values.length; ++i) { - GamePluginMessageProtocol protocol = _values[i]; - protocol.notChannelMap.addAll(allChannels); - protocol.notChannelMap.removeAll(protocol.channelMap[CLIENT_TO_SERVER].keySet()); - protocol.notChannelMap.removeAll(protocol.channelMap[SERVER_TO_CLIENT].keySet()); + if (def.id != -1) { + stream.writeByte(def.id); } + packet.writePacket(stream); + return def.channel; } } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessageHandler.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessageHandler.java index 8a2ec2db..dc01eca8 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessageHandler.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessageHandler.java @@ -1,19 +1,64 @@ package net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.*; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherCapeEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherClientUUIDV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetOtherSkinEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketGetSkinByURLEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketInstallSkinSPEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketRequestServerInfoV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalConnectEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectPeerV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalDisconnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketVoiceSignalRequestEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketWebViewMessageEnV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.client.CPacketWebViewMessageV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketCustomizePauseMenuV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketEnableFNAWSkinsEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientCapeCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientCapePresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinPresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketInvalidatePlayerCacheV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifBadgeHideV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifBadgeShowV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifIconsRegisterV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketNotifIconsReleaseV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapeCustomEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherCapePresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherPlayerClientUUIDV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinPresetEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketRedirectClientV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketServerInfoDataChunkV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketSetServerCookieV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUnforceClientV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketUpdateCertEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalAllowedEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectAnnounceV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalConnectV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDescEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalDisconnectPeerEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalGlobalEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketVoiceSignalICEEAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketWebViewMessageV4EAG; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,6 +69,10 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleClient(CPacketGetOtherClientUUIDV4EAG packet) { + throw new WrongPacketException(); + } + default void handleClient(CPacketGetOtherSkinEAG packet) { throw new WrongPacketException(); } @@ -36,6 +85,10 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleClient(CPacketRequestServerInfoV4EAG packet) { + throw new WrongPacketException(); + } + default void handleClient(CPacketVoiceSignalConnectEAG packet) { throw new WrongPacketException(); } @@ -44,6 +97,10 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleClient(CPacketVoiceSignalDisconnectPeerV4EAG packet) { + throw new WrongPacketException(); + } + default void handleClient(CPacketVoiceSignalDisconnectV3EAG packet) { throw new WrongPacketException(); } @@ -52,10 +109,6 @@ public interface GameMessageHandler { throw new WrongPacketException(); } - default void handleClient(CPacketVoiceSignalDisconnectPeerV4EAG packet) { - throw new WrongPacketException(); - } - default void handleClient(CPacketVoiceSignalICEEAG packet) { throw new WrongPacketException(); } @@ -64,11 +117,7 @@ public interface GameMessageHandler { throw new WrongPacketException(); } - default void handleClient(CPacketGetOtherClientUUIDV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleClient(CPacketRequestServerInfoV4EAG packet) { + default void handleClient(CPacketWebViewMessageEnV4EAG packet) { throw new WrongPacketException(); } @@ -76,7 +125,7 @@ public interface GameMessageHandler { throw new WrongPacketException(); } - default void handleClient(CPacketWebViewMessageEnV4EAG packet) { + default void handleServer(SPacketCustomizePauseMenuV4EAG packet) { throw new WrongPacketException(); } @@ -84,6 +133,42 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleServer(SPacketForceClientCapeCustomV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketForceClientCapePresetV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketForceClientSkinCustomV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketForceClientSkinPresetV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketInvalidatePlayerCacheV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketNotifBadgeHideV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketNotifBadgeShowV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketNotifIconsRegisterV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketNotifIconsReleaseV4EAG packet) { + throw new WrongPacketException(); + } + default void handleServer(SPacketOtherCapeCustomEAG packet) { throw new WrongPacketException(); } @@ -92,6 +177,10 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleServer(SPacketOtherPlayerClientUUIDV4EAG packet) { + throw new WrongPacketException(); + } + default void handleServer(SPacketOtherSkinCustomV3EAG packet) { throw new WrongPacketException(); } @@ -104,6 +193,22 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleServer(SPacketRedirectClientV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketServerInfoDataChunkV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketSetServerCookieV4EAG packet) { + throw new WrongPacketException(); + } + + default void handleServer(SPacketUnforceClientV4EAG packet) { + throw new WrongPacketException(); + } + default void handleServer(SPacketUpdateCertEAG packet) { throw new WrongPacketException(); } @@ -112,6 +217,10 @@ public interface GameMessageHandler { throw new WrongPacketException(); } + default void handleServer(SPacketVoiceSignalConnectAnnounceV4EAG packet) { + throw new WrongPacketException(); + } + default void handleServer(SPacketVoiceSignalConnectV3EAG packet) { throw new WrongPacketException(); } @@ -120,10 +229,6 @@ public interface GameMessageHandler { throw new WrongPacketException(); } - default void handleServer(SPacketVoiceSignalConnectAnnounceV4EAG packet) { - throw new WrongPacketException(); - } - default void handleServer(SPacketVoiceSignalDescEAG packet) { throw new WrongPacketException(); } @@ -140,68 +245,8 @@ public interface GameMessageHandler { throw new WrongPacketException(); } - default void handleServer(SPacketForceClientSkinPresetV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketForceClientSkinCustomV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketSetServerCookieV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketRedirectClientV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketOtherPlayerClientUUIDV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketForceClientCapePresetV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketForceClientCapeCustomV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketInvalidatePlayerCacheV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketUnforceClientV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketCustomizePauseMenuV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketServerInfoDataChunkV4EAG packet) { - throw new WrongPacketException(); - } - default void handleServer(SPacketWebViewMessageV4EAG packet) { throw new WrongPacketException(); } - default void handleServer(SPacketNotifIconsRegisterV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketNotifIconsReleaseV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketNotifBadgeShowV4EAG packet) { - throw new WrongPacketException(); - } - - default void handleServer(SPacketNotifBadgeHideV4EAG packet) { - throw new WrongPacketException(); - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessagePacket.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessagePacket.java index 7f42857d..78185ded 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessagePacket.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/GameMessagePacket.java @@ -8,26 +8,27 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePacketOutputBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface GameMessagePacket { - void readPacket(GamePacketInputBuffer buffer) throws IOException; - - void writePacket(GamePacketOutputBuffer buffer) throws IOException; - void handlePacket(GameMessageHandler handler); int length(); + void readPacket(GamePacketInputBuffer buffer) throws IOException; + + void writePacket(GamePacketOutputBuffer buffer) throws IOException; + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/WrongPacketException.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/WrongPacketException.java index 7ee019a2..cf5474a6 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/WrongPacketException.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/WrongPacketException.java @@ -3,14 +3,15 @@ package net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherCapeEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherCapeEAG.java index ac713785..05a37b27 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherCapeEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherCapeEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class CPacketGetOtherCapeEAG implements GameMessagePacket { this.uuidLeast = uuidLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class CPacketGetOtherCapeEAG implements GameMessagePacket { buffer.writeLong(uuidLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherClientUUIDV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherClientUUIDV4EAG.java index 7a7aafa3..50e9f158 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherClientUUIDV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherClientUUIDV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class CPacketGetOtherClientUUIDV4EAG implements GameMessagePacket { this.playerUUIDLeast = playerUUIDLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return GamePacketOutputBuffer.getVarIntSize(requestId) + 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { requestId = buffer.readVarInt(); @@ -51,14 +62,4 @@ public class CPacketGetOtherClientUUIDV4EAG implements GameMessagePacket { buffer.writeLong(playerUUIDLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return GamePacketOutputBuffer.getVarIntSize(requestId) + 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherSkinEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherSkinEAG.java index f1ffc662..71258764 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherSkinEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetOtherSkinEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class CPacketGetOtherSkinEAG implements GameMessagePacket { this.uuidLeast = uuidLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class CPacketGetOtherSkinEAG implements GameMessagePacket { buffer.writeLong(uuidLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetSkinByURLEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetSkinByURLEAG.java index 83ba98d0..d4199c58 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetSkinByURLEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketGetSkinByURLEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class CPacketGetSkinByURLEAG implements GameMessagePacket { this.url = url; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 18 + url.length(); + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -51,14 +62,4 @@ public class CPacketGetSkinByURLEAG implements GameMessagePacket { buffer.writeStringEaglerASCII16(url); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 18 + url.length(); - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketInstallSkinSPEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketInstallSkinSPEAG.java index bfdadcff..76c7d15a 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketInstallSkinSPEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketInstallSkinSPEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,6 +34,16 @@ public class CPacketInstallSkinSPEAG implements GameMessagePacket { this.customSkin = customSkin; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 2 + customSkin.length; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { customSkin = new byte[buffer.readUnsignedShort()]; @@ -45,14 +56,4 @@ public class CPacketInstallSkinSPEAG implements GameMessagePacket { buffer.write(customSkin); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 2 + customSkin.length; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketRequestServerInfoV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketRequestServerInfoV4EAG.java index 1a392bbb..5b94e94e 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketRequestServerInfoV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketRequestServerInfoV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,20 +34,6 @@ public class CPacketRequestServerInfoV4EAG implements GameMessagePacket { this.requestHash = requestHash; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - requestHash = new byte[20]; - buffer.readFully(requestHash); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(requestHash.length != 20) { - throw new IOException("Hash must be 20 bytes! (" + requestHash.length + " given)"); - } - buffer.write(requestHash); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -57,4 +44,18 @@ public class CPacketRequestServerInfoV4EAG implements GameMessagePacket { return 20; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + requestHash = new byte[20]; + buffer.readFully(requestHash); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (requestHash.length != 20) { + throw new IOException("Hash must be 20 bytes! (" + requestHash.length + " given)"); + } + buffer.write(requestHash); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalConnectEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalConnectEAG.java index 4d72fc19..7976f8cc 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalConnectEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalConnectEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,14 +28,6 @@ public class CPacketVoiceSignalConnectEAG implements GameMessagePacket { public CPacketVoiceSignalConnectEAG() { } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -45,4 +38,12 @@ public class CPacketVoiceSignalConnectEAG implements GameMessagePacket { return 0; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDescEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDescEAG.java index ee752d17..d83e5ff2 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDescEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDescEAG.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,29 +45,6 @@ public class CPacketVoiceSignalDescEAG implements GameMessagePacket { this.desc = desc.getBytes(StandardCharsets.UTF_8); } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - int descLen = buffer.readVarInt(); - if(descLen > 32750) { - throw new IOException("Voice signal packet DESC too long!"); - } - desc = new byte[descLen]; - buffer.readFully(desc); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(desc.length > 32750) { - throw new IOException("Voice signal packet DESC too long!"); - } - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - buffer.writeVarInt(desc.length); - buffer.write(desc); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -77,4 +55,27 @@ public class CPacketVoiceSignalDescEAG implements GameMessagePacket { return 16 + GamePacketOutputBuffer.getArrayMCSize(desc.length); } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + int descLen = buffer.readVarInt(); + if (descLen > 32750) { + throw new IOException("Voice signal packet DESC too long!"); + } + desc = new byte[descLen]; + buffer.readFully(desc); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (desc.length > 32750) { + throw new IOException("Voice signal packet DESC too long!"); + } + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + buffer.writeVarInt(desc.length); + buffer.write(desc); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectPeerV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectPeerV4EAG.java index aa6e5bd7..c6ebcf52 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectPeerV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectPeerV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class CPacketVoiceSignalDisconnectPeerV4EAG implements GameMessagePacket this.uuidLeast = uuidLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class CPacketVoiceSignalDisconnectPeerV4EAG implements GameMessagePacket buffer.writeLong(uuidLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV3EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV3EAG.java index 86763836..9ca0366f 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV3EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV3EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,25 +38,6 @@ public class CPacketVoiceSignalDisconnectV3EAG implements GameMessagePacket { this.uuidLeast = uuidLeast; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - if(buffer.available() > 0) { - isPeerType = true; - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - }else { - isPeerType = false; - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(isPeerType) { - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -66,4 +48,23 @@ public class CPacketVoiceSignalDisconnectV3EAG implements GameMessagePacket { return isPeerType ? 16 : 0; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + if (buffer.available() > 0) { + isPeerType = true; + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + } else { + isPeerType = false; + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (isPeerType) { + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV4EAG.java index 8bf915de..7b15c30e 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalDisconnectV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -27,14 +28,6 @@ public class CPacketVoiceSignalDisconnectV4EAG implements GameMessagePacket { public CPacketVoiceSignalDisconnectV4EAG() { } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -45,4 +38,12 @@ public class CPacketVoiceSignalDisconnectV4EAG implements GameMessagePacket { return 0; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalICEEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalICEEAG.java index c3cf72d5..d80a50fb 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalICEEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalICEEAG.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,29 +45,6 @@ public class CPacketVoiceSignalICEEAG implements GameMessagePacket { this.ice = ice.getBytes(StandardCharsets.UTF_8); } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - int iceLen = buffer.readVarInt(); - if(iceLen > 32750) { - throw new IOException("Voice signal packet ICE too long!"); - } - ice = new byte[iceLen]; - buffer.readFully(ice); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(ice.length > 32750) { - throw new IOException("Voice signal packet ICE too long!"); - } - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - buffer.writeVarInt(ice.length); - buffer.write(ice); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -77,4 +55,27 @@ public class CPacketVoiceSignalICEEAG implements GameMessagePacket { return 16 + GamePacketOutputBuffer.getArrayMCSize(ice.length); } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + int iceLen = buffer.readVarInt(); + if (iceLen > 32750) { + throw new IOException("Voice signal packet ICE too long!"); + } + ice = new byte[iceLen]; + buffer.readFully(ice); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (ice.length > 32750) { + throw new IOException("Voice signal packet ICE too long!"); + } + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + buffer.writeVarInt(ice.length); + buffer.write(ice); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalRequestEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalRequestEAG.java index 78544225..272407e5 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalRequestEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketVoiceSignalRequestEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class CPacketVoiceSignalRequestEAG implements GameMessagePacket { this.uuidLeast = uuidLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class CPacketVoiceSignalRequestEAG implements GameMessagePacket { buffer.writeLong(uuidLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageEnV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageEnV4EAG.java index 6f0f1272..90be085d 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageEnV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageEnV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,29 +36,6 @@ public class CPacketWebViewMessageEnV4EAG implements GameMessagePacket { this.channelName = channelName; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - messageChannelOpen = buffer.readBoolean(); - if(messageChannelOpen) { - channelName = buffer.readStringEaglerASCII8(); - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - buffer.writeBoolean(messageChannelOpen); - if(messageChannelOpen) { - if(channelName != null) { - if(channelName.length() > 255) { - throw new IOException("Channel name too long! (255 max, " + channelName.length() + " given)"); - } - buffer.writeStringEaglerASCII8(channelName); - }else { - buffer.writeByte(0); - } - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleClient(this); @@ -68,4 +46,27 @@ public class CPacketWebViewMessageEnV4EAG implements GameMessagePacket { return messageChannelOpen ? 2 + (channelName != null ? channelName.length() : 0) : 1; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + messageChannelOpen = buffer.readBoolean(); + if (messageChannelOpen) { + channelName = buffer.readStringEaglerASCII8(); + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + buffer.writeBoolean(messageChannelOpen); + if (messageChannelOpen) { + if (channelName != null) { + if (channelName.length() > 255) { + throw new IOException("Channel name too long! (255 max, " + channelName.length() + " given)"); + } + buffer.writeStringEaglerASCII8(channelName); + } else { + buffer.writeByte(0); + } + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageV4EAG.java index f0cf3076..508dea3c 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/client/CPacketWebViewMessageV4EAG.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,6 +35,11 @@ public class CPacketWebViewMessageV4EAG implements GameMessagePacket { public CPacketWebViewMessageV4EAG() { } + public CPacketWebViewMessageV4EAG(byte[] data) { + this.type = TYPE_BINARY; + this.data = data; + } + public CPacketWebViewMessageV4EAG(int type, byte[] data) { this.type = type; this.data = data; @@ -44,9 +50,14 @@ public class CPacketWebViewMessageV4EAG implements GameMessagePacket { this.data = str.getBytes(StandardCharsets.UTF_8); } - public CPacketWebViewMessageV4EAG(byte[] data) { - this.type = TYPE_BINARY; - this.data = data; + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleClient(this); + } + + @Override + public int length() { + return 1 + GamePacketOutputBuffer.getVarIntSize(data.length) + data.length; } @Override @@ -61,14 +72,4 @@ public class CPacketWebViewMessageV4EAG implements GameMessagePacket { buffer.writeByteArrayMC(data); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleClient(this); - } - - @Override - public int length() { - return 1 + GamePacketOutputBuffer.getVarIntSize(data.length) + data.length; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketCustomizePauseMenuV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketCustomizePauseMenuV4EAG.java index a460c040..1cd17c79 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketCustomizePauseMenuV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketCustomizePauseMenuV4EAG.java @@ -16,14 +16,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.PacketImageData; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -52,7 +53,7 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { public String discordButtonText; public String discordInviteURL; - public Map imageMappings; + public Map imageMappings; public List imageData; public SPacketCustomizePauseMenuV4EAG() { @@ -75,6 +76,16 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { this.imageData = imageData; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return -1; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { imageMappings = null; @@ -82,7 +93,7 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { int flags = buffer.readUnsignedByte(); serverInfoMode = (flags & 15); discordButtonMode = ((flags >> 4) & 15); - switch(serverInfoMode) { + switch (serverInfoMode) { case SERVER_INFO_MODE_EXTERNAL_URL: serverInfoButtonText = buffer.readStringMC(127); serverInfoURL = buffer.readStringEaglerASCII16(); @@ -111,22 +122,22 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { serverInfoHash = null; break; } - if(discordButtonMode == DISCORD_MODE_INVITE_URL) { + if (discordButtonMode == DISCORD_MODE_INVITE_URL) { discordButtonText = buffer.readStringMC(127); discordInviteURL = buffer.readStringEaglerASCII16(); - }else { + } else { discordButtonText = null; discordInviteURL = null; } int mappingsCount = buffer.readVarInt(); - if(mappingsCount > 0) { + if (mappingsCount > 0) { imageMappings = new HashMap<>(); imageData = new ArrayList<>(); - for(int i = 0; i < mappingsCount; ++i) { + for (int i = 0; i < mappingsCount; ++i) { imageMappings.put(buffer.readStringEaglerASCII8(), buffer.readVarInt()); } int imageDataCount = buffer.readVarInt(); - for(int i = 0; i < imageDataCount; ++i) { + for (int i = 0; i < imageDataCount; ++i) { imageData.add(PacketImageData.readRGB16(buffer)); } } @@ -135,7 +146,7 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { @Override public void writePacket(GamePacketOutputBuffer buffer) throws IOException { buffer.writeByte(serverInfoMode | (discordButtonMode << 4)); - switch(serverInfoMode) { + switch (serverInfoMode) { case SERVER_INFO_MODE_EXTERNAL_URL: buffer.writeStringMC(serverInfoButtonText); buffer.writeStringEaglerASCII16(serverInfoURL); @@ -150,7 +161,7 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { buffer.writeStringMC(serverInfoButtonText); buffer.writeByte(serverInfoEmbedPerms); buffer.writeStringMC(serverInfoEmbedTitle); - if(serverInfoHash.length != 20) { + if (serverInfoHash.length != 20) { throw new IOException("Hash must be 20 bytes! (" + serverInfoHash.length + " given)"); } buffer.write(serverInfoHash); @@ -158,36 +169,27 @@ public class SPacketCustomizePauseMenuV4EAG implements GameMessagePacket { default: break; } - if(discordButtonMode == DISCORD_MODE_INVITE_URL) { + if (discordButtonMode == DISCORD_MODE_INVITE_URL) { buffer.writeStringMC(discordButtonText); buffer.writeStringEaglerASCII16(discordInviteURL); } - if(imageMappings != null && !imageMappings.isEmpty()) { + if (imageMappings != null && !imageMappings.isEmpty()) { buffer.writeVarInt(imageMappings.size()); - for(Entry etr : imageMappings.entrySet()) { + for (Entry etr : imageMappings.entrySet()) { buffer.writeStringEaglerASCII8(etr.getKey()); buffer.writeVarInt(etr.getValue().intValue()); } buffer.writeVarInt(imageData.size()); - for(PacketImageData etr : imageData) { - if(etr.width < 1 || etr.width > 64 || etr.height < 1 || etr.height > 64) { - throw new IOException("Invalid image dimensions in packet, must be between 1x1 and 64x64, got " + etr.width + "x" + etr.height); + for (PacketImageData etr : imageData) { + if (etr.width < 1 || etr.width > 64 || etr.height < 1 || etr.height > 64) { + throw new IOException("Invalid image dimensions in packet, must be between 1x1 and 64x64, got " + + etr.width + "x" + etr.height); } PacketImageData.writeRGB16(buffer, etr); } - }else { + } else { buffer.writeByte(0); } } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return -1; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketEnableFNAWSkinsEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketEnableFNAWSkinsEAG.java index 36d26bd4..cd5fd47a 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketEnableFNAWSkinsEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketEnableFNAWSkinsEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class SPacketEnableFNAWSkinsEAG implements GameMessagePacket { this.force = force; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 1; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { int i = buffer.readUnsignedByte(); @@ -47,14 +58,4 @@ public class SPacketEnableFNAWSkinsEAG implements GameMessagePacket { buffer.writeByte((enableSkins ? 1 : 0) | (force ? 2 : 0)); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 1; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapeCustomV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapeCustomV4EAG.java index 8070bb3d..3d9a0f4e 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapeCustomV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapeCustomV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,20 +34,6 @@ public class SPacketForceClientCapeCustomV4EAG implements GameMessagePacket { this.customCape = customCape; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - customCape = new byte[1173]; - buffer.readFully(customCape); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(customCape.length != 1173) { - throw new IOException("Custom cape data length is not 1173 bytes! (" + customCape.length + ")"); - } - buffer.write(customCape); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -57,4 +44,18 @@ public class SPacketForceClientCapeCustomV4EAG implements GameMessagePacket { return 1173; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + customCape = new byte[1173]; + buffer.readFully(customCape); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (customCape.length != 1173) { + throw new IOException("Custom cape data length is not 1173 bytes! (" + customCape.length + ")"); + } + buffer.write(customCape); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapePresetV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapePresetV4EAG.java index e2f58939..26ad70b9 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapePresetV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientCapePresetV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,16 +34,6 @@ public class SPacketForceClientCapePresetV4EAG implements GameMessagePacket { this.presetCape = presetCape; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - presetCape = buffer.readInt(); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - buffer.writeInt(presetCape); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -53,4 +44,14 @@ public class SPacketForceClientCapePresetV4EAG implements GameMessagePacket { return 4; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + presetCape = buffer.readInt(); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + buffer.writeInt(presetCape); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinCustomV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinCustomV4EAG.java index aae745fd..e14f1cb8 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinCustomV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinCustomV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,22 +36,6 @@ public class SPacketForceClientSkinCustomV4EAG implements GameMessagePacket { this.customSkin = customSkin; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - modelID = buffer.readUnsignedByte(); - customSkin = new byte[12288]; - buffer.readFully(customSkin); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(customSkin.length != 12288) { - throw new IOException("Custom skin data length is not 12288 bytes! (" + customSkin.length + ")"); - } - buffer.write(modelID); - buffer.write(customSkin); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -61,4 +46,20 @@ public class SPacketForceClientSkinCustomV4EAG implements GameMessagePacket { return 12289; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + modelID = buffer.readUnsignedByte(); + customSkin = new byte[12288]; + buffer.readFully(customSkin); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (customSkin.length != 12288) { + throw new IOException("Custom skin data length is not 12288 bytes! (" + customSkin.length + ")"); + } + buffer.write(modelID); + buffer.write(customSkin); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinPresetV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinPresetV4EAG.java index 29984850..0b95c227 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinPresetV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketForceClientSkinPresetV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,16 +34,6 @@ public class SPacketForceClientSkinPresetV4EAG implements GameMessagePacket { this.presetSkin = presetSkin; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - presetSkin = buffer.readInt(); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - buffer.writeInt(presetSkin); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -53,4 +44,14 @@ public class SPacketForceClientSkinPresetV4EAG implements GameMessagePacket { return 4; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + presetSkin = buffer.readInt(); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + buffer.writeInt(presetSkin); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketInvalidatePlayerCacheV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketInvalidatePlayerCacheV4EAG.java index cfb68fc2..bf923654 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketInvalidatePlayerCacheV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketInvalidatePlayerCacheV4EAG.java @@ -15,41 +15,47 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SPacketInvalidatePlayerCacheV4EAG implements GameMessagePacket { - public Collection players; - public static class InvalidateRequest { - + public final boolean invalidateSkin; public final boolean invalidateCape; public final long uuidMost; public final long uuidLeast; - + public InvalidateRequest(boolean invalidateSkin, boolean invalidateCape, long uuidMost, long uuidLeast) { this.invalidateSkin = invalidateSkin; this.invalidateCape = invalidateCape; this.uuidMost = uuidMost; this.uuidLeast = uuidLeast; } - + } + public Collection players; + public SPacketInvalidatePlayerCacheV4EAG() { } + public SPacketInvalidatePlayerCacheV4EAG(boolean invalidateSkin, boolean invalidateCape, long uuidMost, + long uuidLeast) { + this.players = Arrays.asList(new InvalidateRequest(invalidateSkin, invalidateCape, uuidMost, uuidLeast)); + } + public SPacketInvalidatePlayerCacheV4EAG(Collection players) { this.players = players; } @@ -58,48 +64,6 @@ public class SPacketInvalidatePlayerCacheV4EAG implements GameMessagePacket { this.players = Arrays.asList(players); } - public SPacketInvalidatePlayerCacheV4EAG(boolean invalidateSkin, boolean invalidateCape, long uuidMost, long uuidLeast) { - this.players = Arrays.asList(new InvalidateRequest(invalidateSkin, invalidateCape, uuidMost, uuidLeast)); - } - - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - int cnt = buffer.readVarInt(); - List userList = (List)(players = new ArrayList<>(cnt)); - if(cnt > 0) { - for(int i = 0; i < cnt; ++i) { - int flags = buffer.readUnsignedByte(); - userList.add(new InvalidateRequest((flags & 1) != 0, (flags & 2) != 0, buffer.readLong(), buffer.readLong())); - } - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(players == null || players.size() == 0) { - buffer.write(0); - }else { - if(players instanceof RandomAccess) { - List userList = (List)players; - int cnt = userList.size(); - buffer.writeVarInt(cnt); - for(int i = 0; i < cnt; ++i) { - InvalidateRequest dt = userList.get(i); - buffer.writeByte((dt.invalidateSkin ? 1 : 0) | (dt.invalidateCape ? 2 : 0)); - buffer.writeLong(dt.uuidMost); - buffer.writeLong(dt.uuidLeast); - } - }else { - buffer.writeVarInt(players.size()); - for(InvalidateRequest dt : players) { - buffer.writeByte((dt.invalidateSkin ? 1 : 0) | (dt.invalidateCape ? 2 : 0)); - buffer.writeLong(dt.uuidMost); - buffer.writeLong(dt.uuidLeast); - } - } - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -111,4 +75,43 @@ public class SPacketInvalidatePlayerCacheV4EAG implements GameMessagePacket { return GamePacketOutputBuffer.getVarIntSize(cnt) + 17 * cnt; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + int cnt = buffer.readVarInt(); + List userList = (List) (players = new ArrayList<>(cnt)); + if (cnt > 0) { + for (int i = 0; i < cnt; ++i) { + int flags = buffer.readUnsignedByte(); + userList.add(new InvalidateRequest((flags & 1) != 0, (flags & 2) != 0, buffer.readLong(), + buffer.readLong())); + } + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (players == null || players.size() == 0) { + buffer.write(0); + } else { + if (players instanceof RandomAccess) { + List userList = (List) players; + int cnt = userList.size(); + buffer.writeVarInt(cnt); + for (int i = 0; i < cnt; ++i) { + InvalidateRequest dt = userList.get(i); + buffer.writeByte((dt.invalidateSkin ? 1 : 0) | (dt.invalidateCape ? 2 : 0)); + buffer.writeLong(dt.uuidMost); + buffer.writeLong(dt.uuidLeast); + } + } else { + buffer.writeVarInt(players.size()); + for (InvalidateRequest dt : players) { + buffer.writeByte((dt.invalidateSkin ? 1 : 0) | (dt.invalidateCape ? 2 : 0)); + buffer.writeLong(dt.uuidMost); + buffer.writeLong(dt.uuidLeast); + } + } + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeHideV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeHideV4EAG.java index 60da4d66..37f4d1c1 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeHideV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeHideV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class SPacketNotifBadgeHideV4EAG implements GameMessagePacket { this.badgeUUIDLeast = badgeUUIDLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { badgeUUIDMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class SPacketNotifBadgeHideV4EAG implements GameMessagePacket { buffer.writeLong(badgeUUIDLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeShowV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeShowV4EAG.java index 3c51744e..a9cb7c14 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeShowV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifBadgeShowV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -26,28 +27,28 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { public static enum EnumBadgePriority { LOW(0), NORMAL(1), HIGHER(2), HIGHEST(3); - - public final int priority; - - private EnumBadgePriority(int priority) { - this.priority = priority; - } - + private static final EnumBadgePriority[] lookup = new EnumBadgePriority[4]; - + + static { + EnumBadgePriority[] _values = values(); + for (int i = 0; i < _values.length; ++i) { + lookup[_values[i].priority] = _values[i]; + } + } + public static EnumBadgePriority getByID(int id) { - if(id >= 0 && id < lookup.length) { + if (id >= 0 && id < lookup.length) { return lookup[id]; - }else { + } else { return NORMAL; } } - - static { - EnumBadgePriority[] _values = values(); - for(int i = 0; i < _values.length; ++i) { - lookup[_values[i].priority] = _values[i]; - } + + public final int priority; + + private EnumBadgePriority(int priority) { + this.priority = priority; } } @@ -98,6 +99,16 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { this.sourceTxtColor = sourceTxtColor; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return -1; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { badgeUUIDMost = buffer.readLong(); @@ -105,7 +116,7 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { bodyComponent = buffer.readStringMC(32767); titleComponent = buffer.readStringMC(255); sourceComponent = buffer.readStringMC(255); - originalTimestampSec = ((long)buffer.readUnsignedShort() << 32l) | ((long)buffer.readInt() & 0xFFFFFFFFl); + originalTimestampSec = ((long) buffer.readUnsignedShort() << 32l) | ((long) buffer.readInt() & 0xFFFFFFFFl); int flags = buffer.readUnsignedByte(); silent = (flags & 1) != 0; priority = EnumBadgePriority.getByID((flags >>> 1) & 3); @@ -115,10 +126,13 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { mainIconUUIDLeast = (flags & 8) != 0 ? buffer.readLong() : 0l; titleIconUUIDMost = (flags & 16) != 0 ? buffer.readLong() : 0l; titleIconUUIDLeast = (flags & 16) != 0 ? buffer.readLong() : 0l; - backgroundColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) | buffer.readUnsignedByte(); + backgroundColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) + | buffer.readUnsignedByte(); bodyTxtColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) | buffer.readUnsignedByte(); - titleTxtColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) | buffer.readUnsignedByte(); - sourceTxtColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) | buffer.readUnsignedByte(); + titleTxtColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) + | buffer.readUnsignedByte(); + sourceTxtColor = (buffer.readUnsignedByte() << 16) | (buffer.readUnsignedByte() << 8) + | buffer.readUnsignedByte(); } @Override @@ -128,8 +142,8 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { buffer.writeStringMC(bodyComponent); buffer.writeStringMC(titleComponent); buffer.writeStringMC(sourceComponent); - buffer.writeShort((int)((originalTimestampSec >>> 32l) & 0xFFFFl)); - buffer.writeInt((int)(originalTimestampSec & 0xFFFFFFFFl)); + buffer.writeShort((int) ((originalTimestampSec >>> 32l) & 0xFFFFl)); + buffer.writeInt((int) (originalTimestampSec & 0xFFFFFFFFl)); int flags = (silent ? 1 : 0); flags |= ((priority != null ? priority.priority : 1) << 1); flags |= ((mainIconUUIDMost != 0l || mainIconUUIDLeast != 0l) ? 8 : 0); @@ -137,11 +151,11 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { buffer.writeByte(flags); buffer.writeByte(hideAfterSec); buffer.writeShort(expireAfterSec); - if((flags & 8) != 0) { + if ((flags & 8) != 0) { buffer.writeLong(mainIconUUIDMost); buffer.writeLong(mainIconUUIDLeast); } - if((flags & 16) != 0) { + if ((flags & 16) != 0) { buffer.writeLong(titleIconUUIDMost); buffer.writeLong(titleIconUUIDLeast); } @@ -159,14 +173,4 @@ public class SPacketNotifBadgeShowV4EAG implements GameMessagePacket { buffer.writeByte(sourceTxtColor & 0xFF); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return -1; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsRegisterV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsRegisterV4EAG.java index 31db843d..6471d391 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsRegisterV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsRegisterV4EAG.java @@ -15,14 +15,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.util.PacketImageData; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -56,37 +57,6 @@ public class SPacketNotifIconsRegisterV4EAG implements GameMessagePacket { this.iconsToCreate = iconsToCreate; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - int len = buffer.readVarInt(); - iconsToCreate = new ArrayList<>(len); - for(int i = 0; i < len; ++i) { - iconsToCreate.add(new CreateIcon(buffer.readLong(), buffer.readLong(), PacketImageData.readRGB16(buffer))); - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(iconsToCreate instanceof RandomAccess) { - int len = iconsToCreate.size(); - buffer.writeVarInt(len); - List vigg = (List)iconsToCreate; - for(int i = 0, l = vigg.size(); i < l; ++i) { - CreateIcon icn = vigg.get(i); - buffer.writeLong(icn.uuidMost); - buffer.writeLong(icn.uuidLeast); - PacketImageData.writeRGB16(buffer, icn.imageData); - } - }else { - buffer.writeVarInt(iconsToCreate.size()); - for(CreateIcon icn : iconsToCreate) { - buffer.writeLong(icn.uuidMost); - buffer.writeLong(icn.uuidLeast); - PacketImageData.writeRGB16(buffer, icn.imageData); - } - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -95,17 +65,48 @@ public class SPacketNotifIconsRegisterV4EAG implements GameMessagePacket { @Override public int length() { int len = GamePacketOutputBuffer.getVarIntSize(iconsToCreate.size()); - if(iconsToCreate instanceof RandomAccess) { - List vigg = (List)iconsToCreate; - for(int i = 0, l = vigg.size(); i < l; ++i) { + if (iconsToCreate instanceof RandomAccess) { + List vigg = (List) iconsToCreate; + for (int i = 0, l = vigg.size(); i < l; ++i) { len += vigg.get(i).length(); } - }else { - for(CreateIcon icn : iconsToCreate) { + } else { + for (CreateIcon icn : iconsToCreate) { len += icn.length(); } } return len; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + int len = buffer.readVarInt(); + iconsToCreate = new ArrayList<>(len); + for (int i = 0; i < len; ++i) { + iconsToCreate.add(new CreateIcon(buffer.readLong(), buffer.readLong(), PacketImageData.readRGB16(buffer))); + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (iconsToCreate instanceof RandomAccess) { + int len = iconsToCreate.size(); + buffer.writeVarInt(len); + List vigg = (List) iconsToCreate; + for (int i = 0, l = vigg.size(); i < l; ++i) { + CreateIcon icn = vigg.get(i); + buffer.writeLong(icn.uuidMost); + buffer.writeLong(icn.uuidLeast); + PacketImageData.writeRGB16(buffer, icn.imageData); + } + } else { + buffer.writeVarInt(iconsToCreate.size()); + for (CreateIcon icn : iconsToCreate) { + buffer.writeLong(icn.uuidMost); + buffer.writeLong(icn.uuidLeast); + PacketImageData.writeRGB16(buffer, icn.imageData); + } + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsReleaseV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsReleaseV4EAG.java index 5b854684..b46fd373 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsReleaseV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketNotifIconsReleaseV4EAG.java @@ -14,14 +14,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -49,35 +50,6 @@ public class SPacketNotifIconsReleaseV4EAG implements GameMessagePacket { this.iconsToDestroy = iconsToDestroy; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - int len = buffer.readVarInt(); - iconsToDestroy = new ArrayList<>(len); - for(int i = 0; i < len; ++i) { - iconsToDestroy.add(new DestroyIcon(buffer.readLong(), buffer.readLong())); - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(iconsToDestroy instanceof RandomAccess) { - int len = iconsToDestroy.size(); - buffer.writeVarInt(len); - List vigg = (List)iconsToDestroy; - for(int i = 0; i < len; ++i) { - DestroyIcon icn = vigg.get(i); - buffer.writeLong(icn.uuidMost); - buffer.writeLong(icn.uuidLeast); - } - }else { - buffer.writeVarInt(iconsToDestroy.size()); - for(DestroyIcon icn : iconsToDestroy) { - buffer.writeLong(icn.uuidMost); - buffer.writeLong(icn.uuidLeast); - } - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -89,4 +61,33 @@ public class SPacketNotifIconsReleaseV4EAG implements GameMessagePacket { return GamePacketOutputBuffer.getVarIntSize(len) + (len << 4); } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + int len = buffer.readVarInt(); + iconsToDestroy = new ArrayList<>(len); + for (int i = 0; i < len; ++i) { + iconsToDestroy.add(new DestroyIcon(buffer.readLong(), buffer.readLong())); + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (iconsToDestroy instanceof RandomAccess) { + int len = iconsToDestroy.size(); + buffer.writeVarInt(len); + List vigg = (List) iconsToDestroy; + for (int i = 0; i < len; ++i) { + DestroyIcon icn = vigg.get(i); + buffer.writeLong(icn.uuidMost); + buffer.writeLong(icn.uuidLeast); + } + } else { + buffer.writeVarInt(iconsToDestroy.size()); + for (DestroyIcon icn : iconsToDestroy) { + buffer.writeLong(icn.uuidMost); + buffer.writeLong(icn.uuidLeast); + } + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapeCustomEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapeCustomEAG.java index 28efa6da..e2bdc030 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapeCustomEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapeCustomEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,24 +38,6 @@ public class SPacketOtherCapeCustomEAG implements GameMessagePacket { this.customCape = customCape; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - customCape = new byte[1173]; - buffer.readFully(customCape); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(customCape.length != 1173) { - throw new IOException("Custom cape data length is not 1173 bytes! (" + customCape.length + ")"); - } - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - buffer.write(customCape); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -65,4 +48,22 @@ public class SPacketOtherCapeCustomEAG implements GameMessagePacket { return 1189; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + customCape = new byte[1173]; + buffer.readFully(customCape); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (customCape.length != 1173) { + throw new IOException("Custom cape data length is not 1173 bytes! (" + customCape.length + ")"); + } + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + buffer.write(customCape); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapePresetEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapePresetEAG.java index 6c20046d..a2d34837 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapePresetEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherCapePresetEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class SPacketOtherCapePresetEAG implements GameMessagePacket { this.presetCape = presetCape; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 20; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -51,14 +62,4 @@ public class SPacketOtherCapePresetEAG implements GameMessagePacket { buffer.writeInt(presetCape); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 20; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherPlayerClientUUIDV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherPlayerClientUUIDV4EAG.java index 0d098043..cf17ea53 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherPlayerClientUUIDV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherPlayerClientUUIDV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class SPacketOtherPlayerClientUUIDV4EAG implements GameMessagePacket { this.clientUUIDLeast = playerUUIDLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return GamePacketOutputBuffer.getVarIntSize(requestId) + 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { requestId = buffer.readVarInt(); @@ -51,14 +62,4 @@ public class SPacketOtherPlayerClientUUIDV4EAG implements GameMessagePacket { buffer.writeLong(clientUUIDLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return GamePacketOutputBuffer.getVarIntSize(requestId) + 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV3EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV3EAG.java index 8702983e..e54083cd 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV3EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV3EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,6 +40,16 @@ public class SPacketOtherSkinCustomV3EAG implements GameMessagePacket { this.customSkin = customSkin; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 16401; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -50,7 +61,7 @@ public class SPacketOtherSkinCustomV3EAG implements GameMessagePacket { @Override public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(customSkin.length != 16384) { + if (customSkin.length != 16384) { throw new IOException("Custom skin data length is not 16384 bytes! (" + customSkin.length + ")"); } buffer.writeLong(uuidMost); @@ -59,14 +70,4 @@ public class SPacketOtherSkinCustomV3EAG implements GameMessagePacket { buffer.write(customSkin); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 16401; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV4EAG.java index dcbdad88..32e0fccc 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinCustomV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,6 +40,16 @@ public class SPacketOtherSkinCustomV4EAG implements GameMessagePacket { this.customSkin = customSkin; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 12305; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -50,7 +61,7 @@ public class SPacketOtherSkinCustomV4EAG implements GameMessagePacket { @Override public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(customSkin.length != 12288) { + if (customSkin.length != 12288) { throw new IOException("Custom skin data length is not 12288 bytes! (" + customSkin.length + ")"); } buffer.writeLong(uuidMost); @@ -59,14 +70,4 @@ public class SPacketOtherSkinCustomV4EAG implements GameMessagePacket { buffer.write(customSkin); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 12305; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinPresetEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinPresetEAG.java index a79efe31..2fd752ab 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinPresetEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketOtherSkinPresetEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class SPacketOtherSkinPresetEAG implements GameMessagePacket { this.presetSkin = presetSkin; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 20; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -51,14 +62,4 @@ public class SPacketOtherSkinPresetEAG implements GameMessagePacket { buffer.writeInt(presetSkin); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 20; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketRedirectClientV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketRedirectClientV4EAG.java index 58f342ed..73ad6483 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketRedirectClientV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketRedirectClientV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,16 +34,6 @@ public class SPacketRedirectClientV4EAG implements GameMessagePacket { this.redirectURI = redirectURI; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - redirectURI = buffer.readStringEaglerASCII16(); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - buffer.writeStringEaglerASCII16(redirectURI); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -53,4 +44,14 @@ public class SPacketRedirectClientV4EAG implements GameMessagePacket { return 2 + redirectURI.length(); } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + redirectURI = buffer.readStringEaglerASCII16(); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + buffer.writeStringEaglerASCII16(redirectURI); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketServerInfoDataChunkV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketServerInfoDataChunkV4EAG.java index a90078b1..998f158d 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketServerInfoDataChunkV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketServerInfoDataChunkV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -41,6 +42,17 @@ public class SPacketServerInfoDataChunkV4EAG implements GameMessagePacket { this.data = data; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 21 + GamePacketOutputBuffer.getVarIntSize(finalSize) + GamePacketOutputBuffer.getVarIntSize(seqId) + + GamePacketOutputBuffer.getVarIntSize(data.length) + data.length; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { lastChunk = buffer.readBoolean(); @@ -54,7 +66,7 @@ public class SPacketServerInfoDataChunkV4EAG implements GameMessagePacket { @Override public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(finalHash.length != 20) { + if (finalHash.length != 20) { throw new IOException("Hash must be 20 bytes! (" + finalHash.length + " given)"); } buffer.writeBoolean(lastChunk); @@ -65,15 +77,4 @@ public class SPacketServerInfoDataChunkV4EAG implements GameMessagePacket { buffer.write(data); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 21 + GamePacketOutputBuffer.getVarIntSize(finalSize) + GamePacketOutputBuffer.getVarIntSize(seqId) - + GamePacketOutputBuffer.getVarIntSize(data.length) + data.length; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketSetServerCookieV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketSetServerCookieV4EAG.java index 14ca4395..5bdde6b8 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketSetServerCookieV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketSetServerCookieV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,8 +33,9 @@ public class SPacketSetServerCookieV4EAG implements GameMessagePacket { public SPacketSetServerCookieV4EAG() { } - public SPacketSetServerCookieV4EAG(byte[] data, long expires, boolean revokeQuerySupported, boolean saveCookieToDisk) { - if(data.length > 255) { + public SPacketSetServerCookieV4EAG(byte[] data, long expires, boolean revokeQuerySupported, + boolean saveCookieToDisk) { + if (data.length > 255) { throw new IllegalArgumentException("Cookie is too large! (Max 255 bytes)"); } this.data = data; @@ -42,36 +44,6 @@ public class SPacketSetServerCookieV4EAG implements GameMessagePacket { this.saveCookieToDisk = saveCookieToDisk; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - byte b = buffer.readByte(); - revokeQuerySupported = (b & 1) != 0; - saveCookieToDisk = (b & 2) != 0; - expires = buffer.readVarLong(); - int len = buffer.readUnsignedByte(); - if(len > 0) { - data = new byte[len]; - buffer.readFully(data); - }else { - data = null; - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(data != null && data.length > 255) { - throw new IOException("Cookie is too large! (Max 255 bytes)"); - } - buffer.writeByte((revokeQuerySupported ? 1 : 0) | (saveCookieToDisk ? 2 : 0)); - buffer.writeVarLong(expires); - if(data != null) { - buffer.writeByte(data.length); - buffer.write(data); - }else { - buffer.writeByte(0); - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -82,4 +54,34 @@ public class SPacketSetServerCookieV4EAG implements GameMessagePacket { return GamePacketOutputBuffer.getVarLongSize(expires) + 2 + data.length; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + byte b = buffer.readByte(); + revokeQuerySupported = (b & 1) != 0; + saveCookieToDisk = (b & 2) != 0; + expires = buffer.readVarLong(); + int len = buffer.readUnsignedByte(); + if (len > 0) { + data = new byte[len]; + buffer.readFully(data); + } else { + data = null; + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (data != null && data.length > 255) { + throw new IOException("Cookie is too large! (Max 255 bytes)"); + } + buffer.writeByte((revokeQuerySupported ? 1 : 0) | (saveCookieToDisk ? 2 : 0)); + buffer.writeVarLong(expires); + if (data != null) { + buffer.writeByte(data.length); + buffer.write(data); + } else { + buffer.writeByte(0); + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUnforceClientV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUnforceClientV4EAG.java index 41e37daf..9ab00aa5 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUnforceClientV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUnforceClientV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class SPacketUnforceClientV4EAG implements GameMessagePacket { this.resetFNAW = resetFNAW; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 1; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { int i = buffer.readUnsignedByte(); @@ -50,14 +61,4 @@ public class SPacketUnforceClientV4EAG implements GameMessagePacket { buffer.writeByte((resetSkin ? 1 : 0) | (resetCape ? 2 : 0) | (resetFNAW ? 4 : 0)); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 1; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUpdateCertEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUpdateCertEAG.java index b0f90c62..3b1230b2 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUpdateCertEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketUpdateCertEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -33,6 +34,16 @@ public class SPacketUpdateCertEAG implements GameMessagePacket { this.updateCert = updateCert; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return updateCert.length; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { updateCert = buffer.toByteArray(); @@ -45,14 +56,4 @@ public class SPacketUpdateCertEAG implements GameMessagePacket { buffer.write(updateCert); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return updateCert.length; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalAllowedEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalAllowedEAG.java index 36d74e2c..cc538167 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalAllowedEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalAllowedEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,37 +36,6 @@ public class SPacketVoiceSignalAllowedEAG implements GameMessagePacket { this.iceServers = iceServers; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - allowed = buffer.readBoolean(); - if(allowed) { - int numIce = buffer.readVarInt(); - if(numIce > 64) { - throw new IOException("Too many STUN/TURN servers recieved! (" + numIce + ", max is 64!)"); - } - iceServers = new String[numIce]; - for(int i = 0; i < iceServers.length; ++i) { - iceServers[i] = buffer.readStringMC(1024); - } - }else { - iceServers = null; - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(allowed && iceServers.length > 64) { - throw new IOException("Too many STUN/TURN servers to send! (" + iceServers.length + ", max is 64!)"); - } - buffer.writeBoolean(allowed); - if(allowed) { - buffer.writeVarInt(iceServers.length); - for(int i = 0; i < iceServers.length; ++i) { - buffer.writeStringMC(iceServers[i]); - } - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -76,4 +46,35 @@ public class SPacketVoiceSignalAllowedEAG implements GameMessagePacket { return -1; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + allowed = buffer.readBoolean(); + if (allowed) { + int numIce = buffer.readVarInt(); + if (numIce > 64) { + throw new IOException("Too many STUN/TURN servers recieved! (" + numIce + ", max is 64!)"); + } + iceServers = new String[numIce]; + for (int i = 0; i < iceServers.length; ++i) { + iceServers[i] = buffer.readStringMC(1024); + } + } else { + iceServers = null; + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (allowed && iceServers.length > 64) { + throw new IOException("Too many STUN/TURN servers to send! (" + iceServers.length + ", max is 64!)"); + } + buffer.writeBoolean(allowed); + if (allowed) { + buffer.writeVarInt(iceServers.length); + for (int i = 0; i < iceServers.length; ++i) { + buffer.writeStringMC(iceServers[i]); + } + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectAnnounceV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectAnnounceV4EAG.java index 42fd0077..75218808 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectAnnounceV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectAnnounceV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class SPacketVoiceSignalConnectAnnounceV4EAG implements GameMessagePacket this.uuidLeast = uuidLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class SPacketVoiceSignalConnectAnnounceV4EAG implements GameMessagePacket buffer.writeLong(uuidLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV3EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV3EAG.java index 0c3f2347..97d254b8 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV3EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV3EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,27 +40,6 @@ public class SPacketVoiceSignalConnectV3EAG implements GameMessagePacket { this.offer = offer; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - if(buffer.available() > 0) { - isAnnounceType = false; - offer = buffer.readBoolean(); - }else { - isAnnounceType = true; - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - if(!isAnnounceType) { - buffer.writeBoolean(offer); - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -70,4 +50,25 @@ public class SPacketVoiceSignalConnectV3EAG implements GameMessagePacket { return isAnnounceType ? 16 : 17; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + if (buffer.available() > 0) { + isAnnounceType = false; + offer = buffer.readBoolean(); + } else { + isAnnounceType = true; + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + if (!isAnnounceType) { + buffer.writeBoolean(offer); + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV4EAG.java index 4eaf7252..c3093185 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalConnectV4EAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,6 +38,16 @@ public class SPacketVoiceSignalConnectV4EAG implements GameMessagePacket { this.offer = offer; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 17; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -51,14 +62,4 @@ public class SPacketVoiceSignalConnectV4EAG implements GameMessagePacket { buffer.writeBoolean(offer); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 17; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDescEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDescEAG.java index 82a31316..8164954e 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDescEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDescEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,29 +38,6 @@ public class SPacketVoiceSignalDescEAG implements GameMessagePacket { this.desc = desc; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - int descLen = buffer.readVarInt(); - if(descLen > 32750) { - throw new IOException("Voice signal packet DESC too long!"); - } - desc = new byte[descLen]; - buffer.readFully(desc); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(desc.length > 32750) { - throw new IOException("Voice signal packet DESC too long!"); - } - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - buffer.writeVarInt(desc.length); - buffer.write(desc); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -70,4 +48,27 @@ public class SPacketVoiceSignalDescEAG implements GameMessagePacket { return 16 + GamePacketOutputBuffer.getArrayMCSize(desc.length); } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + int descLen = buffer.readVarInt(); + if (descLen > 32750) { + throw new IOException("Voice signal packet DESC too long!"); + } + desc = new byte[descLen]; + buffer.readFully(desc); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (desc.length > 32750) { + throw new IOException("Voice signal packet DESC too long!"); + } + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + buffer.writeVarInt(desc.length); + buffer.write(desc); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDisconnectPeerEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDisconnectPeerEAG.java index 55cab99c..f837cdde 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDisconnectPeerEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalDisconnectPeerEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -35,6 +36,16 @@ public class SPacketVoiceSignalDisconnectPeerEAG implements GameMessagePacket { this.uuidLeast = uuidLeast; } + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 16; + } + @Override public void readPacket(GamePacketInputBuffer buffer) throws IOException { uuidMost = buffer.readLong(); @@ -47,14 +58,4 @@ public class SPacketVoiceSignalDisconnectPeerEAG implements GameMessagePacket { buffer.writeLong(uuidLeast); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 16; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalGlobalEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalGlobalEAG.java index e396573c..c6f306f9 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalGlobalEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalGlobalEAG.java @@ -14,22 +14,21 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SPacketVoiceSignalGlobalEAG implements GameMessagePacket { - public Collection users; - public static class UserData { public long uuidMost; @@ -44,6 +43,8 @@ public class SPacketVoiceSignalGlobalEAG implements GameMessagePacket { } + public Collection users; + public SPacketVoiceSignalGlobalEAG() { } @@ -51,52 +52,6 @@ public class SPacketVoiceSignalGlobalEAG implements GameMessagePacket { this.users = users; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - int cnt = buffer.readVarInt(); - List userList = (List)(users = new ArrayList<>(cnt)); - if(cnt > 0) { - for(int i = 0; i < cnt; ++i) { - userList.add(new UserData(buffer.readLong(), buffer.readLong(), null)); - } - if(buffer.available() > 0) { - for(int i = 0; i < cnt; ++i) { - userList.get(i).username = buffer.readStringMC(16); - } - } - } - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(users == null || users.size() == 0) { - buffer.write(0); - }else { - if(users instanceof RandomAccess) { - List userList = (List)users; - int cnt = userList.size(); - buffer.writeVarInt(cnt); - for(int i = 0; i < cnt; ++i) { - UserData dt = userList.get(i); - buffer.writeLong(dt.uuidMost); - buffer.writeLong(dt.uuidLeast); - } - for(int i = 0; i < cnt; ++i) { - buffer.writeStringMC(userList.get(i).username); - } - }else { - buffer.writeVarInt(users.size()); - for(UserData dt : users) { - buffer.writeLong(dt.uuidMost); - buffer.writeLong(dt.uuidLeast); - } - for(UserData dt : users) { - buffer.writeStringMC(dt.username); - } - } - } - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -107,4 +62,50 @@ public class SPacketVoiceSignalGlobalEAG implements GameMessagePacket { return -1; } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + int cnt = buffer.readVarInt(); + List userList = (List) (users = new ArrayList<>(cnt)); + if (cnt > 0) { + for (int i = 0; i < cnt; ++i) { + userList.add(new UserData(buffer.readLong(), buffer.readLong(), null)); + } + if (buffer.available() > 0) { + for (int i = 0; i < cnt; ++i) { + userList.get(i).username = buffer.readStringMC(16); + } + } + } + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (users == null || users.size() == 0) { + buffer.write(0); + } else { + if (users instanceof RandomAccess) { + List userList = (List) users; + int cnt = userList.size(); + buffer.writeVarInt(cnt); + for (int i = 0; i < cnt; ++i) { + UserData dt = userList.get(i); + buffer.writeLong(dt.uuidMost); + buffer.writeLong(dt.uuidLeast); + } + for (int i = 0; i < cnt; ++i) { + buffer.writeStringMC(userList.get(i).username); + } + } else { + buffer.writeVarInt(users.size()); + for (UserData dt : users) { + buffer.writeLong(dt.uuidMost); + buffer.writeLong(dt.uuidLeast); + } + for (UserData dt : users) { + buffer.writeStringMC(dt.username); + } + } + } + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalICEEAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalICEEAG.java index 0822cef3..f2eb4f51 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalICEEAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketVoiceSignalICEEAG.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -37,29 +38,6 @@ public class SPacketVoiceSignalICEEAG implements GameMessagePacket { this.ice = ice; } - @Override - public void readPacket(GamePacketInputBuffer buffer) throws IOException { - uuidMost = buffer.readLong(); - uuidLeast = buffer.readLong(); - int iceLen = buffer.readVarInt(); - if(iceLen > 32750) { - throw new IOException("Voice signal packet ICE too long!"); - } - ice = new byte[iceLen]; - buffer.readFully(ice); - } - - @Override - public void writePacket(GamePacketOutputBuffer buffer) throws IOException { - if(ice.length > 32750) { - throw new IOException("Voice signal packet ICE too long!"); - } - buffer.writeLong(uuidMost); - buffer.writeLong(uuidLeast); - buffer.writeVarInt(ice.length); - buffer.write(ice); - } - @Override public void handlePacket(GameMessageHandler handler) { handler.handleServer(this); @@ -70,4 +48,27 @@ public class SPacketVoiceSignalICEEAG implements GameMessagePacket { return 16 + GamePacketOutputBuffer.getArrayMCSize(ice.length); } + @Override + public void readPacket(GamePacketInputBuffer buffer) throws IOException { + uuidMost = buffer.readLong(); + uuidLeast = buffer.readLong(); + int iceLen = buffer.readVarInt(); + if (iceLen > 32750) { + throw new IOException("Voice signal packet ICE too long!"); + } + ice = new byte[iceLen]; + buffer.readFully(ice); + } + + @Override + public void writePacket(GamePacketOutputBuffer buffer) throws IOException { + if (ice.length > 32750) { + throw new IOException("Voice signal packet ICE too long!"); + } + buffer.writeLong(uuidMost); + buffer.writeLong(uuidLeast); + buffer.writeVarInt(ice.length); + buffer.write(ice); + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketWebViewMessageV4EAG.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketWebViewMessageV4EAG.java index aa47a718..41dd3381 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketWebViewMessageV4EAG.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/pkt/server/SPacketWebViewMessageV4EAG.java @@ -11,14 +11,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,6 +35,11 @@ public class SPacketWebViewMessageV4EAG implements GameMessagePacket { public SPacketWebViewMessageV4EAG() { } + public SPacketWebViewMessageV4EAG(byte[] data) { + this.type = TYPE_BINARY; + this.data = data; + } + public SPacketWebViewMessageV4EAG(int type, byte[] data) { this.type = type; this.data = data; @@ -44,9 +50,14 @@ public class SPacketWebViewMessageV4EAG implements GameMessagePacket { this.data = str.getBytes(StandardCharsets.UTF_8); } - public SPacketWebViewMessageV4EAG(byte[] data) { - this.type = TYPE_BINARY; - this.data = data; + @Override + public void handlePacket(GameMessageHandler handler) { + handler.handleServer(this); + } + + @Override + public int length() { + return 1 + GamePacketOutputBuffer.getVarIntSize(data.length) + data.length; } @Override @@ -61,14 +72,4 @@ public class SPacketWebViewMessageV4EAG implements GameMessagePacket { buffer.writeByteArrayMC(data); } - @Override - public void handlePacket(GameMessageHandler handler) { - handler.handleServer(this); - } - - @Override - public int length() { - return 1 + GamePacketOutputBuffer.getVarIntSize(data.length) + data.length; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/PacketImageData.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/PacketImageData.java index be29f9bc..08786110 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/PacketImageData.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/PacketImageData.java @@ -8,22 +8,66 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePacketOutputBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class PacketImageData { + public static PacketImageData readRGB16(GamePacketInputBuffer buffer) throws IOException { + int w = buffer.readUnsignedByte(); + int h = buffer.readUnsignedByte(); + int pixelCount = w * h; + int[] pixels = new int[pixelCount]; + for (int j = 0, p, pR, pG, pB; j < pixelCount; ++j) { + p = buffer.readUnsignedShort(); + pR = (p >>> 11) & 0x1F; + pG = (p >>> 5) & 0x3F; + pB = p & 0x1F; + if (pR + pG + pB > 0) { + pB = (int) ((pB - 1) * 8.5f); + pixels[j] = 0xFF000000 | (pR << 19) | (pG << 10) | pB; + } else { + pixels[j] = 0; + } + } + return new PacketImageData(w, h, pixels); + } + + public static void writeRGB16(GamePacketOutputBuffer buffer, PacketImageData imageData) throws IOException { + if (imageData.width < 1 || imageData.width > 255 || imageData.height < 1 || imageData.height > 255) { + throw new IOException("Invalid image dimensions in packet, must be between 1x1 and 255x255, got " + + imageData.width + "x" + imageData.height); + } + buffer.writeByte(imageData.width); + buffer.writeByte(imageData.height); + int pixelCount = imageData.width * imageData.height; + for (int j = 0, p, pR, pG, pB; j < pixelCount; ++j) { + p = imageData.rgba[j]; + if ((p >>> 24) > 0x7F) { + pR = (p >>> 19) & 0x1F; + pG = (p >>> 10) & 0x3F; + pB = (int) ((p & 0xFF) * 0.1176471f) + 1; + buffer.writeShort((pR << 11) | (pG << 5) | pB); + } else { + buffer.writeShort(0); + } + } + } + public final int width; + public final int height; + public final int[] rgba; public PacketImageData(int width, int height, int[] rgba) { @@ -36,44 +80,4 @@ public class PacketImageData { return 2 + (rgba.length << 1); } - public static PacketImageData readRGB16(GamePacketInputBuffer buffer) throws IOException { - int w = buffer.readUnsignedByte(); - int h = buffer.readUnsignedByte(); - int pixelCount = w * h; - int[] pixels = new int[pixelCount]; - for(int j = 0, p, pR, pG, pB; j < pixelCount; ++j) { - p = buffer.readUnsignedShort(); - pR = (p >>> 11) & 0x1F; - pG = (p >>> 5) & 0x3F; - pB = p & 0x1F; - if(pR + pG + pB > 0) { - pB = (int)((pB - 1) * 8.5f); - pixels[j] = 0xFF000000 | (pR << 19) | (pG << 10) | pB; - }else { - pixels[j] = 0; - } - } - return new PacketImageData(w, h, pixels); - } - - public static void writeRGB16(GamePacketOutputBuffer buffer, PacketImageData imageData) throws IOException { - if(imageData.width < 1 || imageData.width > 255 || imageData.height < 1 || imageData.height > 255) { - throw new IOException("Invalid image dimensions in packet, must be between 1x1 and 255x255, got " + imageData.width + "x" + imageData.height); - } - buffer.writeByte(imageData.width); - buffer.writeByte(imageData.height); - int pixelCount = imageData.width * imageData.height; - for(int j = 0, p, pR, pG, pB; j < pixelCount; ++j) { - p = imageData.rgba[j]; - if((p >>> 24) > 0x7F) { - pR = (p >>> 19) & 0x1F; - pG = (p >>> 10) & 0x3F; - pB = (int)((p & 0xFF) * 0.1176471f) + 1; - buffer.writeShort((pR << 11) | (pG << 5) | pB); - }else { - buffer.writeShort(0); - } - } - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayInputStream.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayInputStream.java index 637bbde1..dc32600b 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayInputStream.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayInputStream.java @@ -6,14 +6,15 @@ import java.io.InputStream; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,52 +25,21 @@ public class ReusableByteArrayInputStream extends InputStream { private int idx = 0; private int markIDX = 0; + public int available() { + return Math.max(currentBuffer.length - idx, 0); + } + public void feedBuffer(byte[] b) { currentBuffer = b; idx = 0; markIDX = 0; } - @Override - public int read() throws IOException { - if(currentBuffer.length <= idx) throw new IOException("ReusableByteArrayInputStream buffer underflow, no bytes remaining"); - return (int)currentBuffer[idx++] & 0xFF; - } - - @Override - public int read(byte b[], int off, int len) throws IOException { - if(idx + len > currentBuffer.length) { - throw new IOException( - "ReusableByteArrayInputStream buffer underflow, tried to read " + len + " when there are only " - + (currentBuffer.length - idx) + " bytes remaining", - new ArrayIndexOutOfBoundsException(idx + len - 1)); - } - if(off + len > b.length) { - throw new ArrayIndexOutOfBoundsException(off + len - 1); - } - System.arraycopy(currentBuffer, idx, b, off, len); - idx += len; - return len; - } - - public void mark() { - markIDX = idx; - } - - public void reset() { - idx = markIDX; - } - public int getReaderIndex() { return idx; } - public int available() { - return Math.max(currentBuffer.length - idx, 0); - } - - public void setReaderIndex(int i) { - idx = i; + public void mark() { markIDX = idx; } @@ -77,4 +47,36 @@ public class ReusableByteArrayInputStream extends InputStream { return true; } + @Override + public int read() throws IOException { + if (currentBuffer.length <= idx) + throw new IOException("ReusableByteArrayInputStream buffer underflow, no bytes remaining"); + return (int) currentBuffer[idx++] & 0xFF; + } + + @Override + public int read(byte b[], int off, int len) throws IOException { + if (idx + len > currentBuffer.length) { + throw new IOException( + "ReusableByteArrayInputStream buffer underflow, tried to read " + len + " when there are only " + + (currentBuffer.length - idx) + " bytes remaining", + new ArrayIndexOutOfBoundsException(idx + len - 1)); + } + if (off + len > b.length) { + throw new ArrayIndexOutOfBoundsException(off + len - 1); + } + System.arraycopy(currentBuffer, idx, b, off, len); + idx += len; + return len; + } + + public void reset() { + idx = markIDX; + } + + public void setReaderIndex(int i) { + idx = i; + markIDX = idx; + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayOutputStream.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayOutputStream.java index 27ad95bf..b56681d4 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayOutputStream.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/ReusableByteArrayOutputStream.java @@ -7,14 +7,15 @@ import java.util.Arrays; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,13 +25,31 @@ public class ReusableByteArrayOutputStream extends OutputStream { private volatile byte[] currentBuffer = null; private int idx = 0; private int originalSize = 0; - + public void feedBuffer(byte[] buf) { currentBuffer = buf; idx = 0; originalSize = buf == null ? 0 : buf.length; } + public int getWriterIndex() { + return idx; + } + + private void growBuffer(int i) { + int ii = currentBuffer.length; + int iii = i - ii; + if (iii > 0) { + int j = ii + (ii >> 1); + while (j < i) { + j += (j >> 1); + } + byte[] n = new byte[j]; + System.arraycopy(currentBuffer, 0, n, 0, ii); + currentBuffer = n; + } + } + public boolean hasGrown() { return currentBuffer.length != originalSize; } @@ -39,43 +58,25 @@ public class ReusableByteArrayOutputStream extends OutputStream { return currentBuffer.length == idx ? currentBuffer : Arrays.copyOf(currentBuffer, idx); } - private void growBuffer(int i) { - int ii = currentBuffer.length; - int iii = i - ii; - if(iii > 0) { - int j = ii + (ii >> 1); - while(j < i) { - j += (j >> 1); - } - byte[] n = new byte[j]; - System.arraycopy(currentBuffer, 0, n, 0, ii); - currentBuffer = n; - } - } - - public int getWriterIndex() { - return idx; - } - public void setWriterIndex(int i) { idx = i; } - @Override - public void write(int b) throws IOException { - if(idx >= currentBuffer.length) { - growBuffer(idx + 1); - } - currentBuffer[idx++] = (byte) b; - } - @Override public void write(byte b[], int off, int len) throws IOException { - if(idx + len > currentBuffer.length) { + if (idx + len > currentBuffer.length) { growBuffer(idx + len); } System.arraycopy(b, off, currentBuffer, idx, len); idx += len; } + @Override + public void write(int b) throws IOException { + if (idx >= currentBuffer.length) { + growBuffer(idx + 1); + } + currentBuffer[idx++] = (byte) b; + } + } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleInputBufferImpl.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleInputBufferImpl.java index 634e8097..c287cfdd 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleInputBufferImpl.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleInputBufferImpl.java @@ -13,14 +13,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePacketInputBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -39,66 +40,42 @@ public class SimpleInputBufferImpl extends DataInputStream implements GamePacket this.toByteArrayReturns = toByteArrayReturns; } - public void setStream(InputStream parent) { - in = parent; - toByteArrayReturns = null; - } - - public void setToByteArrayReturns(byte[] toByteArrayReturns) { - this.toByteArrayReturns = toByteArrayReturns; + @Override + public byte[] readByteArrayMC() throws IOException { + byte[] abyte = new byte[this.readVarInt()]; + this.readFully(abyte); + return abyte; } @Override - public void skipAllBytes(int n) throws IOException { - if(skipBytes(n) != n) { + public String readStringEaglerASCII16() throws IOException { + int len = readUnsignedShort(); + char[] ret = new char[len]; + for (int i = 0, j; i < len; ++i) { + j = in.read(); + if (j < 0) { + throw new EOFException(); + } + ret[i] = (char) j; + } + return new String(ret); + } + + @Override + public String readStringEaglerASCII8() throws IOException { + int len = in.read(); + if (len < 0) { throw new EOFException(); } - } - - @Override - public int readVarInt() throws IOException { - int i = 0; - int j = 0; - - while (true) { - int b0 = in.read(); - if(b0 < 0) { + char[] ret = new char[len]; + for (int i = 0, j; i < len; ++i) { + j = in.read(); + if (j < 0) { throw new EOFException(); } - i |= (b0 & 127) << j++ * 7; - if (j > 5) { - throw new IOException("VarInt too big"); - } - - if ((b0 & 128) != 128) { - break; - } + ret[i] = (char) j; } - - return i; - } - - @Override - public long readVarLong() throws IOException { - long i = 0L; - int j = 0; - - while (true) { - int b0 = in.read(); - if(b0 < 0) { - throw new EOFException(); - } - i |= (long) (b0 & 127) << j++ * 7; - if (j > 10) { - throw new IOException("VarLong too big"); - } - - if ((b0 & 128) != 128) { - break; - } - } - - return i; + return new String(ret); } @Override @@ -123,41 +100,65 @@ public class SimpleInputBufferImpl extends DataInputStream implements GamePacket } @Override - public String readStringEaglerASCII8() throws IOException { - int len = in.read(); - if(len < 0) { + public int readVarInt() throws IOException { + int i = 0; + int j = 0; + + while (true) { + int b0 = in.read(); + if (b0 < 0) { + throw new EOFException(); + } + i |= (b0 & 127) << j++ * 7; + if (j > 5) { + throw new IOException("VarInt too big"); + } + + if ((b0 & 128) != 128) { + break; + } + } + + return i; + } + + @Override + public long readVarLong() throws IOException { + long i = 0L; + int j = 0; + + while (true) { + int b0 = in.read(); + if (b0 < 0) { + throw new EOFException(); + } + i |= (long) (b0 & 127) << j++ * 7; + if (j > 10) { + throw new IOException("VarLong too big"); + } + + if ((b0 & 128) != 128) { + break; + } + } + + return i; + } + + public void setStream(InputStream parent) { + in = parent; + toByteArrayReturns = null; + } + + public void setToByteArrayReturns(byte[] toByteArrayReturns) { + this.toByteArrayReturns = toByteArrayReturns; + } + + @Override + public void skipAllBytes(int n) throws IOException { + if (skipBytes(n) != n) { throw new EOFException(); } - char[] ret = new char[len]; - for(int i = 0, j; i < len; ++i) { - j = in.read(); - if(j < 0) { - throw new EOFException(); - } - ret[i] = (char)j; - } - return new String(ret); - } - - @Override - public String readStringEaglerASCII16() throws IOException { - int len = readUnsignedShort(); - char[] ret = new char[len]; - for(int i = 0, j; i < len; ++i) { - j = in.read(); - if(j < 0) { - throw new EOFException(); - } - ret[i] = (char)j; - } - return new String(ret); - } - - @Override - public byte[] readByteArrayMC() throws IOException { - byte[] abyte = new byte[this.readVarInt()]; - this.readFully(abyte); - return abyte; } @Override @@ -167,39 +168,39 @@ public class SimpleInputBufferImpl extends DataInputStream implements GamePacket @Override public byte[] toByteArray() throws IOException { - if(toByteArrayReturns != null) { + if (toByteArrayReturns != null) { return toByteArrayReturns; - }else if(in instanceof ByteArrayInputStream) { - ByteArrayInputStream bis = (ByteArrayInputStream)in; + } else if (in instanceof ByteArrayInputStream) { + ByteArrayInputStream bis = (ByteArrayInputStream) in; byte[] ret = new byte[bis.available()]; bis.read(ret); return ret; - }else { + } else { ByteArrayOutputStream bao = null; byte[] copyBuffer = new byte[in.available()]; int i = in.read(copyBuffer); - if(i == copyBuffer.length) { + if (i == copyBuffer.length) { int j = in.read(); - if(j == -1) { + if (j == -1) { return copyBuffer; - }else { + } else { int k = Math.max(copyBuffer.length, 64); bao = new ByteArrayOutputStream(k + 1); bao.write(copyBuffer); bao.write(j); - if(k != copyBuffer.length) { + if (k != copyBuffer.length) { copyBuffer = new byte[k]; } } - }else { + } else { int j = Math.max(copyBuffer.length, 64); bao = new ByteArrayOutputStream(j); bao.write(copyBuffer); - if(j != copyBuffer.length) { + if (j != copyBuffer.length) { copyBuffer = new byte[j]; } } - while((i = in.read(copyBuffer)) != -1) { + while ((i = in.read(copyBuffer)) != -1) { bao.write(copyBuffer, 0, i); } return bao.toByteArray(); diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleOutputBufferImpl.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleOutputBufferImpl.java index 30c3d871..99a61db9 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleOutputBufferImpl.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SimpleOutputBufferImpl.java @@ -10,14 +10,15 @@ import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePacketOutputBuffer; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -32,6 +33,60 @@ public class SimpleOutputBufferImpl extends DataOutputStream implements GamePack out = parent; } + @Override + public OutputStream stream() { + return out; + } + + @Override + public void writeByteArrayMC(byte[] bytes) throws IOException { + this.writeVarInt(bytes.length); + this.write(bytes); + } + + @Override + public void writeStringEaglerASCII16(String str) throws IOException { + int len = str.length(); + if (len > 65535) { + throw new IOException("String is longer than 65535 chars! (" + len + ")"); + } + writeShort(len); + for (int i = 0, j; i < len; ++i) { + j = (int) str.charAt(i); + if (j > 255) { + j = (int) '?'; + } + out.write(j); + } + } + + @Override + public void writeStringEaglerASCII8(String str) throws IOException { + int len = str.length(); + if (len > 255) { + throw new IOException("String is longer than 255 chars! (" + len + ")"); + } + out.write(len); + for (int i = 0, j; i < len; ++i) { + j = (int) str.charAt(i); + if (j > 255) { + j = (int) '?'; + } + out.write(j); + } + } + + @Override + public void writeStringMC(String str) throws IOException { + byte[] abyte = str.getBytes(StandardCharsets.UTF_8); + if (abyte.length > 32767) { + throw new IOException("String too big (was " + str.length() + " bytes encoded, max " + 32767 + ")"); + } else { + this.writeVarInt(abyte.length); + this.write(abyte); + } + } + @Override public void writeVarInt(int i) throws IOException { while ((i & -128) != 0) { @@ -50,58 +105,4 @@ public class SimpleOutputBufferImpl extends DataOutputStream implements GamePack out.write((int) i); } - @Override - public void writeStringMC(String str) throws IOException { - byte[] abyte = str.getBytes(StandardCharsets.UTF_8); - if (abyte.length > 32767) { - throw new IOException("String too big (was " + str.length() + " bytes encoded, max " + 32767 + ")"); - } else { - this.writeVarInt(abyte.length); - this.write(abyte); - } - } - - @Override - public void writeStringEaglerASCII8(String str) throws IOException { - int len = str.length(); - if(len > 255) { - throw new IOException("String is longer than 255 chars! (" + len + ")"); - } - out.write(len); - for(int i = 0, j; i < len; ++i) { - j = (int)str.charAt(i); - if(j > 255) { - j = (int)'?'; - } - out.write(j); - } - } - - @Override - public void writeStringEaglerASCII16(String str) throws IOException { - int len = str.length(); - if(len > 65535) { - throw new IOException("String is longer than 65535 chars! (" + len + ")"); - } - writeShort(len); - for(int i = 0, j; i < len; ++i) { - j = (int)str.charAt(i); - if(j > 255) { - j = (int)'?'; - } - out.write(j); - } - } - - @Override - public void writeByteArrayMC(byte[] bytes) throws IOException { - this.writeVarInt(bytes.length); - this.write(bytes); - } - - @Override - public OutputStream stream() { - return out; - } - } diff --git a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SkinPacketVersionCache.java b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SkinPacketVersionCache.java index 1bb0d952..94f29616 100644 --- a/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SkinPacketVersionCache.java +++ b/src/protocol-game/java/net/lax1dude/eaglercraft/v1_8/socket/protocol/util/SkinPacketVersionCache.java @@ -2,43 +2,122 @@ package net.lax1dude.eaglercraft.v1_8.socket.protocol.util; import net.lax1dude.eaglercraft.v1_8.socket.protocol.GamePluginMessageProtocol; import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.GameMessagePacket; -import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.*; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketForceClientSkinPresetV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV3EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinCustomV4EAG; +import net.lax1dude.eaglercraft.v1_8.socket.protocol.pkt.server.SPacketOtherSkinPresetEAG; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class SkinPacketVersionCache { - public GameMessagePacket skinPacketV3; - public GameMessagePacket skinPacketV4; - - public SkinPacketVersionCache(GameMessagePacket skinPacketV3, GameMessagePacket skinPacketV4) { - this.skinPacketV3 = skinPacketV3; - this.skinPacketV4 = skinPacketV4; + public static GameMessagePacket convertToForceV4(GameMessagePacket v4pkt) { + if (v4pkt instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG) v4pkt; + return new SPacketForceClientSkinCustomV4EAG(pkt.modelID, pkt.customSkin); + } else if (v4pkt instanceof SPacketOtherSkinPresetEAG) { + return new SPacketForceClientSkinPresetV4EAG(((SPacketOtherSkinPresetEAG) v4pkt).presetSkin); + } else { + return v4pkt; + } } - public static SkinPacketVersionCache createPreset(long uuidMost, long uuidLeast) { - long hilo = uuidMost ^ uuidLeast; - GameMessagePacket pkt = new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, - ((((int) (hilo >> 32)) ^ (int) hilo) & 1) != 0 ? 1 : 0); - return new SkinPacketVersionCache(pkt, pkt); + public static GameMessagePacket convertToV3(GameMessagePacket v4pkt) { + if (v4pkt instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG) v4pkt; + return new SPacketOtherSkinCustomV3EAG(pkt.uuidMost, pkt.uuidLeast, pkt.modelID, + convertToV3Raw(pkt.customSkin)); + } else { + return v4pkt; + } } - public static SkinPacketVersionCache createPreset(long uuidMost, long uuidLeast, int presetID) { - GameMessagePacket pkt = new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, presetID); - return new SkinPacketVersionCache(pkt, pkt); + public static byte[] convertToV3Raw(byte[] v4data) { + byte[] v3data = new byte[16384]; + for (int i = 0, j, k; i < 4096; ++i) { + j = i * 3; + k = i << 2; + v3data[k + 1] = v4data[j]; + v3data[k + 2] = v4data[j + 1]; + v3data[k + 3] = (byte) (v4data[j + 2] << 1); + v3data[k] = (v4data[j + 2] & 0x80) != 0 ? (byte) 0xFF : (byte) 0; + } + return v3data; + } + + public static GameMessagePacket convertToV3RewriteUUID(GameMessagePacket v4pkt, long uuidMost, long uuidLeast) { + if (v4pkt instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG) v4pkt; + return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, pkt.modelID, convertToV3Raw(pkt.customSkin)); + } else { + return v4pkt; + } + } + + public static GameMessagePacket convertToV3RewriteUUIDModel(GameMessagePacket v4pkt, long uuidMost, long uuidLeast, + int modelID) { + if (v4pkt instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG) v4pkt; + return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, modelID, convertToV3Raw(pkt.customSkin)); + } else { + return v4pkt; + } + } + + public static GameMessagePacket convertToV4(GameMessagePacket v3pkt) { + if (v3pkt instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG) v3pkt; + return new SPacketOtherSkinCustomV4EAG(pkt.uuidMost, pkt.uuidLeast, pkt.modelID, + convertToV4Raw(pkt.customSkin)); + } else { + return v3pkt; + } + } + + public static byte[] convertToV4Raw(byte[] v3data) { + byte[] v4data = new byte[12288]; + for (int i = 0, j, k; i < 4096; ++i) { + j = i << 2; + k = i * 3; + v4data[k] = v3data[j + 1]; + v4data[k + 1] = v3data[j + 2]; + v4data[k + 2] = (byte) ((v3data[j + 3] >>> 1) | (v3data[j] & 0x80)); + } + return v4data; + } + + public static GameMessagePacket convertToV4RewriteUUID(GameMessagePacket v3pkt, long uuidMost, long uuidLeast) { + if (v3pkt instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG) v3pkt; + return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, pkt.modelID, convertToV4Raw(pkt.customSkin)); + } else { + return v3pkt; + } + } + + public static GameMessagePacket convertToV4RewriteUUIDModel(GameMessagePacket v3pkt, long uuidMost, long uuidLeast, + int modelID) { + if (v3pkt instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG) v3pkt; + return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, modelID, convertToV4Raw(pkt.customSkin)); + } else { + return v3pkt; + } } public static SkinPacketVersionCache createCustomV3(long uuidMost, long uuidLeast, int modelID, byte[] texture) { @@ -49,8 +128,103 @@ public class SkinPacketVersionCache { return new SkinPacketVersionCache(null, new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, modelID, texture)); } + public static SkinPacketVersionCache createPreset(long uuidMost, long uuidLeast) { + long hilo = uuidMost ^ uuidLeast; + GameMessagePacket pkt = new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, + ((((int) (hilo >> 32)) ^ (int) hilo) & 1) != 0 ? 1 : 0); + return new SkinPacketVersionCache(pkt, pkt); + } + + public static SkinPacketVersionCache createPreset(long uuidMost, long uuidLeast, int presetID) { + GameMessagePacket pkt = new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, presetID); + return new SkinPacketVersionCache(pkt, pkt); + } + + public static GameMessagePacket rewriteUUID(GameMessagePacket pkt, long uuidMost, long uuidLeast) { + if (pkt instanceof SPacketOtherSkinPresetEAG) { + return new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, ((SPacketOtherSkinPresetEAG) pkt).presetSkin); + } else if (pkt instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG) pkt; + return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); + } else if (pkt instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG) pkt; + return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); + } else { + return pkt; + } + } + + public static SkinPacketVersionCache rewriteUUID(SkinPacketVersionCache pkt, long uuidMost, long uuidLeast) { + GameMessagePacket rv3 = null; + GameMessagePacket rv4 = null; + if (pkt.skinPacketV3 != null) { + if (pkt.skinPacketV3 instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG) pkt.skinPacketV3; + rv3 = new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); + } else { + rv3 = pkt.skinPacketV3; + } + } + if (pkt.skinPacketV4 != null) { + if (pkt.skinPacketV4 instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG) pkt.skinPacketV4; + rv4 = new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); + } else { + rv4 = pkt.skinPacketV4; + } + } + return new SkinPacketVersionCache(rv3, rv4); + } + + public static GameMessagePacket rewriteUUIDModel(GameMessagePacket pkt, long uuidMost, long uuidLeast, + int modelID) { + if (pkt instanceof SPacketOtherSkinPresetEAG) { + return new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, ((SPacketOtherSkinPresetEAG) pkt).presetSkin); + } else if (pkt instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG) pkt; + return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, modelID, pkt2.customSkin); + } else if (pkt instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG) pkt; + return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, modelID, pkt2.customSkin); + } else { + return pkt; + } + } + + public static SkinPacketVersionCache rewriteUUIDModel(SkinPacketVersionCache pkt, long uuidMost, long uuidLeast, + int model) { + GameMessagePacket rv3 = null; + GameMessagePacket rv4 = null; + if (pkt.skinPacketV3 != null) { + if (pkt.skinPacketV3 instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG) pkt.skinPacketV3; + rv3 = new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, model, pkt2.customSkin); + } else { + rv3 = pkt.skinPacketV3; + } + } + if (pkt.skinPacketV4 != null) { + if (pkt.skinPacketV4 instanceof SPacketOtherSkinCustomV4EAG) { + SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG) pkt.skinPacketV4; + rv4 = new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, model, pkt2.customSkin); + } else { + rv4 = pkt.skinPacketV4; + } + } + return new SkinPacketVersionCache(rv3, rv4); + } + + public GameMessagePacket skinPacketV3; + + public GameMessagePacket skinPacketV4; + + public SkinPacketVersionCache(GameMessagePacket skinPacketV3, GameMessagePacket skinPacketV4) { + this.skinPacketV3 = skinPacketV3; + this.skinPacketV4 = skinPacketV4; + } + public GameMessagePacket get(GamePluginMessageProtocol vers) { - switch(vers) { + switch (vers) { case V3: return getV3(); case V4: @@ -61,7 +235,7 @@ public class SkinPacketVersionCache { } public GameMessagePacket get(GamePluginMessageProtocol vers, long rewriteUUIDMost, long rewriteUUIDLeast) { - switch(vers) { + switch (vers) { case V3: return getV3(rewriteUUIDMost, rewriteUUIDLeast); case V4: @@ -71,8 +245,9 @@ public class SkinPacketVersionCache { } } - public GameMessagePacket get(GamePluginMessageProtocol vers, long rewriteUUIDMost, long rewriteUUIDLeast, int rewriteModel) { - switch(vers) { + public GameMessagePacket get(GamePluginMessageProtocol vers, long rewriteUUIDMost, long rewriteUUIDLeast, + int rewriteModel) { + switch (vers) { case V3: return getV3(rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); case V4: @@ -82,278 +257,118 @@ public class SkinPacketVersionCache { } } - public GameMessagePacket getV3() { - if(skinPacketV3 != null) { - return skinPacketV3; - }else { - if(skinPacketV4 == null) { - return null; - } - return skinPacketV3 = convertToV3(skinPacketV4); - } - } - - public GameMessagePacket getV4() { - if(skinPacketV4 != null) { - return skinPacketV4; - }else { - if(skinPacketV3 == null) { - return null; - } - return skinPacketV4 = convertToV4(skinPacketV3); - } - } - - public GameMessagePacket getV3(long rewriteUUIDMost, long rewriteUUIDLeast) { - if(skinPacketV3 != null) { - return rewriteUUID(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast); - }else { - if(skinPacketV4 == null) { - return null; - } - return skinPacketV3 = convertToV3RewriteUUID(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast); - } - } - - public GameMessagePacket getV4(long rewriteUUIDMost, long rewriteUUIDLeast) { - if(skinPacketV4 != null) { - return rewriteUUID(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast); - }else { - if(skinPacketV3 == null) { - return null; - } - return skinPacketV4 = convertToV4RewriteUUID(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast); - } - } - - public GameMessagePacket getV3(long rewriteUUIDMost, long rewriteUUIDLeast, int rewriteModel) { - if(skinPacketV3 != null) { - return rewriteUUIDModel(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); - }else { - if(skinPacketV4 == null) { - return null; - } - return skinPacketV3 = convertToV3RewriteUUIDModel(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); - } - } - - public GameMessagePacket getV4(long rewriteUUIDMost, long rewriteUUIDLeast, int rewriteModel) { - if(skinPacketV4 != null) { - return rewriteUUIDModel(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); - }else { - if(skinPacketV3 == null) { - return null; - } - return skinPacketV4 = convertToV4RewriteUUIDModel(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); - } - } - public GameMessagePacket getForceClientV4() { - if(skinPacketV4 != null) { + if (skinPacketV4 != null) { return convertToForceV4(skinPacketV4); - }else { - if(skinPacketV3 == null) { + } else { + if (skinPacketV3 == null) { return null; } return convertToForceV4(skinPacketV4 = convertToV4(skinPacketV3)); } } - public byte[] getV3HandshakeData() { - GameMessagePacket packetV3 = getV3(); - if(packetV3 instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG)packetV3; - byte[] tex = pkt.customSkin; - byte[] ret = new byte[2 + tex.length]; - ret[0] = (byte)2; - ret[1] = (byte)pkt.modelID; - System.arraycopy(tex, 0, ret, 2, tex.length); - return ret; - }else { - SPacketOtherSkinPresetEAG pkt = (SPacketOtherSkinPresetEAG)packetV3; - int p = pkt.presetSkin; - byte[] ret = new byte[5]; - ret[0] = (byte)1; - ret[1] = (byte)(p >>> 24); - ret[2] = (byte)(p >>> 16); - ret[3] = (byte)(p >>> 8); - ret[4] = (byte)(p & 0xFF); - return ret; - } - } - public int getModelId() { - if(skinPacketV4 != null) { - if(skinPacketV4 instanceof SPacketOtherSkinCustomV4EAG) { - return ((SPacketOtherSkinCustomV4EAG)skinPacketV4).modelID; + if (skinPacketV4 != null) { + if (skinPacketV4 instanceof SPacketOtherSkinCustomV4EAG) { + return ((SPacketOtherSkinCustomV4EAG) skinPacketV4).modelID; } - }else if(skinPacketV3 != null) { - if(skinPacketV3 instanceof SPacketOtherSkinCustomV3EAG) { - return ((SPacketOtherSkinCustomV3EAG)skinPacketV3).modelID; + } else if (skinPacketV3 != null) { + if (skinPacketV3 instanceof SPacketOtherSkinCustomV3EAG) { + return ((SPacketOtherSkinCustomV3EAG) skinPacketV3).modelID; } } return -1; } - public static GameMessagePacket rewriteUUID(GameMessagePacket pkt, long uuidMost, long uuidLeast) { - if(pkt instanceof SPacketOtherSkinPresetEAG) { - return new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, ((SPacketOtherSkinPresetEAG)pkt).presetSkin); - }else if(pkt instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG)pkt; - return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); - }else if(pkt instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG)pkt; - return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); - }else { - return pkt; - } - } - - public static GameMessagePacket rewriteUUIDModel(GameMessagePacket pkt, long uuidMost, long uuidLeast, int modelID) { - if(pkt instanceof SPacketOtherSkinPresetEAG) { - return new SPacketOtherSkinPresetEAG(uuidMost, uuidLeast, ((SPacketOtherSkinPresetEAG)pkt).presetSkin); - }else if(pkt instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG)pkt; - return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, modelID, pkt2.customSkin); - }else if(pkt instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG)pkt; - return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, modelID, pkt2.customSkin); - }else { - return pkt; - } - } - - public static byte[] convertToV3Raw(byte[] v4data) { - byte[] v3data = new byte[16384]; - for(int i = 0, j, k; i < 4096; ++i) { - j = i * 3; - k = i << 2; - v3data[k + 1] = v4data[j]; - v3data[k + 2] = v4data[j + 1]; - v3data[k + 3] = (byte)(v4data[j + 2] << 1); - v3data[k] = (v4data[j + 2] & 0x80) != 0 ? (byte)0xFF : (byte)0; - } - return v3data; - } - - public static byte[] convertToV4Raw(byte[] v3data) { - byte[] v4data = new byte[12288]; - for(int i = 0, j, k; i < 4096; ++i) { - j = i << 2; - k = i * 3; - v4data[k] = v3data[j + 1]; - v4data[k + 1] = v3data[j + 2]; - v4data[k + 2] = (byte)((v3data[j + 3] >>> 1) | (v3data[j] & 0x80)); - } - return v4data; - } - - public static GameMessagePacket convertToV3(GameMessagePacket v4pkt) { - if(v4pkt instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG)v4pkt; - return new SPacketOtherSkinCustomV3EAG(pkt.uuidMost, pkt.uuidLeast, pkt.modelID, convertToV3Raw(pkt.customSkin)); - }else { - return v4pkt; - } - } - - public static GameMessagePacket convertToV4(GameMessagePacket v3pkt) { - if(v3pkt instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG)v3pkt; - return new SPacketOtherSkinCustomV4EAG(pkt.uuidMost, pkt.uuidLeast, pkt.modelID, convertToV4Raw(pkt.customSkin)); - }else { - return v3pkt; - } - } - - public static GameMessagePacket convertToV3RewriteUUID(GameMessagePacket v4pkt, long uuidMost, long uuidLeast) { - if(v4pkt instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG)v4pkt; - return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, pkt.modelID, convertToV3Raw(pkt.customSkin)); - }else { - return v4pkt; - } - } - - public static GameMessagePacket convertToV4RewriteUUID(GameMessagePacket v3pkt, long uuidMost, long uuidLeast) { - if(v3pkt instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG)v3pkt; - return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, pkt.modelID, convertToV4Raw(pkt.customSkin)); - }else { - return v3pkt; - } - } - - public static GameMessagePacket convertToV3RewriteUUIDModel(GameMessagePacket v4pkt, long uuidMost, long uuidLeast, int modelID) { - if(v4pkt instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG)v4pkt; - return new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, modelID, convertToV3Raw(pkt.customSkin)); - }else { - return v4pkt; - } - } - - public static GameMessagePacket convertToV4RewriteUUIDModel(GameMessagePacket v3pkt, long uuidMost, long uuidLeast, int modelID) { - if(v3pkt instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG)v3pkt; - return new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, modelID, convertToV4Raw(pkt.customSkin)); - }else { - return v3pkt; - } - } - - public static SkinPacketVersionCache rewriteUUID(SkinPacketVersionCache pkt, long uuidMost, long uuidLeast) { - GameMessagePacket rv3 = null; - GameMessagePacket rv4 = null; - if(pkt.skinPacketV3 != null) { - if(pkt.skinPacketV3 instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG)pkt.skinPacketV3; - rv3 = new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); - }else { - rv3 = pkt.skinPacketV3; + public GameMessagePacket getV3() { + if (skinPacketV3 != null) { + return skinPacketV3; + } else { + if (skinPacketV4 == null) { + return null; } + return skinPacketV3 = convertToV3(skinPacketV4); } - if(pkt.skinPacketV4 != null) { - if(pkt.skinPacketV4 instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG)pkt.skinPacketV4; - rv4 = new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, pkt2.modelID, pkt2.customSkin); - }else { - rv4 = pkt.skinPacketV4; - } - } - return new SkinPacketVersionCache(rv3, rv4); } - public static SkinPacketVersionCache rewriteUUIDModel(SkinPacketVersionCache pkt, long uuidMost, long uuidLeast, int model) { - GameMessagePacket rv3 = null; - GameMessagePacket rv4 = null; - if(pkt.skinPacketV3 != null) { - if(pkt.skinPacketV3 instanceof SPacketOtherSkinCustomV3EAG) { - SPacketOtherSkinCustomV3EAG pkt2 = (SPacketOtherSkinCustomV3EAG)pkt.skinPacketV3; - rv3 = new SPacketOtherSkinCustomV3EAG(uuidMost, uuidLeast, model, pkt2.customSkin); - }else { - rv3 = pkt.skinPacketV3; + public GameMessagePacket getV3(long rewriteUUIDMost, long rewriteUUIDLeast) { + if (skinPacketV3 != null) { + return rewriteUUID(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast); + } else { + if (skinPacketV4 == null) { + return null; } + return skinPacketV3 = convertToV3RewriteUUID(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast); } - if(pkt.skinPacketV4 != null) { - if(pkt.skinPacketV4 instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt2 = (SPacketOtherSkinCustomV4EAG)pkt.skinPacketV4; - rv4 = new SPacketOtherSkinCustomV4EAG(uuidMost, uuidLeast, model, pkt2.customSkin); - }else { - rv4 = pkt.skinPacketV4; - } - } - return new SkinPacketVersionCache(rv3, rv4); } - public static GameMessagePacket convertToForceV4(GameMessagePacket v4pkt) { - if(v4pkt instanceof SPacketOtherSkinCustomV4EAG) { - SPacketOtherSkinCustomV4EAG pkt = (SPacketOtherSkinCustomV4EAG)v4pkt; - return new SPacketForceClientSkinCustomV4EAG(pkt.modelID, pkt.customSkin); - }else if(v4pkt instanceof SPacketOtherSkinPresetEAG) { - return new SPacketForceClientSkinPresetV4EAG(((SPacketOtherSkinPresetEAG)v4pkt).presetSkin); - }else { - return v4pkt; + public GameMessagePacket getV3(long rewriteUUIDMost, long rewriteUUIDLeast, int rewriteModel) { + if (skinPacketV3 != null) { + return rewriteUUIDModel(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); + } else { + if (skinPacketV4 == null) { + return null; + } + return skinPacketV3 = convertToV3RewriteUUIDModel(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast, + rewriteModel); + } + } + + public byte[] getV3HandshakeData() { + GameMessagePacket packetV3 = getV3(); + if (packetV3 instanceof SPacketOtherSkinCustomV3EAG) { + SPacketOtherSkinCustomV3EAG pkt = (SPacketOtherSkinCustomV3EAG) packetV3; + byte[] tex = pkt.customSkin; + byte[] ret = new byte[2 + tex.length]; + ret[0] = (byte) 2; + ret[1] = (byte) pkt.modelID; + System.arraycopy(tex, 0, ret, 2, tex.length); + return ret; + } else { + SPacketOtherSkinPresetEAG pkt = (SPacketOtherSkinPresetEAG) packetV3; + int p = pkt.presetSkin; + byte[] ret = new byte[5]; + ret[0] = (byte) 1; + ret[1] = (byte) (p >>> 24); + ret[2] = (byte) (p >>> 16); + ret[3] = (byte) (p >>> 8); + ret[4] = (byte) (p & 0xFF); + return ret; + } + } + + public GameMessagePacket getV4() { + if (skinPacketV4 != null) { + return skinPacketV4; + } else { + if (skinPacketV3 == null) { + return null; + } + return skinPacketV4 = convertToV4(skinPacketV3); + } + } + + public GameMessagePacket getV4(long rewriteUUIDMost, long rewriteUUIDLeast) { + if (skinPacketV4 != null) { + return rewriteUUID(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast); + } else { + if (skinPacketV3 == null) { + return null; + } + return skinPacketV4 = convertToV4RewriteUUID(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast); + } + } + + public GameMessagePacket getV4(long rewriteUUIDMost, long rewriteUUIDLeast, int rewriteModel) { + if (skinPacketV4 != null) { + return rewriteUUIDModel(skinPacketV4, rewriteUUIDMost, rewriteUUIDLeast, rewriteModel); + } else { + if (skinPacketV3 == null) { + return null; + } + return skinPacketV4 = convertToV4RewriteUUIDModel(skinPacketV3, rewriteUUIDMost, rewriteUUIDLeast, + rewriteModel); } } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/IRelayLogger.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/IRelayLogger.java index 3282f6d9..1024269d 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/IRelayLogger.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/IRelayLogger.java @@ -3,28 +3,29 @@ package net.lax1dude.eaglercraft.v1_8.sp.relay.pkt; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public interface IRelayLogger { - void debug(String msg, Object...args); + void debug(String msg, Object... args); - void info(String msg, Object...args); - - void warn(String msg, Object...args); - - void error(String msg, Object...args); + void error(String msg, Object... args); void error(Throwable th); + void info(String msg, Object... args); + + void warn(String msg, Object... args); + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket.java index 3f5f1ee2..5fbb9d68 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket.java @@ -13,27 +13,23 @@ import java.util.Map; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayPacket { - private static final Map> definedPacketClasses = new HashMap<>(); - private static final Map,Integer> definedPacketIds = new HashMap<>(); - - private static void register(int id, Class clazz) { - definedPacketClasses.put(id, clazz); - definedPacketIds.put(clazz, id); - } + private static final Map> definedPacketClasses = new HashMap<>(); + private static final Map, Integer> definedPacketIds = new HashMap<>(); static { register(0x00, RelayPacket00Handshake.class); @@ -50,17 +46,60 @@ public class RelayPacket { register(0xFF, RelayPacketFFErrorCode.class); } + public static String readASCII(InputStream is, int len) throws IOException { + char[] ret = new char[len]; + for (int i = 0; i < len; ++i) { + int j = is.read(); + if (j < 0) { + throw new EOFException(); + } + ret[i] = (char) j; + } + return new String(ret); + } + + public static String readASCII16(InputStream is) throws IOException { + int hi = is.read(); + int lo = is.read(); + if (hi < 0 || lo < 0) { + throw new EOFException(); + } else { + return readASCII(is, (hi << 8) | lo); + } + } + + public static String readASCII8(InputStream is) throws IOException { + int i = is.read(); + if (i < 0) { + throw new EOFException(); + } else { + return readASCII(is, i); + } + } + + public static byte[] readBytes16(InputStream is) throws IOException { + int hi = is.read(); + int lo = is.read(); + if (hi < 0 || lo < 0) { + throw new EOFException(); + } else { + byte[] ret = new byte[(hi << 8) | lo]; + is.read(ret); + return ret; + } + } + public static RelayPacket readPacket(DataInputStream input, IRelayLogger logger) throws IOException { int i = input.read(); try { Class clazz = definedPacketClasses.get(i); - if(clazz == null) { + if (clazz == null) { throw new IOException("Unknown packet type: " + i); } RelayPacket pkt = clazz.newInstance(); pkt.read(input); int j = input.available(); - if(j > 0) { + if (j > 0) { throw new IOException("Packet type " + i + " had " + j + " remaining bytes"); } return pkt; @@ -71,131 +110,18 @@ public class RelayPacket { } } - public static byte[] writePacket(RelayPacket packet, IRelayLogger logger) throws IOException { - Integer i = definedPacketIds.get(packet.getClass()); - if(i != null) { - int len = packet.packetLength(); - ByteArrayOutputStream bao = len == -1 ? new ByteArrayOutputStream() : - new ByteArrayOutputStream(len + 1); - bao.write(i); - packet.write(new DataOutputStream(bao)); - byte[] ret = bao.toByteArray(); - if(len != -1 && ret.length != len + 1) { - logger.debug("writePacket buffer for packet {} {} by {} bytes", packet.getClass().getSimpleName(), - len + 1 < ret.length ? "overflowed" : "underflowed", - len + 1 < ret.length ? ret.length - len - 1 : len + 1 - ret.length); - } - return ret; - }else { - throw new IOException("Unknown packet type: " + packet.getClass().getSimpleName()); - } - } - - public void read(DataInputStream input) throws IOException { - } - - public void write(DataOutputStream output) throws IOException { - } - - public int packetLength() { - return -1; - } - - public static String readASCII(InputStream is, int len) throws IOException { - char[] ret = new char[len]; - for(int i = 0; i < len; ++i) { - int j = is.read(); - if(j < 0) { - throw new EOFException(); - } - ret[i] = (char)j; - } - return new String(ret); - } - - public static void writeASCII(OutputStream is, String txt) throws IOException { - for(int i = 0, l = txt.length(); i < l; ++i) { - is.write((int)txt.charAt(i)); - } - } - - public static String readASCII8(InputStream is) throws IOException { - int i = is.read(); - if(i < 0) { - throw new EOFException(); - }else { - return readASCII(is, i); - } - } - - public static void writeASCII8(OutputStream is, String txt) throws IOException { - if(txt == null) { - is.write(0); - }else { - int l = txt.length(); - is.write(l); - for(int i = 0; i < l; ++i) { - is.write((int)txt.charAt(i)); - } - } - } - - public static String readASCII16(InputStream is) throws IOException { - int hi = is.read(); - int lo = is.read(); - if(hi < 0 || lo < 0) { - throw new EOFException(); - }else { - return readASCII(is, (hi << 8) | lo); - } - } - - public static void writeASCII16(OutputStream is, String txt) throws IOException { - if(txt == null) { - is.write(0); - is.write(0); - }else { - int l = txt.length(); - is.write((l >>> 8) & 0xFF); - is.write(l & 0xFF); - for(int i = 0; i < l; ++i) { - is.write((int)txt.charAt(i)); - } - } - } - - public static byte[] readBytes16(InputStream is) throws IOException { - int hi = is.read(); - int lo = is.read(); - if(hi < 0 || lo < 0) { - throw new EOFException(); - }else { - byte[] ret = new byte[(hi << 8) | lo]; - is.read(ret); - return ret; - } - } - - public static void writeBytes16(OutputStream is, byte[] arr) throws IOException { - if(arr == null) { - is.write(0); - is.write(0); - }else { - is.write((arr.length >>> 8) & 0xFF); - is.write(arr.length & 0xFF); - for(int i = 0; i < arr.length; ++i) { - is.write(arr[i]); - } - } + private static void register(int id, Class clazz) { + definedPacketClasses.put(id, clazz); + definedPacketIds.put(clazz, id); } public static byte[] toASCIIBin(String txt) { - if(txt == null) { + if (txt == null) { return new byte[0]; - }else { + } else { byte[] ret = new byte[txt.length()]; - for(int i = 0; i < ret.length; ++i) { - ret[i] = (byte)txt.charAt(i); + for (int i = 0; i < ret.length; ++i) { + ret[i] = (byte) txt.charAt(i); } return ret; } @@ -203,9 +129,83 @@ public class RelayPacket { public static String toASCIIStr(byte[] bin) { char[] charRet = new char[bin.length]; - for(int i = 0; i < charRet.length; ++i) { - charRet[i] = (char)((int)bin[i] & 0xFF); + for (int i = 0; i < charRet.length; ++i) { + charRet[i] = (char) ((int) bin[i] & 0xFF); } return new String(charRet); } + + public static void writeASCII(OutputStream is, String txt) throws IOException { + for (int i = 0, l = txt.length(); i < l; ++i) { + is.write((int) txt.charAt(i)); + } + } + + public static void writeASCII16(OutputStream is, String txt) throws IOException { + if (txt == null) { + is.write(0); + is.write(0); + } else { + int l = txt.length(); + is.write((l >>> 8) & 0xFF); + is.write(l & 0xFF); + for (int i = 0; i < l; ++i) { + is.write((int) txt.charAt(i)); + } + } + } + + public static void writeASCII8(OutputStream is, String txt) throws IOException { + if (txt == null) { + is.write(0); + } else { + int l = txt.length(); + is.write(l); + for (int i = 0; i < l; ++i) { + is.write((int) txt.charAt(i)); + } + } + } + + public static void writeBytes16(OutputStream is, byte[] arr) throws IOException { + if (arr == null) { + is.write(0); + is.write(0); + } else { + is.write((arr.length >>> 8) & 0xFF); + is.write(arr.length & 0xFF); + for (int i = 0; i < arr.length; ++i) { + is.write(arr[i]); + } + } + } + + public static byte[] writePacket(RelayPacket packet, IRelayLogger logger) throws IOException { + Integer i = definedPacketIds.get(packet.getClass()); + if (i != null) { + int len = packet.packetLength(); + ByteArrayOutputStream bao = len == -1 ? new ByteArrayOutputStream() : new ByteArrayOutputStream(len + 1); + bao.write(i); + packet.write(new DataOutputStream(bao)); + byte[] ret = bao.toByteArray(); + if (len != -1 && ret.length != len + 1) { + logger.debug("writePacket buffer for packet {} {} by {} bytes", packet.getClass().getSimpleName(), + len + 1 < ret.length ? "overflowed" : "underflowed", + len + 1 < ret.length ? ret.length - len - 1 : len + 1 - ret.length); + } + return ret; + } else { + throw new IOException("Unknown packet type: " + packet.getClass().getSimpleName()); + } + } + + public int packetLength() { + return -1; + } + + public void read(DataInputStream input) throws IOException { + } + + public void write(DataOutputStream output) throws IOException { + } } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket00Handshake.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket00Handshake.java index 61999e86..2672ec7f 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket00Handshake.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket00Handshake.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,34 +25,33 @@ public class RelayPacket00Handshake extends RelayPacket { public int connectionType = 0; public int connectionVersion = 1; public String connectionCode = null; - + public RelayPacket00Handshake() { } - - public RelayPacket00Handshake(int connectionType, int connectionVersion, - String connectionCode) { + + public RelayPacket00Handshake(int connectionType, int connectionVersion, String connectionCode) { this.connectionType = connectionType; this.connectionVersion = connectionVersion; this.connectionCode = connectionCode; } - + + @Override + public int packetLength() { + return 1 + 1 + (connectionCode != null ? 1 + connectionCode.length() : 0); + } + @Override public void read(DataInputStream input) throws IOException { connectionType = input.read(); connectionVersion = input.read(); connectionCode = RelayPacket.readASCII8(input); } - + @Override public void write(DataOutputStream output) throws IOException { output.write(connectionType); output.write(connectionVersion); RelayPacket.writeASCII8(output, connectionCode); } - - @Override - public int packetLength() { - return 1 + 1 + (connectionCode != null ? 1 + connectionCode.length() : 0); - } } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket01ICEServers.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket01ICEServers.java index 84829891..514c63ba 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket01ICEServers.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket01ICEServers.java @@ -10,22 +10,21 @@ import java.util.Iterator; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayPacket01ICEServers extends RelayPacket { - public final Collection servers; - public static class RelayServer { public String address; @@ -41,9 +40,9 @@ public class RelayPacket01ICEServers extends RelayPacket { } public String getICEString() { - if(username == null) { + if (username == null) { return address; - }else { + } else { return address + ";" + username + ";" + password; } } @@ -54,6 +53,8 @@ public class RelayPacket01ICEServers extends RelayPacket { NO_PASSWD, PASSWD; } + public final Collection servers; + public RelayPacket01ICEServers() { this.servers = new ArrayList<>(); } @@ -62,17 +63,34 @@ public class RelayPacket01ICEServers extends RelayPacket { this.servers = servers; } + public void read(DataInputStream input) throws IOException { + servers.clear(); + int l = input.readUnsignedShort(); + for (int i = 0; i < l; ++i) { + char type = (char) input.read(); + RelayType typeEnum; + if (type == 'S') { + typeEnum = RelayType.NO_PASSWD; + } else if (type == 'T') { + typeEnum = RelayType.PASSWD; + } else { + throw new IOException("Unknown/Unsupported Relay Type: '" + type + "'"); + } + servers.add(new RelayServer(readASCII16(input), typeEnum, readASCII8(input), readASCII8(input))); + } + } + public void write(DataOutputStream output) throws IOException { int l = servers.size(); output.writeShort(l); Iterator itr = servers.iterator(); - while(itr.hasNext()) { + while (itr.hasNext()) { RelayServer srv = itr.next(); - if(srv.type == RelayType.NO_PASSWD) { + if (srv.type == RelayType.NO_PASSWD) { output.write('S'); - }else if(srv.type == RelayType.PASSWD) { + } else if (srv.type == RelayType.PASSWD) { output.write('T'); - }else { + } else { throw new IOException("Unknown/Unsupported Relay Type: " + srv.type.name()); } writeASCII16(output, srv.address); @@ -80,26 +98,4 @@ public class RelayPacket01ICEServers extends RelayPacket { writeASCII8(output, srv.password); } } - - public void read(DataInputStream input) throws IOException { - servers.clear(); - int l = input.readUnsignedShort(); - for(int i = 0; i < l; ++i) { - char type = (char)input.read(); - RelayType typeEnum; - if(type == 'S') { - typeEnum = RelayType.NO_PASSWD; - }else if(type == 'T') { - typeEnum = RelayType.PASSWD; - }else { - throw new IOException("Unknown/Unsupported Relay Type: '" + type + "'"); - } - servers.add(new RelayServer( - readASCII16(input), - typeEnum, - readASCII8(input), - readASCII8(input) - )); - } - } } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket02NewClient.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket02NewClient.java index 0f7b534c..be01626a 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket02NewClient.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket02NewClient.java @@ -7,39 +7,40 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayPacket02NewClient extends RelayPacket { - + public String clientId; - + + public RelayPacket02NewClient() { + } + public RelayPacket02NewClient(String clientId) { this.clientId = clientId; } - - public RelayPacket02NewClient() { - } - - public void write(DataOutputStream output) throws IOException { - writeASCII8(output, clientId); - } - - public void read(DataInputStream input) throws IOException { - clientId = readASCII8(input); - } - + public int packetLength() { return 1 + clientId.length(); } - + + public void read(DataInputStream input) throws IOException { + clientId = readASCII8(input); + } + + public void write(DataOutputStream output) throws IOException { + writeASCII8(output, clientId); + } + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket03ICECandidate.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket03ICECandidate.java index f9ac7bba..ec3fb759 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket03ICECandidate.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket03ICECandidate.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,36 +24,36 @@ public class RelayPacket03ICECandidate extends RelayPacket { public String peerId; public byte[] candidate; - + public RelayPacket03ICECandidate() { } - - public RelayPacket03ICECandidate(String peerId, String desc) { - this.peerId = peerId; - this.candidate = toASCIIBin(desc); - } - + public RelayPacket03ICECandidate(String peerId, byte[] desc) { this.peerId = peerId; this.candidate = desc; } - - public void read(DataInputStream input) throws IOException { - peerId = readASCII8(input); - candidate = readBytes16(input); + + public RelayPacket03ICECandidate(String peerId, String desc) { + this.peerId = peerId; + this.candidate = toASCIIBin(desc); } - - public void write(DataOutputStream output) throws IOException { - writeASCII8(output, peerId); - writeBytes16(output, candidate); - } - + public String getCandidateString() { return candidate == null ? null : toASCIIStr(candidate); } - + public int packetLength() { return 1 + peerId.length() + 2 + candidate.length; } + public void read(DataInputStream input) throws IOException { + peerId = readASCII8(input); + candidate = readBytes16(input); + } + + public void write(DataOutputStream output) throws IOException { + writeASCII8(output, peerId); + writeBytes16(output, candidate); + } + } \ No newline at end of file diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket04Description.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket04Description.java index ca9a9048..89e80353 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket04Description.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket04Description.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -23,36 +24,36 @@ public class RelayPacket04Description extends RelayPacket { public String peerId; public byte[] description; - + public RelayPacket04Description() { } - - public RelayPacket04Description(String peerId, String desc) { - this.peerId = peerId; - this.description = toASCIIBin(desc); - } - + public RelayPacket04Description(String peerId, byte[] desc) { this.peerId = peerId; this.description = desc; } - - public void read(DataInputStream input) throws IOException { - peerId = readASCII8(input); - description = readBytes16(input); + + public RelayPacket04Description(String peerId, String desc) { + this.peerId = peerId; + this.description = toASCIIBin(desc); } - - public void write(DataOutputStream output) throws IOException { - writeASCII8(output, peerId); - writeBytes16(output, description); - } - + public String getDescriptionString() { return description == null ? null : toASCIIStr(description); } - + public int packetLength() { return 1 + peerId.length() + 2 + description.length; } + public void read(DataInputStream input) throws IOException { + peerId = readASCII8(input); + description = readBytes16(input); + } + + public void write(DataOutputStream output) throws IOException { + writeASCII8(output, peerId); + writeBytes16(output, description); + } + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket05ClientSuccess.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket05ClientSuccess.java index e49d2fe9..2e557a1d 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket05ClientSuccess.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket05ClientSuccess.java @@ -7,29 +7,34 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayPacket05ClientSuccess extends RelayPacket { - + public String clientId; - + public RelayPacket05ClientSuccess() { } - + public RelayPacket05ClientSuccess(String clientId) { this.clientId = clientId; } + public int packetLength() { + return 1 + clientId.length(); + } + public void read(DataInputStream input) throws IOException { clientId = readASCII8(input); } @@ -37,9 +42,5 @@ public class RelayPacket05ClientSuccess extends RelayPacket { public void write(DataOutputStream output) throws IOException { writeASCII8(output, clientId); } - - public int packetLength() { - return 1 + clientId.length(); - } - + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket06ClientFailure.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket06ClientFailure.java index bf9c0030..295e0d53 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket06ClientFailure.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket06ClientFailure.java @@ -7,29 +7,34 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayPacket06ClientFailure extends RelayPacket { - + public String clientId; - + public RelayPacket06ClientFailure() { } - + public RelayPacket06ClientFailure(String clientId) { this.clientId = clientId; } - + + public int packetLength() { + return 1 + clientId.length(); + } + public void read(DataInputStream input) throws IOException { clientId = readASCII8(input); } @@ -37,9 +42,5 @@ public class RelayPacket06ClientFailure extends RelayPacket { public void write(DataOutputStream output) throws IOException { writeASCII8(output, clientId); } - - public int packetLength() { - return 1 + clientId.length(); - } - + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket07LocalWorlds.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket07LocalWorlds.java index b53f29b5..df676245 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket07LocalWorlds.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket07LocalWorlds.java @@ -9,78 +9,79 @@ import java.util.List; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ public class RelayPacket07LocalWorlds extends RelayPacket { - + public static class LocalWorld { - + public final String worldName; public final String worldCode; - + public LocalWorld(String worldName, String worldCode) { this.worldName = worldName; this.worldCode = worldCode; } - + } - + public List worldsList; - + public RelayPacket07LocalWorlds() { } - + public RelayPacket07LocalWorlds(List worldsList) { this.worldsList = worldsList; } - public void write(DataOutputStream output) throws IOException { - if(worldsList == null) { - output.write(0); - }else { - int i = worldsList.size(); - if(i > 255) { - i = 255; - } - output.write(i); - for(int j = 0; j < i; ++j) { - LocalWorld w = worldsList.get(j); - writeASCII8(output, w.worldName); - writeASCII8(output, w.worldCode); - } - } - } - - public void read(DataInputStream input) throws IOException { - int l = input.read(); - if(worldsList == null) { - worldsList = new ArrayList<>(l); - }else { - worldsList.clear(); - } - for(int i = 0; i < l; ++i) { - worldsList.add(new LocalWorld(readASCII8(input), readASCII8(input))); - } - } - public int packetLength() { int accum = 1; - if(worldsList != null) { - for(int i = 0, l = worldsList.size(); i < l; ++i) { + if (worldsList != null) { + for (int i = 0, l = worldsList.size(); i < l; ++i) { LocalWorld j = worldsList.get(i); accum += 2 + j.worldName.length() + j.worldCode.length(); } } return accum; } + + public void read(DataInputStream input) throws IOException { + int l = input.read(); + if (worldsList == null) { + worldsList = new ArrayList<>(l); + } else { + worldsList.clear(); + } + for (int i = 0; i < l; ++i) { + worldsList.add(new LocalWorld(readASCII8(input), readASCII8(input))); + } + } + + public void write(DataOutputStream output) throws IOException { + if (worldsList == null) { + output.write(0); + } else { + int i = worldsList.size(); + if (i > 255) { + i = 255; + } + output.write(i); + for (int j = 0; j < i; ++j) { + LocalWorld w = worldsList.get(j); + writeASCII8(output, w.worldName); + writeASCII8(output, w.worldCode); + } + } + } } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket69Pong.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket69Pong.java index 9276c495..8a53008e 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket69Pong.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket69Pong.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -24,9 +25,12 @@ public class RelayPacket69Pong extends RelayPacket { public int protcolVersion; public String comment; public String brand; - + + public RelayPacket69Pong() { + } + public RelayPacket69Pong(int protcolVersion, String comment, String brand) { - if(comment.length() > 255) { + if (comment.length() > 255) { comment = comment.substring(0, 256); } this.protcolVersion = protcolVersion; @@ -34,23 +38,20 @@ public class RelayPacket69Pong extends RelayPacket { this.brand = brand; } - public RelayPacket69Pong() { + public int packetLength() { + return 3 + comment.length() + brand.length(); } - - public void write(DataOutputStream output) throws IOException { - output.write(protcolVersion); - writeASCII8(output, comment); - writeASCII8(output, brand); - } - + public void read(DataInputStream output) throws IOException { protcolVersion = output.read(); comment = readASCII8(output); brand = readASCII8(output); } - - public int packetLength() { - return 3 + comment.length() + brand.length(); + + public void write(DataOutputStream output) throws IOException { + output.write(protcolVersion); + writeASCII8(output, comment); + writeASCII8(output, brand); } - + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket70SpecialUpdate.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket70SpecialUpdate.java index 5d522928..9c1111c6 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket70SpecialUpdate.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacket70SpecialUpdate.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -34,6 +35,11 @@ public class RelayPacket70SpecialUpdate extends RelayPacket { this.updatePacket = updatePacket; } + @Override + public int packetLength() { + return 3 + updatePacket.length; + } + @Override public void read(DataInputStream input) throws IOException { operation = input.read(); @@ -47,9 +53,4 @@ public class RelayPacket70SpecialUpdate extends RelayPacket { output.writeShort(updatePacket.length); output.write(updatePacket); } - - @Override - public int packetLength() { - return 3 + updatePacket.length; - } } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFEDisconnectClient.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFEDisconnectClient.java index 866a0af4..704c8379 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFEDisconnectClient.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFEDisconnectClient.java @@ -8,14 +8,15 @@ import java.nio.ByteBuffer; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -29,39 +30,42 @@ public class RelayPacketFEDisconnectClient extends RelayPacket { public static final int TYPE_INTERNAL_ERROR = 0x04; public static final int TYPE_SERVER_DISCONNECT = 0x05; public static final int TYPE_UNKNOWN = 0xFF; - + + public static final ByteBuffer ratelimitPacketTooMany = ByteBuffer.wrap(new byte[] { (byte) 0xFC, (byte) 0x00 }); + public static final ByteBuffer ratelimitPacketBlock = ByteBuffer.wrap(new byte[] { (byte) 0xFC, (byte) 0x01 }); + public static final ByteBuffer ratelimitPacketBlockLock = ByteBuffer.wrap(new byte[] { (byte) 0xFC, (byte) 0x02 }); + + public static final ByteBuffer ratelimitPacketLocked = ByteBuffer.wrap(new byte[] { (byte) 0xFC, (byte) 0x03 }); + public String clientId; + public int code; + public String reason; - + public RelayPacketFEDisconnectClient() { } - + public RelayPacketFEDisconnectClient(String clientId, int code, String reason) { this.clientId = clientId; this.code = code; this.reason = reason; } - + + public int packetLength() { + return 1 + 1 + 2 + clientId.length() + (reason != null ? reason.length() : 0); + } + public void read(DataInputStream input) throws IOException { clientId = readASCII8(input); code = input.read(); reason = readASCII16(input); } - + public void write(DataOutputStream output) throws IOException { writeASCII8(output, clientId); output.write(code); writeASCII16(output, reason); } - - public int packetLength() { - return 1 + 1 + 2 + clientId.length() + (reason != null ? reason.length() : 0); - } - - public static final ByteBuffer ratelimitPacketTooMany = ByteBuffer.wrap(new byte[] { (byte)0xFC, (byte)0x00 }); - public static final ByteBuffer ratelimitPacketBlock = ByteBuffer.wrap(new byte[] { (byte)0xFC, (byte)0x01 }); - public static final ByteBuffer ratelimitPacketBlockLock = ByteBuffer.wrap(new byte[] { (byte)0xFC, (byte)0x02 }); - public static final ByteBuffer ratelimitPacketLocked = ByteBuffer.wrap(new byte[] { (byte)0xFC, (byte)0x03 }); - + } diff --git a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFFErrorCode.java b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFFErrorCode.java index 9ca959c8..06906b02 100644 --- a/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFFErrorCode.java +++ b/src/protocol-relay/java/net/lax1dude/eaglercraft/v1_8/sp/relay/pkt/RelayPacketFFErrorCode.java @@ -7,14 +7,15 @@ import java.io.IOException; /** * Copyright (c) 2022-2024 lax1dude. All Rights Reserved. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, - * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * @@ -44,9 +45,9 @@ public class RelayPacketFFErrorCode extends RelayPacket { } public static String code2string(int i) { - if(i >= 0 || i < packetTypes.length) { + if (i >= 0 || i < packetTypes.length) { return packetTypes[i]; - }else { + } else { return "UNKNOWN"; } } @@ -62,6 +63,11 @@ public class RelayPacketFFErrorCode extends RelayPacket { this.desc = desc; } + @Override + public int packetLength() { + return 1 + 2 + desc.length(); + } + @Override public void read(DataInputStream input) throws IOException { code = input.read(); @@ -74,9 +80,4 @@ public class RelayPacketFFErrorCode extends RelayPacket { writeASCII16(input, desc); } - @Override - public int packetLength() { - return 1 + 2 + desc.length(); - } - } diff --git a/src/teavm-boot-menu/java/net/lax1dude/eaglercraft/v1_8/boot_menu/teavm/BootMenuEntryPoint.java b/src/teavm-boot-menu/java/net/lax1dude/eaglercraft/v1_8/boot_menu/teavm/BootMenuEntryPoint.java index b7879fe8..61090f30 100644 --- a/src/teavm-boot-menu/java/net/lax1dude/eaglercraft/v1_8/boot_menu/teavm/BootMenuEntryPoint.java +++ b/src/teavm-boot-menu/java/net/lax1dude/eaglercraft/v1_8/boot_menu/teavm/BootMenuEntryPoint.java @@ -60,12 +60,14 @@ public class BootMenuEntryPoint { return ((flag & 1) != 0 || IBootMenuConfigAdapter.instance.isShowBootMenuOnLaunch()) && !getHasAlreadyBooted(); } + private static boolean hasInit = false; private static byte[] signatureData = null; private static byte[] bundleData = null; public static void launchMenu(Window parentWindow, HTMLElement parentElement) { signatureData = PlatformUpdateSvc.getClientSignatureData(); bundleData = PlatformUpdateSvc.getClientBundleData(); + hasInit = true; BootMenuMain.launchMenu(parentWindow, parentElement); } @@ -83,6 +85,11 @@ public class BootMenuEntryPoint { } public static boolean isSignedClient() { + if(!hasInit) { + signatureData = PlatformUpdateSvc.getClientSignatureData(); + bundleData = PlatformUpdateSvc.getClientBundleData(); + hasInit = true; + } return signatureData != null && bundleData != null; } diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java index cdff2098..8d46ddff 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformInput.java @@ -330,8 +330,8 @@ public class PlatformInput { int b = evt.getButton(); b = b == 1 ? 2 : (b == 2 ? 1 : b); buttonStates[b] = true; - int eventX = (int)(getOffsetX(evt) * windowDPI); - int eventY = windowHeight - (int)(getOffsetY(evt) * windowDPI) - 1; + int eventX = (int)(getOffsetX(evt, touchOffsetXTeaVM) * windowDPI); + int eventY = windowHeight - (int)(getOffsetY(evt, touchOffsetYTeaVM) * windowDPI) - 1; synchronized(mouseEvents) { mouseEvents.add(new VMouseEvent(eventX, eventY, b, 0.0f, EVENT_MOUSE_DOWN)); if(mouseEvents.size() > 64) { @@ -348,8 +348,8 @@ public class PlatformInput { int b = evt.getButton(); b = b == 1 ? 2 : (b == 2 ? 1 : b); buttonStates[b] = false; - int eventX = (int)(getOffsetX(evt) * windowDPI); - int eventY = windowHeight - (int)(getOffsetY(evt) * windowDPI) - 1; + int eventX = (int)(getOffsetX(evt, touchOffsetXTeaVM) * windowDPI); + int eventY = windowHeight - (int)(getOffsetY(evt, touchOffsetYTeaVM) * windowDPI) - 1; synchronized(mouseEvents) { mouseEvents.add(new VMouseEvent(eventX, eventY, b, 0.0f, EVENT_MOUSE_UP)); if(mouseEvents.size() > 64) { @@ -363,13 +363,13 @@ public class PlatformInput { public void handleEvent(MouseEvent evt) { evt.preventDefault(); evt.stopPropagation(); - mouseX = (int)(getOffsetX(evt) * windowDPI); - mouseY = windowHeight - (int)(getOffsetY(evt) * windowDPI) - 1; + mouseX = (int)(getOffsetX(evt, touchOffsetXTeaVM) * windowDPI); + mouseY = windowHeight - (int)(getOffsetY(evt, touchOffsetYTeaVM) * windowDPI) - 1; mouseDX += evt.getMovementX(); mouseDY += -evt.getMovementY(); if(hasShownPressAnyKey) { - int eventX = (int)(getOffsetX(evt) * windowDPI); - int eventY = windowHeight - (int)(getOffsetY(evt) * windowDPI) - 1; + int eventX = (int)(getOffsetX(evt, touchOffsetXTeaVM) * windowDPI); + int eventY = windowHeight - (int)(getOffsetY(evt, touchOffsetYTeaVM) * windowDPI) - 1; synchronized(mouseEvents) { mouseEvents.add(new VMouseEvent(eventX, eventY, -1, 0.0f, EVENT_MOUSE_MOVE)); if(mouseEvents.size() > 64) { @@ -597,11 +597,11 @@ public class PlatformInput { public void handleEvent(WheelEvent evt) { evt.preventDefault(); evt.stopPropagation(); - double delta = evt.getDeltaY(); + double delta = -evt.getDeltaY(); mouseDWheel += delta; if(hasShownPressAnyKey) { - int eventX = (int)(getOffsetX(evt) * windowDPI); - int eventY = windowHeight - (int)(getOffsetY(evt) * windowDPI) - 1; + int eventX = (int)(getOffsetX(evt, touchOffsetXTeaVM) * windowDPI); + int eventY = windowHeight - (int)(getOffsetY(evt, touchOffsetYTeaVM) * windowDPI) - 1; synchronized(mouseEvents) { mouseEvents.add(new VMouseEvent(eventX, eventY, -1, (float)delta, EVENT_MOUSE_WHEEL)); if(mouseEvents.size() > 64) { @@ -825,11 +825,11 @@ public class PlatformInput { @JSBody(params = { "fallback" }, script = "if(window.navigator.userActivation){return window.navigator.userActivation.hasBeenActive;}else{return fallback;}") public static native boolean hasBeenActiveTeaVM(boolean fallback); - @JSBody(params = { "m" }, script = "return m.offsetX;") - private static native int getOffsetX(MouseEvent m); + @JSBody(params = { "m", "off" }, script = "return (typeof m.offsetX === \"number\") ? m.offsetX : (m.pageX - off);") + private static native int getOffsetX(MouseEvent m, int offX); - @JSBody(params = { "m" }, script = "return m.offsetY;") - private static native int getOffsetY(MouseEvent m); + @JSBody(params = { "m", "off" }, script = "return (typeof m.offsetY === \"number\") ? m.offsetY : (m.pageY - off);") + private static native int getOffsetY(MouseEvent m, int offY); @JSBody(params = { "e" }, script = "return (typeof e.which === \"number\") ? e.which : ((typeof e.keyCode === \"number\") ? e.keyCode : 0);") private static native int getWhich(KeyboardEvent e); @@ -1246,7 +1246,11 @@ public class PlatformInput { } public static int mouseGetEventDWheel() { - return (currentEvent.type == EVENT_MOUSE_WHEEL) ? (currentEvent.wheel == 0.0f ? 0 : (currentEvent.wheel > 0.0f ? -1 : 1)) : 0; + return (currentEvent.type == EVENT_MOUSE_WHEEL) ? fixWheel(currentEvent.wheel) : 0; + } + + private static int fixWheel(float val) { + return (val > 0.0f ? 1 : (val < 0.0f ? -1 : 0)); } public static int mouseGetX() { diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java index d44a0e1b..60564210 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/PlatformRuntime.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -13,6 +14,7 @@ import java.util.function.Consumer; import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EagUtils; import net.lax1dude.eaglercraft.v1_8.EaglercraftUUID; +import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; import net.lax1dude.eaglercraft.v1_8.Filesystem; import net.lax1dude.eaglercraft.v1_8.boot_menu.teavm.BootMenuEntryPoint; import org.teavm.interop.Async; @@ -48,7 +50,6 @@ import net.lax1dude.eaglercraft.v1_8.internal.buffer.ByteBuffer; import net.lax1dude.eaglercraft.v1_8.internal.buffer.EaglerArrayBufferAllocator; import net.lax1dude.eaglercraft.v1_8.internal.buffer.FloatBuffer; import net.lax1dude.eaglercraft.v1_8.internal.buffer.IntBuffer; -import net.lax1dude.eaglercraft.v1_8.internal.teavm.EPKLoader; import net.lax1dude.eaglercraft.v1_8.internal.teavm.ES6ShimStatus; import net.lax1dude.eaglercraft.v1_8.internal.teavm.EarlyLoadScreen; import net.lax1dude.eaglercraft.v1_8.internal.teavm.EnumES6ShimStatus; @@ -58,8 +59,8 @@ import net.lax1dude.eaglercraft.v1_8.internal.teavm.ImmediateContinue; import net.lax1dude.eaglercraft.v1_8.internal.teavm.MessageChannel; import net.lax1dude.eaglercraft.v1_8.internal.teavm.TeaVMBlobURLManager; import net.lax1dude.eaglercraft.v1_8.internal.teavm.ClientMain; -import net.lax1dude.eaglercraft.v1_8.internal.teavm.ClientMain.EPKFileEntry; import net.lax1dude.eaglercraft.v1_8.internal.teavm.DebugConsoleWindow; +import net.lax1dude.eaglercraft.v1_8.internal.teavm.EPKDownloadHelper; import net.lax1dude.eaglercraft.v1_8.internal.teavm.TeaVMClientConfigAdapter; import net.lax1dude.eaglercraft.v1_8.internal.teavm.TeaVMDataURLManager; import net.lax1dude.eaglercraft.v1_8.internal.teavm.TeaVMEnterBootMenuException; @@ -426,29 +427,14 @@ public class PlatformRuntime { EarlyLoadScreen.paintScreen(glesVer, PlatformOpenGL.checkVAOCapable(), allowBootMenu); - EPKFileEntry[] epkFiles = ClientMain.configEPKFiles; - - for(int i = 0; i < epkFiles.length; ++i) { - String url = epkFiles[i].url; - String logURL = url.startsWith("data:") ? "" : url; - - logger.info("Downloading: {}", logURL); - - ArrayBuffer epkFileData = downloadRemoteURI(url); - - if(epkFileData == null) { - throw new RuntimeInitializationFailureException("Could not download EPK file \"" + url + "\""); - } - - logger.info("Decompressing: {}", logURL); - - try { - EPKLoader.loadEPK(epkFileData, epkFiles[i].path, PlatformAssets.assets); - }catch(Throwable t) { - throw new RuntimeInitializationFailureException("Could not extract EPK file \"" + url + "\"", t); - } + if(PlatformAssets.assets == null || !PlatformAssets.assets.isEmpty()) { + PlatformAssets.assets = new HashMap<>(); } + EPKDownloadHelper.downloadEPKFilesOfVersion(ClientMain.configEPKFiles, + teavmCfg.isEnableEPKVersionCheckTeaVM() ? EaglercraftVersion.EPKVersionIdentifier : null, + PlatformAssets.assets); + logger.info("Loaded {} resources from EPKs", PlatformAssets.assets.size()); if(allowBootMenu && BootMenuEntryPoint.checkShouldLaunchFlag(win)) { @@ -517,26 +503,6 @@ public class PlatformRuntime { @JSBody(params = { }, script = "return {antialias: false, depth: false, powerPreference: \"high-performance\", desynchronized: true, preserveDrawingBuffer: false, premultipliedAlpha: false, alpha: false};") public static native JSObject youEagler(); - - public static class RuntimeInitializationFailureException extends IllegalStateException { - - public RuntimeInitializationFailureException(String message, Throwable cause) { - super(message, cause); - } - - public RuntimeInitializationFailureException(String s) { - super(s); - } - - } - - public static class PlatformIncompatibleException extends IllegalStateException { - - public PlatformIncompatibleException(String s) { - super(s); - } - - } public static void destroy() { logger.fatal("Game tried to destroy the context! Browser runtime can't do that"); @@ -626,6 +592,10 @@ public class PlatformRuntime { } + public static boolean hasFetchSupportTeaVM() { + return hasFetchSupport; + } + public static void downloadRemoteURIByteArray(String assetPackageURI, final Consumer cb) { downloadRemoteURI(assetPackageURI, arr -> cb.accept(TeaVMUtils.wrapByteArrayBuffer(arr))); } diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerArrayByteBuffer.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerArrayByteBuffer.java index 48d19bc6..558d8fe4 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerArrayByteBuffer.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/buffer/EaglerArrayByteBuffer.java @@ -296,9 +296,7 @@ public class EaglerArrayByteBuffer implements ByteBuffer { @Override public long getLong() { if(position + 8 > limit) throw Buffer.makeIOOBE(position); - long l = dataView.getUint32(position) | ((long) dataView.getUint8(position + 4) << 32) - | ((long) dataView.getUint8(position + 5) << 40) | ((long) dataView.getUint8(position + 6) << 48) - | ((long) dataView.getUint8(position + 7) << 56); + long l = (long)dataView.getUint32(position, true) | ((long) dataView.getUint32(position + 4) << 32l); position += 8; return l; } @@ -307,10 +305,7 @@ public class EaglerArrayByteBuffer implements ByteBuffer { public ByteBuffer putLong(long value) { if(position + 8 > limit) throw Buffer.makeIOOBE(position); dataView.setUint32(position, (int) (value & 0xFFFFFFFFl), true); - dataView.setUint8(position + 4, (short) ((value >>> 32l) & 0xFFl)); - dataView.setUint8(position + 5, (short) ((value >>> 40l) & 0xFFl)); - dataView.setUint8(position + 6, (short) ((value >>> 48l) & 0xFFl)); - dataView.setUint8(position + 7, (short) ((value >>> 56l) & 0xFFl)); + dataView.setUint32(position + 4, (int) (value >>> 32l), true); position += 8; return this; } @@ -318,19 +313,14 @@ public class EaglerArrayByteBuffer implements ByteBuffer { @Override public long getLong(int index) { if(index < 0 || index + 8 > limit) throw Buffer.makeIOOBE(index); - return dataView.getUint32(index, true) | ((long) dataView.getUint8(index + 4) << 32) - | ((long) dataView.getUint8(index + 5) << 40) | ((long) dataView.getUint8(index + 6) << 48) - | ((long) dataView.getUint8(index + 7) << 56); + return (long)dataView.getUint32(index, true) | ((long) dataView.getUint32(index + 4) << 32l); } @Override public ByteBuffer putLong(int index, long value) { if(index < 0 || index + 8 > limit) throw Buffer.makeIOOBE(index); dataView.setUint32(index, (int) (value & 0xFFFFFFFFl), true); - dataView.setUint8(index + 4, (short) ((value >>> 32l) & 0xFFl)); - dataView.setUint8(index + 5, (short) ((value >>> 40l) & 0xFFl)); - dataView.setUint8(index + 6, (short) ((value >>> 48l) & 0xFFl)); - dataView.setUint8(index + 7, (short) ((value >>> 56l) & 0xFFl)); + dataView.setUint32(index + 4, (int) (value >>> 32l), true); return this; } diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/ClientMain.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/ClientMain.java index e8ecf58e..40993f11 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/ClientMain.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/ClientMain.java @@ -25,6 +25,7 @@ import net.lax1dude.eaglercraft.v1_8.EagRuntime; import net.lax1dude.eaglercraft.v1_8.EaglercraftVersion; import net.lax1dude.eaglercraft.v1_8.boot_menu.teavm.BootMenuEntryPoint; import net.lax1dude.eaglercraft.v1_8.internal.PlatformApplication; +import net.lax1dude.eaglercraft.v1_8.internal.PlatformIncompatibleException; import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; import net.lax1dude.eaglercraft.v1_8.internal.PlatformOpenGL; import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; @@ -63,23 +64,12 @@ public class ClientMain { @JSBody(params = {}, script = "if((typeof __isEaglerX188Running === \"string\") && __isEaglerX188Running === \"yes\") return true; __isEaglerX188Running = \"yes\"; return false;") private static native boolean getRunningFlag(); - @JSBody(params = { "str" }, script = "return (typeof location !== \"undefined\") && (typeof location.hostname === \"string\") && location.hostname.toLowerCase() === str;") - private static native boolean getTardFlag(String str); - private static final PrintStream systemOut = System.out; private static final PrintStream systemErr = System.err; private static JSObject windowErrorHandler = null; public static void _main() { - if(getTardFlag(new String(new char[] { 'e', 'a', 'g', 'l', 'e', 'r', 'c', 'r', 'a', 'f', 't', '.', 'd', 'e', 'v' }))) { - // Have fun, boys!!! - Window.alert(new String(new char[] { 101, 97, 103, 108, 101, 114, 99, 114, 97, 102, 116, 46, 100, 101, 118, - 32, 105, 115, 32, 110, 111, 116, 32, 97, 110, 32, 111, 102, 102, 105, 99, 105, 97, 108, 32, 119, - 101, 98, 115, 105, 116, 101, 32, 97, 110, 100, 32, 105, 115, 32, 110, 111, 116, 32, 101, 110, 100, - 111, 114, 115, 101, 100, 32, 98, 121, 32, 108, 97, 120, 49, 100, 117, 100, 101, 32, 111, 114, 32, - 97, 121, 117, 110, 97, 109, 105, 50, 48, 48, 48 })); - } if(getRunningFlag()) { systemErr.println("ClientMain: [ERROR] eaglercraftx is already running!"); return; @@ -201,7 +191,7 @@ public class ClientMain { try { EagRuntime.create(); - }catch(PlatformRuntime.PlatformIncompatibleException ex) { + }catch(PlatformIncompatibleException ex) { systemErr.println("ClientMain: [ERROR] this browser is incompatible with eaglercraftx!"); systemErr.println("ClientMain: [ERROR] Reason: " + ex.getMessage()); try { diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/EPKDownloadHelper.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/EPKDownloadHelper.java new file mode 100644 index 00000000..ac822dca --- /dev/null +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/EPKDownloadHelper.java @@ -0,0 +1,160 @@ +package net.lax1dude.eaglercraft.v1_8.internal.teavm; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; + +import org.teavm.jso.browser.Window; +import org.teavm.jso.typedarrays.ArrayBuffer; + +import net.lax1dude.eaglercraft.v1_8.Base64; +import net.lax1dude.eaglercraft.v1_8.internal.PlatformApplication; +import net.lax1dude.eaglercraft.v1_8.internal.PlatformRuntime; +import net.lax1dude.eaglercraft.v1_8.internal.RuntimeInitializationFailureException; +import net.lax1dude.eaglercraft.v1_8.internal.teavm.ClientMain.EPKFileEntry; +import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; +import net.lax1dude.eaglercraft.v1_8.log4j.Logger; + +/** + * Copyright (c) 2024 lax1dude. All Rights Reserved. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + */ +public class EPKDownloadHelper { + + private static final Logger logger = LogManager.getLogger("BrowserRuntime"); + + public static void downloadEPKFilesOfVersion(EPKFileEntry[] epkFiles, String expectedVersionIdentifier, + Map loadedFiles) { + byte[] bTrue = Base64.decodeBase64("true"); + boolean oldEPKInvalidFlag = Arrays.equals(bTrue, PlatformApplication.getLocalStorage("epkInvalidFlag", false)); + boolean epkInvalidFlag = oldEPKInvalidFlag; + attempt_loop: for(int a = 0; a < 3; ++a) { + if(a == 1 && !PlatformRuntime.hasFetchSupportTeaVM()) continue; + loadedFiles.clear(); + boolean canBeInvalid = expectedVersionIdentifier != null; + for(int i = 0; i < epkFiles.length; ++i) { + boolean noCache = false; + String url = null; + switch(a) { + case 0: + url = epkFiles[i].url; + noCache = false; + break; + case 1: + logger.warn("Failed to download one or more correct/valid files, attempting to bypass the browser's cache..."); + url = epkFiles[i].url; + noCache = true; + break; + case 2: + logger.warn("Failed to download one or more correct/valid files, attempting to bypass the server's cache..."); + url = injectCacheInvalidationHack(epkFiles[i].url, expectedVersionIdentifier); + noCache = true; + break; + } + boolean b = url.startsWith("data:"); + boolean c = !b && !url.startsWith("blob:"); + String toCheck = url.indexOf("://") != -1 ? url : PlatformRuntime.win.getLocation().getFullURL(); + boolean canBeCorrupt = c && (a < 1 || toCheck.startsWith("http:") || toCheck.startsWith("https:")); + canBeInvalid &= c; + String logURL = b ? "" : url; + + logger.info("Downloading: {}", logURL); + + ArrayBuffer epkFileData = PlatformRuntime.downloadRemoteURI(url, !noCache); + + if(epkFileData == null) { + if(a < 2 && canBeCorrupt) { + logger.error("Could not download EPK file \"{}\"", logURL); + continue attempt_loop; + }else { + throw new RuntimeInitializationFailureException("Could not download EPK file \"" + logURL + "\""); + } + } + + logger.info("Decompressing: {}", logURL); + + try { + EPKLoader.loadEPK(epkFileData, epkFiles[i].path, loadedFiles); + }catch(Throwable t) { + if(a < 2 && canBeCorrupt) { + logger.error("Could not extract EPK file \"{}\"", logURL); + continue attempt_loop; + }else { + throw new RuntimeInitializationFailureException("Could not extract EPK file \"" + logURL + "\"", t); + } + } + } + if(canBeInvalid) { + byte[] dat = loadedFiles.get("EPKVersionIdentifier.txt"); + if(dat != null) { + String epkStr = (new String(dat, StandardCharsets.UTF_8)).trim(); + if(expectedVersionIdentifier.equals(epkStr)) { + epkInvalidFlag = false; + break; + } + logger.error("EPK version identifier \"{}\" does not match the expected identifier \"{}\"", epkStr, expectedVersionIdentifier); + }else { + logger.error("Version identifier file is missing from the EPK, expecting \"{}\"", expectedVersionIdentifier); + } + if(epkInvalidFlag) { + break; + }else { + if(a < 2) { + continue; + }else { + logger.error("Nothing we can do about this, ignoring the invalid EPK version and setting invalid flag to true"); + epkInvalidFlag = true; + } + } + }else { + epkInvalidFlag = false; + break; + } + } + if(epkInvalidFlag != oldEPKInvalidFlag) { + PlatformApplication.setLocalStorage("epkInvalidFlag", epkInvalidFlag ? bTrue : null, false); + } + } + + private static String injectCacheInvalidationHack(String url, String cacheFixStr) { + if(cacheFixStr != null) { + cacheFixStr = Window.encodeURIComponent(cacheFixStr); + }else { + cacheFixStr = "t" + System.currentTimeMillis(); + } + String toCheck = url.indexOf("://") != -1 ? url : PlatformRuntime.win.getLocation().getFullURL(); + if(toCheck.startsWith("http:") || toCheck.startsWith("https:")) { + int i = url.indexOf('?'); + if(i == url.length() - 1) { + return url + "eaglerCacheFix=" + cacheFixStr; + }else if(i != -1) { + String s = url.substring(i + 1); + if(!s.startsWith("&") && !s.startsWith("#")) { + s = "&" + s; + } + return url.substring(0, i + 1) + "eaglerCacheFix=" + cacheFixStr + s; + }else { + i = url.indexOf('#'); + if(i != -1) { + return url.substring(0, i) + "?eaglerCacheFix=" + cacheFixStr + url.substring(i); + }else { + return url + "?eaglerCacheFix=" + cacheFixStr; + } + } + }else { + return url; + } + } + +} diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/FixWebMDurationJS.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/FixWebMDurationJS.java index 294d204f..8bbf4a1d 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/FixWebMDurationJS.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/FixWebMDurationJS.java @@ -1,16 +1,10 @@ package net.lax1dude.eaglercraft.v1_8.internal.teavm; -import java.nio.charset.StandardCharsets; - -import org.apache.commons.lang3.StringUtils; import org.teavm.jso.JSBody; import org.teavm.jso.JSFunctor; import org.teavm.jso.JSObject; -import org.teavm.jso.browser.Window; import org.teavm.jso.dom.events.Event; -import net.lax1dude.eaglercraft.v1_8.Base64; -import net.lax1dude.eaglercraft.v1_8.internal.PlatformInput; import net.lax1dude.eaglercraft.v1_8.log4j.LogManager; import net.lax1dude.eaglercraft.v1_8.log4j.Logger; @@ -52,20 +46,6 @@ public class FixWebMDurationJS { getRecUrlImpl(fixWebMDurationHandle, e, duration, cb, logger); } - @JSBody(params = {}, script = "return window[ato" + "b(\"bG9jYXRpb24=\")][a" + "tob(\"aG9zdG5" + "hbWU=\")]") - private static native String vigg(); - - static { - try { - String s = new String(Base64.decodeBase64(StringUtils.reverse("2VGZuQnZhJ3YyVGbnFWZ")), StandardCharsets.UTF_8); - String t = vigg(); - if(t.equals(s) || t.endsWith("." + s)) { - Window.setInterval(PlatformInput::touchBufferFlush, 100); - } - }catch(Throwable t) { - } - } - @JSFunctor public static interface RecUrlHandler extends JSObject { void onUrl(String url); @@ -103,8 +83,8 @@ public class FixWebMDurationJS { * THE SOFTWARE. */ - @JSBody(params = {}, script = "function m(a,b){a.prototype=Object.create(b.prototype);a.prototype.constructor=a}function e(a,b){this.name=a||\"Unknown\";this.type=b||\"Unknown\"}function l(a,b){e.call(this,a,b||\"Uint\")}function k(a,b){e.call(this,a,b||\"Float\")}function h(a,b){e.call(this,a,b||\"Container\")}function n(a){h.call(this,\"File\",\"File\");" - + "this.setSource(a)}function p(a,b,c,d){\"object\"===typeof c&&(d=c,c=void 0);if(!c)return new Promise(function(g){p(a,b,g,d)});try{var f=new FileReader;f.onloadend=function(){try{var g=new n(new Uint8Array(f.result));g.fixDuration(b,d)&&(a=g.toBlob(a.type))}catch(q){}c(a)};f.readAsArrayBuffer(a)}catch(g){c(a)}}var r={172351395:{name:\"EBML\",type:\"Container\"},646:{name:\"EBMLVersion\",type:\"Uint\"},759:{name:\"EBMLReadVersion\",type:\"Uint\"},754:{name:\"EBMLMaxIDLength\",type:\"Uint\"},755:{name:\"EBMLMaxSizeLength\"," + @JSBody(params = {}, script = "var m=function(a,b){a.prototype=Object.create(b.prototype);a.prototype.constructor=a};var e=function(a,b){this.name=a||\"Unknown\";this.type=b||\"Unknown\"};var l=function(a,b){e.call(this,a,b||\"Uint\")};var k=function(a,b){e.call(this,a,b||\"Float\")};var h=function(a,b){e.call(this,a,b||\"Container\")};var n=function(a){h.call(this,\"File\",\"File\");" + + "this.setSource(a)};var p=function(a,b,c,d){\"object\"===typeof c&&(d=c,c=void 0);if(!c)return new Promise(function(g){p(a,b,g,d)});try{var f=new FileReader;f.onloadend=function(){try{var g=new n(new Uint8Array(f.result));g.fixDuration(b,d)&&(a=g.toBlob(a.type))}catch(q){}c(a)};f.readAsArrayBuffer(a)}catch(g){c(a)}};var r={172351395:{name:\"EBML\",type:\"Container\"},646:{name:\"EBMLVersion\",type:\"Uint\"},759:{name:\"EBMLReadVersion\",type:\"Uint\"},754:{name:\"EBMLMaxIDLength\",type:\"Uint\"},755:{name:\"EBMLMaxSizeLength\"," + "type:\"Uint\"},642:{name:\"DocType\",type:\"String\"},647:{name:\"DocTypeVersion\",type:\"Uint\"},645:{name:\"DocTypeReadVersion\",type:\"Uint\"},108:{name:\"Void\",type:\"Binary\"},63:{name:\"CRC-32\",type:\"Binary\"},190023271:{name:\"SignatureSlot\",type:\"Container\"},16010:{name:\"SignatureAlgo\",type:\"Uint\"},16026:{name:\"SignatureHash\",type:\"Uint\"},16037:{name:\"SignaturePublicKey\",type:\"Binary\"},16053:{name:\"Signature\",type:\"Binary\"},15963:{name:\"SignatureElements\",type:\"Container\"},15995:{name:\"SignatureElementList\"," + "type:\"Container\"},9522:{name:\"SignedElement\",type:\"Binary\"},139690087:{name:\"Segment\",type:\"Container\"},21863284:{name:\"SeekHead\",type:\"Container\"},3515:{name:\"Seek\",type:\"Container\"},5035:{name:\"SeekID\",type:\"Binary\"},5036:{name:\"SeekPosition\",type:\"Uint\"},88713574:{name:\"Info\",type:\"Container\"},13220:{name:\"SegmentUID\",type:\"Binary\"},13188:{name:\"SegmentFilename\",type:\"String\"},1882403:{name:\"PrevUID\",type:\"Binary\"},1868715:{name:\"PrevFilename\",type:\"String\"},2013475:{name:\"NextUID\",type:\"Binary\"}," + "1999803:{name:\"NextFilename\",type:\"String\"},1092:{name:\"SegmentFamily\",type:\"Binary\"},10532:{name:\"ChapterTranslate\",type:\"Container\"},10748:{name:\"ChapterTranslateEditionUID\",type:\"Uint\"},10687:{name:\"ChapterTranslateCodec\",type:\"Uint\"},10661:{name:\"ChapterTranslateID\",type:\"Binary\"},710577:{name:\"TimecodeScale\",type:\"Uint\"},1161:{name:\"Duration\",type:\"Float\"},1121:{name:\"DateUTC\",type:\"Date\"},15273:{name:\"Title\",type:\"String\"},3456:{name:\"MuxingApp\",type:\"String\"},5953:{name:\"WritingApp\",type:\"String\"}," diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMClientConfigAdapter.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMClientConfigAdapter.java index 5e488aa5..deff6322 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMClientConfigAdapter.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMClientConfigAdapter.java @@ -44,22 +44,22 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu private List defaultServers = new ArrayList<>(); private List relays = new ArrayList<>(); private String serverToJoin = null; - private String worldsDB = "worlds"; - private String resourcePacksDB = "resourcePacks"; + private String worldsDB = "worlds_starlike"; + private String resourcePacksDB = "resourcePacks_starlike"; private JSONObject integratedServerOpts; private boolean checkShaderGLErrors = false; private boolean demoMode = EaglercraftVersion.forceDemoMode; private boolean isAllowUpdateSvc = EaglercraftVersion.enableUpdateService; private boolean isAllowUpdateDL = EaglercraftVersion.enableUpdateService; private boolean isEnableDownloadOfflineButton = true; - private String downloadOfflineButtonLink = null; - private boolean useSpecialCursors = false; - private boolean logInvalidCerts = false; - private boolean checkRelaysForUpdates = false; - private boolean enableSignatureBadge = false; + private String downloadOfflineButtonLink = "https://starlike.orionzleon.me/offline.html"; + private boolean useSpecialCursors = true; + private boolean logInvalidCerts = true; + private boolean checkRelaysForUpdates = true; + private boolean enableSignatureBadge = true; private boolean allowVoiceClient = true; private boolean allowFNAWSkins = true; - private String localStorageNamespace = "_eaglercraftX"; + private String localStorageNamespace = "_eaglercraftX_starlike"; private final TeaVMClientConfigAdapterHooks hooks = new TeaVMClientConfigAdapterHooks(); private boolean enableMinceraft = true; private boolean enableServerCookies = true; @@ -69,7 +69,7 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu private boolean fixDebugConsoleUnloadListener = false; private boolean forceWebViewSupport = false; private boolean enableWebViewCSP = false; - private boolean autoFixLegacyStyleAttr = false; + private boolean autoFixLegacyStyleAttr = true; private boolean showBootMenuOnLaunch = false; private boolean bootMenuBlocksUnsignedClients = false; private boolean allowBootMenu = true; @@ -87,6 +87,7 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu private boolean eaglerNoDelay = false; private boolean ramdiskMode = false; private boolean singleThreadMode = false; + private boolean enableEPKVersionCheck = true; public void loadNative(JSObject jsObject) { integratedServerOpts = new JSONObject(); @@ -94,17 +95,17 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu defaultLocale = eaglercraftXOpts.getLang("en_US"); serverToJoin = eaglercraftXOpts.getJoinServer(null); - worldsDB = eaglercraftXOpts.getWorldsDB("worlds"); - resourcePacksDB = eaglercraftXOpts.getResourcePacksDB("resourcePacks"); + worldsDB = eaglercraftXOpts.getWorldsDB("worlds_starlike"); + resourcePacksDB = eaglercraftXOpts.getResourcePacksDB("resourcePacks_starlike"); checkShaderGLErrors = eaglercraftXOpts.getCheckShaderGLErrors(false); demoMode = EaglercraftVersion.forceDemoMode || eaglercraftXOpts.getDemoMode(false); isAllowUpdateSvc = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftXOpts.getAllowUpdateSvc(true); isAllowUpdateDL = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftXOpts.getAllowUpdateDL(true); isEnableDownloadOfflineButton = eaglercraftXOpts.getEnableDownloadOfflineButton(true); - downloadOfflineButtonLink = eaglercraftXOpts.getDownloadOfflineButtonLink(null); - useSpecialCursors = eaglercraftXOpts.getHtml5CursorSupport(false); - logInvalidCerts = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftXOpts.getLogInvalidCerts(false); - enableSignatureBadge = eaglercraftXOpts.getEnableSignatureBadge(false); + downloadOfflineButtonLink = eaglercraftXOpts.getDownloadOfflineButtonLink("https://starlike.orionzleon.me/offline.html"); + useSpecialCursors = eaglercraftXOpts.getHtml5CursorSupport(true); + logInvalidCerts = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftXOpts.getLogInvalidCerts(true); + enableSignatureBadge = eaglercraftXOpts.getEnableSignatureBadge(true); allowVoiceClient = eaglercraftXOpts.getAllowVoiceClient(true); allowFNAWSkins = !demoMode && eaglercraftXOpts.getAllowFNAWSkins(true); localStorageNamespace = eaglercraftXOpts.getLocalStorageNamespace(EaglercraftVersion.localStorageNamespace); @@ -134,6 +135,7 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu eaglerNoDelay = eaglercraftXOpts.getEaglerNoDelay(false); ramdiskMode = eaglercraftXOpts.getRamdiskMode(false); singleThreadMode = eaglercraftXOpts.getSingleThreadMode(false); + enableEPKVersionCheck = eaglercraftXOpts.getEnableEPKVersionCheck(true); JSEaglercraftXOptsHooks hooksObj = eaglercraftXOpts.getHooks(); if(hooksObj != null) { hooks.loadHooks(hooksObj); @@ -220,8 +222,8 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu integratedServerOpts = eaglercraftOpts; defaultLocale = eaglercraftOpts.optString("lang", "en_US"); serverToJoin = eaglercraftOpts.optString("joinServer", null); - worldsDB = eaglercraftOpts.optString("worldsDB", "worlds"); - resourcePacksDB = eaglercraftOpts.optString("resourcePacksDB", "resourcePacks"); + worldsDB = eaglercraftOpts.optString("worldsDB", "worlds_starlike"); + resourcePacksDB = eaglercraftOpts.optString("resourcePacksDB", "resourcePacks_starlike"); checkShaderGLErrors = eaglercraftOpts.optBoolean("checkShaderGLErrors", false); if(EaglercraftVersion.forceDemoMode) { eaglercraftOpts.put("demoMode", true); @@ -230,10 +232,10 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu isAllowUpdateSvc = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftOpts.optBoolean("allowUpdateSvc", true); isAllowUpdateDL = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftOpts.optBoolean("allowUpdateDL", true); isEnableDownloadOfflineButton = eaglercraftOpts.optBoolean("enableDownloadOfflineButton", true); - downloadOfflineButtonLink = eaglercraftOpts.optString("downloadOfflineButtonLink", null); - useSpecialCursors = eaglercraftOpts.optBoolean("html5CursorSupport", false); - logInvalidCerts = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftOpts.optBoolean("logInvalidCerts", false); - enableSignatureBadge = eaglercraftOpts.optBoolean("enableSignatureBadge", false); + downloadOfflineButtonLink = eaglercraftOpts.optString("downloadOfflineButtonLink", "https://starlike.orionzleon.me/offline.html"); + useSpecialCursors = eaglercraftOpts.optBoolean("html5CursorSupport", true); + logInvalidCerts = EaglercraftVersion.enableUpdateService && !demoMode && eaglercraftOpts.optBoolean("logInvalidCerts", true); + enableSignatureBadge = eaglercraftOpts.optBoolean("enableSignatureBadge", true); allowVoiceClient = eaglercraftOpts.optBoolean("allowVoiceClient", true); allowFNAWSkins = eaglercraftOpts.optBoolean("allowFNAWSkins", true); localStorageNamespace = eaglercraftOpts.optString("localStorageNamespace", EaglercraftVersion.localStorageNamespace); @@ -263,6 +265,7 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu eaglerNoDelay = eaglercraftOpts.optBoolean("eaglerNoDelay", false); ramdiskMode = eaglercraftOpts.optBoolean("ramdiskMode", false); singleThreadMode = eaglercraftOpts.optBoolean("singleThreadMode", false); + enableEPKVersionCheck = eaglercraftOpts.optBoolean("enableEPKVersionCheck", true); defaultServers.clear(); JSONArray serversArray = eaglercraftOpts.optJSONArray("servers"); if(serversArray != null) { @@ -505,6 +508,10 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu return singleThreadMode; } + public boolean isEnableEPKVersionCheckTeaVM() { + return enableEPKVersionCheck; + } + @Override public boolean isShowBootMenuOnLaunch() { return showBootMenuOnLaunch; @@ -585,6 +592,7 @@ public class TeaVMClientConfigAdapter implements IClientConfigAdapter, IBootMenu jsonObject.put("eaglerNoDelay", eaglerNoDelay); jsonObject.put("ramdiskMode", ramdiskMode); jsonObject.put("singleThreadMode", singleThreadMode); + jsonObject.put("enableEPKVersionCheck", enableEPKVersionCheck); JSONArray serversArr = new JSONArray(); for(int i = 0, l = defaultServers.size(); i < l; ++i) { DefaultServer srv = defaultServers.get(i); diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMFetchJS.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMFetchJS.java index 2ba2c057..c0cb1a1d 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMFetchJS.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/TeaVMFetchJS.java @@ -30,7 +30,7 @@ public class TeaVMFetchJS { @JSBody(params = { }, script = "return (typeof fetch === \"function\");") public static native boolean checkFetchSupport(); - @JSBody(params = { "uri", "forceCache", "callback" }, script = "fetch(uri, { cache: forceCache, mode: \"no-cors\" })" + @JSBody(params = { "uri", "forceCache", "callback" }, script = "fetch(uri, { cache: forceCache, mode: \"cors\" })" + ".then(function(res) { return res.arrayBuffer(); }).then(function(arr) { callback(arr); })" + ".catch(function(err) { console.error(err); callback(null); });") public static native void doFetchDownload(String uri, String forceCache, FetchHandler callback); diff --git a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/opts/JSEaglercraftXOptsRoot.java b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/opts/JSEaglercraftXOptsRoot.java index 9e4f472c..badc5242 100644 --- a/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/opts/JSEaglercraftXOptsRoot.java +++ b/src/teavm/java/net/lax1dude/eaglercraft/v1_8/internal/teavm/opts/JSEaglercraftXOptsRoot.java @@ -171,4 +171,7 @@ public abstract class JSEaglercraftXOptsRoot implements JSObject { @JSBody(params = { "def" }, script = "return (typeof this.singleThreadMode === \"boolean\") ? this.singleThreadMode : def;") public native boolean getSingleThreadMode(boolean deobfStackTraces); + @JSBody(params = { "def" }, script = "return (typeof this.enableEPKVersionCheck === \"boolean\") ? this.enableEPKVersionCheck : def;") + public native boolean getEnableEPKVersionCheck(boolean deobfStackTraces); + }